@evident-ai/cli 3.1.1-dev.993411a → 3.1.1-dev.9e90301
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 +28 -11
- package/dist/index.js +1980 -239
- 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,25 @@ async function deviceFlowLogin(options) {
|
|
|
373
417
|
}
|
|
374
418
|
async function tokenLogin() {
|
|
375
419
|
console.log("Token login mode.");
|
|
376
|
-
console.log("
|
|
420
|
+
console.log("Create a token under Settings \u2192 CLI tokens in the dashboard, then paste it below.");
|
|
421
|
+
console.log(
|
|
422
|
+
"(Alternatively, run `evident login` on a machine with a browser, or set EVIDENT_TOKEN for CI.)"
|
|
423
|
+
);
|
|
377
424
|
blank();
|
|
378
425
|
process.stdout.write("Paste token: ");
|
|
379
|
-
const token = await new Promise((
|
|
426
|
+
const token = await new Promise((resolve3) => {
|
|
380
427
|
let data = "";
|
|
381
428
|
process.stdin.setEncoding("utf8");
|
|
382
429
|
process.stdin.on("data", (chunk) => {
|
|
383
430
|
data += chunk;
|
|
384
431
|
});
|
|
385
432
|
process.stdin.on("end", () => {
|
|
386
|
-
|
|
433
|
+
resolve3(data.trim());
|
|
387
434
|
});
|
|
388
435
|
if (process.stdin.isTTY) {
|
|
389
436
|
process.stdin.once("data", (chunk) => {
|
|
390
437
|
process.stdin.pause();
|
|
391
|
-
|
|
438
|
+
resolve3(chunk.toString().trim());
|
|
392
439
|
});
|
|
393
440
|
process.stdin.resume();
|
|
394
441
|
}
|
|
@@ -397,13 +444,22 @@ async function tokenLogin() {
|
|
|
397
444
|
printError("No token provided.");
|
|
398
445
|
process.exit(1);
|
|
399
446
|
}
|
|
447
|
+
await validateAndStoreToken(token);
|
|
448
|
+
}
|
|
449
|
+
async function validateAndStoreToken(token) {
|
|
400
450
|
const spinner = ora("Validating token...").start();
|
|
401
451
|
try {
|
|
402
|
-
const result = await api.
|
|
452
|
+
const result = await api.get("/me", {
|
|
453
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
454
|
+
});
|
|
455
|
+
if (!result.user) {
|
|
456
|
+
throw new Error(
|
|
457
|
+
"This token is not a user login (e.g. a runner key). Paste a CLI token instead."
|
|
458
|
+
);
|
|
459
|
+
}
|
|
403
460
|
await storeToken({
|
|
404
461
|
token,
|
|
405
|
-
user: result.user
|
|
406
|
-
expiresAt: result.expires_at
|
|
462
|
+
user: { email: result.user.email }
|
|
407
463
|
});
|
|
408
464
|
spinner.stop();
|
|
409
465
|
printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
|
|
@@ -423,9 +479,22 @@ async function login(options) {
|
|
|
423
479
|
}
|
|
424
480
|
|
|
425
481
|
// src/commands/logout.ts
|
|
482
|
+
function describeFailure(failure) {
|
|
483
|
+
if (failure.type === "enumerate") {
|
|
484
|
+
return `could not list stored keychain entries (${failure.error.message})`;
|
|
485
|
+
}
|
|
486
|
+
return `${failure.account} (${failure.error.message})`;
|
|
487
|
+
}
|
|
426
488
|
async function logout(options = {}) {
|
|
427
489
|
if (options.all) {
|
|
428
|
-
await deleteToken({ all: true });
|
|
490
|
+
const result = await deleteToken({ all: true });
|
|
491
|
+
if (result.failures.length > 0) {
|
|
492
|
+
printError(
|
|
493
|
+
`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.`
|
|
494
|
+
);
|
|
495
|
+
process.exitCode = 1;
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
429
498
|
printSuccess("Logged out of all endpoints.");
|
|
430
499
|
return;
|
|
431
500
|
}
|
|
@@ -450,7 +519,9 @@ async function whoami() {
|
|
|
450
519
|
blank();
|
|
451
520
|
console.log(keyValue("Endpoint", apiUrl));
|
|
452
521
|
console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
|
|
453
|
-
|
|
522
|
+
if (credentials2.user.id) {
|
|
523
|
+
console.log(keyValue("User ID", credentials2.user.id));
|
|
524
|
+
}
|
|
454
525
|
if (credentials2.expiresAt) {
|
|
455
526
|
const expiresAt = new Date(credentials2.expiresAt);
|
|
456
527
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -466,10 +537,125 @@ async function whoami() {
|
|
|
466
537
|
blank();
|
|
467
538
|
}
|
|
468
539
|
|
|
540
|
+
// src/lib/claude-usage.ts
|
|
541
|
+
import { execFileSync } from "child_process";
|
|
542
|
+
import { readFileSync } from "fs";
|
|
543
|
+
import { homedir } from "os";
|
|
544
|
+
import { join } from "path";
|
|
545
|
+
var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
546
|
+
var KEYCHAIN_SERVICE = "Claude Code-credentials";
|
|
547
|
+
function parseClaudeCliCredentials(raw) {
|
|
548
|
+
let parsed;
|
|
549
|
+
try {
|
|
550
|
+
parsed = JSON.parse(raw);
|
|
551
|
+
} catch {
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
const data = parsed.claudeAiOauth ?? parsed;
|
|
555
|
+
const creds = data;
|
|
556
|
+
if (typeof creds.accessToken !== "string" || typeof creds.expiresAt !== "number") {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
return { accessToken: creds.accessToken, expiresAt: creds.expiresAt };
|
|
560
|
+
}
|
|
561
|
+
function readClaudeCliCredentials() {
|
|
562
|
+
if (process.platform === "darwin") {
|
|
563
|
+
try {
|
|
564
|
+
const raw = execFileSync(
|
|
565
|
+
"/usr/bin/security",
|
|
566
|
+
["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
|
|
567
|
+
{ encoding: "utf-8", timeout: 2e3, stdio: ["pipe", "pipe", "ignore"] }
|
|
568
|
+
);
|
|
569
|
+
return parseClaudeCliCredentials(raw);
|
|
570
|
+
} catch {
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
try {
|
|
575
|
+
const raw = readFileSync(join(homedir(), ".claude", ".credentials.json"), "utf-8");
|
|
576
|
+
return parseClaudeCliCredentials(raw);
|
|
577
|
+
} catch {
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
var ClaudeUsageError = class extends Error {
|
|
582
|
+
constructor(message, reason) {
|
|
583
|
+
super(message);
|
|
584
|
+
this.reason = reason;
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
function isLocalCredentialProblem(err) {
|
|
588
|
+
return err instanceof ClaudeUsageError && (err.reason === "no_credentials" || err.reason === "credentials_expired");
|
|
589
|
+
}
|
|
590
|
+
function toWindow(value) {
|
|
591
|
+
if (!value || typeof value !== "object") {
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
const window = value;
|
|
595
|
+
if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
return { utilization: window.utilization, resetsAt: window.resets_at };
|
|
599
|
+
}
|
|
600
|
+
async function getClaudeUsage() {
|
|
601
|
+
const credentials2 = readClaudeCliCredentials();
|
|
602
|
+
if (!credentials2) {
|
|
603
|
+
throw new ClaudeUsageError(
|
|
604
|
+
"No local Claude Code login found. Run `claude` once to sign in with your Claude subscription.",
|
|
605
|
+
"no_credentials"
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
if (credentials2.expiresAt < Date.now()) {
|
|
609
|
+
throw new ClaudeUsageError(
|
|
610
|
+
"Claude Code credentials have expired. Run `claude` to refresh them.",
|
|
611
|
+
"credentials_expired"
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
const res = await fetch(CLAUDE_USAGE_URL, {
|
|
615
|
+
headers: {
|
|
616
|
+
Authorization: `Bearer ${credentials2.accessToken}`,
|
|
617
|
+
"Content-Type": "application/json",
|
|
618
|
+
"anthropic-version": "2023-06-01"
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
if (!res.ok) {
|
|
622
|
+
throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
|
|
623
|
+
}
|
|
624
|
+
const body = await res.json();
|
|
625
|
+
return {
|
|
626
|
+
fiveHour: toWindow(body.five_hour),
|
|
627
|
+
sevenDay: toWindow(body.seven_day)
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// src/commands/claude-usage.ts
|
|
632
|
+
function formatWindow(label, window) {
|
|
633
|
+
if (!window) {
|
|
634
|
+
return keyValue(label, "not available for this plan");
|
|
635
|
+
}
|
|
636
|
+
const resetsAt = new Date(window.resetsAt);
|
|
637
|
+
return keyValue(label, `${window.utilization}% used, resets ${resetsAt.toLocaleString()}`);
|
|
638
|
+
}
|
|
639
|
+
async function claudeUsage() {
|
|
640
|
+
try {
|
|
641
|
+
const usage = await getClaudeUsage();
|
|
642
|
+
blank();
|
|
643
|
+
console.log(formatWindow("5-hour session", usage.fiveHour));
|
|
644
|
+
console.log(formatWindow("7-day", usage.sevenDay));
|
|
645
|
+
blank();
|
|
646
|
+
} catch (err) {
|
|
647
|
+
if (err instanceof ClaudeUsageError) {
|
|
648
|
+
printError(err.message);
|
|
649
|
+
process.exit(1);
|
|
650
|
+
}
|
|
651
|
+
throw err;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
469
655
|
// src/commands/run.ts
|
|
656
|
+
import { homedir as homedir3 } from "os";
|
|
657
|
+
import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
|
|
470
658
|
import chalk6 from "chalk";
|
|
471
|
-
import ora3 from "ora";
|
|
472
|
-
import { select as select3 } from "@inquirer/prompts";
|
|
473
659
|
|
|
474
660
|
// ../../packages/types/src/telemetry/index.ts
|
|
475
661
|
var TelemetryEventTypes = {
|
|
@@ -478,13 +664,20 @@ var TelemetryEventTypes = {
|
|
|
478
664
|
AGENT_DISCONNECTED: "agent.disconnected",
|
|
479
665
|
AGENT_MESSAGE_PROCESSING: "agent.message_processing",
|
|
480
666
|
AGENT_MESSAGE_DONE: "agent.message_done",
|
|
481
|
-
AGENT_MESSAGE_FAILED: "agent.message_failed"
|
|
667
|
+
AGENT_MESSAGE_FAILED: "agent.message_failed",
|
|
668
|
+
// A `warn`/`error` runner-side log line forwarded server-side for
|
|
669
|
+
// observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
|
|
670
|
+
RUNNER_ACTIVITY: "runner.activity"
|
|
482
671
|
};
|
|
483
672
|
|
|
484
673
|
// ../../packages/types/src/tunnel/index.ts
|
|
485
674
|
var MAX_FRAME_BYTES = 256 * 1024;
|
|
486
675
|
var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
|
|
487
676
|
|
|
677
|
+
// ../../packages/types/src/runner-files.ts
|
|
678
|
+
var MAX_FILE_PUSH_BYTES = 64 * 1024;
|
|
679
|
+
var MAX_FILE_SYNC_DIRECTORIES = 16;
|
|
680
|
+
|
|
488
681
|
// ../../packages/types/src/logging/index.ts
|
|
489
682
|
var CORRELATION_ID_HEADER = "x-evident-correlation-id";
|
|
490
683
|
function log(level, event, fields) {
|
|
@@ -499,6 +692,12 @@ function log(level, event, fields) {
|
|
|
499
692
|
);
|
|
500
693
|
}
|
|
501
694
|
}
|
|
695
|
+
function errorFields(err) {
|
|
696
|
+
if (err instanceof Error) {
|
|
697
|
+
return { error: err.message, error_name: err.name };
|
|
698
|
+
}
|
|
699
|
+
return { error: String(err) };
|
|
700
|
+
}
|
|
502
701
|
function stripQuery(url) {
|
|
503
702
|
try {
|
|
504
703
|
return new URL(url).pathname;
|
|
@@ -508,6 +707,10 @@ function stripQuery(url) {
|
|
|
508
707
|
}
|
|
509
708
|
}
|
|
510
709
|
|
|
710
|
+
// src/commands/run.ts
|
|
711
|
+
import ora3 from "ora";
|
|
712
|
+
import { select as select3 } from "@inquirer/prompts";
|
|
713
|
+
|
|
511
714
|
// src/lib/telemetry.ts
|
|
512
715
|
var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
513
716
|
function getCliVersion() {
|
|
@@ -519,6 +722,13 @@ var isShuttingDown = false;
|
|
|
519
722
|
var FLUSH_INTERVAL_MS = 5e3;
|
|
520
723
|
var MAX_BUFFER_SIZE = 50;
|
|
521
724
|
var FLUSH_TIMEOUT_MS = 3e3;
|
|
725
|
+
var authProvider = null;
|
|
726
|
+
function setTelemetryAuthProvider(provider) {
|
|
727
|
+
authProvider = provider;
|
|
728
|
+
}
|
|
729
|
+
var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
|
|
730
|
+
var lastFlushFailureLoggedAt = 0;
|
|
731
|
+
var suppressedFlushFailureCount = 0;
|
|
522
732
|
function logEvent(eventType, options = {}) {
|
|
523
733
|
const event = {
|
|
524
734
|
event_type: eventType,
|
|
@@ -553,9 +763,16 @@ async function flushEvents() {
|
|
|
553
763
|
flushTimeout = null;
|
|
554
764
|
}
|
|
555
765
|
try {
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
|
|
766
|
+
const providerContext = authProvider?.();
|
|
767
|
+
let authHeader;
|
|
768
|
+
if (providerContext?.authHeader) {
|
|
769
|
+
authHeader = providerContext.authHeader;
|
|
770
|
+
} else {
|
|
771
|
+
const credentials2 = await getToken();
|
|
772
|
+
if (!credentials2) {
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
authHeader = `Bearer ${credentials2.token}`;
|
|
559
776
|
}
|
|
560
777
|
const apiUrl = getApiUrlConfig();
|
|
561
778
|
const controller = new AbortController();
|
|
@@ -570,7 +787,7 @@ async function flushEvents() {
|
|
|
570
787
|
method: "POST",
|
|
571
788
|
headers: {
|
|
572
789
|
"Content-Type": "application/json",
|
|
573
|
-
Authorization:
|
|
790
|
+
Authorization: authHeader
|
|
574
791
|
},
|
|
575
792
|
body: JSON.stringify(request),
|
|
576
793
|
signal: controller.signal
|
|
@@ -582,8 +799,15 @@ async function flushEvents() {
|
|
|
582
799
|
clearTimeout(timeout);
|
|
583
800
|
}
|
|
584
801
|
} catch (error2) {
|
|
585
|
-
|
|
586
|
-
|
|
802
|
+
const now = Date.now();
|
|
803
|
+
if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
|
|
804
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
805
|
+
const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
|
|
806
|
+
console.error(`Telemetry flush error: ${message}${suffix}`);
|
|
807
|
+
lastFlushFailureLoggedAt = now;
|
|
808
|
+
suppressedFlushFailureCount = 0;
|
|
809
|
+
} else {
|
|
810
|
+
suppressedFlushFailureCount++;
|
|
587
811
|
}
|
|
588
812
|
}
|
|
589
813
|
}
|
|
@@ -652,6 +876,69 @@ var EventTypes = {
|
|
|
652
876
|
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
653
877
|
};
|
|
654
878
|
|
|
879
|
+
// src/lib/runner-activity-telemetry.ts
|
|
880
|
+
var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
|
|
881
|
+
var SEVERITY_BY_LEVEL = {
|
|
882
|
+
warn: "warning",
|
|
883
|
+
error: "error"
|
|
884
|
+
};
|
|
885
|
+
var MAX_MESSAGE_LENGTH = 500;
|
|
886
|
+
var TRUNCATION_MARKER = "\u2026";
|
|
887
|
+
function redact(message) {
|
|
888
|
+
return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
889
|
+
}
|
|
890
|
+
function truncate(message) {
|
|
891
|
+
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
892
|
+
return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
|
|
893
|
+
}
|
|
894
|
+
var RATE_LIMIT_WINDOW_MS = 6e4;
|
|
895
|
+
var RATE_LIMIT_MAX_EVENTS = 30;
|
|
896
|
+
var windowStartedAt = 0;
|
|
897
|
+
var windowCount = 0;
|
|
898
|
+
var windowDroppedCount = 0;
|
|
899
|
+
function admitUnderRateLimit(now) {
|
|
900
|
+
if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
|
|
901
|
+
if (windowDroppedCount > 0) {
|
|
902
|
+
console.error(
|
|
903
|
+
`[runner-activity-telemetry] rate cap reached: dropped ${windowDroppedCount} ${windowDroppedCount === 1 ? "entry" : "entries"} in the last ${RATE_LIMIT_WINDOW_MS / 1e3}s (cap ${RATE_LIMIT_MAX_EVENTS}/min)`
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
windowStartedAt = now;
|
|
907
|
+
windowCount = 0;
|
|
908
|
+
windowDroppedCount = 0;
|
|
909
|
+
}
|
|
910
|
+
if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
911
|
+
windowDroppedCount++;
|
|
912
|
+
if (windowDroppedCount === 1) {
|
|
913
|
+
console.error(
|
|
914
|
+
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
return false;
|
|
918
|
+
}
|
|
919
|
+
windowCount++;
|
|
920
|
+
return true;
|
|
921
|
+
}
|
|
922
|
+
function forwardRunnerActivity(entry, context) {
|
|
923
|
+
try {
|
|
924
|
+
if (!FORWARDED_LEVELS.has(entry.level)) return;
|
|
925
|
+
if (!context.agentId || !context.authHeader) return;
|
|
926
|
+
if (!admitUnderRateLimit(Date.now())) return;
|
|
927
|
+
const rawMessage = entry.error ?? entry.message ?? "";
|
|
928
|
+
const message = truncate(redact(rawMessage));
|
|
929
|
+
logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
|
|
930
|
+
severity: SEVERITY_BY_LEVEL[entry.level],
|
|
931
|
+
message,
|
|
932
|
+
metadata: { source: "cli.run" },
|
|
933
|
+
agentId: context.agentId
|
|
934
|
+
});
|
|
935
|
+
} catch (err) {
|
|
936
|
+
console.error(
|
|
937
|
+
`[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
|
|
938
|
+
);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
|
|
655
942
|
// src/lib/auth.ts
|
|
656
943
|
async function getAuthCredentials() {
|
|
657
944
|
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
@@ -719,7 +1006,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
719
1006
|
if (health.healthy) {
|
|
720
1007
|
return health;
|
|
721
1008
|
}
|
|
722
|
-
await new Promise((
|
|
1009
|
+
await new Promise((resolve3) => setTimeout(resolve3, 1e3));
|
|
723
1010
|
}
|
|
724
1011
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
725
1012
|
}
|
|
@@ -734,7 +1021,7 @@ function buildOpenCodeVersionWarning(version2) {
|
|
|
734
1021
|
if (isQueueValidatedVersion(version2)) return null;
|
|
735
1022
|
const detected = version2 ? `v${version2}` : "unknown";
|
|
736
1023
|
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
737
|
-
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack
|
|
1024
|
+
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
|
|
738
1025
|
}
|
|
739
1026
|
|
|
740
1027
|
// src/lib/opencode/process.ts
|
|
@@ -1026,6 +1313,12 @@ async function promptOpenCodeInstall(interactive) {
|
|
|
1026
1313
|
return action;
|
|
1027
1314
|
}
|
|
1028
1315
|
|
|
1316
|
+
// src/lib/opencode/provider-check.ts
|
|
1317
|
+
function buildNoProviderWarning(hasProvider) {
|
|
1318
|
+
if (hasProvider !== false) return null;
|
|
1319
|
+
return "Warning: opencode has no authenticated model provider configured, so it won't be able to answer prompts. Run `opencode auth login` to set one up (see https://opencode.ai for details).";
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1029
1322
|
// src/lib/opencode/session.ts
|
|
1030
1323
|
function opencodeBase(port) {
|
|
1031
1324
|
return `http://127.0.0.1:${port}`;
|
|
@@ -1228,6 +1521,11 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
1228
1521
|
}
|
|
1229
1522
|
const entry = provider.models[modelId];
|
|
1230
1523
|
if (!entry || typeof entry !== "object") return null;
|
|
1524
|
+
if (entry.capabilities && typeof entry.capabilities === "object") {
|
|
1525
|
+
if (typeof entry.capabilities.attachment === "boolean") {
|
|
1526
|
+
return entry.capabilities.attachment;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1231
1529
|
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
1232
1530
|
} catch (err) {
|
|
1233
1531
|
console.error(
|
|
@@ -1256,6 +1554,16 @@ async function buildFileParts(attachments, capable) {
|
|
|
1256
1554
|
);
|
|
1257
1555
|
dataUrl = null;
|
|
1258
1556
|
}
|
|
1557
|
+
if (dataUrl !== null && typeof dataUrl === "object") {
|
|
1558
|
+
outcomes.push({
|
|
1559
|
+
index: a.index,
|
|
1560
|
+
mime: a.mime,
|
|
1561
|
+
filename: a.filename,
|
|
1562
|
+
status: "failed",
|
|
1563
|
+
reason: "needs_reauth"
|
|
1564
|
+
});
|
|
1565
|
+
continue;
|
|
1566
|
+
}
|
|
1259
1567
|
if (dataUrl == null) {
|
|
1260
1568
|
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1261
1569
|
continue;
|
|
@@ -1337,7 +1645,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
1337
1645
|
}
|
|
1338
1646
|
}
|
|
1339
1647
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
1340
|
-
await new Promise((
|
|
1648
|
+
await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
|
|
1341
1649
|
}
|
|
1342
1650
|
}
|
|
1343
1651
|
return null;
|
|
@@ -1465,6 +1773,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1465
1773
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1466
1774
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1467
1775
|
}
|
|
1776
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1777
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1778
|
+
}
|
|
1468
1779
|
function messageError(messages, userMessageId) {
|
|
1469
1780
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1470
1781
|
const error2 = errorOf(reply);
|
|
@@ -1478,12 +1789,79 @@ function messageError(messages, userMessageId) {
|
|
|
1478
1789
|
}
|
|
1479
1790
|
return "The agent run failed.";
|
|
1480
1791
|
}
|
|
1792
|
+
function messageFailure(messages, userMessageId) {
|
|
1793
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1794
|
+
const error2 = errorOf(reply);
|
|
1795
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
1796
|
+
const e = error2;
|
|
1797
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
1798
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
1799
|
+
if (e.name === "ProviderAuthError") {
|
|
1800
|
+
const data = e.data;
|
|
1801
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
1802
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
1803
|
+
}
|
|
1804
|
+
if (e.name === "APIError") {
|
|
1805
|
+
const data = e.data;
|
|
1806
|
+
const statusCode = data?.statusCode;
|
|
1807
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
1808
|
+
return {
|
|
1809
|
+
kind: "model_auth",
|
|
1810
|
+
providerId: replyProviderId,
|
|
1811
|
+
modelId: replyModelId,
|
|
1812
|
+
reason: "rejected"
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
return null;
|
|
1817
|
+
}
|
|
1818
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
1819
|
+
if (classified != null) return classified;
|
|
1820
|
+
if (hasConfiguredProvider !== false) return null;
|
|
1821
|
+
return {
|
|
1822
|
+
kind: "model_auth",
|
|
1823
|
+
providerId: replyProviderId,
|
|
1824
|
+
modelId: replyModelId,
|
|
1825
|
+
reason: "missing"
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1481
1828
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1482
1829
|
if (!messages || messages.length === 0) return false;
|
|
1483
1830
|
return messages.some(
|
|
1484
1831
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1485
1832
|
);
|
|
1486
1833
|
}
|
|
1834
|
+
async function hasAnyConfiguredProvider(port) {
|
|
1835
|
+
try {
|
|
1836
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1837
|
+
if (!res.ok) {
|
|
1838
|
+
console.error(
|
|
1839
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1840
|
+
);
|
|
1841
|
+
return null;
|
|
1842
|
+
}
|
|
1843
|
+
const body = await res.json();
|
|
1844
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1845
|
+
console.error(
|
|
1846
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
1847
|
+
);
|
|
1848
|
+
return null;
|
|
1849
|
+
}
|
|
1850
|
+
const defaults2 = body.default;
|
|
1851
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
1852
|
+
console.error(
|
|
1853
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
1854
|
+
);
|
|
1855
|
+
return null;
|
|
1856
|
+
}
|
|
1857
|
+
return Object.keys(defaults2).length > 0;
|
|
1858
|
+
} catch (err) {
|
|
1859
|
+
console.error(
|
|
1860
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1861
|
+
);
|
|
1862
|
+
return null;
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1487
1865
|
|
|
1488
1866
|
// src/lib/opencode/session-cleanup.ts
|
|
1489
1867
|
var DURATION_UNIT_MS = {
|
|
@@ -1642,10 +2020,11 @@ var StreamForwarder = class {
|
|
|
1642
2020
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1643
2021
|
*/
|
|
1644
2022
|
abortAll() {
|
|
1645
|
-
for (const stream of this.inflight.
|
|
2023
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1646
2024
|
try {
|
|
1647
2025
|
stream.abort();
|
|
1648
|
-
} catch {
|
|
2026
|
+
} catch (err) {
|
|
2027
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1649
2028
|
}
|
|
1650
2029
|
}
|
|
1651
2030
|
this.inflight.clear();
|
|
@@ -1679,12 +2058,12 @@ var StreamForwarder = class {
|
|
|
1679
2058
|
let endBody;
|
|
1680
2059
|
if (has_body) {
|
|
1681
2060
|
const chunks = [];
|
|
1682
|
-
bodyPromise = new Promise((
|
|
2061
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1683
2062
|
pushBody = (buf) => {
|
|
1684
2063
|
chunks.push(buf);
|
|
1685
2064
|
};
|
|
1686
2065
|
endBody = () => {
|
|
1687
|
-
|
|
2066
|
+
resolve3(Buffer.concat(chunks));
|
|
1688
2067
|
};
|
|
1689
2068
|
});
|
|
1690
2069
|
}
|
|
@@ -1795,31 +2174,20 @@ function connectTunnel(options) {
|
|
|
1795
2174
|
onConnected,
|
|
1796
2175
|
onDisconnected,
|
|
1797
2176
|
onError,
|
|
1798
|
-
onRequest,
|
|
1799
2177
|
onResponse,
|
|
1800
2178
|
onInfo,
|
|
1801
2179
|
onDrainPing
|
|
1802
2180
|
} = options;
|
|
1803
2181
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1804
2182
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1805
|
-
return new Promise((
|
|
2183
|
+
return new Promise((resolve3, reject) => {
|
|
1806
2184
|
const ws = new WebSocket2(url, {
|
|
1807
2185
|
headers: {
|
|
1808
2186
|
Authorization: authHeader
|
|
1809
2187
|
}
|
|
1810
2188
|
});
|
|
1811
|
-
const streamStartTimes = /* @__PURE__ */ new Map();
|
|
1812
2189
|
const forwarder = new StreamForwarder(ws, port, {
|
|
1813
|
-
|
|
1814
|
-
if (path === TUNNEL_DRAIN_PING_PATH) return;
|
|
1815
|
-
streamStartTimes.set(sid, Date.now());
|
|
1816
|
-
onRequest?.(method, path, sid);
|
|
1817
|
-
},
|
|
1818
|
-
onHead: (sid, status) => {
|
|
1819
|
-
const startedAt = streamStartTimes.get(sid);
|
|
1820
|
-
streamStartTimes.delete(sid);
|
|
1821
|
-
onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
|
|
1822
|
-
},
|
|
2190
|
+
onHead: () => onResponse?.(),
|
|
1823
2191
|
onDrainPing: () => onDrainPing?.()
|
|
1824
2192
|
});
|
|
1825
2193
|
const connectionTimeout = setTimeout(() => {
|
|
@@ -1867,7 +2235,7 @@ function connectTunnel(options) {
|
|
|
1867
2235
|
clearTimeout(connectionTimeout);
|
|
1868
2236
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1869
2237
|
onConnected?.(connectedAgentId);
|
|
1870
|
-
|
|
2238
|
+
resolve3({
|
|
1871
2239
|
ws,
|
|
1872
2240
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1873
2241
|
});
|
|
@@ -1895,7 +2263,6 @@ function connectTunnel(options) {
|
|
|
1895
2263
|
ws.on("close", (code, reason) => {
|
|
1896
2264
|
const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
|
|
1897
2265
|
forwarder.abortAll();
|
|
1898
|
-
streamStartTimes.clear();
|
|
1899
2266
|
onDisconnected?.(code, reasonStr);
|
|
1900
2267
|
});
|
|
1901
2268
|
});
|
|
@@ -1930,7 +2297,11 @@ var RunnerConnection = class {
|
|
|
1930
2297
|
if (this.connection) {
|
|
1931
2298
|
try {
|
|
1932
2299
|
this.connection.close();
|
|
1933
|
-
} catch {
|
|
2300
|
+
} catch (err) {
|
|
2301
|
+
log("error", "runner_connection_close_failed", {
|
|
2302
|
+
agent_id: this.resolvedAgentId,
|
|
2303
|
+
...errorFields(err)
|
|
2304
|
+
});
|
|
1934
2305
|
}
|
|
1935
2306
|
this.connection = null;
|
|
1936
2307
|
}
|
|
@@ -1982,61 +2353,501 @@ var RunnerConnection = class {
|
|
|
1982
2353
|
}
|
|
1983
2354
|
};
|
|
1984
2355
|
|
|
1985
|
-
// src/lib/
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
2356
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2357
|
+
import { writeFileSync } from "fs";
|
|
2358
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2359
|
+
try {
|
|
2360
|
+
writeFileSync(path, `${agentId}
|
|
2361
|
+
`);
|
|
2362
|
+
return { ok: true };
|
|
2363
|
+
} catch (error2) {
|
|
2364
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2365
|
+
}
|
|
1991
2366
|
}
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
2367
|
+
|
|
2368
|
+
// src/lib/claude-usage-reporting.ts
|
|
2369
|
+
var VALID_MODES = ["auto", "on", "off"];
|
|
2370
|
+
function resolveClaudeUsageReportingMode(flagValue, env) {
|
|
2371
|
+
const raw = flagValue ?? env.EVIDENT_CLAUDE_USAGE_REPORTING;
|
|
2372
|
+
if (raw === void 0 || raw === "") {
|
|
2373
|
+
return { mode: "auto", warnings: [] };
|
|
2374
|
+
}
|
|
2375
|
+
const normalized = raw.trim().toLowerCase();
|
|
2376
|
+
if (VALID_MODES.includes(normalized)) {
|
|
2377
|
+
return { mode: normalized, warnings: [] };
|
|
2378
|
+
}
|
|
2379
|
+
const source = flagValue !== void 0 ? "--claude-usage-reporting" : "EVIDENT_CLAUDE_USAGE_REPORTING";
|
|
2380
|
+
return {
|
|
2381
|
+
mode: "auto",
|
|
2382
|
+
warnings: [
|
|
2383
|
+
`Ignoring invalid ${source} "${raw}": expected one of ${VALID_MODES.join(", ")}; using auto`
|
|
2384
|
+
]
|
|
2385
|
+
};
|
|
1996
2386
|
}
|
|
1997
|
-
var
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
}
|
|
2003
|
-
var
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
var
|
|
2013
|
-
var
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2387
|
+
var BASE_REPORT_DELAY_MS = 10 * 6e4;
|
|
2388
|
+
var REPORT_DELAY_JITTER_FRACTION = 0.2;
|
|
2389
|
+
function nextReportDelayMs(random = Math.random) {
|
|
2390
|
+
const jitterRangeMs = BASE_REPORT_DELAY_MS * REPORT_DELAY_JITTER_FRACTION;
|
|
2391
|
+
return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
|
|
2392
|
+
}
|
|
2393
|
+
var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
|
|
2394
|
+
|
|
2395
|
+
// src/lib/channels/driver.ts
|
|
2396
|
+
import { homedir as homedir2 } from "os";
|
|
2397
|
+
|
|
2398
|
+
// src/lib/file-push.ts
|
|
2399
|
+
import { randomUUID } from "crypto";
|
|
2400
|
+
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2401
|
+
import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
|
|
2402
|
+
var FILE_MODE = 384;
|
|
2403
|
+
var DIRECTORY_MODE = 448;
|
|
2404
|
+
async function writePushedFile(request) {
|
|
2405
|
+
const { requestedPath, content, allowedDirectories, homeDir } = request;
|
|
2406
|
+
const bytes = content.byteLength;
|
|
2407
|
+
if (allowedDirectories.length === 0) {
|
|
2408
|
+
return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
2409
|
+
path: requestedPath,
|
|
2410
|
+
bytes
|
|
2411
|
+
});
|
|
2018
2412
|
}
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2413
|
+
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
2414
|
+
return refuse(
|
|
2415
|
+
"file_too_large",
|
|
2416
|
+
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
2417
|
+
{
|
|
2418
|
+
path: requestedPath,
|
|
2419
|
+
bytes
|
|
2420
|
+
}
|
|
2421
|
+
);
|
|
2422
|
+
}
|
|
2423
|
+
const candidate = expandAndValidate(requestedPath, homeDir);
|
|
2424
|
+
if (candidate === null) {
|
|
2425
|
+
return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
2426
|
+
path: requestedPath,
|
|
2427
|
+
bytes
|
|
2428
|
+
});
|
|
2429
|
+
}
|
|
2430
|
+
try {
|
|
2431
|
+
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2432
|
+
dirname2(candidate)
|
|
2433
|
+
);
|
|
2434
|
+
const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
|
|
2435
|
+
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2436
|
+
if (allowedDirectory === null) {
|
|
2437
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2438
|
+
path: realTarget,
|
|
2439
|
+
bytes
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
if (missingSegments.length > 0) {
|
|
2443
|
+
await createMissingDirectories(existingAncestor, missingSegments);
|
|
2444
|
+
const realParent = await realpath(dirname2(realTarget));
|
|
2445
|
+
if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
2446
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2447
|
+
path: realTarget,
|
|
2448
|
+
bytes,
|
|
2449
|
+
reason: "parent_changed_after_create"
|
|
2450
|
+
});
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
await writeAtomically(realTarget, content);
|
|
2454
|
+
log("info", "file_push_written", { path: realTarget, bytes });
|
|
2455
|
+
return { ok: true, path: realTarget };
|
|
2456
|
+
} catch (err) {
|
|
2457
|
+
const errno = err.code ?? "UNKNOWN";
|
|
2458
|
+
return refuse("write_failed", `The runner could not write the file (${errno}).`, {
|
|
2459
|
+
path: candidate,
|
|
2460
|
+
bytes,
|
|
2461
|
+
errno,
|
|
2462
|
+
...errorFields(err)
|
|
2463
|
+
});
|
|
2026
2464
|
}
|
|
2027
|
-
};
|
|
2028
|
-
function backoffDelay(attempt, policy) {
|
|
2029
|
-
const exp = policy.baseDelayMs * Math.pow(2, attempt);
|
|
2030
|
-
const capped = Math.min(policy.maxDelayMs, exp);
|
|
2031
|
-
return Math.floor(Math.random() * capped);
|
|
2032
2465
|
}
|
|
2033
|
-
function
|
|
2034
|
-
|
|
2466
|
+
function expandAndValidate(requestedPath, homeDir) {
|
|
2467
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2468
|
+
return null;
|
|
2469
|
+
}
|
|
2470
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2471
|
+
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2472
|
+
return null;
|
|
2473
|
+
}
|
|
2474
|
+
if (!isAbsolute(expanded)) {
|
|
2475
|
+
return null;
|
|
2476
|
+
}
|
|
2477
|
+
const candidate = resolve2(expanded);
|
|
2478
|
+
const name = basename(candidate);
|
|
2479
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
2035
2480
|
}
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2481
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
2482
|
+
const missingSegments = [];
|
|
2483
|
+
let current = directory;
|
|
2484
|
+
for (; ; ) {
|
|
2485
|
+
try {
|
|
2486
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
2487
|
+
} catch (err) {
|
|
2488
|
+
const parent = dirname2(current);
|
|
2489
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
2490
|
+
throw err;
|
|
2491
|
+
}
|
|
2492
|
+
missingSegments.unshift(basename(current));
|
|
2493
|
+
current = parent;
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
2498
|
+
for (const directory of allowedDirectories) {
|
|
2499
|
+
if (!isAbsolute(directory)) {
|
|
2500
|
+
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
2501
|
+
continue;
|
|
2502
|
+
}
|
|
2503
|
+
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
2504
|
+
if (realDirectory !== null && contains(realDirectory, realTarget)) {
|
|
2505
|
+
return realDirectory;
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
return null;
|
|
2509
|
+
}
|
|
2510
|
+
async function realpathCreatingIfMissing(directory) {
|
|
2511
|
+
try {
|
|
2512
|
+
return await realpath(directory);
|
|
2513
|
+
} catch (err) {
|
|
2514
|
+
if (err.code !== "ENOENT") {
|
|
2515
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2516
|
+
directory,
|
|
2517
|
+
reason: "unresolvable",
|
|
2518
|
+
...errorFields(err)
|
|
2519
|
+
});
|
|
2520
|
+
return null;
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
try {
|
|
2524
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
2525
|
+
await chmod(directory, DIRECTORY_MODE);
|
|
2526
|
+
return await realpath(directory);
|
|
2527
|
+
} catch (err) {
|
|
2528
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2529
|
+
directory,
|
|
2530
|
+
reason: "create_failed",
|
|
2531
|
+
...errorFields(err)
|
|
2532
|
+
});
|
|
2533
|
+
return null;
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
function contains(realDirectory, realTarget) {
|
|
2537
|
+
const rel = relative(realDirectory, realTarget);
|
|
2538
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
2539
|
+
}
|
|
2540
|
+
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2541
|
+
let current = existingAncestor;
|
|
2542
|
+
for (const segment of missingSegments) {
|
|
2543
|
+
current = join2(current, segment);
|
|
2544
|
+
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2545
|
+
await chmod(current, DIRECTORY_MODE);
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
async function writeAtomically(realTarget, content) {
|
|
2549
|
+
const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2550
|
+
let handle;
|
|
2551
|
+
try {
|
|
2552
|
+
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
2553
|
+
await handle.writeFile(content);
|
|
2554
|
+
await handle.chmod(FILE_MODE);
|
|
2555
|
+
await handle.close();
|
|
2556
|
+
handle = void 0;
|
|
2557
|
+
await rename(temporaryPath, realTarget);
|
|
2558
|
+
} catch (err) {
|
|
2559
|
+
await discardTemporaryFile(temporaryPath, handle);
|
|
2560
|
+
throw err;
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
async function discardTemporaryFile(temporaryPath, handle) {
|
|
2564
|
+
try {
|
|
2565
|
+
await handle?.close();
|
|
2566
|
+
} catch (err) {
|
|
2567
|
+
log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2568
|
+
}
|
|
2569
|
+
try {
|
|
2570
|
+
await unlink(temporaryPath);
|
|
2571
|
+
} catch (err) {
|
|
2572
|
+
const errno = err.code;
|
|
2573
|
+
if (errno !== "ENOENT" && errno !== "ENOTDIR") {
|
|
2574
|
+
log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
function refuse(code, message, fields) {
|
|
2579
|
+
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
2580
|
+
return { ok: false, code, message };
|
|
2581
|
+
}
|
|
2582
|
+
|
|
2583
|
+
// src/lib/runner-file-sync.ts
|
|
2584
|
+
var MAX_ACK_ATTEMPTS = 5;
|
|
2585
|
+
async function syncPendingRunnerFiles(options) {
|
|
2586
|
+
const pending = await listPendingFiles(options);
|
|
2587
|
+
const pendingIds = new Set(pending.map((file) => file.id));
|
|
2588
|
+
for (const id of options.ackFailures.keys()) {
|
|
2589
|
+
if (!pendingIds.has(id)) options.ackFailures.delete(id);
|
|
2590
|
+
}
|
|
2591
|
+
if (pending.length === 0) return 0;
|
|
2592
|
+
options.log({
|
|
2593
|
+
level: "info",
|
|
2594
|
+
message: `Runner file sync: ${pending.length} file(s) queued for this runner`
|
|
2595
|
+
});
|
|
2596
|
+
let applied = 0;
|
|
2597
|
+
for (const file of pending) {
|
|
2598
|
+
if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
|
|
2599
|
+
if (await applyOne(options, file)) applied += 1;
|
|
2600
|
+
}
|
|
2601
|
+
return applied;
|
|
2602
|
+
}
|
|
2603
|
+
async function listPendingFiles(options) {
|
|
2604
|
+
let res;
|
|
2605
|
+
try {
|
|
2606
|
+
res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
|
|
2607
|
+
headers: { Authorization: options.getAuthHeader() }
|
|
2608
|
+
});
|
|
2609
|
+
} catch (err) {
|
|
2610
|
+
options.log({
|
|
2611
|
+
level: "warn",
|
|
2612
|
+
message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
|
|
2613
|
+
});
|
|
2614
|
+
return [];
|
|
2615
|
+
}
|
|
2616
|
+
if (!res.ok) {
|
|
2617
|
+
options.log({
|
|
2618
|
+
level: res.status === 404 ? "debug" : "warn",
|
|
2619
|
+
message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2620
|
+
});
|
|
2621
|
+
return [];
|
|
2622
|
+
}
|
|
2623
|
+
let body;
|
|
2624
|
+
try {
|
|
2625
|
+
body = await res.json();
|
|
2626
|
+
} catch (err) {
|
|
2627
|
+
options.log({
|
|
2628
|
+
level: "warn",
|
|
2629
|
+
message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
|
|
2630
|
+
});
|
|
2631
|
+
return [];
|
|
2632
|
+
}
|
|
2633
|
+
if (!Array.isArray(body)) {
|
|
2634
|
+
options.log({
|
|
2635
|
+
level: "warn",
|
|
2636
|
+
message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
|
|
2637
|
+
});
|
|
2638
|
+
return [];
|
|
2639
|
+
}
|
|
2640
|
+
const files = [];
|
|
2641
|
+
for (const entry of body) {
|
|
2642
|
+
const file = asPendingFile(entry);
|
|
2643
|
+
if (file === null) {
|
|
2644
|
+
options.log({
|
|
2645
|
+
level: "warn",
|
|
2646
|
+
message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
|
|
2647
|
+
});
|
|
2648
|
+
continue;
|
|
2649
|
+
}
|
|
2650
|
+
files.push(file);
|
|
2651
|
+
}
|
|
2652
|
+
return files;
|
|
2653
|
+
}
|
|
2654
|
+
function asPendingFile(entry) {
|
|
2655
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
2656
|
+
const { id, path, size } = entry;
|
|
2657
|
+
if (typeof id !== "string" || id === "") return null;
|
|
2658
|
+
if (typeof path !== "string" || path === "") return null;
|
|
2659
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
|
|
2660
|
+
return { id, path, size };
|
|
2661
|
+
}
|
|
2662
|
+
async function applyOne(options, file) {
|
|
2663
|
+
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
2664
|
+
if (options.allowedDirectories.length === 0) {
|
|
2665
|
+
options.log({
|
|
2666
|
+
level: "warn",
|
|
2667
|
+
message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
|
|
2668
|
+
});
|
|
2669
|
+
await ack(options, file, "rejected", "file_sync_disabled");
|
|
2670
|
+
return false;
|
|
2671
|
+
}
|
|
2672
|
+
if (file.size > MAX_FILE_PUSH_BYTES) {
|
|
2673
|
+
options.log({
|
|
2674
|
+
level: "warn",
|
|
2675
|
+
message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
|
|
2676
|
+
});
|
|
2677
|
+
await ack(options, file, "rejected", "file_too_large");
|
|
2678
|
+
return false;
|
|
2679
|
+
}
|
|
2680
|
+
const download = await downloadContent(options, file, label);
|
|
2681
|
+
if (!download.ok) {
|
|
2682
|
+
if (download.terminal) await ack(options, file, "rejected", download.code);
|
|
2683
|
+
return false;
|
|
2684
|
+
}
|
|
2685
|
+
let outcome;
|
|
2686
|
+
try {
|
|
2687
|
+
outcome = await writePushedFile({
|
|
2688
|
+
requestedPath: file.path,
|
|
2689
|
+
content: download.content,
|
|
2690
|
+
allowedDirectories: options.allowedDirectories,
|
|
2691
|
+
homeDir: options.homeDir
|
|
2692
|
+
});
|
|
2693
|
+
} catch (err) {
|
|
2694
|
+
options.log({
|
|
2695
|
+
level: "error",
|
|
2696
|
+
message: `Runner file ${label} could not be written: ${describe(err)}`
|
|
2697
|
+
});
|
|
2698
|
+
await ack(options, file, "rejected", "write_failed");
|
|
2699
|
+
return false;
|
|
2700
|
+
}
|
|
2701
|
+
if (!outcome.ok) {
|
|
2702
|
+
options.log({
|
|
2703
|
+
level: "warn",
|
|
2704
|
+
message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
|
|
2705
|
+
});
|
|
2706
|
+
await ack(options, file, "rejected", outcome.code);
|
|
2707
|
+
return false;
|
|
2708
|
+
}
|
|
2709
|
+
options.log({
|
|
2710
|
+
level: "info",
|
|
2711
|
+
message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
|
|
2712
|
+
});
|
|
2713
|
+
await ack(options, file, "applied");
|
|
2714
|
+
return true;
|
|
2715
|
+
}
|
|
2716
|
+
function durableDownloadCode(status) {
|
|
2717
|
+
return status === 413 ? "file_too_large" : "write_failed";
|
|
2718
|
+
}
|
|
2719
|
+
async function downloadContent(options, file, label) {
|
|
2720
|
+
try {
|
|
2721
|
+
const res = await options.fetchImpl(
|
|
2722
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
|
|
2723
|
+
{ headers: { Authorization: options.getAuthHeader() } }
|
|
2724
|
+
);
|
|
2725
|
+
if (!res.ok) {
|
|
2726
|
+
const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
|
|
2727
|
+
if (!terminal) {
|
|
2728
|
+
options.log({
|
|
2729
|
+
level: "warn",
|
|
2730
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2731
|
+
});
|
|
2732
|
+
return { ok: false, terminal: false };
|
|
2733
|
+
}
|
|
2734
|
+
const code = durableDownloadCode(res.status);
|
|
2735
|
+
options.log({
|
|
2736
|
+
level: "error",
|
|
2737
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
|
|
2738
|
+
});
|
|
2739
|
+
return { ok: false, terminal: true, code };
|
|
2740
|
+
}
|
|
2741
|
+
return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
|
|
2742
|
+
} catch (err) {
|
|
2743
|
+
options.log({
|
|
2744
|
+
level: "warn",
|
|
2745
|
+
message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
|
|
2746
|
+
});
|
|
2747
|
+
return { ok: false, terminal: false };
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
async function ack(options, file, status, reason) {
|
|
2751
|
+
const outcome = `${status}${reason ? ` (${reason})` : ""}`;
|
|
2752
|
+
try {
|
|
2753
|
+
const res = await options.fetchImpl(
|
|
2754
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
2755
|
+
{
|
|
2756
|
+
method: "POST",
|
|
2757
|
+
headers: {
|
|
2758
|
+
Authorization: options.getAuthHeader(),
|
|
2759
|
+
"Content-Type": "application/json"
|
|
2760
|
+
},
|
|
2761
|
+
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
2762
|
+
}
|
|
2763
|
+
);
|
|
2764
|
+
if (!res.ok) {
|
|
2765
|
+
recordAckFailure(
|
|
2766
|
+
options,
|
|
2767
|
+
file,
|
|
2768
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
|
|
2769
|
+
);
|
|
2770
|
+
return;
|
|
2771
|
+
}
|
|
2772
|
+
options.ackFailures.delete(file.id);
|
|
2773
|
+
} catch (err) {
|
|
2774
|
+
recordAckFailure(
|
|
2775
|
+
options,
|
|
2776
|
+
file,
|
|
2777
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
|
|
2778
|
+
);
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
function recordAckFailure(options, file, what) {
|
|
2782
|
+
const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
|
|
2783
|
+
options.ackFailures.set(file.id, attempts);
|
|
2784
|
+
options.log({
|
|
2785
|
+
level: "error",
|
|
2786
|
+
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})`
|
|
2787
|
+
});
|
|
2788
|
+
}
|
|
2789
|
+
function describe(err) {
|
|
2790
|
+
return err instanceof Error ? err.message : String(err);
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
// src/lib/channels/driver.ts
|
|
2794
|
+
function messageIdOf(m) {
|
|
2795
|
+
if (!m || typeof m !== "object") return void 0;
|
|
2796
|
+
if (typeof m.id === "string") return m.id;
|
|
2797
|
+
const infoId = m.info?.id;
|
|
2798
|
+
return typeof infoId === "string" ? infoId : void 0;
|
|
2799
|
+
}
|
|
2800
|
+
function cleanImageMime(contentType) {
|
|
2801
|
+
if (!contentType) return null;
|
|
2802
|
+
const media = contentType.split(";")[0].trim().toLowerCase();
|
|
2803
|
+
return /^image\/[a-z0-9.+-]+$/.test(media) ? media : null;
|
|
2804
|
+
}
|
|
2805
|
+
var LOG_LEVELS = {
|
|
2806
|
+
debug: 0,
|
|
2807
|
+
info: 1,
|
|
2808
|
+
warn: 2,
|
|
2809
|
+
error: 3
|
|
2810
|
+
};
|
|
2811
|
+
var DEFAULT_RETRY_POLICY = {
|
|
2812
|
+
maxAttempts: 6,
|
|
2813
|
+
baseDelayMs: 500,
|
|
2814
|
+
maxDelayMs: 3e4
|
|
2815
|
+
};
|
|
2816
|
+
var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
|
|
2817
|
+
var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
2818
|
+
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
2819
|
+
var HEARTBEAT_MS = 6e4;
|
|
2820
|
+
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2821
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2822
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
2823
|
+
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2824
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
2825
|
+
var ChannelAuthError = class extends Error {
|
|
2826
|
+
constructor(message) {
|
|
2827
|
+
super(message);
|
|
2828
|
+
this.name = "ChannelAuthError";
|
|
2829
|
+
}
|
|
2830
|
+
};
|
|
2831
|
+
var ChannelTerminalError = class extends Error {
|
|
2832
|
+
status;
|
|
2833
|
+
constructor(message, status) {
|
|
2834
|
+
super(message);
|
|
2835
|
+
this.name = "ChannelTerminalError";
|
|
2836
|
+
this.status = status;
|
|
2837
|
+
}
|
|
2838
|
+
};
|
|
2839
|
+
function backoffDelay(attempt, policy) {
|
|
2840
|
+
const exp = policy.baseDelayMs * Math.pow(2, attempt);
|
|
2841
|
+
const capped = Math.min(policy.maxDelayMs, exp);
|
|
2842
|
+
return Math.floor(Math.random() * capped);
|
|
2843
|
+
}
|
|
2844
|
+
function isRetryableStatus(status) {
|
|
2845
|
+
return status === 429 || status >= 500 && status <= 599;
|
|
2846
|
+
}
|
|
2847
|
+
var ChannelDriver = class _ChannelDriver {
|
|
2848
|
+
agentId;
|
|
2849
|
+
port;
|
|
2850
|
+
apiUrl;
|
|
2040
2851
|
getAuthHeader;
|
|
2041
2852
|
conversationFilter;
|
|
2042
2853
|
retry;
|
|
@@ -2047,8 +2858,38 @@ var ChannelDriver = class {
|
|
|
2047
2858
|
pausedMaxWaitMs;
|
|
2048
2859
|
stuckQueuedMs;
|
|
2049
2860
|
now;
|
|
2861
|
+
fileSyncDirectories;
|
|
2862
|
+
homeDir;
|
|
2050
2863
|
/** Cache of conversationId → opencode sessionId. */
|
|
2051
2864
|
sessions = /* @__PURE__ */ new Map();
|
|
2865
|
+
/**
|
|
2866
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2867
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2868
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2869
|
+
* must bind a fresh one.
|
|
2870
|
+
*
|
|
2871
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2872
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2873
|
+
* the same session, and its watcher's routine status writes carry
|
|
2874
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2875
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2876
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2877
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2878
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2879
|
+
* is one we deliberately keep (see `markDone`).
|
|
2880
|
+
*
|
|
2881
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2882
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2883
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2884
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2885
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2886
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2887
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2888
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2889
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2890
|
+
* bounded cost.
|
|
2891
|
+
*/
|
|
2892
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
2052
2893
|
/**
|
|
2053
2894
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
2054
2895
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2158,9 +2999,12 @@ var ChannelDriver = class {
|
|
|
2158
2999
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2159
3000
|
/**
|
|
2160
3001
|
* Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
|
|
2161
|
-
* NON-EMPTY name is stored (terminal — a real session name
|
|
2162
|
-
* so we do NOT re-GET `/session/:id` every tick.
|
|
2163
|
-
*
|
|
3002
|
+
* NON-EMPTY, non-placeholder name is stored (terminal — a real session name
|
|
3003
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
|
|
3004
|
+
* excludes OpenCode's synchronous default title (see
|
|
3005
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
|
|
3006
|
+
* as an empty title so it never latches. A missing entry = not yet resolved OR
|
|
3007
|
+
* resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
|
|
2164
3008
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2165
3009
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2166
3010
|
* no watcher) can resolve the title.
|
|
@@ -2168,6 +3012,24 @@ var ChannelDriver = class {
|
|
|
2168
3012
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2169
3013
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2170
3014
|
draining = false;
|
|
3015
|
+
/**
|
|
3016
|
+
* Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
|
|
3017
|
+
* drain ping don't download, write and ack the same file twice.
|
|
3018
|
+
*/
|
|
3019
|
+
syncingFiles = false;
|
|
3020
|
+
/**
|
|
3021
|
+
* Consecutive failed acks per pending file (#559). Lives on the driver so it
|
|
3022
|
+
* survives across drains — without it, a file whose ack keeps failing is
|
|
3023
|
+
* re-downloaded and re-written every ~2s until the server expires it.
|
|
3024
|
+
*/
|
|
3025
|
+
fileAckFailures = /* @__PURE__ */ new Map();
|
|
3026
|
+
/**
|
|
3027
|
+
* Monotonic count of files this runner has pulled and written (#559). Only
|
|
3028
|
+
* ever increases, so `run.ts` detects work by comparing it against the value
|
|
3029
|
+
* it saw on the previous cycle — including work that landed mid-sleep, the
|
|
3030
|
+
* same trick `lastProxiedActivityAt` uses.
|
|
3031
|
+
*/
|
|
3032
|
+
appliedFileCount = 0;
|
|
2171
3033
|
/**
|
|
2172
3034
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2173
3035
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2198,6 +3060,8 @@ var ChannelDriver = class {
|
|
|
2198
3060
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2199
3061
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2200
3062
|
this.now = config2.now ?? (() => Date.now());
|
|
3063
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
3064
|
+
this.homeDir = config2.homeDir ?? homedir2();
|
|
2201
3065
|
}
|
|
2202
3066
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2203
3067
|
get opencodeBase() {
|
|
@@ -2225,6 +3089,47 @@ var ChannelDriver = class {
|
|
|
2225
3089
|
);
|
|
2226
3090
|
return run2;
|
|
2227
3091
|
}
|
|
3092
|
+
/**
|
|
3093
|
+
* Pull-and-apply any files Evident has queued for this runner (#559), riding
|
|
3094
|
+
* the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
|
|
3095
|
+
* and drain ping that call `drainPending()`. There is deliberately no channel,
|
|
3096
|
+
* control frame or poll loop of its own: worst-case latency is one poll tick.
|
|
3097
|
+
*
|
|
3098
|
+
* NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
|
|
3099
|
+
* cost a conversation turn. Failures are logged and either acked as a terminal
|
|
3100
|
+
* outcome or left pending for the next drain (see `runner-file-sync.ts`).
|
|
3101
|
+
*
|
|
3102
|
+
* Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
|
|
3103
|
+
*
|
|
3104
|
+
* @returns the number of files written to disk.
|
|
3105
|
+
*/
|
|
3106
|
+
async syncPendingFiles() {
|
|
3107
|
+
if (this.stopped) return 0;
|
|
3108
|
+
if (this.syncingFiles) return 0;
|
|
3109
|
+
this.syncingFiles = true;
|
|
3110
|
+
try {
|
|
3111
|
+
const applied = await syncPendingRunnerFiles({
|
|
3112
|
+
agentId: this.agentId,
|
|
3113
|
+
apiUrl: this.apiUrl,
|
|
3114
|
+
getAuthHeader: this.getAuthHeader,
|
|
3115
|
+
fetchImpl: this.fetchImpl,
|
|
3116
|
+
allowedDirectories: this.fileSyncDirectories,
|
|
3117
|
+
homeDir: this.homeDir,
|
|
3118
|
+
ackFailures: this.fileAckFailures,
|
|
3119
|
+
log: this.log
|
|
3120
|
+
});
|
|
3121
|
+
this.appliedFileCount += applied;
|
|
3122
|
+
return applied;
|
|
3123
|
+
} catch (err) {
|
|
3124
|
+
this.log({
|
|
3125
|
+
level: "error",
|
|
3126
|
+
message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
|
|
3127
|
+
});
|
|
3128
|
+
return 0;
|
|
3129
|
+
} finally {
|
|
3130
|
+
this.syncingFiles = false;
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
2228
3133
|
async runDrain() {
|
|
2229
3134
|
let dispatched = 0;
|
|
2230
3135
|
try {
|
|
@@ -2258,6 +3163,28 @@ var ChannelDriver = class {
|
|
|
2258
3163
|
}
|
|
2259
3164
|
return false;
|
|
2260
3165
|
}
|
|
3166
|
+
/**
|
|
3167
|
+
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
3168
|
+
*
|
|
3169
|
+
* Pulling a file is real work that `drainPending()` knows nothing about, so
|
|
3170
|
+
* without this a near-idle runner counts a credential pull as an empty tick
|
|
3171
|
+
* and `--idle-timeout` can `process.exit` mid-pull — leaving a
|
|
3172
|
+
* `.evident-push-*.tmp` behind — or immediately after the write, before the
|
|
3173
|
+
* browser has run the authorize/callback that activates it (the user then sees
|
|
3174
|
+
* `saved_not_activated` for a runner that was fine).
|
|
3175
|
+
*
|
|
3176
|
+
* Two signals because one cannot cover both cases: `inFlight` is the pull
|
|
3177
|
+
* happening RIGHT NOW (it may outlive the tick that started it), and
|
|
3178
|
+
* `appliedFiles` is monotonic so a pull that started AND finished between two
|
|
3179
|
+
* idle checks still shows up as an advance.
|
|
3180
|
+
*
|
|
3181
|
+
* CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
|
|
3182
|
+
* the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
|
|
3183
|
+
* samples afterwards reads `true` every single cycle and can never idle out.
|
|
3184
|
+
*/
|
|
3185
|
+
fileSyncActivity() {
|
|
3186
|
+
return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
|
|
3187
|
+
}
|
|
2261
3188
|
/**
|
|
2262
3189
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2263
3190
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2319,7 +3246,7 @@ var ChannelDriver = class {
|
|
|
2319
3246
|
await this.sleep(step);
|
|
2320
3247
|
}
|
|
2321
3248
|
}
|
|
2322
|
-
while (this.hasInFlightWatchers()) {
|
|
3249
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2323
3250
|
if (this.now() >= deadline) return false;
|
|
2324
3251
|
await this.sleep(step);
|
|
2325
3252
|
}
|
|
@@ -2354,10 +3281,15 @@ var ChannelDriver = class {
|
|
|
2354
3281
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2355
3282
|
*/
|
|
2356
3283
|
async processConversation(conv) {
|
|
2357
|
-
const sessionId = await this.ensureSession(conv);
|
|
3284
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2358
3285
|
const messages = await this.getPendingMessages(conv.id);
|
|
2359
3286
|
let dispatched = 0;
|
|
2360
3287
|
let skippedAlreadyDispatched = 0;
|
|
3288
|
+
if (refusedSessionId && messages.length > 0) {
|
|
3289
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
3290
|
+
superseded_session_id: refusedSessionId
|
|
3291
|
+
});
|
|
3292
|
+
}
|
|
2361
3293
|
for (const message of messages) {
|
|
2362
3294
|
if (this.stopped) break;
|
|
2363
3295
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2384,7 +3316,8 @@ var ChannelDriver = class {
|
|
|
2384
3316
|
} catch (err) {
|
|
2385
3317
|
if (err instanceof ChannelAuthError) throw err;
|
|
2386
3318
|
this.dispatched.delete(message.id);
|
|
2387
|
-
|
|
3319
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
3320
|
+
if (exists === false) {
|
|
2388
3321
|
this.sessions.delete(conv.id);
|
|
2389
3322
|
this.log({
|
|
2390
3323
|
level: "warn",
|
|
@@ -2394,15 +3327,39 @@ var ChannelDriver = class {
|
|
|
2394
3327
|
});
|
|
2395
3328
|
break;
|
|
2396
3329
|
}
|
|
2397
|
-
|
|
3330
|
+
if (exists === null) {
|
|
3331
|
+
this.log({
|
|
3332
|
+
level: "warn",
|
|
3333
|
+
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.`,
|
|
3334
|
+
conversation_id: conv.id,
|
|
3335
|
+
message_id: message.id
|
|
3336
|
+
});
|
|
3337
|
+
break;
|
|
3338
|
+
}
|
|
3339
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3340
|
+
this.sessions.delete(conv.id);
|
|
3341
|
+
this.supersede(conv.id, sessionId);
|
|
3342
|
+
this.log({
|
|
3343
|
+
level: "warn",
|
|
3344
|
+
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.`,
|
|
3345
|
+
conversation_id: conv.id,
|
|
3346
|
+
message_id: message.id
|
|
3347
|
+
});
|
|
3348
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3349
|
+
this.log({
|
|
3350
|
+
level: "warn",
|
|
3351
|
+
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)}`,
|
|
3352
|
+
conversation_id: conv.id,
|
|
3353
|
+
message_id: message.id
|
|
3354
|
+
});
|
|
2398
3355
|
});
|
|
2399
3356
|
this.log({
|
|
2400
3357
|
level: "error",
|
|
2401
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3358
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2402
3359
|
conversation_id: conv.id,
|
|
2403
3360
|
message_id: message.id
|
|
2404
3361
|
});
|
|
2405
|
-
|
|
3362
|
+
break;
|
|
2406
3363
|
}
|
|
2407
3364
|
if (opencodeMessageId === null) {
|
|
2408
3365
|
this.log({
|
|
@@ -2428,8 +3385,42 @@ var ChannelDriver = class {
|
|
|
2428
3385
|
this.ensureWatcherRunning(sessionId);
|
|
2429
3386
|
return dispatched;
|
|
2430
3387
|
}
|
|
3388
|
+
/**
|
|
3389
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
3390
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
3391
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
3392
|
+
*/
|
|
3393
|
+
supersede(conversationId, sessionId) {
|
|
3394
|
+
this.supersededSessions.delete(conversationId);
|
|
3395
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
3396
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
3397
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
3398
|
+
if (oldest === void 0) return;
|
|
3399
|
+
this.supersededSessions.delete(oldest);
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
3403
|
+
isSuperseded(conversationId, sessionId) {
|
|
3404
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
3405
|
+
}
|
|
3406
|
+
/**
|
|
3407
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
3408
|
+
*
|
|
3409
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3410
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3411
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
3412
|
+
*/
|
|
2431
3413
|
async ensureSession(conv) {
|
|
2432
3414
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
3415
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
3416
|
+
this.log({
|
|
3417
|
+
level: "warn",
|
|
3418
|
+
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.`,
|
|
3419
|
+
conversation_id: conv.id
|
|
3420
|
+
});
|
|
3421
|
+
this.sessions.delete(conv.id);
|
|
3422
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
3423
|
+
}
|
|
2433
3424
|
if (bound) {
|
|
2434
3425
|
const exists = await sessionExists(this.port, bound);
|
|
2435
3426
|
if (exists === false) {
|
|
@@ -2439,12 +3430,12 @@ var ChannelDriver = class {
|
|
|
2439
3430
|
conversation_id: conv.id
|
|
2440
3431
|
});
|
|
2441
3432
|
this.sessions.delete(conv.id);
|
|
2442
|
-
return this.createAndBindSession(conv.id);
|
|
3433
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2443
3434
|
}
|
|
2444
3435
|
this.sessions.set(conv.id, bound);
|
|
2445
|
-
return bound;
|
|
3436
|
+
return { sessionId: bound };
|
|
2446
3437
|
}
|
|
2447
|
-
return this.createAndBindSession(conv.id);
|
|
3438
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2448
3439
|
}
|
|
2449
3440
|
/**
|
|
2450
3441
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2455,7 +3446,12 @@ var ChannelDriver = class {
|
|
|
2455
3446
|
const directory = await this.resolveOpenCodeDirectory();
|
|
2456
3447
|
const sessionId = await createOpenCodeSession(this.port, directory);
|
|
2457
3448
|
this.sessions.set(conversationId, sessionId);
|
|
2458
|
-
await this.persistSession(conversationId, sessionId).catch(() => {
|
|
3449
|
+
await this.persistSession(conversationId, sessionId).catch((err) => {
|
|
3450
|
+
this.log({
|
|
3451
|
+
level: "warn",
|
|
3452
|
+
message: `Persisting the OpenCode session binding ${sessionId.slice(0, 8)} for conversation ${conversationId.slice(0, 8)} failed (best-effort, not retried) \u2014 the completion PATCH also carries opencode_session_id, so the binding is repaired when the turn finishes: ${err instanceof Error ? err.message : String(err)}`,
|
|
3453
|
+
conversation_id: conversationId
|
|
3454
|
+
});
|
|
2459
3455
|
});
|
|
2460
3456
|
return sessionId;
|
|
2461
3457
|
}
|
|
@@ -2532,7 +3528,11 @@ var ChannelDriver = class {
|
|
|
2532
3528
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2533
3529
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2534
3530
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2535
|
-
*
|
|
3531
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
3532
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
3533
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
3534
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
3535
|
+
* logged with context (no silent swallow).
|
|
2536
3536
|
*/
|
|
2537
3537
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2538
3538
|
try {
|
|
@@ -2541,6 +3541,25 @@ var ChannelDriver = class {
|
|
|
2541
3541
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2542
3542
|
);
|
|
2543
3543
|
if (!res.ok) {
|
|
3544
|
+
let reason;
|
|
3545
|
+
try {
|
|
3546
|
+
const body = await res.json();
|
|
3547
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
3548
|
+
} catch (parseErr) {
|
|
3549
|
+
this.log({
|
|
3550
|
+
level: "debug",
|
|
3551
|
+
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`,
|
|
3552
|
+
message_id: messageId
|
|
3553
|
+
});
|
|
3554
|
+
}
|
|
3555
|
+
if (reason === "needs_reauth") {
|
|
3556
|
+
this.log({
|
|
3557
|
+
level: "error",
|
|
3558
|
+
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)`,
|
|
3559
|
+
message_id: messageId
|
|
3560
|
+
});
|
|
3561
|
+
return { needsReauth: true };
|
|
3562
|
+
}
|
|
2544
3563
|
this.log({
|
|
2545
3564
|
level: "error",
|
|
2546
3565
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2580,6 +3599,9 @@ var ChannelDriver = class {
|
|
|
2580
3599
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2581
3600
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2582
3601
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
3602
|
+
const failedReason = outcomes.some(
|
|
3603
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
3604
|
+
) ? "needs_reauth" : void 0;
|
|
2583
3605
|
this.log({
|
|
2584
3606
|
level: "info",
|
|
2585
3607
|
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`,
|
|
@@ -2589,7 +3611,8 @@ var ChannelDriver = class {
|
|
|
2589
3611
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2590
3612
|
skipped,
|
|
2591
3613
|
failed,
|
|
2592
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3614
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3615
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2593
3616
|
});
|
|
2594
3617
|
}
|
|
2595
3618
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2620,12 +3643,17 @@ var ChannelDriver = class {
|
|
|
2620
3643
|
stuckReported: false,
|
|
2621
3644
|
lastAliveAt: 0,
|
|
2622
3645
|
aliveInFlight: false,
|
|
3646
|
+
titleSynced: false,
|
|
3647
|
+
titleSyncInFlight: false,
|
|
2623
3648
|
awaitingHumanLatched: false,
|
|
2624
3649
|
pausedOnQuestion: false,
|
|
2625
3650
|
pausedOnPermission: false,
|
|
2626
3651
|
pausedClearConfirmed: false,
|
|
2627
3652
|
pausedInFlight: false,
|
|
2628
|
-
deliveryDeadlineAnchored: false
|
|
3653
|
+
deliveryDeadlineAnchored: false,
|
|
3654
|
+
b2PinnedSinceMs: 0,
|
|
3655
|
+
b2LastDescendantCheckMs: 0,
|
|
3656
|
+
b2AbandonedSignalled: false
|
|
2629
3657
|
});
|
|
2630
3658
|
}
|
|
2631
3659
|
/**
|
|
@@ -2693,12 +3721,17 @@ var ChannelDriver = class {
|
|
|
2693
3721
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
2694
3722
|
lastAliveAt: 0,
|
|
2695
3723
|
aliveInFlight: false,
|
|
3724
|
+
titleSynced: false,
|
|
3725
|
+
titleSyncInFlight: false,
|
|
2696
3726
|
awaitingHumanLatched: false,
|
|
2697
3727
|
pausedOnQuestion: false,
|
|
2698
3728
|
pausedOnPermission: false,
|
|
2699
3729
|
pausedClearConfirmed: false,
|
|
2700
3730
|
pausedInFlight: false,
|
|
2701
|
-
deliveryDeadlineAnchored: false
|
|
3731
|
+
deliveryDeadlineAnchored: false,
|
|
3732
|
+
b2PinnedSinceMs: 0,
|
|
3733
|
+
b2LastDescendantCheckMs: 0,
|
|
3734
|
+
b2AbandonedSignalled: false
|
|
2702
3735
|
});
|
|
2703
3736
|
}
|
|
2704
3737
|
/**
|
|
@@ -2860,58 +3893,7 @@ var ChannelDriver = class {
|
|
|
2860
3893
|
}
|
|
2861
3894
|
}
|
|
2862
3895
|
if (state === "done") {
|
|
2863
|
-
this.
|
|
2864
|
-
if (!inFlight.done) {
|
|
2865
|
-
this.log({
|
|
2866
|
-
level: "info",
|
|
2867
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
2868
|
-
conversation_id: conv.id,
|
|
2869
|
-
message_id: inFlight.evidentMessageId
|
|
2870
|
-
});
|
|
2871
|
-
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
2872
|
-
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2873
|
-
try {
|
|
2874
|
-
await this.markDone(
|
|
2875
|
-
conv.id,
|
|
2876
|
-
inFlight.evidentMessageId,
|
|
2877
|
-
sessionId,
|
|
2878
|
-
inFlight.opencodeMessageId,
|
|
2879
|
-
title,
|
|
2880
|
-
usage
|
|
2881
|
-
);
|
|
2882
|
-
} catch (err) {
|
|
2883
|
-
if (err instanceof ChannelAuthError) throw err;
|
|
2884
|
-
if (err instanceof ChannelTerminalError) {
|
|
2885
|
-
this.log({
|
|
2886
|
-
level: "warn",
|
|
2887
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
2888
|
-
conversation_id: conv.id,
|
|
2889
|
-
message_id: inFlight.evidentMessageId
|
|
2890
|
-
});
|
|
2891
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2892
|
-
return;
|
|
2893
|
-
}
|
|
2894
|
-
if (this.now() >= inFlight.deadline) {
|
|
2895
|
-
this.log({
|
|
2896
|
-
level: "warn",
|
|
2897
|
-
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)}`,
|
|
2898
|
-
conversation_id: conv.id,
|
|
2899
|
-
message_id: inFlight.evidentMessageId
|
|
2900
|
-
});
|
|
2901
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2902
|
-
return;
|
|
2903
|
-
}
|
|
2904
|
-
this.log({
|
|
2905
|
-
level: "warn",
|
|
2906
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
2907
|
-
conversation_id: conv.id,
|
|
2908
|
-
message_id: inFlight.evidentMessageId
|
|
2909
|
-
});
|
|
2910
|
-
return;
|
|
2911
|
-
}
|
|
2912
|
-
inFlight.done = true;
|
|
2913
|
-
}
|
|
2914
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3896
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
2915
3897
|
return;
|
|
2916
3898
|
}
|
|
2917
3899
|
if (state === "failed") {
|
|
@@ -2925,8 +3907,16 @@ var ChannelDriver = class {
|
|
|
2925
3907
|
message_id: inFlight.evidentMessageId
|
|
2926
3908
|
});
|
|
2927
3909
|
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3910
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
2928
3911
|
try {
|
|
2929
|
-
await this.markFailed(
|
|
3912
|
+
await this.markFailed(
|
|
3913
|
+
conv.id,
|
|
3914
|
+
inFlight.evidentMessageId,
|
|
3915
|
+
sessionId,
|
|
3916
|
+
error2,
|
|
3917
|
+
usage,
|
|
3918
|
+
failure
|
|
3919
|
+
);
|
|
2930
3920
|
} catch (err) {
|
|
2931
3921
|
if (err instanceof ChannelAuthError) throw err;
|
|
2932
3922
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -2971,6 +3961,44 @@ var ChannelDriver = class {
|
|
|
2971
3961
|
});
|
|
2972
3962
|
}
|
|
2973
3963
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3964
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3965
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3966
|
+
if (!pinnedNow) {
|
|
3967
|
+
if (snapshotReadable) {
|
|
3968
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3969
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3970
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3971
|
+
}
|
|
3972
|
+
} else {
|
|
3973
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3974
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3975
|
+
return;
|
|
3976
|
+
}
|
|
3977
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3978
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3979
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3980
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3981
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3982
|
+
if (isB2AbandonmentConfirmed({
|
|
3983
|
+
pinnedForMs,
|
|
3984
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3985
|
+
descendantOngoing
|
|
3986
|
+
})) {
|
|
3987
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3988
|
+
this.log({
|
|
3989
|
+
level: "warn",
|
|
3990
|
+
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`,
|
|
3991
|
+
conversation_id: conv.id,
|
|
3992
|
+
message_id: id
|
|
3993
|
+
});
|
|
3994
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3995
|
+
watched_for_ms: pinnedForMs
|
|
3996
|
+
});
|
|
3997
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3998
|
+
return;
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
}
|
|
2974
4002
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
2975
4003
|
this.log({
|
|
2976
4004
|
level: "warn",
|
|
@@ -2990,6 +4018,18 @@ var ChannelDriver = class {
|
|
|
2990
4018
|
inFlight.aliveInFlight = false;
|
|
2991
4019
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
2992
4020
|
});
|
|
4021
|
+
if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
|
|
4022
|
+
inFlight.titleSyncInFlight = true;
|
|
4023
|
+
void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
|
|
4024
|
+
if (!title) {
|
|
4025
|
+
inFlight.titleSyncInFlight = false;
|
|
4026
|
+
return;
|
|
4027
|
+
}
|
|
4028
|
+
const ok = await this.patchConversationTitle(conv.id, title);
|
|
4029
|
+
inFlight.titleSyncInFlight = false;
|
|
4030
|
+
if (ok) inFlight.titleSynced = true;
|
|
4031
|
+
});
|
|
4032
|
+
}
|
|
2993
4033
|
}
|
|
2994
4034
|
if (awaitingHuman) {
|
|
2995
4035
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -3003,29 +4043,93 @@ var ChannelDriver = class {
|
|
|
3003
4043
|
if (ok && inFlight.awaitingHumanLatched) inFlight.pausedClearConfirmed = true;
|
|
3004
4044
|
});
|
|
3005
4045
|
}
|
|
3006
|
-
} else if (inFlight.awaitingHumanLatched) {
|
|
3007
|
-
inFlight.awaitingHumanLatched = false;
|
|
3008
|
-
inFlight.pausedOnQuestion = false;
|
|
3009
|
-
inFlight.pausedOnPermission = false;
|
|
3010
|
-
inFlight.pausedClearConfirmed = false;
|
|
3011
|
-
}
|
|
3012
|
-
const siblingPaused = (sib) => openQuestions.has(sib.evidentMessageId) || openPermissions.has(sib.evidentMessageId) || sib.awaitingHumanLatched || sib.pausedOnQuestion || sib.pausedOnPermission;
|
|
3013
|
-
const hasActivelyRunningSibling = [...watcher.inFlight.values()].some(
|
|
3014
|
-
(sib) => sib.evidentMessageId !== inFlight.evidentMessageId && messageRunState(messages, sib.opencodeMessageId) === "running" && !siblingPaused(sib)
|
|
3015
|
-
);
|
|
3016
|
-
const queuedBehindRunningSibling = state === "queued" && hasActivelyRunningSibling;
|
|
3017
|
-
if (!activelyRunning && !queuedBehindRunningSibling && this.now() >= inFlight.deadline) {
|
|
3018
|
-
this.log({
|
|
3019
|
-
level: "debug",
|
|
3020
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
|
|
3021
|
-
conversation_id: conv.id,
|
|
3022
|
-
message_id: inFlight.evidentMessageId
|
|
3023
|
-
});
|
|
3024
|
-
void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
|
|
3025
|
-
watched_for_ms: this.now() - inFlight.dispatchedAt
|
|
3026
|
-
});
|
|
3027
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4046
|
+
} else if (inFlight.awaitingHumanLatched) {
|
|
4047
|
+
inFlight.awaitingHumanLatched = false;
|
|
4048
|
+
inFlight.pausedOnQuestion = false;
|
|
4049
|
+
inFlight.pausedOnPermission = false;
|
|
4050
|
+
inFlight.pausedClearConfirmed = false;
|
|
4051
|
+
}
|
|
4052
|
+
const siblingPaused = (sib) => openQuestions.has(sib.evidentMessageId) || openPermissions.has(sib.evidentMessageId) || sib.awaitingHumanLatched || sib.pausedOnQuestion || sib.pausedOnPermission;
|
|
4053
|
+
const hasActivelyRunningSibling = [...watcher.inFlight.values()].some(
|
|
4054
|
+
(sib) => sib.evidentMessageId !== inFlight.evidentMessageId && messageRunState(messages, sib.opencodeMessageId) === "running" && !siblingPaused(sib)
|
|
4055
|
+
);
|
|
4056
|
+
const queuedBehindRunningSibling = state === "queued" && hasActivelyRunningSibling;
|
|
4057
|
+
if (!activelyRunning && !queuedBehindRunningSibling && this.now() >= inFlight.deadline) {
|
|
4058
|
+
this.log({
|
|
4059
|
+
level: "debug",
|
|
4060
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
|
|
4061
|
+
conversation_id: conv.id,
|
|
4062
|
+
message_id: inFlight.evidentMessageId
|
|
4063
|
+
});
|
|
4064
|
+
void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
|
|
4065
|
+
watched_for_ms: this.now() - inFlight.dispatchedAt
|
|
4066
|
+
});
|
|
4067
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4068
|
+
}
|
|
4069
|
+
}
|
|
4070
|
+
/**
|
|
4071
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
4072
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
4073
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
4074
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
4075
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
4076
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
4077
|
+
* and risking the two copies silently drifting apart.
|
|
4078
|
+
*/
|
|
4079
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
4080
|
+
const conv = watcher.conv;
|
|
4081
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
4082
|
+
if (!inFlight.done) {
|
|
4083
|
+
this.log({
|
|
4084
|
+
level: "info",
|
|
4085
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
4086
|
+
conversation_id: conv.id,
|
|
4087
|
+
message_id: inFlight.evidentMessageId
|
|
4088
|
+
});
|
|
4089
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
4090
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
4091
|
+
try {
|
|
4092
|
+
await this.markDone(
|
|
4093
|
+
conv.id,
|
|
4094
|
+
inFlight.evidentMessageId,
|
|
4095
|
+
sessionId,
|
|
4096
|
+
inFlight.opencodeMessageId,
|
|
4097
|
+
title,
|
|
4098
|
+
usage
|
|
4099
|
+
);
|
|
4100
|
+
} catch (err) {
|
|
4101
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4102
|
+
if (err instanceof ChannelTerminalError) {
|
|
4103
|
+
this.log({
|
|
4104
|
+
level: "warn",
|
|
4105
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
4106
|
+
conversation_id: conv.id,
|
|
4107
|
+
message_id: inFlight.evidentMessageId
|
|
4108
|
+
});
|
|
4109
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4110
|
+
return;
|
|
4111
|
+
}
|
|
4112
|
+
if (this.now() >= inFlight.deadline) {
|
|
4113
|
+
this.log({
|
|
4114
|
+
level: "warn",
|
|
4115
|
+
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)}`,
|
|
4116
|
+
conversation_id: conv.id,
|
|
4117
|
+
message_id: inFlight.evidentMessageId
|
|
4118
|
+
});
|
|
4119
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4120
|
+
return;
|
|
4121
|
+
}
|
|
4122
|
+
this.log({
|
|
4123
|
+
level: "warn",
|
|
4124
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
4125
|
+
conversation_id: conv.id,
|
|
4126
|
+
message_id: inFlight.evidentMessageId
|
|
4127
|
+
});
|
|
4128
|
+
return;
|
|
4129
|
+
}
|
|
4130
|
+
inFlight.done = true;
|
|
3028
4131
|
}
|
|
4132
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3029
4133
|
}
|
|
3030
4134
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
3031
4135
|
/**
|
|
@@ -3193,6 +4297,7 @@ var ChannelDriver = class {
|
|
|
3193
4297
|
if (state === "failed") {
|
|
3194
4298
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3195
4299
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4300
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3196
4301
|
this.log({
|
|
3197
4302
|
level: "error",
|
|
3198
4303
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3200,7 +4305,7 @@ var ChannelDriver = class {
|
|
|
3200
4305
|
message_id: row.id
|
|
3201
4306
|
});
|
|
3202
4307
|
try {
|
|
3203
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
4308
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3204
4309
|
} catch (err) {
|
|
3205
4310
|
if (err instanceof ChannelAuthError) throw err;
|
|
3206
4311
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3606,6 +4711,47 @@ var ChannelDriver = class {
|
|
|
3606
4711
|
}
|
|
3607
4712
|
return false;
|
|
3608
4713
|
}
|
|
4714
|
+
/**
|
|
4715
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4716
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4717
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4718
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4719
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4720
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4721
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4722
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4723
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4724
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4725
|
+
* not ongoing".
|
|
4726
|
+
*
|
|
4727
|
+
* Return contract:
|
|
4728
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4729
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4730
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4731
|
+
* CONFIRMED NOT a descendant of it.
|
|
4732
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4733
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4734
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4735
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4736
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4737
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4738
|
+
* here.
|
|
4739
|
+
*
|
|
4740
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4741
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4742
|
+
* by interaction attribution or the recovery path.
|
|
4743
|
+
*/
|
|
4744
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4745
|
+
let current = sessionId;
|
|
4746
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4747
|
+
if (current === rootSessionId) return true;
|
|
4748
|
+
const parent = await this.resolveSessionParent(current);
|
|
4749
|
+
if (parent === void 0) return null;
|
|
4750
|
+
if (parent === null) return false;
|
|
4751
|
+
current = parent;
|
|
4752
|
+
}
|
|
4753
|
+
return null;
|
|
4754
|
+
}
|
|
3609
4755
|
/**
|
|
3610
4756
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
3611
4757
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -3628,19 +4774,36 @@ var ChannelDriver = class {
|
|
|
3628
4774
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3629
4775
|
return parent;
|
|
3630
4776
|
}
|
|
4777
|
+
/**
|
|
4778
|
+
* OpenCode's synchronous default session title (e.g.
|
|
4779
|
+
* `"New session - 1737800000000"`), assigned immediately when a session is
|
|
4780
|
+
* created — before OpenCode's async LLM-based auto-titling later renames it
|
|
4781
|
+
* mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
|
|
4782
|
+
* timestamp suffix's exact format is deliberately NOT matched, since the prefix
|
|
4783
|
+
* alone is the stable, cheap signal and over-anchoring on the timestamp
|
|
4784
|
+
* representation risks silently breaking if OpenCode ever changes it. Accepted
|
|
4785
|
+
* trade-off: a genuine LLM-assigned title that happens to literally start with
|
|
4786
|
+
* this prefix would also fail to latch (see `resolveSessionTitle`) —
|
|
4787
|
+
* vanishingly unlikely in practice, and deliberately not engineered around.
|
|
4788
|
+
*/
|
|
4789
|
+
static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
|
|
3631
4790
|
/**
|
|
3632
4791
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3633
4792
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3634
4793
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3635
4794
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3636
4795
|
* Best-effort:
|
|
3637
|
-
* - a resolved NON-EMPTY title
|
|
4796
|
+
* - a resolved NON-EMPTY title that does NOT match
|
|
4797
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
|
|
3638
4798
|
* won't later un-name), so we do NOT re-GET `/session/:id` every tick;
|
|
3639
|
-
* - while the title is still absent
|
|
3640
|
-
*
|
|
3641
|
-
*
|
|
3642
|
-
*
|
|
3643
|
-
*
|
|
4799
|
+
* - while the title is still absent, empty, or matches the OpenCode
|
|
4800
|
+
* placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
|
|
4801
|
+
* asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
|
|
4802
|
+
* the cache unresolved and re-fetch on the next need so a later call (e.g. at
|
|
4803
|
+
* `done`) picks up the name assigned in the meantime. Such a call returns
|
|
4804
|
+
* `null` (omit the title on THIS PATCH) without caching. If a session is
|
|
4805
|
+
* never renamed, the title is omitted forever rather than ever persisting
|
|
4806
|
+
* the placeholder as a last resort;
|
|
3644
4807
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3645
4808
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3646
4809
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3653,7 +4816,7 @@ var ChannelDriver = class {
|
|
|
3653
4816
|
if (res.ok) {
|
|
3654
4817
|
const body = await res.json();
|
|
3655
4818
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3656
|
-
if (title.length > 0) {
|
|
4819
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3657
4820
|
this.sessionTitles.set(sessionId, title);
|
|
3658
4821
|
return title;
|
|
3659
4822
|
}
|
|
@@ -3673,6 +4836,54 @@ var ChannelDriver = class {
|
|
|
3673
4836
|
}
|
|
3674
4837
|
return null;
|
|
3675
4838
|
}
|
|
4839
|
+
/**
|
|
4840
|
+
* Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
|
|
4841
|
+
* session title onto the conversation via the PLAIN conversation-update
|
|
4842
|
+
* endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
|
|
4843
|
+
* message-status endpoint `markProcessing`/`markDone` use. Deliberately a
|
|
4844
|
+
* separate, lighter call: it carries no `status`, so it cannot re-trigger the
|
|
4845
|
+
* `processing`/`done` transition side effects (Slack notices, activity-log
|
|
4846
|
+
* rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
|
|
4847
|
+
* ever touches `conversations.title`. That route (`routes/conversations.ts`)
|
|
4848
|
+
* skips a title write matching the stored value, so a redundant call with the
|
|
4849
|
+
* same title is a real no-op — it does not bump `updated_at`, which the
|
|
4850
|
+
* conversation list sorts and paginates on. (Note this is a DIFFERENT guard
|
|
4851
|
+
* from `threads.ts`'s "non-empty AND changed" one, which only covers the
|
|
4852
|
+
* message-status PATCH; the non-empty half is enforced here instead, by
|
|
4853
|
+
* `resolveSessionTitle` never returning an empty/placeholder title.)
|
|
4854
|
+
*
|
|
4855
|
+
* Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
|
|
4856
|
+
* is logged and the title is simply retried on the next heartbeat tick (the
|
|
4857
|
+
* caller only latches `titleSynced` on `true`).
|
|
4858
|
+
*/
|
|
4859
|
+
async patchConversationTitle(conversationId, title) {
|
|
4860
|
+
try {
|
|
4861
|
+
const res = await this.fetchImpl(
|
|
4862
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
|
|
4863
|
+
{
|
|
4864
|
+
method: "PATCH",
|
|
4865
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
4866
|
+
body: JSON.stringify({ title })
|
|
4867
|
+
}
|
|
4868
|
+
);
|
|
4869
|
+
if (!res.ok) {
|
|
4870
|
+
this.log({
|
|
4871
|
+
level: "debug",
|
|
4872
|
+
message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
|
|
4873
|
+
conversation_id: conversationId
|
|
4874
|
+
});
|
|
4875
|
+
return false;
|
|
4876
|
+
}
|
|
4877
|
+
return true;
|
|
4878
|
+
} catch (err) {
|
|
4879
|
+
this.log({
|
|
4880
|
+
level: "debug",
|
|
4881
|
+
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)}`,
|
|
4882
|
+
conversation_id: conversationId
|
|
4883
|
+
});
|
|
4884
|
+
return false;
|
|
4885
|
+
}
|
|
4886
|
+
}
|
|
3676
4887
|
/**
|
|
3677
4888
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
3678
4889
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -3731,6 +4942,84 @@ var ChannelDriver = class {
|
|
|
3731
4942
|
}
|
|
3732
4943
|
return false;
|
|
3733
4944
|
}
|
|
4945
|
+
/**
|
|
4946
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4947
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4948
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4949
|
+
*
|
|
4950
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4951
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4952
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4953
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4954
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4955
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4956
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4957
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4958
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4959
|
+
* executing, between its step's completion and the next generation step"
|
|
4960
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4961
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4962
|
+
* message timestamps at all.
|
|
4963
|
+
*
|
|
4964
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4965
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4966
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4967
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4968
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4969
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4970
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4971
|
+
* delegation — which the root's status is not.
|
|
4972
|
+
*
|
|
4973
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4974
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4975
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4976
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4977
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4978
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4979
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4980
|
+
* instead.
|
|
4981
|
+
*
|
|
4982
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4983
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4984
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4985
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4986
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4987
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4988
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4989
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4990
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4991
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4992
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4993
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4994
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4995
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4996
|
+
* (unlike the recovery cross-check's contract) — see
|
|
4997
|
+
* `isB2AbandonmentConfirmed`.
|
|
4998
|
+
*/
|
|
4999
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
5000
|
+
const sessions = await listSessions(this.port);
|
|
5001
|
+
if (!sessions) {
|
|
5002
|
+
this.log({
|
|
5003
|
+
level: "warn",
|
|
5004
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
5005
|
+
});
|
|
5006
|
+
return null;
|
|
5007
|
+
}
|
|
5008
|
+
let indeterminate = false;
|
|
5009
|
+
for (const candidate of sessions) {
|
|
5010
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
5011
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
5012
|
+
if (membership === null) {
|
|
5013
|
+
indeterminate = true;
|
|
5014
|
+
continue;
|
|
5015
|
+
}
|
|
5016
|
+
if (membership === false) continue;
|
|
5017
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
5018
|
+
if (ongoing === true) return true;
|
|
5019
|
+
if (ongoing === null) indeterminate = true;
|
|
5020
|
+
}
|
|
5021
|
+
return indeterminate ? null : false;
|
|
5022
|
+
}
|
|
3734
5023
|
/**
|
|
3735
5024
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
3736
5025
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -3859,6 +5148,32 @@ var ChannelDriver = class {
|
|
|
3859
5148
|
}
|
|
3860
5149
|
return messages;
|
|
3861
5150
|
}
|
|
5151
|
+
/**
|
|
5152
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
5153
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
5154
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
5155
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
5156
|
+
*
|
|
5157
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
5158
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
5159
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
5160
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
5161
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
5162
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
5163
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
5164
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
5165
|
+
* stick.
|
|
5166
|
+
*/
|
|
5167
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
5168
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
5169
|
+
this.log({
|
|
5170
|
+
level: "debug",
|
|
5171
|
+
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)}`,
|
|
5172
|
+
conversation_id: conversationId,
|
|
5173
|
+
message_id: messageId
|
|
5174
|
+
});
|
|
5175
|
+
return {};
|
|
5176
|
+
}
|
|
3862
5177
|
/**
|
|
3863
5178
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3864
5179
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3888,7 +5203,7 @@ var ChannelDriver = class {
|
|
|
3888
5203
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3889
5204
|
body: JSON.stringify({
|
|
3890
5205
|
status: "processing",
|
|
3891
|
-
|
|
5206
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3892
5207
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3893
5208
|
...title ? { title } : {}
|
|
3894
5209
|
})
|
|
@@ -3937,6 +5252,11 @@ var ChannelDriver = class {
|
|
|
3937
5252
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3938
5253
|
body: JSON.stringify({
|
|
3939
5254
|
status: "done",
|
|
5255
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
5256
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
5257
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
5258
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
5259
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3940
5260
|
opencode_session_id: sessionId,
|
|
3941
5261
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3942
5262
|
...title ? { title } : {},
|
|
@@ -3953,16 +5273,31 @@ var ChannelDriver = class {
|
|
|
3953
5273
|
}
|
|
3954
5274
|
/**
|
|
3955
5275
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3956
|
-
* when provided (issue #182)
|
|
3957
|
-
* `
|
|
3958
|
-
*
|
|
3959
|
-
*
|
|
5276
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
5277
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
5278
|
+
* session untouched (unused today; kept for API symmetry).
|
|
5279
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
5280
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
5281
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
5282
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
5283
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
5284
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
3960
5285
|
*/
|
|
3961
|
-
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
5286
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
3962
5287
|
const body = { status: "failed" };
|
|
3963
|
-
if (sessionId
|
|
5288
|
+
if (sessionId === null) {
|
|
5289
|
+
body.opencode_session_id = null;
|
|
5290
|
+
} else if (sessionId !== void 0) {
|
|
5291
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
5292
|
+
}
|
|
3964
5293
|
if (error2 !== void 0) body.error = error2;
|
|
3965
5294
|
if (usage) Object.assign(body, usage);
|
|
5295
|
+
if (failure) {
|
|
5296
|
+
body.failure_kind = failure.kind;
|
|
5297
|
+
body.failure_provider_id = failure.providerId;
|
|
5298
|
+
body.failure_model_id = failure.modelId;
|
|
5299
|
+
body.failure_reason = failure.reason;
|
|
5300
|
+
}
|
|
3966
5301
|
await this.callWithRetry(
|
|
3967
5302
|
"marking message as failed",
|
|
3968
5303
|
() => this.fetchImpl(
|
|
@@ -3975,6 +5310,29 @@ var ChannelDriver = class {
|
|
|
3975
5310
|
)
|
|
3976
5311
|
);
|
|
3977
5312
|
}
|
|
5313
|
+
/**
|
|
5314
|
+
* Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
|
|
5315
|
+
*
|
|
5316
|
+
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
5317
|
+
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
5318
|
+
* to the P1-2b zero-provider check — one extra loopback call to
|
|
5319
|
+
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
5320
|
+
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
5321
|
+
* (`null`/indeterminate) leaves the classification `null`, which produces
|
|
5322
|
+
* today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
|
|
5323
|
+
*/
|
|
5324
|
+
async classifyModelAuthFailure(messages, userMessageId) {
|
|
5325
|
+
const classified = messageFailure(messages, userMessageId);
|
|
5326
|
+
if (classified != null) return classified;
|
|
5327
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5328
|
+
const hasProvider = await hasAnyConfiguredProvider(this.port);
|
|
5329
|
+
return applyZeroProviderFallback(
|
|
5330
|
+
classified,
|
|
5331
|
+
hasProvider,
|
|
5332
|
+
reply?.info?.providerID ?? null,
|
|
5333
|
+
reply?.info?.modelID ?? null
|
|
5334
|
+
);
|
|
5335
|
+
}
|
|
3978
5336
|
/**
|
|
3979
5337
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
3980
5338
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -4127,10 +5485,16 @@ var ChannelDriver = class {
|
|
|
4127
5485
|
import chalk5 from "chalk";
|
|
4128
5486
|
import ora2 from "ora";
|
|
4129
5487
|
import { select as select2 } from "@inquirer/prompts";
|
|
5488
|
+
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
4130
5489
|
async function ensureOpenCodeRunning(ctx) {
|
|
4131
5490
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
4132
5491
|
if (healthCheck.healthy) {
|
|
4133
|
-
return {
|
|
5492
|
+
return {
|
|
5493
|
+
port: ctx.port,
|
|
5494
|
+
process: null,
|
|
5495
|
+
version: healthCheck.version ?? null,
|
|
5496
|
+
notReadyReason: null
|
|
5497
|
+
};
|
|
4134
5498
|
}
|
|
4135
5499
|
const runningInstances = await findHealthyOpenCodeInstances();
|
|
4136
5500
|
if (runningInstances.length > 0) {
|
|
@@ -4151,7 +5515,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4151
5515
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4152
5516
|
console.log(
|
|
4153
5517
|
chalk5.dim(
|
|
4154
|
-
` ${getCliName()} run --
|
|
5518
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4155
5519
|
)
|
|
4156
5520
|
);
|
|
4157
5521
|
}
|
|
@@ -4171,14 +5535,22 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4171
5535
|
if (!ctx.interactive) {
|
|
4172
5536
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
4173
5537
|
const proc = await startOpenCode(ctx.port);
|
|
4174
|
-
const health = await waitForOpenCodeHealth(ctx.port,
|
|
5538
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
4175
5539
|
if (!health.healthy) {
|
|
4176
|
-
|
|
4177
|
-
|
|
4178
|
-
|
|
5540
|
+
return {
|
|
5541
|
+
port: ctx.port,
|
|
5542
|
+
process: proc,
|
|
5543
|
+
version: null,
|
|
5544
|
+
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
|
|
5545
|
+
};
|
|
4179
5546
|
}
|
|
4180
5547
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
4181
|
-
return {
|
|
5548
|
+
return {
|
|
5549
|
+
port: ctx.port,
|
|
5550
|
+
process: proc,
|
|
5551
|
+
version: health.version ?? null,
|
|
5552
|
+
notReadyReason: null
|
|
5553
|
+
};
|
|
4182
5554
|
}
|
|
4183
5555
|
let port = ctx.port;
|
|
4184
5556
|
if (isPortInUse(port)) {
|
|
@@ -4231,15 +5603,15 @@ Port ${port} is already in use.`));
|
|
|
4231
5603
|
if (action === "start") {
|
|
4232
5604
|
const spinner = ora2("Starting OpenCode...").start();
|
|
4233
5605
|
const proc = await startOpenCode(port);
|
|
4234
|
-
const health = await waitForOpenCodeHealth(port,
|
|
5606
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
4235
5607
|
if (!health.healthy) {
|
|
4236
5608
|
spinner.fail("Failed to start OpenCode");
|
|
4237
5609
|
throw new Error("OpenCode failed to start");
|
|
4238
5610
|
}
|
|
4239
5611
|
spinner.stop();
|
|
4240
|
-
return { port, process: proc, version: health.version ?? null };
|
|
5612
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
4241
5613
|
}
|
|
4242
|
-
return { port, process: null, version: null };
|
|
5614
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
4243
5615
|
}
|
|
4244
5616
|
|
|
4245
5617
|
// src/commands/agent-lookup.ts
|
|
@@ -4281,19 +5653,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4281
5653
|
return { agent_id: data.agent_id };
|
|
4282
5654
|
}
|
|
4283
5655
|
return {
|
|
4284
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5656
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
4285
5657
|
};
|
|
4286
5658
|
} catch (error2) {
|
|
4287
5659
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
4288
5660
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
4289
5661
|
}
|
|
4290
5662
|
}
|
|
5663
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
4291
5664
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4292
5665
|
const apiUrl = getApiUrlConfig();
|
|
4293
5666
|
try {
|
|
4294
5667
|
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4295
5668
|
method: "POST",
|
|
4296
|
-
headers: { Authorization: authHeader }
|
|
5669
|
+
headers: { Authorization: authHeader },
|
|
5670
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
4297
5671
|
});
|
|
4298
5672
|
if (!response.ok) {
|
|
4299
5673
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -4304,7 +5678,63 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4304
5678
|
}
|
|
4305
5679
|
return { ok: true };
|
|
4306
5680
|
} catch (error2) {
|
|
4307
|
-
return { ok: false, error:
|
|
5681
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5682
|
+
}
|
|
5683
|
+
}
|
|
5684
|
+
function describeBestEffortError(error2) {
|
|
5685
|
+
const name = error2?.name;
|
|
5686
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5687
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5688
|
+
}
|
|
5689
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5690
|
+
}
|
|
5691
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5692
|
+
try {
|
|
5693
|
+
const apiUrl = getApiUrlConfig();
|
|
5694
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5695
|
+
method: "POST",
|
|
5696
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5697
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5698
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5699
|
+
});
|
|
5700
|
+
if (!response.ok) {
|
|
5701
|
+
const serverMessage = await readErrorMessage(response);
|
|
5702
|
+
return {
|
|
5703
|
+
ok: false,
|
|
5704
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5705
|
+
};
|
|
5706
|
+
}
|
|
5707
|
+
return { ok: true };
|
|
5708
|
+
} catch (error2) {
|
|
5709
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5710
|
+
}
|
|
5711
|
+
}
|
|
5712
|
+
function toReportedWindow(window) {
|
|
5713
|
+
if (!window) return null;
|
|
5714
|
+
return { utilization: window.utilization, resets_at: window.resetsAt };
|
|
5715
|
+
}
|
|
5716
|
+
async function reportClaudeUsage(agentId, authHeader, snapshot) {
|
|
5717
|
+
try {
|
|
5718
|
+
const apiUrl = getApiUrlConfig();
|
|
5719
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
|
|
5720
|
+
method: "POST",
|
|
5721
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5722
|
+
body: JSON.stringify({
|
|
5723
|
+
five_hour: toReportedWindow(snapshot.fiveHour),
|
|
5724
|
+
seven_day: toReportedWindow(snapshot.sevenDay)
|
|
5725
|
+
}),
|
|
5726
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5727
|
+
});
|
|
5728
|
+
if (!response.ok) {
|
|
5729
|
+
const serverMessage = await readErrorMessage(response);
|
|
5730
|
+
return {
|
|
5731
|
+
ok: false,
|
|
5732
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5733
|
+
};
|
|
5734
|
+
}
|
|
5735
|
+
return { ok: true };
|
|
5736
|
+
} catch (error2) {
|
|
5737
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
4308
5738
|
}
|
|
4309
5739
|
}
|
|
4310
5740
|
async function getAgentInfo(agentId, authHeader) {
|
|
@@ -4354,6 +5784,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
4354
5784
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
4355
5785
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4356
5786
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5787
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
4357
5788
|
function resolveLogLevel(options) {
|
|
4358
5789
|
const accepted = Object.keys(LOG_LEVELS);
|
|
4359
5790
|
const validate = (value, source) => {
|
|
@@ -4377,6 +5808,63 @@ function resolveLogLevel(options) {
|
|
|
4377
5808
|
}
|
|
4378
5809
|
return "info";
|
|
4379
5810
|
}
|
|
5811
|
+
function resolveFileSyncDirectories(raw, homeDir) {
|
|
5812
|
+
const directories = [];
|
|
5813
|
+
for (const entry of raw ?? []) {
|
|
5814
|
+
const trimmed = entry.trim();
|
|
5815
|
+
if (trimmed === "") {
|
|
5816
|
+
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5817
|
+
}
|
|
5818
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
|
|
5819
|
+
if (!isAbsolute2(expanded)) {
|
|
5820
|
+
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5821
|
+
}
|
|
5822
|
+
const normalized = resolvePath(expanded);
|
|
5823
|
+
if (parse(normalized).root === normalized) {
|
|
5824
|
+
throw new Error(
|
|
5825
|
+
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
5826
|
+
);
|
|
5827
|
+
}
|
|
5828
|
+
if (!directories.includes(normalized)) {
|
|
5829
|
+
directories.push(normalized);
|
|
5830
|
+
}
|
|
5831
|
+
}
|
|
5832
|
+
if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
|
|
5833
|
+
throw new Error(
|
|
5834
|
+
`--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
|
|
5835
|
+
);
|
|
5836
|
+
}
|
|
5837
|
+
return directories;
|
|
5838
|
+
}
|
|
5839
|
+
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
5840
|
+
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
5841
|
+
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
5842
|
+
function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
5843
|
+
const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
|
|
5844
|
+
let raw;
|
|
5845
|
+
let source;
|
|
5846
|
+
if (options.opencodeStartTimeout !== void 0) {
|
|
5847
|
+
raw = options.opencodeStartTimeout;
|
|
5848
|
+
source = "--opencode-start-timeout";
|
|
5849
|
+
} else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
|
|
5850
|
+
raw = env[OPENCODE_START_TIMEOUT_ENV];
|
|
5851
|
+
source = OPENCODE_START_TIMEOUT_ENV;
|
|
5852
|
+
} else {
|
|
5853
|
+
return { timeoutMs: defaultMs, warnings: [] };
|
|
5854
|
+
}
|
|
5855
|
+
const trimmed = raw.trim();
|
|
5856
|
+
const seconds = Number(trimmed);
|
|
5857
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
|
|
5858
|
+
if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
|
|
5859
|
+
return {
|
|
5860
|
+
timeoutMs: defaultMs,
|
|
5861
|
+
warnings: [
|
|
5862
|
+
`Ignoring invalid ${source} "${raw}": expected a positive integer number of seconds (at most ${MAX_OPENCODE_START_TIMEOUT_SECONDS}); using the default ${DEFAULT_OPENCODE_START_TIMEOUT_SECONDS}s`
|
|
5863
|
+
]
|
|
5864
|
+
};
|
|
5865
|
+
}
|
|
5866
|
+
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
5867
|
+
}
|
|
4380
5868
|
function meetsThreshold(state, level) {
|
|
4381
5869
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4382
5870
|
}
|
|
@@ -4398,6 +5886,10 @@ function log2(state, message, level = "info") {
|
|
|
4398
5886
|
function logActivity(state, entry) {
|
|
4399
5887
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
4400
5888
|
if (!meetsThreshold(state, level)) return;
|
|
5889
|
+
forwardRunnerActivity(
|
|
5890
|
+
{ level, message: entry.message, error: entry.error },
|
|
5891
|
+
{ agentId: state.agentId, authHeader: state.authHeader }
|
|
5892
|
+
);
|
|
4401
5893
|
const fullEntry = {
|
|
4402
5894
|
...entry,
|
|
4403
5895
|
level,
|
|
@@ -4498,18 +5990,29 @@ async function handleAuthError(state, error2) {
|
|
|
4498
5990
|
async function driveChannels(state, driver) {
|
|
4499
5991
|
let idlePolls = 0;
|
|
4500
5992
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5993
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4501
5994
|
while (state.running) {
|
|
4502
5995
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4503
5996
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4504
5997
|
if (state.interactive) displayStatus(state);
|
|
4505
5998
|
await state.connection.reconnectPromise;
|
|
4506
5999
|
}
|
|
6000
|
+
const carriedOverFileSync = driver.fileSyncActivity().inFlight;
|
|
6001
|
+
void driver.syncPendingFiles().catch(
|
|
6002
|
+
(error2) => logActivity(state, {
|
|
6003
|
+
type: "error",
|
|
6004
|
+
error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
6005
|
+
})
|
|
6006
|
+
);
|
|
4507
6007
|
try {
|
|
4508
6008
|
const processed = await driver.drainPending();
|
|
4509
6009
|
state.messageCount += processed;
|
|
4510
6010
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4511
6011
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4512
|
-
|
|
6012
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
6013
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
6014
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
6015
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4513
6016
|
idlePolls = 0;
|
|
4514
6017
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4515
6018
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4538,7 +6041,7 @@ async function driveChannels(state, driver) {
|
|
|
4538
6041
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4539
6042
|
if (state.interactive) displayStatus(state);
|
|
4540
6043
|
}
|
|
4541
|
-
await new Promise((
|
|
6044
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4542
6045
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4543
6046
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4544
6047
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4624,6 +6127,94 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
4624
6127
|
);
|
|
4625
6128
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
4626
6129
|
}
|
|
6130
|
+
function scheduleClaudeUsageReporting(state, options) {
|
|
6131
|
+
const { mode, warnings } = resolveClaudeUsageReportingMode(
|
|
6132
|
+
options.claudeUsageReporting,
|
|
6133
|
+
process.env
|
|
6134
|
+
);
|
|
6135
|
+
for (const warning2 of warnings) {
|
|
6136
|
+
logActivity(state, {
|
|
6137
|
+
type: "info",
|
|
6138
|
+
level: "warn",
|
|
6139
|
+
message: `Claude usage reporting: ${warning2}`
|
|
6140
|
+
});
|
|
6141
|
+
}
|
|
6142
|
+
if (mode === "off") {
|
|
6143
|
+
logActivity(state, {
|
|
6144
|
+
type: "info",
|
|
6145
|
+
level: "debug",
|
|
6146
|
+
message: "Claude usage reporting is off (--claude-usage-reporting off)"
|
|
6147
|
+
});
|
|
6148
|
+
return;
|
|
6149
|
+
}
|
|
6150
|
+
let consecutiveFailures = 0;
|
|
6151
|
+
const scheduleNextTick = () => {
|
|
6152
|
+
state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
|
|
6153
|
+
};
|
|
6154
|
+
const tick = async (isFirst) => {
|
|
6155
|
+
try {
|
|
6156
|
+
const usage = await getClaudeUsage();
|
|
6157
|
+
const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
|
|
6158
|
+
if (result.ok) {
|
|
6159
|
+
if (consecutiveFailures > 0) {
|
|
6160
|
+
logActivity(state, {
|
|
6161
|
+
type: "info",
|
|
6162
|
+
level: "info",
|
|
6163
|
+
message: "Claude usage reporting recovered"
|
|
6164
|
+
});
|
|
6165
|
+
}
|
|
6166
|
+
consecutiveFailures = 0;
|
|
6167
|
+
logActivity(state, {
|
|
6168
|
+
type: "info",
|
|
6169
|
+
level: "debug",
|
|
6170
|
+
message: "Reported Claude usage to Evident"
|
|
6171
|
+
});
|
|
6172
|
+
} else {
|
|
6173
|
+
consecutiveFailures++;
|
|
6174
|
+
logActivity(state, {
|
|
6175
|
+
type: "info",
|
|
6176
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6177
|
+
message: `Failed to report Claude usage: ${result.error}`
|
|
6178
|
+
});
|
|
6179
|
+
}
|
|
6180
|
+
scheduleNextTick();
|
|
6181
|
+
} catch (error2) {
|
|
6182
|
+
if (error2 instanceof ClaudeUsageError && isLocalCredentialProblem(error2)) {
|
|
6183
|
+
if (mode === "on") {
|
|
6184
|
+
logActivity(state, {
|
|
6185
|
+
type: "info",
|
|
6186
|
+
level: "warn",
|
|
6187
|
+
message: "Claude usage reporting is forced on but no usable Claude Code login was found \u2014 run `claude` to sign in; reporting will keep retrying"
|
|
6188
|
+
});
|
|
6189
|
+
scheduleNextTick();
|
|
6190
|
+
} else if (isFirst) {
|
|
6191
|
+
logActivity(state, {
|
|
6192
|
+
type: "info",
|
|
6193
|
+
level: "debug",
|
|
6194
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6195
|
+
});
|
|
6196
|
+
} else {
|
|
6197
|
+
logActivity(state, {
|
|
6198
|
+
type: "info",
|
|
6199
|
+
level: "debug",
|
|
6200
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6201
|
+
});
|
|
6202
|
+
scheduleNextTick();
|
|
6203
|
+
}
|
|
6204
|
+
} else {
|
|
6205
|
+
consecutiveFailures++;
|
|
6206
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
6207
|
+
logActivity(state, {
|
|
6208
|
+
type: "info",
|
|
6209
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6210
|
+
message: `Claude usage reporting failed: ${message}`
|
|
6211
|
+
});
|
|
6212
|
+
scheduleNextTick();
|
|
6213
|
+
}
|
|
6214
|
+
}
|
|
6215
|
+
};
|
|
6216
|
+
state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
|
|
6217
|
+
}
|
|
4627
6218
|
async function notifyOffline(state) {
|
|
4628
6219
|
if (!state.agentId || !state.authHeader) return;
|
|
4629
6220
|
if (!state.connected) {
|
|
@@ -4641,13 +6232,28 @@ async function notifyOffline(state) {
|
|
|
4641
6232
|
if (state.interactive) displayStatus(state);
|
|
4642
6233
|
}
|
|
4643
6234
|
}
|
|
6235
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
6236
|
+
const startedAt = Date.now();
|
|
6237
|
+
try {
|
|
6238
|
+
return await run2();
|
|
6239
|
+
} finally {
|
|
6240
|
+
const elapsedMs = Date.now() - startedAt;
|
|
6241
|
+
durations[name] = elapsedMs;
|
|
6242
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
6243
|
+
}
|
|
6244
|
+
}
|
|
4644
6245
|
async function cleanup(state, opts = {}) {
|
|
6246
|
+
const durations = {};
|
|
4645
6247
|
state.running = false;
|
|
4646
6248
|
for (const timer of state.sessionCleanupTimers) {
|
|
4647
6249
|
clearInterval(timer);
|
|
4648
6250
|
clearTimeout(timer);
|
|
4649
6251
|
}
|
|
4650
6252
|
state.sessionCleanupTimers = [];
|
|
6253
|
+
if (state.claudeUsageTimer) {
|
|
6254
|
+
clearTimeout(state.claudeUsageTimer);
|
|
6255
|
+
state.claudeUsageTimer = null;
|
|
6256
|
+
}
|
|
4651
6257
|
if (opts.graceful && state.channelDriver) {
|
|
4652
6258
|
state.channelDriver.stop();
|
|
4653
6259
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -4655,7 +6261,13 @@ async function cleanup(state, opts = {}) {
|
|
|
4655
6261
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4656
6262
|
displayStatus(state);
|
|
4657
6263
|
}
|
|
4658
|
-
const
|
|
6264
|
+
const driver = state.channelDriver;
|
|
6265
|
+
const settled = await timeShutdownPhase(
|
|
6266
|
+
state,
|
|
6267
|
+
durations,
|
|
6268
|
+
"drain",
|
|
6269
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
6270
|
+
);
|
|
4659
6271
|
if (!settled) {
|
|
4660
6272
|
logActivity(state, {
|
|
4661
6273
|
type: "info",
|
|
@@ -4664,13 +6276,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4664
6276
|
if (state.interactive) displayStatus(state);
|
|
4665
6277
|
}
|
|
4666
6278
|
}
|
|
4667
|
-
await notifyOffline(state);
|
|
6279
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
4668
6280
|
if (state.connection) {
|
|
4669
|
-
state.connection
|
|
6281
|
+
const connection = state.connection;
|
|
6282
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
4670
6283
|
state.connection = null;
|
|
4671
6284
|
}
|
|
4672
6285
|
if (state.opencodeProcess) {
|
|
4673
|
-
|
|
6286
|
+
const opencodeProcess = state.opencodeProcess;
|
|
6287
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
4674
6288
|
if (state.interactive) {
|
|
4675
6289
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
4676
6290
|
displayStatus(state);
|
|
@@ -4679,12 +6293,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4679
6293
|
}
|
|
4680
6294
|
state.opencodeProcess = null;
|
|
4681
6295
|
}
|
|
6296
|
+
return durations;
|
|
4682
6297
|
}
|
|
4683
6298
|
async function run(options) {
|
|
4684
6299
|
const interactive = isInteractive(options.json);
|
|
4685
6300
|
let logLevel;
|
|
6301
|
+
let fileSyncDirectories;
|
|
4686
6302
|
try {
|
|
4687
6303
|
logLevel = resolveLogLevel(options);
|
|
6304
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
4688
6305
|
} catch (error2) {
|
|
4689
6306
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4690
6307
|
if (options.json) {
|
|
@@ -4717,8 +6334,15 @@ async function run(options) {
|
|
|
4717
6334
|
messageCount: 0,
|
|
4718
6335
|
lastProxiedActivityAt: null,
|
|
4719
6336
|
sessionCleanupTimers: [],
|
|
6337
|
+
claudeUsageTimer: null,
|
|
4720
6338
|
authHeader: ""
|
|
4721
6339
|
};
|
|
6340
|
+
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
6341
|
+
if (fileSyncDirectories.length > 0) {
|
|
6342
|
+
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
6343
|
+
} else {
|
|
6344
|
+
log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
|
|
6345
|
+
}
|
|
4722
6346
|
if (!options.runner && options.agent) {
|
|
4723
6347
|
telemetry.info(
|
|
4724
6348
|
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
@@ -4742,14 +6366,38 @@ async function run(options) {
|
|
|
4742
6366
|
const handleSignal = async () => {
|
|
4743
6367
|
if (state.shuttingDown) return;
|
|
4744
6368
|
state.shuttingDown = true;
|
|
6369
|
+
const shutdownStartedAt = Date.now();
|
|
4745
6370
|
if (state.interactive) {
|
|
4746
6371
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
4747
6372
|
displayStatus(state);
|
|
4748
6373
|
} else {
|
|
4749
6374
|
log2(state, "Shutting down...");
|
|
4750
6375
|
}
|
|
4751
|
-
await cleanup(state, { graceful: true });
|
|
4752
|
-
|
|
6376
|
+
const durations = await cleanup(state, { graceful: true });
|
|
6377
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
6378
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
6379
|
+
let timer;
|
|
6380
|
+
const flushed = shutdownTelemetry().then(
|
|
6381
|
+
() => true,
|
|
6382
|
+
(error2) => {
|
|
6383
|
+
log2(
|
|
6384
|
+
state,
|
|
6385
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
6386
|
+
"warn"
|
|
6387
|
+
);
|
|
6388
|
+
return true;
|
|
6389
|
+
}
|
|
6390
|
+
);
|
|
6391
|
+
const timedOut = new Promise((resolve3) => {
|
|
6392
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
6393
|
+
});
|
|
6394
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
6395
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
6396
|
+
}
|
|
6397
|
+
clearTimeout(timer);
|
|
6398
|
+
});
|
|
6399
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
6400
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
4753
6401
|
process.exit(0);
|
|
4754
6402
|
};
|
|
4755
6403
|
process.on("SIGINT", handleSignal);
|
|
@@ -4863,25 +6511,67 @@ async function run(options) {
|
|
|
4863
6511
|
}
|
|
4864
6512
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
4865
6513
|
state.agentName = validation.agent.name;
|
|
6514
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
6515
|
+
if (microvmId) {
|
|
6516
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
6517
|
+
if (reported.ok) {
|
|
6518
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
6519
|
+
} else {
|
|
6520
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
6521
|
+
log2(state, message, "warn");
|
|
6522
|
+
if (state.interactive && !state.json) {
|
|
6523
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6524
|
+
}
|
|
6525
|
+
}
|
|
6526
|
+
} else {
|
|
6527
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6528
|
+
}
|
|
6529
|
+
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
6530
|
+
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6531
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6532
|
+
}
|
|
4866
6533
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
4867
6534
|
try {
|
|
4868
6535
|
const oc = await ensureOpenCodeRunning({
|
|
4869
6536
|
port: state.port,
|
|
4870
6537
|
interactive: state.interactive,
|
|
4871
6538
|
agentId: state.agentId,
|
|
4872
|
-
log: (message) => log2(state, message)
|
|
6539
|
+
log: (message) => log2(state, message),
|
|
6540
|
+
startTimeoutMs: opencodeStartTimeoutMs
|
|
4873
6541
|
});
|
|
4874
6542
|
state.port = oc.port;
|
|
4875
6543
|
state.opencodeProcess = oc.process;
|
|
4876
6544
|
state.opencodeVersion = oc.version;
|
|
4877
|
-
state.opencodeConnected = oc.
|
|
6545
|
+
state.opencodeConnected = oc.notReadyReason === null;
|
|
4878
6546
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
4879
6547
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
4880
|
-
|
|
4881
|
-
|
|
4882
|
-
|
|
4883
|
-
|
|
4884
|
-
|
|
6548
|
+
if (!state.interactive && oc.notReadyReason !== null) {
|
|
6549
|
+
const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers \u2014 raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV}).`;
|
|
6550
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6551
|
+
} else {
|
|
6552
|
+
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
6553
|
+
if (versionWarning) {
|
|
6554
|
+
log2(state, versionWarning, "warn");
|
|
6555
|
+
if (state.interactive && !state.json) {
|
|
6556
|
+
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
6557
|
+
}
|
|
6558
|
+
}
|
|
6559
|
+
const noProviderWarning = buildNoProviderWarning(
|
|
6560
|
+
await hasAnyConfiguredProvider(state.port)
|
|
6561
|
+
);
|
|
6562
|
+
if (noProviderWarning) {
|
|
6563
|
+
log2(state, noProviderWarning, "warn");
|
|
6564
|
+
if (state.interactive && !state.json) {
|
|
6565
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6566
|
+
blank();
|
|
6567
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6568
|
+
console.log(
|
|
6569
|
+
chalk6.dim(
|
|
6570
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6571
|
+
)
|
|
6572
|
+
);
|
|
6573
|
+
blank();
|
|
6574
|
+
}
|
|
4885
6575
|
}
|
|
4886
6576
|
}
|
|
4887
6577
|
} catch (error2) {
|
|
@@ -4896,6 +6586,10 @@ async function run(options) {
|
|
|
4896
6586
|
getAuthHeader: () => state.authHeader,
|
|
4897
6587
|
conversationFilter: state.conversationFilter,
|
|
4898
6588
|
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
6589
|
+
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
6590
|
+
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
6591
|
+
fileSyncDirectories,
|
|
6592
|
+
homeDir: homedir3(),
|
|
4899
6593
|
log: (entry) => (
|
|
4900
6594
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4901
6595
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4922,6 +6616,18 @@ async function run(options) {
|
|
|
4922
6616
|
type: "info",
|
|
4923
6617
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
4924
6618
|
});
|
|
6619
|
+
if (options.tunnelReadyFile) {
|
|
6620
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6621
|
+
if (marker.ok) {
|
|
6622
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6623
|
+
} else {
|
|
6624
|
+
log2(
|
|
6625
|
+
state,
|
|
6626
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6627
|
+
"error"
|
|
6628
|
+
);
|
|
6629
|
+
}
|
|
6630
|
+
}
|
|
4925
6631
|
emitAgentConnected(state.agentId, {
|
|
4926
6632
|
port: state.port,
|
|
4927
6633
|
cli_version: getCliVersion(),
|
|
@@ -4977,6 +6683,12 @@ async function run(options) {
|
|
|
4977
6683
|
onDrainPing: () => {
|
|
4978
6684
|
if (!state.running) return;
|
|
4979
6685
|
logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
|
|
6686
|
+
void channelDriver.syncPendingFiles().catch(
|
|
6687
|
+
(error2) => logActivity(state, {
|
|
6688
|
+
type: "error",
|
|
6689
|
+
error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
6690
|
+
})
|
|
6691
|
+
);
|
|
4980
6692
|
channelDriver.drainPending().then((processed) => {
|
|
4981
6693
|
if (processed > 0) {
|
|
4982
6694
|
state.messageCount += processed;
|
|
@@ -5006,6 +6718,7 @@ async function run(options) {
|
|
|
5006
6718
|
throw error2;
|
|
5007
6719
|
}
|
|
5008
6720
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6721
|
+
scheduleClaudeUsageReporting(state, options);
|
|
5009
6722
|
if (!interactive || state.json) {
|
|
5010
6723
|
log2(state, "Driving channel messages...");
|
|
5011
6724
|
}
|
|
@@ -5060,10 +6773,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
5060
6773
|
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);
|
|
5061
6774
|
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 }));
|
|
5062
6775
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
5063
|
-
program.command("
|
|
6776
|
+
program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
|
|
6777
|
+
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(
|
|
6778
|
+
"-a, --agent [id]",
|
|
6779
|
+
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
6780
|
+
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
5064
6781
|
"--log-level <level>",
|
|
5065
6782
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
5066
|
-
).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(
|
|
6783
|
+
).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(
|
|
6784
|
+
"--opencode-start-timeout <seconds>",
|
|
6785
|
+
"Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
|
|
6786
|
+
).option("--json", "Output in JSON format").option(
|
|
5067
6787
|
"--session-cleanup-max-age <duration>",
|
|
5068
6788
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
5069
6789
|
).option(
|
|
@@ -5072,6 +6792,17 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5072
6792
|
).option(
|
|
5073
6793
|
"--session-cleanup-interval <duration>",
|
|
5074
6794
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6795
|
+
).option(
|
|
6796
|
+
"--claude-usage-reporting <mode>",
|
|
6797
|
+
"Report Claude subscription usage to Evident: auto | on | off (default: auto). Env: EVIDENT_CLAUDE_USAGE_REPORTING"
|
|
6798
|
+
).option(
|
|
6799
|
+
"--enable-file-sync-to <dir>",
|
|
6800
|
+
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
6801
|
+
(value, previous) => previous.concat([value]),
|
|
6802
|
+
[]
|
|
6803
|
+
).option(
|
|
6804
|
+
"--tunnel-ready-file <path>",
|
|
6805
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
5075
6806
|
).action(
|
|
5076
6807
|
(options) => {
|
|
5077
6808
|
run({
|
|
@@ -5084,11 +6815,21 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5084
6815
|
verbose: options.verbose,
|
|
5085
6816
|
conversation: options.conversation,
|
|
5086
6817
|
idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
|
|
6818
|
+
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
6819
|
+
// resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
|
|
6820
|
+
opencodeStartTimeout: options.opencodeStartTimeout,
|
|
5087
6821
|
json: options.json,
|
|
5088
6822
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
5089
6823
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
5090
6824
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
5091
|
-
sessionCleanupInterval: options.sessionCleanupInterval
|
|
6825
|
+
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6826
|
+
// Raw string — the resolver in run.ts single-sources parsing
|
|
6827
|
+
// (resolveClaudeUsageReportingMode).
|
|
6828
|
+
claudeUsageReporting: options.claudeUsageReporting,
|
|
6829
|
+
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6830
|
+
// resolveFileSyncDirectories.
|
|
6831
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6832
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
5092
6833
|
});
|
|
5093
6834
|
}
|
|
5094
6835
|
);
|