Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
66.4 KB
Raw Blame
import { Router } from 'express'
import type { Response as ExpressResponse, NextFunction } from 'express'
import { randomUUID } from 'crypto'
import { config } from '../config.js'
import {
  type AuthedRequest,
  extractAuthToken,
  requireRpcAuth,
  requireScope,
} from '../middleware/auth.js'
import { chatJsonBody } from '../middleware/chatJsonBody.js'
import { jsonBody } from '../middleware/jsonBody.js'
import { rpcInvocationContext } from '../rpcAccessContext.js'
import {
  ControlApiConnectorsRejectedError,
  type HostWakeApiResponse,
  fetchUserConnectorsFromControlApi,
  requestHostWakeFromControlApi,
} from '../services/controlApiRestService.js'
import {
  type HostAccessDenialCode,
  isHostAccessDenied,
  respondHostAccessDenied,
  withoutReservedHostAccessCode,
} from '../services/hostAccessDenial.js'
import {
  type HostRuntimeMessageRequest,
  forwardCancelToHost,
  forwardHostActivity,
  forwardHostHealth,
  forwardHostMessageToHost,
  forwardHostStatus,
  forwardRpcToServer,
  forwardTaskResultFromHost,
  listAllowedServersForUser,
  resolveHostConnectionForUser,
  resolveServerConnectionForUser,
  validateRpcRequest,
} from '../services/mcpProxyService.js'
import { readMutatingResponseBody } from '../services/upstreamBody.js'
import {
  describeErrorForLog,
  isHostPayloadTooLargeError,
  isUpstreamTimeoutError,
  isWakeEligibleHostError,
  respondWithWakeAndHold,
  sanitizeHostRefForLog,
} from '../services/wakeAndHold.js'
import { mintOrReuseDirectTraceContext } from '../traceContext.js'

const RFC1123_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/

// Edge caps on the client-supplied page size before forwarding upstream. The
// host enforces its own identical caps independently; these are the proxy's
// own copy (the two services share no package, so each names its own).
const SESSIONS_LIMIT_CAP = 100
const MESSAGES_LIMIT_CAP = 200

function isSafeUpstreamPathSegment(value: string): boolean {
  return (
    value.length > 0 &&
    value !== '.' &&
    value !== '..' &&
    value.length <= 500 &&
    !/[/\\\u0000-\u001f\u007f]/.test(value)
  )
}

function isSafeUpstreamAgentSegment(value: string): boolean {
  return isSafeUpstreamPathSegment(value) && value.length <= 200 && !value.includes(':')
}

function parseUnsignedIntegerQuery(value: unknown): number | undefined | null {
  if (value === undefined) return undefined
  if (typeof value !== 'string' || !/^\d+$/.test(value)) return null
  const parsed = Number(value)
  return Number.isSafeInteger(parsed) ? parsed : null
}

/**
 * Pre-wake host error mapping: fetch timeout → 504, everything else → 502.
 *
 * Guards `res.headersSent` (§11.5): this is the terminal responder that
 * route-level outer catches invoke after a held request may already have
 * committed a response. A second write here is the ERR_HTTP_HEADERS_SENT /
 * duplicate-terminal-response bug, so it becomes a loud no-op instead.
 */
export function respondUpstreamUnavailable(res: ExpressResponse, error: unknown): void {
  if (res.headersSent) {
    console.warn(
      `[RPC_PROXY] suppressing duplicate terminal response (upstream-unavailable): ${describeErrorForLog(
        error
      )}`
    )
    return
  }
  if (isUpstreamTimeoutError(error)) {
    res.status(504).json({ error: 'Gateway Timeout' })
    return
  }
  res.status(502).json({ error: 'Upstream host unavailable' })
}

/**
 * Terminal mapping for a failed Host message forward, on the first attempt and
 * on the post-wake retry alike. A Host 413 is the client's body to fix, not an
 * unavailable Host: it gets the same body as chatJsonBody's own 413, so the
 * Desktop maps a Host refusal and a proxy refusal identically. Everything else
 * keeps the respondUpstreamUnavailable mapping, including its headersSent guard.
 */
function respondHostMessageForwardFailure(res: ExpressResponse, error: unknown): void {
  if (isHostPayloadTooLargeError(error) && !res.headersSent) {
    res.status(413).json({ error: 'Payload Too Large' })
    return
  }
  respondUpstreamUnavailable(res, error)
}

/**
 * Guards a `next(error)` handoff against a committed response (§11.5). Express
 * routes an error to the default handler which, when headers are already sent,
 * aborts the socket; suppress it loudly instead so a held request that already
 * wrote its terminal response is never double-terminated.
 */
function guardedNext(res: ExpressResponse, next: NextFunction, error: unknown): void {
  if (res.headersSent) {
    console.warn(`[RPC_PROXY] suppressing post-response route error: ${describeErrorForLog(error)}`)
    return
  }
  next(error)
}

/**
 * The single writer of a relayed mcp-host response body. Every passthrough
 * route answers through here so an upstream 403 can never carry the reserved
 * Host-access `code` that only respondHostAccessDenied may set. `contentType`
 * is set only by the routes that relay the upstream content type.
 */
function sendUpstreamBody(
  res: ExpressResponse,
  status: number,
  body: string,
  contentType?: string
): void {
  res.status(status)
  if (contentType !== undefined) res.type(contentType)
  res.send(withoutReservedHostAccessCode(status, body))
}

/**
 * A 503 carrying mcp-host's `host_draining` fence is a wake-eligible upstream
 * error, not a client-visible failure: convert it so the finite routes below
 * can hand it to respondWithWakeAndHold.
 */
function sessionDrainingFence(response: Response, body: string): Error | null {
  if (response.status !== 503 || !body.includes('host_draining')) return null
  return Object.assign(new Error('Upstream host returned draining fence'), {
    name: 'UpstreamHostError',
    status: response.status,
    bodySnippet: body,
  })
}

export type ControlApiHostAccessRejection =
  | { status: 401 | 409 }
  | { status: 403; code: HostAccessDenialCode }

function controlApiHostAccessRejection(error: unknown): ControlApiHostAccessRejection | null {
  if (!(error instanceof Error) || error.name !== 'ControlApiHostAccessRejectedError') {
    return null
  }
  const { status, denialCode } = error as Error & { status?: unknown; denialCode?: unknown }
  if (status === 401 || status === 409) return { status }
  if (
    status === 403 &&
    (denialCode === 'host_access_revoked' || denialCode === 'host_access_denied')
  ) {
    return { status, code: denialCode }
  }
  return null
}

export function respondControlApiHostAccessRejection(
  res: ExpressResponse,
  rejection: ControlApiHostAccessRejection
): void {
  if (res.headersSent) {
    console.warn(
      `[RPC_PROXY] suppressing duplicate terminal response (host-access-rejection ${rejection.status})`
    )
    return
  }
  if (rejection.status === 401) {
    res.status(401).json({ error: 'Unauthorized' })
    return
  }
  if (rejection.status === 403) {
    respondHostAccessDenied(res, rejection.code)
    return
  }
  res.status(409).json({ error: 'Direct run attribution conflict' })
}

/**
 * Abort signal for a MUTATING upstream call (approve, deny, set-model, task
 * cancel). The first attempt has no client-side timeout by design: aborting a
 * request the upstream may already have applied would answer 504 for a change
 * that took effect, and the user's retry would then hit "No pending approval".
 * Only a wake-and-hold retry passes `timeoutMs`, bounded by the hold deadline;
 * session rename, which has no wake retry, passes its plain upstream timeout.
 * A client that disconnects before the response is written aborts the call on
 * every attempt, so a gone client never pins the upstream socket.
 */
function mutatingCallSignal(timeoutMs: number | undefined, res: ExpressResponse): AbortSignal {
  const clientGone = new AbortController()
  // A client can leave while the host is still being resolved; its 'close'
  // has already fired by now, so a listener alone would never see it.
  if (res.closed && !res.writableFinished) {
    clientGone.abort(new Error('client disconnected'))
  }
  res.once('close', () => {
    if (!res.writableFinished) clientGone.abort(new Error('client disconnected'))
  })
  return timeoutMs === undefined
    ? clientGone.signal
    : AbortSignal.any([clientGone.signal, AbortSignal.timeout(timeoutMs)])
}

class ProxyArtifactTooLargeError extends Error {
  constructor(readonly maxBytes: number) {
    super(`Artifact too large to download: max ${maxBytes} bytes`)
    this.name = 'ProxyArtifactTooLargeError'
  }
}

async function cancelResponseBody(response: Response): Promise<void> {
  try {
    await response.body?.cancel()
  } catch {
    /* best effort only */
  }
}

async function readArtifactResponseBuffer(response: Response): Promise<Buffer> {
  const maxBytes = config.artifactDownloadMaxBytes
  const contentLength = response.headers.get('content-length')
  if (contentLength) {
    const declaredBytes = Number(contentLength)
    if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
      await cancelResponseBody(response)
      throw new ProxyArtifactTooLargeError(maxBytes)
    }
  }

  if (!response.body) {
    const arrayBuffer = await response.arrayBuffer()
    if (arrayBuffer.byteLength > maxBytes) throw new ProxyArtifactTooLargeError(maxBytes)
    return Buffer.from(arrayBuffer)
  }

  const reader = response.body.getReader()
  const chunks: Buffer[] = []
  let totalBytes = 0

  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    if (!value) continue
    totalBytes += value.byteLength
    if (totalBytes > maxBytes) {
      await reader.cancel()
      throw new ProxyArtifactTooLargeError(maxBytes)
    }
    chunks.push(Buffer.from(value))
  }

  return Buffer.concat(chunks, totalBytes)
}

export function createRpcRouter(): Router {
  const router = Router()

  router.get(
    '/rpc/servers',
    requireRpcAuth,
    requireScope('mcp:servers:list'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const result = await listAllowedServersForUser(auth.sub, rpcAccessToken)
        res.status(200).json({
          userId: result.userId,
          contextIds: result.contextIds,
          servers: result.servers,
        })
      } catch (error) {
        next(error)
      }
    }
  )

  // Proactive connectors panel read-model (spec 11 U1): per-agent classified
  // fleet (`authorized`/`requires_setup`/`no_oauth`). Read of the same catalog
  // rail as `/rpc/servers`, so it REUSES the `mcp:servers:list` scope (no new
  // scope minted). `userId` is the signed session subject (`auth.sub`), never a
  // body/query param.
  //
  // SCOPE NOTE (review R1-SM2, owner decision): `mcp:servers:list` now spans two
  // result-sets. `/rpc/servers` returns the INVOCABLE set (control-api's
  // classifier filters via `filterInvocable`); this route returns the CLASSIFIED
  // set, a strict SUPERSET — it also lists disabled and static-auth servers, with
  // their authorization state. Not an escalation (the caller's own fleet,
  // non-secret policy only), but anyone granting this scope should know it now
  // covers both. See classifyConnector in control-api mcpInvocable.ts.
  router.get(
    '/rpc/connectors',
    requireRpcAuth,
    requireScope('mcp:servers:list'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const result = await fetchUserConnectorsFromControlApi(auth.sub, rpcAccessToken)
        res.status(200).json(result)
      } catch (error) {
        // Map a control-api 401/403 to a real status instead of the default
        // 500. A 500 is non-refreshable on the desktop (shouldRefreshRpcToken),
        // so an expired rpc access token surfaced as 500 would never trigger a
        // refresh and would leave the panel stuck. 401 keeps the refresh path
        // alive; everything else stays 500/504 via the app error handler.
        if (error instanceof ControlApiConnectorsRejectedError) {
          if (error.status === 401) {
            res.status(401).json({ error: 'Unauthorized' })
            return
          }
          res.status(403).json({ error: 'Forbidden: user cannot read connectors' })
          return
        }
        next(error)
      }
    }
  )

  router.post(
    '/rpc/:serverName',
    requireRpcAuth,
    requireScope('mcp:server:invoke'),
    jsonBody,
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const serverName = String(req.params.serverName || '').trim()
        if (!serverName) {
          res.status(400).json({ error: 'serverName is required' })
          return
        }

        const server = await resolveServerConnectionForUser(auth.sub, serverName, rpcAccessToken)
        if (!server) {
          res.status(403).json({ error: 'Forbidden: user cannot access this server' })
          return
        }

        const rpcRequest = validateRpcRequest(req.body)
        if (!rpcRequest) {
          res.status(400).json({ error: 'Invalid JSON-RPC request payload' })
          return
        }

        // Avoid logging params to prevent accidental sensitive data exposure.
        console.info(
          `[RPC_PROXY] user=${auth.sub} server=${serverName} method=${rpcRequest.method}`
        )

        const rpcResponse = await forwardRpcToServer(server, rpcRequest, auth.sub)
        res.status(200).json(rpcResponse)
      } catch (error) {
        next(error)
      }
    }
  )

  router.post(
    '/rpc/hosts/:hostRef/messages',
    requireRpcAuth,
    requireScope('host:message:invoke'),
    chatJsonBody,
    async (req: AuthedRequest, res) => {
      // Host runtime write path (REST-oriented):
      // - separate from read-only status stream
      // - explicitly scoped to host:message:invoke
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!isSafeUpstreamPathSegment(hostRef)) {
          res.status(400).json({ error: 'Invalid hostRef' })
          return
        }

        const body = req.body as HostRuntimeMessageRequest
        if (!body || typeof body !== 'object' || Array.isArray(body)) {
          res.status(400).json({ error: 'Invalid host message request payload' })
          return
        }
        if (typeof body.content !== 'string' || !body.content.trim()) {
          res.status(400).json({ error: 'Invalid host message request payload' })
          return
        }

        // Identity invariant: rpc-proxy is the sole authority on the Desktop
        // RPC envelope. Ignore client-supplied channel, sender, host, and
        // metadata values; derive them from the route and signed JWT.
        //
        // Per-request idempotency identity (D1): the delivery id must be UNIQUE
        // per inbound HTTP request, NOT a function of content. A content-hash
        // key would suppress legitimate duplicate turns — a user sending
        // identical content twice in one thread ("yes", "ok", "retry") within
        // mcp-host's dedup TTL would have the FIRST answer replayed and the 2nd
        // turn silently dropped.
        //
        // Prefer a client-supplied Idempotency-Key header when present (lets the
        // Desktop App scope its own retries); otherwise mint a fresh random
        // nonce. It is computed exactly ONCE here — before the first forward —
        // and carried on the single forwardedBody object reused by BOTH the
        // initial forward and the wake-and-hold retry (attemptUpstream reuses
        // the same object and never recomputes the id). So a socket-death retry
        // of ONE request re-presents the SAME messageId — mcp-host's admission
        // sink (MessageQueue.deliveryKeyOf) dedups it (duplicate_delivery →
        // replay) instead of re-executing the turn — while two DISTINCT sends
        // (even byte-identical content) get distinct ids and both execute.
        const clientIdempotencyKey =
          typeof req.headers['idempotency-key'] === 'string'
            ? req.headers['idempotency-key'].trim()
            : ''
        const deliveryMessageId = clientIdempotencyKey || randomUUID()
        const requestId =
          typeof req.headers['x-request-id'] === 'string'
            ? req.headers['x-request-id'].trim()
            : undefined
        const desktopSessionId =
          typeof body.threadId === 'string' ? body.threadId.trim() || undefined : undefined
        const traceContext = mintOrReuseDirectTraceContext({
          authorityScope: `${auth.sub}:${hostRef}`,
          deliveryId: deliveryMessageId,
          sessionId: desktopSessionId,
          requestId,
          origin: 'direct_chat',
        })
        if (body.attachments != null && !Array.isArray(body.attachments)) {
          res
            .status(400)
            .json({ error: 'invalid_attachments', message: 'Attachments must be a list.' })
          return
        }
        const forwardedBody: HostRuntimeMessageRequest = {
          content: body.content,
          channelType: 'rpc',
          channelId: hostRef,
          hostRef,
          sender: auth.sub,
          messageId: deliveryMessageId,
          metadata: rpcInvocationContext(auth),
          threadId: desktopSessionId,
          attachments: Array.isArray(body.attachments) ? body.attachments : undefined,
          ...(body.fileReferences === undefined ? {} : { fileReferences: body.fileReferences }),
          ...(body.modelSelectionRevision === undefined
            ? {}
            : { modelSelectionRevision: body.modelSelectionRevision }),
          traceContext,
          // R2 "Option A": thread the optional piggybacked per-session model.
          // This body is an explicit field allow-list, so an unlisted field is
          // dropped. Trimmed/empty values are omitted.
          ...(typeof body.model === 'string' && body.model.trim()
            ? { model: body.model.trim() }
            : {}),
        }

        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
          ...(traceContext.sessionId
            ? {
                directRunBinding: {
                  runId: traceContext.runId,
                  sessionId: traceContext.sessionId,
                  origin: traceContext.origin,
                },
              }
            : {}),
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        if (host.attributionBindingStatus === 'unavailable') {
          console.warn(
            JSON.stringify({
              event: 'governed_trace_operational_error',
              scope: 'agent_run',
              reason: 'attribution_binding_unavailable',
            })
          )
        }

        const isAsync = req.query.async === 'true'
        const attachmentCount = Array.isArray(forwardedBody.attachments)
          ? (forwardedBody.attachments as unknown[]).length
          : 0
        console.info(
          `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=host-message-rest${isAsync ? ' (async)' : ''} attachments=${attachmentCount}`
        )
        let upstreamResponse: Record<string, unknown> | null = null
        try {
          // Always use the configured upstream timeout for the first POST.
          // A separate statelessness pre-check would double-charge the
          // rate-limited wake endpoint and risk aborting a healthy send.
          // The wake path below already checks statelessness when a
          // connection-level failure triggers it.
          upstreamResponse = await forwardHostMessageToHost(host, forwardedBody, {
            async: isAsync,
          })
        } catch (error) {
          console.warn(
            `[RPC_PROXY] host message forward failed host=${sanitizeHostRefForLog(hostRef)} error=${describeErrorForLog(
              error
            )}`
          )
          if (isWakeEligibleHostError(error)) {
            // Stateless wake-and-hold: a down or draining host triggers a
            // control-api wake (and possibly a bounded hold) instead of the
            // generic 502. Non-stateless hosts fall back to the legacy path.
            await respondWithWakeAndHold({
              res,
              hostRef,
              host,
              claims: auth,
              rpcAccessToken,
              deadlineMs: wakeDeadlineMs,
              // The per-request messageId makes a re-presented POST a
              // duplicate_delivery replay, so retrying until the deadline is safe.
              retryUntilDeadline: true,
              attemptUpstream: async timeoutMs => {
                const retried = await forwardHostMessageToHost(host, forwardedBody, {
                  async: isAsync,
                  timeoutMs,
                })
                res.status(200).json(retried)
              },
              respondLegacy: legacyError => respondHostMessageForwardFailure(res, legacyError),
            })
            return
          }
          respondHostMessageForwardFailure(res, error)
          return
        }
        // The upstream accepted the message: the request is resolved. Writing
        // the success response OUTSIDE the catch above guarantees a failure in
        // the write itself can never be classified as "host down" and re-enter
        // the wake path (which would re-forward an already-delivered message).
        res.status(200).json(upstreamResponse)
      } catch (error) {
        const rejection = controlApiHostAccessRejection(error)
        if (rejection) {
          respondControlApiHostAccessRejection(res, rejection)
          return
        }
        console.warn(
          `[RPC_PROXY] host message forward failed host=${sanitizeHostRefForLog(String(req.params.hostRef || '').trim())} error=${describeErrorForLog(
            error
          )}`
        )
        respondUpstreamUnavailable(res, error)
      }
    }
  )

  // Pre-warm a suspended stateless host. The Desktop App calls this when the
  // user opens the agent view so the cold wake overlaps with the user reading
  // history/typing. Fire-and-forget: control-api owns dedup/coalescing/
  // rate-limiting and the monotonic wake generation — this route only passes
  // its answer through. NO hold and NO readiness polling here (that is the
  // held-request path in wakeAndHold.ts).
  router.post(
    '/rpc/hosts/:hostRef/wake',
    requireRpcAuth,
    requireScope('host:wake:write'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!isSafeUpstreamPathSegment(hostRef)) {
          res.status(400).json({ error: 'Invalid hostRef' })
          return
        }

        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }

        console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=host-wake`)
        let wake: HostWakeApiResponse
        try {
          wake = await requestHostWakeFromControlApi(hostRef, rpcAccessToken)
        } catch (error) {
          console.warn(
            `[RPC_PROXY] host wake request failed host=${hostRef} error=${
              error instanceof Error ? error.message : String(error)
            }`
          )
          res.status(502).json({ error: 'Control API host wake unavailable' })
          return
        }

        switch (wake.kind) {
          case 'active':
            res.status(200).json({
              status: 'active',
              ...(wake.wakeGeneration !== null ? { wakeGeneration: wake.wakeGeneration } : {}),
            })
            return
          case 'wake-requested':
            res.status(202).json({
              status: 'wake-requested',
              ...(wake.wakeGeneration !== null ? { wakeGeneration: wake.wakeGeneration } : {}),
            })
            return
          case 'not-stateless':
            res.status(409).json({ status: 'not-stateless' })
            return
          case 'unknown':
            res.status(404).json({ status: 'unknown' })
            return
          case 'rate-limited':
            res.setHeader('Retry-After', String(Math.max(1, Math.ceil(wake.retryAfterSeconds))))
            res.status(429).json({
              error: 'Host wake rate limited',
              retryAfterSeconds: wake.retryAfterSeconds,
            })
            return
          case 'auth':
            // control-api rejected the caller's rpc access token — mirror it.
            res.status(wake.status).json({ error: 'Control API rejected the rpc access token' })
            return
          default: {
            // Exhaustiveness guard: a future HostWakeApiResponse kind must
            // answer 502 instead of leaving the request hanging until the
            // client times out.
            const unhandledWake: never = wake
            void unhandledWake
            console.warn(`[RPC_PROXY] unhandled host wake response kind host=${hostRef}`)
            res.status(502).json({ error: 'Unhandled wake response' })
            return
          }
        }
      } catch (error) {
        next(error)
      }
    }
  )

  // Approve tool execution
  router.post(
    '/rpc/hosts/:hostRef/approvals/approve',
    requireRpcAuth,
    requireScope('host:approval:write'),
    jsonBody,
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        // Translate Desktop App fields → mcp-host approval API fields.
        // Identity is always the JWT auth.sub (server-assigned, matches the
        // sender that was stamped onto the original message).
        const parsed = req.body as Record<string, unknown>
        const upstreamBody = {
          userId: auth.sub,
          requestId: parsed.toolCallId || parsed.requestId,
          alwaysApprove: parsed.alwaysApprove || false,
        }
        // Wake-eligible finite operation (§11.4): the route scope stays
        // host:approval:write; wake capability rides on the token. A suspended
        // (network-down) or draining Host triggers a wake-and-hold instead of a
        // bare next(error)/passthrough.
        const attempt = async (timeoutMs?: number) => {
          const response = await fetch(`${baseUrl}/v1/runtime/approvals/approve`, {
            method: 'POST',
            headers: { 'content-type': 'application/json', ...host.headers },
            body: JSON.stringify(upstreamBody),
            signal: mutatingCallSignal(timeoutMs, res),
          })
          const body = await readMutatingResponseBody(response)
          const draining = sessionDrainingFence(response, body)
          if (draining) throw draining
          sendUpstreamBody(res, response.status, body)
        }
        try {
          await attempt()
        } catch (error) {
          if (!isWakeEligibleHostError(error)) throw error
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            attemptUpstream: attempt,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // Deny tool execution
  router.post(
    '/rpc/hosts/:hostRef/approvals/deny',
    requireRpcAuth,
    requireScope('host:approval:write'),
    jsonBody,
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        // Translate Desktop App fields → mcp-host denial API fields.
        // Identity is always the JWT auth.sub (server-assigned, matches the
        // sender that was stamped onto the original message).
        const parsed = req.body as Record<string, unknown>
        const upstreamBody = {
          userId: auth.sub,
          requestId: parsed.toolCallId || parsed.requestId,
        }
        // Wake-eligible finite operation (§11.4): scope stays host:approval:write.
        const attempt = async (timeoutMs?: number) => {
          const response = await fetch(`${baseUrl}/v1/runtime/approvals/deny`, {
            method: 'POST',
            headers: { 'content-type': 'application/json', ...host.headers },
            body: JSON.stringify(upstreamBody),
            signal: mutatingCallSignal(timeoutMs, res),
          })
          const body = await readMutatingResponseBody(response)
          const draining = sessionDrainingFence(response, body)
          if (draining) throw draining
          sendUpstreamBody(res, response.status, body)
        }
        try {
          await attempt()
        } catch (error) {
          if (!isWakeEligibleHostError(error)) throw error
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            attemptUpstream: attempt,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // List sessions for the authenticated user — passthrough to mcp-host /v1/runtime/sessions.
  router.get(
    '/rpc/hosts/:hostRef/sessions',
    requireRpcAuth,
    requireScope('host:session:read'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!isSafeUpstreamPathSegment(hostRef)) {
          res.status(400).json({ error: 'Invalid hostRef' })
          return
        }
        const rawSessionAgent = req.query.agent
        const sessionAgent =
          typeof rawSessionAgent === 'string' ? rawSessionAgent.trim() : undefined
        const rawSessionCursor = req.query.cursor
        const sessionCursor = typeof rawSessionCursor === 'string' ? rawSessionCursor : ''
        const sessionLimit = parseUnsignedIntegerQuery(req.query.limit)
        if (
          (rawSessionAgent !== undefined && typeof rawSessionAgent !== 'string') ||
          (rawSessionCursor !== undefined && typeof rawSessionCursor !== 'string') ||
          (rawSessionAgent !== undefined &&
            (!sessionAgent || !isSafeUpstreamAgentSegment(sessionAgent))) ||
          (rawSessionCursor !== undefined && !sessionCursor) ||
          sessionCursor.length > 2048 ||
          sessionLimit === null ||
          (sessionLimit !== undefined && sessionLimit < 1)
        ) {
          res.status(400).json({ error: 'Invalid session pagination query' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions`)
        if (sessionAgent) upstreamUrl.searchParams.set('agent', sessionAgent)
        if (sessionLimit !== undefined) {
          upstreamUrl.searchParams.set('limit', String(Math.min(sessionLimit, SESSIONS_LIMIT_CAP)))
        }
        if (sessionCursor) upstreamUrl.searchParams.set('cursor', sessionCursor)
        console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-sessions`)
        // Wake-eligible finite operation (§11.4): the route scope stays
        // host:session:read; wake capability rides on the token. A suspended
        // (network-down) or draining Host triggers a wake-and-hold instead of a
        // bare next(error)/passthrough.
        const forwardSessionList = async (timeoutMs = config.upstreamTimeoutMs) => {
          const response = await fetch(upstreamUrl, {
            method: 'GET',
            headers: { ...host.headers },
            signal: AbortSignal.timeout(timeoutMs),
          })
          const body = await response.text()
          const draining = sessionDrainingFence(response, body)
          if (draining) throw draining
          sendUpstreamBody(
            res,
            response.status,
            body,
            response.headers.get('content-type') || 'application/json'
          )
        }
        try {
          await forwardSessionList()
        } catch (error) {
          // A sanitized session boundary can also wrap local response-body
          // failures. Wake only when its retained cause proves the host is
          // unavailable, or when the host explicitly returned the draining
          // fence; otherwise preserve the ordinary sanitized error path.
          if (!isWakeEligibleHostError(error)) {
            throw error
          }
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            // idempotent GET: a re-issued read cannot duplicate a side effect
            retryUntilDeadline: true,
            attemptUpstream: forwardSessionList,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // Fetch one session's transcript — passthrough to mcp-host.
  router.get(
    '/rpc/hosts/:hostRef/sessions/:agent/:chatId/messages',
    requireRpcAuth,
    requireScope('host:session:read'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        const agent = String(req.params.agent || '').trim()
        const chatId = String(req.params.chatId || '').trim()
        if (
          !isSafeUpstreamPathSegment(hostRef) ||
          !isSafeUpstreamAgentSegment(agent) ||
          !isSafeUpstreamPathSegment(chatId)
        ) {
          res.status(400).json({ error: 'Invalid hostRef, agent, or chatId' })
          return
        }
        const rawLimit = parseUnsignedIntegerQuery(req.query.limit)
        const beforeTurn = parseUnsignedIntegerQuery(req.query.beforeTurn)
        const afterTurn = parseUnsignedIntegerQuery(req.query.afterTurn)
        const invalidQueryShape = ['limit', 'beforeTurn', 'afterTurn'].some(
          key => req.query[key] !== undefined && typeof req.query[key] !== 'string'
        )
        if (
          invalidQueryShape ||
          rawLimit === null ||
          (rawLimit !== undefined && rawLimit < 1) ||
          beforeTurn === null ||
          (beforeTurn !== undefined && beforeTurn < 1) ||
          afterTurn === null ||
          (afterTurn !== undefined && afterTurn < 0) ||
          (beforeTurn !== undefined && afterTurn !== undefined)
        ) {
          res.status(400).json({ error: 'Invalid session messages pagination query' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        const upstreamUrl = new URL(
          `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`
        )
        if (rawLimit !== undefined) {
          upstreamUrl.searchParams.set('limit', String(Math.min(rawLimit, MESSAGES_LIMIT_CAP)))
        }
        if (beforeTurn !== undefined) {
          upstreamUrl.searchParams.set('beforeTurn', String(beforeTurn))
        }
        if (afterTurn !== undefined) upstreamUrl.searchParams.set('afterTurn', String(afterTurn))
        console.info(
          `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-session-messages agent=${agent} chatId=${chatId}`
        )
        // Wake-eligible finite operation (§11.4): scope stays host:session:read.
        const forwardTranscript = async (timeoutMs = config.upstreamTimeoutMs) => {
          const response = await fetch(upstreamUrl, {
            method: 'GET',
            headers: { ...host.headers },
            signal: AbortSignal.timeout(timeoutMs),
          })
          const body = await response.text()
          const draining = sessionDrainingFence(response, body)
          if (draining) throw draining
          sendUpstreamBody(
            res,
            response.status,
            body,
            response.headers.get('content-type') || 'application/json'
          )
        }
        try {
          await forwardTranscript()
        } catch (error) {
          // See the list route above: availability recovery is deliberately
          // narrower than the generic sanitized upstream-error boundary.
          if (!isWakeEligibleHostError(error)) {
            throw error
          }
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            // idempotent GET: a re-issued read cannot duplicate a side effect
            retryUntilDeadline: true,
            attemptUpstream: forwardTranscript,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // Fetch one session's context-window breakdown — passthrough to mcp-host.
  // Mirrors the .../messages route exactly: same host:session:read scope and
  // per-user host resolution. mcp-host owns the per-user authorization (userSub
  // from the verified edge caller) and the anti-enumeration 404.
  router.get(
    '/rpc/hosts/:hostRef/sessions/:agent/:chatId/context-breakdown',
    requireRpcAuth,
    requireScope('host:session:read'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        const agent = String(req.params.agent || '').trim()
        const chatId = String(req.params.chatId || '').trim()
        if (
          !isSafeUpstreamPathSegment(hostRef) ||
          !isSafeUpstreamAgentSegment(agent) ||
          !isSafeUpstreamPathSegment(chatId)
        ) {
          res.status(400).json({ error: 'Invalid hostRef, agent, or chatId' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        console.info(
          `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-context-breakdown agent=${agent} chatId=${chatId}`
        )
        // Wake-eligible finite operation (§11.4): scope stays host:session:read.
        const attempt = async (timeoutMs = config.upstreamTimeoutMs) => {
          const response = await fetch(
            `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/context-breakdown`,
            {
              method: 'GET',
              headers: { ...host.headers },
              signal: AbortSignal.timeout(timeoutMs),
            }
          )
          const body = await response.text()
          const draining = sessionDrainingFence(response, body)
          if (draining) throw draining
          sendUpstreamBody(
            res,
            response.status,
            body,
            response.headers.get('content-type') || 'application/json'
          )
        }
        try {
          await attempt()
        } catch (error) {
          if (!isWakeEligibleHostError(error)) throw error
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            // idempotent GET: a re-issued read cannot duplicate a side effect
            retryUntilDeadline: true,
            attemptUpstream: attempt,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // Rename a session — write path, scoped to host:session:write (a distinct
  // scope from host:session:read, so a read/navigation token can never rename).
  // Passthrough to mcp-host PATCH /v1/runtime/sessions/:agent/:chatId/name: the
  // request body (the new title) is forwarded verbatim, and mcp-host owns title
  // validation, ownership, and the anti-enumeration 404, so its 400/403/404/200
  // pass through unchanged. Title content is NOT validated here (only the path
  // segments); the raw title value is never logged.
  //
  // Deliberately NOT wake-eligible: the Desktop App renames optimistically
  // (local-first) and reconciles on the next listSessions poll, so a suspended
  // host needs no wake-and-hold here — a network/timeout failure surfaces as the
  // ordinary 502/504 and the client keeps the pending rename to retry.
  router.patch(
    '/rpc/hosts/:hostRef/sessions/:agent/:chatId/name',
    requireRpcAuth,
    requireScope('host:session:write'),
    jsonBody,
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        const agent = String(req.params.agent || '').trim()
        const chatId = String(req.params.chatId || '').trim()
        if (
          !isSafeUpstreamPathSegment(hostRef) ||
          !isSafeUpstreamAgentSegment(agent) ||
          !isSafeUpstreamPathSegment(chatId)
        ) {
          res.status(400).json({ error: 'Invalid hostRef, agent, or chatId' })
          return
        }
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        // Strip line breaks from the user-derived path segments before logging.
        // They are already control-char-free (isSafeUpstreamPathSegment rejects
        // the C0 range, CR/LF included, above) so this is defense in depth: a
        // logged value can never forge an extra log line. Never log the raw title
        // (spec 15 §5): titles are user content.
        const logHost = hostRef.replace(/[\r\n]/g, '')
        const logAgent = agent.replace(/[\r\n]/g, '')
        const logChatId = chatId.replace(/[\r\n]/g, '')
        console.info(
          `[RPC_PROXY] user=${auth.sub} host=${logHost} method=rename-session agent=${logAgent} chatId=${logChatId}`
        )
        try {
          // Only host.headers carry the edge identity (x-clerum-edge-user-id and
          // the caller marker); the client Authorization is never forwarded, so
          // mcp-host's runtimeEdgeGuard stays satisfied. Body is re-serialized
          // from the parsed JSON and forwarded verbatim: unlike the /model write
          // path this route does no body-shape guard, since mcp-host owns title
          // validation and returns its own 400 for a malformed body.
          const response = await fetch(
            `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/name`,
            {
              method: 'PATCH',
              headers: { 'content-type': 'application/json', ...host.headers },
              body: JSON.stringify(req.body),
              // No wake retry re-issues a rename, so the timeout stays; a client
              // that leaves still releases the upstream call.
              signal: mutatingCallSignal(config.upstreamTimeoutMs, res),
            }
          )
          const body = await response.text()
          sendUpstreamBody(
            res,
            response.status,
            body,
            response.headers.get('content-type') || 'application/json'
          )
        } catch (error) {
          respondUpstreamUnavailable(res, error)
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // List selectable models for the session — passthrough to mcp-host.
  // Read-only projection of the in-memory allowlist; scoped to host:session:read
  // (same as the other session reads). Passes the optional chatId query through
  // so mcp-host can include the per-session selection.
  router.get(
    '/rpc/hosts/:hostRef/models',
    requireRpcAuth,
    requireScope('host:session:read'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        const chatId = typeof req.query.chatId === 'string' ? req.query.chatId.trim() : ''
        const upstreamUrl = chatId
          ? `${baseUrl}/v1/runtime/models?chatId=${encodeURIComponent(chatId)}`
          : `${baseUrl}/v1/runtime/models`
        console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-models`)
        // Wake-eligible finite operation (§11.4): scope stays host:session:read.
        const attempt = async (timeoutMs = config.upstreamTimeoutMs) => {
          const response = await fetch(upstreamUrl, {
            method: 'GET',
            headers: { ...host.headers },
            signal: AbortSignal.timeout(timeoutMs),
          })
          const body = await response.text()
          const draining = sessionDrainingFence(response, body)
          if (draining) throw draining
          sendUpstreamBody(
            res,
            response.status,
            body,
            response.headers.get('content-type') || 'application/json'
          )
        }
        try {
          await attempt()
        } catch (error) {
          if (!isWakeEligibleHostError(error)) throw error
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            // idempotent GET: a re-issued read cannot duplicate a side effect
            retryUntilDeadline: true,
            attemptUpstream: attempt,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // Set the per-session model — write path, scoped to host:model:write.
  // Body {chatId, model} is passed through verbatim; mcp-host owns validation
  // (model_not_allowed) and per-user authorization, so its 400/403 pass through.
  router.post(
    '/rpc/hosts/:hostRef/model',
    requireRpcAuth,
    requireScope('host:model:write'),
    jsonBody,
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const body = req.body as Record<string, unknown>
        if (!body || typeof body !== 'object' || Array.isArray(body)) {
          res.status(400).json({ error: 'Invalid set-model request payload' })
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=set-model`)
        // Wake-eligible finite operation (§11.4): scope stays host:model:write.
        const attempt = async (timeoutMs?: number) => {
          const response = await fetch(`${baseUrl}/v1/runtime/model`, {
            method: 'POST',
            headers: { 'content-type': 'application/json', ...host.headers },
            body: JSON.stringify(body),
            signal: mutatingCallSignal(timeoutMs, res),
          })
          const upstreamBody = await readMutatingResponseBody(response)
          const draining = sessionDrainingFence(response, upstreamBody)
          if (draining) throw draining
          sendUpstreamBody(
            res,
            response.status,
            upstreamBody,
            response.headers.get('content-type') || 'application/json'
          )
        }
        try {
          await attempt()
        } catch (error) {
          if (!isWakeEligibleHostError(error)) throw error
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            attemptUpstream: attempt,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  router.get(
    '/rpc/hosts/:hostRef/tasks/:taskId/result',
    requireRpcAuth,
    requireScope('host:message:invoke'),
    async (req: AuthedRequest, res) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        const taskId = String(req.params.taskId || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        if (!taskId || !/^[a-zA-Z0-9_-]+$/.test(taskId)) {
          res.status(400).json({ error: 'Invalid taskId' })
          return
        }

        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          res.status(404).json({ error: 'Host not found or not accessible' })
          return
        }

        console.info(
          `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-task-result taskId=${taskId}`
        )
        const attemptTaskResult = async (timeoutMs = config.upstreamTimeoutMs) => {
          const result = await forwardTaskResultFromHost(host, taskId, timeoutMs)
          if (!result) {
            res.status(404).json({ error: 'Task result not found' })
            return
          }
          res.status(200).json(result)
        }
        try {
          await attemptTaskResult()
        } catch (error) {
          console.warn(`[RPC_PROXY] task result forward failed error=${describeErrorForLog(error)}`)
          if (isWakeEligibleHostError(error)) {
            await respondWithWakeAndHold({
              res,
              hostRef,
              host,
              claims: auth,
              rpcAccessToken,
              deadlineMs: wakeDeadlineMs,
              // idempotent GET: a re-issued read cannot duplicate a side effect
              retryUntilDeadline: true,
              attemptUpstream: attemptTaskResult,
              respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
            })
            return
          }
          respondUpstreamUnavailable(res, error)
        }
      } catch (error) {
        console.warn(`[RPC_PROXY] task result forward failed error=${describeErrorForLog(error)}`)
        respondUpstreamUnavailable(res, error)
      }
    }
  )

  router.post(
    '/rpc/hosts/:hostRef/tasks/:taskId/cancel',
    requireRpcAuth,
    requireScope('host:message:invoke'),
    async (req: AuthedRequest, res) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        const taskId = String(req.params.taskId || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        if (!taskId || !/^[a-zA-Z0-9_-]+$/.test(taskId)) {
          res.status(400).json({ error: 'Invalid taskId' })
          return
        }

        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          res.status(404).json({ error: 'Host not found or not accessible' })
          return
        }

        console.info(
          `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=cancel-task taskId=${taskId}`
        )

        const attemptCancel = async (timeoutMs?: number) => {
          const result = await forwardCancelToHost(
            host,
            taskId,
            auth.sub,
            mutatingCallSignal(timeoutMs, res)
          )
          if (result.body) {
            sendUpstreamBody(
              res,
              result.status,
              result.body,
              result.contentType || 'application/json'
            )
          } else {
            res.status(result.status).end()
          }
        }
        try {
          await attemptCancel()
        } catch (error) {
          console.warn(`[RPC_PROXY] cancel forward failed error=${describeErrorForLog(error)}`)
          if (isWakeEligibleHostError(error)) {
            await respondWithWakeAndHold({
              res,
              hostRef,
              host,
              claims: auth,
              rpcAccessToken,
              deadlineMs: wakeDeadlineMs,
              attemptUpstream: attemptCancel,
              respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
            })
            return
          }
          respondUpstreamUnavailable(res, error)
        }
      } catch (error) {
        console.warn(`[RPC_PROXY] cancel forward failed error=${describeErrorForLog(error)}`)
        respondUpstreamUnavailable(res, error)
      }
    }
  )

  // List artifacts generated by internal tools
  router.get(
    '/rpc/hosts/:hostRef/artifacts',
    requireRpcAuth,
    requireScope('host:task:read'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        if (!RFC1123_RE.test(hostRef)) {
          res.status(400).json({ error: 'Invalid host reference' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        // Wake-eligible finite operation (§11.4): scope stays host:task:read.
        // Unlike approve/deny/model this is a read-only list of small JSON: a
        // timeout cannot leave a half-applied change, and without one a hung
        // host would pin this socket. It therefore keeps a finite deadline on
        // the first attempt as well.
        const attempt = async (timeoutMs = config.upstreamTimeoutMs) => {
          const response = await fetch(`${baseUrl}/v1/runtime/artifacts`, {
            headers: { ...host.headers },
            signal: AbortSignal.timeout(timeoutMs),
          })
          const body = await response.text()
          const draining = sessionDrainingFence(response, body)
          if (draining) throw draining
          sendUpstreamBody(res, response.status, body)
        }
        try {
          await attempt()
        } catch (error) {
          if (!isWakeEligibleHostError(error)) throw error
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            // idempotent GET: a re-issued read cannot duplicate a side effect
            retryUntilDeadline: true,
            attemptUpstream: attempt,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  // Download a specific artifact
  router.get(
    '/rpc/hosts/:hostRef/artifacts/:filename/download',
    requireRpcAuth,
    requireScope('host:task:read'),
    async (req: AuthedRequest, res, next) => {
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        const filename = String(req.params.filename || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        if (!RFC1123_RE.test(hostRef)) {
          res.status(400).json({ error: 'Invalid host reference' })
          return
        }
        if (
          !filename ||
          filename.includes('..') ||
          filename.includes('/') ||
          filename.includes('\\') ||
          filename.includes('\0')
        ) {
          res.status(400).json({ error: 'Invalid filename' })
          return
        }
        const wakeDeadlineMs = Date.now() + config.wakeMaxHoldMs
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const baseUrl = host.url.replace(/\/+$/, '')
        // Wake-eligible finite operation (§11.4): scope stays host:task:read.
        // The success path only commits (`res.send`) at the very end, so a
        // wake retry before that point is safe from duplicate delivery.
        const attemptDownload = async (
          timeoutMs = config.upstreamTimeoutMs,
          holdDeadlineMs?: number
        ) => {
          const controller = new AbortController()
          let timeout = setTimeout(() => controller.abort(), timeoutMs)
          try {
            const response = await fetch(
              `${baseUrl}/v1/runtime/artifacts/${encodeURIComponent(filename)}/download`,
              {
                headers: { ...host.headers },
                signal: controller.signal,
              }
            )
            // The upstream timeout protects connection and header latency. Once
            // headers arrive, allow the separately bounded artifact transfer to
            // finish; the small JSON-operation deadline must not truncate a
            // valid large download while its body is streaming. On a wake retry
            // the transfer is also bounded by what is left of the hold budget,
            // so a stalled body cannot outlive the request deadline.
            clearTimeout(timeout)
            timeout = setTimeout(
              () => controller.abort(),
              holdDeadlineMs === undefined
                ? config.artifactDownloadTimeoutMs
                : Math.min(
                    config.artifactDownloadTimeoutMs,
                    Math.max(0, holdDeadlineMs - Date.now())
                  )
            )
            if (!response.ok) {
              const errBody = await response.text()
              const draining = sessionDrainingFence(response, errBody)
              if (draining) throw draining
              sendUpstreamBody(res, response.status, errBody)
              return
            }
            const contentType = response.headers.get('content-type') || 'application/octet-stream'
            const safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, '_')
            const redaction = response.headers.get('x-clerum-redaction')
            let buffer: Buffer
            try {
              buffer = await readArtifactResponseBuffer(response)
            } catch (error) {
              if (error instanceof ProxyArtifactTooLargeError) {
                res.status(413).json({ error: 'Artifact too large to download' })
                return
              }
              throw error
            }
            res.setHeader('Content-Type', contentType)
            res.setHeader('Content-Disposition', `attachment; filename="${safeFilename}"`)
            if (redaction) res.setHeader('X-Clerum-Redaction', redaction)
            res.send(buffer)
          } finally {
            clearTimeout(timeout)
          }
        }
        try {
          await attemptDownload()
        } catch (error) {
          if (!isWakeEligibleHostError(error)) throw error
          await respondWithWakeAndHold({
            res,
            hostRef,
            host,
            claims: auth,
            rpcAccessToken,
            deadlineMs: wakeDeadlineMs,
            // idempotent GET: a re-issued read cannot duplicate a side effect
            retryUntilDeadline: true,
            attemptUpstream: attemptDownload,
            respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),
          })
        }
      } catch (error) {
        guardedNext(res, next, error)
      }
    }
  )

  router.get(
    '/rpc/hosts/:hostRef/activity',
    requireRpcAuth,
    requireScope('host:activity:read'),
    async (req: AuthedRequest, res, next) => {
      // Host runtime read-only activity timeline snapshot.
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }
        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }
        const limit = Number(req.query.limit || 50)
        const sinceEventId =
          typeof req.query.sinceEventId === 'string' ? req.query.sinceEventId : undefined
        const activity = await forwardHostActivity(host, limit, sinceEventId)
        res.status(200).json(activity)
      } catch (error) {
        console.warn(
          `[RPC_PROXY] host activity failed host=${sanitizeHostRefForLog(String(req.params.hostRef || '').trim())} error=${describeErrorForLog(
            error
          )}`
        )
        next(error)
      }
    }
  )

  router.get(
    '/rpc/hosts/:hostRef/status',
    requireRpcAuth,
    requireScope('host:status:read'),
    async (req: AuthedRequest, res, next) => {
      // Host runtime read snapshot (REST-oriented) scoped to host:status:read.
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }

        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }

        const status = await forwardHostStatus(host)
        if (!status) {
          console.warn(
            `[RPC_PROXY] host status malformed host=${sanitizeHostRefForLog(hostRef)} user=${auth.sub}`
          )
          res.status(502).json({ error: 'Invalid upstream host status response' })
          return
        }
        res.status(200).json(status)
      } catch (error) {
        console.warn(
          `[RPC_PROXY] host status failed host=${sanitizeHostRefForLog(String(req.params.hostRef || '').trim())} error=${describeErrorForLog(
            error
          )}`
        )
        next(error)
      }
    }
  )

  router.get(
    '/rpc/hosts/:hostRef/health',
    requireRpcAuth,
    requireScope('host:health:read'),
    async (req: AuthedRequest, res, next) => {
      // Host runtime health/liveness read path (REST-oriented) scoped to host:health:read.
      try {
        const auth = req.auth!
        const rpcAccessToken = extractAuthToken(req)
        const hostRef = String(req.params.hostRef || '').trim()
        if (!hostRef) {
          res.status(400).json({ error: 'hostRef is required' })
          return
        }

        const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {
          teamId: auth.teamId,
        })
        if (isHostAccessDenied(host)) {
          respondHostAccessDenied(res, host)
          return
        }

        const health = await forwardHostHealth(host)
        res.status(200).json(health)
      } catch (error) {
        console.warn(
          `[RPC_PROXY] host health failed host=${sanitizeHostRefForLog(String(req.params.hostRef || '').trim())} error=${describeErrorForLog(
            error
          )}`
        )
        next(error)
      }
    }
  )

  return router
}