@evident-ai/cli 3.1.1-dev.c826a17 → 3.1.1-dev.ca87eba

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;
@@ -3254,6 +3291,84 @@ var ChannelDriver = class _ChannelDriver {
3254
3291
  * processing list, exactly like `dontRedispatch`/`doneUndeliverable`.
3255
3292
  */
3256
3293
  readoptPollUnresolvedSignalled = /* @__PURE__ */ new Set();
3294
+ /**
3295
+ * "Already emitted `redrive_unresolved` for this row" (#965). Mirrors
3296
+ * `readoptPollUnresolvedSignalled`: `resolveRedrive`'s `unresolved` leaf recurs
3297
+ * every ~2s drain until opencode's status becomes readable, but the
3298
+ * server-visible signal is an OUTCOME, so it fires at most once per row. Cleared
3299
+ * on any non-`unresolved` outcome so the set cannot grow beyond the currently
3300
+ * unresolvable rows.
3301
+ */
3302
+ redriveUnresolvedSignalled = /* @__PURE__ */ new Set();
3303
+ /**
3304
+ * First `now()` a `pending` row's re-drive was observed `unresolved` (#965). A
3305
+ * `pending` row is invisible to every cron arm (all require `status =
3306
+ * 'processing'`), so an indefinitely-`unresolved` row would be stranded with
3307
+ * nothing driving it. Once `now - since >= pausedMaxWaitMs`, `resolveRedrive`
3308
+ * takes `dispatch` instead of `unresolved` (reusing the existing knob — see
3309
+ * ADR-0047's own "unreachable ⇒ bounded" rule). Cleared on any other outcome.
3310
+ */
3311
+ redriveUnresolvedSince = /* @__PURE__ */ new Map();
3312
+ /**
3313
+ * Consecutive-identical-poll-failure streak for the re-drive fence (#1348),
3314
+ * keyed by Evident **message id** (not session) so `clearRedriveUnresolved`
3315
+ * can drop it with the other two trackers and it cannot leak. `sessionId` is
3316
+ * carried inside the entry, not the key: a session change is a different
3317
+ * situation and resets the streak, which gives the `(sessionId, message.id)`
3318
+ * pairing #1348 asks for without a composite map key.
3319
+ */
3320
+ redrivePollFailures = /* @__PURE__ */ new Map();
3321
+ /**
3322
+ * "Already emitted `redrive_outcome_unreported` for THIS (message, outcome)
3323
+ * streak" (Class B, #1340: the runner DECIDED reattach/settle/fail_permanent
3324
+ * but its own PATCH to record it failed — distinct from Class A's
3325
+ * `redrive_poll_failed`, where opencode itself can't be observed). Keyed by
3326
+ * message id, valued by the outcome currently failing to report, so a
3327
+ * change of outcome starts a fresh signal. Cleared by
3328
+ * `clearRedriveUnresolved` the instant either PATCH succeeds.
3329
+ */
3330
+ redriveOutcomeUnreportedSignalled = /* @__PURE__ */ new Map();
3331
+ /**
3332
+ * First `now()` a Class B outcome PATCH (reattach/settle/fail_permanent) was
3333
+ * observed to fail for this message (#1366's failure-window trip arm,
3334
+ * `boundRedriveOutcome`). Duration, not a tick count — bounded by the
3335
+ * existing `pausedMaxWaitMs` window (reusing the knob, not a new constant).
3336
+ * Cleared by `clearRedriveUnresolved` the instant the original PATCH
3337
+ * succeeds.
3338
+ */
3339
+ redriveOutcomeFailingSince = /* @__PURE__ */ new Map();
3340
+ /**
3341
+ * "Already posted `redrive_outcome_abandoned` with `reported: false` for this
3342
+ * row" (#1366) — the bound tripped but the terminal `markFailed` fallback ALSO
3343
+ * failed (the route-level fault of G2), so every following tick re-attempts
3344
+ * the same terminal PATCH. Guards that quiet retry from re-signalling on
3345
+ * every tick. Cleared by `clearRedriveUnresolved`.
3346
+ */
3347
+ redriveOutcomeAbandonedSignalled = /* @__PURE__ */ new Set();
3348
+ /**
3349
+ * "Already emitted `dispatch_not_started` for THIS (message, branch) streak"
3350
+ * (#1340). Valued by the branch currently firing, so a row that moves between
3351
+ * exits re-signals — the move IS the finding. Cleared only on a CONFIRMED
3352
+ * dispatch, never on the fence's decision to dispatch: `clearRedriveUnresolved`
3353
+ * runs on that decision (`resolveRedriveUnresolved`), so clearing there would
3354
+ * re-signal on every one of the 15h of re-dispatch attempts #1110 made.
3355
+ */
3356
+ dispatchNotStartedSignalled = /* @__PURE__ */ new Map();
3357
+ /**
3358
+ * Consecutive-UNCONFIRMED-dispatch streak for a `pending` row with NO stored
3359
+ * `opencode_message_id` yet — i.e. one that has never even reached the
3360
+ * re-drive fence above. `sendPromptAsync`'s POST may 2xx, but its own
3361
+ * read-back retries can never confirm the assigned id when the session's
3362
+ * message list is PERMANENTLY unreadable (e.g. a corrupted local opencode
3363
+ * SQLite DB, #1345/#1348's exact fault, just hit BEFORE the row is ever
3364
+ * dispatched instead of after). Unlike an already-dispatched row, THIS row has
3365
+ * no other safety net at all: the lifecycle cron only reclaims `status =
3366
+ * 'processing'` rows, and a row stuck here never reaches `processing`. Keyed
3367
+ * by message id, carrying `sessionId` so a session change (a fresh one bound
3368
+ * after abandonment) starts a new streak rather than inheriting the old
3369
+ * session's count — same shape as `redrivePollFailures` above.
3370
+ */
3371
+ unconfirmedDispatchFailures = /* @__PURE__ */ new Map();
3257
3372
  /**
3258
3373
  * "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
3259
3374
  * Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
@@ -3578,7 +3693,7 @@ var ChannelDriver = class _ChannelDriver {
3578
3693
  * @returns the count of messages NEWLY dispatched (not already in-flight).
3579
3694
  */
3580
3695
  async processConversation(conv) {
3581
- const { sessionId, refusedSessionId } = await this.ensureSession(conv);
3696
+ const { sessionId, refusedSessionId, created: sessionCreated } = await this.ensureSession(conv);
3582
3697
  const messages = await this.getPendingMessages(conv.id);
3583
3698
  let dispatched = 0;
3584
3699
  let skippedAlreadyDispatched = 0;
@@ -3593,6 +3708,15 @@ var ChannelDriver = class _ChannelDriver {
3593
3708
  skippedAlreadyDispatched += 1;
3594
3709
  continue;
3595
3710
  }
3711
+ if (message.opencode_message_id) {
3712
+ const outcome = await this.resolveRedrive(conv, sessionId, message, sessionCreated);
3713
+ if (outcome === "abandoned") {
3714
+ continue;
3715
+ }
3716
+ if (outcome !== "dispatch") {
3717
+ break;
3718
+ }
3719
+ }
3596
3720
  const options = {
3597
3721
  agent: message.opencode_agent ?? void 0,
3598
3722
  model: message.opencode_model ?? void 0
@@ -3622,6 +3746,7 @@ var ChannelDriver = class _ChannelDriver {
3622
3746
  conversation_id: conv.id,
3623
3747
  message_id: message.id
3624
3748
  });
3749
+ this.signalDispatchNotStarted(conv, message, "session_deleted_race");
3625
3750
  break;
3626
3751
  }
3627
3752
  if (exists === null) {
@@ -3631,6 +3756,7 @@ var ChannelDriver = class _ChannelDriver {
3631
3756
  conversation_id: conv.id,
3632
3757
  message_id: message.id
3633
3758
  });
3759
+ this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
3634
3760
  break;
3635
3761
  }
3636
3762
  const errorMessage = err instanceof Error ? err.message : String(err);
@@ -3649,6 +3775,7 @@ var ChannelDriver = class _ChannelDriver {
3649
3775
  conversation_id: conv.id,
3650
3776
  message_id: message.id
3651
3777
  });
3778
+ this.signalDispatchNotStarted(conv, message, "failure_unreported");
3652
3779
  });
3653
3780
  this.log({
3654
3781
  level: "error",
@@ -3659,14 +3786,40 @@ var ChannelDriver = class _ChannelDriver {
3659
3786
  break;
3660
3787
  }
3661
3788
  if (opencodeMessageId === null) {
3789
+ const streak = this.recordUnconfirmedDispatch(message.id, sessionId);
3790
+ if (streak < MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
3791
+ this.log({
3792
+ level: "warn",
3793
+ 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`,
3794
+ conversation_id: conv.id,
3795
+ message_id: message.id
3796
+ });
3797
+ this.signalDispatchNotStarted(conv, message, "readback_unconfirmed");
3798
+ continue;
3799
+ }
3800
+ this.unconfirmedDispatchFailures.delete(message.id);
3801
+ this.sessions.delete(conv.id);
3802
+ this.supersede(conv.id, sessionId);
3803
+ 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
3804
  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`,
3805
+ level: "error",
3806
+ message: errorMessage,
3665
3807
  conversation_id: conv.id,
3666
3808
  message_id: message.id
3667
3809
  });
3668
- continue;
3810
+ await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
3811
+ this.log({
3812
+ level: "warn",
3813
+ 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)}`,
3814
+ conversation_id: conv.id,
3815
+ message_id: message.id
3816
+ });
3817
+ this.signalDispatchNotStarted(conv, message, "abandon_unreported");
3818
+ });
3819
+ break;
3669
3820
  }
3821
+ this.unconfirmedDispatchFailures.delete(message.id);
3822
+ this.dispatchNotStartedSignalled.delete(message.id);
3670
3823
  this.dispatched.add(message.id);
3671
3824
  this.registerInFlight(conv, sessionId, message, opencodeMessageId);
3672
3825
  dispatched += 1;
@@ -3682,6 +3835,442 @@ var ChannelDriver = class _ChannelDriver {
3682
3835
  this.ensureWatcherRunning(sessionId);
3683
3836
  return dispatched;
3684
3837
  }
3838
+ /**
3839
+ * Poll a session's message list for the re-drive fence (#965), via the
3840
+ * INJECTED `fetchImpl` — NOT the imported `getSessionMessages` helper, which
3841
+ * hits the global `fetch` and would bypass the same override every other
3842
+ * opencode poll in this file respects. Mirrors `readoptProcessing`'s own
3843
+ * snapshot fetch (`:3081-3111`).
3844
+ *
3845
+ * Returns `{ ok: true, messages }` on a readable snapshot, or
3846
+ * `{ ok: false, signature }` on failure — `signature` is a string that
3847
+ * repeats across attempts for the SAME underlying fault (used by the
3848
+ * consecutive-identical-failure bound, #1348), or `null` for a thrown
3849
+ * exception, which is NOT countable toward that bound (a network blip / an
3850
+ * opencode restart also throws identically every tick, and must keep
3851
+ * retrying unbounded rather than ever being treated as permanent).
3852
+ */
3853
+ async pollSessionMessagesForRedrive(conv, message, sessionId) {
3854
+ try {
3855
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
3856
+ if (!res.ok) {
3857
+ const rawBody = await res.text();
3858
+ const normalized = normalizeRedrivePollFailureBody(rawBody);
3859
+ this.log({
3860
+ level: "warn",
3861
+ 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`,
3862
+ conversation_id: conv.id,
3863
+ message_id: message.id
3864
+ });
3865
+ return { ok: false, signature: `HTTP ${res.status}${normalized ? `: ${normalized}` : ""}` };
3866
+ }
3867
+ const body = await res.json();
3868
+ if (!Array.isArray(body)) {
3869
+ this.log({
3870
+ level: "warn",
3871
+ 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`,
3872
+ conversation_id: conv.id,
3873
+ message_id: message.id
3874
+ });
3875
+ return { ok: false, signature: "non-array message body" };
3876
+ }
3877
+ return { ok: true, messages: body };
3878
+ } catch (err) {
3879
+ this.log({
3880
+ level: "warn",
3881
+ 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)}`,
3882
+ conversation_id: conv.id,
3883
+ message_id: message.id
3884
+ });
3885
+ return { ok: false, signature: null };
3886
+ }
3887
+ }
3888
+ /**
3889
+ * The re-drive fence for a `pending` row that already carries a stored
3890
+ * `opencode_message_id` (#965) — i.e. it has already been handed to opencode at
3891
+ * least once (see the invariant at `QueuedMessage.opencode_message_id`'s doc).
3892
+ * The lifecycle cron can falsely reclaim a `processing` row back to `pending`
3893
+ * mid-turn (a 5-minute liveness-staleness check racing a still-running turn);
3894
+ * without this fence the drain loop would re-`prompt_async` the SAME turn a
3895
+ * second time against live GitHub state. Mirrors `readoptOne`'s job for the
3896
+ * `processing` re-adopt path, but simpler: no b1/b2 preamble cross-check is
3897
+ * needed here because `sessionCreated` already handles the cases (a #553
3898
+ * abandoned session, a #190 vanished one) that path exists for.
3899
+ *
3900
+ * Only `ChannelAuthError` propagates. A poll that fails identically
3901
+ * `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row reports the message
3902
+ * failed instead of retrying it (#1348) — SEPARATE from, not a replacement
3903
+ * for, `resolveRedriveUnresolved`'s own `pausedMaxWaitMs` bound below. Every
3904
+ * other failure resolves to `unresolved` and is retried whole on the next
3905
+ * ~2s drain tick.
3906
+ */
3907
+ async resolveRedrive(conv, sessionId, message, sessionCreated) {
3908
+ const ocId = message.opencode_message_id ?? null;
3909
+ if (sessionCreated) {
3910
+ this.clearRedriveUnresolved(message.id);
3911
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
3912
+ return "dispatch";
3913
+ }
3914
+ const polled = await this.pollSessionMessagesForRedrive(conv, message, sessionId);
3915
+ if (!polled.ok) {
3916
+ const streak = this.recordRedrivePollFailure(message.id, sessionId, polled.signature);
3917
+ if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES && polled.signature !== null) {
3918
+ return this.failRedrivePollPermanent(conv, sessionId, message, polled.signature, streak);
3919
+ }
3920
+ return this.resolveRedriveUnresolved(conv, message);
3921
+ }
3922
+ this.redrivePollFailures.delete(message.id);
3923
+ const messages = polled.messages;
3924
+ if (messages.length === 0) {
3925
+ return this.resolveRedriveUnresolved(conv, message);
3926
+ }
3927
+ const state = messageRunState(messages, ocId ?? "");
3928
+ if (state === "failed" && isAbortedTerminalReply(messages, ocId ?? "")) {
3929
+ const ongoing = await isSessionOngoing(this.port, sessionId);
3930
+ if (ongoing === false) {
3931
+ this.log({
3932
+ level: "info",
3933
+ 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`,
3934
+ conversation_id: conv.id,
3935
+ message_id: message.id
3936
+ });
3937
+ this.clearRedriveUnresolved(message.id);
3938
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
3939
+ return "dispatch";
3940
+ }
3941
+ }
3942
+ if (state === "done" || state === "failed") {
3943
+ return this.settleRedrive(conv, sessionId, message, ocId, messages, state);
3944
+ }
3945
+ if (state === "running" || state === "queued") {
3946
+ const ongoing = await isSessionOngoing(this.port, sessionId);
3947
+ if (ongoing === true) {
3948
+ return this.reattachRedrive(conv, sessionId, message, ocId);
3949
+ }
3950
+ if (ongoing === false) {
3951
+ this.clearRedriveUnresolved(message.id);
3952
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
3953
+ return "dispatch";
3954
+ }
3955
+ return this.resolveRedriveUnresolved(conv, message);
3956
+ }
3957
+ this.clearRedriveUnresolved(message.id);
3958
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
3959
+ return "dispatch";
3960
+ }
3961
+ /**
3962
+ * The `reattached` outcome (Task 3.3): the prior turn is STILL ONGOING per
3963
+ * opencode's own status map — undo the false reclaim instead of starting a
3964
+ * second turn.
3965
+ */
3966
+ async reattachRedrive(conv, sessionId, message, ocId) {
3967
+ let anchorMs;
3968
+ const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
3969
+ if (!Number.isNaN(parsed)) {
3970
+ anchorMs = parsed;
3971
+ } else {
3972
+ anchorMs = this.now();
3973
+ this.log({
3974
+ level: "error",
3975
+ 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)`,
3976
+ conversation_id: conv.id,
3977
+ message_id: message.id
3978
+ });
3979
+ }
3980
+ const title = await this.resolveSessionTitle(sessionId, conv.id);
3981
+ try {
3982
+ await this.markProcessing(conv.id, message.id, sessionId, ocId, title);
3983
+ } catch (err) {
3984
+ if (err instanceof ChannelAuthError) throw err;
3985
+ this.log({
3986
+ level: "warn",
3987
+ 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)}`,
3988
+ conversation_id: conv.id,
3989
+ message_id: message.id
3990
+ });
3991
+ const bound = await this.boundRedriveOutcome(conv, message, "reattach");
3992
+ return bound === "abandoned" ? "abandoned" : "unresolved";
3993
+ }
3994
+ this.clearRedriveUnresolved(message.id);
3995
+ this.registerReadopted(conv, sessionId, message, ocId ?? "", anchorMs);
3996
+ this.dispatched.add(message.id);
3997
+ this.readopted.add(message.id);
3998
+ this.ensureWatcherRunning(sessionId);
3999
+ const watchedForMs = this.now() - anchorMs;
4000
+ void this.postSignal(conv.id, message.id, "redrive_reattached", {
4001
+ watched_for_ms: watchedForMs
4002
+ });
4003
+ this.log({
4004
+ level: "warn",
4005
+ 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`,
4006
+ conversation_id: conv.id,
4007
+ message_id: message.id
4008
+ });
4009
+ return "reattached";
4010
+ }
4011
+ /**
4012
+ * The `settled` outcome (Task 3.2): the prior turn already finished (or
4013
+ * errored) while nobody was watching — deliver/report it instead of re-running.
4014
+ * Mirrors `readoptOne`'s `done`/`failed` branches' error discipline, simplified
4015
+ * (no `doneUndeliverable` park: a terminal PATCH failure here just retries next
4016
+ * drain, same as any other non-auth failure). The restart-abort carve-out that
4017
+ * keeps the two in step for `failed` lives in the caller (`resolveRedrive`, #1310),
4018
+ * so a row reaching this `failed` branch is a GENUINE failure.
4019
+ */
4020
+ async settleRedrive(conv, sessionId, message, ocId, messages, state) {
4021
+ try {
4022
+ if (state === "done") {
4023
+ const title = await this.resolveSessionTitle(sessionId, conv.id);
4024
+ const usage = messageUsage(messages, ocId ?? "");
4025
+ this.log({
4026
+ level: "info",
4027
+ 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`,
4028
+ conversation_id: conv.id,
4029
+ message_id: message.id
4030
+ });
4031
+ await this.markDone(conv.id, message.id, sessionId, ocId, title, usage);
4032
+ } else {
4033
+ const error2 = messageError(messages, ocId ?? "") ?? void 0;
4034
+ const usage = messageUsage(messages, ocId ?? "");
4035
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
4036
+ this.log({
4037
+ level: "error",
4038
+ 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)"}`,
4039
+ conversation_id: conv.id,
4040
+ message_id: message.id
4041
+ });
4042
+ await this.markFailed(conv.id, message.id, sessionId, error2, usage, failure);
4043
+ }
4044
+ } catch (err) {
4045
+ if (err instanceof ChannelAuthError) throw err;
4046
+ this.log({
4047
+ level: "warn",
4048
+ message: `Re-drive: failed to report message ${message.id.slice(0, 8)} ${state} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
4049
+ conversation_id: conv.id,
4050
+ message_id: message.id
4051
+ });
4052
+ const bound = await this.boundRedriveOutcome(conv, message, "settle");
4053
+ return bound === "abandoned" ? "abandoned" : "unresolved";
4054
+ }
4055
+ this.clearRedriveUnresolved(message.id);
4056
+ void this.postSignal(conv.id, message.id, "redrive_settled");
4057
+ return "settled";
4058
+ }
4059
+ /**
4060
+ * The permanent-failure outcome (#1348): the fence's own poll of this session
4061
+ * failed with the SAME opencode-answered signature
4062
+ * `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row — a transient blip
4063
+ * would have varied or eventually cleared (see `pollSessionMessagesForRedrive`
4064
+ * and `recordRedrivePollFailure`), so this is a durable fault (e.g. #1345's
4065
+ * corrupted opencode session) rather than something worth retrying forever.
4066
+ * Mirrors `settleRedrive`'s error discipline: no `usage`/`failure` args to
4067
+ * `markFailed` (no opencode snapshot to extract them from — this poll never
4068
+ * got a readable one).
4069
+ */
4070
+ async failRedrivePollPermanent(conv, sessionId, message, signature, streak) {
4071
+ this.log({
4072
+ level: "error",
4073
+ 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`,
4074
+ conversation_id: conv.id,
4075
+ message_id: message.id
4076
+ });
4077
+ try {
4078
+ await this.markFailed(
4079
+ conv.id,
4080
+ message.id,
4081
+ sessionId,
4082
+ `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.`
4083
+ );
4084
+ } catch (err) {
4085
+ if (err instanceof ChannelAuthError) throw err;
4086
+ this.log({
4087
+ level: "warn",
4088
+ 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)}`,
4089
+ conversation_id: conv.id,
4090
+ message_id: message.id
4091
+ });
4092
+ const bound = await this.boundRedriveOutcome(conv, message, "fail_permanent");
4093
+ return bound === "abandoned" ? "abandoned" : "unresolved";
4094
+ }
4095
+ this.clearRedriveUnresolved(message.id);
4096
+ void this.postSignal(conv.id, message.id, "redrive_poll_failed");
4097
+ return "settled";
4098
+ }
4099
+ /**
4100
+ * The bounded `unresolved` outcome (Task 3.4): opencode's state could not be
4101
+ * observed (snapshot unreadable/empty, or `isSessionOngoing` returned `null`).
4102
+ * A `pending` row is swept by the server's own `PENDING_MAX_AGE_MS` (24h,
4103
+ * #1368) cron arm, but that is a day-scale backstop — this local bound acts
4104
+ * in minutes so the row (and the conversation it starves, per the ordering
4105
+ * invariant below) isn't left stranded for that long. Bound to the existing
4106
+ * `pausedMaxWaitMs` window (reusing the knob, not a new constant); takes
4107
+ * `dispatch` once elapsed.
4108
+ */
4109
+ resolveRedriveUnresolved(conv, message) {
4110
+ const now = this.now();
4111
+ const since = this.redriveUnresolvedSince.get(message.id);
4112
+ if (since !== void 0 && now - since >= this.pausedMaxWaitMs) {
4113
+ this.clearRedriveUnresolved(message.id);
4114
+ void this.postSignal(conv.id, message.id, "redrive_redispatched");
4115
+ return "dispatch";
4116
+ }
4117
+ if (since === void 0) {
4118
+ this.redriveUnresolvedSince.set(message.id, now);
4119
+ }
4120
+ if (!this.redriveUnresolvedSignalled.has(message.id)) {
4121
+ this.redriveUnresolvedSignalled.add(message.id);
4122
+ void this.postSignal(conv.id, message.id, "redrive_unresolved");
4123
+ }
4124
+ return "unresolved";
4125
+ }
4126
+ /** Clear all `unresolved`/failure-streak trackers for a row (any non-`unresolved` outcome). */
4127
+ clearRedriveUnresolved(messageId) {
4128
+ this.redriveUnresolvedSince.delete(messageId);
4129
+ this.redriveUnresolvedSignalled.delete(messageId);
4130
+ this.redrivePollFailures.delete(messageId);
4131
+ this.redriveOutcomeUnreportedSignalled.delete(messageId);
4132
+ this.redriveOutcomeFailingSince.delete(messageId);
4133
+ this.redriveOutcomeAbandonedSignalled.delete(messageId);
4134
+ }
4135
+ /**
4136
+ * #1340: the dispatch loop reached a message and did NOT start a turn. Fires at
4137
+ * most once per (message, branch) streak — a wedged row is re-tried every tick,
4138
+ * and the per-tick count is already carried by the co-occurring
4139
+ * `redrive_unresolved`/`redrive_redispatched` signals.
4140
+ */
4141
+ signalDispatchNotStarted(conv, message, branch) {
4142
+ if (this.dispatchNotStartedSignalled.get(message.id) === branch) return;
4143
+ this.dispatchNotStartedSignalled.set(message.id, branch);
4144
+ void this.postSignal(conv.id, message.id, "dispatch_not_started", { branch });
4145
+ }
4146
+ /**
4147
+ * Class B (#1340): the runner DECIDED an outcome (reattach/settle/fail_permanent)
4148
+ * but its own PATCH to record it failed. Fires at most once per (message,
4149
+ * outcome) streak, and only while `boundRedriveOutcome` has not yet tripped —
4150
+ * once it trips, `redrive_outcome_abandoned` takes over reporting for the row
4151
+ * (#1366).
4152
+ */
4153
+ signalRedriveOutcomeUnreported(conv, message, outcome) {
4154
+ if (this.redriveOutcomeUnreportedSignalled.get(message.id) === outcome) return;
4155
+ this.redriveOutcomeUnreportedSignalled.set(message.id, outcome);
4156
+ void this.postSignal(conv.id, message.id, "redrive_outcome_unreported", {
4157
+ attempted_outcome: outcome
4158
+ });
4159
+ }
4160
+ /**
4161
+ * The runner-authored, honest error text for the terminal fallback a tripped
4162
+ * `boundRedriveOutcome` sends. Distinguishable per outcome and truthful about
4163
+ * what actually happened — the `settle`/done case must say the turn finished
4164
+ * but its result could not be recorded, never that the runner stopped
4165
+ * responding (that would be a lie for this shape, see #1366's "why this ships").
4166
+ */
4167
+ static REDRIVE_ABANDON_ERROR = {
4168
+ reattach: "your runner could not record that this message had started, so it was given up on",
4169
+ settle: "your runner finished this message but could not record the result, so the reply could not be delivered",
4170
+ 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"
4171
+ };
4172
+ /**
4173
+ * Bound for Class B (#1340, #1366): the runner DECIDED an outcome but its own
4174
+ * PATCH to record it failed. Two independent trip arms (either sufficient):
4175
+ * (1) this failure streak has lasted `pausedMaxWaitMs` — DURATION, not a tick
4176
+ * count, reusing the knob `resolveRedriveUnresolved` already established; (2)
4177
+ * the turn's `processing_started_at` age has crossed
4178
+ * `ABSOLUTE_MAX_PROCESSING_MS` — durable and restart-surviving, since arm (1)'s
4179
+ * in-memory streak resets on a scale-to-zero restart.
4180
+ *
4181
+ * INVARIANT — a tripped bound never suppresses the original outcome attempt;
4182
+ * it only adds a fallback after that attempt has failed again. This is only
4183
+ * ever reached from inside the catch of the ORIGINAL outcome PATCH, which is
4184
+ * attempted first on every tick whether or not this bound tripped before —
4185
+ * there is no give-up latch that would short-circuit it. That is what lets a
4186
+ * route-level fault that heals later still deliver the turn's real
4187
+ * `done`/`failed` payload: once the original PATCH succeeds again, this
4188
+ * helper is never entered and the row settles with its real result.
4189
+ */
4190
+ async boundRedriveOutcome(conv, message, outcome) {
4191
+ const now = this.now();
4192
+ const since = this.redriveOutcomeFailingSince.get(message.id);
4193
+ if (since === void 0) this.redriveOutcomeFailingSince.set(message.id, now);
4194
+ const durationTripped = now - (since ?? now) >= this.pausedMaxWaitMs;
4195
+ const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
4196
+ const absoluteAgeTripped = !Number.isNaN(parsed) && now - parsed >= ABSOLUTE_MAX_PROCESSING_MS;
4197
+ if (!durationTripped && !absoluteAgeTripped) {
4198
+ this.signalRedriveOutcomeUnreported(conv, message, outcome);
4199
+ return "retry";
4200
+ }
4201
+ const arm = durationTripped ? "failure_window" : "absolute_age";
4202
+ try {
4203
+ await this.markFailed(
4204
+ conv.id,
4205
+ message.id,
4206
+ void 0,
4207
+ _ChannelDriver.REDRIVE_ABANDON_ERROR[outcome]
4208
+ );
4209
+ } catch (err) {
4210
+ if (err instanceof ChannelAuthError) throw err;
4211
+ this.log({
4212
+ level: "warn",
4213
+ 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)}`,
4214
+ conversation_id: conv.id,
4215
+ message_id: message.id
4216
+ });
4217
+ if (!this.redriveOutcomeAbandonedSignalled.has(message.id)) {
4218
+ this.redriveOutcomeAbandonedSignalled.add(message.id);
4219
+ void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
4220
+ attempted_outcome: outcome,
4221
+ reported: false,
4222
+ arm
4223
+ });
4224
+ }
4225
+ return "retry";
4226
+ }
4227
+ this.clearRedriveUnresolved(message.id);
4228
+ void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
4229
+ attempted_outcome: outcome,
4230
+ reported: true,
4231
+ arm
4232
+ });
4233
+ return "abandoned";
4234
+ }
4235
+ /**
4236
+ * Record one poll outcome toward the re-drive fence's consecutive-identical-
4237
+ * failure streak (#1348) and return the resulting count. `signature === null`
4238
+ * (a thrown exception, H1) always clears the streak and returns `0` — it is
4239
+ * never countable. Otherwise the streak continues only when BOTH the session
4240
+ * and the signature match the previous failure; anything else (a different
4241
+ * session, or the same session failing a DIFFERENT way) starts a fresh streak
4242
+ * at `1`.
4243
+ */
4244
+ recordRedrivePollFailure(messageId, sessionId, signature) {
4245
+ if (signature === null) {
4246
+ this.redrivePollFailures.delete(messageId);
4247
+ return 0;
4248
+ }
4249
+ const existing = this.redrivePollFailures.get(messageId);
4250
+ if (existing && existing.sessionId === sessionId && existing.signature === signature) {
4251
+ existing.count += 1;
4252
+ return existing.count;
4253
+ }
4254
+ this.redrivePollFailures.set(messageId, { sessionId, signature, count: 1 });
4255
+ return 1;
4256
+ }
4257
+ /**
4258
+ * Record one UNCONFIRMED-dispatch outcome (a `pending` row with no stored
4259
+ * `opencode_message_id` whose `sendPromptAsync` returned `null`) toward the
4260
+ * bound in `processConversation`'s dispatch loop, and return the resulting
4261
+ * count. Mirrors `recordRedrivePollFailure`'s session-scoping: a session
4262
+ * change starts a fresh streak at `1` rather than inheriting the old one's
4263
+ * count, since a new session is a genuinely different attempt.
4264
+ */
4265
+ recordUnconfirmedDispatch(messageId, sessionId) {
4266
+ const existing = this.unconfirmedDispatchFailures.get(messageId);
4267
+ if (existing && existing.sessionId === sessionId) {
4268
+ existing.count += 1;
4269
+ return existing.count;
4270
+ }
4271
+ this.unconfirmedDispatchFailures.set(messageId, { sessionId, count: 1 });
4272
+ return 1;
4273
+ }
3685
4274
  /**
3686
4275
  * Record that `sessionId` is no longer a valid binding for `conversationId`
3687
4276
  * (#553). Keyed by conversation and hard-capped, so it cannot grow with the
@@ -3706,6 +4295,13 @@ var ChannelDriver = class _ChannelDriver {
3706
4295
  * `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
3707
4296
  * binding was an id this runner had abandoned, so a resurrection genuinely
3708
4297
  * happened and a fresh session was bound instead. The caller reports it.
4298
+ *
4299
+ * `created` says the returned session was made JUST NOW, so it provably holds
4300
+ * no prior turn. The re-drive fence needs that as CONTRARY evidence ("nothing
4301
+ * to reconcile against") — distinct from the ambiguous "I polled and saw an
4302
+ * empty transcript", which stays a deferral. Keep it separate from
4303
+ * `refusedSessionId`: only the latter means a #553 resurrection happened, and
4304
+ * only it may drive the `session_superseded` signal.
3709
4305
  */
3710
4306
  async ensureSession(conv) {
3711
4307
  const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
@@ -3716,7 +4312,11 @@ var ChannelDriver = class _ChannelDriver {
3716
4312
  conversation_id: conv.id
3717
4313
  });
3718
4314
  this.sessions.delete(conv.id);
3719
- return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
4315
+ return {
4316
+ sessionId: await this.createAndBindSession(conv.id),
4317
+ refusedSessionId: bound,
4318
+ created: true
4319
+ };
3720
4320
  }
3721
4321
  if (bound) {
3722
4322
  const exists = await sessionExists(this.port, bound);
@@ -3727,12 +4327,12 @@ var ChannelDriver = class _ChannelDriver {
3727
4327
  conversation_id: conv.id
3728
4328
  });
3729
4329
  this.sessions.delete(conv.id);
3730
- return { sessionId: await this.createAndBindSession(conv.id) };
4330
+ return { sessionId: await this.createAndBindSession(conv.id), created: true };
3731
4331
  }
3732
4332
  this.sessions.set(conv.id, bound);
3733
- return { sessionId: bound };
4333
+ return { sessionId: bound, created: false };
3734
4334
  }
3735
- return { sessionId: await this.createAndBindSession(conv.id) };
4335
+ return { sessionId: await this.createAndBindSession(conv.id), created: true };
3736
4336
  }
3737
4337
  /**
3738
4338
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -3965,9 +4565,10 @@ var ChannelDriver = class _ChannelDriver {
3965
4565
  * opencode reports ACTIVELY `running` is watched to completion (its liveness
3966
4566
  * heartbeat keeps the cron off its row), while a re-adopted turn that is paused
3967
4567
  * 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`
4568
+ * handed to the cron. Real invariant (#965): the cron MAY reclaim a row this
4569
+ * runner still holds; a reclaimed row that already ran is never re-dispatched
4570
+ * while opencode reports its turn ongoing (readopt's own gate here, and the
4571
+ * `pending`-row re-drive fence, `resolveRedrive`). `dispatchedAt` stays `now`
3971
4572
  * (only the appear-guard uses it).
3972
4573
  *
3973
4574
  * `evidentMessageId` addresses the SERVER row (for markProcessing/markDone);
@@ -4527,7 +5128,10 @@ var ChannelDriver = class _ChannelDriver {
4527
5128
  * re-dispatched (at most once, see `forceReadoptRun`):
4528
5129
  * - `done` → `markDone` now (guarded like the watcher's done branch);
4529
5130
  * - `failed` → `markFailed` with the surfaced error (issue #182), so an
4530
- * errored turn is reported failed on restart, NOT re-dispatched;
5131
+ * errored turn is reported failed on restart, NOT re-dispatched
5132
+ * EXCEPT a restart-ABORTED turn under a not-ongoing session,
5133
+ * which is a restart orphan wearing a terminal error and is
5134
+ * re-dispatched instead (issue #1310, see the branch below);
4531
5135
  * - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
4532
5136
  * tracking the stored id so the reply correlates by it;
4533
5137
  * - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
@@ -4591,7 +5195,16 @@ var ChannelDriver = class _ChannelDriver {
4591
5195
  void this.postSignal(row.conversation_id, row.id, "readopt_done");
4592
5196
  return;
4593
5197
  }
4594
- if (state === "failed") {
5198
+ const restartAborted = state === "failed" && sessionOngoing === false && isAbortedTerminalReply(messages, ocId ?? "");
5199
+ if (restartAborted) {
5200
+ this.log({
5201
+ level: "info",
5202
+ 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`,
5203
+ conversation_id: row.conversation_id,
5204
+ message_id: row.id
5205
+ });
5206
+ }
5207
+ if (state === "failed" && !restartAborted) {
4595
5208
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
4596
5209
  const usage = messageUsage(messages, ocId ?? "");
4597
5210
  const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
@@ -4805,15 +5418,39 @@ var ChannelDriver = class _ChannelDriver {
4805
5418
  }
4806
5419
  if (ocId === null) {
4807
5420
  this.awaitingReadopt.delete(row.id);
5421
+ const streak = this.recordUnconfirmedDispatch(row.id, sessionId);
5422
+ if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
5423
+ this.unconfirmedDispatchFailures.delete(row.id);
5424
+ this.sessions.delete(readoptConv.id);
5425
+ this.supersede(readoptConv.id, sessionId);
5426
+ 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.`;
5427
+ this.log({
5428
+ level: "error",
5429
+ message: errorMessage,
5430
+ conversation_id: row.conversation_id,
5431
+ message_id: row.id
5432
+ });
5433
+ await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
5434
+ this.log({
5435
+ level: "warn",
5436
+ 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)}`,
5437
+ conversation_id: row.conversation_id,
5438
+ message_id: row.id
5439
+ });
5440
+ });
5441
+ void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
5442
+ return;
5443
+ }
4808
5444
  this.log({
4809
5445
  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`,
5446
+ 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
5447
  conversation_id: row.conversation_id,
4812
5448
  message_id: row.id
4813
5449
  });
4814
5450
  void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
4815
5451
  return;
4816
5452
  }
5453
+ this.unconfirmedDispatchFailures.delete(row.id);
4817
5454
  this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
4818
5455
  this.dispatched.add(row.id);
4819
5456
  this.readopted.add(row.id);
@@ -4869,7 +5506,8 @@ var ChannelDriver = class _ChannelDriver {
4869
5506
  opencode_model: row.opencode_model,
4870
5507
  source_message_id: row.source_message_id,
4871
5508
  slack_user_id: row.slack_user_id,
4872
- attachments: row.attachments ?? null
5509
+ attachments: row.attachments ?? null,
5510
+ opencode_message_id: row.opencode_message_id
4873
5511
  };
4874
5512
  }
4875
5513
  /**
@@ -6121,10 +6759,15 @@ async function handleAuthError(state, error2) {
6121
6759
  }
6122
6760
  async function driveChannels(state, driver) {
6123
6761
  let idlePolls = 0;
6762
+ let idleMs = 0;
6124
6763
  let consecutiveDrainFailures = 0;
6764
+ let unreachableMs = 0;
6125
6765
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
6126
6766
  let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
6127
6767
  while (state.running) {
6768
+ const cycleStartedAtMs = performance.now();
6769
+ let idleThisCycle = false;
6770
+ let unreachableThisCycle = false;
6128
6771
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
6129
6772
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
6130
6773
  if (state.interactive) displayStatus(state);
@@ -6140,17 +6783,22 @@ async function driveChannels(state, driver) {
6140
6783
  try {
6141
6784
  const processed = await driver.drainPending();
6142
6785
  consecutiveDrainFailures = 0;
6786
+ unreachableMs = 0;
6143
6787
  state.messageCount += processed;
6144
6788
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
6145
6789
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
6146
6790
  const appliedFiles = driver.fileSyncActivity().appliedFiles;
6147
- const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
6791
+ const filesApplied = appliedFiles !== lastSeenAppliedFiles;
6792
+ const fileActivity = carriedOverFileSync || filesApplied;
6148
6793
  lastSeenAppliedFiles = appliedFiles;
6794
+ if (filesApplied) state.claudeUsageRearm?.();
6149
6795
  if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
6150
6796
  idlePolls = 0;
6797
+ idleMs = 0;
6151
6798
  if (processed > 0 && state.interactive) displayStatus(state);
6152
6799
  } else if (state.idleTimeout !== null) {
6153
6800
  idlePolls++;
6801
+ idleThisCycle = true;
6154
6802
  if (idlePolls === 1) {
6155
6803
  logActivity(state, {
6156
6804
  type: "info",
@@ -6176,8 +6824,10 @@ async function driveChannels(state, driver) {
6176
6824
  if (state.interactive) displayStatus(state);
6177
6825
  if (driver.hasInFlightWatchers()) {
6178
6826
  consecutiveDrainFailures = 0;
6827
+ unreachableMs = 0;
6179
6828
  } else if (state.idleTimeout !== null) {
6180
6829
  consecutiveDrainFailures++;
6830
+ unreachableThisCycle = true;
6181
6831
  if (consecutiveDrainFailures === 1) {
6182
6832
  logActivity(state, {
6183
6833
  type: "info",
@@ -6188,25 +6838,22 @@ async function driveChannels(state, driver) {
6188
6838
  }
6189
6839
  }
6190
6840
  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
- }
6841
+ const cycleMs = performance.now() - cycleStartedAtMs;
6842
+ if (idleThisCycle) idleMs += cycleMs;
6843
+ if (unreachableThisCycle) unreachableMs += cycleMs;
6844
+ if (state.idleTimeout !== null && consecutiveDrainFailures >= 2 && unreachableMs > state.idleTimeout * 1e3) {
6845
+ logActivity(state, {
6846
+ type: "info",
6847
+ level: "warn",
6848
+ message: `Exiting: could not reach Evident for ${consecutiveDrainFailures} consecutive polls (${Math.round(unreachableMs / 1e3)}s)`
6849
+ });
6850
+ if (state.interactive) displayStatus(state);
6851
+ break;
6202
6852
  }
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
- }
6853
+ if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3) {
6854
+ logActivity(state, { type: "info", message: "Idle timeout reached" });
6855
+ if (state.interactive) displayStatus(state);
6856
+ break;
6210
6857
  }
6211
6858
  }
6212
6859
  }
@@ -6285,6 +6932,9 @@ function scheduleSessionCleanup(state, driver, options) {
6285
6932
  );
6286
6933
  state.sessionCleanupTimers.push(interval, firstSweep);
6287
6934
  }
6935
+ function claudeUsageFailureStreakSuffix(consecutiveFailures) {
6936
+ return consecutiveFailures > 1 ? ` (${consecutiveFailures} consecutive failures)` : "";
6937
+ }
6288
6938
  function scheduleClaudeUsageReporting(state, options) {
6289
6939
  const { mode, warnings } = resolveClaudeUsageReportingMode(
6290
6940
  options.claudeUsageReporting,
@@ -6303,13 +6953,26 @@ function scheduleClaudeUsageReporting(state, options) {
6303
6953
  level: "debug",
6304
6954
  message: "Claude usage reporting is off (--claude-usage-reporting off)"
6305
6955
  });
6306
- return;
6956
+ return null;
6307
6957
  }
6308
6958
  let consecutiveFailures = 0;
6959
+ let armed = false;
6960
+ let rearmRequested = false;
6309
6961
  const scheduleNextTick = () => {
6962
+ armed = true;
6963
+ rearmRequested = false;
6310
6964
  state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
6311
6965
  };
6312
- const tick = async (isFirst) => {
6966
+ const rearm = () => {
6967
+ if (armed) {
6968
+ rearmRequested = true;
6969
+ return;
6970
+ }
6971
+ rearmRequested = false;
6972
+ armed = true;
6973
+ state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
6974
+ };
6975
+ const tick = async (isProbe) => {
6313
6976
  try {
6314
6977
  const usage = await getClaudeUsage();
6315
6978
  const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
@@ -6331,8 +6994,8 @@ function scheduleClaudeUsageReporting(state, options) {
6331
6994
  consecutiveFailures++;
6332
6995
  logActivity(state, {
6333
6996
  type: "info",
6334
- level: consecutiveFailures === 1 ? "warn" : "debug",
6335
- message: `Failed to report Claude usage: ${result.error}`
6997
+ level: claudeUsageFailureLogLevel(consecutiveFailures),
6998
+ message: `Failed to report Claude usage: ${result.error}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
6336
6999
  });
6337
7000
  }
6338
7001
  scheduleNextTick();
@@ -6345,12 +7008,14 @@ function scheduleClaudeUsageReporting(state, options) {
6345
7008
  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
7009
  });
6347
7010
  scheduleNextTick();
6348
- } else if (isFirst) {
7011
+ } else if (isProbe) {
6349
7012
  logActivity(state, {
6350
7013
  type: "info",
6351
7014
  level: "debug",
6352
7015
  message: `Claude usage reporting: ${error2.message}`
6353
7016
  });
7017
+ armed = false;
7018
+ if (rearmRequested) rearm();
6354
7019
  } else {
6355
7020
  logActivity(state, {
6356
7021
  type: "info",
@@ -6364,14 +7029,16 @@ function scheduleClaudeUsageReporting(state, options) {
6364
7029
  const message = error2 instanceof Error ? error2.message : String(error2);
6365
7030
  logActivity(state, {
6366
7031
  type: "info",
6367
- level: consecutiveFailures === 1 ? "warn" : "debug",
6368
- message: `Claude usage reporting failed: ${message}`
7032
+ level: claudeUsageFailureLogLevel(consecutiveFailures),
7033
+ message: `Claude usage reporting failed: ${message}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
6369
7034
  });
6370
7035
  scheduleNextTick();
6371
7036
  }
6372
7037
  }
6373
7038
  };
7039
+ armed = true;
6374
7040
  state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
7041
+ return rearm;
6375
7042
  }
6376
7043
  async function notifyOffline(state) {
6377
7044
  if (!state.agentId || !state.authHeader) return;
@@ -6412,6 +7079,7 @@ async function cleanup(state, opts = {}) {
6412
7079
  clearTimeout(state.claudeUsageTimer);
6413
7080
  state.claudeUsageTimer = null;
6414
7081
  }
7082
+ state.claudeUsageRearm = null;
6415
7083
  if (opts.graceful && state.channelDriver) {
6416
7084
  state.channelDriver.stop();
6417
7085
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -6493,6 +7161,7 @@ async function run(options) {
6493
7161
  lastProxiedActivityAt: null,
6494
7162
  sessionCleanupTimers: [],
6495
7163
  claudeUsageTimer: null,
7164
+ claudeUsageRearm: null,
6496
7165
  authHeader: ""
6497
7166
  };
6498
7167
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
@@ -6572,6 +7241,7 @@ async function run(options) {
6572
7241
  console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
6573
7242
  blank();
6574
7243
  process.exit(1);
7244
+ return;
6575
7245
  }
6576
7246
  blank();
6577
7247
  console.log(chalk6.yellow("You are not logged in to Evident."));
@@ -6616,6 +7286,7 @@ async function run(options) {
6616
7286
  } else {
6617
7287
  printError(resolved.error || "Failed to resolve runner ID from key");
6618
7288
  process.exit(1);
7289
+ return;
6619
7290
  }
6620
7291
  } else {
6621
7292
  printError(
@@ -6629,6 +7300,7 @@ async function run(options) {
6629
7300
  );
6630
7301
  blank();
6631
7302
  process.exit(1);
7303
+ return;
6632
7304
  }
6633
7305
  }
6634
7306
  telemetry.info(
@@ -6876,7 +7548,7 @@ async function run(options) {
6876
7548
  throw error2;
6877
7549
  }
6878
7550
  scheduleSessionCleanup(state, channelDriver, options);
6879
- scheduleClaudeUsageReporting(state, options);
7551
+ state.claudeUsageRearm = scheduleClaudeUsageReporting(state, options);
6880
7552
  if (!interactive || state.json) {
6881
7553
  log2(state, "Driving channel messages...");
6882
7554
  }
@@ -6961,7 +7633,7 @@ program.command("run").description("Connect to Evident and process messages").op
6961
7633
  []
6962
7634
  ).option(
6963
7635
  "--tunnel-ready-file <path>",
6964
- "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
7636
+ "Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
6965
7637
  ).action(
6966
7638
  (options) => {
6967
7639
  run({