@evident-ai/cli 3.1.1-dev.c64b404 → 3.1.1-dev.d5a7e80
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 +15 -11
- package/dist/index.js +867 -63
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -285,14 +285,14 @@ function blank() {
|
|
|
285
285
|
console.log();
|
|
286
286
|
}
|
|
287
287
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
288
|
-
return new Promise((
|
|
288
|
+
return new Promise((resolve3) => {
|
|
289
289
|
process.stdout.write(chalk.dim(prompt));
|
|
290
290
|
const handler = () => {
|
|
291
291
|
process.stdin.removeListener("data", handler);
|
|
292
292
|
process.stdin.setRawMode?.(false);
|
|
293
293
|
process.stdin.pause();
|
|
294
294
|
console.log();
|
|
295
|
-
|
|
295
|
+
resolve3();
|
|
296
296
|
};
|
|
297
297
|
if (process.stdin.isTTY) {
|
|
298
298
|
process.stdin.setRawMode?.(true);
|
|
@@ -302,7 +302,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
302
302
|
});
|
|
303
303
|
}
|
|
304
304
|
function sleep(ms) {
|
|
305
|
-
return new Promise((
|
|
305
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
306
306
|
}
|
|
307
307
|
|
|
308
308
|
// src/commands/login.ts
|
|
@@ -376,19 +376,19 @@ async function tokenLogin() {
|
|
|
376
376
|
console.log("Visit your Evident dashboard to generate a CLI token.");
|
|
377
377
|
blank();
|
|
378
378
|
process.stdout.write("Paste token: ");
|
|
379
|
-
const token = await new Promise((
|
|
379
|
+
const token = await new Promise((resolve3) => {
|
|
380
380
|
let data = "";
|
|
381
381
|
process.stdin.setEncoding("utf8");
|
|
382
382
|
process.stdin.on("data", (chunk) => {
|
|
383
383
|
data += chunk;
|
|
384
384
|
});
|
|
385
385
|
process.stdin.on("end", () => {
|
|
386
|
-
|
|
386
|
+
resolve3(data.trim());
|
|
387
387
|
});
|
|
388
388
|
if (process.stdin.isTTY) {
|
|
389
389
|
process.stdin.once("data", (chunk) => {
|
|
390
390
|
process.stdin.pause();
|
|
391
|
-
|
|
391
|
+
resolve3(chunk.toString().trim());
|
|
392
392
|
});
|
|
393
393
|
process.stdin.resume();
|
|
394
394
|
}
|
|
@@ -467,9 +467,9 @@ async function whoami() {
|
|
|
467
467
|
}
|
|
468
468
|
|
|
469
469
|
// src/commands/run.ts
|
|
470
|
+
import { homedir as homedir3 } from "os";
|
|
471
|
+
import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
|
|
470
472
|
import chalk6 from "chalk";
|
|
471
|
-
import ora3 from "ora";
|
|
472
|
-
import { select as select3 } from "@inquirer/prompts";
|
|
473
473
|
|
|
474
474
|
// ../../packages/types/src/telemetry/index.ts
|
|
475
475
|
var TelemetryEventTypes = {
|
|
@@ -485,6 +485,10 @@ var TelemetryEventTypes = {
|
|
|
485
485
|
var MAX_FRAME_BYTES = 256 * 1024;
|
|
486
486
|
var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
|
|
487
487
|
|
|
488
|
+
// ../../packages/types/src/runner-files.ts
|
|
489
|
+
var MAX_FILE_PUSH_BYTES = 64 * 1024;
|
|
490
|
+
var MAX_FILE_SYNC_DIRECTORIES = 16;
|
|
491
|
+
|
|
488
492
|
// ../../packages/types/src/logging/index.ts
|
|
489
493
|
var CORRELATION_ID_HEADER = "x-evident-correlation-id";
|
|
490
494
|
function log(level, event, fields) {
|
|
@@ -499,6 +503,12 @@ function log(level, event, fields) {
|
|
|
499
503
|
);
|
|
500
504
|
}
|
|
501
505
|
}
|
|
506
|
+
function errorFields(err) {
|
|
507
|
+
if (err instanceof Error) {
|
|
508
|
+
return { error: err.message, error_name: err.name };
|
|
509
|
+
}
|
|
510
|
+
return { error: String(err) };
|
|
511
|
+
}
|
|
502
512
|
function stripQuery(url) {
|
|
503
513
|
try {
|
|
504
514
|
return new URL(url).pathname;
|
|
@@ -508,6 +518,10 @@ function stripQuery(url) {
|
|
|
508
518
|
}
|
|
509
519
|
}
|
|
510
520
|
|
|
521
|
+
// src/commands/run.ts
|
|
522
|
+
import ora3 from "ora";
|
|
523
|
+
import { select as select3 } from "@inquirer/prompts";
|
|
524
|
+
|
|
511
525
|
// src/lib/telemetry.ts
|
|
512
526
|
var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
513
527
|
function getCliVersion() {
|
|
@@ -719,7 +733,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
719
733
|
if (health.healthy) {
|
|
720
734
|
return health;
|
|
721
735
|
}
|
|
722
|
-
await new Promise((
|
|
736
|
+
await new Promise((resolve3) => setTimeout(resolve3, 1e3));
|
|
723
737
|
}
|
|
724
738
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
725
739
|
}
|
|
@@ -734,7 +748,7 @@ function buildOpenCodeVersionWarning(version2) {
|
|
|
734
748
|
if (isQueueValidatedVersion(version2)) return null;
|
|
735
749
|
const detected = version2 ? `v${version2}` : "unknown";
|
|
736
750
|
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
737
|
-
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack
|
|
751
|
+
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
|
|
738
752
|
}
|
|
739
753
|
|
|
740
754
|
// src/lib/opencode/process.ts
|
|
@@ -1026,6 +1040,12 @@ async function promptOpenCodeInstall(interactive) {
|
|
|
1026
1040
|
return action;
|
|
1027
1041
|
}
|
|
1028
1042
|
|
|
1043
|
+
// src/lib/opencode/provider-check.ts
|
|
1044
|
+
function buildNoProviderWarning(hasProvider) {
|
|
1045
|
+
if (hasProvider !== false) return null;
|
|
1046
|
+
return "Warning: opencode has no authenticated model provider configured, so it won't be able to answer prompts. Run `opencode auth login` to set one up (see https://opencode.ai for details).";
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1029
1049
|
// src/lib/opencode/session.ts
|
|
1030
1050
|
function opencodeBase(port) {
|
|
1031
1051
|
return `http://127.0.0.1:${port}`;
|
|
@@ -1228,6 +1248,11 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
1228
1248
|
}
|
|
1229
1249
|
const entry = provider.models[modelId];
|
|
1230
1250
|
if (!entry || typeof entry !== "object") return null;
|
|
1251
|
+
if (entry.capabilities && typeof entry.capabilities === "object") {
|
|
1252
|
+
if (typeof entry.capabilities.attachment === "boolean") {
|
|
1253
|
+
return entry.capabilities.attachment;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1231
1256
|
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
1232
1257
|
} catch (err) {
|
|
1233
1258
|
console.error(
|
|
@@ -1256,6 +1281,16 @@ async function buildFileParts(attachments, capable) {
|
|
|
1256
1281
|
);
|
|
1257
1282
|
dataUrl = null;
|
|
1258
1283
|
}
|
|
1284
|
+
if (dataUrl !== null && typeof dataUrl === "object") {
|
|
1285
|
+
outcomes.push({
|
|
1286
|
+
index: a.index,
|
|
1287
|
+
mime: a.mime,
|
|
1288
|
+
filename: a.filename,
|
|
1289
|
+
status: "failed",
|
|
1290
|
+
reason: "needs_reauth"
|
|
1291
|
+
});
|
|
1292
|
+
continue;
|
|
1293
|
+
}
|
|
1259
1294
|
if (dataUrl == null) {
|
|
1260
1295
|
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1261
1296
|
continue;
|
|
@@ -1337,7 +1372,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
1337
1372
|
}
|
|
1338
1373
|
}
|
|
1339
1374
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
1340
|
-
await new Promise((
|
|
1375
|
+
await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
|
|
1341
1376
|
}
|
|
1342
1377
|
}
|
|
1343
1378
|
return null;
|
|
@@ -1484,6 +1519,37 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
|
1484
1519
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1485
1520
|
);
|
|
1486
1521
|
}
|
|
1522
|
+
async function hasAnyConfiguredProvider(port) {
|
|
1523
|
+
try {
|
|
1524
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1525
|
+
if (!res.ok) {
|
|
1526
|
+
console.error(
|
|
1527
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1528
|
+
);
|
|
1529
|
+
return null;
|
|
1530
|
+
}
|
|
1531
|
+
const body = await res.json();
|
|
1532
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1533
|
+
console.error(
|
|
1534
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
1535
|
+
);
|
|
1536
|
+
return null;
|
|
1537
|
+
}
|
|
1538
|
+
const defaults2 = body.default;
|
|
1539
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
1540
|
+
console.error(
|
|
1541
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
1542
|
+
);
|
|
1543
|
+
return null;
|
|
1544
|
+
}
|
|
1545
|
+
return Object.keys(defaults2).length > 0;
|
|
1546
|
+
} catch (err) {
|
|
1547
|
+
console.error(
|
|
1548
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1549
|
+
);
|
|
1550
|
+
return null;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1487
1553
|
|
|
1488
1554
|
// src/lib/opencode/session-cleanup.ts
|
|
1489
1555
|
var DURATION_UNIT_MS = {
|
|
@@ -1642,10 +1708,11 @@ var StreamForwarder = class {
|
|
|
1642
1708
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1643
1709
|
*/
|
|
1644
1710
|
abortAll() {
|
|
1645
|
-
for (const stream of this.inflight.
|
|
1711
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1646
1712
|
try {
|
|
1647
1713
|
stream.abort();
|
|
1648
|
-
} catch {
|
|
1714
|
+
} catch (err) {
|
|
1715
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1649
1716
|
}
|
|
1650
1717
|
}
|
|
1651
1718
|
this.inflight.clear();
|
|
@@ -1679,12 +1746,12 @@ var StreamForwarder = class {
|
|
|
1679
1746
|
let endBody;
|
|
1680
1747
|
if (has_body) {
|
|
1681
1748
|
const chunks = [];
|
|
1682
|
-
bodyPromise = new Promise((
|
|
1749
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1683
1750
|
pushBody = (buf) => {
|
|
1684
1751
|
chunks.push(buf);
|
|
1685
1752
|
};
|
|
1686
1753
|
endBody = () => {
|
|
1687
|
-
|
|
1754
|
+
resolve3(Buffer.concat(chunks));
|
|
1688
1755
|
};
|
|
1689
1756
|
});
|
|
1690
1757
|
}
|
|
@@ -1795,31 +1862,20 @@ function connectTunnel(options) {
|
|
|
1795
1862
|
onConnected,
|
|
1796
1863
|
onDisconnected,
|
|
1797
1864
|
onError,
|
|
1798
|
-
onRequest,
|
|
1799
1865
|
onResponse,
|
|
1800
1866
|
onInfo,
|
|
1801
1867
|
onDrainPing
|
|
1802
1868
|
} = options;
|
|
1803
1869
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1804
1870
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1805
|
-
return new Promise((
|
|
1871
|
+
return new Promise((resolve3, reject) => {
|
|
1806
1872
|
const ws = new WebSocket2(url, {
|
|
1807
1873
|
headers: {
|
|
1808
1874
|
Authorization: authHeader
|
|
1809
1875
|
}
|
|
1810
1876
|
});
|
|
1811
|
-
const streamStartTimes = /* @__PURE__ */ new Map();
|
|
1812
1877
|
const forwarder = new StreamForwarder(ws, port, {
|
|
1813
|
-
|
|
1814
|
-
if (path === TUNNEL_DRAIN_PING_PATH) return;
|
|
1815
|
-
streamStartTimes.set(sid, Date.now());
|
|
1816
|
-
onRequest?.(method, path, sid);
|
|
1817
|
-
},
|
|
1818
|
-
onHead: (sid, status) => {
|
|
1819
|
-
const startedAt = streamStartTimes.get(sid);
|
|
1820
|
-
streamStartTimes.delete(sid);
|
|
1821
|
-
onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
|
|
1822
|
-
},
|
|
1878
|
+
onHead: () => onResponse?.(),
|
|
1823
1879
|
onDrainPing: () => onDrainPing?.()
|
|
1824
1880
|
});
|
|
1825
1881
|
const connectionTimeout = setTimeout(() => {
|
|
@@ -1867,7 +1923,7 @@ function connectTunnel(options) {
|
|
|
1867
1923
|
clearTimeout(connectionTimeout);
|
|
1868
1924
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1869
1925
|
onConnected?.(connectedAgentId);
|
|
1870
|
-
|
|
1926
|
+
resolve3({
|
|
1871
1927
|
ws,
|
|
1872
1928
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1873
1929
|
});
|
|
@@ -1895,7 +1951,6 @@ function connectTunnel(options) {
|
|
|
1895
1951
|
ws.on("close", (code, reason) => {
|
|
1896
1952
|
const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
|
|
1897
1953
|
forwarder.abortAll();
|
|
1898
|
-
streamStartTimes.clear();
|
|
1899
1954
|
onDisconnected?.(code, reasonStr);
|
|
1900
1955
|
});
|
|
1901
1956
|
});
|
|
@@ -1930,7 +1985,11 @@ var RunnerConnection = class {
|
|
|
1930
1985
|
if (this.connection) {
|
|
1931
1986
|
try {
|
|
1932
1987
|
this.connection.close();
|
|
1933
|
-
} catch {
|
|
1988
|
+
} catch (err) {
|
|
1989
|
+
log("error", "runner_connection_close_failed", {
|
|
1990
|
+
agent_id: this.resolvedAgentId,
|
|
1991
|
+
...errorFields(err)
|
|
1992
|
+
});
|
|
1934
1993
|
}
|
|
1935
1994
|
this.connection = null;
|
|
1936
1995
|
}
|
|
@@ -1982,6 +2041,404 @@ var RunnerConnection = class {
|
|
|
1982
2041
|
}
|
|
1983
2042
|
};
|
|
1984
2043
|
|
|
2044
|
+
// src/lib/channels/driver.ts
|
|
2045
|
+
import { homedir as homedir2 } from "os";
|
|
2046
|
+
|
|
2047
|
+
// src/lib/file-push.ts
|
|
2048
|
+
import { randomUUID } from "crypto";
|
|
2049
|
+
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2050
|
+
import { basename, dirname, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
|
|
2051
|
+
var FILE_MODE = 384;
|
|
2052
|
+
var DIRECTORY_MODE = 448;
|
|
2053
|
+
async function writePushedFile(request) {
|
|
2054
|
+
const { requestedPath, content, allowedDirectories, homeDir } = request;
|
|
2055
|
+
const bytes = content.byteLength;
|
|
2056
|
+
if (allowedDirectories.length === 0) {
|
|
2057
|
+
return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
2058
|
+
path: requestedPath,
|
|
2059
|
+
bytes
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
2062
|
+
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
2063
|
+
return refuse(
|
|
2064
|
+
"file_too_large",
|
|
2065
|
+
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
2066
|
+
{
|
|
2067
|
+
path: requestedPath,
|
|
2068
|
+
bytes
|
|
2069
|
+
}
|
|
2070
|
+
);
|
|
2071
|
+
}
|
|
2072
|
+
const candidate = expandAndValidate(requestedPath, homeDir);
|
|
2073
|
+
if (candidate === null) {
|
|
2074
|
+
return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
2075
|
+
path: requestedPath,
|
|
2076
|
+
bytes
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
try {
|
|
2080
|
+
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2081
|
+
dirname(candidate)
|
|
2082
|
+
);
|
|
2083
|
+
const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
|
|
2084
|
+
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2085
|
+
if (allowedDirectory === null) {
|
|
2086
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2087
|
+
path: realTarget,
|
|
2088
|
+
bytes
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
2091
|
+
if (missingSegments.length > 0) {
|
|
2092
|
+
await createMissingDirectories(existingAncestor, missingSegments);
|
|
2093
|
+
const realParent = await realpath(dirname(realTarget));
|
|
2094
|
+
if (realParent !== dirname(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
2095
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2096
|
+
path: realTarget,
|
|
2097
|
+
bytes,
|
|
2098
|
+
reason: "parent_changed_after_create"
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
await writeAtomically(realTarget, content);
|
|
2103
|
+
log("info", "file_push_written", { path: realTarget, bytes });
|
|
2104
|
+
return { ok: true, path: realTarget };
|
|
2105
|
+
} catch (err) {
|
|
2106
|
+
const errno = err.code ?? "UNKNOWN";
|
|
2107
|
+
return refuse("write_failed", `The runner could not write the file (${errno}).`, {
|
|
2108
|
+
path: candidate,
|
|
2109
|
+
bytes,
|
|
2110
|
+
errno,
|
|
2111
|
+
...errorFields(err)
|
|
2112
|
+
});
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
function expandAndValidate(requestedPath, homeDir) {
|
|
2116
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2117
|
+
return null;
|
|
2118
|
+
}
|
|
2119
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2120
|
+
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2121
|
+
return null;
|
|
2122
|
+
}
|
|
2123
|
+
if (!isAbsolute(expanded)) {
|
|
2124
|
+
return null;
|
|
2125
|
+
}
|
|
2126
|
+
const candidate = resolve2(expanded);
|
|
2127
|
+
const name = basename(candidate);
|
|
2128
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
2129
|
+
}
|
|
2130
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
2131
|
+
const missingSegments = [];
|
|
2132
|
+
let current = directory;
|
|
2133
|
+
for (; ; ) {
|
|
2134
|
+
try {
|
|
2135
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
2136
|
+
} catch (err) {
|
|
2137
|
+
const parent = dirname(current);
|
|
2138
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
2139
|
+
throw err;
|
|
2140
|
+
}
|
|
2141
|
+
missingSegments.unshift(basename(current));
|
|
2142
|
+
current = parent;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
2147
|
+
for (const directory of allowedDirectories) {
|
|
2148
|
+
if (!isAbsolute(directory)) {
|
|
2149
|
+
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
2150
|
+
continue;
|
|
2151
|
+
}
|
|
2152
|
+
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
2153
|
+
if (realDirectory !== null && contains(realDirectory, realTarget)) {
|
|
2154
|
+
return realDirectory;
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
return null;
|
|
2158
|
+
}
|
|
2159
|
+
async function realpathCreatingIfMissing(directory) {
|
|
2160
|
+
try {
|
|
2161
|
+
return await realpath(directory);
|
|
2162
|
+
} catch (err) {
|
|
2163
|
+
if (err.code !== "ENOENT") {
|
|
2164
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2165
|
+
directory,
|
|
2166
|
+
reason: "unresolvable",
|
|
2167
|
+
...errorFields(err)
|
|
2168
|
+
});
|
|
2169
|
+
return null;
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
try {
|
|
2173
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
2174
|
+
await chmod(directory, DIRECTORY_MODE);
|
|
2175
|
+
return await realpath(directory);
|
|
2176
|
+
} catch (err) {
|
|
2177
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2178
|
+
directory,
|
|
2179
|
+
reason: "create_failed",
|
|
2180
|
+
...errorFields(err)
|
|
2181
|
+
});
|
|
2182
|
+
return null;
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
function contains(realDirectory, realTarget) {
|
|
2186
|
+
const rel = relative(realDirectory, realTarget);
|
|
2187
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
2188
|
+
}
|
|
2189
|
+
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2190
|
+
let current = existingAncestor;
|
|
2191
|
+
for (const segment of missingSegments) {
|
|
2192
|
+
current = join2(current, segment);
|
|
2193
|
+
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2194
|
+
await chmod(current, DIRECTORY_MODE);
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
async function writeAtomically(realTarget, content) {
|
|
2198
|
+
const temporaryPath = join2(dirname(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2199
|
+
let handle;
|
|
2200
|
+
try {
|
|
2201
|
+
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
2202
|
+
await handle.writeFile(content);
|
|
2203
|
+
await handle.chmod(FILE_MODE);
|
|
2204
|
+
await handle.close();
|
|
2205
|
+
handle = void 0;
|
|
2206
|
+
await rename(temporaryPath, realTarget);
|
|
2207
|
+
} catch (err) {
|
|
2208
|
+
await discardTemporaryFile(temporaryPath, handle);
|
|
2209
|
+
throw err;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
async function discardTemporaryFile(temporaryPath, handle) {
|
|
2213
|
+
try {
|
|
2214
|
+
await handle?.close();
|
|
2215
|
+
} catch (err) {
|
|
2216
|
+
log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2217
|
+
}
|
|
2218
|
+
try {
|
|
2219
|
+
await unlink(temporaryPath);
|
|
2220
|
+
} catch (err) {
|
|
2221
|
+
const errno = err.code;
|
|
2222
|
+
if (errno !== "ENOENT" && errno !== "ENOTDIR") {
|
|
2223
|
+
log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
function refuse(code, message, fields) {
|
|
2228
|
+
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
2229
|
+
return { ok: false, code, message };
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
// src/lib/runner-file-sync.ts
|
|
2233
|
+
var MAX_ACK_ATTEMPTS = 5;
|
|
2234
|
+
async function syncPendingRunnerFiles(options) {
|
|
2235
|
+
const pending = await listPendingFiles(options);
|
|
2236
|
+
const pendingIds = new Set(pending.map((file) => file.id));
|
|
2237
|
+
for (const id of options.ackFailures.keys()) {
|
|
2238
|
+
if (!pendingIds.has(id)) options.ackFailures.delete(id);
|
|
2239
|
+
}
|
|
2240
|
+
if (pending.length === 0) return 0;
|
|
2241
|
+
options.log({
|
|
2242
|
+
level: "info",
|
|
2243
|
+
message: `Runner file sync: ${pending.length} file(s) queued for this runner`
|
|
2244
|
+
});
|
|
2245
|
+
let applied = 0;
|
|
2246
|
+
for (const file of pending) {
|
|
2247
|
+
if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
|
|
2248
|
+
if (await applyOne(options, file)) applied += 1;
|
|
2249
|
+
}
|
|
2250
|
+
return applied;
|
|
2251
|
+
}
|
|
2252
|
+
async function listPendingFiles(options) {
|
|
2253
|
+
let res;
|
|
2254
|
+
try {
|
|
2255
|
+
res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
|
|
2256
|
+
headers: { Authorization: options.getAuthHeader() }
|
|
2257
|
+
});
|
|
2258
|
+
} catch (err) {
|
|
2259
|
+
options.log({
|
|
2260
|
+
level: "warn",
|
|
2261
|
+
message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
|
|
2262
|
+
});
|
|
2263
|
+
return [];
|
|
2264
|
+
}
|
|
2265
|
+
if (!res.ok) {
|
|
2266
|
+
options.log({
|
|
2267
|
+
level: res.status === 404 ? "debug" : "warn",
|
|
2268
|
+
message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2269
|
+
});
|
|
2270
|
+
return [];
|
|
2271
|
+
}
|
|
2272
|
+
let body;
|
|
2273
|
+
try {
|
|
2274
|
+
body = await res.json();
|
|
2275
|
+
} catch (err) {
|
|
2276
|
+
options.log({
|
|
2277
|
+
level: "warn",
|
|
2278
|
+
message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
|
|
2279
|
+
});
|
|
2280
|
+
return [];
|
|
2281
|
+
}
|
|
2282
|
+
if (!Array.isArray(body)) {
|
|
2283
|
+
options.log({
|
|
2284
|
+
level: "warn",
|
|
2285
|
+
message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
|
|
2286
|
+
});
|
|
2287
|
+
return [];
|
|
2288
|
+
}
|
|
2289
|
+
const files = [];
|
|
2290
|
+
for (const entry of body) {
|
|
2291
|
+
const file = asPendingFile(entry);
|
|
2292
|
+
if (file === null) {
|
|
2293
|
+
options.log({
|
|
2294
|
+
level: "warn",
|
|
2295
|
+
message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
|
|
2296
|
+
});
|
|
2297
|
+
continue;
|
|
2298
|
+
}
|
|
2299
|
+
files.push(file);
|
|
2300
|
+
}
|
|
2301
|
+
return files;
|
|
2302
|
+
}
|
|
2303
|
+
function asPendingFile(entry) {
|
|
2304
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
2305
|
+
const { id, path, size } = entry;
|
|
2306
|
+
if (typeof id !== "string" || id === "") return null;
|
|
2307
|
+
if (typeof path !== "string" || path === "") return null;
|
|
2308
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
|
|
2309
|
+
return { id, path, size };
|
|
2310
|
+
}
|
|
2311
|
+
async function applyOne(options, file) {
|
|
2312
|
+
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
2313
|
+
if (options.allowedDirectories.length === 0) {
|
|
2314
|
+
options.log({
|
|
2315
|
+
level: "warn",
|
|
2316
|
+
message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
|
|
2317
|
+
});
|
|
2318
|
+
await ack(options, file, "rejected", "file_sync_disabled");
|
|
2319
|
+
return false;
|
|
2320
|
+
}
|
|
2321
|
+
if (file.size > MAX_FILE_PUSH_BYTES) {
|
|
2322
|
+
options.log({
|
|
2323
|
+
level: "warn",
|
|
2324
|
+
message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
|
|
2325
|
+
});
|
|
2326
|
+
await ack(options, file, "rejected", "file_too_large");
|
|
2327
|
+
return false;
|
|
2328
|
+
}
|
|
2329
|
+
const download = await downloadContent(options, file, label);
|
|
2330
|
+
if (!download.ok) {
|
|
2331
|
+
if (download.terminal) await ack(options, file, "rejected", download.code);
|
|
2332
|
+
return false;
|
|
2333
|
+
}
|
|
2334
|
+
let outcome;
|
|
2335
|
+
try {
|
|
2336
|
+
outcome = await writePushedFile({
|
|
2337
|
+
requestedPath: file.path,
|
|
2338
|
+
content: download.content,
|
|
2339
|
+
allowedDirectories: options.allowedDirectories,
|
|
2340
|
+
homeDir: options.homeDir
|
|
2341
|
+
});
|
|
2342
|
+
} catch (err) {
|
|
2343
|
+
options.log({
|
|
2344
|
+
level: "error",
|
|
2345
|
+
message: `Runner file ${label} could not be written: ${describe(err)}`
|
|
2346
|
+
});
|
|
2347
|
+
await ack(options, file, "rejected", "write_failed");
|
|
2348
|
+
return false;
|
|
2349
|
+
}
|
|
2350
|
+
if (!outcome.ok) {
|
|
2351
|
+
options.log({
|
|
2352
|
+
level: "warn",
|
|
2353
|
+
message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
|
|
2354
|
+
});
|
|
2355
|
+
await ack(options, file, "rejected", outcome.code);
|
|
2356
|
+
return false;
|
|
2357
|
+
}
|
|
2358
|
+
options.log({
|
|
2359
|
+
level: "info",
|
|
2360
|
+
message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
|
|
2361
|
+
});
|
|
2362
|
+
await ack(options, file, "applied");
|
|
2363
|
+
return true;
|
|
2364
|
+
}
|
|
2365
|
+
function durableDownloadCode(status) {
|
|
2366
|
+
return status === 413 ? "file_too_large" : "write_failed";
|
|
2367
|
+
}
|
|
2368
|
+
async function downloadContent(options, file, label) {
|
|
2369
|
+
try {
|
|
2370
|
+
const res = await options.fetchImpl(
|
|
2371
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
|
|
2372
|
+
{ headers: { Authorization: options.getAuthHeader() } }
|
|
2373
|
+
);
|
|
2374
|
+
if (!res.ok) {
|
|
2375
|
+
const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
|
|
2376
|
+
if (!terminal) {
|
|
2377
|
+
options.log({
|
|
2378
|
+
level: "warn",
|
|
2379
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2380
|
+
});
|
|
2381
|
+
return { ok: false, terminal: false };
|
|
2382
|
+
}
|
|
2383
|
+
const code = durableDownloadCode(res.status);
|
|
2384
|
+
options.log({
|
|
2385
|
+
level: "error",
|
|
2386
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
|
|
2387
|
+
});
|
|
2388
|
+
return { ok: false, terminal: true, code };
|
|
2389
|
+
}
|
|
2390
|
+
return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
|
|
2391
|
+
} catch (err) {
|
|
2392
|
+
options.log({
|
|
2393
|
+
level: "warn",
|
|
2394
|
+
message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
|
|
2395
|
+
});
|
|
2396
|
+
return { ok: false, terminal: false };
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
async function ack(options, file, status, reason) {
|
|
2400
|
+
const outcome = `${status}${reason ? ` (${reason})` : ""}`;
|
|
2401
|
+
try {
|
|
2402
|
+
const res = await options.fetchImpl(
|
|
2403
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
2404
|
+
{
|
|
2405
|
+
method: "POST",
|
|
2406
|
+
headers: {
|
|
2407
|
+
Authorization: options.getAuthHeader(),
|
|
2408
|
+
"Content-Type": "application/json"
|
|
2409
|
+
},
|
|
2410
|
+
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
2411
|
+
}
|
|
2412
|
+
);
|
|
2413
|
+
if (!res.ok) {
|
|
2414
|
+
recordAckFailure(
|
|
2415
|
+
options,
|
|
2416
|
+
file,
|
|
2417
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
|
|
2418
|
+
);
|
|
2419
|
+
return;
|
|
2420
|
+
}
|
|
2421
|
+
options.ackFailures.delete(file.id);
|
|
2422
|
+
} catch (err) {
|
|
2423
|
+
recordAckFailure(
|
|
2424
|
+
options,
|
|
2425
|
+
file,
|
|
2426
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
|
|
2427
|
+
);
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
function recordAckFailure(options, file, what) {
|
|
2431
|
+
const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
|
|
2432
|
+
options.ackFailures.set(file.id, attempts);
|
|
2433
|
+
options.log({
|
|
2434
|
+
level: "error",
|
|
2435
|
+
message: attempts >= MAX_ACK_ATTEMPTS ? `${what} \u2014 giving up after ${attempts} attempts. It stays pending until the server expires it; restart the runner to retry.` : `${what} \u2014 it stays pending until a later drain re-acks it (attempt ${attempts} of ${MAX_ACK_ATTEMPTS})`
|
|
2436
|
+
});
|
|
2437
|
+
}
|
|
2438
|
+
function describe(err) {
|
|
2439
|
+
return err instanceof Error ? err.message : String(err);
|
|
2440
|
+
}
|
|
2441
|
+
|
|
1985
2442
|
// src/lib/channels/driver.ts
|
|
1986
2443
|
function messageIdOf(m) {
|
|
1987
2444
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -2011,6 +2468,7 @@ var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
|
2011
2468
|
var HEARTBEAT_MS = 6e4;
|
|
2012
2469
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2013
2470
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2471
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
2014
2472
|
var ChannelAuthError = class extends Error {
|
|
2015
2473
|
constructor(message) {
|
|
2016
2474
|
super(message);
|
|
@@ -2033,7 +2491,7 @@ function backoffDelay(attempt, policy) {
|
|
|
2033
2491
|
function isRetryableStatus(status) {
|
|
2034
2492
|
return status === 429 || status >= 500 && status <= 599;
|
|
2035
2493
|
}
|
|
2036
|
-
var ChannelDriver = class {
|
|
2494
|
+
var ChannelDriver = class _ChannelDriver {
|
|
2037
2495
|
agentId;
|
|
2038
2496
|
port;
|
|
2039
2497
|
apiUrl;
|
|
@@ -2047,8 +2505,38 @@ var ChannelDriver = class {
|
|
|
2047
2505
|
pausedMaxWaitMs;
|
|
2048
2506
|
stuckQueuedMs;
|
|
2049
2507
|
now;
|
|
2508
|
+
fileSyncDirectories;
|
|
2509
|
+
homeDir;
|
|
2050
2510
|
/** Cache of conversationId → opencode sessionId. */
|
|
2051
2511
|
sessions = /* @__PURE__ */ new Map();
|
|
2512
|
+
/**
|
|
2513
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2514
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2515
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2516
|
+
* must bind a fresh one.
|
|
2517
|
+
*
|
|
2518
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2519
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2520
|
+
* the same session, and its watcher's routine status writes carry
|
|
2521
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2522
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2523
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2524
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2525
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2526
|
+
* is one we deliberately keep (see `markDone`).
|
|
2527
|
+
*
|
|
2528
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2529
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2530
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2531
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2532
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2533
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2534
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2535
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2536
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2537
|
+
* bounded cost.
|
|
2538
|
+
*/
|
|
2539
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
2052
2540
|
/**
|
|
2053
2541
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
2054
2542
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2158,9 +2646,12 @@ var ChannelDriver = class {
|
|
|
2158
2646
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2159
2647
|
/**
|
|
2160
2648
|
* Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
|
|
2161
|
-
* NON-EMPTY name is stored (terminal — a real session name
|
|
2162
|
-
* so we do NOT re-GET `/session/:id` every tick.
|
|
2163
|
-
*
|
|
2649
|
+
* NON-EMPTY, non-placeholder name is stored (terminal — a real session name
|
|
2650
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
|
|
2651
|
+
* excludes OpenCode's synchronous default title (see
|
|
2652
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
|
|
2653
|
+
* as an empty title so it never latches. A missing entry = not yet resolved OR
|
|
2654
|
+
* resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
|
|
2164
2655
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2165
2656
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2166
2657
|
* no watcher) can resolve the title.
|
|
@@ -2168,6 +2659,24 @@ var ChannelDriver = class {
|
|
|
2168
2659
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2169
2660
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2170
2661
|
draining = false;
|
|
2662
|
+
/**
|
|
2663
|
+
* Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
|
|
2664
|
+
* drain ping don't download, write and ack the same file twice.
|
|
2665
|
+
*/
|
|
2666
|
+
syncingFiles = false;
|
|
2667
|
+
/**
|
|
2668
|
+
* Consecutive failed acks per pending file (#559). Lives on the driver so it
|
|
2669
|
+
* survives across drains — without it, a file whose ack keeps failing is
|
|
2670
|
+
* re-downloaded and re-written every ~2s until the server expires it.
|
|
2671
|
+
*/
|
|
2672
|
+
fileAckFailures = /* @__PURE__ */ new Map();
|
|
2673
|
+
/**
|
|
2674
|
+
* Monotonic count of files this runner has pulled and written (#559). Only
|
|
2675
|
+
* ever increases, so `run.ts` detects work by comparing it against the value
|
|
2676
|
+
* it saw on the previous cycle — including work that landed mid-sleep, the
|
|
2677
|
+
* same trick `lastProxiedActivityAt` uses.
|
|
2678
|
+
*/
|
|
2679
|
+
appliedFileCount = 0;
|
|
2171
2680
|
/**
|
|
2172
2681
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2173
2682
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2198,6 +2707,8 @@ var ChannelDriver = class {
|
|
|
2198
2707
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2199
2708
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2200
2709
|
this.now = config2.now ?? (() => Date.now());
|
|
2710
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
2711
|
+
this.homeDir = config2.homeDir ?? homedir2();
|
|
2201
2712
|
}
|
|
2202
2713
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2203
2714
|
get opencodeBase() {
|
|
@@ -2225,6 +2736,47 @@ var ChannelDriver = class {
|
|
|
2225
2736
|
);
|
|
2226
2737
|
return run2;
|
|
2227
2738
|
}
|
|
2739
|
+
/**
|
|
2740
|
+
* Pull-and-apply any files Evident has queued for this runner (#559), riding
|
|
2741
|
+
* the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
|
|
2742
|
+
* and drain ping that call `drainPending()`. There is deliberately no channel,
|
|
2743
|
+
* control frame or poll loop of its own: worst-case latency is one poll tick.
|
|
2744
|
+
*
|
|
2745
|
+
* NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
|
|
2746
|
+
* cost a conversation turn. Failures are logged and either acked as a terminal
|
|
2747
|
+
* outcome or left pending for the next drain (see `runner-file-sync.ts`).
|
|
2748
|
+
*
|
|
2749
|
+
* Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
|
|
2750
|
+
*
|
|
2751
|
+
* @returns the number of files written to disk.
|
|
2752
|
+
*/
|
|
2753
|
+
async syncPendingFiles() {
|
|
2754
|
+
if (this.stopped) return 0;
|
|
2755
|
+
if (this.syncingFiles) return 0;
|
|
2756
|
+
this.syncingFiles = true;
|
|
2757
|
+
try {
|
|
2758
|
+
const applied = await syncPendingRunnerFiles({
|
|
2759
|
+
agentId: this.agentId,
|
|
2760
|
+
apiUrl: this.apiUrl,
|
|
2761
|
+
getAuthHeader: this.getAuthHeader,
|
|
2762
|
+
fetchImpl: this.fetchImpl,
|
|
2763
|
+
allowedDirectories: this.fileSyncDirectories,
|
|
2764
|
+
homeDir: this.homeDir,
|
|
2765
|
+
ackFailures: this.fileAckFailures,
|
|
2766
|
+
log: this.log
|
|
2767
|
+
});
|
|
2768
|
+
this.appliedFileCount += applied;
|
|
2769
|
+
return applied;
|
|
2770
|
+
} catch (err) {
|
|
2771
|
+
this.log({
|
|
2772
|
+
level: "error",
|
|
2773
|
+
message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
|
|
2774
|
+
});
|
|
2775
|
+
return 0;
|
|
2776
|
+
} finally {
|
|
2777
|
+
this.syncingFiles = false;
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2228
2780
|
async runDrain() {
|
|
2229
2781
|
let dispatched = 0;
|
|
2230
2782
|
try {
|
|
@@ -2258,6 +2810,28 @@ var ChannelDriver = class {
|
|
|
2258
2810
|
}
|
|
2259
2811
|
return false;
|
|
2260
2812
|
}
|
|
2813
|
+
/**
|
|
2814
|
+
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
2815
|
+
*
|
|
2816
|
+
* Pulling a file is real work that `drainPending()` knows nothing about, so
|
|
2817
|
+
* without this a near-idle runner counts a credential pull as an empty tick
|
|
2818
|
+
* and `--idle-timeout` can `process.exit` mid-pull — leaving a
|
|
2819
|
+
* `.evident-push-*.tmp` behind — or immediately after the write, before the
|
|
2820
|
+
* browser has run the authorize/callback that activates it (the user then sees
|
|
2821
|
+
* `saved_not_activated` for a runner that was fine).
|
|
2822
|
+
*
|
|
2823
|
+
* Two signals because one cannot cover both cases: `inFlight` is the pull
|
|
2824
|
+
* happening RIGHT NOW (it may outlive the tick that started it), and
|
|
2825
|
+
* `appliedFiles` is monotonic so a pull that started AND finished between two
|
|
2826
|
+
* idle checks still shows up as an advance.
|
|
2827
|
+
*
|
|
2828
|
+
* CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
|
|
2829
|
+
* the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
|
|
2830
|
+
* samples afterwards reads `true` every single cycle and can never idle out.
|
|
2831
|
+
*/
|
|
2832
|
+
fileSyncActivity() {
|
|
2833
|
+
return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
|
|
2834
|
+
}
|
|
2261
2835
|
/**
|
|
2262
2836
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2263
2837
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2319,7 +2893,7 @@ var ChannelDriver = class {
|
|
|
2319
2893
|
await this.sleep(step);
|
|
2320
2894
|
}
|
|
2321
2895
|
}
|
|
2322
|
-
while (this.hasInFlightWatchers()) {
|
|
2896
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2323
2897
|
if (this.now() >= deadline) return false;
|
|
2324
2898
|
await this.sleep(step);
|
|
2325
2899
|
}
|
|
@@ -2354,10 +2928,15 @@ var ChannelDriver = class {
|
|
|
2354
2928
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2355
2929
|
*/
|
|
2356
2930
|
async processConversation(conv) {
|
|
2357
|
-
const sessionId = await this.ensureSession(conv);
|
|
2931
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2358
2932
|
const messages = await this.getPendingMessages(conv.id);
|
|
2359
2933
|
let dispatched = 0;
|
|
2360
2934
|
let skippedAlreadyDispatched = 0;
|
|
2935
|
+
if (refusedSessionId && messages.length > 0) {
|
|
2936
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
2937
|
+
superseded_session_id: refusedSessionId
|
|
2938
|
+
});
|
|
2939
|
+
}
|
|
2361
2940
|
for (const message of messages) {
|
|
2362
2941
|
if (this.stopped) break;
|
|
2363
2942
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2384,7 +2963,8 @@ var ChannelDriver = class {
|
|
|
2384
2963
|
} catch (err) {
|
|
2385
2964
|
if (err instanceof ChannelAuthError) throw err;
|
|
2386
2965
|
this.dispatched.delete(message.id);
|
|
2387
|
-
|
|
2966
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
2967
|
+
if (exists === false) {
|
|
2388
2968
|
this.sessions.delete(conv.id);
|
|
2389
2969
|
this.log({
|
|
2390
2970
|
level: "warn",
|
|
@@ -2394,15 +2974,39 @@ var ChannelDriver = class {
|
|
|
2394
2974
|
});
|
|
2395
2975
|
break;
|
|
2396
2976
|
}
|
|
2397
|
-
|
|
2977
|
+
if (exists === null) {
|
|
2978
|
+
this.log({
|
|
2979
|
+
level: "warn",
|
|
2980
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed (opencode momentarily unreachable) \u2014 deferring this and later messages for conversation ${conv.id.slice(0, 8)} to the next tick rather than treating it as a genuine failure.`,
|
|
2981
|
+
conversation_id: conv.id,
|
|
2982
|
+
message_id: message.id
|
|
2983
|
+
});
|
|
2984
|
+
break;
|
|
2985
|
+
}
|
|
2986
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
2987
|
+
this.sessions.delete(conv.id);
|
|
2988
|
+
this.supersede(conv.id, sessionId);
|
|
2989
|
+
this.log({
|
|
2990
|
+
level: "warn",
|
|
2991
|
+
message: `Abandoning OpenCode session ${sessionId.slice(0, 8)} as the binding for conversation ${conv.id.slice(0, 8)} (it exists but failed to run a turn) \u2014 a fresh session is created on the next tick, whatever the persisted binding says by then.`,
|
|
2992
|
+
conversation_id: conv.id,
|
|
2993
|
+
message_id: message.id
|
|
2994
|
+
});
|
|
2995
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
2996
|
+
this.log({
|
|
2997
|
+
level: "warn",
|
|
2998
|
+
message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
2999
|
+
conversation_id: conv.id,
|
|
3000
|
+
message_id: message.id
|
|
3001
|
+
});
|
|
2398
3002
|
});
|
|
2399
3003
|
this.log({
|
|
2400
3004
|
level: "error",
|
|
2401
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3005
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2402
3006
|
conversation_id: conv.id,
|
|
2403
3007
|
message_id: message.id
|
|
2404
3008
|
});
|
|
2405
|
-
|
|
3009
|
+
break;
|
|
2406
3010
|
}
|
|
2407
3011
|
if (opencodeMessageId === null) {
|
|
2408
3012
|
this.log({
|
|
@@ -2428,8 +3032,42 @@ var ChannelDriver = class {
|
|
|
2428
3032
|
this.ensureWatcherRunning(sessionId);
|
|
2429
3033
|
return dispatched;
|
|
2430
3034
|
}
|
|
3035
|
+
/**
|
|
3036
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
3037
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
3038
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
3039
|
+
*/
|
|
3040
|
+
supersede(conversationId, sessionId) {
|
|
3041
|
+
this.supersededSessions.delete(conversationId);
|
|
3042
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
3043
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
3044
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
3045
|
+
if (oldest === void 0) return;
|
|
3046
|
+
this.supersededSessions.delete(oldest);
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
3050
|
+
isSuperseded(conversationId, sessionId) {
|
|
3051
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
3052
|
+
}
|
|
3053
|
+
/**
|
|
3054
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
3055
|
+
*
|
|
3056
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3057
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3058
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
3059
|
+
*/
|
|
2431
3060
|
async ensureSession(conv) {
|
|
2432
3061
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
3062
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
3063
|
+
this.log({
|
|
3064
|
+
level: "warn",
|
|
3065
|
+
message: `OpenCode session ${bound.slice(0, 8)} was abandoned for conversation ${conv.id.slice(0, 8)} after a failed dispatch but is still bound to it (the persisted id was written back by a turn already in flight) \u2014 ignoring it and binding a fresh session.`,
|
|
3066
|
+
conversation_id: conv.id
|
|
3067
|
+
});
|
|
3068
|
+
this.sessions.delete(conv.id);
|
|
3069
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
3070
|
+
}
|
|
2433
3071
|
if (bound) {
|
|
2434
3072
|
const exists = await sessionExists(this.port, bound);
|
|
2435
3073
|
if (exists === false) {
|
|
@@ -2439,12 +3077,12 @@ var ChannelDriver = class {
|
|
|
2439
3077
|
conversation_id: conv.id
|
|
2440
3078
|
});
|
|
2441
3079
|
this.sessions.delete(conv.id);
|
|
2442
|
-
return this.createAndBindSession(conv.id);
|
|
3080
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2443
3081
|
}
|
|
2444
3082
|
this.sessions.set(conv.id, bound);
|
|
2445
|
-
return bound;
|
|
3083
|
+
return { sessionId: bound };
|
|
2446
3084
|
}
|
|
2447
|
-
return this.createAndBindSession(conv.id);
|
|
3085
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2448
3086
|
}
|
|
2449
3087
|
/**
|
|
2450
3088
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2532,7 +3170,11 @@ var ChannelDriver = class {
|
|
|
2532
3170
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2533
3171
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2534
3172
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2535
|
-
*
|
|
3173
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
3174
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
3175
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
3176
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
3177
|
+
* logged with context (no silent swallow).
|
|
2536
3178
|
*/
|
|
2537
3179
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2538
3180
|
try {
|
|
@@ -2541,6 +3183,25 @@ var ChannelDriver = class {
|
|
|
2541
3183
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2542
3184
|
);
|
|
2543
3185
|
if (!res.ok) {
|
|
3186
|
+
let reason;
|
|
3187
|
+
try {
|
|
3188
|
+
const body = await res.json();
|
|
3189
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
3190
|
+
} catch (parseErr) {
|
|
3191
|
+
this.log({
|
|
3192
|
+
level: "debug",
|
|
3193
|
+
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index}: error body was not JSON (${parseErr instanceof Error ? parseErr.message : String(parseErr)}) \u2014 treating as a plain failure`,
|
|
3194
|
+
message_id: messageId
|
|
3195
|
+
});
|
|
3196
|
+
}
|
|
3197
|
+
if (reason === "needs_reauth") {
|
|
3198
|
+
this.log({
|
|
3199
|
+
level: "error",
|
|
3200
|
+
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 server confirmed a Slack reauth/scope problem \u2014 omitting this image (text turn proceeds)`,
|
|
3201
|
+
message_id: messageId
|
|
3202
|
+
});
|
|
3203
|
+
return { needsReauth: true };
|
|
3204
|
+
}
|
|
2544
3205
|
this.log({
|
|
2545
3206
|
level: "error",
|
|
2546
3207
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2580,6 +3241,9 @@ var ChannelDriver = class {
|
|
|
2580
3241
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2581
3242
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2582
3243
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
3244
|
+
const failedReason = outcomes.some(
|
|
3245
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
3246
|
+
) ? "needs_reauth" : void 0;
|
|
2583
3247
|
this.log({
|
|
2584
3248
|
level: "info",
|
|
2585
3249
|
message: `Message ${messageId.slice(0, 8)}: ${skipped} image(s) skipped (${capabilityUnknown ? "capability was unreadable \u2014 failed open to text-only" : "model not attachment-capable"}), ${failed} image(s) unavailable (deleted-at-source or fetch failure) \u2014 noting to Evident`,
|
|
@@ -2589,7 +3253,8 @@ var ChannelDriver = class {
|
|
|
2589
3253
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2590
3254
|
skipped,
|
|
2591
3255
|
failed,
|
|
2592
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3256
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3257
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2593
3258
|
});
|
|
2594
3259
|
}
|
|
2595
3260
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -3628,19 +4293,36 @@ var ChannelDriver = class {
|
|
|
3628
4293
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3629
4294
|
return parent;
|
|
3630
4295
|
}
|
|
4296
|
+
/**
|
|
4297
|
+
* OpenCode's synchronous default session title (e.g.
|
|
4298
|
+
* `"New session - 1737800000000"`), assigned immediately when a session is
|
|
4299
|
+
* created — before OpenCode's async LLM-based auto-titling later renames it
|
|
4300
|
+
* mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
|
|
4301
|
+
* timestamp suffix's exact format is deliberately NOT matched, since the prefix
|
|
4302
|
+
* alone is the stable, cheap signal and over-anchoring on the timestamp
|
|
4303
|
+
* representation risks silently breaking if OpenCode ever changes it. Accepted
|
|
4304
|
+
* trade-off: a genuine LLM-assigned title that happens to literally start with
|
|
4305
|
+
* this prefix would also fail to latch (see `resolveSessionTitle`) —
|
|
4306
|
+
* vanishingly unlikely in practice, and deliberately not engineered around.
|
|
4307
|
+
*/
|
|
4308
|
+
static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
|
|
3631
4309
|
/**
|
|
3632
4310
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3633
4311
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3634
4312
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3635
4313
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3636
4314
|
* Best-effort:
|
|
3637
|
-
* - a resolved NON-EMPTY title
|
|
4315
|
+
* - a resolved NON-EMPTY title that does NOT match
|
|
4316
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
|
|
3638
4317
|
* won't later un-name), so we do NOT re-GET `/session/:id` every tick;
|
|
3639
|
-
* - while the title is still absent
|
|
3640
|
-
*
|
|
3641
|
-
*
|
|
3642
|
-
*
|
|
3643
|
-
*
|
|
4318
|
+
* - while the title is still absent, empty, or matches the OpenCode
|
|
4319
|
+
* placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
|
|
4320
|
+
* asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
|
|
4321
|
+
* the cache unresolved and re-fetch on the next need so a later call (e.g. at
|
|
4322
|
+
* `done`) picks up the name assigned in the meantime. Such a call returns
|
|
4323
|
+
* `null` (omit the title on THIS PATCH) without caching. If a session is
|
|
4324
|
+
* never renamed, the title is omitted forever rather than ever persisting
|
|
4325
|
+
* the placeholder as a last resort;
|
|
3644
4326
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3645
4327
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3646
4328
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3653,7 +4335,7 @@ var ChannelDriver = class {
|
|
|
3653
4335
|
if (res.ok) {
|
|
3654
4336
|
const body = await res.json();
|
|
3655
4337
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3656
|
-
if (title.length > 0) {
|
|
4338
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3657
4339
|
this.sessionTitles.set(sessionId, title);
|
|
3658
4340
|
return title;
|
|
3659
4341
|
}
|
|
@@ -3859,6 +4541,32 @@ var ChannelDriver = class {
|
|
|
3859
4541
|
}
|
|
3860
4542
|
return messages;
|
|
3861
4543
|
}
|
|
4544
|
+
/**
|
|
4545
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
4546
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
4547
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
4548
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
4549
|
+
*
|
|
4550
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
4551
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
4552
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
4553
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
4554
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
4555
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
4556
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
4557
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
4558
|
+
* stick.
|
|
4559
|
+
*/
|
|
4560
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
4561
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
4562
|
+
this.log({
|
|
4563
|
+
level: "debug",
|
|
4564
|
+
message: `Omitting the abandoned OpenCode session ${sessionId.slice(0, 8)} from the '${status}' update for message ${messageId.slice(0, 8)} so it is not re-bound to conversation ${conversationId.slice(0, 8)}`,
|
|
4565
|
+
conversation_id: conversationId,
|
|
4566
|
+
message_id: messageId
|
|
4567
|
+
});
|
|
4568
|
+
return {};
|
|
4569
|
+
}
|
|
3862
4570
|
/**
|
|
3863
4571
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3864
4572
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3888,7 +4596,7 @@ var ChannelDriver = class {
|
|
|
3888
4596
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3889
4597
|
body: JSON.stringify({
|
|
3890
4598
|
status: "processing",
|
|
3891
|
-
|
|
4599
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3892
4600
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3893
4601
|
...title ? { title } : {}
|
|
3894
4602
|
})
|
|
@@ -3937,6 +4645,11 @@ var ChannelDriver = class {
|
|
|
3937
4645
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3938
4646
|
body: JSON.stringify({
|
|
3939
4647
|
status: "done",
|
|
4648
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
4649
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
4650
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
4651
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
4652
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3940
4653
|
opencode_session_id: sessionId,
|
|
3941
4654
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3942
4655
|
...title ? { title } : {},
|
|
@@ -3953,14 +4666,23 @@ var ChannelDriver = class {
|
|
|
3953
4666
|
}
|
|
3954
4667
|
/**
|
|
3955
4668
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3956
|
-
* when provided (issue #182)
|
|
3957
|
-
* `
|
|
3958
|
-
*
|
|
3959
|
-
*
|
|
4669
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
4670
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
4671
|
+
* session untouched (unused today; kept for API symmetry).
|
|
4672
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
4673
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
4674
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
4675
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
4676
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
4677
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
3960
4678
|
*/
|
|
3961
4679
|
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
3962
4680
|
const body = { status: "failed" };
|
|
3963
|
-
if (sessionId
|
|
4681
|
+
if (sessionId === null) {
|
|
4682
|
+
body.opencode_session_id = null;
|
|
4683
|
+
} else if (sessionId !== void 0) {
|
|
4684
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
4685
|
+
}
|
|
3964
4686
|
if (error2 !== void 0) body.error = error2;
|
|
3965
4687
|
if (usage) Object.assign(body, usage);
|
|
3966
4688
|
await this.callWithRetry(
|
|
@@ -4377,6 +5099,34 @@ function resolveLogLevel(options) {
|
|
|
4377
5099
|
}
|
|
4378
5100
|
return "info";
|
|
4379
5101
|
}
|
|
5102
|
+
function resolveFileSyncDirectories(raw, homeDir) {
|
|
5103
|
+
const directories = [];
|
|
5104
|
+
for (const entry of raw ?? []) {
|
|
5105
|
+
const trimmed = entry.trim();
|
|
5106
|
+
if (trimmed === "") {
|
|
5107
|
+
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5108
|
+
}
|
|
5109
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
|
|
5110
|
+
if (!isAbsolute2(expanded)) {
|
|
5111
|
+
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5112
|
+
}
|
|
5113
|
+
const normalized = resolvePath(expanded);
|
|
5114
|
+
if (parse(normalized).root === normalized) {
|
|
5115
|
+
throw new Error(
|
|
5116
|
+
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
5117
|
+
);
|
|
5118
|
+
}
|
|
5119
|
+
if (!directories.includes(normalized)) {
|
|
5120
|
+
directories.push(normalized);
|
|
5121
|
+
}
|
|
5122
|
+
}
|
|
5123
|
+
if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
|
|
5124
|
+
throw new Error(
|
|
5125
|
+
`--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
|
|
5126
|
+
);
|
|
5127
|
+
}
|
|
5128
|
+
return directories;
|
|
5129
|
+
}
|
|
4380
5130
|
function meetsThreshold(state, level) {
|
|
4381
5131
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4382
5132
|
}
|
|
@@ -4498,18 +5248,29 @@ async function handleAuthError(state, error2) {
|
|
|
4498
5248
|
async function driveChannels(state, driver) {
|
|
4499
5249
|
let idlePolls = 0;
|
|
4500
5250
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5251
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4501
5252
|
while (state.running) {
|
|
4502
5253
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4503
5254
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4504
5255
|
if (state.interactive) displayStatus(state);
|
|
4505
5256
|
await state.connection.reconnectPromise;
|
|
4506
5257
|
}
|
|
5258
|
+
const carriedOverFileSync = driver.fileSyncActivity().inFlight;
|
|
5259
|
+
void driver.syncPendingFiles().catch(
|
|
5260
|
+
(error2) => logActivity(state, {
|
|
5261
|
+
type: "error",
|
|
5262
|
+
error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5263
|
+
})
|
|
5264
|
+
);
|
|
4507
5265
|
try {
|
|
4508
5266
|
const processed = await driver.drainPending();
|
|
4509
5267
|
state.messageCount += processed;
|
|
4510
5268
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4511
5269
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4512
|
-
|
|
5270
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5271
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
5272
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
5273
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4513
5274
|
idlePolls = 0;
|
|
4514
5275
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4515
5276
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4538,7 +5299,7 @@ async function driveChannels(state, driver) {
|
|
|
4538
5299
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4539
5300
|
if (state.interactive) displayStatus(state);
|
|
4540
5301
|
}
|
|
4541
|
-
await new Promise((
|
|
5302
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4542
5303
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4543
5304
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4544
5305
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4683,8 +5444,10 @@ async function cleanup(state, opts = {}) {
|
|
|
4683
5444
|
async function run(options) {
|
|
4684
5445
|
const interactive = isInteractive(options.json);
|
|
4685
5446
|
let logLevel;
|
|
5447
|
+
let fileSyncDirectories;
|
|
4686
5448
|
try {
|
|
4687
5449
|
logLevel = resolveLogLevel(options);
|
|
5450
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
4688
5451
|
} catch (error2) {
|
|
4689
5452
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4690
5453
|
if (options.json) {
|
|
@@ -4719,6 +5482,11 @@ async function run(options) {
|
|
|
4719
5482
|
sessionCleanupTimers: [],
|
|
4720
5483
|
authHeader: ""
|
|
4721
5484
|
};
|
|
5485
|
+
if (fileSyncDirectories.length > 0) {
|
|
5486
|
+
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5487
|
+
} else {
|
|
5488
|
+
log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
|
|
5489
|
+
}
|
|
4722
5490
|
if (!options.runner && options.agent) {
|
|
4723
5491
|
telemetry.info(
|
|
4724
5492
|
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
@@ -4884,6 +5652,21 @@ async function run(options) {
|
|
|
4884
5652
|
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
4885
5653
|
}
|
|
4886
5654
|
}
|
|
5655
|
+
const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
|
|
5656
|
+
if (noProviderWarning) {
|
|
5657
|
+
log2(state, noProviderWarning, "warn");
|
|
5658
|
+
if (state.interactive && !state.json) {
|
|
5659
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
5660
|
+
blank();
|
|
5661
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
5662
|
+
console.log(
|
|
5663
|
+
chalk6.dim(
|
|
5664
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
5665
|
+
)
|
|
5666
|
+
);
|
|
5667
|
+
blank();
|
|
5668
|
+
}
|
|
5669
|
+
}
|
|
4887
5670
|
} catch (error2) {
|
|
4888
5671
|
ocSpinner?.fail(error2.message);
|
|
4889
5672
|
throw error2;
|
|
@@ -4896,6 +5679,10 @@ async function run(options) {
|
|
|
4896
5679
|
getAuthHeader: () => state.authHeader,
|
|
4897
5680
|
conversationFilter: state.conversationFilter,
|
|
4898
5681
|
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
5682
|
+
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
5683
|
+
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
5684
|
+
fileSyncDirectories,
|
|
5685
|
+
homeDir: homedir3(),
|
|
4899
5686
|
log: (entry) => (
|
|
4900
5687
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4901
5688
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4977,6 +5764,12 @@ async function run(options) {
|
|
|
4977
5764
|
onDrainPing: () => {
|
|
4978
5765
|
if (!state.running) return;
|
|
4979
5766
|
logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
|
|
5767
|
+
void channelDriver.syncPendingFiles().catch(
|
|
5768
|
+
(error2) => logActivity(state, {
|
|
5769
|
+
type: "error",
|
|
5770
|
+
error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5771
|
+
})
|
|
5772
|
+
);
|
|
4980
5773
|
channelDriver.drainPending().then((processed) => {
|
|
4981
5774
|
if (processed > 0) {
|
|
4982
5775
|
state.messageCount += processed;
|
|
@@ -5060,7 +5853,10 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
5060
5853
|
program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
|
|
5061
5854
|
program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
|
|
5062
5855
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
5063
|
-
program.command("run").description("Connect to Evident and process messages").option("
|
|
5856
|
+
program.command("run").description("Connect to Evident and process messages").option("--runner [id]", "Runner ID to connect to (optional when EVIDENT_RUNNER_KEY is set)").option(
|
|
5857
|
+
"-a, --agent [id]",
|
|
5858
|
+
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
5859
|
+
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
5064
5860
|
"--log-level <level>",
|
|
5065
5861
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
5066
5862
|
).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option("--json", "Output in JSON format").option(
|
|
@@ -5072,6 +5868,11 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5072
5868
|
).option(
|
|
5073
5869
|
"--session-cleanup-interval <duration>",
|
|
5074
5870
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
5871
|
+
).option(
|
|
5872
|
+
"--enable-file-sync-to <dir>",
|
|
5873
|
+
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
5874
|
+
(value, previous) => previous.concat([value]),
|
|
5875
|
+
[]
|
|
5075
5876
|
).action(
|
|
5076
5877
|
(options) => {
|
|
5077
5878
|
run({
|
|
@@ -5088,7 +5889,10 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5088
5889
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
5089
5890
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
5090
5891
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
5091
|
-
sessionCleanupInterval: options.sessionCleanupInterval
|
|
5892
|
+
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
5893
|
+
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
5894
|
+
// resolveFileSyncDirectories.
|
|
5895
|
+
enableFileSyncTo: options.enableFileSyncTo
|
|
5092
5896
|
});
|
|
5093
5897
|
}
|
|
5094
5898
|
);
|