@evident-ai/cli 3.5.2-dev.35de651 → 3.5.2-dev.3c6c52c
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/dist/index.js +568 -137
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -315,14 +315,14 @@ function blank() {
|
|
|
315
315
|
console.log();
|
|
316
316
|
}
|
|
317
317
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
318
|
-
return new Promise((
|
|
318
|
+
return new Promise((resolve5) => {
|
|
319
319
|
process.stdout.write(chalk.dim(prompt));
|
|
320
320
|
const handler = () => {
|
|
321
321
|
process.stdin.removeListener("data", handler);
|
|
322
322
|
process.stdin.setRawMode?.(false);
|
|
323
323
|
process.stdin.pause();
|
|
324
324
|
console.log();
|
|
325
|
-
|
|
325
|
+
resolve5();
|
|
326
326
|
};
|
|
327
327
|
if (process.stdin.isTTY) {
|
|
328
328
|
process.stdin.setRawMode?.(true);
|
|
@@ -332,7 +332,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
332
332
|
});
|
|
333
333
|
}
|
|
334
334
|
function sleep(ms) {
|
|
335
|
-
return new Promise((
|
|
335
|
+
return new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
336
336
|
}
|
|
337
337
|
|
|
338
338
|
// src/commands/login.ts
|
|
@@ -410,19 +410,19 @@ async function tokenLogin() {
|
|
|
410
410
|
);
|
|
411
411
|
blank();
|
|
412
412
|
process.stdout.write("Paste token: ");
|
|
413
|
-
const token = await new Promise((
|
|
413
|
+
const token = await new Promise((resolve5) => {
|
|
414
414
|
let data = "";
|
|
415
415
|
process.stdin.setEncoding("utf8");
|
|
416
416
|
process.stdin.on("data", (chunk) => {
|
|
417
417
|
data += chunk;
|
|
418
418
|
});
|
|
419
419
|
process.stdin.on("end", () => {
|
|
420
|
-
|
|
420
|
+
resolve5(data.trim());
|
|
421
421
|
});
|
|
422
422
|
if (process.stdin.isTTY) {
|
|
423
423
|
process.stdin.once("data", (chunk) => {
|
|
424
424
|
process.stdin.pause();
|
|
425
|
-
|
|
425
|
+
resolve5(chunk.toString().trim());
|
|
426
426
|
});
|
|
427
427
|
process.stdin.resume();
|
|
428
428
|
}
|
|
@@ -1158,7 +1158,7 @@ async function claudeUsage() {
|
|
|
1158
1158
|
// src/commands/run.ts
|
|
1159
1159
|
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "node:fs";
|
|
1160
1160
|
import { homedir as homedir7 } from "node:os";
|
|
1161
|
-
import { isAbsolute as
|
|
1161
|
+
import { isAbsolute as isAbsolute4, join as join12, parse, resolve as resolvePath2 } from "node:path";
|
|
1162
1162
|
import chalk7 from "chalk";
|
|
1163
1163
|
|
|
1164
1164
|
// ../../packages/types/src/agents/index.ts
|
|
@@ -1293,7 +1293,11 @@ var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
|
|
|
1293
1293
|
function log(level, event, fields) {
|
|
1294
1294
|
const method = level === "debug" ? "log" : level;
|
|
1295
1295
|
try {
|
|
1296
|
-
|
|
1296
|
+
const payload = Object.fromEntries(
|
|
1297
|
+
Object.entries({ level, event, ...fields }).filter(([, value]) => value !== void 0)
|
|
1298
|
+
);
|
|
1299
|
+
const secondArgument = globalThis.navigator?.userAgent === "Cloudflare-Workers" ? payload : JSON.stringify(payload);
|
|
1300
|
+
console[method]("[evident]", secondArgument);
|
|
1297
1301
|
} catch (err) {
|
|
1298
1302
|
console.error(
|
|
1299
1303
|
"[evident] log_serialize_failed",
|
|
@@ -1322,7 +1326,7 @@ import ora4 from "ora";
|
|
|
1322
1326
|
import { select as select4 } from "@inquirer/prompts";
|
|
1323
1327
|
|
|
1324
1328
|
// src/lib/telemetry.ts
|
|
1325
|
-
var CLI_VERSION = (true ? "3.5.2-dev.
|
|
1329
|
+
var CLI_VERSION = (true ? "3.5.2-dev.3c6c52c" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
1326
1330
|
function getCliVersion() {
|
|
1327
1331
|
return CLI_VERSION;
|
|
1328
1332
|
}
|
|
@@ -1810,6 +1814,263 @@ async function reclaimSessionDbSpace(input) {
|
|
|
1810
1814
|
}
|
|
1811
1815
|
}
|
|
1812
1816
|
|
|
1817
|
+
// src/lib/opencode/dependency-install-diagnostic.ts
|
|
1818
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
1819
|
+
import { basename, dirname as dirname3, isAbsolute, join as join2, relative, resolve, sep } from "node:path";
|
|
1820
|
+
var DEPENDENCY_INSTALL_FAILURE_MESSAGE = "background dependency install failed";
|
|
1821
|
+
var MAX_DISTINCT_DIAGNOSTICS = 32;
|
|
1822
|
+
var EFFECT = "OpenCode could not install background dependencies for this scope; its plugins and tools may be unavailable";
|
|
1823
|
+
function readOpenCodeLogField(line, key) {
|
|
1824
|
+
const match = line.match(new RegExp(`(?:^|\\s)${key}=(?:"((?:\\\\.|[^"])*)"|(\\S+))`));
|
|
1825
|
+
if (!match) return void 0;
|
|
1826
|
+
if (match[1] === void 0) return match[2];
|
|
1827
|
+
return match[1].replace(/\\(["\\n])/g, (_match, escaped) => {
|
|
1828
|
+
return escaped === "n" ? "\n" : escaped;
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
function parseTrigger(line) {
|
|
1832
|
+
if (readOpenCodeLogField(line, "message") !== DEPENDENCY_INSTALL_FAILURE_MESSAGE) {
|
|
1833
|
+
return null;
|
|
1834
|
+
}
|
|
1835
|
+
const error2 = readOpenCodeLogField(line, "error");
|
|
1836
|
+
if (!error2 || !/\bEACCES\b/.test(error2)) return null;
|
|
1837
|
+
const errnoMatch = error2.match(/\bEACCES:\s*permission denied,\s*([a-z_]+)\s+'([^']*)'/);
|
|
1838
|
+
const capturedPath = errnoMatch?.[2];
|
|
1839
|
+
return {
|
|
1840
|
+
dir: readOpenCodeLogField(line, "dir"),
|
|
1841
|
+
op: errnoMatch?.[1],
|
|
1842
|
+
path: capturedPath && isAbsolute(capturedPath) ? capturedPath : void 0
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
function getErrorCode(error2) {
|
|
1846
|
+
if (typeof error2 === "object" && error2 !== null && "code" in error2) {
|
|
1847
|
+
const code = error2.code;
|
|
1848
|
+
if (typeof code === "string") return code;
|
|
1849
|
+
}
|
|
1850
|
+
return "UNKNOWN";
|
|
1851
|
+
}
|
|
1852
|
+
function isWithin(path, root) {
|
|
1853
|
+
const candidate = resolve(path);
|
|
1854
|
+
const resolvedRoot = resolve(root);
|
|
1855
|
+
return candidate === resolvedRoot || candidate.startsWith(`${resolvedRoot}${sep}`);
|
|
1856
|
+
}
|
|
1857
|
+
function rootSpecs(context) {
|
|
1858
|
+
return [
|
|
1859
|
+
{ token: "~", configured: resolve(context.homeDir) },
|
|
1860
|
+
{ token: "$WORKSPACE", configured: resolve(context.cwd) }
|
|
1861
|
+
];
|
|
1862
|
+
}
|
|
1863
|
+
function resolveRoots(context) {
|
|
1864
|
+
const resolved = [];
|
|
1865
|
+
const unresolved = [];
|
|
1866
|
+
for (const spec of rootSpecs(context)) {
|
|
1867
|
+
try {
|
|
1868
|
+
resolved.push({ ...spec, real: realpathSync(spec.configured) });
|
|
1869
|
+
} catch (_error) {
|
|
1870
|
+
unresolved.push(spec);
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
return { resolved, unresolved };
|
|
1874
|
+
}
|
|
1875
|
+
function resolveNearestAncestor(failingPath, remaining, error2) {
|
|
1876
|
+
let ancestor = dirname3(failingPath);
|
|
1877
|
+
const suffix = [basename(failingPath), ...remaining];
|
|
1878
|
+
while (ancestor) {
|
|
1879
|
+
try {
|
|
1880
|
+
return {
|
|
1881
|
+
path: resolve(realpathSync(ancestor), ...suffix),
|
|
1882
|
+
failure: { path: resolve(failingPath), error: error2 }
|
|
1883
|
+
};
|
|
1884
|
+
} catch (ancestorError) {
|
|
1885
|
+
if (ancestor === dirname3(ancestor) || !getErrorCode(ancestorError).startsWith("E")) {
|
|
1886
|
+
return null;
|
|
1887
|
+
}
|
|
1888
|
+
suffix.unshift(basename(ancestor));
|
|
1889
|
+
ancestor = dirname3(ancestor);
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
return null;
|
|
1893
|
+
}
|
|
1894
|
+
function resolveExistingPath(absolutePath) {
|
|
1895
|
+
if (!isAbsolute(absolutePath)) return null;
|
|
1896
|
+
const candidate = resolve(absolutePath);
|
|
1897
|
+
const remaining = [];
|
|
1898
|
+
let current = candidate;
|
|
1899
|
+
while (current) {
|
|
1900
|
+
try {
|
|
1901
|
+
const stat2 = lstatSync(current);
|
|
1902
|
+
if (stat2.isSymbolicLink()) {
|
|
1903
|
+
if (remaining.length === 0) {
|
|
1904
|
+
return { path: join2(realpathSync(dirname3(current)), basename(current)) };
|
|
1905
|
+
}
|
|
1906
|
+
return { path: resolve(realpathSync(current), ...remaining) };
|
|
1907
|
+
}
|
|
1908
|
+
return { path: resolve(realpathSync(current), ...remaining) };
|
|
1909
|
+
} catch (error2) {
|
|
1910
|
+
const code = getErrorCode(error2);
|
|
1911
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
1912
|
+
return resolveNearestAncestor(current, remaining, error2);
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
if (current === dirname3(current)) return null;
|
|
1916
|
+
remaining.unshift(basename(current));
|
|
1917
|
+
current = dirname3(current);
|
|
1918
|
+
}
|
|
1919
|
+
return null;
|
|
1920
|
+
}
|
|
1921
|
+
function tokenise(absolutePath, roots) {
|
|
1922
|
+
const pathResolution = resolveExistingPath(absolutePath);
|
|
1923
|
+
if (!pathResolution) return null;
|
|
1924
|
+
const root = roots.reduce((selected, candidate) => {
|
|
1925
|
+
if (!isWithin(pathResolution.path, candidate.real)) return selected;
|
|
1926
|
+
if (!selected || candidate.real.length > selected.real.length || candidate.real.length === selected.real.length && candidate.token === "$WORKSPACE") {
|
|
1927
|
+
return candidate;
|
|
1928
|
+
}
|
|
1929
|
+
return selected;
|
|
1930
|
+
}, null);
|
|
1931
|
+
if (!root) return null;
|
|
1932
|
+
const suffix = relative(root.real, pathResolution.path);
|
|
1933
|
+
return {
|
|
1934
|
+
value: suffix ? `${root.token}/${suffix.split(sep).join("/")}` : root.token,
|
|
1935
|
+
root,
|
|
1936
|
+
resolutionFailure: pathResolution.failure
|
|
1937
|
+
};
|
|
1938
|
+
}
|
|
1939
|
+
function classifyScope(dir, roots) {
|
|
1940
|
+
if (!dir) return "other";
|
|
1941
|
+
const tokenisedDir = tokenise(dir, roots.resolved);
|
|
1942
|
+
if (tokenisedDir) return tokenisedDir.root.token === "$WORKSPACE" ? "workspace" : "global";
|
|
1943
|
+
for (const spec of roots.unresolved) {
|
|
1944
|
+
if (isWithin(dir, spec.configured)) {
|
|
1945
|
+
return spec.token === "$WORKSPACE" ? "workspace" : "global";
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
return "other";
|
|
1949
|
+
}
|
|
1950
|
+
function unresolvedRootForPath(path, unresolved) {
|
|
1951
|
+
return unresolved.find((spec) => isWithin(path, spec.configured));
|
|
1952
|
+
}
|
|
1953
|
+
function statType(stat2) {
|
|
1954
|
+
if (stat2.isDirectory()) return "d";
|
|
1955
|
+
if (stat2.isFile()) return "f";
|
|
1956
|
+
if (stat2.isSymbolicLink()) return "l";
|
|
1957
|
+
return "o";
|
|
1958
|
+
}
|
|
1959
|
+
function renderStat(name, stat2) {
|
|
1960
|
+
const mode = (stat2.mode & 4095).toString(8).padStart(4, "0");
|
|
1961
|
+
return `${name}:${statType(stat2)}:${stat2.uid}:${stat2.gid}:${mode}`;
|
|
1962
|
+
}
|
|
1963
|
+
function renderStatError(name, error2) {
|
|
1964
|
+
const code = getErrorCode(error2);
|
|
1965
|
+
return `${name}:${renderErrorCode(code)}`;
|
|
1966
|
+
}
|
|
1967
|
+
function renderErrorCode(code) {
|
|
1968
|
+
if (code === "ENOENT") return "missing";
|
|
1969
|
+
return code.startsWith("E") ? code : `E${code}`;
|
|
1970
|
+
}
|
|
1971
|
+
function inspectChain(rootReal, rootToken, absolutePath, resolutionFailure) {
|
|
1972
|
+
const target = resolve(absolutePath);
|
|
1973
|
+
const relativePath = relative(rootReal, target);
|
|
1974
|
+
const components = relativePath ? relativePath.split(sep) : [];
|
|
1975
|
+
const entries = [];
|
|
1976
|
+
let current = rootReal;
|
|
1977
|
+
let status2 = "complete";
|
|
1978
|
+
let finalStat;
|
|
1979
|
+
for (const name of [rootToken, ...components]) {
|
|
1980
|
+
if (name !== rootToken) current = join2(current, name);
|
|
1981
|
+
if (resolutionFailure && resolve(current) === resolve(resolutionFailure.path)) {
|
|
1982
|
+
entries.push(renderStatError(name, resolutionFailure.error));
|
|
1983
|
+
status2 = "stat_failed";
|
|
1984
|
+
break;
|
|
1985
|
+
}
|
|
1986
|
+
try {
|
|
1987
|
+
const stat2 = lstatSync(current);
|
|
1988
|
+
entries.push(renderStat(name, stat2));
|
|
1989
|
+
finalStat = stat2;
|
|
1990
|
+
} catch (error2) {
|
|
1991
|
+
entries.push(renderStatError(name, error2));
|
|
1992
|
+
if (getErrorCode(error2) !== "ENOENT") status2 = "stat_failed";
|
|
1993
|
+
break;
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
let symlinkTarget;
|
|
1997
|
+
let symlinkMeta;
|
|
1998
|
+
if (finalStat?.isSymbolicLink() && entries.length === components.length + 1) {
|
|
1999
|
+
try {
|
|
2000
|
+
symlinkTarget = realpathSync(current);
|
|
2001
|
+
try {
|
|
2002
|
+
symlinkMeta = renderStat("", lstatSync(symlinkTarget)).slice(1);
|
|
2003
|
+
} catch (error2) {
|
|
2004
|
+
symlinkMeta = renderErrorCode(getErrorCode(error2));
|
|
2005
|
+
status2 = "stat_failed";
|
|
2006
|
+
}
|
|
2007
|
+
} catch (error2) {
|
|
2008
|
+
symlinkTarget = "<unresolved>";
|
|
2009
|
+
symlinkMeta = renderErrorCode(getErrorCode(error2));
|
|
2010
|
+
status2 = "stat_failed";
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
return { status: status2, chain: entries.join(","), symlinkTarget, symlinkMeta };
|
|
2014
|
+
}
|
|
2015
|
+
function buildDiagnostic(line, context) {
|
|
2016
|
+
const trigger = parseTrigger(line);
|
|
2017
|
+
if (!trigger) return null;
|
|
2018
|
+
const roots = resolveRoots(context);
|
|
2019
|
+
const scope = classifyScope(trigger.dir, roots);
|
|
2020
|
+
const pathSource = trigger.path ? "error" : trigger.dir ? "dir" : "none";
|
|
2021
|
+
const inspectedPath = trigger.path ?? trigger.dir;
|
|
2022
|
+
const microvmId = context.microvmId?.trim() || "unknown";
|
|
2023
|
+
const euid = context.euid === void 0 ? "unavailable" : String(context.euid);
|
|
2024
|
+
const egid = context.egid === void 0 ? "unavailable" : String(context.egid);
|
|
2025
|
+
const op = trigger.op ?? "unknown";
|
|
2026
|
+
if (!inspectedPath) {
|
|
2027
|
+
return {
|
|
2028
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=no_path path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=unknown cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
|
|
2029
|
+
localDetail: null
|
|
2030
|
+
};
|
|
2031
|
+
}
|
|
2032
|
+
const tokenisedPath = tokenise(inspectedPath, roots.resolved);
|
|
2033
|
+
if (!tokenisedPath) {
|
|
2034
|
+
const unresolvedRoot = unresolvedRootForPath(inspectedPath, roots.unresolved);
|
|
2035
|
+
if (unresolvedRoot) {
|
|
2036
|
+
return {
|
|
2037
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=root_unresolved path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=unknown cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
|
|
2038
|
+
localDetail: null
|
|
2039
|
+
};
|
|
2040
|
+
}
|
|
2041
|
+
return {
|
|
2042
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=outside_roots path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=<outside-approved-roots> cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
|
|
2043
|
+
localDetail: `OPENCODE-DEPENDENCY-INSTALL-EACCES (local only): outside approved roots: ${inspectedPath}`
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
const inspection = inspectChain(
|
|
2047
|
+
tokenisedPath.root.real,
|
|
2048
|
+
tokenisedPath.root.token,
|
|
2049
|
+
inspectedPath,
|
|
2050
|
+
tokenisedPath.resolutionFailure
|
|
2051
|
+
);
|
|
2052
|
+
const optionalSymlinkFields = inspection.symlinkTarget ? ` symlink_target=${tokenise(inspection.symlinkTarget, roots.resolved)?.value ?? "<outside-approved-roots>"}` + (inspection.symlinkMeta ? ` symlink_meta=${inspection.symlinkMeta}` : "") : "";
|
|
2053
|
+
return {
|
|
2054
|
+
event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=${inspection.status} path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=${tokenisedPath.value} cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=${inspection.chain}${optionalSymlinkFields}`,
|
|
2055
|
+
localDetail: null
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
function createDependencyInstallDiagnosticReporter({
|
|
2059
|
+
context,
|
|
2060
|
+
emitEvent: emitEvent2,
|
|
2061
|
+
emitLocal
|
|
2062
|
+
}) {
|
|
2063
|
+
const emittedEvents = /* @__PURE__ */ new Set();
|
|
2064
|
+
return (line) => {
|
|
2065
|
+
const diagnostic = buildDiagnostic(line, context);
|
|
2066
|
+
if (!diagnostic || emittedEvents.has(diagnostic.event)) return;
|
|
2067
|
+
if (emittedEvents.size >= MAX_DISTINCT_DIAGNOSTICS) return;
|
|
2068
|
+
emittedEvents.add(diagnostic.event);
|
|
2069
|
+
emitEvent2(diagnostic.event);
|
|
2070
|
+
if (diagnostic.localDetail) emitLocal(diagnostic.localDetail);
|
|
2071
|
+
};
|
|
2072
|
+
}
|
|
2073
|
+
|
|
1813
2074
|
// src/lib/runner-activity-telemetry.ts
|
|
1814
2075
|
var FORWARDED_LEVELS_BY_SOURCE = {
|
|
1815
2076
|
"cli.run": /* @__PURE__ */ new Set(["warn", "error"]),
|
|
@@ -1841,7 +2102,17 @@ function parseOpenCodeLogLine(line) {
|
|
|
1841
2102
|
}
|
|
1842
2103
|
var MAX_LINE_BUFFER_BYTES = 16 * 1024;
|
|
1843
2104
|
var REPEAT_SUPPRESSION_WINDOW_MS = 6e4;
|
|
1844
|
-
function
|
|
2105
|
+
function sanitiseDependencyInstallWarning(line) {
|
|
2106
|
+
const withoutDirectory = line.replace(
|
|
2107
|
+
/((?:^|\s)dir=)(?:"(?:\\.|[^"])*"|\/[^\s)"']+|\S+)/g,
|
|
2108
|
+
"$1<path>"
|
|
2109
|
+
);
|
|
2110
|
+
return withoutDirectory.replace(
|
|
2111
|
+
/((?:^|\s)error=)"((?:\\.|[^"])*)"/,
|
|
2112
|
+
(_match, prefix, error2) => `${prefix}"${error2.replace(/'\/[^']*'/g, "'<path>'")}"`
|
|
2113
|
+
);
|
|
2114
|
+
}
|
|
2115
|
+
function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure, onDependencyInstallFailure) {
|
|
1845
2116
|
let buffer = Buffer.alloc(0);
|
|
1846
2117
|
const repeatStates = /* @__PURE__ */ new Map();
|
|
1847
2118
|
const forwardLine = (line, parsed, repeatsSuppressed = 0) => {
|
|
@@ -1853,7 +2124,7 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
|
|
|
1853
2124
|
forwardRunnerActivity(
|
|
1854
2125
|
{
|
|
1855
2126
|
level: parsed.level,
|
|
1856
|
-
error: line,
|
|
2127
|
+
error: parsed.message === DEPENDENCY_INSTALL_FAILURE_MESSAGE ? sanitiseDependencyInstallWarning(line) : line,
|
|
1857
2128
|
metadata: Object.keys(metadata).length > 0 ? metadata : void 0,
|
|
1858
2129
|
source: "opencode"
|
|
1859
2130
|
},
|
|
@@ -1871,24 +2142,7 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
|
|
|
1871
2142
|
repeatStates.delete(key);
|
|
1872
2143
|
}
|
|
1873
2144
|
};
|
|
1874
|
-
const
|
|
1875
|
-
const parsed = parseOpenCodeLogLine(line);
|
|
1876
|
-
const isDiskFailure = isSessionStoreWriteFailure(line);
|
|
1877
|
-
const cause = sessionStoreCauseToken(line);
|
|
1878
|
-
if (onSessionStoreWriteFailure && (isDiskFailure || cause !== null)) {
|
|
1879
|
-
try {
|
|
1880
|
-
onSessionStoreWriteFailure({
|
|
1881
|
-
isDiskFailure,
|
|
1882
|
-
sessionId: parsed?.sessionID ?? null,
|
|
1883
|
-
cause
|
|
1884
|
-
});
|
|
1885
|
-
} catch (err) {
|
|
1886
|
-
reportTelemetryDiagnostic(
|
|
1887
|
-
`Runner activity telemetry could not record session-store write failure: ${err instanceof Error ? err.message : String(err)}`
|
|
1888
|
-
);
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
if (!parsed) return;
|
|
2145
|
+
const forwardWithRepeatSuppression = (line, parsed) => {
|
|
1892
2146
|
const now = Date.now();
|
|
1893
2147
|
const key = parsed.message === void 0 ? void 0 : `${parsed.level}\0${parsed.message}\0${parsed.sessionID ?? ""}\0${parsed.messageID ?? ""}`;
|
|
1894
2148
|
expireRepeatStates(now, key);
|
|
@@ -1911,6 +2165,35 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
|
|
|
1911
2165
|
previous.parsed = parsed;
|
|
1912
2166
|
previous.repeatsSuppressed++;
|
|
1913
2167
|
};
|
|
2168
|
+
const flushLine = (line) => {
|
|
2169
|
+
const parsed = parseOpenCodeLogLine(line);
|
|
2170
|
+
const isDiskFailure = isSessionStoreWriteFailure(line);
|
|
2171
|
+
const cause = sessionStoreCauseToken(line);
|
|
2172
|
+
if (onSessionStoreWriteFailure && (isDiskFailure || cause !== null)) {
|
|
2173
|
+
try {
|
|
2174
|
+
onSessionStoreWriteFailure({
|
|
2175
|
+
isDiskFailure,
|
|
2176
|
+
sessionId: parsed?.sessionID ?? null,
|
|
2177
|
+
cause
|
|
2178
|
+
});
|
|
2179
|
+
} catch (err) {
|
|
2180
|
+
reportTelemetryDiagnostic(
|
|
2181
|
+
`Runner activity telemetry could not record session-store write failure: ${err instanceof Error ? err.message : String(err)}`
|
|
2182
|
+
);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
if (!parsed) return;
|
|
2186
|
+
forwardWithRepeatSuppression(line, parsed);
|
|
2187
|
+
if (onDependencyInstallFailure && parsed.message === DEPENDENCY_INSTALL_FAILURE_MESSAGE) {
|
|
2188
|
+
try {
|
|
2189
|
+
onDependencyInstallFailure(line);
|
|
2190
|
+
} catch (err) {
|
|
2191
|
+
reportTelemetryDiagnostic(
|
|
2192
|
+
`Runner activity telemetry could not record dependency-install failure diagnostic: ${err instanceof Error ? err.message : String(err)}`
|
|
2193
|
+
);
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
};
|
|
1914
2197
|
const forward = ((chunk) => {
|
|
1915
2198
|
buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf-8")]);
|
|
1916
2199
|
let newlineIndex;
|
|
@@ -1950,6 +2233,23 @@ function truncate(message) {
|
|
|
1950
2233
|
const remaining = MAX_MESSAGE_LENGTH - marker.length;
|
|
1951
2234
|
const headLength = Math.ceil(remaining * 0.6);
|
|
1952
2235
|
const tailLength = remaining - headLength;
|
|
2236
|
+
const effectMatch = message.startsWith("OPENCODE-DEPENDENCY-INSTALL-EACCES:") ? message.match(/ effect="[^"]*"/) : null;
|
|
2237
|
+
if (effectMatch?.index !== void 0) {
|
|
2238
|
+
const effectEnd = effectMatch.index + effectMatch[0].length;
|
|
2239
|
+
if (effectEnd > headLength && effectEnd < message.length) {
|
|
2240
|
+
const effectLength = effectMatch[0].length;
|
|
2241
|
+
const nonEffectLength = remaining - effectLength;
|
|
2242
|
+
const preservedTailLength = Math.min(
|
|
2243
|
+
message.length - effectEnd,
|
|
2244
|
+
nonEffectLength - Math.min(effectMatch.index, Math.ceil(nonEffectLength * 0.6))
|
|
2245
|
+
);
|
|
2246
|
+
const preservedHeadLength = Math.min(
|
|
2247
|
+
effectMatch.index,
|
|
2248
|
+
nonEffectLength - preservedTailLength
|
|
2249
|
+
);
|
|
2250
|
+
return message.slice(0, preservedHeadLength) + marker + message.slice(effectMatch.index, effectEnd) + message.slice(message.length - preservedTailLength);
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
1953
2253
|
return message.slice(0, headLength) + marker + message.slice(message.length - tailLength);
|
|
1954
2254
|
}
|
|
1955
2255
|
function sanitiseMetadata(metadata) {
|
|
@@ -2027,10 +2327,10 @@ function forwardRunnerActivity(entry, context) {
|
|
|
2027
2327
|
|
|
2028
2328
|
// src/lib/opencode/session-db-recovery-report.ts
|
|
2029
2329
|
import { readFileSync as readFileSync2, unlinkSync } from "node:fs";
|
|
2030
|
-
import { join as
|
|
2330
|
+
import { join as join3 } from "node:path";
|
|
2031
2331
|
function sessionDbRecoveryReportPath(homeDir, env) {
|
|
2032
2332
|
const override = env.EVIDENT_SESSION_DB_RECOVERY_REPORT?.trim();
|
|
2033
|
-
return override ||
|
|
2333
|
+
return override || join3(homeDir, ".local", "state", "evident", "session-db-recovery.jsonl");
|
|
2034
2334
|
}
|
|
2035
2335
|
function drainSessionDbRecoveryReport({
|
|
2036
2336
|
homeDir,
|
|
@@ -2303,7 +2603,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
2303
2603
|
if (health.healthy || health.authFailed) {
|
|
2304
2604
|
return health;
|
|
2305
2605
|
}
|
|
2306
|
-
await new Promise((
|
|
2606
|
+
await new Promise((resolve5) => setTimeout(resolve5, 1e3));
|
|
2307
2607
|
}
|
|
2308
2608
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
2309
2609
|
}
|
|
@@ -2314,7 +2614,7 @@ async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
|
|
|
2314
2614
|
if (health.healthy || health.authFailed) {
|
|
2315
2615
|
return health;
|
|
2316
2616
|
}
|
|
2317
|
-
await new Promise((
|
|
2617
|
+
await new Promise((resolve5) => setTimeout(resolve5, 1e3));
|
|
2318
2618
|
}
|
|
2319
2619
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
2320
2620
|
}
|
|
@@ -2904,7 +3204,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments, c
|
|
|
2904
3204
|
return dispatchedUserMessageId;
|
|
2905
3205
|
}
|
|
2906
3206
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
2907
|
-
await new Promise((
|
|
3207
|
+
await new Promise((resolve5) => setTimeout(resolve5, READ_BACK_DELAY_MS));
|
|
2908
3208
|
}
|
|
2909
3209
|
}
|
|
2910
3210
|
return null;
|
|
@@ -3076,9 +3376,11 @@ function sumAssistantUsage(messages) {
|
|
|
3076
3376
|
let cacheWriteSum = 0;
|
|
3077
3377
|
let costSum = 0;
|
|
3078
3378
|
let sawCost = false;
|
|
3379
|
+
let toolCallCount = 0;
|
|
3079
3380
|
let modelId = null;
|
|
3080
3381
|
let providerId = null;
|
|
3081
3382
|
for (const m of selected) {
|
|
3383
|
+
toolCallCount += m.parts?.filter((part) => part.type === "tool").length ?? 0;
|
|
3082
3384
|
const info = m.info;
|
|
3083
3385
|
if (!info) continue;
|
|
3084
3386
|
const tokens = info.tokens;
|
|
@@ -3115,7 +3417,8 @@ function sumAssistantUsage(messages) {
|
|
|
3115
3417
|
usage_tokens_cache_write: cacheWriteSum,
|
|
3116
3418
|
// NULL means OpenCode never reported a cost; it is distinct from a genuine
|
|
3117
3419
|
// zero-cost message, which sets `sawCost` with `costSum === 0`.
|
|
3118
|
-
usage_cost_usd: sawCost ? costSum : null
|
|
3420
|
+
usage_cost_usd: sawCost ? costSum : null,
|
|
3421
|
+
turn_tool_calls: toolCallCount
|
|
3119
3422
|
};
|
|
3120
3423
|
}
|
|
3121
3424
|
function messageUsage(messages, userMessageId) {
|
|
@@ -3219,19 +3522,32 @@ function isAbortedTerminalReply(messages, userMessageId) {
|
|
|
3219
3522
|
}
|
|
3220
3523
|
return false;
|
|
3221
3524
|
}
|
|
3525
|
+
var CLAUDE_AUTH_EXPIRY_MESSAGES = Object.freeze([
|
|
3526
|
+
"Claude Code credentials are unavailable or expired. Run `claude` to refresh them."
|
|
3527
|
+
]);
|
|
3528
|
+
function extractReplyErrorShape(reply) {
|
|
3529
|
+
const error2 = errorOf(reply);
|
|
3530
|
+
if (error2 == null || typeof error2 !== "object") {
|
|
3531
|
+
return { name: null, statusCode: null };
|
|
3532
|
+
}
|
|
3533
|
+
const e = error2;
|
|
3534
|
+
const name = typeof e.name === "string" ? e.name.slice(0, 100) : null;
|
|
3535
|
+
const data = e.data;
|
|
3536
|
+
const statusCode = typeof data?.statusCode === "number" && Number.isFinite(data.statusCode) ? data.statusCode : null;
|
|
3537
|
+
return { name, statusCode };
|
|
3538
|
+
}
|
|
3222
3539
|
function classifyReplyAuthError(reply) {
|
|
3223
3540
|
const error2 = errorOf(reply);
|
|
3224
3541
|
if (error2 == null || typeof error2 !== "object") return null;
|
|
3225
3542
|
const e = error2;
|
|
3226
3543
|
const replyProviderId = reply?.info?.providerID ?? null;
|
|
3227
3544
|
const replyModelId = reply?.info?.modelID ?? null;
|
|
3545
|
+
const data = e.data;
|
|
3228
3546
|
if (e.name === "ProviderAuthError") {
|
|
3229
|
-
const data = e.data;
|
|
3230
3547
|
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
3231
3548
|
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
3232
3549
|
}
|
|
3233
3550
|
if (e.name === "APIError") {
|
|
3234
|
-
const data = e.data;
|
|
3235
3551
|
const statusCode = data?.statusCode;
|
|
3236
3552
|
if (statusCode === 401 || statusCode === 403) {
|
|
3237
3553
|
return {
|
|
@@ -3242,11 +3558,23 @@ function classifyReplyAuthError(reply) {
|
|
|
3242
3558
|
};
|
|
3243
3559
|
}
|
|
3244
3560
|
}
|
|
3561
|
+
const errorMessage3 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
|
|
3562
|
+
if (errorMessage3 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage3.includes(knownMessage))) {
|
|
3563
|
+
return {
|
|
3564
|
+
kind: "model_auth",
|
|
3565
|
+
providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
|
|
3566
|
+
modelId: replyModelId,
|
|
3567
|
+
reason: "rejected"
|
|
3568
|
+
};
|
|
3569
|
+
}
|
|
3245
3570
|
return null;
|
|
3246
3571
|
}
|
|
3247
3572
|
function messageFailure(messages, userMessageId) {
|
|
3248
3573
|
return classifyReplyAuthError(findLastAssistantReplyFor(messages, userMessageId));
|
|
3249
3574
|
}
|
|
3575
|
+
function isProviderModelNotFoundError(reason) {
|
|
3576
|
+
return reason.includes("Model not found:");
|
|
3577
|
+
}
|
|
3250
3578
|
function findLatestSubagentAuthOutcome(messages, sinceMs) {
|
|
3251
3579
|
if (!messages || messages.length === 0) return null;
|
|
3252
3580
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
@@ -3964,12 +4292,12 @@ async function readV2SessionErrorStream(client, options) {
|
|
|
3964
4292
|
|
|
3965
4293
|
// src/lib/opencode/credential-import-v2.ts
|
|
3966
4294
|
import { readFileSync as readFileSync4 } from "node:fs";
|
|
3967
|
-
import { join as
|
|
4295
|
+
import { join as join5 } from "node:path";
|
|
3968
4296
|
|
|
3969
4297
|
// src/lib/openai-usage.ts
|
|
3970
4298
|
import { readFileSync as readFileSync3 } from "node:fs";
|
|
3971
4299
|
import { homedir as homedir3 } from "node:os";
|
|
3972
|
-
import { join as
|
|
4300
|
+
import { join as join4 } from "node:path";
|
|
3973
4301
|
var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
3974
4302
|
var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
|
|
3975
4303
|
var OpenAiUsageError = class extends Error {
|
|
@@ -3983,7 +4311,7 @@ function isLocalCredentialProblem2(err) {
|
|
|
3983
4311
|
}
|
|
3984
4312
|
function readOpenCodeChatGptCredentials() {
|
|
3985
4313
|
try {
|
|
3986
|
-
const raw = readFileSync3(
|
|
4314
|
+
const raw = readFileSync3(join4(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
|
|
3987
4315
|
let parsed;
|
|
3988
4316
|
try {
|
|
3989
4317
|
parsed = JSON.parse(raw);
|
|
@@ -4209,13 +4537,13 @@ var INTEGRATION_LIST_RETRY_DELAY_MS = 1e3;
|
|
|
4209
4537
|
function isRecord3(value) {
|
|
4210
4538
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4211
4539
|
}
|
|
4212
|
-
var sleep2 = (milliseconds) => new Promise((
|
|
4540
|
+
var sleep2 = (milliseconds) => new Promise((resolve5) => setTimeout(resolve5, milliseconds));
|
|
4213
4541
|
function emptyResult(unsupported = [], outcome = "completed") {
|
|
4214
4542
|
return { outcome, imported: [], alreadyConnected: [], unsupported, failed: [] };
|
|
4215
4543
|
}
|
|
4216
4544
|
function readOpenCodeCredentials(homeDir, log3) {
|
|
4217
4545
|
try {
|
|
4218
|
-
const raw = readFileSync4(
|
|
4546
|
+
const raw = readFileSync4(join5(homeDir, ...OPENCODE_AUTH_SEGMENTS), "utf8");
|
|
4219
4547
|
let parsed;
|
|
4220
4548
|
try {
|
|
4221
4549
|
parsed = JSON.parse(raw);
|
|
@@ -4417,7 +4745,7 @@ async function importOpenCodeV2Credentials({
|
|
|
4417
4745
|
import { spawn as spawn2 } from "node:child_process";
|
|
4418
4746
|
import { mkdirSync, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync } from "node:fs";
|
|
4419
4747
|
import { homedir as homedir4 } from "node:os";
|
|
4420
|
-
import { dirname as
|
|
4748
|
+
import { dirname as dirname4, resolve as resolvePath } from "node:path";
|
|
4421
4749
|
|
|
4422
4750
|
// src/lib/runner-synchroniser.ts
|
|
4423
4751
|
import { spawn } from "node:child_process";
|
|
@@ -4427,7 +4755,7 @@ function appendError(stderr, error2) {
|
|
|
4427
4755
|
${message}`;
|
|
4428
4756
|
}
|
|
4429
4757
|
function runSynchroniser(args, opts) {
|
|
4430
|
-
return new Promise((
|
|
4758
|
+
return new Promise((resolve5) => {
|
|
4431
4759
|
let child;
|
|
4432
4760
|
let stdout = "";
|
|
4433
4761
|
let stderr = "";
|
|
@@ -4441,7 +4769,7 @@ function runSynchroniser(args, opts) {
|
|
|
4441
4769
|
if (timer.handle) clearTimeout(timer.handle);
|
|
4442
4770
|
if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
|
|
4443
4771
|
if (spawnListener) child.removeListener("spawn", spawnListener);
|
|
4444
|
-
|
|
4772
|
+
resolve5(result);
|
|
4445
4773
|
};
|
|
4446
4774
|
try {
|
|
4447
4775
|
child = spawn("runner-synchroniser", args, {
|
|
@@ -4545,7 +4873,7 @@ function clearMarker(options) {
|
|
|
4545
4873
|
function markNoReplicate(options, message) {
|
|
4546
4874
|
if (options.noReplicateMarker) {
|
|
4547
4875
|
try {
|
|
4548
|
-
mkdirSync(
|
|
4876
|
+
mkdirSync(dirname4(options.noReplicateMarker), { recursive: true });
|
|
4549
4877
|
writeFileSync(options.noReplicateMarker, "");
|
|
4550
4878
|
} catch (error2) {
|
|
4551
4879
|
options.log(
|
|
@@ -4604,7 +4932,7 @@ function parseSynchroniserEnv(stdout) {
|
|
|
4604
4932
|
return values;
|
|
4605
4933
|
}
|
|
4606
4934
|
function runCommand(command, args, options) {
|
|
4607
|
-
return new Promise((
|
|
4935
|
+
return new Promise((resolve5) => {
|
|
4608
4936
|
let child;
|
|
4609
4937
|
let stdout = "";
|
|
4610
4938
|
let stderr = "";
|
|
@@ -4613,7 +4941,7 @@ function runCommand(command, args, options) {
|
|
|
4613
4941
|
if (settled) return;
|
|
4614
4942
|
settled = true;
|
|
4615
4943
|
if (timer) clearTimeout(timer);
|
|
4616
|
-
|
|
4944
|
+
resolve5(result);
|
|
4617
4945
|
};
|
|
4618
4946
|
try {
|
|
4619
4947
|
child = spawn2(command, args, {
|
|
@@ -4621,7 +4949,7 @@ function runCommand(command, args, options) {
|
|
|
4621
4949
|
stdio: ["ignore", "pipe", "pipe"]
|
|
4622
4950
|
});
|
|
4623
4951
|
} catch (error2) {
|
|
4624
|
-
|
|
4952
|
+
resolve5({
|
|
4625
4953
|
code: null,
|
|
4626
4954
|
stdout,
|
|
4627
4955
|
stderr: error2 instanceof Error ? error2.message : String(error2),
|
|
@@ -4700,7 +5028,7 @@ async function ensureLitestreamConfig(options, env) {
|
|
|
4700
5028
|
return null;
|
|
4701
5029
|
}
|
|
4702
5030
|
try {
|
|
4703
|
-
mkdirSync(
|
|
5031
|
+
mkdirSync(dirname4(configPath), { recursive: true });
|
|
4704
5032
|
writeFileSync(configPath, rendered.stdout);
|
|
4705
5033
|
} catch (error2) {
|
|
4706
5034
|
options.log(
|
|
@@ -4967,7 +5295,7 @@ async function restoreAndVerifySessionDb(options) {
|
|
|
4967
5295
|
// src/lib/opencode/session-db-provenance.ts
|
|
4968
5296
|
import { createRequire } from "node:module";
|
|
4969
5297
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
|
|
4970
|
-
import { dirname as
|
|
5298
|
+
import { dirname as dirname5, join as join6 } from "node:path";
|
|
4971
5299
|
var require2 = createRequire(import.meta.url);
|
|
4972
5300
|
function readSessionDbMigrationIds(dbPath) {
|
|
4973
5301
|
let db;
|
|
@@ -5004,7 +5332,7 @@ function readSessionDbMigrationIds(dbPath) {
|
|
|
5004
5332
|
}
|
|
5005
5333
|
function sessionDbProvenanceStatePath(homeDir, env) {
|
|
5006
5334
|
const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
|
|
5007
|
-
return override ||
|
|
5335
|
+
return override || join6(homeDir, ".local", "state", "evident", "session-db-provenance.json");
|
|
5008
5336
|
}
|
|
5009
5337
|
function loadSessionDbProvenanceState(path) {
|
|
5010
5338
|
let value;
|
|
@@ -5033,7 +5361,7 @@ function loadSessionDbProvenanceState(path) {
|
|
|
5033
5361
|
}
|
|
5034
5362
|
function saveSessionDbProvenanceState(path, state) {
|
|
5035
5363
|
try {
|
|
5036
|
-
mkdirSync2(
|
|
5364
|
+
mkdirSync2(dirname5(path), { recursive: true });
|
|
5037
5365
|
writeFileSync2(path, `${JSON.stringify(state, null, 2)}
|
|
5038
5366
|
`, "utf8");
|
|
5039
5367
|
} catch (error2) {
|
|
@@ -5124,7 +5452,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
|
5124
5452
|
if (child.exitCode !== null || child.signalCode !== null) {
|
|
5125
5453
|
return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
|
|
5126
5454
|
}
|
|
5127
|
-
return new Promise((
|
|
5455
|
+
return new Promise((resolve5, reject) => {
|
|
5128
5456
|
let forced = false;
|
|
5129
5457
|
let settled = false;
|
|
5130
5458
|
const timer = setTimeout(() => {
|
|
@@ -5144,7 +5472,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
|
5144
5472
|
settled = true;
|
|
5145
5473
|
clearTimeout(timer);
|
|
5146
5474
|
child.removeListener("exit", onExit);
|
|
5147
|
-
|
|
5475
|
+
resolve5(result);
|
|
5148
5476
|
};
|
|
5149
5477
|
const fail = (error2) => {
|
|
5150
5478
|
if (settled) return;
|
|
@@ -5620,7 +5948,7 @@ function selectSessionsToDelete(sessions, opts) {
|
|
|
5620
5948
|
);
|
|
5621
5949
|
}
|
|
5622
5950
|
var DEFAULT_INTERVAL = "1h";
|
|
5623
|
-
function
|
|
5951
|
+
function resolve2(flag, envValue, fallback) {
|
|
5624
5952
|
return flag ?? envValue ?? fallback;
|
|
5625
5953
|
}
|
|
5626
5954
|
function parseMaxCount(input) {
|
|
@@ -5636,9 +5964,9 @@ function parseMaxCount(input) {
|
|
|
5636
5964
|
}
|
|
5637
5965
|
function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
5638
5966
|
const warnings = [];
|
|
5639
|
-
const maxAgeRaw =
|
|
5640
|
-
const maxCountRaw =
|
|
5641
|
-
const intervalRaw =
|
|
5967
|
+
const maxAgeRaw = resolve2(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
|
|
5968
|
+
const maxCountRaw = resolve2(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
|
|
5969
|
+
const intervalRaw = resolve2(
|
|
5642
5970
|
flags.interval,
|
|
5643
5971
|
env.EVIDENT_SESSION_CLEANUP_INTERVAL,
|
|
5644
5972
|
DEFAULT_INTERVAL
|
|
@@ -5678,10 +6006,10 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
|
5678
6006
|
|
|
5679
6007
|
// src/lib/opencode/session-db-size.ts
|
|
5680
6008
|
import { statSync as statSync4 } from "node:fs";
|
|
5681
|
-
import { join as
|
|
6009
|
+
import { join as join7 } from "node:path";
|
|
5682
6010
|
var LARGE_DB_THRESHOLD_BYTES = 268435456;
|
|
5683
6011
|
function statSessionDbBytes(homeDir) {
|
|
5684
|
-
const dbPath =
|
|
6012
|
+
const dbPath = join7(homeDir, ".local", "share", "opencode", "opencode.db");
|
|
5685
6013
|
try {
|
|
5686
6014
|
return statSync4(dbPath).size;
|
|
5687
6015
|
} catch (err) {
|
|
@@ -5711,12 +6039,12 @@ function buildSessionStoreSizeWarning(input) {
|
|
|
5711
6039
|
// src/lib/opencode/log-tail.ts
|
|
5712
6040
|
import { statSync as statSync5 } from "node:fs";
|
|
5713
6041
|
import { homedir as homedir5 } from "node:os";
|
|
5714
|
-
import { join as
|
|
6042
|
+
import { join as join8 } from "node:path";
|
|
5715
6043
|
import { open as open2, stat } from "node:fs/promises";
|
|
5716
6044
|
var DEFAULT_POLL_INTERVAL_MS = 1e3;
|
|
5717
6045
|
function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
|
|
5718
|
-
const dataDir = env.XDG_DATA_HOME ||
|
|
5719
|
-
return
|
|
6046
|
+
const dataDir = env.XDG_DATA_HOME || join8(homeDir, ".local", "share");
|
|
6047
|
+
return join8(dataDir, "opencode", "log", "opencode.log");
|
|
5720
6048
|
}
|
|
5721
6049
|
function isEnoent(error2) {
|
|
5722
6050
|
return error2?.code === "ENOENT";
|
|
@@ -5871,8 +6199,8 @@ var StreamForwarder = class {
|
|
|
5871
6199
|
pauseStream(sid, stream) {
|
|
5872
6200
|
if (!stream.paused) {
|
|
5873
6201
|
stream.paused = true;
|
|
5874
|
-
stream.pausePromise = new Promise((
|
|
5875
|
-
stream.resume =
|
|
6202
|
+
stream.pausePromise = new Promise((resolve5) => {
|
|
6203
|
+
stream.resume = resolve5;
|
|
5876
6204
|
});
|
|
5877
6205
|
}
|
|
5878
6206
|
if (stream.pauseTimer !== null) clearTimeout(stream.pauseTimer);
|
|
@@ -5939,12 +6267,12 @@ var StreamForwarder = class {
|
|
|
5939
6267
|
let endBody;
|
|
5940
6268
|
if (has_body) {
|
|
5941
6269
|
const chunks = [];
|
|
5942
|
-
bodyPromise = new Promise((
|
|
6270
|
+
bodyPromise = new Promise((resolve5) => {
|
|
5943
6271
|
pushBody = (buf) => {
|
|
5944
6272
|
chunks.push(buf);
|
|
5945
6273
|
};
|
|
5946
6274
|
endBody = () => {
|
|
5947
|
-
|
|
6275
|
+
resolve5(Buffer.concat(chunks));
|
|
5948
6276
|
};
|
|
5949
6277
|
});
|
|
5950
6278
|
}
|
|
@@ -6115,7 +6443,7 @@ function connectTunnel(options) {
|
|
|
6115
6443
|
} = options;
|
|
6116
6444
|
const tunnelUrl = getTunnelUrlConfig();
|
|
6117
6445
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
6118
|
-
return new Promise((
|
|
6446
|
+
return new Promise((resolve5, reject) => {
|
|
6119
6447
|
const ws = new WebSocket2(url, {
|
|
6120
6448
|
headers: {
|
|
6121
6449
|
Authorization: authHeader,
|
|
@@ -6224,7 +6552,7 @@ function connectTunnel(options) {
|
|
|
6224
6552
|
forwarder.setBinaryFramesSupported(message.binary_frames === true);
|
|
6225
6553
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
6226
6554
|
onConnected?.(connectedAgentId);
|
|
6227
|
-
|
|
6555
|
+
resolve5({
|
|
6228
6556
|
ws,
|
|
6229
6557
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
6230
6558
|
});
|
|
@@ -6779,12 +7107,12 @@ function createSessionStoreHealth(options = {}) {
|
|
|
6779
7107
|
import { homedir as homedir6 } from "node:os";
|
|
6780
7108
|
|
|
6781
7109
|
// src/lib/runner-file-sync.ts
|
|
6782
|
-
import { join as
|
|
7110
|
+
import { join as join10 } from "node:path";
|
|
6783
7111
|
|
|
6784
7112
|
// src/lib/file-push.ts
|
|
6785
7113
|
import { randomUUID } from "node:crypto";
|
|
6786
7114
|
import { chmod, mkdir, open as open3, realpath, rename, unlink } from "node:fs/promises";
|
|
6787
|
-
import { basename, dirname as
|
|
7115
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute2, join as join9, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
|
|
6788
7116
|
var FILE_MODE = 384;
|
|
6789
7117
|
var DIRECTORY_MODE = 448;
|
|
6790
7118
|
async function writePushedFile(request2) {
|
|
@@ -6815,9 +7143,9 @@ async function writePushedFile(request2) {
|
|
|
6815
7143
|
}
|
|
6816
7144
|
try {
|
|
6817
7145
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
6818
|
-
|
|
7146
|
+
dirname6(candidate)
|
|
6819
7147
|
);
|
|
6820
|
-
const realTarget =
|
|
7148
|
+
const realTarget = join9(existingAncestor, ...missingSegments, basename2(candidate));
|
|
6821
7149
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
6822
7150
|
if (allowedDirectory === null) {
|
|
6823
7151
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -6827,8 +7155,8 @@ async function writePushedFile(request2) {
|
|
|
6827
7155
|
}
|
|
6828
7156
|
if (missingSegments.length > 0) {
|
|
6829
7157
|
await createMissingDirectories(existingAncestor, missingSegments);
|
|
6830
|
-
const realParent = await realpath(
|
|
6831
|
-
if (realParent !==
|
|
7158
|
+
const realParent = await realpath(dirname6(realTarget));
|
|
7159
|
+
if (realParent !== dirname6(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
6832
7160
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
6833
7161
|
path: realTarget,
|
|
6834
7162
|
bytes,
|
|
@@ -6853,15 +7181,15 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
6853
7181
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
6854
7182
|
return null;
|
|
6855
7183
|
}
|
|
6856
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
7184
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join9(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
6857
7185
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
6858
7186
|
return null;
|
|
6859
7187
|
}
|
|
6860
|
-
if (!
|
|
7188
|
+
if (!isAbsolute2(expanded)) {
|
|
6861
7189
|
return null;
|
|
6862
7190
|
}
|
|
6863
|
-
const candidate =
|
|
6864
|
-
const name =
|
|
7191
|
+
const candidate = resolve3(expanded);
|
|
7192
|
+
const name = basename2(candidate);
|
|
6865
7193
|
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
6866
7194
|
}
|
|
6867
7195
|
async function resolveNearestExistingAncestor(directory) {
|
|
@@ -6871,18 +7199,18 @@ async function resolveNearestExistingAncestor(directory) {
|
|
|
6871
7199
|
try {
|
|
6872
7200
|
return { existingAncestor: await realpath(current), missingSegments };
|
|
6873
7201
|
} catch (err) {
|
|
6874
|
-
const parent =
|
|
7202
|
+
const parent = dirname6(current);
|
|
6875
7203
|
if (err.code !== "ENOENT" || parent === current) {
|
|
6876
7204
|
throw err;
|
|
6877
7205
|
}
|
|
6878
|
-
missingSegments.unshift(
|
|
7206
|
+
missingSegments.unshift(basename2(current));
|
|
6879
7207
|
current = parent;
|
|
6880
7208
|
}
|
|
6881
7209
|
}
|
|
6882
7210
|
}
|
|
6883
7211
|
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
6884
7212
|
for (const directory of allowedDirectories) {
|
|
6885
|
-
if (!
|
|
7213
|
+
if (!isAbsolute2(directory)) {
|
|
6886
7214
|
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
6887
7215
|
continue;
|
|
6888
7216
|
}
|
|
@@ -6920,19 +7248,19 @@ async function realpathCreatingIfMissing(directory) {
|
|
|
6920
7248
|
}
|
|
6921
7249
|
}
|
|
6922
7250
|
function contains(realDirectory, realTarget) {
|
|
6923
|
-
const rel =
|
|
6924
|
-
return rel !== "" && rel !== ".." && !rel.startsWith(`..${
|
|
7251
|
+
const rel = relative2(realDirectory, realTarget);
|
|
7252
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
|
|
6925
7253
|
}
|
|
6926
7254
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
6927
7255
|
let current = existingAncestor;
|
|
6928
7256
|
for (const segment of missingSegments) {
|
|
6929
|
-
current =
|
|
7257
|
+
current = join9(current, segment);
|
|
6930
7258
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
6931
7259
|
await chmod(current, DIRECTORY_MODE);
|
|
6932
7260
|
}
|
|
6933
7261
|
}
|
|
6934
7262
|
async function writeAtomically(realTarget, content) {
|
|
6935
|
-
const temporaryPath =
|
|
7263
|
+
const temporaryPath = join9(dirname6(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
6936
7264
|
let handle;
|
|
6937
7265
|
try {
|
|
6938
7266
|
handle = await open3(temporaryPath, "wx", FILE_MODE);
|
|
@@ -7062,12 +7390,12 @@ var NOT_APPLIED = {
|
|
|
7062
7390
|
opencodeAuthApplied: false
|
|
7063
7391
|
};
|
|
7064
7392
|
function isClaudeCredentialPath(requestedPath, homeDir) {
|
|
7065
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
7066
|
-
return expanded ===
|
|
7393
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
7394
|
+
return expanded === join10(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
|
|
7067
7395
|
}
|
|
7068
7396
|
function isOpenCodeAuthPath(requestedPath, homeDir) {
|
|
7069
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
7070
|
-
return expanded ===
|
|
7397
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
7398
|
+
return expanded === join10(homeDir, ...OPENCODE_AUTH_SEGMENTS);
|
|
7071
7399
|
}
|
|
7072
7400
|
async function applyOne(options, file) {
|
|
7073
7401
|
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
@@ -7238,7 +7566,7 @@ var SESSION_ERROR_BUFFER_TTL_MS = SESSION_ERROR_STREAM_HEALTHY_MS;
|
|
|
7238
7566
|
var MAX_BUFFERED_SESSION_ERRORS = 256;
|
|
7239
7567
|
var SESSION_ERROR_RETENTION_TTL_MS = 6e4;
|
|
7240
7568
|
var SESSION_STORE_UNWRITABLE_ERROR = "The runner session database could not be written, so this turn did not finish. Nothing was lost from the queue. Clear disk space and retry.";
|
|
7241
|
-
var SESSION_ERROR_RETAINED_DETAIL = "
|
|
7569
|
+
var SESSION_ERROR_RETAINED_DETAIL = "Runner-observed OpenCode session error: ";
|
|
7242
7570
|
var SESSION_ERROR_OBSERVED_CAUSE = "Runner-observed OpenCode session-store cause: ";
|
|
7243
7571
|
var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
|
|
7244
7572
|
var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
@@ -9634,14 +9962,53 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9634
9962
|
conversation_id: watcher.conv.id,
|
|
9635
9963
|
message_id: inFlight.evidentMessageId
|
|
9636
9964
|
});
|
|
9637
|
-
|
|
9638
|
-
|
|
9639
|
-
inFlight.
|
|
9640
|
-
|
|
9641
|
-
|
|
9642
|
-
|
|
9965
|
+
const isMissingProvider = isProviderModelNotFoundError(event.reason);
|
|
9966
|
+
if (isMissingProvider) {
|
|
9967
|
+
const dispatchedModel = inFlight.message.opencode_model;
|
|
9968
|
+
const separator = dispatchedModel?.indexOf("/") ?? -1;
|
|
9969
|
+
const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
|
|
9970
|
+
await this.markFailed(
|
|
9971
|
+
watcher.conv.id,
|
|
9972
|
+
inFlight.evidentMessageId,
|
|
9973
|
+
event.sessionId,
|
|
9974
|
+
`OpenCode could not run this turn: ${event.reason}`,
|
|
9975
|
+
void 0,
|
|
9976
|
+
{
|
|
9977
|
+
classification: {
|
|
9978
|
+
kind: "model_auth",
|
|
9979
|
+
providerId: hasProviderAndModel ? dispatchedModel.slice(0, separator) : null,
|
|
9980
|
+
modelId: hasProviderAndModel ? dispatchedModel.slice(separator + 1) : null,
|
|
9981
|
+
reason: "missing"
|
|
9982
|
+
},
|
|
9983
|
+
errorShape: { name: null, statusCode: null }
|
|
9984
|
+
}
|
|
9985
|
+
);
|
|
9986
|
+
} else {
|
|
9987
|
+
await this.markFailed(
|
|
9988
|
+
watcher.conv.id,
|
|
9989
|
+
inFlight.evidentMessageId,
|
|
9990
|
+
event.sessionId,
|
|
9991
|
+
`OpenCode could not run this turn: ${event.reason}`
|
|
9992
|
+
);
|
|
9993
|
+
}
|
|
9643
9994
|
inFlight.done = true;
|
|
9644
9995
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
9996
|
+
if (isMissingProvider) {
|
|
9997
|
+
if (this.isV2) {
|
|
9998
|
+
void this.postSignal(
|
|
9999
|
+
watcher.conv.id,
|
|
10000
|
+
inFlight.evidentMessageId,
|
|
10001
|
+
"provider_registry_reload_unsupported"
|
|
10002
|
+
);
|
|
10003
|
+
} else {
|
|
10004
|
+
await reloadProviderCache(this.port, this.openCodeClient);
|
|
10005
|
+
void this.postSignal(
|
|
10006
|
+
watcher.conv.id,
|
|
10007
|
+
inFlight.evidentMessageId,
|
|
10008
|
+
"provider_registry_reload_issued"
|
|
10009
|
+
);
|
|
10010
|
+
}
|
|
10011
|
+
}
|
|
9645
10012
|
} catch (err) {
|
|
9646
10013
|
if (err instanceof ChannelAuthError) {
|
|
9647
10014
|
this.log({
|
|
@@ -9853,7 +10220,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9853
10220
|
if (!inFlight.done) {
|
|
9854
10221
|
const messageErrorText = messageError(messages, inFlight.opencodeMessageId);
|
|
9855
10222
|
const retainedReason = this.readRetainedSessionError(sessionId);
|
|
9856
|
-
const retainedError = retainedReason === null ? null : `${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}`;
|
|
10223
|
+
const retainedError = retainedReason === null || messageErrorText !== null && messageErrorText.includes(retainedReason) ? null : `${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}`;
|
|
9857
10224
|
const observedCause = this.sessionStoreHealth?.readCause(sessionId);
|
|
9858
10225
|
const causeError = observedCause === null || observedCause === void 0 ? null : `${SESSION_ERROR_OBSERVED_CAUSE}${observedCause}`;
|
|
9859
10226
|
const storeError = this.sessionStoreHealth?.isUnwritable() ? SESSION_STORE_UNWRITABLE_ERROR : null;
|
|
@@ -11562,14 +11929,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
11562
11929
|
const fetchChildWithoutBlocking = async (sessionId) => {
|
|
11563
11930
|
const pending = fetchChildMessages(sessionId);
|
|
11564
11931
|
let timer;
|
|
11565
|
-
const timeout = new Promise((
|
|
11932
|
+
const timeout = new Promise((resolve5) => {
|
|
11566
11933
|
timer = setTimeout(() => {
|
|
11567
11934
|
this.log({
|
|
11568
11935
|
level: "warn",
|
|
11569
11936
|
message: `Best-effort subagent session fetch for message ${messageId.slice(0, 8)} and child session ${sessionId.slice(0, 8)} was slow \u2014 omitting invocation telemetry without delaying completion`,
|
|
11570
11937
|
message_id: messageId
|
|
11571
11938
|
});
|
|
11572
|
-
|
|
11939
|
+
resolve5(null);
|
|
11573
11940
|
}, SUBAGENT_TELEMETRY_FETCH_TIMEOUT_MS);
|
|
11574
11941
|
});
|
|
11575
11942
|
try {
|
|
@@ -12208,11 +12575,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
12208
12575
|
if (subagentInvocations && subagentInvocations.length > 0) {
|
|
12209
12576
|
body.subagent_invocations = subagentInvocations;
|
|
12210
12577
|
}
|
|
12211
|
-
if (failure) {
|
|
12212
|
-
body.
|
|
12213
|
-
|
|
12214
|
-
|
|
12215
|
-
body.
|
|
12578
|
+
if (failure && failure.errorShape.name !== null) {
|
|
12579
|
+
body.failure_error_name = failure.errorShape.name;
|
|
12580
|
+
}
|
|
12581
|
+
if (failure && failure.errorShape.statusCode !== null) {
|
|
12582
|
+
body.failure_status_code = failure.errorShape.statusCode;
|
|
12583
|
+
}
|
|
12584
|
+
if (failure?.classification) {
|
|
12585
|
+
body.failure_kind = failure.classification.kind;
|
|
12586
|
+
body.failure_provider_id = failure.classification.providerId;
|
|
12587
|
+
body.failure_model_id = failure.classification.modelId;
|
|
12588
|
+
body.failure_reason = failure.classification.reason;
|
|
12216
12589
|
}
|
|
12217
12590
|
try {
|
|
12218
12591
|
await this.callWithRetry(
|
|
@@ -12233,27 +12606,28 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
12233
12606
|
this.clearSubagentInvocationCaches(messageId);
|
|
12234
12607
|
}
|
|
12235
12608
|
/**
|
|
12236
|
-
* Classify an errored turn
|
|
12609
|
+
* Classify an errored turn and extract its bounded error shape for `markFailed`.
|
|
12237
12610
|
*
|
|
12238
12611
|
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
12239
12612
|
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
12240
12613
|
* to the P1-2b zero-provider check — one extra loopback call to
|
|
12241
12614
|
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
12242
12615
|
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
12243
|
-
* (`null`/indeterminate) leaves the classification `null
|
|
12244
|
-
*
|
|
12616
|
+
* (`null`/indeterminate) leaves the classification `null`; the raw error shape
|
|
12617
|
+
* is still retained for diagnostics.
|
|
12245
12618
|
*/
|
|
12246
12619
|
async classifyModelAuthFailure(messages, userMessageId) {
|
|
12247
|
-
const classified = messageFailure(messages, userMessageId);
|
|
12248
|
-
if (classified != null) return classified;
|
|
12249
12620
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
12250
|
-
const
|
|
12251
|
-
|
|
12621
|
+
const errorShape = extractReplyErrorShape(reply);
|
|
12622
|
+
const classified = messageFailure(messages, userMessageId);
|
|
12623
|
+
if (classified != null) return { classification: classified, errorShape };
|
|
12624
|
+
const classification = applyZeroProviderFallback(
|
|
12252
12625
|
classified,
|
|
12253
|
-
|
|
12626
|
+
await this.hasAnyConfiguredProvider(),
|
|
12254
12627
|
reply?.info?.providerID ?? null,
|
|
12255
12628
|
reply?.info?.modelID ?? null
|
|
12256
12629
|
);
|
|
12630
|
+
return { classification, errorShape };
|
|
12257
12631
|
}
|
|
12258
12632
|
async recordSubagentModelAuthFailure(failure, conversationId, messageId) {
|
|
12259
12633
|
const providerId = failure.providerId ?? "(unknown)";
|
|
@@ -12811,7 +13185,7 @@ function commandError2(result) {
|
|
|
12811
13185
|
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
12812
13186
|
}
|
|
12813
13187
|
var runCommand2 = (command, args, opts) => {
|
|
12814
|
-
return new Promise((
|
|
13188
|
+
return new Promise((resolve5) => {
|
|
12815
13189
|
let child;
|
|
12816
13190
|
let stdout = "";
|
|
12817
13191
|
let stderr = "";
|
|
@@ -12821,7 +13195,7 @@ var runCommand2 = (command, args, opts) => {
|
|
|
12821
13195
|
if (settled) return;
|
|
12822
13196
|
settled = true;
|
|
12823
13197
|
if (timer.handle) clearTimeout(timer.handle);
|
|
12824
|
-
|
|
13198
|
+
resolve5(result);
|
|
12825
13199
|
};
|
|
12826
13200
|
try {
|
|
12827
13201
|
child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -13077,7 +13451,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
|
|
|
13077
13451
|
// src/lib/opencode/config-overlay.ts
|
|
13078
13452
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
13079
13453
|
import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
|
|
13080
|
-
import { isAbsolute as
|
|
13454
|
+
import { isAbsolute as isAbsolute3, join as join11, resolve as resolve4 } from "node:path";
|
|
13081
13455
|
function isFile(filePath) {
|
|
13082
13456
|
return existsSync2(filePath) && statSync6(filePath).isFile();
|
|
13083
13457
|
}
|
|
@@ -13090,8 +13464,8 @@ function applyRunnerOpenCodeConfig({
|
|
|
13090
13464
|
log3("runner OpenCode config is not configured; using the baked project config", "debug");
|
|
13091
13465
|
return;
|
|
13092
13466
|
}
|
|
13093
|
-
const source =
|
|
13094
|
-
const target = isFile(
|
|
13467
|
+
const source = isAbsolute3(overlayPath) ? overlayPath : resolve4(cwd, overlayPath);
|
|
13468
|
+
const target = isFile(join11(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
|
|
13095
13469
|
if (!isFile(source)) {
|
|
13096
13470
|
log3(
|
|
13097
13471
|
`RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
|
|
@@ -13099,7 +13473,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
13099
13473
|
);
|
|
13100
13474
|
return;
|
|
13101
13475
|
}
|
|
13102
|
-
copyFileSync(source,
|
|
13476
|
+
copyFileSync(source, join11(cwd, target));
|
|
13103
13477
|
try {
|
|
13104
13478
|
execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
|
|
13105
13479
|
stdio: "ignore"
|
|
@@ -13108,7 +13482,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
13108
13482
|
const detail = error2 instanceof Error ? error2.message : String(error2);
|
|
13109
13483
|
log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
|
|
13110
13484
|
}
|
|
13111
|
-
log3(`Applied runner OpenCode config ${source} to ${
|
|
13485
|
+
log3(`Applied runner OpenCode config ${source} to ${join11(cwd, target)}`);
|
|
13112
13486
|
}
|
|
13113
13487
|
|
|
13114
13488
|
// src/lib/credential-sync.ts
|
|
@@ -13126,14 +13500,14 @@ function errorMessage2(error2) {
|
|
|
13126
13500
|
return error2 instanceof Error ? error2.message : String(error2);
|
|
13127
13501
|
}
|
|
13128
13502
|
function waitForSettlement(promise, timeoutMs) {
|
|
13129
|
-
return new Promise((
|
|
13503
|
+
return new Promise((resolve5) => {
|
|
13130
13504
|
let settled = false;
|
|
13131
13505
|
const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
|
|
13132
13506
|
const finish = (value) => {
|
|
13133
13507
|
if (settled) return;
|
|
13134
13508
|
settled = true;
|
|
13135
13509
|
clearTimeout(timer);
|
|
13136
|
-
|
|
13510
|
+
resolve5(value);
|
|
13137
13511
|
};
|
|
13138
13512
|
promise.then(
|
|
13139
13513
|
() => finish(true),
|
|
@@ -13384,8 +13758,8 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
13384
13758
|
if (trimmed === "") {
|
|
13385
13759
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
13386
13760
|
}
|
|
13387
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
13388
|
-
if (!
|
|
13761
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join12(homeDir, trimmed.slice(2)) : trimmed;
|
|
13762
|
+
if (!isAbsolute4(expanded)) {
|
|
13389
13763
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
13390
13764
|
}
|
|
13391
13765
|
const normalized = resolvePath2(expanded);
|
|
@@ -13485,8 +13859,7 @@ function resolveMaxActiveSessions(options, env = process.env) {
|
|
|
13485
13859
|
function meetsThreshold(state, level) {
|
|
13486
13860
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
13487
13861
|
}
|
|
13488
|
-
function
|
|
13489
|
-
if (!meetsThreshold(state, level)) return;
|
|
13862
|
+
function writeConsoleLog(state, message, level) {
|
|
13490
13863
|
if (state.json) {
|
|
13491
13864
|
console.log(
|
|
13492
13865
|
JSON.stringify({
|
|
@@ -13495,10 +13868,18 @@ function log2(state, message, level = "info") {
|
|
|
13495
13868
|
message
|
|
13496
13869
|
})
|
|
13497
13870
|
);
|
|
13498
|
-
|
|
13499
|
-
const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
|
|
13500
|
-
console.log(`${prefix} ${message}`);
|
|
13871
|
+
return;
|
|
13501
13872
|
}
|
|
13873
|
+
const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
|
|
13874
|
+
console.log(`${prefix} ${message}`);
|
|
13875
|
+
}
|
|
13876
|
+
function log2(state, message, level = "info") {
|
|
13877
|
+
if (!meetsThreshold(state, level)) return;
|
|
13878
|
+
if (state.json || !state.interactive) writeConsoleLog(state, message, level);
|
|
13879
|
+
}
|
|
13880
|
+
function logLocalOnly(state, message, level = "info") {
|
|
13881
|
+
if (!meetsThreshold(state, level)) return;
|
|
13882
|
+
writeConsoleLog(state, message, level);
|
|
13502
13883
|
}
|
|
13503
13884
|
function logActivity(state, entry) {
|
|
13504
13885
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
@@ -13699,6 +14080,8 @@ async function driveChannels(state, driver) {
|
|
|
13699
14080
|
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
13700
14081
|
let lastSeenClaudeApplies = driver.fileSyncActivity().claudeCredentialApplies;
|
|
13701
14082
|
let lastSeenOpencodeAuthApplies = driver.fileSyncActivity().opencodeAuthApplyCount;
|
|
14083
|
+
const stayAwakeHolds = () => state.stayAwakeUntilMs !== null && Date.now() < state.stayAwakeUntilMs;
|
|
14084
|
+
let stayAwakeSuppressionLogged = false;
|
|
13702
14085
|
while (state.running) {
|
|
13703
14086
|
const cycleStartedAtMs = performance.now();
|
|
13704
14087
|
let idleThisCycle = false;
|
|
@@ -13800,7 +14183,7 @@ async function driveChannels(state, driver) {
|
|
|
13800
14183
|
}
|
|
13801
14184
|
}
|
|
13802
14185
|
}
|
|
13803
|
-
await new Promise((
|
|
14186
|
+
await new Promise((resolve5) => setTimeout(resolve5, CHANNEL_POLL_INTERVAL_MS));
|
|
13804
14187
|
const cycleMs = performance.now() - cycleStartedAtMs;
|
|
13805
14188
|
if (idleThisCycle) idleMs += cycleMs;
|
|
13806
14189
|
if (unreachableThisCycle) unreachableMs += cycleMs;
|
|
@@ -13813,11 +14196,20 @@ async function driveChannels(state, driver) {
|
|
|
13813
14196
|
if (state.interactive) displayStatus(state);
|
|
13814
14197
|
break;
|
|
13815
14198
|
}
|
|
13816
|
-
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3) {
|
|
14199
|
+
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
|
|
13817
14200
|
logActivity(state, { type: "info", message: "Idle timeout reached" });
|
|
13818
14201
|
if (state.interactive) displayStatus(state);
|
|
13819
14202
|
break;
|
|
13820
14203
|
}
|
|
14204
|
+
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && stayAwakeHolds()) {
|
|
14205
|
+
if (!stayAwakeSuppressionLogged) {
|
|
14206
|
+
stayAwakeSuppressionLogged = true;
|
|
14207
|
+
logActivity(state, {
|
|
14208
|
+
type: "info",
|
|
14209
|
+
message: "Idle, but staying awake until the requested minimum passes"
|
|
14210
|
+
});
|
|
14211
|
+
}
|
|
14212
|
+
}
|
|
13821
14213
|
}
|
|
13822
14214
|
}
|
|
13823
14215
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
@@ -13835,7 +14227,7 @@ function shouldWarnForReclaimSkip(reason) {
|
|
|
13835
14227
|
return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
|
|
13836
14228
|
}
|
|
13837
14229
|
function sessionDbPath() {
|
|
13838
|
-
return
|
|
14230
|
+
return join12(homedir7(), ".local", "share", "opencode", "opencode.db");
|
|
13839
14231
|
}
|
|
13840
14232
|
function logSessionCleanupActivity(state, phase, entry) {
|
|
13841
14233
|
logActivity(state, {
|
|
@@ -14146,10 +14538,12 @@ function scheduleUsageReporting(state, params) {
|
|
|
14146
14538
|
let phase = "dormant";
|
|
14147
14539
|
let rearmRequested = false;
|
|
14148
14540
|
const armProbe = () => {
|
|
14541
|
+
if (!state.running) return;
|
|
14149
14542
|
phase = "probe-pending";
|
|
14150
14543
|
params.setTimer(setTimeout(() => void tick(true), params.firstDelayMs()));
|
|
14151
14544
|
};
|
|
14152
14545
|
const scheduleNextTick = () => {
|
|
14546
|
+
if (!state.running) return;
|
|
14153
14547
|
if (rearmRequested) {
|
|
14154
14548
|
rearmRequested = false;
|
|
14155
14549
|
armProbe();
|
|
@@ -14183,6 +14577,7 @@ function scheduleUsageReporting(state, params) {
|
|
|
14183
14577
|
phase = "tick-in-flight";
|
|
14184
14578
|
try {
|
|
14185
14579
|
const usage = await params.fetchUsage();
|
|
14580
|
+
if (!state.running) return;
|
|
14186
14581
|
const result = await params.report(usage);
|
|
14187
14582
|
if (result.ok) {
|
|
14188
14583
|
if (consecutiveFailures > 0) {
|
|
@@ -14321,6 +14716,7 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
14321
14716
|
message: lowDiskDecision.warning
|
|
14322
14717
|
});
|
|
14323
14718
|
}
|
|
14719
|
+
if (!state.running) return;
|
|
14324
14720
|
const result = await reportResourceUsage(state.agentId, state.authHeader, usage);
|
|
14325
14721
|
if (result.ok) {
|
|
14326
14722
|
if (consecutiveFailures > 0) {
|
|
@@ -14353,7 +14749,9 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
14353
14749
|
message: `Resource usage reporting failed: ${message}${failureStreakSuffix(consecutiveFailures)}`
|
|
14354
14750
|
});
|
|
14355
14751
|
} finally {
|
|
14356
|
-
state.
|
|
14752
|
+
if (state.running) {
|
|
14753
|
+
state.resourceUsageTimer = setTimeout(() => void tick(), usageReportDelayMs());
|
|
14754
|
+
}
|
|
14357
14755
|
}
|
|
14358
14756
|
};
|
|
14359
14757
|
state.resourceUsageTimer = setTimeout(() => void tick(), firstReportDelayMs());
|
|
@@ -14515,8 +14913,8 @@ async function beginGracefulShutdown(state, trigger) {
|
|
|
14515
14913
|
return true;
|
|
14516
14914
|
}
|
|
14517
14915
|
);
|
|
14518
|
-
const timedOut = new Promise((
|
|
14519
|
-
timer = setTimeout(() =>
|
|
14916
|
+
const timedOut = new Promise((resolve5) => {
|
|
14917
|
+
timer = setTimeout(() => resolve5(false), telemetryBudgetMs);
|
|
14520
14918
|
});
|
|
14521
14919
|
if (!await Promise.race([flushed, timedOut])) {
|
|
14522
14920
|
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
@@ -14556,6 +14954,8 @@ async function run(options) {
|
|
|
14556
14954
|
port: options.port ?? 4096,
|
|
14557
14955
|
conversationFilter: options.conversation ?? null,
|
|
14558
14956
|
idleTimeout: options.idleTimeout ?? null,
|
|
14957
|
+
stayAwakeSeconds: null,
|
|
14958
|
+
stayAwakeUntilMs: null,
|
|
14559
14959
|
json: options.json ?? false,
|
|
14560
14960
|
interactive,
|
|
14561
14961
|
logLevel,
|
|
@@ -14745,6 +15145,17 @@ async function run(options) {
|
|
|
14745
15145
|
}
|
|
14746
15146
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
14747
15147
|
state.agentName = validation.agent.name;
|
|
15148
|
+
const requestedStayAwakeSeconds = validation.agent?.wake_stay_awake_seconds;
|
|
15149
|
+
if (typeof requestedStayAwakeSeconds === "number" && Number.isFinite(requestedStayAwakeSeconds) && requestedStayAwakeSeconds > 0) {
|
|
15150
|
+
state.stayAwakeSeconds = requestedStayAwakeSeconds;
|
|
15151
|
+
} else if (requestedStayAwakeSeconds !== void 0 && requestedStayAwakeSeconds !== null) {
|
|
15152
|
+
state.stayAwakeSeconds = null;
|
|
15153
|
+
log2(
|
|
15154
|
+
state,
|
|
15155
|
+
`Ignoring invalid wake_stay_awake_seconds (type: ${typeof requestedStayAwakeSeconds})`,
|
|
15156
|
+
"warn"
|
|
15157
|
+
);
|
|
15158
|
+
}
|
|
14748
15159
|
const microvmId = process.env.MICROVM_ID?.trim();
|
|
14749
15160
|
if (microvmId) {
|
|
14750
15161
|
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
@@ -14804,6 +15215,17 @@ async function run(options) {
|
|
|
14804
15215
|
}
|
|
14805
15216
|
if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
|
|
14806
15217
|
state.credentialSync?.arm();
|
|
15218
|
+
const dependencyInstallDiagnosticReporter = createDependencyInstallDiagnosticReporter({
|
|
15219
|
+
context: {
|
|
15220
|
+
homeDir: homedir7(),
|
|
15221
|
+
cwd: process.cwd(),
|
|
15222
|
+
microvmId: process.env.MICROVM_ID?.trim(),
|
|
15223
|
+
euid: process.getuid?.(),
|
|
15224
|
+
egid: process.getgid?.()
|
|
15225
|
+
},
|
|
15226
|
+
emitEvent: (message) => logActivity(state, { type: "info", level: "warn", message }),
|
|
15227
|
+
emitLocal: (message) => logLocalOnly(state, message, "warn")
|
|
15228
|
+
});
|
|
14807
15229
|
const openCodeActivityForwarder = createOpenCodeActivityForwarder(
|
|
14808
15230
|
() => ({
|
|
14809
15231
|
agentId: state.agentId,
|
|
@@ -14814,7 +15236,8 @@ async function run(options) {
|
|
|
14814
15236
|
if (cause !== null && sessionId !== null) {
|
|
14815
15237
|
state.sessionStoreHealth.observeCause(sessionId, cause);
|
|
14816
15238
|
}
|
|
14817
|
-
}
|
|
15239
|
+
},
|
|
15240
|
+
dependencyInstallDiagnosticReporter
|
|
14818
15241
|
);
|
|
14819
15242
|
const openCodeLogTail = tailOpenCodeLogFile(
|
|
14820
15243
|
resolveOpenCodeLogPath(homedir7(), process.env),
|
|
@@ -15147,6 +15570,13 @@ async function run(options) {
|
|
|
15147
15570
|
type: "info",
|
|
15148
15571
|
message: connectionMessage
|
|
15149
15572
|
});
|
|
15573
|
+
if (!isReconnect && state.stayAwakeSeconds !== null && state.stayAwakeUntilMs === null) {
|
|
15574
|
+
state.stayAwakeUntilMs = Date.now() + state.stayAwakeSeconds * 1e3;
|
|
15575
|
+
logActivity(state, {
|
|
15576
|
+
type: "info",
|
|
15577
|
+
message: `Staying awake for at least ${state.stayAwakeSeconds}s as requested by the wake`
|
|
15578
|
+
});
|
|
15579
|
+
}
|
|
15150
15580
|
if (options.tunnelReadyFile) {
|
|
15151
15581
|
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
15152
15582
|
if (marker.ok) {
|
|
@@ -15281,6 +15711,7 @@ async function run(options) {
|
|
|
15281
15711
|
if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
|
|
15282
15712
|
throw error2;
|
|
15283
15713
|
}
|
|
15714
|
+
if (!state.running) return;
|
|
15284
15715
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
15285
15716
|
state.claudeUsageRearm = scheduleClaudeUsageReporting(state, options);
|
|
15286
15717
|
state.openaiUsageRearm = scheduleUsageReporting(state, {
|