Skip to content

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

TypeScript
10.6 KB
Raw Blame
import {
  type GrokCompletionRequest,
  SCHEMA_VERSION_V2,
  buildGrokProxyEnvelope,
} from '@clerum/grok-provider-attempt-contract'
import { fetchCauseCode, isConnectPhaseFailure } from './controlPlaneReachability'
import { canonicalRefusalCode } from './imageSource'
import { rateLimitedCode, retryAfterMs } from './retryAfter'
import { upstreamRejectedStatus } from './upstreamRejected'

export const GROK_PROXY_COMPLETIONS_PATH = '/internal/runtime/v1/grok/completions'

/**
 * Operator-facing text for a proxy denial. Codes an operator must act on get a
 * sentence that says what to do; everything else keeps the diagnostic shape.
 */
export function grokProxyErrorMessage(code: string, status?: number): string {
  if (
    code === 'visual_host_share' ||
    code === 'visual_gate' ||
    code === 'proxy_capacity_exceeded'
  ) {
    return 'Grok proxy admission is full. Wait for an active request to finish or send fewer concurrent requests before retrying; this is not a Grok outage.'
  }
  if (code === 'client_upgrade_required') {
    return 'Grok subscription inference is unavailable: xAI now requires a newer Grok client version than this deployment sends. An operator can set GROK_LLM_PROXY_CLIENT_VERSION to a current Grok Build release, or contact support — retrying will not help.'
  }
  if (code === 'tool_call_arguments_exceeded') {
    // The remedy belongs to whoever composes the next turn, not to an
    // operator: the transport refused a tool call whose arguments exceeded its
    // per-response size budget, so the response was rejected rather than
    // truncated. Interim text — issue #731 owns the end-to-end size budget and
    // will restate this guidance against the contract's own value.
    return 'Grok returned a tool call whose arguments exceed the transport size budget, so the response was refused instead of truncated. Retry with a more bounded request: ask for fewer items per call, request narrower fields, or split the work into several smaller tool calls.'
  }
  return status === undefined
    ? `proxy stream failed with ${code}`
    : `proxy stream failed with ${status} (${code})`
}

/**
 * The code for an envelope the contract refused: a hash mismatch keeps its own
 * code, and every other refusal takes the providers' canonical mapping, so a
 * `count` refusal is an invalid request and only `kind: 'size'` is
 * `payload_too_large`.
 */
function envelopeRefusalCode(refusal: { code: string; message: string; kind?: string }): string {
  if (refusal.code === 'request_hash_mismatch') return 'request_hash_mismatch'
  return canonicalRefusalCode(refusal)
}

export type GrokProxyErrorOptions = {
  /**
   * Whether a request had already left this process when the error was
   * raised. It defaults to `true` because every construction site except the
   * pre-stream abort happens after the fetch was issued, and the safe default
   * is the one that keeps the attempt fenced.
   */
  dispatched?: boolean
  /** The delay a 429 advised through Retry-After (G1-6). */
  retryAfterMs?: number
  /** The upstream 4xx behind an upstream_rejected (R1-H2). */
  upstreamStatus?: number
}

export class GrokProxyError extends Error {
  readonly dispatched: boolean
  readonly retryAfterMs?: number
  readonly upstreamStatus?: number

  constructor(
    readonly code: string,
    message: string,
    options: GrokProxyErrorOptions = {}
  ) {
    super(message)
    this.name = 'GrokProxyError'
    this.dispatched = options.dispatched ?? true
    this.retryAfterMs = options.retryAfterMs
    this.upstreamStatus = options.upstreamStatus
  }
}

export type GrokProxyFrame =
  | { type: 'text'; text: string }
  | { type: 'tool_call'; id: string; name: string; arguments: Record<string, unknown> }
  | {
      type: 'done'
      outcome: 'success' | 'canceled' | 'error' | 'unknown'
      usage?: { inputTokens: number; outputTokens: number }
    }
  | { type: 'error'; code: string; upstreamStatus?: unknown }

export type GrokProxyStreamResult = {
  text: string
  toolCalls: Array<{ id: string; name: string; arguments: Record<string, unknown> }>
  outcome: 'success' | 'canceled' | 'error' | 'unknown'
  /** Present only when the proxy forwarded real upstream token counts. */
  usage?: { inputTokens: number; outputTokens: number }
}

export type GrokLlmProxyClientOptions = {
  runtimeUrl: string
  readPlatformJwt: () => string
  refreshOnUnauthorized?: () => Promise<void>
  fetchFn?: typeof fetch
}

export class GrokLlmProxyClient {
  constructor(private readonly options: GrokLlmProxyClientOptions) {
    if (!options.runtimeUrl.startsWith('http://') && !options.runtimeUrl.startsWith('https://')) {
      throw new Error('[GrokProxy] runtime URL must be an absolute server-owned URL')
    }
  }

  async stream(input: {
    executionTicket: string
    requestHash: string
    request: unknown
    deadlineMs?: number
    signal?: AbortSignal
  }): Promise<GrokProxyStreamResult> {
    if (input.signal?.aborted) {
      throw new GrokProxyError('canceled', 'aborted before proxy stream', { dispatched: false })
    }
    return this.streamOnce(input, Boolean(this.options.refreshOnUnauthorized))
  }

  private async streamOnce(
    input: {
      executionTicket: string
      requestHash: string
      request: unknown
      deadlineMs?: number
      signal?: AbortSignal
    },
    retryOnUnauthorized: boolean
  ): Promise<GrokProxyStreamResult> {
    let body: unknown = {
      executionTicket: input.executionTicket,
      requestHash: input.requestHash,
      request: input.request,
      ...(input.deadlineMs !== undefined ? { deadlineMs: input.deadlineMs } : {}),
    }
    // A V2 request carries its deadline inside the hashed request, and
    // grok-llm-proxy refuses an outer one. The envelope is the contract's own,
    // so a request the proxy would refuse never leaves this process (#784).
    // The envelope builder parses and hashes the request itself, so the request
    // is parsed once here; the deadline is compared with the parsed value.
    if ((input.request as { schemaVersion?: string } | null)?.schemaVersion === SCHEMA_VERSION_V2) {
      const envelope = buildGrokProxyEnvelope({
        executionTicket: input.executionTicket,
        requestHash: input.requestHash,
        request: input.request as GrokCompletionRequest,
      })
      if (!envelope.ok) {
        throw new GrokProxyError(envelopeRefusalCode(envelope), envelope.message, {
          dispatched: false,
        })
      }
      if (
        input.deadlineMs !== undefined &&
        input.deadlineMs !== envelope.value.request.deadlineMs
      ) {
        throw new GrokProxyError(
          'invalid_request',
          'Grok deadline must match the authorized request',
          { dispatched: false }
        )
      }
      body = envelope.value
    }
    const jwt = this.options.readPlatformJwt()
    const fetchFn = this.options.fetchFn ?? fetch
    let response: Response
    try {
      response = await fetchFn(this.options.runtimeUrl, {
        method: 'POST',
        headers: {
          authorization: `Bearer ${jwt}`,
          'content-type': 'application/json',
        },
        body: JSON.stringify(body),
        signal: input.signal,
      })
    } catch (err) {
      // No live proxy process received the request (G1-7, #720). Every other
      // rejection, the caller's abort included, is rethrown unchanged; a
      // failure while the stream is read is never relabelled here.
      if (isConnectPhaseFailure(err, input.signal)) {
        throw new GrokProxyError(
          'control_plane_unavailable',
          `proxy could not be reached (${fetchCauseCode(err)})`
        )
      }
      throw err
    }
    if (!response.ok) {
      if (response.status === 401 && retryOnUnauthorized && this.options.refreshOnUnauthorized) {
        await this.options.refreshOnUnauthorized()
        return this.streamOnce(input, false)
      }
      const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>
      // Only the proxy-owned machine `error` field identifies the outcome; an
      // upstream `reason` string is never promoted to trusted provenance. A
      // 413 with no JSON code comes from the gateway in front of the proxy
      // (nginx `client_max_body_size`): a size refusal of this request, never a
      // provider outage (#739). A code the 413 carries still wins. A 429 is a
      // rate limit (G1-6, G1-11, #720): the proxy answers `rate_limited`
      // itself, and a 429 with no JSON code or a reason phrase is read the same
      // way, so only a machine code a 429 carries replaces `rate_limited`.
      const code =
        response.status === 429
          ? rateLimitedCode(payload.error)
          : typeof payload.error === 'string'
            ? payload.error
            : response.status === 413
              ? 'payload_too_large'
              : 'provider_unavailable'
      throw new GrokProxyError(code, grokProxyErrorMessage(code, response.status), {
        retryAfterMs: response.status === 429 ? retryAfterMs(response) : undefined,
        upstreamStatus: upstreamRejectedStatus(code, payload.upstreamStatus),
      })
    }
    if (!response.body) {
      throw new GrokProxyError('provider_unavailable', 'proxy stream had no body')
    }
    return readProxySse(response.body)
  }
}

export function resolveGrokProxyRuntimeUrl(base: string): string {
  const trimmed = base.replace(/\/+$/, '')
  if (trimmed.endsWith(GROK_PROXY_COMPLETIONS_PATH)) return trimmed
  return `${trimmed}${GROK_PROXY_COMPLETIONS_PATH}`
}

async function readProxySse(body: ReadableStream<Uint8Array>): Promise<GrokProxyStreamResult> {
  const reader = body.getReader()
  const decoder = new TextDecoder()
  let buffer = ''
  let text = ''
  const toolCalls: GrokProxyStreamResult['toolCalls'] = []
  let outcome: GrokProxyStreamResult['outcome'] = 'unknown'
  let usage: GrokProxyStreamResult['usage']
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    buffer += decoder.decode(value, { stream: true })
    const parts = buffer.split('\n\n')
    buffer = parts.pop() ?? ''
    for (const part of parts) {
      const line = part.split('\n').find(entry => entry.startsWith('data: '))
      if (!line) continue
      const frame = JSON.parse(line.slice(6)) as GrokProxyFrame
      if (frame.type === 'error') {
        throw new GrokProxyError(frame.code, grokProxyErrorMessage(frame.code), {
          upstreamStatus: upstreamRejectedStatus(frame.code, frame.upstreamStatus),
        })
      }
      if (frame.type === 'text') text += frame.text
      if (frame.type === 'tool_call') toolCalls.push(frame)
      if (frame.type === 'done') {
        outcome = frame.outcome
        if (frame.usage) usage = frame.usage
      }
    }
  }
  return { text, toolCalls, outcome, ...(usage ? { usage } : {}) }
}