@evident-ai/cli 3.1.1-dev.fe0815c → 3.2.1-dev.6b1a578
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/dist/index.js +589 -82
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -212,6 +212,7 @@ var api = {
|
|
|
212
212
|
|
|
213
213
|
// src/lib/keychain.ts
|
|
214
214
|
var SERVICE_NAME = "evident-cli";
|
|
215
|
+
var keytarWarned = false;
|
|
215
216
|
async function getKeytar() {
|
|
216
217
|
try {
|
|
217
218
|
const keytar = await import("keytar");
|
|
@@ -219,7 +220,13 @@ async function getKeytar() {
|
|
|
219
220
|
return null;
|
|
220
221
|
}
|
|
221
222
|
return keytar;
|
|
222
|
-
} catch {
|
|
223
|
+
} catch (err) {
|
|
224
|
+
if (!keytarWarned) {
|
|
225
|
+
keytarWarned = true;
|
|
226
|
+
console.warn(
|
|
227
|
+
`System keychain unavailable, falling back to file-based credential storage: ${err instanceof Error ? err.message : String(err)}`
|
|
228
|
+
);
|
|
229
|
+
}
|
|
223
230
|
return null;
|
|
224
231
|
}
|
|
225
232
|
}
|
|
@@ -368,8 +375,9 @@ async function deviceFlowLogin(options) {
|
|
|
368
375
|
await waitForEnter("Press Enter to open the browser...");
|
|
369
376
|
try {
|
|
370
377
|
await open(verification_uri);
|
|
371
|
-
} catch {
|
|
372
|
-
|
|
378
|
+
} catch (error2) {
|
|
379
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
380
|
+
console.log(chalk2.dim(`Could not open browser (${message}). Please visit the URL manually.`));
|
|
373
381
|
}
|
|
374
382
|
}
|
|
375
383
|
const spinner = ora("Waiting for authentication...").start();
|
|
@@ -797,6 +805,16 @@ async function checkStatus(jsonMode) {
|
|
|
797
805
|
exitCode: 1
|
|
798
806
|
};
|
|
799
807
|
}
|
|
808
|
+
if (response.status === 404) {
|
|
809
|
+
return {
|
|
810
|
+
ok: false,
|
|
811
|
+
endpoint: apiUrl,
|
|
812
|
+
authLabel: authLabelFor(credentials2),
|
|
813
|
+
reason: "endpoint_not_found",
|
|
814
|
+
error: `${apiUrl}/me returned HTTP 404 \u2014 that endpoint has no /me route, so it is probably missing the /v1 prefix. The credentials were NOT validated.`,
|
|
815
|
+
exitCode: 75
|
|
816
|
+
};
|
|
817
|
+
}
|
|
800
818
|
if (response.status >= 500) {
|
|
801
819
|
const serverMessage = await readErrorMessage(response);
|
|
802
820
|
return {
|
|
@@ -899,14 +917,25 @@ function readClaudeCliCredentials() {
|
|
|
899
917
|
{ encoding: "utf-8", timeout: 2e3, stdio: ["pipe", "pipe", "ignore"] }
|
|
900
918
|
);
|
|
901
919
|
return parseClaudeCliCredentials(raw);
|
|
902
|
-
} catch {
|
|
920
|
+
} catch (err) {
|
|
921
|
+
if (err.status !== 44) {
|
|
922
|
+
console.warn(
|
|
923
|
+
`readClaudeCliCredentials: security find-generic-password failed: ${err instanceof Error ? err.message : String(err)}`
|
|
924
|
+
);
|
|
925
|
+
}
|
|
903
926
|
return null;
|
|
904
927
|
}
|
|
905
928
|
}
|
|
906
929
|
try {
|
|
907
930
|
const raw = readFileSync(join(homedir(), ".claude", ".credentials.json"), "utf-8");
|
|
908
931
|
return parseClaudeCliCredentials(raw);
|
|
909
|
-
} catch {
|
|
932
|
+
} catch (err) {
|
|
933
|
+
const code = err.code;
|
|
934
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
935
|
+
console.warn(
|
|
936
|
+
`readClaudeCliCredentials: reading .claude/.credentials.json failed: ${err instanceof Error ? err.message : String(err)}`
|
|
937
|
+
);
|
|
938
|
+
}
|
|
910
939
|
return null;
|
|
911
940
|
}
|
|
912
941
|
}
|
|
@@ -1404,7 +1433,10 @@ function findOpenCodeProcesses() {
|
|
|
1404
1433
|
}
|
|
1405
1434
|
}
|
|
1406
1435
|
}
|
|
1407
|
-
} catch {
|
|
1436
|
+
} catch (err) {
|
|
1437
|
+
console.warn(
|
|
1438
|
+
`findOpenCodeProcesses: ps fallback failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1439
|
+
);
|
|
1408
1440
|
}
|
|
1409
1441
|
}
|
|
1410
1442
|
for (const pid of pids) {
|
|
@@ -1427,7 +1459,10 @@ function findOpenCodeProcesses() {
|
|
|
1427
1459
|
}
|
|
1428
1460
|
}
|
|
1429
1461
|
}
|
|
1430
|
-
} catch {
|
|
1462
|
+
} catch (err) {
|
|
1463
|
+
console.warn(
|
|
1464
|
+
`findOpenCodeProcesses: process detection failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1465
|
+
);
|
|
1431
1466
|
}
|
|
1432
1467
|
return instances;
|
|
1433
1468
|
}
|
|
@@ -1501,7 +1536,12 @@ function stopOpenCode(opencodeProcess) {
|
|
|
1501
1536
|
} else {
|
|
1502
1537
|
process.kill(-opencodeProcess.pid, "SIGTERM");
|
|
1503
1538
|
}
|
|
1504
|
-
} catch {
|
|
1539
|
+
} catch (err) {
|
|
1540
|
+
if (err.code !== "ESRCH") {
|
|
1541
|
+
console.warn(
|
|
1542
|
+
`stopOpenCode: kill failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1543
|
+
);
|
|
1544
|
+
}
|
|
1505
1545
|
}
|
|
1506
1546
|
}
|
|
1507
1547
|
|
|
@@ -2089,6 +2129,21 @@ function messageError(messages, userMessageId) {
|
|
|
2089
2129
|
}
|
|
2090
2130
|
return "The agent run failed.";
|
|
2091
2131
|
}
|
|
2132
|
+
function isAbortedTerminalReply(messages, userMessageId) {
|
|
2133
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
2134
|
+
const error2 = errorOf(reply);
|
|
2135
|
+
if (error2 == null) return false;
|
|
2136
|
+
if (typeof error2 === "string") return error2.trim() === "Aborted";
|
|
2137
|
+
if (typeof error2 === "object") {
|
|
2138
|
+
const e = error2;
|
|
2139
|
+
if (e.name === "MessageAbortedError") return true;
|
|
2140
|
+
if (e.name === "AbortError") return true;
|
|
2141
|
+
const dataMessage = e.data?.message;
|
|
2142
|
+
const rendered = typeof dataMessage === "string" ? dataMessage : typeof e.message === "string" ? e.message : null;
|
|
2143
|
+
return rendered != null && rendered.trim() === "Aborted";
|
|
2144
|
+
}
|
|
2145
|
+
return false;
|
|
2146
|
+
}
|
|
2092
2147
|
function messageFailure(messages, userMessageId) {
|
|
2093
2148
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
2094
2149
|
const error2 = errorOf(reply);
|
|
@@ -3126,6 +3181,7 @@ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
|
3126
3181
|
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
3127
3182
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
3128
3183
|
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
3184
|
+
var MAX_IDENTICAL_REDRIVE_POLL_FAILURES = 5;
|
|
3129
3185
|
var ChannelAuthError = class extends Error {
|
|
3130
3186
|
constructor(message) {
|
|
3131
3187
|
super(message);
|
|
@@ -3148,6 +3204,10 @@ function backoffDelay(attempt, policy) {
|
|
|
3148
3204
|
function isRetryableStatus(status2) {
|
|
3149
3205
|
return status2 === 429 || status2 >= 500 && status2 <= 599;
|
|
3150
3206
|
}
|
|
3207
|
+
var VOLATILE_BODY_FIELD_PATTERN = /("(?:ref|requestId|request_id|traceId|trace_id)"\s*:\s*)"[^"]*"/gi;
|
|
3208
|
+
function normalizeRedrivePollFailureBody(body) {
|
|
3209
|
+
return body.replace(VOLATILE_BODY_FIELD_PATTERN, '$1"<redacted>"').replace(/\s+/g, " ").trim().slice(0, 200);
|
|
3210
|
+
}
|
|
3151
3211
|
var ChannelDriver = class _ChannelDriver {
|
|
3152
3212
|
agentId;
|
|
3153
3213
|
port;
|
|
@@ -3164,6 +3224,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3164
3224
|
now;
|
|
3165
3225
|
fileSyncDirectories;
|
|
3166
3226
|
homeDir;
|
|
3227
|
+
maxActiveSessions;
|
|
3167
3228
|
/** Cache of conversationId → opencode sessionId. */
|
|
3168
3229
|
sessions = /* @__PURE__ */ new Map();
|
|
3169
3230
|
/**
|
|
@@ -3279,6 +3340,66 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3279
3340
|
* ADR-0047's own "unreachable ⇒ bounded" rule). Cleared on any other outcome.
|
|
3280
3341
|
*/
|
|
3281
3342
|
redriveUnresolvedSince = /* @__PURE__ */ new Map();
|
|
3343
|
+
/**
|
|
3344
|
+
* Consecutive-identical-poll-failure streak for the re-drive fence (#1348),
|
|
3345
|
+
* keyed by Evident **message id** (not session) so `clearRedriveUnresolved`
|
|
3346
|
+
* can drop it with the other two trackers and it cannot leak. `sessionId` is
|
|
3347
|
+
* carried inside the entry, not the key: a session change is a different
|
|
3348
|
+
* situation and resets the streak, which gives the `(sessionId, message.id)`
|
|
3349
|
+
* pairing #1348 asks for without a composite map key.
|
|
3350
|
+
*/
|
|
3351
|
+
redrivePollFailures = /* @__PURE__ */ new Map();
|
|
3352
|
+
/**
|
|
3353
|
+
* "Already emitted `redrive_outcome_unreported` for THIS (message, outcome)
|
|
3354
|
+
* streak" (Class B, #1340: the runner DECIDED reattach/settle/fail_permanent
|
|
3355
|
+
* but its own PATCH to record it failed — distinct from Class A's
|
|
3356
|
+
* `redrive_poll_failed`, where opencode itself can't be observed). Keyed by
|
|
3357
|
+
* message id, valued by the outcome currently failing to report, so a
|
|
3358
|
+
* change of outcome starts a fresh signal. Cleared by
|
|
3359
|
+
* `clearRedriveUnresolved` the instant either PATCH succeeds.
|
|
3360
|
+
*/
|
|
3361
|
+
redriveOutcomeUnreportedSignalled = /* @__PURE__ */ new Map();
|
|
3362
|
+
/**
|
|
3363
|
+
* First `now()` a Class B outcome PATCH (reattach/settle/fail_permanent) was
|
|
3364
|
+
* observed to fail for this message (#1366's failure-window trip arm,
|
|
3365
|
+
* `boundRedriveOutcome`). Duration, not a tick count — bounded by the
|
|
3366
|
+
* existing `pausedMaxWaitMs` window (reusing the knob, not a new constant).
|
|
3367
|
+
* Cleared by `clearRedriveUnresolved` the instant the original PATCH
|
|
3368
|
+
* succeeds.
|
|
3369
|
+
*/
|
|
3370
|
+
redriveOutcomeFailingSince = /* @__PURE__ */ new Map();
|
|
3371
|
+
/**
|
|
3372
|
+
* "Already posted `redrive_outcome_abandoned` with `reported: false` for this
|
|
3373
|
+
* row" (#1366) — the bound tripped but the terminal `markFailed` fallback ALSO
|
|
3374
|
+
* failed (the route-level fault of G2), so every following tick re-attempts
|
|
3375
|
+
* the same terminal PATCH. Guards that quiet retry from re-signalling on
|
|
3376
|
+
* every tick. Cleared by `clearRedriveUnresolved`.
|
|
3377
|
+
*/
|
|
3378
|
+
redriveOutcomeAbandonedSignalled = /* @__PURE__ */ new Set();
|
|
3379
|
+
/**
|
|
3380
|
+
* "Already emitted `dispatch_not_started` for THIS (message, branch) streak"
|
|
3381
|
+
* (#1340). Valued by the branch currently firing, so a row that moves between
|
|
3382
|
+
* exits re-signals — the move IS the finding. Cleared only on a CONFIRMED
|
|
3383
|
+
* dispatch, never on the fence's decision to dispatch: `clearRedriveUnresolved`
|
|
3384
|
+
* runs on that decision (`resolveRedriveUnresolved`), so clearing there would
|
|
3385
|
+
* re-signal on every one of the 15h of re-dispatch attempts #1110 made.
|
|
3386
|
+
*/
|
|
3387
|
+
dispatchNotStartedSignalled = /* @__PURE__ */ new Map();
|
|
3388
|
+
/**
|
|
3389
|
+
* Consecutive-UNCONFIRMED-dispatch streak for a `pending` row with NO stored
|
|
3390
|
+
* `opencode_message_id` yet — i.e. one that has never even reached the
|
|
3391
|
+
* re-drive fence above. `sendPromptAsync`'s POST may 2xx, but its own
|
|
3392
|
+
* read-back retries can never confirm the assigned id when the session's
|
|
3393
|
+
* message list is PERMANENTLY unreadable (e.g. a corrupted local opencode
|
|
3394
|
+
* SQLite DB, #1345/#1348's exact fault, just hit BEFORE the row is ever
|
|
3395
|
+
* dispatched instead of after). Unlike an already-dispatched row, THIS row has
|
|
3396
|
+
* no other safety net at all: the lifecycle cron only reclaims `status =
|
|
3397
|
+
* 'processing'` rows, and a row stuck here never reaches `processing`. Keyed
|
|
3398
|
+
* by message id, carrying `sessionId` so a session change (a fresh one bound
|
|
3399
|
+
* after abandonment) starts a new streak rather than inheriting the old
|
|
3400
|
+
* session's count — same shape as `redrivePollFailures` above.
|
|
3401
|
+
*/
|
|
3402
|
+
unconfirmedDispatchFailures = /* @__PURE__ */ new Map();
|
|
3282
3403
|
/**
|
|
3283
3404
|
* "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
|
|
3284
3405
|
* Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
|
|
@@ -3384,6 +3505,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3384
3505
|
this.now = config.now ?? (() => Date.now());
|
|
3385
3506
|
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
3386
3507
|
this.homeDir = config.homeDir ?? homedir2();
|
|
3508
|
+
this.maxActiveSessions = config.maxActiveSessions;
|
|
3387
3509
|
}
|
|
3388
3510
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
3389
3511
|
get opencodeBase() {
|
|
@@ -3463,10 +3585,26 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3463
3585
|
message: `Found ${total} pending message(s) across ${conversations.length} conversation(s) \u2014 draining`
|
|
3464
3586
|
});
|
|
3465
3587
|
}
|
|
3588
|
+
let cappedSkips = 0;
|
|
3466
3589
|
for (const conv of conversations) {
|
|
3467
3590
|
if (this.stopped) break;
|
|
3591
|
+
if (this.maxActiveSessions !== void 0) {
|
|
3592
|
+
const activeSessionIds = this.activeSessionIdsForCap();
|
|
3593
|
+
const resolvedSessionId = this.sessions.get(conv.id) ?? conv.opencode_session_id;
|
|
3594
|
+
const alreadyActive = resolvedSessionId != null && activeSessionIds.has(resolvedSessionId);
|
|
3595
|
+
if (activeSessionIds.size >= this.maxActiveSessions && !alreadyActive) {
|
|
3596
|
+
cappedSkips++;
|
|
3597
|
+
continue;
|
|
3598
|
+
}
|
|
3599
|
+
}
|
|
3468
3600
|
dispatched += await this.processConversation(conv);
|
|
3469
3601
|
}
|
|
3602
|
+
if (cappedSkips > 0) {
|
|
3603
|
+
this.log({
|
|
3604
|
+
level: "warn",
|
|
3605
|
+
message: `max-active-sessions cap (${this.maxActiveSessions}) reached \u2014 skipped ${cappedSkips} pending conversation(s) this tick`
|
|
3606
|
+
});
|
|
3607
|
+
}
|
|
3470
3608
|
await this.readoptProcessing();
|
|
3471
3609
|
} finally {
|
|
3472
3610
|
this.draining = false;
|
|
@@ -3485,6 +3623,22 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3485
3623
|
}
|
|
3486
3624
|
return false;
|
|
3487
3625
|
}
|
|
3626
|
+
/**
|
|
3627
|
+
* Session ids active *for the `--max-active-sessions` cap*: in-flight work AND
|
|
3628
|
+
* a live watcher loop. Unlike `hasInFlightWatchers()` / `protectedSessionIds()`,
|
|
3629
|
+
* a ZOMBIE watcher (in-flight but `loop === null`, left by a non-auth failure
|
|
3630
|
+
* inside `runWatcherLoop`) does not count here — under a cap it would
|
|
3631
|
+
* permanently consume a slot, whereas cleanup/idle-exit should still treat it
|
|
3632
|
+
* as protected. One call per drain iteration serves both the cap check
|
|
3633
|
+
* (`.size`) and the already-active exemption (`.has`).
|
|
3634
|
+
*/
|
|
3635
|
+
activeSessionIdsForCap() {
|
|
3636
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3637
|
+
for (const [sessionId, watcher] of this.watchers) {
|
|
3638
|
+
if (watcher.inFlight.size > 0 && watcher.loop !== null) ids.add(sessionId);
|
|
3639
|
+
}
|
|
3640
|
+
return ids;
|
|
3641
|
+
}
|
|
3488
3642
|
/**
|
|
3489
3643
|
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
3490
3644
|
*
|
|
@@ -3603,7 +3757,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3603
3757
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
3604
3758
|
*/
|
|
3605
3759
|
async processConversation(conv) {
|
|
3606
|
-
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
3760
|
+
const { sessionId, refusedSessionId, created: sessionCreated } = await this.ensureSession(conv);
|
|
3607
3761
|
const messages = await this.getPendingMessages(conv.id);
|
|
3608
3762
|
let dispatched = 0;
|
|
3609
3763
|
let skippedAlreadyDispatched = 0;
|
|
@@ -3619,7 +3773,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3619
3773
|
continue;
|
|
3620
3774
|
}
|
|
3621
3775
|
if (message.opencode_message_id) {
|
|
3622
|
-
const outcome = await this.resolveRedrive(conv, sessionId, message,
|
|
3776
|
+
const outcome = await this.resolveRedrive(conv, sessionId, message, sessionCreated);
|
|
3777
|
+
if (outcome === "abandoned") {
|
|
3778
|
+
continue;
|
|
3779
|
+
}
|
|
3623
3780
|
if (outcome !== "dispatch") {
|
|
3624
3781
|
break;
|
|
3625
3782
|
}
|
|
@@ -3653,6 +3810,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3653
3810
|
conversation_id: conv.id,
|
|
3654
3811
|
message_id: message.id
|
|
3655
3812
|
});
|
|
3813
|
+
this.signalDispatchNotStarted(conv, message, "session_deleted_race");
|
|
3656
3814
|
break;
|
|
3657
3815
|
}
|
|
3658
3816
|
if (exists === null) {
|
|
@@ -3662,6 +3820,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3662
3820
|
conversation_id: conv.id,
|
|
3663
3821
|
message_id: message.id
|
|
3664
3822
|
});
|
|
3823
|
+
this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
|
|
3665
3824
|
break;
|
|
3666
3825
|
}
|
|
3667
3826
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
@@ -3680,6 +3839,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3680
3839
|
conversation_id: conv.id,
|
|
3681
3840
|
message_id: message.id
|
|
3682
3841
|
});
|
|
3842
|
+
this.signalDispatchNotStarted(conv, message, "failure_unreported");
|
|
3683
3843
|
});
|
|
3684
3844
|
this.log({
|
|
3685
3845
|
level: "error",
|
|
@@ -3690,14 +3850,40 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3690
3850
|
break;
|
|
3691
3851
|
}
|
|
3692
3852
|
if (opencodeMessageId === null) {
|
|
3853
|
+
const streak = this.recordUnconfirmedDispatch(message.id, sessionId);
|
|
3854
|
+
if (streak < MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
|
|
3855
|
+
this.log({
|
|
3856
|
+
level: "warn",
|
|
3857
|
+
message: `Message ${message.id.slice(0, 8)} dispatched but its opencode id could not be read back (${streak}/${MAX_IDENTICAL_REDRIVE_POLL_FAILURES}) \u2014 leaving un-tracked to retry next tick`,
|
|
3858
|
+
conversation_id: conv.id,
|
|
3859
|
+
message_id: message.id
|
|
3860
|
+
});
|
|
3861
|
+
this.signalDispatchNotStarted(conv, message, "readback_unconfirmed");
|
|
3862
|
+
continue;
|
|
3863
|
+
}
|
|
3864
|
+
this.unconfirmedDispatchFailures.delete(message.id);
|
|
3865
|
+
this.sessions.delete(conv.id);
|
|
3866
|
+
this.supersede(conv.id, sessionId);
|
|
3867
|
+
const errorMessage = `OpenCode accepted this message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
|
|
3693
3868
|
this.log({
|
|
3694
|
-
level: "
|
|
3695
|
-
message:
|
|
3869
|
+
level: "error",
|
|
3870
|
+
message: errorMessage,
|
|
3696
3871
|
conversation_id: conv.id,
|
|
3697
3872
|
message_id: message.id
|
|
3698
3873
|
});
|
|
3699
|
-
|
|
3874
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3875
|
+
this.log({
|
|
3876
|
+
level: "warn",
|
|
3877
|
+
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)}`,
|
|
3878
|
+
conversation_id: conv.id,
|
|
3879
|
+
message_id: message.id
|
|
3880
|
+
});
|
|
3881
|
+
this.signalDispatchNotStarted(conv, message, "abandon_unreported");
|
|
3882
|
+
});
|
|
3883
|
+
break;
|
|
3700
3884
|
}
|
|
3885
|
+
this.unconfirmedDispatchFailures.delete(message.id);
|
|
3886
|
+
this.dispatchNotStartedSignalled.delete(message.id);
|
|
3701
3887
|
this.dispatched.add(message.id);
|
|
3702
3888
|
this.registerInFlight(conv, sessionId, message, opencodeMessageId);
|
|
3703
3889
|
dispatched += 1;
|
|
@@ -3718,21 +3904,29 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3718
3904
|
* INJECTED `fetchImpl` — NOT the imported `getSessionMessages` helper, which
|
|
3719
3905
|
* hits the global `fetch` and would bypass the same override every other
|
|
3720
3906
|
* opencode poll in this file respects. Mirrors `readoptProcessing`'s own
|
|
3721
|
-
* snapshot fetch (`:3081-3111`).
|
|
3722
|
-
*
|
|
3723
|
-
*
|
|
3907
|
+
* snapshot fetch (`:3081-3111`).
|
|
3908
|
+
*
|
|
3909
|
+
* Returns `{ ok: true, messages }` on a readable snapshot, or
|
|
3910
|
+
* `{ ok: false, signature }` on failure — `signature` is a string that
|
|
3911
|
+
* repeats across attempts for the SAME underlying fault (used by the
|
|
3912
|
+
* consecutive-identical-failure bound, #1348), or `null` for a thrown
|
|
3913
|
+
* exception, which is NOT countable toward that bound (a network blip / an
|
|
3914
|
+
* opencode restart also throws identically every tick, and must keep
|
|
3915
|
+
* retrying unbounded rather than ever being treated as permanent).
|
|
3724
3916
|
*/
|
|
3725
3917
|
async pollSessionMessagesForRedrive(conv, message, sessionId) {
|
|
3726
3918
|
try {
|
|
3727
3919
|
const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
|
|
3728
3920
|
if (!res.ok) {
|
|
3921
|
+
const rawBody = await res.text();
|
|
3922
|
+
const normalized = normalizeRedrivePollFailureBody(rawBody);
|
|
3729
3923
|
this.log({
|
|
3730
3924
|
level: "warn",
|
|
3731
|
-
message: `Re-drive: polling session ${sessionId.slice(0, 8)} for message ${message.id.slice(0, 8)} returned HTTP ${res.status} \u2014 treating as unreadable this tick`,
|
|
3925
|
+
message: `Re-drive: polling session ${sessionId.slice(0, 8)} for message ${message.id.slice(0, 8)} returned HTTP ${res.status}${normalized ? `: ${normalized}` : ""} \u2014 treating as unreadable this tick`,
|
|
3732
3926
|
conversation_id: conv.id,
|
|
3733
3927
|
message_id: message.id
|
|
3734
3928
|
});
|
|
3735
|
-
return
|
|
3929
|
+
return { ok: false, signature: `HTTP ${res.status}${normalized ? `: ${normalized}` : ""}` };
|
|
3736
3930
|
}
|
|
3737
3931
|
const body = await res.json();
|
|
3738
3932
|
if (!Array.isArray(body)) {
|
|
@@ -3742,9 +3936,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3742
3936
|
conversation_id: conv.id,
|
|
3743
3937
|
message_id: message.id
|
|
3744
3938
|
});
|
|
3745
|
-
return
|
|
3939
|
+
return { ok: false, signature: "non-array message body" };
|
|
3746
3940
|
}
|
|
3747
|
-
return body;
|
|
3941
|
+
return { ok: true, messages: body };
|
|
3748
3942
|
} catch (err) {
|
|
3749
3943
|
this.log({
|
|
3750
3944
|
level: "warn",
|
|
@@ -3752,7 +3946,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3752
3946
|
conversation_id: conv.id,
|
|
3753
3947
|
message_id: message.id
|
|
3754
3948
|
});
|
|
3755
|
-
return null;
|
|
3949
|
+
return { ok: false, signature: null };
|
|
3756
3950
|
}
|
|
3757
3951
|
}
|
|
3758
3952
|
/**
|
|
@@ -3764,24 +3958,51 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3764
3958
|
* without this fence the drain loop would re-`prompt_async` the SAME turn a
|
|
3765
3959
|
* second time against live GitHub state. Mirrors `readoptOne`'s job for the
|
|
3766
3960
|
* `processing` re-adopt path, but simpler: no b1/b2 preamble cross-check is
|
|
3767
|
-
* needed here because `
|
|
3768
|
-
*
|
|
3961
|
+
* needed here because `sessionCreated` already handles the cases (a #553
|
|
3962
|
+
* abandoned session, a #190 vanished one) that path exists for.
|
|
3769
3963
|
*
|
|
3770
|
-
* Only `ChannelAuthError` propagates
|
|
3771
|
-
* `
|
|
3964
|
+
* Only `ChannelAuthError` propagates. A poll that fails identically
|
|
3965
|
+
* `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row reports the message
|
|
3966
|
+
* failed instead of retrying it (#1348) — SEPARATE from, not a replacement
|
|
3967
|
+
* for, `resolveRedriveUnresolved`'s own `pausedMaxWaitMs` bound below. Every
|
|
3968
|
+
* other failure resolves to `unresolved` and is retried whole on the next
|
|
3969
|
+
* ~2s drain tick.
|
|
3772
3970
|
*/
|
|
3773
|
-
async resolveRedrive(conv, sessionId, message,
|
|
3971
|
+
async resolveRedrive(conv, sessionId, message, sessionCreated) {
|
|
3774
3972
|
const ocId = message.opencode_message_id ?? null;
|
|
3775
|
-
if (
|
|
3973
|
+
if (sessionCreated) {
|
|
3776
3974
|
this.clearRedriveUnresolved(message.id);
|
|
3777
3975
|
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
3778
3976
|
return "dispatch";
|
|
3779
3977
|
}
|
|
3780
|
-
const
|
|
3781
|
-
if (
|
|
3978
|
+
const polled = await this.pollSessionMessagesForRedrive(conv, message, sessionId);
|
|
3979
|
+
if (!polled.ok) {
|
|
3980
|
+
const streak = this.recordRedrivePollFailure(message.id, sessionId, polled.signature);
|
|
3981
|
+
if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES && polled.signature !== null) {
|
|
3982
|
+
return this.failRedrivePollPermanent(conv, sessionId, message, polled.signature, streak);
|
|
3983
|
+
}
|
|
3984
|
+
return this.resolveRedriveUnresolved(conv, message);
|
|
3985
|
+
}
|
|
3986
|
+
this.redrivePollFailures.delete(message.id);
|
|
3987
|
+
const messages = polled.messages;
|
|
3988
|
+
if (messages.length === 0) {
|
|
3782
3989
|
return this.resolveRedriveUnresolved(conv, message);
|
|
3783
3990
|
}
|
|
3784
3991
|
const state = messageRunState(messages, ocId ?? "");
|
|
3992
|
+
if (state === "failed" && isAbortedTerminalReply(messages, ocId ?? "")) {
|
|
3993
|
+
const ongoing = await isSessionOngoing(this.port, sessionId);
|
|
3994
|
+
if (ongoing === false) {
|
|
3995
|
+
this.log({
|
|
3996
|
+
level: "info",
|
|
3997
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} carries an abort-shaped terminal error and session ${sessionId.slice(0, 8)} is not-ongoing per GET /session/status \u2014 restart orphan, re-dispatching instead of marking it permanently failed`,
|
|
3998
|
+
conversation_id: conv.id,
|
|
3999
|
+
message_id: message.id
|
|
4000
|
+
});
|
|
4001
|
+
this.clearRedriveUnresolved(message.id);
|
|
4002
|
+
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
4003
|
+
return "dispatch";
|
|
4004
|
+
}
|
|
4005
|
+
}
|
|
3785
4006
|
if (state === "done" || state === "failed") {
|
|
3786
4007
|
return this.settleRedrive(conv, sessionId, message, ocId, messages, state);
|
|
3787
4008
|
}
|
|
@@ -3825,13 +4046,23 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3825
4046
|
await this.markProcessing(conv.id, message.id, sessionId, ocId, title);
|
|
3826
4047
|
} catch (err) {
|
|
3827
4048
|
if (err instanceof ChannelAuthError) throw err;
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
|
|
3834
|
-
|
|
4049
|
+
if (err instanceof ChannelTerminalError) {
|
|
4050
|
+
this.log({
|
|
4051
|
+
level: "error",
|
|
4052
|
+
message: `Re-drive: the server definitively refused to restore message ${message.id.slice(0, 8)} to processing (terminal HTTP ${err.status} \u2014 the row is gone or the update was rejected); NOT reporting a re-attach`,
|
|
4053
|
+
conversation_id: conv.id,
|
|
4054
|
+
message_id: message.id
|
|
4055
|
+
});
|
|
4056
|
+
} else {
|
|
4057
|
+
this.log({
|
|
4058
|
+
level: "warn",
|
|
4059
|
+
message: `Re-drive: failed to restore message ${message.id.slice(0, 8)} to processing (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
4060
|
+
conversation_id: conv.id,
|
|
4061
|
+
message_id: message.id
|
|
4062
|
+
});
|
|
4063
|
+
}
|
|
4064
|
+
const bound = await this.boundRedriveOutcome(conv, message, "reattach");
|
|
4065
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
3835
4066
|
}
|
|
3836
4067
|
this.clearRedriveUnresolved(message.id);
|
|
3837
4068
|
this.registerReadopted(conv, sessionId, message, ocId ?? "", anchorMs);
|
|
@@ -3855,7 +4086,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3855
4086
|
* errored) while nobody was watching — deliver/report it instead of re-running.
|
|
3856
4087
|
* Mirrors `readoptOne`'s `done`/`failed` branches' error discipline, simplified
|
|
3857
4088
|
* (no `doneUndeliverable` park: a terminal PATCH failure here just retries next
|
|
3858
|
-
* drain, same as any other non-auth failure).
|
|
4089
|
+
* drain, same as any other non-auth failure). The restart-abort carve-out that
|
|
4090
|
+
* keeps the two in step for `failed` lives in the caller (`resolveRedrive`, #1310),
|
|
4091
|
+
* so a row reaching this `failed` branch is a GENUINE failure.
|
|
3859
4092
|
*/
|
|
3860
4093
|
async settleRedrive(conv, sessionId, message, ocId, messages, state) {
|
|
3861
4094
|
try {
|
|
@@ -3889,19 +4122,62 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3889
4122
|
conversation_id: conv.id,
|
|
3890
4123
|
message_id: message.id
|
|
3891
4124
|
});
|
|
3892
|
-
|
|
4125
|
+
const bound = await this.boundRedriveOutcome(conv, message, "settle");
|
|
4126
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
3893
4127
|
}
|
|
3894
4128
|
this.clearRedriveUnresolved(message.id);
|
|
3895
4129
|
void this.postSignal(conv.id, message.id, "redrive_settled");
|
|
3896
4130
|
return "settled";
|
|
3897
4131
|
}
|
|
4132
|
+
/**
|
|
4133
|
+
* The permanent-failure outcome (#1348): the fence's own poll of this session
|
|
4134
|
+
* failed with the SAME opencode-answered signature
|
|
4135
|
+
* `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row — a transient blip
|
|
4136
|
+
* would have varied or eventually cleared (see `pollSessionMessagesForRedrive`
|
|
4137
|
+
* and `recordRedrivePollFailure`), so this is a durable fault (e.g. #1345's
|
|
4138
|
+
* corrupted opencode session) rather than something worth retrying forever.
|
|
4139
|
+
* Mirrors `settleRedrive`'s error discipline: no `usage`/`failure` args to
|
|
4140
|
+
* `markFailed` (no opencode snapshot to extract them from — this poll never
|
|
4141
|
+
* got a readable one).
|
|
4142
|
+
*/
|
|
4143
|
+
async failRedrivePollPermanent(conv, sessionId, message, signature, streak) {
|
|
4144
|
+
this.log({
|
|
4145
|
+
level: "error",
|
|
4146
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} (session ${sessionId.slice(0, 8)}) failed to poll with the identical signature "${signature}" ${streak} times in a row \u2014 reporting the message failed instead of retrying forever`,
|
|
4147
|
+
conversation_id: conv.id,
|
|
4148
|
+
message_id: message.id
|
|
4149
|
+
});
|
|
4150
|
+
try {
|
|
4151
|
+
await this.markFailed(
|
|
4152
|
+
conv.id,
|
|
4153
|
+
message.id,
|
|
4154
|
+
sessionId,
|
|
4155
|
+
`The runner could not read this conversation's state from OpenCode (${signature}). The same failure repeated ${streak} times in a row, so the message was not retried further.`
|
|
4156
|
+
);
|
|
4157
|
+
} catch (err) {
|
|
4158
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4159
|
+
this.log({
|
|
4160
|
+
level: "warn",
|
|
4161
|
+
message: `Re-drive: failed to report message ${message.id.slice(0, 8)} permanently failed (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
4162
|
+
conversation_id: conv.id,
|
|
4163
|
+
message_id: message.id
|
|
4164
|
+
});
|
|
4165
|
+
const bound = await this.boundRedriveOutcome(conv, message, "fail_permanent");
|
|
4166
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
4167
|
+
}
|
|
4168
|
+
this.clearRedriveUnresolved(message.id);
|
|
4169
|
+
void this.postSignal(conv.id, message.id, "redrive_poll_failed");
|
|
4170
|
+
return "settled";
|
|
4171
|
+
}
|
|
3898
4172
|
/**
|
|
3899
4173
|
* The bounded `unresolved` outcome (Task 3.4): opencode's state could not be
|
|
3900
4174
|
* observed (snapshot unreadable/empty, or `isSessionOngoing` returned `null`).
|
|
3901
|
-
* A `pending` row is
|
|
3902
|
-
*
|
|
3903
|
-
*
|
|
3904
|
-
*
|
|
4175
|
+
* A `pending` row is swept by the server's own `PENDING_MAX_AGE_MS` (24h,
|
|
4176
|
+
* #1368) cron arm, but that is a day-scale backstop — this local bound acts
|
|
4177
|
+
* in minutes so the row (and the conversation it starves, per the ordering
|
|
4178
|
+
* invariant below) isn't left stranded for that long. Bound to the existing
|
|
4179
|
+
* `pausedMaxWaitMs` window (reusing the knob, not a new constant); takes
|
|
4180
|
+
* `dispatch` once elapsed.
|
|
3905
4181
|
*/
|
|
3906
4182
|
resolveRedriveUnresolved(conv, message) {
|
|
3907
4183
|
const now = this.now();
|
|
@@ -3920,10 +4196,153 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3920
4196
|
}
|
|
3921
4197
|
return "unresolved";
|
|
3922
4198
|
}
|
|
3923
|
-
/** Clear
|
|
4199
|
+
/** Clear all `unresolved`/failure-streak trackers for a row (any non-`unresolved` outcome). */
|
|
3924
4200
|
clearRedriveUnresolved(messageId) {
|
|
3925
4201
|
this.redriveUnresolvedSince.delete(messageId);
|
|
3926
4202
|
this.redriveUnresolvedSignalled.delete(messageId);
|
|
4203
|
+
this.redrivePollFailures.delete(messageId);
|
|
4204
|
+
this.redriveOutcomeUnreportedSignalled.delete(messageId);
|
|
4205
|
+
this.redriveOutcomeFailingSince.delete(messageId);
|
|
4206
|
+
this.redriveOutcomeAbandonedSignalled.delete(messageId);
|
|
4207
|
+
}
|
|
4208
|
+
/**
|
|
4209
|
+
* #1340: the dispatch loop reached a message and did NOT start a turn. Fires at
|
|
4210
|
+
* most once per (message, branch) streak — a wedged row is re-tried every tick,
|
|
4211
|
+
* and the per-tick count is already carried by the co-occurring
|
|
4212
|
+
* `redrive_unresolved`/`redrive_redispatched` signals.
|
|
4213
|
+
*/
|
|
4214
|
+
signalDispatchNotStarted(conv, message, branch) {
|
|
4215
|
+
if (this.dispatchNotStartedSignalled.get(message.id) === branch) return;
|
|
4216
|
+
this.dispatchNotStartedSignalled.set(message.id, branch);
|
|
4217
|
+
void this.postSignal(conv.id, message.id, "dispatch_not_started", { branch });
|
|
4218
|
+
}
|
|
4219
|
+
/**
|
|
4220
|
+
* Class B (#1340): the runner DECIDED an outcome (reattach/settle/fail_permanent)
|
|
4221
|
+
* but its own PATCH to record it failed. Fires at most once per (message,
|
|
4222
|
+
* outcome) streak, and only while `boundRedriveOutcome` has not yet tripped —
|
|
4223
|
+
* once it trips, `redrive_outcome_abandoned` takes over reporting for the row
|
|
4224
|
+
* (#1366).
|
|
4225
|
+
*/
|
|
4226
|
+
signalRedriveOutcomeUnreported(conv, message, outcome) {
|
|
4227
|
+
if (this.redriveOutcomeUnreportedSignalled.get(message.id) === outcome) return;
|
|
4228
|
+
this.redriveOutcomeUnreportedSignalled.set(message.id, outcome);
|
|
4229
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_unreported", {
|
|
4230
|
+
attempted_outcome: outcome
|
|
4231
|
+
});
|
|
4232
|
+
}
|
|
4233
|
+
/**
|
|
4234
|
+
* The runner-authored, honest error text for the terminal fallback a tripped
|
|
4235
|
+
* `boundRedriveOutcome` sends. Distinguishable per outcome and truthful about
|
|
4236
|
+
* what actually happened — the `settle`/done case must say the turn finished
|
|
4237
|
+
* but its result could not be recorded, never that the runner stopped
|
|
4238
|
+
* responding (that would be a lie for this shape, see #1366's "why this ships").
|
|
4239
|
+
*/
|
|
4240
|
+
static REDRIVE_ABANDON_ERROR = {
|
|
4241
|
+
reattach: "your runner could not record that this message had started, so it was given up on",
|
|
4242
|
+
settle: "your runner finished this message but could not record the result, so the reply could not be delivered",
|
|
4243
|
+
fail_permanent: "the runner could not read this conversation's state from OpenCode, and could not record that failure either, so the message was given up on"
|
|
4244
|
+
};
|
|
4245
|
+
/**
|
|
4246
|
+
* Bound for Class B (#1340, #1366): the runner DECIDED an outcome but its own
|
|
4247
|
+
* PATCH to record it failed. Two independent trip arms (either sufficient):
|
|
4248
|
+
* (1) this failure streak has lasted `pausedMaxWaitMs` — DURATION, not a tick
|
|
4249
|
+
* count, reusing the knob `resolveRedriveUnresolved` already established; (2)
|
|
4250
|
+
* the turn's `processing_started_at` age has crossed
|
|
4251
|
+
* `ABSOLUTE_MAX_PROCESSING_MS` — durable and restart-surviving, since arm (1)'s
|
|
4252
|
+
* in-memory streak resets on a scale-to-zero restart.
|
|
4253
|
+
*
|
|
4254
|
+
* INVARIANT — a tripped bound never suppresses the original outcome attempt;
|
|
4255
|
+
* it only adds a fallback after that attempt has failed again. This is only
|
|
4256
|
+
* ever reached from inside the catch of the ORIGINAL outcome PATCH, which is
|
|
4257
|
+
* attempted first on every tick whether or not this bound tripped before —
|
|
4258
|
+
* there is no give-up latch that would short-circuit it. That is what lets a
|
|
4259
|
+
* route-level fault that heals later still deliver the turn's real
|
|
4260
|
+
* `done`/`failed` payload: once the original PATCH succeeds again, this
|
|
4261
|
+
* helper is never entered and the row settles with its real result.
|
|
4262
|
+
*/
|
|
4263
|
+
async boundRedriveOutcome(conv, message, outcome) {
|
|
4264
|
+
const now = this.now();
|
|
4265
|
+
const since = this.redriveOutcomeFailingSince.get(message.id);
|
|
4266
|
+
if (since === void 0) this.redriveOutcomeFailingSince.set(message.id, now);
|
|
4267
|
+
const durationTripped = now - (since ?? now) >= this.pausedMaxWaitMs;
|
|
4268
|
+
const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
|
|
4269
|
+
const absoluteAgeTripped = !Number.isNaN(parsed) && now - parsed >= ABSOLUTE_MAX_PROCESSING_MS;
|
|
4270
|
+
if (!durationTripped && !absoluteAgeTripped) {
|
|
4271
|
+
this.signalRedriveOutcomeUnreported(conv, message, outcome);
|
|
4272
|
+
return "retry";
|
|
4273
|
+
}
|
|
4274
|
+
const arm = durationTripped ? "failure_window" : "absolute_age";
|
|
4275
|
+
try {
|
|
4276
|
+
await this.markFailed(
|
|
4277
|
+
conv.id,
|
|
4278
|
+
message.id,
|
|
4279
|
+
void 0,
|
|
4280
|
+
_ChannelDriver.REDRIVE_ABANDON_ERROR[outcome]
|
|
4281
|
+
);
|
|
4282
|
+
} catch (err) {
|
|
4283
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4284
|
+
this.log({
|
|
4285
|
+
level: "warn",
|
|
4286
|
+
message: `Re-drive bound: fallback markFailed for message ${message.id.slice(0, 8)} also failed (arm ${arm}, will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
4287
|
+
conversation_id: conv.id,
|
|
4288
|
+
message_id: message.id
|
|
4289
|
+
});
|
|
4290
|
+
if (!this.redriveOutcomeAbandonedSignalled.has(message.id)) {
|
|
4291
|
+
this.redriveOutcomeAbandonedSignalled.add(message.id);
|
|
4292
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
|
|
4293
|
+
attempted_outcome: outcome,
|
|
4294
|
+
reported: false,
|
|
4295
|
+
arm
|
|
4296
|
+
});
|
|
4297
|
+
}
|
|
4298
|
+
return "retry";
|
|
4299
|
+
}
|
|
4300
|
+
this.clearRedriveUnresolved(message.id);
|
|
4301
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
|
|
4302
|
+
attempted_outcome: outcome,
|
|
4303
|
+
reported: true,
|
|
4304
|
+
arm
|
|
4305
|
+
});
|
|
4306
|
+
return "abandoned";
|
|
4307
|
+
}
|
|
4308
|
+
/**
|
|
4309
|
+
* Record one poll outcome toward the re-drive fence's consecutive-identical-
|
|
4310
|
+
* failure streak (#1348) and return the resulting count. `signature === null`
|
|
4311
|
+
* (a thrown exception, H1) always clears the streak and returns `0` — it is
|
|
4312
|
+
* never countable. Otherwise the streak continues only when BOTH the session
|
|
4313
|
+
* and the signature match the previous failure; anything else (a different
|
|
4314
|
+
* session, or the same session failing a DIFFERENT way) starts a fresh streak
|
|
4315
|
+
* at `1`.
|
|
4316
|
+
*/
|
|
4317
|
+
recordRedrivePollFailure(messageId, sessionId, signature) {
|
|
4318
|
+
if (signature === null) {
|
|
4319
|
+
this.redrivePollFailures.delete(messageId);
|
|
4320
|
+
return 0;
|
|
4321
|
+
}
|
|
4322
|
+
const existing = this.redrivePollFailures.get(messageId);
|
|
4323
|
+
if (existing && existing.sessionId === sessionId && existing.signature === signature) {
|
|
4324
|
+
existing.count += 1;
|
|
4325
|
+
return existing.count;
|
|
4326
|
+
}
|
|
4327
|
+
this.redrivePollFailures.set(messageId, { sessionId, signature, count: 1 });
|
|
4328
|
+
return 1;
|
|
4329
|
+
}
|
|
4330
|
+
/**
|
|
4331
|
+
* Record one UNCONFIRMED-dispatch outcome (a `pending` row with no stored
|
|
4332
|
+
* `opencode_message_id` whose `sendPromptAsync` returned `null`) toward the
|
|
4333
|
+
* bound in `processConversation`'s dispatch loop, and return the resulting
|
|
4334
|
+
* count. Mirrors `recordRedrivePollFailure`'s session-scoping: a session
|
|
4335
|
+
* change starts a fresh streak at `1` rather than inheriting the old one's
|
|
4336
|
+
* count, since a new session is a genuinely different attempt.
|
|
4337
|
+
*/
|
|
4338
|
+
recordUnconfirmedDispatch(messageId, sessionId) {
|
|
4339
|
+
const existing = this.unconfirmedDispatchFailures.get(messageId);
|
|
4340
|
+
if (existing && existing.sessionId === sessionId) {
|
|
4341
|
+
existing.count += 1;
|
|
4342
|
+
return existing.count;
|
|
4343
|
+
}
|
|
4344
|
+
this.unconfirmedDispatchFailures.set(messageId, { sessionId, count: 1 });
|
|
4345
|
+
return 1;
|
|
3927
4346
|
}
|
|
3928
4347
|
/**
|
|
3929
4348
|
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
@@ -3949,6 +4368,13 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3949
4368
|
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3950
4369
|
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3951
4370
|
* happened and a fresh session was bound instead. The caller reports it.
|
|
4371
|
+
*
|
|
4372
|
+
* `created` says the returned session was made JUST NOW, so it provably holds
|
|
4373
|
+
* no prior turn. The re-drive fence needs that as CONTRARY evidence ("nothing
|
|
4374
|
+
* to reconcile against") — distinct from the ambiguous "I polled and saw an
|
|
4375
|
+
* empty transcript", which stays a deferral. Keep it separate from
|
|
4376
|
+
* `refusedSessionId`: only the latter means a #553 resurrection happened, and
|
|
4377
|
+
* only it may drive the `session_superseded` signal.
|
|
3952
4378
|
*/
|
|
3953
4379
|
async ensureSession(conv) {
|
|
3954
4380
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
@@ -3959,7 +4385,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3959
4385
|
conversation_id: conv.id
|
|
3960
4386
|
});
|
|
3961
4387
|
this.sessions.delete(conv.id);
|
|
3962
|
-
return {
|
|
4388
|
+
return {
|
|
4389
|
+
sessionId: await this.createAndBindSession(conv.id),
|
|
4390
|
+
refusedSessionId: bound,
|
|
4391
|
+
created: true
|
|
4392
|
+
};
|
|
3963
4393
|
}
|
|
3964
4394
|
if (bound) {
|
|
3965
4395
|
const exists = await sessionExists(this.port, bound);
|
|
@@ -3970,12 +4400,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3970
4400
|
conversation_id: conv.id
|
|
3971
4401
|
});
|
|
3972
4402
|
this.sessions.delete(conv.id);
|
|
3973
|
-
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
4403
|
+
return { sessionId: await this.createAndBindSession(conv.id), created: true };
|
|
3974
4404
|
}
|
|
3975
4405
|
this.sessions.set(conv.id, bound);
|
|
3976
|
-
return { sessionId: bound };
|
|
4406
|
+
return { sessionId: bound, created: false };
|
|
3977
4407
|
}
|
|
3978
|
-
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
4408
|
+
return { sessionId: await this.createAndBindSession(conv.id), created: true };
|
|
3979
4409
|
}
|
|
3980
4410
|
/**
|
|
3981
4411
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -4404,9 +4834,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4404
4834
|
const awaitingHuman = observedOpen || latchedPaused;
|
|
4405
4835
|
if ((state === "running" || state === "done" || state === "failed") && !inFlight.started) {
|
|
4406
4836
|
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
4407
|
-
let claimed;
|
|
4408
4837
|
try {
|
|
4409
|
-
|
|
4838
|
+
await this.markProcessing(
|
|
4410
4839
|
conv.id,
|
|
4411
4840
|
inFlight.evidentMessageId,
|
|
4412
4841
|
sessionId,
|
|
@@ -4415,23 +4844,24 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4415
4844
|
);
|
|
4416
4845
|
} catch (err) {
|
|
4417
4846
|
if (err instanceof ChannelAuthError) throw err;
|
|
4418
|
-
|
|
4419
|
-
|
|
4420
|
-
|
|
4421
|
-
|
|
4422
|
-
|
|
4423
|
-
|
|
4424
|
-
|
|
4847
|
+
if (err instanceof ChannelTerminalError) {
|
|
4848
|
+
this.log({
|
|
4849
|
+
level: "error",
|
|
4850
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (terminal HTTP ${err.status}) \u2014 the server definitively refused the swap`,
|
|
4851
|
+
conversation_id: conv.id,
|
|
4852
|
+
message_id: inFlight.evidentMessageId
|
|
4853
|
+
});
|
|
4854
|
+
} else {
|
|
4855
|
+
this.log({
|
|
4856
|
+
level: "warn",
|
|
4857
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
4858
|
+
conversation_id: conv.id,
|
|
4859
|
+
message_id: inFlight.evidentMessageId
|
|
4860
|
+
});
|
|
4861
|
+
return;
|
|
4862
|
+
}
|
|
4425
4863
|
}
|
|
4426
4864
|
inFlight.started = true;
|
|
4427
|
-
if (!claimed) {
|
|
4428
|
-
this.log({
|
|
4429
|
-
level: "debug",
|
|
4430
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
|
|
4431
|
-
conversation_id: conv.id,
|
|
4432
|
-
message_id: inFlight.evidentMessageId
|
|
4433
|
-
});
|
|
4434
|
-
}
|
|
4435
4865
|
}
|
|
4436
4866
|
if (state === "done") {
|
|
4437
4867
|
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
@@ -4771,7 +5201,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4771
5201
|
* re-dispatched (at most once, see `forceReadoptRun`):
|
|
4772
5202
|
* - `done` → `markDone` now (guarded like the watcher's done branch);
|
|
4773
5203
|
* - `failed` → `markFailed` with the surfaced error (issue #182), so an
|
|
4774
|
-
* errored turn is reported failed on restart, NOT re-dispatched
|
|
5204
|
+
* errored turn is reported failed on restart, NOT re-dispatched —
|
|
5205
|
+
* EXCEPT a restart-ABORTED turn under a not-ongoing session,
|
|
5206
|
+
* which is a restart orphan wearing a terminal error and is
|
|
5207
|
+
* re-dispatched instead (issue #1310, see the branch below);
|
|
4775
5208
|
* - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
|
|
4776
5209
|
* tracking the stored id so the reply correlates by it;
|
|
4777
5210
|
* - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
|
|
@@ -4835,7 +5268,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4835
5268
|
void this.postSignal(row.conversation_id, row.id, "readopt_done");
|
|
4836
5269
|
return;
|
|
4837
5270
|
}
|
|
4838
|
-
|
|
5271
|
+
const restartAborted = state === "failed" && sessionOngoing === false && isAbortedTerminalReply(messages, ocId ?? "");
|
|
5272
|
+
if (restartAborted) {
|
|
5273
|
+
this.log({
|
|
5274
|
+
level: "info",
|
|
5275
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} carries an abort-shaped terminal error and session ${sessionId.slice(0, 8)} is not-ongoing per GET /session/status \u2014 restart orphan, re-dispatching instead of marking it permanently failed`,
|
|
5276
|
+
conversation_id: row.conversation_id,
|
|
5277
|
+
message_id: row.id
|
|
5278
|
+
});
|
|
5279
|
+
}
|
|
5280
|
+
if (state === "failed" && !restartAborted) {
|
|
4839
5281
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
4840
5282
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4841
5283
|
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
@@ -5049,15 +5491,39 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5049
5491
|
}
|
|
5050
5492
|
if (ocId === null) {
|
|
5051
5493
|
this.awaitingReadopt.delete(row.id);
|
|
5494
|
+
const streak = this.recordUnconfirmedDispatch(row.id, sessionId);
|
|
5495
|
+
if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
|
|
5496
|
+
this.unconfirmedDispatchFailures.delete(row.id);
|
|
5497
|
+
this.sessions.delete(readoptConv.id);
|
|
5498
|
+
this.supersede(readoptConv.id, sessionId);
|
|
5499
|
+
const errorMessage = `OpenCode accepted this re-dispatched message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
|
|
5500
|
+
this.log({
|
|
5501
|
+
level: "error",
|
|
5502
|
+
message: errorMessage,
|
|
5503
|
+
conversation_id: row.conversation_id,
|
|
5504
|
+
message_id: row.id
|
|
5505
|
+
});
|
|
5506
|
+
await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
|
|
5507
|
+
this.log({
|
|
5508
|
+
level: "warn",
|
|
5509
|
+
message: `markFailed PATCH for message ${row.id.slice(0, 8)} (conversation ${row.conversation_id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
5510
|
+
conversation_id: row.conversation_id,
|
|
5511
|
+
message_id: row.id
|
|
5512
|
+
});
|
|
5513
|
+
});
|
|
5514
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
5515
|
+
return;
|
|
5516
|
+
}
|
|
5052
5517
|
this.log({
|
|
5053
5518
|
level: "warn",
|
|
5054
|
-
message: `Re-adopt: message ${row.id.slice(0, 8)} re-dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next drain`,
|
|
5519
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} re-dispatched but its opencode id could not be read back (${streak}/${MAX_IDENTICAL_REDRIVE_POLL_FAILURES}) \u2014 leaving un-tracked to retry next drain`,
|
|
5055
5520
|
conversation_id: row.conversation_id,
|
|
5056
5521
|
message_id: row.id
|
|
5057
5522
|
});
|
|
5058
5523
|
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
5059
5524
|
return;
|
|
5060
5525
|
}
|
|
5526
|
+
this.unconfirmedDispatchFailures.delete(row.id);
|
|
5061
5527
|
this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
|
|
5062
5528
|
this.dispatched.add(row.id);
|
|
5063
5529
|
this.readopted.add(row.id);
|
|
@@ -5722,18 +6188,22 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5722
6188
|
* opencode_session_id}` → `notifyMessageStarted` (hourglass→runner swap +
|
|
5723
6189
|
* deep-linked "View in Evident" notice).
|
|
5724
6190
|
*
|
|
5725
|
-
*
|
|
5726
|
-
* -
|
|
5727
|
-
*
|
|
5728
|
-
*
|
|
5729
|
-
*
|
|
5730
|
-
*
|
|
5731
|
-
*
|
|
5732
|
-
*
|
|
5733
|
-
*
|
|
5734
|
-
*
|
|
5735
|
-
*
|
|
5736
|
-
*
|
|
6191
|
+
* Outcome contract (consumed by the watcher's swap-to-running guard):
|
|
6192
|
+
* - resolves (`void`) → the server transitioned the row to
|
|
6193
|
+
* processing (or idempotently confirmed
|
|
6194
|
+
* already-processing — that answer is
|
|
6195
|
+
* still a 200, never a refusal);
|
|
6196
|
+
* - throws `ChannelAuthError` → 401/403 (terminal auth failure);
|
|
6197
|
+
* - throws `ChannelTerminalError` → a definitive non-retryable, non-auth 4xx
|
|
6198
|
+
* (404 the row or its conversation is
|
|
6199
|
+
* gone, 400 the update was rejected).
|
|
6200
|
+
* Retrying cannot help;
|
|
6201
|
+
* - throws a plain `Error` → a TRANSIENT failure (retryable 5xx/429
|
|
6202
|
+
* status, or a network-level error from
|
|
6203
|
+
* `fetch`) — i.e. NO definitive server
|
|
6204
|
+
* response — so the caller leaves the
|
|
6205
|
+
* message un-started and retries the swap
|
|
6206
|
+
* on the next tick.
|
|
5737
6207
|
* A single attempt (no internal retry): the watcher's per-tick loop is the
|
|
5738
6208
|
* retry vehicle for the swap-to-running.
|
|
5739
6209
|
*/
|
|
@@ -5752,11 +6222,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5752
6222
|
}
|
|
5753
6223
|
);
|
|
5754
6224
|
this.assertAuth(res, "marking message as processing");
|
|
5755
|
-
if (res.ok) return
|
|
6225
|
+
if (res.ok) return;
|
|
5756
6226
|
if (isRetryableStatus(res.status)) {
|
|
5757
6227
|
throw new Error(`marking message as processing: HTTP ${res.status}`);
|
|
5758
6228
|
}
|
|
5759
|
-
|
|
6229
|
+
throw new ChannelTerminalError(`marking message as processing: HTTP ${res.status}`, res.status);
|
|
5760
6230
|
}
|
|
5761
6231
|
/**
|
|
5762
6232
|
* EXISTING combinedAuth completion route — idempotent (WI-CHAN-2). `PATCH
|
|
@@ -6242,6 +6712,32 @@ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
|
6242
6712
|
}
|
|
6243
6713
|
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
6244
6714
|
}
|
|
6715
|
+
var MAX_ACTIVE_SESSIONS_ENV = "EVIDENT_MAX_ACTIVE_SESSIONS";
|
|
6716
|
+
function resolveMaxActiveSessions(options, env = process.env) {
|
|
6717
|
+
let raw;
|
|
6718
|
+
let source;
|
|
6719
|
+
if (options.maxActiveSessions !== void 0) {
|
|
6720
|
+
raw = options.maxActiveSessions;
|
|
6721
|
+
source = "--max-active-sessions";
|
|
6722
|
+
} else if (env[MAX_ACTIVE_SESSIONS_ENV] !== void 0 && env[MAX_ACTIVE_SESSIONS_ENV] !== "") {
|
|
6723
|
+
raw = env[MAX_ACTIVE_SESSIONS_ENV];
|
|
6724
|
+
source = MAX_ACTIVE_SESSIONS_ENV;
|
|
6725
|
+
} else {
|
|
6726
|
+
return { value: void 0, warnings: [] };
|
|
6727
|
+
}
|
|
6728
|
+
const trimmed = raw.trim();
|
|
6729
|
+
const count = Number(trimmed);
|
|
6730
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(count) && count > 0;
|
|
6731
|
+
if (!isPositiveInteger) {
|
|
6732
|
+
return {
|
|
6733
|
+
value: void 0,
|
|
6734
|
+
warnings: [
|
|
6735
|
+
`Ignoring invalid ${source} "${raw}": expected a positive integer; using unlimited`
|
|
6736
|
+
]
|
|
6737
|
+
};
|
|
6738
|
+
}
|
|
6739
|
+
return { value: count, warnings: [] };
|
|
6740
|
+
}
|
|
6245
6741
|
function meetsThreshold(state, level) {
|
|
6246
6742
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
6247
6743
|
}
|
|
@@ -6360,7 +6856,9 @@ async function handleAuthError(state, error2) {
|
|
|
6360
6856
|
);
|
|
6361
6857
|
const newAuthHeader = getAuthHeader(credentials2);
|
|
6362
6858
|
return { success: true, newAuthHeader };
|
|
6363
|
-
} catch {
|
|
6859
|
+
} catch (error3) {
|
|
6860
|
+
const message = error3 instanceof Error ? error3.message : String(error3);
|
|
6861
|
+
logActivity(state, { type: "error", error: `Re-authentication failed: ${message}` });
|
|
6364
6862
|
return { success: false };
|
|
6365
6863
|
}
|
|
6366
6864
|
}
|
|
@@ -6967,6 +7465,10 @@ async function run(options) {
|
|
|
6967
7465
|
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6968
7466
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6969
7467
|
}
|
|
7468
|
+
const { value: maxActiveSessions, warnings: maxActiveSessionsWarnings } = resolveMaxActiveSessions(options, process.env);
|
|
7469
|
+
for (const warning2 of maxActiveSessionsWarnings) {
|
|
7470
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
7471
|
+
}
|
|
6970
7472
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
6971
7473
|
try {
|
|
6972
7474
|
const oc = await ensureOpenCodeRunning({
|
|
@@ -7027,6 +7529,7 @@ async function run(options) {
|
|
|
7027
7529
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
7028
7530
|
fileSyncDirectories,
|
|
7029
7531
|
homeDir: homedir3(),
|
|
7532
|
+
maxActiveSessions,
|
|
7030
7533
|
log: (entry) => (
|
|
7031
7534
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
7032
7535
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -7227,6 +7730,9 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
7227
7730
|
).option(
|
|
7228
7731
|
"--session-cleanup-max-count <n>",
|
|
7229
7732
|
"Keep only the newest N OpenCode sessions. Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_COUNT"
|
|
7733
|
+
).option(
|
|
7734
|
+
"--max-active-sessions <n>",
|
|
7735
|
+
"Cap how many sessions this runner works on at once (default: unlimited). Env: EVIDENT_MAX_ACTIVE_SESSIONS"
|
|
7230
7736
|
).option(
|
|
7231
7737
|
"--session-cleanup-interval <duration>",
|
|
7232
7738
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
@@ -7260,6 +7766,7 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
7260
7766
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
7261
7767
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
7262
7768
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
7769
|
+
maxActiveSessions: options.maxActiveSessions,
|
|
7263
7770
|
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
7264
7771
|
// Raw string — the resolver in run.ts single-sources parsing
|
|
7265
7772
|
// (resolveClaudeUsageReportingMode).
|