@evident-ai/cli 3.6.1-dev.6fa67d6 → 3.6.1-dev.795576a

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,9 @@ 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 open2 from "open";
1186
1223
 
1187
1224
  // ../../packages/types/src/agents/index.ts
1188
1225
  var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
@@ -1234,23 +1271,28 @@ function lastText(assistantRun) {
1234
1271
  }
1235
1272
  return null;
1236
1273
  }
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;
1274
+ function literalContinueRun(messages, userMessageId) {
1275
+ if (!messages) return [];
1276
+ const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
1277
+ if (userIndex === -1) return [];
1242
1278
  let continuation;
1243
- for (let i = userIndex + 1; messages && i < messages.length; i++) {
1279
+ for (let i = userIndex + 1; i < messages.length; i++) {
1244
1280
  if (roleOf(messages[i]) === "user") {
1245
1281
  continuation = messages[i];
1246
1282
  break;
1247
1283
  }
1248
1284
  }
1249
1285
  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;
1286
+ if (roleOf(continuation) !== "user" || textPartsOf(continuation).join("\n").trim().toLowerCase() !== "continue" || !continuationId) {
1287
+ return [];
1253
1288
  }
1289
+ return correlatedAssistantRun(messages, continuationId);
1290
+ }
1291
+ function effectiveCorrelatedRun(messages, userMessageId) {
1292
+ const run2 = correlatedAssistantRun(messages, userMessageId);
1293
+ if (lastText(run2) !== null) return run2;
1294
+ const continuationRun = literalContinueRun(messages, userMessageId);
1295
+ if (continuationRun.length > 0) return continuationRun;
1254
1296
  return run2;
1255
1297
  }
1256
1298
  function extractReplyTextForMessage(messages, opencodeUserMessageId) {
@@ -1438,6 +1480,14 @@ function buildCredentialProxyNativeConfig({
1438
1480
  };
1439
1481
  }
1440
1482
 
1483
+ // ../../packages/types/src/mcp-proxies.ts
1484
+ var MCP_LOOPBACK_REDIRECT_POLICY = {
1485
+ scheme: "http",
1486
+ host: "127.0.0.1",
1487
+ path: "/callback",
1488
+ preferred_port: 18443
1489
+ };
1490
+
1441
1491
  // ../../packages/types/src/logging/index.ts
1442
1492
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
1443
1493
  var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
@@ -1472,12 +1522,653 @@ function stripQuery(url) {
1472
1522
  }
1473
1523
  }
1474
1524
 
1525
+ // src/commands/mcp-authorize.ts
1526
+ var API_TIMEOUT_MS = 1e4;
1527
+ var CALLBACK_OK_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Sign-in received</title></head><body><p>Sign-in response received. You can close this window.</p></body></html>';
1528
+ var CALLBACK_REJECTED_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Invalid response</title></head><body><p>This sign-in response was not accepted.</p></body></html>';
1529
+ var KNOWN_CALLBACK_PARAMETERS = /* @__PURE__ */ new Set(["state", "code", "error", "error_description", "iss"]);
1530
+ var ApiHttpError = class extends Error {
1531
+ constructor(status2, operation) {
1532
+ super(`Evident API returned HTTP ${status2} while ${operation}`);
1533
+ this.status = status2;
1534
+ this.operation = operation;
1535
+ }
1536
+ };
1537
+ var CallbackExpiredError = class extends Error {
1538
+ constructor() {
1539
+ super("The local sign-in attempt expired before the provider returned.");
1540
+ }
1541
+ };
1542
+ var InterruptedError = class extends Error {
1543
+ constructor() {
1544
+ super("Authorization was interrupted.");
1545
+ }
1546
+ };
1547
+ function apiPath(proxyId, connectionId, suffix) {
1548
+ const path = `/mcp-proxies/${encodeURIComponent(proxyId)}`;
1549
+ if (!connectionId) return path + "/connections";
1550
+ return `${path}/connections/${encodeURIComponent(connectionId)}/local-authorization/${suffix}`;
1551
+ }
1552
+ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1553
+ const method = body === void 0 ? "GET" : "POST";
1554
+ const requestController = new AbortController();
1555
+ const onCancel = () => requestController.abort();
1556
+ const timeout = setTimeout(() => requestController.abort(), API_TIMEOUT_MS);
1557
+ cancelSignal.addEventListener("abort", onCancel, { once: true });
1558
+ if (cancelSignal.aborted) onCancel();
1559
+ try {
1560
+ let response;
1561
+ try {
1562
+ response = await fetch(`${getApiUrlConfig()}${path}`, {
1563
+ method,
1564
+ headers: {
1565
+ ...buildAuthHeaders(credentials2),
1566
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
1567
+ },
1568
+ body: body === void 0 ? void 0 : JSON.stringify(body),
1569
+ signal: requestController.signal
1570
+ });
1571
+ } catch (error2) {
1572
+ if (cancelSignal.aborted) throw new InterruptedError();
1573
+ if (requestController.signal.aborted) {
1574
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1575
+ }
1576
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1577
+ throw new Error(
1578
+ `Could not reach Evident while ${operation}: ${detail}. Check --endpoint or EVIDENT_API_URL and retry.`
1579
+ );
1580
+ }
1581
+ if (!response.ok) throw new ApiHttpError(response.status, operation);
1582
+ try {
1583
+ return await response.json();
1584
+ } catch (error2) {
1585
+ if (cancelSignal.aborted) throw new InterruptedError();
1586
+ if (requestController.signal.aborted) {
1587
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1588
+ }
1589
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1590
+ throw new Error(`Evident returned an invalid response while ${operation}: ${detail}`);
1591
+ }
1592
+ } finally {
1593
+ clearTimeout(timeout);
1594
+ cancelSignal.removeEventListener("abort", onCancel);
1595
+ }
1596
+ }
1597
+ function callbackResponse(response, status2, html) {
1598
+ response.writeHead(status2, {
1599
+ "Content-Type": "text/html; charset=utf-8",
1600
+ "Cache-Control": "no-store",
1601
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
1602
+ "X-Content-Type-Options": "nosniff"
1603
+ });
1604
+ response.end(html);
1605
+ }
1606
+ function parseCallbackRequest(request3) {
1607
+ if (request3.method !== "GET" || !request3.url || !request3.url.startsWith("/") || request3.url.length > 16384) {
1608
+ return { reason: "malformed_response" };
1609
+ }
1610
+ if (request3.headers["transfer-encoding"] || Number(request3.headers["content-length"] ?? 0) > 0) {
1611
+ return { reason: "malformed_response" };
1612
+ }
1613
+ const callbackBase = `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1614
+ if (!URL.canParse(request3.url, callbackBase)) return { reason: "malformed_response" };
1615
+ const url = new URL(request3.url, callbackBase);
1616
+ if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash) {
1617
+ return { reason: "malformed_response" };
1618
+ }
1619
+ for (const parameter of url.search.slice(1).split("&")) {
1620
+ const separator = parameter.indexOf("=");
1621
+ const rawKey = separator === -1 ? parameter : parameter.slice(0, separator);
1622
+ let key;
1623
+ try {
1624
+ key = decodeURIComponent(rawKey.replaceAll("+", " "));
1625
+ } catch (_error) {
1626
+ continue;
1627
+ }
1628
+ if (!KNOWN_CALLBACK_PARAMETERS.has(key)) continue;
1629
+ const rawValue = separator === -1 ? "" : parameter.slice(separator + 1);
1630
+ try {
1631
+ decodeURIComponent(rawValue.replaceAll("+", " "));
1632
+ } catch (_error) {
1633
+ return { reason: "malformed_response" };
1634
+ }
1635
+ }
1636
+ const params = url.searchParams;
1637
+ for (const key of ["state", "code", "error", "error_description", "iss"]) {
1638
+ if (params.getAll(key).length > 1) return { reason: "malformed_response" };
1639
+ }
1640
+ const state = params.get("state");
1641
+ const code = params.get("code");
1642
+ const error2 = params.get("error");
1643
+ const errorDescription = params.get("error_description");
1644
+ const issuer = params.get("iss");
1645
+ 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)) {
1646
+ return { reason: "malformed_response" };
1647
+ }
1648
+ return {
1649
+ callback: {
1650
+ state,
1651
+ ...code === null ? {} : { code },
1652
+ ...error2 === null ? {} : { error: error2 },
1653
+ ...errorDescription === null ? {} : { error_description: errorDescription },
1654
+ ...issuer === null ? {} : { iss: issuer }
1655
+ }
1656
+ };
1657
+ }
1658
+ function reportProgress(options, event, message, details = {}) {
1659
+ if (options.json) {
1660
+ console.error(JSON.stringify({ event, ...details }));
1661
+ } else {
1662
+ console.error(message);
1663
+ }
1664
+ }
1665
+ function rejectCallback(response, options, reason) {
1666
+ callbackResponse(response, 400, CALLBACK_REJECTED_HTML);
1667
+ reportProgress(options, "callback_rejected", callbackRejectionMessage(reason), {
1668
+ reason,
1669
+ action: "still_waiting"
1670
+ });
1671
+ }
1672
+ function callbackRejectionMessage(reason) {
1673
+ switch (reason) {
1674
+ case "malformed_response":
1675
+ return "The callback had a malformed response; authorization is still waiting for a valid response. Retry authorization if needed.";
1676
+ case "state_mismatch":
1677
+ return "The callback had a state mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1678
+ case "issuer_missing":
1679
+ return "The callback was missing its issuer; authorization is still waiting for a valid response. Update the provider or retry authorization.";
1680
+ case "issuer_mismatch":
1681
+ return "The callback had an issuer mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1682
+ case "issuer_unavailable":
1683
+ return "The Evident endpoint has issuer validation unavailable; authorization is still waiting for a valid response. Update the endpoint or start a new authorization.";
1684
+ case "attempt_not_ready":
1685
+ return "The authorization attempt is not ready yet; authorization is still waiting for a valid response while Evident finishes starting it.";
1686
+ case "attempt_expired":
1687
+ return "The authorization attempt expired; authorization is still waiting for a valid response. Start a new authorization.";
1688
+ }
1689
+ }
1690
+ function handleCallbackRequest(request3, response, waiter, options) {
1691
+ if (!request3.url || !request3.url.startsWith("/") || !URL.canParse(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`)) {
1692
+ rejectCallback(response, options, "malformed_response");
1693
+ return;
1694
+ }
1695
+ const pathname = new URL(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`).pathname;
1696
+ if (pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path) {
1697
+ callbackResponse(response, 404, CALLBACK_REJECTED_HTML);
1698
+ return;
1699
+ }
1700
+ if (request3.method !== "GET") {
1701
+ response.setHeader("Allow", "GET");
1702
+ callbackResponse(response, 405, CALLBACK_REJECTED_HTML);
1703
+ return;
1704
+ }
1705
+ if (waiter.accepted) {
1706
+ callbackResponse(response, 409, CALLBACK_REJECTED_HTML);
1707
+ return;
1708
+ }
1709
+ const parsed = parseCallbackRequest(request3);
1710
+ if (!("callback" in parsed)) {
1711
+ rejectCallback(response, options, parsed.reason);
1712
+ return;
1713
+ }
1714
+ const callback = parsed.callback;
1715
+ const expiresAtMs = waiter.expiresAtMs;
1716
+ let rejectionReason;
1717
+ if (expiresAtMs === void 0) {
1718
+ rejectionReason = "attempt_not_ready";
1719
+ } else if (Date.now() >= expiresAtMs) {
1720
+ rejectionReason = "attempt_expired";
1721
+ } else if (!waiter.expectedState || callback.state !== waiter.expectedState) {
1722
+ rejectionReason = "state_mismatch";
1723
+ } else if (waiter.issuerParameterSupported && callback.iss === void 0) {
1724
+ rejectionReason = "issuer_missing";
1725
+ } else if (callback.iss !== void 0 && waiter.expectedIssuer === void 0) {
1726
+ rejectionReason = "issuer_unavailable";
1727
+ } else if (callback.iss !== void 0 && callback.iss !== waiter.expectedIssuer) {
1728
+ rejectionReason = "issuer_mismatch";
1729
+ }
1730
+ if (rejectionReason) {
1731
+ rejectCallback(response, options, rejectionReason);
1732
+ return;
1733
+ }
1734
+ waiter.accepted = true;
1735
+ response.writeHead(200, {
1736
+ "Content-Type": "text/html; charset=utf-8",
1737
+ "Cache-Control": "no-store",
1738
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
1739
+ "X-Content-Type-Options": "nosniff"
1740
+ });
1741
+ response.end(CALLBACK_OK_HTML, () => waiter.resolve?.(callback));
1742
+ }
1743
+ function listen(server, port) {
1744
+ return new Promise((resolve6, reject) => {
1745
+ const onError = (error2) => reject(error2);
1746
+ server.once("error", onError);
1747
+ server.listen(port, MCP_LOOPBACK_REDIRECT_POLICY.host, () => {
1748
+ server.removeListener("error", onError);
1749
+ const address = server.address();
1750
+ if (!address || typeof address === "string") {
1751
+ reject(new Error("The local callback listener did not report a TCP port."));
1752
+ return;
1753
+ }
1754
+ resolve6(address.port);
1755
+ });
1756
+ });
1757
+ }
1758
+ function isAddressInUse(error2) {
1759
+ return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EADDRINUSE";
1760
+ }
1761
+ async function bindCallbackListener(waiter, options) {
1762
+ const createListener = () => createServer((request3, response) => handleCallbackRequest(request3, response, waiter, options));
1763
+ try {
1764
+ const server2 = createListener();
1765
+ return { server: server2, port: await listen(server2, MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) };
1766
+ } catch (error2) {
1767
+ if (!isAddressInUse(error2)) {
1768
+ throw new Error(
1769
+ `Could not listen on 127.0.0.1:${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port}: ${error2 instanceof Error ? error2.message : String(error2)}`
1770
+ );
1771
+ }
1772
+ }
1773
+ const server = createListener();
1774
+ try {
1775
+ return { server, port: await listen(server, 0) };
1776
+ } catch (error2) {
1777
+ throw new Error(
1778
+ `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)}`
1779
+ );
1780
+ }
1781
+ }
1782
+ function waitForCallback(waiter, expiresAtMs, signal) {
1783
+ return new Promise((resolve6, reject) => {
1784
+ const remainingMs = expiresAtMs - Date.now();
1785
+ if (remainingMs <= 0) {
1786
+ reject(new CallbackExpiredError());
1787
+ return;
1788
+ }
1789
+ if (signal.aborted) {
1790
+ reject(new InterruptedError());
1791
+ return;
1792
+ }
1793
+ let settled = false;
1794
+ function settle(callback, error2) {
1795
+ if (settled) return;
1796
+ settled = true;
1797
+ clearTimeout(timer);
1798
+ signal.removeEventListener("abort", onAbort);
1799
+ waiter.resolve = void 0;
1800
+ if (error2) reject(error2);
1801
+ else resolve6(callback);
1802
+ }
1803
+ const onAbort = () => settle(void 0, new InterruptedError());
1804
+ const timer = setTimeout(() => settle(void 0, new CallbackExpiredError()), remainingMs);
1805
+ waiter.expiresAtMs = expiresAtMs;
1806
+ waiter.resolve = (callback) => settle(callback);
1807
+ timer.unref?.();
1808
+ signal.addEventListener("abort", onAbort, { once: true });
1809
+ if (signal.aborted) onAbort();
1810
+ });
1811
+ }
1812
+ function authorizationState(authorizationUrl) {
1813
+ let url;
1814
+ try {
1815
+ url = new URL(authorizationUrl);
1816
+ } catch (error2) {
1817
+ throw new Error(
1818
+ `Evident returned an invalid authorization URL: ${error2 instanceof Error ? error2.message : String(error2)}`
1819
+ );
1820
+ }
1821
+ const states = url.searchParams.getAll("state");
1822
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || states.length !== 1 || !states[0]) {
1823
+ throw new Error("Evident returned an unsafe or incomplete authorization URL.");
1824
+ }
1825
+ return { url, state: states[0] };
1826
+ }
1827
+ function apiFailureMessage(error2) {
1828
+ const context = `Evident returned HTTP ${error2.status} while ${error2.operation}.`;
1829
+ switch (error2.status) {
1830
+ case 400:
1831
+ return `${context} Retry the command; if it continues, update the CLI and try again.`;
1832
+ case 401:
1833
+ 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.`;
1834
+ case 403:
1835
+ return `${context} Only workspace owners and admins can authorize MCP connections. Ask a workspace admin for access.`;
1836
+ case 404:
1837
+ return `${context} Confirm the proxy and connection IDs and that this CLI user can access the proxy.`;
1838
+ case 409:
1839
+ return `${context} This connection does not support local sign-in. Use its hosted authorization flow in Evident.`;
1840
+ case 502:
1841
+ case 503:
1842
+ return `${context} The Evident MCP authorization service is unavailable. Retry shortly or contact your workspace admin.`;
1843
+ default:
1844
+ return `${context} Check your endpoint and retry.`;
1845
+ }
1846
+ }
1847
+ function completionFailureMessage(reason) {
1848
+ switch (reason) {
1849
+ case "state_unknown":
1850
+ return "This sign-in was started by another user or could not be found. Start a new authorization from the same user account.";
1851
+ case "state_consumed":
1852
+ return "This sign-in was already used. Start a new authorization.";
1853
+ case "state_expired":
1854
+ return "This sign-in attempt expired. Start a new authorization.";
1855
+ case "issuer_unavailable":
1856
+ return "This sign-in attempt predates issuer validation. Start a new authorization.";
1857
+ case "issuer_missing":
1858
+ return "The provider response did not include its required issuer. Start a new authorization and update the CLI if needed.";
1859
+ case "issuer_mismatch":
1860
+ return "The provider response came from an unexpected issuer. Start a new authorization and contact support if it continues.";
1861
+ case "invalid_response":
1862
+ return "The provider returned an invalid sign-in response. Start a new authorization.";
1863
+ case "provider_denied":
1864
+ return "The provider denied the sign-in. Retry and approve the requested access.";
1865
+ case "provider_error":
1866
+ return "The provider could not complete sign-in. Retry, or contact the provider if it continues.";
1867
+ case "exchange_failed":
1868
+ return "The provider sign-in completed, but Evident could not exchange the authorization. Retry or contact support.";
1869
+ case "reconcile_failed":
1870
+ case "tools_pending":
1871
+ return "Sign-in completed, but Evident could not finish setting up this connection. Retry or contact support.";
1872
+ case "not_configured":
1873
+ return "Local authorization is not configured for this Evident environment. Contact your workspace admin.";
1874
+ default:
1875
+ return "Evident could not complete this sign-in. Start a new authorization and try again.";
1876
+ }
1877
+ }
1878
+ function printLink(options, url, reason) {
1879
+ if (options.json) {
1880
+ console.error(JSON.stringify({ event: "authorization_required", authorization_url: url.href }));
1881
+ return;
1882
+ }
1883
+ printWarning(reason ?? "Open this authorization URL in your browser:");
1884
+ console.log(url.href);
1885
+ }
1886
+ function printResult(options, proxyId, connectionId, error2) {
1887
+ if (options.json) {
1888
+ console.log(
1889
+ JSON.stringify({
1890
+ ok: !error2,
1891
+ proxy_id: proxyId,
1892
+ connection_id: connectionId,
1893
+ ...error2 ? { error: error2 } : {}
1894
+ })
1895
+ );
1896
+ } else if (error2) {
1897
+ printError(error2);
1898
+ } else {
1899
+ printSuccess("MCP connection authorized.");
1900
+ }
1901
+ }
1902
+ function errorMessage(error2) {
1903
+ if (error2 instanceof ApiHttpError) return apiFailureMessage(error2);
1904
+ if (error2 instanceof CallbackExpiredError) {
1905
+ return "The sign-in attempt expired before the provider returned. Run the command again.";
1906
+ }
1907
+ if (error2 instanceof InterruptedError) return "Authorization was interrupted.";
1908
+ if (error2 instanceof Error) return error2.message;
1909
+ return `Authorization failed: ${String(error2)}`;
1910
+ }
1911
+ function requestFailed(reason) {
1912
+ if (reason instanceof Error) throw reason;
1913
+ throw new Error(`Authorization failed: ${String(reason)}`);
1914
+ }
1915
+ function validateConnectionList(value) {
1916
+ if (!value || !Array.isArray(value.mcp_proxy_connections)) {
1917
+ throw new Error("Evident returned an invalid MCP connection list. Update the CLI and retry.");
1918
+ }
1919
+ return value.mcp_proxy_connections;
1920
+ }
1921
+ function validateBeginResponse(value) {
1922
+ 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)) {
1923
+ throw new Error(
1924
+ "Evident returned an invalid local authorization attempt. Update the CLI and retry."
1925
+ );
1926
+ }
1927
+ }
1928
+ async function startBrowser(url) {
1929
+ const child = await open2(url);
1930
+ let signalFailure = () => void 0;
1931
+ const failure = new Promise((resolve6) => {
1932
+ signalFailure = resolve6;
1933
+ });
1934
+ child.once("error", signalFailure);
1935
+ child.once("close", (code) => {
1936
+ if (code !== 0) signalFailure();
1937
+ });
1938
+ await new Promise((resolve6, reject) => {
1939
+ if (child.pid !== void 0) {
1940
+ resolve6();
1941
+ return;
1942
+ }
1943
+ child.once("spawn", resolve6);
1944
+ child.once("error", reject);
1945
+ });
1946
+ return { failure };
1947
+ }
1948
+ function closeServer(server, force) {
1949
+ if (!server.listening) return Promise.resolve();
1950
+ return new Promise((resolve6, reject) => {
1951
+ server.close((error2) => error2 ? reject(error2) : resolve6());
1952
+ if (force) server.closeAllConnections();
1953
+ });
1954
+ }
1955
+ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1956
+ let credentials2;
1957
+ try {
1958
+ credentials2 = await getAuthCredentials();
1959
+ } catch (error2) {
1960
+ const kind = error2 instanceof Error ? error2.name : "unknown error";
1961
+ printResult(
1962
+ options,
1963
+ proxyId,
1964
+ connectionId,
1965
+ `Could not read the saved Evident credentials (${kind}). Check keychain access or run evident login again.`
1966
+ );
1967
+ process.exitCode = 1;
1968
+ return;
1969
+ }
1970
+ if (!credentials2) {
1971
+ printResult(
1972
+ options,
1973
+ proxyId,
1974
+ connectionId,
1975
+ "No credentials found. Run `evident login` and retry."
1976
+ );
1977
+ process.exitCode = 1;
1978
+ return;
1979
+ }
1980
+ if (credentials2.authType !== "bearer") {
1981
+ printResult(
1982
+ options,
1983
+ proxyId,
1984
+ connectionId,
1985
+ "MCP authorization requires a user login, not a runner key. Unset EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY, then run `evident login`."
1986
+ );
1987
+ process.exitCode = 1;
1988
+ return;
1989
+ }
1990
+ const waiter = { accepted: false };
1991
+ let server;
1992
+ let closePromise;
1993
+ let closeFailureLogged = false;
1994
+ let failure;
1995
+ const cancelController = new AbortController();
1996
+ const closeListener = (force = false) => {
1997
+ if (!server || closePromise) return closePromise ?? Promise.resolve();
1998
+ closePromise = closeServer(server, force);
1999
+ return closePromise;
2000
+ };
2001
+ const onSigint = () => {
2002
+ cancelController.abort();
2003
+ void closeListener(true).catch((error2) => {
2004
+ closeFailureLogged = true;
2005
+ console.error(
2006
+ `[mcp authorize] listener shutdown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${error2 instanceof Error ? error2.message : String(error2)}`
2007
+ );
2008
+ });
2009
+ };
2010
+ try {
2011
+ const listener = await bindCallbackListener(waiter, options);
2012
+ server = listener.server;
2013
+ process.once("SIGINT", onSigint);
2014
+ const redirectUri = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}${MCP_LOOPBACK_REDIRECT_POLICY.path}`;
2015
+ const fallback = listener.port !== MCP_LOOPBACK_REDIRECT_POLICY.preferred_port;
2016
+ reportProgress(
2017
+ options,
2018
+ fallback ? "listener_fallback" : "listener_ready",
2019
+ fallback ? `Port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} is busy; listening at ${redirectUri}.` : `Listening for the sign-in response at ${redirectUri}.`,
2020
+ {
2021
+ callback_url: redirectUri,
2022
+ ...fallback ? { preferred_port: MCP_LOOPBACK_REDIRECT_POLICY.preferred_port } : {},
2023
+ port: listener.port
2024
+ }
2025
+ );
2026
+ const connectionList = await requestJson(
2027
+ apiPath(proxyId),
2028
+ credentials2,
2029
+ cancelController.signal,
2030
+ "checking the MCP connection"
2031
+ );
2032
+ const connection = validateConnectionList(connectionList).find(
2033
+ (candidate) => candidate.connection_id === connectionId
2034
+ );
2035
+ if (!connection)
2036
+ throw new Error("The MCP connection was not found. Check the connection ID and try again.");
2037
+ if (connection.authorization_mode !== "local") {
2038
+ throw new Error("This connection uses hosted sign-in. Authorize it from Evident instead.");
2039
+ }
2040
+ if (connection.auth_kind !== "oauth2") {
2041
+ throw new Error("This MCP connection does not support OAuth authorization.");
2042
+ }
2043
+ reportProgress(options, "authorization_starting", "Starting authorization with Evident.");
2044
+ const begin = await requestJson(
2045
+ apiPath(proxyId, connectionId, "begin"),
2046
+ credentials2,
2047
+ cancelController.signal,
2048
+ "starting local authorization",
2049
+ { redirect_uri: redirectUri }
2050
+ );
2051
+ validateBeginResponse(begin);
2052
+ const { url: authorizationUrl, state } = authorizationState(begin.authorization_url);
2053
+ waiter.expectedState = state;
2054
+ waiter.expectedIssuer = begin.issuer;
2055
+ waiter.issuerParameterSupported = begin.authorization_response_iss_parameter_supported;
2056
+ const expiresAtMs = Date.parse(begin.expires_at);
2057
+ if (expiresAtMs <= Date.now()) throw new CallbackExpiredError();
2058
+ waiter.expiresAtMs = expiresAtMs;
2059
+ const callbackOutcome = waitForCallback(waiter, expiresAtMs, cancelController.signal).then(
2060
+ (callback2) => ({ ok: true, callback: callback2 }),
2061
+ (error2) => ({ ok: false, error: error2 })
2062
+ );
2063
+ const waitForCallbackWithProgress = (linkReason) => {
2064
+ if (linkReason) printLink(options, authorizationUrl, linkReason);
2065
+ reportProgress(
2066
+ options,
2067
+ "waiting_for_callback",
2068
+ "Waiting for the provider to return to this computer."
2069
+ );
2070
+ return (async () => {
2071
+ const outcome = await callbackOutcome;
2072
+ if (!outcome.ok) requestFailed(outcome.error);
2073
+ return outcome.callback;
2074
+ })();
2075
+ };
2076
+ let callback;
2077
+ if (options.noBrowser) {
2078
+ callback = await waitForCallbackWithProgress("Open this authorization URL in your browser:");
2079
+ } else {
2080
+ reportProgress(
2081
+ options,
2082
+ "opening_browser",
2083
+ "Opening the provider authorization page in your browser."
2084
+ );
2085
+ const browserOutcome = startBrowser(authorizationUrl.href).then(
2086
+ ({ failure: browserFailure }) => ({ ok: true, failure: browserFailure }),
2087
+ () => ({ ok: false })
2088
+ );
2089
+ const first = await Promise.race([
2090
+ browserOutcome.then((outcome) => ({ kind: "browser", outcome })),
2091
+ callbackOutcome.then((outcome) => ({ kind: "callback", outcome }))
2092
+ ]);
2093
+ if (first.kind === "callback") {
2094
+ if (!first.outcome.ok) requestFailed(first.outcome.error);
2095
+ callback = first.outcome.callback;
2096
+ } else {
2097
+ if (!first.outcome.ok) {
2098
+ callback = await waitForCallbackWithProgress(
2099
+ "Could not open the browser automatically. Open this URL:"
2100
+ );
2101
+ } else {
2102
+ const callbackWait = waitForCallbackWithProgress();
2103
+ const waitOutcome = await Promise.race([
2104
+ callbackWait.then(
2105
+ (value) => ({ kind: "callback", value }),
2106
+ (error2) => ({ kind: "callback_error", error: error2 })
2107
+ ),
2108
+ first.outcome.failure.then(() => ({ kind: "browser_failure" }))
2109
+ ]);
2110
+ if (waitOutcome.kind === "callback") {
2111
+ callback = waitOutcome.value;
2112
+ } else if (waitOutcome.kind === "callback_error") {
2113
+ requestFailed(waitOutcome.error);
2114
+ } else {
2115
+ printLink(
2116
+ options,
2117
+ authorizationUrl,
2118
+ "The browser could not keep the authorization page open. Open this URL:"
2119
+ );
2120
+ callback = await callbackWait;
2121
+ }
2122
+ }
2123
+ }
2124
+ }
2125
+ reportProgress(options, "forwarding_callback", "Forwarding the sign-in response to Evident.");
2126
+ const completionBody = {
2127
+ state: callback.state,
2128
+ ...callback.code === void 0 ? {} : { code: callback.code },
2129
+ ...callback.error === void 0 ? {} : { error: callback.error },
2130
+ ...callback.error_description === void 0 ? {} : { error_description: callback.error_description },
2131
+ ...callback.iss === void 0 ? {} : { iss: callback.iss }
2132
+ };
2133
+ reportProgress(options, "completing_authorization", "Completing authorization with Evident.");
2134
+ const completion = await requestJson(
2135
+ apiPath(proxyId, connectionId, "complete"),
2136
+ credentials2,
2137
+ cancelController.signal,
2138
+ "completing local authorization",
2139
+ completionBody
2140
+ );
2141
+ if (completion.outcome !== "success") failure = completionFailureMessage(completion.reason);
2142
+ } catch (error2) {
2143
+ failure = errorMessage(error2);
2144
+ } finally {
2145
+ process.removeListener("SIGINT", onSigint);
2146
+ try {
2147
+ await closeListener();
2148
+ } catch (error2) {
2149
+ const detail = error2 instanceof Error ? error2.message : String(error2);
2150
+ if (!closeFailureLogged) {
2151
+ console.error(
2152
+ `[mcp authorize] listener teardown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${detail}`
2153
+ );
2154
+ }
2155
+ failure ??= "The local callback listener could not be closed cleanly. Check for a lingering process and retry.";
2156
+ }
2157
+ }
2158
+ printResult(options, proxyId, connectionId, failure);
2159
+ if (failure) process.exitCode = cancelController.signal.aborted ? 130 : 1;
2160
+ }
2161
+
1475
2162
  // src/commands/run.ts
2163
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
2164
+ import { homedir as homedir9 } from "node:os";
2165
+ import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
2166
+ import chalk7 from "chalk";
1476
2167
  import ora4 from "ora";
1477
2168
  import { select as select4 } from "@inquirer/prompts";
1478
2169
 
1479
2170
  // src/lib/telemetry.ts
1480
- var CLI_VERSION = (true ? "3.6.1-dev.6fa67d6" : void 0) ?? process.env.npm_package_version ?? "unknown";
2171
+ var CLI_VERSION = (true ? "3.6.1-dev.795576a" : void 0) ?? process.env.npm_package_version ?? "unknown";
1481
2172
  function getCliVersion() {
1482
2173
  return CLI_VERSION;
1483
2174
  }
@@ -1674,7 +2365,7 @@ var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
1674
2365
  var SESSION_DB_RECLAIM_TIME_BUDGET_MS = 500;
1675
2366
  var SESSION_DB_RECLAIM_PAGE_CEILING = 4e4;
1676
2367
  var SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS = 5e3;
1677
- function errorMessage(error2) {
2368
+ function errorMessage2(error2) {
1678
2369
  if (!(error2 instanceof Error)) return String(error2);
1679
2370
  return error2.cause instanceof Error ? error2.cause.message : error2.message;
1680
2371
  }
@@ -1808,7 +2499,7 @@ async function probeReclaimAvailability(input) {
1808
2499
  try {
1809
2500
  sqlite = await import("node:sqlite");
1810
2501
  } catch (err) {
1811
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2502
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1812
2503
  console.warn(`[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ` + detail);
1813
2504
  return { reason: "sqlite-unavailable", detail };
1814
2505
  }
@@ -1843,7 +2534,7 @@ async function reclaimSessionDbSpace(input) {
1843
2534
  try {
1844
2535
  sqlite = await import("node:sqlite");
1845
2536
  } catch (err) {
1846
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2537
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1847
2538
  console.warn(
1848
2539
  `[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${detail}`
1849
2540
  );
@@ -1954,11 +2645,11 @@ async function reclaimSessionDbSpace(input) {
1954
2645
  );
1955
2646
  return { ok: false, skipped: "auto-vacuum-not-applicable" };
1956
2647
  } catch (err) {
1957
- console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage(err));
2648
+ console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage2(err));
1958
2649
  return {
1959
2650
  ok: false,
1960
2651
  skipped: isSessionStoreWriteFailure(err) ? "disk-exhaustion" : "reclaim-error",
1961
- detail: errorMessage(err)
2652
+ detail: errorMessage2(err)
1962
2653
  };
1963
2654
  } finally {
1964
2655
  db?.close();
@@ -3110,7 +3801,7 @@ function buildSessionArchive(input) {
3110
3801
  function isRecord2(value) {
3111
3802
  return typeof value === "object" && value !== null && !Array.isArray(value);
3112
3803
  }
3113
- function errorMessage2(error2) {
3804
+ function errorMessage3(error2) {
3114
3805
  return error2 instanceof Error ? error2.message : String(error2);
3115
3806
  }
3116
3807
  function invalidResponse(version2, sessionId, path, reason) {
@@ -3128,7 +3819,7 @@ async function requestPage(client, sessionId, path, signal) {
3128
3819
  } catch (error2) {
3129
3820
  throw new SessionArchiveExportError(
3130
3821
  "request-failed",
3131
- `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage2(error2)}`
3822
+ `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage3(error2)}`
3132
3823
  );
3133
3824
  }
3134
3825
  if (response.status === 404) {
@@ -3149,7 +3840,7 @@ async function requestPage(client, sessionId, path, signal) {
3149
3840
  } catch (error2) {
3150
3841
  throw new SessionArchiveExportError(
3151
3842
  "request-failed",
3152
- `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage2(error2)}`
3843
+ `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage3(error2)}`
3153
3844
  );
3154
3845
  }
3155
3846
  try {
@@ -3184,7 +3875,7 @@ function v1NextCursor(response, sessionId, path) {
3184
3875
  } catch (error2) {
3185
3876
  throw new SessionArchiveExportError(
3186
3877
  "pagination-failed",
3187
- `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage2(error2)}`
3878
+ `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage3(error2)}`
3188
3879
  );
3189
3880
  }
3190
3881
  }
@@ -5708,8 +6399,8 @@ function classifyReplyAuthError(reply) {
5708
6399
  };
5709
6400
  }
5710
6401
  }
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))) {
6402
+ const errorMessage5 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
6403
+ if (errorMessage5 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage5.includes(knownMessage))) {
5713
6404
  return {
5714
6405
  kind: "model_auth",
5715
6406
  providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
@@ -5764,7 +6455,7 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
5764
6455
  (m) => roleOf2(m) === "assistant" && parentIdOf2(m) !== exceptUserMessageId && isAssistantInFlight(m)
5765
6456
  );
5766
6457
  }
5767
- function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds) {
6458
+ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds, apiVersion) {
5768
6459
  if (!messages || messages.length === 0) return false;
5769
6460
  const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
5770
6461
  if (userIndex === -1) return false;
@@ -5778,7 +6469,7 @@ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageI
5778
6469
  if (laterUserMessageId === void 0 || !siblingUserMessageIds.has(laterUserMessageId)) {
5779
6470
  return false;
5780
6471
  }
5781
- if (messages.some(
6472
+ if (apiVersion === "v2" || messages.some(
5782
6473
  (candidate) => roleOf2(candidate) === "assistant" && parentIdOf2(candidate) === laterUserMessageId
5783
6474
  )) {
5784
6475
  hasStartedLaterUser = true;
@@ -7666,7 +8357,7 @@ function buildSessionStoreSizeWarning(input) {
7666
8357
  import { statSync as statSync5 } from "node:fs";
7667
8358
  import { homedir as homedir5 } from "node:os";
7668
8359
  import { join as join11 } from "node:path";
7669
- import { open as open2, stat } from "node:fs/promises";
8360
+ import { open as open3, stat } from "node:fs/promises";
7670
8361
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
7671
8362
  function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
7672
8363
  const dataDir = env.XDG_DATA_HOME || join11(homeDir, ".local", "share");
@@ -7720,7 +8411,7 @@ function tailOpenCodeLogFile(logPath, onChunk, opts = {}) {
7720
8411
  inode = current.ino;
7721
8412
  if (current.size === offset) return;
7722
8413
  const length = current.size - offset;
7723
- const fh = await open2(logPath, "r");
8414
+ const fh = await open3(logPath, "r");
7724
8415
  try {
7725
8416
  const buf = Buffer.alloc(length);
7726
8417
  const { bytesRead } = await fh.read(buf, 0, length, offset);
@@ -7753,7 +8444,7 @@ import WebSocket from "ws";
7753
8444
 
7754
8445
  // src/lib/file-read.ts
7755
8446
  import { constants } from "node:fs";
7756
- import { open as open3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
8447
+ import { open as open4, realpath as realpath2, stat as stat2 } from "node:fs/promises";
7757
8448
  import { extname, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
7758
8449
  import { homedir as homedir6 } from "node:os";
7759
8450
 
@@ -7803,7 +8494,7 @@ var FILE_MIME_TYPES = {
7803
8494
  ".mp4": "video/mp4",
7804
8495
  ".mov": "video/quicktime"
7805
8496
  };
7806
- async function readProjectFile(projectRoot, method, requestedPath, openFile = open3) {
8497
+ async function readProjectFile(projectRoot, method, requestedPath, openFile = open4) {
7807
8498
  if (method !== "GET") return refuse(405, "method_not_allowed");
7808
8499
  if (!projectRoot || !isAbsolute3(projectRoot)) return refuse(503, "project_root_unavailable");
7809
8500
  if (!requestedPath || requestedPath.length > 4096 || requestedPath.includes("\0")) {
@@ -8376,8 +9067,8 @@ function connectTunnel(options) {
8376
9067
  }
8377
9068
  forwarder.handleBinaryBodyFrame(frame.sid, frame.payload);
8378
9069
  } catch (error2) {
8379
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8380
- onError?.(`Failed to handle binary message: ${errorMessage4}`);
9070
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9071
+ onError?.(`Failed to handle binary message: ${errorMessage5}`);
8381
9072
  }
8382
9073
  return;
8383
9074
  }
@@ -8385,8 +9076,8 @@ function connectTunnel(options) {
8385
9076
  try {
8386
9077
  message = JSON.parse(data.toString());
8387
9078
  } catch (error2) {
8388
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8389
- onError?.(`Failed to handle message: ${errorMessage4}`);
9079
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9080
+ onError?.(`Failed to handle message: ${errorMessage5}`);
8390
9081
  return;
8391
9082
  }
8392
9083
  if (isStreamFrame(message)) {
@@ -8965,7 +9656,7 @@ import { join as join14 } from "node:path";
8965
9656
 
8966
9657
  // src/lib/file-push.ts
8967
9658
  import { randomUUID } from "node:crypto";
8968
- import { chmod, mkdir, open as open4, realpath as realpath3, rename, unlink } from "node:fs/promises";
9659
+ import { chmod, mkdir, open as open5, realpath as realpath3, rename, unlink } from "node:fs/promises";
8969
9660
  import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute4, join as join13 } from "node:path";
8970
9661
  var FILE_MODE = 384;
8971
9662
  var DIRECTORY_MODE = 448;
@@ -9098,7 +9789,7 @@ async function writeAtomically(realTarget, content) {
9098
9789
  const temporaryPath = join13(dirname10(realTarget), `.evident-push-${randomUUID()}.tmp`);
9099
9790
  let handle;
9100
9791
  try {
9101
- handle = await open4(temporaryPath, "wx", FILE_MODE);
9792
+ handle = await open5(temporaryPath, "wx", FILE_MODE);
9102
9793
  await handle.writeFile(content);
9103
9794
  await handle.chmod(FILE_MODE);
9104
9795
  await handle.close();
@@ -10299,12 +10990,12 @@ var ChannelDriver = class _ChannelDriver {
10299
10990
  this.sessions.delete(conversationId);
10300
10991
  this.supersede(conversationId, sessionId);
10301
10992
  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);
10993
+ 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.`;
10994
+ this.untrackableAck.set(messageId, errorMessage5);
10304
10995
  this.untrackableAckSessionIds.set(messageId, null);
10305
10996
  this.log({
10306
10997
  level: "error",
10307
- message: errorMessage4,
10998
+ message: errorMessage5,
10308
10999
  conversation_id: conversationId,
10309
11000
  message_id: messageId
10310
11001
  });
@@ -10312,7 +11003,7 @@ var ChannelDriver = class _ChannelDriver {
10312
11003
  conversationId,
10313
11004
  messageId,
10314
11005
  null,
10315
- errorMessage4
11006
+ errorMessage5
10316
11007
  );
10317
11008
  if (reportError !== null) {
10318
11009
  this.log({
@@ -10493,12 +11184,12 @@ var ChannelDriver = class _ChannelDriver {
10493
11184
  conversation_id: conv.id,
10494
11185
  message_id: message.id
10495
11186
  });
10496
- const errorMessage4 = this.untrackableAck.get(message.id);
11187
+ const errorMessage5 = this.untrackableAck.get(message.id);
10497
11188
  const reportError = await this.reportUntrackableAck(
10498
11189
  conv.id,
10499
11190
  message.id,
10500
11191
  null,
10501
- errorMessage4
11192
+ errorMessage5
10502
11193
  );
10503
11194
  if (reportError === null) {
10504
11195
  continue;
@@ -10586,7 +11277,7 @@ var ChannelDriver = class _ChannelDriver {
10586
11277
  const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
10587
11278
  const providerId = hasProviderAndModel ? dispatchedModel.slice(0, separator) : null;
10588
11279
  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.`;
11280
+ const errorMessage5 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
10590
11281
  this.log({
10591
11282
  level: "error",
10592
11283
  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 +11285,7 @@ var ChannelDriver = class _ChannelDriver {
10594
11285
  message_id: message.id
10595
11286
  });
10596
11287
  try {
10597
- await this.markFailed(conv.id, message.id, sessionId, errorMessage4, void 0, {
11288
+ await this.markFailed(conv.id, message.id, sessionId, errorMessage5, void 0, {
10598
11289
  classification: {
10599
11290
  kind: "model_auth",
10600
11291
  providerId,
@@ -10672,12 +11363,12 @@ var ChannelDriver = class _ChannelDriver {
10672
11363
  } catch (err) {
10673
11364
  if (err instanceof ChannelAuthError) throw err;
10674
11365
  if (this.isV2 && err instanceof OpenCodeV2PromptAckError) {
10675
- const errorMessage5 = err instanceof Error ? err.message : String(err);
10676
- this.untrackableAck.set(message.id, errorMessage5);
11366
+ const errorMessage6 = err instanceof Error ? err.message : String(err);
11367
+ this.untrackableAck.set(message.id, errorMessage6);
10677
11368
  this.untrackableAckSessionIds.set(message.id, null);
10678
11369
  this.log({
10679
11370
  level: "error",
10680
- message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage5}`,
11371
+ message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage6}`,
10681
11372
  conversation_id: conv.id,
10682
11373
  message_id: message.id
10683
11374
  });
@@ -10685,7 +11376,7 @@ var ChannelDriver = class _ChannelDriver {
10685
11376
  conv.id,
10686
11377
  message.id,
10687
11378
  null,
10688
- errorMessage5
11379
+ errorMessage6
10689
11380
  );
10690
11381
  if (markError !== null) {
10691
11382
  this.log({
@@ -10724,7 +11415,7 @@ var ChannelDriver = class _ChannelDriver {
10724
11415
  await this.failV2ModelSwitch(conv, message, sessionId, err);
10725
11416
  break;
10726
11417
  }
10727
- const errorMessage4 = err instanceof Error ? err.message : String(err);
11418
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
10728
11419
  this.sessions.delete(conv.id);
10729
11420
  this.supersede(conv.id, sessionId);
10730
11421
  this.log({
@@ -10733,7 +11424,7 @@ var ChannelDriver = class _ChannelDriver {
10733
11424
  conversation_id: conv.id,
10734
11425
  message_id: message.id
10735
11426
  });
10736
- await this.markFailed(conv.id, message.id, null, errorMessage4).catch((markErr) => {
11427
+ await this.markFailed(conv.id, message.id, null, errorMessage5).catch((markErr) => {
10737
11428
  this.log({
10738
11429
  level: "warn",
10739
11430
  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 +11435,7 @@ var ChannelDriver = class _ChannelDriver {
10744
11435
  });
10745
11436
  this.log({
10746
11437
  level: "error",
10747
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage4}`,
11438
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage5}`,
10748
11439
  conversation_id: conv.id,
10749
11440
  message_id: message.id
10750
11441
  });
@@ -11029,7 +11720,12 @@ var ChannelDriver = class _ChannelDriver {
11029
11720
  this.watchers.get(sessionId),
11030
11721
  message.id
11031
11722
  );
11032
- if (hasLaterSiblingTurnStarted(messages, ocId ?? "", siblingOcIds)) {
11723
+ if (hasLaterSiblingTurnStarted(
11724
+ messages,
11725
+ ocId ?? "",
11726
+ siblingOcIds,
11727
+ this.openCodeClient.version
11728
+ )) {
11033
11729
  this.log({
11034
11730
  level: "warn",
11035
11731
  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 +13364,12 @@ var ChannelDriver = class _ChannelDriver {
12668
13364
  return;
12669
13365
  }
12670
13366
  const siblingOcIds = this.siblingOpencodeMessageIds(watcher, inFlight.evidentMessageId);
12671
- const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(messages, inFlight.opencodeMessageId, siblingOcIds);
13367
+ const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(
13368
+ messages,
13369
+ inFlight.opencodeMessageId,
13370
+ siblingOcIds,
13371
+ this.openCodeClient.version
13372
+ );
12672
13373
  const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
12673
13374
  const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
12674
13375
  if (state === "queued" && pastStuckBound && (sessionIdle || skippedByOpencode) && !inFlight.stuckReported) {
@@ -13679,12 +14380,12 @@ var ChannelDriver = class _ChannelDriver {
13679
14380
  conversation_id: row.conversation_id,
13680
14381
  message_id: row.id
13681
14382
  });
13682
- const errorMessage4 = this.untrackableAck.get(row.id);
14383
+ const errorMessage5 = this.untrackableAck.get(row.id);
13683
14384
  const reportError = await this.reportUntrackableAck(
13684
14385
  row.conversation_id,
13685
14386
  row.id,
13686
14387
  this.untrackableAckSessionIds.get(row.id) ?? null,
13687
- errorMessage4
14388
+ errorMessage5
13688
14389
  );
13689
14390
  if (reportError !== null) {
13690
14391
  this.log({
@@ -14003,14 +14704,14 @@ var ChannelDriver = class _ChannelDriver {
14003
14704
  this.awaitingReadopt.delete(row.id);
14004
14705
  if (err instanceof ChannelAuthError) throw err;
14005
14706
  if (this.isV2) {
14006
- const errorMessage4 = err instanceof Error ? err.message : String(err);
14707
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
14007
14708
  const invalidPromptAck = err instanceof OpenCodeV2PromptAckError;
14008
14709
  if (!invalidPromptAck) {
14009
14710
  const exists = await this.sessionExists(sessionId);
14010
14711
  if (exists === false) {
14011
14712
  this.log({
14012
14713
  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}`,
14714
+ 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
14715
  conversation_id: row.conversation_id,
14015
14716
  message_id: row.id
14016
14717
  });
@@ -14020,7 +14721,7 @@ var ChannelDriver = class _ChannelDriver {
14020
14721
  if (exists === null) {
14021
14722
  this.log({
14022
14723
  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}`,
14724
+ 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
14725
  conversation_id: row.conversation_id,
14025
14726
  message_id: row.id
14026
14727
  });
@@ -14028,7 +14729,7 @@ var ChannelDriver = class _ChannelDriver {
14028
14729
  return;
14029
14730
  }
14030
14731
  } else {
14031
- this.untrackableAck.set(row.id, errorMessage4);
14732
+ this.untrackableAck.set(row.id, errorMessage5);
14032
14733
  this.untrackableAckSessionIds.set(row.id, sessionId);
14033
14734
  }
14034
14735
  if (err instanceof OpenCodeV2ModelSwitchError) {
@@ -14037,7 +14738,7 @@ var ChannelDriver = class _ChannelDriver {
14037
14738
  }
14038
14739
  this.log({
14039
14740
  level: "error",
14040
- message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage4}`,
14741
+ message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage5}`,
14041
14742
  conversation_id: row.conversation_id,
14042
14743
  message_id: row.id
14043
14744
  });
@@ -14046,7 +14747,7 @@ var ChannelDriver = class _ChannelDriver {
14046
14747
  row.conversation_id,
14047
14748
  row.id,
14048
14749
  sessionId,
14049
- errorMessage4
14750
+ errorMessage5
14050
14751
  );
14051
14752
  if (markError !== null) {
14052
14753
  this.log({
@@ -14057,7 +14758,7 @@ var ChannelDriver = class _ChannelDriver {
14057
14758
  });
14058
14759
  }
14059
14760
  } else {
14060
- await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage4).catch(
14761
+ await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage5).catch(
14061
14762
  (markErr) => {
14062
14763
  this.log({
14063
14764
  level: "warn",
@@ -15041,9 +15742,9 @@ var ChannelDriver = class _ChannelDriver {
15041
15742
  * trackable. Callers use the returned error to keep their path-specific logging
15042
15743
  * while the same report payload can be retried on a later drain.
15043
15744
  */
15044
- async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage4) {
15745
+ async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage5) {
15045
15746
  try {
15046
- await this.markFailed(conversationId, messageId, sessionId, errorMessage4);
15747
+ await this.markFailed(conversationId, messageId, sessionId, errorMessage5);
15047
15748
  return null;
15048
15749
  } catch (err) {
15049
15750
  this.signalUntrackableAck(conversationId, messageId);
@@ -16207,7 +16908,7 @@ var MAX_FLUSH_PASSES = 2;
16207
16908
  function outcomesWith(outcome) {
16208
16909
  return { claude: outcome, opencode: outcome };
16209
16910
  }
16210
- function errorMessage3(error2) {
16911
+ function errorMessage4(error2) {
16211
16912
  return error2 instanceof Error ? error2.message : String(error2);
16212
16913
  }
16213
16914
  function waitForSettlement(promise, timeoutMs) {
@@ -16234,7 +16935,7 @@ function writeMarker(markerPath, outcomes, log3) {
16234
16935
  writeFileSync8(temporaryPath, body, { mode: 384 });
16235
16936
  renameSync(temporaryPath, markerPath);
16236
16937
  } catch (error2) {
16237
- log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage3(error2)}`, "warn");
16938
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage4(error2)}`, "warn");
16238
16939
  }
16239
16940
  }
16240
16941
  function intervalSeconds(env, log3) {
@@ -16266,7 +16967,7 @@ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
16266
16967
  },
16267
16968
  (error2) => {
16268
16969
  failed = true;
16269
- log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage3(error2)}`, "warn");
16970
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage4(error2)}`, "warn");
16270
16971
  }
16271
16972
  );
16272
16973
  const abortTimer = setTimeout(() => controller.abort(), remainingMs);
@@ -16326,7 +17027,7 @@ function createCredentialSync({
16326
17027
  outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
16327
17028
  } catch (error2) {
16328
17029
  outcomes[store] = "failed";
16329
- log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage3(error2)}`, "debug");
17030
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage4(error2)}`, "debug");
16330
17031
  }
16331
17032
  }
16332
17033
  const failed = STORES.some((store) => outcomes[store] === "failed");
@@ -17331,8 +18032,8 @@ async function driveChannels(state, driver) {
17331
18032
  state.running = false;
17332
18033
  break;
17333
18034
  }
17334
- const errorMessage4 = error2 instanceof Error ? error2.message : String(error2);
17335
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage4}` });
18035
+ const errorMessage5 = error2 instanceof Error ? error2.message : String(error2);
18036
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage5}` });
17336
18037
  if (state.interactive) displayStatus(state);
17337
18038
  if (driver.hasInFlightWatchers()) {
17338
18039
  consecutiveDrainFailures = 0;
@@ -19618,24 +20319,95 @@ async function run(options) {
19618
20319
  }
19619
20320
  }
19620
20321
 
20322
+ // src/commands/teams.ts
20323
+ function printTeam(team, selected) {
20324
+ console.log(`${selected ? "* " : " "}${team.id} ${team.name}`);
20325
+ }
20326
+ function isTeam(value) {
20327
+ return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.name === "string";
20328
+ }
20329
+ async function teams() {
20330
+ const apiUrl = getApiUrlConfig();
20331
+ let credentials2;
20332
+ try {
20333
+ credentials2 = await getAuthCredentials();
20334
+ } catch (error2) {
20335
+ printError(
20336
+ `Could not read the saved Evident credentials: ${error2 instanceof Error ? error2.message : String(error2)}`
20337
+ );
20338
+ process.exitCode = 1;
20339
+ return;
20340
+ }
20341
+ if (!credentials2) {
20342
+ printError(`Not logged in to ${apiUrl}. Run the \`login\` command to authenticate.`);
20343
+ process.exitCode = 1;
20344
+ return;
20345
+ }
20346
+ try {
20347
+ const response = await fetch(`${apiUrl}/teams`, {
20348
+ headers: buildAuthHeaders(credentials2)
20349
+ });
20350
+ if (!response.ok) {
20351
+ const serverMessage = await readErrorMessage(response);
20352
+ throw new Error(
20353
+ `Evident returned HTTP ${response.status} while listing teams${serverMessage ? `: ${serverMessage}` : ""}`
20354
+ );
20355
+ }
20356
+ const data = await response.json();
20357
+ if (!Array.isArray(data) || !data.every(isTeam)) {
20358
+ throw new Error("Evident returned an invalid team list. Update the CLI and retry.");
20359
+ }
20360
+ const selectedTeam = getTeamSelection();
20361
+ blank();
20362
+ if (data.length === 0) {
20363
+ console.log("No teams found for this account.");
20364
+ blank();
20365
+ return;
20366
+ }
20367
+ for (const team of data) {
20368
+ printTeam(team, team.id === selectedTeam);
20369
+ }
20370
+ if (data.length === 1) {
20371
+ console.log("This is your only team; commands act in it automatically.");
20372
+ } else if (!selectedTeam) {
20373
+ console.log("Choose a team with --team <id> or set EVIDENT_TEAM.");
20374
+ }
20375
+ blank();
20376
+ } catch (error2) {
20377
+ printError(`Could not list teams: ${error2 instanceof Error ? error2.message : String(error2)}`);
20378
+ process.exitCode = 1;
20379
+ }
20380
+ }
20381
+
19621
20382
  // src/index.ts
19622
20383
  var version = getCliVersion();
19623
20384
  var program = new Command();
19624
20385
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
19625
20386
  "--endpoint <url>",
19626
20387
  "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();
20388
+ ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").option(
20389
+ "--team <id>",
20390
+ "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"
20391
+ ).hook("preAction", (thisCommand) => {
20392
+ const { endpoint: endpoint2, tunnel, team } = thisCommand.optsWithGlobals();
19629
20393
  if (endpoint2) {
19630
20394
  setEndpoint(endpoint2);
19631
20395
  }
19632
20396
  if (tunnel) {
19633
20397
  setTunnelUrl(tunnel);
19634
20398
  }
20399
+ setTeamSelection(team);
19635
20400
  });
19636
20401
  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
20402
  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
20403
  program.command("whoami").description("Show the currently logged in user").action(whoami);
20404
+ program.command("teams").description("List the teams you belong to").action(teams);
20405
+ 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(
20406
+ (proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
20407
+ noBrowser: options.browser === false,
20408
+ json: options.json
20409
+ })
20410
+ );
19639
20411
  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
20412
  program.command("credential-vault-env").description("Print the shell assignment a runner image evals before starting the synchroniser").action(credentialVaultEnv);
19641
20413
  program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);