Skip to content

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

TypeScript
9.2 KB
Raw Blame
import {
  ENVELOPE_ALLOWANCE_BYTES as GROK_ENVELOPE_ALLOWANCE_BYTES,
  LIMITS as GROK_LIMITS,
  PROVIDER_ID as GROK_PROVIDER_ID,
  requestBodyLimitBytes as grokRequestBodyLimitBytes,
} from '@clerum/grok-provider-attempt-contract'
import {
  ENVELOPE_ALLOWANCE_BYTES,
  LIMITS,
  parseAuthorizeAttemptResponse,
  requestBodyLimitBytes,
} from '@clerum/llm-provider-attempt-contract'
import { fetchCauseCode, isConnectPhaseFailure } from './controlPlaneReachability'
import { rateLimitedCode, retryAfterMs } from './retryAfter'

export const AUTHORIZE_PATH = '/api/v1/mcp-host/llm/provider-attempts/authorize'

type RequestContract = {
  label: 'Codex' | 'Grok'
  maxRequestBodyBytes: number
  envelopeAllowanceBytes: number
  requestBodyLimitBytes: (request: unknown) => number
}

/**
 * The contract that bounds `request`. The authorize route is shared, and
 * control-api picks the Grok contract by `request.provider` (#784); checking a
 * Grok request against the Codex caps here would refuse a Grok V2 body that
 * control-api accepts.
 */
function requestContract(request: unknown): RequestContract {
  if ((request as { provider?: unknown } | null)?.provider === GROK_PROVIDER_ID) {
    return {
      label: 'Grok',
      maxRequestBodyBytes: GROK_LIMITS.maxRequestBodyBytes,
      envelopeAllowanceBytes: GROK_ENVELOPE_ALLOWANCE_BYTES,
      requestBodyLimitBytes: grokRequestBodyLimitBytes,
    }
  }
  return {
    label: 'Codex',
    maxRequestBodyBytes: LIMITS.maxRequestBodyBytes,
    envelopeAllowanceBytes: ENVELOPE_ALLOWANCE_BYTES,
    requestBodyLimitBytes,
  }
}

/**
 * Room for the authorize envelope around the contract-capped `request`: ids,
 * revisions, hashes and recipe names, a few hundred bytes in practice. The
 * contract owns the value and control-api imports the same one, so a request
 * control-api would accept is never refused here for its envelope (#739).
 * Production code does not read this export: the authorizer takes the
 * allowance from `requestContract(request).envelopeAllowanceBytes`, which
 * selects the Grok contract's value for a Grok request. This export is the
 * Codex value, kept so `providerAttemptAuthorizer.test.ts` can pin it to the
 * contract.
 */
export const AUTHORIZE_ENVELOPE_ALLOWANCE_BYTES = ENVELOPE_ALLOWANCE_BYTES

export type CodexAuthorizeErrorOptions = {
  /** G1-11 (#720): the delay a 429 advised, read from its Retry-After. */
  retryAfterMs?: number
}

export class CodexAuthorizeError extends Error {
  readonly retryAfterMs?: number

  constructor(
    readonly code: string,
    message: string,
    options: CodexAuthorizeErrorOptions = {}
  ) {
    super(message)
    this.name = 'CodexAuthorizeError'
    this.retryAfterMs = options.retryAfterMs
  }
}

export type AuthorizeAttemptBody = {
  request: unknown
  invocationId: string
  attemptGeneration: number
  providerAttemptIndex: number
  policyRevision: number
  policyHash: string
  requestHash?: string
  hostRef?: string
  recipeNamespace?: string
  recipeName?: string
  userId?: string
  budgetReservationId?: string
  pluginWorkloadSdkProviderAttemptId?: string
  targetRef?: string
}

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

const LEAK_KEYS = ['accessToken', 'refreshToken', 'authorization']

export class ProviderAttemptAuthorizer {
  constructor(private readonly options: ProviderAttemptAuthorizerOptions) {
    if (
      !options.authorizeUrl.startsWith('http://') &&
      !options.authorizeUrl.startsWith('https://')
    ) {
      throw new Error('[CodexAuthorize] authorize URL must be an absolute server-owned URL')
    }
  }

  /**
   * The caller's `signal` is the only clock on this hop. Authorize deliberately
   * has no timeout of its own: the bridge already bounds the whole attempt, and
   * a second independent deadline would make two different answers possible for
   * "did this attempt still have time?".
   */
  async authorize(
    body: AuthorizeAttemptBody,
    options?: { signal?: AbortSignal }
  ): Promise<{
    providerAttemptId: string
    requestHash: string
    executionTicket: string
    expiresAt: string
  }> {
    return this.authorizeOnce(body, Boolean(this.options.refreshOnUnauthorized), options?.signal)
  }

  private async authorizeOnce(
    body: AuthorizeAttemptBody,
    retryOnUnauthorized: boolean,
    signal?: AbortSignal
  ): Promise<{
    providerAttemptId: string
    requestHash: string
    executionTicket: string
    expiresAt: string
  }> {
    const serialized = JSON.stringify(body)
    const contract = requestContract(body.request)
    const requestLimit = contract.requestBodyLimitBytes(body.request)
    // The larger of the two budgets wins, as in control-api's authorizer: the
    // non-image cap plus the envelope allowance, or the V2 visual envelope.
    const bodyLimit = Math.max(
      requestLimit,
      contract.maxRequestBodyBytes + contract.envelopeAllowanceBytes
    )
    if (Buffer.byteLength(serialized, 'utf8') > bodyLimit) {
      throw new CodexAuthorizeError(
        'payload_too_large',
        `${contract.label} request exceeds ${requestLimit / (1024 * 1024)} MiB; use fewer or smaller images, or reduce context`
      )
    }
    const jwt = this.options.readPlatformJwt()
    if (!jwt) {
      throw new CodexAuthorizeError('no_grant', 'platform JWT is missing')
    }
    const fetchFn = this.options.fetchFn ?? fetch
    let response: Response
    try {
      response = await fetchFn(this.options.authorizeUrl, {
        method: 'POST',
        headers: {
          authorization: `Bearer ${jwt}`,
          'content-type': 'application/json',
        },
        body: serialized,
        ...(signal ? { signal } : {}),
      })
    } catch (err) {
      // No live gateway process received the request (G1-7, #720). Every
      // other rejection, the caller's abort included, is rethrown unchanged.
      if (isConnectPhaseFailure(err, signal)) {
        throw new CodexAuthorizeError(
          'control_plane_unavailable',
          `authorize could not reach the control plane (${fetchCauseCode(err)})`
        )
      }
      throw err
    }
    const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>
    if (!response.ok) {
      if (response.status === 401 && retryOnUnauthorized && this.options.refreshOnUnauthorized) {
        await this.options.refreshOnUnauthorized()
        return this.authorizeOnce(body, false, signal)
      }
      // Every 413 is a size refusal of this request, never a provider outage
      // (#731): control-api answers `payload_too_large`, and the gateway in
      // front of it (nginx `client_max_body_size`) answers with no JSON code.
      // A 429 is a rate limit, not a provider outage (G1-6, G1-11, #720):
      // control-api's own authorize limiters answer the reason phrase
      // `Too Many Requests`, so only a machine code a 429 carries (such as
      // `budget_denied`) replaces `rate_limited`; a 429 with no JSON code is
      // `rate_limited` too.
      // A 504 with no JSON code is the gateway's read or send timeout on a
      // connection control-api accepted (a connect timeout is answered as
      // `control_plane_unavailable`), so authorize outlived the gateway, as
      // with control-api's own `authorize_timeout`. It is not a provider
      // outage and must not fail over.
      const code =
        response.status === 413
          ? 'payload_too_large'
          : response.status === 429
            ? rateLimitedCode(payload.error)
            : typeof payload.error === 'string'
              ? payload.error
              : response.status === 504
                ? 'authorize_timeout'
                : 'provider_unavailable'
      throw new CodexAuthorizeError(
        code,
        code === 'payload_too_large'
          ? `${contract.label} request is too large; use fewer or smaller images, or reduce context`
          : code === 'authorize_capacity_exceeded'
            ? 'Authorization is busy with other large requests, which share one capacity across all Hosts. Nothing was sent to the provider; wait for them to finish, then try again.'
            : code === 'authorize_timeout'
              ? 'Request authorization timed out. Wait for active requests to finish, then try again.'
              : `authorize failed with ${response.status}`,
        // Retry-After is read on a 429 and on control-api's capacity refusal,
        // which the provider retries once after it (M-A).
        {
          retryAfterMs:
            response.status === 429 ||
            (response.status === 503 && code === 'authorize_capacity_exceeded')
              ? retryAfterMs(response)
              : undefined,
        }
      )
    }
    for (const key of LEAK_KEYS) {
      if (key in payload) {
        throw new CodexAuthorizeError(
          'invalid_request',
          'authorize response leaked credential material'
        )
      }
    }
    const parsed = parseAuthorizeAttemptResponse(payload)
    if (!parsed.ok) {
      throw new CodexAuthorizeError('invalid_request', parsed.message)
    }
    return parsed.value
  }
}

export function resolveCodexAuthorizeUrl(gatewayBase: string): string {
  const trimmed = gatewayBase.replace(/\/+$/, '')
  return `${trimmed}${AUTHORIZE_PATH}`
}