@evident-ai/cli 3.1.1-dev.b860956 → 3.1.1-dev.be525f8
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 +22 -12
- package/dist/index.js +1155 -102
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -11,8 +11,8 @@ import chalk2 from "chalk";
|
|
|
11
11
|
|
|
12
12
|
// src/lib/config.ts
|
|
13
13
|
import Conf from "conf";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
14
|
+
import { chmodSync, existsSync, statSync } from "fs";
|
|
15
|
+
import { dirname } from "path";
|
|
16
16
|
var PRODUCTION_API_URL = "https://api.production.evident.run/v1";
|
|
17
17
|
var PRODUCTION_TUNNEL_URL = "wss://tunnel.production.evident.run";
|
|
18
18
|
var defaults = {
|
|
@@ -47,8 +47,35 @@ var credentials = new Conf({
|
|
|
47
47
|
projectName: "evident",
|
|
48
48
|
projectSuffix: "",
|
|
49
49
|
configName: "credentials",
|
|
50
|
-
defaults: {}
|
|
50
|
+
defaults: {},
|
|
51
|
+
configFileMode: 384
|
|
51
52
|
});
|
|
53
|
+
var CREDENTIALS_FILE_MODE = 384;
|
|
54
|
+
var CREDENTIALS_DIR_MODE = 448;
|
|
55
|
+
var permissionWarningEmitted = false;
|
|
56
|
+
function hardenCredentialsPermissions() {
|
|
57
|
+
if (process.platform === "win32") {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const file = credentials.path;
|
|
61
|
+
for (const [path, mode] of [
|
|
62
|
+
[file, CREDENTIALS_FILE_MODE],
|
|
63
|
+
[dirname(file), CREDENTIALS_DIR_MODE]
|
|
64
|
+
]) {
|
|
65
|
+
try {
|
|
66
|
+
if (existsSync(path) && (statSync(path).mode & 511) !== mode) {
|
|
67
|
+
chmodSync(path, mode);
|
|
68
|
+
}
|
|
69
|
+
} catch (err) {
|
|
70
|
+
if (!permissionWarningEmitted) {
|
|
71
|
+
permissionWarningEmitted = true;
|
|
72
|
+
console.error(
|
|
73
|
+
`[config] could not restrict permissions on ${path}; the credentials file may be readable by other users on this machine: ${err instanceof Error ? err.message : String(err)}`
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
52
79
|
function getApiUrlConfig() {
|
|
53
80
|
return getApiUrl();
|
|
54
81
|
}
|
|
@@ -59,6 +86,7 @@ function credentialsKey() {
|
|
|
59
86
|
return getApiUrl();
|
|
60
87
|
}
|
|
61
88
|
function getCredentials() {
|
|
89
|
+
hardenCredentialsPermissions();
|
|
62
90
|
const byEndpoint = credentials.get("byEndpoint") ?? {};
|
|
63
91
|
return byEndpoint[credentialsKey()] ?? {};
|
|
64
92
|
}
|
|
@@ -70,14 +98,17 @@ function setCredentials(creds) {
|
|
|
70
98
|
expiresAt: creds.expiresAt
|
|
71
99
|
};
|
|
72
100
|
credentials.set("byEndpoint", byEndpoint);
|
|
101
|
+
hardenCredentialsPermissions();
|
|
73
102
|
}
|
|
74
103
|
function clearCredentials() {
|
|
75
104
|
const byEndpoint = credentials.get("byEndpoint") ?? {};
|
|
76
105
|
delete byEndpoint[credentialsKey()];
|
|
77
106
|
credentials.set("byEndpoint", byEndpoint);
|
|
107
|
+
hardenCredentialsPermissions();
|
|
78
108
|
}
|
|
79
109
|
function clearAllCredentials() {
|
|
80
110
|
credentials.clear();
|
|
111
|
+
hardenCredentialsPermissions();
|
|
81
112
|
}
|
|
82
113
|
function getCliName() {
|
|
83
114
|
const argv1 = process.argv[1] || "";
|
|
@@ -285,14 +316,14 @@ function blank() {
|
|
|
285
316
|
console.log();
|
|
286
317
|
}
|
|
287
318
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
288
|
-
return new Promise((
|
|
319
|
+
return new Promise((resolve3) => {
|
|
289
320
|
process.stdout.write(chalk.dim(prompt));
|
|
290
321
|
const handler = () => {
|
|
291
322
|
process.stdin.removeListener("data", handler);
|
|
292
323
|
process.stdin.setRawMode?.(false);
|
|
293
324
|
process.stdin.pause();
|
|
294
325
|
console.log();
|
|
295
|
-
|
|
326
|
+
resolve3();
|
|
296
327
|
};
|
|
297
328
|
if (process.stdin.isTTY) {
|
|
298
329
|
process.stdin.setRawMode?.(true);
|
|
@@ -302,7 +333,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
302
333
|
});
|
|
303
334
|
}
|
|
304
335
|
function sleep(ms) {
|
|
305
|
-
return new Promise((
|
|
336
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
306
337
|
}
|
|
307
338
|
|
|
308
339
|
// src/commands/login.ts
|
|
@@ -373,22 +404,23 @@ async function deviceFlowLogin(options) {
|
|
|
373
404
|
}
|
|
374
405
|
async function tokenLogin() {
|
|
375
406
|
console.log("Token login mode.");
|
|
376
|
-
console.log("
|
|
407
|
+
console.log("Run `evident login` on a machine with a browser to get a token.");
|
|
408
|
+
console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
|
|
377
409
|
blank();
|
|
378
410
|
process.stdout.write("Paste token: ");
|
|
379
|
-
const token = await new Promise((
|
|
411
|
+
const token = await new Promise((resolve3) => {
|
|
380
412
|
let data = "";
|
|
381
413
|
process.stdin.setEncoding("utf8");
|
|
382
414
|
process.stdin.on("data", (chunk) => {
|
|
383
415
|
data += chunk;
|
|
384
416
|
});
|
|
385
417
|
process.stdin.on("end", () => {
|
|
386
|
-
|
|
418
|
+
resolve3(data.trim());
|
|
387
419
|
});
|
|
388
420
|
if (process.stdin.isTTY) {
|
|
389
421
|
process.stdin.once("data", (chunk) => {
|
|
390
422
|
process.stdin.pause();
|
|
391
|
-
|
|
423
|
+
resolve3(chunk.toString().trim());
|
|
392
424
|
});
|
|
393
425
|
process.stdin.resume();
|
|
394
426
|
}
|
|
@@ -467,9 +499,9 @@ async function whoami() {
|
|
|
467
499
|
}
|
|
468
500
|
|
|
469
501
|
// src/commands/run.ts
|
|
502
|
+
import { homedir as homedir2 } from "os";
|
|
503
|
+
import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
|
|
470
504
|
import chalk6 from "chalk";
|
|
471
|
-
import ora3 from "ora";
|
|
472
|
-
import { select as select3 } from "@inquirer/prompts";
|
|
473
505
|
|
|
474
506
|
// ../../packages/types/src/telemetry/index.ts
|
|
475
507
|
var TelemetryEventTypes = {
|
|
@@ -485,6 +517,10 @@ var TelemetryEventTypes = {
|
|
|
485
517
|
var MAX_FRAME_BYTES = 256 * 1024;
|
|
486
518
|
var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
|
|
487
519
|
|
|
520
|
+
// ../../packages/types/src/runner-files.ts
|
|
521
|
+
var MAX_FILE_PUSH_BYTES = 64 * 1024;
|
|
522
|
+
var MAX_FILE_SYNC_DIRECTORIES = 16;
|
|
523
|
+
|
|
488
524
|
// ../../packages/types/src/logging/index.ts
|
|
489
525
|
var CORRELATION_ID_HEADER = "x-evident-correlation-id";
|
|
490
526
|
function log(level, event, fields) {
|
|
@@ -499,6 +535,12 @@ function log(level, event, fields) {
|
|
|
499
535
|
);
|
|
500
536
|
}
|
|
501
537
|
}
|
|
538
|
+
function errorFields(err) {
|
|
539
|
+
if (err instanceof Error) {
|
|
540
|
+
return { error: err.message, error_name: err.name };
|
|
541
|
+
}
|
|
542
|
+
return { error: String(err) };
|
|
543
|
+
}
|
|
502
544
|
function stripQuery(url) {
|
|
503
545
|
try {
|
|
504
546
|
return new URL(url).pathname;
|
|
@@ -508,6 +550,10 @@ function stripQuery(url) {
|
|
|
508
550
|
}
|
|
509
551
|
}
|
|
510
552
|
|
|
553
|
+
// src/commands/run.ts
|
|
554
|
+
import ora3 from "ora";
|
|
555
|
+
import { select as select3 } from "@inquirer/prompts";
|
|
556
|
+
|
|
511
557
|
// src/lib/telemetry.ts
|
|
512
558
|
var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
513
559
|
function getCliVersion() {
|
|
@@ -645,14 +691,27 @@ var EventTypes = {
|
|
|
645
691
|
// CLI lifecycle
|
|
646
692
|
CLI_STARTED: "cli.started",
|
|
647
693
|
CLI_COMMAND: "cli.command",
|
|
648
|
-
CLI_ERROR: "cli.error"
|
|
694
|
+
CLI_ERROR: "cli.error",
|
|
695
|
+
// Deprecation telemetry (#412) — usage of the old `--agent`/`EVIDENT_AGENT_KEY`
|
|
696
|
+
// names instead of the preferred `--runner`/`EVIDENT_RUNNER_KEY` (#409).
|
|
697
|
+
DEPRECATED_AGENT_FLAG_USED: "cli.deprecated_agent_flag_used",
|
|
698
|
+
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
649
699
|
};
|
|
650
700
|
|
|
651
701
|
// src/lib/auth.ts
|
|
652
702
|
async function getAuthCredentials() {
|
|
703
|
+
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
653
704
|
const agentKey = process.env.EVIDENT_AGENT_KEY;
|
|
705
|
+
if (runnerKey) {
|
|
706
|
+
return {
|
|
707
|
+
token: runnerKey,
|
|
708
|
+
authType: "agent_key",
|
|
709
|
+
keySource: "runner_key",
|
|
710
|
+
notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
|
|
711
|
+
};
|
|
712
|
+
}
|
|
654
713
|
if (agentKey) {
|
|
655
|
-
return { token: agentKey, authType: "agent_key" };
|
|
714
|
+
return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
|
|
656
715
|
}
|
|
657
716
|
const userToken = process.env.EVIDENT_TOKEN;
|
|
658
717
|
if (userToken) {
|
|
@@ -706,7 +765,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
706
765
|
if (health.healthy) {
|
|
707
766
|
return health;
|
|
708
767
|
}
|
|
709
|
-
await new Promise((
|
|
768
|
+
await new Promise((resolve3) => setTimeout(resolve3, 1e3));
|
|
710
769
|
}
|
|
711
770
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
712
771
|
}
|
|
@@ -721,7 +780,7 @@ function buildOpenCodeVersionWarning(version2) {
|
|
|
721
780
|
if (isQueueValidatedVersion(version2)) return null;
|
|
722
781
|
const detected = version2 ? `v${version2}` : "unknown";
|
|
723
782
|
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
724
|
-
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack
|
|
783
|
+
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.`;
|
|
725
784
|
}
|
|
726
785
|
|
|
727
786
|
// src/lib/opencode/process.ts
|
|
@@ -1013,6 +1072,12 @@ async function promptOpenCodeInstall(interactive) {
|
|
|
1013
1072
|
return action;
|
|
1014
1073
|
}
|
|
1015
1074
|
|
|
1075
|
+
// src/lib/opencode/provider-check.ts
|
|
1076
|
+
function buildNoProviderWarning(hasProvider) {
|
|
1077
|
+
if (hasProvider !== false) return null;
|
|
1078
|
+
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).";
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1016
1081
|
// src/lib/opencode/session.ts
|
|
1017
1082
|
function opencodeBase(port) {
|
|
1018
1083
|
return `http://127.0.0.1:${port}`;
|
|
@@ -1215,6 +1280,11 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
1215
1280
|
}
|
|
1216
1281
|
const entry = provider.models[modelId];
|
|
1217
1282
|
if (!entry || typeof entry !== "object") return null;
|
|
1283
|
+
if (entry.capabilities && typeof entry.capabilities === "object") {
|
|
1284
|
+
if (typeof entry.capabilities.attachment === "boolean") {
|
|
1285
|
+
return entry.capabilities.attachment;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1218
1288
|
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
1219
1289
|
} catch (err) {
|
|
1220
1290
|
console.error(
|
|
@@ -1243,6 +1313,16 @@ async function buildFileParts(attachments, capable) {
|
|
|
1243
1313
|
);
|
|
1244
1314
|
dataUrl = null;
|
|
1245
1315
|
}
|
|
1316
|
+
if (dataUrl !== null && typeof dataUrl === "object") {
|
|
1317
|
+
outcomes.push({
|
|
1318
|
+
index: a.index,
|
|
1319
|
+
mime: a.mime,
|
|
1320
|
+
filename: a.filename,
|
|
1321
|
+
status: "failed",
|
|
1322
|
+
reason: "needs_reauth"
|
|
1323
|
+
});
|
|
1324
|
+
continue;
|
|
1325
|
+
}
|
|
1246
1326
|
if (dataUrl == null) {
|
|
1247
1327
|
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1248
1328
|
continue;
|
|
@@ -1324,7 +1404,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
1324
1404
|
}
|
|
1325
1405
|
}
|
|
1326
1406
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
1327
|
-
await new Promise((
|
|
1407
|
+
await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
|
|
1328
1408
|
}
|
|
1329
1409
|
}
|
|
1330
1410
|
return null;
|
|
@@ -1370,6 +1450,72 @@ function findLastAssistantReplyFor(messages, userMessageId) {
|
|
|
1370
1450
|
}
|
|
1371
1451
|
return lastOk ?? last;
|
|
1372
1452
|
}
|
|
1453
|
+
function messageUsage(messages, userMessageId) {
|
|
1454
|
+
if (!messages || messages.length === 0) return null;
|
|
1455
|
+
const byParentAll = messages.filter(
|
|
1456
|
+
(m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
|
|
1457
|
+
);
|
|
1458
|
+
const byParentNonErrored = byParentAll.filter((m) => errorOf(m) == null);
|
|
1459
|
+
const byParent = byParentNonErrored.length > 0 ? byParentNonErrored : byParentAll;
|
|
1460
|
+
let correlated;
|
|
1461
|
+
if (byParent.length > 0) {
|
|
1462
|
+
correlated = byParent;
|
|
1463
|
+
} else {
|
|
1464
|
+
const reply = findAssistantReplyAfter(messages, userMessageId);
|
|
1465
|
+
correlated = reply ? [reply] : [];
|
|
1466
|
+
}
|
|
1467
|
+
if (correlated.length === 0) return null;
|
|
1468
|
+
let sawAnyUsage = false;
|
|
1469
|
+
let inputSum = 0;
|
|
1470
|
+
let outputSum = 0;
|
|
1471
|
+
let reasoningSum = 0;
|
|
1472
|
+
let cacheReadSum = 0;
|
|
1473
|
+
let cacheWriteSum = 0;
|
|
1474
|
+
let costSum = 0;
|
|
1475
|
+
let sawCost = false;
|
|
1476
|
+
let modelId = null;
|
|
1477
|
+
let providerId = null;
|
|
1478
|
+
for (const m of correlated) {
|
|
1479
|
+
const info = m.info;
|
|
1480
|
+
if (!info) continue;
|
|
1481
|
+
const tokens = info.tokens;
|
|
1482
|
+
if (tokens) {
|
|
1483
|
+
sawAnyUsage = true;
|
|
1484
|
+
inputSum += tokens.input ?? 0;
|
|
1485
|
+
outputSum += tokens.output ?? 0;
|
|
1486
|
+
reasoningSum += tokens.reasoning ?? 0;
|
|
1487
|
+
cacheReadSum += tokens.cache?.read ?? 0;
|
|
1488
|
+
cacheWriteSum += tokens.cache?.write ?? 0;
|
|
1489
|
+
}
|
|
1490
|
+
if (typeof info.cost === "number") {
|
|
1491
|
+
sawAnyUsage = true;
|
|
1492
|
+
sawCost = true;
|
|
1493
|
+
costSum += info.cost;
|
|
1494
|
+
}
|
|
1495
|
+
if (typeof info.modelID === "string") {
|
|
1496
|
+
sawAnyUsage = true;
|
|
1497
|
+
modelId = info.modelID;
|
|
1498
|
+
}
|
|
1499
|
+
if (typeof info.providerID === "string") {
|
|
1500
|
+
sawAnyUsage = true;
|
|
1501
|
+
providerId = info.providerID;
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
if (!sawAnyUsage) return null;
|
|
1505
|
+
return {
|
|
1506
|
+
usage_provider_id: providerId,
|
|
1507
|
+
usage_model_id: modelId,
|
|
1508
|
+
usage_tokens_input: inputSum,
|
|
1509
|
+
usage_tokens_output: outputSum,
|
|
1510
|
+
usage_tokens_reasoning: reasoningSum,
|
|
1511
|
+
usage_tokens_cache_read: cacheReadSum,
|
|
1512
|
+
usage_tokens_cache_write: cacheWriteSum,
|
|
1513
|
+
// NULL means "OpenCode never reported a cost" (never inferred from
|
|
1514
|
+
// tokens) — distinct from a genuine 0-cost turn, which would set
|
|
1515
|
+
// `sawCost` true with `costSum === 0`.
|
|
1516
|
+
usage_cost_usd: sawCost ? costSum : null
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1373
1519
|
function messageRunState(messages, userMessageId) {
|
|
1374
1520
|
if (!messages || messages.length === 0) return "unknown";
|
|
1375
1521
|
const hasUser = messages.some((m) => idOf(m) === userMessageId);
|
|
@@ -1405,6 +1551,37 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
|
1405
1551
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1406
1552
|
);
|
|
1407
1553
|
}
|
|
1554
|
+
async function hasAnyConfiguredProvider(port) {
|
|
1555
|
+
try {
|
|
1556
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1557
|
+
if (!res.ok) {
|
|
1558
|
+
console.error(
|
|
1559
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1560
|
+
);
|
|
1561
|
+
return null;
|
|
1562
|
+
}
|
|
1563
|
+
const body = await res.json();
|
|
1564
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1565
|
+
console.error(
|
|
1566
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
1567
|
+
);
|
|
1568
|
+
return null;
|
|
1569
|
+
}
|
|
1570
|
+
const defaults2 = body.default;
|
|
1571
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
1572
|
+
console.error(
|
|
1573
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
1574
|
+
);
|
|
1575
|
+
return null;
|
|
1576
|
+
}
|
|
1577
|
+
return Object.keys(defaults2).length > 0;
|
|
1578
|
+
} catch (err) {
|
|
1579
|
+
console.error(
|
|
1580
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1581
|
+
);
|
|
1582
|
+
return null;
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1408
1585
|
|
|
1409
1586
|
// src/lib/opencode/session-cleanup.ts
|
|
1410
1587
|
var DURATION_UNIT_MS = {
|
|
@@ -1563,10 +1740,11 @@ var StreamForwarder = class {
|
|
|
1563
1740
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1564
1741
|
*/
|
|
1565
1742
|
abortAll() {
|
|
1566
|
-
for (const stream of this.inflight.
|
|
1743
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1567
1744
|
try {
|
|
1568
1745
|
stream.abort();
|
|
1569
|
-
} catch {
|
|
1746
|
+
} catch (err) {
|
|
1747
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1570
1748
|
}
|
|
1571
1749
|
}
|
|
1572
1750
|
this.inflight.clear();
|
|
@@ -1600,12 +1778,12 @@ var StreamForwarder = class {
|
|
|
1600
1778
|
let endBody;
|
|
1601
1779
|
if (has_body) {
|
|
1602
1780
|
const chunks = [];
|
|
1603
|
-
bodyPromise = new Promise((
|
|
1781
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1604
1782
|
pushBody = (buf) => {
|
|
1605
1783
|
chunks.push(buf);
|
|
1606
1784
|
};
|
|
1607
1785
|
endBody = () => {
|
|
1608
|
-
|
|
1786
|
+
resolve3(Buffer.concat(chunks));
|
|
1609
1787
|
};
|
|
1610
1788
|
});
|
|
1611
1789
|
}
|
|
@@ -1716,31 +1894,20 @@ function connectTunnel(options) {
|
|
|
1716
1894
|
onConnected,
|
|
1717
1895
|
onDisconnected,
|
|
1718
1896
|
onError,
|
|
1719
|
-
onRequest,
|
|
1720
1897
|
onResponse,
|
|
1721
1898
|
onInfo,
|
|
1722
1899
|
onDrainPing
|
|
1723
1900
|
} = options;
|
|
1724
1901
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1725
1902
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1726
|
-
return new Promise((
|
|
1903
|
+
return new Promise((resolve3, reject) => {
|
|
1727
1904
|
const ws = new WebSocket2(url, {
|
|
1728
1905
|
headers: {
|
|
1729
1906
|
Authorization: authHeader
|
|
1730
1907
|
}
|
|
1731
1908
|
});
|
|
1732
|
-
const streamStartTimes = /* @__PURE__ */ new Map();
|
|
1733
1909
|
const forwarder = new StreamForwarder(ws, port, {
|
|
1734
|
-
|
|
1735
|
-
if (path === TUNNEL_DRAIN_PING_PATH) return;
|
|
1736
|
-
streamStartTimes.set(sid, Date.now());
|
|
1737
|
-
onRequest?.(method, path, sid);
|
|
1738
|
-
},
|
|
1739
|
-
onHead: (sid, status) => {
|
|
1740
|
-
const startedAt = streamStartTimes.get(sid);
|
|
1741
|
-
streamStartTimes.delete(sid);
|
|
1742
|
-
onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
|
|
1743
|
-
},
|
|
1910
|
+
onHead: () => onResponse?.(),
|
|
1744
1911
|
onDrainPing: () => onDrainPing?.()
|
|
1745
1912
|
});
|
|
1746
1913
|
const connectionTimeout = setTimeout(() => {
|
|
@@ -1788,7 +1955,7 @@ function connectTunnel(options) {
|
|
|
1788
1955
|
clearTimeout(connectionTimeout);
|
|
1789
1956
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1790
1957
|
onConnected?.(connectedAgentId);
|
|
1791
|
-
|
|
1958
|
+
resolve3({
|
|
1792
1959
|
ws,
|
|
1793
1960
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1794
1961
|
});
|
|
@@ -1816,7 +1983,6 @@ function connectTunnel(options) {
|
|
|
1816
1983
|
ws.on("close", (code, reason) => {
|
|
1817
1984
|
const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
|
|
1818
1985
|
forwarder.abortAll();
|
|
1819
|
-
streamStartTimes.clear();
|
|
1820
1986
|
onDisconnected?.(code, reasonStr);
|
|
1821
1987
|
});
|
|
1822
1988
|
});
|
|
@@ -1851,7 +2017,11 @@ var RunnerConnection = class {
|
|
|
1851
2017
|
if (this.connection) {
|
|
1852
2018
|
try {
|
|
1853
2019
|
this.connection.close();
|
|
1854
|
-
} catch {
|
|
2020
|
+
} catch (err) {
|
|
2021
|
+
log("error", "runner_connection_close_failed", {
|
|
2022
|
+
agent_id: this.resolvedAgentId,
|
|
2023
|
+
...errorFields(err)
|
|
2024
|
+
});
|
|
1855
2025
|
}
|
|
1856
2026
|
this.connection = null;
|
|
1857
2027
|
}
|
|
@@ -1903,6 +2073,404 @@ var RunnerConnection = class {
|
|
|
1903
2073
|
}
|
|
1904
2074
|
};
|
|
1905
2075
|
|
|
2076
|
+
// src/lib/channels/driver.ts
|
|
2077
|
+
import { homedir } from "os";
|
|
2078
|
+
|
|
2079
|
+
// src/lib/file-push.ts
|
|
2080
|
+
import { randomUUID } from "crypto";
|
|
2081
|
+
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2082
|
+
import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
|
|
2083
|
+
var FILE_MODE = 384;
|
|
2084
|
+
var DIRECTORY_MODE = 448;
|
|
2085
|
+
async function writePushedFile(request) {
|
|
2086
|
+
const { requestedPath, content, allowedDirectories, homeDir } = request;
|
|
2087
|
+
const bytes = content.byteLength;
|
|
2088
|
+
if (allowedDirectories.length === 0) {
|
|
2089
|
+
return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
2090
|
+
path: requestedPath,
|
|
2091
|
+
bytes
|
|
2092
|
+
});
|
|
2093
|
+
}
|
|
2094
|
+
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
2095
|
+
return refuse(
|
|
2096
|
+
"file_too_large",
|
|
2097
|
+
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
2098
|
+
{
|
|
2099
|
+
path: requestedPath,
|
|
2100
|
+
bytes
|
|
2101
|
+
}
|
|
2102
|
+
);
|
|
2103
|
+
}
|
|
2104
|
+
const candidate = expandAndValidate(requestedPath, homeDir);
|
|
2105
|
+
if (candidate === null) {
|
|
2106
|
+
return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
2107
|
+
path: requestedPath,
|
|
2108
|
+
bytes
|
|
2109
|
+
});
|
|
2110
|
+
}
|
|
2111
|
+
try {
|
|
2112
|
+
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2113
|
+
dirname2(candidate)
|
|
2114
|
+
);
|
|
2115
|
+
const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
|
|
2116
|
+
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2117
|
+
if (allowedDirectory === null) {
|
|
2118
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2119
|
+
path: realTarget,
|
|
2120
|
+
bytes
|
|
2121
|
+
});
|
|
2122
|
+
}
|
|
2123
|
+
if (missingSegments.length > 0) {
|
|
2124
|
+
await createMissingDirectories(existingAncestor, missingSegments);
|
|
2125
|
+
const realParent = await realpath(dirname2(realTarget));
|
|
2126
|
+
if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
2127
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2128
|
+
path: realTarget,
|
|
2129
|
+
bytes,
|
|
2130
|
+
reason: "parent_changed_after_create"
|
|
2131
|
+
});
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
await writeAtomically(realTarget, content);
|
|
2135
|
+
log("info", "file_push_written", { path: realTarget, bytes });
|
|
2136
|
+
return { ok: true, path: realTarget };
|
|
2137
|
+
} catch (err) {
|
|
2138
|
+
const errno = err.code ?? "UNKNOWN";
|
|
2139
|
+
return refuse("write_failed", `The runner could not write the file (${errno}).`, {
|
|
2140
|
+
path: candidate,
|
|
2141
|
+
bytes,
|
|
2142
|
+
errno,
|
|
2143
|
+
...errorFields(err)
|
|
2144
|
+
});
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
function expandAndValidate(requestedPath, homeDir) {
|
|
2148
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2149
|
+
return null;
|
|
2150
|
+
}
|
|
2151
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2152
|
+
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2153
|
+
return null;
|
|
2154
|
+
}
|
|
2155
|
+
if (!isAbsolute(expanded)) {
|
|
2156
|
+
return null;
|
|
2157
|
+
}
|
|
2158
|
+
const candidate = resolve2(expanded);
|
|
2159
|
+
const name = basename(candidate);
|
|
2160
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
2161
|
+
}
|
|
2162
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
2163
|
+
const missingSegments = [];
|
|
2164
|
+
let current = directory;
|
|
2165
|
+
for (; ; ) {
|
|
2166
|
+
try {
|
|
2167
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
2168
|
+
} catch (err) {
|
|
2169
|
+
const parent = dirname2(current);
|
|
2170
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
2171
|
+
throw err;
|
|
2172
|
+
}
|
|
2173
|
+
missingSegments.unshift(basename(current));
|
|
2174
|
+
current = parent;
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
2179
|
+
for (const directory of allowedDirectories) {
|
|
2180
|
+
if (!isAbsolute(directory)) {
|
|
2181
|
+
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
2182
|
+
continue;
|
|
2183
|
+
}
|
|
2184
|
+
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
2185
|
+
if (realDirectory !== null && contains(realDirectory, realTarget)) {
|
|
2186
|
+
return realDirectory;
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
return null;
|
|
2190
|
+
}
|
|
2191
|
+
async function realpathCreatingIfMissing(directory) {
|
|
2192
|
+
try {
|
|
2193
|
+
return await realpath(directory);
|
|
2194
|
+
} catch (err) {
|
|
2195
|
+
if (err.code !== "ENOENT") {
|
|
2196
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2197
|
+
directory,
|
|
2198
|
+
reason: "unresolvable",
|
|
2199
|
+
...errorFields(err)
|
|
2200
|
+
});
|
|
2201
|
+
return null;
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
try {
|
|
2205
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
2206
|
+
await chmod(directory, DIRECTORY_MODE);
|
|
2207
|
+
return await realpath(directory);
|
|
2208
|
+
} catch (err) {
|
|
2209
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2210
|
+
directory,
|
|
2211
|
+
reason: "create_failed",
|
|
2212
|
+
...errorFields(err)
|
|
2213
|
+
});
|
|
2214
|
+
return null;
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
function contains(realDirectory, realTarget) {
|
|
2218
|
+
const rel = relative(realDirectory, realTarget);
|
|
2219
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
2220
|
+
}
|
|
2221
|
+
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2222
|
+
let current = existingAncestor;
|
|
2223
|
+
for (const segment of missingSegments) {
|
|
2224
|
+
current = join(current, segment);
|
|
2225
|
+
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2226
|
+
await chmod(current, DIRECTORY_MODE);
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
async function writeAtomically(realTarget, content) {
|
|
2230
|
+
const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2231
|
+
let handle;
|
|
2232
|
+
try {
|
|
2233
|
+
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
2234
|
+
await handle.writeFile(content);
|
|
2235
|
+
await handle.chmod(FILE_MODE);
|
|
2236
|
+
await handle.close();
|
|
2237
|
+
handle = void 0;
|
|
2238
|
+
await rename(temporaryPath, realTarget);
|
|
2239
|
+
} catch (err) {
|
|
2240
|
+
await discardTemporaryFile(temporaryPath, handle);
|
|
2241
|
+
throw err;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
async function discardTemporaryFile(temporaryPath, handle) {
|
|
2245
|
+
try {
|
|
2246
|
+
await handle?.close();
|
|
2247
|
+
} catch (err) {
|
|
2248
|
+
log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2249
|
+
}
|
|
2250
|
+
try {
|
|
2251
|
+
await unlink(temporaryPath);
|
|
2252
|
+
} catch (err) {
|
|
2253
|
+
const errno = err.code;
|
|
2254
|
+
if (errno !== "ENOENT" && errno !== "ENOTDIR") {
|
|
2255
|
+
log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
function refuse(code, message, fields) {
|
|
2260
|
+
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
2261
|
+
return { ok: false, code, message };
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
// src/lib/runner-file-sync.ts
|
|
2265
|
+
var MAX_ACK_ATTEMPTS = 5;
|
|
2266
|
+
async function syncPendingRunnerFiles(options) {
|
|
2267
|
+
const pending = await listPendingFiles(options);
|
|
2268
|
+
const pendingIds = new Set(pending.map((file) => file.id));
|
|
2269
|
+
for (const id of options.ackFailures.keys()) {
|
|
2270
|
+
if (!pendingIds.has(id)) options.ackFailures.delete(id);
|
|
2271
|
+
}
|
|
2272
|
+
if (pending.length === 0) return 0;
|
|
2273
|
+
options.log({
|
|
2274
|
+
level: "info",
|
|
2275
|
+
message: `Runner file sync: ${pending.length} file(s) queued for this runner`
|
|
2276
|
+
});
|
|
2277
|
+
let applied = 0;
|
|
2278
|
+
for (const file of pending) {
|
|
2279
|
+
if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
|
|
2280
|
+
if (await applyOne(options, file)) applied += 1;
|
|
2281
|
+
}
|
|
2282
|
+
return applied;
|
|
2283
|
+
}
|
|
2284
|
+
async function listPendingFiles(options) {
|
|
2285
|
+
let res;
|
|
2286
|
+
try {
|
|
2287
|
+
res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
|
|
2288
|
+
headers: { Authorization: options.getAuthHeader() }
|
|
2289
|
+
});
|
|
2290
|
+
} catch (err) {
|
|
2291
|
+
options.log({
|
|
2292
|
+
level: "warn",
|
|
2293
|
+
message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
|
|
2294
|
+
});
|
|
2295
|
+
return [];
|
|
2296
|
+
}
|
|
2297
|
+
if (!res.ok) {
|
|
2298
|
+
options.log({
|
|
2299
|
+
level: res.status === 404 ? "debug" : "warn",
|
|
2300
|
+
message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2301
|
+
});
|
|
2302
|
+
return [];
|
|
2303
|
+
}
|
|
2304
|
+
let body;
|
|
2305
|
+
try {
|
|
2306
|
+
body = await res.json();
|
|
2307
|
+
} catch (err) {
|
|
2308
|
+
options.log({
|
|
2309
|
+
level: "warn",
|
|
2310
|
+
message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
|
|
2311
|
+
});
|
|
2312
|
+
return [];
|
|
2313
|
+
}
|
|
2314
|
+
if (!Array.isArray(body)) {
|
|
2315
|
+
options.log({
|
|
2316
|
+
level: "warn",
|
|
2317
|
+
message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
|
|
2318
|
+
});
|
|
2319
|
+
return [];
|
|
2320
|
+
}
|
|
2321
|
+
const files = [];
|
|
2322
|
+
for (const entry of body) {
|
|
2323
|
+
const file = asPendingFile(entry);
|
|
2324
|
+
if (file === null) {
|
|
2325
|
+
options.log({
|
|
2326
|
+
level: "warn",
|
|
2327
|
+
message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
|
|
2328
|
+
});
|
|
2329
|
+
continue;
|
|
2330
|
+
}
|
|
2331
|
+
files.push(file);
|
|
2332
|
+
}
|
|
2333
|
+
return files;
|
|
2334
|
+
}
|
|
2335
|
+
function asPendingFile(entry) {
|
|
2336
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
2337
|
+
const { id, path, size } = entry;
|
|
2338
|
+
if (typeof id !== "string" || id === "") return null;
|
|
2339
|
+
if (typeof path !== "string" || path === "") return null;
|
|
2340
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
|
|
2341
|
+
return { id, path, size };
|
|
2342
|
+
}
|
|
2343
|
+
async function applyOne(options, file) {
|
|
2344
|
+
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
2345
|
+
if (options.allowedDirectories.length === 0) {
|
|
2346
|
+
options.log({
|
|
2347
|
+
level: "warn",
|
|
2348
|
+
message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
|
|
2349
|
+
});
|
|
2350
|
+
await ack(options, file, "rejected", "file_sync_disabled");
|
|
2351
|
+
return false;
|
|
2352
|
+
}
|
|
2353
|
+
if (file.size > MAX_FILE_PUSH_BYTES) {
|
|
2354
|
+
options.log({
|
|
2355
|
+
level: "warn",
|
|
2356
|
+
message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
|
|
2357
|
+
});
|
|
2358
|
+
await ack(options, file, "rejected", "file_too_large");
|
|
2359
|
+
return false;
|
|
2360
|
+
}
|
|
2361
|
+
const download = await downloadContent(options, file, label);
|
|
2362
|
+
if (!download.ok) {
|
|
2363
|
+
if (download.terminal) await ack(options, file, "rejected", download.code);
|
|
2364
|
+
return false;
|
|
2365
|
+
}
|
|
2366
|
+
let outcome;
|
|
2367
|
+
try {
|
|
2368
|
+
outcome = await writePushedFile({
|
|
2369
|
+
requestedPath: file.path,
|
|
2370
|
+
content: download.content,
|
|
2371
|
+
allowedDirectories: options.allowedDirectories,
|
|
2372
|
+
homeDir: options.homeDir
|
|
2373
|
+
});
|
|
2374
|
+
} catch (err) {
|
|
2375
|
+
options.log({
|
|
2376
|
+
level: "error",
|
|
2377
|
+
message: `Runner file ${label} could not be written: ${describe(err)}`
|
|
2378
|
+
});
|
|
2379
|
+
await ack(options, file, "rejected", "write_failed");
|
|
2380
|
+
return false;
|
|
2381
|
+
}
|
|
2382
|
+
if (!outcome.ok) {
|
|
2383
|
+
options.log({
|
|
2384
|
+
level: "warn",
|
|
2385
|
+
message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
|
|
2386
|
+
});
|
|
2387
|
+
await ack(options, file, "rejected", outcome.code);
|
|
2388
|
+
return false;
|
|
2389
|
+
}
|
|
2390
|
+
options.log({
|
|
2391
|
+
level: "info",
|
|
2392
|
+
message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
|
|
2393
|
+
});
|
|
2394
|
+
await ack(options, file, "applied");
|
|
2395
|
+
return true;
|
|
2396
|
+
}
|
|
2397
|
+
function durableDownloadCode(status) {
|
|
2398
|
+
return status === 413 ? "file_too_large" : "write_failed";
|
|
2399
|
+
}
|
|
2400
|
+
async function downloadContent(options, file, label) {
|
|
2401
|
+
try {
|
|
2402
|
+
const res = await options.fetchImpl(
|
|
2403
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
|
|
2404
|
+
{ headers: { Authorization: options.getAuthHeader() } }
|
|
2405
|
+
);
|
|
2406
|
+
if (!res.ok) {
|
|
2407
|
+
const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
|
|
2408
|
+
if (!terminal) {
|
|
2409
|
+
options.log({
|
|
2410
|
+
level: "warn",
|
|
2411
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2412
|
+
});
|
|
2413
|
+
return { ok: false, terminal: false };
|
|
2414
|
+
}
|
|
2415
|
+
const code = durableDownloadCode(res.status);
|
|
2416
|
+
options.log({
|
|
2417
|
+
level: "error",
|
|
2418
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
|
|
2419
|
+
});
|
|
2420
|
+
return { ok: false, terminal: true, code };
|
|
2421
|
+
}
|
|
2422
|
+
return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
|
|
2423
|
+
} catch (err) {
|
|
2424
|
+
options.log({
|
|
2425
|
+
level: "warn",
|
|
2426
|
+
message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
|
|
2427
|
+
});
|
|
2428
|
+
return { ok: false, terminal: false };
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
async function ack(options, file, status, reason) {
|
|
2432
|
+
const outcome = `${status}${reason ? ` (${reason})` : ""}`;
|
|
2433
|
+
try {
|
|
2434
|
+
const res = await options.fetchImpl(
|
|
2435
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
2436
|
+
{
|
|
2437
|
+
method: "POST",
|
|
2438
|
+
headers: {
|
|
2439
|
+
Authorization: options.getAuthHeader(),
|
|
2440
|
+
"Content-Type": "application/json"
|
|
2441
|
+
},
|
|
2442
|
+
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
2443
|
+
}
|
|
2444
|
+
);
|
|
2445
|
+
if (!res.ok) {
|
|
2446
|
+
recordAckFailure(
|
|
2447
|
+
options,
|
|
2448
|
+
file,
|
|
2449
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
|
|
2450
|
+
);
|
|
2451
|
+
return;
|
|
2452
|
+
}
|
|
2453
|
+
options.ackFailures.delete(file.id);
|
|
2454
|
+
} catch (err) {
|
|
2455
|
+
recordAckFailure(
|
|
2456
|
+
options,
|
|
2457
|
+
file,
|
|
2458
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
|
|
2459
|
+
);
|
|
2460
|
+
}
|
|
2461
|
+
}
|
|
2462
|
+
function recordAckFailure(options, file, what) {
|
|
2463
|
+
const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
|
|
2464
|
+
options.ackFailures.set(file.id, attempts);
|
|
2465
|
+
options.log({
|
|
2466
|
+
level: "error",
|
|
2467
|
+
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})`
|
|
2468
|
+
});
|
|
2469
|
+
}
|
|
2470
|
+
function describe(err) {
|
|
2471
|
+
return err instanceof Error ? err.message : String(err);
|
|
2472
|
+
}
|
|
2473
|
+
|
|
1906
2474
|
// src/lib/channels/driver.ts
|
|
1907
2475
|
function messageIdOf(m) {
|
|
1908
2476
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -1932,6 +2500,7 @@ var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
|
1932
2500
|
var HEARTBEAT_MS = 6e4;
|
|
1933
2501
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
1934
2502
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2503
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
1935
2504
|
var ChannelAuthError = class extends Error {
|
|
1936
2505
|
constructor(message) {
|
|
1937
2506
|
super(message);
|
|
@@ -1954,7 +2523,7 @@ function backoffDelay(attempt, policy) {
|
|
|
1954
2523
|
function isRetryableStatus(status) {
|
|
1955
2524
|
return status === 429 || status >= 500 && status <= 599;
|
|
1956
2525
|
}
|
|
1957
|
-
var ChannelDriver = class {
|
|
2526
|
+
var ChannelDriver = class _ChannelDriver {
|
|
1958
2527
|
agentId;
|
|
1959
2528
|
port;
|
|
1960
2529
|
apiUrl;
|
|
@@ -1968,8 +2537,38 @@ var ChannelDriver = class {
|
|
|
1968
2537
|
pausedMaxWaitMs;
|
|
1969
2538
|
stuckQueuedMs;
|
|
1970
2539
|
now;
|
|
2540
|
+
fileSyncDirectories;
|
|
2541
|
+
homeDir;
|
|
1971
2542
|
/** Cache of conversationId → opencode sessionId. */
|
|
1972
2543
|
sessions = /* @__PURE__ */ new Map();
|
|
2544
|
+
/**
|
|
2545
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2546
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2547
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2548
|
+
* must bind a fresh one.
|
|
2549
|
+
*
|
|
2550
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2551
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2552
|
+
* the same session, and its watcher's routine status writes carry
|
|
2553
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2554
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2555
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2556
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2557
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2558
|
+
* is one we deliberately keep (see `markDone`).
|
|
2559
|
+
*
|
|
2560
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2561
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2562
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2563
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2564
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2565
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2566
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2567
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2568
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2569
|
+
* bounded cost.
|
|
2570
|
+
*/
|
|
2571
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
1973
2572
|
/**
|
|
1974
2573
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
1975
2574
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2079,9 +2678,12 @@ var ChannelDriver = class {
|
|
|
2079
2678
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2080
2679
|
/**
|
|
2081
2680
|
* Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
|
|
2082
|
-
* NON-EMPTY name is stored (terminal — a real session name
|
|
2083
|
-
* so we do NOT re-GET `/session/:id` every tick.
|
|
2084
|
-
*
|
|
2681
|
+
* NON-EMPTY, non-placeholder name is stored (terminal — a real session name
|
|
2682
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
|
|
2683
|
+
* excludes OpenCode's synchronous default title (see
|
|
2684
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
|
|
2685
|
+
* as an empty title so it never latches. A missing entry = not yet resolved OR
|
|
2686
|
+
* resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
|
|
2085
2687
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2086
2688
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2087
2689
|
* no watcher) can resolve the title.
|
|
@@ -2089,6 +2691,24 @@ var ChannelDriver = class {
|
|
|
2089
2691
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2090
2692
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2091
2693
|
draining = false;
|
|
2694
|
+
/**
|
|
2695
|
+
* Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
|
|
2696
|
+
* drain ping don't download, write and ack the same file twice.
|
|
2697
|
+
*/
|
|
2698
|
+
syncingFiles = false;
|
|
2699
|
+
/**
|
|
2700
|
+
* Consecutive failed acks per pending file (#559). Lives on the driver so it
|
|
2701
|
+
* survives across drains — without it, a file whose ack keeps failing is
|
|
2702
|
+
* re-downloaded and re-written every ~2s until the server expires it.
|
|
2703
|
+
*/
|
|
2704
|
+
fileAckFailures = /* @__PURE__ */ new Map();
|
|
2705
|
+
/**
|
|
2706
|
+
* Monotonic count of files this runner has pulled and written (#559). Only
|
|
2707
|
+
* ever increases, so `run.ts` detects work by comparing it against the value
|
|
2708
|
+
* it saw on the previous cycle — including work that landed mid-sleep, the
|
|
2709
|
+
* same trick `lastProxiedActivityAt` uses.
|
|
2710
|
+
*/
|
|
2711
|
+
appliedFileCount = 0;
|
|
2092
2712
|
/**
|
|
2093
2713
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2094
2714
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2119,6 +2739,8 @@ var ChannelDriver = class {
|
|
|
2119
2739
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2120
2740
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2121
2741
|
this.now = config2.now ?? (() => Date.now());
|
|
2742
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
2743
|
+
this.homeDir = config2.homeDir ?? homedir();
|
|
2122
2744
|
}
|
|
2123
2745
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2124
2746
|
get opencodeBase() {
|
|
@@ -2146,6 +2768,47 @@ var ChannelDriver = class {
|
|
|
2146
2768
|
);
|
|
2147
2769
|
return run2;
|
|
2148
2770
|
}
|
|
2771
|
+
/**
|
|
2772
|
+
* Pull-and-apply any files Evident has queued for this runner (#559), riding
|
|
2773
|
+
* the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
|
|
2774
|
+
* and drain ping that call `drainPending()`. There is deliberately no channel,
|
|
2775
|
+
* control frame or poll loop of its own: worst-case latency is one poll tick.
|
|
2776
|
+
*
|
|
2777
|
+
* NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
|
|
2778
|
+
* cost a conversation turn. Failures are logged and either acked as a terminal
|
|
2779
|
+
* outcome or left pending for the next drain (see `runner-file-sync.ts`).
|
|
2780
|
+
*
|
|
2781
|
+
* Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
|
|
2782
|
+
*
|
|
2783
|
+
* @returns the number of files written to disk.
|
|
2784
|
+
*/
|
|
2785
|
+
async syncPendingFiles() {
|
|
2786
|
+
if (this.stopped) return 0;
|
|
2787
|
+
if (this.syncingFiles) return 0;
|
|
2788
|
+
this.syncingFiles = true;
|
|
2789
|
+
try {
|
|
2790
|
+
const applied = await syncPendingRunnerFiles({
|
|
2791
|
+
agentId: this.agentId,
|
|
2792
|
+
apiUrl: this.apiUrl,
|
|
2793
|
+
getAuthHeader: this.getAuthHeader,
|
|
2794
|
+
fetchImpl: this.fetchImpl,
|
|
2795
|
+
allowedDirectories: this.fileSyncDirectories,
|
|
2796
|
+
homeDir: this.homeDir,
|
|
2797
|
+
ackFailures: this.fileAckFailures,
|
|
2798
|
+
log: this.log
|
|
2799
|
+
});
|
|
2800
|
+
this.appliedFileCount += applied;
|
|
2801
|
+
return applied;
|
|
2802
|
+
} catch (err) {
|
|
2803
|
+
this.log({
|
|
2804
|
+
level: "error",
|
|
2805
|
+
message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
|
|
2806
|
+
});
|
|
2807
|
+
return 0;
|
|
2808
|
+
} finally {
|
|
2809
|
+
this.syncingFiles = false;
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2149
2812
|
async runDrain() {
|
|
2150
2813
|
let dispatched = 0;
|
|
2151
2814
|
try {
|
|
@@ -2179,6 +2842,28 @@ var ChannelDriver = class {
|
|
|
2179
2842
|
}
|
|
2180
2843
|
return false;
|
|
2181
2844
|
}
|
|
2845
|
+
/**
|
|
2846
|
+
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
2847
|
+
*
|
|
2848
|
+
* Pulling a file is real work that `drainPending()` knows nothing about, so
|
|
2849
|
+
* without this a near-idle runner counts a credential pull as an empty tick
|
|
2850
|
+
* and `--idle-timeout` can `process.exit` mid-pull — leaving a
|
|
2851
|
+
* `.evident-push-*.tmp` behind — or immediately after the write, before the
|
|
2852
|
+
* browser has run the authorize/callback that activates it (the user then sees
|
|
2853
|
+
* `saved_not_activated` for a runner that was fine).
|
|
2854
|
+
*
|
|
2855
|
+
* Two signals because one cannot cover both cases: `inFlight` is the pull
|
|
2856
|
+
* happening RIGHT NOW (it may outlive the tick that started it), and
|
|
2857
|
+
* `appliedFiles` is monotonic so a pull that started AND finished between two
|
|
2858
|
+
* idle checks still shows up as an advance.
|
|
2859
|
+
*
|
|
2860
|
+
* CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
|
|
2861
|
+
* the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
|
|
2862
|
+
* samples afterwards reads `true` every single cycle and can never idle out.
|
|
2863
|
+
*/
|
|
2864
|
+
fileSyncActivity() {
|
|
2865
|
+
return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
|
|
2866
|
+
}
|
|
2182
2867
|
/**
|
|
2183
2868
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2184
2869
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2240,7 +2925,7 @@ var ChannelDriver = class {
|
|
|
2240
2925
|
await this.sleep(step);
|
|
2241
2926
|
}
|
|
2242
2927
|
}
|
|
2243
|
-
while (this.hasInFlightWatchers()) {
|
|
2928
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2244
2929
|
if (this.now() >= deadline) return false;
|
|
2245
2930
|
await this.sleep(step);
|
|
2246
2931
|
}
|
|
@@ -2275,10 +2960,15 @@ var ChannelDriver = class {
|
|
|
2275
2960
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2276
2961
|
*/
|
|
2277
2962
|
async processConversation(conv) {
|
|
2278
|
-
const sessionId = await this.ensureSession(conv);
|
|
2963
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2279
2964
|
const messages = await this.getPendingMessages(conv.id);
|
|
2280
2965
|
let dispatched = 0;
|
|
2281
2966
|
let skippedAlreadyDispatched = 0;
|
|
2967
|
+
if (refusedSessionId && messages.length > 0) {
|
|
2968
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
2969
|
+
superseded_session_id: refusedSessionId
|
|
2970
|
+
});
|
|
2971
|
+
}
|
|
2282
2972
|
for (const message of messages) {
|
|
2283
2973
|
if (this.stopped) break;
|
|
2284
2974
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2305,7 +2995,8 @@ var ChannelDriver = class {
|
|
|
2305
2995
|
} catch (err) {
|
|
2306
2996
|
if (err instanceof ChannelAuthError) throw err;
|
|
2307
2997
|
this.dispatched.delete(message.id);
|
|
2308
|
-
|
|
2998
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
2999
|
+
if (exists === false) {
|
|
2309
3000
|
this.sessions.delete(conv.id);
|
|
2310
3001
|
this.log({
|
|
2311
3002
|
level: "warn",
|
|
@@ -2315,15 +3006,39 @@ var ChannelDriver = class {
|
|
|
2315
3006
|
});
|
|
2316
3007
|
break;
|
|
2317
3008
|
}
|
|
2318
|
-
|
|
3009
|
+
if (exists === null) {
|
|
3010
|
+
this.log({
|
|
3011
|
+
level: "warn",
|
|
3012
|
+
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.`,
|
|
3013
|
+
conversation_id: conv.id,
|
|
3014
|
+
message_id: message.id
|
|
3015
|
+
});
|
|
3016
|
+
break;
|
|
3017
|
+
}
|
|
3018
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3019
|
+
this.sessions.delete(conv.id);
|
|
3020
|
+
this.supersede(conv.id, sessionId);
|
|
3021
|
+
this.log({
|
|
3022
|
+
level: "warn",
|
|
3023
|
+
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.`,
|
|
3024
|
+
conversation_id: conv.id,
|
|
3025
|
+
message_id: message.id
|
|
3026
|
+
});
|
|
3027
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3028
|
+
this.log({
|
|
3029
|
+
level: "warn",
|
|
3030
|
+
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)}`,
|
|
3031
|
+
conversation_id: conv.id,
|
|
3032
|
+
message_id: message.id
|
|
3033
|
+
});
|
|
2319
3034
|
});
|
|
2320
3035
|
this.log({
|
|
2321
3036
|
level: "error",
|
|
2322
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3037
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2323
3038
|
conversation_id: conv.id,
|
|
2324
3039
|
message_id: message.id
|
|
2325
3040
|
});
|
|
2326
|
-
|
|
3041
|
+
break;
|
|
2327
3042
|
}
|
|
2328
3043
|
if (opencodeMessageId === null) {
|
|
2329
3044
|
this.log({
|
|
@@ -2349,8 +3064,42 @@ var ChannelDriver = class {
|
|
|
2349
3064
|
this.ensureWatcherRunning(sessionId);
|
|
2350
3065
|
return dispatched;
|
|
2351
3066
|
}
|
|
3067
|
+
/**
|
|
3068
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
3069
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
3070
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
3071
|
+
*/
|
|
3072
|
+
supersede(conversationId, sessionId) {
|
|
3073
|
+
this.supersededSessions.delete(conversationId);
|
|
3074
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
3075
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
3076
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
3077
|
+
if (oldest === void 0) return;
|
|
3078
|
+
this.supersededSessions.delete(oldest);
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
3082
|
+
isSuperseded(conversationId, sessionId) {
|
|
3083
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
3084
|
+
}
|
|
3085
|
+
/**
|
|
3086
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
3087
|
+
*
|
|
3088
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3089
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3090
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
3091
|
+
*/
|
|
2352
3092
|
async ensureSession(conv) {
|
|
2353
3093
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
3094
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
3095
|
+
this.log({
|
|
3096
|
+
level: "warn",
|
|
3097
|
+
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.`,
|
|
3098
|
+
conversation_id: conv.id
|
|
3099
|
+
});
|
|
3100
|
+
this.sessions.delete(conv.id);
|
|
3101
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
3102
|
+
}
|
|
2354
3103
|
if (bound) {
|
|
2355
3104
|
const exists = await sessionExists(this.port, bound);
|
|
2356
3105
|
if (exists === false) {
|
|
@@ -2360,12 +3109,12 @@ var ChannelDriver = class {
|
|
|
2360
3109
|
conversation_id: conv.id
|
|
2361
3110
|
});
|
|
2362
3111
|
this.sessions.delete(conv.id);
|
|
2363
|
-
return this.createAndBindSession(conv.id);
|
|
3112
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2364
3113
|
}
|
|
2365
3114
|
this.sessions.set(conv.id, bound);
|
|
2366
|
-
return bound;
|
|
3115
|
+
return { sessionId: bound };
|
|
2367
3116
|
}
|
|
2368
|
-
return this.createAndBindSession(conv.id);
|
|
3117
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2369
3118
|
}
|
|
2370
3119
|
/**
|
|
2371
3120
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2445,7 +3194,7 @@ var ChannelDriver = class {
|
|
|
2445
3194
|
}
|
|
2446
3195
|
/**
|
|
2447
3196
|
* Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
|
|
2448
|
-
* (`GET {apiUrl}/
|
|
3197
|
+
* (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
|
|
2449
3198
|
* existing authenticated fetch, and base64-encode into a
|
|
2450
3199
|
* `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
|
|
2451
3200
|
*
|
|
@@ -2453,15 +3202,38 @@ var ChannelDriver = class {
|
|
|
2453
3202
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2454
3203
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2455
3204
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2456
|
-
*
|
|
3205
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
3206
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
3207
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
3208
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
3209
|
+
* logged with context (no silent swallow).
|
|
2457
3210
|
*/
|
|
2458
3211
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2459
3212
|
try {
|
|
2460
3213
|
const res = await this.fetchImpl(
|
|
2461
|
-
`${this.apiUrl}/
|
|
3214
|
+
`${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
|
|
2462
3215
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2463
3216
|
);
|
|
2464
3217
|
if (!res.ok) {
|
|
3218
|
+
let reason;
|
|
3219
|
+
try {
|
|
3220
|
+
const body = await res.json();
|
|
3221
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
3222
|
+
} catch (parseErr) {
|
|
3223
|
+
this.log({
|
|
3224
|
+
level: "debug",
|
|
3225
|
+
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`,
|
|
3226
|
+
message_id: messageId
|
|
3227
|
+
});
|
|
3228
|
+
}
|
|
3229
|
+
if (reason === "needs_reauth") {
|
|
3230
|
+
this.log({
|
|
3231
|
+
level: "error",
|
|
3232
|
+
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)`,
|
|
3233
|
+
message_id: messageId
|
|
3234
|
+
});
|
|
3235
|
+
return { needsReauth: true };
|
|
3236
|
+
}
|
|
2465
3237
|
this.log({
|
|
2466
3238
|
level: "error",
|
|
2467
3239
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2501,6 +3273,9 @@ var ChannelDriver = class {
|
|
|
2501
3273
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2502
3274
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2503
3275
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
3276
|
+
const failedReason = outcomes.some(
|
|
3277
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
3278
|
+
) ? "needs_reauth" : void 0;
|
|
2504
3279
|
this.log({
|
|
2505
3280
|
level: "info",
|
|
2506
3281
|
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`,
|
|
@@ -2510,7 +3285,8 @@ var ChannelDriver = class {
|
|
|
2510
3285
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2511
3286
|
skipped,
|
|
2512
3287
|
failed,
|
|
2513
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3288
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3289
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2514
3290
|
});
|
|
2515
3291
|
}
|
|
2516
3292
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2790,13 +3566,15 @@ var ChannelDriver = class {
|
|
|
2790
3566
|
message_id: inFlight.evidentMessageId
|
|
2791
3567
|
});
|
|
2792
3568
|
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3569
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2793
3570
|
try {
|
|
2794
3571
|
await this.markDone(
|
|
2795
3572
|
conv.id,
|
|
2796
3573
|
inFlight.evidentMessageId,
|
|
2797
3574
|
sessionId,
|
|
2798
3575
|
inFlight.opencodeMessageId,
|
|
2799
|
-
title
|
|
3576
|
+
title,
|
|
3577
|
+
usage
|
|
2800
3578
|
);
|
|
2801
3579
|
} catch (err) {
|
|
2802
3580
|
if (err instanceof ChannelAuthError) throw err;
|
|
@@ -2843,8 +3621,9 @@ var ChannelDriver = class {
|
|
|
2843
3621
|
conversation_id: conv.id,
|
|
2844
3622
|
message_id: inFlight.evidentMessageId
|
|
2845
3623
|
});
|
|
3624
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2846
3625
|
try {
|
|
2847
|
-
await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
|
|
3626
|
+
await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
|
|
2848
3627
|
} catch (err) {
|
|
2849
3628
|
if (err instanceof ChannelAuthError) throw err;
|
|
2850
3629
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3081,7 +3860,8 @@ var ChannelDriver = class {
|
|
|
3081
3860
|
});
|
|
3082
3861
|
try {
|
|
3083
3862
|
const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
|
|
3084
|
-
|
|
3863
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
3864
|
+
await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
|
|
3085
3865
|
} catch (err) {
|
|
3086
3866
|
if (err instanceof ChannelAuthError) throw err;
|
|
3087
3867
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3109,6 +3889,7 @@ var ChannelDriver = class {
|
|
|
3109
3889
|
}
|
|
3110
3890
|
if (state === "failed") {
|
|
3111
3891
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3892
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
3112
3893
|
this.log({
|
|
3113
3894
|
level: "error",
|
|
3114
3895
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3116,7 +3897,7 @@ var ChannelDriver = class {
|
|
|
3116
3897
|
message_id: row.id
|
|
3117
3898
|
});
|
|
3118
3899
|
try {
|
|
3119
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2);
|
|
3900
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
3120
3901
|
} catch (err) {
|
|
3121
3902
|
if (err instanceof ChannelAuthError) throw err;
|
|
3122
3903
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3544,19 +4325,36 @@ var ChannelDriver = class {
|
|
|
3544
4325
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3545
4326
|
return parent;
|
|
3546
4327
|
}
|
|
4328
|
+
/**
|
|
4329
|
+
* OpenCode's synchronous default session title (e.g.
|
|
4330
|
+
* `"New session - 1737800000000"`), assigned immediately when a session is
|
|
4331
|
+
* created — before OpenCode's async LLM-based auto-titling later renames it
|
|
4332
|
+
* mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
|
|
4333
|
+
* timestamp suffix's exact format is deliberately NOT matched, since the prefix
|
|
4334
|
+
* alone is the stable, cheap signal and over-anchoring on the timestamp
|
|
4335
|
+
* representation risks silently breaking if OpenCode ever changes it. Accepted
|
|
4336
|
+
* trade-off: a genuine LLM-assigned title that happens to literally start with
|
|
4337
|
+
* this prefix would also fail to latch (see `resolveSessionTitle`) —
|
|
4338
|
+
* vanishingly unlikely in practice, and deliberately not engineered around.
|
|
4339
|
+
*/
|
|
4340
|
+
static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
|
|
3547
4341
|
/**
|
|
3548
4342
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3549
4343
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3550
4344
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3551
4345
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3552
4346
|
* Best-effort:
|
|
3553
|
-
* - a resolved NON-EMPTY title
|
|
4347
|
+
* - a resolved NON-EMPTY title that does NOT match
|
|
4348
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
|
|
3554
4349
|
* won't later un-name), so we do NOT re-GET `/session/:id` every tick;
|
|
3555
|
-
* - while the title is still absent
|
|
3556
|
-
*
|
|
3557
|
-
*
|
|
3558
|
-
*
|
|
3559
|
-
*
|
|
4350
|
+
* - while the title is still absent, empty, or matches the OpenCode
|
|
4351
|
+
* placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
|
|
4352
|
+
* asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
|
|
4353
|
+
* the cache unresolved and re-fetch on the next need so a later call (e.g. at
|
|
4354
|
+
* `done`) picks up the name assigned in the meantime. Such a call returns
|
|
4355
|
+
* `null` (omit the title on THIS PATCH) without caching. If a session is
|
|
4356
|
+
* never renamed, the title is omitted forever rather than ever persisting
|
|
4357
|
+
* the placeholder as a last resort;
|
|
3560
4358
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3561
4359
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3562
4360
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3569,7 +4367,7 @@ var ChannelDriver = class {
|
|
|
3569
4367
|
if (res.ok) {
|
|
3570
4368
|
const body = await res.json();
|
|
3571
4369
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3572
|
-
if (title.length > 0) {
|
|
4370
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3573
4371
|
this.sessionTitles.set(sessionId, title);
|
|
3574
4372
|
return title;
|
|
3575
4373
|
}
|
|
@@ -3719,7 +4517,7 @@ var ChannelDriver = class {
|
|
|
3719
4517
|
// Evident API calls (combinedAuth thread routes)
|
|
3720
4518
|
async getPendingConversations() {
|
|
3721
4519
|
const res = await this.fetchImpl(
|
|
3722
|
-
`${this.apiUrl}/
|
|
4520
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
|
|
3723
4521
|
{
|
|
3724
4522
|
headers: { Authorization: this.getAuthHeader() }
|
|
3725
4523
|
}
|
|
@@ -3737,7 +4535,7 @@ var ChannelDriver = class {
|
|
|
3737
4535
|
}
|
|
3738
4536
|
async getPendingMessages(conversationId) {
|
|
3739
4537
|
const res = await this.fetchImpl(
|
|
3740
|
-
`${this.apiUrl}/
|
|
4538
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
|
|
3741
4539
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3742
4540
|
);
|
|
3743
4541
|
this.assertAuth(res, "fetching pending messages");
|
|
@@ -3761,7 +4559,7 @@ var ChannelDriver = class {
|
|
|
3761
4559
|
*/
|
|
3762
4560
|
async getProcessingMessages() {
|
|
3763
4561
|
const res = await this.fetchImpl(
|
|
3764
|
-
`${this.apiUrl}/
|
|
4562
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
|
|
3765
4563
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3766
4564
|
);
|
|
3767
4565
|
this.assertAuth(res, "fetching processing messages");
|
|
@@ -3775,6 +4573,32 @@ var ChannelDriver = class {
|
|
|
3775
4573
|
}
|
|
3776
4574
|
return messages;
|
|
3777
4575
|
}
|
|
4576
|
+
/**
|
|
4577
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
4578
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
4579
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
4580
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
4581
|
+
*
|
|
4582
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
4583
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
4584
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
4585
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
4586
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
4587
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
4588
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
4589
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
4590
|
+
* stick.
|
|
4591
|
+
*/
|
|
4592
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
4593
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
4594
|
+
this.log({
|
|
4595
|
+
level: "debug",
|
|
4596
|
+
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)}`,
|
|
4597
|
+
conversation_id: conversationId,
|
|
4598
|
+
message_id: messageId
|
|
4599
|
+
});
|
|
4600
|
+
return {};
|
|
4601
|
+
}
|
|
3778
4602
|
/**
|
|
3779
4603
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3780
4604
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3798,13 +4622,13 @@ var ChannelDriver = class {
|
|
|
3798
4622
|
*/
|
|
3799
4623
|
async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
3800
4624
|
const res = await this.fetchImpl(
|
|
3801
|
-
`${this.apiUrl}/
|
|
4625
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3802
4626
|
{
|
|
3803
4627
|
method: "PATCH",
|
|
3804
4628
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3805
4629
|
body: JSON.stringify({
|
|
3806
4630
|
status: "processing",
|
|
3807
|
-
|
|
4631
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3808
4632
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3809
4633
|
...title ? { title } : {}
|
|
3810
4634
|
})
|
|
@@ -3845,17 +4669,23 @@ var ChannelDriver = class {
|
|
|
3845
4669
|
* watcher retries next tick within the
|
|
3846
4670
|
* deadline, Finding 4).
|
|
3847
4671
|
*/
|
|
3848
|
-
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
4672
|
+
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
|
|
3849
4673
|
const res = await this.fetchImpl(
|
|
3850
|
-
`${this.apiUrl}/
|
|
4674
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3851
4675
|
{
|
|
3852
4676
|
method: "PATCH",
|
|
3853
4677
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3854
4678
|
body: JSON.stringify({
|
|
3855
4679
|
status: "done",
|
|
4680
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
4681
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
4682
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
4683
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
4684
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3856
4685
|
opencode_session_id: sessionId,
|
|
3857
4686
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3858
|
-
...title ? { title } : {}
|
|
4687
|
+
...title ? { title } : {},
|
|
4688
|
+
...usage ? usage : {}
|
|
3859
4689
|
})
|
|
3860
4690
|
}
|
|
3861
4691
|
);
|
|
@@ -3868,19 +4698,29 @@ var ChannelDriver = class {
|
|
|
3868
4698
|
}
|
|
3869
4699
|
/**
|
|
3870
4700
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3871
|
-
* when provided (issue #182)
|
|
3872
|
-
* `
|
|
3873
|
-
*
|
|
3874
|
-
*
|
|
4701
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
4702
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
4703
|
+
* session untouched (unused today; kept for API symmetry).
|
|
4704
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
4705
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
4706
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
4707
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
4708
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
4709
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
3875
4710
|
*/
|
|
3876
|
-
async markFailed(conversationId, messageId, sessionId, error2) {
|
|
4711
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
3877
4712
|
const body = { status: "failed" };
|
|
3878
|
-
if (sessionId
|
|
4713
|
+
if (sessionId === null) {
|
|
4714
|
+
body.opencode_session_id = null;
|
|
4715
|
+
} else if (sessionId !== void 0) {
|
|
4716
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
4717
|
+
}
|
|
3879
4718
|
if (error2 !== void 0) body.error = error2;
|
|
4719
|
+
if (usage) Object.assign(body, usage);
|
|
3880
4720
|
await this.callWithRetry(
|
|
3881
4721
|
"marking message as failed",
|
|
3882
4722
|
() => this.fetchImpl(
|
|
3883
|
-
`${this.apiUrl}/
|
|
4723
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3884
4724
|
{
|
|
3885
4725
|
method: "PATCH",
|
|
3886
4726
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3907,7 +4747,7 @@ var ChannelDriver = class {
|
|
|
3907
4747
|
async postSignal(conversationId, messageId, signal, extra) {
|
|
3908
4748
|
try {
|
|
3909
4749
|
const res = await this.fetchImpl(
|
|
3910
|
-
`${this.apiUrl}/
|
|
4750
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
|
|
3911
4751
|
{
|
|
3912
4752
|
method: "POST",
|
|
3913
4753
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3936,7 +4776,7 @@ var ChannelDriver = class {
|
|
|
3936
4776
|
}
|
|
3937
4777
|
async persistSession(conversationId, sessionId) {
|
|
3938
4778
|
const res = await this.fetchImpl(
|
|
3939
|
-
`${this.apiUrl}/
|
|
4779
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
|
|
3940
4780
|
{
|
|
3941
4781
|
method: "PATCH",
|
|
3942
4782
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3962,7 +4802,7 @@ var ChannelDriver = class {
|
|
|
3962
4802
|
await this.callWithRetry(
|
|
3963
4803
|
"reporting interactive event",
|
|
3964
4804
|
() => this.fetchImpl(
|
|
3965
|
-
`${this.apiUrl}/
|
|
4805
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
|
|
3966
4806
|
{
|
|
3967
4807
|
method: "POST",
|
|
3968
4808
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -4202,12 +5042,14 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4202
5042
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
4203
5043
|
}
|
|
4204
5044
|
}
|
|
5045
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
4205
5046
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4206
5047
|
const apiUrl = getApiUrlConfig();
|
|
4207
5048
|
try {
|
|
4208
|
-
const response = await fetch(`${apiUrl}/
|
|
5049
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4209
5050
|
method: "POST",
|
|
4210
|
-
headers: { Authorization: authHeader }
|
|
5051
|
+
headers: { Authorization: authHeader },
|
|
5052
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
4211
5053
|
});
|
|
4212
5054
|
if (!response.ok) {
|
|
4213
5055
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -4218,13 +5060,41 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4218
5060
|
}
|
|
4219
5061
|
return { ok: true };
|
|
4220
5062
|
} catch (error2) {
|
|
4221
|
-
return { ok: false, error:
|
|
5063
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5064
|
+
}
|
|
5065
|
+
}
|
|
5066
|
+
function describeBestEffortError(error2) {
|
|
5067
|
+
const name = error2?.name;
|
|
5068
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5069
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5070
|
+
}
|
|
5071
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5072
|
+
}
|
|
5073
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5074
|
+
try {
|
|
5075
|
+
const apiUrl = getApiUrlConfig();
|
|
5076
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5077
|
+
method: "POST",
|
|
5078
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5079
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5080
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5081
|
+
});
|
|
5082
|
+
if (!response.ok) {
|
|
5083
|
+
const serverMessage = await readErrorMessage(response);
|
|
5084
|
+
return {
|
|
5085
|
+
ok: false,
|
|
5086
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5087
|
+
};
|
|
5088
|
+
}
|
|
5089
|
+
return { ok: true };
|
|
5090
|
+
} catch (error2) {
|
|
5091
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
4222
5092
|
}
|
|
4223
5093
|
}
|
|
4224
5094
|
async function getAgentInfo(agentId, authHeader) {
|
|
4225
5095
|
const apiUrl = getApiUrlConfig();
|
|
4226
5096
|
try {
|
|
4227
|
-
const response = await fetch(`${apiUrl}/
|
|
5097
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}`, {
|
|
4228
5098
|
headers: { Authorization: authHeader }
|
|
4229
5099
|
});
|
|
4230
5100
|
if (response.status === 401) {
|
|
@@ -4268,6 +5138,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
4268
5138
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
4269
5139
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4270
5140
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5141
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
4271
5142
|
function resolveLogLevel(options) {
|
|
4272
5143
|
const accepted = Object.keys(LOG_LEVELS);
|
|
4273
5144
|
const validate = (value, source) => {
|
|
@@ -4291,6 +5162,34 @@ function resolveLogLevel(options) {
|
|
|
4291
5162
|
}
|
|
4292
5163
|
return "info";
|
|
4293
5164
|
}
|
|
5165
|
+
function resolveFileSyncDirectories(raw, homeDir) {
|
|
5166
|
+
const directories = [];
|
|
5167
|
+
for (const entry of raw ?? []) {
|
|
5168
|
+
const trimmed = entry.trim();
|
|
5169
|
+
if (trimmed === "") {
|
|
5170
|
+
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5171
|
+
}
|
|
5172
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
|
|
5173
|
+
if (!isAbsolute2(expanded)) {
|
|
5174
|
+
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5175
|
+
}
|
|
5176
|
+
const normalized = resolvePath(expanded);
|
|
5177
|
+
if (parse(normalized).root === normalized) {
|
|
5178
|
+
throw new Error(
|
|
5179
|
+
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
5180
|
+
);
|
|
5181
|
+
}
|
|
5182
|
+
if (!directories.includes(normalized)) {
|
|
5183
|
+
directories.push(normalized);
|
|
5184
|
+
}
|
|
5185
|
+
}
|
|
5186
|
+
if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
|
|
5187
|
+
throw new Error(
|
|
5188
|
+
`--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
|
|
5189
|
+
);
|
|
5190
|
+
}
|
|
5191
|
+
return directories;
|
|
5192
|
+
}
|
|
4294
5193
|
function meetsThreshold(state, level) {
|
|
4295
5194
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4296
5195
|
}
|
|
@@ -4412,18 +5311,29 @@ async function handleAuthError(state, error2) {
|
|
|
4412
5311
|
async function driveChannels(state, driver) {
|
|
4413
5312
|
let idlePolls = 0;
|
|
4414
5313
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5314
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4415
5315
|
while (state.running) {
|
|
4416
5316
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4417
5317
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4418
5318
|
if (state.interactive) displayStatus(state);
|
|
4419
5319
|
await state.connection.reconnectPromise;
|
|
4420
5320
|
}
|
|
5321
|
+
const carriedOverFileSync = driver.fileSyncActivity().inFlight;
|
|
5322
|
+
void driver.syncPendingFiles().catch(
|
|
5323
|
+
(error2) => logActivity(state, {
|
|
5324
|
+
type: "error",
|
|
5325
|
+
error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5326
|
+
})
|
|
5327
|
+
);
|
|
4421
5328
|
try {
|
|
4422
5329
|
const processed = await driver.drainPending();
|
|
4423
5330
|
state.messageCount += processed;
|
|
4424
5331
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4425
5332
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4426
|
-
|
|
5333
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5334
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
5335
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
5336
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4427
5337
|
idlePolls = 0;
|
|
4428
5338
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4429
5339
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4452,7 +5362,7 @@ async function driveChannels(state, driver) {
|
|
|
4452
5362
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4453
5363
|
if (state.interactive) displayStatus(state);
|
|
4454
5364
|
}
|
|
4455
|
-
await new Promise((
|
|
5365
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4456
5366
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4457
5367
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4458
5368
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4555,7 +5465,18 @@ async function notifyOffline(state) {
|
|
|
4555
5465
|
if (state.interactive) displayStatus(state);
|
|
4556
5466
|
}
|
|
4557
5467
|
}
|
|
5468
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
5469
|
+
const startedAt = Date.now();
|
|
5470
|
+
try {
|
|
5471
|
+
return await run2();
|
|
5472
|
+
} finally {
|
|
5473
|
+
const elapsedMs = Date.now() - startedAt;
|
|
5474
|
+
durations[name] = elapsedMs;
|
|
5475
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
5476
|
+
}
|
|
5477
|
+
}
|
|
4558
5478
|
async function cleanup(state, opts = {}) {
|
|
5479
|
+
const durations = {};
|
|
4559
5480
|
state.running = false;
|
|
4560
5481
|
for (const timer of state.sessionCleanupTimers) {
|
|
4561
5482
|
clearInterval(timer);
|
|
@@ -4569,7 +5490,13 @@ async function cleanup(state, opts = {}) {
|
|
|
4569
5490
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4570
5491
|
displayStatus(state);
|
|
4571
5492
|
}
|
|
4572
|
-
const
|
|
5493
|
+
const driver = state.channelDriver;
|
|
5494
|
+
const settled = await timeShutdownPhase(
|
|
5495
|
+
state,
|
|
5496
|
+
durations,
|
|
5497
|
+
"drain",
|
|
5498
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
5499
|
+
);
|
|
4573
5500
|
if (!settled) {
|
|
4574
5501
|
logActivity(state, {
|
|
4575
5502
|
type: "info",
|
|
@@ -4578,13 +5505,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4578
5505
|
if (state.interactive) displayStatus(state);
|
|
4579
5506
|
}
|
|
4580
5507
|
}
|
|
4581
|
-
await notifyOffline(state);
|
|
5508
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
4582
5509
|
if (state.connection) {
|
|
4583
|
-
state.connection
|
|
5510
|
+
const connection = state.connection;
|
|
5511
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
4584
5512
|
state.connection = null;
|
|
4585
5513
|
}
|
|
4586
5514
|
if (state.opencodeProcess) {
|
|
4587
|
-
|
|
5515
|
+
const opencodeProcess = state.opencodeProcess;
|
|
5516
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
4588
5517
|
if (state.interactive) {
|
|
4589
5518
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
4590
5519
|
displayStatus(state);
|
|
@@ -4593,12 +5522,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4593
5522
|
}
|
|
4594
5523
|
state.opencodeProcess = null;
|
|
4595
5524
|
}
|
|
5525
|
+
return durations;
|
|
4596
5526
|
}
|
|
4597
5527
|
async function run(options) {
|
|
4598
5528
|
const interactive = isInteractive(options.json);
|
|
4599
5529
|
let logLevel;
|
|
5530
|
+
let fileSyncDirectories;
|
|
4600
5531
|
try {
|
|
4601
5532
|
logLevel = resolveLogLevel(options);
|
|
5533
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
|
|
4602
5534
|
} catch (error2) {
|
|
4603
5535
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4604
5536
|
if (options.json) {
|
|
@@ -4611,7 +5543,7 @@ async function run(options) {
|
|
|
4611
5543
|
return;
|
|
4612
5544
|
}
|
|
4613
5545
|
const state = {
|
|
4614
|
-
agentId: options.agent || "",
|
|
5546
|
+
agentId: options.runner || options.agent || "",
|
|
4615
5547
|
agentName: null,
|
|
4616
5548
|
port: options.port ?? 4096,
|
|
4617
5549
|
conversationFilter: options.conversation ?? null,
|
|
@@ -4633,6 +5565,24 @@ async function run(options) {
|
|
|
4633
5565
|
sessionCleanupTimers: [],
|
|
4634
5566
|
authHeader: ""
|
|
4635
5567
|
};
|
|
5568
|
+
if (fileSyncDirectories.length > 0) {
|
|
5569
|
+
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5570
|
+
} else {
|
|
5571
|
+
log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
|
|
5572
|
+
}
|
|
5573
|
+
if (!options.runner && options.agent) {
|
|
5574
|
+
telemetry.info(
|
|
5575
|
+
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
5576
|
+
"Deprecated --agent flag used instead of --runner",
|
|
5577
|
+
{ command: "run" },
|
|
5578
|
+
state.agentId
|
|
5579
|
+
);
|
|
5580
|
+
const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
|
|
5581
|
+
log2(state, agentFlagNotice, "warn");
|
|
5582
|
+
if (state.interactive && !state.json) {
|
|
5583
|
+
logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
|
|
5584
|
+
}
|
|
5585
|
+
}
|
|
4636
5586
|
if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
|
|
4637
5587
|
log2(
|
|
4638
5588
|
state,
|
|
@@ -4643,14 +5593,38 @@ async function run(options) {
|
|
|
4643
5593
|
const handleSignal = async () => {
|
|
4644
5594
|
if (state.shuttingDown) return;
|
|
4645
5595
|
state.shuttingDown = true;
|
|
5596
|
+
const shutdownStartedAt = Date.now();
|
|
4646
5597
|
if (state.interactive) {
|
|
4647
5598
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
4648
5599
|
displayStatus(state);
|
|
4649
5600
|
} else {
|
|
4650
5601
|
log2(state, "Shutting down...");
|
|
4651
5602
|
}
|
|
4652
|
-
await cleanup(state, { graceful: true });
|
|
4653
|
-
|
|
5603
|
+
const durations = await cleanup(state, { graceful: true });
|
|
5604
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
5605
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
5606
|
+
let timer;
|
|
5607
|
+
const flushed = shutdownTelemetry().then(
|
|
5608
|
+
() => true,
|
|
5609
|
+
(error2) => {
|
|
5610
|
+
log2(
|
|
5611
|
+
state,
|
|
5612
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
5613
|
+
"warn"
|
|
5614
|
+
);
|
|
5615
|
+
return true;
|
|
5616
|
+
}
|
|
5617
|
+
);
|
|
5618
|
+
const timedOut = new Promise((resolve3) => {
|
|
5619
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
5620
|
+
});
|
|
5621
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
5622
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
5623
|
+
}
|
|
5624
|
+
clearTimeout(timer);
|
|
5625
|
+
});
|
|
5626
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
5627
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
4654
5628
|
process.exit(0);
|
|
4655
5629
|
};
|
|
4656
5630
|
process.on("SIGINT", handleSignal);
|
|
@@ -4661,7 +5635,9 @@ async function run(options) {
|
|
|
4661
5635
|
if (!interactive) {
|
|
4662
5636
|
printError("Authentication required");
|
|
4663
5637
|
blank();
|
|
4664
|
-
console.log(
|
|
5638
|
+
console.log(
|
|
5639
|
+
chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
|
|
5640
|
+
);
|
|
4665
5641
|
console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
|
|
4666
5642
|
blank();
|
|
4667
5643
|
process.exit(1);
|
|
@@ -4675,6 +5651,25 @@ async function run(options) {
|
|
|
4675
5651
|
);
|
|
4676
5652
|
}
|
|
4677
5653
|
state.authHeader = getAuthHeader(credentials2);
|
|
5654
|
+
if (credentials2.notice) {
|
|
5655
|
+
log2(state, credentials2.notice, "warn");
|
|
5656
|
+
if (state.interactive && !state.json) {
|
|
5657
|
+
logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
|
|
5658
|
+
}
|
|
5659
|
+
}
|
|
5660
|
+
if (credentials2.keySource === "agent_key") {
|
|
5661
|
+
telemetry.info(
|
|
5662
|
+
EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
|
|
5663
|
+
"Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
|
|
5664
|
+
{ command: "run" },
|
|
5665
|
+
state.agentId
|
|
5666
|
+
);
|
|
5667
|
+
const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
|
|
5668
|
+
log2(state, agentKeyNotice, "warn");
|
|
5669
|
+
if (state.interactive && !state.json) {
|
|
5670
|
+
logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
|
|
5671
|
+
}
|
|
5672
|
+
}
|
|
4678
5673
|
if (!state.agentId) {
|
|
4679
5674
|
if (credentials2.authType === "agent_key") {
|
|
4680
5675
|
const resolved = await resolveAgentIdFromKey(state.authHeader);
|
|
@@ -4692,9 +5687,15 @@ async function run(options) {
|
|
|
4692
5687
|
process.exit(1);
|
|
4693
5688
|
}
|
|
4694
5689
|
} else {
|
|
4695
|
-
printError(
|
|
5690
|
+
printError(
|
|
5691
|
+
"--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
|
|
5692
|
+
);
|
|
4696
5693
|
blank();
|
|
4697
|
-
console.log(
|
|
5694
|
+
console.log(
|
|
5695
|
+
chalk6.dim(
|
|
5696
|
+
"Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
|
|
5697
|
+
)
|
|
5698
|
+
);
|
|
4698
5699
|
blank();
|
|
4699
5700
|
process.exit(1);
|
|
4700
5701
|
}
|
|
@@ -4737,6 +5738,21 @@ async function run(options) {
|
|
|
4737
5738
|
}
|
|
4738
5739
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
4739
5740
|
state.agentName = validation.agent.name;
|
|
5741
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
5742
|
+
if (microvmId) {
|
|
5743
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
5744
|
+
if (reported.ok) {
|
|
5745
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
5746
|
+
} else {
|
|
5747
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
5748
|
+
log2(state, message, "warn");
|
|
5749
|
+
if (state.interactive && !state.json) {
|
|
5750
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
5751
|
+
}
|
|
5752
|
+
}
|
|
5753
|
+
} else {
|
|
5754
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
5755
|
+
}
|
|
4740
5756
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
4741
5757
|
try {
|
|
4742
5758
|
const oc = await ensureOpenCodeRunning({
|
|
@@ -4758,6 +5774,21 @@ async function run(options) {
|
|
|
4758
5774
|
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
4759
5775
|
}
|
|
4760
5776
|
}
|
|
5777
|
+
const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
|
|
5778
|
+
if (noProviderWarning) {
|
|
5779
|
+
log2(state, noProviderWarning, "warn");
|
|
5780
|
+
if (state.interactive && !state.json) {
|
|
5781
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
5782
|
+
blank();
|
|
5783
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
5784
|
+
console.log(
|
|
5785
|
+
chalk6.dim(
|
|
5786
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
5787
|
+
)
|
|
5788
|
+
);
|
|
5789
|
+
blank();
|
|
5790
|
+
}
|
|
5791
|
+
}
|
|
4761
5792
|
} catch (error2) {
|
|
4762
5793
|
ocSpinner?.fail(error2.message);
|
|
4763
5794
|
throw error2;
|
|
@@ -4770,6 +5801,10 @@ async function run(options) {
|
|
|
4770
5801
|
getAuthHeader: () => state.authHeader,
|
|
4771
5802
|
conversationFilter: state.conversationFilter,
|
|
4772
5803
|
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
5804
|
+
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
5805
|
+
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
5806
|
+
fileSyncDirectories,
|
|
5807
|
+
homeDir: homedir2(),
|
|
4773
5808
|
log: (entry) => (
|
|
4774
5809
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4775
5810
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4851,6 +5886,12 @@ async function run(options) {
|
|
|
4851
5886
|
onDrainPing: () => {
|
|
4852
5887
|
if (!state.running) return;
|
|
4853
5888
|
logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
|
|
5889
|
+
void channelDriver.syncPendingFiles().catch(
|
|
5890
|
+
(error2) => logActivity(state, {
|
|
5891
|
+
type: "error",
|
|
5892
|
+
error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5893
|
+
})
|
|
5894
|
+
);
|
|
4854
5895
|
channelDriver.drainPending().then((processed) => {
|
|
4855
5896
|
if (processed > 0) {
|
|
4856
5897
|
state.messageCount += processed;
|
|
@@ -4909,7 +5950,7 @@ async function run(options) {
|
|
|
4909
5950
|
}
|
|
4910
5951
|
telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
|
|
4911
5952
|
command: "run",
|
|
4912
|
-
agentId: options.agent
|
|
5953
|
+
agentId: options.runner || options.agent
|
|
4913
5954
|
});
|
|
4914
5955
|
await shutdownTelemetry();
|
|
4915
5956
|
process.exit(1);
|
|
@@ -4934,7 +5975,10 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
4934
5975
|
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);
|
|
4935
5976
|
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 }));
|
|
4936
5977
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
4937
|
-
program.command("run").description("Connect to Evident and process messages").option("
|
|
5978
|
+
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(
|
|
5979
|
+
"-a, --agent [id]",
|
|
5980
|
+
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
5981
|
+
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
4938
5982
|
"--log-level <level>",
|
|
4939
5983
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
4940
5984
|
).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(
|
|
@@ -4946,10 +5990,16 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4946
5990
|
).option(
|
|
4947
5991
|
"--session-cleanup-interval <duration>",
|
|
4948
5992
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
5993
|
+
).option(
|
|
5994
|
+
"--enable-file-sync-to <dir>",
|
|
5995
|
+
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
5996
|
+
(value, previous) => previous.concat([value]),
|
|
5997
|
+
[]
|
|
4949
5998
|
).action(
|
|
4950
5999
|
(options) => {
|
|
4951
6000
|
run({
|
|
4952
6001
|
agent: options.agent,
|
|
6002
|
+
runner: options.runner,
|
|
4953
6003
|
port: parseInt(options.port, 10),
|
|
4954
6004
|
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
4955
6005
|
// resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
|
|
@@ -4961,7 +6011,10 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4961
6011
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
4962
6012
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
4963
6013
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
4964
|
-
sessionCleanupInterval: options.sessionCleanupInterval
|
|
6014
|
+
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6015
|
+
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6016
|
+
// resolveFileSyncDirectories.
|
|
6017
|
+
enableFileSyncTo: options.enableFileSyncTo
|
|
4965
6018
|
});
|
|
4966
6019
|
}
|
|
4967
6020
|
);
|