# Tyr file configuration, schema version 1.
# Startup configuration seeds each pool. A control-plane integration can later
# apply complete higher-revision limit snapshots without restarting Tyr.
version: 1

server:
  port: 8787
  maxRequestBodyBytes: 1048576
  maxOutputTokens: 200000

# Configure at least one provider-shaped upstream. Tyr forwards the caller's
# supported provider authentication headers; API keys do not belong here.
upstreams:
  anthropic:
    baseUrl: https://api.anthropic.com
  openai:
    baseUrl: https://api.openai.com

timeouts:
  # Maximum wait for upstream response headers. Omit for no timeout.
  responseHeadersMs: 30000
  # Maximum gap between streaming response chunks. Omit for no timeout.
  streamIdleMs: 30000
  # Maximum wait for a backpressured client to drain. When omitted, this
  # defaults to streamIdleMs in the gateway.
  clientStallMs: 30000

shutdown:
  # Uses async-bulkhead-llm v3.19.1 bounded drain. At the deadline Tyr reports
  # outstanding work and closes remaining HTTP connections. Omit to wait
  # indefinitely, preserving the previous behavior.
  drainTimeoutMs: 30000
  # true stops the requests still running at the deadline before the
  # connections close. A request that has been sent no part of its reply gets
  # 503 admission_stopped, a reply under way is cut, and each is counted and
  # audited as stopped. Requires drainTimeoutMs. Default: false.
  stopOnDrainTimeout: false

priority:
  # Legacy trusted-proxy fallback. Ignored for provider requests when
  # first-class identity is configured below.
  trustHeader: false

# Optional capacity-aware routing across Tyr replicas. Every replica uses the
# same secret, keeps a short-lived cache of protected peer capacity snapshots,
# and forwards at most once to the peer with the best request-specific
# concurrency and token headroom. In standalone mode this peer list is static;
# in Latchflo 0.13+ managed mode it is the startup/fallback set and is replaced
# by newer versioned routingTopology snapshots from desired state.
# routing:
#   capacityAware:
#     instanceId: tyr-r1
#     sharedSecretEnv: TYR_ROUTING_SECRET
#     pollIntervalMs: 100
#     staleAfterMs: 1000
#     probeTimeoutMs: 250
#     forwardTimeoutMs: 30000
#     peers:
#       - id: tyr-r2
#         baseUrl: http://tyr-r2:8787
#       - id: tyr-r3
#         baseUrl: http://tyr-r3:8787

# Optional first-class request identity. When configured, provider requests
# must present `Bearer <JWT>` in this header and are authenticated before Tyr
# reads the request body. The provider Authorization header remains untouched.
# identity:
#   jwt:
#     jwksUrl: https://identity.example.com/.well-known/jwks.json
#     issuer: https://identity.example.com/
#     audience: moflux-tyr
#     header: x-tyr-identity-token
#     algorithms: [RS256]
#     cacheTtlMs: 300000
#     requestTimeoutMs: 5000
#     clockSkewSeconds: 30
#     requireExpiration: true
#     claims:
#       subject: sub
#       tenantId: tenant_id
#       applicationId: azp
#       roles: roles
#   roles:
#     # Each list uses any-of semantics. Empty/omitted invoke allows every
#     # authenticated identity; operator access otherwise falls back to
#     # TYR_OPERATOR_BEARER_TOKEN; highPriority defaults to normal priority.
#     invoke: [tyr.invoke]
#     operator: [tyr.operator]
#     highPriority: [tyr.priority.high]

# Optional response memory for OpenAI Responses follow-ups. Requires
# upstreams.openai. Tyr records the provider-reported size of each Responses
# reply, and a request that names previous_response_id reserves its own
# estimate plus that size. A follow-up that names a response Tyr has no record
# of gets 422 unknown_previous_response and the provider is not called. Without
# this block, previous_response_id is rejected with 400.
# Records are local to one Tyr process; give each replica its own file.
# responsesState:
#   # Created when missing. A relative path is resolved from this file's
#   # directory, so mount a writable directory for it in a container.
#   file: ./tyr-responses-state.jsonl
#   # Most records kept at once; the oldest is dropped first.
#   maxEntries: 10000
#   # How long a record stays usable. The default is 30 days.
#   ttlMs: 2592000000

telemetry:
  metrics:
    # Prometheus text format is served at GET /metrics.
    enabled: true
  audit:
    # Emits one JSON line per admitted, bypassed, or rejected decision.
    enabled: false

pools:
  - name: interactive-claude
    # Longest model-prefix match wins across all pools.
    modelPrefixes:
      - claude-sonnet-4
      - claude-haiku-4
    # Used by the admission estimator; it does not rewrite the requested model.
    estimatorModel: claude-sonnet-4-5
    maxConcurrent: 40
    # v3.14 complete admission-limit snapshot. maxQueue defaults to 0.
    # limitsRevision must increase for every runtime control-plane update.
    maxQueue: 0
    limitsRevision: 100
    # enforce: reject overload. observe: record the same decision but proxy
    # capacity rejections upstream, allowing a safe shadow-mode rollout.
    admissionMode: enforce
    # Omit to disable token-budget admission, use 0 to admit no budget-gated
    # work, or set a positive in-flight token ceiling.
    inFlightTokenBudget: 400000
    # Reserves token headroom for priority=high; it does not reserve a
    # concurrency slot and does not preempt running work.
    highPriorityTokenReserve: 80000
    # Used when the request does not specify max_tokens/max_completion_tokens.
    defaultOutputReservation: 8192
    # Fixed surcharge per opaque image/audio/document/file/video block.
    # Omit for the conservative default of 2048; set 0 to disable it.
    opaqueMediaInputTokenReservation: 2048
    # Enabled by default for budgeted pools. As cumulative streaming output
    # arrives, Tyr returns already-processed capacity in 256-token steps while
    # retaining a 256-token future-output safety floor until final release.
    progressiveReconciliation:
      enabled: true
      updateStepTokens: 256
      outputSafetyMarginTokens: 256
    # Per-model EWMA calibration. Native observe bypasses also feed it. Enabled by default for budgeted pools.
    # It learns only from provider-reported input usage and is local/in-memory.
    adaptiveEstimation:
      enabled: true
      smoothing: 0.2
      minSamples: 5
      minCorrection: 0.5
      maxCorrection: 2
      maxModels: 64
    # Optional stopping of admitted requests. Nothing is stopped without this
    # block, and it cannot be combined with admissionMode: observe. A stopped
    # request gets 503 admission_stopped, or has its reply cut once part of
    # the reply has been written. Its concurrency slot returns at once and
    # Tyr drops the upstream call; that does not prove the provider stopped
    # work. Tyr states this policy on every limits update, and a pool that
    # starts open with it starts at revision max(limitsRevision, 1).
    # stop:
    #   # Tokens a request's hold may grow above its reservation before the
    #   # request is stopped. Requires inFlightTokenBudget. The hold, not the
    #   # usage, is measured: with progressiveReconciliation on, a hold shrinks
    #   # as the reply streams, so it passes its reservation only after output
    #   # has overrun by about the size of the reservation. Usage a provider
    #   # reports only as a reply ends never stops that reply, which is all
    #   # the usage OpenAI's streams report.
    #   overrunAllowanceTokens: 2000
    #   # After a limits update, requests it left above the new limits are
    #   # stopped once this many milliseconds have passed.
    #   takeBackGraceMs: 5000
    # Optional bounded service classes. Trusted identity claims are mapped to
    # fixed class IDs; raw tenant/application IDs never become bulkhead keys or
    # Prometheus labels. First matching rule wins. Selector categories within
    # one rule are ANDed, while values within one category are ORed.
    admissionClasses:
      defaultClass: standard
      classes:
        standard:
          protectedConcurrent: 12
          maxConcurrent: 32
          protectedInFlightTokens: 100000
          maxInFlightTokens: 300000
          # Enforces restoration only for a borrowed Tyr concurrency slot.
          # Upstream reclamation remains unverified; retain a real unlent
          # provider/token floor when cancellation cannot release it.
          borrowedAdmissionSlot:
            releaseMechanism: deadline_abandonment
            deadlineMs: 30000
        premium:
          protectedConcurrent: 8
          maxConcurrent: 24
          protectedInFlightTokens: 80000
          maxInFlightTokens: 240000
      rules:
        - admissionClass: premium
          tenantIds: [tenant-paid]
        - admissionClass: premium
          applicationIds: [latency-sensitive-app]
          roles: [tier.premium]

  - name: batch-openai
    modelPrefixes:
      - gpt-4o
      - gpt-5
      - o1
      - o3
      - o4
    estimatorModel: gpt-4o
    maxConcurrent: 20
    maxQueue: 0
    limitsRevision: 100
    # Observe first to measure prospective rejections before enforcement.
    admissionMode: observe
    inFlightTokenBudget: 250000
    defaultOutputReservation: 4096
