@evident-ai/cli 3.6.1-dev.7a7e0e5 → 3.6.1-dev.87c1db8

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
@@ -1178,11 +1178,9 @@ async function claudeUsage() {
1178
1178
  }
1179
1179
  }
1180
1180
 
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";
1181
+ // src/commands/mcp-authorize.ts
1182
+ import { createServer } from "node:http";
1183
+ import open2 from "open";
1186
1184
 
1187
1185
  // ../../packages/types/src/agents/index.ts
1188
1186
  var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
@@ -1234,23 +1232,28 @@ function lastText(assistantRun) {
1234
1232
  }
1235
1233
  return null;
1236
1234
  }
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;
1235
+ function literalContinueRun(messages, userMessageId) {
1236
+ if (!messages) return [];
1237
+ const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
1238
+ if (userIndex === -1) return [];
1242
1239
  let continuation;
1243
- for (let i = userIndex + 1; messages && i < messages.length; i++) {
1240
+ for (let i = userIndex + 1; i < messages.length; i++) {
1244
1241
  if (roleOf(messages[i]) === "user") {
1245
1242
  continuation = messages[i];
1246
1243
  break;
1247
1244
  }
1248
1245
  }
1249
1246
  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;
1247
+ if (roleOf(continuation) !== "user" || textPartsOf(continuation).join("\n").trim().toLowerCase() !== "continue" || !continuationId) {
1248
+ return [];
1253
1249
  }
1250
+ return correlatedAssistantRun(messages, continuationId);
1251
+ }
1252
+ function effectiveCorrelatedRun(messages, userMessageId) {
1253
+ const run2 = correlatedAssistantRun(messages, userMessageId);
1254
+ if (lastText(run2) !== null) return run2;
1255
+ const continuationRun = literalContinueRun(messages, userMessageId);
1256
+ if (continuationRun.length > 0) return continuationRun;
1254
1257
  return run2;
1255
1258
  }
1256
1259
  function extractReplyTextForMessage(messages, opencodeUserMessageId) {
@@ -1438,6 +1441,14 @@ function buildCredentialProxyNativeConfig({
1438
1441
  };
1439
1442
  }
1440
1443
 
1444
+ // ../../packages/types/src/mcp-proxies.ts
1445
+ var MCP_LOOPBACK_REDIRECT_POLICY = {
1446
+ scheme: "http",
1447
+ host: "127.0.0.1",
1448
+ path: "/callback",
1449
+ preferred_port: 18443
1450
+ };
1451
+
1441
1452
  // ../../packages/types/src/logging/index.ts
1442
1453
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
1443
1454
  var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
@@ -1472,12 +1483,508 @@ function stripQuery(url) {
1472
1483
  }
1473
1484
  }
1474
1485
 
1486
+ // src/commands/mcp-authorize.ts
1487
+ var API_TIMEOUT_MS = 1e4;
1488
+ var CALLBACK_OK_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Sign-in received</title></head><body><p>Sign-in response received. You can close this window.</p></body></html>';
1489
+ var CALLBACK_REJECTED_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Invalid response</title></head><body><p>This sign-in response was not accepted.</p></body></html>';
1490
+ var ApiHttpError = class extends Error {
1491
+ constructor(status2, operation) {
1492
+ super(`Evident API returned HTTP ${status2} while ${operation}`);
1493
+ this.status = status2;
1494
+ this.operation = operation;
1495
+ }
1496
+ };
1497
+ var CallbackExpiredError = class extends Error {
1498
+ constructor() {
1499
+ super("The local sign-in attempt expired before the provider returned.");
1500
+ }
1501
+ };
1502
+ var InterruptedError = class extends Error {
1503
+ constructor() {
1504
+ super("Authorization was interrupted.");
1505
+ }
1506
+ };
1507
+ function apiPath(proxyId, connectionId, suffix) {
1508
+ const path = `/mcp-proxies/${encodeURIComponent(proxyId)}`;
1509
+ if (!connectionId) return path + "/connections";
1510
+ return `${path}/connections/${encodeURIComponent(connectionId)}/local-authorization/${suffix}`;
1511
+ }
1512
+ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1513
+ const method = body === void 0 ? "GET" : "POST";
1514
+ const requestController = new AbortController();
1515
+ const onCancel = () => requestController.abort();
1516
+ const timeout = setTimeout(() => requestController.abort(), API_TIMEOUT_MS);
1517
+ cancelSignal.addEventListener("abort", onCancel, { once: true });
1518
+ if (cancelSignal.aborted) onCancel();
1519
+ try {
1520
+ let response;
1521
+ try {
1522
+ response = await fetch(`${getApiUrlConfig()}${path}`, {
1523
+ method,
1524
+ headers: {
1525
+ Authorization: getAuthHeader(credentials2),
1526
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
1527
+ },
1528
+ body: body === void 0 ? void 0 : JSON.stringify(body),
1529
+ signal: requestController.signal
1530
+ });
1531
+ } catch (error2) {
1532
+ if (cancelSignal.aborted) throw new InterruptedError();
1533
+ if (requestController.signal.aborted) {
1534
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1535
+ }
1536
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1537
+ throw new Error(
1538
+ `Could not reach Evident while ${operation}: ${detail}. Check --endpoint or EVIDENT_API_URL and retry.`
1539
+ );
1540
+ }
1541
+ if (!response.ok) throw new ApiHttpError(response.status, operation);
1542
+ try {
1543
+ return await response.json();
1544
+ } catch (error2) {
1545
+ if (cancelSignal.aborted) throw new InterruptedError();
1546
+ if (requestController.signal.aborted) {
1547
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1548
+ }
1549
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1550
+ throw new Error(`Evident returned an invalid response while ${operation}: ${detail}`);
1551
+ }
1552
+ } finally {
1553
+ clearTimeout(timeout);
1554
+ cancelSignal.removeEventListener("abort", onCancel);
1555
+ }
1556
+ }
1557
+ function callbackResponse(response, status2, html) {
1558
+ response.writeHead(status2, {
1559
+ "Content-Type": "text/html; charset=utf-8",
1560
+ "Cache-Control": "no-store",
1561
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
1562
+ "X-Content-Type-Options": "nosniff"
1563
+ });
1564
+ response.end(html);
1565
+ }
1566
+ function parseCallbackRequest(request3) {
1567
+ if (request3.method !== "GET" || !request3.url || !request3.url.startsWith("/") || request3.url.length > 16384) {
1568
+ return void 0;
1569
+ }
1570
+ if (request3.headers["transfer-encoding"] || Number(request3.headers["content-length"] ?? 0) > 0) {
1571
+ return void 0;
1572
+ }
1573
+ const callbackBase = `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1574
+ if (!URL.canParse(request3.url, callbackBase)) return void 0;
1575
+ const url = new URL(request3.url, callbackBase);
1576
+ if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash) return void 0;
1577
+ const allowedParams = /* @__PURE__ */ new Set(["state", "code", "error", "error_description"]);
1578
+ for (const [key] of url.searchParams) {
1579
+ if (!allowedParams.has(key) || url.searchParams.getAll(key).length !== 1) return void 0;
1580
+ }
1581
+ const state = url.searchParams.get("state");
1582
+ const code = url.searchParams.get("code");
1583
+ const error2 = url.searchParams.get("error");
1584
+ const errorDescription = url.searchParams.get("error_description");
1585
+ 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)) {
1586
+ return void 0;
1587
+ }
1588
+ return {
1589
+ state,
1590
+ ...code === null ? {} : { code },
1591
+ ...error2 === null ? {} : { error: error2 },
1592
+ ...errorDescription === null ? {} : { error_description: errorDescription }
1593
+ };
1594
+ }
1595
+ function handleCallbackRequest(request3, response, waiter) {
1596
+ if (!request3.url || !request3.url.startsWith("/") || !URL.canParse(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`)) {
1597
+ callbackResponse(response, 400, CALLBACK_REJECTED_HTML);
1598
+ return;
1599
+ }
1600
+ const pathname = new URL(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`).pathname;
1601
+ if (pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path) {
1602
+ callbackResponse(response, 404, CALLBACK_REJECTED_HTML);
1603
+ return;
1604
+ }
1605
+ if (request3.method !== "GET") {
1606
+ response.setHeader("Allow", "GET");
1607
+ callbackResponse(response, 405, CALLBACK_REJECTED_HTML);
1608
+ return;
1609
+ }
1610
+ if (waiter.accepted) {
1611
+ callbackResponse(response, 409, CALLBACK_REJECTED_HTML);
1612
+ return;
1613
+ }
1614
+ const callback = parseCallbackRequest(request3);
1615
+ if (!callback || !waiter.expectedState || !waiter.expiresAtMs || Date.now() >= waiter.expiresAtMs || callback.state !== waiter.expectedState) {
1616
+ callbackResponse(response, 400, CALLBACK_REJECTED_HTML);
1617
+ return;
1618
+ }
1619
+ waiter.accepted = true;
1620
+ response.writeHead(200, {
1621
+ "Content-Type": "text/html; charset=utf-8",
1622
+ "Cache-Control": "no-store",
1623
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
1624
+ "X-Content-Type-Options": "nosniff"
1625
+ });
1626
+ response.end(CALLBACK_OK_HTML, () => waiter.resolve?.(callback));
1627
+ }
1628
+ function listen(server, port) {
1629
+ return new Promise((resolve6, reject) => {
1630
+ const onError = (error2) => reject(error2);
1631
+ server.once("error", onError);
1632
+ server.listen(port, MCP_LOOPBACK_REDIRECT_POLICY.host, () => {
1633
+ server.removeListener("error", onError);
1634
+ const address = server.address();
1635
+ if (!address || typeof address === "string") {
1636
+ reject(new Error("The local callback listener did not report a TCP port."));
1637
+ return;
1638
+ }
1639
+ resolve6(address.port);
1640
+ });
1641
+ });
1642
+ }
1643
+ function isAddressInUse(error2) {
1644
+ return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EADDRINUSE";
1645
+ }
1646
+ async function bindCallbackListener(waiter) {
1647
+ const createListener = () => createServer((request3, response) => handleCallbackRequest(request3, response, waiter));
1648
+ try {
1649
+ const server2 = createListener();
1650
+ return { server: server2, port: await listen(server2, MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) };
1651
+ } catch (error2) {
1652
+ if (!isAddressInUse(error2)) {
1653
+ throw new Error(
1654
+ `Could not listen on 127.0.0.1:${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port}: ${error2 instanceof Error ? error2.message : String(error2)}`
1655
+ );
1656
+ }
1657
+ }
1658
+ const server = createListener();
1659
+ try {
1660
+ return { server, port: await listen(server, 0) };
1661
+ } catch (error2) {
1662
+ throw new Error(
1663
+ `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)}`
1664
+ );
1665
+ }
1666
+ }
1667
+ function waitForCallback(waiter, expiresAtMs, signal) {
1668
+ return new Promise((resolve6, reject) => {
1669
+ const remainingMs = expiresAtMs - Date.now();
1670
+ if (remainingMs <= 0) {
1671
+ reject(new CallbackExpiredError());
1672
+ return;
1673
+ }
1674
+ if (signal.aborted) {
1675
+ reject(new InterruptedError());
1676
+ return;
1677
+ }
1678
+ let settled = false;
1679
+ function settle(callback, error2) {
1680
+ if (settled) return;
1681
+ settled = true;
1682
+ clearTimeout(timer);
1683
+ signal.removeEventListener("abort", onAbort);
1684
+ waiter.resolve = void 0;
1685
+ if (error2) reject(error2);
1686
+ else resolve6(callback);
1687
+ }
1688
+ const onAbort = () => settle(void 0, new InterruptedError());
1689
+ const timer = setTimeout(() => settle(void 0, new CallbackExpiredError()), remainingMs);
1690
+ waiter.expiresAtMs = expiresAtMs;
1691
+ waiter.resolve = (callback) => settle(callback);
1692
+ timer.unref?.();
1693
+ signal.addEventListener("abort", onAbort, { once: true });
1694
+ if (signal.aborted) onAbort();
1695
+ });
1696
+ }
1697
+ function authorizationState(authorizationUrl) {
1698
+ let url;
1699
+ try {
1700
+ url = new URL(authorizationUrl);
1701
+ } catch (error2) {
1702
+ throw new Error(
1703
+ `Evident returned an invalid authorization URL: ${error2 instanceof Error ? error2.message : String(error2)}`
1704
+ );
1705
+ }
1706
+ const states = url.searchParams.getAll("state");
1707
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || states.length !== 1 || !states[0]) {
1708
+ throw new Error("Evident returned an unsafe or incomplete authorization URL.");
1709
+ }
1710
+ return { url, state: states[0] };
1711
+ }
1712
+ function apiFailureMessage(error2) {
1713
+ const context = `Evident returned HTTP ${error2.status} while ${error2.operation}.`;
1714
+ switch (error2.status) {
1715
+ case 400:
1716
+ return `${context} Retry the command; if it continues, update the CLI and try again.`;
1717
+ case 401:
1718
+ 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.`;
1719
+ case 403:
1720
+ return `${context} Only workspace owners and admins can authorize MCP connections. Ask a workspace admin for access.`;
1721
+ case 404:
1722
+ return `${context} Confirm the proxy and connection IDs and that this CLI user can access the proxy.`;
1723
+ case 409:
1724
+ return `${context} This connection does not support local sign-in. Use its hosted authorization flow in Evident.`;
1725
+ case 502:
1726
+ case 503:
1727
+ return `${context} The Evident MCP authorization service is unavailable. Retry shortly or contact your workspace admin.`;
1728
+ default:
1729
+ return `${context} Check your endpoint and retry.`;
1730
+ }
1731
+ }
1732
+ function completionFailureMessage(reason) {
1733
+ switch (reason) {
1734
+ case "state_unknown":
1735
+ return "This sign-in was started by another user or could not be found. Start a new authorization from the same user account.";
1736
+ case "state_consumed":
1737
+ return "This sign-in was already used. Start a new authorization.";
1738
+ case "state_expired":
1739
+ return "This sign-in attempt expired. Start a new authorization.";
1740
+ case "provider_denied":
1741
+ return "The provider denied the sign-in. Retry and approve the requested access.";
1742
+ case "provider_error":
1743
+ return "The provider could not complete sign-in. Retry, or contact the provider if it continues.";
1744
+ case "exchange_failed":
1745
+ return "The provider sign-in completed, but Evident could not exchange the authorization. Retry or contact support.";
1746
+ case "reconcile_failed":
1747
+ case "tools_pending":
1748
+ return "Sign-in completed, but Evident could not finish setting up this connection. Retry or contact support.";
1749
+ case "not_configured":
1750
+ return "Local authorization is not configured for this Evident environment. Contact your workspace admin.";
1751
+ default:
1752
+ return "Evident could not complete this sign-in. Start a new authorization and try again.";
1753
+ }
1754
+ }
1755
+ function printLink(options, url, reason) {
1756
+ if (options.json) {
1757
+ console.error(JSON.stringify({ event: "authorization_required", authorization_url: url.href }));
1758
+ return;
1759
+ }
1760
+ printWarning(reason ?? "Open this authorization URL in your browser:");
1761
+ console.log(url.href);
1762
+ }
1763
+ function printResult(options, proxyId, connectionId, error2) {
1764
+ if (options.json) {
1765
+ console.log(
1766
+ JSON.stringify({
1767
+ ok: !error2,
1768
+ proxy_id: proxyId,
1769
+ connection_id: connectionId,
1770
+ ...error2 ? { error: error2 } : {}
1771
+ })
1772
+ );
1773
+ } else if (error2) {
1774
+ printError(error2);
1775
+ } else {
1776
+ printSuccess("MCP connection authorized.");
1777
+ }
1778
+ }
1779
+ function errorMessage(error2) {
1780
+ if (error2 instanceof ApiHttpError) return apiFailureMessage(error2);
1781
+ if (error2 instanceof CallbackExpiredError) {
1782
+ return "The sign-in attempt expired before the provider returned. Run the command again.";
1783
+ }
1784
+ if (error2 instanceof InterruptedError) return "Authorization was interrupted.";
1785
+ if (error2 instanceof Error) return error2.message;
1786
+ return `Authorization failed: ${String(error2)}`;
1787
+ }
1788
+ function requestFailed(reason) {
1789
+ if (reason instanceof Error) throw reason;
1790
+ throw new Error(`Authorization failed: ${String(reason)}`);
1791
+ }
1792
+ function validateConnectionList(value) {
1793
+ if (!value || !Array.isArray(value.mcp_proxy_connections)) {
1794
+ throw new Error("Evident returned an invalid MCP connection list. Update the CLI and retry.");
1795
+ }
1796
+ return value.mcp_proxy_connections;
1797
+ }
1798
+ function validateBeginResponse(value) {
1799
+ if (!value || typeof value.authorization_url !== "string" || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at))) {
1800
+ throw new Error(
1801
+ "Evident returned an invalid local authorization attempt. Update the CLI and retry."
1802
+ );
1803
+ }
1804
+ }
1805
+ function closeServer(server, force) {
1806
+ if (!server.listening) return Promise.resolve();
1807
+ return new Promise((resolve6, reject) => {
1808
+ server.close((error2) => error2 ? reject(error2) : resolve6());
1809
+ if (force) server.closeAllConnections();
1810
+ });
1811
+ }
1812
+ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1813
+ let credentials2;
1814
+ try {
1815
+ credentials2 = await getAuthCredentials();
1816
+ } catch (error2) {
1817
+ const kind = error2 instanceof Error ? error2.name : "unknown error";
1818
+ printResult(
1819
+ options,
1820
+ proxyId,
1821
+ connectionId,
1822
+ `Could not read the saved Evident credentials (${kind}). Check keychain access or run evident login again.`
1823
+ );
1824
+ process.exitCode = 1;
1825
+ return;
1826
+ }
1827
+ if (!credentials2) {
1828
+ printResult(
1829
+ options,
1830
+ proxyId,
1831
+ connectionId,
1832
+ "No credentials found. Run `evident login` and retry."
1833
+ );
1834
+ process.exitCode = 1;
1835
+ return;
1836
+ }
1837
+ if (credentials2.authType !== "bearer") {
1838
+ printResult(
1839
+ options,
1840
+ proxyId,
1841
+ connectionId,
1842
+ "MCP authorization requires a user login, not a runner key. Unset EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY, then run `evident login`."
1843
+ );
1844
+ process.exitCode = 1;
1845
+ return;
1846
+ }
1847
+ const waiter = { accepted: false };
1848
+ let server;
1849
+ let closePromise;
1850
+ let closeFailureLogged = false;
1851
+ let failure;
1852
+ const cancelController = new AbortController();
1853
+ const closeListener = (force = false) => {
1854
+ if (!server || closePromise) return closePromise ?? Promise.resolve();
1855
+ closePromise = closeServer(server, force);
1856
+ return closePromise;
1857
+ };
1858
+ const onSigint = () => {
1859
+ cancelController.abort();
1860
+ void closeListener(true).catch((error2) => {
1861
+ closeFailureLogged = true;
1862
+ console.error(
1863
+ `[mcp authorize] listener shutdown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${error2 instanceof Error ? error2.message : String(error2)}`
1864
+ );
1865
+ });
1866
+ };
1867
+ try {
1868
+ const listener = await bindCallbackListener(waiter);
1869
+ server = listener.server;
1870
+ process.once("SIGINT", onSigint);
1871
+ if (listener.port !== MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) {
1872
+ const notice = `Port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} is busy; using an ephemeral local port.`;
1873
+ if (options.json)
1874
+ console.error(JSON.stringify({ event: "listener_fallback", message: notice }));
1875
+ else printWarning(notice);
1876
+ }
1877
+ const connectionList = await requestJson(
1878
+ apiPath(proxyId),
1879
+ credentials2,
1880
+ cancelController.signal,
1881
+ "checking the MCP connection"
1882
+ );
1883
+ const connection = validateConnectionList(connectionList).find(
1884
+ (candidate) => candidate.connection_id === connectionId
1885
+ );
1886
+ if (!connection)
1887
+ throw new Error("The MCP connection was not found. Check the connection ID and try again.");
1888
+ if (connection.authorization_mode !== "local") {
1889
+ throw new Error("This connection uses hosted sign-in. Authorize it from Evident instead.");
1890
+ }
1891
+ if (connection.auth_kind !== "oauth2") {
1892
+ throw new Error("This MCP connection does not support OAuth authorization.");
1893
+ }
1894
+ const redirectUri = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}${MCP_LOOPBACK_REDIRECT_POLICY.path}`;
1895
+ const begin = await requestJson(
1896
+ apiPath(proxyId, connectionId, "begin"),
1897
+ credentials2,
1898
+ cancelController.signal,
1899
+ "starting local authorization",
1900
+ { redirect_uri: redirectUri }
1901
+ );
1902
+ validateBeginResponse(begin);
1903
+ const { url: authorizationUrl, state } = authorizationState(begin.authorization_url);
1904
+ waiter.expectedState = state;
1905
+ const expiresAtMs = Date.parse(begin.expires_at);
1906
+ if (expiresAtMs <= Date.now()) throw new CallbackExpiredError();
1907
+ waiter.expiresAtMs = expiresAtMs;
1908
+ const callbackOutcome = waitForCallback(waiter, expiresAtMs, cancelController.signal).then(
1909
+ (callback2) => ({ ok: true, callback: callback2 }),
1910
+ (error2) => ({ ok: false, error: error2 })
1911
+ );
1912
+ let callback;
1913
+ if (options.noBrowser) {
1914
+ printLink(options, authorizationUrl);
1915
+ const outcome = await callbackOutcome;
1916
+ if (!outcome.ok) requestFailed(outcome.error);
1917
+ callback = outcome.callback;
1918
+ } else {
1919
+ const browserOutcome = open2(authorizationUrl.href).then(
1920
+ () => ({ ok: true }),
1921
+ (error2) => ({ ok: false, error: error2 })
1922
+ );
1923
+ const first = await Promise.race([
1924
+ browserOutcome.then((outcome) => ({ kind: "browser", outcome })),
1925
+ callbackOutcome.then((outcome) => ({ kind: "callback", outcome }))
1926
+ ]);
1927
+ if (first.kind === "callback") {
1928
+ if (!first.outcome.ok) requestFailed(first.outcome.error);
1929
+ callback = first.outcome.callback;
1930
+ } else {
1931
+ if (!first.outcome.ok) {
1932
+ const detail = first.outcome.error instanceof Error ? ` (${first.outcome.error.message})` : "";
1933
+ printLink(
1934
+ options,
1935
+ authorizationUrl,
1936
+ `Could not open the browser automatically${detail}. Open this URL:`
1937
+ );
1938
+ }
1939
+ const outcome = await callbackOutcome;
1940
+ if (!outcome.ok) requestFailed(outcome.error);
1941
+ callback = outcome.callback;
1942
+ }
1943
+ }
1944
+ const completionBody = {
1945
+ state: callback.state,
1946
+ ...callback.code === void 0 ? {} : { code: callback.code },
1947
+ ...callback.error === void 0 ? {} : { error: callback.error },
1948
+ ...callback.error_description === void 0 ? {} : { error_description: callback.error_description }
1949
+ };
1950
+ const completion = await requestJson(
1951
+ apiPath(proxyId, connectionId, "complete"),
1952
+ credentials2,
1953
+ cancelController.signal,
1954
+ "completing local authorization",
1955
+ completionBody
1956
+ );
1957
+ if (completion.outcome !== "success") failure = completionFailureMessage(completion.reason);
1958
+ } catch (error2) {
1959
+ failure = errorMessage(error2);
1960
+ } finally {
1961
+ process.removeListener("SIGINT", onSigint);
1962
+ try {
1963
+ await closeListener();
1964
+ } catch (error2) {
1965
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1966
+ if (!closeFailureLogged) {
1967
+ console.error(
1968
+ `[mcp authorize] listener teardown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${detail}`
1969
+ );
1970
+ }
1971
+ failure ??= "The local callback listener could not be closed cleanly. Check for a lingering process and retry.";
1972
+ }
1973
+ }
1974
+ printResult(options, proxyId, connectionId, failure);
1975
+ if (failure) process.exitCode = cancelController.signal.aborted ? 130 : 1;
1976
+ }
1977
+
1475
1978
  // src/commands/run.ts
1979
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
1980
+ import { homedir as homedir9 } from "node:os";
1981
+ import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
1982
+ import chalk7 from "chalk";
1476
1983
  import ora4 from "ora";
1477
1984
  import { select as select4 } from "@inquirer/prompts";
1478
1985
 
1479
1986
  // src/lib/telemetry.ts
1480
- var CLI_VERSION = (true ? "3.6.1-dev.7a7e0e5" : void 0) ?? process.env.npm_package_version ?? "unknown";
1987
+ var CLI_VERSION = (true ? "3.6.1-dev.87c1db8" : void 0) ?? process.env.npm_package_version ?? "unknown";
1481
1988
  function getCliVersion() {
1482
1989
  return CLI_VERSION;
1483
1990
  }
@@ -1674,7 +2181,7 @@ var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
1674
2181
  var SESSION_DB_RECLAIM_TIME_BUDGET_MS = 500;
1675
2182
  var SESSION_DB_RECLAIM_PAGE_CEILING = 4e4;
1676
2183
  var SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS = 5e3;
1677
- function errorMessage(error2) {
2184
+ function errorMessage2(error2) {
1678
2185
  if (!(error2 instanceof Error)) return String(error2);
1679
2186
  return error2.cause instanceof Error ? error2.cause.message : error2.message;
1680
2187
  }
@@ -1808,7 +2315,7 @@ async function probeReclaimAvailability(input) {
1808
2315
  try {
1809
2316
  sqlite = await import("node:sqlite");
1810
2317
  } catch (err) {
1811
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2318
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1812
2319
  console.warn(`[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ` + detail);
1813
2320
  return { reason: "sqlite-unavailable", detail };
1814
2321
  }
@@ -1843,7 +2350,7 @@ async function reclaimSessionDbSpace(input) {
1843
2350
  try {
1844
2351
  sqlite = await import("node:sqlite");
1845
2352
  } catch (err) {
1846
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2353
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1847
2354
  console.warn(
1848
2355
  `[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${detail}`
1849
2356
  );
@@ -1954,11 +2461,11 @@ async function reclaimSessionDbSpace(input) {
1954
2461
  );
1955
2462
  return { ok: false, skipped: "auto-vacuum-not-applicable" };
1956
2463
  } catch (err) {
1957
- console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage(err));
2464
+ console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage2(err));
1958
2465
  return {
1959
2466
  ok: false,
1960
2467
  skipped: isSessionStoreWriteFailure(err) ? "disk-exhaustion" : "reclaim-error",
1961
- detail: errorMessage(err)
2468
+ detail: errorMessage2(err)
1962
2469
  };
1963
2470
  } finally {
1964
2471
  db?.close();
@@ -3110,7 +3617,7 @@ function buildSessionArchive(input) {
3110
3617
  function isRecord2(value) {
3111
3618
  return typeof value === "object" && value !== null && !Array.isArray(value);
3112
3619
  }
3113
- function errorMessage2(error2) {
3620
+ function errorMessage3(error2) {
3114
3621
  return error2 instanceof Error ? error2.message : String(error2);
3115
3622
  }
3116
3623
  function invalidResponse(version2, sessionId, path, reason) {
@@ -3128,7 +3635,7 @@ async function requestPage(client, sessionId, path, signal) {
3128
3635
  } catch (error2) {
3129
3636
  throw new SessionArchiveExportError(
3130
3637
  "request-failed",
3131
- `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage2(error2)}`
3638
+ `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage3(error2)}`
3132
3639
  );
3133
3640
  }
3134
3641
  if (response.status === 404) {
@@ -3149,7 +3656,7 @@ async function requestPage(client, sessionId, path, signal) {
3149
3656
  } catch (error2) {
3150
3657
  throw new SessionArchiveExportError(
3151
3658
  "request-failed",
3152
- `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage2(error2)}`
3659
+ `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage3(error2)}`
3153
3660
  );
3154
3661
  }
3155
3662
  try {
@@ -3184,7 +3691,7 @@ function v1NextCursor(response, sessionId, path) {
3184
3691
  } catch (error2) {
3185
3692
  throw new SessionArchiveExportError(
3186
3693
  "pagination-failed",
3187
- `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage2(error2)}`
3694
+ `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage3(error2)}`
3188
3695
  );
3189
3696
  }
3190
3697
  }
@@ -5708,8 +6215,8 @@ function classifyReplyAuthError(reply) {
5708
6215
  };
5709
6216
  }
5710
6217
  }
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))) {
6218
+ const errorMessage5 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
6219
+ if (errorMessage5 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage5.includes(knownMessage))) {
5713
6220
  return {
5714
6221
  kind: "model_auth",
5715
6222
  providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
@@ -5764,7 +6271,7 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
5764
6271
  (m) => roleOf2(m) === "assistant" && parentIdOf2(m) !== exceptUserMessageId && isAssistantInFlight(m)
5765
6272
  );
5766
6273
  }
5767
- function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds) {
6274
+ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds, apiVersion) {
5768
6275
  if (!messages || messages.length === 0) return false;
5769
6276
  const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
5770
6277
  if (userIndex === -1) return false;
@@ -5778,7 +6285,7 @@ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageI
5778
6285
  if (laterUserMessageId === void 0 || !siblingUserMessageIds.has(laterUserMessageId)) {
5779
6286
  return false;
5780
6287
  }
5781
- if (messages.some(
6288
+ if (apiVersion === "v2" || messages.some(
5782
6289
  (candidate) => roleOf2(candidate) === "assistant" && parentIdOf2(candidate) === laterUserMessageId
5783
6290
  )) {
5784
6291
  hasStartedLaterUser = true;
@@ -7666,7 +8173,7 @@ function buildSessionStoreSizeWarning(input) {
7666
8173
  import { statSync as statSync5 } from "node:fs";
7667
8174
  import { homedir as homedir5 } from "node:os";
7668
8175
  import { join as join11 } from "node:path";
7669
- import { open as open2, stat } from "node:fs/promises";
8176
+ import { open as open3, stat } from "node:fs/promises";
7670
8177
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
7671
8178
  function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
7672
8179
  const dataDir = env.XDG_DATA_HOME || join11(homeDir, ".local", "share");
@@ -7720,7 +8227,7 @@ function tailOpenCodeLogFile(logPath, onChunk, opts = {}) {
7720
8227
  inode = current.ino;
7721
8228
  if (current.size === offset) return;
7722
8229
  const length = current.size - offset;
7723
- const fh = await open2(logPath, "r");
8230
+ const fh = await open3(logPath, "r");
7724
8231
  try {
7725
8232
  const buf = Buffer.alloc(length);
7726
8233
  const { bytesRead } = await fh.read(buf, 0, length, offset);
@@ -7753,7 +8260,7 @@ import WebSocket from "ws";
7753
8260
 
7754
8261
  // src/lib/file-read.ts
7755
8262
  import { constants } from "node:fs";
7756
- import { open as open3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
8263
+ import { open as open4, realpath as realpath2, stat as stat2 } from "node:fs/promises";
7757
8264
  import { extname, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
7758
8265
  import { homedir as homedir6 } from "node:os";
7759
8266
 
@@ -7803,7 +8310,7 @@ var FILE_MIME_TYPES = {
7803
8310
  ".mp4": "video/mp4",
7804
8311
  ".mov": "video/quicktime"
7805
8312
  };
7806
- async function readProjectFile(projectRoot, method, requestedPath, openFile = open3) {
8313
+ async function readProjectFile(projectRoot, method, requestedPath, openFile = open4) {
7807
8314
  if (method !== "GET") return refuse(405, "method_not_allowed");
7808
8315
  if (!projectRoot || !isAbsolute3(projectRoot)) return refuse(503, "project_root_unavailable");
7809
8316
  if (!requestedPath || requestedPath.length > 4096 || requestedPath.includes("\0")) {
@@ -8376,8 +8883,8 @@ function connectTunnel(options) {
8376
8883
  }
8377
8884
  forwarder.handleBinaryBodyFrame(frame.sid, frame.payload);
8378
8885
  } catch (error2) {
8379
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8380
- onError?.(`Failed to handle binary message: ${errorMessage4}`);
8886
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
8887
+ onError?.(`Failed to handle binary message: ${errorMessage5}`);
8381
8888
  }
8382
8889
  return;
8383
8890
  }
@@ -8385,8 +8892,8 @@ function connectTunnel(options) {
8385
8892
  try {
8386
8893
  message = JSON.parse(data.toString());
8387
8894
  } catch (error2) {
8388
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8389
- onError?.(`Failed to handle message: ${errorMessage4}`);
8895
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
8896
+ onError?.(`Failed to handle message: ${errorMessage5}`);
8390
8897
  return;
8391
8898
  }
8392
8899
  if (isStreamFrame(message)) {
@@ -8965,7 +9472,7 @@ import { join as join14 } from "node:path";
8965
9472
 
8966
9473
  // src/lib/file-push.ts
8967
9474
  import { randomUUID } from "node:crypto";
8968
- import { chmod, mkdir, open as open4, realpath as realpath3, rename, unlink } from "node:fs/promises";
9475
+ import { chmod, mkdir, open as open5, realpath as realpath3, rename, unlink } from "node:fs/promises";
8969
9476
  import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute4, join as join13 } from "node:path";
8970
9477
  var FILE_MODE = 384;
8971
9478
  var DIRECTORY_MODE = 448;
@@ -9098,7 +9605,7 @@ async function writeAtomically(realTarget, content) {
9098
9605
  const temporaryPath = join13(dirname10(realTarget), `.evident-push-${randomUUID()}.tmp`);
9099
9606
  let handle;
9100
9607
  try {
9101
- handle = await open4(temporaryPath, "wx", FILE_MODE);
9608
+ handle = await open5(temporaryPath, "wx", FILE_MODE);
9102
9609
  await handle.writeFile(content);
9103
9610
  await handle.chmod(FILE_MODE);
9104
9611
  await handle.close();
@@ -10299,12 +10806,12 @@ var ChannelDriver = class _ChannelDriver {
10299
10806
  this.sessions.delete(conversationId);
10300
10807
  this.supersede(conversationId, sessionId);
10301
10808
  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);
10809
+ 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.`;
10810
+ this.untrackableAck.set(messageId, errorMessage5);
10304
10811
  this.untrackableAckSessionIds.set(messageId, null);
10305
10812
  this.log({
10306
10813
  level: "error",
10307
- message: errorMessage4,
10814
+ message: errorMessage5,
10308
10815
  conversation_id: conversationId,
10309
10816
  message_id: messageId
10310
10817
  });
@@ -10312,7 +10819,7 @@ var ChannelDriver = class _ChannelDriver {
10312
10819
  conversationId,
10313
10820
  messageId,
10314
10821
  null,
10315
- errorMessage4
10822
+ errorMessage5
10316
10823
  );
10317
10824
  if (reportError !== null) {
10318
10825
  this.log({
@@ -10493,12 +11000,12 @@ var ChannelDriver = class _ChannelDriver {
10493
11000
  conversation_id: conv.id,
10494
11001
  message_id: message.id
10495
11002
  });
10496
- const errorMessage4 = this.untrackableAck.get(message.id);
11003
+ const errorMessage5 = this.untrackableAck.get(message.id);
10497
11004
  const reportError = await this.reportUntrackableAck(
10498
11005
  conv.id,
10499
11006
  message.id,
10500
11007
  null,
10501
- errorMessage4
11008
+ errorMessage5
10502
11009
  );
10503
11010
  if (reportError === null) {
10504
11011
  continue;
@@ -10586,7 +11093,7 @@ var ChannelDriver = class _ChannelDriver {
10586
11093
  const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
10587
11094
  const providerId = hasProviderAndModel ? dispatchedModel.slice(0, separator) : null;
10588
11095
  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.`;
11096
+ const errorMessage5 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
10590
11097
  this.log({
10591
11098
  level: "error",
10592
11099
  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 +11101,7 @@ var ChannelDriver = class _ChannelDriver {
10594
11101
  message_id: message.id
10595
11102
  });
10596
11103
  try {
10597
- await this.markFailed(conv.id, message.id, sessionId, errorMessage4, void 0, {
11104
+ await this.markFailed(conv.id, message.id, sessionId, errorMessage5, void 0, {
10598
11105
  classification: {
10599
11106
  kind: "model_auth",
10600
11107
  providerId,
@@ -10672,12 +11179,12 @@ var ChannelDriver = class _ChannelDriver {
10672
11179
  } catch (err) {
10673
11180
  if (err instanceof ChannelAuthError) throw err;
10674
11181
  if (this.isV2 && err instanceof OpenCodeV2PromptAckError) {
10675
- const errorMessage5 = err instanceof Error ? err.message : String(err);
10676
- this.untrackableAck.set(message.id, errorMessage5);
11182
+ const errorMessage6 = err instanceof Error ? err.message : String(err);
11183
+ this.untrackableAck.set(message.id, errorMessage6);
10677
11184
  this.untrackableAckSessionIds.set(message.id, null);
10678
11185
  this.log({
10679
11186
  level: "error",
10680
- message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage5}`,
11187
+ message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage6}`,
10681
11188
  conversation_id: conv.id,
10682
11189
  message_id: message.id
10683
11190
  });
@@ -10685,7 +11192,7 @@ var ChannelDriver = class _ChannelDriver {
10685
11192
  conv.id,
10686
11193
  message.id,
10687
11194
  null,
10688
- errorMessage5
11195
+ errorMessage6
10689
11196
  );
10690
11197
  if (markError !== null) {
10691
11198
  this.log({
@@ -10724,7 +11231,7 @@ var ChannelDriver = class _ChannelDriver {
10724
11231
  await this.failV2ModelSwitch(conv, message, sessionId, err);
10725
11232
  break;
10726
11233
  }
10727
- const errorMessage4 = err instanceof Error ? err.message : String(err);
11234
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
10728
11235
  this.sessions.delete(conv.id);
10729
11236
  this.supersede(conv.id, sessionId);
10730
11237
  this.log({
@@ -10733,7 +11240,7 @@ var ChannelDriver = class _ChannelDriver {
10733
11240
  conversation_id: conv.id,
10734
11241
  message_id: message.id
10735
11242
  });
10736
- await this.markFailed(conv.id, message.id, null, errorMessage4).catch((markErr) => {
11243
+ await this.markFailed(conv.id, message.id, null, errorMessage5).catch((markErr) => {
10737
11244
  this.log({
10738
11245
  level: "warn",
10739
11246
  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 +11251,7 @@ var ChannelDriver = class _ChannelDriver {
10744
11251
  });
10745
11252
  this.log({
10746
11253
  level: "error",
10747
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage4}`,
11254
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage5}`,
10748
11255
  conversation_id: conv.id,
10749
11256
  message_id: message.id
10750
11257
  });
@@ -11029,7 +11536,12 @@ var ChannelDriver = class _ChannelDriver {
11029
11536
  this.watchers.get(sessionId),
11030
11537
  message.id
11031
11538
  );
11032
- if (hasLaterSiblingTurnStarted(messages, ocId ?? "", siblingOcIds)) {
11539
+ if (hasLaterSiblingTurnStarted(
11540
+ messages,
11541
+ ocId ?? "",
11542
+ siblingOcIds,
11543
+ this.openCodeClient.version
11544
+ )) {
11033
11545
  this.log({
11034
11546
  level: "warn",
11035
11547
  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 +13180,12 @@ var ChannelDriver = class _ChannelDriver {
12668
13180
  return;
12669
13181
  }
12670
13182
  const siblingOcIds = this.siblingOpencodeMessageIds(watcher, inFlight.evidentMessageId);
12671
- const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(messages, inFlight.opencodeMessageId, siblingOcIds);
13183
+ const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(
13184
+ messages,
13185
+ inFlight.opencodeMessageId,
13186
+ siblingOcIds,
13187
+ this.openCodeClient.version
13188
+ );
12672
13189
  const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
12673
13190
  const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
12674
13191
  if (state === "queued" && pastStuckBound && (sessionIdle || skippedByOpencode) && !inFlight.stuckReported) {
@@ -13679,12 +14196,12 @@ var ChannelDriver = class _ChannelDriver {
13679
14196
  conversation_id: row.conversation_id,
13680
14197
  message_id: row.id
13681
14198
  });
13682
- const errorMessage4 = this.untrackableAck.get(row.id);
14199
+ const errorMessage5 = this.untrackableAck.get(row.id);
13683
14200
  const reportError = await this.reportUntrackableAck(
13684
14201
  row.conversation_id,
13685
14202
  row.id,
13686
14203
  this.untrackableAckSessionIds.get(row.id) ?? null,
13687
- errorMessage4
14204
+ errorMessage5
13688
14205
  );
13689
14206
  if (reportError !== null) {
13690
14207
  this.log({
@@ -14003,14 +14520,14 @@ var ChannelDriver = class _ChannelDriver {
14003
14520
  this.awaitingReadopt.delete(row.id);
14004
14521
  if (err instanceof ChannelAuthError) throw err;
14005
14522
  if (this.isV2) {
14006
- const errorMessage4 = err instanceof Error ? err.message : String(err);
14523
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
14007
14524
  const invalidPromptAck = err instanceof OpenCodeV2PromptAckError;
14008
14525
  if (!invalidPromptAck) {
14009
14526
  const exists = await this.sessionExists(sessionId);
14010
14527
  if (exists === false) {
14011
14528
  this.log({
14012
14529
  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}`,
14530
+ 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
14531
  conversation_id: row.conversation_id,
14015
14532
  message_id: row.id
14016
14533
  });
@@ -14020,7 +14537,7 @@ var ChannelDriver = class _ChannelDriver {
14020
14537
  if (exists === null) {
14021
14538
  this.log({
14022
14539
  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}`,
14540
+ 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
14541
  conversation_id: row.conversation_id,
14025
14542
  message_id: row.id
14026
14543
  });
@@ -14028,7 +14545,7 @@ var ChannelDriver = class _ChannelDriver {
14028
14545
  return;
14029
14546
  }
14030
14547
  } else {
14031
- this.untrackableAck.set(row.id, errorMessage4);
14548
+ this.untrackableAck.set(row.id, errorMessage5);
14032
14549
  this.untrackableAckSessionIds.set(row.id, sessionId);
14033
14550
  }
14034
14551
  if (err instanceof OpenCodeV2ModelSwitchError) {
@@ -14037,7 +14554,7 @@ var ChannelDriver = class _ChannelDriver {
14037
14554
  }
14038
14555
  this.log({
14039
14556
  level: "error",
14040
- message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage4}`,
14557
+ message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage5}`,
14041
14558
  conversation_id: row.conversation_id,
14042
14559
  message_id: row.id
14043
14560
  });
@@ -14046,7 +14563,7 @@ var ChannelDriver = class _ChannelDriver {
14046
14563
  row.conversation_id,
14047
14564
  row.id,
14048
14565
  sessionId,
14049
- errorMessage4
14566
+ errorMessage5
14050
14567
  );
14051
14568
  if (markError !== null) {
14052
14569
  this.log({
@@ -14057,7 +14574,7 @@ var ChannelDriver = class _ChannelDriver {
14057
14574
  });
14058
14575
  }
14059
14576
  } else {
14060
- await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage4).catch(
14577
+ await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage5).catch(
14061
14578
  (markErr) => {
14062
14579
  this.log({
14063
14580
  level: "warn",
@@ -15041,9 +15558,9 @@ var ChannelDriver = class _ChannelDriver {
15041
15558
  * trackable. Callers use the returned error to keep their path-specific logging
15042
15559
  * while the same report payload can be retried on a later drain.
15043
15560
  */
15044
- async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage4) {
15561
+ async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage5) {
15045
15562
  try {
15046
- await this.markFailed(conversationId, messageId, sessionId, errorMessage4);
15563
+ await this.markFailed(conversationId, messageId, sessionId, errorMessage5);
15047
15564
  return null;
15048
15565
  } catch (err) {
15049
15566
  this.signalUntrackableAck(conversationId, messageId);
@@ -16207,7 +16724,7 @@ var MAX_FLUSH_PASSES = 2;
16207
16724
  function outcomesWith(outcome) {
16208
16725
  return { claude: outcome, opencode: outcome };
16209
16726
  }
16210
- function errorMessage3(error2) {
16727
+ function errorMessage4(error2) {
16211
16728
  return error2 instanceof Error ? error2.message : String(error2);
16212
16729
  }
16213
16730
  function waitForSettlement(promise, timeoutMs) {
@@ -16234,7 +16751,7 @@ function writeMarker(markerPath, outcomes, log3) {
16234
16751
  writeFileSync8(temporaryPath, body, { mode: 384 });
16235
16752
  renameSync(temporaryPath, markerPath);
16236
16753
  } catch (error2) {
16237
- log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage3(error2)}`, "warn");
16754
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage4(error2)}`, "warn");
16238
16755
  }
16239
16756
  }
16240
16757
  function intervalSeconds(env, log3) {
@@ -16266,7 +16783,7 @@ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
16266
16783
  },
16267
16784
  (error2) => {
16268
16785
  failed = true;
16269
- log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage3(error2)}`, "warn");
16786
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage4(error2)}`, "warn");
16270
16787
  }
16271
16788
  );
16272
16789
  const abortTimer = setTimeout(() => controller.abort(), remainingMs);
@@ -16326,7 +16843,7 @@ function createCredentialSync({
16326
16843
  outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
16327
16844
  } catch (error2) {
16328
16845
  outcomes[store] = "failed";
16329
- log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage3(error2)}`, "debug");
16846
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage4(error2)}`, "debug");
16330
16847
  }
16331
16848
  }
16332
16849
  const failed = STORES.some((store) => outcomes[store] === "failed");
@@ -17331,8 +17848,8 @@ async function driveChannels(state, driver) {
17331
17848
  state.running = false;
17332
17849
  break;
17333
17850
  }
17334
- const errorMessage4 = error2 instanceof Error ? error2.message : String(error2);
17335
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage4}` });
17851
+ const errorMessage5 = error2 instanceof Error ? error2.message : String(error2);
17852
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage5}` });
17336
17853
  if (state.interactive) displayStatus(state);
17337
17854
  if (driver.hasInFlightWatchers()) {
17338
17855
  consecutiveDrainFailures = 0;
@@ -19625,7 +20142,7 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
19625
20142
  "--endpoint <url>",
19626
20143
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
19627
20144
  ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
19628
- const { endpoint: endpoint2, tunnel } = thisCommand.opts();
20145
+ const { endpoint: endpoint2, tunnel } = thisCommand.optsWithGlobals();
19629
20146
  if (endpoint2) {
19630
20147
  setEndpoint(endpoint2);
19631
20148
  }
@@ -19636,6 +20153,12 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
19636
20153
  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
20154
  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
20155
  program.command("whoami").description("Show the currently logged in user").action(whoami);
20156
+ 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(
20157
+ (proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
20158
+ noBrowser: options.browser === false,
20159
+ json: options.json
20160
+ })
20161
+ );
19639
20162
  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
20163
  program.command("credential-vault-env").description("Print the shell assignment a runner image evals before starting the synchroniser").action(credentialVaultEnv);
19641
20164
  program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);