@evident-ai/cli 3.4.1-dev.c6e7cf0 → 3.4.1-dev.dbc0a1f
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 +21 -0
- package/dist/index.js +1320 -99
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -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
|
}
|
|
@@ -1183,8 +1183,9 @@ async function claudeUsage() {
|
|
|
1183
1183
|
}
|
|
1184
1184
|
|
|
1185
1185
|
// src/commands/run.ts
|
|
1186
|
-
import {
|
|
1187
|
-
import {
|
|
1186
|
+
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
|
|
1187
|
+
import { homedir as homedir5 } from "os";
|
|
1188
|
+
import { isAbsolute as isAbsolute3, join as join8, parse, resolve as resolvePath2 } from "path";
|
|
1188
1189
|
import chalk6 from "chalk";
|
|
1189
1190
|
|
|
1190
1191
|
// ../../packages/types/src/agents/index.ts
|
|
@@ -1524,7 +1525,7 @@ function drainSessionDbRecoveryReport({
|
|
|
1524
1525
|
skippedLines++;
|
|
1525
1526
|
return [];
|
|
1526
1527
|
}
|
|
1527
|
-
return [value];
|
|
1528
|
+
return [{ ...value, replication_suspended: value.replication_suspended ?? false }];
|
|
1528
1529
|
} catch (error2) {
|
|
1529
1530
|
skippedLines++;
|
|
1530
1531
|
console.error(
|
|
@@ -1549,12 +1550,39 @@ function buildSessionDbRecoveryActivity(record) {
|
|
|
1549
1550
|
const level = record.severity === "warning" ? "warn" : record.severity === "error" ? "error" : null;
|
|
1550
1551
|
if (!level) return null;
|
|
1551
1552
|
const noVerifiedPoint = record.verified_restore_point ? ` The verified restore point is ${record.verified_restore_point}.` : " No verified restore point is known.";
|
|
1553
|
+
const replication = record.replication_suspended ? " This start is not backing up its new session history; restart after fixing the cause." : "";
|
|
1554
|
+
const giveupMessage = (() => {
|
|
1555
|
+
switch (record.reason) {
|
|
1556
|
+
case "restore_deadline_exceeded":
|
|
1557
|
+
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.";
|
|
1558
|
+
case "restore_tool_unusable":
|
|
1559
|
+
case "classification_unrecognised":
|
|
1560
|
+
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.";
|
|
1561
|
+
case "synchroniser_config_unevaluable":
|
|
1562
|
+
case "synchroniser_config_incomplete":
|
|
1563
|
+
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.";
|
|
1564
|
+
case "synchroniser_config_unresolved":
|
|
1565
|
+
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.";
|
|
1566
|
+
case "litestream_config_unavailable":
|
|
1567
|
+
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.";
|
|
1568
|
+
case "classification_fatal":
|
|
1569
|
+
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.";
|
|
1570
|
+
default:
|
|
1571
|
+
return null;
|
|
1572
|
+
}
|
|
1573
|
+
})();
|
|
1574
|
+
if (giveupMessage)
|
|
1575
|
+
return {
|
|
1576
|
+
level,
|
|
1577
|
+
metadata: withoutContractFields(record),
|
|
1578
|
+
message: `${giveupMessage}${replication}`
|
|
1579
|
+
};
|
|
1552
1580
|
switch (record.outcome) {
|
|
1553
1581
|
case "fresh_session_db":
|
|
1554
1582
|
return {
|
|
1555
1583
|
level,
|
|
1556
1584
|
metadata: withoutContractFields(record),
|
|
1557
|
-
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
|
|
1585
|
+
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}`
|
|
1558
1586
|
};
|
|
1559
1587
|
case "restore_retried":
|
|
1560
1588
|
return {
|
|
@@ -1592,7 +1620,7 @@ function buildSessionDbRecoveryActivity(record) {
|
|
|
1592
1620
|
return {
|
|
1593
1621
|
level,
|
|
1594
1622
|
metadata: withoutContractFields(record),
|
|
1595
|
-
message:
|
|
1623
|
+
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}`
|
|
1596
1624
|
};
|
|
1597
1625
|
case "session_db_boot_refused":
|
|
1598
1626
|
return {
|
|
@@ -1632,7 +1660,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
|
|
|
1632
1660
|
function isSessionDbRecoveryRecord(value) {
|
|
1633
1661
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1634
1662
|
const record = value;
|
|
1635
|
-
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(
|
|
1663
|
+
return record.v === 1 && record.event === "session_db_recovery" && typeof record.at === "string" && STAGES.has(record.stage) && OUTCOMES.has(record.outcome) && SEVERITIES.has(record.severity) && typeof record.reason === "string" && (record.replication_suspended === void 0 || typeof record.replication_suspended === "boolean") && NUMBER_FIELDS.every((field) => record[field] === null || Number.isInteger(record[field])) && STRING_OR_NULL_FIELDS.every(
|
|
1636
1664
|
(field) => record[field] === null || typeof record[field] === "string"
|
|
1637
1665
|
);
|
|
1638
1666
|
}
|
|
@@ -1661,11 +1689,517 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
1661
1689
|
if (health.healthy) {
|
|
1662
1690
|
return health;
|
|
1663
1691
|
}
|
|
1664
|
-
await new Promise((
|
|
1692
|
+
await new Promise((resolve4) => setTimeout(resolve4, 1e3));
|
|
1665
1693
|
}
|
|
1666
1694
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
1667
1695
|
}
|
|
1668
1696
|
|
|
1697
|
+
// src/lib/opencode/session-db-boot.ts
|
|
1698
|
+
import { spawn as spawn2 } from "child_process";
|
|
1699
|
+
import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "fs";
|
|
1700
|
+
import { homedir as homedir2 } from "os";
|
|
1701
|
+
import { dirname as dirname2, resolve as resolvePath } from "path";
|
|
1702
|
+
|
|
1703
|
+
// src/lib/runner-synchroniser.ts
|
|
1704
|
+
import { spawn } from "child_process";
|
|
1705
|
+
function appendError(stderr, error2) {
|
|
1706
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
1707
|
+
return stderr === "" ? message : `${stderr}
|
|
1708
|
+
${message}`;
|
|
1709
|
+
}
|
|
1710
|
+
function runSynchroniser(args, opts) {
|
|
1711
|
+
return new Promise((resolve4) => {
|
|
1712
|
+
let child;
|
|
1713
|
+
let stdout = "";
|
|
1714
|
+
let stderr = "";
|
|
1715
|
+
let settled = false;
|
|
1716
|
+
const timer = {};
|
|
1717
|
+
const finish = (result) => {
|
|
1718
|
+
if (settled) return;
|
|
1719
|
+
settled = true;
|
|
1720
|
+
if (timer.handle) clearTimeout(timer.handle);
|
|
1721
|
+
resolve4(result);
|
|
1722
|
+
};
|
|
1723
|
+
try {
|
|
1724
|
+
child = spawn("runner-synchroniser", args, {
|
|
1725
|
+
env: opts.env ?? process.env,
|
|
1726
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1727
|
+
});
|
|
1728
|
+
} catch (error2) {
|
|
1729
|
+
finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
|
|
1730
|
+
return;
|
|
1731
|
+
}
|
|
1732
|
+
child.stdout?.setEncoding("utf8");
|
|
1733
|
+
child.stdout?.on("data", (chunk) => {
|
|
1734
|
+
stdout += chunk;
|
|
1735
|
+
});
|
|
1736
|
+
child.stderr?.setEncoding("utf8");
|
|
1737
|
+
child.stderr?.on("data", (chunk) => {
|
|
1738
|
+
stderr += chunk;
|
|
1739
|
+
});
|
|
1740
|
+
child.once("error", (error2) => {
|
|
1741
|
+
finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
|
|
1742
|
+
});
|
|
1743
|
+
child.once("close", (code) => {
|
|
1744
|
+
finish({ code, stdout, stderr, timedOut: false });
|
|
1745
|
+
});
|
|
1746
|
+
timer.handle = setTimeout(
|
|
1747
|
+
() => {
|
|
1748
|
+
child.kill("SIGKILL");
|
|
1749
|
+
finish({ code: null, stdout, stderr, timedOut: true });
|
|
1750
|
+
},
|
|
1751
|
+
Math.max(0, opts.timeoutMs)
|
|
1752
|
+
);
|
|
1753
|
+
});
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// src/lib/opencode/session-db-boot.ts
|
|
1757
|
+
var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
|
|
1758
|
+
var SESSION_DB_VERIFY_TIMEOUT_MS = 12e4;
|
|
1759
|
+
var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
|
|
1760
|
+
var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 120;
|
|
1761
|
+
function commandError(result) {
|
|
1762
|
+
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
1763
|
+
}
|
|
1764
|
+
function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
|
|
1765
|
+
options.reportRecovery({
|
|
1766
|
+
v: 1,
|
|
1767
|
+
event: "session_db_recovery",
|
|
1768
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1769
|
+
stage,
|
|
1770
|
+
outcome,
|
|
1771
|
+
severity: "error",
|
|
1772
|
+
reason,
|
|
1773
|
+
litestream_exit_code: litestreamExitCode,
|
|
1774
|
+
attempt: null,
|
|
1775
|
+
replica_objects: null,
|
|
1776
|
+
replica_bytes: null,
|
|
1777
|
+
quarantine_destination: null,
|
|
1778
|
+
quarantined_objects: null,
|
|
1779
|
+
quarantine_failed_objects: null,
|
|
1780
|
+
quarantined_bytes: null,
|
|
1781
|
+
verified_restore_point: null,
|
|
1782
|
+
restore_points_tried: null,
|
|
1783
|
+
replication_suspended: stage === "restore"
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
function clearMarker(options) {
|
|
1787
|
+
if (!options.noReplicateMarker) return;
|
|
1788
|
+
try {
|
|
1789
|
+
unlinkSync2(options.noReplicateMarker);
|
|
1790
|
+
} catch (error2) {
|
|
1791
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return;
|
|
1792
|
+
options.log(
|
|
1793
|
+
`Could not clear the previous session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1794
|
+
"warn"
|
|
1795
|
+
);
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
function markNoReplicate(options, message) {
|
|
1799
|
+
if (options.noReplicateMarker) {
|
|
1800
|
+
try {
|
|
1801
|
+
mkdirSync(dirname2(options.noReplicateMarker), { recursive: true });
|
|
1802
|
+
writeFileSync(options.noReplicateMarker, "");
|
|
1803
|
+
} catch (error2) {
|
|
1804
|
+
options.log(
|
|
1805
|
+
`Could not write session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1806
|
+
"error"
|
|
1807
|
+
);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
options.log(`SESSION-DB-NO-REPLICATE: ${message}`, "warn");
|
|
1811
|
+
}
|
|
1812
|
+
function discardSessionDbDebris(options) {
|
|
1813
|
+
for (const path of [options.dbPath, `${options.dbPath}-wal`, `${options.dbPath}-shm`]) {
|
|
1814
|
+
try {
|
|
1815
|
+
unlinkSync2(path);
|
|
1816
|
+
} catch (error2) {
|
|
1817
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") continue;
|
|
1818
|
+
options.log(
|
|
1819
|
+
`Could not remove session-DB debris ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1820
|
+
"warn"
|
|
1821
|
+
);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
function splitDiagnostics(text) {
|
|
1826
|
+
return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
|
|
1827
|
+
}
|
|
1828
|
+
function logSynchroniserDiagnostics(result, options) {
|
|
1829
|
+
for (const line of splitDiagnostics(result.stderr)) options.log(line, "warn");
|
|
1830
|
+
}
|
|
1831
|
+
function parseSingleQuotedAssignment(line) {
|
|
1832
|
+
const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
|
|
1833
|
+
if (!match || !match[2].startsWith("'")) return null;
|
|
1834
|
+
const valueSource = match[2];
|
|
1835
|
+
let value = "";
|
|
1836
|
+
for (let index = 1; index < valueSource.length; index++) {
|
|
1837
|
+
const character = valueSource[index];
|
|
1838
|
+
if (character !== "'") {
|
|
1839
|
+
value += character;
|
|
1840
|
+
continue;
|
|
1841
|
+
}
|
|
1842
|
+
if (index === valueSource.length - 1) return [match[1], value];
|
|
1843
|
+
if (valueSource.slice(index + 1, index + 4) !== "\\''") return null;
|
|
1844
|
+
value += "'";
|
|
1845
|
+
index += 3;
|
|
1846
|
+
}
|
|
1847
|
+
return null;
|
|
1848
|
+
}
|
|
1849
|
+
function parseSynchroniserEnv(stdout) {
|
|
1850
|
+
const values = {};
|
|
1851
|
+
for (const line of stdout.split("\n")) {
|
|
1852
|
+
if (line.trim() === "") continue;
|
|
1853
|
+
const assignment = parseSingleQuotedAssignment(line);
|
|
1854
|
+
if (!assignment) return null;
|
|
1855
|
+
values[assignment[0]] = assignment[1];
|
|
1856
|
+
}
|
|
1857
|
+
return values;
|
|
1858
|
+
}
|
|
1859
|
+
function runCommand(command, args, options) {
|
|
1860
|
+
return new Promise((resolve4) => {
|
|
1861
|
+
let child;
|
|
1862
|
+
let stdout = "";
|
|
1863
|
+
let stderr = "";
|
|
1864
|
+
let settled = false;
|
|
1865
|
+
const finish = (result) => {
|
|
1866
|
+
if (settled) return;
|
|
1867
|
+
settled = true;
|
|
1868
|
+
if (timer) clearTimeout(timer);
|
|
1869
|
+
resolve4(result);
|
|
1870
|
+
};
|
|
1871
|
+
try {
|
|
1872
|
+
child = spawn2(command, args, {
|
|
1873
|
+
env: options.env,
|
|
1874
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1875
|
+
});
|
|
1876
|
+
} catch (error2) {
|
|
1877
|
+
resolve4({
|
|
1878
|
+
code: null,
|
|
1879
|
+
stdout,
|
|
1880
|
+
stderr: error2 instanceof Error ? error2.message : String(error2),
|
|
1881
|
+
timedOut: false
|
|
1882
|
+
});
|
|
1883
|
+
return;
|
|
1884
|
+
}
|
|
1885
|
+
child.stdout?.setEncoding("utf8");
|
|
1886
|
+
child.stdout?.on("data", (chunk) => {
|
|
1887
|
+
stdout += chunk;
|
|
1888
|
+
});
|
|
1889
|
+
child.stderr?.setEncoding("utf8");
|
|
1890
|
+
child.stderr?.on("data", (chunk) => {
|
|
1891
|
+
stderr += chunk;
|
|
1892
|
+
});
|
|
1893
|
+
child.once("error", (error2) => {
|
|
1894
|
+
finish({
|
|
1895
|
+
code: null,
|
|
1896
|
+
stdout,
|
|
1897
|
+
stderr: stderr === "" ? error2.message : `${stderr}
|
|
1898
|
+
${error2.message}`,
|
|
1899
|
+
timedOut: false
|
|
1900
|
+
});
|
|
1901
|
+
});
|
|
1902
|
+
child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
|
|
1903
|
+
const timer = setTimeout(
|
|
1904
|
+
() => {
|
|
1905
|
+
child.kill("SIGKILL");
|
|
1906
|
+
finish({ code: null, stdout, stderr, timedOut: true });
|
|
1907
|
+
},
|
|
1908
|
+
Math.max(0, options.timeoutMs)
|
|
1909
|
+
);
|
|
1910
|
+
});
|
|
1911
|
+
}
|
|
1912
|
+
async function ensureLitestreamConfig(options, env) {
|
|
1913
|
+
const configPath = options.litestreamConfig;
|
|
1914
|
+
if (!configPath) {
|
|
1915
|
+
markNoReplicate(options, "no Litestream configuration path was provided");
|
|
1916
|
+
reportRecord(
|
|
1917
|
+
"restore",
|
|
1918
|
+
"restore_misconfigured",
|
|
1919
|
+
"litestream_config_unavailable",
|
|
1920
|
+
null,
|
|
1921
|
+
options
|
|
1922
|
+
);
|
|
1923
|
+
return null;
|
|
1924
|
+
}
|
|
1925
|
+
try {
|
|
1926
|
+
if (statSync2(configPath).size > 0) return configPath;
|
|
1927
|
+
} catch (error2) {
|
|
1928
|
+
if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
|
|
1929
|
+
options.log(
|
|
1930
|
+
`Could not inspect ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1931
|
+
"warn"
|
|
1932
|
+
);
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
const rendered = await runSynchroniser(["litestream-config"], {
|
|
1936
|
+
timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
|
|
1937
|
+
env
|
|
1938
|
+
});
|
|
1939
|
+
logSynchroniserDiagnostics(rendered, options);
|
|
1940
|
+
if (rendered.timedOut || rendered.code !== 0) {
|
|
1941
|
+
options.log(
|
|
1942
|
+
`Could not generate ${configPath}: runner-synchroniser litestream-config failed (${commandError(rendered)})`,
|
|
1943
|
+
"error"
|
|
1944
|
+
);
|
|
1945
|
+
markNoReplicate(options, `could not generate ${configPath}`);
|
|
1946
|
+
reportRecord(
|
|
1947
|
+
"restore",
|
|
1948
|
+
"restore_misconfigured",
|
|
1949
|
+
"litestream_config_unavailable",
|
|
1950
|
+
null,
|
|
1951
|
+
options
|
|
1952
|
+
);
|
|
1953
|
+
return null;
|
|
1954
|
+
}
|
|
1955
|
+
try {
|
|
1956
|
+
mkdirSync(dirname2(configPath), { recursive: true });
|
|
1957
|
+
writeFileSync(configPath, rendered.stdout);
|
|
1958
|
+
} catch (error2) {
|
|
1959
|
+
options.log(
|
|
1960
|
+
`Could not write ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
1961
|
+
"error"
|
|
1962
|
+
);
|
|
1963
|
+
markNoReplicate(options, `could not generate ${configPath}`);
|
|
1964
|
+
reportRecord(
|
|
1965
|
+
"restore",
|
|
1966
|
+
"restore_misconfigured",
|
|
1967
|
+
"litestream_config_unavailable",
|
|
1968
|
+
null,
|
|
1969
|
+
options
|
|
1970
|
+
);
|
|
1971
|
+
return null;
|
|
1972
|
+
}
|
|
1973
|
+
const version2 = await runCommand("litestream", ["version"], {
|
|
1974
|
+
env,
|
|
1975
|
+
timeoutMs: 1e4
|
|
1976
|
+
});
|
|
1977
|
+
const litestreamVersion = version2.code === 0 ? version2.stdout.trim() || "unknown" : "unknown";
|
|
1978
|
+
const regionEmpty = !/^\s*region:\s*\S+/m.test(rendered.stdout);
|
|
1979
|
+
options.log(
|
|
1980
|
+
`litestream ${litestreamVersion}; AWS_REGION=${env.AWS_REGION ?? "<unset>"} AWS_DEFAULT_REGION=${env.AWS_DEFAULT_REGION ?? "<unset>"}; rendered litestream.yml region empty: ${regionEmpty ? "yes" : "no"}`
|
|
1981
|
+
);
|
|
1982
|
+
return configPath;
|
|
1983
|
+
}
|
|
1984
|
+
function restoreGiveUp(options, reason, message, litestreamExitCode, outcome = "fresh_session_db") {
|
|
1985
|
+
discardSessionDbDebris(options);
|
|
1986
|
+
markNoReplicate(options, message);
|
|
1987
|
+
reportRecord("restore", outcome, reason, litestreamExitCode, options);
|
|
1988
|
+
}
|
|
1989
|
+
async function restoreSessionDb(options, configPath, env) {
|
|
1990
|
+
const restored = await runCommand(
|
|
1991
|
+
"litestream",
|
|
1992
|
+
["restore", "-config", configPath, "-if-db-not-exists", "-if-replica-exists", options.dbPath],
|
|
1993
|
+
{ env, timeoutMs: SESSION_DB_RESTORE_TIMEOUT_MS }
|
|
1994
|
+
);
|
|
1995
|
+
for (const line of splitDiagnostics(restored.stderr)) options.log(line, "warn");
|
|
1996
|
+
if (restored.timedOut || restored.code === 124 || restored.code === 137) {
|
|
1997
|
+
restoreGiveUp(
|
|
1998
|
+
options,
|
|
1999
|
+
"restore_deadline_exceeded",
|
|
2000
|
+
`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`,
|
|
2001
|
+
restored.code ?? 124
|
|
2002
|
+
);
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
if (restored.code === null || restored.code === 125 || restored.code === 126 || restored.code === 127) {
|
|
2006
|
+
options.log(`litestream restore could not run (${commandError(restored)})`, "error");
|
|
2007
|
+
restoreGiveUp(
|
|
2008
|
+
options,
|
|
2009
|
+
"restore_tool_unusable",
|
|
2010
|
+
`restore tool is broken (${commandError(restored)}); opencode starts with a fresh session DB and nothing is replicated this boot`,
|
|
2011
|
+
restored.code
|
|
2012
|
+
);
|
|
2013
|
+
return;
|
|
2014
|
+
}
|
|
2015
|
+
const classified = await runSynchroniser(
|
|
2016
|
+
[
|
|
2017
|
+
"session-db-classify",
|
|
2018
|
+
String(restored.code ?? 1),
|
|
2019
|
+
"1",
|
|
2020
|
+
"--on-unusable-replica=leave",
|
|
2021
|
+
"--fresh-db-fallback"
|
|
2022
|
+
],
|
|
2023
|
+
{ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS, env }
|
|
2024
|
+
);
|
|
2025
|
+
logSynchroniserDiagnostics(classified, options);
|
|
2026
|
+
const classifyCode = classified.code;
|
|
2027
|
+
switch (classifyCode) {
|
|
2028
|
+
case 0:
|
|
2029
|
+
return;
|
|
2030
|
+
case 31:
|
|
2031
|
+
acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
|
|
2032
|
+
options.log(
|
|
2033
|
+
"SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and replicating into the existing prefix this boot",
|
|
2034
|
+
"warn"
|
|
2035
|
+
);
|
|
2036
|
+
return;
|
|
2037
|
+
case 32:
|
|
2038
|
+
acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
|
|
2039
|
+
discardSessionDbDebris(options);
|
|
2040
|
+
markNoReplicate(
|
|
2041
|
+
options,
|
|
2042
|
+
"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"
|
|
2043
|
+
);
|
|
2044
|
+
return;
|
|
2045
|
+
case 30:
|
|
2046
|
+
restoreGiveUp(
|
|
2047
|
+
options,
|
|
2048
|
+
"classification_fatal",
|
|
2049
|
+
"session-db-classify returned fatal (30); see the FATAL message above",
|
|
2050
|
+
restored.code,
|
|
2051
|
+
"restore_misconfigured"
|
|
2052
|
+
);
|
|
2053
|
+
return;
|
|
2054
|
+
default:
|
|
2055
|
+
restoreGiveUp(
|
|
2056
|
+
options,
|
|
2057
|
+
"classification_unrecognised",
|
|
2058
|
+
`session-db-classify exited ${classifyCode ?? "null"}, which is none of its documented answers`,
|
|
2059
|
+
restored.code
|
|
2060
|
+
);
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
async function verifySessionDb(options, configPath, env) {
|
|
2064
|
+
if (!options.noReplicateMarker || !fileExists(options.noReplicateMarker)) {
|
|
2065
|
+
const result = await runSynchroniser(["session-db-verify", configPath], {
|
|
2066
|
+
timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
|
|
2067
|
+
env: {
|
|
2068
|
+
...env,
|
|
2069
|
+
// The synchroniser reads this value in SECONDS. Keep this at 120, not
|
|
2070
|
+
// 120_000, so the walkback gives up before the outer process bound.
|
|
2071
|
+
EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
|
|
2072
|
+
SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
|
|
2073
|
+
)
|
|
2074
|
+
}
|
|
2075
|
+
});
|
|
2076
|
+
logSynchroniserDiagnostics(result, options);
|
|
2077
|
+
if (result.timedOut || result.code === 124 || result.code === 137) {
|
|
2078
|
+
options.log(
|
|
2079
|
+
`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`,
|
|
2080
|
+
"warn"
|
|
2081
|
+
);
|
|
2082
|
+
return false;
|
|
2083
|
+
}
|
|
2084
|
+
if (result.code === 34) {
|
|
2085
|
+
reportRecord(
|
|
2086
|
+
"verify",
|
|
2087
|
+
"session_db_boot_refused",
|
|
2088
|
+
result.stderr.includes("SESSION-DB-LOCAL-DISCARD-FAILED") ? "local_discard_failed" : "replica_separation_unproven",
|
|
2089
|
+
null,
|
|
2090
|
+
options
|
|
2091
|
+
);
|
|
2092
|
+
return true;
|
|
2093
|
+
}
|
|
2094
|
+
if (result.code === 33) {
|
|
2095
|
+
options.log(
|
|
2096
|
+
"SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
|
|
2097
|
+
"warn"
|
|
2098
|
+
);
|
|
2099
|
+
return false;
|
|
2100
|
+
}
|
|
2101
|
+
if (result.code !== 0) {
|
|
2102
|
+
options.log(
|
|
2103
|
+
`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`,
|
|
2104
|
+
"warn"
|
|
2105
|
+
);
|
|
2106
|
+
}
|
|
2107
|
+
return false;
|
|
2108
|
+
}
|
|
2109
|
+
options.log(
|
|
2110
|
+
"skipping session-DB verification: this boot's session DB was not proven safe to replicate",
|
|
2111
|
+
"debug"
|
|
2112
|
+
);
|
|
2113
|
+
return false;
|
|
2114
|
+
}
|
|
2115
|
+
function fileExists(path) {
|
|
2116
|
+
try {
|
|
2117
|
+
statSync2(path);
|
|
2118
|
+
return true;
|
|
2119
|
+
} catch (error2) {
|
|
2120
|
+
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return false;
|
|
2121
|
+
return true;
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
async function restoreAndVerifySessionDb(options) {
|
|
2125
|
+
const env = options.env ?? process.env;
|
|
2126
|
+
clearMarker(options);
|
|
2127
|
+
acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
|
|
2128
|
+
const synchroniserEnv = await runSynchroniser(["env"], {
|
|
2129
|
+
timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
|
|
2130
|
+
env
|
|
2131
|
+
});
|
|
2132
|
+
logSynchroniserDiagnostics(synchroniserEnv, options);
|
|
2133
|
+
if (synchroniserEnv.timedOut || synchroniserEnv.code !== 0) {
|
|
2134
|
+
options.log(
|
|
2135
|
+
`runner-synchroniser env could not resolve the session-DB configuration (${commandError(synchroniserEnv)})`,
|
|
2136
|
+
"error"
|
|
2137
|
+
);
|
|
2138
|
+
markNoReplicate(
|
|
2139
|
+
options,
|
|
2140
|
+
"could not resolve the runner-synchroniser configuration (see the ERROR above)"
|
|
2141
|
+
);
|
|
2142
|
+
reportRecord(
|
|
2143
|
+
"restore",
|
|
2144
|
+
"restore_misconfigured",
|
|
2145
|
+
"synchroniser_config_unresolved",
|
|
2146
|
+
null,
|
|
2147
|
+
options
|
|
2148
|
+
);
|
|
2149
|
+
return { verifyFatal: false };
|
|
2150
|
+
}
|
|
2151
|
+
const values = parseSynchroniserEnv(synchroniserEnv.stdout);
|
|
2152
|
+
if (!values) {
|
|
2153
|
+
markNoReplicate(
|
|
2154
|
+
options,
|
|
2155
|
+
"the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
|
|
2156
|
+
);
|
|
2157
|
+
reportRecord(
|
|
2158
|
+
"restore",
|
|
2159
|
+
"restore_misconfigured",
|
|
2160
|
+
"synchroniser_config_unevaluable",
|
|
2161
|
+
null,
|
|
2162
|
+
options
|
|
2163
|
+
);
|
|
2164
|
+
return { verifyFatal: false };
|
|
2165
|
+
}
|
|
2166
|
+
const synchroniserDbPath = values.OPENCODE_DB_PATH;
|
|
2167
|
+
if (!synchroniserDbPath) {
|
|
2168
|
+
markNoReplicate(
|
|
2169
|
+
options,
|
|
2170
|
+
"run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
|
|
2171
|
+
);
|
|
2172
|
+
reportRecord(
|
|
2173
|
+
"restore",
|
|
2174
|
+
"restore_misconfigured",
|
|
2175
|
+
"synchroniser_config_incomplete",
|
|
2176
|
+
null,
|
|
2177
|
+
options
|
|
2178
|
+
);
|
|
2179
|
+
return { verifyFatal: false };
|
|
2180
|
+
}
|
|
2181
|
+
if (resolvePath(synchroniserDbPath) !== resolvePath(options.dbPath)) {
|
|
2182
|
+
options.log(
|
|
2183
|
+
`runner-synchroniser reported OPENCODE_DB_PATH=${synchroniserDbPath}, but OpenCode uses ${options.dbPath}; continuing with OpenCode's session-DB path`,
|
|
2184
|
+
"warn"
|
|
2185
|
+
);
|
|
2186
|
+
}
|
|
2187
|
+
if (!values.PERSISTENCE_BUCKET) {
|
|
2188
|
+
options.log(
|
|
2189
|
+
"SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated.",
|
|
2190
|
+
"warn"
|
|
2191
|
+
);
|
|
2192
|
+
return { verifyFatal: false };
|
|
2193
|
+
}
|
|
2194
|
+
const configPath = await ensureLitestreamConfig(options, env);
|
|
2195
|
+
if (!configPath) return { verifyFatal: false };
|
|
2196
|
+
await restoreSessionDb(options, configPath, env);
|
|
2197
|
+
if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
|
|
2198
|
+
return { verifyFatal: false };
|
|
2199
|
+
}
|
|
2200
|
+
return { verifyFatal: await verifySessionDb(options, configPath, env) };
|
|
2201
|
+
}
|
|
2202
|
+
|
|
1669
2203
|
// src/lib/opencode/opencode-version-gate.ts
|
|
1670
2204
|
var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
|
|
1671
2205
|
function isQueueValidatedVersion(version2) {
|
|
@@ -1680,7 +2214,63 @@ function buildOpenCodeVersionWarning(version2) {
|
|
|
1680
2214
|
}
|
|
1681
2215
|
|
|
1682
2216
|
// src/lib/opencode/process.ts
|
|
1683
|
-
import { execSync, spawn } from "child_process";
|
|
2217
|
+
import { execSync, spawn as spawn3 } from "child_process";
|
|
2218
|
+
|
|
2219
|
+
// src/lib/process-stop.ts
|
|
2220
|
+
async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
2221
|
+
if (!child.pid) {
|
|
2222
|
+
return { outcome: "not-running", code: child.exitCode, signal: child.signalCode };
|
|
2223
|
+
}
|
|
2224
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
2225
|
+
return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
|
|
2226
|
+
}
|
|
2227
|
+
return new Promise((resolve4, reject) => {
|
|
2228
|
+
let forced = false;
|
|
2229
|
+
let settled = false;
|
|
2230
|
+
const timer = setTimeout(() => {
|
|
2231
|
+
forced = true;
|
|
2232
|
+
try {
|
|
2233
|
+
sendKill();
|
|
2234
|
+
} catch (error2) {
|
|
2235
|
+
if (error2.code === "ESRCH") {
|
|
2236
|
+
finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
|
|
2237
|
+
} else {
|
|
2238
|
+
fail(error2);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
}, timeoutMs);
|
|
2242
|
+
const finish = (result) => {
|
|
2243
|
+
if (settled) return;
|
|
2244
|
+
settled = true;
|
|
2245
|
+
clearTimeout(timer);
|
|
2246
|
+
child.removeListener("exit", onExit);
|
|
2247
|
+
resolve4(result);
|
|
2248
|
+
};
|
|
2249
|
+
const fail = (error2) => {
|
|
2250
|
+
if (settled) return;
|
|
2251
|
+
settled = true;
|
|
2252
|
+
clearTimeout(timer);
|
|
2253
|
+
child.removeListener("exit", onExit);
|
|
2254
|
+
reject(error2);
|
|
2255
|
+
};
|
|
2256
|
+
const onExit = (code, signal) => {
|
|
2257
|
+
finish({ outcome: forced ? "killed" : "exited", code, signal });
|
|
2258
|
+
};
|
|
2259
|
+
child.once("exit", onExit);
|
|
2260
|
+
try {
|
|
2261
|
+
sendTerm();
|
|
2262
|
+
} catch (error2) {
|
|
2263
|
+
if (error2.code === "ESRCH") {
|
|
2264
|
+
finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
|
|
2265
|
+
} else {
|
|
2266
|
+
fail(error2);
|
|
2267
|
+
}
|
|
2268
|
+
return;
|
|
2269
|
+
}
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
|
|
2273
|
+
// src/lib/opencode/process.ts
|
|
1684
2274
|
var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
|
|
1685
2275
|
function getProcessCwd(pid) {
|
|
1686
2276
|
const platform = process.platform;
|
|
@@ -1836,39 +2426,45 @@ async function findHealthyOpenCodeInstances() {
|
|
|
1836
2426
|
}
|
|
1837
2427
|
return healthy;
|
|
1838
2428
|
}
|
|
1839
|
-
async function startOpenCode(port) {
|
|
2429
|
+
async function startOpenCode(port, options = {}) {
|
|
1840
2430
|
let command = "opencode";
|
|
1841
|
-
|
|
2431
|
+
const printLogs = options.inheritStdio ? ["--print-logs"] : [];
|
|
2432
|
+
let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
|
|
1842
2433
|
try {
|
|
1843
2434
|
execSync("which opencode", { stdio: "ignore" });
|
|
1844
2435
|
} catch {
|
|
1845
2436
|
command = "npx";
|
|
1846
|
-
args = [
|
|
1847
|
-
|
|
1848
|
-
|
|
2437
|
+
args = [
|
|
2438
|
+
"opencode",
|
|
2439
|
+
"serve",
|
|
2440
|
+
"--port",
|
|
2441
|
+
port.toString(),
|
|
2442
|
+
"--hostname",
|
|
2443
|
+
"127.0.0.1",
|
|
2444
|
+
...printLogs
|
|
2445
|
+
];
|
|
2446
|
+
}
|
|
2447
|
+
const child = spawn3(command, args, {
|
|
1849
2448
|
detached: true,
|
|
1850
|
-
stdio: "ignore",
|
|
2449
|
+
stdio: options.inheritStdio ? "inherit" : "ignore",
|
|
1851
2450
|
cwd: process.cwd()
|
|
1852
2451
|
});
|
|
1853
2452
|
return child;
|
|
1854
2453
|
}
|
|
1855
|
-
function
|
|
1856
|
-
|
|
1857
|
-
return;
|
|
1858
|
-
}
|
|
1859
|
-
try {
|
|
2454
|
+
function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
|
|
2455
|
+
const sendSignal = (signal) => {
|
|
1860
2456
|
if (process.platform === "win32") {
|
|
1861
|
-
opencodeProcess.kill(
|
|
2457
|
+
opencodeProcess.kill(signal);
|
|
1862
2458
|
} else {
|
|
1863
|
-
process.kill(-opencodeProcess.pid,
|
|
1864
|
-
}
|
|
1865
|
-
} catch (err) {
|
|
1866
|
-
if (err.code !== "ESRCH") {
|
|
1867
|
-
console.warn(
|
|
1868
|
-
`stopOpenCode: kill failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1869
|
-
);
|
|
2459
|
+
process.kill(-opencodeProcess.pid, signal);
|
|
1870
2460
|
}
|
|
1871
|
-
}
|
|
2461
|
+
};
|
|
2462
|
+
return stopProcessAndWait(
|
|
2463
|
+
opencodeProcess,
|
|
2464
|
+
timeoutMs,
|
|
2465
|
+
() => sendSignal("SIGTERM"),
|
|
2466
|
+
() => sendSignal("SIGKILL")
|
|
2467
|
+
);
|
|
1872
2468
|
}
|
|
1873
2469
|
|
|
1874
2470
|
// src/lib/opencode/install.ts
|
|
@@ -2155,6 +2751,7 @@ async function createOpenCodeSession(port, directory) {
|
|
|
2155
2751
|
return data.id;
|
|
2156
2752
|
}
|
|
2157
2753
|
async function getModelAttachmentCapability(port, model) {
|
|
2754
|
+
const { model: baseModel } = splitModelVariant(model);
|
|
2158
2755
|
try {
|
|
2159
2756
|
const res = await timedFetch(`${opencodeBase(port)}/config/providers`);
|
|
2160
2757
|
if (!res.ok) {
|
|
@@ -2171,9 +2768,9 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
2171
2768
|
);
|
|
2172
2769
|
return null;
|
|
2173
2770
|
}
|
|
2174
|
-
const slash =
|
|
2175
|
-
const providerId = slash > 0 ?
|
|
2176
|
-
let modelId = slash > 0 ?
|
|
2771
|
+
const slash = baseModel ? baseModel.indexOf("/") : -1;
|
|
2772
|
+
const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
|
|
2773
|
+
let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
|
|
2177
2774
|
const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
|
|
2178
2775
|
let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
|
|
2179
2776
|
if (!provider && !providerId) {
|
|
@@ -2253,6 +2850,29 @@ async function buildFileParts(attachments, capable) {
|
|
|
2253
2850
|
}
|
|
2254
2851
|
return { parts, outcomes, capabilityUnknown };
|
|
2255
2852
|
}
|
|
2853
|
+
function splitModelVariant(raw) {
|
|
2854
|
+
const value = raw?.trim();
|
|
2855
|
+
if (!value) return {};
|
|
2856
|
+
const hashIndex = value.indexOf("#");
|
|
2857
|
+
if (hashIndex === -1) return { model: value };
|
|
2858
|
+
const model = value.slice(0, hashIndex).trim() || void 0;
|
|
2859
|
+
const variant = value.slice(hashIndex + 1).trim() || void 0;
|
|
2860
|
+
return { model, variant };
|
|
2861
|
+
}
|
|
2862
|
+
function applyModelOptions(body, options) {
|
|
2863
|
+
if (options?.agent) body.agent = options.agent;
|
|
2864
|
+
const { model, variant } = splitModelVariant(options?.model);
|
|
2865
|
+
if (model) {
|
|
2866
|
+
const slashIndex = model.indexOf("/");
|
|
2867
|
+
if (slashIndex !== -1) {
|
|
2868
|
+
body.model = {
|
|
2869
|
+
providerID: model.substring(0, slashIndex),
|
|
2870
|
+
modelID: model.substring(slashIndex + 1)
|
|
2871
|
+
};
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
if (variant) body.variant = variant;
|
|
2875
|
+
}
|
|
2256
2876
|
function messageText(m) {
|
|
2257
2877
|
if (!m || !Array.isArray(m.parts)) return "";
|
|
2258
2878
|
return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
|
|
@@ -2277,18 +2897,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
2277
2897
|
const body = {
|
|
2278
2898
|
parts
|
|
2279
2899
|
};
|
|
2280
|
-
|
|
2281
|
-
body.agent = options.agent;
|
|
2282
|
-
}
|
|
2283
|
-
if (options?.model) {
|
|
2284
|
-
const slashIndex = options.model.indexOf("/");
|
|
2285
|
-
if (slashIndex !== -1) {
|
|
2286
|
-
body.model = {
|
|
2287
|
-
providerID: options.model.substring(0, slashIndex),
|
|
2288
|
-
modelID: options.model.substring(slashIndex + 1)
|
|
2289
|
-
};
|
|
2290
|
-
}
|
|
2291
|
-
}
|
|
2900
|
+
applyModelOptions(body, options);
|
|
2292
2901
|
const res = await timedFetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
|
|
2293
2902
|
method: "POST",
|
|
2294
2903
|
headers: { "Content-Type": "application/json" },
|
|
@@ -2296,7 +2905,10 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
2296
2905
|
});
|
|
2297
2906
|
if (res.status < 200 || res.status >= 300) {
|
|
2298
2907
|
const text = await res.text().catch(() => "");
|
|
2299
|
-
|
|
2908
|
+
const { variant } = splitModelVariant(options?.model);
|
|
2909
|
+
throw new Error(
|
|
2910
|
+
`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
|
|
2911
|
+
);
|
|
2300
2912
|
}
|
|
2301
2913
|
const READ_BACK_ATTEMPTS = 5;
|
|
2302
2914
|
const READ_BACK_DELAY_MS = 150;
|
|
@@ -2320,7 +2932,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
2320
2932
|
}
|
|
2321
2933
|
}
|
|
2322
2934
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
2323
|
-
await new Promise((
|
|
2935
|
+
await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
|
|
2324
2936
|
}
|
|
2325
2937
|
}
|
|
2326
2938
|
return null;
|
|
@@ -2451,7 +3063,7 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
2451
3063
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
2452
3064
|
}
|
|
2453
3065
|
function isB2AbandonmentConfirmed(params) {
|
|
2454
|
-
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
3066
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false && params.rootOngoing === false;
|
|
2455
3067
|
}
|
|
2456
3068
|
function isAmbiguousTerminalFinish(m) {
|
|
2457
3069
|
if (completedOf(m) == null) return false;
|
|
@@ -2464,7 +3076,7 @@ function isAmbiguousFinishPinnedRunning(messages, userMessageId) {
|
|
|
2464
3076
|
return isAmbiguousTerminalFinish(reply);
|
|
2465
3077
|
}
|
|
2466
3078
|
function isAmbiguousFinishResolved(params) {
|
|
2467
|
-
return params.sessionOngoing === false || params.pinnedForMs >= params.maxPinnedMs;
|
|
3079
|
+
return params.sessionOngoing === false || params.sessionOngoing !== true && params.pinnedForMs >= params.maxPinnedMs;
|
|
2468
3080
|
}
|
|
2469
3081
|
function messageError(messages, userMessageId) {
|
|
2470
3082
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
@@ -2673,13 +3285,13 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
|
2673
3285
|
}
|
|
2674
3286
|
|
|
2675
3287
|
// src/lib/opencode/session-db-size.ts
|
|
2676
|
-
import { statSync as
|
|
3288
|
+
import { statSync as statSync3 } from "fs";
|
|
2677
3289
|
import { join as join3 } from "path";
|
|
2678
3290
|
var LARGE_DB_THRESHOLD_BYTES = 268435456;
|
|
2679
3291
|
function statSessionDbBytes(homeDir) {
|
|
2680
3292
|
const dbPath = join3(homeDir, ".local", "share", "opencode", "opencode.db");
|
|
2681
3293
|
try {
|
|
2682
|
-
return
|
|
3294
|
+
return statSync3(dbPath).size;
|
|
2683
3295
|
} catch (err) {
|
|
2684
3296
|
const isMissingFile = err instanceof Error && "code" in err && err.code === "ENOENT";
|
|
2685
3297
|
if (!isMissingFile) {
|
|
@@ -2705,11 +3317,11 @@ function buildSessionStoreSizeWarning(input) {
|
|
|
2705
3317
|
}
|
|
2706
3318
|
|
|
2707
3319
|
// src/lib/opencode/session-db-reclaim.ts
|
|
2708
|
-
import { statSync as
|
|
2709
|
-
import { dirname as
|
|
3320
|
+
import { statSync as statSync4, statfsSync } from "fs";
|
|
3321
|
+
import { dirname as dirname3 } from "path";
|
|
2710
3322
|
function insufficientSpaceReason(dbPath, requiredBytes) {
|
|
2711
3323
|
try {
|
|
2712
|
-
const fsStats = statfsSync(
|
|
3324
|
+
const fsStats = statfsSync(dirname3(dbPath));
|
|
2713
3325
|
const availableBytes = fsStats.bavail * fsStats.bsize;
|
|
2714
3326
|
if (availableBytes < requiredBytes) {
|
|
2715
3327
|
return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
|
|
@@ -2778,7 +3390,7 @@ async function reclaimSessionDbSpace(input) {
|
|
|
2778
3390
|
);
|
|
2779
3391
|
return { ok: false, skipped: "full-vacuum-blocked" };
|
|
2780
3392
|
}
|
|
2781
|
-
const fileBytesForGuard =
|
|
3393
|
+
const fileBytesForGuard = statSync4(dbPath).size;
|
|
2782
3394
|
const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
|
|
2783
3395
|
if (skipReason !== null) {
|
|
2784
3396
|
console.warn(
|
|
@@ -2906,12 +3518,12 @@ var StreamForwarder = class {
|
|
|
2906
3518
|
let endBody;
|
|
2907
3519
|
if (has_body) {
|
|
2908
3520
|
const chunks = [];
|
|
2909
|
-
bodyPromise = new Promise((
|
|
3521
|
+
bodyPromise = new Promise((resolve4) => {
|
|
2910
3522
|
pushBody = (buf) => {
|
|
2911
3523
|
chunks.push(buf);
|
|
2912
3524
|
};
|
|
2913
3525
|
endBody = () => {
|
|
2914
|
-
|
|
3526
|
+
resolve4(Buffer.concat(chunks));
|
|
2915
3527
|
};
|
|
2916
3528
|
});
|
|
2917
3529
|
}
|
|
@@ -3040,7 +3652,7 @@ function connectTunnel(options) {
|
|
|
3040
3652
|
} = options;
|
|
3041
3653
|
const tunnelUrl = getTunnelUrlConfig();
|
|
3042
3654
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
3043
|
-
return new Promise((
|
|
3655
|
+
return new Promise((resolve4, reject) => {
|
|
3044
3656
|
const ws = new WebSocket2(url, {
|
|
3045
3657
|
headers: {
|
|
3046
3658
|
Authorization: authHeader
|
|
@@ -3104,7 +3716,7 @@ function connectTunnel(options) {
|
|
|
3104
3716
|
clearTimeout(connectionTimeout);
|
|
3105
3717
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
3106
3718
|
onConnected?.(connectedAgentId);
|
|
3107
|
-
|
|
3719
|
+
resolve4({
|
|
3108
3720
|
ws,
|
|
3109
3721
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
3110
3722
|
});
|
|
@@ -3235,10 +3847,10 @@ var RunnerConnection = class {
|
|
|
3235
3847
|
};
|
|
3236
3848
|
|
|
3237
3849
|
// src/lib/tunnel/ready-marker.ts
|
|
3238
|
-
import { writeFileSync } from "fs";
|
|
3850
|
+
import { writeFileSync as writeFileSync2 } from "fs";
|
|
3239
3851
|
function writeTunnelReadyMarker(path, agentId) {
|
|
3240
3852
|
try {
|
|
3241
|
-
|
|
3853
|
+
writeFileSync2(path, `${agentId}
|
|
3242
3854
|
`);
|
|
3243
3855
|
return { ok: true };
|
|
3244
3856
|
} catch (error2) {
|
|
@@ -3246,9 +3858,51 @@ function writeTunnelReadyMarker(path, agentId) {
|
|
|
3246
3858
|
}
|
|
3247
3859
|
}
|
|
3248
3860
|
|
|
3249
|
-
// src/lib/
|
|
3861
|
+
// src/lib/replication.ts
|
|
3862
|
+
import { spawn as spawn4 } from "child_process";
|
|
3863
|
+
function startSessionDbReplication(configPath) {
|
|
3864
|
+
return spawn4("litestream", ["replicate", "-config", configPath], {
|
|
3865
|
+
stdio: "inherit"
|
|
3866
|
+
});
|
|
3867
|
+
}
|
|
3868
|
+
async function stopSessionDbReplication(child, timeoutMs) {
|
|
3869
|
+
return stopProcessAndWait(
|
|
3870
|
+
child,
|
|
3871
|
+
timeoutMs,
|
|
3872
|
+
() => child.kill("SIGTERM"),
|
|
3873
|
+
() => child.kill("SIGKILL")
|
|
3874
|
+
);
|
|
3875
|
+
}
|
|
3876
|
+
|
|
3877
|
+
// src/lib/process-liveness.ts
|
|
3250
3878
|
import { readFileSync as readFileSync3 } from "fs";
|
|
3251
|
-
|
|
3879
|
+
function isProcessAlive(pid) {
|
|
3880
|
+
try {
|
|
3881
|
+
process.kill(pid, 0);
|
|
3882
|
+
} catch (error2) {
|
|
3883
|
+
const code = error2.code;
|
|
3884
|
+
if (code === "ESRCH") return false;
|
|
3885
|
+
if (code === "EPERM") return true;
|
|
3886
|
+
console.error(
|
|
3887
|
+
`[process-liveness] could not probe process ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
3888
|
+
);
|
|
3889
|
+
return false;
|
|
3890
|
+
}
|
|
3891
|
+
if (process.platform !== "linux") return true;
|
|
3892
|
+
try {
|
|
3893
|
+
const status2 = readFileSync3(`/proc/${pid}/status`, "utf8");
|
|
3894
|
+
return !/^State:\s+Z(?:\s|$)/m.test(status2);
|
|
3895
|
+
} catch (error2) {
|
|
3896
|
+
console.error(
|
|
3897
|
+
`[process-liveness] could not inspect /proc/${pid}/status: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
3898
|
+
);
|
|
3899
|
+
return true;
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
|
|
3903
|
+
// src/lib/openai-usage.ts
|
|
3904
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
3905
|
+
import { homedir as homedir3 } from "os";
|
|
3252
3906
|
import { join as join4 } from "path";
|
|
3253
3907
|
var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
3254
3908
|
var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
|
|
@@ -3263,7 +3917,7 @@ function isLocalCredentialProblem2(err) {
|
|
|
3263
3917
|
}
|
|
3264
3918
|
function readOpenCodeChatGptCredentials() {
|
|
3265
3919
|
try {
|
|
3266
|
-
const raw =
|
|
3920
|
+
const raw = readFileSync4(join4(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
|
|
3267
3921
|
let parsed;
|
|
3268
3922
|
try {
|
|
3269
3923
|
parsed = JSON.parse(raw);
|
|
@@ -3636,7 +4290,7 @@ function createResourceUsageCollector(homeDir) {
|
|
|
3636
4290
|
}
|
|
3637
4291
|
|
|
3638
4292
|
// src/lib/channels/driver.ts
|
|
3639
|
-
import { homedir as
|
|
4293
|
+
import { homedir as homedir4 } from "os";
|
|
3640
4294
|
|
|
3641
4295
|
// src/lib/runner-file-sync.ts
|
|
3642
4296
|
import { join as join6 } from "path";
|
|
@@ -3644,7 +4298,7 @@ import { join as join6 } from "path";
|
|
|
3644
4298
|
// src/lib/file-push.ts
|
|
3645
4299
|
import { randomUUID } from "crypto";
|
|
3646
4300
|
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
3647
|
-
import { basename, dirname as
|
|
4301
|
+
import { basename, dirname as dirname4, isAbsolute, join as join5, relative, resolve as resolve2, sep } from "path";
|
|
3648
4302
|
var FILE_MODE = 384;
|
|
3649
4303
|
var DIRECTORY_MODE = 448;
|
|
3650
4304
|
async function writePushedFile(request) {
|
|
@@ -3675,7 +4329,7 @@ async function writePushedFile(request) {
|
|
|
3675
4329
|
}
|
|
3676
4330
|
try {
|
|
3677
4331
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
3678
|
-
|
|
4332
|
+
dirname4(candidate)
|
|
3679
4333
|
);
|
|
3680
4334
|
const realTarget = join5(existingAncestor, ...missingSegments, basename(candidate));
|
|
3681
4335
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
@@ -3687,8 +4341,8 @@ async function writePushedFile(request) {
|
|
|
3687
4341
|
}
|
|
3688
4342
|
if (missingSegments.length > 0) {
|
|
3689
4343
|
await createMissingDirectories(existingAncestor, missingSegments);
|
|
3690
|
-
const realParent = await realpath(
|
|
3691
|
-
if (realParent !==
|
|
4344
|
+
const realParent = await realpath(dirname4(realTarget));
|
|
4345
|
+
if (realParent !== dirname4(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
3692
4346
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
3693
4347
|
path: realTarget,
|
|
3694
4348
|
bytes,
|
|
@@ -3731,7 +4385,7 @@ async function resolveNearestExistingAncestor(directory) {
|
|
|
3731
4385
|
try {
|
|
3732
4386
|
return { existingAncestor: await realpath(current), missingSegments };
|
|
3733
4387
|
} catch (err) {
|
|
3734
|
-
const parent =
|
|
4388
|
+
const parent = dirname4(current);
|
|
3735
4389
|
if (err.code !== "ENOENT" || parent === current) {
|
|
3736
4390
|
throw err;
|
|
3737
4391
|
}
|
|
@@ -3792,7 +4446,7 @@ async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
|
3792
4446
|
}
|
|
3793
4447
|
}
|
|
3794
4448
|
async function writeAtomically(realTarget, content) {
|
|
3795
|
-
const temporaryPath = join5(
|
|
4449
|
+
const temporaryPath = join5(dirname4(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
3796
4450
|
let handle;
|
|
3797
4451
|
try {
|
|
3798
4452
|
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
@@ -4473,7 +5127,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4473
5127
|
this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
4474
5128
|
this.now = config.now ?? (() => Date.now());
|
|
4475
5129
|
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
4476
|
-
this.homeDir = config.homeDir ??
|
|
5130
|
+
this.homeDir = config.homeDir ?? homedir4();
|
|
4477
5131
|
this.maxActiveSessions = config.maxActiveSessions;
|
|
4478
5132
|
this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
|
|
4479
5133
|
this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
|
|
@@ -5740,6 +6394,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5740
6394
|
deliveryDeadlineAnchored: false,
|
|
5741
6395
|
b2PinnedSinceMs: 0,
|
|
5742
6396
|
b2LastDescendantCheckMs: 0,
|
|
6397
|
+
b2RootOngoingHeldLogged: false,
|
|
5743
6398
|
b2AbandonedSignalled: false,
|
|
5744
6399
|
ambiguousPinnedSinceMs: 0,
|
|
5745
6400
|
ambiguousResolved: false
|
|
@@ -5834,6 +6489,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5834
6489
|
deliveryDeadlineAnchored: false,
|
|
5835
6490
|
b2PinnedSinceMs: 0,
|
|
5836
6491
|
b2LastDescendantCheckMs: 0,
|
|
6492
|
+
b2RootOngoingHeldLogged: false,
|
|
5837
6493
|
b2AbandonedSignalled: false,
|
|
5838
6494
|
ambiguousPinnedSinceMs: 0,
|
|
5839
6495
|
ambiguousResolved: false
|
|
@@ -6187,6 +6843,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6187
6843
|
if (snapshotReadable) {
|
|
6188
6844
|
inFlight.b2PinnedSinceMs = 0;
|
|
6189
6845
|
inFlight.b2LastDescendantCheckMs = 0;
|
|
6846
|
+
inFlight.b2RootOngoingHeldLogged = false;
|
|
6190
6847
|
inFlight.b2AbandonedSignalled = false;
|
|
6191
6848
|
}
|
|
6192
6849
|
} else {
|
|
@@ -6198,11 +6855,15 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6198
6855
|
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
6199
6856
|
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
6200
6857
|
inFlight.b2LastDescendantCheckMs = this.now();
|
|
6201
|
-
const descendantOngoing = await
|
|
6858
|
+
const [descendantOngoing, rootOngoing] = await Promise.all([
|
|
6859
|
+
this.isAnyDescendantSessionOngoing(sessionId),
|
|
6860
|
+
isSessionOngoing(this.port, sessionId)
|
|
6861
|
+
]);
|
|
6202
6862
|
if (isB2AbandonmentConfirmed({
|
|
6203
6863
|
pinnedForMs,
|
|
6204
6864
|
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
6205
|
-
descendantOngoing
|
|
6865
|
+
descendantOngoing,
|
|
6866
|
+
rootOngoing
|
|
6206
6867
|
})) {
|
|
6207
6868
|
inFlight.b2AbandonedSignalled = true;
|
|
6208
6869
|
this.log({
|
|
@@ -6211,12 +6872,26 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
6211
6872
|
conversation_id: conv.id,
|
|
6212
6873
|
message_id: id
|
|
6213
6874
|
});
|
|
6875
|
+
const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
|
|
6214
6876
|
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
6215
|
-
watched_for_ms: pinnedForMs
|
|
6877
|
+
watched_for_ms: pinnedForMs,
|
|
6878
|
+
finish: reply?.info?.finish ?? reply?.finish,
|
|
6879
|
+
...rootOngoing != null ? { root_ongoing: rootOngoing } : {},
|
|
6880
|
+
...descendantOngoing != null ? { descendant_ongoing: descendantOngoing } : {},
|
|
6881
|
+
opencode_message_id: inFlight.opencodeMessageId
|
|
6216
6882
|
});
|
|
6217
6883
|
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
6218
6884
|
return;
|
|
6219
6885
|
}
|
|
6886
|
+
if (rootOngoing === true && !inFlight.b2RootOngoingHeldLogged) {
|
|
6887
|
+
inFlight.b2RootOngoingHeldLogged = true;
|
|
6888
|
+
this.log({
|
|
6889
|
+
level: "warn",
|
|
6890
|
+
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`,
|
|
6891
|
+
conversation_id: conv.id,
|
|
6892
|
+
message_id: id
|
|
6893
|
+
});
|
|
6894
|
+
}
|
|
6220
6895
|
}
|
|
6221
6896
|
}
|
|
6222
6897
|
const ambiguousPinnedNow = activelyRunning && isAmbiguousFinishPinnedRunning(messages, inFlight.opencodeMessageId);
|
|
@@ -7873,7 +8548,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
7873
8548
|
}
|
|
7874
8549
|
if (!ctx.interactive) {
|
|
7875
8550
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
7876
|
-
const proc = await startOpenCode(ctx.port);
|
|
8551
|
+
const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
|
|
7877
8552
|
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
7878
8553
|
if (!health.healthy) {
|
|
7879
8554
|
return {
|
|
@@ -7941,7 +8616,7 @@ Port ${port} is already in use.`));
|
|
|
7941
8616
|
}
|
|
7942
8617
|
if (action === "start") {
|
|
7943
8618
|
const spinner = ora2("Starting OpenCode...").start();
|
|
7944
|
-
const proc = await startOpenCode(port);
|
|
8619
|
+
const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
|
|
7945
8620
|
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
7946
8621
|
if (!health.healthy) {
|
|
7947
8622
|
spinner.fail("Failed to start OpenCode");
|
|
@@ -7953,12 +8628,323 @@ Port ${port} is already in use.`));
|
|
|
7953
8628
|
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
7954
8629
|
}
|
|
7955
8630
|
|
|
8631
|
+
// src/lib/runner-credentials.ts
|
|
8632
|
+
import { chmodSync as chmodSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
8633
|
+
import { spawn as spawn5 } from "child_process";
|
|
8634
|
+
var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
|
|
8635
|
+
var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
|
|
8636
|
+
var GITHUB_PROBE_TIMEOUT_MS = 1e4;
|
|
8637
|
+
var GIT_CONFIG_GLOBAL = "/tmp/gitconfig";
|
|
8638
|
+
var GIT_CREDENTIAL_HELPER = "/tmp/git-credential-helper.sh";
|
|
8639
|
+
function commandError2(result) {
|
|
8640
|
+
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
8641
|
+
}
|
|
8642
|
+
var runCommand2 = (command, args, opts) => {
|
|
8643
|
+
return new Promise((resolve4) => {
|
|
8644
|
+
let child;
|
|
8645
|
+
let stdout = "";
|
|
8646
|
+
let stderr = "";
|
|
8647
|
+
let settled = false;
|
|
8648
|
+
const timer = {};
|
|
8649
|
+
const finish = (result) => {
|
|
8650
|
+
if (settled) return;
|
|
8651
|
+
settled = true;
|
|
8652
|
+
if (timer.handle) clearTimeout(timer.handle);
|
|
8653
|
+
resolve4(result);
|
|
8654
|
+
};
|
|
8655
|
+
try {
|
|
8656
|
+
child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
8657
|
+
} catch (error2) {
|
|
8658
|
+
finish({
|
|
8659
|
+
code: null,
|
|
8660
|
+
stdout,
|
|
8661
|
+
stderr: error2 instanceof Error ? error2.message : String(error2),
|
|
8662
|
+
timedOut: false
|
|
8663
|
+
});
|
|
8664
|
+
return;
|
|
8665
|
+
}
|
|
8666
|
+
child.stdout?.setEncoding("utf8");
|
|
8667
|
+
child.stdout?.on("data", (chunk) => {
|
|
8668
|
+
stdout += chunk;
|
|
8669
|
+
});
|
|
8670
|
+
child.stderr?.setEncoding("utf8");
|
|
8671
|
+
child.stderr?.on("data", (chunk) => {
|
|
8672
|
+
stderr += chunk;
|
|
8673
|
+
});
|
|
8674
|
+
child.once("error", (error2) => {
|
|
8675
|
+
finish({
|
|
8676
|
+
code: null,
|
|
8677
|
+
stdout,
|
|
8678
|
+
stderr: stderr === "" ? error2.message : `${stderr}
|
|
8679
|
+
${error2.message}`,
|
|
8680
|
+
timedOut: false
|
|
8681
|
+
});
|
|
8682
|
+
});
|
|
8683
|
+
child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
|
|
8684
|
+
timer.handle = setTimeout(
|
|
8685
|
+
() => {
|
|
8686
|
+
child.kill("SIGKILL");
|
|
8687
|
+
finish({ code: null, stdout, stderr, timedOut: true });
|
|
8688
|
+
},
|
|
8689
|
+
Math.max(0, opts.timeoutMs)
|
|
8690
|
+
);
|
|
8691
|
+
});
|
|
8692
|
+
};
|
|
8693
|
+
function isEnvironmentObject(value) {
|
|
8694
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8695
|
+
}
|
|
8696
|
+
function secretFailure(marker, detail, log3) {
|
|
8697
|
+
const message = `${marker}: ${detail}`;
|
|
8698
|
+
log3(message, "error");
|
|
8699
|
+
return new Error(message);
|
|
8700
|
+
}
|
|
8701
|
+
async function installRunnerSecret({
|
|
8702
|
+
env,
|
|
8703
|
+
log: log3,
|
|
8704
|
+
commandRunner
|
|
8705
|
+
}) {
|
|
8706
|
+
const arn = env.RUNNER_SECRET_ARN?.trim();
|
|
8707
|
+
if (!arn) {
|
|
8708
|
+
log3("runner secret is not configured; continuing without GitHub and MCP credentials");
|
|
8709
|
+
return false;
|
|
8710
|
+
}
|
|
8711
|
+
const result = await (commandRunner ?? runCommand2)(
|
|
8712
|
+
"aws",
|
|
8713
|
+
[
|
|
8714
|
+
"secretsmanager",
|
|
8715
|
+
"get-secret-value",
|
|
8716
|
+
"--secret-id",
|
|
8717
|
+
arn,
|
|
8718
|
+
"--query",
|
|
8719
|
+
"SecretString",
|
|
8720
|
+
"--output",
|
|
8721
|
+
"text"
|
|
8722
|
+
],
|
|
8723
|
+
{ env, timeoutMs: RUNNER_SECRET_FETCH_TIMEOUT_MS }
|
|
8724
|
+
);
|
|
8725
|
+
if (result.timedOut) {
|
|
8726
|
+
throw secretFailure(
|
|
8727
|
+
"CREDENTIAL-RESTORE-TIMEOUT",
|
|
8728
|
+
`runner-secret did not finish within ${RUNNER_SECRET_FETCH_TIMEOUT_MS}ms`,
|
|
8729
|
+
log3
|
|
8730
|
+
);
|
|
8731
|
+
}
|
|
8732
|
+
if (result.code !== 0) {
|
|
8733
|
+
throw secretFailure("RUNNER-SECRET-UNREADABLE", commandError2(result), log3);
|
|
8734
|
+
}
|
|
8735
|
+
let payload;
|
|
8736
|
+
try {
|
|
8737
|
+
payload = JSON.parse(result.stdout);
|
|
8738
|
+
} catch (error2) {
|
|
8739
|
+
log3(
|
|
8740
|
+
`RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object (${error2 instanceof Error ? error2.message : String(error2)})`,
|
|
8741
|
+
"warn"
|
|
8742
|
+
);
|
|
8743
|
+
return false;
|
|
8744
|
+
}
|
|
8745
|
+
if (!isEnvironmentObject(payload)) {
|
|
8746
|
+
log3("RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object", "warn");
|
|
8747
|
+
return false;
|
|
8748
|
+
}
|
|
8749
|
+
let populated = 0;
|
|
8750
|
+
let skipped = 0;
|
|
8751
|
+
let githubTokenPopulated = false;
|
|
8752
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
8753
|
+
if (typeof value !== "string" || value.length === 0) continue;
|
|
8754
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
|
8755
|
+
log3(
|
|
8756
|
+
`RUNNER-SECRET-KEY-SKIPPED: ${JSON.stringify(key)} is not a valid environment variable name`,
|
|
8757
|
+
"warn"
|
|
8758
|
+
);
|
|
8759
|
+
skipped += 1;
|
|
8760
|
+
continue;
|
|
8761
|
+
}
|
|
8762
|
+
env[key] = value;
|
|
8763
|
+
populated += 1;
|
|
8764
|
+
if (key === "GH_TOKEN") githubTokenPopulated = true;
|
|
8765
|
+
}
|
|
8766
|
+
if (populated === 0) {
|
|
8767
|
+
log3(
|
|
8768
|
+
"RUNNER-SECRET-UNPOPULATED: populate the runner secret as documented in infrastructure/evident-runner/MICROVM.md",
|
|
8769
|
+
"warn"
|
|
8770
|
+
);
|
|
8771
|
+
} else {
|
|
8772
|
+
log3(
|
|
8773
|
+
`RUNNER-SECRET-OK: exported ${populated} secret values; skipped ${skipped} invalid environment variable names`
|
|
8774
|
+
);
|
|
8775
|
+
}
|
|
8776
|
+
return githubTokenPopulated;
|
|
8777
|
+
}
|
|
8778
|
+
function restoreFailure(operation, result, log3) {
|
|
8779
|
+
const message = `CREDENTIAL-RESTORE-FAILED: ${operation} failed: ${commandError2(result)}`;
|
|
8780
|
+
log3(message, "error");
|
|
8781
|
+
return new Error(message);
|
|
8782
|
+
}
|
|
8783
|
+
async function runCredentialRestore(args, operation, log3, synchroniserRunner) {
|
|
8784
|
+
const result = await synchroniserRunner(args, { timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS });
|
|
8785
|
+
if (result.timedOut) {
|
|
8786
|
+
log3(
|
|
8787
|
+
`CREDENTIAL-RESTORE-TIMEOUT: ${operation} did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
|
|
8788
|
+
"warn"
|
|
8789
|
+
);
|
|
8790
|
+
return result;
|
|
8791
|
+
}
|
|
8792
|
+
if (result.code !== 0) throw restoreFailure(operation, result, log3);
|
|
8793
|
+
return result;
|
|
8794
|
+
}
|
|
8795
|
+
async function restoreCredentialStores({
|
|
8796
|
+
env,
|
|
8797
|
+
log: log3,
|
|
8798
|
+
synchroniserRunner = runSynchroniser
|
|
8799
|
+
}) {
|
|
8800
|
+
await runCredentialRestore(["restore", "claude"], "restore-claude", log3, synchroniserRunner);
|
|
8801
|
+
await runCredentialRestore(["restore", "opencode"], "restore-opencode", log3, synchroniserRunner);
|
|
8802
|
+
const result = await synchroniserRunner(["model-auth-ready"], {
|
|
8803
|
+
timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS
|
|
8804
|
+
});
|
|
8805
|
+
if (result.timedOut) {
|
|
8806
|
+
log3(
|
|
8807
|
+
`CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
|
|
8808
|
+
"warn"
|
|
8809
|
+
);
|
|
8810
|
+
return;
|
|
8811
|
+
}
|
|
8812
|
+
switch (result.code) {
|
|
8813
|
+
case 0:
|
|
8814
|
+
return;
|
|
8815
|
+
case 10:
|
|
8816
|
+
log3(
|
|
8817
|
+
`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.`,
|
|
8818
|
+
"warn"
|
|
8819
|
+
);
|
|
8820
|
+
return;
|
|
8821
|
+
default:
|
|
8822
|
+
log3("could not determine whether this VM has model credentials", "warn");
|
|
8823
|
+
}
|
|
8824
|
+
}
|
|
8825
|
+
var GIT_CREDENTIAL_HELPER_CONTENT = [
|
|
8826
|
+
"#!/usr/bin/env bash",
|
|
8827
|
+
'[ "$1" = get ] || exit 0',
|
|
8828
|
+
"echo username=x-access-token",
|
|
8829
|
+
'echo "password=${GH_TOKEN}"',
|
|
8830
|
+
""
|
|
8831
|
+
].join("\n");
|
|
8832
|
+
async function probeGitHubAccess({ env, log: log3 }) {
|
|
8833
|
+
const auth = await runCommand2("gh", ["api", "user", "--jq", ".login"], {
|
|
8834
|
+
env,
|
|
8835
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
8836
|
+
});
|
|
8837
|
+
if (auth.timedOut) {
|
|
8838
|
+
log3(`GITHUB-PROBE-TIMEOUT: auth probe exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`, "warn");
|
|
8839
|
+
return;
|
|
8840
|
+
}
|
|
8841
|
+
if (auth.code !== 0) {
|
|
8842
|
+
log3(`GITHUB-AUTH-REJECTED: ${commandError2(auth)}`, "warn");
|
|
8843
|
+
return;
|
|
8844
|
+
}
|
|
8845
|
+
log3(`GITHUB-AUTH-OK: ${auth.stdout.trim()}`, "debug");
|
|
8846
|
+
const remote = await runCommand2("git", ["-C", process.cwd(), "remote", "get-url", "origin"], {
|
|
8847
|
+
env,
|
|
8848
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
8849
|
+
});
|
|
8850
|
+
if (remote.code !== 0 || remote.timedOut) return;
|
|
8851
|
+
const repo = remote.stdout.trim().replace(/^(?:https:\/\/github\.com\/|git@github\.com:)/, "").replace(/\.git$/, "");
|
|
8852
|
+
if (!repo) return;
|
|
8853
|
+
const repository = await runCommand2("gh", ["api", `repos/${repo}`, "--jq", ".full_name"], {
|
|
8854
|
+
env,
|
|
8855
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
8856
|
+
});
|
|
8857
|
+
if (repository.timedOut) {
|
|
8858
|
+
log3(
|
|
8859
|
+
`GITHUB-PROBE-TIMEOUT: repository probe for ${repo} exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`,
|
|
8860
|
+
"warn"
|
|
8861
|
+
);
|
|
8862
|
+
} else if (repository.code !== 0) {
|
|
8863
|
+
log3(`GITHUB-REPO-INACCESSIBLE: ${repo}: ${commandError2(repository)}`, "warn");
|
|
8864
|
+
}
|
|
8865
|
+
}
|
|
8866
|
+
async function configureGitHubAccess({ env, log: log3 }) {
|
|
8867
|
+
if (!env.GH_TOKEN) {
|
|
8868
|
+
log3("GITHUB-CREDENTIALS-MISSING: GH_TOKEN is unavailable; see RUNNER-SECRET-* above", "warn");
|
|
8869
|
+
return;
|
|
8870
|
+
}
|
|
8871
|
+
try {
|
|
8872
|
+
env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
|
|
8873
|
+
writeFileSync3(GIT_CONFIG_GLOBAL, "");
|
|
8874
|
+
writeFileSync3(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
|
|
8875
|
+
chmodSync2(GIT_CREDENTIAL_HELPER, 448);
|
|
8876
|
+
const config = [
|
|
8877
|
+
["user.name", env.GIT_USER_NAME ?? "evident-bot"],
|
|
8878
|
+
["user.email", env.GIT_USER_EMAIL ?? "evident-bot@users.noreply.github.com"],
|
|
8879
|
+
["init.defaultBranch", "main"],
|
|
8880
|
+
["credential.https://github.com.helper", GIT_CREDENTIAL_HELPER]
|
|
8881
|
+
];
|
|
8882
|
+
for (const [key, value] of config) {
|
|
8883
|
+
const result = await runCommand2("git", ["config", "--global", key, value], {
|
|
8884
|
+
env,
|
|
8885
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
8886
|
+
});
|
|
8887
|
+
if (result.timedOut || result.code !== 0) throw new Error(commandError2(result));
|
|
8888
|
+
}
|
|
8889
|
+
} catch (error2) {
|
|
8890
|
+
log3(
|
|
8891
|
+
`GITHUB-SETUP-FAILED: could not configure local git credentials; continuing without GitHub access (${error2 instanceof Error ? error2.message : String(error2)})`,
|
|
8892
|
+
"warn"
|
|
8893
|
+
);
|
|
8894
|
+
return;
|
|
8895
|
+
}
|
|
8896
|
+
void probeGitHubAccess({ env, log: log3 }).catch((error2) => {
|
|
8897
|
+
log3(
|
|
8898
|
+
`GITHUB-SETUP-FAILED: GitHub access probe failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
8899
|
+
"warn"
|
|
8900
|
+
);
|
|
8901
|
+
});
|
|
8902
|
+
}
|
|
8903
|
+
|
|
8904
|
+
// src/lib/opencode/config-overlay.ts
|
|
8905
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
8906
|
+
import { copyFileSync, existsSync as existsSync2, statSync as statSync5 } from "fs";
|
|
8907
|
+
import { isAbsolute as isAbsolute2, join as join7, resolve as resolve3 } from "path";
|
|
8908
|
+
function isFile(filePath) {
|
|
8909
|
+
return existsSync2(filePath) && statSync5(filePath).isFile();
|
|
8910
|
+
}
|
|
8911
|
+
function applyRunnerOpenCodeConfig({
|
|
8912
|
+
overlayPath,
|
|
8913
|
+
cwd = process.cwd(),
|
|
8914
|
+
log: log3
|
|
8915
|
+
}) {
|
|
8916
|
+
if (!overlayPath) {
|
|
8917
|
+
log3("runner OpenCode config is not configured; using the baked project config", "debug");
|
|
8918
|
+
return;
|
|
8919
|
+
}
|
|
8920
|
+
const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
|
|
8921
|
+
const target = isFile(join7(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
|
|
8922
|
+
if (!isFile(source)) {
|
|
8923
|
+
log3(
|
|
8924
|
+
`RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
|
|
8925
|
+
"error"
|
|
8926
|
+
);
|
|
8927
|
+
return;
|
|
8928
|
+
}
|
|
8929
|
+
copyFileSync(source, join7(cwd, target));
|
|
8930
|
+
try {
|
|
8931
|
+
execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
|
|
8932
|
+
stdio: "ignore"
|
|
8933
|
+
});
|
|
8934
|
+
} catch (error2) {
|
|
8935
|
+
const detail = error2 instanceof Error ? error2.message : String(error2);
|
|
8936
|
+
log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
|
|
8937
|
+
}
|
|
8938
|
+
log3(`Applied runner OpenCode config ${source} to ${join7(cwd, target)}`);
|
|
8939
|
+
}
|
|
8940
|
+
|
|
7956
8941
|
// src/commands/run.ts
|
|
7957
8942
|
var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
7958
8943
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
7959
8944
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
7960
8945
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
7961
8946
|
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
8947
|
+
var CHILD_STOP_TIMEOUT_MS = 1e4;
|
|
7962
8948
|
function resolveLogLevel(options) {
|
|
7963
8949
|
const accepted = Object.keys(LOG_LEVELS);
|
|
7964
8950
|
const validate = (value, source) => {
|
|
@@ -7989,11 +8975,11 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
7989
8975
|
if (trimmed === "") {
|
|
7990
8976
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
7991
8977
|
}
|
|
7992
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
7993
|
-
if (!
|
|
8978
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join8(homeDir, trimmed.slice(2)) : trimmed;
|
|
8979
|
+
if (!isAbsolute3(expanded)) {
|
|
7994
8980
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
7995
8981
|
}
|
|
7996
|
-
const normalized =
|
|
8982
|
+
const normalized = resolvePath2(expanded);
|
|
7997
8983
|
if (parse(normalized).root === normalized) {
|
|
7998
8984
|
throw new Error(
|
|
7999
8985
|
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
@@ -8109,7 +9095,7 @@ function logActivity(state, entry) {
|
|
|
8109
9095
|
}
|
|
8110
9096
|
function reportSessionDbRecovery(state) {
|
|
8111
9097
|
try {
|
|
8112
|
-
const report = drainSessionDbRecoveryReport({ homeDir:
|
|
9098
|
+
const report = drainSessionDbRecoveryReport({ homeDir: homedir5(), env: process.env });
|
|
8113
9099
|
for (const record of report.records) {
|
|
8114
9100
|
const activity = buildSessionDbRecoveryActivity(record);
|
|
8115
9101
|
if (!activity) throw new Error("could not map session-DB recovery record");
|
|
@@ -8127,6 +9113,16 @@ function reportSessionDbRecovery(state) {
|
|
|
8127
9113
|
);
|
|
8128
9114
|
}
|
|
8129
9115
|
}
|
|
9116
|
+
function reportSessionDbRecoveryRecord(state, record) {
|
|
9117
|
+
const activity = buildSessionDbRecoveryActivity(record);
|
|
9118
|
+
if (!activity) throw new Error("could not map session-DB recovery record");
|
|
9119
|
+
logActivity(state, {
|
|
9120
|
+
type: activity.level === "error" ? "error" : "info",
|
|
9121
|
+
level: activity.level,
|
|
9122
|
+
...activity.level === "error" ? { error: activity.message } : { message: activity.message },
|
|
9123
|
+
metadata: activity.metadata
|
|
9124
|
+
});
|
|
9125
|
+
}
|
|
8130
9126
|
function displayStatus(state) {
|
|
8131
9127
|
if (!state.interactive) return;
|
|
8132
9128
|
const attempt = state.connection?.reconnectAttempt ?? 0;
|
|
@@ -8299,7 +9295,7 @@ async function driveChannels(state, driver) {
|
|
|
8299
9295
|
}
|
|
8300
9296
|
}
|
|
8301
9297
|
}
|
|
8302
|
-
await new Promise((
|
|
9298
|
+
await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
|
|
8303
9299
|
const cycleMs = performance.now() - cycleStartedAtMs;
|
|
8304
9300
|
if (idleThisCycle) idleMs += cycleMs;
|
|
8305
9301
|
if (unreachableThisCycle) unreachableMs += cycleMs;
|
|
@@ -8322,7 +9318,7 @@ async function driveChannels(state, driver) {
|
|
|
8322
9318
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
8323
9319
|
var SESSION_DB_RECLAIM_MAX_PAGES = 2e3;
|
|
8324
9320
|
function sessionDbPath() {
|
|
8325
|
-
return
|
|
9321
|
+
return join8(homedir5(), ".local", "share", "opencode", "opencode.db");
|
|
8326
9322
|
}
|
|
8327
9323
|
async function runSweep(state, driver, config) {
|
|
8328
9324
|
const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
|
|
@@ -8405,7 +9401,7 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
8405
9401
|
for (const warning2 of config.warnings) {
|
|
8406
9402
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
8407
9403
|
}
|
|
8408
|
-
const dbBytes = statSessionDbBytes(
|
|
9404
|
+
const dbBytes = statSessionDbBytes(homedir5());
|
|
8409
9405
|
void (async () => {
|
|
8410
9406
|
const reclaimSkipReason = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
|
|
8411
9407
|
const sizeWarning = buildSessionStoreSizeWarning({
|
|
@@ -8606,7 +9602,7 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
8606
9602
|
});
|
|
8607
9603
|
return;
|
|
8608
9604
|
}
|
|
8609
|
-
const collect = createResourceUsageCollector(
|
|
9605
|
+
const collect = createResourceUsageCollector(homedir5());
|
|
8610
9606
|
let consecutiveFailures = 0;
|
|
8611
9607
|
const tick = async () => {
|
|
8612
9608
|
try {
|
|
@@ -8746,15 +9742,31 @@ async function cleanup(state, opts = {}) {
|
|
|
8746
9742
|
}
|
|
8747
9743
|
if (state.opencodeProcess) {
|
|
8748
9744
|
const opencodeProcess = state.opencodeProcess;
|
|
8749
|
-
|
|
9745
|
+
const result = await timeShutdownPhase(
|
|
9746
|
+
state,
|
|
9747
|
+
durations,
|
|
9748
|
+
"opencode_stop",
|
|
9749
|
+
() => stopOpenCodeAndWait(opencodeProcess, CHILD_STOP_TIMEOUT_MS)
|
|
9750
|
+
);
|
|
8750
9751
|
if (state.interactive) {
|
|
8751
|
-
logActivity(state, { type: "info", message:
|
|
9752
|
+
logActivity(state, { type: "info", message: `Stopped OpenCode process (${result.outcome})` });
|
|
8752
9753
|
displayStatus(state);
|
|
8753
9754
|
} else {
|
|
8754
|
-
log2(state,
|
|
9755
|
+
log2(state, `Stopped OpenCode process (${result.outcome})`);
|
|
8755
9756
|
}
|
|
8756
9757
|
state.opencodeProcess = null;
|
|
8757
9758
|
}
|
|
9759
|
+
if (state.litestreamProcess) {
|
|
9760
|
+
const litestreamProcess = state.litestreamProcess;
|
|
9761
|
+
const result = await timeShutdownPhase(
|
|
9762
|
+
state,
|
|
9763
|
+
durations,
|
|
9764
|
+
"litestream_stop",
|
|
9765
|
+
() => stopSessionDbReplication(litestreamProcess, CHILD_STOP_TIMEOUT_MS)
|
|
9766
|
+
);
|
|
9767
|
+
log2(state, `Stopped litestream replication (${result.outcome})`);
|
|
9768
|
+
state.litestreamProcess = null;
|
|
9769
|
+
}
|
|
8758
9770
|
return durations;
|
|
8759
9771
|
}
|
|
8760
9772
|
async function run(options) {
|
|
@@ -8763,7 +9775,12 @@ async function run(options) {
|
|
|
8763
9775
|
let fileSyncDirectories;
|
|
8764
9776
|
try {
|
|
8765
9777
|
logLevel = resolveLogLevel(options);
|
|
8766
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
9778
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir5());
|
|
9779
|
+
if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
|
|
9780
|
+
throw new Error(
|
|
9781
|
+
"--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
|
|
9782
|
+
);
|
|
9783
|
+
}
|
|
8767
9784
|
} catch (error2) {
|
|
8768
9785
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
8769
9786
|
if (options.json) {
|
|
@@ -8788,6 +9805,7 @@ async function run(options) {
|
|
|
8788
9805
|
opencodeConnected: false,
|
|
8789
9806
|
opencodeVersion: null,
|
|
8790
9807
|
opencodeProcess: null,
|
|
9808
|
+
litestreamProcess: null,
|
|
8791
9809
|
connection: null,
|
|
8792
9810
|
channelDriver: null,
|
|
8793
9811
|
running: true,
|
|
@@ -8854,8 +9872,8 @@ async function run(options) {
|
|
|
8854
9872
|
return true;
|
|
8855
9873
|
}
|
|
8856
9874
|
);
|
|
8857
|
-
const timedOut = new Promise((
|
|
8858
|
-
timer = setTimeout(() =>
|
|
9875
|
+
const timedOut = new Promise((resolve4) => {
|
|
9876
|
+
timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
|
|
8859
9877
|
});
|
|
8860
9878
|
if (!await Promise.race([flushed, timedOut])) {
|
|
8861
9879
|
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
@@ -8995,7 +10013,67 @@ async function run(options) {
|
|
|
8995
10013
|
} else {
|
|
8996
10014
|
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
8997
10015
|
}
|
|
10016
|
+
if (options.restoreRunnerCredentials) {
|
|
10017
|
+
log2(state, "Restoring runner credentials before starting OpenCode");
|
|
10018
|
+
const credentialContext = {
|
|
10019
|
+
env: process.env,
|
|
10020
|
+
log: (message, level = "info") => {
|
|
10021
|
+
if (level === "error") {
|
|
10022
|
+
logActivity(state, { type: "error", error: message });
|
|
10023
|
+
} else {
|
|
10024
|
+
logActivity(state, { type: "info", level, message });
|
|
10025
|
+
}
|
|
10026
|
+
}
|
|
10027
|
+
};
|
|
10028
|
+
const githubTokenPopulated = await installRunnerSecret(credentialContext);
|
|
10029
|
+
await restoreCredentialStores(credentialContext);
|
|
10030
|
+
if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
|
|
10031
|
+
}
|
|
10032
|
+
let sessionDbVerifyFatal = false;
|
|
10033
|
+
if (!options.restoreSessionDb) {
|
|
10034
|
+
log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
|
|
10035
|
+
} else {
|
|
10036
|
+
const health = await checkOpenCodeHealth(state.port);
|
|
10037
|
+
if (health.healthy) {
|
|
10038
|
+
log2(
|
|
10039
|
+
state,
|
|
10040
|
+
"Skipping session-DB restore: OpenCode is already serving this database",
|
|
10041
|
+
"debug"
|
|
10042
|
+
);
|
|
10043
|
+
} else {
|
|
10044
|
+
const result = await restoreAndVerifySessionDb({
|
|
10045
|
+
dbPath: sessionDbPath(),
|
|
10046
|
+
litestreamConfig: options.litestreamConfig,
|
|
10047
|
+
noReplicateMarker: options.sessionDbNoReplicateMarker,
|
|
10048
|
+
env: process.env,
|
|
10049
|
+
log: (message, level = "info") => {
|
|
10050
|
+
if (level === "error") {
|
|
10051
|
+
logActivity(state, { type: "error", error: message });
|
|
10052
|
+
} else {
|
|
10053
|
+
logActivity(state, { type: "info", level, message });
|
|
10054
|
+
}
|
|
10055
|
+
},
|
|
10056
|
+
reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
|
|
10057
|
+
});
|
|
10058
|
+
sessionDbVerifyFatal = result.verifyFatal;
|
|
10059
|
+
}
|
|
10060
|
+
}
|
|
8998
10061
|
reportSessionDbRecovery(state);
|
|
10062
|
+
if (sessionDbVerifyFatal) {
|
|
10063
|
+
throw new Error(
|
|
10064
|
+
"SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
|
|
10065
|
+
);
|
|
10066
|
+
}
|
|
10067
|
+
applyRunnerOpenCodeConfig({
|
|
10068
|
+
overlayPath: options.opencodeConfigOverlay,
|
|
10069
|
+
log: (message, level = "info") => {
|
|
10070
|
+
if (level === "error") {
|
|
10071
|
+
logActivity(state, { type: "error", error: message });
|
|
10072
|
+
} else {
|
|
10073
|
+
logActivity(state, { type: "info", level, message });
|
|
10074
|
+
}
|
|
10075
|
+
}
|
|
10076
|
+
});
|
|
8999
10077
|
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
9000
10078
|
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
9001
10079
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
@@ -9011,11 +10089,24 @@ async function run(options) {
|
|
|
9011
10089
|
interactive: state.interactive,
|
|
9012
10090
|
agentId: state.agentId,
|
|
9013
10091
|
log: (message) => log2(state, message),
|
|
9014
|
-
startTimeoutMs: opencodeStartTimeoutMs
|
|
10092
|
+
startTimeoutMs: opencodeStartTimeoutMs,
|
|
10093
|
+
inheritStdio: Boolean(options.opencodePidFile)
|
|
9015
10094
|
});
|
|
9016
10095
|
state.port = oc.port;
|
|
9017
|
-
state.opencodeProcess = oc.process;
|
|
10096
|
+
state.opencodeProcess = options.opencodePidFile ? null : oc.process;
|
|
9018
10097
|
state.opencodeVersion = oc.version;
|
|
10098
|
+
if (options.opencodePidFile && oc.process?.pid !== void 0) {
|
|
10099
|
+
try {
|
|
10100
|
+
writeFileSync4(options.opencodePidFile, `${oc.process.pid}
|
|
10101
|
+
`, { mode: 384 });
|
|
10102
|
+
chmodSync3(options.opencodePidFile, 384);
|
|
10103
|
+
} catch (error2) {
|
|
10104
|
+
logActivity(state, {
|
|
10105
|
+
type: "error",
|
|
10106
|
+
error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10107
|
+
});
|
|
10108
|
+
}
|
|
10109
|
+
}
|
|
9019
10110
|
state.opencodeConnected = oc.notReadyReason === null;
|
|
9020
10111
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
9021
10112
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
@@ -9052,6 +10143,108 @@ async function run(options) {
|
|
|
9052
10143
|
ocSpinner?.fail(error2.message);
|
|
9053
10144
|
throw error2;
|
|
9054
10145
|
}
|
|
10146
|
+
if (options.litestreamPidFile) {
|
|
10147
|
+
if (options.sessionDbNoReplicateMarker && existsSync3(options.sessionDbNoReplicateMarker)) {
|
|
10148
|
+
log2(
|
|
10149
|
+
state,
|
|
10150
|
+
`Skipping Litestream replication because ${options.sessionDbNoReplicateMarker} marks this session database unsafe to replicate`
|
|
10151
|
+
);
|
|
10152
|
+
} else if (!options.litestreamConfig) {
|
|
10153
|
+
logActivity(state, {
|
|
10154
|
+
type: "info",
|
|
10155
|
+
level: "warn",
|
|
10156
|
+
message: "Skipping Litestream replication because no configuration file was provided"
|
|
10157
|
+
});
|
|
10158
|
+
} else {
|
|
10159
|
+
let existingPid;
|
|
10160
|
+
if (existsSync3(options.litestreamPidFile)) {
|
|
10161
|
+
try {
|
|
10162
|
+
const rawPid = readFileSync5(options.litestreamPidFile, "utf8").trim();
|
|
10163
|
+
const parsedPid = Number(rawPid);
|
|
10164
|
+
if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
|
|
10165
|
+
existingPid = parsedPid;
|
|
10166
|
+
}
|
|
10167
|
+
} catch (error2) {
|
|
10168
|
+
logActivity(state, {
|
|
10169
|
+
type: "info",
|
|
10170
|
+
level: "warn",
|
|
10171
|
+
message: `Could not read Litestream pid file ${options.litestreamPidFile}; checking for a new process: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10172
|
+
});
|
|
10173
|
+
}
|
|
10174
|
+
}
|
|
10175
|
+
if (existingPid !== void 0 && isProcessAlive(existingPid)) {
|
|
10176
|
+
log2(state, `Litestream replication is already running with pid ${existingPid}`);
|
|
10177
|
+
} else {
|
|
10178
|
+
const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
|
|
10179
|
+
state.litestreamProcess = null;
|
|
10180
|
+
let failureHandled = false;
|
|
10181
|
+
const reportImageOwnedReplicationFailure = (message) => {
|
|
10182
|
+
if (failureHandled || state.shuttingDown || !state.running) return;
|
|
10183
|
+
failureHandled = true;
|
|
10184
|
+
logActivity(state, { type: "error", error: message });
|
|
10185
|
+
if (state.interactive) displayStatus(state);
|
|
10186
|
+
};
|
|
10187
|
+
litestreamProcess.on("exit", (code, signal) => {
|
|
10188
|
+
reportImageOwnedReplicationFailure(
|
|
10189
|
+
`Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
|
|
10190
|
+
);
|
|
10191
|
+
});
|
|
10192
|
+
litestreamProcess.on("error", (error2) => {
|
|
10193
|
+
reportImageOwnedReplicationFailure(
|
|
10194
|
+
`Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10195
|
+
);
|
|
10196
|
+
});
|
|
10197
|
+
try {
|
|
10198
|
+
if (litestreamProcess.pid !== void 0) {
|
|
10199
|
+
writeFileSync4(options.litestreamPidFile, `${litestreamProcess.pid}
|
|
10200
|
+
`, {
|
|
10201
|
+
mode: 384
|
|
10202
|
+
});
|
|
10203
|
+
chmodSync3(options.litestreamPidFile, 384);
|
|
10204
|
+
}
|
|
10205
|
+
} catch (error2) {
|
|
10206
|
+
logActivity(state, {
|
|
10207
|
+
type: "error",
|
|
10208
|
+
error: `Failed to write Litestream pid file ${options.litestreamPidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10209
|
+
});
|
|
10210
|
+
}
|
|
10211
|
+
log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
|
|
10212
|
+
}
|
|
10213
|
+
}
|
|
10214
|
+
} else if (options.litestreamConfig) {
|
|
10215
|
+
const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
|
|
10216
|
+
state.litestreamProcess = litestreamProcess;
|
|
10217
|
+
let failureHandled = false;
|
|
10218
|
+
const failRunForReplication = (message) => {
|
|
10219
|
+
if (failureHandled || state.shuttingDown || !state.running) return;
|
|
10220
|
+
failureHandled = true;
|
|
10221
|
+
state.shuttingDown = true;
|
|
10222
|
+
logActivity(state, { type: "error", error: message });
|
|
10223
|
+
if (state.interactive) displayStatus(state);
|
|
10224
|
+
void (async () => {
|
|
10225
|
+
try {
|
|
10226
|
+
await cleanup(state);
|
|
10227
|
+
await shutdownTelemetry();
|
|
10228
|
+
} catch (error2) {
|
|
10229
|
+
console.error(
|
|
10230
|
+
`[run] replication failure cleanup failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10231
|
+
);
|
|
10232
|
+
}
|
|
10233
|
+
process.exit(1);
|
|
10234
|
+
})();
|
|
10235
|
+
};
|
|
10236
|
+
litestreamProcess.on("exit", (code, signal) => {
|
|
10237
|
+
failRunForReplication(
|
|
10238
|
+
`Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
|
|
10239
|
+
);
|
|
10240
|
+
});
|
|
10241
|
+
litestreamProcess.on("error", (error2) => {
|
|
10242
|
+
failRunForReplication(
|
|
10243
|
+
`Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
10244
|
+
);
|
|
10245
|
+
});
|
|
10246
|
+
log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
|
|
10247
|
+
}
|
|
9055
10248
|
const tunnelSpinner = interactive && !state.json ? ora3("Connecting tunnel...").start() : null;
|
|
9056
10249
|
const channelDriver = new ChannelDriver({
|
|
9057
10250
|
agentId: state.agentId,
|
|
@@ -9063,7 +10256,7 @@ async function run(options) {
|
|
|
9063
10256
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
9064
10257
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
9065
10258
|
fileSyncDirectories,
|
|
9066
|
-
homeDir:
|
|
10259
|
+
homeDir: homedir5(),
|
|
9067
10260
|
maxActiveSessions,
|
|
9068
10261
|
log: (entry) => (
|
|
9069
10262
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
@@ -9312,6 +10505,27 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
9312
10505
|
).option(
|
|
9313
10506
|
"--tunnel-ready-file <path>",
|
|
9314
10507
|
"Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
|
|
10508
|
+
).option(
|
|
10509
|
+
"--litestream-config <path>",
|
|
10510
|
+
"Replicate the OpenCode session database with `litestream replicate` using this config file (written by the runner image). Omit to disable replication."
|
|
10511
|
+
).option(
|
|
10512
|
+
"--opencode-pid-file <path>",
|
|
10513
|
+
"Record the OpenCode pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
|
|
10514
|
+
).option(
|
|
10515
|
+
"--litestream-pid-file <path>",
|
|
10516
|
+
"Record the Litestream pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
|
|
10517
|
+
).option(
|
|
10518
|
+
"--session-db-no-replicate-marker <path>",
|
|
10519
|
+
"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."
|
|
10520
|
+
).option(
|
|
10521
|
+
"--restore-session-db",
|
|
10522
|
+
"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."
|
|
10523
|
+
).option(
|
|
10524
|
+
"--restore-runner-credentials",
|
|
10525
|
+
"Restore the hosted runner secret and persisted credential stores before starting OpenCode."
|
|
10526
|
+
).option(
|
|
10527
|
+
"--opencode-config-overlay <path>",
|
|
10528
|
+
"Apply this runner-provided OpenCode config before starting OpenCode."
|
|
9315
10529
|
).action(
|
|
9316
10530
|
(options) => {
|
|
9317
10531
|
run({
|
|
@@ -9343,7 +10557,14 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
9343
10557
|
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
9344
10558
|
// resolveFileSyncDirectories.
|
|
9345
10559
|
enableFileSyncTo: options.enableFileSyncTo,
|
|
9346
|
-
tunnelReadyFile: options.tunnelReadyFile
|
|
10560
|
+
tunnelReadyFile: options.tunnelReadyFile,
|
|
10561
|
+
litestreamConfig: options.litestreamConfig,
|
|
10562
|
+
opencodePidFile: options.opencodePidFile,
|
|
10563
|
+
litestreamPidFile: options.litestreamPidFile,
|
|
10564
|
+
sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
|
|
10565
|
+
restoreSessionDb: options.restoreSessionDb,
|
|
10566
|
+
restoreRunnerCredentials: options.restoreRunnerCredentials,
|
|
10567
|
+
opencodeConfigOverlay: options.opencodeConfigOverlay
|
|
9347
10568
|
});
|
|
9348
10569
|
}
|
|
9349
10570
|
);
|