@evident-ai/cli 3.1.1-dev.2ab3b19 → 3.1.1-dev.2b780b5

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/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 {
@@ -997,6 +1007,9 @@ import { homedir as homedir3 } from "os";
997
1007
  import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
998
1008
  import chalk6 from "chalk";
999
1009
 
1010
+ // ../../packages/types/src/agents/index.ts
1011
+ var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
1012
+
1000
1013
  // ../../packages/types/src/telemetry/index.ts
1001
1014
  var TelemetryEventTypes = {
1002
1015
  // Agent activity events (shown in web UI activity log)
@@ -2086,6 +2099,21 @@ function messageError(messages, userMessageId) {
2086
2099
  }
2087
2100
  return "The agent run failed.";
2088
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
+ }
2089
2117
  function messageFailure(messages, userMessageId) {
2090
2118
  const reply = findLastAssistantReplyFor(messages, userMessageId);
2091
2119
  const error2 = errorOf(reply);
@@ -2688,6 +2716,10 @@ function nextReportDelayMs(random = Math.random) {
2688
2716
  return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
2689
2717
  }
2690
2718
  var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
2719
+ var CLAUDE_USAGE_FAILURE_REESCALATION_TICKS = 6;
2720
+ function claudeUsageFailureLogLevel(consecutiveFailures) {
2721
+ return consecutiveFailures === 1 || consecutiveFailures % CLAUDE_USAGE_FAILURE_REESCALATION_TICKS === 0 ? "warn" : "debug";
2722
+ }
2691
2723
 
2692
2724
  // src/lib/channels/driver.ts
2693
2725
  import { homedir as homedir2 } from "os";
@@ -3119,6 +3151,7 @@ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
3119
3151
  var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
3120
3152
  var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
3121
3153
  var MAX_SUPERSEDED_CONVERSATIONS = 256;
3154
+ var MAX_IDENTICAL_REDRIVE_POLL_FAILURES = 5;
3122
3155
  var ChannelAuthError = class extends Error {
3123
3156
  constructor(message) {
3124
3157
  super(message);
@@ -3141,6 +3174,10 @@ function backoffDelay(attempt, policy) {
3141
3174
  function isRetryableStatus(status2) {
3142
3175
  return status2 === 429 || status2 >= 500 && status2 <= 599;
3143
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
+ }
3144
3181
  var ChannelDriver = class _ChannelDriver {
3145
3182
  agentId;
3146
3183
  port;
@@ -3157,6 +3194,7 @@ var ChannelDriver = class _ChannelDriver {
3157
3194
  now;
3158
3195
  fileSyncDirectories;
3159
3196
  homeDir;
3197
+ maxActiveSessions;
3160
3198
  /** Cache of conversationId → opencode sessionId. */
3161
3199
  sessions = /* @__PURE__ */ new Map();
3162
3200
  /**
@@ -3254,6 +3292,84 @@ var ChannelDriver = class _ChannelDriver {
3254
3292
  * processing list, exactly like `dontRedispatch`/`doneUndeliverable`.
3255
3293
  */
3256
3294
  readoptPollUnresolvedSignalled = /* @__PURE__ */ new Set();
3295
+ /**
3296
+ * "Already emitted `redrive_unresolved` for this row" (#965). Mirrors
3297
+ * `readoptPollUnresolvedSignalled`: `resolveRedrive`'s `unresolved` leaf recurs
3298
+ * every ~2s drain until opencode's status becomes readable, but the
3299
+ * server-visible signal is an OUTCOME, so it fires at most once per row. Cleared
3300
+ * on any non-`unresolved` outcome so the set cannot grow beyond the currently
3301
+ * unresolvable rows.
3302
+ */
3303
+ redriveUnresolvedSignalled = /* @__PURE__ */ new Set();
3304
+ /**
3305
+ * First `now()` a `pending` row's re-drive was observed `unresolved` (#965). A
3306
+ * `pending` row is invisible to every cron arm (all require `status =
3307
+ * 'processing'`), so an indefinitely-`unresolved` row would be stranded with
3308
+ * nothing driving it. Once `now - since >= pausedMaxWaitMs`, `resolveRedrive`
3309
+ * takes `dispatch` instead of `unresolved` (reusing the existing knob — see
3310
+ * ADR-0047's own "unreachable ⇒ bounded" rule). Cleared on any other outcome.
3311
+ */
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();
3257
3373
  /**
3258
3374
  * "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
3259
3375
  * Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
@@ -3359,6 +3475,7 @@ var ChannelDriver = class _ChannelDriver {
3359
3475
  this.now = config.now ?? (() => Date.now());
3360
3476
  this.fileSyncDirectories = config.fileSyncDirectories ?? [];
3361
3477
  this.homeDir = config.homeDir ?? homedir2();
3478
+ this.maxActiveSessions = config.maxActiveSessions;
3362
3479
  }
3363
3480
  /** The IPv4-loopback base URL for the local `opencode serve`. */
3364
3481
  get opencodeBase() {
@@ -3438,10 +3555,26 @@ var ChannelDriver = class _ChannelDriver {
3438
3555
  message: `Found ${total} pending message(s) across ${conversations.length} conversation(s) \u2014 draining`
3439
3556
  });
3440
3557
  }
3558
+ let cappedSkips = 0;
3441
3559
  for (const conv of conversations) {
3442
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
+ }
3443
3570
  dispatched += await this.processConversation(conv);
3444
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
+ }
3445
3578
  await this.readoptProcessing();
3446
3579
  } finally {
3447
3580
  this.draining = false;
@@ -3460,6 +3593,22 @@ var ChannelDriver = class _ChannelDriver {
3460
3593
  }
3461
3594
  return false;
3462
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
+ }
3463
3612
  /**
3464
3613
  * File-pull work, for `run.ts`'s idle accounting (#559).
3465
3614
  *
@@ -3578,7 +3727,7 @@ var ChannelDriver = class _ChannelDriver {
3578
3727
  * @returns the count of messages NEWLY dispatched (not already in-flight).
3579
3728
  */
3580
3729
  async processConversation(conv) {
3581
- const { sessionId, refusedSessionId } = await this.ensureSession(conv);
3730
+ const { sessionId, refusedSessionId, created: sessionCreated } = await this.ensureSession(conv);
3582
3731
  const messages = await this.getPendingMessages(conv.id);
3583
3732
  let dispatched = 0;
3584
3733
  let skippedAlreadyDispatched = 0;
@@ -3593,6 +3742,15 @@ var ChannelDriver = class _ChannelDriver {
3593
3742
  skippedAlreadyDispatched += 1;
3594
3743
  continue;
3595
3744
  }
3745
+ if (message.opencode_message_id) {
3746
+ const outcome = await this.resolveRedrive(conv, sessionId, message, sessionCreated);
3747
+ if (outcome === "abandoned") {
3748
+ continue;
3749
+ }
3750
+ if (outcome !== "dispatch") {
3751
+ break;
3752
+ }
3753
+ }
3596
3754
  const options = {
3597
3755
  agent: message.opencode_agent ?? void 0,
3598
3756
  model: message.opencode_model ?? void 0
@@ -3622,6 +3780,7 @@ var ChannelDriver = class _ChannelDriver {
3622
3780
  conversation_id: conv.id,
3623
3781
  message_id: message.id
3624
3782
  });
3783
+ this.signalDispatchNotStarted(conv, message, "session_deleted_race");
3625
3784
  break;
3626
3785
  }
3627
3786
  if (exists === null) {
@@ -3631,6 +3790,7 @@ var ChannelDriver = class _ChannelDriver {
3631
3790
  conversation_id: conv.id,
3632
3791
  message_id: message.id
3633
3792
  });
3793
+ this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
3634
3794
  break;
3635
3795
  }
3636
3796
  const errorMessage = err instanceof Error ? err.message : String(err);
@@ -3649,6 +3809,7 @@ var ChannelDriver = class _ChannelDriver {
3649
3809
  conversation_id: conv.id,
3650
3810
  message_id: message.id
3651
3811
  });
3812
+ this.signalDispatchNotStarted(conv, message, "failure_unreported");
3652
3813
  });
3653
3814
  this.log({
3654
3815
  level: "error",
@@ -3659,14 +3820,40 @@ var ChannelDriver = class _ChannelDriver {
3659
3820
  break;
3660
3821
  }
3661
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.`;
3662
3838
  this.log({
3663
- level: "warn",
3664
- message: `Message ${message.id.slice(0, 8)} dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next tick`,
3839
+ level: "error",
3840
+ message: errorMessage,
3665
3841
  conversation_id: conv.id,
3666
3842
  message_id: message.id
3667
3843
  });
3668
- continue;
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;
3669
3854
  }
3855
+ this.unconfirmedDispatchFailures.delete(message.id);
3856
+ this.dispatchNotStartedSignalled.delete(message.id);
3670
3857
  this.dispatched.add(message.id);
3671
3858
  this.registerInFlight(conv, sessionId, message, opencodeMessageId);
3672
3859
  dispatched += 1;
@@ -3682,6 +3869,451 @@ var ChannelDriver = class _ChannelDriver {
3682
3869
  this.ensureWatcherRunning(sessionId);
3683
3870
  return dispatched;
3684
3871
  }
3872
+ /**
3873
+ * Poll a session's message list for the re-drive fence (#965), via the
3874
+ * INJECTED `fetchImpl` — NOT the imported `getSessionMessages` helper, which
3875
+ * hits the global `fetch` and would bypass the same override every other
3876
+ * opencode poll in this file respects. Mirrors `readoptProcessing`'s own
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).
3886
+ */
3887
+ async pollSessionMessagesForRedrive(conv, message, sessionId) {
3888
+ try {
3889
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
3890
+ if (!res.ok) {
3891
+ const rawBody = await res.text();
3892
+ const normalized = normalizeRedrivePollFailureBody(rawBody);
3893
+ this.log({
3894
+ level: "warn",
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`,
3896
+ conversation_id: conv.id,
3897
+ message_id: message.id
3898
+ });
3899
+ return { ok: false, signature: `HTTP ${res.status}${normalized ? `: ${normalized}` : ""}` };
3900
+ }
3901
+ const body = await res.json();
3902
+ if (!Array.isArray(body)) {
3903
+ this.log({
3904
+ level: "warn",
3905
+ message: `Re-drive: polling session ${sessionId.slice(0, 8)} for message ${message.id.slice(0, 8)} returned a non-array message body \u2014 treating as unreadable this tick`,
3906
+ conversation_id: conv.id,
3907
+ message_id: message.id
3908
+ });
3909
+ return { ok: false, signature: "non-array message body" };
3910
+ }
3911
+ return { ok: true, messages: body };
3912
+ } catch (err) {
3913
+ this.log({
3914
+ level: "warn",
3915
+ message: `Re-drive: failed to poll session ${sessionId.slice(0, 8)} for message ${message.id.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
3916
+ conversation_id: conv.id,
3917
+ message_id: message.id
3918
+ });
3919
+ return { ok: false, signature: null };
3920
+ }
3921
+ }
3922
+ /**
3923
+ * The re-drive fence for a `pending` row that already carries a stored
3924
+ * `opencode_message_id` (#965) — i.e. it has already been handed to opencode at
3925
+ * least once (see the invariant at `QueuedMessage.opencode_message_id`'s doc).
3926
+ * The lifecycle cron can falsely reclaim a `processing` row back to `pending`
3927
+ * mid-turn (a 5-minute liveness-staleness check racing a still-running turn);
3928
+ * without this fence the drain loop would re-`prompt_async` the SAME turn a
3929
+ * second time against live GitHub state. Mirrors `readoptOne`'s job for the
3930
+ * `processing` re-adopt path, but simpler: no b1/b2 preamble cross-check is
3931
+ * needed here because `sessionCreated` already handles the cases (a #553
3932
+ * abandoned session, a #190 vanished one) that path exists for.
3933
+ *
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.
3940
+ */
3941
+ async resolveRedrive(conv, sessionId, message, sessionCreated) {
3942
+ const ocId = message.opencode_message_id ?? null;
3943
+ if (sessionCreated) {
3944
+ this.clearRedriveUnresolved(message.id);
3945
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
3946
+ return "dispatch";
3947
+ }
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) {
3959
+ return this.resolveRedriveUnresolved(conv, message);
3960
+ }
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
+ }
3976
+ if (state === "done" || state === "failed") {
3977
+ return this.settleRedrive(conv, sessionId, message, ocId, messages, state);
3978
+ }
3979
+ if (state === "running" || state === "queued") {
3980
+ const ongoing = await isSessionOngoing(this.port, sessionId);
3981
+ if (ongoing === true) {
3982
+ return this.reattachRedrive(conv, sessionId, message, ocId);
3983
+ }
3984
+ if (ongoing === false) {
3985
+ this.clearRedriveUnresolved(message.id);
3986
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
3987
+ return "dispatch";
3988
+ }
3989
+ return this.resolveRedriveUnresolved(conv, message);
3990
+ }
3991
+ this.clearRedriveUnresolved(message.id);
3992
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
3993
+ return "dispatch";
3994
+ }
3995
+ /**
3996
+ * The `reattached` outcome (Task 3.3): the prior turn is STILL ONGOING per
3997
+ * opencode's own status map — undo the false reclaim instead of starting a
3998
+ * second turn.
3999
+ */
4000
+ async reattachRedrive(conv, sessionId, message, ocId) {
4001
+ let anchorMs;
4002
+ const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
4003
+ if (!Number.isNaN(parsed)) {
4004
+ anchorMs = parsed;
4005
+ } else {
4006
+ anchorMs = this.now();
4007
+ this.log({
4008
+ level: "error",
4009
+ message: `Re-drive: message ${message.id.slice(0, 8)} has null/unparseable processing_started_at (${String(message.processing_started_at)}) \u2014 anchoring the watcher's absolute-age ceiling to now (defensive)`,
4010
+ conversation_id: conv.id,
4011
+ message_id: message.id
4012
+ });
4013
+ }
4014
+ const title = await this.resolveSessionTitle(sessionId, conv.id);
4015
+ try {
4016
+ await this.markProcessing(conv.id, message.id, sessionId, ocId, title);
4017
+ } catch (err) {
4018
+ if (err instanceof ChannelAuthError) throw err;
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";
4036
+ }
4037
+ this.clearRedriveUnresolved(message.id);
4038
+ this.registerReadopted(conv, sessionId, message, ocId ?? "", anchorMs);
4039
+ this.dispatched.add(message.id);
4040
+ this.readopted.add(message.id);
4041
+ this.ensureWatcherRunning(sessionId);
4042
+ const watchedForMs = this.now() - anchorMs;
4043
+ void this.postSignal(conv.id, message.id, "redrive_reattached", {
4044
+ watched_for_ms: watchedForMs
4045
+ });
4046
+ this.log({
4047
+ level: "warn",
4048
+ message: `Re-drive: message ${message.id.slice(0, 8)} (session ${sessionId.slice(0, 8)}) was wrongly reclaimed to pending while its turn was still running (watched ${watchedForMs}ms) \u2014 restored to processing instead of re-dispatching`,
4049
+ conversation_id: conv.id,
4050
+ message_id: message.id
4051
+ });
4052
+ return "reattached";
4053
+ }
4054
+ /**
4055
+ * The `settled` outcome (Task 3.2): the prior turn already finished (or
4056
+ * errored) while nobody was watching — deliver/report it instead of re-running.
4057
+ * Mirrors `readoptOne`'s `done`/`failed` branches' error discipline, simplified
4058
+ * (no `doneUndeliverable` park: a terminal PATCH failure here just retries next
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.
4062
+ */
4063
+ async settleRedrive(conv, sessionId, message, ocId, messages, state) {
4064
+ try {
4065
+ if (state === "done") {
4066
+ const title = await this.resolveSessionTitle(sessionId, conv.id);
4067
+ const usage = messageUsage(messages, ocId ?? "");
4068
+ this.log({
4069
+ level: "info",
4070
+ message: `Re-drive: message ${message.id.slice(0, 8)} completed while its row was wrongly reclaimed to pending \u2014 marking done instead of re-dispatching`,
4071
+ conversation_id: conv.id,
4072
+ message_id: message.id
4073
+ });
4074
+ await this.markDone(conv.id, message.id, sessionId, ocId, title, usage);
4075
+ } else {
4076
+ const error2 = messageError(messages, ocId ?? "") ?? void 0;
4077
+ const usage = messageUsage(messages, ocId ?? "");
4078
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
4079
+ this.log({
4080
+ level: "error",
4081
+ message: `Re-drive: message ${message.id.slice(0, 8)} errored while its row was wrongly reclaimed to pending \u2014 marking failed instead of re-dispatching: ${error2 ?? "(no error text)"}`,
4082
+ conversation_id: conv.id,
4083
+ message_id: message.id
4084
+ });
4085
+ await this.markFailed(conv.id, message.id, sessionId, error2, usage, failure);
4086
+ }
4087
+ } catch (err) {
4088
+ if (err instanceof ChannelAuthError) throw err;
4089
+ this.log({
4090
+ level: "warn",
4091
+ message: `Re-drive: failed to report message ${message.id.slice(0, 8)} ${state} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
4092
+ conversation_id: conv.id,
4093
+ message_id: message.id
4094
+ });
4095
+ const bound = await this.boundRedriveOutcome(conv, message, "settle");
4096
+ return bound === "abandoned" ? "abandoned" : "unresolved";
4097
+ }
4098
+ this.clearRedriveUnresolved(message.id);
4099
+ void this.postSignal(conv.id, message.id, "redrive_settled");
4100
+ return "settled";
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
+ }
4142
+ /**
4143
+ * The bounded `unresolved` outcome (Task 3.4): opencode's state could not be
4144
+ * observed (snapshot unreadable/empty, or `isSessionOngoing` returned `null`).
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.
4151
+ */
4152
+ resolveRedriveUnresolved(conv, message) {
4153
+ const now = this.now();
4154
+ const since = this.redriveUnresolvedSince.get(message.id);
4155
+ if (since !== void 0 && now - since >= this.pausedMaxWaitMs) {
4156
+ this.clearRedriveUnresolved(message.id);
4157
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
4158
+ return "dispatch";
4159
+ }
4160
+ if (since === void 0) {
4161
+ this.redriveUnresolvedSince.set(message.id, now);
4162
+ }
4163
+ if (!this.redriveUnresolvedSignalled.has(message.id)) {
4164
+ this.redriveUnresolvedSignalled.add(message.id);
4165
+ void this.postSignal(conv.id, message.id, "redrive_unresolved");
4166
+ }
4167
+ return "unresolved";
4168
+ }
4169
+ /** Clear all `unresolved`/failure-streak trackers for a row (any non-`unresolved` outcome). */
4170
+ clearRedriveUnresolved(messageId) {
4171
+ this.redriveUnresolvedSince.delete(messageId);
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;
4316
+ }
3685
4317
  /**
3686
4318
  * Record that `sessionId` is no longer a valid binding for `conversationId`
3687
4319
  * (#553). Keyed by conversation and hard-capped, so it cannot grow with the
@@ -3706,6 +4338,13 @@ var ChannelDriver = class _ChannelDriver {
3706
4338
  * `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
3707
4339
  * binding was an id this runner had abandoned, so a resurrection genuinely
3708
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.
3709
4348
  */
3710
4349
  async ensureSession(conv) {
3711
4350
  const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
@@ -3716,7 +4355,11 @@ var ChannelDriver = class _ChannelDriver {
3716
4355
  conversation_id: conv.id
3717
4356
  });
3718
4357
  this.sessions.delete(conv.id);
3719
- return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
4358
+ return {
4359
+ sessionId: await this.createAndBindSession(conv.id),
4360
+ refusedSessionId: bound,
4361
+ created: true
4362
+ };
3720
4363
  }
3721
4364
  if (bound) {
3722
4365
  const exists = await sessionExists(this.port, bound);
@@ -3727,12 +4370,12 @@ var ChannelDriver = class _ChannelDriver {
3727
4370
  conversation_id: conv.id
3728
4371
  });
3729
4372
  this.sessions.delete(conv.id);
3730
- return { sessionId: await this.createAndBindSession(conv.id) };
4373
+ return { sessionId: await this.createAndBindSession(conv.id), created: true };
3731
4374
  }
3732
4375
  this.sessions.set(conv.id, bound);
3733
- return { sessionId: bound };
4376
+ return { sessionId: bound, created: false };
3734
4377
  }
3735
- return { sessionId: await this.createAndBindSession(conv.id) };
4378
+ return { sessionId: await this.createAndBindSession(conv.id), created: true };
3736
4379
  }
3737
4380
  /**
3738
4381
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -3965,9 +4608,10 @@ var ChannelDriver = class _ChannelDriver {
3965
4608
  * opencode reports ACTIVELY `running` is watched to completion (its liveness
3966
4609
  * heartbeat keeps the cron off its row), while a re-adopted turn that is paused
3967
4610
  * awaiting a human — or queued/unreachable — is still bounded by `deadline` and
3968
- * handed to the cron. The old "the `deadline` must settle before the ~15-min
3969
- * cron or they double-drive" reasoning is superseded: liveness now settles the
3970
- * actively-running case; `deadline` settles the rest. `dispatchedAt` stays `now`
4611
+ * handed to the cron. Real invariant (#965): the cron MAY reclaim a row this
4612
+ * runner still holds; a reclaimed row that already ran is never re-dispatched
4613
+ * while opencode reports its turn ongoing (readopt's own gate here, and the
4614
+ * `pending`-row re-drive fence, `resolveRedrive`). `dispatchedAt` stays `now`
3971
4615
  * (only the appear-guard uses it).
3972
4616
  *
3973
4617
  * `evidentMessageId` addresses the SERVER row (for markProcessing/markDone);
@@ -4160,9 +4804,8 @@ var ChannelDriver = class _ChannelDriver {
4160
4804
  const awaitingHuman = observedOpen || latchedPaused;
4161
4805
  if ((state === "running" || state === "done" || state === "failed") && !inFlight.started) {
4162
4806
  const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
4163
- let claimed;
4164
4807
  try {
4165
- claimed = await this.markProcessing(
4808
+ await this.markProcessing(
4166
4809
  conv.id,
4167
4810
  inFlight.evidentMessageId,
4168
4811
  sessionId,
@@ -4171,23 +4814,24 @@ var ChannelDriver = class _ChannelDriver {
4171
4814
  );
4172
4815
  } catch (err) {
4173
4816
  if (err instanceof ChannelAuthError) throw err;
4174
- this.log({
4175
- level: "warn",
4176
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
4177
- conversation_id: conv.id,
4178
- message_id: inFlight.evidentMessageId
4179
- });
4180
- return;
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
+ }
4181
4833
  }
4182
4834
  inFlight.started = true;
4183
- if (!claimed) {
4184
- this.log({
4185
- level: "debug",
4186
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
4187
- conversation_id: conv.id,
4188
- message_id: inFlight.evidentMessageId
4189
- });
4190
- }
4191
4835
  }
4192
4836
  if (state === "done") {
4193
4837
  await this.settleMessageDone(sessionId, watcher, inFlight, messages);
@@ -4527,7 +5171,10 @@ var ChannelDriver = class _ChannelDriver {
4527
5171
  * re-dispatched (at most once, see `forceReadoptRun`):
4528
5172
  * - `done` → `markDone` now (guarded like the watcher's done branch);
4529
5173
  * - `failed` → `markFailed` with the surfaced error (issue #182), so an
4530
- * 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);
4531
5178
  * - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
4532
5179
  * tracking the stored id so the reply correlates by it;
4533
5180
  * - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
@@ -4591,7 +5238,16 @@ var ChannelDriver = class _ChannelDriver {
4591
5238
  void this.postSignal(row.conversation_id, row.id, "readopt_done");
4592
5239
  return;
4593
5240
  }
4594
- if (state === "failed") {
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) {
4595
5251
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
4596
5252
  const usage = messageUsage(messages, ocId ?? "");
4597
5253
  const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
@@ -4805,15 +5461,39 @@ var ChannelDriver = class _ChannelDriver {
4805
5461
  }
4806
5462
  if (ocId === null) {
4807
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
+ }
4808
5487
  this.log({
4809
5488
  level: "warn",
4810
- 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`,
4811
5490
  conversation_id: row.conversation_id,
4812
5491
  message_id: row.id
4813
5492
  });
4814
5493
  void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
4815
5494
  return;
4816
5495
  }
5496
+ this.unconfirmedDispatchFailures.delete(row.id);
4817
5497
  this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
4818
5498
  this.dispatched.add(row.id);
4819
5499
  this.readopted.add(row.id);
@@ -4869,7 +5549,8 @@ var ChannelDriver = class _ChannelDriver {
4869
5549
  opencode_model: row.opencode_model,
4870
5550
  source_message_id: row.source_message_id,
4871
5551
  slack_user_id: row.slack_user_id,
4872
- attachments: row.attachments ?? null
5552
+ attachments: row.attachments ?? null,
5553
+ opencode_message_id: row.opencode_message_id
4873
5554
  };
4874
5555
  }
4875
5556
  /**
@@ -5477,18 +6158,22 @@ var ChannelDriver = class _ChannelDriver {
5477
6158
  * opencode_session_id}` → `notifyMessageStarted` (hourglass→runner swap +
5478
6159
  * deep-linked "View in Evident" notice).
5479
6160
  *
5480
- * Return/throw contract (consumed by the watcher's swap-to-running guard):
5481
- * - returns `true` → the server transitioned the row to processing;
5482
- * - returns `false` → the server gave a DEFINITIVE "already-processing"
5483
- * answer (a non-retryable, non-auth status e.g. a
5484
- * conflict because a duplicate already transitioned it),
5485
- * so the caller treats it as already-started and does NOT
5486
- * retry;
5487
- * - throws `ChannelAuthError` on 401/403 (terminal auth failure);
5488
- * - throws on a TRANSIENT failure (retryable 5xx/429 status, or a
5489
- * network-level error from `fetch`) — i.e. NO definitive server response —
5490
- * so the caller leaves the message un-started and retries the swap on the
5491
- * next tick.
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.
5492
6177
  * A single attempt (no internal retry): the watcher's per-tick loop is the
5493
6178
  * retry vehicle for the swap-to-running.
5494
6179
  */
@@ -5507,11 +6192,11 @@ var ChannelDriver = class _ChannelDriver {
5507
6192
  }
5508
6193
  );
5509
6194
  this.assertAuth(res, "marking message as processing");
5510
- if (res.ok) return true;
6195
+ if (res.ok) return;
5511
6196
  if (isRetryableStatus(res.status)) {
5512
6197
  throw new Error(`marking message as processing: HTTP ${res.status}`);
5513
6198
  }
5514
- return false;
6199
+ throw new ChannelTerminalError(`marking message as processing: HTTP ${res.status}`, res.status);
5515
6200
  }
5516
6201
  /**
5517
6202
  * EXISTING combinedAuth completion route — idempotent (WI-CHAN-2). `PATCH
@@ -5997,6 +6682,32 @@ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
5997
6682
  }
5998
6683
  return { timeoutMs: seconds * 1e3, warnings: [] };
5999
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
+ }
6000
6711
  function meetsThreshold(state, level) {
6001
6712
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
6002
6713
  }
@@ -6121,10 +6832,15 @@ async function handleAuthError(state, error2) {
6121
6832
  }
6122
6833
  async function driveChannels(state, driver) {
6123
6834
  let idlePolls = 0;
6835
+ let idleMs = 0;
6124
6836
  let consecutiveDrainFailures = 0;
6837
+ let unreachableMs = 0;
6125
6838
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
6126
6839
  let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
6127
6840
  while (state.running) {
6841
+ const cycleStartedAtMs = performance.now();
6842
+ let idleThisCycle = false;
6843
+ let unreachableThisCycle = false;
6128
6844
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
6129
6845
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
6130
6846
  if (state.interactive) displayStatus(state);
@@ -6140,17 +6856,22 @@ async function driveChannels(state, driver) {
6140
6856
  try {
6141
6857
  const processed = await driver.drainPending();
6142
6858
  consecutiveDrainFailures = 0;
6859
+ unreachableMs = 0;
6143
6860
  state.messageCount += processed;
6144
6861
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
6145
6862
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
6146
6863
  const appliedFiles = driver.fileSyncActivity().appliedFiles;
6147
- const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
6864
+ const filesApplied = appliedFiles !== lastSeenAppliedFiles;
6865
+ const fileActivity = carriedOverFileSync || filesApplied;
6148
6866
  lastSeenAppliedFiles = appliedFiles;
6867
+ if (filesApplied) state.claudeUsageRearm?.();
6149
6868
  if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
6150
6869
  idlePolls = 0;
6870
+ idleMs = 0;
6151
6871
  if (processed > 0 && state.interactive) displayStatus(state);
6152
6872
  } else if (state.idleTimeout !== null) {
6153
6873
  idlePolls++;
6874
+ idleThisCycle = true;
6154
6875
  if (idlePolls === 1) {
6155
6876
  logActivity(state, {
6156
6877
  type: "info",
@@ -6176,8 +6897,10 @@ async function driveChannels(state, driver) {
6176
6897
  if (state.interactive) displayStatus(state);
6177
6898
  if (driver.hasInFlightWatchers()) {
6178
6899
  consecutiveDrainFailures = 0;
6900
+ unreachableMs = 0;
6179
6901
  } else if (state.idleTimeout !== null) {
6180
6902
  consecutiveDrainFailures++;
6903
+ unreachableThisCycle = true;
6181
6904
  if (consecutiveDrainFailures === 1) {
6182
6905
  logActivity(state, {
6183
6906
  type: "info",
@@ -6188,25 +6911,22 @@ async function driveChannels(state, driver) {
6188
6911
  }
6189
6912
  }
6190
6913
  await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
6191
- if (state.idleTimeout !== null && consecutiveDrainFailures >= 2) {
6192
- const unreachableMs = consecutiveDrainFailures * CHANNEL_POLL_INTERVAL_MS;
6193
- if (unreachableMs > state.idleTimeout * 1e3) {
6194
- logActivity(state, {
6195
- type: "info",
6196
- level: "warn",
6197
- message: `Exiting: could not reach Evident for ${consecutiveDrainFailures} consecutive polls (${Math.round(unreachableMs / 1e3)}s)`
6198
- });
6199
- if (state.interactive) displayStatus(state);
6200
- break;
6201
- }
6914
+ const cycleMs = performance.now() - cycleStartedAtMs;
6915
+ if (idleThisCycle) idleMs += cycleMs;
6916
+ if (unreachableThisCycle) unreachableMs += cycleMs;
6917
+ if (state.idleTimeout !== null && consecutiveDrainFailures >= 2 && unreachableMs > state.idleTimeout * 1e3) {
6918
+ logActivity(state, {
6919
+ type: "info",
6920
+ level: "warn",
6921
+ message: `Exiting: could not reach Evident for ${consecutiveDrainFailures} consecutive polls (${Math.round(unreachableMs / 1e3)}s)`
6922
+ });
6923
+ if (state.interactive) displayStatus(state);
6924
+ break;
6202
6925
  }
6203
- if (state.idleTimeout !== null && idlePolls >= 2) {
6204
- const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
6205
- if (idleMs > state.idleTimeout * 1e3) {
6206
- logActivity(state, { type: "info", message: "Idle timeout reached" });
6207
- if (state.interactive) displayStatus(state);
6208
- break;
6209
- }
6926
+ if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3) {
6927
+ logActivity(state, { type: "info", message: "Idle timeout reached" });
6928
+ if (state.interactive) displayStatus(state);
6929
+ break;
6210
6930
  }
6211
6931
  }
6212
6932
  }
@@ -6285,6 +7005,9 @@ function scheduleSessionCleanup(state, driver, options) {
6285
7005
  );
6286
7006
  state.sessionCleanupTimers.push(interval, firstSweep);
6287
7007
  }
7008
+ function claudeUsageFailureStreakSuffix(consecutiveFailures) {
7009
+ return consecutiveFailures > 1 ? ` (${consecutiveFailures} consecutive failures)` : "";
7010
+ }
6288
7011
  function scheduleClaudeUsageReporting(state, options) {
6289
7012
  const { mode, warnings } = resolveClaudeUsageReportingMode(
6290
7013
  options.claudeUsageReporting,
@@ -6303,13 +7026,26 @@ function scheduleClaudeUsageReporting(state, options) {
6303
7026
  level: "debug",
6304
7027
  message: "Claude usage reporting is off (--claude-usage-reporting off)"
6305
7028
  });
6306
- return;
7029
+ return null;
6307
7030
  }
6308
7031
  let consecutiveFailures = 0;
7032
+ let armed = false;
7033
+ let rearmRequested = false;
6309
7034
  const scheduleNextTick = () => {
7035
+ armed = true;
7036
+ rearmRequested = false;
6310
7037
  state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
6311
7038
  };
6312
- const tick = async (isFirst) => {
7039
+ const rearm = () => {
7040
+ if (armed) {
7041
+ rearmRequested = true;
7042
+ return;
7043
+ }
7044
+ rearmRequested = false;
7045
+ armed = true;
7046
+ state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
7047
+ };
7048
+ const tick = async (isProbe) => {
6313
7049
  try {
6314
7050
  const usage = await getClaudeUsage();
6315
7051
  const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
@@ -6331,8 +7067,8 @@ function scheduleClaudeUsageReporting(state, options) {
6331
7067
  consecutiveFailures++;
6332
7068
  logActivity(state, {
6333
7069
  type: "info",
6334
- level: consecutiveFailures === 1 ? "warn" : "debug",
6335
- message: `Failed to report Claude usage: ${result.error}`
7070
+ level: claudeUsageFailureLogLevel(consecutiveFailures),
7071
+ message: `Failed to report Claude usage: ${result.error}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
6336
7072
  });
6337
7073
  }
6338
7074
  scheduleNextTick();
@@ -6345,12 +7081,14 @@ function scheduleClaudeUsageReporting(state, options) {
6345
7081
  message: "Claude usage reporting is forced on but no usable Claude Code login was found \u2014 run `claude` to sign in; reporting will keep retrying"
6346
7082
  });
6347
7083
  scheduleNextTick();
6348
- } else if (isFirst) {
7084
+ } else if (isProbe) {
6349
7085
  logActivity(state, {
6350
7086
  type: "info",
6351
7087
  level: "debug",
6352
7088
  message: `Claude usage reporting: ${error2.message}`
6353
7089
  });
7090
+ armed = false;
7091
+ if (rearmRequested) rearm();
6354
7092
  } else {
6355
7093
  logActivity(state, {
6356
7094
  type: "info",
@@ -6364,14 +7102,16 @@ function scheduleClaudeUsageReporting(state, options) {
6364
7102
  const message = error2 instanceof Error ? error2.message : String(error2);
6365
7103
  logActivity(state, {
6366
7104
  type: "info",
6367
- level: consecutiveFailures === 1 ? "warn" : "debug",
6368
- message: `Claude usage reporting failed: ${message}`
7105
+ level: claudeUsageFailureLogLevel(consecutiveFailures),
7106
+ message: `Claude usage reporting failed: ${message}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
6369
7107
  });
6370
7108
  scheduleNextTick();
6371
7109
  }
6372
7110
  }
6373
7111
  };
7112
+ armed = true;
6374
7113
  state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
7114
+ return rearm;
6375
7115
  }
6376
7116
  async function notifyOffline(state) {
6377
7117
  if (!state.agentId || !state.authHeader) return;
@@ -6412,6 +7152,7 @@ async function cleanup(state, opts = {}) {
6412
7152
  clearTimeout(state.claudeUsageTimer);
6413
7153
  state.claudeUsageTimer = null;
6414
7154
  }
7155
+ state.claudeUsageRearm = null;
6415
7156
  if (opts.graceful && state.channelDriver) {
6416
7157
  state.channelDriver.stop();
6417
7158
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -6493,6 +7234,7 @@ async function run(options) {
6493
7234
  lastProxiedActivityAt: null,
6494
7235
  sessionCleanupTimers: [],
6495
7236
  claudeUsageTimer: null,
7237
+ claudeUsageRearm: null,
6496
7238
  authHeader: ""
6497
7239
  };
6498
7240
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
@@ -6572,6 +7314,7 @@ async function run(options) {
6572
7314
  console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
6573
7315
  blank();
6574
7316
  process.exit(1);
7317
+ return;
6575
7318
  }
6576
7319
  blank();
6577
7320
  console.log(chalk6.yellow("You are not logged in to Evident."));
@@ -6616,6 +7359,7 @@ async function run(options) {
6616
7359
  } else {
6617
7360
  printError(resolved.error || "Failed to resolve runner ID from key");
6618
7361
  process.exit(1);
7362
+ return;
6619
7363
  }
6620
7364
  } else {
6621
7365
  printError(
@@ -6629,6 +7373,7 @@ async function run(options) {
6629
7373
  );
6630
7374
  blank();
6631
7375
  process.exit(1);
7376
+ return;
6632
7377
  }
6633
7378
  }
6634
7379
  telemetry.info(
@@ -6688,6 +7433,10 @@ async function run(options) {
6688
7433
  for (const warning2 of opencodeStartTimeoutWarnings) {
6689
7434
  logActivity(state, { type: "info", level: "warn", message: warning2 });
6690
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
+ }
6691
7440
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
6692
7441
  try {
6693
7442
  const oc = await ensureOpenCodeRunning({
@@ -6748,6 +7497,7 @@ async function run(options) {
6748
7497
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6749
7498
  fileSyncDirectories,
6750
7499
  homeDir: homedir3(),
7500
+ maxActiveSessions,
6751
7501
  log: (entry) => (
6752
7502
  // Thread the driver's real level straight through so `debug`/`warn`
6753
7503
  // survive the sink filter (they no longer collapse to info). `type`
@@ -6876,7 +7626,7 @@ async function run(options) {
6876
7626
  throw error2;
6877
7627
  }
6878
7628
  scheduleSessionCleanup(state, channelDriver, options);
6879
- scheduleClaudeUsageReporting(state, options);
7629
+ state.claudeUsageRearm = scheduleClaudeUsageReporting(state, options);
6880
7630
  if (!interactive || state.json) {
6881
7631
  log2(state, "Driving channel messages...");
6882
7632
  }
@@ -6948,6 +7698,9 @@ program.command("run").description("Connect to Evident and process messages").op
6948
7698
  ).option(
6949
7699
  "--session-cleanup-max-count <n>",
6950
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"
6951
7704
  ).option(
6952
7705
  "--session-cleanup-interval <duration>",
6953
7706
  "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
@@ -6961,7 +7714,7 @@ program.command("run").description("Connect to Evident and process messages").op
6961
7714
  []
6962
7715
  ).option(
6963
7716
  "--tunnel-ready-file <path>",
6964
- "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
7717
+ "Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
6965
7718
  ).action(
6966
7719
  (options) => {
6967
7720
  run({
@@ -6981,6 +7734,7 @@ program.command("run").description("Connect to Evident and process messages").op
6981
7734
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
6982
7735
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
6983
7736
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
7737
+ maxActiveSessions: options.maxActiveSessions,
6984
7738
  sessionCleanupInterval: options.sessionCleanupInterval,
6985
7739
  // Raw string — the resolver in run.ts single-sources parsing
6986
7740
  // (resolveClaudeUsageReportingMode).