@evident-ai/cli 3.1.1-dev.9ff0701 → 3.1.1-dev.a98a2ef
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 +68 -13
- package/dist/index.js +2058 -190
- 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
|
}
|
|
@@ -645,14 +869,90 @@ var EventTypes = {
|
|
|
645
869
|
// CLI lifecycle
|
|
646
870
|
CLI_STARTED: "cli.started",
|
|
647
871
|
CLI_COMMAND: "cli.command",
|
|
648
|
-
CLI_ERROR: "cli.error"
|
|
872
|
+
CLI_ERROR: "cli.error",
|
|
873
|
+
// Deprecation telemetry (#412) — usage of the old `--agent`/`EVIDENT_AGENT_KEY`
|
|
874
|
+
// names instead of the preferred `--runner`/`EVIDENT_RUNNER_KEY` (#409).
|
|
875
|
+
DEPRECATED_AGENT_FLAG_USED: "cli.deprecated_agent_flag_used",
|
|
876
|
+
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
649
877
|
};
|
|
650
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
|
+
|
|
651
942
|
// src/lib/auth.ts
|
|
652
943
|
async function getAuthCredentials() {
|
|
944
|
+
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
653
945
|
const agentKey = process.env.EVIDENT_AGENT_KEY;
|
|
946
|
+
if (runnerKey) {
|
|
947
|
+
return {
|
|
948
|
+
token: runnerKey,
|
|
949
|
+
authType: "agent_key",
|
|
950
|
+
keySource: "runner_key",
|
|
951
|
+
notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
|
|
952
|
+
};
|
|
953
|
+
}
|
|
654
954
|
if (agentKey) {
|
|
655
|
-
return { token: agentKey, authType: "agent_key" };
|
|
955
|
+
return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
|
|
656
956
|
}
|
|
657
957
|
const userToken = process.env.EVIDENT_TOKEN;
|
|
658
958
|
if (userToken) {
|
|
@@ -706,7 +1006,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
706
1006
|
if (health.healthy) {
|
|
707
1007
|
return health;
|
|
708
1008
|
}
|
|
709
|
-
await new Promise((
|
|
1009
|
+
await new Promise((resolve3) => setTimeout(resolve3, 1e3));
|
|
710
1010
|
}
|
|
711
1011
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
712
1012
|
}
|
|
@@ -721,7 +1021,7 @@ function buildOpenCodeVersionWarning(version2) {
|
|
|
721
1021
|
if (isQueueValidatedVersion(version2)) return null;
|
|
722
1022
|
const detected = version2 ? `v${version2}` : "unknown";
|
|
723
1023
|
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
724
|
-
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack
|
|
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.`;
|
|
725
1025
|
}
|
|
726
1026
|
|
|
727
1027
|
// src/lib/opencode/process.ts
|
|
@@ -1013,6 +1313,12 @@ async function promptOpenCodeInstall(interactive) {
|
|
|
1013
1313
|
return action;
|
|
1014
1314
|
}
|
|
1015
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
|
+
|
|
1016
1322
|
// src/lib/opencode/session.ts
|
|
1017
1323
|
function opencodeBase(port) {
|
|
1018
1324
|
return `http://127.0.0.1:${port}`;
|
|
@@ -1215,6 +1521,11 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
1215
1521
|
}
|
|
1216
1522
|
const entry = provider.models[modelId];
|
|
1217
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
|
+
}
|
|
1218
1529
|
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
1219
1530
|
} catch (err) {
|
|
1220
1531
|
console.error(
|
|
@@ -1243,6 +1554,16 @@ async function buildFileParts(attachments, capable) {
|
|
|
1243
1554
|
);
|
|
1244
1555
|
dataUrl = null;
|
|
1245
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
|
+
}
|
|
1246
1567
|
if (dataUrl == null) {
|
|
1247
1568
|
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1248
1569
|
continue;
|
|
@@ -1324,7 +1645,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
1324
1645
|
}
|
|
1325
1646
|
}
|
|
1326
1647
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
1327
|
-
await new Promise((
|
|
1648
|
+
await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
|
|
1328
1649
|
}
|
|
1329
1650
|
}
|
|
1330
1651
|
return null;
|
|
@@ -1370,6 +1691,72 @@ function findLastAssistantReplyFor(messages, userMessageId) {
|
|
|
1370
1691
|
}
|
|
1371
1692
|
return lastOk ?? last;
|
|
1372
1693
|
}
|
|
1694
|
+
function messageUsage(messages, userMessageId) {
|
|
1695
|
+
if (!messages || messages.length === 0) return null;
|
|
1696
|
+
const byParentAll = messages.filter(
|
|
1697
|
+
(m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
|
|
1698
|
+
);
|
|
1699
|
+
const byParentNonErrored = byParentAll.filter((m) => errorOf(m) == null);
|
|
1700
|
+
const byParent = byParentNonErrored.length > 0 ? byParentNonErrored : byParentAll;
|
|
1701
|
+
let correlated;
|
|
1702
|
+
if (byParent.length > 0) {
|
|
1703
|
+
correlated = byParent;
|
|
1704
|
+
} else {
|
|
1705
|
+
const reply = findAssistantReplyAfter(messages, userMessageId);
|
|
1706
|
+
correlated = reply ? [reply] : [];
|
|
1707
|
+
}
|
|
1708
|
+
if (correlated.length === 0) return null;
|
|
1709
|
+
let sawAnyUsage = false;
|
|
1710
|
+
let inputSum = 0;
|
|
1711
|
+
let outputSum = 0;
|
|
1712
|
+
let reasoningSum = 0;
|
|
1713
|
+
let cacheReadSum = 0;
|
|
1714
|
+
let cacheWriteSum = 0;
|
|
1715
|
+
let costSum = 0;
|
|
1716
|
+
let sawCost = false;
|
|
1717
|
+
let modelId = null;
|
|
1718
|
+
let providerId = null;
|
|
1719
|
+
for (const m of correlated) {
|
|
1720
|
+
const info = m.info;
|
|
1721
|
+
if (!info) continue;
|
|
1722
|
+
const tokens = info.tokens;
|
|
1723
|
+
if (tokens) {
|
|
1724
|
+
sawAnyUsage = true;
|
|
1725
|
+
inputSum += tokens.input ?? 0;
|
|
1726
|
+
outputSum += tokens.output ?? 0;
|
|
1727
|
+
reasoningSum += tokens.reasoning ?? 0;
|
|
1728
|
+
cacheReadSum += tokens.cache?.read ?? 0;
|
|
1729
|
+
cacheWriteSum += tokens.cache?.write ?? 0;
|
|
1730
|
+
}
|
|
1731
|
+
if (typeof info.cost === "number") {
|
|
1732
|
+
sawAnyUsage = true;
|
|
1733
|
+
sawCost = true;
|
|
1734
|
+
costSum += info.cost;
|
|
1735
|
+
}
|
|
1736
|
+
if (typeof info.modelID === "string") {
|
|
1737
|
+
sawAnyUsage = true;
|
|
1738
|
+
modelId = info.modelID;
|
|
1739
|
+
}
|
|
1740
|
+
if (typeof info.providerID === "string") {
|
|
1741
|
+
sawAnyUsage = true;
|
|
1742
|
+
providerId = info.providerID;
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
if (!sawAnyUsage) return null;
|
|
1746
|
+
return {
|
|
1747
|
+
usage_provider_id: providerId,
|
|
1748
|
+
usage_model_id: modelId,
|
|
1749
|
+
usage_tokens_input: inputSum,
|
|
1750
|
+
usage_tokens_output: outputSum,
|
|
1751
|
+
usage_tokens_reasoning: reasoningSum,
|
|
1752
|
+
usage_tokens_cache_read: cacheReadSum,
|
|
1753
|
+
usage_tokens_cache_write: cacheWriteSum,
|
|
1754
|
+
// NULL means "OpenCode never reported a cost" (never inferred from
|
|
1755
|
+
// tokens) — distinct from a genuine 0-cost turn, which would set
|
|
1756
|
+
// `sawCost` true with `costSum === 0`.
|
|
1757
|
+
usage_cost_usd: sawCost ? costSum : null
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1373
1760
|
function messageRunState(messages, userMessageId) {
|
|
1374
1761
|
if (!messages || messages.length === 0) return "unknown";
|
|
1375
1762
|
const hasUser = messages.some((m) => idOf(m) === userMessageId);
|
|
@@ -1386,6 +1773,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1386
1773
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1387
1774
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1388
1775
|
}
|
|
1776
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1777
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1778
|
+
}
|
|
1389
1779
|
function messageError(messages, userMessageId) {
|
|
1390
1780
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1391
1781
|
const error2 = errorOf(reply);
|
|
@@ -1399,12 +1789,79 @@ function messageError(messages, userMessageId) {
|
|
|
1399
1789
|
}
|
|
1400
1790
|
return "The agent run failed.";
|
|
1401
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
|
+
}
|
|
1402
1828
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1403
1829
|
if (!messages || messages.length === 0) return false;
|
|
1404
1830
|
return messages.some(
|
|
1405
1831
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1406
1832
|
);
|
|
1407
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
|
+
}
|
|
1408
1865
|
|
|
1409
1866
|
// src/lib/opencode/session-cleanup.ts
|
|
1410
1867
|
var DURATION_UNIT_MS = {
|
|
@@ -1563,10 +2020,11 @@ var StreamForwarder = class {
|
|
|
1563
2020
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1564
2021
|
*/
|
|
1565
2022
|
abortAll() {
|
|
1566
|
-
for (const stream of this.inflight.
|
|
2023
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1567
2024
|
try {
|
|
1568
2025
|
stream.abort();
|
|
1569
|
-
} catch {
|
|
2026
|
+
} catch (err) {
|
|
2027
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1570
2028
|
}
|
|
1571
2029
|
}
|
|
1572
2030
|
this.inflight.clear();
|
|
@@ -1600,12 +2058,12 @@ var StreamForwarder = class {
|
|
|
1600
2058
|
let endBody;
|
|
1601
2059
|
if (has_body) {
|
|
1602
2060
|
const chunks = [];
|
|
1603
|
-
bodyPromise = new Promise((
|
|
2061
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1604
2062
|
pushBody = (buf) => {
|
|
1605
2063
|
chunks.push(buf);
|
|
1606
2064
|
};
|
|
1607
2065
|
endBody = () => {
|
|
1608
|
-
|
|
2066
|
+
resolve3(Buffer.concat(chunks));
|
|
1609
2067
|
};
|
|
1610
2068
|
});
|
|
1611
2069
|
}
|
|
@@ -1716,31 +2174,20 @@ function connectTunnel(options) {
|
|
|
1716
2174
|
onConnected,
|
|
1717
2175
|
onDisconnected,
|
|
1718
2176
|
onError,
|
|
1719
|
-
onRequest,
|
|
1720
2177
|
onResponse,
|
|
1721
2178
|
onInfo,
|
|
1722
2179
|
onDrainPing
|
|
1723
2180
|
} = options;
|
|
1724
2181
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1725
2182
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1726
|
-
return new Promise((
|
|
2183
|
+
return new Promise((resolve3, reject) => {
|
|
1727
2184
|
const ws = new WebSocket2(url, {
|
|
1728
2185
|
headers: {
|
|
1729
2186
|
Authorization: authHeader
|
|
1730
2187
|
}
|
|
1731
2188
|
});
|
|
1732
|
-
const streamStartTimes = /* @__PURE__ */ new Map();
|
|
1733
2189
|
const forwarder = new StreamForwarder(ws, port, {
|
|
1734
|
-
|
|
1735
|
-
if (path === TUNNEL_DRAIN_PING_PATH) return;
|
|
1736
|
-
streamStartTimes.set(sid, Date.now());
|
|
1737
|
-
onRequest?.(method, path, sid);
|
|
1738
|
-
},
|
|
1739
|
-
onHead: (sid, status) => {
|
|
1740
|
-
const startedAt = streamStartTimes.get(sid);
|
|
1741
|
-
streamStartTimes.delete(sid);
|
|
1742
|
-
onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
|
|
1743
|
-
},
|
|
2190
|
+
onHead: () => onResponse?.(),
|
|
1744
2191
|
onDrainPing: () => onDrainPing?.()
|
|
1745
2192
|
});
|
|
1746
2193
|
const connectionTimeout = setTimeout(() => {
|
|
@@ -1788,7 +2235,7 @@ function connectTunnel(options) {
|
|
|
1788
2235
|
clearTimeout(connectionTimeout);
|
|
1789
2236
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1790
2237
|
onConnected?.(connectedAgentId);
|
|
1791
|
-
|
|
2238
|
+
resolve3({
|
|
1792
2239
|
ws,
|
|
1793
2240
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1794
2241
|
});
|
|
@@ -1816,7 +2263,6 @@ function connectTunnel(options) {
|
|
|
1816
2263
|
ws.on("close", (code, reason) => {
|
|
1817
2264
|
const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
|
|
1818
2265
|
forwarder.abortAll();
|
|
1819
|
-
streamStartTimes.clear();
|
|
1820
2266
|
onDisconnected?.(code, reasonStr);
|
|
1821
2267
|
});
|
|
1822
2268
|
});
|
|
@@ -1851,7 +2297,11 @@ var RunnerConnection = class {
|
|
|
1851
2297
|
if (this.connection) {
|
|
1852
2298
|
try {
|
|
1853
2299
|
this.connection.close();
|
|
1854
|
-
} catch {
|
|
2300
|
+
} catch (err) {
|
|
2301
|
+
log("error", "runner_connection_close_failed", {
|
|
2302
|
+
agent_id: this.resolvedAgentId,
|
|
2303
|
+
...errorFields(err)
|
|
2304
|
+
});
|
|
1855
2305
|
}
|
|
1856
2306
|
this.connection = null;
|
|
1857
2307
|
}
|
|
@@ -1903,6 +2353,443 @@ var RunnerConnection = class {
|
|
|
1903
2353
|
}
|
|
1904
2354
|
};
|
|
1905
2355
|
|
|
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
|
+
}
|
|
2366
|
+
}
|
|
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
|
+
};
|
|
2386
|
+
}
|
|
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
|
+
});
|
|
2412
|
+
}
|
|
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
|
+
});
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
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;
|
|
2480
|
+
}
|
|
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
|
+
|
|
1906
2793
|
// src/lib/channels/driver.ts
|
|
1907
2794
|
function messageIdOf(m) {
|
|
1908
2795
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -1931,7 +2818,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
1931
2818
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
1932
2819
|
var HEARTBEAT_MS = 6e4;
|
|
1933
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;
|
|
1934
2823
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2824
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
1935
2825
|
var ChannelAuthError = class extends Error {
|
|
1936
2826
|
constructor(message) {
|
|
1937
2827
|
super(message);
|
|
@@ -1954,7 +2844,7 @@ function backoffDelay(attempt, policy) {
|
|
|
1954
2844
|
function isRetryableStatus(status) {
|
|
1955
2845
|
return status === 429 || status >= 500 && status <= 599;
|
|
1956
2846
|
}
|
|
1957
|
-
var ChannelDriver = class {
|
|
2847
|
+
var ChannelDriver = class _ChannelDriver {
|
|
1958
2848
|
agentId;
|
|
1959
2849
|
port;
|
|
1960
2850
|
apiUrl;
|
|
@@ -1968,8 +2858,38 @@ var ChannelDriver = class {
|
|
|
1968
2858
|
pausedMaxWaitMs;
|
|
1969
2859
|
stuckQueuedMs;
|
|
1970
2860
|
now;
|
|
2861
|
+
fileSyncDirectories;
|
|
2862
|
+
homeDir;
|
|
1971
2863
|
/** Cache of conversationId → opencode sessionId. */
|
|
1972
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();
|
|
1973
2893
|
/**
|
|
1974
2894
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
1975
2895
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2079,9 +2999,12 @@ var ChannelDriver = class {
|
|
|
2079
2999
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2080
3000
|
/**
|
|
2081
3001
|
* Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
|
|
2082
|
-
* NON-EMPTY name is stored (terminal — a real session name
|
|
2083
|
-
* so we do NOT re-GET `/session/:id` every tick.
|
|
2084
|
-
*
|
|
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
|
|
2085
3008
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2086
3009
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2087
3010
|
* no watcher) can resolve the title.
|
|
@@ -2089,6 +3012,24 @@ var ChannelDriver = class {
|
|
|
2089
3012
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2090
3013
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2091
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;
|
|
2092
3033
|
/**
|
|
2093
3034
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2094
3035
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2119,6 +3060,8 @@ var ChannelDriver = class {
|
|
|
2119
3060
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2120
3061
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2121
3062
|
this.now = config2.now ?? (() => Date.now());
|
|
3063
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
3064
|
+
this.homeDir = config2.homeDir ?? homedir2();
|
|
2122
3065
|
}
|
|
2123
3066
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2124
3067
|
get opencodeBase() {
|
|
@@ -2146,6 +3089,47 @@ var ChannelDriver = class {
|
|
|
2146
3089
|
);
|
|
2147
3090
|
return run2;
|
|
2148
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
|
+
}
|
|
2149
3133
|
async runDrain() {
|
|
2150
3134
|
let dispatched = 0;
|
|
2151
3135
|
try {
|
|
@@ -2179,6 +3163,28 @@ var ChannelDriver = class {
|
|
|
2179
3163
|
}
|
|
2180
3164
|
return false;
|
|
2181
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
|
+
}
|
|
2182
3188
|
/**
|
|
2183
3189
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2184
3190
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2240,7 +3246,7 @@ var ChannelDriver = class {
|
|
|
2240
3246
|
await this.sleep(step);
|
|
2241
3247
|
}
|
|
2242
3248
|
}
|
|
2243
|
-
while (this.hasInFlightWatchers()) {
|
|
3249
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2244
3250
|
if (this.now() >= deadline) return false;
|
|
2245
3251
|
await this.sleep(step);
|
|
2246
3252
|
}
|
|
@@ -2275,10 +3281,15 @@ var ChannelDriver = class {
|
|
|
2275
3281
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2276
3282
|
*/
|
|
2277
3283
|
async processConversation(conv) {
|
|
2278
|
-
const sessionId = await this.ensureSession(conv);
|
|
3284
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2279
3285
|
const messages = await this.getPendingMessages(conv.id);
|
|
2280
3286
|
let dispatched = 0;
|
|
2281
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
|
+
}
|
|
2282
3293
|
for (const message of messages) {
|
|
2283
3294
|
if (this.stopped) break;
|
|
2284
3295
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2305,7 +3316,8 @@ var ChannelDriver = class {
|
|
|
2305
3316
|
} catch (err) {
|
|
2306
3317
|
if (err instanceof ChannelAuthError) throw err;
|
|
2307
3318
|
this.dispatched.delete(message.id);
|
|
2308
|
-
|
|
3319
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
3320
|
+
if (exists === false) {
|
|
2309
3321
|
this.sessions.delete(conv.id);
|
|
2310
3322
|
this.log({
|
|
2311
3323
|
level: "warn",
|
|
@@ -2315,15 +3327,39 @@ var ChannelDriver = class {
|
|
|
2315
3327
|
});
|
|
2316
3328
|
break;
|
|
2317
3329
|
}
|
|
2318
|
-
|
|
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
|
+
});
|
|
2319
3355
|
});
|
|
2320
3356
|
this.log({
|
|
2321
3357
|
level: "error",
|
|
2322
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3358
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2323
3359
|
conversation_id: conv.id,
|
|
2324
3360
|
message_id: message.id
|
|
2325
3361
|
});
|
|
2326
|
-
|
|
3362
|
+
break;
|
|
2327
3363
|
}
|
|
2328
3364
|
if (opencodeMessageId === null) {
|
|
2329
3365
|
this.log({
|
|
@@ -2349,8 +3385,42 @@ var ChannelDriver = class {
|
|
|
2349
3385
|
this.ensureWatcherRunning(sessionId);
|
|
2350
3386
|
return dispatched;
|
|
2351
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
|
+
*/
|
|
2352
3413
|
async ensureSession(conv) {
|
|
2353
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
|
+
}
|
|
2354
3424
|
if (bound) {
|
|
2355
3425
|
const exists = await sessionExists(this.port, bound);
|
|
2356
3426
|
if (exists === false) {
|
|
@@ -2360,12 +3430,12 @@ var ChannelDriver = class {
|
|
|
2360
3430
|
conversation_id: conv.id
|
|
2361
3431
|
});
|
|
2362
3432
|
this.sessions.delete(conv.id);
|
|
2363
|
-
return this.createAndBindSession(conv.id);
|
|
3433
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2364
3434
|
}
|
|
2365
3435
|
this.sessions.set(conv.id, bound);
|
|
2366
|
-
return bound;
|
|
3436
|
+
return { sessionId: bound };
|
|
2367
3437
|
}
|
|
2368
|
-
return this.createAndBindSession(conv.id);
|
|
3438
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2369
3439
|
}
|
|
2370
3440
|
/**
|
|
2371
3441
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2376,7 +3446,12 @@ var ChannelDriver = class {
|
|
|
2376
3446
|
const directory = await this.resolveOpenCodeDirectory();
|
|
2377
3447
|
const sessionId = await createOpenCodeSession(this.port, directory);
|
|
2378
3448
|
this.sessions.set(conversationId, sessionId);
|
|
2379
|
-
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
|
+
});
|
|
2380
3455
|
});
|
|
2381
3456
|
return sessionId;
|
|
2382
3457
|
}
|
|
@@ -2445,7 +3520,7 @@ var ChannelDriver = class {
|
|
|
2445
3520
|
}
|
|
2446
3521
|
/**
|
|
2447
3522
|
* Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
|
|
2448
|
-
* (`GET {apiUrl}/
|
|
3523
|
+
* (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
|
|
2449
3524
|
* existing authenticated fetch, and base64-encode into a
|
|
2450
3525
|
* `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
|
|
2451
3526
|
*
|
|
@@ -2453,15 +3528,38 @@ var ChannelDriver = class {
|
|
|
2453
3528
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2454
3529
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2455
3530
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2456
|
-
*
|
|
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).
|
|
2457
3536
|
*/
|
|
2458
3537
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2459
3538
|
try {
|
|
2460
3539
|
const res = await this.fetchImpl(
|
|
2461
|
-
`${this.apiUrl}/
|
|
3540
|
+
`${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
|
|
2462
3541
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2463
3542
|
);
|
|
2464
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
|
+
}
|
|
2465
3563
|
this.log({
|
|
2466
3564
|
level: "error",
|
|
2467
3565
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2501,6 +3599,9 @@ var ChannelDriver = class {
|
|
|
2501
3599
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2502
3600
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2503
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;
|
|
2504
3605
|
this.log({
|
|
2505
3606
|
level: "info",
|
|
2506
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`,
|
|
@@ -2510,7 +3611,8 @@ var ChannelDriver = class {
|
|
|
2510
3611
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2511
3612
|
skipped,
|
|
2512
3613
|
failed,
|
|
2513
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3614
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3615
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2514
3616
|
});
|
|
2515
3617
|
}
|
|
2516
3618
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2541,12 +3643,17 @@ var ChannelDriver = class {
|
|
|
2541
3643
|
stuckReported: false,
|
|
2542
3644
|
lastAliveAt: 0,
|
|
2543
3645
|
aliveInFlight: false,
|
|
3646
|
+
titleSynced: false,
|
|
3647
|
+
titleSyncInFlight: false,
|
|
2544
3648
|
awaitingHumanLatched: false,
|
|
2545
3649
|
pausedOnQuestion: false,
|
|
2546
3650
|
pausedOnPermission: false,
|
|
2547
3651
|
pausedClearConfirmed: false,
|
|
2548
3652
|
pausedInFlight: false,
|
|
2549
|
-
deliveryDeadlineAnchored: false
|
|
3653
|
+
deliveryDeadlineAnchored: false,
|
|
3654
|
+
b2PinnedSinceMs: 0,
|
|
3655
|
+
b2LastDescendantCheckMs: 0,
|
|
3656
|
+
b2AbandonedSignalled: false
|
|
2550
3657
|
});
|
|
2551
3658
|
}
|
|
2552
3659
|
/**
|
|
@@ -2614,12 +3721,17 @@ var ChannelDriver = class {
|
|
|
2614
3721
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
2615
3722
|
lastAliveAt: 0,
|
|
2616
3723
|
aliveInFlight: false,
|
|
3724
|
+
titleSynced: false,
|
|
3725
|
+
titleSyncInFlight: false,
|
|
2617
3726
|
awaitingHumanLatched: false,
|
|
2618
3727
|
pausedOnQuestion: false,
|
|
2619
3728
|
pausedOnPermission: false,
|
|
2620
3729
|
pausedClearConfirmed: false,
|
|
2621
3730
|
pausedInFlight: false,
|
|
2622
|
-
deliveryDeadlineAnchored: false
|
|
3731
|
+
deliveryDeadlineAnchored: false,
|
|
3732
|
+
b2PinnedSinceMs: 0,
|
|
3733
|
+
b2LastDescendantCheckMs: 0,
|
|
3734
|
+
b2AbandonedSignalled: false
|
|
2623
3735
|
});
|
|
2624
3736
|
}
|
|
2625
3737
|
/**
|
|
@@ -2781,56 +3893,7 @@ var ChannelDriver = class {
|
|
|
2781
3893
|
}
|
|
2782
3894
|
}
|
|
2783
3895
|
if (state === "done") {
|
|
2784
|
-
this.
|
|
2785
|
-
if (!inFlight.done) {
|
|
2786
|
-
this.log({
|
|
2787
|
-
level: "info",
|
|
2788
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
2789
|
-
conversation_id: conv.id,
|
|
2790
|
-
message_id: inFlight.evidentMessageId
|
|
2791
|
-
});
|
|
2792
|
-
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
2793
|
-
try {
|
|
2794
|
-
await this.markDone(
|
|
2795
|
-
conv.id,
|
|
2796
|
-
inFlight.evidentMessageId,
|
|
2797
|
-
sessionId,
|
|
2798
|
-
inFlight.opencodeMessageId,
|
|
2799
|
-
title
|
|
2800
|
-
);
|
|
2801
|
-
} catch (err) {
|
|
2802
|
-
if (err instanceof ChannelAuthError) throw err;
|
|
2803
|
-
if (err instanceof ChannelTerminalError) {
|
|
2804
|
-
this.log({
|
|
2805
|
-
level: "warn",
|
|
2806
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
2807
|
-
conversation_id: conv.id,
|
|
2808
|
-
message_id: inFlight.evidentMessageId
|
|
2809
|
-
});
|
|
2810
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2811
|
-
return;
|
|
2812
|
-
}
|
|
2813
|
-
if (this.now() >= inFlight.deadline) {
|
|
2814
|
-
this.log({
|
|
2815
|
-
level: "warn",
|
|
2816
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
|
|
2817
|
-
conversation_id: conv.id,
|
|
2818
|
-
message_id: inFlight.evidentMessageId
|
|
2819
|
-
});
|
|
2820
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2821
|
-
return;
|
|
2822
|
-
}
|
|
2823
|
-
this.log({
|
|
2824
|
-
level: "warn",
|
|
2825
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
2826
|
-
conversation_id: conv.id,
|
|
2827
|
-
message_id: inFlight.evidentMessageId
|
|
2828
|
-
});
|
|
2829
|
-
return;
|
|
2830
|
-
}
|
|
2831
|
-
inFlight.done = true;
|
|
2832
|
-
}
|
|
2833
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3896
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
2834
3897
|
return;
|
|
2835
3898
|
}
|
|
2836
3899
|
if (state === "failed") {
|
|
@@ -2843,8 +3906,17 @@ var ChannelDriver = class {
|
|
|
2843
3906
|
conversation_id: conv.id,
|
|
2844
3907
|
message_id: inFlight.evidentMessageId
|
|
2845
3908
|
});
|
|
3909
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3910
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
2846
3911
|
try {
|
|
2847
|
-
await this.markFailed(
|
|
3912
|
+
await this.markFailed(
|
|
3913
|
+
conv.id,
|
|
3914
|
+
inFlight.evidentMessageId,
|
|
3915
|
+
sessionId,
|
|
3916
|
+
error2,
|
|
3917
|
+
usage,
|
|
3918
|
+
failure
|
|
3919
|
+
);
|
|
2848
3920
|
} catch (err) {
|
|
2849
3921
|
if (err instanceof ChannelAuthError) throw err;
|
|
2850
3922
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -2889,6 +3961,44 @@ var ChannelDriver = class {
|
|
|
2889
3961
|
});
|
|
2890
3962
|
}
|
|
2891
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
|
+
}
|
|
2892
4002
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
2893
4003
|
this.log({
|
|
2894
4004
|
level: "warn",
|
|
@@ -2908,6 +4018,18 @@ var ChannelDriver = class {
|
|
|
2908
4018
|
inFlight.aliveInFlight = false;
|
|
2909
4019
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
2910
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
|
+
}
|
|
2911
4033
|
}
|
|
2912
4034
|
if (awaitingHuman) {
|
|
2913
4035
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -2945,6 +4067,70 @@ var ChannelDriver = class {
|
|
|
2945
4067
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2946
4068
|
}
|
|
2947
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;
|
|
4131
|
+
}
|
|
4132
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4133
|
+
}
|
|
2948
4134
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
2949
4135
|
/**
|
|
2950
4136
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3081,7 +4267,8 @@ var ChannelDriver = class {
|
|
|
3081
4267
|
});
|
|
3082
4268
|
try {
|
|
3083
4269
|
const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
|
|
3084
|
-
|
|
4270
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
4271
|
+
await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
|
|
3085
4272
|
} catch (err) {
|
|
3086
4273
|
if (err instanceof ChannelAuthError) throw err;
|
|
3087
4274
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3109,6 +4296,8 @@ var ChannelDriver = class {
|
|
|
3109
4296
|
}
|
|
3110
4297
|
if (state === "failed") {
|
|
3111
4298
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
4299
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
4300
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3112
4301
|
this.log({
|
|
3113
4302
|
level: "error",
|
|
3114
4303
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3116,7 +4305,7 @@ var ChannelDriver = class {
|
|
|
3116
4305
|
message_id: row.id
|
|
3117
4306
|
});
|
|
3118
4307
|
try {
|
|
3119
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2);
|
|
4308
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3120
4309
|
} catch (err) {
|
|
3121
4310
|
if (err instanceof ChannelAuthError) throw err;
|
|
3122
4311
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3522,6 +4711,47 @@ var ChannelDriver = class {
|
|
|
3522
4711
|
}
|
|
3523
4712
|
return false;
|
|
3524
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
|
+
}
|
|
3525
4755
|
/**
|
|
3526
4756
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
3527
4757
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -3544,19 +4774,36 @@ var ChannelDriver = class {
|
|
|
3544
4774
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3545
4775
|
return parent;
|
|
3546
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 - /;
|
|
3547
4790
|
/**
|
|
3548
4791
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3549
4792
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3550
4793
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3551
4794
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3552
4795
|
* Best-effort:
|
|
3553
|
-
* - 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
|
|
3554
4798
|
* won't later un-name), so we do NOT re-GET `/session/:id` every tick;
|
|
3555
|
-
* - while the title is still absent
|
|
3556
|
-
*
|
|
3557
|
-
*
|
|
3558
|
-
*
|
|
3559
|
-
*
|
|
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;
|
|
3560
4807
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3561
4808
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3562
4809
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3569,7 +4816,7 @@ var ChannelDriver = class {
|
|
|
3569
4816
|
if (res.ok) {
|
|
3570
4817
|
const body = await res.json();
|
|
3571
4818
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3572
|
-
if (title.length > 0) {
|
|
4819
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3573
4820
|
this.sessionTitles.set(sessionId, title);
|
|
3574
4821
|
return title;
|
|
3575
4822
|
}
|
|
@@ -3589,6 +4836,54 @@ var ChannelDriver = class {
|
|
|
3589
4836
|
}
|
|
3590
4837
|
return null;
|
|
3591
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
|
+
}
|
|
3592
4887
|
/**
|
|
3593
4888
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
3594
4889
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -3647,6 +4942,84 @@ var ChannelDriver = class {
|
|
|
3647
4942
|
}
|
|
3648
4943
|
return false;
|
|
3649
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
|
+
}
|
|
3650
5023
|
/**
|
|
3651
5024
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
3652
5025
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -3719,7 +5092,7 @@ var ChannelDriver = class {
|
|
|
3719
5092
|
// Evident API calls (combinedAuth thread routes)
|
|
3720
5093
|
async getPendingConversations() {
|
|
3721
5094
|
const res = await this.fetchImpl(
|
|
3722
|
-
`${this.apiUrl}/
|
|
5095
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
|
|
3723
5096
|
{
|
|
3724
5097
|
headers: { Authorization: this.getAuthHeader() }
|
|
3725
5098
|
}
|
|
@@ -3737,7 +5110,7 @@ var ChannelDriver = class {
|
|
|
3737
5110
|
}
|
|
3738
5111
|
async getPendingMessages(conversationId) {
|
|
3739
5112
|
const res = await this.fetchImpl(
|
|
3740
|
-
`${this.apiUrl}/
|
|
5113
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
|
|
3741
5114
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3742
5115
|
);
|
|
3743
5116
|
this.assertAuth(res, "fetching pending messages");
|
|
@@ -3761,7 +5134,7 @@ var ChannelDriver = class {
|
|
|
3761
5134
|
*/
|
|
3762
5135
|
async getProcessingMessages() {
|
|
3763
5136
|
const res = await this.fetchImpl(
|
|
3764
|
-
`${this.apiUrl}/
|
|
5137
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
|
|
3765
5138
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3766
5139
|
);
|
|
3767
5140
|
this.assertAuth(res, "fetching processing messages");
|
|
@@ -3775,6 +5148,32 @@ var ChannelDriver = class {
|
|
|
3775
5148
|
}
|
|
3776
5149
|
return messages;
|
|
3777
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
|
+
}
|
|
3778
5177
|
/**
|
|
3779
5178
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3780
5179
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3798,13 +5197,13 @@ var ChannelDriver = class {
|
|
|
3798
5197
|
*/
|
|
3799
5198
|
async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
3800
5199
|
const res = await this.fetchImpl(
|
|
3801
|
-
`${this.apiUrl}/
|
|
5200
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3802
5201
|
{
|
|
3803
5202
|
method: "PATCH",
|
|
3804
5203
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3805
5204
|
body: JSON.stringify({
|
|
3806
5205
|
status: "processing",
|
|
3807
|
-
|
|
5206
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3808
5207
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3809
5208
|
...title ? { title } : {}
|
|
3810
5209
|
})
|
|
@@ -3845,17 +5244,23 @@ var ChannelDriver = class {
|
|
|
3845
5244
|
* watcher retries next tick within the
|
|
3846
5245
|
* deadline, Finding 4).
|
|
3847
5246
|
*/
|
|
3848
|
-
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
5247
|
+
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
|
|
3849
5248
|
const res = await this.fetchImpl(
|
|
3850
|
-
`${this.apiUrl}/
|
|
5249
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3851
5250
|
{
|
|
3852
5251
|
method: "PATCH",
|
|
3853
5252
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3854
5253
|
body: JSON.stringify({
|
|
3855
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.
|
|
3856
5260
|
opencode_session_id: sessionId,
|
|
3857
5261
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3858
|
-
...title ? { title } : {}
|
|
5262
|
+
...title ? { title } : {},
|
|
5263
|
+
...usage ? usage : {}
|
|
3859
5264
|
})
|
|
3860
5265
|
}
|
|
3861
5266
|
);
|
|
@@ -3868,19 +5273,35 @@ var ChannelDriver = class {
|
|
|
3868
5273
|
}
|
|
3869
5274
|
/**
|
|
3870
5275
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3871
|
-
* when provided (issue #182)
|
|
3872
|
-
* `
|
|
3873
|
-
*
|
|
3874
|
-
*
|
|
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).
|
|
3875
5285
|
*/
|
|
3876
|
-
async markFailed(conversationId, messageId, sessionId, error2) {
|
|
5286
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
3877
5287
|
const body = { status: "failed" };
|
|
3878
|
-
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
|
+
}
|
|
3879
5293
|
if (error2 !== void 0) body.error = error2;
|
|
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
|
+
}
|
|
3880
5301
|
await this.callWithRetry(
|
|
3881
5302
|
"marking message as failed",
|
|
3882
5303
|
() => this.fetchImpl(
|
|
3883
|
-
`${this.apiUrl}/
|
|
5304
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3884
5305
|
{
|
|
3885
5306
|
method: "PATCH",
|
|
3886
5307
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3889,6 +5310,29 @@ var ChannelDriver = class {
|
|
|
3889
5310
|
)
|
|
3890
5311
|
);
|
|
3891
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
|
+
}
|
|
3892
5336
|
/**
|
|
3893
5337
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
3894
5338
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -3907,7 +5351,7 @@ var ChannelDriver = class {
|
|
|
3907
5351
|
async postSignal(conversationId, messageId, signal, extra) {
|
|
3908
5352
|
try {
|
|
3909
5353
|
const res = await this.fetchImpl(
|
|
3910
|
-
`${this.apiUrl}/
|
|
5354
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
|
|
3911
5355
|
{
|
|
3912
5356
|
method: "POST",
|
|
3913
5357
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3936,7 +5380,7 @@ var ChannelDriver = class {
|
|
|
3936
5380
|
}
|
|
3937
5381
|
async persistSession(conversationId, sessionId) {
|
|
3938
5382
|
const res = await this.fetchImpl(
|
|
3939
|
-
`${this.apiUrl}/
|
|
5383
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
|
|
3940
5384
|
{
|
|
3941
5385
|
method: "PATCH",
|
|
3942
5386
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3962,7 +5406,7 @@ var ChannelDriver = class {
|
|
|
3962
5406
|
await this.callWithRetry(
|
|
3963
5407
|
"reporting interactive event",
|
|
3964
5408
|
() => this.fetchImpl(
|
|
3965
|
-
`${this.apiUrl}/
|
|
5409
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
|
|
3966
5410
|
{
|
|
3967
5411
|
method: "POST",
|
|
3968
5412
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -4041,10 +5485,16 @@ var ChannelDriver = class {
|
|
|
4041
5485
|
import chalk5 from "chalk";
|
|
4042
5486
|
import ora2 from "ora";
|
|
4043
5487
|
import { select as select2 } from "@inquirer/prompts";
|
|
5488
|
+
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
4044
5489
|
async function ensureOpenCodeRunning(ctx) {
|
|
4045
5490
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
4046
5491
|
if (healthCheck.healthy) {
|
|
4047
|
-
return {
|
|
5492
|
+
return {
|
|
5493
|
+
port: ctx.port,
|
|
5494
|
+
process: null,
|
|
5495
|
+
version: healthCheck.version ?? null,
|
|
5496
|
+
notReadyReason: null
|
|
5497
|
+
};
|
|
4048
5498
|
}
|
|
4049
5499
|
const runningInstances = await findHealthyOpenCodeInstances();
|
|
4050
5500
|
if (runningInstances.length > 0) {
|
|
@@ -4065,7 +5515,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4065
5515
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4066
5516
|
console.log(
|
|
4067
5517
|
chalk5.dim(
|
|
4068
|
-
` ${getCliName()} run --
|
|
5518
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4069
5519
|
)
|
|
4070
5520
|
);
|
|
4071
5521
|
}
|
|
@@ -4085,14 +5535,22 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4085
5535
|
if (!ctx.interactive) {
|
|
4086
5536
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
4087
5537
|
const proc = await startOpenCode(ctx.port);
|
|
4088
|
-
const health = await waitForOpenCodeHealth(ctx.port,
|
|
5538
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
4089
5539
|
if (!health.healthy) {
|
|
4090
|
-
|
|
4091
|
-
|
|
4092
|
-
|
|
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
|
+
};
|
|
4093
5546
|
}
|
|
4094
5547
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
4095
|
-
return {
|
|
5548
|
+
return {
|
|
5549
|
+
port: ctx.port,
|
|
5550
|
+
process: proc,
|
|
5551
|
+
version: health.version ?? null,
|
|
5552
|
+
notReadyReason: null
|
|
5553
|
+
};
|
|
4096
5554
|
}
|
|
4097
5555
|
let port = ctx.port;
|
|
4098
5556
|
if (isPortInUse(port)) {
|
|
@@ -4145,15 +5603,15 @@ Port ${port} is already in use.`));
|
|
|
4145
5603
|
if (action === "start") {
|
|
4146
5604
|
const spinner = ora2("Starting OpenCode...").start();
|
|
4147
5605
|
const proc = await startOpenCode(port);
|
|
4148
|
-
const health = await waitForOpenCodeHealth(port,
|
|
5606
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
4149
5607
|
if (!health.healthy) {
|
|
4150
5608
|
spinner.fail("Failed to start OpenCode");
|
|
4151
5609
|
throw new Error("OpenCode failed to start");
|
|
4152
5610
|
}
|
|
4153
5611
|
spinner.stop();
|
|
4154
|
-
return { port, process: proc, version: health.version ?? null };
|
|
5612
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
4155
5613
|
}
|
|
4156
|
-
return { port, process: null, version: null };
|
|
5614
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
4157
5615
|
}
|
|
4158
5616
|
|
|
4159
5617
|
// src/commands/agent-lookup.ts
|
|
@@ -4195,19 +5653,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4195
5653
|
return { agent_id: data.agent_id };
|
|
4196
5654
|
}
|
|
4197
5655
|
return {
|
|
4198
|
-
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."
|
|
4199
5657
|
};
|
|
4200
5658
|
} catch (error2) {
|
|
4201
5659
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
4202
5660
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
4203
5661
|
}
|
|
4204
5662
|
}
|
|
5663
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
4205
5664
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4206
5665
|
const apiUrl = getApiUrlConfig();
|
|
4207
5666
|
try {
|
|
4208
|
-
const response = await fetch(`${apiUrl}/
|
|
5667
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4209
5668
|
method: "POST",
|
|
4210
|
-
headers: { Authorization: authHeader }
|
|
5669
|
+
headers: { Authorization: authHeader },
|
|
5670
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
4211
5671
|
});
|
|
4212
5672
|
if (!response.ok) {
|
|
4213
5673
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -4218,13 +5678,69 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4218
5678
|
}
|
|
4219
5679
|
return { ok: true };
|
|
4220
5680
|
} catch (error2) {
|
|
4221
|
-
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) };
|
|
4222
5738
|
}
|
|
4223
5739
|
}
|
|
4224
5740
|
async function getAgentInfo(agentId, authHeader) {
|
|
4225
5741
|
const apiUrl = getApiUrlConfig();
|
|
4226
5742
|
try {
|
|
4227
|
-
const response = await fetch(`${apiUrl}/
|
|
5743
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}`, {
|
|
4228
5744
|
headers: { Authorization: authHeader }
|
|
4229
5745
|
});
|
|
4230
5746
|
if (response.status === 401) {
|
|
@@ -4268,6 +5784,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
4268
5784
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
4269
5785
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4270
5786
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5787
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
4271
5788
|
function resolveLogLevel(options) {
|
|
4272
5789
|
const accepted = Object.keys(LOG_LEVELS);
|
|
4273
5790
|
const validate = (value, source) => {
|
|
@@ -4291,6 +5808,63 @@ function resolveLogLevel(options) {
|
|
|
4291
5808
|
}
|
|
4292
5809
|
return "info";
|
|
4293
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
|
+
}
|
|
4294
5868
|
function meetsThreshold(state, level) {
|
|
4295
5869
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4296
5870
|
}
|
|
@@ -4312,6 +5886,10 @@ function log2(state, message, level = "info") {
|
|
|
4312
5886
|
function logActivity(state, entry) {
|
|
4313
5887
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
4314
5888
|
if (!meetsThreshold(state, level)) return;
|
|
5889
|
+
forwardRunnerActivity(
|
|
5890
|
+
{ level, message: entry.message, error: entry.error },
|
|
5891
|
+
{ agentId: state.agentId, authHeader: state.authHeader }
|
|
5892
|
+
);
|
|
4315
5893
|
const fullEntry = {
|
|
4316
5894
|
...entry,
|
|
4317
5895
|
level,
|
|
@@ -4412,18 +5990,29 @@ async function handleAuthError(state, error2) {
|
|
|
4412
5990
|
async function driveChannels(state, driver) {
|
|
4413
5991
|
let idlePolls = 0;
|
|
4414
5992
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5993
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4415
5994
|
while (state.running) {
|
|
4416
5995
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4417
5996
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4418
5997
|
if (state.interactive) displayStatus(state);
|
|
4419
5998
|
await state.connection.reconnectPromise;
|
|
4420
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
|
+
);
|
|
4421
6007
|
try {
|
|
4422
6008
|
const processed = await driver.drainPending();
|
|
4423
6009
|
state.messageCount += processed;
|
|
4424
6010
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4425
6011
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4426
|
-
|
|
6012
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
6013
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
6014
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
6015
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4427
6016
|
idlePolls = 0;
|
|
4428
6017
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4429
6018
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4452,7 +6041,7 @@ async function driveChannels(state, driver) {
|
|
|
4452
6041
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4453
6042
|
if (state.interactive) displayStatus(state);
|
|
4454
6043
|
}
|
|
4455
|
-
await new Promise((
|
|
6044
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4456
6045
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4457
6046
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4458
6047
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4538,6 +6127,94 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
4538
6127
|
);
|
|
4539
6128
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
4540
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
|
+
}
|
|
4541
6218
|
async function notifyOffline(state) {
|
|
4542
6219
|
if (!state.agentId || !state.authHeader) return;
|
|
4543
6220
|
if (!state.connected) {
|
|
@@ -4555,13 +6232,28 @@ async function notifyOffline(state) {
|
|
|
4555
6232
|
if (state.interactive) displayStatus(state);
|
|
4556
6233
|
}
|
|
4557
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
|
+
}
|
|
4558
6245
|
async function cleanup(state, opts = {}) {
|
|
6246
|
+
const durations = {};
|
|
4559
6247
|
state.running = false;
|
|
4560
6248
|
for (const timer of state.sessionCleanupTimers) {
|
|
4561
6249
|
clearInterval(timer);
|
|
4562
6250
|
clearTimeout(timer);
|
|
4563
6251
|
}
|
|
4564
6252
|
state.sessionCleanupTimers = [];
|
|
6253
|
+
if (state.claudeUsageTimer) {
|
|
6254
|
+
clearTimeout(state.claudeUsageTimer);
|
|
6255
|
+
state.claudeUsageTimer = null;
|
|
6256
|
+
}
|
|
4565
6257
|
if (opts.graceful && state.channelDriver) {
|
|
4566
6258
|
state.channelDriver.stop();
|
|
4567
6259
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -4569,7 +6261,13 @@ async function cleanup(state, opts = {}) {
|
|
|
4569
6261
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4570
6262
|
displayStatus(state);
|
|
4571
6263
|
}
|
|
4572
|
-
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
|
+
);
|
|
4573
6271
|
if (!settled) {
|
|
4574
6272
|
logActivity(state, {
|
|
4575
6273
|
type: "info",
|
|
@@ -4578,13 +6276,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4578
6276
|
if (state.interactive) displayStatus(state);
|
|
4579
6277
|
}
|
|
4580
6278
|
}
|
|
4581
|
-
await notifyOffline(state);
|
|
6279
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
4582
6280
|
if (state.connection) {
|
|
4583
|
-
state.connection
|
|
6281
|
+
const connection = state.connection;
|
|
6282
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
4584
6283
|
state.connection = null;
|
|
4585
6284
|
}
|
|
4586
6285
|
if (state.opencodeProcess) {
|
|
4587
|
-
|
|
6286
|
+
const opencodeProcess = state.opencodeProcess;
|
|
6287
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
4588
6288
|
if (state.interactive) {
|
|
4589
6289
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
4590
6290
|
displayStatus(state);
|
|
@@ -4593,12 +6293,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4593
6293
|
}
|
|
4594
6294
|
state.opencodeProcess = null;
|
|
4595
6295
|
}
|
|
6296
|
+
return durations;
|
|
4596
6297
|
}
|
|
4597
6298
|
async function run(options) {
|
|
4598
6299
|
const interactive = isInteractive(options.json);
|
|
4599
6300
|
let logLevel;
|
|
6301
|
+
let fileSyncDirectories;
|
|
4600
6302
|
try {
|
|
4601
6303
|
logLevel = resolveLogLevel(options);
|
|
6304
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
4602
6305
|
} catch (error2) {
|
|
4603
6306
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4604
6307
|
if (options.json) {
|
|
@@ -4611,7 +6314,7 @@ async function run(options) {
|
|
|
4611
6314
|
return;
|
|
4612
6315
|
}
|
|
4613
6316
|
const state = {
|
|
4614
|
-
agentId: options.agent || "",
|
|
6317
|
+
agentId: options.runner || options.agent || "",
|
|
4615
6318
|
agentName: null,
|
|
4616
6319
|
port: options.port ?? 4096,
|
|
4617
6320
|
conversationFilter: options.conversation ?? null,
|
|
@@ -4631,8 +6334,28 @@ async function run(options) {
|
|
|
4631
6334
|
messageCount: 0,
|
|
4632
6335
|
lastProxiedActivityAt: null,
|
|
4633
6336
|
sessionCleanupTimers: [],
|
|
6337
|
+
claudeUsageTimer: null,
|
|
4634
6338
|
authHeader: ""
|
|
4635
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
|
+
}
|
|
6346
|
+
if (!options.runner && options.agent) {
|
|
6347
|
+
telemetry.info(
|
|
6348
|
+
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
6349
|
+
"Deprecated --agent flag used instead of --runner",
|
|
6350
|
+
{ command: "run" },
|
|
6351
|
+
state.agentId
|
|
6352
|
+
);
|
|
6353
|
+
const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
|
|
6354
|
+
log2(state, agentFlagNotice, "warn");
|
|
6355
|
+
if (state.interactive && !state.json) {
|
|
6356
|
+
logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
|
|
6357
|
+
}
|
|
6358
|
+
}
|
|
4636
6359
|
if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
|
|
4637
6360
|
log2(
|
|
4638
6361
|
state,
|
|
@@ -4643,14 +6366,38 @@ async function run(options) {
|
|
|
4643
6366
|
const handleSignal = async () => {
|
|
4644
6367
|
if (state.shuttingDown) return;
|
|
4645
6368
|
state.shuttingDown = true;
|
|
6369
|
+
const shutdownStartedAt = Date.now();
|
|
4646
6370
|
if (state.interactive) {
|
|
4647
6371
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
4648
6372
|
displayStatus(state);
|
|
4649
6373
|
} else {
|
|
4650
6374
|
log2(state, "Shutting down...");
|
|
4651
6375
|
}
|
|
4652
|
-
await cleanup(state, { graceful: true });
|
|
4653
|
-
|
|
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})`);
|
|
4654
6401
|
process.exit(0);
|
|
4655
6402
|
};
|
|
4656
6403
|
process.on("SIGINT", handleSignal);
|
|
@@ -4661,7 +6408,9 @@ async function run(options) {
|
|
|
4661
6408
|
if (!interactive) {
|
|
4662
6409
|
printError("Authentication required");
|
|
4663
6410
|
blank();
|
|
4664
|
-
console.log(
|
|
6411
|
+
console.log(
|
|
6412
|
+
chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
|
|
6413
|
+
);
|
|
4665
6414
|
console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
|
|
4666
6415
|
blank();
|
|
4667
6416
|
process.exit(1);
|
|
@@ -4675,6 +6424,25 @@ async function run(options) {
|
|
|
4675
6424
|
);
|
|
4676
6425
|
}
|
|
4677
6426
|
state.authHeader = getAuthHeader(credentials2);
|
|
6427
|
+
if (credentials2.notice) {
|
|
6428
|
+
log2(state, credentials2.notice, "warn");
|
|
6429
|
+
if (state.interactive && !state.json) {
|
|
6430
|
+
logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
|
|
6431
|
+
}
|
|
6432
|
+
}
|
|
6433
|
+
if (credentials2.keySource === "agent_key") {
|
|
6434
|
+
telemetry.info(
|
|
6435
|
+
EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
|
|
6436
|
+
"Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
|
|
6437
|
+
{ command: "run" },
|
|
6438
|
+
state.agentId
|
|
6439
|
+
);
|
|
6440
|
+
const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
|
|
6441
|
+
log2(state, agentKeyNotice, "warn");
|
|
6442
|
+
if (state.interactive && !state.json) {
|
|
6443
|
+
logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
|
|
6444
|
+
}
|
|
6445
|
+
}
|
|
4678
6446
|
if (!state.agentId) {
|
|
4679
6447
|
if (credentials2.authType === "agent_key") {
|
|
4680
6448
|
const resolved = await resolveAgentIdFromKey(state.authHeader);
|
|
@@ -4692,9 +6460,15 @@ async function run(options) {
|
|
|
4692
6460
|
process.exit(1);
|
|
4693
6461
|
}
|
|
4694
6462
|
} else {
|
|
4695
|
-
printError(
|
|
6463
|
+
printError(
|
|
6464
|
+
"--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
|
|
6465
|
+
);
|
|
4696
6466
|
blank();
|
|
4697
|
-
console.log(
|
|
6467
|
+
console.log(
|
|
6468
|
+
chalk6.dim(
|
|
6469
|
+
"Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
|
|
6470
|
+
)
|
|
6471
|
+
);
|
|
4698
6472
|
blank();
|
|
4699
6473
|
process.exit(1);
|
|
4700
6474
|
}
|
|
@@ -4737,25 +6511,67 @@ async function run(options) {
|
|
|
4737
6511
|
}
|
|
4738
6512
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
4739
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
|
+
}
|
|
4740
6533
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
4741
6534
|
try {
|
|
4742
6535
|
const oc = await ensureOpenCodeRunning({
|
|
4743
6536
|
port: state.port,
|
|
4744
6537
|
interactive: state.interactive,
|
|
4745
6538
|
agentId: state.agentId,
|
|
4746
|
-
log: (message) => log2(state, message)
|
|
6539
|
+
log: (message) => log2(state, message),
|
|
6540
|
+
startTimeoutMs: opencodeStartTimeoutMs
|
|
4747
6541
|
});
|
|
4748
6542
|
state.port = oc.port;
|
|
4749
6543
|
state.opencodeProcess = oc.process;
|
|
4750
6544
|
state.opencodeVersion = oc.version;
|
|
4751
|
-
state.opencodeConnected = oc.
|
|
6545
|
+
state.opencodeConnected = oc.notReadyReason === null;
|
|
4752
6546
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
4753
6547
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
4754
|
-
|
|
4755
|
-
|
|
4756
|
-
|
|
4757
|
-
|
|
4758
|
-
|
|
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
|
+
}
|
|
4759
6575
|
}
|
|
4760
6576
|
}
|
|
4761
6577
|
} catch (error2) {
|
|
@@ -4770,6 +6586,10 @@ async function run(options) {
|
|
|
4770
6586
|
getAuthHeader: () => state.authHeader,
|
|
4771
6587
|
conversationFilter: state.conversationFilter,
|
|
4772
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(),
|
|
4773
6593
|
log: (entry) => (
|
|
4774
6594
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4775
6595
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4796,6 +6616,18 @@ async function run(options) {
|
|
|
4796
6616
|
type: "info",
|
|
4797
6617
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
4798
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
|
+
}
|
|
4799
6631
|
emitAgentConnected(state.agentId, {
|
|
4800
6632
|
port: state.port,
|
|
4801
6633
|
cli_version: getCliVersion(),
|
|
@@ -4851,6 +6683,12 @@ async function run(options) {
|
|
|
4851
6683
|
onDrainPing: () => {
|
|
4852
6684
|
if (!state.running) return;
|
|
4853
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
|
+
);
|
|
4854
6692
|
channelDriver.drainPending().then((processed) => {
|
|
4855
6693
|
if (processed > 0) {
|
|
4856
6694
|
state.messageCount += processed;
|
|
@@ -4880,6 +6718,7 @@ async function run(options) {
|
|
|
4880
6718
|
throw error2;
|
|
4881
6719
|
}
|
|
4882
6720
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6721
|
+
scheduleClaudeUsageReporting(state, options);
|
|
4883
6722
|
if (!interactive || state.json) {
|
|
4884
6723
|
log2(state, "Driving channel messages...");
|
|
4885
6724
|
}
|
|
@@ -4909,7 +6748,7 @@ async function run(options) {
|
|
|
4909
6748
|
}
|
|
4910
6749
|
telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
|
|
4911
6750
|
command: "run",
|
|
4912
|
-
agentId: options.agent
|
|
6751
|
+
agentId: options.runner || options.agent
|
|
4913
6752
|
});
|
|
4914
6753
|
await shutdownTelemetry();
|
|
4915
6754
|
process.exit(1);
|
|
@@ -4934,10 +6773,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
4934
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);
|
|
4935
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 }));
|
|
4936
6775
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
4937
|
-
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(
|
|
4938
6781
|
"--log-level <level>",
|
|
4939
6782
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
4940
|
-
).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(
|
|
4941
6787
|
"--session-cleanup-max-age <duration>",
|
|
4942
6788
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
4943
6789
|
).option(
|
|
@@ -4946,10 +6792,22 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4946
6792
|
).option(
|
|
4947
6793
|
"--session-cleanup-interval <duration>",
|
|
4948
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)"
|
|
4949
6806
|
).action(
|
|
4950
6807
|
(options) => {
|
|
4951
6808
|
run({
|
|
4952
6809
|
agent: options.agent,
|
|
6810
|
+
runner: options.runner,
|
|
4953
6811
|
port: parseInt(options.port, 10),
|
|
4954
6812
|
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
4955
6813
|
// resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
|
|
@@ -4957,11 +6815,21 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4957
6815
|
verbose: options.verbose,
|
|
4958
6816
|
conversation: options.conversation,
|
|
4959
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,
|
|
4960
6821
|
json: options.json,
|
|
4961
6822
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
4962
6823
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
4963
6824
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
4964
|
-
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
|
|
4965
6833
|
});
|
|
4966
6834
|
}
|
|
4967
6835
|
);
|