@evident-ai/cli 3.1.1-dev.9ff0701 → 3.1.1-dev.a4167a6
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 +1555 -155
- 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);
|
|
@@ -1399,12 +1548,79 @@ function messageError(messages, userMessageId) {
|
|
|
1399
1548
|
}
|
|
1400
1549
|
return "The agent run failed.";
|
|
1401
1550
|
}
|
|
1551
|
+
function messageFailure(messages, userMessageId) {
|
|
1552
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1553
|
+
const error2 = errorOf(reply);
|
|
1554
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
1555
|
+
const e = error2;
|
|
1556
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
1557
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
1558
|
+
if (e.name === "ProviderAuthError") {
|
|
1559
|
+
const data = e.data;
|
|
1560
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
1561
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
1562
|
+
}
|
|
1563
|
+
if (e.name === "APIError") {
|
|
1564
|
+
const data = e.data;
|
|
1565
|
+
const statusCode = data?.statusCode;
|
|
1566
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
1567
|
+
return {
|
|
1568
|
+
kind: "model_auth",
|
|
1569
|
+
providerId: replyProviderId,
|
|
1570
|
+
modelId: replyModelId,
|
|
1571
|
+
reason: "rejected"
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
return null;
|
|
1576
|
+
}
|
|
1577
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
1578
|
+
if (classified != null) return classified;
|
|
1579
|
+
if (hasConfiguredProvider !== false) return null;
|
|
1580
|
+
return {
|
|
1581
|
+
kind: "model_auth",
|
|
1582
|
+
providerId: replyProviderId,
|
|
1583
|
+
modelId: replyModelId,
|
|
1584
|
+
reason: "missing"
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1402
1587
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1403
1588
|
if (!messages || messages.length === 0) return false;
|
|
1404
1589
|
return messages.some(
|
|
1405
1590
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1406
1591
|
);
|
|
1407
1592
|
}
|
|
1593
|
+
async function hasAnyConfiguredProvider(port) {
|
|
1594
|
+
try {
|
|
1595
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1596
|
+
if (!res.ok) {
|
|
1597
|
+
console.error(
|
|
1598
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1599
|
+
);
|
|
1600
|
+
return null;
|
|
1601
|
+
}
|
|
1602
|
+
const body = await res.json();
|
|
1603
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1604
|
+
console.error(
|
|
1605
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
1606
|
+
);
|
|
1607
|
+
return null;
|
|
1608
|
+
}
|
|
1609
|
+
const defaults2 = body.default;
|
|
1610
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
1611
|
+
console.error(
|
|
1612
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
1613
|
+
);
|
|
1614
|
+
return null;
|
|
1615
|
+
}
|
|
1616
|
+
return Object.keys(defaults2).length > 0;
|
|
1617
|
+
} catch (err) {
|
|
1618
|
+
console.error(
|
|
1619
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1620
|
+
);
|
|
1621
|
+
return null;
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1408
1624
|
|
|
1409
1625
|
// src/lib/opencode/session-cleanup.ts
|
|
1410
1626
|
var DURATION_UNIT_MS = {
|
|
@@ -1563,10 +1779,11 @@ var StreamForwarder = class {
|
|
|
1563
1779
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1564
1780
|
*/
|
|
1565
1781
|
abortAll() {
|
|
1566
|
-
for (const stream of this.inflight.
|
|
1782
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1567
1783
|
try {
|
|
1568
1784
|
stream.abort();
|
|
1569
|
-
} catch {
|
|
1785
|
+
} catch (err) {
|
|
1786
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1570
1787
|
}
|
|
1571
1788
|
}
|
|
1572
1789
|
this.inflight.clear();
|
|
@@ -1600,12 +1817,12 @@ var StreamForwarder = class {
|
|
|
1600
1817
|
let endBody;
|
|
1601
1818
|
if (has_body) {
|
|
1602
1819
|
const chunks = [];
|
|
1603
|
-
bodyPromise = new Promise((
|
|
1820
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1604
1821
|
pushBody = (buf) => {
|
|
1605
1822
|
chunks.push(buf);
|
|
1606
1823
|
};
|
|
1607
1824
|
endBody = () => {
|
|
1608
|
-
|
|
1825
|
+
resolve3(Buffer.concat(chunks));
|
|
1609
1826
|
};
|
|
1610
1827
|
});
|
|
1611
1828
|
}
|
|
@@ -1716,31 +1933,20 @@ function connectTunnel(options) {
|
|
|
1716
1933
|
onConnected,
|
|
1717
1934
|
onDisconnected,
|
|
1718
1935
|
onError,
|
|
1719
|
-
onRequest,
|
|
1720
1936
|
onResponse,
|
|
1721
1937
|
onInfo,
|
|
1722
1938
|
onDrainPing
|
|
1723
1939
|
} = options;
|
|
1724
1940
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1725
1941
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1726
|
-
return new Promise((
|
|
1942
|
+
return new Promise((resolve3, reject) => {
|
|
1727
1943
|
const ws = new WebSocket2(url, {
|
|
1728
1944
|
headers: {
|
|
1729
1945
|
Authorization: authHeader
|
|
1730
1946
|
}
|
|
1731
1947
|
});
|
|
1732
|
-
const streamStartTimes = /* @__PURE__ */ new Map();
|
|
1733
1948
|
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
|
-
},
|
|
1949
|
+
onHead: () => onResponse?.(),
|
|
1744
1950
|
onDrainPing: () => onDrainPing?.()
|
|
1745
1951
|
});
|
|
1746
1952
|
const connectionTimeout = setTimeout(() => {
|
|
@@ -1788,7 +1994,7 @@ function connectTunnel(options) {
|
|
|
1788
1994
|
clearTimeout(connectionTimeout);
|
|
1789
1995
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1790
1996
|
onConnected?.(connectedAgentId);
|
|
1791
|
-
|
|
1997
|
+
resolve3({
|
|
1792
1998
|
ws,
|
|
1793
1999
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1794
2000
|
});
|
|
@@ -1816,7 +2022,6 @@ function connectTunnel(options) {
|
|
|
1816
2022
|
ws.on("close", (code, reason) => {
|
|
1817
2023
|
const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
|
|
1818
2024
|
forwarder.abortAll();
|
|
1819
|
-
streamStartTimes.clear();
|
|
1820
2025
|
onDisconnected?.(code, reasonStr);
|
|
1821
2026
|
});
|
|
1822
2027
|
});
|
|
@@ -1851,7 +2056,11 @@ var RunnerConnection = class {
|
|
|
1851
2056
|
if (this.connection) {
|
|
1852
2057
|
try {
|
|
1853
2058
|
this.connection.close();
|
|
1854
|
-
} catch {
|
|
2059
|
+
} catch (err) {
|
|
2060
|
+
log("error", "runner_connection_close_failed", {
|
|
2061
|
+
agent_id: this.resolvedAgentId,
|
|
2062
|
+
...errorFields(err)
|
|
2063
|
+
});
|
|
1855
2064
|
}
|
|
1856
2065
|
this.connection = null;
|
|
1857
2066
|
}
|
|
@@ -1903,6 +2112,416 @@ var RunnerConnection = class {
|
|
|
1903
2112
|
}
|
|
1904
2113
|
};
|
|
1905
2114
|
|
|
2115
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2116
|
+
import { writeFileSync } from "fs";
|
|
2117
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2118
|
+
try {
|
|
2119
|
+
writeFileSync(path, `${agentId}
|
|
2120
|
+
`);
|
|
2121
|
+
return { ok: true };
|
|
2122
|
+
} catch (error2) {
|
|
2123
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
// src/lib/channels/driver.ts
|
|
2128
|
+
import { homedir } from "os";
|
|
2129
|
+
|
|
2130
|
+
// src/lib/file-push.ts
|
|
2131
|
+
import { randomUUID } from "crypto";
|
|
2132
|
+
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2133
|
+
import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
|
|
2134
|
+
var FILE_MODE = 384;
|
|
2135
|
+
var DIRECTORY_MODE = 448;
|
|
2136
|
+
async function writePushedFile(request) {
|
|
2137
|
+
const { requestedPath, content, allowedDirectories, homeDir } = request;
|
|
2138
|
+
const bytes = content.byteLength;
|
|
2139
|
+
if (allowedDirectories.length === 0) {
|
|
2140
|
+
return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
2141
|
+
path: requestedPath,
|
|
2142
|
+
bytes
|
|
2143
|
+
});
|
|
2144
|
+
}
|
|
2145
|
+
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
2146
|
+
return refuse(
|
|
2147
|
+
"file_too_large",
|
|
2148
|
+
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
2149
|
+
{
|
|
2150
|
+
path: requestedPath,
|
|
2151
|
+
bytes
|
|
2152
|
+
}
|
|
2153
|
+
);
|
|
2154
|
+
}
|
|
2155
|
+
const candidate = expandAndValidate(requestedPath, homeDir);
|
|
2156
|
+
if (candidate === null) {
|
|
2157
|
+
return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
2158
|
+
path: requestedPath,
|
|
2159
|
+
bytes
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
try {
|
|
2163
|
+
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2164
|
+
dirname2(candidate)
|
|
2165
|
+
);
|
|
2166
|
+
const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
|
|
2167
|
+
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2168
|
+
if (allowedDirectory === null) {
|
|
2169
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2170
|
+
path: realTarget,
|
|
2171
|
+
bytes
|
|
2172
|
+
});
|
|
2173
|
+
}
|
|
2174
|
+
if (missingSegments.length > 0) {
|
|
2175
|
+
await createMissingDirectories(existingAncestor, missingSegments);
|
|
2176
|
+
const realParent = await realpath(dirname2(realTarget));
|
|
2177
|
+
if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
2178
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2179
|
+
path: realTarget,
|
|
2180
|
+
bytes,
|
|
2181
|
+
reason: "parent_changed_after_create"
|
|
2182
|
+
});
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
await writeAtomically(realTarget, content);
|
|
2186
|
+
log("info", "file_push_written", { path: realTarget, bytes });
|
|
2187
|
+
return { ok: true, path: realTarget };
|
|
2188
|
+
} catch (err) {
|
|
2189
|
+
const errno = err.code ?? "UNKNOWN";
|
|
2190
|
+
return refuse("write_failed", `The runner could not write the file (${errno}).`, {
|
|
2191
|
+
path: candidate,
|
|
2192
|
+
bytes,
|
|
2193
|
+
errno,
|
|
2194
|
+
...errorFields(err)
|
|
2195
|
+
});
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
function expandAndValidate(requestedPath, homeDir) {
|
|
2199
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2200
|
+
return null;
|
|
2201
|
+
}
|
|
2202
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2203
|
+
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2204
|
+
return null;
|
|
2205
|
+
}
|
|
2206
|
+
if (!isAbsolute(expanded)) {
|
|
2207
|
+
return null;
|
|
2208
|
+
}
|
|
2209
|
+
const candidate = resolve2(expanded);
|
|
2210
|
+
const name = basename(candidate);
|
|
2211
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
2212
|
+
}
|
|
2213
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
2214
|
+
const missingSegments = [];
|
|
2215
|
+
let current = directory;
|
|
2216
|
+
for (; ; ) {
|
|
2217
|
+
try {
|
|
2218
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
2219
|
+
} catch (err) {
|
|
2220
|
+
const parent = dirname2(current);
|
|
2221
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
2222
|
+
throw err;
|
|
2223
|
+
}
|
|
2224
|
+
missingSegments.unshift(basename(current));
|
|
2225
|
+
current = parent;
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
2230
|
+
for (const directory of allowedDirectories) {
|
|
2231
|
+
if (!isAbsolute(directory)) {
|
|
2232
|
+
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
2233
|
+
continue;
|
|
2234
|
+
}
|
|
2235
|
+
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
2236
|
+
if (realDirectory !== null && contains(realDirectory, realTarget)) {
|
|
2237
|
+
return realDirectory;
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
return null;
|
|
2241
|
+
}
|
|
2242
|
+
async function realpathCreatingIfMissing(directory) {
|
|
2243
|
+
try {
|
|
2244
|
+
return await realpath(directory);
|
|
2245
|
+
} catch (err) {
|
|
2246
|
+
if (err.code !== "ENOENT") {
|
|
2247
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2248
|
+
directory,
|
|
2249
|
+
reason: "unresolvable",
|
|
2250
|
+
...errorFields(err)
|
|
2251
|
+
});
|
|
2252
|
+
return null;
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
try {
|
|
2256
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
2257
|
+
await chmod(directory, DIRECTORY_MODE);
|
|
2258
|
+
return await realpath(directory);
|
|
2259
|
+
} catch (err) {
|
|
2260
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2261
|
+
directory,
|
|
2262
|
+
reason: "create_failed",
|
|
2263
|
+
...errorFields(err)
|
|
2264
|
+
});
|
|
2265
|
+
return null;
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
function contains(realDirectory, realTarget) {
|
|
2269
|
+
const rel = relative(realDirectory, realTarget);
|
|
2270
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
2271
|
+
}
|
|
2272
|
+
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2273
|
+
let current = existingAncestor;
|
|
2274
|
+
for (const segment of missingSegments) {
|
|
2275
|
+
current = join(current, segment);
|
|
2276
|
+
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2277
|
+
await chmod(current, DIRECTORY_MODE);
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
async function writeAtomically(realTarget, content) {
|
|
2281
|
+
const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2282
|
+
let handle;
|
|
2283
|
+
try {
|
|
2284
|
+
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
2285
|
+
await handle.writeFile(content);
|
|
2286
|
+
await handle.chmod(FILE_MODE);
|
|
2287
|
+
await handle.close();
|
|
2288
|
+
handle = void 0;
|
|
2289
|
+
await rename(temporaryPath, realTarget);
|
|
2290
|
+
} catch (err) {
|
|
2291
|
+
await discardTemporaryFile(temporaryPath, handle);
|
|
2292
|
+
throw err;
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
async function discardTemporaryFile(temporaryPath, handle) {
|
|
2296
|
+
try {
|
|
2297
|
+
await handle?.close();
|
|
2298
|
+
} catch (err) {
|
|
2299
|
+
log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2300
|
+
}
|
|
2301
|
+
try {
|
|
2302
|
+
await unlink(temporaryPath);
|
|
2303
|
+
} catch (err) {
|
|
2304
|
+
const errno = err.code;
|
|
2305
|
+
if (errno !== "ENOENT" && errno !== "ENOTDIR") {
|
|
2306
|
+
log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
function refuse(code, message, fields) {
|
|
2311
|
+
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
2312
|
+
return { ok: false, code, message };
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2315
|
+
// src/lib/runner-file-sync.ts
|
|
2316
|
+
var MAX_ACK_ATTEMPTS = 5;
|
|
2317
|
+
async function syncPendingRunnerFiles(options) {
|
|
2318
|
+
const pending = await listPendingFiles(options);
|
|
2319
|
+
const pendingIds = new Set(pending.map((file) => file.id));
|
|
2320
|
+
for (const id of options.ackFailures.keys()) {
|
|
2321
|
+
if (!pendingIds.has(id)) options.ackFailures.delete(id);
|
|
2322
|
+
}
|
|
2323
|
+
if (pending.length === 0) return 0;
|
|
2324
|
+
options.log({
|
|
2325
|
+
level: "info",
|
|
2326
|
+
message: `Runner file sync: ${pending.length} file(s) queued for this runner`
|
|
2327
|
+
});
|
|
2328
|
+
let applied = 0;
|
|
2329
|
+
for (const file of pending) {
|
|
2330
|
+
if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
|
|
2331
|
+
if (await applyOne(options, file)) applied += 1;
|
|
2332
|
+
}
|
|
2333
|
+
return applied;
|
|
2334
|
+
}
|
|
2335
|
+
async function listPendingFiles(options) {
|
|
2336
|
+
let res;
|
|
2337
|
+
try {
|
|
2338
|
+
res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
|
|
2339
|
+
headers: { Authorization: options.getAuthHeader() }
|
|
2340
|
+
});
|
|
2341
|
+
} catch (err) {
|
|
2342
|
+
options.log({
|
|
2343
|
+
level: "warn",
|
|
2344
|
+
message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
|
|
2345
|
+
});
|
|
2346
|
+
return [];
|
|
2347
|
+
}
|
|
2348
|
+
if (!res.ok) {
|
|
2349
|
+
options.log({
|
|
2350
|
+
level: res.status === 404 ? "debug" : "warn",
|
|
2351
|
+
message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2352
|
+
});
|
|
2353
|
+
return [];
|
|
2354
|
+
}
|
|
2355
|
+
let body;
|
|
2356
|
+
try {
|
|
2357
|
+
body = await res.json();
|
|
2358
|
+
} catch (err) {
|
|
2359
|
+
options.log({
|
|
2360
|
+
level: "warn",
|
|
2361
|
+
message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
|
|
2362
|
+
});
|
|
2363
|
+
return [];
|
|
2364
|
+
}
|
|
2365
|
+
if (!Array.isArray(body)) {
|
|
2366
|
+
options.log({
|
|
2367
|
+
level: "warn",
|
|
2368
|
+
message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
|
|
2369
|
+
});
|
|
2370
|
+
return [];
|
|
2371
|
+
}
|
|
2372
|
+
const files = [];
|
|
2373
|
+
for (const entry of body) {
|
|
2374
|
+
const file = asPendingFile(entry);
|
|
2375
|
+
if (file === null) {
|
|
2376
|
+
options.log({
|
|
2377
|
+
level: "warn",
|
|
2378
|
+
message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
|
|
2379
|
+
});
|
|
2380
|
+
continue;
|
|
2381
|
+
}
|
|
2382
|
+
files.push(file);
|
|
2383
|
+
}
|
|
2384
|
+
return files;
|
|
2385
|
+
}
|
|
2386
|
+
function asPendingFile(entry) {
|
|
2387
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
2388
|
+
const { id, path, size } = entry;
|
|
2389
|
+
if (typeof id !== "string" || id === "") return null;
|
|
2390
|
+
if (typeof path !== "string" || path === "") return null;
|
|
2391
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
|
|
2392
|
+
return { id, path, size };
|
|
2393
|
+
}
|
|
2394
|
+
async function applyOne(options, file) {
|
|
2395
|
+
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
2396
|
+
if (options.allowedDirectories.length === 0) {
|
|
2397
|
+
options.log({
|
|
2398
|
+
level: "warn",
|
|
2399
|
+
message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
|
|
2400
|
+
});
|
|
2401
|
+
await ack(options, file, "rejected", "file_sync_disabled");
|
|
2402
|
+
return false;
|
|
2403
|
+
}
|
|
2404
|
+
if (file.size > MAX_FILE_PUSH_BYTES) {
|
|
2405
|
+
options.log({
|
|
2406
|
+
level: "warn",
|
|
2407
|
+
message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
|
|
2408
|
+
});
|
|
2409
|
+
await ack(options, file, "rejected", "file_too_large");
|
|
2410
|
+
return false;
|
|
2411
|
+
}
|
|
2412
|
+
const download = await downloadContent(options, file, label);
|
|
2413
|
+
if (!download.ok) {
|
|
2414
|
+
if (download.terminal) await ack(options, file, "rejected", download.code);
|
|
2415
|
+
return false;
|
|
2416
|
+
}
|
|
2417
|
+
let outcome;
|
|
2418
|
+
try {
|
|
2419
|
+
outcome = await writePushedFile({
|
|
2420
|
+
requestedPath: file.path,
|
|
2421
|
+
content: download.content,
|
|
2422
|
+
allowedDirectories: options.allowedDirectories,
|
|
2423
|
+
homeDir: options.homeDir
|
|
2424
|
+
});
|
|
2425
|
+
} catch (err) {
|
|
2426
|
+
options.log({
|
|
2427
|
+
level: "error",
|
|
2428
|
+
message: `Runner file ${label} could not be written: ${describe(err)}`
|
|
2429
|
+
});
|
|
2430
|
+
await ack(options, file, "rejected", "write_failed");
|
|
2431
|
+
return false;
|
|
2432
|
+
}
|
|
2433
|
+
if (!outcome.ok) {
|
|
2434
|
+
options.log({
|
|
2435
|
+
level: "warn",
|
|
2436
|
+
message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
|
|
2437
|
+
});
|
|
2438
|
+
await ack(options, file, "rejected", outcome.code);
|
|
2439
|
+
return false;
|
|
2440
|
+
}
|
|
2441
|
+
options.log({
|
|
2442
|
+
level: "info",
|
|
2443
|
+
message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
|
|
2444
|
+
});
|
|
2445
|
+
await ack(options, file, "applied");
|
|
2446
|
+
return true;
|
|
2447
|
+
}
|
|
2448
|
+
function durableDownloadCode(status) {
|
|
2449
|
+
return status === 413 ? "file_too_large" : "write_failed";
|
|
2450
|
+
}
|
|
2451
|
+
async function downloadContent(options, file, label) {
|
|
2452
|
+
try {
|
|
2453
|
+
const res = await options.fetchImpl(
|
|
2454
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
|
|
2455
|
+
{ headers: { Authorization: options.getAuthHeader() } }
|
|
2456
|
+
);
|
|
2457
|
+
if (!res.ok) {
|
|
2458
|
+
const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
|
|
2459
|
+
if (!terminal) {
|
|
2460
|
+
options.log({
|
|
2461
|
+
level: "warn",
|
|
2462
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2463
|
+
});
|
|
2464
|
+
return { ok: false, terminal: false };
|
|
2465
|
+
}
|
|
2466
|
+
const code = durableDownloadCode(res.status);
|
|
2467
|
+
options.log({
|
|
2468
|
+
level: "error",
|
|
2469
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
|
|
2470
|
+
});
|
|
2471
|
+
return { ok: false, terminal: true, code };
|
|
2472
|
+
}
|
|
2473
|
+
return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
|
|
2474
|
+
} catch (err) {
|
|
2475
|
+
options.log({
|
|
2476
|
+
level: "warn",
|
|
2477
|
+
message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
|
|
2478
|
+
});
|
|
2479
|
+
return { ok: false, terminal: false };
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
async function ack(options, file, status, reason) {
|
|
2483
|
+
const outcome = `${status}${reason ? ` (${reason})` : ""}`;
|
|
2484
|
+
try {
|
|
2485
|
+
const res = await options.fetchImpl(
|
|
2486
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
2487
|
+
{
|
|
2488
|
+
method: "POST",
|
|
2489
|
+
headers: {
|
|
2490
|
+
Authorization: options.getAuthHeader(),
|
|
2491
|
+
"Content-Type": "application/json"
|
|
2492
|
+
},
|
|
2493
|
+
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
2494
|
+
}
|
|
2495
|
+
);
|
|
2496
|
+
if (!res.ok) {
|
|
2497
|
+
recordAckFailure(
|
|
2498
|
+
options,
|
|
2499
|
+
file,
|
|
2500
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
|
|
2501
|
+
);
|
|
2502
|
+
return;
|
|
2503
|
+
}
|
|
2504
|
+
options.ackFailures.delete(file.id);
|
|
2505
|
+
} catch (err) {
|
|
2506
|
+
recordAckFailure(
|
|
2507
|
+
options,
|
|
2508
|
+
file,
|
|
2509
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
|
|
2510
|
+
);
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
function recordAckFailure(options, file, what) {
|
|
2514
|
+
const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
|
|
2515
|
+
options.ackFailures.set(file.id, attempts);
|
|
2516
|
+
options.log({
|
|
2517
|
+
level: "error",
|
|
2518
|
+
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})`
|
|
2519
|
+
});
|
|
2520
|
+
}
|
|
2521
|
+
function describe(err) {
|
|
2522
|
+
return err instanceof Error ? err.message : String(err);
|
|
2523
|
+
}
|
|
2524
|
+
|
|
1906
2525
|
// src/lib/channels/driver.ts
|
|
1907
2526
|
function messageIdOf(m) {
|
|
1908
2527
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -1931,7 +2550,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
1931
2550
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
1932
2551
|
var HEARTBEAT_MS = 6e4;
|
|
1933
2552
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2553
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2554
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
1934
2555
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2556
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
1935
2557
|
var ChannelAuthError = class extends Error {
|
|
1936
2558
|
constructor(message) {
|
|
1937
2559
|
super(message);
|
|
@@ -1954,7 +2576,7 @@ function backoffDelay(attempt, policy) {
|
|
|
1954
2576
|
function isRetryableStatus(status) {
|
|
1955
2577
|
return status === 429 || status >= 500 && status <= 599;
|
|
1956
2578
|
}
|
|
1957
|
-
var ChannelDriver = class {
|
|
2579
|
+
var ChannelDriver = class _ChannelDriver {
|
|
1958
2580
|
agentId;
|
|
1959
2581
|
port;
|
|
1960
2582
|
apiUrl;
|
|
@@ -1968,8 +2590,38 @@ var ChannelDriver = class {
|
|
|
1968
2590
|
pausedMaxWaitMs;
|
|
1969
2591
|
stuckQueuedMs;
|
|
1970
2592
|
now;
|
|
2593
|
+
fileSyncDirectories;
|
|
2594
|
+
homeDir;
|
|
1971
2595
|
/** Cache of conversationId → opencode sessionId. */
|
|
1972
2596
|
sessions = /* @__PURE__ */ new Map();
|
|
2597
|
+
/**
|
|
2598
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2599
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2600
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2601
|
+
* must bind a fresh one.
|
|
2602
|
+
*
|
|
2603
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2604
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2605
|
+
* the same session, and its watcher's routine status writes carry
|
|
2606
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2607
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2608
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2609
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2610
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2611
|
+
* is one we deliberately keep (see `markDone`).
|
|
2612
|
+
*
|
|
2613
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2614
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2615
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2616
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2617
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2618
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2619
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2620
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2621
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2622
|
+
* bounded cost.
|
|
2623
|
+
*/
|
|
2624
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
1973
2625
|
/**
|
|
1974
2626
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
1975
2627
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2079,9 +2731,12 @@ var ChannelDriver = class {
|
|
|
2079
2731
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2080
2732
|
/**
|
|
2081
2733
|
* 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
|
-
*
|
|
2734
|
+
* NON-EMPTY, non-placeholder name is stored (terminal — a real session name
|
|
2735
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
|
|
2736
|
+
* excludes OpenCode's synchronous default title (see
|
|
2737
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
|
|
2738
|
+
* as an empty title so it never latches. A missing entry = not yet resolved OR
|
|
2739
|
+
* resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
|
|
2085
2740
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2086
2741
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2087
2742
|
* no watcher) can resolve the title.
|
|
@@ -2089,6 +2744,24 @@ var ChannelDriver = class {
|
|
|
2089
2744
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2090
2745
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2091
2746
|
draining = false;
|
|
2747
|
+
/**
|
|
2748
|
+
* Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
|
|
2749
|
+
* drain ping don't download, write and ack the same file twice.
|
|
2750
|
+
*/
|
|
2751
|
+
syncingFiles = false;
|
|
2752
|
+
/**
|
|
2753
|
+
* Consecutive failed acks per pending file (#559). Lives on the driver so it
|
|
2754
|
+
* survives across drains — without it, a file whose ack keeps failing is
|
|
2755
|
+
* re-downloaded and re-written every ~2s until the server expires it.
|
|
2756
|
+
*/
|
|
2757
|
+
fileAckFailures = /* @__PURE__ */ new Map();
|
|
2758
|
+
/**
|
|
2759
|
+
* Monotonic count of files this runner has pulled and written (#559). Only
|
|
2760
|
+
* ever increases, so `run.ts` detects work by comparing it against the value
|
|
2761
|
+
* it saw on the previous cycle — including work that landed mid-sleep, the
|
|
2762
|
+
* same trick `lastProxiedActivityAt` uses.
|
|
2763
|
+
*/
|
|
2764
|
+
appliedFileCount = 0;
|
|
2092
2765
|
/**
|
|
2093
2766
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2094
2767
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2119,6 +2792,8 @@ var ChannelDriver = class {
|
|
|
2119
2792
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2120
2793
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2121
2794
|
this.now = config2.now ?? (() => Date.now());
|
|
2795
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
2796
|
+
this.homeDir = config2.homeDir ?? homedir();
|
|
2122
2797
|
}
|
|
2123
2798
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2124
2799
|
get opencodeBase() {
|
|
@@ -2146,6 +2821,47 @@ var ChannelDriver = class {
|
|
|
2146
2821
|
);
|
|
2147
2822
|
return run2;
|
|
2148
2823
|
}
|
|
2824
|
+
/**
|
|
2825
|
+
* Pull-and-apply any files Evident has queued for this runner (#559), riding
|
|
2826
|
+
* the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
|
|
2827
|
+
* and drain ping that call `drainPending()`. There is deliberately no channel,
|
|
2828
|
+
* control frame or poll loop of its own: worst-case latency is one poll tick.
|
|
2829
|
+
*
|
|
2830
|
+
* NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
|
|
2831
|
+
* cost a conversation turn. Failures are logged and either acked as a terminal
|
|
2832
|
+
* outcome or left pending for the next drain (see `runner-file-sync.ts`).
|
|
2833
|
+
*
|
|
2834
|
+
* Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
|
|
2835
|
+
*
|
|
2836
|
+
* @returns the number of files written to disk.
|
|
2837
|
+
*/
|
|
2838
|
+
async syncPendingFiles() {
|
|
2839
|
+
if (this.stopped) return 0;
|
|
2840
|
+
if (this.syncingFiles) return 0;
|
|
2841
|
+
this.syncingFiles = true;
|
|
2842
|
+
try {
|
|
2843
|
+
const applied = await syncPendingRunnerFiles({
|
|
2844
|
+
agentId: this.agentId,
|
|
2845
|
+
apiUrl: this.apiUrl,
|
|
2846
|
+
getAuthHeader: this.getAuthHeader,
|
|
2847
|
+
fetchImpl: this.fetchImpl,
|
|
2848
|
+
allowedDirectories: this.fileSyncDirectories,
|
|
2849
|
+
homeDir: this.homeDir,
|
|
2850
|
+
ackFailures: this.fileAckFailures,
|
|
2851
|
+
log: this.log
|
|
2852
|
+
});
|
|
2853
|
+
this.appliedFileCount += applied;
|
|
2854
|
+
return applied;
|
|
2855
|
+
} catch (err) {
|
|
2856
|
+
this.log({
|
|
2857
|
+
level: "error",
|
|
2858
|
+
message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
|
|
2859
|
+
});
|
|
2860
|
+
return 0;
|
|
2861
|
+
} finally {
|
|
2862
|
+
this.syncingFiles = false;
|
|
2863
|
+
}
|
|
2864
|
+
}
|
|
2149
2865
|
async runDrain() {
|
|
2150
2866
|
let dispatched = 0;
|
|
2151
2867
|
try {
|
|
@@ -2179,6 +2895,28 @@ var ChannelDriver = class {
|
|
|
2179
2895
|
}
|
|
2180
2896
|
return false;
|
|
2181
2897
|
}
|
|
2898
|
+
/**
|
|
2899
|
+
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
2900
|
+
*
|
|
2901
|
+
* Pulling a file is real work that `drainPending()` knows nothing about, so
|
|
2902
|
+
* without this a near-idle runner counts a credential pull as an empty tick
|
|
2903
|
+
* and `--idle-timeout` can `process.exit` mid-pull — leaving a
|
|
2904
|
+
* `.evident-push-*.tmp` behind — or immediately after the write, before the
|
|
2905
|
+
* browser has run the authorize/callback that activates it (the user then sees
|
|
2906
|
+
* `saved_not_activated` for a runner that was fine).
|
|
2907
|
+
*
|
|
2908
|
+
* Two signals because one cannot cover both cases: `inFlight` is the pull
|
|
2909
|
+
* happening RIGHT NOW (it may outlive the tick that started it), and
|
|
2910
|
+
* `appliedFiles` is monotonic so a pull that started AND finished between two
|
|
2911
|
+
* idle checks still shows up as an advance.
|
|
2912
|
+
*
|
|
2913
|
+
* CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
|
|
2914
|
+
* the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
|
|
2915
|
+
* samples afterwards reads `true` every single cycle and can never idle out.
|
|
2916
|
+
*/
|
|
2917
|
+
fileSyncActivity() {
|
|
2918
|
+
return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
|
|
2919
|
+
}
|
|
2182
2920
|
/**
|
|
2183
2921
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2184
2922
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2240,7 +2978,7 @@ var ChannelDriver = class {
|
|
|
2240
2978
|
await this.sleep(step);
|
|
2241
2979
|
}
|
|
2242
2980
|
}
|
|
2243
|
-
while (this.hasInFlightWatchers()) {
|
|
2981
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2244
2982
|
if (this.now() >= deadline) return false;
|
|
2245
2983
|
await this.sleep(step);
|
|
2246
2984
|
}
|
|
@@ -2275,10 +3013,15 @@ var ChannelDriver = class {
|
|
|
2275
3013
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2276
3014
|
*/
|
|
2277
3015
|
async processConversation(conv) {
|
|
2278
|
-
const sessionId = await this.ensureSession(conv);
|
|
3016
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2279
3017
|
const messages = await this.getPendingMessages(conv.id);
|
|
2280
3018
|
let dispatched = 0;
|
|
2281
3019
|
let skippedAlreadyDispatched = 0;
|
|
3020
|
+
if (refusedSessionId && messages.length > 0) {
|
|
3021
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
3022
|
+
superseded_session_id: refusedSessionId
|
|
3023
|
+
});
|
|
3024
|
+
}
|
|
2282
3025
|
for (const message of messages) {
|
|
2283
3026
|
if (this.stopped) break;
|
|
2284
3027
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2305,7 +3048,8 @@ var ChannelDriver = class {
|
|
|
2305
3048
|
} catch (err) {
|
|
2306
3049
|
if (err instanceof ChannelAuthError) throw err;
|
|
2307
3050
|
this.dispatched.delete(message.id);
|
|
2308
|
-
|
|
3051
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
3052
|
+
if (exists === false) {
|
|
2309
3053
|
this.sessions.delete(conv.id);
|
|
2310
3054
|
this.log({
|
|
2311
3055
|
level: "warn",
|
|
@@ -2315,15 +3059,39 @@ var ChannelDriver = class {
|
|
|
2315
3059
|
});
|
|
2316
3060
|
break;
|
|
2317
3061
|
}
|
|
2318
|
-
|
|
3062
|
+
if (exists === null) {
|
|
3063
|
+
this.log({
|
|
3064
|
+
level: "warn",
|
|
3065
|
+
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.`,
|
|
3066
|
+
conversation_id: conv.id,
|
|
3067
|
+
message_id: message.id
|
|
3068
|
+
});
|
|
3069
|
+
break;
|
|
3070
|
+
}
|
|
3071
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3072
|
+
this.sessions.delete(conv.id);
|
|
3073
|
+
this.supersede(conv.id, sessionId);
|
|
3074
|
+
this.log({
|
|
3075
|
+
level: "warn",
|
|
3076
|
+
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.`,
|
|
3077
|
+
conversation_id: conv.id,
|
|
3078
|
+
message_id: message.id
|
|
3079
|
+
});
|
|
3080
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3081
|
+
this.log({
|
|
3082
|
+
level: "warn",
|
|
3083
|
+
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)}`,
|
|
3084
|
+
conversation_id: conv.id,
|
|
3085
|
+
message_id: message.id
|
|
3086
|
+
});
|
|
2319
3087
|
});
|
|
2320
3088
|
this.log({
|
|
2321
3089
|
level: "error",
|
|
2322
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3090
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2323
3091
|
conversation_id: conv.id,
|
|
2324
3092
|
message_id: message.id
|
|
2325
3093
|
});
|
|
2326
|
-
|
|
3094
|
+
break;
|
|
2327
3095
|
}
|
|
2328
3096
|
if (opencodeMessageId === null) {
|
|
2329
3097
|
this.log({
|
|
@@ -2349,8 +3117,42 @@ var ChannelDriver = class {
|
|
|
2349
3117
|
this.ensureWatcherRunning(sessionId);
|
|
2350
3118
|
return dispatched;
|
|
2351
3119
|
}
|
|
3120
|
+
/**
|
|
3121
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
3122
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
3123
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
3124
|
+
*/
|
|
3125
|
+
supersede(conversationId, sessionId) {
|
|
3126
|
+
this.supersededSessions.delete(conversationId);
|
|
3127
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
3128
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
3129
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
3130
|
+
if (oldest === void 0) return;
|
|
3131
|
+
this.supersededSessions.delete(oldest);
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
3135
|
+
isSuperseded(conversationId, sessionId) {
|
|
3136
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
3137
|
+
}
|
|
3138
|
+
/**
|
|
3139
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
3140
|
+
*
|
|
3141
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3142
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3143
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
3144
|
+
*/
|
|
2352
3145
|
async ensureSession(conv) {
|
|
2353
3146
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
3147
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
3148
|
+
this.log({
|
|
3149
|
+
level: "warn",
|
|
3150
|
+
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.`,
|
|
3151
|
+
conversation_id: conv.id
|
|
3152
|
+
});
|
|
3153
|
+
this.sessions.delete(conv.id);
|
|
3154
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
3155
|
+
}
|
|
2354
3156
|
if (bound) {
|
|
2355
3157
|
const exists = await sessionExists(this.port, bound);
|
|
2356
3158
|
if (exists === false) {
|
|
@@ -2360,12 +3162,12 @@ var ChannelDriver = class {
|
|
|
2360
3162
|
conversation_id: conv.id
|
|
2361
3163
|
});
|
|
2362
3164
|
this.sessions.delete(conv.id);
|
|
2363
|
-
return this.createAndBindSession(conv.id);
|
|
3165
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2364
3166
|
}
|
|
2365
3167
|
this.sessions.set(conv.id, bound);
|
|
2366
|
-
return bound;
|
|
3168
|
+
return { sessionId: bound };
|
|
2367
3169
|
}
|
|
2368
|
-
return this.createAndBindSession(conv.id);
|
|
3170
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2369
3171
|
}
|
|
2370
3172
|
/**
|
|
2371
3173
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2445,7 +3247,7 @@ var ChannelDriver = class {
|
|
|
2445
3247
|
}
|
|
2446
3248
|
/**
|
|
2447
3249
|
* Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
|
|
2448
|
-
* (`GET {apiUrl}/
|
|
3250
|
+
* (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
|
|
2449
3251
|
* existing authenticated fetch, and base64-encode into a
|
|
2450
3252
|
* `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
|
|
2451
3253
|
*
|
|
@@ -2453,15 +3255,38 @@ var ChannelDriver = class {
|
|
|
2453
3255
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2454
3256
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2455
3257
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2456
|
-
*
|
|
3258
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
3259
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
3260
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
3261
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
3262
|
+
* logged with context (no silent swallow).
|
|
2457
3263
|
*/
|
|
2458
3264
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2459
3265
|
try {
|
|
2460
3266
|
const res = await this.fetchImpl(
|
|
2461
|
-
`${this.apiUrl}/
|
|
3267
|
+
`${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
|
|
2462
3268
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2463
3269
|
);
|
|
2464
3270
|
if (!res.ok) {
|
|
3271
|
+
let reason;
|
|
3272
|
+
try {
|
|
3273
|
+
const body = await res.json();
|
|
3274
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
3275
|
+
} catch (parseErr) {
|
|
3276
|
+
this.log({
|
|
3277
|
+
level: "debug",
|
|
3278
|
+
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`,
|
|
3279
|
+
message_id: messageId
|
|
3280
|
+
});
|
|
3281
|
+
}
|
|
3282
|
+
if (reason === "needs_reauth") {
|
|
3283
|
+
this.log({
|
|
3284
|
+
level: "error",
|
|
3285
|
+
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)`,
|
|
3286
|
+
message_id: messageId
|
|
3287
|
+
});
|
|
3288
|
+
return { needsReauth: true };
|
|
3289
|
+
}
|
|
2465
3290
|
this.log({
|
|
2466
3291
|
level: "error",
|
|
2467
3292
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2501,6 +3326,9 @@ var ChannelDriver = class {
|
|
|
2501
3326
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2502
3327
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2503
3328
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
3329
|
+
const failedReason = outcomes.some(
|
|
3330
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
3331
|
+
) ? "needs_reauth" : void 0;
|
|
2504
3332
|
this.log({
|
|
2505
3333
|
level: "info",
|
|
2506
3334
|
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 +3338,8 @@ var ChannelDriver = class {
|
|
|
2510
3338
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2511
3339
|
skipped,
|
|
2512
3340
|
failed,
|
|
2513
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3341
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3342
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2514
3343
|
});
|
|
2515
3344
|
}
|
|
2516
3345
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2541,12 +3370,17 @@ var ChannelDriver = class {
|
|
|
2541
3370
|
stuckReported: false,
|
|
2542
3371
|
lastAliveAt: 0,
|
|
2543
3372
|
aliveInFlight: false,
|
|
3373
|
+
titleSynced: false,
|
|
3374
|
+
titleSyncInFlight: false,
|
|
2544
3375
|
awaitingHumanLatched: false,
|
|
2545
3376
|
pausedOnQuestion: false,
|
|
2546
3377
|
pausedOnPermission: false,
|
|
2547
3378
|
pausedClearConfirmed: false,
|
|
2548
3379
|
pausedInFlight: false,
|
|
2549
|
-
deliveryDeadlineAnchored: false
|
|
3380
|
+
deliveryDeadlineAnchored: false,
|
|
3381
|
+
b2PinnedSinceMs: 0,
|
|
3382
|
+
b2LastDescendantCheckMs: 0,
|
|
3383
|
+
b2AbandonedSignalled: false
|
|
2550
3384
|
});
|
|
2551
3385
|
}
|
|
2552
3386
|
/**
|
|
@@ -2614,12 +3448,17 @@ var ChannelDriver = class {
|
|
|
2614
3448
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
2615
3449
|
lastAliveAt: 0,
|
|
2616
3450
|
aliveInFlight: false,
|
|
3451
|
+
titleSynced: false,
|
|
3452
|
+
titleSyncInFlight: false,
|
|
2617
3453
|
awaitingHumanLatched: false,
|
|
2618
3454
|
pausedOnQuestion: false,
|
|
2619
3455
|
pausedOnPermission: false,
|
|
2620
3456
|
pausedClearConfirmed: false,
|
|
2621
3457
|
pausedInFlight: false,
|
|
2622
|
-
deliveryDeadlineAnchored: false
|
|
3458
|
+
deliveryDeadlineAnchored: false,
|
|
3459
|
+
b2PinnedSinceMs: 0,
|
|
3460
|
+
b2LastDescendantCheckMs: 0,
|
|
3461
|
+
b2AbandonedSignalled: false
|
|
2623
3462
|
});
|
|
2624
3463
|
}
|
|
2625
3464
|
/**
|
|
@@ -2781,56 +3620,7 @@ var ChannelDriver = class {
|
|
|
2781
3620
|
}
|
|
2782
3621
|
}
|
|
2783
3622
|
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);
|
|
3623
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
2834
3624
|
return;
|
|
2835
3625
|
}
|
|
2836
3626
|
if (state === "failed") {
|
|
@@ -2843,8 +3633,17 @@ var ChannelDriver = class {
|
|
|
2843
3633
|
conversation_id: conv.id,
|
|
2844
3634
|
message_id: inFlight.evidentMessageId
|
|
2845
3635
|
});
|
|
3636
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3637
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
2846
3638
|
try {
|
|
2847
|
-
await this.markFailed(
|
|
3639
|
+
await this.markFailed(
|
|
3640
|
+
conv.id,
|
|
3641
|
+
inFlight.evidentMessageId,
|
|
3642
|
+
sessionId,
|
|
3643
|
+
error2,
|
|
3644
|
+
usage,
|
|
3645
|
+
failure
|
|
3646
|
+
);
|
|
2848
3647
|
} catch (err) {
|
|
2849
3648
|
if (err instanceof ChannelAuthError) throw err;
|
|
2850
3649
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -2889,6 +3688,44 @@ var ChannelDriver = class {
|
|
|
2889
3688
|
});
|
|
2890
3689
|
}
|
|
2891
3690
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3691
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3692
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3693
|
+
if (!pinnedNow) {
|
|
3694
|
+
if (snapshotReadable) {
|
|
3695
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3696
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3697
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3698
|
+
}
|
|
3699
|
+
} else {
|
|
3700
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3701
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3702
|
+
return;
|
|
3703
|
+
}
|
|
3704
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3705
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3706
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3707
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3708
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3709
|
+
if (isB2AbandonmentConfirmed({
|
|
3710
|
+
pinnedForMs,
|
|
3711
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3712
|
+
descendantOngoing
|
|
3713
|
+
})) {
|
|
3714
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3715
|
+
this.log({
|
|
3716
|
+
level: "warn",
|
|
3717
|
+
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`,
|
|
3718
|
+
conversation_id: conv.id,
|
|
3719
|
+
message_id: id
|
|
3720
|
+
});
|
|
3721
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3722
|
+
watched_for_ms: pinnedForMs
|
|
3723
|
+
});
|
|
3724
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3725
|
+
return;
|
|
3726
|
+
}
|
|
3727
|
+
}
|
|
3728
|
+
}
|
|
2892
3729
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
2893
3730
|
this.log({
|
|
2894
3731
|
level: "warn",
|
|
@@ -2908,6 +3745,18 @@ var ChannelDriver = class {
|
|
|
2908
3745
|
inFlight.aliveInFlight = false;
|
|
2909
3746
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
2910
3747
|
});
|
|
3748
|
+
if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
|
|
3749
|
+
inFlight.titleSyncInFlight = true;
|
|
3750
|
+
void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
|
|
3751
|
+
if (!title) {
|
|
3752
|
+
inFlight.titleSyncInFlight = false;
|
|
3753
|
+
return;
|
|
3754
|
+
}
|
|
3755
|
+
const ok = await this.patchConversationTitle(conv.id, title);
|
|
3756
|
+
inFlight.titleSyncInFlight = false;
|
|
3757
|
+
if (ok) inFlight.titleSynced = true;
|
|
3758
|
+
});
|
|
3759
|
+
}
|
|
2911
3760
|
}
|
|
2912
3761
|
if (awaitingHuman) {
|
|
2913
3762
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -2945,6 +3794,70 @@ var ChannelDriver = class {
|
|
|
2945
3794
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2946
3795
|
}
|
|
2947
3796
|
}
|
|
3797
|
+
/**
|
|
3798
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
3799
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
3800
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
3801
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
3802
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
3803
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
3804
|
+
* and risking the two copies silently drifting apart.
|
|
3805
|
+
*/
|
|
3806
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
3807
|
+
const conv = watcher.conv;
|
|
3808
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
3809
|
+
if (!inFlight.done) {
|
|
3810
|
+
this.log({
|
|
3811
|
+
level: "info",
|
|
3812
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
3813
|
+
conversation_id: conv.id,
|
|
3814
|
+
message_id: inFlight.evidentMessageId
|
|
3815
|
+
});
|
|
3816
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3817
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3818
|
+
try {
|
|
3819
|
+
await this.markDone(
|
|
3820
|
+
conv.id,
|
|
3821
|
+
inFlight.evidentMessageId,
|
|
3822
|
+
sessionId,
|
|
3823
|
+
inFlight.opencodeMessageId,
|
|
3824
|
+
title,
|
|
3825
|
+
usage
|
|
3826
|
+
);
|
|
3827
|
+
} catch (err) {
|
|
3828
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3829
|
+
if (err instanceof ChannelTerminalError) {
|
|
3830
|
+
this.log({
|
|
3831
|
+
level: "warn",
|
|
3832
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
3833
|
+
conversation_id: conv.id,
|
|
3834
|
+
message_id: inFlight.evidentMessageId
|
|
3835
|
+
});
|
|
3836
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3837
|
+
return;
|
|
3838
|
+
}
|
|
3839
|
+
if (this.now() >= inFlight.deadline) {
|
|
3840
|
+
this.log({
|
|
3841
|
+
level: "warn",
|
|
3842
|
+
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)}`,
|
|
3843
|
+
conversation_id: conv.id,
|
|
3844
|
+
message_id: inFlight.evidentMessageId
|
|
3845
|
+
});
|
|
3846
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3847
|
+
return;
|
|
3848
|
+
}
|
|
3849
|
+
this.log({
|
|
3850
|
+
level: "warn",
|
|
3851
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
3852
|
+
conversation_id: conv.id,
|
|
3853
|
+
message_id: inFlight.evidentMessageId
|
|
3854
|
+
});
|
|
3855
|
+
return;
|
|
3856
|
+
}
|
|
3857
|
+
inFlight.done = true;
|
|
3858
|
+
}
|
|
3859
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3860
|
+
}
|
|
2948
3861
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
2949
3862
|
/**
|
|
2950
3863
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3081,7 +3994,8 @@ var ChannelDriver = class {
|
|
|
3081
3994
|
});
|
|
3082
3995
|
try {
|
|
3083
3996
|
const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
|
|
3084
|
-
|
|
3997
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
3998
|
+
await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
|
|
3085
3999
|
} catch (err) {
|
|
3086
4000
|
if (err instanceof ChannelAuthError) throw err;
|
|
3087
4001
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3109,6 +4023,8 @@ var ChannelDriver = class {
|
|
|
3109
4023
|
}
|
|
3110
4024
|
if (state === "failed") {
|
|
3111
4025
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
4026
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
4027
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3112
4028
|
this.log({
|
|
3113
4029
|
level: "error",
|
|
3114
4030
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3116,7 +4032,7 @@ var ChannelDriver = class {
|
|
|
3116
4032
|
message_id: row.id
|
|
3117
4033
|
});
|
|
3118
4034
|
try {
|
|
3119
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2);
|
|
4035
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3120
4036
|
} catch (err) {
|
|
3121
4037
|
if (err instanceof ChannelAuthError) throw err;
|
|
3122
4038
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3522,6 +4438,47 @@ var ChannelDriver = class {
|
|
|
3522
4438
|
}
|
|
3523
4439
|
return false;
|
|
3524
4440
|
}
|
|
4441
|
+
/**
|
|
4442
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4443
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4444
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4445
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4446
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4447
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4448
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4449
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4450
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4451
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4452
|
+
* not ongoing".
|
|
4453
|
+
*
|
|
4454
|
+
* Return contract:
|
|
4455
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4456
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4457
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4458
|
+
* CONFIRMED NOT a descendant of it.
|
|
4459
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4460
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4461
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4462
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4463
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4464
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4465
|
+
* here.
|
|
4466
|
+
*
|
|
4467
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4468
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4469
|
+
* by interaction attribution or the recovery path.
|
|
4470
|
+
*/
|
|
4471
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4472
|
+
let current = sessionId;
|
|
4473
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4474
|
+
if (current === rootSessionId) return true;
|
|
4475
|
+
const parent = await this.resolveSessionParent(current);
|
|
4476
|
+
if (parent === void 0) return null;
|
|
4477
|
+
if (parent === null) return false;
|
|
4478
|
+
current = parent;
|
|
4479
|
+
}
|
|
4480
|
+
return null;
|
|
4481
|
+
}
|
|
3525
4482
|
/**
|
|
3526
4483
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
3527
4484
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -3544,19 +4501,36 @@ var ChannelDriver = class {
|
|
|
3544
4501
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3545
4502
|
return parent;
|
|
3546
4503
|
}
|
|
4504
|
+
/**
|
|
4505
|
+
* OpenCode's synchronous default session title (e.g.
|
|
4506
|
+
* `"New session - 1737800000000"`), assigned immediately when a session is
|
|
4507
|
+
* created — before OpenCode's async LLM-based auto-titling later renames it
|
|
4508
|
+
* mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
|
|
4509
|
+
* timestamp suffix's exact format is deliberately NOT matched, since the prefix
|
|
4510
|
+
* alone is the stable, cheap signal and over-anchoring on the timestamp
|
|
4511
|
+
* representation risks silently breaking if OpenCode ever changes it. Accepted
|
|
4512
|
+
* trade-off: a genuine LLM-assigned title that happens to literally start with
|
|
4513
|
+
* this prefix would also fail to latch (see `resolveSessionTitle`) —
|
|
4514
|
+
* vanishingly unlikely in practice, and deliberately not engineered around.
|
|
4515
|
+
*/
|
|
4516
|
+
static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
|
|
3547
4517
|
/**
|
|
3548
4518
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3549
4519
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3550
4520
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3551
4521
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3552
4522
|
* Best-effort:
|
|
3553
|
-
* - a resolved NON-EMPTY title
|
|
4523
|
+
* - a resolved NON-EMPTY title that does NOT match
|
|
4524
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
|
|
3554
4525
|
* 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
|
-
*
|
|
4526
|
+
* - while the title is still absent, empty, or matches the OpenCode
|
|
4527
|
+
* placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
|
|
4528
|
+
* asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
|
|
4529
|
+
* the cache unresolved and re-fetch on the next need so a later call (e.g. at
|
|
4530
|
+
* `done`) picks up the name assigned in the meantime. Such a call returns
|
|
4531
|
+
* `null` (omit the title on THIS PATCH) without caching. If a session is
|
|
4532
|
+
* never renamed, the title is omitted forever rather than ever persisting
|
|
4533
|
+
* the placeholder as a last resort;
|
|
3560
4534
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3561
4535
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3562
4536
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3569,7 +4543,7 @@ var ChannelDriver = class {
|
|
|
3569
4543
|
if (res.ok) {
|
|
3570
4544
|
const body = await res.json();
|
|
3571
4545
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3572
|
-
if (title.length > 0) {
|
|
4546
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3573
4547
|
this.sessionTitles.set(sessionId, title);
|
|
3574
4548
|
return title;
|
|
3575
4549
|
}
|
|
@@ -3589,6 +4563,54 @@ var ChannelDriver = class {
|
|
|
3589
4563
|
}
|
|
3590
4564
|
return null;
|
|
3591
4565
|
}
|
|
4566
|
+
/**
|
|
4567
|
+
* Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
|
|
4568
|
+
* session title onto the conversation via the PLAIN conversation-update
|
|
4569
|
+
* endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
|
|
4570
|
+
* message-status endpoint `markProcessing`/`markDone` use. Deliberately a
|
|
4571
|
+
* separate, lighter call: it carries no `status`, so it cannot re-trigger the
|
|
4572
|
+
* `processing`/`done` transition side effects (Slack notices, activity-log
|
|
4573
|
+
* rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
|
|
4574
|
+
* ever touches `conversations.title`. That route (`routes/conversations.ts`)
|
|
4575
|
+
* skips a title write matching the stored value, so a redundant call with the
|
|
4576
|
+
* same title is a real no-op — it does not bump `updated_at`, which the
|
|
4577
|
+
* conversation list sorts and paginates on. (Note this is a DIFFERENT guard
|
|
4578
|
+
* from `threads.ts`'s "non-empty AND changed" one, which only covers the
|
|
4579
|
+
* message-status PATCH; the non-empty half is enforced here instead, by
|
|
4580
|
+
* `resolveSessionTitle` never returning an empty/placeholder title.)
|
|
4581
|
+
*
|
|
4582
|
+
* Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
|
|
4583
|
+
* is logged and the title is simply retried on the next heartbeat tick (the
|
|
4584
|
+
* caller only latches `titleSynced` on `true`).
|
|
4585
|
+
*/
|
|
4586
|
+
async patchConversationTitle(conversationId, title) {
|
|
4587
|
+
try {
|
|
4588
|
+
const res = await this.fetchImpl(
|
|
4589
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
|
|
4590
|
+
{
|
|
4591
|
+
method: "PATCH",
|
|
4592
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
4593
|
+
body: JSON.stringify({ title })
|
|
4594
|
+
}
|
|
4595
|
+
);
|
|
4596
|
+
if (!res.ok) {
|
|
4597
|
+
this.log({
|
|
4598
|
+
level: "debug",
|
|
4599
|
+
message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
|
|
4600
|
+
conversation_id: conversationId
|
|
4601
|
+
});
|
|
4602
|
+
return false;
|
|
4603
|
+
}
|
|
4604
|
+
return true;
|
|
4605
|
+
} catch (err) {
|
|
4606
|
+
this.log({
|
|
4607
|
+
level: "debug",
|
|
4608
|
+
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)}`,
|
|
4609
|
+
conversation_id: conversationId
|
|
4610
|
+
});
|
|
4611
|
+
return false;
|
|
4612
|
+
}
|
|
4613
|
+
}
|
|
3592
4614
|
/**
|
|
3593
4615
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
3594
4616
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -3647,6 +4669,84 @@ var ChannelDriver = class {
|
|
|
3647
4669
|
}
|
|
3648
4670
|
return false;
|
|
3649
4671
|
}
|
|
4672
|
+
/**
|
|
4673
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4674
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4675
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4676
|
+
*
|
|
4677
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4678
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4679
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4680
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4681
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4682
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4683
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4684
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4685
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4686
|
+
* executing, between its step's completion and the next generation step"
|
|
4687
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4688
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4689
|
+
* message timestamps at all.
|
|
4690
|
+
*
|
|
4691
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4692
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4693
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4694
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4695
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4696
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4697
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4698
|
+
* delegation — which the root's status is not.
|
|
4699
|
+
*
|
|
4700
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4701
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4702
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4703
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4704
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4705
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4706
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4707
|
+
* instead.
|
|
4708
|
+
*
|
|
4709
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4710
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4711
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4712
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4713
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4714
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4715
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4716
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4717
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4718
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4719
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4720
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4721
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4722
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4723
|
+
* (unlike the recovery cross-check's contract) — see
|
|
4724
|
+
* `isB2AbandonmentConfirmed`.
|
|
4725
|
+
*/
|
|
4726
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
4727
|
+
const sessions = await listSessions(this.port);
|
|
4728
|
+
if (!sessions) {
|
|
4729
|
+
this.log({
|
|
4730
|
+
level: "warn",
|
|
4731
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
4732
|
+
});
|
|
4733
|
+
return null;
|
|
4734
|
+
}
|
|
4735
|
+
let indeterminate = false;
|
|
4736
|
+
for (const candidate of sessions) {
|
|
4737
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
4738
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
4739
|
+
if (membership === null) {
|
|
4740
|
+
indeterminate = true;
|
|
4741
|
+
continue;
|
|
4742
|
+
}
|
|
4743
|
+
if (membership === false) continue;
|
|
4744
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
4745
|
+
if (ongoing === true) return true;
|
|
4746
|
+
if (ongoing === null) indeterminate = true;
|
|
4747
|
+
}
|
|
4748
|
+
return indeterminate ? null : false;
|
|
4749
|
+
}
|
|
3650
4750
|
/**
|
|
3651
4751
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
3652
4752
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -3719,7 +4819,7 @@ var ChannelDriver = class {
|
|
|
3719
4819
|
// Evident API calls (combinedAuth thread routes)
|
|
3720
4820
|
async getPendingConversations() {
|
|
3721
4821
|
const res = await this.fetchImpl(
|
|
3722
|
-
`${this.apiUrl}/
|
|
4822
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
|
|
3723
4823
|
{
|
|
3724
4824
|
headers: { Authorization: this.getAuthHeader() }
|
|
3725
4825
|
}
|
|
@@ -3737,7 +4837,7 @@ var ChannelDriver = class {
|
|
|
3737
4837
|
}
|
|
3738
4838
|
async getPendingMessages(conversationId) {
|
|
3739
4839
|
const res = await this.fetchImpl(
|
|
3740
|
-
`${this.apiUrl}/
|
|
4840
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
|
|
3741
4841
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3742
4842
|
);
|
|
3743
4843
|
this.assertAuth(res, "fetching pending messages");
|
|
@@ -3761,7 +4861,7 @@ var ChannelDriver = class {
|
|
|
3761
4861
|
*/
|
|
3762
4862
|
async getProcessingMessages() {
|
|
3763
4863
|
const res = await this.fetchImpl(
|
|
3764
|
-
`${this.apiUrl}/
|
|
4864
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
|
|
3765
4865
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3766
4866
|
);
|
|
3767
4867
|
this.assertAuth(res, "fetching processing messages");
|
|
@@ -3775,6 +4875,32 @@ var ChannelDriver = class {
|
|
|
3775
4875
|
}
|
|
3776
4876
|
return messages;
|
|
3777
4877
|
}
|
|
4878
|
+
/**
|
|
4879
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
4880
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
4881
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
4882
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
4883
|
+
*
|
|
4884
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
4885
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
4886
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
4887
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
4888
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
4889
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
4890
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
4891
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
4892
|
+
* stick.
|
|
4893
|
+
*/
|
|
4894
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
4895
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
4896
|
+
this.log({
|
|
4897
|
+
level: "debug",
|
|
4898
|
+
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)}`,
|
|
4899
|
+
conversation_id: conversationId,
|
|
4900
|
+
message_id: messageId
|
|
4901
|
+
});
|
|
4902
|
+
return {};
|
|
4903
|
+
}
|
|
3778
4904
|
/**
|
|
3779
4905
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3780
4906
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3798,13 +4924,13 @@ var ChannelDriver = class {
|
|
|
3798
4924
|
*/
|
|
3799
4925
|
async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
3800
4926
|
const res = await this.fetchImpl(
|
|
3801
|
-
`${this.apiUrl}/
|
|
4927
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3802
4928
|
{
|
|
3803
4929
|
method: "PATCH",
|
|
3804
4930
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3805
4931
|
body: JSON.stringify({
|
|
3806
4932
|
status: "processing",
|
|
3807
|
-
|
|
4933
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3808
4934
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3809
4935
|
...title ? { title } : {}
|
|
3810
4936
|
})
|
|
@@ -3845,17 +4971,23 @@ var ChannelDriver = class {
|
|
|
3845
4971
|
* watcher retries next tick within the
|
|
3846
4972
|
* deadline, Finding 4).
|
|
3847
4973
|
*/
|
|
3848
|
-
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
4974
|
+
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
|
|
3849
4975
|
const res = await this.fetchImpl(
|
|
3850
|
-
`${this.apiUrl}/
|
|
4976
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3851
4977
|
{
|
|
3852
4978
|
method: "PATCH",
|
|
3853
4979
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3854
4980
|
body: JSON.stringify({
|
|
3855
4981
|
status: "done",
|
|
4982
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
4983
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
4984
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
4985
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
4986
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3856
4987
|
opencode_session_id: sessionId,
|
|
3857
4988
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3858
|
-
...title ? { title } : {}
|
|
4989
|
+
...title ? { title } : {},
|
|
4990
|
+
...usage ? usage : {}
|
|
3859
4991
|
})
|
|
3860
4992
|
}
|
|
3861
4993
|
);
|
|
@@ -3868,19 +5000,35 @@ var ChannelDriver = class {
|
|
|
3868
5000
|
}
|
|
3869
5001
|
/**
|
|
3870
5002
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3871
|
-
* when provided (issue #182)
|
|
3872
|
-
* `
|
|
3873
|
-
*
|
|
3874
|
-
*
|
|
5003
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
5004
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
5005
|
+
* session untouched (unused today; kept for API symmetry).
|
|
5006
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
5007
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
5008
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
5009
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
5010
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
5011
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
3875
5012
|
*/
|
|
3876
|
-
async markFailed(conversationId, messageId, sessionId, error2) {
|
|
5013
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
3877
5014
|
const body = { status: "failed" };
|
|
3878
|
-
if (sessionId
|
|
5015
|
+
if (sessionId === null) {
|
|
5016
|
+
body.opencode_session_id = null;
|
|
5017
|
+
} else if (sessionId !== void 0) {
|
|
5018
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
5019
|
+
}
|
|
3879
5020
|
if (error2 !== void 0) body.error = error2;
|
|
5021
|
+
if (usage) Object.assign(body, usage);
|
|
5022
|
+
if (failure) {
|
|
5023
|
+
body.failure_kind = failure.kind;
|
|
5024
|
+
body.failure_provider_id = failure.providerId;
|
|
5025
|
+
body.failure_model_id = failure.modelId;
|
|
5026
|
+
body.failure_reason = failure.reason;
|
|
5027
|
+
}
|
|
3880
5028
|
await this.callWithRetry(
|
|
3881
5029
|
"marking message as failed",
|
|
3882
5030
|
() => this.fetchImpl(
|
|
3883
|
-
`${this.apiUrl}/
|
|
5031
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3884
5032
|
{
|
|
3885
5033
|
method: "PATCH",
|
|
3886
5034
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3889,6 +5037,29 @@ var ChannelDriver = class {
|
|
|
3889
5037
|
)
|
|
3890
5038
|
);
|
|
3891
5039
|
}
|
|
5040
|
+
/**
|
|
5041
|
+
* Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
|
|
5042
|
+
*
|
|
5043
|
+
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
5044
|
+
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
5045
|
+
* to the P1-2b zero-provider check — one extra loopback call to
|
|
5046
|
+
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
5047
|
+
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
5048
|
+
* (`null`/indeterminate) leaves the classification `null`, which produces
|
|
5049
|
+
* today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
|
|
5050
|
+
*/
|
|
5051
|
+
async classifyModelAuthFailure(messages, userMessageId) {
|
|
5052
|
+
const classified = messageFailure(messages, userMessageId);
|
|
5053
|
+
if (classified != null) return classified;
|
|
5054
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5055
|
+
const hasProvider = await hasAnyConfiguredProvider(this.port);
|
|
5056
|
+
return applyZeroProviderFallback(
|
|
5057
|
+
classified,
|
|
5058
|
+
hasProvider,
|
|
5059
|
+
reply?.info?.providerID ?? null,
|
|
5060
|
+
reply?.info?.modelID ?? null
|
|
5061
|
+
);
|
|
5062
|
+
}
|
|
3892
5063
|
/**
|
|
3893
5064
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
3894
5065
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -3907,7 +5078,7 @@ var ChannelDriver = class {
|
|
|
3907
5078
|
async postSignal(conversationId, messageId, signal, extra) {
|
|
3908
5079
|
try {
|
|
3909
5080
|
const res = await this.fetchImpl(
|
|
3910
|
-
`${this.apiUrl}/
|
|
5081
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
|
|
3911
5082
|
{
|
|
3912
5083
|
method: "POST",
|
|
3913
5084
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3936,7 +5107,7 @@ var ChannelDriver = class {
|
|
|
3936
5107
|
}
|
|
3937
5108
|
async persistSession(conversationId, sessionId) {
|
|
3938
5109
|
const res = await this.fetchImpl(
|
|
3939
|
-
`${this.apiUrl}/
|
|
5110
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
|
|
3940
5111
|
{
|
|
3941
5112
|
method: "PATCH",
|
|
3942
5113
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3962,7 +5133,7 @@ var ChannelDriver = class {
|
|
|
3962
5133
|
await this.callWithRetry(
|
|
3963
5134
|
"reporting interactive event",
|
|
3964
5135
|
() => this.fetchImpl(
|
|
3965
|
-
`${this.apiUrl}/
|
|
5136
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
|
|
3966
5137
|
{
|
|
3967
5138
|
method: "POST",
|
|
3968
5139
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -4065,7 +5236,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4065
5236
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4066
5237
|
console.log(
|
|
4067
5238
|
chalk5.dim(
|
|
4068
|
-
` ${getCliName()} run --
|
|
5239
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4069
5240
|
)
|
|
4070
5241
|
);
|
|
4071
5242
|
}
|
|
@@ -4195,19 +5366,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4195
5366
|
return { agent_id: data.agent_id };
|
|
4196
5367
|
}
|
|
4197
5368
|
return {
|
|
4198
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5369
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
4199
5370
|
};
|
|
4200
5371
|
} catch (error2) {
|
|
4201
5372
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
4202
5373
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
4203
5374
|
}
|
|
4204
5375
|
}
|
|
5376
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
4205
5377
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4206
5378
|
const apiUrl = getApiUrlConfig();
|
|
4207
5379
|
try {
|
|
4208
|
-
const response = await fetch(`${apiUrl}/
|
|
5380
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4209
5381
|
method: "POST",
|
|
4210
|
-
headers: { Authorization: authHeader }
|
|
5382
|
+
headers: { Authorization: authHeader },
|
|
5383
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
4211
5384
|
});
|
|
4212
5385
|
if (!response.ok) {
|
|
4213
5386
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -4218,13 +5391,41 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4218
5391
|
}
|
|
4219
5392
|
return { ok: true };
|
|
4220
5393
|
} catch (error2) {
|
|
4221
|
-
return { ok: false, error:
|
|
5394
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5395
|
+
}
|
|
5396
|
+
}
|
|
5397
|
+
function describeBestEffortError(error2) {
|
|
5398
|
+
const name = error2?.name;
|
|
5399
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5400
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5401
|
+
}
|
|
5402
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5403
|
+
}
|
|
5404
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5405
|
+
try {
|
|
5406
|
+
const apiUrl = getApiUrlConfig();
|
|
5407
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5408
|
+
method: "POST",
|
|
5409
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5410
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5411
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5412
|
+
});
|
|
5413
|
+
if (!response.ok) {
|
|
5414
|
+
const serverMessage = await readErrorMessage(response);
|
|
5415
|
+
return {
|
|
5416
|
+
ok: false,
|
|
5417
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5418
|
+
};
|
|
5419
|
+
}
|
|
5420
|
+
return { ok: true };
|
|
5421
|
+
} catch (error2) {
|
|
5422
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
4222
5423
|
}
|
|
4223
5424
|
}
|
|
4224
5425
|
async function getAgentInfo(agentId, authHeader) {
|
|
4225
5426
|
const apiUrl = getApiUrlConfig();
|
|
4226
5427
|
try {
|
|
4227
|
-
const response = await fetch(`${apiUrl}/
|
|
5428
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}`, {
|
|
4228
5429
|
headers: { Authorization: authHeader }
|
|
4229
5430
|
});
|
|
4230
5431
|
if (response.status === 401) {
|
|
@@ -4268,6 +5469,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
4268
5469
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
4269
5470
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4270
5471
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5472
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
4271
5473
|
function resolveLogLevel(options) {
|
|
4272
5474
|
const accepted = Object.keys(LOG_LEVELS);
|
|
4273
5475
|
const validate = (value, source) => {
|
|
@@ -4291,6 +5493,34 @@ function resolveLogLevel(options) {
|
|
|
4291
5493
|
}
|
|
4292
5494
|
return "info";
|
|
4293
5495
|
}
|
|
5496
|
+
function resolveFileSyncDirectories(raw, homeDir) {
|
|
5497
|
+
const directories = [];
|
|
5498
|
+
for (const entry of raw ?? []) {
|
|
5499
|
+
const trimmed = entry.trim();
|
|
5500
|
+
if (trimmed === "") {
|
|
5501
|
+
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5502
|
+
}
|
|
5503
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
|
|
5504
|
+
if (!isAbsolute2(expanded)) {
|
|
5505
|
+
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5506
|
+
}
|
|
5507
|
+
const normalized = resolvePath(expanded);
|
|
5508
|
+
if (parse(normalized).root === normalized) {
|
|
5509
|
+
throw new Error(
|
|
5510
|
+
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
5511
|
+
);
|
|
5512
|
+
}
|
|
5513
|
+
if (!directories.includes(normalized)) {
|
|
5514
|
+
directories.push(normalized);
|
|
5515
|
+
}
|
|
5516
|
+
}
|
|
5517
|
+
if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
|
|
5518
|
+
throw new Error(
|
|
5519
|
+
`--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
|
|
5520
|
+
);
|
|
5521
|
+
}
|
|
5522
|
+
return directories;
|
|
5523
|
+
}
|
|
4294
5524
|
function meetsThreshold(state, level) {
|
|
4295
5525
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4296
5526
|
}
|
|
@@ -4412,18 +5642,29 @@ async function handleAuthError(state, error2) {
|
|
|
4412
5642
|
async function driveChannels(state, driver) {
|
|
4413
5643
|
let idlePolls = 0;
|
|
4414
5644
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5645
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4415
5646
|
while (state.running) {
|
|
4416
5647
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4417
5648
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4418
5649
|
if (state.interactive) displayStatus(state);
|
|
4419
5650
|
await state.connection.reconnectPromise;
|
|
4420
5651
|
}
|
|
5652
|
+
const carriedOverFileSync = driver.fileSyncActivity().inFlight;
|
|
5653
|
+
void driver.syncPendingFiles().catch(
|
|
5654
|
+
(error2) => logActivity(state, {
|
|
5655
|
+
type: "error",
|
|
5656
|
+
error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5657
|
+
})
|
|
5658
|
+
);
|
|
4421
5659
|
try {
|
|
4422
5660
|
const processed = await driver.drainPending();
|
|
4423
5661
|
state.messageCount += processed;
|
|
4424
5662
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4425
5663
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4426
|
-
|
|
5664
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5665
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
5666
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
5667
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4427
5668
|
idlePolls = 0;
|
|
4428
5669
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4429
5670
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4452,7 +5693,7 @@ async function driveChannels(state, driver) {
|
|
|
4452
5693
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4453
5694
|
if (state.interactive) displayStatus(state);
|
|
4454
5695
|
}
|
|
4455
|
-
await new Promise((
|
|
5696
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4456
5697
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4457
5698
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4458
5699
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4555,7 +5796,18 @@ async function notifyOffline(state) {
|
|
|
4555
5796
|
if (state.interactive) displayStatus(state);
|
|
4556
5797
|
}
|
|
4557
5798
|
}
|
|
5799
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
5800
|
+
const startedAt = Date.now();
|
|
5801
|
+
try {
|
|
5802
|
+
return await run2();
|
|
5803
|
+
} finally {
|
|
5804
|
+
const elapsedMs = Date.now() - startedAt;
|
|
5805
|
+
durations[name] = elapsedMs;
|
|
5806
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
5807
|
+
}
|
|
5808
|
+
}
|
|
4558
5809
|
async function cleanup(state, opts = {}) {
|
|
5810
|
+
const durations = {};
|
|
4559
5811
|
state.running = false;
|
|
4560
5812
|
for (const timer of state.sessionCleanupTimers) {
|
|
4561
5813
|
clearInterval(timer);
|
|
@@ -4569,7 +5821,13 @@ async function cleanup(state, opts = {}) {
|
|
|
4569
5821
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4570
5822
|
displayStatus(state);
|
|
4571
5823
|
}
|
|
4572
|
-
const
|
|
5824
|
+
const driver = state.channelDriver;
|
|
5825
|
+
const settled = await timeShutdownPhase(
|
|
5826
|
+
state,
|
|
5827
|
+
durations,
|
|
5828
|
+
"drain",
|
|
5829
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
5830
|
+
);
|
|
4573
5831
|
if (!settled) {
|
|
4574
5832
|
logActivity(state, {
|
|
4575
5833
|
type: "info",
|
|
@@ -4578,13 +5836,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4578
5836
|
if (state.interactive) displayStatus(state);
|
|
4579
5837
|
}
|
|
4580
5838
|
}
|
|
4581
|
-
await notifyOffline(state);
|
|
5839
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
4582
5840
|
if (state.connection) {
|
|
4583
|
-
state.connection
|
|
5841
|
+
const connection = state.connection;
|
|
5842
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
4584
5843
|
state.connection = null;
|
|
4585
5844
|
}
|
|
4586
5845
|
if (state.opencodeProcess) {
|
|
4587
|
-
|
|
5846
|
+
const opencodeProcess = state.opencodeProcess;
|
|
5847
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
4588
5848
|
if (state.interactive) {
|
|
4589
5849
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
4590
5850
|
displayStatus(state);
|
|
@@ -4593,12 +5853,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4593
5853
|
}
|
|
4594
5854
|
state.opencodeProcess = null;
|
|
4595
5855
|
}
|
|
5856
|
+
return durations;
|
|
4596
5857
|
}
|
|
4597
5858
|
async function run(options) {
|
|
4598
5859
|
const interactive = isInteractive(options.json);
|
|
4599
5860
|
let logLevel;
|
|
5861
|
+
let fileSyncDirectories;
|
|
4600
5862
|
try {
|
|
4601
5863
|
logLevel = resolveLogLevel(options);
|
|
5864
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
|
|
4602
5865
|
} catch (error2) {
|
|
4603
5866
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4604
5867
|
if (options.json) {
|
|
@@ -4611,7 +5874,7 @@ async function run(options) {
|
|
|
4611
5874
|
return;
|
|
4612
5875
|
}
|
|
4613
5876
|
const state = {
|
|
4614
|
-
agentId: options.agent || "",
|
|
5877
|
+
agentId: options.runner || options.agent || "",
|
|
4615
5878
|
agentName: null,
|
|
4616
5879
|
port: options.port ?? 4096,
|
|
4617
5880
|
conversationFilter: options.conversation ?? null,
|
|
@@ -4633,6 +5896,24 @@ async function run(options) {
|
|
|
4633
5896
|
sessionCleanupTimers: [],
|
|
4634
5897
|
authHeader: ""
|
|
4635
5898
|
};
|
|
5899
|
+
if (fileSyncDirectories.length > 0) {
|
|
5900
|
+
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5901
|
+
} else {
|
|
5902
|
+
log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
|
|
5903
|
+
}
|
|
5904
|
+
if (!options.runner && options.agent) {
|
|
5905
|
+
telemetry.info(
|
|
5906
|
+
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
5907
|
+
"Deprecated --agent flag used instead of --runner",
|
|
5908
|
+
{ command: "run" },
|
|
5909
|
+
state.agentId
|
|
5910
|
+
);
|
|
5911
|
+
const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
|
|
5912
|
+
log2(state, agentFlagNotice, "warn");
|
|
5913
|
+
if (state.interactive && !state.json) {
|
|
5914
|
+
logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
|
|
5915
|
+
}
|
|
5916
|
+
}
|
|
4636
5917
|
if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
|
|
4637
5918
|
log2(
|
|
4638
5919
|
state,
|
|
@@ -4643,14 +5924,38 @@ async function run(options) {
|
|
|
4643
5924
|
const handleSignal = async () => {
|
|
4644
5925
|
if (state.shuttingDown) return;
|
|
4645
5926
|
state.shuttingDown = true;
|
|
5927
|
+
const shutdownStartedAt = Date.now();
|
|
4646
5928
|
if (state.interactive) {
|
|
4647
5929
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
4648
5930
|
displayStatus(state);
|
|
4649
5931
|
} else {
|
|
4650
5932
|
log2(state, "Shutting down...");
|
|
4651
5933
|
}
|
|
4652
|
-
await cleanup(state, { graceful: true });
|
|
4653
|
-
|
|
5934
|
+
const durations = await cleanup(state, { graceful: true });
|
|
5935
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
5936
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
5937
|
+
let timer;
|
|
5938
|
+
const flushed = shutdownTelemetry().then(
|
|
5939
|
+
() => true,
|
|
5940
|
+
(error2) => {
|
|
5941
|
+
log2(
|
|
5942
|
+
state,
|
|
5943
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
5944
|
+
"warn"
|
|
5945
|
+
);
|
|
5946
|
+
return true;
|
|
5947
|
+
}
|
|
5948
|
+
);
|
|
5949
|
+
const timedOut = new Promise((resolve3) => {
|
|
5950
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
5951
|
+
});
|
|
5952
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
5953
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
5954
|
+
}
|
|
5955
|
+
clearTimeout(timer);
|
|
5956
|
+
});
|
|
5957
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
5958
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
4654
5959
|
process.exit(0);
|
|
4655
5960
|
};
|
|
4656
5961
|
process.on("SIGINT", handleSignal);
|
|
@@ -4661,7 +5966,9 @@ async function run(options) {
|
|
|
4661
5966
|
if (!interactive) {
|
|
4662
5967
|
printError("Authentication required");
|
|
4663
5968
|
blank();
|
|
4664
|
-
console.log(
|
|
5969
|
+
console.log(
|
|
5970
|
+
chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
|
|
5971
|
+
);
|
|
4665
5972
|
console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
|
|
4666
5973
|
blank();
|
|
4667
5974
|
process.exit(1);
|
|
@@ -4675,6 +5982,25 @@ async function run(options) {
|
|
|
4675
5982
|
);
|
|
4676
5983
|
}
|
|
4677
5984
|
state.authHeader = getAuthHeader(credentials2);
|
|
5985
|
+
if (credentials2.notice) {
|
|
5986
|
+
log2(state, credentials2.notice, "warn");
|
|
5987
|
+
if (state.interactive && !state.json) {
|
|
5988
|
+
logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
|
|
5989
|
+
}
|
|
5990
|
+
}
|
|
5991
|
+
if (credentials2.keySource === "agent_key") {
|
|
5992
|
+
telemetry.info(
|
|
5993
|
+
EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
|
|
5994
|
+
"Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
|
|
5995
|
+
{ command: "run" },
|
|
5996
|
+
state.agentId
|
|
5997
|
+
);
|
|
5998
|
+
const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
|
|
5999
|
+
log2(state, agentKeyNotice, "warn");
|
|
6000
|
+
if (state.interactive && !state.json) {
|
|
6001
|
+
logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
|
|
6002
|
+
}
|
|
6003
|
+
}
|
|
4678
6004
|
if (!state.agentId) {
|
|
4679
6005
|
if (credentials2.authType === "agent_key") {
|
|
4680
6006
|
const resolved = await resolveAgentIdFromKey(state.authHeader);
|
|
@@ -4692,9 +6018,15 @@ async function run(options) {
|
|
|
4692
6018
|
process.exit(1);
|
|
4693
6019
|
}
|
|
4694
6020
|
} else {
|
|
4695
|
-
printError(
|
|
6021
|
+
printError(
|
|
6022
|
+
"--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
|
|
6023
|
+
);
|
|
4696
6024
|
blank();
|
|
4697
|
-
console.log(
|
|
6025
|
+
console.log(
|
|
6026
|
+
chalk6.dim(
|
|
6027
|
+
"Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
|
|
6028
|
+
)
|
|
6029
|
+
);
|
|
4698
6030
|
blank();
|
|
4699
6031
|
process.exit(1);
|
|
4700
6032
|
}
|
|
@@ -4737,6 +6069,21 @@ async function run(options) {
|
|
|
4737
6069
|
}
|
|
4738
6070
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
4739
6071
|
state.agentName = validation.agent.name;
|
|
6072
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
6073
|
+
if (microvmId) {
|
|
6074
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
6075
|
+
if (reported.ok) {
|
|
6076
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
6077
|
+
} else {
|
|
6078
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
6079
|
+
log2(state, message, "warn");
|
|
6080
|
+
if (state.interactive && !state.json) {
|
|
6081
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6082
|
+
}
|
|
6083
|
+
}
|
|
6084
|
+
} else {
|
|
6085
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6086
|
+
}
|
|
4740
6087
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
4741
6088
|
try {
|
|
4742
6089
|
const oc = await ensureOpenCodeRunning({
|
|
@@ -4758,6 +6105,21 @@ async function run(options) {
|
|
|
4758
6105
|
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
4759
6106
|
}
|
|
4760
6107
|
}
|
|
6108
|
+
const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
|
|
6109
|
+
if (noProviderWarning) {
|
|
6110
|
+
log2(state, noProviderWarning, "warn");
|
|
6111
|
+
if (state.interactive && !state.json) {
|
|
6112
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6113
|
+
blank();
|
|
6114
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6115
|
+
console.log(
|
|
6116
|
+
chalk6.dim(
|
|
6117
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6118
|
+
)
|
|
6119
|
+
);
|
|
6120
|
+
blank();
|
|
6121
|
+
}
|
|
6122
|
+
}
|
|
4761
6123
|
} catch (error2) {
|
|
4762
6124
|
ocSpinner?.fail(error2.message);
|
|
4763
6125
|
throw error2;
|
|
@@ -4770,6 +6132,10 @@ async function run(options) {
|
|
|
4770
6132
|
getAuthHeader: () => state.authHeader,
|
|
4771
6133
|
conversationFilter: state.conversationFilter,
|
|
4772
6134
|
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
6135
|
+
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
6136
|
+
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
6137
|
+
fileSyncDirectories,
|
|
6138
|
+
homeDir: homedir2(),
|
|
4773
6139
|
log: (entry) => (
|
|
4774
6140
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4775
6141
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4796,6 +6162,18 @@ async function run(options) {
|
|
|
4796
6162
|
type: "info",
|
|
4797
6163
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
4798
6164
|
});
|
|
6165
|
+
if (options.tunnelReadyFile) {
|
|
6166
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6167
|
+
if (marker.ok) {
|
|
6168
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6169
|
+
} else {
|
|
6170
|
+
log2(
|
|
6171
|
+
state,
|
|
6172
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6173
|
+
"error"
|
|
6174
|
+
);
|
|
6175
|
+
}
|
|
6176
|
+
}
|
|
4799
6177
|
emitAgentConnected(state.agentId, {
|
|
4800
6178
|
port: state.port,
|
|
4801
6179
|
cli_version: getCliVersion(),
|
|
@@ -4851,6 +6229,12 @@ async function run(options) {
|
|
|
4851
6229
|
onDrainPing: () => {
|
|
4852
6230
|
if (!state.running) return;
|
|
4853
6231
|
logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
|
|
6232
|
+
void channelDriver.syncPendingFiles().catch(
|
|
6233
|
+
(error2) => logActivity(state, {
|
|
6234
|
+
type: "error",
|
|
6235
|
+
error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
6236
|
+
})
|
|
6237
|
+
);
|
|
4854
6238
|
channelDriver.drainPending().then((processed) => {
|
|
4855
6239
|
if (processed > 0) {
|
|
4856
6240
|
state.messageCount += processed;
|
|
@@ -4909,7 +6293,7 @@ async function run(options) {
|
|
|
4909
6293
|
}
|
|
4910
6294
|
telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
|
|
4911
6295
|
command: "run",
|
|
4912
|
-
agentId: options.agent
|
|
6296
|
+
agentId: options.runner || options.agent
|
|
4913
6297
|
});
|
|
4914
6298
|
await shutdownTelemetry();
|
|
4915
6299
|
process.exit(1);
|
|
@@ -4934,7 +6318,10 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
4934
6318
|
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
6319
|
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
6320
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
4937
|
-
program.command("run").description("Connect to Evident and process messages").option("
|
|
6321
|
+
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(
|
|
6322
|
+
"-a, --agent [id]",
|
|
6323
|
+
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
6324
|
+
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
4938
6325
|
"--log-level <level>",
|
|
4939
6326
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
4940
6327
|
).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 +6333,19 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4946
6333
|
).option(
|
|
4947
6334
|
"--session-cleanup-interval <duration>",
|
|
4948
6335
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6336
|
+
).option(
|
|
6337
|
+
"--enable-file-sync-to <dir>",
|
|
6338
|
+
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
6339
|
+
(value, previous) => previous.concat([value]),
|
|
6340
|
+
[]
|
|
6341
|
+
).option(
|
|
6342
|
+
"--tunnel-ready-file <path>",
|
|
6343
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
4949
6344
|
).action(
|
|
4950
6345
|
(options) => {
|
|
4951
6346
|
run({
|
|
4952
6347
|
agent: options.agent,
|
|
6348
|
+
runner: options.runner,
|
|
4953
6349
|
port: parseInt(options.port, 10),
|
|
4954
6350
|
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
4955
6351
|
// resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
|
|
@@ -4961,7 +6357,11 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4961
6357
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
4962
6358
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
4963
6359
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
4964
|
-
sessionCleanupInterval: options.sessionCleanupInterval
|
|
6360
|
+
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6361
|
+
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6362
|
+
// resolveFileSyncDirectories.
|
|
6363
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6364
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
4965
6365
|
});
|
|
4966
6366
|
}
|
|
4967
6367
|
);
|