@evident-ai/cli 3.6.1-dev.9c960b2 → 3.6.1-dev.a6e5986
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/README.md +39 -0
- package/dist/index.js +1101 -153
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __export = (target, all) => {
|
|
4
|
+
for (var name in all)
|
|
5
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
6
|
+
};
|
|
2
7
|
|
|
3
8
|
// src/index.ts
|
|
4
9
|
import { Command } from "commander";
|
|
@@ -9,6 +14,24 @@ import ora from "ora";
|
|
|
9
14
|
import chalk2 from "chalk";
|
|
10
15
|
|
|
11
16
|
// src/lib/config.ts
|
|
17
|
+
var config_exports = {};
|
|
18
|
+
__export(config_exports, {
|
|
19
|
+
clearAllCredentials: () => clearAllCredentials,
|
|
20
|
+
clearCredentials: () => clearCredentials,
|
|
21
|
+
clearManagedInferenceCredential: () => clearManagedInferenceCredential,
|
|
22
|
+
credentials: () => credentials,
|
|
23
|
+
getApiUrlConfig: () => getApiUrlConfig,
|
|
24
|
+
getCliName: () => getCliName,
|
|
25
|
+
getCredentials: () => getCredentials,
|
|
26
|
+
getManagedInferenceCredential: () => getManagedInferenceCredential,
|
|
27
|
+
getTeamSelection: () => getTeamSelection,
|
|
28
|
+
getTunnelUrlConfig: () => getTunnelUrlConfig,
|
|
29
|
+
setCredentials: () => setCredentials,
|
|
30
|
+
setEndpoint: () => setEndpoint,
|
|
31
|
+
setManagedInferenceCredential: () => setManagedInferenceCredential,
|
|
32
|
+
setTeamSelection: () => setTeamSelection,
|
|
33
|
+
setTunnelUrl: () => setTunnelUrl
|
|
34
|
+
});
|
|
12
35
|
import Conf from "conf";
|
|
13
36
|
import { chmodSync, existsSync, statSync } from "node:fs";
|
|
14
37
|
import { dirname } from "node:path";
|
|
@@ -20,6 +43,7 @@ var defaults = {
|
|
|
20
43
|
};
|
|
21
44
|
var endpointOverride;
|
|
22
45
|
var tunnelOverride;
|
|
46
|
+
var teamOverride;
|
|
23
47
|
function setEndpoint(url) {
|
|
24
48
|
if (!url) {
|
|
25
49
|
endpointOverride = void 0;
|
|
@@ -31,6 +55,13 @@ function setEndpoint(url) {
|
|
|
31
55
|
function setTunnelUrl(url) {
|
|
32
56
|
tunnelOverride = url ? url.replace(/\/+$/, "") : void 0;
|
|
33
57
|
}
|
|
58
|
+
function setTeamSelection(id) {
|
|
59
|
+
const trimmed = id?.trim();
|
|
60
|
+
teamOverride = trimmed || void 0;
|
|
61
|
+
}
|
|
62
|
+
function getTeamSelection() {
|
|
63
|
+
return teamOverride ?? (process.env.EVIDENT_TEAM?.trim() || void 0);
|
|
64
|
+
}
|
|
34
65
|
function getApiUrl() {
|
|
35
66
|
return endpointOverride ?? process.env.EVIDENT_API_URL ?? defaults.apiUrl;
|
|
36
67
|
}
|
|
@@ -579,6 +610,14 @@ function getAuthHeader(credentials2) {
|
|
|
579
610
|
}
|
|
580
611
|
return `Bearer ${credentials2.token}`;
|
|
581
612
|
}
|
|
613
|
+
function buildAuthHeaders(credentials2) {
|
|
614
|
+
const headers = { Authorization: getAuthHeader(credentials2) };
|
|
615
|
+
const team = Object.hasOwn(config_exports, "getTeamSelection") ? getTeamSelection() : void 0;
|
|
616
|
+
if (credentials2.authType === "bearer" && team) {
|
|
617
|
+
headers["X-Evident-Team"] = team;
|
|
618
|
+
}
|
|
619
|
+
return headers;
|
|
620
|
+
}
|
|
582
621
|
function isInteractive(jsonOutput) {
|
|
583
622
|
if (jsonOutput) return false;
|
|
584
623
|
if (process.env.CI) return false;
|
|
@@ -1180,6 +1219,7 @@ async function claudeUsage() {
|
|
|
1180
1219
|
|
|
1181
1220
|
// src/commands/mcp-authorize.ts
|
|
1182
1221
|
import { createServer } from "node:http";
|
|
1222
|
+
import { randomBytes } from "node:crypto";
|
|
1183
1223
|
import open2 from "open";
|
|
1184
1224
|
|
|
1185
1225
|
// ../../packages/types/src/agents/index.ts
|
|
@@ -1485,8 +1525,9 @@ function stripQuery(url) {
|
|
|
1485
1525
|
|
|
1486
1526
|
// src/commands/mcp-authorize.ts
|
|
1487
1527
|
var API_TIMEOUT_MS = 1e4;
|
|
1488
|
-
var
|
|
1489
|
-
var
|
|
1528
|
+
var CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS = 2e3;
|
|
1529
|
+
var COMPLETION_UNCONFIRMED_MESSAGE = "Completion could not be confirmed; check the connection in Evident before retrying.";
|
|
1530
|
+
var KNOWN_CALLBACK_PARAMETERS = /* @__PURE__ */ new Set(["state", "code", "error", "error_description", "iss"]);
|
|
1490
1531
|
var ApiHttpError = class extends Error {
|
|
1491
1532
|
constructor(status2, operation) {
|
|
1492
1533
|
super(`Evident API returned HTTP ${status2} while ${operation}`);
|
|
@@ -1522,7 +1563,7 @@ async function requestJson(path, credentials2, cancelSignal, operation, body) {
|
|
|
1522
1563
|
response = await fetch(`${getApiUrlConfig()}${path}`, {
|
|
1523
1564
|
method,
|
|
1524
1565
|
headers: {
|
|
1525
|
-
|
|
1566
|
+
...buildAuthHeaders(credentials2),
|
|
1526
1567
|
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
|
1527
1568
|
},
|
|
1528
1569
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
@@ -1554,76 +1595,400 @@ async function requestJson(path, credentials2, cancelSignal, operation, body) {
|
|
|
1554
1595
|
cancelSignal.removeEventListener("abort", onCancel);
|
|
1555
1596
|
}
|
|
1556
1597
|
}
|
|
1557
|
-
function
|
|
1598
|
+
function callbackPage(statusPath) {
|
|
1599
|
+
const nonce = randomBytes(18).toString("base64url");
|
|
1600
|
+
const statusMarkup = statusPath ? `<main class="card" id="callback-page" data-status-url="${statusPath}" role="status" aria-live="polite" aria-atomic="true">
|
|
1601
|
+
<span class="dot" aria-hidden="true"></span>
|
|
1602
|
+
<h1 id="status-heading">Provider response received</h1>
|
|
1603
|
+
<p id="status-message">Your provider response is here. Evident is preparing the connection.</p>
|
|
1604
|
+
<ol class="steps" aria-label="Authorization progress">
|
|
1605
|
+
<li data-step="provider" data-state="done"><span class="step-mark" aria-hidden="true">\u2713</span><span>Provider response received</span></li>
|
|
1606
|
+
<li data-step="evident" data-state="pending"><span class="step-mark" aria-hidden="true">2</span><span>Evident completes authorization</span></li>
|
|
1607
|
+
<li data-step="connection" data-state="pending"><span class="step-mark" aria-hidden="true">3</span><span>Review tools in Evident</span></li>
|
|
1608
|
+
</ol>
|
|
1609
|
+
<p class="footnote" id="status-footnote">Keep this page open while Evident finishes. The terminal shows the same progress.</p>
|
|
1610
|
+
</main>` : `<main class="card" role="status">
|
|
1611
|
+
<span class="dot" aria-hidden="true"></span>
|
|
1612
|
+
<h1>Sign-in response not accepted</h1>
|
|
1613
|
+
<p>This response wasn\u2019t accepted. Return to the terminal for details, then retry authorization if needed.</p>
|
|
1614
|
+
</main>`;
|
|
1615
|
+
const script = statusPath ? `<script nonce="${nonce}">
|
|
1616
|
+
history.replaceState(null, '', location.pathname);
|
|
1617
|
+
const page = document.getElementById('callback-page');
|
|
1618
|
+
const statusUrl = page.dataset.statusUrl;
|
|
1619
|
+
const views = {
|
|
1620
|
+
received: {
|
|
1621
|
+
heading: 'Provider response received',
|
|
1622
|
+
message: 'Your provider response is here. Evident is preparing the connection.',
|
|
1623
|
+
footnote: 'Keep this page open while Evident finishes. The terminal shows the same progress.',
|
|
1624
|
+
steps: ['done', 'pending', 'pending'],
|
|
1625
|
+
},
|
|
1626
|
+
completing: {
|
|
1627
|
+
heading: 'Evident is finishing setup',
|
|
1628
|
+
message: 'Evident received the response and is completing authorization.',
|
|
1629
|
+
footnote: 'This can take a moment. The terminal shows the same progress.',
|
|
1630
|
+
steps: ['done', 'current', 'pending'],
|
|
1631
|
+
},
|
|
1632
|
+
success: {
|
|
1633
|
+
heading: 'Authorization confirmed',
|
|
1634
|
+
message:
|
|
1635
|
+
'Evident confirmed authorization. Review the discovered tools in Evident to choose which to enable.',
|
|
1636
|
+
footnote: 'You can close this window.',
|
|
1637
|
+
steps: ['done', 'done', 'current'],
|
|
1638
|
+
},
|
|
1639
|
+
tools_pending: {
|
|
1640
|
+
heading: 'Authorization confirmed',
|
|
1641
|
+
message: 'Evident authorized the connection, but its tools are still being prepared.',
|
|
1642
|
+
footnote: 'Check the connection in Evident for tool status. You can close this window.',
|
|
1643
|
+
steps: ['done', 'done', 'current'],
|
|
1644
|
+
},
|
|
1645
|
+
failed: {
|
|
1646
|
+
heading: 'Sign-in did not finish',
|
|
1647
|
+
message: 'Evident could not complete setup. Check the terminal for the next step.',
|
|
1648
|
+
footnote: 'You can close this window after reading the terminal.',
|
|
1649
|
+
steps: ['done', 'failed', 'pending'],
|
|
1650
|
+
},
|
|
1651
|
+
unconfirmed: {
|
|
1652
|
+
heading: 'Completion could not be confirmed',
|
|
1653
|
+
message: 'Check the connection in Evident before retrying.',
|
|
1654
|
+
footnote: 'The terminal has the same status. Check the connection before starting another sign-in.',
|
|
1655
|
+
steps: ['done', 'uncertain', 'pending'],
|
|
1656
|
+
},
|
|
1657
|
+
};
|
|
1658
|
+
const terminalPhases = new Set(['success', 'tools_pending', 'failed', 'unconfirmed']);
|
|
1659
|
+
function showView(phase, view) {
|
|
1660
|
+
document.body.dataset.phase = phase;
|
|
1661
|
+
document.getElementById('status-heading').textContent = view.heading;
|
|
1662
|
+
document.getElementById('status-message').textContent = view.message;
|
|
1663
|
+
document.getElementById('status-footnote').textContent = view.footnote;
|
|
1664
|
+
['provider', 'evident', 'connection'].forEach((name, index) => {
|
|
1665
|
+
const step = document.querySelector('[data-step="' + name + '"]');
|
|
1666
|
+
const state = view.steps[index];
|
|
1667
|
+
step.dataset.state = state;
|
|
1668
|
+
step.querySelector('.step-mark').textContent = state === 'done' ? '\u2713' : String(index + 1);
|
|
1669
|
+
});
|
|
1670
|
+
}
|
|
1671
|
+
async function poll() {
|
|
1672
|
+
try {
|
|
1673
|
+
const response = await fetch(statusUrl, {
|
|
1674
|
+
cache: 'no-store',
|
|
1675
|
+
credentials: 'omit',
|
|
1676
|
+
redirect: 'error',
|
|
1677
|
+
headers: { Accept: 'application/json' },
|
|
1678
|
+
});
|
|
1679
|
+
if (!response.ok) throw new Error('status unavailable');
|
|
1680
|
+
const result = await response.json();
|
|
1681
|
+
const view = views[result.phase];
|
|
1682
|
+
if (!view) throw new Error('unknown status');
|
|
1683
|
+
showView(result.phase, view);
|
|
1684
|
+
if (terminalPhases.has(result.phase)) return;
|
|
1685
|
+
} catch (_error) {
|
|
1686
|
+
document.getElementById('status-message').textContent =
|
|
1687
|
+
'Evident is still finishing. Check the terminal for the latest status.';
|
|
1688
|
+
}
|
|
1689
|
+
window.setTimeout(poll, 400);
|
|
1690
|
+
}
|
|
1691
|
+
document.addEventListener('DOMContentLoaded', poll, { once: true });
|
|
1692
|
+
</script>` : `<script nonce="${nonce}">history.replaceState(null, '', location.pathname);</script>`;
|
|
1693
|
+
const html = `<!doctype html>
|
|
1694
|
+
<html lang="en">
|
|
1695
|
+
<head>
|
|
1696
|
+
<meta charset="utf-8" />
|
|
1697
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
1698
|
+
<meta name="robots" content="noindex" />
|
|
1699
|
+
<meta name="referrer" content="no-referrer" />
|
|
1700
|
+
<title>Sign-in \xB7 Evident</title>
|
|
1701
|
+
<style nonce="${nonce}">
|
|
1702
|
+
:root { color-scheme: light dark; }
|
|
1703
|
+
* { box-sizing: border-box; }
|
|
1704
|
+
body {
|
|
1705
|
+
margin: 0;
|
|
1706
|
+
min-height: 100vh;
|
|
1707
|
+
display: flex;
|
|
1708
|
+
align-items: center;
|
|
1709
|
+
justify-content: center;
|
|
1710
|
+
padding: 24px;
|
|
1711
|
+
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
|
1712
|
+
background: #0b0d12;
|
|
1713
|
+
color: #e6e8ee;
|
|
1714
|
+
}
|
|
1715
|
+
.card {
|
|
1716
|
+
width: 100%;
|
|
1717
|
+
max-width: 420px;
|
|
1718
|
+
text-align: center;
|
|
1719
|
+
background: #12151c;
|
|
1720
|
+
border: 1px solid #232838;
|
|
1721
|
+
border-radius: 16px;
|
|
1722
|
+
padding: 36px 24px;
|
|
1723
|
+
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
|
|
1724
|
+
}
|
|
1725
|
+
.dot {
|
|
1726
|
+
width: 12px;
|
|
1727
|
+
height: 12px;
|
|
1728
|
+
border-radius: 50%;
|
|
1729
|
+
background: #f59e0b;
|
|
1730
|
+
display: inline-block;
|
|
1731
|
+
margin-bottom: 20px;
|
|
1732
|
+
box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.15);
|
|
1733
|
+
}
|
|
1734
|
+
body[data-phase="success"] .dot {
|
|
1735
|
+
background: #34d399;
|
|
1736
|
+
box-shadow: 0 0 0 4px rgba(52, 211, 153, 0.15);
|
|
1737
|
+
}
|
|
1738
|
+
body[data-phase="failed"] .dot {
|
|
1739
|
+
background: #fb7185;
|
|
1740
|
+
box-shadow: 0 0 0 4px rgba(251, 113, 133, 0.15);
|
|
1741
|
+
}
|
|
1742
|
+
h1 { font-size: 20px; margin: 0 0 8px; font-weight: 600; }
|
|
1743
|
+
p { margin: 0; color: #9aa2b4; font-size: 14px; line-height: 1.5; }
|
|
1744
|
+
.steps { list-style: none; margin: 24px 0 0; padding: 0; text-align: left; }
|
|
1745
|
+
.steps li {
|
|
1746
|
+
display: flex;
|
|
1747
|
+
align-items: center;
|
|
1748
|
+
gap: 12px;
|
|
1749
|
+
min-height: 48px;
|
|
1750
|
+
border-top: 1px solid #232838;
|
|
1751
|
+
color: #9aa2b4;
|
|
1752
|
+
font-size: 14px;
|
|
1753
|
+
}
|
|
1754
|
+
.step-mark {
|
|
1755
|
+
width: 24px;
|
|
1756
|
+
height: 24px;
|
|
1757
|
+
border: 1px solid #42495b;
|
|
1758
|
+
border-radius: 50%;
|
|
1759
|
+
display: inline-flex;
|
|
1760
|
+
align-items: center;
|
|
1761
|
+
justify-content: center;
|
|
1762
|
+
flex: 0 0 auto;
|
|
1763
|
+
font-size: 12px;
|
|
1764
|
+
}
|
|
1765
|
+
[data-state="done"] { color: #e6e8ee !important; }
|
|
1766
|
+
[data-state="done"] .step-mark { border-color: #34d399; color: #34d399; }
|
|
1767
|
+
[data-state="current"] { color: #e6e8ee !important; }
|
|
1768
|
+
[data-state="current"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
|
|
1769
|
+
[data-state="failed"] .step-mark { border-color: #fb7185; color: #fb7185; }
|
|
1770
|
+
[data-state="uncertain"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
|
|
1771
|
+
.footnote { margin-top: 20px; font-size: 12px; }
|
|
1772
|
+
@media (max-width: 480px) {
|
|
1773
|
+
body { padding: 16px; }
|
|
1774
|
+
.card { padding: 32px 20px; }
|
|
1775
|
+
}
|
|
1776
|
+
</style>
|
|
1777
|
+
</head>
|
|
1778
|
+
<body>${statusMarkup}${script}</body>
|
|
1779
|
+
</html>`;
|
|
1780
|
+
return { html, nonce };
|
|
1781
|
+
}
|
|
1782
|
+
function callbackResponse(response, status2, html, nonce, onFinish) {
|
|
1558
1783
|
response.writeHead(status2, {
|
|
1559
1784
|
"Content-Type": "text/html; charset=utf-8",
|
|
1560
1785
|
"Cache-Control": "no-store",
|
|
1561
|
-
|
|
1562
|
-
"
|
|
1786
|
+
Pragma: "no-cache",
|
|
1787
|
+
"Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
|
|
1788
|
+
"X-Content-Type-Options": "nosniff",
|
|
1789
|
+
"X-Frame-Options": "DENY",
|
|
1790
|
+
"Referrer-Policy": "no-referrer",
|
|
1791
|
+
"Cross-Origin-Resource-Policy": "same-origin"
|
|
1792
|
+
});
|
|
1793
|
+
response.end(html, onFinish);
|
|
1794
|
+
}
|
|
1795
|
+
function statusResponse(response, status2, phase, onFinish) {
|
|
1796
|
+
response.writeHead(status2, {
|
|
1797
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
1798
|
+
"Cache-Control": "no-store",
|
|
1799
|
+
Pragma: "no-cache",
|
|
1800
|
+
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
|
|
1801
|
+
"X-Content-Type-Options": "nosniff",
|
|
1802
|
+
"X-Frame-Options": "DENY",
|
|
1803
|
+
"Referrer-Policy": "no-referrer",
|
|
1804
|
+
"Cross-Origin-Resource-Policy": "same-origin"
|
|
1805
|
+
});
|
|
1806
|
+
response.end(phase ? JSON.stringify({ phase }) : "", onFinish);
|
|
1807
|
+
}
|
|
1808
|
+
function isTerminalPagePhase(phase) {
|
|
1809
|
+
return phase === "success" || phase === "tools_pending" || phase === "failed" || phase === "unconfirmed";
|
|
1810
|
+
}
|
|
1811
|
+
function waitForTerminalStatusRead(page, signal) {
|
|
1812
|
+
if (page.terminalRead || signal.aborted) return Promise.resolve();
|
|
1813
|
+
return new Promise((resolve6) => {
|
|
1814
|
+
let settled = false;
|
|
1815
|
+
const finish = () => {
|
|
1816
|
+
if (settled) return;
|
|
1817
|
+
settled = true;
|
|
1818
|
+
clearTimeout(timer);
|
|
1819
|
+
signal.removeEventListener("abort", finish);
|
|
1820
|
+
if (page.notifyTerminalRead === finish) page.notifyTerminalRead = void 0;
|
|
1821
|
+
resolve6();
|
|
1822
|
+
};
|
|
1823
|
+
const timer = setTimeout(finish, CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS);
|
|
1824
|
+
page.notifyTerminalRead = finish;
|
|
1825
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
1826
|
+
if (signal.aborted) finish();
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
function handleStatusRequest(request3, response, page) {
|
|
1830
|
+
if (!request3.url?.startsWith("/_status/")) return false;
|
|
1831
|
+
const statusPath = `/_status/${page.capability}`;
|
|
1832
|
+
const base = page.origin ?? `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
|
|
1833
|
+
const url = URL.canParse(request3.url, base) ? new URL(request3.url, base) : void 0;
|
|
1834
|
+
const fetchSite = request3.headers["sec-fetch-site"];
|
|
1835
|
+
if (request3.method !== "GET" || !url || url.pathname !== statusPath || url.search || request3.headers.host !== page.host || fetchSite !== void 0 && fetchSite !== "same-origin" || request3.headers.origin !== void 0 && request3.headers.origin !== page.origin || request3.headers["transfer-encoding"] !== void 0 || Number(request3.headers["content-length"] ?? 0) > 0) {
|
|
1836
|
+
statusResponse(response, 404);
|
|
1837
|
+
return true;
|
|
1838
|
+
}
|
|
1839
|
+
const phase = page.phase;
|
|
1840
|
+
statusResponse(response, 200, phase, () => {
|
|
1841
|
+
if (isTerminalPagePhase(phase)) {
|
|
1842
|
+
page.terminalRead = true;
|
|
1843
|
+
page.notifyTerminalRead?.();
|
|
1844
|
+
}
|
|
1563
1845
|
});
|
|
1564
|
-
|
|
1846
|
+
return true;
|
|
1847
|
+
}
|
|
1848
|
+
function rejectedCallbackResponse(response, status2) {
|
|
1849
|
+
const page = callbackPage();
|
|
1850
|
+
callbackResponse(response, status2, page.html, page.nonce);
|
|
1565
1851
|
}
|
|
1566
1852
|
function parseCallbackRequest(request3) {
|
|
1567
1853
|
if (request3.method !== "GET" || !request3.url || !request3.url.startsWith("/") || request3.url.length > 16384) {
|
|
1568
|
-
return
|
|
1854
|
+
return { reason: "malformed_response" };
|
|
1569
1855
|
}
|
|
1570
1856
|
if (request3.headers["transfer-encoding"] || Number(request3.headers["content-length"] ?? 0) > 0) {
|
|
1571
|
-
return
|
|
1857
|
+
return { reason: "malformed_response" };
|
|
1572
1858
|
}
|
|
1573
1859
|
const callbackBase = `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
|
|
1574
|
-
if (!URL.canParse(request3.url, callbackBase)) return
|
|
1860
|
+
if (!URL.canParse(request3.url, callbackBase)) return { reason: "malformed_response" };
|
|
1575
1861
|
const url = new URL(request3.url, callbackBase);
|
|
1576
|
-
if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash)
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1862
|
+
if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash) {
|
|
1863
|
+
return { reason: "malformed_response" };
|
|
1864
|
+
}
|
|
1865
|
+
for (const parameter of url.search.slice(1).split("&")) {
|
|
1866
|
+
const separator = parameter.indexOf("=");
|
|
1867
|
+
const rawKey = separator === -1 ? parameter : parameter.slice(0, separator);
|
|
1868
|
+
let key;
|
|
1869
|
+
try {
|
|
1870
|
+
key = decodeURIComponent(rawKey.replaceAll("+", " "));
|
|
1871
|
+
} catch (_error) {
|
|
1872
|
+
continue;
|
|
1873
|
+
}
|
|
1874
|
+
if (!KNOWN_CALLBACK_PARAMETERS.has(key)) continue;
|
|
1875
|
+
const rawValue = separator === -1 ? "" : parameter.slice(separator + 1);
|
|
1876
|
+
try {
|
|
1877
|
+
decodeURIComponent(rawValue.replaceAll("+", " "));
|
|
1878
|
+
} catch (_error) {
|
|
1879
|
+
return { reason: "malformed_response" };
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
const params = url.searchParams;
|
|
1883
|
+
for (const key of ["state", "code", "error", "error_description", "iss"]) {
|
|
1884
|
+
if (params.getAll(key).length > 1) return { reason: "malformed_response" };
|
|
1885
|
+
}
|
|
1886
|
+
const state = params.get("state");
|
|
1887
|
+
const code = params.get("code");
|
|
1888
|
+
const error2 = params.get("error");
|
|
1889
|
+
const errorDescription = params.get("error_description");
|
|
1890
|
+
const issuer = params.get("iss");
|
|
1891
|
+
if (!state || state.length > 2048 || Boolean(code) === Boolean(error2) || code !== null && (!code || code.length > 8192) || error2 !== null && (!error2 || error2.length > 256) || errorDescription !== null && (!error2 || errorDescription.length > 2048) || issuer !== null && (!issuer || issuer.length > 2048)) {
|
|
1892
|
+
return { reason: "malformed_response" };
|
|
1587
1893
|
}
|
|
1588
1894
|
return {
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1895
|
+
callback: {
|
|
1896
|
+
state,
|
|
1897
|
+
...code === null ? {} : { code },
|
|
1898
|
+
...error2 === null ? {} : { error: error2 },
|
|
1899
|
+
...errorDescription === null ? {} : { error_description: errorDescription },
|
|
1900
|
+
...issuer === null ? {} : { iss: issuer }
|
|
1901
|
+
}
|
|
1593
1902
|
};
|
|
1594
1903
|
}
|
|
1595
|
-
function
|
|
1904
|
+
function reportProgress(options, event, message, details = {}) {
|
|
1905
|
+
if (options.json) {
|
|
1906
|
+
console.error(JSON.stringify({ event, ...details }));
|
|
1907
|
+
} else {
|
|
1908
|
+
console.error(message);
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
function rejectCallback(response, options, reason) {
|
|
1912
|
+
rejectedCallbackResponse(response, 400);
|
|
1913
|
+
reportProgress(options, "callback_rejected", callbackRejectionMessage(reason), {
|
|
1914
|
+
reason,
|
|
1915
|
+
action: "still_waiting"
|
|
1916
|
+
});
|
|
1917
|
+
}
|
|
1918
|
+
function callbackRejectionMessage(reason) {
|
|
1919
|
+
switch (reason) {
|
|
1920
|
+
case "malformed_response":
|
|
1921
|
+
return "The callback had a malformed response; authorization is still waiting for a valid response. Retry authorization if needed.";
|
|
1922
|
+
case "state_mismatch":
|
|
1923
|
+
return "The callback had a state mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
|
|
1924
|
+
case "issuer_missing":
|
|
1925
|
+
return "The callback was missing its issuer; authorization is still waiting for a valid response. Update the provider or retry authorization.";
|
|
1926
|
+
case "issuer_mismatch":
|
|
1927
|
+
return "The callback had an issuer mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
|
|
1928
|
+
case "issuer_unavailable":
|
|
1929
|
+
return "The Evident endpoint has issuer validation unavailable; authorization is still waiting for a valid response. Update the endpoint or start a new authorization.";
|
|
1930
|
+
case "attempt_not_ready":
|
|
1931
|
+
return "The authorization attempt is not ready yet; authorization is still waiting for a valid response while Evident finishes starting it.";
|
|
1932
|
+
case "attempt_expired":
|
|
1933
|
+
return "The authorization attempt expired; authorization is still waiting for a valid response. Start a new authorization.";
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
function handleCallbackRequest(request3, response, waiter, options, page) {
|
|
1937
|
+
if (handleStatusRequest(request3, response, page)) return;
|
|
1596
1938
|
if (!request3.url || !request3.url.startsWith("/") || !URL.canParse(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`)) {
|
|
1597
|
-
|
|
1939
|
+
rejectCallback(response, options, "malformed_response");
|
|
1598
1940
|
return;
|
|
1599
1941
|
}
|
|
1600
1942
|
const pathname = new URL(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`).pathname;
|
|
1601
1943
|
if (pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path) {
|
|
1602
|
-
|
|
1944
|
+
rejectedCallbackResponse(response, 404);
|
|
1603
1945
|
return;
|
|
1604
1946
|
}
|
|
1605
1947
|
if (request3.method !== "GET") {
|
|
1606
1948
|
response.setHeader("Allow", "GET");
|
|
1607
|
-
|
|
1949
|
+
rejectedCallbackResponse(response, 405);
|
|
1608
1950
|
return;
|
|
1609
1951
|
}
|
|
1610
1952
|
if (waiter.accepted) {
|
|
1611
|
-
|
|
1953
|
+
rejectedCallbackResponse(response, 409);
|
|
1954
|
+
return;
|
|
1955
|
+
}
|
|
1956
|
+
const parsed = parseCallbackRequest(request3);
|
|
1957
|
+
if (!("callback" in parsed)) {
|
|
1958
|
+
rejectCallback(response, options, parsed.reason);
|
|
1612
1959
|
return;
|
|
1613
1960
|
}
|
|
1614
|
-
const callback =
|
|
1615
|
-
|
|
1616
|
-
|
|
1961
|
+
const callback = parsed.callback;
|
|
1962
|
+
const expiresAtMs = waiter.expiresAtMs;
|
|
1963
|
+
let rejectionReason;
|
|
1964
|
+
if (expiresAtMs === void 0) {
|
|
1965
|
+
rejectionReason = "attempt_not_ready";
|
|
1966
|
+
} else if (Date.now() >= expiresAtMs) {
|
|
1967
|
+
rejectionReason = "attempt_expired";
|
|
1968
|
+
} else if (!waiter.expectedState || callback.state !== waiter.expectedState) {
|
|
1969
|
+
rejectionReason = "state_mismatch";
|
|
1970
|
+
} else if (waiter.issuerParameterSupported && callback.iss === void 0) {
|
|
1971
|
+
rejectionReason = "issuer_missing";
|
|
1972
|
+
} else if (callback.iss !== void 0 && waiter.expectedIssuer === void 0) {
|
|
1973
|
+
rejectionReason = "issuer_unavailable";
|
|
1974
|
+
} else if (callback.iss !== void 0 && callback.iss !== waiter.expectedIssuer) {
|
|
1975
|
+
rejectionReason = "issuer_mismatch";
|
|
1976
|
+
}
|
|
1977
|
+
if (rejectionReason) {
|
|
1978
|
+
rejectCallback(response, options, rejectionReason);
|
|
1617
1979
|
return;
|
|
1618
1980
|
}
|
|
1619
1981
|
waiter.accepted = true;
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1982
|
+
page.phase = "received";
|
|
1983
|
+
reportProgress(options, "callback_received", "Provider sign-in response received.");
|
|
1984
|
+
const callbackPageResponse = callbackPage(`/_status/${page.capability}`);
|
|
1985
|
+
callbackResponse(
|
|
1986
|
+
response,
|
|
1987
|
+
200,
|
|
1988
|
+
callbackPageResponse.html,
|
|
1989
|
+
callbackPageResponse.nonce,
|
|
1990
|
+
() => waiter.resolve?.(callback)
|
|
1991
|
+
);
|
|
1627
1992
|
}
|
|
1628
1993
|
function listen(server, port) {
|
|
1629
1994
|
return new Promise((resolve6, reject) => {
|
|
@@ -1643,8 +2008,10 @@ function listen(server, port) {
|
|
|
1643
2008
|
function isAddressInUse(error2) {
|
|
1644
2009
|
return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EADDRINUSE";
|
|
1645
2010
|
}
|
|
1646
|
-
async function bindCallbackListener(waiter) {
|
|
1647
|
-
const createListener = () => createServer(
|
|
2011
|
+
async function bindCallbackListener(waiter, options, page) {
|
|
2012
|
+
const createListener = () => createServer(
|
|
2013
|
+
(request3, response) => handleCallbackRequest(request3, response, waiter, options, page)
|
|
2014
|
+
);
|
|
1648
2015
|
try {
|
|
1649
2016
|
const server2 = createListener();
|
|
1650
2017
|
return { server: server2, port: await listen(server2, MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) };
|
|
@@ -1737,6 +2104,14 @@ function completionFailureMessage(reason) {
|
|
|
1737
2104
|
return "This sign-in was already used. Start a new authorization.";
|
|
1738
2105
|
case "state_expired":
|
|
1739
2106
|
return "This sign-in attempt expired. Start a new authorization.";
|
|
2107
|
+
case "issuer_unavailable":
|
|
2108
|
+
return "This sign-in attempt predates issuer validation. Start a new authorization.";
|
|
2109
|
+
case "issuer_missing":
|
|
2110
|
+
return "The provider response did not include its required issuer. Start a new authorization and update the CLI if needed.";
|
|
2111
|
+
case "issuer_mismatch":
|
|
2112
|
+
return "The provider response came from an unexpected issuer. Start a new authorization and contact support if it continues.";
|
|
2113
|
+
case "invalid_response":
|
|
2114
|
+
return "The provider returned an invalid sign-in response. Start a new authorization.";
|
|
1740
2115
|
case "provider_denied":
|
|
1741
2116
|
return "The provider denied the sign-in. Retry and approve the requested access.";
|
|
1742
2117
|
case "provider_error":
|
|
@@ -1760,20 +2135,21 @@ function printLink(options, url, reason) {
|
|
|
1760
2135
|
printWarning(reason ?? "Open this authorization URL in your browser:");
|
|
1761
2136
|
console.log(url.href);
|
|
1762
2137
|
}
|
|
1763
|
-
function printResult(options, proxyId, connectionId, error2) {
|
|
2138
|
+
function printResult(options, proxyId, connectionId, error2, successMessage = "MCP connection authorized.", reason) {
|
|
1764
2139
|
if (options.json) {
|
|
1765
2140
|
console.log(
|
|
1766
2141
|
JSON.stringify({
|
|
1767
2142
|
ok: !error2,
|
|
1768
2143
|
proxy_id: proxyId,
|
|
1769
2144
|
connection_id: connectionId,
|
|
1770
|
-
...error2 ? { error: error2 } : {}
|
|
2145
|
+
...error2 ? { error: error2 } : {},
|
|
2146
|
+
...reason ? { reason } : {}
|
|
1771
2147
|
})
|
|
1772
2148
|
);
|
|
1773
2149
|
} else if (error2) {
|
|
1774
2150
|
printError(error2);
|
|
1775
2151
|
} else {
|
|
1776
|
-
printSuccess(
|
|
2152
|
+
printSuccess(successMessage);
|
|
1777
2153
|
}
|
|
1778
2154
|
}
|
|
1779
2155
|
function errorMessage(error2) {
|
|
@@ -1796,12 +2172,32 @@ function validateConnectionList(value) {
|
|
|
1796
2172
|
return value.mcp_proxy_connections;
|
|
1797
2173
|
}
|
|
1798
2174
|
function validateBeginResponse(value) {
|
|
1799
|
-
if (!value || typeof value.authorization_url !== "string" || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at))) {
|
|
2175
|
+
if (!value || typeof value.authorization_url !== "string" || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at)) || value.issuer !== void 0 && (typeof value.issuer !== "string" || value.issuer.length === 0 || value.issuer.length > 2048) || value.authorization_response_iss_parameter_supported !== void 0 && typeof value.authorization_response_iss_parameter_supported !== "boolean" || value.issuer === void 0 !== (value.authorization_response_iss_parameter_supported === void 0)) {
|
|
1800
2176
|
throw new Error(
|
|
1801
2177
|
"Evident returned an invalid local authorization attempt. Update the CLI and retry."
|
|
1802
2178
|
);
|
|
1803
2179
|
}
|
|
1804
2180
|
}
|
|
2181
|
+
async function startBrowser(url) {
|
|
2182
|
+
const child = await open2(url);
|
|
2183
|
+
let signalFailure = () => void 0;
|
|
2184
|
+
const failure = new Promise((resolve6) => {
|
|
2185
|
+
signalFailure = resolve6;
|
|
2186
|
+
});
|
|
2187
|
+
child.once("error", signalFailure);
|
|
2188
|
+
child.once("close", (code) => {
|
|
2189
|
+
if (code !== 0) signalFailure();
|
|
2190
|
+
});
|
|
2191
|
+
await new Promise((resolve6, reject) => {
|
|
2192
|
+
if (child.pid !== void 0) {
|
|
2193
|
+
resolve6();
|
|
2194
|
+
return;
|
|
2195
|
+
}
|
|
2196
|
+
child.once("spawn", resolve6);
|
|
2197
|
+
child.once("error", reject);
|
|
2198
|
+
});
|
|
2199
|
+
return { failure };
|
|
2200
|
+
}
|
|
1805
2201
|
function closeServer(server, force) {
|
|
1806
2202
|
if (!server.listening) return Promise.resolve();
|
|
1807
2203
|
return new Promise((resolve6, reject) => {
|
|
@@ -1845,10 +2241,17 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1845
2241
|
return;
|
|
1846
2242
|
}
|
|
1847
2243
|
const waiter = { accepted: false };
|
|
2244
|
+
const page = {
|
|
2245
|
+
capability: randomBytes(32).toString("base64url"),
|
|
2246
|
+
phase: "waiting",
|
|
2247
|
+
terminalRead: false
|
|
2248
|
+
};
|
|
1848
2249
|
let server;
|
|
1849
2250
|
let closePromise;
|
|
1850
2251
|
let closeFailureLogged = false;
|
|
1851
2252
|
let failure;
|
|
2253
|
+
let successMessage = "MCP connection authorized.";
|
|
2254
|
+
let completionReason;
|
|
1852
2255
|
const cancelController = new AbortController();
|
|
1853
2256
|
const closeListener = (force = false) => {
|
|
1854
2257
|
if (!server || closePromise) return closePromise ?? Promise.resolve();
|
|
@@ -1865,15 +2268,23 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1865
2268
|
});
|
|
1866
2269
|
};
|
|
1867
2270
|
try {
|
|
1868
|
-
const listener = await bindCallbackListener(waiter);
|
|
2271
|
+
const listener = await bindCallbackListener(waiter, options, page);
|
|
1869
2272
|
server = listener.server;
|
|
1870
2273
|
process.once("SIGINT", onSigint);
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
2274
|
+
page.host = `${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}`;
|
|
2275
|
+
page.origin = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${page.host}`;
|
|
2276
|
+
const redirectUri = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}${MCP_LOOPBACK_REDIRECT_POLICY.path}`;
|
|
2277
|
+
const fallback = listener.port !== MCP_LOOPBACK_REDIRECT_POLICY.preferred_port;
|
|
2278
|
+
reportProgress(
|
|
2279
|
+
options,
|
|
2280
|
+
fallback ? "listener_fallback" : "listener_ready",
|
|
2281
|
+
fallback ? `Port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} is busy; listening at ${redirectUri}.` : `Listening for the sign-in response at ${redirectUri}.`,
|
|
2282
|
+
{
|
|
2283
|
+
callback_url: redirectUri,
|
|
2284
|
+
...fallback ? { preferred_port: MCP_LOOPBACK_REDIRECT_POLICY.preferred_port } : {},
|
|
2285
|
+
port: listener.port
|
|
2286
|
+
}
|
|
2287
|
+
);
|
|
1877
2288
|
const connectionList = await requestJson(
|
|
1878
2289
|
apiPath(proxyId),
|
|
1879
2290
|
credentials2,
|
|
@@ -1891,7 +2302,7 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1891
2302
|
if (connection.auth_kind !== "oauth2") {
|
|
1892
2303
|
throw new Error("This MCP connection does not support OAuth authorization.");
|
|
1893
2304
|
}
|
|
1894
|
-
|
|
2305
|
+
reportProgress(options, "authorization_starting", "Starting authorization with Evident.");
|
|
1895
2306
|
const begin = await requestJson(
|
|
1896
2307
|
apiPath(proxyId, connectionId, "begin"),
|
|
1897
2308
|
credentials2,
|
|
@@ -1902,6 +2313,8 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1902
2313
|
validateBeginResponse(begin);
|
|
1903
2314
|
const { url: authorizationUrl, state } = authorizationState(begin.authorization_url);
|
|
1904
2315
|
waiter.expectedState = state;
|
|
2316
|
+
waiter.expectedIssuer = begin.issuer;
|
|
2317
|
+
waiter.issuerParameterSupported = begin.authorization_response_iss_parameter_supported;
|
|
1905
2318
|
const expiresAtMs = Date.parse(begin.expires_at);
|
|
1906
2319
|
if (expiresAtMs <= Date.now()) throw new CallbackExpiredError();
|
|
1907
2320
|
waiter.expiresAtMs = expiresAtMs;
|
|
@@ -1909,16 +2322,31 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1909
2322
|
(callback2) => ({ ok: true, callback: callback2 }),
|
|
1910
2323
|
(error2) => ({ ok: false, error: error2 })
|
|
1911
2324
|
);
|
|
2325
|
+
const waitForCallbackWithProgress = (linkReason) => {
|
|
2326
|
+
if (linkReason) printLink(options, authorizationUrl, linkReason);
|
|
2327
|
+
reportProgress(
|
|
2328
|
+
options,
|
|
2329
|
+
"waiting_for_callback",
|
|
2330
|
+
"Waiting for the provider to return to this computer."
|
|
2331
|
+
);
|
|
2332
|
+
return (async () => {
|
|
2333
|
+
const outcome = await callbackOutcome;
|
|
2334
|
+
if (!outcome.ok) requestFailed(outcome.error);
|
|
2335
|
+
return outcome.callback;
|
|
2336
|
+
})();
|
|
2337
|
+
};
|
|
1912
2338
|
let callback;
|
|
1913
2339
|
if (options.noBrowser) {
|
|
1914
|
-
|
|
1915
|
-
const outcome = await callbackOutcome;
|
|
1916
|
-
if (!outcome.ok) requestFailed(outcome.error);
|
|
1917
|
-
callback = outcome.callback;
|
|
2340
|
+
callback = await waitForCallbackWithProgress("Open this authorization URL in your browser:");
|
|
1918
2341
|
} else {
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
2342
|
+
reportProgress(
|
|
2343
|
+
options,
|
|
2344
|
+
"opening_browser",
|
|
2345
|
+
"Opening the provider authorization page in your browser."
|
|
2346
|
+
);
|
|
2347
|
+
const browserOutcome = startBrowser(authorizationUrl.href).then(
|
|
2348
|
+
({ failure: browserFailure }) => ({ ok: true, failure: browserFailure }),
|
|
2349
|
+
() => ({ ok: false })
|
|
1922
2350
|
);
|
|
1923
2351
|
const first = await Promise.race([
|
|
1924
2352
|
browserOutcome.then((outcome) => ({ kind: "browser", outcome })),
|
|
@@ -1929,24 +2357,43 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1929
2357
|
callback = first.outcome.callback;
|
|
1930
2358
|
} else {
|
|
1931
2359
|
if (!first.outcome.ok) {
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
options,
|
|
1935
|
-
authorizationUrl,
|
|
1936
|
-
`Could not open the browser automatically${detail}. Open this URL:`
|
|
2360
|
+
callback = await waitForCallbackWithProgress(
|
|
2361
|
+
"Could not open the browser automatically. Open this URL:"
|
|
1937
2362
|
);
|
|
2363
|
+
} else {
|
|
2364
|
+
const callbackWait = waitForCallbackWithProgress();
|
|
2365
|
+
const waitOutcome = await Promise.race([
|
|
2366
|
+
callbackWait.then(
|
|
2367
|
+
(value) => ({ kind: "callback", value }),
|
|
2368
|
+
(error2) => ({ kind: "callback_error", error: error2 })
|
|
2369
|
+
),
|
|
2370
|
+
first.outcome.failure.then(() => ({ kind: "browser_failure" }))
|
|
2371
|
+
]);
|
|
2372
|
+
if (waitOutcome.kind === "callback") {
|
|
2373
|
+
callback = waitOutcome.value;
|
|
2374
|
+
} else if (waitOutcome.kind === "callback_error") {
|
|
2375
|
+
requestFailed(waitOutcome.error);
|
|
2376
|
+
} else {
|
|
2377
|
+
printLink(
|
|
2378
|
+
options,
|
|
2379
|
+
authorizationUrl,
|
|
2380
|
+
"The browser could not keep the authorization page open. Open this URL:"
|
|
2381
|
+
);
|
|
2382
|
+
callback = await callbackWait;
|
|
2383
|
+
}
|
|
1938
2384
|
}
|
|
1939
|
-
const outcome = await callbackOutcome;
|
|
1940
|
-
if (!outcome.ok) requestFailed(outcome.error);
|
|
1941
|
-
callback = outcome.callback;
|
|
1942
2385
|
}
|
|
1943
2386
|
}
|
|
2387
|
+
reportProgress(options, "forwarding_callback", "Forwarding the sign-in response to Evident.");
|
|
1944
2388
|
const completionBody = {
|
|
1945
2389
|
state: callback.state,
|
|
1946
2390
|
...callback.code === void 0 ? {} : { code: callback.code },
|
|
1947
2391
|
...callback.error === void 0 ? {} : { error: callback.error },
|
|
1948
|
-
...callback.error_description === void 0 ? {} : { error_description: callback.error_description }
|
|
2392
|
+
...callback.error_description === void 0 ? {} : { error_description: callback.error_description },
|
|
2393
|
+
...callback.iss === void 0 ? {} : { iss: callback.iss }
|
|
1949
2394
|
};
|
|
2395
|
+
reportProgress(options, "completing_authorization", "Completing authorization with Evident.");
|
|
2396
|
+
page.phase = "completing";
|
|
1950
2397
|
const completion = await requestJson(
|
|
1951
2398
|
apiPath(proxyId, connectionId, "complete"),
|
|
1952
2399
|
credentials2,
|
|
@@ -1954,12 +2401,36 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1954
2401
|
"completing local authorization",
|
|
1955
2402
|
completionBody
|
|
1956
2403
|
);
|
|
1957
|
-
if (completion.outcome
|
|
2404
|
+
if (completion.outcome === "success") {
|
|
2405
|
+
if (completion.reason === "tools_pending") {
|
|
2406
|
+
completionReason = completion.reason;
|
|
2407
|
+
page.phase = "tools_pending";
|
|
2408
|
+
reportProgress(
|
|
2409
|
+
options,
|
|
2410
|
+
"tools_pending",
|
|
2411
|
+
"Authorization confirmed; Evident is still preparing its tools."
|
|
2412
|
+
);
|
|
2413
|
+
successMessage = "MCP connection authorized. Evident is still preparing its tools.";
|
|
2414
|
+
} else {
|
|
2415
|
+
page.phase = "success";
|
|
2416
|
+
}
|
|
2417
|
+
} else {
|
|
2418
|
+
page.phase = "failed";
|
|
2419
|
+
failure = completionFailureMessage(completion.reason);
|
|
2420
|
+
}
|
|
1958
2421
|
} catch (error2) {
|
|
1959
|
-
|
|
2422
|
+
if (waiter.accepted && !isTerminalPagePhase(page.phase)) {
|
|
2423
|
+
page.phase = "unconfirmed";
|
|
2424
|
+
failure = `${COMPLETION_UNCONFIRMED_MESSAGE} ${errorMessage(error2)}`;
|
|
2425
|
+
} else {
|
|
2426
|
+
failure = errorMessage(error2);
|
|
2427
|
+
}
|
|
1960
2428
|
} finally {
|
|
1961
|
-
process.removeListener("SIGINT", onSigint);
|
|
1962
2429
|
try {
|
|
2430
|
+
if (waiter.accepted && isTerminalPagePhase(page.phase) && !cancelController.signal.aborted) {
|
|
2431
|
+
await waitForTerminalStatusRead(page, cancelController.signal);
|
|
2432
|
+
}
|
|
2433
|
+
process.removeListener("SIGINT", onSigint);
|
|
1963
2434
|
await closeListener();
|
|
1964
2435
|
} catch (error2) {
|
|
1965
2436
|
const detail = error2 instanceof Error ? error2.message : String(error2);
|
|
@@ -1971,11 +2442,12 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
|
|
|
1971
2442
|
failure ??= "The local callback listener could not be closed cleanly. Check for a lingering process and retry.";
|
|
1972
2443
|
}
|
|
1973
2444
|
}
|
|
1974
|
-
printResult(options, proxyId, connectionId, failure);
|
|
2445
|
+
printResult(options, proxyId, connectionId, failure, successMessage, completionReason);
|
|
1975
2446
|
if (failure) process.exitCode = cancelController.signal.aborted ? 130 : 1;
|
|
1976
2447
|
}
|
|
1977
2448
|
|
|
1978
2449
|
// src/commands/run.ts
|
|
2450
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1979
2451
|
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
|
|
1980
2452
|
import { homedir as homedir9 } from "node:os";
|
|
1981
2453
|
import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
|
|
@@ -1984,7 +2456,7 @@ import ora4 from "ora";
|
|
|
1984
2456
|
import { select as select4 } from "@inquirer/prompts";
|
|
1985
2457
|
|
|
1986
2458
|
// src/lib/telemetry.ts
|
|
1987
|
-
var CLI_VERSION = (true ? "3.6.1-dev.
|
|
2459
|
+
var CLI_VERSION = (true ? "3.6.1-dev.a6e5986" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
1988
2460
|
function getCliVersion() {
|
|
1989
2461
|
return CLI_VERSION;
|
|
1990
2462
|
}
|
|
@@ -3827,7 +4299,7 @@ function isRecord3(value) {
|
|
|
3827
4299
|
}
|
|
3828
4300
|
function isWatermark(value) {
|
|
3829
4301
|
if (!isRecord3(value)) return false;
|
|
3830
|
-
return typeof value.fingerprint === "string" && typeof value.uploaded_at === "string" && typeof value.key === "string" && (!("conversation_id" in value) || value.conversation_id === null || typeof value.conversation_id === "string");
|
|
4302
|
+
return typeof value.fingerprint === "string" && typeof value.uploaded_at === "string" && typeof value.key === "string" && (!("conversation_id" in value) || value.conversation_id === null || typeof value.conversation_id === "string") && (!("version_id" in value) || value.version_id === null || typeof value.version_id === "string") && (!("etag" in value) || value.etag === null || typeof value.etag === "string");
|
|
3831
4303
|
}
|
|
3832
4304
|
function isMissingFile3(error2) {
|
|
3833
4305
|
return error2 instanceof Error && "code" in error2 && error2.code === "ENOENT";
|
|
@@ -4008,6 +4480,37 @@ function isJson(body) {
|
|
|
4008
4480
|
return false;
|
|
4009
4481
|
}
|
|
4010
4482
|
}
|
|
4483
|
+
function parseArchivePutMetadata(stderr, onMetadataDecodeError) {
|
|
4484
|
+
const prefix = "ARCHIVE-PUT: outcome=ok ";
|
|
4485
|
+
const lines = stderr.split(/\r?\n/);
|
|
4486
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
4487
|
+
const line = lines[index];
|
|
4488
|
+
if (line === void 0) continue;
|
|
4489
|
+
const prefixIndex = line.indexOf(prefix);
|
|
4490
|
+
if (prefixIndex === -1) continue;
|
|
4491
|
+
const record = line.slice(prefixIndex + prefix.length);
|
|
4492
|
+
const versionMatch = /(?:^|\s)version_id=(\S*)/.exec(record);
|
|
4493
|
+
const etagMatch = /(?:^|\s)etag=(\S*)/.exec(record);
|
|
4494
|
+
const decode = (value, field) => {
|
|
4495
|
+
if (value === void 0 || value === "") return null;
|
|
4496
|
+
try {
|
|
4497
|
+
return decodeURIComponent(value);
|
|
4498
|
+
} catch (error2) {
|
|
4499
|
+
onMetadataDecodeError?.(
|
|
4500
|
+
field,
|
|
4501
|
+
error2 instanceof URIError ? "uri-malformed" : "decode-failed"
|
|
4502
|
+
);
|
|
4503
|
+
return null;
|
|
4504
|
+
}
|
|
4505
|
+
};
|
|
4506
|
+
return {
|
|
4507
|
+
metadataReported: versionMatch !== null || etagMatch !== null,
|
|
4508
|
+
versionId: decode(versionMatch?.[1], "version_id"),
|
|
4509
|
+
etag: decode(etagMatch?.[1], "etag")
|
|
4510
|
+
};
|
|
4511
|
+
}
|
|
4512
|
+
return { metadataReported: false, versionId: null, etag: null };
|
|
4513
|
+
}
|
|
4011
4514
|
async function uploadSessionArchive(key, body, options) {
|
|
4012
4515
|
const bytes = Buffer.from(body);
|
|
4013
4516
|
if (bytes.byteLength > MAX_SESSION_ARCHIVE_BYTES) {
|
|
@@ -4030,7 +4533,13 @@ async function uploadSessionArchive(key, body, options) {
|
|
|
4030
4533
|
);
|
|
4031
4534
|
}
|
|
4032
4535
|
if (result.timedOut) return transportFailure(bytes.byteLength, "timeout");
|
|
4033
|
-
if (result.code === 0)
|
|
4536
|
+
if (result.code === 0) {
|
|
4537
|
+
return {
|
|
4538
|
+
kind: "ok",
|
|
4539
|
+
bytes: bytes.byteLength,
|
|
4540
|
+
...parseArchivePutMetadata(result.stderr, options.onMetadataDecodeError)
|
|
4541
|
+
};
|
|
4542
|
+
}
|
|
4034
4543
|
if (result.code === EXIT_ARCHIVE_CONFIG_MISSING) {
|
|
4035
4544
|
return { kind: "config-missing", bytes: bytes.byteLength };
|
|
4036
4545
|
}
|
|
@@ -4248,6 +4757,14 @@ async function runSessionArchive({
|
|
|
4248
4757
|
uploadFailures: 0,
|
|
4249
4758
|
skippedBudget: 0,
|
|
4250
4759
|
skippedBudgetIds: [],
|
|
4760
|
+
skippedChanged: 0,
|
|
4761
|
+
skippedChangedSessions: [],
|
|
4762
|
+
skippedUnknown: 0,
|
|
4763
|
+
skippedUnknownIds: [],
|
|
4764
|
+
inventoryNeverArchived: 0,
|
|
4765
|
+
inventoryPriorFailures: 0,
|
|
4766
|
+
inventoryKnownChanged: 0,
|
|
4767
|
+
outcomesReconciled: false,
|
|
4251
4768
|
neverWatermarkedFailures: 0,
|
|
4252
4769
|
unmappedIds: [],
|
|
4253
4770
|
conflictedIds: [],
|
|
@@ -4264,6 +4781,8 @@ async function runSessionArchive({
|
|
|
4264
4781
|
parent: 0
|
|
4265
4782
|
},
|
|
4266
4783
|
archivedSessionIds: [],
|
|
4784
|
+
uploadedSessions: [],
|
|
4785
|
+
unchangedSessions: [],
|
|
4267
4786
|
failures: [],
|
|
4268
4787
|
staleSince: null
|
|
4269
4788
|
};
|
|
@@ -4287,17 +4806,44 @@ async function runSessionArchive({
|
|
|
4287
4806
|
}
|
|
4288
4807
|
summary.unresolved = summary.unmappedIds.length + summary.conflictedIds.length;
|
|
4289
4808
|
summary.conflicts = summary.conflictedIds.length;
|
|
4809
|
+
const priorFailureIds = deps.priorFailureIds ?? /* @__PURE__ */ new Set();
|
|
4810
|
+
const knownChanged = /* @__PURE__ */ new Map();
|
|
4811
|
+
for (const session of sessions) {
|
|
4812
|
+
if (!deps.watermarks.has(session.id)) {
|
|
4813
|
+
knownChanged.set(session.id, "no-prior-archive");
|
|
4814
|
+
summary.inventoryNeverArchived++;
|
|
4815
|
+
} else if (priorFailureIds.has(session.id)) {
|
|
4816
|
+
knownChanged.set(session.id, "prior-attempt-failed");
|
|
4817
|
+
summary.inventoryPriorFailures++;
|
|
4818
|
+
}
|
|
4819
|
+
}
|
|
4820
|
+
summary.inventoryKnownChanged = knownChanged.size;
|
|
4290
4821
|
const failedWatermarks = [];
|
|
4822
|
+
const priorFailureUploads = [];
|
|
4291
4823
|
const recordFailedWatermark = (watermark) => {
|
|
4292
4824
|
if (watermark) failedWatermarks.push(watermark.uploaded_at);
|
|
4293
4825
|
else summary.neverWatermarkedFailures++;
|
|
4294
4826
|
};
|
|
4827
|
+
const recordBudgetSkip = (startIndex) => {
|
|
4828
|
+
const skippedIds = ordered.slice(startIndex).map(({ id }) => id);
|
|
4829
|
+
summary.skippedBudgetIds.push(...skippedIds);
|
|
4830
|
+
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4831
|
+
for (const sessionId of skippedIds) {
|
|
4832
|
+
const reason = knownChanged.get(sessionId);
|
|
4833
|
+
if (reason) {
|
|
4834
|
+
summary.skippedChangedSessions.push({ sessionId, reason });
|
|
4835
|
+
summary.skippedChanged++;
|
|
4836
|
+
} else {
|
|
4837
|
+
summary.skippedUnknownIds.push(sessionId);
|
|
4838
|
+
summary.skippedUnknown++;
|
|
4839
|
+
}
|
|
4840
|
+
}
|
|
4841
|
+
};
|
|
4295
4842
|
for (let index = 0; index < ordered.length; index++) {
|
|
4296
4843
|
const session = ordered[index];
|
|
4297
4844
|
const remainingMs = Math.floor(deadline - now());
|
|
4298
4845
|
if (remainingMs <= 0 || deps.signal?.aborted) {
|
|
4299
|
-
|
|
4300
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4846
|
+
recordBudgetSkip(index);
|
|
4301
4847
|
break;
|
|
4302
4848
|
}
|
|
4303
4849
|
const resolution = resolutions.get(session.id) ?? { reason: "unmapped" };
|
|
@@ -4322,8 +4868,7 @@ async function runSessionArchive({
|
|
|
4322
4868
|
messages = await exportMessages(deps.client, session.id, exportBudget.signal);
|
|
4323
4869
|
} catch (error2) {
|
|
4324
4870
|
if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
|
|
4325
|
-
|
|
4326
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4871
|
+
recordBudgetSkip(index);
|
|
4327
4872
|
break;
|
|
4328
4873
|
}
|
|
4329
4874
|
summary.failed++;
|
|
@@ -4341,8 +4886,7 @@ async function runSessionArchive({
|
|
|
4341
4886
|
exportBudget.dispose();
|
|
4342
4887
|
}
|
|
4343
4888
|
if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
|
|
4344
|
-
|
|
4345
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4889
|
+
recordBudgetSkip(index);
|
|
4346
4890
|
break;
|
|
4347
4891
|
}
|
|
4348
4892
|
try {
|
|
@@ -4361,12 +4905,21 @@ async function runSessionArchive({
|
|
|
4361
4905
|
if (existing?.fingerprint === snapshot.content_fingerprint) {
|
|
4362
4906
|
summary.unchanged++;
|
|
4363
4907
|
summary.archivedSessionIds.push(session.id);
|
|
4908
|
+
summary.unchangedSessions.push({
|
|
4909
|
+
sessionId: session.id,
|
|
4910
|
+
fingerprint: snapshot.content_fingerprint,
|
|
4911
|
+
watermarkKey: existing.key,
|
|
4912
|
+
watermarkFingerprint: existing.fingerprint,
|
|
4913
|
+
watermarkVersionId: existing.version_id ?? null,
|
|
4914
|
+
watermarkEtag: existing.etag ?? null,
|
|
4915
|
+
watermarkUploadedAt: existing.uploaded_at
|
|
4916
|
+
});
|
|
4364
4917
|
continue;
|
|
4365
4918
|
}
|
|
4366
4919
|
const uploadRemainingMs = Math.floor(deadline - now());
|
|
4367
4920
|
if (uploadRemainingMs <= 0 || deps.signal?.aborted) {
|
|
4368
|
-
|
|
4369
|
-
|
|
4921
|
+
knownChanged.set(session.id, "fingerprint-differs");
|
|
4922
|
+
recordBudgetSkip(index);
|
|
4370
4923
|
break;
|
|
4371
4924
|
}
|
|
4372
4925
|
summary.uploadAttempts++;
|
|
@@ -4375,7 +4928,8 @@ async function runSessionArchive({
|
|
|
4375
4928
|
try {
|
|
4376
4929
|
outcome = await upload(key, JSON.stringify(snapshot), {
|
|
4377
4930
|
timeoutMs: Math.min(uploadRemainingMs, SESSION_ARCHIVE_UPLOAD_TIMEOUT_MS),
|
|
4378
|
-
signal: uploadBudget.signal
|
|
4931
|
+
signal: uploadBudget.signal,
|
|
4932
|
+
onMetadataDecodeError: (field, reason) => deps.onMetadataDecodeError?.(field, reason, session.id)
|
|
4379
4933
|
});
|
|
4380
4934
|
} finally {
|
|
4381
4935
|
uploadBudget.dispose();
|
|
@@ -4398,19 +4952,31 @@ async function runSessionArchive({
|
|
|
4398
4952
|
});
|
|
4399
4953
|
recordFailedWatermark(existing);
|
|
4400
4954
|
if (uploadBudget.signal.aborted) {
|
|
4401
|
-
|
|
4402
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4955
|
+
recordBudgetSkip(index + 1);
|
|
4403
4956
|
break;
|
|
4404
4957
|
}
|
|
4405
4958
|
continue;
|
|
4406
4959
|
}
|
|
4407
4960
|
summary.uploaded++;
|
|
4408
4961
|
summary.archivedSessionIds.push(session.id);
|
|
4962
|
+
const uploadRecord = {
|
|
4963
|
+
sessionId: session.id,
|
|
4964
|
+
key,
|
|
4965
|
+
fingerprint: snapshot.content_fingerprint,
|
|
4966
|
+
versionId: outcome.versionId,
|
|
4967
|
+
etag: outcome.etag,
|
|
4968
|
+
metadataReported: outcome.metadataReported,
|
|
4969
|
+
retriedPriorFailure: priorFailureIds.has(session.id)
|
|
4970
|
+
};
|
|
4971
|
+
if (uploadRecord.retriedPriorFailure) priorFailureUploads.push(uploadRecord);
|
|
4972
|
+
else summary.uploadedSessions.push(uploadRecord);
|
|
4409
4973
|
const watermark = {
|
|
4410
4974
|
fingerprint: snapshot.content_fingerprint,
|
|
4411
4975
|
uploaded_at: new Date(now()).toISOString(),
|
|
4412
4976
|
key,
|
|
4413
|
-
conversation_id: conversationId
|
|
4977
|
+
conversation_id: conversationId,
|
|
4978
|
+
version_id: outcome.versionId,
|
|
4979
|
+
etag: outcome.etag
|
|
4414
4980
|
};
|
|
4415
4981
|
try {
|
|
4416
4982
|
writeWatermark(deps.watermarkPath, session.id, watermark, deps.watermarks);
|
|
@@ -4424,8 +4990,7 @@ async function runSessionArchive({
|
|
|
4424
4990
|
}
|
|
4425
4991
|
} catch (error2) {
|
|
4426
4992
|
if (isBudgetExpired(deadline, now, deps.signal)) {
|
|
4427
|
-
|
|
4428
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4993
|
+
recordBudgetSkip(index);
|
|
4429
4994
|
break;
|
|
4430
4995
|
}
|
|
4431
4996
|
summary.failed++;
|
|
@@ -4438,10 +5003,115 @@ async function runSessionArchive({
|
|
|
4438
5003
|
recordFailedWatermark(deps.watermarks.get(session.id));
|
|
4439
5004
|
}
|
|
4440
5005
|
}
|
|
5006
|
+
summary.uploadedSessions = [...priorFailureUploads, ...summary.uploadedSessions];
|
|
5007
|
+
for (const sessionId of summary.archivedSessionIds) priorFailureIds.delete(sessionId);
|
|
5008
|
+
for (const failure of summary.failures) {
|
|
5009
|
+
if (!failure.archived) priorFailureIds.add(failure.sessionId);
|
|
5010
|
+
}
|
|
5011
|
+
summary.outcomesReconciled = summary.uploaded + summary.unchanged + summary.failed + summary.skippedChanged + summary.skippedUnknown === summary.inspected;
|
|
4441
5012
|
summary.staleSince = failedWatermarks.sort()[0] ?? null;
|
|
4442
5013
|
return summary;
|
|
4443
5014
|
}
|
|
4444
5015
|
|
|
5016
|
+
// src/lib/opencode/session-archive-manifest.ts
|
|
5017
|
+
var SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION = 1;
|
|
5018
|
+
function sessionArchiveManifestKey(keyPrefix, identity) {
|
|
5019
|
+
return `${keyPrefix.replace(/\/+$/, "")}/archive-audit/${identity.bootId}-${String(identity.passSequence).padStart(4, "0")}-${identity.phase}.json`;
|
|
5020
|
+
}
|
|
5021
|
+
function buildSessionArchiveManifest(identity, summary) {
|
|
5022
|
+
const failedSessions = summary?.failures.filter(({ archived }) => !archived) ?? [];
|
|
5023
|
+
const watermarkWriteFailures = new Set(
|
|
5024
|
+
summary?.failures.filter(({ archived }) => archived).map(({ sessionId }) => sessionId)
|
|
5025
|
+
);
|
|
5026
|
+
const sessions = summary ? [
|
|
5027
|
+
...summary.uploadedSessions.map((upload) => ({
|
|
5028
|
+
id: upload.sessionId,
|
|
5029
|
+
outcome: "uploaded",
|
|
5030
|
+
archive_key: upload.key,
|
|
5031
|
+
fingerprint: upload.fingerprint,
|
|
5032
|
+
version_id: upload.versionId,
|
|
5033
|
+
etag: upload.etag,
|
|
5034
|
+
object_metadata_reported: upload.metadataReported,
|
|
5035
|
+
retried_prior_failure: upload.retriedPriorFailure,
|
|
5036
|
+
...watermarkWriteFailures.has(upload.sessionId) ? { watermark_write_failed: true } : {}
|
|
5037
|
+
})),
|
|
5038
|
+
...summary.unchangedSessions.map((unchanged) => ({
|
|
5039
|
+
id: unchanged.sessionId,
|
|
5040
|
+
outcome: "unchanged",
|
|
5041
|
+
fingerprint: unchanged.fingerprint,
|
|
5042
|
+
watermark_fingerprint: unchanged.watermarkFingerprint,
|
|
5043
|
+
watermark_key: unchanged.watermarkKey,
|
|
5044
|
+
watermark_version_id: unchanged.watermarkVersionId,
|
|
5045
|
+
watermark_etag: unchanged.watermarkEtag,
|
|
5046
|
+
watermark_uploaded_at: unchanged.watermarkUploadedAt
|
|
5047
|
+
})),
|
|
5048
|
+
...failedSessions.map((failure) => ({
|
|
5049
|
+
id: failure.sessionId,
|
|
5050
|
+
outcome: "failed",
|
|
5051
|
+
failure_outcome: failure.outcome,
|
|
5052
|
+
...failure.reason !== void 0 ? { reason: failure.reason } : {},
|
|
5053
|
+
...failure.bytes !== void 0 ? { payload_bytes: failure.bytes } : {},
|
|
5054
|
+
...failure.byteLimit !== void 0 ? { payload_limit_bytes: failure.byteLimit } : {},
|
|
5055
|
+
...failure.messageCount !== void 0 ? { message_count: failure.messageCount } : {},
|
|
5056
|
+
...failure.partCount !== void 0 ? { part_count: failure.partCount } : {},
|
|
5057
|
+
...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
|
|
5058
|
+
})),
|
|
5059
|
+
...summary.skippedChangedSessions.map((skipped) => ({
|
|
5060
|
+
id: skipped.sessionId,
|
|
5061
|
+
outcome: "skipped-changed",
|
|
5062
|
+
reason: skipped.reason
|
|
5063
|
+
})),
|
|
5064
|
+
...summary.skippedUnknownIds.map((sessionId) => ({
|
|
5065
|
+
id: sessionId,
|
|
5066
|
+
outcome: "skipped-unknown"
|
|
5067
|
+
}))
|
|
5068
|
+
] : [];
|
|
5069
|
+
return {
|
|
5070
|
+
schema_version: SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION,
|
|
5071
|
+
runner_id: identity.runnerId,
|
|
5072
|
+
boot_id: identity.bootId,
|
|
5073
|
+
pass_sequence: identity.passSequence,
|
|
5074
|
+
phase: identity.phase,
|
|
5075
|
+
started_at: identity.startedAt,
|
|
5076
|
+
completed_at: identity.completedAt,
|
|
5077
|
+
budget_ms: identity.budgetMs,
|
|
5078
|
+
enumeration_complete: identity.enumerationComplete,
|
|
5079
|
+
enumeration_reason: identity.enumerationReason,
|
|
5080
|
+
watermark_file_present: identity.watermarkFilePresent,
|
|
5081
|
+
watermarks_loaded: identity.watermarksLoaded,
|
|
5082
|
+
inspected: summary?.inspected ?? 0,
|
|
5083
|
+
counts: {
|
|
5084
|
+
uploaded: summary?.uploaded ?? 0,
|
|
5085
|
+
unchanged: summary?.unchanged ?? 0,
|
|
5086
|
+
failed: failedSessions.length,
|
|
5087
|
+
skipped_changed: summary?.skippedChanged ?? 0,
|
|
5088
|
+
skipped_unknown: summary?.skippedUnknown ?? 0
|
|
5089
|
+
},
|
|
5090
|
+
outcomes_reconciled: summary?.outcomesReconciled ?? null,
|
|
5091
|
+
inventory_never_archived: summary?.inventoryNeverArchived ?? 0,
|
|
5092
|
+
inventory_prior_failures: summary?.inventoryPriorFailures ?? 0,
|
|
5093
|
+
sessions
|
|
5094
|
+
};
|
|
5095
|
+
}
|
|
5096
|
+
async function uploadSessionArchiveManifest({
|
|
5097
|
+
keyPrefix,
|
|
5098
|
+
identity,
|
|
5099
|
+
summary,
|
|
5100
|
+
timeoutMs,
|
|
5101
|
+
signal,
|
|
5102
|
+
onMetadataDecodeError,
|
|
5103
|
+
upload
|
|
5104
|
+
}) {
|
|
5105
|
+
const key = sessionArchiveManifestKey(keyPrefix, identity);
|
|
5106
|
+
const manifest = buildSessionArchiveManifest(identity, summary);
|
|
5107
|
+
const outcome = await (upload ?? uploadSessionArchive)(key, JSON.stringify(manifest), {
|
|
5108
|
+
timeoutMs,
|
|
5109
|
+
signal,
|
|
5110
|
+
onMetadataDecodeError
|
|
5111
|
+
});
|
|
5112
|
+
return { key, outcome };
|
|
5113
|
+
}
|
|
5114
|
+
|
|
4445
5115
|
// src/lib/opencode/auth.ts
|
|
4446
5116
|
function buildOpenCodeBasicAuthHeader(password) {
|
|
4447
5117
|
return `Basic ${Buffer.from(["opencode", password].join(":")).toString("base64")}`;
|
|
@@ -7630,7 +8300,7 @@ function reportedOpenCodeVersion(input) {
|
|
|
7630
8300
|
|
|
7631
8301
|
// src/lib/opencode/process.ts
|
|
7632
8302
|
import { execSync, spawn as spawn3 } from "child_process";
|
|
7633
|
-
import { randomBytes } from "node:crypto";
|
|
8303
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
7634
8304
|
|
|
7635
8305
|
// src/lib/process-stop.ts
|
|
7636
8306
|
async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
@@ -7908,7 +8578,7 @@ async function startOpenCode(port, options = {}) {
|
|
|
7908
8578
|
return child;
|
|
7909
8579
|
}
|
|
7910
8580
|
async function startOpenCode2(port, options = {}) {
|
|
7911
|
-
const password =
|
|
8581
|
+
const password = randomBytes2(24).toString("hex");
|
|
7912
8582
|
let command = options.command ?? "opencode2";
|
|
7913
8583
|
const logLevel = options.inheritStdio ? ["--log-level", resolveOpenCode2LogLevel(process.env)] : [];
|
|
7914
8584
|
let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...logLevel];
|
|
@@ -17944,6 +18614,8 @@ var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
|
|
|
17944
18614
|
var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
|
|
17945
18615
|
var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
|
|
17946
18616
|
var MAX_SESSION_DELETE_BODY_LENGTH = 200;
|
|
18617
|
+
var SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET = 3;
|
|
18618
|
+
var SESSION_ARCHIVE_MANIFEST_BUDGET_MS = 500;
|
|
17947
18619
|
function shouldWarnForReclaimSkip(reason) {
|
|
17948
18620
|
if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
|
|
17949
18621
|
const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
|
|
@@ -17967,18 +18639,52 @@ function logSessionArchiveActivity(state, phase, entry) {
|
|
|
17967
18639
|
logActivity(state, {
|
|
17968
18640
|
...entry,
|
|
17969
18641
|
source: "cli.session-archive",
|
|
17970
|
-
metadata
|
|
18642
|
+
// The forwarder drops metadata beyond its 20-entry cap in insertion order.
|
|
18643
|
+
metadata: { phase, ...entry.metadata }
|
|
17971
18644
|
});
|
|
17972
18645
|
}
|
|
17973
|
-
function
|
|
18646
|
+
function logSessionArchiveMetadataDecodeFailure(state, phase, details) {
|
|
18647
|
+
const subject = details.sessionId ? `session ${details.sessionId}` : "audit manifest";
|
|
18648
|
+
logSessionArchiveActivity(state, phase, {
|
|
18649
|
+
type: "info",
|
|
18650
|
+
level: "warn",
|
|
18651
|
+
message: `Session archive: ${subject} upload returned malformed ${details.field} metadata; the upload succeeded without that value`,
|
|
18652
|
+
metadata: {
|
|
18653
|
+
outcome: "archive-upload-metadata-malformed",
|
|
18654
|
+
metadata_field: details.field,
|
|
18655
|
+
metadata_decode_reason: details.reason,
|
|
18656
|
+
...details.sessionId ? { session_id: details.sessionId } : {},
|
|
18657
|
+
...details.manifestKey ? { manifest_key: details.manifestKey } : {}
|
|
18658
|
+
}
|
|
18659
|
+
});
|
|
18660
|
+
}
|
|
18661
|
+
function logSessionArchiveSummary(state, phase, summary, reconciliation) {
|
|
17974
18662
|
const everyUploadFailed = summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
|
|
17975
|
-
const staleSince = everyUploadFailed && summary.staleSince !== null ? `; archive stale since ${summary.staleSince}` : "";
|
|
17976
18663
|
const neverWatermarked = summary.neverWatermarkedFailures > 0 ? `; ${summary.neverWatermarkedFailures} failed session(s) had no prior successful upload` : "";
|
|
17977
18664
|
const warning2 = summary.failed > 0 || summary.failures.length > 0 || everyUploadFailed || !summary.reconciliationComplete;
|
|
18665
|
+
if (!reconciliation.complete) {
|
|
18666
|
+
const failure = reconciliation.failures[0];
|
|
18667
|
+
const detail = failure.kind === "http" ? `HTTP ${failure.status} for chunk ${failure.chunk}` : failure.kind === "network" ? `network failure for chunk ${failure.chunk}: ${redactDiagnosticText(failure.message ?? "unknown error").slice(0, 200)}` : `invalid response for chunk ${failure.chunk}`;
|
|
18668
|
+
logSessionArchiveActivity(state, phase, {
|
|
18669
|
+
type: "info",
|
|
18670
|
+
level: "warn",
|
|
18671
|
+
message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
|
|
18672
|
+
metadata: {
|
|
18673
|
+
outcome: "binding-reconciliation-incomplete",
|
|
18674
|
+
runner_id: state.agentId,
|
|
18675
|
+
failed_chunks: reconciliation.failures.length,
|
|
18676
|
+
first_failed_chunk: failure.chunk,
|
|
18677
|
+
first_failure_kind: failure.kind,
|
|
18678
|
+
...failure.status !== void 0 ? { http_status: failure.status } : {}
|
|
18679
|
+
}
|
|
18680
|
+
});
|
|
18681
|
+
}
|
|
17978
18682
|
logSessionArchiveActivity(state, phase, {
|
|
17979
18683
|
type: "info",
|
|
17980
18684
|
level: warning2 ? "warn" : "info",
|
|
17981
|
-
message: `Session archive: inspected ${summary.inspected}, uploaded ${summary.uploaded}, unchanged ${summary.unchanged}, failed ${summary.failed}, skipped budget ${summary.skippedBudget}, unmapped ${summary.unmappedIds.length}, conflicts ${summary.conflicts}, reconciliation incomplete ${summary.reconciliationIncomplete}; bindings ledger ${summary.bindingSourceCounts.ledger}, watermark ${summary.bindingSourceCounts.watermark}, current ${summary.bindingSourceCounts.current}, invocation ${summary.bindingSourceCounts.invocation}, history ${summary.bindingSourceCounts.history}, parent ${summary.bindingSourceCounts.parent}` +
|
|
18685
|
+
message: `Session archive: inspected ${summary.inspected}, uploaded ${summary.uploaded}, unchanged ${summary.unchanged}, failed ${summary.failed}, skipped budget ${summary.skippedBudget}, unmapped ${summary.unmappedIds.length}, conflicts ${summary.conflicts}, reconciliation incomplete ${summary.reconciliationIncomplete}; bindings ledger ${summary.bindingSourceCounts.ledger}, watermark ${summary.bindingSourceCounts.watermark}, current ${summary.bindingSourceCounts.current}, invocation ${summary.bindingSourceCounts.invocation}, history ${summary.bindingSourceCounts.history}, parent ${summary.bindingSourceCounts.parent}` + neverWatermarked,
|
|
18686
|
+
// Keep this summary at the forwarder's 20-entry metadata cap; phase is
|
|
18687
|
+
// prepended by logSessionArchiveActivity.
|
|
17982
18688
|
metadata: {
|
|
17983
18689
|
outcome: "archive-run-complete",
|
|
17984
18690
|
sessions_inspected: summary.inspected,
|
|
@@ -17989,7 +18695,6 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
17989
18695
|
uploads_failed: summary.uploadFailures,
|
|
17990
18696
|
sessions_skipped_budget: summary.skippedBudget,
|
|
17991
18697
|
sessions_unmapped: summary.unmappedIds.length,
|
|
17992
|
-
sessions_unresolved: summary.unresolved,
|
|
17993
18698
|
sessions_conflicted: summary.conflicts,
|
|
17994
18699
|
sessions_reconciliation_incomplete: summary.reconciliationIncomplete,
|
|
17995
18700
|
binding_reconciliation_complete: summary.reconciliationComplete,
|
|
@@ -17999,11 +18704,10 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
17999
18704
|
bindings_from_invocation: summary.bindingSourceCounts.invocation,
|
|
18000
18705
|
bindings_from_history: summary.bindingSourceCounts.history,
|
|
18001
18706
|
bindings_from_parent: summary.bindingSourceCounts.parent,
|
|
18002
|
-
sessions_without_prior_watermark: summary.neverWatermarkedFailures
|
|
18003
|
-
...everyUploadFailed && summary.staleSince !== null ? { stale_since: summary.staleSince } : {}
|
|
18707
|
+
sessions_without_prior_watermark: summary.neverWatermarkedFailures
|
|
18004
18708
|
}
|
|
18005
18709
|
});
|
|
18006
|
-
|
|
18710
|
+
const logFailure = (failure) => {
|
|
18007
18711
|
const permanentSizeFailure = failure.reason === "too-large";
|
|
18008
18712
|
const hasPayloadDetails = failure.bytes !== void 0 && failure.byteLimit !== void 0 && failure.messageCount !== void 0 && failure.partCount !== void 0;
|
|
18009
18713
|
const payloadDetails = hasPayloadDetails ? `; payload bytes=${failure.bytes} limit=${failure.byteLimit} messages=${failure.messageCount} parts=${failure.partCount}` : "";
|
|
@@ -18026,7 +18730,9 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
18026
18730
|
} : {}
|
|
18027
18731
|
}
|
|
18028
18732
|
});
|
|
18029
|
-
}
|
|
18733
|
+
};
|
|
18734
|
+
const failuresToLog = phase === "sweep" ? summary.failures : summary.failures.slice(0, SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET);
|
|
18735
|
+
for (const failure of failuresToLog) logFailure(failure);
|
|
18030
18736
|
if (summary.unmappedIds.length > 0) {
|
|
18031
18737
|
logSessionArchiveActivity(state, phase, {
|
|
18032
18738
|
type: "info",
|
|
@@ -18050,6 +18756,117 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
18050
18756
|
});
|
|
18051
18757
|
}
|
|
18052
18758
|
}
|
|
18759
|
+
function hasSessionArchivePrerequisites(state) {
|
|
18760
|
+
return Boolean(
|
|
18761
|
+
state.opencodeClient && state.sessionArchiveConfig.keyPrefix && state.sessionArchiveWatermarkPath && state.agentId
|
|
18762
|
+
);
|
|
18763
|
+
}
|
|
18764
|
+
async function publishSessionArchiveAudit(state, phase, identity, summary, manifestWindowMs, manifestSignal, parentSignal) {
|
|
18765
|
+
if (!hasSessionArchivePrerequisites(state)) return;
|
|
18766
|
+
const manifestKey = sessionArchiveManifestKey(state.sessionArchiveConfig.keyPrefix, identity);
|
|
18767
|
+
let manifestDurable = false;
|
|
18768
|
+
let manifestVersionId = null;
|
|
18769
|
+
let failure = null;
|
|
18770
|
+
if (parentSignal.aborted) {
|
|
18771
|
+
failure = { kind: "not-attempted", reason: "pass-aborted" };
|
|
18772
|
+
} else if (manifestWindowMs <= 0) {
|
|
18773
|
+
failure = { kind: "not-attempted", reason: "no-manifest-budget" };
|
|
18774
|
+
} else {
|
|
18775
|
+
try {
|
|
18776
|
+
const result = await uploadSessionArchiveManifest({
|
|
18777
|
+
keyPrefix: state.sessionArchiveConfig.keyPrefix,
|
|
18778
|
+
identity,
|
|
18779
|
+
summary,
|
|
18780
|
+
timeoutMs: manifestWindowMs,
|
|
18781
|
+
signal: manifestSignal,
|
|
18782
|
+
upload: uploadSessionArchive,
|
|
18783
|
+
onMetadataDecodeError: (field, reason) => logSessionArchiveMetadataDecodeFailure(state, phase, {
|
|
18784
|
+
field,
|
|
18785
|
+
reason,
|
|
18786
|
+
manifestKey
|
|
18787
|
+
})
|
|
18788
|
+
});
|
|
18789
|
+
if (result.outcome.kind === "ok") {
|
|
18790
|
+
manifestDurable = true;
|
|
18791
|
+
manifestVersionId = result.outcome.versionId;
|
|
18792
|
+
} else {
|
|
18793
|
+
failure = {
|
|
18794
|
+
kind: result.outcome.kind,
|
|
18795
|
+
..."reason" in result.outcome ? { reason: result.outcome.reason } : {},
|
|
18796
|
+
..."exitCode" in result.outcome && result.outcome.exitCode !== void 0 ? { exitCode: result.outcome.exitCode } : {}
|
|
18797
|
+
};
|
|
18798
|
+
}
|
|
18799
|
+
} catch (error2) {
|
|
18800
|
+
const diagnostic = redactDiagnosticText(
|
|
18801
|
+
error2 instanceof Error ? error2.message : String(error2)
|
|
18802
|
+
).replace(/[\r\n]+/g, " ").slice(0, 200);
|
|
18803
|
+
logSessionArchiveActivity(state, phase, {
|
|
18804
|
+
type: "info",
|
|
18805
|
+
level: "warn",
|
|
18806
|
+
message: `Session archive audit manifest upload threw for boot ${identity.bootId}, pass ${identity.passSequence}, phase ${phase}: ${diagnostic}`,
|
|
18807
|
+
metadata: {
|
|
18808
|
+
outcome: "archive-audit-manifest-upload-threw",
|
|
18809
|
+
boot_id: identity.bootId,
|
|
18810
|
+
pass_sequence: identity.passSequence
|
|
18811
|
+
}
|
|
18812
|
+
});
|
|
18813
|
+
failure = { kind: "thrown", reason: "upload-threw" };
|
|
18814
|
+
}
|
|
18815
|
+
}
|
|
18816
|
+
if (failure !== null) {
|
|
18817
|
+
logSessionArchiveActivity(state, phase, {
|
|
18818
|
+
type: "info",
|
|
18819
|
+
level: "warn",
|
|
18820
|
+
message: `Session archive audit manifest was not durable for ${phase} pass ${identity.passSequence}: ${failure.kind}${failure.reason ? ` (${failure.reason})` : ""}`,
|
|
18821
|
+
metadata: {
|
|
18822
|
+
outcome: "archive-audit-manifest-failed",
|
|
18823
|
+
boot_id: identity.bootId,
|
|
18824
|
+
pass_sequence: identity.passSequence,
|
|
18825
|
+
manifest_key: manifestKey,
|
|
18826
|
+
kind: failure.kind,
|
|
18827
|
+
...failure.reason !== void 0 ? { reason: failure.reason } : {},
|
|
18828
|
+
...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
|
|
18829
|
+
}
|
|
18830
|
+
});
|
|
18831
|
+
}
|
|
18832
|
+
const sessionsInspected = summary?.inspected ?? 0;
|
|
18833
|
+
const sessionsUploaded = summary?.uploaded ?? 0;
|
|
18834
|
+
const sessionsUnchanged = summary?.unchanged ?? 0;
|
|
18835
|
+
const sessionsFailed = summary?.failed ?? 0;
|
|
18836
|
+
const sessionsSkippedChanged = summary?.skippedChanged ?? 0;
|
|
18837
|
+
const sessionsSkippedUnknown = summary?.skippedUnknown ?? 0;
|
|
18838
|
+
const outcomesReconciled = summary?.outcomesReconciled ?? null;
|
|
18839
|
+
const retries = summary?.uploadedSessions.filter(({ retriedPriorFailure }) => retriedPriorFailure).length ?? 0;
|
|
18840
|
+
const everyUploadFailed = summary !== null && summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
|
|
18841
|
+
const level = summary === null || !summary.outcomesReconciled || summary.skippedChanged > 0 ? "warn" : "info";
|
|
18842
|
+
const message = summary === null ? `Session archive audit: ${phase} pass could not enumerate the session store (${identity.enumerationReason ?? "unknown"}); no session was inspected` : `Session archive audit: inspected ${sessionsInspected}, uploaded ${sessionsUploaded}, unchanged ${sessionsUnchanged}, failed ${sessionsFailed}, skipped known changed ${sessionsSkippedChanged}, skipped unknown ${sessionsSkippedUnknown}; outcomes reconciled ${outcomesReconciled ? "yes" : "no"}; manifest ${manifestKey}`;
|
|
18843
|
+
logSessionArchiveActivity(state, phase, {
|
|
18844
|
+
type: "info",
|
|
18845
|
+
level,
|
|
18846
|
+
message,
|
|
18847
|
+
metadata: {
|
|
18848
|
+
outcome: "archive-outcome-audit",
|
|
18849
|
+
boot_id: identity.bootId,
|
|
18850
|
+
pass_sequence: identity.passSequence,
|
|
18851
|
+
enumeration_complete: identity.enumerationComplete,
|
|
18852
|
+
sessions_inspected: sessionsInspected,
|
|
18853
|
+
sessions_uploaded: sessionsUploaded,
|
|
18854
|
+
sessions_unchanged: sessionsUnchanged,
|
|
18855
|
+
sessions_failed: sessionsFailed,
|
|
18856
|
+
sessions_skipped_changed: sessionsSkippedChanged,
|
|
18857
|
+
sessions_skipped_unknown: sessionsSkippedUnknown,
|
|
18858
|
+
outcomes_reconciled: outcomesReconciled,
|
|
18859
|
+
manifest_durable: manifestDurable,
|
|
18860
|
+
manifest_key: manifestKey,
|
|
18861
|
+
manifest_version_id: manifestVersionId,
|
|
18862
|
+
watermark_file_present: identity.watermarkFilePresent,
|
|
18863
|
+
watermarks_loaded: identity.watermarksLoaded,
|
|
18864
|
+
uploads_retrying_prior_failures: retries,
|
|
18865
|
+
...summary === null ? { enumeration_reason: identity.enumerationReason ?? "unknown" } : {},
|
|
18866
|
+
...everyUploadFailed && summary?.staleSince !== null ? { stale_since: summary.staleSince } : {}
|
|
18867
|
+
}
|
|
18868
|
+
});
|
|
18869
|
+
}
|
|
18053
18870
|
async function drainSessionDeletionReports(state) {
|
|
18054
18871
|
const path = sessionDeletionReportPath(homedir9(), process.env);
|
|
18055
18872
|
let delivered = 0;
|
|
@@ -18467,14 +19284,10 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
|
|
|
18467
19284
|
}
|
|
18468
19285
|
const controller = new AbortController();
|
|
18469
19286
|
state.sessionArchiveAbortController = controller;
|
|
19287
|
+
let budgetExceeded = false;
|
|
18470
19288
|
const timeout = setTimeout(() => {
|
|
19289
|
+
budgetExceeded = true;
|
|
18471
19290
|
controller.abort();
|
|
18472
|
-
logSessionArchiveActivity(state, phase, {
|
|
18473
|
-
type: "info",
|
|
18474
|
-
level: "warn",
|
|
18475
|
-
message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
|
|
18476
|
-
metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
|
|
18477
|
-
});
|
|
18478
19291
|
}, budgetMs);
|
|
18479
19292
|
const task = Promise.resolve().then(() => work(controller.signal)).catch((error2) => {
|
|
18480
19293
|
logSessionArchiveActivity(state, phase, {
|
|
@@ -18485,6 +19298,19 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
|
|
|
18485
19298
|
});
|
|
18486
19299
|
return null;
|
|
18487
19300
|
}).finally(() => {
|
|
19301
|
+
if (budgetExceeded) {
|
|
19302
|
+
logSessionArchiveActivity(state, phase, {
|
|
19303
|
+
type: "info",
|
|
19304
|
+
level: "warn",
|
|
19305
|
+
message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
|
|
19306
|
+
metadata: {
|
|
19307
|
+
outcome: "archive-budget-exceeded",
|
|
19308
|
+
budget_ms: budgetMs,
|
|
19309
|
+
boot_id: state.sessionArchiveBootId,
|
|
19310
|
+
pass_sequence: state.sessionArchivePassSequence
|
|
19311
|
+
}
|
|
19312
|
+
});
|
|
19313
|
+
}
|
|
18488
19314
|
clearTimeout(timeout);
|
|
18489
19315
|
if (state.sessionArchiveInFlight === task) {
|
|
18490
19316
|
state.sessionArchiveInFlight = null;
|
|
@@ -18495,10 +19321,7 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
|
|
|
18495
19321
|
return task;
|
|
18496
19322
|
}
|
|
18497
19323
|
async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal) {
|
|
18498
|
-
|
|
18499
|
-
const client = state.opencodeClient;
|
|
18500
|
-
const watermarkPath = state.sessionArchiveWatermarkPath;
|
|
18501
|
-
if (!client || !config.keyPrefix || !watermarkPath || !state.agentId) {
|
|
19324
|
+
if (!hasSessionArchivePrerequisites(state)) {
|
|
18502
19325
|
logSessionArchiveActivity(state, phase, {
|
|
18503
19326
|
type: "info",
|
|
18504
19327
|
level: "warn",
|
|
@@ -18507,6 +19330,9 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
|
|
|
18507
19330
|
});
|
|
18508
19331
|
return null;
|
|
18509
19332
|
}
|
|
19333
|
+
const config = state.sessionArchiveConfig;
|
|
19334
|
+
const client = state.opencodeClient;
|
|
19335
|
+
const watermarkPath = state.sessionArchiveWatermarkPath;
|
|
18510
19336
|
const bindings = readSessionBindings(
|
|
18511
19337
|
sessionBindingLedgerPath(homedir9(), process.env),
|
|
18512
19338
|
(message) => logSessionArchiveActivity(state, phase, {
|
|
@@ -18523,23 +19349,6 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
|
|
|
18523
19349
|
sessions,
|
|
18524
19350
|
signal
|
|
18525
19351
|
});
|
|
18526
|
-
if (!reconciliation.complete) {
|
|
18527
|
-
const failure = reconciliation.failures[0];
|
|
18528
|
-
const detail = failure.kind === "http" ? `HTTP ${failure.status} for chunk ${failure.chunk}` : failure.kind === "network" ? `network failure for chunk ${failure.chunk}: ${redactDiagnosticText(failure.message ?? "unknown error").slice(0, 200)}` : `invalid response for chunk ${failure.chunk}`;
|
|
18529
|
-
logSessionArchiveActivity(state, phase, {
|
|
18530
|
-
type: "info",
|
|
18531
|
-
level: "warn",
|
|
18532
|
-
message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
|
|
18533
|
-
metadata: {
|
|
18534
|
-
outcome: "binding-reconciliation-incomplete",
|
|
18535
|
-
runner_id: state.agentId,
|
|
18536
|
-
failed_chunks: reconciliation.failures.length,
|
|
18537
|
-
first_failed_chunk: failure.chunk,
|
|
18538
|
-
first_failure_kind: failure.kind,
|
|
18539
|
-
...failure.status !== void 0 ? { http_status: failure.status } : {}
|
|
18540
|
-
}
|
|
18541
|
-
});
|
|
18542
|
-
}
|
|
18543
19352
|
const summary = await runSessionArchive({
|
|
18544
19353
|
sessions,
|
|
18545
19354
|
deps: {
|
|
@@ -18550,40 +19359,97 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
|
|
|
18550
19359
|
projection: reconciliation.projection,
|
|
18551
19360
|
reconciliationComplete: reconciliation.complete,
|
|
18552
19361
|
watermarks: state.sessionArchiveWatermarks,
|
|
19362
|
+
priorFailureIds: state.sessionArchivePriorFailureIds,
|
|
18553
19363
|
watermarkPath,
|
|
18554
19364
|
signal,
|
|
19365
|
+
onMetadataDecodeError: (field, reason, sessionId) => logSessionArchiveMetadataDecodeFailure(state, phase, { field, reason, sessionId }),
|
|
18555
19366
|
upload: uploadSessionArchive,
|
|
18556
19367
|
exportMessages: exportSessionMessages,
|
|
18557
19368
|
recordWatermark: recordUpload
|
|
18558
19369
|
},
|
|
18559
19370
|
budgetMs
|
|
18560
19371
|
});
|
|
18561
|
-
logSessionArchiveSummary(state, phase, summary);
|
|
19372
|
+
logSessionArchiveSummary(state, phase, summary, reconciliation);
|
|
18562
19373
|
return summary;
|
|
18563
19374
|
}
|
|
18564
19375
|
async function runSessionArchiveFleet(state, phase, budgetMs, signal) {
|
|
19376
|
+
state.sessionArchivePassSequence++;
|
|
18565
19377
|
const startedAt = Date.now();
|
|
18566
|
-
const
|
|
18567
|
-
|
|
18568
|
-
|
|
18569
|
-
|
|
18570
|
-
|
|
18571
|
-
|
|
18572
|
-
|
|
18573
|
-
|
|
18574
|
-
|
|
18575
|
-
|
|
19378
|
+
const passDeadline = startedAt + budgetMs;
|
|
19379
|
+
const workDeadline = passDeadline - SESSION_ARCHIVE_MANIFEST_BUDGET_MS;
|
|
19380
|
+
const watermarksLoaded = state.sessionArchiveWatermarks.size;
|
|
19381
|
+
const workBudget = createBudgetSignal(signal, Math.max(0, workDeadline - Date.now()));
|
|
19382
|
+
let summary = null;
|
|
19383
|
+
let enumerationComplete = false;
|
|
19384
|
+
let enumerationReason = null;
|
|
19385
|
+
try {
|
|
19386
|
+
const enumeration = await listAllSessions(
|
|
19387
|
+
state.port,
|
|
19388
|
+
state.opencodeClient ?? void 0,
|
|
19389
|
+
workBudget.signal
|
|
19390
|
+
);
|
|
19391
|
+
if (enumeration.sessions === null) {
|
|
19392
|
+
enumerationComplete = false;
|
|
19393
|
+
enumerationReason = workBudget.signal.aborted ? "enumeration-interrupted" : enumeration.reason;
|
|
19394
|
+
const interrupted = workBudget.signal.aborted;
|
|
19395
|
+
logSessionArchiveActivity(state, phase, {
|
|
19396
|
+
type: "info",
|
|
19397
|
+
level: "warn",
|
|
19398
|
+
message: interrupted ? "Session archive: enumeration was interrupted before the complete store was known; no session was marked archived" : `Session archive: could not enumerate the complete session store (${enumerationReason}); no session was marked archived`,
|
|
19399
|
+
metadata: {
|
|
19400
|
+
outcome: interrupted ? "enumeration-interrupted" : "enumeration-refused",
|
|
19401
|
+
...!interrupted ? { reason: enumerationReason } : {}
|
|
19402
|
+
}
|
|
19403
|
+
});
|
|
19404
|
+
} else {
|
|
19405
|
+
enumerationComplete = true;
|
|
19406
|
+
enumerationReason = null;
|
|
19407
|
+
const enumeratedIds = new Set(enumeration.sessions.map(({ id }) => id));
|
|
19408
|
+
for (const sessionId of state.sessionArchivePriorFailureIds) {
|
|
19409
|
+
if (!enumeratedIds.has(sessionId)) state.sessionArchivePriorFailureIds.delete(sessionId);
|
|
18576
19410
|
}
|
|
18577
|
-
|
|
18578
|
-
|
|
19411
|
+
summary = await runSessionArchiveBatch(
|
|
19412
|
+
state,
|
|
19413
|
+
phase,
|
|
19414
|
+
enumeration.sessions,
|
|
19415
|
+
Math.max(0, workDeadline - Date.now()),
|
|
19416
|
+
workBudget.signal
|
|
19417
|
+
);
|
|
19418
|
+
}
|
|
19419
|
+
} finally {
|
|
19420
|
+
workBudget.dispose();
|
|
18579
19421
|
}
|
|
18580
|
-
|
|
18581
|
-
|
|
18582
|
-
|
|
18583
|
-
|
|
18584
|
-
|
|
18585
|
-
|
|
18586
|
-
|
|
19422
|
+
const manifestWindowMs = Math.max(0, passDeadline - Date.now());
|
|
19423
|
+
const manifestBudget = createBudgetSignal(signal, manifestWindowMs);
|
|
19424
|
+
try {
|
|
19425
|
+
if (summary !== null || !enumerationComplete) {
|
|
19426
|
+
const identity = {
|
|
19427
|
+
runnerId: state.agentId,
|
|
19428
|
+
bootId: state.sessionArchiveBootId,
|
|
19429
|
+
passSequence: state.sessionArchivePassSequence,
|
|
19430
|
+
phase,
|
|
19431
|
+
startedAt: new Date(startedAt).toISOString(),
|
|
19432
|
+
completedAt: new Date(Date.now()).toISOString(),
|
|
19433
|
+
budgetMs,
|
|
19434
|
+
enumerationComplete,
|
|
19435
|
+
enumerationReason,
|
|
19436
|
+
watermarkFilePresent: state.sessionArchiveWatermarkFileLoaded,
|
|
19437
|
+
watermarksLoaded
|
|
19438
|
+
};
|
|
19439
|
+
await publishSessionArchiveAudit(
|
|
19440
|
+
state,
|
|
19441
|
+
phase,
|
|
19442
|
+
identity,
|
|
19443
|
+
summary,
|
|
19444
|
+
manifestWindowMs,
|
|
19445
|
+
manifestBudget.signal,
|
|
19446
|
+
signal
|
|
19447
|
+
);
|
|
19448
|
+
}
|
|
19449
|
+
} finally {
|
|
19450
|
+
manifestBudget.dispose();
|
|
19451
|
+
}
|
|
19452
|
+
return summary;
|
|
18587
19453
|
}
|
|
18588
19454
|
async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
18589
19455
|
const deadline = Date.now() + budgetMs;
|
|
@@ -18606,7 +19472,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
|
18606
19472
|
type: "info",
|
|
18607
19473
|
level: "warn",
|
|
18608
19474
|
message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
|
|
18609
|
-
metadata: {
|
|
19475
|
+
metadata: {
|
|
19476
|
+
outcome: "archive-budget-exceeded",
|
|
19477
|
+
budget_ms: budgetMs,
|
|
19478
|
+
boot_id: state.sessionArchiveBootId,
|
|
19479
|
+
pass_sequence: state.sessionArchivePassSequence,
|
|
19480
|
+
manifest_written: false
|
|
19481
|
+
}
|
|
18610
19482
|
});
|
|
18611
19483
|
return null;
|
|
18612
19484
|
}
|
|
@@ -18617,7 +19489,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
|
18617
19489
|
type: "info",
|
|
18618
19490
|
level: "warn",
|
|
18619
19491
|
message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
|
|
18620
|
-
metadata: {
|
|
19492
|
+
metadata: {
|
|
19493
|
+
outcome: "archive-budget-exceeded",
|
|
19494
|
+
budget_ms: budgetMs,
|
|
19495
|
+
boot_id: state.sessionArchiveBootId,
|
|
19496
|
+
pass_sequence: state.sessionArchivePassSequence,
|
|
19497
|
+
manifest_written: false
|
|
19498
|
+
}
|
|
18621
19499
|
});
|
|
18622
19500
|
return null;
|
|
18623
19501
|
}
|
|
@@ -18641,6 +19519,7 @@ function scheduleSessionArchive(state) {
|
|
|
18641
19519
|
metadata: { outcome: "watermark-read-failed" }
|
|
18642
19520
|
})
|
|
18643
19521
|
);
|
|
19522
|
+
state.sessionArchiveWatermarkFileLoaded = state.sessionArchiveWatermarks.size > 0;
|
|
18644
19523
|
logSessionArchiveActivity(state, "startup", {
|
|
18645
19524
|
type: "info",
|
|
18646
19525
|
message: `Session archive enabled (interval=${config.intervalMs}ms)`,
|
|
@@ -19150,9 +20029,13 @@ async function run(options) {
|
|
|
19150
20029
|
),
|
|
19151
20030
|
sessionArchiveTimers: [],
|
|
19152
20031
|
sessionArchiveWatermarks: /* @__PURE__ */ new Map(),
|
|
20032
|
+
sessionArchivePriorFailureIds: /* @__PURE__ */ new Set(),
|
|
19153
20033
|
sessionArchiveWatermarkPath: null,
|
|
19154
20034
|
sessionArchiveInFlight: null,
|
|
19155
20035
|
sessionArchiveAbortController: null,
|
|
20036
|
+
sessionArchiveBootId: randomUUID2(),
|
|
20037
|
+
sessionArchivePassSequence: 0,
|
|
20038
|
+
sessionArchiveWatermarkFileLoaded: false,
|
|
19156
20039
|
sessionDeleteFailures: /* @__PURE__ */ new Map(),
|
|
19157
20040
|
claudeUsageTimer: null,
|
|
19158
20041
|
claudeUsageRearm: null,
|
|
@@ -20135,24 +21018,89 @@ async function run(options) {
|
|
|
20135
21018
|
}
|
|
20136
21019
|
}
|
|
20137
21020
|
|
|
21021
|
+
// src/commands/teams.ts
|
|
21022
|
+
function printTeam(team, selected) {
|
|
21023
|
+
console.log(`${selected ? "* " : " "}${team.id} ${team.name}`);
|
|
21024
|
+
}
|
|
21025
|
+
function isTeam(value) {
|
|
21026
|
+
return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.name === "string";
|
|
21027
|
+
}
|
|
21028
|
+
async function teams() {
|
|
21029
|
+
const apiUrl = getApiUrlConfig();
|
|
21030
|
+
let credentials2;
|
|
21031
|
+
try {
|
|
21032
|
+
credentials2 = await getAuthCredentials();
|
|
21033
|
+
} catch (error2) {
|
|
21034
|
+
printError(
|
|
21035
|
+
`Could not read the saved Evident credentials: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
21036
|
+
);
|
|
21037
|
+
process.exitCode = 1;
|
|
21038
|
+
return;
|
|
21039
|
+
}
|
|
21040
|
+
if (!credentials2) {
|
|
21041
|
+
printError(`Not logged in to ${apiUrl}. Run the \`login\` command to authenticate.`);
|
|
21042
|
+
process.exitCode = 1;
|
|
21043
|
+
return;
|
|
21044
|
+
}
|
|
21045
|
+
try {
|
|
21046
|
+
const response = await fetch(`${apiUrl}/teams`, {
|
|
21047
|
+
headers: buildAuthHeaders(credentials2)
|
|
21048
|
+
});
|
|
21049
|
+
if (!response.ok) {
|
|
21050
|
+
const serverMessage = await readErrorMessage(response);
|
|
21051
|
+
throw new Error(
|
|
21052
|
+
`Evident returned HTTP ${response.status} while listing teams${serverMessage ? `: ${serverMessage}` : ""}`
|
|
21053
|
+
);
|
|
21054
|
+
}
|
|
21055
|
+
const data = await response.json();
|
|
21056
|
+
if (!Array.isArray(data) || !data.every(isTeam)) {
|
|
21057
|
+
throw new Error("Evident returned an invalid team list. Update the CLI and retry.");
|
|
21058
|
+
}
|
|
21059
|
+
const selectedTeam = getTeamSelection();
|
|
21060
|
+
blank();
|
|
21061
|
+
if (data.length === 0) {
|
|
21062
|
+
console.log("No teams found for this account.");
|
|
21063
|
+
blank();
|
|
21064
|
+
return;
|
|
21065
|
+
}
|
|
21066
|
+
for (const team of data) {
|
|
21067
|
+
printTeam(team, team.id === selectedTeam);
|
|
21068
|
+
}
|
|
21069
|
+
if (data.length === 1) {
|
|
21070
|
+
console.log("This is your only team; commands act in it automatically.");
|
|
21071
|
+
} else if (!selectedTeam) {
|
|
21072
|
+
console.log("Choose a team with --team <id> or set EVIDENT_TEAM.");
|
|
21073
|
+
}
|
|
21074
|
+
blank();
|
|
21075
|
+
} catch (error2) {
|
|
21076
|
+
printError(`Could not list teams: ${error2 instanceof Error ? error2.message : String(error2)}`);
|
|
21077
|
+
process.exitCode = 1;
|
|
21078
|
+
}
|
|
21079
|
+
}
|
|
21080
|
+
|
|
20138
21081
|
// src/index.ts
|
|
20139
21082
|
var version = getCliVersion();
|
|
20140
21083
|
var program = new Command();
|
|
20141
21084
|
program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
|
|
20142
21085
|
"--endpoint <url>",
|
|
20143
21086
|
"Evident API base URL (default: production; e.g. http://localhost:3001)"
|
|
20144
|
-
).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").
|
|
20145
|
-
|
|
21087
|
+
).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").option(
|
|
21088
|
+
"--team <id>",
|
|
21089
|
+
"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"
|
|
21090
|
+
).hook("preAction", (thisCommand) => {
|
|
21091
|
+
const { endpoint: endpoint2, tunnel, team } = thisCommand.optsWithGlobals();
|
|
20146
21092
|
if (endpoint2) {
|
|
20147
21093
|
setEndpoint(endpoint2);
|
|
20148
21094
|
}
|
|
20149
21095
|
if (tunnel) {
|
|
20150
21096
|
setTunnelUrl(tunnel);
|
|
20151
21097
|
}
|
|
21098
|
+
setTeamSelection(team);
|
|
20152
21099
|
});
|
|
20153
21100
|
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);
|
|
20154
21101
|
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 }));
|
|
20155
21102
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
21103
|
+
program.command("teams").description("List the teams you belong to").action(teams);
|
|
20156
21104
|
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
21105
|
(proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
|
|
20158
21106
|
noBrowser: options.browser === false,
|