@evident-ai/cli 3.4.1-dev.59c7df3 → 3.4.1-dev.5e8a101
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 +17 -0
- package/dist/index.js +1398 -246
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import { createRequire } from "module";
|
|
4
|
+
import { createRequire as createRequire2 } from "module";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
|
|
7
7
|
// src/commands/login.ts
|
|
@@ -11,8 +11,8 @@ import chalk2 from "chalk";
|
|
|
11
11
|
|
|
12
12
|
// src/lib/config.ts
|
|
13
13
|
import Conf from "conf";
|
|
14
|
-
import { chmodSync, existsSync, statSync } from "fs";
|
|
15
|
-
import { dirname } from "path";
|
|
14
|
+
import { chmodSync, existsSync, statSync } from "node:fs";
|
|
15
|
+
import { dirname } from "node:path";
|
|
16
16
|
var PRODUCTION_API_URL = "https://api.production.evident.run/v1";
|
|
17
17
|
var PRODUCTION_TUNNEL_URL = "wss://tunnel.production.evident.run";
|
|
18
18
|
var defaults = {
|
|
@@ -763,6 +763,13 @@ function toReportedOpenAiWindow(window) {
|
|
|
763
763
|
resets_at: window.resetsAt
|
|
764
764
|
};
|
|
765
765
|
}
|
|
766
|
+
function toReportedOpenAiSubscription(snapshot) {
|
|
767
|
+
if (!snapshot.subscription) return null;
|
|
768
|
+
return {
|
|
769
|
+
owner_email: snapshot.subscription.ownerEmail,
|
|
770
|
+
plan_type: snapshot.subscription.planType
|
|
771
|
+
};
|
|
772
|
+
}
|
|
766
773
|
async function reportOpenAiUsage(agentId, authHeader, snapshot) {
|
|
767
774
|
try {
|
|
768
775
|
const apiUrl = getApiUrlConfig();
|
|
@@ -773,7 +780,8 @@ async function reportOpenAiUsage(agentId, authHeader, snapshot) {
|
|
|
773
780
|
primary: toReportedOpenAiWindow(snapshot.primary),
|
|
774
781
|
secondary: toReportedOpenAiWindow(snapshot.secondary),
|
|
775
782
|
has_credits: snapshot.hasCredits,
|
|
776
|
-
credits_unlimited: snapshot.creditsUnlimited
|
|
783
|
+
credits_unlimited: snapshot.creditsUnlimited,
|
|
784
|
+
subscription: toReportedOpenAiSubscription(snapshot)
|
|
777
785
|
}),
|
|
778
786
|
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
779
787
|
});
|
|
@@ -797,6 +805,7 @@ async function reportResourceUsage(agentId, authHeader, usage) {
|
|
|
797
805
|
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
798
806
|
body: JSON.stringify({
|
|
799
807
|
cpu_percent: usage.cpuPercent,
|
|
808
|
+
cpu_peak_percent: usage.cpuPeakPercent,
|
|
800
809
|
cpu_count: usage.cpuCount,
|
|
801
810
|
memory_total_bytes: usage.memoryTotalBytes,
|
|
802
811
|
memory_available_bytes: usage.memoryAvailableBytes,
|
|
@@ -1000,10 +1009,10 @@ async function status(options = {}) {
|
|
|
1000
1009
|
}
|
|
1001
1010
|
|
|
1002
1011
|
// src/lib/claude-usage.ts
|
|
1003
|
-
import { execFileSync } from "child_process";
|
|
1004
|
-
import { readFileSync } from "fs";
|
|
1005
|
-
import { homedir } from "os";
|
|
1006
|
-
import { join } from "path";
|
|
1012
|
+
import { execFileSync } from "node:child_process";
|
|
1013
|
+
import { readFileSync } from "node:fs";
|
|
1014
|
+
import { homedir } from "node:os";
|
|
1015
|
+
import { join } from "node:path";
|
|
1007
1016
|
var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
1008
1017
|
var CLAUDE_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
|
|
1009
1018
|
var CLAUDE_PROFILE_TIMEOUT_MS = 2e3;
|
|
@@ -1183,10 +1192,10 @@ async function claudeUsage() {
|
|
|
1183
1192
|
}
|
|
1184
1193
|
|
|
1185
1194
|
// src/commands/run.ts
|
|
1186
|
-
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as
|
|
1187
|
-
import { homedir as
|
|
1188
|
-
import { isAbsolute as isAbsolute3, join as
|
|
1189
|
-
import
|
|
1195
|
+
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
|
|
1196
|
+
import { homedir as homedir6 } from "node:os";
|
|
1197
|
+
import { isAbsolute as isAbsolute3, join as join10, parse, resolve as resolvePath2 } from "node:path";
|
|
1198
|
+
import chalk7 from "chalk";
|
|
1190
1199
|
|
|
1191
1200
|
// ../../packages/types/src/agents/index.ts
|
|
1192
1201
|
var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
|
|
@@ -1207,6 +1216,7 @@ var TelemetryEventTypes = {
|
|
|
1207
1216
|
// ../../packages/types/src/tunnel/index.ts
|
|
1208
1217
|
var MAX_FRAME_BYTES = 256 * 1024;
|
|
1209
1218
|
var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
|
|
1219
|
+
var TUNNEL_USAGE_REARM_PING_PATH = "/__evident/usage-rearm";
|
|
1210
1220
|
|
|
1211
1221
|
// ../../packages/types/src/runner-files.ts
|
|
1212
1222
|
var MAX_FILE_PUSH_BYTES = 64 * 1024;
|
|
@@ -1244,7 +1254,7 @@ function stripQuery(url) {
|
|
|
1244
1254
|
|
|
1245
1255
|
// src/commands/run.ts
|
|
1246
1256
|
import ora3 from "ora";
|
|
1247
|
-
import { select as
|
|
1257
|
+
import { select as select4 } from "@inquirer/prompts";
|
|
1248
1258
|
|
|
1249
1259
|
// src/lib/telemetry.ts
|
|
1250
1260
|
var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
@@ -1417,12 +1427,50 @@ var SEVERITY_BY_LEVEL = {
|
|
|
1417
1427
|
warn: "warning",
|
|
1418
1428
|
error: "error"
|
|
1419
1429
|
};
|
|
1430
|
+
function parseOpenCodeLogLine(line) {
|
|
1431
|
+
const normalisedLine = line.replace(/\r$/, "");
|
|
1432
|
+
const levelMatch = normalisedLine.match(/(?:^|\s)level=(\w+)/i);
|
|
1433
|
+
if (!levelMatch) return null;
|
|
1434
|
+
const level = levelMatch[1].toUpperCase();
|
|
1435
|
+
if (level !== "WARN" && level !== "ERROR") return null;
|
|
1436
|
+
const sessionMatch = normalisedLine.match(/(?:^|\s)sessionID=(\S+)/);
|
|
1437
|
+
return { level: level === "WARN" ? "warn" : "error", sessionID: sessionMatch?.[1] };
|
|
1438
|
+
}
|
|
1439
|
+
var MAX_LINE_BUFFER_BYTES = 16 * 1024;
|
|
1440
|
+
function createOpenCodeActivityForwarder(getContext) {
|
|
1441
|
+
let buffer = Buffer.alloc(0);
|
|
1442
|
+
const flushLine = (line) => {
|
|
1443
|
+
const parsed = parseOpenCodeLogLine(line);
|
|
1444
|
+
if (!parsed) return;
|
|
1445
|
+
forwardRunnerActivity(
|
|
1446
|
+
{
|
|
1447
|
+
level: parsed.level,
|
|
1448
|
+
error: line,
|
|
1449
|
+
metadata: parsed.sessionID ? { sessionID: parsed.sessionID } : void 0,
|
|
1450
|
+
source: "opencode"
|
|
1451
|
+
},
|
|
1452
|
+
getContext()
|
|
1453
|
+
);
|
|
1454
|
+
};
|
|
1455
|
+
return (chunk) => {
|
|
1456
|
+
buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf-8")]);
|
|
1457
|
+
let newlineIndex;
|
|
1458
|
+
while ((newlineIndex = buffer.indexOf(10)) !== -1) {
|
|
1459
|
+
flushLine(buffer.subarray(0, newlineIndex).toString("utf-8").replace(/\r$/, ""));
|
|
1460
|
+
buffer = buffer.subarray(newlineIndex + 1);
|
|
1461
|
+
}
|
|
1462
|
+
if (buffer.length > MAX_LINE_BUFFER_BYTES) {
|
|
1463
|
+
flushLine(buffer.toString("utf-8"));
|
|
1464
|
+
buffer = Buffer.alloc(0);
|
|
1465
|
+
}
|
|
1466
|
+
};
|
|
1467
|
+
}
|
|
1420
1468
|
var MAX_MESSAGE_LENGTH = 500;
|
|
1421
1469
|
var MAX_METADATA_VALUE_LENGTH = 200;
|
|
1422
1470
|
var MAX_METADATA_ENTRIES = 20;
|
|
1423
1471
|
var TRUNCATION_MARKER = "\u2026";
|
|
1424
1472
|
function redact(message) {
|
|
1425
|
-
return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
1473
|
+
return 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>");
|
|
1426
1474
|
}
|
|
1427
1475
|
function truncate(message) {
|
|
1428
1476
|
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
@@ -1448,43 +1496,47 @@ function sanitiseMetadata(metadata) {
|
|
|
1448
1496
|
}
|
|
1449
1497
|
var RATE_LIMIT_WINDOW_MS = 6e4;
|
|
1450
1498
|
var RATE_LIMIT_MAX_EVENTS = 30;
|
|
1451
|
-
var
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1499
|
+
var rateWindows = /* @__PURE__ */ new Map();
|
|
1500
|
+
function admitUnderRateLimit(source, now) {
|
|
1501
|
+
let window = rateWindows.get(source);
|
|
1502
|
+
if (!window) {
|
|
1503
|
+
window = { windowStartedAt: 0, windowCount: 0, windowDroppedCount: 0 };
|
|
1504
|
+
rateWindows.set(source, window);
|
|
1505
|
+
}
|
|
1506
|
+
if (now - window.windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
|
|
1507
|
+
if (window.windowDroppedCount > 0) {
|
|
1457
1508
|
console.error(
|
|
1458
|
-
`[runner-activity-telemetry] rate cap reached: dropped ${windowDroppedCount} ${windowDroppedCount === 1 ? "entry" : "entries"} in the last ${RATE_LIMIT_WINDOW_MS / 1e3}s (cap ${RATE_LIMIT_MAX_EVENTS}/min)`
|
|
1509
|
+
`[runner-activity-telemetry] rate cap reached: dropped ${window.windowDroppedCount} ${window.windowDroppedCount === 1 ? "entry" : "entries"} in the last ${RATE_LIMIT_WINDOW_MS / 1e3}s (cap ${RATE_LIMIT_MAX_EVENTS}/min) for source "${source}"`
|
|
1459
1510
|
);
|
|
1460
1511
|
}
|
|
1461
|
-
windowStartedAt = now;
|
|
1462
|
-
windowCount = 0;
|
|
1463
|
-
windowDroppedCount = 0;
|
|
1512
|
+
window.windowStartedAt = now;
|
|
1513
|
+
window.windowCount = 0;
|
|
1514
|
+
window.windowDroppedCount = 0;
|
|
1464
1515
|
}
|
|
1465
|
-
if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
1466
|
-
windowDroppedCount++;
|
|
1467
|
-
if (windowDroppedCount === 1) {
|
|
1516
|
+
if (window.windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
1517
|
+
window.windowDroppedCount++;
|
|
1518
|
+
if (window.windowDroppedCount === 1) {
|
|
1468
1519
|
console.error(
|
|
1469
|
-
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
|
|
1520
|
+
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window for source "${source}"`
|
|
1470
1521
|
);
|
|
1471
1522
|
}
|
|
1472
1523
|
return false;
|
|
1473
1524
|
}
|
|
1474
|
-
windowCount++;
|
|
1525
|
+
window.windowCount++;
|
|
1475
1526
|
return true;
|
|
1476
1527
|
}
|
|
1477
1528
|
function forwardRunnerActivity(entry, context) {
|
|
1478
1529
|
try {
|
|
1479
1530
|
if (!FORWARDED_LEVELS.has(entry.level)) return;
|
|
1480
1531
|
if (!context.agentId || !context.authHeader) return;
|
|
1481
|
-
|
|
1532
|
+
const source = entry.source ?? "cli.run";
|
|
1533
|
+
if (!admitUnderRateLimit(source, Date.now())) return;
|
|
1482
1534
|
const rawMessage = entry.error ?? entry.message ?? "";
|
|
1483
1535
|
const message = truncate(redact(rawMessage));
|
|
1484
1536
|
logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
|
|
1485
1537
|
severity: SEVERITY_BY_LEVEL[entry.level],
|
|
1486
1538
|
message,
|
|
1487
|
-
metadata: { ...sanitiseMetadata(entry.metadata), source
|
|
1539
|
+
metadata: { ...sanitiseMetadata(entry.metadata), source },
|
|
1488
1540
|
agentId: context.agentId
|
|
1489
1541
|
});
|
|
1490
1542
|
} catch (err) {
|
|
@@ -1495,8 +1547,8 @@ function forwardRunnerActivity(entry, context) {
|
|
|
1495
1547
|
}
|
|
1496
1548
|
|
|
1497
1549
|
// src/lib/opencode/session-db-recovery-report.ts
|
|
1498
|
-
import { readFileSync as readFileSync2, unlinkSync } from "fs";
|
|
1499
|
-
import { join as join2 } from "path";
|
|
1550
|
+
import { readFileSync as readFileSync2, unlinkSync } from "node:fs";
|
|
1551
|
+
import { join as join2 } from "node:path";
|
|
1500
1552
|
function sessionDbRecoveryReportPath(homeDir, env) {
|
|
1501
1553
|
const override = env.EVIDENT_SESSION_DB_RECOVERY_REPORT?.trim();
|
|
1502
1554
|
return override || join2(homeDir, ".local", "state", "evident", "session-db-recovery.jsonl");
|
|
@@ -1525,7 +1577,14 @@ function drainSessionDbRecoveryReport({
|
|
|
1525
1577
|
skippedLines++;
|
|
1526
1578
|
return [];
|
|
1527
1579
|
}
|
|
1528
|
-
return [
|
|
1580
|
+
return [
|
|
1581
|
+
{
|
|
1582
|
+
...value,
|
|
1583
|
+
provenance_reason: value.provenance_reason ?? null,
|
|
1584
|
+
provenance_migration_delta: value.provenance_migration_delta ?? null,
|
|
1585
|
+
replication_suspended: value.replication_suspended ?? false
|
|
1586
|
+
}
|
|
1587
|
+
];
|
|
1529
1588
|
} catch (error2) {
|
|
1530
1589
|
skippedLines++;
|
|
1531
1590
|
console.error(
|
|
@@ -1628,6 +1687,12 @@ function buildSessionDbRecoveryActivity(record) {
|
|
|
1628
1687
|
metadata: withoutContractFields(record),
|
|
1629
1688
|
message: `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.`
|
|
1630
1689
|
};
|
|
1690
|
+
case "schema_provenance_mismatch":
|
|
1691
|
+
return {
|
|
1692
|
+
level,
|
|
1693
|
+
metadata: withoutContractFields(record),
|
|
1694
|
+
message: `Session database schema provenance mismatch for ${record.dbPath ?? record.db_path ?? "unknown"}: recorded version=${record.recorded_version ?? "unknown"}, current version=${record.current_version ?? "unknown"}, reason=${record.provenance_reason ?? "unknown"}, migration delta=${record.provenance_migration_delta ?? "unknown"}. Inspect the session database and runner backup before continuing.`
|
|
1695
|
+
};
|
|
1631
1696
|
default:
|
|
1632
1697
|
return null;
|
|
1633
1698
|
}
|
|
@@ -1642,7 +1707,8 @@ var OUTCOMES = /* @__PURE__ */ new Set([
|
|
|
1642
1707
|
"fresh_session_db",
|
|
1643
1708
|
"history_rolled_back",
|
|
1644
1709
|
"restore_misconfigured",
|
|
1645
|
-
"session_db_boot_refused"
|
|
1710
|
+
"session_db_boot_refused",
|
|
1711
|
+
"schema_provenance_mismatch"
|
|
1646
1712
|
]);
|
|
1647
1713
|
var STAGES = /* @__PURE__ */ new Set(["restore", "verify"]);
|
|
1648
1714
|
var SEVERITIES = /* @__PURE__ */ new Set(["warning", "error"]);
|
|
@@ -1660,7 +1726,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
|
|
|
1660
1726
|
function isSessionDbRecoveryRecord(value) {
|
|
1661
1727
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1662
1728
|
const record = value;
|
|
1663
|
-
return record.v === 1 && record.event === "session_db_recovery" && typeof record.at === "string" && STAGES.has(record.stage) && OUTCOMES.has(record.outcome) && SEVERITIES.has(record.severity) && typeof record.reason === "string" && (record.replication_suspended === void 0 || typeof record.replication_suspended === "boolean") && NUMBER_FIELDS.every((field) => record[field] === null || Number.isInteger(record[field])) && STRING_OR_NULL_FIELDS.every(
|
|
1729
|
+
return record.v === 1 && record.event === "session_db_recovery" && typeof record.at === "string" && STAGES.has(record.stage) && OUTCOMES.has(record.outcome) && SEVERITIES.has(record.severity) && typeof record.reason === "string" && (record.replication_suspended === void 0 || typeof record.replication_suspended === "boolean") && (record.provenance_reason === void 0 || record.provenance_reason === null || typeof record.provenance_reason === "string") && (record.provenance_migration_delta === void 0 || record.provenance_migration_delta === null || Number.isInteger(record.provenance_migration_delta)) && NUMBER_FIELDS.every((field) => record[field] === null || Number.isInteger(record[field])) && STRING_OR_NULL_FIELDS.every(
|
|
1664
1730
|
(field) => record[field] === null || typeof record[field] === "string"
|
|
1665
1731
|
);
|
|
1666
1732
|
}
|
|
@@ -1695,13 +1761,13 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
1695
1761
|
}
|
|
1696
1762
|
|
|
1697
1763
|
// src/lib/opencode/session-db-boot.ts
|
|
1698
|
-
import { spawn as spawn2 } from "child_process";
|
|
1699
|
-
import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "fs";
|
|
1700
|
-
import { homedir as homedir2 } from "os";
|
|
1701
|
-
import { dirname as dirname2, resolve as resolvePath } from "path";
|
|
1764
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1765
|
+
import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "node:fs";
|
|
1766
|
+
import { homedir as homedir2 } from "node:os";
|
|
1767
|
+
import { dirname as dirname2, resolve as resolvePath } from "node:path";
|
|
1702
1768
|
|
|
1703
1769
|
// src/lib/runner-synchroniser.ts
|
|
1704
|
-
import { spawn } from "child_process";
|
|
1770
|
+
import { spawn } from "node:child_process";
|
|
1705
1771
|
function appendError(stderr, error2) {
|
|
1706
1772
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
1707
1773
|
return stderr === "" ? message : `${stderr}
|
|
@@ -1714,10 +1780,14 @@ function runSynchroniser(args, opts) {
|
|
|
1714
1780
|
let stderr = "";
|
|
1715
1781
|
let settled = false;
|
|
1716
1782
|
const timer = {};
|
|
1783
|
+
let abortListener;
|
|
1784
|
+
let spawnListener;
|
|
1717
1785
|
const finish = (result) => {
|
|
1718
1786
|
if (settled) return;
|
|
1719
1787
|
settled = true;
|
|
1720
1788
|
if (timer.handle) clearTimeout(timer.handle);
|
|
1789
|
+
if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
|
|
1790
|
+
if (spawnListener) child.removeListener("spawn", spawnListener);
|
|
1721
1791
|
resolve4(result);
|
|
1722
1792
|
};
|
|
1723
1793
|
try {
|
|
@@ -1743,6 +1813,25 @@ function runSynchroniser(args, opts) {
|
|
|
1743
1813
|
child.once("close", (code) => {
|
|
1744
1814
|
finish({ code, stdout, stderr, timedOut: false });
|
|
1745
1815
|
});
|
|
1816
|
+
if (opts.signal) {
|
|
1817
|
+
const killChild = () => {
|
|
1818
|
+
if (child.pid === void 0) {
|
|
1819
|
+
if (!spawnListener) {
|
|
1820
|
+
spawnListener = killChild;
|
|
1821
|
+
child.once("spawn", spawnListener);
|
|
1822
|
+
}
|
|
1823
|
+
return;
|
|
1824
|
+
}
|
|
1825
|
+
child.kill("SIGKILL");
|
|
1826
|
+
};
|
|
1827
|
+
abortListener = killChild;
|
|
1828
|
+
if (opts.signal.aborted) {
|
|
1829
|
+
abortListener();
|
|
1830
|
+
} else {
|
|
1831
|
+
opts.signal.addEventListener("abort", abortListener, { once: true });
|
|
1832
|
+
if (opts.signal.aborted) abortListener();
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1746
1835
|
timer.handle = setTimeout(
|
|
1747
1836
|
() => {
|
|
1748
1837
|
child.kill("SIGKILL");
|
|
@@ -1780,6 +1869,8 @@ function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
|
|
|
1780
1869
|
quarantined_bytes: null,
|
|
1781
1870
|
verified_restore_point: null,
|
|
1782
1871
|
restore_points_tried: null,
|
|
1872
|
+
provenance_reason: null,
|
|
1873
|
+
provenance_migration_delta: null,
|
|
1783
1874
|
replication_suspended: stage === "restore"
|
|
1784
1875
|
});
|
|
1785
1876
|
}
|
|
@@ -2200,6 +2291,131 @@ async function restoreAndVerifySessionDb(options) {
|
|
|
2200
2291
|
return { verifyFatal: await verifySessionDb(options, configPath, env) };
|
|
2201
2292
|
}
|
|
2202
2293
|
|
|
2294
|
+
// src/lib/opencode/session-db-provenance.ts
|
|
2295
|
+
import { createRequire } from "node:module";
|
|
2296
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
2297
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
2298
|
+
var require2 = createRequire(import.meta.url);
|
|
2299
|
+
function readSessionDbMigrationIds(dbPath) {
|
|
2300
|
+
let db;
|
|
2301
|
+
try {
|
|
2302
|
+
const { DatabaseSync } = require2("node:sqlite");
|
|
2303
|
+
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
2304
|
+
const columns = db.prepare("PRAGMA table_info(migration)").all();
|
|
2305
|
+
const hasExpectedShape = columns.length === 2 && columns.some(
|
|
2306
|
+
(column) => column.name === "id" && typeof column.type === "string" && column.type.toUpperCase() === "TEXT" && column.pk === 1
|
|
2307
|
+
) && columns.some(
|
|
2308
|
+
(column) => column.name === "time_completed" && typeof column.type === "string" && column.type.toUpperCase() === "INTEGER" && column.notnull === 1 && column.pk === 0
|
|
2309
|
+
);
|
|
2310
|
+
if (!hasExpectedShape) {
|
|
2311
|
+
console.warn(`[readSessionDbMigrationIds] unsupported migration table shape in ${dbPath}`);
|
|
2312
|
+
return null;
|
|
2313
|
+
}
|
|
2314
|
+
const rows = db.prepare("SELECT id FROM migration ORDER BY id").all();
|
|
2315
|
+
if (rows.some((row) => typeof row.id !== "string")) return null;
|
|
2316
|
+
return rows.map((row) => row.id);
|
|
2317
|
+
} catch (error2) {
|
|
2318
|
+
console.warn(
|
|
2319
|
+
`[readSessionDbMigrationIds] could not read migration history from ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2320
|
+
);
|
|
2321
|
+
return null;
|
|
2322
|
+
} finally {
|
|
2323
|
+
try {
|
|
2324
|
+
db?.close();
|
|
2325
|
+
} catch (error2) {
|
|
2326
|
+
console.warn(
|
|
2327
|
+
`[readSessionDbMigrationIds] could not close ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2328
|
+
);
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
function sessionDbProvenanceStatePath(homeDir, env) {
|
|
2333
|
+
const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
|
|
2334
|
+
return override || join3(homeDir, ".local", "state", "evident", "session-db-provenance.json");
|
|
2335
|
+
}
|
|
2336
|
+
function loadSessionDbProvenanceState(path) {
|
|
2337
|
+
let value;
|
|
2338
|
+
try {
|
|
2339
|
+
value = JSON.parse(readFileSync3(path, "utf8"));
|
|
2340
|
+
} catch (error2) {
|
|
2341
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return {};
|
|
2342
|
+
console.error(
|
|
2343
|
+
`[session-db-provenance] could not read ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2344
|
+
);
|
|
2345
|
+
return {};
|
|
2346
|
+
}
|
|
2347
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
2348
|
+
console.error(`[session-db-provenance] ignored malformed state in ${path}`);
|
|
2349
|
+
return {};
|
|
2350
|
+
}
|
|
2351
|
+
const state = {};
|
|
2352
|
+
for (const [dbPath, record] of Object.entries(value)) {
|
|
2353
|
+
if (!isSessionDbProvenanceRecord(record)) {
|
|
2354
|
+
console.error(`[session-db-provenance] ignored malformed state in ${path}`);
|
|
2355
|
+
return {};
|
|
2356
|
+
}
|
|
2357
|
+
state[dbPath] = record;
|
|
2358
|
+
}
|
|
2359
|
+
return state;
|
|
2360
|
+
}
|
|
2361
|
+
function saveSessionDbProvenanceState(path, state) {
|
|
2362
|
+
try {
|
|
2363
|
+
mkdirSync2(dirname3(path), { recursive: true });
|
|
2364
|
+
writeFileSync2(path, `${JSON.stringify(state, null, 2)}
|
|
2365
|
+
`, "utf8");
|
|
2366
|
+
} catch (error2) {
|
|
2367
|
+
console.error(
|
|
2368
|
+
`[session-db-provenance] could not write ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2369
|
+
);
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
2372
|
+
function evaluateSessionDbProvenance(input) {
|
|
2373
|
+
const { currentVersion, currentIds, previous } = input;
|
|
2374
|
+
if (!previous) return { anomaly: false, reason: null };
|
|
2375
|
+
const current = new Set(currentIds);
|
|
2376
|
+
const prior = new Set(previous.migrationIds);
|
|
2377
|
+
for (const id of prior) {
|
|
2378
|
+
if (!current.has(id)) return { anomaly: true, reason: "migration-history-regressed" };
|
|
2379
|
+
}
|
|
2380
|
+
if (current.size > prior.size && previous.opencodeVersion === currentVersion) {
|
|
2381
|
+
return { anomaly: true, reason: "foreign-version-migrations" };
|
|
2382
|
+
}
|
|
2383
|
+
return { anomaly: false, reason: null };
|
|
2384
|
+
}
|
|
2385
|
+
function checkSessionDbProvenance(input) {
|
|
2386
|
+
const { dbPath, currentVersion, homeDir, env } = input;
|
|
2387
|
+
const path = sessionDbProvenanceStatePath(homeDir, env);
|
|
2388
|
+
const state = loadSessionDbProvenanceState(path);
|
|
2389
|
+
const previous = state[dbPath];
|
|
2390
|
+
const currentIds = readSessionDbMigrationIds(dbPath);
|
|
2391
|
+
if (currentIds === null) {
|
|
2392
|
+
return {
|
|
2393
|
+
anomaly: false,
|
|
2394
|
+
reason: null,
|
|
2395
|
+
recordedVersion: previous?.opencodeVersion ?? null,
|
|
2396
|
+
migrationDelta: null
|
|
2397
|
+
};
|
|
2398
|
+
}
|
|
2399
|
+
const decision = evaluateSessionDbProvenance({ currentVersion, currentIds, previous });
|
|
2400
|
+
const migrationDelta = previous ? new Set(currentIds).size - new Set(previous.migrationIds).size : null;
|
|
2401
|
+
state[dbPath] = {
|
|
2402
|
+
opencodeVersion: currentVersion,
|
|
2403
|
+
migrationIds: currentIds,
|
|
2404
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2405
|
+
};
|
|
2406
|
+
saveSessionDbProvenanceState(path, state);
|
|
2407
|
+
return {
|
|
2408
|
+
...decision,
|
|
2409
|
+
recordedVersion: previous?.opencodeVersion ?? null,
|
|
2410
|
+
migrationDelta
|
|
2411
|
+
};
|
|
2412
|
+
}
|
|
2413
|
+
function isSessionDbProvenanceRecord(value) {
|
|
2414
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2415
|
+
const record = value;
|
|
2416
|
+
return typeof record.opencodeVersion === "string" && Array.isArray(record.migrationIds) && record.migrationIds.every((id) => typeof id === "string") && typeof record.updatedAt === "string";
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2203
2419
|
// src/lib/opencode/opencode-version-gate.ts
|
|
2204
2420
|
var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
|
|
2205
2421
|
function isQueueValidatedVersion(version2) {
|
|
@@ -2272,6 +2488,17 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
|
2272
2488
|
|
|
2273
2489
|
// src/lib/opencode/process.ts
|
|
2274
2490
|
var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
|
|
2491
|
+
var VALID_OPENCODE_LOG_LEVELS = /* @__PURE__ */ new Set(["DEBUG", "INFO", "WARN", "ERROR"]);
|
|
2492
|
+
function resolveOpenCodeLogLevel(env) {
|
|
2493
|
+
const raw = env.OPENCODE_LOG_LEVEL;
|
|
2494
|
+
if (!raw) return "INFO";
|
|
2495
|
+
const upper = raw.toUpperCase();
|
|
2496
|
+
if (VALID_OPENCODE_LOG_LEVELS.has(upper)) return upper;
|
|
2497
|
+
console.warn(
|
|
2498
|
+
`startOpenCode: ignoring invalid OPENCODE_LOG_LEVEL "${raw}" (expected DEBUG|INFO|WARN|ERROR) \u2014 using INFO`
|
|
2499
|
+
);
|
|
2500
|
+
return "INFO";
|
|
2501
|
+
}
|
|
2275
2502
|
function getProcessCwd(pid) {
|
|
2276
2503
|
const platform = process.platform;
|
|
2277
2504
|
try {
|
|
@@ -2320,14 +2547,14 @@ function findAvailablePort(startPort, maxAttempts = 10) {
|
|
|
2320
2547
|
}
|
|
2321
2548
|
return null;
|
|
2322
2549
|
}
|
|
2323
|
-
function
|
|
2550
|
+
function findProcessesByPattern(pgrepPattern, psPattern) {
|
|
2324
2551
|
const instances = [];
|
|
2325
2552
|
try {
|
|
2326
2553
|
const platform = process.platform;
|
|
2327
2554
|
if (platform === "darwin" || platform === "linux") {
|
|
2328
2555
|
let pids = [];
|
|
2329
2556
|
try {
|
|
2330
|
-
const pgrepOutput = execSync(
|
|
2557
|
+
const pgrepOutput = execSync(`pgrep -f "${pgrepPattern}"`, {
|
|
2331
2558
|
encoding: "utf-8",
|
|
2332
2559
|
stdio: ["pipe", "pipe", "pipe"]
|
|
2333
2560
|
}).trim();
|
|
@@ -2336,7 +2563,7 @@ function findOpenCodeProcesses() {
|
|
|
2336
2563
|
}
|
|
2337
2564
|
} catch {
|
|
2338
2565
|
try {
|
|
2339
|
-
const psOutput = execSync(
|
|
2566
|
+
const psOutput = execSync(`ps aux | grep -E "${psPattern}" | grep -v grep`, {
|
|
2340
2567
|
encoding: "utf-8",
|
|
2341
2568
|
stdio: ["pipe", "pipe", "pipe"]
|
|
2342
2569
|
}).trim();
|
|
@@ -2382,6 +2609,9 @@ function findOpenCodeProcesses() {
|
|
|
2382
2609
|
}
|
|
2383
2610
|
return instances;
|
|
2384
2611
|
}
|
|
2612
|
+
function findOpenCodeProcesses() {
|
|
2613
|
+
return findProcessesByPattern("opencode serve|opencode-serve", "opencode (serve|--port)");
|
|
2614
|
+
}
|
|
2385
2615
|
async function scanPortsForOpenCode() {
|
|
2386
2616
|
const instances = [];
|
|
2387
2617
|
const checks = OPENCODE_PORT_RANGE.map(async (port) => {
|
|
@@ -2428,7 +2658,7 @@ async function findHealthyOpenCodeInstances() {
|
|
|
2428
2658
|
}
|
|
2429
2659
|
async function startOpenCode(port, options = {}) {
|
|
2430
2660
|
let command = "opencode";
|
|
2431
|
-
const printLogs = options.inheritStdio ? ["--print-logs"] : [];
|
|
2661
|
+
const printLogs = options.inheritStdio ? ["--print-logs", "--log-level", resolveOpenCodeLogLevel(process.env)] : [];
|
|
2432
2662
|
let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
|
|
2433
2663
|
try {
|
|
2434
2664
|
execSync("which opencode", { stdio: "ignore" });
|
|
@@ -2485,6 +2715,19 @@ function isOpenCodeInstalled() {
|
|
|
2485
2715
|
return false;
|
|
2486
2716
|
}
|
|
2487
2717
|
}
|
|
2718
|
+
function isOpenCode2Installed() {
|
|
2719
|
+
try {
|
|
2720
|
+
const platform = process.platform;
|
|
2721
|
+
if (platform === "win32") {
|
|
2722
|
+
execSync2("where opencode2", { stdio: "ignore" });
|
|
2723
|
+
} else {
|
|
2724
|
+
execSync2("which opencode2", { stdio: "ignore" });
|
|
2725
|
+
}
|
|
2726
|
+
return true;
|
|
2727
|
+
} catch {
|
|
2728
|
+
return false;
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2488
2731
|
async function promptOpenCodeInstall(interactive) {
|
|
2489
2732
|
if (!interactive) {
|
|
2490
2733
|
console.log(
|
|
@@ -2494,7 +2737,11 @@ async function promptOpenCodeInstall(interactive) {
|
|
|
2494
2737
|
install_url: OPENCODE_INSTALL_URL,
|
|
2495
2738
|
install_commands: {
|
|
2496
2739
|
npm: "npm install -g opencode-ai",
|
|
2497
|
-
curl: "curl -fsSL https://opencode.ai/install.sh | sh"
|
|
2740
|
+
curl: "curl -fsSL https://opencode.ai/install.sh | sh",
|
|
2741
|
+
v2: {
|
|
2742
|
+
npm: "npm install -g @opencode-ai/cli@beta",
|
|
2743
|
+
curl: "curl -fsSL https://opencode.ai/v2/install | bash"
|
|
2744
|
+
}
|
|
2498
2745
|
}
|
|
2499
2746
|
})
|
|
2500
2747
|
);
|
|
@@ -2978,6 +3225,44 @@ function findLastAssistantReplyFor(messages, userMessageId) {
|
|
|
2978
3225
|
}
|
|
2979
3226
|
return lastOk ?? last;
|
|
2980
3227
|
}
|
|
3228
|
+
function collectSubagentSessions(messages, userMessageId) {
|
|
3229
|
+
if (!messages || messages.length === 0) return [];
|
|
3230
|
+
const byParent = messages.filter(
|
|
3231
|
+
(message) => roleOf(message) === "assistant" && parentIdOf(message) === userMessageId
|
|
3232
|
+
);
|
|
3233
|
+
const assistants = byParent.length > 0 ? byParent : [];
|
|
3234
|
+
if (assistants.length === 0) {
|
|
3235
|
+
const userIndex = messages.findIndex((message) => idOf(message) === userMessageId);
|
|
3236
|
+
if (userIndex === -1) return [];
|
|
3237
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
3238
|
+
const message = messages[i];
|
|
3239
|
+
if (roleOf(message) === "user") break;
|
|
3240
|
+
if (roleOf(message) === "assistant") assistants.push(message);
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
const refs = [];
|
|
3244
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3245
|
+
for (const message of assistants) {
|
|
3246
|
+
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
3247
|
+
for (const part of parts) {
|
|
3248
|
+
if (!part || typeof part !== "object" || part.type !== "tool" || part.tool !== "task")
|
|
3249
|
+
continue;
|
|
3250
|
+
const state = part.state;
|
|
3251
|
+
if (!state || typeof state !== "object") continue;
|
|
3252
|
+
const metadata = state.metadata;
|
|
3253
|
+
if (!metadata || typeof metadata !== "object") continue;
|
|
3254
|
+
const sessionId = metadata.sessionId;
|
|
3255
|
+
if (typeof sessionId !== "string" || sessionId.length === 0 || seen.has(sessionId)) continue;
|
|
3256
|
+
seen.add(sessionId);
|
|
3257
|
+
const start = state.time?.start;
|
|
3258
|
+
refs.push({
|
|
3259
|
+
sessionId,
|
|
3260
|
+
startedAtMs: typeof start === "number" && Number.isFinite(start) ? start : null
|
|
3261
|
+
});
|
|
3262
|
+
}
|
|
3263
|
+
}
|
|
3264
|
+
return refs;
|
|
3265
|
+
}
|
|
2981
3266
|
function messageUsage(messages, userMessageId) {
|
|
2982
3267
|
if (!messages || messages.length === 0) return null;
|
|
2983
3268
|
const byParentAll = messages.filter(
|
|
@@ -3106,8 +3391,7 @@ function isAbortedTerminalReply(messages, userMessageId) {
|
|
|
3106
3391
|
}
|
|
3107
3392
|
return false;
|
|
3108
3393
|
}
|
|
3109
|
-
function
|
|
3110
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
3394
|
+
function classifyReplyAuthError(reply) {
|
|
3111
3395
|
const error2 = errorOf(reply);
|
|
3112
3396
|
if (error2 == null || typeof error2 !== "object") return null;
|
|
3113
3397
|
const e = error2;
|
|
@@ -3132,6 +3416,32 @@ function messageFailure(messages, userMessageId) {
|
|
|
3132
3416
|
}
|
|
3133
3417
|
return null;
|
|
3134
3418
|
}
|
|
3419
|
+
function messageFailure(messages, userMessageId) {
|
|
3420
|
+
return classifyReplyAuthError(findLastAssistantReplyFor(messages, userMessageId));
|
|
3421
|
+
}
|
|
3422
|
+
function findLatestSubagentAuthOutcome(messages, sinceMs) {
|
|
3423
|
+
if (!messages || messages.length === 0) return null;
|
|
3424
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
3425
|
+
const message = messages[i];
|
|
3426
|
+
if (roleOf(message) !== "assistant") continue;
|
|
3427
|
+
const created = createdOf(message);
|
|
3428
|
+
if (sinceMs !== null && typeof created === "number" && created < sinceMs) continue;
|
|
3429
|
+
const failure = classifyReplyAuthError(message);
|
|
3430
|
+
if (failure) {
|
|
3431
|
+
if (!failure.providerId) return null;
|
|
3432
|
+
return { providerId: failure.providerId, outcome: "failed", failure };
|
|
3433
|
+
}
|
|
3434
|
+
const providerId = message.info?.providerID;
|
|
3435
|
+
if (errorOf(message) == null && typeof providerId === "string" && providerId.length > 0) {
|
|
3436
|
+
return { providerId, outcome: "succeeded" };
|
|
3437
|
+
}
|
|
3438
|
+
return null;
|
|
3439
|
+
}
|
|
3440
|
+
return null;
|
|
3441
|
+
}
|
|
3442
|
+
function findSubagentAuthOutcome(messages, sinceMs) {
|
|
3443
|
+
return findLatestSubagentAuthOutcome(messages, sinceMs);
|
|
3444
|
+
}
|
|
3135
3445
|
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
3136
3446
|
if (classified != null) return classified;
|
|
3137
3447
|
if (hasConfiguredProvider !== false) return null;
|
|
@@ -3285,11 +3595,11 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
|
3285
3595
|
}
|
|
3286
3596
|
|
|
3287
3597
|
// src/lib/opencode/session-db-size.ts
|
|
3288
|
-
import { statSync as statSync3 } from "fs";
|
|
3289
|
-
import { join as
|
|
3598
|
+
import { statSync as statSync3 } from "node:fs";
|
|
3599
|
+
import { join as join4 } from "node:path";
|
|
3290
3600
|
var LARGE_DB_THRESHOLD_BYTES = 268435456;
|
|
3291
3601
|
function statSessionDbBytes(homeDir) {
|
|
3292
|
-
const dbPath =
|
|
3602
|
+
const dbPath = join4(homeDir, ".local", "share", "opencode", "opencode.db");
|
|
3293
3603
|
try {
|
|
3294
3604
|
return statSync3(dbPath).size;
|
|
3295
3605
|
} catch (err) {
|
|
@@ -3316,12 +3626,99 @@ function buildSessionStoreSizeWarning(input) {
|
|
|
3316
3626
|
return null;
|
|
3317
3627
|
}
|
|
3318
3628
|
|
|
3629
|
+
// src/lib/opencode/log-tail.ts
|
|
3630
|
+
import { statSync as statSync4 } from "node:fs";
|
|
3631
|
+
import { homedir as homedir3 } from "node:os";
|
|
3632
|
+
import { join as join5 } from "node:path";
|
|
3633
|
+
import { open as open2, stat } from "node:fs/promises";
|
|
3634
|
+
var DEFAULT_POLL_INTERVAL_MS = 1e3;
|
|
3635
|
+
function resolveOpenCodeLogPath(homeDir = homedir3(), env = process.env) {
|
|
3636
|
+
const dataDir = env.XDG_DATA_HOME || join5(homeDir, ".local", "share");
|
|
3637
|
+
return join5(dataDir, "opencode", "log", "opencode.log");
|
|
3638
|
+
}
|
|
3639
|
+
function isEnoent(error2) {
|
|
3640
|
+
return error2?.code === "ENOENT";
|
|
3641
|
+
}
|
|
3642
|
+
function reportFailure(operation, logPath, error2) {
|
|
3643
|
+
console.error(
|
|
3644
|
+
`[opencode-log-tail] ${operation} failed for ${logPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
3645
|
+
);
|
|
3646
|
+
}
|
|
3647
|
+
function tailOpenCodeLogFile(logPath, onChunk, opts = {}) {
|
|
3648
|
+
const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
3649
|
+
let offset = 0;
|
|
3650
|
+
let inode = null;
|
|
3651
|
+
let baselineReady = true;
|
|
3652
|
+
try {
|
|
3653
|
+
const initial = statSync4(logPath);
|
|
3654
|
+
offset = initial.size;
|
|
3655
|
+
inode = initial.ino;
|
|
3656
|
+
} catch (error2) {
|
|
3657
|
+
if (!isEnoent(error2)) {
|
|
3658
|
+
reportFailure("initial stat", logPath, error2);
|
|
3659
|
+
baselineReady = false;
|
|
3660
|
+
}
|
|
3661
|
+
}
|
|
3662
|
+
let polling = false;
|
|
3663
|
+
let stopped = false;
|
|
3664
|
+
const poll = async () => {
|
|
3665
|
+
if (polling || stopped) return;
|
|
3666
|
+
polling = true;
|
|
3667
|
+
try {
|
|
3668
|
+
let current;
|
|
3669
|
+
try {
|
|
3670
|
+
current = await stat(logPath);
|
|
3671
|
+
} catch (error2) {
|
|
3672
|
+
if (!isEnoent(error2)) reportFailure("stat", logPath, error2);
|
|
3673
|
+
return;
|
|
3674
|
+
}
|
|
3675
|
+
if (!baselineReady) {
|
|
3676
|
+
offset = current.size;
|
|
3677
|
+
inode = current.ino;
|
|
3678
|
+
baselineReady = true;
|
|
3679
|
+
return;
|
|
3680
|
+
}
|
|
3681
|
+
if (inode !== null && current.ino !== inode || current.size < offset) {
|
|
3682
|
+
offset = 0;
|
|
3683
|
+
}
|
|
3684
|
+
inode = current.ino;
|
|
3685
|
+
if (current.size === offset) return;
|
|
3686
|
+
const length = current.size - offset;
|
|
3687
|
+
const fh = await open2(logPath, "r");
|
|
3688
|
+
try {
|
|
3689
|
+
const buf = Buffer.alloc(length);
|
|
3690
|
+
const { bytesRead } = await fh.read(buf, 0, length, offset);
|
|
3691
|
+
offset += bytesRead;
|
|
3692
|
+
if (bytesRead > 0) onChunk(buf.subarray(0, bytesRead));
|
|
3693
|
+
} finally {
|
|
3694
|
+
await fh.close();
|
|
3695
|
+
}
|
|
3696
|
+
} catch (error2) {
|
|
3697
|
+
if (!isEnoent(error2)) reportFailure("poll", logPath, error2);
|
|
3698
|
+
} finally {
|
|
3699
|
+
polling = false;
|
|
3700
|
+
}
|
|
3701
|
+
};
|
|
3702
|
+
const interval = setInterval(() => void poll(), pollIntervalMs);
|
|
3703
|
+
void poll();
|
|
3704
|
+
return {
|
|
3705
|
+
stop: () => {
|
|
3706
|
+
stopped = true;
|
|
3707
|
+
clearInterval(interval);
|
|
3708
|
+
}
|
|
3709
|
+
};
|
|
3710
|
+
}
|
|
3711
|
+
|
|
3319
3712
|
// src/lib/opencode/session-db-reclaim.ts
|
|
3320
|
-
import { statSync as
|
|
3321
|
-
import { dirname as
|
|
3713
|
+
import { statSync as statSync5, statfsSync } from "node:fs";
|
|
3714
|
+
import { dirname as dirname4 } from "node:path";
|
|
3715
|
+
function errorMessage(error2) {
|
|
3716
|
+
if (!(error2 instanceof Error)) return String(error2);
|
|
3717
|
+
return error2.cause instanceof Error ? error2.cause.message : error2.message;
|
|
3718
|
+
}
|
|
3322
3719
|
function insufficientSpaceReason(dbPath, requiredBytes) {
|
|
3323
3720
|
try {
|
|
3324
|
-
const fsStats = statfsSync(
|
|
3721
|
+
const fsStats = statfsSync(dirname4(dbPath));
|
|
3325
3722
|
const availableBytes = fsStats.bavail * fsStats.bsize;
|
|
3326
3723
|
if (availableBytes < requiredBytes) {
|
|
3327
3724
|
return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
|
|
@@ -3344,17 +3741,17 @@ async function probeReclaimAvailability(input) {
|
|
|
3344
3741
|
const { dbPath, requiredBytes } = input;
|
|
3345
3742
|
let sqlite;
|
|
3346
3743
|
try {
|
|
3347
|
-
sqlite = await import("sqlite");
|
|
3744
|
+
sqlite = await import("node:sqlite");
|
|
3348
3745
|
} catch (err) {
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
return "sqlite-unavailable";
|
|
3746
|
+
const detail = `Node ${process.version}: ${errorMessage(err)}`;
|
|
3747
|
+
console.warn(`[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ` + detail);
|
|
3748
|
+
return { reason: "sqlite-unavailable", detail };
|
|
3353
3749
|
}
|
|
3354
3750
|
let autoVacuum = null;
|
|
3355
3751
|
try {
|
|
3356
3752
|
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
|
|
3357
3753
|
try {
|
|
3754
|
+
db.exec("PRAGMA busy_timeout=5000");
|
|
3358
3755
|
autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
|
|
3359
3756
|
} finally {
|
|
3360
3757
|
db.close();
|
|
@@ -3365,23 +3762,25 @@ async function probeReclaimAvailability(input) {
|
|
|
3365
3762
|
);
|
|
3366
3763
|
}
|
|
3367
3764
|
if (autoVacuum !== 0) return null;
|
|
3368
|
-
return insufficientSpaceReason(dbPath, requiredBytes) !== null ? "insufficient-disk-space" : null;
|
|
3765
|
+
return insufficientSpaceReason(dbPath, requiredBytes) !== null ? { reason: "insufficient-disk-space" } : null;
|
|
3369
3766
|
}
|
|
3370
3767
|
async function reclaimSessionDbSpace(input) {
|
|
3371
3768
|
const { dbPath, maxPages, allowFullVacuum = true } = input;
|
|
3372
3769
|
let sqlite;
|
|
3373
3770
|
try {
|
|
3374
|
-
sqlite = await import("sqlite");
|
|
3771
|
+
sqlite = await import("node:sqlite");
|
|
3375
3772
|
} catch (err) {
|
|
3773
|
+
const detail = `Node ${process.version}: ${errorMessage(err)}`;
|
|
3376
3774
|
console.warn(
|
|
3377
|
-
`[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${
|
|
3775
|
+
`[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${detail}`
|
|
3378
3776
|
);
|
|
3379
|
-
return { ok: false, skipped: "sqlite-unavailable" };
|
|
3777
|
+
return { ok: false, skipped: "sqlite-unavailable", detail };
|
|
3380
3778
|
}
|
|
3381
3779
|
const { DatabaseSync } = sqlite;
|
|
3382
3780
|
let db;
|
|
3383
3781
|
try {
|
|
3384
3782
|
db = new DatabaseSync(dbPath);
|
|
3783
|
+
db.exec("PRAGMA busy_timeout=5000");
|
|
3385
3784
|
const autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
|
|
3386
3785
|
if (autoVacuum === 0) {
|
|
3387
3786
|
if (!allowFullVacuum) {
|
|
@@ -3390,7 +3789,7 @@ async function reclaimSessionDbSpace(input) {
|
|
|
3390
3789
|
);
|
|
3391
3790
|
return { ok: false, skipped: "full-vacuum-blocked" };
|
|
3392
3791
|
}
|
|
3393
|
-
const fileBytesForGuard =
|
|
3792
|
+
const fileBytesForGuard = statSync5(dbPath).size;
|
|
3394
3793
|
const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
|
|
3395
3794
|
if (skipReason !== null) {
|
|
3396
3795
|
console.warn(
|
|
@@ -3418,10 +3817,12 @@ async function reclaimSessionDbSpace(input) {
|
|
|
3418
3817
|
);
|
|
3419
3818
|
return { ok: false, skipped: "auto-vacuum-not-applicable" };
|
|
3420
3819
|
} catch (err) {
|
|
3421
|
-
console.error(
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3820
|
+
console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage(err));
|
|
3821
|
+
return {
|
|
3822
|
+
ok: false,
|
|
3823
|
+
skipped: "reclaim-error",
|
|
3824
|
+
detail: errorMessage(err)
|
|
3825
|
+
};
|
|
3425
3826
|
} finally {
|
|
3426
3827
|
db?.close();
|
|
3427
3828
|
}
|
|
@@ -3462,7 +3863,6 @@ var StreamForwarder = class {
|
|
|
3462
3863
|
handleFrame(frame) {
|
|
3463
3864
|
switch (frame.type) {
|
|
3464
3865
|
case "open":
|
|
3465
|
-
this.callbacks.onOpen?.(frame.sid, frame.method, frame.path);
|
|
3466
3866
|
void this.handleOpen(frame);
|
|
3467
3867
|
break;
|
|
3468
3868
|
case "req_data":
|
|
@@ -3498,12 +3898,21 @@ var StreamForwarder = class {
|
|
|
3498
3898
|
const { sid, method, path, headers, has_body } = frame;
|
|
3499
3899
|
const correlationId = headers?.[CORRELATION_ID_HEADER];
|
|
3500
3900
|
const startedAt = Date.now();
|
|
3901
|
+
if (path !== TUNNEL_DRAIN_PING_PATH && path !== TUNNEL_USAGE_REARM_PING_PATH) {
|
|
3902
|
+
this.callbacks.onOpen?.(sid, method, path);
|
|
3903
|
+
}
|
|
3501
3904
|
if (path === TUNNEL_DRAIN_PING_PATH) {
|
|
3502
3905
|
this.callbacks.onDrainPing?.();
|
|
3503
3906
|
this.send({ type: "head", sid, status: 204, headers: {} });
|
|
3504
3907
|
this.send({ type: "res_end", sid });
|
|
3505
3908
|
return;
|
|
3506
3909
|
}
|
|
3910
|
+
if (path === TUNNEL_USAGE_REARM_PING_PATH) {
|
|
3911
|
+
this.callbacks.onUsageRearmPing?.();
|
|
3912
|
+
this.send({ type: "head", sid, status: 204, headers: {} });
|
|
3913
|
+
this.send({ type: "res_end", sid });
|
|
3914
|
+
return;
|
|
3915
|
+
}
|
|
3507
3916
|
if (process.env.DEBUG) {
|
|
3508
3917
|
log("debug", "agent_request", {
|
|
3509
3918
|
correlation_id: correlationId,
|
|
@@ -3648,7 +4057,8 @@ function connectTunnel(options) {
|
|
|
3648
4057
|
onResponse,
|
|
3649
4058
|
onInfo,
|
|
3650
4059
|
onWarning,
|
|
3651
|
-
onDrainPing
|
|
4060
|
+
onDrainPing,
|
|
4061
|
+
onUsageRearmPing
|
|
3652
4062
|
} = options;
|
|
3653
4063
|
const tunnelUrl = getTunnelUrlConfig();
|
|
3654
4064
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
@@ -3660,7 +4070,8 @@ function connectTunnel(options) {
|
|
|
3660
4070
|
});
|
|
3661
4071
|
const forwarder = new StreamForwarder(ws, port, {
|
|
3662
4072
|
onHead: () => onResponse?.(),
|
|
3663
|
-
onDrainPing: () => onDrainPing?.()
|
|
4073
|
+
onDrainPing: () => onDrainPing?.(),
|
|
4074
|
+
onUsageRearmPing: () => onUsageRearmPing?.()
|
|
3664
4075
|
});
|
|
3665
4076
|
const connectionTimeout = setTimeout(() => {
|
|
3666
4077
|
ws.close();
|
|
@@ -3703,8 +4114,8 @@ function connectTunnel(options) {
|
|
|
3703
4114
|
try {
|
|
3704
4115
|
message = JSON.parse(data.toString());
|
|
3705
4116
|
} catch (error2) {
|
|
3706
|
-
const
|
|
3707
|
-
onError?.(`Failed to handle message: ${
|
|
4117
|
+
const errorMessage3 = error2 instanceof Error ? error2.message : "Unknown error";
|
|
4118
|
+
onError?.(`Failed to handle message: ${errorMessage3}`);
|
|
3708
4119
|
return;
|
|
3709
4120
|
}
|
|
3710
4121
|
if (isStreamFrame(message)) {
|
|
@@ -3821,6 +4232,7 @@ var RunnerConnection = class {
|
|
|
3821
4232
|
onError: (error2) => events.onError?.(error2),
|
|
3822
4233
|
onResponse: () => events.onResponse?.(),
|
|
3823
4234
|
onDrainPing: () => events.onDrainPing?.(),
|
|
4235
|
+
onUsageRearmPing: () => events.onUsageRearmPing?.(),
|
|
3824
4236
|
onInfo: (message) => events.onInfo?.(message),
|
|
3825
4237
|
onWarning: (message) => events.onWarning?.(message)
|
|
3826
4238
|
});
|
|
@@ -3847,10 +4259,10 @@ var RunnerConnection = class {
|
|
|
3847
4259
|
};
|
|
3848
4260
|
|
|
3849
4261
|
// src/lib/tunnel/ready-marker.ts
|
|
3850
|
-
import { writeFileSync as
|
|
4262
|
+
import { writeFileSync as writeFileSync3 } from "node:fs";
|
|
3851
4263
|
function writeTunnelReadyMarker(path, agentId) {
|
|
3852
4264
|
try {
|
|
3853
|
-
|
|
4265
|
+
writeFileSync3(path, `${agentId}
|
|
3854
4266
|
`);
|
|
3855
4267
|
return { ok: true };
|
|
3856
4268
|
} catch (error2) {
|
|
@@ -3859,7 +4271,7 @@ function writeTunnelReadyMarker(path, agentId) {
|
|
|
3859
4271
|
}
|
|
3860
4272
|
|
|
3861
4273
|
// src/lib/replication.ts
|
|
3862
|
-
import { spawn as spawn4 } from "child_process";
|
|
4274
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
3863
4275
|
function startSessionDbReplication(configPath) {
|
|
3864
4276
|
return spawn4("litestream", ["replicate", "-config", configPath], {
|
|
3865
4277
|
stdio: "inherit"
|
|
@@ -3875,7 +4287,7 @@ async function stopSessionDbReplication(child, timeoutMs) {
|
|
|
3875
4287
|
}
|
|
3876
4288
|
|
|
3877
4289
|
// src/lib/process-liveness.ts
|
|
3878
|
-
import { readFileSync as
|
|
4290
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
3879
4291
|
function isProcessAlive(pid) {
|
|
3880
4292
|
try {
|
|
3881
4293
|
process.kill(pid, 0);
|
|
@@ -3890,7 +4302,7 @@ function isProcessAlive(pid) {
|
|
|
3890
4302
|
}
|
|
3891
4303
|
if (process.platform !== "linux") return true;
|
|
3892
4304
|
try {
|
|
3893
|
-
const status2 =
|
|
4305
|
+
const status2 = readFileSync4(`/proc/${pid}/status`, "utf8");
|
|
3894
4306
|
return !/^State:\s+Z(?:\s|$)/m.test(status2);
|
|
3895
4307
|
} catch (error2) {
|
|
3896
4308
|
console.error(
|
|
@@ -3901,9 +4313,9 @@ function isProcessAlive(pid) {
|
|
|
3901
4313
|
}
|
|
3902
4314
|
|
|
3903
4315
|
// src/lib/openai-usage.ts
|
|
3904
|
-
import { readFileSync as
|
|
3905
|
-
import { homedir as
|
|
3906
|
-
import { join as
|
|
4316
|
+
import { readFileSync as readFileSync5 } from "node:fs";
|
|
4317
|
+
import { homedir as homedir4 } from "node:os";
|
|
4318
|
+
import { join as join6 } from "node:path";
|
|
3907
4319
|
var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
3908
4320
|
var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
|
|
3909
4321
|
var OpenAiUsageError = class extends Error {
|
|
@@ -3917,7 +4329,7 @@ function isLocalCredentialProblem2(err) {
|
|
|
3917
4329
|
}
|
|
3918
4330
|
function readOpenCodeChatGptCredentials() {
|
|
3919
4331
|
try {
|
|
3920
|
-
const raw =
|
|
4332
|
+
const raw = readFileSync5(join6(homedir4(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
|
|
3921
4333
|
let parsed;
|
|
3922
4334
|
try {
|
|
3923
4335
|
parsed = JSON.parse(raw);
|
|
@@ -3939,6 +4351,23 @@ function readOpenCodeChatGptCredentials() {
|
|
|
3939
4351
|
return null;
|
|
3940
4352
|
}
|
|
3941
4353
|
}
|
|
4354
|
+
function parseChatGptIdentity(accessToken) {
|
|
4355
|
+
const segments = accessToken.split(".");
|
|
4356
|
+
if (segments.length !== 3) return null;
|
|
4357
|
+
let payload;
|
|
4358
|
+
try {
|
|
4359
|
+
const parsed = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8"));
|
|
4360
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
|
4361
|
+
payload = parsed;
|
|
4362
|
+
} catch {
|
|
4363
|
+
return null;
|
|
4364
|
+
}
|
|
4365
|
+
const profile = payload["https://api.openai.com/profile"];
|
|
4366
|
+
const auth = payload["https://api.openai.com/auth"];
|
|
4367
|
+
const ownerEmail = typeof profile?.email === "string" ? profile.email.trim() || null : null;
|
|
4368
|
+
const planType = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type.trim() || null : null;
|
|
4369
|
+
return ownerEmail === null && planType === null ? null : { ownerEmail, planType };
|
|
4370
|
+
}
|
|
3942
4371
|
function toWindow2(headers, name) {
|
|
3943
4372
|
const utilizationHeader = headers.get(`x-codex-${name}-used-percent`);
|
|
3944
4373
|
const windowMinutesHeader = headers.get(`x-codex-${name}-window-minutes`);
|
|
@@ -4014,6 +4443,7 @@ async function getOpenAiUsage(port) {
|
|
|
4014
4443
|
"credentials_expired"
|
|
4015
4444
|
);
|
|
4016
4445
|
}
|
|
4446
|
+
const subscription = parseChatGptIdentity(credentials2.accessToken);
|
|
4017
4447
|
const models = await resolveProbeModels(port);
|
|
4018
4448
|
if (models.length === 0) {
|
|
4019
4449
|
throw new OpenAiUsageError("No supported OpenAI probe model is available.", "no_probe_model");
|
|
@@ -4046,7 +4476,7 @@ async function getOpenAiUsage(port) {
|
|
|
4046
4476
|
"no_usable_window"
|
|
4047
4477
|
);
|
|
4048
4478
|
}
|
|
4049
|
-
return usage;
|
|
4479
|
+
return { ...usage, subscription };
|
|
4050
4480
|
}
|
|
4051
4481
|
if (res.status === 401) {
|
|
4052
4482
|
throw new OpenAiUsageError(
|
|
@@ -4161,8 +4591,8 @@ function resolveResourceUsageReportingEnabled(flagValue, env) {
|
|
|
4161
4591
|
}
|
|
4162
4592
|
|
|
4163
4593
|
// src/lib/resource-usage.ts
|
|
4164
|
-
import { cpus, totalmem, freemem } from "os";
|
|
4165
|
-
import { statfsSync as statfsSync2 } from "fs";
|
|
4594
|
+
import { cpus, totalmem, freemem } from "node:os";
|
|
4595
|
+
import { statfsSync as statfsSync2 } from "node:fs";
|
|
4166
4596
|
|
|
4167
4597
|
// src/lib/ecs-task-metadata.ts
|
|
4168
4598
|
var ECS_METADATA_TIMEOUT_MS = 2e3;
|
|
@@ -4247,58 +4677,97 @@ function readDisk(homeDir) {
|
|
|
4247
4677
|
};
|
|
4248
4678
|
}
|
|
4249
4679
|
}
|
|
4250
|
-
|
|
4251
|
-
|
|
4252
|
-
|
|
4680
|
+
var CPU_PEAK_WINDOW_MS = 6e4;
|
|
4681
|
+
var CPU_PEAK_WINDOW_SAMPLE_COUNT = 4;
|
|
4682
|
+
var CPU_PEAK_SAMPLE_INTERVAL_MS = CPU_PEAK_WINDOW_MS / CPU_PEAK_WINDOW_SAMPLE_COUNT;
|
|
4683
|
+
function createCpuPeakSampler() {
|
|
4684
|
+
const sampleHistory = new Array(CPU_PEAK_WINDOW_SAMPLE_COUNT);
|
|
4685
|
+
sampleHistory[0] = readCpuSample();
|
|
4686
|
+
let nextSampleIndex = 1;
|
|
4687
|
+
let sampleCount = 1;
|
|
4688
|
+
let peak = null;
|
|
4689
|
+
const timer = setInterval(() => {
|
|
4253
4690
|
const current = readCpuSample();
|
|
4254
|
-
const
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
const warnings = [];
|
|
4261
|
-
if (disk.warning) warnings.push(disk.warning);
|
|
4262
|
-
if (ecsWarning) warnings.push(ecsWarning);
|
|
4263
|
-
let cpuPercent = hostCpuPercent;
|
|
4264
|
-
let cpuCount = hostCpuCount;
|
|
4265
|
-
let memoryTotalBytes = totalmem();
|
|
4266
|
-
let memoryAvailableBytes = freemem();
|
|
4267
|
-
if (limits !== null) {
|
|
4268
|
-
cpuCount = limits.cpuCount;
|
|
4269
|
-
memoryTotalBytes = limits.memoryTotalBytes;
|
|
4270
|
-
memoryAvailableBytes = clamp(
|
|
4271
|
-
limits.memoryTotalBytes - (totalmem() - freemem()),
|
|
4272
|
-
0,
|
|
4273
|
-
limits.memoryTotalBytes
|
|
4274
|
-
);
|
|
4275
|
-
cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
|
|
4691
|
+
const sampleFromWindowAgo = sampleCount === CPU_PEAK_WINDOW_SAMPLE_COUNT ? sampleHistory[nextSampleIndex] : void 0;
|
|
4692
|
+
if (sampleFromWindowAgo !== void 0) {
|
|
4693
|
+
const percentage = cpuPercentBetween(sampleFromWindowAgo, current);
|
|
4694
|
+
if (percentage !== null) {
|
|
4695
|
+
peak = peak === null ? percentage : Math.max(peak, percentage);
|
|
4696
|
+
}
|
|
4276
4697
|
}
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4698
|
+
sampleHistory[nextSampleIndex] = current;
|
|
4699
|
+
nextSampleIndex = (nextSampleIndex + 1) % CPU_PEAK_WINDOW_SAMPLE_COUNT;
|
|
4700
|
+
sampleCount = Math.min(sampleCount + 1, CPU_PEAK_WINDOW_SAMPLE_COUNT);
|
|
4701
|
+
}, CPU_PEAK_SAMPLE_INTERVAL_MS);
|
|
4702
|
+
return {
|
|
4703
|
+
takeAndReset: () => {
|
|
4704
|
+
const currentPeak = peak;
|
|
4705
|
+
peak = null;
|
|
4706
|
+
return currentPeak;
|
|
4707
|
+
},
|
|
4708
|
+
stop: () => clearInterval(timer)
|
|
4709
|
+
};
|
|
4710
|
+
}
|
|
4711
|
+
function createResourceUsageCollector(homeDir) {
|
|
4712
|
+
let previous = readCpuSample();
|
|
4713
|
+
const cpuPeakSampler = createCpuPeakSampler();
|
|
4714
|
+
return {
|
|
4715
|
+
collect: async () => {
|
|
4716
|
+
const current = readCpuSample();
|
|
4717
|
+
const hostCpuPercent = cpuPercentBetween(previous, current);
|
|
4718
|
+
const hostCpuPeakPercent = cpuPeakSampler.takeAndReset();
|
|
4719
|
+
const hostCpuCount = cpus().length;
|
|
4720
|
+
previous = current;
|
|
4721
|
+
const disk = readDisk(homeDir);
|
|
4722
|
+
const opencodeDbBytes = statSessionDbBytes(homeDir);
|
|
4723
|
+
const { limits, warning: ecsWarning } = await readEcsTaskLimits(process.env);
|
|
4724
|
+
const warnings = [];
|
|
4725
|
+
if (disk.warning) warnings.push(disk.warning);
|
|
4726
|
+
if (ecsWarning) warnings.push(ecsWarning);
|
|
4727
|
+
let cpuPercent = hostCpuPercent;
|
|
4728
|
+
let cpuPeakPercent = hostCpuPeakPercent;
|
|
4729
|
+
let cpuCount = hostCpuCount;
|
|
4730
|
+
let memoryTotalBytes = totalmem();
|
|
4731
|
+
let memoryAvailableBytes = freemem();
|
|
4732
|
+
if (limits !== null) {
|
|
4733
|
+
cpuCount = limits.cpuCount;
|
|
4734
|
+
memoryTotalBytes = limits.memoryTotalBytes;
|
|
4735
|
+
memoryAvailableBytes = clamp(
|
|
4736
|
+
limits.memoryTotalBytes - (totalmem() - freemem()),
|
|
4737
|
+
0,
|
|
4738
|
+
limits.memoryTotalBytes
|
|
4739
|
+
);
|
|
4740
|
+
cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
|
|
4741
|
+
cpuPeakPercent = hostCpuPeakPercent === null ? null : clamp(round2(hostCpuPeakPercent * hostCpuCount / limits.cpuCount), 0, 100);
|
|
4742
|
+
}
|
|
4743
|
+
return {
|
|
4744
|
+
usage: {
|
|
4745
|
+
cpuPercent,
|
|
4746
|
+
cpuPeakPercent,
|
|
4747
|
+
cpuCount,
|
|
4748
|
+
memoryTotalBytes,
|
|
4749
|
+
memoryAvailableBytes,
|
|
4750
|
+
diskTotalBytes: disk.totalBytes,
|
|
4751
|
+
diskFreeBytes: disk.freeBytes,
|
|
4752
|
+
opencodeDbBytes
|
|
4753
|
+
},
|
|
4754
|
+
warnings
|
|
4755
|
+
};
|
|
4756
|
+
},
|
|
4757
|
+
stop: cpuPeakSampler.stop
|
|
4289
4758
|
};
|
|
4290
4759
|
}
|
|
4291
4760
|
|
|
4292
4761
|
// src/lib/channels/driver.ts
|
|
4293
|
-
import { homedir as
|
|
4762
|
+
import { homedir as homedir5 } from "node:os";
|
|
4294
4763
|
|
|
4295
4764
|
// src/lib/runner-file-sync.ts
|
|
4296
|
-
import { join as
|
|
4765
|
+
import { join as join8 } from "node:path";
|
|
4297
4766
|
|
|
4298
4767
|
// src/lib/file-push.ts
|
|
4299
|
-
import { randomUUID } from "crypto";
|
|
4300
|
-
import { chmod, mkdir, open as
|
|
4301
|
-
import { basename, dirname as
|
|
4768
|
+
import { randomUUID } from "node:crypto";
|
|
4769
|
+
import { chmod, mkdir, open as open3, realpath, rename, unlink } from "node:fs/promises";
|
|
4770
|
+
import { basename, dirname as dirname5, isAbsolute, join as join7, relative, resolve as resolve2, sep } from "node:path";
|
|
4302
4771
|
var FILE_MODE = 384;
|
|
4303
4772
|
var DIRECTORY_MODE = 448;
|
|
4304
4773
|
async function writePushedFile(request) {
|
|
@@ -4329,9 +4798,9 @@ async function writePushedFile(request) {
|
|
|
4329
4798
|
}
|
|
4330
4799
|
try {
|
|
4331
4800
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
4332
|
-
|
|
4801
|
+
dirname5(candidate)
|
|
4333
4802
|
);
|
|
4334
|
-
const realTarget =
|
|
4803
|
+
const realTarget = join7(existingAncestor, ...missingSegments, basename(candidate));
|
|
4335
4804
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
4336
4805
|
if (allowedDirectory === null) {
|
|
4337
4806
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -4341,8 +4810,8 @@ async function writePushedFile(request) {
|
|
|
4341
4810
|
}
|
|
4342
4811
|
if (missingSegments.length > 0) {
|
|
4343
4812
|
await createMissingDirectories(existingAncestor, missingSegments);
|
|
4344
|
-
const realParent = await realpath(
|
|
4345
|
-
if (realParent !==
|
|
4813
|
+
const realParent = await realpath(dirname5(realTarget));
|
|
4814
|
+
if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
4346
4815
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
4347
4816
|
path: realTarget,
|
|
4348
4817
|
bytes,
|
|
@@ -4367,7 +4836,7 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
4367
4836
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
4368
4837
|
return null;
|
|
4369
4838
|
}
|
|
4370
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
4839
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
4371
4840
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
4372
4841
|
return null;
|
|
4373
4842
|
}
|
|
@@ -4385,7 +4854,7 @@ async function resolveNearestExistingAncestor(directory) {
|
|
|
4385
4854
|
try {
|
|
4386
4855
|
return { existingAncestor: await realpath(current), missingSegments };
|
|
4387
4856
|
} catch (err) {
|
|
4388
|
-
const parent =
|
|
4857
|
+
const parent = dirname5(current);
|
|
4389
4858
|
if (err.code !== "ENOENT" || parent === current) {
|
|
4390
4859
|
throw err;
|
|
4391
4860
|
}
|
|
@@ -4440,16 +4909,16 @@ function contains(realDirectory, realTarget) {
|
|
|
4440
4909
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
4441
4910
|
let current = existingAncestor;
|
|
4442
4911
|
for (const segment of missingSegments) {
|
|
4443
|
-
current =
|
|
4912
|
+
current = join7(current, segment);
|
|
4444
4913
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
4445
4914
|
await chmod(current, DIRECTORY_MODE);
|
|
4446
4915
|
}
|
|
4447
4916
|
}
|
|
4448
4917
|
async function writeAtomically(realTarget, content) {
|
|
4449
|
-
const temporaryPath =
|
|
4918
|
+
const temporaryPath = join7(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
4450
4919
|
let handle;
|
|
4451
4920
|
try {
|
|
4452
|
-
handle = await
|
|
4921
|
+
handle = await open3(temporaryPath, "wx", FILE_MODE);
|
|
4453
4922
|
await handle.writeFile(content);
|
|
4454
4923
|
await handle.chmod(FILE_MODE);
|
|
4455
4924
|
await handle.close();
|
|
@@ -4576,12 +5045,12 @@ var NOT_APPLIED = {
|
|
|
4576
5045
|
opencodeAuthApplied: false
|
|
4577
5046
|
};
|
|
4578
5047
|
function isClaudeCredentialPath(requestedPath, homeDir) {
|
|
4579
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
4580
|
-
return expanded ===
|
|
5048
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join8(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
5049
|
+
return expanded === join8(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
|
|
4581
5050
|
}
|
|
4582
5051
|
function isOpenCodeAuthPath(requestedPath, homeDir) {
|
|
4583
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
4584
|
-
return expanded ===
|
|
5052
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join8(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
5053
|
+
return expanded === join8(homeDir, ...OPENCODE_AUTH_SEGMENTS);
|
|
4585
5054
|
}
|
|
4586
5055
|
async function applyOne(options, file) {
|
|
4587
5056
|
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
@@ -5108,6 +5577,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5108
5577
|
* and stops opencode.
|
|
5109
5578
|
*/
|
|
5110
5579
|
stopped = false;
|
|
5580
|
+
recycleRequestedFlag = false;
|
|
5111
5581
|
constructor(config) {
|
|
5112
5582
|
this.agentId = config.agentId;
|
|
5113
5583
|
this.port = config.port;
|
|
@@ -5127,7 +5597,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5127
5597
|
this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
5128
5598
|
this.now = config.now ?? (() => Date.now());
|
|
5129
5599
|
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
5130
|
-
this.homeDir = config.homeDir ??
|
|
5600
|
+
this.homeDir = config.homeDir ?? homedir5();
|
|
5131
5601
|
this.maxActiveSessions = config.maxActiveSessions;
|
|
5132
5602
|
this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
|
|
5133
5603
|
this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
|
|
@@ -5213,6 +5683,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5213
5683
|
let dispatched = 0;
|
|
5214
5684
|
try {
|
|
5215
5685
|
const conversations = await this.getPendingConversations();
|
|
5686
|
+
if (this.recycleRequestedFlag) {
|
|
5687
|
+
this.stop();
|
|
5688
|
+
}
|
|
5216
5689
|
if (conversations.length > 0) {
|
|
5217
5690
|
const total = conversations.reduce((sum, c) => sum + (c.pending_message_count ?? 0), 0);
|
|
5218
5691
|
this.log({
|
|
@@ -5341,6 +5814,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5341
5814
|
stop() {
|
|
5342
5815
|
this.stopped = true;
|
|
5343
5816
|
}
|
|
5817
|
+
/**
|
|
5818
|
+
* The server clears this request when a new MicroVM identity is recorded, so a
|
|
5819
|
+
* same-VM tunnel reconnect does not consume it. This is a plain read rather
|
|
5820
|
+
* than a consume; `run.ts` guards the action once-only.
|
|
5821
|
+
*/
|
|
5822
|
+
get recycleRequested() {
|
|
5823
|
+
return this.recycleRequestedFlag;
|
|
5824
|
+
}
|
|
5344
5825
|
/**
|
|
5345
5826
|
* Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
|
|
5346
5827
|
* graceful shutdown, so a turn whose reply is ready — or completes within the
|
|
@@ -5478,7 +5959,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5478
5959
|
this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
|
|
5479
5960
|
break;
|
|
5480
5961
|
}
|
|
5481
|
-
const
|
|
5962
|
+
const errorMessage3 = err instanceof Error ? err.message : String(err);
|
|
5482
5963
|
this.sessions.delete(conv.id);
|
|
5483
5964
|
this.supersede(conv.id, sessionId);
|
|
5484
5965
|
this.log({
|
|
@@ -5487,7 +5968,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5487
5968
|
conversation_id: conv.id,
|
|
5488
5969
|
message_id: message.id
|
|
5489
5970
|
});
|
|
5490
|
-
await this.markFailed(conv.id, message.id, null,
|
|
5971
|
+
await this.markFailed(conv.id, message.id, null, errorMessage3).catch((markErr) => {
|
|
5491
5972
|
this.log({
|
|
5492
5973
|
level: "warn",
|
|
5493
5974
|
message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
@@ -5498,7 +5979,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5498
5979
|
});
|
|
5499
5980
|
this.log({
|
|
5500
5981
|
level: "error",
|
|
5501
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
5982
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage3}`,
|
|
5502
5983
|
conversation_id: conv.id,
|
|
5503
5984
|
message_id: message.id
|
|
5504
5985
|
});
|
|
@@ -5519,14 +6000,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5519
6000
|
this.unconfirmedDispatchFailures.delete(message.id);
|
|
5520
6001
|
this.sessions.delete(conv.id);
|
|
5521
6002
|
this.supersede(conv.id, sessionId);
|
|
5522
|
-
const
|
|
6003
|
+
const errorMessage3 = `OpenCode accepted this message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
|
|
5523
6004
|
this.log({
|
|
5524
6005
|
level: "error",
|
|
5525
|
-
message:
|
|
6006
|
+
message: errorMessage3,
|
|
5526
6007
|
conversation_id: conv.id,
|
|
5527
6008
|
message_id: message.id
|
|
5528
6009
|
});
|
|
5529
|
-
await this.markFailed(conv.id, message.id, null,
|
|
6010
|
+
await this.markFailed(conv.id, message.id, null, errorMessage3).catch((markErr) => {
|
|
5530
6011
|
this.log({
|
|
5531
6012
|
level: "warn",
|
|
5532
6013
|
message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
@@ -5860,6 +6341,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5860
6341
|
});
|
|
5861
6342
|
await this.markFailed(conv.id, message.id, sessionId, error2, usage, failure);
|
|
5862
6343
|
}
|
|
6344
|
+
if (ocId !== null) {
|
|
6345
|
+
await this.reportSubagentAuthFailures(conv.id, ocId, message.id, messages);
|
|
6346
|
+
}
|
|
5863
6347
|
} catch (err) {
|
|
5864
6348
|
if (err instanceof ChannelAuthError) throw err;
|
|
5865
6349
|
this.log({
|
|
@@ -6824,6 +7308,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6824
7308
|
return;
|
|
6825
7309
|
}
|
|
6826
7310
|
inFlight.done = true;
|
|
7311
|
+
await this.reportSubagentAuthFailures(
|
|
7312
|
+
watcher.conv.id,
|
|
7313
|
+
inFlight.opencodeMessageId,
|
|
7314
|
+
inFlight.evidentMessageId,
|
|
7315
|
+
messages
|
|
7316
|
+
);
|
|
6827
7317
|
}
|
|
6828
7318
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
6829
7319
|
return;
|
|
@@ -7066,6 +7556,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
7066
7556
|
return;
|
|
7067
7557
|
}
|
|
7068
7558
|
inFlight.done = true;
|
|
7559
|
+
await this.reportSubagentAuthFailures(
|
|
7560
|
+
watcher.conv.id,
|
|
7561
|
+
inFlight.opencodeMessageId,
|
|
7562
|
+
inFlight.evidentMessageId,
|
|
7563
|
+
messages
|
|
7564
|
+
);
|
|
7069
7565
|
}
|
|
7070
7566
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
7071
7567
|
}
|
|
@@ -7236,6 +7732,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
7236
7732
|
});
|
|
7237
7733
|
return;
|
|
7238
7734
|
}
|
|
7735
|
+
await this.reportSubagentAuthFailures(row.conversation_id, ocId ?? "", row.id, messages);
|
|
7239
7736
|
this.dontRedispatch.delete(row.id);
|
|
7240
7737
|
void this.postSignal(row.conversation_id, row.id, "readopt_failed");
|
|
7241
7738
|
return;
|
|
@@ -7397,6 +7894,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
7397
7894
|
});
|
|
7398
7895
|
return;
|
|
7399
7896
|
}
|
|
7897
|
+
if (ocId !== null) {
|
|
7898
|
+
await this.reportSubagentAuthFailures(row.conversation_id, ocId, row.id, messages);
|
|
7899
|
+
}
|
|
7400
7900
|
this.dontRedispatch.delete(row.id);
|
|
7401
7901
|
void this.postSignal(row.conversation_id, row.id, "readopt_done");
|
|
7402
7902
|
}
|
|
@@ -7490,14 +7990,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
7490
7990
|
this.unconfirmedDispatchFailures.delete(row.id);
|
|
7491
7991
|
this.sessions.delete(readoptConv.id);
|
|
7492
7992
|
this.supersede(readoptConv.id, sessionId);
|
|
7493
|
-
const
|
|
7993
|
+
const errorMessage3 = `OpenCode accepted this re-dispatched message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
|
|
7494
7994
|
this.log({
|
|
7495
7995
|
level: "error",
|
|
7496
|
-
message:
|
|
7996
|
+
message: errorMessage3,
|
|
7497
7997
|
conversation_id: row.conversation_id,
|
|
7498
7998
|
message_id: row.id
|
|
7499
7999
|
});
|
|
7500
|
-
await this.markFailed(row.conversation_id, row.id, null,
|
|
8000
|
+
await this.markFailed(row.conversation_id, row.id, null, errorMessage3).catch((markErr) => {
|
|
7501
8001
|
this.log({
|
|
7502
8002
|
level: "warn",
|
|
7503
8003
|
message: `markFailed PATCH for message ${row.id.slice(0, 8)} (conversation ${row.conversation_id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
@@ -8112,6 +8612,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
8112
8612
|
throw new Error(`Failed to get pending conversations: HTTP ${res.status}`);
|
|
8113
8613
|
}
|
|
8114
8614
|
const data = await res.json();
|
|
8615
|
+
this.recycleRequestedFlag = data.recycle_requested === true;
|
|
8115
8616
|
let conversations = data.conversations;
|
|
8116
8617
|
if (this.conversationFilter) {
|
|
8117
8618
|
conversations = conversations.filter((c) => c.id === this.conversationFilter);
|
|
@@ -8347,6 +8848,111 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
8347
8848
|
reply?.info?.modelID ?? null
|
|
8348
8849
|
);
|
|
8349
8850
|
}
|
|
8851
|
+
async recordSubagentModelAuthFailure(failure, conversationId, messageId) {
|
|
8852
|
+
const providerId = failure.providerId ?? "(unknown)";
|
|
8853
|
+
try {
|
|
8854
|
+
const res = await this.fetchImpl(
|
|
8855
|
+
`${this.apiUrl}/runners/${this.agentId}/model-auth-failures`,
|
|
8856
|
+
{
|
|
8857
|
+
method: "POST",
|
|
8858
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
8859
|
+
body: JSON.stringify({
|
|
8860
|
+
provider_id: failure.providerId,
|
|
8861
|
+
model_id: failure.modelId,
|
|
8862
|
+
reason: failure.reason
|
|
8863
|
+
})
|
|
8864
|
+
}
|
|
8865
|
+
);
|
|
8866
|
+
if (!res.ok) {
|
|
8867
|
+
this.log({
|
|
8868
|
+
level: "warn",
|
|
8869
|
+
message: `Sub-agent model-auth report for provider ${providerId} (${failure.reason}) returned HTTP ${res.status} (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)})`,
|
|
8870
|
+
conversation_id: conversationId,
|
|
8871
|
+
message_id: messageId
|
|
8872
|
+
});
|
|
8873
|
+
}
|
|
8874
|
+
} catch (err) {
|
|
8875
|
+
this.log({
|
|
8876
|
+
level: "warn",
|
|
8877
|
+
message: `Sub-agent model-auth report for provider ${providerId} (${failure.reason}) failed with status network-error (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)}): ${err instanceof Error ? err.message : String(err)}`,
|
|
8878
|
+
conversation_id: conversationId,
|
|
8879
|
+
message_id: messageId
|
|
8880
|
+
});
|
|
8881
|
+
}
|
|
8882
|
+
}
|
|
8883
|
+
async clearSubagentModelAuthFailure(providerId, conversationId, messageId) {
|
|
8884
|
+
try {
|
|
8885
|
+
const res = await this.fetchImpl(
|
|
8886
|
+
`${this.apiUrl}/runners/${this.agentId}/model-auth-failures/${encodeURIComponent(providerId)}`,
|
|
8887
|
+
{
|
|
8888
|
+
method: "DELETE",
|
|
8889
|
+
headers: { Authorization: this.getAuthHeader() }
|
|
8890
|
+
}
|
|
8891
|
+
);
|
|
8892
|
+
if (!res.ok) {
|
|
8893
|
+
this.log({
|
|
8894
|
+
level: "warn",
|
|
8895
|
+
message: `Sub-agent model-auth clear for provider ${providerId} returned HTTP ${res.status} (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)})`,
|
|
8896
|
+
conversation_id: conversationId,
|
|
8897
|
+
message_id: messageId
|
|
8898
|
+
});
|
|
8899
|
+
}
|
|
8900
|
+
} catch (err) {
|
|
8901
|
+
this.log({
|
|
8902
|
+
level: "warn",
|
|
8903
|
+
message: `Sub-agent model-auth clear for provider ${providerId} failed with status network-error (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)}): ${err instanceof Error ? err.message : String(err)}`,
|
|
8904
|
+
conversation_id: conversationId,
|
|
8905
|
+
message_id: messageId
|
|
8906
|
+
});
|
|
8907
|
+
}
|
|
8908
|
+
}
|
|
8909
|
+
async reportSubagentAuthFailures(conversationId, opencodeMessageId, evidentMessageId, messages) {
|
|
8910
|
+
const refs = collectSubagentSessions(messages, opencodeMessageId);
|
|
8911
|
+
if (refs.length === 0) return;
|
|
8912
|
+
const failedProviders = /* @__PURE__ */ new Map();
|
|
8913
|
+
const succeededProviders = /* @__PURE__ */ new Set();
|
|
8914
|
+
for (const ref of refs) {
|
|
8915
|
+
try {
|
|
8916
|
+
const childMessages = await getSessionMessages(this.port, ref.sessionId);
|
|
8917
|
+
if (childMessages === null) {
|
|
8918
|
+
this.log({
|
|
8919
|
+
level: "debug",
|
|
8920
|
+
message: `Could not read sub-agent session ${ref.sessionId} while checking credential failures \u2014 skipping it`,
|
|
8921
|
+
conversation_id: conversationId,
|
|
8922
|
+
message_id: evidentMessageId
|
|
8923
|
+
});
|
|
8924
|
+
continue;
|
|
8925
|
+
}
|
|
8926
|
+
const outcome = findSubagentAuthOutcome(childMessages, ref.startedAtMs);
|
|
8927
|
+
if (!outcome) continue;
|
|
8928
|
+
if (outcome.outcome === "failed") {
|
|
8929
|
+
failedProviders.set(outcome.providerId, outcome.failure);
|
|
8930
|
+
} else {
|
|
8931
|
+
succeededProviders.add(outcome.providerId);
|
|
8932
|
+
}
|
|
8933
|
+
} catch (err) {
|
|
8934
|
+
this.log({
|
|
8935
|
+
level: "warn",
|
|
8936
|
+
message: `Failed to inspect sub-agent session ${ref.sessionId} for credential failures (conversation ${conversationId.slice(0, 8)}, message ${evidentMessageId.slice(0, 8)}): ${err instanceof Error ? err.message : String(err)}`,
|
|
8937
|
+
conversation_id: conversationId,
|
|
8938
|
+
message_id: evidentMessageId
|
|
8939
|
+
});
|
|
8940
|
+
}
|
|
8941
|
+
}
|
|
8942
|
+
for (const [providerId, failure] of failedProviders) {
|
|
8943
|
+
this.log({
|
|
8944
|
+
level: "warn",
|
|
8945
|
+
message: `Sub-agent turn failed on provider ${providerId} (${failure.reason}) \u2014 recording credential evidence`,
|
|
8946
|
+
conversation_id: conversationId,
|
|
8947
|
+
message_id: evidentMessageId
|
|
8948
|
+
});
|
|
8949
|
+
await this.recordSubagentModelAuthFailure(failure, conversationId, evidentMessageId);
|
|
8950
|
+
}
|
|
8951
|
+
for (const providerId of succeededProviders) {
|
|
8952
|
+
if (failedProviders.has(providerId)) continue;
|
|
8953
|
+
await this.clearSubagentModelAuthFailure(providerId, conversationId, evidentMessageId);
|
|
8954
|
+
}
|
|
8955
|
+
}
|
|
8350
8956
|
/**
|
|
8351
8957
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
8352
8958
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -8500,6 +9106,13 @@ import chalk5 from "chalk";
|
|
|
8500
9106
|
import ora2 from "ora";
|
|
8501
9107
|
import { select as select2 } from "@inquirer/prompts";
|
|
8502
9108
|
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
9109
|
+
function checkNonInteractivePortConflict(port, isPortInUseFn) {
|
|
9110
|
+
if (isPortInUseFn(port)) {
|
|
9111
|
+
throw new Error(
|
|
9112
|
+
`Port ${port} is already in use by a non-OpenCode process. Free it or pass --port.`
|
|
9113
|
+
);
|
|
9114
|
+
}
|
|
9115
|
+
}
|
|
8503
9116
|
async function ensureOpenCodeRunning(ctx) {
|
|
8504
9117
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
8505
9118
|
if (healthCheck.healthy) {
|
|
@@ -8547,6 +9160,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
8547
9160
|
}
|
|
8548
9161
|
}
|
|
8549
9162
|
if (!ctx.interactive) {
|
|
9163
|
+
checkNonInteractivePortConflict(ctx.port, isPortInUse);
|
|
8550
9164
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
8551
9165
|
const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
|
|
8552
9166
|
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
@@ -8628,9 +9242,119 @@ Port ${port} is already in use.`));
|
|
|
8628
9242
|
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
8629
9243
|
}
|
|
8630
9244
|
|
|
9245
|
+
// src/commands/ensure-opencode-v2.ts
|
|
9246
|
+
import chalk6 from "chalk";
|
|
9247
|
+
import { select as select3 } from "@inquirer/prompts";
|
|
9248
|
+
async function probeOpenCode2WithoutPassword(port) {
|
|
9249
|
+
try {
|
|
9250
|
+
const response = await fetch(`http://127.0.0.1:${port}/global/health`, {
|
|
9251
|
+
signal: AbortSignal.timeout(2e3)
|
|
9252
|
+
});
|
|
9253
|
+
if (response.status === 401) {
|
|
9254
|
+
return { healthy: false, authFailed: true, error: "HTTP 401" };
|
|
9255
|
+
}
|
|
9256
|
+
if (!response.ok) {
|
|
9257
|
+
return { healthy: false, error: `HTTP ${response.status}` };
|
|
9258
|
+
}
|
|
9259
|
+
return { healthy: true };
|
|
9260
|
+
} catch (error2) {
|
|
9261
|
+
return {
|
|
9262
|
+
healthy: false,
|
|
9263
|
+
error: error2 instanceof Error ? error2.message : "Unknown error"
|
|
9264
|
+
};
|
|
9265
|
+
}
|
|
9266
|
+
}
|
|
9267
|
+
function unknownPasswordError(port) {
|
|
9268
|
+
return new Error(
|
|
9269
|
+
`OpenCode V2 (opencode2) is already running on port ${port} with a password this runner doesn't know. Free the port or pass --port.`
|
|
9270
|
+
);
|
|
9271
|
+
}
|
|
9272
|
+
function v2SessionSupportIncompleteError() {
|
|
9273
|
+
return new Error(
|
|
9274
|
+
"OpenCode V2 (opencode2) session support is incomplete \u2014 see https://github.com/sroze/evident/issues/2075. Not starting a new opencode2 process."
|
|
9275
|
+
);
|
|
9276
|
+
}
|
|
9277
|
+
async function ensureOpenCode2Running(ctx) {
|
|
9278
|
+
const initialHealth = await probeOpenCode2WithoutPassword(ctx.port);
|
|
9279
|
+
if (initialHealth.authFailed) {
|
|
9280
|
+
throw unknownPasswordError(ctx.port);
|
|
9281
|
+
}
|
|
9282
|
+
if (initialHealth.healthy) {
|
|
9283
|
+
return {
|
|
9284
|
+
port: ctx.port,
|
|
9285
|
+
process: null,
|
|
9286
|
+
version: null,
|
|
9287
|
+
notReadyReason: null,
|
|
9288
|
+
password: null
|
|
9289
|
+
};
|
|
9290
|
+
}
|
|
9291
|
+
if (!isOpenCode2Installed()) {
|
|
9292
|
+
throw new Error(
|
|
9293
|
+
"OpenCode V2 (opencode2) is not installed. Install it with: npm install -g @opencode-ai/cli@beta"
|
|
9294
|
+
);
|
|
9295
|
+
}
|
|
9296
|
+
let port = ctx.port;
|
|
9297
|
+
if (!ctx.interactive) {
|
|
9298
|
+
checkNonInteractivePortConflict(port, isPortInUse);
|
|
9299
|
+
} else if (isPortInUse(port)) {
|
|
9300
|
+
console.log(chalk6.yellow(`
|
|
9301
|
+
Port ${port} is already in use.`));
|
|
9302
|
+
const alternativePort = findAvailablePort(port + 1);
|
|
9303
|
+
if (alternativePort) {
|
|
9304
|
+
const useAlternative = await select3({
|
|
9305
|
+
message: `Use port ${alternativePort} instead?`,
|
|
9306
|
+
choices: [
|
|
9307
|
+
{ name: `Yes, use port ${alternativePort}`, value: "yes" },
|
|
9308
|
+
{ name: "No, I will free the port manually", value: "no" }
|
|
9309
|
+
]
|
|
9310
|
+
});
|
|
9311
|
+
if (useAlternative === "yes") {
|
|
9312
|
+
port = alternativePort;
|
|
9313
|
+
} else {
|
|
9314
|
+
throw new Error(`Port ${ctx.port} is in use`);
|
|
9315
|
+
}
|
|
9316
|
+
}
|
|
9317
|
+
}
|
|
9318
|
+
if (!ctx.interactive) {
|
|
9319
|
+
throw v2SessionSupportIncompleteError();
|
|
9320
|
+
}
|
|
9321
|
+
console.log(chalk6.yellow(`
|
|
9322
|
+
${v2SessionSupportIncompleteError().message}`));
|
|
9323
|
+
const action = await select3({
|
|
9324
|
+
message: "OpenCode V2 is not running. What would you like to do?",
|
|
9325
|
+
choices: [
|
|
9326
|
+
{
|
|
9327
|
+
name: "Show me the command",
|
|
9328
|
+
value: "manual",
|
|
9329
|
+
description: "Display the command to run manually"
|
|
9330
|
+
},
|
|
9331
|
+
{
|
|
9332
|
+
name: "Continue without OpenCode V2",
|
|
9333
|
+
value: "continue",
|
|
9334
|
+
description: "Requests will fail until OpenCode V2 starts"
|
|
9335
|
+
}
|
|
9336
|
+
]
|
|
9337
|
+
});
|
|
9338
|
+
if (action === "manual") {
|
|
9339
|
+
blank();
|
|
9340
|
+
console.log(chalk6.bold("Run this command in another terminal:"));
|
|
9341
|
+
blank();
|
|
9342
|
+
console.log(` ${chalk6.cyan(`opencode2 serve --port ${port}`)}`);
|
|
9343
|
+
blank();
|
|
9344
|
+
throw new Error("Please start OpenCode V2 manually");
|
|
9345
|
+
}
|
|
9346
|
+
return {
|
|
9347
|
+
port,
|
|
9348
|
+
process: null,
|
|
9349
|
+
version: null,
|
|
9350
|
+
notReadyReason: "you chose to continue without OpenCode V2",
|
|
9351
|
+
password: null
|
|
9352
|
+
};
|
|
9353
|
+
}
|
|
9354
|
+
|
|
8631
9355
|
// src/lib/runner-credentials.ts
|
|
8632
|
-
import { chmodSync as chmodSync2, writeFileSync as
|
|
8633
|
-
import { spawn as spawn5 } from "child_process";
|
|
9356
|
+
import { chmodSync as chmodSync2, writeFileSync as writeFileSync4 } from "node:fs";
|
|
9357
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
8634
9358
|
var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
|
|
8635
9359
|
var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
|
|
8636
9360
|
var GITHUB_PROBE_TIMEOUT_MS = 1e4;
|
|
@@ -8870,8 +9594,8 @@ async function configureGitHubAccess({ env, log: log3 }) {
|
|
|
8870
9594
|
}
|
|
8871
9595
|
try {
|
|
8872
9596
|
env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
|
|
8873
|
-
|
|
8874
|
-
|
|
9597
|
+
writeFileSync4(GIT_CONFIG_GLOBAL, "");
|
|
9598
|
+
writeFileSync4(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
|
|
8875
9599
|
chmodSync2(GIT_CREDENTIAL_HELPER, 448);
|
|
8876
9600
|
const config = [
|
|
8877
9601
|
["user.name", env.GIT_USER_NAME ?? "evident-bot"],
|
|
@@ -8902,11 +9626,11 @@ async function configureGitHubAccess({ env, log: log3 }) {
|
|
|
8902
9626
|
}
|
|
8903
9627
|
|
|
8904
9628
|
// src/lib/opencode/config-overlay.ts
|
|
8905
|
-
import { execFileSync as execFileSync2 } from "child_process";
|
|
8906
|
-
import { copyFileSync, existsSync as existsSync2, statSync as
|
|
8907
|
-
import { isAbsolute as isAbsolute2, join as
|
|
9629
|
+
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
9630
|
+
import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
|
|
9631
|
+
import { isAbsolute as isAbsolute2, join as join9, resolve as resolve3 } from "node:path";
|
|
8908
9632
|
function isFile(filePath) {
|
|
8909
|
-
return existsSync2(filePath) &&
|
|
9633
|
+
return existsSync2(filePath) && statSync6(filePath).isFile();
|
|
8910
9634
|
}
|
|
8911
9635
|
function applyRunnerOpenCodeConfig({
|
|
8912
9636
|
overlayPath,
|
|
@@ -8918,7 +9642,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
8918
9642
|
return;
|
|
8919
9643
|
}
|
|
8920
9644
|
const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
|
|
8921
|
-
const target = isFile(
|
|
9645
|
+
const target = isFile(join9(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
|
|
8922
9646
|
if (!isFile(source)) {
|
|
8923
9647
|
log3(
|
|
8924
9648
|
`RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
|
|
@@ -8926,7 +9650,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
8926
9650
|
);
|
|
8927
9651
|
return;
|
|
8928
9652
|
}
|
|
8929
|
-
copyFileSync(source,
|
|
9653
|
+
copyFileSync(source, join9(cwd, target));
|
|
8930
9654
|
try {
|
|
8931
9655
|
execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
|
|
8932
9656
|
stdio: "ignore"
|
|
@@ -8935,7 +9659,242 @@ function applyRunnerOpenCodeConfig({
|
|
|
8935
9659
|
const detail = error2 instanceof Error ? error2.message : String(error2);
|
|
8936
9660
|
log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
|
|
8937
9661
|
}
|
|
8938
|
-
log3(`Applied runner OpenCode config ${source} to ${
|
|
9662
|
+
log3(`Applied runner OpenCode config ${source} to ${join9(cwd, target)}`);
|
|
9663
|
+
}
|
|
9664
|
+
|
|
9665
|
+
// src/lib/credential-sync.ts
|
|
9666
|
+
import { renameSync, writeFileSync as writeFileSync5 } from "node:fs";
|
|
9667
|
+
var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
|
|
9668
|
+
var CREDENTIAL_FLUSH_DEADLINE_MS = 8e3;
|
|
9669
|
+
var CREDENTIAL_FLUSH_ABORT_GRACE_MS = 500;
|
|
9670
|
+
var DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS = 60;
|
|
9671
|
+
var STORES = ["claude", "opencode"];
|
|
9672
|
+
var MAX_FLUSH_PASSES = 2;
|
|
9673
|
+
function outcomesWith(outcome) {
|
|
9674
|
+
return { claude: outcome, opencode: outcome };
|
|
9675
|
+
}
|
|
9676
|
+
function errorMessage2(error2) {
|
|
9677
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
9678
|
+
}
|
|
9679
|
+
function waitForSettlement(promise, timeoutMs) {
|
|
9680
|
+
return new Promise((resolve4) => {
|
|
9681
|
+
let settled = false;
|
|
9682
|
+
const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
|
|
9683
|
+
const finish = (value) => {
|
|
9684
|
+
if (settled) return;
|
|
9685
|
+
settled = true;
|
|
9686
|
+
clearTimeout(timer);
|
|
9687
|
+
resolve4(value);
|
|
9688
|
+
};
|
|
9689
|
+
promise.then(
|
|
9690
|
+
() => finish(true),
|
|
9691
|
+
() => finish(true)
|
|
9692
|
+
);
|
|
9693
|
+
});
|
|
9694
|
+
}
|
|
9695
|
+
function writeMarker(markerPath, outcomes, log3) {
|
|
9696
|
+
const body = `${STORES.map((store) => `${store}=${outcomes[store]}`).join("\n")}
|
|
9697
|
+
`;
|
|
9698
|
+
const temporaryPath = `${markerPath}.tmp`;
|
|
9699
|
+
try {
|
|
9700
|
+
writeFileSync5(temporaryPath, body, { mode: 384 });
|
|
9701
|
+
renameSync(temporaryPath, markerPath);
|
|
9702
|
+
} catch (error2) {
|
|
9703
|
+
log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage2(error2)}`, "warn");
|
|
9704
|
+
}
|
|
9705
|
+
}
|
|
9706
|
+
function intervalSeconds(env, log3) {
|
|
9707
|
+
const raw = env.CREDS_SYNC_INTERVAL;
|
|
9708
|
+
if (raw === void 0 || /^[1-9][0-9]*$/.test(raw) && Number.isSafeInteger(Number(raw))) {
|
|
9709
|
+
return raw === void 0 ? DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS : Number(raw);
|
|
9710
|
+
}
|
|
9711
|
+
log3(
|
|
9712
|
+
`CREDENTIAL-SYNC-INTERVAL-INVALID: CREDS_SYNC_INTERVAL='${raw}' is not a positive integer; using ${DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS}s`,
|
|
9713
|
+
"warn"
|
|
9714
|
+
);
|
|
9715
|
+
return DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS;
|
|
9716
|
+
}
|
|
9717
|
+
async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
|
|
9718
|
+
const remainingMs = deadlineAt - Date.now();
|
|
9719
|
+
if (remainingMs <= 0) return { outcome: "timeout", orphaned: false };
|
|
9720
|
+
const controller = new AbortController();
|
|
9721
|
+
let result;
|
|
9722
|
+
let failed = false;
|
|
9723
|
+
const completion = Promise.resolve().then(
|
|
9724
|
+
() => synchroniserRunner(["sync-once", store], {
|
|
9725
|
+
timeoutMs: remainingMs,
|
|
9726
|
+
env,
|
|
9727
|
+
signal: controller.signal
|
|
9728
|
+
})
|
|
9729
|
+
).then(
|
|
9730
|
+
(value) => {
|
|
9731
|
+
result = value;
|
|
9732
|
+
},
|
|
9733
|
+
(error2) => {
|
|
9734
|
+
failed = true;
|
|
9735
|
+
log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage2(error2)}`, "warn");
|
|
9736
|
+
}
|
|
9737
|
+
);
|
|
9738
|
+
const abortTimer = setTimeout(() => controller.abort(), remainingMs);
|
|
9739
|
+
const settledBeforeDeadline = await waitForSettlement(completion, remainingMs);
|
|
9740
|
+
clearTimeout(abortTimer);
|
|
9741
|
+
if (!settledBeforeDeadline) {
|
|
9742
|
+
controller.abort();
|
|
9743
|
+
const settledAfterAbort = await waitForSettlement(completion, CREDENTIAL_FLUSH_ABORT_GRACE_MS);
|
|
9744
|
+
if (!settledAfterAbort) return { outcome: "timeout", orphaned: true };
|
|
9745
|
+
return { outcome: "timeout", orphaned: false };
|
|
9746
|
+
}
|
|
9747
|
+
if (failed || !result) return { outcome: "failed", orphaned: false };
|
|
9748
|
+
if (result.timedOut || Date.now() >= deadlineAt) {
|
|
9749
|
+
return { outcome: "timeout", orphaned: false };
|
|
9750
|
+
}
|
|
9751
|
+
return { outcome: result.code === 0 ? "ok" : "failed", orphaned: false };
|
|
9752
|
+
}
|
|
9753
|
+
function createCredentialSync({
|
|
9754
|
+
markerPath,
|
|
9755
|
+
env,
|
|
9756
|
+
log: log3,
|
|
9757
|
+
synchroniserRunner = runSynchroniser
|
|
9758
|
+
}) {
|
|
9759
|
+
const persistenceDisabled = !env.PERSISTENCE_BUCKET;
|
|
9760
|
+
let disabled = persistenceDisabled;
|
|
9761
|
+
let armed = false;
|
|
9762
|
+
let stopped = false;
|
|
9763
|
+
let timer;
|
|
9764
|
+
let inFlight;
|
|
9765
|
+
let activeTickAbort;
|
|
9766
|
+
let lastTickFailed;
|
|
9767
|
+
let flushPromise;
|
|
9768
|
+
const scheduleTick = (intervalMs, startTick2) => {
|
|
9769
|
+
if (stopped) return;
|
|
9770
|
+
timer = setTimeout(() => {
|
|
9771
|
+
timer = void 0;
|
|
9772
|
+
startTick2();
|
|
9773
|
+
}, intervalMs);
|
|
9774
|
+
};
|
|
9775
|
+
const startTick = (intervalMs) => {
|
|
9776
|
+
if (stopped) return;
|
|
9777
|
+
const controller = new AbortController();
|
|
9778
|
+
activeTickAbort = controller;
|
|
9779
|
+
const tick = (async () => {
|
|
9780
|
+
const outcomes = {
|
|
9781
|
+
claude: "failed",
|
|
9782
|
+
opencode: "failed"
|
|
9783
|
+
};
|
|
9784
|
+
for (const store of STORES) {
|
|
9785
|
+
if (controller.signal.aborted) break;
|
|
9786
|
+
try {
|
|
9787
|
+
const result = await synchroniserRunner(["sync-once", store], {
|
|
9788
|
+
timeoutMs: CREDENTIAL_SYNC_TICK_TIMEOUT_MS,
|
|
9789
|
+
env,
|
|
9790
|
+
signal: controller.signal
|
|
9791
|
+
});
|
|
9792
|
+
outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
|
|
9793
|
+
} catch (error2) {
|
|
9794
|
+
outcomes[store] = "failed";
|
|
9795
|
+
log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage2(error2)}`, "debug");
|
|
9796
|
+
}
|
|
9797
|
+
}
|
|
9798
|
+
const failed = STORES.some((store) => outcomes[store] === "failed");
|
|
9799
|
+
log3(
|
|
9800
|
+
`CREDENTIAL-SYNC-TICK: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
|
|
9801
|
+
"debug"
|
|
9802
|
+
);
|
|
9803
|
+
if (failed && lastTickFailed !== true) {
|
|
9804
|
+
log3(
|
|
9805
|
+
"CREDENTIAL-SYNC-FAILED: an interval credential sync failed; retrying on the next tick",
|
|
9806
|
+
"warn"
|
|
9807
|
+
);
|
|
9808
|
+
} else if (!failed && lastTickFailed === true) {
|
|
9809
|
+
log3("CREDENTIAL-SYNC-RECOVERED: interval credential sync succeeded again", "warn");
|
|
9810
|
+
}
|
|
9811
|
+
lastTickFailed = failed;
|
|
9812
|
+
})().finally(() => {
|
|
9813
|
+
if (activeTickAbort === controller) activeTickAbort = void 0;
|
|
9814
|
+
if (inFlight === tick) inFlight = void 0;
|
|
9815
|
+
scheduleTick(intervalMs, () => startTick(intervalMs));
|
|
9816
|
+
});
|
|
9817
|
+
inFlight = tick;
|
|
9818
|
+
};
|
|
9819
|
+
const performFlush = async () => {
|
|
9820
|
+
stopped = true;
|
|
9821
|
+
if (timer) {
|
|
9822
|
+
clearTimeout(timer);
|
|
9823
|
+
timer = void 0;
|
|
9824
|
+
}
|
|
9825
|
+
const deadlineAt = Date.now() + CREDENTIAL_FLUSH_DEADLINE_MS;
|
|
9826
|
+
if (inFlight) {
|
|
9827
|
+
const settled = await waitForSettlement(inFlight, CREDENTIAL_FLUSH_DEADLINE_MS);
|
|
9828
|
+
if (!settled) {
|
|
9829
|
+
activeTickAbort?.abort();
|
|
9830
|
+
const settledAfterAbort = await waitForSettlement(
|
|
9831
|
+
inFlight,
|
|
9832
|
+
CREDENTIAL_FLUSH_ABORT_GRACE_MS
|
|
9833
|
+
);
|
|
9834
|
+
if (!settledAfterAbort) {
|
|
9835
|
+
log3(
|
|
9836
|
+
"CREDENTIAL-FLUSH-ORPHANED-TICK: a sync-once child could not be proven settled; skipping the boundary flush rather than becoming a second writer",
|
|
9837
|
+
"warn"
|
|
9838
|
+
);
|
|
9839
|
+
return { outcomes: outcomesWith("timeout"), orphaned: true };
|
|
9840
|
+
}
|
|
9841
|
+
}
|
|
9842
|
+
}
|
|
9843
|
+
if (disabled) return { outcomes: outcomesWith("skipped"), orphaned: false };
|
|
9844
|
+
const outcomes = outcomesWith("timeout");
|
|
9845
|
+
for (const store of STORES) {
|
|
9846
|
+
const result = await runFlushStore(store, env, synchroniserRunner, log3, deadlineAt);
|
|
9847
|
+
if (result.orphaned) {
|
|
9848
|
+
log3(
|
|
9849
|
+
"CREDENTIAL-FLUSH-ORPHANED-CHILD: a flush sync-once child could not be proven settled; refusing another flush pass rather than becoming a second writer",
|
|
9850
|
+
"warn"
|
|
9851
|
+
);
|
|
9852
|
+
return { outcomes: outcomesWith("timeout"), orphaned: true };
|
|
9853
|
+
}
|
|
9854
|
+
outcomes[store] = result.outcome;
|
|
9855
|
+
}
|
|
9856
|
+
return { outcomes, orphaned: false };
|
|
9857
|
+
};
|
|
9858
|
+
let flushPasses = 0;
|
|
9859
|
+
let lastFlush;
|
|
9860
|
+
return {
|
|
9861
|
+
arm() {
|
|
9862
|
+
if (stopped || armed) return;
|
|
9863
|
+
armed = true;
|
|
9864
|
+
if (persistenceDisabled) {
|
|
9865
|
+
disabled = true;
|
|
9866
|
+
log3(
|
|
9867
|
+
"CREDENTIAL-SYNC-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; no interval credential sync this boot",
|
|
9868
|
+
"warn"
|
|
9869
|
+
);
|
|
9870
|
+
return;
|
|
9871
|
+
}
|
|
9872
|
+
disabled = false;
|
|
9873
|
+
const intervalMs = intervalSeconds(env, log3) * 1e3;
|
|
9874
|
+
scheduleTick(intervalMs, () => startTick(intervalMs));
|
|
9875
|
+
},
|
|
9876
|
+
async stopAndFlush(publish) {
|
|
9877
|
+
let result;
|
|
9878
|
+
const runningFlush = flushPromise;
|
|
9879
|
+
if (runningFlush) {
|
|
9880
|
+
result = await runningFlush;
|
|
9881
|
+
} else if (flushPasses >= MAX_FLUSH_PASSES || lastFlush?.orphaned) {
|
|
9882
|
+
result = lastFlush ?? { outcomes: outcomesWith("timeout"), orphaned: true };
|
|
9883
|
+
} else {
|
|
9884
|
+
flushPasses++;
|
|
9885
|
+
const currentFlush = performFlush();
|
|
9886
|
+
flushPromise = currentFlush;
|
|
9887
|
+
try {
|
|
9888
|
+
result = await currentFlush;
|
|
9889
|
+
lastFlush = result;
|
|
9890
|
+
} finally {
|
|
9891
|
+
if (flushPromise === currentFlush) flushPromise = void 0;
|
|
9892
|
+
}
|
|
9893
|
+
}
|
|
9894
|
+
if (publish) writeMarker(markerPath, result.outcomes, log3);
|
|
9895
|
+
return result.outcomes;
|
|
9896
|
+
}
|
|
9897
|
+
};
|
|
8939
9898
|
}
|
|
8940
9899
|
|
|
8941
9900
|
// src/commands/run.ts
|
|
@@ -8975,7 +9934,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
8975
9934
|
if (trimmed === "") {
|
|
8976
9935
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
8977
9936
|
}
|
|
8978
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
9937
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join10(homeDir, trimmed.slice(2)) : trimmed;
|
|
8979
9938
|
if (!isAbsolute3(expanded)) {
|
|
8980
9939
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
8981
9940
|
}
|
|
@@ -8999,6 +9958,28 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
8999
9958
|
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
9000
9959
|
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
9001
9960
|
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
9961
|
+
var OPENCODE_VERSION_ENV = "EVIDENT_OPENCODE_VERSION";
|
|
9962
|
+
function resolveOpenCodeVersion(options, env = process.env) {
|
|
9963
|
+
let raw;
|
|
9964
|
+
let source;
|
|
9965
|
+
if (options.opencodeVersion !== void 0) {
|
|
9966
|
+
raw = options.opencodeVersion;
|
|
9967
|
+
source = "--opencode-version";
|
|
9968
|
+
} else if (env[OPENCODE_VERSION_ENV] !== void 0 && env[OPENCODE_VERSION_ENV] !== "") {
|
|
9969
|
+
raw = env[OPENCODE_VERSION_ENV];
|
|
9970
|
+
source = OPENCODE_VERSION_ENV;
|
|
9971
|
+
} else {
|
|
9972
|
+
return { version: "v1", warnings: [] };
|
|
9973
|
+
}
|
|
9974
|
+
const normalized = raw.trim().toLowerCase();
|
|
9975
|
+
if (normalized !== "v1" && normalized !== "v2") {
|
|
9976
|
+
return {
|
|
9977
|
+
version: "v1",
|
|
9978
|
+
warnings: [`Ignoring invalid ${source} "${raw}": expected v1 or v2; using the default v1`]
|
|
9979
|
+
};
|
|
9980
|
+
}
|
|
9981
|
+
return { version: normalized, warnings: [] };
|
|
9982
|
+
}
|
|
9002
9983
|
function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
9003
9984
|
const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
|
|
9004
9985
|
let raw;
|
|
@@ -9065,7 +10046,7 @@ function log2(state, message, level = "info") {
|
|
|
9065
10046
|
})
|
|
9066
10047
|
);
|
|
9067
10048
|
} else if (!state.interactive) {
|
|
9068
|
-
const prefix = level === "error" ?
|
|
10049
|
+
const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
|
|
9069
10050
|
console.log(`${prefix} ${message}`);
|
|
9070
10051
|
}
|
|
9071
10052
|
}
|
|
@@ -9095,7 +10076,7 @@ function logActivity(state, entry) {
|
|
|
9095
10076
|
}
|
|
9096
10077
|
function reportSessionDbRecovery(state) {
|
|
9097
10078
|
try {
|
|
9098
|
-
const report = drainSessionDbRecoveryReport({ homeDir:
|
|
10079
|
+
const report = drainSessionDbRecoveryReport({ homeDir: homedir6(), env: process.env });
|
|
9099
10080
|
for (const record of report.records) {
|
|
9100
10081
|
const activity = buildSessionDbRecoveryActivity(record);
|
|
9101
10082
|
if (!activity) throw new Error("could not map session-DB recovery record");
|
|
@@ -9126,18 +10107,18 @@ function reportSessionDbRecoveryRecord(state, record) {
|
|
|
9126
10107
|
function displayStatus(state) {
|
|
9127
10108
|
if (!state.interactive) return;
|
|
9128
10109
|
const attempt = state.connection?.reconnectAttempt ?? 0;
|
|
9129
|
-
const tunnel = state.connected ?
|
|
9130
|
-
const opencode = state.opencodeConnected ?
|
|
9131
|
-
const messages = state.messageCount > 0 ?
|
|
10110
|
+
const tunnel = state.connected ? chalk7.green("tunnel: connected") : attempt > 0 ? chalk7.yellow(`tunnel: reconnecting (#${attempt})`) : chalk7.yellow("tunnel: connecting");
|
|
10111
|
+
const opencode = state.opencodeConnected ? chalk7.green(`opencode: :${state.port}`) : chalk7.red(`opencode: :${state.port} (down)`);
|
|
10112
|
+
const messages = state.messageCount > 0 ? chalk7.dim(` \xB7 ${state.messageCount} processed`) : "";
|
|
9132
10113
|
const last = state.activityLog[state.activityLog.length - 1];
|
|
9133
|
-
const detail = last ?
|
|
10114
|
+
const detail = last ? chalk7.dim(` \xB7 ${last.type === "error" ? last.error ?? "" : last.message ?? ""}`) : "";
|
|
9134
10115
|
const agent = state.agentName ?? state.agentId;
|
|
9135
10116
|
console.log(
|
|
9136
|
-
`${
|
|
10117
|
+
`${chalk7.bold("Evident")} ${chalk7.dim(agent)} ${tunnel} ${opencode}${messages}${detail}`
|
|
9137
10118
|
);
|
|
9138
10119
|
}
|
|
9139
10120
|
async function promptForLogin(promptMessage, successMessage) {
|
|
9140
|
-
const action = await
|
|
10121
|
+
const action = await select4({
|
|
9141
10122
|
message: promptMessage,
|
|
9142
10123
|
choices: [
|
|
9143
10124
|
{
|
|
@@ -9153,7 +10134,7 @@ async function promptForLogin(promptMessage, successMessage) {
|
|
|
9153
10134
|
]
|
|
9154
10135
|
});
|
|
9155
10136
|
if (action === "exit") {
|
|
9156
|
-
console.log(
|
|
10137
|
+
console.log(chalk7.dim(`
|
|
9157
10138
|
You can log in later by running: ${getCliName()} login`));
|
|
9158
10139
|
process.exit(0);
|
|
9159
10140
|
}
|
|
@@ -9164,7 +10145,7 @@ You can log in later by running: ${getCliName()} login`));
|
|
|
9164
10145
|
process.exit(1);
|
|
9165
10146
|
}
|
|
9166
10147
|
blank();
|
|
9167
|
-
console.log(
|
|
10148
|
+
console.log(chalk7.green(successMessage));
|
|
9168
10149
|
blank();
|
|
9169
10150
|
return { token: credentials2.token, authType: "bearer", user: credentials2.user };
|
|
9170
10151
|
}
|
|
@@ -9177,12 +10158,12 @@ async function handleAuthError(state, error2) {
|
|
|
9177
10158
|
if (state.interactive) displayStatus(state);
|
|
9178
10159
|
if (!state.interactive) {
|
|
9179
10160
|
blank();
|
|
9180
|
-
console.log(
|
|
9181
|
-
console.log(
|
|
10161
|
+
console.log(chalk7.red("Authentication expired"));
|
|
10162
|
+
console.log(chalk7.dim("Your authentication token is no longer valid."));
|
|
9182
10163
|
blank();
|
|
9183
|
-
console.log(
|
|
9184
|
-
console.log(
|
|
9185
|
-
console.log(
|
|
10164
|
+
console.log(chalk7.dim("To fix this:"));
|
|
10165
|
+
console.log(chalk7.dim(` 1. Run '${getCliName()} login' to re-authenticate`));
|
|
10166
|
+
console.log(chalk7.dim(" 2. Restart this command"));
|
|
9186
10167
|
blank();
|
|
9187
10168
|
await cleanup(state);
|
|
9188
10169
|
await shutdownTelemetry();
|
|
@@ -9190,7 +10171,7 @@ async function handleAuthError(state, error2) {
|
|
|
9190
10171
|
return { success: false };
|
|
9191
10172
|
}
|
|
9192
10173
|
blank();
|
|
9193
|
-
console.log(
|
|
10174
|
+
console.log(chalk7.yellow("Your authentication has expired."));
|
|
9194
10175
|
blank();
|
|
9195
10176
|
try {
|
|
9196
10177
|
const credentials2 = await promptForLogin(
|
|
@@ -9235,6 +10216,10 @@ async function driveChannels(state, driver) {
|
|
|
9235
10216
|
consecutiveDrainFailures = 0;
|
|
9236
10217
|
unreachableMs = 0;
|
|
9237
10218
|
state.messageCount += processed;
|
|
10219
|
+
if (driver.recycleRequested) {
|
|
10220
|
+
await beginGracefulShutdown(state, "recycle");
|
|
10221
|
+
return;
|
|
10222
|
+
}
|
|
9238
10223
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
9239
10224
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
9240
10225
|
const fileActivitySnapshot = driver.fileSyncActivity();
|
|
@@ -9277,8 +10262,8 @@ async function driveChannels(state, driver) {
|
|
|
9277
10262
|
state.running = false;
|
|
9278
10263
|
break;
|
|
9279
10264
|
}
|
|
9280
|
-
const
|
|
9281
|
-
logActivity(state, { type: "error", error: `Channel processing error: ${
|
|
10265
|
+
const errorMessage3 = error2 instanceof Error ? error2.message : String(error2);
|
|
10266
|
+
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage3}` });
|
|
9282
10267
|
if (state.interactive) displayStatus(state);
|
|
9283
10268
|
if (driver.hasInFlightWatchers()) {
|
|
9284
10269
|
consecutiveDrainFailures = 0;
|
|
@@ -9316,9 +10301,54 @@ async function driveChannels(state, driver) {
|
|
|
9316
10301
|
}
|
|
9317
10302
|
}
|
|
9318
10303
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
9319
|
-
var SESSION_DB_RECLAIM_MAX_PAGES =
|
|
10304
|
+
var SESSION_DB_RECLAIM_MAX_PAGES = 2e4;
|
|
10305
|
+
function shouldWarnForReclaimSkip(reason) {
|
|
10306
|
+
if (reason !== "sqlite-unavailable") return false;
|
|
10307
|
+
const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
|
|
10308
|
+
if (!version2) return false;
|
|
10309
|
+
const major = Number(version2[1]);
|
|
10310
|
+
const minor = Number(version2[2]);
|
|
10311
|
+
const patch = Number(version2[3]);
|
|
10312
|
+
return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
|
|
10313
|
+
}
|
|
9320
10314
|
function sessionDbPath() {
|
|
9321
|
-
return
|
|
10315
|
+
return join10(homedir6(), ".local", "share", "opencode", "opencode.db");
|
|
10316
|
+
}
|
|
10317
|
+
function logSessionDbProvenanceMismatch(state, provenance, currentVersion, preBootMigrationCount) {
|
|
10318
|
+
const record = {
|
|
10319
|
+
v: 1,
|
|
10320
|
+
event: "session_db_recovery",
|
|
10321
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
10322
|
+
stage: "verify",
|
|
10323
|
+
outcome: "schema_provenance_mismatch",
|
|
10324
|
+
severity: "error",
|
|
10325
|
+
reason: provenance.reason ?? "schema-provenance-mismatch",
|
|
10326
|
+
litestream_exit_code: null,
|
|
10327
|
+
attempt: null,
|
|
10328
|
+
replica_objects: null,
|
|
10329
|
+
replica_bytes: null,
|
|
10330
|
+
quarantine_destination: null,
|
|
10331
|
+
quarantined_objects: null,
|
|
10332
|
+
quarantine_failed_objects: null,
|
|
10333
|
+
quarantined_bytes: null,
|
|
10334
|
+
verified_restore_point: null,
|
|
10335
|
+
restore_points_tried: null,
|
|
10336
|
+
provenance_reason: provenance.reason,
|
|
10337
|
+
provenance_migration_delta: provenance.migrationDelta,
|
|
10338
|
+
replication_suspended: false,
|
|
10339
|
+
dbPath: sessionDbPath(),
|
|
10340
|
+
recorded_version: provenance.recordedVersion,
|
|
10341
|
+
current_version: currentVersion,
|
|
10342
|
+
provenance_pre_boot_migration_count: preBootMigrationCount
|
|
10343
|
+
};
|
|
10344
|
+
const activity = buildSessionDbRecoveryActivity(record);
|
|
10345
|
+
if (!activity) throw new Error("could not map session-DB provenance activity");
|
|
10346
|
+
logActivity(state, {
|
|
10347
|
+
type: activity.level === "error" ? "error" : "info",
|
|
10348
|
+
level: activity.level,
|
|
10349
|
+
...activity.level === "error" ? { error: activity.message } : { message: activity.message },
|
|
10350
|
+
metadata: activity.metadata
|
|
10351
|
+
});
|
|
9322
10352
|
}
|
|
9323
10353
|
async function runSweep(state, driver, config) {
|
|
9324
10354
|
const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
|
|
@@ -9365,7 +10395,7 @@ async function runSweep(state, driver, config) {
|
|
|
9365
10395
|
const reclaimResult = await reclaimSessionDbSpace({
|
|
9366
10396
|
dbPath: sessionDbPath(),
|
|
9367
10397
|
maxPages: SESSION_DB_RECLAIM_MAX_PAGES,
|
|
9368
|
-
allowFullVacuum: protectedNow.size === 0
|
|
10398
|
+
allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
|
|
9369
10399
|
});
|
|
9370
10400
|
if (reclaimResult.ok) {
|
|
9371
10401
|
const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
|
|
@@ -9378,7 +10408,7 @@ async function runSweep(state, driver, config) {
|
|
|
9378
10408
|
} else {
|
|
9379
10409
|
logActivity(state, {
|
|
9380
10410
|
type: "info",
|
|
9381
|
-
message: `Session cleanup: session-db space reclaim skipped (${reclaimResult.skipped})`
|
|
10411
|
+
message: `Session cleanup: session-db space reclaim skipped (${reclaimResult.skipped})` + (reclaimResult.detail ? `: ${reclaimResult.detail}` : "")
|
|
9382
10412
|
});
|
|
9383
10413
|
}
|
|
9384
10414
|
} catch (error2) {
|
|
@@ -9401,13 +10431,20 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
9401
10431
|
for (const warning2 of config.warnings) {
|
|
9402
10432
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
9403
10433
|
}
|
|
9404
|
-
const dbBytes = statSessionDbBytes(
|
|
10434
|
+
const dbBytes = statSessionDbBytes(homedir6());
|
|
9405
10435
|
void (async () => {
|
|
9406
|
-
const
|
|
10436
|
+
const reclaimAvailability = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
|
|
10437
|
+
if (reclaimAvailability !== null) {
|
|
10438
|
+
logActivity(state, {
|
|
10439
|
+
type: "info",
|
|
10440
|
+
level: shouldWarnForReclaimSkip(reclaimAvailability.reason) ? "warn" : "info",
|
|
10441
|
+
message: `Session cleanup: reclaim preflight skipped (${reclaimAvailability.reason})` + (reclaimAvailability.detail ? `: ${reclaimAvailability.detail}` : "")
|
|
10442
|
+
});
|
|
10443
|
+
}
|
|
9407
10444
|
const sizeWarning = buildSessionStoreSizeWarning({
|
|
9408
10445
|
dbBytes,
|
|
9409
10446
|
cleanupEnabled: config.enabled,
|
|
9410
|
-
reclaimSkipReason
|
|
10447
|
+
reclaimSkipReason: reclaimAvailability?.reason ?? null
|
|
9411
10448
|
});
|
|
9412
10449
|
if (sizeWarning !== null) {
|
|
9413
10450
|
logActivity(state, { type: "info", level: "warn", message: sizeWarning });
|
|
@@ -9602,7 +10639,8 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
9602
10639
|
});
|
|
9603
10640
|
return;
|
|
9604
10641
|
}
|
|
9605
|
-
const collect = createResourceUsageCollector(
|
|
10642
|
+
const { collect, stop } = createResourceUsageCollector(homedir6());
|
|
10643
|
+
state.stopResourceUsageSampling = stop;
|
|
9606
10644
|
let consecutiveFailures = 0;
|
|
9607
10645
|
const tick = async () => {
|
|
9608
10646
|
try {
|
|
@@ -9698,6 +10736,8 @@ async function cleanup(state, opts = {}) {
|
|
|
9698
10736
|
clearTimeout(timer);
|
|
9699
10737
|
}
|
|
9700
10738
|
state.sessionCleanupTimers = [];
|
|
10739
|
+
state.stopOpenCodeLogTail?.();
|
|
10740
|
+
state.stopOpenCodeLogTail = null;
|
|
9701
10741
|
if (state.claudeUsageTimer) {
|
|
9702
10742
|
clearTimeout(state.claudeUsageTimer);
|
|
9703
10743
|
state.claudeUsageTimer = null;
|
|
@@ -9712,21 +10752,41 @@ async function cleanup(state, opts = {}) {
|
|
|
9712
10752
|
clearTimeout(state.resourceUsageTimer);
|
|
9713
10753
|
state.resourceUsageTimer = null;
|
|
9714
10754
|
}
|
|
10755
|
+
state.stopResourceUsageSampling?.();
|
|
10756
|
+
state.stopResourceUsageSampling = null;
|
|
10757
|
+
const credentialSync = state.credentialSync;
|
|
10758
|
+
const flushCredentials = credentialSync ? async (phase, publish) => {
|
|
10759
|
+
await timeShutdownPhase(state, durations, phase, async () => {
|
|
10760
|
+
const outcomes = await credentialSync.stopAndFlush(publish);
|
|
10761
|
+
const level = Object.values(outcomes).every((outcome) => outcome === "ok") ? "info" : "warn";
|
|
10762
|
+
log2(
|
|
10763
|
+
state,
|
|
10764
|
+
`Credential flush: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
|
|
10765
|
+
level
|
|
10766
|
+
);
|
|
10767
|
+
});
|
|
10768
|
+
} : void 0;
|
|
10769
|
+
let drainSettled = true;
|
|
9715
10770
|
if (opts.graceful && state.channelDriver) {
|
|
9716
10771
|
state.channelDriver.stop();
|
|
10772
|
+
}
|
|
10773
|
+
if (flushCredentials) {
|
|
10774
|
+
await flushCredentials("credential_flush", !(opts.graceful && state.channelDriver));
|
|
10775
|
+
}
|
|
10776
|
+
if (opts.graceful && state.channelDriver) {
|
|
9717
10777
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
9718
10778
|
if (state.interactive) {
|
|
9719
10779
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
9720
10780
|
displayStatus(state);
|
|
9721
10781
|
}
|
|
9722
10782
|
const driver = state.channelDriver;
|
|
9723
|
-
|
|
10783
|
+
drainSettled = await timeShutdownPhase(
|
|
9724
10784
|
state,
|
|
9725
10785
|
durations,
|
|
9726
10786
|
"drain",
|
|
9727
10787
|
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
9728
10788
|
);
|
|
9729
|
-
if (!
|
|
10789
|
+
if (!drainSettled) {
|
|
9730
10790
|
logActivity(state, {
|
|
9731
10791
|
type: "info",
|
|
9732
10792
|
message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
|
|
@@ -9734,6 +10794,9 @@ async function cleanup(state, opts = {}) {
|
|
|
9734
10794
|
if (state.interactive) displayStatus(state);
|
|
9735
10795
|
}
|
|
9736
10796
|
}
|
|
10797
|
+
if (opts.graceful && state.channelDriver && flushCredentials && drainSettled) {
|
|
10798
|
+
await flushCredentials("credential_flush_final", true);
|
|
10799
|
+
}
|
|
9737
10800
|
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
9738
10801
|
if (state.connection) {
|
|
9739
10802
|
const connection = state.connection;
|
|
@@ -9769,13 +10832,51 @@ async function cleanup(state, opts = {}) {
|
|
|
9769
10832
|
}
|
|
9770
10833
|
return durations;
|
|
9771
10834
|
}
|
|
10835
|
+
async function beginGracefulShutdown(state, trigger) {
|
|
10836
|
+
if (state.shuttingDown) return;
|
|
10837
|
+
state.shuttingDown = true;
|
|
10838
|
+
const shutdownStartedAt = Date.now();
|
|
10839
|
+
const shutdownMessage = trigger === "recycle" ? "Recycle requested \u2014 finishing in-flight work, then exiting" : "Shutting down...";
|
|
10840
|
+
if (state.interactive) {
|
|
10841
|
+
logActivity(state, { type: "info", message: shutdownMessage });
|
|
10842
|
+
displayStatus(state);
|
|
10843
|
+
} else {
|
|
10844
|
+
log2(state, shutdownMessage);
|
|
10845
|
+
}
|
|
10846
|
+
const durations = await cleanup(state, { graceful: true });
|
|
10847
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
10848
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
10849
|
+
let timer;
|
|
10850
|
+
const flushed = shutdownTelemetry().then(
|
|
10851
|
+
() => true,
|
|
10852
|
+
(error2) => {
|
|
10853
|
+
log2(
|
|
10854
|
+
state,
|
|
10855
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
10856
|
+
"warn"
|
|
10857
|
+
);
|
|
10858
|
+
return true;
|
|
10859
|
+
}
|
|
10860
|
+
);
|
|
10861
|
+
const timedOut = new Promise((resolve4) => {
|
|
10862
|
+
timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
|
|
10863
|
+
});
|
|
10864
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
10865
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
10866
|
+
}
|
|
10867
|
+
clearTimeout(timer);
|
|
10868
|
+
});
|
|
10869
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
10870
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
10871
|
+
process.exit(0);
|
|
10872
|
+
}
|
|
9772
10873
|
async function run(options) {
|
|
9773
10874
|
const interactive = isInteractive(options.json);
|
|
9774
10875
|
let logLevel;
|
|
9775
10876
|
let fileSyncDirectories;
|
|
9776
10877
|
try {
|
|
9777
10878
|
logLevel = resolveLogLevel(options);
|
|
9778
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
10879
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir6());
|
|
9779
10880
|
if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
|
|
9780
10881
|
throw new Error(
|
|
9781
10882
|
"--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
|
|
@@ -9804,7 +10905,9 @@ async function run(options) {
|
|
|
9804
10905
|
connected: false,
|
|
9805
10906
|
opencodeConnected: false,
|
|
9806
10907
|
opencodeVersion: null,
|
|
10908
|
+
sessionDbProvenanceAnomaly: false,
|
|
9807
10909
|
opencodeProcess: null,
|
|
10910
|
+
stopOpenCodeLogTail: null,
|
|
9808
10911
|
litestreamProcess: null,
|
|
9809
10912
|
connection: null,
|
|
9810
10913
|
channelDriver: null,
|
|
@@ -9819,9 +10922,24 @@ async function run(options) {
|
|
|
9819
10922
|
openaiUsageTimer: null,
|
|
9820
10923
|
openaiUsageRearm: null,
|
|
9821
10924
|
resourceUsageTimer: null,
|
|
10925
|
+
stopResourceUsageSampling: null,
|
|
10926
|
+
credentialSync: null,
|
|
9822
10927
|
authHeader: ""
|
|
9823
10928
|
};
|
|
9824
10929
|
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
10930
|
+
if (options.credentialSyncMarker) {
|
|
10931
|
+
state.credentialSync = createCredentialSync({
|
|
10932
|
+
markerPath: options.credentialSyncMarker,
|
|
10933
|
+
env: process.env,
|
|
10934
|
+
log: (message, level = "info") => {
|
|
10935
|
+
if (level === "error") {
|
|
10936
|
+
logActivity(state, { type: "error", error: message });
|
|
10937
|
+
} else {
|
|
10938
|
+
logActivity(state, { type: "info", level, message });
|
|
10939
|
+
}
|
|
10940
|
+
}
|
|
10941
|
+
});
|
|
10942
|
+
}
|
|
9825
10943
|
if (fileSyncDirectories.length > 0) {
|
|
9826
10944
|
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
9827
10945
|
} else {
|
|
@@ -9847,43 +10965,7 @@ async function run(options) {
|
|
|
9847
10965
|
"warn"
|
|
9848
10966
|
);
|
|
9849
10967
|
}
|
|
9850
|
-
const handleSignal =
|
|
9851
|
-
if (state.shuttingDown) return;
|
|
9852
|
-
state.shuttingDown = true;
|
|
9853
|
-
const shutdownStartedAt = Date.now();
|
|
9854
|
-
if (state.interactive) {
|
|
9855
|
-
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
9856
|
-
displayStatus(state);
|
|
9857
|
-
} else {
|
|
9858
|
-
log2(state, "Shutting down...");
|
|
9859
|
-
}
|
|
9860
|
-
const durations = await cleanup(state, { graceful: true });
|
|
9861
|
-
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
9862
|
-
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
9863
|
-
let timer;
|
|
9864
|
-
const flushed = shutdownTelemetry().then(
|
|
9865
|
-
() => true,
|
|
9866
|
-
(error2) => {
|
|
9867
|
-
log2(
|
|
9868
|
-
state,
|
|
9869
|
-
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
9870
|
-
"warn"
|
|
9871
|
-
);
|
|
9872
|
-
return true;
|
|
9873
|
-
}
|
|
9874
|
-
);
|
|
9875
|
-
const timedOut = new Promise((resolve4) => {
|
|
9876
|
-
timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
|
|
9877
|
-
});
|
|
9878
|
-
if (!await Promise.race([flushed, timedOut])) {
|
|
9879
|
-
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
9880
|
-
}
|
|
9881
|
-
clearTimeout(timer);
|
|
9882
|
-
});
|
|
9883
|
-
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
9884
|
-
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
9885
|
-
process.exit(0);
|
|
9886
|
-
};
|
|
10968
|
+
const handleSignal = () => beginGracefulShutdown(state, "signal");
|
|
9887
10969
|
process.on("SIGINT", handleSignal);
|
|
9888
10970
|
process.on("SIGTERM", handleSignal);
|
|
9889
10971
|
try {
|
|
@@ -9893,15 +10975,15 @@ async function run(options) {
|
|
|
9893
10975
|
printError("Authentication required");
|
|
9894
10976
|
blank();
|
|
9895
10977
|
console.log(
|
|
9896
|
-
|
|
10978
|
+
chalk7.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
|
|
9897
10979
|
);
|
|
9898
|
-
console.log(
|
|
10980
|
+
console.log(chalk7.dim("Or run `evident login` for interactive authentication"));
|
|
9899
10981
|
blank();
|
|
9900
10982
|
process.exit(1);
|
|
9901
10983
|
return;
|
|
9902
10984
|
}
|
|
9903
10985
|
blank();
|
|
9904
|
-
console.log(
|
|
10986
|
+
console.log(chalk7.yellow("You are not logged in to Evident."));
|
|
9905
10987
|
blank();
|
|
9906
10988
|
credentials2 = await promptForLogin(
|
|
9907
10989
|
"Would you like to log in now?",
|
|
@@ -9951,7 +11033,7 @@ async function run(options) {
|
|
|
9951
11033
|
);
|
|
9952
11034
|
blank();
|
|
9953
11035
|
console.log(
|
|
9954
|
-
|
|
11036
|
+
chalk7.dim(
|
|
9955
11037
|
"Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
|
|
9956
11038
|
)
|
|
9957
11039
|
);
|
|
@@ -9974,15 +11056,15 @@ async function run(options) {
|
|
|
9974
11056
|
);
|
|
9975
11057
|
if (interactive && !state.json) {
|
|
9976
11058
|
blank();
|
|
9977
|
-
console.log(
|
|
9978
|
-
console.log(
|
|
11059
|
+
console.log(chalk7.bold("Evident Run"));
|
|
11060
|
+
console.log(chalk7.dim("-".repeat(40)));
|
|
9979
11061
|
}
|
|
9980
11062
|
const spinner = interactive && !state.json ? ora3("Validating runner...").start() : null;
|
|
9981
11063
|
let validation = await getAgentInfo(state.agentId, state.authHeader);
|
|
9982
11064
|
if (!validation.valid && validation.authFailed && interactive) {
|
|
9983
11065
|
spinner?.fail("Authentication failed");
|
|
9984
11066
|
blank();
|
|
9985
|
-
console.log(
|
|
11067
|
+
console.log(chalk7.yellow("Your authentication token is invalid or expired."));
|
|
9986
11068
|
blank();
|
|
9987
11069
|
credentials2 = await promptForLogin(
|
|
9988
11070
|
"Would you like to log in again?",
|
|
@@ -10029,6 +11111,14 @@ async function run(options) {
|
|
|
10029
11111
|
await restoreCredentialStores(credentialContext);
|
|
10030
11112
|
if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
|
|
10031
11113
|
}
|
|
11114
|
+
state.credentialSync?.arm();
|
|
11115
|
+
state.stopOpenCodeLogTail = tailOpenCodeLogFile(
|
|
11116
|
+
resolveOpenCodeLogPath(homedir6(), process.env),
|
|
11117
|
+
createOpenCodeActivityForwarder(() => ({
|
|
11118
|
+
agentId: state.agentId,
|
|
11119
|
+
authHeader: state.authHeader
|
|
11120
|
+
}))
|
|
11121
|
+
).stop;
|
|
10032
11122
|
let sessionDbVerifyFatal = false;
|
|
10033
11123
|
if (!options.restoreSessionDb) {
|
|
10034
11124
|
log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
|
|
@@ -10078,13 +11168,28 @@ async function run(options) {
|
|
|
10078
11168
|
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
10079
11169
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
10080
11170
|
}
|
|
11171
|
+
const { version: opencodeVersion, warnings: opencodeVersionWarnings } = resolveOpenCodeVersion(
|
|
11172
|
+
options,
|
|
11173
|
+
process.env
|
|
11174
|
+
);
|
|
11175
|
+
for (const warning2 of opencodeVersionWarnings) {
|
|
11176
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
11177
|
+
}
|
|
10081
11178
|
const { value: maxActiveSessions, warnings: maxActiveSessionsWarnings } = resolveMaxActiveSessions(options, process.env);
|
|
10082
11179
|
for (const warning2 of maxActiveSessionsWarnings) {
|
|
10083
11180
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
10084
11181
|
}
|
|
11182
|
+
const preBootMigrationIds = readSessionDbMigrationIds(sessionDbPath());
|
|
10085
11183
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
10086
11184
|
try {
|
|
10087
|
-
const oc = await
|
|
11185
|
+
const oc = opencodeVersion === "v2" ? await ensureOpenCode2Running({
|
|
11186
|
+
port: state.port,
|
|
11187
|
+
interactive: state.interactive,
|
|
11188
|
+
agentId: state.agentId,
|
|
11189
|
+
log: (message) => log2(state, message),
|
|
11190
|
+
startTimeoutMs: opencodeStartTimeoutMs,
|
|
11191
|
+
inheritStdio: Boolean(options.opencodePidFile)
|
|
11192
|
+
}) : await ensureOpenCodeRunning({
|
|
10088
11193
|
port: state.port,
|
|
10089
11194
|
interactive: state.interactive,
|
|
10090
11195
|
agentId: state.agentId,
|
|
@@ -10097,7 +11202,7 @@ async function run(options) {
|
|
|
10097
11202
|
state.opencodeVersion = oc.version;
|
|
10098
11203
|
if (options.opencodePidFile && oc.process?.pid !== void 0) {
|
|
10099
11204
|
try {
|
|
10100
|
-
|
|
11205
|
+
writeFileSync6(options.opencodePidFile, `${oc.process.pid}
|
|
10101
11206
|
`, { mode: 384 });
|
|
10102
11207
|
chmodSync3(options.opencodePidFile, 384);
|
|
10103
11208
|
} catch (error2) {
|
|
@@ -10107,6 +11212,23 @@ async function run(options) {
|
|
|
10107
11212
|
});
|
|
10108
11213
|
}
|
|
10109
11214
|
}
|
|
11215
|
+
if (state.opencodeVersion !== null) {
|
|
11216
|
+
const provenance = checkSessionDbProvenance({
|
|
11217
|
+
dbPath: sessionDbPath(),
|
|
11218
|
+
currentVersion: state.opencodeVersion,
|
|
11219
|
+
homeDir: homedir6(),
|
|
11220
|
+
env: process.env
|
|
11221
|
+
});
|
|
11222
|
+
if (provenance.anomaly) {
|
|
11223
|
+
state.sessionDbProvenanceAnomaly = true;
|
|
11224
|
+
logSessionDbProvenanceMismatch(
|
|
11225
|
+
state,
|
|
11226
|
+
provenance,
|
|
11227
|
+
state.opencodeVersion,
|
|
11228
|
+
preBootMigrationIds?.length ?? null
|
|
11229
|
+
);
|
|
11230
|
+
}
|
|
11231
|
+
}
|
|
10110
11232
|
state.opencodeConnected = oc.notReadyReason === null;
|
|
10111
11233
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
10112
11234
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
@@ -10129,10 +11251,10 @@ async function run(options) {
|
|
|
10129
11251
|
if (state.interactive && !state.json) {
|
|
10130
11252
|
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
10131
11253
|
blank();
|
|
10132
|
-
console.log(
|
|
11254
|
+
console.log(chalk7.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
10133
11255
|
console.log(
|
|
10134
|
-
|
|
10135
|
-
`Run ${
|
|
11256
|
+
chalk7.dim(
|
|
11257
|
+
`Run ${chalk7.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
10136
11258
|
)
|
|
10137
11259
|
);
|
|
10138
11260
|
blank();
|
|
@@ -10159,7 +11281,7 @@ async function run(options) {
|
|
|
10159
11281
|
let existingPid;
|
|
10160
11282
|
if (existsSync3(options.litestreamPidFile)) {
|
|
10161
11283
|
try {
|
|
10162
|
-
const rawPid =
|
|
11284
|
+
const rawPid = readFileSync6(options.litestreamPidFile, "utf8").trim();
|
|
10163
11285
|
const parsedPid = Number(rawPid);
|
|
10164
11286
|
if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
|
|
10165
11287
|
existingPid = parsedPid;
|
|
@@ -10196,7 +11318,7 @@ async function run(options) {
|
|
|
10196
11318
|
});
|
|
10197
11319
|
try {
|
|
10198
11320
|
if (litestreamProcess.pid !== void 0) {
|
|
10199
|
-
|
|
11321
|
+
writeFileSync6(options.litestreamPidFile, `${litestreamProcess.pid}
|
|
10200
11322
|
`, {
|
|
10201
11323
|
mode: 384
|
|
10202
11324
|
});
|
|
@@ -10256,7 +11378,7 @@ async function run(options) {
|
|
|
10256
11378
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
10257
11379
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
10258
11380
|
fileSyncDirectories,
|
|
10259
|
-
homeDir:
|
|
11381
|
+
homeDir: homedir6(),
|
|
10260
11382
|
maxActiveSessions,
|
|
10261
11383
|
log: (entry) => (
|
|
10262
11384
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
@@ -10382,6 +11504,18 @@ async function run(options) {
|
|
|
10382
11504
|
if (state.interactive) displayStatus(state);
|
|
10383
11505
|
});
|
|
10384
11506
|
},
|
|
11507
|
+
// Both loops are rearmed because `rearm()` is idempotent for the
|
|
11508
|
+
// provider that did not just connect, and is a no-op when reporting is off.
|
|
11509
|
+
onUsageRearmPing: () => {
|
|
11510
|
+
if (!state.running) return;
|
|
11511
|
+
logActivity(state, {
|
|
11512
|
+
type: "info",
|
|
11513
|
+
level: "debug",
|
|
11514
|
+
message: "Usage rearm ping received"
|
|
11515
|
+
});
|
|
11516
|
+
state.claudeUsageRearm?.();
|
|
11517
|
+
state.openaiUsageRearm?.();
|
|
11518
|
+
},
|
|
10385
11519
|
onInfo: (message) => logActivity(state, { type: "info", message })
|
|
10386
11520
|
}
|
|
10387
11521
|
});
|
|
@@ -10402,7 +11536,17 @@ async function run(options) {
|
|
|
10402
11536
|
setTimer: (timer) => {
|
|
10403
11537
|
state.openaiUsageTimer = timer;
|
|
10404
11538
|
},
|
|
10405
|
-
fetchUsage: () =>
|
|
11539
|
+
fetchUsage: async () => {
|
|
11540
|
+
const usage = await getOpenAiUsage(state.port);
|
|
11541
|
+
if (usage.subscription === null) {
|
|
11542
|
+
logActivity(state, {
|
|
11543
|
+
type: "info",
|
|
11544
|
+
level: "debug",
|
|
11545
|
+
message: "OpenAI usage subscription could not be identified from the local credential"
|
|
11546
|
+
});
|
|
11547
|
+
}
|
|
11548
|
+
return usage;
|
|
11549
|
+
},
|
|
10406
11550
|
report: (usage) => reportOpenAiUsage(state.agentId, state.authHeader, usage),
|
|
10407
11551
|
isLocalCredentialProblem: isLocalCredentialProblem2,
|
|
10408
11552
|
forcedOnHint: "connect a ChatGPT account to this runner, or run `opencode auth login`",
|
|
@@ -10448,7 +11592,7 @@ async function run(options) {
|
|
|
10448
11592
|
}
|
|
10449
11593
|
|
|
10450
11594
|
// src/index.ts
|
|
10451
|
-
var { version } =
|
|
11595
|
+
var { version } = createRequire2(import.meta.url)("../package.json");
|
|
10452
11596
|
var program = new Command();
|
|
10453
11597
|
program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
|
|
10454
11598
|
"--endpoint <url>",
|
|
@@ -10476,6 +11620,9 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
10476
11620
|
).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option(
|
|
10477
11621
|
"--opencode-start-timeout <seconds>",
|
|
10478
11622
|
"Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
|
|
11623
|
+
).option(
|
|
11624
|
+
"--opencode-version <v1|v2>",
|
|
11625
|
+
"Which OpenCode major version to launch: v1 or v2 (default: v1). Env: EVIDENT_OPENCODE_VERSION"
|
|
10479
11626
|
).option("--json", "Output in JSON format").option(
|
|
10480
11627
|
"--session-cleanup-max-age <duration>",
|
|
10481
11628
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
@@ -10526,6 +11673,9 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
10526
11673
|
).option(
|
|
10527
11674
|
"--opencode-config-overlay <path>",
|
|
10528
11675
|
"Apply this runner-provided OpenCode config before starting OpenCode."
|
|
11676
|
+
).option(
|
|
11677
|
+
"--credential-sync-marker <path>",
|
|
11678
|
+
"Own the interval credential sync and write this marker once the shutdown flush has finished, so the runner image's lifecycle hooks can wait on it."
|
|
10529
11679
|
).action(
|
|
10530
11680
|
(options) => {
|
|
10531
11681
|
run({
|
|
@@ -10541,6 +11691,7 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
10541
11691
|
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
10542
11692
|
// resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
|
|
10543
11693
|
opencodeStartTimeout: options.opencodeStartTimeout,
|
|
11694
|
+
opencodeVersion: options.opencodeVersion,
|
|
10544
11695
|
json: options.json,
|
|
10545
11696
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
10546
11697
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
@@ -10564,7 +11715,8 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
10564
11715
|
sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
|
|
10565
11716
|
restoreSessionDb: options.restoreSessionDb,
|
|
10566
11717
|
restoreRunnerCredentials: options.restoreRunnerCredentials,
|
|
10567
|
-
opencodeConfigOverlay: options.opencodeConfigOverlay
|
|
11718
|
+
opencodeConfigOverlay: options.opencodeConfigOverlay,
|
|
11719
|
+
credentialSyncMarker: options.credentialSyncMarker
|
|
10568
11720
|
});
|
|
10569
11721
|
}
|
|
10570
11722
|
);
|