Skip to content

The agent that grows with you

30.8 KB
Raw Blame
/**
 * The cross-connection bot relay: the Desktop-as-router loops that let a bot
 * on one gateway reach a bot on another.
 *
 * There is one relay per renderer, so its lifecycle lives in the module-scoped
 * `relay` record below rather than in an atom — no UI reads it. plugin.tsx
 * drives the two doors, startBotRelay / stopBotRelay.
 */

import { host, LruCache } from '@hermes/plugin-sdk'

import { botHandle, clearBotAttention, noteBotAttention } from './data'
import { RELAY_DELIVER_TIMEOUT_MS } from './relay-budget'
import { ID } from './shared'
import type { ProfileRoute, RosterRow } from './types'

// ── cross-connection bot relay ────────────────────────────────────────────
// Connections ARE the peer set: every gateway this Desktop holds a socket
// to (local, remote URL, SSH, Hermes Cloud, docker) must be able to find
// every other connection's agents and message them via message_agent. The
// Desktop is the relay — it owns every socket. Two loops:
//  - roster loop: pushes each gateway the union roster of agents on the
//    OTHER connections (bot_relay.roster.sync), so message_agent resolves
//    cross-connection targets and Bot Chat prompts list them;
//  - drain loop: collects queued envelopes from every gateway
//    (bot_relay.outbox.drain), delivers each on the target connection's
//    own socket (bot_relay.deliver), and posts the reply back to the
//    sender gateway (bot_relay.reply) where a waiter wakes the sender.
// Older backends without the RPCs fail per-call and are skipped — the
// relay degrades to whatever subset of connections supports it.
const RELAY_ROSTER_INTERVAL_MS = 60_000
// Backstop cadence only (#93594): the push path below carries envelope latency,
// so the interval poll exists for older backends that cannot signal
// `bot_relay.outbox.pending`. On a shell with that door, the tick must not
// open a gateway socket for a route that has not signaled outbox work — that
// dial/teardown is the idle ~30s cost (#118856). It was 4s back when the
// poll WAS the delivery path, which (before route retention) also meant a
// fresh WebSocket dial + teardown per registered connection every 4s.
const RELAY_DRAIN_INTERVAL_MS = 30_000
// Push path (#93091): the gateway broadcasts `bot_relay.outbox.pending` when
// an envelope lands on disk; a burst of signals inside this window collapses
// to ONE drain. The interval poll above stays as the backstop for older
// backends (and connections whose events don't reach the tap).
const RELAY_PUSH_DEBOUNCE_MS = 250

/** Everything the two loops mutate. */
interface RelayLifecycle {
  disposed: boolean
  drainBusy: boolean
  /** A push landing while a drain is ALREADY running would be lost forever —
   *  the gateway signature is monotone (one event per new envelope, never
   *  re-broadcast) — so remember it and re-schedule after the drain finishes. */
  drainRerun: boolean
  drainTimer: null | ReturnType<typeof setInterval>
  pushDebounceTimer: null | ReturnType<typeof setTimeout>
  pushUnsub: (() => void) | null
  rosterBusy: boolean
  /** Invalidates pending roster reads when the relay stops or restarts. */
  rosterGeneration: number
  /** Id of the sole connection whose roster clear went out; null once the peer set relays again. */
  rosterClearedFor: null | string
  rosterTimer: null | ReturnType<typeof setInterval>
}

const relay: RelayLifecycle = {
  disposed: false,
  drainBusy: false,
  drainRerun: false,
  drainTimer: null,
  pushDebounceTimer: null,
  pushUnsub: null,
  rosterBusy: false,
  rosterGeneration: 0,
  rosterClearedFor: null,
  rosterTimer: null
}

// Relay-route socket retention (#93594): connection id → release fn. While
// the relay is active each registered connection's pooled socket is pinned
// open (host.retainProfileSocket) so drain RPCs reuse ONE persistent
// WebSocket instead of dialing and tearing down a fresh one per tick.
// Feature-detected — older shells lack the door and fall back to per-call
// leases. Local routes get a no-op release inside the host (idle-reaper
// exemption). stopBotRelay releases everything.
const relayRouteRetentions = new Map<string, () => void>()
// Claimed envelopes remain pinned to their sender until terminal reply ACK.
// The sender's durable claimed directory restores these after renderer restart.
const pendingRelays = new Map<string, Map<string, RelayEnvelope>>()

function pendingRelaysFor(sender: RelayConnection): Map<string, RelayEnvelope> {
  const senderKey = JSON.stringify(sender.route)
  const pending = pendingRelays.get(senderKey) || new Map<string, RelayEnvelope>()
  pendingRelays.set(senderKey, pending)

  return pending
}

// Routes whose gateway has signaled `bot_relay.outbox.pending` since the last
// drain pass. `*` means the event carried no connection id (local/legacy
// primary, or an older payload) — every route may hold that envelope, so the
// pass still visits them. A route absent from this set has no outbox work;
// opening a socket to drain it is the idle dial.
const RELAY_OUTBOX_ANY = '*'
const routesWithOutboxWork = new Set<string>()

function relayBotModeOn(): boolean {
  const decisions = host.pluginDecisions?.get() ?? {}

  return ID in decisions ? Boolean(decisions[ID]) : true
}

function noteRelayOutboxWork(event?: { connectionId?: string }) {
  const id = String(event?.connectionId || '').trim()

  routesWithOutboxWork.add(id || RELAY_OUTBOX_ANY)
}

function takeRelayOutboxWork(): { any: boolean; ids: Set<string> } {
  const any = routesWithOutboxWork.has(RELAY_OUTBOX_ANY)
  const ids = new Set(routesWithOutboxWork)

  routesWithOutboxWork.clear()

  return { any, ids }
}

function routeSignaledOutboxWork(connectionId: string, work: { any: boolean; ids: Set<string> }): boolean {
  return work.any || work.ids.has(connectionId)
}

/** One reachable gateway plus a representative route onto it. The route carries
 *  identity only, so the human label comes from the registry (connectionLabels). */
interface RelayConnection {
  id: string
  route: ProfileRoute
}

/** One agent as pushed to a peer gateway's relay roster. */
interface RelayAgentRow {
  connection_id: string
  connection_label: string
  description: string
  handle: string
  profile: string
  title: string
}

/** Remove the mandatory local registry source only when Electron identifies
 * one unambiguous REMOTE primary. Older or inconsistent route inventories
 * fail open to the prior peer set. Distinct remote peers always remain. */
function relayEligibleRoutes(routes: ProfileRoute[]): ProfileRoute[] {
  const routesByConnection = new Map<string, ProfileRoute[]>()

  for (const route of routes) {
    if (
      !route ||
      typeof route.connectionId !== 'string' ||
      !route.connectionId ||
      (route.mode !== 'local' && route.mode !== 'remote') ||
      (route.primary !== undefined && route.primary !== true)
    ) {
      return routes
    }

    const grouped = routesByConnection.get(route.connectionId) || []

    grouped.push(route)
    routesByConnection.set(route.connectionId, grouped)
  }

  const primaryGroups = [...routesByConnection.entries()].filter(([, grouped]) =>
    grouped.some(route => route.primary === true)
  )

  if (primaryGroups.length !== 1) {
    return routes
  }

  const [primaryId, primaryRoutes] = primaryGroups[0]

  if (primaryRoutes.some(route => route.mode !== 'remote' || route.primary !== true)) {
    return routes
  }

  const localGroups = [...routesByConnection.entries()].filter(([, grouped]) =>
    grouped.some(route => route.mode === 'local')
  )

  if (
    localGroups.length !== 1 ||
    localGroups[0][1].some(route => route.mode !== 'local') ||
    localGroups[0][0] === primaryId
  ) {
    return routes
  }

  const localId = localGroups[0][0]

  return routes.filter(route => route.connectionId !== localId)
}

/** A queued cross-connection message drained from a gateway's outbox. */
interface RelayEnvelope {
  id?: string
  message?: string
  from_profile?: string
  from_handle?: string
  target_connection?: string
  target_profile?: string
}

/** Reconcile retention with the CURRENT connection set: pin new connections,
 *  release removed ones. Runs on every drain/roster connection fetch. */
function syncRelayRetention(connections: RelayConnection[]) {
  if (typeof host.retainProfileSocket !== 'function') {
    return
  }

  const live = new Set(connections.map(connection => JSON.stringify(connection.route)))

  for (const [id, release] of [...relayRouteRetentions]) {
    if (!live.has(id)) {
      relayRouteRetentions.delete(id)

      try {
        release()
      } catch {
        // Never let a release failure break the relay loop.
      }
    }
  }

  if (relay.disposed) {
    return
  }

  for (const connection of connections) {
    if (!relayRouteRetentions.has(JSON.stringify(connection.route))) {
      relayRouteRetentions.set(JSON.stringify(connection.route), host.retainProfileSocket(connection.route))
    }
  }
}

/** Drop every relay pin — stop/dispose path. */
function releaseRelayRetention() {
  for (const release of relayRouteRetentions.values()) {
    try {
      release()
    } catch {
      // Disposer from an older shell shape — never break teardown.
    }
  }

  relayRouteRetentions.clear()
}

/** Every relay-eligible profile route, once each. The canonical gateway keeps a
 *  roster and an outbox per profile home, so drain/roster/pins are per ROUTE;
 *  the peer set (is there anything to relay between?) is per connection id. */
async function relayConnections(): Promise<RelayConnection[]> {
  if (typeof host.profileRoutes !== 'function' || typeof host.requestProfile !== 'function') {
    return []
  }

  try {
    const rawRoutes = await host.profileRoutes()
    const routes = relayEligibleRoutes(Array.isArray(rawRoutes) ? rawRoutes : [])
    const byConnection = new Map<string, ProfileRoute>()

    for (const route of routes) {
      const id = String(route?.connectionId || '')

      const key = JSON.stringify(route)

      if (id && !byConnection.has(key)) {
        byConnection.set(key, route)
      }
    }

    return [...byConnection.values()].map(route => ({
      id: route.connectionId,
      route
    }))
  } catch {
    return []
  }
}

/** Distinct connections among the relay routes: profiles of one connection are not peers. */
function peerCount(connections: RelayConnection[]): number {
  return new Set(connections.map(connection => connection.id)).size
}

/** Human label per connection id, from the registry — the only place that has one.
 *  A `host.profileRoutes()` route carries identity alone, so without this the roster a
 *  peer gateway shows its bots ("@chii on 127-0-0-1-9119", tools/bot_mode_probe.py) and
 *  its refusal text name machines by raw connection id. A build with no registry rejects
 *  the call, and ids stay. */
async function connectionLabels(): Promise<Map<string, string>> {
  if (typeof host.connections !== 'function') {
    return new Map()
  }

  try {
    const rows = await host.connections()

    return new Map(
      (Array.isArray(rows) ? rows : [])
        .map(row => [String(row?.id || ''), String(row?.label || '').trim()] as const)
        .filter(([id, label]) => Boolean(id && label))
    )
  } catch {
    return new Map()
  }
}

/** The agents living on one connection, as relay roster rows.
 *  Returns null on FAILURE (transient RPC blip, slow socket) — distinct from
 *  a genuine empty profile list. Conflating the two would push a fresh union
 *  roster missing a LIVE connection's agents, and the gateway-side liveness
 *  check (bot_relay._target_liveness) reads "absent from a fresh roster" as
 *  definitively offline → false runtime_offline refusals (#93091 item 2). */
async function relayAgentsOn(
  connection: RelayConnection,
  labels: Map<string, string>
): Promise<RelayAgentRow[] | null> {
  try {
    const res = await host.requestProfile<{ install_id?: string; profiles?: RosterRow[] }>(
      connection.route,
      'profiles.list',
      {
        include_sessions: false
      }
    )

    const profiles = Array.isArray(res?.profiles) ? res.profiles : []
    // This connection's default is @hermes only while it has no real 'hermes' profile.
    const hermesTaken = profiles.some(profile => profile?.name === 'hermes')
    const label = labels.get(connection.id) || connection.id

    const rows = profiles
      .map(profile => ({
        profile: String(profile?.name || ''),
        handle: botHandle(
          profile?.name,
          hermesTaken && profile?.name === 'default' ? { ...profile, hermesHandleTaken: true } : profile
        ),
        connection_id: connection.id,
        connection_label: label,
        title: String(profile?.ui_meta?.['hermes-bots']?.title || profile?.display_name || ''),
        description: String(profile?.description || '')
      }))
      .filter(row => row.profile)

    host.traceIdentityChange?.('bot-relay', `rows ${connection.id}`, rosterTrace(rows, String(res?.install_id || '')))

    return rows
  } catch {
    return null
  }
}

/** Which connection last answered from each install: a second connection
 *  answering from the same machine is a misrouted request (or one machine
 *  registered twice) and is flagged in the trace. */
const answeringInstall = new Map<string, string>()

function rosterTrace(rows: RelayAgentRow[], installId: string): string {
  const connectionId = rows[0]?.connection_id ?? ''
  const other = installId ? answeringInstall.get(installId) : undefined
  const flag = other && other !== connectionId ? `MISROUTED (same install as ${other}) ` : ''

  if (installId && connectionId && !flag) {
    answeringInstall.set(installId, connectionId)
  }

  return `${flag}install=${installId.slice(0, 8) || '-'} n=${rows.length} [${rows.map(row => `${row.connection_id}/${row.profile}=${JSON.stringify(row.title)}`).join(' ')}]`
}

/** Last good agent rows per connection id — reused when a fetch blips so a
 *  transient failure never reads as "everyone on that machine went away".
 *  The sweep below drops disconnected ids, but only on a cycle that had two
 *  or more connections to relay between; the ceiling is what bounds the rest.
 *  Every live connection is rewritten each cycle, so eviction can only ever
 *  reach ids that stopped being fetched. */
const RELAY_AGENTS_CACHE_MAX = 32
const relayAgentsCache = new LruCache<string, RelayAgentRow[]>(RELAY_AGENTS_CACHE_MAX)

/** Push every gateway the union roster of agents on the OTHER connections. */
async function syncRelayRosters() {
  if (relay.disposed || relay.rosterBusy || !relayBotModeOn()) {
    return
  }

  relay.rosterBusy = true
  const generation = relay.rosterGeneration
  const isCurrent = () => !relay.disposed && relay.rosterGeneration === generation && relayBotModeOn()

  try {
    const connections = await relayConnections()

    if (!isCurrent()) {
      return
    }

    // A connection removed and re-added under a new id answers from the same
    // install; remembering the departed id flagged the replacement MISROUTED.
    const live = new Set(connections.map(connection => connection.id))

    for (const [install, connectionId] of answeringInstall) {
      if (!live.has(connectionId)) {
        answeringInstall.delete(install)
      }
    }

    const labels = await connectionLabels()

    if (!isCurrent()) {
      return
    }

    if (peerCount(connections) < 2) {
      // Nothing to relay — but the gateways that remain still hold the last
      // pushed roster, so a departed machine's agents would stay in every
      // bot's prompt (and as message_agent targets) until a second connection
      // reappears. Push the now-empty roster once per sole connection so it
      // forgets it — a replacement sole connection has never been told. An
      // empty route list (registry not loaded yet) must not spend the clear.
      if (peerCount(connections) === 1 && connections[0].id !== relay.rosterClearedFor) {
        const cleared = await Promise.all(
          connections.map(async connection => {
            if (!isCurrent()) {
              return false
            }

            try {
              await host.requestProfile(connection.route, 'bot_relay.roster.sync', { agents: [] })

              return true
            } catch {
              // An older backend without the relay RPCs, but also a socket that is not up yet —
              // requestProfile throws for both. Either way this gateway still holds the departed
              // machine's agents, so the clear is NOT spent and the next tick tries again.
              return false
            }
          })
        )

        // Spend it only once every gateway has actually forgotten.
        if (isCurrent() && cleared.every(Boolean)) {
          relay.rosterClearedFor = connections[0].id
        }
      }

      return
    }

    relay.rosterClearedFor = null

    const agentsByConnection = new Map<string, RelayAgentRow[]>()
    // One profiles.list per connection: its routes share a socket and answer one profile set.
    const firstRoutes = connections.filter((connection, index) => connections.findIndex(other => other.id === connection.id) === index)
    await Promise.all(
      firstRoutes.map(async connection => {
        const agents = await relayAgentsOn(connection, labels)

        if (!isCurrent()) {
          return
        }

        if (agents === null) {
          // Transient fetch failure: reuse the last good rows for this
          // connection (or contribute nothing this cycle) so the pushed
          // roster never drops a live machine's agents — absence from a
          // fresh roster means offline to the gateway-side fail-fast.
          agentsByConnection.set(connection.id, relayAgentsCache.get(connection.id) || [])
        } else {
          relayAgentsCache.set(connection.id, agents)
          agentsByConnection.set(connection.id, agents)
        }
      })
    )

    if (!isCurrent()) {
      return
    }

    // Connections gone from profileRoutes are genuinely disconnected — drop
    // their cache so a later reconnect starts from live data.
    const liveIds = new Set(connections.map(connection => connection.id))

    for (const id of [...relayAgentsCache.keys()]) {
      if (!liveIds.has(id)) {
        relayAgentsCache.delete(id)
      }
    }

    await Promise.all(
      connections.map(async connection => {
        if (!isCurrent()) {
          return
        }

        const others: RelayAgentRow[] = []

        for (const [id, agents] of agentsByConnection) {
          if (id !== connection.id) {
            others.push(...agents)
          }
        }

        try {
          await host.requestProfile(connection.route, 'bot_relay.roster.sync', {
            agents: others
          })
        } catch {
          // Older backend without the relay RPCs — skip this connection.
        }
      })
    )
  } finally {
    if (relay.rosterGeneration === generation) {
      relay.rosterBusy = false
    }
  }
}

/** Drain every gateway's outbox and deliver each envelope on the target
 *  connection's own socket; the reply (or error) is posted back to the
 *  sender gateway for its waiter. */
async function drainRelayOutboxes() {
  if (relay.disposed || !relayBotModeOn()) {
    return
  }

  if (relay.drainBusy) {
    // A push signal raced an in-flight drain. The gateway never re-sends it
    // (monotone signature), so without this flag the envelope would wait out
    // the full poll interval — exactly the latency the push path removes.
    relay.drainRerun = true

    return
  }

  relay.drainBusy = true

  try {
    const connections = await relayConnections()

    // Retention follows the relay-eligible set: with fewer than two
    // connections there is nothing to relay, so nothing stays pinned.
    syncRelayRetention(peerCount(connections) >= 2 ? connections : [])

    if (peerCount(connections) < 2) {
      return
    }

    // A shell with the push door already knows which routes have mail. Do not
    // open a throwaway socket to ask a route that has not signaled — Bot Mode
    // off is the early return above; no outbox work is this skip (#118856).
    // Older shells have no event, so the interval remains their only drain.
    const pushDoor = typeof host.onEvent === 'function'
    const work = pushDoor ? takeRelayOutboxWork() : { any: true, ids: new Set<string>() }

    const byId = new Map(connections.map(connection => [connection.id, connection]))

    // Phase 1 — claim every gateway's outbox before delivering anything. The
    // gateway checks an envelope's age against bot_mode.envelope_ttl_seconds
    // AT the claim, so a claim must never wait behind another gateway's
    // delivery turn: draining and delivering sender by sender let one long
    // turn (up to RELAY_DELIVER_TIMEOUT_MS) age a sibling gateway's envelope
    // past the TTL before it was even claimed, and that sender's waiter got
    // `queued_expired` for a message nothing was wrong with.
    const queued: RelayQueuedEnvelope[] = []

    for (const sender of connections) {
      if (pushDoor && !routeSignaledOutboxWork(sender.id, work)) {
        continue
      }

      try {
        const res = await host.requestProfile<{ envelopes?: RelayEnvelope[] }>(
          sender.route,
          'bot_relay.outbox.drain',
          {}
        )

        const pending = pendingRelaysFor(sender)

        for (const envelope of Array.isArray(res?.envelopes) ? res.envelopes : []) {
          if (envelope.id && !pending.has(envelope.id)) {pending.set(envelope.id, structuredClone(envelope))}
        }

        // Every claimed-but-unACKed envelope rides again: a delivery that
        // settled without an exact identity, or whose ACK was lost, retries
        // from the sender's pin instead of being silently dropped.
        for (const envelope of pending.values()) {
          queued.push({ envelope, sender })
        }
      } catch {
        // Older backend without the relay RPCs — skip this connection.
      }
    }

    // Phase 2 — deliver, without holding the drain. Envelopes for the same
    // target profile stay in order, one turn at a time (the target gateway
    // serialises that profile's turns behind its turn lock anyway; a second
    // envelope sent while the first runs would only burn its lock-wait
    // budget). Different targets run concurrently, so one long turn never
    // holds every other bot's mail. The lanes outlive this drain: `drainBusy`
    // covers the claim only, so a push that lands while a turn runs claims
    // its envelope NOW instead of after that turn — otherwise the TTL clock
    // kept running against a message the Desktop had not even looked at.
    for (const { envelope, sender } of queued) {
      enqueueRelayDelivery(sender, envelope, byId)
    }
  } finally {
    relay.drainBusy = false

    if (relay.drainRerun && !relay.disposed) {
      // Envelopes signaled mid-drain: schedule one follow-up pass (debounced)
      // instead of leaving them to the interval poll.
      relay.drainRerun = false
      scheduleRelayPushDrain()
    }
  }
}

interface RelayQueuedEnvelope {
  envelope: RelayEnvelope
  sender: RelayConnection
}

// Delivery lanes: `target_connection::target_profile` → the tail of that
// target's in-flight deliveries. A lane entry is removed once its tail
// settles so an idle target holds no state.
const relayLanes = new Map<string, Promise<void>>()

/** Queue one claimed envelope behind the deliveries already running for the
 *  same target profile; other targets are untouched. */
function enqueueRelayDelivery(sender: RelayConnection, envelope: RelayEnvelope, byId: Map<string, RelayConnection>) {
  const key = `${String(envelope?.target_connection || '')}::${String(envelope?.target_profile || '')}`

  const tail = (relayLanes.get(key) ?? Promise.resolve()).then(() =>
    relay.disposed ? undefined : deliverRelayEnvelope(sender, envelope, byId)
  )

  relayLanes.set(key, tail)
  void tail.finally(() => {
    if (relayLanes.get(key) === tail) {
      relayLanes.delete(key)
    }
  })
}

function relayDeliverParams(sender: RelayConnection, envelope: RelayEnvelope, envelopeId: string) {
  return {
    id: envelopeId,
    profile: String(envelope?.target_profile || ''),
    message: String(envelope?.message || ''),
    from_profile: String(envelope?.from_profile || ''),
    from_handle: String(envelope?.from_handle || ''),
    from_connection: String(sender.id)
  }
}

type RelayDeliverResult = {
  status?: string
  delivery_id?: string
  admission_id?: string | null
  refused?: true | null
  reply?: string
  error?: string
  reason?: string
}

/** Act on a `bot_relay.deliver` answer: only a settled/failed receipt for THIS
 *  envelope posts back; anything else stays retained for recovery. A receipt
 *  names its admission, or is `refused` (terminal `failed`, nothing admitted). */
async function settleRelayDelivery(
  res: RelayDeliverResult,
  envelopeId: string,
  attentionKey: string,
  postReply: (payload: { error?: string; reason?: string; reply?: string }) => Promise<void>
) {
  const refused = res.refused === true && res.status === 'failed'

  if (res.delivery_id !== envelopeId || !(res.admission_id || refused)) {
    noteBotAttention(attentionKey, 'Delivery identity unavailable; retained for recovery')

    return
  }

  if (res.status !== 'settled' && res.status !== 'failed') {
    if (res.status === 'ambiguous') {noteBotAttention(attentionKey, 'unknown_execution')}

    return
  }

  if (res.status === 'failed') {
    noteBotAttention(attentionKey, res.reason || res.error || 'delivery failed')
    await postReply({ error: res.error || res.reply || 'delivery failed', reason: res.reason })

    return
  }

  clearBotAttention(attentionKey)
  await postReply({
    reply: String(res?.reply || '')
  })
}

/** Deliver one claimed envelope on the target connection's own socket and post
 *  the reply (or the error) back to the sender gateway for its waiter. */
async function deliverRelayEnvelope(
  sender: RelayConnection,
  envelope: RelayEnvelope,
  byId: Map<string, RelayConnection>
) {
  const envelopeId = String(envelope?.id || '')
  const target = byId.get(String(envelope?.target_connection || ''))
  const pending = pendingRelaysFor(sender)

  // A later drain re-queues every pinned envelope; the lane serialises them, so
  // one already ACKed by an earlier delivery in this lane must not ride twice.
  if (!envelopeId || !pending.has(envelopeId)) {
    return
  }

  const postReply = async (payload: { error?: string; reason?: string; reply?: string }) => {
    try {
      await host.requestProfile(sender.route, 'bot_relay.reply', {
        id: envelopeId,
        ...payload
      })
      pending.delete(envelopeId)
    } catch {
      // Sender gateway unreachable — its waiter times out with guidance.
    }
  }

  if (!target) {
    await postReply({
      error: `connection '${envelope?.target_connection}' is not connected to this Desktop right now`
    })

    return
  }

  // Needs-attention hook (#93091 item 3): a delivered background DM is
  // this bot's "good turn"; a classified delivery failure badges it.
  const attentionKey = `${target.id}::${String(envelope?.target_profile || '')}`

  try {
    const res = await host.requestProfile<RelayDeliverResult>(
      { ...target.route, profile: String(envelope.target_profile), targetProfile: String(envelope.target_profile) },
      'bot_relay.deliver',
      relayDeliverParams(sender, envelope, envelopeId),
      RELAY_DELIVER_TIMEOUT_MS
    )

    await settleRelayDelivery(res, envelopeId, attentionKey, postReply)
  } catch (error: any) {
    // #93091: bot_relay.deliver classifies the failed turn and ships the
    // typed code in the JSON-RPC error's `data.reason`; forward it into
    // the sender-side reply file so the waiter (and the sending agent)
    // get the machine-readable cause, and prefer it for the badge —
    // classified codes beat free-text re-parsing.
    const reason = String(error?.data?.reason || '').trim()
    noteBotAttention(attentionKey, reason || error?.message || error)

    // A transport exception can follow a committed admission; never settle it as failure.
    if (!reason || reason === 'runtime_unavailable') {return}
    await postReply({
      error: String(error?.message || error || 'delivery failed'),
      ...(reason
        ? {
            reason
          }
        : {})
    })
  }
}

/** Push-notified drain (#93091): collapse a burst of pending signals into
 *  one drain call ~RELAY_PUSH_DEBOUNCE_MS after the first signal. */
function scheduleRelayPushDrain() {
  if (relay.disposed || typeof setTimeout !== 'function') {
    return
  }

  if (relay.pushDebounceTimer !== null) {
    return
  }

  relay.pushDebounceTimer = setTimeout(() => {
    relay.pushDebounceTimer = null
    void drainRelayOutboxes()
  }, RELAY_PUSH_DEBOUNCE_MS)
}

export function startBotRelay() {
  relay.disposed = false
  relay.rosterClearedFor = null

  // Source-shape test harnesses evaluate plugin.js without DOM timers —
  // the relay only runs where a real event loop exists.
  if (typeof setInterval !== 'function' || typeof clearInterval !== 'function') {
    return
  }

  if (relay.rosterTimer === null) {
    relay.rosterTimer = setInterval(() => void syncRelayRosters(), RELAY_ROSTER_INTERVAL_MS)
    void syncRelayRosters()
  }

  if (relay.drainTimer === null) {
    relay.drainTimer = setInterval(() => void drainRelayOutboxes(), RELAY_DRAIN_INTERVAL_MS)
  }

  // Push path: the gateway change watcher broadcasts when an envelope hits
  // the outbox; drain immediately (debounced) instead of waiting the poll
  // out. Feature-detected — older shells have no host.onEvent — and only
  // those shells still open a socket from the interval. A signaled event
  // names its connection when the renderer stamped one; an untagged event
  // (local/legacy primary) may belong to any route.
  if (relay.pushUnsub === null && typeof host.onEvent === 'function') {
    relay.pushUnsub = host.onEvent('bot_relay.outbox.pending', event => {
      noteRelayOutboxWork(event)
      scheduleRelayPushDrain()
    })
  }
}

export function stopBotRelay() {
  relay.disposed = true
  relay.rosterGeneration += 1
  relay.rosterBusy = false
  // A rerun remembered mid-drain must not leak into the next start —
  // it would fire one stale drain after restart.
  relay.drainRerun = false
  routesWithOutboxWork.clear()
  // Queued deliveries check `disposed` before they run; forget the lane tails
  // so a restart starts every target fresh instead of behind stale chains.
  relayLanes.clear()
  // Unpin every relay-retained socket (#93594): with the relay stopped the
  // pooled entries return to dispose-at-refcount-0 semantics.
  releaseRelayRetention()

  if (relay.rosterTimer !== null) {
    clearInterval(relay.rosterTimer)
    relay.rosterTimer = null
  }

  if (relay.drainTimer !== null) {
    clearInterval(relay.drainTimer)
    relay.drainTimer = null
  }

  if (relay.pushDebounceTimer !== null) {
    clearTimeout(relay.pushDebounceTimer)
    relay.pushDebounceTimer = null
  }

  if (relay.pushUnsub !== null) {
    try {
      relay.pushUnsub()
    } catch {
      // Disposer from an older shell shape — never break teardown.
    }

    relay.pushUnsub = null
  }
}