@evident-ai/cli 3.1.1-dev.51bb5fa → 3.1.1-dev.561700
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -11
- package/dist/index.js +1349 -115
- 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] || "";
|
|
@@ -236,16 +267,28 @@ async function getToken() {
|
|
|
236
267
|
}
|
|
237
268
|
return null;
|
|
238
269
|
}
|
|
270
|
+
function toError(err) {
|
|
271
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
272
|
+
}
|
|
239
273
|
async function deleteToken(options = {}) {
|
|
240
274
|
const keytar = await getKeytar();
|
|
275
|
+
const failures = [];
|
|
241
276
|
if (keytar) {
|
|
242
277
|
if (options.all) {
|
|
243
|
-
|
|
278
|
+
let accounts = [];
|
|
279
|
+
try {
|
|
280
|
+
accounts = await keytar.findCredentials(SERVICE_NAME);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
failures.push({ type: "enumerate", error: toError(err) });
|
|
283
|
+
}
|
|
244
284
|
await Promise.all(
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
285
|
+
accounts.map(async (entry) => {
|
|
286
|
+
try {
|
|
287
|
+
await keytar.deletePassword(SERVICE_NAME, entry.account);
|
|
288
|
+
} catch (err) {
|
|
289
|
+
failures.push({ type: "delete", account: entry.account, error: toError(err) });
|
|
290
|
+
}
|
|
291
|
+
})
|
|
249
292
|
);
|
|
250
293
|
} else {
|
|
251
294
|
await keytar.deletePassword(SERVICE_NAME, keychainAccount());
|
|
@@ -256,6 +299,7 @@ async function deleteToken(options = {}) {
|
|
|
256
299
|
} else {
|
|
257
300
|
clearCredentials();
|
|
258
301
|
}
|
|
302
|
+
return { failures };
|
|
259
303
|
}
|
|
260
304
|
|
|
261
305
|
// src/utils/ui.ts
|
|
@@ -285,14 +329,14 @@ function blank() {
|
|
|
285
329
|
console.log();
|
|
286
330
|
}
|
|
287
331
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
288
|
-
return new Promise((
|
|
332
|
+
return new Promise((resolve3) => {
|
|
289
333
|
process.stdout.write(chalk.dim(prompt));
|
|
290
334
|
const handler = () => {
|
|
291
335
|
process.stdin.removeListener("data", handler);
|
|
292
336
|
process.stdin.setRawMode?.(false);
|
|
293
337
|
process.stdin.pause();
|
|
294
338
|
console.log();
|
|
295
|
-
|
|
339
|
+
resolve3();
|
|
296
340
|
};
|
|
297
341
|
if (process.stdin.isTTY) {
|
|
298
342
|
process.stdin.setRawMode?.(true);
|
|
@@ -302,7 +346,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
302
346
|
});
|
|
303
347
|
}
|
|
304
348
|
function sleep(ms) {
|
|
305
|
-
return new Promise((
|
|
349
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
306
350
|
}
|
|
307
351
|
|
|
308
352
|
// src/commands/login.ts
|
|
@@ -373,22 +417,23 @@ async function deviceFlowLogin(options) {
|
|
|
373
417
|
}
|
|
374
418
|
async function tokenLogin() {
|
|
375
419
|
console.log("Token login mode.");
|
|
376
|
-
console.log("
|
|
420
|
+
console.log("Run `evident login` on a machine with a browser to get a token.");
|
|
421
|
+
console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
|
|
377
422
|
blank();
|
|
378
423
|
process.stdout.write("Paste token: ");
|
|
379
|
-
const token = await new Promise((
|
|
424
|
+
const token = await new Promise((resolve3) => {
|
|
380
425
|
let data = "";
|
|
381
426
|
process.stdin.setEncoding("utf8");
|
|
382
427
|
process.stdin.on("data", (chunk) => {
|
|
383
428
|
data += chunk;
|
|
384
429
|
});
|
|
385
430
|
process.stdin.on("end", () => {
|
|
386
|
-
|
|
431
|
+
resolve3(data.trim());
|
|
387
432
|
});
|
|
388
433
|
if (process.stdin.isTTY) {
|
|
389
434
|
process.stdin.once("data", (chunk) => {
|
|
390
435
|
process.stdin.pause();
|
|
391
|
-
|
|
436
|
+
resolve3(chunk.toString().trim());
|
|
392
437
|
});
|
|
393
438
|
process.stdin.resume();
|
|
394
439
|
}
|
|
@@ -423,9 +468,22 @@ async function login(options) {
|
|
|
423
468
|
}
|
|
424
469
|
|
|
425
470
|
// src/commands/logout.ts
|
|
471
|
+
function describeFailure(failure) {
|
|
472
|
+
if (failure.type === "enumerate") {
|
|
473
|
+
return `could not list stored keychain entries (${failure.error.message})`;
|
|
474
|
+
}
|
|
475
|
+
return `${failure.account} (${failure.error.message})`;
|
|
476
|
+
}
|
|
426
477
|
async function logout(options = {}) {
|
|
427
478
|
if (options.all) {
|
|
428
|
-
await deleteToken({ all: true });
|
|
479
|
+
const result = await deleteToken({ all: true });
|
|
480
|
+
if (result.failures.length > 0) {
|
|
481
|
+
printError(
|
|
482
|
+
`Failed to fully clear your keychain: ${result.failures.map(describeFailure).join("; ")}. Your local credentials file was cleared, but stale keychain entries may remain \u2014 run \`evident logout --all\` again, or remove them manually from your OS keychain / credential manager.`
|
|
483
|
+
);
|
|
484
|
+
process.exitCode = 1;
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
429
487
|
printSuccess("Logged out of all endpoints.");
|
|
430
488
|
return;
|
|
431
489
|
}
|
|
@@ -467,9 +525,9 @@ async function whoami() {
|
|
|
467
525
|
}
|
|
468
526
|
|
|
469
527
|
// src/commands/run.ts
|
|
528
|
+
import { homedir as homedir2 } from "os";
|
|
529
|
+
import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
|
|
470
530
|
import chalk6 from "chalk";
|
|
471
|
-
import ora3 from "ora";
|
|
472
|
-
import { select as select3 } from "@inquirer/prompts";
|
|
473
531
|
|
|
474
532
|
// ../../packages/types/src/telemetry/index.ts
|
|
475
533
|
var TelemetryEventTypes = {
|
|
@@ -485,6 +543,10 @@ var TelemetryEventTypes = {
|
|
|
485
543
|
var MAX_FRAME_BYTES = 256 * 1024;
|
|
486
544
|
var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
|
|
487
545
|
|
|
546
|
+
// ../../packages/types/src/runner-files.ts
|
|
547
|
+
var MAX_FILE_PUSH_BYTES = 64 * 1024;
|
|
548
|
+
var MAX_FILE_SYNC_DIRECTORIES = 16;
|
|
549
|
+
|
|
488
550
|
// ../../packages/types/src/logging/index.ts
|
|
489
551
|
var CORRELATION_ID_HEADER = "x-evident-correlation-id";
|
|
490
552
|
function log(level, event, fields) {
|
|
@@ -499,6 +561,12 @@ function log(level, event, fields) {
|
|
|
499
561
|
);
|
|
500
562
|
}
|
|
501
563
|
}
|
|
564
|
+
function errorFields(err) {
|
|
565
|
+
if (err instanceof Error) {
|
|
566
|
+
return { error: err.message, error_name: err.name };
|
|
567
|
+
}
|
|
568
|
+
return { error: String(err) };
|
|
569
|
+
}
|
|
502
570
|
function stripQuery(url) {
|
|
503
571
|
try {
|
|
504
572
|
return new URL(url).pathname;
|
|
@@ -508,6 +576,10 @@ function stripQuery(url) {
|
|
|
508
576
|
}
|
|
509
577
|
}
|
|
510
578
|
|
|
579
|
+
// src/commands/run.ts
|
|
580
|
+
import ora3 from "ora";
|
|
581
|
+
import { select as select3 } from "@inquirer/prompts";
|
|
582
|
+
|
|
511
583
|
// src/lib/telemetry.ts
|
|
512
584
|
var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
513
585
|
function getCliVersion() {
|
|
@@ -719,7 +791,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
719
791
|
if (health.healthy) {
|
|
720
792
|
return health;
|
|
721
793
|
}
|
|
722
|
-
await new Promise((
|
|
794
|
+
await new Promise((resolve3) => setTimeout(resolve3, 1e3));
|
|
723
795
|
}
|
|
724
796
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
725
797
|
}
|
|
@@ -1267,6 +1339,16 @@ async function buildFileParts(attachments, capable) {
|
|
|
1267
1339
|
);
|
|
1268
1340
|
dataUrl = null;
|
|
1269
1341
|
}
|
|
1342
|
+
if (dataUrl !== null && typeof dataUrl === "object") {
|
|
1343
|
+
outcomes.push({
|
|
1344
|
+
index: a.index,
|
|
1345
|
+
mime: a.mime,
|
|
1346
|
+
filename: a.filename,
|
|
1347
|
+
status: "failed",
|
|
1348
|
+
reason: "needs_reauth"
|
|
1349
|
+
});
|
|
1350
|
+
continue;
|
|
1351
|
+
}
|
|
1270
1352
|
if (dataUrl == null) {
|
|
1271
1353
|
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1272
1354
|
continue;
|
|
@@ -1348,7 +1430,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
1348
1430
|
}
|
|
1349
1431
|
}
|
|
1350
1432
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
1351
|
-
await new Promise((
|
|
1433
|
+
await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
|
|
1352
1434
|
}
|
|
1353
1435
|
}
|
|
1354
1436
|
return null;
|
|
@@ -1476,6 +1558,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1476
1558
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1477
1559
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1478
1560
|
}
|
|
1561
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1562
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1563
|
+
}
|
|
1479
1564
|
function messageError(messages, userMessageId) {
|
|
1480
1565
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1481
1566
|
const error2 = errorOf(reply);
|
|
@@ -1489,6 +1574,42 @@ function messageError(messages, userMessageId) {
|
|
|
1489
1574
|
}
|
|
1490
1575
|
return "The agent run failed.";
|
|
1491
1576
|
}
|
|
1577
|
+
function messageFailure(messages, userMessageId) {
|
|
1578
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1579
|
+
const error2 = errorOf(reply);
|
|
1580
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
1581
|
+
const e = error2;
|
|
1582
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
1583
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
1584
|
+
if (e.name === "ProviderAuthError") {
|
|
1585
|
+
const data = e.data;
|
|
1586
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
1587
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
1588
|
+
}
|
|
1589
|
+
if (e.name === "APIError") {
|
|
1590
|
+
const data = e.data;
|
|
1591
|
+
const statusCode = data?.statusCode;
|
|
1592
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
1593
|
+
return {
|
|
1594
|
+
kind: "model_auth",
|
|
1595
|
+
providerId: replyProviderId,
|
|
1596
|
+
modelId: replyModelId,
|
|
1597
|
+
reason: "rejected"
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
return null;
|
|
1602
|
+
}
|
|
1603
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
1604
|
+
if (classified != null) return classified;
|
|
1605
|
+
if (hasConfiguredProvider !== false) return null;
|
|
1606
|
+
return {
|
|
1607
|
+
kind: "model_auth",
|
|
1608
|
+
providerId: replyProviderId,
|
|
1609
|
+
modelId: replyModelId,
|
|
1610
|
+
reason: "missing"
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1492
1613
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1493
1614
|
if (!messages || messages.length === 0) return false;
|
|
1494
1615
|
return messages.some(
|
|
@@ -1684,10 +1805,11 @@ var StreamForwarder = class {
|
|
|
1684
1805
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1685
1806
|
*/
|
|
1686
1807
|
abortAll() {
|
|
1687
|
-
for (const stream of this.inflight.
|
|
1808
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1688
1809
|
try {
|
|
1689
1810
|
stream.abort();
|
|
1690
|
-
} catch {
|
|
1811
|
+
} catch (err) {
|
|
1812
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1691
1813
|
}
|
|
1692
1814
|
}
|
|
1693
1815
|
this.inflight.clear();
|
|
@@ -1721,12 +1843,12 @@ var StreamForwarder = class {
|
|
|
1721
1843
|
let endBody;
|
|
1722
1844
|
if (has_body) {
|
|
1723
1845
|
const chunks = [];
|
|
1724
|
-
bodyPromise = new Promise((
|
|
1846
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1725
1847
|
pushBody = (buf) => {
|
|
1726
1848
|
chunks.push(buf);
|
|
1727
1849
|
};
|
|
1728
1850
|
endBody = () => {
|
|
1729
|
-
|
|
1851
|
+
resolve3(Buffer.concat(chunks));
|
|
1730
1852
|
};
|
|
1731
1853
|
});
|
|
1732
1854
|
}
|
|
@@ -1843,7 +1965,7 @@ function connectTunnel(options) {
|
|
|
1843
1965
|
} = options;
|
|
1844
1966
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1845
1967
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1846
|
-
return new Promise((
|
|
1968
|
+
return new Promise((resolve3, reject) => {
|
|
1847
1969
|
const ws = new WebSocket2(url, {
|
|
1848
1970
|
headers: {
|
|
1849
1971
|
Authorization: authHeader
|
|
@@ -1898,7 +2020,7 @@ function connectTunnel(options) {
|
|
|
1898
2020
|
clearTimeout(connectionTimeout);
|
|
1899
2021
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1900
2022
|
onConnected?.(connectedAgentId);
|
|
1901
|
-
|
|
2023
|
+
resolve3({
|
|
1902
2024
|
ws,
|
|
1903
2025
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1904
2026
|
});
|
|
@@ -1960,7 +2082,11 @@ var RunnerConnection = class {
|
|
|
1960
2082
|
if (this.connection) {
|
|
1961
2083
|
try {
|
|
1962
2084
|
this.connection.close();
|
|
1963
|
-
} catch {
|
|
2085
|
+
} catch (err) {
|
|
2086
|
+
log("error", "runner_connection_close_failed", {
|
|
2087
|
+
agent_id: this.resolvedAgentId,
|
|
2088
|
+
...errorFields(err)
|
|
2089
|
+
});
|
|
1964
2090
|
}
|
|
1965
2091
|
this.connection = null;
|
|
1966
2092
|
}
|
|
@@ -2012,6 +2138,416 @@ var RunnerConnection = class {
|
|
|
2012
2138
|
}
|
|
2013
2139
|
};
|
|
2014
2140
|
|
|
2141
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2142
|
+
import { writeFileSync } from "fs";
|
|
2143
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2144
|
+
try {
|
|
2145
|
+
writeFileSync(path, `${agentId}
|
|
2146
|
+
`);
|
|
2147
|
+
return { ok: true };
|
|
2148
|
+
} catch (error2) {
|
|
2149
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
// src/lib/channels/driver.ts
|
|
2154
|
+
import { homedir } from "os";
|
|
2155
|
+
|
|
2156
|
+
// src/lib/file-push.ts
|
|
2157
|
+
import { randomUUID } from "crypto";
|
|
2158
|
+
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2159
|
+
import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
|
|
2160
|
+
var FILE_MODE = 384;
|
|
2161
|
+
var DIRECTORY_MODE = 448;
|
|
2162
|
+
async function writePushedFile(request) {
|
|
2163
|
+
const { requestedPath, content, allowedDirectories, homeDir } = request;
|
|
2164
|
+
const bytes = content.byteLength;
|
|
2165
|
+
if (allowedDirectories.length === 0) {
|
|
2166
|
+
return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
2167
|
+
path: requestedPath,
|
|
2168
|
+
bytes
|
|
2169
|
+
});
|
|
2170
|
+
}
|
|
2171
|
+
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
2172
|
+
return refuse(
|
|
2173
|
+
"file_too_large",
|
|
2174
|
+
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
2175
|
+
{
|
|
2176
|
+
path: requestedPath,
|
|
2177
|
+
bytes
|
|
2178
|
+
}
|
|
2179
|
+
);
|
|
2180
|
+
}
|
|
2181
|
+
const candidate = expandAndValidate(requestedPath, homeDir);
|
|
2182
|
+
if (candidate === null) {
|
|
2183
|
+
return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
2184
|
+
path: requestedPath,
|
|
2185
|
+
bytes
|
|
2186
|
+
});
|
|
2187
|
+
}
|
|
2188
|
+
try {
|
|
2189
|
+
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2190
|
+
dirname2(candidate)
|
|
2191
|
+
);
|
|
2192
|
+
const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
|
|
2193
|
+
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2194
|
+
if (allowedDirectory === null) {
|
|
2195
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2196
|
+
path: realTarget,
|
|
2197
|
+
bytes
|
|
2198
|
+
});
|
|
2199
|
+
}
|
|
2200
|
+
if (missingSegments.length > 0) {
|
|
2201
|
+
await createMissingDirectories(existingAncestor, missingSegments);
|
|
2202
|
+
const realParent = await realpath(dirname2(realTarget));
|
|
2203
|
+
if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
2204
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2205
|
+
path: realTarget,
|
|
2206
|
+
bytes,
|
|
2207
|
+
reason: "parent_changed_after_create"
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
await writeAtomically(realTarget, content);
|
|
2212
|
+
log("info", "file_push_written", { path: realTarget, bytes });
|
|
2213
|
+
return { ok: true, path: realTarget };
|
|
2214
|
+
} catch (err) {
|
|
2215
|
+
const errno = err.code ?? "UNKNOWN";
|
|
2216
|
+
return refuse("write_failed", `The runner could not write the file (${errno}).`, {
|
|
2217
|
+
path: candidate,
|
|
2218
|
+
bytes,
|
|
2219
|
+
errno,
|
|
2220
|
+
...errorFields(err)
|
|
2221
|
+
});
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
function expandAndValidate(requestedPath, homeDir) {
|
|
2225
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2226
|
+
return null;
|
|
2227
|
+
}
|
|
2228
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2229
|
+
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2230
|
+
return null;
|
|
2231
|
+
}
|
|
2232
|
+
if (!isAbsolute(expanded)) {
|
|
2233
|
+
return null;
|
|
2234
|
+
}
|
|
2235
|
+
const candidate = resolve2(expanded);
|
|
2236
|
+
const name = basename(candidate);
|
|
2237
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
2238
|
+
}
|
|
2239
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
2240
|
+
const missingSegments = [];
|
|
2241
|
+
let current = directory;
|
|
2242
|
+
for (; ; ) {
|
|
2243
|
+
try {
|
|
2244
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
2245
|
+
} catch (err) {
|
|
2246
|
+
const parent = dirname2(current);
|
|
2247
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
2248
|
+
throw err;
|
|
2249
|
+
}
|
|
2250
|
+
missingSegments.unshift(basename(current));
|
|
2251
|
+
current = parent;
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
2256
|
+
for (const directory of allowedDirectories) {
|
|
2257
|
+
if (!isAbsolute(directory)) {
|
|
2258
|
+
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
2259
|
+
continue;
|
|
2260
|
+
}
|
|
2261
|
+
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
2262
|
+
if (realDirectory !== null && contains(realDirectory, realTarget)) {
|
|
2263
|
+
return realDirectory;
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
return null;
|
|
2267
|
+
}
|
|
2268
|
+
async function realpathCreatingIfMissing(directory) {
|
|
2269
|
+
try {
|
|
2270
|
+
return await realpath(directory);
|
|
2271
|
+
} catch (err) {
|
|
2272
|
+
if (err.code !== "ENOENT") {
|
|
2273
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2274
|
+
directory,
|
|
2275
|
+
reason: "unresolvable",
|
|
2276
|
+
...errorFields(err)
|
|
2277
|
+
});
|
|
2278
|
+
return null;
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
try {
|
|
2282
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
2283
|
+
await chmod(directory, DIRECTORY_MODE);
|
|
2284
|
+
return await realpath(directory);
|
|
2285
|
+
} catch (err) {
|
|
2286
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2287
|
+
directory,
|
|
2288
|
+
reason: "create_failed",
|
|
2289
|
+
...errorFields(err)
|
|
2290
|
+
});
|
|
2291
|
+
return null;
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
function contains(realDirectory, realTarget) {
|
|
2295
|
+
const rel = relative(realDirectory, realTarget);
|
|
2296
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
2297
|
+
}
|
|
2298
|
+
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2299
|
+
let current = existingAncestor;
|
|
2300
|
+
for (const segment of missingSegments) {
|
|
2301
|
+
current = join(current, segment);
|
|
2302
|
+
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2303
|
+
await chmod(current, DIRECTORY_MODE);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
async function writeAtomically(realTarget, content) {
|
|
2307
|
+
const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2308
|
+
let handle;
|
|
2309
|
+
try {
|
|
2310
|
+
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
2311
|
+
await handle.writeFile(content);
|
|
2312
|
+
await handle.chmod(FILE_MODE);
|
|
2313
|
+
await handle.close();
|
|
2314
|
+
handle = void 0;
|
|
2315
|
+
await rename(temporaryPath, realTarget);
|
|
2316
|
+
} catch (err) {
|
|
2317
|
+
await discardTemporaryFile(temporaryPath, handle);
|
|
2318
|
+
throw err;
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
async function discardTemporaryFile(temporaryPath, handle) {
|
|
2322
|
+
try {
|
|
2323
|
+
await handle?.close();
|
|
2324
|
+
} catch (err) {
|
|
2325
|
+
log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2326
|
+
}
|
|
2327
|
+
try {
|
|
2328
|
+
await unlink(temporaryPath);
|
|
2329
|
+
} catch (err) {
|
|
2330
|
+
const errno = err.code;
|
|
2331
|
+
if (errno !== "ENOENT" && errno !== "ENOTDIR") {
|
|
2332
|
+
log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
function refuse(code, message, fields) {
|
|
2337
|
+
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
2338
|
+
return { ok: false, code, message };
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
// src/lib/runner-file-sync.ts
|
|
2342
|
+
var MAX_ACK_ATTEMPTS = 5;
|
|
2343
|
+
async function syncPendingRunnerFiles(options) {
|
|
2344
|
+
const pending = await listPendingFiles(options);
|
|
2345
|
+
const pendingIds = new Set(pending.map((file) => file.id));
|
|
2346
|
+
for (const id of options.ackFailures.keys()) {
|
|
2347
|
+
if (!pendingIds.has(id)) options.ackFailures.delete(id);
|
|
2348
|
+
}
|
|
2349
|
+
if (pending.length === 0) return 0;
|
|
2350
|
+
options.log({
|
|
2351
|
+
level: "info",
|
|
2352
|
+
message: `Runner file sync: ${pending.length} file(s) queued for this runner`
|
|
2353
|
+
});
|
|
2354
|
+
let applied = 0;
|
|
2355
|
+
for (const file of pending) {
|
|
2356
|
+
if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
|
|
2357
|
+
if (await applyOne(options, file)) applied += 1;
|
|
2358
|
+
}
|
|
2359
|
+
return applied;
|
|
2360
|
+
}
|
|
2361
|
+
async function listPendingFiles(options) {
|
|
2362
|
+
let res;
|
|
2363
|
+
try {
|
|
2364
|
+
res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
|
|
2365
|
+
headers: { Authorization: options.getAuthHeader() }
|
|
2366
|
+
});
|
|
2367
|
+
} catch (err) {
|
|
2368
|
+
options.log({
|
|
2369
|
+
level: "warn",
|
|
2370
|
+
message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
|
|
2371
|
+
});
|
|
2372
|
+
return [];
|
|
2373
|
+
}
|
|
2374
|
+
if (!res.ok) {
|
|
2375
|
+
options.log({
|
|
2376
|
+
level: res.status === 404 ? "debug" : "warn",
|
|
2377
|
+
message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2378
|
+
});
|
|
2379
|
+
return [];
|
|
2380
|
+
}
|
|
2381
|
+
let body;
|
|
2382
|
+
try {
|
|
2383
|
+
body = await res.json();
|
|
2384
|
+
} catch (err) {
|
|
2385
|
+
options.log({
|
|
2386
|
+
level: "warn",
|
|
2387
|
+
message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
|
|
2388
|
+
});
|
|
2389
|
+
return [];
|
|
2390
|
+
}
|
|
2391
|
+
if (!Array.isArray(body)) {
|
|
2392
|
+
options.log({
|
|
2393
|
+
level: "warn",
|
|
2394
|
+
message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
|
|
2395
|
+
});
|
|
2396
|
+
return [];
|
|
2397
|
+
}
|
|
2398
|
+
const files = [];
|
|
2399
|
+
for (const entry of body) {
|
|
2400
|
+
const file = asPendingFile(entry);
|
|
2401
|
+
if (file === null) {
|
|
2402
|
+
options.log({
|
|
2403
|
+
level: "warn",
|
|
2404
|
+
message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
|
|
2405
|
+
});
|
|
2406
|
+
continue;
|
|
2407
|
+
}
|
|
2408
|
+
files.push(file);
|
|
2409
|
+
}
|
|
2410
|
+
return files;
|
|
2411
|
+
}
|
|
2412
|
+
function asPendingFile(entry) {
|
|
2413
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
2414
|
+
const { id, path, size } = entry;
|
|
2415
|
+
if (typeof id !== "string" || id === "") return null;
|
|
2416
|
+
if (typeof path !== "string" || path === "") return null;
|
|
2417
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
|
|
2418
|
+
return { id, path, size };
|
|
2419
|
+
}
|
|
2420
|
+
async function applyOne(options, file) {
|
|
2421
|
+
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
2422
|
+
if (options.allowedDirectories.length === 0) {
|
|
2423
|
+
options.log({
|
|
2424
|
+
level: "warn",
|
|
2425
|
+
message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
|
|
2426
|
+
});
|
|
2427
|
+
await ack(options, file, "rejected", "file_sync_disabled");
|
|
2428
|
+
return false;
|
|
2429
|
+
}
|
|
2430
|
+
if (file.size > MAX_FILE_PUSH_BYTES) {
|
|
2431
|
+
options.log({
|
|
2432
|
+
level: "warn",
|
|
2433
|
+
message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
|
|
2434
|
+
});
|
|
2435
|
+
await ack(options, file, "rejected", "file_too_large");
|
|
2436
|
+
return false;
|
|
2437
|
+
}
|
|
2438
|
+
const download = await downloadContent(options, file, label);
|
|
2439
|
+
if (!download.ok) {
|
|
2440
|
+
if (download.terminal) await ack(options, file, "rejected", download.code);
|
|
2441
|
+
return false;
|
|
2442
|
+
}
|
|
2443
|
+
let outcome;
|
|
2444
|
+
try {
|
|
2445
|
+
outcome = await writePushedFile({
|
|
2446
|
+
requestedPath: file.path,
|
|
2447
|
+
content: download.content,
|
|
2448
|
+
allowedDirectories: options.allowedDirectories,
|
|
2449
|
+
homeDir: options.homeDir
|
|
2450
|
+
});
|
|
2451
|
+
} catch (err) {
|
|
2452
|
+
options.log({
|
|
2453
|
+
level: "error",
|
|
2454
|
+
message: `Runner file ${label} could not be written: ${describe(err)}`
|
|
2455
|
+
});
|
|
2456
|
+
await ack(options, file, "rejected", "write_failed");
|
|
2457
|
+
return false;
|
|
2458
|
+
}
|
|
2459
|
+
if (!outcome.ok) {
|
|
2460
|
+
options.log({
|
|
2461
|
+
level: "warn",
|
|
2462
|
+
message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
|
|
2463
|
+
});
|
|
2464
|
+
await ack(options, file, "rejected", outcome.code);
|
|
2465
|
+
return false;
|
|
2466
|
+
}
|
|
2467
|
+
options.log({
|
|
2468
|
+
level: "info",
|
|
2469
|
+
message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
|
|
2470
|
+
});
|
|
2471
|
+
await ack(options, file, "applied");
|
|
2472
|
+
return true;
|
|
2473
|
+
}
|
|
2474
|
+
function durableDownloadCode(status) {
|
|
2475
|
+
return status === 413 ? "file_too_large" : "write_failed";
|
|
2476
|
+
}
|
|
2477
|
+
async function downloadContent(options, file, label) {
|
|
2478
|
+
try {
|
|
2479
|
+
const res = await options.fetchImpl(
|
|
2480
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
|
|
2481
|
+
{ headers: { Authorization: options.getAuthHeader() } }
|
|
2482
|
+
);
|
|
2483
|
+
if (!res.ok) {
|
|
2484
|
+
const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
|
|
2485
|
+
if (!terminal) {
|
|
2486
|
+
options.log({
|
|
2487
|
+
level: "warn",
|
|
2488
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2489
|
+
});
|
|
2490
|
+
return { ok: false, terminal: false };
|
|
2491
|
+
}
|
|
2492
|
+
const code = durableDownloadCode(res.status);
|
|
2493
|
+
options.log({
|
|
2494
|
+
level: "error",
|
|
2495
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
|
|
2496
|
+
});
|
|
2497
|
+
return { ok: false, terminal: true, code };
|
|
2498
|
+
}
|
|
2499
|
+
return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
|
|
2500
|
+
} catch (err) {
|
|
2501
|
+
options.log({
|
|
2502
|
+
level: "warn",
|
|
2503
|
+
message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
|
|
2504
|
+
});
|
|
2505
|
+
return { ok: false, terminal: false };
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
async function ack(options, file, status, reason) {
|
|
2509
|
+
const outcome = `${status}${reason ? ` (${reason})` : ""}`;
|
|
2510
|
+
try {
|
|
2511
|
+
const res = await options.fetchImpl(
|
|
2512
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
2513
|
+
{
|
|
2514
|
+
method: "POST",
|
|
2515
|
+
headers: {
|
|
2516
|
+
Authorization: options.getAuthHeader(),
|
|
2517
|
+
"Content-Type": "application/json"
|
|
2518
|
+
},
|
|
2519
|
+
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
2520
|
+
}
|
|
2521
|
+
);
|
|
2522
|
+
if (!res.ok) {
|
|
2523
|
+
recordAckFailure(
|
|
2524
|
+
options,
|
|
2525
|
+
file,
|
|
2526
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
|
|
2527
|
+
);
|
|
2528
|
+
return;
|
|
2529
|
+
}
|
|
2530
|
+
options.ackFailures.delete(file.id);
|
|
2531
|
+
} catch (err) {
|
|
2532
|
+
recordAckFailure(
|
|
2533
|
+
options,
|
|
2534
|
+
file,
|
|
2535
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
|
|
2536
|
+
);
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
function recordAckFailure(options, file, what) {
|
|
2540
|
+
const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
|
|
2541
|
+
options.ackFailures.set(file.id, attempts);
|
|
2542
|
+
options.log({
|
|
2543
|
+
level: "error",
|
|
2544
|
+
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})`
|
|
2545
|
+
});
|
|
2546
|
+
}
|
|
2547
|
+
function describe(err) {
|
|
2548
|
+
return err instanceof Error ? err.message : String(err);
|
|
2549
|
+
}
|
|
2550
|
+
|
|
2015
2551
|
// src/lib/channels/driver.ts
|
|
2016
2552
|
function messageIdOf(m) {
|
|
2017
2553
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -2040,7 +2576,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
2040
2576
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
2041
2577
|
var HEARTBEAT_MS = 6e4;
|
|
2042
2578
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2579
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2580
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
2043
2581
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2582
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
2044
2583
|
var ChannelAuthError = class extends Error {
|
|
2045
2584
|
constructor(message) {
|
|
2046
2585
|
super(message);
|
|
@@ -2077,8 +2616,38 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2077
2616
|
pausedMaxWaitMs;
|
|
2078
2617
|
stuckQueuedMs;
|
|
2079
2618
|
now;
|
|
2619
|
+
fileSyncDirectories;
|
|
2620
|
+
homeDir;
|
|
2080
2621
|
/** Cache of conversationId → opencode sessionId. */
|
|
2081
2622
|
sessions = /* @__PURE__ */ new Map();
|
|
2623
|
+
/**
|
|
2624
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2625
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2626
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2627
|
+
* must bind a fresh one.
|
|
2628
|
+
*
|
|
2629
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2630
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2631
|
+
* the same session, and its watcher's routine status writes carry
|
|
2632
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2633
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2634
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2635
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2636
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2637
|
+
* is one we deliberately keep (see `markDone`).
|
|
2638
|
+
*
|
|
2639
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2640
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2641
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2642
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2643
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2644
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2645
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2646
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2647
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2648
|
+
* bounded cost.
|
|
2649
|
+
*/
|
|
2650
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
2082
2651
|
/**
|
|
2083
2652
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
2084
2653
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2201,6 +2770,24 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2201
2770
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2202
2771
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2203
2772
|
draining = false;
|
|
2773
|
+
/**
|
|
2774
|
+
* Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
|
|
2775
|
+
* drain ping don't download, write and ack the same file twice.
|
|
2776
|
+
*/
|
|
2777
|
+
syncingFiles = false;
|
|
2778
|
+
/**
|
|
2779
|
+
* Consecutive failed acks per pending file (#559). Lives on the driver so it
|
|
2780
|
+
* survives across drains — without it, a file whose ack keeps failing is
|
|
2781
|
+
* re-downloaded and re-written every ~2s until the server expires it.
|
|
2782
|
+
*/
|
|
2783
|
+
fileAckFailures = /* @__PURE__ */ new Map();
|
|
2784
|
+
/**
|
|
2785
|
+
* Monotonic count of files this runner has pulled and written (#559). Only
|
|
2786
|
+
* ever increases, so `run.ts` detects work by comparing it against the value
|
|
2787
|
+
* it saw on the previous cycle — including work that landed mid-sleep, the
|
|
2788
|
+
* same trick `lastProxiedActivityAt` uses.
|
|
2789
|
+
*/
|
|
2790
|
+
appliedFileCount = 0;
|
|
2204
2791
|
/**
|
|
2205
2792
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2206
2793
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2231,6 +2818,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2231
2818
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2232
2819
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2233
2820
|
this.now = config2.now ?? (() => Date.now());
|
|
2821
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
2822
|
+
this.homeDir = config2.homeDir ?? homedir();
|
|
2234
2823
|
}
|
|
2235
2824
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2236
2825
|
get opencodeBase() {
|
|
@@ -2258,6 +2847,47 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2258
2847
|
);
|
|
2259
2848
|
return run2;
|
|
2260
2849
|
}
|
|
2850
|
+
/**
|
|
2851
|
+
* Pull-and-apply any files Evident has queued for this runner (#559), riding
|
|
2852
|
+
* the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
|
|
2853
|
+
* and drain ping that call `drainPending()`. There is deliberately no channel,
|
|
2854
|
+
* control frame or poll loop of its own: worst-case latency is one poll tick.
|
|
2855
|
+
*
|
|
2856
|
+
* NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
|
|
2857
|
+
* cost a conversation turn. Failures are logged and either acked as a terminal
|
|
2858
|
+
* outcome or left pending for the next drain (see `runner-file-sync.ts`).
|
|
2859
|
+
*
|
|
2860
|
+
* Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
|
|
2861
|
+
*
|
|
2862
|
+
* @returns the number of files written to disk.
|
|
2863
|
+
*/
|
|
2864
|
+
async syncPendingFiles() {
|
|
2865
|
+
if (this.stopped) return 0;
|
|
2866
|
+
if (this.syncingFiles) return 0;
|
|
2867
|
+
this.syncingFiles = true;
|
|
2868
|
+
try {
|
|
2869
|
+
const applied = await syncPendingRunnerFiles({
|
|
2870
|
+
agentId: this.agentId,
|
|
2871
|
+
apiUrl: this.apiUrl,
|
|
2872
|
+
getAuthHeader: this.getAuthHeader,
|
|
2873
|
+
fetchImpl: this.fetchImpl,
|
|
2874
|
+
allowedDirectories: this.fileSyncDirectories,
|
|
2875
|
+
homeDir: this.homeDir,
|
|
2876
|
+
ackFailures: this.fileAckFailures,
|
|
2877
|
+
log: this.log
|
|
2878
|
+
});
|
|
2879
|
+
this.appliedFileCount += applied;
|
|
2880
|
+
return applied;
|
|
2881
|
+
} catch (err) {
|
|
2882
|
+
this.log({
|
|
2883
|
+
level: "error",
|
|
2884
|
+
message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
|
|
2885
|
+
});
|
|
2886
|
+
return 0;
|
|
2887
|
+
} finally {
|
|
2888
|
+
this.syncingFiles = false;
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2261
2891
|
async runDrain() {
|
|
2262
2892
|
let dispatched = 0;
|
|
2263
2893
|
try {
|
|
@@ -2291,6 +2921,28 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2291
2921
|
}
|
|
2292
2922
|
return false;
|
|
2293
2923
|
}
|
|
2924
|
+
/**
|
|
2925
|
+
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
2926
|
+
*
|
|
2927
|
+
* Pulling a file is real work that `drainPending()` knows nothing about, so
|
|
2928
|
+
* without this a near-idle runner counts a credential pull as an empty tick
|
|
2929
|
+
* and `--idle-timeout` can `process.exit` mid-pull — leaving a
|
|
2930
|
+
* `.evident-push-*.tmp` behind — or immediately after the write, before the
|
|
2931
|
+
* browser has run the authorize/callback that activates it (the user then sees
|
|
2932
|
+
* `saved_not_activated` for a runner that was fine).
|
|
2933
|
+
*
|
|
2934
|
+
* Two signals because one cannot cover both cases: `inFlight` is the pull
|
|
2935
|
+
* happening RIGHT NOW (it may outlive the tick that started it), and
|
|
2936
|
+
* `appliedFiles` is monotonic so a pull that started AND finished between two
|
|
2937
|
+
* idle checks still shows up as an advance.
|
|
2938
|
+
*
|
|
2939
|
+
* CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
|
|
2940
|
+
* the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
|
|
2941
|
+
* samples afterwards reads `true` every single cycle and can never idle out.
|
|
2942
|
+
*/
|
|
2943
|
+
fileSyncActivity() {
|
|
2944
|
+
return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
|
|
2945
|
+
}
|
|
2294
2946
|
/**
|
|
2295
2947
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2296
2948
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2352,7 +3004,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2352
3004
|
await this.sleep(step);
|
|
2353
3005
|
}
|
|
2354
3006
|
}
|
|
2355
|
-
while (this.hasInFlightWatchers()) {
|
|
3007
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2356
3008
|
if (this.now() >= deadline) return false;
|
|
2357
3009
|
await this.sleep(step);
|
|
2358
3010
|
}
|
|
@@ -2387,10 +3039,15 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2387
3039
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2388
3040
|
*/
|
|
2389
3041
|
async processConversation(conv) {
|
|
2390
|
-
const sessionId = await this.ensureSession(conv);
|
|
3042
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2391
3043
|
const messages = await this.getPendingMessages(conv.id);
|
|
2392
3044
|
let dispatched = 0;
|
|
2393
3045
|
let skippedAlreadyDispatched = 0;
|
|
3046
|
+
if (refusedSessionId && messages.length > 0) {
|
|
3047
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
3048
|
+
superseded_session_id: refusedSessionId
|
|
3049
|
+
});
|
|
3050
|
+
}
|
|
2394
3051
|
for (const message of messages) {
|
|
2395
3052
|
if (this.stopped) break;
|
|
2396
3053
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2417,7 +3074,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2417
3074
|
} catch (err) {
|
|
2418
3075
|
if (err instanceof ChannelAuthError) throw err;
|
|
2419
3076
|
this.dispatched.delete(message.id);
|
|
2420
|
-
|
|
3077
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
3078
|
+
if (exists === false) {
|
|
2421
3079
|
this.sessions.delete(conv.id);
|
|
2422
3080
|
this.log({
|
|
2423
3081
|
level: "warn",
|
|
@@ -2427,15 +3085,39 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2427
3085
|
});
|
|
2428
3086
|
break;
|
|
2429
3087
|
}
|
|
2430
|
-
|
|
3088
|
+
if (exists === null) {
|
|
3089
|
+
this.log({
|
|
3090
|
+
level: "warn",
|
|
3091
|
+
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.`,
|
|
3092
|
+
conversation_id: conv.id,
|
|
3093
|
+
message_id: message.id
|
|
3094
|
+
});
|
|
3095
|
+
break;
|
|
3096
|
+
}
|
|
3097
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3098
|
+
this.sessions.delete(conv.id);
|
|
3099
|
+
this.supersede(conv.id, sessionId);
|
|
3100
|
+
this.log({
|
|
3101
|
+
level: "warn",
|
|
3102
|
+
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.`,
|
|
3103
|
+
conversation_id: conv.id,
|
|
3104
|
+
message_id: message.id
|
|
3105
|
+
});
|
|
3106
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3107
|
+
this.log({
|
|
3108
|
+
level: "warn",
|
|
3109
|
+
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)}`,
|
|
3110
|
+
conversation_id: conv.id,
|
|
3111
|
+
message_id: message.id
|
|
3112
|
+
});
|
|
2431
3113
|
});
|
|
2432
3114
|
this.log({
|
|
2433
3115
|
level: "error",
|
|
2434
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3116
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2435
3117
|
conversation_id: conv.id,
|
|
2436
3118
|
message_id: message.id
|
|
2437
3119
|
});
|
|
2438
|
-
|
|
3120
|
+
break;
|
|
2439
3121
|
}
|
|
2440
3122
|
if (opencodeMessageId === null) {
|
|
2441
3123
|
this.log({
|
|
@@ -2461,8 +3143,42 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2461
3143
|
this.ensureWatcherRunning(sessionId);
|
|
2462
3144
|
return dispatched;
|
|
2463
3145
|
}
|
|
3146
|
+
/**
|
|
3147
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
3148
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
3149
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
3150
|
+
*/
|
|
3151
|
+
supersede(conversationId, sessionId) {
|
|
3152
|
+
this.supersededSessions.delete(conversationId);
|
|
3153
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
3154
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
3155
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
3156
|
+
if (oldest === void 0) return;
|
|
3157
|
+
this.supersededSessions.delete(oldest);
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
3161
|
+
isSuperseded(conversationId, sessionId) {
|
|
3162
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
3163
|
+
}
|
|
3164
|
+
/**
|
|
3165
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
3166
|
+
*
|
|
3167
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3168
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3169
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
3170
|
+
*/
|
|
2464
3171
|
async ensureSession(conv) {
|
|
2465
3172
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
3173
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
3174
|
+
this.log({
|
|
3175
|
+
level: "warn",
|
|
3176
|
+
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.`,
|
|
3177
|
+
conversation_id: conv.id
|
|
3178
|
+
});
|
|
3179
|
+
this.sessions.delete(conv.id);
|
|
3180
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
3181
|
+
}
|
|
2466
3182
|
if (bound) {
|
|
2467
3183
|
const exists = await sessionExists(this.port, bound);
|
|
2468
3184
|
if (exists === false) {
|
|
@@ -2472,12 +3188,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2472
3188
|
conversation_id: conv.id
|
|
2473
3189
|
});
|
|
2474
3190
|
this.sessions.delete(conv.id);
|
|
2475
|
-
return this.createAndBindSession(conv.id);
|
|
3191
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2476
3192
|
}
|
|
2477
3193
|
this.sessions.set(conv.id, bound);
|
|
2478
|
-
return bound;
|
|
3194
|
+
return { sessionId: bound };
|
|
2479
3195
|
}
|
|
2480
|
-
return this.createAndBindSession(conv.id);
|
|
3196
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2481
3197
|
}
|
|
2482
3198
|
/**
|
|
2483
3199
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2565,7 +3281,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2565
3281
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2566
3282
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2567
3283
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2568
|
-
*
|
|
3284
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
3285
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
3286
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
3287
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
3288
|
+
* logged with context (no silent swallow).
|
|
2569
3289
|
*/
|
|
2570
3290
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2571
3291
|
try {
|
|
@@ -2574,6 +3294,25 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2574
3294
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2575
3295
|
);
|
|
2576
3296
|
if (!res.ok) {
|
|
3297
|
+
let reason;
|
|
3298
|
+
try {
|
|
3299
|
+
const body = await res.json();
|
|
3300
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
3301
|
+
} catch (parseErr) {
|
|
3302
|
+
this.log({
|
|
3303
|
+
level: "debug",
|
|
3304
|
+
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`,
|
|
3305
|
+
message_id: messageId
|
|
3306
|
+
});
|
|
3307
|
+
}
|
|
3308
|
+
if (reason === "needs_reauth") {
|
|
3309
|
+
this.log({
|
|
3310
|
+
level: "error",
|
|
3311
|
+
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)`,
|
|
3312
|
+
message_id: messageId
|
|
3313
|
+
});
|
|
3314
|
+
return { needsReauth: true };
|
|
3315
|
+
}
|
|
2577
3316
|
this.log({
|
|
2578
3317
|
level: "error",
|
|
2579
3318
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2613,6 +3352,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2613
3352
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2614
3353
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2615
3354
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
3355
|
+
const failedReason = outcomes.some(
|
|
3356
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
3357
|
+
) ? "needs_reauth" : void 0;
|
|
2616
3358
|
this.log({
|
|
2617
3359
|
level: "info",
|
|
2618
3360
|
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`,
|
|
@@ -2622,7 +3364,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2622
3364
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2623
3365
|
skipped,
|
|
2624
3366
|
failed,
|
|
2625
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3367
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3368
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2626
3369
|
});
|
|
2627
3370
|
}
|
|
2628
3371
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2653,12 +3396,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2653
3396
|
stuckReported: false,
|
|
2654
3397
|
lastAliveAt: 0,
|
|
2655
3398
|
aliveInFlight: false,
|
|
3399
|
+
titleSynced: false,
|
|
3400
|
+
titleSyncInFlight: false,
|
|
2656
3401
|
awaitingHumanLatched: false,
|
|
2657
3402
|
pausedOnQuestion: false,
|
|
2658
3403
|
pausedOnPermission: false,
|
|
2659
3404
|
pausedClearConfirmed: false,
|
|
2660
3405
|
pausedInFlight: false,
|
|
2661
|
-
deliveryDeadlineAnchored: false
|
|
3406
|
+
deliveryDeadlineAnchored: false,
|
|
3407
|
+
b2PinnedSinceMs: 0,
|
|
3408
|
+
b2LastDescendantCheckMs: 0,
|
|
3409
|
+
b2AbandonedSignalled: false
|
|
2662
3410
|
});
|
|
2663
3411
|
}
|
|
2664
3412
|
/**
|
|
@@ -2726,12 +3474,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2726
3474
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
2727
3475
|
lastAliveAt: 0,
|
|
2728
3476
|
aliveInFlight: false,
|
|
3477
|
+
titleSynced: false,
|
|
3478
|
+
titleSyncInFlight: false,
|
|
2729
3479
|
awaitingHumanLatched: false,
|
|
2730
3480
|
pausedOnQuestion: false,
|
|
2731
3481
|
pausedOnPermission: false,
|
|
2732
3482
|
pausedClearConfirmed: false,
|
|
2733
3483
|
pausedInFlight: false,
|
|
2734
|
-
deliveryDeadlineAnchored: false
|
|
3484
|
+
deliveryDeadlineAnchored: false,
|
|
3485
|
+
b2PinnedSinceMs: 0,
|
|
3486
|
+
b2LastDescendantCheckMs: 0,
|
|
3487
|
+
b2AbandonedSignalled: false
|
|
2735
3488
|
});
|
|
2736
3489
|
}
|
|
2737
3490
|
/**
|
|
@@ -2893,58 +3646,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2893
3646
|
}
|
|
2894
3647
|
}
|
|
2895
3648
|
if (state === "done") {
|
|
2896
|
-
this.
|
|
2897
|
-
if (!inFlight.done) {
|
|
2898
|
-
this.log({
|
|
2899
|
-
level: "info",
|
|
2900
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
2901
|
-
conversation_id: conv.id,
|
|
2902
|
-
message_id: inFlight.evidentMessageId
|
|
2903
|
-
});
|
|
2904
|
-
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
2905
|
-
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2906
|
-
try {
|
|
2907
|
-
await this.markDone(
|
|
2908
|
-
conv.id,
|
|
2909
|
-
inFlight.evidentMessageId,
|
|
2910
|
-
sessionId,
|
|
2911
|
-
inFlight.opencodeMessageId,
|
|
2912
|
-
title,
|
|
2913
|
-
usage
|
|
2914
|
-
);
|
|
2915
|
-
} catch (err) {
|
|
2916
|
-
if (err instanceof ChannelAuthError) throw err;
|
|
2917
|
-
if (err instanceof ChannelTerminalError) {
|
|
2918
|
-
this.log({
|
|
2919
|
-
level: "warn",
|
|
2920
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
2921
|
-
conversation_id: conv.id,
|
|
2922
|
-
message_id: inFlight.evidentMessageId
|
|
2923
|
-
});
|
|
2924
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2925
|
-
return;
|
|
2926
|
-
}
|
|
2927
|
-
if (this.now() >= inFlight.deadline) {
|
|
2928
|
-
this.log({
|
|
2929
|
-
level: "warn",
|
|
2930
|
-
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)}`,
|
|
2931
|
-
conversation_id: conv.id,
|
|
2932
|
-
message_id: inFlight.evidentMessageId
|
|
2933
|
-
});
|
|
2934
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2935
|
-
return;
|
|
2936
|
-
}
|
|
2937
|
-
this.log({
|
|
2938
|
-
level: "warn",
|
|
2939
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
2940
|
-
conversation_id: conv.id,
|
|
2941
|
-
message_id: inFlight.evidentMessageId
|
|
2942
|
-
});
|
|
2943
|
-
return;
|
|
2944
|
-
}
|
|
2945
|
-
inFlight.done = true;
|
|
2946
|
-
}
|
|
2947
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3649
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
2948
3650
|
return;
|
|
2949
3651
|
}
|
|
2950
3652
|
if (state === "failed") {
|
|
@@ -2958,8 +3660,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2958
3660
|
message_id: inFlight.evidentMessageId
|
|
2959
3661
|
});
|
|
2960
3662
|
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3663
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
2961
3664
|
try {
|
|
2962
|
-
await this.markFailed(
|
|
3665
|
+
await this.markFailed(
|
|
3666
|
+
conv.id,
|
|
3667
|
+
inFlight.evidentMessageId,
|
|
3668
|
+
sessionId,
|
|
3669
|
+
error2,
|
|
3670
|
+
usage,
|
|
3671
|
+
failure
|
|
3672
|
+
);
|
|
2963
3673
|
} catch (err) {
|
|
2964
3674
|
if (err instanceof ChannelAuthError) throw err;
|
|
2965
3675
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3004,6 +3714,44 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3004
3714
|
});
|
|
3005
3715
|
}
|
|
3006
3716
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3717
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3718
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3719
|
+
if (!pinnedNow) {
|
|
3720
|
+
if (snapshotReadable) {
|
|
3721
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3722
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3723
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3724
|
+
}
|
|
3725
|
+
} else {
|
|
3726
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3727
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3728
|
+
return;
|
|
3729
|
+
}
|
|
3730
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3731
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3732
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3733
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3734
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3735
|
+
if (isB2AbandonmentConfirmed({
|
|
3736
|
+
pinnedForMs,
|
|
3737
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3738
|
+
descendantOngoing
|
|
3739
|
+
})) {
|
|
3740
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3741
|
+
this.log({
|
|
3742
|
+
level: "warn",
|
|
3743
|
+
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`,
|
|
3744
|
+
conversation_id: conv.id,
|
|
3745
|
+
message_id: id
|
|
3746
|
+
});
|
|
3747
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3748
|
+
watched_for_ms: pinnedForMs
|
|
3749
|
+
});
|
|
3750
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3751
|
+
return;
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
}
|
|
3007
3755
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
3008
3756
|
this.log({
|
|
3009
3757
|
level: "warn",
|
|
@@ -3023,6 +3771,18 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3023
3771
|
inFlight.aliveInFlight = false;
|
|
3024
3772
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
3025
3773
|
});
|
|
3774
|
+
if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
|
|
3775
|
+
inFlight.titleSyncInFlight = true;
|
|
3776
|
+
void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
|
|
3777
|
+
if (!title) {
|
|
3778
|
+
inFlight.titleSyncInFlight = false;
|
|
3779
|
+
return;
|
|
3780
|
+
}
|
|
3781
|
+
const ok = await this.patchConversationTitle(conv.id, title);
|
|
3782
|
+
inFlight.titleSyncInFlight = false;
|
|
3783
|
+
if (ok) inFlight.titleSynced = true;
|
|
3784
|
+
});
|
|
3785
|
+
}
|
|
3026
3786
|
}
|
|
3027
3787
|
if (awaitingHuman) {
|
|
3028
3788
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -3060,6 +3820,70 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3060
3820
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3061
3821
|
}
|
|
3062
3822
|
}
|
|
3823
|
+
/**
|
|
3824
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
3825
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
3826
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
3827
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
3828
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
3829
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
3830
|
+
* and risking the two copies silently drifting apart.
|
|
3831
|
+
*/
|
|
3832
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
3833
|
+
const conv = watcher.conv;
|
|
3834
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
3835
|
+
if (!inFlight.done) {
|
|
3836
|
+
this.log({
|
|
3837
|
+
level: "info",
|
|
3838
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
3839
|
+
conversation_id: conv.id,
|
|
3840
|
+
message_id: inFlight.evidentMessageId
|
|
3841
|
+
});
|
|
3842
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3843
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3844
|
+
try {
|
|
3845
|
+
await this.markDone(
|
|
3846
|
+
conv.id,
|
|
3847
|
+
inFlight.evidentMessageId,
|
|
3848
|
+
sessionId,
|
|
3849
|
+
inFlight.opencodeMessageId,
|
|
3850
|
+
title,
|
|
3851
|
+
usage
|
|
3852
|
+
);
|
|
3853
|
+
} catch (err) {
|
|
3854
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3855
|
+
if (err instanceof ChannelTerminalError) {
|
|
3856
|
+
this.log({
|
|
3857
|
+
level: "warn",
|
|
3858
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
3859
|
+
conversation_id: conv.id,
|
|
3860
|
+
message_id: inFlight.evidentMessageId
|
|
3861
|
+
});
|
|
3862
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3863
|
+
return;
|
|
3864
|
+
}
|
|
3865
|
+
if (this.now() >= inFlight.deadline) {
|
|
3866
|
+
this.log({
|
|
3867
|
+
level: "warn",
|
|
3868
|
+
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)}`,
|
|
3869
|
+
conversation_id: conv.id,
|
|
3870
|
+
message_id: inFlight.evidentMessageId
|
|
3871
|
+
});
|
|
3872
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3873
|
+
return;
|
|
3874
|
+
}
|
|
3875
|
+
this.log({
|
|
3876
|
+
level: "warn",
|
|
3877
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
3878
|
+
conversation_id: conv.id,
|
|
3879
|
+
message_id: inFlight.evidentMessageId
|
|
3880
|
+
});
|
|
3881
|
+
return;
|
|
3882
|
+
}
|
|
3883
|
+
inFlight.done = true;
|
|
3884
|
+
}
|
|
3885
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3886
|
+
}
|
|
3063
3887
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
3064
3888
|
/**
|
|
3065
3889
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3226,6 +4050,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3226
4050
|
if (state === "failed") {
|
|
3227
4051
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3228
4052
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4053
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3229
4054
|
this.log({
|
|
3230
4055
|
level: "error",
|
|
3231
4056
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3233,7 +4058,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3233
4058
|
message_id: row.id
|
|
3234
4059
|
});
|
|
3235
4060
|
try {
|
|
3236
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
4061
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3237
4062
|
} catch (err) {
|
|
3238
4063
|
if (err instanceof ChannelAuthError) throw err;
|
|
3239
4064
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3639,6 +4464,47 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3639
4464
|
}
|
|
3640
4465
|
return false;
|
|
3641
4466
|
}
|
|
4467
|
+
/**
|
|
4468
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4469
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4470
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4471
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4472
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4473
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4474
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4475
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4476
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4477
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4478
|
+
* not ongoing".
|
|
4479
|
+
*
|
|
4480
|
+
* Return contract:
|
|
4481
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4482
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4483
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4484
|
+
* CONFIRMED NOT a descendant of it.
|
|
4485
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4486
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4487
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4488
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4489
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4490
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4491
|
+
* here.
|
|
4492
|
+
*
|
|
4493
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4494
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4495
|
+
* by interaction attribution or the recovery path.
|
|
4496
|
+
*/
|
|
4497
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4498
|
+
let current = sessionId;
|
|
4499
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4500
|
+
if (current === rootSessionId) return true;
|
|
4501
|
+
const parent = await this.resolveSessionParent(current);
|
|
4502
|
+
if (parent === void 0) return null;
|
|
4503
|
+
if (parent === null) return false;
|
|
4504
|
+
current = parent;
|
|
4505
|
+
}
|
|
4506
|
+
return null;
|
|
4507
|
+
}
|
|
3642
4508
|
/**
|
|
3643
4509
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
3644
4510
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -3723,6 +4589,54 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3723
4589
|
}
|
|
3724
4590
|
return null;
|
|
3725
4591
|
}
|
|
4592
|
+
/**
|
|
4593
|
+
* Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
|
|
4594
|
+
* session title onto the conversation via the PLAIN conversation-update
|
|
4595
|
+
* endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
|
|
4596
|
+
* message-status endpoint `markProcessing`/`markDone` use. Deliberately a
|
|
4597
|
+
* separate, lighter call: it carries no `status`, so it cannot re-trigger the
|
|
4598
|
+
* `processing`/`done` transition side effects (Slack notices, activity-log
|
|
4599
|
+
* rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
|
|
4600
|
+
* ever touches `conversations.title`. That route (`routes/conversations.ts`)
|
|
4601
|
+
* skips a title write matching the stored value, so a redundant call with the
|
|
4602
|
+
* same title is a real no-op — it does not bump `updated_at`, which the
|
|
4603
|
+
* conversation list sorts and paginates on. (Note this is a DIFFERENT guard
|
|
4604
|
+
* from `threads.ts`'s "non-empty AND changed" one, which only covers the
|
|
4605
|
+
* message-status PATCH; the non-empty half is enforced here instead, by
|
|
4606
|
+
* `resolveSessionTitle` never returning an empty/placeholder title.)
|
|
4607
|
+
*
|
|
4608
|
+
* Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
|
|
4609
|
+
* is logged and the title is simply retried on the next heartbeat tick (the
|
|
4610
|
+
* caller only latches `titleSynced` on `true`).
|
|
4611
|
+
*/
|
|
4612
|
+
async patchConversationTitle(conversationId, title) {
|
|
4613
|
+
try {
|
|
4614
|
+
const res = await this.fetchImpl(
|
|
4615
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
|
|
4616
|
+
{
|
|
4617
|
+
method: "PATCH",
|
|
4618
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
4619
|
+
body: JSON.stringify({ title })
|
|
4620
|
+
}
|
|
4621
|
+
);
|
|
4622
|
+
if (!res.ok) {
|
|
4623
|
+
this.log({
|
|
4624
|
+
level: "debug",
|
|
4625
|
+
message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
|
|
4626
|
+
conversation_id: conversationId
|
|
4627
|
+
});
|
|
4628
|
+
return false;
|
|
4629
|
+
}
|
|
4630
|
+
return true;
|
|
4631
|
+
} catch (err) {
|
|
4632
|
+
this.log({
|
|
4633
|
+
level: "debug",
|
|
4634
|
+
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)}`,
|
|
4635
|
+
conversation_id: conversationId
|
|
4636
|
+
});
|
|
4637
|
+
return false;
|
|
4638
|
+
}
|
|
4639
|
+
}
|
|
3726
4640
|
/**
|
|
3727
4641
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
3728
4642
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -3781,6 +4695,84 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3781
4695
|
}
|
|
3782
4696
|
return false;
|
|
3783
4697
|
}
|
|
4698
|
+
/**
|
|
4699
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4700
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4701
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4702
|
+
*
|
|
4703
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4704
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4705
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4706
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4707
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4708
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4709
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4710
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4711
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4712
|
+
* executing, between its step's completion and the next generation step"
|
|
4713
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4714
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4715
|
+
* message timestamps at all.
|
|
4716
|
+
*
|
|
4717
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4718
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4719
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4720
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4721
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4722
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4723
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4724
|
+
* delegation — which the root's status is not.
|
|
4725
|
+
*
|
|
4726
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4727
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4728
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4729
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4730
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4731
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4732
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4733
|
+
* instead.
|
|
4734
|
+
*
|
|
4735
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4736
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4737
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4738
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4739
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4740
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4741
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4742
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4743
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4744
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4745
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4746
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4747
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4748
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4749
|
+
* (unlike the recovery cross-check's contract) — see
|
|
4750
|
+
* `isB2AbandonmentConfirmed`.
|
|
4751
|
+
*/
|
|
4752
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
4753
|
+
const sessions = await listSessions(this.port);
|
|
4754
|
+
if (!sessions) {
|
|
4755
|
+
this.log({
|
|
4756
|
+
level: "warn",
|
|
4757
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
4758
|
+
});
|
|
4759
|
+
return null;
|
|
4760
|
+
}
|
|
4761
|
+
let indeterminate = false;
|
|
4762
|
+
for (const candidate of sessions) {
|
|
4763
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
4764
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
4765
|
+
if (membership === null) {
|
|
4766
|
+
indeterminate = true;
|
|
4767
|
+
continue;
|
|
4768
|
+
}
|
|
4769
|
+
if (membership === false) continue;
|
|
4770
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
4771
|
+
if (ongoing === true) return true;
|
|
4772
|
+
if (ongoing === null) indeterminate = true;
|
|
4773
|
+
}
|
|
4774
|
+
return indeterminate ? null : false;
|
|
4775
|
+
}
|
|
3784
4776
|
/**
|
|
3785
4777
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
3786
4778
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -3909,6 +4901,32 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3909
4901
|
}
|
|
3910
4902
|
return messages;
|
|
3911
4903
|
}
|
|
4904
|
+
/**
|
|
4905
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
4906
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
4907
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
4908
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
4909
|
+
*
|
|
4910
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
4911
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
4912
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
4913
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
4914
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
4915
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
4916
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
4917
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
4918
|
+
* stick.
|
|
4919
|
+
*/
|
|
4920
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
4921
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
4922
|
+
this.log({
|
|
4923
|
+
level: "debug",
|
|
4924
|
+
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)}`,
|
|
4925
|
+
conversation_id: conversationId,
|
|
4926
|
+
message_id: messageId
|
|
4927
|
+
});
|
|
4928
|
+
return {};
|
|
4929
|
+
}
|
|
3912
4930
|
/**
|
|
3913
4931
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3914
4932
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3938,7 +4956,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3938
4956
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3939
4957
|
body: JSON.stringify({
|
|
3940
4958
|
status: "processing",
|
|
3941
|
-
|
|
4959
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3942
4960
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3943
4961
|
...title ? { title } : {}
|
|
3944
4962
|
})
|
|
@@ -3987,6 +5005,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3987
5005
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3988
5006
|
body: JSON.stringify({
|
|
3989
5007
|
status: "done",
|
|
5008
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
5009
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
5010
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
5011
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
5012
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3990
5013
|
opencode_session_id: sessionId,
|
|
3991
5014
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3992
5015
|
...title ? { title } : {},
|
|
@@ -4003,16 +5026,31 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4003
5026
|
}
|
|
4004
5027
|
/**
|
|
4005
5028
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
4006
|
-
* when provided (issue #182)
|
|
4007
|
-
* `
|
|
4008
|
-
*
|
|
4009
|
-
*
|
|
5029
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
5030
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
5031
|
+
* session untouched (unused today; kept for API symmetry).
|
|
5032
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
5033
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
5034
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
5035
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
5036
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
5037
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
4010
5038
|
*/
|
|
4011
|
-
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
5039
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
4012
5040
|
const body = { status: "failed" };
|
|
4013
|
-
if (sessionId
|
|
5041
|
+
if (sessionId === null) {
|
|
5042
|
+
body.opencode_session_id = null;
|
|
5043
|
+
} else if (sessionId !== void 0) {
|
|
5044
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
5045
|
+
}
|
|
4014
5046
|
if (error2 !== void 0) body.error = error2;
|
|
4015
5047
|
if (usage) Object.assign(body, usage);
|
|
5048
|
+
if (failure) {
|
|
5049
|
+
body.failure_kind = failure.kind;
|
|
5050
|
+
body.failure_provider_id = failure.providerId;
|
|
5051
|
+
body.failure_model_id = failure.modelId;
|
|
5052
|
+
body.failure_reason = failure.reason;
|
|
5053
|
+
}
|
|
4016
5054
|
await this.callWithRetry(
|
|
4017
5055
|
"marking message as failed",
|
|
4018
5056
|
() => this.fetchImpl(
|
|
@@ -4025,6 +5063,29 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4025
5063
|
)
|
|
4026
5064
|
);
|
|
4027
5065
|
}
|
|
5066
|
+
/**
|
|
5067
|
+
* Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
|
|
5068
|
+
*
|
|
5069
|
+
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
5070
|
+
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
5071
|
+
* to the P1-2b zero-provider check — one extra loopback call to
|
|
5072
|
+
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
5073
|
+
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
5074
|
+
* (`null`/indeterminate) leaves the classification `null`, which produces
|
|
5075
|
+
* today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
|
|
5076
|
+
*/
|
|
5077
|
+
async classifyModelAuthFailure(messages, userMessageId) {
|
|
5078
|
+
const classified = messageFailure(messages, userMessageId);
|
|
5079
|
+
if (classified != null) return classified;
|
|
5080
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5081
|
+
const hasProvider = await hasAnyConfiguredProvider(this.port);
|
|
5082
|
+
return applyZeroProviderFallback(
|
|
5083
|
+
classified,
|
|
5084
|
+
hasProvider,
|
|
5085
|
+
reply?.info?.providerID ?? null,
|
|
5086
|
+
reply?.info?.modelID ?? null
|
|
5087
|
+
);
|
|
5088
|
+
}
|
|
4028
5089
|
/**
|
|
4029
5090
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
4030
5091
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -4201,7 +5262,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4201
5262
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4202
5263
|
console.log(
|
|
4203
5264
|
chalk5.dim(
|
|
4204
|
-
` ${getCliName()} run --
|
|
5265
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4205
5266
|
)
|
|
4206
5267
|
);
|
|
4207
5268
|
}
|
|
@@ -4331,19 +5392,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4331
5392
|
return { agent_id: data.agent_id };
|
|
4332
5393
|
}
|
|
4333
5394
|
return {
|
|
4334
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5395
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
4335
5396
|
};
|
|
4336
5397
|
} catch (error2) {
|
|
4337
5398
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
4338
5399
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
4339
5400
|
}
|
|
4340
5401
|
}
|
|
5402
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
4341
5403
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4342
5404
|
const apiUrl = getApiUrlConfig();
|
|
4343
5405
|
try {
|
|
4344
5406
|
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4345
5407
|
method: "POST",
|
|
4346
|
-
headers: { Authorization: authHeader }
|
|
5408
|
+
headers: { Authorization: authHeader },
|
|
5409
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
4347
5410
|
});
|
|
4348
5411
|
if (!response.ok) {
|
|
4349
5412
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -4354,7 +5417,35 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4354
5417
|
}
|
|
4355
5418
|
return { ok: true };
|
|
4356
5419
|
} catch (error2) {
|
|
4357
|
-
return { ok: false, error:
|
|
5420
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5421
|
+
}
|
|
5422
|
+
}
|
|
5423
|
+
function describeBestEffortError(error2) {
|
|
5424
|
+
const name = error2?.name;
|
|
5425
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5426
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5427
|
+
}
|
|
5428
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5429
|
+
}
|
|
5430
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5431
|
+
try {
|
|
5432
|
+
const apiUrl = getApiUrlConfig();
|
|
5433
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5434
|
+
method: "POST",
|
|
5435
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5436
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5437
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5438
|
+
});
|
|
5439
|
+
if (!response.ok) {
|
|
5440
|
+
const serverMessage = await readErrorMessage(response);
|
|
5441
|
+
return {
|
|
5442
|
+
ok: false,
|
|
5443
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5444
|
+
};
|
|
5445
|
+
}
|
|
5446
|
+
return { ok: true };
|
|
5447
|
+
} catch (error2) {
|
|
5448
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
4358
5449
|
}
|
|
4359
5450
|
}
|
|
4360
5451
|
async function getAgentInfo(agentId, authHeader) {
|
|
@@ -4404,6 +5495,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
4404
5495
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
4405
5496
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4406
5497
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5498
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
4407
5499
|
function resolveLogLevel(options) {
|
|
4408
5500
|
const accepted = Object.keys(LOG_LEVELS);
|
|
4409
5501
|
const validate = (value, source) => {
|
|
@@ -4427,6 +5519,34 @@ function resolveLogLevel(options) {
|
|
|
4427
5519
|
}
|
|
4428
5520
|
return "info";
|
|
4429
5521
|
}
|
|
5522
|
+
function resolveFileSyncDirectories(raw, homeDir) {
|
|
5523
|
+
const directories = [];
|
|
5524
|
+
for (const entry of raw ?? []) {
|
|
5525
|
+
const trimmed = entry.trim();
|
|
5526
|
+
if (trimmed === "") {
|
|
5527
|
+
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5528
|
+
}
|
|
5529
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
|
|
5530
|
+
if (!isAbsolute2(expanded)) {
|
|
5531
|
+
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5532
|
+
}
|
|
5533
|
+
const normalized = resolvePath(expanded);
|
|
5534
|
+
if (parse(normalized).root === normalized) {
|
|
5535
|
+
throw new Error(
|
|
5536
|
+
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
5537
|
+
);
|
|
5538
|
+
}
|
|
5539
|
+
if (!directories.includes(normalized)) {
|
|
5540
|
+
directories.push(normalized);
|
|
5541
|
+
}
|
|
5542
|
+
}
|
|
5543
|
+
if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
|
|
5544
|
+
throw new Error(
|
|
5545
|
+
`--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
|
|
5546
|
+
);
|
|
5547
|
+
}
|
|
5548
|
+
return directories;
|
|
5549
|
+
}
|
|
4430
5550
|
function meetsThreshold(state, level) {
|
|
4431
5551
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4432
5552
|
}
|
|
@@ -4548,18 +5668,29 @@ async function handleAuthError(state, error2) {
|
|
|
4548
5668
|
async function driveChannels(state, driver) {
|
|
4549
5669
|
let idlePolls = 0;
|
|
4550
5670
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5671
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4551
5672
|
while (state.running) {
|
|
4552
5673
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4553
5674
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4554
5675
|
if (state.interactive) displayStatus(state);
|
|
4555
5676
|
await state.connection.reconnectPromise;
|
|
4556
5677
|
}
|
|
5678
|
+
const carriedOverFileSync = driver.fileSyncActivity().inFlight;
|
|
5679
|
+
void driver.syncPendingFiles().catch(
|
|
5680
|
+
(error2) => logActivity(state, {
|
|
5681
|
+
type: "error",
|
|
5682
|
+
error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5683
|
+
})
|
|
5684
|
+
);
|
|
4557
5685
|
try {
|
|
4558
5686
|
const processed = await driver.drainPending();
|
|
4559
5687
|
state.messageCount += processed;
|
|
4560
5688
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4561
5689
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4562
|
-
|
|
5690
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5691
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
5692
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
5693
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4563
5694
|
idlePolls = 0;
|
|
4564
5695
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4565
5696
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4588,7 +5719,7 @@ async function driveChannels(state, driver) {
|
|
|
4588
5719
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4589
5720
|
if (state.interactive) displayStatus(state);
|
|
4590
5721
|
}
|
|
4591
|
-
await new Promise((
|
|
5722
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4592
5723
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4593
5724
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4594
5725
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4691,7 +5822,18 @@ async function notifyOffline(state) {
|
|
|
4691
5822
|
if (state.interactive) displayStatus(state);
|
|
4692
5823
|
}
|
|
4693
5824
|
}
|
|
5825
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
5826
|
+
const startedAt = Date.now();
|
|
5827
|
+
try {
|
|
5828
|
+
return await run2();
|
|
5829
|
+
} finally {
|
|
5830
|
+
const elapsedMs = Date.now() - startedAt;
|
|
5831
|
+
durations[name] = elapsedMs;
|
|
5832
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
5833
|
+
}
|
|
5834
|
+
}
|
|
4694
5835
|
async function cleanup(state, opts = {}) {
|
|
5836
|
+
const durations = {};
|
|
4695
5837
|
state.running = false;
|
|
4696
5838
|
for (const timer of state.sessionCleanupTimers) {
|
|
4697
5839
|
clearInterval(timer);
|
|
@@ -4705,7 +5847,13 @@ async function cleanup(state, opts = {}) {
|
|
|
4705
5847
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4706
5848
|
displayStatus(state);
|
|
4707
5849
|
}
|
|
4708
|
-
const
|
|
5850
|
+
const driver = state.channelDriver;
|
|
5851
|
+
const settled = await timeShutdownPhase(
|
|
5852
|
+
state,
|
|
5853
|
+
durations,
|
|
5854
|
+
"drain",
|
|
5855
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
5856
|
+
);
|
|
4709
5857
|
if (!settled) {
|
|
4710
5858
|
logActivity(state, {
|
|
4711
5859
|
type: "info",
|
|
@@ -4714,13 +5862,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4714
5862
|
if (state.interactive) displayStatus(state);
|
|
4715
5863
|
}
|
|
4716
5864
|
}
|
|
4717
|
-
await notifyOffline(state);
|
|
5865
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
4718
5866
|
if (state.connection) {
|
|
4719
|
-
state.connection
|
|
5867
|
+
const connection = state.connection;
|
|
5868
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
4720
5869
|
state.connection = null;
|
|
4721
5870
|
}
|
|
4722
5871
|
if (state.opencodeProcess) {
|
|
4723
|
-
|
|
5872
|
+
const opencodeProcess = state.opencodeProcess;
|
|
5873
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
4724
5874
|
if (state.interactive) {
|
|
4725
5875
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
4726
5876
|
displayStatus(state);
|
|
@@ -4729,12 +5879,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4729
5879
|
}
|
|
4730
5880
|
state.opencodeProcess = null;
|
|
4731
5881
|
}
|
|
5882
|
+
return durations;
|
|
4732
5883
|
}
|
|
4733
5884
|
async function run(options) {
|
|
4734
5885
|
const interactive = isInteractive(options.json);
|
|
4735
5886
|
let logLevel;
|
|
5887
|
+
let fileSyncDirectories;
|
|
4736
5888
|
try {
|
|
4737
5889
|
logLevel = resolveLogLevel(options);
|
|
5890
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
|
|
4738
5891
|
} catch (error2) {
|
|
4739
5892
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4740
5893
|
if (options.json) {
|
|
@@ -4769,6 +5922,11 @@ async function run(options) {
|
|
|
4769
5922
|
sessionCleanupTimers: [],
|
|
4770
5923
|
authHeader: ""
|
|
4771
5924
|
};
|
|
5925
|
+
if (fileSyncDirectories.length > 0) {
|
|
5926
|
+
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5927
|
+
} else {
|
|
5928
|
+
log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
|
|
5929
|
+
}
|
|
4772
5930
|
if (!options.runner && options.agent) {
|
|
4773
5931
|
telemetry.info(
|
|
4774
5932
|
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
@@ -4792,14 +5950,38 @@ async function run(options) {
|
|
|
4792
5950
|
const handleSignal = async () => {
|
|
4793
5951
|
if (state.shuttingDown) return;
|
|
4794
5952
|
state.shuttingDown = true;
|
|
5953
|
+
const shutdownStartedAt = Date.now();
|
|
4795
5954
|
if (state.interactive) {
|
|
4796
5955
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
4797
5956
|
displayStatus(state);
|
|
4798
5957
|
} else {
|
|
4799
5958
|
log2(state, "Shutting down...");
|
|
4800
5959
|
}
|
|
4801
|
-
await cleanup(state, { graceful: true });
|
|
4802
|
-
|
|
5960
|
+
const durations = await cleanup(state, { graceful: true });
|
|
5961
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
5962
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
5963
|
+
let timer;
|
|
5964
|
+
const flushed = shutdownTelemetry().then(
|
|
5965
|
+
() => true,
|
|
5966
|
+
(error2) => {
|
|
5967
|
+
log2(
|
|
5968
|
+
state,
|
|
5969
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
5970
|
+
"warn"
|
|
5971
|
+
);
|
|
5972
|
+
return true;
|
|
5973
|
+
}
|
|
5974
|
+
);
|
|
5975
|
+
const timedOut = new Promise((resolve3) => {
|
|
5976
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
5977
|
+
});
|
|
5978
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
5979
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
5980
|
+
}
|
|
5981
|
+
clearTimeout(timer);
|
|
5982
|
+
});
|
|
5983
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
5984
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
4803
5985
|
process.exit(0);
|
|
4804
5986
|
};
|
|
4805
5987
|
process.on("SIGINT", handleSignal);
|
|
@@ -4913,6 +6095,21 @@ async function run(options) {
|
|
|
4913
6095
|
}
|
|
4914
6096
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
4915
6097
|
state.agentName = validation.agent.name;
|
|
6098
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
6099
|
+
if (microvmId) {
|
|
6100
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
6101
|
+
if (reported.ok) {
|
|
6102
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
6103
|
+
} else {
|
|
6104
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
6105
|
+
log2(state, message, "warn");
|
|
6106
|
+
if (state.interactive && !state.json) {
|
|
6107
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6108
|
+
}
|
|
6109
|
+
}
|
|
6110
|
+
} else {
|
|
6111
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6112
|
+
}
|
|
4916
6113
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
4917
6114
|
try {
|
|
4918
6115
|
const oc = await ensureOpenCodeRunning({
|
|
@@ -4961,6 +6158,10 @@ async function run(options) {
|
|
|
4961
6158
|
getAuthHeader: () => state.authHeader,
|
|
4962
6159
|
conversationFilter: state.conversationFilter,
|
|
4963
6160
|
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
6161
|
+
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
6162
|
+
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
6163
|
+
fileSyncDirectories,
|
|
6164
|
+
homeDir: homedir2(),
|
|
4964
6165
|
log: (entry) => (
|
|
4965
6166
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4966
6167
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4987,6 +6188,18 @@ async function run(options) {
|
|
|
4987
6188
|
type: "info",
|
|
4988
6189
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
4989
6190
|
});
|
|
6191
|
+
if (options.tunnelReadyFile) {
|
|
6192
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6193
|
+
if (marker.ok) {
|
|
6194
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6195
|
+
} else {
|
|
6196
|
+
log2(
|
|
6197
|
+
state,
|
|
6198
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6199
|
+
"error"
|
|
6200
|
+
);
|
|
6201
|
+
}
|
|
6202
|
+
}
|
|
4990
6203
|
emitAgentConnected(state.agentId, {
|
|
4991
6204
|
port: state.port,
|
|
4992
6205
|
cli_version: getCliVersion(),
|
|
@@ -5042,6 +6255,12 @@ async function run(options) {
|
|
|
5042
6255
|
onDrainPing: () => {
|
|
5043
6256
|
if (!state.running) return;
|
|
5044
6257
|
logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
|
|
6258
|
+
void channelDriver.syncPendingFiles().catch(
|
|
6259
|
+
(error2) => logActivity(state, {
|
|
6260
|
+
type: "error",
|
|
6261
|
+
error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
6262
|
+
})
|
|
6263
|
+
);
|
|
5045
6264
|
channelDriver.drainPending().then((processed) => {
|
|
5046
6265
|
if (processed > 0) {
|
|
5047
6266
|
state.messageCount += processed;
|
|
@@ -5125,7 +6344,10 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
5125
6344
|
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);
|
|
5126
6345
|
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 }));
|
|
5127
6346
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
5128
|
-
program.command("run").description("Connect to Evident and process messages").option("
|
|
6347
|
+
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(
|
|
6348
|
+
"-a, --agent [id]",
|
|
6349
|
+
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
6350
|
+
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
5129
6351
|
"--log-level <level>",
|
|
5130
6352
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
5131
6353
|
).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(
|
|
@@ -5137,6 +6359,14 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5137
6359
|
).option(
|
|
5138
6360
|
"--session-cleanup-interval <duration>",
|
|
5139
6361
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6362
|
+
).option(
|
|
6363
|
+
"--enable-file-sync-to <dir>",
|
|
6364
|
+
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
6365
|
+
(value, previous) => previous.concat([value]),
|
|
6366
|
+
[]
|
|
6367
|
+
).option(
|
|
6368
|
+
"--tunnel-ready-file <path>",
|
|
6369
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
5140
6370
|
).action(
|
|
5141
6371
|
(options) => {
|
|
5142
6372
|
run({
|
|
@@ -5153,7 +6383,11 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5153
6383
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
5154
6384
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
5155
6385
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
5156
|
-
sessionCleanupInterval: options.sessionCleanupInterval
|
|
6386
|
+
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6387
|
+
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6388
|
+
// resolveFileSyncDirectories.
|
|
6389
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6390
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
5157
6391
|
});
|
|
5158
6392
|
}
|
|
5159
6393
|
);
|