@evident-ai/cli 3.1.1-dev.fe0815c → 3.2.0
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 +548 -73
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -797,6 +797,16 @@ async function checkStatus(jsonMode) {
|
|
|
797
797
|
exitCode: 1
|
|
798
798
|
};
|
|
799
799
|
}
|
|
800
|
+
if (response.status === 404) {
|
|
801
|
+
return {
|
|
802
|
+
ok: false,
|
|
803
|
+
endpoint: apiUrl,
|
|
804
|
+
authLabel: authLabelFor(credentials2),
|
|
805
|
+
reason: "endpoint_not_found",
|
|
806
|
+
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.`,
|
|
807
|
+
exitCode: 75
|
|
808
|
+
};
|
|
809
|
+
}
|
|
800
810
|
if (response.status >= 500) {
|
|
801
811
|
const serverMessage = await readErrorMessage(response);
|
|
802
812
|
return {
|
|
@@ -2089,6 +2099,21 @@ function messageError(messages, userMessageId) {
|
|
|
2089
2099
|
}
|
|
2090
2100
|
return "The agent run failed.";
|
|
2091
2101
|
}
|
|
2102
|
+
function isAbortedTerminalReply(messages, userMessageId) {
|
|
2103
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
2104
|
+
const error2 = errorOf(reply);
|
|
2105
|
+
if (error2 == null) return false;
|
|
2106
|
+
if (typeof error2 === "string") return error2.trim() === "Aborted";
|
|
2107
|
+
if (typeof error2 === "object") {
|
|
2108
|
+
const e = error2;
|
|
2109
|
+
if (e.name === "MessageAbortedError") return true;
|
|
2110
|
+
if (e.name === "AbortError") return true;
|
|
2111
|
+
const dataMessage = e.data?.message;
|
|
2112
|
+
const rendered = typeof dataMessage === "string" ? dataMessage : typeof e.message === "string" ? e.message : null;
|
|
2113
|
+
return rendered != null && rendered.trim() === "Aborted";
|
|
2114
|
+
}
|
|
2115
|
+
return false;
|
|
2116
|
+
}
|
|
2092
2117
|
function messageFailure(messages, userMessageId) {
|
|
2093
2118
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
2094
2119
|
const error2 = errorOf(reply);
|
|
@@ -3126,6 +3151,7 @@ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
|
3126
3151
|
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
3127
3152
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
3128
3153
|
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
3154
|
+
var MAX_IDENTICAL_REDRIVE_POLL_FAILURES = 5;
|
|
3129
3155
|
var ChannelAuthError = class extends Error {
|
|
3130
3156
|
constructor(message) {
|
|
3131
3157
|
super(message);
|
|
@@ -3148,6 +3174,10 @@ function backoffDelay(attempt, policy) {
|
|
|
3148
3174
|
function isRetryableStatus(status2) {
|
|
3149
3175
|
return status2 === 429 || status2 >= 500 && status2 <= 599;
|
|
3150
3176
|
}
|
|
3177
|
+
var VOLATILE_BODY_FIELD_PATTERN = /("(?:ref|requestId|request_id|traceId|trace_id)"\s*:\s*)"[^"]*"/gi;
|
|
3178
|
+
function normalizeRedrivePollFailureBody(body) {
|
|
3179
|
+
return body.replace(VOLATILE_BODY_FIELD_PATTERN, '$1"<redacted>"').replace(/\s+/g, " ").trim().slice(0, 200);
|
|
3180
|
+
}
|
|
3151
3181
|
var ChannelDriver = class _ChannelDriver {
|
|
3152
3182
|
agentId;
|
|
3153
3183
|
port;
|
|
@@ -3164,6 +3194,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3164
3194
|
now;
|
|
3165
3195
|
fileSyncDirectories;
|
|
3166
3196
|
homeDir;
|
|
3197
|
+
maxActiveSessions;
|
|
3167
3198
|
/** Cache of conversationId → opencode sessionId. */
|
|
3168
3199
|
sessions = /* @__PURE__ */ new Map();
|
|
3169
3200
|
/**
|
|
@@ -3279,6 +3310,66 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3279
3310
|
* ADR-0047's own "unreachable ⇒ bounded" rule). Cleared on any other outcome.
|
|
3280
3311
|
*/
|
|
3281
3312
|
redriveUnresolvedSince = /* @__PURE__ */ new Map();
|
|
3313
|
+
/**
|
|
3314
|
+
* Consecutive-identical-poll-failure streak for the re-drive fence (#1348),
|
|
3315
|
+
* keyed by Evident **message id** (not session) so `clearRedriveUnresolved`
|
|
3316
|
+
* can drop it with the other two trackers and it cannot leak. `sessionId` is
|
|
3317
|
+
* carried inside the entry, not the key: a session change is a different
|
|
3318
|
+
* situation and resets the streak, which gives the `(sessionId, message.id)`
|
|
3319
|
+
* pairing #1348 asks for without a composite map key.
|
|
3320
|
+
*/
|
|
3321
|
+
redrivePollFailures = /* @__PURE__ */ new Map();
|
|
3322
|
+
/**
|
|
3323
|
+
* "Already emitted `redrive_outcome_unreported` for THIS (message, outcome)
|
|
3324
|
+
* streak" (Class B, #1340: the runner DECIDED reattach/settle/fail_permanent
|
|
3325
|
+
* but its own PATCH to record it failed — distinct from Class A's
|
|
3326
|
+
* `redrive_poll_failed`, where opencode itself can't be observed). Keyed by
|
|
3327
|
+
* message id, valued by the outcome currently failing to report, so a
|
|
3328
|
+
* change of outcome starts a fresh signal. Cleared by
|
|
3329
|
+
* `clearRedriveUnresolved` the instant either PATCH succeeds.
|
|
3330
|
+
*/
|
|
3331
|
+
redriveOutcomeUnreportedSignalled = /* @__PURE__ */ new Map();
|
|
3332
|
+
/**
|
|
3333
|
+
* First `now()` a Class B outcome PATCH (reattach/settle/fail_permanent) was
|
|
3334
|
+
* observed to fail for this message (#1366's failure-window trip arm,
|
|
3335
|
+
* `boundRedriveOutcome`). Duration, not a tick count — bounded by the
|
|
3336
|
+
* existing `pausedMaxWaitMs` window (reusing the knob, not a new constant).
|
|
3337
|
+
* Cleared by `clearRedriveUnresolved` the instant the original PATCH
|
|
3338
|
+
* succeeds.
|
|
3339
|
+
*/
|
|
3340
|
+
redriveOutcomeFailingSince = /* @__PURE__ */ new Map();
|
|
3341
|
+
/**
|
|
3342
|
+
* "Already posted `redrive_outcome_abandoned` with `reported: false` for this
|
|
3343
|
+
* row" (#1366) — the bound tripped but the terminal `markFailed` fallback ALSO
|
|
3344
|
+
* failed (the route-level fault of G2), so every following tick re-attempts
|
|
3345
|
+
* the same terminal PATCH. Guards that quiet retry from re-signalling on
|
|
3346
|
+
* every tick. Cleared by `clearRedriveUnresolved`.
|
|
3347
|
+
*/
|
|
3348
|
+
redriveOutcomeAbandonedSignalled = /* @__PURE__ */ new Set();
|
|
3349
|
+
/**
|
|
3350
|
+
* "Already emitted `dispatch_not_started` for THIS (message, branch) streak"
|
|
3351
|
+
* (#1340). Valued by the branch currently firing, so a row that moves between
|
|
3352
|
+
* exits re-signals — the move IS the finding. Cleared only on a CONFIRMED
|
|
3353
|
+
* dispatch, never on the fence's decision to dispatch: `clearRedriveUnresolved`
|
|
3354
|
+
* runs on that decision (`resolveRedriveUnresolved`), so clearing there would
|
|
3355
|
+
* re-signal on every one of the 15h of re-dispatch attempts #1110 made.
|
|
3356
|
+
*/
|
|
3357
|
+
dispatchNotStartedSignalled = /* @__PURE__ */ new Map();
|
|
3358
|
+
/**
|
|
3359
|
+
* Consecutive-UNCONFIRMED-dispatch streak for a `pending` row with NO stored
|
|
3360
|
+
* `opencode_message_id` yet — i.e. one that has never even reached the
|
|
3361
|
+
* re-drive fence above. `sendPromptAsync`'s POST may 2xx, but its own
|
|
3362
|
+
* read-back retries can never confirm the assigned id when the session's
|
|
3363
|
+
* message list is PERMANENTLY unreadable (e.g. a corrupted local opencode
|
|
3364
|
+
* SQLite DB, #1345/#1348's exact fault, just hit BEFORE the row is ever
|
|
3365
|
+
* dispatched instead of after). Unlike an already-dispatched row, THIS row has
|
|
3366
|
+
* no other safety net at all: the lifecycle cron only reclaims `status =
|
|
3367
|
+
* 'processing'` rows, and a row stuck here never reaches `processing`. Keyed
|
|
3368
|
+
* by message id, carrying `sessionId` so a session change (a fresh one bound
|
|
3369
|
+
* after abandonment) starts a new streak rather than inheriting the old
|
|
3370
|
+
* session's count — same shape as `redrivePollFailures` above.
|
|
3371
|
+
*/
|
|
3372
|
+
unconfirmedDispatchFailures = /* @__PURE__ */ new Map();
|
|
3282
3373
|
/**
|
|
3283
3374
|
* "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
|
|
3284
3375
|
* Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
|
|
@@ -3384,6 +3475,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3384
3475
|
this.now = config.now ?? (() => Date.now());
|
|
3385
3476
|
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
3386
3477
|
this.homeDir = config.homeDir ?? homedir2();
|
|
3478
|
+
this.maxActiveSessions = config.maxActiveSessions;
|
|
3387
3479
|
}
|
|
3388
3480
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
3389
3481
|
get opencodeBase() {
|
|
@@ -3463,10 +3555,26 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3463
3555
|
message: `Found ${total} pending message(s) across ${conversations.length} conversation(s) \u2014 draining`
|
|
3464
3556
|
});
|
|
3465
3557
|
}
|
|
3558
|
+
let cappedSkips = 0;
|
|
3466
3559
|
for (const conv of conversations) {
|
|
3467
3560
|
if (this.stopped) break;
|
|
3561
|
+
if (this.maxActiveSessions !== void 0) {
|
|
3562
|
+
const activeSessionIds = this.activeSessionIdsForCap();
|
|
3563
|
+
const resolvedSessionId = this.sessions.get(conv.id) ?? conv.opencode_session_id;
|
|
3564
|
+
const alreadyActive = resolvedSessionId != null && activeSessionIds.has(resolvedSessionId);
|
|
3565
|
+
if (activeSessionIds.size >= this.maxActiveSessions && !alreadyActive) {
|
|
3566
|
+
cappedSkips++;
|
|
3567
|
+
continue;
|
|
3568
|
+
}
|
|
3569
|
+
}
|
|
3468
3570
|
dispatched += await this.processConversation(conv);
|
|
3469
3571
|
}
|
|
3572
|
+
if (cappedSkips > 0) {
|
|
3573
|
+
this.log({
|
|
3574
|
+
level: "warn",
|
|
3575
|
+
message: `max-active-sessions cap (${this.maxActiveSessions}) reached \u2014 skipped ${cappedSkips} pending conversation(s) this tick`
|
|
3576
|
+
});
|
|
3577
|
+
}
|
|
3470
3578
|
await this.readoptProcessing();
|
|
3471
3579
|
} finally {
|
|
3472
3580
|
this.draining = false;
|
|
@@ -3485,6 +3593,22 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3485
3593
|
}
|
|
3486
3594
|
return false;
|
|
3487
3595
|
}
|
|
3596
|
+
/**
|
|
3597
|
+
* Session ids active *for the `--max-active-sessions` cap*: in-flight work AND
|
|
3598
|
+
* a live watcher loop. Unlike `hasInFlightWatchers()` / `protectedSessionIds()`,
|
|
3599
|
+
* a ZOMBIE watcher (in-flight but `loop === null`, left by a non-auth failure
|
|
3600
|
+
* inside `runWatcherLoop`) does not count here — under a cap it would
|
|
3601
|
+
* permanently consume a slot, whereas cleanup/idle-exit should still treat it
|
|
3602
|
+
* as protected. One call per drain iteration serves both the cap check
|
|
3603
|
+
* (`.size`) and the already-active exemption (`.has`).
|
|
3604
|
+
*/
|
|
3605
|
+
activeSessionIdsForCap() {
|
|
3606
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3607
|
+
for (const [sessionId, watcher] of this.watchers) {
|
|
3608
|
+
if (watcher.inFlight.size > 0 && watcher.loop !== null) ids.add(sessionId);
|
|
3609
|
+
}
|
|
3610
|
+
return ids;
|
|
3611
|
+
}
|
|
3488
3612
|
/**
|
|
3489
3613
|
* File-pull work, for `run.ts`'s idle accounting (#559).
|
|
3490
3614
|
*
|
|
@@ -3603,7 +3727,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3603
3727
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
3604
3728
|
*/
|
|
3605
3729
|
async processConversation(conv) {
|
|
3606
|
-
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
3730
|
+
const { sessionId, refusedSessionId, created: sessionCreated } = await this.ensureSession(conv);
|
|
3607
3731
|
const messages = await this.getPendingMessages(conv.id);
|
|
3608
3732
|
let dispatched = 0;
|
|
3609
3733
|
let skippedAlreadyDispatched = 0;
|
|
@@ -3619,7 +3743,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3619
3743
|
continue;
|
|
3620
3744
|
}
|
|
3621
3745
|
if (message.opencode_message_id) {
|
|
3622
|
-
const outcome = await this.resolveRedrive(conv, sessionId, message,
|
|
3746
|
+
const outcome = await this.resolveRedrive(conv, sessionId, message, sessionCreated);
|
|
3747
|
+
if (outcome === "abandoned") {
|
|
3748
|
+
continue;
|
|
3749
|
+
}
|
|
3623
3750
|
if (outcome !== "dispatch") {
|
|
3624
3751
|
break;
|
|
3625
3752
|
}
|
|
@@ -3653,6 +3780,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3653
3780
|
conversation_id: conv.id,
|
|
3654
3781
|
message_id: message.id
|
|
3655
3782
|
});
|
|
3783
|
+
this.signalDispatchNotStarted(conv, message, "session_deleted_race");
|
|
3656
3784
|
break;
|
|
3657
3785
|
}
|
|
3658
3786
|
if (exists === null) {
|
|
@@ -3662,6 +3790,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3662
3790
|
conversation_id: conv.id,
|
|
3663
3791
|
message_id: message.id
|
|
3664
3792
|
});
|
|
3793
|
+
this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
|
|
3665
3794
|
break;
|
|
3666
3795
|
}
|
|
3667
3796
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
@@ -3680,6 +3809,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3680
3809
|
conversation_id: conv.id,
|
|
3681
3810
|
message_id: message.id
|
|
3682
3811
|
});
|
|
3812
|
+
this.signalDispatchNotStarted(conv, message, "failure_unreported");
|
|
3683
3813
|
});
|
|
3684
3814
|
this.log({
|
|
3685
3815
|
level: "error",
|
|
@@ -3690,14 +3820,40 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3690
3820
|
break;
|
|
3691
3821
|
}
|
|
3692
3822
|
if (opencodeMessageId === null) {
|
|
3823
|
+
const streak = this.recordUnconfirmedDispatch(message.id, sessionId);
|
|
3824
|
+
if (streak < MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
|
|
3825
|
+
this.log({
|
|
3826
|
+
level: "warn",
|
|
3827
|
+
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`,
|
|
3828
|
+
conversation_id: conv.id,
|
|
3829
|
+
message_id: message.id
|
|
3830
|
+
});
|
|
3831
|
+
this.signalDispatchNotStarted(conv, message, "readback_unconfirmed");
|
|
3832
|
+
continue;
|
|
3833
|
+
}
|
|
3834
|
+
this.unconfirmedDispatchFailures.delete(message.id);
|
|
3835
|
+
this.sessions.delete(conv.id);
|
|
3836
|
+
this.supersede(conv.id, sessionId);
|
|
3837
|
+
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
3838
|
this.log({
|
|
3694
|
-
level: "
|
|
3695
|
-
message:
|
|
3839
|
+
level: "error",
|
|
3840
|
+
message: errorMessage,
|
|
3696
3841
|
conversation_id: conv.id,
|
|
3697
3842
|
message_id: message.id
|
|
3698
3843
|
});
|
|
3699
|
-
|
|
3844
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3845
|
+
this.log({
|
|
3846
|
+
level: "warn",
|
|
3847
|
+
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)}`,
|
|
3848
|
+
conversation_id: conv.id,
|
|
3849
|
+
message_id: message.id
|
|
3850
|
+
});
|
|
3851
|
+
this.signalDispatchNotStarted(conv, message, "abandon_unreported");
|
|
3852
|
+
});
|
|
3853
|
+
break;
|
|
3700
3854
|
}
|
|
3855
|
+
this.unconfirmedDispatchFailures.delete(message.id);
|
|
3856
|
+
this.dispatchNotStartedSignalled.delete(message.id);
|
|
3701
3857
|
this.dispatched.add(message.id);
|
|
3702
3858
|
this.registerInFlight(conv, sessionId, message, opencodeMessageId);
|
|
3703
3859
|
dispatched += 1;
|
|
@@ -3718,21 +3874,29 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3718
3874
|
* INJECTED `fetchImpl` — NOT the imported `getSessionMessages` helper, which
|
|
3719
3875
|
* hits the global `fetch` and would bypass the same override every other
|
|
3720
3876
|
* opencode poll in this file respects. Mirrors `readoptProcessing`'s own
|
|
3721
|
-
* snapshot fetch (`:3081-3111`).
|
|
3722
|
-
*
|
|
3723
|
-
*
|
|
3877
|
+
* snapshot fetch (`:3081-3111`).
|
|
3878
|
+
*
|
|
3879
|
+
* Returns `{ ok: true, messages }` on a readable snapshot, or
|
|
3880
|
+
* `{ ok: false, signature }` on failure — `signature` is a string that
|
|
3881
|
+
* repeats across attempts for the SAME underlying fault (used by the
|
|
3882
|
+
* consecutive-identical-failure bound, #1348), or `null` for a thrown
|
|
3883
|
+
* exception, which is NOT countable toward that bound (a network blip / an
|
|
3884
|
+
* opencode restart also throws identically every tick, and must keep
|
|
3885
|
+
* retrying unbounded rather than ever being treated as permanent).
|
|
3724
3886
|
*/
|
|
3725
3887
|
async pollSessionMessagesForRedrive(conv, message, sessionId) {
|
|
3726
3888
|
try {
|
|
3727
3889
|
const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
|
|
3728
3890
|
if (!res.ok) {
|
|
3891
|
+
const rawBody = await res.text();
|
|
3892
|
+
const normalized = normalizeRedrivePollFailureBody(rawBody);
|
|
3729
3893
|
this.log({
|
|
3730
3894
|
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`,
|
|
3895
|
+
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
3896
|
conversation_id: conv.id,
|
|
3733
3897
|
message_id: message.id
|
|
3734
3898
|
});
|
|
3735
|
-
return
|
|
3899
|
+
return { ok: false, signature: `HTTP ${res.status}${normalized ? `: ${normalized}` : ""}` };
|
|
3736
3900
|
}
|
|
3737
3901
|
const body = await res.json();
|
|
3738
3902
|
if (!Array.isArray(body)) {
|
|
@@ -3742,9 +3906,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3742
3906
|
conversation_id: conv.id,
|
|
3743
3907
|
message_id: message.id
|
|
3744
3908
|
});
|
|
3745
|
-
return
|
|
3909
|
+
return { ok: false, signature: "non-array message body" };
|
|
3746
3910
|
}
|
|
3747
|
-
return body;
|
|
3911
|
+
return { ok: true, messages: body };
|
|
3748
3912
|
} catch (err) {
|
|
3749
3913
|
this.log({
|
|
3750
3914
|
level: "warn",
|
|
@@ -3752,7 +3916,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3752
3916
|
conversation_id: conv.id,
|
|
3753
3917
|
message_id: message.id
|
|
3754
3918
|
});
|
|
3755
|
-
return null;
|
|
3919
|
+
return { ok: false, signature: null };
|
|
3756
3920
|
}
|
|
3757
3921
|
}
|
|
3758
3922
|
/**
|
|
@@ -3764,24 +3928,51 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3764
3928
|
* without this fence the drain loop would re-`prompt_async` the SAME turn a
|
|
3765
3929
|
* second time against live GitHub state. Mirrors `readoptOne`'s job for the
|
|
3766
3930
|
* `processing` re-adopt path, but simpler: no b1/b2 preamble cross-check is
|
|
3767
|
-
* needed here because `
|
|
3768
|
-
*
|
|
3931
|
+
* needed here because `sessionCreated` already handles the cases (a #553
|
|
3932
|
+
* abandoned session, a #190 vanished one) that path exists for.
|
|
3769
3933
|
*
|
|
3770
|
-
* Only `ChannelAuthError` propagates
|
|
3771
|
-
* `
|
|
3934
|
+
* Only `ChannelAuthError` propagates. A poll that fails identically
|
|
3935
|
+
* `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row reports the message
|
|
3936
|
+
* failed instead of retrying it (#1348) — SEPARATE from, not a replacement
|
|
3937
|
+
* for, `resolveRedriveUnresolved`'s own `pausedMaxWaitMs` bound below. Every
|
|
3938
|
+
* other failure resolves to `unresolved` and is retried whole on the next
|
|
3939
|
+
* ~2s drain tick.
|
|
3772
3940
|
*/
|
|
3773
|
-
async resolveRedrive(conv, sessionId, message,
|
|
3941
|
+
async resolveRedrive(conv, sessionId, message, sessionCreated) {
|
|
3774
3942
|
const ocId = message.opencode_message_id ?? null;
|
|
3775
|
-
if (
|
|
3943
|
+
if (sessionCreated) {
|
|
3776
3944
|
this.clearRedriveUnresolved(message.id);
|
|
3777
3945
|
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
3778
3946
|
return "dispatch";
|
|
3779
3947
|
}
|
|
3780
|
-
const
|
|
3781
|
-
if (
|
|
3948
|
+
const polled = await this.pollSessionMessagesForRedrive(conv, message, sessionId);
|
|
3949
|
+
if (!polled.ok) {
|
|
3950
|
+
const streak = this.recordRedrivePollFailure(message.id, sessionId, polled.signature);
|
|
3951
|
+
if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES && polled.signature !== null) {
|
|
3952
|
+
return this.failRedrivePollPermanent(conv, sessionId, message, polled.signature, streak);
|
|
3953
|
+
}
|
|
3954
|
+
return this.resolveRedriveUnresolved(conv, message);
|
|
3955
|
+
}
|
|
3956
|
+
this.redrivePollFailures.delete(message.id);
|
|
3957
|
+
const messages = polled.messages;
|
|
3958
|
+
if (messages.length === 0) {
|
|
3782
3959
|
return this.resolveRedriveUnresolved(conv, message);
|
|
3783
3960
|
}
|
|
3784
3961
|
const state = messageRunState(messages, ocId ?? "");
|
|
3962
|
+
if (state === "failed" && isAbortedTerminalReply(messages, ocId ?? "")) {
|
|
3963
|
+
const ongoing = await isSessionOngoing(this.port, sessionId);
|
|
3964
|
+
if (ongoing === false) {
|
|
3965
|
+
this.log({
|
|
3966
|
+
level: "info",
|
|
3967
|
+
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`,
|
|
3968
|
+
conversation_id: conv.id,
|
|
3969
|
+
message_id: message.id
|
|
3970
|
+
});
|
|
3971
|
+
this.clearRedriveUnresolved(message.id);
|
|
3972
|
+
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
3973
|
+
return "dispatch";
|
|
3974
|
+
}
|
|
3975
|
+
}
|
|
3785
3976
|
if (state === "done" || state === "failed") {
|
|
3786
3977
|
return this.settleRedrive(conv, sessionId, message, ocId, messages, state);
|
|
3787
3978
|
}
|
|
@@ -3825,13 +4016,23 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3825
4016
|
await this.markProcessing(conv.id, message.id, sessionId, ocId, title);
|
|
3826
4017
|
} catch (err) {
|
|
3827
4018
|
if (err instanceof ChannelAuthError) throw err;
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
|
|
3834
|
-
|
|
4019
|
+
if (err instanceof ChannelTerminalError) {
|
|
4020
|
+
this.log({
|
|
4021
|
+
level: "error",
|
|
4022
|
+
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`,
|
|
4023
|
+
conversation_id: conv.id,
|
|
4024
|
+
message_id: message.id
|
|
4025
|
+
});
|
|
4026
|
+
} else {
|
|
4027
|
+
this.log({
|
|
4028
|
+
level: "warn",
|
|
4029
|
+
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)}`,
|
|
4030
|
+
conversation_id: conv.id,
|
|
4031
|
+
message_id: message.id
|
|
4032
|
+
});
|
|
4033
|
+
}
|
|
4034
|
+
const bound = await this.boundRedriveOutcome(conv, message, "reattach");
|
|
4035
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
3835
4036
|
}
|
|
3836
4037
|
this.clearRedriveUnresolved(message.id);
|
|
3837
4038
|
this.registerReadopted(conv, sessionId, message, ocId ?? "", anchorMs);
|
|
@@ -3855,7 +4056,9 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3855
4056
|
* errored) while nobody was watching — deliver/report it instead of re-running.
|
|
3856
4057
|
* Mirrors `readoptOne`'s `done`/`failed` branches' error discipline, simplified
|
|
3857
4058
|
* (no `doneUndeliverable` park: a terminal PATCH failure here just retries next
|
|
3858
|
-
* drain, same as any other non-auth failure).
|
|
4059
|
+
* drain, same as any other non-auth failure). The restart-abort carve-out that
|
|
4060
|
+
* keeps the two in step for `failed` lives in the caller (`resolveRedrive`, #1310),
|
|
4061
|
+
* so a row reaching this `failed` branch is a GENUINE failure.
|
|
3859
4062
|
*/
|
|
3860
4063
|
async settleRedrive(conv, sessionId, message, ocId, messages, state) {
|
|
3861
4064
|
try {
|
|
@@ -3889,19 +4092,62 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3889
4092
|
conversation_id: conv.id,
|
|
3890
4093
|
message_id: message.id
|
|
3891
4094
|
});
|
|
3892
|
-
|
|
4095
|
+
const bound = await this.boundRedriveOutcome(conv, message, "settle");
|
|
4096
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
3893
4097
|
}
|
|
3894
4098
|
this.clearRedriveUnresolved(message.id);
|
|
3895
4099
|
void this.postSignal(conv.id, message.id, "redrive_settled");
|
|
3896
4100
|
return "settled";
|
|
3897
4101
|
}
|
|
4102
|
+
/**
|
|
4103
|
+
* The permanent-failure outcome (#1348): the fence's own poll of this session
|
|
4104
|
+
* failed with the SAME opencode-answered signature
|
|
4105
|
+
* `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row — a transient blip
|
|
4106
|
+
* would have varied or eventually cleared (see `pollSessionMessagesForRedrive`
|
|
4107
|
+
* and `recordRedrivePollFailure`), so this is a durable fault (e.g. #1345's
|
|
4108
|
+
* corrupted opencode session) rather than something worth retrying forever.
|
|
4109
|
+
* Mirrors `settleRedrive`'s error discipline: no `usage`/`failure` args to
|
|
4110
|
+
* `markFailed` (no opencode snapshot to extract them from — this poll never
|
|
4111
|
+
* got a readable one).
|
|
4112
|
+
*/
|
|
4113
|
+
async failRedrivePollPermanent(conv, sessionId, message, signature, streak) {
|
|
4114
|
+
this.log({
|
|
4115
|
+
level: "error",
|
|
4116
|
+
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`,
|
|
4117
|
+
conversation_id: conv.id,
|
|
4118
|
+
message_id: message.id
|
|
4119
|
+
});
|
|
4120
|
+
try {
|
|
4121
|
+
await this.markFailed(
|
|
4122
|
+
conv.id,
|
|
4123
|
+
message.id,
|
|
4124
|
+
sessionId,
|
|
4125
|
+
`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.`
|
|
4126
|
+
);
|
|
4127
|
+
} catch (err) {
|
|
4128
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4129
|
+
this.log({
|
|
4130
|
+
level: "warn",
|
|
4131
|
+
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)}`,
|
|
4132
|
+
conversation_id: conv.id,
|
|
4133
|
+
message_id: message.id
|
|
4134
|
+
});
|
|
4135
|
+
const bound = await this.boundRedriveOutcome(conv, message, "fail_permanent");
|
|
4136
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
4137
|
+
}
|
|
4138
|
+
this.clearRedriveUnresolved(message.id);
|
|
4139
|
+
void this.postSignal(conv.id, message.id, "redrive_poll_failed");
|
|
4140
|
+
return "settled";
|
|
4141
|
+
}
|
|
3898
4142
|
/**
|
|
3899
4143
|
* The bounded `unresolved` outcome (Task 3.4): opencode's state could not be
|
|
3900
4144
|
* observed (snapshot unreadable/empty, or `isSessionOngoing` returned `null`).
|
|
3901
|
-
* A `pending` row is
|
|
3902
|
-
*
|
|
3903
|
-
*
|
|
3904
|
-
*
|
|
4145
|
+
* A `pending` row is swept by the server's own `PENDING_MAX_AGE_MS` (24h,
|
|
4146
|
+
* #1368) cron arm, but that is a day-scale backstop — this local bound acts
|
|
4147
|
+
* in minutes so the row (and the conversation it starves, per the ordering
|
|
4148
|
+
* invariant below) isn't left stranded for that long. Bound to the existing
|
|
4149
|
+
* `pausedMaxWaitMs` window (reusing the knob, not a new constant); takes
|
|
4150
|
+
* `dispatch` once elapsed.
|
|
3905
4151
|
*/
|
|
3906
4152
|
resolveRedriveUnresolved(conv, message) {
|
|
3907
4153
|
const now = this.now();
|
|
@@ -3920,10 +4166,153 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3920
4166
|
}
|
|
3921
4167
|
return "unresolved";
|
|
3922
4168
|
}
|
|
3923
|
-
/** Clear
|
|
4169
|
+
/** Clear all `unresolved`/failure-streak trackers for a row (any non-`unresolved` outcome). */
|
|
3924
4170
|
clearRedriveUnresolved(messageId) {
|
|
3925
4171
|
this.redriveUnresolvedSince.delete(messageId);
|
|
3926
4172
|
this.redriveUnresolvedSignalled.delete(messageId);
|
|
4173
|
+
this.redrivePollFailures.delete(messageId);
|
|
4174
|
+
this.redriveOutcomeUnreportedSignalled.delete(messageId);
|
|
4175
|
+
this.redriveOutcomeFailingSince.delete(messageId);
|
|
4176
|
+
this.redriveOutcomeAbandonedSignalled.delete(messageId);
|
|
4177
|
+
}
|
|
4178
|
+
/**
|
|
4179
|
+
* #1340: the dispatch loop reached a message and did NOT start a turn. Fires at
|
|
4180
|
+
* most once per (message, branch) streak — a wedged row is re-tried every tick,
|
|
4181
|
+
* and the per-tick count is already carried by the co-occurring
|
|
4182
|
+
* `redrive_unresolved`/`redrive_redispatched` signals.
|
|
4183
|
+
*/
|
|
4184
|
+
signalDispatchNotStarted(conv, message, branch) {
|
|
4185
|
+
if (this.dispatchNotStartedSignalled.get(message.id) === branch) return;
|
|
4186
|
+
this.dispatchNotStartedSignalled.set(message.id, branch);
|
|
4187
|
+
void this.postSignal(conv.id, message.id, "dispatch_not_started", { branch });
|
|
4188
|
+
}
|
|
4189
|
+
/**
|
|
4190
|
+
* Class B (#1340): the runner DECIDED an outcome (reattach/settle/fail_permanent)
|
|
4191
|
+
* but its own PATCH to record it failed. Fires at most once per (message,
|
|
4192
|
+
* outcome) streak, and only while `boundRedriveOutcome` has not yet tripped —
|
|
4193
|
+
* once it trips, `redrive_outcome_abandoned` takes over reporting for the row
|
|
4194
|
+
* (#1366).
|
|
4195
|
+
*/
|
|
4196
|
+
signalRedriveOutcomeUnreported(conv, message, outcome) {
|
|
4197
|
+
if (this.redriveOutcomeUnreportedSignalled.get(message.id) === outcome) return;
|
|
4198
|
+
this.redriveOutcomeUnreportedSignalled.set(message.id, outcome);
|
|
4199
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_unreported", {
|
|
4200
|
+
attempted_outcome: outcome
|
|
4201
|
+
});
|
|
4202
|
+
}
|
|
4203
|
+
/**
|
|
4204
|
+
* The runner-authored, honest error text for the terminal fallback a tripped
|
|
4205
|
+
* `boundRedriveOutcome` sends. Distinguishable per outcome and truthful about
|
|
4206
|
+
* what actually happened — the `settle`/done case must say the turn finished
|
|
4207
|
+
* but its result could not be recorded, never that the runner stopped
|
|
4208
|
+
* responding (that would be a lie for this shape, see #1366's "why this ships").
|
|
4209
|
+
*/
|
|
4210
|
+
static REDRIVE_ABANDON_ERROR = {
|
|
4211
|
+
reattach: "your runner could not record that this message had started, so it was given up on",
|
|
4212
|
+
settle: "your runner finished this message but could not record the result, so the reply could not be delivered",
|
|
4213
|
+
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"
|
|
4214
|
+
};
|
|
4215
|
+
/**
|
|
4216
|
+
* Bound for Class B (#1340, #1366): the runner DECIDED an outcome but its own
|
|
4217
|
+
* PATCH to record it failed. Two independent trip arms (either sufficient):
|
|
4218
|
+
* (1) this failure streak has lasted `pausedMaxWaitMs` — DURATION, not a tick
|
|
4219
|
+
* count, reusing the knob `resolveRedriveUnresolved` already established; (2)
|
|
4220
|
+
* the turn's `processing_started_at` age has crossed
|
|
4221
|
+
* `ABSOLUTE_MAX_PROCESSING_MS` — durable and restart-surviving, since arm (1)'s
|
|
4222
|
+
* in-memory streak resets on a scale-to-zero restart.
|
|
4223
|
+
*
|
|
4224
|
+
* INVARIANT — a tripped bound never suppresses the original outcome attempt;
|
|
4225
|
+
* it only adds a fallback after that attempt has failed again. This is only
|
|
4226
|
+
* ever reached from inside the catch of the ORIGINAL outcome PATCH, which is
|
|
4227
|
+
* attempted first on every tick whether or not this bound tripped before —
|
|
4228
|
+
* there is no give-up latch that would short-circuit it. That is what lets a
|
|
4229
|
+
* route-level fault that heals later still deliver the turn's real
|
|
4230
|
+
* `done`/`failed` payload: once the original PATCH succeeds again, this
|
|
4231
|
+
* helper is never entered and the row settles with its real result.
|
|
4232
|
+
*/
|
|
4233
|
+
async boundRedriveOutcome(conv, message, outcome) {
|
|
4234
|
+
const now = this.now();
|
|
4235
|
+
const since = this.redriveOutcomeFailingSince.get(message.id);
|
|
4236
|
+
if (since === void 0) this.redriveOutcomeFailingSince.set(message.id, now);
|
|
4237
|
+
const durationTripped = now - (since ?? now) >= this.pausedMaxWaitMs;
|
|
4238
|
+
const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
|
|
4239
|
+
const absoluteAgeTripped = !Number.isNaN(parsed) && now - parsed >= ABSOLUTE_MAX_PROCESSING_MS;
|
|
4240
|
+
if (!durationTripped && !absoluteAgeTripped) {
|
|
4241
|
+
this.signalRedriveOutcomeUnreported(conv, message, outcome);
|
|
4242
|
+
return "retry";
|
|
4243
|
+
}
|
|
4244
|
+
const arm = durationTripped ? "failure_window" : "absolute_age";
|
|
4245
|
+
try {
|
|
4246
|
+
await this.markFailed(
|
|
4247
|
+
conv.id,
|
|
4248
|
+
message.id,
|
|
4249
|
+
void 0,
|
|
4250
|
+
_ChannelDriver.REDRIVE_ABANDON_ERROR[outcome]
|
|
4251
|
+
);
|
|
4252
|
+
} catch (err) {
|
|
4253
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4254
|
+
this.log({
|
|
4255
|
+
level: "warn",
|
|
4256
|
+
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)}`,
|
|
4257
|
+
conversation_id: conv.id,
|
|
4258
|
+
message_id: message.id
|
|
4259
|
+
});
|
|
4260
|
+
if (!this.redriveOutcomeAbandonedSignalled.has(message.id)) {
|
|
4261
|
+
this.redriveOutcomeAbandonedSignalled.add(message.id);
|
|
4262
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
|
|
4263
|
+
attempted_outcome: outcome,
|
|
4264
|
+
reported: false,
|
|
4265
|
+
arm
|
|
4266
|
+
});
|
|
4267
|
+
}
|
|
4268
|
+
return "retry";
|
|
4269
|
+
}
|
|
4270
|
+
this.clearRedriveUnresolved(message.id);
|
|
4271
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
|
|
4272
|
+
attempted_outcome: outcome,
|
|
4273
|
+
reported: true,
|
|
4274
|
+
arm
|
|
4275
|
+
});
|
|
4276
|
+
return "abandoned";
|
|
4277
|
+
}
|
|
4278
|
+
/**
|
|
4279
|
+
* Record one poll outcome toward the re-drive fence's consecutive-identical-
|
|
4280
|
+
* failure streak (#1348) and return the resulting count. `signature === null`
|
|
4281
|
+
* (a thrown exception, H1) always clears the streak and returns `0` — it is
|
|
4282
|
+
* never countable. Otherwise the streak continues only when BOTH the session
|
|
4283
|
+
* and the signature match the previous failure; anything else (a different
|
|
4284
|
+
* session, or the same session failing a DIFFERENT way) starts a fresh streak
|
|
4285
|
+
* at `1`.
|
|
4286
|
+
*/
|
|
4287
|
+
recordRedrivePollFailure(messageId, sessionId, signature) {
|
|
4288
|
+
if (signature === null) {
|
|
4289
|
+
this.redrivePollFailures.delete(messageId);
|
|
4290
|
+
return 0;
|
|
4291
|
+
}
|
|
4292
|
+
const existing = this.redrivePollFailures.get(messageId);
|
|
4293
|
+
if (existing && existing.sessionId === sessionId && existing.signature === signature) {
|
|
4294
|
+
existing.count += 1;
|
|
4295
|
+
return existing.count;
|
|
4296
|
+
}
|
|
4297
|
+
this.redrivePollFailures.set(messageId, { sessionId, signature, count: 1 });
|
|
4298
|
+
return 1;
|
|
4299
|
+
}
|
|
4300
|
+
/**
|
|
4301
|
+
* Record one UNCONFIRMED-dispatch outcome (a `pending` row with no stored
|
|
4302
|
+
* `opencode_message_id` whose `sendPromptAsync` returned `null`) toward the
|
|
4303
|
+
* bound in `processConversation`'s dispatch loop, and return the resulting
|
|
4304
|
+
* count. Mirrors `recordRedrivePollFailure`'s session-scoping: a session
|
|
4305
|
+
* change starts a fresh streak at `1` rather than inheriting the old one's
|
|
4306
|
+
* count, since a new session is a genuinely different attempt.
|
|
4307
|
+
*/
|
|
4308
|
+
recordUnconfirmedDispatch(messageId, sessionId) {
|
|
4309
|
+
const existing = this.unconfirmedDispatchFailures.get(messageId);
|
|
4310
|
+
if (existing && existing.sessionId === sessionId) {
|
|
4311
|
+
existing.count += 1;
|
|
4312
|
+
return existing.count;
|
|
4313
|
+
}
|
|
4314
|
+
this.unconfirmedDispatchFailures.set(messageId, { sessionId, count: 1 });
|
|
4315
|
+
return 1;
|
|
3927
4316
|
}
|
|
3928
4317
|
/**
|
|
3929
4318
|
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
@@ -3949,6 +4338,13 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3949
4338
|
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3950
4339
|
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3951
4340
|
* happened and a fresh session was bound instead. The caller reports it.
|
|
4341
|
+
*
|
|
4342
|
+
* `created` says the returned session was made JUST NOW, so it provably holds
|
|
4343
|
+
* no prior turn. The re-drive fence needs that as CONTRARY evidence ("nothing
|
|
4344
|
+
* to reconcile against") — distinct from the ambiguous "I polled and saw an
|
|
4345
|
+
* empty transcript", which stays a deferral. Keep it separate from
|
|
4346
|
+
* `refusedSessionId`: only the latter means a #553 resurrection happened, and
|
|
4347
|
+
* only it may drive the `session_superseded` signal.
|
|
3952
4348
|
*/
|
|
3953
4349
|
async ensureSession(conv) {
|
|
3954
4350
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
@@ -3959,7 +4355,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3959
4355
|
conversation_id: conv.id
|
|
3960
4356
|
});
|
|
3961
4357
|
this.sessions.delete(conv.id);
|
|
3962
|
-
return {
|
|
4358
|
+
return {
|
|
4359
|
+
sessionId: await this.createAndBindSession(conv.id),
|
|
4360
|
+
refusedSessionId: bound,
|
|
4361
|
+
created: true
|
|
4362
|
+
};
|
|
3963
4363
|
}
|
|
3964
4364
|
if (bound) {
|
|
3965
4365
|
const exists = await sessionExists(this.port, bound);
|
|
@@ -3970,12 +4370,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3970
4370
|
conversation_id: conv.id
|
|
3971
4371
|
});
|
|
3972
4372
|
this.sessions.delete(conv.id);
|
|
3973
|
-
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
4373
|
+
return { sessionId: await this.createAndBindSession(conv.id), created: true };
|
|
3974
4374
|
}
|
|
3975
4375
|
this.sessions.set(conv.id, bound);
|
|
3976
|
-
return { sessionId: bound };
|
|
4376
|
+
return { sessionId: bound, created: false };
|
|
3977
4377
|
}
|
|
3978
|
-
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
4378
|
+
return { sessionId: await this.createAndBindSession(conv.id), created: true };
|
|
3979
4379
|
}
|
|
3980
4380
|
/**
|
|
3981
4381
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -4404,9 +4804,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4404
4804
|
const awaitingHuman = observedOpen || latchedPaused;
|
|
4405
4805
|
if ((state === "running" || state === "done" || state === "failed") && !inFlight.started) {
|
|
4406
4806
|
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
4407
|
-
let claimed;
|
|
4408
4807
|
try {
|
|
4409
|
-
|
|
4808
|
+
await this.markProcessing(
|
|
4410
4809
|
conv.id,
|
|
4411
4810
|
inFlight.evidentMessageId,
|
|
4412
4811
|
sessionId,
|
|
@@ -4415,23 +4814,24 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4415
4814
|
);
|
|
4416
4815
|
} catch (err) {
|
|
4417
4816
|
if (err instanceof ChannelAuthError) throw err;
|
|
4418
|
-
|
|
4419
|
-
|
|
4420
|
-
|
|
4421
|
-
|
|
4422
|
-
|
|
4423
|
-
|
|
4424
|
-
|
|
4817
|
+
if (err instanceof ChannelTerminalError) {
|
|
4818
|
+
this.log({
|
|
4819
|
+
level: "error",
|
|
4820
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (terminal HTTP ${err.status}) \u2014 the server definitively refused the swap`,
|
|
4821
|
+
conversation_id: conv.id,
|
|
4822
|
+
message_id: inFlight.evidentMessageId
|
|
4823
|
+
});
|
|
4824
|
+
} else {
|
|
4825
|
+
this.log({
|
|
4826
|
+
level: "warn",
|
|
4827
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
4828
|
+
conversation_id: conv.id,
|
|
4829
|
+
message_id: inFlight.evidentMessageId
|
|
4830
|
+
});
|
|
4831
|
+
return;
|
|
4832
|
+
}
|
|
4425
4833
|
}
|
|
4426
4834
|
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
4835
|
}
|
|
4436
4836
|
if (state === "done") {
|
|
4437
4837
|
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
@@ -4771,7 +5171,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4771
5171
|
* re-dispatched (at most once, see `forceReadoptRun`):
|
|
4772
5172
|
* - `done` → `markDone` now (guarded like the watcher's done branch);
|
|
4773
5173
|
* - `failed` → `markFailed` with the surfaced error (issue #182), so an
|
|
4774
|
-
* errored turn is reported failed on restart, NOT re-dispatched
|
|
5174
|
+
* errored turn is reported failed on restart, NOT re-dispatched —
|
|
5175
|
+
* EXCEPT a restart-ABORTED turn under a not-ongoing session,
|
|
5176
|
+
* which is a restart orphan wearing a terminal error and is
|
|
5177
|
+
* re-dispatched instead (issue #1310, see the branch below);
|
|
4775
5178
|
* - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
|
|
4776
5179
|
* tracking the stored id so the reply correlates by it;
|
|
4777
5180
|
* - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
|
|
@@ -4835,7 +5238,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4835
5238
|
void this.postSignal(row.conversation_id, row.id, "readopt_done");
|
|
4836
5239
|
return;
|
|
4837
5240
|
}
|
|
4838
|
-
|
|
5241
|
+
const restartAborted = state === "failed" && sessionOngoing === false && isAbortedTerminalReply(messages, ocId ?? "");
|
|
5242
|
+
if (restartAborted) {
|
|
5243
|
+
this.log({
|
|
5244
|
+
level: "info",
|
|
5245
|
+
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`,
|
|
5246
|
+
conversation_id: row.conversation_id,
|
|
5247
|
+
message_id: row.id
|
|
5248
|
+
});
|
|
5249
|
+
}
|
|
5250
|
+
if (state === "failed" && !restartAborted) {
|
|
4839
5251
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
4840
5252
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4841
5253
|
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
@@ -5049,15 +5461,39 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5049
5461
|
}
|
|
5050
5462
|
if (ocId === null) {
|
|
5051
5463
|
this.awaitingReadopt.delete(row.id);
|
|
5464
|
+
const streak = this.recordUnconfirmedDispatch(row.id, sessionId);
|
|
5465
|
+
if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
|
|
5466
|
+
this.unconfirmedDispatchFailures.delete(row.id);
|
|
5467
|
+
this.sessions.delete(readoptConv.id);
|
|
5468
|
+
this.supersede(readoptConv.id, sessionId);
|
|
5469
|
+
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.`;
|
|
5470
|
+
this.log({
|
|
5471
|
+
level: "error",
|
|
5472
|
+
message: errorMessage,
|
|
5473
|
+
conversation_id: row.conversation_id,
|
|
5474
|
+
message_id: row.id
|
|
5475
|
+
});
|
|
5476
|
+
await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
|
|
5477
|
+
this.log({
|
|
5478
|
+
level: "warn",
|
|
5479
|
+
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)}`,
|
|
5480
|
+
conversation_id: row.conversation_id,
|
|
5481
|
+
message_id: row.id
|
|
5482
|
+
});
|
|
5483
|
+
});
|
|
5484
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
5485
|
+
return;
|
|
5486
|
+
}
|
|
5052
5487
|
this.log({
|
|
5053
5488
|
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`,
|
|
5489
|
+
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
5490
|
conversation_id: row.conversation_id,
|
|
5056
5491
|
message_id: row.id
|
|
5057
5492
|
});
|
|
5058
5493
|
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
5059
5494
|
return;
|
|
5060
5495
|
}
|
|
5496
|
+
this.unconfirmedDispatchFailures.delete(row.id);
|
|
5061
5497
|
this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
|
|
5062
5498
|
this.dispatched.add(row.id);
|
|
5063
5499
|
this.readopted.add(row.id);
|
|
@@ -5722,18 +6158,22 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5722
6158
|
* opencode_session_id}` → `notifyMessageStarted` (hourglass→runner swap +
|
|
5723
6159
|
* deep-linked "View in Evident" notice).
|
|
5724
6160
|
*
|
|
5725
|
-
*
|
|
5726
|
-
* -
|
|
5727
|
-
*
|
|
5728
|
-
*
|
|
5729
|
-
*
|
|
5730
|
-
*
|
|
5731
|
-
*
|
|
5732
|
-
*
|
|
5733
|
-
*
|
|
5734
|
-
*
|
|
5735
|
-
*
|
|
5736
|
-
*
|
|
6161
|
+
* Outcome contract (consumed by the watcher's swap-to-running guard):
|
|
6162
|
+
* - resolves (`void`) → the server transitioned the row to
|
|
6163
|
+
* processing (or idempotently confirmed
|
|
6164
|
+
* already-processing — that answer is
|
|
6165
|
+
* still a 200, never a refusal);
|
|
6166
|
+
* - throws `ChannelAuthError` → 401/403 (terminal auth failure);
|
|
6167
|
+
* - throws `ChannelTerminalError` → a definitive non-retryable, non-auth 4xx
|
|
6168
|
+
* (404 the row or its conversation is
|
|
6169
|
+
* gone, 400 the update was rejected).
|
|
6170
|
+
* Retrying cannot help;
|
|
6171
|
+
* - throws a plain `Error` → a TRANSIENT failure (retryable 5xx/429
|
|
6172
|
+
* status, or a network-level error from
|
|
6173
|
+
* `fetch`) — i.e. NO definitive server
|
|
6174
|
+
* response — so the caller leaves the
|
|
6175
|
+
* message un-started and retries the swap
|
|
6176
|
+
* on the next tick.
|
|
5737
6177
|
* A single attempt (no internal retry): the watcher's per-tick loop is the
|
|
5738
6178
|
* retry vehicle for the swap-to-running.
|
|
5739
6179
|
*/
|
|
@@ -5752,11 +6192,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5752
6192
|
}
|
|
5753
6193
|
);
|
|
5754
6194
|
this.assertAuth(res, "marking message as processing");
|
|
5755
|
-
if (res.ok) return
|
|
6195
|
+
if (res.ok) return;
|
|
5756
6196
|
if (isRetryableStatus(res.status)) {
|
|
5757
6197
|
throw new Error(`marking message as processing: HTTP ${res.status}`);
|
|
5758
6198
|
}
|
|
5759
|
-
|
|
6199
|
+
throw new ChannelTerminalError(`marking message as processing: HTTP ${res.status}`, res.status);
|
|
5760
6200
|
}
|
|
5761
6201
|
/**
|
|
5762
6202
|
* EXISTING combinedAuth completion route — idempotent (WI-CHAN-2). `PATCH
|
|
@@ -6242,6 +6682,32 @@ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
|
6242
6682
|
}
|
|
6243
6683
|
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
6244
6684
|
}
|
|
6685
|
+
var MAX_ACTIVE_SESSIONS_ENV = "EVIDENT_MAX_ACTIVE_SESSIONS";
|
|
6686
|
+
function resolveMaxActiveSessions(options, env = process.env) {
|
|
6687
|
+
let raw;
|
|
6688
|
+
let source;
|
|
6689
|
+
if (options.maxActiveSessions !== void 0) {
|
|
6690
|
+
raw = options.maxActiveSessions;
|
|
6691
|
+
source = "--max-active-sessions";
|
|
6692
|
+
} else if (env[MAX_ACTIVE_SESSIONS_ENV] !== void 0 && env[MAX_ACTIVE_SESSIONS_ENV] !== "") {
|
|
6693
|
+
raw = env[MAX_ACTIVE_SESSIONS_ENV];
|
|
6694
|
+
source = MAX_ACTIVE_SESSIONS_ENV;
|
|
6695
|
+
} else {
|
|
6696
|
+
return { value: void 0, warnings: [] };
|
|
6697
|
+
}
|
|
6698
|
+
const trimmed = raw.trim();
|
|
6699
|
+
const count = Number(trimmed);
|
|
6700
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(count) && count > 0;
|
|
6701
|
+
if (!isPositiveInteger) {
|
|
6702
|
+
return {
|
|
6703
|
+
value: void 0,
|
|
6704
|
+
warnings: [
|
|
6705
|
+
`Ignoring invalid ${source} "${raw}": expected a positive integer; using unlimited`
|
|
6706
|
+
]
|
|
6707
|
+
};
|
|
6708
|
+
}
|
|
6709
|
+
return { value: count, warnings: [] };
|
|
6710
|
+
}
|
|
6245
6711
|
function meetsThreshold(state, level) {
|
|
6246
6712
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
6247
6713
|
}
|
|
@@ -6967,6 +7433,10 @@ async function run(options) {
|
|
|
6967
7433
|
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6968
7434
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6969
7435
|
}
|
|
7436
|
+
const { value: maxActiveSessions, warnings: maxActiveSessionsWarnings } = resolveMaxActiveSessions(options, process.env);
|
|
7437
|
+
for (const warning2 of maxActiveSessionsWarnings) {
|
|
7438
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
7439
|
+
}
|
|
6970
7440
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
6971
7441
|
try {
|
|
6972
7442
|
const oc = await ensureOpenCodeRunning({
|
|
@@ -7027,6 +7497,7 @@ async function run(options) {
|
|
|
7027
7497
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
7028
7498
|
fileSyncDirectories,
|
|
7029
7499
|
homeDir: homedir3(),
|
|
7500
|
+
maxActiveSessions,
|
|
7030
7501
|
log: (entry) => (
|
|
7031
7502
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
7032
7503
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -7227,6 +7698,9 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
7227
7698
|
).option(
|
|
7228
7699
|
"--session-cleanup-max-count <n>",
|
|
7229
7700
|
"Keep only the newest N OpenCode sessions. Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_COUNT"
|
|
7701
|
+
).option(
|
|
7702
|
+
"--max-active-sessions <n>",
|
|
7703
|
+
"Cap how many sessions this runner works on at once (default: unlimited). Env: EVIDENT_MAX_ACTIVE_SESSIONS"
|
|
7230
7704
|
).option(
|
|
7231
7705
|
"--session-cleanup-interval <duration>",
|
|
7232
7706
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
@@ -7260,6 +7734,7 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
7260
7734
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
7261
7735
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
7262
7736
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
7737
|
+
maxActiveSessions: options.maxActiveSessions,
|
|
7263
7738
|
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
7264
7739
|
// Raw string — the resolver in run.ts single-sources parsing
|
|
7265
7740
|
// (resolveClaudeUsageReportingMode).
|