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