Compare commits

...
54 Commits
Author SHA1 Message Date
Bellmanandclawdbot 0210856f6b docs(changelog): correct v0.1.15 gateway docs attribution (#3409)
Co-authored-by: clawdbot <clawdbot@ultraworkers.dev>
2026-11-27 05:10:42 +00:00
BellmanandWatch 52bbfccb2a release: v0.1.15 (#3408)
Co-authored-by: Watch <watch@local>
2026-11-27 04:17:06 +00:00
tree-zbyandtree-zby 41837f8d82 feat(api): allow hosts to add outbound headers to model requests (#3407)
Adds an optional per-client ExtraHeadersHook. Hosts that need routing, quota or cache-affinity metadata can install it with with_extra_headers_provider on AnthropicClient, OpenAiCompatClient or ProviderClient; headers are applied inside send_raw_request after the JSON body is built.

There is no global state and no behaviour change when no provider is installed. count_tokens does not go through send_raw_request, so it stays unannotated. Transport-owned headers and malformed names/values are dropped, so a broken hook cannot rewrite credentials or fail a call.

Co-authored-by: tree-zby <203675912+tree-zby@users.noreply.github.com>
2026-11-27 04:04:54 +00:00
BellmanandWatch 1849213241 test(runtime): give bash unit tests a realistic timeout on slow Windows ARM runners (#3406)
- Increased timeout from 1_000ms to 30_000ms in executes_simple_command,
  disables_sandbox_when_requested, and prevents_stdin_hangs_by_redirecting_to_null
  tests to account for git-bash cold start delays on Windows ARM runners
- Added clear error message to executes_simple_command assertion that includes
  stderr for better debugging of future timeout failures
- Fixes CI flake: ultraworkers/claw-code ca875261 run 45476362842 and 578e910b run 45815130318

Co-authored-by: Watch <watch@local>
2026-11-26 13:02:52 +00:00
AL Global 578e910bd8 docs: rename UberLLM to MartLLM (#3405)
UberLLM is now MartLLM: same service, accounts and API keys. New site https://martllm.com, API base URL https://api.martllm.com/v1 (the old uberllm.dev addresses keep working).
2026-11-26 11:56:57 +00:00
Joseph Perla ecd697f9f2 docs: document TrustedRouter OpenAI-compatible gateway setup (#3403)
Adds a TrustedRouter section to docs/local-openai-compatible-providers.md: OPENAI_BASE_URL/OPENAI_API_KEY setup, the local/ hatch for vendor-prefixed ids (incl. trustedrouter/auto), the 64k output-token note, and the public /v1/models listing.
2026-11-26 03:01:25 +00:00
Jianbo Maand2867297362mjb-sketch ca8752613b docs: document TeamoRouter OpenAI-compatible gateway setup (#3402)
Co-authored-by: 2867297362mjb-sketch <2867297362@qq.com>
2026-11-24 20:01:24 +00:00
Hashim Syedandhsyed02 a5c2775e81 docs: document Straitly OpenAI-compatible gateway setup (#3400)
Co-authored-by: hsyed02 <hsyed02@student.ubc.ca>
2026-11-23 18:03:38 +00:00
Owaid0723666andOwaid0723666 659f630cce docs: document onomeo OpenAI-compatible gateway setup (#3399)
Co-authored-by: Owaid0723666 <174245396+Owaid0723666@users.noreply.github.com>
2026-11-23 16:01:59 +00:00
d53a088278 docs: document WorldRouter OpenAI-compatible gateway setup
Co-authored-by: Opgeek-1 <173865771+Opgeek-1@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:01:56 +00:00
Bellman eb6f730839 release: v0.1.14 (#3397)
release: v0.1.14
2026-11-23 01:58:17 +00:00
MUGUNDAN 054447e6c2 [CI] Add CI support for building and testing Claw-Code on Windows ARM64 (#3393)
* Add Windows ARM64 build to release workflow

* Add Windows ARM64 build to release workflow
2026-11-22 19:33:26 +00:00
Wei-Lun Li dcf154793a fix(runtime): match CRLF line endings in edit_file (#3387)
read_file and grep_search return a file's lines joined with `\n`, so a
multi-line old_string quoted from a CRLF file never matched and
edit_file failed with "old_string not found in file". On Windows that is
every multi-line edit in a checkout made with Git's default
core.autocrlf=true.

When every line break in the file is `\r\n`, convert old_string and
new_string to CRLF before matching, so the edit applies and inserted
lines keep the file's line endings. LF and mixed files are unchanged.
2026-11-22 19:25:00 +00:00
Thibault Jaigu c3d19aa7d8 docs: document Requesty OpenAI-compatible gateway setup (#3391) 2026-11-22 19:21:07 +00:00
DrSkyle 56c53efa64 fix(tools): expose selector parameter in read_file schema and description (#3395) 2026-11-22 19:19:29 +00:00
Matthew Charles Vladislav Busel dae4337e8b feat(runtime): add Gemini, OpenAI pro, and long-context pricing tiers (#3389)
Adds Gemini API rows and the missing o1-pro, o3-pro, gpt-5.x-pro and
gpt-5.3-codex rows to OPENAI_COMPATIBLE_PRICING, and a per-request
pricing_for_request() that applies the Haiku 5.5 >100K, OpenAI >272K and
Gemini >200K prompt tiers. Usage::estimated_cost_usd uses it, since it
prices one response. pricing_for_model() and aggregated session totals are
unchanged.
2026-11-22 19:17:57 +00:00
Wei-Lun Li 4fb176c65d fix(runtime): prune heavy directories in grep_search (#3388)
grep_search walked and read every file under its root, including .git,
node_modules and target. glob_search already prunes these directories
(#2986), and docs/g002-security-verification-map.md says both search tools
do. In a Rust checkout with a 2.5 GB target/ directory, one grep_search
call took about 2.3 s instead of about 0.13 s, with the same results.

Use the same pruning for grep_search, and never prune the search root
itself, so a search the caller points into node_modules or target still
works for both tools.
2026-11-22 19:17:35 +00:00
Vlad Shulcz f3b0bd5058 docs: list deja-vu in ecosystem section (#3390)
Add deja-vu under community integrations for local cross-agent session memory across Claw Code and 46 other coding agents.
2026-11-22 19:14:49 +00:00
Dror Meirovich 078a27ece5 fix(cli): honor configured output token limits (#3385)
* test(cli): serialize cwd-dependent tests

* fix(cli): honor configured output token limits
2026-11-22 19:10:46 +00:00
Victor He 508b4d862d docs: document HopBase OpenAI-compatible gateway setup (#3384) 2026-11-10 14:59:17 +09:00
henrikdukefossandClaude Opus 5.5 f51a33a896 docs: document Standard Compute OpenAI-compatible gateway setup (#3383)
* docs: document Standard Compute OpenAI-compatible gateway setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: align Standard Compute routing sentence with its docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:02:36 +00:00
Bellman 6a29e08883 Merge pull request #3382 from ultraworkers/release/v0.1.13
release: v0.1.13
2026-11-09 12:07:40 +09:00
clawdbot 7041894439 release: v0.1.13 2026-11-09 03:01:44 +00:00
generaltony007andgeneraltony007 333298ae53 fix(api): retry 529 overloaded and gateway-flake 400 responses (#3381)
* fix(api): retry 529 + gateway-400 in anthropic provider

Co-authored-by: generaltony007 <144252170+GeneralTony007@users.noreply.github.com>

* fix(api): retry 529 + gateway-400 in openai_compat provider

Co-authored-by: generaltony007 <144252170+GeneralTony007@users.noreply.github.com>

* fix(api): correct EOF whitespace in openai_compat

Co-authored-by: generaltony007 <144252170+GeneralTony007@users.noreply.github.com>

---------

Co-authored-by: generaltony007 <144252170+GeneralTony007@users.noreply.github.com>
2026-11-09 02:07:20 +00:00
Bellmanandclawdbot fe2b64ae9e ci(release): build macOS arm64 on macos-15; macos-14 runners are no longer supported (#3380)
Co-authored-by: clawdbot <clawdbot@ultraworkers.dev>
2026-11-08 20:21:40 +00:00
Bellman bd4043a83e Merge pull request #3379 from ultraworkers/release/v0.1.12
release: v0.1.12
2026-11-09 05:08:25 +09:00
clawdbot 072892ff1e release: v0.1.12 2026-11-08 20:02:31 +00:00
Dror Meirovichandclawdbot 407a6c62f8 fix(windows): fix native runtime compatibility and enable workspace t… (#3378)
* fix(windows): fix native runtime compatibility and enable workspace tests

Fix shell discovery, hook quoting, native path handling and OAuth
randomness on Windows, make the test fixtures portable, and run the
full workspace test suite in the Windows CI job.

* test(plugins): make lifecycle fixtures Windows-compatible

* fix(windows): address workspace test failures

---------

Co-authored-by: clawdbot <clawdbot@ultraworkers.dev>
2026-11-08 19:45:52 +00:00
Rohan BhartiandClaude ca48ec7500 test(tools): cover NotebookEdit cell-type switching, id collisions and unknown ids (#3377)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-06 21:56:45 +00:00
Penguin Secret Agencyandsang nguyen ab8561dc37 docs: document UberLLM OpenAI-compatible gateway setup (#3376)
Co-authored-by: sang nguyen <sangnguyen@sangs-MacBook-Pro-5.local>
2026-11-05 07:01:42 +09:00
Bellman 747e160b59 Merge pull request #3374 from ultraworkers/release/v0.1.11
release: v0.1.11
2026-11-04 22:02:52 +09:00
knowhyandknowhy 6ac59ab90b docs: document LLMTR OpenAI-compatible gateway setup (#3373)
Co-authored-by: knowhy <194148385+knowhycodata@users.noreply.github.com>
2026-11-04 13:00:45 +00:00
clawdbot 67e5783894 release: v0.1.11 2026-11-04 12:59:09 +00:00
Iain db58b190bd fix(tools): stop NotebookEdit reusing cell ids after a delete (#3371)
Inserted cells were named cell-{len+1}, which is still taken once any
cell but the last has been deleted, so a later edit by the returned id
went to the older cell instead.
2026-11-04 12:02:30 +00:00
Bellman 51cfca114c Merge pull request #3370 from ultraworkers/release/v0.1.10
release: v0.1.10
2026-11-02 10:23:26 +09:00
clawdbot 1cae56fd3f release: v0.1.10 2026-11-02 01:14:53 +00:00
Iainandclawdbot a289024b35 fix(tools): cut RemoteTrigger responses on a char boundary (#3369)
* fix(tools): cut RemoteTrigger responses on a char boundary

A response over 8192 bytes with a multi-byte character across byte 8192 panicked on the slice.

* test(tools): add multibyte char boundary truncation test for RemoteTrigger

---------

Co-authored-by: clawdbot <clawdbot@ultraworkers.dev>
2026-11-02 00:03:39 +00:00
Bellman f4fff38de1 Merge pull request #3368 from ultraworkers/release/v0.1.9
release: v0.1.9
2026-10-29 04:59:12 +09:00
clawdbot 3a802f7bf9 release: v0.1.9 2026-10-28 19:58:30 +00:00
Bougie 8523d59a84 fix(runtime): keep tool-use/tool-result pairs paired in Trident compaction (#3367)
Trident stage 1 dropped the assistant message that carried a file tool
use while keeping the tool result that answered it, so the compacted
session ended up with orphaned `tool_result` blocks. Providers reject
such requests with HTTP 400 ("tool_result blocks must be a response to
a preceding tool_use"), which breaks the auto-compact retry path that
runs Trident before resending a request.

Stage 1 also counted a tool result as an independent file operation,
which pushed `last_write` past the write the result belonged to and made
the newest write look obsolete.

Only tool uses count as file operations now, and a tool result is
dropped together with the tool use that produced it.
2026-10-28 19:01:54 +00:00
Bellman 8aab1d4e54 Merge pull request #3366 from ultraworkers/release/v0.1.8
release: v0.1.8
2026-10-23 23:02:25 +09:00
clawdbot 26611f44c5 release: v0.1.8 2026-10-23 13:58:42 +00:00
Bellmanandclawdbot fd8527f899 Fix #3364: web search robustness - handle non-2xx responses and filter search engine self-links (#3365)
* Fix issue #3364: web search returns error on non-2xx response and filters search engine self-links

- Add HTTP status code check to execute_web_search: return error if response is not 2xx
  instead of proceeding with potentially junk results (e.g., DuckDuckGo challenge pages)
- Filter out links pointing back to the search engine host in extract_search_hits_from_generic_links
  to avoid returning search engine self-links when no proper search results are found
- Add regression tests for both scenarios

Refs #3364

* fix: implement registrable domain filtering and error on 202/blocked responses

- Replace exact host matching with registrable domain comparison to properly
  filter search engine self-links across subdomains (e.g., html.duckduckgo.com
  vs duckduckgo.com)
- Add error handling for 2xx responses with no search results (e.g., 202
  challenge pages from blocked search providers)
- Add regression tests for both 202 challenge page and mixed self-link scenarios
- Remove unrelated Cargo.lock version bumps (revert to 0.1.6)

Fixes #3364

* fix(tools): reject DuckDuckGo 202 challenge pages and drop search-engine links

The challenge page arrives as HTTP 202, which is_success() accepts, and its
links point at duckduckgo.com while the request goes to html.duckduckgo.com,
so the previous filter kept them. Only a 200 page is parsed now, and the
generic fallback drops any duckduckgo.com link or link to the configured
search host. Removes the registrable-domain heuristic and the 'no hits is an
error' path (a real query can legitimately return nothing), and replaces
tests that never exercised a self-link with ones that fail on the old code.

Refs #3364

---------

Co-authored-by: clawdbot <clawdbot@ultraworkers.dev>
2026-10-23 14:22:40 +01:00
Bellman 22fe36072a Merge pull request #3363 from ultraworkers/release/v0.1.7
release: v0.1.7
2026-10-19 13:07:03 +09:00
clawdbot 0a899b630b test: update user-agent version check to 0.1.7 2026-10-19 04:04:04 +00:00
clawdbot 3e514dbf18 release: v0.1.7 2026-10-19 04:01:05 +00:00
twtrubiks 66418c6127 fix(runtime): name the session model in the system prompt (#3359)
The environment section rendered "Model family: Claude Opus 4.6" for
every Anthropic model, so claude-opus-5-5, claude-sonnet-4-6, and any
other Claude model told users it was Opus 4.6.

Render a neutral "Claude" family label followed by the resolved model
ID, and rebuild the system prompt on /model so the line follows a
mid-session switch instead of keeping the startup model.
2026-10-19 04:52:41 +01:00
twtrubiks 3cc90cfc7a feat(runtime): add OpenAI, xAI, and DashScope pricing (#3358)
Models from the OpenAI-compatible providers fell back to
default_sonnet_tier ($3/$15 per MTok), so e.g. gpt-5.4-nano was
estimated at 15x its input price and qwen-plus at about 26x.

Add a table of published rates keyed by model id, matching dated
snapshots and -latest aliases:

- OpenAI standard tier for current gpt-6 / gpt-5.x / gpt-4.1 / gpt-4o
  and o-series models (Responses-only pro models are omitted).
- xAI grok-4.x and grok-build. Slugs retired on 2026-05-15 (grok-3,
  grok-4-0709, grok-4-fast-*, grok-4-1-fast-*) are billed at grok-4.3
  rates, and grok-code-fast-* is served as grok-build.
- DashScope qwen-max, qwen-plus, qwen-flash and kimi-k2.5 at China
  (Beijing) rates, which is claw's default DashScope endpoint, with
  non-thinking output and the 20% implicit-cache hit rate.

Long-context and higher input tiers use the base rate because usage is
aggregated across requests.
2026-10-19 12:15:58 +09:00
clawdbot b8f93afbb3 fix: parallel tool-result pairing, terminal-scope path limit, credential hint
Merge PR #3360 from c01dsummer/claw-code (fix/roadmap-835-838)

Four fixes addressing issues #3361 and #3360:

1. Parallel tool-result pairing (835): The Anthropic Messages API requires all
   tool results of a turn to be in a single message. When a turn issued two tool
   calls at once, the results were sent in separate messages, causing a 400 error.
   Fixed by merging adjacent tool-result-only messages into one.

2. Terminal-scope path limit (836): Correlation keys up to 512 bytes expanded to
   1024+ hex characters, exceeding APFS's 1024-byte total path limit. Fixed by
   using SHA256 digest (32 hex chars) for path components while storing the full
   key in the record for exact matching.

3. Credential hint (838): When ANTHROPIC_BASE_URL points to a non-Anthropic
   endpoint (DeepSeek, corporate gateways), the missing-credentials error now
   explains that the endpoint expects its own credentials, not Anthropic's.

4. ROADMAP entries: Documents all three fixes with verification details.

All tests pass (370+ for rusty-claude-cli, 240+ for sdk, 122+ for tools, 209+ for
api). Formatting verified with cargo fmt. CI checks approved and passed.

Fixes #3361, #3360
2026-10-19 03:11:01 +00:00
twtrubiks c55c7e4710 fix(runtime): skip non-UTF-8 environment variables instead of panicking (#3356)
std::env::vars() panics on any non-UTF-8 value. zsh exports a metafied
$_ when the command path contains non-ASCII characters (e.g. 下載), so
claw panicked on startup. Use vars_os() and skip entries that are not
valid UTF-8.
2026-10-19 12:04:36 +09:00
Wu Shuwen 917a9e28ee fix(plugins): cfg-gate non-Windows hook path import (#3302) 2026-10-19 12:03:10 +09:00
twtrubiks 4b8c79e73c fix(runtime): update model pricing for Anthropic and DeepSeek APIs
* fix(runtime): update model pricing table to current rates

Align pricing_for_model with the published Anthropic pricing table:

- default_sonnet_tier was $15/$75 (the old Opus rate); it is now the
  Sonnet 4.x rate of $3/$15, which is what the `sonnet` alias resolves to.
- Add Sonnet 5 / 5.5, Haiku 5.5, Haiku 3.5, and Fable / Mythos rates.
- Opus 4.5+ is $5/$25 and Opus 5.5 is $4/$20; Opus 4/4.1 keep the $15/$75
  tier they are still billed at on Bedrock and Google Cloud.

Versions are parsed from the model id so dated, provider-prefixed, and
Vertex-style ids resolve to the right tier. Haiku 5.5's >100K-token tier
is not modeled because usage is aggregated across requests.

* fix(runtime): add DeepSeek API pricing

DeepSeek models fell back to default_sonnet_tier ($3/$15 per MTok),
overestimating V4 Flash by about 10x on input and 12x on output.

Price the ids served by the DeepSeek API at peak rates: deepseek-v4-pro
at $1.32/$3.96, and deepseek-flash, deepseek-v4-flash and the retired
deepseek-chat / deepseek-reasoner aliases at $0.30/$1.20. Off-peak usage
is billed at half. Other DeepSeek models on third-party hosts keep the
default because their prices vary by host.
2026-10-19 12:02:18 +09:00
twtrubiks 78ffd13d19 fix(cli): stop duplicating thinking blocks in streamed responses
push_output_block recorded a thinking event at content_block_start (an
empty placeholder) and the stream loop recorded the full block again at
content_block_stop. The empty duplicate was replayed on the next request
and rejected with 400 "each thinking block must contain thinking".
Only emit the event from the non-streaming path.
2026-10-19 03:01:20 +00:00
devilking7x 6d7412d958 docs: sync zh README star-history chart to dera.page mirror (#3354)
The English README migrated the star-history chart/link from
star-history.com / api.star-history.com to star-history.dera.page,
but README.zh.md (last synced at d229a9b) still used the old domains.
Update the 4 URLs so both language versions stay consistent.
2026-10-13 09:57:11 +01:00
61 changed files with 4342 additions and 800 deletions

No files matched your search

+5 -1
View File
@@ -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
+14 -2
View File
@@ -126,8 +126,15 @@ jobs:
run: cargo clippy --workspace
windows-smoke:
name: windows 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
@@ -138,6 +145,11 @@ jobs:
- uses: Swatinem/rust-cache@49a0bdc70d2e1b713ca9e2869b211fcce03d3c1c
with:
workspaces: rust -> target
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
with:
python-version: "3.x"
- name: Run Windows workspace tests
run: cargo test --workspace --locked --no-fail-fast
- name: Build CLI for Windows smoke
run: cargo build -p rusty-claude-cli
- name: Smoke local commands without live credentials
+1
View File
@@ -19,3 +19,4 @@ status-help.txt
.envrc.local
result
result-*
.DS_Store
+113
View File
@@ -5,6 +5,119 @@ 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
- Git Bash discovery works when only Git's `cmd` directory is on `PATH` (#3378)
- REPL and PowerShell executables resolve from `PATH`, honoring Windows `PATHEXT` (#3378)
- Quoted hook and plugin script paths containing spaces are preserved through `cmd /D /S /C` (#3378)
- Windows verbatim and native paths are handled correctly in glob matching and workspace-containment checks (#3378)
- OAuth PKCE and state use OS-backed randomness instead of `/dev/urandom` (#3378)
### Changed
- Windows hooks now run with `cmd /D`, which disables AutoRun (#3378)
- CI runs the full Rust workspace test suite on Windows (#3378)
## [0.1.11] - 2026-11-04
### Fixed
- NotebookEdit no longer reuses an existing cell id for a newly inserted cell after a cell has been deleted, so later edits by id target the intended cell (#3371)
## [0.1.10] - 2026-11-02
### Fixed
- RemoteTrigger no longer panics when a webhook response over 8 KiB has a multibyte character across the truncation point; it is now cut on a character boundary (#3369)
## [0.1.9] - 2026-10-29
### Fixed
- Trident compaction no longer leaves orphaned tool_result blocks after superseding a file tool use, which made providers reject auto-compact retries with HTTP 400 (#3367)
## [0.1.8] - 2026-10-23
### Fixed
- Web search error handling: explicit 'Web search unavailable (HTTP N)' error on non-2xx responses instead of junk results (#3365)
- Web search result filtering: drop links back to search engine host (#3365)
## [0.1.7] - 2026-10-19
### Added
- Parallel tool-result pairing with concurrent execution support
- Explicit session model naming in system prompt for clarity
- Custom OpenAI provider namespace support (separate environment variables)
### Fixed
- Stop duplicating thinking blocks in streamed responses (#3355)
- Non-UTF-8 environment variable handling to skip instead of panic (#3356)
- Parallel tool-result ordering by call index to fix provider 400 errors (#3360, #3361)
- Windows build cfg-gating for non-Windows hook Path import (#3302)
### Changed
- Updated Anthropic and DeepSeek model pricing (#3357)
- Updated OpenAI, X.AI, and DashScope model pricing (#3358)
- Enhanced credential hint for non-Anthropic ANTHROPIC_BASE_URL usage
- Terminal-scope path length limit enforcement
### Known Limitations
- ACP / Zed integration is not yet implemented (status stub available via `claw acp`)
- Python porting workspace is for reference only, not used in production
## [0.1.6] - 2026-10-13
### Added
+4
View File
@@ -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.
+4 -4
View File
@@ -87,11 +87,11 @@
</p>
<p align="center">
<a href="https://star-history.com/#ultraworkers/claw-code&Date">
<a href="https://star-history.dera.page/#ultraworkers/claw-code&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=ultraworkers/claw-code&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=ultraworkers/claw-code&type=Date" />
<img alt="Star history for ultraworkers/claw-code" src="https://api.star-history.com/svg?repos=ultraworkers/claw-code&type=Date" width="600" />
<source media="(prefers-color-scheme: dark)" srcset="https://star-history.dera.page/svg?repos=ultraworkers/claw-code&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://star-history.dera.page/svg?repos=ultraworkers/claw-code&type=Date" />
<img alt="Star history for ultraworkers/claw-code" src="https://star-history.dera.page/svg?repos=ultraworkers/claw-code&type=Date" width="600" />
</picture>
</a>
</p>
+20
View File
@@ -8018,3 +8018,23 @@ Original filing (2026-04-18): the session emitted `SessionStart hook (completed)
834. **DONE — Local-model syntax bypass only covered Ollama-shaped tags, not bare LM Studio/llama.cpp aliases** — follow-up to #833/PR #3213. `is_local_openai_model_syntax()` waived strict `provider/model` syntax under `OPENAI_BASE_URL` only when the model name contained a `.` or `:` (Ollama-tag-shaped). A local server registering a model under a bare alias with none of those characters — for example an LM Studio custom name or a llama.cpp `--alias` value like `mistral` — still failed CLI-parse-time validation unless the user discovered the `local/` prefix workaround. Fix: (1) `is_local_openai_compatible_base_url()` in `openai_compat.rs`, already used to waive the API-key requirement for loopback/private-network base URLs, is now `pub` and re-exported from the `api` crate root; (2) `is_local_openai_model_syntax()` in `rusty-claude-cli`'s `main.rs` calls it against the configured `OPENAI_BASE_URL` and accepts any non-empty model name when the host is local/private, matching the existing `OLLAMA_HOST` bypass; (3) remote/hosted `OPENAI_BASE_URL` gateways keep the stricter dot/colon-tag heuristic so a mistyped bare name doesn't silently route to a paid hosted API; (4) `local/` remains the explicit escape hatch for slash-containing IDs regardless of host; (5) added an LM Studio section and updated routing notes in `docs/local-openai-compatible-providers.md`. [SCOPE: claw-code]
**Verification.** `scripts/fmt.sh --check`; `cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets -- -D warnings`; `cargo test --manifest-path rust/Cargo.toml --workspace`; new tests `local_openai_base_url_bypasses_bare_model_names`, `private_network_openai_base_url_bypasses_bare_model_names`, and `remote_openai_base_url_still_requires_provider_model_or_tag_syntax` in `rusty-claude-cli`'s `alias_resolution_tests` module; `is_local_openai_compatible_base_url_is_reachable_via_crate_root` in `api`'s `client.rs` confirming the re-export.
835. **DONE — Parallel tool-call turns sent `tool_result` blocks one message too late** — found while investigating a live `claw` REPL failure that returned `api returned 400 Bad Request (invalid_request_error): messages.3: tool_use ids were found without tool_result blocks immediately after: call_01_4QJqcZ0075kla1ILwra75582`. `runtime` records one `MessageRole::Tool` message per tool call, and `convert_messages()` in `rusty-claude-cli`'s `main.rs` turned each of them into its own wire message. The Anthropic Messages API requires *every* `tool_use` of an assistant message to be answered by `tool_result` blocks **in the single message immediately after it**, so when a turn issued two tool calls at once the first result was paired and the second arrived one message late — the provider rejected the whole request. The 400 itself only appears when a turn requests several tools at once, because a single-call turn already puts its one result in the following message. Fix: (1) `convert_messages()` is split into a per-message `convert_message()` plus a folding accumulator `absorb_tool_result_message()`; (2) a run of adjacent tool-result messages now merges into the one `user` message that follows the assistant turn, matching what the API requires; (3) a merge requires both the accumulated message and the incoming one to be pure tool results, so neither user text nor an assistant turn can be joined into a tool-result message; (4) `converts_tool_roundtrip_messages` keeps its previous single-call contract. Evidence for the reported failure: `.claw/sessions/e49619b247aa3fce/session-1792170907799-0.jsonl`, whose step-1 assistant message carries two `tool_use` blocks followed by two separate tool-result messages. [SCOPE: claw-code]
**Verification.** New unit test `converts_parallel_tool_call_results_into_one_paired_message` in `rusty-claude-cli`'s `main.rs` asserts both ids are answered in one message and in call order; new integration test `rust/crates/rusty-claude-cli/tests/parallel_tool_result_pairing.rs` drives the real `claw` binary against the mock Anthropic service for the `multi_tool_turn_roundtrip` scenario and asserts the wire contract on the captured request bodies. Run against the pre-fix implementation that integration test fails with the payload behind the live 400 (`assistant["tool_use", "tool_use"]` followed by `user["tool_result"]`, `user["tool_result"]`; only `toolu_multi_read` answered). It lives in `tests/` rather than unit-test scope so it can be reverted independently of the fix.
**Correction during review (PR #3360).** The first cut of this fix checked only the *accumulated* message when deciding whether to merge, so any message that arrived after a tool result was folded into it: `user -> assistant(tool_use) -> tool_result -> assistant("done")` turned that reply into an extra `text` block inside the tool-result message and the assistant role was lost. `AnthropicRuntimeClient::stream` converts the whole history on every request, so the damage outlived the turn that caused it, and it was reachable on single-tool-call turns too — the original tests stopped at the tool-result message and could not see the next round. A merge now requires **both** sides to be pure tool results; `keeps_the_assistant_reply_that_follows_tool_results` and `keeps_a_user_follow_up_that_follows_tool_results_separate` pin it, and both fail when the incoming side is not checked. The second review point was a missed call site: `rust/crates/tools/src/lib.rs` carries its own `convert_messages` for the subagent path, where the parallel-call 400 was still live; it now folds through the same merge rule with its own coverage (`subagent_parallel_tool_results_share_one_message`, `subagent_merge_requires_both_sides_to_be_tool_results`). `scripts/fmt.sh --check`; `cargo test --manifest-path rust/Cargo.toml -p rusty-claude-cli`; `cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets -- -D warnings` reports no findings in the changed crates.
836. **DONE — Terminal-scope record paths exceeded the filesystem path limit for long correlation keys** — `TerminalScopeStore::record_path()` in the `sdk` crate expanded the correlation key into full hex and chunked it into 180-byte path components. A maximal 512-byte key expands to 1024 hex characters, so the generated path ran past the 1024-byte total-path limit enforced by APFS and `set()`/`get()` failed with `File name too long (os error 63)`. The misleading part is where the limit lives: every component stayed within the 255-byte filename limit (five 180-byte directories plus a 129-byte leaf), so the errno named a generated leaf name the caller never chose, and lowering the chunk size cannot help because the hex expansion stays 1024 characters however it is split. The same code passes on Linux, where `PATH_MAX` is 4096, so `cargo test --workspace` on the ubuntu-latest CI job could not catch it. Fix: (1) `record_path()` now names records from a fixed-width SHA-256 digest (`<32 hex>.json`) and the multi-level chunking is gone; (2) the full key still lives in `TerminalScopeRecord::correlation_key` and is still checked on read, so `encoded_keys_are_isolated_and_cannot_traverse_paths` keeps holding; (3) `encode_key_as_hex()` is replaced by `encode_key_for_path()`; (4) `sha2` joins the `sdk` dependencies, reusing the version `runtime` already pulls so `Cargo.lock` gains one line. [SCOPE: claw-code]
**Verification.** `long_hex_keys_use_safe_path_components` now asserts on the path shape (longest component ≤ 255 bytes, total path < 1024 bytes) instead of only round-tripping, because a round trip inside a short temporary root succeeds even when the generated path is unusable in practice. That assertion fails against the pre-fix implementation with the recorded error above. `cargo test --manifest-path rust/Cargo.toml -p sdk`; `scripts/fmt.sh --check`; `cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets -- -D warnings` reports no findings in the changed crates.
837. **KNOWN FLAKE (not fixed) — MCP stdio fixtures exceed their test-only handshake budget under the default parallel test run** — found while establishing a green baseline for #835/#836. `cargo test --workspace` (the command [rust-ci.yml](.github/workflows/rust-ci.yml) runs, with no thread limit) reports 10-11 failures in `runtime`'s `mcp_stdio::tests` and `mcp_tool_bridge::tests` on this machine, all of the shape `Timeout { server_name: "alpha", method: "initialize", timeout_ms: 200 }`. Cause: `mcp_stdio.rs` halves the production handshake budgets for test builds only — `MCP_INITIALIZE_TIMEOUT_MS` 200ms vs 10_000ms, `MCP_LIST_TOOLS_TIMEOUT_MS` 300ms vs 30_000ms — while the tests drive a real `python3` stdio fixture whose cold start measures 18-21ms (`min=18 max=21 avg=20` over 10 runs). That is ~10x headroom when the tests run serially, but the default run starts a dozen fixture children at once and the budget is consumed by process startup alone. The `#[cfg(test)]` gate is why the impact is bounded: integration targets such as `runtime/tests/*.rs` link the non-test library and therefore use the production budgets, which is why only the two in-crate unit-test modules go red — no production path is affected, and no CLI or harness behavior depends on these values. [SCOPE: claw-code]
**Disposition.** The budget constants were deliberately left unchanged: shortening them is what makes a real handshake regression fail fast, so widening them to buy parallel tolerance trades away the guard those cases exist for. Instead the cause is documented where the numbers are read, and this item records it for claws that hit the failures and misread them as a product defect. This mirrors the existing documented-but-unfixed items in this roadmap (for example the `clippy` job running without `-D warnings`).
**How to read it.** Re-run with `--test-threads=1` before treating those failures as a regression. On the same machine and commit: `cargo test --workspace` (parallel) = 11 failed / 1792 passed; `cargo test --workspace -- --test-threads=1` = **0 failed / 1803 passed / 1 ignored**; `cargo test -p runtime --lib -- --test-threads=1` = 721 passed; `cargo test -p runtime --lib mcp_stdio:: -- --test-threads=1` = 22 passed. The failure set also moves between runs (`mcp_tool_bridge::tests::call_tool_payload_structure` and `manager_times_out_slow_tool_calls` each fail in one run and pass in the next), and libtest aborts in-flight cases when one panics, so the reported `passed` count itself varies between parallel runs — another sign that these are scheduling artifacts rather than deterministic defects. The single `ignored` case is `api/tests/client_integration.rs::live_stream_smoke_test`, which is marked `requires ANTHROPIC_API_KEY and network access`.
838. **DONE — Missing-credential message ignored a configured non-Anthropic `ANTHROPIC_BASE_URL`** — dogfooded while running `./target/debug/claw prompt "say hello"` with `ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic` and no credential exported. The error was truthful but misleading: `missing Anthropic credentials; export ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY before calling the Anthropic API` names two env vars that a DeepSeek user does need to set, yet reads as "go obtain an Anthropic key" and never mentions the endpoint the user had already configured. Third-party Anthropic-compatible endpoints (DeepSeek's `/anthropic` path, corporate gateways, local proxies) accept those two variable names only as a wire-compatibility convention: the value must be a credential the endpoint itself issued, and an `sk-ant-` key will be rejected. `anthropic_missing_credentials_hint()` only sniffed `FOREIGN_PROVIDER_ENV_VARS` (`OPENAI_API_KEY` / `XAI_API_KEY` / `DASHSCOPE_API_KEY`) and never looked at `ANTHROPIC_BASE_URL`, so this whole class of user — someone who already knows what to configure — fell through to the generic wall. Fix: (1) a new `custom_anthropic_base_url_hint()` branch returns a hint whenever `ANTHROPIC_BASE_URL` is set to anything other than `anthropic::DEFAULT_BASE_URL` (empty or whitespace-only values are ignored); (2) the hint names the configured URL, states it is not the Anthropic API, and explains the variable-name convention; (3) the branch runs before the foreign-provider loop, because a configured endpoint is a fact about what the user asked for while a presence check on another provider's key only guesses at intent; (4) base-url resolution reuses `anthropic::read_base_url()` so the hint can never disagree with the client's own endpoint. [SCOPE: claw-code]
**Verification.** Reproduced the exact command with the fix: the error now carries a third line naming `https://api.deepseek.com/anthropic`. New tests `anthropic_missing_credentials_hint_names_a_custom_base_url` (asserts the URL, the "not the Anthropic API" claim, and that both credential variable names survive), `anthropic_missing_credentials_hint_prefers_custom_base_url_over_foreign_creds` (pins the precedence rule against a regression, since both hints can apply at once), and `anthropic_missing_credentials_hint_is_none_for_the_default_base_url`. Seven pre-existing hint/error tests previously depended on the ambient `ANTHROPIC_BASE_URL` and now pin it explicitly, so they no longer pass or fail according to the developer's shell. `cargo test -p api` (172 unit tests plus the four integration targets); `scripts/fmt.sh --check`.
+21
View File
@@ -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`):
+229
View File
@@ -149,6 +149,235 @@ curl -sS "$OPENAI_BASE_URL/models" \
For local configuration, see your gateway's documentation for the correct base URL, API key format, and available model IDs. The same OPENAI_BASE_URL + OPENAI_API_KEY pattern applies to any OpenAI-compatible remote gateway.
## LLMTR
[LLMTR](https://llmtr.com) is an OpenAI-compatible gateway. Use the same client: set `OPENAI_BASE_URL` to `https://llmtr.com/v1` and `OPENAI_API_KEY` to a bearer key (`llmtr-...`).
```bash
export OPENAI_BASE_URL="https://llmtr.com/v1"
export OPENAI_API_KEY="llmtr-..."
claw --model "local/llmtr/qwen3-8-27b" prompt "Reply exactly HELLO_WORLD_123"
```
Send the catalog id unchanged. `llmtr/qwen3-8-27b` already starts with the gateway name, so that prefix stays on the wire. The `local/` hatch only selects the OpenAI-compatible transport and is removed before the request. A bare `qwen/` or `qwen-` name is a DashScope route and will not reach LLMTR, so vendor-prefixed ids need the same hatch: `local/<vendor>/<model>`.
Claw asks for up to 64,000 output tokens on these routes. LLMTR rejects a request whose `max_tokens` is above the model's output limit, so pick a model that allows at least that much. `llmtr/qwen3-8-27b` allows 262,144. 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://llmtr.com/v1/models" \
| jq -r '.data[] | "\(.id)\t\(.top_provider.max_completion_tokens)"'
```
## MartLLM
[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.martllm.com/v1"
export OPENAI_API_KEY="ull_..."
claw --model "local/deepseek/deepseek-v4-flash" prompt "Reply exactly HELLO_WORLD_123"
```
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. 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.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/`.
+15 -11
View File
@@ -93,7 +93,7 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "api"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"criterion",
"reqwest",
@@ -478,7 +478,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "claw-analog"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"api",
"clap",
@@ -498,7 +498,7 @@ dependencies = [
[[package]]
name = "claw-rag-service"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"axum 0.8.9",
"blake3",
@@ -531,7 +531,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "commands"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"plugins",
"runtime",
@@ -540,7 +540,7 @@ dependencies = [
[[package]]
name = "compat-harness"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"commands",
"runtime",
@@ -1568,7 +1568,7 @@ dependencies = [
[[package]]
name = "mock-anthropic-service"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"api",
"serde_json",
@@ -1761,7 +1761,7 @@ dependencies = [
[[package]]
name = "plugins"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"serde",
"serde_json",
@@ -2136,11 +2136,13 @@ dependencies = [
[[package]]
name = "runtime"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"getrandom 0.2.17",
"glob",
"plugins",
"regex",
"same-file",
"serde",
"serde_json",
"sha2",
@@ -2261,7 +2263,7 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "rusty-claude-cli"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"api",
"commands",
@@ -2340,6 +2342,7 @@ dependencies = [
"runtime",
"serde",
"serde_json",
"sha2",
"tempfile",
"tokio",
"tokio-tungstenite",
@@ -2621,7 +2624,7 @@ dependencies = [
[[package]]
name = "telemetry"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"serde",
"serde_json",
@@ -2901,7 +2904,7 @@ dependencies = [
[[package]]
name = "tools"
version = "0.1.6"
version = "0.1.15"
dependencies = [
"api",
"aspect-core",
@@ -2910,6 +2913,7 @@ dependencies = [
"commands",
"flate2",
"log",
"mock-anthropic-service",
"plugins",
"reqwest",
"runtime",
+1 -1
View File
@@ -3,7 +3,7 @@ members = ["crates/*"]
resolver = "2"
[workspace.package]
version = "0.1.6"
version = "0.1.15"
edition = "2021"
license = "MIT"
publish = false
+17 -11
View File
@@ -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 {
@@ -281,21 +297,11 @@ pub fn read_xai_base_url() -> String {
#[cfg(test)]
mod tests {
use std::sync::{Mutex, OnceLock};
use crate::test_env_lock as env_lock;
use super::{ProviderClient, ProviderConfig, ProviderConfigKind};
use crate::providers::{detect_provider_kind, resolve_model_alias, ProviderKind};
/// Serializes every test in this module that mutates process-wide
/// environment variables so concurrent test threads cannot observe
/// each other's partially-applied state.
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[test]
fn resolves_existing_and_grok_aliases() {
assert_eq!(resolve_model_alias("opus"), "claude-opus-4-7");
+31 -8
View File
@@ -56,14 +56,14 @@ pub enum ApiError {
status: reqwest::StatusCode,
error_type: Option<String>,
message: Option<String>,
request_id: Option<String>,
request_id: Option<Box<str>>,
body: String,
retryable: bool,
/// Suggested user action based on error type (e.g., "Reduce prompt size" for 413)
suggested_action: Option<String>,
suggested_action: Option<&'static str>,
/// Parsed Retry-After header value (seconds) for 429 responses.
/// When present, overrides the exponential backoff delay.
retry_after: Option<Duration>,
retry_after: Option<Box<Duration>>,
},
RetriesExhausted {
attempts: u32,
@@ -137,7 +137,7 @@ impl ApiError {
/// over the computed backoff delay when it exists.
pub fn retry_after(&self) -> Option<Duration> {
match self {
Self::Api { retry_after, .. } => *retry_after,
Self::Api { retry_after, .. } => retry_after.as_deref().copied(),
Self::RetriesExhausted { last_error, .. } => last_error.retry_after(),
_ => None,
}
@@ -531,6 +531,29 @@ mod tests {
assert_eq!(snippet, "한글한글…");
}
#[test]
fn retry_after_survives_retry_exhaustion_wrapping() {
let delay = std::time::Duration::from_secs(42);
let error = ApiError::Api {
status: reqwest::StatusCode::TOO_MANY_REQUESTS,
error_type: None,
message: None,
request_id: Some("retry-trace".into()),
body: String::new(),
retryable: true,
suggested_action: Some("Wait before retrying"),
retry_after: Some(Box::new(delay)),
};
assert_eq!(error.retry_after(), Some(delay));
let wrapped = ApiError::RetriesExhausted {
attempts: 2,
last_error: Box::new(error),
};
assert_eq!(wrapped.retry_after(), Some(delay));
assert_eq!(wrapped.request_id(), Some("retry-trace"));
assert!(wrapped.is_retryable());
}
#[test]
fn detects_generic_fatal_wrapper_and_classifies_it_as_provider_internal() {
let error = ApiError::Api {
@@ -540,7 +563,7 @@ mod tests {
"Something went wrong while processing your request. Please try again, or use /new to start a fresh session."
.to_string(),
),
request_id: Some("req_jobdori_123".to_string()),
request_id: Some("req_jobdori_123".into()),
body: String::new(),
retryable: true,
suggested_action: None,
@@ -564,7 +587,7 @@ mod tests {
"Something went wrong while processing your request. Please try again, or use /new to start a fresh session."
.to_string(),
),
request_id: Some("req_nested_456".to_string()),
request_id: Some("req_nested_456".into()),
body: String::new(),
retryable: true,
suggested_action: None,
@@ -586,7 +609,7 @@ mod tests {
"This model's maximum context length is 200000 tokens, but your request used 230000 tokens."
.to_string(),
),
request_id: Some("req_ctx_123".to_string()),
request_id: Some("req_ctx_123".into()),
body: String::new(),
retryable: false,
suggested_action: None,
@@ -607,7 +630,7 @@ mod tests {
"Input tokens exceed the configured limit of 922000 tokens. Your messages resulted in 1860900 tokens. Please reduce the length of the messages."
.to_string(),
),
request_id: Some("req_ctx_openai_123".to_string()),
request_id: Some("req_ctx_openai_123".into()),
body: String::new(),
retryable: false,
suggested_action: None,
+150
View File
@@ -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());
}
}
+12
View File
@@ -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,
@@ -46,3 +48,13 @@ pub use telemetry::{
MemoryTelemetrySink, SessionTraceRecord, SessionTracer, TelemetryEvent, TelemetrySink,
DEFAULT_ANTHROPIC_VERSION,
};
// Environment variables are shared by every test module in this process.
// Module-local locks cannot protect provider tests from each other.
#[cfg(test)]
pub(crate) fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
LOCK.get_or_init(|| std::sync::Mutex::new(()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
+1 -8
View File
@@ -500,7 +500,7 @@ fn stable_hash_bytes(bytes: &[u8]) -> u64 {
#[cfg(test)]
mod tests {
use std::sync::{Mutex, OnceLock};
use crate::test_env_lock;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use super::{
@@ -509,13 +509,6 @@ mod tests {
};
use crate::types::{InputMessage, MessageRequest, MessageResponse, OutputContentBlock, Usage};
fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[test]
fn path_builder_sanitizes_session_identifier() {
let paths = PromptCachePaths::for_session("session:/with spaces");
+174 -15
View File
@@ -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)
}
@@ -886,11 +910,11 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
}
let headers = response.headers().clone();
let request_id = request_id_from_headers(&headers);
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 retry_after = parse_retry_after(&headers, 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 {
status,
@@ -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
@@ -1083,9 +1110,9 @@ struct AnthropicErrorBody {
#[cfg(test)]
mod tests {
use super::{ALT_REQUEST_ID_HEADER, REQUEST_ID_HEADER};
use crate::test_env_lock as env_lock;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Mutex, OnceLock};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -1095,14 +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};
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
use crate::extra_headers::ExtraHeadersHook;
use crate::types::{ContentBlockDelta, InputMessage, MessageRequest};
fn temp_config_home() -> std::path::PathBuf {
std::env::temp_dir().join(format!(
@@ -1153,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();
@@ -1452,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]
@@ -1651,7 +1756,7 @@ mod tests {
status: reqwest::StatusCode::UNAUTHORIZED,
error_type: Some("authentication_error".to_string()),
message: Some("Invalid bearer token".to_string()),
request_id: Some("req_varleg_001".to_string()),
request_id: Some("req_varleg_001".into()),
body: String::new(),
retryable: false,
suggested_action: None,
@@ -1811,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}"
);
}
}
+124 -17
View File
@@ -773,12 +773,14 @@ fn env_or_dotenv_present(key: &str) -> bool {
}
}
/// Produce a hint string describing the first foreign provider credential
/// that is present in the environment when Anthropic auth resolution has
/// just failed. Returns `None` when no foreign credential is set, in which
/// case the caller should fall back to the plain `missing_credentials`
/// error without a hint.
/// Produce a hint string describing the most probable reason Anthropic auth
/// resolution just failed. Returns `None` when nothing in the environment
/// explains the failure, in which case the caller should fall back to the
/// plain `missing_credentials` error without a hint.
pub(crate) fn anthropic_missing_credentials_hint() -> Option<String> {
if let Some(hint) = custom_anthropic_base_url_hint() {
return Some(hint);
}
for (env_var, provider_label, fix_hint) in FOREIGN_PROVIDER_ENV_VARS {
if env_or_dotenv_present(env_var) {
return Some(format!(
@@ -789,6 +791,34 @@ pub(crate) fn anthropic_missing_credentials_hint() -> Option<String> {
None
}
/// Hint for the case where `ANTHROPIC_BASE_URL` points at something other than
/// the Anthropic API.
///
/// Third-party Anthropic-compatible endpoints (DeepSeek's `/anthropic` path,
/// corporate gateways, local proxies) authenticate with the `ANTHROPIC_API_KEY`
/// and `ANTHROPIC_AUTH_TOKEN` variable names purely by wire-compatibility
/// convention, so the standard missing-credential message reads as "go get an
/// Anthropic key" when the user in fact needs a credential issued by the
/// endpoint they already configured. Nothing in that message mentions the base
/// URL, which is the one piece of configuration the user deliberately set.
///
/// This takes precedence over the foreign-provider hints: a configured endpoint
/// is a fact about what the user asked for, while a presence check on another
/// provider's key only guesses at intent.
fn custom_anthropic_base_url_hint() -> Option<String> {
let base_url = anthropic::read_base_url();
let base_url = base_url.trim();
if base_url.is_empty() || base_url == anthropic::DEFAULT_BASE_URL {
return None;
}
Some(format!(
"ANTHROPIC_BASE_URL is set to {base_url}, which is not the Anthropic API. \
The ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN variable names are a \
compatibility convention — this endpoint expects a credential it issued \
itself, not an Anthropic key."
))
}
/// Build an Anthropic-specific `MissingCredentials` error, attaching a
/// hint suggesting the probable fix whenever a different provider's
/// credentials are already present in the environment. Anthropic call
@@ -861,8 +891,8 @@ pub(crate) fn dotenv_value(key: &str) -> Option<String> {
#[cfg(test)]
mod tests {
use crate::test_env_lock as env_lock;
use std::ffi::OsString;
use std::sync::{Mutex, OnceLock};
use serde_json::json;
@@ -880,17 +910,6 @@ mod tests {
ProviderKind, ProviderWireProtocol,
};
/// Serializes every test in this module that mutates process-wide
/// environment variables so concurrent test threads cannot observe
/// each other's partially-applied state while probing the foreign
/// provider credential sniffer.
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Snapshot-restore guard for a single environment variable. Captures
/// the original value on construction, applies the requested override
/// (set or remove), and restores the original on drop so tests leave
@@ -1688,6 +1707,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", None);
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let hint = anthropic_missing_credentials_hint();
@@ -1699,6 +1719,86 @@ NO_EQUALS_LINE
);
}
#[test]
fn anthropic_missing_credentials_hint_names_a_custom_base_url() {
// given
let _lock = env_lock();
let _openai = EnvVarGuard::set("OPENAI_API_KEY", None);
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set(
"ANTHROPIC_BASE_URL",
Some("https://api.deepseek.com/anthropic"),
);
// when
let hint = anthropic_missing_credentials_hint()
.expect("a configured non-Anthropic endpoint should produce a hint");
// then
assert!(
hint.contains("https://api.deepseek.com/anthropic"),
"hint should name the configured endpoint so the user recognizes their own setting: {hint}"
);
assert!(
hint.contains("not the Anthropic API"),
"hint should state that the endpoint is not Anthropic: {hint}"
);
assert!(
hint.contains("ANTHROPIC_API_KEY") && hint.contains("ANTHROPIC_AUTH_TOKEN"),
"hint should keep naming the env vars that carry the credential: {hint}"
);
}
#[test]
fn anthropic_missing_credentials_hint_prefers_custom_base_url_over_foreign_creds() {
// given
let _lock = env_lock();
let _openai = EnvVarGuard::set("OPENAI_API_KEY", Some("sk-openrouter-varleg"));
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set(
"ANTHROPIC_BASE_URL",
Some("https://api.deepseek.com/anthropic"),
);
// when
let hint = anthropic_missing_credentials_hint()
.expect("a configured non-Anthropic endpoint should produce a hint");
// then
assert!(
hint.contains("ANTHROPIC_BASE_URL"),
"the endpoint the user configured is a fact and should win over a guess about intent: {hint}"
);
assert!(
!hint.contains("openai/"),
"the foreign-provider routing hint should not displace the base-url hint: {hint}"
);
}
#[test]
fn anthropic_missing_credentials_hint_is_none_for_the_default_base_url() {
// given
let _lock = env_lock();
let _openai = EnvVarGuard::set("OPENAI_API_KEY", None);
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set(
"ANTHROPIC_BASE_URL",
Some(super::anthropic::DEFAULT_BASE_URL),
);
// when
let hint = anthropic_missing_credentials_hint();
// then
assert!(
hint.is_none(),
"pointing at the real Anthropic API should not produce a base-url hint, got {hint:?}"
);
}
#[test]
fn anthropic_missing_credentials_hint_detects_openai_api_key_and_recommends_openai_prefix() {
// given
@@ -1706,6 +1806,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", Some("sk-openrouter-varleg"));
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let hint = anthropic_missing_credentials_hint()
@@ -1737,6 +1838,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", None);
let _xai = EnvVarGuard::set("XAI_API_KEY", Some("xai-test-key"));
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let hint = anthropic_missing_credentials_hint()
@@ -1764,6 +1866,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", None);
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", Some("sk-dashscope-test"));
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let hint = anthropic_missing_credentials_hint()
@@ -1791,6 +1894,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", Some("sk-openrouter-varleg"));
let _xai = EnvVarGuard::set("XAI_API_KEY", Some("xai-test-key"));
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", Some("sk-dashscope-test"));
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let hint = anthropic_missing_credentials_hint()
@@ -1814,6 +1918,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", None);
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let error = anthropic_missing_credentials();
@@ -1848,6 +1953,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", Some("sk-openrouter-varleg"));
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let error = anthropic_missing_credentials();
@@ -1896,6 +2002,7 @@ NO_EQUALS_LINE
let _openai = EnvVarGuard::set("OPENAI_API_KEY", Some(""));
let _xai = EnvVarGuard::set("XAI_API_KEY", None);
let _dashscope = EnvVarGuard::set("DASHSCOPE_API_KEY", None);
let _base_url = EnvVarGuard::set("ANTHROPIC_BASE_URL", None);
// when
let hint = anthropic_missing_credentials_hint();
+196 -34
View File
@@ -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,
@@ -261,7 +274,7 @@ impl OpenAiCompatClient {
.and_then(|t| t.as_str())
.map(str::to_owned),
message: Some(msg),
request_id,
request_id: request_id.map(String::into_boxed_str),
body,
retryable: false,
suggested_action: suggested_action_for_status(
@@ -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> {
@@ -1653,7 +1673,7 @@ fn parse_sse_frame(
request_id: None,
body: trimmed.chars().take(200).collect(),
retryable: false,
suggested_action: Some("verify the API endpoint URL is correct".to_string()),
suggested_action: Some("verify the API endpoint URL is correct"),
retry_after: None,
});
}
@@ -1706,7 +1726,7 @@ fn parse_sse_frame(
request_id: None,
body: payload.chars().take(200).collect(),
retryable: false,
suggested_action: Some("verify the API endpoint URL is correct".to_string()),
suggested_action: Some("verify the API endpoint URL is correct"),
retry_after: None,
});
}
@@ -1760,11 +1780,11 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
}
let headers = response.headers().clone();
let request_id = request_id_from_headers(&headers);
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 retry_after = parse_retry_after(&headers, 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
@@ -1819,14 +1842,14 @@ fn is_retryable_400(status: reqwest::StatusCode, body: &str) -> bool {
/// Generate a suggested user action based on the HTTP status code and error context.
/// This provides actionable guidance when API requests fail.
fn suggested_action_for_status(status: reqwest::StatusCode) -> Option<String> {
fn suggested_action_for_status(status: reqwest::StatusCode) -> Option<&'static str> {
match status.as_u16() {
401 => Some("Check API key is set correctly and has not expired".to_string()),
403 => Some("Verify API key has required permissions for this operation".to_string()),
413 => Some("Reduce prompt size or context window before retrying".to_string()),
429 => Some("Wait a moment before retrying; consider reducing request rate".to_string()),
500 => Some("Provider server error - retry after a brief wait".to_string()),
502..=504 => Some("Provider gateway error - retry after a brief wait".to_string()),
401 => Some("Check API key is set correctly and has not expired"),
403 => Some("Verify API key has required permissions for this operation"),
413 => Some("Reduce prompt size or context window before retrying"),
429 => Some("Wait a moment before retrying; consider reducing request rate"),
500 => Some("Provider server error - retry after a brief wait"),
502..=504 => Some("Provider gateway error - retry after a brief wait"),
_ => None,
}
}
@@ -1858,11 +1881,13 @@ 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,
InputContentBlock, InputMessage, MessageRequest, OutputContentBlock, StreamEvent,
@@ -1871,7 +1896,97 @@ mod tests {
use serde_json::json;
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::sync::{Mutex, OnceLock};
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() {
@@ -2371,13 +2486,6 @@ mod tests {
}
}
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
.lock()
.expect("env lock")
}
#[test]
fn normalizes_stop_reasons() {
assert_eq!(normalize_finish_reason("stop"), "end_turn");
@@ -3055,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}"
);
}
}
+5 -3
View File
@@ -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),
)
@@ -320,7 +322,7 @@ mod tests {
};
let cost = response.usage.estimated_cost_usd(&response.model);
assert_eq!(format_usd(cost.total_cost_usd()), "$54.6750");
assert_eq!(format_usd(cost.total_cost_usd()), "$10.9350");
assert_eq!(response.total_tokens(), 1_800_000);
}
+4 -4
View File
@@ -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.6")
Some("claude-code/0.1.15")
);
assert_eq!(
request.headers.get("anthropic-beta").map(String::as_str),
@@ -208,7 +208,7 @@ async fn send_message_applies_request_profile_and_records_telemetry() {
"\"model\":\"claude-3-7-sonnet-latest\",",
"\"stop_reason\":\"end_turn\",",
"\"stop_sequence\":null,",
"\"usage\":{\"input_tokens\":1,\"cache_creation_input_tokens\":2,\"cache_read_input_tokens\":3,\"output_tokens\":1}",
"\"usage\":{\"input_tokens\":100,\"cache_creation_input_tokens\":200,\"cache_read_input_tokens\":300,\"output_tokens\":100}",
"}"
),
&[("request-id", "req_profile_123")],
@@ -283,8 +283,8 @@ async fn send_message_applies_request_profile_and_records_telemetry() {
if event.namespace == "api"
&& event.action == "message_usage"
&& event.properties.get("request_id") == Some(&json!("req_profile_123"))
&& event.properties.get("total_tokens") == Some(&json!(7))
&& event.properties.get("estimated_cost_usd") == Some(&json!("$0.0001"))
&& event.properties.get("total_tokens") == Some(&json!(700))
&& event.properties.get("estimated_cost_usd") == Some(&json!("$0.0026"))
));
assert!(matches!(
&events[5],
+22 -8
View File
@@ -39,12 +39,13 @@ impl Drop for EnvVarGuard {
fn proxy_config_from_env_reads_uppercase_proxy_vars() {
// given
let _lock = env_lock();
let _http = EnvVarGuard::set("HTTP_PROXY", Some("http://proxy.corp:3128"));
let _https = EnvVarGuard::set("HTTPS_PROXY", Some("http://secure.corp:3129"));
let _no = EnvVarGuard::set("NO_PROXY", Some("localhost,127.0.0.1"));
// Clear aliases before setting values: environment keys are case-insensitive on Windows.
let _http_lower = EnvVarGuard::set("http_proxy", None);
let _https_lower = EnvVarGuard::set("https_proxy", None);
let _no_lower = EnvVarGuard::set("no_proxy", None);
let _http = EnvVarGuard::set("HTTP_PROXY", Some("http://proxy.corp:3128"));
let _https = EnvVarGuard::set("HTTPS_PROXY", Some("http://secure.corp:3129"));
let _no = EnvVarGuard::set("NO_PROXY", Some("localhost,127.0.0.1"));
// when
let config = ProxyConfig::from_env();
@@ -127,13 +128,19 @@ fn proxy_config_from_env_treats_empty_values_as_unset() {
fn build_client_with_env_proxy_config_succeeds() {
// given
let _lock = env_lock();
let _http = EnvVarGuard::set("HTTP_PROXY", Some("http://proxy.corp:3128"));
let _https = EnvVarGuard::set("HTTPS_PROXY", Some("http://secure.corp:3129"));
let _no = EnvVarGuard::set("NO_PROXY", Some("localhost"));
// Clear aliases before setting values: environment keys are case-insensitive on Windows.
let _http_lower = EnvVarGuard::set("http_proxy", None);
let _https_lower = EnvVarGuard::set("https_proxy", None);
let _no_lower = EnvVarGuard::set("no_proxy", None);
let _http = EnvVarGuard::set("HTTP_PROXY", Some("http://proxy.corp:3128"));
let _https = EnvVarGuard::set("HTTPS_PROXY", Some("http://secure.corp:3129"));
let _no = EnvVarGuard::set("NO_PROXY", Some("localhost"));
let config = ProxyConfig::from_env();
assert_eq!(config.http_proxy.as_deref(), Some("http://proxy.corp:3128"));
assert_eq!(
config.https_proxy.as_deref(),
Some("http://secure.corp:3129")
);
// when
let result = build_http_client_with(&config);
@@ -155,7 +162,7 @@ fn build_client_with_proxy_url_config_succeeds() {
}
#[test]
fn proxy_config_from_env_prefers_uppercase_over_lowercase() {
fn proxy_config_from_env_respects_platform_case_semantics() {
// given
let _lock = env_lock();
let _http_upper = EnvVarGuard::set("HTTP_PROXY", Some("http://upper.corp:3128"));
@@ -169,5 +176,12 @@ fn proxy_config_from_env_prefers_uppercase_over_lowercase() {
let config = ProxyConfig::from_env();
// then
assert_eq!(config.http_proxy.as_deref(), Some("http://upper.corp:3128"));
// Unix retains two keys and prefers uppercase. On Windows the second
// assignment replaces the same environment entry, regardless of casing.
let expected = if cfg!(windows) {
"http://lower.corp:3128"
} else {
"http://upper.corp:3128"
};
assert_eq!(config.http_proxy.as_deref(), Some(expected));
}
+2 -2
View File
@@ -166,8 +166,8 @@ pub fn blob_to_f32_vec(blob: &[u8], dim: usize) -> Option<Vec<f32>> {
return None;
}
let mut v = Vec::with_capacity(dim);
for chunk in blob.chunks_exact(4) {
v.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
for chunk in blob.as_chunks::<4>().0 {
v.push(f32::from_le_bytes(*chunk));
}
Some(v)
}
+1 -1
View File
@@ -66,7 +66,7 @@ async fn flush_path_batch(
#[cfg(feature = "qdrant-index")]
let mut qdrant_points: Vec<ChunkPoint> = Vec::with_capacity(batch.len());
for ((ord, t), vec) in batch.drain(..).zip(vecs.into_iter()) {
for ((ord, t), vec) in batch.drain(..).zip(vecs) {
let dim = vec.len();
let cid = insert_chunk(conn, path, ord, &t)?;
insert_embedding(conn, cid, dim, &vec)?;
+2 -2
View File
@@ -7328,8 +7328,8 @@ mod tests {
.find(|r| r.origin == SkillOrigin::Bundled)
.expect("should have bundled skills root");
let loaded_skills =
load_skills_from_roots(&[bundled_root.clone()]).expect("should load bundled skills");
let loaded_skills = load_skills_from_roots(std::slice::from_ref(bundled_root))
.expect("should load bundled skills");
assert!(
!loaded_skills.is_empty() || bundled_root.path.exists(),
+64 -31
View File
@@ -281,8 +281,18 @@ fn format_hook_warning(command: &str, code: i32, stdout: Option<&str>, stderr: &
fn shell_command(command: &str) -> CommandWithStdin {
#[cfg(windows)]
let command_builder = {
use std::os::windows::process::CommandExt;
// This is a configured shell command, not a single argv value. cmd
// does not understand the C-runtime backslash escaping used by arg().
let command = if Path::new(command).is_file() {
format!("\"{command}\"")
} else {
command.to_string()
};
let mut command_builder = Command::new("cmd");
command_builder.arg("/C").arg(command);
command_builder.args(["/D", "/S", "/C"]);
command_builder.raw_arg(format!("\"{command}\""));
CommandWithStdin::new(command_builder)
};
@@ -380,6 +390,14 @@ mod tests {
std::env::temp_dir().join(format!("plugins-hook-runner-{label}-{nanos}"))
}
fn plugin_hook(message: &str, code: i32) -> String {
if cfg!(windows) {
format!("echo {message}& exit /b {code}")
} else {
format!("printf '%s' '{message}'; exit {code}")
}
}
fn make_executable(path: &Path) {
#[cfg(unix)]
{
@@ -402,34 +420,34 @@ mod tests {
fs::create_dir_all(root.join(".claude-plugin")).expect("manifest dir");
fs::create_dir_all(root.join("hooks")).expect("hooks dir");
let pre_path = root.join("hooks").join("pre.sh");
fs::write(
&pre_path,
format!("#!/bin/sh\nprintf '%s\\n' '{pre_message}'\n"),
)
.expect("write pre hook");
make_executable(&pre_path);
let post_path = root.join("hooks").join("post.sh");
fs::write(
&post_path,
format!("#!/bin/sh\nprintf '%s\\n' '{post_message}'\n"),
)
.expect("write post hook");
make_executable(&post_path);
let failure_path = root.join("hooks").join("failure.sh");
fs::write(
&failure_path,
format!("#!/bin/sh\nprintf '%s\\n' '{failure_message}'\n"),
)
.expect("write failure hook");
make_executable(&failure_path);
let extension = if cfg!(windows) { "cmd" } else { "sh" };
for (phase, message) in [
("pre", pre_message),
("post", post_message),
("failure", failure_message),
] {
let path = root.join("hooks").join(format!("{phase}.{extension}"));
let script = if cfg!(windows) {
format!("@echo off\r\necho {message}\r\n")
} else {
format!("#!/bin/sh\nprintf '%s\\n' '{message}'\n")
};
fs::write(&path, script).expect("write hook");
make_executable(&path);
}
fs::write(
root.join(".claude-plugin").join("plugin.json"),
format!(
"{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"hook plugin\",\n \"hooks\": {{\n \"PreToolUse\": [\"./hooks/pre.sh\"],\n \"PostToolUse\": [\"./hooks/post.sh\"],\n \"PostToolUseFailure\": [\"./hooks/failure.sh\"]\n }}\n}}"
),
serde_json::json!({
"name": name,
"version": "1.0.0",
"description": "hook plugin",
"hooks": {
"PreToolUse": [format!("./hooks/pre.{extension}")],
"PostToolUse": [format!("./hooks/post.{extension}")],
"PostToolUseFailure": [format!("./hooks/failure.{extension}")]
}
})
.to_string(),
)
.expect("write plugin manifest");
}
@@ -438,7 +456,7 @@ mod tests {
fn collects_and_runs_hooks_from_enabled_plugins() {
// given
let config_home = temp_dir("config");
let first_source_root = temp_dir("source-a");
let first_source_root = temp_dir("source a");
let second_source_root = temp_dir("source-b");
write_hook_plugin(
&first_source_root,
@@ -499,7 +517,7 @@ mod tests {
fn pre_tool_use_denies_when_plugin_hook_exits_two() {
// given
let runner = HookRunner::new(crate::PluginHooks {
pre_tool_use: vec!["printf 'blocked by plugin'; exit 2".to_string()],
pre_tool_use: vec![plugin_hook("blocked by plugin", 2)],
post_tool_use: Vec::new(),
post_tool_use_failure: Vec::new(),
});
@@ -512,13 +530,28 @@ mod tests {
assert_eq!(result.messages(), &["blocked by plugin".to_string()]);
}
#[test]
fn preserves_quoted_arguments_in_plugin_hooks() {
let python = if cfg!(windows) { "python" } else { "python3" };
let runner = HookRunner::new(crate::PluginHooks {
pre_tool_use: vec![format!(
"{python} -c \"import sys; sys.stdout.write('quoted plugin hook'); sys.exit(2)\""
)],
post_tool_use: Vec::new(),
post_tool_use_failure: Vec::new(),
});
let result = runner.run_pre_tool_use("Read", r#"{"path":"README.md"}"#);
assert!(result.is_denied(), "{result:?}");
assert_eq!(result.messages(), &["quoted plugin hook".to_string()]);
}
#[test]
fn propagates_plugin_hook_failures() {
// given
let runner = HookRunner::new(crate::PluginHooks {
pre_tool_use: vec![
"printf 'broken plugin hook'; exit 1".to_string(),
"printf 'later plugin hook'".to_string(),
plugin_hook("broken plugin hook", 1),
plugin_hook("later plugin hook", 0),
],
post_tool_use: Vec::new(),
post_tool_use_failure: Vec::new(),
+49 -24
View File
@@ -2502,20 +2502,42 @@ mod tests {
fn write_lifecycle_plugin(root: &Path, name: &str, version: &str) -> PathBuf {
let log_path = root.join("lifecycle.log");
let extension = if cfg!(windows) { "cmd" } else { "sh" };
let (init_script, shutdown_script) = if cfg!(windows) {
(
"@echo off\r\necho init>>lifecycle.log\r\n",
"@echo off\r\necho shutdown>>lifecycle.log\r\n",
)
} else {
(
"#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
"#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
)
};
write_file(
root.join("lifecycle").join("init.sh").as_path(),
"#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
root.join("lifecycle")
.join(format!("init.{extension}"))
.as_path(),
init_script,
);
write_file(
root.join("lifecycle").join("shutdown.sh").as_path(),
"#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
root.join("lifecycle")
.join(format!("shutdown.{extension}"))
.as_path(),
shutdown_script,
);
write_file(
root.join(MANIFEST_RELATIVE_PATH).as_path(),
format!(
"{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"lifecycle plugin\",\n \"lifecycle\": {{\n \"Init\": [\"./lifecycle/init.sh\"],\n \"Shutdown\": [\"./lifecycle/shutdown.sh\"]\n }}\n}}"
)
.as_str(),
&serde_json::json!({
"name": name,
"version": version,
"description": "lifecycle plugin",
"lifecycle": {
"Init": [format!("./lifecycle/init.{extension}")],
"Shutdown": [format!("./lifecycle/shutdown.{extension}")]
}
})
.to_string(),
);
log_path
}
@@ -2525,25 +2547,28 @@ mod tests {
}
fn write_tool_plugin_with_name(root: &Path, name: &str, version: &str, tool_name: &str) {
let script_path = root.join("tools").join("echo-json.sh");
let script_path = root.join("tools").join("echo-json.py");
write_file(
&script_path,
"#!/bin/sh\nINPUT=$(cat)\nprintf '{\"plugin\":\"%s\",\"tool\":\"%s\",\"input\":%s}\\n' \"$CLAWD_PLUGIN_ID\" \"$CLAWD_TOOL_NAME\" \"$INPUT\"\n",
r#"import json, os, sys
print(json.dumps({"plugin": os.environ["CLAWD_PLUGIN_ID"], "tool": os.environ["CLAWD_TOOL_NAME"], "input": json.load(sys.stdin)}))
"#,
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("chmod");
}
write_file(
root.join(MANIFEST_RELATIVE_PATH).as_path(),
format!(
"{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"tool plugin\",\n \"tools\": [\n {{\n \"name\": \"{tool_name}\",\n \"description\": \"Echo JSON input\",\n \"inputSchema\": {{\"type\": \"object\", \"properties\": {{\"message\": {{\"type\": \"string\"}}}}, \"required\": [\"message\"], \"additionalProperties\": false}},\n \"command\": \"./tools/echo-json.sh\",\n \"requiredPermission\": \"workspace-write\"\n }}\n ]\n}}"
)
.as_str(),
&serde_json::json!({
"name": name,
"version": version,
"description": "tool plugin",
"tools": [{
"name": tool_name,
"description": "Echo JSON input",
"inputSchema": {"type": "object", "properties": {"message": {"type": "string"}}, "required": ["message"], "additionalProperties": false},
"command": if cfg!(windows) { "python" } else { "python3" },
"args": ["tools/echo-json.py"],
"requiredPermission": "workspace-write"
}]
}).to_string(),
);
}
@@ -3623,7 +3648,7 @@ mod tests {
registry.shutdown().expect("shutdown should succeed");
let log = fs::read_to_string(&log_path).expect("lifecycle log should exist");
assert_eq!(log, "init\nshutdown\n");
assert_eq!(log.replace("\r\n", "\n"), "init\nshutdown\n");
let _ = fs::remove_dir_all(config_home);
let _ = fs::remove_dir_all(source_root);
@@ -3820,7 +3845,7 @@ mod tests {
if registry.initialize().is_ok() && registry.shutdown().is_ok() {
// Verify lifecycle.log exists and has expected content
if let Ok(log) = fs::read_to_string(&log_path) {
if log == "init\nshutdown\n" {
if log.replace("\r\n", "\n") == "init\nshutdown\n" {
success_count.fetch_add(1, AtomicOrdering::Relaxed);
}
}
+2
View File
@@ -7,11 +7,13 @@ publish.workspace = true
[dependencies]
sha2 = "0.10"
getrandom = "0.2"
glob = "0.3"
plugins = { path = "../plugins" }
regex = "1"
serde = { version = "1", features = ["derive"] }
serde_json.workspace = true
same-file = "1.0.6"
telemetry = { path = "../telemetry" }
tokio = { version = "1", features = ["io-std", "io-util", "macros", "process", "rt", "rt-multi-thread", "time"] }
walkdir = "2"
+45 -6
View File
@@ -293,6 +293,41 @@ fn sandbox_status_for_input(input: &BashCommandInput, cwd: &std::path::Path) ->
resolve_sandbox_status_for_request(&request, cwd)
}
// Git for Windows normally adds Git/cmd, but not Git/bin, to PATH.
// Prefer a native shell there rather than the Windows WSL bash launcher.
fn posix_shell() -> std::path::PathBuf {
#[cfg(windows)]
{
if let Some(path) = env::var_os("PATH") {
for directory in env::split_paths(&path) {
let shell = directory.join("sh.exe");
if shell.is_file() {
return shell;
}
if directory.join("git.exe").is_file() {
if let Some(root) = directory.parent() {
let shell = root.join("bin").join("sh.exe");
if shell.is_file() {
return shell;
}
}
}
}
}
for variable in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
if let Some(root) = env::var_os(variable) {
for relative in ["Git/bin/sh.exe", "Programs/Git/bin/sh.exe"] {
let shell = std::path::PathBuf::from(&root).join(relative);
if shell.is_file() {
return shell;
}
}
}
}
}
std::path::PathBuf::from("sh")
}
fn prepare_command(
command: &str,
cwd: &std::path::Path,
@@ -311,7 +346,7 @@ fn prepare_command(
return prepared;
}
let mut prepared = Command::new("sh");
let mut prepared = Command::new(posix_shell());
prepared.arg("-lc").arg(command).current_dir(cwd);
if sandbox_status.filesystem_active {
prepared.env("HOME", cwd.join(".sandbox-home"));
@@ -337,7 +372,7 @@ fn prepare_tokio_command(
cmd.envs(launcher.env);
cmd
} else {
let mut cmd = TokioCommand::new("sh");
let mut cmd = TokioCommand::new(posix_shell());
cmd.arg("-lc").arg(command);
if sandbox_status.filesystem_active {
cmd.env("HOME", cwd.join(".sandbox-home"));
@@ -365,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),
@@ -376,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());
}
@@ -385,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),
@@ -428,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),
+1 -1
View File
@@ -826,7 +826,7 @@ mod tests {
"message[{}] is a ToolResult but message[{}] has no ToolUse: {:?}",
i,
i - 1,
&messages[i - 1].blocks
messages[i - 1].blocks
);
}
}
+2 -2
View File
@@ -2817,12 +2817,12 @@ mod tests {
let command = format!("echo compromised >> {}", marker.display());
fs::write(
&project_legacy_settings,
format!(r#"{{"hooks":{{"PreToolUse":["{command}"]}}}}"#),
serde_json::json!({"hooks": {"PreToolUse": [command]}}).to_string(),
)
.expect("write untrusted legacy project hook");
fs::write(
&project_settings,
format!(r#"{{"hooks":{{"PreToolUse":["{command}"]}}}}"#),
serde_json::json!({"hooks": {"PreToolUse": [command]}}).to_string(),
)
.expect("write untrusted project hook");
+9 -19
View File
@@ -1705,9 +1705,9 @@ mod tests {
));
let hook_command = format!("echo compromised >> \"{}\"", marker.display());
let features = RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
vec![shell_snippet(&hook_command)],
vec![shell_snippet(&hook_command)],
vec![shell_snippet(&hook_command)],
vec![hook_command.clone()],
vec![hook_command.clone()],
vec![hook_command.clone()],
));
let mut runtime = ConversationRuntime::new_with_features(
Session::new(),
@@ -1858,7 +1858,7 @@ mod tests {
PermissionPolicy::new(PermissionMode::DangerFullAccess),
vec!["system".to_string()],
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
vec![crate::test_hook("blocked by hook", "", 2, 0)],
Vec::new(),
Vec::new(),
)),
@@ -1921,7 +1921,7 @@ mod tests {
PermissionPolicy::new(PermissionMode::DangerFullAccess),
vec!["system".to_string()],
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
vec![shell_snippet("printf 'broken hook'; exit 1")],
vec![crate::test_hook("broken hook", "", 1, 0)],
Vec::new(),
Vec::new(),
)),
@@ -1990,8 +1990,8 @@ mod tests {
PermissionPolicy::new(PermissionMode::DangerFullAccess),
vec!["system".to_string()],
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
vec![shell_snippet("printf 'pre hook ran'")],
vec![shell_snippet("printf 'post hook ran'")],
vec![crate::test_hook("pre hook ran", "", 0, 0)],
vec![crate::test_hook("post hook ran", "", 0, 0)],
Vec::new(),
)),
);
@@ -2068,8 +2068,8 @@ mod tests {
vec!["system".to_string()],
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
Vec::new(),
vec![shell_snippet("printf 'post hook should not run'")],
vec![shell_snippet("printf 'failure hook ran'")],
vec![crate::test_hook("post hook should not run", "", 0, 0)],
vec![crate::test_hook("failure hook ran", "", 0, 0)],
)),
);
@@ -2263,16 +2263,6 @@ mod tests {
std::env::temp_dir().join(format!("runtime-conversation-{label}-{nanos}.json"))
}
#[cfg(windows)]
fn shell_snippet(script: &str) -> String {
script.replace('\'', "\"")
}
#[cfg(not(windows))]
fn shell_snippet(script: &str) -> String {
script.to_string()
}
#[test]
fn auto_compacts_when_cumulative_input_threshold_is_crossed() {
struct SimpleApi;
+312 -30
View File
@@ -2,7 +2,7 @@ use std::cmp::Reverse;
use std::collections::HashSet;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::path::{Component, Path, PathBuf};
use std::time::Instant;
use glob::Pattern;
@@ -44,7 +44,7 @@ fn is_binary_file(path: &Path) -> io::Result<bool> {
fn validate_workspace_boundary(resolved: &Path, workspace_root: &Path) -> io::Result<()> {
let workspace_root = normalize_for_comparison(workspace_root);
let comparable = normalize_for_comparison(resolved);
if comparable.starts_with(&workspace_root) || resolves_within(resolved, &workspace_root) {
if resolves_within(resolved, &workspace_root) {
return Ok(());
}
Err(io::Error::new(
@@ -61,13 +61,87 @@ fn validate_workspace_boundary(resolved: &Path, workspace_root: &Path) -> io::Re
/// filesystem resolves it. Windows accepts several spellings of one location
/// that [`Path::starts_with`] treats as different: letter case (a working
/// directory typed as `c:\users\...` for `C:\Users\...`), the `\\.\` device
/// namespace, and 8.3 short names. Only consulted after the lexical comparison
/// fails, so it can accept such a spelling but never widens what already
/// compared inside, and a path whose canonical form is outside stays rejected.
/// namespace, and 8.3 short names. Existing ancestors are canonicalized so
/// equivalent names are accepted while symlink and parent traversal escapes
/// remain outside the workspace.
fn resolves_within(resolved: &Path, workspace_root: &Path) -> bool {
resolved
.canonicalize()
.is_ok_and(|canonical| normalize_for_comparison(&canonical).starts_with(workspace_root))
if let Ok(canonical) = resolved.canonicalize() {
if normalize_for_comparison(&canonical).starts_with(workspace_root) {
return true;
}
}
// Writes can target a path whose parent directories do not exist yet, so
// canonicalizing the whole path may not be possible. Resolve the nearest
// existing ancestor (including symlinks), then check its canonical path
// and file identity before applying only the missing suffix.
let mut existing_ancestor = resolved;
loop {
match fs::symlink_metadata(existing_ancestor) {
Ok(_) => break,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let Some(parent) = existing_ancestor.parent() else {
return false;
};
existing_ancestor = parent;
}
Err(_) => return false,
}
}
let Ok(canonical_ancestor) = existing_ancestor.canonicalize() else {
// In particular, do not treat a dangling symlink as a missing path.
return false;
};
#[cfg(windows)]
if has_workspace_ancestor(&canonical_ancestor, workspace_root) {
return resolved
.strip_prefix(existing_ancestor)
.is_ok_and(|suffix| {
suffix.components().all(|component| {
!matches!(
component,
Component::ParentDir | Component::Prefix(_) | Component::RootDir
)
})
});
}
let Ok(missing_suffix) = resolved.strip_prefix(existing_ancestor) else {
return false;
};
let mut canonical_path = normalize_for_comparison(&canonical_ancestor);
for component in missing_suffix.components() {
match component {
Component::CurDir => {}
// A parent component after a missing component could later
// traverse a symlink once the missing directory is created.
Component::ParentDir => return false,
Component::Normal(name) => canonical_path.push(name),
Component::Prefix(_) | Component::RootDir => return false,
}
}
canonical_path.starts_with(workspace_root)
}
/// Compare Windows directory identities when canonical paths use different
/// long/8.3 spellings. Path strings alone cannot establish this relationship.
#[cfg(windows)]
fn has_workspace_ancestor(path: &Path, workspace_root: &Path) -> bool {
let mut ancestor = path;
loop {
if same_file::is_same_file(ancestor, workspace_root).unwrap_or(false) {
return true;
}
let Some(parent) = ancestor.parent() else {
return false;
};
if parent == ancestor {
return false;
}
ancestor = parent;
}
}
/// Text payload returned by file-reading operations.
@@ -368,12 +442,10 @@ fn extract_merge_conflicts(lines: &[&str]) -> Vec<ConflictBlock> {
}
// Check for separator
if current.trim() == SEPARATOR {
if separator_line.is_none() {
separator_line = Some(j + 1);
j += 1;
continue;
}
if current.trim() == SEPARATOR && separator_line.is_none() {
separator_line = Some(j + 1);
j += 1;
continue;
}
// Check for end marker
@@ -419,13 +491,12 @@ fn extract_merge_conflicts(lines: &[&str]) -> Vec<ConflictBlock> {
/// Returns the label text (stripped of leading/trailing spaces) if the line matches the prefix,
/// or None otherwise.
fn extract_marker_label<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
if line.starts_with(prefix) {
let rest = &line[prefix.len()..];
if let Some(rest) = line.strip_prefix(prefix) {
// Accept either just the prefix or prefix + single space + label
if rest.is_empty() {
Some("")
} else if rest.starts_with(' ') {
Some(rest[1..].trim())
} else if let Some(label) = rest.strip_prefix(' ') {
Some(label.trim())
} else {
None
}
@@ -595,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",
@@ -609,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)?;
@@ -627,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)
@@ -652,6 +741,11 @@ fn glob_search_impl(
base_dir.join(pattern).to_string_lossy().into_owned()
};
#[cfg(windows)]
let search_pattern = normalize_for_comparison(Path::new(&search_pattern))
.to_string_lossy()
.replace('\\', "/");
// The `glob` crate does not support brace expansion ({a,b,c}).
// Expand braces into multiple patterns so patterns like
// `Assets/**/*.{cs,uxml,uss}` work correctly.
@@ -874,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()
@@ -913,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());
@@ -1126,14 +1228,15 @@ fn expand_braces(pattern: &str) -> Vec<String> {
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(any(unix, windows))]
use super::write_file_in_workspace;
use super::{
component_contains_glob, derive_glob_walk_root, edit_file, expand_braces, glob_search,
grep_search, is_symlink_escape, normalize_for_comparison, read_file,
read_file_in_workspace, write_file, write_file_in_workspace, GrepSearchInput,
MAX_WRITE_SIZE,
read_file_in_workspace, write_file, GrepSearchInput, MAX_WRITE_SIZE,
};
fn temp_path(name: &str) -> std::path::PathBuf {
@@ -1166,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");
@@ -1220,9 +1374,9 @@ mod tests {
let outside = temp_path("symlink-target.txt");
std::fs::write(&outside, "target content").expect("target should write");
let link_path = workspace.join("escape-link.txt");
#[cfg(unix)]
{
let link_path = workspace.join("escape-link.txt");
std::os::unix::fs::symlink(&outside, &link_path).expect("symlink should create");
assert!(is_symlink_escape(&link_path, &workspace).expect("check should succeed"));
}
@@ -1341,6 +1495,69 @@ mod tests {
let _ = std::fs::remove_dir_all(&workspace);
}
#[test]
#[cfg(windows)]
fn writes_inside_workspace_through_short_path_with_missing_nested_directories() {
let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") else {
return;
};
let long_temp = PathBuf::from(local_app_data).join("Temp");
let short_temp = std::env::temp_dir();
if !long_temp.is_dir()
|| !short_temp.is_dir()
|| long_temp == short_temp
|| !same_file::is_same_file(&long_temp, &short_temp).unwrap_or(false)
{
// Some Windows hosts disable short-name generation or configure
// TEMP outside the user's local application data directory.
return;
}
let unique = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("time should move forward")
.as_nanos();
let workspace = long_temp.join(format!("clawd-native-short-path-{unique}"));
std::fs::create_dir_all(&workspace).expect("workspace dir should be created");
let root = workspace
.canonicalize()
.expect("workspace should canonicalize");
let short_workspace = short_temp.join(
workspace
.file_name()
.expect("workspace should have a file name"),
);
let target = short_workspace.join("nested").join("demo.txt");
write_file_in_workspace(&target.to_string_lossy(), "safe content", &root)
.expect("an equivalent short path inside the workspace should be accepted");
assert_eq!(
std::fs::read_to_string(workspace.join("nested/demo.txt"))
.expect("written file should be readable"),
"safe content"
);
let update = write_file_in_workspace(&target.to_string_lossy(), "updated content", &root)
.expect("an existing file through an equivalent short path should be accepted");
assert_eq!(update.kind, "update");
assert_eq!(update.original_file.as_deref(), Some("safe content"));
assert_eq!(
std::fs::read_to_string(workspace.join("nested/demo.txt"))
.expect("updated file should be readable"),
"updated content"
);
let escaping_target = short_workspace
.join("not-created")
.join("..")
.join("..")
.join("escape.txt");
write_file_in_workspace(&escaping_target.to_string_lossy(), "must not escape", &root)
.expect_err("parent traversal from a missing path must stay outside the boundary");
let _ = std::fs::remove_dir_all(&workspace);
}
#[test]
#[cfg(unix)]
fn workspace_write_rejects_parent_symlink_escape_regression_3007_class() {
@@ -1371,6 +1588,21 @@ mod tests {
"write should not create through an escaping symlink"
);
let escaped_nested_child = link_dir.join("not-created").join("nested.txt");
let result = write_file_in_workspace(
escaped_nested_child.to_string_lossy().as_ref(),
"must not escape",
&workspace,
);
assert!(
result.is_err(),
"a missing descendant under an escaping symlink must be rejected"
);
assert!(
!outside.join("not-created").exists(),
"write should not create missing directories through an escaping symlink"
);
let _ = std::fs::remove_dir_all(&workspace);
let _ = std::fs::remove_dir_all(&outside);
}
@@ -1410,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"]);
@@ -1479,11 +1755,11 @@ mod tests {
assert!(result
.filenames
.iter()
.any(|path| path.ends_with("src/AGENTS.md")));
.any(|path| Path::new(path).ends_with("src/AGENTS.md")));
assert!(result
.filenames
.iter()
.any(|path| path.ends_with("docs/AGENTS.md")));
.any(|path| Path::new(path).ends_with("docs/AGENTS.md")));
assert!(!result
.filenames
.iter()
@@ -1491,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);
}
+44 -35
View File
@@ -742,8 +742,13 @@ fn format_hook_failure(command: &str, code: i32, stdout: Option<&str>, stderr: &
fn shell_command(command: &str) -> CommandWithStdin {
#[cfg(windows)]
let command_builder = {
use std::os::windows::process::CommandExt;
// This is a configured shell command, not a single argv value. cmd
// does not understand the C-runtime backslash escaping used by arg().
let mut command_builder = Command::new("cmd");
command_builder.arg("/C").arg(command);
command_builder.args(["/D", "/S", "/C"]);
command_builder.raw_arg(format!("\"{command}\""));
CommandWithStdin::new(command_builder)
};
@@ -845,7 +850,7 @@ mod tests {
#[test]
fn allows_exit_code_zero_and_captures_stdout() {
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![shell_snippet("printf 'pre ok'")],
vec![crate::test_hook("pre ok", "", 0, 0)],
Vec::new(),
Vec::new(),
));
@@ -859,13 +864,13 @@ mod tests {
fn object_style_hook_matchers_filter_runtime_execution() {
let runner = HookRunner::new(RuntimeHookConfig::from_hook_commands(
vec![
RuntimeHookCommand::new(shell_snippet("printf 'legacy'")),
RuntimeHookCommand::new(crate::test_hook("legacy", "", 0, 0)),
RuntimeHookCommand::with_matcher(
shell_snippet("printf 'bash only'"),
crate::test_hook("bash only", "", 0, 0),
Some("Bash".to_string()),
),
RuntimeHookCommand::with_matcher(
shell_snippet("printf 'read only'"),
crate::test_hook("read only", "", 0, 0),
Some("Read*".to_string()),
),
],
@@ -889,7 +894,7 @@ mod tests {
#[test]
fn denies_exit_code_two() {
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
vec![crate::test_hook("blocked by hook", "", 2, 0)],
Vec::new(),
Vec::new(),
));
@@ -904,7 +909,7 @@ mod tests {
fn propagates_other_non_zero_statuses_as_failures() {
let runner = HookRunner::from_feature_config(&RuntimeFeatureConfig::default().with_hooks(
RuntimeHookConfig::new(
vec![shell_snippet("printf 'warning hook'; exit 1")],
vec![crate::test_hook("warning hook", "", 1, 0)],
Vec::new(),
Vec::new(),
),
@@ -925,8 +930,11 @@ mod tests {
#[test]
fn parses_pre_hook_permission_override_and_updated_input() {
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![shell_snippet(
r#"printf '%s' '{"systemMessage":"updated","hookSpecificOutput":{"permissionDecision":"allow","permissionDecisionReason":"hook ok","updatedInput":{"command":"git status"}}}'"#,
vec![crate::test_hook(
r#"{"systemMessage":"updated","hookSpecificOutput":{"permissionDecision":"allow","permissionDecisionReason":"hook ok","updatedInput":{"command":"git status"}}}"#,
"",
0,
0,
)],
Vec::new(),
Vec::new(),
@@ -949,7 +957,7 @@ mod tests {
let runner = HookRunner::new(RuntimeHookConfig::new(
Vec::new(),
Vec::new(),
vec![shell_snippet("printf 'failure hook ran'")],
vec![crate::test_hook("failure hook ran", "", 0, 0)],
));
// when
@@ -968,8 +976,8 @@ mod tests {
Vec::new(),
Vec::new(),
vec![
shell_snippet("printf 'broken failure hook'; exit 1"),
shell_snippet("printf 'later failure hook'"),
crate::test_hook("broken failure hook", "", 1, 0),
crate::test_hook("later failure hook", "", 0, 0),
],
));
@@ -994,8 +1002,8 @@ mod tests {
// given
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![
shell_snippet("printf 'first'"),
shell_snippet("printf 'second'"),
crate::test_hook("first", "", 0, 0),
crate::test_hook("second", "", 0, 0),
],
Vec::new(),
Vec::new(),
@@ -1022,7 +1030,7 @@ mod tests {
event: HookEvent::PreToolUse,
command,
..
} if command == "printf 'first'"
} if command == &crate::test_hook("first", "", 0, 0)
));
assert!(matches!(
&reporter.events[1],
@@ -1030,7 +1038,7 @@ mod tests {
event: HookEvent::PreToolUse,
command,
..
} if command == "printf 'first'"
} if command == &crate::test_hook("first", "", 0, 0)
));
assert!(matches!(
&reporter.events[2],
@@ -1038,7 +1046,7 @@ mod tests {
event: HookEvent::PreToolUse,
command,
..
} if command == "printf 'second'"
} if command == &crate::test_hook("second", "", 0, 0)
));
assert!(matches!(
&reporter.events[3],
@@ -1046,7 +1054,7 @@ mod tests {
event: HookEvent::PreToolUse,
command,
..
} if command == "printf 'second'"
} if command == &crate::test_hook("second", "", 0, 0)
));
}
@@ -1055,8 +1063,8 @@ mod tests {
// given
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![
shell_snippet("printf 'broken'; exit 1"),
shell_snippet("printf 'later'"),
crate::test_hook("broken", "", 1, 0),
crate::test_hook("later", "", 0, 0),
],
Vec::new(),
Vec::new(),
@@ -1077,8 +1085,11 @@ mod tests {
#[test]
fn malformed_nonempty_hook_output_reports_explicit_diagnostic_with_previews() {
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![shell_snippet(
"printf '{not-json\nsecond line'; printf 'stderr warning' >&2; exit 1",
vec![crate::test_hook(
"{not-json\nsecond line",
"stderr warning",
1,
0,
)],
Vec::new(),
Vec::new(),
@@ -1091,8 +1102,16 @@ mod tests {
assert!(rendered.contains("hook_invalid_json:"));
assert!(rendered.contains("phase=PreToolUse"));
assert!(rendered.contains("tool=Edit"));
assert!(rendered.contains("command=printf '{not-json"));
assert!(rendered.contains("printf 'stderr warning' >&2; exit 1"));
assert!(rendered.contains(&format!(
"command={}",
super::bounded_hook_preview(&crate::test_hook(
"{not-json\nsecond line",
"stderr warning",
1,
0
))
.expect("command preview")
)));
assert!(rendered.contains("detail=key must be a string"));
assert!(rendered.contains("stdout_preview={not-json"));
assert!(rendered.contains("second line stderr_preview=stderr warning"));
@@ -1102,7 +1121,7 @@ mod tests {
#[test]
fn abort_signal_cancels_long_running_hook_and_reports_progress() {
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![shell_snippet("sleep 5")],
vec![crate::test_hook("", "", 0, 5)],
Vec::new(),
Vec::new(),
));
@@ -1138,14 +1157,4 @@ mod tests {
}
)));
}
#[cfg(windows)]
fn shell_snippet(script: &str) -> String {
script.replace('\'', "\"")
}
#[cfg(not(windows))]
fn shell_snippet(script: &str) -> String {
script.to_string()
}
}
+17 -2
View File
@@ -151,7 +151,7 @@ pub use policy_engine::{
pub use prompt::{
load_system_prompt, load_system_prompt_with_context, prepend_bullets, ContextFile,
ModelFamilyIdentity, ProjectContext, PromptBuildError, SystemPromptBuilder,
FRONTIER_MODEL_NAME, SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
};
pub use recovery_recipes::{
attempt_recovery, recipe_for, EscalationPolicy, FailureScenario, RecoveryAttemptState,
@@ -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,
@@ -214,3 +215,17 @@ pub(crate) fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(test)]
pub(crate) fn test_hook(stdout: &str, stderr: &str, exit_code: i32, delay: u32) -> String {
let python = if cfg!(windows) { "python" } else { "python3" };
let encode = |text: &str| {
text.bytes()
.map(|byte| format!("{byte:02x}"))
.collect::<String>()
};
format!(
"{python} -c \"import sys,time; time.sleep({delay}); sys.stdout.write(bytes.fromhex('{}').decode()); sys.stderr.write(bytes.fromhex('{}').decode()); sys.exit({exit_code})\"",
encode(stdout), encode(stderr)
)
}
@@ -58,6 +58,11 @@ impl LineRange {
}
}
/// Check if this range contains no lines.
pub fn is_empty(&self) -> bool {
self.start_line > self.end_line
}
/// Check if this range is valid.
pub fn is_valid(&self) -> bool {
self.start_line > 0 && self.end_line > 0 && self.start_line <= self.end_line
@@ -344,4 +349,13 @@ mod tests {
assert_eq!(LineRange::new(50, 200).len(), 151);
assert_eq!(LineRange::new(50, 50).len(), 1);
}
#[test]
fn test_line_range_is_empty() {
assert!(LineRange::new(51, 50).is_empty());
assert_eq!(LineRange::new(51, 50).len(), 0);
assert!(!LineRange::new(50, 50).is_empty());
assert!(!LineRange::new(50, 200).is_empty());
assert!(!LineRange::new(0, 0).is_empty());
}
}
+37 -30
View File
@@ -18,11 +18,24 @@ use crate::mcp_lifecycle_hardened::{
McpDegradedReport, McpErrorSurface, McpFailedServer, McpLifecyclePhase,
};
// Test builds shrink the production handshake budgets (10s/30s) so that cases
// using the scripted stdio fixture finish quickly. The fixture is a real
// `python3` child, whose cold start measures 18-21ms here, so 200ms/300ms is
// roughly 10x headroom and enough when these tests run serially
// (`--test-threads=1`); under the default parallel run a dozen fixture children
// start at once and the budget runs out, which shows up as
// `Timeout { method: "initialize", timeout_ms: 200 }` failures across
// `mcp_stdio::tests` and `mcp_tool_bridge::tests` (ROADMAP #837). Re-run with
// `--test-threads=1` before treating those failures as a regression: the suite
// is green that way. Keep the budgets short rather than generous so a real
// handshake slowdown still fails fast; production keeps its own values.
#[cfg(test)]
const MCP_INITIALIZE_TIMEOUT_MS: u64 = 200;
#[cfg(not(test))]
const MCP_INITIALIZE_TIMEOUT_MS: u64 = 10_000;
// `MCP_LIST_TOOLS_TIMEOUT_MS` below shares the test-only shrink and the parallel
// caveat described here.
#[cfg(test)]
const MCP_LIST_TOOLS_TIMEOUT_MS: u64 = 300;
#[cfg(not(test))]
@@ -1430,7 +1443,6 @@ mod tests {
use std::collections::BTreeMap;
use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -1453,6 +1465,9 @@ mod tests {
};
use crate::McpLifecyclePhase;
// Fixtures are interpreter inputs, not directly executable Unix scripts.
const TEST_PYTHON: &str = if cfg!(windows) { "python" } else { "python3" };
fn temp_dir() -> PathBuf {
static NEXT_TEMP_DIR_ID: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
@@ -1466,15 +1481,19 @@ mod tests {
fn write_echo_script() -> PathBuf {
let root = temp_dir();
fs::create_dir_all(&root).expect("temp dir");
let script_path = root.join("echo-mcp.sh");
fs::write(
&script_path,
"#!/bin/sh\nprintf 'READY:%s\\n' \"$MCP_TEST_TOKEN\"\nIFS= read -r line\nprintf 'ECHO:%s\\n' \"$line\"\n",
)
.expect("write script");
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("chmod");
let script_path = root.join("echo-mcp.py");
let script = [
"import os, sys",
r"ready = ('READY:' + os.environ['MCP_TEST_TOKEN'] + '\n').encode()",
"sys.stdout.buffer.write(ready)",
"sys.stdout.buffer.flush()",
"line = sys.stdin.buffer.readline()",
r"sys.stdout.buffer.write(b'ECHO:' + line.rstrip(b'\r\n') + b'\n')",
"sys.stdout.buffer.flush()",
"",
]
.join("\n");
fs::write(&script_path, script).expect("write script");
script_path
}
@@ -1518,9 +1537,6 @@ mod tests {
]
.join("\n");
fs::write(&script_path, script).expect("write script");
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("chmod");
script_path
}
@@ -1652,9 +1668,6 @@ mod tests {
]
.join("\n");
fs::write(&script_path, script).expect("write script");
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("chmod");
script_path
}
@@ -1777,9 +1790,6 @@ mod tests {
]
.join("\n");
fs::write(&script_path, script).expect("write script");
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("chmod");
script_path
}
@@ -1788,7 +1798,7 @@ mod tests {
required: false,
scope: ConfigSource::Local,
config: McpServerConfig::Stdio(McpStdioServerConfig {
command: "/bin/sh".to_string(),
command: TEST_PYTHON.to_string(),
args: vec![script_path.to_string_lossy().into_owned()],
env: BTreeMap::from([("MCP_TEST_TOKEN".to_string(), "secret-value".to_string())]),
tool_call_timeout_ms: None,
@@ -1806,7 +1816,7 @@ mod tests {
env: BTreeMap<String, String>,
) -> crate::mcp_client::McpStdioTransport {
crate::mcp_client::McpStdioTransport {
command: "python3".to_string(),
command: TEST_PYTHON.to_string(),
args: vec![script_path.to_string_lossy().into_owned()],
env,
tool_call_timeout_ms: None,
@@ -1856,7 +1866,7 @@ mod tests {
required: false,
scope: ConfigSource::Local,
config: McpServerConfig::Stdio(McpStdioServerConfig {
command: "python3".to_string(),
command: TEST_PYTHON.to_string(),
args: vec![script_path.to_string_lossy().into_owned()],
env,
tool_call_timeout_ms: None,
@@ -2076,7 +2086,7 @@ mod tests {
runtime.block_on(async {
let script_path = write_echo_script();
let transport = crate::mcp_client::McpStdioTransport {
command: "/bin/sh".to_string(),
command: TEST_PYTHON.to_string(),
args: vec![script_path.to_string_lossy().into_owned()],
env: BTreeMap::from([("MCP_TEST_TOKEN".to_string(), "direct-secret".to_string())]),
tool_call_timeout_ms: None,
@@ -2336,7 +2346,7 @@ mod tests {
required: false,
scope: ConfigSource::Local,
config: McpServerConfig::Stdio(McpStdioServerConfig {
command: "python3".to_string(),
command: TEST_PYTHON.to_string(),
args: vec![script_path.to_string_lossy().into_owned()],
env: BTreeMap::from([(
"MCP_TOOL_CALL_DELAY_MS".to_string(),
@@ -2390,7 +2400,7 @@ mod tests {
required: false,
scope: ConfigSource::Local,
config: McpServerConfig::Stdio(McpStdioServerConfig {
command: "python3".to_string(),
command: TEST_PYTHON.to_string(),
args: vec![script_path.to_string_lossy().into_owned()],
env: BTreeMap::from([(
"MCP_INVALID_TOOL_CALL_RESPONSE".to_string(),
@@ -2701,9 +2711,6 @@ mod tests {
]
.join("\n");
fs::write(&script_path, script).expect("write script");
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("chmod");
script_path
}
@@ -2729,8 +2736,8 @@ mod tests {
required: true,
scope: ConfigSource::Local,
config: McpServerConfig::Stdio(McpStdioServerConfig {
command: broken_script_path.display().to_string(),
args: Vec::new(),
command: TEST_PYTHON.to_string(),
args: vec![broken_script_path.to_string_lossy().into_owned()],
env: BTreeMap::new(),
tool_call_timeout_ms: None,
}),
+4 -5
View File
@@ -314,7 +314,6 @@ impl McpToolRegistry {
mod tests {
use std::collections::BTreeMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -324,6 +323,9 @@ mod tests {
ConfigSource, McpServerConfig, McpStdioServerConfig, ScopedMcpServerConfig,
};
// Fixtures are interpreter inputs, not directly executable Unix scripts.
const TEST_PYTHON: &str = if cfg!(windows) { "python" } else { "python3" };
fn temp_dir() -> PathBuf {
static NEXT_TEMP_DIR_ID: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
@@ -430,9 +432,6 @@ mod tests {
]
.join("\n");
fs::write(&script_path, script).expect("write script");
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("chmod");
script_path
}
@@ -445,7 +444,7 @@ mod tests {
required: false,
scope: ConfigSource::Local,
config: McpServerConfig::Stdio(McpStdioServerConfig {
command: "python3".to_string(),
command: TEST_PYTHON.to_string(),
args: vec![script_path.to_string_lossy().into_owned()],
env: BTreeMap::from([
("MCP_SERVER_LABEL".to_string(), server_name.to_string()),
+3 -3
View File
@@ -1,6 +1,6 @@
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{self, Read};
use std::fs;
use std::io;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@@ -326,7 +326,7 @@ pub fn parse_oauth_callback_query(query: &str) -> Result<OAuthCallbackParams, St
fn generate_random_token(bytes: usize) -> io::Result<String> {
let mut buffer = vec![0_u8; bytes];
File::open("/dev/urandom")?.read_exact(&mut buffer)?;
getrandom::getrandom(&mut buffer).map_err(|error| io::Error::other(error.to_string()))?;
Ok(base64url_encode(&buffer))
}
+55 -12
View File
@@ -38,8 +38,6 @@ impl From<ConfigError> for PromptBuildError {
/// Marker separating static prompt scaffolding from dynamic runtime context.
pub const SYSTEM_PROMPT_DYNAMIC_BOUNDARY: &str = "__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__";
/// Human-readable default frontier model name embedded into generated prompts.
pub const FRONTIER_MODEL_NAME: &str = "Claude Opus 4.6";
const MAX_INSTRUCTION_FILE_CHARS: usize = 4_000;
const MAX_TOTAL_INSTRUCTION_CHARS: usize = 12_000;
const MAX_GIT_DIFF_CHARS: usize = 50_000;
@@ -56,7 +54,7 @@ impl ModelFamilyIdentity {
#[must_use]
pub const fn family_label(self) -> &'static str {
match self {
Self::Claude => FRONTIER_MODEL_NAME,
Self::Claude => "Claude",
Self::Generic => "an AI assistant",
}
}
@@ -158,6 +156,7 @@ pub struct SystemPromptBuilder {
os_name: Option<String>,
os_version: Option<String>,
model_family: Option<ModelFamilyIdentity>,
model: Option<String>,
append_sections: Vec<String>,
project_context: Option<ProjectContext>,
config: Option<RuntimeConfig>,
@@ -191,6 +190,12 @@ impl SystemPromptBuilder {
self
}
#[must_use]
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
#[must_use]
pub fn with_project_context(mut self, project_context: ProjectContext) -> Self {
self.project_context = Some(project_context);
@@ -294,9 +299,11 @@ impl SystemPromptBuilder {
|context| context.current_date.clone(),
);
let identity = self.model_family.unwrap_or_default();
let mut lines = vec!["# Environment context".to_string()];
lines.extend(prepend_bullets(vec![
format!("Model family: {}", identity.family_label()),
let mut items = vec![format!("Model family: {}", identity.family_label())];
if let Some(model) = &self.model {
items.push(format!("Model: {model}"));
}
items.extend([
format!("Working directory: {cwd}"),
format!("Date: {date}"),
format!(
@@ -304,7 +311,9 @@ impl SystemPromptBuilder {
self.os_name.as_deref().unwrap_or("unknown"),
self.os_version.as_deref().unwrap_or("unknown")
),
]));
]);
let mut lines = vec!["# Environment context".to_string()];
lines.extend(prepend_bullets(items));
lines.join("\n")
}
}
@@ -670,11 +679,18 @@ pub fn load_system_prompt(
current_date: impl Into<String>,
os_name: impl Into<String>,
os_version: impl Into<String>,
model: impl Into<String>,
model_family: ModelFamilyIdentity,
) -> Result<Vec<String>, PromptBuildError> {
let cwd = cwd.into();
let (sections, _) =
load_system_prompt_with_context(cwd, current_date, os_name, os_version, model_family)?;
let (sections, _) = load_system_prompt_with_context(
cwd,
current_date,
os_name,
os_version,
model,
model_family,
)?;
Ok(sections)
}
@@ -684,6 +700,7 @@ pub fn load_system_prompt_with_context(
current_date: impl Into<String>,
os_name: impl Into<String>,
os_version: impl Into<String>,
model: impl Into<String>,
model_family: ModelFamilyIdentity,
) -> Result<(Vec<String>, ProjectContext), PromptBuildError> {
let cwd = cwd.into();
@@ -693,6 +710,7 @@ pub fn load_system_prompt_with_context(
let memory_enabled = config.feature_config().auto_memory_enabled();
let mut builder = SystemPromptBuilder::new()
.with_os(os_name, os_version)
.with_model(model)
.with_model_family(model_family)
.with_project_context(project_context.clone())
.with_runtime_config(config);
@@ -1255,6 +1273,7 @@ mod tests {
"2026-03-31",
"linux",
"6.8",
"claude-opus-4-6",
ModelFamilyIdentity::Claude,
)
.expect("system prompt should load")
@@ -1304,6 +1323,7 @@ mod tests {
"2026-03-31",
"linux",
"6.8",
"claude-opus-4-6",
ModelFamilyIdentity::Claude,
)
.expect("system prompt should load")
@@ -1341,7 +1361,30 @@ mod tests {
.render();
// then: the Claude model family label is preserved by default
assert!(prompt.contains("Model family: Claude Opus 4.6"));
assert!(prompt.contains(" - Model family: Claude\n"));
assert!(!prompt.contains("Model:"));
}
#[test]
fn renders_configured_model_instead_of_a_fixed_claude_version() {
// given: a prompt builder for the model the session actually uses
let project_context = ProjectContext {
cwd: PathBuf::from("/tmp/project"),
current_date: "2026-03-31".to_string(),
..ProjectContext::default()
};
// when: rendering the system prompt environment section
let prompt = SystemPromptBuilder::new()
.with_os("linux", "6.8")
.with_model("claude-sonnet-4-6")
.with_model_family(ModelFamilyIdentity::Claude)
.with_project_context(project_context)
.render();
// then: the prompt names that model rather than a hardcoded Opus release
assert!(prompt.contains(" - Model family: Claude\n - Model: claude-sonnet-4-6\n"));
assert!(!prompt.contains("Opus"));
}
#[test]
@@ -1364,9 +1407,9 @@ mod tests {
.find(|line| line.contains("Model family:"))
.expect("model family line should render");
// then: the model family line is neutral and excludes Claude Opus 4.6
// then: the model family line is neutral and excludes Claude
assert_eq!(model_family_line, " - Model family: an AI assistant");
assert!(!model_family_line.contains("Claude Opus 4.6"));
assert!(!model_family_line.contains("Claude"));
}
#[test]
+12 -2
View File
@@ -66,7 +66,7 @@ pub struct UpstreamProxyState {
impl RemoteSessionContext {
#[must_use]
pub fn from_env() -> Self {
Self::from_env_map(&env::vars().collect())
Self::from_env_map(&utf8_env_map())
}
#[must_use]
@@ -89,7 +89,7 @@ impl RemoteSessionContext {
impl UpstreamProxyBootstrap {
#[must_use]
pub fn from_env() -> Self {
Self::from_env_map(&env::vars().collect())
Self::from_env_map(&utf8_env_map())
}
#[must_use]
@@ -234,6 +234,16 @@ pub fn inherited_upstream_proxy_env(
.collect()
}
/// Snapshot of the process environment, skipping non-UTF-8 entries.
///
/// `env::vars()` panics on non-UTF-8 values (e.g. zsh exports a metafied `$_`
/// when the command path contains non-ASCII characters).
fn utf8_env_map() -> BTreeMap<String, String> {
env::vars_os()
.filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
.collect()
}
fn default_ca_bundle_path() -> PathBuf {
env::var_os("HOME")
.map_or_else(|| PathBuf::from("."), PathBuf::from)
+5 -1
View File
@@ -109,7 +109,11 @@ impl SandboxConfig {
pub fn detect_container_environment() -> ContainerEnvironment {
let proc_1_cgroup = fs::read_to_string("/proc/1/cgroup").ok();
detect_container_environment_from(SandboxDetectionInputs {
env_pairs: env::vars().collect(),
// `env::vars()` panics on non-UTF-8 values (e.g. zsh exports a
// metafied `$_` for non-ASCII paths); skip those entries instead.
env_pairs: env::vars_os()
.filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
.collect(),
dockerenv_exists: Path::new("/.dockerenv").exists(),
containerenv_exists: Path::new("/run/.containerenv").exists(),
proc_1_cgroup: proc_1_cgroup.as_deref(),
+6
View File
@@ -262,6 +262,12 @@ impl Session {
pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, SessionError> {
let path = path.as_ref();
if fs::metadata(path)?.is_dir() {
return Err(SessionError::Io(std::io::Error::new(
std::io::ErrorKind::IsADirectory,
format!("session_path_is_directory: {}", path.display()),
)));
}
let contents = fs::read_to_string(path)?;
let session = match JsonValue::parse(&contents) {
Ok(value)
+140 -40
View File
@@ -29,7 +29,7 @@ impl Default for TridentConfig {
}
/// Statistics from a Trident compaction run.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TridentStats {
pub superseded_count: usize,
pub collapsed_chains: usize,
@@ -41,21 +41,6 @@ pub struct TridentStats {
pub final_message_count: usize,
}
impl Default for TridentStats {
fn default() -> Self {
Self {
superseded_count: 0,
collapsed_chains: 0,
messages_collapsed: 0,
clusters_found: 0,
messages_clustered: 0,
tokens_saved_estimate: 0,
original_message_count: 0,
final_message_count: 0,
}
}
}
impl TridentStats {
pub fn format_report(&self) -> String {
let compression = if self.final_message_count > 0 {
@@ -192,7 +177,7 @@ fn stage1_supersede(messages: &[ConversationMessage]) -> (Vec<ConversationMessag
let mut obsolete_indices: BTreeSet<usize> = BTreeSet::new();
for (_path, ops) in &file_ops {
for ops in file_ops.values() {
if ops.len() < 2 {
continue;
}
@@ -205,17 +190,55 @@ fn stage1_supersede(messages: &[ConversationMessage]) -> (Vec<ConversationMessag
if let Some(last_write) = last_write_idx {
for op in ops {
if op.op_type == FileOp::Read && op.index < last_write {
obsolete_indices.insert(op.index);
} else if (op.op_type == FileOp::Write || op.op_type == FileOp::Edit)
&& op.index < last_write
{
if op.index < last_write {
obsolete_indices.insert(op.index);
}
}
}
}
// A tool result is only meaningful together with the tool use that
// produced it. Dropping the tool use while keeping its result leaves an
// orphaned `tool_result` block, which providers reject with
// "tool_result blocks must be a response to a preceding tool_use".
let dropped_tool_use_ids: BTreeSet<&str> = obsolete_indices
.iter()
.filter_map(|index| messages.get(*index))
.flat_map(|message| message.blocks.iter())
.filter_map(|block| match block {
ContentBlock::ToolUse { id, .. } => Some(id.as_str()),
_ => None,
})
.collect();
for (index, message) in messages.iter().enumerate() {
if obsolete_indices.contains(&index) {
continue;
}
let answers_dropped_tool_use = message.blocks.iter().any(|block| {
matches!(
block,
ContentBlock::ToolResult { tool_use_id, .. }
if dropped_tool_use_ids.contains(tool_use_id.as_str())
)
});
if !answers_dropped_tool_use {
continue;
}
// Keep a message that still carries a surviving tool use: dropping it
// would orphan that tool use instead.
let keeps_surviving_tool_use = message.blocks.iter().any(|block| {
matches!(
block,
ContentBlock::ToolUse { id, .. }
if !dropped_tool_use_ids.contains(id.as_str())
)
});
if !keeps_surviving_tool_use {
obsolete_indices.insert(index);
}
}
let superseded_count = obsolete_indices.len();
let kept: Vec<ConversationMessage> = messages
.iter()
@@ -239,18 +262,11 @@ fn extract_file_operation(block: &ContentBlock) -> Option<(String, FileOp)> {
};
Some((path, op_type))
}
ContentBlock::ToolResult {
tool_name, output, ..
} => {
let path = extract_path_from_tool_output(tool_name, output)?;
let op_type = match tool_name.as_str() {
"read_file" | "Read" => FileOp::Read,
"write_file" | "Write" => FileOp::Write,
"edit_file" | "Edit" => FileOp::Edit,
_ => return None,
};
Some((path, op_type))
}
// A tool result is the answer half of a tool use, not an independent
// file operation. Counting it as one shifts `last_write` past the
// write it belongs to, which makes the newest write look obsolete
// and splits its tool-use/tool-result pair.
ContentBlock::ToolResult { .. } => None,
ContentBlock::Text { .. } => None,
ContentBlock::Thinking { .. } => None,
}
@@ -325,7 +341,7 @@ fn stage2_collapse(
usage: None,
});
} else {
result.extend(buffer.drain(..));
result.append(&mut buffer);
}
buffer.clear();
result.push(msg.clone());
@@ -476,7 +492,7 @@ fn stage3_cluster(
}
let total_clustered: usize = cluster_assignments.len();
let clusters_found = cluster_id as usize;
let clusters_found = cluster_id;
let mut result: Vec<ConversationMessage> = Vec::new();
let mut cluster_buffers: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
@@ -677,7 +693,7 @@ fn truncate_text(text: &str, max_chars: usize) -> String {
mod tests {
use super::*;
use crate::compact::CompactionConfig;
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
use crate::session::{ContentBlock, ConversationMessage, Session};
#[test]
fn stage1_removes_obsolete_file_reads() {
@@ -732,11 +748,95 @@ mod tests {
assert_eq!(kept.len(), messages.len());
}
#[test]
fn stage1_keeps_tool_use_and_result_paired() {
// Realistic transcript: the model reads the same file twice and then
// rewrites it. Stage 1 must drop the obsolete reads *and* their tool
// results, but it must never leave a `tool_result` behind without the
// `tool_use` that produced it: providers reject such requests with
// "tool_result blocks must be a response to a preceding tool_use".
let messages = vec![
ConversationMessage::assistant(vec![ContentBlock::ToolUse {
id: "1".to_string(),
name: "read_file".to_string(),
input: r#"{"path":"src/main.rs"}"#.to_string(),
}]),
ConversationMessage::tool_result(
"1",
"read_file",
r#"{"type":"text","file":{"filePath":"/ws/src/main.rs","content":"old"}}"#,
false,
),
ConversationMessage::assistant(vec![ContentBlock::ToolUse {
id: "2".to_string(),
name: "read_file".to_string(),
input: r#"{"path":"src/main.rs"}"#.to_string(),
}]),
ConversationMessage::tool_result(
"2",
"read_file",
r#"{"type":"text","file":{"filePath":"/ws/src/main.rs","content":"old"}}"#,
false,
),
ConversationMessage::assistant(vec![ContentBlock::ToolUse {
id: "3".to_string(),
name: "write_file".to_string(),
input: r#"{"path":"src/main.rs","content":"new"}"#.to_string(),
}]),
ConversationMessage::tool_result(
"3",
"write_file",
r#"{"type":"update","filePath":"/ws/src/main.rs","content":"new"}"#,
false,
),
];
let (kept, superseded) = stage1_supersede(&messages);
assert!(superseded > 0, "obsolete reads should be superseded");
let tool_use_ids: BTreeSet<&str> = kept
.iter()
.flat_map(|message| message.blocks.iter())
.filter_map(|block| match block {
ContentBlock::ToolUse { id, .. } => Some(id.as_str()),
_ => None,
})
.collect();
for message in &kept {
for block in &message.blocks {
if let ContentBlock::ToolResult { tool_use_id, .. } = block {
assert!(
tool_use_ids.contains(tool_use_id.as_str()),
"orphaned tool_result for tool_use {tool_use_id}"
);
}
}
}
// The most recent write survives, together with its tool result.
let has_tool_use = |id: &str| {
kept.iter().any(|message| {
message.blocks.iter().any(
|block| matches!(block, ContentBlock::ToolUse { id: tool_use_id, .. } if tool_use_id == id),
)
})
};
let has_tool_result = |id: &str| {
kept.iter().any(|message| {
message.blocks.iter().any(
|block| matches!(block, ContentBlock::ToolResult { tool_use_id, .. } if tool_use_id == id),
)
})
};
assert!(has_tool_use("3"), "the newest write must survive");
assert!(has_tool_result("3"), "its tool result must survive too");
}
#[test]
fn stage2_collapses_chatty_messages() {
let mut messages = vec![];
for i in 0..6 {
messages.push(ConversationMessage::user_text(&format!("ok {i}")));
messages.push(ConversationMessage::user_text(format!("ok {i}")));
messages.push(ConversationMessage::assistant(vec![ContentBlock::Text {
text: format!("got {i}"),
}]));
@@ -767,9 +867,9 @@ mod tests {
},
]));
messages.push(ConversationMessage::tool_result(
&format!("read_{i}"),
format!("read_{i}"),
"read_file",
&format!(r#"{{"path":"src/{i}.rs","content":"data {i}"}}"#),
format!(r#"{{"path":"src/{i}.rs","content":"data {i}"}}"#),
false,
));
}
+367 -31
View File
@@ -1,9 +1,9 @@
use crate::session::Session;
const DEFAULT_INPUT_COST_PER_MILLION: f64 = 15.0;
const DEFAULT_OUTPUT_COST_PER_MILLION: f64 = 75.0;
const DEFAULT_CACHE_CREATION_COST_PER_MILLION: f64 = 18.75;
const DEFAULT_CACHE_READ_COST_PER_MILLION: f64 = 1.5;
const DEFAULT_INPUT_COST_PER_MILLION: f64 = 3.0;
const DEFAULT_OUTPUT_COST_PER_MILLION: f64 = 15.0;
const DEFAULT_CACHE_CREATION_COST_PER_MILLION: f64 = 3.75;
const DEFAULT_CACHE_READ_COST_PER_MILLION: f64 = 0.3;
/// Per-million-token pricing used for cost estimation.
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -17,11 +17,24 @@ pub struct ModelPricing {
impl ModelPricing {
#[must_use]
pub const fn default_sonnet_tier() -> Self {
Self::per_million(
DEFAULT_INPUT_COST_PER_MILLION,
DEFAULT_OUTPUT_COST_PER_MILLION,
DEFAULT_CACHE_CREATION_COST_PER_MILLION,
DEFAULT_CACHE_READ_COST_PER_MILLION,
)
}
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: DEFAULT_INPUT_COST_PER_MILLION,
output_cost_per_million: DEFAULT_OUTPUT_COST_PER_MILLION,
cache_creation_cost_per_million: DEFAULT_CACHE_CREATION_COST_PER_MILLION,
cache_read_cost_per_million: DEFAULT_CACHE_READ_COST_PER_MILLION,
input_cost_per_million: input,
output_cost_per_million: output,
cache_creation_cost_per_million: cache_creation,
cache_read_cost_per_million: cache_read,
}
}
}
@@ -55,29 +68,219 @@ impl UsageCostEstimate {
}
/// Returns pricing metadata for a known model alias or family.
///
/// Anthropic rates follow <https://platform.claude.com/docs/en/about-claude/pricing>, using
/// 5-minute cache writes. Unversioned ids fall back to the tier the bare alias resolves to.
#[must_use]
pub fn pricing_for_model(model: &str) -> Option<ModelPricing> {
let normalized = model.to_ascii_lowercase();
if normalized.contains("fable") || normalized.contains("mythos") {
let version =
family_version(&normalized, "fable").or_else(|| family_version(&normalized, "mythos"));
return Some(match version {
Some((5, 1)) => ModelPricing::per_million(10.0, 50.0, 12.5, 0.25),
_ => ModelPricing::per_million(10.0, 50.0, 12.5, 1.0),
});
}
if normalized.contains("haiku") {
return Some(ModelPricing {
input_cost_per_million: 1.0,
output_cost_per_million: 5.0,
cache_creation_cost_per_million: 1.25,
cache_read_cost_per_million: 0.1,
if normalized.contains("3-5-haiku") {
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; 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),
});
}
if normalized.contains("opus") {
return Some(ModelPricing {
input_cost_per_million: 15.0,
output_cost_per_million: 75.0,
cache_creation_cost_per_million: 18.75,
cache_read_cost_per_million: 1.5,
return Some(match family_version(&normalized, "opus") {
Some((5, 5)) => ModelPricing::per_million(4.0, 20.0, 5.0, 0.2),
// Opus 4/4.1 remain on Bedrock and Google Cloud at the original tier.
Some((4, 0 | 1)) => ModelPricing::per_million(15.0, 75.0, 18.75, 1.5),
_ => ModelPricing::per_million(5.0, 25.0, 6.25, 0.5),
});
}
if normalized.contains("sonnet") {
return Some(ModelPricing::default_sonnet_tier());
return Some(match family_version(&normalized, "sonnet") {
Some((5, 5)) => ModelPricing::per_million(2.0, 10.0, 2.5, 0.1),
Some((5, 0)) => ModelPricing::per_million(2.0, 10.0, 2.5, 0.2),
_ => ModelPricing::default_sonnet_tier(),
});
}
None
// DeepSeek API peak rates (<https://api-docs.deepseek.com/quick_start/pricing>);
// off-peak usage is billed at half. Cache misses are billed as regular input,
// with no separate cache-write charge. The retired `deepseek-chat` and
// `deepseek-reasoner` ids were served by V4 Flash.
if normalized.contains("deepseek-v4-pro") {
return Some(ModelPricing::per_million(1.32, 3.96, 1.32, 0.044));
}
if [
"deepseek-flash",
"deepseek-v4-flash",
"deepseek-chat",
"deepseek-reasoner",
]
.iter()
.any(|id| normalized.contains(id))
{
return Some(ModelPricing::per_million(0.3, 1.2, 0.3, 0.006));
}
openai_compatible_pricing(&normalized)
}
/// xAI bills slugs retired on 2026-05-15 at grok-4.3 rates
/// (<https://docs.x.ai/developers/migration/may-15-retirement>).
const GROK_4_3: [f64; 4] = [1.25, 2.5, 1.25, 0.2];
const GROK_BUILD: [f64; 4] = [1.0, 2.0, 1.0, 0.2];
/// Input, output, cache-write and cache-read rates per MTok for models served through
/// 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 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]),
("gpt-6.1-sol", [2.0, 10.0, 2.5, 0.1]),
("gpt-6-sol", [2.0, 10.0, 2.5, 0.2]),
("gpt-6-luna", [0.1, 0.5, 0.125, 0.01]),
("gpt-5.6-sol", [4.0, 20.0, 5.0, 0.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]),
("gpt-4o-2024-05-13", [5.0, 15.0, 5.0, 5.0]),
("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]),
("grok-4.5", [2.0, 6.0, 2.0, 0.3]),
("grok-4.3", GROK_4_3),
("grok-4.20", GROK_4_3),
("grok-4.20-reasoning", GROK_4_3),
("grok-4.20-non-reasoning", GROK_4_3),
("grok-4.20-multi-agent", GROK_4_3),
("grok-build", GROK_BUILD),
("grok-code-fast", GROK_BUILD),
("grok-4", GROK_4_3),
("grok-4-fast-reasoning", GROK_4_3),
("grok-4-fast-non-reasoning", GROK_4_3),
("grok-3", GROK_4_3),
// Alibaba Model Studio, China (Beijing) region, which is claw's default DashScope
// endpoint (<https://www.alibabacloud.com/help/en/model-studio/model-pricing>).
// Non-thinking output; implicit cache hits bill at 20% of input.
("qwen-max", [0.345, 1.377, 0.345, 0.069]),
("qwen-plus", [0.115, 0.287, 0.115, 0.023]),
("qwen-flash", [0.022, 0.216, 0.022, 0.0044]),
("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);
table
.iter()
.find(|(model, _)| {
id.strip_prefix(model).is_some_and(|rest| {
rest.is_empty()
|| rest.strip_prefix('-').is_some_and(|suffix| {
suffix == "latest" || suffix.starts_with(|c: char| c.is_ascii_digit())
})
})
})
.map(|&(_, value)| value)
}
/// Parses the `(major, minor)` version after `family` in ids such as
/// `claude-opus-4-1-20250805`, `anthropic/claude-sonnet-5-5`, or `claude-opus-4@20250514`.
/// Date suffixes are not treated as a minor version.
fn family_version(model: &str, family: &str) -> Option<(u32, u32)> {
let rest = model[model.find(family)? + family.len()..].strip_prefix('-')?;
let mut parts = rest.split(|c: char| !c.is_ascii_digit());
let parse = |part: &str| part.parse::<u32>().ok().filter(|_| part.len() <= 2);
let major = parse(parts.next()?)?;
let minor = parts.next().and_then(parse).unwrap_or(0);
Some((major, minor))
}
impl TokenUsage {
@@ -216,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]
@@ -253,12 +456,12 @@ mod tests {
};
let cost = usage.estimate_cost_usd();
assert_eq!(format_usd(cost.input_cost_usd), "$15.0000");
assert_eq!(format_usd(cost.output_cost_usd), "$37.5000");
assert_eq!(format_usd(cost.input_cost_usd), "$3.0000");
assert_eq!(format_usd(cost.output_cost_usd), "$7.5000");
let lines = usage.summary_lines_for_model("usage", Some("claude-sonnet-4-20250514"));
assert!(lines[0].contains("estimated_cost=$54.6750"));
assert!(lines[0].contains("estimated_cost=$10.9350"));
assert!(lines[0].contains("model=claude-sonnet-4-20250514"));
assert!(lines[1].contains("cache_read=$0.3000"));
assert!(lines[1].contains("cache_read=$0.0600"));
}
#[test]
@@ -269,13 +472,146 @@ mod tests {
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
};
let total_for = |model: &str| {
let pricing = pricing_for_model(model).expect("known model pricing");
format_usd(
usage
.estimate_cost_usd_with_pricing(pricing)
.total_cost_usd(),
)
};
let haiku = pricing_for_model("claude-haiku-4-5-20251001").expect("haiku pricing");
let opus = pricing_for_model("claude-opus-4-6").expect("opus pricing");
let haiku_cost = usage.estimate_cost_usd_with_pricing(haiku);
let opus_cost = usage.estimate_cost_usd_with_pricing(opus);
assert_eq!(format_usd(haiku_cost.total_cost_usd()), "$3.5000");
assert_eq!(format_usd(opus_cost.total_cost_usd()), "$52.5000");
assert_eq!(total_for("claude-fable-5-1"), "$35.0000");
assert_eq!(total_for("claude-opus-4-6"), "$17.5000");
assert_eq!(total_for("anthropic/claude-opus-5-5"), "$14.0000");
assert_eq!(total_for("claude-opus-4-1-20250805"), "$52.5000");
assert_eq!(total_for("claude-opus-4@20250514"), "$52.5000");
assert_eq!(total_for("claude-sonnet-5-5"), "$7.0000");
assert_eq!(total_for("claude-sonnet-4-6"), "$10.5000");
assert_eq!(total_for("claude-haiku-5-5"), "$0.3500");
assert_eq!(total_for("claude-haiku-4-5-20251001"), "$3.5000");
assert_eq!(total_for("claude-3-5-haiku-20241022"), "$2.8000");
}
#[test]
fn distinguishes_cache_read_rates_across_versions() {
let usage = TokenUsage {
input_tokens: 0,
output_tokens: 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 1_000_000,
};
let cache_read_for = |model: &str| {
let pricing = pricing_for_model(model).expect("known model pricing");
format_usd(
usage
.estimate_cost_usd_with_pricing(pricing)
.cache_read_cost_usd,
)
};
assert_eq!(cache_read_for("claude-fable-5-1"), "$0.2500");
assert_eq!(cache_read_for("claude-fable-5"), "$1.0000");
assert_eq!(cache_read_for("claude-sonnet-5-5"), "$0.1000");
assert_eq!(cache_read_for("claude-sonnet-5"), "$0.2000");
}
#[test]
fn prices_deepseek_api_models_at_peak_rates() {
let usage = TokenUsage {
input_tokens: 1_000_000,
output_tokens: 500_000,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 1_000_000,
};
let total_for = |model: &str| {
let pricing = pricing_for_model(model).expect("known model pricing");
format_usd(
usage
.estimate_cost_usd_with_pricing(pricing)
.total_cost_usd(),
)
};
assert_eq!(total_for("deepseek-v4-pro"), "$3.3440");
assert_eq!(total_for("openai/deepseek-v4-pro"), "$3.3440");
assert_eq!(total_for("deepseek-flash"), "$0.9060");
assert_eq!(total_for("deepseek/deepseek-v4-flash"), "$0.9060");
assert_eq!(total_for("deepseek-reasoner"), "$0.9060");
// Third-party hosts set their own prices for other DeepSeek models.
assert_eq!(pricing_for_model("deepseek-r1"), None);
}
#[test]
fn prices_openai_compatible_provider_models() {
let usage = TokenUsage {
input_tokens: 1_000_000,
output_tokens: 500_000,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 1_000_000,
};
let total_for = |model: &str| {
let pricing = pricing_for_model(model).expect("known model pricing");
format_usd(
usage
.estimate_cost_usd_with_pricing(pricing)
.total_cost_usd(),
)
};
assert_eq!(total_for("gpt-5.4-mini"), "$3.0750");
assert_eq!(total_for("openai/gpt-4.1-2025-04-14"), "$6.5000");
assert_eq!(total_for("gpt-4o-2024-08-06"), "$8.7500");
assert_eq!(total_for("gpt-4o-2024-05-13"), "$17.5000");
assert_eq!(total_for("o3-mini"), "$3.8500");
assert_eq!(total_for("grok-4.3"), "$2.7000");
// Retired xAI slugs are billed as grok-4.3.
assert_eq!(total_for("grok-3"), "$2.7000");
assert_eq!(total_for("grok-4-1-fast-reasoning"), "$2.7000");
assert_eq!(total_for("grok-code-fast-1"), "$2.2000");
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",
"qwen-turbo",
"qwen-plus-character",
] {
assert_eq!(pricing_for_model(unpriced), None, "{unpriced}");
}
}
#[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]
+413 -136
View File
@@ -460,7 +460,10 @@ fn classify_error_kind(message: &str) -> &'static str {
// error message is "failed to restore session: legacy session is missing workspace
// binding: ...", so the specific arm must be checked first.
"legacy_session_no_workspace_binding"
} else if message.contains("Is a directory") || message.contains("os error 21") {
} else if message.contains("session_path_is_directory:")
|| message.contains("Is a directory")
|| message.contains("os error 21")
{
// #787: --resume given a directory path instead of a .jsonl file
"session_path_is_directory"
} else if message.contains("failed to restore session") {
@@ -517,7 +520,10 @@ fn classify_error_kind(message: &str) -> &'static str {
"api_http_error"
} else if message.contains("mcpServers") {
"malformed_mcp_config"
} else if message.contains(".claw/settings.json") || message.contains(".claw.json") {
} else if message.contains(".claw/settings.json")
|| message.contains(r".claw\settings.json")
|| message.contains(".claw.json")
{
// #763: config file JSON parse / validation errors (e.g. unterminated string, type mismatch)
"config_parse_error"
} else if message.starts_with("empty prompt") {
@@ -1950,9 +1956,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
// Only reject for known top-level subcommands that don't use compact.
let first = rest[0].as_str();
if is_known_top_level_subcommand(first) && first != "prompt" {
return Err(format!(
"invalid_flag_value: --compact is only supported with prompt mode.\nUsage: claw --compact \"<prompt>\" or echo \"<prompt>\" | claw --compact"
));
return Err("invalid_flag_value: --compact is only supported with prompt mode.\nUsage: claw --compact \"<prompt>\" or echo \"<prompt>\" | claw --compact".to_string());
}
}
@@ -3237,9 +3241,7 @@ fn parse_system_prompt_args(
})?;
// #99: validate --date is a plausible date string (no newlines, reasonable length)
if value.contains('\n') || value.contains('\r') {
return Err(format!(
"invalid_flag_value: --date value contains invalid characters.\nUsage: --date <YYYY-MM-DD>"
));
return Err("invalid_flag_value: --date value contains invalid characters.\nUsage: --date <YYYY-MM-DD>".to_string());
}
if value.len() > 20 {
return Err(format!(
@@ -3476,11 +3478,7 @@ impl DiagnosticCheck {
fn json_value(&self) -> Value {
// Derive a stable snake_case id from the check name for machine-readable keying (#704).
let id = self
.name
.to_ascii_lowercase()
.replace(' ', "_")
.replace('-', "_");
let id = self.name.to_ascii_lowercase().replace([' ', '-'], "_");
let mut value = Map::from_iter([
("id".to_string(), Value::String(id.clone())),
(
@@ -5012,6 +5010,7 @@ fn print_system_prompt(
date,
env::consts::OS,
"unknown",
model,
model_family_identity_for(model),
)?;
let (project_root, _) =
@@ -6973,16 +6972,15 @@ fn run_resume_command(
}
SlashCommand::Plugins { action, target } => {
// Only list is supported in resume mode (no runtime to reload)
match action.as_deref() {
Some(action @ ("install" | "uninstall" | "enable" | "disable" | "update")) => {
// #777: use interactive_only: prefix + \n hint so #776's classify/split
// emits error_kind:interactive_only + non-null hint instead of unknown+null.
// Orchestrators can now detect this and switch to a live REPL instead of retrying.
return Err(format!(
"interactive_only: /plugins {action} requires a live session to reload the plugin runtime.\nStart `claw` and run `/plugins {action}` inside the REPL, or use `claw plugins {action}` as a direct CLI command."
).into());
}
_ => {}
if let Some(action @ ("install" | "uninstall" | "enable" | "disable" | "update")) =
action.as_deref()
{
// #777: use interactive_only: prefix + \n hint so #776's classify/split
// emits error_kind:interactive_only + non-null hint instead of unknown+null.
// Orchestrators can now detect this and switch to a live REPL instead of retrying.
return Err(format!(
"interactive_only: /plugins {action} requires a live session to reload the plugin runtime.\nStart `claw` and run `/plugins {action}` inside the REPL, or use `claw plugins {action}` as a direct CLI command."
).into());
}
let cwd = env::current_dir()?;
let payload = plugins_command_payload_for(
@@ -7393,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>>>,
@@ -8165,8 +8164,7 @@ impl LiveCli {
let max_compact_rounds = 4;
let preserve_schedule = [4, 2, 1, 0];
for round in 0..max_compact_rounds {
let preserve = preserve_schedule[round];
for (round, preserve) in preserve_schedule.into_iter().enumerate() {
println!(
" Auto-compacting session (round {}/{}, preserving {} recent messages)...",
round + 1,
@@ -8749,11 +8747,12 @@ impl LiveCli {
let previous = self.model.clone();
let session = self.runtime.session().clone();
let message_count = session.messages.len();
let system_prompt = build_system_prompt(&model)?;
let runtime = build_runtime(
session,
&self.session.id,
model.clone(),
self.system_prompt.clone(),
system_prompt.clone(),
true,
true,
TerminalTail::new(),
@@ -8763,6 +8762,7 @@ impl LiveCli {
)?;
self.replace_runtime(runtime)?;
self.model.clone_from(&model);
self.system_prompt = system_prompt;
println!(
"{}",
format_model_switch_report(&previous, &model, message_count)
@@ -8992,8 +8992,8 @@ impl LiveCli {
let cwd = env::current_dir()?;
// #803: reject flag-shaped tokens in list filter for BOTH text and JSON modes.
// Previously the guard was JSON-only (#793); text mode silently returned empty success.
if action.as_deref() == Some("list") {
if let Some(filter) = target.as_deref() {
if action == Some("list") {
if let Some(filter) = target {
if filter.starts_with('-') {
if matches!(output_format, CliOutputFormat::Json) {
// ROADMAP #817: this is a handled local inventory parse error.
@@ -9999,6 +9999,8 @@ fn print_status_snapshot(
Ok(())
}
// Keep the independently optional provenance fields explicit at rendering callsites.
#[allow(clippy::too_many_arguments)]
fn status_json_value(
model: Option<&str>,
usage: StatusUsage,
@@ -10495,9 +10497,7 @@ fn sandbox_json_value(status: &runtime::SandboxStatus) -> serde_json::Value {
// (#731: "not supported on macOS" is a degraded state, not a hard error;
// filesystem_active:true means partial containment is working)
// error = enabled but unsupported AND no filesystem sandbox either (nothing active)
let top_status = if !status.enabled {
"ok"
} else if status.active {
let top_status = if !status.enabled || status.active {
"ok"
} else if status.supported {
"warn"
@@ -10871,10 +10871,7 @@ fn render_doctor_help_json() -> serde_json::Value {
})
}
/// #683-#692: extract structured metadata from help prose
fn extract_help_metadata(
topic: LocalHelpTopic,
) -> (
type HelpMetadata = (
Option<String>, // usage
Option<String>, // purpose
Option<String>, // output description
@@ -10883,7 +10880,10 @@ fn extract_help_metadata(
Option<Vec<String>>, // aliases
bool, // local_only
bool, // requires_credentials
) {
);
/// #683-#692: extract structured metadata from help prose
fn extract_help_metadata(topic: LocalHelpTopic) -> HelpMetadata {
let text = render_help_topic(topic);
let mut usage = None;
let mut purpose = None;
@@ -11942,7 +11942,7 @@ fn render_prompt_history_report(entries: &[PromptHistoryEntry], limit: usize) ->
"Prompt history".to_string(),
format!(" Total {total}"),
format!(" Showing {} most recent", shown.len()),
format!(" Reverse search Ctrl-R in the REPL"),
" Reverse search Ctrl-R in the REPL".to_string(),
String::new(),
];
for (offset, entry) in shown.iter().enumerate() {
@@ -12360,6 +12360,7 @@ fn build_system_prompt(model: &str) -> Result<Vec<String>, Box<dyn std::error::E
DEFAULT_DATE,
env::consts::OS,
"unknown",
model,
model_family_identity_for(model),
)?)
}
@@ -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,
@@ -13200,6 +13205,8 @@ struct AnthropicRuntimeClient {
}
impl AnthropicRuntimeClient {
// These independent runtime dependencies are supplied together at construction.
#[allow(clippy::too_many_arguments)]
fn new(
session_id: &str,
model: String,
@@ -13210,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.
@@ -13275,6 +13283,7 @@ impl AnthropicRuntimeClient {
client,
session_id: session_id.to_string(),
model,
max_output_tokens,
enable_tools,
emit_output,
terminal_tail,
@@ -13324,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
@@ -14466,7 +14478,7 @@ fn push_output_block(
out: &mut (impl Write + ?Sized),
events: &mut Vec<AssistantEvent>,
pending_tool: &mut Option<(String, String, String)>,
streaming_tool_input: bool,
streaming: bool,
block_has_thinking_summary: &mut bool,
) -> Result<(), RuntimeError> {
match block {
@@ -14483,7 +14495,7 @@ fn push_output_block(
// During streaming, the initial content_block_start has an empty input ({}).
// The real input arrives via input_json_delta events. In
// non-streaming responses, preserve a legitimate empty object.
let initial_input = if streaming_tool_input
let initial_input = if streaming
&& input.is_object()
&& input.as_object().is_some_and(serde_json::Map::is_empty)
{
@@ -14498,10 +14510,16 @@ fn push_output_block(
signature,
} => {
render_thinking_block_summary(out, Some(thinking.chars().count()), false)?;
events.push(AssistantEvent::Thinking {
thinking,
signature,
});
// During streaming, content_block_start only carries an empty
// placeholder; the full block (thinking + signature) is emitted on
// content_block_stop. Pushing it here too would replay an empty
// thinking block that the API rejects with 400 on the next turn.
if !streaming {
events.push(AssistantEvent::Thinking {
thinking,
signature,
});
}
*block_has_thinking_summary = true;
}
OutputContentBlock::RedactedThinking { .. } => {
@@ -14720,55 +14738,109 @@ fn permission_policy(
fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
messages
.iter()
.filter_map(|message| {
let role = match message.role {
MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
MessageRole::Assistant => "assistant",
};
let content = message
.blocks
.iter()
.filter_map(|block| match block {
ContentBlock::Text { text } => {
Some(InputContentBlock::Text { text: text.clone() })
}
ContentBlock::Thinking {
thinking,
signature,
} => {
// 保留 Thinking 块:OpenAI 兼容协议会把它转成 reasoning_content 字段
// 回传给 DeepSeek V4(避免 400 "reasoning_content must be passed back" 错误)
Some(InputContentBlock::Thinking {
thinking: thinking.clone(),
signature: signature.clone(),
})
}
ContentBlock::ToolUse { id, name, input } => Some(InputContentBlock::ToolUse {
id: id.clone(),
name: name.clone(),
input: serde_json::from_str(input)
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
}),
ContentBlock::ToolResult {
tool_use_id,
output,
is_error,
..
} => Some(InputContentBlock::ToolResult {
tool_use_id: tool_use_id.clone(),
content: vec![ToolResultContentBlock::Text {
text: output.clone(),
}],
is_error: *is_error,
}),
})
.collect::<Vec<_>>();
(!content.is_empty()).then(|| InputMessage {
role: role.to_string(),
content,
})
.filter_map(convert_message)
.fold(Vec::new(), absorb_tool_result_message)
}
/// Converts one conversation message into its wire form.
fn convert_message(message: &ConversationMessage) -> Option<InputMessage> {
let role = match message.role {
MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
MessageRole::Assistant => "assistant",
};
let content = message
.blocks
.iter()
.map(|block| match block {
ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
ContentBlock::Thinking {
thinking,
signature,
} => {
// 保留 Thinking 块:OpenAI 兼容协议会把它转成 reasoning_content 字段
// 回传给 DeepSeek V4(避免 400 "reasoning_content must be passed back" 错误)
InputContentBlock::Thinking {
thinking: thinking.clone(),
signature: signature.clone(),
}
}
ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
id: id.clone(),
name: name.clone(),
input: serde_json::from_str(input)
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
},
ContentBlock::ToolResult {
tool_use_id,
output,
is_error,
..
} => InputContentBlock::ToolResult {
tool_use_id: tool_use_id.clone(),
content: vec![ToolResultContentBlock::Text {
text: output.clone(),
}],
is_error: *is_error,
},
})
.collect()
.collect::<Vec<_>>();
(!content.is_empty()).then(|| InputMessage {
role: role.to_string(),
content,
})
}
/// Identical in `rusty-claude-cli` and `tools`; kept in both copies by review
/// decision rather than shared, but they must still be changed together.
///
/// The two `convert_messages` call sites are not interchangeable: `tools` drops
/// empty `Text` blocks and the CLI keeps them. That difference is confined to
/// `convert_message`, so it constrains hoisting the whole conversion, not this
/// fold. It is reachable when history is not built from the model stream — an
/// empty `user_text("")` or a persisted `"text":""` restored from a session log
/// bypasses the `flush_text_block` filter that the streaming path applies.
/// Appends a message to the wire history, merging a *run* of pure tool-result
/// messages into one message.
///
/// `runtime` records one `MessageRole::Tool` message per tool call, but the
/// Anthropic Messages API requires *every* `tool_use` of an assistant turn to be
/// answered by `tool_result` blocks **in the same following message**. Emitting
/// one message per result leaves the second and later results of a parallel
/// tool-call turn one message too late, and the request is rejected with
/// `messages.N: tool_use ids were found without tool_result blocks immediately
/// after`.
///
/// A merge requires **both** sides to be pure tool results: the accumulated
/// message and the incoming one. Checking only the accumulated side folds the
/// turn that *follows* a tool result into it — the assistant reply the model
/// produced after the tool ran, or a later user turn, would arrive as extra
/// content inside the tool-result message and its role would be lost. That
/// message is re-read on every request (`stream()` converts the whole history
/// again), so the damage is not limited to the turn that produced it, and it
/// happens on single-tool-call turns too.
fn absorb_tool_result_message(
mut messages: Vec<InputMessage>,
message: InputMessage,
) -> Vec<InputMessage> {
if is_tool_result_only(&message) {
if let Some(previous) = messages.last_mut() {
if previous.role == "user" && is_tool_result_only(previous) {
previous.content.extend(message.content);
return messages;
}
}
}
messages.push(message);
messages
}
/// Reports whether a wire message carries tool results and nothing else.
fn is_tool_result_only(message: &InputMessage) -> bool {
!message.content.is_empty()
&& message
.content
.iter()
.all(|block| matches!(block, InputContentBlock::ToolResult { .. }))
}
#[allow(clippy::too_many_lines)]
@@ -15013,7 +15085,7 @@ mod tests {
SessionLifecycleSummary, SlashCommand, StatusUsage, TerminalTail, TmuxPaneSnapshot,
DEFAULT_MODEL, LATEST_SESSION_REFERENCE, STUB_COMMANDS,
};
use api::{ApiError, MessageResponse, OutputContentBlock, Usage};
use api::{ApiError, InputContentBlock, MessageResponse, OutputContentBlock, Usage};
use plugins::{
PluginManager, PluginManagerConfig, PluginTool, PluginToolDefinition, PluginToolPermission,
};
@@ -15096,7 +15168,7 @@ mod tests {
"Something went wrong while processing your request. Please try again, or use /new to start a fresh session."
.to_string(),
),
request_id: Some("req_jobdori_789".to_string()),
request_id: Some("req_jobdori_789".into()),
body: String::new(),
retryable: true,
suggested_action: None,
@@ -15120,7 +15192,7 @@ mod tests {
"Something went wrong while processing your request. Please try again, or use /new to start a fresh session."
.to_string(),
),
request_id: Some("req_jobdori_790".to_string()),
request_id: Some("req_jobdori_790".into()),
body: String::new(),
retryable: true,
suggested_action: None,
@@ -15185,7 +15257,7 @@ mod tests {
"This model's maximum context length is 200000 tokens, but your request used 230000 tokens."
.to_string(),
),
request_id: Some("req_ctx_456".to_string()),
request_id: Some("req_ctx_456".into()),
body: String::new(),
retryable: false,
suggested_action: None,
@@ -15219,7 +15291,7 @@ mod tests {
"Input tokens exceed the configured limit of 922000 tokens. Your messages resulted in 1860900 tokens. Please reduce the length of the messages."
.to_string(),
),
request_id: Some("req_ctx_openai_456".to_string()),
request_id: Some("req_ctx_openai_456".into()),
body: String::new(),
retryable: false,
suggested_action: None,
@@ -15254,7 +15326,7 @@ mod tests {
status: "413".parse().expect("status"),
error_type: Some("invalid_request_error".to_string()),
message: Some("Request is too large for this model's context window.".to_string()),
request_id: Some("req_ctx_retry_789".to_string()),
request_id: Some("req_ctx_retry_789".into()),
body: String::new(),
retryable: false,
suggested_action: None,
@@ -15347,30 +15419,43 @@ mod tests {
)
.expect("write hook");
}
if include_lifecycle {
let lifecycle = if include_lifecycle {
fs::create_dir_all(root.join("lifecycle")).expect("lifecycle dir");
let (extension, init_script, shutdown_script) = if cfg!(windows) {
(
"cmd",
"@echo off\r\necho init>>lifecycle.log\r\n",
"@echo off\r\necho shutdown>>lifecycle.log\r\n",
)
} else {
(
"sh",
"#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
"#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
)
};
fs::write(
root.join("lifecycle").join("init.sh"),
"#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
root.join("lifecycle").join(format!("init.{extension}")),
init_script,
)
.expect("write init lifecycle");
fs::write(
root.join("lifecycle").join("shutdown.sh"),
"#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
root.join("lifecycle").join(format!("shutdown.{extension}")),
shutdown_script,
)
.expect("write shutdown lifecycle");
}
format!(
",\n \"lifecycle\": {{\n \"Init\": [\"./lifecycle/init.{extension}\"],\n \"Shutdown\": [\"./lifecycle/shutdown.{extension}\"]\n }}"
)
} else {
String::new()
};
let hooks = if include_hooks {
",\n \"hooks\": {\n \"PreToolUse\": [\"./hooks/pre.sh\"]\n }"
} else {
""
};
let lifecycle = if include_lifecycle {
",\n \"lifecycle\": {\n \"Init\": [\"./lifecycle/init.sh\"],\n \"Shutdown\": [\"./lifecycle/shutdown.sh\"]\n }"
} else {
""
};
fs::write(
root.join(".claude-plugin").join("plugin.json"),
format!(
@@ -15991,10 +16076,11 @@ mod tests {
#[test]
fn parses_system_prompt_options() {
// given: system-prompt options for cwd and date
let cwd = std::env::temp_dir();
let args = vec![
"system-prompt".to_string(),
"--cwd".to_string(),
"/tmp".to_string(),
cwd.to_string_lossy().into_owned(),
"--date".to_string(),
"2026-04-01".to_string(),
];
@@ -16006,7 +16092,7 @@ mod tests {
assert_eq!(
action,
CliAction::PrintSystemPrompt {
cwd: PathBuf::from("/tmp"),
cwd,
date: "2026-04-01".to_string(),
model: DEFAULT_MODEL.to_string(),
output_format: CliOutputFormat::Text,
@@ -16641,7 +16727,10 @@ mod tests {
// Phase 1 contract: workspace/git/sandbox fields are still populated
// (independent of config parse). Sandbox falls back to defaults.
assert_eq!(context.cwd, cwd.canonicalize().unwrap_or(cwd.clone()));
assert_eq!(
context.cwd.canonicalize().expect("canonical cwd"),
cwd.canonicalize().expect("canonical workspace")
);
assert_eq!(
context.loaded_config_files, 0,
"loaded_config_files should be 0 when config parse fails"
@@ -16982,6 +17071,16 @@ mod tests {
classify_error_kind("failed to restore session: Is a directory (os error 21)"),
"session_path_is_directory"
);
assert_eq!(
classify_error_kind(
r"failed to restore session: session_path_is_directory: C:\sessions"
),
"session_path_is_directory"
);
assert_eq!(
classify_error_kind(r"C:\workspace\.claw\settings.json: model must be a string"),
"config_parse_error"
);
assert_eq!(
classify_error_kind("unrecognized argument `--foo` for subcommand `doctor`"),
"cli_parse"
@@ -17723,7 +17822,7 @@ mod tests {
for action in ["remove", "uninstall", "delete"] {
assert_eq!(
parse_args(&["skills".to_string(), action.to_string()])
.expect(&format!("skills {action} should parse")),
.unwrap_or_else(|_| panic!("skills {action} should parse")),
CliAction::Skills {
args: Some(action.to_string()),
output_format: CliOutputFormat::Text,
@@ -18200,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(
@@ -18722,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);
@@ -18995,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);
@@ -19274,16 +19378,22 @@ UU conflicted.rs",
error.to_string().contains("session workspace mismatch"),
"unexpected error: {error}"
);
let error = error.to_string();
let workspace_a_name = workspace_a
.file_name()
.expect("workspace a should have a name")
.to_string_lossy();
let workspace_b_name = workspace_b
.file_name()
.expect("workspace b should have a name")
.to_string_lossy();
assert_ne!(workspace_a_name, workspace_b_name);
assert!(
error
.to_string()
.contains(&workspace_b.display().to_string()),
error.contains(workspace_b_name.as_ref()),
"expected current workspace in error: {error}"
);
assert!(
error
.to_string()
.contains(&workspace_a.display().to_string()),
error.contains(workspace_a_name.as_ref()),
"expected originating workspace in error: {error}"
);
@@ -19358,6 +19468,95 @@ UU conflicted.rs",
assert!(rendered.contains("cargo clippy --workspace --all-targets -- -D warnings"));
}
#[test]
fn keeps_the_assistant_reply_that_follows_tool_results() {
let tool_result = |id: &str| ConversationMessage {
role: MessageRole::Tool,
blocks: vec![ContentBlock::ToolResult {
tool_use_id: id.to_string(),
tool_name: "bash".to_string(),
output: "ok".to_string(),
is_error: false,
}],
usage: None,
};
let messages = vec![
ConversationMessage::user_text("run it"),
ConversationMessage::assistant(vec![ContentBlock::ToolUse {
id: "tool-1".to_string(),
name: "bash".to_string(),
input: "{\"command\":\"pwd\"}".to_string(),
}]),
tool_result("tool-1"),
// The model's answer after the tool ran; the next request carries it
// back, because `stream()` converts the whole history again.
ConversationMessage::assistant(vec![ContentBlock::Text {
text: "done".to_string(),
}]),
ConversationMessage::user_text("and now?"),
];
let converted = super::convert_messages(&messages);
assert_eq!(
converted.len(),
messages.len(),
"each turn keeps its own message; converted: {converted:?}"
);
assert_eq!(converted[2].role, "user");
assert_eq!(
converted[3].role, "assistant",
"the reply after a tool result must stay an assistant turn: {converted:?}"
);
assert_eq!(
converted[3].content,
vec![InputContentBlock::Text {
text: "done".to_string()
}]
);
}
#[test]
fn keeps_a_user_follow_up_that_follows_tool_results_separate() {
let tool_result = |id: &str| ConversationMessage {
role: MessageRole::Tool,
blocks: vec![ContentBlock::ToolResult {
tool_use_id: id.to_string(),
tool_name: "bash".to_string(),
output: "ok".to_string(),
is_error: false,
}],
usage: None,
};
let messages = vec![
ConversationMessage::user_text("run it"),
ConversationMessage::assistant(vec![ContentBlock::ToolUse {
id: "tool-1".to_string(),
name: "bash".to_string(),
input: "{\"command\":\"pwd\"}".to_string(),
}]),
tool_result("tool-1"),
// A new user turn appended to the same history must not be folded
// into the tool-result message either.
ConversationMessage::user_text("hello again"),
];
let converted = super::convert_messages(&messages);
assert_eq!(
converted.len(),
messages.len(),
"a later user turn is its own message; converted: {converted:?}"
);
assert_eq!(converted[3].role, "user");
assert_eq!(
converted[3].content,
vec![InputContentBlock::Text {
text: "hello again".to_string()
}]
);
}
#[test]
fn converts_tool_roundtrip_messages() {
let messages = vec![
@@ -19384,6 +19583,49 @@ UU conflicted.rs",
assert_eq!(converted[1].role, "assistant");
assert_eq!(converted[2].role, "user");
}
#[test]
fn converts_parallel_tool_call_results_into_one_paired_message() {
let tool_use = |id: &str| ContentBlock::ToolUse {
id: id.to_string(),
name: "bash".to_string(),
input: "{\"command\":\"pwd\"}".to_string(),
};
let tool_result = |id: &str| ConversationMessage {
role: MessageRole::Tool,
blocks: vec![ContentBlock::ToolResult {
tool_use_id: id.to_string(),
tool_name: "bash".to_string(),
output: "ok".to_string(),
is_error: false,
}],
usage: None,
};
let messages = vec![
ConversationMessage::user_text("hello"),
ConversationMessage::assistant(vec![tool_use("tool-1"), tool_use("tool-2")]),
tool_result("tool-1"),
tool_result("tool-2"),
];
let converted = super::convert_messages(&messages);
// one user turn, one assistant turn, and ONE user message carrying both
// results: the API requires every tool_use of a turn to be answered in
// the message immediately after it.
assert_eq!(converted.len(), 3, "converted messages: {converted:?}");
assert_eq!(converted[1].role, "assistant");
assert_eq!(converted[2].role, "user");
let answered = converted[2]
.content
.iter()
.filter_map(|block| match block {
InputContentBlock::ToolResult { tool_use_id, .. } => Some(tool_use_id.as_str()),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(answered, vec!["tool-1", "tool-2"]);
}
#[test]
fn repl_help_mentions_history_completion_and_multiline() {
let help = render_repl_help();
@@ -19772,6 +20014,34 @@ UU conflicted.rs",
);
}
#[test]
fn push_output_block_defers_thinking_event_while_streaming() {
let mut out = Vec::new();
let mut events = Vec::new();
let mut pending_tool = None;
let mut block_has_thinking_summary = false;
push_output_block(
OutputContentBlock::Thinking {
thinking: String::new(),
signature: Some(String::new()),
},
&mut out,
&mut events,
&mut pending_tool,
true,
&mut block_has_thinking_summary,
)
.expect("thinking block start should render");
// The full thinking block is emitted on content_block_stop; emitting the
// empty placeholder here would duplicate it in the session history.
assert!(events.is_empty());
assert!(block_has_thinking_summary);
let rendered = String::from_utf8(out).expect("utf8");
assert!(rendered.contains("▶ Thinking (0 chars hidden)"));
}
#[test]
fn response_to_events_preserves_empty_object_json_input_outside_streaming() {
let mut out = Vec::new();
@@ -19976,6 +20246,7 @@ UU conflicted.rs",
GlobalToolRegistry::builtin(),
None,
Some(config),
None,
)
.expect("runtime client should construct from explicit model provider hint");
@@ -20074,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");
@@ -20091,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");
@@ -20099,21 +20374,19 @@ UU conflicted.rs",
write_mcp_server_fixture(&script_path);
fs::write(
config_home.join("settings.json"),
format!(
r#"{{
"mcpServers": {{
"alpha": {{
"command": "python3",
"args": ["{}"]
}},
"broken": {{
"command": "python3",
"args": ["-c", "import sys; sys.exit(0)"]
}}
}}
}}"#,
script_path.to_string_lossy()
),
serde_json::json!({
"mcpServers": {
"alpha": {
"command": if cfg!(windows) { "python" } else { "python3" },
"args": [script_path]
},
"broken": {
"command": if cfg!(windows) { "python" } else { "python3" },
"args": ["-c", "import sys; sys.exit(0)"]
}
}
})
.to_string(),
)
.expect("write mcp settings");
@@ -20302,7 +20575,9 @@ UU conflicted.rs",
.expect("runtime should build");
assert_eq!(
fs::read_to_string(&log_path).expect("init log should exist"),
fs::read_to_string(&log_path)
.expect("init log should exist")
.replace("\r\n", "\n"),
"init\n"
);
@@ -20311,7 +20586,9 @@ UU conflicted.rs",
.expect("plugin shutdown should succeed");
assert_eq!(
fs::read_to_string(&log_path).expect("shutdown log should exist"),
fs::read_to_string(&log_path)
.expect("shutdown log should exist")
.replace("\r\n", "\n"),
"init\nshutdown\n"
);
+8 -16
View File
@@ -632,7 +632,7 @@ impl TerminalRenderer {
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MarkdownStreamState {
pending: String,
/// Track whether the last emitted output ended with a newline.
@@ -640,15 +640,6 @@ pub struct MarkdownStreamState {
last_output_ends_with_newline: bool,
}
impl Default for MarkdownStreamState {
fn default() -> Self {
Self {
pending: String::new(),
last_output_ends_with_newline: false,
}
}
}
impl MarkdownStreamState {
#[must_use]
pub fn push(&mut self, renderer: &TerminalRenderer, delta: &str) -> Option<String> {
@@ -662,16 +653,16 @@ impl MarkdownStreamState {
// If the previous output didn't end with a newline and this chunk starts
// with a block-level element, ensure proper spacing before it.
if !self.last_output_ends_with_newline && !rendered.is_empty() {
if stripped.starts_with("\u{256d}\u{2500}")
if !self.last_output_ends_with_newline
&& !rendered.is_empty()
&& (stripped.starts_with("\u{256d}\u{2500}")
|| stripped.starts_with("```")
|| stripped.starts_with("|")
|| stripped.starts_with("• ")
|| stripped.starts_with("1. ")
|| stripped.starts_with("-")
{
rendered = format!("\n\n{}", rendered);
}
|| stripped.starts_with("-"))
{
rendered = format!("\n\n{}", rendered);
}
// When markdown ends with a code block closing marker or other block-level element,
@@ -916,6 +907,7 @@ fn normalize_nested_fences(markdown: &str) -> String {
/// Safe boundaries are:
/// - After a closing fence line (when fence is closed)
/// - After an empty line
///
/// This function returns the position of the last safe boundary found.
fn find_stream_safe_boundary(markdown: &str) -> Option<usize> {
let mut open_fence: Option<FenceMarker> = None;
@@ -2,8 +2,6 @@ use std::io::{self, IsTerminal, Write};
use runtime::{save_user_provider_settings, ConfigLoader, RuntimeProviderConfig};
use serde_json;
const PROVIDERS: &[(&str, &str, &str)] = &[
("1", "Anthropic", "anthropic"),
("2", "xAI / Grok", "xai"),
@@ -257,6 +257,34 @@ fn local_smoke_commands_do_not_require_live_credentials() {
fs::remove_dir_all(temp_dir).expect("cleanup temp dir");
}
#[cfg(unix)]
#[test]
fn doctor_tolerates_non_utf8_environment_values() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
// given: zsh exports a metafied (non-UTF-8) `$_` when the command path
// contains non-ASCII characters such as `下載`
let temp_dir = unique_temp_dir("non-utf8-env");
let config_home = temp_dir.join(".claw");
fs::create_dir_all(&config_home).expect("config home should exist");
let metafied_path = OsStr::from_bytes(b"/home/user/\xe4\xb8\x83\xab\xe8\xbc\x83\xa9/claw");
// when
let output = offline_command_in(&temp_dir, &config_home)
.env("_", metafied_path)
.arg("doctor")
.output()
.expect("claw should launch");
// then
assert_success(&output);
let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
assert!(stdout.contains("Doctor"));
fs::remove_dir_all(temp_dir).expect("cleanup temp dir");
}
#[test]
fn local_subcommand_help_does_not_fall_through_to_runtime_or_provider_calls() {
let temp_dir = unique_temp_dir("subcommand-help");
@@ -1,5 +1,7 @@
#![allow(clippy::while_let_on_iterator)]
mod support;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
@@ -655,12 +657,12 @@ fn run_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")
.env("PATH", "/usr/bin:/bin")
.args(args);
command.output().expect("claw should launch")
}
@@ -676,12 +678,12 @@ fn run_claw_with_stdin(
let mut child = Command::new(env!("CARGO_BIN_EXE_claw"))
.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")
.env("PATH", "/usr/bin:/bin")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -708,10 +710,10 @@ fn run_claw_closed_stdin_with_timeout(
let mut child = Command::new(env!("CARGO_BIN_EXE_claw"))
.current_dir(cwd)
.env_clear()
.envs(support::process_environment())
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -1,3 +1,5 @@
mod support;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
@@ -55,15 +57,15 @@ fn run_claw_repl(
home: &std::path::Path,
stdin: &str,
) -> Output {
let mut command = python_pty_command(env!("CARGO_BIN_EXE_claw"));
let mut command = python_terminal_command(env!("CARGO_BIN_EXE_claw"));
let mut child = command
.current_dir(cwd)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-compact-repl-key")
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -80,30 +82,12 @@ fn run_claw_repl(
child.wait_with_output().expect("claw should finish")
}
fn python_pty_command(claw: &str) -> Command {
let mut command = Command::new("python3");
command.args([
"-c",
r#"
import os
import pty
import subprocess
import sys
claw = sys.argv[1]
payload = sys.stdin.buffer.read()
master, slave = pty.openpty()
child = subprocess.Popen([claw], stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
os.close(slave)
os.write(master, payload)
stdout, stderr = child.communicate(timeout=30)
os.close(master)
sys.stdout.buffer.write(stdout)
sys.stderr.buffer.write(stderr)
raise SystemExit(child.returncode)
"#,
claw,
]);
fn python_terminal_command(claw: &str) -> Command {
let mut command = Command::new(if cfg!(windows) { "python" } else { "python3" });
command.arg(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/repl_console.py"),
);
command.arg(claw);
command
}
@@ -1,3 +1,5 @@
mod support;
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
@@ -312,12 +314,12 @@ fn run_case(case: ScenarioCase, workspace: &HarnessWorkspace, base_url: &str) ->
command
.current_dir(&workspace.root)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-parity-key")
.env("ANTHROPIC_BASE_URL", base_url)
.env("CLAW_CONFIG_HOME", &workspace.config_home)
.env("HOME", &workspace.home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.args([
"--model",
"sonnet",
@@ -411,6 +413,33 @@ fn prepare_multi_tool_fixture(workspace: &HarnessWorkspace) {
}
fn prepare_plugin_fixture(workspace: &HarnessWorkspace) {
// A Windows `python` command can be an install-manager launcher whose
// bootstrap messages go to stdout. Resolve it before entering the isolated
// CLI environment, then execute the interpreter itself for the JSON tool.
let python = Command::new(if cfg!(windows) { "python" } else { "python3" })
.args([
"-I",
"-c",
"import json, sys; print(json.dumps(sys.executable))",
])
.output()
.expect("Python interpreter discovery should launch");
assert!(
python.status.success(),
"Python interpreter discovery failed: {}",
String::from_utf8_lossy(&python.stderr)
);
let discovery_stdout = String::from_utf8(python.stdout).expect("Python discovery UTF-8");
let interpreter: String = serde_json::from_str(
discovery_stdout
.lines()
.last()
.expect("Python interpreter path"),
)
.expect("Python discovery must end with its JSON-encoded executable path");
assert!(Path::new(&interpreter).is_absolute());
assert!(Path::new(&interpreter).is_file());
let plugin_root = workspace
.root
.join("external-plugins")
@@ -420,45 +449,36 @@ fn prepare_plugin_fixture(workspace: &HarnessWorkspace) {
fs::create_dir_all(&tool_dir).expect("plugin tools dir");
fs::create_dir_all(&manifest_dir).expect("plugin manifest dir");
let script_path = tool_dir.join("echo-json.sh");
let script_path = tool_dir.join("echo-json.py");
fs::write(
&script_path,
"#!/bin/sh\nINPUT=$(cat)\nprintf '{\"plugin\":\"%s\",\"tool\":\"%s\",\"input\":%s}\\n' \"$CLAWD_PLUGIN_ID\" \"$CLAWD_TOOL_NAME\" \"$INPUT\"\n",
r#"import json, os, sys
print(json.dumps({"plugin": os.environ["CLAWD_PLUGIN_ID"], "tool": os.environ["CLAWD_TOOL_NAME"], "input": json.load(sys.stdin)}))
"#,
)
.expect("plugin script should write");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut permissions = fs::metadata(&script_path)
.expect("plugin script metadata")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("plugin script should be executable");
}
fs::write(
manifest_dir.join("plugin.json"),
r#"{
"name": "parity-plugin",
"version": "1.0.0",
"description": "mock parity plugin",
"tools": [
{
"name": "plugin_echo",
"description": "Echo JSON input",
"inputSchema": {
"type": "object",
"properties": {
"message": { "type": "string" }
},
"required": ["message"],
"additionalProperties": false
},
"command": "./tools/echo-json.sh",
"requiredPermission": "workspace-write"
}
]
}"#,
json!({
"name": "parity-plugin",
"version": "1.0.0",
"description": "mock parity plugin",
"tools": [{
"name": "plugin_echo",
"description": "Echo JSON input",
"inputSchema": {
"type": "object",
"properties": {"message": {"type": "string"}},
"required": ["message"],
"additionalProperties": false
},
"command": interpreter,
"args": ["-I", "tools/echo-json.py"],
"requiredPermission": "workspace-write"
}]
})
.to_string(),
)
.expect("plugin manifest should write");
@@ -504,8 +524,16 @@ fn assert_read_file_roundtrip(workspace: &HarnessWorkspace, run: &ScenarioRun) {
let output = run.response["tool_results"][0]["output"]
.as_str()
.expect("tool output");
assert!(output.contains(&workspace.root.join("fixture.txt").display().to_string()));
assert!(output.contains("alpha parity line"));
let payload: Value = serde_json::from_str(output).expect("read_file output JSON");
let actual_path = payload["file"]["filePath"].as_str().expect("filePath");
assert_eq!(
fs::canonicalize(actual_path).expect("canonical reported file"),
fs::canonicalize(workspace.root.join("fixture.txt")).expect("canonical fixture file")
);
assert!(payload["file"]["content"]
.as_str()
.expect("file content")
.contains("alpha parity line"));
}
fn assert_grep_chunk_assembly(_: &HarnessWorkspace, run: &ScenarioRun) {
@@ -536,10 +564,11 @@ fn assert_write_file_allowed(workspace: &HarnessWorkspace, run: &ScenarioRun) {
run.response["tool_uses"][0]["name"],
Value::String("write_file".to_string())
);
assert!(run.response["message"]
.as_str()
.expect("message text")
.contains("generated/output.txt"));
let message = run.response["message"].as_str().expect("message text");
assert!(
message.contains("write_file succeeded"),
"expected successful write confirmation in assistant message: {message:?}"
);
let generated = workspace.root.join("generated").join("output.txt");
let contents = fs::read_to_string(&generated).expect("generated file should exist");
assert_eq!(contents, "created by mock service\n");
@@ -676,7 +705,13 @@ fn assert_plugin_tool_roundtrip(_: &HarnessWorkspace, run: &ScenarioRun) {
let tool_output = run.response["tool_results"][0]["output"]
.as_str()
.expect("tool output");
let parsed: Value = serde_json::from_str(tool_output).expect("plugin output json");
assert_eq!(
run.response["tool_results"][0]["is_error"],
Value::Bool(false),
"plugin tool failed: {tool_output}"
);
let parsed: Value = serde_json::from_str(tool_output)
.unwrap_or_else(|err| panic!("plugin output is not JSON: {err}; output: {tool_output:?}"));
assert_eq!(
parsed["plugin"],
Value::String("parity-plugin@external".to_string())
@@ -638,13 +638,25 @@ fn global_cwd_flag_routes_status_workspace_and_short_alias_429() {
&["--cwd", workspace_str, "--output-format", "json", "status"],
);
assert_eq!(status["kind"], "status");
assert_eq!(status["workspace"]["cwd"], expected_cwd);
assert_eq!(
fs::canonicalize(status["workspace"]["cwd"].as_str().expect("cwd"))
.expect("canonical cwd")
.display()
.to_string(),
expected_cwd
);
let short_status = assert_json_command(
&launcher,
&["-C", workspace_str, "status", "--output-format", "json"],
);
assert_eq!(short_status["workspace"]["cwd"], expected_cwd);
assert_eq!(
fs::canonicalize(short_status["workspace"]["cwd"].as_str().expect("cwd"))
.expect("canonical cwd")
.display()
.to_string(),
expected_cwd
);
let directory_status = assert_json_command(
&launcher,
@@ -655,7 +667,13 @@ fn global_cwd_flag_routes_status_workspace_and_short_alias_429() {
"status",
],
);
assert_eq!(directory_status["workspace"]["cwd"], expected_cwd);
assert_eq!(
fs::canonicalize(directory_status["workspace"]["cwd"].as_str().expect("cwd"))
.expect("canonical cwd")
.display()
.to_string(),
expected_cwd
);
}
#[test]
@@ -1016,13 +1034,13 @@ fn inventory_commands_emit_structured_json_when_requested() {
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("reload_runtime")),
.is_some_and(|o| o.contains_key("reload_runtime")),
"plugins list should not include reload_runtime"
);
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("target")),
.is_some_and(|o| o.contains_key("target")),
"plugins list should not include target"
);
// #703: structured summary replaces prose message
@@ -1716,13 +1734,13 @@ fn resumed_inventory_commands_emit_structured_json_when_requested() {
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("reload_runtime")),
.is_some_and(|o| o.contains_key("reload_runtime")),
"plugins list should not include reload_runtime"
);
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("target")),
.is_some_and(|o| o.contains_key("target")),
"plugins list should not include target"
);
assert!(
@@ -2295,7 +2313,7 @@ fn config_json_attributes_precedence_and_shadowed_keys_425() {
file["source"] == "project"
&& file["path"]
.as_str()
.is_some_and(|path| path.ends_with(".claw/settings.json"))
.is_some_and(|path| std::path::Path::new(path).ends_with(".claw/settings.json"))
})
.expect("project .claw/settings.json entry");
@@ -2955,7 +2973,7 @@ fn prompt_empty_arg_json_stdout_missing_prompt_823() {
"claw prompt empty arg must retain abort action (#823); got: {parsed}"
);
assert!(
parsed["hint"].as_str().map_or(false, |h| !h.is_empty()),
parsed["hint"].as_str().is_some_and(|h| !h.is_empty()),
"claw prompt empty arg missing_prompt hint must be non-empty (#823)"
);
}
@@ -2993,9 +3011,9 @@ fn flag_value_errors_have_error_kind_and_hint_756() {
"invalid --reasoning-effort must be invalid_flag_value (#756): {parsed}"
);
assert!(
parsed["hint"].as_str().map_or(false, |h| h.contains("low")
|| h.contains("medium")
|| h.contains("high")),
parsed["hint"]
.as_str()
.is_some_and(|h| h.contains("low") || h.contains("medium") || h.contains("high")),
"hint must mention valid values (#756): {parsed}"
);
@@ -3021,7 +3039,7 @@ fn flag_value_errors_have_error_kind_and_hint_756() {
"missing --model value must be missing_flag_value (#756): {parsed2}"
);
assert!(
parsed2["hint"].as_str().map_or(false, |h| !h.is_empty()),
parsed2["hint"].as_str().is_some_and(|h| !h.is_empty()),
"missing --model hint must be non-empty (#756): {parsed2}"
);
}
@@ -3265,7 +3283,7 @@ fn short_p_flag_swallows_no_flags_755() {
"flag-like token after -p must be rejected as missing_prompt (#755): {parsed2}"
);
assert!(
parsed2["hint"].as_str().map_or(false, |h| !h.is_empty()),
parsed2["hint"].as_str().is_some_and(|h| !h.is_empty()),
"missing_prompt hint must be non-empty (#755)"
);
}
@@ -3407,7 +3425,7 @@ fn config_unsupported_section_json_hint_741() {
assert!(
parsed["supported_sections"]
.as_array()
.map_or(false, |a| !a.is_empty()),
.is_some_and(|a| !a.is_empty()),
"config {section} JSON must include supported_sections (#741)"
);
}
@@ -3464,11 +3482,6 @@ fn export_json_has_kind_702() {
// On success stdout has kind:export; on failure stderr has type:error.
// Either way, both envelopes must be valid JSON.
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr)
.lines()
.filter(|l| l.starts_with('{'))
.collect::<Vec<_>>()
.join("");
if output.status.success() {
let parsed: serde_json::Value =
@@ -3557,8 +3570,6 @@ fn config_parse_error_has_typed_error_kind_and_hint_764() {
"malformed settings.json should cause non-zero exit"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
.find(|l| l.trim_start().starts_with('{'))
@@ -3592,8 +3603,6 @@ fn login_logout_removed_subcommands_have_error_kind_and_hint_765() {
"claw {subcmd} should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
.find(|l| l.trim_start().starts_with('{'))
@@ -3732,8 +3741,6 @@ fn resume_non_slash_trailing_arg_has_typed_error_kind_and_hint_768() {
"claw --resume latest compact should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
.find(|l| l.trim_start().starts_with('{'))
@@ -3772,8 +3779,6 @@ fn session_with_unknown_subcommand_returns_interactive_only_not_credentials_767(
"claw session {sub} should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
.find(|l| l.trim_start().starts_with('{'))
@@ -3825,7 +3830,6 @@ fn slash_only_verbs_with_args_return_interactive_only_not_credentials_770() {
"claw {} should exit non-zero",
args.join(" ")
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -3868,8 +3872,6 @@ fn agents_plugins_mcp_unknown_subcommand_have_hint_774() {
let output = run_claw(&root, &["--output-format", "json", "agents", "bogus"], &[]);
assert!(!output.status.success(), "agents bogus should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
.find(|l| l.trim_start().starts_with('{'))
@@ -3892,8 +3894,6 @@ fn agents_plugins_mcp_unknown_subcommand_have_hint_774() {
let output = run_claw(&root, &["--output-format", "json", "plugins", "bogus"], &[]);
assert!(!output.status.success(), "plugins bogus should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
.find(|l| l.trim_start().starts_with('{'))
@@ -3911,7 +3911,6 @@ fn agents_plugins_mcp_unknown_subcommand_have_hint_774() {
{
let output = run_claw(&root, &["--output-format", "json", "mcp", "bogus"], &[]);
assert!(!output.status.success(), "mcp bogus should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_str = if stdout.trim().starts_with('{') {
@@ -4026,7 +4025,6 @@ fn interactive_only_guard_batch_769_to_771() {
"claw {} should exit non-zero",
args.join(" ")
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -4090,7 +4088,6 @@ fn resume_plugin_mutations_are_typed_interactive_only_777() {
!output.status.success(),
"/plugins {mutation} in resume mode should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -4147,7 +4144,6 @@ fn resume_skills_invocation_is_typed_interactive_only_779() {
!output.status.success(),
"/skills <skill> in resume mode should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -4189,8 +4185,6 @@ fn acp_unsupported_invocation_has_hint_782() {
let output = run_claw(&root, &["--output-format", "json", "acp", "start"], &[]);
assert!(!output.status.success(), "acp start should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
.find(|l| l.trim_start().starts_with('{'))
@@ -4226,7 +4220,6 @@ fn init_json_envelope_has_hint_and_already_initialized_783() {
// Fresh init — already_initialized should be false, hint should mention CLAUDE.md
let output = run_claw(&root, &["--output-format", "json", "init"], &[]);
assert!(output.status.success(), "init should succeed");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let raw = if stdout.trim_start().starts_with('{') {
@@ -4295,7 +4288,6 @@ fn init_json_envelope_has_hint_and_already_initialized_783() {
// Idempotent re-init — already_initialized should be true
let output2 = run_claw(&root, &["--output-format", "json", "init"], &[]);
assert!(output2.status.success(), "re-init should succeed");
let stdout2 = String::from_utf8_lossy(&output2.stdout);
let stderr2 = String::from_utf8_lossy(&output2.stderr);
let stdout2 = String::from_utf8_lossy(&output2.stdout);
let raw2 = if stdout2.trim_start().starts_with('{') {
@@ -4376,7 +4368,6 @@ fn export_arg_errors_have_typed_kind_and_hint_784() {
&[],
);
assert!(!out1.status.success(), "--output with no value should fail");
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4403,7 +4394,6 @@ fn export_arg_errors_have_typed_kind_and_hint_784() {
&[],
);
assert!(!out2.status.success(), "extra positional should fail");
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -4440,7 +4430,6 @@ fn unknown_subcommand_returns_typed_kind_785() {
// "dump" is close enough to "dump-manifests" to trigger the typo suggestion path
let output = run_claw(&root, &["--output-format", "json", "dump"], &[]);
assert!(!output.status.success(), "unknown subcommand should fail");
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -4488,7 +4477,6 @@ fn dump_manifests_missing_dir_has_typed_kind_and_hint_786() {
&[],
);
assert!(!out1.status.success());
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4520,7 +4508,6 @@ fn dump_manifests_missing_dir_has_typed_kind_and_hint_786() {
&[],
);
assert!(!out2.status.success());
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -4570,7 +4557,6 @@ fn resume_directory_path_returns_typed_kind_and_hint_787() {
!output.status.success(),
"resume with directory should fail"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -4620,7 +4606,6 @@ fn skills_show_not_found_emits_single_json_object_788() {
assert!(!output.status.success(), "skills show unknown should fail");
// Skills handler emits JSON to stdout; the duplicate was on stderr from the main error path.
// After fix: stdout has 1 JSON object, stderr has none (no duplicate).
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -4782,7 +4767,6 @@ fn system_prompt_unknown_option_returns_typed_kind_790() {
&[],
);
assert!(!out1.status.success());
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4809,7 +4793,6 @@ fn system_prompt_unknown_option_returns_typed_kind_790() {
&[],
);
assert!(!out2.status.success());
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -4847,7 +4830,6 @@ fn config_extra_args_have_non_null_hint_791() {
&[],
);
assert!(!out1.status.success());
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4881,7 +4863,6 @@ fn config_extra_args_have_non_null_hint_791() {
&[],
);
assert!(!out2.status.success());
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -5067,7 +5048,6 @@ fn plugins_uninstall_not_found_has_hint_793() {
"plugins uninstall not-found must exit non-zero (#793)"
);
// Error envelope goes to stderr (propagated via ? to main error handler)
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -5112,7 +5092,6 @@ fn plugins_install_not_found_path_returns_typed_kind_794() {
!output.status.success(),
"plugins install not-found-path must exit non-zero (#794)"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -5359,7 +5338,7 @@ fn agents_create_scaffolds_toml_and_lists_locally_431() {
assert_eq!(create_json["status"], "ok");
assert_eq!(create_json["format"], "toml");
assert_eq!(
reported_agent_path,
fs::canonicalize(&reported_agent_path).expect("canonical reported agent path"),
fs::canonicalize(&agent_path).expect("canonical agent path")
);
assert!(agent_path.is_file());
@@ -5376,7 +5355,8 @@ fn agents_create_scaffolds_toml_and_lists_locally_431() {
.iter()
.any(|agent| {
agent["name"] == "my-agent"
&& PathBuf::from(agent["path"].as_str().expect("listed agent path"))
&& fs::canonicalize(agent["path"].as_str().expect("listed agent path"))
.expect("canonical reported list path")
== fs::canonicalize(&agent_path).expect("canonical listed agent path")
}));
}
@@ -5501,7 +5481,6 @@ fn plugins_extra_args_have_non_null_hint_797() {
!output.status.success(),
"plugins show with extra arg must exit non-zero (#797)"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -5567,7 +5546,6 @@ fn plugins_list_trailing_dash_text_error_stays_on_stderr_817() {
String::from_utf8_lossy(&output.stdout)
);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stderr.contains("[error-kind: cli_parse]"), "{stderr}");
assert!(
stderr.contains("unknown option for `claw plugins list`: --"),
@@ -5592,7 +5570,6 @@ fn empty_prompt_has_non_null_hint_798() {
!output.status.success(),
"empty prompt must exit non-zero (#798)"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -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()
))
}
@@ -0,0 +1,233 @@
//! Wire contract for turns that issue several tool calls at once.
//!
//! The Anthropic Messages API requires every `tool_use` of an assistant message
//! to be answered by `tool_result` blocks in the message that immediately
//! follows it. A turn with two tool calls used to emit one result message per
//! call, so the second result arrived one message too late and the provider
//! rejected the request with `messages.N: tool_use ids were found without
//! tool_result blocks immediately after`.
//!
//! This test drives the real `claw` binary against the mock Anthropic service
//! and asserts on the payload the provider would receive, so it fails against
//! the pre-fix implementation without depending on any private helper. The
//! mock service does not validate pairing itself, which is why the assertion
//! lives here.
mod support;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use mock_anthropic_service::{MockAnthropicService, SCENARIO_PREFIX};
use serde_json::{json, Value};
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
const SCENARIO: &str = "multi_tool_turn_roundtrip";
#[test]
fn parallel_tool_calls_are_answered_in_one_following_message() {
let runtime = tokio::runtime::Runtime::new().expect("tokio runtime should build");
let workspace = unique_temp_dir("parallel-tool-pairing");
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::write(
workspace.join("fixture.txt"),
"alpha parity line\nbeta line\ngamma parity line\n",
)
.expect("fixture should write");
prepare_config_home(&config_home);
let server = runtime
.block_on(MockAnthropicService::spawn())
.expect("mock service should start");
let output = run_claw(&workspace, &config_home, &home, &server.base_url());
assert!(
output.status.success(),
"claw should complete the parallel tool turn\nstdout:\n{}\n\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
let requests = runtime
.block_on(server.captured_requests())
.into_iter()
.filter(|request| request.path == "/v1/messages")
.map(|request| {
serde_json::from_str::<Value>(&request.raw_body).expect("request body should be json")
})
.collect::<Vec<_>>();
// The turn issued two tool calls, so the follow-up request must carry their
// results. Asserting the count also catches a split into two messages.
let tool_result_requests = requests
.iter()
.filter(|body| messages_have_tool_result(body))
.count();
assert_eq!(
tool_result_requests,
1,
"tool results must reach the provider in one message; requests were:\n{}",
describe_requests(&requests),
);
let mut inspected_tool_uses = 0_u64;
for body in &requests {
let messages = body
.get("messages")
.and_then(Value::as_array)
.unwrap_or_else(|| panic!("request should carry messages: {body}"));
for (index, message) in messages.iter().enumerate() {
let calls = tool_use_ids(message);
if calls.is_empty() {
continue;
}
inspected_tool_uses += calls.len() as u64;
let answered = messages
.get(index + 1)
.map(tool_result_ids)
.unwrap_or_default();
assert_eq!(
answered,
calls,
"messages.{index} tool_use {calls:?} must be answered by the next message; \
requests were:\n{}",
describe_requests(&requests),
);
}
}
assert!(
inspected_tool_uses >= 2,
"the scenario should exercise parallel tool calls, saw {inspected_tool_uses}: {}",
describe_requests(&requests),
);
fs::remove_dir_all(&workspace).expect("workspace cleanup should succeed");
}
/// Writes the permission preset the mock harness runs with.
fn prepare_config_home(config_home: &std::path::Path) {
fs::write(
config_home.join("settings.json"),
json!({ "permissions": { "defaultMode": "read-only" } }).to_string(),
)
.expect("settings should write");
}
fn run_claw(workspace: &PathBuf, config_home: &PathBuf, home: &PathBuf, base_url: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_claw"))
.current_dir(workspace)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-parallel-tool-key")
.env("ANTHROPIC_BASE_URL", base_url)
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.args([
"--model",
"sonnet",
"--permission-mode",
"read-only",
"--output-format=json",
"--allowedTools",
"read_file,grep_search",
])
.arg(format!("{SCENARIO_PREFIX}{SCENARIO}"))
.output()
.expect("claw should launch")
}
fn messages_have_tool_result(body: &Value) -> bool {
body.get("messages")
.and_then(Value::as_array)
.is_some_and(|messages| {
messages
.iter()
.any(|message| !tool_result_ids(message).is_empty())
})
}
fn tool_use_ids(message: &Value) -> Vec<String> {
block_ids(message, "tool_use", "id")
}
fn tool_result_ids(message: &Value) -> Vec<String> {
block_ids(message, "tool_result", "tool_use_id")
}
fn block_ids(message: &Value, block_type: &str, id_field: &str) -> Vec<String> {
message
.get("content")
.and_then(Value::as_array)
.map(|blocks| {
blocks
.iter()
.filter(|block| block.get("type").and_then(Value::as_str) == Some(block_type))
.filter_map(|block| block.get(id_field).and_then(Value::as_str))
.map(ToString::to_string)
.collect()
})
.unwrap_or_default()
}
/// Renders the message role/block shape of every captured request for failures.
fn describe_requests(requests: &[Value]) -> String {
requests
.iter()
.enumerate()
.map(|(index, body)| {
let shape = body
.get("messages")
.and_then(Value::as_array)
.map(|messages| {
messages
.iter()
.map(|message| {
let role = message
.get("role")
.and_then(Value::as_str)
.unwrap_or("unknown");
let blocks = message
.get("content")
.and_then(Value::as_array)
.map(|blocks| {
blocks
.iter()
.map(|block| {
block
.get("type")
.and_then(Value::as_str)
.unwrap_or("unknown")
.to_string()
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
format!("{role}{blocks:?}")
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
format!(" request {index}: {shape:?}")
})
.collect::<Vec<_>>()
.join("\n")
}
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-{label}-{}-{millis}-{counter}",
std::process::id()
))
}
@@ -0,0 +1,27 @@
use std::ffi::OsString;
// Keep credentials, proxy variables and user configuration out of subprocess
// tests, but preserve the operating-system environment needed to load DLLs,
// initialize networking and find the installed test interpreters on Windows.
pub fn process_environment() -> Vec<(&'static str, OsString)> {
#[cfg(windows)]
{
[
"PATH",
"SYSTEMROOT",
"WINDIR",
"SYSTEMDRIVE",
"COMSPEC",
"PATHEXT",
"TEMP",
"TMP",
]
.into_iter()
.filter_map(|name| std::env::var_os(name).map(|value| (name, value)))
.collect()
}
#[cfg(not(windows))]
{
vec![("PATH", OsString::from("/usr/bin:/bin"))]
}
}
@@ -0,0 +1,92 @@
"""Give the CLI terminal stdin and captured stdout, using only Python's stdlib."""
import os
import subprocess
import sys
def run_unix(claw, payload):
import pty
master, slave = pty.openpty()
try:
with subprocess.Popen([claw], stdin=slave, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as child:
os.close(slave)
slave = None
os.write(master, payload)
try:
stdout, stderr = child.communicate(timeout=30)
except subprocess.TimeoutExpired:
child.kill()
child.communicate()
raise
return child.returncode, stdout, stderr
finally:
if slave is not None:
os.close(slave)
os.close(master)
def run_windows(claw, payload):
import ctypes
import msvcrt
from ctypes import wintypes
class KeyEvent(ctypes.Structure):
_fields_ = [("down", wintypes.BOOL), ("repeat", wintypes.WORD),
("virtual_key", wintypes.WORD), ("scan", wintypes.WORD),
("char", wintypes.WCHAR), ("control", wintypes.DWORD)]
class Event(ctypes.Union):
_fields_ = [("key", KeyEvent), ("storage", ctypes.c_byte * 16)]
class InputRecord(ctypes.Structure):
_fields_ = [("kind", wintypes.WORD), ("event", Event)]
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.AllocConsole.argtypes = []
kernel.AllocConsole.restype = wintypes.BOOL
kernel.FreeConsole.argtypes = []
kernel.FreeConsole.restype = wintypes.BOOL
kernel.WriteConsoleInputW.argtypes = [wintypes.HANDLE, ctypes.POINTER(InputRecord),
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
kernel.WriteConsoleInputW.restype = wintypes.BOOL
# This affects only this helper process, never the test runner's console.
kernel.FreeConsole()
if not kernel.AllocConsole():
raise ctypes.WinError(ctypes.get_last_error())
try:
with open("CONIN$", "r+b", buffering=0) as console:
records = []
for char in payload.decode("utf-8").replace("\r\n", "\n").replace("\n", "\r"):
for down in (True, False):
record = InputRecord()
record.kind = 1 # KEY_EVENT
record.event.key = KeyEvent(down, 1, 13 if char == "\r" else 0,
0, char, 0)
records.append(record)
inputs = (InputRecord * len(records))(*records)
written = wintypes.DWORD()
if not kernel.WriteConsoleInputW(msvcrt.get_osfhandle(console.fileno()),
inputs, len(inputs), ctypes.byref(written)):
raise ctypes.WinError(ctypes.get_last_error())
if written.value != len(inputs):
raise RuntimeError("incomplete console input")
with subprocess.Popen([claw], stdin=console, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as child:
try:
stdout, stderr = child.communicate(timeout=30)
except subprocess.TimeoutExpired:
child.kill()
child.communicate()
raise
return child.returncode, stdout, stderr
finally:
kernel.FreeConsole()
if __name__ == "__main__":
run = run_windows if os.name == "nt" else run_unix
code, stdout, stderr = run(sys.argv[1], sys.stdin.buffer.read())
sys.stdout.buffer.write(stdout)
sys.stderr.buffer.write(stderr)
raise SystemExit(code)
+1
View File
@@ -14,6 +14,7 @@ uuid = { version = "1", features = ["v4", "serde"] }
tracing = "0.1"
url = "2"
runtime = { path = "../runtime" }
sha2 = "0.10"
[dev-dependencies]
tempfile = "3"
+53 -15
View File
@@ -8,6 +8,7 @@ use std::{
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::error::{SdkError, SdkResult};
@@ -135,18 +136,17 @@ impl TerminalScopeStore {
Ok(Some(record))
}
/// Builds the record path for a correlation key.
///
/// Files are named from a fixed-width digest instead of the key's hex
/// expansion: a maximal 512-byte key expands to 1024 hex characters, which
/// overflows the 1024-byte total-path limit enforced by APFS before any
/// chunking can help, and `File name too long` would be reported for a
/// generated leaf name the caller never chose. The key itself is still
/// stored in `TerminalScopeRecord::correlation_key` and checked on read.
fn record_path(&self, correlation_key: &str) -> PathBuf {
const MAX_COMPONENT_BYTES: usize = 180;
let encoded = encode_key_as_hex(correlation_key);
let mut path = self.root.clone();
let mut remaining = encoded.as_str();
while remaining.len() > MAX_COMPONENT_BYTES {
let (component, tail) = remaining.split_at(MAX_COMPONENT_BYTES);
path.push(component);
remaining = tail;
}
path.push(format!("{remaining}.json"));
path
self.root
.join(format!("{}.json", encode_key_for_path(correlation_key)))
}
}
@@ -158,10 +158,14 @@ fn validate_correlation_key(correlation_key: &str) -> SdkResult<()> {
}
}
fn encode_key_as_hex(key: &str) -> String {
/// Encodes a correlation key as a fixed-width filesystem-safe path component.
fn encode_key_for_path(key: &str) -> String {
const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut encoded = String::with_capacity(key.len() * 2);
for byte in key.as_bytes() {
let digest = Sha256::digest(key.as_bytes());
// The first 16 bytes are far more than the number of records one store
// holds, and the full key survives in the record for exact matching.
let mut encoded = String::with_capacity(32);
for byte in digest.iter().take(16) {
encoded.push(char::from(HEX_DIGITS[usize::from(*byte >> 4)]));
encoded.push(char::from(HEX_DIGITS[usize::from(*byte & 0x0f)]));
}
@@ -180,6 +184,7 @@ fn current_timestamp_ms() -> u64 {
mod tests {
use super::*;
use std::fs;
use std::path::Component;
use uuid::Uuid;
struct TestDirectory(PathBuf);
@@ -279,7 +284,7 @@ mod tests {
let store = TerminalScopeStore::new(&root.0);
let path = root
.0
.join(format!("{}.json", encode_key_as_hex("request")));
.join(format!("{}.json", encode_key_for_path("request")));
fs::write(path, "{").expect("write malformed scope");
assert!(store.get("request").is_err());
}
@@ -296,6 +301,39 @@ mod tests {
store.get(&key).expect("get long key").unwrap().session_id,
"session-long"
);
// A maximum-length key is 1024 hex characters. Expanding it into the
// path used to exceed the filesystem's total-path limit, so assert on
// the path shape rather than only on the round trip: the store works in
// a short temporary root even when the generated path is unusable.
let record_path = single_record_path(&root.0);
let longest_component = record_path
.components()
.filter_map(|component| match component {
Component::Normal(part) => Some(part.to_string_lossy().len()),
_ => None,
})
.max()
.expect("record path has a component");
assert!(
longest_component <= 255,
"path component must stay within the filesystem filename limit, got {longest_component}"
);
assert!(
record_path.as_os_str().len() < 1024,
"record path must stay within the APFS total-path limit, got {} bytes",
record_path.as_os_str().len()
);
}
/// Returns the single record file under a store root.
fn single_record_path(root: &std::path::Path) -> PathBuf {
let entries = fs::read_dir(root)
.expect("read store root")
.collect::<Result<Vec<_>, _>>()
.expect("read store entries");
assert_eq!(entries.len(), 1, "store should hold exactly one record");
entries[0].path()
}
#[test]
+3
View File
@@ -20,5 +20,8 @@ aspect-macros = "0.1"
aspect-std = "0.1"
log = "0.4"
[dev-dependencies]
mock-anthropic-service = { path = "../mock-anthropic-service" }
[lints]
workspace = true
File diff suppressed because it is too large. Load diff