@evident-ai/cli 3.1.1-dev.9ff0701 → 3.1.1-dev.b4e1c75
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 +1487 -161
- 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);
|
|
@@ -1386,6 +1532,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1386
1532
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1387
1533
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1388
1534
|
}
|
|
1535
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1536
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1537
|
+
}
|
|
1389
1538
|
function messageError(messages, userMessageId) {
|
|
1390
1539
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1391
1540
|
const error2 = errorOf(reply);
|
|
@@ -1405,6 +1554,37 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
|
1405
1554
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1406
1555
|
);
|
|
1407
1556
|
}
|
|
1557
|
+
async function hasAnyConfiguredProvider(port) {
|
|
1558
|
+
try {
|
|
1559
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1560
|
+
if (!res.ok) {
|
|
1561
|
+
console.error(
|
|
1562
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1563
|
+
);
|
|
1564
|
+
return null;
|
|
1565
|
+
}
|
|
1566
|
+
const body = await res.json();
|
|
1567
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1568
|
+
console.error(
|
|
1569
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
1570
|
+
);
|
|
1571
|
+
return null;
|
|
1572
|
+
}
|
|
1573
|
+
const defaults2 = body.default;
|
|
1574
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
1575
|
+
console.error(
|
|
1576
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
1577
|
+
);
|
|
1578
|
+
return null;
|
|
1579
|
+
}
|
|
1580
|
+
return Object.keys(defaults2).length > 0;
|
|
1581
|
+
} catch (err) {
|
|
1582
|
+
console.error(
|
|
1583
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1584
|
+
);
|
|
1585
|
+
return null;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1408
1588
|
|
|
1409
1589
|
// src/lib/opencode/session-cleanup.ts
|
|
1410
1590
|
var DURATION_UNIT_MS = {
|
|
@@ -1563,10 +1743,11 @@ var StreamForwarder = class {
|
|
|
1563
1743
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1564
1744
|
*/
|
|
1565
1745
|
abortAll() {
|
|
1566
|
-
for (const stream of this.inflight.
|
|
1746
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1567
1747
|
try {
|
|
1568
1748
|
stream.abort();
|
|
1569
|
-
} catch {
|
|
1749
|
+
} catch (err) {
|
|
1750
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1570
1751
|
}
|
|
1571
1752
|
}
|
|
1572
1753
|
this.inflight.clear();
|
|
@@ -1600,12 +1781,12 @@ var StreamForwarder = class {
|
|
|
1600
1781
|
let endBody;
|
|
1601
1782
|
if (has_body) {
|
|
1602
1783
|
const chunks = [];
|
|
1603
|
-
bodyPromise = new Promise((
|
|
1784
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1604
1785
|
pushBody = (buf) => {
|
|
1605
1786
|
chunks.push(buf);
|
|
1606
1787
|
};
|
|
1607
1788
|
endBody = () => {
|
|
1608
|
-
|
|
1789
|
+
resolve3(Buffer.concat(chunks));
|
|
1609
1790
|
};
|
|
1610
1791
|
});
|
|
1611
1792
|
}
|
|
@@ -1716,31 +1897,20 @@ function connectTunnel(options) {
|
|
|
1716
1897
|
onConnected,
|
|
1717
1898
|
onDisconnected,
|
|
1718
1899
|
onError,
|
|
1719
|
-
onRequest,
|
|
1720
1900
|
onResponse,
|
|
1721
1901
|
onInfo,
|
|
1722
1902
|
onDrainPing
|
|
1723
1903
|
} = options;
|
|
1724
1904
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1725
1905
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1726
|
-
return new Promise((
|
|
1906
|
+
return new Promise((resolve3, reject) => {
|
|
1727
1907
|
const ws = new WebSocket2(url, {
|
|
1728
1908
|
headers: {
|
|
1729
1909
|
Authorization: authHeader
|
|
1730
1910
|
}
|
|
1731
1911
|
});
|
|
1732
|
-
const streamStartTimes = /* @__PURE__ */ new Map();
|
|
1733
1912
|
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
|
-
},
|
|
1913
|
+
onHead: () => onResponse?.(),
|
|
1744
1914
|
onDrainPing: () => onDrainPing?.()
|
|
1745
1915
|
});
|
|
1746
1916
|
const connectionTimeout = setTimeout(() => {
|
|
@@ -1788,7 +1958,7 @@ function connectTunnel(options) {
|
|
|
1788
1958
|
clearTimeout(connectionTimeout);
|
|
1789
1959
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1790
1960
|
onConnected?.(connectedAgentId);
|
|
1791
|
-
|
|
1961
|
+
resolve3({
|
|
1792
1962
|
ws,
|
|
1793
1963
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1794
1964
|
});
|
|
@@ -1816,7 +1986,6 @@ function connectTunnel(options) {
|
|
|
1816
1986
|
ws.on("close", (code, reason) => {
|
|
1817
1987
|
const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
|
|
1818
1988
|
forwarder.abortAll();
|
|
1819
|
-
streamStartTimes.clear();
|
|
1820
1989
|
onDisconnected?.(code, reasonStr);
|
|
1821
1990
|
});
|
|
1822
1991
|
});
|
|
@@ -1851,7 +2020,11 @@ var RunnerConnection = class {
|
|
|
1851
2020
|
if (this.connection) {
|
|
1852
2021
|
try {
|
|
1853
2022
|
this.connection.close();
|
|
1854
|
-
} catch {
|
|
2023
|
+
} catch (err) {
|
|
2024
|
+
log("error", "runner_connection_close_failed", {
|
|
2025
|
+
agent_id: this.resolvedAgentId,
|
|
2026
|
+
...errorFields(err)
|
|
2027
|
+
});
|
|
1855
2028
|
}
|
|
1856
2029
|
this.connection = null;
|
|
1857
2030
|
}
|
|
@@ -1903,6 +2076,416 @@ var RunnerConnection = class {
|
|
|
1903
2076
|
}
|
|
1904
2077
|
};
|
|
1905
2078
|
|
|
2079
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2080
|
+
import { writeFileSync } from "fs";
|
|
2081
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2082
|
+
try {
|
|
2083
|
+
writeFileSync(path, `${agentId}
|
|
2084
|
+
`);
|
|
2085
|
+
return { ok: true };
|
|
2086
|
+
} catch (error2) {
|
|
2087
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
// src/lib/channels/driver.ts
|
|
2092
|
+
import { homedir } from "os";
|
|
2093
|
+
|
|
2094
|
+
// src/lib/file-push.ts
|
|
2095
|
+
import { randomUUID } from "crypto";
|
|
2096
|
+
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2097
|
+
import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
|
|
2098
|
+
var FILE_MODE = 384;
|
|
2099
|
+
var DIRECTORY_MODE = 448;
|
|
2100
|
+
async function writePushedFile(request) {
|
|
2101
|
+
const { requestedPath, content, allowedDirectories, homeDir } = request;
|
|
2102
|
+
const bytes = content.byteLength;
|
|
2103
|
+
if (allowedDirectories.length === 0) {
|
|
2104
|
+
return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
2105
|
+
path: requestedPath,
|
|
2106
|
+
bytes
|
|
2107
|
+
});
|
|
2108
|
+
}
|
|
2109
|
+
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
2110
|
+
return refuse(
|
|
2111
|
+
"file_too_large",
|
|
2112
|
+
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
2113
|
+
{
|
|
2114
|
+
path: requestedPath,
|
|
2115
|
+
bytes
|
|
2116
|
+
}
|
|
2117
|
+
);
|
|
2118
|
+
}
|
|
2119
|
+
const candidate = expandAndValidate(requestedPath, homeDir);
|
|
2120
|
+
if (candidate === null) {
|
|
2121
|
+
return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
2122
|
+
path: requestedPath,
|
|
2123
|
+
bytes
|
|
2124
|
+
});
|
|
2125
|
+
}
|
|
2126
|
+
try {
|
|
2127
|
+
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2128
|
+
dirname2(candidate)
|
|
2129
|
+
);
|
|
2130
|
+
const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
|
|
2131
|
+
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2132
|
+
if (allowedDirectory === null) {
|
|
2133
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2134
|
+
path: realTarget,
|
|
2135
|
+
bytes
|
|
2136
|
+
});
|
|
2137
|
+
}
|
|
2138
|
+
if (missingSegments.length > 0) {
|
|
2139
|
+
await createMissingDirectories(existingAncestor, missingSegments);
|
|
2140
|
+
const realParent = await realpath(dirname2(realTarget));
|
|
2141
|
+
if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
2142
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2143
|
+
path: realTarget,
|
|
2144
|
+
bytes,
|
|
2145
|
+
reason: "parent_changed_after_create"
|
|
2146
|
+
});
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
await writeAtomically(realTarget, content);
|
|
2150
|
+
log("info", "file_push_written", { path: realTarget, bytes });
|
|
2151
|
+
return { ok: true, path: realTarget };
|
|
2152
|
+
} catch (err) {
|
|
2153
|
+
const errno = err.code ?? "UNKNOWN";
|
|
2154
|
+
return refuse("write_failed", `The runner could not write the file (${errno}).`, {
|
|
2155
|
+
path: candidate,
|
|
2156
|
+
bytes,
|
|
2157
|
+
errno,
|
|
2158
|
+
...errorFields(err)
|
|
2159
|
+
});
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
function expandAndValidate(requestedPath, homeDir) {
|
|
2163
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2164
|
+
return null;
|
|
2165
|
+
}
|
|
2166
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2167
|
+
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2168
|
+
return null;
|
|
2169
|
+
}
|
|
2170
|
+
if (!isAbsolute(expanded)) {
|
|
2171
|
+
return null;
|
|
2172
|
+
}
|
|
2173
|
+
const candidate = resolve2(expanded);
|
|
2174
|
+
const name = basename(candidate);
|
|
2175
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
2176
|
+
}
|
|
2177
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
2178
|
+
const missingSegments = [];
|
|
2179
|
+
let current = directory;
|
|
2180
|
+
for (; ; ) {
|
|
2181
|
+
try {
|
|
2182
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
2183
|
+
} catch (err) {
|
|
2184
|
+
const parent = dirname2(current);
|
|
2185
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
2186
|
+
throw err;
|
|
2187
|
+
}
|
|
2188
|
+
missingSegments.unshift(basename(current));
|
|
2189
|
+
current = parent;
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
2194
|
+
for (const directory of allowedDirectories) {
|
|
2195
|
+
if (!isAbsolute(directory)) {
|
|
2196
|
+
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
2197
|
+
continue;
|
|
2198
|
+
}
|
|
2199
|
+
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
2200
|
+
if (realDirectory !== null && contains(realDirectory, realTarget)) {
|
|
2201
|
+
return realDirectory;
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
return null;
|
|
2205
|
+
}
|
|
2206
|
+
async function realpathCreatingIfMissing(directory) {
|
|
2207
|
+
try {
|
|
2208
|
+
return await realpath(directory);
|
|
2209
|
+
} catch (err) {
|
|
2210
|
+
if (err.code !== "ENOENT") {
|
|
2211
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2212
|
+
directory,
|
|
2213
|
+
reason: "unresolvable",
|
|
2214
|
+
...errorFields(err)
|
|
2215
|
+
});
|
|
2216
|
+
return null;
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
try {
|
|
2220
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
2221
|
+
await chmod(directory, DIRECTORY_MODE);
|
|
2222
|
+
return await realpath(directory);
|
|
2223
|
+
} catch (err) {
|
|
2224
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2225
|
+
directory,
|
|
2226
|
+
reason: "create_failed",
|
|
2227
|
+
...errorFields(err)
|
|
2228
|
+
});
|
|
2229
|
+
return null;
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
function contains(realDirectory, realTarget) {
|
|
2233
|
+
const rel = relative(realDirectory, realTarget);
|
|
2234
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
2235
|
+
}
|
|
2236
|
+
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2237
|
+
let current = existingAncestor;
|
|
2238
|
+
for (const segment of missingSegments) {
|
|
2239
|
+
current = join(current, segment);
|
|
2240
|
+
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2241
|
+
await chmod(current, DIRECTORY_MODE);
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
async function writeAtomically(realTarget, content) {
|
|
2245
|
+
const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2246
|
+
let handle;
|
|
2247
|
+
try {
|
|
2248
|
+
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
2249
|
+
await handle.writeFile(content);
|
|
2250
|
+
await handle.chmod(FILE_MODE);
|
|
2251
|
+
await handle.close();
|
|
2252
|
+
handle = void 0;
|
|
2253
|
+
await rename(temporaryPath, realTarget);
|
|
2254
|
+
} catch (err) {
|
|
2255
|
+
await discardTemporaryFile(temporaryPath, handle);
|
|
2256
|
+
throw err;
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
async function discardTemporaryFile(temporaryPath, handle) {
|
|
2260
|
+
try {
|
|
2261
|
+
await handle?.close();
|
|
2262
|
+
} catch (err) {
|
|
2263
|
+
log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2264
|
+
}
|
|
2265
|
+
try {
|
|
2266
|
+
await unlink(temporaryPath);
|
|
2267
|
+
} catch (err) {
|
|
2268
|
+
const errno = err.code;
|
|
2269
|
+
if (errno !== "ENOENT" && errno !== "ENOTDIR") {
|
|
2270
|
+
log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
function refuse(code, message, fields) {
|
|
2275
|
+
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
2276
|
+
return { ok: false, code, message };
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
// src/lib/runner-file-sync.ts
|
|
2280
|
+
var MAX_ACK_ATTEMPTS = 5;
|
|
2281
|
+
async function syncPendingRunnerFiles(options) {
|
|
2282
|
+
const pending = await listPendingFiles(options);
|
|
2283
|
+
const pendingIds = new Set(pending.map((file) => file.id));
|
|
2284
|
+
for (const id of options.ackFailures.keys()) {
|
|
2285
|
+
if (!pendingIds.has(id)) options.ackFailures.delete(id);
|
|
2286
|
+
}
|
|
2287
|
+
if (pending.length === 0) return 0;
|
|
2288
|
+
options.log({
|
|
2289
|
+
level: "info",
|
|
2290
|
+
message: `Runner file sync: ${pending.length} file(s) queued for this runner`
|
|
2291
|
+
});
|
|
2292
|
+
let applied = 0;
|
|
2293
|
+
for (const file of pending) {
|
|
2294
|
+
if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
|
|
2295
|
+
if (await applyOne(options, file)) applied += 1;
|
|
2296
|
+
}
|
|
2297
|
+
return applied;
|
|
2298
|
+
}
|
|
2299
|
+
async function listPendingFiles(options) {
|
|
2300
|
+
let res;
|
|
2301
|
+
try {
|
|
2302
|
+
res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
|
|
2303
|
+
headers: { Authorization: options.getAuthHeader() }
|
|
2304
|
+
});
|
|
2305
|
+
} catch (err) {
|
|
2306
|
+
options.log({
|
|
2307
|
+
level: "warn",
|
|
2308
|
+
message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
|
|
2309
|
+
});
|
|
2310
|
+
return [];
|
|
2311
|
+
}
|
|
2312
|
+
if (!res.ok) {
|
|
2313
|
+
options.log({
|
|
2314
|
+
level: res.status === 404 ? "debug" : "warn",
|
|
2315
|
+
message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2316
|
+
});
|
|
2317
|
+
return [];
|
|
2318
|
+
}
|
|
2319
|
+
let body;
|
|
2320
|
+
try {
|
|
2321
|
+
body = await res.json();
|
|
2322
|
+
} catch (err) {
|
|
2323
|
+
options.log({
|
|
2324
|
+
level: "warn",
|
|
2325
|
+
message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
|
|
2326
|
+
});
|
|
2327
|
+
return [];
|
|
2328
|
+
}
|
|
2329
|
+
if (!Array.isArray(body)) {
|
|
2330
|
+
options.log({
|
|
2331
|
+
level: "warn",
|
|
2332
|
+
message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
|
|
2333
|
+
});
|
|
2334
|
+
return [];
|
|
2335
|
+
}
|
|
2336
|
+
const files = [];
|
|
2337
|
+
for (const entry of body) {
|
|
2338
|
+
const file = asPendingFile(entry);
|
|
2339
|
+
if (file === null) {
|
|
2340
|
+
options.log({
|
|
2341
|
+
level: "warn",
|
|
2342
|
+
message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
|
|
2343
|
+
});
|
|
2344
|
+
continue;
|
|
2345
|
+
}
|
|
2346
|
+
files.push(file);
|
|
2347
|
+
}
|
|
2348
|
+
return files;
|
|
2349
|
+
}
|
|
2350
|
+
function asPendingFile(entry) {
|
|
2351
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
2352
|
+
const { id, path, size } = entry;
|
|
2353
|
+
if (typeof id !== "string" || id === "") return null;
|
|
2354
|
+
if (typeof path !== "string" || path === "") return null;
|
|
2355
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
|
|
2356
|
+
return { id, path, size };
|
|
2357
|
+
}
|
|
2358
|
+
async function applyOne(options, file) {
|
|
2359
|
+
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
2360
|
+
if (options.allowedDirectories.length === 0) {
|
|
2361
|
+
options.log({
|
|
2362
|
+
level: "warn",
|
|
2363
|
+
message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
|
|
2364
|
+
});
|
|
2365
|
+
await ack(options, file, "rejected", "file_sync_disabled");
|
|
2366
|
+
return false;
|
|
2367
|
+
}
|
|
2368
|
+
if (file.size > MAX_FILE_PUSH_BYTES) {
|
|
2369
|
+
options.log({
|
|
2370
|
+
level: "warn",
|
|
2371
|
+
message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
|
|
2372
|
+
});
|
|
2373
|
+
await ack(options, file, "rejected", "file_too_large");
|
|
2374
|
+
return false;
|
|
2375
|
+
}
|
|
2376
|
+
const download = await downloadContent(options, file, label);
|
|
2377
|
+
if (!download.ok) {
|
|
2378
|
+
if (download.terminal) await ack(options, file, "rejected", download.code);
|
|
2379
|
+
return false;
|
|
2380
|
+
}
|
|
2381
|
+
let outcome;
|
|
2382
|
+
try {
|
|
2383
|
+
outcome = await writePushedFile({
|
|
2384
|
+
requestedPath: file.path,
|
|
2385
|
+
content: download.content,
|
|
2386
|
+
allowedDirectories: options.allowedDirectories,
|
|
2387
|
+
homeDir: options.homeDir
|
|
2388
|
+
});
|
|
2389
|
+
} catch (err) {
|
|
2390
|
+
options.log({
|
|
2391
|
+
level: "error",
|
|
2392
|
+
message: `Runner file ${label} could not be written: ${describe(err)}`
|
|
2393
|
+
});
|
|
2394
|
+
await ack(options, file, "rejected", "write_failed");
|
|
2395
|
+
return false;
|
|
2396
|
+
}
|
|
2397
|
+
if (!outcome.ok) {
|
|
2398
|
+
options.log({
|
|
2399
|
+
level: "warn",
|
|
2400
|
+
message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
|
|
2401
|
+
});
|
|
2402
|
+
await ack(options, file, "rejected", outcome.code);
|
|
2403
|
+
return false;
|
|
2404
|
+
}
|
|
2405
|
+
options.log({
|
|
2406
|
+
level: "info",
|
|
2407
|
+
message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
|
|
2408
|
+
});
|
|
2409
|
+
await ack(options, file, "applied");
|
|
2410
|
+
return true;
|
|
2411
|
+
}
|
|
2412
|
+
function durableDownloadCode(status) {
|
|
2413
|
+
return status === 413 ? "file_too_large" : "write_failed";
|
|
2414
|
+
}
|
|
2415
|
+
async function downloadContent(options, file, label) {
|
|
2416
|
+
try {
|
|
2417
|
+
const res = await options.fetchImpl(
|
|
2418
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
|
|
2419
|
+
{ headers: { Authorization: options.getAuthHeader() } }
|
|
2420
|
+
);
|
|
2421
|
+
if (!res.ok) {
|
|
2422
|
+
const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
|
|
2423
|
+
if (!terminal) {
|
|
2424
|
+
options.log({
|
|
2425
|
+
level: "warn",
|
|
2426
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2427
|
+
});
|
|
2428
|
+
return { ok: false, terminal: false };
|
|
2429
|
+
}
|
|
2430
|
+
const code = durableDownloadCode(res.status);
|
|
2431
|
+
options.log({
|
|
2432
|
+
level: "error",
|
|
2433
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
|
|
2434
|
+
});
|
|
2435
|
+
return { ok: false, terminal: true, code };
|
|
2436
|
+
}
|
|
2437
|
+
return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
|
|
2438
|
+
} catch (err) {
|
|
2439
|
+
options.log({
|
|
2440
|
+
level: "warn",
|
|
2441
|
+
message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
|
|
2442
|
+
});
|
|
2443
|
+
return { ok: false, terminal: false };
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
async function ack(options, file, status, reason) {
|
|
2447
|
+
const outcome = `${status}${reason ? ` (${reason})` : ""}`;
|
|
2448
|
+
try {
|
|
2449
|
+
const res = await options.fetchImpl(
|
|
2450
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
2451
|
+
{
|
|
2452
|
+
method: "POST",
|
|
2453
|
+
headers: {
|
|
2454
|
+
Authorization: options.getAuthHeader(),
|
|
2455
|
+
"Content-Type": "application/json"
|
|
2456
|
+
},
|
|
2457
|
+
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
2458
|
+
}
|
|
2459
|
+
);
|
|
2460
|
+
if (!res.ok) {
|
|
2461
|
+
recordAckFailure(
|
|
2462
|
+
options,
|
|
2463
|
+
file,
|
|
2464
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
|
|
2465
|
+
);
|
|
2466
|
+
return;
|
|
2467
|
+
}
|
|
2468
|
+
options.ackFailures.delete(file.id);
|
|
2469
|
+
} catch (err) {
|
|
2470
|
+
recordAckFailure(
|
|
2471
|
+
options,
|
|
2472
|
+
file,
|
|
2473
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
|
|
2474
|
+
);
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
function recordAckFailure(options, file, what) {
|
|
2478
|
+
const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
|
|
2479
|
+
options.ackFailures.set(file.id, attempts);
|
|
2480
|
+
options.log({
|
|
2481
|
+
level: "error",
|
|
2482
|
+
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})`
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
function describe(err) {
|
|
2486
|
+
return err instanceof Error ? err.message : String(err);
|
|
2487
|
+
}
|
|
2488
|
+
|
|
1906
2489
|
// src/lib/channels/driver.ts
|
|
1907
2490
|
function messageIdOf(m) {
|
|
1908
2491
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -1931,7 +2514,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
1931
2514
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
1932
2515
|
var HEARTBEAT_MS = 6e4;
|
|
1933
2516
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2517
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2518
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
1934
2519
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2520
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
1935
2521
|
var ChannelAuthError = class extends Error {
|
|
1936
2522
|
constructor(message) {
|
|
1937
2523
|
super(message);
|
|
@@ -1954,7 +2540,7 @@ function backoffDelay(attempt, policy) {
|
|
|
1954
2540
|
function isRetryableStatus(status) {
|
|
1955
2541
|
return status === 429 || status >= 500 && status <= 599;
|
|
1956
2542
|
}
|
|
1957
|
-
var ChannelDriver = class {
|
|
2543
|
+
var ChannelDriver = class _ChannelDriver {
|
|
1958
2544
|
agentId;
|
|
1959
2545
|
port;
|
|
1960
2546
|
apiUrl;
|
|
@@ -1968,8 +2554,38 @@ var ChannelDriver = class {
|
|
|
1968
2554
|
pausedMaxWaitMs;
|
|
1969
2555
|
stuckQueuedMs;
|
|
1970
2556
|
now;
|
|
2557
|
+
fileSyncDirectories;
|
|
2558
|
+
homeDir;
|
|
1971
2559
|
/** Cache of conversationId → opencode sessionId. */
|
|
1972
2560
|
sessions = /* @__PURE__ */ new Map();
|
|
2561
|
+
/**
|
|
2562
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2563
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2564
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2565
|
+
* must bind a fresh one.
|
|
2566
|
+
*
|
|
2567
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2568
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2569
|
+
* the same session, and its watcher's routine status writes carry
|
|
2570
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2571
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2572
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2573
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2574
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2575
|
+
* is one we deliberately keep (see `markDone`).
|
|
2576
|
+
*
|
|
2577
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2578
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2579
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2580
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2581
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2582
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2583
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2584
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2585
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2586
|
+
* bounded cost.
|
|
2587
|
+
*/
|
|
2588
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
1973
2589
|
/**
|
|
1974
2590
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
1975
2591
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2079,9 +2695,12 @@ var ChannelDriver = class {
|
|
|
2079
2695
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2080
2696
|
/**
|
|
2081
2697
|
* 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
|
-
*
|
|
2698
|
+
* NON-EMPTY, non-placeholder name is stored (terminal — a real session name
|
|
2699
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
|
|
2700
|
+
* excludes OpenCode's synchronous default title (see
|
|
2701
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
|
|
2702
|
+
* as an empty title so it never latches. A missing entry = not yet resolved OR
|
|
2703
|
+
* resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
|
|
2085
2704
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2086
2705
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2087
2706
|
* no watcher) can resolve the title.
|
|
@@ -2089,6 +2708,24 @@ var ChannelDriver = class {
|
|
|
2089
2708
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2090
2709
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2091
2710
|
draining = false;
|
|
2711
|
+
/**
|
|
2712
|
+
* Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
|
|
2713
|
+
* drain ping don't download, write and ack the same file twice.
|
|
2714
|
+
*/
|
|
2715
|
+
syncingFiles = false;
|
|
2716
|
+
/**
|
|
2717
|
+
* Consecutive failed acks per pending file (#559). Lives on the driver so it
|
|
2718
|
+
* survives across drains — without it, a file whose ack keeps failing is
|
|
2719
|
+
* re-downloaded and re-written every ~2s until the server expires it.
|
|
2720
|
+
*/
|
|
2721
|
+
fileAckFailures = /* @__PURE__ */ new Map();
|
|
2722
|
+
/**
|
|
2723
|
+
* Monotonic count of files this runner has pulled and written (#559). Only
|
|
2724
|
+
* ever increases, so `run.ts` detects work by comparing it against the value
|
|
2725
|
+
* it saw on the previous cycle — including work that landed mid-sleep, the
|
|
2726
|
+
* same trick `lastProxiedActivityAt` uses.
|
|
2727
|
+
*/
|
|
2728
|
+
appliedFileCount = 0;
|
|
2092
2729
|
/**
|
|
2093
2730
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2094
2731
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2119,6 +2756,8 @@ var ChannelDriver = class {
|
|
|
2119
2756
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2120
2757
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2121
2758
|
this.now = config2.now ?? (() => Date.now());
|
|
2759
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
2760
|
+
this.homeDir = config2.homeDir ?? homedir();
|
|
2122
2761
|
}
|
|
2123
2762
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2124
2763
|
get opencodeBase() {
|
|
@@ -2146,6 +2785,47 @@ var ChannelDriver = class {
|
|
|
2146
2785
|
);
|
|
2147
2786
|
return run2;
|
|
2148
2787
|
}
|
|
2788
|
+
/**
|
|
2789
|
+
* Pull-and-apply any files Evident has queued for this runner (#559), riding
|
|
2790
|
+
* the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
|
|
2791
|
+
* and drain ping that call `drainPending()`. There is deliberately no channel,
|
|
2792
|
+
* control frame or poll loop of its own: worst-case latency is one poll tick.
|
|
2793
|
+
*
|
|
2794
|
+
* NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
|
|
2795
|
+
* cost a conversation turn. Failures are logged and either acked as a terminal
|
|
2796
|
+
* outcome or left pending for the next drain (see `runner-file-sync.ts`).
|
|
2797
|
+
*
|
|
2798
|
+
* Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
|
|
2799
|
+
*
|
|
2800
|
+
* @returns the number of files written to disk.
|
|
2801
|
+
*/
|
|
2802
|
+
async syncPendingFiles() {
|
|
2803
|
+
if (this.stopped) return 0;
|
|
2804
|
+
if (this.syncingFiles) return 0;
|
|
2805
|
+
this.syncingFiles = true;
|
|
2806
|
+
try {
|
|
2807
|
+
const applied = await syncPendingRunnerFiles({
|
|
2808
|
+
agentId: this.agentId,
|
|
2809
|
+
apiUrl: this.apiUrl,
|
|
2810
|
+
getAuthHeader: this.getAuthHeader,
|
|
2811
|
+
fetchImpl: this.fetchImpl,
|
|
2812
|
+
allowedDirectories: this.fileSyncDirectories,
|
|
2813
|
+
homeDir: this.homeDir,
|
|
2814
|
+
ackFailures: this.fileAckFailures,
|
|
2815
|
+
log: this.log
|
|
2816
|
+
});
|
|
2817
|
+
this.appliedFileCount += applied;
|
|
2818
|
+
return applied;
|
|
2819
|
+
} catch (err) {
|
|
2820
|
+
this.log({
|
|
2821
|
+
level: "error",
|
|
2822
|
+
message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
|
|
2823
|
+
});
|
|
2824
|
+
return 0;
|
|
2825
|
+
} finally {
|
|
2826
|
+
this.syncingFiles = false;
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2149
2829
|
async runDrain() {
|
|
2150
2830
|
let dispatched = 0;
|
|
2151
2831
|
try {
|
|
@@ -2179,6 +2859,28 @@ var ChannelDriver = class {
|
|
|
2179
2859
|
}
|
|
2180
2860
|
return false;
|
|
2181
2861
|
}
|
|
2862
|
+
/**
|
|
2863
|
+
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
2864
|
+
*
|
|
2865
|
+
* Pulling a file is real work that `drainPending()` knows nothing about, so
|
|
2866
|
+
* without this a near-idle runner counts a credential pull as an empty tick
|
|
2867
|
+
* and `--idle-timeout` can `process.exit` mid-pull — leaving a
|
|
2868
|
+
* `.evident-push-*.tmp` behind — or immediately after the write, before the
|
|
2869
|
+
* browser has run the authorize/callback that activates it (the user then sees
|
|
2870
|
+
* `saved_not_activated` for a runner that was fine).
|
|
2871
|
+
*
|
|
2872
|
+
* Two signals because one cannot cover both cases: `inFlight` is the pull
|
|
2873
|
+
* happening RIGHT NOW (it may outlive the tick that started it), and
|
|
2874
|
+
* `appliedFiles` is monotonic so a pull that started AND finished between two
|
|
2875
|
+
* idle checks still shows up as an advance.
|
|
2876
|
+
*
|
|
2877
|
+
* CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
|
|
2878
|
+
* the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
|
|
2879
|
+
* samples afterwards reads `true` every single cycle and can never idle out.
|
|
2880
|
+
*/
|
|
2881
|
+
fileSyncActivity() {
|
|
2882
|
+
return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
|
|
2883
|
+
}
|
|
2182
2884
|
/**
|
|
2183
2885
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2184
2886
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2240,7 +2942,7 @@ var ChannelDriver = class {
|
|
|
2240
2942
|
await this.sleep(step);
|
|
2241
2943
|
}
|
|
2242
2944
|
}
|
|
2243
|
-
while (this.hasInFlightWatchers()) {
|
|
2945
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2244
2946
|
if (this.now() >= deadline) return false;
|
|
2245
2947
|
await this.sleep(step);
|
|
2246
2948
|
}
|
|
@@ -2275,10 +2977,15 @@ var ChannelDriver = class {
|
|
|
2275
2977
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2276
2978
|
*/
|
|
2277
2979
|
async processConversation(conv) {
|
|
2278
|
-
const sessionId = await this.ensureSession(conv);
|
|
2980
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2279
2981
|
const messages = await this.getPendingMessages(conv.id);
|
|
2280
2982
|
let dispatched = 0;
|
|
2281
2983
|
let skippedAlreadyDispatched = 0;
|
|
2984
|
+
if (refusedSessionId && messages.length > 0) {
|
|
2985
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
2986
|
+
superseded_session_id: refusedSessionId
|
|
2987
|
+
});
|
|
2988
|
+
}
|
|
2282
2989
|
for (const message of messages) {
|
|
2283
2990
|
if (this.stopped) break;
|
|
2284
2991
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2305,7 +3012,8 @@ var ChannelDriver = class {
|
|
|
2305
3012
|
} catch (err) {
|
|
2306
3013
|
if (err instanceof ChannelAuthError) throw err;
|
|
2307
3014
|
this.dispatched.delete(message.id);
|
|
2308
|
-
|
|
3015
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
3016
|
+
if (exists === false) {
|
|
2309
3017
|
this.sessions.delete(conv.id);
|
|
2310
3018
|
this.log({
|
|
2311
3019
|
level: "warn",
|
|
@@ -2315,15 +3023,39 @@ var ChannelDriver = class {
|
|
|
2315
3023
|
});
|
|
2316
3024
|
break;
|
|
2317
3025
|
}
|
|
2318
|
-
|
|
3026
|
+
if (exists === null) {
|
|
3027
|
+
this.log({
|
|
3028
|
+
level: "warn",
|
|
3029
|
+
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.`,
|
|
3030
|
+
conversation_id: conv.id,
|
|
3031
|
+
message_id: message.id
|
|
3032
|
+
});
|
|
3033
|
+
break;
|
|
3034
|
+
}
|
|
3035
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3036
|
+
this.sessions.delete(conv.id);
|
|
3037
|
+
this.supersede(conv.id, sessionId);
|
|
3038
|
+
this.log({
|
|
3039
|
+
level: "warn",
|
|
3040
|
+
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.`,
|
|
3041
|
+
conversation_id: conv.id,
|
|
3042
|
+
message_id: message.id
|
|
3043
|
+
});
|
|
3044
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3045
|
+
this.log({
|
|
3046
|
+
level: "warn",
|
|
3047
|
+
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)}`,
|
|
3048
|
+
conversation_id: conv.id,
|
|
3049
|
+
message_id: message.id
|
|
3050
|
+
});
|
|
2319
3051
|
});
|
|
2320
3052
|
this.log({
|
|
2321
3053
|
level: "error",
|
|
2322
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3054
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2323
3055
|
conversation_id: conv.id,
|
|
2324
3056
|
message_id: message.id
|
|
2325
3057
|
});
|
|
2326
|
-
|
|
3058
|
+
break;
|
|
2327
3059
|
}
|
|
2328
3060
|
if (opencodeMessageId === null) {
|
|
2329
3061
|
this.log({
|
|
@@ -2342,15 +3074,49 @@ var ChannelDriver = class {
|
|
|
2342
3074
|
if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
|
|
2343
3075
|
this.log({
|
|
2344
3076
|
level: "warn",
|
|
2345
|
-
message: `Conversation ${conv.id.slice(0, 8)} has ${messages.length} pending message(s) but ALL are already marked dispatched locally (in-flight set: ${this.dispatched.size}) \u2014 none sent to OpenCode this tick. If this repeats, a message may be stuck acknowledged-but-never-dispatched (its watcher never settled).`,
|
|
3077
|
+
message: `Conversation ${conv.id.slice(0, 8)} has ${messages.length} pending message(s) but ALL are already marked dispatched locally (in-flight set: ${this.dispatched.size}) \u2014 none sent to OpenCode this tick. If this repeats, a message may be stuck acknowledged-but-never-dispatched (its watcher never settled).`,
|
|
3078
|
+
conversation_id: conv.id
|
|
3079
|
+
});
|
|
3080
|
+
}
|
|
3081
|
+
this.ensureWatcherRunning(sessionId);
|
|
3082
|
+
return dispatched;
|
|
3083
|
+
}
|
|
3084
|
+
/**
|
|
3085
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
3086
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
3087
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
3088
|
+
*/
|
|
3089
|
+
supersede(conversationId, sessionId) {
|
|
3090
|
+
this.supersededSessions.delete(conversationId);
|
|
3091
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
3092
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
3093
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
3094
|
+
if (oldest === void 0) return;
|
|
3095
|
+
this.supersededSessions.delete(oldest);
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
3099
|
+
isSuperseded(conversationId, sessionId) {
|
|
3100
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
3101
|
+
}
|
|
3102
|
+
/**
|
|
3103
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
3104
|
+
*
|
|
3105
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3106
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3107
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
3108
|
+
*/
|
|
3109
|
+
async ensureSession(conv) {
|
|
3110
|
+
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
3111
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
3112
|
+
this.log({
|
|
3113
|
+
level: "warn",
|
|
3114
|
+
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.`,
|
|
2346
3115
|
conversation_id: conv.id
|
|
2347
3116
|
});
|
|
3117
|
+
this.sessions.delete(conv.id);
|
|
3118
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
2348
3119
|
}
|
|
2349
|
-
this.ensureWatcherRunning(sessionId);
|
|
2350
|
-
return dispatched;
|
|
2351
|
-
}
|
|
2352
|
-
async ensureSession(conv) {
|
|
2353
|
-
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
2354
3120
|
if (bound) {
|
|
2355
3121
|
const exists = await sessionExists(this.port, bound);
|
|
2356
3122
|
if (exists === false) {
|
|
@@ -2360,12 +3126,12 @@ var ChannelDriver = class {
|
|
|
2360
3126
|
conversation_id: conv.id
|
|
2361
3127
|
});
|
|
2362
3128
|
this.sessions.delete(conv.id);
|
|
2363
|
-
return this.createAndBindSession(conv.id);
|
|
3129
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2364
3130
|
}
|
|
2365
3131
|
this.sessions.set(conv.id, bound);
|
|
2366
|
-
return bound;
|
|
3132
|
+
return { sessionId: bound };
|
|
2367
3133
|
}
|
|
2368
|
-
return this.createAndBindSession(conv.id);
|
|
3134
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2369
3135
|
}
|
|
2370
3136
|
/**
|
|
2371
3137
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2445,7 +3211,7 @@ var ChannelDriver = class {
|
|
|
2445
3211
|
}
|
|
2446
3212
|
/**
|
|
2447
3213
|
* Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
|
|
2448
|
-
* (`GET {apiUrl}/
|
|
3214
|
+
* (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
|
|
2449
3215
|
* existing authenticated fetch, and base64-encode into a
|
|
2450
3216
|
* `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
|
|
2451
3217
|
*
|
|
@@ -2453,15 +3219,38 @@ var ChannelDriver = class {
|
|
|
2453
3219
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2454
3220
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2455
3221
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2456
|
-
*
|
|
3222
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
3223
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
3224
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
3225
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
3226
|
+
* logged with context (no silent swallow).
|
|
2457
3227
|
*/
|
|
2458
3228
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2459
3229
|
try {
|
|
2460
3230
|
const res = await this.fetchImpl(
|
|
2461
|
-
`${this.apiUrl}/
|
|
3231
|
+
`${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
|
|
2462
3232
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2463
3233
|
);
|
|
2464
3234
|
if (!res.ok) {
|
|
3235
|
+
let reason;
|
|
3236
|
+
try {
|
|
3237
|
+
const body = await res.json();
|
|
3238
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
3239
|
+
} catch (parseErr) {
|
|
3240
|
+
this.log({
|
|
3241
|
+
level: "debug",
|
|
3242
|
+
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`,
|
|
3243
|
+
message_id: messageId
|
|
3244
|
+
});
|
|
3245
|
+
}
|
|
3246
|
+
if (reason === "needs_reauth") {
|
|
3247
|
+
this.log({
|
|
3248
|
+
level: "error",
|
|
3249
|
+
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)`,
|
|
3250
|
+
message_id: messageId
|
|
3251
|
+
});
|
|
3252
|
+
return { needsReauth: true };
|
|
3253
|
+
}
|
|
2465
3254
|
this.log({
|
|
2466
3255
|
level: "error",
|
|
2467
3256
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2501,6 +3290,9 @@ var ChannelDriver = class {
|
|
|
2501
3290
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2502
3291
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2503
3292
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
3293
|
+
const failedReason = outcomes.some(
|
|
3294
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
3295
|
+
) ? "needs_reauth" : void 0;
|
|
2504
3296
|
this.log({
|
|
2505
3297
|
level: "info",
|
|
2506
3298
|
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 +3302,8 @@ var ChannelDriver = class {
|
|
|
2510
3302
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2511
3303
|
skipped,
|
|
2512
3304
|
failed,
|
|
2513
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3305
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3306
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2514
3307
|
});
|
|
2515
3308
|
}
|
|
2516
3309
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2541,12 +3334,17 @@ var ChannelDriver = class {
|
|
|
2541
3334
|
stuckReported: false,
|
|
2542
3335
|
lastAliveAt: 0,
|
|
2543
3336
|
aliveInFlight: false,
|
|
3337
|
+
titleSynced: false,
|
|
3338
|
+
titleSyncInFlight: false,
|
|
2544
3339
|
awaitingHumanLatched: false,
|
|
2545
3340
|
pausedOnQuestion: false,
|
|
2546
3341
|
pausedOnPermission: false,
|
|
2547
3342
|
pausedClearConfirmed: false,
|
|
2548
3343
|
pausedInFlight: false,
|
|
2549
|
-
deliveryDeadlineAnchored: false
|
|
3344
|
+
deliveryDeadlineAnchored: false,
|
|
3345
|
+
b2PinnedSinceMs: 0,
|
|
3346
|
+
b2LastDescendantCheckMs: 0,
|
|
3347
|
+
b2AbandonedSignalled: false
|
|
2550
3348
|
});
|
|
2551
3349
|
}
|
|
2552
3350
|
/**
|
|
@@ -2614,12 +3412,17 @@ var ChannelDriver = class {
|
|
|
2614
3412
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
2615
3413
|
lastAliveAt: 0,
|
|
2616
3414
|
aliveInFlight: false,
|
|
3415
|
+
titleSynced: false,
|
|
3416
|
+
titleSyncInFlight: false,
|
|
2617
3417
|
awaitingHumanLatched: false,
|
|
2618
3418
|
pausedOnQuestion: false,
|
|
2619
3419
|
pausedOnPermission: false,
|
|
2620
3420
|
pausedClearConfirmed: false,
|
|
2621
3421
|
pausedInFlight: false,
|
|
2622
|
-
deliveryDeadlineAnchored: false
|
|
3422
|
+
deliveryDeadlineAnchored: false,
|
|
3423
|
+
b2PinnedSinceMs: 0,
|
|
3424
|
+
b2LastDescendantCheckMs: 0,
|
|
3425
|
+
b2AbandonedSignalled: false
|
|
2623
3426
|
});
|
|
2624
3427
|
}
|
|
2625
3428
|
/**
|
|
@@ -2781,56 +3584,7 @@ var ChannelDriver = class {
|
|
|
2781
3584
|
}
|
|
2782
3585
|
}
|
|
2783
3586
|
if (state === "done") {
|
|
2784
|
-
this.
|
|
2785
|
-
if (!inFlight.done) {
|
|
2786
|
-
this.log({
|
|
2787
|
-
level: "info",
|
|
2788
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
2789
|
-
conversation_id: conv.id,
|
|
2790
|
-
message_id: inFlight.evidentMessageId
|
|
2791
|
-
});
|
|
2792
|
-
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
2793
|
-
try {
|
|
2794
|
-
await this.markDone(
|
|
2795
|
-
conv.id,
|
|
2796
|
-
inFlight.evidentMessageId,
|
|
2797
|
-
sessionId,
|
|
2798
|
-
inFlight.opencodeMessageId,
|
|
2799
|
-
title
|
|
2800
|
-
);
|
|
2801
|
-
} catch (err) {
|
|
2802
|
-
if (err instanceof ChannelAuthError) throw err;
|
|
2803
|
-
if (err instanceof ChannelTerminalError) {
|
|
2804
|
-
this.log({
|
|
2805
|
-
level: "warn",
|
|
2806
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
2807
|
-
conversation_id: conv.id,
|
|
2808
|
-
message_id: inFlight.evidentMessageId
|
|
2809
|
-
});
|
|
2810
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2811
|
-
return;
|
|
2812
|
-
}
|
|
2813
|
-
if (this.now() >= inFlight.deadline) {
|
|
2814
|
-
this.log({
|
|
2815
|
-
level: "warn",
|
|
2816
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
|
|
2817
|
-
conversation_id: conv.id,
|
|
2818
|
-
message_id: inFlight.evidentMessageId
|
|
2819
|
-
});
|
|
2820
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2821
|
-
return;
|
|
2822
|
-
}
|
|
2823
|
-
this.log({
|
|
2824
|
-
level: "warn",
|
|
2825
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
2826
|
-
conversation_id: conv.id,
|
|
2827
|
-
message_id: inFlight.evidentMessageId
|
|
2828
|
-
});
|
|
2829
|
-
return;
|
|
2830
|
-
}
|
|
2831
|
-
inFlight.done = true;
|
|
2832
|
-
}
|
|
2833
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3587
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
2834
3588
|
return;
|
|
2835
3589
|
}
|
|
2836
3590
|
if (state === "failed") {
|
|
@@ -2843,8 +3597,9 @@ var ChannelDriver = class {
|
|
|
2843
3597
|
conversation_id: conv.id,
|
|
2844
3598
|
message_id: inFlight.evidentMessageId
|
|
2845
3599
|
});
|
|
3600
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2846
3601
|
try {
|
|
2847
|
-
await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
|
|
3602
|
+
await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
|
|
2848
3603
|
} catch (err) {
|
|
2849
3604
|
if (err instanceof ChannelAuthError) throw err;
|
|
2850
3605
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -2889,6 +3644,44 @@ var ChannelDriver = class {
|
|
|
2889
3644
|
});
|
|
2890
3645
|
}
|
|
2891
3646
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3647
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3648
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3649
|
+
if (!pinnedNow) {
|
|
3650
|
+
if (snapshotReadable) {
|
|
3651
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3652
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3653
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3654
|
+
}
|
|
3655
|
+
} else {
|
|
3656
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3657
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3658
|
+
return;
|
|
3659
|
+
}
|
|
3660
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3661
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3662
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3663
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3664
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3665
|
+
if (isB2AbandonmentConfirmed({
|
|
3666
|
+
pinnedForMs,
|
|
3667
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3668
|
+
descendantOngoing
|
|
3669
|
+
})) {
|
|
3670
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3671
|
+
this.log({
|
|
3672
|
+
level: "warn",
|
|
3673
|
+
message: `Message ${id.slice(0, 8)} b2-pinned for ${Math.round(pinnedForMs / 1e3)}s with no ongoing descendant sub-agent session (status-map confirmed) \u2014 treating the delegated/tool turn as abandoned, resolving done`,
|
|
3674
|
+
conversation_id: conv.id,
|
|
3675
|
+
message_id: id
|
|
3676
|
+
});
|
|
3677
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3678
|
+
watched_for_ms: pinnedForMs
|
|
3679
|
+
});
|
|
3680
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3681
|
+
return;
|
|
3682
|
+
}
|
|
3683
|
+
}
|
|
3684
|
+
}
|
|
2892
3685
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
2893
3686
|
this.log({
|
|
2894
3687
|
level: "warn",
|
|
@@ -2908,6 +3701,18 @@ var ChannelDriver = class {
|
|
|
2908
3701
|
inFlight.aliveInFlight = false;
|
|
2909
3702
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
2910
3703
|
});
|
|
3704
|
+
if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
|
|
3705
|
+
inFlight.titleSyncInFlight = true;
|
|
3706
|
+
void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
|
|
3707
|
+
if (!title) {
|
|
3708
|
+
inFlight.titleSyncInFlight = false;
|
|
3709
|
+
return;
|
|
3710
|
+
}
|
|
3711
|
+
const ok = await this.patchConversationTitle(conv.id, title);
|
|
3712
|
+
inFlight.titleSyncInFlight = false;
|
|
3713
|
+
if (ok) inFlight.titleSynced = true;
|
|
3714
|
+
});
|
|
3715
|
+
}
|
|
2911
3716
|
}
|
|
2912
3717
|
if (awaitingHuman) {
|
|
2913
3718
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -2945,6 +3750,70 @@ var ChannelDriver = class {
|
|
|
2945
3750
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2946
3751
|
}
|
|
2947
3752
|
}
|
|
3753
|
+
/**
|
|
3754
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
3755
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
3756
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
3757
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
3758
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
3759
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
3760
|
+
* and risking the two copies silently drifting apart.
|
|
3761
|
+
*/
|
|
3762
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
3763
|
+
const conv = watcher.conv;
|
|
3764
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
3765
|
+
if (!inFlight.done) {
|
|
3766
|
+
this.log({
|
|
3767
|
+
level: "info",
|
|
3768
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
3769
|
+
conversation_id: conv.id,
|
|
3770
|
+
message_id: inFlight.evidentMessageId
|
|
3771
|
+
});
|
|
3772
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3773
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3774
|
+
try {
|
|
3775
|
+
await this.markDone(
|
|
3776
|
+
conv.id,
|
|
3777
|
+
inFlight.evidentMessageId,
|
|
3778
|
+
sessionId,
|
|
3779
|
+
inFlight.opencodeMessageId,
|
|
3780
|
+
title,
|
|
3781
|
+
usage
|
|
3782
|
+
);
|
|
3783
|
+
} catch (err) {
|
|
3784
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3785
|
+
if (err instanceof ChannelTerminalError) {
|
|
3786
|
+
this.log({
|
|
3787
|
+
level: "warn",
|
|
3788
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
3789
|
+
conversation_id: conv.id,
|
|
3790
|
+
message_id: inFlight.evidentMessageId
|
|
3791
|
+
});
|
|
3792
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3793
|
+
return;
|
|
3794
|
+
}
|
|
3795
|
+
if (this.now() >= inFlight.deadline) {
|
|
3796
|
+
this.log({
|
|
3797
|
+
level: "warn",
|
|
3798
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
|
|
3799
|
+
conversation_id: conv.id,
|
|
3800
|
+
message_id: inFlight.evidentMessageId
|
|
3801
|
+
});
|
|
3802
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3803
|
+
return;
|
|
3804
|
+
}
|
|
3805
|
+
this.log({
|
|
3806
|
+
level: "warn",
|
|
3807
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
3808
|
+
conversation_id: conv.id,
|
|
3809
|
+
message_id: inFlight.evidentMessageId
|
|
3810
|
+
});
|
|
3811
|
+
return;
|
|
3812
|
+
}
|
|
3813
|
+
inFlight.done = true;
|
|
3814
|
+
}
|
|
3815
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3816
|
+
}
|
|
2948
3817
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
2949
3818
|
/**
|
|
2950
3819
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3081,7 +3950,8 @@ var ChannelDriver = class {
|
|
|
3081
3950
|
});
|
|
3082
3951
|
try {
|
|
3083
3952
|
const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
|
|
3084
|
-
|
|
3953
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
3954
|
+
await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
|
|
3085
3955
|
} catch (err) {
|
|
3086
3956
|
if (err instanceof ChannelAuthError) throw err;
|
|
3087
3957
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3109,6 +3979,7 @@ var ChannelDriver = class {
|
|
|
3109
3979
|
}
|
|
3110
3980
|
if (state === "failed") {
|
|
3111
3981
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3982
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
3112
3983
|
this.log({
|
|
3113
3984
|
level: "error",
|
|
3114
3985
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3116,7 +3987,7 @@ var ChannelDriver = class {
|
|
|
3116
3987
|
message_id: row.id
|
|
3117
3988
|
});
|
|
3118
3989
|
try {
|
|
3119
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2);
|
|
3990
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
3120
3991
|
} catch (err) {
|
|
3121
3992
|
if (err instanceof ChannelAuthError) throw err;
|
|
3122
3993
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3522,6 +4393,47 @@ var ChannelDriver = class {
|
|
|
3522
4393
|
}
|
|
3523
4394
|
return false;
|
|
3524
4395
|
}
|
|
4396
|
+
/**
|
|
4397
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4398
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4399
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4400
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4401
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4402
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4403
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4404
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4405
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4406
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4407
|
+
* not ongoing".
|
|
4408
|
+
*
|
|
4409
|
+
* Return contract:
|
|
4410
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4411
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4412
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4413
|
+
* CONFIRMED NOT a descendant of it.
|
|
4414
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4415
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4416
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4417
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4418
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4419
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4420
|
+
* here.
|
|
4421
|
+
*
|
|
4422
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4423
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4424
|
+
* by interaction attribution or the recovery path.
|
|
4425
|
+
*/
|
|
4426
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4427
|
+
let current = sessionId;
|
|
4428
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4429
|
+
if (current === rootSessionId) return true;
|
|
4430
|
+
const parent = await this.resolveSessionParent(current);
|
|
4431
|
+
if (parent === void 0) return null;
|
|
4432
|
+
if (parent === null) return false;
|
|
4433
|
+
current = parent;
|
|
4434
|
+
}
|
|
4435
|
+
return null;
|
|
4436
|
+
}
|
|
3525
4437
|
/**
|
|
3526
4438
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
3527
4439
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -3544,19 +4456,36 @@ var ChannelDriver = class {
|
|
|
3544
4456
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3545
4457
|
return parent;
|
|
3546
4458
|
}
|
|
4459
|
+
/**
|
|
4460
|
+
* OpenCode's synchronous default session title (e.g.
|
|
4461
|
+
* `"New session - 1737800000000"`), assigned immediately when a session is
|
|
4462
|
+
* created — before OpenCode's async LLM-based auto-titling later renames it
|
|
4463
|
+
* mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
|
|
4464
|
+
* timestamp suffix's exact format is deliberately NOT matched, since the prefix
|
|
4465
|
+
* alone is the stable, cheap signal and over-anchoring on the timestamp
|
|
4466
|
+
* representation risks silently breaking if OpenCode ever changes it. Accepted
|
|
4467
|
+
* trade-off: a genuine LLM-assigned title that happens to literally start with
|
|
4468
|
+
* this prefix would also fail to latch (see `resolveSessionTitle`) —
|
|
4469
|
+
* vanishingly unlikely in practice, and deliberately not engineered around.
|
|
4470
|
+
*/
|
|
4471
|
+
static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
|
|
3547
4472
|
/**
|
|
3548
4473
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3549
4474
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3550
4475
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3551
4476
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3552
4477
|
* Best-effort:
|
|
3553
|
-
* - a resolved NON-EMPTY title
|
|
4478
|
+
* - a resolved NON-EMPTY title that does NOT match
|
|
4479
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
|
|
3554
4480
|
* 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
|
-
*
|
|
4481
|
+
* - while the title is still absent, empty, or matches the OpenCode
|
|
4482
|
+
* placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
|
|
4483
|
+
* asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
|
|
4484
|
+
* the cache unresolved and re-fetch on the next need so a later call (e.g. at
|
|
4485
|
+
* `done`) picks up the name assigned in the meantime. Such a call returns
|
|
4486
|
+
* `null` (omit the title on THIS PATCH) without caching. If a session is
|
|
4487
|
+
* never renamed, the title is omitted forever rather than ever persisting
|
|
4488
|
+
* the placeholder as a last resort;
|
|
3560
4489
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3561
4490
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3562
4491
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3569,7 +4498,7 @@ var ChannelDriver = class {
|
|
|
3569
4498
|
if (res.ok) {
|
|
3570
4499
|
const body = await res.json();
|
|
3571
4500
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3572
|
-
if (title.length > 0) {
|
|
4501
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3573
4502
|
this.sessionTitles.set(sessionId, title);
|
|
3574
4503
|
return title;
|
|
3575
4504
|
}
|
|
@@ -3589,6 +4518,54 @@ var ChannelDriver = class {
|
|
|
3589
4518
|
}
|
|
3590
4519
|
return null;
|
|
3591
4520
|
}
|
|
4521
|
+
/**
|
|
4522
|
+
* Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
|
|
4523
|
+
* session title onto the conversation via the PLAIN conversation-update
|
|
4524
|
+
* endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
|
|
4525
|
+
* message-status endpoint `markProcessing`/`markDone` use. Deliberately a
|
|
4526
|
+
* separate, lighter call: it carries no `status`, so it cannot re-trigger the
|
|
4527
|
+
* `processing`/`done` transition side effects (Slack notices, activity-log
|
|
4528
|
+
* rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
|
|
4529
|
+
* ever touches `conversations.title`. That route (`routes/conversations.ts`)
|
|
4530
|
+
* skips a title write matching the stored value, so a redundant call with the
|
|
4531
|
+
* same title is a real no-op — it does not bump `updated_at`, which the
|
|
4532
|
+
* conversation list sorts and paginates on. (Note this is a DIFFERENT guard
|
|
4533
|
+
* from `threads.ts`'s "non-empty AND changed" one, which only covers the
|
|
4534
|
+
* message-status PATCH; the non-empty half is enforced here instead, by
|
|
4535
|
+
* `resolveSessionTitle` never returning an empty/placeholder title.)
|
|
4536
|
+
*
|
|
4537
|
+
* Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
|
|
4538
|
+
* is logged and the title is simply retried on the next heartbeat tick (the
|
|
4539
|
+
* caller only latches `titleSynced` on `true`).
|
|
4540
|
+
*/
|
|
4541
|
+
async patchConversationTitle(conversationId, title) {
|
|
4542
|
+
try {
|
|
4543
|
+
const res = await this.fetchImpl(
|
|
4544
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
|
|
4545
|
+
{
|
|
4546
|
+
method: "PATCH",
|
|
4547
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
4548
|
+
body: JSON.stringify({ title })
|
|
4549
|
+
}
|
|
4550
|
+
);
|
|
4551
|
+
if (!res.ok) {
|
|
4552
|
+
this.log({
|
|
4553
|
+
level: "debug",
|
|
4554
|
+
message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
|
|
4555
|
+
conversation_id: conversationId
|
|
4556
|
+
});
|
|
4557
|
+
return false;
|
|
4558
|
+
}
|
|
4559
|
+
return true;
|
|
4560
|
+
} catch (err) {
|
|
4561
|
+
this.log({
|
|
4562
|
+
level: "debug",
|
|
4563
|
+
message: `Best-effort mid-turn title sync PATCH failed for conversation ${conversationId.slice(0, 8)} (will retry next heartbeat): ${err instanceof Error ? err.message : String(err)}`,
|
|
4564
|
+
conversation_id: conversationId
|
|
4565
|
+
});
|
|
4566
|
+
return false;
|
|
4567
|
+
}
|
|
4568
|
+
}
|
|
3592
4569
|
/**
|
|
3593
4570
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
3594
4571
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -3647,6 +4624,84 @@ var ChannelDriver = class {
|
|
|
3647
4624
|
}
|
|
3648
4625
|
return false;
|
|
3649
4626
|
}
|
|
4627
|
+
/**
|
|
4628
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4629
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4630
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4631
|
+
*
|
|
4632
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4633
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4634
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4635
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4636
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4637
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4638
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4639
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4640
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4641
|
+
* executing, between its step's completion and the next generation step"
|
|
4642
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4643
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4644
|
+
* message timestamps at all.
|
|
4645
|
+
*
|
|
4646
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4647
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4648
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4649
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4650
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4651
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4652
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4653
|
+
* delegation — which the root's status is not.
|
|
4654
|
+
*
|
|
4655
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4656
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4657
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4658
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4659
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4660
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4661
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4662
|
+
* instead.
|
|
4663
|
+
*
|
|
4664
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4665
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4666
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4667
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4668
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4669
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4670
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4671
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4672
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4673
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4674
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4675
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4676
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4677
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4678
|
+
* (unlike the recovery cross-check's contract) — see
|
|
4679
|
+
* `isB2AbandonmentConfirmed`.
|
|
4680
|
+
*/
|
|
4681
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
4682
|
+
const sessions = await listSessions(this.port);
|
|
4683
|
+
if (!sessions) {
|
|
4684
|
+
this.log({
|
|
4685
|
+
level: "warn",
|
|
4686
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
4687
|
+
});
|
|
4688
|
+
return null;
|
|
4689
|
+
}
|
|
4690
|
+
let indeterminate = false;
|
|
4691
|
+
for (const candidate of sessions) {
|
|
4692
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
4693
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
4694
|
+
if (membership === null) {
|
|
4695
|
+
indeterminate = true;
|
|
4696
|
+
continue;
|
|
4697
|
+
}
|
|
4698
|
+
if (membership === false) continue;
|
|
4699
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
4700
|
+
if (ongoing === true) return true;
|
|
4701
|
+
if (ongoing === null) indeterminate = true;
|
|
4702
|
+
}
|
|
4703
|
+
return indeterminate ? null : false;
|
|
4704
|
+
}
|
|
3650
4705
|
/**
|
|
3651
4706
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
3652
4707
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -3719,7 +4774,7 @@ var ChannelDriver = class {
|
|
|
3719
4774
|
// Evident API calls (combinedAuth thread routes)
|
|
3720
4775
|
async getPendingConversations() {
|
|
3721
4776
|
const res = await this.fetchImpl(
|
|
3722
|
-
`${this.apiUrl}/
|
|
4777
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
|
|
3723
4778
|
{
|
|
3724
4779
|
headers: { Authorization: this.getAuthHeader() }
|
|
3725
4780
|
}
|
|
@@ -3737,7 +4792,7 @@ var ChannelDriver = class {
|
|
|
3737
4792
|
}
|
|
3738
4793
|
async getPendingMessages(conversationId) {
|
|
3739
4794
|
const res = await this.fetchImpl(
|
|
3740
|
-
`${this.apiUrl}/
|
|
4795
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
|
|
3741
4796
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3742
4797
|
);
|
|
3743
4798
|
this.assertAuth(res, "fetching pending messages");
|
|
@@ -3761,7 +4816,7 @@ var ChannelDriver = class {
|
|
|
3761
4816
|
*/
|
|
3762
4817
|
async getProcessingMessages() {
|
|
3763
4818
|
const res = await this.fetchImpl(
|
|
3764
|
-
`${this.apiUrl}/
|
|
4819
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
|
|
3765
4820
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3766
4821
|
);
|
|
3767
4822
|
this.assertAuth(res, "fetching processing messages");
|
|
@@ -3775,6 +4830,32 @@ var ChannelDriver = class {
|
|
|
3775
4830
|
}
|
|
3776
4831
|
return messages;
|
|
3777
4832
|
}
|
|
4833
|
+
/**
|
|
4834
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
4835
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
4836
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
4837
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
4838
|
+
*
|
|
4839
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
4840
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
4841
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
4842
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
4843
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
4844
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
4845
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
4846
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
4847
|
+
* stick.
|
|
4848
|
+
*/
|
|
4849
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
4850
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
4851
|
+
this.log({
|
|
4852
|
+
level: "debug",
|
|
4853
|
+
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)}`,
|
|
4854
|
+
conversation_id: conversationId,
|
|
4855
|
+
message_id: messageId
|
|
4856
|
+
});
|
|
4857
|
+
return {};
|
|
4858
|
+
}
|
|
3778
4859
|
/**
|
|
3779
4860
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3780
4861
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3798,13 +4879,13 @@ var ChannelDriver = class {
|
|
|
3798
4879
|
*/
|
|
3799
4880
|
async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
3800
4881
|
const res = await this.fetchImpl(
|
|
3801
|
-
`${this.apiUrl}/
|
|
4882
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3802
4883
|
{
|
|
3803
4884
|
method: "PATCH",
|
|
3804
4885
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3805
4886
|
body: JSON.stringify({
|
|
3806
4887
|
status: "processing",
|
|
3807
|
-
|
|
4888
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3808
4889
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3809
4890
|
...title ? { title } : {}
|
|
3810
4891
|
})
|
|
@@ -3845,17 +4926,23 @@ var ChannelDriver = class {
|
|
|
3845
4926
|
* watcher retries next tick within the
|
|
3846
4927
|
* deadline, Finding 4).
|
|
3847
4928
|
*/
|
|
3848
|
-
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
4929
|
+
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
|
|
3849
4930
|
const res = await this.fetchImpl(
|
|
3850
|
-
`${this.apiUrl}/
|
|
4931
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3851
4932
|
{
|
|
3852
4933
|
method: "PATCH",
|
|
3853
4934
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3854
4935
|
body: JSON.stringify({
|
|
3855
4936
|
status: "done",
|
|
4937
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
4938
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
4939
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
4940
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
4941
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3856
4942
|
opencode_session_id: sessionId,
|
|
3857
4943
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3858
|
-
...title ? { title } : {}
|
|
4944
|
+
...title ? { title } : {},
|
|
4945
|
+
...usage ? usage : {}
|
|
3859
4946
|
})
|
|
3860
4947
|
}
|
|
3861
4948
|
);
|
|
@@ -3868,19 +4955,29 @@ var ChannelDriver = class {
|
|
|
3868
4955
|
}
|
|
3869
4956
|
/**
|
|
3870
4957
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3871
|
-
* when provided (issue #182)
|
|
3872
|
-
* `
|
|
3873
|
-
*
|
|
3874
|
-
*
|
|
4958
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
4959
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
4960
|
+
* session untouched (unused today; kept for API symmetry).
|
|
4961
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
4962
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
4963
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
4964
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
4965
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
4966
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
3875
4967
|
*/
|
|
3876
|
-
async markFailed(conversationId, messageId, sessionId, error2) {
|
|
4968
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
3877
4969
|
const body = { status: "failed" };
|
|
3878
|
-
if (sessionId
|
|
4970
|
+
if (sessionId === null) {
|
|
4971
|
+
body.opencode_session_id = null;
|
|
4972
|
+
} else if (sessionId !== void 0) {
|
|
4973
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
4974
|
+
}
|
|
3879
4975
|
if (error2 !== void 0) body.error = error2;
|
|
4976
|
+
if (usage) Object.assign(body, usage);
|
|
3880
4977
|
await this.callWithRetry(
|
|
3881
4978
|
"marking message as failed",
|
|
3882
4979
|
() => this.fetchImpl(
|
|
3883
|
-
`${this.apiUrl}/
|
|
4980
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3884
4981
|
{
|
|
3885
4982
|
method: "PATCH",
|
|
3886
4983
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3907,7 +5004,7 @@ var ChannelDriver = class {
|
|
|
3907
5004
|
async postSignal(conversationId, messageId, signal, extra) {
|
|
3908
5005
|
try {
|
|
3909
5006
|
const res = await this.fetchImpl(
|
|
3910
|
-
`${this.apiUrl}/
|
|
5007
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
|
|
3911
5008
|
{
|
|
3912
5009
|
method: "POST",
|
|
3913
5010
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3936,7 +5033,7 @@ var ChannelDriver = class {
|
|
|
3936
5033
|
}
|
|
3937
5034
|
async persistSession(conversationId, sessionId) {
|
|
3938
5035
|
const res = await this.fetchImpl(
|
|
3939
|
-
`${this.apiUrl}/
|
|
5036
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
|
|
3940
5037
|
{
|
|
3941
5038
|
method: "PATCH",
|
|
3942
5039
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3962,7 +5059,7 @@ var ChannelDriver = class {
|
|
|
3962
5059
|
await this.callWithRetry(
|
|
3963
5060
|
"reporting interactive event",
|
|
3964
5061
|
() => this.fetchImpl(
|
|
3965
|
-
`${this.apiUrl}/
|
|
5062
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
|
|
3966
5063
|
{
|
|
3967
5064
|
method: "POST",
|
|
3968
5065
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -4065,7 +5162,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4065
5162
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4066
5163
|
console.log(
|
|
4067
5164
|
chalk5.dim(
|
|
4068
|
-
` ${getCliName()} run --
|
|
5165
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4069
5166
|
)
|
|
4070
5167
|
);
|
|
4071
5168
|
}
|
|
@@ -4195,19 +5292,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4195
5292
|
return { agent_id: data.agent_id };
|
|
4196
5293
|
}
|
|
4197
5294
|
return {
|
|
4198
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5295
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
4199
5296
|
};
|
|
4200
5297
|
} catch (error2) {
|
|
4201
5298
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
4202
5299
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
4203
5300
|
}
|
|
4204
5301
|
}
|
|
5302
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
4205
5303
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4206
5304
|
const apiUrl = getApiUrlConfig();
|
|
4207
5305
|
try {
|
|
4208
|
-
const response = await fetch(`${apiUrl}/
|
|
5306
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4209
5307
|
method: "POST",
|
|
4210
|
-
headers: { Authorization: authHeader }
|
|
5308
|
+
headers: { Authorization: authHeader },
|
|
5309
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
4211
5310
|
});
|
|
4212
5311
|
if (!response.ok) {
|
|
4213
5312
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -4218,13 +5317,41 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4218
5317
|
}
|
|
4219
5318
|
return { ok: true };
|
|
4220
5319
|
} catch (error2) {
|
|
4221
|
-
return { ok: false, error:
|
|
5320
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5321
|
+
}
|
|
5322
|
+
}
|
|
5323
|
+
function describeBestEffortError(error2) {
|
|
5324
|
+
const name = error2?.name;
|
|
5325
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5326
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5327
|
+
}
|
|
5328
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5329
|
+
}
|
|
5330
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5331
|
+
try {
|
|
5332
|
+
const apiUrl = getApiUrlConfig();
|
|
5333
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5334
|
+
method: "POST",
|
|
5335
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5336
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5337
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5338
|
+
});
|
|
5339
|
+
if (!response.ok) {
|
|
5340
|
+
const serverMessage = await readErrorMessage(response);
|
|
5341
|
+
return {
|
|
5342
|
+
ok: false,
|
|
5343
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5344
|
+
};
|
|
5345
|
+
}
|
|
5346
|
+
return { ok: true };
|
|
5347
|
+
} catch (error2) {
|
|
5348
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
4222
5349
|
}
|
|
4223
5350
|
}
|
|
4224
5351
|
async function getAgentInfo(agentId, authHeader) {
|
|
4225
5352
|
const apiUrl = getApiUrlConfig();
|
|
4226
5353
|
try {
|
|
4227
|
-
const response = await fetch(`${apiUrl}/
|
|
5354
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}`, {
|
|
4228
5355
|
headers: { Authorization: authHeader }
|
|
4229
5356
|
});
|
|
4230
5357
|
if (response.status === 401) {
|
|
@@ -4268,6 +5395,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
4268
5395
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
4269
5396
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4270
5397
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5398
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
4271
5399
|
function resolveLogLevel(options) {
|
|
4272
5400
|
const accepted = Object.keys(LOG_LEVELS);
|
|
4273
5401
|
const validate = (value, source) => {
|
|
@@ -4291,6 +5419,34 @@ function resolveLogLevel(options) {
|
|
|
4291
5419
|
}
|
|
4292
5420
|
return "info";
|
|
4293
5421
|
}
|
|
5422
|
+
function resolveFileSyncDirectories(raw, homeDir) {
|
|
5423
|
+
const directories = [];
|
|
5424
|
+
for (const entry of raw ?? []) {
|
|
5425
|
+
const trimmed = entry.trim();
|
|
5426
|
+
if (trimmed === "") {
|
|
5427
|
+
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5428
|
+
}
|
|
5429
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
|
|
5430
|
+
if (!isAbsolute2(expanded)) {
|
|
5431
|
+
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5432
|
+
}
|
|
5433
|
+
const normalized = resolvePath(expanded);
|
|
5434
|
+
if (parse(normalized).root === normalized) {
|
|
5435
|
+
throw new Error(
|
|
5436
|
+
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
5437
|
+
);
|
|
5438
|
+
}
|
|
5439
|
+
if (!directories.includes(normalized)) {
|
|
5440
|
+
directories.push(normalized);
|
|
5441
|
+
}
|
|
5442
|
+
}
|
|
5443
|
+
if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
|
|
5444
|
+
throw new Error(
|
|
5445
|
+
`--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
|
|
5446
|
+
);
|
|
5447
|
+
}
|
|
5448
|
+
return directories;
|
|
5449
|
+
}
|
|
4294
5450
|
function meetsThreshold(state, level) {
|
|
4295
5451
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4296
5452
|
}
|
|
@@ -4412,18 +5568,29 @@ async function handleAuthError(state, error2) {
|
|
|
4412
5568
|
async function driveChannels(state, driver) {
|
|
4413
5569
|
let idlePolls = 0;
|
|
4414
5570
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5571
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4415
5572
|
while (state.running) {
|
|
4416
5573
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4417
5574
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4418
5575
|
if (state.interactive) displayStatus(state);
|
|
4419
5576
|
await state.connection.reconnectPromise;
|
|
4420
5577
|
}
|
|
5578
|
+
const carriedOverFileSync = driver.fileSyncActivity().inFlight;
|
|
5579
|
+
void driver.syncPendingFiles().catch(
|
|
5580
|
+
(error2) => logActivity(state, {
|
|
5581
|
+
type: "error",
|
|
5582
|
+
error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5583
|
+
})
|
|
5584
|
+
);
|
|
4421
5585
|
try {
|
|
4422
5586
|
const processed = await driver.drainPending();
|
|
4423
5587
|
state.messageCount += processed;
|
|
4424
5588
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4425
5589
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4426
|
-
|
|
5590
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5591
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
5592
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
5593
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4427
5594
|
idlePolls = 0;
|
|
4428
5595
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4429
5596
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4452,7 +5619,7 @@ async function driveChannels(state, driver) {
|
|
|
4452
5619
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4453
5620
|
if (state.interactive) displayStatus(state);
|
|
4454
5621
|
}
|
|
4455
|
-
await new Promise((
|
|
5622
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4456
5623
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4457
5624
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4458
5625
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4555,7 +5722,18 @@ async function notifyOffline(state) {
|
|
|
4555
5722
|
if (state.interactive) displayStatus(state);
|
|
4556
5723
|
}
|
|
4557
5724
|
}
|
|
5725
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
5726
|
+
const startedAt = Date.now();
|
|
5727
|
+
try {
|
|
5728
|
+
return await run2();
|
|
5729
|
+
} finally {
|
|
5730
|
+
const elapsedMs = Date.now() - startedAt;
|
|
5731
|
+
durations[name] = elapsedMs;
|
|
5732
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
5733
|
+
}
|
|
5734
|
+
}
|
|
4558
5735
|
async function cleanup(state, opts = {}) {
|
|
5736
|
+
const durations = {};
|
|
4559
5737
|
state.running = false;
|
|
4560
5738
|
for (const timer of state.sessionCleanupTimers) {
|
|
4561
5739
|
clearInterval(timer);
|
|
@@ -4569,7 +5747,13 @@ async function cleanup(state, opts = {}) {
|
|
|
4569
5747
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4570
5748
|
displayStatus(state);
|
|
4571
5749
|
}
|
|
4572
|
-
const
|
|
5750
|
+
const driver = state.channelDriver;
|
|
5751
|
+
const settled = await timeShutdownPhase(
|
|
5752
|
+
state,
|
|
5753
|
+
durations,
|
|
5754
|
+
"drain",
|
|
5755
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
5756
|
+
);
|
|
4573
5757
|
if (!settled) {
|
|
4574
5758
|
logActivity(state, {
|
|
4575
5759
|
type: "info",
|
|
@@ -4578,13 +5762,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4578
5762
|
if (state.interactive) displayStatus(state);
|
|
4579
5763
|
}
|
|
4580
5764
|
}
|
|
4581
|
-
await notifyOffline(state);
|
|
5765
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
4582
5766
|
if (state.connection) {
|
|
4583
|
-
state.connection
|
|
5767
|
+
const connection = state.connection;
|
|
5768
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
4584
5769
|
state.connection = null;
|
|
4585
5770
|
}
|
|
4586
5771
|
if (state.opencodeProcess) {
|
|
4587
|
-
|
|
5772
|
+
const opencodeProcess = state.opencodeProcess;
|
|
5773
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
4588
5774
|
if (state.interactive) {
|
|
4589
5775
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
4590
5776
|
displayStatus(state);
|
|
@@ -4593,12 +5779,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4593
5779
|
}
|
|
4594
5780
|
state.opencodeProcess = null;
|
|
4595
5781
|
}
|
|
5782
|
+
return durations;
|
|
4596
5783
|
}
|
|
4597
5784
|
async function run(options) {
|
|
4598
5785
|
const interactive = isInteractive(options.json);
|
|
4599
5786
|
let logLevel;
|
|
5787
|
+
let fileSyncDirectories;
|
|
4600
5788
|
try {
|
|
4601
5789
|
logLevel = resolveLogLevel(options);
|
|
5790
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
|
|
4602
5791
|
} catch (error2) {
|
|
4603
5792
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4604
5793
|
if (options.json) {
|
|
@@ -4611,7 +5800,7 @@ async function run(options) {
|
|
|
4611
5800
|
return;
|
|
4612
5801
|
}
|
|
4613
5802
|
const state = {
|
|
4614
|
-
agentId: options.agent || "",
|
|
5803
|
+
agentId: options.runner || options.agent || "",
|
|
4615
5804
|
agentName: null,
|
|
4616
5805
|
port: options.port ?? 4096,
|
|
4617
5806
|
conversationFilter: options.conversation ?? null,
|
|
@@ -4633,6 +5822,24 @@ async function run(options) {
|
|
|
4633
5822
|
sessionCleanupTimers: [],
|
|
4634
5823
|
authHeader: ""
|
|
4635
5824
|
};
|
|
5825
|
+
if (fileSyncDirectories.length > 0) {
|
|
5826
|
+
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5827
|
+
} else {
|
|
5828
|
+
log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
|
|
5829
|
+
}
|
|
5830
|
+
if (!options.runner && options.agent) {
|
|
5831
|
+
telemetry.info(
|
|
5832
|
+
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
5833
|
+
"Deprecated --agent flag used instead of --runner",
|
|
5834
|
+
{ command: "run" },
|
|
5835
|
+
state.agentId
|
|
5836
|
+
);
|
|
5837
|
+
const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
|
|
5838
|
+
log2(state, agentFlagNotice, "warn");
|
|
5839
|
+
if (state.interactive && !state.json) {
|
|
5840
|
+
logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
|
|
5841
|
+
}
|
|
5842
|
+
}
|
|
4636
5843
|
if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
|
|
4637
5844
|
log2(
|
|
4638
5845
|
state,
|
|
@@ -4643,14 +5850,38 @@ async function run(options) {
|
|
|
4643
5850
|
const handleSignal = async () => {
|
|
4644
5851
|
if (state.shuttingDown) return;
|
|
4645
5852
|
state.shuttingDown = true;
|
|
5853
|
+
const shutdownStartedAt = Date.now();
|
|
4646
5854
|
if (state.interactive) {
|
|
4647
5855
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
4648
5856
|
displayStatus(state);
|
|
4649
5857
|
} else {
|
|
4650
5858
|
log2(state, "Shutting down...");
|
|
4651
5859
|
}
|
|
4652
|
-
await cleanup(state, { graceful: true });
|
|
4653
|
-
|
|
5860
|
+
const durations = await cleanup(state, { graceful: true });
|
|
5861
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
5862
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
5863
|
+
let timer;
|
|
5864
|
+
const flushed = shutdownTelemetry().then(
|
|
5865
|
+
() => true,
|
|
5866
|
+
(error2) => {
|
|
5867
|
+
log2(
|
|
5868
|
+
state,
|
|
5869
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
5870
|
+
"warn"
|
|
5871
|
+
);
|
|
5872
|
+
return true;
|
|
5873
|
+
}
|
|
5874
|
+
);
|
|
5875
|
+
const timedOut = new Promise((resolve3) => {
|
|
5876
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
5877
|
+
});
|
|
5878
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
5879
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
5880
|
+
}
|
|
5881
|
+
clearTimeout(timer);
|
|
5882
|
+
});
|
|
5883
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
5884
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
4654
5885
|
process.exit(0);
|
|
4655
5886
|
};
|
|
4656
5887
|
process.on("SIGINT", handleSignal);
|
|
@@ -4661,7 +5892,9 @@ async function run(options) {
|
|
|
4661
5892
|
if (!interactive) {
|
|
4662
5893
|
printError("Authentication required");
|
|
4663
5894
|
blank();
|
|
4664
|
-
console.log(
|
|
5895
|
+
console.log(
|
|
5896
|
+
chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
|
|
5897
|
+
);
|
|
4665
5898
|
console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
|
|
4666
5899
|
blank();
|
|
4667
5900
|
process.exit(1);
|
|
@@ -4675,6 +5908,25 @@ async function run(options) {
|
|
|
4675
5908
|
);
|
|
4676
5909
|
}
|
|
4677
5910
|
state.authHeader = getAuthHeader(credentials2);
|
|
5911
|
+
if (credentials2.notice) {
|
|
5912
|
+
log2(state, credentials2.notice, "warn");
|
|
5913
|
+
if (state.interactive && !state.json) {
|
|
5914
|
+
logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
|
|
5915
|
+
}
|
|
5916
|
+
}
|
|
5917
|
+
if (credentials2.keySource === "agent_key") {
|
|
5918
|
+
telemetry.info(
|
|
5919
|
+
EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
|
|
5920
|
+
"Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
|
|
5921
|
+
{ command: "run" },
|
|
5922
|
+
state.agentId
|
|
5923
|
+
);
|
|
5924
|
+
const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
|
|
5925
|
+
log2(state, agentKeyNotice, "warn");
|
|
5926
|
+
if (state.interactive && !state.json) {
|
|
5927
|
+
logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
|
|
5928
|
+
}
|
|
5929
|
+
}
|
|
4678
5930
|
if (!state.agentId) {
|
|
4679
5931
|
if (credentials2.authType === "agent_key") {
|
|
4680
5932
|
const resolved = await resolveAgentIdFromKey(state.authHeader);
|
|
@@ -4692,9 +5944,15 @@ async function run(options) {
|
|
|
4692
5944
|
process.exit(1);
|
|
4693
5945
|
}
|
|
4694
5946
|
} else {
|
|
4695
|
-
printError(
|
|
5947
|
+
printError(
|
|
5948
|
+
"--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
|
|
5949
|
+
);
|
|
4696
5950
|
blank();
|
|
4697
|
-
console.log(
|
|
5951
|
+
console.log(
|
|
5952
|
+
chalk6.dim(
|
|
5953
|
+
"Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
|
|
5954
|
+
)
|
|
5955
|
+
);
|
|
4698
5956
|
blank();
|
|
4699
5957
|
process.exit(1);
|
|
4700
5958
|
}
|
|
@@ -4737,6 +5995,21 @@ async function run(options) {
|
|
|
4737
5995
|
}
|
|
4738
5996
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
4739
5997
|
state.agentName = validation.agent.name;
|
|
5998
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
5999
|
+
if (microvmId) {
|
|
6000
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
6001
|
+
if (reported.ok) {
|
|
6002
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
6003
|
+
} else {
|
|
6004
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
6005
|
+
log2(state, message, "warn");
|
|
6006
|
+
if (state.interactive && !state.json) {
|
|
6007
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6008
|
+
}
|
|
6009
|
+
}
|
|
6010
|
+
} else {
|
|
6011
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6012
|
+
}
|
|
4740
6013
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
4741
6014
|
try {
|
|
4742
6015
|
const oc = await ensureOpenCodeRunning({
|
|
@@ -4758,6 +6031,21 @@ async function run(options) {
|
|
|
4758
6031
|
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
4759
6032
|
}
|
|
4760
6033
|
}
|
|
6034
|
+
const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
|
|
6035
|
+
if (noProviderWarning) {
|
|
6036
|
+
log2(state, noProviderWarning, "warn");
|
|
6037
|
+
if (state.interactive && !state.json) {
|
|
6038
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6039
|
+
blank();
|
|
6040
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6041
|
+
console.log(
|
|
6042
|
+
chalk6.dim(
|
|
6043
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6044
|
+
)
|
|
6045
|
+
);
|
|
6046
|
+
blank();
|
|
6047
|
+
}
|
|
6048
|
+
}
|
|
4761
6049
|
} catch (error2) {
|
|
4762
6050
|
ocSpinner?.fail(error2.message);
|
|
4763
6051
|
throw error2;
|
|
@@ -4770,6 +6058,10 @@ async function run(options) {
|
|
|
4770
6058
|
getAuthHeader: () => state.authHeader,
|
|
4771
6059
|
conversationFilter: state.conversationFilter,
|
|
4772
6060
|
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
6061
|
+
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
6062
|
+
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
6063
|
+
fileSyncDirectories,
|
|
6064
|
+
homeDir: homedir2(),
|
|
4773
6065
|
log: (entry) => (
|
|
4774
6066
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4775
6067
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4796,6 +6088,18 @@ async function run(options) {
|
|
|
4796
6088
|
type: "info",
|
|
4797
6089
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
4798
6090
|
});
|
|
6091
|
+
if (options.tunnelReadyFile) {
|
|
6092
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6093
|
+
if (marker.ok) {
|
|
6094
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6095
|
+
} else {
|
|
6096
|
+
log2(
|
|
6097
|
+
state,
|
|
6098
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6099
|
+
"error"
|
|
6100
|
+
);
|
|
6101
|
+
}
|
|
6102
|
+
}
|
|
4799
6103
|
emitAgentConnected(state.agentId, {
|
|
4800
6104
|
port: state.port,
|
|
4801
6105
|
cli_version: getCliVersion(),
|
|
@@ -4851,6 +6155,12 @@ async function run(options) {
|
|
|
4851
6155
|
onDrainPing: () => {
|
|
4852
6156
|
if (!state.running) return;
|
|
4853
6157
|
logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
|
|
6158
|
+
void channelDriver.syncPendingFiles().catch(
|
|
6159
|
+
(error2) => logActivity(state, {
|
|
6160
|
+
type: "error",
|
|
6161
|
+
error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
6162
|
+
})
|
|
6163
|
+
);
|
|
4854
6164
|
channelDriver.drainPending().then((processed) => {
|
|
4855
6165
|
if (processed > 0) {
|
|
4856
6166
|
state.messageCount += processed;
|
|
@@ -4909,7 +6219,7 @@ async function run(options) {
|
|
|
4909
6219
|
}
|
|
4910
6220
|
telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
|
|
4911
6221
|
command: "run",
|
|
4912
|
-
agentId: options.agent
|
|
6222
|
+
agentId: options.runner || options.agent
|
|
4913
6223
|
});
|
|
4914
6224
|
await shutdownTelemetry();
|
|
4915
6225
|
process.exit(1);
|
|
@@ -4934,7 +6244,10 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
4934
6244
|
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
6245
|
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
6246
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
4937
|
-
program.command("run").description("Connect to Evident and process messages").option("
|
|
6247
|
+
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(
|
|
6248
|
+
"-a, --agent [id]",
|
|
6249
|
+
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
6250
|
+
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
4938
6251
|
"--log-level <level>",
|
|
4939
6252
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
4940
6253
|
).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 +6259,19 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4946
6259
|
).option(
|
|
4947
6260
|
"--session-cleanup-interval <duration>",
|
|
4948
6261
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6262
|
+
).option(
|
|
6263
|
+
"--enable-file-sync-to <dir>",
|
|
6264
|
+
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
6265
|
+
(value, previous) => previous.concat([value]),
|
|
6266
|
+
[]
|
|
6267
|
+
).option(
|
|
6268
|
+
"--tunnel-ready-file <path>",
|
|
6269
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
4949
6270
|
).action(
|
|
4950
6271
|
(options) => {
|
|
4951
6272
|
run({
|
|
4952
6273
|
agent: options.agent,
|
|
6274
|
+
runner: options.runner,
|
|
4953
6275
|
port: parseInt(options.port, 10),
|
|
4954
6276
|
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
4955
6277
|
// resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
|
|
@@ -4961,7 +6283,11 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4961
6283
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
4962
6284
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
4963
6285
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
4964
|
-
sessionCleanupInterval: options.sessionCleanupInterval
|
|
6286
|
+
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6287
|
+
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6288
|
+
// resolveFileSyncDirectories.
|
|
6289
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6290
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
4965
6291
|
});
|
|
4966
6292
|
}
|
|
4967
6293
|
);
|