@evident-ai/cli 3.1.1-dev.716aea1 → 3.1.1-dev.7a5732a

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);
@@ -2079,6 +2101,34 @@ var ChannelDriver = class _ChannelDriver {
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
@@ -2387,10 +2437,15 @@ var ChannelDriver = class _ChannelDriver {
2387
2437
  * @returns the count of messages NEWLY dispatched (not already in-flight).
2388
2438
  */
2389
2439
  async processConversation(conv) {
2390
- const sessionId = await this.ensureSession(conv);
2440
+ const { sessionId, refusedSessionId } = await this.ensureSession(conv);
2391
2441
  const messages = await this.getPendingMessages(conv.id);
2392
2442
  let dispatched = 0;
2393
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
+ }
2394
2449
  for (const message of messages) {
2395
2450
  if (this.stopped) break;
2396
2451
  if (this.dispatched.has(message.id)) {
@@ -2417,7 +2472,8 @@ var ChannelDriver = class _ChannelDriver {
2417
2472
  } catch (err) {
2418
2473
  if (err instanceof ChannelAuthError) throw err;
2419
2474
  this.dispatched.delete(message.id);
2420
- if (await sessionExists(this.port, sessionId) === false) {
2475
+ const exists = await sessionExists(this.port, sessionId);
2476
+ if (exists === false) {
2421
2477
  this.sessions.delete(conv.id);
2422
2478
  this.log({
2423
2479
  level: "warn",
@@ -2427,15 +2483,39 @@ var ChannelDriver = class _ChannelDriver {
2427
2483
  });
2428
2484
  break;
2429
2485
  }
2430
- 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
+ });
2431
2511
  });
2432
2512
  this.log({
2433
2513
  level: "error",
2434
- 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}`,
2435
2515
  conversation_id: conv.id,
2436
2516
  message_id: message.id
2437
2517
  });
2438
- continue;
2518
+ break;
2439
2519
  }
2440
2520
  if (opencodeMessageId === null) {
2441
2521
  this.log({
@@ -2461,8 +2541,42 @@ var ChannelDriver = class _ChannelDriver {
2461
2541
  this.ensureWatcherRunning(sessionId);
2462
2542
  return dispatched;
2463
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
+ */
2464
2569
  async ensureSession(conv) {
2465
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
+ }
2466
2580
  if (bound) {
2467
2581
  const exists = await sessionExists(this.port, bound);
2468
2582
  if (exists === false) {
@@ -2472,12 +2586,12 @@ var ChannelDriver = class _ChannelDriver {
2472
2586
  conversation_id: conv.id
2473
2587
  });
2474
2588
  this.sessions.delete(conv.id);
2475
- return this.createAndBindSession(conv.id);
2589
+ return { sessionId: await this.createAndBindSession(conv.id) };
2476
2590
  }
2477
2591
  this.sessions.set(conv.id, bound);
2478
- return bound;
2592
+ return { sessionId: bound };
2479
2593
  }
2480
- return this.createAndBindSession(conv.id);
2594
+ return { sessionId: await this.createAndBindSession(conv.id) };
2481
2595
  }
2482
2596
  /**
2483
2597
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -2565,7 +2679,11 @@ var ChannelDriver = class _ChannelDriver {
2565
2679
  * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2566
2680
  * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2567
2681
  * OMITS that one image and the text turn still sends — NEVER throws the turn.
2568
- * 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).
2569
2687
  */
2570
2688
  async fetchAttachmentDataUrl(messageId, index, mime) {
2571
2689
  try {
@@ -2574,6 +2692,25 @@ var ChannelDriver = class _ChannelDriver {
2574
2692
  { headers: { Authorization: this.getAuthHeader() } }
2575
2693
  );
2576
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
+ }
2577
2714
  this.log({
2578
2715
  level: "error",
2579
2716
  message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
@@ -2613,6 +2750,9 @@ var ChannelDriver = class _ChannelDriver {
2613
2750
  if (this.attachmentsSkippedSignalled.has(messageId)) return;
2614
2751
  this.attachmentsSkippedSignalled.add(messageId);
2615
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;
2616
2756
  this.log({
2617
2757
  level: "info",
2618
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`,
@@ -2622,7 +2762,8 @@ var ChannelDriver = class _ChannelDriver {
2622
2762
  void this.postSignal(conversationId, messageId, "attachments_skipped", {
2623
2763
  skipped,
2624
2764
  failed,
2625
- ...skipped > 0 ? { skipped_reason: skippedReason } : {}
2765
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {},
2766
+ ...failedReason ? { failed_reason: failedReason } : {}
2626
2767
  });
2627
2768
  }
2628
2769
  /** Register a freshly-dispatched message with its session's watcher state. */
@@ -3909,6 +4050,32 @@ var ChannelDriver = class _ChannelDriver {
3909
4050
  }
3910
4051
  return messages;
3911
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
+ }
3912
4079
  /**
3913
4080
  * EXISTING combinedAuth route — now fired by the watcher on queued→running
3914
4081
  * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
@@ -3938,7 +4105,7 @@ var ChannelDriver = class _ChannelDriver {
3938
4105
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3939
4106
  body: JSON.stringify({
3940
4107
  status: "processing",
3941
- opencode_session_id: sessionId,
4108
+ ...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
3942
4109
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3943
4110
  ...title ? { title } : {}
3944
4111
  })
@@ -3987,6 +4154,11 @@ var ChannelDriver = class _ChannelDriver {
3987
4154
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3988
4155
  body: JSON.stringify({
3989
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.
3990
4162
  opencode_session_id: sessionId,
3991
4163
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3992
4164
  ...title ? { title } : {},
@@ -4003,14 +4175,23 @@ var ChannelDriver = class _ChannelDriver {
4003
4175
  }
4004
4176
  /**
4005
4177
  * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
4006
- * when provided (issue #182): a bare `markFailed(conv, msg)` sends
4007
- * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
4008
- * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
4009
- * 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).
4010
4187
  */
4011
4188
  async markFailed(conversationId, messageId, sessionId, error2, usage) {
4012
4189
  const body = { status: "failed" };
4013
- 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
+ }
4014
4195
  if (error2 !== void 0) body.error = error2;
4015
4196
  if (usage) Object.assign(body, usage);
4016
4197
  await this.callWithRetry(