@evident-ai/cli 3.5.2-dev.60daa5f → 3.5.2-dev.678bfa4
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 +5 -3
- package/dist/index.js +1159 -260
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -315,14 +315,14 @@ function blank() {
|
|
|
315
315
|
console.log();
|
|
316
316
|
}
|
|
317
317
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
318
|
-
return new Promise((
|
|
318
|
+
return new Promise((resolve5) => {
|
|
319
319
|
process.stdout.write(chalk.dim(prompt));
|
|
320
320
|
const handler = () => {
|
|
321
321
|
process.stdin.removeListener("data", handler);
|
|
322
322
|
process.stdin.setRawMode?.(false);
|
|
323
323
|
process.stdin.pause();
|
|
324
324
|
console.log();
|
|
325
|
-
|
|
325
|
+
resolve5();
|
|
326
326
|
};
|
|
327
327
|
if (process.stdin.isTTY) {
|
|
328
328
|
process.stdin.setRawMode?.(true);
|
|
@@ -332,7 +332,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
332
332
|
});
|
|
333
333
|
}
|
|
334
334
|
function sleep(ms) {
|
|
335
|
-
return new Promise((
|
|
335
|
+
return new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
336
336
|
}
|
|
337
337
|
|
|
338
338
|
// src/commands/login.ts
|
|
@@ -410,19 +410,19 @@ async function tokenLogin() {
|
|
|
410
410
|
);
|
|
411
411
|
blank();
|
|
412
412
|
process.stdout.write("Paste token: ");
|
|
413
|
-
const token = await new Promise((
|
|
413
|
+
const token = await new Promise((resolve5) => {
|
|
414
414
|
let data = "";
|
|
415
415
|
process.stdin.setEncoding("utf8");
|
|
416
416
|
process.stdin.on("data", (chunk) => {
|
|
417
417
|
data += chunk;
|
|
418
418
|
});
|
|
419
419
|
process.stdin.on("end", () => {
|
|
420
|
-
|
|
420
|
+
resolve5(data.trim());
|
|
421
421
|
});
|
|
422
422
|
if (process.stdin.isTTY) {
|
|
423
423
|
process.stdin.once("data", (chunk) => {
|
|
424
424
|
process.stdin.pause();
|
|
425
|
-
|
|
425
|
+
resolve5(chunk.toString().trim());
|
|
426
426
|
});
|
|
427
427
|
process.stdin.resume();
|
|
428
428
|
}
|
|
@@ -703,6 +703,31 @@ async function reportResourceUsage(agentId, authHeader, usage) {
|
|
|
703
703
|
opencode_db_bytes: usage.opencodeDbBytes
|
|
704
704
|
});
|
|
705
705
|
}
|
|
706
|
+
async function getRunnerCredentialVault(agentId, authHeader) {
|
|
707
|
+
const empty = { prefix: null, vaultId: null, source: null };
|
|
708
|
+
try {
|
|
709
|
+
const apiUrl = getApiUrlConfig();
|
|
710
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/credential-vault`, {
|
|
711
|
+
headers: { Authorization: authHeader },
|
|
712
|
+
signal: AbortSignal.timeout(1e4)
|
|
713
|
+
});
|
|
714
|
+
if (!response.ok) {
|
|
715
|
+
const serverMessage = await readErrorMessage(response);
|
|
716
|
+
return {
|
|
717
|
+
...empty,
|
|
718
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
const data = await response.json();
|
|
722
|
+
return {
|
|
723
|
+
prefix: data.credential_vault_prefix,
|
|
724
|
+
vaultId: data.vault_id,
|
|
725
|
+
source: data.source
|
|
726
|
+
};
|
|
727
|
+
} catch (error2) {
|
|
728
|
+
return { ...empty, error: describeTimeoutError(error2, 1e4) };
|
|
729
|
+
}
|
|
730
|
+
}
|
|
706
731
|
async function getAgentInfo(agentId, authHeader) {
|
|
707
732
|
const apiUrl = getApiUrlConfig();
|
|
708
733
|
try {
|
|
@@ -877,6 +902,76 @@ async function status(options = {}) {
|
|
|
877
902
|
process.exit(result.exitCode);
|
|
878
903
|
}
|
|
879
904
|
|
|
905
|
+
// src/commands/credential-vault-env.ts
|
|
906
|
+
function shellQuote(value) {
|
|
907
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
908
|
+
}
|
|
909
|
+
function printAssignment(prefix) {
|
|
910
|
+
console.log(`CREDENTIAL_VAULT_PREFIX=${shellQuote(prefix ?? "")}`);
|
|
911
|
+
}
|
|
912
|
+
function safeReason(reason, credentials2, authHeader) {
|
|
913
|
+
let safe = reason;
|
|
914
|
+
for (const secret of [
|
|
915
|
+
authHeader,
|
|
916
|
+
credentials2?.token,
|
|
917
|
+
process.env.EVIDENT_RUNNER_KEY,
|
|
918
|
+
process.env.EVIDENT_AGENT_KEY,
|
|
919
|
+
process.env.EVIDENT_TOKEN
|
|
920
|
+
]) {
|
|
921
|
+
if (secret) safe = safe.replaceAll(secret, "[redacted]");
|
|
922
|
+
}
|
|
923
|
+
return safe.replace(/[\r\n]+/g, " ");
|
|
924
|
+
}
|
|
925
|
+
function printFallback(reason, credentials2, authHeader) {
|
|
926
|
+
printAssignment(null);
|
|
927
|
+
console.error(
|
|
928
|
+
`WARNING: ${safeReason(reason, credentials2, authHeader)}; using this runner's own credential prefix.`
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
async function credentialVaultEnv() {
|
|
932
|
+
let credentials2 = null;
|
|
933
|
+
let authHeader;
|
|
934
|
+
try {
|
|
935
|
+
credentials2 = await getAuthCredentials();
|
|
936
|
+
if (!credentials2) {
|
|
937
|
+
printFallback("no runner credentials are configured");
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
authHeader = getAuthHeader(credentials2);
|
|
941
|
+
const runner = await resolveAgentIdFromKey(authHeader);
|
|
942
|
+
if (!runner.agent_id) {
|
|
943
|
+
printFallback(
|
|
944
|
+
runner.error ?? "the runner identity could not be resolved",
|
|
945
|
+
credentials2,
|
|
946
|
+
authHeader
|
|
947
|
+
);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
const lookup = await getRunnerCredentialVault(runner.agent_id, authHeader);
|
|
951
|
+
if (lookup.error) {
|
|
952
|
+
printFallback(`credential vault lookup failed: ${lookup.error}`, credentials2, authHeader);
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
if (lookup.prefix === null) {
|
|
956
|
+
printFallback("this runner is not linked to a credential vault", credentials2, authHeader);
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
if (/[\r\n]/.test(lookup.prefix)) {
|
|
960
|
+
printFallback("credential vault lookup returned an invalid prefix", credentials2, authHeader);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
printAssignment(lookup.prefix);
|
|
964
|
+
console.error(
|
|
965
|
+
`VAULT-MODE: credential stores use vault=${lookup.vaultId} source=${lookup.source} prefix=${lookup.prefix}.`
|
|
966
|
+
);
|
|
967
|
+
} catch (error2) {
|
|
968
|
+
const detail = credentials2 === null ? "credential resolution failed" : `credential vault lookup could not be completed: ${error2 instanceof Error ? error2.message : String(error2)}`;
|
|
969
|
+
printFallback(detail, credentials2, authHeader);
|
|
970
|
+
} finally {
|
|
971
|
+
process.exitCode = 0;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
880
975
|
// src/lib/claude-usage.ts
|
|
881
976
|
import { execFileSync } from "node:child_process";
|
|
882
977
|
import { readFileSync } from "node:fs";
|
|
@@ -1063,7 +1158,7 @@ async function claudeUsage() {
|
|
|
1063
1158
|
// src/commands/run.ts
|
|
1064
1159
|
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "node:fs";
|
|
1065
1160
|
import { homedir as homedir7 } from "node:os";
|
|
1066
|
-
import { isAbsolute as
|
|
1161
|
+
import { isAbsolute as isAbsolute4, join as join12, parse, resolve as resolvePath2 } from "node:path";
|
|
1067
1162
|
import chalk7 from "chalk";
|
|
1068
1163
|
|
|
1069
1164
|
// ../../packages/types/src/agents/index.ts
|
|
@@ -1227,7 +1322,7 @@ import ora4 from "ora";
|
|
|
1227
1322
|
import { select as select4 } from "@inquirer/prompts";
|
|
1228
1323
|
|
|
1229
1324
|
// src/lib/telemetry.ts
|
|
1230
|
-
var CLI_VERSION = (true ? "3.5.2-dev.
|
|
1325
|
+
var CLI_VERSION = (true ? "3.5.2-dev.678bfa4" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
1231
1326
|
function getCliVersion() {
|
|
1232
1327
|
return CLI_VERSION;
|
|
1233
1328
|
}
|
|
@@ -1388,20 +1483,47 @@ var EventTypes = {
|
|
|
1388
1483
|
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
1389
1484
|
};
|
|
1390
1485
|
|
|
1391
|
-
// src/lib/runner-activity-telemetry.ts
|
|
1392
|
-
import { homedir as homedir2 } from "node:os";
|
|
1393
|
-
|
|
1394
1486
|
// src/lib/opencode/session-db-reclaim.ts
|
|
1395
1487
|
import { statSync as statSync2, statfsSync } from "node:fs";
|
|
1396
1488
|
import { dirname as dirname2 } from "node:path";
|
|
1397
|
-
|
|
1489
|
+
|
|
1490
|
+
// src/lib/diagnostic-redaction.ts
|
|
1491
|
+
import { homedir as homedir2 } from "node:os";
|
|
1492
|
+
function redactHomeDirectory(message) {
|
|
1493
|
+
const home = homedir2();
|
|
1494
|
+
if (!home || home === "/") {
|
|
1495
|
+
return message;
|
|
1496
|
+
}
|
|
1497
|
+
const pathSegmentCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-";
|
|
1498
|
+
let result = "";
|
|
1499
|
+
let searchFrom = 0;
|
|
1500
|
+
let homeIndex;
|
|
1501
|
+
while ((homeIndex = message.indexOf(home, searchFrom)) !== -1) {
|
|
1502
|
+
const homeEnd = homeIndex + home.length;
|
|
1503
|
+
const previousCharacter = message[homeIndex - 1];
|
|
1504
|
+
const nextCharacter = message[homeEnd];
|
|
1505
|
+
const atPathBoundary = (!previousCharacter || !pathSegmentCharacters.includes(previousCharacter)) && (!nextCharacter || !pathSegmentCharacters.includes(nextCharacter));
|
|
1506
|
+
result += message.slice(searchFrom, homeIndex);
|
|
1507
|
+
result += atPathBoundary ? "~" : home;
|
|
1508
|
+
searchFrom = homeEnd;
|
|
1509
|
+
}
|
|
1510
|
+
return result + message.slice(searchFrom);
|
|
1511
|
+
}
|
|
1512
|
+
function redactDiagnosticText(message) {
|
|
1513
|
+
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>");
|
|
1514
|
+
return redactHomeDirectory(redacted);
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/lib/opencode/session-db-reclaim.ts
|
|
1518
|
+
var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
|
|
1398
1519
|
var SESSION_DB_RECLAIM_TIME_BUDGET_MS = 500;
|
|
1399
1520
|
var SESSION_DB_RECLAIM_PAGE_CEILING = 4e4;
|
|
1521
|
+
var SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS = 5e3;
|
|
1400
1522
|
function errorMessage(error2) {
|
|
1401
1523
|
if (!(error2 instanceof Error)) return String(error2);
|
|
1402
1524
|
return error2.cause instanceof Error ? error2.cause.message : error2.message;
|
|
1403
1525
|
}
|
|
1404
|
-
function
|
|
1526
|
+
function errorMessages(error2) {
|
|
1405
1527
|
const messages = [];
|
|
1406
1528
|
const visited = /* @__PURE__ */ new Set();
|
|
1407
1529
|
let current = error2;
|
|
@@ -1425,12 +1547,81 @@ function isSessionStoreWriteFailure(error2) {
|
|
|
1425
1547
|
}
|
|
1426
1548
|
break;
|
|
1427
1549
|
}
|
|
1428
|
-
return messages
|
|
1550
|
+
return messages;
|
|
1551
|
+
}
|
|
1552
|
+
function isSessionStoreWriteFailure(error2) {
|
|
1553
|
+
return errorMessages(error2).some(
|
|
1429
1554
|
(message) => /(?:database or disk is full|disk is full|no space left on device|SQLITE_(?:FULL|IOERR)(?:\b|_))/i.test(
|
|
1430
1555
|
message
|
|
1431
1556
|
)
|
|
1432
1557
|
);
|
|
1433
1558
|
}
|
|
1559
|
+
var SQLITE_CAUSE_TOKEN = /(?:^|cause:\s+)(SQLiteError:\s+[A-Za-z][A-Za-z0-9]*(?:\s+[A-Za-z][A-Za-z0-9]*){0,7})(?=\s*(?:[)\]"',;]|$))/i;
|
|
1560
|
+
var EFFECT_SQL_CAUSE_TOKEN = /(?:^|cause:\s+)(effect\/sql\/SqlError\/[A-Za-z][A-Za-z0-9_]*)/i;
|
|
1561
|
+
var PARAMS_FIELD = /\bparams\s*(?:=|:)/i;
|
|
1562
|
+
function isCauseBearingText(text) {
|
|
1563
|
+
return /^(?:SQLiteError:\s+|effect\/sql\/SqlError\/)/i.test(text.trim()) || /(?:^|\s)cause:\s+(?:SQLiteError:\s+|effect\/sql\/SqlError\/)/i.test(text);
|
|
1564
|
+
}
|
|
1565
|
+
function structuredLogFields(line) {
|
|
1566
|
+
const fields = [];
|
|
1567
|
+
for (let index = 0; index < line.length; index++) {
|
|
1568
|
+
if (line[index] === '"') {
|
|
1569
|
+
index++;
|
|
1570
|
+
while (index < line.length) {
|
|
1571
|
+
if (line[index] === "\\") {
|
|
1572
|
+
index++;
|
|
1573
|
+
} else if (line[index] === '"') {
|
|
1574
|
+
break;
|
|
1575
|
+
}
|
|
1576
|
+
index++;
|
|
1577
|
+
}
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1580
|
+
const atFieldBoundary = index === 0 || /\s/.test(line[index - 1]);
|
|
1581
|
+
const key = line.startsWith("error=", index) ? "error=" : line.startsWith("cause=", index) ? "cause=" : null;
|
|
1582
|
+
if (!atFieldBoundary || key === null) continue;
|
|
1583
|
+
const valueStart = index + key.length;
|
|
1584
|
+
if (line[valueStart] !== '"') {
|
|
1585
|
+
const valueEnd2 = line.indexOf(" ", valueStart);
|
|
1586
|
+
fields.push(line.slice(valueStart, valueEnd2 === -1 ? line.length : valueEnd2));
|
|
1587
|
+
index = valueEnd2 === -1 ? line.length : valueEnd2;
|
|
1588
|
+
continue;
|
|
1589
|
+
}
|
|
1590
|
+
let valueEnd = valueStart + 1;
|
|
1591
|
+
for (; valueEnd < line.length; valueEnd++) {
|
|
1592
|
+
if (line[valueEnd] === "\\") {
|
|
1593
|
+
valueEnd++;
|
|
1594
|
+
} else if (line[valueEnd] === '"') {
|
|
1595
|
+
break;
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
fields.push(line.slice(valueStart + 1, valueEnd));
|
|
1599
|
+
index = valueEnd;
|
|
1600
|
+
}
|
|
1601
|
+
return fields;
|
|
1602
|
+
}
|
|
1603
|
+
function structuredCauseMessages(text) {
|
|
1604
|
+
const fields = structuredLogFields(text);
|
|
1605
|
+
if (fields.length > 0) return fields;
|
|
1606
|
+
return isCauseBearingText(text) ? [text] : [];
|
|
1607
|
+
}
|
|
1608
|
+
function causeTokenFromText(text) {
|
|
1609
|
+
const paramsIndex = text.search(PARAMS_FIELD);
|
|
1610
|
+
for (const pattern of [SQLITE_CAUSE_TOKEN, EFFECT_SQL_CAUSE_TOKEN]) {
|
|
1611
|
+
const match = pattern.exec(text);
|
|
1612
|
+
if (match?.[1] && (paramsIndex === -1 || match.index < paramsIndex)) {
|
|
1613
|
+
return match[1];
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
return null;
|
|
1617
|
+
}
|
|
1618
|
+
function sessionStoreCauseToken(value) {
|
|
1619
|
+
for (const message of structuredCauseMessages(value)) {
|
|
1620
|
+
const token = causeTokenFromText(message);
|
|
1621
|
+
if (token !== null) return redactDiagnosticText(token).slice(0, 120);
|
|
1622
|
+
}
|
|
1623
|
+
return null;
|
|
1624
|
+
}
|
|
1434
1625
|
function insufficientSpaceReason(dbPath, requiredBytes) {
|
|
1435
1626
|
try {
|
|
1436
1627
|
const fsStats = statfsSync(dirname2(dbPath));
|
|
@@ -1452,6 +1643,7 @@ function readFreelistCount(db) {
|
|
|
1452
1643
|
return db.prepare("PRAGMA freelist_count").get().freelist_count;
|
|
1453
1644
|
}
|
|
1454
1645
|
function readCheckpointResult(db) {
|
|
1646
|
+
db.exec("PRAGMA busy_timeout=0");
|
|
1455
1647
|
const row = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
|
|
1456
1648
|
return { busy: row.busy !== 0, log: row.log, checkpointed: row.checkpointed };
|
|
1457
1649
|
}
|
|
@@ -1469,7 +1661,7 @@ async function probeReclaimAvailability(input) {
|
|
|
1469
1661
|
try {
|
|
1470
1662
|
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
|
|
1471
1663
|
try {
|
|
1472
|
-
db.exec(
|
|
1664
|
+
db.exec(`PRAGMA busy_timeout=${SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS}`);
|
|
1473
1665
|
autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
|
|
1474
1666
|
} finally {
|
|
1475
1667
|
db.close();
|
|
@@ -1489,7 +1681,8 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1489
1681
|
timeBudgetMs = SESSION_DB_RECLAIM_TIME_BUDGET_MS,
|
|
1490
1682
|
chunkPages = SESSION_DB_RECLAIM_CHUNK_PAGES,
|
|
1491
1683
|
now = () => performance.now(),
|
|
1492
|
-
|
|
1684
|
+
hasLiveTurn = false,
|
|
1685
|
+
hasProvenanceAnomaly = false
|
|
1493
1686
|
} = input;
|
|
1494
1687
|
let sqlite;
|
|
1495
1688
|
try {
|
|
@@ -1505,17 +1698,19 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1505
1698
|
let db;
|
|
1506
1699
|
try {
|
|
1507
1700
|
db = new DatabaseSync(dbPath);
|
|
1508
|
-
db.exec(
|
|
1701
|
+
db.exec(`PRAGMA busy_timeout=${SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS}`);
|
|
1509
1702
|
const autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
|
|
1510
1703
|
if (autoVacuum === 0) {
|
|
1511
|
-
if (
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1704
|
+
if (hasLiveTurn || hasProvenanceAnomaly) {
|
|
1705
|
+
const detail = [
|
|
1706
|
+
...hasLiveTurn ? ["a session turn is live"] : [],
|
|
1707
|
+
...hasProvenanceAnomaly ? ["session-DB provenance is anomalous"] : []
|
|
1708
|
+
].join(" and ");
|
|
1709
|
+
console.warn(`[reclaimSessionDbSpace] skipping VACUUM conversion of ${dbPath}: ${detail}`);
|
|
1515
1710
|
return {
|
|
1516
1711
|
ok: false,
|
|
1517
1712
|
skipped: "full-vacuum-blocked",
|
|
1518
|
-
detail
|
|
1713
|
+
detail
|
|
1519
1714
|
};
|
|
1520
1715
|
}
|
|
1521
1716
|
const fileBytesForGuard = statSync2(dbPath).size;
|
|
@@ -1533,7 +1728,9 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1533
1728
|
db.exec("VACUUM");
|
|
1534
1729
|
const afterBytes = readLogicalBytes(db);
|
|
1535
1730
|
const freelistAfter = readFreelistCount(db);
|
|
1731
|
+
const checkpointStartedAt = now();
|
|
1536
1732
|
const checkpoint = readCheckpointResult(db);
|
|
1733
|
+
const checkpointElapsedMs = Math.max(0, now() - checkpointStartedAt);
|
|
1537
1734
|
return {
|
|
1538
1735
|
ok: true,
|
|
1539
1736
|
mode: "convert",
|
|
@@ -1544,10 +1741,18 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1544
1741
|
pagesReclaimed: Math.max(0, freelistBefore - freelistAfter),
|
|
1545
1742
|
stoppedBy: "freelist-drained",
|
|
1546
1743
|
elapsedMs: Math.max(0, now() - startedAt),
|
|
1744
|
+
checkpointElapsedMs,
|
|
1547
1745
|
checkpoint
|
|
1548
1746
|
};
|
|
1549
1747
|
}
|
|
1550
1748
|
if (autoVacuum === 2) {
|
|
1749
|
+
if (hasLiveTurn) {
|
|
1750
|
+
const detail = "a session turn is live";
|
|
1751
|
+
console.warn(
|
|
1752
|
+
`[reclaimSessionDbSpace] skipping incremental reclaim of ${dbPath}: ${detail}`
|
|
1753
|
+
);
|
|
1754
|
+
return { ok: false, skipped: "live-turn", detail };
|
|
1755
|
+
}
|
|
1551
1756
|
const beforeBytes = readLogicalBytes(db);
|
|
1552
1757
|
const freelistBefore = readFreelistCount(db);
|
|
1553
1758
|
const startedAt = now();
|
|
@@ -1572,7 +1777,9 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1572
1777
|
freelistAfter = readFreelistCount(db);
|
|
1573
1778
|
}
|
|
1574
1779
|
const afterBytes = readLogicalBytes(db);
|
|
1780
|
+
const checkpointStartedAt = now();
|
|
1575
1781
|
const checkpoint = readCheckpointResult(db);
|
|
1782
|
+
const checkpointElapsedMs = Math.max(0, now() - checkpointStartedAt);
|
|
1576
1783
|
return {
|
|
1577
1784
|
ok: true,
|
|
1578
1785
|
mode: "incremental",
|
|
@@ -1583,6 +1790,7 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1583
1790
|
pagesReclaimed: Math.max(0, freelistBefore - freelistAfter),
|
|
1584
1791
|
stoppedBy,
|
|
1585
1792
|
elapsedMs: Math.max(0, now() - startedAt),
|
|
1793
|
+
checkpointElapsedMs,
|
|
1586
1794
|
checkpoint
|
|
1587
1795
|
};
|
|
1588
1796
|
}
|
|
@@ -1602,6 +1810,263 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1602
1810
|
}
|
|
1603
1811
|
}
|
|
1604
1812
|
|
|
1813
|
+
// src/lib/opencode/dependency-install-diagnostic.ts
|
|
1814
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
1815
|
+
import { basename, dirname as dirname3, isAbsolute, join as join2, relative, resolve, sep } from "node:path";
|
|
1816
|
+
var DEPENDENCY_INSTALL_FAILURE_MESSAGE = "background dependency install failed";
|
|
1817
|
+
var MAX_DISTINCT_DIAGNOSTICS = 32;
|
|
1818
|
+
var EFFECT = "OpenCode could not install background dependencies for this scope; its plugins and tools may be unavailable";
|
|
1819
|
+
function readOpenCodeLogField(line, key) {
|
|
1820
|
+
const match = line.match(new RegExp(`(?:^|\\s)${key}=(?:"((?:\\\\.|[^"])*)"|(\\S+))`));
|
|
1821
|
+
if (!match) return void 0;
|
|
1822
|
+
if (match[1] === void 0) return match[2];
|
|
1823
|
+
return match[1].replace(/\\(["\\n])/g, (_match, escaped) => {
|
|
1824
|
+
return escaped === "n" ? "\n" : escaped;
|
|
1825
|
+
});
|
|
1826
|
+
}
|
|
1827
|
+
function parseTrigger(line) {
|
|
1828
|
+
if (readOpenCodeLogField(line, "message") !== DEPENDENCY_INSTALL_FAILURE_MESSAGE) {
|
|
1829
|
+
return null;
|
|
1830
|
+
}
|
|
1831
|
+
const error2 = readOpenCodeLogField(line, "error");
|
|
1832
|
+
if (!error2 || !/\bEACCES\b/.test(error2)) return null;
|
|
1833
|
+
const errnoMatch = error2.match(/\bEACCES:\s*permission denied,\s*([a-z_]+)\s+'([^']*)'/);
|
|
1834
|
+
const capturedPath = errnoMatch?.[2];
|
|
1835
|
+
return {
|
|
1836
|
+
dir: readOpenCodeLogField(line, "dir"),
|
|
1837
|
+
op: errnoMatch?.[1],
|
|
1838
|
+
path: capturedPath && isAbsolute(capturedPath) ? capturedPath : void 0
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
function getErrorCode(error2) {
|
|
1842
|
+
if (typeof error2 === "object" && error2 !== null && "code" in error2) {
|
|
1843
|
+
const code = error2.code;
|
|
1844
|
+
if (typeof code === "string") return code;
|
|
1845
|
+
}
|
|
1846
|
+
return "UNKNOWN";
|
|
1847
|
+
}
|
|
1848
|
+
function isWithin(path, root) {
|
|
1849
|
+
const candidate = resolve(path);
|
|
1850
|
+
const resolvedRoot = resolve(root);
|
|
1851
|
+
return candidate === resolvedRoot || candidate.startsWith(`${resolvedRoot}${sep}`);
|
|
1852
|
+
}
|
|
1853
|
+
function rootSpecs(context) {
|
|
1854
|
+
return [
|
|
1855
|
+
{ token: "~", configured: resolve(context.homeDir) },
|
|
1856
|
+
{ token: "$WORKSPACE", configured: resolve(context.cwd) }
|
|
1857
|
+
];
|
|
1858
|
+
}
|
|
1859
|
+
function resolveRoots(context) {
|
|
1860
|
+
const resolved = [];
|
|
1861
|
+
const unresolved = [];
|
|
1862
|
+
for (const spec of rootSpecs(context)) {
|
|
1863
|
+
try {
|
|
1864
|
+
resolved.push({ ...spec, real: realpathSync(spec.configured) });
|
|
1865
|
+
} catch (_error) {
|
|
1866
|
+
unresolved.push(spec);
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
return { resolved, unresolved };
|
|
1870
|
+
}
|
|
1871
|
+
function resolveNearestAncestor(failingPath, remaining, error2) {
|
|
1872
|
+
let ancestor = dirname3(failingPath);
|
|
1873
|
+
const suffix = [basename(failingPath), ...remaining];
|
|
1874
|
+
while (ancestor) {
|
|
1875
|
+
try {
|
|
1876
|
+
return {
|
|
1877
|
+
path: resolve(realpathSync(ancestor), ...suffix),
|
|
1878
|
+
failure: { path: resolve(failingPath), error: error2 }
|
|
1879
|
+
};
|
|
1880
|
+
} catch (ancestorError) {
|
|
1881
|
+
if (ancestor === dirname3(ancestor) || !getErrorCode(ancestorError).startsWith("E")) {
|
|
1882
|
+
return null;
|
|
1883
|
+
}
|
|
1884
|
+
suffix.unshift(basename(ancestor));
|
|
1885
|
+
ancestor = dirname3(ancestor);
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
return null;
|
|
1889
|
+
}
|
|
1890
|
+
function resolveExistingPath(absolutePath) {
|
|
1891
|
+
if (!isAbsolute(absolutePath)) return null;
|
|
1892
|
+
const candidate = resolve(absolutePath);
|
|
1893
|
+
const remaining = [];
|
|
1894
|
+
let current = candidate;
|
|
1895
|
+
while (current) {
|
|
1896
|
+
try {
|
|
1897
|
+
const stat2 = lstatSync(current);
|
|
1898
|
+
if (stat2.isSymbolicLink()) {
|
|
1899
|
+
if (remaining.length === 0) {
|
|
1900
|
+
return { path: join2(realpathSync(dirname3(current)), basename(current)) };
|
|
1901
|
+
}
|
|
1902
|
+
return { path: resolve(realpathSync(current), ...remaining) };
|
|
1903
|
+
}
|
|
1904
|
+
return { path: resolve(realpathSync(current), ...remaining) };
|
|
1905
|
+
} catch (error2) {
|
|
1906
|
+
const code = getErrorCode(error2);
|
|
1907
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
1908
|
+
return resolveNearestAncestor(current, remaining, error2);
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
if (current === dirname3(current)) return null;
|
|
1912
|
+
remaining.unshift(basename(current));
|
|
1913
|
+
current = dirname3(current);
|
|
1914
|
+
}
|
|
1915
|
+
return null;
|
|
1916
|
+
}
|
|
1917
|
+
function tokenise(absolutePath, roots) {
|
|
1918
|
+
const pathResolution = resolveExistingPath(absolutePath);
|
|
1919
|
+
if (!pathResolution) return null;
|
|
1920
|
+
const root = roots.reduce((selected, candidate) => {
|
|
1921
|
+
if (!isWithin(pathResolution.path, candidate.real)) return selected;
|
|
1922
|
+
if (!selected || candidate.real.length > selected.real.length || candidate.real.length === selected.real.length && candidate.token === "$WORKSPACE") {
|
|
1923
|
+
return candidate;
|
|
1924
|
+
}
|
|
1925
|
+
return selected;
|
|
1926
|
+
}, null);
|
|
1927
|
+
if (!root) return null;
|
|
1928
|
+
const suffix = relative(root.real, pathResolution.path);
|
|
1929
|
+
return {
|
|
1930
|
+
value: suffix ? `${root.token}/${suffix.split(sep).join("/")}` : root.token,
|
|
1931
|
+
root,
|
|
1932
|
+
resolutionFailure: pathResolution.failure
|
|
1933
|
+
};
|
|
1934
|
+
}
|
|
1935
|
+
function classifyScope(dir, roots) {
|
|
1936
|
+
if (!dir) return "other";
|
|
1937
|
+
const tokenisedDir = tokenise(dir, roots.resolved);
|
|
1938
|
+
if (tokenisedDir) return tokenisedDir.root.token === "$WORKSPACE" ? "workspace" : "global";
|
|
1939
|
+
for (const spec of roots.unresolved) {
|
|
1940
|
+
if (isWithin(dir, spec.configured)) {
|
|
1941
|
+
return spec.token === "$WORKSPACE" ? "workspace" : "global";
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
return "other";
|
|
1945
|
+
}
|
|
1946
|
+
function unresolvedRootForPath(path, unresolved) {
|
|
1947
|
+
return unresolved.find((spec) => isWithin(path, spec.configured));
|
|
1948
|
+
}
|
|
1949
|
+
function statType(stat2) {
|
|
1950
|
+
if (stat2.isDirectory()) return "d";
|
|
1951
|
+
if (stat2.isFile()) return "f";
|
|
1952
|
+
if (stat2.isSymbolicLink()) return "l";
|
|
1953
|
+
return "o";
|
|
1954
|
+
}
|
|
1955
|
+
function renderStat(name, stat2) {
|
|
1956
|
+
const mode = (stat2.mode & 4095).toString(8).padStart(4, "0");
|
|
1957
|
+
return `${name}:${statType(stat2)}:${stat2.uid}:${stat2.gid}:${mode}`;
|
|
1958
|
+
}
|
|
1959
|
+
function renderStatError(name, error2) {
|
|
1960
|
+
const code = getErrorCode(error2);
|
|
1961
|
+
return `${name}:${renderErrorCode(code)}`;
|
|
1962
|
+
}
|
|
1963
|
+
function renderErrorCode(code) {
|
|
1964
|
+
if (code === "ENOENT") return "missing";
|
|
1965
|
+
return code.startsWith("E") ? code : `E${code}`;
|
|
1966
|
+
}
|
|
1967
|
+
function inspectChain(rootReal, rootToken, absolutePath, resolutionFailure) {
|
|
1968
|
+
const target = resolve(absolutePath);
|
|
1969
|
+
const relativePath = relative(rootReal, target);
|
|
1970
|
+
const components = relativePath ? relativePath.split(sep) : [];
|
|
1971
|
+
const entries = [];
|
|
1972
|
+
let current = rootReal;
|
|
1973
|
+
let status2 = "complete";
|
|
1974
|
+
let finalStat;
|
|
1975
|
+
for (const name of [rootToken, ...components]) {
|
|
1976
|
+
if (name !== rootToken) current = join2(current, name);
|
|
1977
|
+
if (resolutionFailure && resolve(current) === resolve(resolutionFailure.path)) {
|
|
1978
|
+
entries.push(renderStatError(name, resolutionFailure.error));
|
|
1979
|
+
status2 = "stat_failed";
|
|
1980
|
+
break;
|
|
1981
|
+
}
|
|
1982
|
+
try {
|
|
1983
|
+
const stat2 = lstatSync(current);
|
|
1984
|
+
entries.push(renderStat(name, stat2));
|
|
1985
|
+
finalStat = stat2;
|
|
1986
|
+
} catch (error2) {
|
|
1987
|
+
entries.push(renderStatError(name, error2));
|
|
1988
|
+
if (getErrorCode(error2) !== "ENOENT") status2 = "stat_failed";
|
|
1989
|
+
break;
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
let symlinkTarget;
|
|
1993
|
+
let symlinkMeta;
|
|
1994
|
+
if (finalStat?.isSymbolicLink() && entries.length === components.length + 1) {
|
|
1995
|
+
try {
|
|
1996
|
+
symlinkTarget = realpathSync(current);
|
|
1997
|
+
try {
|
|
1998
|
+
symlinkMeta = renderStat("", lstatSync(symlinkTarget)).slice(1);
|
|
1999
|
+
} catch (error2) {
|
|
2000
|
+
symlinkMeta = renderErrorCode(getErrorCode(error2));
|
|
2001
|
+
status2 = "stat_failed";
|
|
2002
|
+
}
|
|
2003
|
+
} catch (error2) {
|
|
2004
|
+
symlinkTarget = "<unresolved>";
|
|
2005
|
+
symlinkMeta = renderErrorCode(getErrorCode(error2));
|
|
2006
|
+
status2 = "stat_failed";
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
return { status: status2, chain: entries.join(","), symlinkTarget, symlinkMeta };
|
|
2010
|
+
}
|
|
2011
|
+
function buildDiagnostic(line, context) {
|
|
2012
|
+
const trigger = parseTrigger(line);
|
|
2013
|
+
if (!trigger) return null;
|
|
2014
|
+
const roots = resolveRoots(context);
|
|
2015
|
+
const scope = classifyScope(trigger.dir, roots);
|
|
2016
|
+
const pathSource = trigger.path ? "error" : trigger.dir ? "dir" : "none";
|
|
2017
|
+
const inspectedPath = trigger.path ?? trigger.dir;
|
|
2018
|
+
const microvmId = context.microvmId?.trim() || "unknown";
|
|
2019
|
+
const euid = context.euid === void 0 ? "unavailable" : String(context.euid);
|
|
2020
|
+
const egid = context.egid === void 0 ? "unavailable" : String(context.egid);
|
|
2021
|
+
const op = trigger.op ?? "unknown";
|
|
2022
|
+
if (!inspectedPath) {
|
|
2023
|
+
return {
|
|
2024
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=no_path path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=unknown cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
|
|
2025
|
+
localDetail: null
|
|
2026
|
+
};
|
|
2027
|
+
}
|
|
2028
|
+
const tokenisedPath = tokenise(inspectedPath, roots.resolved);
|
|
2029
|
+
if (!tokenisedPath) {
|
|
2030
|
+
const unresolvedRoot = unresolvedRootForPath(inspectedPath, roots.unresolved);
|
|
2031
|
+
if (unresolvedRoot) {
|
|
2032
|
+
return {
|
|
2033
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=root_unresolved path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=unknown cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
|
|
2034
|
+
localDetail: null
|
|
2035
|
+
};
|
|
2036
|
+
}
|
|
2037
|
+
return {
|
|
2038
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=outside_roots path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=<outside-approved-roots> cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
|
|
2039
|
+
localDetail: `OPENCODE-DEPENDENCY-INSTALL-EACCES (local only): outside approved roots: ${inspectedPath}`
|
|
2040
|
+
};
|
|
2041
|
+
}
|
|
2042
|
+
const inspection = inspectChain(
|
|
2043
|
+
tokenisedPath.root.real,
|
|
2044
|
+
tokenisedPath.root.token,
|
|
2045
|
+
inspectedPath,
|
|
2046
|
+
tokenisedPath.resolutionFailure
|
|
2047
|
+
);
|
|
2048
|
+
const optionalSymlinkFields = inspection.symlinkTarget ? ` symlink_target=${tokenise(inspection.symlinkTarget, roots.resolved)?.value ?? "<outside-approved-roots>"}` + (inspection.symlinkMeta ? ` symlink_meta=${inspection.symlinkMeta}` : "") : "";
|
|
2049
|
+
return {
|
|
2050
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=${inspection.status} path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=${tokenisedPath.value} cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=${inspection.chain}${optionalSymlinkFields}`,
|
|
2051
|
+
localDetail: null
|
|
2052
|
+
};
|
|
2053
|
+
}
|
|
2054
|
+
function createDependencyInstallDiagnosticReporter({
|
|
2055
|
+
context,
|
|
2056
|
+
emitEvent: emitEvent2,
|
|
2057
|
+
emitLocal
|
|
2058
|
+
}) {
|
|
2059
|
+
const emittedEvents = /* @__PURE__ */ new Set();
|
|
2060
|
+
return (line) => {
|
|
2061
|
+
const diagnostic = buildDiagnostic(line, context);
|
|
2062
|
+
if (!diagnostic || emittedEvents.has(diagnostic.event)) return;
|
|
2063
|
+
if (emittedEvents.size >= MAX_DISTINCT_DIAGNOSTICS) return;
|
|
2064
|
+
emittedEvents.add(diagnostic.event);
|
|
2065
|
+
emitEvent2(diagnostic.event);
|
|
2066
|
+
if (diagnostic.localDetail) emitLocal(diagnostic.localDetail);
|
|
2067
|
+
};
|
|
2068
|
+
}
|
|
2069
|
+
|
|
1605
2070
|
// src/lib/runner-activity-telemetry.ts
|
|
1606
2071
|
var FORWARDED_LEVELS_BY_SOURCE = {
|
|
1607
2072
|
"cli.run": /* @__PURE__ */ new Set(["warn", "error"]),
|
|
@@ -1633,7 +2098,17 @@ function parseOpenCodeLogLine(line) {
|
|
|
1633
2098
|
}
|
|
1634
2099
|
var MAX_LINE_BUFFER_BYTES = 16 * 1024;
|
|
1635
2100
|
var REPEAT_SUPPRESSION_WINDOW_MS = 6e4;
|
|
1636
|
-
function
|
|
2101
|
+
function sanitiseDependencyInstallWarning(line) {
|
|
2102
|
+
const withoutDirectory = line.replace(
|
|
2103
|
+
/((?:^|\s)dir=)(?:"(?:\\.|[^"])*"|\/[^\s)"']+|\S+)/g,
|
|
2104
|
+
"$1<path>"
|
|
2105
|
+
);
|
|
2106
|
+
return withoutDirectory.replace(
|
|
2107
|
+
/((?:^|\s)error=)"((?:\\.|[^"])*)"/,
|
|
2108
|
+
(_match, prefix, error2) => `${prefix}"${error2.replace(/'\/[^']*'/g, "'<path>'")}"`
|
|
2109
|
+
);
|
|
2110
|
+
}
|
|
2111
|
+
function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure, onDependencyInstallFailure) {
|
|
1637
2112
|
let buffer = Buffer.alloc(0);
|
|
1638
2113
|
const repeatStates = /* @__PURE__ */ new Map();
|
|
1639
2114
|
const forwardLine = (line, parsed, repeatsSuppressed = 0) => {
|
|
@@ -1645,7 +2120,7 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
|
|
|
1645
2120
|
forwardRunnerActivity(
|
|
1646
2121
|
{
|
|
1647
2122
|
level: parsed.level,
|
|
1648
|
-
error: line,
|
|
2123
|
+
error: parsed.message === DEPENDENCY_INSTALL_FAILURE_MESSAGE ? sanitiseDependencyInstallWarning(line) : line,
|
|
1649
2124
|
metadata: Object.keys(metadata).length > 0 ? metadata : void 0,
|
|
1650
2125
|
source: "opencode"
|
|
1651
2126
|
},
|
|
@@ -1663,18 +2138,7 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
|
|
|
1663
2138
|
repeatStates.delete(key);
|
|
1664
2139
|
}
|
|
1665
2140
|
};
|
|
1666
|
-
const
|
|
1667
|
-
if (onSessionStoreWriteFailure && isSessionStoreWriteFailure(line)) {
|
|
1668
|
-
try {
|
|
1669
|
-
onSessionStoreWriteFailure();
|
|
1670
|
-
} catch (err) {
|
|
1671
|
-
reportTelemetryDiagnostic(
|
|
1672
|
-
`Runner activity telemetry could not record session-store write failure: ${err instanceof Error ? err.message : String(err)}`
|
|
1673
|
-
);
|
|
1674
|
-
}
|
|
1675
|
-
}
|
|
1676
|
-
const parsed = parseOpenCodeLogLine(line);
|
|
1677
|
-
if (!parsed) return;
|
|
2141
|
+
const forwardWithRepeatSuppression = (line, parsed) => {
|
|
1678
2142
|
const now = Date.now();
|
|
1679
2143
|
const key = parsed.message === void 0 ? void 0 : `${parsed.level}\0${parsed.message}\0${parsed.sessionID ?? ""}\0${parsed.messageID ?? ""}`;
|
|
1680
2144
|
expireRepeatStates(now, key);
|
|
@@ -1697,6 +2161,35 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
|
|
|
1697
2161
|
previous.parsed = parsed;
|
|
1698
2162
|
previous.repeatsSuppressed++;
|
|
1699
2163
|
};
|
|
2164
|
+
const flushLine = (line) => {
|
|
2165
|
+
const parsed = parseOpenCodeLogLine(line);
|
|
2166
|
+
const isDiskFailure = isSessionStoreWriteFailure(line);
|
|
2167
|
+
const cause = sessionStoreCauseToken(line);
|
|
2168
|
+
if (onSessionStoreWriteFailure && (isDiskFailure || cause !== null)) {
|
|
2169
|
+
try {
|
|
2170
|
+
onSessionStoreWriteFailure({
|
|
2171
|
+
isDiskFailure,
|
|
2172
|
+
sessionId: parsed?.sessionID ?? null,
|
|
2173
|
+
cause
|
|
2174
|
+
});
|
|
2175
|
+
} catch (err) {
|
|
2176
|
+
reportTelemetryDiagnostic(
|
|
2177
|
+
`Runner activity telemetry could not record session-store write failure: ${err instanceof Error ? err.message : String(err)}`
|
|
2178
|
+
);
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
if (!parsed) return;
|
|
2182
|
+
forwardWithRepeatSuppression(line, parsed);
|
|
2183
|
+
if (onDependencyInstallFailure && parsed.message === DEPENDENCY_INSTALL_FAILURE_MESSAGE) {
|
|
2184
|
+
try {
|
|
2185
|
+
onDependencyInstallFailure(line);
|
|
2186
|
+
} catch (err) {
|
|
2187
|
+
reportTelemetryDiagnostic(
|
|
2188
|
+
`Runner activity telemetry could not record dependency-install failure diagnostic: ${err instanceof Error ? err.message : String(err)}`
|
|
2189
|
+
);
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
};
|
|
1700
2193
|
const forward = ((chunk) => {
|
|
1701
2194
|
buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf-8")]);
|
|
1702
2195
|
let newlineIndex;
|
|
@@ -1722,34 +2215,38 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
|
|
|
1722
2215
|
var MAX_MESSAGE_LENGTH = 500;
|
|
1723
2216
|
var MAX_METADATA_VALUE_LENGTH = 200;
|
|
1724
2217
|
var MAX_METADATA_ENTRIES = 20;
|
|
1725
|
-
var TRUNCATION_MARKER = "\u2026";
|
|
1726
|
-
function redactHomeDirectory(message) {
|
|
1727
|
-
const home = homedir2();
|
|
1728
|
-
if (!home || home === "/") {
|
|
1729
|
-
return message;
|
|
1730
|
-
}
|
|
1731
|
-
const pathSegmentCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-";
|
|
1732
|
-
let result = "";
|
|
1733
|
-
let searchFrom = 0;
|
|
1734
|
-
let homeIndex;
|
|
1735
|
-
while ((homeIndex = message.indexOf(home, searchFrom)) !== -1) {
|
|
1736
|
-
const homeEnd = homeIndex + home.length;
|
|
1737
|
-
const previousCharacter = message[homeIndex - 1];
|
|
1738
|
-
const nextCharacter = message[homeEnd];
|
|
1739
|
-
const atPathBoundary = home === "/" || (!previousCharacter || !pathSegmentCharacters.includes(previousCharacter)) && (!nextCharacter || !pathSegmentCharacters.includes(nextCharacter));
|
|
1740
|
-
result += message.slice(searchFrom, homeIndex);
|
|
1741
|
-
result += atPathBoundary ? "~" : home;
|
|
1742
|
-
searchFrom = homeEnd;
|
|
1743
|
-
}
|
|
1744
|
-
return result + message.slice(searchFrom);
|
|
1745
|
-
}
|
|
1746
|
-
function redactDiagnosticText(message) {
|
|
1747
|
-
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>");
|
|
1748
|
-
return redactHomeDirectory(redacted);
|
|
1749
|
-
}
|
|
1750
2218
|
function truncate(message) {
|
|
1751
2219
|
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
1752
|
-
|
|
2220
|
+
let dropped = message.length - MAX_MESSAGE_LENGTH;
|
|
2221
|
+
let marker = `\u2026${dropped} chars omitted\u2026`;
|
|
2222
|
+
let previousDropped = -1;
|
|
2223
|
+
while (dropped !== previousDropped) {
|
|
2224
|
+
previousDropped = dropped;
|
|
2225
|
+
const nextDropped = message.length - MAX_MESSAGE_LENGTH + marker.length;
|
|
2226
|
+
dropped = nextDropped;
|
|
2227
|
+
marker = `\u2026${dropped} chars omitted\u2026`;
|
|
2228
|
+
}
|
|
2229
|
+
const remaining = MAX_MESSAGE_LENGTH - marker.length;
|
|
2230
|
+
const headLength = Math.ceil(remaining * 0.6);
|
|
2231
|
+
const tailLength = remaining - headLength;
|
|
2232
|
+
const effectMatch = message.startsWith("OPENCODE-DEPENDENCY-INSTALL-EACCES:") ? message.match(/ effect="[^"]*"/) : null;
|
|
2233
|
+
if (effectMatch?.index !== void 0) {
|
|
2234
|
+
const effectEnd = effectMatch.index + effectMatch[0].length;
|
|
2235
|
+
if (effectEnd > headLength && effectEnd < message.length) {
|
|
2236
|
+
const effectLength = effectMatch[0].length;
|
|
2237
|
+
const nonEffectLength = remaining - effectLength;
|
|
2238
|
+
const preservedTailLength = Math.min(
|
|
2239
|
+
message.length - effectEnd,
|
|
2240
|
+
nonEffectLength - Math.min(effectMatch.index, Math.ceil(nonEffectLength * 0.6))
|
|
2241
|
+
);
|
|
2242
|
+
const preservedHeadLength = Math.min(
|
|
2243
|
+
effectMatch.index,
|
|
2244
|
+
nonEffectLength - preservedTailLength
|
|
2245
|
+
);
|
|
2246
|
+
return message.slice(0, preservedHeadLength) + marker + message.slice(effectMatch.index, effectEnd) + message.slice(message.length - preservedTailLength);
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
return message.slice(0, headLength) + marker + message.slice(message.length - tailLength);
|
|
1753
2250
|
}
|
|
1754
2251
|
function sanitiseMetadata(metadata) {
|
|
1755
2252
|
if (!metadata) return {};
|
|
@@ -1826,10 +2323,10 @@ function forwardRunnerActivity(entry, context) {
|
|
|
1826
2323
|
|
|
1827
2324
|
// src/lib/opencode/session-db-recovery-report.ts
|
|
1828
2325
|
import { readFileSync as readFileSync2, unlinkSync } from "node:fs";
|
|
1829
|
-
import { join as
|
|
2326
|
+
import { join as join3 } from "node:path";
|
|
1830
2327
|
function sessionDbRecoveryReportPath(homeDir, env) {
|
|
1831
2328
|
const override = env.EVIDENT_SESSION_DB_RECOVERY_REPORT?.trim();
|
|
1832
|
-
return override ||
|
|
2329
|
+
return override || join3(homeDir, ".local", "state", "evident", "session-db-recovery.jsonl");
|
|
1833
2330
|
}
|
|
1834
2331
|
function drainSessionDbRecoveryReport({
|
|
1835
2332
|
homeDir,
|
|
@@ -1959,12 +2456,23 @@ function buildSessionDbRecoveryActivity(record) {
|
|
|
1959
2456
|
metadata: withoutContractFields(record),
|
|
1960
2457
|
message: `This runner started without restoring session history because it could not verify where its session history is backed up. Nothing in the backup was changed; check the runner backup configuration and permissions.${replication}`
|
|
1961
2458
|
};
|
|
1962
|
-
case "session_db_boot_refused":
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
2459
|
+
case "session_db_boot_refused": {
|
|
2460
|
+
const message = (() => {
|
|
2461
|
+
switch (record.reason) {
|
|
2462
|
+
case "local_discard_failed":
|
|
2463
|
+
return `This runner did not come online because its damaged session database could not be safely separated from its active backup or proven removed. Backed-up session history remains readable at ${record.quarantine_destination ?? "its original location or the quarantine destination named in the boot logs"}; any local session-database files that remain were left in place and nothing opened or wrote them. See the runner boot logs for SESSION-DB-LOCAL-DISCARD-FAILED details.`;
|
|
2464
|
+
case "replica_separation_unproven":
|
|
2465
|
+
return `This runner did not come online because its damaged session database could not be safely separated from its active backup. The SESSION-DB-REPLICA-SEPARATION-UNVERIFIED boot log contains the partial-quarantine moved and remaining counts. Backed-up session history remains readable at ${record.quarantine_destination ?? "its original location or the quarantine destination named in the boot logs"}; any local session-database files that remain were left in place and nothing opened or wrote them.`;
|
|
2466
|
+
case "verification_timeout_before_separation":
|
|
2467
|
+
return "This runner did not come online because session database verification timed out after detecting corruption, before replica separation was attempted. No replica progress is claimed. See SESSION-DB-VERIFY-TIMEOUT in the runner boot logs before retrying.";
|
|
2468
|
+
case "verification_timeout_during_separation":
|
|
2469
|
+
return "This runner did not come online because session database verification timed out while replica separation was in progress. Separation completion and object removal were not proven. See SESSION-DB-VERIFY-TIMEOUT in the runner boot logs before retrying.";
|
|
2470
|
+
default:
|
|
2471
|
+
return "This runner did not come online because session database recovery could not be completed. Inspect the runner boot logs for the refusal reason before retrying.";
|
|
2472
|
+
}
|
|
2473
|
+
})();
|
|
2474
|
+
return { level, metadata: withoutContractFields(record), message };
|
|
2475
|
+
}
|
|
1968
2476
|
case "schema_provenance_mismatch":
|
|
1969
2477
|
return {
|
|
1970
2478
|
level,
|
|
@@ -2091,7 +2599,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
2091
2599
|
if (health.healthy || health.authFailed) {
|
|
2092
2600
|
return health;
|
|
2093
2601
|
}
|
|
2094
|
-
await new Promise((
|
|
2602
|
+
await new Promise((resolve5) => setTimeout(resolve5, 1e3));
|
|
2095
2603
|
}
|
|
2096
2604
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
2097
2605
|
}
|
|
@@ -2102,7 +2610,7 @@ async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
|
|
|
2102
2610
|
if (health.healthy || health.authFailed) {
|
|
2103
2611
|
return health;
|
|
2104
2612
|
}
|
|
2105
|
-
await new Promise((
|
|
2613
|
+
await new Promise((resolve5) => setTimeout(resolve5, 1e3));
|
|
2106
2614
|
}
|
|
2107
2615
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
2108
2616
|
}
|
|
@@ -2250,8 +2758,12 @@ function errorOf(m) {
|
|
|
2250
2758
|
if (!m || typeof m !== "object") return void 0;
|
|
2251
2759
|
return m.info?.error ?? m.error;
|
|
2252
2760
|
}
|
|
2761
|
+
function isTerminalStopAnswer(m) {
|
|
2762
|
+
return completedOf(m) != null && errorOf(m) == null && finishOf(m) === "stop";
|
|
2763
|
+
}
|
|
2253
2764
|
function isAssistantInFlight(m) {
|
|
2254
2765
|
if (completedOf(m) == null) return true;
|
|
2766
|
+
if (errorOf(m) != null) return false;
|
|
2255
2767
|
return finishOf(m) === "tool-calls";
|
|
2256
2768
|
}
|
|
2257
2769
|
async function getSessionMessages(port, sessionId, client) {
|
|
@@ -2365,7 +2877,18 @@ async function deleteSession(port, id, client) {
|
|
|
2365
2877
|
{ method: "DELETE" },
|
|
2366
2878
|
{ allowStatuses: ALL_HTTP_STATUSES }
|
|
2367
2879
|
);
|
|
2368
|
-
|
|
2880
|
+
if (res.status >= 200 && res.status < 300) {
|
|
2881
|
+
return { ok: true, status: res.status };
|
|
2882
|
+
}
|
|
2883
|
+
try {
|
|
2884
|
+
const body = await res.text();
|
|
2885
|
+
return body ? { ok: false, status: res.status, body } : { ok: false, status: res.status };
|
|
2886
|
+
} catch (error2) {
|
|
2887
|
+
console.error(
|
|
2888
|
+
`[deleteSession] DELETE /session/${id} response body read failed for HTTP ${res.status}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2889
|
+
);
|
|
2890
|
+
return { ok: false, status: res.status };
|
|
2891
|
+
}
|
|
2369
2892
|
} catch (error2) {
|
|
2370
2893
|
console.error(
|
|
2371
2894
|
`[deleteSession] DELETE /session/${id} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
@@ -2677,7 +3200,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments, c
|
|
|
2677
3200
|
return dispatchedUserMessageId;
|
|
2678
3201
|
}
|
|
2679
3202
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
2680
|
-
await new Promise((
|
|
3203
|
+
await new Promise((resolve5) => setTimeout(resolve5, READ_BACK_DELAY_MS));
|
|
2681
3204
|
}
|
|
2682
3205
|
}
|
|
2683
3206
|
return null;
|
|
@@ -2698,30 +3221,41 @@ function findAssistantReplyAfter(messages, userMessageId) {
|
|
|
2698
3221
|
function findLastAssistantReplyFor(messages, userMessageId) {
|
|
2699
3222
|
if (!messages || messages.length === 0) return null;
|
|
2700
3223
|
let lastCorrelated = null;
|
|
2701
|
-
let lastNonErrored = null;
|
|
2702
3224
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
2703
3225
|
const m = messages[i];
|
|
2704
3226
|
if (roleOf2(m) !== "assistant" || parentIdOf2(m) !== userMessageId) continue;
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
3227
|
+
lastCorrelated = m;
|
|
3228
|
+
break;
|
|
3229
|
+
}
|
|
3230
|
+
if (lastCorrelated) {
|
|
3231
|
+
if (errorOf(lastCorrelated) == null) return lastCorrelated;
|
|
3232
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
3233
|
+
const m = messages[i];
|
|
3234
|
+
if (roleOf2(m) === "assistant" && parentIdOf2(m) === userMessageId && isTerminalStopAnswer(m)) {
|
|
3235
|
+
return m;
|
|
3236
|
+
}
|
|
2709
3237
|
}
|
|
3238
|
+
return lastCorrelated;
|
|
2710
3239
|
}
|
|
2711
|
-
if (lastCorrelated) return lastNonErrored ?? lastCorrelated;
|
|
2712
3240
|
const userIndex = messages.findIndex((m) => idOf2(m) === userMessageId);
|
|
2713
3241
|
if (userIndex === -1) return null;
|
|
2714
3242
|
let last = null;
|
|
2715
|
-
let
|
|
3243
|
+
let lastAssistantIndex = -1;
|
|
2716
3244
|
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
2717
3245
|
const role = roleOf2(messages[i]);
|
|
2718
3246
|
if (role === "user") break;
|
|
2719
3247
|
if (role === "assistant") {
|
|
2720
3248
|
last = messages[i];
|
|
2721
|
-
|
|
3249
|
+
lastAssistantIndex = i;
|
|
2722
3250
|
}
|
|
2723
3251
|
}
|
|
2724
|
-
|
|
3252
|
+
if (last === null || errorOf(last) == null) return last;
|
|
3253
|
+
for (let i = lastAssistantIndex; i > userIndex; i--) {
|
|
3254
|
+
const m = messages[i];
|
|
3255
|
+
if (roleOf2(m) === "user") break;
|
|
3256
|
+
if (roleOf2(m) === "assistant" && isTerminalStopAnswer(m)) return m;
|
|
3257
|
+
}
|
|
3258
|
+
return last;
|
|
2725
3259
|
}
|
|
2726
3260
|
function collectSubagentSessions(messages, userMessageId) {
|
|
2727
3261
|
if (!messages || messages.length === 0) return [];
|
|
@@ -2827,8 +3361,9 @@ function attributeTaskCallUsage(messages, windows) {
|
|
|
2827
3361
|
}
|
|
2828
3362
|
function sumAssistantUsage(messages) {
|
|
2829
3363
|
if (!messages || messages.length === 0) return null;
|
|
2830
|
-
const
|
|
2831
|
-
const
|
|
3364
|
+
const hasTrailingError = errorOf(messages[messages.length - 1]) != null;
|
|
3365
|
+
const hasTerminalStopAnswer = messages.some(isTerminalStopAnswer);
|
|
3366
|
+
const selected = hasTrailingError && hasTerminalStopAnswer ? messages.filter((message) => errorOf(message) == null) : messages;
|
|
2832
3367
|
let sawAnyUsage = false;
|
|
2833
3368
|
let inputSum = 0;
|
|
2834
3369
|
let outputSum = 0;
|
|
@@ -2837,9 +3372,11 @@ function sumAssistantUsage(messages) {
|
|
|
2837
3372
|
let cacheWriteSum = 0;
|
|
2838
3373
|
let costSum = 0;
|
|
2839
3374
|
let sawCost = false;
|
|
3375
|
+
let toolCallCount = 0;
|
|
2840
3376
|
let modelId = null;
|
|
2841
3377
|
let providerId = null;
|
|
2842
3378
|
for (const m of selected) {
|
|
3379
|
+
toolCallCount += m.parts?.filter((part) => part.type === "tool").length ?? 0;
|
|
2843
3380
|
const info = m.info;
|
|
2844
3381
|
if (!info) continue;
|
|
2845
3382
|
const tokens = info.tokens;
|
|
@@ -2876,7 +3413,8 @@ function sumAssistantUsage(messages) {
|
|
|
2876
3413
|
usage_tokens_cache_write: cacheWriteSum,
|
|
2877
3414
|
// NULL means OpenCode never reported a cost; it is distinct from a genuine
|
|
2878
3415
|
// zero-cost message, which sets `sawCost` with `costSum === 0`.
|
|
2879
|
-
usage_cost_usd: sawCost ? costSum : null
|
|
3416
|
+
usage_cost_usd: sawCost ? costSum : null,
|
|
3417
|
+
turn_tool_calls: toolCallCount
|
|
2880
3418
|
};
|
|
2881
3419
|
}
|
|
2882
3420
|
function messageUsage(messages, userMessageId) {
|
|
@@ -2884,11 +3422,9 @@ function messageUsage(messages, userMessageId) {
|
|
|
2884
3422
|
const byParentAll = messages.filter(
|
|
2885
3423
|
(m) => roleOf2(m) === "assistant" && parentIdOf2(m) === userMessageId
|
|
2886
3424
|
);
|
|
2887
|
-
const byParentNonErrored = byParentAll.filter((m) => errorOf(m) == null);
|
|
2888
|
-
const byParent = byParentNonErrored.length > 0 ? byParentNonErrored : byParentAll;
|
|
2889
3425
|
let correlated;
|
|
2890
|
-
if (
|
|
2891
|
-
correlated =
|
|
3426
|
+
if (byParentAll.length > 0) {
|
|
3427
|
+
correlated = byParentAll;
|
|
2892
3428
|
} else {
|
|
2893
3429
|
const reply = findAssistantReplyAfter(messages, userMessageId);
|
|
2894
3430
|
correlated = reply ? [reply] : [];
|
|
@@ -2934,14 +3470,38 @@ function messageError(messages, userMessageId) {
|
|
|
2934
3470
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
2935
3471
|
const error2 = errorOf(reply);
|
|
2936
3472
|
if (error2 == null) return null;
|
|
2937
|
-
|
|
2938
|
-
if (typeof error2 === "
|
|
3473
|
+
let rendered;
|
|
3474
|
+
if (typeof error2 === "string") {
|
|
3475
|
+
rendered = error2;
|
|
3476
|
+
} else if (typeof error2 === "object") {
|
|
2939
3477
|
const e = error2;
|
|
2940
3478
|
const dataMessage = e.data?.message;
|
|
2941
|
-
if (typeof dataMessage === "string")
|
|
2942
|
-
|
|
3479
|
+
if (typeof dataMessage === "string") {
|
|
3480
|
+
rendered = dataMessage;
|
|
3481
|
+
} else if (typeof e.message === "string") {
|
|
3482
|
+
rendered = e.message;
|
|
3483
|
+
} else {
|
|
3484
|
+
rendered = "The agent run failed.";
|
|
3485
|
+
}
|
|
3486
|
+
} else {
|
|
3487
|
+
rendered = "The agent run failed.";
|
|
2943
3488
|
}
|
|
2944
|
-
|
|
3489
|
+
const toolPart = Array.isArray(reply?.parts) ? reply.parts.find(
|
|
3490
|
+
(part) => part && typeof part === "object" && part.type === "tool" && part.state?.status === "error"
|
|
3491
|
+
) : void 0;
|
|
3492
|
+
return typeof toolPart?.tool === "string" && toolPart.tool.length > 0 ? `${rendered} (tool "${toolPart.tool}")` : rendered;
|
|
3493
|
+
}
|
|
3494
|
+
function describeAbandonedReplyShape(messages, userMessageId) {
|
|
3495
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
3496
|
+
if (!reply) return null;
|
|
3497
|
+
const parts = Array.isArray(reply.parts) ? reply.parts : [];
|
|
3498
|
+
const lastTool = [...parts].reverse().find((part) => part?.type === "tool");
|
|
3499
|
+
return {
|
|
3500
|
+
partTypes: parts.slice(-12).map((part) => typeof part?.type === "string" ? part.type : "(unknown)"),
|
|
3501
|
+
droppedPartCount: Math.max(0, parts.length - 12),
|
|
3502
|
+
lastToolName: typeof lastTool?.tool === "string" && lastTool.tool.length > 0 ? lastTool.tool : null,
|
|
3503
|
+
lastToolStatus: typeof lastTool?.state?.status === "string" && lastTool.state.status.length > 0 ? lastTool.state.status : null
|
|
3504
|
+
};
|
|
2945
3505
|
}
|
|
2946
3506
|
function isAbortedTerminalReply(messages, userMessageId) {
|
|
2947
3507
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
@@ -2958,19 +3518,32 @@ function isAbortedTerminalReply(messages, userMessageId) {
|
|
|
2958
3518
|
}
|
|
2959
3519
|
return false;
|
|
2960
3520
|
}
|
|
3521
|
+
var CLAUDE_AUTH_EXPIRY_MESSAGES = Object.freeze([
|
|
3522
|
+
"Claude Code credentials are unavailable or expired. Run `claude` to refresh them."
|
|
3523
|
+
]);
|
|
3524
|
+
function extractReplyErrorShape(reply) {
|
|
3525
|
+
const error2 = errorOf(reply);
|
|
3526
|
+
if (error2 == null || typeof error2 !== "object") {
|
|
3527
|
+
return { name: null, statusCode: null };
|
|
3528
|
+
}
|
|
3529
|
+
const e = error2;
|
|
3530
|
+
const name = typeof e.name === "string" ? e.name.slice(0, 100) : null;
|
|
3531
|
+
const data = e.data;
|
|
3532
|
+
const statusCode = typeof data?.statusCode === "number" && Number.isFinite(data.statusCode) ? data.statusCode : null;
|
|
3533
|
+
return { name, statusCode };
|
|
3534
|
+
}
|
|
2961
3535
|
function classifyReplyAuthError(reply) {
|
|
2962
3536
|
const error2 = errorOf(reply);
|
|
2963
3537
|
if (error2 == null || typeof error2 !== "object") return null;
|
|
2964
3538
|
const e = error2;
|
|
2965
3539
|
const replyProviderId = reply?.info?.providerID ?? null;
|
|
2966
3540
|
const replyModelId = reply?.info?.modelID ?? null;
|
|
3541
|
+
const data = e.data;
|
|
2967
3542
|
if (e.name === "ProviderAuthError") {
|
|
2968
|
-
const data = e.data;
|
|
2969
3543
|
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
2970
3544
|
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
2971
3545
|
}
|
|
2972
3546
|
if (e.name === "APIError") {
|
|
2973
|
-
const data = e.data;
|
|
2974
3547
|
const statusCode = data?.statusCode;
|
|
2975
3548
|
if (statusCode === 401 || statusCode === 403) {
|
|
2976
3549
|
return {
|
|
@@ -2981,11 +3554,23 @@ function classifyReplyAuthError(reply) {
|
|
|
2981
3554
|
};
|
|
2982
3555
|
}
|
|
2983
3556
|
}
|
|
3557
|
+
const errorMessage3 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
|
|
3558
|
+
if (errorMessage3 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage3.includes(knownMessage))) {
|
|
3559
|
+
return {
|
|
3560
|
+
kind: "model_auth",
|
|
3561
|
+
providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
|
|
3562
|
+
modelId: replyModelId,
|
|
3563
|
+
reason: "rejected"
|
|
3564
|
+
};
|
|
3565
|
+
}
|
|
2984
3566
|
return null;
|
|
2985
3567
|
}
|
|
2986
3568
|
function messageFailure(messages, userMessageId) {
|
|
2987
3569
|
return classifyReplyAuthError(findLastAssistantReplyFor(messages, userMessageId));
|
|
2988
3570
|
}
|
|
3571
|
+
function isProviderModelNotFoundError(reason) {
|
|
3572
|
+
return reason.includes("Model not found:");
|
|
3573
|
+
}
|
|
2989
3574
|
function findLatestSubagentAuthOutcome(messages, sinceMs) {
|
|
2990
3575
|
if (!messages || messages.length === 0) return null;
|
|
2991
3576
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
@@ -3516,7 +4101,18 @@ async function deleteV2Session(client, sessionId) {
|
|
|
3516
4101
|
{ method: "DELETE" },
|
|
3517
4102
|
{ allowStatuses: Array.from({ length: 500 }, (_, index) => index + 100) }
|
|
3518
4103
|
);
|
|
3519
|
-
|
|
4104
|
+
if (response.status >= 200 && response.status < 300) {
|
|
4105
|
+
return { ok: true, status: response.status };
|
|
4106
|
+
}
|
|
4107
|
+
try {
|
|
4108
|
+
const body = await response.text();
|
|
4109
|
+
return body ? { ok: false, status: response.status, body } : { ok: false, status: response.status };
|
|
4110
|
+
} catch (error2) {
|
|
4111
|
+
console.error(
|
|
4112
|
+
`[deleteV2Session] DELETE /api/session/${sessionId} response body read failed for HTTP ${response.status}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4113
|
+
);
|
|
4114
|
+
return { ok: false, status: response.status };
|
|
4115
|
+
}
|
|
3520
4116
|
} catch (error2) {
|
|
3521
4117
|
console.error(
|
|
3522
4118
|
`[deleteV2Session] DELETE /api/session/${sessionId} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
@@ -3692,12 +4288,12 @@ async function readV2SessionErrorStream(client, options) {
|
|
|
3692
4288
|
|
|
3693
4289
|
// src/lib/opencode/credential-import-v2.ts
|
|
3694
4290
|
import { readFileSync as readFileSync4 } from "node:fs";
|
|
3695
|
-
import { join as
|
|
4291
|
+
import { join as join5 } from "node:path";
|
|
3696
4292
|
|
|
3697
4293
|
// src/lib/openai-usage.ts
|
|
3698
4294
|
import { readFileSync as readFileSync3 } from "node:fs";
|
|
3699
4295
|
import { homedir as homedir3 } from "node:os";
|
|
3700
|
-
import { join as
|
|
4296
|
+
import { join as join4 } from "node:path";
|
|
3701
4297
|
var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
3702
4298
|
var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
|
|
3703
4299
|
var OpenAiUsageError = class extends Error {
|
|
@@ -3711,7 +4307,7 @@ function isLocalCredentialProblem2(err) {
|
|
|
3711
4307
|
}
|
|
3712
4308
|
function readOpenCodeChatGptCredentials() {
|
|
3713
4309
|
try {
|
|
3714
|
-
const raw = readFileSync3(
|
|
4310
|
+
const raw = readFileSync3(join4(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
|
|
3715
4311
|
let parsed;
|
|
3716
4312
|
try {
|
|
3717
4313
|
parsed = JSON.parse(raw);
|
|
@@ -3937,13 +4533,13 @@ var INTEGRATION_LIST_RETRY_DELAY_MS = 1e3;
|
|
|
3937
4533
|
function isRecord3(value) {
|
|
3938
4534
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3939
4535
|
}
|
|
3940
|
-
var sleep2 = (milliseconds) => new Promise((
|
|
4536
|
+
var sleep2 = (milliseconds) => new Promise((resolve5) => setTimeout(resolve5, milliseconds));
|
|
3941
4537
|
function emptyResult(unsupported = [], outcome = "completed") {
|
|
3942
4538
|
return { outcome, imported: [], alreadyConnected: [], unsupported, failed: [] };
|
|
3943
4539
|
}
|
|
3944
4540
|
function readOpenCodeCredentials(homeDir, log3) {
|
|
3945
4541
|
try {
|
|
3946
|
-
const raw = readFileSync4(
|
|
4542
|
+
const raw = readFileSync4(join5(homeDir, ...OPENCODE_AUTH_SEGMENTS), "utf8");
|
|
3947
4543
|
let parsed;
|
|
3948
4544
|
try {
|
|
3949
4545
|
parsed = JSON.parse(raw);
|
|
@@ -4145,7 +4741,7 @@ async function importOpenCodeV2Credentials({
|
|
|
4145
4741
|
import { spawn as spawn2 } from "node:child_process";
|
|
4146
4742
|
import { mkdirSync, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync } from "node:fs";
|
|
4147
4743
|
import { homedir as homedir4 } from "node:os";
|
|
4148
|
-
import { dirname as
|
|
4744
|
+
import { dirname as dirname4, resolve as resolvePath } from "node:path";
|
|
4149
4745
|
|
|
4150
4746
|
// src/lib/runner-synchroniser.ts
|
|
4151
4747
|
import { spawn } from "node:child_process";
|
|
@@ -4155,7 +4751,7 @@ function appendError(stderr, error2) {
|
|
|
4155
4751
|
${message}`;
|
|
4156
4752
|
}
|
|
4157
4753
|
function runSynchroniser(args, opts) {
|
|
4158
|
-
return new Promise((
|
|
4754
|
+
return new Promise((resolve5) => {
|
|
4159
4755
|
let child;
|
|
4160
4756
|
let stdout = "";
|
|
4161
4757
|
let stderr = "";
|
|
@@ -4169,7 +4765,7 @@ function runSynchroniser(args, opts) {
|
|
|
4169
4765
|
if (timer.handle) clearTimeout(timer.handle);
|
|
4170
4766
|
if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
|
|
4171
4767
|
if (spawnListener) child.removeListener("spawn", spawnListener);
|
|
4172
|
-
|
|
4768
|
+
resolve5(result);
|
|
4173
4769
|
};
|
|
4174
4770
|
try {
|
|
4175
4771
|
child = spawn("runner-synchroniser", args, {
|
|
@@ -4225,9 +4821,12 @@ function runSynchroniser(args, opts) {
|
|
|
4225
4821
|
|
|
4226
4822
|
// src/lib/opencode/session-db-boot.ts
|
|
4227
4823
|
var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
|
|
4228
|
-
var SESSION_DB_VERIFY_TIMEOUT_MS =
|
|
4824
|
+
var SESSION_DB_VERIFY_TIMEOUT_MS = 36e4;
|
|
4229
4825
|
var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
|
|
4230
|
-
var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS =
|
|
4826
|
+
var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 40;
|
|
4827
|
+
var SESSION_DB_VERIFY_RESTORE_POINTS_TIMEOUT_SECONDS = 30;
|
|
4828
|
+
var SESSION_DB_VERIFY_RESTORE_CANDIDATE_TIMEOUT_SECONDS = 120;
|
|
4829
|
+
var SESSION_DB_VERIFY_DISPOSAL_BUDGET_SECONDS = 90;
|
|
4231
4830
|
function commandError(result) {
|
|
4232
4831
|
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
4233
4832
|
}
|
|
@@ -4270,7 +4869,7 @@ function clearMarker(options) {
|
|
|
4270
4869
|
function markNoReplicate(options, message) {
|
|
4271
4870
|
if (options.noReplicateMarker) {
|
|
4272
4871
|
try {
|
|
4273
|
-
mkdirSync(
|
|
4872
|
+
mkdirSync(dirname4(options.noReplicateMarker), { recursive: true });
|
|
4274
4873
|
writeFileSync(options.noReplicateMarker, "");
|
|
4275
4874
|
} catch (error2) {
|
|
4276
4875
|
options.log(
|
|
@@ -4329,7 +4928,7 @@ function parseSynchroniserEnv(stdout) {
|
|
|
4329
4928
|
return values;
|
|
4330
4929
|
}
|
|
4331
4930
|
function runCommand(command, args, options) {
|
|
4332
|
-
return new Promise((
|
|
4931
|
+
return new Promise((resolve5) => {
|
|
4333
4932
|
let child;
|
|
4334
4933
|
let stdout = "";
|
|
4335
4934
|
let stderr = "";
|
|
@@ -4338,7 +4937,7 @@ function runCommand(command, args, options) {
|
|
|
4338
4937
|
if (settled) return;
|
|
4339
4938
|
settled = true;
|
|
4340
4939
|
if (timer) clearTimeout(timer);
|
|
4341
|
-
|
|
4940
|
+
resolve5(result);
|
|
4342
4941
|
};
|
|
4343
4942
|
try {
|
|
4344
4943
|
child = spawn2(command, args, {
|
|
@@ -4346,7 +4945,7 @@ function runCommand(command, args, options) {
|
|
|
4346
4945
|
stdio: ["ignore", "pipe", "pipe"]
|
|
4347
4946
|
});
|
|
4348
4947
|
} catch (error2) {
|
|
4349
|
-
|
|
4948
|
+
resolve5({
|
|
4350
4949
|
code: null,
|
|
4351
4950
|
stdout,
|
|
4352
4951
|
stderr: error2 instanceof Error ? error2.message : String(error2),
|
|
@@ -4425,7 +5024,7 @@ async function ensureLitestreamConfig(options, env) {
|
|
|
4425
5024
|
return null;
|
|
4426
5025
|
}
|
|
4427
5026
|
try {
|
|
4428
|
-
mkdirSync(
|
|
5027
|
+
mkdirSync(dirname4(configPath), { recursive: true });
|
|
4429
5028
|
writeFileSync(configPath, rendered.stdout);
|
|
4430
5029
|
} catch (error2) {
|
|
4431
5030
|
options.log(
|
|
@@ -4538,20 +5137,37 @@ async function verifySessionDb(options, configPath, env) {
|
|
|
4538
5137
|
timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
|
|
4539
5138
|
env: {
|
|
4540
5139
|
...env,
|
|
4541
|
-
// The synchroniser reads
|
|
4542
|
-
// 120_000, so the walkback gives up before the outer process bound.
|
|
5140
|
+
// The synchroniser reads all four values in SECONDS.
|
|
4543
5141
|
EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
|
|
4544
5142
|
SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
|
|
5143
|
+
),
|
|
5144
|
+
EVIDENT_SESSION_DB_RESTORE_POINTS_TIMEOUT_SECONDS: String(
|
|
5145
|
+
SESSION_DB_VERIFY_RESTORE_POINTS_TIMEOUT_SECONDS
|
|
5146
|
+
),
|
|
5147
|
+
EVIDENT_SESSION_DB_RESTORE_CANDIDATE_TIMEOUT_SECONDS: String(
|
|
5148
|
+
SESSION_DB_VERIFY_RESTORE_CANDIDATE_TIMEOUT_SECONDS
|
|
5149
|
+
),
|
|
5150
|
+
EVIDENT_SESSION_DB_DISPOSAL_BUDGET_SECONDS: String(
|
|
5151
|
+
SESSION_DB_VERIFY_DISPOSAL_BUDGET_SECONDS
|
|
4545
5152
|
)
|
|
4546
5153
|
}
|
|
4547
5154
|
});
|
|
4548
5155
|
logSynchroniserDiagnostics(result, options);
|
|
4549
5156
|
if (result.timedOut || result.code === 124 || result.code === 137) {
|
|
5157
|
+
if (result.stderr.includes("SESSION-DB-INTEGRITY-FAILED")) {
|
|
5158
|
+
const reason = result.stderr.includes("SESSION-DB-REPLICA-SIZE") ? "verification_timeout_during_separation" : "verification_timeout_before_separation";
|
|
5159
|
+
options.log(
|
|
5160
|
+
`SESSION-DB-VERIFY-TIMEOUT: verification did not finish within its ${SESSION_DB_VERIFY_TIMEOUT_MS}ms deadline; refusing to start with the restored opencode.db (${reason})`,
|
|
5161
|
+
"error"
|
|
5162
|
+
);
|
|
5163
|
+
reportRecord("verify", "session_db_boot_refused", reason, null, options);
|
|
5164
|
+
return { verifyFatal: true, verifyFatalReason: reason };
|
|
5165
|
+
}
|
|
4550
5166
|
options.log(
|
|
4551
5167
|
`SESSION-DB-VERIFY-TIMEOUT: verification did not finish within its ${SESSION_DB_VERIFY_TIMEOUT_MS}ms deadline; continuing with the restored opencode.db as-is, unverified`,
|
|
4552
5168
|
"warn"
|
|
4553
5169
|
);
|
|
4554
|
-
return false;
|
|
5170
|
+
return { verifyFatal: false };
|
|
4555
5171
|
}
|
|
4556
5172
|
if (result.code === 34) {
|
|
4557
5173
|
reportRecord(
|
|
@@ -4561,14 +5177,14 @@ async function verifySessionDb(options, configPath, env) {
|
|
|
4561
5177
|
null,
|
|
4562
5178
|
options
|
|
4563
5179
|
);
|
|
4564
|
-
return true;
|
|
5180
|
+
return { verifyFatal: true };
|
|
4565
5181
|
}
|
|
4566
5182
|
if (result.code === 33) {
|
|
4567
5183
|
options.log(
|
|
4568
5184
|
"SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
|
|
4569
5185
|
"warn"
|
|
4570
5186
|
);
|
|
4571
|
-
return false;
|
|
5187
|
+
return { verifyFatal: false };
|
|
4572
5188
|
}
|
|
4573
5189
|
if (result.code !== 0) {
|
|
4574
5190
|
options.log(
|
|
@@ -4576,13 +5192,13 @@ async function verifySessionDb(options, configPath, env) {
|
|
|
4576
5192
|
"warn"
|
|
4577
5193
|
);
|
|
4578
5194
|
}
|
|
4579
|
-
return false;
|
|
5195
|
+
return { verifyFatal: false };
|
|
4580
5196
|
}
|
|
4581
5197
|
options.log(
|
|
4582
5198
|
"skipping session-DB verification: this boot's session DB was not proven safe to replicate",
|
|
4583
5199
|
"debug"
|
|
4584
5200
|
);
|
|
4585
|
-
return false;
|
|
5201
|
+
return { verifyFatal: false };
|
|
4586
5202
|
}
|
|
4587
5203
|
function fileExists(path) {
|
|
4588
5204
|
try {
|
|
@@ -4669,13 +5285,13 @@ async function restoreAndVerifySessionDb(options) {
|
|
|
4669
5285
|
if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
|
|
4670
5286
|
return { verifyFatal: false };
|
|
4671
5287
|
}
|
|
4672
|
-
return
|
|
5288
|
+
return verifySessionDb(options, configPath, env);
|
|
4673
5289
|
}
|
|
4674
5290
|
|
|
4675
5291
|
// src/lib/opencode/session-db-provenance.ts
|
|
4676
5292
|
import { createRequire } from "node:module";
|
|
4677
5293
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
|
|
4678
|
-
import { dirname as
|
|
5294
|
+
import { dirname as dirname5, join as join6 } from "node:path";
|
|
4679
5295
|
var require2 = createRequire(import.meta.url);
|
|
4680
5296
|
function readSessionDbMigrationIds(dbPath) {
|
|
4681
5297
|
let db;
|
|
@@ -4712,7 +5328,7 @@ function readSessionDbMigrationIds(dbPath) {
|
|
|
4712
5328
|
}
|
|
4713
5329
|
function sessionDbProvenanceStatePath(homeDir, env) {
|
|
4714
5330
|
const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
|
|
4715
|
-
return override ||
|
|
5331
|
+
return override || join6(homeDir, ".local", "state", "evident", "session-db-provenance.json");
|
|
4716
5332
|
}
|
|
4717
5333
|
function loadSessionDbProvenanceState(path) {
|
|
4718
5334
|
let value;
|
|
@@ -4741,7 +5357,7 @@ function loadSessionDbProvenanceState(path) {
|
|
|
4741
5357
|
}
|
|
4742
5358
|
function saveSessionDbProvenanceState(path, state) {
|
|
4743
5359
|
try {
|
|
4744
|
-
mkdirSync2(
|
|
5360
|
+
mkdirSync2(dirname5(path), { recursive: true });
|
|
4745
5361
|
writeFileSync2(path, `${JSON.stringify(state, null, 2)}
|
|
4746
5362
|
`, "utf8");
|
|
4747
5363
|
} catch (error2) {
|
|
@@ -4832,7 +5448,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
|
4832
5448
|
if (child.exitCode !== null || child.signalCode !== null) {
|
|
4833
5449
|
return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
|
|
4834
5450
|
}
|
|
4835
|
-
return new Promise((
|
|
5451
|
+
return new Promise((resolve5, reject) => {
|
|
4836
5452
|
let forced = false;
|
|
4837
5453
|
let settled = false;
|
|
4838
5454
|
const timer = setTimeout(() => {
|
|
@@ -4852,7 +5468,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
|
4852
5468
|
settled = true;
|
|
4853
5469
|
clearTimeout(timer);
|
|
4854
5470
|
child.removeListener("exit", onExit);
|
|
4855
|
-
|
|
5471
|
+
resolve5(result);
|
|
4856
5472
|
};
|
|
4857
5473
|
const fail = (error2) => {
|
|
4858
5474
|
if (settled) return;
|
|
@@ -5328,7 +5944,7 @@ function selectSessionsToDelete(sessions, opts) {
|
|
|
5328
5944
|
);
|
|
5329
5945
|
}
|
|
5330
5946
|
var DEFAULT_INTERVAL = "1h";
|
|
5331
|
-
function
|
|
5947
|
+
function resolve2(flag, envValue, fallback) {
|
|
5332
5948
|
return flag ?? envValue ?? fallback;
|
|
5333
5949
|
}
|
|
5334
5950
|
function parseMaxCount(input) {
|
|
@@ -5344,9 +5960,9 @@ function parseMaxCount(input) {
|
|
|
5344
5960
|
}
|
|
5345
5961
|
function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
5346
5962
|
const warnings = [];
|
|
5347
|
-
const maxAgeRaw =
|
|
5348
|
-
const maxCountRaw =
|
|
5349
|
-
const intervalRaw =
|
|
5963
|
+
const maxAgeRaw = resolve2(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
|
|
5964
|
+
const maxCountRaw = resolve2(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
|
|
5965
|
+
const intervalRaw = resolve2(
|
|
5350
5966
|
flags.interval,
|
|
5351
5967
|
env.EVIDENT_SESSION_CLEANUP_INTERVAL,
|
|
5352
5968
|
DEFAULT_INTERVAL
|
|
@@ -5386,10 +6002,10 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
|
5386
6002
|
|
|
5387
6003
|
// src/lib/opencode/session-db-size.ts
|
|
5388
6004
|
import { statSync as statSync4 } from "node:fs";
|
|
5389
|
-
import { join as
|
|
6005
|
+
import { join as join7 } from "node:path";
|
|
5390
6006
|
var LARGE_DB_THRESHOLD_BYTES = 268435456;
|
|
5391
6007
|
function statSessionDbBytes(homeDir) {
|
|
5392
|
-
const dbPath =
|
|
6008
|
+
const dbPath = join7(homeDir, ".local", "share", "opencode", "opencode.db");
|
|
5393
6009
|
try {
|
|
5394
6010
|
return statSync4(dbPath).size;
|
|
5395
6011
|
} catch (err) {
|
|
@@ -5419,12 +6035,12 @@ function buildSessionStoreSizeWarning(input) {
|
|
|
5419
6035
|
// src/lib/opencode/log-tail.ts
|
|
5420
6036
|
import { statSync as statSync5 } from "node:fs";
|
|
5421
6037
|
import { homedir as homedir5 } from "node:os";
|
|
5422
|
-
import { join as
|
|
6038
|
+
import { join as join8 } from "node:path";
|
|
5423
6039
|
import { open as open2, stat } from "node:fs/promises";
|
|
5424
6040
|
var DEFAULT_POLL_INTERVAL_MS = 1e3;
|
|
5425
6041
|
function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
|
|
5426
|
-
const dataDir = env.XDG_DATA_HOME ||
|
|
5427
|
-
return
|
|
6042
|
+
const dataDir = env.XDG_DATA_HOME || join8(homeDir, ".local", "share");
|
|
6043
|
+
return join8(dataDir, "opencode", "log", "opencode.log");
|
|
5428
6044
|
}
|
|
5429
6045
|
function isEnoent(error2) {
|
|
5430
6046
|
return error2?.code === "ENOENT";
|
|
@@ -5579,8 +6195,8 @@ var StreamForwarder = class {
|
|
|
5579
6195
|
pauseStream(sid, stream) {
|
|
5580
6196
|
if (!stream.paused) {
|
|
5581
6197
|
stream.paused = true;
|
|
5582
|
-
stream.pausePromise = new Promise((
|
|
5583
|
-
stream.resume =
|
|
6198
|
+
stream.pausePromise = new Promise((resolve5) => {
|
|
6199
|
+
stream.resume = resolve5;
|
|
5584
6200
|
});
|
|
5585
6201
|
}
|
|
5586
6202
|
if (stream.pauseTimer !== null) clearTimeout(stream.pauseTimer);
|
|
@@ -5647,12 +6263,12 @@ var StreamForwarder = class {
|
|
|
5647
6263
|
let endBody;
|
|
5648
6264
|
if (has_body) {
|
|
5649
6265
|
const chunks = [];
|
|
5650
|
-
bodyPromise = new Promise((
|
|
6266
|
+
bodyPromise = new Promise((resolve5) => {
|
|
5651
6267
|
pushBody = (buf) => {
|
|
5652
6268
|
chunks.push(buf);
|
|
5653
6269
|
};
|
|
5654
6270
|
endBody = () => {
|
|
5655
|
-
|
|
6271
|
+
resolve5(Buffer.concat(chunks));
|
|
5656
6272
|
};
|
|
5657
6273
|
});
|
|
5658
6274
|
}
|
|
@@ -5823,7 +6439,7 @@ function connectTunnel(options) {
|
|
|
5823
6439
|
} = options;
|
|
5824
6440
|
const tunnelUrl = getTunnelUrlConfig();
|
|
5825
6441
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
5826
|
-
return new Promise((
|
|
6442
|
+
return new Promise((resolve5, reject) => {
|
|
5827
6443
|
const ws = new WebSocket2(url, {
|
|
5828
6444
|
headers: {
|
|
5829
6445
|
Authorization: authHeader,
|
|
@@ -5932,7 +6548,7 @@ function connectTunnel(options) {
|
|
|
5932
6548
|
forwarder.setBinaryFramesSupported(message.binary_frames === true);
|
|
5933
6549
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
5934
6550
|
onConnected?.(connectedAgentId);
|
|
5935
|
-
|
|
6551
|
+
resolve5({
|
|
5936
6552
|
ws,
|
|
5937
6553
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
5938
6554
|
});
|
|
@@ -6450,6 +7066,7 @@ function createSessionStoreHealth(options = {}) {
|
|
|
6450
7066
|
const stalenessMs = Math.max(0, options.stalenessMs ?? SESSION_STORE_HEALTH_STALENESS_MS);
|
|
6451
7067
|
let lastUnwritableAt = null;
|
|
6452
7068
|
let lastWritableAt = null;
|
|
7069
|
+
const causes = /* @__PURE__ */ new Map();
|
|
6453
7070
|
return {
|
|
6454
7071
|
observeUnwritable: () => {
|
|
6455
7072
|
lastUnwritableAt = now();
|
|
@@ -6461,6 +7078,23 @@ function createSessionStoreHealth(options = {}) {
|
|
|
6461
7078
|
if (lastUnwritableAt === null) return false;
|
|
6462
7079
|
if (lastWritableAt !== null && lastWritableAt >= lastUnwritableAt) return false;
|
|
6463
7080
|
return now() - lastUnwritableAt < stalenessMs;
|
|
7081
|
+
},
|
|
7082
|
+
observeCause: (sessionId, cause) => {
|
|
7083
|
+
if (sessionId === null) return;
|
|
7084
|
+
causes.delete(sessionId);
|
|
7085
|
+
causes.set(sessionId, { cause, observedAt: now() });
|
|
7086
|
+
while (causes.size > 256) {
|
|
7087
|
+
const oldest = causes.keys().next().value;
|
|
7088
|
+
if (typeof oldest !== "string") break;
|
|
7089
|
+
causes.delete(oldest);
|
|
7090
|
+
}
|
|
7091
|
+
},
|
|
7092
|
+
readCause: (sessionId) => {
|
|
7093
|
+
const observed = causes.get(sessionId);
|
|
7094
|
+
if (!observed) return null;
|
|
7095
|
+
causes.delete(sessionId);
|
|
7096
|
+
if (now() - observed.observedAt >= stalenessMs) return null;
|
|
7097
|
+
return observed.cause;
|
|
6464
7098
|
}
|
|
6465
7099
|
};
|
|
6466
7100
|
}
|
|
@@ -6469,12 +7103,12 @@ function createSessionStoreHealth(options = {}) {
|
|
|
6469
7103
|
import { homedir as homedir6 } from "node:os";
|
|
6470
7104
|
|
|
6471
7105
|
// src/lib/runner-file-sync.ts
|
|
6472
|
-
import { join as
|
|
7106
|
+
import { join as join10 } from "node:path";
|
|
6473
7107
|
|
|
6474
7108
|
// src/lib/file-push.ts
|
|
6475
7109
|
import { randomUUID } from "node:crypto";
|
|
6476
7110
|
import { chmod, mkdir, open as open3, realpath, rename, unlink } from "node:fs/promises";
|
|
6477
|
-
import { basename, dirname as
|
|
7111
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute2, join as join9, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
|
|
6478
7112
|
var FILE_MODE = 384;
|
|
6479
7113
|
var DIRECTORY_MODE = 448;
|
|
6480
7114
|
async function writePushedFile(request2) {
|
|
@@ -6505,9 +7139,9 @@ async function writePushedFile(request2) {
|
|
|
6505
7139
|
}
|
|
6506
7140
|
try {
|
|
6507
7141
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
6508
|
-
|
|
7142
|
+
dirname6(candidate)
|
|
6509
7143
|
);
|
|
6510
|
-
const realTarget =
|
|
7144
|
+
const realTarget = join9(existingAncestor, ...missingSegments, basename2(candidate));
|
|
6511
7145
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
6512
7146
|
if (allowedDirectory === null) {
|
|
6513
7147
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -6517,8 +7151,8 @@ async function writePushedFile(request2) {
|
|
|
6517
7151
|
}
|
|
6518
7152
|
if (missingSegments.length > 0) {
|
|
6519
7153
|
await createMissingDirectories(existingAncestor, missingSegments);
|
|
6520
|
-
const realParent = await realpath(
|
|
6521
|
-
if (realParent !==
|
|
7154
|
+
const realParent = await realpath(dirname6(realTarget));
|
|
7155
|
+
if (realParent !== dirname6(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
6522
7156
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
6523
7157
|
path: realTarget,
|
|
6524
7158
|
bytes,
|
|
@@ -6543,15 +7177,15 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
6543
7177
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
6544
7178
|
return null;
|
|
6545
7179
|
}
|
|
6546
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
7180
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join9(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
6547
7181
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
6548
7182
|
return null;
|
|
6549
7183
|
}
|
|
6550
|
-
if (!
|
|
7184
|
+
if (!isAbsolute2(expanded)) {
|
|
6551
7185
|
return null;
|
|
6552
7186
|
}
|
|
6553
|
-
const candidate =
|
|
6554
|
-
const name =
|
|
7187
|
+
const candidate = resolve3(expanded);
|
|
7188
|
+
const name = basename2(candidate);
|
|
6555
7189
|
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
6556
7190
|
}
|
|
6557
7191
|
async function resolveNearestExistingAncestor(directory) {
|
|
@@ -6561,18 +7195,18 @@ async function resolveNearestExistingAncestor(directory) {
|
|
|
6561
7195
|
try {
|
|
6562
7196
|
return { existingAncestor: await realpath(current), missingSegments };
|
|
6563
7197
|
} catch (err) {
|
|
6564
|
-
const parent =
|
|
7198
|
+
const parent = dirname6(current);
|
|
6565
7199
|
if (err.code !== "ENOENT" || parent === current) {
|
|
6566
7200
|
throw err;
|
|
6567
7201
|
}
|
|
6568
|
-
missingSegments.unshift(
|
|
7202
|
+
missingSegments.unshift(basename2(current));
|
|
6569
7203
|
current = parent;
|
|
6570
7204
|
}
|
|
6571
7205
|
}
|
|
6572
7206
|
}
|
|
6573
7207
|
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
6574
7208
|
for (const directory of allowedDirectories) {
|
|
6575
|
-
if (!
|
|
7209
|
+
if (!isAbsolute2(directory)) {
|
|
6576
7210
|
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
6577
7211
|
continue;
|
|
6578
7212
|
}
|
|
@@ -6610,19 +7244,19 @@ async function realpathCreatingIfMissing(directory) {
|
|
|
6610
7244
|
}
|
|
6611
7245
|
}
|
|
6612
7246
|
function contains(realDirectory, realTarget) {
|
|
6613
|
-
const rel =
|
|
6614
|
-
return rel !== "" && rel !== ".." && !rel.startsWith(`..${
|
|
7247
|
+
const rel = relative2(realDirectory, realTarget);
|
|
7248
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
|
|
6615
7249
|
}
|
|
6616
7250
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
6617
7251
|
let current = existingAncestor;
|
|
6618
7252
|
for (const segment of missingSegments) {
|
|
6619
|
-
current =
|
|
7253
|
+
current = join9(current, segment);
|
|
6620
7254
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
6621
7255
|
await chmod(current, DIRECTORY_MODE);
|
|
6622
7256
|
}
|
|
6623
7257
|
}
|
|
6624
7258
|
async function writeAtomically(realTarget, content) {
|
|
6625
|
-
const temporaryPath =
|
|
7259
|
+
const temporaryPath = join9(dirname6(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
6626
7260
|
let handle;
|
|
6627
7261
|
try {
|
|
6628
7262
|
handle = await open3(temporaryPath, "wx", FILE_MODE);
|
|
@@ -6752,12 +7386,12 @@ var NOT_APPLIED = {
|
|
|
6752
7386
|
opencodeAuthApplied: false
|
|
6753
7387
|
};
|
|
6754
7388
|
function isClaudeCredentialPath(requestedPath, homeDir) {
|
|
6755
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
6756
|
-
return expanded ===
|
|
7389
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
7390
|
+
return expanded === join10(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
|
|
6757
7391
|
}
|
|
6758
7392
|
function isOpenCodeAuthPath(requestedPath, homeDir) {
|
|
6759
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
6760
|
-
return expanded ===
|
|
7393
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
7394
|
+
return expanded === join10(homeDir, ...OPENCODE_AUTH_SEGMENTS);
|
|
6761
7395
|
}
|
|
6762
7396
|
async function applyOne(options, file) {
|
|
6763
7397
|
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
@@ -6901,6 +7535,11 @@ function messageIdOf(m) {
|
|
|
6901
7535
|
const infoId = m.info?.id;
|
|
6902
7536
|
return typeof infoId === "string" ? infoId : void 0;
|
|
6903
7537
|
}
|
|
7538
|
+
function composeAbandonmentNote(finish, replyShape, outcome) {
|
|
7539
|
+
const base = `OpenCode ended this turn after a tool call (finish="${finish ?? "(unknown)"}") ` + (outcome === "without-answer" ? "without writing an answer, and confirmed it is no longer working on this conversation. Evident is reporting the run as failed so the failure and its reason are visible in failed runs." : "after writing only part of an answer, and confirmed it is no longer working on this conversation. Evident delivered what was written and is reporting the run as finished.");
|
|
7540
|
+
if (replyShape === null) return base;
|
|
7541
|
+
return `${base} ${replyShape.lastToolName === null ? "No tool call was recorded" : `The last tool call was "${replyShape.lastToolName}" with status "${replyShape.lastToolStatus ?? "(unknown)"}"`}; the reply's final part types were [${replyShape.partTypes.join(", ")}]${replyShape.droppedPartCount > 0 ? ` (${replyShape.droppedPartCount} earlier part types omitted)` : ""}.`;
|
|
7542
|
+
}
|
|
6904
7543
|
function cleanImageMime(contentType) {
|
|
6905
7544
|
if (!contentType) return null;
|
|
6906
7545
|
const media = contentType.split(";")[0].trim().toLowerCase();
|
|
@@ -6921,6 +7560,10 @@ var SUBAGENT_TELEMETRY_FETCH_TIMEOUT_MS = 2e3;
|
|
|
6921
7560
|
var SESSION_ERROR_STREAM_HEALTHY_MS = 5e3;
|
|
6922
7561
|
var SESSION_ERROR_BUFFER_TTL_MS = SESSION_ERROR_STREAM_HEALTHY_MS;
|
|
6923
7562
|
var MAX_BUFFERED_SESSION_ERRORS = 256;
|
|
7563
|
+
var SESSION_ERROR_RETENTION_TTL_MS = 6e4;
|
|
7564
|
+
var SESSION_STORE_UNWRITABLE_ERROR = "The runner session database could not be written, so this turn did not finish. Nothing was lost from the queue. Clear disk space and retry.";
|
|
7565
|
+
var SESSION_ERROR_RETAINED_DETAIL = "Runner-observed OpenCode session error: ";
|
|
7566
|
+
var SESSION_ERROR_OBSERVED_CAUSE = "Runner-observed OpenCode session-store cause: ";
|
|
6924
7567
|
var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
|
|
6925
7568
|
var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
6926
7569
|
var DRIVER_SESSION_ENUMERATION_LIMIT = 20;
|
|
@@ -7078,6 +7721,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
7078
7721
|
* with a short TTL so an unmatched session cannot retain an event indefinitely.
|
|
7079
7722
|
*/
|
|
7080
7723
|
bufferedSessionErrors = /* @__PURE__ */ new Map();
|
|
7724
|
+
retainedSessionErrors = /* @__PURE__ */ new Map();
|
|
7081
7725
|
/**
|
|
7082
7726
|
* AUTHORITATIVE local dedup (WI-3): Evident message ids that have been
|
|
7083
7727
|
* dispatched and are still in-flight. A message in this set is never
|
|
@@ -8918,6 +9562,28 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
8918
9562
|
this.bufferedSessionErrors.delete(oldest);
|
|
8919
9563
|
}
|
|
8920
9564
|
}
|
|
9565
|
+
retainSessionError(event) {
|
|
9566
|
+
this.retainedSessionErrors.delete(event.sessionId);
|
|
9567
|
+
this.retainedSessionErrors.set(event.sessionId, {
|
|
9568
|
+
reason: event.reason,
|
|
9569
|
+
observedAt: this.now()
|
|
9570
|
+
});
|
|
9571
|
+
while (this.retainedSessionErrors.size > MAX_BUFFERED_SESSION_ERRORS) {
|
|
9572
|
+
const oldest = this.retainedSessionErrors.keys().next().value;
|
|
9573
|
+
if (typeof oldest !== "string") break;
|
|
9574
|
+
this.retainedSessionErrors.delete(oldest);
|
|
9575
|
+
}
|
|
9576
|
+
}
|
|
9577
|
+
readRetainedSessionError(sessionId) {
|
|
9578
|
+
const retained = this.retainedSessionErrors.get(sessionId);
|
|
9579
|
+
if (!retained) return null;
|
|
9580
|
+
if (this.now() - retained.observedAt >= SESSION_ERROR_RETENTION_TTL_MS) {
|
|
9581
|
+
this.retainedSessionErrors.delete(sessionId);
|
|
9582
|
+
return null;
|
|
9583
|
+
}
|
|
9584
|
+
this.retainedSessionErrors.delete(sessionId);
|
|
9585
|
+
return retained.reason;
|
|
9586
|
+
}
|
|
8921
9587
|
/**
|
|
8922
9588
|
* Build a fresh `SessionWatcher`. Seeds `lastTickAt`/`lastObservedTickAt`
|
|
8923
9589
|
* EQUAL (#1618) so a watcher whose loop has not started ticking yet is never
|
|
@@ -9244,9 +9910,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9244
9910
|
return;
|
|
9245
9911
|
}
|
|
9246
9912
|
if ([...watcher.inFlight.values()].some((message) => message.started && !message.done)) {
|
|
9913
|
+
this.retainSessionError(event);
|
|
9247
9914
|
this.log({
|
|
9248
|
-
level: "
|
|
9249
|
-
message: `A turn is already running in session ${event.sessionId.slice(0, 8)} \u2014 deferring to transcript polling`,
|
|
9915
|
+
level: "warn",
|
|
9916
|
+
message: `A turn is already running in session ${event.sessionId.slice(0, 8)} \u2014 retaining the session error and deferring to transcript polling: ${event.reason}`,
|
|
9250
9917
|
conversation_id: watcher.conv.id
|
|
9251
9918
|
});
|
|
9252
9919
|
return;
|
|
@@ -9276,9 +9943,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9276
9943
|
const messages = await this.getSessionMessages(event.sessionId);
|
|
9277
9944
|
const state = messageRunState(messages, inFlight.opencodeMessageId);
|
|
9278
9945
|
if (state !== "queued") {
|
|
9946
|
+
this.retainSessionError(event);
|
|
9279
9947
|
this.log({
|
|
9280
|
-
level: "
|
|
9281
|
-
message: `Session error for message ${inFlight.evidentMessageId.slice(0, 8)} observed state ${state};
|
|
9948
|
+
level: "warn",
|
|
9949
|
+
message: `Session error for message ${inFlight.evidentMessageId.slice(0, 8)} in session ${event.sessionId.slice(0, 8)} observed state ${state}; retaining the reason for transcript polling: ${event.reason}`,
|
|
9282
9950
|
conversation_id: watcher.conv.id,
|
|
9283
9951
|
message_id: inFlight.evidentMessageId
|
|
9284
9952
|
});
|
|
@@ -9290,14 +9958,53 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9290
9958
|
conversation_id: watcher.conv.id,
|
|
9291
9959
|
message_id: inFlight.evidentMessageId
|
|
9292
9960
|
});
|
|
9293
|
-
|
|
9294
|
-
|
|
9295
|
-
inFlight.
|
|
9296
|
-
|
|
9297
|
-
|
|
9298
|
-
|
|
9961
|
+
const isMissingProvider = isProviderModelNotFoundError(event.reason);
|
|
9962
|
+
if (isMissingProvider) {
|
|
9963
|
+
const dispatchedModel = inFlight.message.opencode_model;
|
|
9964
|
+
const separator = dispatchedModel?.indexOf("/") ?? -1;
|
|
9965
|
+
const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
|
|
9966
|
+
await this.markFailed(
|
|
9967
|
+
watcher.conv.id,
|
|
9968
|
+
inFlight.evidentMessageId,
|
|
9969
|
+
event.sessionId,
|
|
9970
|
+
`OpenCode could not run this turn: ${event.reason}`,
|
|
9971
|
+
void 0,
|
|
9972
|
+
{
|
|
9973
|
+
classification: {
|
|
9974
|
+
kind: "model_auth",
|
|
9975
|
+
providerId: hasProviderAndModel ? dispatchedModel.slice(0, separator) : null,
|
|
9976
|
+
modelId: hasProviderAndModel ? dispatchedModel.slice(separator + 1) : null,
|
|
9977
|
+
reason: "missing"
|
|
9978
|
+
},
|
|
9979
|
+
errorShape: { name: null, statusCode: null }
|
|
9980
|
+
}
|
|
9981
|
+
);
|
|
9982
|
+
} else {
|
|
9983
|
+
await this.markFailed(
|
|
9984
|
+
watcher.conv.id,
|
|
9985
|
+
inFlight.evidentMessageId,
|
|
9986
|
+
event.sessionId,
|
|
9987
|
+
`OpenCode could not run this turn: ${event.reason}`
|
|
9988
|
+
);
|
|
9989
|
+
}
|
|
9299
9990
|
inFlight.done = true;
|
|
9300
9991
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
9992
|
+
if (isMissingProvider) {
|
|
9993
|
+
if (this.isV2) {
|
|
9994
|
+
void this.postSignal(
|
|
9995
|
+
watcher.conv.id,
|
|
9996
|
+
inFlight.evidentMessageId,
|
|
9997
|
+
"provider_registry_reload_unsupported"
|
|
9998
|
+
);
|
|
9999
|
+
} else {
|
|
10000
|
+
await reloadProviderCache(this.port, this.openCodeClient);
|
|
10001
|
+
void this.postSignal(
|
|
10002
|
+
watcher.conv.id,
|
|
10003
|
+
inFlight.evidentMessageId,
|
|
10004
|
+
"provider_registry_reload_issued"
|
|
10005
|
+
);
|
|
10006
|
+
}
|
|
10007
|
+
}
|
|
9301
10008
|
} catch (err) {
|
|
9302
10009
|
if (err instanceof ChannelAuthError) {
|
|
9303
10010
|
this.log({
|
|
@@ -9507,7 +10214,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9507
10214
|
if (state === "failed") {
|
|
9508
10215
|
this.anchorDeliveryDeadline(inFlight);
|
|
9509
10216
|
if (!inFlight.done) {
|
|
9510
|
-
const
|
|
10217
|
+
const messageErrorText = messageError(messages, inFlight.opencodeMessageId);
|
|
10218
|
+
const retainedReason = this.readRetainedSessionError(sessionId);
|
|
10219
|
+
const retainedError = retainedReason === null || messageErrorText !== null && messageErrorText.includes(retainedReason) ? null : `${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}`;
|
|
10220
|
+
const observedCause = this.sessionStoreHealth?.readCause(sessionId);
|
|
10221
|
+
const causeError = observedCause === null || observedCause === void 0 ? null : `${SESSION_ERROR_OBSERVED_CAUSE}${observedCause}`;
|
|
10222
|
+
const storeError = this.sessionStoreHealth?.isUnwritable() ? SESSION_STORE_UNWRITABLE_ERROR : null;
|
|
10223
|
+
const runnerDetails = [retainedError, causeError, storeError].filter(
|
|
10224
|
+
(detail) => detail !== null
|
|
10225
|
+
);
|
|
10226
|
+
const error2 = messageErrorText === null ? runnerDetails.length === 0 ? void 0 : runnerDetails.join(" ") : [messageErrorText, ...runnerDetails].join(" ");
|
|
9511
10227
|
this.log({
|
|
9512
10228
|
level: "error",
|
|
9513
10229
|
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} errored \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -9597,17 +10313,28 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9597
10313
|
}
|
|
9598
10314
|
} else {
|
|
9599
10315
|
if (inFlight.b2AbandonedSignalled) {
|
|
10316
|
+
const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
|
|
10317
|
+
const finish = reply?.info?.finish ?? reply?.finish;
|
|
9600
10318
|
if (inFlight.b2AbandonedWithoutAnswer) {
|
|
9601
|
-
const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
|
|
9602
10319
|
await this.settleMessageAbandonedWithoutAnswer(
|
|
9603
10320
|
sessionId,
|
|
9604
10321
|
watcher,
|
|
9605
10322
|
inFlight,
|
|
9606
10323
|
messages,
|
|
9607
|
-
|
|
10324
|
+
finish
|
|
9608
10325
|
);
|
|
9609
10326
|
} else {
|
|
9610
|
-
await this.settleMessageDone(
|
|
10327
|
+
await this.settleMessageDone(
|
|
10328
|
+
sessionId,
|
|
10329
|
+
watcher,
|
|
10330
|
+
inFlight,
|
|
10331
|
+
messages,
|
|
10332
|
+
composeAbandonmentNote(
|
|
10333
|
+
finish,
|
|
10334
|
+
describeAbandonedReplyShape(messages, inFlight.opencodeMessageId),
|
|
10335
|
+
"with-answer"
|
|
10336
|
+
)
|
|
10337
|
+
);
|
|
9611
10338
|
}
|
|
9612
10339
|
return;
|
|
9613
10340
|
}
|
|
@@ -9670,7 +10397,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9670
10397
|
...descendantOngoing != null ? { descendant_ongoing: descendantOngoing } : {},
|
|
9671
10398
|
opencode_message_id: inFlight.opencodeMessageId
|
|
9672
10399
|
});
|
|
9673
|
-
await this.settleMessageDone(
|
|
10400
|
+
await this.settleMessageDone(
|
|
10401
|
+
sessionId,
|
|
10402
|
+
watcher,
|
|
10403
|
+
inFlight,
|
|
10404
|
+
messages,
|
|
10405
|
+
composeAbandonmentNote(
|
|
10406
|
+
finish,
|
|
10407
|
+
describeAbandonedReplyShape(messages, inFlight.opencodeMessageId),
|
|
10408
|
+
"with-answer"
|
|
10409
|
+
)
|
|
10410
|
+
);
|
|
9674
10411
|
return;
|
|
9675
10412
|
}
|
|
9676
10413
|
if (rootOngoing === true && !inFlight.b2RootOngoingHeldLogged) {
|
|
@@ -9870,15 +10607,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9870
10607
|
}
|
|
9871
10608
|
}
|
|
9872
10609
|
/**
|
|
9873
|
-
* Settle a message whose run-state has resolved `'done'
|
|
9874
|
-
*
|
|
9875
|
-
*
|
|
9876
|
-
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
9877
|
-
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
9878
|
-
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
9879
|
-
* and risking the two copies silently drifting apart.
|
|
10610
|
+
* Settle a message whose run-state has resolved `'done'`. Normal completion and
|
|
10611
|
+
* confirmed b2 abandonment share the same delivery, usage, and terminal handling.
|
|
10612
|
+
* Normal completions omit the optional terminal diagnostic.
|
|
9880
10613
|
*/
|
|
9881
|
-
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
10614
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages, note) {
|
|
9882
10615
|
const conv = watcher.conv;
|
|
9883
10616
|
this.anchorDeliveryDeadline(inFlight);
|
|
9884
10617
|
if (!inFlight.done) {
|
|
@@ -9905,7 +10638,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9905
10638
|
title,
|
|
9906
10639
|
usage,
|
|
9907
10640
|
usageAgentName,
|
|
9908
|
-
subagentInvocations
|
|
10641
|
+
subagentInvocations,
|
|
10642
|
+
note
|
|
9909
10643
|
);
|
|
9910
10644
|
} catch (err) {
|
|
9911
10645
|
if (err instanceof ChannelAuthError) throw err;
|
|
@@ -9950,7 +10684,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9950
10684
|
/** Report a confirmed b2 abandonment that produced no answer text. */
|
|
9951
10685
|
async settleMessageAbandonedWithoutAnswer(sessionId, watcher, inFlight, messages, finish) {
|
|
9952
10686
|
const conv = watcher.conv;
|
|
9953
|
-
const error2 =
|
|
10687
|
+
const error2 = composeAbandonmentNote(
|
|
10688
|
+
finish,
|
|
10689
|
+
describeAbandonedReplyShape(messages, inFlight.opencodeMessageId),
|
|
10690
|
+
"without-answer"
|
|
10691
|
+
);
|
|
9954
10692
|
this.anchorDeliveryDeadline(inFlight);
|
|
9955
10693
|
this.log({
|
|
9956
10694
|
level: "warn",
|
|
@@ -10077,7 +10815,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
10077
10815
|
*/
|
|
10078
10816
|
async settleMessageSessionStoreUnwritable(sessionId, watcher, inFlight) {
|
|
10079
10817
|
const conv = watcher.conv;
|
|
10080
|
-
const error2 =
|
|
10818
|
+
const error2 = SESSION_STORE_UNWRITABLE_ERROR;
|
|
10081
10819
|
this.log({
|
|
10082
10820
|
level: "error",
|
|
10083
10821
|
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} was not resolved as done: ${error2}`,
|
|
@@ -11187,14 +11925,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
11187
11925
|
const fetchChildWithoutBlocking = async (sessionId) => {
|
|
11188
11926
|
const pending = fetchChildMessages(sessionId);
|
|
11189
11927
|
let timer;
|
|
11190
|
-
const timeout = new Promise((
|
|
11928
|
+
const timeout = new Promise((resolve5) => {
|
|
11191
11929
|
timer = setTimeout(() => {
|
|
11192
11930
|
this.log({
|
|
11193
11931
|
level: "warn",
|
|
11194
11932
|
message: `Best-effort subagent session fetch for message ${messageId.slice(0, 8)} and child session ${sessionId.slice(0, 8)} was slow \u2014 omitting invocation telemetry without delaying completion`,
|
|
11195
11933
|
message_id: messageId
|
|
11196
11934
|
});
|
|
11197
|
-
|
|
11935
|
+
resolve5(null);
|
|
11198
11936
|
}, SUBAGENT_TELEMETRY_FETCH_TIMEOUT_MS);
|
|
11199
11937
|
});
|
|
11200
11938
|
try {
|
|
@@ -11754,7 +12492,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
11754
12492
|
* watcher retries next tick within the
|
|
11755
12493
|
* deadline, Finding 4).
|
|
11756
12494
|
*/
|
|
11757
|
-
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage, usageAgentName, subagentInvocations) {
|
|
12495
|
+
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage, usageAgentName, subagentInvocations, error2) {
|
|
11758
12496
|
const res = await this.fetchImpl(
|
|
11759
12497
|
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
11760
12498
|
{
|
|
@@ -11772,7 +12510,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
11772
12510
|
...title ? { title } : {},
|
|
11773
12511
|
...usage ? usage : {},
|
|
11774
12512
|
...usageAgentName ? { usage_agent_name: usageAgentName } : {},
|
|
11775
|
-
...subagentInvocations && subagentInvocations.length > 0 ? { subagent_invocations: subagentInvocations } : {}
|
|
12513
|
+
...subagentInvocations && subagentInvocations.length > 0 ? { subagent_invocations: subagentInvocations } : {},
|
|
12514
|
+
...error2 ? { error: error2 } : {}
|
|
11776
12515
|
})
|
|
11777
12516
|
}
|
|
11778
12517
|
);
|
|
@@ -11832,11 +12571,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
11832
12571
|
if (subagentInvocations && subagentInvocations.length > 0) {
|
|
11833
12572
|
body.subagent_invocations = subagentInvocations;
|
|
11834
12573
|
}
|
|
11835
|
-
if (failure) {
|
|
11836
|
-
body.
|
|
11837
|
-
|
|
11838
|
-
|
|
11839
|
-
body.
|
|
12574
|
+
if (failure && failure.errorShape.name !== null) {
|
|
12575
|
+
body.failure_error_name = failure.errorShape.name;
|
|
12576
|
+
}
|
|
12577
|
+
if (failure && failure.errorShape.statusCode !== null) {
|
|
12578
|
+
body.failure_status_code = failure.errorShape.statusCode;
|
|
12579
|
+
}
|
|
12580
|
+
if (failure?.classification) {
|
|
12581
|
+
body.failure_kind = failure.classification.kind;
|
|
12582
|
+
body.failure_provider_id = failure.classification.providerId;
|
|
12583
|
+
body.failure_model_id = failure.classification.modelId;
|
|
12584
|
+
body.failure_reason = failure.classification.reason;
|
|
11840
12585
|
}
|
|
11841
12586
|
try {
|
|
11842
12587
|
await this.callWithRetry(
|
|
@@ -11857,27 +12602,28 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
11857
12602
|
this.clearSubagentInvocationCaches(messageId);
|
|
11858
12603
|
}
|
|
11859
12604
|
/**
|
|
11860
|
-
* Classify an errored turn
|
|
12605
|
+
* Classify an errored turn and extract its bounded error shape for `markFailed`.
|
|
11861
12606
|
*
|
|
11862
12607
|
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
11863
12608
|
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
11864
12609
|
* to the P1-2b zero-provider check — one extra loopback call to
|
|
11865
12610
|
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
11866
12611
|
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
11867
|
-
* (`null`/indeterminate) leaves the classification `null
|
|
11868
|
-
*
|
|
12612
|
+
* (`null`/indeterminate) leaves the classification `null`; the raw error shape
|
|
12613
|
+
* is still retained for diagnostics.
|
|
11869
12614
|
*/
|
|
11870
12615
|
async classifyModelAuthFailure(messages, userMessageId) {
|
|
11871
|
-
const classified = messageFailure(messages, userMessageId);
|
|
11872
|
-
if (classified != null) return classified;
|
|
11873
12616
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
11874
|
-
const
|
|
11875
|
-
|
|
12617
|
+
const errorShape = extractReplyErrorShape(reply);
|
|
12618
|
+
const classified = messageFailure(messages, userMessageId);
|
|
12619
|
+
if (classified != null) return { classification: classified, errorShape };
|
|
12620
|
+
const classification = applyZeroProviderFallback(
|
|
11876
12621
|
classified,
|
|
11877
|
-
|
|
12622
|
+
await this.hasAnyConfiguredProvider(),
|
|
11878
12623
|
reply?.info?.providerID ?? null,
|
|
11879
12624
|
reply?.info?.modelID ?? null
|
|
11880
12625
|
);
|
|
12626
|
+
return { classification, errorShape };
|
|
11881
12627
|
}
|
|
11882
12628
|
async recordSubagentModelAuthFailure(failure, conversationId, messageId) {
|
|
11883
12629
|
const providerId = failure.providerId ?? "(unknown)";
|
|
@@ -12435,7 +13181,7 @@ function commandError2(result) {
|
|
|
12435
13181
|
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
12436
13182
|
}
|
|
12437
13183
|
var runCommand2 = (command, args, opts) => {
|
|
12438
|
-
return new Promise((
|
|
13184
|
+
return new Promise((resolve5) => {
|
|
12439
13185
|
let child;
|
|
12440
13186
|
let stdout = "";
|
|
12441
13187
|
let stderr = "";
|
|
@@ -12445,7 +13191,7 @@ var runCommand2 = (command, args, opts) => {
|
|
|
12445
13191
|
if (settled) return;
|
|
12446
13192
|
settled = true;
|
|
12447
13193
|
if (timer.handle) clearTimeout(timer.handle);
|
|
12448
|
-
|
|
13194
|
+
resolve5(result);
|
|
12449
13195
|
};
|
|
12450
13196
|
try {
|
|
12451
13197
|
child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -12500,7 +13246,9 @@ async function installRunnerSecret({
|
|
|
12500
13246
|
}) {
|
|
12501
13247
|
const arn = env.RUNNER_SECRET_ARN?.trim();
|
|
12502
13248
|
if (!arn) {
|
|
12503
|
-
|
|
13249
|
+
if (!env.GH_TOKEN) {
|
|
13250
|
+
log3("runner secret is not configured; continuing without GitHub and MCP credentials");
|
|
13251
|
+
}
|
|
12504
13252
|
return false;
|
|
12505
13253
|
}
|
|
12506
13254
|
const result = await (commandRunner ?? runCommand2)(
|
|
@@ -12699,7 +13447,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
|
|
|
12699
13447
|
// src/lib/opencode/config-overlay.ts
|
|
12700
13448
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
12701
13449
|
import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
|
|
12702
|
-
import { isAbsolute as
|
|
13450
|
+
import { isAbsolute as isAbsolute3, join as join11, resolve as resolve4 } from "node:path";
|
|
12703
13451
|
function isFile(filePath) {
|
|
12704
13452
|
return existsSync2(filePath) && statSync6(filePath).isFile();
|
|
12705
13453
|
}
|
|
@@ -12712,8 +13460,8 @@ function applyRunnerOpenCodeConfig({
|
|
|
12712
13460
|
log3("runner OpenCode config is not configured; using the baked project config", "debug");
|
|
12713
13461
|
return;
|
|
12714
13462
|
}
|
|
12715
|
-
const source =
|
|
12716
|
-
const target = isFile(
|
|
13463
|
+
const source = isAbsolute3(overlayPath) ? overlayPath : resolve4(cwd, overlayPath);
|
|
13464
|
+
const target = isFile(join11(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
|
|
12717
13465
|
if (!isFile(source)) {
|
|
12718
13466
|
log3(
|
|
12719
13467
|
`RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
|
|
@@ -12721,7 +13469,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
12721
13469
|
);
|
|
12722
13470
|
return;
|
|
12723
13471
|
}
|
|
12724
|
-
copyFileSync(source,
|
|
13472
|
+
copyFileSync(source, join11(cwd, target));
|
|
12725
13473
|
try {
|
|
12726
13474
|
execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
|
|
12727
13475
|
stdio: "ignore"
|
|
@@ -12730,7 +13478,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
12730
13478
|
const detail = error2 instanceof Error ? error2.message : String(error2);
|
|
12731
13479
|
log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
|
|
12732
13480
|
}
|
|
12733
|
-
log3(`Applied runner OpenCode config ${source} to ${
|
|
13481
|
+
log3(`Applied runner OpenCode config ${source} to ${join11(cwd, target)}`);
|
|
12734
13482
|
}
|
|
12735
13483
|
|
|
12736
13484
|
// src/lib/credential-sync.ts
|
|
@@ -12748,14 +13496,14 @@ function errorMessage2(error2) {
|
|
|
12748
13496
|
return error2 instanceof Error ? error2.message : String(error2);
|
|
12749
13497
|
}
|
|
12750
13498
|
function waitForSettlement(promise, timeoutMs) {
|
|
12751
|
-
return new Promise((
|
|
13499
|
+
return new Promise((resolve5) => {
|
|
12752
13500
|
let settled = false;
|
|
12753
13501
|
const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
|
|
12754
13502
|
const finish = (value) => {
|
|
12755
13503
|
if (settled) return;
|
|
12756
13504
|
settled = true;
|
|
12757
13505
|
clearTimeout(timer);
|
|
12758
|
-
|
|
13506
|
+
resolve5(value);
|
|
12759
13507
|
};
|
|
12760
13508
|
promise.then(
|
|
12761
13509
|
() => finish(true),
|
|
@@ -13006,8 +13754,8 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
13006
13754
|
if (trimmed === "") {
|
|
13007
13755
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
13008
13756
|
}
|
|
13009
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
13010
|
-
if (!
|
|
13757
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join12(homeDir, trimmed.slice(2)) : trimmed;
|
|
13758
|
+
if (!isAbsolute4(expanded)) {
|
|
13011
13759
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
13012
13760
|
}
|
|
13013
13761
|
const normalized = resolvePath2(expanded);
|
|
@@ -13107,8 +13855,7 @@ function resolveMaxActiveSessions(options, env = process.env) {
|
|
|
13107
13855
|
function meetsThreshold(state, level) {
|
|
13108
13856
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
13109
13857
|
}
|
|
13110
|
-
function
|
|
13111
|
-
if (!meetsThreshold(state, level)) return;
|
|
13858
|
+
function writeConsoleLog(state, message, level) {
|
|
13112
13859
|
if (state.json) {
|
|
13113
13860
|
console.log(
|
|
13114
13861
|
JSON.stringify({
|
|
@@ -13117,10 +13864,18 @@ function log2(state, message, level = "info") {
|
|
|
13117
13864
|
message
|
|
13118
13865
|
})
|
|
13119
13866
|
);
|
|
13120
|
-
|
|
13121
|
-
const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
|
|
13122
|
-
console.log(`${prefix} ${message}`);
|
|
13867
|
+
return;
|
|
13123
13868
|
}
|
|
13869
|
+
const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
|
|
13870
|
+
console.log(`${prefix} ${message}`);
|
|
13871
|
+
}
|
|
13872
|
+
function log2(state, message, level = "info") {
|
|
13873
|
+
if (!meetsThreshold(state, level)) return;
|
|
13874
|
+
if (state.json || !state.interactive) writeConsoleLog(state, message, level);
|
|
13875
|
+
}
|
|
13876
|
+
function logLocalOnly(state, message, level = "info") {
|
|
13877
|
+
if (!meetsThreshold(state, level)) return;
|
|
13878
|
+
writeConsoleLog(state, message, level);
|
|
13124
13879
|
}
|
|
13125
13880
|
function logActivity(state, entry) {
|
|
13126
13881
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
@@ -13321,6 +14076,8 @@ async function driveChannels(state, driver) {
|
|
|
13321
14076
|
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
13322
14077
|
let lastSeenClaudeApplies = driver.fileSyncActivity().claudeCredentialApplies;
|
|
13323
14078
|
let lastSeenOpencodeAuthApplies = driver.fileSyncActivity().opencodeAuthApplyCount;
|
|
14079
|
+
const stayAwakeHolds = () => state.stayAwakeUntilMs !== null && Date.now() < state.stayAwakeUntilMs;
|
|
14080
|
+
let stayAwakeSuppressionLogged = false;
|
|
13324
14081
|
while (state.running) {
|
|
13325
14082
|
const cycleStartedAtMs = performance.now();
|
|
13326
14083
|
let idleThisCycle = false;
|
|
@@ -13422,7 +14179,7 @@ async function driveChannels(state, driver) {
|
|
|
13422
14179
|
}
|
|
13423
14180
|
}
|
|
13424
14181
|
}
|
|
13425
|
-
await new Promise((
|
|
14182
|
+
await new Promise((resolve5) => setTimeout(resolve5, CHANNEL_POLL_INTERVAL_MS));
|
|
13426
14183
|
const cycleMs = performance.now() - cycleStartedAtMs;
|
|
13427
14184
|
if (idleThisCycle) idleMs += cycleMs;
|
|
13428
14185
|
if (unreachableThisCycle) unreachableMs += cycleMs;
|
|
@@ -13435,15 +14192,27 @@ async function driveChannels(state, driver) {
|
|
|
13435
14192
|
if (state.interactive) displayStatus(state);
|
|
13436
14193
|
break;
|
|
13437
14194
|
}
|
|
13438
|
-
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3) {
|
|
14195
|
+
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
|
|
13439
14196
|
logActivity(state, { type: "info", message: "Idle timeout reached" });
|
|
13440
14197
|
if (state.interactive) displayStatus(state);
|
|
13441
14198
|
break;
|
|
13442
14199
|
}
|
|
14200
|
+
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && stayAwakeHolds()) {
|
|
14201
|
+
if (!stayAwakeSuppressionLogged) {
|
|
14202
|
+
stayAwakeSuppressionLogged = true;
|
|
14203
|
+
logActivity(state, {
|
|
14204
|
+
type: "info",
|
|
14205
|
+
message: "Idle, but staying awake until the requested minimum passes"
|
|
14206
|
+
});
|
|
14207
|
+
}
|
|
14208
|
+
}
|
|
13443
14209
|
}
|
|
13444
14210
|
}
|
|
13445
14211
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
13446
14212
|
var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
|
|
14213
|
+
var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
|
|
14214
|
+
var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
|
|
14215
|
+
var MAX_SESSION_DELETE_BODY_LENGTH = 200;
|
|
13447
14216
|
function shouldWarnForReclaimSkip(reason) {
|
|
13448
14217
|
if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
|
|
13449
14218
|
const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
|
|
@@ -13454,7 +14223,7 @@ function shouldWarnForReclaimSkip(reason) {
|
|
|
13454
14223
|
return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
|
|
13455
14224
|
}
|
|
13456
14225
|
function sessionDbPath() {
|
|
13457
|
-
return
|
|
14226
|
+
return join12(homedir7(), ".local", "share", "opencode", "opencode.db");
|
|
13458
14227
|
}
|
|
13459
14228
|
function logSessionCleanupActivity(state, phase, entry) {
|
|
13460
14229
|
logActivity(state, {
|
|
@@ -13531,8 +14300,12 @@ async function runSweep(state, driver, config) {
|
|
|
13531
14300
|
protectedIds: protectedNow
|
|
13532
14301
|
}
|
|
13533
14302
|
);
|
|
13534
|
-
const
|
|
13535
|
-
|
|
14303
|
+
const eligibleToDelete = toDelete.filter(
|
|
14304
|
+
(id) => (state.sessionDeleteFailures.get(id)?.isolatedFailures ?? 0) < SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES
|
|
14305
|
+
);
|
|
14306
|
+
const deleteCandidates = eligibleToDelete.slice(0, SESSION_CLEANUP_MAX_DELETES_PER_SWEEP);
|
|
14307
|
+
remaining = eligibleToDelete.length - deleteCandidates.length;
|
|
14308
|
+
const answeredFailures = [];
|
|
13536
14309
|
protectedNow = driver.protectedSessionIds();
|
|
13537
14310
|
for (const id of deleteCandidates) {
|
|
13538
14311
|
if (protectedNow.has(id)) {
|
|
@@ -13555,8 +14328,44 @@ async function runSweep(state, driver, config) {
|
|
|
13555
14328
|
if (statusClass === 4) failed4xx++;
|
|
13556
14329
|
else if (statusClass === 5) failed5xx++;
|
|
13557
14330
|
else failedOtherStatus++;
|
|
14331
|
+
answeredFailures.push({
|
|
14332
|
+
id,
|
|
14333
|
+
status: outcome.status,
|
|
14334
|
+
...outcome.body !== void 0 ? { body: outcome.body } : {}
|
|
14335
|
+
});
|
|
13558
14336
|
}
|
|
13559
14337
|
}
|
|
14338
|
+
const givenUpFailures = [];
|
|
14339
|
+
if (failed > SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES) {
|
|
14340
|
+
for (const { id } of answeredFailures) state.sessionDeleteFailures.delete(id);
|
|
14341
|
+
} else {
|
|
14342
|
+
for (const failure of answeredFailures) {
|
|
14343
|
+
const previous = state.sessionDeleteFailures.get(failure.id);
|
|
14344
|
+
const record = previous?.status === failure.status ? { status: failure.status, isolatedFailures: previous.isolatedFailures + 1 } : { status: failure.status, isolatedFailures: 1 };
|
|
14345
|
+
state.sessionDeleteFailures.set(failure.id, record);
|
|
14346
|
+
if (record.isolatedFailures >= SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES) {
|
|
14347
|
+
givenUpFailures.push(failure);
|
|
14348
|
+
}
|
|
14349
|
+
}
|
|
14350
|
+
}
|
|
14351
|
+
for (const failure of givenUpFailures) {
|
|
14352
|
+
const excerpt = redactDiagnosticText(failure.body ?? "(no response body)").slice(
|
|
14353
|
+
0,
|
|
14354
|
+
MAX_SESSION_DELETE_BODY_LENGTH
|
|
14355
|
+
);
|
|
14356
|
+
logSessionCleanupActivity(state, "sweep", {
|
|
14357
|
+
type: "info",
|
|
14358
|
+
level: "warn",
|
|
14359
|
+
message: `Session cleanup: gave up on session ${failure.id} after ${SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES} isolated delete failures (status ${failure.status}): ${excerpt}`,
|
|
14360
|
+
metadata: {
|
|
14361
|
+
outcome: "session-delete-given-up",
|
|
14362
|
+
session_id: failure.id,
|
|
14363
|
+
status: failure.status,
|
|
14364
|
+
body_excerpt: excerpt,
|
|
14365
|
+
given_up_count: givenUpFailures.length
|
|
14366
|
+
}
|
|
14367
|
+
});
|
|
14368
|
+
}
|
|
13560
14369
|
const failedNote = failed > 0 ? `, failed ${failed}` : "";
|
|
13561
14370
|
const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
|
|
13562
14371
|
const remainingNote = remaining > 0 ? `, remaining ${remaining}` : "";
|
|
@@ -13577,21 +14386,31 @@ async function runSweep(state, driver, config) {
|
|
|
13577
14386
|
sessions_remaining: remaining,
|
|
13578
14387
|
...enumerationReason !== null ? { session_enumeration_reason: enumerationReason } : {}
|
|
13579
14388
|
};
|
|
14389
|
+
const protectedForReclaim = driver.protectedSessionIds();
|
|
13580
14390
|
const reclaimResult = await reclaimSessionDbSpace({
|
|
13581
14391
|
dbPath: sessionDbPath(),
|
|
13582
14392
|
chunkPages: SESSION_DB_RECLAIM_CHUNK_PAGES,
|
|
13583
14393
|
pageCeiling: SESSION_DB_RECLAIM_PAGE_CEILING,
|
|
13584
14394
|
timeBudgetMs: SESSION_DB_RECLAIM_TIME_BUDGET_MS,
|
|
13585
|
-
|
|
14395
|
+
hasLiveTurn: protectedForReclaim.size > 0,
|
|
14396
|
+
hasProvenanceAnomaly: state.sessionDbProvenanceAnomaly
|
|
13586
14397
|
});
|
|
13587
14398
|
if (reclaimResult.ok) {
|
|
13588
14399
|
state.sessionStoreHealth.observeWritable();
|
|
13589
14400
|
const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
|
|
13590
14401
|
const afterMib = (reclaimResult.afterBytes / 1024 / 1024).toFixed(1);
|
|
13591
14402
|
const checkpointNote = reclaimResult.checkpoint.busy ? ` (on-disk file truncation deferred: checkpoint busy, ${reclaimResult.checkpoint.log} WAL frames pending)` : "";
|
|
14403
|
+
const loopElapsedMs = Math.max(
|
|
14404
|
+
0,
|
|
14405
|
+
reclaimResult.elapsedMs - reclaimResult.checkpointElapsedMs
|
|
14406
|
+
);
|
|
14407
|
+
const reclaimIsSlow = reclaimResult.elapsedMs >= 4 * SESSION_DB_RECLAIM_TIME_BUDGET_MS;
|
|
14408
|
+
const perPageNote = reclaimResult.pagesReclaimed > 0 ? `, per-page ${(loopElapsedMs / reclaimResult.pagesReclaimed).toFixed(2)} ms/page` : "";
|
|
14409
|
+
const slowReclaimNote = reclaimIsSlow ? ` (slow reclaim: total elapsed ${reclaimResult.elapsedMs} ms, checkpoint ${reclaimResult.checkpointElapsedMs} ms, loop ${loopElapsedMs} ms, budget ${SESSION_DB_RECLAIM_TIME_BUDGET_MS} ms${perPageNote})` : "";
|
|
13592
14410
|
logSessionCleanupActivity(state, "sweep", {
|
|
13593
14411
|
type: "info",
|
|
13594
|
-
|
|
14412
|
+
level: reclaimIsSlow ? "warn" : "info",
|
|
14413
|
+
message: `Session cleanup: reclaimed session-db space (${reclaimResult.mode}): ${beforeMib} MiB -> ${afterMib} MiB (stopped by ${reclaimResult.stoppedBy}; freelist ${reclaimResult.freelistBefore} -> ${reclaimResult.freelistAfter} pages)` + checkpointNote + slowReclaimNote,
|
|
13595
14414
|
metadata: {
|
|
13596
14415
|
outcome: "reclaimed",
|
|
13597
14416
|
mode: reclaimResult.mode,
|
|
@@ -13604,6 +14423,7 @@ async function runSweep(state, driver, config) {
|
|
|
13604
14423
|
freelist_after: reclaimResult.freelistAfter,
|
|
13605
14424
|
pages_reclaimed: reclaimResult.pagesReclaimed,
|
|
13606
14425
|
reclaim_elapsed_ms: reclaimResult.elapsedMs,
|
|
14426
|
+
checkpoint_elapsed_ms: reclaimResult.checkpointElapsedMs,
|
|
13607
14427
|
...sessionMetadata
|
|
13608
14428
|
}
|
|
13609
14429
|
});
|
|
@@ -13714,10 +14534,12 @@ function scheduleUsageReporting(state, params) {
|
|
|
13714
14534
|
let phase = "dormant";
|
|
13715
14535
|
let rearmRequested = false;
|
|
13716
14536
|
const armProbe = () => {
|
|
14537
|
+
if (!state.running) return;
|
|
13717
14538
|
phase = "probe-pending";
|
|
13718
14539
|
params.setTimer(setTimeout(() => void tick(true), params.firstDelayMs()));
|
|
13719
14540
|
};
|
|
13720
14541
|
const scheduleNextTick = () => {
|
|
14542
|
+
if (!state.running) return;
|
|
13721
14543
|
if (rearmRequested) {
|
|
13722
14544
|
rearmRequested = false;
|
|
13723
14545
|
armProbe();
|
|
@@ -13751,6 +14573,7 @@ function scheduleUsageReporting(state, params) {
|
|
|
13751
14573
|
phase = "tick-in-flight";
|
|
13752
14574
|
try {
|
|
13753
14575
|
const usage = await params.fetchUsage();
|
|
14576
|
+
if (!state.running) return;
|
|
13754
14577
|
const result = await params.report(usage);
|
|
13755
14578
|
if (result.ok) {
|
|
13756
14579
|
if (consecutiveFailures > 0) {
|
|
@@ -13889,6 +14712,7 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
13889
14712
|
message: lowDiskDecision.warning
|
|
13890
14713
|
});
|
|
13891
14714
|
}
|
|
14715
|
+
if (!state.running) return;
|
|
13892
14716
|
const result = await reportResourceUsage(state.agentId, state.authHeader, usage);
|
|
13893
14717
|
if (result.ok) {
|
|
13894
14718
|
if (consecutiveFailures > 0) {
|
|
@@ -13921,7 +14745,9 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
13921
14745
|
message: `Resource usage reporting failed: ${message}${failureStreakSuffix(consecutiveFailures)}`
|
|
13922
14746
|
});
|
|
13923
14747
|
} finally {
|
|
13924
|
-
state.
|
|
14748
|
+
if (state.running) {
|
|
14749
|
+
state.resourceUsageTimer = setTimeout(() => void tick(), usageReportDelayMs());
|
|
14750
|
+
}
|
|
13925
14751
|
}
|
|
13926
14752
|
};
|
|
13927
14753
|
state.resourceUsageTimer = setTimeout(() => void tick(), firstReportDelayMs());
|
|
@@ -14083,8 +14909,8 @@ async function beginGracefulShutdown(state, trigger) {
|
|
|
14083
14909
|
return true;
|
|
14084
14910
|
}
|
|
14085
14911
|
);
|
|
14086
|
-
const timedOut = new Promise((
|
|
14087
|
-
timer = setTimeout(() =>
|
|
14912
|
+
const timedOut = new Promise((resolve5) => {
|
|
14913
|
+
timer = setTimeout(() => resolve5(false), telemetryBudgetMs);
|
|
14088
14914
|
});
|
|
14089
14915
|
if (!await Promise.race([flushed, timedOut])) {
|
|
14090
14916
|
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
@@ -14124,6 +14950,8 @@ async function run(options) {
|
|
|
14124
14950
|
port: options.port ?? 4096,
|
|
14125
14951
|
conversationFilter: options.conversation ?? null,
|
|
14126
14952
|
idleTimeout: options.idleTimeout ?? null,
|
|
14953
|
+
stayAwakeSeconds: null,
|
|
14954
|
+
stayAwakeUntilMs: null,
|
|
14127
14955
|
json: options.json ?? false,
|
|
14128
14956
|
interactive,
|
|
14129
14957
|
logLevel,
|
|
@@ -14147,6 +14975,7 @@ async function run(options) {
|
|
|
14147
14975
|
messageCount: 0,
|
|
14148
14976
|
lastProxiedActivityAt: null,
|
|
14149
14977
|
sessionCleanupTimers: [],
|
|
14978
|
+
sessionDeleteFailures: /* @__PURE__ */ new Map(),
|
|
14150
14979
|
claudeUsageTimer: null,
|
|
14151
14980
|
claudeUsageRearm: null,
|
|
14152
14981
|
openaiUsageTimer: null,
|
|
@@ -14312,6 +15141,17 @@ async function run(options) {
|
|
|
14312
15141
|
}
|
|
14313
15142
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
14314
15143
|
state.agentName = validation.agent.name;
|
|
15144
|
+
const requestedStayAwakeSeconds = validation.agent?.wake_stay_awake_seconds;
|
|
15145
|
+
if (typeof requestedStayAwakeSeconds === "number" && Number.isFinite(requestedStayAwakeSeconds) && requestedStayAwakeSeconds > 0) {
|
|
15146
|
+
state.stayAwakeSeconds = requestedStayAwakeSeconds;
|
|
15147
|
+
} else if (requestedStayAwakeSeconds !== void 0 && requestedStayAwakeSeconds !== null) {
|
|
15148
|
+
state.stayAwakeSeconds = null;
|
|
15149
|
+
log2(
|
|
15150
|
+
state,
|
|
15151
|
+
`Ignoring invalid wake_stay_awake_seconds (type: ${typeof requestedStayAwakeSeconds})`,
|
|
15152
|
+
"warn"
|
|
15153
|
+
);
|
|
15154
|
+
}
|
|
14315
15155
|
const microvmId = process.env.MICROVM_ID?.trim();
|
|
14316
15156
|
if (microvmId) {
|
|
14317
15157
|
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
@@ -14327,29 +15167,73 @@ async function run(options) {
|
|
|
14327
15167
|
} else {
|
|
14328
15168
|
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
14329
15169
|
}
|
|
14330
|
-
if (options.restoreRunnerCredentials) {
|
|
14331
|
-
|
|
14332
|
-
|
|
14333
|
-
|
|
14334
|
-
|
|
14335
|
-
if (level === "error") {
|
|
14336
|
-
logActivity(state, { type: "error", error: message });
|
|
14337
|
-
} else {
|
|
14338
|
-
logActivity(state, { type: "info", level, message });
|
|
14339
|
-
}
|
|
15170
|
+
if (options.restoreRunnerCredentials || options.credentialSyncMarker) {
|
|
15171
|
+
const logCredentialVaultResolution = (message, level) => {
|
|
15172
|
+
log2(state, message, level);
|
|
15173
|
+
if (state.interactive && !state.json) {
|
|
15174
|
+
logActivity(state, { type: "info", level, message });
|
|
14340
15175
|
}
|
|
14341
15176
|
};
|
|
14342
|
-
const
|
|
15177
|
+
const vaultResolution = await getRunnerCredentialVault(state.agentId, state.authHeader);
|
|
15178
|
+
if (vaultResolution.error) {
|
|
15179
|
+
delete process.env.CREDENTIAL_VAULT_PREFIX;
|
|
15180
|
+
logCredentialVaultResolution(
|
|
15181
|
+
`CREDENTIAL-VAULT-LOOKUP-FAILED: ${vaultResolution.error}; credentials will be read from and written to this runner's own prefix this boot`,
|
|
15182
|
+
"warn"
|
|
15183
|
+
);
|
|
15184
|
+
} else if (vaultResolution.prefix !== null && vaultResolution.vaultId !== null && vaultResolution.source !== null) {
|
|
15185
|
+
process.env.CREDENTIAL_VAULT_PREFIX = vaultResolution.prefix;
|
|
15186
|
+
logCredentialVaultResolution(
|
|
15187
|
+
`CREDENTIAL-VAULT: source=${vaultResolution.source} vault=${vaultResolution.vaultId} prefix=${vaultResolution.prefix}`,
|
|
15188
|
+
"info"
|
|
15189
|
+
);
|
|
15190
|
+
} else {
|
|
15191
|
+
delete process.env.CREDENTIAL_VAULT_PREFIX;
|
|
15192
|
+
logCredentialVaultResolution(
|
|
15193
|
+
"CREDENTIAL-VAULT-NONE: this runner is not linked to a credential vault; using its own prefix",
|
|
15194
|
+
"debug"
|
|
15195
|
+
);
|
|
15196
|
+
}
|
|
15197
|
+
}
|
|
15198
|
+
const credentialContext = {
|
|
15199
|
+
env: process.env,
|
|
15200
|
+
log: (message, level = "info") => {
|
|
15201
|
+
if (level === "error") {
|
|
15202
|
+
logActivity(state, { type: "error", error: message });
|
|
15203
|
+
} else {
|
|
15204
|
+
logActivity(state, { type: "info", level, message });
|
|
15205
|
+
}
|
|
15206
|
+
}
|
|
15207
|
+
};
|
|
15208
|
+
const githubTokenPopulated = await installRunnerSecret(credentialContext);
|
|
15209
|
+
if (options.restoreRunnerCredentials) {
|
|
14343
15210
|
await restoreCredentialStores(credentialContext);
|
|
14344
|
-
if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
|
|
14345
15211
|
}
|
|
15212
|
+
if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
|
|
14346
15213
|
state.credentialSync?.arm();
|
|
15214
|
+
const dependencyInstallDiagnosticReporter = createDependencyInstallDiagnosticReporter({
|
|
15215
|
+
context: {
|
|
15216
|
+
homeDir: homedir7(),
|
|
15217
|
+
cwd: process.cwd(),
|
|
15218
|
+
microvmId: process.env.MICROVM_ID?.trim(),
|
|
15219
|
+
euid: process.getuid?.(),
|
|
15220
|
+
egid: process.getgid?.()
|
|
15221
|
+
},
|
|
15222
|
+
emitEvent: (message) => logActivity(state, { type: "info", level: "warn", message }),
|
|
15223
|
+
emitLocal: (message) => logLocalOnly(state, message, "warn")
|
|
15224
|
+
});
|
|
14347
15225
|
const openCodeActivityForwarder = createOpenCodeActivityForwarder(
|
|
14348
15226
|
() => ({
|
|
14349
15227
|
agentId: state.agentId,
|
|
14350
15228
|
authHeader: state.authHeader
|
|
14351
15229
|
}),
|
|
14352
|
-
|
|
15230
|
+
({ isDiskFailure, sessionId, cause }) => {
|
|
15231
|
+
if (isDiskFailure) state.sessionStoreHealth.observeUnwritable();
|
|
15232
|
+
if (cause !== null && sessionId !== null) {
|
|
15233
|
+
state.sessionStoreHealth.observeCause(sessionId, cause);
|
|
15234
|
+
}
|
|
15235
|
+
},
|
|
15236
|
+
dependencyInstallDiagnosticReporter
|
|
14353
15237
|
);
|
|
14354
15238
|
const openCodeLogTail = tailOpenCodeLogFile(
|
|
14355
15239
|
resolveOpenCodeLogPath(homedir7(), process.env),
|
|
@@ -14360,22 +15244,27 @@ async function run(options) {
|
|
|
14360
15244
|
openCodeLogTail.stop();
|
|
14361
15245
|
};
|
|
14362
15246
|
let sessionDbVerifyFatal = false;
|
|
15247
|
+
let sessionDbVerifyFatalReason;
|
|
14363
15248
|
if (!options.restoreSessionDb) {
|
|
14364
|
-
|
|
15249
|
+
logActivity(state, {
|
|
15250
|
+
type: "info",
|
|
15251
|
+
level: "warn",
|
|
15252
|
+
message: "SESSION-DB-VERIFY-SKIPPED: reason=flag-absent \u2014 Skipping session-DB restore: --restore-session-db was not passed"
|
|
15253
|
+
});
|
|
14365
15254
|
} else {
|
|
14366
15255
|
const health = await checkOpenCodeHealth(state.port);
|
|
14367
15256
|
if (health.healthy) {
|
|
14368
|
-
|
|
14369
|
-
|
|
14370
|
-
|
|
14371
|
-
"
|
|
14372
|
-
);
|
|
15257
|
+
logActivity(state, {
|
|
15258
|
+
type: "info",
|
|
15259
|
+
level: "warn",
|
|
15260
|
+
message: "SESSION-DB-VERIFY-SKIPPED: reason=opencode-serving \u2014 Skipping session-DB restore: OpenCode is already serving this database"
|
|
15261
|
+
});
|
|
14373
15262
|
} else if (health.authFailed) {
|
|
14374
|
-
|
|
14375
|
-
|
|
14376
|
-
|
|
14377
|
-
"
|
|
14378
|
-
);
|
|
15263
|
+
logActivity(state, {
|
|
15264
|
+
type: "info",
|
|
15265
|
+
level: "warn",
|
|
15266
|
+
message: "SESSION-DB-VERIFY-SKIPPED: reason=opencode-auth-challenge \u2014 Skipping session-DB restore: OpenCode answered with an authentication challenge; assuming this database is in use"
|
|
15267
|
+
});
|
|
14379
15268
|
} else {
|
|
14380
15269
|
const result = await restoreAndVerifySessionDb({
|
|
14381
15270
|
dbPath: sessionDbPath(),
|
|
@@ -14392,12 +15281,13 @@ async function run(options) {
|
|
|
14392
15281
|
reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
|
|
14393
15282
|
});
|
|
14394
15283
|
sessionDbVerifyFatal = result.verifyFatal;
|
|
15284
|
+
sessionDbVerifyFatalReason = result.verifyFatalReason;
|
|
14395
15285
|
}
|
|
14396
15286
|
}
|
|
14397
15287
|
reportSessionDbRecovery(state);
|
|
14398
15288
|
if (sessionDbVerifyFatal) {
|
|
14399
15289
|
throw new Error(
|
|
14400
|
-
"SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
|
|
15290
|
+
sessionDbVerifyFatalReason === void 0 ? "SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk" : `SESSION-DB-VERIFY-TIMEOUT: session DB verification timed out (${sessionDbVerifyFatalReason}); refusing to start`
|
|
14401
15291
|
);
|
|
14402
15292
|
}
|
|
14403
15293
|
applyRunnerOpenCodeConfig({
|
|
@@ -14676,6 +15566,13 @@ async function run(options) {
|
|
|
14676
15566
|
type: "info",
|
|
14677
15567
|
message: connectionMessage
|
|
14678
15568
|
});
|
|
15569
|
+
if (!isReconnect && state.stayAwakeSeconds !== null && state.stayAwakeUntilMs === null) {
|
|
15570
|
+
state.stayAwakeUntilMs = Date.now() + state.stayAwakeSeconds * 1e3;
|
|
15571
|
+
logActivity(state, {
|
|
15572
|
+
type: "info",
|
|
15573
|
+
message: `Staying awake for at least ${state.stayAwakeSeconds}s as requested by the wake`
|
|
15574
|
+
});
|
|
15575
|
+
}
|
|
14679
15576
|
if (options.tunnelReadyFile) {
|
|
14680
15577
|
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
14681
15578
|
if (marker.ok) {
|
|
@@ -14724,14 +15621,14 @@ async function run(options) {
|
|
|
14724
15621
|
},
|
|
14725
15622
|
onDisconnected: (code, reason, transition) => {
|
|
14726
15623
|
state.connected = false;
|
|
14727
|
-
const
|
|
15624
|
+
const safeReason2 = redactDiagnosticText(reason).slice(0, MAX_DISCONNECT_REASON_LENGTH);
|
|
14728
15625
|
logActivity(state, {
|
|
14729
15626
|
type: "info",
|
|
14730
|
-
message: `Tunnel disconnected (generation: ${transition.generation}, code: ${code}, reason: ${
|
|
15627
|
+
message: `Tunnel disconnected (generation: ${transition.generation}, code: ${code}, reason: ${safeReason2})`
|
|
14731
15628
|
});
|
|
14732
15629
|
emitAgentDisconnected(state.agentId, {
|
|
14733
15630
|
code,
|
|
14734
|
-
reason:
|
|
15631
|
+
reason: safeReason2,
|
|
14735
15632
|
connection_generation: transition.generation
|
|
14736
15633
|
});
|
|
14737
15634
|
if (state.interactive) displayStatus(state);
|
|
@@ -14810,6 +15707,7 @@ async function run(options) {
|
|
|
14810
15707
|
if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
|
|
14811
15708
|
throw error2;
|
|
14812
15709
|
}
|
|
15710
|
+
if (!state.running) return;
|
|
14813
15711
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
14814
15712
|
state.claudeUsageRearm = scheduleClaudeUsageReporting(state, options);
|
|
14815
15713
|
state.openaiUsageRearm = scheduleUsageReporting(state, {
|
|
@@ -14894,6 +15792,7 @@ program.command("login").description("Authenticate with Evident").option("--toke
|
|
|
14894
15792
|
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 }));
|
|
14895
15793
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
14896
15794
|
program.command("status").description("Check whether the configured credentials can reach Evident").option("--json", "Output in JSON format").action((options) => status({ json: options.json }));
|
|
15795
|
+
program.command("credential-vault-env").description("Print the shell assignment a runner image evals before starting the synchroniser").action(credentialVaultEnv);
|
|
14897
15796
|
program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
|
|
14898
15797
|
program.command("run").description("Connect to Evident and process messages").option("--runner [id]", "Runner ID to connect to (optional when EVIDENT_RUNNER_KEY is set)").option(
|
|
14899
15798
|
"-a, --agent [id]",
|