@evident-ai/cli 3.1.1-dev.14c6359 → 3.1.1-dev.1997a8e

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;
@@ -645,14 +651,27 @@ var EventTypes = {
645
651
  // CLI lifecycle
646
652
  CLI_STARTED: "cli.started",
647
653
  CLI_COMMAND: "cli.command",
648
- CLI_ERROR: "cli.error"
654
+ CLI_ERROR: "cli.error",
655
+ // Deprecation telemetry (#412) — usage of the old `--agent`/`EVIDENT_AGENT_KEY`
656
+ // names instead of the preferred `--runner`/`EVIDENT_RUNNER_KEY` (#409).
657
+ DEPRECATED_AGENT_FLAG_USED: "cli.deprecated_agent_flag_used",
658
+ DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
649
659
  };
650
660
 
651
661
  // src/lib/auth.ts
652
662
  async function getAuthCredentials() {
663
+ const runnerKey = process.env.EVIDENT_RUNNER_KEY;
653
664
  const agentKey = process.env.EVIDENT_AGENT_KEY;
665
+ if (runnerKey) {
666
+ return {
667
+ token: runnerKey,
668
+ authType: "agent_key",
669
+ keySource: "runner_key",
670
+ notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
671
+ };
672
+ }
654
673
  if (agentKey) {
655
- return { token: agentKey, authType: "agent_key" };
674
+ return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
656
675
  }
657
676
  const userToken = process.env.EVIDENT_TOKEN;
658
677
  if (userToken) {
@@ -721,7 +740,7 @@ function buildOpenCodeVersionWarning(version2) {
721
740
  if (isQueueValidatedVersion(version2)) return null;
722
741
  const detected = version2 ? `v${version2}` : "unknown";
723
742
  const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
724
- return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack/WhatsApp) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
743
+ return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
725
744
  }
726
745
 
727
746
  // src/lib/opencode/process.ts
@@ -1013,6 +1032,12 @@ async function promptOpenCodeInstall(interactive) {
1013
1032
  return action;
1014
1033
  }
1015
1034
 
1035
+ // src/lib/opencode/provider-check.ts
1036
+ function buildNoProviderWarning(hasProvider) {
1037
+ if (hasProvider !== false) return null;
1038
+ return "Warning: opencode has no authenticated model provider configured, so it won't be able to answer prompts. Run `opencode auth login` to set one up (see https://opencode.ai for details).";
1039
+ }
1040
+
1016
1041
  // src/lib/opencode/session.ts
1017
1042
  function opencodeBase(port) {
1018
1043
  return `http://127.0.0.1:${port}`;
@@ -1215,6 +1240,11 @@ async function getModelAttachmentCapability(port, model) {
1215
1240
  }
1216
1241
  const entry = provider.models[modelId];
1217
1242
  if (!entry || typeof entry !== "object") return null;
1243
+ if (entry.capabilities && typeof entry.capabilities === "object") {
1244
+ if (typeof entry.capabilities.attachment === "boolean") {
1245
+ return entry.capabilities.attachment;
1246
+ }
1247
+ }
1218
1248
  return typeof entry.attachment === "boolean" ? entry.attachment : null;
1219
1249
  } catch (err) {
1220
1250
  console.error(
@@ -1243,6 +1273,16 @@ async function buildFileParts(attachments, capable) {
1243
1273
  );
1244
1274
  dataUrl = null;
1245
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
+ }
1246
1286
  if (dataUrl == null) {
1247
1287
  outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
1248
1288
  continue;
@@ -1471,6 +1511,37 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1471
1511
  (m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
1472
1512
  );
1473
1513
  }
1514
+ async function hasAnyConfiguredProvider(port) {
1515
+ try {
1516
+ const res = await fetch(`${opencodeBase(port)}/config/providers`);
1517
+ if (!res.ok) {
1518
+ console.error(
1519
+ `[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
1520
+ );
1521
+ return null;
1522
+ }
1523
+ const body = await res.json();
1524
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
1525
+ console.error(
1526
+ `[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
1527
+ );
1528
+ return null;
1529
+ }
1530
+ const defaults2 = body.default;
1531
+ if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
1532
+ console.error(
1533
+ `[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
1534
+ );
1535
+ return null;
1536
+ }
1537
+ return Object.keys(defaults2).length > 0;
1538
+ } catch (err) {
1539
+ console.error(
1540
+ `[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1541
+ );
1542
+ return null;
1543
+ }
1544
+ }
1474
1545
 
1475
1546
  // src/lib/opencode/session-cleanup.ts
1476
1547
  var DURATION_UNIT_MS = {
@@ -1629,10 +1700,11 @@ var StreamForwarder = class {
1629
1700
  * Abort every in-flight stream (e.g. on WebSocket close).
1630
1701
  */
1631
1702
  abortAll() {
1632
- for (const stream of this.inflight.values()) {
1703
+ for (const [sid, stream] of this.inflight.entries()) {
1633
1704
  try {
1634
1705
  stream.abort();
1635
- } catch {
1706
+ } catch (err) {
1707
+ log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
1636
1708
  }
1637
1709
  }
1638
1710
  this.inflight.clear();
@@ -1782,7 +1854,6 @@ function connectTunnel(options) {
1782
1854
  onConnected,
1783
1855
  onDisconnected,
1784
1856
  onError,
1785
- onRequest,
1786
1857
  onResponse,
1787
1858
  onInfo,
1788
1859
  onDrainPing
@@ -1795,18 +1866,8 @@ function connectTunnel(options) {
1795
1866
  Authorization: authHeader
1796
1867
  }
1797
1868
  });
1798
- const streamStartTimes = /* @__PURE__ */ new Map();
1799
1869
  const forwarder = new StreamForwarder(ws, port, {
1800
- onOpen: (sid, method, path) => {
1801
- if (path === TUNNEL_DRAIN_PING_PATH) return;
1802
- streamStartTimes.set(sid, Date.now());
1803
- onRequest?.(method, path, sid);
1804
- },
1805
- onHead: (sid, status) => {
1806
- const startedAt = streamStartTimes.get(sid);
1807
- streamStartTimes.delete(sid);
1808
- onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
1809
- },
1870
+ onHead: () => onResponse?.(),
1810
1871
  onDrainPing: () => onDrainPing?.()
1811
1872
  });
1812
1873
  const connectionTimeout = setTimeout(() => {
@@ -1882,7 +1943,6 @@ function connectTunnel(options) {
1882
1943
  ws.on("close", (code, reason) => {
1883
1944
  const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
1884
1945
  forwarder.abortAll();
1885
- streamStartTimes.clear();
1886
1946
  onDisconnected?.(code, reasonStr);
1887
1947
  });
1888
1948
  });
@@ -1917,7 +1977,11 @@ var RunnerConnection = class {
1917
1977
  if (this.connection) {
1918
1978
  try {
1919
1979
  this.connection.close();
1920
- } catch {
1980
+ } catch (err) {
1981
+ log("error", "runner_connection_close_failed", {
1982
+ agent_id: this.resolvedAgentId,
1983
+ ...errorFields(err)
1984
+ });
1921
1985
  }
1922
1986
  this.connection = null;
1923
1987
  }
@@ -1998,6 +2062,7 @@ var DEFAULT_STUCK_QUEUED_MS = 6e4;
1998
2062
  var HEARTBEAT_MS = 6e4;
1999
2063
  var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
2000
2064
  var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
2065
+ var MAX_SUPERSEDED_CONVERSATIONS = 256;
2001
2066
  var ChannelAuthError = class extends Error {
2002
2067
  constructor(message) {
2003
2068
  super(message);
@@ -2020,7 +2085,7 @@ function backoffDelay(attempt, policy) {
2020
2085
  function isRetryableStatus(status) {
2021
2086
  return status === 429 || status >= 500 && status <= 599;
2022
2087
  }
2023
- var ChannelDriver = class {
2088
+ var ChannelDriver = class _ChannelDriver {
2024
2089
  agentId;
2025
2090
  port;
2026
2091
  apiUrl;
@@ -2036,6 +2101,34 @@ var ChannelDriver = class {
2036
2101
  now;
2037
2102
  /** Cache of conversationId → opencode sessionId. */
2038
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();
2039
2132
  /**
2040
2133
  * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
2041
2134
  * longer idempotent (no caller-supplied `messageID`), and its read-back picks
@@ -2145,9 +2238,12 @@ var ChannelDriver = class {
2145
2238
  sessionParents = /* @__PURE__ */ new Map();
2146
2239
  /**
2147
2240
  * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2148
- * NON-EMPTY name is stored (terminal — a real session name won't later un-name),
2149
- * so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
2150
- * 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
2151
2247
  * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2152
2248
  * the watcher completion path AND the restart-recovery re-adopt path (which has
2153
2249
  * no watcher) can resolve the title.
@@ -2341,10 +2437,15 @@ var ChannelDriver = class {
2341
2437
  * @returns the count of messages NEWLY dispatched (not already in-flight).
2342
2438
  */
2343
2439
  async processConversation(conv) {
2344
- const sessionId = await this.ensureSession(conv);
2440
+ const { sessionId, refusedSessionId } = await this.ensureSession(conv);
2345
2441
  const messages = await this.getPendingMessages(conv.id);
2346
2442
  let dispatched = 0;
2347
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
+ }
2348
2449
  for (const message of messages) {
2349
2450
  if (this.stopped) break;
2350
2451
  if (this.dispatched.has(message.id)) {
@@ -2371,7 +2472,8 @@ var ChannelDriver = class {
2371
2472
  } catch (err) {
2372
2473
  if (err instanceof ChannelAuthError) throw err;
2373
2474
  this.dispatched.delete(message.id);
2374
- if (await sessionExists(this.port, sessionId) === false) {
2475
+ const exists = await sessionExists(this.port, sessionId);
2476
+ if (exists === false) {
2375
2477
  this.sessions.delete(conv.id);
2376
2478
  this.log({
2377
2479
  level: "warn",
@@ -2381,15 +2483,39 @@ var ChannelDriver = class {
2381
2483
  });
2382
2484
  break;
2383
2485
  }
2384
- 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
+ });
2385
2511
  });
2386
2512
  this.log({
2387
2513
  level: "error",
2388
- 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}`,
2389
2515
  conversation_id: conv.id,
2390
2516
  message_id: message.id
2391
2517
  });
2392
- continue;
2518
+ break;
2393
2519
  }
2394
2520
  if (opencodeMessageId === null) {
2395
2521
  this.log({
@@ -2415,8 +2541,42 @@ var ChannelDriver = class {
2415
2541
  this.ensureWatcherRunning(sessionId);
2416
2542
  return dispatched;
2417
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
+ */
2418
2569
  async ensureSession(conv) {
2419
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
+ }
2420
2580
  if (bound) {
2421
2581
  const exists = await sessionExists(this.port, bound);
2422
2582
  if (exists === false) {
@@ -2426,12 +2586,12 @@ var ChannelDriver = class {
2426
2586
  conversation_id: conv.id
2427
2587
  });
2428
2588
  this.sessions.delete(conv.id);
2429
- return this.createAndBindSession(conv.id);
2589
+ return { sessionId: await this.createAndBindSession(conv.id) };
2430
2590
  }
2431
2591
  this.sessions.set(conv.id, bound);
2432
- return bound;
2592
+ return { sessionId: bound };
2433
2593
  }
2434
- return this.createAndBindSession(conv.id);
2594
+ return { sessionId: await this.createAndBindSession(conv.id) };
2435
2595
  }
2436
2596
  /**
2437
2597
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -2511,7 +2671,7 @@ var ChannelDriver = class {
2511
2671
  }
2512
2672
  /**
2513
2673
  * Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
2514
- * (`GET {apiUrl}/agents/{agentId}/attachments/{messageId}/{index}`) using the
2674
+ * (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
2515
2675
  * existing authenticated fetch, and base64-encode into a
2516
2676
  * `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
2517
2677
  *
@@ -2519,15 +2679,38 @@ var ChannelDriver = class {
2519
2679
  * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2520
2680
  * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2521
2681
  * OMITS that one image and the text turn still sends — NEVER throws the turn.
2522
- * 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).
2523
2687
  */
2524
2688
  async fetchAttachmentDataUrl(messageId, index, mime) {
2525
2689
  try {
2526
2690
  const res = await this.fetchImpl(
2527
- `${this.apiUrl}/agents/${this.agentId}/attachments/${messageId}/${index}`,
2691
+ `${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
2528
2692
  { headers: { Authorization: this.getAuthHeader() } }
2529
2693
  );
2530
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
+ }
2531
2714
  this.log({
2532
2715
  level: "error",
2533
2716
  message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
@@ -2567,6 +2750,9 @@ var ChannelDriver = class {
2567
2750
  if (this.attachmentsSkippedSignalled.has(messageId)) return;
2568
2751
  this.attachmentsSkippedSignalled.add(messageId);
2569
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;
2570
2756
  this.log({
2571
2757
  level: "info",
2572
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`,
@@ -2576,7 +2762,8 @@ var ChannelDriver = class {
2576
2762
  void this.postSignal(conversationId, messageId, "attachments_skipped", {
2577
2763
  skipped,
2578
2764
  failed,
2579
- ...skipped > 0 ? { skipped_reason: skippedReason } : {}
2765
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {},
2766
+ ...failedReason ? { failed_reason: failedReason } : {}
2580
2767
  });
2581
2768
  }
2582
2769
  /** Register a freshly-dispatched message with its session's watcher state. */
@@ -3615,19 +3802,36 @@ var ChannelDriver = class {
3615
3802
  if (parent !== void 0) this.sessionParents.set(sessionId, parent);
3616
3803
  return parent;
3617
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 - /;
3618
3818
  /**
3619
3819
  * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
3620
3820
  * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
3621
3821
  * BOTH the watcher completion path and the restart-recovery re-adopt path (which
3622
3822
  * has no watcher) can use it. `conversationId` is passed only for log context.
3623
3823
  * Best-effort:
3624
- * - 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
3625
3826
  * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
3626
- * - while the title is still absent/empty we do NOT latch it — OpenCode names
3627
- * sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
3628
- * must leave the cache unresolved and re-fetch on the next need so a later
3629
- * call (e.g. at `done`) picks up the name assigned in the meantime. Such a
3630
- * 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;
3631
3835
  * - a failed request likewise leaves the cache unresolved (retry next need)
3632
3836
  * and returns `null` — it must NEVER throw or block completion.
3633
3837
  * A failure is logged with agent/session context (no silent catch).
@@ -3640,7 +3844,7 @@ var ChannelDriver = class {
3640
3844
  if (res.ok) {
3641
3845
  const body = await res.json();
3642
3846
  const title = body && typeof body.title === "string" ? body.title.trim() : "";
3643
- if (title.length > 0) {
3847
+ if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
3644
3848
  this.sessionTitles.set(sessionId, title);
3645
3849
  return title;
3646
3850
  }
@@ -3790,7 +3994,7 @@ var ChannelDriver = class {
3790
3994
  // Evident API calls (combinedAuth thread routes)
3791
3995
  async getPendingConversations() {
3792
3996
  const res = await this.fetchImpl(
3793
- `${this.apiUrl}/agents/${this.agentId}/conversations/pending`,
3997
+ `${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
3794
3998
  {
3795
3999
  headers: { Authorization: this.getAuthHeader() }
3796
4000
  }
@@ -3808,7 +4012,7 @@ var ChannelDriver = class {
3808
4012
  }
3809
4013
  async getPendingMessages(conversationId) {
3810
4014
  const res = await this.fetchImpl(
3811
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages?status=pending`,
4015
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
3812
4016
  { headers: { Authorization: this.getAuthHeader() } }
3813
4017
  );
3814
4018
  this.assertAuth(res, "fetching pending messages");
@@ -3832,7 +4036,7 @@ var ChannelDriver = class {
3832
4036
  */
3833
4037
  async getProcessingMessages() {
3834
4038
  const res = await this.fetchImpl(
3835
- `${this.apiUrl}/agents/${this.agentId}/conversations/processing`,
4039
+ `${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
3836
4040
  { headers: { Authorization: this.getAuthHeader() } }
3837
4041
  );
3838
4042
  this.assertAuth(res, "fetching processing messages");
@@ -3846,6 +4050,32 @@ var ChannelDriver = class {
3846
4050
  }
3847
4051
  return messages;
3848
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
+ }
3849
4079
  /**
3850
4080
  * EXISTING combinedAuth route — now fired by the watcher on queued→running
3851
4081
  * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
@@ -3869,13 +4099,13 @@ var ChannelDriver = class {
3869
4099
  */
3870
4100
  async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
3871
4101
  const res = await this.fetchImpl(
3872
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
4102
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3873
4103
  {
3874
4104
  method: "PATCH",
3875
4105
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3876
4106
  body: JSON.stringify({
3877
4107
  status: "processing",
3878
- opencode_session_id: sessionId,
4108
+ ...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
3879
4109
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3880
4110
  ...title ? { title } : {}
3881
4111
  })
@@ -3918,12 +4148,17 @@ var ChannelDriver = class {
3918
4148
  */
3919
4149
  async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
3920
4150
  const res = await this.fetchImpl(
3921
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
4151
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3922
4152
  {
3923
4153
  method: "PATCH",
3924
4154
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3925
4155
  body: JSON.stringify({
3926
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.
3927
4162
  opencode_session_id: sessionId,
3928
4163
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3929
4164
  ...title ? { title } : {},
@@ -3940,20 +4175,29 @@ var ChannelDriver = class {
3940
4175
  }
3941
4176
  /**
3942
4177
  * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
3943
- * when provided (issue #182): a bare `markFailed(conv, msg)` sends
3944
- * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
3945
- * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3946
- * 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).
3947
4187
  */
3948
4188
  async markFailed(conversationId, messageId, sessionId, error2, usage) {
3949
4189
  const body = { status: "failed" };
3950
- 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
+ }
3951
4195
  if (error2 !== void 0) body.error = error2;
3952
4196
  if (usage) Object.assign(body, usage);
3953
4197
  await this.callWithRetry(
3954
4198
  "marking message as failed",
3955
4199
  () => this.fetchImpl(
3956
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
4200
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3957
4201
  {
3958
4202
  method: "PATCH",
3959
4203
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3980,7 +4224,7 @@ var ChannelDriver = class {
3980
4224
  async postSignal(conversationId, messageId, signal, extra) {
3981
4225
  try {
3982
4226
  const res = await this.fetchImpl(
3983
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
4227
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
3984
4228
  {
3985
4229
  method: "POST",
3986
4230
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -4009,7 +4253,7 @@ var ChannelDriver = class {
4009
4253
  }
4010
4254
  async persistSession(conversationId, sessionId) {
4011
4255
  const res = await this.fetchImpl(
4012
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}`,
4256
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
4013
4257
  {
4014
4258
  method: "PATCH",
4015
4259
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -4035,7 +4279,7 @@ var ChannelDriver = class {
4035
4279
  await this.callWithRetry(
4036
4280
  "reporting interactive event",
4037
4281
  () => this.fetchImpl(
4038
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/interactive-event`,
4282
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
4039
4283
  {
4040
4284
  method: "POST",
4041
4285
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -4278,7 +4522,7 @@ async function resolveAgentIdFromKey(authHeader) {
4278
4522
  async function notifyAgentDisconnected(agentId, authHeader) {
4279
4523
  const apiUrl = getApiUrlConfig();
4280
4524
  try {
4281
- const response = await fetch(`${apiUrl}/agents/${agentId}/disconnect`, {
4525
+ const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
4282
4526
  method: "POST",
4283
4527
  headers: { Authorization: authHeader }
4284
4528
  });
@@ -4297,7 +4541,7 @@ async function notifyAgentDisconnected(agentId, authHeader) {
4297
4541
  async function getAgentInfo(agentId, authHeader) {
4298
4542
  const apiUrl = getApiUrlConfig();
4299
4543
  try {
4300
- const response = await fetch(`${apiUrl}/agents/${agentId}`, {
4544
+ const response = await fetch(`${apiUrl}/runners/${agentId}`, {
4301
4545
  headers: { Authorization: authHeader }
4302
4546
  });
4303
4547
  if (response.status === 401) {
@@ -4684,7 +4928,7 @@ async function run(options) {
4684
4928
  return;
4685
4929
  }
4686
4930
  const state = {
4687
- agentId: options.agent || "",
4931
+ agentId: options.runner || options.agent || "",
4688
4932
  agentName: null,
4689
4933
  port: options.port ?? 4096,
4690
4934
  conversationFilter: options.conversation ?? null,
@@ -4706,6 +4950,19 @@ async function run(options) {
4706
4950
  sessionCleanupTimers: [],
4707
4951
  authHeader: ""
4708
4952
  };
4953
+ if (!options.runner && options.agent) {
4954
+ telemetry.info(
4955
+ EventTypes.DEPRECATED_AGENT_FLAG_USED,
4956
+ "Deprecated --agent flag used instead of --runner",
4957
+ { command: "run" },
4958
+ state.agentId
4959
+ );
4960
+ const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
4961
+ log2(state, agentFlagNotice, "warn");
4962
+ if (state.interactive && !state.json) {
4963
+ logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
4964
+ }
4965
+ }
4709
4966
  if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
4710
4967
  log2(
4711
4968
  state,
@@ -4734,7 +4991,9 @@ async function run(options) {
4734
4991
  if (!interactive) {
4735
4992
  printError("Authentication required");
4736
4993
  blank();
4737
- console.log(chalk6.dim("Set EVIDENT_AGENT_KEY environment variable for CI"));
4994
+ console.log(
4995
+ chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
4996
+ );
4738
4997
  console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
4739
4998
  blank();
4740
4999
  process.exit(1);
@@ -4748,6 +5007,25 @@ async function run(options) {
4748
5007
  );
4749
5008
  }
4750
5009
  state.authHeader = getAuthHeader(credentials2);
5010
+ if (credentials2.notice) {
5011
+ log2(state, credentials2.notice, "warn");
5012
+ if (state.interactive && !state.json) {
5013
+ logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
5014
+ }
5015
+ }
5016
+ if (credentials2.keySource === "agent_key") {
5017
+ telemetry.info(
5018
+ EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
5019
+ "Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
5020
+ { command: "run" },
5021
+ state.agentId
5022
+ );
5023
+ const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
5024
+ log2(state, agentKeyNotice, "warn");
5025
+ if (state.interactive && !state.json) {
5026
+ logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
5027
+ }
5028
+ }
4751
5029
  if (!state.agentId) {
4752
5030
  if (credentials2.authType === "agent_key") {
4753
5031
  const resolved = await resolveAgentIdFromKey(state.authHeader);
@@ -4765,9 +5043,15 @@ async function run(options) {
4765
5043
  process.exit(1);
4766
5044
  }
4767
5045
  } else {
4768
- printError("--agent is required when not using EVIDENT_AGENT_KEY");
5046
+ printError(
5047
+ "--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
5048
+ );
4769
5049
  blank();
4770
- console.log(chalk6.dim("Either provide --agent <id> or set EVIDENT_AGENT_KEY"));
5050
+ console.log(
5051
+ chalk6.dim(
5052
+ "Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
5053
+ )
5054
+ );
4771
5055
  blank();
4772
5056
  process.exit(1);
4773
5057
  }
@@ -4831,6 +5115,21 @@ async function run(options) {
4831
5115
  logActivity(state, { type: "info", level: "warn", message: versionWarning });
4832
5116
  }
4833
5117
  }
5118
+ const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
5119
+ if (noProviderWarning) {
5120
+ log2(state, noProviderWarning, "warn");
5121
+ if (state.interactive && !state.json) {
5122
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
5123
+ blank();
5124
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
5125
+ console.log(
5126
+ chalk6.dim(
5127
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
5128
+ )
5129
+ );
5130
+ blank();
5131
+ }
5132
+ }
4834
5133
  } catch (error2) {
4835
5134
  ocSpinner?.fail(error2.message);
4836
5135
  throw error2;
@@ -4982,7 +5281,7 @@ async function run(options) {
4982
5281
  }
4983
5282
  telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
4984
5283
  command: "run",
4985
- agentId: options.agent
5284
+ agentId: options.runner || options.agent
4986
5285
  });
4987
5286
  await shutdownTelemetry();
4988
5287
  process.exit(1);
@@ -5007,7 +5306,7 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
5007
5306
  program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
5008
5307
  program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
5009
5308
  program.command("whoami").description("Show the currently logged in user").action(whoami);
5010
- program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
5309
+ program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("--runner [id]", "Alias for --agent (preferred name; wins if both are given)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
5011
5310
  "--log-level <level>",
5012
5311
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
5013
5312
  ).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option("--json", "Output in JSON format").option(
@@ -5023,6 +5322,7 @@ program.command("run").description("Connect to Evident and process messages").op
5023
5322
  (options) => {
5024
5323
  run({
5025
5324
  agent: options.agent,
5325
+ runner: options.runner,
5026
5326
  port: parseInt(options.port, 10),
5027
5327
  // Raw string — validation/precedence is single-sourced in run.ts's
5028
5328
  // resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).