Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| edf2f8e03c | |||
| 80c1fc6a69 | |||
|
|
3f87b19a2d | ||
|
|
f52eef1657 | ||
|
|
e80e522c10 | ||
| 9d0f4b400c | |||
| 2a65c4e7a2 | |||
| 42a157b049 | |||
| c47597b421 | |||
| 61cc59d9a0 | |||
|
|
0282244114 | ||
|
|
51982b7f63 | ||
|
|
254cf83d9d | ||
|
|
8331859537 | ||
|
|
6e87cf2e6c | ||
|
|
549962cb8a | ||
|
|
7d4c1bf56e | ||
|
|
8fb8b5a71d | ||
|
|
f242290ca5 | ||
|
|
481428a7ce | ||
|
|
e17ef16d48 | ||
|
|
c1cc349b19 | ||
|
|
6982cbca7e | ||
|
|
7f3a46313e | ||
|
|
9143d2c5e2 | ||
|
|
79792eea85 |
25 changed files with 4994 additions and 93 deletions
139
Cargo.lock
generated
139
Cargo.lock
generated
|
|
@ -73,6 +73,12 @@ version = "0.22.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "base64"
|
||||||
|
version = "0.23.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64ct"
|
name = "base64ct"
|
||||||
version = "1.8.3"
|
version = "1.8.3"
|
||||||
|
|
@ -94,6 +100,12 @@ version = "3.20.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytes"
|
||||||
|
version = "1.12.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.4.4"
|
version = "1.4.4"
|
||||||
|
|
@ -139,16 +151,19 @@ name = "claude-connector"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"chrono",
|
||||||
"cultcache-rs",
|
"cultcache-rs",
|
||||||
"hmac",
|
"hmac",
|
||||||
"libc",
|
"libc",
|
||||||
"model-connector",
|
"model-connector",
|
||||||
|
"rand_core 0.6.4",
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
"rmpv",
|
"rmpv",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"ureq",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -230,7 +245,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f111
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64 0.22.1",
|
||||||
"chrono",
|
"chrono",
|
||||||
"cultcache-rs",
|
"cultcache-rs",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
|
|
@ -435,6 +450,22 @@ dependencies = [
|
||||||
"digest",
|
"digest",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "http"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"itoa",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "httparse"
|
||||||
|
version = "1.10.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "iana-time-zone"
|
name = "iana-time-zone"
|
||||||
version = "0.1.65"
|
version = "0.1.65"
|
||||||
|
|
@ -509,7 +540,7 @@ version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64 0.22.1",
|
||||||
"cultcache-rs",
|
"cultcache-rs",
|
||||||
"cultnet-rs",
|
"cultnet-rs",
|
||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
|
|
@ -554,6 +585,12 @@ version = "0.3.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "percent-encoding"
|
||||||
|
version = "2.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pin-project-lite"
|
name = "pin-project-lite"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
|
|
@ -698,6 +735,20 @@ dependencies = [
|
||||||
"syn 3.0.4",
|
"syn 3.0.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ring"
|
||||||
|
version = "0.17.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"getrandom 0.2.17",
|
||||||
|
"libc",
|
||||||
|
"untrusted",
|
||||||
|
"windows-sys 0.52.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rmp"
|
name = "rmp"
|
||||||
version = "0.8.15"
|
version = "0.8.15"
|
||||||
|
|
@ -737,6 +788,41 @@ dependencies = [
|
||||||
"semver",
|
"semver",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls"
|
||||||
|
version = "0.23.46"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"once_cell",
|
||||||
|
"ring",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"rustls-webpki",
|
||||||
|
"subtle",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls-pki-types"
|
||||||
|
version = "1.16.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||||
|
dependencies = [
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls-webpki"
|
||||||
|
version = "0.103.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
|
||||||
|
dependencies = [
|
||||||
|
"ring",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"untrusted",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustversion"
|
name = "rustversion"
|
||||||
version = "1.0.23"
|
version = "1.0.23"
|
||||||
|
|
@ -984,6 +1070,46 @@ dependencies = [
|
||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "untrusted"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ureq"
|
||||||
|
version = "3.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.22.1",
|
||||||
|
"log",
|
||||||
|
"percent-encoding",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"ureq-proto",
|
||||||
|
"utf8-zero",
|
||||||
|
"webpki-roots",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ureq-proto"
|
||||||
|
version = "0.6.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.23.1",
|
||||||
|
"http",
|
||||||
|
"httparse",
|
||||||
|
"log",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf8-zero"
|
||||||
|
version = "0.8.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.25.0"
|
version = "1.25.0"
|
||||||
|
|
@ -1061,6 +1187,15 @@ dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "webpki-roots"
|
||||||
|
version = "1.0.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
|
||||||
|
dependencies = [
|
||||||
|
"rustls-pki-types",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winapi"
|
name = "winapi"
|
||||||
version = "0.3.9"
|
version = "0.3.9"
|
||||||
|
|
|
||||||
31
README.md
31
README.md
|
|
@ -5,12 +5,12 @@ between a caller that needs a model turn and a daemon that holds the provider
|
||||||
credential, so no project wires its own provider calls.
|
credential, so no project wires its own provider calls.
|
||||||
|
|
||||||
The connector meters nothing in dollars. It holds the subscription token, lends it, and
|
The connector meters nothing in dollars. It holds the subscription token, lends it, and
|
||||||
publishes the plan's usage windows (`usage_readout`, and `plan_quota` on every lease grant) for the
|
publishes the plan's usage windows (`usage_readout`, `claude_usage_readout` on the lease socket, and `plan_quota` on every lease grant) for the
|
||||||
minds to read and decide their own burn. The one usage-derived refusal is the provider's own
|
minds to read and decide their own burn. The one usage-derived refusal is the provider's own
|
||||||
(`ProviderRejected`), repeated until its reset.
|
(`ProviderRejected`), repeated until its reset.
|
||||||
|
|
||||||
Status: the `model-connector` crate and the `claude-connector` backend crate are live. No
|
Status: the `model-connector` crate and the `claude-connector` backend crate and binary are live
|
||||||
connector binary exists yet (the Claude connector binary is first, then an OpenAI-compatible one).
|
(`claude-connector serve|config|ask`); an OpenAI-compatible connector is not written.
|
||||||
|
|
||||||
## Entry points
|
## Entry points
|
||||||
|
|
||||||
|
|
@ -40,7 +40,7 @@ Crate `crates/model-connector`:
|
||||||
`ProviderBackend` trait. A connector binary implements `ProviderBackend` for its
|
`ProviderBackend` trait. A connector binary implements `ProviderBackend` for its
|
||||||
provider and calls `serve`; the kit names no provider.
|
provider and calls `serve`; the kit names no provider.
|
||||||
|
|
||||||
Crate `crates/claude-connector` (library only; the binary that wires it to `serve` is not written):
|
Crate `crates/claude-connector` (library and the `claude-connector` binary that wires it to `serve`):
|
||||||
|
|
||||||
- `ClaudeCodeBackend` implements `ProviderBackend` for provider `claude-code` by driving the
|
- `ClaudeCodeBackend` implements `ProviderBackend` for provider `claude-code` by driving the
|
||||||
unmodified `claude` binary, one child per call, in print stream-json mode with no tools, no MCP
|
unmodified `claude` binary, one child per call, in print stream-json mode with no tools, no MCP
|
||||||
|
|
@ -50,12 +50,31 @@ Crate `crates/claude-connector` (library only; the binary that wires it to `serv
|
||||||
- Reasoning state is a session handle (`ClaudeCodeHandle`) authenticated with a connector secret
|
- Reasoning state is a session handle (`ClaudeCodeHandle`) authenticated with a connector secret
|
||||||
and bound to the caller it was minted for; a handle that cannot be proven to match the request
|
and bound to the caller it was minted for; a handle that cannot be proven to match the request
|
||||||
and its caller re-seeds from the caller's transcript, and every resume forks.
|
and its caller re-seeds from the caller's transcript, and every resume forks.
|
||||||
|
- `MessagesBackend` implements `ProviderBackend` for provider `anthropic-messages` when the config document says `auth` is an API key (`config init --auth api-key`; one choice for the whole connector, held in the credential `--token-credential` names). One non-streaming `POST /v1/messages` per call: tools, tool calls and results, thinking blocks (replayed unchanged as reasoning state), `cache_control` (5 minutes, or 1 hour for long retention) and cache read and write usage map natively. The key is read from the systemd credential at every call and travels only as the `x-api-key` header. A request's output schema is `output_config.format`; `Required` tool choice is `tool_choice: any` where the model accepts it and a refusal before sending where it does not (the current Sonnet and Opus reject it). A key has no plan: no meter runs, the plan windows stay empty, and a key document refuses leases.
|
||||||
- `ProcessPort` is the one OS seam (`StdProcessPort`, unix, kills the child's whole process
|
- `ProcessPort` is the one OS seam (`StdProcessPort`, unix, kills the child's whole process
|
||||||
group); `SessionStore` and `StderrSink` are the other ports. `ClaudeCodeConfig` is what the
|
group); `SessionStore` and `StderrSink` are the other ports. `ClaudeCodeConfig` is what the
|
||||||
binary hands in; the credential is read from a systemd credential and reaches the child on a
|
binary hands in; the subscription token is read from a systemd credential and reaches the child on a
|
||||||
pipe (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`), never in an environment. `QuotaCell` keeps the
|
pipe, never in an environment (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`). `QuotaCell` keeps the
|
||||||
plan windows the CLI's `rate_limit_event`s report, for the usage readout and the lease grant.
|
plan windows the CLI's `rate_limit_event`s report, for the usage readout and the lease grant.
|
||||||
|
|
||||||
|
## Asking for one no-tools completion
|
||||||
|
|
||||||
|
`claude-connector ask` is a caller of a running connector for a Mind's Self run: the prompt is all
|
||||||
|
of stdin, the answer text is stdout.
|
||||||
|
|
||||||
|
```
|
||||||
|
claude-connector ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] < prompt > answer
|
||||||
|
```
|
||||||
|
|
||||||
|
Defaults: endpoint `127.0.0.1:4110`, 8192 output tokens, 300 s. The key is read from the file (the
|
||||||
|
same text the connector reads for the caller; never argv or environment). There is no tools flag,
|
||||||
|
no working-directory flag and no other endpoint: the request is built by `ProviderRequest::new`
|
||||||
|
(no tools) and the model child's cwd and environment stay the connector's. Any failure (refused,
|
||||||
|
over a cap, model not allowed, wrong key or caller, timeout, provider failure, empty answer, empty
|
||||||
|
stdin) exits nonzero with one `claude-connector: <cause>` line on stderr and nothing on stdout;
|
||||||
|
the line never carries the key, the prompt or the provider's message. Each run uses a fresh request
|
||||||
|
id. Code: `crates/claude-connector/src/ask.rs`; tests: `crates/claude-connector/tests/ask.rs`.
|
||||||
|
|
||||||
Frame arithmetic is public in `src/envelope.rs`, measured on the carriage frame: `frame_bytes_for_payload(n)` is the frame a
|
Frame arithmetic is public in `src/envelope.rs`, measured on the carriage frame: `frame_bytes_for_payload(n)` is the frame a
|
||||||
caller payload bound of `n` needs, `payload_bytes_for_frame(frame)` is the largest payload bound
|
caller payload bound of `n` needs, `payload_bytes_for_frame(frame)` is the largest payload bound
|
||||||
a frame allows, and `MAX_IDENTITY_BYTES` (256) bounds caller ids, request ids and model names.
|
a frame allows, and `MAX_IDENTITY_BYTES` (256) bounds caller ids, request ids and model names.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "claude-connector"
|
name = "claude-connector"
|
||||||
description = "Claude backend for the connector kit: drives the unmodified claude binary in print stream-json mode"
|
description = "Claude backends for the connector kit: the claude CLI on a subscription token, the Messages API on an API key"
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
@ -13,14 +13,17 @@ path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
|
chrono = { version = "0.4", default-features = false }
|
||||||
hmac = "0.12"
|
hmac = "0.12"
|
||||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "a4eae9056152335662f1115f97bf35fb00ab6d23", package = "cultcache-rs" }
|
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "a4eae9056152335662f1115f97bf35fb00ab6d23", package = "cultcache-rs" }
|
||||||
model-connector = { path = "../model-connector", features = ["daemon"] }
|
model-connector = { path = "../model-connector", features = ["daemon"] }
|
||||||
|
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||||
rmp-serde = "1"
|
rmp-serde = "1"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
|
ureq = { version = "~3.3", default-features = false, features = ["rustls"] }
|
||||||
zeroize = "1"
|
zeroize = "1"
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
|
|
||||||
336
crates/claude-connector/src/ask.rs
Normal file
336
crates/claude-connector/src/ask.rs
Normal file
|
|
@ -0,0 +1,336 @@
|
||||||
|
//! `claude-connector ask`: one no-tools completion through a running connector.
|
||||||
|
//!
|
||||||
|
//! A thin caller over [`ConnectorClient`]. It builds a [`ProviderRequest`] with
|
||||||
|
//! `ProviderRequest::new`, which carries no tools, and has no field, flag or
|
||||||
|
//! path by which a caller could add one; the working directory and environment
|
||||||
|
//! of the model child belong to the connector. Every failure is an
|
||||||
|
//! [`AskError`] whose text names a cause and never echoes the key, the prompt
|
||||||
|
//! or the instructions.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use model_connector::{
|
||||||
|
ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest,
|
||||||
|
ReasoningEffort, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation,
|
||||||
|
TransportOutcome, TransportResult, frame_bytes_for_payload, provider_request_sha256,
|
||||||
|
};
|
||||||
|
use rand_core::{OsRng, RngCore};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// The loopback endpoint a claude connector listens on.
|
||||||
|
pub const DEFAULT_ENDPOINT: &str = "127.0.0.1:4110";
|
||||||
|
/// The payload bound the connector's own `config init` defaults to.
|
||||||
|
pub const PAYLOAD_BYTES: usize = 1 << 20;
|
||||||
|
const MAX_KEY_BYTES: usize = 1024;
|
||||||
|
pub const MAX_SYSTEM_BYTES: usize = 64 * 1024;
|
||||||
|
|
||||||
|
pub struct AskArgs {
|
||||||
|
pub endpoint: SocketAddr,
|
||||||
|
pub caller_id: String,
|
||||||
|
pub key_file: std::path::PathBuf,
|
||||||
|
pub model: String,
|
||||||
|
pub instructions: String,
|
||||||
|
pub effort: Option<ReasoningEffort>,
|
||||||
|
pub max_output_tokens: u32,
|
||||||
|
pub timeout: Duration,
|
||||||
|
pub prompt: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum AskError {
|
||||||
|
#[error("the prompt on stdin is empty")]
|
||||||
|
EmptyPrompt,
|
||||||
|
#[error("the prompt on stdin is larger than the {PAYLOAD_BYTES} byte payload bound")]
|
||||||
|
PromptTooLarge,
|
||||||
|
#[error("the instructions are empty")]
|
||||||
|
EmptyInstructions,
|
||||||
|
#[error("the connection key file cannot be read")]
|
||||||
|
KeyUnreadable,
|
||||||
|
#[error("the connection key file is not text")]
|
||||||
|
KeyEncoding,
|
||||||
|
#[error("the connection key file is not a regular file")]
|
||||||
|
KeyNotRegular,
|
||||||
|
#[error("the connection key file is readable by group or world (chmod 600)")]
|
||||||
|
KeyExposed,
|
||||||
|
#[error("the instructions file cannot be read as text from a regular file")]
|
||||||
|
SystemUnreadable,
|
||||||
|
#[error("the instructions file is larger than {MAX_SYSTEM_BYTES} bytes")]
|
||||||
|
SystemTooLarge,
|
||||||
|
#[error("standard input cannot be read")]
|
||||||
|
StdinRead,
|
||||||
|
#[error("standard input is not UTF-8 text")]
|
||||||
|
StdinNotText,
|
||||||
|
#[error("the answer cannot be written to standard output")]
|
||||||
|
StdoutWrite,
|
||||||
|
#[error("nothing is listening at the connector endpoint")]
|
||||||
|
NotListening,
|
||||||
|
#[error(
|
||||||
|
"the connector closed the connection without answering (key, caller or frame not accepted)"
|
||||||
|
)]
|
||||||
|
ClosedWithoutAnswer,
|
||||||
|
#[error("the connection key file is empty or longer than {MAX_KEY_BYTES} bytes")]
|
||||||
|
KeyLength,
|
||||||
|
#[error("the connection key is not usable as a key (surrounding whitespace?)")]
|
||||||
|
KeyUnusable,
|
||||||
|
#[error("the request is invalid for the connector contract")]
|
||||||
|
Request,
|
||||||
|
#[error("timed out waiting for the connector")]
|
||||||
|
Timeout,
|
||||||
|
#[error("the connector connection failed: {0}")]
|
||||||
|
Connection(std::io::ErrorKind),
|
||||||
|
#[error("the connector answer was not accepted (wrong key, caller or tampered frame): {0}")]
|
||||||
|
Transport(model_connector::ServiceError),
|
||||||
|
#[error("the request exceeded a frame bound")]
|
||||||
|
FrameSize,
|
||||||
|
#[error("the connector refused the request: {0:?}")]
|
||||||
|
Refused(model_connector::Refusal),
|
||||||
|
#[error("the provider failed: {0:?}")]
|
||||||
|
Failed(FailureKind),
|
||||||
|
#[error("the answer stopped as {0:?}, not a completed text")]
|
||||||
|
NotCompleted(StopReason),
|
||||||
|
#[error("the answer carried a tool call, which this command never requests")]
|
||||||
|
ToolCall,
|
||||||
|
#[error("the answer is empty")]
|
||||||
|
EmptyAnswer,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ReadFailure {
|
||||||
|
Unreadable,
|
||||||
|
NotRegular,
|
||||||
|
TooLarge,
|
||||||
|
Exposed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens `path` without blocking (a FIFO must not hang the open), requires the
|
||||||
|
/// opened file to be a regular file (a symlink is followed and its target
|
||||||
|
/// judged), optionally refuses one readable by group or world, and reads at
|
||||||
|
/// most `cap` bytes, failing if there are more.
|
||||||
|
fn read_regular(path: &Path, cap: usize, private: bool) -> Result<Zeroizing<Vec<u8>>, ReadFailure> {
|
||||||
|
use std::io::Read;
|
||||||
|
let mut options = std::fs::OpenOptions::new();
|
||||||
|
options.read(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
options.custom_flags(libc::O_NONBLOCK);
|
||||||
|
}
|
||||||
|
let file = options.open(path).map_err(|_| ReadFailure::Unreadable)?;
|
||||||
|
let metadata = file.metadata().map_err(|_| ReadFailure::Unreadable)?;
|
||||||
|
if !metadata.is_file() {
|
||||||
|
return Err(ReadFailure::NotRegular);
|
||||||
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
if private && metadata.permissions().mode() & 0o077 != 0 {
|
||||||
|
return Err(ReadFailure::Exposed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut bytes = Zeroizing::new(Vec::new());
|
||||||
|
file.take(cap as u64 + 1)
|
||||||
|
.read_to_end(&mut bytes)
|
||||||
|
.map_err(|_| ReadFailure::Unreadable)?;
|
||||||
|
if bytes.len() > cap {
|
||||||
|
return Err(ReadFailure::TooLarge);
|
||||||
|
}
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the key as the connector reads its own key file (the text without the
|
||||||
|
/// trailing line ending). The bytes are zeroized on drop and never shown.
|
||||||
|
pub fn read_key(path: &Path) -> Result<Zeroizing<String>, AskError> {
|
||||||
|
let raw = read_regular(path, MAX_KEY_BYTES, true).map_err(|failure| match failure {
|
||||||
|
ReadFailure::Unreadable => AskError::KeyUnreadable,
|
||||||
|
ReadFailure::NotRegular => AskError::KeyNotRegular,
|
||||||
|
ReadFailure::TooLarge => AskError::KeyLength,
|
||||||
|
ReadFailure::Exposed => AskError::KeyExposed,
|
||||||
|
})?;
|
||||||
|
let text = std::str::from_utf8(raw.as_slice()).map_err(|_| AskError::KeyEncoding)?;
|
||||||
|
let key = Zeroizing::new(text.trim_end_matches(['\r', '\n']).to_string());
|
||||||
|
if key.is_empty() || key.len() > MAX_KEY_BYTES {
|
||||||
|
return Err(AskError::KeyLength);
|
||||||
|
}
|
||||||
|
if key.trim() != key.as_str() {
|
||||||
|
return Err(AskError::KeyUnusable);
|
||||||
|
}
|
||||||
|
Ok(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The instructions file: a regular file of at most [`MAX_SYSTEM_BYTES`] of text.
|
||||||
|
pub fn read_system_file(path: &Path) -> Result<String, AskError> {
|
||||||
|
let raw = read_regular(path, MAX_SYSTEM_BYTES, false).map_err(|failure| match failure {
|
||||||
|
ReadFailure::TooLarge => AskError::SystemTooLarge,
|
||||||
|
_ => AskError::SystemUnreadable,
|
||||||
|
})?;
|
||||||
|
String::from_utf8(raw.to_vec()).map_err(|_| AskError::SystemUnreadable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fresh_id(prefix: &str) -> String {
|
||||||
|
let mut nonce = [0_u8; 16];
|
||||||
|
OsRng.fill_bytes(&mut nonce);
|
||||||
|
let hex: String = nonce.iter().map(|b| format!("{b:02x}")).collect();
|
||||||
|
format!("{prefix}-{hex}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one invocation `ask` ever sends: instructions, one user text, no tools.
|
||||||
|
pub fn build_invocation(args: &AskArgs) -> Result<TransportInvocation, AskError> {
|
||||||
|
if args.prompt.trim().is_empty() {
|
||||||
|
return Err(AskError::EmptyPrompt);
|
||||||
|
}
|
||||||
|
if args.prompt.len() > PAYLOAD_BYTES {
|
||||||
|
return Err(AskError::PromptTooLarge);
|
||||||
|
}
|
||||||
|
if args.instructions.trim().is_empty() {
|
||||||
|
return Err(AskError::EmptyInstructions);
|
||||||
|
}
|
||||||
|
let mut request = ProviderRequest::new(
|
||||||
|
fresh_id("ask"),
|
||||||
|
fresh_id("ask-conversation"),
|
||||||
|
args.model.clone(),
|
||||||
|
args.instructions.clone(),
|
||||||
|
args.max_output_tokens,
|
||||||
|
);
|
||||||
|
request.input = vec![InputItem::UserText {
|
||||||
|
text: args.prompt.clone(),
|
||||||
|
}];
|
||||||
|
request.reasoning_effort = args.effort;
|
||||||
|
let digest = provider_request_sha256(&request).map_err(|_| AskError::Request)?;
|
||||||
|
let now = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map_or(0, |d| d.as_millis() as u64);
|
||||||
|
let invocation =
|
||||||
|
TransportInvocation::new(args.caller_id.clone(), now + 120_000, digest, request)
|
||||||
|
.map_err(|_| AskError::Request)?;
|
||||||
|
invocation
|
||||||
|
.validate(now, 300_000)
|
||||||
|
.map_err(|_| AskError::Request)?;
|
||||||
|
Ok(invocation)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The answer text of a result, or the one cause it is not an answer.
|
||||||
|
pub fn answer_text(result: &TransportResult) -> Result<String, AskError> {
|
||||||
|
let (events, receipt) = match &result.disposition {
|
||||||
|
TransportDisposition::Refused(reason) => return Err(AskError::Refused(reason.clone())),
|
||||||
|
TransportDisposition::Transported { events, receipt } => (events, receipt),
|
||||||
|
};
|
||||||
|
match &receipt.outcome {
|
||||||
|
TransportOutcome::Failed { kind, .. } => return Err(AskError::Failed(*kind)),
|
||||||
|
TransportOutcome::Completed { stop_reason, .. } => {
|
||||||
|
if !matches!(stop_reason, StopReason::EndTurn | StopReason::StopSequence) {
|
||||||
|
return Err(AskError::NotCompleted(*stop_reason));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut text = String::new();
|
||||||
|
for event in events {
|
||||||
|
match &event.payload {
|
||||||
|
TransportEventPayload::TextDelta { text: delta } => text.push_str(delta),
|
||||||
|
TransportEventPayload::ToolCall { .. } => return Err(AskError::ToolCall),
|
||||||
|
TransportEventPayload::ReasoningState { .. } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
return Err(AskError::EmptyAnswer);
|
||||||
|
}
|
||||||
|
Ok(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ask(args: &AskArgs) -> Result<String, AskError> {
|
||||||
|
let invocation = build_invocation(args)?;
|
||||||
|
let key = read_key(&args.key_file)?;
|
||||||
|
let client = ConnectorClient::new(
|
||||||
|
args.endpoint,
|
||||||
|
key.as_str(),
|
||||||
|
frame_bytes_for_payload(PAYLOAD_BYTES),
|
||||||
|
Some(args.timeout),
|
||||||
|
)
|
||||||
|
.map_err(|error| match error {
|
||||||
|
ConnectorClientError::Transport(_) => AskError::KeyUnusable,
|
||||||
|
_ => AskError::Request,
|
||||||
|
})?;
|
||||||
|
let result = client.execute(&invocation).map_err(|error| match error {
|
||||||
|
ConnectorClientError::Connection(io)
|
||||||
|
if matches!(
|
||||||
|
io.kind(),
|
||||||
|
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
AskError::Timeout
|
||||||
|
}
|
||||||
|
ConnectorClientError::Connection(io) => match io.kind() {
|
||||||
|
std::io::ErrorKind::ConnectionRefused => AskError::NotListening,
|
||||||
|
std::io::ErrorKind::UnexpectedEof
|
||||||
|
| std::io::ErrorKind::ConnectionReset
|
||||||
|
| std::io::ErrorKind::BrokenPipe => AskError::ClosedWithoutAnswer,
|
||||||
|
kind => AskError::Connection(kind),
|
||||||
|
},
|
||||||
|
ConnectorClientError::Transport(error) => AskError::Transport(error),
|
||||||
|
ConnectorClientError::FrameSize => AskError::FrameSize,
|
||||||
|
ConnectorClientError::InvalidConfig | ConnectorClientError::RequestIdTooLong => {
|
||||||
|
AskError::Request
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
answer_text(&result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
||||||
|
use crate::handle::{SessionStore, plan};
|
||||||
|
use model_connector::ToolDefinition;
|
||||||
|
|
||||||
|
struct NoSessions;
|
||||||
|
impl SessionStore for NoSessions {
|
||||||
|
fn exists(&self, _: &str) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn args() -> AskArgs {
|
||||||
|
AskArgs {
|
||||||
|
endpoint: DEFAULT_ENDPOINT.parse().unwrap(),
|
||||||
|
caller_id: "c".into(),
|
||||||
|
key_file: "/nonexistent".into(),
|
||||||
|
model: "m".into(),
|
||||||
|
instructions: "i".into(),
|
||||||
|
effort: None,
|
||||||
|
max_output_tokens: 16,
|
||||||
|
timeout: Duration::from_secs(1),
|
||||||
|
prompt: "p".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The claude backend's own planner accepts what `ask` builds and refuses
|
||||||
|
/// the same request once a tool is forced into it.
|
||||||
|
#[test]
|
||||||
|
fn the_backend_planner_refuses_a_forced_tool_and_accepts_the_asked_request() {
|
||||||
|
let config = ClaudeCodeConfig {
|
||||||
|
claude_binary: "/claude".into(),
|
||||||
|
claude_binary_sha256: [0; 32],
|
||||||
|
work_dir: "/w".into(),
|
||||||
|
config_dir: "/c".into(),
|
||||||
|
prompt_dir: "/p".into(),
|
||||||
|
token_credential: "t".into(),
|
||||||
|
handle_secret_credential: "h".into(),
|
||||||
|
instance: "i".into(),
|
||||||
|
limits: ClaudeCodeLimits {
|
||||||
|
deadline: Duration::from_secs(1),
|
||||||
|
max_line_bytes: 1024,
|
||||||
|
max_total_bytes: 4096,
|
||||||
|
stderr_tail_bytes: 64,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let mut request = build_invocation(&args()).unwrap().request;
|
||||||
|
let secret = [7_u8; 32];
|
||||||
|
assert!(plan(&request, &config, &secret, "c", &NoSessions).is_ok());
|
||||||
|
request.tools.push(ToolDefinition {
|
||||||
|
name: "t".into(),
|
||||||
|
description: "d".into(),
|
||||||
|
parameters_json: "{}".into(),
|
||||||
|
});
|
||||||
|
assert!(plan(&request, &config, &secret, "c", &NoSessions).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -20,6 +20,12 @@ use crate::process::{ProcessPort, RunningChild, StdoutRead};
|
||||||
use crate::quota::QuotaCell;
|
use crate::quota::QuotaCell;
|
||||||
use crate::stream::{Failure, Finished, Step, StreamState};
|
use crate::stream::{Failure, Finished, Step, StreamState};
|
||||||
|
|
||||||
|
/// The meter's call: the cheapest model, a trivial prompt, and an answer cap
|
||||||
|
/// that only bounds a runaway.
|
||||||
|
const METER_MODEL: &str = "claude-haiku-5-5";
|
||||||
|
const METER_CALLER: &str = "meter";
|
||||||
|
const METER_MAX_OUTPUT_TOKENS: u32 = 16;
|
||||||
|
|
||||||
/// Where the child's credential comes from, read afresh at every use. The
|
/// Where the child's credential comes from, read afresh at every use. The
|
||||||
/// connector's own environment is never a source (ruling
|
/// connector's own environment is never a source (ruling
|
||||||
/// claude-connector-token-credential).
|
/// claude-connector-token-credential).
|
||||||
|
|
@ -156,16 +162,40 @@ impl ClaudeCodeBackend {
|
||||||
self.quota.clone()
|
self.quota.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The meter's call: the smallest real one, through the same child,
|
||||||
|
/// stream and cell as any other. The stream's `rate_limit_event` is what
|
||||||
|
/// the caller wants; this returns what the call billed, or the failure's
|
||||||
|
/// kind (never its message).
|
||||||
|
pub(crate) fn read_meter(&self) -> Result<Usage, String> {
|
||||||
|
let mut request = ProviderRequest::new(
|
||||||
|
METER_CALLER,
|
||||||
|
METER_CALLER,
|
||||||
|
METER_MODEL,
|
||||||
|
"Reply with the single word ok.",
|
||||||
|
METER_MAX_OUTPUT_TOKENS,
|
||||||
|
);
|
||||||
|
request.input = vec![InputItem::UserText {
|
||||||
|
text: "ok?".to_string(),
|
||||||
|
}];
|
||||||
|
match self.run(&request, METER_CALLER, true).1 {
|
||||||
|
TransportOutcome::Completed { usage, .. } => Ok(usage),
|
||||||
|
TransportOutcome::Failed { kind, .. } => Err(format!("{kind:?}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The one pin check: `ready` and every spawn use it, and nothing caches
|
/// The one pin check: `ready` and every spawn use it, and nothing caches
|
||||||
/// its answer.
|
/// its answer.
|
||||||
fn binary_matches_pin(&self) -> bool {
|
fn binary_matches_pin(&self) -> bool {
|
||||||
binary_matches_pin(&self.config)
|
binary_matches_pin(&self.config)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `ephemeral` leaves no transcript behind: the meter keeps no handle and
|
||||||
|
/// resumes nothing, every other call is resumed by its session.
|
||||||
fn run(
|
fn run(
|
||||||
&self,
|
&self,
|
||||||
request: &ProviderRequest,
|
request: &ProviderRequest,
|
||||||
caller: &str,
|
caller: &str,
|
||||||
|
ephemeral: bool,
|
||||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
let Some(secret) = usable_secret(self.handle_secret.as_ref()) else {
|
let Some(secret) = usable_secret(self.handle_secret.as_ref()) else {
|
||||||
return failed(
|
return failed(
|
||||||
|
|
@ -209,7 +239,7 @@ impl ClaudeCodeBackend {
|
||||||
"claude-code: the system prompt could not be staged",
|
"claude-code: the system prompt could not be staged",
|
||||||
));
|
));
|
||||||
};
|
};
|
||||||
let argv = argv(&self.config, request, &plan, prompt.path());
|
let argv = argv(&self.config, request, &plan, prompt.path(), ephemeral);
|
||||||
let env = child_env(&self.config, request);
|
let env = child_env(&self.config, request);
|
||||||
let deadline = Instant::now() + self.config.limits.deadline;
|
let deadline = Instant::now() + self.config.limits.deadline;
|
||||||
|
|
||||||
|
|
@ -231,7 +261,7 @@ impl ClaudeCodeBackend {
|
||||||
deadline,
|
deadline,
|
||||||
&request.model,
|
&request.model,
|
||||||
request.output_schema_json.as_deref(),
|
request.output_schema_json.as_deref(),
|
||||||
&self.quota,
|
Some(&*self.quota),
|
||||||
);
|
);
|
||||||
child.kill();
|
child.kill();
|
||||||
child.wait();
|
child.wait();
|
||||||
|
|
@ -323,7 +353,7 @@ impl ProviderBackend for ClaudeCodeBackend {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
let (events, outcome) = self.run(call.request(), call.caller_runtime_id());
|
let (events, outcome) = self.run(call.request(), call.caller_runtime_id(), false);
|
||||||
call.transported(events, outcome)
|
call.transported(events, outcome)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -337,7 +367,7 @@ fn read_stream(
|
||||||
deadline: Instant,
|
deadline: Instant,
|
||||||
model: &str,
|
model: &str,
|
||||||
schema: Option<&str>,
|
schema: Option<&str>,
|
||||||
quota: &QuotaCell,
|
quota: Option<&QuotaCell>,
|
||||||
) -> Result<Finished, Failure> {
|
) -> Result<Finished, Failure> {
|
||||||
let mut state = StreamState::new(model, schema, quota);
|
let mut state = StreamState::new(model, schema, quota);
|
||||||
let finished = loop {
|
let finished = loop {
|
||||||
|
|
|
||||||
|
|
@ -674,6 +674,15 @@ fn child_env_is_cleared_and_names_the_token_descriptor_never_the_token() {
|
||||||
assert!(!format!("{result:?}").contains(CANARY_TOKEN));
|
assert!(!format!("{result:?}").contains(CANARY_TOKEN));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_cell_is_fed_and_the_oauth_descriptor_named() {
|
||||||
|
let rig = rig(vec![structured_script()]);
|
||||||
|
rig.run(schema_request());
|
||||||
|
assert!(!quota_of(&rig).windows.is_empty());
|
||||||
|
let seen = rig.seen();
|
||||||
|
assert!(seen.env.iter().any(|(name, _)| name == TOKEN_FD_ENV));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_token_never_reaches_a_message_an_event_or_a_debug_form() {
|
fn the_token_never_reaches_a_message_an_event_or_a_debug_form() {
|
||||||
// A failing run, so a message is built, and the env's own Debug.
|
// A failing run, so a message is built, and the env's own Debug.
|
||||||
|
|
@ -2113,7 +2122,16 @@ fn quota_of(rig: &Rig) -> model_connector::PlanQuotaSnapshot {
|
||||||
|
|
||||||
/// The windows with their observation stamps zeroed, for comparing readings.
|
/// The windows with their observation stamps zeroed, for comparing readings.
|
||||||
fn readings(rig: &Rig) -> Vec<model_connector::PlanQuota> {
|
fn readings(rig: &Rig) -> Vec<model_connector::PlanQuota> {
|
||||||
let mut windows = quota_of(rig).windows;
|
readings_at(rig, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The held windows as of `now` (unix ms), or as of the wall clock when none.
|
||||||
|
fn readings_at(rig: &Rig, now: Option<u64>) -> Vec<model_connector::PlanQuota> {
|
||||||
|
let cell = rig.backend.quota();
|
||||||
|
let mut windows = match now {
|
||||||
|
Some(now) => cell.snapshot_at(now).windows,
|
||||||
|
None => cell.snapshot().windows,
|
||||||
|
};
|
||||||
for window in &mut windows {
|
for window in &mut windows {
|
||||||
window.observed_at_unix_ms = 0;
|
window.observed_at_unix_ms = 0;
|
||||||
}
|
}
|
||||||
|
|
@ -2160,7 +2178,7 @@ fn rate_limit_event_updates_quota_cell() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_rejected_turn_still_reports_its_windows_and_a_bad_window_costs_only_itself() {
|
fn a_rejected_turn_still_reports_its_windows_and_a_bad_window_costs_only_itself() {
|
||||||
let event = r#"{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","unifiedWindows":{"five_hour":{"utilization":0.9996,"resetsAt":4102444800,"status":"rejected"},"seven_day":{"resetsAt":4102531200,"status":"allowed"},"idle":{"utilization":0,"resetsAt":4102444800,"status":"allowed"},"odd":{"utilization":"high","resetsAt":1,"status":"allowed"},"negative":{"utilization":-0.5,"resetsAt":1,"status":"allowed"}}}}"#;
|
let event = r#"{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","unifiedWindows":{"five_hour":{"utilization":0.9996,"resetsAt":4102444800,"status":"rejected"},"seven_day":{"utilization":0,"resetsAt":4102531200,"status":"allowed"},"seven_day_overage_included":{"utilization":1,"resetsAt":4102531200,"status":"rejected"},"idle":{"utilization":0,"resetsAt":4102444800,"status":"allowed"}}}}"#;
|
||||||
let rig = rig(vec![Script::lines(vec![
|
let rig = rig(vec![Script::lines(vec![
|
||||||
init_line(MODEL, SESSION),
|
init_line(MODEL, SESSION),
|
||||||
event.to_string(),
|
event.to_string(),
|
||||||
|
|
@ -2170,12 +2188,12 @@ fn a_rejected_turn_still_reports_its_windows_and_a_bad_window_costs_only_itself(
|
||||||
assert_eq!(kind, FailureKind::RateLimited);
|
assert_eq!(kind, FailureKind::RateLimited);
|
||||||
let mut rejected = window("five_hour", 1000, 4_102_444_800_000);
|
let mut rejected = window("five_hour", 1000, 4_102_444_800_000);
|
||||||
rejected.status = "rejected".to_string();
|
rejected.status = "rejected".to_string();
|
||||||
// Unknown is never zero: a window missing a field or of another type is
|
// A window at exactly zero use is a reading, and is kept. Only the two
|
||||||
// skipped, not read as empty.
|
// windows pacing reads are taken: a per-model bucket that reads rejected
|
||||||
// A window at exactly zero use is a reading, and is kept.
|
// must not close every lease, and no other name is a window of the plan.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
readings(&rig),
|
readings(&rig),
|
||||||
vec![rejected, window("idle", 0, 4_102_444_800_000)]
|
vec![rejected, window("seven_day", 0, 4_102_531_200_000)]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2746,3 +2764,48 @@ fn a_turn_after_a_schema_turn_is_seeded_not_resumed() {
|
||||||
assert!(!argv.iter().any(|a| a == "--resume"), "{argv:?}");
|
assert!(!argv.iter().any(|a| a == "--resume"), "{argv:?}");
|
||||||
assert!(!argv.iter().any(|a| a == "--json-schema"));
|
assert!(!argv.iter().any(|a| a == "--json-schema"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- the meter's call ----
|
||||||
|
|
||||||
|
/// One real call of the pinned CLI (2.1.312), captured on Yggdrasil on
|
||||||
|
/// 2026-11-03 with the connector's own argv: haiku, no tools, the trivial
|
||||||
|
/// prompt. Its `rate_limit_event` names only the week.
|
||||||
|
const METER_CALL: &str = include_str!("../../tests/fixtures/claude-2.1.312-meter-call.jsonl");
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_meter_call_reads_the_week_from_a_real_captured_event() {
|
||||||
|
let rig = rig(vec![Script::lines(
|
||||||
|
METER_CALL.lines().map(str::to_string).collect(),
|
||||||
|
)]);
|
||||||
|
let usage = rig
|
||||||
|
.backend
|
||||||
|
.read_meter()
|
||||||
|
.expect("the captured call completes");
|
||||||
|
assert_eq!((usage.input_tokens, usage.output_tokens), (384, 4));
|
||||||
|
// 0.06 of the week used; it resets at 1794261600 (unix s). Read as of an instant before
|
||||||
|
// that reset, so the captured event stays a live reading whatever the wall clock says.
|
||||||
|
assert_eq!(
|
||||||
|
readings_at(&rig, Some(1_794_261_600_000 - 1)),
|
||||||
|
vec![window("seven_day", 60, 1_794_261_600_000)]
|
||||||
|
);
|
||||||
|
let argv = rig.seen().argv;
|
||||||
|
let after = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
|
||||||
|
assert_eq!(after("--model"), METER_MODEL);
|
||||||
|
assert_eq!(after("--tools"), "", "the call can use no tool");
|
||||||
|
assert!(
|
||||||
|
argv.iter().any(|a| a == "--no-session-persistence"),
|
||||||
|
"the meter's transcript is nobody's to keep: {argv:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(rig.spawns(), 1, "one child, never run again");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failed_meter_call_names_its_kind_and_leaves_the_cell_alone() {
|
||||||
|
let rig = rig(vec![Script::lines(vec![
|
||||||
|
init_line(MODEL, SESSION),
|
||||||
|
error_result_line(r#","api_error_status":500"#),
|
||||||
|
])]);
|
||||||
|
let failed = rig.backend.read_meter().expect_err("the call fails");
|
||||||
|
assert!(!failed.is_empty() && !failed.contains(' '), "{failed}");
|
||||||
|
assert!(quota_of(&rig).windows.is_empty());
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,27 @@
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// The provider tag the kit puts on every receipt and on the reasoning state
|
/// The provider tag the kit puts on every receipt and on the reasoning state
|
||||||
/// of this backend. It is distinct from any Messages-API backend's tag, so the
|
/// of the CLI backend. It is distinct from the Messages backend's tag, so the
|
||||||
/// kit treats each backend's state as foreign to the other.
|
/// kit treats each backend's state as foreign to the other.
|
||||||
pub(crate) const PROVIDER: &str = "claude-code";
|
pub(crate) const PROVIDER: &str = "claude-code";
|
||||||
|
|
||||||
|
/// Which credential the connector authenticates with. One choice for the whole
|
||||||
|
/// connector, held in the systemd credential the config document's
|
||||||
|
/// `token_credential` names.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum ClaudeAuth {
|
||||||
|
/// The subscription's OAuth token, given to the `claude` CLI child by
|
||||||
|
/// [`ClaudeCodeBackend`](crate::ClaudeCodeBackend). The plan's usage is
|
||||||
|
/// metered.
|
||||||
|
OAuthToken,
|
||||||
|
/// An Anthropic API key, used by [`MessagesBackend`](crate::MessagesBackend)
|
||||||
|
/// over HTTP; the CLI is never spawned. Nothing is metered: a key has no
|
||||||
|
/// subscription plan.
|
||||||
|
ApiKey,
|
||||||
|
}
|
||||||
|
|
||||||
/// What the connector's binary hands the backend. Every path is absolute.
|
/// What the connector's binary hands the backend. Every path is absolute.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ClaudeCodeConfig {
|
pub struct ClaudeCodeConfig {
|
||||||
|
|
@ -22,7 +38,7 @@ pub struct ClaudeCodeConfig {
|
||||||
/// A directory the connector owns (mode 0700), where each call's system
|
/// A directory the connector owns (mode 0700), where each call's system
|
||||||
/// prompt is staged for the child.
|
/// prompt is staged for the child.
|
||||||
pub prompt_dir: PathBuf,
|
pub prompt_dir: PathBuf,
|
||||||
/// The name of the systemd credential that holds the child's token, under
|
/// The name of the systemd credential that holds the child's subscription token, under
|
||||||
/// `$CREDENTIALS_DIRECTORY`.
|
/// `$CREDENTIALS_DIRECTORY`.
|
||||||
pub token_credential: String,
|
pub token_credential: String,
|
||||||
/// The name of the systemd credential that holds the handle secret: the
|
/// The name of the systemd credential that holds the handle secret: the
|
||||||
|
|
|
||||||
|
|
@ -22,8 +22,11 @@ use crate::backend::readiness;
|
||||||
use crate::lease::{LeaseCaller, LeaseLimits, serve_leases, user_uid};
|
use crate::lease::{LeaseCaller, LeaseLimits, serve_leases, user_uid};
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
use crate::unit::SystemdUnits;
|
use crate::unit::SystemdUnits;
|
||||||
|
#[cfg(unix)]
|
||||||
|
use crate::meter;
|
||||||
use crate::{
|
use crate::{
|
||||||
ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, StderrSink,
|
ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource,
|
||||||
|
MessagesBackend, MessagesConfig, StderrSink,
|
||||||
};
|
};
|
||||||
|
|
||||||
const CONFIG_KEY: &str = "runtime";
|
const CONFIG_KEY: &str = "runtime";
|
||||||
|
|
@ -104,6 +107,11 @@ pub struct ClaudeConnectorConfig {
|
||||||
/// least 32 bytes), the key every handle is authenticated with.
|
/// least 32 bytes), the key every handle is authenticated with.
|
||||||
#[cultcache(key = 22)]
|
#[cultcache(key = 22)]
|
||||||
pub handle_secret_credential: String,
|
pub handle_secret_credential: String,
|
||||||
|
/// Which credential `token_credential` holds: the subscription token, or an
|
||||||
|
/// Anthropic API key. A document written before this field existed is refused at
|
||||||
|
/// load (the canonical-form check): the installer authors the document again.
|
||||||
|
#[cultcache(key = 23)]
|
||||||
|
pub auth: ClaudeAuth,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A refusal. It names the field or stage that failed and nothing the
|
/// A refusal. It names the field or stage that failed and nothing the
|
||||||
|
|
@ -240,6 +248,13 @@ impl ClaudeConnectorConfig {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_leases(&self) -> Result<(), ConfigError> {
|
fn validate_leases(&self) -> Result<(), ConfigError> {
|
||||||
|
// A key has no plan and is never lent: no lease socket, no lease row, whatever else the
|
||||||
|
// document says. Personas call with their own connection keys and need neither.
|
||||||
|
if self.auth == ClaudeAuth::ApiKey
|
||||||
|
&& (self.lease_socket.is_some() || !self.lease_callers.is_empty())
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid("auth"));
|
||||||
|
}
|
||||||
let Some(socket) = &self.lease_socket else {
|
let Some(socket) = &self.lease_socket else {
|
||||||
return if self.lease_callers.is_empty() {
|
return if self.lease_callers.is_empty() {
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
@ -289,6 +304,14 @@ impl ClaudeConnectorConfig {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn messages_config(&self) -> MessagesConfig {
|
||||||
|
MessagesConfig {
|
||||||
|
key_credential: self.token_credential.clone(),
|
||||||
|
deadline: Duration::from_millis(self.deadline_ms),
|
||||||
|
max_response_bytes: self.max_total_bytes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn serve_limits(&self) -> ServeLimits {
|
fn serve_limits(&self) -> ServeLimits {
|
||||||
ServeLimits {
|
ServeLimits {
|
||||||
max_frame_bytes: self.max_frame_bytes,
|
max_frame_bytes: self.max_frame_bytes,
|
||||||
|
|
@ -434,18 +457,27 @@ impl<W: std::io::Write + Send> StderrSink for LogSink<W> {
|
||||||
/// key and the frame and connection bounds. Returns the admitted callers.
|
/// key and the frame and connection bounds. Returns the admitted callers.
|
||||||
fn readiness_of(config: &ClaudeConnectorConfig) -> Result<Vec<CallerAdmission>, ConfigError> {
|
fn readiness_of(config: &ClaudeConnectorConfig) -> Result<Vec<CallerAdmission>, ConfigError> {
|
||||||
config.validate()?;
|
config.validate()?;
|
||||||
#[cfg(unix)]
|
|
||||||
check_prompt_dir(&config.prompt_dir)?;
|
|
||||||
let admissions = load_admissions(&config.callers)?;
|
let admissions = load_admissions(&config.callers)?;
|
||||||
config.serve_limits().validate(&admissions)?;
|
config.serve_limits().validate(&admissions)?;
|
||||||
let backend = config.backend_config();
|
match config.auth {
|
||||||
readiness(
|
// The CLI is never spawned on a key: its binary, directories and
|
||||||
&backend,
|
// handle secret are not this backend's, only the key is.
|
||||||
&CredentialTokenSource::from_environment(backend.token_credential.clone()),
|
ClaudeAuth::ApiKey => MessagesBackend::new(config.messages_config())
|
||||||
&CredentialTokenSource::from_environment(backend.handle_secret_credential.clone())
|
.ready()
|
||||||
.for_field("handle_secret_credential"),
|
.map_err(ConfigError::Unusable)?,
|
||||||
)
|
ClaudeAuth::OAuthToken => {
|
||||||
.map_err(ConfigError::Unusable)?;
|
#[cfg(unix)]
|
||||||
|
check_prompt_dir(&config.prompt_dir)?;
|
||||||
|
let backend = config.backend_config();
|
||||||
|
readiness(
|
||||||
|
&backend,
|
||||||
|
&CredentialTokenSource::from_environment(backend.token_credential.clone()),
|
||||||
|
&CredentialTokenSource::from_environment(backend.handle_secret_credential.clone())
|
||||||
|
.for_field("handle_secret_credential"),
|
||||||
|
)
|
||||||
|
.map_err(ConfigError::Unusable)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
if config.lease_socket.is_some() {
|
if config.lease_socket.is_some() {
|
||||||
lease_callers_of(config)?;
|
lease_callers_of(config)?;
|
||||||
}
|
}
|
||||||
|
|
@ -535,13 +567,30 @@ pub fn check_ready(config: &ClaudeConnectorConfig) -> Result<(), ConfigError> {
|
||||||
/// Loads the document and serves until the listener fails.
|
/// Loads the document and serves until the listener fails.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
|
pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
|
||||||
|
serve_config_with(path, |_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`serve_config`] handing the quota cell to `started` once the meter runs:
|
||||||
|
/// a test stands in for the swarm's lease requests only through here.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn serve_config_with(
|
||||||
|
path: &Path,
|
||||||
|
started: impl FnOnce(&Arc<crate::QuotaCell>),
|
||||||
|
) -> Result<(), ConfigError> {
|
||||||
let config = load_config(path)?;
|
let config = load_config(path)?;
|
||||||
let admissions = readiness_of(&config)?;
|
let admissions = readiness_of(&config)?;
|
||||||
let listen = config.validate()?;
|
let listen = config.validate()?;
|
||||||
let backend = Arc::new(ClaudeCodeBackend::new(
|
// The CLI backend on a subscription token, the Messages backend on a key.
|
||||||
config.backend_config(),
|
let claude = (config.auth == ClaudeAuth::OAuthToken).then(|| {
|
||||||
Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))),
|
Arc::new(ClaudeCodeBackend::new(
|
||||||
));
|
config.backend_config(),
|
||||||
|
Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
let backend: Arc<dyn ProviderBackend> = match &claude {
|
||||||
|
Some(claude) => claude.clone(),
|
||||||
|
None => Arc::new(MessagesBackend::new(config.messages_config())),
|
||||||
|
};
|
||||||
let listener = TcpListener::bind(listen).map_err(|_| ConfigError::Listen)?;
|
let listener = TcpListener::bind(listen).map_err(|_| ConfigError::Listen)?;
|
||||||
let service = Arc::new(Mutex::new(
|
let service = Arc::new(Mutex::new(
|
||||||
TransportService::open(
|
TransportService::open(
|
||||||
|
|
@ -552,9 +601,20 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
|
||||||
)
|
)
|
||||||
.map_err(|error| ConfigError::from(ServeError::Service(error)))?,
|
.map_err(|error| ConfigError::from(ServeError::Service(error)))?,
|
||||||
));
|
));
|
||||||
|
// The meter is running before the first lease can ask, so that lease can
|
||||||
|
// wait for its first read. An API key has no subscription plan to read:
|
||||||
|
// no meter runs, the cell stays empty, and no lease waits for it.
|
||||||
|
let quota = claude
|
||||||
|
.as_ref()
|
||||||
|
.map_or_else(|| Arc::new(crate::QuotaCell::new()), |claude| claude.quota());
|
||||||
|
if let Some(claude) = &claude {
|
||||||
|
meter::start(quota.clone(), Box::new(claude.clone()))
|
||||||
|
.map_err(|_| ConfigError::Serving("meter"))?;
|
||||||
|
}
|
||||||
|
started("a);
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
if let Some(socket) = &config.lease_socket {
|
if let Some(socket) = &config.lease_socket {
|
||||||
start_leases(&config, socket, service.clone(), backend.quota())?;
|
start_leases(&config, socket, service.clone(), quota.clone())?;
|
||||||
}
|
}
|
||||||
serve_service(listener, config.serve_limits(), service, backend)?;
|
serve_service(listener, config.serve_limits(), service, backend)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
@ -564,6 +624,8 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use sha2::Digest;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
/// A log that a test can read back.
|
/// A log that a test can read back.
|
||||||
|
|
@ -580,6 +642,105 @@ mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `serve` starts the meter beside the listener, wired to the backend's own
|
||||||
|
/// cell: it makes no call while nobody asks, and once a lease is asked for
|
||||||
|
/// it runs the claude binary and serve stays up. The binary is a script
|
||||||
|
/// that replays a real captured call.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn serve_config_starts_the_meter_and_stays_up() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
const CALL: &str = include_str!("../tests/fixtures/claude-2.1.312-meter-call.jsonl");
|
||||||
|
let dir =
|
||||||
|
std::env::temp_dir().join(format!("claude-connector-serve-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let at = |name: &str| dir.join(name);
|
||||||
|
for sub in ["work", "home", "prompts", "credentials"] {
|
||||||
|
std::fs::create_dir_all(at(sub)).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::set_permissions(at("prompts"), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||||
|
std::fs::write(at("call.jsonl"), CALL).unwrap();
|
||||||
|
let script = format!(
|
||||||
|
"#!/bin/sh\ncat > /dev/null\necho spawned >> '{}'\ncat '{}'\n",
|
||||||
|
at("spawned").display(),
|
||||||
|
at("call.jsonl").display()
|
||||||
|
);
|
||||||
|
std::fs::write(at("claude"), &script).unwrap();
|
||||||
|
std::fs::set_permissions(at("claude"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
std::fs::write(at("caller.key"), "k".repeat(48)).unwrap();
|
||||||
|
std::fs::write(at("credentials/claude-token"), "sk-ant-oat01-fake-token").unwrap();
|
||||||
|
std::fs::write(at("credentials/claude-handle-secret"), "s".repeat(48)).unwrap();
|
||||||
|
let config = ClaudeConnectorConfig {
|
||||||
|
listen: "127.0.0.1:0".to_string(),
|
||||||
|
replay_store: at("replay.cc"),
|
||||||
|
claude_binary: at("claude"),
|
||||||
|
claude_binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(),
|
||||||
|
work_dir: at("work"),
|
||||||
|
config_dir: at("home"),
|
||||||
|
prompt_dir: at("prompts"),
|
||||||
|
instance: "persona-a".to_string(),
|
||||||
|
token_credential: "claude-token".to_string(),
|
||||||
|
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||||
|
auth: ClaudeAuth::OAuthToken,
|
||||||
|
deadline_ms: 600_000,
|
||||||
|
max_line_bytes: 4 << 20,
|
||||||
|
max_total_bytes: 64 << 20,
|
||||||
|
stderr_tail_bytes: 8192,
|
||||||
|
max_frame_bytes: 2 << 20,
|
||||||
|
max_connections: 8,
|
||||||
|
socket_timeout_ms: 10_000,
|
||||||
|
max_expiry_skew_ms: 300_000,
|
||||||
|
callers: vec![CallerConfig {
|
||||||
|
caller_runtime_id: "persona-a-caller".to_string(),
|
||||||
|
connection_key_file: at("caller.key"),
|
||||||
|
connection_key_epoch: 1,
|
||||||
|
allowed_models: vec!["claude-haiku-5-5".to_string()],
|
||||||
|
max_concurrent_requests: 4,
|
||||||
|
max_payload_bytes: 1 << 20,
|
||||||
|
max_output_tokens: 32_768,
|
||||||
|
}],
|
||||||
|
lease_socket: None,
|
||||||
|
lease_callers: Vec::new(),
|
||||||
|
lease_max_ms: 3_600_000,
|
||||||
|
};
|
||||||
|
write_config(&at("connector.cc"), &config).unwrap();
|
||||||
|
// SAFETY: set once, to a directory only this test reads, before the
|
||||||
|
// serve thread it starts.
|
||||||
|
unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", at("credentials")) };
|
||||||
|
|
||||||
|
let path = at("connector.cc");
|
||||||
|
let lease = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||||
|
let swarm = lease.clone();
|
||||||
|
let served = std::thread::spawn(move || {
|
||||||
|
serve_config_with(&path, |cell| {
|
||||||
|
*swarm.lock().unwrap() = Some(cell.clone());
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
||||||
|
let cell = loop {
|
||||||
|
if let Some(cell) = lease.lock().unwrap().clone() {
|
||||||
|
break cell;
|
||||||
|
}
|
||||||
|
assert!(std::time::Instant::now() < deadline, "serve never started");
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
};
|
||||||
|
std::thread::sleep(Duration::from_millis(500));
|
||||||
|
assert!(!at("spawned").exists(), "a quiet swarm spends nothing");
|
||||||
|
let _lease = cell.asking();
|
||||||
|
|
||||||
|
while !at("spawned").exists() {
|
||||||
|
assert!(
|
||||||
|
std::time::Instant::now() < deadline,
|
||||||
|
"the meter never ran the claude binary"
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
assert!(!served.is_finished(), "serve returned after starting the meter");
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn serve_errors_name_a_field_or_stage_and_never_a_stored_value() {
|
fn serve_errors_name_a_field_or_stage_and_never_a_stored_value() {
|
||||||
const CANARY: &str = "canary-path-8e2a";
|
const CANARY: &str = "canary-path-8e2a";
|
||||||
|
|
|
||||||
|
|
@ -13,13 +13,13 @@ use model_connector::{ProviderRequest, ReasoningEffort};
|
||||||
use crate::config::ClaudeCodeConfig;
|
use crate::config::ClaudeCodeConfig;
|
||||||
use crate::handle::Plan;
|
use crate::handle::Plan;
|
||||||
|
|
||||||
/// The variable that tells the CLI which file descriptor holds its credential.
|
/// The credential never enters the environment:
|
||||||
/// The token itself never enters the environment: the process port writes it
|
/// the process port writes it into a pipe and hands the child the read end at
|
||||||
/// into a pipe and hands the child the read end at [`TOKEN_FD`].
|
/// [`TOKEN_FD`], the first descriptor after stdin, stdout and stderr, and the
|
||||||
pub(crate) const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
|
/// environment names that descriptor.
|
||||||
/// The descriptor number the child finds the token pipe at: the first one
|
|
||||||
/// after stdin, stdout and stderr.
|
|
||||||
pub(crate) const TOKEN_FD: i32 = 3;
|
pub(crate) const TOKEN_FD: i32 = 3;
|
||||||
|
/// The variable that tells the CLI which descriptor holds the subscription token.
|
||||||
|
const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
|
||||||
const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
|
const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
|
||||||
|
|
||||||
/// The environment of the child: exactly these names and nothing inherited.
|
/// The environment of the child: exactly these names and nothing inherited.
|
||||||
|
|
@ -107,13 +107,15 @@ fn effort(effort: ReasoningEffort) -> &'static str {
|
||||||
/// rather than an argument because one argument is capped near 128 KiB
|
/// rather than an argument because one argument is capped near 128 KiB
|
||||||
/// (E2BIG) and instructions are not, the child has
|
/// (E2BIG) and instructions are not, the child has
|
||||||
/// no tools, no MCP servers, no settings, no slash commands and nobody to ask
|
/// no tools, no MCP servers, no settings, no slash commands and nobody to ask
|
||||||
/// for permission, and a resume always forks. A request's output schema goes
|
/// for permission, and a resume always forks. An ephemeral call (the
|
||||||
/// to the CLI as `--json-schema`; without one the flag is absent.
|
/// meter's) keeps no session on disk. A request's output schema goes to the
|
||||||
|
/// CLI as `--json-schema`; without one the flag is absent.
|
||||||
pub(crate) fn argv(
|
pub(crate) fn argv(
|
||||||
config: &ClaudeCodeConfig,
|
config: &ClaudeCodeConfig,
|
||||||
request: &ProviderRequest,
|
request: &ProviderRequest,
|
||||||
plan: &Plan,
|
plan: &Plan,
|
||||||
system_prompt_file: &Path,
|
system_prompt_file: &Path,
|
||||||
|
ephemeral: bool,
|
||||||
) -> Vec<String> {
|
) -> Vec<String> {
|
||||||
let mut argv: Vec<String> = [
|
let mut argv: Vec<String> = [
|
||||||
config.claude_binary.to_string_lossy().as_ref(),
|
config.claude_binary.to_string_lossy().as_ref(),
|
||||||
|
|
@ -139,6 +141,9 @@ pub(crate) fn argv(
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(str::to_string)
|
.map(str::to_string)
|
||||||
.collect();
|
.collect();
|
||||||
|
if ephemeral {
|
||||||
|
argv.push("--no-session-persistence".to_string());
|
||||||
|
}
|
||||||
if let Some(level) = request.reasoning_effort {
|
if let Some(level) = request.reasoning_effort {
|
||||||
argv.extend(["--effort".to_string(), effort(level).to_string()]);
|
argv.extend(["--effort".to_string(), effort(level).to_string()]);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,10 @@
|
||||||
//! provider's own, repeated until its own reset. Nothing the run says about
|
//! provider's own, repeated until its own reset. Nothing the run says about
|
||||||
//! itself decides who it is or what the plan allows.
|
//! itself decides who it is or what the plan allows.
|
||||||
//!
|
//!
|
||||||
|
//! The same socket also answers a usage readout to any peer that can reach it
|
||||||
|
//! (the claude-lease group): no lease, no caller check, no token read and no
|
||||||
|
//! wake of the meter. Usage is state every Mind reads.
|
||||||
|
//!
|
||||||
//! The token exists in this process only as the value the token source returns
|
//! The token exists in this process only as the value the token source returns
|
||||||
//! and in the pipe. It is not in an environment, an argument, a file, a log or
|
//! and in the pipe. It is not in an environment, an argument, a file, a log or
|
||||||
//! a reply frame. The connector spawns nothing here: the Self run's `claude`
|
//! a reply frame. The connector spawns nothing here: the Self run's `claude`
|
||||||
|
|
@ -27,7 +31,7 @@ use std::thread;
|
||||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use model_connector::{
|
use model_connector::{
|
||||||
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn, PlanQuota, TransportService,
|
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn, PlanQuota, TransportService, UsageReadout,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
@ -48,6 +52,10 @@ pub enum LeaseMessage {
|
||||||
/// holds the token, its write end closed.
|
/// holds the token, its write end closed.
|
||||||
ClaudeLeaseGrant(LeaseGranted),
|
ClaudeLeaseGrant(LeaseGranted),
|
||||||
ClaudeLeaseRefusal(LeaseRefused),
|
ClaudeLeaseRefusal(LeaseRefused),
|
||||||
|
/// Asks for the plan's usage windows. Opens no lease.
|
||||||
|
ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest),
|
||||||
|
/// The answer to a readout request: the cell's windows as of now, no fd.
|
||||||
|
ClaudeUsageReadout(UsageReadout),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A request names only when the lease ends. Who asks is the connector's to know.
|
/// A request names only when the lease ends. Who asks is the connector's to know.
|
||||||
|
|
@ -56,6 +64,10 @@ pub struct LeaseRequest {
|
||||||
pub expires_at_unix_ms: u64,
|
pub expires_at_unix_ms: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A readout request names nothing: the answer is the same for every asker.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct LeaseUsageReadoutRequest {}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct LeaseGranted {
|
pub struct LeaseGranted {
|
||||||
pub lease_id: String,
|
pub lease_id: String,
|
||||||
|
|
@ -383,10 +395,22 @@ struct Lender {
|
||||||
quota: Arc<QuotaCell>,
|
quota: Arc<QuotaCell>,
|
||||||
tokens: Arc<dyn TokenSource>,
|
tokens: Arc<dyn TokenSource>,
|
||||||
units: Arc<dyn PeerUnits>,
|
units: Arc<dyn PeerUnits>,
|
||||||
|
/// Connections holding or waiting on a lease, at most `max_connections`.
|
||||||
|
leases: Arc<AtomicUsize>,
|
||||||
|
/// Connections being answered a readout, at most `READOUT_CONNECTIONS`.
|
||||||
|
readouts: Arc<AtomicUsize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serves leases on `listener` until it fails. Each connection is one lease:
|
/// How many usage readouts are served at once, beside the leases. A readout
|
||||||
/// request, then grant or refusal, then (after a grant) the hold. A caller is
|
/// holds nothing, so a few suffice, and a flood of them cannot take a lease's
|
||||||
|
/// slot: the accept loop admits `max_connections` plus this many.
|
||||||
|
const READOUT_CONNECTIONS: usize = 4;
|
||||||
|
|
||||||
|
/// Serves leases on `listener` until it fails. Each connection is one lease or
|
||||||
|
/// one usage readout. A lease: request, then grant or refusal, then (after a
|
||||||
|
/// grant) the hold. A readout: request, then one frame, then close; its reach
|
||||||
|
/// is the socket's group, and it reads the plan's windows without waking the
|
||||||
|
/// meter. A caller is
|
||||||
/// the account whose uid the kernel reports for the connection, and only a
|
/// the account whose uid the kernel reports for the connection, and only a
|
||||||
/// process in that caller's unit may lease, once per unit invocation for a Self
|
/// process in that caller's unit may lease, once per unit invocation for a Self
|
||||||
/// run and once per turn for a Persona; no
|
/// run and once per turn for a Persona; no
|
||||||
|
|
@ -407,11 +431,14 @@ pub fn serve_leases(
|
||||||
quota,
|
quota,
|
||||||
tokens,
|
tokens,
|
||||||
units,
|
units,
|
||||||
|
leases: Arc::new(AtomicUsize::new(0)),
|
||||||
|
readouts: Arc::new(AtomicUsize::new(0)),
|
||||||
});
|
});
|
||||||
let active = Arc::new(AtomicUsize::new(0));
|
let active = Arc::new(AtomicUsize::new(0));
|
||||||
loop {
|
loop {
|
||||||
let (stream, _) = listener.accept()?;
|
let (stream, _) = listener.accept()?;
|
||||||
let Some(permit) = Permit::acquire(&active, limits.max_connections) else {
|
let admitted = limits.max_connections.saturating_add(READOUT_CONNECTIONS);
|
||||||
|
let Some(permit) = Permit::acquire(&active, admitted) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let lender = lender.clone();
|
let lender = lender.clone();
|
||||||
|
|
@ -421,21 +448,45 @@ pub fn serve_leases(
|
||||||
let _permit = permit;
|
let _permit = permit;
|
||||||
// A connection that fails is dropped; the lease it may have
|
// A connection that fails is dropped; the lease it may have
|
||||||
// held is ended inside `lend`.
|
// held is ended inside `lend`.
|
||||||
let _ = lender.lend(stream);
|
let _ = lender.serve_one(stream);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Lender {
|
impl Lender {
|
||||||
fn lend(&self, mut stream: UnixStream) -> io::Result<()> {
|
fn serve_one(&self, mut stream: UnixStream) -> io::Result<()> {
|
||||||
stream.set_write_timeout(Some(self.limits.socket_timeout))?;
|
stream.set_write_timeout(Some(self.limits.socket_timeout))?;
|
||||||
let peer = peer_credentials(&stream)?;
|
|
||||||
let request_deadline = Instant::now() + self.limits.socket_timeout;
|
let request_deadline = Instant::now() + self.limits.socket_timeout;
|
||||||
let LeaseMessage::ClaudeLeaseRequest(request) =
|
match read_message(&mut stream, request_deadline)? {
|
||||||
read_message(&mut stream, request_deadline)?
|
LeaseMessage::ClaudeLeaseRequest(request) => {
|
||||||
else {
|
// A lease over the limit is dropped unanswered; readouts
|
||||||
return Err(io::Error::from(io::ErrorKind::InvalidData));
|
// never count against it.
|
||||||
};
|
let Some(_slot) = Permit::acquire(&self.leases, self.limits.max_connections) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let peer = peer_credentials(&stream)?;
|
||||||
|
self.lend(stream, peer, request)
|
||||||
|
}
|
||||||
|
LeaseMessage::ClaudeUsageReadoutRequest(_) => {
|
||||||
|
let Some(_slot) = Permit::acquire(&self.readouts, READOUT_CONNECTIONS) else {
|
||||||
|
return refuse(
|
||||||
|
&mut stream,
|
||||||
|
LeaseRefusalKind::Busy,
|
||||||
|
"too many usage readouts at once",
|
||||||
|
);
|
||||||
|
};
|
||||||
|
stream.write_all(&encode_frame(&readout(&self.quota, unix_ms())))
|
||||||
|
}
|
||||||
|
_ => Err(io::Error::from(io::ErrorKind::InvalidData)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lend(
|
||||||
|
&self,
|
||||||
|
mut stream: UnixStream,
|
||||||
|
peer: PeerCredentials,
|
||||||
|
request: LeaseRequest,
|
||||||
|
) -> io::Result<()> {
|
||||||
let Some(caller) = self.callers.iter().find(|caller| caller.uid == peer.uid) else {
|
let Some(caller) = self.callers.iter().find(|caller| caller.uid == peer.uid) else {
|
||||||
return refuse(
|
return refuse(
|
||||||
&mut stream,
|
&mut stream,
|
||||||
|
|
@ -468,8 +519,14 @@ impl Lender {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// The lease is claimed before the token is read, let alone lent. The
|
// The lease is claimed before the token is read, let alone lent. The
|
||||||
// plan the refusal reads is the one this process last observed.
|
// plan the refusal reads is the one this process last observed, but a
|
||||||
let plan = self.quota.snapshot();
|
// cell with no weekly reading (a restart empties it) gets the meter's
|
||||||
|
// first read, bounded, before the lease is lent "unobserved" for its
|
||||||
|
// whole life. The request is the swarm's sign of life, however it
|
||||||
|
// ends: the meter reads while one is held or lately asked for.
|
||||||
|
let _asking = self.quota.asking();
|
||||||
|
let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT);
|
||||||
|
let now = unix_ms();
|
||||||
let admission = self
|
let admission = self
|
||||||
.service
|
.service
|
||||||
.lock()
|
.lock()
|
||||||
|
|
@ -603,6 +660,16 @@ impl Lender {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The plan's windows as the cell holds them at `now_ms`. It takes the cell by
|
||||||
|
/// reference so it cannot note a request, and never waits for a first read.
|
||||||
|
fn readout(quota: &QuotaCell, now_ms: u64) -> LeaseMessage {
|
||||||
|
LeaseMessage::ClaudeUsageReadout(UsageReadout::new(now_ms, quota.snapshot()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The longest a lease waits for the meter's first read of the week. A call
|
||||||
|
/// takes a few seconds; the holder's own wait for the grant is far longer.
|
||||||
|
const FIRST_READ_WAIT: Duration = Duration::from_secs(10);
|
||||||
|
|
||||||
/// How often a held lease looks again at its holder's unit invocation.
|
/// How often a held lease looks again at its holder's unit invocation.
|
||||||
const HOLD_POLL_MS: u64 = 500;
|
const HOLD_POLL_MS: u64 = 500;
|
||||||
|
|
||||||
|
|
@ -619,6 +686,210 @@ fn refuse(stream: &mut UnixStream, kind: LeaseRefusalKind, detail: &str) -> io::
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
struct NoTokens;
|
||||||
|
impl TokenSource for NoTokens {
|
||||||
|
fn read(&self) -> Option<zeroize::Zeroizing<String>> {
|
||||||
|
panic!("a readout read the token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct NoUnits;
|
||||||
|
impl PeerUnits for NoUnits {
|
||||||
|
fn invocation_in(&self, _: BorrowedFd<'_>, _: &str) -> Option<PeerUnit> {
|
||||||
|
panic!("a readout looked up the peer's unit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lender(
|
||||||
|
quota: &Arc<QuotaCell>,
|
||||||
|
dir: &std::path::Path,
|
||||||
|
max_connections: usize,
|
||||||
|
) -> (Arc<Mutex<TransportService>>, Lender) {
|
||||||
|
let service = Arc::new(Mutex::new(
|
||||||
|
TransportService::open(
|
||||||
|
&dir.join("replay.cc"),
|
||||||
|
"claude-code",
|
||||||
|
[model_connector::CallerAdmission::new(
|
||||||
|
"lease-test-caller",
|
||||||
|
"lease-test-connection-key",
|
||||||
|
1,
|
||||||
|
["model".to_string()],
|
||||||
|
1,
|
||||||
|
65_536,
|
||||||
|
32_768,
|
||||||
|
)
|
||||||
|
.unwrap()],
|
||||||
|
300_000,
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
let lender = Lender {
|
||||||
|
callers: Vec::new(),
|
||||||
|
limits: LeaseLimits {
|
||||||
|
socket_timeout: Duration::from_secs(2),
|
||||||
|
max_lease_ms: 3_600_000,
|
||||||
|
max_connections,
|
||||||
|
},
|
||||||
|
service: service.clone(),
|
||||||
|
quota: quota.clone(),
|
||||||
|
tokens: Arc::new(NoTokens),
|
||||||
|
units: Arc::new(NoUnits),
|
||||||
|
leases: Arc::new(AtomicUsize::new(0)),
|
||||||
|
readouts: Arc::new(AtomicUsize::new(0)),
|
||||||
|
};
|
||||||
|
(service, lender)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves `lender`'s parts on a socket in `dir`; the path comes back.
|
||||||
|
fn serve(lender: Lender, dir: &std::path::Path) -> std::path::PathBuf {
|
||||||
|
let socket = dir.join("lease.sock");
|
||||||
|
let listener = UnixListener::bind(&socket).unwrap();
|
||||||
|
let (service, quota) = (lender.service.clone(), lender.quota.clone());
|
||||||
|
thread::spawn(move || {
|
||||||
|
let _ = serve_leases(
|
||||||
|
&listener,
|
||||||
|
lender.callers,
|
||||||
|
lender.limits,
|
||||||
|
service,
|
||||||
|
quota,
|
||||||
|
lender.tokens,
|
||||||
|
lender.units,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
socket
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ask(socket: &std::path::Path, message: &LeaseMessage) -> Option<LeaseMessage> {
|
||||||
|
let mut stream = UnixStream::connect(socket).ok()?;
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||||
|
.unwrap();
|
||||||
|
stream.write_all(&encode_frame(message)).ok()?;
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
let _ = stream.read_to_end(&mut raw);
|
||||||
|
decode_frame(&raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn readout_request() -> LeaseMessage {
|
||||||
|
LeaseMessage::ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest {})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scratch(name: &str) -> std::path::PathBuf {
|
||||||
|
let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_socket_readout_never_asks_the_meter_waits_for_a_week_or_takes_the_service_lock() {
|
||||||
|
let dir = scratch("readout-arm");
|
||||||
|
let quota = Arc::new(QuotaCell::new());
|
||||||
|
quota.attach_meter();
|
||||||
|
let (service, lender) = lender("a, &dir, 8);
|
||||||
|
let socket = serve(lender, &dir);
|
||||||
|
// Held throughout: a readout that takes it hangs past the read timeout.
|
||||||
|
let guard = service.lock().unwrap();
|
||||||
|
for _ in 0..20 {
|
||||||
|
let started = Instant::now();
|
||||||
|
let Some(LeaseMessage::ClaudeUsageReadout(answer)) = ask(&socket, &readout_request())
|
||||||
|
else {
|
||||||
|
panic!("no readout");
|
||||||
|
};
|
||||||
|
assert!(started.elapsed() < Duration::from_secs(1));
|
||||||
|
assert!(answer.plan_quota.is_empty());
|
||||||
|
}
|
||||||
|
drop(guard);
|
||||||
|
assert_eq!(quota.asks_so_far(), 0);
|
||||||
|
assert!(!quota.wanted_at(unix_ms(), Duration::from_secs(15 * 60)));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_flood_of_readouts_at_their_limit_leaves_every_lease_request_answered() {
|
||||||
|
let dir = scratch("readout-flood");
|
||||||
|
let quota = Arc::new(QuotaCell::new());
|
||||||
|
// Fewer lease slots than flooding readers: the readers must not need them.
|
||||||
|
let (_service, lender) = lender("a, &dir, 2);
|
||||||
|
let socket = serve(lender, &dir);
|
||||||
|
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
let flood: Vec<_> = (0..READOUT_CONNECTIONS)
|
||||||
|
.map(|_| {
|
||||||
|
let (socket, stop) = (socket.clone(), stop.clone());
|
||||||
|
thread::spawn(move || {
|
||||||
|
while !stop.load(Ordering::Acquire) {
|
||||||
|
let _ = ask(&socket, &readout_request());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
// No caller is configured, so each lease is answered UnknownCaller:
|
||||||
|
// an answer is all that is asked.
|
||||||
|
let lease = LeaseMessage::ClaudeLeaseRequest(LeaseRequest {
|
||||||
|
expires_at_unix_ms: unix_ms() + 60_000,
|
||||||
|
});
|
||||||
|
let unanswered = (0..40)
|
||||||
|
.filter(|_| {
|
||||||
|
!matches!(
|
||||||
|
ask(&socket, &lease),
|
||||||
|
Some(LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||||
|
kind: LeaseRefusalKind::UnknownCaller,
|
||||||
|
..
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.count();
|
||||||
|
stop.store(true, Ordering::Release);
|
||||||
|
for client in flood {
|
||||||
|
client.join().unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(unanswered, 0);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_readout_over_the_readout_limit_is_refused_busy_not_dropped() {
|
||||||
|
let dir = scratch("readout-limit");
|
||||||
|
let quota = Arc::new(QuotaCell::new());
|
||||||
|
let (_service, lender) = lender("a, &dir, 8);
|
||||||
|
let held: Vec<_> = (0..READOUT_CONNECTIONS)
|
||||||
|
.map(|_| Permit::acquire(&lender.readouts, READOUT_CONNECTIONS).unwrap())
|
||||||
|
.collect();
|
||||||
|
let (mut client, server) = UnixStream::pair().unwrap();
|
||||||
|
client.write_all(&encode_frame(&readout_request())).unwrap();
|
||||||
|
lender.serve_one(server).unwrap();
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
client.read_to_end(&mut raw).unwrap();
|
||||||
|
let Some(LeaseMessage::ClaudeLeaseRefusal(refusal)) = decode_frame(&raw) else {
|
||||||
|
panic!("no refusal");
|
||||||
|
};
|
||||||
|
assert_eq!(refusal.kind, LeaseRefusalKind::Busy);
|
||||||
|
drop(held);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_readout_of_an_empty_metered_cell_does_not_wait() {
|
||||||
|
let quota = QuotaCell::new();
|
||||||
|
quota.attach_meter();
|
||||||
|
let started = Instant::now();
|
||||||
|
let LeaseMessage::ClaudeUsageReadout(answer) = readout("a, 77) else {
|
||||||
|
panic!("a readout answers with a readout");
|
||||||
|
};
|
||||||
|
assert!(started.elapsed() < Duration::from_secs(1));
|
||||||
|
assert!(answer.plan_quota.is_empty());
|
||||||
|
assert_eq!(answer.at_unix_ms, 77);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_readout_is_no_sign_of_life() {
|
||||||
|
let quota = Arc::new(QuotaCell::new());
|
||||||
|
let within = Duration::from_secs(15 * 60);
|
||||||
|
let now = unix_ms();
|
||||||
|
let _ = readout("a, now);
|
||||||
|
assert!(!quota.wanted_at(now, within));
|
||||||
|
let _asking = quota.asking();
|
||||||
|
assert!(quota.wanted_at(now, within));
|
||||||
|
}
|
||||||
|
|
||||||
/// A refusal frame whose body is exactly `body_bytes` long.
|
/// A refusal frame whose body is exactly `body_bytes` long.
|
||||||
fn frame_of(body_bytes: usize) -> Vec<u8> {
|
fn frame_of(body_bytes: usize) -> Vec<u8> {
|
||||||
let frame_with = |pad: usize| {
|
let frame_with = |pad: usize| {
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
//! stream-json in and out, with every tool, MCP server, settings source and
|
//! stream-json in and out, with every tool, MCP server, settings source and
|
||||||
//! plugin switched off. A binary wires it to [`model_connector::serve`].
|
//! plugin switched off. A binary wires it to [`model_connector::serve`].
|
||||||
|
|
||||||
|
pub mod ask;
|
||||||
mod backend;
|
mod backend;
|
||||||
mod config;
|
mod config;
|
||||||
mod daemon;
|
mod daemon;
|
||||||
|
|
@ -10,6 +11,8 @@ mod handle;
|
||||||
mod launch;
|
mod launch;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
mod lease;
|
mod lease;
|
||||||
|
mod messages;
|
||||||
|
mod meter;
|
||||||
mod process;
|
mod process;
|
||||||
mod quota;
|
mod quota;
|
||||||
mod stream;
|
mod stream;
|
||||||
|
|
@ -17,19 +20,20 @@ mod stream;
|
||||||
mod unit;
|
mod unit;
|
||||||
|
|
||||||
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
|
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
|
||||||
pub use config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
|
||||||
pub use daemon::{
|
pub use daemon::{
|
||||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config,
|
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config,
|
||||||
};
|
};
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub use daemon::{check_prompt_dir, serve_config};
|
pub use daemon::{check_prompt_dir, serve_config};
|
||||||
|
pub use messages::{MessagesBackend, MessagesConfig};
|
||||||
pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore};
|
pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore};
|
||||||
pub use launch::ChildEnv;
|
pub use launch::ChildEnv;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
pub use lease::{
|
pub use lease::{
|
||||||
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
||||||
LeaseRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit, PeerUnits, decode_frame,
|
LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
|
||||||
encode_frame, peer_credentials, serve_leases, user_uid,
|
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
|
||||||
};
|
};
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub use process::StdProcessPort;
|
pub use process::StdProcessPort;
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@
|
||||||
//! claude-connector config add-caller PATH.cc --caller-id ID --connection-key-file F ...
|
//! claude-connector config add-caller PATH.cc --caller-id ID --connection-key-file F ...
|
||||||
//! claude-connector config add-lease-caller PATH.cc --lease-user U --caller-id ID ...
|
//! claude-connector config add-lease-caller PATH.cc --lease-user U --caller-id ID ...
|
||||||
//! claude-connector config check PATH.cc
|
//! claude-connector config check PATH.cc
|
||||||
|
//! claude-connector ask --caller-id ID --connection-key-file F --model M (--system TEXT | --system-file F) < prompt
|
||||||
//!
|
//!
|
||||||
//! `serve` takes its configuration from the typed document alone. The flags of
|
//! `serve` takes its configuration from the typed document alone. The flags of
|
||||||
//! `config init` exist only to author that document. No message here echoes a
|
//! `config init` exist only to author that document. No message here echoes a
|
||||||
|
|
@ -14,8 +15,9 @@ use std::collections::BTreeMap;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::process::ExitCode;
|
use std::process::ExitCode;
|
||||||
|
|
||||||
|
use claude_connector::ask::{self, AskArgs, AskError};
|
||||||
use claude_connector::{
|
use claude_connector::{
|
||||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
||||||
load_config, write_config,
|
load_config, write_config,
|
||||||
};
|
};
|
||||||
use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload};
|
use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload};
|
||||||
|
|
@ -29,6 +31,7 @@ fn main() -> ExitCode {
|
||||||
["config", "add-caller", path, flags @ ..] => add_caller(path, flags),
|
["config", "add-caller", path, flags @ ..] => add_caller(path, flags),
|
||||||
["config", "add-lease-caller", path, flags @ ..] => add_lease_caller(path, flags),
|
["config", "add-lease-caller", path, flags @ ..] => add_lease_caller(path, flags),
|
||||||
["config", "check", path] => check(path),
|
["config", "check", path] => check(path),
|
||||||
|
["ask", flags @ ..] => run_ask(flags),
|
||||||
_ => Err(Failure::Usage),
|
_ => Err(Failure::Usage),
|
||||||
};
|
};
|
||||||
match result {
|
match result {
|
||||||
|
|
@ -43,7 +46,7 @@ fn main() -> ExitCode {
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
enum Failure {
|
enum Failure {
|
||||||
#[error(
|
#[error(
|
||||||
"usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-caller PATH --flag value ... | config check PATH (check reads the credentials from the environment it runs in: run it in the unit's environment)"
|
"usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-caller PATH --flag value ... | config check PATH | ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] (prompt on stdin, answer on stdout) (check reads the credentials from the environment it runs in: run it in the unit's environment)"
|
||||||
)]
|
)]
|
||||||
Usage,
|
Usage,
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
|
|
@ -54,6 +57,8 @@ enum Failure {
|
||||||
Malformed(&'static str),
|
Malformed(&'static str),
|
||||||
#[error("a flag is unknown, repeated or has no value")]
|
#[error("a flag is unknown, repeated or has no value")]
|
||||||
Flags,
|
Flags,
|
||||||
|
#[error("{0}")]
|
||||||
|
Ask(#[from] AskError),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
|
|
@ -75,6 +80,68 @@ fn check(path: &str) -> Result<(), Failure> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ASK: [&str; 9] = [
|
||||||
|
"--endpoint",
|
||||||
|
"--caller-id",
|
||||||
|
"--connection-key-file",
|
||||||
|
"--model",
|
||||||
|
"--system",
|
||||||
|
"--system-file",
|
||||||
|
"--effort",
|
||||||
|
"--max-output-tokens",
|
||||||
|
"--timeout-secs",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// One no-tools completion: the prompt is all of stdin, the answer is stdout.
|
||||||
|
fn run_ask(args: &[&str]) -> Result<(), Failure> {
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
|
||||||
|
let flags = Flags::parse(args, &[&ASK], &[])?;
|
||||||
|
let instructions = match (
|
||||||
|
flags.single.get("--system"),
|
||||||
|
flags.single.get("--system-file"),
|
||||||
|
) {
|
||||||
|
(Some(text), None) => text.clone(),
|
||||||
|
(None, Some(path)) => ask::read_system_file(std::path::Path::new(path))?,
|
||||||
|
_ => return Err(Failure::Missing("--system or --system-file (exactly one)")),
|
||||||
|
};
|
||||||
|
let effort = match flags.single.get("--effort").map(String::as_str) {
|
||||||
|
None => None,
|
||||||
|
Some("low") => Some(model_connector::ReasoningEffort::Low),
|
||||||
|
Some("medium") => Some(model_connector::ReasoningEffort::Medium),
|
||||||
|
Some("high") => Some(model_connector::ReasoningEffort::High),
|
||||||
|
Some("max") => Some(model_connector::ReasoningEffort::Max),
|
||||||
|
Some(_) => return Err(Failure::Malformed("--effort")),
|
||||||
|
};
|
||||||
|
let endpoint = flags
|
||||||
|
.single
|
||||||
|
.get("--endpoint")
|
||||||
|
.map_or(ask::DEFAULT_ENDPOINT, String::as_str)
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| Failure::Malformed("--endpoint"))?;
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
std::io::stdin()
|
||||||
|
.take(ask::PAYLOAD_BYTES as u64 + 1)
|
||||||
|
.read_to_end(&mut raw)
|
||||||
|
.map_err(|_| AskError::StdinRead)?;
|
||||||
|
let prompt = String::from_utf8(raw).map_err(|_| AskError::StdinNotText)?;
|
||||||
|
let answer = ask::ask(&AskArgs {
|
||||||
|
endpoint,
|
||||||
|
caller_id: flags.text("--caller-id")?,
|
||||||
|
key_file: flags.path("--connection-key-file")?,
|
||||||
|
model: flags.text("--model")?,
|
||||||
|
instructions,
|
||||||
|
effort,
|
||||||
|
max_output_tokens: flags.number_or("--max-output-tokens", 8192)?,
|
||||||
|
timeout: std::time::Duration::from_secs(flags.number_or("--timeout-secs", 300)?),
|
||||||
|
prompt,
|
||||||
|
})?;
|
||||||
|
let mut out = std::io::stdout();
|
||||||
|
out.write_all(answer.as_bytes())
|
||||||
|
.and_then(|()| out.flush())
|
||||||
|
.map_err(|_| AskError::StdoutWrite.into())
|
||||||
|
}
|
||||||
|
|
||||||
/// The flags of one config verb: each single flag at most once, each list
|
/// The flags of one config verb: each single flag at most once, each list
|
||||||
/// flag any number of times.
|
/// flag any number of times.
|
||||||
struct Flags {
|
struct Flags {
|
||||||
|
|
@ -92,7 +159,8 @@ const CALLER: [&str; 5] = [
|
||||||
"--max-output-tokens",
|
"--max-output-tokens",
|
||||||
];
|
];
|
||||||
|
|
||||||
const INIT: [&str; 21] = [
|
const INIT: [&str; 22] = [
|
||||||
|
"--auth",
|
||||||
"--listen",
|
"--listen",
|
||||||
"--replay-store",
|
"--replay-store",
|
||||||
"--claude-binary",
|
"--claude-binary",
|
||||||
|
|
@ -173,6 +241,15 @@ impl Flags {
|
||||||
.map_err(|_| Failure::Malformed(name))
|
.map_err(|_| Failure::Malformed(name))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Which credential `--token-credential` names: `oauth-token` (the default) or `api-key`.
|
||||||
|
fn auth(&self) -> Result<ClaudeAuth, Failure> {
|
||||||
|
match self.single.get("--auth").map(String::as_str) {
|
||||||
|
None | Some("oauth-token") => Ok(ClaudeAuth::OAuthToken),
|
||||||
|
Some("api-key") => Ok(ClaudeAuth::ApiKey),
|
||||||
|
Some(_) => Err(Failure::Malformed("--auth")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The kind of turn a leasing account serves: `self` or `persona`.
|
/// The kind of turn a leasing account serves: `self` or `persona`.
|
||||||
fn turn(&self) -> Result<LeaseTurn, Failure> {
|
fn turn(&self) -> Result<LeaseTurn, Failure> {
|
||||||
match self.text("--turn")?.as_str() {
|
match self.text("--turn")?.as_str() {
|
||||||
|
|
@ -324,6 +401,7 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
||||||
lease_callers,
|
lease_callers,
|
||||||
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
|
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
|
||||||
handle_secret_credential: flags.text("--handle-secret-credential")?,
|
handle_secret_credential: flags.text("--handle-secret-credential")?,
|
||||||
|
auth: flags.auth()?,
|
||||||
};
|
};
|
||||||
// Validate before the secret file exists: a refused document leaves nothing.
|
// Validate before the secret file exists: a refused document leaves nothing.
|
||||||
config.validate()?;
|
config.validate()?;
|
||||||
|
|
|
||||||
626
crates/claude-connector/src/messages.rs
Normal file
626
crates/claude-connector/src/messages.rs
Normal file
|
|
@ -0,0 +1,626 @@
|
||||||
|
//! The Messages API backend: one non-streaming `POST /v1/messages` per call,
|
||||||
|
//! authenticated with an Anthropic API key. It is the backend of a connector
|
||||||
|
//! whose document says `auth` is an API key; the `claude` CLI is never spawned
|
||||||
|
//! for it. Tools, tool calls and results, thinking blocks, cache breakpoints
|
||||||
|
//! and cache usage map natively; the contract's shapes are unchanged.
|
||||||
|
//!
|
||||||
|
//! API facts this module follows were read from the Claude API reference on
|
||||||
|
//! 2026-11-29 (`anthropic-version: 2026-10-21`):
|
||||||
|
//! - `claude-sonnet-5-5`, `claude-opus-5-5` and any model
|
||||||
|
//! [`rejects_forced_tool_choice`] does not name answer a forced
|
||||||
|
//! `tool_choice` (`any`, `tool`) with a 400. [`ToolChoice::Required`] is
|
||||||
|
//! `tool_choice: any` on a model that accepts it and a typed refusal before
|
||||||
|
//! sending on one that does not; the request's `system` never depends on it.
|
||||||
|
//! Thinking is `{"type":"adaptive"}` with `output_config.effort`
|
||||||
|
//! (`thinking.budget_tokens` is rejected), and a request's output schema is
|
||||||
|
//! `output_config.format` (`json_schema`) instead of a forced tool.
|
||||||
|
//! - A thinking block is replayed unchanged, in transcript order; the API
|
||||||
|
//! drops one its model cannot read. Its `signature` is the provider's.
|
||||||
|
//! - Usage reports thinking tokens in `output_tokens_details.thinking_tokens`
|
||||||
|
//! (a detail of `output_tokens`) and `input_tokens` apart from `cache_read_input_tokens` and
|
||||||
|
//! `cache_creation_input_tokens`.
|
||||||
|
//!
|
||||||
|
//! The key is read from the systemd credential at every call and reaches the
|
||||||
|
//! HTTP client as the `x-api-key` header; it is in no environment, argument,
|
||||||
|
//! log line or message. A failed call is never run again, and a redirect is
|
||||||
|
//! never followed: it would carry the key to whatever host it names.
|
||||||
|
//!
|
||||||
|
//! Failures are typed as the Persona drain reads them: no answer could be had
|
||||||
|
//! (connection, deadline, 5xx, 429, 402, 3xx) is an outage kind, and only a
|
||||||
|
//! request or answer the provider refused is a strike. Two 400
|
||||||
|
//! `invalid_request_error` answers are the exception: the provider reports a
|
||||||
|
//! spent balance and the operator's Console spend limit as a 400 whose message
|
||||||
|
//! begins with a fixed string (`SPEND_EXHAUSTED`), and only that string tells
|
||||||
|
//! them from a bad request, so they are matched, as 402 is, to `Authentication`.
|
||||||
|
//!
|
||||||
|
//! The assistant turn is replayed from what the contract carries: thinking
|
||||||
|
//! blocks as parsed, text by its text, tool calls by id, name and input. The
|
||||||
|
//! contract has no shape for a block of another type or for a tool call's other
|
||||||
|
//! fields, and the API rejects an empty text block, so those are not replayed;
|
||||||
|
//! with no server tools sent, no response carries one.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use model_connector::{
|
||||||
|
CacheRetention, FailureKind, InputItem, PlanQuotaSnapshot, ProviderBackend, ProviderCall,
|
||||||
|
ProviderRequest, ReasoningEffort, StopReason, ToolChoice, TransportEvent,
|
||||||
|
TransportEventPayload, TransportOutcome, TransportResult, Usage,
|
||||||
|
};
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
|
||||||
|
use crate::backend::TokenSource;
|
||||||
|
|
||||||
|
/// The provider tag on every receipt and every reasoning block of this
|
||||||
|
/// backend; distinct from the CLI backend's tag.
|
||||||
|
pub(crate) const PROVIDER: &str = "anthropic-messages";
|
||||||
|
const ENDPOINT: &str = "https://api.anthropic.com";
|
||||||
|
const API_VERSION: &str = "2026-10-21";
|
||||||
|
/// The longest provider message a receipt carries.
|
||||||
|
const MESSAGE_BYTES: usize = 2048;
|
||||||
|
|
||||||
|
/// Whether the API answers `tool_choice: any` with a 400 for this model, by
|
||||||
|
/// the table in the tool-use docs (read 2026-11-29). A model not named as
|
||||||
|
/// accepting it is treated as rejecting it, so a new model is refused here
|
||||||
|
/// until someone reads its row.
|
||||||
|
fn rejects_forced_tool_choice(model: &str) -> bool {
|
||||||
|
let base = match model.rsplit_once('-') {
|
||||||
|
Some((base, date)) if date.len() == 8 && date.bytes().all(|b| b.is_ascii_digit()) => base,
|
||||||
|
_ => model,
|
||||||
|
};
|
||||||
|
!matches!(
|
||||||
|
base,
|
||||||
|
"claude-opus-5"
|
||||||
|
| "claude-sonnet-5"
|
||||||
|
| "claude-haiku-5-5"
|
||||||
|
| "claude-haiku-4-5"
|
||||||
|
| "claude-opus-4-8"
|
||||||
|
| "claude-opus-4-7"
|
||||||
|
| "claude-opus-4-6"
|
||||||
|
| "claude-opus-4-5"
|
||||||
|
| "claude-sonnet-4-6"
|
||||||
|
| "claude-sonnet-4-5"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the connector's binary hands the backend.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct MessagesConfig {
|
||||||
|
/// The name of the systemd credential that holds the API key, under
|
||||||
|
/// `$CREDENTIALS_DIRECTORY`.
|
||||||
|
pub key_credential: String,
|
||||||
|
/// The whole call, connect to the last byte of the response.
|
||||||
|
pub deadline: Duration,
|
||||||
|
/// The largest response body read.
|
||||||
|
pub max_response_bytes: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers each call with one HTTP request to the Messages API.
|
||||||
|
pub struct MessagesBackend {
|
||||||
|
agent: ureq::Agent,
|
||||||
|
endpoint: String,
|
||||||
|
keys: Box<dyn TokenSource>,
|
||||||
|
max_response_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MessagesBackend {
|
||||||
|
/// The backend over the real API, with the key read from the credential
|
||||||
|
/// `config.key_credential` names.
|
||||||
|
pub fn new(config: MessagesConfig) -> Self {
|
||||||
|
let keys = Box::new(crate::backend::CredentialTokenSource::from_environment(
|
||||||
|
config.key_credential.clone(),
|
||||||
|
));
|
||||||
|
Self::with_parts(config, keys, ENDPOINT.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn with_parts(
|
||||||
|
config: MessagesConfig,
|
||||||
|
keys: Box<dyn TokenSource>,
|
||||||
|
endpoint: String,
|
||||||
|
) -> Self {
|
||||||
|
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||||
|
.timeout_global(Some(config.deadline))
|
||||||
|
.http_status_as_error(false)
|
||||||
|
.max_redirects(0)
|
||||||
|
.build()
|
||||||
|
.into();
|
||||||
|
Self {
|
||||||
|
agent,
|
||||||
|
endpoint,
|
||||||
|
keys,
|
||||||
|
max_response_bytes: config.max_response_bytes as u64,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, request: &ProviderRequest) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
let Some(key) = self.keys.read() else {
|
||||||
|
return failed(
|
||||||
|
FailureKind::Authentication,
|
||||||
|
"anthropic-messages: the connector has no API key".to_string(),
|
||||||
|
Some(zero_usage()),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let body = match render(request).and_then(|body| {
|
||||||
|
serde_json::to_vec(&body).map_err(|_| "the request could not be encoded".to_string())
|
||||||
|
}) {
|
||||||
|
Ok(body) => body,
|
||||||
|
Err(message) => {
|
||||||
|
return failed(
|
||||||
|
FailureKind::InvalidRequest,
|
||||||
|
format!("anthropic-messages: {message}"),
|
||||||
|
Some(zero_usage()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let sent = self
|
||||||
|
.agent
|
||||||
|
.post(format!("{}/v1/messages", self.endpoint))
|
||||||
|
.header("x-api-key", key.as_str())
|
||||||
|
.header("anthropic-version", API_VERSION)
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.send(&body[..]);
|
||||||
|
let mut response = match sent {
|
||||||
|
Ok(response) => response,
|
||||||
|
Err(error) => return transport_failure(&error),
|
||||||
|
};
|
||||||
|
let status = response.status().as_u16();
|
||||||
|
let text = match response
|
||||||
|
.body_mut()
|
||||||
|
.with_config()
|
||||||
|
.limit(self.max_response_bytes)
|
||||||
|
.read_to_vec()
|
||||||
|
{
|
||||||
|
Ok(bytes) => bytes,
|
||||||
|
Err(error) => return transport_failure(&error),
|
||||||
|
};
|
||||||
|
if !(200..300).contains(&status) {
|
||||||
|
return http_failure(status, &text);
|
||||||
|
}
|
||||||
|
let required = request.tool_choice == ToolChoice::Required && !request.tools.is_empty();
|
||||||
|
match parse(&text, required) {
|
||||||
|
Ok(done) => {
|
||||||
|
let events = done
|
||||||
|
.payloads
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(sequence, payload)| TransportEvent {
|
||||||
|
sequence: sequence as u64,
|
||||||
|
payload,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
(
|
||||||
|
events,
|
||||||
|
TransportOutcome::Completed {
|
||||||
|
provider_response_id: done.id,
|
||||||
|
stop_reason: done.stop_reason,
|
||||||
|
usage: done.usage,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Err(failure) => failed(failure.kind, failure.message, failure.usage),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProviderBackend for MessagesBackend {
|
||||||
|
fn ready(&self) -> Result<(), &'static str> {
|
||||||
|
match self.keys.read() {
|
||||||
|
Some(_) => Ok(()),
|
||||||
|
None => Err(self.keys.missing()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn provider(&self) -> &str {
|
||||||
|
PROVIDER
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plan_quota(&self) -> PlanQuotaSnapshot {
|
||||||
|
PlanQuotaSnapshot::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
|
let (events, outcome) = self.run(call.request());
|
||||||
|
call.transported(events, outcome)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- request ----
|
||||||
|
|
||||||
|
/// The request body, or what is wrong with the request.
|
||||||
|
fn render(request: &ProviderRequest) -> Result<Value, String> {
|
||||||
|
let mut body = Map::new();
|
||||||
|
body.insert("model".into(), json!(request.model));
|
||||||
|
body.insert("max_tokens".into(), json!(request.max_output_tokens));
|
||||||
|
|
||||||
|
body.insert(
|
||||||
|
"system".into(),
|
||||||
|
json!([{"type": "text", "text": request.instructions}]),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut messages = messages_of(&request.input)?;
|
||||||
|
if let Some(retention) = request.cache_retention {
|
||||||
|
mark_cache_breakpoint(&mut messages, retention);
|
||||||
|
}
|
||||||
|
body.insert("messages".into(), Value::Array(messages));
|
||||||
|
|
||||||
|
if !request.tools.is_empty() {
|
||||||
|
let mut tools = Vec::with_capacity(request.tools.len());
|
||||||
|
for tool in &request.tools {
|
||||||
|
let schema: Value = serde_json::from_str(&tool.parameters_json)
|
||||||
|
.map_err(|_| format!("tool {} has parameters that are not JSON", tool.name))?;
|
||||||
|
tools.push(json!({
|
||||||
|
"name": tool.name,
|
||||||
|
"description": tool.description,
|
||||||
|
"input_schema": schema,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
body.insert("tools".into(), Value::Array(tools));
|
||||||
|
let kind = if request.tool_choice == ToolChoice::Required {
|
||||||
|
if rejects_forced_tool_choice(&request.model) {
|
||||||
|
return Err(format!(
|
||||||
|
"model {} does not accept a required tool choice",
|
||||||
|
request.model
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Some("any")
|
||||||
|
} else if !request.parallel_tool_calls {
|
||||||
|
Some("auto")
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if let Some(kind) = kind {
|
||||||
|
let mut choice = json!({"type": kind});
|
||||||
|
if !request.parallel_tool_calls {
|
||||||
|
choice["disable_parallel_tool_use"] = json!(true);
|
||||||
|
}
|
||||||
|
body.insert("tool_choice".into(), choice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut output = Map::new();
|
||||||
|
if let Some(effort) = request.reasoning_effort {
|
||||||
|
body.insert("thinking".into(), json!({"type": "adaptive"}));
|
||||||
|
output.insert("effort".into(), json!(effort_name(effort)));
|
||||||
|
}
|
||||||
|
if let Some(schema) = &request.output_schema_json {
|
||||||
|
let schema: Value = serde_json::from_str(schema)
|
||||||
|
.map_err(|_| "the output schema is not JSON".to_string())?;
|
||||||
|
output.insert(
|
||||||
|
"format".into(),
|
||||||
|
json!({"type": "json_schema", "schema": schema}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if !output.is_empty() {
|
||||||
|
body.insert("output_config".into(), Value::Object(output));
|
||||||
|
}
|
||||||
|
Ok(Value::Object(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn effort_name(effort: ReasoningEffort) -> &'static str {
|
||||||
|
match effort {
|
||||||
|
ReasoningEffort::Low => "low",
|
||||||
|
ReasoningEffort::Medium => "medium",
|
||||||
|
ReasoningEffort::High => "high",
|
||||||
|
ReasoningEffort::Max => "max",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Role {
|
||||||
|
User,
|
||||||
|
Assistant,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The transcript as alternating messages: consecutive assistant-side items
|
||||||
|
/// (reasoning, text, tool calls) are one assistant message in their order,
|
||||||
|
/// consecutive user-side items (text, tool results) one user message with its
|
||||||
|
/// tool results first, as the API requires.
|
||||||
|
fn messages_of(input: &[InputItem]) -> Result<Vec<Value>, String> {
|
||||||
|
let mut messages: Vec<Value> = Vec::new();
|
||||||
|
let mut open: Option<(Role, Vec<Value>)> = None;
|
||||||
|
for item in input {
|
||||||
|
let (role, block) = block_of(item)?;
|
||||||
|
match &mut open {
|
||||||
|
Some((current, blocks)) if *current == role => blocks.push(block),
|
||||||
|
_ => {
|
||||||
|
if let Some(done) = open.take() {
|
||||||
|
messages.push(message_of(done));
|
||||||
|
}
|
||||||
|
open = Some((role, vec![block]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(done) = open {
|
||||||
|
messages.push(message_of(done));
|
||||||
|
}
|
||||||
|
Ok(messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn message_of((role, mut blocks): (Role, Vec<Value>)) -> Value {
|
||||||
|
if role == Role::User {
|
||||||
|
blocks.sort_by_key(|block| block["type"] != "tool_result");
|
||||||
|
}
|
||||||
|
json!({
|
||||||
|
"role": if role == Role::User { "user" } else { "assistant" },
|
||||||
|
"content": blocks,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn block_of(item: &InputItem) -> Result<(Role, Value), String> {
|
||||||
|
Ok(match item {
|
||||||
|
InputItem::UserText { text } => (Role::User, json!({"type": "text", "text": text})),
|
||||||
|
InputItem::AssistantText { text } => {
|
||||||
|
(Role::Assistant, json!({"type": "text", "text": text}))
|
||||||
|
}
|
||||||
|
InputItem::ToolCall {
|
||||||
|
call_id,
|
||||||
|
name,
|
||||||
|
arguments,
|
||||||
|
} => {
|
||||||
|
let input: Value = serde_json::from_str(arguments)
|
||||||
|
.ok()
|
||||||
|
.filter(Value::is_object)
|
||||||
|
.ok_or_else(|| format!("the arguments of call {call_id} are not a JSON object"))?;
|
||||||
|
(
|
||||||
|
Role::Assistant,
|
||||||
|
json!({"type": "tool_use", "id": call_id, "name": name, "input": input}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
InputItem::ToolResult { call_id, output } => (
|
||||||
|
Role::User,
|
||||||
|
json!({"type": "tool_result", "tool_use_id": call_id, "content": output}),
|
||||||
|
),
|
||||||
|
InputItem::ReasoningState {
|
||||||
|
provider, state, ..
|
||||||
|
} => {
|
||||||
|
let block: Value = serde_json::from_slice(state)
|
||||||
|
.ok()
|
||||||
|
.filter(|block: &Value| {
|
||||||
|
provider == PROVIDER
|
||||||
|
&& matches!(
|
||||||
|
block["type"].as_str(),
|
||||||
|
Some("thinking" | "redacted_thinking")
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.ok_or_else(|| {
|
||||||
|
"a reasoning state is not a thinking block of this provider".to_string()
|
||||||
|
})?;
|
||||||
|
(Role::Assistant, block)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the one breakpoint on the last block of the last message that can
|
||||||
|
/// carry it (a thinking block cannot).
|
||||||
|
fn mark_cache_breakpoint(messages: &mut [Value], retention: CacheRetention) {
|
||||||
|
let mark = match retention {
|
||||||
|
CacheRetention::Short => json!({"type": "ephemeral"}),
|
||||||
|
CacheRetention::Long => json!({"type": "ephemeral", "ttl": "1h"}),
|
||||||
|
};
|
||||||
|
let Some(blocks) = messages
|
||||||
|
.last_mut()
|
||||||
|
.and_then(|message| message["content"].as_array_mut())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if let Some(block) = blocks.iter_mut().rev().find(|block| {
|
||||||
|
!matches!(
|
||||||
|
block["type"].as_str(),
|
||||||
|
Some("thinking" | "redacted_thinking")
|
||||||
|
)
|
||||||
|
}) {
|
||||||
|
block["cache_control"] = mark;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- response ----
|
||||||
|
|
||||||
|
struct Done {
|
||||||
|
id: Option<String>,
|
||||||
|
payloads: Vec<TransportEventPayload>,
|
||||||
|
stop_reason: StopReason,
|
||||||
|
usage: Usage,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Failure {
|
||||||
|
kind: FailureKind,
|
||||||
|
message: String,
|
||||||
|
usage: Option<Usage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `required`: the request forced a tool call, so an answer without one is a
|
||||||
|
/// failure, never a completed turn.
|
||||||
|
fn parse(bytes: &[u8], required: bool) -> Result<Done, Failure> {
|
||||||
|
let provider_failure = |message: &str, usage: Option<Usage>| Failure {
|
||||||
|
kind: FailureKind::Provider,
|
||||||
|
message: format!("anthropic-messages: {message}"),
|
||||||
|
usage,
|
||||||
|
};
|
||||||
|
let response: Value = serde_json::from_slice(bytes)
|
||||||
|
.map_err(|_| provider_failure("the response is not JSON", None))?;
|
||||||
|
let usage = usage_of(&response["usage"]);
|
||||||
|
let blocks = response["content"]
|
||||||
|
.as_array()
|
||||||
|
.ok_or_else(|| provider_failure("the response has no content", usage.clone()))?;
|
||||||
|
let mut payloads = Vec::new();
|
||||||
|
for block in blocks {
|
||||||
|
match block["type"].as_str() {
|
||||||
|
Some("text") => {
|
||||||
|
if let Some(text) = block["text"].as_str().filter(|text| !text.is_empty()) {
|
||||||
|
payloads.push(TransportEventPayload::TextDelta {
|
||||||
|
text: text.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some("tool_use") => {
|
||||||
|
let (Some(id), Some(name)) = (block["id"].as_str(), block["name"].as_str()) else {
|
||||||
|
return Err(provider_failure("a tool call has no id or name", usage));
|
||||||
|
};
|
||||||
|
payloads.push(TransportEventPayload::ToolCall {
|
||||||
|
call_id: id.to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
arguments: serde_json::to_string(&block["input"]).unwrap_or_default(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Some("thinking" | "redacted_thinking") => {
|
||||||
|
payloads.push(TransportEventPayload::ReasoningState {
|
||||||
|
state: serde_json::to_vec(block).unwrap_or_default(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if required
|
||||||
|
&& !payloads
|
||||||
|
.iter()
|
||||||
|
.any(|payload| matches!(payload, TransportEventPayload::ToolCall { .. }))
|
||||||
|
{
|
||||||
|
return Err(provider_failure("a required tool call did not come", usage));
|
||||||
|
}
|
||||||
|
let stop_reason = match response["stop_reason"].as_str() {
|
||||||
|
Some("end_turn") => StopReason::EndTurn,
|
||||||
|
Some("tool_use") => StopReason::ToolUse,
|
||||||
|
Some("max_tokens") => StopReason::MaxOutputTokens,
|
||||||
|
Some("stop_sequence") => StopReason::StopSequence,
|
||||||
|
Some("refusal") => StopReason::Refusal,
|
||||||
|
Some("model_context_window_exceeded") => StopReason::ContextWindow,
|
||||||
|
_ => {
|
||||||
|
return Err(provider_failure(
|
||||||
|
"the stop reason is not one this backend maps",
|
||||||
|
usage,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(Done {
|
||||||
|
id: response["id"].as_str().map(str::to_string),
|
||||||
|
payloads,
|
||||||
|
stop_reason,
|
||||||
|
usage: usage.unwrap_or_else(zero_usage),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usage_of(usage: &Value) -> Option<Usage> {
|
||||||
|
usage.is_object().then(|| {
|
||||||
|
let count = |name: &str| usage[name].as_u64().unwrap_or(0);
|
||||||
|
Usage {
|
||||||
|
input_tokens: count("input_tokens"),
|
||||||
|
cache_read_tokens: count("cache_read_input_tokens"),
|
||||||
|
cache_write_tokens: count("cache_creation_input_tokens"),
|
||||||
|
output_tokens: count("output_tokens"),
|
||||||
|
reasoning_tokens: usage["output_tokens_details"]["thinking_tokens"].as_u64(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- failures ----
|
||||||
|
|
||||||
|
/// The Persona drain treats `RateLimited`, `Unavailable`, `Timeout` and
|
||||||
|
/// `Authentication` as outages and every other kind as a strike against the
|
||||||
|
/// line the turn was waking on. A fault of the key's account or of the path to
|
||||||
|
/// the API is never the line's.
|
||||||
|
///
|
||||||
|
/// 402 is a credential-level fault, not a transient one: the key's account
|
||||||
|
/// cannot pay and only the operator fixes it, as with 401 and 403, so it is
|
||||||
|
/// `Authentication`; `Unavailable` would promise that it heals itself.
|
||||||
|
fn kind_of_status(status: u16) -> FailureKind {
|
||||||
|
match status {
|
||||||
|
401..=403 => FailureKind::Authentication,
|
||||||
|
408 | 504 => FailureKind::Timeout,
|
||||||
|
429 => FailureKind::RateLimited,
|
||||||
|
300..=399 | 500..=599 => FailureKind::Unavailable,
|
||||||
|
400 => FailureKind::InvalidRequest,
|
||||||
|
_ => FailureKind::Provider,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fixed beginnings of the provider's 400 messages for a spent balance
|
||||||
|
/// and a reached Console spend limit, lower-cased.
|
||||||
|
const SPEND_EXHAUSTED: [&str; 2] = [
|
||||||
|
"your credit balance is too low",
|
||||||
|
"you have reached your specified api usage limits",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn spend_exhausted(error: &Value) -> bool {
|
||||||
|
error["type"].as_str() == Some("invalid_request_error")
|
||||||
|
&& error["message"].as_str().is_some_and(|text| {
|
||||||
|
let text = text.trim_start().to_lowercase();
|
||||||
|
SPEND_EXHAUSTED.iter().any(|prefix| text.starts_with(prefix))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failure the provider answered: its own type and message, bounded.
|
||||||
|
fn http_failure(status: u16, body: &[u8]) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
let parsed: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
|
||||||
|
let error = &parsed["error"];
|
||||||
|
let mut message = format!("anthropic-messages: HTTP {status}");
|
||||||
|
if let Some(kind) = error["type"].as_str() {
|
||||||
|
message.push(' ');
|
||||||
|
message.push_str(kind);
|
||||||
|
}
|
||||||
|
if let Some(text) = error["message"].as_str().filter(|text| !text.is_empty()) {
|
||||||
|
message.push_str(": ");
|
||||||
|
message.push_str(text);
|
||||||
|
}
|
||||||
|
let kind = if status == 400 && spend_exhausted(error) {
|
||||||
|
FailureKind::Authentication
|
||||||
|
} else {
|
||||||
|
kind_of_status(status)
|
||||||
|
};
|
||||||
|
failed(kind, bounded(message), None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failure before an answer: the deadline, the size cap, the connection.
|
||||||
|
fn transport_failure(error: &ureq::Error) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
let (kind, what) = match error {
|
||||||
|
ureq::Error::Timeout(_) => (
|
||||||
|
FailureKind::Timeout,
|
||||||
|
"the deadline passed before a response",
|
||||||
|
),
|
||||||
|
ureq::Error::BodyExceedsLimit(_) => {
|
||||||
|
(FailureKind::Provider, "the response passed its size cap")
|
||||||
|
}
|
||||||
|
ureq::Error::BadUri(_) | ureq::Error::Http(_) | ureq::Error::InvalidProxyUrl => {
|
||||||
|
(FailureKind::Provider, "the request could not be built")
|
||||||
|
}
|
||||||
|
_ => (FailureKind::Unavailable, "the API could not be reached"),
|
||||||
|
};
|
||||||
|
failed(kind, format!("anthropic-messages: {what}"), None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bounded(mut message: String) -> String {
|
||||||
|
if message.len() > MESSAGE_BYTES {
|
||||||
|
let mut end = MESSAGE_BYTES;
|
||||||
|
while !message.is_char_boundary(end) {
|
||||||
|
end -= 1;
|
||||||
|
}
|
||||||
|
message.truncate(end);
|
||||||
|
}
|
||||||
|
message
|
||||||
|
}
|
||||||
|
|
||||||
|
fn zero_usage() -> Usage {
|
||||||
|
Usage {
|
||||||
|
input_tokens: 0,
|
||||||
|
cache_read_tokens: 0,
|
||||||
|
cache_write_tokens: 0,
|
||||||
|
output_tokens: 0,
|
||||||
|
reasoning_tokens: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failed(
|
||||||
|
kind: FailureKind,
|
||||||
|
message: String,
|
||||||
|
usage: Option<Usage>,
|
||||||
|
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
(
|
||||||
|
Vec::new(),
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind,
|
||||||
|
message,
|
||||||
|
usage,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
1095
crates/claude-connector/src/messages/tests.rs
Normal file
1095
crates/claude-connector/src/messages/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
651
crates/claude-connector/src/meter.rs
Normal file
651
crates/claude-connector/src/meter.rs
Normal file
|
|
@ -0,0 +1,651 @@
|
||||||
|
//! The meter: keeps the plan's weekly reading fresh while the swarm is
|
||||||
|
//! working. The subscription reports its windows only inside the CLI's
|
||||||
|
//! `rate_limit_event`, on a call the CLI makes, and Personas make theirs under
|
||||||
|
//! leases that report nothing back. So when the `seven_day` reading in the
|
||||||
|
//! [`QuotaCell`] is `STALE` old, the meter makes the smallest real call
|
||||||
|
//! through the backend's own path (one `claude -p` on the cheapest model with
|
||||||
|
//! a trivial prompt) and the stream fills the cell exactly as it does for any
|
||||||
|
//! call. The meter holds no credential, speaks no protocol and writes nothing
|
||||||
|
//! itself.
|
||||||
|
//!
|
||||||
|
//! The meter is driven by the connector's own lease state. It reads only
|
||||||
|
//! while a lease is held or one was asked for less than `STALE` ago: a held
|
||||||
|
//! swarm brake stops the units, they ask for nothing, and a braked or quiet
|
||||||
|
//! swarm spends nothing. A call that fails, or completes without refreshing
|
||||||
|
//! the reading, is not retried at the staleness period: the wait doubles per
|
||||||
|
//! consecutive miss, up to `CEILING`.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use model_connector::{PlanQuota, Usage};
|
||||||
|
|
||||||
|
use crate::backend::ClaudeCodeBackend;
|
||||||
|
use crate::quota::{EXPIRED, QuotaCell, WEEK};
|
||||||
|
|
||||||
|
/// A reading this old, or older, is stale; also the least gap between calls.
|
||||||
|
const STALE: Duration = Duration::from_secs(15 * 60);
|
||||||
|
/// The longest any backoff may wait; also how long an idle meter sleeps
|
||||||
|
/// before looking again, since a lease request wakes it.
|
||||||
|
const CEILING: Duration = Duration::from_secs(6 * 60 * 60);
|
||||||
|
|
||||||
|
/// The smallest real call, as the backend makes it.
|
||||||
|
pub(crate) trait Probe: Send {
|
||||||
|
/// What the call billed, or the failure's kind. Never a message: a
|
||||||
|
/// provider's words do not enter the meter's log.
|
||||||
|
fn call(&self) -> Result<Usage, String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Probe for Arc<ClaudeCodeBackend> {
|
||||||
|
fn call(&self) -> Result<Usage, String> {
|
||||||
|
self.read_meter()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why the meter is waiting. A refresh is logged every time, with the reading
|
||||||
|
/// it saw; the other states are logged once per change.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
enum State {
|
||||||
|
/// The week window as the refresh left it; a window with no reading is
|
||||||
|
/// `None`.
|
||||||
|
Read {
|
||||||
|
permille: Option<u32>,
|
||||||
|
resets_at_unix_ms: u64,
|
||||||
|
},
|
||||||
|
Idle,
|
||||||
|
/// The call failed; the kind is the failure's kind, never its message.
|
||||||
|
Failed(String),
|
||||||
|
Unread,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
fn line(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::Read {
|
||||||
|
permille,
|
||||||
|
resets_at_unix_ms,
|
||||||
|
} => {
|
||||||
|
let permille = permille.map_or("unknown".to_string(), |p| p.to_string());
|
||||||
|
format!(
|
||||||
|
"meter: weekly reading refreshed, permille {permille} resets_at_unix_ms {resets_at_unix_ms}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Self::Idle => "meter: no lease asked lately, making no call".to_string(),
|
||||||
|
Self::Failed(kind) => format!("meter: the call failed ({kind}), backing off"),
|
||||||
|
Self::Unread => {
|
||||||
|
"meter: the call completed without a weekly reading, backing off".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Meter {
|
||||||
|
cell: Arc<QuotaCell>,
|
||||||
|
probe: Box<dyn Probe>,
|
||||||
|
log: Box<dyn FnMut(&str) + Send>,
|
||||||
|
/// No call before this instant, unix ms.
|
||||||
|
not_before_ms: u64,
|
||||||
|
/// Consecutive calls that left the reading unrefreshed.
|
||||||
|
misses: u32,
|
||||||
|
last_state: Option<State>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Meter {
|
||||||
|
fn new(cell: Arc<QuotaCell>, probe: Box<dyn Probe>, log: Box<dyn FnMut(&str) + Send>) -> Self {
|
||||||
|
Self {
|
||||||
|
cell,
|
||||||
|
probe,
|
||||||
|
log,
|
||||||
|
not_before_ms: 0,
|
||||||
|
misses: 0,
|
||||||
|
last_state: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes the call if one is due at `now_ms`; returns how long to wait
|
||||||
|
/// before looking again. Nothing is due while no lease is held or lately
|
||||||
|
/// asked for, nor before the last miss's backoff has passed, nor while the
|
||||||
|
/// weekly reading is younger than `STALE`.
|
||||||
|
fn tick(&mut self, now_ms: u64) -> Duration {
|
||||||
|
if !self.cell.wanted_at(now_ms, STALE) {
|
||||||
|
self.report(State::Idle);
|
||||||
|
return CEILING;
|
||||||
|
}
|
||||||
|
let due_at = self.due_at_ms();
|
||||||
|
if now_ms < due_at {
|
||||||
|
return Duration::from_millis(due_at - now_ms);
|
||||||
|
}
|
||||||
|
// A failed call may still have refreshed the reading: a rejected turn
|
||||||
|
// reports its windows and then errors. Only the cell says whether the
|
||||||
|
// week was read.
|
||||||
|
let called = self.probe.call();
|
||||||
|
let state = if let Some(week) = self.week_refreshed_since(now_ms) {
|
||||||
|
self.misses = 0;
|
||||||
|
State::Read {
|
||||||
|
permille: week.utilization_permille,
|
||||||
|
resets_at_unix_ms: week.resets_at_unix_ms,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.misses = self.misses.saturating_add(1);
|
||||||
|
match called {
|
||||||
|
Ok(_) => State::Unread,
|
||||||
|
Err(kind) => State::Failed(kind),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.report(state);
|
||||||
|
self.not_before_ms = now_ms.saturating_add(duration_ms(backoff(self.misses)));
|
||||||
|
Duration::from_millis(self.due_at_ms().saturating_sub(now_ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The earliest instant the next call may happen. A window past its reset
|
||||||
|
/// described a week that is over, so it is due at once.
|
||||||
|
fn due_at_ms(&self) -> u64 {
|
||||||
|
let stale_at = self
|
||||||
|
.cell
|
||||||
|
.snapshot()
|
||||||
|
.windows
|
||||||
|
.iter()
|
||||||
|
.find(|quota| quota.window == WEEK)
|
||||||
|
.map_or(0, |quota| {
|
||||||
|
if quota.status == EXPIRED {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
quota.observed_at_unix_ms.saturating_add(duration_ms(STALE))
|
||||||
|
}
|
||||||
|
});
|
||||||
|
stale_at.max(self.not_before_ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The week window if it was observed at or after `since_ms`, from one
|
||||||
|
/// snapshot, so the logged value is the one that decided the refresh.
|
||||||
|
fn week_refreshed_since(&self, since_ms: u64) -> Option<PlanQuota> {
|
||||||
|
self.cell
|
||||||
|
.snapshot()
|
||||||
|
.windows
|
||||||
|
.into_iter()
|
||||||
|
.find(|quota| quota.window == WEEK && quota.observed_at_unix_ms >= since_ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn report(&mut self, state: State) {
|
||||||
|
if matches!(state, State::Read { .. }) || self.last_state.as_ref() != Some(&state) {
|
||||||
|
(self.log)(&state.line());
|
||||||
|
self.last_state = Some(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(mut self) {
|
||||||
|
loop {
|
||||||
|
let seen = self.cell.asks_so_far();
|
||||||
|
let wait = self.tick(unix_ms());
|
||||||
|
self.cell.sleep_until_asked(seen, wait);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wait after `misses` consecutive unrefreshed calls: the staleness
|
||||||
|
/// period, doubling per miss beyond the first, up to the ceiling.
|
||||||
|
fn backoff(misses: u32) -> Duration {
|
||||||
|
let doublings = misses.saturating_sub(1).min(16);
|
||||||
|
STALE.saturating_mul(1 << doublings).min(CEILING)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn duration_ms(duration: Duration) -> u64 {
|
||||||
|
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unix_ms() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map_or(0, duration_ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the meter thread. It writes only through the calls it makes, and
|
||||||
|
/// logs one line to stderr per refresh of the weekly reading and one per
|
||||||
|
/// change of any other state. From here a lease asked of
|
||||||
|
/// a cell with no weekly reading waits for the meter's first read.
|
||||||
|
pub(crate) fn start(
|
||||||
|
cell: Arc<QuotaCell>,
|
||||||
|
probe: Box<dyn Probe>,
|
||||||
|
) -> std::io::Result<std::thread::JoinHandle<()>> {
|
||||||
|
cell.attach_meter();
|
||||||
|
let meter = Meter::new(
|
||||||
|
cell,
|
||||||
|
probe,
|
||||||
|
Box::new(|line| eprintln!("claude-connector: {line}")),
|
||||||
|
);
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("claude-meter".to_string())
|
||||||
|
.spawn(move || meter.run())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::quota::Asking;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
const MIN: u64 = 60_000;
|
||||||
|
const NOW: u64 = 1_800_000_000_000;
|
||||||
|
const RESET: u64 = 4_102_444_800_000;
|
||||||
|
|
||||||
|
fn reading(status: &str) -> Vec<PlanQuota> {
|
||||||
|
vec![PlanQuota {
|
||||||
|
window: WEEK.to_string(),
|
||||||
|
utilization_permille: Some(60),
|
||||||
|
resets_at_unix_ms: RESET,
|
||||||
|
status: status.to_string(),
|
||||||
|
observed_at_unix_ms: 0,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the next call does: the instant its stream stamps a weekly
|
||||||
|
/// reading (if any) and the kind it then fails with (if any).
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct Script {
|
||||||
|
reading_at: Option<u64>,
|
||||||
|
status: String,
|
||||||
|
fails_with: Option<String>,
|
||||||
|
/// The used thousandths the reading reports; 60 when unset.
|
||||||
|
permille: Option<u32>,
|
||||||
|
/// The reset the reading reports; `RESET` when unset.
|
||||||
|
resets_at: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A call that answers as scripted and feeds the cell the way the stream
|
||||||
|
/// does, before it fails, as a rejected turn does.
|
||||||
|
struct Calls {
|
||||||
|
cell: Arc<QuotaCell>,
|
||||||
|
made: Arc<AtomicUsize>,
|
||||||
|
script: Arc<Mutex<Script>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Probe for Calls {
|
||||||
|
fn call(&self) -> Result<Usage, String> {
|
||||||
|
self.made.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let script = self.script.lock().unwrap().clone();
|
||||||
|
if let Some(at) = script.reading_at {
|
||||||
|
let mut week = reading(&script.status);
|
||||||
|
week[0].utilization_permille = Some(script.permille.unwrap_or(60));
|
||||||
|
week[0].resets_at_unix_ms = script.resets_at.unwrap_or(RESET);
|
||||||
|
self.cell.observe_at(at, week);
|
||||||
|
}
|
||||||
|
if let Some(kind) = script.fails_with {
|
||||||
|
return Err(kind);
|
||||||
|
}
|
||||||
|
Ok(Usage {
|
||||||
|
input_tokens: 385,
|
||||||
|
cache_read_tokens: 0,
|
||||||
|
cache_write_tokens: 0,
|
||||||
|
output_tokens: 4,
|
||||||
|
reasoning_tokens: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Rig {
|
||||||
|
meter: Meter,
|
||||||
|
cell: Arc<QuotaCell>,
|
||||||
|
made: Arc<AtomicUsize>,
|
||||||
|
script: Arc<Mutex<Script>>,
|
||||||
|
log: Arc<Mutex<Vec<String>>>,
|
||||||
|
/// The lease the swarm holds until a test lets go of it.
|
||||||
|
lease: Option<Asking>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rig() -> Rig {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
let made = Arc::new(AtomicUsize::new(0));
|
||||||
|
let script = Arc::new(Mutex::new(Script::default()));
|
||||||
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let sink = log.clone();
|
||||||
|
let meter = Meter::new(
|
||||||
|
cell.clone(),
|
||||||
|
Box::new(Calls {
|
||||||
|
cell: cell.clone(),
|
||||||
|
made: made.clone(),
|
||||||
|
script: script.clone(),
|
||||||
|
}),
|
||||||
|
Box::new(move |line| sink.lock().unwrap().push(line.to_string())),
|
||||||
|
);
|
||||||
|
let lease = Some(cell.asking_at(NOW));
|
||||||
|
Rig {
|
||||||
|
meter,
|
||||||
|
cell,
|
||||||
|
made,
|
||||||
|
script,
|
||||||
|
log,
|
||||||
|
lease,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rig {
|
||||||
|
fn reads(&self, at: u64) {
|
||||||
|
*self.script.lock().unwrap() = Script {
|
||||||
|
reading_at: Some(at),
|
||||||
|
status: "allowed".to_string(),
|
||||||
|
fails_with: None,
|
||||||
|
..Script::default()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
fn reads_nothing(&self) {
|
||||||
|
*self.script.lock().unwrap() = Script::default();
|
||||||
|
}
|
||||||
|
fn fails(&self, kind: &str) {
|
||||||
|
*self.script.lock().unwrap() = Script {
|
||||||
|
fails_with: Some(kind.to_string()),
|
||||||
|
..Script::default()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
fn calls(&self) -> usize {
|
||||||
|
self.made.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
fn lines(&self) -> Vec<String> {
|
||||||
|
self.log.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unread_week_triggers_one_call_and_the_fresh_reading_ends_the_asking() {
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.reads(NOW);
|
||||||
|
assert_eq!(rig.meter.tick(NOW), STALE, "fresh for the staleness period");
|
||||||
|
assert_eq!(rig.calls(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
rig.meter.tick(NOW + 5 * MIN),
|
||||||
|
Duration::from_millis(10 * MIN)
|
||||||
|
);
|
||||||
|
assert_eq!(rig.calls(), 1, "a fresh reading makes no call");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stale_reading_triggers_a_call_at_the_period_and_not_before() {
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.cell.observe_at(NOW, reading("allowed"));
|
||||||
|
rig.reads(NOW + 15 * MIN);
|
||||||
|
rig.meter.tick(NOW + 15 * MIN - 1);
|
||||||
|
assert_eq!(rig.calls(), 0, "one millisecond short of stale");
|
||||||
|
rig.meter.tick(NOW + 15 * MIN);
|
||||||
|
assert_eq!(rig.calls(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_window_past_its_reset_is_read_at_once_not_after_the_period() {
|
||||||
|
let mut rig = rig();
|
||||||
|
let now = unix_ms();
|
||||||
|
let mut over = reading("allowed").remove(0);
|
||||||
|
over.resets_at_unix_ms = 1;
|
||||||
|
rig.cell.observe_at(now, vec![over]);
|
||||||
|
rig.reads(now);
|
||||||
|
rig.meter.tick(now);
|
||||||
|
assert_eq!(rig.calls(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_swarm_that_asks_for_nothing_spends_nothing_however_stale_the_reading() {
|
||||||
|
let mut rig = rig();
|
||||||
|
drop(rig.lease.take());
|
||||||
|
for step in 0..10 {
|
||||||
|
let at = NOW + 15 * MIN + step * 60 * MIN;
|
||||||
|
assert_eq!(rig.meter.tick(at), CEILING);
|
||||||
|
}
|
||||||
|
assert_eq!(rig.calls(), 0);
|
||||||
|
assert_eq!(rig.lines(), vec![State::Idle.line()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_lease_asked_for_wakes_the_meter_and_the_empty_cell_is_read() {
|
||||||
|
let mut rig = rig();
|
||||||
|
drop(rig.lease.take());
|
||||||
|
rig.reads(NOW + 180 * MIN);
|
||||||
|
rig.meter.tick(NOW + 180 * MIN);
|
||||||
|
assert_eq!(rig.calls(), 0, "asked three hours ago and let go");
|
||||||
|
let _later = rig.cell.asking_at(NOW + 180 * MIN);
|
||||||
|
rig.meter.tick(NOW + 180 * MIN);
|
||||||
|
assert_eq!(rig.calls(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_lease_let_go_is_still_wanted_for_exactly_one_staleness_period() {
|
||||||
|
let mut rig = rig();
|
||||||
|
drop(rig.lease.take());
|
||||||
|
rig.reads(NOW + 15 * MIN - 1);
|
||||||
|
rig.meter.tick(NOW + 15 * MIN - 1);
|
||||||
|
assert_eq!(rig.calls(), 1, "one millisecond inside the period");
|
||||||
|
rig.reads(NOW + 30 * MIN);
|
||||||
|
rig.meter.tick(NOW + 30 * MIN);
|
||||||
|
assert_eq!(rig.calls(), 1, "a period after the last ask: unwanted");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_lease_held_for_four_hours_keeps_the_week_read_throughout() {
|
||||||
|
let mut rig = rig();
|
||||||
|
for step in 0..=16 {
|
||||||
|
let at = NOW + step * 15 * MIN;
|
||||||
|
rig.reads(at);
|
||||||
|
rig.meter.tick(at);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
rig.calls(),
|
||||||
|
17,
|
||||||
|
"one read per period, the lease never lapsing"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failed_call_leaves_the_cell_and_backs_off_instead_of_hammering() {
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.cell.observe_at(NOW, reading("allowed"));
|
||||||
|
let before = rig.cell.snapshot();
|
||||||
|
rig.fails("Provider");
|
||||||
|
let mut at = NOW + 15 * MIN;
|
||||||
|
let mut waits = Vec::new();
|
||||||
|
for _ in 0..4 {
|
||||||
|
waits.push(rig.meter.tick(at));
|
||||||
|
at += duration_ms(*waits.last().unwrap());
|
||||||
|
}
|
||||||
|
assert_eq!(rig.calls(), 4);
|
||||||
|
assert_eq!(rig.cell.snapshot(), before, "the cell is untouched");
|
||||||
|
assert_eq!(
|
||||||
|
waits,
|
||||||
|
[15, 30, 60, 120].map(|m| Duration::from_secs(m * 60)),
|
||||||
|
"the wait doubles per consecutive miss"
|
||||||
|
);
|
||||||
|
rig.meter.tick(at - MIN);
|
||||||
|
assert_eq!(rig.calls(), 4, "nothing is asked before the backoff ends");
|
||||||
|
assert_eq!(
|
||||||
|
rig.lines(),
|
||||||
|
vec!["meter: the call failed (Provider), backing off"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_failure_kind_is_logged_again_when_it_changes_and_not_when_it_repeats() {
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.fails("Authentication");
|
||||||
|
rig.meter.tick(NOW);
|
||||||
|
rig.meter.tick(NOW + 15 * MIN);
|
||||||
|
rig.fails("InvalidRequest");
|
||||||
|
rig.meter.tick(NOW + 45 * MIN);
|
||||||
|
assert_eq!(
|
||||||
|
rig.lines(),
|
||||||
|
vec![
|
||||||
|
"meter: the call failed (Authentication), backing off",
|
||||||
|
"meter: the call failed (InvalidRequest), backing off",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backoff_stops_at_the_ceiling_and_one_good_reading_resets_it() {
|
||||||
|
assert_eq!(backoff(0), STALE);
|
||||||
|
assert_eq!(backoff(1), STALE);
|
||||||
|
assert_eq!(backoff(u32::MAX), CEILING);
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.fails("Provider");
|
||||||
|
rig.meter.tick(NOW);
|
||||||
|
rig.meter.tick(NOW + 15 * MIN);
|
||||||
|
assert_eq!(rig.meter.misses, 2);
|
||||||
|
rig.reads(NOW + 45 * MIN);
|
||||||
|
rig.meter.tick(NOW + 45 * MIN);
|
||||||
|
assert_eq!(rig.meter.misses, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_call_that_completes_without_a_weekly_reading_is_a_miss_too() {
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.reads_nothing();
|
||||||
|
assert_eq!(rig.meter.tick(NOW), STALE);
|
||||||
|
assert_eq!(rig.meter.tick(NOW + 15 * MIN), 2 * STALE);
|
||||||
|
assert_eq!(rig.calls(), 2);
|
||||||
|
assert_eq!(rig.lines(), vec![State::Unread.line()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_rejected_turn_that_refreshed_the_reading_and_then_errored_is_no_miss() {
|
||||||
|
let mut rig = rig();
|
||||||
|
*rig.script.lock().unwrap() = Script {
|
||||||
|
reading_at: Some(NOW),
|
||||||
|
status: "rejected".to_string(),
|
||||||
|
fails_with: Some("RateLimited".to_string()),
|
||||||
|
..Script::default()
|
||||||
|
};
|
||||||
|
assert_eq!(rig.meter.tick(NOW), STALE, "the next read is a period away");
|
||||||
|
assert_eq!(rig.meter.misses, 0);
|
||||||
|
assert_eq!(
|
||||||
|
rig.lines(),
|
||||||
|
vec![format!(
|
||||||
|
"meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}"
|
||||||
|
)]
|
||||||
|
);
|
||||||
|
rig.reads(NOW + 15 * MIN);
|
||||||
|
rig.meter.tick(NOW + 15 * MIN);
|
||||||
|
assert_eq!(rig.calls(), 2, "a rejected reading is kept fresh");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_reading_from_before_the_call_does_not_count_as_its_answer() {
|
||||||
|
let mut rig = rig();
|
||||||
|
// A slow concurrent sensor stamped earlier than this call began.
|
||||||
|
rig.reads(NOW - 1);
|
||||||
|
rig.meter.tick(NOW);
|
||||||
|
assert_eq!(rig.meter.misses, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_refresh_logs_the_reading_and_an_unchanged_value_logs_again() {
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.reads(NOW);
|
||||||
|
rig.meter.tick(NOW);
|
||||||
|
rig.reads(NOW + 15 * MIN);
|
||||||
|
rig.meter.tick(NOW + 15 * MIN);
|
||||||
|
let line =
|
||||||
|
format!("meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}");
|
||||||
|
assert_eq!(rig.lines(), vec![line.clone(), line]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_logged_value_follows_the_reading_and_an_expired_week_is_unknown() {
|
||||||
|
let mut rig = rig();
|
||||||
|
for (at, permille) in [(NOW, 60), (NOW + 15 * MIN, 75)] {
|
||||||
|
*rig.script.lock().unwrap() = Script {
|
||||||
|
reading_at: Some(at),
|
||||||
|
status: "allowed".to_string(),
|
||||||
|
permille: Some(permille),
|
||||||
|
resets_at: Some(RESET + permille as u64),
|
||||||
|
..Script::default()
|
||||||
|
};
|
||||||
|
rig.meter.tick(at);
|
||||||
|
}
|
||||||
|
let mut expired = self::rig();
|
||||||
|
let now = unix_ms();
|
||||||
|
*expired.script.lock().unwrap() = Script {
|
||||||
|
reading_at: Some(now),
|
||||||
|
status: "allowed".to_string(),
|
||||||
|
resets_at: Some(1),
|
||||||
|
..Script::default()
|
||||||
|
};
|
||||||
|
expired.meter.tick(now);
|
||||||
|
assert_eq!(
|
||||||
|
expired.lines(),
|
||||||
|
vec!["meter: weekly reading refreshed, permille unknown resets_at_unix_ms 1"]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
rig.lines(),
|
||||||
|
vec![
|
||||||
|
format!(
|
||||||
|
"meter: weekly reading refreshed, permille 60 resets_at_unix_ms {}",
|
||||||
|
RESET + 60
|
||||||
|
),
|
||||||
|
format!(
|
||||||
|
"meter: weekly reading refreshed, permille 75 resets_at_unix_ms {}",
|
||||||
|
RESET + 75
|
||||||
|
),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn idle_logs_once_per_change_however_often_it_repeats() {
|
||||||
|
let mut rig = rig();
|
||||||
|
rig.lease = None;
|
||||||
|
for step in 0..3 {
|
||||||
|
rig.meter.tick(NOW + 60 * MIN * (step + 1));
|
||||||
|
}
|
||||||
|
assert_eq!(rig.lines(), vec![State::Idle.line()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_log_says_what_the_meter_is_doing_in_words() {
|
||||||
|
assert_eq!(
|
||||||
|
State::Idle.line(),
|
||||||
|
"meter: no lease asked lately, making no call"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
State::Read {
|
||||||
|
permille: None,
|
||||||
|
resets_at_unix_ms: 7
|
||||||
|
}
|
||||||
|
.line(),
|
||||||
|
"meter: weekly reading refreshed, permille unknown resets_at_unix_ms 7"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
State::Unread.line(),
|
||||||
|
"meter: the call completed without a weekly reading, backing off"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_clock_is_the_system_clock_in_unix_milliseconds() {
|
||||||
|
let before = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||||
|
let read = unix_ms();
|
||||||
|
let after = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||||
|
assert!((before.as_millis() as u64..=after.as_millis() as u64).contains(&read));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_started_meter_sleeps_until_a_lease_asks_and_then_reads() {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
let made = Arc::new(AtomicUsize::new(0));
|
||||||
|
let probe = Calls {
|
||||||
|
cell: cell.clone(),
|
||||||
|
made: made.clone(),
|
||||||
|
script: Arc::new(Mutex::new(Script {
|
||||||
|
reading_at: Some(unix_ms() + 60 * MIN),
|
||||||
|
status: "allowed".to_string(),
|
||||||
|
fails_with: None,
|
||||||
|
..Script::default()
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
start(cell.clone(), Box::new(probe)).unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(300));
|
||||||
|
assert_eq!(made.load(Ordering::SeqCst), 0, "no lease, no call");
|
||||||
|
let _lease = cell.asking();
|
||||||
|
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||||
|
while made.load(Ordering::SeqCst) == 0 {
|
||||||
|
assert!(std::time::Instant::now() < deadline, "the ask woke nobody");
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
assert_eq!(cell.snapshot_with_week(Duration::ZERO).windows.len(), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,38 +1,150 @@
|
||||||
//! The plan's own usage windows, as the CLI reports them. The subscription
|
//! The plan's own usage windows, as the subscription reports them. The
|
||||||
//! decides how much a plan may burn; the CLI's `rate_limit_event` is the only
|
//! subscription decides how much a plan may burn, and one sensor observes it:
|
||||||
//! place that number appears, so the latest observation of each window is kept
|
//! the CLI's `rate_limit_event` on the connector's own calls, which the
|
||||||
//! here and published as the usage readout and lent with each lease.
|
//! `meter` makes when the week's reading goes stale. The latest observation of
|
||||||
|
//! each window is kept here and published as the usage readout and lent with
|
||||||
|
//! each lease.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::sync::Mutex;
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::sync::{Arc, Condvar, Mutex};
|
||||||
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use model_connector::{PlanQuota, PlanQuotaSnapshot};
|
use model_connector::{PlanQuota, PlanQuotaSnapshot};
|
||||||
|
|
||||||
|
/// The window the weekly pacing reads, and the one the meter keeps fresh.
|
||||||
|
pub(crate) const WEEK: &str = "seven_day";
|
||||||
|
/// The windows the pacing reads, and so the only ones the cell keeps.
|
||||||
|
pub(crate) const PACED: [&str; 2] = ["five_hour", WEEK];
|
||||||
|
|
||||||
|
/// How often a lease waiting for its first reading looks at the cell again.
|
||||||
|
const FIRST_READ_POLL: Duration = Duration::from_millis(50);
|
||||||
|
|
||||||
/// The latest observation of each plan window, shared by the backend that
|
/// The latest observation of each plan window, shared by the backend that
|
||||||
/// feeds it and whatever reads it out. Each window carries the time of its
|
/// feeds it and whatever reads it out. Each window carries the time of its
|
||||||
/// own observation: an event that names one window says nothing about the
|
/// own observation: an event that names one window says nothing about the
|
||||||
/// others.
|
/// others.
|
||||||
|
///
|
||||||
|
/// It also keeps who is asking: a lease request is the swarm's only sign of
|
||||||
|
/// life the connector sees, and the meter reads the plan only while someone
|
||||||
|
/// asks.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct QuotaCell(Mutex<BTreeMap<String, PlanQuota>>);
|
pub struct QuotaCell {
|
||||||
|
windows: Mutex<BTreeMap<String, PlanQuota>>,
|
||||||
|
asks: Mutex<Asks>,
|
||||||
|
asked: Condvar,
|
||||||
|
metered: AtomicBool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Asks {
|
||||||
|
/// Lease requests in flight or held.
|
||||||
|
live: usize,
|
||||||
|
/// Requests ever made; the meter sleeps until it changes.
|
||||||
|
count: u64,
|
||||||
|
/// When the latest request came, unix ms.
|
||||||
|
last_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A lease request while it is in flight or held. Dropping it is the lease
|
||||||
|
/// ending, by whatever road.
|
||||||
|
pub(crate) struct Asking(Arc<QuotaCell>);
|
||||||
|
|
||||||
|
impl Drop for Asking {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let mut asks = self.0.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
asks.live = asks.live.saturating_sub(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl QuotaCell {
|
impl QuotaCell {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self::default()
|
Self::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Records the windows one event reported, stamping each with now. Each
|
/// Notes a lease request, now, and wakes the meter.
|
||||||
/// replaces that window's earlier observation, and windows the event did
|
pub(crate) fn asking(self: &Arc<Self>) -> Asking {
|
||||||
/// not mention stay as they were, stamp included.
|
self.asking_at(unix_ms())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn asking_at(self: &Arc<Self>, now: u64) -> Asking {
|
||||||
|
{
|
||||||
|
let mut asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
asks.live += 1;
|
||||||
|
asks.count += 1;
|
||||||
|
asks.last_ms = Some(now);
|
||||||
|
}
|
||||||
|
self.asked.notify_all();
|
||||||
|
Asking(self.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a lease is held, or one was asked for less than `within` ago.
|
||||||
|
pub(crate) fn wanted_at(&self, now: u64, within: Duration) -> bool {
|
||||||
|
let asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
asks.live > 0
|
||||||
|
|| asks.last_ms.is_some_and(|last| {
|
||||||
|
now < last.saturating_add(u64::try_from(within.as_millis()).unwrap_or(u64::MAX))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn asks_so_far(&self) -> u64 {
|
||||||
|
self.asks.lock().unwrap_or_else(|e| e.into_inner()).count
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sleeps up to `limit`, or until a request beyond the first `seen` comes.
|
||||||
|
pub(crate) fn sleep_until_asked(&self, seen: u64, limit: Duration) {
|
||||||
|
let asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
drop(
|
||||||
|
self.asked
|
||||||
|
.wait_timeout_while(asks, limit, |asks| asks.count == seen)
|
||||||
|
.unwrap_or_else(|e| e.into_inner()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Declares that a meter reads this cell, so a first lease may wait for it.
|
||||||
|
pub(crate) fn attach_meter(&self) {
|
||||||
|
self.metered.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The windows as they stand, but with no weekly reading yet (a restart
|
||||||
|
/// leaves the cell empty) a metered cell is given up to `within` to get
|
||||||
|
/// one, so a lease is not lent "unobserved" for want of a few seconds.
|
||||||
|
pub(crate) fn snapshot_with_week(&self, within: Duration) -> PlanQuotaSnapshot {
|
||||||
|
let deadline = Instant::now() + within;
|
||||||
|
loop {
|
||||||
|
let snapshot = self.snapshot();
|
||||||
|
let read = snapshot
|
||||||
|
.windows
|
||||||
|
.iter()
|
||||||
|
.any(|quota| quota.window == WEEK && quota.status != EXPIRED);
|
||||||
|
let now = Instant::now();
|
||||||
|
if read || !self.metered.load(Ordering::SeqCst) || now >= deadline {
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
std::thread::sleep(FIRST_READ_POLL.min(deadline - now));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records the windows one event reported, stamping each with now. See
|
||||||
|
/// [`QuotaCell::observe_at`] for how a reading combines with what is held.
|
||||||
pub fn observe(&self, windows: impl IntoIterator<Item = PlanQuota>) {
|
pub fn observe(&self, windows: impl IntoIterator<Item = PlanQuota>) {
|
||||||
self.observe_at(unix_ms(), windows);
|
self.observe_at(unix_ms(), windows);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn observe_at(&self, now: u64, windows: impl IntoIterator<Item = PlanQuota>) {
|
/// Records readings taken at `at` (unix ms). A reading older than the
|
||||||
let mut held = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
/// held one is dropped, so a slow call cannot replace what a faster one
|
||||||
|
/// saw meanwhile. Windows the readings did not mention stay as they were,
|
||||||
|
/// stamp included.
|
||||||
|
pub fn observe_at(&self, at: u64, windows: impl IntoIterator<Item = PlanQuota>) {
|
||||||
|
let mut held = self.windows.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
for mut quota in windows {
|
for mut quota in windows {
|
||||||
quota.observed_at_unix_ms = now;
|
quota.observed_at_unix_ms = at;
|
||||||
held.insert(quota.window.clone(), quota);
|
if held
|
||||||
|
.get("a.window)
|
||||||
|
.is_none_or(|current| quota.observed_at_unix_ms >= current.observed_at_unix_ms)
|
||||||
|
{
|
||||||
|
held.insert(quota.window.clone(), quota);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -43,8 +155,8 @@ impl QuotaCell {
|
||||||
/// The windows as of `now`. One whose reset time has passed is reported
|
/// The windows as of `now`. One whose reset time has passed is reported
|
||||||
/// `expired` with no utilization: the reading described a window that no
|
/// `expired` with no utilization: the reading described a window that no
|
||||||
/// longer exists.
|
/// longer exists.
|
||||||
fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot {
|
pub(crate) fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot {
|
||||||
let held = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
let held = self.windows.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
PlanQuotaSnapshot {
|
PlanQuotaSnapshot {
|
||||||
windows: held
|
windows: held
|
||||||
.values()
|
.values()
|
||||||
|
|
@ -62,7 +174,7 @@ impl QuotaCell {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The status of a window whose reset has passed since it was observed.
|
/// The status of a window whose reset has passed since it was observed.
|
||||||
const EXPIRED: &str = "expired";
|
pub(crate) const EXPIRED: &str = "expired";
|
||||||
|
|
||||||
fn unix_ms() -> u64 {
|
fn unix_ms() -> u64 {
|
||||||
SystemTime::now()
|
SystemTime::now()
|
||||||
|
|
@ -133,6 +245,38 @@ mod tests {
|
||||||
assert_eq!(expired[0].resets_at_unix_ms, RESET);
|
assert_eq!(expired[0].resets_at_unix_ms, RESET);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn with_status(mut quota: PlanQuota, status: &str) -> PlanQuota {
|
||||||
|
quota.status = status.to_string();
|
||||||
|
quota
|
||||||
|
}
|
||||||
|
|
||||||
|
fn held(cell: &QuotaCell) -> (String, Option<u32>, u64) {
|
||||||
|
let window = cell.snapshot_at(250).windows.remove(0);
|
||||||
|
(
|
||||||
|
window.status,
|
||||||
|
window.utilization_permille,
|
||||||
|
window.observed_at_unix_ms,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_reading_older_than_the_held_one_is_dropped_and_an_equal_one_replaces() {
|
||||||
|
let cell = QuotaCell::new();
|
||||||
|
cell.observe_at(200, [quota("five_hour", 80, 0)]);
|
||||||
|
cell.observe_at(100, [quota("five_hour", 10, 0)]);
|
||||||
|
assert_eq!(held(&cell), ("allowed".to_string(), Some(80), 200));
|
||||||
|
cell.observe_at(200, [quota("five_hour", 90, 0)]);
|
||||||
|
assert_eq!(held(&cell), ("allowed".to_string(), Some(90), 200));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_newer_reading_lifts_a_rejection() {
|
||||||
|
let cell = QuotaCell::new();
|
||||||
|
cell.observe_at(100, [with_status(quota("five_hour", 1000, 0), "rejected")]);
|
||||||
|
cell.observe_at(200, [quota("five_hour", 300, 0)]);
|
||||||
|
assert_eq!(held(&cell), ("allowed".to_string(), Some(300), 200));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_live_clock_stamps_and_expires() {
|
fn the_live_clock_stamps_and_expires() {
|
||||||
let cell = QuotaCell::new();
|
let cell = QuotaCell::new();
|
||||||
|
|
@ -148,4 +292,114 @@ mod tests {
|
||||||
assert_eq!(windows[0].utilization_permille, Some(80));
|
assert_eq!(windows[0].utilization_permille, Some(80));
|
||||||
assert_eq!(windows[1].status, "expired");
|
assert_eq!(windows[1].status, "expired");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const HOUR: u64 = 3_600_000;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nobody_wants_the_plan_before_anyone_asks() {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
assert!(!cell.wanted_at(0, Duration::from_secs(900)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_lease_in_flight_or_held_is_wanted_for_as_long_as_it_lives() {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
let lease = cell.asking_at(1_000);
|
||||||
|
let other = cell.asking_at(2_000);
|
||||||
|
let day = Duration::from_secs(86_400);
|
||||||
|
assert!(cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)));
|
||||||
|
drop(lease);
|
||||||
|
assert!(cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)), "one lease still lives");
|
||||||
|
drop(other);
|
||||||
|
assert!(!cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)));
|
||||||
|
assert!(cell.wanted_at(2_000 + 4 * HOUR, day), "within the window of the last ask");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_lease_let_go_is_wanted_until_exactly_the_period_after_its_ask() {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
drop(cell.asking_at(10_000));
|
||||||
|
let period = Duration::from_millis(900);
|
||||||
|
assert!(cell.wanted_at(10_899, period));
|
||||||
|
assert!(!cell.wanted_at(10_900, period));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_ask_is_counted_and_wakes_a_sleeper_at_once() {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
assert_eq!(cell.asks_so_far(), 0);
|
||||||
|
let sleeper = {
|
||||||
|
let cell = cell.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let started = Instant::now();
|
||||||
|
cell.sleep_until_asked(0, Duration::from_secs(30));
|
||||||
|
started.elapsed()
|
||||||
|
})
|
||||||
|
};
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
drop(cell.asking());
|
||||||
|
assert!(sleeper.join().unwrap() < Duration::from_secs(10), "woken, not timed out");
|
||||||
|
assert_eq!(cell.asks_so_far(), 1);
|
||||||
|
// An ask that came after `seen` was read ends the sleep before it starts.
|
||||||
|
let started = Instant::now();
|
||||||
|
cell.sleep_until_asked(0, Duration::from_secs(30));
|
||||||
|
assert!(started.elapsed() < Duration::from_secs(10));
|
||||||
|
// Nothing new: the sleep is the whole limit.
|
||||||
|
let started = Instant::now();
|
||||||
|
cell.sleep_until_asked(1, Duration::from_millis(200));
|
||||||
|
assert!(started.elapsed() >= Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_metered_cell_with_no_week_gives_a_first_lease_the_reading_when_it_lands() {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
cell.attach_meter();
|
||||||
|
let feeder = {
|
||||||
|
let cell = cell.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
cell.observe([quota(WEEK, 60, 0)]);
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let plan = cell.snapshot_with_week(Duration::from_secs(20));
|
||||||
|
feeder.join().unwrap();
|
||||||
|
assert_eq!(plan.windows.len(), 1, "the lease waited for the week");
|
||||||
|
assert_eq!(plan.windows[0].window, WEEK);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_wait_for_the_first_reading_is_bounded() {
|
||||||
|
let cell = Arc::new(QuotaCell::new());
|
||||||
|
cell.attach_meter();
|
||||||
|
let started = Instant::now();
|
||||||
|
let plan = cell.snapshot_with_week(Duration::from_millis(300));
|
||||||
|
let waited = started.elapsed();
|
||||||
|
assert!(plan.windows.is_empty(), "no reading came: unobserved, not hung");
|
||||||
|
assert!(waited >= Duration::from_millis(300), "{waited:?}");
|
||||||
|
assert!(waited < Duration::from_secs(10), "{waited:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cell_nobody_meters_or_that_holds_the_week_is_never_waited_on() {
|
||||||
|
let bare = QuotaCell::new();
|
||||||
|
let started = Instant::now();
|
||||||
|
assert!(bare.snapshot_with_week(Duration::from_secs(20)).windows.is_empty());
|
||||||
|
let held = QuotaCell::new();
|
||||||
|
held.attach_meter();
|
||||||
|
held.observe([quota(WEEK, 60, 0)]);
|
||||||
|
assert_eq!(held.snapshot_with_week(Duration::from_secs(20)).windows.len(), 1);
|
||||||
|
assert!(started.elapsed() < Duration::from_secs(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_week_past_its_reset_is_waited_on_like_no_week() {
|
||||||
|
let cell = QuotaCell::new();
|
||||||
|
cell.attach_meter();
|
||||||
|
let mut over = quota(WEEK, 60, 0);
|
||||||
|
over.resets_at_unix_ms = 1;
|
||||||
|
cell.observe([over]);
|
||||||
|
let started = Instant::now();
|
||||||
|
cell.snapshot_with_week(Duration::from_millis(300));
|
||||||
|
assert!(started.elapsed() >= Duration::from_millis(300));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ use model_connector::{FailureKind, PlanQuota, StopReason, Usage};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::quota::QuotaCell;
|
use crate::quota::{PACED, QuotaCell};
|
||||||
|
|
||||||
/// The tool the CLI gives the model to deliver an answer that must match a
|
/// The tool the CLI gives the model to deliver an answer that must match a
|
||||||
/// `--json-schema`. Its call is the structured output, not a tool exchange.
|
/// `--json-schema`. Its call is the structured output, not a tool exchange.
|
||||||
|
|
@ -121,7 +121,7 @@ pub(crate) struct StreamState<'a> {
|
||||||
/// Whether that schema's top type admits an object (absent counts): the
|
/// Whether that schema's top type admits an object (absent counts): the
|
||||||
/// structured output must be an object, never a bare scalar or array.
|
/// structured output must be an object, never a bare scalar or array.
|
||||||
schema_top_is_object: bool,
|
schema_top_is_object: bool,
|
||||||
quota: &'a QuotaCell,
|
quota: Option<&'a QuotaCell>,
|
||||||
session_id: Option<String>,
|
session_id: Option<String>,
|
||||||
texts: Vec<String>,
|
texts: Vec<String>,
|
||||||
message_id: Option<String>,
|
message_id: Option<String>,
|
||||||
|
|
@ -130,7 +130,7 @@ pub(crate) struct StreamState<'a> {
|
||||||
|
|
||||||
impl<'a> StreamState<'a> {
|
impl<'a> StreamState<'a> {
|
||||||
/// `schema` is the request's output schema text, when it carried one.
|
/// `schema` is the request's output schema text, when it carried one.
|
||||||
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: &'a QuotaCell) -> Self {
|
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: Option<&'a QuotaCell>) -> Self {
|
||||||
let top = schema
|
let top = schema
|
||||||
.and_then(|text| serde_json::from_str::<Value>(text).ok())
|
.and_then(|text| serde_json::from_str::<Value>(text).ok())
|
||||||
.and_then(|schema| schema.get("type").cloned());
|
.and_then(|schema| schema.get("type").cloned());
|
||||||
|
|
@ -176,7 +176,9 @@ impl<'a> StreamState<'a> {
|
||||||
if let Some(info) = &line.rate_limit_info {
|
if let Some(info) = &line.rate_limit_info {
|
||||||
self.plan_rejected |=
|
self.plan_rejected |=
|
||||||
info.get("status").and_then(Value::as_str) == Some("rejected");
|
info.get("status").and_then(Value::as_str) == Some("rejected");
|
||||||
self.quota.observe(plan_windows(info));
|
if let Some(quota) = self.quota {
|
||||||
|
quota.observe(plan_windows(info));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Step::More
|
Step::More
|
||||||
}
|
}
|
||||||
|
|
@ -320,12 +322,16 @@ impl<'a> StreamState<'a> {
|
||||||
/// `rate_limit_info.unifiedWindows`: utilization as a fraction of the window,
|
/// `rate_limit_info.unifiedWindows`: utilization as a fraction of the window,
|
||||||
/// reset as unix seconds. A window missing any of its three fields is skipped;
|
/// reset as unix seconds. A window missing any of its three fields is skipped;
|
||||||
/// an unknown reading is never zero.
|
/// an unknown reading is never zero.
|
||||||
|
/// Only the windows pacing reads are taken ([`PACED`]): the event also names
|
||||||
|
/// per-model buckets, and one of those reading `rejected` must not close every
|
||||||
|
/// lease.
|
||||||
fn plan_windows(info: &Value) -> Vec<PlanQuota> {
|
fn plan_windows(info: &Value) -> Vec<PlanQuota> {
|
||||||
let Some(windows) = info.get("unifiedWindows").and_then(Value::as_object) else {
|
let Some(windows) = info.get("unifiedWindows").and_then(Value::as_object) else {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
windows
|
windows
|
||||||
.iter()
|
.iter()
|
||||||
|
.filter(|(window, _)| PACED.contains(&window.as_str()))
|
||||||
.filter_map(|(window, reading)| {
|
.filter_map(|(window, reading)| {
|
||||||
let utilization = reading.get("utilization")?.as_f64()?;
|
let utilization = reading.get("utilization")?.as_f64()?;
|
||||||
let resets_at = reading.get("resetsAt")?.as_u64()?;
|
let resets_at = reading.get("resetsAt")?.as_u64()?;
|
||||||
|
|
@ -392,3 +398,50 @@ fn sum_usage(models: impl Iterator<Item = ModelUsage>) -> Usage {
|
||||||
}
|
}
|
||||||
usage
|
usage
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn windows(body: &str) -> Vec<(String, Option<u32>, u64)> {
|
||||||
|
let info: Value = serde_json::from_str(&format!(r#"{{"unifiedWindows":{body}}}"#)).unwrap();
|
||||||
|
plan_windows(&info)
|
||||||
|
.into_iter()
|
||||||
|
.map(|q| (q.window, q.utilization_permille, q.resets_at_unix_ms))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_five_hour_and_seven_day_windows_are_taken() {
|
||||||
|
let taken = windows(
|
||||||
|
r#"{"five_hour":{"utilization":0.5,"resetsAt":2,"status":"allowed"},
|
||||||
|
"seven_day":{"utilization":0.25,"resetsAt":3,"status":"allowed"},
|
||||||
|
"seven_day_opus":{"utilization":0.1,"resetsAt":4,"status":"allowed"},
|
||||||
|
"seven_day_overage_included":{"utilization":1,"resetsAt":5,"status":"rejected"}}"#,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
taken,
|
||||||
|
vec![
|
||||||
|
("five_hour".to_string(), Some(500), 2000),
|
||||||
|
("seven_day".to_string(), Some(250), 3000),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_window_missing_a_field_or_of_the_wrong_type_costs_only_itself() {
|
||||||
|
// Unknown is never zero: such a window is skipped, not read as empty.
|
||||||
|
for broken in [
|
||||||
|
r#"{"resetsAt":2,"status":"allowed"}"#,
|
||||||
|
r#"{"utilization":0.5,"status":"allowed"}"#,
|
||||||
|
r#"{"utilization":0.5,"resetsAt":2}"#,
|
||||||
|
r#"{"utilization":"high","resetsAt":2,"status":"allowed"}"#,
|
||||||
|
r#"{"utilization":-0.5,"resetsAt":2,"status":"allowed"}"#,
|
||||||
|
] {
|
||||||
|
let both = windows(&format!(
|
||||||
|
r#"{{"five_hour":{broken},"seven_day":{{"utilization":0,"resetsAt":3,"status":"allowed"}}}}"#
|
||||||
|
));
|
||||||
|
assert_eq!(both, vec![("seven_day".to_string(), Some(0), 3000)], "{broken}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
769
crates/claude-connector/tests/ask.rs
Normal file
769
crates/claude-connector/tests/ask.rs
Normal file
|
|
@ -0,0 +1,769 @@
|
||||||
|
//! `claude-connector ask` against a real serve loop on loopback with a scripted
|
||||||
|
//! backend: the consumer side of the no-tools completion.
|
||||||
|
|
||||||
|
use std::net::{SocketAddr, TcpListener};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use claude_connector::ask::{AskArgs, AskError, ask, build_invocation};
|
||||||
|
use model_connector::*;
|
||||||
|
|
||||||
|
const CALLER: &str = "ask-caller";
|
||||||
|
const KEY: &str = "ask-test-key-0123456789-abcdefghijklmnop";
|
||||||
|
const MODEL: &str = "claude-haiku-5-5";
|
||||||
|
const FRAME: usize = 4 << 20;
|
||||||
|
|
||||||
|
/// What the scripted backend does with each call.
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum Script {
|
||||||
|
Text(&'static str),
|
||||||
|
Empty,
|
||||||
|
Failed(&'static str),
|
||||||
|
Sleep(Duration),
|
||||||
|
ToolCall,
|
||||||
|
Stop(StopReason),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Backend {
|
||||||
|
script: Script,
|
||||||
|
seen: Mutex<Vec<ProviderRequest>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProviderBackend for Backend {
|
||||||
|
fn ready(&self) -> Result<(), &'static str> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn provider(&self) -> &str {
|
||||||
|
"claude-code"
|
||||||
|
}
|
||||||
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
|
self.seen.lock().unwrap().push(call.request().clone());
|
||||||
|
let usage = Usage {
|
||||||
|
input_tokens: 1,
|
||||||
|
cache_read_tokens: 0,
|
||||||
|
cache_write_tokens: 0,
|
||||||
|
output_tokens: 1,
|
||||||
|
reasoning_tokens: None,
|
||||||
|
};
|
||||||
|
let text = |t: &str| {
|
||||||
|
vec![TransportEvent {
|
||||||
|
sequence: 0,
|
||||||
|
payload: TransportEventPayload::TextDelta { text: t.into() },
|
||||||
|
}]
|
||||||
|
};
|
||||||
|
let stop = match &self.script {
|
||||||
|
Script::Stop(reason) => *reason,
|
||||||
|
_ => StopReason::EndTurn,
|
||||||
|
};
|
||||||
|
let completed = TransportOutcome::Completed {
|
||||||
|
provider_response_id: None,
|
||||||
|
stop_reason: stop,
|
||||||
|
usage: usage.clone(),
|
||||||
|
};
|
||||||
|
match &self.script {
|
||||||
|
Script::Text(t) => call.transported(text(t), completed),
|
||||||
|
Script::Empty => call.transported(Vec::new(), completed),
|
||||||
|
Script::Failed(message) => call.transported(
|
||||||
|
Vec::new(),
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::Provider,
|
||||||
|
message: message.to_string(),
|
||||||
|
usage: None,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
Script::Stop(_) => call.transported(text("cut off"), completed),
|
||||||
|
Script::ToolCall => call.transported(
|
||||||
|
vec![TransportEvent {
|
||||||
|
sequence: 0,
|
||||||
|
payload: TransportEventPayload::ToolCall {
|
||||||
|
call_id: "c".into(),
|
||||||
|
name: "n".into(),
|
||||||
|
arguments: "{}".into(),
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
completed,
|
||||||
|
),
|
||||||
|
Script::Sleep(d) => {
|
||||||
|
thread::sleep(*d);
|
||||||
|
call.transported(text("late"), completed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_key(path: &std::path::Path, bytes: &[u8], mode: u32) {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
std::fs::write(path, bytes).unwrap();
|
||||||
|
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Rig {
|
||||||
|
endpoint: SocketAddr,
|
||||||
|
dir: PathBuf,
|
||||||
|
key_file: PathBuf,
|
||||||
|
backend: Arc<Backend>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rig(script: Script) -> Rig {
|
||||||
|
static SEQ: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
let dir = std::env::temp_dir().join(format!(
|
||||||
|
"claude-connector-ask-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
SEQ.fetch_add(1, Ordering::Relaxed)
|
||||||
|
));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let key_file = dir.join("caller.key");
|
||||||
|
write_key(&key_file, format!("{KEY}\n").as_bytes(), 0o600);
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let endpoint = listener.local_addr().unwrap();
|
||||||
|
let admission =
|
||||||
|
CallerAdmission::new(CALLER, KEY, 1, [MODEL.to_string()], 4, 1 << 20, 4_096).unwrap();
|
||||||
|
let limits = ServeLimits {
|
||||||
|
max_frame_bytes: FRAME,
|
||||||
|
max_connections: 8,
|
||||||
|
socket_timeout_ms: 5_000,
|
||||||
|
max_expiry_skew_ms: 300_000,
|
||||||
|
};
|
||||||
|
let backend = Arc::new(Backend {
|
||||||
|
script,
|
||||||
|
seen: Mutex::new(Vec::new()),
|
||||||
|
});
|
||||||
|
let served = backend.clone();
|
||||||
|
let store = dir.join("replay.cc");
|
||||||
|
thread::spawn(move || serve(listener, limits, vec![admission], &store, served));
|
||||||
|
Rig {
|
||||||
|
endpoint,
|
||||||
|
dir,
|
||||||
|
key_file,
|
||||||
|
backend,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rig {
|
||||||
|
fn args(&self) -> AskArgs {
|
||||||
|
AskArgs {
|
||||||
|
endpoint: self.endpoint,
|
||||||
|
caller_id: CALLER.into(),
|
||||||
|
key_file: self.key_file.clone(),
|
||||||
|
model: MODEL.into(),
|
||||||
|
instructions: "Answer briefly.".into(),
|
||||||
|
effort: Some(ReasoningEffort::Low),
|
||||||
|
max_output_tokens: 1_024,
|
||||||
|
timeout: Duration::from_secs(5),
|
||||||
|
prompt: "SECRET-PROMPT-TEXT".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn seen(&self) -> Vec<ProviderRequest> {
|
||||||
|
self.backend.seen.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn message(error: &AskError) -> String {
|
||||||
|
error.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn success_returns_the_answer_text_and_the_backend_saw_a_toolless_request() {
|
||||||
|
let rig = rig(Script::Text("four"));
|
||||||
|
assert_eq!(ask(&rig.args()).unwrap(), "four");
|
||||||
|
let seen = rig.seen();
|
||||||
|
assert_eq!(seen.len(), 1);
|
||||||
|
assert!(seen[0].tools.is_empty());
|
||||||
|
assert_eq!(seen[0].model, MODEL);
|
||||||
|
assert_eq!(seen[0].instructions, "Answer briefly.");
|
||||||
|
assert_eq!(seen[0].reasoning_effort, Some(ReasoningEffort::Low));
|
||||||
|
assert_eq!(seen[0].max_output_tokens, 1_024);
|
||||||
|
assert_eq!(
|
||||||
|
seen[0].input,
|
||||||
|
vec![InputItem::UserText {
|
||||||
|
text: "SECRET-PROMPT-TEXT".into()
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_run_uses_a_fresh_request_id_so_replay_never_answers_a_new_question() {
|
||||||
|
let rig = rig(Script::Text("again"));
|
||||||
|
ask(&rig.args()).unwrap();
|
||||||
|
ask(&rig.args()).unwrap();
|
||||||
|
let seen = rig.seen();
|
||||||
|
assert_eq!(seen.len(), 2, "the provider ran once per run");
|
||||||
|
assert_ne!(seen[0].request_id, seen[1].request_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_cli_cannot_construct_a_request_with_tools() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let invocation = build_invocation(&rig.args()).unwrap();
|
||||||
|
assert!(invocation.request.tools.is_empty());
|
||||||
|
assert_eq!(invocation.request.tool_choice, ToolChoice::Auto);
|
||||||
|
assert!(
|
||||||
|
invocation
|
||||||
|
.request
|
||||||
|
.input
|
||||||
|
.iter()
|
||||||
|
.all(|item| matches!(item, InputItem::UserText { .. }))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_model_outside_allowed_models_is_refused_loudly() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.model = "claude-opus-5".into();
|
||||||
|
let error = ask(&args).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(error, AskError::Refused(Refusal::ModelNotAllowed)),
|
||||||
|
"{error}"
|
||||||
|
);
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_output_bound_over_the_callers_cap_is_refused() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.max_output_tokens = 4_097;
|
||||||
|
assert!(matches!(
|
||||||
|
ask(&args).unwrap_err(),
|
||||||
|
AskError::Refused(Refusal::OutputBound)
|
||||||
|
));
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wrong_key_or_caller_is_an_error_and_never_reaches_the_provider() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let mut wrong_key = rig.args();
|
||||||
|
let other = rig.dir.join("other.key");
|
||||||
|
write_key(&other, b"some-other-connection-key-0123456789", 0o600);
|
||||||
|
wrong_key.key_file = other;
|
||||||
|
let error = ask(&wrong_key).unwrap_err();
|
||||||
|
assert!(!message(&error).contains("some-other"), "{error}");
|
||||||
|
let mut wrong_caller = rig.args();
|
||||||
|
wrong_caller.caller_id = "someone-else".into();
|
||||||
|
ask(&wrong_caller).unwrap_err();
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unusable_key_file_errors_without_echoing_its_contents() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let cases: Vec<(&str, Vec<u8>)> = vec![
|
||||||
|
("empty", b"\n".to_vec()),
|
||||||
|
("long", vec![b'k'; 2_000]),
|
||||||
|
("binary", vec![0xff, 0xfe, 0xfd, 0x41]),
|
||||||
|
("padded", b" spaced-secret-value-padded ".to_vec()),
|
||||||
|
];
|
||||||
|
for (name, bytes) in cases {
|
||||||
|
let path = rig.dir.join(format!("{name}.key"));
|
||||||
|
write_key(&path, &bytes, 0o600);
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.key_file = path;
|
||||||
|
let text = message(&ask(&args).unwrap_err());
|
||||||
|
assert!(!text.contains("spaced-secret"), "{name}: {text}");
|
||||||
|
assert!(!text.contains("kkkk"), "{name}: {text}");
|
||||||
|
}
|
||||||
|
let mut missing = rig.args();
|
||||||
|
missing.key_file = rig.dir.join("absent.key");
|
||||||
|
assert!(matches!(
|
||||||
|
ask(&missing).unwrap_err(),
|
||||||
|
AskError::KeyUnreadable
|
||||||
|
));
|
||||||
|
let mut directory = rig.args();
|
||||||
|
directory.key_file = rig.dir.clone();
|
||||||
|
assert!(matches!(
|
||||||
|
ask(&directory).unwrap_err(),
|
||||||
|
AskError::KeyNotRegular
|
||||||
|
));
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_answer_is_an_error() {
|
||||||
|
for script in [Script::Empty, Script::Text(" \n")] {
|
||||||
|
let rig = rig(script);
|
||||||
|
assert!(matches!(
|
||||||
|
ask(&rig.args()).unwrap_err(),
|
||||||
|
AskError::EmptyAnswer
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_prompt_is_an_error_before_any_connection() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.prompt = " \n\t".into();
|
||||||
|
assert!(matches!(ask(&args).unwrap_err(), AskError::EmptyPrompt));
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_provider_failure_names_its_kind_and_not_its_message() {
|
||||||
|
let rig = rig(Script::Failed("stderr tail with SECRET-PROMPT-TEXT"));
|
||||||
|
let error = ask(&rig.args()).unwrap_err();
|
||||||
|
assert!(matches!(error, AskError::Failed(FailureKind::Provider)));
|
||||||
|
assert!(!message(&error).contains("SECRET"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_connector_that_does_not_answer_in_time_is_a_timeout() {
|
||||||
|
let rig = rig(Script::Sleep(Duration::from_secs(3)));
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.timeout = Duration::from_millis(300);
|
||||||
|
assert!(matches!(ask(&args).unwrap_err(), AskError::Timeout));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dead_endpoint_is_a_connection_error() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.endpoint = listener.local_addr().unwrap();
|
||||||
|
drop(listener);
|
||||||
|
assert!(matches!(ask(&args).unwrap_err(), AskError::NotListening));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_binary(rig: &Rig, stdin: &str, extra: &[&str]) -> std::process::Output {
|
||||||
|
run_binary_with_key(rig, &rig.key_file, stdin, extra)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_binary_with_key(
|
||||||
|
rig: &Rig,
|
||||||
|
key_file: &std::path::Path,
|
||||||
|
stdin: &str,
|
||||||
|
extra: &[&str],
|
||||||
|
) -> std::process::Output {
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||||
|
.args(["ask", "--endpoint", &rig.endpoint.to_string()])
|
||||||
|
.args([
|
||||||
|
"--caller-id",
|
||||||
|
CALLER,
|
||||||
|
"--model",
|
||||||
|
MODEL,
|
||||||
|
"--system",
|
||||||
|
"Be brief.",
|
||||||
|
])
|
||||||
|
.args(["--connection-key-file", key_file.to_str().unwrap()])
|
||||||
|
.args(extra)
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
{
|
||||||
|
use std::io::Write;
|
||||||
|
let _ = child.stdin.take().unwrap().write_all(stdin.as_bytes());
|
||||||
|
}
|
||||||
|
child.wait_with_output().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_toolcall_in_the_answer_is_an_error() {
|
||||||
|
let rig = rig(Script::ToolCall);
|
||||||
|
assert!(matches!(ask(&rig.args()).unwrap_err(), AskError::ToolCall));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rule: only a turn that ended (end of turn or a stop sequence) is an
|
||||||
|
/// answer; a truncated, refused or context-limited turn is an error even when
|
||||||
|
/// it carries text.
|
||||||
|
#[test]
|
||||||
|
fn a_turn_that_did_not_end_is_an_error() {
|
||||||
|
for reason in [
|
||||||
|
StopReason::MaxOutputTokens,
|
||||||
|
StopReason::Refusal,
|
||||||
|
StopReason::ContextWindow,
|
||||||
|
StopReason::ToolUse,
|
||||||
|
] {
|
||||||
|
let rig = rig(Script::Stop(reason));
|
||||||
|
assert!(
|
||||||
|
matches!(ask(&rig.args()).unwrap_err(), AskError::NotCompleted(r) if r == reason),
|
||||||
|
"{reason:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let rig = rig(Script::Stop(StopReason::StopSequence));
|
||||||
|
assert_eq!(ask(&rig.args()).unwrap(), "cut off");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_fifo_key_file_errors_promptly_instead_of_hanging() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let fifo = rig.dir.join("fifo.key");
|
||||||
|
let path = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap();
|
||||||
|
assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.key_file = fifo;
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
thread::spawn(move || tx.send(ask(&args)).unwrap());
|
||||||
|
let error = rx
|
||||||
|
.recv_timeout(Duration::from_secs(3))
|
||||||
|
.expect("reading a FIFO key file must not hang")
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(error, AskError::KeyNotRegular), "{error}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_key_file_readable_by_group_or_world_is_refused_and_a_private_one_accepted() {
|
||||||
|
let rig = rig(Script::Text("fine"));
|
||||||
|
for mode in [0o644, 0o640, 0o604] {
|
||||||
|
let path = rig.dir.join(format!("mode-{mode:o}.key"));
|
||||||
|
write_key(&path, KEY.as_bytes(), mode);
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.key_file = path;
|
||||||
|
let error = ask(&args).unwrap_err();
|
||||||
|
assert!(matches!(error, AskError::KeyExposed), "{mode:o}: {error}");
|
||||||
|
assert!(!message(&error).contains(KEY));
|
||||||
|
}
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
assert_eq!(ask(&rig.args()).unwrap(), "fine");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_symlinked_key_is_judged_by_its_target() {
|
||||||
|
let rig = rig(Script::Text("linked"));
|
||||||
|
let link = rig.dir.join("link.key");
|
||||||
|
std::os::unix::fs::symlink(&rig.key_file, &link).unwrap();
|
||||||
|
let mut args = rig.args();
|
||||||
|
args.key_file = link;
|
||||||
|
assert_eq!(ask(&args).unwrap(), "linked");
|
||||||
|
let dir_link = rig.dir.join("dir.key");
|
||||||
|
std::os::unix::fs::symlink(&rig.dir, &dir_link).unwrap();
|
||||||
|
args.key_file = dir_link;
|
||||||
|
assert!(matches!(ask(&args).unwrap_err(), AskError::KeyNotRegular));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_key_read_is_bounded_at_1024_bytes() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let path = rig.dir.join("big.key");
|
||||||
|
write_key(&path, &vec![b'k'; 1_025], 0o600);
|
||||||
|
assert!(matches!(
|
||||||
|
claude_connector::ask::read_key(&path).unwrap_err(),
|
||||||
|
AskError::KeyLength
|
||||||
|
));
|
||||||
|
write_key(&path, &vec![b'k'; 1_024], 0o600);
|
||||||
|
assert!(claude_connector::ask::read_key(&path).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_instructions_file_is_capped_and_must_be_a_regular_file() {
|
||||||
|
use claude_connector::ask::{MAX_SYSTEM_BYTES, read_system_file};
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let path = rig.dir.join("system.txt");
|
||||||
|
std::fs::write(&path, vec![b's'; MAX_SYSTEM_BYTES]).unwrap();
|
||||||
|
assert_eq!(read_system_file(&path).unwrap().len(), MAX_SYSTEM_BYTES);
|
||||||
|
std::fs::write(&path, vec![b's'; MAX_SYSTEM_BYTES + 1]).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
read_system_file(&path).unwrap_err(),
|
||||||
|
AskError::SystemTooLarge
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
read_system_file(&rig.dir).unwrap_err(),
|
||||||
|
AskError::SystemUnreadable
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_binary_never_prints_key_bytes_for_a_bad_key_file() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let cases: [(&str, &[u8], u32); 3] = [
|
||||||
|
("exposed", b"exposed-key-bytes-0123456789", 0o644),
|
||||||
|
("padded", b" padded-key-bytes-0123456789 ", 0o600),
|
||||||
|
("wrong", b"wrong-but-wellformed-key-0123456789", 0o600),
|
||||||
|
];
|
||||||
|
for (name, bytes, mode) in cases {
|
||||||
|
let path = rig.dir.join(format!("bin-{name}.key"));
|
||||||
|
write_key(&path, bytes, mode);
|
||||||
|
let out = run_binary_with_key(&rig, &path, "q", &[]);
|
||||||
|
assert!(!out.status.success(), "{name}");
|
||||||
|
let shown = [out.stdout.clone(), out.stderr.clone()].concat();
|
||||||
|
let shown = String::from_utf8_lossy(&shown);
|
||||||
|
assert!(
|
||||||
|
!shown.contains("key-bytes") && !shown.contains("wellformed"),
|
||||||
|
"{name}: {shown}"
|
||||||
|
);
|
||||||
|
assert!(out.stdout.is_empty());
|
||||||
|
}
|
||||||
|
let out = run_binary(&rig, "q", &["--system-file", "/nonexistent"]);
|
||||||
|
assert!(!out.status.success());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stdin_and_stdout_failures_have_their_own_wording() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||||
|
.args(["ask", "--endpoint", &rig.endpoint.to_string()])
|
||||||
|
.args(["--caller-id", CALLER, "--model", MODEL, "--system", "s"])
|
||||||
|
.args(["--connection-key-file", rig.key_file.to_str().unwrap()])
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
{
|
||||||
|
use std::io::Write;
|
||||||
|
child
|
||||||
|
.stdin
|
||||||
|
.take()
|
||||||
|
.unwrap()
|
||||||
|
.write_all(&[0xff, 0xfe])
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let out = child.wait_with_output().unwrap();
|
||||||
|
let err = String::from_utf8(out.stderr).unwrap();
|
||||||
|
assert!(err.contains("not UTF-8"), "{err}");
|
||||||
|
assert!(!err.contains("flag"), "{err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the wire returns for a tools-bearing request that gets past the CLI's
|
||||||
|
/// own construction (here forced by hand) when the real claude backend sits
|
||||||
|
/// behind the real serve loop: the service admits it, the backend's planner
|
||||||
|
/// refuses it, the caller receives a transported `Failed(InvalidRequest)`
|
||||||
|
/// result, and the claude child is never started.
|
||||||
|
#[test]
|
||||||
|
fn t_c0_oauth_still_cli_a_tools_request_is_refused_and_no_child_starts() {
|
||||||
|
use claude_connector::{
|
||||||
|
ChildEnv, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
|
||||||
|
SessionStore, StderrSink, TokenSource,
|
||||||
|
};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
struct CountingPort(Arc<AtomicUsize>);
|
||||||
|
impl ProcessPort for CountingPort {
|
||||||
|
fn spawn(
|
||||||
|
&self,
|
||||||
|
_: &[String],
|
||||||
|
_: &ChildEnv,
|
||||||
|
_: &std::path::Path,
|
||||||
|
_: Vec<u8>,
|
||||||
|
_: &str,
|
||||||
|
) -> std::io::Result<Box<dyn RunningChild>> {
|
||||||
|
self.0.fetch_add(1, Ordering::SeqCst);
|
||||||
|
Err(std::io::Error::other("no child in this test"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Fixed(&'static str);
|
||||||
|
impl TokenSource for Fixed {
|
||||||
|
fn read(&self) -> Option<Zeroizing<String>> {
|
||||||
|
Some(Zeroizing::new(self.0.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct NoSessions;
|
||||||
|
impl SessionStore for NoSessions {
|
||||||
|
fn exists(&self, _: &str) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Quiet;
|
||||||
|
impl StderrSink for Quiet {
|
||||||
|
fn stderr_tail(&self, _: &[u8]) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let dir =
|
||||||
|
std::env::temp_dir().join(format!("claude-connector-ask-tools-{}", std::process::id()));
|
||||||
|
for sub in ["work", "config", "prompt"] {
|
||||||
|
std::fs::create_dir_all(dir.join(sub)).unwrap();
|
||||||
|
}
|
||||||
|
let binary = dir.join("claude");
|
||||||
|
std::fs::write(&binary, b"pretend claude").unwrap();
|
||||||
|
let spawns = Arc::new(AtomicUsize::new(0));
|
||||||
|
let backend = ClaudeCodeBackend::with_ports(
|
||||||
|
ClaudeCodeConfig {
|
||||||
|
claude_binary: binary,
|
||||||
|
claude_binary_sha256: Sha256::digest(b"pretend claude").into(),
|
||||||
|
work_dir: dir.join("work"),
|
||||||
|
config_dir: dir.join("config"),
|
||||||
|
prompt_dir: dir.join("prompt"),
|
||||||
|
token_credential: "t".into(),
|
||||||
|
handle_secret_credential: "h".into(),
|
||||||
|
instance: "i".into(),
|
||||||
|
limits: ClaudeCodeLimits {
|
||||||
|
deadline: Duration::from_secs(5),
|
||||||
|
max_line_bytes: 1 << 16,
|
||||||
|
max_total_bytes: 1 << 20,
|
||||||
|
stderr_tail_bytes: 64,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Box::new(CountingPort(spawns.clone())),
|
||||||
|
Box::new(NoSessions),
|
||||||
|
Box::new(Quiet),
|
||||||
|
Box::new(Fixed("token")),
|
||||||
|
Box::new(Fixed(
|
||||||
|
"handle-secret-0000000000000000000000000000000000000000",
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let endpoint = listener.local_addr().unwrap();
|
||||||
|
let admission =
|
||||||
|
CallerAdmission::new(CALLER, KEY, 1, [MODEL.to_string()], 4, 1 << 20, 4_096).unwrap();
|
||||||
|
let limits = ServeLimits {
|
||||||
|
max_frame_bytes: FRAME,
|
||||||
|
max_connections: 8,
|
||||||
|
socket_timeout_ms: 5_000,
|
||||||
|
max_expiry_skew_ms: 300_000,
|
||||||
|
};
|
||||||
|
let store = dir.join("replay.cc");
|
||||||
|
thread::spawn(move || serve(listener, limits, vec![admission], &store, Arc::new(backend)));
|
||||||
|
|
||||||
|
let mut args = AskArgs {
|
||||||
|
endpoint,
|
||||||
|
caller_id: CALLER.into(),
|
||||||
|
key_file: dir.join("unused"),
|
||||||
|
model: MODEL.into(),
|
||||||
|
instructions: "i".into(),
|
||||||
|
effort: None,
|
||||||
|
max_output_tokens: 64,
|
||||||
|
timeout: Duration::from_secs(5),
|
||||||
|
prompt: "p".into(),
|
||||||
|
};
|
||||||
|
let mut forced = build_invocation(&args).unwrap().request;
|
||||||
|
forced.tools.push(ToolDefinition {
|
||||||
|
name: "lookup".into(),
|
||||||
|
description: "d".into(),
|
||||||
|
parameters_json: "{}".into(),
|
||||||
|
});
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_millis() as u64;
|
||||||
|
let invocation = TransportInvocation::new(
|
||||||
|
CALLER,
|
||||||
|
now + 60_000,
|
||||||
|
provider_request_sha256(&forced).unwrap(),
|
||||||
|
forced,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let client = ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
||||||
|
let result = client.execute(&invocation).unwrap();
|
||||||
|
let TransportDisposition::Transported { receipt, .. } = &result.disposition else {
|
||||||
|
panic!(
|
||||||
|
"expected the planner's failed result, got {:?}",
|
||||||
|
result.disposition
|
||||||
|
);
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
receipt.outcome,
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::InvalidRequest,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
spawns.load(Ordering::SeqCst),
|
||||||
|
0,
|
||||||
|
"the claude child must never start"
|
||||||
|
);
|
||||||
|
// The same CLI path with no tools would have reached the spawn.
|
||||||
|
args.key_file = dir.join("unused");
|
||||||
|
let clean = client.execute(&build_invocation(&args).unwrap()).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
clean.disposition,
|
||||||
|
TransportDisposition::Transported { .. }
|
||||||
|
));
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_binary_prints_the_answer_on_success() {
|
||||||
|
let rig = rig(Script::Text("pong"));
|
||||||
|
let out = run_binary(
|
||||||
|
&rig,
|
||||||
|
"ping",
|
||||||
|
&["--effort", "low", "--max-output-tokens", "1024"],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
out.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
assert_eq!(String::from_utf8(out.stdout).unwrap(), "pong");
|
||||||
|
assert!(out.stderr.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_binary_fails_loudly_with_one_stderr_line_and_empty_stdout() {
|
||||||
|
let rig = rig(Script::Text("x"));
|
||||||
|
let out = run_binary(&rig, "", &[]);
|
||||||
|
assert!(!out.status.success());
|
||||||
|
assert!(out.stdout.is_empty());
|
||||||
|
let err = String::from_utf8(out.stderr).unwrap();
|
||||||
|
assert_eq!(err.trim_end().lines().count(), 1, "{err}");
|
||||||
|
assert!(err.starts_with("claude-connector: "));
|
||||||
|
assert!(!err.contains(KEY));
|
||||||
|
// Tools, a working directory and a second endpoint are not flags.
|
||||||
|
for flag in ["--tools", "--cwd", "--work-dir"] {
|
||||||
|
let out = run_binary(&rig, "q", &[flag, "x"]);
|
||||||
|
assert!(!out.status.success());
|
||||||
|
assert!(out.stdout.is_empty());
|
||||||
|
}
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the binary with `--system-file` instead of `--system`, killing it if it
|
||||||
|
/// has not exited within five seconds (a hang is a failure, not a stuck suite).
|
||||||
|
fn run_with_system_file(rig: &Rig, file: &std::path::Path) -> std::process::Output {
|
||||||
|
use std::io::Write;
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||||
|
.args(["ask", "--endpoint", &rig.endpoint.to_string()])
|
||||||
|
.args(["--caller-id", CALLER, "--model", MODEL])
|
||||||
|
.args(["--max-output-tokens", "1024"])
|
||||||
|
.args(["--connection-key-file", rig.key_file.to_str().unwrap()])
|
||||||
|
.args(["--system-file", file.to_str().unwrap()])
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
let _ = child.stdin.take().unwrap().write_all(b"question");
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
while child.try_wait().unwrap().is_none() {
|
||||||
|
if started.elapsed() > Duration::from_secs(5) {
|
||||||
|
child.kill().unwrap();
|
||||||
|
let _ = child.wait();
|
||||||
|
panic!("the binary hung on its --system-file");
|
||||||
|
}
|
||||||
|
thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
child.wait_with_output().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_binary_bounds_and_guards_its_system_file() {
|
||||||
|
use claude_connector::ask::MAX_SYSTEM_BYTES;
|
||||||
|
let rig = rig(Script::Text("accepted"));
|
||||||
|
|
||||||
|
let fifo = rig.dir.join("system.fifo");
|
||||||
|
let path = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap();
|
||||||
|
assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
|
||||||
|
let out = run_with_system_file(&rig, &fifo);
|
||||||
|
assert!(!out.status.success());
|
||||||
|
assert!(out.stdout.is_empty());
|
||||||
|
|
||||||
|
let zero = run_with_system_file(&rig, std::path::Path::new("/dev/zero"));
|
||||||
|
assert!(!zero.status.success());
|
||||||
|
assert!(zero.stdout.is_empty());
|
||||||
|
|
||||||
|
let file = rig.dir.join("system.txt");
|
||||||
|
std::fs::write(&file, vec![b's'; MAX_SYSTEM_BYTES + 1]).unwrap();
|
||||||
|
let over = run_with_system_file(&rig, &file);
|
||||||
|
assert!(!over.status.success());
|
||||||
|
assert!(over.stdout.is_empty());
|
||||||
|
assert!(String::from_utf8_lossy(&over.stderr).contains("larger than"));
|
||||||
|
assert!(rig.seen().is_empty());
|
||||||
|
|
||||||
|
std::fs::write(&file, vec![b's'; MAX_SYSTEM_BYTES]).unwrap();
|
||||||
|
let exact = run_with_system_file(&rig, &file);
|
||||||
|
assert!(
|
||||||
|
exact.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&exact.stderr)
|
||||||
|
);
|
||||||
|
assert_eq!(String::from_utf8(exact.stdout).unwrap(), "accepted");
|
||||||
|
assert_eq!(rig.seen()[0].instructions.len(), MAX_SYSTEM_BYTES);
|
||||||
|
}
|
||||||
|
|
@ -8,7 +8,7 @@ use std::process::{Command, Output};
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
use claude_connector::{
|
use claude_connector::{
|
||||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
|
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
|
||||||
};
|
};
|
||||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||||
use model_connector::{CallerConfig, LeaseTurn};
|
use model_connector::{CallerConfig, LeaseTurn};
|
||||||
|
|
@ -53,6 +53,7 @@ fn valid() -> ClaudeConnectorConfig {
|
||||||
instance: "persona-a".to_string(),
|
instance: "persona-a".to_string(),
|
||||||
token_credential: "claude-token".to_string(),
|
token_credential: "claude-token".to_string(),
|
||||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||||
|
auth: ClaudeAuth::OAuthToken,
|
||||||
deadline_ms: 600_000,
|
deadline_ms: 600_000,
|
||||||
max_line_bytes: 4 << 20,
|
max_line_bytes: 4 << 20,
|
||||||
max_total_bytes: 64 << 20,
|
max_total_bytes: 64 << 20,
|
||||||
|
|
@ -286,3 +287,214 @@ fn the_dollar_flags_are_not_flags() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serve_refuses_a_document_that_is_not_there() {
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let missing = scratch.path("missing.cc");
|
||||||
|
let served = run(&["serve", "--config", missing.to_str().unwrap()]);
|
||||||
|
assert!(!served.status.success(), "{served:?}");
|
||||||
|
assert!(!String::from_utf8_lossy(&served.stderr).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_auth_choice_round_trips() {
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let path = scratch.path("connector.cc");
|
||||||
|
let keyed = ClaudeConnectorConfig {
|
||||||
|
auth: ClaudeAuth::ApiKey,
|
||||||
|
lease_socket: None,
|
||||||
|
lease_callers: vec![],
|
||||||
|
..valid()
|
||||||
|
};
|
||||||
|
write_config(&path, &keyed).unwrap();
|
||||||
|
assert_eq!(load_config(&path).unwrap().auth, ClaudeAuth::ApiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A document written before the auth field existed: the same type id, keys 0 to 22.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||||
|
#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")]
|
||||||
|
struct BeforeAuth {
|
||||||
|
#[cultcache(key = 0)]
|
||||||
|
listen: String,
|
||||||
|
#[cultcache(key = 1)]
|
||||||
|
replay_store: PathBuf,
|
||||||
|
#[cultcache(key = 2)]
|
||||||
|
claude_binary: PathBuf,
|
||||||
|
#[cultcache(key = 3)]
|
||||||
|
claude_binary_sha256: [u8; 32],
|
||||||
|
#[cultcache(key = 4)]
|
||||||
|
work_dir: PathBuf,
|
||||||
|
#[cultcache(key = 5)]
|
||||||
|
config_dir: PathBuf,
|
||||||
|
#[cultcache(key = 6)]
|
||||||
|
prompt_dir: PathBuf,
|
||||||
|
#[cultcache(key = 7)]
|
||||||
|
instance: String,
|
||||||
|
#[cultcache(key = 8)]
|
||||||
|
token_credential: String,
|
||||||
|
#[cultcache(key = 9)]
|
||||||
|
deadline_ms: u64,
|
||||||
|
#[cultcache(key = 10)]
|
||||||
|
max_line_bytes: usize,
|
||||||
|
#[cultcache(key = 11)]
|
||||||
|
max_total_bytes: usize,
|
||||||
|
#[cultcache(key = 12)]
|
||||||
|
stderr_tail_bytes: usize,
|
||||||
|
#[cultcache(key = 13)]
|
||||||
|
max_frame_bytes: usize,
|
||||||
|
#[cultcache(key = 14)]
|
||||||
|
max_connections: usize,
|
||||||
|
#[cultcache(key = 15)]
|
||||||
|
socket_timeout_ms: u64,
|
||||||
|
#[cultcache(key = 16)]
|
||||||
|
max_expiry_skew_ms: u64,
|
||||||
|
#[cultcache(key = 17)]
|
||||||
|
callers: Vec<CallerConfig>,
|
||||||
|
#[cultcache(key = 19)]
|
||||||
|
lease_socket: Option<PathBuf>,
|
||||||
|
#[cultcache(key = 20)]
|
||||||
|
lease_callers: Vec<LeaseCallerConfig>,
|
||||||
|
#[cultcache(key = 21)]
|
||||||
|
lease_max_ms: u64,
|
||||||
|
#[cultcache(key = 22)]
|
||||||
|
handle_secret_credential: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_document_from_before_the_auth_field_is_refused_until_it_is_authored_again() {
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let path = scratch.path("before.cc");
|
||||||
|
let now = valid();
|
||||||
|
{
|
||||||
|
let mut cache = CultCache::new();
|
||||||
|
cache.register_entry_type::<BeforeAuth>().unwrap();
|
||||||
|
cache
|
||||||
|
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
|
||||||
|
.unwrap();
|
||||||
|
cache
|
||||||
|
.put(
|
||||||
|
"runtime".to_string(),
|
||||||
|
&BeforeAuth {
|
||||||
|
listen: now.listen.clone(),
|
||||||
|
replay_store: now.replay_store.clone(),
|
||||||
|
claude_binary: now.claude_binary.clone(),
|
||||||
|
claude_binary_sha256: now.claude_binary_sha256,
|
||||||
|
work_dir: now.work_dir.clone(),
|
||||||
|
config_dir: now.config_dir.clone(),
|
||||||
|
prompt_dir: now.prompt_dir.clone(),
|
||||||
|
instance: now.instance.clone(),
|
||||||
|
token_credential: now.token_credential.clone(),
|
||||||
|
deadline_ms: now.deadline_ms,
|
||||||
|
max_line_bytes: now.max_line_bytes,
|
||||||
|
max_total_bytes: now.max_total_bytes,
|
||||||
|
stderr_tail_bytes: now.stderr_tail_bytes,
|
||||||
|
max_frame_bytes: now.max_frame_bytes,
|
||||||
|
max_connections: now.max_connections,
|
||||||
|
socket_timeout_ms: now.socket_timeout_ms,
|
||||||
|
max_expiry_skew_ms: now.max_expiry_skew_ms,
|
||||||
|
callers: now.callers.clone(),
|
||||||
|
lease_socket: now.lease_socket.clone(),
|
||||||
|
lease_callers: now.lease_callers.clone(),
|
||||||
|
lease_max_ms: now.lease_max_ms,
|
||||||
|
handle_secret_credential: now.handle_secret_credential.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
assert!(matches!(load_config(&path), Err(ConfigError::Store)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_init_takes_the_auth_flag_and_refuses_an_unknown_one() {
|
||||||
|
let auth_of = |extra: &[&str]| {
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let made = init(&scratch, &init_flags(&scratch, extra));
|
||||||
|
made.status
|
||||||
|
.success()
|
||||||
|
.then(|| load_config(&scratch.path("connector.cc")).unwrap().auth)
|
||||||
|
};
|
||||||
|
assert_eq!(auth_of(&[]), Some(ClaudeAuth::OAuthToken));
|
||||||
|
assert_eq!(auth_of(&["--auth", "oauth-token"]), Some(ClaudeAuth::OAuthToken));
|
||||||
|
assert_eq!(auth_of(&["--auth", "api-key"]), Some(ClaudeAuth::ApiKey));
|
||||||
|
assert_eq!(auth_of(&["--auth", "key"]), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The document an operator could author by hand around `write_config`'s refusal: a key and a lease.
|
||||||
|
fn keyed_with_a_lease() -> ClaudeConnectorConfig {
|
||||||
|
ClaudeConnectorConfig {
|
||||||
|
auth: ClaudeAuth::ApiKey,
|
||||||
|
..valid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_key_is_never_lent_so_no_lease_socket_or_row_may_accompany_it() {
|
||||||
|
assert_eq!(refused(&keyed_with_a_lease()), "auth");
|
||||||
|
let socket_only = ClaudeConnectorConfig {
|
||||||
|
lease_callers: vec![],
|
||||||
|
..keyed_with_a_lease()
|
||||||
|
};
|
||||||
|
assert_eq!(refused(&socket_only), "auth");
|
||||||
|
let rows_only = ClaudeConnectorConfig {
|
||||||
|
lease_socket: None,
|
||||||
|
..keyed_with_a_lease()
|
||||||
|
};
|
||||||
|
assert_eq!(refused(&rows_only), "auth");
|
||||||
|
let personas_only = ClaudeConnectorConfig {
|
||||||
|
lease_socket: None,
|
||||||
|
lease_callers: vec![],
|
||||||
|
..keyed_with_a_lease()
|
||||||
|
};
|
||||||
|
assert!(personas_only.validate().is_ok());
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
assert!(write_config(&scratch.path("keyed.cc"), &keyed_with_a_lease()).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_init_refuses_a_key_with_a_lease_and_accepts_it_without() {
|
||||||
|
let lease = [
|
||||||
|
"--lease-socket",
|
||||||
|
"/run/claude-connector/lease.sock",
|
||||||
|
"--lease-user",
|
||||||
|
"mind-a-self",
|
||||||
|
"--turn",
|
||||||
|
"self",
|
||||||
|
"--lease-unit-instance",
|
||||||
|
"a",
|
||||||
|
];
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let leased = init(&scratch, &init_flags(&scratch, &[&["--auth", "api-key"], &lease[..]].concat()));
|
||||||
|
assert!(!leased.status.success(), "{leased:?}");
|
||||||
|
assert!(!scratch.path("connector.cc").exists());
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let bare = init(&scratch, &init_flags(&scratch, &["--auth", "api-key"]));
|
||||||
|
assert!(bare.status.success(), "{bare:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serve_and_check_refuse_a_key_document_that_carries_a_lease() {
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let path = scratch.path("handmade.cc");
|
||||||
|
{
|
||||||
|
// Written around write_config, which would refuse it.
|
||||||
|
let mut cache = CultCache::new();
|
||||||
|
cache.register_entry_type::<ClaudeConnectorConfig>().unwrap();
|
||||||
|
cache
|
||||||
|
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
|
||||||
|
.unwrap();
|
||||||
|
cache
|
||||||
|
.put("runtime".to_string(), &keyed_with_a_lease())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let p = path.to_str().unwrap();
|
||||||
|
for args in [vec!["serve", "--config", p], vec!["config", "check", p]] {
|
||||||
|
let out = run(&args);
|
||||||
|
assert!(!out.status.success(), "{args:?}: {out:?}");
|
||||||
|
assert!(
|
||||||
|
String::from_utf8_lossy(&out.stderr).contains("auth"),
|
||||||
|
"{args:?}: {}",
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
4
crates/claude-connector/tests/fixtures/claude-2.1.312-meter-call.jsonl
vendored
Normal file
4
crates/claude-connector/tests/fixtures/claude-2.1.312-meter-call.jsonl
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
{"type":"system","subtype":"init","cwd":"/tmp/meter-probe.Ye68uq/work","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","tools":[],"mcp_servers":[],"model":"claude-haiku-5-5","permissionMode":"bypassPermissions","slash_commands":[],"apiKeySource":"none","claude_code_version":"2.1.312","output_style":"default","agents":["claude","Explore","general-purpose","Plan","statusline-setup"],"skills":[],"plugins":[{"name":"cc-plugin-sec-default","path":"builtin","source":"cc-plugin-sec-default@builtin"},{"name":"cc-plugin-agents-md","path":"builtin","source":"cc-plugin-agents-md@builtin"},{"name":"cc-plugin-telemetry","path":"builtin","source":"cc-plugin-telemetry@builtin"},{"name":"cc-plugin-plugin-authoring","path":"builtin","source":"cc-plugin-plugin-authoring@builtin"}],"capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"analytics_disabled":false,"product_feedback_disabled":false,"uuid":"8ad7f8d7-2831-43f2-a221-8af6323dcbd9","memory_paths":{"auto":"/tmp/meter-probe.Ye68uq/home/projects/-tmp-meter-probe-Ye68uq-work/memory/"},"original_cwd":"/tmp/meter-probe.Ye68uq/work","additional_directories":[],"messaging_socket_path":"/tmp/cc-socks/2838104.sock","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","per_turn_effort_active":true,"view_mode":"default"}
|
||||||
|
{"type":"assistant","message":{"model":"claude-haiku-5-5","id":"msg_011Cgfu1sQvRAVmjwWNHc58s","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":384,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":4,"service_tier":"standard","inference_geo":"global","speed":"standard"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","uuid":"f80db687-b098-415c-ac44-51c40a6cb63a","timestamp":"2026-11-03T11:14:35.024Z","request_id":"req_011Cgfu1sCXBsDrfz8a1LoMd"}
|
||||||
|
{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1794261600,"rateLimitType":"seven_day","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false,"unifiedWindows":{"seven_day":{"utilization":0.06,"resetsAt":1794261600,"status":"allowed"}}},"uuid":"acb3b364-a218-4965-b967-f73028254f8b","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01"}
|
||||||
|
{"duration_api_ms":995,"stop_reason":"end_turn","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","total_cost_usd":0.000040400000000000006,"usage":{"input_tokens":384,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":4,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[{"input_tokens":384,"output_tokens":4,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-haiku-5-5":{"inputTokens":384,"outputTokens":4,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.000040400000000000006,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":0,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":false,"num_turns":1,"subtype":"success","api_error_status":null,"result":"ok","ttft_ms":1210,"type":"result","duration_ms":1228,"uuid":"d0b1b31b-1428-45aa-b90e-d35903c9b91b","ttft_stream_ms":1209,"time_to_request_ms":232,"first_content_frame_ms":1209,"queued_turn_count":0,"result_index":0,"model_usage_since_last_result":{"claude-haiku-5-5":{"inputTokens":384,"outputTokens":4,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.000040400000000000006,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":0,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}}}
|
||||||
|
|
@ -11,6 +11,10 @@ big-endian length, then the named-MessagePack map `{kind, value}`).
|
||||||
`seven_day` windows (utilization_permille, resets_at_unix_ms, status, observed_at_unix_ms).
|
`seven_day` windows (utilization_permille, resets_at_unix_ms, status, observed_at_unix_ms).
|
||||||
On the wire the grant travels with one SCM_RIGHTS fd; the file holds the frame only.
|
On the wire the grant travels with one SCM_RIGHTS fd; the file holds the frame only.
|
||||||
|
|
||||||
|
- `usage_readout_request.bin`: `claude_usage_readout_request`, an empty map; opens no lease.
|
||||||
|
- `usage_readout.bin`: `claude_usage_readout`, the kit's `UsageReadout` (`schema_id`, `at_unix_ms`,
|
||||||
|
`plan_quota` with `five_hour` and `seven_day` windows); no fd travels with it.
|
||||||
|
|
||||||
Huginn's lease client vendors these files from this repository and tests against the same
|
Huginn's lease client vendors these files from this repository and tests against the same
|
||||||
bytes. Generator: `tests/lease_wire_golden.rs`; run it with `LEASE_V2_REGENERATE=1`, then
|
bytes. Generator: `tests/lease_wire_golden.rs`; run it with `LEASE_V2_REGENERATE=1`, then
|
||||||
review the diff: a changed byte is a wire change.
|
review the diff: a changed byte is a wire change.
|
||||||
|
|
|
||||||
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout.bin
vendored
Normal file
Binary file not shown.
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout_request.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout_request.bin
vendored
Normal file
Binary file not shown.
|
|
@ -15,10 +15,10 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use claude_connector::{
|
use claude_connector::{
|
||||||
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
||||||
LeaseRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource, decode_frame, encode_frame,
|
LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource,
|
||||||
serve_leases,
|
decode_frame, encode_frame, serve_leases,
|
||||||
};
|
};
|
||||||
use model_connector::{CallerAdmission, LeaseTurn, PlanQuota, TransportService};
|
use model_connector::{CallerAdmission, LeaseTurn, PlanQuota, TransportService, UsageReadout};
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
const CALLER: &str = "eureka";
|
const CALLER: &str = "eureka";
|
||||||
|
|
@ -649,3 +649,80 @@ fn a_request_trickled_past_the_socket_timeout_is_dropped_without_a_lease() {
|
||||||
assert!(started.elapsed() < Duration::from_secs(6));
|
assert!(started.elapsed() < Duration::from_secs(6));
|
||||||
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
|
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a usage readout request came back with.
|
||||||
|
fn read_usage(harness: &Harness) -> Answer {
|
||||||
|
let mut stream = UnixStream::connect(&harness.socket).unwrap();
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(10)))
|
||||||
|
.unwrap();
|
||||||
|
stream
|
||||||
|
.write_all(&encode_frame(&LeaseMessage::ClaudeUsageReadoutRequest(
|
||||||
|
LeaseUsageReadoutRequest {},
|
||||||
|
)))
|
||||||
|
.unwrap();
|
||||||
|
let (raw, fds) = receive(&stream);
|
||||||
|
let message = decode_frame(&raw);
|
||||||
|
Answer {
|
||||||
|
_stream: stream,
|
||||||
|
raw,
|
||||||
|
message,
|
||||||
|
fds,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usage_of(answer: &Answer) -> UsageReadout {
|
||||||
|
match &answer.message {
|
||||||
|
Some(LeaseMessage::ClaudeUsageReadout(readout)) => readout.clone(),
|
||||||
|
other => panic!("expected a usage readout, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_readout_answers_the_cells_windows_and_lends_nothing() {
|
||||||
|
let harness = start(setup());
|
||||||
|
let reset = now_ms() + 3_600_000;
|
||||||
|
harness.quota.observe([
|
||||||
|
window("five_hour", 420, "allowed", reset),
|
||||||
|
window("seven_day", 999, "allowed_warning", reset + 86_400_000),
|
||||||
|
]);
|
||||||
|
let before = now_ms();
|
||||||
|
let answer = read_usage(&harness);
|
||||||
|
let readout = usage_of(&answer);
|
||||||
|
assert!(answer.fds.is_empty(), "a readout lends no descriptor");
|
||||||
|
assert_eq!(readout.plan_quota, harness.quota.snapshot().windows);
|
||||||
|
assert_eq!(readout.plan_quota.len(), 2);
|
||||||
|
assert!(readout.at_unix_ms >= before && readout.at_unix_ms <= now_ms());
|
||||||
|
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
|
||||||
|
// No lease was opened: the next request is granted.
|
||||||
|
assert!(granted_ok(&ask(&harness, 60_000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_peer_outside_the_lease_callers_still_reads_usage() {
|
||||||
|
let harness = start(Setup {
|
||||||
|
uid: own_uid().wrapping_add(1),
|
||||||
|
..setup()
|
||||||
|
});
|
||||||
|
harness
|
||||||
|
.quota
|
||||||
|
.observe([window("five_hour", 420, "allowed", now_ms() + 3_600_000)]);
|
||||||
|
let refused = ask(&harness, 60_000);
|
||||||
|
assert_eq!(refusal_of(&refused), Some(LeaseRefusalKind::UnknownCaller));
|
||||||
|
let readout = usage_of(&read_usage(&harness));
|
||||||
|
assert_eq!(readout.plan_quota.len(), 1);
|
||||||
|
assert_eq!(readout.plan_quota[0].utilization_permille, Some(420));
|
||||||
|
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_readout_beside_a_held_lease_leaves_it_held() {
|
||||||
|
let harness = start(setup());
|
||||||
|
let held = ask(&harness, 60_000);
|
||||||
|
assert!(granted_ok(&held));
|
||||||
|
assert_eq!(usage_of(&read_usage(&harness)).plan_quota.len(), 0);
|
||||||
|
harness.enter(2);
|
||||||
|
let second = ask(&harness, 60_000);
|
||||||
|
assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy));
|
||||||
|
assert!(granted_ok(&held));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,10 +8,10 @@
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use claude_connector::{
|
use claude_connector::{
|
||||||
LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest, decode_frame,
|
LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest,
|
||||||
encode_frame,
|
LeaseUsageReadoutRequest, decode_frame, encode_frame,
|
||||||
};
|
};
|
||||||
use model_connector::PlanQuota;
|
use model_connector::{PlanQuota, PlanQuotaSnapshot, UsageReadout};
|
||||||
|
|
||||||
const REGENERATE: &str = "LEASE_V2_REGENERATE";
|
const REGENERATE: &str = "LEASE_V2_REGENERATE";
|
||||||
|
|
||||||
|
|
@ -97,3 +97,38 @@ fn a_grant_with_both_usage_windows_is_pinned() {
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_usage_readout_frames_are_pinned() {
|
||||||
|
let window = |name: &str, permille, status: &str, resets| PlanQuota {
|
||||||
|
window: name.to_string(),
|
||||||
|
utilization_permille: Some(permille),
|
||||||
|
resets_at_unix_ms: resets,
|
||||||
|
status: status.to_string(),
|
||||||
|
observed_at_unix_ms: 1_793_300_000_000,
|
||||||
|
};
|
||||||
|
let request = LeaseMessage::ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest {});
|
||||||
|
let answer = LeaseMessage::ClaudeUsageReadout(UsageReadout::new(
|
||||||
|
1_793_300_100_000,
|
||||||
|
PlanQuotaSnapshot {
|
||||||
|
windows: vec![
|
||||||
|
window("five_hour", 420, "allowed", 1_793_307_000_000),
|
||||||
|
window("seven_day", 999, "allowed_warning", 1_793_800_000_000),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
));
|
||||||
|
assert_frame("usage_readout_request.bin", &request);
|
||||||
|
assert_frame("usage_readout.bin", &answer);
|
||||||
|
for (message, spelled) in [
|
||||||
|
(&request, "claude_usage_readout_request"),
|
||||||
|
(&answer, "claude_usage_readout"),
|
||||||
|
] {
|
||||||
|
let bytes = encode_frame(message);
|
||||||
|
let value: rmpv::Value = rmp_serde::from_slice(&bytes[4..]).unwrap();
|
||||||
|
let rmpv::Value::Map(outer) = value else {
|
||||||
|
panic!("a frame is a map")
|
||||||
|
};
|
||||||
|
assert_eq!(outer[0].0.as_str(), Some("kind"));
|
||||||
|
assert_eq!(outer[0].1.as_str(), Some(spelled));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue