@evident-ai/cli 3.1.1-dev.bf45828 → 3.1.1-dev.c0fca20
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 +19 -11
- package/dist/index.js +1618 -154
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -11,8 +11,8 @@ import chalk2 from "chalk";
|
|
|
11
11
|
|
|
12
12
|
// src/lib/config.ts
|
|
13
13
|
import Conf from "conf";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
14
|
+
import { chmodSync, existsSync, statSync } from "fs";
|
|
15
|
+
import { dirname } from "path";
|
|
16
16
|
var PRODUCTION_API_URL = "https://api.production.evident.run/v1";
|
|
17
17
|
var PRODUCTION_TUNNEL_URL = "wss://tunnel.production.evident.run";
|
|
18
18
|
var defaults = {
|
|
@@ -47,8 +47,35 @@ var credentials = new Conf({
|
|
|
47
47
|
projectName: "evident",
|
|
48
48
|
projectSuffix: "",
|
|
49
49
|
configName: "credentials",
|
|
50
|
-
defaults: {}
|
|
50
|
+
defaults: {},
|
|
51
|
+
configFileMode: 384
|
|
51
52
|
});
|
|
53
|
+
var CREDENTIALS_FILE_MODE = 384;
|
|
54
|
+
var CREDENTIALS_DIR_MODE = 448;
|
|
55
|
+
var permissionWarningEmitted = false;
|
|
56
|
+
function hardenCredentialsPermissions() {
|
|
57
|
+
if (process.platform === "win32") {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const file = credentials.path;
|
|
61
|
+
for (const [path, mode] of [
|
|
62
|
+
[file, CREDENTIALS_FILE_MODE],
|
|
63
|
+
[dirname(file), CREDENTIALS_DIR_MODE]
|
|
64
|
+
]) {
|
|
65
|
+
try {
|
|
66
|
+
if (existsSync(path) && (statSync(path).mode & 511) !== mode) {
|
|
67
|
+
chmodSync(path, mode);
|
|
68
|
+
}
|
|
69
|
+
} catch (err) {
|
|
70
|
+
if (!permissionWarningEmitted) {
|
|
71
|
+
permissionWarningEmitted = true;
|
|
72
|
+
console.error(
|
|
73
|
+
`[config] could not restrict permissions on ${path}; the credentials file may be readable by other users on this machine: ${err instanceof Error ? err.message : String(err)}`
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
52
79
|
function getApiUrlConfig() {
|
|
53
80
|
return getApiUrl();
|
|
54
81
|
}
|
|
@@ -59,6 +86,7 @@ function credentialsKey() {
|
|
|
59
86
|
return getApiUrl();
|
|
60
87
|
}
|
|
61
88
|
function getCredentials() {
|
|
89
|
+
hardenCredentialsPermissions();
|
|
62
90
|
const byEndpoint = credentials.get("byEndpoint") ?? {};
|
|
63
91
|
return byEndpoint[credentialsKey()] ?? {};
|
|
64
92
|
}
|
|
@@ -70,14 +98,17 @@ function setCredentials(creds) {
|
|
|
70
98
|
expiresAt: creds.expiresAt
|
|
71
99
|
};
|
|
72
100
|
credentials.set("byEndpoint", byEndpoint);
|
|
101
|
+
hardenCredentialsPermissions();
|
|
73
102
|
}
|
|
74
103
|
function clearCredentials() {
|
|
75
104
|
const byEndpoint = credentials.get("byEndpoint") ?? {};
|
|
76
105
|
delete byEndpoint[credentialsKey()];
|
|
77
106
|
credentials.set("byEndpoint", byEndpoint);
|
|
107
|
+
hardenCredentialsPermissions();
|
|
78
108
|
}
|
|
79
109
|
function clearAllCredentials() {
|
|
80
110
|
credentials.clear();
|
|
111
|
+
hardenCredentialsPermissions();
|
|
81
112
|
}
|
|
82
113
|
function getCliName() {
|
|
83
114
|
const argv1 = process.argv[1] || "";
|
|
@@ -236,16 +267,28 @@ async function getToken() {
|
|
|
236
267
|
}
|
|
237
268
|
return null;
|
|
238
269
|
}
|
|
270
|
+
function toError(err) {
|
|
271
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
272
|
+
}
|
|
239
273
|
async function deleteToken(options = {}) {
|
|
240
274
|
const keytar = await getKeytar();
|
|
275
|
+
const failures = [];
|
|
241
276
|
if (keytar) {
|
|
242
277
|
if (options.all) {
|
|
243
|
-
|
|
278
|
+
let accounts = [];
|
|
279
|
+
try {
|
|
280
|
+
accounts = await keytar.findCredentials(SERVICE_NAME);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
failures.push({ type: "enumerate", error: toError(err) });
|
|
283
|
+
}
|
|
244
284
|
await Promise.all(
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
285
|
+
accounts.map(async (entry) => {
|
|
286
|
+
try {
|
|
287
|
+
await keytar.deletePassword(SERVICE_NAME, entry.account);
|
|
288
|
+
} catch (err) {
|
|
289
|
+
failures.push({ type: "delete", account: entry.account, error: toError(err) });
|
|
290
|
+
}
|
|
291
|
+
})
|
|
249
292
|
);
|
|
250
293
|
} else {
|
|
251
294
|
await keytar.deletePassword(SERVICE_NAME, keychainAccount());
|
|
@@ -256,6 +299,7 @@ async function deleteToken(options = {}) {
|
|
|
256
299
|
} else {
|
|
257
300
|
clearCredentials();
|
|
258
301
|
}
|
|
302
|
+
return { failures };
|
|
259
303
|
}
|
|
260
304
|
|
|
261
305
|
// src/utils/ui.ts
|
|
@@ -285,14 +329,14 @@ function blank() {
|
|
|
285
329
|
console.log();
|
|
286
330
|
}
|
|
287
331
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
288
|
-
return new Promise((
|
|
332
|
+
return new Promise((resolve3) => {
|
|
289
333
|
process.stdout.write(chalk.dim(prompt));
|
|
290
334
|
const handler = () => {
|
|
291
335
|
process.stdin.removeListener("data", handler);
|
|
292
336
|
process.stdin.setRawMode?.(false);
|
|
293
337
|
process.stdin.pause();
|
|
294
338
|
console.log();
|
|
295
|
-
|
|
339
|
+
resolve3();
|
|
296
340
|
};
|
|
297
341
|
if (process.stdin.isTTY) {
|
|
298
342
|
process.stdin.setRawMode?.(true);
|
|
@@ -302,7 +346,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
302
346
|
});
|
|
303
347
|
}
|
|
304
348
|
function sleep(ms) {
|
|
305
|
-
return new Promise((
|
|
349
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
306
350
|
}
|
|
307
351
|
|
|
308
352
|
// src/commands/login.ts
|
|
@@ -373,22 +417,23 @@ async function deviceFlowLogin(options) {
|
|
|
373
417
|
}
|
|
374
418
|
async function tokenLogin() {
|
|
375
419
|
console.log("Token login mode.");
|
|
376
|
-
console.log("
|
|
420
|
+
console.log("Run `evident login` on a machine with a browser to get a token.");
|
|
421
|
+
console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
|
|
377
422
|
blank();
|
|
378
423
|
process.stdout.write("Paste token: ");
|
|
379
|
-
const token = await new Promise((
|
|
424
|
+
const token = await new Promise((resolve3) => {
|
|
380
425
|
let data = "";
|
|
381
426
|
process.stdin.setEncoding("utf8");
|
|
382
427
|
process.stdin.on("data", (chunk) => {
|
|
383
428
|
data += chunk;
|
|
384
429
|
});
|
|
385
430
|
process.stdin.on("end", () => {
|
|
386
|
-
|
|
431
|
+
resolve3(data.trim());
|
|
387
432
|
});
|
|
388
433
|
if (process.stdin.isTTY) {
|
|
389
434
|
process.stdin.once("data", (chunk) => {
|
|
390
435
|
process.stdin.pause();
|
|
391
|
-
|
|
436
|
+
resolve3(chunk.toString().trim());
|
|
392
437
|
});
|
|
393
438
|
process.stdin.resume();
|
|
394
439
|
}
|
|
@@ -423,9 +468,22 @@ async function login(options) {
|
|
|
423
468
|
}
|
|
424
469
|
|
|
425
470
|
// src/commands/logout.ts
|
|
471
|
+
function describeFailure(failure) {
|
|
472
|
+
if (failure.type === "enumerate") {
|
|
473
|
+
return `could not list stored keychain entries (${failure.error.message})`;
|
|
474
|
+
}
|
|
475
|
+
return `${failure.account} (${failure.error.message})`;
|
|
476
|
+
}
|
|
426
477
|
async function logout(options = {}) {
|
|
427
478
|
if (options.all) {
|
|
428
|
-
await deleteToken({ all: true });
|
|
479
|
+
const result = await deleteToken({ all: true });
|
|
480
|
+
if (result.failures.length > 0) {
|
|
481
|
+
printError(
|
|
482
|
+
`Failed to fully clear your keychain: ${result.failures.map(describeFailure).join("; ")}. Your local credentials file was cleared, but stale keychain entries may remain \u2014 run \`evident logout --all\` again, or remove them manually from your OS keychain / credential manager.`
|
|
483
|
+
);
|
|
484
|
+
process.exitCode = 1;
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
429
487
|
printSuccess("Logged out of all endpoints.");
|
|
430
488
|
return;
|
|
431
489
|
}
|
|
@@ -467,9 +525,9 @@ async function whoami() {
|
|
|
467
525
|
}
|
|
468
526
|
|
|
469
527
|
// src/commands/run.ts
|
|
528
|
+
import { homedir as homedir2 } from "os";
|
|
529
|
+
import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
|
|
470
530
|
import chalk6 from "chalk";
|
|
471
|
-
import ora3 from "ora";
|
|
472
|
-
import { select as select3 } from "@inquirer/prompts";
|
|
473
531
|
|
|
474
532
|
// ../../packages/types/src/telemetry/index.ts
|
|
475
533
|
var TelemetryEventTypes = {
|
|
@@ -478,13 +536,20 @@ var TelemetryEventTypes = {
|
|
|
478
536
|
AGENT_DISCONNECTED: "agent.disconnected",
|
|
479
537
|
AGENT_MESSAGE_PROCESSING: "agent.message_processing",
|
|
480
538
|
AGENT_MESSAGE_DONE: "agent.message_done",
|
|
481
|
-
AGENT_MESSAGE_FAILED: "agent.message_failed"
|
|
539
|
+
AGENT_MESSAGE_FAILED: "agent.message_failed",
|
|
540
|
+
// A `warn`/`error` runner-side log line forwarded server-side for
|
|
541
|
+
// observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
|
|
542
|
+
RUNNER_ACTIVITY: "runner.activity"
|
|
482
543
|
};
|
|
483
544
|
|
|
484
545
|
// ../../packages/types/src/tunnel/index.ts
|
|
485
546
|
var MAX_FRAME_BYTES = 256 * 1024;
|
|
486
547
|
var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
|
|
487
548
|
|
|
549
|
+
// ../../packages/types/src/runner-files.ts
|
|
550
|
+
var MAX_FILE_PUSH_BYTES = 64 * 1024;
|
|
551
|
+
var MAX_FILE_SYNC_DIRECTORIES = 16;
|
|
552
|
+
|
|
488
553
|
// ../../packages/types/src/logging/index.ts
|
|
489
554
|
var CORRELATION_ID_HEADER = "x-evident-correlation-id";
|
|
490
555
|
function log(level, event, fields) {
|
|
@@ -499,6 +564,12 @@ function log(level, event, fields) {
|
|
|
499
564
|
);
|
|
500
565
|
}
|
|
501
566
|
}
|
|
567
|
+
function errorFields(err) {
|
|
568
|
+
if (err instanceof Error) {
|
|
569
|
+
return { error: err.message, error_name: err.name };
|
|
570
|
+
}
|
|
571
|
+
return { error: String(err) };
|
|
572
|
+
}
|
|
502
573
|
function stripQuery(url) {
|
|
503
574
|
try {
|
|
504
575
|
return new URL(url).pathname;
|
|
@@ -508,6 +579,10 @@ function stripQuery(url) {
|
|
|
508
579
|
}
|
|
509
580
|
}
|
|
510
581
|
|
|
582
|
+
// src/commands/run.ts
|
|
583
|
+
import ora3 from "ora";
|
|
584
|
+
import { select as select3 } from "@inquirer/prompts";
|
|
585
|
+
|
|
511
586
|
// src/lib/telemetry.ts
|
|
512
587
|
var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
513
588
|
function getCliVersion() {
|
|
@@ -519,6 +594,13 @@ var isShuttingDown = false;
|
|
|
519
594
|
var FLUSH_INTERVAL_MS = 5e3;
|
|
520
595
|
var MAX_BUFFER_SIZE = 50;
|
|
521
596
|
var FLUSH_TIMEOUT_MS = 3e3;
|
|
597
|
+
var authProvider = null;
|
|
598
|
+
function setTelemetryAuthProvider(provider) {
|
|
599
|
+
authProvider = provider;
|
|
600
|
+
}
|
|
601
|
+
var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
|
|
602
|
+
var lastFlushFailureLoggedAt = 0;
|
|
603
|
+
var suppressedFlushFailureCount = 0;
|
|
522
604
|
function logEvent(eventType, options = {}) {
|
|
523
605
|
const event = {
|
|
524
606
|
event_type: eventType,
|
|
@@ -553,9 +635,16 @@ async function flushEvents() {
|
|
|
553
635
|
flushTimeout = null;
|
|
554
636
|
}
|
|
555
637
|
try {
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
|
|
638
|
+
const providerContext = authProvider?.();
|
|
639
|
+
let authHeader;
|
|
640
|
+
if (providerContext?.authHeader) {
|
|
641
|
+
authHeader = providerContext.authHeader;
|
|
642
|
+
} else {
|
|
643
|
+
const credentials2 = await getToken();
|
|
644
|
+
if (!credentials2) {
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
authHeader = `Bearer ${credentials2.token}`;
|
|
559
648
|
}
|
|
560
649
|
const apiUrl = getApiUrlConfig();
|
|
561
650
|
const controller = new AbortController();
|
|
@@ -570,7 +659,7 @@ async function flushEvents() {
|
|
|
570
659
|
method: "POST",
|
|
571
660
|
headers: {
|
|
572
661
|
"Content-Type": "application/json",
|
|
573
|
-
Authorization:
|
|
662
|
+
Authorization: authHeader
|
|
574
663
|
},
|
|
575
664
|
body: JSON.stringify(request),
|
|
576
665
|
signal: controller.signal
|
|
@@ -582,8 +671,15 @@ async function flushEvents() {
|
|
|
582
671
|
clearTimeout(timeout);
|
|
583
672
|
}
|
|
584
673
|
} catch (error2) {
|
|
585
|
-
|
|
586
|
-
|
|
674
|
+
const now = Date.now();
|
|
675
|
+
if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
|
|
676
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
677
|
+
const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
|
|
678
|
+
console.error(`Telemetry flush error: ${message}${suffix}`);
|
|
679
|
+
lastFlushFailureLoggedAt = now;
|
|
680
|
+
suppressedFlushFailureCount = 0;
|
|
681
|
+
} else {
|
|
682
|
+
suppressedFlushFailureCount++;
|
|
587
683
|
}
|
|
588
684
|
}
|
|
589
685
|
}
|
|
@@ -652,6 +748,69 @@ var EventTypes = {
|
|
|
652
748
|
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
653
749
|
};
|
|
654
750
|
|
|
751
|
+
// src/lib/runner-activity-telemetry.ts
|
|
752
|
+
var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
|
|
753
|
+
var SEVERITY_BY_LEVEL = {
|
|
754
|
+
warn: "warning",
|
|
755
|
+
error: "error"
|
|
756
|
+
};
|
|
757
|
+
var MAX_MESSAGE_LENGTH = 500;
|
|
758
|
+
var TRUNCATION_MARKER = "\u2026";
|
|
759
|
+
function redact(message) {
|
|
760
|
+
return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
761
|
+
}
|
|
762
|
+
function truncate(message) {
|
|
763
|
+
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
764
|
+
return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
|
|
765
|
+
}
|
|
766
|
+
var RATE_LIMIT_WINDOW_MS = 6e4;
|
|
767
|
+
var RATE_LIMIT_MAX_EVENTS = 30;
|
|
768
|
+
var windowStartedAt = 0;
|
|
769
|
+
var windowCount = 0;
|
|
770
|
+
var windowDroppedCount = 0;
|
|
771
|
+
function admitUnderRateLimit(now) {
|
|
772
|
+
if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
|
|
773
|
+
if (windowDroppedCount > 0) {
|
|
774
|
+
console.error(
|
|
775
|
+
`[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)`
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
windowStartedAt = now;
|
|
779
|
+
windowCount = 0;
|
|
780
|
+
windowDroppedCount = 0;
|
|
781
|
+
}
|
|
782
|
+
if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
783
|
+
windowDroppedCount++;
|
|
784
|
+
if (windowDroppedCount === 1) {
|
|
785
|
+
console.error(
|
|
786
|
+
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
windowCount++;
|
|
792
|
+
return true;
|
|
793
|
+
}
|
|
794
|
+
function forwardRunnerActivity(entry, context) {
|
|
795
|
+
try {
|
|
796
|
+
if (!FORWARDED_LEVELS.has(entry.level)) return;
|
|
797
|
+
if (!context.agentId || !context.authHeader) return;
|
|
798
|
+
if (!admitUnderRateLimit(Date.now())) return;
|
|
799
|
+
const rawMessage = entry.error ?? entry.message ?? "";
|
|
800
|
+
const message = truncate(redact(rawMessage));
|
|
801
|
+
logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
|
|
802
|
+
severity: SEVERITY_BY_LEVEL[entry.level],
|
|
803
|
+
message,
|
|
804
|
+
metadata: { source: "cli.run" },
|
|
805
|
+
agentId: context.agentId
|
|
806
|
+
});
|
|
807
|
+
} catch (err) {
|
|
808
|
+
console.error(
|
|
809
|
+
`[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
655
814
|
// src/lib/auth.ts
|
|
656
815
|
async function getAuthCredentials() {
|
|
657
816
|
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
@@ -719,7 +878,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
719
878
|
if (health.healthy) {
|
|
720
879
|
return health;
|
|
721
880
|
}
|
|
722
|
-
await new Promise((
|
|
881
|
+
await new Promise((resolve3) => setTimeout(resolve3, 1e3));
|
|
723
882
|
}
|
|
724
883
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
725
884
|
}
|
|
@@ -734,7 +893,7 @@ function buildOpenCodeVersionWarning(version2) {
|
|
|
734
893
|
if (isQueueValidatedVersion(version2)) return null;
|
|
735
894
|
const detected = version2 ? `v${version2}` : "unknown";
|
|
736
895
|
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
737
|
-
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack
|
|
896
|
+
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
|
|
738
897
|
}
|
|
739
898
|
|
|
740
899
|
// src/lib/opencode/process.ts
|
|
@@ -1026,6 +1185,12 @@ async function promptOpenCodeInstall(interactive) {
|
|
|
1026
1185
|
return action;
|
|
1027
1186
|
}
|
|
1028
1187
|
|
|
1188
|
+
// src/lib/opencode/provider-check.ts
|
|
1189
|
+
function buildNoProviderWarning(hasProvider) {
|
|
1190
|
+
if (hasProvider !== false) return null;
|
|
1191
|
+
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).";
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1029
1194
|
// src/lib/opencode/session.ts
|
|
1030
1195
|
function opencodeBase(port) {
|
|
1031
1196
|
return `http://127.0.0.1:${port}`;
|
|
@@ -1228,6 +1393,11 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
1228
1393
|
}
|
|
1229
1394
|
const entry = provider.models[modelId];
|
|
1230
1395
|
if (!entry || typeof entry !== "object") return null;
|
|
1396
|
+
if (entry.capabilities && typeof entry.capabilities === "object") {
|
|
1397
|
+
if (typeof entry.capabilities.attachment === "boolean") {
|
|
1398
|
+
return entry.capabilities.attachment;
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1231
1401
|
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
1232
1402
|
} catch (err) {
|
|
1233
1403
|
console.error(
|
|
@@ -1256,6 +1426,16 @@ async function buildFileParts(attachments, capable) {
|
|
|
1256
1426
|
);
|
|
1257
1427
|
dataUrl = null;
|
|
1258
1428
|
}
|
|
1429
|
+
if (dataUrl !== null && typeof dataUrl === "object") {
|
|
1430
|
+
outcomes.push({
|
|
1431
|
+
index: a.index,
|
|
1432
|
+
mime: a.mime,
|
|
1433
|
+
filename: a.filename,
|
|
1434
|
+
status: "failed",
|
|
1435
|
+
reason: "needs_reauth"
|
|
1436
|
+
});
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1259
1439
|
if (dataUrl == null) {
|
|
1260
1440
|
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1261
1441
|
continue;
|
|
@@ -1337,7 +1517,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
|
1337
1517
|
}
|
|
1338
1518
|
}
|
|
1339
1519
|
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
1340
|
-
await new Promise((
|
|
1520
|
+
await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
|
|
1341
1521
|
}
|
|
1342
1522
|
}
|
|
1343
1523
|
return null;
|
|
@@ -1465,6 +1645,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1465
1645
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1466
1646
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1467
1647
|
}
|
|
1648
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1649
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1650
|
+
}
|
|
1468
1651
|
function messageError(messages, userMessageId) {
|
|
1469
1652
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1470
1653
|
const error2 = errorOf(reply);
|
|
@@ -1478,12 +1661,79 @@ function messageError(messages, userMessageId) {
|
|
|
1478
1661
|
}
|
|
1479
1662
|
return "The agent run failed.";
|
|
1480
1663
|
}
|
|
1664
|
+
function messageFailure(messages, userMessageId) {
|
|
1665
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1666
|
+
const error2 = errorOf(reply);
|
|
1667
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
1668
|
+
const e = error2;
|
|
1669
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
1670
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
1671
|
+
if (e.name === "ProviderAuthError") {
|
|
1672
|
+
const data = e.data;
|
|
1673
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
1674
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
1675
|
+
}
|
|
1676
|
+
if (e.name === "APIError") {
|
|
1677
|
+
const data = e.data;
|
|
1678
|
+
const statusCode = data?.statusCode;
|
|
1679
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
1680
|
+
return {
|
|
1681
|
+
kind: "model_auth",
|
|
1682
|
+
providerId: replyProviderId,
|
|
1683
|
+
modelId: replyModelId,
|
|
1684
|
+
reason: "rejected"
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
return null;
|
|
1689
|
+
}
|
|
1690
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
1691
|
+
if (classified != null) return classified;
|
|
1692
|
+
if (hasConfiguredProvider !== false) return null;
|
|
1693
|
+
return {
|
|
1694
|
+
kind: "model_auth",
|
|
1695
|
+
providerId: replyProviderId,
|
|
1696
|
+
modelId: replyModelId,
|
|
1697
|
+
reason: "missing"
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1481
1700
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1482
1701
|
if (!messages || messages.length === 0) return false;
|
|
1483
1702
|
return messages.some(
|
|
1484
1703
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1485
1704
|
);
|
|
1486
1705
|
}
|
|
1706
|
+
async function hasAnyConfiguredProvider(port) {
|
|
1707
|
+
try {
|
|
1708
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1709
|
+
if (!res.ok) {
|
|
1710
|
+
console.error(
|
|
1711
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1712
|
+
);
|
|
1713
|
+
return null;
|
|
1714
|
+
}
|
|
1715
|
+
const body = await res.json();
|
|
1716
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1717
|
+
console.error(
|
|
1718
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
1719
|
+
);
|
|
1720
|
+
return null;
|
|
1721
|
+
}
|
|
1722
|
+
const defaults2 = body.default;
|
|
1723
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
1724
|
+
console.error(
|
|
1725
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
1726
|
+
);
|
|
1727
|
+
return null;
|
|
1728
|
+
}
|
|
1729
|
+
return Object.keys(defaults2).length > 0;
|
|
1730
|
+
} catch (err) {
|
|
1731
|
+
console.error(
|
|
1732
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1733
|
+
);
|
|
1734
|
+
return null;
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1487
1737
|
|
|
1488
1738
|
// src/lib/opencode/session-cleanup.ts
|
|
1489
1739
|
var DURATION_UNIT_MS = {
|
|
@@ -1642,10 +1892,11 @@ var StreamForwarder = class {
|
|
|
1642
1892
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1643
1893
|
*/
|
|
1644
1894
|
abortAll() {
|
|
1645
|
-
for (const stream of this.inflight.
|
|
1895
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1646
1896
|
try {
|
|
1647
1897
|
stream.abort();
|
|
1648
|
-
} catch {
|
|
1898
|
+
} catch (err) {
|
|
1899
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1649
1900
|
}
|
|
1650
1901
|
}
|
|
1651
1902
|
this.inflight.clear();
|
|
@@ -1679,12 +1930,12 @@ var StreamForwarder = class {
|
|
|
1679
1930
|
let endBody;
|
|
1680
1931
|
if (has_body) {
|
|
1681
1932
|
const chunks = [];
|
|
1682
|
-
bodyPromise = new Promise((
|
|
1933
|
+
bodyPromise = new Promise((resolve3) => {
|
|
1683
1934
|
pushBody = (buf) => {
|
|
1684
1935
|
chunks.push(buf);
|
|
1685
1936
|
};
|
|
1686
1937
|
endBody = () => {
|
|
1687
|
-
|
|
1938
|
+
resolve3(Buffer.concat(chunks));
|
|
1688
1939
|
};
|
|
1689
1940
|
});
|
|
1690
1941
|
}
|
|
@@ -1801,7 +2052,7 @@ function connectTunnel(options) {
|
|
|
1801
2052
|
} = options;
|
|
1802
2053
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1803
2054
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1804
|
-
return new Promise((
|
|
2055
|
+
return new Promise((resolve3, reject) => {
|
|
1805
2056
|
const ws = new WebSocket2(url, {
|
|
1806
2057
|
headers: {
|
|
1807
2058
|
Authorization: authHeader
|
|
@@ -1856,7 +2107,7 @@ function connectTunnel(options) {
|
|
|
1856
2107
|
clearTimeout(connectionTimeout);
|
|
1857
2108
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1858
2109
|
onConnected?.(connectedAgentId);
|
|
1859
|
-
|
|
2110
|
+
resolve3({
|
|
1860
2111
|
ws,
|
|
1861
2112
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1862
2113
|
});
|
|
@@ -1918,7 +2169,11 @@ var RunnerConnection = class {
|
|
|
1918
2169
|
if (this.connection) {
|
|
1919
2170
|
try {
|
|
1920
2171
|
this.connection.close();
|
|
1921
|
-
} catch {
|
|
2172
|
+
} catch (err) {
|
|
2173
|
+
log("error", "runner_connection_close_failed", {
|
|
2174
|
+
agent_id: this.resolvedAgentId,
|
|
2175
|
+
...errorFields(err)
|
|
2176
|
+
});
|
|
1922
2177
|
}
|
|
1923
2178
|
this.connection = null;
|
|
1924
2179
|
}
|
|
@@ -1970,6 +2225,416 @@ var RunnerConnection = class {
|
|
|
1970
2225
|
}
|
|
1971
2226
|
};
|
|
1972
2227
|
|
|
2228
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2229
|
+
import { writeFileSync } from "fs";
|
|
2230
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2231
|
+
try {
|
|
2232
|
+
writeFileSync(path, `${agentId}
|
|
2233
|
+
`);
|
|
2234
|
+
return { ok: true };
|
|
2235
|
+
} catch (error2) {
|
|
2236
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
// src/lib/channels/driver.ts
|
|
2241
|
+
import { homedir } from "os";
|
|
2242
|
+
|
|
2243
|
+
// src/lib/file-push.ts
|
|
2244
|
+
import { randomUUID } from "crypto";
|
|
2245
|
+
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2246
|
+
import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
|
|
2247
|
+
var FILE_MODE = 384;
|
|
2248
|
+
var DIRECTORY_MODE = 448;
|
|
2249
|
+
async function writePushedFile(request) {
|
|
2250
|
+
const { requestedPath, content, allowedDirectories, homeDir } = request;
|
|
2251
|
+
const bytes = content.byteLength;
|
|
2252
|
+
if (allowedDirectories.length === 0) {
|
|
2253
|
+
return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
2254
|
+
path: requestedPath,
|
|
2255
|
+
bytes
|
|
2256
|
+
});
|
|
2257
|
+
}
|
|
2258
|
+
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
2259
|
+
return refuse(
|
|
2260
|
+
"file_too_large",
|
|
2261
|
+
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
2262
|
+
{
|
|
2263
|
+
path: requestedPath,
|
|
2264
|
+
bytes
|
|
2265
|
+
}
|
|
2266
|
+
);
|
|
2267
|
+
}
|
|
2268
|
+
const candidate = expandAndValidate(requestedPath, homeDir);
|
|
2269
|
+
if (candidate === null) {
|
|
2270
|
+
return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
2271
|
+
path: requestedPath,
|
|
2272
|
+
bytes
|
|
2273
|
+
});
|
|
2274
|
+
}
|
|
2275
|
+
try {
|
|
2276
|
+
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2277
|
+
dirname2(candidate)
|
|
2278
|
+
);
|
|
2279
|
+
const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
|
|
2280
|
+
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2281
|
+
if (allowedDirectory === null) {
|
|
2282
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2283
|
+
path: realTarget,
|
|
2284
|
+
bytes
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
if (missingSegments.length > 0) {
|
|
2288
|
+
await createMissingDirectories(existingAncestor, missingSegments);
|
|
2289
|
+
const realParent = await realpath(dirname2(realTarget));
|
|
2290
|
+
if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
|
|
2291
|
+
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
2292
|
+
path: realTarget,
|
|
2293
|
+
bytes,
|
|
2294
|
+
reason: "parent_changed_after_create"
|
|
2295
|
+
});
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
await writeAtomically(realTarget, content);
|
|
2299
|
+
log("info", "file_push_written", { path: realTarget, bytes });
|
|
2300
|
+
return { ok: true, path: realTarget };
|
|
2301
|
+
} catch (err) {
|
|
2302
|
+
const errno = err.code ?? "UNKNOWN";
|
|
2303
|
+
return refuse("write_failed", `The runner could not write the file (${errno}).`, {
|
|
2304
|
+
path: candidate,
|
|
2305
|
+
bytes,
|
|
2306
|
+
errno,
|
|
2307
|
+
...errorFields(err)
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
function expandAndValidate(requestedPath, homeDir) {
|
|
2312
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2313
|
+
return null;
|
|
2314
|
+
}
|
|
2315
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2316
|
+
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2317
|
+
return null;
|
|
2318
|
+
}
|
|
2319
|
+
if (!isAbsolute(expanded)) {
|
|
2320
|
+
return null;
|
|
2321
|
+
}
|
|
2322
|
+
const candidate = resolve2(expanded);
|
|
2323
|
+
const name = basename(candidate);
|
|
2324
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
2325
|
+
}
|
|
2326
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
2327
|
+
const missingSegments = [];
|
|
2328
|
+
let current = directory;
|
|
2329
|
+
for (; ; ) {
|
|
2330
|
+
try {
|
|
2331
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
2332
|
+
} catch (err) {
|
|
2333
|
+
const parent = dirname2(current);
|
|
2334
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
2335
|
+
throw err;
|
|
2336
|
+
}
|
|
2337
|
+
missingSegments.unshift(basename(current));
|
|
2338
|
+
current = parent;
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
2343
|
+
for (const directory of allowedDirectories) {
|
|
2344
|
+
if (!isAbsolute(directory)) {
|
|
2345
|
+
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
2349
|
+
if (realDirectory !== null && contains(realDirectory, realTarget)) {
|
|
2350
|
+
return realDirectory;
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
return null;
|
|
2354
|
+
}
|
|
2355
|
+
async function realpathCreatingIfMissing(directory) {
|
|
2356
|
+
try {
|
|
2357
|
+
return await realpath(directory);
|
|
2358
|
+
} catch (err) {
|
|
2359
|
+
if (err.code !== "ENOENT") {
|
|
2360
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2361
|
+
directory,
|
|
2362
|
+
reason: "unresolvable",
|
|
2363
|
+
...errorFields(err)
|
|
2364
|
+
});
|
|
2365
|
+
return null;
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
try {
|
|
2369
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
2370
|
+
await chmod(directory, DIRECTORY_MODE);
|
|
2371
|
+
return await realpath(directory);
|
|
2372
|
+
} catch (err) {
|
|
2373
|
+
log("warn", "file_push_allowed_directory_skipped", {
|
|
2374
|
+
directory,
|
|
2375
|
+
reason: "create_failed",
|
|
2376
|
+
...errorFields(err)
|
|
2377
|
+
});
|
|
2378
|
+
return null;
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
function contains(realDirectory, realTarget) {
|
|
2382
|
+
const rel = relative(realDirectory, realTarget);
|
|
2383
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
2384
|
+
}
|
|
2385
|
+
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2386
|
+
let current = existingAncestor;
|
|
2387
|
+
for (const segment of missingSegments) {
|
|
2388
|
+
current = join(current, segment);
|
|
2389
|
+
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2390
|
+
await chmod(current, DIRECTORY_MODE);
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
async function writeAtomically(realTarget, content) {
|
|
2394
|
+
const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2395
|
+
let handle;
|
|
2396
|
+
try {
|
|
2397
|
+
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
2398
|
+
await handle.writeFile(content);
|
|
2399
|
+
await handle.chmod(FILE_MODE);
|
|
2400
|
+
await handle.close();
|
|
2401
|
+
handle = void 0;
|
|
2402
|
+
await rename(temporaryPath, realTarget);
|
|
2403
|
+
} catch (err) {
|
|
2404
|
+
await discardTemporaryFile(temporaryPath, handle);
|
|
2405
|
+
throw err;
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
async function discardTemporaryFile(temporaryPath, handle) {
|
|
2409
|
+
try {
|
|
2410
|
+
await handle?.close();
|
|
2411
|
+
} catch (err) {
|
|
2412
|
+
log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2413
|
+
}
|
|
2414
|
+
try {
|
|
2415
|
+
await unlink(temporaryPath);
|
|
2416
|
+
} catch (err) {
|
|
2417
|
+
const errno = err.code;
|
|
2418
|
+
if (errno !== "ENOENT" && errno !== "ENOTDIR") {
|
|
2419
|
+
log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
function refuse(code, message, fields) {
|
|
2424
|
+
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
2425
|
+
return { ok: false, code, message };
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
// src/lib/runner-file-sync.ts
|
|
2429
|
+
var MAX_ACK_ATTEMPTS = 5;
|
|
2430
|
+
async function syncPendingRunnerFiles(options) {
|
|
2431
|
+
const pending = await listPendingFiles(options);
|
|
2432
|
+
const pendingIds = new Set(pending.map((file) => file.id));
|
|
2433
|
+
for (const id of options.ackFailures.keys()) {
|
|
2434
|
+
if (!pendingIds.has(id)) options.ackFailures.delete(id);
|
|
2435
|
+
}
|
|
2436
|
+
if (pending.length === 0) return 0;
|
|
2437
|
+
options.log({
|
|
2438
|
+
level: "info",
|
|
2439
|
+
message: `Runner file sync: ${pending.length} file(s) queued for this runner`
|
|
2440
|
+
});
|
|
2441
|
+
let applied = 0;
|
|
2442
|
+
for (const file of pending) {
|
|
2443
|
+
if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
|
|
2444
|
+
if (await applyOne(options, file)) applied += 1;
|
|
2445
|
+
}
|
|
2446
|
+
return applied;
|
|
2447
|
+
}
|
|
2448
|
+
async function listPendingFiles(options) {
|
|
2449
|
+
let res;
|
|
2450
|
+
try {
|
|
2451
|
+
res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
|
|
2452
|
+
headers: { Authorization: options.getAuthHeader() }
|
|
2453
|
+
});
|
|
2454
|
+
} catch (err) {
|
|
2455
|
+
options.log({
|
|
2456
|
+
level: "warn",
|
|
2457
|
+
message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
|
|
2458
|
+
});
|
|
2459
|
+
return [];
|
|
2460
|
+
}
|
|
2461
|
+
if (!res.ok) {
|
|
2462
|
+
options.log({
|
|
2463
|
+
level: res.status === 404 ? "debug" : "warn",
|
|
2464
|
+
message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2465
|
+
});
|
|
2466
|
+
return [];
|
|
2467
|
+
}
|
|
2468
|
+
let body;
|
|
2469
|
+
try {
|
|
2470
|
+
body = await res.json();
|
|
2471
|
+
} catch (err) {
|
|
2472
|
+
options.log({
|
|
2473
|
+
level: "warn",
|
|
2474
|
+
message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
|
|
2475
|
+
});
|
|
2476
|
+
return [];
|
|
2477
|
+
}
|
|
2478
|
+
if (!Array.isArray(body)) {
|
|
2479
|
+
options.log({
|
|
2480
|
+
level: "warn",
|
|
2481
|
+
message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
|
|
2482
|
+
});
|
|
2483
|
+
return [];
|
|
2484
|
+
}
|
|
2485
|
+
const files = [];
|
|
2486
|
+
for (const entry of body) {
|
|
2487
|
+
const file = asPendingFile(entry);
|
|
2488
|
+
if (file === null) {
|
|
2489
|
+
options.log({
|
|
2490
|
+
level: "warn",
|
|
2491
|
+
message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
|
|
2492
|
+
});
|
|
2493
|
+
continue;
|
|
2494
|
+
}
|
|
2495
|
+
files.push(file);
|
|
2496
|
+
}
|
|
2497
|
+
return files;
|
|
2498
|
+
}
|
|
2499
|
+
function asPendingFile(entry) {
|
|
2500
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
2501
|
+
const { id, path, size } = entry;
|
|
2502
|
+
if (typeof id !== "string" || id === "") return null;
|
|
2503
|
+
if (typeof path !== "string" || path === "") return null;
|
|
2504
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
|
|
2505
|
+
return { id, path, size };
|
|
2506
|
+
}
|
|
2507
|
+
async function applyOne(options, file) {
|
|
2508
|
+
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
2509
|
+
if (options.allowedDirectories.length === 0) {
|
|
2510
|
+
options.log({
|
|
2511
|
+
level: "warn",
|
|
2512
|
+
message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
|
|
2513
|
+
});
|
|
2514
|
+
await ack(options, file, "rejected", "file_sync_disabled");
|
|
2515
|
+
return false;
|
|
2516
|
+
}
|
|
2517
|
+
if (file.size > MAX_FILE_PUSH_BYTES) {
|
|
2518
|
+
options.log({
|
|
2519
|
+
level: "warn",
|
|
2520
|
+
message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
|
|
2521
|
+
});
|
|
2522
|
+
await ack(options, file, "rejected", "file_too_large");
|
|
2523
|
+
return false;
|
|
2524
|
+
}
|
|
2525
|
+
const download = await downloadContent(options, file, label);
|
|
2526
|
+
if (!download.ok) {
|
|
2527
|
+
if (download.terminal) await ack(options, file, "rejected", download.code);
|
|
2528
|
+
return false;
|
|
2529
|
+
}
|
|
2530
|
+
let outcome;
|
|
2531
|
+
try {
|
|
2532
|
+
outcome = await writePushedFile({
|
|
2533
|
+
requestedPath: file.path,
|
|
2534
|
+
content: download.content,
|
|
2535
|
+
allowedDirectories: options.allowedDirectories,
|
|
2536
|
+
homeDir: options.homeDir
|
|
2537
|
+
});
|
|
2538
|
+
} catch (err) {
|
|
2539
|
+
options.log({
|
|
2540
|
+
level: "error",
|
|
2541
|
+
message: `Runner file ${label} could not be written: ${describe(err)}`
|
|
2542
|
+
});
|
|
2543
|
+
await ack(options, file, "rejected", "write_failed");
|
|
2544
|
+
return false;
|
|
2545
|
+
}
|
|
2546
|
+
if (!outcome.ok) {
|
|
2547
|
+
options.log({
|
|
2548
|
+
level: "warn",
|
|
2549
|
+
message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
|
|
2550
|
+
});
|
|
2551
|
+
await ack(options, file, "rejected", outcome.code);
|
|
2552
|
+
return false;
|
|
2553
|
+
}
|
|
2554
|
+
options.log({
|
|
2555
|
+
level: "info",
|
|
2556
|
+
message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
|
|
2557
|
+
});
|
|
2558
|
+
await ack(options, file, "applied");
|
|
2559
|
+
return true;
|
|
2560
|
+
}
|
|
2561
|
+
function durableDownloadCode(status) {
|
|
2562
|
+
return status === 413 ? "file_too_large" : "write_failed";
|
|
2563
|
+
}
|
|
2564
|
+
async function downloadContent(options, file, label) {
|
|
2565
|
+
try {
|
|
2566
|
+
const res = await options.fetchImpl(
|
|
2567
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
|
|
2568
|
+
{ headers: { Authorization: options.getAuthHeader() } }
|
|
2569
|
+
);
|
|
2570
|
+
if (!res.ok) {
|
|
2571
|
+
const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
|
|
2572
|
+
if (!terminal) {
|
|
2573
|
+
options.log({
|
|
2574
|
+
level: "warn",
|
|
2575
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
|
|
2576
|
+
});
|
|
2577
|
+
return { ok: false, terminal: false };
|
|
2578
|
+
}
|
|
2579
|
+
const code = durableDownloadCode(res.status);
|
|
2580
|
+
options.log({
|
|
2581
|
+
level: "error",
|
|
2582
|
+
message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
|
|
2583
|
+
});
|
|
2584
|
+
return { ok: false, terminal: true, code };
|
|
2585
|
+
}
|
|
2586
|
+
return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
|
|
2587
|
+
} catch (err) {
|
|
2588
|
+
options.log({
|
|
2589
|
+
level: "warn",
|
|
2590
|
+
message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
|
|
2591
|
+
});
|
|
2592
|
+
return { ok: false, terminal: false };
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
async function ack(options, file, status, reason) {
|
|
2596
|
+
const outcome = `${status}${reason ? ` (${reason})` : ""}`;
|
|
2597
|
+
try {
|
|
2598
|
+
const res = await options.fetchImpl(
|
|
2599
|
+
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
2600
|
+
{
|
|
2601
|
+
method: "POST",
|
|
2602
|
+
headers: {
|
|
2603
|
+
Authorization: options.getAuthHeader(),
|
|
2604
|
+
"Content-Type": "application/json"
|
|
2605
|
+
},
|
|
2606
|
+
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
2607
|
+
}
|
|
2608
|
+
);
|
|
2609
|
+
if (!res.ok) {
|
|
2610
|
+
recordAckFailure(
|
|
2611
|
+
options,
|
|
2612
|
+
file,
|
|
2613
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
|
|
2614
|
+
);
|
|
2615
|
+
return;
|
|
2616
|
+
}
|
|
2617
|
+
options.ackFailures.delete(file.id);
|
|
2618
|
+
} catch (err) {
|
|
2619
|
+
recordAckFailure(
|
|
2620
|
+
options,
|
|
2621
|
+
file,
|
|
2622
|
+
`Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
|
|
2623
|
+
);
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
function recordAckFailure(options, file, what) {
|
|
2627
|
+
const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
|
|
2628
|
+
options.ackFailures.set(file.id, attempts);
|
|
2629
|
+
options.log({
|
|
2630
|
+
level: "error",
|
|
2631
|
+
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})`
|
|
2632
|
+
});
|
|
2633
|
+
}
|
|
2634
|
+
function describe(err) {
|
|
2635
|
+
return err instanceof Error ? err.message : String(err);
|
|
2636
|
+
}
|
|
2637
|
+
|
|
1973
2638
|
// src/lib/channels/driver.ts
|
|
1974
2639
|
function messageIdOf(m) {
|
|
1975
2640
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -1998,7 +2663,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
1998
2663
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
1999
2664
|
var HEARTBEAT_MS = 6e4;
|
|
2000
2665
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2666
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2667
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
2001
2668
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2669
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
2002
2670
|
var ChannelAuthError = class extends Error {
|
|
2003
2671
|
constructor(message) {
|
|
2004
2672
|
super(message);
|
|
@@ -2021,7 +2689,7 @@ function backoffDelay(attempt, policy) {
|
|
|
2021
2689
|
function isRetryableStatus(status) {
|
|
2022
2690
|
return status === 429 || status >= 500 && status <= 599;
|
|
2023
2691
|
}
|
|
2024
|
-
var ChannelDriver = class {
|
|
2692
|
+
var ChannelDriver = class _ChannelDriver {
|
|
2025
2693
|
agentId;
|
|
2026
2694
|
port;
|
|
2027
2695
|
apiUrl;
|
|
@@ -2035,8 +2703,38 @@ var ChannelDriver = class {
|
|
|
2035
2703
|
pausedMaxWaitMs;
|
|
2036
2704
|
stuckQueuedMs;
|
|
2037
2705
|
now;
|
|
2706
|
+
fileSyncDirectories;
|
|
2707
|
+
homeDir;
|
|
2038
2708
|
/** Cache of conversationId → opencode sessionId. */
|
|
2039
2709
|
sessions = /* @__PURE__ */ new Map();
|
|
2710
|
+
/**
|
|
2711
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2712
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2713
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2714
|
+
* must bind a fresh one.
|
|
2715
|
+
*
|
|
2716
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2717
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2718
|
+
* the same session, and its watcher's routine status writes carry
|
|
2719
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2720
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2721
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2722
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2723
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2724
|
+
* is one we deliberately keep (see `markDone`).
|
|
2725
|
+
*
|
|
2726
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2727
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2728
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2729
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2730
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2731
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2732
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2733
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2734
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2735
|
+
* bounded cost.
|
|
2736
|
+
*/
|
|
2737
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
2040
2738
|
/**
|
|
2041
2739
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
2042
2740
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2146,9 +2844,12 @@ var ChannelDriver = class {
|
|
|
2146
2844
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2147
2845
|
/**
|
|
2148
2846
|
* Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
|
|
2149
|
-
* NON-EMPTY name is stored (terminal — a real session name
|
|
2150
|
-
* so we do NOT re-GET `/session/:id` every tick.
|
|
2151
|
-
*
|
|
2847
|
+
* NON-EMPTY, non-placeholder name is stored (terminal — a real session name
|
|
2848
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
|
|
2849
|
+
* excludes OpenCode's synchronous default title (see
|
|
2850
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
|
|
2851
|
+
* as an empty title so it never latches. A missing entry = not yet resolved OR
|
|
2852
|
+
* resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
|
|
2152
2853
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2153
2854
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2154
2855
|
* no watcher) can resolve the title.
|
|
@@ -2156,6 +2857,24 @@ var ChannelDriver = class {
|
|
|
2156
2857
|
sessionTitles = /* @__PURE__ */ new Map();
|
|
2157
2858
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
2158
2859
|
draining = false;
|
|
2860
|
+
/**
|
|
2861
|
+
* Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
|
|
2862
|
+
* drain ping don't download, write and ack the same file twice.
|
|
2863
|
+
*/
|
|
2864
|
+
syncingFiles = false;
|
|
2865
|
+
/**
|
|
2866
|
+
* Consecutive failed acks per pending file (#559). Lives on the driver so it
|
|
2867
|
+
* survives across drains — without it, a file whose ack keeps failing is
|
|
2868
|
+
* re-downloaded and re-written every ~2s until the server expires it.
|
|
2869
|
+
*/
|
|
2870
|
+
fileAckFailures = /* @__PURE__ */ new Map();
|
|
2871
|
+
/**
|
|
2872
|
+
* Monotonic count of files this runner has pulled and written (#559). Only
|
|
2873
|
+
* ever increases, so `run.ts` detects work by comparing it against the value
|
|
2874
|
+
* it saw on the previous cycle — including work that landed mid-sleep, the
|
|
2875
|
+
* same trick `lastProxiedActivityAt` uses.
|
|
2876
|
+
*/
|
|
2877
|
+
appliedFileCount = 0;
|
|
2159
2878
|
/**
|
|
2160
2879
|
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2161
2880
|
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
@@ -2186,6 +2905,8 @@ var ChannelDriver = class {
|
|
|
2186
2905
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
2187
2906
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2188
2907
|
this.now = config2.now ?? (() => Date.now());
|
|
2908
|
+
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
2909
|
+
this.homeDir = config2.homeDir ?? homedir();
|
|
2189
2910
|
}
|
|
2190
2911
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2191
2912
|
get opencodeBase() {
|
|
@@ -2213,6 +2934,47 @@ var ChannelDriver = class {
|
|
|
2213
2934
|
);
|
|
2214
2935
|
return run2;
|
|
2215
2936
|
}
|
|
2937
|
+
/**
|
|
2938
|
+
* Pull-and-apply any files Evident has queued for this runner (#559), riding
|
|
2939
|
+
* the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
|
|
2940
|
+
* and drain ping that call `drainPending()`. There is deliberately no channel,
|
|
2941
|
+
* control frame or poll loop of its own: worst-case latency is one poll tick.
|
|
2942
|
+
*
|
|
2943
|
+
* NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
|
|
2944
|
+
* cost a conversation turn. Failures are logged and either acked as a terminal
|
|
2945
|
+
* outcome or left pending for the next drain (see `runner-file-sync.ts`).
|
|
2946
|
+
*
|
|
2947
|
+
* Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
|
|
2948
|
+
*
|
|
2949
|
+
* @returns the number of files written to disk.
|
|
2950
|
+
*/
|
|
2951
|
+
async syncPendingFiles() {
|
|
2952
|
+
if (this.stopped) return 0;
|
|
2953
|
+
if (this.syncingFiles) return 0;
|
|
2954
|
+
this.syncingFiles = true;
|
|
2955
|
+
try {
|
|
2956
|
+
const applied = await syncPendingRunnerFiles({
|
|
2957
|
+
agentId: this.agentId,
|
|
2958
|
+
apiUrl: this.apiUrl,
|
|
2959
|
+
getAuthHeader: this.getAuthHeader,
|
|
2960
|
+
fetchImpl: this.fetchImpl,
|
|
2961
|
+
allowedDirectories: this.fileSyncDirectories,
|
|
2962
|
+
homeDir: this.homeDir,
|
|
2963
|
+
ackFailures: this.fileAckFailures,
|
|
2964
|
+
log: this.log
|
|
2965
|
+
});
|
|
2966
|
+
this.appliedFileCount += applied;
|
|
2967
|
+
return applied;
|
|
2968
|
+
} catch (err) {
|
|
2969
|
+
this.log({
|
|
2970
|
+
level: "error",
|
|
2971
|
+
message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
|
|
2972
|
+
});
|
|
2973
|
+
return 0;
|
|
2974
|
+
} finally {
|
|
2975
|
+
this.syncingFiles = false;
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2216
2978
|
async runDrain() {
|
|
2217
2979
|
let dispatched = 0;
|
|
2218
2980
|
try {
|
|
@@ -2246,6 +3008,28 @@ var ChannelDriver = class {
|
|
|
2246
3008
|
}
|
|
2247
3009
|
return false;
|
|
2248
3010
|
}
|
|
3011
|
+
/**
|
|
3012
|
+
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
3013
|
+
*
|
|
3014
|
+
* Pulling a file is real work that `drainPending()` knows nothing about, so
|
|
3015
|
+
* without this a near-idle runner counts a credential pull as an empty tick
|
|
3016
|
+
* and `--idle-timeout` can `process.exit` mid-pull — leaving a
|
|
3017
|
+
* `.evident-push-*.tmp` behind — or immediately after the write, before the
|
|
3018
|
+
* browser has run the authorize/callback that activates it (the user then sees
|
|
3019
|
+
* `saved_not_activated` for a runner that was fine).
|
|
3020
|
+
*
|
|
3021
|
+
* Two signals because one cannot cover both cases: `inFlight` is the pull
|
|
3022
|
+
* happening RIGHT NOW (it may outlive the tick that started it), and
|
|
3023
|
+
* `appliedFiles` is monotonic so a pull that started AND finished between two
|
|
3024
|
+
* idle checks still shows up as an advance.
|
|
3025
|
+
*
|
|
3026
|
+
* CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
|
|
3027
|
+
* the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
|
|
3028
|
+
* samples afterwards reads `true` every single cycle and can never idle out.
|
|
3029
|
+
*/
|
|
3030
|
+
fileSyncActivity() {
|
|
3031
|
+
return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
|
|
3032
|
+
}
|
|
2249
3033
|
/**
|
|
2250
3034
|
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2251
3035
|
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
@@ -2307,7 +3091,7 @@ var ChannelDriver = class {
|
|
|
2307
3091
|
await this.sleep(step);
|
|
2308
3092
|
}
|
|
2309
3093
|
}
|
|
2310
|
-
while (this.hasInFlightWatchers()) {
|
|
3094
|
+
while (this.hasInFlightWatchers() || this.syncingFiles) {
|
|
2311
3095
|
if (this.now() >= deadline) return false;
|
|
2312
3096
|
await this.sleep(step);
|
|
2313
3097
|
}
|
|
@@ -2342,10 +3126,15 @@ var ChannelDriver = class {
|
|
|
2342
3126
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2343
3127
|
*/
|
|
2344
3128
|
async processConversation(conv) {
|
|
2345
|
-
const sessionId = await this.ensureSession(conv);
|
|
3129
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2346
3130
|
const messages = await this.getPendingMessages(conv.id);
|
|
2347
3131
|
let dispatched = 0;
|
|
2348
3132
|
let skippedAlreadyDispatched = 0;
|
|
3133
|
+
if (refusedSessionId && messages.length > 0) {
|
|
3134
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
3135
|
+
superseded_session_id: refusedSessionId
|
|
3136
|
+
});
|
|
3137
|
+
}
|
|
2349
3138
|
for (const message of messages) {
|
|
2350
3139
|
if (this.stopped) break;
|
|
2351
3140
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2372,7 +3161,8 @@ var ChannelDriver = class {
|
|
|
2372
3161
|
} catch (err) {
|
|
2373
3162
|
if (err instanceof ChannelAuthError) throw err;
|
|
2374
3163
|
this.dispatched.delete(message.id);
|
|
2375
|
-
|
|
3164
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
3165
|
+
if (exists === false) {
|
|
2376
3166
|
this.sessions.delete(conv.id);
|
|
2377
3167
|
this.log({
|
|
2378
3168
|
level: "warn",
|
|
@@ -2382,15 +3172,39 @@ var ChannelDriver = class {
|
|
|
2382
3172
|
});
|
|
2383
3173
|
break;
|
|
2384
3174
|
}
|
|
2385
|
-
|
|
3175
|
+
if (exists === null) {
|
|
3176
|
+
this.log({
|
|
3177
|
+
level: "warn",
|
|
3178
|
+
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.`,
|
|
3179
|
+
conversation_id: conv.id,
|
|
3180
|
+
message_id: message.id
|
|
3181
|
+
});
|
|
3182
|
+
break;
|
|
3183
|
+
}
|
|
3184
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3185
|
+
this.sessions.delete(conv.id);
|
|
3186
|
+
this.supersede(conv.id, sessionId);
|
|
3187
|
+
this.log({
|
|
3188
|
+
level: "warn",
|
|
3189
|
+
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.`,
|
|
3190
|
+
conversation_id: conv.id,
|
|
3191
|
+
message_id: message.id
|
|
3192
|
+
});
|
|
3193
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3194
|
+
this.log({
|
|
3195
|
+
level: "warn",
|
|
3196
|
+
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)}`,
|
|
3197
|
+
conversation_id: conv.id,
|
|
3198
|
+
message_id: message.id
|
|
3199
|
+
});
|
|
2386
3200
|
});
|
|
2387
3201
|
this.log({
|
|
2388
3202
|
level: "error",
|
|
2389
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
3203
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2390
3204
|
conversation_id: conv.id,
|
|
2391
3205
|
message_id: message.id
|
|
2392
3206
|
});
|
|
2393
|
-
|
|
3207
|
+
break;
|
|
2394
3208
|
}
|
|
2395
3209
|
if (opencodeMessageId === null) {
|
|
2396
3210
|
this.log({
|
|
@@ -2416,8 +3230,42 @@ var ChannelDriver = class {
|
|
|
2416
3230
|
this.ensureWatcherRunning(sessionId);
|
|
2417
3231
|
return dispatched;
|
|
2418
3232
|
}
|
|
3233
|
+
/**
|
|
3234
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
3235
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
3236
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
3237
|
+
*/
|
|
3238
|
+
supersede(conversationId, sessionId) {
|
|
3239
|
+
this.supersededSessions.delete(conversationId);
|
|
3240
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
3241
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
3242
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
3243
|
+
if (oldest === void 0) return;
|
|
3244
|
+
this.supersededSessions.delete(oldest);
|
|
3245
|
+
}
|
|
3246
|
+
}
|
|
3247
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
3248
|
+
isSuperseded(conversationId, sessionId) {
|
|
3249
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
3250
|
+
}
|
|
3251
|
+
/**
|
|
3252
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
3253
|
+
*
|
|
3254
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3255
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3256
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
3257
|
+
*/
|
|
2419
3258
|
async ensureSession(conv) {
|
|
2420
3259
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
3260
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
3261
|
+
this.log({
|
|
3262
|
+
level: "warn",
|
|
3263
|
+
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.`,
|
|
3264
|
+
conversation_id: conv.id
|
|
3265
|
+
});
|
|
3266
|
+
this.sessions.delete(conv.id);
|
|
3267
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
3268
|
+
}
|
|
2421
3269
|
if (bound) {
|
|
2422
3270
|
const exists = await sessionExists(this.port, bound);
|
|
2423
3271
|
if (exists === false) {
|
|
@@ -2427,12 +3275,12 @@ var ChannelDriver = class {
|
|
|
2427
3275
|
conversation_id: conv.id
|
|
2428
3276
|
});
|
|
2429
3277
|
this.sessions.delete(conv.id);
|
|
2430
|
-
return this.createAndBindSession(conv.id);
|
|
3278
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2431
3279
|
}
|
|
2432
3280
|
this.sessions.set(conv.id, bound);
|
|
2433
|
-
return bound;
|
|
3281
|
+
return { sessionId: bound };
|
|
2434
3282
|
}
|
|
2435
|
-
return this.createAndBindSession(conv.id);
|
|
3283
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2436
3284
|
}
|
|
2437
3285
|
/**
|
|
2438
3286
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2520,7 +3368,11 @@ var ChannelDriver = class {
|
|
|
2520
3368
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2521
3369
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2522
3370
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2523
|
-
*
|
|
3371
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
3372
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
3373
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
3374
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
3375
|
+
* logged with context (no silent swallow).
|
|
2524
3376
|
*/
|
|
2525
3377
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2526
3378
|
try {
|
|
@@ -2529,6 +3381,25 @@ var ChannelDriver = class {
|
|
|
2529
3381
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2530
3382
|
);
|
|
2531
3383
|
if (!res.ok) {
|
|
3384
|
+
let reason;
|
|
3385
|
+
try {
|
|
3386
|
+
const body = await res.json();
|
|
3387
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
3388
|
+
} catch (parseErr) {
|
|
3389
|
+
this.log({
|
|
3390
|
+
level: "debug",
|
|
3391
|
+
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`,
|
|
3392
|
+
message_id: messageId
|
|
3393
|
+
});
|
|
3394
|
+
}
|
|
3395
|
+
if (reason === "needs_reauth") {
|
|
3396
|
+
this.log({
|
|
3397
|
+
level: "error",
|
|
3398
|
+
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)`,
|
|
3399
|
+
message_id: messageId
|
|
3400
|
+
});
|
|
3401
|
+
return { needsReauth: true };
|
|
3402
|
+
}
|
|
2532
3403
|
this.log({
|
|
2533
3404
|
level: "error",
|
|
2534
3405
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2568,6 +3439,9 @@ var ChannelDriver = class {
|
|
|
2568
3439
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2569
3440
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2570
3441
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
3442
|
+
const failedReason = outcomes.some(
|
|
3443
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
3444
|
+
) ? "needs_reauth" : void 0;
|
|
2571
3445
|
this.log({
|
|
2572
3446
|
level: "info",
|
|
2573
3447
|
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`,
|
|
@@ -2577,7 +3451,8 @@ var ChannelDriver = class {
|
|
|
2577
3451
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2578
3452
|
skipped,
|
|
2579
3453
|
failed,
|
|
2580
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
3454
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
3455
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2581
3456
|
});
|
|
2582
3457
|
}
|
|
2583
3458
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2608,12 +3483,17 @@ var ChannelDriver = class {
|
|
|
2608
3483
|
stuckReported: false,
|
|
2609
3484
|
lastAliveAt: 0,
|
|
2610
3485
|
aliveInFlight: false,
|
|
3486
|
+
titleSynced: false,
|
|
3487
|
+
titleSyncInFlight: false,
|
|
2611
3488
|
awaitingHumanLatched: false,
|
|
2612
3489
|
pausedOnQuestion: false,
|
|
2613
3490
|
pausedOnPermission: false,
|
|
2614
3491
|
pausedClearConfirmed: false,
|
|
2615
3492
|
pausedInFlight: false,
|
|
2616
|
-
deliveryDeadlineAnchored: false
|
|
3493
|
+
deliveryDeadlineAnchored: false,
|
|
3494
|
+
b2PinnedSinceMs: 0,
|
|
3495
|
+
b2LastDescendantCheckMs: 0,
|
|
3496
|
+
b2AbandonedSignalled: false
|
|
2617
3497
|
});
|
|
2618
3498
|
}
|
|
2619
3499
|
/**
|
|
@@ -2681,12 +3561,17 @@ var ChannelDriver = class {
|
|
|
2681
3561
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
2682
3562
|
lastAliveAt: 0,
|
|
2683
3563
|
aliveInFlight: false,
|
|
3564
|
+
titleSynced: false,
|
|
3565
|
+
titleSyncInFlight: false,
|
|
2684
3566
|
awaitingHumanLatched: false,
|
|
2685
3567
|
pausedOnQuestion: false,
|
|
2686
3568
|
pausedOnPermission: false,
|
|
2687
3569
|
pausedClearConfirmed: false,
|
|
2688
3570
|
pausedInFlight: false,
|
|
2689
|
-
deliveryDeadlineAnchored: false
|
|
3571
|
+
deliveryDeadlineAnchored: false,
|
|
3572
|
+
b2PinnedSinceMs: 0,
|
|
3573
|
+
b2LastDescendantCheckMs: 0,
|
|
3574
|
+
b2AbandonedSignalled: false
|
|
2690
3575
|
});
|
|
2691
3576
|
}
|
|
2692
3577
|
/**
|
|
@@ -2841,65 +3726,14 @@ var ChannelDriver = class {
|
|
|
2841
3726
|
if (!claimed) {
|
|
2842
3727
|
this.log({
|
|
2843
3728
|
level: "debug",
|
|
2844
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
|
|
2845
|
-
conversation_id: conv.id,
|
|
2846
|
-
message_id: inFlight.evidentMessageId
|
|
2847
|
-
});
|
|
2848
|
-
}
|
|
2849
|
-
}
|
|
2850
|
-
if (state === "done") {
|
|
2851
|
-
this.anchorDeliveryDeadline(inFlight);
|
|
2852
|
-
if (!inFlight.done) {
|
|
2853
|
-
this.log({
|
|
2854
|
-
level: "info",
|
|
2855
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
3729
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
|
|
2856
3730
|
conversation_id: conv.id,
|
|
2857
3731
|
message_id: inFlight.evidentMessageId
|
|
2858
3732
|
});
|
|
2859
|
-
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
2860
|
-
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2861
|
-
try {
|
|
2862
|
-
await this.markDone(
|
|
2863
|
-
conv.id,
|
|
2864
|
-
inFlight.evidentMessageId,
|
|
2865
|
-
sessionId,
|
|
2866
|
-
inFlight.opencodeMessageId,
|
|
2867
|
-
title,
|
|
2868
|
-
usage
|
|
2869
|
-
);
|
|
2870
|
-
} catch (err) {
|
|
2871
|
-
if (err instanceof ChannelAuthError) throw err;
|
|
2872
|
-
if (err instanceof ChannelTerminalError) {
|
|
2873
|
-
this.log({
|
|
2874
|
-
level: "warn",
|
|
2875
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
2876
|
-
conversation_id: conv.id,
|
|
2877
|
-
message_id: inFlight.evidentMessageId
|
|
2878
|
-
});
|
|
2879
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2880
|
-
return;
|
|
2881
|
-
}
|
|
2882
|
-
if (this.now() >= inFlight.deadline) {
|
|
2883
|
-
this.log({
|
|
2884
|
-
level: "warn",
|
|
2885
|
-
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)}`,
|
|
2886
|
-
conversation_id: conv.id,
|
|
2887
|
-
message_id: inFlight.evidentMessageId
|
|
2888
|
-
});
|
|
2889
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2890
|
-
return;
|
|
2891
|
-
}
|
|
2892
|
-
this.log({
|
|
2893
|
-
level: "warn",
|
|
2894
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
2895
|
-
conversation_id: conv.id,
|
|
2896
|
-
message_id: inFlight.evidentMessageId
|
|
2897
|
-
});
|
|
2898
|
-
return;
|
|
2899
|
-
}
|
|
2900
|
-
inFlight.done = true;
|
|
2901
3733
|
}
|
|
2902
|
-
|
|
3734
|
+
}
|
|
3735
|
+
if (state === "done") {
|
|
3736
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
2903
3737
|
return;
|
|
2904
3738
|
}
|
|
2905
3739
|
if (state === "failed") {
|
|
@@ -2913,8 +3747,16 @@ var ChannelDriver = class {
|
|
|
2913
3747
|
message_id: inFlight.evidentMessageId
|
|
2914
3748
|
});
|
|
2915
3749
|
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3750
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
2916
3751
|
try {
|
|
2917
|
-
await this.markFailed(
|
|
3752
|
+
await this.markFailed(
|
|
3753
|
+
conv.id,
|
|
3754
|
+
inFlight.evidentMessageId,
|
|
3755
|
+
sessionId,
|
|
3756
|
+
error2,
|
|
3757
|
+
usage,
|
|
3758
|
+
failure
|
|
3759
|
+
);
|
|
2918
3760
|
} catch (err) {
|
|
2919
3761
|
if (err instanceof ChannelAuthError) throw err;
|
|
2920
3762
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -2959,6 +3801,44 @@ var ChannelDriver = class {
|
|
|
2959
3801
|
});
|
|
2960
3802
|
}
|
|
2961
3803
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3804
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3805
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3806
|
+
if (!pinnedNow) {
|
|
3807
|
+
if (snapshotReadable) {
|
|
3808
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3809
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3810
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3811
|
+
}
|
|
3812
|
+
} else {
|
|
3813
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3814
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3815
|
+
return;
|
|
3816
|
+
}
|
|
3817
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3818
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3819
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3820
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3821
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3822
|
+
if (isB2AbandonmentConfirmed({
|
|
3823
|
+
pinnedForMs,
|
|
3824
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3825
|
+
descendantOngoing
|
|
3826
|
+
})) {
|
|
3827
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3828
|
+
this.log({
|
|
3829
|
+
level: "warn",
|
|
3830
|
+
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`,
|
|
3831
|
+
conversation_id: conv.id,
|
|
3832
|
+
message_id: id
|
|
3833
|
+
});
|
|
3834
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3835
|
+
watched_for_ms: pinnedForMs
|
|
3836
|
+
});
|
|
3837
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3838
|
+
return;
|
|
3839
|
+
}
|
|
3840
|
+
}
|
|
3841
|
+
}
|
|
2962
3842
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
2963
3843
|
this.log({
|
|
2964
3844
|
level: "warn",
|
|
@@ -2978,6 +3858,18 @@ var ChannelDriver = class {
|
|
|
2978
3858
|
inFlight.aliveInFlight = false;
|
|
2979
3859
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
2980
3860
|
});
|
|
3861
|
+
if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
|
|
3862
|
+
inFlight.titleSyncInFlight = true;
|
|
3863
|
+
void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
|
|
3864
|
+
if (!title) {
|
|
3865
|
+
inFlight.titleSyncInFlight = false;
|
|
3866
|
+
return;
|
|
3867
|
+
}
|
|
3868
|
+
const ok = await this.patchConversationTitle(conv.id, title);
|
|
3869
|
+
inFlight.titleSyncInFlight = false;
|
|
3870
|
+
if (ok) inFlight.titleSynced = true;
|
|
3871
|
+
});
|
|
3872
|
+
}
|
|
2981
3873
|
}
|
|
2982
3874
|
if (awaitingHuman) {
|
|
2983
3875
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -3015,6 +3907,70 @@ var ChannelDriver = class {
|
|
|
3015
3907
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3016
3908
|
}
|
|
3017
3909
|
}
|
|
3910
|
+
/**
|
|
3911
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
3912
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
3913
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
3914
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
3915
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
3916
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
3917
|
+
* and risking the two copies silently drifting apart.
|
|
3918
|
+
*/
|
|
3919
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
3920
|
+
const conv = watcher.conv;
|
|
3921
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
3922
|
+
if (!inFlight.done) {
|
|
3923
|
+
this.log({
|
|
3924
|
+
level: "info",
|
|
3925
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
3926
|
+
conversation_id: conv.id,
|
|
3927
|
+
message_id: inFlight.evidentMessageId
|
|
3928
|
+
});
|
|
3929
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3930
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3931
|
+
try {
|
|
3932
|
+
await this.markDone(
|
|
3933
|
+
conv.id,
|
|
3934
|
+
inFlight.evidentMessageId,
|
|
3935
|
+
sessionId,
|
|
3936
|
+
inFlight.opencodeMessageId,
|
|
3937
|
+
title,
|
|
3938
|
+
usage
|
|
3939
|
+
);
|
|
3940
|
+
} catch (err) {
|
|
3941
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3942
|
+
if (err instanceof ChannelTerminalError) {
|
|
3943
|
+
this.log({
|
|
3944
|
+
level: "warn",
|
|
3945
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
3946
|
+
conversation_id: conv.id,
|
|
3947
|
+
message_id: inFlight.evidentMessageId
|
|
3948
|
+
});
|
|
3949
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3950
|
+
return;
|
|
3951
|
+
}
|
|
3952
|
+
if (this.now() >= inFlight.deadline) {
|
|
3953
|
+
this.log({
|
|
3954
|
+
level: "warn",
|
|
3955
|
+
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)}`,
|
|
3956
|
+
conversation_id: conv.id,
|
|
3957
|
+
message_id: inFlight.evidentMessageId
|
|
3958
|
+
});
|
|
3959
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3960
|
+
return;
|
|
3961
|
+
}
|
|
3962
|
+
this.log({
|
|
3963
|
+
level: "warn",
|
|
3964
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
3965
|
+
conversation_id: conv.id,
|
|
3966
|
+
message_id: inFlight.evidentMessageId
|
|
3967
|
+
});
|
|
3968
|
+
return;
|
|
3969
|
+
}
|
|
3970
|
+
inFlight.done = true;
|
|
3971
|
+
}
|
|
3972
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3973
|
+
}
|
|
3018
3974
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
3019
3975
|
/**
|
|
3020
3976
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3181,6 +4137,7 @@ var ChannelDriver = class {
|
|
|
3181
4137
|
if (state === "failed") {
|
|
3182
4138
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3183
4139
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4140
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3184
4141
|
this.log({
|
|
3185
4142
|
level: "error",
|
|
3186
4143
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3188,7 +4145,7 @@ var ChannelDriver = class {
|
|
|
3188
4145
|
message_id: row.id
|
|
3189
4146
|
});
|
|
3190
4147
|
try {
|
|
3191
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
4148
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3192
4149
|
} catch (err) {
|
|
3193
4150
|
if (err instanceof ChannelAuthError) throw err;
|
|
3194
4151
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3594,6 +4551,47 @@ var ChannelDriver = class {
|
|
|
3594
4551
|
}
|
|
3595
4552
|
return false;
|
|
3596
4553
|
}
|
|
4554
|
+
/**
|
|
4555
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4556
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4557
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4558
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4559
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4560
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4561
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4562
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4563
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4564
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4565
|
+
* not ongoing".
|
|
4566
|
+
*
|
|
4567
|
+
* Return contract:
|
|
4568
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4569
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4570
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4571
|
+
* CONFIRMED NOT a descendant of it.
|
|
4572
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4573
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4574
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4575
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4576
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4577
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4578
|
+
* here.
|
|
4579
|
+
*
|
|
4580
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4581
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4582
|
+
* by interaction attribution or the recovery path.
|
|
4583
|
+
*/
|
|
4584
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4585
|
+
let current = sessionId;
|
|
4586
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4587
|
+
if (current === rootSessionId) return true;
|
|
4588
|
+
const parent = await this.resolveSessionParent(current);
|
|
4589
|
+
if (parent === void 0) return null;
|
|
4590
|
+
if (parent === null) return false;
|
|
4591
|
+
current = parent;
|
|
4592
|
+
}
|
|
4593
|
+
return null;
|
|
4594
|
+
}
|
|
3597
4595
|
/**
|
|
3598
4596
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
3599
4597
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -3616,19 +4614,36 @@ var ChannelDriver = class {
|
|
|
3616
4614
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3617
4615
|
return parent;
|
|
3618
4616
|
}
|
|
4617
|
+
/**
|
|
4618
|
+
* OpenCode's synchronous default session title (e.g.
|
|
4619
|
+
* `"New session - 1737800000000"`), assigned immediately when a session is
|
|
4620
|
+
* created — before OpenCode's async LLM-based auto-titling later renames it
|
|
4621
|
+
* mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
|
|
4622
|
+
* timestamp suffix's exact format is deliberately NOT matched, since the prefix
|
|
4623
|
+
* alone is the stable, cheap signal and over-anchoring on the timestamp
|
|
4624
|
+
* representation risks silently breaking if OpenCode ever changes it. Accepted
|
|
4625
|
+
* trade-off: a genuine LLM-assigned title that happens to literally start with
|
|
4626
|
+
* this prefix would also fail to latch (see `resolveSessionTitle`) —
|
|
4627
|
+
* vanishingly unlikely in practice, and deliberately not engineered around.
|
|
4628
|
+
*/
|
|
4629
|
+
static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
|
|
3619
4630
|
/**
|
|
3620
4631
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3621
4632
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3622
4633
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3623
4634
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3624
4635
|
* Best-effort:
|
|
3625
|
-
* - a resolved NON-EMPTY title
|
|
4636
|
+
* - a resolved NON-EMPTY title that does NOT match
|
|
4637
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
|
|
3626
4638
|
* won't later un-name), so we do NOT re-GET `/session/:id` every tick;
|
|
3627
|
-
* - while the title is still absent
|
|
3628
|
-
*
|
|
3629
|
-
*
|
|
3630
|
-
*
|
|
3631
|
-
*
|
|
4639
|
+
* - while the title is still absent, empty, or matches the OpenCode
|
|
4640
|
+
* placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
|
|
4641
|
+
* asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
|
|
4642
|
+
* the cache unresolved and re-fetch on the next need so a later call (e.g. at
|
|
4643
|
+
* `done`) picks up the name assigned in the meantime. Such a call returns
|
|
4644
|
+
* `null` (omit the title on THIS PATCH) without caching. If a session is
|
|
4645
|
+
* never renamed, the title is omitted forever rather than ever persisting
|
|
4646
|
+
* the placeholder as a last resort;
|
|
3632
4647
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3633
4648
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3634
4649
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3641,7 +4656,7 @@ var ChannelDriver = class {
|
|
|
3641
4656
|
if (res.ok) {
|
|
3642
4657
|
const body = await res.json();
|
|
3643
4658
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3644
|
-
if (title.length > 0) {
|
|
4659
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3645
4660
|
this.sessionTitles.set(sessionId, title);
|
|
3646
4661
|
return title;
|
|
3647
4662
|
}
|
|
@@ -3661,6 +4676,54 @@ var ChannelDriver = class {
|
|
|
3661
4676
|
}
|
|
3662
4677
|
return null;
|
|
3663
4678
|
}
|
|
4679
|
+
/**
|
|
4680
|
+
* Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
|
|
4681
|
+
* session title onto the conversation via the PLAIN conversation-update
|
|
4682
|
+
* endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
|
|
4683
|
+
* message-status endpoint `markProcessing`/`markDone` use. Deliberately a
|
|
4684
|
+
* separate, lighter call: it carries no `status`, so it cannot re-trigger the
|
|
4685
|
+
* `processing`/`done` transition side effects (Slack notices, activity-log
|
|
4686
|
+
* rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
|
|
4687
|
+
* ever touches `conversations.title`. That route (`routes/conversations.ts`)
|
|
4688
|
+
* skips a title write matching the stored value, so a redundant call with the
|
|
4689
|
+
* same title is a real no-op — it does not bump `updated_at`, which the
|
|
4690
|
+
* conversation list sorts and paginates on. (Note this is a DIFFERENT guard
|
|
4691
|
+
* from `threads.ts`'s "non-empty AND changed" one, which only covers the
|
|
4692
|
+
* message-status PATCH; the non-empty half is enforced here instead, by
|
|
4693
|
+
* `resolveSessionTitle` never returning an empty/placeholder title.)
|
|
4694
|
+
*
|
|
4695
|
+
* Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
|
|
4696
|
+
* is logged and the title is simply retried on the next heartbeat tick (the
|
|
4697
|
+
* caller only latches `titleSynced` on `true`).
|
|
4698
|
+
*/
|
|
4699
|
+
async patchConversationTitle(conversationId, title) {
|
|
4700
|
+
try {
|
|
4701
|
+
const res = await this.fetchImpl(
|
|
4702
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
|
|
4703
|
+
{
|
|
4704
|
+
method: "PATCH",
|
|
4705
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
4706
|
+
body: JSON.stringify({ title })
|
|
4707
|
+
}
|
|
4708
|
+
);
|
|
4709
|
+
if (!res.ok) {
|
|
4710
|
+
this.log({
|
|
4711
|
+
level: "debug",
|
|
4712
|
+
message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
|
|
4713
|
+
conversation_id: conversationId
|
|
4714
|
+
});
|
|
4715
|
+
return false;
|
|
4716
|
+
}
|
|
4717
|
+
return true;
|
|
4718
|
+
} catch (err) {
|
|
4719
|
+
this.log({
|
|
4720
|
+
level: "debug",
|
|
4721
|
+
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)}`,
|
|
4722
|
+
conversation_id: conversationId
|
|
4723
|
+
});
|
|
4724
|
+
return false;
|
|
4725
|
+
}
|
|
4726
|
+
}
|
|
3664
4727
|
/**
|
|
3665
4728
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
3666
4729
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -3719,6 +4782,84 @@ var ChannelDriver = class {
|
|
|
3719
4782
|
}
|
|
3720
4783
|
return false;
|
|
3721
4784
|
}
|
|
4785
|
+
/**
|
|
4786
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4787
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4788
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4789
|
+
*
|
|
4790
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4791
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4792
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4793
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4794
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4795
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4796
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4797
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4798
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4799
|
+
* executing, between its step's completion and the next generation step"
|
|
4800
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4801
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4802
|
+
* message timestamps at all.
|
|
4803
|
+
*
|
|
4804
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4805
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4806
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4807
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4808
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4809
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4810
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4811
|
+
* delegation — which the root's status is not.
|
|
4812
|
+
*
|
|
4813
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4814
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4815
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4816
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4817
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4818
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4819
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4820
|
+
* instead.
|
|
4821
|
+
*
|
|
4822
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4823
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4824
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4825
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4826
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4827
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4828
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4829
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4830
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4831
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4832
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4833
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4834
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4835
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4836
|
+
* (unlike the recovery cross-check's contract) — see
|
|
4837
|
+
* `isB2AbandonmentConfirmed`.
|
|
4838
|
+
*/
|
|
4839
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
4840
|
+
const sessions = await listSessions(this.port);
|
|
4841
|
+
if (!sessions) {
|
|
4842
|
+
this.log({
|
|
4843
|
+
level: "warn",
|
|
4844
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
4845
|
+
});
|
|
4846
|
+
return null;
|
|
4847
|
+
}
|
|
4848
|
+
let indeterminate = false;
|
|
4849
|
+
for (const candidate of sessions) {
|
|
4850
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
4851
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
4852
|
+
if (membership === null) {
|
|
4853
|
+
indeterminate = true;
|
|
4854
|
+
continue;
|
|
4855
|
+
}
|
|
4856
|
+
if (membership === false) continue;
|
|
4857
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
4858
|
+
if (ongoing === true) return true;
|
|
4859
|
+
if (ongoing === null) indeterminate = true;
|
|
4860
|
+
}
|
|
4861
|
+
return indeterminate ? null : false;
|
|
4862
|
+
}
|
|
3722
4863
|
/**
|
|
3723
4864
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
3724
4865
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -3847,6 +4988,32 @@ var ChannelDriver = class {
|
|
|
3847
4988
|
}
|
|
3848
4989
|
return messages;
|
|
3849
4990
|
}
|
|
4991
|
+
/**
|
|
4992
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
4993
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
4994
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
4995
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
4996
|
+
*
|
|
4997
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
4998
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
4999
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
5000
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
5001
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
5002
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
5003
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
5004
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
5005
|
+
* stick.
|
|
5006
|
+
*/
|
|
5007
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
5008
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
5009
|
+
this.log({
|
|
5010
|
+
level: "debug",
|
|
5011
|
+
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)}`,
|
|
5012
|
+
conversation_id: conversationId,
|
|
5013
|
+
message_id: messageId
|
|
5014
|
+
});
|
|
5015
|
+
return {};
|
|
5016
|
+
}
|
|
3850
5017
|
/**
|
|
3851
5018
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3852
5019
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3876,7 +5043,7 @@ var ChannelDriver = class {
|
|
|
3876
5043
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3877
5044
|
body: JSON.stringify({
|
|
3878
5045
|
status: "processing",
|
|
3879
|
-
|
|
5046
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3880
5047
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3881
5048
|
...title ? { title } : {}
|
|
3882
5049
|
})
|
|
@@ -3925,6 +5092,11 @@ var ChannelDriver = class {
|
|
|
3925
5092
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3926
5093
|
body: JSON.stringify({
|
|
3927
5094
|
status: "done",
|
|
5095
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
5096
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
5097
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
5098
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
5099
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3928
5100
|
opencode_session_id: sessionId,
|
|
3929
5101
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3930
5102
|
...title ? { title } : {},
|
|
@@ -3941,16 +5113,31 @@ var ChannelDriver = class {
|
|
|
3941
5113
|
}
|
|
3942
5114
|
/**
|
|
3943
5115
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3944
|
-
* when provided (issue #182)
|
|
3945
|
-
* `
|
|
3946
|
-
*
|
|
3947
|
-
*
|
|
5116
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
5117
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
5118
|
+
* session untouched (unused today; kept for API symmetry).
|
|
5119
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
5120
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
5121
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
5122
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
5123
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
5124
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
3948
5125
|
*/
|
|
3949
|
-
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
5126
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
3950
5127
|
const body = { status: "failed" };
|
|
3951
|
-
if (sessionId
|
|
5128
|
+
if (sessionId === null) {
|
|
5129
|
+
body.opencode_session_id = null;
|
|
5130
|
+
} else if (sessionId !== void 0) {
|
|
5131
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
5132
|
+
}
|
|
3952
5133
|
if (error2 !== void 0) body.error = error2;
|
|
3953
5134
|
if (usage) Object.assign(body, usage);
|
|
5135
|
+
if (failure) {
|
|
5136
|
+
body.failure_kind = failure.kind;
|
|
5137
|
+
body.failure_provider_id = failure.providerId;
|
|
5138
|
+
body.failure_model_id = failure.modelId;
|
|
5139
|
+
body.failure_reason = failure.reason;
|
|
5140
|
+
}
|
|
3954
5141
|
await this.callWithRetry(
|
|
3955
5142
|
"marking message as failed",
|
|
3956
5143
|
() => this.fetchImpl(
|
|
@@ -3963,6 +5150,29 @@ var ChannelDriver = class {
|
|
|
3963
5150
|
)
|
|
3964
5151
|
);
|
|
3965
5152
|
}
|
|
5153
|
+
/**
|
|
5154
|
+
* Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
|
|
5155
|
+
*
|
|
5156
|
+
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
5157
|
+
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
5158
|
+
* to the P1-2b zero-provider check — one extra loopback call to
|
|
5159
|
+
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
5160
|
+
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
5161
|
+
* (`null`/indeterminate) leaves the classification `null`, which produces
|
|
5162
|
+
* today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
|
|
5163
|
+
*/
|
|
5164
|
+
async classifyModelAuthFailure(messages, userMessageId) {
|
|
5165
|
+
const classified = messageFailure(messages, userMessageId);
|
|
5166
|
+
if (classified != null) return classified;
|
|
5167
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5168
|
+
const hasProvider = await hasAnyConfiguredProvider(this.port);
|
|
5169
|
+
return applyZeroProviderFallback(
|
|
5170
|
+
classified,
|
|
5171
|
+
hasProvider,
|
|
5172
|
+
reply?.info?.providerID ?? null,
|
|
5173
|
+
reply?.info?.modelID ?? null
|
|
5174
|
+
);
|
|
5175
|
+
}
|
|
3966
5176
|
/**
|
|
3967
5177
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
3968
5178
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -4115,10 +5325,16 @@ var ChannelDriver = class {
|
|
|
4115
5325
|
import chalk5 from "chalk";
|
|
4116
5326
|
import ora2 from "ora";
|
|
4117
5327
|
import { select as select2 } from "@inquirer/prompts";
|
|
5328
|
+
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
4118
5329
|
async function ensureOpenCodeRunning(ctx) {
|
|
4119
5330
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
4120
5331
|
if (healthCheck.healthy) {
|
|
4121
|
-
return {
|
|
5332
|
+
return {
|
|
5333
|
+
port: ctx.port,
|
|
5334
|
+
process: null,
|
|
5335
|
+
version: healthCheck.version ?? null,
|
|
5336
|
+
notReadyReason: null
|
|
5337
|
+
};
|
|
4122
5338
|
}
|
|
4123
5339
|
const runningInstances = await findHealthyOpenCodeInstances();
|
|
4124
5340
|
if (runningInstances.length > 0) {
|
|
@@ -4139,7 +5355,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4139
5355
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4140
5356
|
console.log(
|
|
4141
5357
|
chalk5.dim(
|
|
4142
|
-
` ${getCliName()} run --
|
|
5358
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4143
5359
|
)
|
|
4144
5360
|
);
|
|
4145
5361
|
}
|
|
@@ -4159,14 +5375,22 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4159
5375
|
if (!ctx.interactive) {
|
|
4160
5376
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
4161
5377
|
const proc = await startOpenCode(ctx.port);
|
|
4162
|
-
const health = await waitForOpenCodeHealth(ctx.port,
|
|
5378
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
4163
5379
|
if (!health.healthy) {
|
|
4164
|
-
|
|
4165
|
-
|
|
4166
|
-
|
|
5380
|
+
return {
|
|
5381
|
+
port: ctx.port,
|
|
5382
|
+
process: proc,
|
|
5383
|
+
version: null,
|
|
5384
|
+
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
|
|
5385
|
+
};
|
|
4167
5386
|
}
|
|
4168
5387
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
4169
|
-
return {
|
|
5388
|
+
return {
|
|
5389
|
+
port: ctx.port,
|
|
5390
|
+
process: proc,
|
|
5391
|
+
version: health.version ?? null,
|
|
5392
|
+
notReadyReason: null
|
|
5393
|
+
};
|
|
4170
5394
|
}
|
|
4171
5395
|
let port = ctx.port;
|
|
4172
5396
|
if (isPortInUse(port)) {
|
|
@@ -4219,15 +5443,15 @@ Port ${port} is already in use.`));
|
|
|
4219
5443
|
if (action === "start") {
|
|
4220
5444
|
const spinner = ora2("Starting OpenCode...").start();
|
|
4221
5445
|
const proc = await startOpenCode(port);
|
|
4222
|
-
const health = await waitForOpenCodeHealth(port,
|
|
5446
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
4223
5447
|
if (!health.healthy) {
|
|
4224
5448
|
spinner.fail("Failed to start OpenCode");
|
|
4225
5449
|
throw new Error("OpenCode failed to start");
|
|
4226
5450
|
}
|
|
4227
5451
|
spinner.stop();
|
|
4228
|
-
return { port, process: proc, version: health.version ?? null };
|
|
5452
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
4229
5453
|
}
|
|
4230
|
-
return { port, process: null, version: null };
|
|
5454
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
4231
5455
|
}
|
|
4232
5456
|
|
|
4233
5457
|
// src/commands/agent-lookup.ts
|
|
@@ -4269,19 +5493,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4269
5493
|
return { agent_id: data.agent_id };
|
|
4270
5494
|
}
|
|
4271
5495
|
return {
|
|
4272
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5496
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
4273
5497
|
};
|
|
4274
5498
|
} catch (error2) {
|
|
4275
5499
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
4276
5500
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
4277
5501
|
}
|
|
4278
5502
|
}
|
|
5503
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
4279
5504
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4280
5505
|
const apiUrl = getApiUrlConfig();
|
|
4281
5506
|
try {
|
|
4282
5507
|
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4283
5508
|
method: "POST",
|
|
4284
|
-
headers: { Authorization: authHeader }
|
|
5509
|
+
headers: { Authorization: authHeader },
|
|
5510
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
4285
5511
|
});
|
|
4286
5512
|
if (!response.ok) {
|
|
4287
5513
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -4292,7 +5518,35 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4292
5518
|
}
|
|
4293
5519
|
return { ok: true };
|
|
4294
5520
|
} catch (error2) {
|
|
4295
|
-
return { ok: false, error:
|
|
5521
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5522
|
+
}
|
|
5523
|
+
}
|
|
5524
|
+
function describeBestEffortError(error2) {
|
|
5525
|
+
const name = error2?.name;
|
|
5526
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5527
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5528
|
+
}
|
|
5529
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5530
|
+
}
|
|
5531
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5532
|
+
try {
|
|
5533
|
+
const apiUrl = getApiUrlConfig();
|
|
5534
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5535
|
+
method: "POST",
|
|
5536
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5537
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5538
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5539
|
+
});
|
|
5540
|
+
if (!response.ok) {
|
|
5541
|
+
const serverMessage = await readErrorMessage(response);
|
|
5542
|
+
return {
|
|
5543
|
+
ok: false,
|
|
5544
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5545
|
+
};
|
|
5546
|
+
}
|
|
5547
|
+
return { ok: true };
|
|
5548
|
+
} catch (error2) {
|
|
5549
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
4296
5550
|
}
|
|
4297
5551
|
}
|
|
4298
5552
|
async function getAgentInfo(agentId, authHeader) {
|
|
@@ -4342,6 +5596,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
4342
5596
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
4343
5597
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4344
5598
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5599
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
4345
5600
|
function resolveLogLevel(options) {
|
|
4346
5601
|
const accepted = Object.keys(LOG_LEVELS);
|
|
4347
5602
|
const validate = (value, source) => {
|
|
@@ -4365,6 +5620,63 @@ function resolveLogLevel(options) {
|
|
|
4365
5620
|
}
|
|
4366
5621
|
return "info";
|
|
4367
5622
|
}
|
|
5623
|
+
function resolveFileSyncDirectories(raw, homeDir) {
|
|
5624
|
+
const directories = [];
|
|
5625
|
+
for (const entry of raw ?? []) {
|
|
5626
|
+
const trimmed = entry.trim();
|
|
5627
|
+
if (trimmed === "") {
|
|
5628
|
+
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5629
|
+
}
|
|
5630
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
|
|
5631
|
+
if (!isAbsolute2(expanded)) {
|
|
5632
|
+
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5633
|
+
}
|
|
5634
|
+
const normalized = resolvePath(expanded);
|
|
5635
|
+
if (parse(normalized).root === normalized) {
|
|
5636
|
+
throw new Error(
|
|
5637
|
+
`--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
|
|
5638
|
+
);
|
|
5639
|
+
}
|
|
5640
|
+
if (!directories.includes(normalized)) {
|
|
5641
|
+
directories.push(normalized);
|
|
5642
|
+
}
|
|
5643
|
+
}
|
|
5644
|
+
if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
|
|
5645
|
+
throw new Error(
|
|
5646
|
+
`--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
|
|
5647
|
+
);
|
|
5648
|
+
}
|
|
5649
|
+
return directories;
|
|
5650
|
+
}
|
|
5651
|
+
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
5652
|
+
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
5653
|
+
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
5654
|
+
function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
5655
|
+
const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
|
|
5656
|
+
let raw;
|
|
5657
|
+
let source;
|
|
5658
|
+
if (options.opencodeStartTimeout !== void 0) {
|
|
5659
|
+
raw = options.opencodeStartTimeout;
|
|
5660
|
+
source = "--opencode-start-timeout";
|
|
5661
|
+
} else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
|
|
5662
|
+
raw = env[OPENCODE_START_TIMEOUT_ENV];
|
|
5663
|
+
source = OPENCODE_START_TIMEOUT_ENV;
|
|
5664
|
+
} else {
|
|
5665
|
+
return { timeoutMs: defaultMs, warnings: [] };
|
|
5666
|
+
}
|
|
5667
|
+
const trimmed = raw.trim();
|
|
5668
|
+
const seconds = Number(trimmed);
|
|
5669
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
|
|
5670
|
+
if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
|
|
5671
|
+
return {
|
|
5672
|
+
timeoutMs: defaultMs,
|
|
5673
|
+
warnings: [
|
|
5674
|
+
`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`
|
|
5675
|
+
]
|
|
5676
|
+
};
|
|
5677
|
+
}
|
|
5678
|
+
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
5679
|
+
}
|
|
4368
5680
|
function meetsThreshold(state, level) {
|
|
4369
5681
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4370
5682
|
}
|
|
@@ -4386,6 +5698,10 @@ function log2(state, message, level = "info") {
|
|
|
4386
5698
|
function logActivity(state, entry) {
|
|
4387
5699
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
4388
5700
|
if (!meetsThreshold(state, level)) return;
|
|
5701
|
+
forwardRunnerActivity(
|
|
5702
|
+
{ level, message: entry.message, error: entry.error },
|
|
5703
|
+
{ agentId: state.agentId, authHeader: state.authHeader }
|
|
5704
|
+
);
|
|
4389
5705
|
const fullEntry = {
|
|
4390
5706
|
...entry,
|
|
4391
5707
|
level,
|
|
@@ -4486,18 +5802,29 @@ async function handleAuthError(state, error2) {
|
|
|
4486
5802
|
async function driveChannels(state, driver) {
|
|
4487
5803
|
let idlePolls = 0;
|
|
4488
5804
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5805
|
+
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
4489
5806
|
while (state.running) {
|
|
4490
5807
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
4491
5808
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
4492
5809
|
if (state.interactive) displayStatus(state);
|
|
4493
5810
|
await state.connection.reconnectPromise;
|
|
4494
5811
|
}
|
|
5812
|
+
const carriedOverFileSync = driver.fileSyncActivity().inFlight;
|
|
5813
|
+
void driver.syncPendingFiles().catch(
|
|
5814
|
+
(error2) => logActivity(state, {
|
|
5815
|
+
type: "error",
|
|
5816
|
+
error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5817
|
+
})
|
|
5818
|
+
);
|
|
4495
5819
|
try {
|
|
4496
5820
|
const processed = await driver.drainPending();
|
|
4497
5821
|
state.messageCount += processed;
|
|
4498
5822
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4499
5823
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4500
|
-
|
|
5824
|
+
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5825
|
+
const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
|
|
5826
|
+
lastSeenAppliedFiles = appliedFiles;
|
|
5827
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
4501
5828
|
idlePolls = 0;
|
|
4502
5829
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
4503
5830
|
} else if (state.idleTimeout !== null) {
|
|
@@ -4526,7 +5853,7 @@ async function driveChannels(state, driver) {
|
|
|
4526
5853
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
4527
5854
|
if (state.interactive) displayStatus(state);
|
|
4528
5855
|
}
|
|
4529
|
-
await new Promise((
|
|
5856
|
+
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
4530
5857
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
4531
5858
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
4532
5859
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -4629,7 +5956,18 @@ async function notifyOffline(state) {
|
|
|
4629
5956
|
if (state.interactive) displayStatus(state);
|
|
4630
5957
|
}
|
|
4631
5958
|
}
|
|
5959
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
5960
|
+
const startedAt = Date.now();
|
|
5961
|
+
try {
|
|
5962
|
+
return await run2();
|
|
5963
|
+
} finally {
|
|
5964
|
+
const elapsedMs = Date.now() - startedAt;
|
|
5965
|
+
durations[name] = elapsedMs;
|
|
5966
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
5967
|
+
}
|
|
5968
|
+
}
|
|
4632
5969
|
async function cleanup(state, opts = {}) {
|
|
5970
|
+
const durations = {};
|
|
4633
5971
|
state.running = false;
|
|
4634
5972
|
for (const timer of state.sessionCleanupTimers) {
|
|
4635
5973
|
clearInterval(timer);
|
|
@@ -4643,7 +5981,13 @@ async function cleanup(state, opts = {}) {
|
|
|
4643
5981
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4644
5982
|
displayStatus(state);
|
|
4645
5983
|
}
|
|
4646
|
-
const
|
|
5984
|
+
const driver = state.channelDriver;
|
|
5985
|
+
const settled = await timeShutdownPhase(
|
|
5986
|
+
state,
|
|
5987
|
+
durations,
|
|
5988
|
+
"drain",
|
|
5989
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
5990
|
+
);
|
|
4647
5991
|
if (!settled) {
|
|
4648
5992
|
logActivity(state, {
|
|
4649
5993
|
type: "info",
|
|
@@ -4652,13 +5996,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4652
5996
|
if (state.interactive) displayStatus(state);
|
|
4653
5997
|
}
|
|
4654
5998
|
}
|
|
4655
|
-
await notifyOffline(state);
|
|
5999
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
4656
6000
|
if (state.connection) {
|
|
4657
|
-
state.connection
|
|
6001
|
+
const connection = state.connection;
|
|
6002
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
4658
6003
|
state.connection = null;
|
|
4659
6004
|
}
|
|
4660
6005
|
if (state.opencodeProcess) {
|
|
4661
|
-
|
|
6006
|
+
const opencodeProcess = state.opencodeProcess;
|
|
6007
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
4662
6008
|
if (state.interactive) {
|
|
4663
6009
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
4664
6010
|
displayStatus(state);
|
|
@@ -4667,12 +6013,15 @@ async function cleanup(state, opts = {}) {
|
|
|
4667
6013
|
}
|
|
4668
6014
|
state.opencodeProcess = null;
|
|
4669
6015
|
}
|
|
6016
|
+
return durations;
|
|
4670
6017
|
}
|
|
4671
6018
|
async function run(options) {
|
|
4672
6019
|
const interactive = isInteractive(options.json);
|
|
4673
6020
|
let logLevel;
|
|
6021
|
+
let fileSyncDirectories;
|
|
4674
6022
|
try {
|
|
4675
6023
|
logLevel = resolveLogLevel(options);
|
|
6024
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
|
|
4676
6025
|
} catch (error2) {
|
|
4677
6026
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4678
6027
|
if (options.json) {
|
|
@@ -4707,6 +6056,12 @@ async function run(options) {
|
|
|
4707
6056
|
sessionCleanupTimers: [],
|
|
4708
6057
|
authHeader: ""
|
|
4709
6058
|
};
|
|
6059
|
+
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
6060
|
+
if (fileSyncDirectories.length > 0) {
|
|
6061
|
+
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
6062
|
+
} else {
|
|
6063
|
+
log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
|
|
6064
|
+
}
|
|
4710
6065
|
if (!options.runner && options.agent) {
|
|
4711
6066
|
telemetry.info(
|
|
4712
6067
|
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
@@ -4730,14 +6085,38 @@ async function run(options) {
|
|
|
4730
6085
|
const handleSignal = async () => {
|
|
4731
6086
|
if (state.shuttingDown) return;
|
|
4732
6087
|
state.shuttingDown = true;
|
|
6088
|
+
const shutdownStartedAt = Date.now();
|
|
4733
6089
|
if (state.interactive) {
|
|
4734
6090
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
4735
6091
|
displayStatus(state);
|
|
4736
6092
|
} else {
|
|
4737
6093
|
log2(state, "Shutting down...");
|
|
4738
6094
|
}
|
|
4739
|
-
await cleanup(state, { graceful: true });
|
|
4740
|
-
|
|
6095
|
+
const durations = await cleanup(state, { graceful: true });
|
|
6096
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
6097
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
6098
|
+
let timer;
|
|
6099
|
+
const flushed = shutdownTelemetry().then(
|
|
6100
|
+
() => true,
|
|
6101
|
+
(error2) => {
|
|
6102
|
+
log2(
|
|
6103
|
+
state,
|
|
6104
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
6105
|
+
"warn"
|
|
6106
|
+
);
|
|
6107
|
+
return true;
|
|
6108
|
+
}
|
|
6109
|
+
);
|
|
6110
|
+
const timedOut = new Promise((resolve3) => {
|
|
6111
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
6112
|
+
});
|
|
6113
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
6114
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
6115
|
+
}
|
|
6116
|
+
clearTimeout(timer);
|
|
6117
|
+
});
|
|
6118
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
6119
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
4741
6120
|
process.exit(0);
|
|
4742
6121
|
};
|
|
4743
6122
|
process.on("SIGINT", handleSignal);
|
|
@@ -4851,25 +6230,67 @@ async function run(options) {
|
|
|
4851
6230
|
}
|
|
4852
6231
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
4853
6232
|
state.agentName = validation.agent.name;
|
|
6233
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
6234
|
+
if (microvmId) {
|
|
6235
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
6236
|
+
if (reported.ok) {
|
|
6237
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
6238
|
+
} else {
|
|
6239
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
6240
|
+
log2(state, message, "warn");
|
|
6241
|
+
if (state.interactive && !state.json) {
|
|
6242
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6243
|
+
}
|
|
6244
|
+
}
|
|
6245
|
+
} else {
|
|
6246
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6247
|
+
}
|
|
6248
|
+
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
6249
|
+
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6250
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6251
|
+
}
|
|
4854
6252
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
4855
6253
|
try {
|
|
4856
6254
|
const oc = await ensureOpenCodeRunning({
|
|
4857
6255
|
port: state.port,
|
|
4858
6256
|
interactive: state.interactive,
|
|
4859
6257
|
agentId: state.agentId,
|
|
4860
|
-
log: (message) => log2(state, message)
|
|
6258
|
+
log: (message) => log2(state, message),
|
|
6259
|
+
startTimeoutMs: opencodeStartTimeoutMs
|
|
4861
6260
|
});
|
|
4862
6261
|
state.port = oc.port;
|
|
4863
6262
|
state.opencodeProcess = oc.process;
|
|
4864
6263
|
state.opencodeVersion = oc.version;
|
|
4865
|
-
state.opencodeConnected = oc.
|
|
6264
|
+
state.opencodeConnected = oc.notReadyReason === null;
|
|
4866
6265
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
4867
6266
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
|
|
4872
|
-
|
|
6267
|
+
if (!state.interactive && oc.notReadyReason !== null) {
|
|
6268
|
+
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}).`;
|
|
6269
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6270
|
+
} else {
|
|
6271
|
+
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
6272
|
+
if (versionWarning) {
|
|
6273
|
+
log2(state, versionWarning, "warn");
|
|
6274
|
+
if (state.interactive && !state.json) {
|
|
6275
|
+
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
6276
|
+
}
|
|
6277
|
+
}
|
|
6278
|
+
const noProviderWarning = buildNoProviderWarning(
|
|
6279
|
+
await hasAnyConfiguredProvider(state.port)
|
|
6280
|
+
);
|
|
6281
|
+
if (noProviderWarning) {
|
|
6282
|
+
log2(state, noProviderWarning, "warn");
|
|
6283
|
+
if (state.interactive && !state.json) {
|
|
6284
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6285
|
+
blank();
|
|
6286
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6287
|
+
console.log(
|
|
6288
|
+
chalk6.dim(
|
|
6289
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6290
|
+
)
|
|
6291
|
+
);
|
|
6292
|
+
blank();
|
|
6293
|
+
}
|
|
4873
6294
|
}
|
|
4874
6295
|
}
|
|
4875
6296
|
} catch (error2) {
|
|
@@ -4884,6 +6305,10 @@ async function run(options) {
|
|
|
4884
6305
|
getAuthHeader: () => state.authHeader,
|
|
4885
6306
|
conversationFilter: state.conversationFilter,
|
|
4886
6307
|
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
6308
|
+
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
6309
|
+
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
6310
|
+
fileSyncDirectories,
|
|
6311
|
+
homeDir: homedir2(),
|
|
4887
6312
|
log: (entry) => (
|
|
4888
6313
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4889
6314
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -4910,6 +6335,18 @@ async function run(options) {
|
|
|
4910
6335
|
type: "info",
|
|
4911
6336
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
4912
6337
|
});
|
|
6338
|
+
if (options.tunnelReadyFile) {
|
|
6339
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6340
|
+
if (marker.ok) {
|
|
6341
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6342
|
+
} else {
|
|
6343
|
+
log2(
|
|
6344
|
+
state,
|
|
6345
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6346
|
+
"error"
|
|
6347
|
+
);
|
|
6348
|
+
}
|
|
6349
|
+
}
|
|
4913
6350
|
emitAgentConnected(state.agentId, {
|
|
4914
6351
|
port: state.port,
|
|
4915
6352
|
cli_version: getCliVersion(),
|
|
@@ -4965,6 +6402,12 @@ async function run(options) {
|
|
|
4965
6402
|
onDrainPing: () => {
|
|
4966
6403
|
if (!state.running) return;
|
|
4967
6404
|
logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
|
|
6405
|
+
void channelDriver.syncPendingFiles().catch(
|
|
6406
|
+
(error2) => logActivity(state, {
|
|
6407
|
+
type: "error",
|
|
6408
|
+
error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
6409
|
+
})
|
|
6410
|
+
);
|
|
4968
6411
|
channelDriver.drainPending().then((processed) => {
|
|
4969
6412
|
if (processed > 0) {
|
|
4970
6413
|
state.messageCount += processed;
|
|
@@ -5048,10 +6491,16 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
5048
6491
|
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);
|
|
5049
6492
|
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 }));
|
|
5050
6493
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
5051
|
-
program.command("run").description("Connect to Evident and process messages").option("
|
|
6494
|
+
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(
|
|
6495
|
+
"-a, --agent [id]",
|
|
6496
|
+
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
6497
|
+
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
5052
6498
|
"--log-level <level>",
|
|
5053
6499
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
5054
|
-
).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(
|
|
6500
|
+
).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(
|
|
6501
|
+
"--opencode-start-timeout <seconds>",
|
|
6502
|
+
"Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
|
|
6503
|
+
).option("--json", "Output in JSON format").option(
|
|
5055
6504
|
"--session-cleanup-max-age <duration>",
|
|
5056
6505
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
5057
6506
|
).option(
|
|
@@ -5060,6 +6509,14 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5060
6509
|
).option(
|
|
5061
6510
|
"--session-cleanup-interval <duration>",
|
|
5062
6511
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6512
|
+
).option(
|
|
6513
|
+
"--enable-file-sync-to <dir>",
|
|
6514
|
+
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
6515
|
+
(value, previous) => previous.concat([value]),
|
|
6516
|
+
[]
|
|
6517
|
+
).option(
|
|
6518
|
+
"--tunnel-ready-file <path>",
|
|
6519
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
5063
6520
|
).action(
|
|
5064
6521
|
(options) => {
|
|
5065
6522
|
run({
|
|
@@ -5072,11 +6529,18 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5072
6529
|
verbose: options.verbose,
|
|
5073
6530
|
conversation: options.conversation,
|
|
5074
6531
|
idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
|
|
6532
|
+
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
6533
|
+
// resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
|
|
6534
|
+
opencodeStartTimeout: options.opencodeStartTimeout,
|
|
5075
6535
|
json: options.json,
|
|
5076
6536
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
5077
6537
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
5078
6538
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
5079
|
-
sessionCleanupInterval: options.sessionCleanupInterval
|
|
6539
|
+
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6540
|
+
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6541
|
+
// resolveFileSyncDirectories.
|
|
6542
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6543
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
5080
6544
|
});
|
|
5081
6545
|
}
|
|
5082
6546
|
);
|