@evident-ai/cli 3.4.1-dev.57ff127 → 3.4.1-dev.661a835
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 +27 -0
- package/dist/index.js +2253 -409
- 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
|
|
@@ -371,14 +371,14 @@ function blank() {
|
|
|
371
371
|
console.log();
|
|
372
372
|
}
|
|
373
373
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
374
|
-
return new Promise((
|
|
374
|
+
return new Promise((resolve4) => {
|
|
375
375
|
process.stdout.write(chalk.dim(prompt));
|
|
376
376
|
const handler = () => {
|
|
377
377
|
process.stdin.removeListener("data", handler);
|
|
378
378
|
process.stdin.setRawMode?.(false);
|
|
379
379
|
process.stdin.pause();
|
|
380
380
|
console.log();
|
|
381
|
-
|
|
381
|
+
resolve4();
|
|
382
382
|
};
|
|
383
383
|
if (process.stdin.isTTY) {
|
|
384
384
|
process.stdin.setRawMode?.(true);
|
|
@@ -388,7 +388,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
388
388
|
});
|
|
389
389
|
}
|
|
390
390
|
function sleep(ms) {
|
|
391
|
-
return new Promise((
|
|
391
|
+
return new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
392
392
|
}
|
|
393
393
|
|
|
394
394
|
// src/commands/login.ts
|
|
@@ -466,19 +466,19 @@ async function tokenLogin() {
|
|
|
466
466
|
);
|
|
467
467
|
blank();
|
|
468
468
|
process.stdout.write("Paste token: ");
|
|
469
|
-
const token = await new Promise((
|
|
469
|
+
const token = await new Promise((resolve4) => {
|
|
470
470
|
let data = "";
|
|
471
471
|
process.stdin.setEncoding("utf8");
|
|
472
472
|
process.stdin.on("data", (chunk) => {
|
|
473
473
|
data += chunk;
|
|
474
474
|
});
|
|
475
475
|
process.stdin.on("end", () => {
|
|
476
|
-
|
|
476
|
+
resolve4(data.trim());
|
|
477
477
|
});
|
|
478
478
|
if (process.stdin.isTTY) {
|
|
479
479
|
process.stdin.once("data", (chunk) => {
|
|
480
480
|
process.stdin.pause();
|
|
481
|
-
|
|
481
|
+
resolve4(chunk.toString().trim());
|
|
482
482
|
});
|
|
483
483
|
process.stdin.resume();
|
|
484
484
|
}
|
|
@@ -722,6 +722,14 @@ function toReportedWindow(window) {
|
|
|
722
722
|
if (!window) return null;
|
|
723
723
|
return { utilization: window.utilization, resets_at: window.resetsAt };
|
|
724
724
|
}
|
|
725
|
+
function toReportedOwner(snapshot) {
|
|
726
|
+
if (!snapshot.owner) return null;
|
|
727
|
+
return {
|
|
728
|
+
email: snapshot.owner.email,
|
|
729
|
+
organization_name: snapshot.owner.organizationName,
|
|
730
|
+
rate_limit_tier: snapshot.owner.rateLimitTier
|
|
731
|
+
};
|
|
732
|
+
}
|
|
725
733
|
async function reportClaudeUsage(agentId, authHeader, snapshot) {
|
|
726
734
|
try {
|
|
727
735
|
const apiUrl = getApiUrlConfig();
|
|
@@ -730,7 +738,8 @@ async function reportClaudeUsage(agentId, authHeader, snapshot) {
|
|
|
730
738
|
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
731
739
|
body: JSON.stringify({
|
|
732
740
|
five_hour: toReportedWindow(snapshot.fiveHour),
|
|
733
|
-
seven_day: toReportedWindow(snapshot.sevenDay)
|
|
741
|
+
seven_day: toReportedWindow(snapshot.sevenDay),
|
|
742
|
+
owner: toReportedOwner(snapshot)
|
|
734
743
|
}),
|
|
735
744
|
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
736
745
|
});
|
|
@@ -754,6 +763,13 @@ function toReportedOpenAiWindow(window) {
|
|
|
754
763
|
resets_at: window.resetsAt
|
|
755
764
|
};
|
|
756
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
|
+
}
|
|
757
773
|
async function reportOpenAiUsage(agentId, authHeader, snapshot) {
|
|
758
774
|
try {
|
|
759
775
|
const apiUrl = getApiUrlConfig();
|
|
@@ -764,7 +780,8 @@ async function reportOpenAiUsage(agentId, authHeader, snapshot) {
|
|
|
764
780
|
primary: toReportedOpenAiWindow(snapshot.primary),
|
|
765
781
|
secondary: toReportedOpenAiWindow(snapshot.secondary),
|
|
766
782
|
has_credits: snapshot.hasCredits,
|
|
767
|
-
credits_unlimited: snapshot.creditsUnlimited
|
|
783
|
+
credits_unlimited: snapshot.creditsUnlimited,
|
|
784
|
+
subscription: toReportedOpenAiSubscription(snapshot)
|
|
768
785
|
}),
|
|
769
786
|
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
770
787
|
});
|
|
@@ -996,7 +1013,10 @@ import { readFileSync } from "fs";
|
|
|
996
1013
|
import { homedir } from "os";
|
|
997
1014
|
import { join } from "path";
|
|
998
1015
|
var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
1016
|
+
var CLAUDE_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
|
|
1017
|
+
var CLAUDE_PROFILE_TIMEOUT_MS = 2e3;
|
|
999
1018
|
var KEYCHAIN_SERVICE = "Claude Code-credentials";
|
|
1019
|
+
var cachedOwner = null;
|
|
1000
1020
|
var CLAUDE_CREDENTIALS_SEGMENTS = [".claude", ".credentials.json"];
|
|
1001
1021
|
function parseClaudeCliCredentials(raw) {
|
|
1002
1022
|
let parsed;
|
|
@@ -1070,6 +1090,47 @@ function toWindow(value) {
|
|
|
1070
1090
|
}
|
|
1071
1091
|
return { utilization: window.utilization, resetsAt };
|
|
1072
1092
|
}
|
|
1093
|
+
function ownerLookupFailure(error2) {
|
|
1094
|
+
const name = error2?.name;
|
|
1095
|
+
return name === "TimeoutError" || name === "AbortError" ? "timed out" : "request failed";
|
|
1096
|
+
}
|
|
1097
|
+
async function getClaudeUsageOwner(accessToken) {
|
|
1098
|
+
if (cachedOwner?.accessToken === accessToken) {
|
|
1099
|
+
return { owner: cachedOwner.owner, ownerLookupError: null };
|
|
1100
|
+
}
|
|
1101
|
+
try {
|
|
1102
|
+
const response = await fetch(CLAUDE_PROFILE_URL, {
|
|
1103
|
+
headers: {
|
|
1104
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1105
|
+
"Content-Type": "application/json",
|
|
1106
|
+
"anthropic-version": "2023-06-01"
|
|
1107
|
+
},
|
|
1108
|
+
signal: AbortSignal.timeout(CLAUDE_PROFILE_TIMEOUT_MS)
|
|
1109
|
+
});
|
|
1110
|
+
if (!response.ok) {
|
|
1111
|
+
return { owner: null, ownerLookupError: `HTTP ${response.status}` };
|
|
1112
|
+
}
|
|
1113
|
+
let body;
|
|
1114
|
+
try {
|
|
1115
|
+
body = await response.json();
|
|
1116
|
+
} catch (error2) {
|
|
1117
|
+
return { owner: null, ownerLookupError: "malformed response" };
|
|
1118
|
+
}
|
|
1119
|
+
const profile = body;
|
|
1120
|
+
if (typeof profile.account?.email !== "string" || !profile.account.email.trim()) {
|
|
1121
|
+
return { owner: null, ownerLookupError: "malformed response" };
|
|
1122
|
+
}
|
|
1123
|
+
const owner = {
|
|
1124
|
+
email: profile.account.email,
|
|
1125
|
+
organizationName: typeof profile.organization?.name === "string" && profile.organization.name.trim() ? profile.organization.name.trim() : null,
|
|
1126
|
+
rateLimitTier: typeof profile.organization?.rate_limit_tier === "string" && profile.organization.rate_limit_tier.trim() ? profile.organization.rate_limit_tier.trim() : null
|
|
1127
|
+
};
|
|
1128
|
+
cachedOwner = { accessToken, owner };
|
|
1129
|
+
return { owner, ownerLookupError: null };
|
|
1130
|
+
} catch (error2) {
|
|
1131
|
+
return { owner: null, ownerLookupError: ownerLookupFailure(error2) };
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1073
1134
|
async function getClaudeUsage() {
|
|
1074
1135
|
const credentials2 = readClaudeCliCredentials();
|
|
1075
1136
|
if (!credentials2) {
|
|
@@ -1089,15 +1150,19 @@ async function getClaudeUsage() {
|
|
|
1089
1150
|
Authorization: `Bearer ${credentials2.accessToken}`,
|
|
1090
1151
|
"Content-Type": "application/json",
|
|
1091
1152
|
"anthropic-version": "2023-06-01"
|
|
1092
|
-
}
|
|
1153
|
+
},
|
|
1154
|
+
signal: AbortSignal.timeout(CLAUDE_PROFILE_TIMEOUT_MS)
|
|
1093
1155
|
});
|
|
1094
1156
|
if (!res.ok) {
|
|
1095
1157
|
throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
|
|
1096
1158
|
}
|
|
1097
1159
|
const body = await res.json();
|
|
1160
|
+
const { owner, ownerLookupError } = await getClaudeUsageOwner(credentials2.accessToken);
|
|
1098
1161
|
return {
|
|
1099
1162
|
fiveHour: toWindow(body.five_hour),
|
|
1100
|
-
sevenDay: toWindow(body.seven_day)
|
|
1163
|
+
sevenDay: toWindow(body.seven_day),
|
|
1164
|
+
owner,
|
|
1165
|
+
ownerLookupError
|
|
1101
1166
|
};
|
|
1102
1167
|
}
|
|
1103
1168
|
|
|
@@ -1126,8 +1191,9 @@ async function claudeUsage() {
|
|
|
1126
1191
|
}
|
|
1127
1192
|
|
|
1128
1193
|
// src/commands/run.ts
|
|
1129
|
-
import {
|
|
1130
|
-
import {
|
|
1194
|
+
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
|
|
1195
|
+
import { homedir as homedir5 } from "os";
|
|
1196
|
+
import { isAbsolute as isAbsolute3, join as join9, parse, resolve as resolvePath2 } from "path";
|
|
1131
1197
|
import chalk6 from "chalk";
|
|
1132
1198
|
|
|
1133
1199
|
// ../../packages/types/src/agents/index.ts
|
|
@@ -1467,7 +1533,14 @@ function drainSessionDbRecoveryReport({
|
|
|
1467
1533
|
skippedLines++;
|
|
1468
1534
|
return [];
|
|
1469
1535
|
}
|
|
1470
|
-
return [
|
|
1536
|
+
return [
|
|
1537
|
+
{
|
|
1538
|
+
...value,
|
|
1539
|
+
provenance_reason: value.provenance_reason ?? null,
|
|
1540
|
+
provenance_migration_delta: value.provenance_migration_delta ?? null,
|
|
1541
|
+
replication_suspended: value.replication_suspended ?? false
|
|
1542
|
+
}
|
|
1543
|
+
];
|
|
1471
1544
|
} catch (error2) {
|
|
1472
1545
|
skippedLines++;
|
|
1473
1546
|
console.error(
|
|
@@ -1492,12 +1565,39 @@ function buildSessionDbRecoveryActivity(record) {
|
|
|
1492
1565
|
const level = record.severity === "warning" ? "warn" : record.severity === "error" ? "error" : null;
|
|
1493
1566
|
if (!level) return null;
|
|
1494
1567
|
const noVerifiedPoint = record.verified_restore_point ? ` The verified restore point is ${record.verified_restore_point}.` : " No verified restore point is known.";
|
|
1568
|
+
const replication = record.replication_suspended ? " This start is not backing up its new session history; restart after fixing the cause." : "";
|
|
1569
|
+
const giveupMessage = (() => {
|
|
1570
|
+
switch (record.reason) {
|
|
1571
|
+
case "restore_deadline_exceeded":
|
|
1572
|
+
return "The restore did not finish before this startup deadline. Earlier sessions are unavailable for this start; collect the SESSION-DB-RESTORE-TRUNCATED boot log before retrying.";
|
|
1573
|
+
case "restore_tool_unusable":
|
|
1574
|
+
case "classification_unrecognised":
|
|
1575
|
+
return "The restore or classification tool produced an unsupported result. Inspect the named boot marker or log and repair the runner image or bundle before restarting.";
|
|
1576
|
+
case "synchroniser_config_unevaluable":
|
|
1577
|
+
case "synchroniser_config_incomplete":
|
|
1578
|
+
return "The installed hook and synchroniser bundle could not agree on configuration. Inspect the named boot marker or log and repair the runner image or bundle before restarting.";
|
|
1579
|
+
case "synchroniser_config_unresolved":
|
|
1580
|
+
return "The synchroniser configuration could not be resolved. Inspect the preceding boot error and repair the identified runner image, bundle, or local environment before restarting.";
|
|
1581
|
+
case "litestream_config_unavailable":
|
|
1582
|
+
return "The local Litestream configuration could not be generated or written. Inspect the preceding boot error and repair the runner image, bundle, local environment, or write permissions before restarting.";
|
|
1583
|
+
case "classification_fatal":
|
|
1584
|
+
return "Session history could not be restored because backup setup could not be established. Inspect the named boot marker or log and repair the identified backup configuration or permissions.";
|
|
1585
|
+
default:
|
|
1586
|
+
return null;
|
|
1587
|
+
}
|
|
1588
|
+
})();
|
|
1589
|
+
if (giveupMessage)
|
|
1590
|
+
return {
|
|
1591
|
+
level,
|
|
1592
|
+
metadata: withoutContractFields(record),
|
|
1593
|
+
message: `${giveupMessage}${replication}`
|
|
1594
|
+
};
|
|
1495
1595
|
switch (record.outcome) {
|
|
1496
1596
|
case "fresh_session_db":
|
|
1497
1597
|
return {
|
|
1498
1598
|
level,
|
|
1499
1599
|
metadata: withoutContractFields(record),
|
|
1500
|
-
message: `This runner started with a fresh session database. Earlier sessions are unavailable, and queued conversation or session references from before this start may no longer resolve.${noVerifiedPoint} Review the runner's backup configuration before relying on restored session history
|
|
1600
|
+
message: `This runner started with a fresh session database. Earlier sessions are unavailable, and queued conversation or session references from before this start may no longer resolve.${noVerifiedPoint} Review the runner's backup configuration before relying on restored session history.${replication}`
|
|
1501
1601
|
};
|
|
1502
1602
|
case "restore_retried":
|
|
1503
1603
|
return {
|
|
@@ -1535,7 +1635,19 @@ function buildSessionDbRecoveryActivity(record) {
|
|
|
1535
1635
|
return {
|
|
1536
1636
|
level,
|
|
1537
1637
|
metadata: withoutContractFields(record),
|
|
1538
|
-
message:
|
|
1638
|
+
message: `This runner started without restoring session history because it could not verify where its session history is backed up. Nothing in the backup was changed; check the runner backup configuration and permissions.${replication}`
|
|
1639
|
+
};
|
|
1640
|
+
case "session_db_boot_refused":
|
|
1641
|
+
return {
|
|
1642
|
+
level,
|
|
1643
|
+
metadata: withoutContractFields(record),
|
|
1644
|
+
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.`
|
|
1645
|
+
};
|
|
1646
|
+
case "schema_provenance_mismatch":
|
|
1647
|
+
return {
|
|
1648
|
+
level,
|
|
1649
|
+
metadata: withoutContractFields(record),
|
|
1650
|
+
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.`
|
|
1539
1651
|
};
|
|
1540
1652
|
default:
|
|
1541
1653
|
return null;
|
|
@@ -1550,7 +1662,9 @@ var OUTCOMES = /* @__PURE__ */ new Set([
|
|
|
1550
1662
|
"restore_retried",
|
|
1551
1663
|
"fresh_session_db",
|
|
1552
1664
|
"history_rolled_back",
|
|
1553
|
-
"restore_misconfigured"
|
|
1665
|
+
"restore_misconfigured",
|
|
1666
|
+
"session_db_boot_refused",
|
|
1667
|
+
"schema_provenance_mismatch"
|
|
1554
1668
|
]);
|
|
1555
1669
|
var STAGES = /* @__PURE__ */ new Set(["restore", "verify"]);
|
|
1556
1670
|
var SEVERITIES = /* @__PURE__ */ new Set(["warning", "error"]);
|
|
@@ -1568,7 +1682,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
|
|
|
1568
1682
|
function isSessionDbRecoveryRecord(value) {
|
|
1569
1683
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1570
1684
|
const record = value;
|
|
1571
|
-
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" && NUMBER_FIELDS.every((field) => record[field] === null || Number.isInteger(record[field])) && STRING_OR_NULL_FIELDS.every(
|
|
1685
|
+
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(
|
|
1572
1686
|
(field) => record[field] === null || typeof record[field] === "string"
|
|
1573
1687
|
);
|
|
1574
1688
|
}
|
|
@@ -1597,214 +1711,932 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
1597
1711
|
if (health.healthy) {
|
|
1598
1712
|
return health;
|
|
1599
1713
|
}
|
|
1600
|
-
await new Promise((
|
|
1714
|
+
await new Promise((resolve4) => setTimeout(resolve4, 1e3));
|
|
1601
1715
|
}
|
|
1602
1716
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
1603
1717
|
}
|
|
1604
1718
|
|
|
1605
|
-
// src/lib/opencode/
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
}
|
|
1611
|
-
function buildOpenCodeVersionWarning(version2) {
|
|
1612
|
-
if (isQueueValidatedVersion(version2)) return null;
|
|
1613
|
-
const detected = version2 ? `v${version2}` : "unknown";
|
|
1614
|
-
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
1615
|
-
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
|
|
1616
|
-
}
|
|
1719
|
+
// src/lib/opencode/session-db-boot.ts
|
|
1720
|
+
import { spawn as spawn2 } from "child_process";
|
|
1721
|
+
import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "fs";
|
|
1722
|
+
import { homedir as homedir2 } from "os";
|
|
1723
|
+
import { dirname as dirname2, resolve as resolvePath } from "path";
|
|
1617
1724
|
|
|
1618
|
-
// src/lib/
|
|
1619
|
-
import {
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1725
|
+
// src/lib/runner-synchroniser.ts
|
|
1726
|
+
import { spawn } from "child_process";
|
|
1727
|
+
function appendError(stderr, error2) {
|
|
1728
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
1729
|
+
return stderr === "" ? message : `${stderr}
|
|
1730
|
+
${message}`;
|
|
1731
|
+
}
|
|
1732
|
+
function runSynchroniser(args, opts) {
|
|
1733
|
+
return new Promise((resolve4) => {
|
|
1734
|
+
let child;
|
|
1735
|
+
let stdout = "";
|
|
1736
|
+
let stderr = "";
|
|
1737
|
+
let settled = false;
|
|
1738
|
+
const timer = {};
|
|
1739
|
+
let abortListener;
|
|
1740
|
+
let spawnListener;
|
|
1741
|
+
const finish = (result) => {
|
|
1742
|
+
if (settled) return;
|
|
1743
|
+
settled = true;
|
|
1744
|
+
if (timer.handle) clearTimeout(timer.handle);
|
|
1745
|
+
if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
|
|
1746
|
+
if (spawnListener) child.removeListener("spawn", spawnListener);
|
|
1747
|
+
resolve4(result);
|
|
1748
|
+
};
|
|
1749
|
+
try {
|
|
1750
|
+
child = spawn("runner-synchroniser", args, {
|
|
1751
|
+
env: opts.env ?? process.env,
|
|
1752
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1753
|
+
});
|
|
1754
|
+
} catch (error2) {
|
|
1755
|
+
finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
|
|
1756
|
+
return;
|
|
1757
|
+
}
|
|
1758
|
+
child.stdout?.setEncoding("utf8");
|
|
1759
|
+
child.stdout?.on("data", (chunk) => {
|
|
1760
|
+
stdout += chunk;
|
|
1761
|
+
});
|
|
1762
|
+
child.stderr?.setEncoding("utf8");
|
|
1763
|
+
child.stderr?.on("data", (chunk) => {
|
|
1764
|
+
stderr += chunk;
|
|
1765
|
+
});
|
|
1766
|
+
child.once("error", (error2) => {
|
|
1767
|
+
finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
|
|
1768
|
+
});
|
|
1769
|
+
child.once("close", (code) => {
|
|
1770
|
+
finish({ code, stdout, stderr, timedOut: false });
|
|
1771
|
+
});
|
|
1772
|
+
if (opts.signal) {
|
|
1773
|
+
const killChild = () => {
|
|
1774
|
+
if (child.pid === void 0) {
|
|
1775
|
+
if (!spawnListener) {
|
|
1776
|
+
spawnListener = killChild;
|
|
1777
|
+
child.once("spawn", spawnListener);
|
|
1778
|
+
}
|
|
1779
|
+
return;
|
|
1633
1780
|
}
|
|
1781
|
+
child.kill("SIGKILL");
|
|
1782
|
+
};
|
|
1783
|
+
abortListener = killChild;
|
|
1784
|
+
if (opts.signal.aborted) {
|
|
1785
|
+
abortListener();
|
|
1786
|
+
} else {
|
|
1787
|
+
opts.signal.addEventListener("abort", abortListener, { once: true });
|
|
1788
|
+
if (opts.signal.aborted) abortListener();
|
|
1634
1789
|
}
|
|
1635
|
-
} else if (platform === "linux") {
|
|
1636
|
-
const output = execSync(`readlink /proc/${pid}/cwd 2>/dev/null`, {
|
|
1637
|
-
encoding: "utf-8",
|
|
1638
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
1639
|
-
}).trim();
|
|
1640
|
-
if (output) return output;
|
|
1641
1790
|
}
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1791
|
+
timer.handle = setTimeout(
|
|
1792
|
+
() => {
|
|
1793
|
+
child.kill("SIGKILL");
|
|
1794
|
+
finish({ code: null, stdout, stderr, timedOut: true });
|
|
1795
|
+
},
|
|
1796
|
+
Math.max(0, opts.timeoutMs)
|
|
1797
|
+
);
|
|
1798
|
+
});
|
|
1645
1799
|
}
|
|
1646
|
-
|
|
1647
|
-
|
|
1800
|
+
|
|
1801
|
+
// src/lib/opencode/session-db-boot.ts
|
|
1802
|
+
var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
|
|
1803
|
+
var SESSION_DB_VERIFY_TIMEOUT_MS = 12e4;
|
|
1804
|
+
var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
|
|
1805
|
+
var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 120;
|
|
1806
|
+
function commandError(result) {
|
|
1807
|
+
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
1808
|
+
}
|
|
1809
|
+
function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
|
|
1810
|
+
options.reportRecovery({
|
|
1811
|
+
v: 1,
|
|
1812
|
+
event: "session_db_recovery",
|
|
1813
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1814
|
+
stage,
|
|
1815
|
+
outcome,
|
|
1816
|
+
severity: "error",
|
|
1817
|
+
reason,
|
|
1818
|
+
litestream_exit_code: litestreamExitCode,
|
|
1819
|
+
attempt: null,
|
|
1820
|
+
replica_objects: null,
|
|
1821
|
+
replica_bytes: null,
|
|
1822
|
+
quarantine_destination: null,
|
|
1823
|
+
quarantined_objects: null,
|
|
1824
|
+
quarantine_failed_objects: null,
|
|
1825
|
+
quarantined_bytes: null,
|
|
1826
|
+
verified_restore_point: null,
|
|
1827
|
+
restore_points_tried: null,
|
|
1828
|
+
provenance_reason: null,
|
|
1829
|
+
provenance_migration_delta: null,
|
|
1830
|
+
replication_suspended: stage === "restore"
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
function clearMarker(options) {
|
|
1834
|
+
if (!options.noReplicateMarker) return;
|
|
1648
1835
|
try {
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
})
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
} catch {
|
|
1836
|
+
unlinkSync2(options.noReplicateMarker);
|
|
1837
|
+
} catch (error2) {
|
|
1838
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return;
|
|
1839
|
+
options.log(
|
|
1840
|
+
`Could not clear the previous session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1841
|
+
"warn"
|
|
1842
|
+
);
|
|
1657
1843
|
}
|
|
1658
|
-
return false;
|
|
1659
1844
|
}
|
|
1660
|
-
function
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1845
|
+
function markNoReplicate(options, message) {
|
|
1846
|
+
if (options.noReplicateMarker) {
|
|
1847
|
+
try {
|
|
1848
|
+
mkdirSync(dirname2(options.noReplicateMarker), { recursive: true });
|
|
1849
|
+
writeFileSync(options.noReplicateMarker, "");
|
|
1850
|
+
} catch (error2) {
|
|
1851
|
+
options.log(
|
|
1852
|
+
`Could not write session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1853
|
+
"error"
|
|
1854
|
+
);
|
|
1665
1855
|
}
|
|
1666
1856
|
}
|
|
1667
|
-
|
|
1857
|
+
options.log(`SESSION-DB-NO-REPLICATE: ${message}`, "warn");
|
|
1668
1858
|
}
|
|
1669
|
-
function
|
|
1670
|
-
const
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
}).trim();
|
|
1680
|
-
if (pgrepOutput) {
|
|
1681
|
-
pids = pgrepOutput.split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => !isNaN(p));
|
|
1682
|
-
}
|
|
1683
|
-
} catch {
|
|
1684
|
-
try {
|
|
1685
|
-
const psOutput = execSync('ps aux | grep -E "opencode (serve|--port)" | grep -v grep', {
|
|
1686
|
-
encoding: "utf-8",
|
|
1687
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
1688
|
-
}).trim();
|
|
1689
|
-
if (psOutput) {
|
|
1690
|
-
for (const line of psOutput.split("\n")) {
|
|
1691
|
-
const parts = line.trim().split(/\s+/);
|
|
1692
|
-
if (parts.length >= 2) {
|
|
1693
|
-
const pid = parseInt(parts[1], 10);
|
|
1694
|
-
if (!isNaN(pid)) pids.push(pid);
|
|
1695
|
-
}
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
} catch (err) {
|
|
1699
|
-
console.warn(
|
|
1700
|
-
`findOpenCodeProcesses: ps fallback failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1701
|
-
);
|
|
1702
|
-
}
|
|
1703
|
-
}
|
|
1704
|
-
for (const pid of pids) {
|
|
1705
|
-
try {
|
|
1706
|
-
const lsofOutput = execSync(`lsof -Pan -p ${pid} -i TCP -sTCP:LISTEN 2>/dev/null`, {
|
|
1707
|
-
encoding: "utf-8",
|
|
1708
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
1709
|
-
}).trim();
|
|
1710
|
-
for (const line of lsofOutput.split("\n")) {
|
|
1711
|
-
const portMatch = line.match(/:(\d+)\s+\(LISTEN\)/);
|
|
1712
|
-
if (portMatch) {
|
|
1713
|
-
const port = parseInt(portMatch[1], 10);
|
|
1714
|
-
if (!isNaN(port) && !instances.some((i) => i.port === port)) {
|
|
1715
|
-
const cwd = getProcessCwd(pid);
|
|
1716
|
-
instances.push({ pid, port, cwd });
|
|
1717
|
-
}
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
} catch {
|
|
1721
|
-
}
|
|
1722
|
-
}
|
|
1859
|
+
function discardSessionDbDebris(options) {
|
|
1860
|
+
for (const path of [options.dbPath, `${options.dbPath}-wal`, `${options.dbPath}-shm`]) {
|
|
1861
|
+
try {
|
|
1862
|
+
unlinkSync2(path);
|
|
1863
|
+
} catch (error2) {
|
|
1864
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") continue;
|
|
1865
|
+
options.log(
|
|
1866
|
+
`Could not remove session-DB debris ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1867
|
+
"warn"
|
|
1868
|
+
);
|
|
1723
1869
|
}
|
|
1724
|
-
} catch (err) {
|
|
1725
|
-
console.warn(
|
|
1726
|
-
`findOpenCodeProcesses: process detection failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1727
|
-
);
|
|
1728
1870
|
}
|
|
1729
|
-
return instances;
|
|
1730
1871
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
const checks = OPENCODE_PORT_RANGE.map(async (port) => {
|
|
1734
|
-
const health = await checkOpenCodeHealth(port);
|
|
1735
|
-
if (health.healthy) {
|
|
1736
|
-
let pid = 0;
|
|
1737
|
-
try {
|
|
1738
|
-
const lsofOutput = execSync(`lsof -ti :${port} -sTCP:LISTEN 2>/dev/null`, {
|
|
1739
|
-
encoding: "utf-8",
|
|
1740
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
1741
|
-
}).trim();
|
|
1742
|
-
if (lsofOutput) {
|
|
1743
|
-
pid = parseInt(lsofOutput.split("\n")[0], 10) || 0;
|
|
1744
|
-
}
|
|
1745
|
-
} catch {
|
|
1746
|
-
}
|
|
1747
|
-
const cwd = pid ? getProcessCwd(pid) : void 0;
|
|
1748
|
-
return { pid, port, cwd, version: health.version };
|
|
1749
|
-
}
|
|
1750
|
-
return null;
|
|
1751
|
-
});
|
|
1752
|
-
const results = await Promise.all(checks);
|
|
1753
|
-
for (const result of results) {
|
|
1754
|
-
if (result) {
|
|
1755
|
-
instances.push(result);
|
|
1756
|
-
}
|
|
1757
|
-
}
|
|
1758
|
-
return instances;
|
|
1872
|
+
function splitDiagnostics(text) {
|
|
1873
|
+
return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
|
|
1759
1874
|
}
|
|
1760
|
-
|
|
1761
|
-
const
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1875
|
+
function logSynchroniserDiagnostics(result, options) {
|
|
1876
|
+
for (const line of splitDiagnostics(result.stderr)) options.log(line, "warn");
|
|
1877
|
+
}
|
|
1878
|
+
function parseSingleQuotedAssignment(line) {
|
|
1879
|
+
const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
|
|
1880
|
+
if (!match || !match[2].startsWith("'")) return null;
|
|
1881
|
+
const valueSource = match[2];
|
|
1882
|
+
let value = "";
|
|
1883
|
+
for (let index = 1; index < valueSource.length; index++) {
|
|
1884
|
+
const character = valueSource[index];
|
|
1885
|
+
if (character !== "'") {
|
|
1886
|
+
value += character;
|
|
1887
|
+
continue;
|
|
1767
1888
|
}
|
|
1889
|
+
if (index === valueSource.length - 1) return [match[1], value];
|
|
1890
|
+
if (valueSource.slice(index + 1, index + 4) !== "\\''") return null;
|
|
1891
|
+
value += "'";
|
|
1892
|
+
index += 3;
|
|
1768
1893
|
}
|
|
1769
|
-
|
|
1770
|
-
const scanned = await scanPortsForOpenCode();
|
|
1771
|
-
return scanned;
|
|
1772
|
-
}
|
|
1773
|
-
return healthy;
|
|
1894
|
+
return null;
|
|
1774
1895
|
}
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1896
|
+
function parseSynchroniserEnv(stdout) {
|
|
1897
|
+
const values = {};
|
|
1898
|
+
for (const line of stdout.split("\n")) {
|
|
1899
|
+
if (line.trim() === "") continue;
|
|
1900
|
+
const assignment = parseSingleQuotedAssignment(line);
|
|
1901
|
+
if (!assignment) return null;
|
|
1902
|
+
values[assignment[0]] = assignment[1];
|
|
1903
|
+
}
|
|
1904
|
+
return values;
|
|
1905
|
+
}
|
|
1906
|
+
function runCommand(command, args, options) {
|
|
1907
|
+
return new Promise((resolve4) => {
|
|
1908
|
+
let child;
|
|
1909
|
+
let stdout = "";
|
|
1910
|
+
let stderr = "";
|
|
1911
|
+
let settled = false;
|
|
1912
|
+
const finish = (result) => {
|
|
1913
|
+
if (settled) return;
|
|
1914
|
+
settled = true;
|
|
1915
|
+
if (timer) clearTimeout(timer);
|
|
1916
|
+
resolve4(result);
|
|
1917
|
+
};
|
|
1918
|
+
try {
|
|
1919
|
+
child = spawn2(command, args, {
|
|
1920
|
+
env: options.env,
|
|
1921
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1922
|
+
});
|
|
1923
|
+
} catch (error2) {
|
|
1924
|
+
resolve4({
|
|
1925
|
+
code: null,
|
|
1926
|
+
stdout,
|
|
1927
|
+
stderr: error2 instanceof Error ? error2.message : String(error2),
|
|
1928
|
+
timedOut: false
|
|
1929
|
+
});
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
child.stdout?.setEncoding("utf8");
|
|
1933
|
+
child.stdout?.on("data", (chunk) => {
|
|
1934
|
+
stdout += chunk;
|
|
1935
|
+
});
|
|
1936
|
+
child.stderr?.setEncoding("utf8");
|
|
1937
|
+
child.stderr?.on("data", (chunk) => {
|
|
1938
|
+
stderr += chunk;
|
|
1939
|
+
});
|
|
1940
|
+
child.once("error", (error2) => {
|
|
1941
|
+
finish({
|
|
1942
|
+
code: null,
|
|
1943
|
+
stdout,
|
|
1944
|
+
stderr: stderr === "" ? error2.message : `${stderr}
|
|
1945
|
+
${error2.message}`,
|
|
1946
|
+
timedOut: false
|
|
1947
|
+
});
|
|
1948
|
+
});
|
|
1949
|
+
child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
|
|
1950
|
+
const timer = setTimeout(
|
|
1951
|
+
() => {
|
|
1952
|
+
child.kill("SIGKILL");
|
|
1953
|
+
finish({ code: null, stdout, stderr, timedOut: true });
|
|
1954
|
+
},
|
|
1955
|
+
Math.max(0, options.timeoutMs)
|
|
1956
|
+
);
|
|
1788
1957
|
});
|
|
1789
|
-
return child;
|
|
1790
1958
|
}
|
|
1791
|
-
function
|
|
1792
|
-
|
|
1793
|
-
|
|
1959
|
+
async function ensureLitestreamConfig(options, env) {
|
|
1960
|
+
const configPath = options.litestreamConfig;
|
|
1961
|
+
if (!configPath) {
|
|
1962
|
+
markNoReplicate(options, "no Litestream configuration path was provided");
|
|
1963
|
+
reportRecord(
|
|
1964
|
+
"restore",
|
|
1965
|
+
"restore_misconfigured",
|
|
1966
|
+
"litestream_config_unavailable",
|
|
1967
|
+
null,
|
|
1968
|
+
options
|
|
1969
|
+
);
|
|
1970
|
+
return null;
|
|
1794
1971
|
}
|
|
1795
1972
|
try {
|
|
1796
|
-
if (
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1973
|
+
if (statSync2(configPath).size > 0) return configPath;
|
|
1974
|
+
} catch (error2) {
|
|
1975
|
+
if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
|
|
1976
|
+
options.log(
|
|
1977
|
+
`Could not inspect ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1978
|
+
"warn"
|
|
1979
|
+
);
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
const rendered = await runSynchroniser(["litestream-config"], {
|
|
1983
|
+
timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
|
|
1984
|
+
env
|
|
1985
|
+
});
|
|
1986
|
+
logSynchroniserDiagnostics(rendered, options);
|
|
1987
|
+
if (rendered.timedOut || rendered.code !== 0) {
|
|
1988
|
+
options.log(
|
|
1989
|
+
`Could not generate ${configPath}: runner-synchroniser litestream-config failed (${commandError(rendered)})`,
|
|
1990
|
+
"error"
|
|
1991
|
+
);
|
|
1992
|
+
markNoReplicate(options, `could not generate ${configPath}`);
|
|
1993
|
+
reportRecord(
|
|
1994
|
+
"restore",
|
|
1995
|
+
"restore_misconfigured",
|
|
1996
|
+
"litestream_config_unavailable",
|
|
1997
|
+
null,
|
|
1998
|
+
options
|
|
1999
|
+
);
|
|
2000
|
+
return null;
|
|
2001
|
+
}
|
|
2002
|
+
try {
|
|
2003
|
+
mkdirSync(dirname2(configPath), { recursive: true });
|
|
2004
|
+
writeFileSync(configPath, rendered.stdout);
|
|
2005
|
+
} catch (error2) {
|
|
2006
|
+
options.log(
|
|
2007
|
+
`Could not write ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
2008
|
+
"error"
|
|
2009
|
+
);
|
|
2010
|
+
markNoReplicate(options, `could not generate ${configPath}`);
|
|
2011
|
+
reportRecord(
|
|
2012
|
+
"restore",
|
|
2013
|
+
"restore_misconfigured",
|
|
2014
|
+
"litestream_config_unavailable",
|
|
2015
|
+
null,
|
|
2016
|
+
options
|
|
2017
|
+
);
|
|
2018
|
+
return null;
|
|
2019
|
+
}
|
|
2020
|
+
const version2 = await runCommand("litestream", ["version"], {
|
|
2021
|
+
env,
|
|
2022
|
+
timeoutMs: 1e4
|
|
2023
|
+
});
|
|
2024
|
+
const litestreamVersion = version2.code === 0 ? version2.stdout.trim() || "unknown" : "unknown";
|
|
2025
|
+
const regionEmpty = !/^\s*region:\s*\S+/m.test(rendered.stdout);
|
|
2026
|
+
options.log(
|
|
2027
|
+
`litestream ${litestreamVersion}; AWS_REGION=${env.AWS_REGION ?? "<unset>"} AWS_DEFAULT_REGION=${env.AWS_DEFAULT_REGION ?? "<unset>"}; rendered litestream.yml region empty: ${regionEmpty ? "yes" : "no"}`
|
|
2028
|
+
);
|
|
2029
|
+
return configPath;
|
|
2030
|
+
}
|
|
2031
|
+
function restoreGiveUp(options, reason, message, litestreamExitCode, outcome = "fresh_session_db") {
|
|
2032
|
+
discardSessionDbDebris(options);
|
|
2033
|
+
markNoReplicate(options, message);
|
|
2034
|
+
reportRecord("restore", outcome, reason, litestreamExitCode, options);
|
|
2035
|
+
}
|
|
2036
|
+
async function restoreSessionDb(options, configPath, env) {
|
|
2037
|
+
const restored = await runCommand(
|
|
2038
|
+
"litestream",
|
|
2039
|
+
["restore", "-config", configPath, "-if-db-not-exists", "-if-replica-exists", options.dbPath],
|
|
2040
|
+
{ env, timeoutMs: SESSION_DB_RESTORE_TIMEOUT_MS }
|
|
2041
|
+
);
|
|
2042
|
+
for (const line of splitDiagnostics(restored.stderr)) options.log(line, "warn");
|
|
2043
|
+
if (restored.timedOut || restored.code === 124 || restored.code === 137) {
|
|
2044
|
+
restoreGiveUp(
|
|
2045
|
+
options,
|
|
2046
|
+
"restore_deadline_exceeded",
|
|
2047
|
+
`SESSION-DB-RESTORE-TRUNCATED: litestream restore did not finish within ${SESSION_DB_RESTORE_TIMEOUT_MS}ms; opencode starts with a fresh session DB and nothing is replicated this boot`,
|
|
2048
|
+
restored.code ?? 124
|
|
2049
|
+
);
|
|
2050
|
+
return;
|
|
2051
|
+
}
|
|
2052
|
+
if (restored.code === null || restored.code === 125 || restored.code === 126 || restored.code === 127) {
|
|
2053
|
+
options.log(`litestream restore could not run (${commandError(restored)})`, "error");
|
|
2054
|
+
restoreGiveUp(
|
|
2055
|
+
options,
|
|
2056
|
+
"restore_tool_unusable",
|
|
2057
|
+
`restore tool is broken (${commandError(restored)}); opencode starts with a fresh session DB and nothing is replicated this boot`,
|
|
2058
|
+
restored.code
|
|
2059
|
+
);
|
|
2060
|
+
return;
|
|
2061
|
+
}
|
|
2062
|
+
const classified = await runSynchroniser(
|
|
2063
|
+
[
|
|
2064
|
+
"session-db-classify",
|
|
2065
|
+
String(restored.code ?? 1),
|
|
2066
|
+
"1",
|
|
2067
|
+
"--on-unusable-replica=leave",
|
|
2068
|
+
"--fresh-db-fallback"
|
|
2069
|
+
],
|
|
2070
|
+
{ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS, env }
|
|
2071
|
+
);
|
|
2072
|
+
logSynchroniserDiagnostics(classified, options);
|
|
2073
|
+
const classifyCode = classified.code;
|
|
2074
|
+
switch (classifyCode) {
|
|
2075
|
+
case 0:
|
|
2076
|
+
return;
|
|
2077
|
+
case 31:
|
|
2078
|
+
acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
|
|
2079
|
+
options.log(
|
|
2080
|
+
"SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and replicating into the existing prefix this boot",
|
|
2081
|
+
"warn"
|
|
2082
|
+
);
|
|
2083
|
+
return;
|
|
2084
|
+
case 32:
|
|
2085
|
+
acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
|
|
2086
|
+
discardSessionDbDebris(options);
|
|
2087
|
+
markNoReplicate(
|
|
2088
|
+
options,
|
|
2089
|
+
"session-db-classify asked for another restore attempt (32), but this boot has budget for only one; treating it as a give-up rather than retrying"
|
|
2090
|
+
);
|
|
2091
|
+
return;
|
|
2092
|
+
case 30:
|
|
2093
|
+
restoreGiveUp(
|
|
2094
|
+
options,
|
|
2095
|
+
"classification_fatal",
|
|
2096
|
+
"session-db-classify returned fatal (30); see the FATAL message above",
|
|
2097
|
+
restored.code,
|
|
2098
|
+
"restore_misconfigured"
|
|
2099
|
+
);
|
|
2100
|
+
return;
|
|
2101
|
+
default:
|
|
2102
|
+
restoreGiveUp(
|
|
2103
|
+
options,
|
|
2104
|
+
"classification_unrecognised",
|
|
2105
|
+
`session-db-classify exited ${classifyCode ?? "null"}, which is none of its documented answers`,
|
|
2106
|
+
restored.code
|
|
2107
|
+
);
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
async function verifySessionDb(options, configPath, env) {
|
|
2111
|
+
if (!options.noReplicateMarker || !fileExists(options.noReplicateMarker)) {
|
|
2112
|
+
const result = await runSynchroniser(["session-db-verify", configPath], {
|
|
2113
|
+
timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
|
|
2114
|
+
env: {
|
|
2115
|
+
...env,
|
|
2116
|
+
// The synchroniser reads this value in SECONDS. Keep this at 120, not
|
|
2117
|
+
// 120_000, so the walkback gives up before the outer process bound.
|
|
2118
|
+
EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
|
|
2119
|
+
SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
|
|
2120
|
+
)
|
|
2121
|
+
}
|
|
2122
|
+
});
|
|
2123
|
+
logSynchroniserDiagnostics(result, options);
|
|
2124
|
+
if (result.timedOut || result.code === 124 || result.code === 137) {
|
|
2125
|
+
options.log(
|
|
2126
|
+
`SESSION-DB-VERIFY-TIMEOUT: verification did not finish within its ${SESSION_DB_VERIFY_TIMEOUT_MS}ms deadline; continuing with the restored opencode.db as-is, unverified`,
|
|
2127
|
+
"warn"
|
|
2128
|
+
);
|
|
2129
|
+
return false;
|
|
2130
|
+
}
|
|
2131
|
+
if (result.code === 34) {
|
|
2132
|
+
reportRecord(
|
|
2133
|
+
"verify",
|
|
2134
|
+
"session_db_boot_refused",
|
|
2135
|
+
result.stderr.includes("SESSION-DB-LOCAL-DISCARD-FAILED") ? "local_discard_failed" : "replica_separation_unproven",
|
|
2136
|
+
null,
|
|
2137
|
+
options
|
|
2138
|
+
);
|
|
2139
|
+
return true;
|
|
2140
|
+
}
|
|
2141
|
+
if (result.code === 33) {
|
|
2142
|
+
options.log(
|
|
2143
|
+
"SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
|
|
2144
|
+
"warn"
|
|
2145
|
+
);
|
|
2146
|
+
return false;
|
|
2147
|
+
}
|
|
2148
|
+
if (result.code !== 0) {
|
|
2149
|
+
options.log(
|
|
2150
|
+
`SESSION-DB-VERIFY-UNKNOWN: session-db-verify exited ${result.code ?? "null"}, which is none of its documented answers; continuing with the restored opencode.db as-is`,
|
|
2151
|
+
"warn"
|
|
2152
|
+
);
|
|
2153
|
+
}
|
|
2154
|
+
return false;
|
|
2155
|
+
}
|
|
2156
|
+
options.log(
|
|
2157
|
+
"skipping session-DB verification: this boot's session DB was not proven safe to replicate",
|
|
2158
|
+
"debug"
|
|
2159
|
+
);
|
|
2160
|
+
return false;
|
|
2161
|
+
}
|
|
2162
|
+
function fileExists(path) {
|
|
2163
|
+
try {
|
|
2164
|
+
statSync2(path);
|
|
2165
|
+
return true;
|
|
2166
|
+
} catch (error2) {
|
|
2167
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return false;
|
|
2168
|
+
return true;
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
async function restoreAndVerifySessionDb(options) {
|
|
2172
|
+
const env = options.env ?? process.env;
|
|
2173
|
+
clearMarker(options);
|
|
2174
|
+
acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
|
|
2175
|
+
const synchroniserEnv = await runSynchroniser(["env"], {
|
|
2176
|
+
timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
|
|
2177
|
+
env
|
|
2178
|
+
});
|
|
2179
|
+
logSynchroniserDiagnostics(synchroniserEnv, options);
|
|
2180
|
+
if (synchroniserEnv.timedOut || synchroniserEnv.code !== 0) {
|
|
2181
|
+
options.log(
|
|
2182
|
+
`runner-synchroniser env could not resolve the session-DB configuration (${commandError(synchroniserEnv)})`,
|
|
2183
|
+
"error"
|
|
2184
|
+
);
|
|
2185
|
+
markNoReplicate(
|
|
2186
|
+
options,
|
|
2187
|
+
"could not resolve the runner-synchroniser configuration (see the ERROR above)"
|
|
2188
|
+
);
|
|
2189
|
+
reportRecord(
|
|
2190
|
+
"restore",
|
|
2191
|
+
"restore_misconfigured",
|
|
2192
|
+
"synchroniser_config_unresolved",
|
|
2193
|
+
null,
|
|
2194
|
+
options
|
|
2195
|
+
);
|
|
2196
|
+
return { verifyFatal: false };
|
|
2197
|
+
}
|
|
2198
|
+
const values = parseSynchroniserEnv(synchroniserEnv.stdout);
|
|
2199
|
+
if (!values) {
|
|
2200
|
+
markNoReplicate(
|
|
2201
|
+
options,
|
|
2202
|
+
"the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
|
|
2203
|
+
);
|
|
2204
|
+
reportRecord(
|
|
2205
|
+
"restore",
|
|
2206
|
+
"restore_misconfigured",
|
|
2207
|
+
"synchroniser_config_unevaluable",
|
|
2208
|
+
null,
|
|
2209
|
+
options
|
|
2210
|
+
);
|
|
2211
|
+
return { verifyFatal: false };
|
|
2212
|
+
}
|
|
2213
|
+
const synchroniserDbPath = values.OPENCODE_DB_PATH;
|
|
2214
|
+
if (!synchroniserDbPath) {
|
|
2215
|
+
markNoReplicate(
|
|
2216
|
+
options,
|
|
2217
|
+
"run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
|
|
2218
|
+
);
|
|
2219
|
+
reportRecord(
|
|
2220
|
+
"restore",
|
|
2221
|
+
"restore_misconfigured",
|
|
2222
|
+
"synchroniser_config_incomplete",
|
|
2223
|
+
null,
|
|
2224
|
+
options
|
|
2225
|
+
);
|
|
2226
|
+
return { verifyFatal: false };
|
|
2227
|
+
}
|
|
2228
|
+
if (resolvePath(synchroniserDbPath) !== resolvePath(options.dbPath)) {
|
|
2229
|
+
options.log(
|
|
2230
|
+
`runner-synchroniser reported OPENCODE_DB_PATH=${synchroniserDbPath}, but OpenCode uses ${options.dbPath}; continuing with OpenCode's session-DB path`,
|
|
2231
|
+
"warn"
|
|
2232
|
+
);
|
|
2233
|
+
}
|
|
2234
|
+
if (!values.PERSISTENCE_BUCKET) {
|
|
2235
|
+
options.log(
|
|
2236
|
+
"SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated.",
|
|
2237
|
+
"warn"
|
|
2238
|
+
);
|
|
2239
|
+
return { verifyFatal: false };
|
|
2240
|
+
}
|
|
2241
|
+
const configPath = await ensureLitestreamConfig(options, env);
|
|
2242
|
+
if (!configPath) return { verifyFatal: false };
|
|
2243
|
+
await restoreSessionDb(options, configPath, env);
|
|
2244
|
+
if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
|
|
2245
|
+
return { verifyFatal: false };
|
|
2246
|
+
}
|
|
2247
|
+
return { verifyFatal: await verifySessionDb(options, configPath, env) };
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
// src/lib/opencode/session-db-provenance.ts
|
|
2251
|
+
import { createRequire } from "module";
|
|
2252
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
2253
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
2254
|
+
var require2 = createRequire(import.meta.url);
|
|
2255
|
+
function readSessionDbMigrationIds(dbPath) {
|
|
2256
|
+
let db;
|
|
2257
|
+
try {
|
|
2258
|
+
const { DatabaseSync } = require2("node:sqlite");
|
|
2259
|
+
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
2260
|
+
const columns = db.prepare("PRAGMA table_info(migration)").all();
|
|
2261
|
+
const hasExpectedShape = columns.length === 2 && columns.some(
|
|
2262
|
+
(column) => column.name === "id" && typeof column.type === "string" && column.type.toUpperCase() === "TEXT" && column.pk === 1
|
|
2263
|
+
) && columns.some(
|
|
2264
|
+
(column) => column.name === "time_completed" && typeof column.type === "string" && column.type.toUpperCase() === "INTEGER" && column.notnull === 1 && column.pk === 0
|
|
2265
|
+
);
|
|
2266
|
+
if (!hasExpectedShape) {
|
|
2267
|
+
console.warn(`[readSessionDbMigrationIds] unsupported migration table shape in ${dbPath}`);
|
|
2268
|
+
return null;
|
|
2269
|
+
}
|
|
2270
|
+
const rows = db.prepare("SELECT id FROM migration ORDER BY id").all();
|
|
2271
|
+
if (rows.some((row) => typeof row.id !== "string")) return null;
|
|
2272
|
+
return rows.map((row) => row.id);
|
|
2273
|
+
} catch (error2) {
|
|
2274
|
+
console.warn(
|
|
2275
|
+
`[readSessionDbMigrationIds] could not read migration history from ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2276
|
+
);
|
|
2277
|
+
return null;
|
|
2278
|
+
} finally {
|
|
2279
|
+
try {
|
|
2280
|
+
db?.close();
|
|
2281
|
+
} catch (error2) {
|
|
1803
2282
|
console.warn(
|
|
1804
|
-
`
|
|
2283
|
+
`[readSessionDbMigrationIds] could not close ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
1805
2284
|
);
|
|
1806
2285
|
}
|
|
1807
|
-
}
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
function sessionDbProvenanceStatePath(homeDir, env) {
|
|
2289
|
+
const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
|
|
2290
|
+
return override || join3(homeDir, ".local", "state", "evident", "session-db-provenance.json");
|
|
2291
|
+
}
|
|
2292
|
+
function loadSessionDbProvenanceState(path) {
|
|
2293
|
+
let value;
|
|
2294
|
+
try {
|
|
2295
|
+
value = JSON.parse(readFileSync3(path, "utf8"));
|
|
2296
|
+
} catch (error2) {
|
|
2297
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return {};
|
|
2298
|
+
console.error(
|
|
2299
|
+
`[session-db-provenance] could not read ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2300
|
+
);
|
|
2301
|
+
return {};
|
|
2302
|
+
}
|
|
2303
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
2304
|
+
console.error(`[session-db-provenance] ignored malformed state in ${path}`);
|
|
2305
|
+
return {};
|
|
2306
|
+
}
|
|
2307
|
+
const state = {};
|
|
2308
|
+
for (const [dbPath, record] of Object.entries(value)) {
|
|
2309
|
+
if (!isSessionDbProvenanceRecord(record)) {
|
|
2310
|
+
console.error(`[session-db-provenance] ignored malformed state in ${path}`);
|
|
2311
|
+
return {};
|
|
2312
|
+
}
|
|
2313
|
+
state[dbPath] = record;
|
|
2314
|
+
}
|
|
2315
|
+
return state;
|
|
2316
|
+
}
|
|
2317
|
+
function saveSessionDbProvenanceState(path, state) {
|
|
2318
|
+
try {
|
|
2319
|
+
mkdirSync2(dirname3(path), { recursive: true });
|
|
2320
|
+
writeFileSync2(path, `${JSON.stringify(state, null, 2)}
|
|
2321
|
+
`, "utf8");
|
|
2322
|
+
} catch (error2) {
|
|
2323
|
+
console.error(
|
|
2324
|
+
`[session-db-provenance] could not write ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
2325
|
+
);
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
function evaluateSessionDbProvenance(input) {
|
|
2329
|
+
const { currentVersion, currentIds, previous } = input;
|
|
2330
|
+
if (!previous) return { anomaly: false, reason: null };
|
|
2331
|
+
const current = new Set(currentIds);
|
|
2332
|
+
const prior = new Set(previous.migrationIds);
|
|
2333
|
+
for (const id of prior) {
|
|
2334
|
+
if (!current.has(id)) return { anomaly: true, reason: "migration-history-regressed" };
|
|
2335
|
+
}
|
|
2336
|
+
if (current.size > prior.size && previous.opencodeVersion === currentVersion) {
|
|
2337
|
+
return { anomaly: true, reason: "foreign-version-migrations" };
|
|
2338
|
+
}
|
|
2339
|
+
return { anomaly: false, reason: null };
|
|
2340
|
+
}
|
|
2341
|
+
function checkSessionDbProvenance(input) {
|
|
2342
|
+
const { dbPath, currentVersion, homeDir, env } = input;
|
|
2343
|
+
const path = sessionDbProvenanceStatePath(homeDir, env);
|
|
2344
|
+
const state = loadSessionDbProvenanceState(path);
|
|
2345
|
+
const previous = state[dbPath];
|
|
2346
|
+
const currentIds = readSessionDbMigrationIds(dbPath);
|
|
2347
|
+
if (currentIds === null) {
|
|
2348
|
+
return {
|
|
2349
|
+
anomaly: false,
|
|
2350
|
+
reason: null,
|
|
2351
|
+
recordedVersion: previous?.opencodeVersion ?? null,
|
|
2352
|
+
migrationDelta: null
|
|
2353
|
+
};
|
|
2354
|
+
}
|
|
2355
|
+
const decision = evaluateSessionDbProvenance({ currentVersion, currentIds, previous });
|
|
2356
|
+
const migrationDelta = previous ? new Set(currentIds).size - new Set(previous.migrationIds).size : null;
|
|
2357
|
+
state[dbPath] = {
|
|
2358
|
+
opencodeVersion: currentVersion,
|
|
2359
|
+
migrationIds: currentIds,
|
|
2360
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2361
|
+
};
|
|
2362
|
+
saveSessionDbProvenanceState(path, state);
|
|
2363
|
+
return {
|
|
2364
|
+
...decision,
|
|
2365
|
+
recordedVersion: previous?.opencodeVersion ?? null,
|
|
2366
|
+
migrationDelta
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
2369
|
+
function isSessionDbProvenanceRecord(value) {
|
|
2370
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2371
|
+
const record = value;
|
|
2372
|
+
return typeof record.opencodeVersion === "string" && Array.isArray(record.migrationIds) && record.migrationIds.every((id) => typeof id === "string") && typeof record.updatedAt === "string";
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
// src/lib/opencode/opencode-version-gate.ts
|
|
2376
|
+
var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
|
|
2377
|
+
function isQueueValidatedVersion(version2) {
|
|
2378
|
+
if (!version2) return false;
|
|
2379
|
+
return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
|
|
2380
|
+
}
|
|
2381
|
+
function buildOpenCodeVersionWarning(version2) {
|
|
2382
|
+
if (isQueueValidatedVersion(version2)) return null;
|
|
2383
|
+
const detected = version2 ? `v${version2}` : "unknown";
|
|
2384
|
+
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
2385
|
+
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
// src/lib/opencode/process.ts
|
|
2389
|
+
import { execSync, spawn as spawn3 } from "child_process";
|
|
2390
|
+
|
|
2391
|
+
// src/lib/process-stop.ts
|
|
2392
|
+
async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
2393
|
+
if (!child.pid) {
|
|
2394
|
+
return { outcome: "not-running", code: child.exitCode, signal: child.signalCode };
|
|
2395
|
+
}
|
|
2396
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
2397
|
+
return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
|
|
2398
|
+
}
|
|
2399
|
+
return new Promise((resolve4, reject) => {
|
|
2400
|
+
let forced = false;
|
|
2401
|
+
let settled = false;
|
|
2402
|
+
const timer = setTimeout(() => {
|
|
2403
|
+
forced = true;
|
|
2404
|
+
try {
|
|
2405
|
+
sendKill();
|
|
2406
|
+
} catch (error2) {
|
|
2407
|
+
if (error2.code === "ESRCH") {
|
|
2408
|
+
finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
|
|
2409
|
+
} else {
|
|
2410
|
+
fail(error2);
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
}, timeoutMs);
|
|
2414
|
+
const finish = (result) => {
|
|
2415
|
+
if (settled) return;
|
|
2416
|
+
settled = true;
|
|
2417
|
+
clearTimeout(timer);
|
|
2418
|
+
child.removeListener("exit", onExit);
|
|
2419
|
+
resolve4(result);
|
|
2420
|
+
};
|
|
2421
|
+
const fail = (error2) => {
|
|
2422
|
+
if (settled) return;
|
|
2423
|
+
settled = true;
|
|
2424
|
+
clearTimeout(timer);
|
|
2425
|
+
child.removeListener("exit", onExit);
|
|
2426
|
+
reject(error2);
|
|
2427
|
+
};
|
|
2428
|
+
const onExit = (code, signal) => {
|
|
2429
|
+
finish({ outcome: forced ? "killed" : "exited", code, signal });
|
|
2430
|
+
};
|
|
2431
|
+
child.once("exit", onExit);
|
|
2432
|
+
try {
|
|
2433
|
+
sendTerm();
|
|
2434
|
+
} catch (error2) {
|
|
2435
|
+
if (error2.code === "ESRCH") {
|
|
2436
|
+
finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
|
|
2437
|
+
} else {
|
|
2438
|
+
fail(error2);
|
|
2439
|
+
}
|
|
2440
|
+
return;
|
|
2441
|
+
}
|
|
2442
|
+
});
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
// src/lib/opencode/process.ts
|
|
2446
|
+
var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
|
|
2447
|
+
function getProcessCwd(pid) {
|
|
2448
|
+
const platform = process.platform;
|
|
2449
|
+
try {
|
|
2450
|
+
if (platform === "darwin") {
|
|
2451
|
+
const output = execSync(`lsof -a -p ${pid} -d cwd -Fn 2>/dev/null`, {
|
|
2452
|
+
encoding: "utf-8",
|
|
2453
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2454
|
+
}).trim();
|
|
2455
|
+
const lines = output.split("\n");
|
|
2456
|
+
for (const line of lines) {
|
|
2457
|
+
if (line.startsWith("n") && !line.startsWith("n ")) {
|
|
2458
|
+
return line.slice(1);
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
} else if (platform === "linux") {
|
|
2462
|
+
const output = execSync(`readlink /proc/${pid}/cwd 2>/dev/null`, {
|
|
2463
|
+
encoding: "utf-8",
|
|
2464
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2465
|
+
}).trim();
|
|
2466
|
+
if (output) return output;
|
|
2467
|
+
}
|
|
2468
|
+
} catch {
|
|
2469
|
+
}
|
|
2470
|
+
return void 0;
|
|
2471
|
+
}
|
|
2472
|
+
function isPortInUse(port) {
|
|
2473
|
+
const platform = process.platform;
|
|
2474
|
+
try {
|
|
2475
|
+
if (platform === "darwin" || platform === "linux") {
|
|
2476
|
+
execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
|
|
2477
|
+
encoding: "utf-8",
|
|
2478
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2479
|
+
});
|
|
2480
|
+
return true;
|
|
2481
|
+
}
|
|
2482
|
+
} catch {
|
|
2483
|
+
}
|
|
2484
|
+
return false;
|
|
2485
|
+
}
|
|
2486
|
+
function findAvailablePort(startPort, maxAttempts = 10) {
|
|
2487
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
2488
|
+
const port = startPort + i;
|
|
2489
|
+
if (!isPortInUse(port)) {
|
|
2490
|
+
return port;
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
return null;
|
|
2494
|
+
}
|
|
2495
|
+
function findOpenCodeProcesses() {
|
|
2496
|
+
const instances = [];
|
|
2497
|
+
try {
|
|
2498
|
+
const platform = process.platform;
|
|
2499
|
+
if (platform === "darwin" || platform === "linux") {
|
|
2500
|
+
let pids = [];
|
|
2501
|
+
try {
|
|
2502
|
+
const pgrepOutput = execSync('pgrep -f "opencode serve|opencode-serve"', {
|
|
2503
|
+
encoding: "utf-8",
|
|
2504
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2505
|
+
}).trim();
|
|
2506
|
+
if (pgrepOutput) {
|
|
2507
|
+
pids = pgrepOutput.split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => !isNaN(p));
|
|
2508
|
+
}
|
|
2509
|
+
} catch {
|
|
2510
|
+
try {
|
|
2511
|
+
const psOutput = execSync('ps aux | grep -E "opencode (serve|--port)" | grep -v grep', {
|
|
2512
|
+
encoding: "utf-8",
|
|
2513
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2514
|
+
}).trim();
|
|
2515
|
+
if (psOutput) {
|
|
2516
|
+
for (const line of psOutput.split("\n")) {
|
|
2517
|
+
const parts = line.trim().split(/\s+/);
|
|
2518
|
+
if (parts.length >= 2) {
|
|
2519
|
+
const pid = parseInt(parts[1], 10);
|
|
2520
|
+
if (!isNaN(pid)) pids.push(pid);
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
}
|
|
2524
|
+
} catch (err) {
|
|
2525
|
+
console.warn(
|
|
2526
|
+
`findOpenCodeProcesses: ps fallback failed: ${err instanceof Error ? err.message : String(err)}`
|
|
2527
|
+
);
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
for (const pid of pids) {
|
|
2531
|
+
try {
|
|
2532
|
+
const lsofOutput = execSync(`lsof -Pan -p ${pid} -i TCP -sTCP:LISTEN 2>/dev/null`, {
|
|
2533
|
+
encoding: "utf-8",
|
|
2534
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2535
|
+
}).trim();
|
|
2536
|
+
for (const line of lsofOutput.split("\n")) {
|
|
2537
|
+
const portMatch = line.match(/:(\d+)\s+\(LISTEN\)/);
|
|
2538
|
+
if (portMatch) {
|
|
2539
|
+
const port = parseInt(portMatch[1], 10);
|
|
2540
|
+
if (!isNaN(port) && !instances.some((i) => i.port === port)) {
|
|
2541
|
+
const cwd = getProcessCwd(pid);
|
|
2542
|
+
instances.push({ pid, port, cwd });
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
} catch {
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
} catch (err) {
|
|
2551
|
+
console.warn(
|
|
2552
|
+
`findOpenCodeProcesses: process detection failed: ${err instanceof Error ? err.message : String(err)}`
|
|
2553
|
+
);
|
|
2554
|
+
}
|
|
2555
|
+
return instances;
|
|
2556
|
+
}
|
|
2557
|
+
async function scanPortsForOpenCode() {
|
|
2558
|
+
const instances = [];
|
|
2559
|
+
const checks = OPENCODE_PORT_RANGE.map(async (port) => {
|
|
2560
|
+
const health = await checkOpenCodeHealth(port);
|
|
2561
|
+
if (health.healthy) {
|
|
2562
|
+
let pid = 0;
|
|
2563
|
+
try {
|
|
2564
|
+
const lsofOutput = execSync(`lsof -ti :${port} -sTCP:LISTEN 2>/dev/null`, {
|
|
2565
|
+
encoding: "utf-8",
|
|
2566
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2567
|
+
}).trim();
|
|
2568
|
+
if (lsofOutput) {
|
|
2569
|
+
pid = parseInt(lsofOutput.split("\n")[0], 10) || 0;
|
|
2570
|
+
}
|
|
2571
|
+
} catch {
|
|
2572
|
+
}
|
|
2573
|
+
const cwd = pid ? getProcessCwd(pid) : void 0;
|
|
2574
|
+
return { pid, port, cwd, version: health.version };
|
|
2575
|
+
}
|
|
2576
|
+
return null;
|
|
2577
|
+
});
|
|
2578
|
+
const results = await Promise.all(checks);
|
|
2579
|
+
for (const result of results) {
|
|
2580
|
+
if (result) {
|
|
2581
|
+
instances.push(result);
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
return instances;
|
|
2585
|
+
}
|
|
2586
|
+
async function findHealthyOpenCodeInstances() {
|
|
2587
|
+
const processes = findOpenCodeProcesses();
|
|
2588
|
+
const healthy = [];
|
|
2589
|
+
for (const proc of processes) {
|
|
2590
|
+
const health = await checkOpenCodeHealth(proc.port);
|
|
2591
|
+
if (health.healthy) {
|
|
2592
|
+
healthy.push({ ...proc, version: health.version });
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
if (healthy.length === 0) {
|
|
2596
|
+
const scanned = await scanPortsForOpenCode();
|
|
2597
|
+
return scanned;
|
|
2598
|
+
}
|
|
2599
|
+
return healthy;
|
|
2600
|
+
}
|
|
2601
|
+
async function startOpenCode(port, options = {}) {
|
|
2602
|
+
let command = "opencode";
|
|
2603
|
+
const printLogs = options.inheritStdio ? ["--print-logs"] : [];
|
|
2604
|
+
let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
|
|
2605
|
+
try {
|
|
2606
|
+
execSync("which opencode", { stdio: "ignore" });
|
|
2607
|
+
} catch {
|
|
2608
|
+
command = "npx";
|
|
2609
|
+
args = [
|
|
2610
|
+
"opencode",
|
|
2611
|
+
"serve",
|
|
2612
|
+
"--port",
|
|
2613
|
+
port.toString(),
|
|
2614
|
+
"--hostname",
|
|
2615
|
+
"127.0.0.1",
|
|
2616
|
+
...printLogs
|
|
2617
|
+
];
|
|
2618
|
+
}
|
|
2619
|
+
const child = spawn3(command, args, {
|
|
2620
|
+
detached: true,
|
|
2621
|
+
stdio: options.inheritStdio ? "inherit" : "ignore",
|
|
2622
|
+
cwd: process.cwd()
|
|
2623
|
+
});
|
|
2624
|
+
return child;
|
|
2625
|
+
}
|
|
2626
|
+
function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
|
|
2627
|
+
const sendSignal = (signal) => {
|
|
2628
|
+
if (process.platform === "win32") {
|
|
2629
|
+
opencodeProcess.kill(signal);
|
|
2630
|
+
} else {
|
|
2631
|
+
process.kill(-opencodeProcess.pid, signal);
|
|
2632
|
+
}
|
|
2633
|
+
};
|
|
2634
|
+
return stopProcessAndWait(
|
|
2635
|
+
opencodeProcess,
|
|
2636
|
+
timeoutMs,
|
|
2637
|
+
() => sendSignal("SIGTERM"),
|
|
2638
|
+
() => sendSignal("SIGKILL")
|
|
2639
|
+
);
|
|
1808
2640
|
}
|
|
1809
2641
|
|
|
1810
2642
|
// src/lib/opencode/install.ts
|
|
@@ -2091,6 +2923,7 @@ async function createOpenCodeSession(port, directory) {
|
|
|
2091
2923
|
return data.id;
|
|
2092
2924
|
}
|
|
2093
2925
|
async function getModelAttachmentCapability(port, model) {
|
|
2926
|
+
const { model: baseModel } = splitModelVariant(model);
|
|
2094
2927
|
try {
|
|
2095
2928
|
const res = await timedFetch(`${opencodeBase(port)}/config/providers`);
|
|
2096
2929
|
if (!res.ok) {
|
|
@@ -2107,9 +2940,9 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
2107
2940
|
);
|
|
2108
2941
|
return null;
|
|
2109
2942
|
}
|
|
2110
|
-
const slash =
|
|
2111
|
-
const providerId = slash > 0 ?
|
|
2112
|
-
let modelId = slash > 0 ?
|
|
2943
|
+
const slash = baseModel ? baseModel.indexOf("/") : -1;
|
|
2944
|
+
const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
|
|
2945
|
+
let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
|
|
2113
2946
|
const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
|
|
2114
2947
|
let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
|
|
2115
2948
|
if (!provider && !providerId) {
|
|
@@ -2189,6 +3022,29 @@ async function buildFileParts(attachments, capable) {
|
|
|
2189
3022
|
}
|
|
2190
3023
|
return { parts, outcomes, capabilityUnknown };
|
|
2191
3024
|
}
|
|
3025
|
+
function splitModelVariant(raw) {
|
|
3026
|
+
const value = raw?.trim();
|
|
3027
|
+
if (!value) return {};
|
|
3028
|
+
const hashIndex = value.indexOf("#");
|
|
3029
|
+
if (hashIndex === -1) return { model: value };
|
|
3030
|
+
const model = value.slice(0, hashIndex).trim() || void 0;
|
|
3031
|
+
const variant = value.slice(hashIndex + 1).trim() || void 0;
|
|
3032
|
+
return { model, variant };
|
|
3033
|
+
}
|
|
3034
|
+
function applyModelOptions(body, options) {
|
|
3035
|
+
if (options?.agent) body.agent = options.agent;
|
|
3036
|
+
const { model, variant } = splitModelVariant(options?.model);
|
|
3037
|
+
if (model) {
|
|
3038
|
+
const slashIndex = model.indexOf("/");
|
|
3039
|
+
if (slashIndex !== -1) {
|
|
3040
|
+
body.model = {
|
|
3041
|
+
providerID: model.substring(0, slashIndex),
|
|
3042
|
+
modelID: model.substring(slashIndex + 1)
|
|
3043
|
+
};
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
if (variant) body.variant = variant;
|
|
3047
|
+
}
|
|
2192
3048
|
function messageText(m) {
|
|
2193
3049
|
if (!m || !Array.isArray(m.parts)) return "";
|
|
2194
3050
|
return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
|
|
@@ -2213,18 +3069,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
2213
3069
|
const body = {
|
|
2214
3070
|
parts
|
|
2215
3071
|
};
|
|
2216
|
-
|
|
2217
|
-
body.agent = options.agent;
|
|
2218
|
-
}
|
|
2219
|
-
if (options?.model) {
|
|
2220
|
-
const slashIndex = options.model.indexOf("/");
|
|
2221
|
-
if (slashIndex !== -1) {
|
|
2222
|
-
body.model = {
|
|
2223
|
-
providerID: options.model.substring(0, slashIndex),
|
|
2224
|
-
modelID: options.model.substring(slashIndex + 1)
|
|
2225
|
-
};
|
|
2226
|
-
}
|
|
2227
|
-
}
|
|
3072
|
+
applyModelOptions(body, options);
|
|
2228
3073
|
const res = await timedFetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
|
|
2229
3074
|
method: "POST",
|
|
2230
3075
|
headers: { "Content-Type": "application/json" },
|
|
@@ -2232,7 +3077,10 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
2232
3077
|
});
|
|
2233
3078
|
if (res.status < 200 || res.status >= 300) {
|
|
2234
3079
|
const text = await res.text().catch(() => "");
|
|
2235
|
-
|
|
3080
|
+
const { variant } = splitModelVariant(options?.model);
|
|
3081
|
+
throw new Error(
|
|
3082
|
+
`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
|
|
3083
|
+
);
|
|
2236
3084
|
}
|
|
2237
3085
|
const READ_BACK_ATTEMPTS = 5;
|
|
2238
3086
|
const READ_BACK_DELAY_MS = 150;
|
|
@@ -2256,7 +3104,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
2256
3104
|
}
|
|
2257
3105
|
}
|
|
2258
3106
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
2259
|
-
await new Promise((
|
|
3107
|
+
await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
|
|
2260
3108
|
}
|
|
2261
3109
|
}
|
|
2262
3110
|
return null;
|
|
@@ -2387,7 +3235,7 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
2387
3235
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
2388
3236
|
}
|
|
2389
3237
|
function isB2AbandonmentConfirmed(params) {
|
|
2390
|
-
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
3238
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false && params.rootOngoing === false;
|
|
2391
3239
|
}
|
|
2392
3240
|
function isAmbiguousTerminalFinish(m) {
|
|
2393
3241
|
if (completedOf(m) == null) return false;
|
|
@@ -2400,7 +3248,7 @@ function isAmbiguousFinishPinnedRunning(messages, userMessageId) {
|
|
|
2400
3248
|
return isAmbiguousTerminalFinish(reply);
|
|
2401
3249
|
}
|
|
2402
3250
|
function isAmbiguousFinishResolved(params) {
|
|
2403
|
-
return params.sessionOngoing === false || params.pinnedForMs >= params.maxPinnedMs;
|
|
3251
|
+
return params.sessionOngoing === false || params.sessionOngoing !== true && params.pinnedForMs >= params.maxPinnedMs;
|
|
2404
3252
|
}
|
|
2405
3253
|
function messageError(messages, userMessageId) {
|
|
2406
3254
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
@@ -2609,13 +3457,13 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
|
2609
3457
|
}
|
|
2610
3458
|
|
|
2611
3459
|
// src/lib/opencode/session-db-size.ts
|
|
2612
|
-
import { statSync as
|
|
2613
|
-
import { join as
|
|
3460
|
+
import { statSync as statSync3 } from "fs";
|
|
3461
|
+
import { join as join4 } from "path";
|
|
2614
3462
|
var LARGE_DB_THRESHOLD_BYTES = 268435456;
|
|
2615
3463
|
function statSessionDbBytes(homeDir) {
|
|
2616
|
-
const dbPath =
|
|
3464
|
+
const dbPath = join4(homeDir, ".local", "share", "opencode", "opencode.db");
|
|
2617
3465
|
try {
|
|
2618
|
-
return
|
|
3466
|
+
return statSync3(dbPath).size;
|
|
2619
3467
|
} catch (err) {
|
|
2620
3468
|
const isMissingFile = err instanceof Error && "code" in err && err.code === "ENOENT";
|
|
2621
3469
|
if (!isMissingFile) {
|
|
@@ -2641,11 +3489,11 @@ function buildSessionStoreSizeWarning(input) {
|
|
|
2641
3489
|
}
|
|
2642
3490
|
|
|
2643
3491
|
// src/lib/opencode/session-db-reclaim.ts
|
|
2644
|
-
import { statSync as
|
|
2645
|
-
import { dirname as
|
|
3492
|
+
import { statSync as statSync4, statfsSync } from "fs";
|
|
3493
|
+
import { dirname as dirname4 } from "path";
|
|
2646
3494
|
function insufficientSpaceReason(dbPath, requiredBytes) {
|
|
2647
3495
|
try {
|
|
2648
|
-
const fsStats = statfsSync(
|
|
3496
|
+
const fsStats = statfsSync(dirname4(dbPath));
|
|
2649
3497
|
const availableBytes = fsStats.bavail * fsStats.bsize;
|
|
2650
3498
|
if (availableBytes < requiredBytes) {
|
|
2651
3499
|
return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
|
|
@@ -2714,7 +3562,7 @@ async function reclaimSessionDbSpace(input) {
|
|
|
2714
3562
|
);
|
|
2715
3563
|
return { ok: false, skipped: "full-vacuum-blocked" };
|
|
2716
3564
|
}
|
|
2717
|
-
const fileBytesForGuard =
|
|
3565
|
+
const fileBytesForGuard = statSync4(dbPath).size;
|
|
2718
3566
|
const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
|
|
2719
3567
|
if (skipReason !== null) {
|
|
2720
3568
|
console.warn(
|
|
@@ -2842,12 +3690,12 @@ var StreamForwarder = class {
|
|
|
2842
3690
|
let endBody;
|
|
2843
3691
|
if (has_body) {
|
|
2844
3692
|
const chunks = [];
|
|
2845
|
-
bodyPromise = new Promise((
|
|
3693
|
+
bodyPromise = new Promise((resolve4) => {
|
|
2846
3694
|
pushBody = (buf) => {
|
|
2847
3695
|
chunks.push(buf);
|
|
2848
3696
|
};
|
|
2849
3697
|
endBody = () => {
|
|
2850
|
-
|
|
3698
|
+
resolve4(Buffer.concat(chunks));
|
|
2851
3699
|
};
|
|
2852
3700
|
});
|
|
2853
3701
|
}
|
|
@@ -2976,7 +3824,7 @@ function connectTunnel(options) {
|
|
|
2976
3824
|
} = options;
|
|
2977
3825
|
const tunnelUrl = getTunnelUrlConfig();
|
|
2978
3826
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
2979
|
-
return new Promise((
|
|
3827
|
+
return new Promise((resolve4, reject) => {
|
|
2980
3828
|
const ws = new WebSocket2(url, {
|
|
2981
3829
|
headers: {
|
|
2982
3830
|
Authorization: authHeader
|
|
@@ -3027,8 +3875,8 @@ function connectTunnel(options) {
|
|
|
3027
3875
|
try {
|
|
3028
3876
|
message = JSON.parse(data.toString());
|
|
3029
3877
|
} catch (error2) {
|
|
3030
|
-
const
|
|
3031
|
-
onError?.(`Failed to handle message: ${
|
|
3878
|
+
const errorMessage2 = error2 instanceof Error ? error2.message : "Unknown error";
|
|
3879
|
+
onError?.(`Failed to handle message: ${errorMessage2}`);
|
|
3032
3880
|
return;
|
|
3033
3881
|
}
|
|
3034
3882
|
if (isStreamFrame(message)) {
|
|
@@ -3040,7 +3888,7 @@ function connectTunnel(options) {
|
|
|
3040
3888
|
clearTimeout(connectionTimeout);
|
|
3041
3889
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
3042
3890
|
onConnected?.(connectedAgentId);
|
|
3043
|
-
|
|
3891
|
+
resolve4({
|
|
3044
3892
|
ws,
|
|
3045
3893
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
3046
3894
|
});
|
|
@@ -3171,10 +4019,10 @@ var RunnerConnection = class {
|
|
|
3171
4019
|
};
|
|
3172
4020
|
|
|
3173
4021
|
// src/lib/tunnel/ready-marker.ts
|
|
3174
|
-
import { writeFileSync } from "fs";
|
|
4022
|
+
import { writeFileSync as writeFileSync3 } from "fs";
|
|
3175
4023
|
function writeTunnelReadyMarker(path, agentId) {
|
|
3176
4024
|
try {
|
|
3177
|
-
|
|
4025
|
+
writeFileSync3(path, `${agentId}
|
|
3178
4026
|
`);
|
|
3179
4027
|
return { ok: true };
|
|
3180
4028
|
} catch (error2) {
|
|
@@ -3182,10 +4030,52 @@ function writeTunnelReadyMarker(path, agentId) {
|
|
|
3182
4030
|
}
|
|
3183
4031
|
}
|
|
3184
4032
|
|
|
4033
|
+
// src/lib/replication.ts
|
|
4034
|
+
import { spawn as spawn4 } from "child_process";
|
|
4035
|
+
function startSessionDbReplication(configPath) {
|
|
4036
|
+
return spawn4("litestream", ["replicate", "-config", configPath], {
|
|
4037
|
+
stdio: "inherit"
|
|
4038
|
+
});
|
|
4039
|
+
}
|
|
4040
|
+
async function stopSessionDbReplication(child, timeoutMs) {
|
|
4041
|
+
return stopProcessAndWait(
|
|
4042
|
+
child,
|
|
4043
|
+
timeoutMs,
|
|
4044
|
+
() => child.kill("SIGTERM"),
|
|
4045
|
+
() => child.kill("SIGKILL")
|
|
4046
|
+
);
|
|
4047
|
+
}
|
|
4048
|
+
|
|
4049
|
+
// src/lib/process-liveness.ts
|
|
4050
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
4051
|
+
function isProcessAlive(pid) {
|
|
4052
|
+
try {
|
|
4053
|
+
process.kill(pid, 0);
|
|
4054
|
+
} catch (error2) {
|
|
4055
|
+
const code = error2.code;
|
|
4056
|
+
if (code === "ESRCH") return false;
|
|
4057
|
+
if (code === "EPERM") return true;
|
|
4058
|
+
console.error(
|
|
4059
|
+
`[process-liveness] could not probe process ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4060
|
+
);
|
|
4061
|
+
return false;
|
|
4062
|
+
}
|
|
4063
|
+
if (process.platform !== "linux") return true;
|
|
4064
|
+
try {
|
|
4065
|
+
const status2 = readFileSync4(`/proc/${pid}/status`, "utf8");
|
|
4066
|
+
return !/^State:\s+Z(?:\s|$)/m.test(status2);
|
|
4067
|
+
} catch (error2) {
|
|
4068
|
+
console.error(
|
|
4069
|
+
`[process-liveness] could not inspect /proc/${pid}/status: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4070
|
+
);
|
|
4071
|
+
return true;
|
|
4072
|
+
}
|
|
4073
|
+
}
|
|
4074
|
+
|
|
3185
4075
|
// src/lib/openai-usage.ts
|
|
3186
|
-
import { readFileSync as
|
|
3187
|
-
import { homedir as
|
|
3188
|
-
import { join as
|
|
4076
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
4077
|
+
import { homedir as homedir3 } from "os";
|
|
4078
|
+
import { join as join5 } from "path";
|
|
3189
4079
|
var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
3190
4080
|
var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
|
|
3191
4081
|
var OpenAiUsageError = class extends Error {
|
|
@@ -3199,7 +4089,7 @@ function isLocalCredentialProblem2(err) {
|
|
|
3199
4089
|
}
|
|
3200
4090
|
function readOpenCodeChatGptCredentials() {
|
|
3201
4091
|
try {
|
|
3202
|
-
const raw =
|
|
4092
|
+
const raw = readFileSync5(join5(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
|
|
3203
4093
|
let parsed;
|
|
3204
4094
|
try {
|
|
3205
4095
|
parsed = JSON.parse(raw);
|
|
@@ -3221,6 +4111,23 @@ function readOpenCodeChatGptCredentials() {
|
|
|
3221
4111
|
return null;
|
|
3222
4112
|
}
|
|
3223
4113
|
}
|
|
4114
|
+
function parseChatGptIdentity(accessToken) {
|
|
4115
|
+
const segments = accessToken.split(".");
|
|
4116
|
+
if (segments.length !== 3) return null;
|
|
4117
|
+
let payload;
|
|
4118
|
+
try {
|
|
4119
|
+
const parsed = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8"));
|
|
4120
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
|
4121
|
+
payload = parsed;
|
|
4122
|
+
} catch {
|
|
4123
|
+
return null;
|
|
4124
|
+
}
|
|
4125
|
+
const profile = payload["https://api.openai.com/profile"];
|
|
4126
|
+
const auth = payload["https://api.openai.com/auth"];
|
|
4127
|
+
const ownerEmail = typeof profile?.email === "string" ? profile.email.trim() || null : null;
|
|
4128
|
+
const planType = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type.trim() || null : null;
|
|
4129
|
+
return ownerEmail === null && planType === null ? null : { ownerEmail, planType };
|
|
4130
|
+
}
|
|
3224
4131
|
function toWindow2(headers, name) {
|
|
3225
4132
|
const utilizationHeader = headers.get(`x-codex-${name}-used-percent`);
|
|
3226
4133
|
const windowMinutesHeader = headers.get(`x-codex-${name}-window-minutes`);
|
|
@@ -3296,6 +4203,7 @@ async function getOpenAiUsage(port) {
|
|
|
3296
4203
|
"credentials_expired"
|
|
3297
4204
|
);
|
|
3298
4205
|
}
|
|
4206
|
+
const subscription = parseChatGptIdentity(credentials2.accessToken);
|
|
3299
4207
|
const models = await resolveProbeModels(port);
|
|
3300
4208
|
if (models.length === 0) {
|
|
3301
4209
|
throw new OpenAiUsageError("No supported OpenAI probe model is available.", "no_probe_model");
|
|
@@ -3328,7 +4236,7 @@ async function getOpenAiUsage(port) {
|
|
|
3328
4236
|
"no_usable_window"
|
|
3329
4237
|
);
|
|
3330
4238
|
}
|
|
3331
|
-
return usage;
|
|
4239
|
+
return { ...usage, subscription };
|
|
3332
4240
|
}
|
|
3333
4241
|
if (res.status === 401) {
|
|
3334
4242
|
throw new OpenAiUsageError(
|
|
@@ -3572,15 +4480,15 @@ function createResourceUsageCollector(homeDir) {
|
|
|
3572
4480
|
}
|
|
3573
4481
|
|
|
3574
4482
|
// src/lib/channels/driver.ts
|
|
3575
|
-
import { homedir as
|
|
4483
|
+
import { homedir as homedir4 } from "os";
|
|
3576
4484
|
|
|
3577
4485
|
// src/lib/runner-file-sync.ts
|
|
3578
|
-
import { join as
|
|
4486
|
+
import { join as join7 } from "path";
|
|
3579
4487
|
|
|
3580
4488
|
// src/lib/file-push.ts
|
|
3581
4489
|
import { randomUUID } from "crypto";
|
|
3582
4490
|
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
3583
|
-
import { basename, dirname as
|
|
4491
|
+
import { basename, dirname as dirname5, isAbsolute, join as join6, relative, resolve as resolve2, sep } from "path";
|
|
3584
4492
|
var FILE_MODE = 384;
|
|
3585
4493
|
var DIRECTORY_MODE = 448;
|
|
3586
4494
|
async function writePushedFile(request) {
|
|
@@ -3611,9 +4519,9 @@ async function writePushedFile(request) {
|
|
|
3611
4519
|
}
|
|
3612
4520
|
try {
|
|
3613
4521
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
3614
|
-
|
|
4522
|
+
dirname5(candidate)
|
|
3615
4523
|
);
|
|
3616
|
-
const realTarget =
|
|
4524
|
+
const realTarget = join6(existingAncestor, ...missingSegments, basename(candidate));
|
|
3617
4525
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
3618
4526
|
if (allowedDirectory === null) {
|
|
3619
4527
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -3623,8 +4531,8 @@ async function writePushedFile(request) {
|
|
|
3623
4531
|
}
|
|
3624
4532
|
if (missingSegments.length > 0) {
|
|
3625
4533
|
await createMissingDirectories(existingAncestor, missingSegments);
|
|
3626
|
-
const realParent = await realpath(
|
|
3627
|
-
if (realParent !==
|
|
4534
|
+
const realParent = await realpath(dirname5(realTarget));
|
|
4535
|
+
if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
3628
4536
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
3629
4537
|
path: realTarget,
|
|
3630
4538
|
bytes,
|
|
@@ -3649,7 +4557,7 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
3649
4557
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
3650
4558
|
return null;
|
|
3651
4559
|
}
|
|
3652
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
4560
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
3653
4561
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
3654
4562
|
return null;
|
|
3655
4563
|
}
|
|
@@ -3667,7 +4575,7 @@ async function resolveNearestExistingAncestor(directory) {
|
|
|
3667
4575
|
try {
|
|
3668
4576
|
return { existingAncestor: await realpath(current), missingSegments };
|
|
3669
4577
|
} catch (err) {
|
|
3670
|
-
const parent =
|
|
4578
|
+
const parent = dirname5(current);
|
|
3671
4579
|
if (err.code !== "ENOENT" || parent === current) {
|
|
3672
4580
|
throw err;
|
|
3673
4581
|
}
|
|
@@ -3722,13 +4630,13 @@ function contains(realDirectory, realTarget) {
|
|
|
3722
4630
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
3723
4631
|
let current = existingAncestor;
|
|
3724
4632
|
for (const segment of missingSegments) {
|
|
3725
|
-
current =
|
|
4633
|
+
current = join6(current, segment);
|
|
3726
4634
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
3727
4635
|
await chmod(current, DIRECTORY_MODE);
|
|
3728
4636
|
}
|
|
3729
4637
|
}
|
|
3730
4638
|
async function writeAtomically(realTarget, content) {
|
|
3731
|
-
const temporaryPath =
|
|
4639
|
+
const temporaryPath = join6(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
3732
4640
|
let handle;
|
|
3733
4641
|
try {
|
|
3734
4642
|
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
@@ -3858,12 +4766,12 @@ var NOT_APPLIED = {
|
|
|
3858
4766
|
opencodeAuthApplied: false
|
|
3859
4767
|
};
|
|
3860
4768
|
function isClaudeCredentialPath(requestedPath, homeDir) {
|
|
3861
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
3862
|
-
return expanded ===
|
|
4769
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
4770
|
+
return expanded === join7(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
|
|
3863
4771
|
}
|
|
3864
4772
|
function isOpenCodeAuthPath(requestedPath, homeDir) {
|
|
3865
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
3866
|
-
return expanded ===
|
|
4773
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
4774
|
+
return expanded === join7(homeDir, ...OPENCODE_AUTH_SEGMENTS);
|
|
3867
4775
|
}
|
|
3868
4776
|
async function applyOne(options, file) {
|
|
3869
4777
|
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
@@ -4390,6 +5298,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4390
5298
|
* and stops opencode.
|
|
4391
5299
|
*/
|
|
4392
5300
|
stopped = false;
|
|
5301
|
+
recycleRequestedFlag = false;
|
|
4393
5302
|
constructor(config) {
|
|
4394
5303
|
this.agentId = config.agentId;
|
|
4395
5304
|
this.port = config.port;
|
|
@@ -4409,7 +5318,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4409
5318
|
this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
4410
5319
|
this.now = config.now ?? (() => Date.now());
|
|
4411
5320
|
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
4412
|
-
this.homeDir = config.homeDir ??
|
|
5321
|
+
this.homeDir = config.homeDir ?? homedir4();
|
|
4413
5322
|
this.maxActiveSessions = config.maxActiveSessions;
|
|
4414
5323
|
this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
|
|
4415
5324
|
this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
|
|
@@ -4495,6 +5404,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4495
5404
|
let dispatched = 0;
|
|
4496
5405
|
try {
|
|
4497
5406
|
const conversations = await this.getPendingConversations();
|
|
5407
|
+
if (this.recycleRequestedFlag) {
|
|
5408
|
+
this.stop();
|
|
5409
|
+
}
|
|
4498
5410
|
if (conversations.length > 0) {
|
|
4499
5411
|
const total = conversations.reduce((sum, c) => sum + (c.pending_message_count ?? 0), 0);
|
|
4500
5412
|
this.log({
|
|
@@ -4623,6 +5535,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4623
5535
|
stop() {
|
|
4624
5536
|
this.stopped = true;
|
|
4625
5537
|
}
|
|
5538
|
+
/**
|
|
5539
|
+
* The server clears this request when a new MicroVM identity is recorded, so a
|
|
5540
|
+
* same-VM tunnel reconnect does not consume it. This is a plain read rather
|
|
5541
|
+
* than a consume; `run.ts` guards the action once-only.
|
|
5542
|
+
*/
|
|
5543
|
+
get recycleRequested() {
|
|
5544
|
+
return this.recycleRequestedFlag;
|
|
5545
|
+
}
|
|
4626
5546
|
/**
|
|
4627
5547
|
* Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
|
|
4628
5548
|
* graceful shutdown, so a turn whose reply is ready — or completes within the
|
|
@@ -4760,7 +5680,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4760
5680
|
this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
|
|
4761
5681
|
break;
|
|
4762
5682
|
}
|
|
4763
|
-
const
|
|
5683
|
+
const errorMessage2 = err instanceof Error ? err.message : String(err);
|
|
4764
5684
|
this.sessions.delete(conv.id);
|
|
4765
5685
|
this.supersede(conv.id, sessionId);
|
|
4766
5686
|
this.log({
|
|
@@ -4769,7 +5689,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4769
5689
|
conversation_id: conv.id,
|
|
4770
5690
|
message_id: message.id
|
|
4771
5691
|
});
|
|
4772
|
-
await this.markFailed(conv.id, message.id, null,
|
|
5692
|
+
await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
|
|
4773
5693
|
this.log({
|
|
4774
5694
|
level: "warn",
|
|
4775
5695
|
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)}`,
|
|
@@ -4780,7 +5700,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4780
5700
|
});
|
|
4781
5701
|
this.log({
|
|
4782
5702
|
level: "error",
|
|
4783
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
5703
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage2}`,
|
|
4784
5704
|
conversation_id: conv.id,
|
|
4785
5705
|
message_id: message.id
|
|
4786
5706
|
});
|
|
@@ -4801,14 +5721,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4801
5721
|
this.unconfirmedDispatchFailures.delete(message.id);
|
|
4802
5722
|
this.sessions.delete(conv.id);
|
|
4803
5723
|
this.supersede(conv.id, sessionId);
|
|
4804
|
-
const
|
|
5724
|
+
const errorMessage2 = `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.`;
|
|
4805
5725
|
this.log({
|
|
4806
5726
|
level: "error",
|
|
4807
|
-
message:
|
|
5727
|
+
message: errorMessage2,
|
|
4808
5728
|
conversation_id: conv.id,
|
|
4809
5729
|
message_id: message.id
|
|
4810
5730
|
});
|
|
4811
|
-
await this.markFailed(conv.id, message.id, null,
|
|
5731
|
+
await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
|
|
4812
5732
|
this.log({
|
|
4813
5733
|
level: "warn",
|
|
4814
5734
|
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)}`,
|
|
@@ -5676,6 +6596,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5676
6596
|
deliveryDeadlineAnchored: false,
|
|
5677
6597
|
b2PinnedSinceMs: 0,
|
|
5678
6598
|
b2LastDescendantCheckMs: 0,
|
|
6599
|
+
b2RootOngoingHeldLogged: false,
|
|
5679
6600
|
b2AbandonedSignalled: false,
|
|
5680
6601
|
ambiguousPinnedSinceMs: 0,
|
|
5681
6602
|
ambiguousResolved: false
|
|
@@ -5770,6 +6691,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5770
6691
|
deliveryDeadlineAnchored: false,
|
|
5771
6692
|
b2PinnedSinceMs: 0,
|
|
5772
6693
|
b2LastDescendantCheckMs: 0,
|
|
6694
|
+
b2RootOngoingHeldLogged: false,
|
|
5773
6695
|
b2AbandonedSignalled: false,
|
|
5774
6696
|
ambiguousPinnedSinceMs: 0,
|
|
5775
6697
|
ambiguousResolved: false
|
|
@@ -6123,6 +7045,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6123
7045
|
if (snapshotReadable) {
|
|
6124
7046
|
inFlight.b2PinnedSinceMs = 0;
|
|
6125
7047
|
inFlight.b2LastDescendantCheckMs = 0;
|
|
7048
|
+
inFlight.b2RootOngoingHeldLogged = false;
|
|
6126
7049
|
inFlight.b2AbandonedSignalled = false;
|
|
6127
7050
|
}
|
|
6128
7051
|
} else {
|
|
@@ -6134,11 +7057,15 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6134
7057
|
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
6135
7058
|
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
6136
7059
|
inFlight.b2LastDescendantCheckMs = this.now();
|
|
6137
|
-
const descendantOngoing = await
|
|
7060
|
+
const [descendantOngoing, rootOngoing] = await Promise.all([
|
|
7061
|
+
this.isAnyDescendantSessionOngoing(sessionId),
|
|
7062
|
+
isSessionOngoing(this.port, sessionId)
|
|
7063
|
+
]);
|
|
6138
7064
|
if (isB2AbandonmentConfirmed({
|
|
6139
7065
|
pinnedForMs,
|
|
6140
7066
|
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
6141
|
-
descendantOngoing
|
|
7067
|
+
descendantOngoing,
|
|
7068
|
+
rootOngoing
|
|
6142
7069
|
})) {
|
|
6143
7070
|
inFlight.b2AbandonedSignalled = true;
|
|
6144
7071
|
this.log({
|
|
@@ -6147,12 +7074,26 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6147
7074
|
conversation_id: conv.id,
|
|
6148
7075
|
message_id: id
|
|
6149
7076
|
});
|
|
7077
|
+
const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
|
|
6150
7078
|
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
6151
|
-
watched_for_ms: pinnedForMs
|
|
7079
|
+
watched_for_ms: pinnedForMs,
|
|
7080
|
+
finish: reply?.info?.finish ?? reply?.finish,
|
|
7081
|
+
...rootOngoing != null ? { root_ongoing: rootOngoing } : {},
|
|
7082
|
+
...descendantOngoing != null ? { descendant_ongoing: descendantOngoing } : {},
|
|
7083
|
+
opencode_message_id: inFlight.opencodeMessageId
|
|
6152
7084
|
});
|
|
6153
7085
|
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
6154
7086
|
return;
|
|
6155
7087
|
}
|
|
7088
|
+
if (rootOngoing === true && !inFlight.b2RootOngoingHeldLogged) {
|
|
7089
|
+
inFlight.b2RootOngoingHeldLogged = true;
|
|
7090
|
+
this.log({
|
|
7091
|
+
level: "warn",
|
|
7092
|
+
message: `Message ${id.slice(0, 8)} b2-pinned for ${Math.round(pinnedForMs / 1e3)}s with root_ongoing=${rootOngoing} and descendant_ongoing=${descendantOngoing} \u2014 holding until OpenCode confirms the root is idle`,
|
|
7093
|
+
conversation_id: conv.id,
|
|
7094
|
+
message_id: id
|
|
7095
|
+
});
|
|
7096
|
+
}
|
|
6156
7097
|
}
|
|
6157
7098
|
}
|
|
6158
7099
|
const ambiguousPinnedNow = activelyRunning && isAmbiguousFinishPinnedRunning(messages, inFlight.opencodeMessageId);
|
|
@@ -6751,14 +7692,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6751
7692
|
this.unconfirmedDispatchFailures.delete(row.id);
|
|
6752
7693
|
this.sessions.delete(readoptConv.id);
|
|
6753
7694
|
this.supersede(readoptConv.id, sessionId);
|
|
6754
|
-
const
|
|
7695
|
+
const errorMessage2 = `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.`;
|
|
6755
7696
|
this.log({
|
|
6756
7697
|
level: "error",
|
|
6757
|
-
message:
|
|
7698
|
+
message: errorMessage2,
|
|
6758
7699
|
conversation_id: row.conversation_id,
|
|
6759
7700
|
message_id: row.id
|
|
6760
7701
|
});
|
|
6761
|
-
await this.markFailed(row.conversation_id, row.id, null,
|
|
7702
|
+
await this.markFailed(row.conversation_id, row.id, null, errorMessage2).catch((markErr) => {
|
|
6762
7703
|
this.log({
|
|
6763
7704
|
level: "warn",
|
|
6764
7705
|
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)}`,
|
|
@@ -7373,6 +8314,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
7373
8314
|
throw new Error(`Failed to get pending conversations: HTTP ${res.status}`);
|
|
7374
8315
|
}
|
|
7375
8316
|
const data = await res.json();
|
|
8317
|
+
this.recycleRequestedFlag = data.recycle_requested === true;
|
|
7376
8318
|
let conversations = data.conversations;
|
|
7377
8319
|
if (this.conversationFilter) {
|
|
7378
8320
|
conversations = conversations.filter((c) => c.id === this.conversationFilter);
|
|
@@ -7797,96 +8739,641 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
7797
8739
|
blank();
|
|
7798
8740
|
throw new Error(`OpenCode not running on port ${ctx.port}`);
|
|
7799
8741
|
}
|
|
7800
|
-
if (!isOpenCodeInstalled()) {
|
|
7801
|
-
if (!ctx.interactive) {
|
|
7802
|
-
throw new Error("OpenCode is not installed. Install it with: npm install -g opencode-ai");
|
|
7803
|
-
}
|
|
7804
|
-
const result = await promptOpenCodeInstall(true);
|
|
7805
|
-
if (result === "exit") process.exit(0);
|
|
7806
|
-
if (result !== "installed" && !isOpenCodeInstalled()) {
|
|
7807
|
-
throw new Error("OpenCode is not installed");
|
|
8742
|
+
if (!isOpenCodeInstalled()) {
|
|
8743
|
+
if (!ctx.interactive) {
|
|
8744
|
+
throw new Error("OpenCode is not installed. Install it with: npm install -g opencode-ai");
|
|
8745
|
+
}
|
|
8746
|
+
const result = await promptOpenCodeInstall(true);
|
|
8747
|
+
if (result === "exit") process.exit(0);
|
|
8748
|
+
if (result !== "installed" && !isOpenCodeInstalled()) {
|
|
8749
|
+
throw new Error("OpenCode is not installed");
|
|
8750
|
+
}
|
|
8751
|
+
}
|
|
8752
|
+
if (!ctx.interactive) {
|
|
8753
|
+
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
8754
|
+
const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
|
|
8755
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
8756
|
+
if (!health.healthy) {
|
|
8757
|
+
return {
|
|
8758
|
+
port: ctx.port,
|
|
8759
|
+
process: proc,
|
|
8760
|
+
version: null,
|
|
8761
|
+
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
|
|
8762
|
+
};
|
|
8763
|
+
}
|
|
8764
|
+
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
8765
|
+
return {
|
|
8766
|
+
port: ctx.port,
|
|
8767
|
+
process: proc,
|
|
8768
|
+
version: health.version ?? null,
|
|
8769
|
+
notReadyReason: null
|
|
8770
|
+
};
|
|
8771
|
+
}
|
|
8772
|
+
let port = ctx.port;
|
|
8773
|
+
if (isPortInUse(port)) {
|
|
8774
|
+
console.log(chalk5.yellow(`
|
|
8775
|
+
Port ${port} is already in use.`));
|
|
8776
|
+
const alternativePort = findAvailablePort(port + 1);
|
|
8777
|
+
if (alternativePort) {
|
|
8778
|
+
const useAlternative = await select2({
|
|
8779
|
+
message: `Use port ${alternativePort} instead?`,
|
|
8780
|
+
choices: [
|
|
8781
|
+
{ name: `Yes, use port ${alternativePort}`, value: "yes" },
|
|
8782
|
+
{ name: "No, I will free the port manually", value: "no" }
|
|
8783
|
+
]
|
|
8784
|
+
});
|
|
8785
|
+
if (useAlternative === "yes") {
|
|
8786
|
+
port = alternativePort;
|
|
8787
|
+
} else {
|
|
8788
|
+
throw new Error(`Port ${ctx.port} is in use`);
|
|
8789
|
+
}
|
|
8790
|
+
}
|
|
8791
|
+
}
|
|
8792
|
+
const action = await select2({
|
|
8793
|
+
message: "OpenCode is not running. What would you like to do?",
|
|
8794
|
+
choices: [
|
|
8795
|
+
{
|
|
8796
|
+
name: "Start OpenCode for me",
|
|
8797
|
+
value: "start",
|
|
8798
|
+
description: `Run 'opencode serve --port ${port}'`
|
|
8799
|
+
},
|
|
8800
|
+
{
|
|
8801
|
+
name: "Show me the command",
|
|
8802
|
+
value: "manual",
|
|
8803
|
+
description: "Display the command to run manually"
|
|
8804
|
+
},
|
|
8805
|
+
{
|
|
8806
|
+
name: "Continue without OpenCode",
|
|
8807
|
+
value: "continue",
|
|
8808
|
+
description: "Requests will fail until OpenCode starts"
|
|
8809
|
+
}
|
|
8810
|
+
]
|
|
8811
|
+
});
|
|
8812
|
+
if (action === "manual") {
|
|
8813
|
+
blank();
|
|
8814
|
+
console.log(chalk5.bold("Run this command in another terminal:"));
|
|
8815
|
+
blank();
|
|
8816
|
+
console.log(` ${chalk5.cyan(`opencode serve --port ${port}`)}`);
|
|
8817
|
+
blank();
|
|
8818
|
+
throw new Error("Please start OpenCode manually");
|
|
8819
|
+
}
|
|
8820
|
+
if (action === "start") {
|
|
8821
|
+
const spinner = ora2("Starting OpenCode...").start();
|
|
8822
|
+
const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
|
|
8823
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
8824
|
+
if (!health.healthy) {
|
|
8825
|
+
spinner.fail("Failed to start OpenCode");
|
|
8826
|
+
throw new Error("OpenCode failed to start");
|
|
8827
|
+
}
|
|
8828
|
+
spinner.stop();
|
|
8829
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
8830
|
+
}
|
|
8831
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
8832
|
+
}
|
|
8833
|
+
|
|
8834
|
+
// src/lib/runner-credentials.ts
|
|
8835
|
+
import { chmodSync as chmodSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
8836
|
+
import { spawn as spawn5 } from "child_process";
|
|
8837
|
+
var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
|
|
8838
|
+
var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
|
|
8839
|
+
var GITHUB_PROBE_TIMEOUT_MS = 1e4;
|
|
8840
|
+
var GIT_CONFIG_GLOBAL = "/tmp/gitconfig";
|
|
8841
|
+
var GIT_CREDENTIAL_HELPER = "/tmp/git-credential-helper.sh";
|
|
8842
|
+
function commandError2(result) {
|
|
8843
|
+
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
8844
|
+
}
|
|
8845
|
+
var runCommand2 = (command, args, opts) => {
|
|
8846
|
+
return new Promise((resolve4) => {
|
|
8847
|
+
let child;
|
|
8848
|
+
let stdout = "";
|
|
8849
|
+
let stderr = "";
|
|
8850
|
+
let settled = false;
|
|
8851
|
+
const timer = {};
|
|
8852
|
+
const finish = (result) => {
|
|
8853
|
+
if (settled) return;
|
|
8854
|
+
settled = true;
|
|
8855
|
+
if (timer.handle) clearTimeout(timer.handle);
|
|
8856
|
+
resolve4(result);
|
|
8857
|
+
};
|
|
8858
|
+
try {
|
|
8859
|
+
child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
8860
|
+
} catch (error2) {
|
|
8861
|
+
finish({
|
|
8862
|
+
code: null,
|
|
8863
|
+
stdout,
|
|
8864
|
+
stderr: error2 instanceof Error ? error2.message : String(error2),
|
|
8865
|
+
timedOut: false
|
|
8866
|
+
});
|
|
8867
|
+
return;
|
|
8868
|
+
}
|
|
8869
|
+
child.stdout?.setEncoding("utf8");
|
|
8870
|
+
child.stdout?.on("data", (chunk) => {
|
|
8871
|
+
stdout += chunk;
|
|
8872
|
+
});
|
|
8873
|
+
child.stderr?.setEncoding("utf8");
|
|
8874
|
+
child.stderr?.on("data", (chunk) => {
|
|
8875
|
+
stderr += chunk;
|
|
8876
|
+
});
|
|
8877
|
+
child.once("error", (error2) => {
|
|
8878
|
+
finish({
|
|
8879
|
+
code: null,
|
|
8880
|
+
stdout,
|
|
8881
|
+
stderr: stderr === "" ? error2.message : `${stderr}
|
|
8882
|
+
${error2.message}`,
|
|
8883
|
+
timedOut: false
|
|
8884
|
+
});
|
|
8885
|
+
});
|
|
8886
|
+
child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
|
|
8887
|
+
timer.handle = setTimeout(
|
|
8888
|
+
() => {
|
|
8889
|
+
child.kill("SIGKILL");
|
|
8890
|
+
finish({ code: null, stdout, stderr, timedOut: true });
|
|
8891
|
+
},
|
|
8892
|
+
Math.max(0, opts.timeoutMs)
|
|
8893
|
+
);
|
|
8894
|
+
});
|
|
8895
|
+
};
|
|
8896
|
+
function isEnvironmentObject(value) {
|
|
8897
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8898
|
+
}
|
|
8899
|
+
function secretFailure(marker, detail, log3) {
|
|
8900
|
+
const message = `${marker}: ${detail}`;
|
|
8901
|
+
log3(message, "error");
|
|
8902
|
+
return new Error(message);
|
|
8903
|
+
}
|
|
8904
|
+
async function installRunnerSecret({
|
|
8905
|
+
env,
|
|
8906
|
+
log: log3,
|
|
8907
|
+
commandRunner
|
|
8908
|
+
}) {
|
|
8909
|
+
const arn = env.RUNNER_SECRET_ARN?.trim();
|
|
8910
|
+
if (!arn) {
|
|
8911
|
+
log3("runner secret is not configured; continuing without GitHub and MCP credentials");
|
|
8912
|
+
return false;
|
|
8913
|
+
}
|
|
8914
|
+
const result = await (commandRunner ?? runCommand2)(
|
|
8915
|
+
"aws",
|
|
8916
|
+
[
|
|
8917
|
+
"secretsmanager",
|
|
8918
|
+
"get-secret-value",
|
|
8919
|
+
"--secret-id",
|
|
8920
|
+
arn,
|
|
8921
|
+
"--query",
|
|
8922
|
+
"SecretString",
|
|
8923
|
+
"--output",
|
|
8924
|
+
"text"
|
|
8925
|
+
],
|
|
8926
|
+
{ env, timeoutMs: RUNNER_SECRET_FETCH_TIMEOUT_MS }
|
|
8927
|
+
);
|
|
8928
|
+
if (result.timedOut) {
|
|
8929
|
+
throw secretFailure(
|
|
8930
|
+
"CREDENTIAL-RESTORE-TIMEOUT",
|
|
8931
|
+
`runner-secret did not finish within ${RUNNER_SECRET_FETCH_TIMEOUT_MS}ms`,
|
|
8932
|
+
log3
|
|
8933
|
+
);
|
|
8934
|
+
}
|
|
8935
|
+
if (result.code !== 0) {
|
|
8936
|
+
throw secretFailure("RUNNER-SECRET-UNREADABLE", commandError2(result), log3);
|
|
8937
|
+
}
|
|
8938
|
+
let payload;
|
|
8939
|
+
try {
|
|
8940
|
+
payload = JSON.parse(result.stdout);
|
|
8941
|
+
} catch (error2) {
|
|
8942
|
+
log3(
|
|
8943
|
+
`RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object (${error2 instanceof Error ? error2.message : String(error2)})`,
|
|
8944
|
+
"warn"
|
|
8945
|
+
);
|
|
8946
|
+
return false;
|
|
8947
|
+
}
|
|
8948
|
+
if (!isEnvironmentObject(payload)) {
|
|
8949
|
+
log3("RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object", "warn");
|
|
8950
|
+
return false;
|
|
8951
|
+
}
|
|
8952
|
+
let populated = 0;
|
|
8953
|
+
let skipped = 0;
|
|
8954
|
+
let githubTokenPopulated = false;
|
|
8955
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
8956
|
+
if (typeof value !== "string" || value.length === 0) continue;
|
|
8957
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
|
8958
|
+
log3(
|
|
8959
|
+
`RUNNER-SECRET-KEY-SKIPPED: ${JSON.stringify(key)} is not a valid environment variable name`,
|
|
8960
|
+
"warn"
|
|
8961
|
+
);
|
|
8962
|
+
skipped += 1;
|
|
8963
|
+
continue;
|
|
8964
|
+
}
|
|
8965
|
+
env[key] = value;
|
|
8966
|
+
populated += 1;
|
|
8967
|
+
if (key === "GH_TOKEN") githubTokenPopulated = true;
|
|
8968
|
+
}
|
|
8969
|
+
if (populated === 0) {
|
|
8970
|
+
log3(
|
|
8971
|
+
"RUNNER-SECRET-UNPOPULATED: populate the runner secret as documented in infrastructure/evident-runner/MICROVM.md",
|
|
8972
|
+
"warn"
|
|
8973
|
+
);
|
|
8974
|
+
} else {
|
|
8975
|
+
log3(
|
|
8976
|
+
`RUNNER-SECRET-OK: exported ${populated} secret values; skipped ${skipped} invalid environment variable names`
|
|
8977
|
+
);
|
|
8978
|
+
}
|
|
8979
|
+
return githubTokenPopulated;
|
|
8980
|
+
}
|
|
8981
|
+
function restoreFailure(operation, result, log3) {
|
|
8982
|
+
const message = `CREDENTIAL-RESTORE-FAILED: ${operation} failed: ${commandError2(result)}`;
|
|
8983
|
+
log3(message, "error");
|
|
8984
|
+
return new Error(message);
|
|
8985
|
+
}
|
|
8986
|
+
async function runCredentialRestore(args, operation, log3, synchroniserRunner) {
|
|
8987
|
+
const result = await synchroniserRunner(args, { timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS });
|
|
8988
|
+
if (result.timedOut) {
|
|
8989
|
+
log3(
|
|
8990
|
+
`CREDENTIAL-RESTORE-TIMEOUT: ${operation} did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
|
|
8991
|
+
"warn"
|
|
8992
|
+
);
|
|
8993
|
+
return result;
|
|
8994
|
+
}
|
|
8995
|
+
if (result.code !== 0) throw restoreFailure(operation, result, log3);
|
|
8996
|
+
return result;
|
|
8997
|
+
}
|
|
8998
|
+
async function restoreCredentialStores({
|
|
8999
|
+
env,
|
|
9000
|
+
log: log3,
|
|
9001
|
+
synchroniserRunner = runSynchroniser
|
|
9002
|
+
}) {
|
|
9003
|
+
await runCredentialRestore(["restore", "claude"], "restore-claude", log3, synchroniserRunner);
|
|
9004
|
+
await runCredentialRestore(["restore", "opencode"], "restore-opencode", log3, synchroniserRunner);
|
|
9005
|
+
const result = await synchroniserRunner(["model-auth-ready"], {
|
|
9006
|
+
timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS
|
|
9007
|
+
});
|
|
9008
|
+
if (result.timedOut) {
|
|
9009
|
+
log3(
|
|
9010
|
+
`CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
|
|
9011
|
+
"warn"
|
|
9012
|
+
);
|
|
9013
|
+
return;
|
|
9014
|
+
}
|
|
9015
|
+
switch (result.code) {
|
|
9016
|
+
case 0:
|
|
9017
|
+
return;
|
|
9018
|
+
case 10:
|
|
9019
|
+
log3(
|
|
9020
|
+
`no model credentials under s3://${env.LITESTREAM_BUCKET ?? ""}/${env.LITESTREAM_PREFIX ?? ""}/ (neither claude/credentials.json nor opencode/auth.json yielded valid JSON) and neither ANTHROPIC_API_KEY nor OPENAI_API_KEY is set. This VM boots and connects; a turn that needs a model provider fails until one is connected. See 'Seeding a credential store' in infrastructure/evident-runner/MICROVM.md.`,
|
|
9021
|
+
"warn"
|
|
9022
|
+
);
|
|
9023
|
+
return;
|
|
9024
|
+
default:
|
|
9025
|
+
log3("could not determine whether this VM has model credentials", "warn");
|
|
9026
|
+
}
|
|
9027
|
+
}
|
|
9028
|
+
var GIT_CREDENTIAL_HELPER_CONTENT = [
|
|
9029
|
+
"#!/usr/bin/env bash",
|
|
9030
|
+
'[ "$1" = get ] || exit 0',
|
|
9031
|
+
"echo username=x-access-token",
|
|
9032
|
+
'echo "password=${GH_TOKEN}"',
|
|
9033
|
+
""
|
|
9034
|
+
].join("\n");
|
|
9035
|
+
async function probeGitHubAccess({ env, log: log3 }) {
|
|
9036
|
+
const auth = await runCommand2("gh", ["api", "user", "--jq", ".login"], {
|
|
9037
|
+
env,
|
|
9038
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
9039
|
+
});
|
|
9040
|
+
if (auth.timedOut) {
|
|
9041
|
+
log3(`GITHUB-PROBE-TIMEOUT: auth probe exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`, "warn");
|
|
9042
|
+
return;
|
|
9043
|
+
}
|
|
9044
|
+
if (auth.code !== 0) {
|
|
9045
|
+
log3(`GITHUB-AUTH-REJECTED: ${commandError2(auth)}`, "warn");
|
|
9046
|
+
return;
|
|
9047
|
+
}
|
|
9048
|
+
log3(`GITHUB-AUTH-OK: ${auth.stdout.trim()}`, "debug");
|
|
9049
|
+
const remote = await runCommand2("git", ["-C", process.cwd(), "remote", "get-url", "origin"], {
|
|
9050
|
+
env,
|
|
9051
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
9052
|
+
});
|
|
9053
|
+
if (remote.code !== 0 || remote.timedOut) return;
|
|
9054
|
+
const repo = remote.stdout.trim().replace(/^(?:https:\/\/github\.com\/|git@github\.com:)/, "").replace(/\.git$/, "");
|
|
9055
|
+
if (!repo) return;
|
|
9056
|
+
const repository = await runCommand2("gh", ["api", `repos/${repo}`, "--jq", ".full_name"], {
|
|
9057
|
+
env,
|
|
9058
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
9059
|
+
});
|
|
9060
|
+
if (repository.timedOut) {
|
|
9061
|
+
log3(
|
|
9062
|
+
`GITHUB-PROBE-TIMEOUT: repository probe for ${repo} exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`,
|
|
9063
|
+
"warn"
|
|
9064
|
+
);
|
|
9065
|
+
} else if (repository.code !== 0) {
|
|
9066
|
+
log3(`GITHUB-REPO-INACCESSIBLE: ${repo}: ${commandError2(repository)}`, "warn");
|
|
9067
|
+
}
|
|
9068
|
+
}
|
|
9069
|
+
async function configureGitHubAccess({ env, log: log3 }) {
|
|
9070
|
+
if (!env.GH_TOKEN) {
|
|
9071
|
+
log3("GITHUB-CREDENTIALS-MISSING: GH_TOKEN is unavailable; see RUNNER-SECRET-* above", "warn");
|
|
9072
|
+
return;
|
|
9073
|
+
}
|
|
9074
|
+
try {
|
|
9075
|
+
env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
|
|
9076
|
+
writeFileSync4(GIT_CONFIG_GLOBAL, "");
|
|
9077
|
+
writeFileSync4(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
|
|
9078
|
+
chmodSync2(GIT_CREDENTIAL_HELPER, 448);
|
|
9079
|
+
const config = [
|
|
9080
|
+
["user.name", env.GIT_USER_NAME ?? "evident-bot"],
|
|
9081
|
+
["user.email", env.GIT_USER_EMAIL ?? "evident-bot@users.noreply.github.com"],
|
|
9082
|
+
["init.defaultBranch", "main"],
|
|
9083
|
+
["credential.https://github.com.helper", GIT_CREDENTIAL_HELPER]
|
|
9084
|
+
];
|
|
9085
|
+
for (const [key, value] of config) {
|
|
9086
|
+
const result = await runCommand2("git", ["config", "--global", key, value], {
|
|
9087
|
+
env,
|
|
9088
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
9089
|
+
});
|
|
9090
|
+
if (result.timedOut || result.code !== 0) throw new Error(commandError2(result));
|
|
9091
|
+
}
|
|
9092
|
+
} catch (error2) {
|
|
9093
|
+
log3(
|
|
9094
|
+
`GITHUB-SETUP-FAILED: could not configure local git credentials; continuing without GitHub access (${error2 instanceof Error ? error2.message : String(error2)})`,
|
|
9095
|
+
"warn"
|
|
9096
|
+
);
|
|
9097
|
+
return;
|
|
9098
|
+
}
|
|
9099
|
+
void probeGitHubAccess({ env, log: log3 }).catch((error2) => {
|
|
9100
|
+
log3(
|
|
9101
|
+
`GITHUB-SETUP-FAILED: GitHub access probe failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
9102
|
+
"warn"
|
|
9103
|
+
);
|
|
9104
|
+
});
|
|
9105
|
+
}
|
|
9106
|
+
|
|
9107
|
+
// src/lib/opencode/config-overlay.ts
|
|
9108
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
9109
|
+
import { copyFileSync, existsSync as existsSync2, statSync as statSync5 } from "fs";
|
|
9110
|
+
import { isAbsolute as isAbsolute2, join as join8, resolve as resolve3 } from "path";
|
|
9111
|
+
function isFile(filePath) {
|
|
9112
|
+
return existsSync2(filePath) && statSync5(filePath).isFile();
|
|
9113
|
+
}
|
|
9114
|
+
function applyRunnerOpenCodeConfig({
|
|
9115
|
+
overlayPath,
|
|
9116
|
+
cwd = process.cwd(),
|
|
9117
|
+
log: log3
|
|
9118
|
+
}) {
|
|
9119
|
+
if (!overlayPath) {
|
|
9120
|
+
log3("runner OpenCode config is not configured; using the baked project config", "debug");
|
|
9121
|
+
return;
|
|
9122
|
+
}
|
|
9123
|
+
const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
|
|
9124
|
+
const target = isFile(join8(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
|
|
9125
|
+
if (!isFile(source)) {
|
|
9126
|
+
log3(
|
|
9127
|
+
`RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
|
|
9128
|
+
"error"
|
|
9129
|
+
);
|
|
9130
|
+
return;
|
|
9131
|
+
}
|
|
9132
|
+
copyFileSync(source, join8(cwd, target));
|
|
9133
|
+
try {
|
|
9134
|
+
execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
|
|
9135
|
+
stdio: "ignore"
|
|
9136
|
+
});
|
|
9137
|
+
} catch (error2) {
|
|
9138
|
+
const detail = error2 instanceof Error ? error2.message : String(error2);
|
|
9139
|
+
log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
|
|
9140
|
+
}
|
|
9141
|
+
log3(`Applied runner OpenCode config ${source} to ${join8(cwd, target)}`);
|
|
9142
|
+
}
|
|
9143
|
+
|
|
9144
|
+
// src/lib/credential-sync.ts
|
|
9145
|
+
import { renameSync, writeFileSync as writeFileSync5 } from "fs";
|
|
9146
|
+
var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
|
|
9147
|
+
var CREDENTIAL_FLUSH_DEADLINE_MS = 8e3;
|
|
9148
|
+
var CREDENTIAL_FLUSH_ABORT_GRACE_MS = 500;
|
|
9149
|
+
var DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS = 60;
|
|
9150
|
+
var STORES = ["claude", "opencode"];
|
|
9151
|
+
var MAX_FLUSH_PASSES = 2;
|
|
9152
|
+
function outcomesWith(outcome) {
|
|
9153
|
+
return { claude: outcome, opencode: outcome };
|
|
9154
|
+
}
|
|
9155
|
+
function errorMessage(error2) {
|
|
9156
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
9157
|
+
}
|
|
9158
|
+
function waitForSettlement(promise, timeoutMs) {
|
|
9159
|
+
return new Promise((resolve4) => {
|
|
9160
|
+
let settled = false;
|
|
9161
|
+
const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
|
|
9162
|
+
const finish = (value) => {
|
|
9163
|
+
if (settled) return;
|
|
9164
|
+
settled = true;
|
|
9165
|
+
clearTimeout(timer);
|
|
9166
|
+
resolve4(value);
|
|
9167
|
+
};
|
|
9168
|
+
promise.then(
|
|
9169
|
+
() => finish(true),
|
|
9170
|
+
() => finish(true)
|
|
9171
|
+
);
|
|
9172
|
+
});
|
|
9173
|
+
}
|
|
9174
|
+
function writeMarker(markerPath, outcomes, log3) {
|
|
9175
|
+
const body = `${STORES.map((store) => `${store}=${outcomes[store]}`).join("\n")}
|
|
9176
|
+
`;
|
|
9177
|
+
const temporaryPath = `${markerPath}.tmp`;
|
|
9178
|
+
try {
|
|
9179
|
+
writeFileSync5(temporaryPath, body, { mode: 384 });
|
|
9180
|
+
renameSync(temporaryPath, markerPath);
|
|
9181
|
+
} catch (error2) {
|
|
9182
|
+
log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage(error2)}`, "warn");
|
|
9183
|
+
}
|
|
9184
|
+
}
|
|
9185
|
+
function intervalSeconds(env, log3) {
|
|
9186
|
+
const raw = env.CREDS_SYNC_INTERVAL;
|
|
9187
|
+
if (raw === void 0 || /^[1-9][0-9]*$/.test(raw) && Number.isSafeInteger(Number(raw))) {
|
|
9188
|
+
return raw === void 0 ? DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS : Number(raw);
|
|
9189
|
+
}
|
|
9190
|
+
log3(
|
|
9191
|
+
`CREDENTIAL-SYNC-INTERVAL-INVALID: CREDS_SYNC_INTERVAL='${raw}' is not a positive integer; using ${DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS}s`,
|
|
9192
|
+
"warn"
|
|
9193
|
+
);
|
|
9194
|
+
return DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS;
|
|
9195
|
+
}
|
|
9196
|
+
async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
|
|
9197
|
+
const remainingMs = deadlineAt - Date.now();
|
|
9198
|
+
if (remainingMs <= 0) return { outcome: "timeout", orphaned: false };
|
|
9199
|
+
const controller = new AbortController();
|
|
9200
|
+
let result;
|
|
9201
|
+
let failed = false;
|
|
9202
|
+
const completion = Promise.resolve().then(
|
|
9203
|
+
() => synchroniserRunner(["sync-once", store], {
|
|
9204
|
+
timeoutMs: remainingMs,
|
|
9205
|
+
env,
|
|
9206
|
+
signal: controller.signal
|
|
9207
|
+
})
|
|
9208
|
+
).then(
|
|
9209
|
+
(value) => {
|
|
9210
|
+
result = value;
|
|
9211
|
+
},
|
|
9212
|
+
(error2) => {
|
|
9213
|
+
failed = true;
|
|
9214
|
+
log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage(error2)}`, "warn");
|
|
7808
9215
|
}
|
|
7809
|
-
|
|
7810
|
-
|
|
7811
|
-
|
|
7812
|
-
|
|
7813
|
-
|
|
7814
|
-
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
|
|
7818
|
-
|
|
7819
|
-
|
|
9216
|
+
);
|
|
9217
|
+
const abortTimer = setTimeout(() => controller.abort(), remainingMs);
|
|
9218
|
+
const settledBeforeDeadline = await waitForSettlement(completion, remainingMs);
|
|
9219
|
+
clearTimeout(abortTimer);
|
|
9220
|
+
if (!settledBeforeDeadline) {
|
|
9221
|
+
controller.abort();
|
|
9222
|
+
const settledAfterAbort = await waitForSettlement(completion, CREDENTIAL_FLUSH_ABORT_GRACE_MS);
|
|
9223
|
+
if (!settledAfterAbort) return { outcome: "timeout", orphaned: true };
|
|
9224
|
+
return { outcome: "timeout", orphaned: false };
|
|
9225
|
+
}
|
|
9226
|
+
if (failed || !result) return { outcome: "failed", orphaned: false };
|
|
9227
|
+
if (result.timedOut || Date.now() >= deadlineAt) {
|
|
9228
|
+
return { outcome: "timeout", orphaned: false };
|
|
9229
|
+
}
|
|
9230
|
+
return { outcome: result.code === 0 ? "ok" : "failed", orphaned: false };
|
|
9231
|
+
}
|
|
9232
|
+
function createCredentialSync({
|
|
9233
|
+
markerPath,
|
|
9234
|
+
env,
|
|
9235
|
+
log: log3,
|
|
9236
|
+
synchroniserRunner = runSynchroniser
|
|
9237
|
+
}) {
|
|
9238
|
+
const persistenceDisabled = !env.PERSISTENCE_BUCKET;
|
|
9239
|
+
let disabled = persistenceDisabled;
|
|
9240
|
+
let armed = false;
|
|
9241
|
+
let stopped = false;
|
|
9242
|
+
let timer;
|
|
9243
|
+
let inFlight;
|
|
9244
|
+
let activeTickAbort;
|
|
9245
|
+
let lastTickFailed;
|
|
9246
|
+
let flushPromise;
|
|
9247
|
+
const scheduleTick = (intervalMs, startTick2) => {
|
|
9248
|
+
if (stopped) return;
|
|
9249
|
+
timer = setTimeout(() => {
|
|
9250
|
+
timer = void 0;
|
|
9251
|
+
startTick2();
|
|
9252
|
+
}, intervalMs);
|
|
9253
|
+
};
|
|
9254
|
+
const startTick = (intervalMs) => {
|
|
9255
|
+
if (stopped) return;
|
|
9256
|
+
const controller = new AbortController();
|
|
9257
|
+
activeTickAbort = controller;
|
|
9258
|
+
const tick = (async () => {
|
|
9259
|
+
const outcomes = {
|
|
9260
|
+
claude: "failed",
|
|
9261
|
+
opencode: "failed"
|
|
7820
9262
|
};
|
|
9263
|
+
for (const store of STORES) {
|
|
9264
|
+
if (controller.signal.aborted) break;
|
|
9265
|
+
try {
|
|
9266
|
+
const result = await synchroniserRunner(["sync-once", store], {
|
|
9267
|
+
timeoutMs: CREDENTIAL_SYNC_TICK_TIMEOUT_MS,
|
|
9268
|
+
env,
|
|
9269
|
+
signal: controller.signal
|
|
9270
|
+
});
|
|
9271
|
+
outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
|
|
9272
|
+
} catch (error2) {
|
|
9273
|
+
outcomes[store] = "failed";
|
|
9274
|
+
log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage(error2)}`, "debug");
|
|
9275
|
+
}
|
|
9276
|
+
}
|
|
9277
|
+
const failed = STORES.some((store) => outcomes[store] === "failed");
|
|
9278
|
+
log3(
|
|
9279
|
+
`CREDENTIAL-SYNC-TICK: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
|
|
9280
|
+
"debug"
|
|
9281
|
+
);
|
|
9282
|
+
if (failed && lastTickFailed !== true) {
|
|
9283
|
+
log3(
|
|
9284
|
+
"CREDENTIAL-SYNC-FAILED: an interval credential sync failed; retrying on the next tick",
|
|
9285
|
+
"warn"
|
|
9286
|
+
);
|
|
9287
|
+
} else if (!failed && lastTickFailed === true) {
|
|
9288
|
+
log3("CREDENTIAL-SYNC-RECOVERED: interval credential sync succeeded again", "warn");
|
|
9289
|
+
}
|
|
9290
|
+
lastTickFailed = failed;
|
|
9291
|
+
})().finally(() => {
|
|
9292
|
+
if (activeTickAbort === controller) activeTickAbort = void 0;
|
|
9293
|
+
if (inFlight === tick) inFlight = void 0;
|
|
9294
|
+
scheduleTick(intervalMs, () => startTick(intervalMs));
|
|
9295
|
+
});
|
|
9296
|
+
inFlight = tick;
|
|
9297
|
+
};
|
|
9298
|
+
const performFlush = async () => {
|
|
9299
|
+
stopped = true;
|
|
9300
|
+
if (timer) {
|
|
9301
|
+
clearTimeout(timer);
|
|
9302
|
+
timer = void 0;
|
|
9303
|
+
}
|
|
9304
|
+
const deadlineAt = Date.now() + CREDENTIAL_FLUSH_DEADLINE_MS;
|
|
9305
|
+
if (inFlight) {
|
|
9306
|
+
const settled = await waitForSettlement(inFlight, CREDENTIAL_FLUSH_DEADLINE_MS);
|
|
9307
|
+
if (!settled) {
|
|
9308
|
+
activeTickAbort?.abort();
|
|
9309
|
+
const settledAfterAbort = await waitForSettlement(
|
|
9310
|
+
inFlight,
|
|
9311
|
+
CREDENTIAL_FLUSH_ABORT_GRACE_MS
|
|
9312
|
+
);
|
|
9313
|
+
if (!settledAfterAbort) {
|
|
9314
|
+
log3(
|
|
9315
|
+
"CREDENTIAL-FLUSH-ORPHANED-TICK: a sync-once child could not be proven settled; skipping the boundary flush rather than becoming a second writer",
|
|
9316
|
+
"warn"
|
|
9317
|
+
);
|
|
9318
|
+
return { outcomes: outcomesWith("timeout"), orphaned: true };
|
|
9319
|
+
}
|
|
9320
|
+
}
|
|
7821
9321
|
}
|
|
7822
|
-
|
|
7823
|
-
|
|
7824
|
-
|
|
7825
|
-
|
|
7826
|
-
|
|
7827
|
-
|
|
7828
|
-
|
|
7829
|
-
|
|
7830
|
-
|
|
7831
|
-
|
|
7832
|
-
console.log(chalk5.yellow(`
|
|
7833
|
-
Port ${port} is already in use.`));
|
|
7834
|
-
const alternativePort = findAvailablePort(port + 1);
|
|
7835
|
-
if (alternativePort) {
|
|
7836
|
-
const useAlternative = await select2({
|
|
7837
|
-
message: `Use port ${alternativePort} instead?`,
|
|
7838
|
-
choices: [
|
|
7839
|
-
{ name: `Yes, use port ${alternativePort}`, value: "yes" },
|
|
7840
|
-
{ name: "No, I will free the port manually", value: "no" }
|
|
7841
|
-
]
|
|
7842
|
-
});
|
|
7843
|
-
if (useAlternative === "yes") {
|
|
7844
|
-
port = alternativePort;
|
|
7845
|
-
} else {
|
|
7846
|
-
throw new Error(`Port ${ctx.port} is in use`);
|
|
9322
|
+
if (disabled) return { outcomes: outcomesWith("skipped"), orphaned: false };
|
|
9323
|
+
const outcomes = outcomesWith("timeout");
|
|
9324
|
+
for (const store of STORES) {
|
|
9325
|
+
const result = await runFlushStore(store, env, synchroniserRunner, log3, deadlineAt);
|
|
9326
|
+
if (result.orphaned) {
|
|
9327
|
+
log3(
|
|
9328
|
+
"CREDENTIAL-FLUSH-ORPHANED-CHILD: a flush sync-once child could not be proven settled; refusing another flush pass rather than becoming a second writer",
|
|
9329
|
+
"warn"
|
|
9330
|
+
);
|
|
9331
|
+
return { outcomes: outcomesWith("timeout"), orphaned: true };
|
|
7847
9332
|
}
|
|
9333
|
+
outcomes[store] = result.outcome;
|
|
7848
9334
|
}
|
|
7849
|
-
|
|
7850
|
-
|
|
7851
|
-
|
|
7852
|
-
|
|
7853
|
-
|
|
7854
|
-
|
|
7855
|
-
|
|
7856
|
-
|
|
7857
|
-
|
|
7858
|
-
|
|
7859
|
-
|
|
7860
|
-
|
|
7861
|
-
|
|
7862
|
-
|
|
7863
|
-
|
|
7864
|
-
name: "Continue without OpenCode",
|
|
7865
|
-
value: "continue",
|
|
7866
|
-
description: "Requests will fail until OpenCode starts"
|
|
9335
|
+
return { outcomes, orphaned: false };
|
|
9336
|
+
};
|
|
9337
|
+
let flushPasses = 0;
|
|
9338
|
+
let lastFlush;
|
|
9339
|
+
return {
|
|
9340
|
+
arm() {
|
|
9341
|
+
if (stopped || armed) return;
|
|
9342
|
+
armed = true;
|
|
9343
|
+
if (persistenceDisabled) {
|
|
9344
|
+
disabled = true;
|
|
9345
|
+
log3(
|
|
9346
|
+
"CREDENTIAL-SYNC-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; no interval credential sync this boot",
|
|
9347
|
+
"warn"
|
|
9348
|
+
);
|
|
9349
|
+
return;
|
|
7867
9350
|
}
|
|
7868
|
-
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
|
|
7881
|
-
|
|
7882
|
-
|
|
7883
|
-
|
|
7884
|
-
|
|
9351
|
+
disabled = false;
|
|
9352
|
+
const intervalMs = intervalSeconds(env, log3) * 1e3;
|
|
9353
|
+
scheduleTick(intervalMs, () => startTick(intervalMs));
|
|
9354
|
+
},
|
|
9355
|
+
async stopAndFlush(publish) {
|
|
9356
|
+
let result;
|
|
9357
|
+
const runningFlush = flushPromise;
|
|
9358
|
+
if (runningFlush) {
|
|
9359
|
+
result = await runningFlush;
|
|
9360
|
+
} else if (flushPasses >= MAX_FLUSH_PASSES || lastFlush?.orphaned) {
|
|
9361
|
+
result = lastFlush ?? { outcomes: outcomesWith("timeout"), orphaned: true };
|
|
9362
|
+
} else {
|
|
9363
|
+
flushPasses++;
|
|
9364
|
+
const currentFlush = performFlush();
|
|
9365
|
+
flushPromise = currentFlush;
|
|
9366
|
+
try {
|
|
9367
|
+
result = await currentFlush;
|
|
9368
|
+
lastFlush = result;
|
|
9369
|
+
} finally {
|
|
9370
|
+
if (flushPromise === currentFlush) flushPromise = void 0;
|
|
9371
|
+
}
|
|
9372
|
+
}
|
|
9373
|
+
if (publish) writeMarker(markerPath, result.outcomes, log3);
|
|
9374
|
+
return result.outcomes;
|
|
7885
9375
|
}
|
|
7886
|
-
|
|
7887
|
-
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
7888
|
-
}
|
|
7889
|
-
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
9376
|
+
};
|
|
7890
9377
|
}
|
|
7891
9378
|
|
|
7892
9379
|
// src/commands/run.ts
|
|
@@ -7895,6 +9382,7 @@ var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_
|
|
|
7895
9382
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
7896
9383
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
7897
9384
|
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
9385
|
+
var CHILD_STOP_TIMEOUT_MS = 1e4;
|
|
7898
9386
|
function resolveLogLevel(options) {
|
|
7899
9387
|
const accepted = Object.keys(LOG_LEVELS);
|
|
7900
9388
|
const validate = (value, source) => {
|
|
@@ -7925,11 +9413,11 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
7925
9413
|
if (trimmed === "") {
|
|
7926
9414
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
7927
9415
|
}
|
|
7928
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
7929
|
-
if (!
|
|
9416
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join9(homeDir, trimmed.slice(2)) : trimmed;
|
|
9417
|
+
if (!isAbsolute3(expanded)) {
|
|
7930
9418
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
7931
9419
|
}
|
|
7932
|
-
const normalized =
|
|
9420
|
+
const normalized = resolvePath2(expanded);
|
|
7933
9421
|
if (parse(normalized).root === normalized) {
|
|
7934
9422
|
throw new Error(
|
|
7935
9423
|
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
@@ -8045,7 +9533,7 @@ function logActivity(state, entry) {
|
|
|
8045
9533
|
}
|
|
8046
9534
|
function reportSessionDbRecovery(state) {
|
|
8047
9535
|
try {
|
|
8048
|
-
const report = drainSessionDbRecoveryReport({ homeDir:
|
|
9536
|
+
const report = drainSessionDbRecoveryReport({ homeDir: homedir5(), env: process.env });
|
|
8049
9537
|
for (const record of report.records) {
|
|
8050
9538
|
const activity = buildSessionDbRecoveryActivity(record);
|
|
8051
9539
|
if (!activity) throw new Error("could not map session-DB recovery record");
|
|
@@ -8063,6 +9551,16 @@ function reportSessionDbRecovery(state) {
|
|
|
8063
9551
|
);
|
|
8064
9552
|
}
|
|
8065
9553
|
}
|
|
9554
|
+
function reportSessionDbRecoveryRecord(state, record) {
|
|
9555
|
+
const activity = buildSessionDbRecoveryActivity(record);
|
|
9556
|
+
if (!activity) throw new Error("could not map session-DB recovery record");
|
|
9557
|
+
logActivity(state, {
|
|
9558
|
+
type: activity.level === "error" ? "error" : "info",
|
|
9559
|
+
level: activity.level,
|
|
9560
|
+
...activity.level === "error" ? { error: activity.message } : { message: activity.message },
|
|
9561
|
+
metadata: activity.metadata
|
|
9562
|
+
});
|
|
9563
|
+
}
|
|
8066
9564
|
function displayStatus(state) {
|
|
8067
9565
|
if (!state.interactive) return;
|
|
8068
9566
|
const attempt = state.connection?.reconnectAttempt ?? 0;
|
|
@@ -8175,6 +9673,10 @@ async function driveChannels(state, driver) {
|
|
|
8175
9673
|
consecutiveDrainFailures = 0;
|
|
8176
9674
|
unreachableMs = 0;
|
|
8177
9675
|
state.messageCount += processed;
|
|
9676
|
+
if (driver.recycleRequested) {
|
|
9677
|
+
await beginGracefulShutdown(state, "recycle");
|
|
9678
|
+
return;
|
|
9679
|
+
}
|
|
8178
9680
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
8179
9681
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
8180
9682
|
const fileActivitySnapshot = driver.fileSyncActivity();
|
|
@@ -8217,8 +9719,8 @@ async function driveChannels(state, driver) {
|
|
|
8217
9719
|
state.running = false;
|
|
8218
9720
|
break;
|
|
8219
9721
|
}
|
|
8220
|
-
const
|
|
8221
|
-
logActivity(state, { type: "error", error: `Channel processing error: ${
|
|
9722
|
+
const errorMessage2 = error2 instanceof Error ? error2.message : String(error2);
|
|
9723
|
+
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage2}` });
|
|
8222
9724
|
if (state.interactive) displayStatus(state);
|
|
8223
9725
|
if (driver.hasInFlightWatchers()) {
|
|
8224
9726
|
consecutiveDrainFailures = 0;
|
|
@@ -8235,7 +9737,7 @@ async function driveChannels(state, driver) {
|
|
|
8235
9737
|
}
|
|
8236
9738
|
}
|
|
8237
9739
|
}
|
|
8238
|
-
await new Promise((
|
|
9740
|
+
await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
|
|
8239
9741
|
const cycleMs = performance.now() - cycleStartedAtMs;
|
|
8240
9742
|
if (idleThisCycle) idleMs += cycleMs;
|
|
8241
9743
|
if (unreachableThisCycle) unreachableMs += cycleMs;
|
|
@@ -8258,7 +9760,43 @@ async function driveChannels(state, driver) {
|
|
|
8258
9760
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
8259
9761
|
var SESSION_DB_RECLAIM_MAX_PAGES = 2e3;
|
|
8260
9762
|
function sessionDbPath() {
|
|
8261
|
-
return
|
|
9763
|
+
return join9(homedir5(), ".local", "share", "opencode", "opencode.db");
|
|
9764
|
+
}
|
|
9765
|
+
function logSessionDbProvenanceMismatch(state, provenance, currentVersion, preBootMigrationCount) {
|
|
9766
|
+
const record = {
|
|
9767
|
+
v: 1,
|
|
9768
|
+
event: "session_db_recovery",
|
|
9769
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
9770
|
+
stage: "verify",
|
|
9771
|
+
outcome: "schema_provenance_mismatch",
|
|
9772
|
+
severity: "error",
|
|
9773
|
+
reason: provenance.reason ?? "schema-provenance-mismatch",
|
|
9774
|
+
litestream_exit_code: null,
|
|
9775
|
+
attempt: null,
|
|
9776
|
+
replica_objects: null,
|
|
9777
|
+
replica_bytes: null,
|
|
9778
|
+
quarantine_destination: null,
|
|
9779
|
+
quarantined_objects: null,
|
|
9780
|
+
quarantine_failed_objects: null,
|
|
9781
|
+
quarantined_bytes: null,
|
|
9782
|
+
verified_restore_point: null,
|
|
9783
|
+
restore_points_tried: null,
|
|
9784
|
+
provenance_reason: provenance.reason,
|
|
9785
|
+
provenance_migration_delta: provenance.migrationDelta,
|
|
9786
|
+
replication_suspended: false,
|
|
9787
|
+
dbPath: sessionDbPath(),
|
|
9788
|
+
recorded_version: provenance.recordedVersion,
|
|
9789
|
+
current_version: currentVersion,
|
|
9790
|
+
provenance_pre_boot_migration_count: preBootMigrationCount
|
|
9791
|
+
};
|
|
9792
|
+
const activity = buildSessionDbRecoveryActivity(record);
|
|
9793
|
+
if (!activity) throw new Error("could not map session-DB provenance activity");
|
|
9794
|
+
logActivity(state, {
|
|
9795
|
+
type: activity.level === "error" ? "error" : "info",
|
|
9796
|
+
level: activity.level,
|
|
9797
|
+
...activity.level === "error" ? { error: activity.message } : { message: activity.message },
|
|
9798
|
+
metadata: activity.metadata
|
|
9799
|
+
});
|
|
8262
9800
|
}
|
|
8263
9801
|
async function runSweep(state, driver, config) {
|
|
8264
9802
|
const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
|
|
@@ -8305,7 +9843,7 @@ async function runSweep(state, driver, config) {
|
|
|
8305
9843
|
const reclaimResult = await reclaimSessionDbSpace({
|
|
8306
9844
|
dbPath: sessionDbPath(),
|
|
8307
9845
|
maxPages: SESSION_DB_RECLAIM_MAX_PAGES,
|
|
8308
|
-
allowFullVacuum: protectedNow.size === 0
|
|
9846
|
+
allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
|
|
8309
9847
|
});
|
|
8310
9848
|
if (reclaimResult.ok) {
|
|
8311
9849
|
const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
|
|
@@ -8341,7 +9879,7 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
8341
9879
|
for (const warning2 of config.warnings) {
|
|
8342
9880
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
8343
9881
|
}
|
|
8344
|
-
const dbBytes = statSessionDbBytes(
|
|
9882
|
+
const dbBytes = statSessionDbBytes(homedir5());
|
|
8345
9883
|
void (async () => {
|
|
8346
9884
|
const reclaimSkipReason = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
|
|
8347
9885
|
const sizeWarning = buildSessionStoreSizeWarning({
|
|
@@ -8500,7 +10038,17 @@ function scheduleClaudeUsageReporting(state, options) {
|
|
|
8500
10038
|
setTimer: (timer) => {
|
|
8501
10039
|
state.claudeUsageTimer = timer;
|
|
8502
10040
|
},
|
|
8503
|
-
fetchUsage:
|
|
10041
|
+
fetchUsage: async () => {
|
|
10042
|
+
const usage = await getClaudeUsage();
|
|
10043
|
+
if (usage.ownerLookupError) {
|
|
10044
|
+
logActivity(state, {
|
|
10045
|
+
type: "info",
|
|
10046
|
+
level: "debug",
|
|
10047
|
+
message: `Claude usage owner lookup failed: ${usage.ownerLookupError}`
|
|
10048
|
+
});
|
|
10049
|
+
}
|
|
10050
|
+
return usage;
|
|
10051
|
+
},
|
|
8504
10052
|
report: (usage) => reportClaudeUsage(state.agentId, state.authHeader, usage),
|
|
8505
10053
|
isLocalCredentialProblem,
|
|
8506
10054
|
forcedOnHint: "run `claude` to sign in",
|
|
@@ -8532,7 +10080,7 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
8532
10080
|
});
|
|
8533
10081
|
return;
|
|
8534
10082
|
}
|
|
8535
|
-
const collect = createResourceUsageCollector(
|
|
10083
|
+
const collect = createResourceUsageCollector(homedir5());
|
|
8536
10084
|
let consecutiveFailures = 0;
|
|
8537
10085
|
const tick = async () => {
|
|
8538
10086
|
try {
|
|
@@ -8642,21 +10190,39 @@ async function cleanup(state, opts = {}) {
|
|
|
8642
10190
|
clearTimeout(state.resourceUsageTimer);
|
|
8643
10191
|
state.resourceUsageTimer = null;
|
|
8644
10192
|
}
|
|
10193
|
+
const credentialSync = state.credentialSync;
|
|
10194
|
+
const flushCredentials = credentialSync ? async (phase, publish) => {
|
|
10195
|
+
await timeShutdownPhase(state, durations, phase, async () => {
|
|
10196
|
+
const outcomes = await credentialSync.stopAndFlush(publish);
|
|
10197
|
+
const level = Object.values(outcomes).every((outcome) => outcome === "ok") ? "info" : "warn";
|
|
10198
|
+
log2(
|
|
10199
|
+
state,
|
|
10200
|
+
`Credential flush: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
|
|
10201
|
+
level
|
|
10202
|
+
);
|
|
10203
|
+
});
|
|
10204
|
+
} : void 0;
|
|
10205
|
+
let drainSettled = true;
|
|
8645
10206
|
if (opts.graceful && state.channelDriver) {
|
|
8646
10207
|
state.channelDriver.stop();
|
|
10208
|
+
}
|
|
10209
|
+
if (flushCredentials) {
|
|
10210
|
+
await flushCredentials("credential_flush", !(opts.graceful && state.channelDriver));
|
|
10211
|
+
}
|
|
10212
|
+
if (opts.graceful && state.channelDriver) {
|
|
8647
10213
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
8648
10214
|
if (state.interactive) {
|
|
8649
10215
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
8650
10216
|
displayStatus(state);
|
|
8651
10217
|
}
|
|
8652
10218
|
const driver = state.channelDriver;
|
|
8653
|
-
|
|
10219
|
+
drainSettled = await timeShutdownPhase(
|
|
8654
10220
|
state,
|
|
8655
10221
|
durations,
|
|
8656
10222
|
"drain",
|
|
8657
10223
|
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
8658
10224
|
);
|
|
8659
|
-
if (!
|
|
10225
|
+
if (!drainSettled) {
|
|
8660
10226
|
logActivity(state, {
|
|
8661
10227
|
type: "info",
|
|
8662
10228
|
message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
|
|
@@ -8664,6 +10230,9 @@ async function cleanup(state, opts = {}) {
|
|
|
8664
10230
|
if (state.interactive) displayStatus(state);
|
|
8665
10231
|
}
|
|
8666
10232
|
}
|
|
10233
|
+
if (opts.graceful && state.channelDriver && flushCredentials && drainSettled) {
|
|
10234
|
+
await flushCredentials("credential_flush_final", true);
|
|
10235
|
+
}
|
|
8667
10236
|
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
8668
10237
|
if (state.connection) {
|
|
8669
10238
|
const connection = state.connection;
|
|
@@ -8672,24 +10241,83 @@ async function cleanup(state, opts = {}) {
|
|
|
8672
10241
|
}
|
|
8673
10242
|
if (state.opencodeProcess) {
|
|
8674
10243
|
const opencodeProcess = state.opencodeProcess;
|
|
8675
|
-
|
|
10244
|
+
const result = await timeShutdownPhase(
|
|
10245
|
+
state,
|
|
10246
|
+
durations,
|
|
10247
|
+
"opencode_stop",
|
|
10248
|
+
() => stopOpenCodeAndWait(opencodeProcess, CHILD_STOP_TIMEOUT_MS)
|
|
10249
|
+
);
|
|
8676
10250
|
if (state.interactive) {
|
|
8677
|
-
logActivity(state, { type: "info", message:
|
|
10251
|
+
logActivity(state, { type: "info", message: `Stopped OpenCode process (${result.outcome})` });
|
|
8678
10252
|
displayStatus(state);
|
|
8679
10253
|
} else {
|
|
8680
|
-
log2(state,
|
|
10254
|
+
log2(state, `Stopped OpenCode process (${result.outcome})`);
|
|
8681
10255
|
}
|
|
8682
10256
|
state.opencodeProcess = null;
|
|
8683
10257
|
}
|
|
10258
|
+
if (state.litestreamProcess) {
|
|
10259
|
+
const litestreamProcess = state.litestreamProcess;
|
|
10260
|
+
const result = await timeShutdownPhase(
|
|
10261
|
+
state,
|
|
10262
|
+
durations,
|
|
10263
|
+
"litestream_stop",
|
|
10264
|
+
() => stopSessionDbReplication(litestreamProcess, CHILD_STOP_TIMEOUT_MS)
|
|
10265
|
+
);
|
|
10266
|
+
log2(state, `Stopped litestream replication (${result.outcome})`);
|
|
10267
|
+
state.litestreamProcess = null;
|
|
10268
|
+
}
|
|
8684
10269
|
return durations;
|
|
8685
10270
|
}
|
|
10271
|
+
async function beginGracefulShutdown(state, trigger) {
|
|
10272
|
+
if (state.shuttingDown) return;
|
|
10273
|
+
state.shuttingDown = true;
|
|
10274
|
+
const shutdownStartedAt = Date.now();
|
|
10275
|
+
const shutdownMessage = trigger === "recycle" ? "Recycle requested \u2014 finishing in-flight work, then exiting" : "Shutting down...";
|
|
10276
|
+
if (state.interactive) {
|
|
10277
|
+
logActivity(state, { type: "info", message: shutdownMessage });
|
|
10278
|
+
displayStatus(state);
|
|
10279
|
+
} else {
|
|
10280
|
+
log2(state, shutdownMessage);
|
|
10281
|
+
}
|
|
10282
|
+
const durations = await cleanup(state, { graceful: true });
|
|
10283
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
10284
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
10285
|
+
let timer;
|
|
10286
|
+
const flushed = shutdownTelemetry().then(
|
|
10287
|
+
() => true,
|
|
10288
|
+
(error2) => {
|
|
10289
|
+
log2(
|
|
10290
|
+
state,
|
|
10291
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
10292
|
+
"warn"
|
|
10293
|
+
);
|
|
10294
|
+
return true;
|
|
10295
|
+
}
|
|
10296
|
+
);
|
|
10297
|
+
const timedOut = new Promise((resolve4) => {
|
|
10298
|
+
timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
|
|
10299
|
+
});
|
|
10300
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
10301
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
10302
|
+
}
|
|
10303
|
+
clearTimeout(timer);
|
|
10304
|
+
});
|
|
10305
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
10306
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
10307
|
+
process.exit(0);
|
|
10308
|
+
}
|
|
8686
10309
|
async function run(options) {
|
|
8687
10310
|
const interactive = isInteractive(options.json);
|
|
8688
10311
|
let logLevel;
|
|
8689
10312
|
let fileSyncDirectories;
|
|
8690
10313
|
try {
|
|
8691
10314
|
logLevel = resolveLogLevel(options);
|
|
8692
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
10315
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir5());
|
|
10316
|
+
if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
|
|
10317
|
+
throw new Error(
|
|
10318
|
+
"--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
|
|
10319
|
+
);
|
|
10320
|
+
}
|
|
8693
10321
|
} catch (error2) {
|
|
8694
10322
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
8695
10323
|
if (options.json) {
|
|
@@ -8713,7 +10341,9 @@ async function run(options) {
|
|
|
8713
10341
|
connected: false,
|
|
8714
10342
|
opencodeConnected: false,
|
|
8715
10343
|
opencodeVersion: null,
|
|
10344
|
+
sessionDbProvenanceAnomaly: false,
|
|
8716
10345
|
opencodeProcess: null,
|
|
10346
|
+
litestreamProcess: null,
|
|
8717
10347
|
connection: null,
|
|
8718
10348
|
channelDriver: null,
|
|
8719
10349
|
running: true,
|
|
@@ -8727,9 +10357,23 @@ async function run(options) {
|
|
|
8727
10357
|
openaiUsageTimer: null,
|
|
8728
10358
|
openaiUsageRearm: null,
|
|
8729
10359
|
resourceUsageTimer: null,
|
|
10360
|
+
credentialSync: null,
|
|
8730
10361
|
authHeader: ""
|
|
8731
10362
|
};
|
|
8732
10363
|
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
10364
|
+
if (options.credentialSyncMarker) {
|
|
10365
|
+
state.credentialSync = createCredentialSync({
|
|
10366
|
+
markerPath: options.credentialSyncMarker,
|
|
10367
|
+
env: process.env,
|
|
10368
|
+
log: (message, level = "info") => {
|
|
10369
|
+
if (level === "error") {
|
|
10370
|
+
logActivity(state, { type: "error", error: message });
|
|
10371
|
+
} else {
|
|
10372
|
+
logActivity(state, { type: "info", level, message });
|
|
10373
|
+
}
|
|
10374
|
+
}
|
|
10375
|
+
});
|
|
10376
|
+
}
|
|
8733
10377
|
if (fileSyncDirectories.length > 0) {
|
|
8734
10378
|
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
8735
10379
|
} else {
|
|
@@ -8755,43 +10399,7 @@ async function run(options) {
|
|
|
8755
10399
|
"warn"
|
|
8756
10400
|
);
|
|
8757
10401
|
}
|
|
8758
|
-
const handleSignal =
|
|
8759
|
-
if (state.shuttingDown) return;
|
|
8760
|
-
state.shuttingDown = true;
|
|
8761
|
-
const shutdownStartedAt = Date.now();
|
|
8762
|
-
if (state.interactive) {
|
|
8763
|
-
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
8764
|
-
displayStatus(state);
|
|
8765
|
-
} else {
|
|
8766
|
-
log2(state, "Shutting down...");
|
|
8767
|
-
}
|
|
8768
|
-
const durations = await cleanup(state, { graceful: true });
|
|
8769
|
-
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
8770
|
-
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
8771
|
-
let timer;
|
|
8772
|
-
const flushed = shutdownTelemetry().then(
|
|
8773
|
-
() => true,
|
|
8774
|
-
(error2) => {
|
|
8775
|
-
log2(
|
|
8776
|
-
state,
|
|
8777
|
-
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
8778
|
-
"warn"
|
|
8779
|
-
);
|
|
8780
|
-
return true;
|
|
8781
|
-
}
|
|
8782
|
-
);
|
|
8783
|
-
const timedOut = new Promise((resolve3) => {
|
|
8784
|
-
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
8785
|
-
});
|
|
8786
|
-
if (!await Promise.race([flushed, timedOut])) {
|
|
8787
|
-
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
8788
|
-
}
|
|
8789
|
-
clearTimeout(timer);
|
|
8790
|
-
});
|
|
8791
|
-
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
8792
|
-
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
8793
|
-
process.exit(0);
|
|
8794
|
-
};
|
|
10402
|
+
const handleSignal = () => beginGracefulShutdown(state, "signal");
|
|
8795
10403
|
process.on("SIGINT", handleSignal);
|
|
8796
10404
|
process.on("SIGTERM", handleSignal);
|
|
8797
10405
|
try {
|
|
@@ -8921,7 +10529,68 @@ async function run(options) {
|
|
|
8921
10529
|
} else {
|
|
8922
10530
|
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
8923
10531
|
}
|
|
10532
|
+
if (options.restoreRunnerCredentials) {
|
|
10533
|
+
log2(state, "Restoring runner credentials before starting OpenCode");
|
|
10534
|
+
const credentialContext = {
|
|
10535
|
+
env: process.env,
|
|
10536
|
+
log: (message, level = "info") => {
|
|
10537
|
+
if (level === "error") {
|
|
10538
|
+
logActivity(state, { type: "error", error: message });
|
|
10539
|
+
} else {
|
|
10540
|
+
logActivity(state, { type: "info", level, message });
|
|
10541
|
+
}
|
|
10542
|
+
}
|
|
10543
|
+
};
|
|
10544
|
+
const githubTokenPopulated = await installRunnerSecret(credentialContext);
|
|
10545
|
+
await restoreCredentialStores(credentialContext);
|
|
10546
|
+
if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
|
|
10547
|
+
}
|
|
10548
|
+
state.credentialSync?.arm();
|
|
10549
|
+
let sessionDbVerifyFatal = false;
|
|
10550
|
+
if (!options.restoreSessionDb) {
|
|
10551
|
+
log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
|
|
10552
|
+
} else {
|
|
10553
|
+
const health = await checkOpenCodeHealth(state.port);
|
|
10554
|
+
if (health.healthy) {
|
|
10555
|
+
log2(
|
|
10556
|
+
state,
|
|
10557
|
+
"Skipping session-DB restore: OpenCode is already serving this database",
|
|
10558
|
+
"debug"
|
|
10559
|
+
);
|
|
10560
|
+
} else {
|
|
10561
|
+
const result = await restoreAndVerifySessionDb({
|
|
10562
|
+
dbPath: sessionDbPath(),
|
|
10563
|
+
litestreamConfig: options.litestreamConfig,
|
|
10564
|
+
noReplicateMarker: options.sessionDbNoReplicateMarker,
|
|
10565
|
+
env: process.env,
|
|
10566
|
+
log: (message, level = "info") => {
|
|
10567
|
+
if (level === "error") {
|
|
10568
|
+
logActivity(state, { type: "error", error: message });
|
|
10569
|
+
} else {
|
|
10570
|
+
logActivity(state, { type: "info", level, message });
|
|
10571
|
+
}
|
|
10572
|
+
},
|
|
10573
|
+
reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
|
|
10574
|
+
});
|
|
10575
|
+
sessionDbVerifyFatal = result.verifyFatal;
|
|
10576
|
+
}
|
|
10577
|
+
}
|
|
8924
10578
|
reportSessionDbRecovery(state);
|
|
10579
|
+
if (sessionDbVerifyFatal) {
|
|
10580
|
+
throw new Error(
|
|
10581
|
+
"SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
|
|
10582
|
+
);
|
|
10583
|
+
}
|
|
10584
|
+
applyRunnerOpenCodeConfig({
|
|
10585
|
+
overlayPath: options.opencodeConfigOverlay,
|
|
10586
|
+
log: (message, level = "info") => {
|
|
10587
|
+
if (level === "error") {
|
|
10588
|
+
logActivity(state, { type: "error", error: message });
|
|
10589
|
+
} else {
|
|
10590
|
+
logActivity(state, { type: "info", level, message });
|
|
10591
|
+
}
|
|
10592
|
+
}
|
|
10593
|
+
});
|
|
8925
10594
|
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
8926
10595
|
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
8927
10596
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
@@ -8930,6 +10599,7 @@ async function run(options) {
|
|
|
8930
10599
|
for (const warning2 of maxActiveSessionsWarnings) {
|
|
8931
10600
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
8932
10601
|
}
|
|
10602
|
+
const preBootMigrationIds = readSessionDbMigrationIds(sessionDbPath());
|
|
8933
10603
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
8934
10604
|
try {
|
|
8935
10605
|
const oc = await ensureOpenCodeRunning({
|
|
@@ -8937,11 +10607,41 @@ async function run(options) {
|
|
|
8937
10607
|
interactive: state.interactive,
|
|
8938
10608
|
agentId: state.agentId,
|
|
8939
10609
|
log: (message) => log2(state, message),
|
|
8940
|
-
startTimeoutMs: opencodeStartTimeoutMs
|
|
10610
|
+
startTimeoutMs: opencodeStartTimeoutMs,
|
|
10611
|
+
inheritStdio: Boolean(options.opencodePidFile)
|
|
8941
10612
|
});
|
|
8942
10613
|
state.port = oc.port;
|
|
8943
|
-
state.opencodeProcess = oc.process;
|
|
10614
|
+
state.opencodeProcess = options.opencodePidFile ? null : oc.process;
|
|
8944
10615
|
state.opencodeVersion = oc.version;
|
|
10616
|
+
if (options.opencodePidFile && oc.process?.pid !== void 0) {
|
|
10617
|
+
try {
|
|
10618
|
+
writeFileSync6(options.opencodePidFile, `${oc.process.pid}
|
|
10619
|
+
`, { mode: 384 });
|
|
10620
|
+
chmodSync3(options.opencodePidFile, 384);
|
|
10621
|
+
} catch (error2) {
|
|
10622
|
+
logActivity(state, {
|
|
10623
|
+
type: "error",
|
|
10624
|
+
error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10625
|
+
});
|
|
10626
|
+
}
|
|
10627
|
+
}
|
|
10628
|
+
if (state.opencodeVersion !== null) {
|
|
10629
|
+
const provenance = checkSessionDbProvenance({
|
|
10630
|
+
dbPath: sessionDbPath(),
|
|
10631
|
+
currentVersion: state.opencodeVersion,
|
|
10632
|
+
homeDir: homedir5(),
|
|
10633
|
+
env: process.env
|
|
10634
|
+
});
|
|
10635
|
+
if (provenance.anomaly) {
|
|
10636
|
+
state.sessionDbProvenanceAnomaly = true;
|
|
10637
|
+
logSessionDbProvenanceMismatch(
|
|
10638
|
+
state,
|
|
10639
|
+
provenance,
|
|
10640
|
+
state.opencodeVersion,
|
|
10641
|
+
preBootMigrationIds?.length ?? null
|
|
10642
|
+
);
|
|
10643
|
+
}
|
|
10644
|
+
}
|
|
8945
10645
|
state.opencodeConnected = oc.notReadyReason === null;
|
|
8946
10646
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
8947
10647
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
@@ -8978,6 +10678,108 @@ async function run(options) {
|
|
|
8978
10678
|
ocSpinner?.fail(error2.message);
|
|
8979
10679
|
throw error2;
|
|
8980
10680
|
}
|
|
10681
|
+
if (options.litestreamPidFile) {
|
|
10682
|
+
if (options.sessionDbNoReplicateMarker && existsSync3(options.sessionDbNoReplicateMarker)) {
|
|
10683
|
+
log2(
|
|
10684
|
+
state,
|
|
10685
|
+
`Skipping Litestream replication because ${options.sessionDbNoReplicateMarker} marks this session database unsafe to replicate`
|
|
10686
|
+
);
|
|
10687
|
+
} else if (!options.litestreamConfig) {
|
|
10688
|
+
logActivity(state, {
|
|
10689
|
+
type: "info",
|
|
10690
|
+
level: "warn",
|
|
10691
|
+
message: "Skipping Litestream replication because no configuration file was provided"
|
|
10692
|
+
});
|
|
10693
|
+
} else {
|
|
10694
|
+
let existingPid;
|
|
10695
|
+
if (existsSync3(options.litestreamPidFile)) {
|
|
10696
|
+
try {
|
|
10697
|
+
const rawPid = readFileSync6(options.litestreamPidFile, "utf8").trim();
|
|
10698
|
+
const parsedPid = Number(rawPid);
|
|
10699
|
+
if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
|
|
10700
|
+
existingPid = parsedPid;
|
|
10701
|
+
}
|
|
10702
|
+
} catch (error2) {
|
|
10703
|
+
logActivity(state, {
|
|
10704
|
+
type: "info",
|
|
10705
|
+
level: "warn",
|
|
10706
|
+
message: `Could not read Litestream pid file ${options.litestreamPidFile}; checking for a new process: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10707
|
+
});
|
|
10708
|
+
}
|
|
10709
|
+
}
|
|
10710
|
+
if (existingPid !== void 0 && isProcessAlive(existingPid)) {
|
|
10711
|
+
log2(state, `Litestream replication is already running with pid ${existingPid}`);
|
|
10712
|
+
} else {
|
|
10713
|
+
const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
|
|
10714
|
+
state.litestreamProcess = null;
|
|
10715
|
+
let failureHandled = false;
|
|
10716
|
+
const reportImageOwnedReplicationFailure = (message) => {
|
|
10717
|
+
if (failureHandled || state.shuttingDown || !state.running) return;
|
|
10718
|
+
failureHandled = true;
|
|
10719
|
+
logActivity(state, { type: "error", error: message });
|
|
10720
|
+
if (state.interactive) displayStatus(state);
|
|
10721
|
+
};
|
|
10722
|
+
litestreamProcess.on("exit", (code, signal) => {
|
|
10723
|
+
reportImageOwnedReplicationFailure(
|
|
10724
|
+
`Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
|
|
10725
|
+
);
|
|
10726
|
+
});
|
|
10727
|
+
litestreamProcess.on("error", (error2) => {
|
|
10728
|
+
reportImageOwnedReplicationFailure(
|
|
10729
|
+
`Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10730
|
+
);
|
|
10731
|
+
});
|
|
10732
|
+
try {
|
|
10733
|
+
if (litestreamProcess.pid !== void 0) {
|
|
10734
|
+
writeFileSync6(options.litestreamPidFile, `${litestreamProcess.pid}
|
|
10735
|
+
`, {
|
|
10736
|
+
mode: 384
|
|
10737
|
+
});
|
|
10738
|
+
chmodSync3(options.litestreamPidFile, 384);
|
|
10739
|
+
}
|
|
10740
|
+
} catch (error2) {
|
|
10741
|
+
logActivity(state, {
|
|
10742
|
+
type: "error",
|
|
10743
|
+
error: `Failed to write Litestream pid file ${options.litestreamPidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10744
|
+
});
|
|
10745
|
+
}
|
|
10746
|
+
log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
|
|
10747
|
+
}
|
|
10748
|
+
}
|
|
10749
|
+
} else if (options.litestreamConfig) {
|
|
10750
|
+
const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
|
|
10751
|
+
state.litestreamProcess = litestreamProcess;
|
|
10752
|
+
let failureHandled = false;
|
|
10753
|
+
const failRunForReplication = (message) => {
|
|
10754
|
+
if (failureHandled || state.shuttingDown || !state.running) return;
|
|
10755
|
+
failureHandled = true;
|
|
10756
|
+
state.shuttingDown = true;
|
|
10757
|
+
logActivity(state, { type: "error", error: message });
|
|
10758
|
+
if (state.interactive) displayStatus(state);
|
|
10759
|
+
void (async () => {
|
|
10760
|
+
try {
|
|
10761
|
+
await cleanup(state);
|
|
10762
|
+
await shutdownTelemetry();
|
|
10763
|
+
} catch (error2) {
|
|
10764
|
+
console.error(
|
|
10765
|
+
`[run] replication failure cleanup failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10766
|
+
);
|
|
10767
|
+
}
|
|
10768
|
+
process.exit(1);
|
|
10769
|
+
})();
|
|
10770
|
+
};
|
|
10771
|
+
litestreamProcess.on("exit", (code, signal) => {
|
|
10772
|
+
failRunForReplication(
|
|
10773
|
+
`Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
|
|
10774
|
+
);
|
|
10775
|
+
});
|
|
10776
|
+
litestreamProcess.on("error", (error2) => {
|
|
10777
|
+
failRunForReplication(
|
|
10778
|
+
`Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10779
|
+
);
|
|
10780
|
+
});
|
|
10781
|
+
log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
|
|
10782
|
+
}
|
|
8981
10783
|
const tunnelSpinner = interactive && !state.json ? ora3("Connecting tunnel...").start() : null;
|
|
8982
10784
|
const channelDriver = new ChannelDriver({
|
|
8983
10785
|
agentId: state.agentId,
|
|
@@ -8989,7 +10791,7 @@ async function run(options) {
|
|
|
8989
10791
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
8990
10792
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
8991
10793
|
fileSyncDirectories,
|
|
8992
|
-
homeDir:
|
|
10794
|
+
homeDir: homedir5(),
|
|
8993
10795
|
maxActiveSessions,
|
|
8994
10796
|
log: (entry) => (
|
|
8995
10797
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
@@ -9135,7 +10937,17 @@ async function run(options) {
|
|
|
9135
10937
|
setTimer: (timer) => {
|
|
9136
10938
|
state.openaiUsageTimer = timer;
|
|
9137
10939
|
},
|
|
9138
|
-
fetchUsage: () =>
|
|
10940
|
+
fetchUsage: async () => {
|
|
10941
|
+
const usage = await getOpenAiUsage(state.port);
|
|
10942
|
+
if (usage.subscription === null) {
|
|
10943
|
+
logActivity(state, {
|
|
10944
|
+
type: "info",
|
|
10945
|
+
level: "debug",
|
|
10946
|
+
message: "OpenAI usage subscription could not be identified from the local credential"
|
|
10947
|
+
});
|
|
10948
|
+
}
|
|
10949
|
+
return usage;
|
|
10950
|
+
},
|
|
9139
10951
|
report: (usage) => reportOpenAiUsage(state.agentId, state.authHeader, usage),
|
|
9140
10952
|
isLocalCredentialProblem: isLocalCredentialProblem2,
|
|
9141
10953
|
forcedOnHint: "connect a ChatGPT account to this runner, or run `opencode auth login`",
|
|
@@ -9181,7 +10993,7 @@ async function run(options) {
|
|
|
9181
10993
|
}
|
|
9182
10994
|
|
|
9183
10995
|
// src/index.ts
|
|
9184
|
-
var { version } =
|
|
10996
|
+
var { version } = createRequire2(import.meta.url)("../package.json");
|
|
9185
10997
|
var program = new Command();
|
|
9186
10998
|
program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
|
|
9187
10999
|
"--endpoint <url>",
|
|
@@ -9238,6 +11050,30 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
9238
11050
|
).option(
|
|
9239
11051
|
"--tunnel-ready-file <path>",
|
|
9240
11052
|
"Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
|
|
11053
|
+
).option(
|
|
11054
|
+
"--litestream-config <path>",
|
|
11055
|
+
"Replicate the OpenCode session database with `litestream replicate` using this config file (written by the runner image). Omit to disable replication."
|
|
11056
|
+
).option(
|
|
11057
|
+
"--opencode-pid-file <path>",
|
|
11058
|
+
"Record the OpenCode pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
|
|
11059
|
+
).option(
|
|
11060
|
+
"--litestream-pid-file <path>",
|
|
11061
|
+
"Record the Litestream pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
|
|
11062
|
+
).option(
|
|
11063
|
+
"--session-db-no-replicate-marker <path>",
|
|
11064
|
+
"Read this marker as a gate before starting Litestream; the session-DB restore writes it when this boot's database is not safe to replicate."
|
|
11065
|
+
).option(
|
|
11066
|
+
"--restore-session-db",
|
|
11067
|
+
"Restore and verify the OpenCode session database before starting OpenCode; requires --litestream-config for the replica and --session-db-no-replicate-marker for give-up records."
|
|
11068
|
+
).option(
|
|
11069
|
+
"--restore-runner-credentials",
|
|
11070
|
+
"Restore the hosted runner secret and persisted credential stores before starting OpenCode."
|
|
11071
|
+
).option(
|
|
11072
|
+
"--opencode-config-overlay <path>",
|
|
11073
|
+
"Apply this runner-provided OpenCode config before starting OpenCode."
|
|
11074
|
+
).option(
|
|
11075
|
+
"--credential-sync-marker <path>",
|
|
11076
|
+
"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."
|
|
9241
11077
|
).action(
|
|
9242
11078
|
(options) => {
|
|
9243
11079
|
run({
|
|
@@ -9269,7 +11105,15 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
9269
11105
|
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
9270
11106
|
// resolveFileSyncDirectories.
|
|
9271
11107
|
enableFileSyncTo: options.enableFileSyncTo,
|
|
9272
|
-
tunnelReadyFile: options.tunnelReadyFile
|
|
11108
|
+
tunnelReadyFile: options.tunnelReadyFile,
|
|
11109
|
+
litestreamConfig: options.litestreamConfig,
|
|
11110
|
+
opencodePidFile: options.opencodePidFile,
|
|
11111
|
+
litestreamPidFile: options.litestreamPidFile,
|
|
11112
|
+
sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
|
|
11113
|
+
restoreSessionDb: options.restoreSessionDb,
|
|
11114
|
+
restoreRunnerCredentials: options.restoreRunnerCredentials,
|
|
11115
|
+
opencodeConfigOverlay: options.opencodeConfigOverlay,
|
|
11116
|
+
credentialSyncMarker: options.credentialSyncMarker
|
|
9273
11117
|
});
|
|
9274
11118
|
}
|
|
9275
11119
|
);
|