Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dc182facf | ||
|
|
d65fb21870 | ||
|
|
4e3df9e114 | ||
|
|
73aea04fb7 | ||
|
|
c1650d5271 | ||
|
|
43085cf5fe | ||
|
|
4796f917ac | ||
|
|
81f1734fd1 | ||
|
|
0904b2eb31 | ||
|
|
c0386bbcd5 | ||
|
|
0098e3d23d | ||
|
|
0d9b7eec70 | ||
|
|
cf30634d3d | ||
|
|
6d22c60529 | ||
|
|
8c320d4626 | ||
|
|
a7ac40d59a | ||
|
|
0b2f3fc3e3 | ||
|
|
3dfd3125cb | ||
|
|
bea242eb58 | ||
|
|
8c45189ae8 | ||
|
|
92e23ea3ce | ||
|
|
38f66dd29c | ||
|
|
898779f4dd | ||
| edf2f8e03c | |||
| 80c1fc6a69 | |||
|
|
3f87b19a2d | ||
|
|
f52eef1657 | ||
|
|
e80e522c10 | ||
| 9d0f4b400c | |||
| 2a65c4e7a2 | |||
| 42a157b049 | |||
| c47597b421 | |||
| 61cc59d9a0 |
35 changed files with 11567 additions and 840 deletions
138
Cargo.lock
generated
138
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"
|
||||||
|
|
@ -144,12 +156,14 @@ dependencies = [
|
||||||
"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",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -231,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",
|
||||||
|
|
@ -436,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"
|
||||||
|
|
@ -510,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",
|
||||||
|
|
@ -555,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"
|
||||||
|
|
@ -699,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"
|
||||||
|
|
@ -738,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"
|
||||||
|
|
@ -985,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"
|
||||||
|
|
@ -1062,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"
|
||||||
|
|
|
||||||
29
README.md
29
README.md
|
|
@ -9,8 +9,8 @@ publishes the plan's usage windows (`usage_readout`, `claude_usage_readout` on t
|
||||||
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
|
||||||
|
|
@ -17,11 +17,13 @@ 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]
|
||||||
|
|
|
||||||
338
crates/claude-connector/src/ask.rs
Normal file
338
crates/claude-connector/src/ask.rs
Normal file
|
|
@ -0,0 +1,338 @@
|
||||||
|
//! `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 {
|
||||||
|
provider_id: "claude-code".into(),
|
||||||
|
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(),
|
||||||
|
meter_model: None,
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use model_connector::{
|
use model_connector::{
|
||||||
FailureKind, InputItem, PlanQuotaSnapshot, ProviderBackend, ProviderCall, ProviderRequest,
|
FailureKind, InputItem, PlanQuotaSnapshot, ProviderRequest, ToolChoice, TransportEvent,
|
||||||
TransportEvent, TransportEventPayload, TransportOutcome, TransportResult, Usage,
|
TransportEventPayload, TransportOutcome, Usage,
|
||||||
};
|
};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
use crate::config::{ClaudeCodeConfig, PROVIDER};
|
use crate::config::{ClaudeCodeConfig, ModelRow, OutputSchemaSupport};
|
||||||
|
use crate::credential::{CredentialTokenSource, TokenSource, credential_ready};
|
||||||
use crate::handle::{
|
use crate::handle::{
|
||||||
Binding, ClaudeCodeHandle, MIN_SECRET_BYTES, SessionStore, plan, prefix_digest, stdin_bytes,
|
Binding, ClaudeCodeHandle, MIN_SECRET_BYTES, SessionStore, plan, prefix_digest, stdin_bytes,
|
||||||
};
|
};
|
||||||
|
|
@ -20,81 +20,9 @@ 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_CALLER: &str = "meter";
|
||||||
const METER_MAX_OUTPUT_TOKENS: u32 = 16;
|
const METER_MAX_OUTPUT_TOKENS: u32 = 16;
|
||||||
|
|
||||||
/// Where the child's credential comes from, read afresh at every use. The
|
|
||||||
/// connector's own environment is never a source (ruling
|
|
||||||
/// claude-connector-token-credential).
|
|
||||||
pub trait TokenSource: Send + Sync {
|
|
||||||
/// The token, or `None` when there is none or it is empty.
|
|
||||||
fn read(&self) -> Option<Zeroizing<String>>;
|
|
||||||
/// What `config check` names when `read` has no token.
|
|
||||||
fn missing(&self) -> &'static str {
|
|
||||||
"token_credential"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A token in a file named by a systemd credential: the file
|
|
||||||
/// `$CREDENTIALS_DIRECTORY/<name>`, read on every call so a rotated credential
|
|
||||||
/// is picked up by the next spawn.
|
|
||||||
pub struct CredentialTokenSource {
|
|
||||||
directory: Option<PathBuf>,
|
|
||||||
name: String,
|
|
||||||
/// The configuration field `missing` names when the credential is absent.
|
|
||||||
field: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CredentialTokenSource {
|
|
||||||
/// The credential `name` under the directory systemd names in
|
|
||||||
/// `CREDENTIALS_DIRECTORY`; with no such variable the source has no token.
|
|
||||||
/// The variable names a directory, never a token.
|
|
||||||
pub fn from_environment(name: impl Into<String>) -> Self {
|
|
||||||
Self {
|
|
||||||
directory: std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from),
|
|
||||||
name: name.into(),
|
|
||||||
field: "token_credential",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The same source, naming `field` when its credential is absent.
|
|
||||||
pub fn for_field(mut self, field: &'static str) -> Self {
|
|
||||||
self.field = field;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn in_directory(directory: impl Into<PathBuf>, name: impl Into<String>) -> Self {
|
|
||||||
Self {
|
|
||||||
directory: Some(directory.into()),
|
|
||||||
name: name.into(),
|
|
||||||
field: "token_credential",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TokenSource for CredentialTokenSource {
|
|
||||||
fn read(&self) -> Option<Zeroizing<String>> {
|
|
||||||
let directory = self.directory.as_ref()?;
|
|
||||||
let mut token = Zeroizing::new(std::fs::read_to_string(directory.join(&self.name)).ok()?);
|
|
||||||
let trimmed = token.trim_end_matches(['\r', '\n']).len();
|
|
||||||
token.truncate(trimmed);
|
|
||||||
(!token.is_empty()).then_some(token)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// No directory at all is the unit's environment lacking its credentials,
|
|
||||||
/// which is not the same fault as a credential the directory lacks.
|
|
||||||
fn missing(&self) -> &'static str {
|
|
||||||
if self.directory.is_none() {
|
|
||||||
"credentials_directory"
|
|
||||||
} else {
|
|
||||||
self.field
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where the tail of a child's stderr goes. The backend never puts it in a
|
/// Where the tail of a child's stderr goes. The backend never puts it in a
|
||||||
/// result; the connector binary wires this to its log.
|
/// result; the connector binary wires this to its log.
|
||||||
pub trait StderrSink: Send + Sync {
|
pub trait StderrSink: Send + Sync {
|
||||||
|
|
@ -157,27 +85,50 @@ impl ClaudeCodeBackend {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Provider tag written on receipts and matched on reasoning state items.
|
||||||
|
pub fn provider_id(&self) -> &str {
|
||||||
|
&self.config.provider_id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the backend can take work, naming the first config field that
|
||||||
|
/// cannot be used.
|
||||||
|
pub fn ready(&self) -> Result<(), &'static str> {
|
||||||
|
readiness(
|
||||||
|
&self.config,
|
||||||
|
self.tokens.as_ref(),
|
||||||
|
self.handle_secret.as_ref(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// The plan windows every stream this backend reads feeds.
|
/// The plan windows every stream this backend reads feeds.
|
||||||
pub fn quota(&self) -> Arc<QuotaCell> {
|
pub fn quota(&self) -> Arc<QuotaCell> {
|
||||||
self.quota.clone()
|
self.quota.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Latest plan quota snapshot paired with this backend's provider id.
|
||||||
|
pub fn plan_quota(&self) -> (&str, PlanQuotaSnapshot) {
|
||||||
|
(&self.config.provider_id, self.quota.snapshot())
|
||||||
|
}
|
||||||
|
|
||||||
/// The meter's call: the smallest real one, through the same child,
|
/// 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
|
/// 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
|
/// the caller wants; this returns what the call billed, or the failure's
|
||||||
/// kind (never its message).
|
/// kind (never its message).
|
||||||
pub(crate) fn read_meter(&self) -> Result<Usage, String> {
|
pub(crate) fn read_meter(&self) -> Result<Usage, String> {
|
||||||
|
let Some(model) = self.config.meter_model.as_deref() else {
|
||||||
|
return Err("MissingMeterModel".to_string());
|
||||||
|
};
|
||||||
let mut request = ProviderRequest::new(
|
let mut request = ProviderRequest::new(
|
||||||
METER_CALLER,
|
METER_CALLER,
|
||||||
METER_CALLER,
|
METER_CALLER,
|
||||||
METER_MODEL,
|
model,
|
||||||
"Reply with the single word ok.",
|
"Reply with the single word ok.",
|
||||||
METER_MAX_OUTPUT_TOKENS,
|
METER_MAX_OUTPUT_TOKENS,
|
||||||
);
|
);
|
||||||
request.input = vec![InputItem::UserText {
|
request.input = vec![InputItem::UserText {
|
||||||
text: "ok?".to_string(),
|
text: "ok?".to_string(),
|
||||||
}];
|
}];
|
||||||
match self.run(&request, METER_CALLER, true).1 {
|
match self.run_inner(&request, METER_CALLER, None, true).1 {
|
||||||
TransportOutcome::Completed { usage, .. } => Ok(usage),
|
TransportOutcome::Completed { usage, .. } => Ok(usage),
|
||||||
TransportOutcome::Failed { kind, .. } => Err(format!("{kind:?}")),
|
TransportOutcome::Failed { kind, .. } => Err(format!("{kind:?}")),
|
||||||
}
|
}
|
||||||
|
|
@ -189,12 +140,54 @@ impl ClaudeCodeBackend {
|
||||||
binary_matches_pin(&self.config)
|
binary_matches_pin(&self.config)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `ephemeral` leaves no transcript behind: the meter keeps no handle and
|
pub(crate) fn run_model(
|
||||||
/// resumes nothing, every other call is resumed by its session.
|
|
||||||
fn run(
|
|
||||||
&self,
|
&self,
|
||||||
request: &ProviderRequest,
|
request: &ProviderRequest,
|
||||||
caller: &str,
|
caller: &str,
|
||||||
|
row: &ModelRow,
|
||||||
|
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
let effort = match row.resolve_effort(request.reasoning_effort) {
|
||||||
|
Ok(effort) => effort,
|
||||||
|
Err(message) => {
|
||||||
|
return failed(
|
||||||
|
FailureKind::InvalidRequest,
|
||||||
|
format!("{}: {message}", self.config.provider_id),
|
||||||
|
Some(zero_usage()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if request.output_schema_json.is_some() && row.output_schema == OutputSchemaSupport::None {
|
||||||
|
return failed(
|
||||||
|
FailureKind::InvalidRequest,
|
||||||
|
format!(
|
||||||
|
"{}: model {} does not accept an output schema",
|
||||||
|
self.config.provider_id, row.id
|
||||||
|
),
|
||||||
|
Some(zero_usage()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if request.tool_choice == ToolChoice::Required
|
||||||
|
&& !row.allows_forced_tool_choice(ModelRow::thinking_active(effort))
|
||||||
|
{
|
||||||
|
return failed(
|
||||||
|
FailureKind::InvalidRequest,
|
||||||
|
format!(
|
||||||
|
"{}: model {} does not accept a required tool choice",
|
||||||
|
self.config.provider_id, row.id
|
||||||
|
),
|
||||||
|
Some(zero_usage()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.run_inner(request, caller, effort, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ephemeral` leaves no transcript behind: the meter keeps no handle and
|
||||||
|
/// resumes nothing, every other call is resumed by its session.
|
||||||
|
fn run_inner(
|
||||||
|
&self,
|
||||||
|
request: &ProviderRequest,
|
||||||
|
caller: &str,
|
||||||
|
effort: Option<&str>,
|
||||||
ephemeral: bool,
|
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 {
|
||||||
|
|
@ -239,7 +232,14 @@ 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(), ephemeral);
|
let argv = argv(
|
||||||
|
&self.config,
|
||||||
|
request,
|
||||||
|
&plan,
|
||||||
|
prompt.path(),
|
||||||
|
effort,
|
||||||
|
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;
|
||||||
|
|
||||||
|
|
@ -261,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();
|
||||||
|
|
@ -339,35 +339,12 @@ impl ClaudeCodeBackend {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProviderBackend for ClaudeCodeBackend {
|
|
||||||
fn ready(&self) -> Result<(), &'static str> {
|
|
||||||
readiness(
|
|
||||||
&self.config,
|
|
||||||
self.tokens.as_ref(),
|
|
||||||
self.handle_secret.as_ref(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn provider(&self) -> &str {
|
|
||||||
PROVIDER
|
|
||||||
}
|
|
||||||
|
|
||||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
|
||||||
let (events, outcome) = self.run(call.request(), call.caller_runtime_id(), false);
|
|
||||||
call.transported(events, outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plan_quota(&self) -> PlanQuotaSnapshot {
|
|
||||||
self.quota.snapshot()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_stream(
|
fn read_stream(
|
||||||
child: &mut dyn RunningChild,
|
child: &mut dyn RunningChild,
|
||||||
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 {
|
||||||
|
|
@ -435,9 +412,7 @@ pub(crate) fn readiness(
|
||||||
if usable_secret(handle_secret).is_none() {
|
if usable_secret(handle_secret).is_none() {
|
||||||
return Err(handle_secret.missing());
|
return Err(handle_secret.missing());
|
||||||
}
|
}
|
||||||
if tokens.read().is_none() {
|
credential_ready(tokens)?;
|
||||||
return Err(tokens.missing());
|
|
||||||
}
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,16 +5,18 @@ use std::sync::{Arc, Mutex};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use model_connector::{
|
use model_connector::{
|
||||||
CallerAdmission, PlanQuotaSnapshot, ReasoningEffort, StopReason, ToolDefinition,
|
CallerAdmission, ProviderBackend, ProviderRoutes, ReasoningEffort, StopReason, ToolDefinition,
|
||||||
TransportAdmission, TransportDisposition, TransportInvocation, TransportKey, TransportReceipt,
|
TransportAdmission, TransportDisposition, TransportInvocation, TransportKey, TransportReceipt,
|
||||||
TransportService, decrypt_result, encrypt_invocation,
|
TransportResult, TransportService, decrypt_result, encrypt_invocation,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::config::ClaudeCodeLimits;
|
use crate::config::{ClaudeCodeLimits, EffortMap, ForcedToolChoice, ModelRow, OutputSchemaSupport};
|
||||||
use crate::handle::{FsSessionStore, SessionStore};
|
use crate::handle::{FsSessionStore, SessionStore};
|
||||||
use crate::launch::ChildEnv;
|
use crate::launch::ChildEnv;
|
||||||
|
use crate::router::RouterBackend;
|
||||||
|
|
||||||
|
const PROVIDER: &str = "claude-code";
|
||||||
const CANARY_TOKEN: &str = "canary-oauth-token-value";
|
const CANARY_TOKEN: &str = "canary-oauth-token-value";
|
||||||
/// The variable the connector's own environment must never hand on.
|
/// The variable the connector's own environment must never hand on.
|
||||||
const TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN";
|
const TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN";
|
||||||
|
|
@ -325,8 +327,27 @@ fn sandbox() -> TempDir {
|
||||||
dir
|
dir
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn default_row(id: &str) -> ModelRow {
|
||||||
|
ModelRow {
|
||||||
|
id: id.to_string(),
|
||||||
|
provider: PROVIDER.to_string(),
|
||||||
|
upstream: id.to_string(),
|
||||||
|
efforts: EffortMap {
|
||||||
|
low: Some("low".to_string()),
|
||||||
|
medium: Some("medium".to_string()),
|
||||||
|
high: Some("high".to_string()),
|
||||||
|
max: Some("max".to_string()),
|
||||||
|
},
|
||||||
|
unset_effort: None,
|
||||||
|
forced_tool_choice: ForcedToolChoice::Never,
|
||||||
|
output_schema: OutputSchemaSupport::Native,
|
||||||
|
strict_tools: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeConfig {
|
fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeConfig {
|
||||||
ClaudeCodeConfig {
|
ClaudeCodeConfig {
|
||||||
|
provider_id: PROVIDER.to_string(),
|
||||||
claude_binary: dir.join("claude"),
|
claude_binary: dir.join("claude"),
|
||||||
claude_binary_sha256: pin_of(PINNED),
|
claude_binary_sha256: pin_of(PINNED),
|
||||||
work_dir: PathBuf::from("/work"),
|
work_dir: PathBuf::from("/work"),
|
||||||
|
|
@ -335,6 +356,7 @@ fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeCon
|
||||||
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(),
|
||||||
instance: instance.to_string(),
|
instance: instance.to_string(),
|
||||||
|
meter_model: Some(MODEL.to_string()),
|
||||||
limits,
|
limits,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -383,7 +405,8 @@ fn limits() -> ClaudeCodeLimits {
|
||||||
|
|
||||||
struct Rig {
|
struct Rig {
|
||||||
dir: TempDir,
|
dir: TempDir,
|
||||||
backend: ClaudeCodeBackend,
|
backend: Arc<ClaudeCodeBackend>,
|
||||||
|
router: RouterBackend,
|
||||||
spawns: Arc<AtomicUsize>,
|
spawns: Arc<AtomicUsize>,
|
||||||
seen: Arc<Mutex<Seen>>,
|
seen: Arc<Mutex<Seen>>,
|
||||||
sink: Sink,
|
sink: Sink,
|
||||||
|
|
@ -410,17 +433,25 @@ fn rig_with_secret(
|
||||||
stderr: stderr.to_vec(),
|
stderr: stderr.to_vec(),
|
||||||
};
|
};
|
||||||
let dir = sandbox();
|
let dir = sandbox();
|
||||||
let backend = ClaudeCodeBackend::with_ports(
|
let backend = Arc::new(ClaudeCodeBackend::with_ports(
|
||||||
config(dir.path(), instance, limits()),
|
config(dir.path(), instance, limits()),
|
||||||
Box::new(port),
|
Box::new(port),
|
||||||
Box::new(Sessions(sessions.iter().map(|s| s.to_string()).collect())),
|
Box::new(Sessions(sessions.iter().map(|s| s.to_string()).collect())),
|
||||||
Box::new(sink.clone()),
|
Box::new(sink.clone()),
|
||||||
canary_token(),
|
canary_token(),
|
||||||
Box::new(FixedSecret(secret)),
|
Box::new(FixedSecret(secret)),
|
||||||
);
|
));
|
||||||
|
let router = RouterBackend::from_backends(
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
Some(backend.clone()),
|
||||||
|
vec![default_row(MODEL), default_row(OTHER_MODEL)],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
Rig {
|
Rig {
|
||||||
dir,
|
dir,
|
||||||
backend,
|
backend,
|
||||||
|
router,
|
||||||
spawns,
|
spawns,
|
||||||
seen,
|
seen,
|
||||||
sink,
|
sink,
|
||||||
|
|
@ -438,7 +469,7 @@ impl Rig {
|
||||||
fn run_as(&self, caller: &str, request: ProviderRequest) -> TransportResult {
|
fn run_as(&self, caller: &str, request: ProviderRequest) -> TransportResult {
|
||||||
let mut door = Door::new();
|
let mut door = Door::new();
|
||||||
let (claim, _) = door.begin_as(caller, request);
|
let (claim, _) = door.begin_as(caller, request);
|
||||||
self.backend.execute(claim.call())
|
self.router.execute(claim.call())
|
||||||
}
|
}
|
||||||
fn seen(&self) -> Seen {
|
fn seen(&self) -> Seen {
|
||||||
self.seen.lock().unwrap().clone()
|
self.seen.lock().unwrap().clone()
|
||||||
|
|
@ -480,8 +511,13 @@ impl Door {
|
||||||
)
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
});
|
});
|
||||||
|
let routes = ProviderRoutes::new([
|
||||||
|
(MODEL.to_string(), PROVIDER.to_string()),
|
||||||
|
(OTHER_MODEL.to_string(), PROVIDER.to_string()),
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
let service =
|
let service =
|
||||||
TransportService::open(&dir.join("replay.cc"), PROVIDER, callers, 5_000).unwrap();
|
TransportService::open(&dir.join("replay.cc"), routes, callers, 5_000).unwrap();
|
||||||
Self { dir, service }
|
Self { dir, service }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -500,11 +536,7 @@ impl Door {
|
||||||
let key = TransportKey::from_connection_secret(&format!("{caller}-key")).unwrap();
|
let key = TransportKey::from_connection_secret(&format!("{caller}-key")).unwrap();
|
||||||
let invocation = TransportInvocation::new(caller, 2_000, [7; 32], request).unwrap();
|
let invocation = TransportInvocation::new(caller, 2_000, [7; 32], request).unwrap();
|
||||||
let envelope = encrypt_invocation(&invocation, &key).unwrap();
|
let envelope = encrypt_invocation(&invocation, &key).unwrap();
|
||||||
match self
|
match self.service.begin(&envelope, 1_000, None, FRAME).unwrap() {
|
||||||
.service
|
|
||||||
.begin(&envelope, 1_000, &PlanQuotaSnapshot::default(), FRAME)
|
|
||||||
.unwrap()
|
|
||||||
{
|
|
||||||
TransportAdmission::Execute(claim) => (*claim, invocation),
|
TransportAdmission::Execute(claim) => (*claim, invocation),
|
||||||
TransportAdmission::Reply(_) => panic!("the door answered instead of admitting"),
|
TransportAdmission::Reply(_) => panic!("the door answered instead of admitting"),
|
||||||
}
|
}
|
||||||
|
|
@ -620,6 +652,169 @@ fn reasoning_effort_is_passed_as_its_level() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cli_parameterized_id_efforts_output_schema_and_meter_model() {
|
||||||
|
let spawns = Arc::new(AtomicUsize::new(0));
|
||||||
|
let seen = Arc::new(Mutex::new(Seen::default()));
|
||||||
|
let dir = sandbox();
|
||||||
|
let mut cfg = config(dir.path(), INSTANCE, limits());
|
||||||
|
cfg.provider_id = "custom-cli-id".to_string();
|
||||||
|
cfg.meter_model = Some("custom-meter-wire".to_string());
|
||||||
|
|
||||||
|
let mut row = ModelRow {
|
||||||
|
id: MODEL.to_string(),
|
||||||
|
provider: "custom-cli-id".to_string(),
|
||||||
|
upstream: "wire-cli-model".to_string(),
|
||||||
|
efforts: EffortMap {
|
||||||
|
low: Some("lo-wire".to_string()),
|
||||||
|
medium: None,
|
||||||
|
high: Some("hi-wire".to_string()),
|
||||||
|
max: None,
|
||||||
|
},
|
||||||
|
unset_effort: Some("unset-wire".to_string()),
|
||||||
|
forced_tool_choice: ForcedToolChoice::Never,
|
||||||
|
output_schema: OutputSchemaSupport::None,
|
||||||
|
strict_tools: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
let backend = ClaudeCodeBackend::with_ports(
|
||||||
|
cfg.clone(),
|
||||||
|
Box::new(ScriptedPort {
|
||||||
|
scripts: Mutex::new(
|
||||||
|
vec![
|
||||||
|
Script::lines(vec![
|
||||||
|
init_line("wire-cli-model", SESSION),
|
||||||
|
text_line("m1", "hi"),
|
||||||
|
result_line("end_turn", USAGE),
|
||||||
|
]),
|
||||||
|
Script::lines(vec![
|
||||||
|
init_line("wire-cli-model", FORK),
|
||||||
|
text_line("m2", "hi2"),
|
||||||
|
result_line("end_turn", USAGE),
|
||||||
|
]),
|
||||||
|
Script::lines(vec![
|
||||||
|
init_line("wire-cli-model", FORK),
|
||||||
|
text_line("m2b", "hi2b"),
|
||||||
|
result_line("end_turn", USAGE),
|
||||||
|
]),
|
||||||
|
Script::lines(vec![
|
||||||
|
init_line("custom-meter-wire", SESSION),
|
||||||
|
text_line("m3", "ok"),
|
||||||
|
result_line("end_turn", USAGE),
|
||||||
|
]),
|
||||||
|
]
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
spawns: spawns.clone(),
|
||||||
|
seen: seen.clone(),
|
||||||
|
stderr: Vec::new(),
|
||||||
|
}),
|
||||||
|
Box::new(Sessions(vec![SESSION.to_string()])),
|
||||||
|
Box::new(Sink::default()),
|
||||||
|
canary_token(),
|
||||||
|
Box::new(FixedSecret(Some(SECRET))),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(backend.plan_quota().0, "custom-cli-id");
|
||||||
|
|
||||||
|
// 1. Unmapped ReasoningEffort refuses before spawn.
|
||||||
|
let mut unmapped = request(vec![user("hello")]);
|
||||||
|
unmapped.reasoning_effort = Some(ReasoningEffort::Medium);
|
||||||
|
let (_, outcome_unmapped) = backend.run_model(&unmapped, CALLER_1, &row);
|
||||||
|
assert!(matches!(
|
||||||
|
outcome_unmapped,
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::InvalidRequest,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 0);
|
||||||
|
|
||||||
|
// 2. OutputSchemaSupport::None refuses output_schema_json before spawn.
|
||||||
|
let mut with_schema = request(vec![user("hello")]);
|
||||||
|
with_schema.output_schema_json = Some(SCHEMA.to_string());
|
||||||
|
let (_, outcome_schema) = backend.run_model(&with_schema, CALLER_1, &row);
|
||||||
|
assert!(matches!(
|
||||||
|
outcome_schema,
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::InvalidRequest,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 0);
|
||||||
|
|
||||||
|
// 3. Mapped effort passes custom wire string; unset_effort applies when request effort is None.
|
||||||
|
let mut wire_req = request(vec![user("hello")]);
|
||||||
|
wire_req.model = row.upstream.clone();
|
||||||
|
wire_req.reasoning_effort = Some(ReasoningEffort::Low);
|
||||||
|
let (_, outcome_low) = backend.run_model(&wire_req, CALLER_1, &row);
|
||||||
|
assert!(matches!(outcome_low, TransportOutcome::Completed { .. }));
|
||||||
|
assert_eq!(
|
||||||
|
arg_after(&seen.lock().unwrap().argv, "--effort"),
|
||||||
|
Some("lo-wire")
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut unset_req = request(vec![user("hello")]);
|
||||||
|
unset_req.model = row.upstream.clone();
|
||||||
|
unset_req.reasoning_effort = None;
|
||||||
|
let (_, outcome_unset) = backend.run_model(&unset_req, CALLER_1, &row);
|
||||||
|
assert!(matches!(outcome_unset, TransportOutcome::Completed { .. }));
|
||||||
|
assert_eq!(
|
||||||
|
arg_after(&seen.lock().unwrap().argv, "--effort"),
|
||||||
|
Some("unset-wire")
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. ForcedToolChoice::Never refuses ToolChoice::Required before spawn; Always allows it.
|
||||||
|
let mut forced_req = request(vec![user("hello")]);
|
||||||
|
forced_req.model = row.upstream.clone();
|
||||||
|
forced_req.tool_choice = model_connector::ToolChoice::Required;
|
||||||
|
let (_, outcome_forced_never) = backend.run_model(&forced_req, CALLER_1, &row);
|
||||||
|
assert!(matches!(
|
||||||
|
outcome_forced_never,
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::InvalidRequest,
|
||||||
|
ref message,
|
||||||
|
..
|
||||||
|
} if message.contains("required tool choice")
|
||||||
|
));
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 2);
|
||||||
|
|
||||||
|
row.forced_tool_choice = ForcedToolChoice::Always;
|
||||||
|
let (_, outcome_forced_always) = backend.run_model(&forced_req, CALLER_1, &row);
|
||||||
|
assert!(matches!(
|
||||||
|
outcome_forced_always,
|
||||||
|
TransportOutcome::Completed { .. }
|
||||||
|
));
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 3);
|
||||||
|
|
||||||
|
// 5. read_meter uses config.meter_model.
|
||||||
|
let meter_ok = backend.read_meter();
|
||||||
|
assert!(meter_ok.is_ok(), "{meter_ok:?}");
|
||||||
|
assert_eq!(
|
||||||
|
arg_after(&seen.lock().unwrap().argv, "--model"),
|
||||||
|
Some("custom-meter-wire")
|
||||||
|
);
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 4);
|
||||||
|
|
||||||
|
// 6. read_meter returns Err("MissingMeterModel") when meter_model is None, without spawning.
|
||||||
|
cfg.meter_model = None;
|
||||||
|
let no_meter = ClaudeCodeBackend::with_ports(
|
||||||
|
cfg,
|
||||||
|
Box::new(ScriptedPort {
|
||||||
|
scripts: Mutex::new(VecDeque::new()),
|
||||||
|
spawns: spawns.clone(),
|
||||||
|
seen: seen.clone(),
|
||||||
|
stderr: Vec::new(),
|
||||||
|
}),
|
||||||
|
Box::new(Sessions(vec![])),
|
||||||
|
Box::new(Sink::default()),
|
||||||
|
canary_token(),
|
||||||
|
Box::new(FixedSecret(Some(SECRET))),
|
||||||
|
);
|
||||||
|
assert_eq!(no_meter.read_meter().unwrap_err(), "MissingMeterModel");
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 4);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resume_always_forks() {
|
fn resume_always_forks() {
|
||||||
let rig = rig(vec![ok_script(SESSION, "hi"), ok_script(FORK, "again")]);
|
let rig = rig(vec![ok_script(SESSION, "hi"), ok_script(FORK, "again")]);
|
||||||
|
|
@ -674,6 +869,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.
|
||||||
|
|
@ -1005,7 +1209,7 @@ fn token_comes_from_the_credential_file_not_the_environment() {
|
||||||
let mut config = config(dir.path(), INSTANCE, limits());
|
let mut config = config(dir.path(), INSTANCE, limits());
|
||||||
config.work_dir = dir.path().join("work");
|
config.work_dir = dir.path().join("work");
|
||||||
config.config_dir = dir.path().join("cfg");
|
config.config_dir = dir.path().join("cfg");
|
||||||
let backend = ClaudeCodeBackend::with_ports(
|
let backend = Arc::new(ClaudeCodeBackend::with_ports(
|
||||||
config,
|
config,
|
||||||
Box::new(ScriptedPort {
|
Box::new(ScriptedPort {
|
||||||
scripts: Mutex::new(vec![ok_script(SESSION, "x")].into()),
|
scripts: Mutex::new(vec![ok_script(SESSION, "x")].into()),
|
||||||
|
|
@ -1020,13 +1224,16 @@ fn token_comes_from_the_credential_file_not_the_environment() {
|
||||||
"claude-token",
|
"claude-token",
|
||||||
)),
|
)),
|
||||||
canary_secret(),
|
canary_secret(),
|
||||||
);
|
));
|
||||||
|
let router =
|
||||||
|
RouterBackend::from_backends([], [], Some(backend.clone()), vec![default_row(MODEL)])
|
||||||
|
.unwrap();
|
||||||
let mut door = Door::new();
|
let mut door = Door::new();
|
||||||
|
|
||||||
// The variable is set and the file is absent: nothing to give the child.
|
// The variable is set and the file is absent: nothing to give the child.
|
||||||
assert_eq!(backend.ready(), Err("token_credential"));
|
assert_eq!(backend.ready(), Err("token_credential"));
|
||||||
let (claim, _) = door.begin(request(vec![user("hi")]));
|
let (claim, _) = door.begin(request(vec![user("hi")]));
|
||||||
let (kind, message, usage) = failure_of(&backend.execute(claim.call()));
|
let (kind, message, usage) = failure_of(&router.execute(claim.call()));
|
||||||
assert_eq!(kind, FailureKind::Authentication);
|
assert_eq!(kind, FailureKind::Authentication);
|
||||||
assert_eq!(usage, Some(usage_zero()));
|
assert_eq!(usage, Some(usage_zero()));
|
||||||
assert!(!message.contains("canary-environment-token"));
|
assert!(!message.contains("canary-environment-token"));
|
||||||
|
|
@ -1042,7 +1249,7 @@ fn token_comes_from_the_credential_file_not_the_environment() {
|
||||||
assert_eq!(backend.ready(), Ok(()));
|
assert_eq!(backend.ready(), Ok(()));
|
||||||
let mut door = Door::new();
|
let mut door = Door::new();
|
||||||
let (claim, _) = door.begin(request(vec![user("hi")]));
|
let (claim, _) = door.begin(request(vec![user("hi")]));
|
||||||
let result = backend.execute(claim.call());
|
let result = router.execute(claim.call());
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
outcome(&result),
|
outcome(&result),
|
||||||
TransportOutcome::Completed { .. }
|
TransportOutcome::Completed { .. }
|
||||||
|
|
@ -1640,12 +1847,31 @@ fn one_spawn_per_execute() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_missing_token_fails_before_spawn() {
|
fn a_missing_token_fails_before_spawn() {
|
||||||
let mut rig = rig(vec![ok_script(SESSION, "x")]);
|
let spawns = Arc::new(AtomicUsize::new(0));
|
||||||
rig.backend.tokens = Box::new(FixedToken(None));
|
let dir = sandbox();
|
||||||
let (kind, _, usage) = failure_of(&rig.run(request(vec![user("hi")])));
|
let backend = ClaudeCodeBackend::with_ports(
|
||||||
assert_eq!(kind, FailureKind::Authentication);
|
config(dir.path(), INSTANCE, limits()),
|
||||||
assert_eq!(usage, Some(usage_zero()));
|
Box::new(ScriptedPort {
|
||||||
assert_eq!(rig.spawns(), 0);
|
scripts: Mutex::new(vec![ok_script(SESSION, "x")].into()),
|
||||||
|
spawns: spawns.clone(),
|
||||||
|
seen: Arc::new(Mutex::new(Seen::default())),
|
||||||
|
stderr: Vec::new(),
|
||||||
|
}),
|
||||||
|
Box::new(Sessions(vec![SESSION.to_string()])),
|
||||||
|
Box::new(Sink::default()),
|
||||||
|
Box::new(FixedToken(None)),
|
||||||
|
canary_secret(),
|
||||||
|
);
|
||||||
|
let (_, outcome) = backend.run_model(&request(vec![user("hi")]), CALLER_1, &default_row(MODEL));
|
||||||
|
assert!(matches!(
|
||||||
|
&outcome,
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::Authentication,
|
||||||
|
usage: Some(u),
|
||||||
|
..
|
||||||
|
} if *u == usage_zero()
|
||||||
|
));
|
||||||
|
assert_eq!(spawns.load(Ordering::SeqCst), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -1664,17 +1890,19 @@ fn a_port_that_cannot_spawn_is_a_provider_failure() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let dir = sandbox();
|
let dir = sandbox();
|
||||||
let backend = ClaudeCodeBackend::with_ports(
|
let backend = Arc::new(ClaudeCodeBackend::with_ports(
|
||||||
config(dir.path(), INSTANCE, limits()),
|
config(dir.path(), INSTANCE, limits()),
|
||||||
Box::new(Refusing),
|
Box::new(Refusing),
|
||||||
Box::new(Sessions(vec![])),
|
Box::new(Sessions(vec![])),
|
||||||
Box::new(Sink::default()),
|
Box::new(Sink::default()),
|
||||||
canary_token(),
|
canary_token(),
|
||||||
canary_secret(),
|
canary_secret(),
|
||||||
);
|
));
|
||||||
|
let router =
|
||||||
|
RouterBackend::from_backends([], [], Some(backend), vec![default_row(MODEL)]).unwrap();
|
||||||
let mut door = Door::new();
|
let mut door = Door::new();
|
||||||
let (claim, _) = door.begin(request(vec![user("hi")]));
|
let (claim, _) = door.begin(request(vec![user("hi")]));
|
||||||
let result = backend.execute(claim.call());
|
let result = router.execute(claim.call());
|
||||||
let (kind, message, usage) = failure_of(&result);
|
let (kind, message, usage) = failure_of(&result);
|
||||||
assert_eq!(kind, FailureKind::Provider);
|
assert_eq!(kind, FailureKind::Provider);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|
@ -1693,7 +1921,7 @@ fn backend_end_to_end_through_the_service() {
|
||||||
let rig = rig(vec![ok_script(SESSION, "hello back")]);
|
let rig = rig(vec![ok_script(SESSION, "hello back")]);
|
||||||
let mut door = Door::new();
|
let mut door = Door::new();
|
||||||
let (claim, invocation) = door.begin(request(vec![user("hello")]));
|
let (claim, invocation) = door.begin(request(vec![user("hello")]));
|
||||||
let result = rig.backend.execute(claim.call());
|
let result = rig.router.execute(claim.call());
|
||||||
let sealed = door.service.complete(claim, result, FRAME).unwrap();
|
let sealed = door.service.complete(claim, result, FRAME).unwrap();
|
||||||
let opened = decrypt_result(
|
let opened = decrypt_result(
|
||||||
&sealed,
|
&sealed,
|
||||||
|
|
@ -1952,11 +2180,6 @@ fn pin_is_checked_before_every_spawn() {
|
||||||
assert_eq!(rig.spawns(), 2);
|
assert_eq!(rig.spawns(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_provider_tag_is_claude_code() {
|
|
||||||
assert_eq!(rig(vec![]).backend.provider(), "claude-code");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- the session store ----
|
// ---- the session store ----
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -2108,12 +2331,23 @@ fn only_the_structured_output_tool_is_allowed_and_only_when_a_schema_was_sent()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn quota_of(rig: &Rig) -> model_connector::PlanQuotaSnapshot {
|
fn quota_of(rig: &Rig) -> model_connector::PlanQuotaSnapshot {
|
||||||
rig.backend.plan_quota()
|
let (provider, snapshot) = rig.backend.plan_quota();
|
||||||
|
assert_eq!(provider, PROVIDER);
|
||||||
|
snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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;
|
||||||
}
|
}
|
||||||
|
|
@ -2214,7 +2448,7 @@ mod real {
|
||||||
struct Fake {
|
struct Fake {
|
||||||
_guard: std::sync::MutexGuard<'static, ()>,
|
_guard: std::sync::MutexGuard<'static, ()>,
|
||||||
dir: TempDir,
|
dir: TempDir,
|
||||||
backend: ClaudeCodeBackend,
|
router: RouterBackend,
|
||||||
sink: Sink,
|
sink: Sink,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2235,18 +2469,20 @@ mod real {
|
||||||
config.work_dir = work;
|
config.work_dir = work;
|
||||||
config.config_dir = cfg;
|
config.config_dir = cfg;
|
||||||
let sink = Sink::default();
|
let sink = Sink::default();
|
||||||
let backend = ClaudeCodeBackend::with_ports(
|
let backend = Arc::new(ClaudeCodeBackend::with_ports(
|
||||||
config.clone(),
|
config.clone(),
|
||||||
Box::new(crate::process::StdProcessPort::new(config.limits)),
|
Box::new(crate::process::StdProcessPort::new(config.limits)),
|
||||||
Box::new(FsSessionStore::new(config.config_dir.clone())),
|
Box::new(FsSessionStore::new(config.config_dir.clone())),
|
||||||
Box::new(sink.clone()),
|
Box::new(sink.clone()),
|
||||||
canary_token(),
|
canary_token(),
|
||||||
canary_secret(),
|
canary_secret(),
|
||||||
);
|
));
|
||||||
|
let router =
|
||||||
|
RouterBackend::from_backends([], [], Some(backend), vec![default_row(MODEL)]).unwrap();
|
||||||
Fake {
|
Fake {
|
||||||
_guard: guard,
|
_guard: guard,
|
||||||
dir,
|
dir,
|
||||||
backend,
|
router,
|
||||||
sink,
|
sink,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -2255,7 +2491,7 @@ mod real {
|
||||||
fn run(&self, request: ProviderRequest) -> TransportResult {
|
fn run(&self, request: ProviderRequest) -> TransportResult {
|
||||||
let mut door = Door::new();
|
let mut door = Door::new();
|
||||||
let (claim, _) = door.begin(request);
|
let (claim, _) = door.begin(request);
|
||||||
self.backend.execute(claim.call())
|
self.router.execute(claim.call())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2764,14 +3000,15 @@ fn the_meter_call_reads_the_week_from_a_real_captured_event() {
|
||||||
.read_meter()
|
.read_meter()
|
||||||
.expect("the captured call completes");
|
.expect("the captured call completes");
|
||||||
assert_eq!((usage.input_tokens, usage.output_tokens), (384, 4));
|
assert_eq!((usage.input_tokens, usage.output_tokens), (384, 4));
|
||||||
// 0.06 of the week used; it resets at 1794261600 (unix s).
|
// 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!(
|
assert_eq!(
|
||||||
readings(&rig),
|
readings_at(&rig, Some(1_794_261_600_000 - 1)),
|
||||||
vec![window("seven_day", 60, 1_794_261_600_000)]
|
vec![window("seven_day", 60, 1_794_261_600_000)]
|
||||||
);
|
);
|
||||||
let argv = rig.seen().argv;
|
let argv = rig.seen().argv;
|
||||||
let after = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
|
let after = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
|
||||||
assert_eq!(after("--model"), METER_MODEL);
|
assert_eq!(after("--model"), MODEL);
|
||||||
assert_eq!(after("--tools"), "", "the call can use no tool");
|
assert_eq!(after("--tools"), "", "the call can use no tool");
|
||||||
assert!(
|
assert!(
|
||||||
argv.iter().any(|a| a == "--no-session-persistence"),
|
argv.iter().any(|a| a == "--no-session-persistence"),
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,135 @@
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
/// The provider tag the kit puts on every receipt and on the reasoning state
|
use model_connector::ReasoningEffort;
|
||||||
/// of this backend. It is distinct from any Messages-API backend's tag, so the
|
use serde::{Deserialize, Serialize};
|
||||||
/// kit treats each backend's state as foreign to the other.
|
|
||||||
pub(crate) const PROVIDER: &str = "claude-code";
|
/// One configured provider entry in the connector's v3 config document.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ProviderEntry {
|
||||||
|
/// Provider tag written on receipts and reasoning state items.
|
||||||
|
pub id: String,
|
||||||
|
/// Systemd credential name under `$CREDENTIALS_DIRECTORY`; `None` only for
|
||||||
|
/// a loopback HTTP `base_url`.
|
||||||
|
pub credential: Option<String>,
|
||||||
|
pub wire: ProviderWire,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wire protocol and per-provider backend parameters for a [`ProviderEntry`].
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum ProviderWire {
|
||||||
|
AnthropicMessages {
|
||||||
|
base_url: String,
|
||||||
|
deadline_ms: u64,
|
||||||
|
max_response_bytes: usize,
|
||||||
|
},
|
||||||
|
OpenAiChat {
|
||||||
|
base_url: String,
|
||||||
|
strict_unsupported: Vec<String>,
|
||||||
|
deadline_ms: u64,
|
||||||
|
max_response_bytes: usize,
|
||||||
|
},
|
||||||
|
ClaudeCodeCli {
|
||||||
|
binary: PathBuf,
|
||||||
|
binary_sha256: [u8; 32],
|
||||||
|
work_dir: PathBuf,
|
||||||
|
config_dir: PathBuf,
|
||||||
|
prompt_dir: PathBuf,
|
||||||
|
handle_secret_credential: String,
|
||||||
|
instance: String,
|
||||||
|
deadline_ms: u64,
|
||||||
|
max_line_bytes: usize,
|
||||||
|
max_total_bytes: usize,
|
||||||
|
stderr_tail_bytes: usize,
|
||||||
|
meter_model: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One caller-facing model routed to a [`ProviderEntry`].
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ModelRow {
|
||||||
|
/// Caller-facing model id named in `ProviderRequest.model` and `allowed_models`.
|
||||||
|
pub id: String,
|
||||||
|
/// Id of the [`ProviderEntry`] that serves this model.
|
||||||
|
pub provider: String,
|
||||||
|
/// Provider-side model name sent on the wire.
|
||||||
|
pub upstream: String,
|
||||||
|
pub efforts: EffortMap,
|
||||||
|
pub unset_effort: Option<String>,
|
||||||
|
pub forced_tool_choice: ForcedToolChoice,
|
||||||
|
pub output_schema: OutputSchemaSupport,
|
||||||
|
pub strict_tools: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModelRow {
|
||||||
|
pub(crate) fn resolve_effort(
|
||||||
|
&self,
|
||||||
|
requested: Option<ReasoningEffort>,
|
||||||
|
) -> Result<Option<&str>, String> {
|
||||||
|
match requested {
|
||||||
|
Some(effort) => self.efforts.get(effort).map(Some).ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"model {} does not support reasoning effort {effort:?}",
|
||||||
|
self.id
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
None => Ok(self.unset_effort.as_deref()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn thinking_active(effort: Option<&str>) -> bool {
|
||||||
|
effort.is_some_and(|level| level != "none")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn allows_forced_tool_choice(&self, thinking_active: bool) -> bool {
|
||||||
|
match self.forced_tool_choice {
|
||||||
|
ForcedToolChoice::Always => true,
|
||||||
|
ForcedToolChoice::WithoutThinking => !thinking_active,
|
||||||
|
ForcedToolChoice::Never => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps each contract [`ReasoningEffort`] to the provider's wire value.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct EffortMap {
|
||||||
|
pub low: Option<String>,
|
||||||
|
pub medium: Option<String>,
|
||||||
|
pub high: Option<String>,
|
||||||
|
pub max: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EffortMap {
|
||||||
|
pub fn get(&self, effort: ReasoningEffort) -> Option<&str> {
|
||||||
|
match effort {
|
||||||
|
ReasoningEffort::Low => self.low.as_deref(),
|
||||||
|
ReasoningEffort::Medium => self.medium.as_deref(),
|
||||||
|
ReasoningEffort::High => self.high.as_deref(),
|
||||||
|
ReasoningEffort::Max => self.max.as_deref(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the model accepts `ToolChoice::Required` (`tool_choice: any` / `required`).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum ForcedToolChoice {
|
||||||
|
Always,
|
||||||
|
WithoutThinking,
|
||||||
|
Never,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the model natively enforces a request's output JSON schema.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum OutputSchemaSupport {
|
||||||
|
Native,
|
||||||
|
None,
|
||||||
|
}
|
||||||
|
|
||||||
/// 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 {
|
||||||
|
/// Provider tag written on receipts and reasoning state items.
|
||||||
|
pub provider_id: String,
|
||||||
/// The `claude` executable.
|
/// The `claude` executable.
|
||||||
pub claude_binary: PathBuf,
|
pub claude_binary: PathBuf,
|
||||||
/// The SHA-256 the executable must have for [`ready`](model_connector::ProviderBackend::ready).
|
/// The SHA-256 the executable must have for [`ready`](model_connector::ProviderBackend::ready).
|
||||||
|
|
@ -22,7 +143,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
|
||||||
|
|
@ -30,6 +151,8 @@ pub struct ClaudeCodeConfig {
|
||||||
pub handle_secret_credential: String,
|
pub handle_secret_credential: String,
|
||||||
/// The connector instance id written into every handle.
|
/// The connector instance id written into every handle.
|
||||||
pub instance: String,
|
pub instance: String,
|
||||||
|
/// Upstream model name used for the subscription plan meter's minimal call.
|
||||||
|
pub meter_model: Option<String>,
|
||||||
pub limits: ClaudeCodeLimits,
|
pub limits: ClaudeCodeLimits,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
88
crates/claude-connector/src/credential.rs
Normal file
88
crates/claude-connector/src/credential.rs
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// Where a backend's or lease lender's credential comes from, read afresh at
|
||||||
|
/// every use. The connector's own environment is never a source (ruling
|
||||||
|
/// claude-connector-token-credential).
|
||||||
|
pub trait TokenSource: Send + Sync {
|
||||||
|
/// The token, or `None` when there is none or it is empty.
|
||||||
|
fn read(&self) -> Option<Zeroizing<String>>;
|
||||||
|
/// What `config check` names when `read` has no token.
|
||||||
|
fn missing(&self) -> &'static str {
|
||||||
|
"token_credential"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A token in a file named by a systemd credential: the file
|
||||||
|
/// `$CREDENTIALS_DIRECTORY/<name>`, read on every call so a rotated credential
|
||||||
|
/// is picked up by the next use.
|
||||||
|
pub struct CredentialTokenSource {
|
||||||
|
directory: Option<PathBuf>,
|
||||||
|
name: String,
|
||||||
|
/// The configuration field `missing` names when the credential is absent.
|
||||||
|
field: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CredentialTokenSource {
|
||||||
|
/// The credential `name` under the directory systemd names in
|
||||||
|
/// `CREDENTIALS_DIRECTORY`; with no such variable the source has no token.
|
||||||
|
/// The variable names a directory, never a token.
|
||||||
|
pub fn from_environment(name: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
directory: std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from),
|
||||||
|
name: name.into(),
|
||||||
|
field: "token_credential",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same source, naming `field` when its credential is absent.
|
||||||
|
pub fn for_field(mut self, field: &'static str) -> Self {
|
||||||
|
self.field = field;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn in_directory(directory: impl Into<PathBuf>, name: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
directory: Some(directory.into()),
|
||||||
|
name: name.into(),
|
||||||
|
field: "token_credential",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn in_optional_directory(directory: Option<&Path>, name: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
directory: directory.map(Path::to_path_buf),
|
||||||
|
name: name.into(),
|
||||||
|
field: "token_credential",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TokenSource for CredentialTokenSource {
|
||||||
|
fn read(&self) -> Option<Zeroizing<String>> {
|
||||||
|
let directory = self.directory.as_ref()?;
|
||||||
|
let mut token = Zeroizing::new(std::fs::read_to_string(directory.join(&self.name)).ok()?);
|
||||||
|
let trimmed = token.trim_end_matches(['\r', '\n']).len();
|
||||||
|
token.truncate(trimmed);
|
||||||
|
(!token.is_empty()).then_some(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// No directory at all is the unit's environment lacking its credentials,
|
||||||
|
/// which is not the same fault as a credential the directory lacks.
|
||||||
|
fn missing(&self) -> &'static str {
|
||||||
|
if self.directory.is_none() {
|
||||||
|
"credentials_directory"
|
||||||
|
} else {
|
||||||
|
self.field
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks whether `source` yields a non-empty credential without leaking it.
|
||||||
|
pub(crate) fn credential_ready(source: &dyn TokenSource) -> Result<(), &'static str> {
|
||||||
|
match source.read() {
|
||||||
|
Some(_) => Ok(()),
|
||||||
|
None => Err(source.missing()),
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -10,7 +10,7 @@ use model_connector::{InputItem, ProviderRequest};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
|
|
||||||
use crate::config::{ClaudeCodeConfig, PROVIDER};
|
use crate::config::ClaudeCodeConfig;
|
||||||
|
|
||||||
/// The state this backend hands a caller inside `ReasoningState`. A new
|
/// The state this backend hands a caller inside `ReasoningState`. A new
|
||||||
/// variant is a new version.
|
/// variant is a new version.
|
||||||
|
|
@ -190,9 +190,9 @@ pub(crate) fn plan(
|
||||||
return Err(PlanError::NoUserText);
|
return Err(PlanError::NoUserText);
|
||||||
}
|
}
|
||||||
|
|
||||||
let last_own = input.iter().rposition(
|
let last_own = input.iter().rposition(|item| {
|
||||||
|item| matches!(item, InputItem::ReasoningState { provider, .. } if provider == PROVIDER),
|
matches!(item, InputItem::ReasoningState { provider, .. } if provider == &config.provider_id)
|
||||||
);
|
});
|
||||||
if let Some(at) = last_own {
|
if let Some(at) = last_own {
|
||||||
let InputItem::ReasoningState { state, .. } = &input[at] else {
|
let InputItem::ReasoningState { state, .. } = &input[at] else {
|
||||||
unreachable!("rposition matched a reasoning state");
|
unreachable!("rposition matched a reasoning state");
|
||||||
|
|
|
||||||
233
crates/claude-connector/src/http.rs
Normal file
233
crates/claude-connector/src/http.rs
Normal file
|
|
@ -0,0 +1,233 @@
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use model_connector::{FailureKind, TransportEvent, TransportOutcome, Usage};
|
||||||
|
use serde_json::Value;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
use crate::credential::TokenSource;
|
||||||
|
|
||||||
|
/// The longest provider message a receipt carries.
|
||||||
|
pub(crate) const MESSAGE_BYTES: usize = 2048;
|
||||||
|
|
||||||
|
/// Builds the HTTP client used by every HTTP backend: global deadline, status
|
||||||
|
/// errors returned as responses, no redirects (so credentials cannot leak to a
|
||||||
|
/// redirect target), and no environment proxy lookup.
|
||||||
|
pub(crate) fn build_agent(deadline: Duration) -> ureq::Agent {
|
||||||
|
ureq::Agent::config_builder()
|
||||||
|
.timeout_global(Some(deadline))
|
||||||
|
.http_status_as_error(false)
|
||||||
|
.max_redirects(0)
|
||||||
|
.proxy(None)
|
||||||
|
.build()
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn read_key(
|
||||||
|
keys: Option<&dyn TokenSource>,
|
||||||
|
label: &str,
|
||||||
|
) -> Result<Option<Zeroizing<String>>, (Vec<TransportEvent>, TransportOutcome)> {
|
||||||
|
match keys {
|
||||||
|
Some(source) => match source.read() {
|
||||||
|
Some(key) => Ok(Some(key)),
|
||||||
|
None => Err(failed(
|
||||||
|
FailureKind::Authentication,
|
||||||
|
format!("{label}: the connector has no API key"),
|
||||||
|
Some(zero_usage()),
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
pub(crate) 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failure the provider answered: its own type/code and message, bounded and
|
||||||
|
/// scrubbed of any credential bytes.
|
||||||
|
pub(crate) fn http_failure(
|
||||||
|
label: &str,
|
||||||
|
status: u16,
|
||||||
|
body: &[u8],
|
||||||
|
secret: Option<&str>,
|
||||||
|
spend_exhausted: impl FnOnce(u16, &Value) -> bool,
|
||||||
|
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
let parsed: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
|
||||||
|
let error = if parsed["error"].is_object() {
|
||||||
|
&parsed["error"]
|
||||||
|
} else {
|
||||||
|
&parsed
|
||||||
|
};
|
||||||
|
let mut message = format!("{label}: HTTP {status}");
|
||||||
|
if let Some(kind) = error["type"].as_str().or_else(|| error["code"].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);
|
||||||
|
}
|
||||||
|
if let Some(secret) = secret.filter(|s| !s.is_empty()) {
|
||||||
|
message = message.replace(secret, "[redacted]");
|
||||||
|
}
|
||||||
|
let kind = if spend_exhausted(status, 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.
|
||||||
|
pub(crate) fn transport_failure(
|
||||||
|
label: &str,
|
||||||
|
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!("{label}: {what}"), None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn zero_usage() -> Usage {
|
||||||
|
Usage {
|
||||||
|
input_tokens: 0,
|
||||||
|
cache_read_tokens: 0,
|
||||||
|
cache_write_tokens: 0,
|
||||||
|
output_tokens: 0,
|
||||||
|
reasoning_tokens: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn failed(
|
||||||
|
kind: FailureKind,
|
||||||
|
message: String,
|
||||||
|
usage: Option<Usage>,
|
||||||
|
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
(
|
||||||
|
Vec::new(),
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind,
|
||||||
|
message,
|
||||||
|
usage,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) static PROXY_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use super::{PROXY_ENV_LOCK, build_agent};
|
||||||
|
|
||||||
|
struct EnvRestore {
|
||||||
|
http: Option<std::ffi::OsString>,
|
||||||
|
https: Option<std::ffi::OsString>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for EnvRestore {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// SAFETY: guarded by PROXY_ENV_LOCK across tests touching proxy env vars.
|
||||||
|
unsafe {
|
||||||
|
match &self.http {
|
||||||
|
Some(v) => std::env::set_var("HTTP_PROXY", v),
|
||||||
|
None => std::env::remove_var("HTTP_PROXY"),
|
||||||
|
}
|
||||||
|
match &self.https {
|
||||||
|
Some(v) => std::env::set_var("HTTPS_PROXY", v),
|
||||||
|
None => std::env::remove_var("HTTPS_PROXY"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn build_agent_ignores_http_and_https_proxy_env() {
|
||||||
|
let _guard = PROXY_ENV_LOCK
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
let _restore = EnvRestore {
|
||||||
|
http: std::env::var_os("HTTP_PROXY"),
|
||||||
|
https: std::env::var_os("HTTPS_PROXY"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let proxy_listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
proxy_listener.set_nonblocking(true).unwrap();
|
||||||
|
let proxy_url = format!("http://{}", proxy_listener.local_addr().unwrap());
|
||||||
|
|
||||||
|
let target_listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let target_url = format!("http://{}/ok", target_listener.local_addr().unwrap());
|
||||||
|
let target_hits = Arc::new(AtomicUsize::new(0));
|
||||||
|
let hits = target_hits.clone();
|
||||||
|
let handle = thread::spawn(move || {
|
||||||
|
let (mut stream, _) = target_listener.accept().unwrap();
|
||||||
|
hits.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let mut buf = [0u8; 512];
|
||||||
|
let _ = stream.read(&mut buf);
|
||||||
|
let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");
|
||||||
|
});
|
||||||
|
|
||||||
|
// SAFETY: guarded by PROXY_ENV_LOCK.
|
||||||
|
unsafe {
|
||||||
|
std::env::set_var("HTTP_PROXY", &proxy_url);
|
||||||
|
std::env::set_var("HTTPS_PROXY", &proxy_url);
|
||||||
|
}
|
||||||
|
|
||||||
|
let agent = build_agent(Duration::from_secs(5));
|
||||||
|
let mut resp = agent.get(&target_url).call().unwrap();
|
||||||
|
assert_eq!(resp.status().as_u16(), 200);
|
||||||
|
let body = resp.body_mut().read_to_string().unwrap();
|
||||||
|
assert_eq!(body, "ok");
|
||||||
|
|
||||||
|
handle.join().unwrap();
|
||||||
|
assert_eq!(target_hits.load(Ordering::SeqCst), 1);
|
||||||
|
assert!(
|
||||||
|
matches!(proxy_listener.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock),
|
||||||
|
"proxy listener must never be contacted"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -8,18 +8,18 @@ use std::io::{self, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
|
||||||
use model_connector::{ProviderRequest, ReasoningEffort};
|
use model_connector::ProviderRequest;
|
||||||
|
|
||||||
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.
|
||||||
|
pub(crate) 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.
|
||||||
|
|
@ -94,15 +94,6 @@ impl Drop for PromptFile {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn effort(effort: ReasoningEffort) -> &'static str {
|
|
||||||
match effort {
|
|
||||||
ReasoningEffort::Low => "low",
|
|
||||||
ReasoningEffort::Medium => "medium",
|
|
||||||
ReasoningEffort::High => "high",
|
|
||||||
ReasoningEffort::Max => "max",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The program and its arguments. The system prompt is replaced, by a file
|
/// The program and its arguments. The system prompt is replaced, by a file
|
||||||
/// 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
|
||||||
|
|
@ -115,6 +106,7 @@ pub(crate) fn argv(
|
||||||
request: &ProviderRequest,
|
request: &ProviderRequest,
|
||||||
plan: &Plan,
|
plan: &Plan,
|
||||||
system_prompt_file: &Path,
|
system_prompt_file: &Path,
|
||||||
|
effort: Option<&str>,
|
||||||
ephemeral: bool,
|
ephemeral: bool,
|
||||||
) -> Vec<String> {
|
) -> Vec<String> {
|
||||||
let mut argv: Vec<String> = [
|
let mut argv: Vec<String> = [
|
||||||
|
|
@ -144,8 +136,8 @@ pub(crate) fn argv(
|
||||||
if ephemeral {
|
if ephemeral {
|
||||||
argv.push("--no-session-persistence".to_string());
|
argv.push("--no-session-persistence".to_string());
|
||||||
}
|
}
|
||||||
if let Some(level) = request.reasoning_effort {
|
if let Some(level) = effort {
|
||||||
argv.extend(["--effort".to_string(), effort(level).to_string()]);
|
argv.extend(["--effort".to_string(), level.to_string()]);
|
||||||
}
|
}
|
||||||
if let Some(schema) = &request.output_schema_json {
|
if let Some(schema) = &request.output_schema_json {
|
||||||
argv.extend(["--json-schema".to_string(), schema.clone()]);
|
argv.extend(["--json-schema".to_string(), schema.clone()]);
|
||||||
|
|
|
||||||
|
|
@ -1,23 +1,22 @@
|
||||||
//! The Self-run credential lease. The connector is the only holder of the
|
//! The credential lease. The connector is the only holder of the
|
||||||
//! subscription token and the one owner of Self-run admission (rulings
|
//! subscription token and the one owner of lease admission. A holder asks
|
||||||
//! self-runs-through-connector and self-run-credential-lease). A Self run asks
|
|
||||||
//! over a unix socket for a lease. The connector decides who may ask (the
|
//! over a unix socket for a lease. The connector decides who may ask (the
|
||||||
//! peer's uid, and the systemd unit invocation its process runs in), and hands
|
//! peer's uid, and the systemd unit invocation its process runs in), and hands
|
||||||
//! back one pipe fd that holds the token, with the plan's usage windows. The
|
//! back one pipe fd that holds the token, with the plan's usage windows. The
|
||||||
//! lease lasts while the holder keeps the socket open: it ends when the holder
|
//! lease lasts while the holder keeps the socket open: it ends when the holder
|
||||||
//! closes it, when its unit invocation ends, or when its expiry passes. Nothing
|
//! closes it, when its unit invocation ends, or when its expiry passes. Nothing
|
||||||
//! is reserved and nothing is billed; the only usage-derived refusal is the
|
//! is reserved and nothing is billed; the only usage-derived refusal is the
|
||||||
//! provider's own, repeated until its own reset. Nothing the run says about
|
//! provider's own, repeated until its own reset. Nothing the holder 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 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
|
//! (the claude-lease group): no lease, no caller check, no token read and no
|
||||||
//! wake of the meter. Usage is state every Mind reads.
|
//! wake of the meter. Usage is state every peer with socket access 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 holder's `claude`
|
||||||
//! stays in the Self run's own unit.
|
//! stays in the holder's own unit.
|
||||||
|
|
||||||
use std::ffi::CString;
|
use std::ffi::CString;
|
||||||
use std::io::{self, Read, Write};
|
use std::io::{self, Read, Write};
|
||||||
|
|
@ -31,7 +30,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, UsageReadout,
|
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope, PlanQuota, TransportService, UsageReadout,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
@ -173,28 +172,16 @@ fn read_message(stream: &mut impl Bounded, deadline: Instant) -> io::Result<Leas
|
||||||
/// The most a pipe takes in one atomic write.
|
/// The most a pipe takes in one atomic write.
|
||||||
const PIPE_BUF: usize = 4096;
|
const PIPE_BUF: usize = 4096;
|
||||||
|
|
||||||
/// A unix account allowed to lease, the unit its process must run in (the
|
/// A unix account allowed to lease, the configured systemd unit its process
|
||||||
/// Self or the Persona unit of its instance, by `turn`), and the
|
/// must run in, the provider it leases for, its exclusivity scope, and the
|
||||||
/// caller whose name its leases carry.
|
/// configured caller whose name its leases carry.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct LeaseCaller {
|
pub struct LeaseHolder {
|
||||||
pub uid: u32,
|
pub uid: u32,
|
||||||
pub caller_id: String,
|
pub caller_id: String,
|
||||||
/// Which kind of turn this account leases for; it picks the unit.
|
pub provider: String,
|
||||||
pub turn: LeaseTurn,
|
pub unit: String,
|
||||||
/// The `<instance>` of `mind-self@<instance>.service` or
|
pub scope: LeaseScope,
|
||||||
/// `mind-persona@<instance>.service`.
|
|
||||||
pub unit_instance: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LeaseCaller {
|
|
||||||
/// The one unit a lease to this caller may be requested from.
|
|
||||||
pub fn unit(&self) -> String {
|
|
||||||
match self.turn {
|
|
||||||
LeaseTurn::SelfRun => format!("mind-self@{}.service", self.unit_instance),
|
|
||||||
LeaseTurn::PersonaTurn => format!("mind-persona@{}.service", self.unit_instance),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The systemd unit invocation a process runs in.
|
/// The systemd unit invocation a process runs in.
|
||||||
|
|
@ -389,7 +376,7 @@ impl Drop for Permit {
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Lender {
|
struct Lender {
|
||||||
callers: Vec<LeaseCaller>,
|
holders: Vec<LeaseHolder>,
|
||||||
limits: LeaseLimits,
|
limits: LeaseLimits,
|
||||||
service: Arc<Mutex<TransportService>>,
|
service: Arc<Mutex<TransportService>>,
|
||||||
quota: Arc<QuotaCell>,
|
quota: Arc<QuotaCell>,
|
||||||
|
|
@ -410,14 +397,13 @@ const READOUT_CONNECTIONS: usize = 4;
|
||||||
/// one usage readout. A lease: request, then grant or refusal, then (after a
|
/// 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
|
/// 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
|
/// is the socket's group, and it reads the plan's windows without waking the
|
||||||
/// meter. A caller is
|
/// meter. A holder is the account whose uid the kernel reports for the
|
||||||
/// the account whose uid the kernel reports for the connection, and only a
|
/// connection, and only a process in that holder's configured unit may lease,
|
||||||
/// process in that caller's unit may lease, once per unit invocation for a Self
|
/// once per caller for `PerCaller` and once per unit invocation for
|
||||||
/// run and once per turn for a Persona; no
|
/// `PerInvocation`; no field of any message names either.
|
||||||
/// field of any message names either.
|
|
||||||
pub fn serve_leases(
|
pub fn serve_leases(
|
||||||
listener: &UnixListener,
|
listener: &UnixListener,
|
||||||
callers: Vec<LeaseCaller>,
|
holders: Vec<LeaseHolder>,
|
||||||
limits: LeaseLimits,
|
limits: LeaseLimits,
|
||||||
service: Arc<Mutex<TransportService>>,
|
service: Arc<Mutex<TransportService>>,
|
||||||
quota: Arc<QuotaCell>,
|
quota: Arc<QuotaCell>,
|
||||||
|
|
@ -425,7 +411,7 @@ pub fn serve_leases(
|
||||||
units: Arc<dyn PeerUnits>,
|
units: Arc<dyn PeerUnits>,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
let lender = Arc::new(Lender {
|
let lender = Arc::new(Lender {
|
||||||
callers,
|
holders,
|
||||||
limits,
|
limits,
|
||||||
service,
|
service,
|
||||||
quota,
|
quota,
|
||||||
|
|
@ -487,7 +473,7 @@ impl Lender {
|
||||||
peer: PeerCredentials,
|
peer: PeerCredentials,
|
||||||
request: LeaseRequest,
|
request: LeaseRequest,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
let Some(caller) = self.callers.iter().find(|caller| caller.uid == peer.uid) else {
|
let Some(holder) = self.holders.iter().find(|holder| holder.uid == peer.uid) else {
|
||||||
return refuse(
|
return refuse(
|
||||||
&mut stream,
|
&mut stream,
|
||||||
LeaseRefusalKind::UnknownCaller,
|
LeaseRefusalKind::UnknownCaller,
|
||||||
|
|
@ -499,13 +485,13 @@ impl Lender {
|
||||||
let Some(invocation) = peer
|
let Some(invocation) = peer
|
||||||
.process
|
.process
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit()))
|
.and_then(|process| self.units.invocation_in(process.as_fd(), &holder.unit))
|
||||||
.filter(|found| found.unit == caller.unit())
|
.filter(|found| found.unit == holder.unit)
|
||||||
else {
|
else {
|
||||||
return refuse(
|
return refuse(
|
||||||
&mut stream,
|
&mut stream,
|
||||||
LeaseRefusalKind::UnknownCaller,
|
LeaseRefusalKind::UnknownCaller,
|
||||||
"this process is not in the Self unit",
|
"this process is not in the configured unit",
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
let now = unix_ms();
|
let now = unix_ms();
|
||||||
|
|
@ -522,7 +508,7 @@ impl Lender {
|
||||||
// plan the refusal reads is the one this process last observed, but a
|
// plan the refusal reads is the one this process last observed, but a
|
||||||
// cell with no weekly reading (a restart empties it) gets the meter's
|
// cell with no weekly reading (a restart empties it) gets the meter's
|
||||||
// first read, bounded, before the lease is lent "unobserved" for its
|
// first read, bounded, before the lease is lent "unobserved" for its
|
||||||
// whole life. The request is the swarm's sign of life, however it
|
// whole life. The request is the holder's sign of life, however it
|
||||||
// ends: the meter reads while one is held or lately asked for.
|
// ends: the meter reads while one is held or lately asked for.
|
||||||
let _asking = self.quota.asking();
|
let _asking = self.quota.asking();
|
||||||
let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT);
|
let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT);
|
||||||
|
|
@ -532,8 +518,8 @@ impl Lender {
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| io::Error::other("service lock"))?
|
.map_err(|_| io::Error::other("service lock"))?
|
||||||
.begin_lease(
|
.begin_lease(
|
||||||
&caller.caller_id,
|
&holder.caller_id,
|
||||||
caller.turn,
|
holder.scope,
|
||||||
&invocation.invocation_id,
|
&invocation.invocation_id,
|
||||||
request.expires_at_unix_ms,
|
request.expires_at_unix_ms,
|
||||||
now,
|
now,
|
||||||
|
|
@ -562,7 +548,7 @@ impl Lender {
|
||||||
};
|
};
|
||||||
self.hold(
|
self.hold(
|
||||||
stream,
|
stream,
|
||||||
caller,
|
holder,
|
||||||
&grant,
|
&grant,
|
||||||
&invocation,
|
&invocation,
|
||||||
peer.process,
|
peer.process,
|
||||||
|
|
@ -579,7 +565,7 @@ impl Lender {
|
||||||
fn hold(
|
fn hold(
|
||||||
&self,
|
&self,
|
||||||
mut stream: UnixStream,
|
mut stream: UnixStream,
|
||||||
caller: &LeaseCaller,
|
holder: &LeaseHolder,
|
||||||
grant: &LeaseGrant,
|
grant: &LeaseGrant,
|
||||||
invocation: &PeerUnit,
|
invocation: &PeerUnit,
|
||||||
process: Option<OwnedFd>,
|
process: Option<OwnedFd>,
|
||||||
|
|
@ -588,7 +574,7 @@ impl Lender {
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
let held = self.keep(
|
let held = self.keep(
|
||||||
&mut stream,
|
&mut stream,
|
||||||
caller,
|
holder,
|
||||||
grant,
|
grant,
|
||||||
invocation,
|
invocation,
|
||||||
process.as_ref(),
|
process.as_ref(),
|
||||||
|
|
@ -598,7 +584,7 @@ impl Lender {
|
||||||
self.service
|
self.service
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| io::Error::other("service lock"))?
|
.map_err(|_| io::Error::other("service lock"))?
|
||||||
.end_lease(&caller.caller_id, &grant.lease_id);
|
.end_lease(&holder.caller_id, &grant.lease_id);
|
||||||
held
|
held
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -607,7 +593,7 @@ impl Lender {
|
||||||
fn keep(
|
fn keep(
|
||||||
&self,
|
&self,
|
||||||
stream: &mut UnixStream,
|
stream: &mut UnixStream,
|
||||||
caller: &LeaseCaller,
|
holder: &LeaseHolder,
|
||||||
grant: &LeaseGrant,
|
grant: &LeaseGrant,
|
||||||
invocation: &PeerUnit,
|
invocation: &PeerUnit,
|
||||||
process: Option<&OwnedFd>,
|
process: Option<&OwnedFd>,
|
||||||
|
|
@ -651,7 +637,7 @@ impl Lender {
|
||||||
Err(_) => return Ok(()),
|
Err(_) => return Ok(()),
|
||||||
}
|
}
|
||||||
let still = process
|
let still = process
|
||||||
.and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit()))
|
.and_then(|process| self.units.invocation_in(process.as_fd(), &holder.unit))
|
||||||
.is_some_and(|found| found == *invocation);
|
.is_some_and(|found| found == *invocation);
|
||||||
if !still {
|
if !still {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
|
|
@ -707,7 +693,11 @@ mod tests {
|
||||||
let service = Arc::new(Mutex::new(
|
let service = Arc::new(Mutex::new(
|
||||||
TransportService::open(
|
TransportService::open(
|
||||||
&dir.join("replay.cc"),
|
&dir.join("replay.cc"),
|
||||||
"claude-code",
|
model_connector::ProviderRoutes::new([(
|
||||||
|
"model".to_string(),
|
||||||
|
"claude-code".to_string(),
|
||||||
|
)])
|
||||||
|
.unwrap(),
|
||||||
[model_connector::CallerAdmission::new(
|
[model_connector::CallerAdmission::new(
|
||||||
"lease-test-caller",
|
"lease-test-caller",
|
||||||
"lease-test-connection-key",
|
"lease-test-connection-key",
|
||||||
|
|
@ -723,7 +713,7 @@ mod tests {
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
));
|
));
|
||||||
let lender = Lender {
|
let lender = Lender {
|
||||||
callers: Vec::new(),
|
holders: Vec::new(),
|
||||||
limits: LeaseLimits {
|
limits: LeaseLimits {
|
||||||
socket_timeout: Duration::from_secs(2),
|
socket_timeout: Duration::from_secs(2),
|
||||||
max_lease_ms: 3_600_000,
|
max_lease_ms: 3_600_000,
|
||||||
|
|
@ -747,7 +737,7 @@ mod tests {
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
let _ = serve_leases(
|
let _ = serve_leases(
|
||||||
&listener,
|
&listener,
|
||||||
lender.callers,
|
lender.holders,
|
||||||
lender.limits,
|
lender.limits,
|
||||||
service,
|
service,
|
||||||
quota,
|
quota,
|
||||||
|
|
|
||||||
379
crates/claude-connector/src/lease_run.rs
Normal file
379
crates/claude-connector/src/lease_run.rs
Normal file
|
|
@ -0,0 +1,379 @@
|
||||||
|
//! Runs a command with a lent subscription token delivered on descriptor 3
|
||||||
|
//! (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3`).
|
||||||
|
//!
|
||||||
|
//! Connects to the connector's lease socket, requests a lease, receives the
|
||||||
|
//! grant frame and the pipe read descriptor via `SCM_RIGHTS`, spawns the child
|
||||||
|
//! with the descriptor placed at fd 3, drops the parent's copy of the pipe,
|
||||||
|
//! holds the unix socket open until the child exits, and returns the child's
|
||||||
|
//! exit status. Never reads the token bytes or writes them (or any path or
|
||||||
|
//! refusal detail) to the environment, argv, or stderr.
|
||||||
|
|
||||||
|
use std::io::{self, ErrorKind, Write};
|
||||||
|
use std::mem::{size_of, zeroed};
|
||||||
|
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
|
||||||
|
use std::os::unix::net::UnixStream;
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Command, ExitStatus};
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use crate::launch::{TOKEN_FD, TOKEN_FD_VAR};
|
||||||
|
use crate::lease::{
|
||||||
|
LeaseMessage, LeaseRefusalKind, LeaseRequest, MAX_LEASE_FRAME_BYTES, decode_frame, encode_frame,
|
||||||
|
};
|
||||||
|
use crate::process::place_fd;
|
||||||
|
|
||||||
|
/// Default lease lifetime requested when `--ttl-secs` is omitted (59 minutes).
|
||||||
|
pub const DEFAULT_TTL_SECS: u64 = 3_540;
|
||||||
|
|
||||||
|
/// Timeout applied to the initial request write and grant frame read.
|
||||||
|
const SOCKET_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
|
/// Arguments for [`lease_run`].
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LeaseRunArgs {
|
||||||
|
pub socket: PathBuf,
|
||||||
|
pub ttl: Duration,
|
||||||
|
pub program: String,
|
||||||
|
pub args: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failures from requesting a lease or launching the child; never echoes
|
||||||
|
/// input paths, program names, token bytes, or lender refusal detail text.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum LeaseRunError {
|
||||||
|
#[error("the lease ttl is invalid")]
|
||||||
|
Ttl,
|
||||||
|
#[error("the system clock could not be read")]
|
||||||
|
Clock,
|
||||||
|
#[error("the lease program is missing")]
|
||||||
|
Program,
|
||||||
|
#[error("the lease socket connection failed: {0}")]
|
||||||
|
Connect(ErrorKind),
|
||||||
|
#[error("the lease request could not be sent: {0}")]
|
||||||
|
Send(ErrorKind),
|
||||||
|
#[error("the lease reply could not be read: {0}")]
|
||||||
|
Receive(ErrorKind),
|
||||||
|
#[error("the lease reply frame is malformed")]
|
||||||
|
Frame,
|
||||||
|
#[error("the lease grant did not carry exactly one token descriptor")]
|
||||||
|
UnexpectedFds,
|
||||||
|
#[error("the lease request was refused: {0:?}")]
|
||||||
|
Refused(LeaseRefusalKind),
|
||||||
|
#[error("the leased command could not be spawned: {0}")]
|
||||||
|
Spawn(ErrorKind),
|
||||||
|
#[error("waiting on the leased command failed: {0}")]
|
||||||
|
Wait(ErrorKind),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Requests a credential lease over `args.socket`, spawns `args.program` with
|
||||||
|
/// `args.args` and the token pipe placed at [`TOKEN_FD`] (`TOKEN_FD_VAR=3`),
|
||||||
|
/// holds the socket open until the child exits, and returns the child's status.
|
||||||
|
pub fn lease_run(args: &LeaseRunArgs) -> Result<ExitStatus, LeaseRunError> {
|
||||||
|
if args.program.is_empty() {
|
||||||
|
return Err(LeaseRunError::Program);
|
||||||
|
}
|
||||||
|
let ttl_ms = u64::try_from(args.ttl.as_millis())
|
||||||
|
.ok()
|
||||||
|
.filter(|ms| *ms > 0)
|
||||||
|
.ok_or(LeaseRunError::Ttl)?;
|
||||||
|
let now_ms = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map_err(|_| LeaseRunError::Clock)
|
||||||
|
.and_then(|elapsed| u64::try_from(elapsed.as_millis()).map_err(|_| LeaseRunError::Clock))?;
|
||||||
|
let expires_at_unix_ms = now_ms.checked_add(ttl_ms).ok_or(LeaseRunError::Ttl)?;
|
||||||
|
|
||||||
|
let mut stream =
|
||||||
|
UnixStream::connect(&args.socket).map_err(|error| LeaseRunError::Connect(error.kind()))?;
|
||||||
|
stream
|
||||||
|
.set_write_timeout(Some(SOCKET_TIMEOUT))
|
||||||
|
.map_err(|error| LeaseRunError::Send(error.kind()))?;
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(SOCKET_TIMEOUT))
|
||||||
|
.map_err(|error| LeaseRunError::Receive(error.kind()))?;
|
||||||
|
|
||||||
|
let request = encode_frame(&LeaseMessage::ClaudeLeaseRequest(LeaseRequest {
|
||||||
|
expires_at_unix_ms,
|
||||||
|
}));
|
||||||
|
stream
|
||||||
|
.write_all(&request)
|
||||||
|
.map_err(|error| LeaseRunError::Send(error.kind()))?;
|
||||||
|
|
||||||
|
let (frame, fds) = recv_frame_with_fds(&stream)?;
|
||||||
|
let message = decode_frame(&frame).ok_or(LeaseRunError::Frame)?;
|
||||||
|
match message {
|
||||||
|
LeaseMessage::ClaudeLeaseRefusal(refusal) => Err(LeaseRunError::Refused(refusal.kind)),
|
||||||
|
LeaseMessage::ClaudeLeaseGrant(_) => {
|
||||||
|
if fds.len() != 1 {
|
||||||
|
return Err(LeaseRunError::UnexpectedFds);
|
||||||
|
}
|
||||||
|
let token_fd = fds.into_iter().next().ok_or(LeaseRunError::UnexpectedFds)?;
|
||||||
|
spawn_and_hold(stream, token_fd, &args.program, &args.args)
|
||||||
|
}
|
||||||
|
_ => Err(LeaseRunError::Frame),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_and_hold(
|
||||||
|
stream: UnixStream,
|
||||||
|
token_fd: OwnedFd,
|
||||||
|
program: &str,
|
||||||
|
args: &[String],
|
||||||
|
) -> Result<ExitStatus, LeaseRunError> {
|
||||||
|
let mut command = Command::new(program);
|
||||||
|
command.args(args).env(TOKEN_FD_VAR, TOKEN_FD.to_string());
|
||||||
|
let source = token_fd.as_raw_fd();
|
||||||
|
// SAFETY: `place_fd` calls only async-signal-safe `dup2` and `fcntl`.
|
||||||
|
unsafe {
|
||||||
|
command.pre_exec(move || place_fd(source, TOKEN_FD));
|
||||||
|
}
|
||||||
|
let mut child = command
|
||||||
|
.spawn()
|
||||||
|
.map_err(|error| LeaseRunError::Spawn(error.kind()))?;
|
||||||
|
drop(token_fd);
|
||||||
|
let status = child
|
||||||
|
.wait()
|
||||||
|
.map_err(|error| LeaseRunError::Wait(error.kind()))?;
|
||||||
|
drop(stream);
|
||||||
|
Ok(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recv_frame_with_fds(stream: &UnixStream) -> Result<(Vec<u8>, Vec<OwnedFd>), LeaseRunError> {
|
||||||
|
let mut frame = Vec::new();
|
||||||
|
let mut fds = Vec::new();
|
||||||
|
let mut expected_total: Option<usize> = None;
|
||||||
|
let mut chunk = vec![0_u8; 4 + MAX_LEASE_FRAME_BYTES + 1];
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let read_cap = match expected_total {
|
||||||
|
None => chunk.len(),
|
||||||
|
Some(total) => (total - frame.len()) + 1,
|
||||||
|
};
|
||||||
|
let (received, mut chunk_fds) = recv_chunk(stream, &mut chunk[..read_cap])?;
|
||||||
|
fds.append(&mut chunk_fds);
|
||||||
|
if received == 0 {
|
||||||
|
return Err(LeaseRunError::Frame);
|
||||||
|
}
|
||||||
|
frame.extend_from_slice(&chunk[..received]);
|
||||||
|
if expected_total.is_none() && frame.len() >= 4 {
|
||||||
|
let len = u32::from_be_bytes([frame[0], frame[1], frame[2], frame[3]]) as usize;
|
||||||
|
if len == 0 || len > MAX_LEASE_FRAME_BYTES {
|
||||||
|
return Err(LeaseRunError::Frame);
|
||||||
|
}
|
||||||
|
expected_total = Some(4 + len);
|
||||||
|
}
|
||||||
|
if let Some(total) = expected_total {
|
||||||
|
if frame.len() > total {
|
||||||
|
return Err(LeaseRunError::Frame);
|
||||||
|
}
|
||||||
|
if frame.len() == total {
|
||||||
|
return Ok((frame, fds));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recv_chunk(stream: &UnixStream, buf: &mut [u8]) -> Result<(usize, Vec<OwnedFd>), LeaseRunError> {
|
||||||
|
const MAX_CMSG_FDS: usize = 16;
|
||||||
|
// SAFETY: `CMSG_SPACE` is a pure size computation.
|
||||||
|
let space = unsafe { libc::CMSG_SPACE((MAX_CMSG_FDS * size_of::<RawFd>()) as u32) } as usize;
|
||||||
|
let mut control = vec![0_u64; space.div_ceil(size_of::<u64>())];
|
||||||
|
let mut vector = libc::iovec {
|
||||||
|
iov_base: buf.as_mut_ptr().cast(),
|
||||||
|
iov_len: buf.len(),
|
||||||
|
};
|
||||||
|
// SAFETY: `buf` and `control` outlive `recvmsg`; `msg_controllen` matches the
|
||||||
|
// byte length of `control`; descriptors received via `SCM_RIGHTS` with
|
||||||
|
// `MSG_CMSG_CLOEXEC` are newly installed in this process and owned nowhere else.
|
||||||
|
unsafe {
|
||||||
|
let mut message: libc::msghdr = zeroed();
|
||||||
|
message.msg_iov = &mut vector;
|
||||||
|
message.msg_iovlen = 1;
|
||||||
|
message.msg_control = control.as_mut_ptr().cast();
|
||||||
|
message.msg_controllen = (control.len() * size_of::<u64>()) as _;
|
||||||
|
let received = loop {
|
||||||
|
let n = libc::recvmsg(stream.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC);
|
||||||
|
if n >= 0 || io::Error::last_os_error().kind() != ErrorKind::Interrupted {
|
||||||
|
break n;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if received < 0 {
|
||||||
|
return Err(LeaseRunError::Receive(io::Error::last_os_error().kind()));
|
||||||
|
}
|
||||||
|
let mut fds = Vec::new();
|
||||||
|
let mut header = libc::CMSG_FIRSTHDR(&message);
|
||||||
|
while !header.is_null() {
|
||||||
|
if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS {
|
||||||
|
let cmsg_len = (*header).cmsg_len as usize;
|
||||||
|
let base = libc::CMSG_LEN(0) as usize;
|
||||||
|
if cmsg_len >= base {
|
||||||
|
let data = libc::CMSG_DATA(header).cast::<RawFd>();
|
||||||
|
for index in 0..(cmsg_len - base) / size_of::<RawFd>() {
|
||||||
|
fds.push(OwnedFd::from_raw_fd(data.add(index).read_unaligned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
header = libc::CMSG_NXTHDR(&message, header);
|
||||||
|
}
|
||||||
|
if (message.msg_flags & libc::MSG_CTRUNC) != 0 {
|
||||||
|
return Err(LeaseRunError::UnexpectedFds);
|
||||||
|
}
|
||||||
|
Ok((received as usize, fds))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::lease::{LeaseGranted, LeaseRefused};
|
||||||
|
|
||||||
|
fn roundtrip_bytes(bytes: &[u8]) -> Result<(Vec<u8>, Vec<OwnedFd>), LeaseRunError> {
|
||||||
|
let (rx, mut tx) = UnixStream::pair().unwrap();
|
||||||
|
let data = bytes.to_vec();
|
||||||
|
let writer = std::thread::spawn(move || {
|
||||||
|
let _ = tx.write_all(&data);
|
||||||
|
drop(tx);
|
||||||
|
});
|
||||||
|
let result = recv_frame_with_fds(&rx);
|
||||||
|
writer.join().unwrap();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zero_ttl_is_rejected_before_connecting() {
|
||||||
|
let args = LeaseRunArgs {
|
||||||
|
socket: PathBuf::from("/nonexistent/lease.sock"),
|
||||||
|
ttl: Duration::ZERO,
|
||||||
|
program: "/bin/true".to_string(),
|
||||||
|
args: vec![],
|
||||||
|
};
|
||||||
|
assert!(matches!(lease_run(&args), Err(LeaseRunError::Ttl)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recv_rejects_zero_over_bound_truncated_and_trailing_frames() {
|
||||||
|
assert!(matches!(roundtrip_bytes(&[]), Err(LeaseRunError::Frame)));
|
||||||
|
assert!(matches!(
|
||||||
|
roundtrip_bytes(&[0, 0, 0, 0]),
|
||||||
|
Err(LeaseRunError::Frame)
|
||||||
|
));
|
||||||
|
let over = (MAX_LEASE_FRAME_BYTES as u32 + 1).to_be_bytes();
|
||||||
|
assert!(matches!(roundtrip_bytes(&over), Err(LeaseRunError::Frame)));
|
||||||
|
|
||||||
|
let valid = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||||
|
kind: LeaseRefusalKind::Busy,
|
||||||
|
detail: "busy".to_string(),
|
||||||
|
}));
|
||||||
|
assert!(matches!(
|
||||||
|
roundtrip_bytes(&valid[..valid.len() - 1]),
|
||||||
|
Err(LeaseRunError::Frame)
|
||||||
|
));
|
||||||
|
let mut trailing = valid.clone();
|
||||||
|
trailing.push(0);
|
||||||
|
assert!(matches!(
|
||||||
|
roundtrip_bytes(&trailing),
|
||||||
|
Err(LeaseRunError::Frame)
|
||||||
|
));
|
||||||
|
let (read, fds) = roundtrip_bytes(&valid).unwrap();
|
||||||
|
assert_eq!(read, valid);
|
||||||
|
assert!(fds.is_empty());
|
||||||
|
|
||||||
|
// Exact MAX_LEASE_FRAME_BYTES body must be accepted.
|
||||||
|
let probe = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||||
|
kind: LeaseRefusalKind::Busy,
|
||||||
|
detail: "x".repeat(300),
|
||||||
|
}));
|
||||||
|
let overhead = probe.len() - 4 - 300;
|
||||||
|
let max_frame = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||||
|
kind: LeaseRefusalKind::Busy,
|
||||||
|
detail: "x".repeat(MAX_LEASE_FRAME_BYTES - overhead),
|
||||||
|
}));
|
||||||
|
assert_eq!(max_frame.len(), 4 + MAX_LEASE_FRAME_BYTES);
|
||||||
|
let (read_max, _) = roundtrip_bytes(&max_frame).unwrap();
|
||||||
|
assert_eq!(read_max, max_frame);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recv_handles_chunked_header_and_body_and_catches_chunked_trailing() {
|
||||||
|
let valid = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||||
|
kind: LeaseRefusalKind::Busy,
|
||||||
|
detail: "chunked-frame-payload".to_string(),
|
||||||
|
}));
|
||||||
|
let (rx, mut tx) = UnixStream::pair().unwrap();
|
||||||
|
let expected = valid.clone();
|
||||||
|
let writer = std::thread::spawn(move || {
|
||||||
|
tx.write_all(&expected[..2]).unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
tx.write_all(&expected[2..expected.len() - 1]).unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
tx.write_all(&expected[expected.len() - 1..]).unwrap();
|
||||||
|
});
|
||||||
|
let (read, fds) = recv_frame_with_fds(&rx).unwrap();
|
||||||
|
assert_eq!(read, valid);
|
||||||
|
assert!(fds.is_empty());
|
||||||
|
writer.join().unwrap();
|
||||||
|
|
||||||
|
let (rx2, mut tx2) = UnixStream::pair().unwrap();
|
||||||
|
let mut with_trailing = valid.clone();
|
||||||
|
with_trailing.push(0xaa);
|
||||||
|
let writer2 = std::thread::spawn(move || {
|
||||||
|
tx2.write_all(&with_trailing[..2]).unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
tx2.write_all(&with_trailing[2..]).unwrap();
|
||||||
|
});
|
||||||
|
assert!(matches!(
|
||||||
|
recv_frame_with_fds(&rx2),
|
||||||
|
Err(LeaseRunError::Frame)
|
||||||
|
));
|
||||||
|
writer2.join().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grant_without_fd_is_rejected_and_refusal_never_echoes_detail() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("lease-run-unit-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let socket = dir.join("lease.sock");
|
||||||
|
let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
|
||||||
|
|
||||||
|
let server = std::thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
let mut buf = [0_u8; 256];
|
||||||
|
let _ = io::Read::read(&mut stream, &mut buf);
|
||||||
|
let grant = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted {
|
||||||
|
lease_id: "lease:1".to_string(),
|
||||||
|
plan_quota: vec![],
|
||||||
|
}));
|
||||||
|
stream.write_all(&grant).unwrap();
|
||||||
|
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
let _ = io::Read::read(&mut stream, &mut buf);
|
||||||
|
let refusal = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||||
|
kind: LeaseRefusalKind::ProviderRejected,
|
||||||
|
detail: "CANARY-DETAIL-SECRET".to_string(),
|
||||||
|
}));
|
||||||
|
stream.write_all(&refusal).unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let args = LeaseRunArgs {
|
||||||
|
socket: socket.clone(),
|
||||||
|
ttl: Duration::from_secs(DEFAULT_TTL_SECS),
|
||||||
|
program: "/bin/true".to_string(),
|
||||||
|
args: vec![],
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
lease_run(&args),
|
||||||
|
Err(LeaseRunError::UnexpectedFds)
|
||||||
|
));
|
||||||
|
let err = lease_run(&args).unwrap_err();
|
||||||
|
let text = format!("{err} {err:?}");
|
||||||
|
assert!(matches!(
|
||||||
|
err,
|
||||||
|
LeaseRunError::Refused(LeaseRefusalKind::ProviderRejected)
|
||||||
|
));
|
||||||
|
assert!(!text.contains("CANARY-DETAIL-SECRET"), "{text}");
|
||||||
|
|
||||||
|
server.join().unwrap();
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -3,24 +3,36 @@
|
||||||
//! 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 credential;
|
||||||
mod daemon;
|
mod daemon;
|
||||||
mod handle;
|
mod handle;
|
||||||
|
mod http;
|
||||||
mod launch;
|
mod launch;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
mod lease;
|
mod lease;
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
pub mod lease_run;
|
||||||
|
mod messages;
|
||||||
mod meter;
|
mod meter;
|
||||||
|
mod openai_chat;
|
||||||
mod process;
|
mod process;
|
||||||
mod quota;
|
mod quota;
|
||||||
|
mod router;
|
||||||
mod stream;
|
mod stream;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
mod unit;
|
mod unit;
|
||||||
|
|
||||||
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
|
pub use backend::{ClaudeCodeBackend, StderrSink};
|
||||||
pub use config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
pub use config::{
|
||||||
|
ClaudeCodeConfig, ClaudeCodeLimits, EffortMap, ForcedToolChoice, ModelRow, OutputSchemaSupport,
|
||||||
|
ProviderEntry, ProviderWire,
|
||||||
|
};
|
||||||
|
pub use credential::{CredentialTokenSource, TokenSource};
|
||||||
pub use daemon::{
|
pub use daemon::{
|
||||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config,
|
ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, 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};
|
||||||
|
|
@ -28,13 +40,16 @@ 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,
|
LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
||||||
LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
|
LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
|
||||||
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
|
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
|
||||||
};
|
};
|
||||||
|
pub use messages::{MessagesBackend, MessagesConfig};
|
||||||
|
pub use openai_chat::{OpenAiChatBackend, OpenAiChatConfig};
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub use process::StdProcessPort;
|
pub use process::StdProcessPort;
|
||||||
pub use process::{ProcessPort, RunningChild, StdoutRead};
|
pub use process::{ProcessPort, RunningChild, StdoutRead};
|
||||||
pub use quota::QuotaCell;
|
pub use quota::QuotaCell;
|
||||||
|
pub use router::RouterBackend;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
pub use unit::SystemdUnits;
|
pub use unit::SystemdUnits;
|
||||||
|
|
|
||||||
|
|
@ -2,37 +2,55 @@
|
||||||
//!
|
//!
|
||||||
//! claude-connector serve --config PATH.cc
|
//! claude-connector serve --config PATH.cc
|
||||||
//! claude-connector config init PATH.cc --flag value ...
|
//! claude-connector config init PATH.cc --flag value ...
|
||||||
|
//! claude-connector config add-provider PATH.cc --provider ID --wire KIND ...
|
||||||
|
//! claude-connector config add-model PATH.cc --model ID --provider ID --upstream NAME ...
|
||||||
//! 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-holder PATH.cc --lease-user U --caller-id ID --provider P --unit NAME --scope per-caller|per-invocation
|
||||||
//! 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
|
||||||
|
//! claude-connector lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...]
|
||||||
//!
|
//!
|
||||||
//! `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`, `add-provider`, and `add-model` exist only to author that document.
|
||||||
//! value that was typed or stored; refusals name a field or a flag.
|
//! No message here echoes a value that was typed or stored; refusals name a field or a flag.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
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,
|
ClaudeConnectorConfig, ConfigError, EffortMap, ForcedToolChoice, LeaseHolderConfig,
|
||||||
|
MIN_SECRET_BYTES, ModelRow, OutputSchemaSupport, ProviderEntry, ProviderWire, check_ready,
|
||||||
load_config, write_config,
|
load_config, write_config,
|
||||||
};
|
};
|
||||||
use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload};
|
use model_connector::{CallerConfig, LeaseScope, frame_bytes_for_payload};
|
||||||
|
|
||||||
fn main() -> ExitCode {
|
fn main() -> ExitCode {
|
||||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||||
let result = match args.as_slice() {
|
let result = match args.as_slice() {
|
||||||
["serve", "--config", path] => serve(path),
|
["serve", "--config", path] => serve(path).map(|()| ExitCode::SUCCESS),
|
||||||
["config", "init", path, flags @ ..] => init(path, flags),
|
["config", "init", path, flags @ ..] => init(path, flags).map(|()| ExitCode::SUCCESS),
|
||||||
["config", "add-caller", path, flags @ ..] => add_caller(path, flags),
|
["config", "add-provider", path, flags @ ..] => {
|
||||||
["config", "add-lease-caller", path, flags @ ..] => add_lease_caller(path, flags),
|
add_provider(path, flags).map(|()| ExitCode::SUCCESS)
|
||||||
["config", "check", path] => check(path),
|
}
|
||||||
|
["config", "add-model", path, flags @ ..] => {
|
||||||
|
add_model(path, flags).map(|()| ExitCode::SUCCESS)
|
||||||
|
}
|
||||||
|
["config", "add-caller", path, flags @ ..] => {
|
||||||
|
add_caller(path, flags).map(|()| ExitCode::SUCCESS)
|
||||||
|
}
|
||||||
|
["config", "add-lease-holder", path, flags @ ..] => {
|
||||||
|
add_lease_holder(path, flags).map(|()| ExitCode::SUCCESS)
|
||||||
|
}
|
||||||
|
["config", "check", path] => check(path).map(|()| ExitCode::SUCCESS),
|
||||||
|
["ask", flags @ ..] => run_ask(flags).map(|()| ExitCode::SUCCESS),
|
||||||
|
["lease", "run", rest @ ..] => run_lease(rest),
|
||||||
_ => Err(Failure::Usage),
|
_ => Err(Failure::Usage),
|
||||||
};
|
};
|
||||||
match result {
|
match result {
|
||||||
Ok(()) => ExitCode::SUCCESS,
|
Ok(code) => code,
|
||||||
Err(failure) => {
|
Err(failure) => {
|
||||||
eprintln!("claude-connector: {failure}");
|
eprintln!("claude-connector: {failure}");
|
||||||
ExitCode::FAILURE
|
ExitCode::FAILURE
|
||||||
|
|
@ -43,7 +61,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-provider PATH --flag value ... | config add-model PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-holder 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] | lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...] (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)]
|
||||||
|
|
@ -52,8 +70,15 @@ enum Failure {
|
||||||
Missing(&'static str),
|
Missing(&'static str),
|
||||||
#[error("flag {0} is malformed")]
|
#[error("flag {0} is malformed")]
|
||||||
Malformed(&'static str),
|
Malformed(&'static str),
|
||||||
|
#[error("flag {0} conflicts with --wire")]
|
||||||
|
Conflict(&'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(target_os = "linux")]
|
||||||
|
#[error("{0}")]
|
||||||
|
LeaseRun(#[from] claude_connector::lease_run::LeaseRunError),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
|
|
@ -70,11 +95,75 @@ fn check(path: &str) -> Result<(), Failure> {
|
||||||
let config = load_config(path.as_ref())?;
|
let config = load_config(path.as_ref())?;
|
||||||
check_ready(&config)?;
|
check_ready(&config)?;
|
||||||
println!("claude connector configuration is valid and ready to serve");
|
println!("claude connector configuration is valid and ready to serve");
|
||||||
|
println!("providers: {}", config.providers.len());
|
||||||
|
println!("models: {}", config.models.len());
|
||||||
println!("callers: {}", config.callers.len());
|
println!("callers: {}", config.callers.len());
|
||||||
println!("lease_callers: {}", config.lease_callers.len());
|
println!("lease_holders: {}", config.lease_holders.len());
|
||||||
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,31 +181,60 @@ const CALLER: [&str; 5] = [
|
||||||
"--max-output-tokens",
|
"--max-output-tokens",
|
||||||
];
|
];
|
||||||
|
|
||||||
const INIT: [&str; 21] = [
|
const INIT: [&str; 8] = [
|
||||||
"--listen",
|
"--listen",
|
||||||
"--replay-store",
|
"--replay-store",
|
||||||
|
"--max-payload-bytes",
|
||||||
|
"--socket-timeout-ms",
|
||||||
|
"--lease-socket",
|
||||||
|
"--lease-max-ms",
|
||||||
|
"--unit",
|
||||||
|
"--scope",
|
||||||
|
];
|
||||||
|
|
||||||
|
const PROVIDER: [&str; 18] = [
|
||||||
|
"--provider",
|
||||||
|
"--wire",
|
||||||
|
"--credential",
|
||||||
|
"--base-url",
|
||||||
|
"--deadline-ms",
|
||||||
|
"--max-response-bytes",
|
||||||
"--claude-binary",
|
"--claude-binary",
|
||||||
"--claude-sha256",
|
"--claude-sha256",
|
||||||
"--work-dir",
|
"--work-dir",
|
||||||
"--config-dir",
|
"--config-dir",
|
||||||
"--prompt-dir",
|
"--prompt-dir",
|
||||||
"--instance",
|
|
||||||
"--token-credential",
|
|
||||||
"--handle-secret-credential",
|
"--handle-secret-credential",
|
||||||
"--handle-secret-file",
|
"--handle-secret-file",
|
||||||
"--deadline-ms",
|
"--instance",
|
||||||
"--max-line-bytes",
|
"--max-line-bytes",
|
||||||
"--max-total-bytes",
|
"--max-total-bytes",
|
||||||
"--stderr-tail-bytes",
|
"--stderr-tail-bytes",
|
||||||
"--max-payload-bytes",
|
"--meter-model",
|
||||||
"--socket-timeout-ms",
|
|
||||||
"--lease-socket",
|
|
||||||
"--lease-max-ms",
|
|
||||||
"--turn",
|
|
||||||
"--lease-unit-instance",
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const LEASE_CALLER: [&str; 3] = ["--caller-id", "--turn", "--lease-unit-instance"];
|
const MODEL: [&str; 11] = [
|
||||||
|
"--model",
|
||||||
|
"--provider",
|
||||||
|
"--upstream",
|
||||||
|
"--effort-low",
|
||||||
|
"--effort-medium",
|
||||||
|
"--effort-high",
|
||||||
|
"--effort-max",
|
||||||
|
"--unset-effort",
|
||||||
|
"--forced-tool-choice",
|
||||||
|
"--output-schema",
|
||||||
|
"--strict-tools",
|
||||||
|
];
|
||||||
|
|
||||||
|
const LEASE_HOLDER: [&str; 4] = ["--caller-id", "--provider", "--unit", "--scope"];
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
enum WireKind {
|
||||||
|
AnthropicMessages,
|
||||||
|
OpenAiChat,
|
||||||
|
ClaudeCodeCli,
|
||||||
|
}
|
||||||
|
|
||||||
impl Flags {
|
impl Flags {
|
||||||
fn parse(
|
fn parse(
|
||||||
|
|
@ -159,6 +277,10 @@ impl Flags {
|
||||||
self.lists.get(name).map_or(&[], Vec::as_slice)
|
self.lists.get(name).map_or(&[], Vec::as_slice)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn optional_text(&self, name: &'static str) -> Option<String> {
|
||||||
|
self.single.get(name).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
fn text(&self, name: &'static str) -> Result<String, Failure> {
|
fn text(&self, name: &'static str) -> Result<String, Failure> {
|
||||||
self.single.get(name).cloned().ok_or(Failure::Missing(name))
|
self.single.get(name).cloned().ok_or(Failure::Missing(name))
|
||||||
}
|
}
|
||||||
|
|
@ -173,12 +295,135 @@ impl Flags {
|
||||||
.map_err(|_| Failure::Malformed(name))
|
.map_err(|_| Failure::Malformed(name))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The kind of turn a leasing account serves: `self` or `persona`.
|
fn reject_any(&self, conflicting: &[&'static str]) -> Result<(), Failure> {
|
||||||
fn turn(&self) -> Result<LeaseTurn, Failure> {
|
for &flag in conflicting {
|
||||||
match self.text("--turn")?.as_str() {
|
if self.single.contains_key(flag) || self.lists.contains_key(flag) {
|
||||||
"self" => Ok(LeaseTurn::SelfRun),
|
return Err(Failure::Conflict(flag));
|
||||||
"persona" => Ok(LeaseTurn::PersonaTurn),
|
}
|
||||||
_ => Err(Failure::Malformed("--turn")),
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wire(&self) -> Result<WireKind, Failure> {
|
||||||
|
match self.text("--wire")?.as_str() {
|
||||||
|
"anthropic-messages" => Ok(WireKind::AnthropicMessages),
|
||||||
|
"openai-chat" => Ok(WireKind::OpenAiChat),
|
||||||
|
"claude-code-cli" => Ok(WireKind::ClaudeCodeCli),
|
||||||
|
_ => Err(Failure::Malformed("--wire")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forced_tool_choice(&self) -> Result<ForcedToolChoice, Failure> {
|
||||||
|
match self.text("--forced-tool-choice")?.as_str() {
|
||||||
|
"always" => Ok(ForcedToolChoice::Always),
|
||||||
|
"without-thinking" => Ok(ForcedToolChoice::WithoutThinking),
|
||||||
|
"never" => Ok(ForcedToolChoice::Never),
|
||||||
|
_ => Err(Failure::Malformed("--forced-tool-choice")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_schema(&self) -> Result<OutputSchemaSupport, Failure> {
|
||||||
|
match self.text("--output-schema")?.as_str() {
|
||||||
|
"native" => Ok(OutputSchemaSupport::Native),
|
||||||
|
"none" => Ok(OutputSchemaSupport::None),
|
||||||
|
_ => Err(Failure::Malformed("--output-schema")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bool_flag(&self, name: &'static str) -> Result<bool, Failure> {
|
||||||
|
match self.text(name)?.as_str() {
|
||||||
|
"true" => Ok(true),
|
||||||
|
"false" => Ok(false),
|
||||||
|
_ => Err(Failure::Malformed(name)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn provider_entry(&self, provider_id: &str) -> Result<ProviderEntry, Failure> {
|
||||||
|
const CLI_ONLY: &[&str] = &[
|
||||||
|
"--claude-binary",
|
||||||
|
"--claude-sha256",
|
||||||
|
"--work-dir",
|
||||||
|
"--config-dir",
|
||||||
|
"--prompt-dir",
|
||||||
|
"--handle-secret-credential",
|
||||||
|
"--handle-secret-file",
|
||||||
|
"--instance",
|
||||||
|
"--max-line-bytes",
|
||||||
|
"--max-total-bytes",
|
||||||
|
"--stderr-tail-bytes",
|
||||||
|
"--meter-model",
|
||||||
|
];
|
||||||
|
const HTTP_ONLY: &[&str] = &["--base-url", "--max-response-bytes", "--strict-unsupported"];
|
||||||
|
|
||||||
|
let wire = match self.wire()? {
|
||||||
|
WireKind::AnthropicMessages => {
|
||||||
|
self.reject_any(CLI_ONLY)?;
|
||||||
|
self.reject_any(&["--strict-unsupported"])?;
|
||||||
|
ProviderWire::AnthropicMessages {
|
||||||
|
base_url: self.text("--base-url")?,
|
||||||
|
deadline_ms: self.number_or("--deadline-ms", 600_000)?,
|
||||||
|
max_response_bytes: self.number_or("--max-response-bytes", 64 << 20)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WireKind::OpenAiChat => {
|
||||||
|
self.reject_any(CLI_ONLY)?;
|
||||||
|
ProviderWire::OpenAiChat {
|
||||||
|
base_url: self.text("--base-url")?,
|
||||||
|
strict_unsupported: self.list("--strict-unsupported").to_vec(),
|
||||||
|
deadline_ms: self.number_or("--deadline-ms", 600_000)?,
|
||||||
|
max_response_bytes: self.number_or("--max-response-bytes", 64 << 20)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WireKind::ClaudeCodeCli => {
|
||||||
|
self.reject_any(HTTP_ONLY)?;
|
||||||
|
ProviderWire::ClaudeCodeCli {
|
||||||
|
binary: self.path("--claude-binary")?,
|
||||||
|
binary_sha256: sha256(&self.text("--claude-sha256")?)
|
||||||
|
.ok_or(Failure::Malformed("--claude-sha256"))?,
|
||||||
|
work_dir: self.path("--work-dir")?,
|
||||||
|
config_dir: self.path("--config-dir")?,
|
||||||
|
prompt_dir: self.path("--prompt-dir")?,
|
||||||
|
handle_secret_credential: self.text("--handle-secret-credential")?,
|
||||||
|
instance: self.text("--instance")?,
|
||||||
|
deadline_ms: self.number_or("--deadline-ms", 600_000)?,
|
||||||
|
max_line_bytes: self.number_or("--max-line-bytes", 4 << 20)?,
|
||||||
|
max_total_bytes: self.number_or("--max-total-bytes", 64 << 20)?,
|
||||||
|
stderr_tail_bytes: self.number_or("--stderr-tail-bytes", 8192)?,
|
||||||
|
meter_model: self.optional_text("--meter-model"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(ProviderEntry {
|
||||||
|
id: provider_id.to_string(),
|
||||||
|
credential: self.optional_text("--credential"),
|
||||||
|
wire,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn model_row(&self, provider_id: &str) -> Result<ModelRow, Failure> {
|
||||||
|
Ok(ModelRow {
|
||||||
|
id: self.text("--model")?,
|
||||||
|
provider: provider_id.to_string(),
|
||||||
|
upstream: self.text("--upstream")?,
|
||||||
|
efforts: EffortMap {
|
||||||
|
low: self.optional_text("--effort-low"),
|
||||||
|
medium: self.optional_text("--effort-medium"),
|
||||||
|
high: self.optional_text("--effort-high"),
|
||||||
|
max: self.optional_text("--effort-max"),
|
||||||
|
},
|
||||||
|
unset_effort: self.optional_text("--unset-effort"),
|
||||||
|
forced_tool_choice: self.forced_tool_choice()?,
|
||||||
|
output_schema: self.output_schema()?,
|
||||||
|
strict_tools: self.bool_flag("--strict-tools")?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The exclusivity scope a leasing account holds: `per-caller` or `per-invocation`.
|
||||||
|
fn scope(&self) -> Result<LeaseScope, Failure> {
|
||||||
|
match self.text("--scope")?.as_str() {
|
||||||
|
"per-caller" => Ok(LeaseScope::PerCaller),
|
||||||
|
"per-invocation" => Ok(LeaseScope::PerInvocation),
|
||||||
|
_ => Err(Failure::Malformed("--scope")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -283,51 +528,77 @@ fn ensure_secret_file(_: &std::path::Path) -> Result<(), Failure> {
|
||||||
fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
||||||
let flags = Flags::parse(
|
let flags = Flags::parse(
|
||||||
args,
|
args,
|
||||||
&[&INIT, &CALLER],
|
&[&INIT, &PROVIDER, &MODEL, &CALLER],
|
||||||
&["--allowed-model", "--lease-user"],
|
&["--allowed-model", "--lease-user", "--strict-unsupported"],
|
||||||
)?;
|
)?;
|
||||||
|
let provider_id = flags.text("--provider")?;
|
||||||
|
let provider = flags.provider_entry(&provider_id)?;
|
||||||
|
let model = flags.model_row(&provider_id)?;
|
||||||
let first = flags.caller()?;
|
let first = flags.caller()?;
|
||||||
let lease_callers = flags
|
let lease_holders = flags
|
||||||
.list("--lease-user")
|
.list("--lease-user")
|
||||||
.iter()
|
.iter()
|
||||||
.map(|unix_user| {
|
.map(|unix_user| {
|
||||||
Ok(LeaseCallerConfig {
|
Ok(LeaseHolderConfig {
|
||||||
unix_user: unix_user.clone(),
|
unix_user: unix_user.clone(),
|
||||||
caller_id: first.caller_runtime_id.clone(),
|
caller_id: first.caller_runtime_id.clone(),
|
||||||
turn: flags.turn()?,
|
provider: provider_id.clone(),
|
||||||
unit_instance: flags.text("--lease-unit-instance")?,
|
unit: flags.text("--unit")?,
|
||||||
|
scope: flags.scope()?,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect::<Result<Vec<_>, Failure>>()?;
|
.collect::<Result<Vec<_>, Failure>>()?;
|
||||||
let secret_file = flags.path("--handle-secret-file")?;
|
let secret_file = matches!(provider.wire, ProviderWire::ClaudeCodeCli { .. })
|
||||||
|
.then(|| flags.single.get("--handle-secret-file").map(PathBuf::from))
|
||||||
|
.flatten();
|
||||||
let config = ClaudeConnectorConfig {
|
let config = ClaudeConnectorConfig {
|
||||||
listen: flags.text("--listen")?,
|
listen: flags.text("--listen")?,
|
||||||
replay_store: flags.path("--replay-store")?,
|
replay_store: flags.path("--replay-store")?,
|
||||||
claude_binary: flags.path("--claude-binary")?,
|
|
||||||
claude_binary_sha256: sha256(&flags.text("--claude-sha256")?)
|
|
||||||
.ok_or(Failure::Malformed("--claude-sha256"))?,
|
|
||||||
work_dir: flags.path("--work-dir")?,
|
|
||||||
config_dir: flags.path("--config-dir")?,
|
|
||||||
prompt_dir: flags.path("--prompt-dir")?,
|
|
||||||
instance: flags.text("--instance")?,
|
|
||||||
token_credential: flags.text("--token-credential")?,
|
|
||||||
deadline_ms: flags.number_or("--deadline-ms", 600_000)?,
|
|
||||||
max_line_bytes: flags.number_or("--max-line-bytes", 4 << 20)?,
|
|
||||||
max_total_bytes: flags.number_or("--max-total-bytes", 64 << 20)?,
|
|
||||||
stderr_tail_bytes: flags.number_or("--stderr-tail-bytes", 8192)?,
|
|
||||||
max_frame_bytes: frame_bytes_for_payload(first.max_payload_bytes),
|
max_frame_bytes: frame_bytes_for_payload(first.max_payload_bytes),
|
||||||
max_connections: first.max_concurrent_requests.max(8),
|
max_connections: first.max_concurrent_requests.max(8),
|
||||||
socket_timeout_ms: flags.number_or("--socket-timeout-ms", 10_000)?,
|
socket_timeout_ms: flags.number_or("--socket-timeout-ms", 10_000)?,
|
||||||
max_expiry_skew_ms: 300_000,
|
max_expiry_skew_ms: 300_000,
|
||||||
|
providers: vec![provider],
|
||||||
|
models: vec![model],
|
||||||
callers: vec![first],
|
callers: vec![first],
|
||||||
lease_socket: flags.single.get("--lease-socket").map(PathBuf::from),
|
lease_socket: flags.single.get("--lease-socket").map(PathBuf::from),
|
||||||
lease_callers,
|
lease_holders,
|
||||||
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")?,
|
|
||||||
};
|
};
|
||||||
// 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()?;
|
||||||
ensure_secret_file(&secret_file)?;
|
if let Some(secret_file) = secret_file {
|
||||||
|
ensure_secret_file(&secret_file)?;
|
||||||
|
}
|
||||||
|
write_config(path.as_ref(), &config)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends one provider entry to an existing document.
|
||||||
|
fn add_provider(path: &str, args: &[&str]) -> Result<(), Failure> {
|
||||||
|
let flags = Flags::parse(args, &[&PROVIDER], &["--strict-unsupported"])?;
|
||||||
|
let provider_id = flags.text("--provider")?;
|
||||||
|
let provider = flags.provider_entry(&provider_id)?;
|
||||||
|
let secret_file = matches!(provider.wire, ProviderWire::ClaudeCodeCli { .. })
|
||||||
|
.then(|| flags.single.get("--handle-secret-file").map(PathBuf::from))
|
||||||
|
.flatten();
|
||||||
|
let mut config = load_config(path.as_ref())?;
|
||||||
|
config.providers.push(provider);
|
||||||
|
config.validate()?;
|
||||||
|
if let Some(secret_file) = secret_file {
|
||||||
|
ensure_secret_file(&secret_file)?;
|
||||||
|
}
|
||||||
|
write_config(path.as_ref(), &config)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends one model row to an existing document.
|
||||||
|
fn add_model(path: &str, args: &[&str]) -> Result<(), Failure> {
|
||||||
|
let flags = Flags::parse(args, &[&MODEL], &[])?;
|
||||||
|
let provider_id = flags.text("--provider")?;
|
||||||
|
let model = flags.model_row(&provider_id)?;
|
||||||
|
let mut config = load_config(path.as_ref())?;
|
||||||
|
config.models.push(model);
|
||||||
write_config(path.as_ref(), &config)?;
|
write_config(path.as_ref(), &config)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -356,20 +627,62 @@ fn add_caller(path: &str, args: &[&str]) -> Result<(), Failure> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends one leasing account to an existing document that lends a token.
|
/// Appends one lease holder to an existing document that lends a token.
|
||||||
fn add_lease_caller(path: &str, args: &[&str]) -> Result<(), Failure> {
|
fn add_lease_holder(path: &str, args: &[&str]) -> Result<(), Failure> {
|
||||||
let flags = Flags::parse(args, &[&LEASE_CALLER, &["--lease-user"]], &[])?;
|
let flags = Flags::parse(args, &[&LEASE_HOLDER, &["--lease-user"]], &[])?;
|
||||||
let mut config = load_config(path.as_ref())?;
|
let mut config = load_config(path.as_ref())?;
|
||||||
config.lease_callers.push(LeaseCallerConfig {
|
config.lease_holders.push(LeaseHolderConfig {
|
||||||
unix_user: flags.text("--lease-user")?,
|
unix_user: flags.text("--lease-user")?,
|
||||||
caller_id: flags.text("--caller-id")?,
|
caller_id: flags.text("--caller-id")?,
|
||||||
turn: flags.turn()?,
|
provider: flags.text("--provider")?,
|
||||||
unit_instance: flags.text("--lease-unit-instance")?,
|
unit: flags.text("--unit")?,
|
||||||
|
scope: flags.scope()?,
|
||||||
});
|
});
|
||||||
write_config(path.as_ref(), &config)?;
|
write_config(path.as_ref(), &config)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
fn run_lease(args: &[&str]) -> Result<ExitCode, Failure> {
|
||||||
|
use std::os::unix::process::ExitStatusExt;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use claude_connector::lease_run::{DEFAULT_TTL_SECS, LeaseRunArgs, lease_run};
|
||||||
|
|
||||||
|
let Some(sep) = args.iter().position(|arg| *arg == "--") else {
|
||||||
|
return Err(Failure::Usage);
|
||||||
|
};
|
||||||
|
let (flag_args, cmd_args) = (&args[..sep], &args[sep + 1..]);
|
||||||
|
let Some((&program, program_args)) = cmd_args.split_first() else {
|
||||||
|
return Err(Failure::Usage);
|
||||||
|
};
|
||||||
|
if program.is_empty() {
|
||||||
|
return Err(Failure::Usage);
|
||||||
|
}
|
||||||
|
let flags = Flags::parse(flag_args, &[&["--socket", "--ttl-secs"]], &[])?;
|
||||||
|
let socket = flags.path("--socket")?;
|
||||||
|
let ttl_secs: u64 = flags.number_or("--ttl-secs", DEFAULT_TTL_SECS)?;
|
||||||
|
if ttl_secs == 0 {
|
||||||
|
return Err(Failure::Malformed("--ttl-secs"));
|
||||||
|
}
|
||||||
|
let status = lease_run(&LeaseRunArgs {
|
||||||
|
socket,
|
||||||
|
ttl: Duration::from_secs(ttl_secs),
|
||||||
|
program: program.to_string(),
|
||||||
|
args: program_args.iter().map(|arg| (*arg).to_string()).collect(),
|
||||||
|
})?;
|
||||||
|
let code = status
|
||||||
|
.code()
|
||||||
|
.or_else(|| status.signal().map(|signal| 128 + signal))
|
||||||
|
.unwrap_or(1);
|
||||||
|
Ok(ExitCode::from(u8::try_from(code).unwrap_or(1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
fn run_lease(_: &[&str]) -> Result<ExitCode, Failure> {
|
||||||
|
Err(Failure::Usage)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(all(test, unix))]
|
#[cfg(all(test, unix))]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||||
|
|
|
||||||
522
crates/claude-connector/src/messages.rs
Normal file
522
crates/claude-connector/src/messages.rs
Normal file
|
|
@ -0,0 +1,522 @@
|
||||||
|
//! The Messages API backend: one non-streaming `POST /v1/messages` per call
|
||||||
|
//! against a configured `base_url` with an optional systemd API key credential
|
||||||
|
//! (omitted only for keyless loopback HTTP). 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`):
|
||||||
|
//! - Per-model `ModelRow` policies govern forced `tool_choice`
|
||||||
|
//! (`Always`, `WithoutThinking`, `Never`), `OutputSchemaSupport`, and
|
||||||
|
//! `EffortMap` / `unset_effort`. [`ToolChoice::Required`] is `tool_choice: any`
|
||||||
|
//! when permitted and a typed refusal before sending otherwise; the request's
|
||||||
|
//! `system` never depends on it. Thinking is `{"type":"adaptive"}` with
|
||||||
|
//! `output_config.effort`, and a request's output schema is
|
||||||
|
//! `output_config.format` (`json_schema`) when `OutputSchemaSupport::Native`.
|
||||||
|
//! - A thinking block is replayed unchanged when tagged with this entry's
|
||||||
|
//! `provider_id`, 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`.
|
||||||
|
//!
|
||||||
|
//! When configured, 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, ProviderRequest, StopReason, ToolChoice,
|
||||||
|
TransportEvent, TransportEventPayload, TransportOutcome, Usage,
|
||||||
|
};
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
|
||||||
|
use crate::config::{ModelRow, OutputSchemaSupport};
|
||||||
|
use crate::credential::{CredentialTokenSource, TokenSource, credential_ready};
|
||||||
|
use crate::http::{build_agent, failed, read_key, transport_failure, zero_usage};
|
||||||
|
|
||||||
|
const API_VERSION: &str = "2026-10-21";
|
||||||
|
const BACKEND_LABEL: &str = "anthropic-messages";
|
||||||
|
|
||||||
|
/// What the connector's binary hands the backend.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct MessagesConfig {
|
||||||
|
/// Provider tag written on receipts and matched on reasoning state items.
|
||||||
|
pub provider_id: String,
|
||||||
|
/// Base URL for the Messages API (`https://...` or loopback `http://...`).
|
||||||
|
pub base_url: String,
|
||||||
|
/// The name of the systemd credential that holds the API key, under
|
||||||
|
/// `$CREDENTIALS_DIRECTORY`; `None` only for a loopback HTTP `base_url`.
|
||||||
|
pub key_credential: Option<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 {
|
||||||
|
provider_id: String,
|
||||||
|
agent: ureq::Agent,
|
||||||
|
base_url: String,
|
||||||
|
keys: Option<Box<dyn TokenSource>>,
|
||||||
|
max_response_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MessagesBackend {
|
||||||
|
/// The backend over the configured base URL, with an optional key read from
|
||||||
|
/// the credential `config.key_credential` names.
|
||||||
|
pub fn new(config: MessagesConfig) -> Self {
|
||||||
|
let keys = config.key_credential.as_ref().map(|name| {
|
||||||
|
Box::new(CredentialTokenSource::from_environment(name.clone())) as Box<dyn TokenSource>
|
||||||
|
});
|
||||||
|
Self::with_parts(config, keys)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn with_parts(config: MessagesConfig, keys: Option<Box<dyn TokenSource>>) -> Self {
|
||||||
|
Self {
|
||||||
|
provider_id: config.provider_id,
|
||||||
|
agent: build_agent(config.deadline),
|
||||||
|
base_url: config.base_url,
|
||||||
|
keys,
|
||||||
|
max_response_bytes: config.max_response_bytes as u64,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn provider_id(&self) -> &str {
|
||||||
|
&self.provider_id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ready(&self) -> Result<(), &'static str> {
|
||||||
|
match &self.keys {
|
||||||
|
Some(source) => credential_ready(source.as_ref()),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn run_model(
|
||||||
|
&self,
|
||||||
|
request: &ProviderRequest,
|
||||||
|
row: &ModelRow,
|
||||||
|
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
let key = match read_key(self.keys.as_deref(), BACKEND_LABEL) {
|
||||||
|
Ok(key) => key,
|
||||||
|
Err(failure) => return failure,
|
||||||
|
};
|
||||||
|
let body = match render(request, &self.provider_id, row).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!("{BACKEND_LABEL}: {message}"),
|
||||||
|
Some(zero_usage()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut post = self
|
||||||
|
.agent
|
||||||
|
.post(format!("{}/v1/messages", self.base_url))
|
||||||
|
.header("anthropic-version", API_VERSION)
|
||||||
|
.header("content-type", "application/json");
|
||||||
|
if let Some(key) = &key {
|
||||||
|
post = post.header("x-api-key", key.as_str());
|
||||||
|
}
|
||||||
|
let sent = post.send(&body[..]);
|
||||||
|
let mut response = match sent {
|
||||||
|
Ok(response) => response,
|
||||||
|
Err(error) => return transport_failure(BACKEND_LABEL, &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(BACKEND_LABEL, &error),
|
||||||
|
};
|
||||||
|
if !(200..300).contains(&status) {
|
||||||
|
return crate::http::http_failure(
|
||||||
|
BACKEND_LABEL,
|
||||||
|
status,
|
||||||
|
&text,
|
||||||
|
key.as_deref().map(String::as_str),
|
||||||
|
spend_exhausted,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- request ----
|
||||||
|
|
||||||
|
/// The request body, or what is wrong with the request.
|
||||||
|
fn render(request: &ProviderRequest, provider_id: &str, row: &ModelRow) -> Result<Value, String> {
|
||||||
|
let effort = row.resolve_effort(request.reasoning_effort)?;
|
||||||
|
if request.tool_choice == ToolChoice::Required
|
||||||
|
&& !row.allows_forced_tool_choice(ModelRow::thinking_active(effort))
|
||||||
|
{
|
||||||
|
return Err(format!(
|
||||||
|
"model {} does not accept a required tool choice",
|
||||||
|
row.id
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut body = Map::new();
|
||||||
|
body.insert("model".into(), json!(request.model));
|
||||||
|
body.insert("max_tokens".into(), json!(request.max_output_tokens));
|
||||||
|
|
||||||
|
// Breakpoints, when caching is asked: after the tools, after the system
|
||||||
|
// prompt and on the last message (three of the API's four). The render
|
||||||
|
// order is tools, system, messages, and an entry is written only where a
|
||||||
|
// breakpoint sits, so the stable prefix is reused by a later turn whose
|
||||||
|
// messages differ.
|
||||||
|
let mark = request.cache_retention.map(cache_mark);
|
||||||
|
|
||||||
|
let mut system = json!({"type": "text", "text": request.instructions});
|
||||||
|
if let Some(mark) = &mark {
|
||||||
|
system["cache_control"] = mark.clone();
|
||||||
|
}
|
||||||
|
body.insert("system".into(), json!([system]));
|
||||||
|
|
||||||
|
let mut messages = messages_of(&request.input, provider_id)?;
|
||||||
|
if let Some(mark) = &mark {
|
||||||
|
mark_last_message(&mut messages, mark.clone());
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if let (Some(mark), Some(last)) = (&mark, tools.last_mut()) {
|
||||||
|
last["cache_control"] = mark.clone();
|
||||||
|
}
|
||||||
|
body.insert("tools".into(), Value::Array(tools));
|
||||||
|
let kind = if request.tool_choice == ToolChoice::Required {
|
||||||
|
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(level) = effort {
|
||||||
|
body.insert("thinking".into(), json!({"type": "adaptive"}));
|
||||||
|
output.insert("effort".into(), json!(level));
|
||||||
|
}
|
||||||
|
if let Some(schema) = &request.output_schema_json {
|
||||||
|
if row.output_schema == OutputSchemaSupport::None {
|
||||||
|
return Err(format!("model {} does not accept an output schema", row.id));
|
||||||
|
}
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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], provider_id: &str) -> 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, provider_id)?;
|
||||||
|
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, provider_id: &str) -> 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_id
|
||||||
|
&& 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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cache_mark(retention: CacheRetention) -> Value {
|
||||||
|
match retention {
|
||||||
|
CacheRetention::Short => json!({"type": "ephemeral"}),
|
||||||
|
CacheRetention::Long => json!({"type": "ephemeral", "ttl": "1h"}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the breakpoint on the last block of the last message that can carry
|
||||||
|
/// it (a thinking block cannot).
|
||||||
|
fn mark_last_message(messages: &mut [Value], mark: Value) {
|
||||||
|
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 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(status: u16, error: &Value) -> bool {
|
||||||
|
status == 400
|
||||||
|
&& 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))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
use crate::http::{MESSAGE_BYTES, bounded};
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn http_failure(status: u16, body: &[u8]) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
crate::http::http_failure(BACKEND_LABEL, status, body, None, spend_exhausted)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
1252
crates/claude-connector/src/messages/tests.rs
Normal file
1252
crates/claude-connector/src/messages/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,24 +1,23 @@
|
||||||
//! The meter: keeps the plan's weekly reading fresh while the swarm is
|
//! The meter: keeps the plan's weekly reading fresh while lease holders are
|
||||||
//! working. The subscription reports its windows only inside the CLI's
|
//! 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
|
//! `rate_limit_event`, on a call the CLI makes, and lease holders make theirs
|
||||||
//! leases that report nothing back. So when the `seven_day` reading in the
|
//! under leases that report nothing back. So when the `seven_day` reading in
|
||||||
//! [`QuotaCell`] is `STALE` old, the meter makes the smallest real call
|
//! 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
|
//! 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
|
//! 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
|
//! call. The meter holds no credential, speaks no protocol and writes nothing
|
||||||
//! itself.
|
//! itself.
|
||||||
//!
|
//!
|
||||||
//! The meter is driven by the connector's own lease state. It reads only
|
//! 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
|
//! while a lease is held or one was asked for less than `STALE` ago: an idle
|
||||||
//! swarm brake stops the units, they ask for nothing, and a braked or quiet
|
//! deployment asks for nothing, and idle lease holders spend nothing. A call
|
||||||
//! swarm spends nothing. A call that fails, or completes without refreshing
|
//! that fails, or completes without refreshing the reading, is not retried at
|
||||||
//! the reading, is not retried at the staleness period: the wait doubles per
|
//! the staleness period: the wait doubles per consecutive miss, up to `CEILING`.
|
||||||
//! consecutive miss, up to `CEILING`.
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use model_connector::Usage;
|
use model_connector::{PlanQuota, Usage};
|
||||||
|
|
||||||
use crate::backend::ClaudeCodeBackend;
|
use crate::backend::ClaudeCodeBackend;
|
||||||
use crate::quota::{EXPIRED, QuotaCell, WEEK};
|
use crate::quota::{EXPIRED, QuotaCell, WEEK};
|
||||||
|
|
@ -42,10 +41,16 @@ impl Probe for Arc<ClaudeCodeBackend> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why the meter is waiting; logged once per change.
|
/// 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)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
enum State {
|
enum State {
|
||||||
Read,
|
/// 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,
|
Idle,
|
||||||
/// The call failed; the kind is the failure's kind, never its message.
|
/// The call failed; the kind is the failure's kind, never its message.
|
||||||
Failed(String),
|
Failed(String),
|
||||||
|
|
@ -55,7 +60,15 @@ enum State {
|
||||||
impl State {
|
impl State {
|
||||||
fn line(&self) -> String {
|
fn line(&self) -> String {
|
||||||
match self {
|
match self {
|
||||||
Self::Read => "meter: weekly reading refreshed".to_string(),
|
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::Idle => "meter: no lease asked lately, making no call".to_string(),
|
||||||
Self::Failed(kind) => format!("meter: the call failed ({kind}), backing off"),
|
Self::Failed(kind) => format!("meter: the call failed ({kind}), backing off"),
|
||||||
Self::Unread => {
|
Self::Unread => {
|
||||||
|
|
@ -105,9 +118,12 @@ impl Meter {
|
||||||
// reports its windows and then errors. Only the cell says whether the
|
// reports its windows and then errors. Only the cell says whether the
|
||||||
// week was read.
|
// week was read.
|
||||||
let called = self.probe.call();
|
let called = self.probe.call();
|
||||||
let state = if self.refreshed_since(now_ms) {
|
let state = if let Some(week) = self.week_refreshed_since(now_ms) {
|
||||||
self.misses = 0;
|
self.misses = 0;
|
||||||
State::Read
|
State::Read {
|
||||||
|
permille: week.utilization_permille,
|
||||||
|
resets_at_unix_ms: week.resets_at_unix_ms,
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
self.misses = self.misses.saturating_add(1);
|
self.misses = self.misses.saturating_add(1);
|
||||||
match called {
|
match called {
|
||||||
|
|
@ -139,16 +155,18 @@ impl Meter {
|
||||||
stale_at.max(self.not_before_ms)
|
stale_at.max(self.not_before_ms)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn refreshed_since(&self, since_ms: u64) -> bool {
|
/// 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
|
self.cell
|
||||||
.snapshot()
|
.snapshot()
|
||||||
.windows
|
.windows
|
||||||
.iter()
|
.into_iter()
|
||||||
.any(|quota| quota.window == WEEK && quota.observed_at_unix_ms >= since_ms)
|
.find(|quota| quota.window == WEEK && quota.observed_at_unix_ms >= since_ms)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn report(&mut self, state: State) {
|
fn report(&mut self, state: State) {
|
||||||
if self.last_state.as_ref() != Some(&state) {
|
if matches!(state, State::Read { .. }) || self.last_state.as_ref() != Some(&state) {
|
||||||
(self.log)(&state.line());
|
(self.log)(&state.line());
|
||||||
self.last_state = Some(state);
|
self.last_state = Some(state);
|
||||||
}
|
}
|
||||||
|
|
@ -181,7 +199,8 @@ fn unix_ms() -> u64 {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the meter thread. It writes only through the calls it makes, and
|
/// Starts the meter thread. It writes only through the calls it makes, and
|
||||||
/// logs one line to stderr when its state changes. From here a lease asked of
|
/// 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.
|
/// a cell with no weekly reading waits for the meter's first read.
|
||||||
pub(crate) fn start(
|
pub(crate) fn start(
|
||||||
cell: Arc<QuotaCell>,
|
cell: Arc<QuotaCell>,
|
||||||
|
|
@ -202,7 +221,6 @@ pub(crate) fn start(
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::quota::Asking;
|
use crate::quota::Asking;
|
||||||
use model_connector::PlanQuota;
|
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
|
@ -227,6 +245,10 @@ mod tests {
|
||||||
reading_at: Option<u64>,
|
reading_at: Option<u64>,
|
||||||
status: String,
|
status: String,
|
||||||
fails_with: Option<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
|
/// A call that answers as scripted and feeds the cell the way the stream
|
||||||
|
|
@ -242,7 +264,10 @@ mod tests {
|
||||||
self.made.fetch_add(1, Ordering::SeqCst);
|
self.made.fetch_add(1, Ordering::SeqCst);
|
||||||
let script = self.script.lock().unwrap().clone();
|
let script = self.script.lock().unwrap().clone();
|
||||||
if let Some(at) = script.reading_at {
|
if let Some(at) = script.reading_at {
|
||||||
self.cell.observe_at(at, reading(&script.status));
|
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 {
|
if let Some(kind) = script.fails_with {
|
||||||
return Err(kind);
|
return Err(kind);
|
||||||
|
|
@ -263,7 +288,7 @@ mod tests {
|
||||||
made: Arc<AtomicUsize>,
|
made: Arc<AtomicUsize>,
|
||||||
script: Arc<Mutex<Script>>,
|
script: Arc<Mutex<Script>>,
|
||||||
log: Arc<Mutex<Vec<String>>>,
|
log: Arc<Mutex<Vec<String>>>,
|
||||||
/// The lease the swarm holds until a test lets go of it.
|
/// The lease held until a test lets go of it.
|
||||||
lease: Option<Asking>,
|
lease: Option<Asking>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -299,6 +324,7 @@ mod tests {
|
||||||
reading_at: Some(at),
|
reading_at: Some(at),
|
||||||
status: "allowed".to_string(),
|
status: "allowed".to_string(),
|
||||||
fails_with: None,
|
fails_with: None,
|
||||||
|
..Script::default()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
fn reads_nothing(&self) {
|
fn reads_nothing(&self) {
|
||||||
|
|
@ -355,7 +381,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_swarm_that_asks_for_nothing_spends_nothing_however_stale_the_reading() {
|
fn no_lease_requests_spends_nothing_however_stale_the_reading() {
|
||||||
let mut rig = rig();
|
let mut rig = rig();
|
||||||
drop(rig.lease.take());
|
drop(rig.lease.take());
|
||||||
for step in 0..10 {
|
for step in 0..10 {
|
||||||
|
|
@ -398,7 +424,11 @@ mod tests {
|
||||||
rig.reads(at);
|
rig.reads(at);
|
||||||
rig.meter.tick(at);
|
rig.meter.tick(at);
|
||||||
}
|
}
|
||||||
assert_eq!(rig.calls(), 17, "one read per period, the lease never lapsing");
|
assert_eq!(
|
||||||
|
rig.calls(),
|
||||||
|
17,
|
||||||
|
"one read per period, the lease never lapsing"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -477,10 +507,16 @@ mod tests {
|
||||||
reading_at: Some(NOW),
|
reading_at: Some(NOW),
|
||||||
status: "rejected".to_string(),
|
status: "rejected".to_string(),
|
||||||
fails_with: Some("RateLimited".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.tick(NOW), STALE, "the next read is a period away");
|
||||||
assert_eq!(rig.meter.misses, 0);
|
assert_eq!(rig.meter.misses, 0);
|
||||||
assert_eq!(rig.lines(), vec![State::Read.line()]);
|
assert_eq!(
|
||||||
|
rig.lines(),
|
||||||
|
vec![format!(
|
||||||
|
"meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}"
|
||||||
|
)]
|
||||||
|
);
|
||||||
rig.reads(NOW + 15 * MIN);
|
rig.reads(NOW + 15 * MIN);
|
||||||
rig.meter.tick(NOW + 15 * MIN);
|
rig.meter.tick(NOW + 15 * MIN);
|
||||||
assert_eq!(rig.calls(), 2, "a rejected reading is kept fresh");
|
assert_eq!(rig.calls(), 2, "a rejected reading is kept fresh");
|
||||||
|
|
@ -495,13 +531,83 @@ mod tests {
|
||||||
assert_eq!(rig.meter.misses, 1);
|
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]
|
#[test]
|
||||||
fn the_log_says_what_the_meter_is_doing_in_words() {
|
fn the_log_says_what_the_meter_is_doing_in_words() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
State::Idle.line(),
|
State::Idle.line(),
|
||||||
"meter: no lease asked lately, making no call"
|
"meter: no lease asked lately, making no call"
|
||||||
);
|
);
|
||||||
assert_eq!(State::Read.line(), "meter: weekly reading refreshed");
|
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!(
|
assert_eq!(
|
||||||
State::Unread.line(),
|
State::Unread.line(),
|
||||||
"meter: the call completed without a weekly reading, backing off"
|
"meter: the call completed without a weekly reading, backing off"
|
||||||
|
|
@ -527,6 +633,7 @@ mod tests {
|
||||||
reading_at: Some(unix_ms() + 60 * MIN),
|
reading_at: Some(unix_ms() + 60 * MIN),
|
||||||
status: "allowed".to_string(),
|
status: "allowed".to_string(),
|
||||||
fails_with: None,
|
fails_with: None,
|
||||||
|
..Script::default()
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
start(cell.clone(), Box::new(probe)).unwrap();
|
start(cell.clone(), Box::new(probe)).unwrap();
|
||||||
|
|
|
||||||
625
crates/claude-connector/src/openai_chat.rs
Normal file
625
crates/claude-connector/src/openai_chat.rs
Normal file
|
|
@ -0,0 +1,625 @@
|
||||||
|
//! The OpenAI-compatible Chat Completions backend: one non-streaming
|
||||||
|
//! `POST {base_url}/chat/completions` per call against a configured `base_url`
|
||||||
|
//! with an optional systemd API key credential (sent as `Authorization: Bearer`,
|
||||||
|
//! omitted only for keyless loopback HTTP).
|
||||||
|
//!
|
||||||
|
//! No vendor dialect enum lives here. Non-standard non-null fields on the
|
||||||
|
//! assistant message (such as DeepSeek `reasoning_content`) and on each tool
|
||||||
|
//! call (such as Gemini `extra_content.google.thought_signature`) are captured
|
||||||
|
//! generically into one opaque `ReasoningState` JSON object
|
||||||
|
//! `{"message":{...},"tool_calls":{call_id:{...}}}` and restored byte-exact on
|
||||||
|
//! replay onto the same assistant message and tool calls. Foreign provider
|
||||||
|
//! state is refused before sending.
|
||||||
|
//!
|
||||||
|
//! Per-model `ModelRow` policies govern `efforts` / `unset_effort`,
|
||||||
|
//! `forced_tool_choice` (using `ModelRow::thinking_active` so
|
||||||
|
//! `unset_effort: Some("none")` counts as thinking-inactive), `output_schema`,
|
||||||
|
//! and `strict_tools`.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use model_connector::{
|
||||||
|
FailureKind, InputItem, ProviderRequest, StopReason, ToolChoice, TransportEvent,
|
||||||
|
TransportEventPayload, TransportOutcome, Usage,
|
||||||
|
};
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
use crate::config::{ModelRow, OutputSchemaSupport};
|
||||||
|
use crate::credential::{CredentialTokenSource, TokenSource, credential_ready};
|
||||||
|
use crate::http::{build_agent, failed, http_failure, read_key, transport_failure, zero_usage};
|
||||||
|
|
||||||
|
const BACKEND_LABEL: &str = "openai-chat";
|
||||||
|
|
||||||
|
const STANDARD_MESSAGE_FIELDS: &[&str] = &[
|
||||||
|
"role",
|
||||||
|
"content",
|
||||||
|
"tool_calls",
|
||||||
|
"refusal",
|
||||||
|
"annotations",
|
||||||
|
"audio",
|
||||||
|
"function_call",
|
||||||
|
];
|
||||||
|
|
||||||
|
const STANDARD_TOOL_CALL_FIELDS: &[&str] = &["id", "type", "function", "index"];
|
||||||
|
|
||||||
|
/// What the connector's config hands the OpenAI-compatible backend.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct OpenAiChatConfig {
|
||||||
|
/// Provider tag written on receipts and matched on reasoning state items.
|
||||||
|
pub provider_id: String,
|
||||||
|
/// Base URL for the Chat Completions API (`https://...` or loopback `http://...`),
|
||||||
|
/// including any version path segment (e.g. `/v1` or `/v1beta/openai`).
|
||||||
|
pub base_url: String,
|
||||||
|
/// The name of the systemd credential that holds the bearer token, under
|
||||||
|
/// `$CREDENTIALS_DIRECTORY`; `None` only for a loopback HTTP `base_url`.
|
||||||
|
pub key_credential: Option<String>,
|
||||||
|
/// Schema keywords to strip-and-describe in strict tool mode (handled in Cut 4).
|
||||||
|
pub strict_unsupported: Vec<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 `POST {base_url}/chat/completions`.
|
||||||
|
pub struct OpenAiChatBackend {
|
||||||
|
provider_id: String,
|
||||||
|
agent: ureq::Agent,
|
||||||
|
endpoint: String,
|
||||||
|
keys: Option<Box<dyn TokenSource>>,
|
||||||
|
max_response_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OpenAiChatBackend {
|
||||||
|
/// The backend over the configured base URL, with an optional bearer token
|
||||||
|
/// read from the credential `config.key_credential` names.
|
||||||
|
pub fn new(config: OpenAiChatConfig) -> Self {
|
||||||
|
let keys = config.key_credential.as_ref().map(|name| {
|
||||||
|
Box::new(CredentialTokenSource::from_environment(name.clone())) as Box<dyn TokenSource>
|
||||||
|
});
|
||||||
|
Self::with_parts(config, keys)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn with_parts(config: OpenAiChatConfig, keys: Option<Box<dyn TokenSource>>) -> Self {
|
||||||
|
let endpoint = format!("{}/chat/completions", config.base_url.trim_end_matches('/'));
|
||||||
|
Self {
|
||||||
|
provider_id: config.provider_id,
|
||||||
|
agent: build_agent(config.deadline),
|
||||||
|
endpoint,
|
||||||
|
keys,
|
||||||
|
max_response_bytes: config.max_response_bytes as u64,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn provider_id(&self) -> &str {
|
||||||
|
&self.provider_id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ready(&self) -> Result<(), &'static str> {
|
||||||
|
match &self.keys {
|
||||||
|
Some(source) => credential_ready(source.as_ref()),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn run_model(
|
||||||
|
&self,
|
||||||
|
request: &ProviderRequest,
|
||||||
|
row: &ModelRow,
|
||||||
|
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||||
|
let key = match read_key(self.keys.as_deref(), BACKEND_LABEL) {
|
||||||
|
Ok(key) => key,
|
||||||
|
Err(failure) => return failure,
|
||||||
|
};
|
||||||
|
let body = match render(request, &self.provider_id, row).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!("{BACKEND_LABEL}: {message}"),
|
||||||
|
Some(zero_usage()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut post = self
|
||||||
|
.agent
|
||||||
|
.post(&self.endpoint)
|
||||||
|
.header("content-type", "application/json");
|
||||||
|
if let Some(key) = &key {
|
||||||
|
let bearer = Zeroizing::new(format!("Bearer {}", key.as_str()));
|
||||||
|
post = post.header("authorization", bearer.as_str());
|
||||||
|
}
|
||||||
|
let sent = post.send(&body[..]);
|
||||||
|
let mut response = match sent {
|
||||||
|
Ok(response) => response,
|
||||||
|
Err(error) => return transport_failure(BACKEND_LABEL, &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(BACKEND_LABEL, &error),
|
||||||
|
};
|
||||||
|
if !(200..300).contains(&status) {
|
||||||
|
return http_failure(
|
||||||
|
BACKEND_LABEL,
|
||||||
|
status,
|
||||||
|
&text,
|
||||||
|
key.as_deref().map(String::as_str),
|
||||||
|
spend_exhausted,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- request ----
|
||||||
|
|
||||||
|
/// Lowers `request` into a Chat Completions JSON body, or explains why the
|
||||||
|
/// request is refused before sending.
|
||||||
|
fn render(request: &ProviderRequest, provider_id: &str, row: &ModelRow) -> Result<Value, String> {
|
||||||
|
let effort = row.resolve_effort(request.reasoning_effort)?;
|
||||||
|
if request.tool_choice == ToolChoice::Required
|
||||||
|
&& !row.allows_forced_tool_choice(ModelRow::thinking_active(effort))
|
||||||
|
{
|
||||||
|
return Err(format!(
|
||||||
|
"model {} does not accept a required tool choice",
|
||||||
|
row.id
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if request.output_schema_json.is_some() && row.output_schema == OutputSchemaSupport::None {
|
||||||
|
return Err(format!("model {} does not accept an output schema", row.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut body = Map::new();
|
||||||
|
body.insert("model".into(), json!(request.model));
|
||||||
|
body.insert(
|
||||||
|
"max_completion_tokens".into(),
|
||||||
|
json!(request.max_output_tokens),
|
||||||
|
);
|
||||||
|
if let Some(level) = effort {
|
||||||
|
body.insert("reasoning_effort".into(), json!(level));
|
||||||
|
}
|
||||||
|
|
||||||
|
let messages = messages_of(&request.instructions, &request.input, provider_id)?;
|
||||||
|
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!({
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": tool.name,
|
||||||
|
"description": tool.description,
|
||||||
|
"parameters": schema,
|
||||||
|
"strict": row.strict_tools,
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
body.insert("tools".into(), Value::Array(tools));
|
||||||
|
body.insert(
|
||||||
|
"parallel_tool_calls".into(),
|
||||||
|
json!(request.parallel_tool_calls),
|
||||||
|
);
|
||||||
|
if request.tool_choice == ToolChoice::Required {
|
||||||
|
body.insert("tool_choice".into(), json!("required"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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())?;
|
||||||
|
body.insert(
|
||||||
|
"response_format".into(),
|
||||||
|
json!({
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "output_schema",
|
||||||
|
"schema": schema,
|
||||||
|
"strict": true,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Value::Object(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct AssistantTurn {
|
||||||
|
text: String,
|
||||||
|
tool_calls: Vec<Value>,
|
||||||
|
restored_message: Map<String, Value>,
|
||||||
|
restored_tool_calls: Map<String, Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AssistantTurn {
|
||||||
|
fn flush(mut self) -> Value {
|
||||||
|
let mut message = Map::new();
|
||||||
|
message.insert("role".into(), json!("assistant"));
|
||||||
|
message.insert(
|
||||||
|
"content".into(),
|
||||||
|
if self.text.is_empty() {
|
||||||
|
Value::Null
|
||||||
|
} else {
|
||||||
|
Value::String(self.text)
|
||||||
|
},
|
||||||
|
);
|
||||||
|
for (key, value) in self.restored_message {
|
||||||
|
if !matches!(key.as_str(), "role" | "content" | "tool_calls") {
|
||||||
|
message.insert(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !self.tool_calls.is_empty() {
|
||||||
|
for tool_call in &mut self.tool_calls {
|
||||||
|
let Some(call_id) = tool_call["id"].as_str() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Some(Value::Object(extra)) = self.restored_tool_calls.get(call_id)
|
||||||
|
&& let Some(obj) = tool_call.as_object_mut()
|
||||||
|
{
|
||||||
|
for (key, value) in extra {
|
||||||
|
if !matches!(key.as_str(), "id" | "type" | "function") {
|
||||||
|
obj.insert(key.clone(), value.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
message.insert("tool_calls".into(), Value::Array(self.tool_calls));
|
||||||
|
}
|
||||||
|
Value::Object(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn messages_of(
|
||||||
|
instructions: &str,
|
||||||
|
input: &[InputItem],
|
||||||
|
provider_id: &str,
|
||||||
|
) -> Result<Vec<Value>, String> {
|
||||||
|
let mut messages = Vec::with_capacity(input.len() + 1);
|
||||||
|
messages.push(json!({
|
||||||
|
"role": "system",
|
||||||
|
"content": instructions,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let mut open_assistant: Option<AssistantTurn> = None;
|
||||||
|
for item in input {
|
||||||
|
match item {
|
||||||
|
InputItem::UserText { text } => {
|
||||||
|
if let Some(turn) = open_assistant.take() {
|
||||||
|
messages.push(turn.flush());
|
||||||
|
}
|
||||||
|
messages.push(json!({
|
||||||
|
"role": "user",
|
||||||
|
"content": text,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
InputItem::ToolResult { call_id, output } => {
|
||||||
|
if let Some(turn) = open_assistant.take() {
|
||||||
|
messages.push(turn.flush());
|
||||||
|
}
|
||||||
|
messages.push(json!({
|
||||||
|
"role": "tool",
|
||||||
|
"tool_call_id": call_id,
|
||||||
|
"content": output,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
InputItem::AssistantText { text } => {
|
||||||
|
let turn = open_assistant.get_or_insert_with(AssistantTurn::default);
|
||||||
|
turn.text.push_str(text);
|
||||||
|
}
|
||||||
|
InputItem::ToolCall {
|
||||||
|
call_id,
|
||||||
|
name,
|
||||||
|
arguments,
|
||||||
|
} => {
|
||||||
|
let turn = open_assistant.get_or_insert_with(AssistantTurn::default);
|
||||||
|
turn.tool_calls.push(json!({
|
||||||
|
"id": call_id,
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": name,
|
||||||
|
"arguments": arguments,
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
InputItem::ReasoningState {
|
||||||
|
provider, state, ..
|
||||||
|
} => {
|
||||||
|
if provider != provider_id {
|
||||||
|
return Err("a reasoning state belongs to another provider".to_string());
|
||||||
|
}
|
||||||
|
let turn = open_assistant.get_or_insert_with(AssistantTurn::default);
|
||||||
|
apply_reasoning_state(turn, state)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(turn) = open_assistant {
|
||||||
|
messages.push(turn.flush());
|
||||||
|
}
|
||||||
|
Ok(messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_reasoning_state(turn: &mut AssistantTurn, state: &[u8]) -> Result<(), String> {
|
||||||
|
let parsed: Value = serde_json::from_slice(state)
|
||||||
|
.map_err(|_| "a reasoning state is not valid JSON".to_string())?;
|
||||||
|
let Some(obj) = parsed.as_object() else {
|
||||||
|
return Err("a reasoning state is not a JSON object".to_string());
|
||||||
|
};
|
||||||
|
let (Some(msg_fields), Some(tc_fields)) = (
|
||||||
|
obj.get("message").and_then(Value::as_object),
|
||||||
|
obj.get("tool_calls").and_then(Value::as_object),
|
||||||
|
) else {
|
||||||
|
return Err("a reasoning state is missing message or tool_calls maps".to_string());
|
||||||
|
};
|
||||||
|
for (key, value) in msg_fields {
|
||||||
|
turn.restored_message.insert(key.clone(), value.clone());
|
||||||
|
}
|
||||||
|
for (call_id, value) in tc_fields {
|
||||||
|
let Some(fields) = value.as_object() else {
|
||||||
|
return Err("a tool call reasoning state entry is not an object".to_string());
|
||||||
|
};
|
||||||
|
let entry = turn
|
||||||
|
.restored_tool_calls
|
||||||
|
.entry(call_id.clone())
|
||||||
|
.or_insert_with(|| Value::Object(Map::new()));
|
||||||
|
if let Some(existing) = entry.as_object_mut() {
|
||||||
|
for (k, v) in fields {
|
||||||
|
existing.insert(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 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!("{BACKEND_LABEL}: {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 choice = response["choices"]
|
||||||
|
.as_array()
|
||||||
|
.and_then(|choices| choices.first())
|
||||||
|
.ok_or_else(|| provider_failure("the response has no choices", usage.clone()))?;
|
||||||
|
|
||||||
|
let stop_reason = match choice["finish_reason"].as_str() {
|
||||||
|
Some("stop") => StopReason::EndTurn,
|
||||||
|
Some("tool_calls") => StopReason::ToolUse,
|
||||||
|
Some("length") => StopReason::MaxOutputTokens,
|
||||||
|
Some("content_filter") => StopReason::Refusal,
|
||||||
|
Some("insufficient_system_resource") => {
|
||||||
|
return Err(Failure {
|
||||||
|
kind: FailureKind::Unavailable,
|
||||||
|
message: format!("{BACKEND_LABEL}: insufficient system resource"),
|
||||||
|
usage,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Some("aborted") => return Err(provider_failure("the generation was aborted", usage)),
|
||||||
|
_ => {
|
||||||
|
return Err(provider_failure(
|
||||||
|
"the finish reason is not one this backend maps",
|
||||||
|
usage,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let message = choice["message"]
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| provider_failure("the response choice has no message", usage.clone()))?;
|
||||||
|
|
||||||
|
let mut payloads = Vec::new();
|
||||||
|
let mut captured_message = Map::new();
|
||||||
|
for (key, value) in message {
|
||||||
|
if !STANDARD_MESSAGE_FIELDS.contains(&key.as_str()) && !value.is_null() {
|
||||||
|
captured_message.insert(key.clone(), value.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(text) = message
|
||||||
|
.get("content")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.filter(|text| !text.is_empty())
|
||||||
|
{
|
||||||
|
payloads.push(TransportEventPayload::TextDelta {
|
||||||
|
text: text.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut captured_tool_calls = Map::new();
|
||||||
|
let mut has_tool_call = false;
|
||||||
|
if let Some(tool_calls_val) = message.get("tool_calls").filter(|v| !v.is_null()) {
|
||||||
|
let Some(tool_calls) = tool_calls_val.as_array() else {
|
||||||
|
return Err(provider_failure("tool_calls is not an array", usage));
|
||||||
|
};
|
||||||
|
for tool_call in tool_calls {
|
||||||
|
let Some(tc_obj) = tool_call.as_object() else {
|
||||||
|
return Err(provider_failure("a tool call is not an object", usage));
|
||||||
|
};
|
||||||
|
let Some(id) = tc_obj
|
||||||
|
.get("id")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.filter(|id| !id.is_empty())
|
||||||
|
else {
|
||||||
|
return Err(provider_failure("a tool call has no id", usage));
|
||||||
|
};
|
||||||
|
let Some(function) = tc_obj.get("function").and_then(Value::as_object) else {
|
||||||
|
return Err(provider_failure("a tool call has no function", usage));
|
||||||
|
};
|
||||||
|
let Some(name) = function
|
||||||
|
.get("name")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.filter(|name| !name.is_empty())
|
||||||
|
else {
|
||||||
|
return Err(provider_failure("a tool call has no function name", usage));
|
||||||
|
};
|
||||||
|
let Some(arguments) = function
|
||||||
|
.get("arguments")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.filter(|args| !args.is_empty())
|
||||||
|
else {
|
||||||
|
return Err(provider_failure(
|
||||||
|
"a tool call has missing or empty arguments",
|
||||||
|
usage,
|
||||||
|
));
|
||||||
|
};
|
||||||
|
has_tool_call = true;
|
||||||
|
payloads.push(TransportEventPayload::ToolCall {
|
||||||
|
call_id: id.to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
arguments: arguments.to_string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut tc_extra = Map::new();
|
||||||
|
for (key, value) in tc_obj {
|
||||||
|
if !STANDARD_TOOL_CALL_FIELDS.contains(&key.as_str()) && !value.is_null() {
|
||||||
|
tc_extra.insert(key.clone(), value.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !tc_extra.is_empty() {
|
||||||
|
captured_tool_calls.insert(id.to_string(), Value::Object(tc_extra));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !captured_message.is_empty() || !captured_tool_calls.is_empty() {
|
||||||
|
let state = serde_json::to_vec(&json!({
|
||||||
|
"message": captured_message,
|
||||||
|
"tool_calls": captured_tool_calls,
|
||||||
|
}))
|
||||||
|
.unwrap_or_default();
|
||||||
|
payloads.push(TransportEventPayload::ReasoningState { state });
|
||||||
|
}
|
||||||
|
|
||||||
|
if required && !has_tool_call {
|
||||||
|
return Err(provider_failure("a required tool call did not come", 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 prompt_tokens = usage["prompt_tokens"].as_u64().unwrap_or(0);
|
||||||
|
let cache_read_tokens = usage["prompt_tokens_details"]["cached_tokens"]
|
||||||
|
.as_u64()
|
||||||
|
.or_else(|| usage["prompt_cache_hit_tokens"].as_u64())
|
||||||
|
.unwrap_or(0);
|
||||||
|
Usage {
|
||||||
|
input_tokens: prompt_tokens.saturating_sub(cache_read_tokens),
|
||||||
|
cache_read_tokens,
|
||||||
|
cache_write_tokens: 0,
|
||||||
|
output_tokens: usage["completion_tokens"].as_u64().unwrap_or(0),
|
||||||
|
reasoning_tokens: usage["completion_tokens_details"]["reasoning_tokens"].as_u64(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- failures ----
|
||||||
|
|
||||||
|
const SPENT_BALANCE_TYPES_OR_CODES: &[&str] = &[
|
||||||
|
"insufficient_balance",
|
||||||
|
"insufficient_quota",
|
||||||
|
"billing_hard_limit_reached",
|
||||||
|
];
|
||||||
|
|
||||||
|
const SPENT_BALANCE_PREFIXES: &[&str] = &[
|
||||||
|
"insufficient balance",
|
||||||
|
"your credit balance is too low",
|
||||||
|
"you have reached your specified api usage limits",
|
||||||
|
"you exceeded your current quota",
|
||||||
|
"insufficient quota",
|
||||||
|
"billing hard limit",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn spend_exhausted(status: u16, error: &Value) -> bool {
|
||||||
|
let tag_matches = |tag: Option<&str>, allowed: &[&str]| {
|
||||||
|
tag.is_some_and(|v| {
|
||||||
|
let lowered = v.trim().to_ascii_lowercase();
|
||||||
|
allowed.iter().any(|candidate| lowered == *candidate)
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let msg_starts_with = |prefixes: &[&str]| {
|
||||||
|
error["message"].as_str().is_some_and(|text| {
|
||||||
|
let lowered = text.trim_start().to_ascii_lowercase();
|
||||||
|
prefixes.iter().any(|prefix| lowered.starts_with(prefix))
|
||||||
|
})
|
||||||
|
};
|
||||||
|
match status {
|
||||||
|
400 => {
|
||||||
|
tag_matches(error["type"].as_str(), SPENT_BALANCE_TYPES_OR_CODES)
|
||||||
|
|| tag_matches(error["code"].as_str(), SPENT_BALANCE_TYPES_OR_CODES)
|
||||||
|
|| msg_starts_with(SPENT_BALANCE_PREFIXES)
|
||||||
|
}
|
||||||
|
429 => {
|
||||||
|
tag_matches(error["type"].as_str(), &["insufficient_quota"])
|
||||||
|
|| tag_matches(error["code"].as_str(), &["insufficient_quota"])
|
||||||
|
|| msg_starts_with(&[
|
||||||
|
"you exceeded your current quota",
|
||||||
|
"insufficient quota",
|
||||||
|
"insufficient_quota",
|
||||||
|
])
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
1083
crates/claude-connector/src/openai_chat/tests.rs
Normal file
1083
crates/claude-connector/src/openai_chat/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -46,6 +46,8 @@ pub trait RunningChild: Send {
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub use unix::StdProcessPort;
|
pub use unix::StdProcessPort;
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) use unix::place_fd;
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
mod unix {
|
mod unix {
|
||||||
|
|
@ -77,7 +79,7 @@ mod unix {
|
||||||
|
|
||||||
/// Makes `source` also descriptor `target`, open across exec. Runs between
|
/// Makes `source` also descriptor `target`, open across exec. Runs between
|
||||||
/// fork and exec in the child, so it calls nothing but `dup2` and `fcntl`.
|
/// fork and exec in the child, so it calls nothing but `dup2` and `fcntl`.
|
||||||
fn place_fd(source: RawFd, target: RawFd) -> io::Result<()> {
|
pub(crate) fn place_fd(source: RawFd, target: RawFd) -> io::Result<()> {
|
||||||
// SAFETY: dup2 and fcntl take integers only and are async-signal-safe.
|
// SAFETY: dup2 and fcntl take integers only and are async-signal-safe.
|
||||||
unsafe {
|
unsafe {
|
||||||
if source == target {
|
if source == target {
|
||||||
|
|
|
||||||
|
|
@ -25,9 +25,8 @@ const FIRST_READ_POLL: Duration = Duration::from_millis(50);
|
||||||
/// 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
|
/// It also keeps who is asking: a lease request is the connector's sign that a
|
||||||
/// life the connector sees, and the meter reads the plan only while someone
|
/// holder is active, and the meter reads the plan only while someone asks.
|
||||||
/// asks.
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct QuotaCell {
|
pub struct QuotaCell {
|
||||||
windows: Mutex<BTreeMap<String, PlanQuota>>,
|
windows: Mutex<BTreeMap<String, PlanQuota>>,
|
||||||
|
|
@ -155,7 +154,7 @@ 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.windows.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
|
||||||
|
|
|
||||||
764
crates/claude-connector/src/router.rs
Normal file
764
crates/claude-connector/src/router.rs
Normal file
|
|
@ -0,0 +1,764 @@
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use model_connector::{
|
||||||
|
FailureKind, PlanQuotaSnapshot, ProviderBackend, ProviderCall, TransportOutcome,
|
||||||
|
TransportResult,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::backend::ClaudeCodeBackend;
|
||||||
|
#[cfg(unix)]
|
||||||
|
use crate::backend::StderrSink;
|
||||||
|
use crate::config::ModelRow;
|
||||||
|
#[cfg(unix)]
|
||||||
|
use crate::config::ProviderWire;
|
||||||
|
use crate::daemon::ConfigError;
|
||||||
|
#[cfg(unix)]
|
||||||
|
use crate::daemon::{
|
||||||
|
ClaudeConnectorConfig, backend_config_for, messages_config_for, openai_chat_config_for,
|
||||||
|
};
|
||||||
|
use crate::messages::MessagesBackend;
|
||||||
|
use crate::openai_chat::OpenAiChatBackend;
|
||||||
|
|
||||||
|
enum RouteBackend {
|
||||||
|
Messages(MessagesBackend),
|
||||||
|
OpenAiChat(OpenAiChatBackend),
|
||||||
|
Cli(Arc<ClaudeCodeBackend>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The connector's sole [`ProviderBackend`]: dispatches each call by
|
||||||
|
/// [`ModelRow`], rewrites `wire_request.model` to `row.upstream` on the wire,
|
||||||
|
/// and leaves caller-facing `model` and `entry.id` on receipts.
|
||||||
|
pub struct RouterBackend {
|
||||||
|
providers: BTreeMap<String, RouteBackend>,
|
||||||
|
models: BTreeMap<String, ModelRow>,
|
||||||
|
cli: Option<Arc<ClaudeCodeBackend>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RouterBackend {
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) fn from_config(
|
||||||
|
config: &ClaudeConnectorConfig,
|
||||||
|
cli_sink: Box<dyn StderrSink>,
|
||||||
|
) -> Result<Self, ConfigError> {
|
||||||
|
config.validate()?;
|
||||||
|
let mut cli_sink = Some(cli_sink);
|
||||||
|
let mut messages = Vec::new();
|
||||||
|
let mut openai_chats = Vec::new();
|
||||||
|
let mut cli = None;
|
||||||
|
for entry in &config.providers {
|
||||||
|
match &entry.wire {
|
||||||
|
ProviderWire::AnthropicMessages { .. } => {
|
||||||
|
let cfg =
|
||||||
|
messages_config_for(entry).ok_or(ConfigError::Unusable("providers"))?;
|
||||||
|
let backend = MessagesBackend::new(cfg);
|
||||||
|
if backend.provider_id() != entry.id {
|
||||||
|
return Err(ConfigError::Invalid("providers"));
|
||||||
|
}
|
||||||
|
messages.push(backend);
|
||||||
|
}
|
||||||
|
ProviderWire::ClaudeCodeCli { .. } => {
|
||||||
|
let sink = cli_sink.take().ok_or(ConfigError::Invalid("providers"))?;
|
||||||
|
let cfg = backend_config_for(entry, &config.models)
|
||||||
|
.ok_or(ConfigError::Unusable("providers"))?;
|
||||||
|
let backend = Arc::new(ClaudeCodeBackend::new(cfg, sink));
|
||||||
|
if backend.provider_id() != entry.id {
|
||||||
|
return Err(ConfigError::Invalid("providers"));
|
||||||
|
}
|
||||||
|
cli = Some(backend);
|
||||||
|
}
|
||||||
|
ProviderWire::OpenAiChat { .. } => {
|
||||||
|
let cfg =
|
||||||
|
openai_chat_config_for(entry).ok_or(ConfigError::Unusable("providers"))?;
|
||||||
|
let backend = OpenAiChatBackend::new(cfg);
|
||||||
|
if backend.provider_id() != entry.id {
|
||||||
|
return Err(ConfigError::Invalid("providers"));
|
||||||
|
}
|
||||||
|
openai_chats.push(backend);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Self::from_backends(messages, openai_chats, cli, config.models.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_backends(
|
||||||
|
messages: impl IntoIterator<Item = MessagesBackend>,
|
||||||
|
openai_chats: impl IntoIterator<Item = OpenAiChatBackend>,
|
||||||
|
cli: Option<Arc<ClaudeCodeBackend>>,
|
||||||
|
models: Vec<ModelRow>,
|
||||||
|
) -> Result<Self, ConfigError> {
|
||||||
|
let mut providers = BTreeMap::new();
|
||||||
|
for backend in messages {
|
||||||
|
let id = backend.provider_id();
|
||||||
|
if id.is_empty()
|
||||||
|
|| id.trim() != id
|
||||||
|
|| providers
|
||||||
|
.insert(id.to_string(), RouteBackend::Messages(backend))
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid("providers"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for backend in openai_chats {
|
||||||
|
let id = backend.provider_id();
|
||||||
|
if id.is_empty()
|
||||||
|
|| id.trim() != id
|
||||||
|
|| providers
|
||||||
|
.insert(id.to_string(), RouteBackend::OpenAiChat(backend))
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid("providers"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(cli_backend) = &cli {
|
||||||
|
let id = cli_backend.provider_id();
|
||||||
|
if id.is_empty()
|
||||||
|
|| id.trim() != id
|
||||||
|
|| providers
|
||||||
|
.insert(id.to_string(), RouteBackend::Cli(cli_backend.clone()))
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid("providers"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if models.is_empty() {
|
||||||
|
return Err(ConfigError::Invalid("models"));
|
||||||
|
}
|
||||||
|
let mut model_map = BTreeMap::new();
|
||||||
|
for row in models {
|
||||||
|
if !providers.contains_key(&row.provider) {
|
||||||
|
return Err(ConfigError::Invalid("model_provider"));
|
||||||
|
}
|
||||||
|
if model_map.insert(row.id.clone(), row).is_some() {
|
||||||
|
return Err(ConfigError::Invalid("models"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
providers,
|
||||||
|
models: model_map,
|
||||||
|
cli,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cli_backend(&self) -> Option<&Arc<ClaudeCodeBackend>> {
|
||||||
|
self.cli.as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProviderBackend for RouterBackend {
|
||||||
|
fn ready(&self) -> Result<(), &'static str> {
|
||||||
|
for backend in self.providers.values() {
|
||||||
|
match backend {
|
||||||
|
RouteBackend::Messages(messages) => messages.ready()?,
|
||||||
|
RouteBackend::OpenAiChat(openai) => openai.ready()?,
|
||||||
|
RouteBackend::Cli(cli) => cli.ready()?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> {
|
||||||
|
self.cli.as_deref().map(ClaudeCodeBackend::plan_quota)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
|
let caller_request = call.request();
|
||||||
|
let Some(row) = self.models.get(&caller_request.model) else {
|
||||||
|
return call.transported(
|
||||||
|
Vec::new(),
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::InvalidRequest,
|
||||||
|
message: "router: unknown model".to_string(),
|
||||||
|
usage: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let Some(backend) = self.providers.get(&row.provider) else {
|
||||||
|
return call.transported(
|
||||||
|
Vec::new(),
|
||||||
|
TransportOutcome::Failed {
|
||||||
|
kind: FailureKind::Provider,
|
||||||
|
message: "router: missing provider".to_string(),
|
||||||
|
usage: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let mut wire_request = caller_request.clone();
|
||||||
|
wire_request.model = row.upstream.clone();
|
||||||
|
let (events, outcome) = match backend {
|
||||||
|
RouteBackend::Messages(messages) => messages.run_model(&wire_request, row),
|
||||||
|
RouteBackend::OpenAiChat(openai) => openai.run_model(&wire_request, row),
|
||||||
|
RouteBackend::Cli(cli) => cli.run_model(&wire_request, call.caller_runtime_id(), row),
|
||||||
|
};
|
||||||
|
call.transported(events, outcome)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use model_connector::{
|
||||||
|
CallerAdmission, ProviderBackend, ProviderRequest, ProviderRoutes, TransportAdmission,
|
||||||
|
TransportDisposition, TransportInvocation, TransportKey, TransportService, decrypt_result,
|
||||||
|
encrypt_invocation,
|
||||||
|
};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::config::{EffortMap, ForcedToolChoice, OutputSchemaSupport};
|
||||||
|
use crate::credential::TokenSource;
|
||||||
|
use crate::messages::MessagesConfig;
|
||||||
|
use crate::openai_chat::OpenAiChatConfig;
|
||||||
|
|
||||||
|
struct FixedKey(&'static str);
|
||||||
|
impl TokenSource for FixedKey {
|
||||||
|
fn read(&self) -> Option<Zeroizing<String>> {
|
||||||
|
Some(Zeroizing::new(self.0.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MissingKey;
|
||||||
|
impl TokenSource for MissingKey {
|
||||||
|
fn read(&self) -> Option<Zeroizing<String>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn msg_backend(id: &str, url: &str, key: Option<Box<dyn TokenSource>>) -> MessagesBackend {
|
||||||
|
MessagesBackend::with_parts(
|
||||||
|
MessagesConfig {
|
||||||
|
provider_id: id.to_string(),
|
||||||
|
base_url: url.to_string(),
|
||||||
|
key_credential: key.as_ref().map(|_| format!("{id}-cred")),
|
||||||
|
deadline: Duration::from_secs(5),
|
||||||
|
max_response_bytes: 1 << 20,
|
||||||
|
},
|
||||||
|
key,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn oai_backend(id: &str, url: &str, key: Option<Box<dyn TokenSource>>) -> OpenAiChatBackend {
|
||||||
|
OpenAiChatBackend::with_parts(
|
||||||
|
OpenAiChatConfig {
|
||||||
|
provider_id: id.to_string(),
|
||||||
|
base_url: url.to_string(),
|
||||||
|
key_credential: key.as_ref().map(|_| format!("{id}-cred")),
|
||||||
|
strict_unsupported: Vec::new(),
|
||||||
|
deadline: Duration::from_secs(5),
|
||||||
|
max_response_bytes: 1 << 20,
|
||||||
|
},
|
||||||
|
key,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row(id: &str, provider: &str, upstream: &str) -> ModelRow {
|
||||||
|
ModelRow {
|
||||||
|
id: id.to_string(),
|
||||||
|
provider: provider.to_string(),
|
||||||
|
upstream: upstream.to_string(),
|
||||||
|
efforts: EffortMap::default(),
|
||||||
|
unset_effort: None,
|
||||||
|
forced_tool_choice: ForcedToolChoice::Never,
|
||||||
|
output_schema: OutputSchemaSupport::Native,
|
||||||
|
strict_tools: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_backends_validates_providers_models_and_readiness() {
|
||||||
|
let ok = msg_backend("entry-a", "http://127.0.0.1:9", None);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends([ok], [], None, vec![]),
|
||||||
|
Err(ConfigError::Invalid("models"))
|
||||||
|
));
|
||||||
|
|
||||||
|
let dup_a = msg_backend("entry-a", "http://127.0.0.1:9", None);
|
||||||
|
let dup_b = msg_backend("entry-a", "http://127.0.0.1:10", None);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends(
|
||||||
|
[dup_a, dup_b],
|
||||||
|
[],
|
||||||
|
None,
|
||||||
|
vec![row("m1", "entry-a", "u1")]
|
||||||
|
),
|
||||||
|
Err(ConfigError::Invalid("providers"))
|
||||||
|
));
|
||||||
|
|
||||||
|
let untrimmed_msg = msg_backend(" entry-a", "http://127.0.0.1:9", None);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends(
|
||||||
|
[untrimmed_msg],
|
||||||
|
[],
|
||||||
|
None,
|
||||||
|
vec![row("m1", "entry-a", "u1")]
|
||||||
|
),
|
||||||
|
Err(ConfigError::Invalid("providers"))
|
||||||
|
));
|
||||||
|
|
||||||
|
let untrimmed_oai = oai_backend("entry-oai ", "http://127.0.0.1:9", None);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends(
|
||||||
|
[],
|
||||||
|
[untrimmed_oai],
|
||||||
|
None,
|
||||||
|
vec![row("m1", "entry-oai", "u1")]
|
||||||
|
),
|
||||||
|
Err(ConfigError::Invalid("providers"))
|
||||||
|
));
|
||||||
|
|
||||||
|
let dup_cross_msg = msg_backend("shared-id", "http://127.0.0.1:9", None);
|
||||||
|
let dup_cross_oai = oai_backend("shared-id", "http://127.0.0.1:10", None);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends(
|
||||||
|
[dup_cross_msg],
|
||||||
|
[dup_cross_oai],
|
||||||
|
None,
|
||||||
|
vec![row("m1", "shared-id", "u1")]
|
||||||
|
),
|
||||||
|
Err(ConfigError::Invalid("providers"))
|
||||||
|
));
|
||||||
|
|
||||||
|
let ok = msg_backend("entry-a", "http://127.0.0.1:9", None);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends([ok], [], None, vec![row("m1", "unknown-entry", "u1")]),
|
||||||
|
Err(ConfigError::Invalid("model_provider"))
|
||||||
|
));
|
||||||
|
|
||||||
|
let ok = msg_backend("entry-a", "http://127.0.0.1:9", None);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends(
|
||||||
|
[ok],
|
||||||
|
[],
|
||||||
|
None,
|
||||||
|
vec![row("m1", "entry-a", "u1"), row("m1", "entry-a", "u2")]
|
||||||
|
),
|
||||||
|
Err(ConfigError::Invalid("models"))
|
||||||
|
));
|
||||||
|
|
||||||
|
let failing = msg_backend(
|
||||||
|
"entry-b",
|
||||||
|
"https://example.test",
|
||||||
|
Some(Box::new(MissingKey)),
|
||||||
|
);
|
||||||
|
let ready = msg_backend(
|
||||||
|
"entry-a",
|
||||||
|
"https://example.test",
|
||||||
|
Some(Box::new(FixedKey("k"))),
|
||||||
|
);
|
||||||
|
let oai_ready = oai_backend(
|
||||||
|
"entry-oai",
|
||||||
|
"https://oai.example.test/v1",
|
||||||
|
Some(Box::new(FixedKey("k2"))),
|
||||||
|
);
|
||||||
|
let router = RouterBackend::from_backends(
|
||||||
|
[ready, failing],
|
||||||
|
[oai_ready],
|
||||||
|
None,
|
||||||
|
vec![
|
||||||
|
row("m1", "entry-a", "u1"),
|
||||||
|
row("m2", "entry-b", "u2"),
|
||||||
|
row("m3", "entry-oai", "u3"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(router.ready(), Err("token_credential"));
|
||||||
|
assert!(router.plan_quota().is_none());
|
||||||
|
assert!(router.cli_backend().is_none());
|
||||||
|
|
||||||
|
let oai_failing = oai_backend(
|
||||||
|
"entry-oai-missing",
|
||||||
|
"https://oai.example.test/v1",
|
||||||
|
Some(Box::new(MissingKey)),
|
||||||
|
);
|
||||||
|
let oai_router = RouterBackend::from_backends(
|
||||||
|
[],
|
||||||
|
[oai_failing],
|
||||||
|
None,
|
||||||
|
vec![row("m1", "entry-oai-missing", "u1")],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(oai_router.ready(), Err("token_credential"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn execute_rewrites_upstream_and_keeps_caller_model_and_entry_id_on_receipt() {
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
let seen_body = Arc::new(Mutex::new(None::<serde_json::Value>));
|
||||||
|
let seen_clone = seen_body.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let mut chunk = [0u8; 4096];
|
||||||
|
let mut header_end = None;
|
||||||
|
let mut content_len = 0usize;
|
||||||
|
loop {
|
||||||
|
let n = stream.read(&mut chunk).unwrap_or(0);
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buf.extend_from_slice(&chunk[..n]);
|
||||||
|
if header_end.is_none()
|
||||||
|
&& let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n")
|
||||||
|
{
|
||||||
|
let end = pos + 4;
|
||||||
|
header_end = Some(end);
|
||||||
|
let headers = String::from_utf8_lossy(&buf[..pos]);
|
||||||
|
for line in headers.lines().skip(1) {
|
||||||
|
if let Some((k, v)) = line.split_once(':')
|
||||||
|
&& k.eq_ignore_ascii_case("content-length")
|
||||||
|
{
|
||||||
|
content_len = v.trim().parse().unwrap_or(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(end) = header_end
|
||||||
|
&& buf.len() >= end + content_len
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let end = header_end.unwrap_or(buf.len());
|
||||||
|
*seen_clone.lock().unwrap() =
|
||||||
|
Some(serde_json::from_slice(&buf[end..end + content_len]).unwrap());
|
||||||
|
let resp = serde_json::json!({
|
||||||
|
"id": "msg_router_1",
|
||||||
|
"content": [{"type": "text", "text": "ok"}],
|
||||||
|
"stop_reason": "end_turn",
|
||||||
|
"usage": {"input_tokens": 2, "output_tokens": 1}
|
||||||
|
})
|
||||||
|
.to_string();
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
|
||||||
|
resp.len(),
|
||||||
|
resp
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let backend = msg_backend(
|
||||||
|
"custom-entry",
|
||||||
|
&format!("http://{addr}"),
|
||||||
|
Some(Box::new(FixedKey("secret-k"))),
|
||||||
|
);
|
||||||
|
let router = RouterBackend::from_backends(
|
||||||
|
[backend],
|
||||||
|
[],
|
||||||
|
None,
|
||||||
|
vec![row("caller-alias", "custom-entry", "wire-upstream-name")],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let dir = std::env::temp_dir().join(format!("router-test-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let admission = CallerAdmission::new(
|
||||||
|
"caller-1",
|
||||||
|
"caller-1-secret-0123456789abcdef0123456789",
|
||||||
|
1,
|
||||||
|
["caller-alias".to_string()],
|
||||||
|
2,
|
||||||
|
1 << 20,
|
||||||
|
4_096,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let routes =
|
||||||
|
ProviderRoutes::new([("caller-alias".to_string(), "custom-entry".to_string())])
|
||||||
|
.unwrap();
|
||||||
|
let mut service =
|
||||||
|
TransportService::open(&dir.join("replay.cc"), routes, [admission], 5_000).unwrap();
|
||||||
|
let key =
|
||||||
|
TransportKey::from_connection_secret("caller-1-secret-0123456789abcdef0123456789")
|
||||||
|
.unwrap();
|
||||||
|
let mut req = ProviderRequest::new("r1", "c1", "caller-alias", "Be brief.", 128);
|
||||||
|
req.input = vec![model_connector::InputItem::UserText {
|
||||||
|
text: "hi".to_string(),
|
||||||
|
}];
|
||||||
|
let inv = TransportInvocation::new("caller-1", 2_000, [9; 32], req).unwrap();
|
||||||
|
let env = encrypt_invocation(&inv, &key).unwrap();
|
||||||
|
let TransportAdmission::Execute(claim) = service.begin(&env, 1_000, None, 1 << 20).unwrap()
|
||||||
|
else {
|
||||||
|
panic!("expected execute");
|
||||||
|
};
|
||||||
|
let result = router.execute(claim.call());
|
||||||
|
let sealed = service.complete(*claim, result, 1 << 20).unwrap();
|
||||||
|
let opened = decrypt_result(&sealed, &key, &inv).unwrap();
|
||||||
|
let TransportDisposition::Transported { receipt, .. } = opened.disposition else {
|
||||||
|
panic!("expected transported");
|
||||||
|
};
|
||||||
|
assert_eq!(receipt.provider, "custom-entry");
|
||||||
|
assert_eq!(receipt.model, "caller-alias");
|
||||||
|
assert_eq!(
|
||||||
|
seen_body.lock().unwrap().as_ref().unwrap()["model"],
|
||||||
|
"wire-upstream-name"
|
||||||
|
);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn from_config_accepts_and_routes_openai_chat_through_service() {
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
let seen = Arc::new(Mutex::new(Vec::<(String, serde_json::Value)>::new()));
|
||||||
|
let seen_clone = seen.clone();
|
||||||
|
let responses = vec![
|
||||||
|
serde_json::json!({
|
||||||
|
"id": "oai_resp_1",
|
||||||
|
"choices": [{
|
||||||
|
"index": 0,
|
||||||
|
"message": {
|
||||||
|
"role": "assistant",
|
||||||
|
"content": null,
|
||||||
|
"reasoning_content": "thought line",
|
||||||
|
"tool_calls": [{
|
||||||
|
"id": "call_r1",
|
||||||
|
"type": "function",
|
||||||
|
"function": {"name": "ping", "arguments": "{\"x\":1}"},
|
||||||
|
"extra_content": {"google": {"thought_signature": "sig-router"}}
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
"finish_reason": "tool_calls"
|
||||||
|
}],
|
||||||
|
"usage": {"prompt_tokens": 10, "completion_tokens": 5}
|
||||||
|
}),
|
||||||
|
serde_json::json!({
|
||||||
|
"id": "oai_resp_2",
|
||||||
|
"choices": [{
|
||||||
|
"index": 0,
|
||||||
|
"message": {"role": "assistant", "content": "done"},
|
||||||
|
"finish_reason": "stop"
|
||||||
|
}],
|
||||||
|
"usage": {"prompt_tokens": 20, "completion_tokens": 3}
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
for resp in responses {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let mut chunk = [0u8; 4096];
|
||||||
|
let mut header_end = None;
|
||||||
|
let mut content_len = 0usize;
|
||||||
|
loop {
|
||||||
|
let n = stream.read(&mut chunk).unwrap_or(0);
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buf.extend_from_slice(&chunk[..n]);
|
||||||
|
if header_end.is_none()
|
||||||
|
&& let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n")
|
||||||
|
{
|
||||||
|
let end = pos + 4;
|
||||||
|
header_end = Some(end);
|
||||||
|
let headers = String::from_utf8_lossy(&buf[..pos]);
|
||||||
|
for line in headers.lines().skip(1) {
|
||||||
|
if let Some((k, v)) = line.split_once(':')
|
||||||
|
&& k.eq_ignore_ascii_case("content-length")
|
||||||
|
{
|
||||||
|
content_len = v.trim().parse().unwrap_or(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(end) = header_end
|
||||||
|
&& buf.len() >= end + content_len
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let end = header_end.unwrap_or(buf.len());
|
||||||
|
let path = String::from_utf8_lossy(&buf[..end])
|
||||||
|
.lines()
|
||||||
|
.next()
|
||||||
|
.and_then(|l| l.split_whitespace().nth(1))
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
let body: serde_json::Value =
|
||||||
|
serde_json::from_slice(&buf[end..end + content_len]).unwrap();
|
||||||
|
seen_clone.lock().unwrap().push((path, body));
|
||||||
|
let payload = resp.to_string();
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
|
||||||
|
payload.len(),
|
||||||
|
payload
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let dir = std::env::temp_dir().join(format!("router-oai-test-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let caller_key_file = dir.join("c1.key");
|
||||||
|
let caller_secret = "caller-1-secret-0123456789abcdef0123456789";
|
||||||
|
std::fs::write(&caller_key_file, caller_secret).unwrap();
|
||||||
|
|
||||||
|
let cfg = ClaudeConnectorConfig {
|
||||||
|
listen: "127.0.0.1:4110".to_string(),
|
||||||
|
replay_store: dir.join("replay.cc"),
|
||||||
|
max_frame_bytes: 2 << 20,
|
||||||
|
max_connections: 8,
|
||||||
|
socket_timeout_ms: 10_000,
|
||||||
|
max_expiry_skew_ms: 300_000,
|
||||||
|
providers: vec![crate::ProviderEntry {
|
||||||
|
id: "oai-entry".to_string(),
|
||||||
|
credential: None,
|
||||||
|
wire: ProviderWire::OpenAiChat {
|
||||||
|
base_url: format!("http://{addr}/v1"),
|
||||||
|
strict_unsupported: vec![],
|
||||||
|
deadline_ms: 10_000,
|
||||||
|
max_response_bytes: 1 << 20,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
models: vec![row("ds-flash", "oai-entry", "deepseek-chat")],
|
||||||
|
callers: vec![model_connector::CallerConfig {
|
||||||
|
caller_runtime_id: "c1".to_string(),
|
||||||
|
connection_key_file: caller_key_file,
|
||||||
|
connection_key_epoch: 1,
|
||||||
|
allowed_models: vec!["ds-flash".to_string()],
|
||||||
|
max_concurrent_requests: 2,
|
||||||
|
max_payload_bytes: 1 << 20,
|
||||||
|
max_output_tokens: 4_096,
|
||||||
|
}],
|
||||||
|
lease_socket: None,
|
||||||
|
lease_holders: vec![],
|
||||||
|
lease_max_ms: 60_000,
|
||||||
|
};
|
||||||
|
let router = RouterBackend::from_config(&cfg, Box::new(NoSink)).unwrap();
|
||||||
|
|
||||||
|
let admission = CallerAdmission::new(
|
||||||
|
"c1",
|
||||||
|
caller_secret,
|
||||||
|
1,
|
||||||
|
["ds-flash".to_string()],
|
||||||
|
2,
|
||||||
|
1 << 20,
|
||||||
|
4_096,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let routes =
|
||||||
|
ProviderRoutes::new([("ds-flash".to_string(), "oai-entry".to_string())]).unwrap();
|
||||||
|
let mut service =
|
||||||
|
TransportService::open(&cfg.replay_store, routes, [admission], 5_000).unwrap();
|
||||||
|
let key = TransportKey::from_connection_secret(caller_secret).unwrap();
|
||||||
|
|
||||||
|
let mut req1 = ProviderRequest::new("r1", "c1", "ds-flash", "Be brief.", 128);
|
||||||
|
req1.input = vec![model_connector::InputItem::UserText {
|
||||||
|
text: "ping".to_string(),
|
||||||
|
}];
|
||||||
|
req1.tools = vec![model_connector::ToolDefinition {
|
||||||
|
name: "ping".to_string(),
|
||||||
|
description: "ping".to_string(),
|
||||||
|
parameters_json: r#"{"type":"object","properties":{"x":{"type":"integer"}}}"#
|
||||||
|
.to_string(),
|
||||||
|
}];
|
||||||
|
let inv1 = TransportInvocation::new("c1", 2_000, [1; 32], req1.clone()).unwrap();
|
||||||
|
let env1 = encrypt_invocation(&inv1, &key).unwrap();
|
||||||
|
let TransportAdmission::Execute(claim1) =
|
||||||
|
service.begin(&env1, 1_000, None, 1 << 20).unwrap()
|
||||||
|
else {
|
||||||
|
panic!("expected execute");
|
||||||
|
};
|
||||||
|
let res1 = router.execute(claim1.call());
|
||||||
|
let sealed1 = service.complete(*claim1, res1, 1 << 20).unwrap();
|
||||||
|
let opened1 = decrypt_result(&sealed1, &key, &inv1).unwrap();
|
||||||
|
let TransportDisposition::Transported {
|
||||||
|
receipt: ref receipt1,
|
||||||
|
..
|
||||||
|
} = opened1.disposition
|
||||||
|
else {
|
||||||
|
panic!("expected transported");
|
||||||
|
};
|
||||||
|
assert_eq!(receipt1.provider, "oai-entry");
|
||||||
|
assert_eq!(receipt1.model, "ds-flash");
|
||||||
|
|
||||||
|
let mut req2 = req1;
|
||||||
|
req2.request_id = "r2".to_string();
|
||||||
|
req2.input.extend(opened1.transcript_items());
|
||||||
|
req2.input.push(model_connector::InputItem::ToolResult {
|
||||||
|
call_id: "call_r1".to_string(),
|
||||||
|
output: "pong".to_string(),
|
||||||
|
});
|
||||||
|
let inv2 = TransportInvocation::new("c1", 2_000, [2; 32], req2).unwrap();
|
||||||
|
let env2 = encrypt_invocation(&inv2, &key).unwrap();
|
||||||
|
let TransportAdmission::Execute(claim2) =
|
||||||
|
service.begin(&env2, 1_000, None, 1 << 20).unwrap()
|
||||||
|
else {
|
||||||
|
panic!("expected execute");
|
||||||
|
};
|
||||||
|
let res2 = router.execute(claim2.call());
|
||||||
|
let sealed2 = service.complete(*claim2, res2, 1 << 20).unwrap();
|
||||||
|
let opened2 = decrypt_result(&sealed2, &key, &inv2).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
opened2.disposition,
|
||||||
|
TransportDisposition::Transported { .. }
|
||||||
|
));
|
||||||
|
|
||||||
|
let seen = seen.lock().unwrap();
|
||||||
|
assert_eq!(seen.len(), 2);
|
||||||
|
assert_eq!(seen[0].0, "/v1/chat/completions");
|
||||||
|
assert_eq!(seen[0].1["model"], "deepseek-chat");
|
||||||
|
assert_eq!(seen[1].1["model"], "deepseek-chat");
|
||||||
|
assert_eq!(
|
||||||
|
seen[1].1["messages"][2]["reasoning_content"],
|
||||||
|
"thought line"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
seen[1].1["messages"][2]["tool_calls"][0]["extra_content"],
|
||||||
|
serde_json::json!({"google": {"thought_signature": "sig-router"}})
|
||||||
|
);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn from_backends_rejects_untrimmed_cli_provider_id() {
|
||||||
|
let cli = ClaudeCodeBackend::new(
|
||||||
|
crate::config::ClaudeCodeConfig {
|
||||||
|
provider_id: " cli-space".to_string(),
|
||||||
|
claude_binary: std::path::PathBuf::from("/usr/bin/false"),
|
||||||
|
claude_binary_sha256: [0xaa; 32],
|
||||||
|
work_dir: std::path::PathBuf::from("/tmp"),
|
||||||
|
config_dir: std::path::PathBuf::from("/tmp"),
|
||||||
|
prompt_dir: std::path::PathBuf::from("/tmp"),
|
||||||
|
token_credential: "tok".to_string(),
|
||||||
|
handle_secret_credential: "sec".to_string(),
|
||||||
|
instance: "inst".to_string(),
|
||||||
|
meter_model: None,
|
||||||
|
limits: crate::config::ClaudeCodeLimits {
|
||||||
|
deadline: Duration::from_secs(5),
|
||||||
|
max_line_bytes: 1024,
|
||||||
|
max_total_bytes: 4096,
|
||||||
|
stderr_tail_bytes: 256,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Box::new(NoSink),
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
RouterBackend::from_backends(
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
Some(Arc::new(cli)),
|
||||||
|
vec![row("m1", "cli-space", "u1")]
|
||||||
|
),
|
||||||
|
Err(ConfigError::Invalid("providers"))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
struct NoSink;
|
||||||
|
#[cfg(unix)]
|
||||||
|
impl StderrSink for NoSink {
|
||||||
|
fn stderr_tail(&self, _: &[u8]) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -141,17 +141,16 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_service_unit_is_the_last_cgroup_component() {
|
fn a_service_unit_is_the_last_cgroup_component() {
|
||||||
let service = "0::/system.slice/system-mind\\x2dself.slice/mind-self@huginn.service\n";
|
let service = "0::/system.slice/system-agent\\x2dpool.slice/agent@alice.service\n";
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
unit_of_cgroup(service).as_deref(),
|
unit_of_cgroup(service).as_deref(),
|
||||||
Some("mind-self@huginn.service")
|
Some("agent@alice.service")
|
||||||
);
|
);
|
||||||
// Several hierarchies listed: the unified one decides.
|
// Several hierarchies listed: the unified one decides.
|
||||||
let hybrid = "12:cpu:/foo\n0::/system.slice/mind-self@a.service\n";
|
let hybrid = "12:cpu:/foo\n0::/system.slice/agent@a.service\n";
|
||||||
assert_eq!(
|
assert_eq!(unit_of_cgroup(hybrid).as_deref(), Some("agent@a.service"));
|
||||||
unit_of_cgroup(hybrid).as_deref(),
|
let plain = "0::/system.slice/other.service\n";
|
||||||
Some("mind-self@a.service")
|
assert_eq!(unit_of_cgroup(plain).as_deref(), Some("other.service"));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -160,7 +159,7 @@ mod tests {
|
||||||
"0::/\n",
|
"0::/\n",
|
||||||
"0::/user.slice/user-1000.slice/session-3.scope\n",
|
"0::/user.slice/user-1000.slice/session-3.scope\n",
|
||||||
"0::/user.slice/user-1000.slice/user@1000.service/app.slice/x.service/child\n",
|
"0::/user.slice/user-1000.slice/user@1000.service/app.slice/x.service/child\n",
|
||||||
"0::/system.slice/mind-self@huginn.service/sub\n",
|
"0::/system.slice/agent@alice.service/sub\n",
|
||||||
"0::/system.slice/.service\n",
|
"0::/system.slice/.service\n",
|
||||||
"1:name=systemd:/system.slice/a.service\n",
|
"1:name=systemd:/system.slice/a.service\n",
|
||||||
"",
|
"",
|
||||||
|
|
@ -188,7 +187,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
const ID: &str = "0123456789abcdef0123456789abcdef";
|
const ID: &str = "0123456789abcdef0123456789abcdef";
|
||||||
const UNIT: &str = "mind-self@eureka.service";
|
const UNIT: &str = "worker@node.service";
|
||||||
|
|
||||||
/// A fake `/proc` with one process in `cgroup`, and a fake `systemctl`
|
/// A fake `/proc` with one process in `cgroup`, and a fake `systemctl`
|
||||||
/// that records its arguments, runs `side_effect`, and exits `status`
|
/// that records its arguments, runs `side_effect`, and exits `status`
|
||||||
|
|
|
||||||
796
crates/claude-connector/tests/ask.rs
Normal file
796
crates/claude-connector/tests/ask.rs
Normal file
|
|
@ -0,0 +1,796 @@
|
||||||
|
//! `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 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");
|
||||||
|
let routes = ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap();
|
||||||
|
thread::spawn(move || serve(listener, limits, vec![admission], &store, routes, 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, EffortMap,
|
||||||
|
ForcedToolChoice, ModelRow, OutputSchemaSupport, ProcessPort, RouterBackend, 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 {
|
||||||
|
provider_id: "claude-code".into(),
|
||||||
|
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(),
|
||||||
|
meter_model: Some(MODEL.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 router = RouterBackend::from_backends(
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
Some(Arc::new(backend)),
|
||||||
|
vec![ModelRow {
|
||||||
|
id: MODEL.into(),
|
||||||
|
provider: "claude-code".into(),
|
||||||
|
upstream: MODEL.into(),
|
||||||
|
efforts: EffortMap::default(),
|
||||||
|
unset_effort: None,
|
||||||
|
forced_tool_choice: ForcedToolChoice::Never,
|
||||||
|
output_schema: OutputSchemaSupport::Native,
|
||||||
|
strict_tools: false,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
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");
|
||||||
|
let routes = ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap();
|
||||||
|
thread::spawn(move || {
|
||||||
|
serve(
|
||||||
|
listener,
|
||||||
|
limits,
|
||||||
|
vec![admission],
|
||||||
|
&store,
|
||||||
|
routes,
|
||||||
|
Arc::new(router),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,4 +1,4 @@
|
||||||
//! The Self-run credential lease over a real unix socket: who may lease, where
|
//! The credential lease over a real unix socket: who may lease, where
|
||||||
//! the token goes, what ends a lease, and the one usage-derived refusal, the
|
//! the token goes, what ends a lease, and the one usage-derived refusal, the
|
||||||
//! provider's own. Nothing is reserved and nothing is billed. The unit a peer
|
//! provider's own. Nothing is reserved and nothing is billed. The unit a peer
|
||||||
//! runs in is the `PeerUnits` port, answered here by a fake.
|
//! runs in is the `PeerUnits` port, answered here by a fake.
|
||||||
|
|
@ -14,18 +14,19 @@ use std::sync::{Arc, Mutex};
|
||||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use claude_connector::{
|
use claude_connector::{
|
||||||
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
||||||
LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource,
|
LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource,
|
||||||
decode_frame, encode_frame, serve_leases,
|
decode_frame, encode_frame, serve_leases,
|
||||||
};
|
};
|
||||||
use model_connector::{CallerAdmission, LeaseTurn, PlanQuota, TransportService, UsageReadout};
|
use model_connector::{
|
||||||
|
CallerAdmission, LeaseScope, PlanQuota, ProviderRoutes, TransportService, UsageReadout,
|
||||||
|
};
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
const CALLER: &str = "eureka";
|
const CALLER: &str = "eureka";
|
||||||
const MODEL: &str = "claude-opus-5-1";
|
const MODEL: &str = "claude-opus-5-1";
|
||||||
const TOKEN: &str = "sk-canary-lease-4c1f9a";
|
const TOKEN: &str = "sk-canary-lease-4c1f9a";
|
||||||
const INSTANCE: &str = "eureka";
|
const UNIT: &str = "agent@alice.service";
|
||||||
const UNIT: &str = "mind-self@eureka.service";
|
|
||||||
|
|
||||||
static SEQUENCE: AtomicUsize = AtomicUsize::new(0);
|
static SEQUENCE: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
|
||||||
|
|
@ -102,7 +103,7 @@ struct Harness {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Harness {
|
impl Harness {
|
||||||
/// The peers connect from invocation `n` of the Self unit.
|
/// The peers connect from invocation `n` of the configured unit.
|
||||||
fn enter(&self, n: u64) {
|
fn enter(&self, n: u64) {
|
||||||
self.run_in(UNIT, n);
|
self.run_in(UNIT, n);
|
||||||
}
|
}
|
||||||
|
|
@ -224,7 +225,8 @@ fn contains(haystack: &[u8], needle: &str) -> bool {
|
||||||
/// What a harness is built from.
|
/// What a harness is built from.
|
||||||
struct Setup {
|
struct Setup {
|
||||||
uid: u32,
|
uid: u32,
|
||||||
turn: LeaseTurn,
|
scope: LeaseScope,
|
||||||
|
unit: &'static str,
|
||||||
token: Option<&'static str>,
|
token: Option<&'static str>,
|
||||||
max_connections: usize,
|
max_connections: usize,
|
||||||
}
|
}
|
||||||
|
|
@ -232,14 +234,15 @@ struct Setup {
|
||||||
fn setup() -> Setup {
|
fn setup() -> Setup {
|
||||||
Setup {
|
Setup {
|
||||||
uid: own_uid(),
|
uid: own_uid(),
|
||||||
turn: LeaseTurn::SelfRun,
|
scope: LeaseScope::PerCaller,
|
||||||
|
unit: UNIT,
|
||||||
token: Some(TOKEN),
|
token: Some(TOKEN),
|
||||||
max_connections: 8,
|
max_connections: 8,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A listener serving `uid` as the caller `eureka`. Peers start in invocation
|
/// A listener serving `uid` as the caller `eureka`. Peers start in invocation
|
||||||
/// 1 of the Self unit.
|
/// 1 of the configured unit.
|
||||||
fn start(setup: Setup) -> Harness {
|
fn start(setup: Setup) -> Harness {
|
||||||
let units = Arc::new(FakeUnits {
|
let units = Arc::new(FakeUnits {
|
||||||
peer: Mutex::new(None),
|
peer: Mutex::new(None),
|
||||||
|
|
@ -255,7 +258,7 @@ fn start(setup: Setup) -> Harness {
|
||||||
let service = Arc::new(Mutex::new(
|
let service = Arc::new(Mutex::new(
|
||||||
TransportService::open(
|
TransportService::open(
|
||||||
&dir.join("replay.cc"),
|
&dir.join("replay.cc"),
|
||||||
"claude-code",
|
ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap(),
|
||||||
[CallerAdmission::new(
|
[CallerAdmission::new(
|
||||||
CALLER,
|
CALLER,
|
||||||
"lease-test-connection-key",
|
"lease-test-connection-key",
|
||||||
|
|
@ -283,16 +286,17 @@ fn start(setup: Setup) -> Harness {
|
||||||
tokens.clone(),
|
tokens.clone(),
|
||||||
units.clone(),
|
units.clone(),
|
||||||
);
|
);
|
||||||
let caller = LeaseCaller {
|
let holder = LeaseHolder {
|
||||||
uid: setup.uid,
|
uid: setup.uid,
|
||||||
caller_id: CALLER.to_string(),
|
caller_id: CALLER.to_string(),
|
||||||
turn: setup.turn,
|
provider: "claude-code".to_string(),
|
||||||
unit_instance: INSTANCE.to_string(),
|
unit: setup.unit.to_string(),
|
||||||
|
scope: setup.scope,
|
||||||
};
|
};
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
let _ = serve_leases(
|
let _ = serve_leases(
|
||||||
&listener,
|
&listener,
|
||||||
vec![caller],
|
vec![holder],
|
||||||
LeaseLimits {
|
LeaseLimits {
|
||||||
socket_timeout: Duration::from_secs(2),
|
socket_timeout: Duration::from_secs(2),
|
||||||
max_lease_ms: 3_600_000,
|
max_lease_ms: 3_600_000,
|
||||||
|
|
@ -449,7 +453,7 @@ fn high_utilization_refuses_nothing() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_peer_uid_outside_the_lease_callers_is_refused_and_nothing_is_read() {
|
fn a_peer_uid_outside_the_lease_holders_is_refused_and_nothing_is_read() {
|
||||||
let harness = start(Setup {
|
let harness = start(Setup {
|
||||||
uid: own_uid().wrapping_add(1),
|
uid: own_uid().wrapping_add(1),
|
||||||
..setup()
|
..setup()
|
||||||
|
|
@ -460,9 +464,9 @@ fn a_peer_uid_outside_the_lease_callers_is_refused_and_nothing_is_read() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_configured_uid_outside_the_self_unit_is_refused_and_nothing_is_read() {
|
fn the_configured_uid_outside_the_configured_unit_is_refused_and_nothing_is_read() {
|
||||||
let harness = start(setup());
|
let harness = start(setup());
|
||||||
harness.run_in("mind-persona@eureka.service", 1);
|
harness.run_in("other.service", 1);
|
||||||
let answer = ask(&harness, 60_000);
|
let answer = ask(&harness, 60_000);
|
||||||
assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller));
|
assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller));
|
||||||
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
|
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
|
||||||
|
|
@ -699,7 +703,7 @@ fn a_readout_answers_the_cells_windows_and_lends_nothing() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_peer_outside_the_lease_callers_still_reads_usage() {
|
fn a_peer_outside_the_lease_holders_still_reads_usage() {
|
||||||
let harness = start(Setup {
|
let harness = start(Setup {
|
||||||
uid: own_uid().wrapping_add(1),
|
uid: own_uid().wrapping_add(1),
|
||||||
..setup()
|
..setup()
|
||||||
|
|
@ -726,3 +730,58 @@ fn a_readout_beside_a_held_lease_leaves_it_held() {
|
||||||
assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy));
|
assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy));
|
||||||
assert!(granted_ok(&held));
|
assert!(granted_ok(&held));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn per_invocation_holder_in_configured_unit_leases_and_other_unit_is_refused() {
|
||||||
|
let harness = start(Setup {
|
||||||
|
scope: LeaseScope::PerInvocation,
|
||||||
|
unit: "agent@alice.service",
|
||||||
|
..setup()
|
||||||
|
});
|
||||||
|
harness.run_in("agent@alice.service", 1);
|
||||||
|
let answer = ask(&harness, 60_000);
|
||||||
|
assert!(granted_ok(&answer));
|
||||||
|
assert_eq!(
|
||||||
|
granted(&answer).lease_id,
|
||||||
|
format!("lease:{}:invocation", invocation(1))
|
||||||
|
);
|
||||||
|
|
||||||
|
harness.run_in("other.service", 2);
|
||||||
|
let refused = ask(&harness, 60_000);
|
||||||
|
assert_eq!(refusal_of(&refused), Some(LeaseRefusalKind::UnknownCaller));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn per_caller_and_per_invocation_busy_rules() {
|
||||||
|
let per_caller = start(Setup {
|
||||||
|
scope: LeaseScope::PerCaller,
|
||||||
|
..setup()
|
||||||
|
});
|
||||||
|
let first = ask(&per_caller, 60_000);
|
||||||
|
assert!(granted_ok(&first));
|
||||||
|
assert_eq!(granted(&first).lease_id, format!("lease:{}", invocation(1)));
|
||||||
|
per_caller.enter(2);
|
||||||
|
assert_eq!(
|
||||||
|
refusal_of(&ask(&per_caller, 60_000)),
|
||||||
|
Some(LeaseRefusalKind::Busy)
|
||||||
|
);
|
||||||
|
drop(first);
|
||||||
|
|
||||||
|
let per_invocation = start(Setup {
|
||||||
|
scope: LeaseScope::PerInvocation,
|
||||||
|
..setup()
|
||||||
|
});
|
||||||
|
let inv1 = ask(&per_invocation, 60_000);
|
||||||
|
assert!(granted_ok(&inv1));
|
||||||
|
assert_eq!(
|
||||||
|
refusal_of(&ask(&per_invocation, 60_000)),
|
||||||
|
Some(LeaseRefusalKind::Busy)
|
||||||
|
);
|
||||||
|
per_invocation.enter(2);
|
||||||
|
let inv2 = ask(&per_invocation, 60_000);
|
||||||
|
assert!(granted_ok(&inv2));
|
||||||
|
assert_eq!(
|
||||||
|
granted(&inv2).lease_id,
|
||||||
|
format!("lease:{}:invocation", invocation(2))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
||||||
316
crates/claude-connector/tests/lease_run.rs
Normal file
316
crates/claude-connector/tests/lease_run.rs
Normal file
|
|
@ -0,0 +1,316 @@
|
||||||
|
//! Integration tests for `claude-connector lease run`.
|
||||||
|
#![cfg(target_os = "linux")]
|
||||||
|
|
||||||
|
use std::io::{self, Read, Write};
|
||||||
|
use std::mem::{size_of, zeroed};
|
||||||
|
use std::os::fd::{AsRawFd, RawFd};
|
||||||
|
use std::os::unix::net::{UnixListener, UnixStream};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::ptr;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use claude_connector::{
|
||||||
|
LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, MAX_LEASE_FRAME_BYTES,
|
||||||
|
decode_frame, encode_frame,
|
||||||
|
};
|
||||||
|
|
||||||
|
static SEQUENCE: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
|
||||||
|
struct Scratch(PathBuf);
|
||||||
|
|
||||||
|
impl Scratch {
|
||||||
|
fn new() -> Self {
|
||||||
|
let dir = std::env::temp_dir().join(format!(
|
||||||
|
"claude-lease-run-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
SEQUENCE.fetch_add(1, Ordering::SeqCst)
|
||||||
|
));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
Self(dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(&self, name: &str) -> PathBuf {
|
||||||
|
self.0.join(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Scratch {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_request_frame(stream: &mut UnixStream) -> LeaseMessage {
|
||||||
|
let mut len_buf = [0_u8; 4];
|
||||||
|
stream.read_exact(&mut len_buf).unwrap();
|
||||||
|
let len = u32::from_be_bytes(len_buf) as usize;
|
||||||
|
assert!(len > 0 && len <= MAX_LEASE_FRAME_BYTES);
|
||||||
|
let mut body = vec![0_u8; len];
|
||||||
|
stream.read_exact(&mut body).unwrap();
|
||||||
|
let mut whole = Vec::with_capacity(4 + len);
|
||||||
|
whole.extend_from_slice(&len_buf);
|
||||||
|
whole.extend_from_slice(&body);
|
||||||
|
decode_frame(&whole).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_with_fd(stream: &UnixStream, frame: &[u8], fd: RawFd) -> io::Result<()> {
|
||||||
|
let fd_size = size_of::<RawFd>() as u32;
|
||||||
|
// SAFETY: `CMSG_SPACE` is a pure size computation.
|
||||||
|
let space = unsafe { libc::CMSG_SPACE(fd_size) } as usize;
|
||||||
|
let mut control = vec![0_u64; space.div_ceil(size_of::<u64>())];
|
||||||
|
let mut vector = libc::iovec {
|
||||||
|
iov_base: frame.as_ptr().cast_mut().cast(),
|
||||||
|
iov_len: frame.len(),
|
||||||
|
};
|
||||||
|
// SAFETY: buffers outlive `sendmsg` and `control` is sized for one fd.
|
||||||
|
let sent = unsafe {
|
||||||
|
let mut message: libc::msghdr = zeroed();
|
||||||
|
message.msg_iov = &mut vector;
|
||||||
|
message.msg_iovlen = 1;
|
||||||
|
message.msg_control = control.as_mut_ptr().cast();
|
||||||
|
message.msg_controllen = space as _;
|
||||||
|
let header = libc::CMSG_FIRSTHDR(&message);
|
||||||
|
(*header).cmsg_level = libc::SOL_SOCKET;
|
||||||
|
(*header).cmsg_type = libc::SCM_RIGHTS;
|
||||||
|
(*header).cmsg_len = libc::CMSG_LEN(fd_size) as _;
|
||||||
|
ptr::copy_nonoverlapping(
|
||||||
|
ptr::from_ref(&fd).cast::<u8>(),
|
||||||
|
libc::CMSG_DATA(header),
|
||||||
|
size_of::<RawFd>(),
|
||||||
|
);
|
||||||
|
libc::sendmsg(stream.as_raw_fd(), &message, libc::MSG_NOSIGNAL)
|
||||||
|
};
|
||||||
|
let Ok(sent) = usize::try_from(sent) else {
|
||||||
|
return Err(io::Error::last_os_error());
|
||||||
|
};
|
||||||
|
let mut stream = stream;
|
||||||
|
stream.write_all(&frame[sent..])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fake_lender_fd3_status_and_socket_hold() {
|
||||||
|
const TOKEN: &str = "sk-canary-lease-run-88f1c";
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let socket = scratch.path("lease.sock");
|
||||||
|
let listener = UnixListener::bind(&socket).unwrap();
|
||||||
|
|
||||||
|
let started_flag = scratch.path("child.started");
|
||||||
|
let release_flag = scratch.path("lender.checked");
|
||||||
|
let token_seen = scratch.path("child.token");
|
||||||
|
let eof_seen = Arc::new(AtomicBool::new(false));
|
||||||
|
let eof_seen_lender = eof_seen.clone();
|
||||||
|
|
||||||
|
let lender = std::thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
let req = read_request_frame(&mut stream);
|
||||||
|
assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_)));
|
||||||
|
|
||||||
|
let (read_end, mut write_end) = std::io::pipe().unwrap();
|
||||||
|
write_end.write_all(TOKEN.as_bytes()).unwrap();
|
||||||
|
drop(write_end);
|
||||||
|
|
||||||
|
let frame = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted {
|
||||||
|
lease_id: "lease:test-run".to_string(),
|
||||||
|
plan_quota: vec![],
|
||||||
|
}));
|
||||||
|
send_with_fd(&stream, &frame, read_end.as_raw_fd()).unwrap();
|
||||||
|
drop(read_end);
|
||||||
|
|
||||||
|
let mut buf = [0_u8; 16];
|
||||||
|
loop {
|
||||||
|
match stream.read(&mut buf) {
|
||||||
|
Ok(0) | Err(_) => {
|
||||||
|
eof_seen_lender.store(true, Ordering::Release);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Ok(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Child reads fd 3, checks env/cmdline do not hold the token, signals startup,
|
||||||
|
// waits for the test thread to assert the lender socket is still open, and exits 42.
|
||||||
|
let script = format!(
|
||||||
|
r#"set -eu
|
||||||
|
test "${{CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR:-}}" = "3"
|
||||||
|
tok=$(cat <&3)
|
||||||
|
printf '%s' "$tok" > "{token_seen}"
|
||||||
|
if env | grep -qF "{TOKEN}"; then exit 91; fi
|
||||||
|
if tr '\0' '\n' < /proc/self/cmdline | grep -qF "{TOKEN}"; then exit 92; fi
|
||||||
|
: > "{started_flag}"
|
||||||
|
i=0
|
||||||
|
while [ ! -e "{release_flag}" ]; do
|
||||||
|
i=$((i + 1))
|
||||||
|
if [ "$i" -gt 200 ]; then exit 93; fi
|
||||||
|
sleep 0.05
|
||||||
|
done
|
||||||
|
exit 42
|
||||||
|
"#,
|
||||||
|
token_seen = token_seen.display(),
|
||||||
|
started_flag = started_flag.display(),
|
||||||
|
release_flag = release_flag.display(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||||
|
.args([
|
||||||
|
"lease",
|
||||||
|
"run",
|
||||||
|
"--socket",
|
||||||
|
socket.to_str().unwrap(),
|
||||||
|
"--",
|
||||||
|
"/bin/sh",
|
||||||
|
"-c",
|
||||||
|
&script,
|
||||||
|
])
|
||||||
|
.env("KEEP_INHERITED", "yes")
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while !started_flag.exists() {
|
||||||
|
if let Some(status) = child.try_wait().unwrap() {
|
||||||
|
let _ = UnixStream::connect(&socket);
|
||||||
|
panic!("leased child exited early before starting: {status:?}");
|
||||||
|
}
|
||||||
|
assert!(Instant::now() < deadline, "leased child never started");
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!eof_seen.load(Ordering::Acquire),
|
||||||
|
"lender saw EOF while leased child was still running"
|
||||||
|
);
|
||||||
|
std::fs::write(&release_flag, b"ok").unwrap();
|
||||||
|
|
||||||
|
let output = child.wait_with_output().unwrap();
|
||||||
|
assert_eq!(output.status.code(), Some(42), "{output:?}");
|
||||||
|
assert_eq!(std::fs::read_to_string(&token_seen).unwrap(), TOKEN);
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
assert!(!stderr.contains(TOKEN), "{stderr}");
|
||||||
|
|
||||||
|
lender.join().unwrap();
|
||||||
|
assert!(
|
||||||
|
eof_seen.load(Ordering::Acquire),
|
||||||
|
"lender did not see EOF after child exited"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refused_busy_and_unknown_caller_do_not_spawn() {
|
||||||
|
const CANARY_DETAIL: &str = "CANARY-REFUSAL-DETAIL-7f3a";
|
||||||
|
for kind in [LeaseRefusalKind::Busy, LeaseRefusalKind::UnknownCaller] {
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let socket = scratch.path("lease.sock");
|
||||||
|
let spawned_marker = scratch.path("should-not-exist");
|
||||||
|
let listener = UnixListener::bind(&socket).unwrap();
|
||||||
|
let handled = Arc::new(AtomicBool::new(false));
|
||||||
|
let handled_lender = handled.clone();
|
||||||
|
|
||||||
|
let lender = std::thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
if handled_lender.load(Ordering::Acquire) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let req = read_request_frame(&mut stream);
|
||||||
|
assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_)));
|
||||||
|
let frame = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||||
|
kind,
|
||||||
|
detail: CANARY_DETAIL.to_string(),
|
||||||
|
}));
|
||||||
|
stream.write_all(&frame).unwrap();
|
||||||
|
handled_lender.store(true, Ordering::Release);
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||||
|
.args([
|
||||||
|
"lease",
|
||||||
|
"run",
|
||||||
|
"--socket",
|
||||||
|
socket.to_str().unwrap(),
|
||||||
|
"--",
|
||||||
|
"/bin/sh",
|
||||||
|
"-c",
|
||||||
|
&format!("touch '{}'", spawned_marker.display()),
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
if !handled.load(Ordering::Acquire) {
|
||||||
|
handled.store(true, Ordering::Release);
|
||||||
|
let _ = UnixStream::connect(&socket);
|
||||||
|
}
|
||||||
|
lender.join().unwrap();
|
||||||
|
assert!(!output.status.success(), "{kind:?}: {output:?}");
|
||||||
|
assert!(
|
||||||
|
!spawned_marker.exists(),
|
||||||
|
"{kind:?}: child spawned on refusal"
|
||||||
|
);
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
assert!(!stderr.contains(CANARY_DETAIL), "{kind:?}: {stderr}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn signal_exit_maps_to_128_plus_signal_and_bad_cli_args_fail() {
|
||||||
|
let scratch = Scratch::new();
|
||||||
|
let socket = scratch.path("lease.sock");
|
||||||
|
let listener = UnixListener::bind(&socket).unwrap();
|
||||||
|
let lender = std::thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
let req = read_request_frame(&mut stream);
|
||||||
|
assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_)));
|
||||||
|
let (read_end, mut write_end) = std::io::pipe().unwrap();
|
||||||
|
write_end.write_all(b"sk-signal-test").unwrap();
|
||||||
|
drop(write_end);
|
||||||
|
let frame = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted {
|
||||||
|
lease_id: "lease:signal".to_string(),
|
||||||
|
plan_quota: vec![],
|
||||||
|
}));
|
||||||
|
send_with_fd(&stream, &frame, read_end.as_raw_fd()).unwrap();
|
||||||
|
drop(read_end);
|
||||||
|
let mut buf = [0_u8; 16];
|
||||||
|
while matches!(stream.read(&mut buf), Ok(n) if n > 0) {}
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||||
|
.args([
|
||||||
|
"lease",
|
||||||
|
"run",
|
||||||
|
"--socket",
|
||||||
|
socket.to_str().unwrap(),
|
||||||
|
"--",
|
||||||
|
"/bin/sh",
|
||||||
|
"-c",
|
||||||
|
"kill -KILL $$",
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
lender.join().unwrap();
|
||||||
|
assert_eq!(output.status.code(), Some(128 + 9), "{output:?}");
|
||||||
|
|
||||||
|
let sock = socket.to_str().unwrap();
|
||||||
|
for bad in [
|
||||||
|
vec!["lease", "run", "--socket", sock],
|
||||||
|
vec!["lease", "run", "--socket", sock, "--"],
|
||||||
|
vec![
|
||||||
|
"lease",
|
||||||
|
"run",
|
||||||
|
"--socket",
|
||||||
|
sock,
|
||||||
|
"--ttl-secs",
|
||||||
|
"0",
|
||||||
|
"--",
|
||||||
|
"/bin/true",
|
||||||
|
],
|
||||||
|
] {
|
||||||
|
let out = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||||
|
.args(&bad)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(!out.status.success(), "{bad:?}: {out:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -171,11 +171,16 @@ pub(crate) fn caller(
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "daemon")]
|
||||||
|
pub(crate) fn routes() -> crate::ProviderRoutes {
|
||||||
|
crate::ProviderRoutes::new([("gpt-5.4".to_string(), "fixture-sse".to_string())]).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "daemon")]
|
#[cfg(feature = "daemon")]
|
||||||
pub(crate) fn open_service(store: &TestStore, max_concurrent_requests: usize) -> TransportService {
|
pub(crate) fn open_service(store: &TestStore, max_concurrent_requests: usize) -> TransportService {
|
||||||
TransportService::open(
|
TransportService::open(
|
||||||
&store.path,
|
&store.path,
|
||||||
"fixture-sse",
|
routes(),
|
||||||
[
|
[
|
||||||
caller(
|
caller(
|
||||||
"epiphany-yggdrasil",
|
"epiphany-yggdrasil",
|
||||||
|
|
|
||||||
|
|
@ -18,26 +18,24 @@ use crate::envelope::{
|
||||||
};
|
};
|
||||||
use crate::readout::PlanQuotaSnapshot;
|
use crate::readout::PlanQuotaSnapshot;
|
||||||
use crate::service::{
|
use crate::service::{
|
||||||
CallerAdmission, ProviderCall, TransportAdmission, TransportService, distinct_admissions,
|
CallerAdmission, ProviderCall, ProviderRoutes, TransportAdmission, TransportService,
|
||||||
|
distinct_admissions,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The only provider seam of the connector kit. A connector binary implements
|
/// The provider seam of the connector kit. A connector binary implements
|
||||||
/// it over one model provider; the kit names no provider.
|
/// it over one or more model routes; the kit derives the provider tag per
|
||||||
|
/// model from [`ProviderRoutes`].
|
||||||
pub trait ProviderBackend: Send + Sync {
|
pub trait ProviderBackend: Send + Sync {
|
||||||
/// Whether the provider can take work; `Err` names the backend field that
|
/// Whether the provider can take work; `Err` names the backend field that
|
||||||
/// is not ready, never a value. `serve` consults it once, before it opens
|
/// is not ready, never a value. `serve` consults it once, before it opens
|
||||||
/// the replay store or accepts a connection; the request path does not
|
/// the replay store or accepts a connection; the request path does not
|
||||||
/// consult it.
|
/// consult it.
|
||||||
fn ready(&self) -> Result<(), &'static str>;
|
fn ready(&self) -> Result<(), &'static str>;
|
||||||
/// The tag of the provider this backend fronts. The service owns it from
|
/// What one provider's own plan allows and has used together with that
|
||||||
/// `serve` on: it names the provider on every receipt and decides which
|
/// provider's tag, for the usage readout and that provider's own refusals.
|
||||||
/// reasoning state is foreign.
|
/// A backend with no plan to report keeps `None`.
|
||||||
fn provider(&self) -> &str;
|
fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> {
|
||||||
/// What the provider's own plan allows and has used, for the usage
|
None
|
||||||
/// readout and the provider's own refusals. A provider with no plan to report
|
|
||||||
/// keeps the default.
|
|
||||||
fn plan_quota(&self) -> PlanQuotaSnapshot {
|
|
||||||
PlanQuotaSnapshot::default()
|
|
||||||
}
|
}
|
||||||
/// Executes one admitted call. The service has already bound it to its
|
/// Executes one admitted call. The service has already bound it to its
|
||||||
/// caller and recorded its replay claim. The call cannot show a foreign
|
/// caller and recorded its replay claim. The call cannot show a foreign
|
||||||
|
|
@ -158,13 +156,14 @@ pub fn serve(
|
||||||
limits: ServeLimits,
|
limits: ServeLimits,
|
||||||
admissions: Vec<CallerAdmission>,
|
admissions: Vec<CallerAdmission>,
|
||||||
replay_store: &Path,
|
replay_store: &Path,
|
||||||
|
routes: ProviderRoutes,
|
||||||
backend: Arc<dyn ProviderBackend>,
|
backend: Arc<dyn ProviderBackend>,
|
||||||
) -> Result<(), ServeError> {
|
) -> Result<(), ServeError> {
|
||||||
limits.validate(&admissions)?;
|
limits.validate(&admissions)?;
|
||||||
admit_listener(&listener, backend.as_ref())?;
|
admit_listener(&listener, backend.as_ref())?;
|
||||||
let service = Arc::new(Mutex::new(TransportService::open(
|
let service = Arc::new(Mutex::new(TransportService::open(
|
||||||
replay_store,
|
replay_store,
|
||||||
backend.provider(),
|
routes,
|
||||||
admissions,
|
admissions,
|
||||||
limits.max_expiry_skew_ms,
|
limits.max_expiry_skew_ms,
|
||||||
)?));
|
)?));
|
||||||
|
|
@ -172,7 +171,7 @@ pub fn serve(
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `serve` over a service the caller opened and keeps a handle to, so another
|
/// `serve` over a service the caller opened and keeps a handle to, so another
|
||||||
/// front of the same service (the Self-run credential lease) shares its
|
/// front of the same service (the credential lease) shares its
|
||||||
/// replay store and plan. The limits must already have been validated against the
|
/// replay store and plan. The limits must already have been validated against the
|
||||||
/// service's admissions.
|
/// service's admissions.
|
||||||
pub fn serve_service(
|
pub fn serve_service(
|
||||||
|
|
@ -261,7 +260,10 @@ fn answer_frame(
|
||||||
let envelope = match decode_request_frame(request).map_err(|_| ServeError::FrameEncoding)? {
|
let envelope = match decode_request_frame(request).map_err(|_| ServeError::FrameEncoding)? {
|
||||||
RequestFrame::Invoke(envelope) => envelope,
|
RequestFrame::Invoke(envelope) => envelope,
|
||||||
RequestFrame::UsageReadout(envelope) => {
|
RequestFrame::UsageReadout(envelope) => {
|
||||||
let plan = backend.plan_quota();
|
let plan = backend
|
||||||
|
.plan_quota()
|
||||||
|
.map(|(_, snapshot)| snapshot)
|
||||||
|
.unwrap_or_default();
|
||||||
let response = service
|
let response = service
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| ServeError::ServicePoisoned)?
|
.map_err(|_| ServeError::ServicePoisoned)?
|
||||||
|
|
@ -270,13 +272,15 @@ fn answer_frame(
|
||||||
.map_err(|_| ServeError::FrameEncoding);
|
.map_err(|_| ServeError::FrameEncoding);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let plan = backend.plan_quota();
|
||||||
let admission = service
|
let admission = service
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| ServeError::ServicePoisoned)?
|
.map_err(|_| ServeError::ServicePoisoned)?
|
||||||
.begin(
|
.begin(
|
||||||
&envelope,
|
&envelope,
|
||||||
unix_ms()?,
|
unix_ms()?,
|
||||||
&backend.plan_quota(),
|
plan.as_ref()
|
||||||
|
.map(|(provider, snapshot)| (*provider, snapshot)),
|
||||||
limits.max_frame_bytes,
|
limits.max_frame_bytes,
|
||||||
)?;
|
)?;
|
||||||
let response = match admission {
|
let response = match admission {
|
||||||
|
|
@ -382,7 +386,7 @@ mod tests {
|
||||||
FailureKind, Refusal, TransportDisposition, TransportEvent, TransportEventPayload,
|
FailureKind, Refusal, TransportDisposition, TransportEvent, TransportEventPayload,
|
||||||
TransportInvocation, TransportOutcome, TransportResult,
|
TransportInvocation, TransportOutcome, TransportResult,
|
||||||
};
|
};
|
||||||
use crate::fixtures::{TestStore, caller, invocation_for, receipt, request};
|
use crate::fixtures::{TestStore, caller, invocation_for, receipt, request, routes};
|
||||||
|
|
||||||
const CALLER: &str = "epiphany-yggdrasil";
|
const CALLER: &str = "epiphany-yggdrasil";
|
||||||
const KEY: &str = "epiphany-distinct-test-key";
|
const KEY: &str = "epiphany-distinct-test-key";
|
||||||
|
|
@ -412,10 +416,6 @@ mod tests {
|
||||||
self.ready.then_some(()).ok_or("fixture")
|
self.ready.then_some(()).ok_or("fixture")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn provider(&self) -> &str {
|
|
||||||
"fixture-sse"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
self.executions.fetch_add(1, Ordering::SeqCst);
|
self.executions.fetch_add(1, Ordering::SeqCst);
|
||||||
call.transported(
|
call.transported(
|
||||||
|
|
@ -458,7 +458,14 @@ mod tests {
|
||||||
let (sender, receiver) = std::sync::mpsc::channel();
|
let (sender, receiver) = std::sync::mpsc::channel();
|
||||||
let path = path.to_path_buf();
|
let path = path.to_path_buf();
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
let _ = sender.send(serve(listener, limits, admissions, &path, backend));
|
let _ = sender.send(serve(
|
||||||
|
listener,
|
||||||
|
limits,
|
||||||
|
admissions,
|
||||||
|
&path,
|
||||||
|
routes(),
|
||||||
|
backend,
|
||||||
|
));
|
||||||
});
|
});
|
||||||
receiver.recv_timeout(Duration::from_secs(2)).ok()
|
receiver.recv_timeout(Duration::from_secs(2)).ok()
|
||||||
}
|
}
|
||||||
|
|
@ -484,7 +491,7 @@ mod tests {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
let endpoint = listener.local_addr().unwrap();
|
let endpoint = listener.local_addr().unwrap();
|
||||||
let path = store.path.clone();
|
let path = store.path.clone();
|
||||||
thread::spawn(move || serve(listener, limits(), admissions, &path, backend));
|
thread::spawn(move || serve(listener, limits(), admissions, &path, routes(), backend));
|
||||||
let client =
|
let client =
|
||||||
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
||||||
(client, endpoint)
|
(client, endpoint)
|
||||||
|
|
@ -509,6 +516,7 @@ mod tests {
|
||||||
/// A counting backend that reports a plan, as a provider with one would.
|
/// A counting backend that reports a plan, as a provider with one would.
|
||||||
struct PlanBackend {
|
struct PlanBackend {
|
||||||
inner: Arc<CountingBackend>,
|
inner: Arc<CountingBackend>,
|
||||||
|
provider: &'static str,
|
||||||
plan: PlanQuotaSnapshot,
|
plan: PlanQuotaSnapshot,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -517,12 +525,8 @@ mod tests {
|
||||||
self.inner.ready()
|
self.inner.ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn provider(&self) -> &str {
|
fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> {
|
||||||
self.inner.provider()
|
Some((self.provider, self.plan.clone()))
|
||||||
}
|
|
||||||
|
|
||||||
fn plan_quota(&self) -> PlanQuotaSnapshot {
|
|
||||||
self.plan.clone()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
|
|
@ -545,6 +549,7 @@ mod tests {
|
||||||
};
|
};
|
||||||
let backend = Arc::new(PlanBackend {
|
let backend = Arc::new(PlanBackend {
|
||||||
inner: inner.clone(),
|
inner: inner.clone(),
|
||||||
|
provider: "fixture-sse",
|
||||||
plan: plan.clone(),
|
plan: plan.clone(),
|
||||||
});
|
});
|
||||||
let (client, endpoint) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
let (client, endpoint) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
||||||
|
|
@ -572,6 +577,11 @@ mod tests {
|
||||||
assert!(stranger.usage_readout(CALLER).is_err());
|
assert!(stranger.usage_readout(CALLER).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plan_quota_defaults_to_none() {
|
||||||
|
assert_eq!(CountingBackend::new(true).plan_quota(), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_backend_with_no_plan_reads_out_none() {
|
fn a_backend_with_no_plan_reads_out_none() {
|
||||||
let store = TestStore::new();
|
let store = TestStore::new();
|
||||||
|
|
@ -598,6 +608,7 @@ mod tests {
|
||||||
let inner = CountingBackend::new(true);
|
let inner = CountingBackend::new(true);
|
||||||
let backend = Arc::new(PlanBackend {
|
let backend = Arc::new(PlanBackend {
|
||||||
inner: inner.clone(),
|
inner: inner.clone(),
|
||||||
|
provider: "fixture-sse",
|
||||||
plan: window_plan(1_000, "rejected", now_ms() + 3_600_000),
|
plan: window_plan(1_000, "rejected", now_ms() + 3_600_000),
|
||||||
});
|
});
|
||||||
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
||||||
|
|
@ -609,12 +620,31 @@ mod tests {
|
||||||
assert_eq!(inner.executions.load(Ordering::SeqCst), 0);
|
assert_eq!(inner.executions.load(Ordering::SeqCst), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serve_rejecting_plan_only_refuses_owning_route() {
|
||||||
|
let store = TestStore::new();
|
||||||
|
let inner = CountingBackend::new(true);
|
||||||
|
let backend = Arc::new(PlanBackend {
|
||||||
|
inner: inner.clone(),
|
||||||
|
provider: "other-provider",
|
||||||
|
plan: window_plan(1_000, "rejected", now_ms() + 3_600_000),
|
||||||
|
});
|
||||||
|
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
||||||
|
let admitted = client.execute(&fresh("request-other-plan")).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
admitted.disposition,
|
||||||
|
TransportDisposition::Transported { .. }
|
||||||
|
));
|
||||||
|
assert_eq!(inner.executions.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn serve_admits_a_full_window_the_provider_still_allows() {
|
fn serve_admits_a_full_window_the_provider_still_allows() {
|
||||||
let store = TestStore::new();
|
let store = TestStore::new();
|
||||||
let inner = CountingBackend::new(true);
|
let inner = CountingBackend::new(true);
|
||||||
let backend = Arc::new(PlanBackend {
|
let backend = Arc::new(PlanBackend {
|
||||||
inner: inner.clone(),
|
inner: inner.clone(),
|
||||||
|
provider: "fixture-sse",
|
||||||
plan: window_plan(999, "allowed", now_ms() + 3_600_000),
|
plan: window_plan(999, "allowed", now_ms() + 3_600_000),
|
||||||
});
|
});
|
||||||
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
||||||
|
|
@ -743,19 +773,14 @@ mod tests {
|
||||||
// The wide completion goes straight through the service: serve holds
|
// The wide completion goes straight through the service: serve holds
|
||||||
// the replay store for as long as it runs, so a second serve cannot
|
// the replay store for as long as it runs, so a second serve cannot
|
||||||
// open it while the first lives.
|
// open it while the first lives.
|
||||||
let mut service = TransportService::open(
|
let mut service =
|
||||||
&store.path,
|
TransportService::open(&store.path, routes(), vec![caller(CALLER, KEY, 4)], 300_000)
|
||||||
"fixture-sse",
|
.unwrap();
|
||||||
vec![caller(CALLER, KEY, 4)],
|
|
||||||
300_000,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let envelope =
|
let envelope =
|
||||||
crate::envelope::encrypt_invocation(&invocation, &crate::fixtures::security(KEY))
|
crate::envelope::encrypt_invocation(&invocation, &crate::fixtures::security(KEY))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let TransportAdmission::Execute(claim) = service
|
let TransportAdmission::Execute(claim) =
|
||||||
.begin(&envelope, now_ms(), &PlanQuotaSnapshot::default(), 1 << 20)
|
service.begin(&envelope, now_ms(), None, 1 << 20).unwrap()
|
||||||
.unwrap()
|
|
||||||
else {
|
else {
|
||||||
panic!("a fresh request must execute");
|
panic!("a fresh request must execute");
|
||||||
};
|
};
|
||||||
|
|
@ -779,6 +804,7 @@ mod tests {
|
||||||
narrowed,
|
narrowed,
|
||||||
vec![caller(CALLER, KEY, 4)],
|
vec![caller(CALLER, KEY, 4)],
|
||||||
&path,
|
&path,
|
||||||
|
routes(),
|
||||||
served,
|
served,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|
@ -1077,7 +1103,7 @@ mod tests {
|
||||||
..limits()
|
..limits()
|
||||||
};
|
};
|
||||||
let admissions = vec![admission(CALLER, KEY, 4, bound)];
|
let admissions = vec![admission(CALLER, KEY, 4, bound)];
|
||||||
thread::spawn(move || serve(listener, tight, admissions, &path, served));
|
thread::spawn(move || serve(listener, tight, admissions, &path, routes(), served));
|
||||||
let client =
|
let client =
|
||||||
ConnectorClient::new(endpoint, KEY, frame, Some(Duration::from_secs(5))).unwrap();
|
ConnectorClient::new(endpoint, KEY, frame, Some(Duration::from_secs(5))).unwrap();
|
||||||
let reply = client.execute(&invocation).unwrap();
|
let reply = client.execute(&invocation).unwrap();
|
||||||
|
|
@ -1129,10 +1155,6 @@ mod tests {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn provider(&self) -> &str {
|
|
||||||
"fixture-sse"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
self.executions.fetch_add(1, Ordering::SeqCst);
|
self.executions.fetch_add(1, Ordering::SeqCst);
|
||||||
sized_result(call, self.text_len)
|
sized_result(call, self.text_len)
|
||||||
|
|
@ -1189,21 +1211,16 @@ mod tests {
|
||||||
/// The encoded size of a result carrying no text, for this request id.
|
/// The encoded size of a result carrying no text, for this request id.
|
||||||
fn empty_result_len(request_id: &str) -> usize {
|
fn empty_result_len(request_id: &str) -> usize {
|
||||||
let store = TestStore::new();
|
let store = TestStore::new();
|
||||||
let mut service = TransportService::open(
|
let mut service =
|
||||||
&store.path,
|
TransportService::open(&store.path, routes(), vec![caller(CALLER, KEY, 4)], 300_000)
|
||||||
"fixture-sse",
|
.unwrap();
|
||||||
vec![caller(CALLER, KEY, 4)],
|
|
||||||
300_000,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let envelope = crate::envelope::encrypt_invocation(
|
let envelope = crate::envelope::encrypt_invocation(
|
||||||
&fresh(request_id),
|
&fresh(request_id),
|
||||||
&crate::fixtures::security(KEY),
|
&crate::fixtures::security(KEY),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let TransportAdmission::Execute(claim) = service
|
let TransportAdmission::Execute(claim) =
|
||||||
.begin(&envelope, now_ms(), &PlanQuotaSnapshot::default(), 1 << 20)
|
service.begin(&envelope, now_ms(), None, 1 << 20).unwrap()
|
||||||
.unwrap()
|
|
||||||
else {
|
else {
|
||||||
panic!("a fresh request must execute");
|
panic!("a fresh request must execute");
|
||||||
};
|
};
|
||||||
|
|
@ -1294,7 +1311,7 @@ mod tests {
|
||||||
let service = Arc::new(Mutex::new(
|
let service = Arc::new(Mutex::new(
|
||||||
TransportService::open(
|
TransportService::open(
|
||||||
&store.path,
|
&store.path,
|
||||||
"fixture-sse",
|
routes(),
|
||||||
vec![caller(CALLER, KEY, 4)],
|
vec![caller(CALLER, KEY, 4)],
|
||||||
300_000,
|
300_000,
|
||||||
)
|
)
|
||||||
|
|
@ -1352,7 +1369,7 @@ mod tests {
|
||||||
let backend = CountingBackend::new(true);
|
let backend = CountingBackend::new(true);
|
||||||
let path = store.path.clone();
|
let path = store.path.clone();
|
||||||
let served = backend.clone();
|
let served = backend.clone();
|
||||||
thread::spawn(move || serve(listener, limits(), admissions, &path, served));
|
thread::spawn(move || serve(listener, limits(), admissions, &path, routes(), served));
|
||||||
let client =
|
let client =
|
||||||
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
||||||
client.execute(&fresh("request-key")).unwrap();
|
client.execute(&fresh("request-key")).unwrap();
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,27 +1,29 @@
|
||||||
//! A credential lease: a Self run's or a Persona turn's hold on the token the
|
//! A credential lease: a holder's hold on the token the connector lends.
|
||||||
//! connector lends. The lease is memory bound to its holder's open connection,
|
//! The lease is memory bound to its holder's open connection, not a record and
|
||||||
//! not a record and not a charge: it decides `Busy` while it is held and
|
//! not a charge: it decides `Busy` while it is held and nothing else. It ends
|
||||||
//! nothing else. It ends when its holder lets go (`end_lease`), when the unit
|
//! when its holder lets go (`end_lease`), when the unit invocation it served
|
||||||
//! invocation it served ends, or when its expiry passes. Nothing is billed and
|
//! ends, or when its expiry passes. Nothing is billed and nothing is reserved.
|
||||||
//! nothing is reserved. The only usage-derived refusal is the provider's own
|
//! The only usage-derived refusal is the provider's own (`ProviderRejected`),
|
||||||
//! (`ProviderRejected`), repeated with the provider's own expiry.
|
//! repeated with the provider's own expiry.
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
/// The request-id namespace of leases.
|
/// The request-id namespace of leases.
|
||||||
const LEASE_PREFIX: &str = "lease:";
|
const LEASE_PREFIX: &str = "lease:";
|
||||||
|
|
||||||
/// What a Persona turn's lease id adds to its invocation id, so a Persona
|
/// What a per-invocation lease id adds to its invocation id, so a
|
||||||
/// lease and a Self lease of one caller and one invocation never share an id.
|
/// per-invocation lease and a per-caller lease of one caller and one
|
||||||
const PERSONA_SUFFIX: &str = ":persona";
|
/// invocation never share an id.
|
||||||
|
const INVOCATION_SUFFIX: &str = ":invocation";
|
||||||
|
|
||||||
/// Which kind of turn a lease serves. It is a property of the lease caller's
|
/// Exclusivity scope of a lease. It is a property of the lease holder's
|
||||||
/// configured row, never of a request. A caller holds one Self lease at a
|
/// configured row, never of a request. A `PerCaller` holder keeps one lease open
|
||||||
/// time; a Persona turn holds one lease per live invocation, one at a time.
|
/// per caller at a time; a `PerInvocation` holder keeps one lease open per live
|
||||||
|
/// unit invocation at a time.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub enum LeaseTurn {
|
pub enum LeaseScope {
|
||||||
SelfRun,
|
PerCaller,
|
||||||
PersonaTurn,
|
PerInvocation,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What an admitted lease holds.
|
/// What an admitted lease holds.
|
||||||
|
|
@ -34,8 +36,8 @@ pub struct LeaseGrant {
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum LeaseRefusal {
|
pub enum LeaseRefusal {
|
||||||
UnknownCaller,
|
UnknownCaller,
|
||||||
/// A Self run: the caller holds a Self lease now. A Persona turn: this
|
/// `PerCaller`: the caller holds a per-caller lease now. `PerInvocation`:
|
||||||
/// invocation holds a lease now.
|
/// this invocation holds a lease now.
|
||||||
Busy,
|
Busy,
|
||||||
/// The provider is refusing right now and has said until when.
|
/// The provider is refusing right now and has said until when.
|
||||||
ProviderRejected,
|
ProviderRejected,
|
||||||
|
|
@ -49,16 +51,16 @@ pub enum LeaseAdmission {
|
||||||
|
|
||||||
impl TransportService {
|
impl TransportService {
|
||||||
/// Grants `caller_runtime_id` a lease for the unit invocation
|
/// Grants `caller_runtime_id` a lease for the unit invocation
|
||||||
/// `invocation_id` until `expires_at_unix_ms`. A Self run's lease is
|
/// `invocation_id` until `expires_at_unix_ms`. A `PerCaller` lease is
|
||||||
/// `lease:<invocation>` and one is open per caller; a Persona turn's is
|
/// `lease:<invocation>` and one is open per caller; a `PerInvocation` lease
|
||||||
/// `lease:<invocation>:persona`, one open per invocation; neither blocks
|
/// is `lease:<invocation>:invocation`, one open per invocation; neither
|
||||||
/// the other. A lease takes no request slot. `plan` is the backend's plan
|
/// blocks the other. A lease takes no request slot. `plan` is the backend's
|
||||||
/// quota as it stands: a provider that is refusing right now refuses the
|
/// plan quota as it stands: a provider that is refusing right now refuses
|
||||||
/// lease. A lease past its expiry no longer holds anything.
|
/// the lease. A lease past its expiry no longer holds anything.
|
||||||
pub fn begin_lease(
|
pub fn begin_lease(
|
||||||
&mut self,
|
&mut self,
|
||||||
caller_runtime_id: &str,
|
caller_runtime_id: &str,
|
||||||
turn: LeaseTurn,
|
scope: LeaseScope,
|
||||||
invocation_id: &str,
|
invocation_id: &str,
|
||||||
expires_at_unix_ms: u64,
|
expires_at_unix_ms: u64,
|
||||||
now_unix_ms: u64,
|
now_unix_ms: u64,
|
||||||
|
|
@ -68,9 +70,9 @@ impl TransportService {
|
||||||
return Ok(LeaseAdmission::Refused(LeaseRefusal::UnknownCaller));
|
return Ok(LeaseAdmission::Refused(LeaseRefusal::UnknownCaller));
|
||||||
}
|
}
|
||||||
require_id(invocation_id, "invocation_id")?;
|
require_id(invocation_id, "invocation_id")?;
|
||||||
let suffix = match turn {
|
let suffix = match scope {
|
||||||
LeaseTurn::SelfRun => "",
|
LeaseScope::PerCaller => "",
|
||||||
LeaseTurn::PersonaTurn => PERSONA_SUFFIX,
|
LeaseScope::PerInvocation => INVOCATION_SUFFIX,
|
||||||
};
|
};
|
||||||
let lease_id = format!("{LEASE_PREFIX}{invocation_id}{suffix}");
|
let lease_id = format!("{LEASE_PREFIX}{invocation_id}{suffix}");
|
||||||
if lease_id.len() > MAX_IDENTITY_BYTES {
|
if lease_id.len() > MAX_IDENTITY_BYTES {
|
||||||
|
|
@ -82,22 +84,22 @@ impl TransportService {
|
||||||
caller_runtime_id: caller_runtime_id.to_string(),
|
caller_runtime_id: caller_runtime_id.to_string(),
|
||||||
request_id: lease_id.clone(),
|
request_id: lease_id.clone(),
|
||||||
};
|
};
|
||||||
let busy = match turn {
|
let busy = match scope {
|
||||||
LeaseTurn::SelfRun => self.leases.iter().any(|(held, lease)| {
|
LeaseScope::PerCaller => self.leases.iter().any(|(held, lease)| {
|
||||||
lease.turn == LeaseTurn::SelfRun && held.caller_runtime_id == caller_runtime_id
|
lease.scope == LeaseScope::PerCaller && held.caller_runtime_id == caller_runtime_id
|
||||||
}),
|
}),
|
||||||
LeaseTurn::PersonaTurn => self.leases.contains_key(&identity),
|
LeaseScope::PerInvocation => self.leases.contains_key(&identity),
|
||||||
};
|
};
|
||||||
if busy {
|
if busy {
|
||||||
return Ok(LeaseAdmission::Refused(LeaseRefusal::Busy));
|
return Ok(LeaseAdmission::Refused(LeaseRefusal::Busy));
|
||||||
}
|
}
|
||||||
if provider_rejects(plan, now_unix_ms) {
|
if plan_rejects(plan, now_unix_ms) {
|
||||||
return Ok(LeaseAdmission::Refused(LeaseRefusal::ProviderRejected));
|
return Ok(LeaseAdmission::Refused(LeaseRefusal::ProviderRejected));
|
||||||
}
|
}
|
||||||
self.leases.insert(
|
self.leases.insert(
|
||||||
identity,
|
identity,
|
||||||
LiveLease {
|
LiveLease {
|
||||||
turn,
|
scope,
|
||||||
expires_at_unix_ms,
|
expires_at_unix_ms,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
@ -121,16 +123,28 @@ mod tests {
|
||||||
use crate::readout::PlanQuota;
|
use crate::readout::PlanQuota;
|
||||||
|
|
||||||
const CALLER: &str = "eureka";
|
const CALLER: &str = "eureka";
|
||||||
|
const CALLER_TWO: &str = "caller-two";
|
||||||
const KEY: &str = "lease-distinct-test-key";
|
const KEY: &str = "lease-distinct-test-key";
|
||||||
|
const KEY_TWO: &str = "lease-distinct-test-key-two";
|
||||||
const NOW: u64 = 7_200_500;
|
const NOW: u64 = 7_200_500;
|
||||||
|
|
||||||
fn open(store: &TestStore) -> TransportService {
|
fn open(store: &TestStore) -> TransportService {
|
||||||
TransportService::open(
|
TransportService::open(
|
||||||
&store.path,
|
&store.path,
|
||||||
"fixture-sse",
|
crate::fixtures::routes(),
|
||||||
[
|
[
|
||||||
CallerAdmission::new(CALLER, KEY, 1, ["gpt-5.4".to_string()], 1, 65_536, 32_768)
|
CallerAdmission::new(CALLER, KEY, 1, ["gpt-5.4".to_string()], 1, 65_536, 32_768)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
|
CallerAdmission::new(
|
||||||
|
CALLER_TWO,
|
||||||
|
KEY_TWO,
|
||||||
|
1,
|
||||||
|
["gpt-5.4".to_string()],
|
||||||
|
1,
|
||||||
|
65_536,
|
||||||
|
32_768,
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
],
|
],
|
||||||
5_000,
|
5_000,
|
||||||
)
|
)
|
||||||
|
|
@ -155,17 +169,17 @@ mod tests {
|
||||||
|
|
||||||
fn lease_in(
|
fn lease_in(
|
||||||
service: &mut TransportService,
|
service: &mut TransportService,
|
||||||
turn: LeaseTurn,
|
scope: LeaseScope,
|
||||||
run: &str,
|
run: &str,
|
||||||
plan: &PlanQuotaSnapshot,
|
plan: &PlanQuotaSnapshot,
|
||||||
) -> LeaseAdmission {
|
) -> LeaseAdmission {
|
||||||
service
|
service
|
||||||
.begin_lease(CALLER, turn, run, NOW + 60_000, NOW, plan)
|
.begin_lease(CALLER, scope, run, NOW + 60_000, NOW, plan)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lease(service: &mut TransportService, run: &str) -> LeaseAdmission {
|
fn lease(service: &mut TransportService, run: &str) -> LeaseAdmission {
|
||||||
lease_in(service, LeaseTurn::SelfRun, run, &none())
|
lease_in(service, LeaseScope::PerCaller, run, &none())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn granted(admission: LeaseAdmission) -> LeaseGrant {
|
fn granted(admission: LeaseAdmission) -> LeaseGrant {
|
||||||
|
|
@ -186,7 +200,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_caller_holds_one_self_lease_at_a_time() {
|
fn a_per_caller_holder_holds_one_lease_at_a_time() {
|
||||||
let store = TestStore::new();
|
let store = TestStore::new();
|
||||||
let mut service = open(&store);
|
let mut service = open(&store);
|
||||||
granted(lease(&mut service, "run-1"));
|
granted(lease(&mut service, "run-1"));
|
||||||
|
|
@ -198,6 +212,19 @@ mod tests {
|
||||||
lease(&mut service, "run-1"),
|
lease(&mut service, "run-1"),
|
||||||
LeaseAdmission::Refused(LeaseRefusal::Busy)
|
LeaseAdmission::Refused(LeaseRefusal::Busy)
|
||||||
);
|
);
|
||||||
|
// Distinct callers hold independent PerCaller leases.
|
||||||
|
granted(
|
||||||
|
service
|
||||||
|
.begin_lease(
|
||||||
|
CALLER_TWO,
|
||||||
|
LeaseScope::PerCaller,
|
||||||
|
"run-other",
|
||||||
|
NOW + 60_000,
|
||||||
|
NOW,
|
||||||
|
&none(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -223,14 +250,21 @@ mod tests {
|
||||||
let mut service = open(&store);
|
let mut service = open(&store);
|
||||||
granted(
|
granted(
|
||||||
service
|
service
|
||||||
.begin_lease(CALLER, LeaseTurn::SelfRun, "run-1", NOW + 10, NOW, &none())
|
.begin_lease(
|
||||||
|
CALLER,
|
||||||
|
LeaseScope::PerCaller,
|
||||||
|
"run-1",
|
||||||
|
NOW + 10,
|
||||||
|
NOW,
|
||||||
|
&none(),
|
||||||
|
)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
service
|
service
|
||||||
.begin_lease(
|
.begin_lease(
|
||||||
CALLER,
|
CALLER,
|
||||||
LeaseTurn::SelfRun,
|
LeaseScope::PerCaller,
|
||||||
"run-2",
|
"run-2",
|
||||||
NOW + 99,
|
NOW + 99,
|
||||||
NOW + 9,
|
NOW + 9,
|
||||||
|
|
@ -244,7 +278,7 @@ mod tests {
|
||||||
service
|
service
|
||||||
.begin_lease(
|
.begin_lease(
|
||||||
CALLER,
|
CALLER,
|
||||||
LeaseTurn::SelfRun,
|
LeaseScope::PerCaller,
|
||||||
"run-2",
|
"run-2",
|
||||||
NOW + 99,
|
NOW + 99,
|
||||||
NOW + 10,
|
NOW + 10,
|
||||||
|
|
@ -262,7 +296,7 @@ mod tests {
|
||||||
service
|
service
|
||||||
.begin_lease(
|
.begin_lease(
|
||||||
"stranger",
|
"stranger",
|
||||||
LeaseTurn::SelfRun,
|
LeaseScope::PerCaller,
|
||||||
"run-1",
|
"run-1",
|
||||||
NOW + 1,
|
NOW + 1,
|
||||||
NOW,
|
NOW,
|
||||||
|
|
@ -274,22 +308,22 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_persona_holds_one_lease_per_invocation_and_never_blocks_the_self_lease() {
|
fn a_per_invocation_holder_holds_one_lease_per_invocation_and_never_blocks_per_caller() {
|
||||||
let store = TestStore::new();
|
let store = TestStore::new();
|
||||||
let mut service = open(&store);
|
let mut service = open(&store);
|
||||||
let persona = |service: &mut TransportService, run: &str| {
|
let per_invocation = |service: &mut TransportService, run: &str| {
|
||||||
lease_in(service, LeaseTurn::PersonaTurn, run, &none())
|
lease_in(service, LeaseScope::PerInvocation, run, &none())
|
||||||
};
|
};
|
||||||
let first = granted(persona(&mut service, "turn-1"));
|
let first = granted(per_invocation(&mut service, "turn-1"));
|
||||||
assert_eq!(first.lease_id, "lease:turn-1:persona");
|
assert_eq!(first.lease_id, "lease:turn-1:invocation");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
persona(&mut service, "turn-1"),
|
per_invocation(&mut service, "turn-1"),
|
||||||
LeaseAdmission::Refused(LeaseRefusal::Busy)
|
LeaseAdmission::Refused(LeaseRefusal::Busy)
|
||||||
);
|
);
|
||||||
granted(persona(&mut service, "turn-2"));
|
granted(per_invocation(&mut service, "turn-2"));
|
||||||
granted(lease(&mut service, "turn-1"));
|
granted(lease(&mut service, "turn-1"));
|
||||||
service.end_lease(CALLER, &first.lease_id);
|
service.end_lease(CALLER, &first.lease_id);
|
||||||
granted(persona(&mut service, "turn-1"));
|
granted(per_invocation(&mut service, "turn-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -298,7 +332,7 @@ mod tests {
|
||||||
let mut service = open(&store);
|
let mut service = open(&store);
|
||||||
let rejected = window(1_000, "rejected", NOW + 5_000);
|
let rejected = window(1_000, "rejected", NOW + 5_000);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
lease_in(&mut service, LeaseTurn::SelfRun, "run-1", &rejected),
|
lease_in(&mut service, LeaseScope::PerCaller, "run-1", &rejected),
|
||||||
LeaseAdmission::Refused(LeaseRefusal::ProviderRejected)
|
LeaseAdmission::Refused(LeaseRefusal::ProviderRejected)
|
||||||
);
|
);
|
||||||
let call = |service: &mut TransportService, now: u64, plan: &PlanQuotaSnapshot| {
|
let call = |service: &mut TransportService, now: u64, plan: &PlanQuotaSnapshot| {
|
||||||
|
|
@ -313,8 +347,9 @@ mod tests {
|
||||||
&security(KEY),
|
&security(KEY),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let TransportAdmission::Reply(reply) =
|
let TransportAdmission::Reply(reply) = service
|
||||||
service.begin(&sealed, now, plan, 1 << 20).unwrap()
|
.begin(&sealed, now, Some(("fixture-sse", plan)), 1 << 20)
|
||||||
|
.unwrap()
|
||||||
else {
|
else {
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
|
|
@ -338,7 +373,7 @@ mod tests {
|
||||||
service
|
service
|
||||||
.begin_lease(
|
.begin_lease(
|
||||||
CALLER,
|
CALLER,
|
||||||
LeaseTurn::SelfRun,
|
LeaseScope::PerCaller,
|
||||||
"run-1",
|
"run-1",
|
||||||
NOW + 9_000,
|
NOW + 9_000,
|
||||||
NOW + 5_000,
|
NOW + 5_000,
|
||||||
|
|
@ -354,11 +389,16 @@ mod tests {
|
||||||
let store = TestStore::new();
|
let store = TestStore::new();
|
||||||
let mut service = open(&store);
|
let mut service = open(&store);
|
||||||
let full = window(999, "allowed", NOW + 5_000);
|
let full = window(999, "allowed", NOW + 5_000);
|
||||||
granted(lease_in(&mut service, LeaseTurn::SelfRun, "run-1", &full));
|
granted(lease_in(
|
||||||
|
&mut service,
|
||||||
|
LeaseScope::PerCaller,
|
||||||
|
"run-1",
|
||||||
|
&full,
|
||||||
|
));
|
||||||
let warned = window(1_000, "allowed_warning", NOW + 5_000);
|
let warned = window(1_000, "allowed_warning", NOW + 5_000);
|
||||||
granted(lease_in(
|
granted(lease_in(
|
||||||
&mut service,
|
&mut service,
|
||||||
LeaseTurn::PersonaTurn,
|
LeaseScope::PerInvocation,
|
||||||
"turn-1",
|
"turn-1",
|
||||||
&warned,
|
&warned,
|
||||||
));
|
));
|
||||||
|
|
@ -371,30 +411,37 @@ mod tests {
|
||||||
let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len());
|
let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len());
|
||||||
let grant = granted(lease(&mut service, &longest));
|
let grant = granted(lease(&mut service, &longest));
|
||||||
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES);
|
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES);
|
||||||
assert!(lease_try(&mut service, LeaseTurn::SelfRun, &format!("{longest}r")).is_err());
|
assert!(lease_try(&mut service, LeaseScope::PerCaller, &format!("{longest}r")).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_persona_invocation_id_leaves_room_for_its_suffix() {
|
fn a_per_invocation_id_leaves_room_for_its_suffix() {
|
||||||
let store = TestStore::new();
|
let store = TestStore::new();
|
||||||
let mut service = open(&store);
|
let mut service = open(&store);
|
||||||
let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len() - PERSONA_SUFFIX.len());
|
let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len() - INVOCATION_SUFFIX.len());
|
||||||
let grant = granted(lease_in(
|
let grant = granted(lease_in(
|
||||||
&mut service,
|
&mut service,
|
||||||
LeaseTurn::PersonaTurn,
|
LeaseScope::PerInvocation,
|
||||||
&longest,
|
&longest,
|
||||||
&none(),
|
&none(),
|
||||||
));
|
));
|
||||||
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES);
|
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES);
|
||||||
assert!(lease_try(&mut service, LeaseTurn::PersonaTurn, &format!("{longest}r")).is_err());
|
assert!(
|
||||||
|
lease_try(
|
||||||
|
&mut service,
|
||||||
|
LeaseScope::PerInvocation,
|
||||||
|
&format!("{longest}r")
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lease_try(
|
fn lease_try(
|
||||||
service: &mut TransportService,
|
service: &mut TransportService,
|
||||||
turn: LeaseTurn,
|
scope: LeaseScope,
|
||||||
run: &str,
|
run: &str,
|
||||||
) -> Result<LeaseAdmission, ServiceError> {
|
) -> Result<LeaseAdmission, ServiceError> {
|
||||||
service.begin_lease(CALLER, turn, run, NOW + 60_000, NOW, &none())
|
service.begin_lease(CALLER, scope, run, NOW + 60_000, NOW, &none())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -415,13 +462,13 @@ mod tests {
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
service.begin(&sealed, NOW, &none(), 1 << 20).unwrap(),
|
service.begin(&sealed, NOW, None, 1 << 20).unwrap(),
|
||||||
TransportAdmission::Execute(_)
|
TransportAdmission::Execute(_)
|
||||||
));
|
));
|
||||||
// And a call in flight does not make the caller busy for a lease.
|
// And a call in flight does not make the caller busy for a lease.
|
||||||
granted(lease_in(
|
granted(lease_in(
|
||||||
&mut service,
|
&mut service,
|
||||||
LeaseTurn::PersonaTurn,
|
LeaseScope::PerInvocation,
|
||||||
"turn-1",
|
"turn-1",
|
||||||
&none(),
|
&none(),
|
||||||
));
|
));
|
||||||
|
|
|
||||||
|
|
@ -42,10 +42,6 @@ impl ProviderBackend for RecordingBackend {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn provider(&self) -> &str {
|
|
||||||
PROVIDER
|
|
||||||
}
|
|
||||||
|
|
||||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
self.executions.fetch_add(1, Ordering::SeqCst);
|
self.executions.fetch_add(1, Ordering::SeqCst);
|
||||||
self.seen.lock().unwrap().push(call.request().clone());
|
self.seen.lock().unwrap().push(call.request().clone());
|
||||||
|
|
@ -114,7 +110,9 @@ fn start_with(backend: Arc<dyn ProviderBackend>, max_concurrent: usize) -> Conne
|
||||||
socket_timeout_ms: 5_000,
|
socket_timeout_ms: 5_000,
|
||||||
max_expiry_skew_ms: 300_000,
|
max_expiry_skew_ms: 300_000,
|
||||||
};
|
};
|
||||||
thread::spawn(move || serve(listener, limits, vec![admission], &store, backend));
|
let routes =
|
||||||
|
ProviderRoutes::new([("claude-opus-4-5".to_string(), PROVIDER.to_string())]).unwrap();
|
||||||
|
thread::spawn(move || serve(listener, limits, vec![admission], &store, routes, backend));
|
||||||
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap()
|
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -279,10 +277,6 @@ impl ProviderBackend for TamperingBackend {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn provider(&self) -> &str {
|
|
||||||
PROVIDER
|
|
||||||
}
|
|
||||||
|
|
||||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||||
let mut result = call.transported(
|
let mut result = call.transported(
|
||||||
vec![TransportEvent {
|
vec![TransportEvent {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue