@evident-ai/cli 3.1.1-dev.4159d3a → 3.1.1-dev.504d05d

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
@@ -499,6 +499,12 @@ function log(level, event, fields) {
499
499
  );
500
500
  }
501
501
  }
502
+ function errorFields(err) {
503
+ if (err instanceof Error) {
504
+ return { error: err.message, error_name: err.name };
505
+ }
506
+ return { error: String(err) };
507
+ }
502
508
  function stripQuery(url) {
503
509
  try {
504
510
  return new URL(url).pathname;
@@ -1267,6 +1273,16 @@ async function buildFileParts(attachments, capable) {
1267
1273
  );
1268
1274
  dataUrl = null;
1269
1275
  }
1276
+ if (dataUrl !== null && typeof dataUrl === "object") {
1277
+ outcomes.push({
1278
+ index: a.index,
1279
+ mime: a.mime,
1280
+ filename: a.filename,
1281
+ status: "failed",
1282
+ reason: "needs_reauth"
1283
+ });
1284
+ continue;
1285
+ }
1270
1286
  if (dataUrl == null) {
1271
1287
  outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
1272
1288
  continue;
@@ -1684,10 +1700,11 @@ var StreamForwarder = class {
1684
1700
  * Abort every in-flight stream (e.g. on WebSocket close).
1685
1701
  */
1686
1702
  abortAll() {
1687
- for (const stream of this.inflight.values()) {
1703
+ for (const [sid, stream] of this.inflight.entries()) {
1688
1704
  try {
1689
1705
  stream.abort();
1690
- } catch {
1706
+ } catch (err) {
1707
+ log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
1691
1708
  }
1692
1709
  }
1693
1710
  this.inflight.clear();
@@ -1960,7 +1977,11 @@ var RunnerConnection = class {
1960
1977
  if (this.connection) {
1961
1978
  try {
1962
1979
  this.connection.close();
1963
- } catch {
1980
+ } catch (err) {
1981
+ log("error", "runner_connection_close_failed", {
1982
+ agent_id: this.resolvedAgentId,
1983
+ ...errorFields(err)
1984
+ });
1964
1985
  }
1965
1986
  this.connection = null;
1966
1987
  }
@@ -2041,6 +2062,7 @@ var DEFAULT_STUCK_QUEUED_MS = 6e4;
2041
2062
  var HEARTBEAT_MS = 6e4;
2042
2063
  var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
2043
2064
  var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
2065
+ var MAX_SUPERSEDED_CONVERSATIONS = 256;
2044
2066
  var ChannelAuthError = class extends Error {
2045
2067
  constructor(message) {
2046
2068
  super(message);
@@ -2063,7 +2085,7 @@ function backoffDelay(attempt, policy) {
2063
2085
  function isRetryableStatus(status) {
2064
2086
  return status === 429 || status >= 500 && status <= 599;
2065
2087
  }
2066
- var ChannelDriver = class {
2088
+ var ChannelDriver = class _ChannelDriver {
2067
2089
  agentId;
2068
2090
  port;
2069
2091
  apiUrl;
@@ -2079,6 +2101,34 @@ var ChannelDriver = class {
2079
2101
  now;
2080
2102
  /** Cache of conversationId → opencode sessionId. */
2081
2103
  sessions = /* @__PURE__ */ new Map();
2104
+ /**
2105
+ * conversationId → the opencode session this runner has ABANDONED as that
2106
+ * conversation's binding (#553), after a genuine (`sessionExists === true`)
2107
+ * dispatch failure: the session still exists but is wedged, so #485's self-heal
2108
+ * must bind a fresh one.
2109
+ *
2110
+ * Dropping the local binding + clearing the server row is not enough on its own:
2111
+ * a SIBLING message dispatched earlier in the same drain is still in-flight under
2112
+ * the same session, and its watcher's routine status writes carry
2113
+ * `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
2114
+ * and `ensureSession`'s persisted-id fallback then reuses it, defeating the
2115
+ * self-heal. This map makes the runner authoritative instead of racing those
2116
+ * writes: *`ensureSession` never reuses an abandoned id for that conversation,
2117
+ * whatever the server row says* — which holds even when the resurrecting write
2118
+ * is one we deliberately keep (see `markDone`).
2119
+ *
2120
+ * Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
2121
+ * one conversation hold ONE entry (the newest abandonment replaces the older), and
2122
+ * hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
2123
+ * NEWEST abandoned id per conversation is guarded: after a second abandonment a
2124
+ * late sibling of the FIRST session can write that id back and `ensureSession`
2125
+ * will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
2126
+ * NOT dropped when the session's watcher tears down: `markDone` still writes the
2127
+ * abandoned id back (it must, or the reply is lost), so the guard has to outlive
2128
+ * the turn that resurrects it. In-memory only — a restart forgets it, at the same
2129
+ * bounded cost.
2130
+ */
2131
+ supersededSessions = /* @__PURE__ */ new Map();
2082
2132
  /**
2083
2133
  * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
2084
2134
  * longer idempotent (no caller-supplied `messageID`), and its read-back picks
@@ -2188,9 +2238,12 @@ var ChannelDriver = class {
2188
2238
  sessionParents = /* @__PURE__ */ new Map();
2189
2239
  /**
2190
2240
  * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2191
- * NON-EMPTY name is stored (terminal — a real session name won't later un-name),
2192
- * so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
2193
- * resolved OR resolved-but-still-empty re-fetch on next need, since OpenCode
2241
+ * NON-EMPTY, non-placeholder name is stored (terminal — a real session name
2242
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
2243
+ * excludes OpenCode's synchronous default title (see
2244
+ * `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
2245
+ * as an empty title so it never latches. A missing entry = not yet resolved OR
2246
+ * resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
2194
2247
  * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2195
2248
  * the watcher completion path AND the restart-recovery re-adopt path (which has
2196
2249
  * no watcher) can resolve the title.
@@ -2384,10 +2437,15 @@ var ChannelDriver = class {
2384
2437
  * @returns the count of messages NEWLY dispatched (not already in-flight).
2385
2438
  */
2386
2439
  async processConversation(conv) {
2387
- const sessionId = await this.ensureSession(conv);
2440
+ const { sessionId, refusedSessionId } = await this.ensureSession(conv);
2388
2441
  const messages = await this.getPendingMessages(conv.id);
2389
2442
  let dispatched = 0;
2390
2443
  let skippedAlreadyDispatched = 0;
2444
+ if (refusedSessionId && messages.length > 0) {
2445
+ void this.postSignal(conv.id, messages[0].id, "session_superseded", {
2446
+ superseded_session_id: refusedSessionId
2447
+ });
2448
+ }
2391
2449
  for (const message of messages) {
2392
2450
  if (this.stopped) break;
2393
2451
  if (this.dispatched.has(message.id)) {
@@ -2414,7 +2472,8 @@ var ChannelDriver = class {
2414
2472
  } catch (err) {
2415
2473
  if (err instanceof ChannelAuthError) throw err;
2416
2474
  this.dispatched.delete(message.id);
2417
- if (await sessionExists(this.port, sessionId) === false) {
2475
+ const exists = await sessionExists(this.port, sessionId);
2476
+ if (exists === false) {
2418
2477
  this.sessions.delete(conv.id);
2419
2478
  this.log({
2420
2479
  level: "warn",
@@ -2424,15 +2483,39 @@ var ChannelDriver = class {
2424
2483
  });
2425
2484
  break;
2426
2485
  }
2427
- await this.markFailed(conv.id, message.id).catch(() => {
2486
+ if (exists === null) {
2487
+ this.log({
2488
+ level: "warn",
2489
+ message: `Message ${message.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed (opencode momentarily unreachable) \u2014 deferring this and later messages for conversation ${conv.id.slice(0, 8)} to the next tick rather than treating it as a genuine failure.`,
2490
+ conversation_id: conv.id,
2491
+ message_id: message.id
2492
+ });
2493
+ break;
2494
+ }
2495
+ const errorMessage = err instanceof Error ? err.message : String(err);
2496
+ this.sessions.delete(conv.id);
2497
+ this.supersede(conv.id, sessionId);
2498
+ this.log({
2499
+ level: "warn",
2500
+ message: `Abandoning OpenCode session ${sessionId.slice(0, 8)} as the binding for conversation ${conv.id.slice(0, 8)} (it exists but failed to run a turn) \u2014 a fresh session is created on the next tick, whatever the persisted binding says by then.`,
2501
+ conversation_id: conv.id,
2502
+ message_id: message.id
2503
+ });
2504
+ await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
2505
+ this.log({
2506
+ level: "warn",
2507
+ 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)}`,
2508
+ conversation_id: conv.id,
2509
+ message_id: message.id
2510
+ });
2428
2511
  });
2429
2512
  this.log({
2430
2513
  level: "error",
2431
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
2514
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
2432
2515
  conversation_id: conv.id,
2433
2516
  message_id: message.id
2434
2517
  });
2435
- continue;
2518
+ break;
2436
2519
  }
2437
2520
  if (opencodeMessageId === null) {
2438
2521
  this.log({
@@ -2458,8 +2541,42 @@ var ChannelDriver = class {
2458
2541
  this.ensureWatcherRunning(sessionId);
2459
2542
  return dispatched;
2460
2543
  }
2544
+ /**
2545
+ * Record that `sessionId` is no longer a valid binding for `conversationId`
2546
+ * (#553). Keyed by conversation and hard-capped, so it cannot grow with the
2547
+ * number of failures — see the `supersededSessions` field doc.
2548
+ */
2549
+ supersede(conversationId, sessionId) {
2550
+ this.supersededSessions.delete(conversationId);
2551
+ this.supersededSessions.set(conversationId, sessionId);
2552
+ while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
2553
+ const oldest = this.supersededSessions.keys().next().value;
2554
+ if (oldest === void 0) return;
2555
+ this.supersededSessions.delete(oldest);
2556
+ }
2557
+ }
2558
+ /** Whether `sessionId` is the session this conversation has abandoned (#553). */
2559
+ isSuperseded(conversationId, sessionId) {
2560
+ return this.supersededSessions.get(conversationId) === sessionId;
2561
+ }
2562
+ /**
2563
+ * Resolve the opencode session to run this conversation's turns in.
2564
+ *
2565
+ * `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
2566
+ * binding was an id this runner had abandoned, so a resurrection genuinely
2567
+ * happened and a fresh session was bound instead. The caller reports it.
2568
+ */
2461
2569
  async ensureSession(conv) {
2462
2570
  const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
2571
+ if (bound && this.isSuperseded(conv.id, bound)) {
2572
+ this.log({
2573
+ level: "warn",
2574
+ message: `OpenCode session ${bound.slice(0, 8)} was abandoned for conversation ${conv.id.slice(0, 8)} after a failed dispatch but is still bound to it (the persisted id was written back by a turn already in flight) \u2014 ignoring it and binding a fresh session.`,
2575
+ conversation_id: conv.id
2576
+ });
2577
+ this.sessions.delete(conv.id);
2578
+ return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
2579
+ }
2463
2580
  if (bound) {
2464
2581
  const exists = await sessionExists(this.port, bound);
2465
2582
  if (exists === false) {
@@ -2469,12 +2586,12 @@ var ChannelDriver = class {
2469
2586
  conversation_id: conv.id
2470
2587
  });
2471
2588
  this.sessions.delete(conv.id);
2472
- return this.createAndBindSession(conv.id);
2589
+ return { sessionId: await this.createAndBindSession(conv.id) };
2473
2590
  }
2474
2591
  this.sessions.set(conv.id, bound);
2475
- return bound;
2592
+ return { sessionId: bound };
2476
2593
  }
2477
- return this.createAndBindSession(conv.id);
2594
+ return { sessionId: await this.createAndBindSession(conv.id) };
2478
2595
  }
2479
2596
  /**
2480
2597
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -2562,7 +2679,11 @@ var ChannelDriver = class {
2562
2679
  * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2563
2680
  * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2564
2681
  * OMITS that one image and the text turn still sends — NEVER throws the turn.
2565
- * Failures are logged with context (no silent swallow).
2682
+ * A 404 body carrying `{ reason: 'needs_reauth' }` (#547 the server CONFIRMED
2683
+ * a Slack `files:read` scope problem via `files.info`) instead resolves the
2684
+ * `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
2685
+ * user to reconnect Slack instead of a generic "unavailable". Failures are
2686
+ * logged with context (no silent swallow).
2566
2687
  */
2567
2688
  async fetchAttachmentDataUrl(messageId, index, mime) {
2568
2689
  try {
@@ -2571,6 +2692,25 @@ var ChannelDriver = class {
2571
2692
  { headers: { Authorization: this.getAuthHeader() } }
2572
2693
  );
2573
2694
  if (!res.ok) {
2695
+ let reason;
2696
+ try {
2697
+ const body = await res.json();
2698
+ if (body && typeof body.reason === "string") reason = body.reason;
2699
+ } catch (parseErr) {
2700
+ this.log({
2701
+ level: "debug",
2702
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index}: error body was not JSON (${parseErr instanceof Error ? parseErr.message : String(parseErr)}) \u2014 treating as a plain failure`,
2703
+ message_id: messageId
2704
+ });
2705
+ }
2706
+ if (reason === "needs_reauth") {
2707
+ this.log({
2708
+ level: "error",
2709
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 server confirmed a Slack reauth/scope problem \u2014 omitting this image (text turn proceeds)`,
2710
+ message_id: messageId
2711
+ });
2712
+ return { needsReauth: true };
2713
+ }
2574
2714
  this.log({
2575
2715
  level: "error",
2576
2716
  message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
@@ -2610,6 +2750,9 @@ var ChannelDriver = class {
2610
2750
  if (this.attachmentsSkippedSignalled.has(messageId)) return;
2611
2751
  this.attachmentsSkippedSignalled.add(messageId);
2612
2752
  const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
2753
+ const failedReason = outcomes.some(
2754
+ (o) => o.status === "failed" && o.reason === "needs_reauth"
2755
+ ) ? "needs_reauth" : void 0;
2613
2756
  this.log({
2614
2757
  level: "info",
2615
2758
  message: `Message ${messageId.slice(0, 8)}: ${skipped} image(s) skipped (${capabilityUnknown ? "capability was unreadable \u2014 failed open to text-only" : "model not attachment-capable"}), ${failed} image(s) unavailable (deleted-at-source or fetch failure) \u2014 noting to Evident`,
@@ -2619,7 +2762,8 @@ var ChannelDriver = class {
2619
2762
  void this.postSignal(conversationId, messageId, "attachments_skipped", {
2620
2763
  skipped,
2621
2764
  failed,
2622
- ...skipped > 0 ? { skipped_reason: skippedReason } : {}
2765
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {},
2766
+ ...failedReason ? { failed_reason: failedReason } : {}
2623
2767
  });
2624
2768
  }
2625
2769
  /** Register a freshly-dispatched message with its session's watcher state. */
@@ -3658,19 +3802,36 @@ var ChannelDriver = class {
3658
3802
  if (parent !== void 0) this.sessionParents.set(sessionId, parent);
3659
3803
  return parent;
3660
3804
  }
3805
+ /**
3806
+ * OpenCode's synchronous default session title (e.g.
3807
+ * `"New session - 1737800000000"`), assigned immediately when a session is
3808
+ * created — before OpenCode's async LLM-based auto-titling later renames it
3809
+ * mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
3810
+ * timestamp suffix's exact format is deliberately NOT matched, since the prefix
3811
+ * alone is the stable, cheap signal and over-anchoring on the timestamp
3812
+ * representation risks silently breaking if OpenCode ever changes it. Accepted
3813
+ * trade-off: a genuine LLM-assigned title that happens to literally start with
3814
+ * this prefix would also fail to latch (see `resolveSessionTitle`) —
3815
+ * vanishingly unlikely in practice, and deliberately not engineered around.
3816
+ */
3817
+ static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
3661
3818
  /**
3662
3819
  * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
3663
3820
  * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
3664
3821
  * BOTH the watcher completion path and the restart-recovery re-adopt path (which
3665
3822
  * has no watcher) can use it. `conversationId` is passed only for log context.
3666
3823
  * Best-effort:
3667
- * - a resolved NON-EMPTY title is cached and terminal (a real session name
3824
+ * - a resolved NON-EMPTY title that does NOT match
3825
+ * `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
3668
3826
  * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
3669
- * - while the title is still absent/empty we do NOT latch it — OpenCode names
3670
- * sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
3671
- * must leave the cache unresolved and re-fetch on the next need so a later
3672
- * call (e.g. at `done`) picks up the name assigned in the meantime. Such a
3673
- * call returns `null` (omit the title on THIS PATCH) without caching;
3827
+ * - while the title is still absent, empty, or matches the OpenCode
3828
+ * placeholder prefix (#549) we do NOT latch it OpenCode names sessions
3829
+ * asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
3830
+ * the cache unresolved and re-fetch on the next need so a later call (e.g. at
3831
+ * `done`) picks up the name assigned in the meantime. Such a call returns
3832
+ * `null` (omit the title on THIS PATCH) without caching. If a session is
3833
+ * never renamed, the title is omitted forever rather than ever persisting
3834
+ * the placeholder as a last resort;
3674
3835
  * - a failed request likewise leaves the cache unresolved (retry next need)
3675
3836
  * and returns `null` — it must NEVER throw or block completion.
3676
3837
  * A failure is logged with agent/session context (no silent catch).
@@ -3683,7 +3844,7 @@ var ChannelDriver = class {
3683
3844
  if (res.ok) {
3684
3845
  const body = await res.json();
3685
3846
  const title = body && typeof body.title === "string" ? body.title.trim() : "";
3686
- if (title.length > 0) {
3847
+ if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
3687
3848
  this.sessionTitles.set(sessionId, title);
3688
3849
  return title;
3689
3850
  }
@@ -3889,6 +4050,32 @@ var ChannelDriver = class {
3889
4050
  }
3890
4051
  return messages;
3891
4052
  }
4053
+ /**
4054
+ * The `opencode_session_id` fragment of a status PATCH body — `{}` when this
4055
+ * conversation has ABANDONED that session (#553). The field is optional
4056
+ * server-side and an absent one leaves the persisted binding untouched, so
4057
+ * omitting it is how a routine status write stops resurrecting it.
4058
+ *
4059
+ * ONLY for writes whose sole cost is a lost deep link. The `processing` notice
4060
+ * degrades to no "View in Evident" link (the reaction swap still fires) and the
4061
+ * turn-failure notice is built from the PATCH's own `error` text with a link off
4062
+ * the persisted row — neither loses content the user came for. `markDone`
4063
+ * deliberately does NOT use this helper: the server fetches the reply text
4064
+ * THROUGH the session id it is given, so suppressing there would replace the
4065
+ * agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
4066
+ * `ensureSession` guard, not this suppression, is what makes the self-heal
4067
+ * stick.
4068
+ */
4069
+ sessionIdBody(sessionId, conversationId, messageId, status) {
4070
+ if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
4071
+ this.log({
4072
+ level: "debug",
4073
+ message: `Omitting the abandoned OpenCode session ${sessionId.slice(0, 8)} from the '${status}' update for message ${messageId.slice(0, 8)} so it is not re-bound to conversation ${conversationId.slice(0, 8)}`,
4074
+ conversation_id: conversationId,
4075
+ message_id: messageId
4076
+ });
4077
+ return {};
4078
+ }
3892
4079
  /**
3893
4080
  * EXISTING combinedAuth route — now fired by the watcher on queued→running
3894
4081
  * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
@@ -3918,7 +4105,7 @@ var ChannelDriver = class {
3918
4105
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3919
4106
  body: JSON.stringify({
3920
4107
  status: "processing",
3921
- opencode_session_id: sessionId,
4108
+ ...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
3922
4109
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3923
4110
  ...title ? { title } : {}
3924
4111
  })
@@ -3967,6 +4154,11 @@ var ChannelDriver = class {
3967
4154
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3968
4155
  body: JSON.stringify({
3969
4156
  status: "done",
4157
+ // ALWAYS sent, even for a session this conversation has abandoned
4158
+ // (#553): the server reads the reply text back out of THIS session id
4159
+ // to deliver it. Omitting it would leave the user with "✅ Done!"
4160
+ // instead of the answer — a worse regression than the resurrection it
4161
+ // would prevent, which `ensureSession`'s guard handles anyway.
3970
4162
  opencode_session_id: sessionId,
3971
4163
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3972
4164
  ...title ? { title } : {},
@@ -3983,14 +4175,23 @@ var ChannelDriver = class {
3983
4175
  }
3984
4176
  /**
3985
4177
  * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
3986
- * when provided (issue #182): a bare `markFailed(conv, msg)` sends
3987
- * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
3988
- * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3989
- * failure reason reaches the channel.
4178
+ * when provided (issue #182). Three states for `sessionId`:
4179
+ * - omitted (`undefined`) → don't send the field, leave the persisted
4180
+ * session untouched (unused today; kept for API symmetry).
4181
+ * - a real id (`string`) → send it, update the persisted session (the
4182
+ * turn-failure call sites: an errored OpenCode turn).
4183
+ * - explicit `null` → send it, CLEAR the persisted session (issue
4184
+ * #485's dispatch-handoff-failure call site: the session id still
4185
+ * exists but is wedged, so the next attempt must get a fresh one
4186
+ * instead of reusing it — see WI-1's server-side null-clearing PATCH).
3990
4187
  */
3991
4188
  async markFailed(conversationId, messageId, sessionId, error2, usage) {
3992
4189
  const body = { status: "failed" };
3993
- if (sessionId !== void 0) body.opencode_session_id = sessionId;
4190
+ if (sessionId === null) {
4191
+ body.opencode_session_id = null;
4192
+ } else if (sessionId !== void 0) {
4193
+ Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
4194
+ }
3994
4195
  if (error2 !== void 0) body.error = error2;
3995
4196
  if (usage) Object.assign(body, usage);
3996
4197
  await this.callWithRetry(