# Local proxy and providers Local proxy presents provider-compatible HTTP routes on loopback, applies configured local transforms, forwards requests to provider endpoints, and records local usage. By default it is a single-operator developer tool with no inbound authentication. Setting `CAVEMAN_AUTH_TOKEN` turns it into a shared, token-gated service that may bind beyond loopback — see [Deploy the proxy for a team](deploy.md). Start it with: ```bash caveman start ``` Default address is `127.0.0.1:8787`. ## Request path ```mermaid sequenceDiagram participant A as Agent SDK participant P as Local proxy participant E as Engine participant U as Provider A->>P: Provider-compatible request P->>E: Inspect or transform eligible context E-->>P: Original or compact request data P->>U: Forward request with provider credential U-->>P: Provider response and usage P-->>A: Provider-compatible response ``` Provider credentials are preserved from inbound requests. Supported environment fallbacks apply only when an integration does not send a credential. Native SSE, Gemini streamed JSON arrays, and AWS EventStream responses are forwarded as they arrive. HTTP error status, response headers, and body bytes are preserved. Provider error events inside an HTTP 200 stream remain HTTP 200 on the wire, as required after the headers have been sent; the local request record carries `provider_stream_error`. Error detection stores only that code, not the provider's error message. Complete billed usage remains distinct from successful generation, and an error-bearing call claims no savings. The protocol regression uses local HTTP servers and the wire envelopes accepted by the [Anthropic SDK](https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/_streaming.py), [OpenAI SDK](https://github.com/openai/openai-python/blob/main/src/openai/_streaming.py), [Google SDK](https://github.com/googleapis/python-genai/blob/main/google/genai/_api_client.py), and [Botocore EventStream parser](https://github.com/boto/botocore/blob/develop/botocore/eventstream.py). It checks first-event delivery before upstream completion, exact bytes, final usage, HTTP errors, and stream errors. AWS Converse frame shapes were also checked with Botocore 1.43.89. This is local protocol evidence; it does not certify every provider endpoint, model, entitlement, or live account. ## Routes ### Anthropic ```text /anthropic/v1/messages /anthropic/v1/messages/count_tokens /v1/messages ``` ### OpenAI ```text /openai/v1/chat/completions /openai/v1/responses /openai/v1/responses/input_tokens /openai/v1/embeddings /v1/chat/completions /v1/responses /v1/responses/input_tokens /v1/embeddings ``` ### Google Gemini ```text /gemini/v1beta/models/{model}:generateContent /gemini/v1beta/models/{model}:streamGenerateContent /gemini/v1beta/models/{model}:countTokens ``` Both `v1beta` and stable `v1` are accepted for these three methods. Equivalent bare Gemini paths are also accepted where profile configuration uses them. See [Google's API versions](https://ai.google.dev/gemini-api/docs/api-versions). ### Amazon Bedrock ```text /bedrock/model/{model}/invoke /bedrock/model/{model}/invoke-with-response-stream /bedrock/model/{model}/converse /bedrock/model/{model}/converse-stream /bedrock/model/{model}/count-tokens ``` Optional Mantle compatibility route: ```text /bedrock/anthropic/v1/messages ``` Bedrock's OpenAI-compatible Chat Completions and Responses APIs on Runtime and Mantle are separate protocols and are not implemented by this Bedrock mount. Paths under `/bedrock/openai/v1/...` or `/bedrock/v1/...` return 404 before forwarding. Enabling the Anthropic Mantle route does not enable them. AWS and the OpenAI SDK distinguish their endpoint roots and IAM signing services; see the [AWS endpoint comparison](https://docs.aws.amazon.com/bedrock/latest/userguide/endpoints.html) and [OpenAI Bedrock provider](https://github.com/openai/openai-python/blob/main/bedrock.md). ### Azure OpenAI and Vertex AI Azure mounts under `/azure/...` after its base URL is configured. Vertex mounts under `/vertex/v1/projects/...` and supports public Google and Anthropic publisher route forms implemented by adapter. Both are opt-in because endpoint and identity configuration are installation-specific. Vertex Express also accepts Google's projectless `/vertex/v1/publishers/google/models/{model}:generateContent` route and the corresponding `:streamGenerateContent` and `:countTokens` methods. Caller API keys use Google's native header; query keys normalize to that header. See [provider authentication](provider-authentication.md) for credential conflicts and the existing OAuth path. Vertex's Google publisher routes also accept `:countTokens`. Token-count requests retain their request and response bytes in every proxy mode; counts are not recorded as generated model usage or spend. These routes follow the [OpenAI SDK](https://github.com/openai/openai-python/blob/main/src/openai/resources/responses/input_tokens.py), [AWS Runtime reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_CountTokens.html), and [Vertex REST reference](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/projects.locations.publishers.models/countTokens). ### OpenAI-compatible providers Named compatibility mounts use: ```text /compat/{name}/... ``` Each mount declares `base_url` and an environment-variable name containing its credential. Compatibility means HTTP shape, not guaranteed support for every provider extension. One mount is built in. The proxy registers `/compat/opencode-go/` with the upstream `https://opencode.ai/zen/go` and the credential variable `OPENCODE_API_KEY`. A `compat` entry with the name `opencode-go` in `caveman.yaml` replaces the built-in mount and can set another endpoint. Pi and local OpenClaw wrappers compare the full request URL their host SDK would send with the URL the running proxy would forward. Scheme, host, port, tenant path, and API version must match. Named mounts use the host's original provider name; native routes use the listener's published native endpoint. Unknown or credential-bearing base URLs remain direct with a notice. A same-host path mismatch is not a verified route. A host provider that answers in-process rather than over HTTP publishes a sentinel base URL with no host. It stays direct and its notice does not propose a compat mount: the provider dispatches on that sentinel value, so routing it would disable the provider instead of compressing it. The proxy publishes credential-free endpoint identities in its run-state file and returns its instance identity on the local health route. Wrappers require that live identity before trusting the file, so a stale process record plus an unrelated listener cannot open the routing gate. Older proxies without endpoint or identity proof leave these host configurations direct. Existing OpenClaw provider identities, model catalogs, fallback settings, and auth profiles remain owned by OpenClaw. Existing managed OpenClaw configurations stay direct until the gateway can establish the same endpoint proof; fresh managed setup still uses its configured Caveman gateway. Endpoint equality is necessary but does not cover host-derived payload policy. Pi preserves supported public compatibility defaults; native OpenAI Chat cache policy and unresolved endpoint-specific attribution can still require direct transport. OpenClaw 2026.8.2 keeps OpenAI Chat, native Responses and native Anthropic routes direct because its public config overlay cannot preserve all private cache, replay, attribution and stream-validation decisions. Supported custom routes also require compatible transport settings and headers. The wrapper reports when proxy compression is off; keeping a host operational on direct transport is not a claim that its traffic was compressed. See the [Pi extension contract](../../packages/pi-extension/README.md). A mount pointing at a loopback relay (litellm, ollama, llama.cpp) also needs a `CAVE_SSRF_ALLOWLIST` entry; see [Security and privacy](security-and-privacy.md). ```yaml compat: myprovider: base_url: http://127.0.0.1:4000 api_key_env: MYPROVIDER_API_KEY ``` A named mount can serve two wire protocols from one upstream. The credential header follows the request path. A request to `/compat/{name}/v1/messages` (Anthropic protocol) carries the key in `x-api-key`. Every other path carries the key in `Authorization: Bearer`. A real inbound Bearer token keeps its header on every path. OpenCode Go rejects a Bearer header on its Anthropic path, so this rule is necessary for the `anthropic-messages` models. The header is the only thing the path decides on its own. If the upstream answers the Anthropic Messages protocol, also declare `wire_dialect: anthropic` on the mount, or its usage blocks are parsed with OpenAI cache semantics and every cache-warm response is recorded as malformed usage — which drops the request from token accounting and from compression eligibility. See [Configuration](configuration.md). ## Modes | Mode | Request behavior | |---|---| | `record` | Forward model-visible bytes unchanged | | `compress` | Apply eligible Engine transforms with recovery, plus the 5.0 savings layers ([below](#compress-mode-in-50)) | | `pixel` | Allow configured text-to-image context transport | | `recommend` | Produce local recommendations without active transform | | `shadow` | Evaluate eligible changes without serving them | | `canary` | Apply configured experimental behavior to selected traffic | | `active` | Apply enabled optimizer behavior | Unknown mode becomes `record`. Standard local CLI workflows expose record, compress, and pixel; other modes support controlled evaluation paths. ## Compress mode in 5.0 Caveman 5.0 turns on its full cache-safe savings stack whenever the proxy runs in `compress` mode. `caveman wrap` uses `compress` by default; a bare `caveman start` stays in `record` unless `think.mode`, `CAVEMAN_MODE`, or `mode` in `caveman.yaml` says otherwise. The switch is `savings_profile` (`CAVEMAN_SAVINGS_PROFILE`): | `savings_profile` | When it applies | What it turns on | |---|---|---| | `max` | Default in `compress` mode | `trim_level: smart_max`, `toolschema_strip: shrink`, and the optimizers `canonical-tool-order`, `anthropic-defer-mcp-tools`, `openai-defer-mcp-tools`, `turn-effort-step`, `anthropic-clear-thinking`, `anthropic-split-cache-ttl`, `gemini-turn-thinking` | | `standard` | Default in every other mode; any unknown value | `trim_level: balanced`; the levers above stay off unless set one by one | Explicit settings win over the profile: `trim_level`, `toolschema_strip`, or an `optimizers` entry set to `false` keeps its value under `max`. `record` mode forwards bytes unchanged whatever the profile says. The layers: | Layer | What it does | Setting | |---|---|---| | Cross-turn shingle delta | In a non-code `tool_result`, a run of at least 4 lines and 80 characters that already appears verbatim in an earlier tool result still in the request becomes `[… N lines identical to earlier tool output …]`, when that saves more than 45 bytes. Blocks under 512 bytes and source-file reads are skipped | Always on in `compress` | | [trim-2](trim-2.md) line selection | Keeps the lines of each live `tool_result` that the current ask needs; pairs with the structural Engine | `trim_level` | | Aged epoch compaction | Compacts old tool results once keeping them costs more than rewriting them (see below) | `epoch_compact` | | Canonical tool order and MCP deferral | Sorts `tools[]` into one stable order and marks MCP tools for deferred loading where the provider supports it | `optimizers` ids above | | Tool-catalog shrink | Rewrites the tool catalog through `caveman-shrink`: drops annotation keywords and condenses long descriptions, keeping names, types, enums, `required`, defaults, and constraint sentences. Deterministic, so the cached prefix stays byte-stable; the original catalog goes to CCR | `toolschema_strip: shrink` | | Anthropic `clear_thinking` | On direct pay-as-you-go `/v1/messages` requests with extended thinking, adds `context_management` with `clear_thinking_20251015`, keeping the 2 most recent thinking turns. Skipped when the caller already sends `context_management` | `anthropic-clear-thinking`, `CAVEMAN_CLEAR_THINKING=1` | | Anthropic split cache TTL | On pay-as-you-go Anthropic requests, upgrades only the tools and system cache breakpoints to a 1-hour TTL; the growing message history keeps 5 minutes | `anthropic-split-cache-ttl`, `CAVEMAN_SPLIT_CACHE_TTL=1` | | Turn-effort stepping | Lowers reasoning effort on mechanical continuation turns ("continue", "go ahead") with append-only per-message effort marks on models that support them (Claude 5 and later, OpenAI Responses GPT-6 and later). Never edits the top-level effort, which would invalidate the cache | `turn-effort-step`, `CAVEMAN_TURN_EFFORT=1` | | Gemini turn thinking | On Gemini 3 and 4 `generateContent` requests (Gemini API or Vertex) whose latest turn is only a clean function response (no human prompt, no error output), sets `thinkingConfig.thinkingLevel` to `LOW`. Never writes `thinkingBudget` and never overrides a caller's value | `gemini-turn-thinking` or `turn-effort-step`: either one turns it on, so turning it off under `max` takes both set to `false` | Every lossy layer stores the exact original before it sends the smaller form, and every rewrite is a pure function of the block's bytes. The first decision for a block is memoised in the PrefixCache and re-sent on every later turn, so the content layers only change blocks the provider has not cached yet. Aged epoch compaction is the one deliberate exception: it rewrites cached history, and only when its trigger (below) says that pays. `TestCacheEconomicsGate` replays 3-, 10- and 18-turn sessions on Anthropic, OpenAI Responses, Gemini, and an OpenAI-compatible mount, with structural compression, canonical tool order, and `ttl_aware` epoch compaction; trim-2 and the provider levers are not in it. It fails on a cache bust caused by Caveman, a recovery handle that does not resolve, or a session whose cache-weighted input costs more than sending it uncompressed. ### Aged epoch compaction Agents resend every old tool result on every turn. Epoch compaction replaces stale ones with a compact, verbatim, in-order excerpt of each block: its opening header, error and test-summary lines, its highest-scoring lines by [trim-2](trim-2.md), any trailing ``, and the CCR handle of the full original. It keeps about 12% of a source-code block and 6% of a log or search block. Older snapshots of the same read-only command (`git status`, `ls`, `rg`, `go test` and similar) are superseded by the newest one, and old `Write`/`Edit` tool inputs are compacted after their bytes are archived. Compaction rewrites history, which costs one cache write. The trigger weighs that cost per provider: | `epoch_compact` | Compacts when | |---|---| | `ttl_aware` (default) | The provider's prompt cache has already expired since the last turn and the saving clears a floor (free, nothing left to bust); or, on a long active session, the expected cached-read saving over the next turns exceeds 1.6 times the cache-write penalty | | `ttl_only` | Only after the cache has expired. Never forces a cache write | | `off` | Never. Unknown values also mean `off` | The economics use each provider's cache prices: Anthropic and Bedrock Claude write at 1.25x and read at 0.10x, OpenAI and Azure write at 1.0x and read at 0.10x on GPT-5 and later (0.50x before), Gemini and Vertex write at 1.0x and read at 0.25x, and uncached OpenAI-compatible upstreams pay 1.0x on every turn. The 4 most recent tool results are never compacted, and blocks under 220 tokens are left alone. A compacted conversation keeps its new excerpts frozen, so every later turn extends the new prefix; the rollover turn is recorded with its own cache-bust cause rather than counted as a Caveman bust. ### Provider coverage The same live-zone pipeline runs on Anthropic, OpenAI Chat and Responses, Azure OpenAI, OpenAI-compatible mounts, Gemini, Vertex (Google and Anthropic publishers), and Bedrock Converse and Anthropic-wire Invoke and Mantle requests. Bedrock `/invoke` for other model vendors and every count-tokens route stay byte-for-byte pass-through. `TestProviderAdapterConformanceContract` holds all eight adapter shapes to one contract. trim-2 needs the human ask as its query. The proxy reads it from Anthropic, OpenAI, Azure, OpenAI-compatible, and Gemini requests only, so on Bedrock and Vertex the structural Engine runs without trim-2. The Responses API WebSocket routes (`/v1/responses`, `/openai/v1/responses`, `/chatgpt/responses`) compress complete, unfragmented, masked text frames carrying `"type":"response.create"`. Binary, control, compressed (RSV), fragmented, oversized, and non-shrinking frames are forwarded verbatim. A frame gets content compression, trim-2 included, and canonical tool order; the tool-catalog shrink and the provider levers run on HTTP requests only. ## Streaming Proxy preserves provider streaming protocols and status behavior. Request transforms finish before upstream dispatch; streaming response stays streaming. ## Reliability The proxy keeps a live agent's endpoint open and never fakes a result: - The serve loop has no idle exit. Only an explicit stop or a process failure ends it, even when an old install still exports `CAVEMAN_NATIVE_IDLE_TIMEOUT`. - A wrapper never restarts a shared listener to change mode or recovery settings. An incompatible new run launches with its own direct provider configuration instead, and a failed local start also launches direct rather than exporting a dead endpoint. - No total upstream deadline by default, so a long stream is never cut off. `CAVE_GATEWAY_UPSTREAM_TIMEOUT_MS` sets an explicit cap. An upstream that connects and then sends nothing is bounded by the response-header deadline, `CAVE_GATEWAY_RESPONSE_HEADER_TIMEOUT_MS` (default 900,000 ms; `0` removes it). - Streams are detected from the response `Content-Type` (SSE, Bedrock event streams, JSON-line streams), not from the request's `stream` flag. Headers flush at once and unknown events pass through unchanged. - An interrupted upstream stream aborts the client's HTTP framing. The proxy records the error and never fabricates a clean end or replays a partial stream. - Retries cover connection setup only (the TCP dial and the `CONNECT` to an outbound HTTP proxy). Ambiguous upload or header failures and truncated bodies are not replayed. A complete 4xx on a transformed request can fall back once to the original bytes. - An encoded request (`Content-Encoding`) keeps its header and bypasses optimization. - Buffers are bounded: non-streaming responses up to 64 MiB (`CAVE_MAX_RESPONSE_BUFFER_BYTES`). The ChatGPT route reads a compress-eligible request whole up to 32 MiB and streams a larger one through untransformed. An agent cannot move off a proxy process the OS killed. Native prompt hooks can start a missing local proxy again; there is no mid-stream migration. ## Credentials API keys stay outside YAML. Anthropic, OpenAI, Gemini, and Azure use their named environment variables; Bedrock uses supported AWS or bearer-token identity paths. Never log authorization headers. Local telemetry should store usage and bounded metadata, not raw secrets. ## Endpoint security Proxy rejects a non-loopback listen address unless `CAVEMAN_AUTH_TOKEN` is set. With that token every request must present it in `x-cave-api-key` or `Authorization: Bearer`; the proxy consumes the header before resolving a provider credential, so it never reaches a provider. Health and metrics endpoints stay unauthenticated. Outbound Server-Side Request Forgery protection checks configured endpoints and redirects. Private, link-local, and loopback upstreams are blocked unless explicitly included in `CAVE_SSRF_ALLOWLIST` for a self-hosted setup; link-local and metadata addresses have no allowlist escape. See [Security and privacy](security-and-privacy.md) before allowing a local model endpoint. ## Pricing and usage Provider catalog supplies dated public list prices. Unknown provider or model prices resolve to zero with an `unpriced` marker rather than a guessed cost. Provider-reported token counts remain distinct from Engine estimates. Displayed provider cost is a list-price subtotal, not a provider invoice. See [Accounting and evidence](accounting-and-evidence.md). ## Troubleshooting - A `404` often means agent uses wrong provider mount or bare route. - Authentication failures should be checked at inbound header and provider credential source without printing secret values. - A blocked custom base URL usually needs a precise `CAVE_SSRF_ALLOWLIST` entry. The proxy answers `502 cave_upstream_blocked` (not `cave_upstream_unavailable`) and logs one `WARN` line naming the refused host and the entry to add. - Unexpected unchanged context is valid when mode is record or a transform fails parse, size, policy, or recovery gates. - For behavior comparison, repeat request in record mode and compare provider request and response classes, not secret-bearing raw logs.