mirror of
https://github.com/instructkr/claw-code.git
synced 2026-11-27 18:37:54 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0210856f6b | ||
|
|
52bbfccb2a | ||
|
|
41837f8d82 | ||
|
|
1849213241 | ||
|
|
578e910bd8 | ||
|
|
ecd697f9f2 | ||
|
|
ca8752613b | ||
|
|
a5c2775e81 | ||
|
|
659f630cce | ||
|
|
d53a088278 | ||
|
|
eb6f730839 | ||
|
|
054447e6c2 | ||
|
|
dcf154793a | ||
|
|
c3d19aa7d8 | ||
|
|
56c53efa64 | ||
|
|
dae4337e8b | ||
|
|
4fb176c65d | ||
|
|
f3b0bd5058 | ||
|
|
078a27ece5 | ||
|
|
508b4d862d | ||
|
|
f51a33a896 | ||
|
|
6a29e08883 | ||
|
|
7041894439 | ||
|
|
333298ae53 | ||
|
|
fe2b64ae9e |
No files matched your search
@@ -29,13 +29,17 @@ jobs:
|
||||
bin: claw
|
||||
artifact_name: claw-linux-x64
|
||||
- name: macos-arm64
|
||||
os: macos-14
|
||||
os: macos-15
|
||||
bin: claw
|
||||
artifact_name: claw-macos-arm64
|
||||
- name: windows-x64
|
||||
os: windows-latest
|
||||
bin: claw.exe
|
||||
artifact_name: claw-windows-x64.exe
|
||||
- name: windows-arm64
|
||||
os: windows-11-arm
|
||||
bin: claw.exe
|
||||
artifact_name: claw-windows-arm64.exe
|
||||
defaults:
|
||||
run:
|
||||
working-directory: rust
|
||||
|
||||
@@ -126,8 +126,15 @@ jobs:
|
||||
run: cargo clippy --workspace
|
||||
|
||||
windows-smoke:
|
||||
name: Windows tests and PowerShell smoke
|
||||
runs-on: windows-latest
|
||||
name: Windows tests and PowerShell smoke (${{ matrix.runner }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runner:
|
||||
- windows-latest
|
||||
- windows-11-arm
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: rust
|
||||
|
||||
@@ -5,6 +5,52 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.1.15] - 2026-11-27
|
||||
|
||||
### Added
|
||||
|
||||
- Outbound extra-headers hook for AnthropicClient, OpenAiCompatClient, and ProviderClient to add custom headers to model requests (#3407)
|
||||
|
||||
### Changed
|
||||
|
||||
- Documentation: document WorldRouter OpenAI-compatible gateway setup (d53a0882)
|
||||
- Documentation: document onomeo OpenAI-compatible gateway setup (#3399)
|
||||
- Documentation: document Straitly OpenAI-compatible gateway setup (#3400)
|
||||
- Documentation: document TeamoRouter OpenAI-compatible gateway setup (#3402)
|
||||
- Documentation: document TrustedRouter OpenAI-compatible gateway setup (#3403)
|
||||
- Documentation: rename UberLLM to MartLLM in gateway setup documentation (#3405)
|
||||
|
||||
### Internal/Tests
|
||||
|
||||
- Windows ARM64 bash test timeout hardening (#3406)
|
||||
|
||||
## [0.1.14] - 2026-11-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- Respect configured output token limits in message requests (#3385)
|
||||
- Match CRLF line endings in edit_file tool (#3387)
|
||||
- Prune heavy directories in grep_search to improve query performance (#3388)
|
||||
|
||||
### Added
|
||||
|
||||
- Gemini and OpenAI pro and long-context pricing tiers for token usage calculations (#3389)
|
||||
- Expose selector in read_file schema to enable iteration over file sections (#3395)
|
||||
- Windows ARM64 CI build and test support (#3393)
|
||||
|
||||
### Changed
|
||||
|
||||
- Documentation: list deja-vu in ecosystem section (#3390)
|
||||
- Documentation: document HopBase OpenAI-compatible gateway setup (#3384)
|
||||
- Documentation: document Standard Compute OpenAI-compatible gateway setup (#3383)
|
||||
- Documentation: document UberLLM OpenAI-compatible gateway setup (#3391)
|
||||
|
||||
## [0.1.13] - 2026-11-09
|
||||
|
||||
### Fixed
|
||||
|
||||
- Anthropic and OpenAI-compatible providers now retry HTTP 529 (overloaded) responses and transient gateway HTTP 400 responses (empty or unparseable body, connection reset, broken pipe, empty reply) with the existing bounded backoff, instead of failing the request immediately (#3381)
|
||||
|
||||
## [0.1.12] - 2026-11-08
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -298,6 +298,10 @@ Claw Code is built in the open alongside the broader UltraWorkers toolchain:
|
||||
- [gajae-code](https://github.com/Yeachan-Heo/gajae-code)
|
||||
- [UltraWorkers Discord](https://discord.gg/5TUQKqFWd)
|
||||
|
||||
Community integrations:
|
||||
|
||||
- [deja-vu](https://github.com/vshulcz/deja-vu) — local BM25 session memory across Claw Code (`~/.claw/sessions/`) and 46 other coding agents
|
||||
|
||||
## Ownership / affiliation disclaimer
|
||||
|
||||
- This repository does **not** claim ownership of the original Claude Code source material.
|
||||
|
||||
@@ -389,6 +389,27 @@ These are the models registered in the built-in alias table with known token lim
|
||||
|
||||
Any model name that does not match an alias is passed through verbatim after provider routing is resolved. This is how you use OpenRouter model slugs (`openai/gpt-4.1-mini` with a custom `OPENAI_BASE_URL`), Ollama tags (`llama3.2` or `qwen2.5-coder:7b`), slash-containing local IDs (`local/Qwen/Qwen3.6-27B-FP8`), or full Anthropic model IDs (`claude-sonnet-4-20250514`).
|
||||
|
||||
### Output token limit
|
||||
|
||||
Set `plugins.maxOutputTokens` in a settings file, such as
|
||||
`.claw/settings.local.json`, to override the output token allowance sent by the
|
||||
`claw` CLI:
|
||||
|
||||
```json
|
||||
{
|
||||
"plugins": {
|
||||
"maxOutputTokens": 1024
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The CLI loads this setting when constructing the conversation client and applies
|
||||
it to each model request, including requests after tool results. When omitted,
|
||||
the existing per-model defaults remain in effect. Choose a positive limit that
|
||||
fits the server's output allowance and leaves room for the input within its
|
||||
context window. This setting does not automatically query server limits and
|
||||
does not configure separate sub-agent clients or the `claw-analog` binary.
|
||||
|
||||
### User-defined aliases
|
||||
|
||||
You can add custom aliases in any settings file (`~/.claw/settings.json`, `.claw/settings.json`, or `.claw/settings.local.json`):
|
||||
|
||||
@@ -170,27 +170,214 @@ curl -sS "https://llmtr.com/v1/models" \
|
||||
| jq -r '.data[] | "\(.id)\t\(.top_provider.max_completion_tokens)"'
|
||||
```
|
||||
|
||||
## UberLLM
|
||||
## MartLLM
|
||||
|
||||
[UberLLM](https://uberllm.dev) is a pay-as-you-go OpenAI-compatible gateway (prepaid, no free tier). Set `OPENAI_BASE_URL` to `https://api.uberllm.dev/v1` and `OPENAI_API_KEY` to a bearer key (`ull_...`).
|
||||
[MartLLM](https://martllm.com) is a pay-as-you-go OpenAI-compatible gateway (prepaid, no free tier). Set `OPENAI_BASE_URL` to `https://api.martllm.com/v1` and `OPENAI_API_KEY` to a bearer key (`ull_...`).
|
||||
|
||||
```bash
|
||||
export OPENAI_BASE_URL="https://api.uberllm.dev/v1"
|
||||
export OPENAI_BASE_URL="https://api.martllm.com/v1"
|
||||
export OPENAI_API_KEY="ull_..."
|
||||
claw --model "local/deepseek/deepseek-v4-flash" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
UberLLM ids are vendor-prefixed (`deepseek/deepseek-v4-flash`, `moonshotai/kimi-k2.6`, `qwen/qwen3.8-flash`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the catalog id goes out unchanged. Some prefixes would otherwise pick a native route; a bare `qwen/qwen3.8-flash`, for example, goes to DashScope and asks for `DASHSCOPE_API_KEY`.
|
||||
MartLLM ids are vendor-prefixed (`deepseek/deepseek-v4-flash`, `moonshotai/kimi-k2.6`, `qwen/qwen3.8-flash`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the catalog id goes out unchanged. Some prefixes would otherwise pick a native route; a bare `qwen/qwen3.8-flash`, for example, goes to DashScope and asks for `DASHSCOPE_API_KEY`.
|
||||
|
||||
Claw asks for up to 64,000 output tokens on these routes. UberLLM does not reject that on a model with a smaller output limit (for example `aion-labs/aion-3-0-mini`, 32,768); the answer is simply bounded by the model's limit, listed as `max_output_tokens` in the catalog below.
|
||||
Claw asks for up to 64,000 output tokens on these routes. MartLLM does not reject that on a model with a smaller output limit (for example `aion-labs/aion-3-0-mini`, 32,768); the answer is simply bounded by the model's limit, listed as `max_output_tokens` in the catalog below.
|
||||
|
||||
The public model list does not need a key:
|
||||
|
||||
```bash
|
||||
curl -sS "https://api.uberllm.dev/v1/models" \
|
||||
curl -sS "https://api.martllm.com/v1/models" \
|
||||
| jq -r '.data[] | "\(.id)\t\(.max_output_tokens)"'
|
||||
```
|
||||
|
||||
## Standard Compute
|
||||
|
||||
[Standard Compute](https://standardcompute.com) is an OpenAI-compatible gateway. Set `OPENAI_BASE_URL` to `https://api.stdcmpt.com/v1` and `OPENAI_API_KEY` to your Standard Compute key.
|
||||
|
||||
```bash
|
||||
export STANDARDCOMPUTE_API_KEY="your-standardcompute-api-key"
|
||||
export OPENAI_BASE_URL="https://api.stdcmpt.com/v1"
|
||||
export OPENAI_API_KEY="$STANDARDCOMPUTE_API_KEY"
|
||||
claw --model "local/StandardCompute" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
`StandardCompute` is the routed model: the router picks from the models enabled on your account using your quality preference, so harder tasks go to stronger models and simpler ones to cheaper models ([routing docs](https://docs.standardcompute.com/models#smart-routing)). It is a bare name on a remote gateway, so it needs the `local/` hatch, which selects the OpenAI-compatible transport and is removed before the request.
|
||||
|
||||
To pin one model, use a vendor-prefixed id from the catalog with the same hatch, for example `--model "local/deepseek/deepseek-v4-flash"`. A bare vendor prefix can pick a native route instead of the gateway.
|
||||
|
||||
The public model list does not need a key:
|
||||
|
||||
```bash
|
||||
curl -sS "https://api.stdcmpt.com/v1/models" | jq -r '.data[].id'
|
||||
```
|
||||
|
||||
See the [Standard Compute docs](https://docs.standardcompute.com) for keys and account setup.
|
||||
|
||||
## HopBase
|
||||
|
||||
[HopBase](https://hop-base.com) is an OpenAI-compatible API for Claude, GPT, GLM, DeepSeek, Qwen, and other model families. Set `OPENAI_BASE_URL` to `https://api.hop-base.com/v1` and `OPENAI_API_KEY` to your HopBase key.
|
||||
|
||||
```bash
|
||||
export HOPBASE_API_KEY="your-hopbase-api-key"
|
||||
export OPENAI_BASE_URL="https://api.hop-base.com/v1"
|
||||
export OPENAI_API_KEY="$HOPBASE_API_KEY"
|
||||
claw --model "local/glm-5.3-flash" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
HopBase ids are bare names without a vendor prefix (`glm-5.3-flash`, `gpt-5.6-luna`, `claude-sonnet-5-5`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the id goes out unchanged. Without it, a bare `claude-` id picks the native Anthropic route, and a bare `qwen-` or `kimi-` id goes to DashScope.
|
||||
|
||||
The model list needs your key and shows the ids that key can call:
|
||||
|
||||
```bash
|
||||
curl -sS "https://api.hop-base.com/v1/models" \
|
||||
-H "Authorization: Bearer $OPENAI_API_KEY" | jq -r '.data[].id'
|
||||
```
|
||||
|
||||
See the [HopBase docs](https://hop-base.com/en/docs) for keys and account setup.
|
||||
|
||||
## Requesty
|
||||
|
||||
[Requesty](https://www.requesty.ai) is an OpenAI-compatible gateway that routes to first-party providers such as OpenAI, Anthropic, and Google. Set `OPENAI_BASE_URL` to `https://router.requesty.ai/v1` (or `https://router.eu.requesty.ai/v1` for the EU endpoint) and `OPENAI_API_KEY` to your Requesty key.
|
||||
|
||||
```bash
|
||||
export REQUESTY_API_KEY="your-requesty-api-key"
|
||||
export OPENAI_BASE_URL="https://router.requesty.ai/v1"
|
||||
export OPENAI_API_KEY="$REQUESTY_API_KEY"
|
||||
claw --model "local/anthropic/claude-sonnet-5-5" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
Requesty ids are vendor-prefixed (`openai/gpt-4o-mini`, `anthropic/claude-sonnet-5-5`, `google/gemini-3.6-flash`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the catalog id goes out unchanged. Without it, an `anthropic/` id picks the native Anthropic route and asks for `ANTHROPIC_API_KEY`.
|
||||
|
||||
Requesty also serves the Anthropic Messages API, so the native route works as well: set `ANTHROPIC_BASE_URL` to `https://router.requesty.ai` (no `/v1`) and `ANTHROPIC_API_KEY` to the same key, then run `--model "anthropic/claude-sonnet-5-5"`.
|
||||
|
||||
The public model list does not need a key:
|
||||
|
||||
```bash
|
||||
curl -sS "https://router.requesty.ai/v1/models" \
|
||||
| jq -r '.data[] | "\(.id)\t\(.max_output_tokens)"'
|
||||
```
|
||||
|
||||
See the [Requesty docs](https://docs.requesty.ai) for keys and account setup.
|
||||
|
||||
## WorldRouter
|
||||
|
||||
[WorldRouter](https://www.worldrouter.ai) is an OpenAI-compatible gateway for Claude, GPT, Gemini, DeepSeek, Kimi, and GLM models. Set `OPENAI_BASE_URL` to `https://inference-api.worldrouter.ai/v1` and `OPENAI_API_KEY` to your WorldRouter key.
|
||||
|
||||
```bash
|
||||
export WORLDROUTER_API_KEY="your-worldrouter-api-key"
|
||||
export OPENAI_BASE_URL="https://inference-api.worldrouter.ai/v1"
|
||||
export OPENAI_API_KEY="$WORLDROUTER_API_KEY"
|
||||
claw --model "local/deepseek-v4-flash" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
WorldRouter ids are bare names without a vendor prefix (`deepseek-v4-flash`, `gpt-5.4`, `claude-sonnet-5-5`, `gemini-4-neon`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the id goes out unchanged. Without it, a bare `claude-` id picks the native Anthropic route and asks for `ANTHROPIC_API_KEY`.
|
||||
|
||||
WorldRouter also serves the Anthropic Messages API, so the native route works as well: set `ANTHROPIC_BASE_URL` to `https://inference-api.worldrouter.ai` (no `/v1`) and `ANTHROPIC_API_KEY` to the same key, then run `--model "claude-sonnet-5-5"`.
|
||||
|
||||
The model list needs your key and shows the ids that key can call:
|
||||
|
||||
```bash
|
||||
curl -sS "https://inference-api.worldrouter.ai/v1/models" \
|
||||
-H "Authorization: Bearer $OPENAI_API_KEY" | jq -r '.data[].id'
|
||||
```
|
||||
|
||||
See the [WorldRouter quickstart](https://www.worldrouter.ai/docs/quickstart) for keys and account setup.
|
||||
|
||||
## onomeo
|
||||
|
||||
[onomeo](https://onomeo.com) is an OpenAI-compatible gateway for Claude, GPT, Gemini and DeepSeek models. Set `OPENAI_BASE_URL` to `https://onomeo.com/v1` and `OPENAI_API_KEY` to your onomeo key.
|
||||
|
||||
```bash
|
||||
export ONOMEO_API_KEY="your-onomeo-api-key"
|
||||
export OPENAI_BASE_URL="https://onomeo.com/v1"
|
||||
export OPENAI_API_KEY="$ONOMEO_API_KEY"
|
||||
claw --model "local/deepseek-v4.1-flash" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
onomeo ids are bare names without a vendor prefix (`deepseek-v4.1-flash`, `claude-sonnet-5.5`, `gpt-6.2-sol`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the id goes out unchanged. Without it, a bare `claude-` id picks the native Anthropic route and asks for `ANTHROPIC_API_KEY`.
|
||||
|
||||
onomeo also serves the Anthropic Messages API, so the native route works as well: set `ANTHROPIC_BASE_URL` to `https://onomeo.com` (no `/v1`) and `ANTHROPIC_API_KEY` to the same key, then run `--model "claude-sonnet-5.5"`.
|
||||
|
||||
The model list needs your key and shows the ids that key can call:
|
||||
|
||||
```bash
|
||||
curl -sS "https://onomeo.com/v1/models" \
|
||||
-H "Authorization: Bearer $OPENAI_API_KEY" | jq -r '.data[].id'
|
||||
```
|
||||
|
||||
See the [onomeo integration guides](https://onomeo.com/integrations) for keys and account setup.
|
||||
|
||||
## Straitly
|
||||
|
||||
[Straitly](https://straitly.ai) is an AI gateway with one OpenAI-compatible API key for 150+ models, including Claude, GPT, Gemini, Grok and DeepSeek. Set `OPENAI_BASE_URL` to `https://api.straitly.ai/v1` and `OPENAI_API_KEY` to your Straitly key.
|
||||
|
||||
```bash
|
||||
export STRAITLY_API_KEY="your-straitly-api-key"
|
||||
export OPENAI_BASE_URL="https://api.straitly.ai/v1"
|
||||
export OPENAI_API_KEY="$STRAITLY_API_KEY"
|
||||
claw --model "local/deepseek/deepseek-v4-1-flash" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
Straitly ids are vendor-prefixed (`owner/model`, such as `deepseek/deepseek-v4-1-flash`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the catalog id goes out unchanged. Without it, an id that starts with `anthropic/` picks the native Anthropic route and asks for `ANTHROPIC_API_KEY`.
|
||||
|
||||
Claw asks for up to 64,000 output tokens on these routes, so pick a model whose output limit is at least that. `deepseek/deepseek-v4-1-flash` allows 1,048,576. Each model's limit is listed as `top_provider.max_completion_tokens` in the catalog below.
|
||||
|
||||
The public model list does not need a key:
|
||||
|
||||
```bash
|
||||
curl -sS "https://api.straitly.ai/v1/models" \
|
||||
| jq -r '.data[] | "\(.id)\t\(.context_length)\t\(.top_provider.max_completion_tokens)"'
|
||||
```
|
||||
|
||||
See the [Straitly quickstart](https://straitly.ai/docs/quickstart) for keys and account setup.
|
||||
|
||||
## TeamoRouter
|
||||
|
||||
[TeamoRouter](https://teamorouter.com) is an OpenAI-compatible gateway for GLM, Kimi, DeepSeek, Qwen, Claude, GPT, Gemini and other model families behind one key. Set `OPENAI_BASE_URL` to `https://api.teamorouter.com/v1` and `OPENAI_API_KEY` to your TeamoRouter key.
|
||||
|
||||
```bash
|
||||
export TEAMOROUTER_API_KEY="your-teamorouter-api-key"
|
||||
export OPENAI_BASE_URL="https://api.teamorouter.com/v1"
|
||||
export OPENAI_API_KEY="$TEAMOROUTER_API_KEY"
|
||||
claw --model "local/glm-5.3" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
TeamoRouter ids are bare names without a vendor prefix (`glm-5.3`, `deepseek-v4-flash`, `claude-sonnet-5-5`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the id goes out unchanged. Without it, a bare `claude-` id picks the native Anthropic route, and a bare `qwen` or `kimi` id goes to DashScope.
|
||||
|
||||
Claw asks for up to 64,000 output tokens on these routes. `glm-5.3`, `deepseek-v4-flash` and `claude-sonnet-5-5` accept that; models with a lower cap list it as `max_output_tokens` in the public catalog, which does not need a key:
|
||||
|
||||
```bash
|
||||
curl -sS "https://api.teamorouter.com/v1/models/pricing" \
|
||||
| jq -r '.models[] | "\(.id)\t\(.context_window)\t\(.max_output_tokens)"'
|
||||
```
|
||||
|
||||
See the [TeamoRouter docs](https://teamorouter.com/docs) for keys and account setup.
|
||||
|
||||
## TrustedRouter
|
||||
|
||||
[TrustedRouter](https://trustedrouter.com) is an OpenAI-compatible gateway that routes to Anthropic, OpenAI, Google, DeepSeek and other providers behind one key. Set `OPENAI_BASE_URL` to `https://api.trustedrouter.com/v1` and `OPENAI_API_KEY` to your TrustedRouter key.
|
||||
|
||||
```bash
|
||||
export TRUSTEDROUTER_API_KEY="your-trustedrouter-api-key"
|
||||
export OPENAI_BASE_URL="https://api.trustedrouter.com/v1"
|
||||
export OPENAI_API_KEY="$TRUSTEDROUTER_API_KEY"
|
||||
claw --model "local/deepseek/deepseek-v4-flash" prompt "Reply exactly HELLO_WORLD_123"
|
||||
```
|
||||
|
||||
TrustedRouter ids are vendor-prefixed (`deepseek/deepseek-v4-flash`, `anthropic/claude-sonnet-4.5`). Put `local/` in front of every one: the hatch selects the OpenAI-compatible transport and is removed, so the catalog id goes out unchanged. Without it, an `anthropic/` id picks the native Anthropic route and asks for `ANTHROPIC_API_KEY`. The routed model `trustedrouter/auto`, which picks a model per request, takes the same hatch: `--model "local/trustedrouter/auto"`.
|
||||
|
||||
Claw asks for up to 64,000 output tokens on these routes, so pick a model whose output limit is at least that. `deepseek/deepseek-v4-flash` allows 393,216. Each model's limit is listed as `top_provider.max_completion_tokens` in the catalog below.
|
||||
|
||||
The public model list does not need a key:
|
||||
|
||||
```bash
|
||||
curl -sS "https://api.trustedrouter.com/v1/models" \
|
||||
| jq -r '.data[] | "\(.id)\t\(.context_length)\t\(.top_provider.max_completion_tokens)"'
|
||||
```
|
||||
|
||||
See the [TrustedRouter docs](https://trustedrouter.com/docs) for keys and account setup.
|
||||
|
||||
## Local skills install from disk
|
||||
|
||||
Skills are discovered from Claw skill roots such as `.claw/skills/` in a workspace and `~/.claw/skills/` for user-level installs. Legacy `.codex/skills/` roots may also be scanned for compatibility, but new local Claw projects should prefer `.claw/skills/`.
|
||||
|
||||
Generated
+11
-11
@@ -93,7 +93,7 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
|
||||
|
||||
[[package]]
|
||||
name = "api"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"reqwest",
|
||||
@@ -478,7 +478,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "claw-analog"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"api",
|
||||
"clap",
|
||||
@@ -498,7 +498,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "claw-rag-service"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"axum 0.8.9",
|
||||
"blake3",
|
||||
@@ -531,7 +531,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "commands"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"plugins",
|
||||
"runtime",
|
||||
@@ -540,7 +540,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compat-harness"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"commands",
|
||||
"runtime",
|
||||
@@ -1568,7 +1568,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mock-anthropic-service"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"api",
|
||||
"serde_json",
|
||||
@@ -1761,7 +1761,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "plugins"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2136,7 +2136,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "runtime"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"glob",
|
||||
@@ -2263,7 +2263,7 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
|
||||
|
||||
[[package]]
|
||||
name = "rusty-claude-cli"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"api",
|
||||
"commands",
|
||||
@@ -2624,7 +2624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "telemetry"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2904,7 +2904,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tools"
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"api",
|
||||
"aspect-core",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ members = ["crates/*"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.12"
|
||||
version = "0.1.15"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::error::ApiError;
|
||||
use crate::extra_headers::ExtraHeadersHook;
|
||||
use crate::prompt_cache::{PromptCache, PromptCacheRecord, PromptCacheStats};
|
||||
use crate::providers::anthropic::{self, AnthropicClient, AuthSource};
|
||||
use crate::providers::openai_compat::{self, OpenAiCompatClient, OpenAiCompatConfig};
|
||||
@@ -200,6 +201,21 @@ impl ProviderClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Install a provider that may add outbound headers to each model request.
|
||||
///
|
||||
/// Applies to every provider variant. Without a provider the request is
|
||||
/// unchanged.
|
||||
#[must_use]
|
||||
pub fn with_extra_headers_provider(self, provider: ExtraHeadersHook) -> Self {
|
||||
match self {
|
||||
Self::Anthropic(client) => {
|
||||
Self::Anthropic(client.with_extra_headers_provider(provider))
|
||||
}
|
||||
Self::Xai(client) => Self::Xai(client.with_extra_headers_provider(provider)),
|
||||
Self::OpenAi(client) => Self::OpenAi(client.with_extra_headers_provider(provider)),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn prompt_cache_stats(&self) -> Option<PromptCacheStats> {
|
||||
match self {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Optional outbound HTTP header provider for model requests.
|
||||
//!
|
||||
//! Some hosts must annotate each model request with routing, quota, or
|
||||
//! cache-affinity metadata that only the caller can compute. A client opts in
|
||||
//! with [`crate::providers::anthropic::AnthropicClient::with_extra_headers_provider`]
|
||||
//! or [`crate::providers::openai_compat::OpenAiCompatClient::with_extra_headers_provider`];
|
||||
//! clients without a provider send byte-for-byte the same headers as before.
|
||||
//!
|
||||
//! The provider runs in-process and receives the exact JSON body that is about
|
||||
//! to be sent. It must treat the body as read-only: the hook can only add
|
||||
//! headers, never change the payload.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use reqwest::header::{HeaderName, HeaderValue};
|
||||
use reqwest::RequestBuilder;
|
||||
use serde_json::Value;
|
||||
|
||||
/// Facts the host may use when deriving headers.
|
||||
pub struct ExtraHeadersContext<'a> {
|
||||
/// Provider label reported by the client (`"Anthropic"`, `"OpenAI"`, ...).
|
||||
pub provider: &'a str,
|
||||
/// Model id as it appears in the request body.
|
||||
pub model: &'a str,
|
||||
/// The JSON body that will be sent with this request. Read-only.
|
||||
pub body: &'a Value,
|
||||
}
|
||||
|
||||
/// Returns `(name, value)` pairs to add to one outbound request.
|
||||
pub type ExtraHeadersProvider =
|
||||
dyn Fn(&ExtraHeadersContext<'_>) -> Vec<(String, String)> + Send + Sync;
|
||||
|
||||
/// Headers owned by the transport. A provider cannot override them.
|
||||
const RESERVED_HEADERS: &[&str] = &[
|
||||
"accept",
|
||||
"accept-encoding",
|
||||
"anthropic-beta",
|
||||
"anthropic-version",
|
||||
"authorization",
|
||||
"connection",
|
||||
"content-length",
|
||||
"content-type",
|
||||
"host",
|
||||
"transfer-encoding",
|
||||
"user-agent",
|
||||
"x-api-key",
|
||||
];
|
||||
|
||||
/// A header provider attached to one client.
|
||||
///
|
||||
/// Cloning a client shares the provider; the closure must be `Send + Sync`.
|
||||
#[derive(Clone)]
|
||||
pub struct ExtraHeadersHook {
|
||||
provider: Arc<ExtraHeadersProvider>,
|
||||
}
|
||||
|
||||
impl ExtraHeadersHook {
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
provider: impl Fn(&ExtraHeadersContext<'_>) -> Vec<(String, String)> + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self {
|
||||
provider: Arc::new(provider),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the provider's headers to one outbound model request.
|
||||
///
|
||||
/// Invalid names or values, and headers the transport owns, are dropped: a
|
||||
/// broken provider must never fail a model call or rewrite credentials.
|
||||
pub fn apply(
|
||||
&self,
|
||||
mut builder: RequestBuilder,
|
||||
context: &ExtraHeadersContext<'_>,
|
||||
) -> RequestBuilder {
|
||||
for (name, value) in (self.provider)(context) {
|
||||
let Ok(name) = HeaderName::from_bytes(name.as_bytes()) else {
|
||||
continue;
|
||||
};
|
||||
if RESERVED_HEADERS.contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(value) = HeaderValue::from_str(&value) else {
|
||||
continue;
|
||||
};
|
||||
builder = builder.header(name, value);
|
||||
}
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ExtraHeadersHook {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ExtraHeadersHook").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn context<'a>(body: &'a Value) -> ExtraHeadersContext<'a> {
|
||||
ExtraHeadersContext {
|
||||
provider: "Anthropic",
|
||||
model: "claude-sonnet-4",
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_keeps_valid_headers_and_drops_the_rest() {
|
||||
let body = json!({"messages": []});
|
||||
let hook = ExtraHeadersHook::new(|ctx: &ExtraHeadersContext<'_>| {
|
||||
vec![
|
||||
(
|
||||
"x-route".to_string(),
|
||||
format!("{}/{}", ctx.provider, ctx.model),
|
||||
),
|
||||
("authorization".to_string(), "Bearer nope".to_string()),
|
||||
("anthropic-version".to_string(), "2099-01-01".to_string()),
|
||||
("anthropic-beta".to_string(), "none".to_string()),
|
||||
("bad header".to_string(), "dropped".to_string()),
|
||||
("x-blank".to_string(), "bad\r\nvalue".to_string()),
|
||||
]
|
||||
});
|
||||
|
||||
let request = hook
|
||||
.apply(
|
||||
reqwest::Client::new().post("http://127.0.0.1/"),
|
||||
&context(&body),
|
||||
)
|
||||
.build()
|
||||
.expect("request builds");
|
||||
|
||||
assert_eq!(
|
||||
request
|
||||
.headers()
|
||||
.get("x-route")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("Anthropic/claude-sonnet-4")
|
||||
);
|
||||
assert!(request.headers().get("authorization").is_none());
|
||||
assert!(request.headers().get("anthropic-version").is_none());
|
||||
assert!(request.headers().get("anthropic-beta").is_none());
|
||||
assert!(request.headers().get("bad header").is_none());
|
||||
assert!(request.headers().get("x-blank").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
mod client;
|
||||
|
||||
mod error;
|
||||
mod extra_headers;
|
||||
mod http_client;
|
||||
mod prompt_cache;
|
||||
mod providers;
|
||||
@@ -13,6 +14,7 @@ pub use client::{
|
||||
ProviderConfigKind,
|
||||
};
|
||||
pub use error::ApiError;
|
||||
pub use extra_headers::{ExtraHeadersContext, ExtraHeadersHook, ExtraHeadersProvider};
|
||||
pub use http_client::{
|
||||
build_http_client, build_http_client_or_default, build_http_client_with,
|
||||
build_http_client_with_opts, ProxyConfig, TimeoutConfig,
|
||||
|
||||
@@ -13,6 +13,7 @@ use serde_json::{Map, Value};
|
||||
use telemetry::{AnalyticsEvent, AnthropicRequestProfile, ClientIdentity, SessionTracer};
|
||||
|
||||
use crate::error::ApiError;
|
||||
use crate::extra_headers::{ExtraHeadersContext, ExtraHeadersHook};
|
||||
use crate::http_client::build_http_client_or_default;
|
||||
use crate::prompt_cache::{PromptCache, PromptCacheRecord, PromptCacheStats};
|
||||
|
||||
@@ -121,6 +122,7 @@ pub struct AnthropicClient {
|
||||
request_profile: AnthropicRequestProfile,
|
||||
session_tracer: Option<SessionTracer>,
|
||||
prompt_cache: Option<PromptCache>,
|
||||
extra_headers: Option<ExtraHeadersHook>,
|
||||
last_prompt_cache_record: Arc<Mutex<Option<PromptCacheRecord>>>,
|
||||
}
|
||||
|
||||
@@ -137,6 +139,7 @@ impl AnthropicClient {
|
||||
request_profile: AnthropicRequestProfile::default(),
|
||||
session_tracer: None,
|
||||
prompt_cache: None,
|
||||
extra_headers: None,
|
||||
last_prompt_cache_record: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
@@ -153,6 +156,7 @@ impl AnthropicClient {
|
||||
request_profile: AnthropicRequestProfile::default(),
|
||||
session_tracer: None,
|
||||
prompt_cache: None,
|
||||
extra_headers: None,
|
||||
last_prompt_cache_record: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
@@ -254,6 +258,16 @@ impl AnthropicClient {
|
||||
self
|
||||
}
|
||||
|
||||
/// Install a provider that may add outbound headers to each model request.
|
||||
///
|
||||
/// The provider sees the final JSON body and can only add headers. Only
|
||||
/// real model requests reach it: `count_tokens` does not.
|
||||
#[must_use]
|
||||
pub fn with_extra_headers_provider(mut self, provider: ExtraHeadersHook) -> Self {
|
||||
self.extra_headers = Some(provider);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn prompt_cache_stats(&self) -> Option<PromptCacheStats> {
|
||||
self.prompt_cache.as_ref().map(PromptCache::stats)
|
||||
@@ -488,7 +502,17 @@ impl AnthropicClient {
|
||||
) -> Result<reqwest::Response, ApiError> {
|
||||
let request_url = format!("{}/v1/messages", self.base_url.trim_end_matches('/'));
|
||||
let request_body = render_standard_messages_body(&self.request_profile, request)?;
|
||||
let request_builder = self.build_request(&request_url).json(&request_body);
|
||||
let mut request_builder = self.build_request(&request_url).json(&request_body);
|
||||
if let Some(extra_headers) = &self.extra_headers {
|
||||
request_builder = extra_headers.apply(
|
||||
request_builder,
|
||||
&ExtraHeadersContext {
|
||||
provider: "Anthropic",
|
||||
model: &request.model,
|
||||
body: &request_body,
|
||||
},
|
||||
);
|
||||
}
|
||||
request_builder.send().await.map_err(ApiError::from)
|
||||
}
|
||||
|
||||
@@ -889,7 +913,7 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
|
||||
let request_id = request_id_from_headers(&headers).map(String::into_boxed_str);
|
||||
let body = response.text().await.unwrap_or_else(|_| String::new());
|
||||
let parsed_error = serde_json::from_str::<AnthropicErrorEnvelope>(&body).ok();
|
||||
let retryable = is_retryable_status(status);
|
||||
let retryable = is_retryable_status(status) || is_retryable_400(status, &body);
|
||||
let retry_after = parse_retry_after(&headers, status).map(Box::new);
|
||||
|
||||
Err(ApiError::Api {
|
||||
@@ -923,7 +947,10 @@ fn parse_retry_after(
|
||||
}
|
||||
|
||||
const fn is_retryable_status(status: reqwest::StatusCode) -> bool {
|
||||
matches!(status.as_u16(), 408 | 409 | 429 | 500 | 502 | 503 | 504)
|
||||
matches!(
|
||||
status.as_u16(),
|
||||
408 | 409 | 429 | 500 | 502 | 503 | 504 | 529
|
||||
)
|
||||
}
|
||||
|
||||
/// Some providers return HTTP 400 with an unparseable body when a gateway
|
||||
@@ -1095,7 +1122,8 @@ mod tests {
|
||||
now_unix_timestamp, oauth_token_is_expired, resolve_saved_oauth_token,
|
||||
resolve_startup_auth_source, AnthropicClient, AuthSource, OAuthTokenSet,
|
||||
};
|
||||
use crate::types::{ContentBlockDelta, MessageRequest};
|
||||
use crate::extra_headers::ExtraHeadersHook;
|
||||
use crate::types::{ContentBlockDelta, InputMessage, MessageRequest};
|
||||
|
||||
fn temp_config_home() -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!(
|
||||
@@ -1146,6 +1174,56 @@ mod tests {
|
||||
format!("http://{address}/oauth/token")
|
||||
}
|
||||
|
||||
fn spawn_status_server(status: u16, body: &'static str) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
|
||||
let address = listener.local_addr().expect("local addr");
|
||||
thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().expect("accept connection");
|
||||
let mut buffer = [0_u8; 4096];
|
||||
let _ = stream.read(&mut buffer).expect("read request");
|
||||
let response = format!(
|
||||
"HTTP/1.1 {status} STATUS\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.expect("write response");
|
||||
});
|
||||
format!("http://{address}/v1/messages")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expect_success_marks_529_overloaded_retryable() {
|
||||
let url = spawn_status_server(
|
||||
529,
|
||||
r#"{"error":{"type":"overloaded_error","message":"Overloaded"}}"#,
|
||||
);
|
||||
let response = reqwest::get(&url).await.expect("response");
|
||||
let error = super::expect_success(response)
|
||||
.await
|
||||
.expect_err("529 should error");
|
||||
assert!(error.is_retryable(), "529 overloaded must be retryable");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expect_success_marks_gateway_flake_400_retryable() {
|
||||
let url = spawn_status_server(400, "HTTP 400 from backend (no parseable body)");
|
||||
let response = reqwest::get(&url).await.expect("response");
|
||||
let error = super::expect_success(response)
|
||||
.await
|
||||
.expect_err("400 should error");
|
||||
assert!(
|
||||
error.is_retryable(),
|
||||
"gateway-flake 400 body must be retryable"
|
||||
);
|
||||
let url = spawn_status_server(400, "invalid request: max_tokens must be positive");
|
||||
let response = reqwest::get(&url).await.expect("response");
|
||||
let error = super::expect_success(response)
|
||||
.await
|
||||
.expect_err("400 should error");
|
||||
assert!(!error.is_retryable(), "a real 400 must not be retried");
|
||||
}
|
||||
#[test]
|
||||
fn read_api_key_requires_presence() {
|
||||
let _guard = env_lock();
|
||||
@@ -1445,6 +1523,40 @@ mod tests {
|
||||
assert!(!super::is_retryable_status(
|
||||
reqwest::StatusCode::UNAUTHORIZED
|
||||
));
|
||||
// Anthropic returns the non-standard 529 when the API is overloaded;
|
||||
// it is transient and must be retried like a 503.
|
||||
assert!(super::is_retryable_status(
|
||||
reqwest::StatusCode::from_u16(529).expect("529 is a valid status")
|
||||
));
|
||||
assert!(!super::is_retryable_status(
|
||||
reqwest::StatusCode::BAD_REQUEST
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_flake_400_bodies_are_retryable() {
|
||||
// Gateways and proxies surface transient network failures as HTTP 400
|
||||
// with an unparseable body; is_retryable_400 detects them so
|
||||
// expect_success marks the resulting error retryable.
|
||||
for body in [
|
||||
"HTTP 400 from backend (no parseable body)",
|
||||
"upstream connection reset by peer",
|
||||
"Broken pipe while reading response",
|
||||
"Empty reply from server",
|
||||
] {
|
||||
assert!(
|
||||
super::is_retryable_400(reqwest::StatusCode::BAD_REQUEST, body),
|
||||
"body should be retryable: {body}"
|
||||
);
|
||||
}
|
||||
assert!(!super::is_retryable_400(
|
||||
reqwest::StatusCode::BAD_REQUEST,
|
||||
"invalid request: max_tokens must be positive"
|
||||
));
|
||||
assert!(!super::is_retryable_400(
|
||||
reqwest::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"connection reset"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1804,4 +1916,58 @@ mod tests {
|
||||
crate::error::ApiError::InvalidSseFrame(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extra_headers_provider_annotates_the_wire_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
|
||||
let address = listener.local_addr().expect("local addr");
|
||||
let (request_tx, request_rx) = std::sync::mpsc::channel();
|
||||
thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().expect("accept connection");
|
||||
let mut buffer = [0_u8; 8192];
|
||||
let read = stream.read(&mut buffer).expect("read request");
|
||||
request_tx
|
||||
.send(String::from_utf8_lossy(&buffer[..read]).into_owned())
|
||||
.expect("send request");
|
||||
let body = r#"{"id":"msg_test","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}"#;
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.expect("write response");
|
||||
});
|
||||
|
||||
let client = AnthropicClient::new("test-key")
|
||||
.with_base_url(format!("http://{address}"))
|
||||
.with_extra_headers_provider(ExtraHeadersHook::new(
|
||||
|ctx: &crate::extra_headers::ExtraHeadersContext<'_>| {
|
||||
vec![(
|
||||
"x-route".to_string(),
|
||||
format!("{}/{}", ctx.provider, ctx.model),
|
||||
)]
|
||||
},
|
||||
));
|
||||
let request = MessageRequest {
|
||||
model: "claude-sonnet-4".to_string(),
|
||||
max_tokens: 16,
|
||||
messages: vec![InputMessage::user_text("hello")],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let response = client.send_raw_request(&request).await.expect("response");
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
|
||||
let captured = request_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("captured request");
|
||||
assert!(
|
||||
captured
|
||||
.to_lowercase()
|
||||
.contains("x-route: anthropic/claude-sonnet-4"),
|
||||
"wire request must carry the provider header: {captured}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::error::ApiError;
|
||||
use crate::extra_headers::{ExtraHeadersContext, ExtraHeadersHook};
|
||||
use crate::http_client::build_http_client_or_default;
|
||||
use crate::types::{
|
||||
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||
@@ -129,6 +130,7 @@ pub struct OpenAiCompatClient {
|
||||
max_retries: u32,
|
||||
initial_backoff: Duration,
|
||||
max_backoff: Duration,
|
||||
extra_headers: Option<ExtraHeadersHook>,
|
||||
}
|
||||
|
||||
impl OpenAiCompatClient {
|
||||
@@ -150,6 +152,7 @@ impl OpenAiCompatClient {
|
||||
max_retries: DEFAULT_MAX_RETRIES,
|
||||
initial_backoff: DEFAULT_INITIAL_BACKOFF,
|
||||
max_backoff: DEFAULT_MAX_BACKOFF,
|
||||
extra_headers: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +188,7 @@ impl OpenAiCompatClient {
|
||||
max_retries: DEFAULT_MAX_RETRIES,
|
||||
initial_backoff: DEFAULT_INITIAL_BACKOFF,
|
||||
max_backoff: DEFAULT_MAX_BACKOFF,
|
||||
extra_headers: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -225,6 +229,15 @@ impl OpenAiCompatClient {
|
||||
self
|
||||
}
|
||||
|
||||
/// Install a provider that may add outbound headers to each model request.
|
||||
///
|
||||
/// The provider sees the final JSON body and can only add headers.
|
||||
#[must_use]
|
||||
pub fn with_extra_headers_provider(mut self, provider: ExtraHeadersHook) -> Self {
|
||||
self.extra_headers = Some(provider);
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn send_message(
|
||||
&self,
|
||||
request: &MessageRequest,
|
||||
@@ -353,18 +366,25 @@ impl OpenAiCompatClient {
|
||||
check_request_body_size_for_base_url(request, self.config(), &self.base_url)?;
|
||||
|
||||
let request_url = chat_completions_endpoint(&self.base_url);
|
||||
self.http
|
||||
let request_body =
|
||||
build_chat_completion_request_for_base_url(request, self.config(), &self.base_url);
|
||||
let mut request_builder = self
|
||||
.http
|
||||
.post(&request_url)
|
||||
.header("content-type", "application/json")
|
||||
.bearer_auth(&self.api_key)
|
||||
.json(&build_chat_completion_request_for_base_url(
|
||||
request,
|
||||
self.config(),
|
||||
&self.base_url,
|
||||
))
|
||||
.send()
|
||||
.await
|
||||
.map_err(ApiError::from)
|
||||
.json(&request_body);
|
||||
if let Some(extra_headers) = &self.extra_headers {
|
||||
request_builder = extra_headers.apply(
|
||||
request_builder,
|
||||
&ExtraHeadersContext {
|
||||
provider: self.config.provider_name,
|
||||
model: &request.model,
|
||||
body: &request_body,
|
||||
},
|
||||
);
|
||||
}
|
||||
request_builder.send().await.map_err(ApiError::from)
|
||||
}
|
||||
|
||||
fn backoff_for_attempt(&self, attempt: u32) -> Result<Duration, ApiError> {
|
||||
@@ -1763,7 +1783,7 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
|
||||
let request_id = request_id_from_headers(&headers).map(String::into_boxed_str);
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
let parsed_error = serde_json::from_str::<ErrorEnvelope>(&body).ok();
|
||||
let retryable = is_retryable_status(status);
|
||||
let retryable = is_retryable_status(status) || is_retryable_400(status, &body);
|
||||
let retry_after = parse_retry_after(&headers, status).map(Box::new);
|
||||
|
||||
let suggested_action = suggested_action_for_status(status);
|
||||
@@ -1799,7 +1819,10 @@ fn parse_retry_after(
|
||||
}
|
||||
|
||||
const fn is_retryable_status(status: reqwest::StatusCode) -> bool {
|
||||
matches!(status.as_u16(), 408 | 409 | 429 | 500 | 502 | 503 | 504)
|
||||
matches!(
|
||||
status.as_u16(),
|
||||
408 | 409 | 429 | 500 | 502 | 503 | 504 | 529
|
||||
)
|
||||
}
|
||||
|
||||
/// Some providers return HTTP 400 with an unparseable body when a gateway
|
||||
@@ -1858,11 +1881,12 @@ impl StringExt for String {
|
||||
mod tests {
|
||||
use super::{
|
||||
build_chat_completion_request, chat_completions_endpoint, is_reasoning_model,
|
||||
model_requires_reasoning_content_in_history, normalize_finish_reason, normalize_response,
|
||||
openai_tool_choice, parse_tool_arguments, OpenAiCompatClient, OpenAiCompatConfig,
|
||||
StreamState,
|
||||
is_retryable_400, is_retryable_status, model_requires_reasoning_content_in_history,
|
||||
normalize_finish_reason, normalize_response, openai_tool_choice, parse_tool_arguments,
|
||||
OpenAiCompatClient, OpenAiCompatConfig, StreamState,
|
||||
};
|
||||
use crate::error::ApiError;
|
||||
use crate::extra_headers::ExtraHeadersHook;
|
||||
use crate::test_env_lock as env_lock;
|
||||
use crate::types::{
|
||||
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||
@@ -1872,6 +1896,97 @@ mod tests {
|
||||
use serde_json::json;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
|
||||
fn spawn_status_server(status: u16, body: &'static str) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
|
||||
let address = listener.local_addr().expect("local addr");
|
||||
thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().expect("accept connection");
|
||||
let mut buffer = [0_u8; 4096];
|
||||
let _ = stream.read(&mut buffer).expect("read request");
|
||||
let response = format!(
|
||||
"HTTP/1.1 {status} STATUS\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.expect("write response");
|
||||
});
|
||||
format!("http://{address}/v1/messages")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expect_success_marks_529_overloaded_retryable() {
|
||||
let url = spawn_status_server(
|
||||
529,
|
||||
r#"{"error":{"type":"overloaded_error","message":"Overloaded"}}"#,
|
||||
);
|
||||
let response = reqwest::get(&url).await.expect("response");
|
||||
let error = super::expect_success(response)
|
||||
.await
|
||||
.expect_err("529 should error");
|
||||
assert!(error.is_retryable(), "529 overloaded must be retryable");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expect_success_marks_gateway_flake_400_retryable() {
|
||||
let url = spawn_status_server(400, "HTTP 400 from backend (no parseable body)");
|
||||
let response = reqwest::get(&url).await.expect("response");
|
||||
let error = super::expect_success(response)
|
||||
.await
|
||||
.expect_err("400 should error");
|
||||
assert!(
|
||||
error.is_retryable(),
|
||||
"gateway-flake 400 body must be retryable"
|
||||
);
|
||||
let url = spawn_status_server(400, "invalid request: max_tokens must be positive");
|
||||
let response = reqwest::get(&url).await.expect("response");
|
||||
let error = super::expect_success(response)
|
||||
.await
|
||||
.expect_err("400 should error");
|
||||
assert!(!error.is_retryable(), "a real 400 must not be retried");
|
||||
}
|
||||
#[test]
|
||||
fn retryable_statuses_are_detected() {
|
||||
assert!(is_retryable_status(reqwest::StatusCode::TOO_MANY_REQUESTS));
|
||||
assert!(is_retryable_status(
|
||||
reqwest::StatusCode::INTERNAL_SERVER_ERROR
|
||||
));
|
||||
assert!(!is_retryable_status(reqwest::StatusCode::UNAUTHORIZED));
|
||||
// Several OpenAI-compatible gateways (and Anthropic) signal overload
|
||||
// with the non-standard 529; it is transient and must be retried.
|
||||
assert!(is_retryable_status(
|
||||
reqwest::StatusCode::from_u16(529).expect("529 is a valid status")
|
||||
));
|
||||
assert!(!is_retryable_status(reqwest::StatusCode::BAD_REQUEST));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_flake_400_bodies_are_retryable() {
|
||||
for body in [
|
||||
"HTTP 400 from backend (no parseable body)",
|
||||
"upstream connection reset by peer",
|
||||
"Broken pipe while reading response",
|
||||
"Empty reply from server",
|
||||
] {
|
||||
assert!(
|
||||
is_retryable_400(reqwest::StatusCode::BAD_REQUEST, body),
|
||||
"body should be retryable: {body}"
|
||||
);
|
||||
}
|
||||
assert!(!is_retryable_400(
|
||||
reqwest::StatusCode::BAD_REQUEST,
|
||||
"invalid request: max_tokens must be positive"
|
||||
));
|
||||
assert!(!is_retryable_400(
|
||||
reqwest::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"connection reset"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_translation_uses_openai_compatible_shape() {
|
||||
@@ -3048,4 +3163,58 @@ mod tests {
|
||||
assert_eq!(super::strip_routing_prefix("kimi-k2.5"), "kimi-k2.5"); // no prefix, unchanged
|
||||
assert_eq!(super::strip_routing_prefix("kimi/kimi-k1.5"), "kimi-k1.5");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extra_headers_provider_annotates_the_wire_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
|
||||
let address = listener.local_addr().expect("local addr");
|
||||
let (request_tx, request_rx) = std::sync::mpsc::channel();
|
||||
thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().expect("accept connection");
|
||||
let mut buffer = [0_u8; 8192];
|
||||
let read = stream.read(&mut buffer).expect("read request");
|
||||
request_tx
|
||||
.send(String::from_utf8_lossy(&buffer[..read]).into_owned())
|
||||
.expect("send request");
|
||||
let body = r#"{"id":"chatcmpl-test","object":"chat.completion","created":0,"model":"gpt-4o-mini","choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}"#;
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.expect("write response");
|
||||
});
|
||||
|
||||
let client = OpenAiCompatClient::new("test-key", OpenAiCompatConfig::openai())
|
||||
.with_base_url(format!("http://{address}"))
|
||||
.with_extra_headers_provider(ExtraHeadersHook::new(
|
||||
|ctx: &crate::extra_headers::ExtraHeadersContext<'_>| {
|
||||
vec![(
|
||||
"x-route".to_string(),
|
||||
format!("{}/{}", ctx.provider, ctx.model),
|
||||
)]
|
||||
},
|
||||
));
|
||||
let request = MessageRequest {
|
||||
model: "gpt-4o-mini".to_string(),
|
||||
max_tokens: 16,
|
||||
messages: vec![InputMessage::user_text("hello")],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let response = client.send_raw_request(&request).await.expect("response");
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
|
||||
let captured = request_rx
|
||||
.recv_timeout(std::time::Duration::from_secs(5))
|
||||
.expect("captured request");
|
||||
assert!(
|
||||
captured
|
||||
.to_lowercase()
|
||||
.contains("x-route: openai/gpt-4o-mini"),
|
||||
"wire request must carry the provider header: {captured}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use runtime::{pricing_for_model, TokenUsage, UsageCostEstimate};
|
||||
use runtime::{pricing_for_request, TokenUsage, UsageCostEstimate};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -213,7 +213,9 @@ impl Usage {
|
||||
#[must_use]
|
||||
pub fn estimated_cost_usd(&self, model: &str) -> UsageCostEstimate {
|
||||
let usage = self.token_usage();
|
||||
pricing_for_model(model).map_or_else(
|
||||
let prompt_tokens =
|
||||
self.input_tokens + self.cache_creation_input_tokens + self.cache_read_input_tokens;
|
||||
pricing_for_request(model, prompt_tokens).map_or_else(
|
||||
|| usage.estimate_cost_usd(),
|
||||
|pricing| usage.estimate_cost_usd_with_pricing(pricing),
|
||||
)
|
||||
|
||||
@@ -82,7 +82,7 @@ async fn send_message_posts_json_and_parses_response() {
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get("user-agent").map(String::as_str),
|
||||
Some("claude-code/0.1.12")
|
||||
Some("claude-code/0.1.15")
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get("anthropic-beta").map(String::as_str),
|
||||
|
||||
@@ -400,7 +400,7 @@ mod tests {
|
||||
fn executes_simple_command() {
|
||||
let output = execute_bash(BashCommandInput {
|
||||
command: String::from("printf 'hello'"),
|
||||
timeout: Some(1_000),
|
||||
timeout: Some(30_000),
|
||||
description: None,
|
||||
run_in_background: Some(false),
|
||||
dangerously_disable_sandbox: Some(false),
|
||||
@@ -411,8 +411,12 @@ mod tests {
|
||||
})
|
||||
.expect("bash command should execute");
|
||||
|
||||
assert!(
|
||||
!output.interrupted,
|
||||
"command was interrupted (timeout?); stderr: {}",
|
||||
output.stderr
|
||||
);
|
||||
assert_eq!(output.stdout, "hello");
|
||||
assert!(!output.interrupted);
|
||||
assert!(output.sandbox_status.is_some());
|
||||
}
|
||||
|
||||
@@ -420,7 +424,7 @@ mod tests {
|
||||
fn disables_sandbox_when_requested() {
|
||||
let output = execute_bash(BashCommandInput {
|
||||
command: String::from("printf 'hello'"),
|
||||
timeout: Some(1_000),
|
||||
timeout: Some(30_000),
|
||||
description: None,
|
||||
run_in_background: Some(false),
|
||||
dangerously_disable_sandbox: Some(true),
|
||||
@@ -463,7 +467,7 @@ mod tests {
|
||||
fn prevents_stdin_hangs_by_redirecting_to_null() {
|
||||
let output = execute_bash(BashCommandInput {
|
||||
command: String::from("cat"),
|
||||
timeout: Some(2_000),
|
||||
timeout: Some(30_000),
|
||||
description: None,
|
||||
run_in_background: Some(false),
|
||||
dangerously_disable_sandbox: Some(true),
|
||||
|
||||
@@ -666,13 +666,21 @@ pub fn edit_file(
|
||||
) -> io::Result<EditFileOutput> {
|
||||
let absolute_path = normalize_path(path)?;
|
||||
let original_file = fs::read_to_string(&absolute_path)?;
|
||||
if old_string == new_string {
|
||||
// read_file and grep_search return lines joined with `\n`, so text quoted
|
||||
// from a CRLF file arrives without its `\r`. Match the file's line endings
|
||||
// so multi-line edits apply and inserted lines stay CRLF.
|
||||
let (target, replacement) = if uses_crlf_line_endings(&original_file) {
|
||||
(to_crlf(old_string), to_crlf(new_string))
|
||||
} else {
|
||||
(old_string.to_owned(), new_string.to_owned())
|
||||
};
|
||||
if target == replacement {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"old_string and new_string must differ",
|
||||
));
|
||||
}
|
||||
if !original_file.contains(old_string) {
|
||||
if !original_file.contains(&target) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"old_string not found in file",
|
||||
@@ -680,9 +688,9 @@ pub fn edit_file(
|
||||
}
|
||||
|
||||
let updated = if replace_all {
|
||||
original_file.replace(old_string, new_string)
|
||||
original_file.replace(&target, &replacement)
|
||||
} else {
|
||||
original_file.replacen(old_string, new_string, 1)
|
||||
original_file.replacen(&target, &replacement, 1)
|
||||
};
|
||||
fs::write(&absolute_path, &updated)?;
|
||||
|
||||
@@ -698,6 +706,16 @@ pub fn edit_file(
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the text has line breaks and every one of them is `\r\n`.
|
||||
fn uses_crlf_line_endings(text: &str) -> bool {
|
||||
let line_feeds = text.matches('\n').count();
|
||||
line_feeds > 0 && text.matches("\r\n").count() == line_feeds
|
||||
}
|
||||
|
||||
fn to_crlf(text: &str) -> String {
|
||||
text.replace("\r\n", "\n").replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
/// Expands a glob pattern and returns matching filenames.
|
||||
pub fn glob_search(pattern: &str, path: Option<&str>) -> io::Result<GlobSearchOutput> {
|
||||
glob_search_impl(pattern, path, None)
|
||||
@@ -950,8 +968,13 @@ fn normalize_for_comparison(path: &Path) -> PathBuf {
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
/// Whether a directory below the search root is one of the heavy
|
||||
/// directories (VCS data, dependencies, build output) that glob and grep
|
||||
/// searches skip. The root itself is always searched, so a search the caller
|
||||
/// points into one of these directories still works.
|
||||
fn should_skip_glob_dir(entry: &DirEntry) -> bool {
|
||||
entry.file_type().is_dir()
|
||||
entry.depth() > 0
|
||||
&& entry.file_type().is_dir()
|
||||
&& entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
@@ -989,7 +1012,10 @@ fn collect_search_files(base_path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
for entry in WalkDir::new(base_path) {
|
||||
for entry in WalkDir::new(base_path)
|
||||
.into_iter()
|
||||
.filter_entry(|entry| !should_skip_glob_dir(entry))
|
||||
{
|
||||
let entry = entry.map_err(|error| io::Error::other(error.to_string()))?;
|
||||
if entry.file_type().is_file() {
|
||||
files.push(entry.path().to_path_buf());
|
||||
@@ -1243,6 +1269,57 @@ mod tests {
|
||||
assert!(output.replace_all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_crlf_file_with_lines_copied_from_read_file() {
|
||||
let path = temp_path("edit-crlf.rs");
|
||||
std::fs::write(&path, "fn main() {\r\n println!(\"hi\");\r\n}\r\n")
|
||||
.expect("initial write should succeed");
|
||||
let path_str = path.to_string_lossy();
|
||||
|
||||
// read_file returns the lines joined with `\n`, so a block quoted from
|
||||
// its output does not contain the file's `\r\n` line endings.
|
||||
let read = read_file(path_str.as_ref(), None, None).expect("read should succeed");
|
||||
let old_string = read
|
||||
.file
|
||||
.content
|
||||
.lines()
|
||||
.take(2)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert_eq!(old_string, "fn main() {\n println!(\"hi\");");
|
||||
|
||||
edit_file(
|
||||
path_str.as_ref(),
|
||||
&old_string,
|
||||
"fn main() {\n println!(\"hello\");\n println!(\"world\");",
|
||||
false,
|
||||
)
|
||||
.expect("edit should match the CRLF lines");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).expect("read back should succeed"),
|
||||
"fn main() {\r\n println!(\"hello\");\r\n println!(\"world\");\r\n}\r\n"
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_keeps_line_endings_of_lf_and_mixed_files() {
|
||||
let path = temp_path("edit-lf.txt");
|
||||
std::fs::write(&path, "one\ntwo\r\nthree\n").expect("initial write should succeed");
|
||||
edit_file(
|
||||
path.to_string_lossy().as_ref(),
|
||||
"one\n",
|
||||
"uno\nwon\n",
|
||||
false,
|
||||
)
|
||||
.expect("edit should succeed");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).expect("read back should succeed"),
|
||||
"uno\nwon\ntwo\r\nthree\n"
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_binary_files() {
|
||||
let path = temp_path("binary-test.bin");
|
||||
@@ -1565,6 +1642,50 @@ mod tests {
|
||||
assert!(grep_output.content.unwrap_or_default().contains("hello"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grep_search_skips_common_heavy_directories() {
|
||||
let dir = temp_path("grep-ignored-dirs");
|
||||
for sub in ["src", ".git/refs", "node_modules/pkg", "target/debug/build"] {
|
||||
std::fs::create_dir_all(dir.join(sub)).unwrap();
|
||||
std::fs::write(dir.join(sub).join("notes.txt"), "needle").unwrap();
|
||||
}
|
||||
let grep = |path: PathBuf| {
|
||||
grep_search(&GrepSearchInput {
|
||||
pattern: String::from("needle"),
|
||||
path: Some(path.to_string_lossy().into_owned()),
|
||||
glob: None,
|
||||
output_mode: Some(String::from("files_with_matches")),
|
||||
before: None,
|
||||
after: None,
|
||||
context_short: None,
|
||||
context: None,
|
||||
line_numbers: None,
|
||||
case_insensitive: None,
|
||||
file_type: None,
|
||||
head_limit: None,
|
||||
offset: None,
|
||||
multiline: None,
|
||||
})
|
||||
.expect("grep should succeed")
|
||||
.filenames
|
||||
};
|
||||
|
||||
let filenames = grep(dir.clone());
|
||||
assert_eq!(
|
||||
filenames.len(),
|
||||
1,
|
||||
"ignored dirs should be pruned: {filenames:?}"
|
||||
);
|
||||
assert!(Path::new(&filenames[0]).ends_with("src/notes.txt"));
|
||||
|
||||
// A search rooted inside an ignored directory still searches it.
|
||||
let filenames = grep(dir.join("node_modules"));
|
||||
assert_eq!(filenames.len(), 1, "{filenames:?}");
|
||||
assert!(Path::new(&filenames[0]).ends_with("node_modules/pkg/notes.txt"));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_braces_no_braces() {
|
||||
assert_eq!(expand_braces("*.rs"), vec!["*.rs"]);
|
||||
@@ -1646,6 +1767,12 @@ mod tests {
|
||||
|| path.contains(".build")
|
||||
|| path.contains("/target/")));
|
||||
|
||||
// A glob rooted inside an ignored directory still searches it.
|
||||
let inside = dir.join("node_modules");
|
||||
let result = glob_search("**/AGENTS.md", Some(inside.to_str().unwrap()))
|
||||
.expect("glob should succeed");
|
||||
assert_eq!(result.num_files, 1, "{:?}", result.filenames);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -200,7 +200,8 @@ pub use task_registry::{LaneBoard, LaneBoardEntry, LaneFreshness, LaneHeartbeat}
|
||||
#[cfg(test)]
|
||||
pub use trust_resolver::{TrustConfig, TrustDecision, TrustEvent, TrustPolicy, TrustResolver};
|
||||
pub use usage::{
|
||||
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
||||
format_usd, pricing_for_model, pricing_for_request, ModelPricing, TokenUsage,
|
||||
UsageCostEstimate, UsageTracker,
|
||||
};
|
||||
pub use worker_boot::{
|
||||
Worker, WorkerEvent, WorkerEventKind, WorkerEventPayload, WorkerFailure, WorkerFailureKind,
|
||||
|
||||
@@ -25,6 +25,10 @@ impl ModelPricing {
|
||||
)
|
||||
}
|
||||
|
||||
const fn from_rates([input, output, cache_creation, cache_read]: [f64; 4]) -> Self {
|
||||
Self::per_million(input, output, cache_creation, cache_read)
|
||||
}
|
||||
|
||||
const fn per_million(input: f64, output: f64, cache_creation: f64, cache_read: f64) -> Self {
|
||||
Self {
|
||||
input_cost_per_million: input,
|
||||
@@ -83,8 +87,8 @@ pub fn pricing_for_model(model: &str) -> Option<ModelPricing> {
|
||||
return Some(ModelPricing::per_million(0.8, 4.0, 1.0, 0.08));
|
||||
}
|
||||
return Some(match family_version(&normalized, "haiku") {
|
||||
// Haiku 5.5 bills prompts over 100K tokens at 5x; usage totals are not
|
||||
// tracked per request, so estimates use the base tier.
|
||||
// Haiku 5.5 bills prompts over 100K tokens at 5x; aggregated usage uses the
|
||||
// base tier, and `pricing_for_request` applies the higher one per request.
|
||||
Some((5, 5)) => ModelPricing::per_million(0.1, 0.5, 0.125, 0.01),
|
||||
_ => ModelPricing::per_million(1.0, 5.0, 1.25, 0.1),
|
||||
});
|
||||
@@ -134,9 +138,9 @@ const GROK_BUILD: [f64; 4] = [1.0, 2.0, 1.0, 0.2];
|
||||
/// OpenAI-compatible providers, keyed by model id.
|
||||
///
|
||||
/// An id also matches its dated snapshots and `-latest` alias (e.g. `gpt-4.1-2025-04-14`),
|
||||
/// so a specific snapshot must precede its base id. Long-context and higher input tiers
|
||||
/// are not modeled because usage is aggregated across requests. Cache writes without a
|
||||
/// separate charge, and models without a cached-input discount, use the input rate.
|
||||
/// so a specific snapshot must precede its base id. Long-context tiers live in
|
||||
/// [`LONG_CONTEXT_PRICING`]. Cache writes without a separate charge, and models without a
|
||||
/// cached-input discount, use the input rate.
|
||||
const OPENAI_COMPATIBLE_PRICING: &[(&str, [f64; 4])] = &[
|
||||
// OpenAI standard tier (<https://developers.openai.com/api/docs/pricing>).
|
||||
("gpt-6-astra", [10.0, 50.0, 12.5, 1.0]),
|
||||
@@ -147,14 +151,19 @@ const OPENAI_COMPATIBLE_PRICING: &[(&str, [f64; 4])] = &[
|
||||
("gpt-5.6-terra", [2.0, 12.0, 2.5, 0.2]),
|
||||
("gpt-5.6-luna", [0.2, 1.2, 0.25, 0.02]),
|
||||
("gpt-5.5", [5.0, 30.0, 5.0, 0.5]),
|
||||
("gpt-5.5-pro", [30.0, 180.0, 30.0, 30.0]),
|
||||
("gpt-5.4", [2.5, 15.0, 2.5, 0.25]),
|
||||
("gpt-5.4-pro", [30.0, 180.0, 30.0, 30.0]),
|
||||
("gpt-5.4-mini", [0.75, 4.5, 0.75, 0.075]),
|
||||
("gpt-5.4-nano", [0.2, 1.25, 0.2, 0.02]),
|
||||
("gpt-5.3-codex", [1.75, 14.0, 1.75, 0.175]),
|
||||
("gpt-5.2", [1.75, 14.0, 1.75, 0.175]),
|
||||
("gpt-5.2-pro", [21.0, 168.0, 21.0, 21.0]),
|
||||
("gpt-5.1", [1.25, 10.0, 1.25, 0.125]),
|
||||
("gpt-5", [1.25, 10.0, 1.25, 0.125]),
|
||||
("gpt-5-mini", [0.25, 2.0, 0.25, 0.025]),
|
||||
("gpt-5-nano", [0.05, 0.4, 0.05, 0.005]),
|
||||
("gpt-5-pro", [15.0, 120.0, 15.0, 15.0]),
|
||||
("gpt-4.1", [2.0, 8.0, 2.0, 0.5]),
|
||||
("gpt-4.1-mini", [0.4, 1.6, 0.4, 0.1]),
|
||||
("gpt-4.1-nano", [0.1, 0.4, 0.1, 0.025]),
|
||||
@@ -162,9 +171,24 @@ const OPENAI_COMPATIBLE_PRICING: &[(&str, [f64; 4])] = &[
|
||||
("gpt-4o", [2.5, 10.0, 2.5, 1.25]),
|
||||
("gpt-4o-mini", [0.15, 0.6, 0.15, 0.075]),
|
||||
("o1", [15.0, 60.0, 15.0, 7.5]),
|
||||
("o1-pro", [150.0, 600.0, 150.0, 150.0]),
|
||||
("o3", [2.0, 8.0, 2.0, 0.5]),
|
||||
("o3-pro", [20.0, 80.0, 20.0, 20.0]),
|
||||
("o3-mini", [1.1, 4.4, 1.1, 0.55]),
|
||||
("o4-mini", [1.1, 4.4, 1.1, 0.275]),
|
||||
// Google Gemini API paid tier (<https://ai.google.dev/gemini-api/docs/pricing>),
|
||||
// reachable through its OpenAI-compatible endpoint and gateways. Context caching
|
||||
// bills storage per hour rather than a write premium, so writes use the input rate.
|
||||
("gemini-4-argon", [2.0, 10.0, 2.0, 0.1]),
|
||||
("gemini-3.8-flash", [0.75, 3.75, 0.75, 0.075]),
|
||||
("gemini-3.6-flash", [0.75, 3.75, 0.75, 0.075]),
|
||||
("gemini-3.5-flash-lite", [0.3, 2.5, 0.3, 0.03]),
|
||||
("gemini-3.1-flash-lite", [0.25, 1.5, 0.25, 0.025]),
|
||||
("gemini-3.1-pro-preview", [2.0, 12.0, 2.0, 0.2]),
|
||||
("gemini-3-flash-preview", [0.5, 3.0, 0.5, 0.05]),
|
||||
("gemini-2.5-pro", [1.25, 10.0, 1.25, 0.125]),
|
||||
("gemini-2.5-flash", [0.3, 2.5, 0.3, 0.03]),
|
||||
("gemini-2.5-flash-lite", [0.1, 0.4, 0.1, 0.01]),
|
||||
// xAI (<https://docs.x.ai/docs/models>).
|
||||
("grok-4.7", [2.0, 6.0, 2.0, 0.5]),
|
||||
("grok-4.6", [2.0, 6.0, 2.0, 0.5]),
|
||||
@@ -189,9 +213,52 @@ const OPENAI_COMPATIBLE_PRICING: &[(&str, [f64; 4])] = &[
|
||||
("kimi-k2.5", [0.574, 3.011, 0.574, 0.1148]),
|
||||
];
|
||||
|
||||
/// Rates that replace the base tier once a single request's prompt (input plus cache
|
||||
/// reads and writes) exceeds the threshold, keyed like [`OPENAI_COMPATIBLE_PRICING`].
|
||||
const LONG_CONTEXT_PRICING: &[(&str, (u32, [f64; 4]))] = &[
|
||||
("gpt-6-astra", (272_000, [20.0, 75.0, 25.0, 2.0])),
|
||||
("gpt-6.1-sol", (272_000, [4.0, 15.0, 5.0, 0.2])),
|
||||
("gpt-6-sol", (272_000, [4.0, 15.0, 5.0, 0.4])),
|
||||
("gpt-6-luna", (272_000, [0.2, 0.75, 0.25, 0.02])),
|
||||
("gpt-5.6-sol", (272_000, [8.0, 30.0, 10.0, 0.8])),
|
||||
("gpt-5.6-terra", (272_000, [4.0, 18.0, 5.0, 0.4])),
|
||||
("gpt-5.6-luna", (272_000, [0.4, 1.8, 0.5, 0.04])),
|
||||
("gpt-5.5", (272_000, [10.0, 45.0, 10.0, 1.0])),
|
||||
("gpt-5.5-pro", (272_000, [60.0, 270.0, 60.0, 60.0])),
|
||||
("gpt-5.4", (272_000, [5.0, 22.5, 5.0, 0.5])),
|
||||
("gpt-5.4-pro", (272_000, [60.0, 270.0, 60.0, 60.0])),
|
||||
("gemini-3.1-pro-preview", (200_000, [4.0, 18.0, 4.0, 0.4])),
|
||||
("gemini-2.5-pro", (200_000, [2.5, 15.0, 2.5, 0.25])),
|
||||
];
|
||||
|
||||
const HAIKU_5_5_LONG_CONTEXT: (u32, [f64; 4]) = (100_000, [0.5, 2.5, 0.625, 0.05]);
|
||||
|
||||
/// Returns pricing for a single request whose prompt (input plus cache reads and writes)
|
||||
/// is `prompt_tokens` long, applying the long-context tiers that [`pricing_for_model`]
|
||||
/// leaves out because it also prices usage aggregated across requests.
|
||||
#[must_use]
|
||||
pub fn pricing_for_request(model: &str, prompt_tokens: u32) -> Option<ModelPricing> {
|
||||
let normalized = model.to_ascii_lowercase();
|
||||
let long_context = if family_version(&normalized, "haiku") == Some((5, 5)) {
|
||||
Some(HAIKU_5_5_LONG_CONTEXT)
|
||||
} else {
|
||||
find_model(LONG_CONTEXT_PRICING, &normalized)
|
||||
};
|
||||
match long_context {
|
||||
Some((threshold, rates)) if prompt_tokens > threshold => {
|
||||
Some(ModelPricing::from_rates(rates))
|
||||
}
|
||||
_ => pricing_for_model(model),
|
||||
}
|
||||
}
|
||||
|
||||
fn openai_compatible_pricing(normalized: &str) -> Option<ModelPricing> {
|
||||
find_model(OPENAI_COMPATIBLE_PRICING, normalized).map(ModelPricing::from_rates)
|
||||
}
|
||||
|
||||
fn find_model<T: Copy>(table: &[(&str, T)], normalized: &str) -> Option<T> {
|
||||
let id = normalized.rsplit_once('/').map_or(normalized, |(_, id)| id);
|
||||
OPENAI_COMPATIBLE_PRICING
|
||||
table
|
||||
.iter()
|
||||
.find(|(model, _)| {
|
||||
id.strip_prefix(model).is_some_and(|rest| {
|
||||
@@ -201,9 +268,7 @@ fn openai_compatible_pricing(normalized: &str) -> Option<ModelPricing> {
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(|&(_, [input, output, cache_write, cache_read])| {
|
||||
ModelPricing::per_million(input, output, cache_write, cache_read)
|
||||
})
|
||||
.map(|&(_, value)| value)
|
||||
}
|
||||
|
||||
/// Parses the `(major, minor)` version after `family` in ids such as
|
||||
@@ -354,7 +419,7 @@ impl UsageTracker {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{format_usd, pricing_for_model, TokenUsage, UsageTracker};
|
||||
use super::{format_usd, pricing_for_model, pricing_for_request, TokenUsage, UsageTracker};
|
||||
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
||||
|
||||
#[test]
|
||||
@@ -507,6 +572,13 @@ mod tests {
|
||||
assert_eq!(total_for("qwen/qwen-max"), "$1.1025");
|
||||
assert_eq!(total_for("qwen-plus-latest"), "$0.2815");
|
||||
assert_eq!(total_for("kimi-k2.5"), "$2.1943");
|
||||
assert_eq!(total_for("gpt-5.5-pro"), "$150.0000");
|
||||
assert_eq!(total_for("gpt-5.3-codex"), "$8.9250");
|
||||
assert_eq!(total_for("o3-pro-2025-06-10"), "$80.0000");
|
||||
assert_eq!(total_for("o3"), "$6.5000");
|
||||
assert_eq!(total_for("google/gemini-2.5-pro"), "$6.3750");
|
||||
assert_eq!(total_for("gemini-2.5-flash-lite"), "$0.3100");
|
||||
assert_eq!(total_for("gemini-3.1-pro-preview"), "$8.2000");
|
||||
for unpriced in [
|
||||
"o1-mini",
|
||||
"grok-3-mini",
|
||||
@@ -517,6 +589,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_long_context_tiers_per_request() {
|
||||
let rates = |model: &str, prompt_tokens: u32| {
|
||||
let pricing = pricing_for_request(model, prompt_tokens).expect("known model pricing");
|
||||
(
|
||||
pricing.input_cost_per_million,
|
||||
pricing.output_cost_per_million,
|
||||
)
|
||||
};
|
||||
|
||||
assert_eq!(rates("claude-haiku-5-5", 100_000), (0.1, 0.5));
|
||||
assert_eq!(rates("claude-haiku-5-5-20260301", 100_001), (0.5, 2.5));
|
||||
assert_eq!(rates("claude-haiku-4-5", 500_000), (1.0, 5.0));
|
||||
assert_eq!(rates("gpt-5.4", 272_000), (2.5, 15.0));
|
||||
assert_eq!(rates("openai/gpt-5.4", 272_001), (5.0, 22.5));
|
||||
assert_eq!(rates("gpt-5.4-mini", 900_000), (0.75, 4.5));
|
||||
assert_eq!(rates("gemini-2.5-pro", 200_001), (2.5, 15.0));
|
||||
assert_eq!(rates("claude-sonnet-4-6", 900_000), (3.0, 15.0));
|
||||
assert_eq!(
|
||||
pricing_for_request("gpt-5.5", 1_000),
|
||||
pricing_for_model("gpt-5.5")
|
||||
);
|
||||
assert_eq!(pricing_for_request("custom-model", 1_000_000), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_unknown_model_pricing_as_fallback() {
|
||||
let usage = TokenUsage {
|
||||
|
||||
@@ -7391,6 +7391,7 @@ struct PromptHistoryEntry {
|
||||
|
||||
struct RuntimePluginState {
|
||||
feature_config: runtime::RuntimeFeatureConfig,
|
||||
max_output_tokens: Option<u32>,
|
||||
tool_registry: GlobalToolRegistry,
|
||||
plugin_registry: PluginRegistry,
|
||||
mcp_state: Option<Arc<Mutex<RuntimeMcpState>>>,
|
||||
@@ -12467,6 +12468,7 @@ fn build_runtime_plugin_state_with_loader(
|
||||
.with_runtime_tools(runtime_tools)?;
|
||||
Ok(RuntimePluginState {
|
||||
feature_config,
|
||||
max_output_tokens: runtime_config.plugins().max_output_tokens(),
|
||||
tool_registry,
|
||||
plugin_registry,
|
||||
mcp_state,
|
||||
@@ -12896,6 +12898,7 @@ fn build_runtime_with_plugin_state(
|
||||
}
|
||||
let RuntimePluginState {
|
||||
feature_config,
|
||||
max_output_tokens,
|
||||
tool_registry,
|
||||
plugin_registry,
|
||||
mcp_state,
|
||||
@@ -12916,6 +12919,7 @@ fn build_runtime_with_plugin_state(
|
||||
tool_registry.clone(),
|
||||
progress_reporter,
|
||||
provider_config,
|
||||
max_output_tokens,
|
||||
)?,
|
||||
CliToolExecutor::new(
|
||||
allowed_tools.clone(),
|
||||
@@ -13189,6 +13193,7 @@ struct AnthropicRuntimeClient {
|
||||
client: ApiProviderClient,
|
||||
session_id: String,
|
||||
model: String,
|
||||
max_output_tokens: Option<u32>,
|
||||
enable_tools: bool,
|
||||
emit_output: bool,
|
||||
terminal_tail: TerminalTail,
|
||||
@@ -13212,6 +13217,7 @@ impl AnthropicRuntimeClient {
|
||||
tool_registry: GlobalToolRegistry,
|
||||
progress_reporter: Option<InternalPromptProgressReporter>,
|
||||
provider_config: Option<api::ProviderConfig>,
|
||||
max_output_tokens: Option<u32>,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
// Explicit persisted provider configuration takes precedence.
|
||||
// When absent, preserve the existing model-based provider detection.
|
||||
@@ -13277,6 +13283,7 @@ impl AnthropicRuntimeClient {
|
||||
client,
|
||||
session_id: session_id.to_string(),
|
||||
model,
|
||||
max_output_tokens,
|
||||
enable_tools,
|
||||
emit_output,
|
||||
terminal_tail,
|
||||
@@ -13326,7 +13333,10 @@ impl ApiClient for AnthropicRuntimeClient {
|
||||
let enable_local_tools = self.enable_tools && model_supports_local_tools(&self.model);
|
||||
let message_request = MessageRequest {
|
||||
model: self.model.clone(),
|
||||
max_tokens: max_tokens_for_model(&self.model),
|
||||
max_tokens: api::max_tokens_for_model_with_override(
|
||||
&self.model,
|
||||
self.max_output_tokens,
|
||||
),
|
||||
messages: convert_messages(&request.messages),
|
||||
system: (!request.system_prompt.is_empty()).then(|| request.system_prompt.join("\n\n")),
|
||||
tools: enable_local_tools
|
||||
@@ -18289,6 +18299,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn session_exists_resume_command_reports_json_contract() {
|
||||
let _cwd_guard = cwd_guard();
|
||||
let session = Session::new();
|
||||
let path = PathBuf::from("missing-session.jsonl");
|
||||
let outcome = run_resume_command(
|
||||
@@ -18811,6 +18822,8 @@ mod tests {
|
||||
#[test]
|
||||
fn boot_preflight_snapshot_reports_machine_readable_contract_fields() {
|
||||
let _guard = env_lock();
|
||||
// Binary availability probes inherit cwd even though Git probes use workspace.
|
||||
let _cwd_guard = cwd_guard();
|
||||
let workspace = temp_workspace("boot-preflight-json");
|
||||
fs::create_dir_all(&workspace).expect("workspace should create");
|
||||
git(&["init", "--quiet"], &workspace);
|
||||
@@ -19084,6 +19097,8 @@ UU conflicted.rs",
|
||||
|
||||
#[test]
|
||||
fn status_context_reads_real_workspace_metadata() {
|
||||
// Reading cwd and launching helpers must serialize with cwd-changing tests.
|
||||
let _cwd_guard = cwd_guard();
|
||||
let context = status_context(None).expect("status context should load");
|
||||
assert!(context.cwd.is_absolute());
|
||||
assert!(context.discovered_config_files >= context.loaded_config_files);
|
||||
@@ -20231,6 +20246,7 @@ UU conflicted.rs",
|
||||
GlobalToolRegistry::builtin(),
|
||||
None,
|
||||
Some(config),
|
||||
None,
|
||||
)
|
||||
.expect("runtime client should construct from explicit model provider hint");
|
||||
|
||||
@@ -20329,6 +20345,7 @@ UU conflicted.rs",
|
||||
GlobalToolRegistry::builtin(),
|
||||
None,
|
||||
Some(provider_config),
|
||||
state.max_output_tokens,
|
||||
)
|
||||
.expect("runtime client should construct from persisted provider configuration");
|
||||
|
||||
@@ -20346,6 +20363,9 @@ UU conflicted.rs",
|
||||
#[test]
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn build_runtime_plugin_state_discovers_mcp_tools_and_surfaces_pending_servers() {
|
||||
// MCP children inherit the process cwd. Keep it stable until shutdown so
|
||||
// they cannot hold another test's temporary directory open on Windows.
|
||||
let _cwd_guard = cwd_guard();
|
||||
let config_home = temp_dir();
|
||||
let workspace = temp_dir();
|
||||
fs::create_dir_all(&config_home).expect("config home");
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
mod support;
|
||||
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use mock_anthropic_service::{MockAnthropicService, SCENARIO_PREFIX};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(
|
||||
windows,
|
||||
ignore = "times out on Windows runners due to slow socket operations"
|
||||
)]
|
||||
fn max_output_tokens_reaches_openai_compatible_tool_roundtrip() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind local mock server");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("nonblocking listener");
|
||||
let base_url = format!(
|
||||
"http://{}/v1",
|
||||
listener.local_addr().expect("server address")
|
||||
);
|
||||
let server = thread::spawn(move || {
|
||||
let mut requests = Vec::new();
|
||||
for turn in 0..2 {
|
||||
let deadline_secs = 30;
|
||||
let deadline = Instant::now() + Duration::from_secs(deadline_secs);
|
||||
let mut stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => break stream,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
assert!(Instant::now() < deadline, "CLI did not send turn {turn}");
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(error) => panic!("mock server accept failed: {error}"),
|
||||
}
|
||||
};
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
stream
|
||||
.set_write_timeout(Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
requests.push(read_openai_request(&mut stream));
|
||||
eprintln!("OpenAI mock: received request {}/2", turn + 1);
|
||||
let (delta, finish_reason) = if turn == 0 {
|
||||
(
|
||||
json!({"role": "assistant", "tool_calls": [{
|
||||
"index": 0, "id": "call_read", "type": "function",
|
||||
"function": {"name": "read_file", "arguments": "{\"path\":\"fixture.txt\"}"}
|
||||
}]}),
|
||||
"tool_calls",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
json!({"role": "assistant", "content": "Local read complete."}),
|
||||
"stop",
|
||||
)
|
||||
};
|
||||
let chunk = json!({
|
||||
"id": "chatcmpl-local", "object": "chat.completion.chunk",
|
||||
"created": 0, "model": "local-test-model",
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}]
|
||||
});
|
||||
let body = format!("data: {chunk}\n\ndata: [DONE]\n\n");
|
||||
write!(stream,
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
).expect("write mock response");
|
||||
eprintln!("OpenAI mock: sent response {}/2", turn + 1);
|
||||
}
|
||||
requests
|
||||
});
|
||||
|
||||
let workspace = unique_temp_dir("openai workspace with spaces");
|
||||
let config_home = workspace.join("config-home");
|
||||
let home = workspace.join("home");
|
||||
fs::create_dir_all(&config_home).unwrap();
|
||||
fs::create_dir_all(&home).unwrap();
|
||||
fs::write(
|
||||
config_home.join("settings.json"),
|
||||
json!({"plugins": {"maxOutputTokens": 512}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
workspace.join("fixture.txt"),
|
||||
"verified local file contents",
|
||||
)
|
||||
.unwrap();
|
||||
let output = output_with_deadline(
|
||||
Command::new(env!("CARGO_BIN_EXE_claw"))
|
||||
.current_dir(&workspace)
|
||||
.env_clear()
|
||||
.envs(support::process_environment())
|
||||
.env("OPENAI_BASE_URL", base_url)
|
||||
.env("OPENAI_API_KEY", "local-test-key")
|
||||
.env("CLAW_CONFIG_HOME", &config_home)
|
||||
.env("HOME", &home)
|
||||
.env("NO_COLOR", "1")
|
||||
.args([
|
||||
"--model",
|
||||
"openai/local-test-model",
|
||||
"--permission-mode",
|
||||
"read-only",
|
||||
"--allowedTools",
|
||||
"read_file",
|
||||
"--compact",
|
||||
"Read fixture.txt once.",
|
||||
]),
|
||||
);
|
||||
let requests = server.join().expect("mock server should finish");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"stdout: {}; stderr: {}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("Local read complete."));
|
||||
for request in &requests {
|
||||
assert_eq!(request["max_tokens"], 512);
|
||||
assert_eq!(request["model"], "local-test-model");
|
||||
}
|
||||
assert!(requests[1]["messages"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|message| message["role"] == "tool"
|
||||
&& message["content"]
|
||||
.as_str()
|
||||
.is_some_and(|content| content.contains("verified local file contents"))));
|
||||
fs::remove_dir_all(workspace).unwrap();
|
||||
}
|
||||
|
||||
fn read_openai_request(stream: &mut TcpStream) -> Value {
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("request line");
|
||||
assert!(line.starts_with("POST /v1/chat/completions "), "{line}");
|
||||
let mut length = None;
|
||||
loop {
|
||||
line.clear();
|
||||
assert!(reader.read_line(&mut line).expect("header") > 0);
|
||||
if line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
if let Some((name, value)) = line.split_once(':') {
|
||||
if name.eq_ignore_ascii_case("content-length") {
|
||||
length = Some(value.trim().parse::<usize>().expect("content length"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let length = length.expect("request must have content length");
|
||||
assert!(length <= 1024 * 1024, "unexpectedly large mock request");
|
||||
let mut body = vec![0; length];
|
||||
reader.read_exact(&mut body).expect("request body");
|
||||
serde_json::from_slice(&body).expect("request JSON")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_output_tokens_config_reaches_every_tool_roundtrip_request() {
|
||||
assert_max_output_tokens_on_wire(Some(1024), None, 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_output_tokens_local_config_overrides_user_config() {
|
||||
assert_max_output_tokens_on_wire(Some(2048), Some(512), 512);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_output_tokens_default_is_preserved_without_config() {
|
||||
assert_max_output_tokens_on_wire(None, None, 64_000);
|
||||
}
|
||||
|
||||
fn assert_max_output_tokens_on_wire(user: Option<u32>, local: Option<u32>, expected: u32) {
|
||||
let runtime = tokio::runtime::Runtime::new().expect("tokio runtime should build");
|
||||
let server = runtime
|
||||
.block_on(MockAnthropicService::spawn())
|
||||
.expect("mock service should start");
|
||||
let workspace = unique_temp_dir("workspace with spaces");
|
||||
let config_home = workspace.join("config-home");
|
||||
let home = workspace.join("home");
|
||||
fs::create_dir_all(&config_home).expect("config home should exist");
|
||||
fs::create_dir_all(&home).expect("home should exist");
|
||||
fs::create_dir_all(workspace.join(".claw")).expect("project config should exist");
|
||||
fs::write(workspace.join("fixture.txt"), "alpha parity line\n").expect("fixture should write");
|
||||
for (path, limit) in [
|
||||
(config_home.join("settings.json"), user),
|
||||
(workspace.join(".claw/settings.local.json"), local),
|
||||
] {
|
||||
if let Some(limit) = limit {
|
||||
fs::write(
|
||||
path,
|
||||
serde_json::json!({"plugins": {"maxOutputTokens": limit}}).to_string(),
|
||||
)
|
||||
.expect("token limit config should write");
|
||||
}
|
||||
}
|
||||
|
||||
let prompt = format!("{SCENARIO_PREFIX}read_file_roundtrip");
|
||||
let output = run_claw(
|
||||
&workspace,
|
||||
&config_home,
|
||||
&home,
|
||||
&server.base_url(),
|
||||
&[
|
||||
"--model",
|
||||
"sonnet",
|
||||
"--permission-mode",
|
||||
"read-only",
|
||||
"--allowedTools",
|
||||
"read_file",
|
||||
"--compact",
|
||||
&prompt,
|
||||
],
|
||||
);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"claw should complete the tool roundtrip\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
let captured = runtime.block_on(server.captured_requests());
|
||||
let requests: Vec<_> = captured
|
||||
.iter()
|
||||
.filter(|request| request.path == "/v1/messages")
|
||||
.collect();
|
||||
assert_eq!(
|
||||
requests.len(),
|
||||
2,
|
||||
"both sides of the tool roundtrip must run"
|
||||
);
|
||||
for request in requests {
|
||||
let body: Value = serde_json::from_str(&request.raw_body).expect("request should be JSON");
|
||||
assert_eq!(
|
||||
body["max_tokens"], expected,
|
||||
"outgoing token limit must match"
|
||||
);
|
||||
}
|
||||
fs::remove_dir_all(&workspace).expect("workspace cleanup should succeed");
|
||||
}
|
||||
|
||||
fn run_claw(
|
||||
cwd: &std::path::Path,
|
||||
config_home: &std::path::Path,
|
||||
home: &std::path::Path,
|
||||
base_url: &str,
|
||||
args: &[&str],
|
||||
) -> Output {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_claw"));
|
||||
command
|
||||
.current_dir(cwd)
|
||||
.env_clear()
|
||||
.envs(support::process_environment())
|
||||
.env("ANTHROPIC_API_KEY", "test-compact-key")
|
||||
.env("ANTHROPIC_BASE_URL", base_url)
|
||||
.env("CLAW_CONFIG_HOME", config_home)
|
||||
.env("HOME", home)
|
||||
.env("NO_COLOR", "1")
|
||||
.args(args);
|
||||
output_with_deadline(&mut command)
|
||||
}
|
||||
|
||||
fn output_with_deadline(command: &mut Command) -> Output {
|
||||
let cwd = command.get_current_dir().expect("isolated workspace");
|
||||
let stdout_path = cwd.join("claw-stdout.txt");
|
||||
let stderr_path = cwd.join("claw-stderr.txt");
|
||||
// Files avoid pipe backpressure and let timeout failures report partial output.
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(fs::File::create(&stdout_path).expect("stdout capture"))
|
||||
.stderr(fs::File::create(&stderr_path).expect("stderr capture"));
|
||||
let mut child = command.spawn().expect("claw should launch");
|
||||
// Release the parent's file handles before workspace cleanup on Windows.
|
||||
command.stdout(Stdio::null()).stderr(Stdio::null());
|
||||
let timeout_secs = 60;
|
||||
let deadline = Instant::now() + Duration::from_secs(timeout_secs);
|
||||
let (status, timed_out) = loop {
|
||||
if let Some(status) = child.try_wait().expect("poll claw") {
|
||||
break (status, false);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().expect("stop timed-out claw");
|
||||
break (child.wait().expect("reap timed-out claw"), true);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
let output = Output {
|
||||
status,
|
||||
stdout: fs::read(&stdout_path).expect("read captured stdout"),
|
||||
stderr: fs::read(&stderr_path).expect("read captured stderr"),
|
||||
};
|
||||
assert!(
|
||||
!timed_out,
|
||||
"claw exceeded the 60-second test deadline; child terminated\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
output
|
||||
}
|
||||
|
||||
fn unique_temp_dir(label: &str) -> PathBuf {
|
||||
let millis = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("clock should be after epoch")
|
||||
.as_millis();
|
||||
let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!(
|
||||
"claw-output-token-limit-{label}-{}-{millis}-{counter}",
|
||||
std::process::id()
|
||||
))
|
||||
}
|
||||
@@ -506,13 +506,14 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
|
||||
},
|
||||
ToolSpec {
|
||||
name: "read_file",
|
||||
description: "Read a text file from the workspace.",
|
||||
description: "Read a text file from the workspace. Optional `selector` (1-indexed lines; overrides `offset`/`limit`): `50` single line, `50-200` inclusive range, `50+150` start plus count, `5-16,960-973` comma-separated (returned as one block from the first to the last selected line), `raw` for the full file, or `conflicts` for a summary of unresolved git merge conflicts. Without `selector`, `offset` (0-based) and `limit` pick the lines; with neither, the whole file is read.",
|
||||
input_schema: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": { "type": "string" },
|
||||
"offset": { "type": "integer", "minimum": 0 },
|
||||
"limit": { "type": "integer", "minimum": 1 }
|
||||
"limit": { "type": "integer", "minimum": 1 },
|
||||
"selector": { "type": "string" }
|
||||
},
|
||||
"required": ["path"],
|
||||
"additionalProperties": false
|
||||
@@ -7210,6 +7211,19 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_file_schema_exposes_selector() {
|
||||
let spec = mvp_tool_specs()
|
||||
.into_iter()
|
||||
.find(|spec| spec.name == "read_file")
|
||||
.expect("read_file spec");
|
||||
assert_eq!(
|
||||
spec.input_schema["properties"]["selector"],
|
||||
json!({ "type": "string" })
|
||||
);
|
||||
assert!(spec.description.contains("selector"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_show_supports_patch_stat_metadata_and_rejects_metadata_path() {
|
||||
let _guard = env_guard();
|
||||
|
||||
Reference in new issue
Block a user