@evident-ai/cli 3.6.1-dev.9c960b2 → 3.6.1-dev.a0ae06e
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 +1471 -232
- 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"
|
|
1563
1805
|
});
|
|
1564
|
-
response.end(
|
|
1806
|
+
response.end(phase ? JSON.stringify({ phase }) : "", onFinish);
|
|
1807
|
+
}
|
|
1808
|
+
function isTerminalPagePhase(phase) {
|
|
1809
|
+
return phase === "success" || phase === "tools_pending" || phase === "failed" || phase === "unconfirmed";
|
|
1810
|
+
}
|
|
1811
|
+
function waitForTerminalStatusRead(page, signal) {
|
|
1812
|
+
if (page.terminalRead || signal.aborted) return Promise.resolve();
|
|
1813
|
+
return new Promise((resolve6) => {
|
|
1814
|
+
let settled = false;
|
|
1815
|
+
const finish = () => {
|
|
1816
|
+
if (settled) return;
|
|
1817
|
+
settled = true;
|
|
1818
|
+
clearTimeout(timer);
|
|
1819
|
+
signal.removeEventListener("abort", finish);
|
|
1820
|
+
if (page.notifyTerminalRead === finish) page.notifyTerminalRead = void 0;
|
|
1821
|
+
resolve6();
|
|
1822
|
+
};
|
|
1823
|
+
const timer = setTimeout(finish, CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS);
|
|
1824
|
+
page.notifyTerminalRead = finish;
|
|
1825
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
1826
|
+
if (signal.aborted) finish();
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
function handleStatusRequest(request3, response, page) {
|
|
1830
|
+
if (!request3.url?.startsWith("/_status/")) return false;
|
|
1831
|
+
const statusPath = `/_status/${page.capability}`;
|
|
1832
|
+
const base = page.origin ?? `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
|
|
1833
|
+
const url = URL.canParse(request3.url, base) ? new URL(request3.url, base) : void 0;
|
|
1834
|
+
const fetchSite = request3.headers["sec-fetch-site"];
|
|
1835
|
+
if (request3.method !== "GET" || !url || url.pathname !== statusPath || url.search || request3.headers.host !== page.host || fetchSite !== void 0 && fetchSite !== "same-origin" || request3.headers.origin !== void 0 && request3.headers.origin !== page.origin || request3.headers["transfer-encoding"] !== void 0 || Number(request3.headers["content-length"] ?? 0) > 0) {
|
|
1836
|
+
statusResponse(response, 404);
|
|
1837
|
+
return true;
|
|
1838
|
+
}
|
|
1839
|
+
const phase = page.phase;
|
|
1840
|
+
statusResponse(response, 200, phase, () => {
|
|
1841
|
+
if (isTerminalPagePhase(phase)) {
|
|
1842
|
+
page.terminalRead = true;
|
|
1843
|
+
page.notifyTerminalRead?.();
|
|
1844
|
+
}
|
|
1845
|
+
});
|
|
1846
|
+
return true;
|
|
1847
|
+
}
|
|
1848
|
+
function rejectedCallbackResponse(response, status2) {
|
|
1849
|
+
const page = callbackPage();
|
|
1850
|
+
callbackResponse(response, status2, page.html, page.nonce);
|
|
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";
|
|
@@ -1983,8 +2455,11 @@ import chalk7 from "chalk";
|
|
|
1983
2455
|
import ora4 from "ora";
|
|
1984
2456
|
import { select as select4 } from "@inquirer/prompts";
|
|
1985
2457
|
|
|
2458
|
+
// src/lib/opencode-start-timeout.ts
|
|
2459
|
+
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
2460
|
+
|
|
1986
2461
|
// src/lib/telemetry.ts
|
|
1987
|
-
var CLI_VERSION = (true ? "3.6.1-dev.
|
|
2462
|
+
var CLI_VERSION = (true ? "3.6.1-dev.a0ae06e" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
1988
2463
|
function getCliVersion() {
|
|
1989
2464
|
return CLI_VERSION;
|
|
1990
2465
|
}
|
|
@@ -2175,6 +2650,22 @@ function redactDiagnosticText(message) {
|
|
|
2175
2650
|
const redacted = message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g, "sk-ant-***").replace(/(?<![A-Za-z0-9_-])sk-proj-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g, "sk-proj-***").replace(/(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{20,}(?![A-Za-z0-9_-])/g, "sk-***").replace(/(?<![A-Za-z0-9_-])(gh[oprsu])_[A-Za-z0-9]{20,}(?![A-Za-z0-9_-])/g, "$1_***").replace(/(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}(?![A-Za-z0-9_-])/g, "github_pat_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
2176
2651
|
return redactHomeDirectory(redacted);
|
|
2177
2652
|
}
|
|
2653
|
+
function describeErrorWithCause(error2) {
|
|
2654
|
+
const base = error2 instanceof Error ? error2.message : String(error2);
|
|
2655
|
+
const cause = error2 instanceof Error ? error2.cause : void 0;
|
|
2656
|
+
let detail;
|
|
2657
|
+
if (cause instanceof Error) {
|
|
2658
|
+
const causeWithCode = cause;
|
|
2659
|
+
detail = cause.message || (typeof causeWithCode.code === "string" ? causeWithCode.code : void 0) || cause.name;
|
|
2660
|
+
} else if (cause !== null && typeof cause === "object") {
|
|
2661
|
+
const causeRecord = cause;
|
|
2662
|
+
detail = typeof causeRecord.message === "string" && causeRecord.message || typeof causeRecord.code === "string" && causeRecord.code || void 0;
|
|
2663
|
+
} else if (typeof cause === "string") {
|
|
2664
|
+
detail = cause;
|
|
2665
|
+
}
|
|
2666
|
+
if (!detail || base.includes(detail)) return base;
|
|
2667
|
+
return `${base} (${redactDiagnosticText(detail).slice(0, 200)})`;
|
|
2668
|
+
}
|
|
2178
2669
|
|
|
2179
2670
|
// src/lib/opencode/session-db-reclaim.ts
|
|
2180
2671
|
var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
|
|
@@ -3827,7 +4318,7 @@ function isRecord3(value) {
|
|
|
3827
4318
|
}
|
|
3828
4319
|
function isWatermark(value) {
|
|
3829
4320
|
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");
|
|
4321
|
+
return typeof value.fingerprint === "string" && typeof value.uploaded_at === "string" && typeof value.key === "string" && (!("conversation_id" in value) || value.conversation_id === null || typeof value.conversation_id === "string") && (!("version_id" in value) || value.version_id === null || typeof value.version_id === "string") && (!("etag" in value) || value.etag === null || typeof value.etag === "string");
|
|
3831
4322
|
}
|
|
3832
4323
|
function isMissingFile3(error2) {
|
|
3833
4324
|
return error2 instanceof Error && "code" in error2 && error2.code === "ENOENT";
|
|
@@ -4008,6 +4499,37 @@ function isJson(body) {
|
|
|
4008
4499
|
return false;
|
|
4009
4500
|
}
|
|
4010
4501
|
}
|
|
4502
|
+
function parseArchivePutMetadata(stderr, onMetadataDecodeError) {
|
|
4503
|
+
const prefix = "ARCHIVE-PUT: outcome=ok ";
|
|
4504
|
+
const lines = stderr.split(/\r?\n/);
|
|
4505
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
4506
|
+
const line = lines[index];
|
|
4507
|
+
if (line === void 0) continue;
|
|
4508
|
+
const prefixIndex = line.indexOf(prefix);
|
|
4509
|
+
if (prefixIndex === -1) continue;
|
|
4510
|
+
const record = line.slice(prefixIndex + prefix.length);
|
|
4511
|
+
const versionMatch = /(?:^|\s)version_id=(\S*)/.exec(record);
|
|
4512
|
+
const etagMatch = /(?:^|\s)etag=(\S*)/.exec(record);
|
|
4513
|
+
const decode = (value, field) => {
|
|
4514
|
+
if (value === void 0 || value === "") return null;
|
|
4515
|
+
try {
|
|
4516
|
+
return decodeURIComponent(value);
|
|
4517
|
+
} catch (error2) {
|
|
4518
|
+
onMetadataDecodeError?.(
|
|
4519
|
+
field,
|
|
4520
|
+
error2 instanceof URIError ? "uri-malformed" : "decode-failed"
|
|
4521
|
+
);
|
|
4522
|
+
return null;
|
|
4523
|
+
}
|
|
4524
|
+
};
|
|
4525
|
+
return {
|
|
4526
|
+
metadataReported: versionMatch !== null || etagMatch !== null,
|
|
4527
|
+
versionId: decode(versionMatch?.[1], "version_id"),
|
|
4528
|
+
etag: decode(etagMatch?.[1], "etag")
|
|
4529
|
+
};
|
|
4530
|
+
}
|
|
4531
|
+
return { metadataReported: false, versionId: null, etag: null };
|
|
4532
|
+
}
|
|
4011
4533
|
async function uploadSessionArchive(key, body, options) {
|
|
4012
4534
|
const bytes = Buffer.from(body);
|
|
4013
4535
|
if (bytes.byteLength > MAX_SESSION_ARCHIVE_BYTES) {
|
|
@@ -4030,7 +4552,13 @@ async function uploadSessionArchive(key, body, options) {
|
|
|
4030
4552
|
);
|
|
4031
4553
|
}
|
|
4032
4554
|
if (result.timedOut) return transportFailure(bytes.byteLength, "timeout");
|
|
4033
|
-
if (result.code === 0)
|
|
4555
|
+
if (result.code === 0) {
|
|
4556
|
+
return {
|
|
4557
|
+
kind: "ok",
|
|
4558
|
+
bytes: bytes.byteLength,
|
|
4559
|
+
...parseArchivePutMetadata(result.stderr, options.onMetadataDecodeError)
|
|
4560
|
+
};
|
|
4561
|
+
}
|
|
4034
4562
|
if (result.code === EXIT_ARCHIVE_CONFIG_MISSING) {
|
|
4035
4563
|
return { kind: "config-missing", bytes: bytes.byteLength };
|
|
4036
4564
|
}
|
|
@@ -4248,6 +4776,14 @@ async function runSessionArchive({
|
|
|
4248
4776
|
uploadFailures: 0,
|
|
4249
4777
|
skippedBudget: 0,
|
|
4250
4778
|
skippedBudgetIds: [],
|
|
4779
|
+
skippedChanged: 0,
|
|
4780
|
+
skippedChangedSessions: [],
|
|
4781
|
+
skippedUnknown: 0,
|
|
4782
|
+
skippedUnknownIds: [],
|
|
4783
|
+
inventoryNeverArchived: 0,
|
|
4784
|
+
inventoryPriorFailures: 0,
|
|
4785
|
+
inventoryKnownChanged: 0,
|
|
4786
|
+
outcomesReconciled: false,
|
|
4251
4787
|
neverWatermarkedFailures: 0,
|
|
4252
4788
|
unmappedIds: [],
|
|
4253
4789
|
conflictedIds: [],
|
|
@@ -4264,6 +4800,8 @@ async function runSessionArchive({
|
|
|
4264
4800
|
parent: 0
|
|
4265
4801
|
},
|
|
4266
4802
|
archivedSessionIds: [],
|
|
4803
|
+
uploadedSessions: [],
|
|
4804
|
+
unchangedSessions: [],
|
|
4267
4805
|
failures: [],
|
|
4268
4806
|
staleSince: null
|
|
4269
4807
|
};
|
|
@@ -4287,17 +4825,44 @@ async function runSessionArchive({
|
|
|
4287
4825
|
}
|
|
4288
4826
|
summary.unresolved = summary.unmappedIds.length + summary.conflictedIds.length;
|
|
4289
4827
|
summary.conflicts = summary.conflictedIds.length;
|
|
4828
|
+
const priorFailureIds = deps.priorFailureIds ?? /* @__PURE__ */ new Set();
|
|
4829
|
+
const knownChanged = /* @__PURE__ */ new Map();
|
|
4830
|
+
for (const session of sessions) {
|
|
4831
|
+
if (!deps.watermarks.has(session.id)) {
|
|
4832
|
+
knownChanged.set(session.id, "no-prior-archive");
|
|
4833
|
+
summary.inventoryNeverArchived++;
|
|
4834
|
+
} else if (priorFailureIds.has(session.id)) {
|
|
4835
|
+
knownChanged.set(session.id, "prior-attempt-failed");
|
|
4836
|
+
summary.inventoryPriorFailures++;
|
|
4837
|
+
}
|
|
4838
|
+
}
|
|
4839
|
+
summary.inventoryKnownChanged = knownChanged.size;
|
|
4290
4840
|
const failedWatermarks = [];
|
|
4841
|
+
const priorFailureUploads = [];
|
|
4291
4842
|
const recordFailedWatermark = (watermark) => {
|
|
4292
4843
|
if (watermark) failedWatermarks.push(watermark.uploaded_at);
|
|
4293
4844
|
else summary.neverWatermarkedFailures++;
|
|
4294
4845
|
};
|
|
4846
|
+
const recordBudgetSkip = (startIndex) => {
|
|
4847
|
+
const skippedIds = ordered.slice(startIndex).map(({ id }) => id);
|
|
4848
|
+
summary.skippedBudgetIds.push(...skippedIds);
|
|
4849
|
+
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4850
|
+
for (const sessionId of skippedIds) {
|
|
4851
|
+
const reason = knownChanged.get(sessionId);
|
|
4852
|
+
if (reason) {
|
|
4853
|
+
summary.skippedChangedSessions.push({ sessionId, reason });
|
|
4854
|
+
summary.skippedChanged++;
|
|
4855
|
+
} else {
|
|
4856
|
+
summary.skippedUnknownIds.push(sessionId);
|
|
4857
|
+
summary.skippedUnknown++;
|
|
4858
|
+
}
|
|
4859
|
+
}
|
|
4860
|
+
};
|
|
4295
4861
|
for (let index = 0; index < ordered.length; index++) {
|
|
4296
4862
|
const session = ordered[index];
|
|
4297
4863
|
const remainingMs = Math.floor(deadline - now());
|
|
4298
4864
|
if (remainingMs <= 0 || deps.signal?.aborted) {
|
|
4299
|
-
|
|
4300
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4865
|
+
recordBudgetSkip(index);
|
|
4301
4866
|
break;
|
|
4302
4867
|
}
|
|
4303
4868
|
const resolution = resolutions.get(session.id) ?? { reason: "unmapped" };
|
|
@@ -4322,8 +4887,7 @@ async function runSessionArchive({
|
|
|
4322
4887
|
messages = await exportMessages(deps.client, session.id, exportBudget.signal);
|
|
4323
4888
|
} catch (error2) {
|
|
4324
4889
|
if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
|
|
4325
|
-
|
|
4326
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4890
|
+
recordBudgetSkip(index);
|
|
4327
4891
|
break;
|
|
4328
4892
|
}
|
|
4329
4893
|
summary.failed++;
|
|
@@ -4341,8 +4905,7 @@ async function runSessionArchive({
|
|
|
4341
4905
|
exportBudget.dispose();
|
|
4342
4906
|
}
|
|
4343
4907
|
if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
|
|
4344
|
-
|
|
4345
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4908
|
+
recordBudgetSkip(index);
|
|
4346
4909
|
break;
|
|
4347
4910
|
}
|
|
4348
4911
|
try {
|
|
@@ -4361,12 +4924,21 @@ async function runSessionArchive({
|
|
|
4361
4924
|
if (existing?.fingerprint === snapshot.content_fingerprint) {
|
|
4362
4925
|
summary.unchanged++;
|
|
4363
4926
|
summary.archivedSessionIds.push(session.id);
|
|
4927
|
+
summary.unchangedSessions.push({
|
|
4928
|
+
sessionId: session.id,
|
|
4929
|
+
fingerprint: snapshot.content_fingerprint,
|
|
4930
|
+
watermarkKey: existing.key,
|
|
4931
|
+
watermarkFingerprint: existing.fingerprint,
|
|
4932
|
+
watermarkVersionId: existing.version_id ?? null,
|
|
4933
|
+
watermarkEtag: existing.etag ?? null,
|
|
4934
|
+
watermarkUploadedAt: existing.uploaded_at
|
|
4935
|
+
});
|
|
4364
4936
|
continue;
|
|
4365
4937
|
}
|
|
4366
4938
|
const uploadRemainingMs = Math.floor(deadline - now());
|
|
4367
4939
|
if (uploadRemainingMs <= 0 || deps.signal?.aborted) {
|
|
4368
|
-
|
|
4369
|
-
|
|
4940
|
+
knownChanged.set(session.id, "fingerprint-differs");
|
|
4941
|
+
recordBudgetSkip(index);
|
|
4370
4942
|
break;
|
|
4371
4943
|
}
|
|
4372
4944
|
summary.uploadAttempts++;
|
|
@@ -4375,7 +4947,8 @@ async function runSessionArchive({
|
|
|
4375
4947
|
try {
|
|
4376
4948
|
outcome = await upload(key, JSON.stringify(snapshot), {
|
|
4377
4949
|
timeoutMs: Math.min(uploadRemainingMs, SESSION_ARCHIVE_UPLOAD_TIMEOUT_MS),
|
|
4378
|
-
signal: uploadBudget.signal
|
|
4950
|
+
signal: uploadBudget.signal,
|
|
4951
|
+
onMetadataDecodeError: (field, reason) => deps.onMetadataDecodeError?.(field, reason, session.id)
|
|
4379
4952
|
});
|
|
4380
4953
|
} finally {
|
|
4381
4954
|
uploadBudget.dispose();
|
|
@@ -4398,19 +4971,31 @@ async function runSessionArchive({
|
|
|
4398
4971
|
});
|
|
4399
4972
|
recordFailedWatermark(existing);
|
|
4400
4973
|
if (uploadBudget.signal.aborted) {
|
|
4401
|
-
|
|
4402
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
4974
|
+
recordBudgetSkip(index + 1);
|
|
4403
4975
|
break;
|
|
4404
4976
|
}
|
|
4405
4977
|
continue;
|
|
4406
4978
|
}
|
|
4407
4979
|
summary.uploaded++;
|
|
4408
4980
|
summary.archivedSessionIds.push(session.id);
|
|
4981
|
+
const uploadRecord = {
|
|
4982
|
+
sessionId: session.id,
|
|
4983
|
+
key,
|
|
4984
|
+
fingerprint: snapshot.content_fingerprint,
|
|
4985
|
+
versionId: outcome.versionId,
|
|
4986
|
+
etag: outcome.etag,
|
|
4987
|
+
metadataReported: outcome.metadataReported,
|
|
4988
|
+
retriedPriorFailure: priorFailureIds.has(session.id)
|
|
4989
|
+
};
|
|
4990
|
+
if (uploadRecord.retriedPriorFailure) priorFailureUploads.push(uploadRecord);
|
|
4991
|
+
else summary.uploadedSessions.push(uploadRecord);
|
|
4409
4992
|
const watermark = {
|
|
4410
4993
|
fingerprint: snapshot.content_fingerprint,
|
|
4411
4994
|
uploaded_at: new Date(now()).toISOString(),
|
|
4412
4995
|
key,
|
|
4413
|
-
conversation_id: conversationId
|
|
4996
|
+
conversation_id: conversationId,
|
|
4997
|
+
version_id: outcome.versionId,
|
|
4998
|
+
etag: outcome.etag
|
|
4414
4999
|
};
|
|
4415
5000
|
try {
|
|
4416
5001
|
writeWatermark(deps.watermarkPath, session.id, watermark, deps.watermarks);
|
|
@@ -4424,8 +5009,7 @@ async function runSessionArchive({
|
|
|
4424
5009
|
}
|
|
4425
5010
|
} catch (error2) {
|
|
4426
5011
|
if (isBudgetExpired(deadline, now, deps.signal)) {
|
|
4427
|
-
|
|
4428
|
-
summary.skippedBudget = summary.skippedBudgetIds.length;
|
|
5012
|
+
recordBudgetSkip(index);
|
|
4429
5013
|
break;
|
|
4430
5014
|
}
|
|
4431
5015
|
summary.failed++;
|
|
@@ -4438,10 +5022,115 @@ async function runSessionArchive({
|
|
|
4438
5022
|
recordFailedWatermark(deps.watermarks.get(session.id));
|
|
4439
5023
|
}
|
|
4440
5024
|
}
|
|
5025
|
+
summary.uploadedSessions = [...priorFailureUploads, ...summary.uploadedSessions];
|
|
5026
|
+
for (const sessionId of summary.archivedSessionIds) priorFailureIds.delete(sessionId);
|
|
5027
|
+
for (const failure of summary.failures) {
|
|
5028
|
+
if (!failure.archived) priorFailureIds.add(failure.sessionId);
|
|
5029
|
+
}
|
|
5030
|
+
summary.outcomesReconciled = summary.uploaded + summary.unchanged + summary.failed + summary.skippedChanged + summary.skippedUnknown === summary.inspected;
|
|
4441
5031
|
summary.staleSince = failedWatermarks.sort()[0] ?? null;
|
|
4442
5032
|
return summary;
|
|
4443
5033
|
}
|
|
4444
5034
|
|
|
5035
|
+
// src/lib/opencode/session-archive-manifest.ts
|
|
5036
|
+
var SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION = 1;
|
|
5037
|
+
function sessionArchiveManifestKey(keyPrefix, identity) {
|
|
5038
|
+
return `${keyPrefix.replace(/\/+$/, "")}/archive-audit/${identity.bootId}-${String(identity.passSequence).padStart(4, "0")}-${identity.phase}.json`;
|
|
5039
|
+
}
|
|
5040
|
+
function buildSessionArchiveManifest(identity, summary) {
|
|
5041
|
+
const failedSessions = summary?.failures.filter(({ archived }) => !archived) ?? [];
|
|
5042
|
+
const watermarkWriteFailures = new Set(
|
|
5043
|
+
summary?.failures.filter(({ archived }) => archived).map(({ sessionId }) => sessionId)
|
|
5044
|
+
);
|
|
5045
|
+
const sessions = summary ? [
|
|
5046
|
+
...summary.uploadedSessions.map((upload) => ({
|
|
5047
|
+
id: upload.sessionId,
|
|
5048
|
+
outcome: "uploaded",
|
|
5049
|
+
archive_key: upload.key,
|
|
5050
|
+
fingerprint: upload.fingerprint,
|
|
5051
|
+
version_id: upload.versionId,
|
|
5052
|
+
etag: upload.etag,
|
|
5053
|
+
object_metadata_reported: upload.metadataReported,
|
|
5054
|
+
retried_prior_failure: upload.retriedPriorFailure,
|
|
5055
|
+
...watermarkWriteFailures.has(upload.sessionId) ? { watermark_write_failed: true } : {}
|
|
5056
|
+
})),
|
|
5057
|
+
...summary.unchangedSessions.map((unchanged) => ({
|
|
5058
|
+
id: unchanged.sessionId,
|
|
5059
|
+
outcome: "unchanged",
|
|
5060
|
+
fingerprint: unchanged.fingerprint,
|
|
5061
|
+
watermark_fingerprint: unchanged.watermarkFingerprint,
|
|
5062
|
+
watermark_key: unchanged.watermarkKey,
|
|
5063
|
+
watermark_version_id: unchanged.watermarkVersionId,
|
|
5064
|
+
watermark_etag: unchanged.watermarkEtag,
|
|
5065
|
+
watermark_uploaded_at: unchanged.watermarkUploadedAt
|
|
5066
|
+
})),
|
|
5067
|
+
...failedSessions.map((failure) => ({
|
|
5068
|
+
id: failure.sessionId,
|
|
5069
|
+
outcome: "failed",
|
|
5070
|
+
failure_outcome: failure.outcome,
|
|
5071
|
+
...failure.reason !== void 0 ? { reason: failure.reason } : {},
|
|
5072
|
+
...failure.bytes !== void 0 ? { payload_bytes: failure.bytes } : {},
|
|
5073
|
+
...failure.byteLimit !== void 0 ? { payload_limit_bytes: failure.byteLimit } : {},
|
|
5074
|
+
...failure.messageCount !== void 0 ? { message_count: failure.messageCount } : {},
|
|
5075
|
+
...failure.partCount !== void 0 ? { part_count: failure.partCount } : {},
|
|
5076
|
+
...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
|
|
5077
|
+
})),
|
|
5078
|
+
...summary.skippedChangedSessions.map((skipped) => ({
|
|
5079
|
+
id: skipped.sessionId,
|
|
5080
|
+
outcome: "skipped-changed",
|
|
5081
|
+
reason: skipped.reason
|
|
5082
|
+
})),
|
|
5083
|
+
...summary.skippedUnknownIds.map((sessionId) => ({
|
|
5084
|
+
id: sessionId,
|
|
5085
|
+
outcome: "skipped-unknown"
|
|
5086
|
+
}))
|
|
5087
|
+
] : [];
|
|
5088
|
+
return {
|
|
5089
|
+
schema_version: SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION,
|
|
5090
|
+
runner_id: identity.runnerId,
|
|
5091
|
+
boot_id: identity.bootId,
|
|
5092
|
+
pass_sequence: identity.passSequence,
|
|
5093
|
+
phase: identity.phase,
|
|
5094
|
+
started_at: identity.startedAt,
|
|
5095
|
+
completed_at: identity.completedAt,
|
|
5096
|
+
budget_ms: identity.budgetMs,
|
|
5097
|
+
enumeration_complete: identity.enumerationComplete,
|
|
5098
|
+
enumeration_reason: identity.enumerationReason,
|
|
5099
|
+
watermark_file_present: identity.watermarkFilePresent,
|
|
5100
|
+
watermarks_loaded: identity.watermarksLoaded,
|
|
5101
|
+
inspected: summary?.inspected ?? 0,
|
|
5102
|
+
counts: {
|
|
5103
|
+
uploaded: summary?.uploaded ?? 0,
|
|
5104
|
+
unchanged: summary?.unchanged ?? 0,
|
|
5105
|
+
failed: failedSessions.length,
|
|
5106
|
+
skipped_changed: summary?.skippedChanged ?? 0,
|
|
5107
|
+
skipped_unknown: summary?.skippedUnknown ?? 0
|
|
5108
|
+
},
|
|
5109
|
+
outcomes_reconciled: summary?.outcomesReconciled ?? null,
|
|
5110
|
+
inventory_never_archived: summary?.inventoryNeverArchived ?? 0,
|
|
5111
|
+
inventory_prior_failures: summary?.inventoryPriorFailures ?? 0,
|
|
5112
|
+
sessions
|
|
5113
|
+
};
|
|
5114
|
+
}
|
|
5115
|
+
async function uploadSessionArchiveManifest({
|
|
5116
|
+
keyPrefix,
|
|
5117
|
+
identity,
|
|
5118
|
+
summary,
|
|
5119
|
+
timeoutMs,
|
|
5120
|
+
signal,
|
|
5121
|
+
onMetadataDecodeError,
|
|
5122
|
+
upload
|
|
5123
|
+
}) {
|
|
5124
|
+
const key = sessionArchiveManifestKey(keyPrefix, identity);
|
|
5125
|
+
const manifest = buildSessionArchiveManifest(identity, summary);
|
|
5126
|
+
const outcome = await (upload ?? uploadSessionArchive)(key, JSON.stringify(manifest), {
|
|
5127
|
+
timeoutMs,
|
|
5128
|
+
signal,
|
|
5129
|
+
onMetadataDecodeError
|
|
5130
|
+
});
|
|
5131
|
+
return { key, outcome };
|
|
5132
|
+
}
|
|
5133
|
+
|
|
4445
5134
|
// src/lib/opencode/auth.ts
|
|
4446
5135
|
function buildOpenCodeBasicAuthHeader(password) {
|
|
4447
5136
|
return `Basic ${Buffer.from(["opencode", password].join(":")).toString("base64")}`;
|
|
@@ -4548,9 +5237,11 @@ async function checkOpenCode2Health(port, password) {
|
|
|
4548
5237
|
return { healthy: false, error: message };
|
|
4549
5238
|
}
|
|
4550
5239
|
}
|
|
4551
|
-
async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
5240
|
+
async function waitForOpenCodeHealth(port, timeoutMs = 3e4, stopEarly) {
|
|
4552
5241
|
const startTime = Date.now();
|
|
4553
5242
|
while (Date.now() - startTime < timeoutMs) {
|
|
5243
|
+
const earlyStopReason = stopEarly?.();
|
|
5244
|
+
if (earlyStopReason) return { healthy: false, error: earlyStopReason };
|
|
4554
5245
|
const health = await checkOpenCodeHealth(port);
|
|
4555
5246
|
if (health.healthy || health.authFailed) {
|
|
4556
5247
|
return health;
|
|
@@ -4559,9 +5250,11 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
4559
5250
|
}
|
|
4560
5251
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
4561
5252
|
}
|
|
4562
|
-
async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
|
|
5253
|
+
async function waitForOpenCode2Health(port, password, timeoutMs = 3e4, stopEarly) {
|
|
4563
5254
|
const startTime = Date.now();
|
|
4564
5255
|
while (Date.now() - startTime < timeoutMs) {
|
|
5256
|
+
const earlyStopReason = stopEarly?.();
|
|
5257
|
+
if (earlyStopReason) return { healthy: false, error: earlyStopReason };
|
|
4565
5258
|
const health = await checkOpenCode2Health(port, password);
|
|
4566
5259
|
if (health.healthy || health.authFailed) {
|
|
4567
5260
|
return health;
|
|
@@ -7630,7 +8323,7 @@ function reportedOpenCodeVersion(input) {
|
|
|
7630
8323
|
|
|
7631
8324
|
// src/lib/opencode/process.ts
|
|
7632
8325
|
import { execSync, spawn as spawn3 } from "child_process";
|
|
7633
|
-
import { randomBytes } from "node:crypto";
|
|
8326
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
7634
8327
|
|
|
7635
8328
|
// src/lib/process-stop.ts
|
|
7636
8329
|
async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
@@ -7745,28 +8438,29 @@ function getProcessCwd(pid) {
|
|
|
7745
8438
|
}
|
|
7746
8439
|
return void 0;
|
|
7747
8440
|
}
|
|
7748
|
-
function
|
|
7749
|
-
|
|
7750
|
-
|
|
7751
|
-
|
|
7752
|
-
|
|
7753
|
-
|
|
7754
|
-
|
|
7755
|
-
|
|
7756
|
-
|
|
8441
|
+
function watchOpenCodeExit(child, log3) {
|
|
8442
|
+
let spawnError = null;
|
|
8443
|
+
child.once("error", (error2) => {
|
|
8444
|
+
spawnError = error2;
|
|
8445
|
+
const code = spawnError.code ?? "unknown error";
|
|
8446
|
+
log3(
|
|
8447
|
+
`[watchOpenCodeExit] OpenCode command ${child.spawnfile ?? "unknown"} could not be spawned: ${code}: ${spawnError.message}`,
|
|
8448
|
+
"error"
|
|
8449
|
+
);
|
|
8450
|
+
});
|
|
8451
|
+
return () => {
|
|
8452
|
+
if (spawnError) {
|
|
8453
|
+
const code = spawnError.code ?? "unknown error";
|
|
8454
|
+
return `it could not be spawned (${code}: ${spawnError.message})`;
|
|
7757
8455
|
}
|
|
7758
|
-
|
|
7759
|
-
|
|
7760
|
-
return false;
|
|
7761
|
-
}
|
|
7762
|
-
function findAvailablePort(startPort, maxAttempts = 10) {
|
|
7763
|
-
for (let i = 0; i < maxAttempts; i++) {
|
|
7764
|
-
const port = startPort + i;
|
|
7765
|
-
if (!isPortInUse(port)) {
|
|
7766
|
-
return port;
|
|
8456
|
+
if (child.signalCode !== null && child.signalCode !== void 0) {
|
|
8457
|
+
return `it was killed by ${child.signalCode} before it answered`;
|
|
7767
8458
|
}
|
|
7768
|
-
|
|
7769
|
-
|
|
8459
|
+
if (child.exitCode !== null && child.exitCode !== void 0) {
|
|
8460
|
+
return `it exited with status ${child.exitCode} before it answered`;
|
|
8461
|
+
}
|
|
8462
|
+
return null;
|
|
8463
|
+
};
|
|
7770
8464
|
}
|
|
7771
8465
|
function findProcessesByPattern(pgrepPattern, psPattern) {
|
|
7772
8466
|
const instances = [];
|
|
@@ -7908,7 +8602,7 @@ async function startOpenCode(port, options = {}) {
|
|
|
7908
8602
|
return child;
|
|
7909
8603
|
}
|
|
7910
8604
|
async function startOpenCode2(port, options = {}) {
|
|
7911
|
-
const password =
|
|
8605
|
+
const password = randomBytes2(24).toString("hex");
|
|
7912
8606
|
let command = options.command ?? "opencode2";
|
|
7913
8607
|
const logLevel = options.inheritStdio ? ["--log-level", resolveOpenCode2LogLevel(process.env)] : [];
|
|
7914
8608
|
let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...logLevel];
|
|
@@ -7956,6 +8650,144 @@ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
|
|
|
7956
8650
|
);
|
|
7957
8651
|
}
|
|
7958
8652
|
|
|
8653
|
+
// src/lib/opencode/port.ts
|
|
8654
|
+
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
8655
|
+
import { createServer as createServer2 } from "node:net";
|
|
8656
|
+
var HOLDER_LOOKUP_TIMEOUT_MS = 250;
|
|
8657
|
+
var RECLAIM_SIGNAL_WAIT_MS = 250;
|
|
8658
|
+
var RECLAIM_POLL_INTERVAL_MS = 25;
|
|
8659
|
+
function isPortInUse(port) {
|
|
8660
|
+
return new Promise((resolve6) => {
|
|
8661
|
+
const server = createServer2();
|
|
8662
|
+
server.once("error", () => resolve6(true));
|
|
8663
|
+
server.listen({ port, host: "127.0.0.1", exclusive: true }, () => {
|
|
8664
|
+
server.close(() => resolve6(false));
|
|
8665
|
+
});
|
|
8666
|
+
});
|
|
8667
|
+
}
|
|
8668
|
+
async function findAvailablePort(startPort, maxAttempts = 10) {
|
|
8669
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
8670
|
+
const port = startPort + i;
|
|
8671
|
+
if (!await isPortInUse(port)) return port;
|
|
8672
|
+
}
|
|
8673
|
+
return null;
|
|
8674
|
+
}
|
|
8675
|
+
function outputText(value) {
|
|
8676
|
+
if (typeof value === "string") return value;
|
|
8677
|
+
if (Buffer.isBuffer(value)) return value.toString("utf8");
|
|
8678
|
+
return value === void 0 || value === null ? "" : String(value);
|
|
8679
|
+
}
|
|
8680
|
+
function holderPids(stdout) {
|
|
8681
|
+
const tokens = stdout.trim() ? stdout.trim().split(/\s+/) : [];
|
|
8682
|
+
if (tokens.length === 0) return [];
|
|
8683
|
+
if (!tokens.every((token) => /^\d+$/.test(token))) return null;
|
|
8684
|
+
return tokens.map(Number);
|
|
8685
|
+
}
|
|
8686
|
+
function isExecTimeout(error2) {
|
|
8687
|
+
if (!error2 || typeof error2 !== "object") return false;
|
|
8688
|
+
const candidate = error2;
|
|
8689
|
+
return candidate.code === "ETIMEDOUT" || candidate.killed === true && candidate.signal === "SIGKILL";
|
|
8690
|
+
}
|
|
8691
|
+
function listLoopbackPortHolders(port) {
|
|
8692
|
+
try {
|
|
8693
|
+
const stdout = outputText(
|
|
8694
|
+
execFileSync2("fuser", ["-n", "tcp", String(port)], {
|
|
8695
|
+
encoding: "utf8",
|
|
8696
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
8697
|
+
// The resume path must not wait indefinitely on a broken /proc read.
|
|
8698
|
+
timeout: HOLDER_LOOKUP_TIMEOUT_MS,
|
|
8699
|
+
killSignal: "SIGKILL"
|
|
8700
|
+
})
|
|
8701
|
+
);
|
|
8702
|
+
const pids = holderPids(stdout);
|
|
8703
|
+
return pids !== null && pids.length > 0 ? pids : { error: "fuser failed to identify the port holder" };
|
|
8704
|
+
} catch (error2) {
|
|
8705
|
+
const candidate = error2;
|
|
8706
|
+
const stdout = outputText(candidate.stdout);
|
|
8707
|
+
const stderr = outputText(candidate.stderr);
|
|
8708
|
+
const pids = holderPids(stdout);
|
|
8709
|
+
if (pids === null) return { error: "fuser failed to identify the port holder" };
|
|
8710
|
+
if (pids.length > 0) return pids;
|
|
8711
|
+
if (candidate.code === "ENOENT") return { error: "fuser is unavailable" };
|
|
8712
|
+
if (isExecTimeout(error2)) return { error: "fuser timed out while identifying the port holder" };
|
|
8713
|
+
if (candidate.status === 1 && stderr.trim() === "") return [];
|
|
8714
|
+
return { error: "fuser failed to identify the port holder" };
|
|
8715
|
+
}
|
|
8716
|
+
}
|
|
8717
|
+
async function identifyHolders(listHolders) {
|
|
8718
|
+
let timer;
|
|
8719
|
+
const timeout = new Promise((resolve6) => {
|
|
8720
|
+
timer = setTimeout(
|
|
8721
|
+
() => resolve6({ error: "holder identification timed out" }),
|
|
8722
|
+
HOLDER_LOOKUP_TIMEOUT_MS
|
|
8723
|
+
);
|
|
8724
|
+
});
|
|
8725
|
+
try {
|
|
8726
|
+
return await Promise.race([Promise.resolve().then(listHolders), timeout]);
|
|
8727
|
+
} catch (error2) {
|
|
8728
|
+
return {
|
|
8729
|
+
error: `holder identification failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
8730
|
+
};
|
|
8731
|
+
} finally {
|
|
8732
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
8733
|
+
}
|
|
8734
|
+
}
|
|
8735
|
+
function isErrno(error2, code) {
|
|
8736
|
+
return error2 !== null && typeof error2 === "object" && "code" in error2 && error2.code === code;
|
|
8737
|
+
}
|
|
8738
|
+
function signalHolders(pids, signal) {
|
|
8739
|
+
let failure = null;
|
|
8740
|
+
for (const pid of pids) {
|
|
8741
|
+
try {
|
|
8742
|
+
process.kill(pid, signal);
|
|
8743
|
+
} catch (error2) {
|
|
8744
|
+
if (isErrno(error2, "ESRCH")) continue;
|
|
8745
|
+
failure ??= `could not send ${signal} to holder ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`;
|
|
8746
|
+
}
|
|
8747
|
+
}
|
|
8748
|
+
return failure;
|
|
8749
|
+
}
|
|
8750
|
+
async function waitForPortFree(port, waitMs) {
|
|
8751
|
+
const deadline = Date.now() + waitMs;
|
|
8752
|
+
let probeError;
|
|
8753
|
+
for (; ; ) {
|
|
8754
|
+
try {
|
|
8755
|
+
if (!await isPortInUse(port)) return { free: true };
|
|
8756
|
+
} catch (error2) {
|
|
8757
|
+
probeError = error2 instanceof Error ? error2.message : String(error2);
|
|
8758
|
+
}
|
|
8759
|
+
const remaining = deadline - Date.now();
|
|
8760
|
+
if (remaining <= 0) return { free: false, detail: probeError };
|
|
8761
|
+
await new Promise(
|
|
8762
|
+
(resolve6) => setTimeout(resolve6, Math.min(RECLAIM_POLL_INTERVAL_MS, remaining))
|
|
8763
|
+
);
|
|
8764
|
+
}
|
|
8765
|
+
}
|
|
8766
|
+
async function reclaimLoopbackPort(port, options = {}) {
|
|
8767
|
+
const holderResult = await identifyHolders(
|
|
8768
|
+
options.listHolders ?? (() => listLoopbackPortHolders(port))
|
|
8769
|
+
);
|
|
8770
|
+
if (!Array.isArray(holderResult)) {
|
|
8771
|
+
return { kind: "blocked", port, detail: holderResult.error };
|
|
8772
|
+
}
|
|
8773
|
+
if (holderResult.length === 0) return { kind: "no-holder", port };
|
|
8774
|
+
const termFailure = signalHolders(holderResult, "SIGTERM");
|
|
8775
|
+
const afterTerm = await waitForPortFree(port, RECLAIM_SIGNAL_WAIT_MS);
|
|
8776
|
+
if (afterTerm.free && termFailure === null) {
|
|
8777
|
+
return { kind: "freed", port, pids: holderResult, usedSigkill: false };
|
|
8778
|
+
}
|
|
8779
|
+
const killFailure = signalHolders(holderResult, "SIGKILL");
|
|
8780
|
+
const afterKill = await waitForPortFree(port, RECLAIM_SIGNAL_WAIT_MS);
|
|
8781
|
+
if (!afterKill.free) {
|
|
8782
|
+
return {
|
|
8783
|
+
kind: "blocked",
|
|
8784
|
+
port,
|
|
8785
|
+
detail: afterKill.detail ?? termFailure ?? killFailure ?? "the port remained in use after SIGTERM and SIGKILL"
|
|
8786
|
+
};
|
|
8787
|
+
}
|
|
8788
|
+
return { kind: "freed", port, pids: holderResult, usedSigkill: true };
|
|
8789
|
+
}
|
|
8790
|
+
|
|
7959
8791
|
// src/lib/opencode/install.ts
|
|
7960
8792
|
import { execSync as execSync2 } from "child_process";
|
|
7961
8793
|
import chalk4 from "chalk";
|
|
@@ -10153,6 +10985,12 @@ var ChannelTerminalError = class extends Error {
|
|
|
10153
10985
|
this.status = status2;
|
|
10154
10986
|
}
|
|
10155
10987
|
};
|
|
10988
|
+
var LocalOpenCodeError = class extends Error {
|
|
10989
|
+
constructor(message, options) {
|
|
10990
|
+
super(message, options);
|
|
10991
|
+
this.name = "LocalOpenCodeError";
|
|
10992
|
+
}
|
|
10993
|
+
};
|
|
10156
10994
|
function backoffDelay(attempt, policy) {
|
|
10157
10995
|
const exp = policy.baseDelayMs * Math.pow(2, attempt);
|
|
10158
10996
|
const capped = Math.min(policy.maxDelayMs, exp);
|
|
@@ -10329,6 +11167,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
10329
11167
|
awaitingCorrelation = /* @__PURE__ */ new Map();
|
|
10330
11168
|
/** Pending rows seen in the current drain, used to retain terminal dispatch fences. */
|
|
10331
11169
|
pendingMessageIds = /* @__PURE__ */ new Set();
|
|
11170
|
+
/** `processing` rows seen in the current drain, for `outstandingQueuedWork()`. */
|
|
11171
|
+
processingMessageIds = /* @__PURE__ */ new Set();
|
|
11172
|
+
outstandingQueuedMessageCount = 0;
|
|
10332
11173
|
/**
|
|
10333
11174
|
* "markDone for this row is TERMINALLY undeliverable" (Bug 4). Set ONLY when a
|
|
10334
11175
|
* re-adopted DONE row's `markDone` returned a terminal 4xx (a status that will
|
|
@@ -10584,7 +11425,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
10584
11425
|
return this.isV2 ? isV2SessionOngoing(this.openCodeClient, sessionId) : isSessionOngoing(this.port, sessionId, this.openCodeClient);
|
|
10585
11426
|
}
|
|
10586
11427
|
async createOpenCodeSession(directory) {
|
|
10587
|
-
|
|
11428
|
+
try {
|
|
11429
|
+
return await (this.isV2 ? createV2Session(this.openCodeClient, directory) : createOpenCodeSession(this.port, directory, this.openCodeClient));
|
|
11430
|
+
} catch (err) {
|
|
11431
|
+
throw new LocalOpenCodeError(
|
|
11432
|
+
`creating an OpenCode session on port ${this.port} failed: ${describeErrorWithCause(err)}`,
|
|
11433
|
+
{ cause: err }
|
|
11434
|
+
);
|
|
11435
|
+
}
|
|
10588
11436
|
}
|
|
10589
11437
|
async hasAnyConfiguredProvider() {
|
|
10590
11438
|
return hasAnyConfiguredProvider(this.port, this.openCodeClient);
|
|
@@ -10742,6 +11590,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
10742
11590
|
});
|
|
10743
11591
|
}
|
|
10744
11592
|
await this.readoptProcessing();
|
|
11593
|
+
this.outstandingQueuedMessageCount = (/* @__PURE__ */ new Set([
|
|
11594
|
+
...this.pendingMessageIds,
|
|
11595
|
+
...this.processingMessageIds
|
|
11596
|
+
])).size;
|
|
10745
11597
|
} finally {
|
|
10746
11598
|
this.draining = false;
|
|
10747
11599
|
}
|
|
@@ -10759,6 +11611,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
10759
11611
|
}
|
|
10760
11612
|
return false;
|
|
10761
11613
|
}
|
|
11614
|
+
/**
|
|
11615
|
+
* Number of distinct non-terminal queued messages (`pending` plus `processing`)
|
|
11616
|
+
* observed by the last completed drain. `run.ts` treats a non-zero value as not
|
|
11617
|
+
* idle. A drain that could not complete both fetches leaves the previous value standing.
|
|
11618
|
+
*/
|
|
11619
|
+
outstandingQueuedWork() {
|
|
11620
|
+
return this.outstandingQueuedMessageCount;
|
|
11621
|
+
}
|
|
10762
11622
|
/**
|
|
10763
11623
|
* Session ids active *for the `--max-active-sessions` cap*: in-flight work AND
|
|
10764
11624
|
* a live watcher loop. Unlike `hasInFlightWatchers()` / `protectedSessionIds()`,
|
|
@@ -13874,6 +14734,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
13874
14734
|
*/
|
|
13875
14735
|
async readoptProcessing() {
|
|
13876
14736
|
const rows = await this.getProcessingMessages();
|
|
14737
|
+
this.processingMessageIds.clear();
|
|
14738
|
+
for (const row of rows) this.processingMessageIds.add(row.id);
|
|
13877
14739
|
if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0 || this.readoptPollUnresolvedSignalled.size > 0) {
|
|
13878
14740
|
const stillProcessing = new Set(rows.map((r) => r.id));
|
|
13879
14741
|
for (const id of [
|
|
@@ -15943,12 +16805,19 @@ import chalk5 from "chalk";
|
|
|
15943
16805
|
import ora2 from "ora";
|
|
15944
16806
|
import { select as select2 } from "@inquirer/prompts";
|
|
15945
16807
|
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
15946
|
-
function
|
|
15947
|
-
|
|
16808
|
+
async function reclaimNonInteractivePort(port, options) {
|
|
16809
|
+
const isPortInUseFn = options.isPortInUse ?? isPortInUse;
|
|
16810
|
+
if (!await isPortInUseFn(port)) return void 0;
|
|
16811
|
+
if (!options.imageManaged) {
|
|
15948
16812
|
throw new Error(
|
|
15949
16813
|
`Port ${port} is already in use by a non-OpenCode process. Free it or pass --port.`
|
|
15950
16814
|
);
|
|
15951
16815
|
}
|
|
16816
|
+
const outcome = await (options.reclaimLoopbackPort ?? reclaimLoopbackPort)(port);
|
|
16817
|
+
if (outcome.kind !== "blocked") return outcome;
|
|
16818
|
+
throw new Error(
|
|
16819
|
+
`Port ${port} is held by an unresponsive process. Evident tried to reclaim it but could not free it: ${outcome.detail}. Stop the holder manually or pass --port.`
|
|
16820
|
+
);
|
|
15952
16821
|
}
|
|
15953
16822
|
function unknownPasswordError(port) {
|
|
15954
16823
|
return new Error(
|
|
@@ -16005,24 +16874,29 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
16005
16874
|
}
|
|
16006
16875
|
}
|
|
16007
16876
|
if (!ctx.interactive) {
|
|
16008
|
-
|
|
16877
|
+
const reclaimOutcome = await reclaimNonInteractivePort(ctx.port, {
|
|
16878
|
+
imageManaged: ctx.inheritStdio === true
|
|
16879
|
+
});
|
|
16009
16880
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
16010
16881
|
const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
|
|
16011
|
-
const
|
|
16882
|
+
const stopEarly = watchOpenCodeExit(proc, ctx.log);
|
|
16883
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs, stopEarly);
|
|
16012
16884
|
if (!health.healthy) {
|
|
16013
16885
|
if (health.authFailed) {
|
|
16014
16886
|
return {
|
|
16015
16887
|
port: ctx.port,
|
|
16016
16888
|
process: proc,
|
|
16017
16889
|
version: null,
|
|
16018
|
-
notReadyReason: "it is answering with an authentication challenge, likely because OPENCODE_SERVER_PASSWORD is set in the environment of the process that started it
|
|
16890
|
+
notReadyReason: "it is answering with an authentication challenge, likely because OPENCODE_SERVER_PASSWORD is set in the environment of the process that started it",
|
|
16891
|
+
...reclaimOutcome ? { reclaimOutcome } : {}
|
|
16019
16892
|
};
|
|
16020
16893
|
}
|
|
16021
16894
|
return {
|
|
16022
16895
|
port: ctx.port,
|
|
16023
16896
|
process: proc,
|
|
16024
16897
|
version: null,
|
|
16025
|
-
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s
|
|
16898
|
+
notReadyReason: stopEarly() ?? `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s; raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV})`,
|
|
16899
|
+
...reclaimOutcome ? { reclaimOutcome } : {}
|
|
16026
16900
|
};
|
|
16027
16901
|
}
|
|
16028
16902
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
@@ -16030,14 +16904,15 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
16030
16904
|
port: ctx.port,
|
|
16031
16905
|
process: proc,
|
|
16032
16906
|
version: health.version ?? null,
|
|
16033
|
-
notReadyReason: null
|
|
16907
|
+
notReadyReason: null,
|
|
16908
|
+
...reclaimOutcome ? { reclaimOutcome } : {}
|
|
16034
16909
|
};
|
|
16035
16910
|
}
|
|
16036
16911
|
let port = ctx.port;
|
|
16037
|
-
if (isPortInUse(port)) {
|
|
16912
|
+
if (await isPortInUse(port)) {
|
|
16038
16913
|
console.log(chalk5.yellow(`
|
|
16039
16914
|
Port ${port} is already in use.`));
|
|
16040
|
-
const alternativePort = findAvailablePort(port + 1);
|
|
16915
|
+
const alternativePort = await findAvailablePort(port + 1);
|
|
16041
16916
|
if (alternativePort) {
|
|
16042
16917
|
const useAlternative = await select2({
|
|
16043
16918
|
message: `Use port ${alternativePort} instead?`,
|
|
@@ -16084,13 +16959,15 @@ Port ${port} is already in use.`));
|
|
|
16084
16959
|
if (action === "start") {
|
|
16085
16960
|
const spinner = ora2("Starting OpenCode...").start();
|
|
16086
16961
|
const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
|
|
16087
|
-
const
|
|
16962
|
+
const stopEarly = watchOpenCodeExit(proc, ctx.log);
|
|
16963
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS, stopEarly);
|
|
16088
16964
|
if (!health.healthy) {
|
|
16089
16965
|
spinner.fail("Failed to start OpenCode");
|
|
16090
16966
|
if (health.authFailed) {
|
|
16091
16967
|
throw unknownPasswordError(port);
|
|
16092
16968
|
}
|
|
16093
|
-
|
|
16969
|
+
const exitReason = stopEarly();
|
|
16970
|
+
throw new Error(`OpenCode failed to start${exitReason ? `: ${exitReason}` : ""}`);
|
|
16094
16971
|
}
|
|
16095
16972
|
spinner.stop();
|
|
16096
16973
|
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
@@ -16129,40 +17006,24 @@ async function ensureOpenCode2Running(ctx) {
|
|
|
16129
17006
|
}
|
|
16130
17007
|
let port = ctx.port;
|
|
16131
17008
|
if (!ctx.interactive) {
|
|
16132
|
-
|
|
16133
|
-
|
|
16134
|
-
|
|
16135
|
-
Port ${port} is already in use.`));
|
|
16136
|
-
const alternativePort = findAvailablePort(port + 1);
|
|
16137
|
-
if (alternativePort) {
|
|
16138
|
-
const useAlternative = await select3({
|
|
16139
|
-
message: `Use port ${alternativePort} instead?`,
|
|
16140
|
-
choices: [
|
|
16141
|
-
{ name: `Yes, use port ${alternativePort}`, value: "yes" },
|
|
16142
|
-
{ name: "No, I will free the port manually", value: "no" }
|
|
16143
|
-
]
|
|
16144
|
-
});
|
|
16145
|
-
if (useAlternative === "yes") {
|
|
16146
|
-
port = alternativePort;
|
|
16147
|
-
} else {
|
|
16148
|
-
throw new Error(`Port ${ctx.port} is in use`);
|
|
16149
|
-
}
|
|
16150
|
-
}
|
|
16151
|
-
}
|
|
16152
|
-
if (!ctx.interactive) {
|
|
17009
|
+
const reclaimOutcome = await reclaimNonInteractivePort(port, {
|
|
17010
|
+
imageManaged: ctx.inheritStdio === true
|
|
17011
|
+
});
|
|
16153
17012
|
ctx.log(`OpenCode V2 is not running on port ${port}. Starting it automatically...`);
|
|
16154
17013
|
const { child: proc, password } = await startOpenCode2(port, {
|
|
16155
17014
|
inheritStdio: ctx.inheritStdio,
|
|
16156
17015
|
command: ctx.command
|
|
16157
17016
|
});
|
|
16158
|
-
const
|
|
17017
|
+
const stopEarly = watchOpenCodeExit(proc, ctx.log);
|
|
17018
|
+
const health = await waitForOpenCode2Health(port, password, ctx.startTimeoutMs, stopEarly);
|
|
16159
17019
|
if (!health.healthy) {
|
|
16160
17020
|
return {
|
|
16161
17021
|
port,
|
|
16162
17022
|
process: proc,
|
|
16163
17023
|
version: null,
|
|
16164
|
-
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`,
|
|
16165
|
-
password
|
|
17024
|
+
notReadyReason: stopEarly() ?? `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s; raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV})`,
|
|
17025
|
+
password,
|
|
17026
|
+
...reclaimOutcome ? { reclaimOutcome } : {}
|
|
16166
17027
|
};
|
|
16167
17028
|
}
|
|
16168
17029
|
ctx.log(`OpenCode V2 started on port ${port}${health.version ? ` (v${health.version})` : ""}`);
|
|
@@ -16171,8 +17032,27 @@ Port ${port} is already in use.`));
|
|
|
16171
17032
|
process: proc,
|
|
16172
17033
|
version: health.version ?? null,
|
|
16173
17034
|
notReadyReason: null,
|
|
16174
|
-
password
|
|
17035
|
+
password,
|
|
17036
|
+
...reclaimOutcome ? { reclaimOutcome } : {}
|
|
16175
17037
|
};
|
|
17038
|
+
} else if (await isPortInUse(port)) {
|
|
17039
|
+
console.log(chalk6.yellow(`
|
|
17040
|
+
Port ${port} is already in use.`));
|
|
17041
|
+
const alternativePort = await findAvailablePort(port + 1);
|
|
17042
|
+
if (alternativePort) {
|
|
17043
|
+
const useAlternative = await select3({
|
|
17044
|
+
message: `Use port ${alternativePort} instead?`,
|
|
17045
|
+
choices: [
|
|
17046
|
+
{ name: `Yes, use port ${alternativePort}`, value: "yes" },
|
|
17047
|
+
{ name: "No, I will free the port manually", value: "no" }
|
|
17048
|
+
]
|
|
17049
|
+
});
|
|
17050
|
+
if (useAlternative === "yes") {
|
|
17051
|
+
port = alternativePort;
|
|
17052
|
+
} else {
|
|
17053
|
+
throw new Error(`Port ${ctx.port} is in use`);
|
|
17054
|
+
}
|
|
17055
|
+
}
|
|
16176
17056
|
}
|
|
16177
17057
|
const command = ctx.command ?? "opencode2";
|
|
16178
17058
|
const action = await select3({
|
|
@@ -16209,10 +17089,17 @@ Port ${port} is already in use.`));
|
|
|
16209
17089
|
inheritStdio: ctx.inheritStdio,
|
|
16210
17090
|
command: ctx.command
|
|
16211
17091
|
});
|
|
16212
|
-
const
|
|
17092
|
+
const stopEarly = watchOpenCodeExit(proc, ctx.log);
|
|
17093
|
+
const health = await waitForOpenCode2Health(
|
|
17094
|
+
port,
|
|
17095
|
+
password,
|
|
17096
|
+
INTERACTIVE_START_TIMEOUT_MS2,
|
|
17097
|
+
stopEarly
|
|
17098
|
+
);
|
|
16213
17099
|
if (!health.healthy) {
|
|
16214
17100
|
spinner.fail("Failed to start OpenCode V2");
|
|
16215
|
-
|
|
17101
|
+
const exitReason = stopEarly();
|
|
17102
|
+
throw new Error(`OpenCode V2 failed to start${exitReason ? `: ${exitReason}` : ""}`);
|
|
16216
17103
|
}
|
|
16217
17104
|
spinner.stop();
|
|
16218
17105
|
return {
|
|
@@ -16508,7 +17395,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
|
|
|
16508
17395
|
}
|
|
16509
17396
|
|
|
16510
17397
|
// src/lib/opencode/config-overlay.ts
|
|
16511
|
-
import { execFileSync as
|
|
17398
|
+
import { execFileSync as execFileSync3 } from "node:child_process";
|
|
16512
17399
|
import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
|
|
16513
17400
|
import { isAbsolute as isAbsolute5, join as join15, resolve as resolve5 } from "node:path";
|
|
16514
17401
|
function parseConfigContent(content) {
|
|
@@ -16550,7 +17437,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
16550
17437
|
}
|
|
16551
17438
|
copyFileSync(source, join15(cwd, target));
|
|
16552
17439
|
try {
|
|
16553
|
-
|
|
17440
|
+
execFileSync3("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
|
|
16554
17441
|
stdio: "ignore"
|
|
16555
17442
|
});
|
|
16556
17443
|
} catch (error2) {
|
|
@@ -17320,7 +18207,6 @@ function resolveFileSyncExactFiles(raw, homeDir) {
|
|
|
17320
18207
|
}
|
|
17321
18208
|
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
17322
18209
|
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
17323
|
-
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
17324
18210
|
var OPENCODE_VERSION_ENV = "EVIDENT_OPENCODE_VERSION";
|
|
17325
18211
|
function resolveOpenCodeVersion(options, env = process.env) {
|
|
17326
18212
|
let raw;
|
|
@@ -17734,6 +18620,10 @@ async function driveChannels(state, driver) {
|
|
|
17734
18620
|
let idleMs = 0;
|
|
17735
18621
|
let consecutiveDrainFailures = 0;
|
|
17736
18622
|
let unreachableMs = 0;
|
|
18623
|
+
let consecutiveOpenCodeFailures = 0;
|
|
18624
|
+
let openCodeFailureMs = 0;
|
|
18625
|
+
let consecutiveOutstandingPolls = 0;
|
|
18626
|
+
let outstandingWorkMs = 0;
|
|
17737
18627
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
17738
18628
|
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
17739
18629
|
let lastSeenClaudeApplies = driver.fileSyncActivity().claudeCredentialApplies;
|
|
@@ -17751,6 +18641,9 @@ async function driveChannels(state, driver) {
|
|
|
17751
18641
|
const cycleStartedAtMs = performance.now();
|
|
17752
18642
|
let idleThisCycle = false;
|
|
17753
18643
|
let unreachableThisCycle = false;
|
|
18644
|
+
let openCodeFailureThisCycle = false;
|
|
18645
|
+
let outstandingWorkThisCycle = false;
|
|
18646
|
+
let outstandingQueuedWork = 0;
|
|
17754
18647
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
17755
18648
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
17756
18649
|
if (state.interactive) displayStatus(state);
|
|
@@ -17767,6 +18660,8 @@ async function driveChannels(state, driver) {
|
|
|
17767
18660
|
const processed = await driver.drainPending();
|
|
17768
18661
|
consecutiveDrainFailures = 0;
|
|
17769
18662
|
unreachableMs = 0;
|
|
18663
|
+
consecutiveOpenCodeFailures = 0;
|
|
18664
|
+
openCodeFailureMs = 0;
|
|
17770
18665
|
state.messageCount += processed;
|
|
17771
18666
|
if (driver.recycleRequested) {
|
|
17772
18667
|
await beginGracefulShutdown(state, "recycle");
|
|
@@ -17824,16 +18719,35 @@ async function driveChannels(state, driver) {
|
|
|
17824
18719
|
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
17825
18720
|
idlePolls = 0;
|
|
17826
18721
|
idleMs = 0;
|
|
18722
|
+
consecutiveOutstandingPolls = 0;
|
|
18723
|
+
outstandingWorkMs = 0;
|
|
17827
18724
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
17828
18725
|
} else if (state.idleTimeout !== null) {
|
|
17829
|
-
|
|
17830
|
-
|
|
17831
|
-
|
|
17832
|
-
|
|
17833
|
-
|
|
17834
|
-
|
|
17835
|
-
|
|
17836
|
-
|
|
18726
|
+
outstandingQueuedWork = driver.outstandingQueuedWork();
|
|
18727
|
+
if (outstandingQueuedWork > 0) {
|
|
18728
|
+
idlePolls = 0;
|
|
18729
|
+
idleMs = 0;
|
|
18730
|
+
consecutiveOutstandingPolls++;
|
|
18731
|
+
outstandingWorkThisCycle = true;
|
|
18732
|
+
if (consecutiveOutstandingPolls === 1) {
|
|
18733
|
+
logActivity(state, {
|
|
18734
|
+
type: "info",
|
|
18735
|
+
message: `${outstandingQueuedWork} queued message(s) are waiting but could not be progressed, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
|
|
18736
|
+
});
|
|
18737
|
+
if (state.interactive) displayStatus(state);
|
|
18738
|
+
}
|
|
18739
|
+
} else {
|
|
18740
|
+
consecutiveOutstandingPolls = 0;
|
|
18741
|
+
outstandingWorkMs = 0;
|
|
18742
|
+
idlePolls++;
|
|
18743
|
+
idleThisCycle = true;
|
|
18744
|
+
if (idlePolls === 1) {
|
|
18745
|
+
logActivity(state, {
|
|
18746
|
+
type: "info",
|
|
18747
|
+
message: `Queue empty, waiting (timeout: ${state.idleTimeout}s)...`
|
|
18748
|
+
});
|
|
18749
|
+
if (state.interactive) displayStatus(state);
|
|
18750
|
+
}
|
|
17837
18751
|
}
|
|
17838
18752
|
}
|
|
17839
18753
|
} catch (error2) {
|
|
@@ -17848,12 +18762,28 @@ async function driveChannels(state, driver) {
|
|
|
17848
18762
|
state.running = false;
|
|
17849
18763
|
break;
|
|
17850
18764
|
}
|
|
17851
|
-
const errorMessage5 =
|
|
18765
|
+
const errorMessage5 = describeErrorWithCause(error2);
|
|
17852
18766
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage5}` });
|
|
17853
18767
|
if (state.interactive) displayStatus(state);
|
|
17854
18768
|
if (driver.hasInFlightWatchers()) {
|
|
17855
18769
|
consecutiveDrainFailures = 0;
|
|
17856
18770
|
unreachableMs = 0;
|
|
18771
|
+
consecutiveOpenCodeFailures = 0;
|
|
18772
|
+
openCodeFailureMs = 0;
|
|
18773
|
+
} else if (error2 instanceof LocalOpenCodeError) {
|
|
18774
|
+
consecutiveDrainFailures = 0;
|
|
18775
|
+
unreachableMs = 0;
|
|
18776
|
+
if (state.idleTimeout !== null) {
|
|
18777
|
+
consecutiveOpenCodeFailures++;
|
|
18778
|
+
openCodeFailureThisCycle = true;
|
|
18779
|
+
if (consecutiveOpenCodeFailures === 1) {
|
|
18780
|
+
logActivity(state, {
|
|
18781
|
+
type: "info",
|
|
18782
|
+
message: `Local OpenCode server on port ${state.port} is failing, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
|
|
18783
|
+
});
|
|
18784
|
+
if (state.interactive) displayStatus(state);
|
|
18785
|
+
}
|
|
18786
|
+
}
|
|
17857
18787
|
} else if (state.idleTimeout !== null) {
|
|
17858
18788
|
consecutiveDrainFailures++;
|
|
17859
18789
|
unreachableThisCycle = true;
|
|
@@ -17913,6 +18843,8 @@ async function driveChannels(state, driver) {
|
|
|
17913
18843
|
const cycleMs = performance.now() - cycleStartedAtMs;
|
|
17914
18844
|
if (idleThisCycle) idleMs += cycleMs;
|
|
17915
18845
|
if (unreachableThisCycle) unreachableMs += cycleMs;
|
|
18846
|
+
if (openCodeFailureThisCycle) openCodeFailureMs += cycleMs;
|
|
18847
|
+
if (outstandingWorkThisCycle) outstandingWorkMs += cycleMs;
|
|
17916
18848
|
if (state.idleTimeout !== null && consecutiveDrainFailures >= 2 && unreachableMs > state.idleTimeout * 1e3) {
|
|
17917
18849
|
logActivity(state, {
|
|
17918
18850
|
type: "info",
|
|
@@ -17922,6 +18854,24 @@ async function driveChannels(state, driver) {
|
|
|
17922
18854
|
if (state.interactive) displayStatus(state);
|
|
17923
18855
|
break;
|
|
17924
18856
|
}
|
|
18857
|
+
if (state.idleTimeout !== null && consecutiveOpenCodeFailures >= 2 && openCodeFailureMs > state.idleTimeout * 1e3) {
|
|
18858
|
+
logActivity(state, {
|
|
18859
|
+
type: "info",
|
|
18860
|
+
level: "warn",
|
|
18861
|
+
message: `Exiting: could not use the local OpenCode server on port ${state.port} for ${consecutiveOpenCodeFailures} consecutive polls (${Math.round(openCodeFailureMs / 1e3)}s)`
|
|
18862
|
+
});
|
|
18863
|
+
if (state.interactive) displayStatus(state);
|
|
18864
|
+
break;
|
|
18865
|
+
}
|
|
18866
|
+
if (state.idleTimeout !== null && outstandingWorkThisCycle && consecutiveOutstandingPolls >= 2 && outstandingWorkMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
|
|
18867
|
+
logActivity(state, {
|
|
18868
|
+
type: "info",
|
|
18869
|
+
level: "warn",
|
|
18870
|
+
message: `Exiting: could not progress ${outstandingQueuedWork} outstanding queued message(s) for ${consecutiveOutstandingPolls} consecutive polls (${Math.round(outstandingWorkMs / 1e3)}s)`
|
|
18871
|
+
});
|
|
18872
|
+
if (state.interactive) displayStatus(state);
|
|
18873
|
+
break;
|
|
18874
|
+
}
|
|
17925
18875
|
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
|
|
17926
18876
|
logActivity(state, { type: "info", message: "Idle timeout reached" });
|
|
17927
18877
|
if (state.interactive) displayStatus(state);
|
|
@@ -17944,6 +18894,8 @@ var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
|
|
|
17944
18894
|
var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
|
|
17945
18895
|
var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
|
|
17946
18896
|
var MAX_SESSION_DELETE_BODY_LENGTH = 200;
|
|
18897
|
+
var SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET = 3;
|
|
18898
|
+
var SESSION_ARCHIVE_MANIFEST_BUDGET_MS = 500;
|
|
17947
18899
|
function shouldWarnForReclaimSkip(reason) {
|
|
17948
18900
|
if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
|
|
17949
18901
|
const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
|
|
@@ -17967,18 +18919,52 @@ function logSessionArchiveActivity(state, phase, entry) {
|
|
|
17967
18919
|
logActivity(state, {
|
|
17968
18920
|
...entry,
|
|
17969
18921
|
source: "cli.session-archive",
|
|
17970
|
-
metadata
|
|
18922
|
+
// The forwarder drops metadata beyond its 20-entry cap in insertion order.
|
|
18923
|
+
metadata: { phase, ...entry.metadata }
|
|
17971
18924
|
});
|
|
17972
18925
|
}
|
|
17973
|
-
function
|
|
18926
|
+
function logSessionArchiveMetadataDecodeFailure(state, phase, details) {
|
|
18927
|
+
const subject = details.sessionId ? `session ${details.sessionId}` : "audit manifest";
|
|
18928
|
+
logSessionArchiveActivity(state, phase, {
|
|
18929
|
+
type: "info",
|
|
18930
|
+
level: "warn",
|
|
18931
|
+
message: `Session archive: ${subject} upload returned malformed ${details.field} metadata; the upload succeeded without that value`,
|
|
18932
|
+
metadata: {
|
|
18933
|
+
outcome: "archive-upload-metadata-malformed",
|
|
18934
|
+
metadata_field: details.field,
|
|
18935
|
+
metadata_decode_reason: details.reason,
|
|
18936
|
+
...details.sessionId ? { session_id: details.sessionId } : {},
|
|
18937
|
+
...details.manifestKey ? { manifest_key: details.manifestKey } : {}
|
|
18938
|
+
}
|
|
18939
|
+
});
|
|
18940
|
+
}
|
|
18941
|
+
function logSessionArchiveSummary(state, phase, summary, reconciliation) {
|
|
17974
18942
|
const everyUploadFailed = summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
|
|
17975
|
-
const staleSince = everyUploadFailed && summary.staleSince !== null ? `; archive stale since ${summary.staleSince}` : "";
|
|
17976
18943
|
const neverWatermarked = summary.neverWatermarkedFailures > 0 ? `; ${summary.neverWatermarkedFailures} failed session(s) had no prior successful upload` : "";
|
|
17977
18944
|
const warning2 = summary.failed > 0 || summary.failures.length > 0 || everyUploadFailed || !summary.reconciliationComplete;
|
|
18945
|
+
if (!reconciliation.complete) {
|
|
18946
|
+
const failure = reconciliation.failures[0];
|
|
18947
|
+
const detail = failure.kind === "http" ? `HTTP ${failure.status} for chunk ${failure.chunk}` : failure.kind === "network" ? `network failure for chunk ${failure.chunk}: ${redactDiagnosticText(failure.message ?? "unknown error").slice(0, 200)}` : `invalid response for chunk ${failure.chunk}`;
|
|
18948
|
+
logSessionArchiveActivity(state, phase, {
|
|
18949
|
+
type: "info",
|
|
18950
|
+
level: "warn",
|
|
18951
|
+
message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
|
|
18952
|
+
metadata: {
|
|
18953
|
+
outcome: "binding-reconciliation-incomplete",
|
|
18954
|
+
runner_id: state.agentId,
|
|
18955
|
+
failed_chunks: reconciliation.failures.length,
|
|
18956
|
+
first_failed_chunk: failure.chunk,
|
|
18957
|
+
first_failure_kind: failure.kind,
|
|
18958
|
+
...failure.status !== void 0 ? { http_status: failure.status } : {}
|
|
18959
|
+
}
|
|
18960
|
+
});
|
|
18961
|
+
}
|
|
17978
18962
|
logSessionArchiveActivity(state, phase, {
|
|
17979
18963
|
type: "info",
|
|
17980
18964
|
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}` +
|
|
18965
|
+
message: `Session archive: inspected ${summary.inspected}, uploaded ${summary.uploaded}, unchanged ${summary.unchanged}, failed ${summary.failed}, skipped budget ${summary.skippedBudget}, unmapped ${summary.unmappedIds.length}, conflicts ${summary.conflicts}, reconciliation incomplete ${summary.reconciliationIncomplete}; bindings ledger ${summary.bindingSourceCounts.ledger}, watermark ${summary.bindingSourceCounts.watermark}, current ${summary.bindingSourceCounts.current}, invocation ${summary.bindingSourceCounts.invocation}, history ${summary.bindingSourceCounts.history}, parent ${summary.bindingSourceCounts.parent}` + neverWatermarked,
|
|
18966
|
+
// Keep this summary at the forwarder's 20-entry metadata cap; phase is
|
|
18967
|
+
// prepended by logSessionArchiveActivity.
|
|
17982
18968
|
metadata: {
|
|
17983
18969
|
outcome: "archive-run-complete",
|
|
17984
18970
|
sessions_inspected: summary.inspected,
|
|
@@ -17989,7 +18975,6 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
17989
18975
|
uploads_failed: summary.uploadFailures,
|
|
17990
18976
|
sessions_skipped_budget: summary.skippedBudget,
|
|
17991
18977
|
sessions_unmapped: summary.unmappedIds.length,
|
|
17992
|
-
sessions_unresolved: summary.unresolved,
|
|
17993
18978
|
sessions_conflicted: summary.conflicts,
|
|
17994
18979
|
sessions_reconciliation_incomplete: summary.reconciliationIncomplete,
|
|
17995
18980
|
binding_reconciliation_complete: summary.reconciliationComplete,
|
|
@@ -17999,11 +18984,10 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
17999
18984
|
bindings_from_invocation: summary.bindingSourceCounts.invocation,
|
|
18000
18985
|
bindings_from_history: summary.bindingSourceCounts.history,
|
|
18001
18986
|
bindings_from_parent: summary.bindingSourceCounts.parent,
|
|
18002
|
-
sessions_without_prior_watermark: summary.neverWatermarkedFailures
|
|
18003
|
-
...everyUploadFailed && summary.staleSince !== null ? { stale_since: summary.staleSince } : {}
|
|
18987
|
+
sessions_without_prior_watermark: summary.neverWatermarkedFailures
|
|
18004
18988
|
}
|
|
18005
18989
|
});
|
|
18006
|
-
|
|
18990
|
+
const logFailure = (failure) => {
|
|
18007
18991
|
const permanentSizeFailure = failure.reason === "too-large";
|
|
18008
18992
|
const hasPayloadDetails = failure.bytes !== void 0 && failure.byteLimit !== void 0 && failure.messageCount !== void 0 && failure.partCount !== void 0;
|
|
18009
18993
|
const payloadDetails = hasPayloadDetails ? `; payload bytes=${failure.bytes} limit=${failure.byteLimit} messages=${failure.messageCount} parts=${failure.partCount}` : "";
|
|
@@ -18026,7 +19010,9 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
18026
19010
|
} : {}
|
|
18027
19011
|
}
|
|
18028
19012
|
});
|
|
18029
|
-
}
|
|
19013
|
+
};
|
|
19014
|
+
const failuresToLog = phase === "sweep" ? summary.failures : summary.failures.slice(0, SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET);
|
|
19015
|
+
for (const failure of failuresToLog) logFailure(failure);
|
|
18030
19016
|
if (summary.unmappedIds.length > 0) {
|
|
18031
19017
|
logSessionArchiveActivity(state, phase, {
|
|
18032
19018
|
type: "info",
|
|
@@ -18050,6 +19036,117 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
18050
19036
|
});
|
|
18051
19037
|
}
|
|
18052
19038
|
}
|
|
19039
|
+
function hasSessionArchivePrerequisites(state) {
|
|
19040
|
+
return Boolean(
|
|
19041
|
+
state.opencodeClient && state.sessionArchiveConfig.keyPrefix && state.sessionArchiveWatermarkPath && state.agentId
|
|
19042
|
+
);
|
|
19043
|
+
}
|
|
19044
|
+
async function publishSessionArchiveAudit(state, phase, identity, summary, manifestWindowMs, manifestSignal, parentSignal) {
|
|
19045
|
+
if (!hasSessionArchivePrerequisites(state)) return;
|
|
19046
|
+
const manifestKey = sessionArchiveManifestKey(state.sessionArchiveConfig.keyPrefix, identity);
|
|
19047
|
+
let manifestDurable = false;
|
|
19048
|
+
let manifestVersionId = null;
|
|
19049
|
+
let failure = null;
|
|
19050
|
+
if (parentSignal.aborted) {
|
|
19051
|
+
failure = { kind: "not-attempted", reason: "pass-aborted" };
|
|
19052
|
+
} else if (manifestWindowMs <= 0) {
|
|
19053
|
+
failure = { kind: "not-attempted", reason: "no-manifest-budget" };
|
|
19054
|
+
} else {
|
|
19055
|
+
try {
|
|
19056
|
+
const result = await uploadSessionArchiveManifest({
|
|
19057
|
+
keyPrefix: state.sessionArchiveConfig.keyPrefix,
|
|
19058
|
+
identity,
|
|
19059
|
+
summary,
|
|
19060
|
+
timeoutMs: manifestWindowMs,
|
|
19061
|
+
signal: manifestSignal,
|
|
19062
|
+
upload: uploadSessionArchive,
|
|
19063
|
+
onMetadataDecodeError: (field, reason) => logSessionArchiveMetadataDecodeFailure(state, phase, {
|
|
19064
|
+
field,
|
|
19065
|
+
reason,
|
|
19066
|
+
manifestKey
|
|
19067
|
+
})
|
|
19068
|
+
});
|
|
19069
|
+
if (result.outcome.kind === "ok") {
|
|
19070
|
+
manifestDurable = true;
|
|
19071
|
+
manifestVersionId = result.outcome.versionId;
|
|
19072
|
+
} else {
|
|
19073
|
+
failure = {
|
|
19074
|
+
kind: result.outcome.kind,
|
|
19075
|
+
..."reason" in result.outcome ? { reason: result.outcome.reason } : {},
|
|
19076
|
+
..."exitCode" in result.outcome && result.outcome.exitCode !== void 0 ? { exitCode: result.outcome.exitCode } : {}
|
|
19077
|
+
};
|
|
19078
|
+
}
|
|
19079
|
+
} catch (error2) {
|
|
19080
|
+
const diagnostic = redactDiagnosticText(
|
|
19081
|
+
error2 instanceof Error ? error2.message : String(error2)
|
|
19082
|
+
).replace(/[\r\n]+/g, " ").slice(0, 200);
|
|
19083
|
+
logSessionArchiveActivity(state, phase, {
|
|
19084
|
+
type: "info",
|
|
19085
|
+
level: "warn",
|
|
19086
|
+
message: `Session archive audit manifest upload threw for boot ${identity.bootId}, pass ${identity.passSequence}, phase ${phase}: ${diagnostic}`,
|
|
19087
|
+
metadata: {
|
|
19088
|
+
outcome: "archive-audit-manifest-upload-threw",
|
|
19089
|
+
boot_id: identity.bootId,
|
|
19090
|
+
pass_sequence: identity.passSequence
|
|
19091
|
+
}
|
|
19092
|
+
});
|
|
19093
|
+
failure = { kind: "thrown", reason: "upload-threw" };
|
|
19094
|
+
}
|
|
19095
|
+
}
|
|
19096
|
+
if (failure !== null) {
|
|
19097
|
+
logSessionArchiveActivity(state, phase, {
|
|
19098
|
+
type: "info",
|
|
19099
|
+
level: "warn",
|
|
19100
|
+
message: `Session archive audit manifest was not durable for ${phase} pass ${identity.passSequence}: ${failure.kind}${failure.reason ? ` (${failure.reason})` : ""}`,
|
|
19101
|
+
metadata: {
|
|
19102
|
+
outcome: "archive-audit-manifest-failed",
|
|
19103
|
+
boot_id: identity.bootId,
|
|
19104
|
+
pass_sequence: identity.passSequence,
|
|
19105
|
+
manifest_key: manifestKey,
|
|
19106
|
+
kind: failure.kind,
|
|
19107
|
+
...failure.reason !== void 0 ? { reason: failure.reason } : {},
|
|
19108
|
+
...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
|
|
19109
|
+
}
|
|
19110
|
+
});
|
|
19111
|
+
}
|
|
19112
|
+
const sessionsInspected = summary?.inspected ?? 0;
|
|
19113
|
+
const sessionsUploaded = summary?.uploaded ?? 0;
|
|
19114
|
+
const sessionsUnchanged = summary?.unchanged ?? 0;
|
|
19115
|
+
const sessionsFailed = summary?.failed ?? 0;
|
|
19116
|
+
const sessionsSkippedChanged = summary?.skippedChanged ?? 0;
|
|
19117
|
+
const sessionsSkippedUnknown = summary?.skippedUnknown ?? 0;
|
|
19118
|
+
const outcomesReconciled = summary?.outcomesReconciled ?? null;
|
|
19119
|
+
const retries = summary?.uploadedSessions.filter(({ retriedPriorFailure }) => retriedPriorFailure).length ?? 0;
|
|
19120
|
+
const everyUploadFailed = summary !== null && summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
|
|
19121
|
+
const level = summary === null || !summary.outcomesReconciled || summary.skippedChanged > 0 ? "warn" : "info";
|
|
19122
|
+
const message = summary === null ? `Session archive audit: ${phase} pass could not enumerate the session store (${identity.enumerationReason ?? "unknown"}); no session was inspected` : `Session archive audit: inspected ${sessionsInspected}, uploaded ${sessionsUploaded}, unchanged ${sessionsUnchanged}, failed ${sessionsFailed}, skipped known changed ${sessionsSkippedChanged}, skipped unknown ${sessionsSkippedUnknown}; outcomes reconciled ${outcomesReconciled ? "yes" : "no"}; manifest ${manifestKey}`;
|
|
19123
|
+
logSessionArchiveActivity(state, phase, {
|
|
19124
|
+
type: "info",
|
|
19125
|
+
level,
|
|
19126
|
+
message,
|
|
19127
|
+
metadata: {
|
|
19128
|
+
outcome: "archive-outcome-audit",
|
|
19129
|
+
boot_id: identity.bootId,
|
|
19130
|
+
pass_sequence: identity.passSequence,
|
|
19131
|
+
enumeration_complete: identity.enumerationComplete,
|
|
19132
|
+
sessions_inspected: sessionsInspected,
|
|
19133
|
+
sessions_uploaded: sessionsUploaded,
|
|
19134
|
+
sessions_unchanged: sessionsUnchanged,
|
|
19135
|
+
sessions_failed: sessionsFailed,
|
|
19136
|
+
sessions_skipped_changed: sessionsSkippedChanged,
|
|
19137
|
+
sessions_skipped_unknown: sessionsSkippedUnknown,
|
|
19138
|
+
outcomes_reconciled: outcomesReconciled,
|
|
19139
|
+
manifest_durable: manifestDurable,
|
|
19140
|
+
manifest_key: manifestKey,
|
|
19141
|
+
manifest_version_id: manifestVersionId,
|
|
19142
|
+
watermark_file_present: identity.watermarkFilePresent,
|
|
19143
|
+
watermarks_loaded: identity.watermarksLoaded,
|
|
19144
|
+
uploads_retrying_prior_failures: retries,
|
|
19145
|
+
...summary === null ? { enumeration_reason: identity.enumerationReason ?? "unknown" } : {},
|
|
19146
|
+
...everyUploadFailed && summary?.staleSince !== null ? { stale_since: summary.staleSince } : {}
|
|
19147
|
+
}
|
|
19148
|
+
});
|
|
19149
|
+
}
|
|
18053
19150
|
async function drainSessionDeletionReports(state) {
|
|
18054
19151
|
const path = sessionDeletionReportPath(homedir9(), process.env);
|
|
18055
19152
|
let delivered = 0;
|
|
@@ -18467,14 +19564,10 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
|
|
|
18467
19564
|
}
|
|
18468
19565
|
const controller = new AbortController();
|
|
18469
19566
|
state.sessionArchiveAbortController = controller;
|
|
19567
|
+
let budgetExceeded = false;
|
|
18470
19568
|
const timeout = setTimeout(() => {
|
|
19569
|
+
budgetExceeded = true;
|
|
18471
19570
|
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
19571
|
}, budgetMs);
|
|
18479
19572
|
const task = Promise.resolve().then(() => work(controller.signal)).catch((error2) => {
|
|
18480
19573
|
logSessionArchiveActivity(state, phase, {
|
|
@@ -18485,6 +19578,19 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
|
|
|
18485
19578
|
});
|
|
18486
19579
|
return null;
|
|
18487
19580
|
}).finally(() => {
|
|
19581
|
+
if (budgetExceeded) {
|
|
19582
|
+
logSessionArchiveActivity(state, phase, {
|
|
19583
|
+
type: "info",
|
|
19584
|
+
level: "warn",
|
|
19585
|
+
message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
|
|
19586
|
+
metadata: {
|
|
19587
|
+
outcome: "archive-budget-exceeded",
|
|
19588
|
+
budget_ms: budgetMs,
|
|
19589
|
+
boot_id: state.sessionArchiveBootId,
|
|
19590
|
+
pass_sequence: state.sessionArchivePassSequence
|
|
19591
|
+
}
|
|
19592
|
+
});
|
|
19593
|
+
}
|
|
18488
19594
|
clearTimeout(timeout);
|
|
18489
19595
|
if (state.sessionArchiveInFlight === task) {
|
|
18490
19596
|
state.sessionArchiveInFlight = null;
|
|
@@ -18495,10 +19601,7 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
|
|
|
18495
19601
|
return task;
|
|
18496
19602
|
}
|
|
18497
19603
|
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) {
|
|
19604
|
+
if (!hasSessionArchivePrerequisites(state)) {
|
|
18502
19605
|
logSessionArchiveActivity(state, phase, {
|
|
18503
19606
|
type: "info",
|
|
18504
19607
|
level: "warn",
|
|
@@ -18507,6 +19610,9 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
|
|
|
18507
19610
|
});
|
|
18508
19611
|
return null;
|
|
18509
19612
|
}
|
|
19613
|
+
const config = state.sessionArchiveConfig;
|
|
19614
|
+
const client = state.opencodeClient;
|
|
19615
|
+
const watermarkPath = state.sessionArchiveWatermarkPath;
|
|
18510
19616
|
const bindings = readSessionBindings(
|
|
18511
19617
|
sessionBindingLedgerPath(homedir9(), process.env),
|
|
18512
19618
|
(message) => logSessionArchiveActivity(state, phase, {
|
|
@@ -18523,23 +19629,6 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
|
|
|
18523
19629
|
sessions,
|
|
18524
19630
|
signal
|
|
18525
19631
|
});
|
|
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
19632
|
const summary = await runSessionArchive({
|
|
18544
19633
|
sessions,
|
|
18545
19634
|
deps: {
|
|
@@ -18550,40 +19639,97 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
|
|
|
18550
19639
|
projection: reconciliation.projection,
|
|
18551
19640
|
reconciliationComplete: reconciliation.complete,
|
|
18552
19641
|
watermarks: state.sessionArchiveWatermarks,
|
|
19642
|
+
priorFailureIds: state.sessionArchivePriorFailureIds,
|
|
18553
19643
|
watermarkPath,
|
|
18554
19644
|
signal,
|
|
19645
|
+
onMetadataDecodeError: (field, reason, sessionId) => logSessionArchiveMetadataDecodeFailure(state, phase, { field, reason, sessionId }),
|
|
18555
19646
|
upload: uploadSessionArchive,
|
|
18556
19647
|
exportMessages: exportSessionMessages,
|
|
18557
19648
|
recordWatermark: recordUpload
|
|
18558
19649
|
},
|
|
18559
19650
|
budgetMs
|
|
18560
19651
|
});
|
|
18561
|
-
logSessionArchiveSummary(state, phase, summary);
|
|
19652
|
+
logSessionArchiveSummary(state, phase, summary, reconciliation);
|
|
18562
19653
|
return summary;
|
|
18563
19654
|
}
|
|
18564
19655
|
async function runSessionArchiveFleet(state, phase, budgetMs, signal) {
|
|
19656
|
+
state.sessionArchivePassSequence++;
|
|
18565
19657
|
const startedAt = Date.now();
|
|
18566
|
-
const
|
|
18567
|
-
|
|
18568
|
-
|
|
18569
|
-
|
|
18570
|
-
|
|
18571
|
-
|
|
18572
|
-
|
|
18573
|
-
|
|
18574
|
-
|
|
18575
|
-
|
|
19658
|
+
const passDeadline = startedAt + budgetMs;
|
|
19659
|
+
const workDeadline = passDeadline - SESSION_ARCHIVE_MANIFEST_BUDGET_MS;
|
|
19660
|
+
const watermarksLoaded = state.sessionArchiveWatermarks.size;
|
|
19661
|
+
const workBudget = createBudgetSignal(signal, Math.max(0, workDeadline - Date.now()));
|
|
19662
|
+
let summary = null;
|
|
19663
|
+
let enumerationComplete = false;
|
|
19664
|
+
let enumerationReason = null;
|
|
19665
|
+
try {
|
|
19666
|
+
const enumeration = await listAllSessions(
|
|
19667
|
+
state.port,
|
|
19668
|
+
state.opencodeClient ?? void 0,
|
|
19669
|
+
workBudget.signal
|
|
19670
|
+
);
|
|
19671
|
+
if (enumeration.sessions === null) {
|
|
19672
|
+
enumerationComplete = false;
|
|
19673
|
+
enumerationReason = workBudget.signal.aborted ? "enumeration-interrupted" : enumeration.reason;
|
|
19674
|
+
const interrupted = workBudget.signal.aborted;
|
|
19675
|
+
logSessionArchiveActivity(state, phase, {
|
|
19676
|
+
type: "info",
|
|
19677
|
+
level: "warn",
|
|
19678
|
+
message: interrupted ? "Session archive: enumeration was interrupted before the complete store was known; no session was marked archived" : `Session archive: could not enumerate the complete session store (${enumerationReason}); no session was marked archived`,
|
|
19679
|
+
metadata: {
|
|
19680
|
+
outcome: interrupted ? "enumeration-interrupted" : "enumeration-refused",
|
|
19681
|
+
...!interrupted ? { reason: enumerationReason } : {}
|
|
19682
|
+
}
|
|
19683
|
+
});
|
|
19684
|
+
} else {
|
|
19685
|
+
enumerationComplete = true;
|
|
19686
|
+
enumerationReason = null;
|
|
19687
|
+
const enumeratedIds = new Set(enumeration.sessions.map(({ id }) => id));
|
|
19688
|
+
for (const sessionId of state.sessionArchivePriorFailureIds) {
|
|
19689
|
+
if (!enumeratedIds.has(sessionId)) state.sessionArchivePriorFailureIds.delete(sessionId);
|
|
18576
19690
|
}
|
|
18577
|
-
|
|
18578
|
-
|
|
19691
|
+
summary = await runSessionArchiveBatch(
|
|
19692
|
+
state,
|
|
19693
|
+
phase,
|
|
19694
|
+
enumeration.sessions,
|
|
19695
|
+
Math.max(0, workDeadline - Date.now()),
|
|
19696
|
+
workBudget.signal
|
|
19697
|
+
);
|
|
19698
|
+
}
|
|
19699
|
+
} finally {
|
|
19700
|
+
workBudget.dispose();
|
|
18579
19701
|
}
|
|
18580
|
-
|
|
18581
|
-
|
|
18582
|
-
|
|
18583
|
-
|
|
18584
|
-
|
|
18585
|
-
|
|
18586
|
-
|
|
19702
|
+
const manifestWindowMs = Math.max(0, passDeadline - Date.now());
|
|
19703
|
+
const manifestBudget = createBudgetSignal(signal, manifestWindowMs);
|
|
19704
|
+
try {
|
|
19705
|
+
if (summary !== null || !enumerationComplete) {
|
|
19706
|
+
const identity = {
|
|
19707
|
+
runnerId: state.agentId,
|
|
19708
|
+
bootId: state.sessionArchiveBootId,
|
|
19709
|
+
passSequence: state.sessionArchivePassSequence,
|
|
19710
|
+
phase,
|
|
19711
|
+
startedAt: new Date(startedAt).toISOString(),
|
|
19712
|
+
completedAt: new Date(Date.now()).toISOString(),
|
|
19713
|
+
budgetMs,
|
|
19714
|
+
enumerationComplete,
|
|
19715
|
+
enumerationReason,
|
|
19716
|
+
watermarkFilePresent: state.sessionArchiveWatermarkFileLoaded,
|
|
19717
|
+
watermarksLoaded
|
|
19718
|
+
};
|
|
19719
|
+
await publishSessionArchiveAudit(
|
|
19720
|
+
state,
|
|
19721
|
+
phase,
|
|
19722
|
+
identity,
|
|
19723
|
+
summary,
|
|
19724
|
+
manifestWindowMs,
|
|
19725
|
+
manifestBudget.signal,
|
|
19726
|
+
signal
|
|
19727
|
+
);
|
|
19728
|
+
}
|
|
19729
|
+
} finally {
|
|
19730
|
+
manifestBudget.dispose();
|
|
19731
|
+
}
|
|
19732
|
+
return summary;
|
|
18587
19733
|
}
|
|
18588
19734
|
async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
18589
19735
|
const deadline = Date.now() + budgetMs;
|
|
@@ -18606,7 +19752,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
|
18606
19752
|
type: "info",
|
|
18607
19753
|
level: "warn",
|
|
18608
19754
|
message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
|
|
18609
|
-
metadata: {
|
|
19755
|
+
metadata: {
|
|
19756
|
+
outcome: "archive-budget-exceeded",
|
|
19757
|
+
budget_ms: budgetMs,
|
|
19758
|
+
boot_id: state.sessionArchiveBootId,
|
|
19759
|
+
pass_sequence: state.sessionArchivePassSequence,
|
|
19760
|
+
manifest_written: false
|
|
19761
|
+
}
|
|
18610
19762
|
});
|
|
18611
19763
|
return null;
|
|
18612
19764
|
}
|
|
@@ -18617,7 +19769,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
|
18617
19769
|
type: "info",
|
|
18618
19770
|
level: "warn",
|
|
18619
19771
|
message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
|
|
18620
|
-
metadata: {
|
|
19772
|
+
metadata: {
|
|
19773
|
+
outcome: "archive-budget-exceeded",
|
|
19774
|
+
budget_ms: budgetMs,
|
|
19775
|
+
boot_id: state.sessionArchiveBootId,
|
|
19776
|
+
pass_sequence: state.sessionArchivePassSequence,
|
|
19777
|
+
manifest_written: false
|
|
19778
|
+
}
|
|
18621
19779
|
});
|
|
18622
19780
|
return null;
|
|
18623
19781
|
}
|
|
@@ -18641,6 +19799,7 @@ function scheduleSessionArchive(state) {
|
|
|
18641
19799
|
metadata: { outcome: "watermark-read-failed" }
|
|
18642
19800
|
})
|
|
18643
19801
|
);
|
|
19802
|
+
state.sessionArchiveWatermarkFileLoaded = state.sessionArchiveWatermarks.size > 0;
|
|
18644
19803
|
logSessionArchiveActivity(state, "startup", {
|
|
18645
19804
|
type: "info",
|
|
18646
19805
|
message: `Session archive enabled (interval=${config.intervalMs}ms)`,
|
|
@@ -19150,9 +20309,13 @@ async function run(options) {
|
|
|
19150
20309
|
),
|
|
19151
20310
|
sessionArchiveTimers: [],
|
|
19152
20311
|
sessionArchiveWatermarks: /* @__PURE__ */ new Map(),
|
|
20312
|
+
sessionArchivePriorFailureIds: /* @__PURE__ */ new Set(),
|
|
19153
20313
|
sessionArchiveWatermarkPath: null,
|
|
19154
20314
|
sessionArchiveInFlight: null,
|
|
19155
20315
|
sessionArchiveAbortController: null,
|
|
20316
|
+
sessionArchiveBootId: randomUUID2(),
|
|
20317
|
+
sessionArchivePassSequence: 0,
|
|
20318
|
+
sessionArchiveWatermarkFileLoaded: false,
|
|
19156
20319
|
sessionDeleteFailures: /* @__PURE__ */ new Map(),
|
|
19157
20320
|
claudeUsageTimer: null,
|
|
19158
20321
|
claudeUsageRearm: null,
|
|
@@ -19613,7 +20776,7 @@ async function run(options) {
|
|
|
19613
20776
|
port: state.port,
|
|
19614
20777
|
interactive: state.interactive,
|
|
19615
20778
|
agentId: state.agentId,
|
|
19616
|
-
log: (message) => log2(state, message),
|
|
20779
|
+
log: (message, level = "info") => log2(state, message, level),
|
|
19617
20780
|
startTimeoutMs: opencodeStartTimeoutMs,
|
|
19618
20781
|
inheritStdio: Boolean(options.opencodePidFile),
|
|
19619
20782
|
command: opencodeV2Command
|
|
@@ -19621,10 +20784,15 @@ async function run(options) {
|
|
|
19621
20784
|
port: state.port,
|
|
19622
20785
|
interactive: state.interactive,
|
|
19623
20786
|
agentId: state.agentId,
|
|
19624
|
-
log: (message) => log2(state, message),
|
|
20787
|
+
log: (message, level = "info") => log2(state, message, level),
|
|
19625
20788
|
startTimeoutMs: opencodeStartTimeoutMs,
|
|
19626
20789
|
inheritStdio: Boolean(options.opencodePidFile)
|
|
19627
20790
|
});
|
|
20791
|
+
if (oc.reclaimOutcome) {
|
|
20792
|
+
const outcome = oc.reclaimOutcome;
|
|
20793
|
+
const message = outcome.kind === "freed" ? `Reclaimed OpenCode port ${outcome.port}: stopped holder PID(s) ${outcome.pids.join(", ")} with ${outcome.usedSigkill ? "SIGTERM and SIGKILL" : "SIGTERM"} and started a fresh OpenCode.` : `Reclaimed OpenCode port ${outcome.port}: the port freed itself before a holder could be signalled, and a fresh OpenCode was started.`;
|
|
20794
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
20795
|
+
}
|
|
19628
20796
|
state.port = oc.port;
|
|
19629
20797
|
state.opencodeProcess = options.opencodePidFile ? null : oc.process;
|
|
19630
20798
|
state.opencodeVersion = oc.version;
|
|
@@ -19668,7 +20836,7 @@ async function run(options) {
|
|
|
19668
20836
|
password: state.opencodePassword
|
|
19669
20837
|
});
|
|
19670
20838
|
state.opencodeClient = openCodeClient;
|
|
19671
|
-
if (options.opencodePidFile && oc.process?.pid !== void 0) {
|
|
20839
|
+
if (options.opencodePidFile && oc.process?.pid !== void 0 && oc.process.exitCode === null && oc.process.signalCode === null) {
|
|
19672
20840
|
try {
|
|
19673
20841
|
writeFileSync9(options.opencodePidFile, `${oc.process.pid}
|
|
19674
20842
|
`, { mode: 384 });
|
|
@@ -19679,6 +20847,12 @@ async function run(options) {
|
|
|
19679
20847
|
error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
19680
20848
|
});
|
|
19681
20849
|
}
|
|
20850
|
+
} else if (options.opencodePidFile && oc.process?.pid !== void 0) {
|
|
20851
|
+
logActivity(state, {
|
|
20852
|
+
type: "info",
|
|
20853
|
+
level: "warn",
|
|
20854
|
+
message: `OpenCode pid file ${options.opencodePidFile} was left unchanged because the process spawned for this run had already exited.`
|
|
20855
|
+
});
|
|
19682
20856
|
}
|
|
19683
20857
|
if (state.opencodeVersion !== null) {
|
|
19684
20858
|
const provenance = checkSessionDbProvenance({
|
|
@@ -19725,7 +20899,7 @@ async function run(options) {
|
|
|
19725
20899
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
19726
20900
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
19727
20901
|
if (!state.interactive && oc.notReadyReason !== null) {
|
|
19728
|
-
const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers
|
|
20902
|
+
const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers.`;
|
|
19729
20903
|
logActivity(state, { type: "info", level: "warn", message });
|
|
19730
20904
|
} else {
|
|
19731
20905
|
const versionWarning = buildOpenCodeVersionWarning(
|
|
@@ -19971,7 +21145,7 @@ async function run(options) {
|
|
|
19971
21145
|
if (state.interactive) displayStatus(state);
|
|
19972
21146
|
}
|
|
19973
21147
|
}).catch((error2) => {
|
|
19974
|
-
const message =
|
|
21148
|
+
const message = describeErrorWithCause(error2);
|
|
19975
21149
|
logActivity(state, {
|
|
19976
21150
|
type: "error",
|
|
19977
21151
|
error: `Failed to drain queued messages on connect: ${message}`
|
|
@@ -20038,7 +21212,7 @@ async function run(options) {
|
|
|
20038
21212
|
if (state.interactive) displayStatus(state);
|
|
20039
21213
|
}
|
|
20040
21214
|
}).catch((error2) => {
|
|
20041
|
-
const message =
|
|
21215
|
+
const message = describeErrorWithCause(error2);
|
|
20042
21216
|
logActivity(state, {
|
|
20043
21217
|
type: "error",
|
|
20044
21218
|
error: `Failed to drain queued messages on ping: ${message}`
|
|
@@ -20135,24 +21309,89 @@ async function run(options) {
|
|
|
20135
21309
|
}
|
|
20136
21310
|
}
|
|
20137
21311
|
|
|
21312
|
+
// src/commands/teams.ts
|
|
21313
|
+
function printTeam(team, selected) {
|
|
21314
|
+
console.log(`${selected ? "* " : " "}${team.id} ${team.name}`);
|
|
21315
|
+
}
|
|
21316
|
+
function isTeam(value) {
|
|
21317
|
+
return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.name === "string";
|
|
21318
|
+
}
|
|
21319
|
+
async function teams() {
|
|
21320
|
+
const apiUrl = getApiUrlConfig();
|
|
21321
|
+
let credentials2;
|
|
21322
|
+
try {
|
|
21323
|
+
credentials2 = await getAuthCredentials();
|
|
21324
|
+
} catch (error2) {
|
|
21325
|
+
printError(
|
|
21326
|
+
`Could not read the saved Evident credentials: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
21327
|
+
);
|
|
21328
|
+
process.exitCode = 1;
|
|
21329
|
+
return;
|
|
21330
|
+
}
|
|
21331
|
+
if (!credentials2) {
|
|
21332
|
+
printError(`Not logged in to ${apiUrl}. Run the \`login\` command to authenticate.`);
|
|
21333
|
+
process.exitCode = 1;
|
|
21334
|
+
return;
|
|
21335
|
+
}
|
|
21336
|
+
try {
|
|
21337
|
+
const response = await fetch(`${apiUrl}/teams`, {
|
|
21338
|
+
headers: buildAuthHeaders(credentials2)
|
|
21339
|
+
});
|
|
21340
|
+
if (!response.ok) {
|
|
21341
|
+
const serverMessage = await readErrorMessage(response);
|
|
21342
|
+
throw new Error(
|
|
21343
|
+
`Evident returned HTTP ${response.status} while listing teams${serverMessage ? `: ${serverMessage}` : ""}`
|
|
21344
|
+
);
|
|
21345
|
+
}
|
|
21346
|
+
const data = await response.json();
|
|
21347
|
+
if (!Array.isArray(data) || !data.every(isTeam)) {
|
|
21348
|
+
throw new Error("Evident returned an invalid team list. Update the CLI and retry.");
|
|
21349
|
+
}
|
|
21350
|
+
const selectedTeam = getTeamSelection();
|
|
21351
|
+
blank();
|
|
21352
|
+
if (data.length === 0) {
|
|
21353
|
+
console.log("No teams found for this account.");
|
|
21354
|
+
blank();
|
|
21355
|
+
return;
|
|
21356
|
+
}
|
|
21357
|
+
for (const team of data) {
|
|
21358
|
+
printTeam(team, team.id === selectedTeam);
|
|
21359
|
+
}
|
|
21360
|
+
if (data.length === 1) {
|
|
21361
|
+
console.log("This is your only team; commands act in it automatically.");
|
|
21362
|
+
} else if (!selectedTeam) {
|
|
21363
|
+
console.log("Choose a team with --team <id> or set EVIDENT_TEAM.");
|
|
21364
|
+
}
|
|
21365
|
+
blank();
|
|
21366
|
+
} catch (error2) {
|
|
21367
|
+
printError(`Could not list teams: ${error2 instanceof Error ? error2.message : String(error2)}`);
|
|
21368
|
+
process.exitCode = 1;
|
|
21369
|
+
}
|
|
21370
|
+
}
|
|
21371
|
+
|
|
20138
21372
|
// src/index.ts
|
|
20139
21373
|
var version = getCliVersion();
|
|
20140
21374
|
var program = new Command();
|
|
20141
21375
|
program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
|
|
20142
21376
|
"--endpoint <url>",
|
|
20143
21377
|
"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
|
-
|
|
21378
|
+
).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").option(
|
|
21379
|
+
"--team <id>",
|
|
21380
|
+
"Evident team ID to act in (Env: EVIDENT_TEAM). Use it when your account belongs to more than one team; list them with evident teams"
|
|
21381
|
+
).hook("preAction", (thisCommand) => {
|
|
21382
|
+
const { endpoint: endpoint2, tunnel, team } = thisCommand.optsWithGlobals();
|
|
20146
21383
|
if (endpoint2) {
|
|
20147
21384
|
setEndpoint(endpoint2);
|
|
20148
21385
|
}
|
|
20149
21386
|
if (tunnel) {
|
|
20150
21387
|
setTunnelUrl(tunnel);
|
|
20151
21388
|
}
|
|
21389
|
+
setTeamSelection(team);
|
|
20152
21390
|
});
|
|
20153
21391
|
program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
|
|
20154
21392
|
program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
|
|
20155
21393
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
21394
|
+
program.command("teams").description("List the teams you belong to").action(teams);
|
|
20156
21395
|
program.command("mcp").description("Manage MCP proxy connections").command("authorize").description("Authorize an MCP proxy connection using your local browser").argument("<proxy-id>", "MCP proxy ID").argument("<connection-id>", "MCP connection ID").option("--no-browser", "Do not open the browser automatically").option("--json", "Output the result as JSON").action(
|
|
20157
21396
|
(proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
|
|
20158
21397
|
noBrowser: options.browser === false,
|