Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
Meta Vens
f3a660e000 test(claude-connector): pin connector_config.v4 tag, parser edges, and README
- Pin ClaudeConnectorConfig::TYPE == gamecult.model_connector.connector_config.v4
  and test a full 12-field connector_config.v3 document failing closed with
  ConfigError::Store.
- Cover >6 colon segments rejection and uppercase/mixed-case TUE/SaT weekday
  parsing in config_init_and_add_model_price_flags.
- Update README.md status and backend descriptions to reflect live
  OpenAiChatBackend, lease run, and RouterBackend as the sole ProviderBackend.
2026-12-06 06:35:12 +01:00
Meta Vens
e074b58e4d test(claude-connector): replay exact TransportInvocation in priced_serve test 2026-12-06 05:53:17 +01:00
Meta Vens
80a19bf818 fix(claude-connector): fix TransportOutcome::Completed and duplicate V3Config in tests 2026-12-06 05:52:02 +01:00
Meta Vens
fcad6ed3f7 feat(claude-connector): wire connector_config.v4 ModelRow.price, CLI flags, and lock-free SpendSnapshot readout
- Bump ClaudeConnectorConfig CultCache type from connector_config.v3 to
  connector_config.v4 and add ModelRow.price: Option<PriceRow>, validated
  solely through PriceRow::validate() in ClaudeConnectorConfig::validate().
- Wire ModelRow.price into ProviderRoutes::with_prices in routes_for and
  extract opened.spend_snapshot() before Mutex wrapping in serve_bound_with
  so start_leases -> serve_leases -> Lender -> lease::readout publishes
  live communal monthly spend without taking service.lock().
- Add --price-input, --price-cache-read, --price-cache-write, --price-output,
  and repeated --price-band flags to config init and add-model, requiring all
  four base rate flags whenever pricing or band flags are given and never
  echoing input values on error.
- Remove obsolete --price refusal from config_document::the_dollar_flags_are_not_flags,
  add v3 refusal / v4 price / PriceRow / CLI / lease / E2E tests, and update README.md.
2026-12-06 05:50:58 +01:00
Meta Vens
3da1471d71 test(model-connector): use CallerModelSpend.caller in identity bounds test 2026-12-06 05:12:30 +01:00
Meta Vens
b645fcb198 test(model-connector): pin complete() batch atomicity and MonthlySpendRecord identity bounds
- Fix FlakyStore::push_all to upsert staged entries into self.held rather than replacing the map.
- Add complete_commits_replay_and_spend_in_one_atomic_batch proving complete() lands ReplayRecord and MonthlySpendRecord in one batch write and preserves prior entries on later commits.
- Add monthly_spend_record_identity_length_bounds pinning 256-byte accepted and 257-byte rejected caller/model lengths in TransportService::with_store.
2026-12-06 05:11:42 +01:00
Meta Vens
fdbbe4d037 test(model-connector): pin 2000-03-01 and 2100-03-01 UTC calendar boundaries 2026-12-06 04:44:26 +01:00
Meta Vens
fb3ce4d21d test(model-connector): kill remaining 7 price.rs mutant survivors and harden spend validation tests 2026-12-06 04:28:08 +01:00
Meta Vens
a6fb8c4f20 test(model-connector): clone env1 before narrowed replay check 2026-12-06 04:09:37 +01:00
Meta Vens
30d08c6b53 test(model-connector): use 2000-byte frame for narrowed replay test 2026-12-06 04:09:08 +01:00
Meta Vens
bbe2d16d0b test(model-connector): disambiguate fixtures::routes() in spend test 2026-12-06 04:08:01 +01:00
Meta Vens
5f69e17075 style(model-connector): rustfmt touched files 2026-12-06 04:07:35 +01:00
Meta Vens
e0256af325 test(model-connector): commit regenerated v5 goldens, schemas, and lease readout 2026-12-06 04:06:58 +01:00
Meta Vens
31c02a26dc test(model-connector): read live schema_for in published_schemas field check 2026-12-06 04:04:48 +01:00
Meta Vens
5f6efd3126 test(model-connector): avoid regen race in wire_golden_v5 2026-12-06 04:04:15 +01:00
Meta Vens
38699f3d3b feat(model-connector): v5 wire contract, PriceRow math, and atomic monthly spend totals
Delete v4 golden suite/fixtures, bump contract schemas to v5 and
usage_readout to v2, add pure-integer PriceRow cost math, persist
MonthlySpendRecord atomically with ReplayRecord via put_prepared_batch,
and keep all dollar/cost figures non-gating.
2026-12-06 03:04:10 +01:00
Meta Vens
4dc182facf kill 6 non-equivalent survivors in openai_chat and router tests 2026-12-04 02:09:35 +01:00
Meta Vens
d65fb21870 write caller.key before running config check in config_document test 2026-12-04 01:54:33 +01:00
Meta Vens
4e3df9e114 fix compile errors in messages.rs, openai_chat.rs, and router.rs tests 2026-12-04 01:53:12 +01:00
Meta Vens
73aea04fb7 cut-mp-openai-chat: add OpenAiChat backend, generic reasoning capture, and shared http
Extract shared ureq client construction (with .proxy(None) and
.max_redirects(0)), credential reading, failure classification, and secret
redaction from messages.rs into crate::http. Add ModelRow::thinking_active
so unset_effort "none" counts as thinking-inactive for WithoutThinking.

Implement OpenAiChatBackend with generic capture and byte-exact replay of
non-standard message/tool_call fields into one ReasoningState, collapsed
assistant turns, role: tool messages, finish_reason and usage mapping,
and 402/spent-balance/insufficient_quota -> Authentication classification.

Remove temporary Cut 2a OpenAiChat refusal arms in daemon.rs, router.rs,
and tests/config_document.rs, and wire OpenAiChat into RouterBackend and
daemon readiness/serve.
2026-12-04 01:51:24 +01:00
Meta Vens
c1650d5271 Remove unused ClaudeCodeBackend import in daemon.rs 2026-12-04 01:13:28 +01:00
Meta Vens
43085cf5fe Kill forced_tool_choice negation survivor in ClaudeCodeBackend::run_model 2026-12-04 01:11:23 +01:00
Meta Vens
4796f917ac Fix test mock HTTP body read in router and parallel_tool_calls in messages tests 2026-12-04 01:00:12 +01:00
Meta Vens
81f1734fd1 Fix compilation in daemon, backend tests, and messages tests 2026-12-04 00:59:29 +01:00
Meta Vens
0904b2eb31 Cut 2b: add RouterBackend, parameterize two wires, and delete hardcoded constants
- Extract TokenSource, CredentialTokenSource, and credential_ready into
  crates/claude-connector/src/credential.rs.
- Add RouterBackend in crates/claude-connector/src/router.rs as the sole
  ProviderBackend in claude-connector, dispatching by ModelRow, rewriting
  wire_request.model to row.upstream while keeping caller-facing model and
  entry.id on receipts, and scoping plan_quota() to ClaudeCodeCli.
- Parameterize ClaudeCodeBackend (provider_id, meter_model, row efforts,
  output_schema, forced_tool_choice) and MessagesBackend (provider_id,
  base_url, optional key_credential, row policies).
- Delete config::PROVIDER, messages::PROVIDER, messages::ENDPOINT,
  rejects_forced_tool_choice, METER_MODEL, launch::effort, direct
  ProviderBackend impls on wire backends, and serve_config_with
  single-entry guards.
- Add unit and loopback integration tests for multi-entry Messages,
  keyless loopback, ModelRow policies, mixed CLI+Messages routing with
  bidirectional ReasoningState isolation and plan_quota scoping, and
  serve readiness failure without secret leakage.
2026-12-04 00:58:29 +01:00
Meta Vens
c0386bbcd5 claude-connector: bound serve_config_with fail-closed test wait
Run negative serve_config_with cases on a bounded thread so a mutant that
enters serve_service fails in seconds rather than hanging until timeout.
2026-12-04 00:22:47 +01:00
Meta Vens
0098e3d23d claude-connector: pin validate_base_url edges, validation bounds, EffortMap::get, and bool_flag
Add negative base_url fixtures (+80/+8080, :0, path whitespace/control/
query/fragment/backslash, malformed hostnames) and validation/CLI tests
for duplicate and empty/whitespace provider/model ids, untrimmed upstream
and unset_effort, meter_model validity, zero HTTP/CLI bounds, EffortMap::get,
and Flags::bool_flag false/invalid handling.
2026-12-04 00:13:36 +01:00
Meta Vens
0d9b7eec70 claude-connector: guard AnthropicMessages endpoint and credential in serve_config_with
Require base_url == messages::ENDPOINT and entry.credential.is_some() in
Cut 2a single-entry serve_config_with, and return None from
messages_config_for when credential is absent instead of synthesizing an
empty credential string. Add behavioural tests pinning fail-closed
Unusable("providers") on custom base_url and keyless loopback entries.
2026-12-04 00:13:36 +01:00
Meta Vens
cf30634d3d claude-connector: avoid duplicating pre-existing OPUS row in allowed_models test 2026-12-03 23:25:34 +01:00
Meta Vens
6d22c60529 claude-connector: drop Ok Vec<CallerAdmission> before unwrap_err in readiness_of_in test 2026-12-03 23:24:46 +01:00
Meta Vens
8c320d4626 claude-connector: format v3 config changes with rustfmt 2026-12-03 23:23:42 +01:00
Meta Vens
a7ac40d59a claude-connector: add v3 multi-provider config, validation, readiness, and CLI verbs
Replace the v2 connector config and global ClaudeAuth switch with the
gamecult.model_connector.connector_config.v3 schema (ProviderEntry,
ProviderWire, ModelRow, EffortMap, ForcedToolChoice, OutputSchemaSupport).
Delete ClaudeAuth, MODEL_PREFIX, has_model_id_form, Flags::auth,
--auth, and --token-credential.

Add v3 validation (loopback-http or https base URLs, non-loopback
credentials, unique credentials and ids, <=1 ClaudeCodeCli, refuse
OpenAiChat until Cut 3, allowed_models subset of configured models),
per-entry readiness_of_in returning ConfigError::UnusableEntry without
leaking secrets, and config init/add-provider/add-model CLI verbs.
2026-12-03 23:22:03 +01:00
Meta Vens
0b2f3fc3e3 fix(mp-provider-per-model): bind test result before moving ExecutionClaim 2026-12-03 22:53:05 +01:00
Meta Vens
3dfd3125cb fix(mp-provider-per-model): resolve replay before live routes and test plan_quota default
- Move ReplayRecord lookup before allowed_models, routes.provider_for,
  max_output_tokens, and partition_reasoning in TransportService::begin
  so route edits or removals never refuse or alter recorded replies.
- Pass the already-derived foreign_reasoning_dropped into seal_stand_in
  (from the sealed completed response on narrowed replay, and from the
  claim receipt in complete) so seal_stand_in never consults routes.
- Add B1/B2/B3 replay tests under route removal, route switch with
  in-flight reasoning state, and narrowed-frame stand-in replay.
- Assert CountingBackend::new(true).plan_quota() == None in serve tests.
2026-12-03 22:52:04 +01:00
Meta Vens
bea242eb58 chore(mp-provider-per-model): remove unused PlanQuotaSnapshot import in backend tests 2026-12-03 22:28:17 +01:00
Meta Vens
8c45189ae8 cut(mp-provider-per-model): derive provider tag per model via ProviderRoutes
Replace the service-wide TransportService.provider and ProviderBackend::provider()
with validated ProviderRoutes (model -> provider tag) owned by TransportService.
Carry the owning provider tag on ProviderBackend::plan_quota() so provider_rejects
refuses only models routed to that plan owner, while factoring plan_rejects for
begin_lease. Temporarily populate ProviderRoutes in claude-connector daemon from
caller allowed_models and auth mode until Cut 2 introduces v3 tables.
2026-12-03 22:20:04 +01:00
Meta Vens
92e23ea3ce Fix unused mut warning and strengthen lease_run and lease tests
Remove unused mut on child in tests/lease_run.rs and align touched lines
with rustfmt. Add tests for zero TTL, chunked and max-size frame reads,
chunked trailing bytes, signal exit code 128 + signal, invalid lease run
CLI flags, and independent PerCaller leases across distinct callers.
2026-12-03 21:26:35 +01:00
Meta Vens
38f66dd29c Generalize credential lease and add lease run launcher
Replace topology-tied lease naming (LeaseTurn, LeaseCaller::unit(),
is_unit_instance, add-lease-caller, mind-self/mind-persona/swarm strings)
with LeaseScope (PerCaller, PerInvocation), LeaseHolder / LeaseHolderConfig
carrying configured provider, full systemd unit name, and scope, and
config add-lease-holder.

Add claude_connector::lease_run and the  CLI
subcommand to request a lease over the unix socket, receive the token pipe
via SCM_RIGHTS, place it on fd 3 with CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3,
hold the socket open until the child exits, and return its exit status.
2026-12-03 21:07:38 +01:00
Meta Vens
898779f4dd claude-connector: with cache retention, breakpoints after the tools and the system prompt too
A cache entry is written only where a breakpoint sits. With one breakpoint on
the last message, a later turn whose messages differ found no entry for the
byte-stable tools and system prefix, so Ghostlight's DM turns resent it
uncached each turn. The last tool and the system block now carry the same
mark as the last message: three of the API's four breakpoints.

Asked by Weksa's Self for Ghostlight (ded2ede sets cache_retention per lane).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 06:26:46 +01:00
edf2f8e03c claude-connector: Messages API backend for API-key auth (tools, thinking, caching) (#4) 2026-11-29 20:25:20 +00:00
80c1fc6a69 claude-connector: authenticate the Claude child with an API key (config auth field) (#3) 2026-11-29 17:36:26 +00:00
Meta Vens
3f87b19a2d claude-connector meter: expired-week test on its own rig
A reading older than the one held is dropped, so the expired week needs a
fresh cell.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:24:20 +01:00
Meta Vens
f52eef1657 claude-connector meter: one snapshot per tick, doc names the per-refresh line, value tests
The Read state and its decision come from one snapshot. A test moves the
reading (60 then 75, reset changing) and expires the week through tick.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:21:24 +01:00
Meta Vens
e80e522c10 claude-connector meter: each refresh of the weekly reading logs the reading
State::Read carries the week window's permille and reset; report writes every
Read, so a day's meter delta is last minus first in the journal. Idle, Failed
and Unread keep once-per-change logging.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:04:07 +01:00
9d0f4b400c Merge pull request 'claude-connector ask: no-tools completion CLI' (#2) from eureka-substrate/notool-ask-cli into main 2026-11-11 08:15:48 +00:00
2a65c4e7a2 ask: the binary reads --system-file through the capped reader
main.rs still called read_to_string, leaving read_system_file dead. Binary-level
tests cover a FIFO, /dev/zero, 64KiB+1 and exactly 64KiB.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 08:14:44 +00:00
42a157b049 ask: guard key and system file reads, name stdin/stdout/connection causes, widen tests
Key file: nonblocking open, regular file only, 1024-byte bound, refuse
group/world-readable. --system-file capped at 64 KiB. Tests drive a forced
tools request through the real serve loop and the real claude backend.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 08:10:53 +00:00
c47597b421 claude-connector: add ask, a no-tools completion CLI over ConnectorClient
Prompt on stdin, answer on stdout; no tools, cwd or endpoint options, key read
from a file, one-line stderr cause on every failure.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 07:56:08 +00:00
61cc59d9a0 Merge pull request 'Lease socket answers a usage readout' (#1) from eureka-body/lease-usage-readout into main 2026-11-06 22:55:17 +00:00
Meta Vens
0282244114 lease tests: rustfmt the renamed imports (Soul s2 test-imports-unformatted)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 23:55:01 +01:00
Hands
51982b7f63 lease readouts: a pool of their own, a refusal over it, the arm's promises pinned, the request type named for the lease
Readouts no longer take a lease's connection slot: the accept loop admits
max_connections + READOUT_CONNECTIONS, a lease holds one of max_connections
after it is read, a readout one of READOUT_CONNECTIONS, and a readout over its
limit is refused Busy rather than dropped. Socket tests hold the service lock
and a metered cell across readouts (no asking, no week wait, no lock), flood
the readout pool beside leases, and pin the refusal. The new public request
type is LeaseUsageReadoutRequest so it no longer shares a name with the kit's
EnvelopeKind::UsageReadoutRequest; wire bytes and fixtures are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 23:31:24 +01:00
Meta Vens
254cf83d9d lease readout tests: drop the integration test that needs a crate-private meter hook (the unit test owns it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 22:59:12 +01:00
Meta Vens
8331859537 lease_v2: pin the usage readout request and answer frames
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 22:58:15 +01:00
Meta Vens
6e87cf2e6c lease socket: a usage readout from the one QuotaCell, no lease, no caller check, no token, no meter wake
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 22:55:06 +01:00
Meta Vens
549962cb8a quota meter: the weekly reading comes from the CLI's own rate-limit event; while a lease is live and the reading is stale the connector makes the smallest real call. The usage poll and its HTTP client go: the setup token can never reach that endpoint (squash of eureka-body/quota-meter-stream 7d4c1bf..c298d9d; Soul s4-s5)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:12:31 +01:00
Meta Vens
7d4c1bf56e usage-meter-poll: gate fixes: the timeout is read per request, serve has a refusal test, the RFC 850 guard is pinned
The timeout field was read only by a test (dead_code under -D warnings), so
ask() applies it to each request. The serve wrapper is reached by a
subprocess refusal test (no network); the serve test fails inside 30 s
instead of hanging; "Wednesday 21-Oct-26 ..." (no comma) is refused.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:30:55 +01:00
Meta Vens
8fb8b5a71d usage-meter-poll: the serve test asks a loopback fake, never the provider (finding serve-test-asks-real-provider)
serve_config is the public wrapper over a crate-private serve_config_with
that takes the usage client; the test runs it in-process against a fake and
asserts the fake received GET /api/oauth/usage with the bearer. The endpoint
is not a document field or env, so whoever writes the config cannot redirect
the token. The subprocess test that reached api.anthropic.com is deleted.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:17:08 +01:00
Meta Vens
f242290ca5 usage-meter-poll: pin what the production client is built with (finding new-client-timeout-unpinned)
UsageClient carries its timeout and url; UsageClient::production() is what
start() builds, and the test asserts that client's url and 10 s timeout as
spec r2 says, replacing a 1..=60 s bound no rule names.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:17:08 +01:00
Meta Vens
481428a7ce usage-meter-poll: Retry-After reads all three HTTP-date forms (finding retry-after-obsolete-date-forms)
RFC 9110 10.2.3 makes a recipient accept IMF-fixdate, RFC 850 and asctime;
the last two read as absent and the poll asked again at the floor. The
two-digit RFC 850 year more than 50 years ahead is the latest past year.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:17:08 +01:00
Meta Vens
e17ef16d48 usage-meter-poll: a subprocess test that serve --config starts the poll
Spawns the claude-connector binary on a ready document and reads the
usage poll state line from its stderr; the connector must also stay up.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 02:49:16 +01:00
Meta Vens
c1cc349b19 usage-meter-poll: the cell decides how a reading combines; a poll is as old as its question
QuotaCell::observe_at is the one decision for both sensors: a reading older
than the held one is dropped, and a rejection stands against a reading that
only reports utilization (status polled) until its window resets or a reading
that carries its own verdict replaces it. The poll stamps its answer with the
moment it asked. Also: Retry-After in HTTP-date form is honoured; a refused
token is not sent again until it reads differently (the poll thread no longer
exits); the client's timeout is a parameter so a silent endpoint is tested;
tests pin redirects(0), the two-window mapping, the slow-server race, and the
late poll against a rejection.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 02:49:16 +01:00
Meta Vens
6982cbca7e usage-meter-poll: pin the log lines and the thread loop
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 01:44:35 +01:00
Meta Vens
7f3a46313e usage-meter-poll: test helper no longer shadowed by its own binding
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 01:37:29 +01:00
Meta Vens
9143d2c5e2 usage-meter-poll: serve_config starts the poll beside the leases
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 01:35:51 +01:00
Meta Vens
79792eea85 usage-meter-poll: the usage poll, the QuotaCell's second sensor
usage_poll asks the subscription's usage endpoint when the seven_day
reading is 15 min old or older, maps five_hour and seven_day onto
PlanQuota with status polled, and honours Retry-After; failures wait,
log once per change of state, and never touch the cell.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 01:35:50 +01:00
Meta Vens
c1802d85be lease v2: committed byte goldens, rustfmt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:38:48 +01:00
Meta Vens
cfea6854ab lease tests: the fake unit record is global, keep it on invocation 1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:30:41 +01:00
Meta Vens
9f10887169 lease v2: byte goldens, hold-loop and lease-helper tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:27:38 +01:00
Meta Vens
9db62027eb connector-usage-only: comment
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:08:19 +01:00
Meta Vens
7d9a6392a7 connector-usage-only: comments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:59:02 +01:00
Meta Vens
a828602649 connector-usage-only: drop a stray doc comment
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:54:14 +01:00
Meta Vens
bb8909f2c2 connector-usage-only: regenerate v4 goldens and schemas, format, fix tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:51:05 +01:00
Meta Vens
28f2e5d2e7 connector-usage-only: test import
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:49:29 +01:00
Meta Vens
dcb5f109f7 connector-usage-only: store-failure tests, README front door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:48:24 +01:00
Meta Vens
af5da3dfaa connector-usage-only: test fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:44:45 +01:00
Meta Vens
702e903fdd connector-usage-only: fix serve test splice
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:44:01 +01:00
Meta Vens
06a47bb13f connector-usage-only: delete the dollar authorities (WIP, does not yet build)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:43:18 +01:00
Meta Vens
d2b82a6c50 lease-persona-callers: the identity bound keeps room for the Persona sequence
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:59:39 +01:00
Meta Vens
47a4dcc6b4 lease-persona-callers: model-connector lease callers take the turn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:58:12 +01:00
Meta Vens
1bf9fdb437 lease-persona-callers: rustfmt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:57:21 +01:00
Meta Vens
13cbdaf23c lease-persona-callers: a lease caller names its turn kind; Persona and Self of one caller lease side by side
LeaseTurn {SelfRun, PersonaTurn} on LeaseCaller and LeaseCallerConfig; the unit derives from the turn; Busy is keyed (caller, turn); a Persona invocation leases in sequence as lease:<invocation>:<n>, one open at a time. config add-lease-caller and init take --turn self|persona.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:56:34 +01:00
Meta Vens
fdcfa063c7 connector-many-callers: one connector serves every Mind as its own caller; session handles are an HMAC under a connector secret over caller, session, instance, instructions, model and transcript prefix; config add-caller/add-lease-caller; one owner for distinct admissions (squash of eureka-body/connector-many-callers d1f25b5..a96b276; Soul s1-s2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 00:11:53 +01:00
Meta Vens
d1f25b5ae6 claude-self-run-lease: Self runs borrow the one Claude token over a unix socket bound to the peer's uid, its pidfd and its unit's InvocationID; the connector sets the reservation, settle bills reported per-model usage uncapped, no report bills the reservation (squash of eureka-body/claude-self-run-lease 480cf94..b5f26ef; Soul s1-s3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 21:54:03 +01:00
480cf941c8 claude-turn-schema-quota: schema-typed Persona replies via --json-schema, token on fd 3 never in the child env, per-window plan-quota capture, communal spend readout, not-logged-in bills zero (squash of eureka-body/claude-turn-schema-quota e867fad..429b344; Soul s1, s2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 20:18:35 +01:00
e867fad379 B4b1 claude-connector-binary: connector daemon over one CultCache config document; token from a systemd credential, pin before every spawn, private prompt dir, 401/403/429 door set, shared readiness for check and serve (squash of eureka-body/claude-connector-binary 200933f..67c7849; Soul s1, s2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:59:23 +01:00
200933f7cf B4a claude-code-backend: Claude backend driving the unmodified claude binary on the operator's subscription; tool-less turns, per-turn usage, process-group kill (squash of eureka-body/claude-code-backend e0c0832..341be82; Soul s1, s2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 11:03:03 +01:00
Meta Vens
e0c0832ae0 connector-spend (B3c): reserve-then-settle spend in the replay ledger, one charge owner, a windowed per-caller ceiling (squash of eureka-body/connector-spend 1d51e71..45d0927)
The reservation and the replay claim are one write in the connector's
replay store; a failed ledger write runs nothing. Amounts are integer
micro-USD with checked arithmetic, and the service derives every cost from
usage and the configured price. One function, ProviderCall::charge, decides
the charge: a result bound to its request and caller pays its true cost with
a truthful overrun, anything else pays the reservation (ruling
spend-bills-on-identity-not-validity). Each caller has a spend ceiling over
fixed epoch-aligned windows in its root-owned config
(connector-spend-caller-window-ceiling); the admission window is monotonic,
so a clock stepping back cannot reopen budget, and a clock-locked caller is
refused ClockBehindAdmissionWindow (spend-window-clock-ahead-fails-closed).
Refusals CostBound, SpendCeiling and ClockBehindAdmissionWindow are typed.

Spec eureka-body:cut_spec:cut-connector-spend.r1; reports h1-h5;
Soul s5 holds (verdict eureka-body:verdict:cut-connector-spend.s5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:47:06 +01:00
75 changed files with 25272 additions and 406 deletions

2
.gitattributes vendored
View file

@ -1,2 +1,2 @@
schemas/*.json text eol=lf schemas/*.json text eol=lf
crates/model-connector/tests/fixtures/wire_v3/* -text crates/model-connector/tests/fixtures/wire_v4/* -text

158
Cargo.lock generated
View file

@ -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"
@ -134,6 +146,27 @@ dependencies = [
"inout", "inout",
] ]
[[package]]
name = "claude-connector"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"cultcache-rs",
"hmac",
"libc",
"model-connector",
"rand_core 0.6.4",
"rmp-serde",
"rmpv",
"serde",
"serde_json",
"sha2",
"thiserror",
"ureq",
"zeroize",
]
[[package]] [[package]]
name = "const-oid" name = "const-oid"
version = "0.9.6" version = "0.9.6"
@ -212,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",
@ -417,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"
@ -490,7 +539,8 @@ name = "model-connector"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"aes-gcm", "aes-gcm",
"base64", "anyhow",
"base64 0.22.1",
"cultcache-rs", "cultcache-rs",
"cultnet-rs", "cultnet-rs",
"rand_core 0.6.4", "rand_core 0.6.4",
@ -535,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"
@ -679,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"
@ -718,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"
@ -965,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"
@ -1042,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"

View file

@ -4,15 +4,18 @@ The connector kit for GameCult minds: one typed, encrypted, replay-safe contract
between a caller that needs a model turn and a daemon that holds the provider between a caller that needs a model turn and a daemon that holds the provider
credential, so no project wires its own provider calls. credential, so no project wires its own provider calls.
Status: the `model-connector` crate is live. No connector binary exists yet The connector gates nothing in dollars. It holds the provider credentials and subscription token, lends leases, derives optional per-call micro-USD visibility on receipts, and publishes communal monthly caller/model spend alongside the plan's usage windows (`usage_readout`, `claude_usage_readout` on the lease socket, and `plan_quota` on every lease grant) for the minds to read and decide their own burn. The one usage-derived refusal is the provider's own (`ProviderRejected`), repeated until its reset.
(the Claude connector is first, then an OpenAI-compatible one).
Status: the `model-connector` crate and the `claude-connector` backend crate and binary are live
(`claude-connector serve|config|ask|lease run`), with `RouterBackend` serving `ClaudeCodeBackend`,
`MessagesBackend`, and `OpenAiChatBackend`.
## Entry points ## Entry points
Crate `crates/model-connector`: Crate `crates/model-connector`:
- `src/contract.rs` - the v3 wire contract (`gamecult.model.*.v3`): `ProviderRequest`, `TransportInvocation`, - `src/contract.rs` - the v5 wire contract (`gamecult.model.*.v5`): `ProviderRequest`, `TransportInvocation`,
`TransportResult`, `TransportReceipt`, the typed `StopReason`, `FailureKind` and `Refusal`, `TransportResult`, `TransportReceipt` (with optional `cost_micro_usd` visibility), the typed `StopReason`, `FailureKind` and `Refusal`,
`InputItem::ReasoningState` (a provider's opaque reasoning block, replayed by callers `InputItem::ReasoningState` (a provider's opaque reasoning block, replayed by callers
verbatim via `TransportResult::transcript_items`; the service refuses another provider's verbatim via `TransportResult::transcript_items`; the service refuses another provider's
state in the in-flight tool exchange and drops it from earlier turns), state in the in-flight tool exchange and drops it from earlier turns),
@ -21,17 +24,73 @@ Crate `crates/model-connector`:
- `src/envelope.rs` - the AES-256-GCM `TransportEnvelope` (binary ciphertext), its - `src/envelope.rs` - the AES-256-GCM `TransportEnvelope` (binary ciphertext), its
identity-binding AAD, the length-prefixed framing, and the CultNet carriage: each frame is a identity-binding AAD, the length-prefixed framing, and the CultNet carriage: each frame is a
`cultnet.operation_request.v0` / `operation_response.v0` for service `cultnet.operation_request.v0` / `operation_response.v0` for service
`gamecult.model.connector`, operation `invoke`, its `message_id` the request id and its `gamecult.model.connector`, operation `invoke` (or `usage_readout`), its `message_id` the
payload the base64 of the sealed envelope. request id and its payload the base64 of the sealed envelope. `usage_readout` answers a
- `schemas/` - one JSON Schema per v3 document, generated from the types. `UsageReadout` (`gamecult.model.usage_readout.v2`): communal monthly `CallerModelSpend` rows
and the backend's plan quota windows, each with utilization, reset, status and age;
`ConnectorClient::usage_readout` asks.
- `schemas/` - one JSON Schema per v5 document, generated from the types.
- `src/client.rs` - `ConnectorClient`, the one-request caller side. - `src/client.rs` - `ConnectorClient`, the one-request caller side.
- `src/price.rs` - pure-integer UTC `PriceRow` (`base` plus ordered `PriceBand` overrides) and
`TokenRates` cost calculation for non-gating visibility.
- `src/service.rs` (feature `daemon`) - `TransportService`: caller admission, durable - `src/service.rs` (feature `daemon`) - `TransportService`: caller admission, durable
replay (a retried request is answered byte-identically and the provider runs once), replay (a retried request is answered byte-identically and the provider runs once),
per-call `cost_micro_usd` derivation, lock-free `SpendSnapshot` projection,
in-flight and capacity refusals. in-flight and capacity refusals.
- `src/serve.rs` (feature `daemon`) - `serve()`, the loopback accept loop, over the - `src/serve.rs` (feature `daemon`) - `serve()`, the loopback accept loop, over the
`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 and the `claude-connector` binary that wires it to `serve`):
- `RouterBackend` is the connector's sole `ProviderBackend` implementation: it routes each configured `ModelRow` in the CultCache `gamecult.model_connector.connector_config.v4`
document to its configured `ProviderEntry` (`ProviderWire::AnthropicMessages`, `ProviderWire::OpenAiChat`, or
`ProviderWire::ClaudeCodeCli`), enforces per-model `ModelRow` policies (`upstream`, `efforts`, `unset_effort`,
`forced_tool_choice`, `output_schema`, `strict_tools`), and isolates `ReasoningState` by provider entry id.
- `ClaudeCodeBackend` serves `ProviderWire::ClaudeCodeCli` (dispatched by `RouterBackend`) by driving the
unmodified `claude` binary, one child per call, in print stream-json mode with no tools, no MCP
servers, no settings sources and the system prompt replaced. Tool-less turns only: a request
with tools or a final tool result is refused before any spawn. A request's output schema goes
to the CLI as `--json-schema` and the result's structured output is the one assistant text.
- 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 its caller re-seeds from the caller's transcript, and every resume forks.
- `MessagesBackend` serves `ProviderWire::AnthropicMessages` (one
non-streaming `POST /v1/messages` per call: tools, tool calls and results, thinking blocks,
`cache_control`, and cache read/write usage; optional `x-api-key` credential). `OpenAiChatBackend`
serves `ProviderWire::OpenAiChat` (non-streaming chat completions with
`reasoning_content` replay and `Bearer` credential when configured). Neither HTTP wire has a
plan: `plan_quota` comes only from a `ClaudeCodeCli` meter, and only a config with a `ClaudeCodeCli`
provider lends token leases.
- `config init` and `config add-model` accept optional per-model pricing flags (`--price-input`,
`--price-cache-read`, `--price-cache-write`, `--price-output`, and repeated
`--price-band WEEKDAYS:UTC_HOURS:INPUT:CACHE_READ:CACHE_WRITE:OUTPUT`) populating `ModelRow.price`
for non-gating receipt and readout visibility only.
- `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
binary hands in; the subscription token is read from a systemd credential and reaches the child on a
pipe, never in an environment (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`). `QuotaCell` keeps the
plan windows the CLI's `rate_limit_event`s report, served alongside `SpendSnapshot` in `usage_readout`
and `ClaudeUsageReadout` without taking the `TransportService` lock.
## 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.
@ -39,8 +98,8 @@ a frame allows, and `MAX_IDENTITY_BYTES` (256) bounds caller ids, request ids an
needed); the smallest legal frame is `frame_bytes_for_payload(MIN_PAYLOAD_BYTES)`. A request id past needed); the smallest legal frame is `frame_bytes_for_payload(MIN_PAYLOAD_BYTES)`. A request id past
the bound is refused on the wire as `Refusal::Malformed`, the reply echoing the id (the connection is dropped only if that reply cannot fit the frame); `ConnectorClient` refuses such an id locally with `RequestIdTooLong`. the bound is refused on the wire as `Refusal::Malformed`, the reply echoing the id (the connection is dropped only if that reply cannot fit the frame); `ConnectorClient` refuses such an id locally with `RequestIdTooLong`.
The default feature set compiles contract, envelope and client only. The kit speaks v3 The default feature set compiles contract, envelope and client only. The kit speaks v5
only: a v2 frame gets no answer. only: a v4 frame gets no answer.
## Verify ## Verify
@ -49,9 +108,9 @@ cargo test --locked --workspace
cargo test --locked --workspace --features model-connector/daemon cargo test --locked --workspace --features model-connector/daemon
``` ```
`crates/model-connector/tests/wire_golden_v3.rs` pins the v3 documents and one sealed carriage `crates/model-connector/tests/wire_golden_v5.rs` pins the v5 documents and one sealed carriage
frame to the fixtures in `crates/model-connector/tests/fixtures/wire_v3` (regenerate with frame to the fixtures in `crates/model-connector/tests/fixtures/wire_v5` (regenerate with
`WIRE_V3_REGENERATE=1`; see the fixtures' README), and `WIRE_V5_REGENERATE=1`; see the fixtures' README), and
`crates/model-connector/tests/published_schemas.rs` fails when `schemas/` differs from the types `crates/model-connector/tests/published_schemas.rs` fails when `schemas/` differs from the types
(`MODEL_CONNECTOR_REGENERATE_SCHEMAS=1` rewrites it). (`MODEL_CONNECTOR_REGENERATE_SCHEMAS=1` rewrites it).

View file

@ -0,0 +1,33 @@
[package]
name = "claude-connector"
description = "Claude backends for the connector kit: the claude CLI on a subscription token, the Messages API on an API key"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
publish = false
[[bin]]
name = "claude-connector"
path = "src/main.rs"
[dependencies]
anyhow = "1"
chrono = { version = "0.4", default-features = false }
hmac = "0.12"
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "a4eae9056152335662f1115f97bf35fb00ab6d23", package = "cultcache-rs" }
model-connector = { path = "../model-connector", features = ["daemon"] }
rand_core = { version = "0.6", features = ["getrandom"] }
rmp-serde = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
thiserror = "2"
ureq = { version = "~3.3", default-features = false, features = ["rustls"] }
zeroize = "1"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[dev-dependencies]
rmpv = "1"

View 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());
}
}

View file

@ -0,0 +1,449 @@
use std::fs::File;
use std::io;
use std::sync::Arc;
use std::time::Instant;
use model_connector::{
FailureKind, InputItem, PlanQuotaSnapshot, ProviderRequest, ToolChoice, TransportEvent,
TransportEventPayload, TransportOutcome, Usage,
};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;
use crate::config::{ClaudeCodeConfig, ModelRow, OutputSchemaSupport};
use crate::credential::{CredentialTokenSource, TokenSource, credential_ready};
use crate::handle::{
Binding, ClaudeCodeHandle, MIN_SECRET_BYTES, SessionStore, plan, prefix_digest, stdin_bytes,
};
use crate::launch::{PromptFile, argv, child_env};
use crate::process::{ProcessPort, RunningChild, StdoutRead};
use crate::quota::QuotaCell;
use crate::stream::{Failure, Finished, Step, StreamState};
const METER_CALLER: &str = "meter";
const METER_MAX_OUTPUT_TOKENS: u32 = 16;
/// 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.
pub trait StderrSink: Send + Sync {
fn stderr_tail(&self, tail: &[u8]);
}
/// Answers each call with one `claude` child process: never more than one per
/// call, and a failed call is never run again.
pub struct ClaudeCodeBackend {
config: ClaudeCodeConfig,
port: Box<dyn ProcessPort>,
sessions: Box<dyn SessionStore>,
sink: Box<dyn StderrSink>,
tokens: Box<dyn TokenSource>,
handle_secret: Box<dyn TokenSource>,
quota: Arc<QuotaCell>,
}
/// The handle secret, or `None` when it is absent or shorter than a key.
fn usable_secret(source: &dyn TokenSource) -> Option<Zeroizing<String>> {
source
.read()
.filter(|secret| secret.len() >= MIN_SECRET_BYTES)
}
impl ClaudeCodeBackend {
/// The backend over real processes and the CLI's real session store.
#[cfg(unix)]
pub fn new(config: ClaudeCodeConfig, sink: Box<dyn StderrSink>) -> Self {
let port = Box::new(crate::process::StdProcessPort::new(config.limits));
let sessions = Box::new(crate::handle::FsSessionStore::new(
config.config_dir.clone(),
));
let tokens = Box::new(CredentialTokenSource::from_environment(
config.token_credential.clone(),
));
let handle_secret = Box::new(
CredentialTokenSource::from_environment(config.handle_secret_credential.clone())
.for_field("handle_secret_credential"),
);
Self::with_ports(config, port, sessions, sink, tokens, handle_secret)
}
pub fn with_ports(
config: ClaudeCodeConfig,
port: Box<dyn ProcessPort>,
sessions: Box<dyn SessionStore>,
sink: Box<dyn StderrSink>,
tokens: Box<dyn TokenSource>,
handle_secret: Box<dyn TokenSource>,
) -> Self {
Self {
config,
port,
sessions,
sink,
tokens,
handle_secret,
quota: Arc::new(QuotaCell::new()),
}
}
/// 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.
pub fn quota(&self) -> Arc<QuotaCell> {
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,
/// stream and cell as any other. The stream's `rate_limit_event` is what
/// the caller wants; this returns what the call billed, or the failure's
/// kind (never its message).
pub(crate) fn read_meter(&self) -> Result<Usage, String> {
let Some(model) = self.config.meter_model.as_deref() else {
return Err("MissingMeterModel".to_string());
};
let mut request = ProviderRequest::new(
METER_CALLER,
METER_CALLER,
model,
"Reply with the single word ok.",
METER_MAX_OUTPUT_TOKENS,
);
request.input = vec![InputItem::UserText {
text: "ok?".to_string(),
}];
match self.run_inner(&request, METER_CALLER, None, true).1 {
TransportOutcome::Completed { usage, .. } => Ok(usage),
TransportOutcome::Failed { kind, .. } => Err(format!("{kind:?}")),
}
}
/// The one pin check: `ready` and every spawn use it, and nothing caches
/// its answer.
fn binary_matches_pin(&self) -> bool {
binary_matches_pin(&self.config)
}
pub(crate) fn run_model(
&self,
request: &ProviderRequest,
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,
) -> (Vec<TransportEvent>, TransportOutcome) {
let Some(secret) = usable_secret(self.handle_secret.as_ref()) else {
return failed(
FailureKind::Authentication,
"claude-code: the connector has no handle secret".to_string(),
Some(zero_usage()),
);
};
let plan = match plan(
request,
&self.config,
secret.as_bytes(),
caller,
self.sessions.as_ref(),
) {
Ok(plan) => plan,
Err(error) => {
return failed(
FailureKind::InvalidRequest,
error.to_string(),
Some(zero_usage()),
);
}
};
let Some(token) = self.tokens.read() else {
return failed(
FailureKind::Authentication,
"claude-code: the connector has no credential to give the child".to_string(),
Some(zero_usage()),
);
};
if !self.binary_matches_pin() {
return failure(Failure::never_reached(
FailureKind::Provider,
"claude-code: the claude binary does not match its pin",
));
}
let Ok(prompt) = PromptFile::create(&self.config.prompt_dir, &request.instructions) else {
return failure(Failure::never_reached(
FailureKind::Provider,
"claude-code: the system prompt could not be staged",
));
};
let argv = argv(
&self.config,
request,
&plan,
prompt.path(),
effort,
ephemeral,
);
let env = child_env(&self.config, request);
let deadline = Instant::now() + self.config.limits.deadline;
let spawned = self.port.spawn(
&argv,
&env,
&self.config.work_dir,
stdin_bytes(plan.blocks()),
&token,
);
let Ok(mut child) = spawned else {
return failure(Failure::never_reached(
FailureKind::Provider,
"claude-code: the child could not be spawned",
));
};
let finished = read_stream(
child.as_mut(),
deadline,
&request.model,
request.output_schema_json.as_deref(),
Some(&*self.quota),
);
child.kill();
child.wait();
let tail = child.stderr_tail();
if !tail.is_empty() {
self.sink.stderr_tail(&tail);
}
match finished {
Ok(finished) => self.completed(request, caller, secret.as_bytes(), finished),
Err(failure_) => failure(failure_),
}
}
fn completed(
&self,
request: &ProviderRequest,
caller: &str,
secret: &[u8],
finished: Finished,
) -> (Vec<TransportEvent>, TransportOutcome) {
let mut payloads: Vec<TransportEventPayload> = finished
.texts
.iter()
.map(|text| TransportEventPayload::TextDelta { text: text.clone() })
.collect();
let mut prefix = request.input.clone();
if !finished.texts.is_empty() {
prefix.push(InputItem::AssistantText {
text: finished.texts.concat(),
});
}
// A schema turn leaves the CLI's StructuredOutput tool exchange in its
// session, and a later turn without the schema runs with no tools: it
// must not resume that session. So a schema turn hands out no handle,
// and whatever follows it is seeded from the caller's transcript.
if request.output_schema_json.is_none() {
let handle = ClaudeCodeHandle::Ended {
session_id: finished.session_id.clone(),
instance: self.config.instance.clone(),
prefix_sha256: prefix_digest(
secret,
&Binding {
caller,
instructions: &request.instructions,
model: &request.model,
session_id: &finished.session_id,
instance: &self.config.instance,
items: &prefix,
},
),
};
payloads.push(TransportEventPayload::ReasoningState {
state: handle.encode(),
});
}
let events = payloads
.into_iter()
.enumerate()
.map(|(sequence, payload)| TransportEvent {
sequence: sequence as u64,
payload,
})
.collect();
(
events,
TransportOutcome::Completed {
provider_response_id: finished.message_id,
stop_reason: finished.stop_reason,
usage: finished.usage,
},
)
}
}
fn read_stream(
child: &mut dyn RunningChild,
deadline: Instant,
model: &str,
schema: Option<&str>,
quota: Option<&QuotaCell>,
) -> Result<Finished, Failure> {
let mut state = StreamState::new(model, schema, quota);
let finished = loop {
match child.read_line(deadline) {
StdoutRead::Line(line) => {
if let Step::Done(done) = state.feed(&line) {
break *done;
}
}
StdoutRead::Eof => {
return Err(Failure::cost_unknown(
FailureKind::Provider,
"claude-code: the stream ended without a result",
));
}
StdoutRead::Timeout => {
return Err(Failure::cost_unknown(
FailureKind::Timeout,
"claude-code: the deadline passed before a result",
));
}
StdoutRead::Breach => {
return Err(Failure::cost_unknown(
FailureKind::Provider,
"claude-code: the output passed its size cap",
));
}
}
};
// The result is in; give the child until its deadline to close stdout.
while matches!(child.read_line(deadline), StdoutRead::Line(_)) {}
finished
}
fn binary_matches_pin(config: &ClaudeCodeConfig) -> bool {
let Ok(mut file) = File::open(&config.claude_binary) else {
return false;
};
let mut hasher = Sha256::new();
io::copy(&mut file, &mut hasher).is_ok()
&& <[u8; 32]>::from(hasher.finalize()) == config.claude_binary_sha256
}
/// Whether the backend can take work, naming the first config field that
/// cannot be used. `config check` and `serve` both ask this.
pub(crate) fn readiness(
config: &ClaudeCodeConfig,
tokens: &dyn TokenSource,
handle_secret: &dyn TokenSource,
) -> Result<(), &'static str> {
if !config.work_dir.is_dir() {
return Err("work_dir");
}
if !config.config_dir.is_dir() {
return Err("config_dir");
}
if !config.prompt_dir.is_dir() {
return Err("prompt_dir");
}
if !binary_matches_pin(config) {
return Err("claude_binary_sha256");
}
// Last: outside the unit the credential is the one thing always absent,
// and it must not hide the faults the document itself has.
if usable_secret(handle_secret).is_none() {
return Err(handle_secret.missing());
}
credential_ready(tokens)?;
Ok(())
}
fn zero_usage() -> Usage {
Usage {
input_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 0,
reasoning_tokens: None,
}
}
fn failed(
kind: FailureKind,
message: String,
usage: Option<Usage>,
) -> (Vec<TransportEvent>, TransportOutcome) {
(
Vec::new(),
TransportOutcome::Failed {
kind,
message,
usage,
},
)
}
fn failure(failure: Failure) -> (Vec<TransportEvent>, TransportOutcome) {
failed(failure.kind, failure.message.to_string(), failure.usage)
}
#[cfg(test)]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,168 @@
use std::path::PathBuf;
use std::time::Duration;
use model_connector::{PriceRow, ReasoningEffort};
use serde::{Deserialize, Serialize};
/// One configured provider entry in the connector's v4 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,
pub price: Option<PriceRow>,
}
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.
#[derive(Debug, Clone)]
pub struct ClaudeCodeConfig {
/// Provider tag written on receipts and reasoning state items.
pub provider_id: String,
/// The `claude` executable.
pub claude_binary: PathBuf,
/// The SHA-256 the executable must have for [`ready`](model_connector::ProviderBackend::ready).
pub claude_binary_sha256: [u8; 32],
/// An empty directory the connector owns: the CLI writes its cwd, git state
/// and platform into the system prompt.
pub work_dir: PathBuf,
/// Passed to the child as `CLAUDE_CONFIG_DIR` and `HOME`; it holds the
/// CLI's session store.
pub config_dir: PathBuf,
/// A directory the connector owns (mode 0700), where each call's system
/// prompt is staged for the child.
pub prompt_dir: PathBuf,
/// The name of the systemd credential that holds the child's subscription token, under
/// `$CREDENTIALS_DIRECTORY`.
pub token_credential: String,
/// The name of the systemd credential that holds the handle secret: the
/// key every handle is authenticated with.
pub handle_secret_credential: String,
/// The connector instance id written into every handle.
pub instance: String,
/// Upstream model name used for the subscription plan meter's minimal call.
pub meter_model: Option<String>,
pub limits: ClaudeCodeLimits,
}
/// The bounds of one child process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClaudeCodeLimits {
/// The whole call, spawn to result.
pub deadline: Duration,
pub max_line_bytes: usize,
pub max_total_bytes: usize,
pub stderr_tail_bytes: usize,
}

View 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

View file

@ -0,0 +1,308 @@
//! The reasoning state of this backend and the decision it drives: resume the
//! CLI session a handle names, or start a fresh one seeded with the caller's
//! transcript. The session is a cache of the caller's transcript; the
//! transcript is the truth.
use std::path::PathBuf;
use hmac::{Hmac, Mac};
use model_connector::{InputItem, ProviderRequest};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use crate::config::ClaudeCodeConfig;
/// The state this backend hands a caller inside `ReasoningState`. A new
/// variant is a new version.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) enum ClaudeCodeHandle {
/// The session a finished turn left behind. `prefix_sha256` is the
/// HMAC-SHA-256, keyed with the connector's handle secret, of the caller
/// that minted the handle, the instructions, the model, this session and
/// instance, and every transcript item that precedes this handle. Another caller, or anyone
/// without the secret, cannot produce or satisfy it.
Ended {
session_id: String,
instance: String,
prefix_sha256: [u8; 32],
},
}
impl ClaudeCodeHandle {
pub(crate) fn encode(&self) -> Vec<u8> {
rmp_serde::to_vec_named(self).expect("a handle of strings and bytes encodes")
}
fn decode(state: &[u8]) -> Option<Self> {
rmp_serde::from_slice(state).ok()
}
}
/// The smallest handle secret the connector accepts, in bytes.
pub const MIN_SECRET_BYTES: usize = 32;
/// Everything a handle's tag binds: the minting caller, the instructions, the
/// model, the session and instance the handle names, and the transcript items
/// before the handle. Swapping any of them into a valid handle breaks the tag.
pub(crate) struct Binding<'a> {
pub(crate) caller: &'a str,
pub(crate) instructions: &'a str,
pub(crate) model: &'a str,
pub(crate) session_id: &'a str,
pub(crate) instance: &'a str,
pub(crate) items: &'a [InputItem],
}
fn prefix_mac(secret: &[u8], binding: &Binding<'_>) -> Hmac<Sha256> {
let bytes = rmp_serde::to_vec_named(&(
binding.caller,
binding.instructions,
binding.model,
binding.session_id,
binding.instance,
binding.items,
))
.expect("strings and bytes encode");
let mut mac = Hmac::<Sha256>::new_from_slice(secret).expect("an HMAC key has any length");
mac.update(&bytes);
mac
}
/// The tag a handle carries: keyed named MessagePack of its [`Binding`].
pub(crate) fn prefix_digest(secret: &[u8], binding: &Binding<'_>) -> [u8; 32] {
prefix_mac(secret, binding).finalize().into_bytes().into()
}
fn prefix_matches(secret: &[u8], binding: &Binding<'_>, tag: &[u8; 32]) -> bool {
prefix_mac(secret, binding).verify_slice(tag).is_ok()
}
/// Whether the CLI's session store still holds a session.
pub trait SessionStore: Send + Sync {
fn exists(&self, session_id: &str) -> bool;
}
/// Looks for `<config_dir>/projects/*/<session_id>.jsonl`. A session id that
/// is not a canonical UUID never names a path.
pub struct FsSessionStore {
config_dir: PathBuf,
}
impl FsSessionStore {
pub fn new(config_dir: PathBuf) -> Self {
Self { config_dir }
}
}
fn is_canonical_uuid(id: &str) -> bool {
id.len() == 36
&& id.char_indices().all(|(at, c)| match at {
8 | 13 | 18 | 23 => c == '-',
_ => c.is_ascii_digit() || ('a'..='f').contains(&c),
})
}
impl SessionStore for FsSessionStore {
fn exists(&self, session_id: &str) -> bool {
if !is_canonical_uuid(session_id) {
return false;
}
let Ok(projects) = std::fs::read_dir(self.config_dir.join("projects")) else {
return false;
};
projects
.flatten()
.any(|project| project.path().join(format!("{session_id}.jsonl")).is_file())
}
}
/// Why a request cannot be answered by this backend; the text is the failure
/// message and names what lifts it.
#[derive(Debug, thiserror::Error)]
pub(crate) enum PlanError {
#[error("claude-code: tools are not supported by this backend yet")]
Tools,
#[error("claude-code: tool results are not supported by this backend yet")]
ToolResult,
#[error("claude-code: the request ends without user text")]
NoUserText,
#[error("claude-code: the request carries a reasoning state this backend cannot read")]
UndecodableHandle,
}
/// How a call reaches the CLI. `blocks` are the text blocks of the one user
/// message the child is given.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Plan {
Resume {
session_id: String,
blocks: Vec<String>,
},
Seed {
blocks: Vec<String>,
},
}
impl Plan {
pub(crate) fn blocks(&self) -> &[String] {
match self {
Plan::Resume { blocks, .. } | Plan::Seed { blocks } => blocks,
}
}
}
pub(crate) fn plan(
request: &ProviderRequest,
config: &ClaudeCodeConfig,
secret: &[u8],
caller: &str,
sessions: &dyn SessionStore,
) -> Result<Plan, PlanError> {
if !request.tools.is_empty() {
return Err(PlanError::Tools);
}
let input = &request.input;
let run_start = input
.iter()
.rposition(|item| {
!matches!(
item,
InputItem::UserText { .. } | InputItem::ToolResult { .. }
)
})
.map_or(0, |at| at + 1);
let run = &input[run_start..];
if run
.iter()
.any(|item| matches!(item, InputItem::ToolResult { .. }))
{
return Err(PlanError::ToolResult);
}
let user_blocks: Vec<String> = run
.iter()
.filter_map(|item| match item {
InputItem::UserText { text } => Some(text.clone()),
_ => None,
})
.collect();
if user_blocks.is_empty() {
return Err(PlanError::NoUserText);
}
let last_own = input.iter().rposition(|item| {
matches!(item, InputItem::ReasoningState { provider, .. } if provider == &config.provider_id)
});
if let Some(at) = last_own {
let InputItem::ReasoningState { state, .. } = &input[at] else {
unreachable!("rposition matched a reasoning state");
};
let Some(ClaudeCodeHandle::Ended {
session_id,
instance,
prefix_sha256,
}) = ClaudeCodeHandle::decode(state)
else {
return Err(PlanError::UndecodableHandle);
};
let tail_is_user_text = input[at + 1..]
.iter()
.all(|item| matches!(item, InputItem::UserText { .. }));
let resumable = instance == config.instance
&& tail_is_user_text
&& prefix_matches(
secret,
&Binding {
caller,
instructions: &request.instructions,
model: &request.model,
session_id: &session_id,
instance: &instance,
items: &input[..at],
},
&prefix_sha256,
)
&& sessions.exists(&session_id);
if resumable {
return Ok(Plan::Resume {
session_id,
blocks: user_blocks,
});
}
}
let mut blocks = Vec::new();
if let Some(transcript) = render_transcript(&input[..run_start]) {
blocks.push(transcript);
}
blocks.extend(user_blocks);
Ok(Plan::Seed { blocks })
}
/// The earlier conversation as one deterministic text, or `None` when nothing
/// of it is renderable. Reasoning states are omitted.
fn render_transcript(items: &[InputItem]) -> Option<String> {
let groups: Vec<String> = items
.iter()
.filter_map(|item| match item {
InputItem::UserText { text } => Some(format!("[user]\n{text}")),
InputItem::AssistantText { text } => Some(format!("[assistant]\n{text}")),
InputItem::ToolCall {
call_id,
name,
arguments,
} => Some(format!("[tool_call name={name} id={call_id}]\n{arguments}")),
InputItem::ToolResult { call_id, output } => {
Some(format!("[tool_result id={call_id}]\n{output}"))
}
InputItem::ReasoningState { .. } => None,
})
.collect();
if groups.is_empty() {
return None;
}
Some(format!(
"The conversation so far, replayed as text because the earlier session cannot be continued:\n\n{}",
groups.join("\n\n")
))
}
#[derive(Serialize)]
struct UserLine<'a> {
#[serde(rename = "type")]
kind: &'static str,
message: UserMessage<'a>,
parent_tool_use_id: Option<&'a str>,
}
#[derive(Serialize)]
struct UserMessage<'a> {
role: &'static str,
content: Vec<TextBlock<'a>>,
}
#[derive(Serialize)]
struct TextBlock<'a> {
#[serde(rename = "type")]
kind: &'static str,
text: &'a str,
}
/// The child's whole stdin: exactly one stream-json user line. Several lines
/// would queue several turns.
pub(crate) fn stdin_bytes(blocks: &[String]) -> Vec<u8> {
let line = UserLine {
kind: "user",
message: UserMessage {
role: "user",
content: blocks
.iter()
.map(|text| TextBlock { kind: "text", text })
.collect(),
},
parent_tool_use_id: None,
};
let mut bytes = serde_json::to_vec(&line).expect("typed strings encode");
bytes.push(b'\n');
bytes
}

View 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"
);
}
}

View file

@ -0,0 +1,207 @@
//! The claude argv and the child environment: every flag and variable name
//! this backend sends is a constant or built here, so a CLI upgrade is one
//! place to re-probe.
use std::fmt;
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use model_connector::ProviderRequest;
use crate::config::ClaudeCodeConfig;
use crate::handle::Plan;
/// The credential never enters the environment:
/// the process port writes it into a pipe and hands the child the read end at
/// [`TOKEN_FD`], the first descriptor after stdin, stdout and stderr, and the
/// environment names that descriptor.
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";
/// The environment of the child: exactly these names and nothing inherited.
/// `Debug` lists names only.
pub struct ChildEnv(Vec<(&'static str, String)>);
impl ChildEnv {
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.0.iter().map(|(name, value)| (*name, value.as_str()))
}
}
impl fmt::Debug for ChildEnv {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.0.iter().map(|(name, _)| name))
.finish()
}
}
pub(crate) fn child_env(config: &ClaudeCodeConfig, request: &ProviderRequest) -> ChildEnv {
let config_dir = config.config_dir.to_string_lossy().into_owned();
ChildEnv(vec![
("PATH", CHILD_PATH.to_string()),
("HOME", config_dir.clone()),
("CLAUDE_CONFIG_DIR", config_dir),
(
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
request.max_output_tokens.to_string(),
),
(TOKEN_FD_VAR, TOKEN_FD.to_string()),
])
}
/// The system prompt staged for one child: an exclusively created file only
/// its owner can read, removed when this value drops, however the call ends.
pub(crate) struct PromptFile(PathBuf);
static PROMPT_FILES: AtomicU64 = AtomicU64::new(0);
impl PromptFile {
pub(crate) fn create(dir: &Path, instructions: &str) -> io::Result<Self> {
let name = format!(
"claude-connector-prompt-{}-{}",
std::process::id(),
PROMPT_FILES.fetch_add(1, Ordering::Relaxed)
);
Self::create_at(dir.join(name), instructions)
}
/// Creates `path` and nothing that already exists there: a file, a link
/// (dangling or not) or a directory at the name fails, and is left alone.
fn create_at(path: PathBuf, instructions: &str) -> io::Result<Self> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(&path)?;
let owned = Self(path);
file.write_all(instructions.as_bytes())?;
Ok(owned)
}
pub(crate) fn path(&self) -> &Path {
&self.0
}
}
impl Drop for PromptFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// 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
/// (E2BIG) and instructions are not, the child has
/// no tools, no MCP servers, no settings, no slash commands and nobody to ask
/// for permission, and a resume always forks. An ephemeral call (the
/// meter's) keeps no session on disk. A request's output schema goes to the
/// CLI as `--json-schema`; without one the flag is absent.
pub(crate) fn argv(
config: &ClaudeCodeConfig,
request: &ProviderRequest,
plan: &Plan,
system_prompt_file: &Path,
effort: Option<&str>,
ephemeral: bool,
) -> Vec<String> {
let mut argv: Vec<String> = [
config.claude_binary.to_string_lossy().as_ref(),
"-p",
"--output-format",
"stream-json",
"--verbose",
"--input-format",
"stream-json",
"--model",
&request.model,
"--system-prompt-file",
&system_prompt_file.to_string_lossy(),
"--tools",
"",
"--strict-mcp-config",
"--setting-sources",
"",
"--disable-slash-commands",
"--permission-prompts",
"none",
]
.into_iter()
.map(str::to_string)
.collect();
if ephemeral {
argv.push("--no-session-persistence".to_string());
}
if let Some(level) = effort {
argv.extend(["--effort".to_string(), level.to_string()]);
}
if let Some(schema) = &request.output_schema_json {
argv.extend(["--json-schema".to_string(), schema.clone()]);
}
if let Plan::Resume { session_id, .. } = plan {
argv.extend([
"--resume".to_string(),
session_id.clone(),
"--fork-session".to_string(),
]);
}
argv
}
#[cfg(all(test, unix))]
mod tests {
use std::os::unix::fs::{PermissionsExt, symlink};
use super::*;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"claude-connector-launch-{name}-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn a_prompt_is_created_private_and_removed_on_drop() {
let dir = scratch("private");
let prompt = PromptFile::create(&dir, "the prompt").unwrap();
let path = prompt.path().to_path_buf();
assert_eq!(path.parent(), Some(dir.as_path()));
assert_eq!(std::fs::read_to_string(&path).unwrap(), "the prompt");
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
drop(prompt);
assert!(!path.exists());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_name_already_taken_is_never_written_or_removed() {
let dir = scratch("taken");
let victim = dir.join("victim");
std::fs::write(&victim, "keep").unwrap();
let file = dir.join("file");
std::fs::write(&file, "mine").unwrap();
let link = dir.join("link");
symlink(&victim, &link).unwrap();
let dangling = dir.join("dangling");
symlink(dir.join("nowhere"), &dangling).unwrap();
for taken in [&file, &link, &dangling] {
assert!(PromptFile::create_at(taken.clone(), "the prompt").is_err());
}
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep");
assert_eq!(std::fs::read_to_string(&file).unwrap(), "mine");
assert!(!dir.join("nowhere").exists());
assert!(link.exists() && dangling.symlink_metadata().is_ok());
std::fs::remove_dir_all(dir).unwrap();
}
}

File diff suppressed because it is too large Load diff

View 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);
}
}

View file

@ -0,0 +1,55 @@
//! The Claude backend of the connector kit. [`ClaudeCodeBackend`] answers each
//! call by driving the unmodified `claude` binary once, in print mode with
//! stream-json in and out, with every tool, MCP server, settings source and
//! plugin switched off. A binary wires it to [`model_connector::serve`].
pub mod ask;
mod backend;
mod config;
mod credential;
mod daemon;
mod handle;
mod http;
mod launch;
#[cfg(target_os = "linux")]
mod lease;
#[cfg(target_os = "linux")]
pub mod lease_run;
mod messages;
mod meter;
mod openai_chat;
mod process;
mod quota;
mod router;
mod stream;
#[cfg(target_os = "linux")]
mod unit;
pub use backend::{ClaudeCodeBackend, StderrSink};
pub use config::{
ClaudeCodeConfig, ClaudeCodeLimits, EffortMap, ForcedToolChoice, ModelRow, OutputSchemaSupport,
ProviderEntry, ProviderWire,
};
pub use credential::{CredentialTokenSource, TokenSource};
pub use daemon::{
ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, check_ready, load_config, write_config,
};
#[cfg(unix)]
pub use daemon::{check_prompt_dir, serve_config};
pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore};
pub use launch::ChildEnv;
#[cfg(target_os = "linux")]
pub use lease::{
LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
};
pub use messages::{MessagesBackend, MessagesConfig};
pub use openai_chat::{OpenAiChatBackend, OpenAiChatConfig};
#[cfg(unix)]
pub use process::StdProcessPort;
pub use process::{ProcessPort, RunningChild, StdoutRead};
pub use quota::QuotaCell;
pub use router::RouterBackend;
#[cfg(target_os = "linux")]
pub use unit::SystemdUnits;

View file

@ -0,0 +1,809 @@
//! The claude-connector binary.
//!
//! claude-connector serve --config PATH.cc
//! 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-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 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
//! `config init`, `add-provider`, and `add-model` exist only to author that document.
//! No message here echoes a value that was typed or stored; refusals name a field or a flag.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::process::ExitCode;
use claude_connector::ask::{self, AskArgs, AskError};
use claude_connector::{
ClaudeConnectorConfig, ConfigError, EffortMap, ForcedToolChoice, LeaseHolderConfig,
MIN_SECRET_BYTES, ModelRow, OutputSchemaSupport, ProviderEntry, ProviderWire, check_ready,
load_config, write_config,
};
use model_connector::{
CallerConfig, LeaseScope, PriceBand, PriceRow, TokenRates, Weekday, frame_bytes_for_payload,
};
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let result = match args.as_slice() {
["serve", "--config", path] => serve(path).map(|()| ExitCode::SUCCESS),
["config", "init", path, flags @ ..] => init(path, flags).map(|()| ExitCode::SUCCESS),
["config", "add-provider", path, flags @ ..] => {
add_provider(path, flags).map(|()| ExitCode::SUCCESS)
}
["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),
};
match result {
Ok(code) => code,
Err(failure) => {
eprintln!("claude-connector: {failure}");
ExitCode::FAILURE
}
}
}
#[derive(Debug, thiserror::Error)]
enum Failure {
#[error(
"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,
#[error(transparent)]
Config(#[from] ConfigError),
#[error("flag {0} is missing")]
Missing(&'static str),
#[error("flag {0} is malformed")]
Malformed(&'static str),
#[error("flag {0} conflicts with --wire")]
Conflict(&'static str),
#[error("a flag is unknown, repeated or has no value")]
Flags,
#[error("{0}")]
Ask(#[from] AskError),
#[cfg(target_os = "linux")]
#[error("{0}")]
LeaseRun(#[from] claude_connector::lease_run::LeaseRunError),
}
#[cfg(unix)]
fn serve(path: &str) -> Result<(), Failure> {
Ok(claude_connector::serve_config(path.as_ref())?)
}
#[cfg(not(unix))]
fn serve(_: &str) -> Result<(), Failure> {
Err(Failure::Usage)
}
fn check(path: &str) -> Result<(), Failure> {
let config = load_config(path.as_ref())?;
check_ready(&config)?;
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!("lease_holders: {}", config.lease_holders.len());
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
/// flag any number of times.
struct Flags {
single: BTreeMap<&'static str, String>,
lists: BTreeMap<&'static str, Vec<String>>,
}
/// The flags that describe one caller, shared by `config init` (which writes
/// the first caller) and `config add-caller`.
const CALLER: [&str; 5] = [
"--caller-id",
"--connection-key-file",
"--connection-key-epoch",
"--max-concurrent-requests",
"--max-output-tokens",
];
const INIT: [&str; 8] = [
"--listen",
"--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-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 MODEL: [&str; 15] = [
"--model",
"--provider",
"--upstream",
"--effort-low",
"--effort-medium",
"--effort-high",
"--effort-max",
"--unset-effort",
"--forced-tool-choice",
"--output-schema",
"--strict-tools",
"--price-input",
"--price-cache-read",
"--price-cache-write",
"--price-output",
];
const LEASE_HOLDER: [&str; 4] = ["--caller-id", "--provider", "--unit", "--scope"];
#[derive(Clone, Copy)]
enum WireKind {
AnthropicMessages,
OpenAiChat,
ClaudeCodeCli,
}
impl Flags {
fn parse(
args: &[&str],
singles: &[&[&'static str]],
lists: &[&'static str],
) -> Result<Self, Failure> {
let mut flags = Flags {
single: BTreeMap::new(),
lists: BTreeMap::new(),
};
let mut args = args.iter();
while let Some(&name) = args.next() {
let Some(&value) = args.next() else {
return Err(Failure::Flags);
};
if let Some(list) = lists.iter().find(|known| **known == name) {
flags
.lists
.entry(*list)
.or_default()
.push(value.to_string());
continue;
}
let Some(known) = singles
.iter()
.flat_map(|set| set.iter())
.find(|k| **k == name)
else {
return Err(Failure::Flags);
};
if flags.single.insert(*known, value.to_string()).is_some() {
return Err(Failure::Flags);
}
}
Ok(flags)
}
fn list(&self, name: &'static str) -> &[String] {
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> {
self.single.get(name).cloned().ok_or(Failure::Missing(name))
}
fn path(&self, name: &'static str) -> Result<PathBuf, Failure> {
self.text(name).map(PathBuf::from)
}
fn number<T: std::str::FromStr>(&self, name: &'static str) -> Result<T, Failure> {
self.text(name)?
.parse()
.map_err(|_| Failure::Malformed(name))
}
fn reject_any(&self, conflicting: &[&'static str]) -> Result<(), Failure> {
for &flag in conflicting {
if self.single.contains_key(flag) || self.lists.contains_key(flag) {
return Err(Failure::Conflict(flag));
}
}
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> {
const PRICE_RATES: [&str; 4] = [
"--price-input",
"--price-cache-read",
"--price-cache-write",
"--price-output",
];
let raw_bands = self.list("--price-band");
let has_price = PRICE_RATES
.iter()
.any(|flag| self.single.contains_key(flag))
|| !raw_bands.is_empty();
let price = if has_price {
let base = TokenRates {
input: self.number("--price-input")?,
cache_read: self.number("--price-cache-read")?,
cache_write: self.number("--price-cache-write")?,
output: self.number("--price-output")?,
};
let bands = raw_bands
.iter()
.map(|raw| parse_price_band(raw))
.collect::<Result<Vec<_>, _>>()?;
Some(PriceRow { base, bands })
} else {
None
};
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")?,
price,
})
}
/// 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")),
}
}
fn number_or<T: std::str::FromStr>(
&self,
name: &'static str,
default: T,
) -> Result<T, Failure> {
match self.single.get(name) {
None => Ok(default),
Some(text) => text.parse().map_err(|_| Failure::Malformed(name)),
}
}
/// The caller these flags describe. Its payload bound comes from
/// `--max-payload-bytes` when the verb takes one.
fn caller(&self) -> Result<CallerConfig, Failure> {
Ok(CallerConfig {
caller_runtime_id: self.text("--caller-id")?,
connection_key_file: self.path("--connection-key-file")?,
connection_key_epoch: self.number("--connection-key-epoch")?,
allowed_models: self.list("--allowed-model").to_vec(),
max_concurrent_requests: self.number_or("--max-concurrent-requests", 4)?,
max_payload_bytes: self.number_or("--max-payload-bytes", 1 << 20)?,
max_output_tokens: self.number_or("--max-output-tokens", 32_768)?,
})
}
}
fn parse_weekday(raw: &str) -> Option<Weekday> {
if raw.eq_ignore_ascii_case("mon") {
Some(Weekday::Mon)
} else if raw.eq_ignore_ascii_case("tue") {
Some(Weekday::Tue)
} else if raw.eq_ignore_ascii_case("wed") {
Some(Weekday::Wed)
} else if raw.eq_ignore_ascii_case("thu") {
Some(Weekday::Thu)
} else if raw.eq_ignore_ascii_case("fri") {
Some(Weekday::Fri)
} else if raw.eq_ignore_ascii_case("sat") {
Some(Weekday::Sat)
} else if raw.eq_ignore_ascii_case("sun") {
Some(Weekday::Sun)
} else {
None
}
}
fn parse_price_band(raw: &str) -> Result<PriceBand, Failure> {
let parts: Vec<&str> = raw.split(':').collect();
let [
days_raw,
hours_raw,
input_raw,
cache_read_raw,
cache_write_raw,
output_raw,
] = parts.as_slice()
else {
return Err(Failure::Malformed("--price-band"));
};
let weekdays = days_raw
.split(',')
.map(|day| parse_weekday(day).ok_or(Failure::Malformed("--price-band")))
.collect::<Result<Vec<_>, _>>()?;
let utc_hours = hours_raw
.split(',')
.map(|hour| {
hour.parse::<u8>()
.map_err(|_| Failure::Malformed("--price-band"))
})
.collect::<Result<Vec<_>, _>>()?;
let rates = TokenRates {
input: input_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
cache_read: cache_read_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
cache_write: cache_write_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
output: output_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
};
Ok(PriceBand {
weekdays,
utc_hours,
rates,
})
}
fn sha256(hex: &str) -> Option<[u8; 32]> {
if hex.len() != 64 || !hex.is_ascii() {
return None;
}
let mut digest = [0_u8; 32];
for (byte, pair) in digest.iter_mut().zip(hex.as_bytes().chunks(2)) {
*byte = u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()?;
}
Some(digest)
}
/// Writes 32 random bytes as 64 hex characters, mode 0600, unless the file is
/// already there: the secret is never read back or shown, and a file that
/// exists is the secret handles already depend on, so it is kept as it is when
/// it is a regular file, mode 0600, owned by this user and at least
/// `MIN_SECRET_BYTES` long, and refused untouched otherwise.
#[cfg(unix)]
fn ensure_secret_file(path: &std::path::Path) -> Result<(), Failure> {
use std::io::{Read, Write};
use std::os::unix::fs::OpenOptionsExt;
if !path.is_absolute() {
return Err(Failure::Malformed("--handle-secret-file"));
}
let mut file = match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
{
Ok(file) => file,
Err(_) => return existing_secret_is_usable(path),
};
let mut bytes = [0_u8; 32];
std::fs::File::open("/dev/urandom")
.and_then(|mut random| random.read_exact(&mut bytes))
.map_err(|_| Failure::Malformed("--handle-secret-file"))?;
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
file.write_all(hex.as_bytes())
.map_err(|_| Failure::Malformed("--handle-secret-file"))
}
/// An existing secret file is accepted only as the connector would use it: not
/// a link, a regular file, readable by no one else, ours and long enough.
#[cfg(unix)]
fn existing_secret_is_usable(path: &std::path::Path) -> Result<(), Failure> {
let metadata =
std::fs::symlink_metadata(path).map_err(|_| Failure::Malformed("--handle-secret-file"))?;
// SAFETY: geteuid has no preconditions and cannot fail.
let uid = unsafe { libc::geteuid() };
if secret_file_usable(&metadata, uid) {
Ok(())
} else {
Err(Failure::Malformed("--handle-secret-file"))
}
}
#[cfg(unix)]
fn secret_file_usable(metadata: &std::fs::Metadata, uid: u32) -> bool {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
metadata.is_file()
&& metadata.permissions().mode() & 0o7777 == 0o600
&& metadata.uid() == uid
&& metadata.len() >= MIN_SECRET_BYTES as u64
}
#[cfg(not(unix))]
fn ensure_secret_file(_: &std::path::Path) -> Result<(), Failure> {
Err(Failure::Usage)
}
fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(
args,
&[&INIT, &PROVIDER, &MODEL, &CALLER],
&[
"--allowed-model",
"--lease-user",
"--strict-unsupported",
"--price-band",
],
)?;
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 lease_holders = flags
.list("--lease-user")
.iter()
.map(|unix_user| {
Ok(LeaseHolderConfig {
unix_user: unix_user.clone(),
caller_id: first.caller_runtime_id.clone(),
provider: provider_id.clone(),
unit: flags.text("--unit")?,
scope: flags.scope()?,
})
})
.collect::<Result<Vec<_>, Failure>>()?;
let secret_file = matches!(provider.wire, ProviderWire::ClaudeCodeCli { .. })
.then(|| flags.single.get("--handle-secret-file").map(PathBuf::from))
.flatten();
let config = ClaudeConnectorConfig {
listen: flags.text("--listen")?,
replay_store: flags.path("--replay-store")?,
max_frame_bytes: frame_bytes_for_payload(first.max_payload_bytes),
max_connections: first.max_concurrent_requests.max(8),
socket_timeout_ms: flags.number_or("--socket-timeout-ms", 10_000)?,
max_expiry_skew_ms: 300_000,
providers: vec![provider],
models: vec![model],
callers: vec![first],
lease_socket: flags.single.get("--lease-socket").map(PathBuf::from),
lease_holders,
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
};
// Validate before the secret file exists: a refused document leaves nothing.
config.validate()?;
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], &["--price-band"])?;
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)?;
Ok(())
}
/// Appends one caller to an existing document. The serve limits grow to carry
/// it: the frame to its payload bound, the connections to every caller's slots.
fn add_caller(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(
args,
&[&CALLER, &["--max-payload-bytes"]],
&["--allowed-model"],
)?;
let caller = flags.caller()?;
let mut config = load_config(path.as_ref())?;
config.max_frame_bytes = config
.max_frame_bytes
.max(frame_bytes_for_payload(caller.max_payload_bytes));
config.callers.push(caller);
let slots: usize = config
.callers
.iter()
.map(|caller| caller.max_concurrent_requests)
.sum();
config.max_connections = config.max_connections.max(slots);
write_config(path.as_ref(), &config)?;
Ok(())
}
/// Appends one lease holder to an existing document that lends a token.
fn add_lease_holder(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(args, &[&LEASE_HOLDER, &["--lease-user"]], &[])?;
let mut config = load_config(path.as_ref())?;
config.lease_holders.push(LeaseHolderConfig {
unix_user: flags.text("--lease-user")?,
caller_id: flags.text("--caller-id")?,
provider: flags.text("--provider")?,
unit: flags.text("--unit")?,
scope: flags.scope()?,
});
write_config(path.as_ref(), &config)?;
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))]
mod tests {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use super::*;
#[test]
fn a_secret_file_owned_by_someone_else_is_not_usable() {
let dir =
std::env::temp_dir().join(format!("claude-connector-main-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("handle.secret");
std::fs::write(&path, "k".repeat(64)).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
let metadata = std::fs::symlink_metadata(&path).unwrap();
let owner = metadata.uid();
assert!(secret_file_usable(&metadata, owner));
assert!(!secret_file_usable(&metadata, owner.wrapping_add(1)));
std::fs::remove_dir_all(&dir).unwrap();
}
}

View 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;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,650 @@
//! The meter: keeps the plan's weekly reading fresh while lease holders are
//! working. The subscription reports its windows only inside the CLI's
//! `rate_limit_event`, on a call the CLI makes, and lease holders make theirs
//! under leases that report nothing back. So when the `seven_day` reading in
//! the [`QuotaCell`] is `STALE` old, the meter makes the smallest real call
//! through the backend's own path (one `claude -p` on the cheapest model with
//! a trivial prompt) and the stream fills the cell exactly as it does for any
//! call. The meter holds no credential, speaks no protocol and writes nothing
//! itself.
//!
//! The meter is driven by the connector's own lease state. It reads only
//! while a lease is held or one was asked for less than `STALE` ago: an idle
//! deployment asks for nothing, and idle lease holders spend nothing. A call
//! that fails, or completes without refreshing the reading, is not retried at
//! the staleness period: the wait doubles per consecutive miss, up to `CEILING`.
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use model_connector::{PlanQuota, Usage};
use crate::backend::ClaudeCodeBackend;
use crate::quota::{EXPIRED, QuotaCell, WEEK};
/// A reading this old, or older, is stale; also the least gap between calls.
const STALE: Duration = Duration::from_secs(15 * 60);
/// The longest any backoff may wait; also how long an idle meter sleeps
/// before looking again, since a lease request wakes it.
const CEILING: Duration = Duration::from_secs(6 * 60 * 60);
/// The smallest real call, as the backend makes it.
pub(crate) trait Probe: Send {
/// What the call billed, or the failure's kind. Never a message: a
/// provider's words do not enter the meter's log.
fn call(&self) -> Result<Usage, String>;
}
impl Probe for Arc<ClaudeCodeBackend> {
fn call(&self) -> Result<Usage, String> {
self.read_meter()
}
}
/// Why the meter is waiting. A refresh is logged every time, with the reading
/// it saw; the other states are logged once per change.
#[derive(Debug, Clone, PartialEq, Eq)]
enum State {
/// The week window as the refresh left it; a window with no reading is
/// `None`.
Read {
permille: Option<u32>,
resets_at_unix_ms: u64,
},
Idle,
/// The call failed; the kind is the failure's kind, never its message.
Failed(String),
Unread,
}
impl State {
fn line(&self) -> String {
match self {
Self::Read {
permille,
resets_at_unix_ms,
} => {
let permille = permille.map_or("unknown".to_string(), |p| p.to_string());
format!(
"meter: weekly reading refreshed, permille {permille} resets_at_unix_ms {resets_at_unix_ms}"
)
}
Self::Idle => "meter: no lease asked lately, making no call".to_string(),
Self::Failed(kind) => format!("meter: the call failed ({kind}), backing off"),
Self::Unread => {
"meter: the call completed without a weekly reading, backing off".to_string()
}
}
}
}
struct Meter {
cell: Arc<QuotaCell>,
probe: Box<dyn Probe>,
log: Box<dyn FnMut(&str) + Send>,
/// No call before this instant, unix ms.
not_before_ms: u64,
/// Consecutive calls that left the reading unrefreshed.
misses: u32,
last_state: Option<State>,
}
impl Meter {
fn new(cell: Arc<QuotaCell>, probe: Box<dyn Probe>, log: Box<dyn FnMut(&str) + Send>) -> Self {
Self {
cell,
probe,
log,
not_before_ms: 0,
misses: 0,
last_state: None,
}
}
/// Makes the call if one is due at `now_ms`; returns how long to wait
/// before looking again. Nothing is due while no lease is held or lately
/// asked for, nor before the last miss's backoff has passed, nor while the
/// weekly reading is younger than `STALE`.
fn tick(&mut self, now_ms: u64) -> Duration {
if !self.cell.wanted_at(now_ms, STALE) {
self.report(State::Idle);
return CEILING;
}
let due_at = self.due_at_ms();
if now_ms < due_at {
return Duration::from_millis(due_at - now_ms);
}
// A failed call may still have refreshed the reading: a rejected turn
// reports its windows and then errors. Only the cell says whether the
// week was read.
let called = self.probe.call();
let state = if let Some(week) = self.week_refreshed_since(now_ms) {
self.misses = 0;
State::Read {
permille: week.utilization_permille,
resets_at_unix_ms: week.resets_at_unix_ms,
}
} else {
self.misses = self.misses.saturating_add(1);
match called {
Ok(_) => State::Unread,
Err(kind) => State::Failed(kind),
}
};
self.report(state);
self.not_before_ms = now_ms.saturating_add(duration_ms(backoff(self.misses)));
Duration::from_millis(self.due_at_ms().saturating_sub(now_ms))
}
/// The earliest instant the next call may happen. A window past its reset
/// described a week that is over, so it is due at once.
fn due_at_ms(&self) -> u64 {
let stale_at = self
.cell
.snapshot()
.windows
.iter()
.find(|quota| quota.window == WEEK)
.map_or(0, |quota| {
if quota.status == EXPIRED {
0
} else {
quota.observed_at_unix_ms.saturating_add(duration_ms(STALE))
}
});
stale_at.max(self.not_before_ms)
}
/// The week window if it was observed at or after `since_ms`, from one
/// snapshot, so the logged value is the one that decided the refresh.
fn week_refreshed_since(&self, since_ms: u64) -> Option<PlanQuota> {
self.cell
.snapshot()
.windows
.into_iter()
.find(|quota| quota.window == WEEK && quota.observed_at_unix_ms >= since_ms)
}
fn report(&mut self, state: State) {
if matches!(state, State::Read { .. }) || self.last_state.as_ref() != Some(&state) {
(self.log)(&state.line());
self.last_state = Some(state);
}
}
fn run(mut self) {
loop {
let seen = self.cell.asks_so_far();
let wait = self.tick(unix_ms());
self.cell.sleep_until_asked(seen, wait);
}
}
}
/// The wait after `misses` consecutive unrefreshed calls: the staleness
/// period, doubling per miss beyond the first, up to the ceiling.
fn backoff(misses: u32) -> Duration {
let doublings = misses.saturating_sub(1).min(16);
STALE.saturating_mul(1 << doublings).min(CEILING)
}
fn duration_ms(duration: Duration) -> u64 {
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}
fn unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, duration_ms)
}
/// Starts the meter thread. It writes only through the calls it makes, and
/// logs one line to stderr per refresh of the weekly reading and one per
/// change of any other state. From here a lease asked of
/// a cell with no weekly reading waits for the meter's first read.
pub(crate) fn start(
cell: Arc<QuotaCell>,
probe: Box<dyn Probe>,
) -> std::io::Result<std::thread::JoinHandle<()>> {
cell.attach_meter();
let meter = Meter::new(
cell,
probe,
Box::new(|line| eprintln!("claude-connector: {line}")),
);
std::thread::Builder::new()
.name("claude-meter".to_string())
.spawn(move || meter.run())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::quota::Asking;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
const MIN: u64 = 60_000;
const NOW: u64 = 1_800_000_000_000;
const RESET: u64 = 4_102_444_800_000;
fn reading(status: &str) -> Vec<PlanQuota> {
vec![PlanQuota {
window: WEEK.to_string(),
utilization_permille: Some(60),
resets_at_unix_ms: RESET,
status: status.to_string(),
observed_at_unix_ms: 0,
}]
}
/// What the next call does: the instant its stream stamps a weekly
/// reading (if any) and the kind it then fails with (if any).
#[derive(Clone, Default)]
struct Script {
reading_at: Option<u64>,
status: String,
fails_with: Option<String>,
/// The used thousandths the reading reports; 60 when unset.
permille: Option<u32>,
/// The reset the reading reports; `RESET` when unset.
resets_at: Option<u64>,
}
/// A call that answers as scripted and feeds the cell the way the stream
/// does, before it fails, as a rejected turn does.
struct Calls {
cell: Arc<QuotaCell>,
made: Arc<AtomicUsize>,
script: Arc<Mutex<Script>>,
}
impl Probe for Calls {
fn call(&self) -> Result<Usage, String> {
self.made.fetch_add(1, Ordering::SeqCst);
let script = self.script.lock().unwrap().clone();
if let Some(at) = script.reading_at {
let mut week = reading(&script.status);
week[0].utilization_permille = Some(script.permille.unwrap_or(60));
week[0].resets_at_unix_ms = script.resets_at.unwrap_or(RESET);
self.cell.observe_at(at, week);
}
if let Some(kind) = script.fails_with {
return Err(kind);
}
Ok(Usage {
input_tokens: 385,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 4,
reasoning_tokens: None,
})
}
}
struct Rig {
meter: Meter,
cell: Arc<QuotaCell>,
made: Arc<AtomicUsize>,
script: Arc<Mutex<Script>>,
log: Arc<Mutex<Vec<String>>>,
/// The lease held until a test lets go of it.
lease: Option<Asking>,
}
fn rig() -> Rig {
let cell = Arc::new(QuotaCell::new());
let made = Arc::new(AtomicUsize::new(0));
let script = Arc::new(Mutex::new(Script::default()));
let log = Arc::new(Mutex::new(Vec::new()));
let sink = log.clone();
let meter = Meter::new(
cell.clone(),
Box::new(Calls {
cell: cell.clone(),
made: made.clone(),
script: script.clone(),
}),
Box::new(move |line| sink.lock().unwrap().push(line.to_string())),
);
let lease = Some(cell.asking_at(NOW));
Rig {
meter,
cell,
made,
script,
log,
lease,
}
}
impl Rig {
fn reads(&self, at: u64) {
*self.script.lock().unwrap() = Script {
reading_at: Some(at),
status: "allowed".to_string(),
fails_with: None,
..Script::default()
};
}
fn reads_nothing(&self) {
*self.script.lock().unwrap() = Script::default();
}
fn fails(&self, kind: &str) {
*self.script.lock().unwrap() = Script {
fails_with: Some(kind.to_string()),
..Script::default()
};
}
fn calls(&self) -> usize {
self.made.load(Ordering::SeqCst)
}
fn lines(&self) -> Vec<String> {
self.log.lock().unwrap().clone()
}
}
#[test]
fn an_unread_week_triggers_one_call_and_the_fresh_reading_ends_the_asking() {
let mut rig = rig();
rig.reads(NOW);
assert_eq!(rig.meter.tick(NOW), STALE, "fresh for the staleness period");
assert_eq!(rig.calls(), 1);
assert_eq!(
rig.meter.tick(NOW + 5 * MIN),
Duration::from_millis(10 * MIN)
);
assert_eq!(rig.calls(), 1, "a fresh reading makes no call");
}
#[test]
fn a_stale_reading_triggers_a_call_at_the_period_and_not_before() {
let mut rig = rig();
rig.cell.observe_at(NOW, reading("allowed"));
rig.reads(NOW + 15 * MIN);
rig.meter.tick(NOW + 15 * MIN - 1);
assert_eq!(rig.calls(), 0, "one millisecond short of stale");
rig.meter.tick(NOW + 15 * MIN);
assert_eq!(rig.calls(), 1);
}
#[test]
fn a_window_past_its_reset_is_read_at_once_not_after_the_period() {
let mut rig = rig();
let now = unix_ms();
let mut over = reading("allowed").remove(0);
over.resets_at_unix_ms = 1;
rig.cell.observe_at(now, vec![over]);
rig.reads(now);
rig.meter.tick(now);
assert_eq!(rig.calls(), 1);
}
#[test]
fn no_lease_requests_spends_nothing_however_stale_the_reading() {
let mut rig = rig();
drop(rig.lease.take());
for step in 0..10 {
let at = NOW + 15 * MIN + step * 60 * MIN;
assert_eq!(rig.meter.tick(at), CEILING);
}
assert_eq!(rig.calls(), 0);
assert_eq!(rig.lines(), vec![State::Idle.line()]);
}
#[test]
fn a_lease_asked_for_wakes_the_meter_and_the_empty_cell_is_read() {
let mut rig = rig();
drop(rig.lease.take());
rig.reads(NOW + 180 * MIN);
rig.meter.tick(NOW + 180 * MIN);
assert_eq!(rig.calls(), 0, "asked three hours ago and let go");
let _later = rig.cell.asking_at(NOW + 180 * MIN);
rig.meter.tick(NOW + 180 * MIN);
assert_eq!(rig.calls(), 1);
}
#[test]
fn a_lease_let_go_is_still_wanted_for_exactly_one_staleness_period() {
let mut rig = rig();
drop(rig.lease.take());
rig.reads(NOW + 15 * MIN - 1);
rig.meter.tick(NOW + 15 * MIN - 1);
assert_eq!(rig.calls(), 1, "one millisecond inside the period");
rig.reads(NOW + 30 * MIN);
rig.meter.tick(NOW + 30 * MIN);
assert_eq!(rig.calls(), 1, "a period after the last ask: unwanted");
}
#[test]
fn a_lease_held_for_four_hours_keeps_the_week_read_throughout() {
let mut rig = rig();
for step in 0..=16 {
let at = NOW + step * 15 * MIN;
rig.reads(at);
rig.meter.tick(at);
}
assert_eq!(
rig.calls(),
17,
"one read per period, the lease never lapsing"
);
}
#[test]
fn a_failed_call_leaves_the_cell_and_backs_off_instead_of_hammering() {
let mut rig = rig();
rig.cell.observe_at(NOW, reading("allowed"));
let before = rig.cell.snapshot();
rig.fails("Provider");
let mut at = NOW + 15 * MIN;
let mut waits = Vec::new();
for _ in 0..4 {
waits.push(rig.meter.tick(at));
at += duration_ms(*waits.last().unwrap());
}
assert_eq!(rig.calls(), 4);
assert_eq!(rig.cell.snapshot(), before, "the cell is untouched");
assert_eq!(
waits,
[15, 30, 60, 120].map(|m| Duration::from_secs(m * 60)),
"the wait doubles per consecutive miss"
);
rig.meter.tick(at - MIN);
assert_eq!(rig.calls(), 4, "nothing is asked before the backoff ends");
assert_eq!(
rig.lines(),
vec!["meter: the call failed (Provider), backing off"]
);
}
#[test]
fn the_failure_kind_is_logged_again_when_it_changes_and_not_when_it_repeats() {
let mut rig = rig();
rig.fails("Authentication");
rig.meter.tick(NOW);
rig.meter.tick(NOW + 15 * MIN);
rig.fails("InvalidRequest");
rig.meter.tick(NOW + 45 * MIN);
assert_eq!(
rig.lines(),
vec![
"meter: the call failed (Authentication), backing off",
"meter: the call failed (InvalidRequest), backing off",
]
);
}
#[test]
fn the_backoff_stops_at_the_ceiling_and_one_good_reading_resets_it() {
assert_eq!(backoff(0), STALE);
assert_eq!(backoff(1), STALE);
assert_eq!(backoff(u32::MAX), CEILING);
let mut rig = rig();
rig.fails("Provider");
rig.meter.tick(NOW);
rig.meter.tick(NOW + 15 * MIN);
assert_eq!(rig.meter.misses, 2);
rig.reads(NOW + 45 * MIN);
rig.meter.tick(NOW + 45 * MIN);
assert_eq!(rig.meter.misses, 0);
}
#[test]
fn a_call_that_completes_without_a_weekly_reading_is_a_miss_too() {
let mut rig = rig();
rig.reads_nothing();
assert_eq!(rig.meter.tick(NOW), STALE);
assert_eq!(rig.meter.tick(NOW + 15 * MIN), 2 * STALE);
assert_eq!(rig.calls(), 2);
assert_eq!(rig.lines(), vec![State::Unread.line()]);
}
#[test]
fn a_rejected_turn_that_refreshed_the_reading_and_then_errored_is_no_miss() {
let mut rig = rig();
*rig.script.lock().unwrap() = Script {
reading_at: Some(NOW),
status: "rejected".to_string(),
fails_with: Some("RateLimited".to_string()),
..Script::default()
};
assert_eq!(rig.meter.tick(NOW), STALE, "the next read is a period away");
assert_eq!(rig.meter.misses, 0);
assert_eq!(
rig.lines(),
vec![format!(
"meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}"
)]
);
rig.reads(NOW + 15 * MIN);
rig.meter.tick(NOW + 15 * MIN);
assert_eq!(rig.calls(), 2, "a rejected reading is kept fresh");
}
#[test]
fn a_reading_from_before_the_call_does_not_count_as_its_answer() {
let mut rig = rig();
// A slow concurrent sensor stamped earlier than this call began.
rig.reads(NOW - 1);
rig.meter.tick(NOW);
assert_eq!(rig.meter.misses, 1);
}
#[test]
fn a_refresh_logs_the_reading_and_an_unchanged_value_logs_again() {
let mut rig = rig();
rig.reads(NOW);
rig.meter.tick(NOW);
rig.reads(NOW + 15 * MIN);
rig.meter.tick(NOW + 15 * MIN);
let line =
format!("meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}");
assert_eq!(rig.lines(), vec![line.clone(), line]);
}
#[test]
fn the_logged_value_follows_the_reading_and_an_expired_week_is_unknown() {
let mut rig = rig();
for (at, permille) in [(NOW, 60), (NOW + 15 * MIN, 75)] {
*rig.script.lock().unwrap() = Script {
reading_at: Some(at),
status: "allowed".to_string(),
permille: Some(permille),
resets_at: Some(RESET + permille as u64),
..Script::default()
};
rig.meter.tick(at);
}
let mut expired = self::rig();
let now = unix_ms();
*expired.script.lock().unwrap() = Script {
reading_at: Some(now),
status: "allowed".to_string(),
resets_at: Some(1),
..Script::default()
};
expired.meter.tick(now);
assert_eq!(
expired.lines(),
vec!["meter: weekly reading refreshed, permille unknown resets_at_unix_ms 1"]
);
assert_eq!(
rig.lines(),
vec![
format!(
"meter: weekly reading refreshed, permille 60 resets_at_unix_ms {}",
RESET + 60
),
format!(
"meter: weekly reading refreshed, permille 75 resets_at_unix_ms {}",
RESET + 75
),
]
);
}
#[test]
fn idle_logs_once_per_change_however_often_it_repeats() {
let mut rig = rig();
rig.lease = None;
for step in 0..3 {
rig.meter.tick(NOW + 60 * MIN * (step + 1));
}
assert_eq!(rig.lines(), vec![State::Idle.line()]);
}
#[test]
fn the_log_says_what_the_meter_is_doing_in_words() {
assert_eq!(
State::Idle.line(),
"meter: no lease asked lately, making no call"
);
assert_eq!(
State::Read {
permille: None,
resets_at_unix_ms: 7
}
.line(),
"meter: weekly reading refreshed, permille unknown resets_at_unix_ms 7"
);
assert_eq!(
State::Unread.line(),
"meter: the call completed without a weekly reading, backing off"
);
}
#[test]
fn the_clock_is_the_system_clock_in_unix_milliseconds() {
let before = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let read = unix_ms();
let after = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
assert!((before.as_millis() as u64..=after.as_millis() as u64).contains(&read));
}
#[test]
fn a_started_meter_sleeps_until_a_lease_asks_and_then_reads() {
let cell = Arc::new(QuotaCell::new());
let made = Arc::new(AtomicUsize::new(0));
let probe = Calls {
cell: cell.clone(),
made: made.clone(),
script: Arc::new(Mutex::new(Script {
reading_at: Some(unix_ms() + 60 * MIN),
status: "allowed".to_string(),
fails_with: None,
..Script::default()
})),
};
start(cell.clone(), Box::new(probe)).unwrap();
std::thread::sleep(Duration::from_millis(300));
assert_eq!(made.load(Ordering::SeqCst), 0, "no lease, no call");
let _lease = cell.asking();
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while made.load(Ordering::SeqCst) == 0 {
assert!(std::time::Instant::now() < deadline, "the ask woke nobody");
std::thread::sleep(Duration::from_millis(20));
}
assert_eq!(cell.snapshot_with_week(Duration::ZERO).windows.len(), 1);
}
}

View 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;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,364 @@
//! The one OS seam: starting the child and reading its output.
use std::io;
use std::path::Path;
use std::time::Instant;
use crate::launch::ChildEnv;
/// What one read of the child's stdout produced.
#[derive(Debug, PartialEq, Eq)]
pub enum StdoutRead {
/// One non-empty line, without its terminator.
Line(Vec<u8>),
/// The child closed its stdout.
Eof,
/// The deadline passed first.
Timeout,
/// A line or the total output passed its cap.
Breach,
}
/// Starts a `claude` child. `argv[0]` is the program; the environment is
/// exactly `env`; `stdin` is written and closed. `token` is the child's
/// credential: it reaches the child on a pipe at `launch::TOKEN_FD`, once, and
/// is in no environment.
pub trait ProcessPort: Send + Sync {
fn spawn(
&self,
argv: &[String],
env: &ChildEnv,
cwd: &Path,
stdin: Vec<u8>,
token: &str,
) -> io::Result<Box<dyn RunningChild>>;
}
/// A started child. The backend ends every child with `kill` then `wait`.
pub trait RunningChild: Send {
fn read_line(&mut self, deadline: Instant) -> StdoutRead;
/// The last bytes the child wrote to stderr.
fn stderr_tail(&self) -> Vec<u8>;
/// Kills the child and everything it started.
fn kill(&mut self);
fn wait(&mut self);
}
#[cfg(unix)]
pub use unix::StdProcessPort;
#[cfg(unix)]
pub(crate) use unix::place_fd;
#[cfg(unix)]
mod unix {
use std::io::{self, BufRead, BufReader, Read, Write};
use std::os::fd::{AsRawFd, RawFd};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use super::{ProcessPort, RunningChild, StdoutRead};
use crate::config::ClaudeCodeLimits;
use crate::launch::{ChildEnv, TOKEN_FD};
/// A pipe holds a token without blocking the writer; a token is a few
/// hundred bytes, so anything near the pipe's capacity is not one.
const MAX_TOKEN_BYTES: usize = 4096;
fn cvt(result: libc::c_int) -> io::Result<libc::c_int> {
if result < 0 {
Err(io::Error::last_os_error())
} else {
Ok(result)
}
}
/// Makes `source` also descriptor `target`, open across exec. Runs between
/// fork and exec in the child, so it calls nothing but `dup2` and `fcntl`.
pub(crate) fn place_fd(source: RawFd, target: RawFd) -> io::Result<()> {
// SAFETY: dup2 and fcntl take integers only and are async-signal-safe.
unsafe {
if source == target {
// dup2 onto itself changes nothing, so the close-on-exec flag
// the pipe was created with must be cleared by hand.
let flags = cvt(libc::fcntl(target, libc::F_GETFD))?;
cvt(libc::fcntl(
target,
libc::F_SETFD,
flags & !libc::FD_CLOEXEC,
))?;
} else {
cvt(libc::dup2(source, target))?;
}
}
Ok(())
}
/// Spawns each child in its own process group, so that killing the call
/// kills what the child started too.
pub struct StdProcessPort {
limits: ClaudeCodeLimits,
}
impl StdProcessPort {
pub fn new(limits: ClaudeCodeLimits) -> Self {
Self { limits }
}
}
impl ProcessPort for StdProcessPort {
fn spawn(
&self,
argv: &[String],
env: &ChildEnv,
cwd: &Path,
stdin: Vec<u8>,
token: &str,
) -> io::Result<Box<dyn RunningChild>> {
if token.len() > MAX_TOKEN_BYTES {
return Err(io::Error::from(io::ErrorKind::InvalidInput));
}
let (program, args) = argv
.split_first()
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
let mut command = Command::new(program);
command
.args(args)
.env_clear()
.envs(env.iter())
.current_dir(cwd)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0);
// The write end closes here, so the child sees the token and then
// the end of the pipe. Both ends are close-on-exec; only the copy
// `place_fd` makes reaches the child.
let (reader, mut writer) = std::io::pipe()?;
writer.write_all(token.as_bytes())?;
drop(writer);
let source = reader.as_raw_fd();
// SAFETY: the closure calls only async-signal-safe functions.
unsafe { command.pre_exec(move || place_fd(source, TOKEN_FD)) };
let mut child = command.spawn()?;
drop(reader);
let (stdin_pipe, stdout, stderr) =
(child.stdin.take(), child.stdout.take(), child.stderr.take());
if let Some(mut pipe) = stdin_pipe {
thread::spawn(move || {
let _ = pipe.write_all(&stdin);
});
}
let (lines, receiver) = channel();
if let Some(stdout) = stdout {
let limits = self.limits;
thread::spawn(move || {
let mut reader = BufReader::new(stdout);
let mut total = 0usize;
loop {
let mut line = Vec::new();
let read = reader
.by_ref()
.take(limits.max_line_bytes as u64 + 1)
.read_until(b'\n', &mut line);
let Ok(read) = read else { break };
if read == 0 {
break;
}
total = total.saturating_add(read);
let terminated = line.last() == Some(&b'\n');
if terminated {
line.pop();
}
if line.last() == Some(&b'\r') {
line.pop();
}
if line.len() > limits.max_line_bytes || total > limits.max_total_bytes {
let _ = lines.send(Piece::Breach);
return;
}
if !line.is_empty() && lines.send(Piece::Line(line)).is_err() {
return;
}
}
});
}
let tail = Arc::new(Mutex::new(Vec::new()));
let stderr_reader = stderr.map(|mut stderr| {
let (tail, keep) = (tail.clone(), self.limits.stderr_tail_bytes);
thread::spawn(move || {
let mut chunk = [0u8; 4096];
while let Ok(read) = stderr.read(&mut chunk) {
if read == 0 {
break;
}
let mut held = tail.lock().unwrap_or_else(|e| e.into_inner());
held.extend_from_slice(&chunk[..read]);
let excess = held.len().saturating_sub(keep);
held.drain(..excess);
}
})
});
Ok(Box::new(StdChild {
child,
receiver,
tail,
stderr_reader,
reaped: false,
}))
}
}
enum Piece {
Line(Vec<u8>),
Breach,
}
struct StdChild {
child: Child,
receiver: Receiver<Piece>,
tail: Arc<Mutex<Vec<u8>>>,
stderr_reader: Option<thread::JoinHandle<()>>,
reaped: bool,
}
impl RunningChild for StdChild {
fn read_line(&mut self, deadline: Instant) -> StdoutRead {
match self
.receiver
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
{
Ok(Piece::Line(line)) => StdoutRead::Line(line),
Ok(Piece::Breach) => StdoutRead::Breach,
Err(RecvTimeoutError::Timeout) => StdoutRead::Timeout,
Err(RecvTimeoutError::Disconnected) => StdoutRead::Eof,
}
}
fn stderr_tail(&self) -> Vec<u8> {
self.tail.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
fn kill(&mut self) {
// The group leader stays a zombie until `wait`, so its pid is
// still ours to signal.
if !self.reaped {
// SAFETY: killpg takes a process group id and no pointers.
unsafe {
libc::killpg(self.child.id() as libc::pid_t, libc::SIGKILL);
}
}
}
fn wait(&mut self) {
let _ = self.child.wait();
self.reaped = true;
// Every writer to stderr died with the group, so the tail is
// complete once its reader sees the end. A process that escaped
// the group is not waited for.
if let Some(reader) = self.stderr_reader.take() {
for _ in 0..100 {
if reader.is_finished() {
let _ = reader.join();
break;
}
thread::sleep(Duration::from_millis(2));
}
}
}
}
impl Drop for StdChild {
fn drop(&mut self) {
self.kill();
self.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cloexec(fd: RawFd) -> bool {
// SAFETY: fcntl on an integer descriptor.
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
assert!(flags >= 0, "descriptor {fd} is not open");
flags & libc::FD_CLOEXEC != 0
}
/// A descriptor at or above 300 on the same pipe, so a test never
/// touches a low number another thread may be using.
fn high_dup(source: RawFd, close_on_exec: bool) -> RawFd {
let command = if close_on_exec {
libc::F_DUPFD_CLOEXEC
} else {
libc::F_DUPFD
};
// SAFETY: fcntl on an integer descriptor.
let fd = unsafe { libc::fcntl(source, command, 300) };
assert!(fd >= 300);
fd
}
/// The three tests below name descriptor numbers by value, and a number
/// one releases is the lowest free one for the next `high_dup`. They
/// hold this for their whole body, so none sees a number another
/// freed or places over one another owns.
static FDS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn fds() -> std::sync::MutexGuard<'static, ()> {
FDS.lock().unwrap_or_else(|e| e.into_inner())
}
fn close(fd: RawFd) {
// SAFETY: closing a descriptor the test owns.
unsafe { libc::close(fd) };
}
#[test]
fn placing_a_descriptor_on_itself_clears_close_on_exec() {
let _held = fds();
let (reader, _writer) = std::io::pipe().unwrap();
let fd = high_dup(reader.as_raw_fd(), true);
assert!(cloexec(fd));
place_fd(fd, fd).unwrap();
assert!(!cloexec(fd), "it must survive exec");
// One that already survives is left alone, not refused.
place_fd(fd, fd).unwrap();
assert!(!cloexec(fd));
close(fd);
}
#[test]
fn placing_a_descriptor_elsewhere_copies_it_open_across_exec() {
let _held = fds();
let (reader, _writer) = std::io::pipe().unwrap();
let source = high_dup(reader.as_raw_fd(), true);
let target = high_dup(reader.as_raw_fd(), true);
assert!(cloexec(target));
place_fd(source, target).unwrap();
assert!(!cloexec(target), "the copy survives exec");
assert!(cloexec(source), "the source does not");
close(source);
close(target);
}
#[test]
fn a_descriptor_that_is_not_open_is_refused_either_way() {
let _held = fds();
let (reader, _writer) = std::io::pipe().unwrap();
let closed = high_dup(reader.as_raw_fd(), true);
close(closed);
assert!(place_fd(closed, closed).is_err());
assert!(place_fd(closed, closed + 1).is_err());
}
}
}

View file

@ -0,0 +1,404 @@
//! The plan's own usage windows, as the subscription reports them. The
//! subscription decides how much a plan may burn, and one sensor observes it:
//! the CLI's `rate_limit_event` on the connector's own calls, which the
//! `meter` makes when the week's reading goes stale. The latest observation of
//! each window is kept here and published as the usage readout and lent with
//! each lease.
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use model_connector::{PlanQuota, PlanQuotaSnapshot};
/// The window the weekly pacing reads, and the one the meter keeps fresh.
pub(crate) const WEEK: &str = "seven_day";
/// The windows the pacing reads, and so the only ones the cell keeps.
pub(crate) const PACED: [&str; 2] = ["five_hour", WEEK];
/// How often a lease waiting for its first reading looks at the cell again.
const FIRST_READ_POLL: Duration = Duration::from_millis(50);
/// The latest observation of each plan window, shared by the backend that
/// feeds it and whatever reads it out. Each window carries the time of its
/// own observation: an event that names one window says nothing about the
/// others.
///
/// It also keeps who is asking: a lease request is the connector's sign that a
/// holder is active, and the meter reads the plan only while someone asks.
#[derive(Default)]
pub struct QuotaCell {
windows: Mutex<BTreeMap<String, PlanQuota>>,
asks: Mutex<Asks>,
asked: Condvar,
metered: AtomicBool,
}
#[derive(Default)]
struct Asks {
/// Lease requests in flight or held.
live: usize,
/// Requests ever made; the meter sleeps until it changes.
count: u64,
/// When the latest request came, unix ms.
last_ms: Option<u64>,
}
/// A lease request while it is in flight or held. Dropping it is the lease
/// ending, by whatever road.
pub(crate) struct Asking(Arc<QuotaCell>);
impl Drop for Asking {
fn drop(&mut self) {
let mut asks = self.0.asks.lock().unwrap_or_else(|e| e.into_inner());
asks.live = asks.live.saturating_sub(1);
}
}
impl QuotaCell {
pub fn new() -> Self {
Self::default()
}
/// Notes a lease request, now, and wakes the meter.
pub(crate) fn asking(self: &Arc<Self>) -> Asking {
self.asking_at(unix_ms())
}
pub(crate) fn asking_at(self: &Arc<Self>, now: u64) -> Asking {
{
let mut asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
asks.live += 1;
asks.count += 1;
asks.last_ms = Some(now);
}
self.asked.notify_all();
Asking(self.clone())
}
/// Whether a lease is held, or one was asked for less than `within` ago.
pub(crate) fn wanted_at(&self, now: u64, within: Duration) -> bool {
let asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
asks.live > 0
|| asks.last_ms.is_some_and(|last| {
now < last.saturating_add(u64::try_from(within.as_millis()).unwrap_or(u64::MAX))
})
}
pub(crate) fn asks_so_far(&self) -> u64 {
self.asks.lock().unwrap_or_else(|e| e.into_inner()).count
}
/// Sleeps up to `limit`, or until a request beyond the first `seen` comes.
pub(crate) fn sleep_until_asked(&self, seen: u64, limit: Duration) {
let asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
drop(
self.asked
.wait_timeout_while(asks, limit, |asks| asks.count == seen)
.unwrap_or_else(|e| e.into_inner()),
);
}
/// Declares that a meter reads this cell, so a first lease may wait for it.
pub(crate) fn attach_meter(&self) {
self.metered.store(true, Ordering::SeqCst);
}
/// The windows as they stand, but with no weekly reading yet (a restart
/// leaves the cell empty) a metered cell is given up to `within` to get
/// one, so a lease is not lent "unobserved" for want of a few seconds.
pub(crate) fn snapshot_with_week(&self, within: Duration) -> PlanQuotaSnapshot {
let deadline = Instant::now() + within;
loop {
let snapshot = self.snapshot();
let read = snapshot
.windows
.iter()
.any(|quota| quota.window == WEEK && quota.status != EXPIRED);
let now = Instant::now();
if read || !self.metered.load(Ordering::SeqCst) || now >= deadline {
return snapshot;
}
std::thread::sleep(FIRST_READ_POLL.min(deadline - now));
}
}
/// Records the windows one event reported, stamping each with now. See
/// [`QuotaCell::observe_at`] for how a reading combines with what is held.
pub fn observe(&self, windows: impl IntoIterator<Item = PlanQuota>) {
self.observe_at(unix_ms(), windows);
}
/// Records readings taken at `at` (unix ms). A reading older than the
/// held one is dropped, so a slow call cannot replace what a faster one
/// saw meanwhile. Windows the readings did not mention stay as they were,
/// stamp included.
pub fn observe_at(&self, at: u64, windows: impl IntoIterator<Item = PlanQuota>) {
let mut held = self.windows.lock().unwrap_or_else(|e| e.into_inner());
for mut quota in windows {
quota.observed_at_unix_ms = at;
if held
.get(&quota.window)
.is_none_or(|current| quota.observed_at_unix_ms >= current.observed_at_unix_ms)
{
held.insert(quota.window.clone(), quota);
}
}
}
pub fn snapshot(&self) -> PlanQuotaSnapshot {
self.snapshot_at(unix_ms())
}
/// The windows as of `now`. One whose reset time has passed is reported
/// `expired` with no utilization: the reading described a window that no
/// longer exists.
pub(crate) fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot {
let held = self.windows.lock().unwrap_or_else(|e| e.into_inner());
PlanQuotaSnapshot {
windows: held
.values()
.cloned()
.map(|mut quota| {
if now >= quota.resets_at_unix_ms {
quota.utilization_permille = None;
quota.status = EXPIRED.to_string();
}
quota
})
.collect(),
}
}
}
/// The status of a window whose reset has passed since it was observed.
pub(crate) const EXPIRED: &str = "expired";
fn unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| {
u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
})
}
#[cfg(test)]
mod tests {
use super::*;
const RESET: u64 = 4_102_444_800_000;
fn quota(window: &str, permille: u32, observed_at: u64) -> PlanQuota {
PlanQuota {
window: window.to_string(),
utilization_permille: Some(permille),
resets_at_unix_ms: RESET,
status: "allowed".to_string(),
observed_at_unix_ms: observed_at,
}
}
#[test]
fn an_empty_cell_has_observed_nothing() {
assert!(QuotaCell::new().snapshot().windows.is_empty());
}
#[test]
fn each_window_keeps_its_own_latest_observation_and_its_own_time() {
let cell = QuotaCell::new();
cell.observe_at(100, [quota("five_hour", 80, 0), quota("seven_day", 300, 0)]);
cell.observe_at(200, [quota("five_hour", 120, 0)]);
assert_eq!(
cell.snapshot_at(250).windows,
vec![quota("five_hour", 120, 200), quota("seven_day", 300, 100)],
"the window the later event did not name keeps its older stamp"
);
}
#[test]
fn an_event_with_no_windows_changes_nothing() {
let cell = QuotaCell::new();
cell.observe_at(100, [quota("five_hour", 80, 0)]);
cell.observe_at(900, Vec::new());
assert_eq!(
cell.snapshot_at(950).windows,
vec![quota("five_hour", 80, 100)]
);
}
#[test]
fn a_window_past_its_reset_is_expired_not_old_utilization() {
let cell = QuotaCell::new();
cell.observe_at(100, [quota("five_hour", 80, 0)]);
let live = cell.snapshot_at(RESET - 1).windows;
assert_eq!(live, vec![quota("five_hour", 80, 100)]);
let expired = cell.snapshot_at(RESET).windows;
assert_eq!(expired.len(), 1);
assert_eq!(expired[0].status, "expired");
assert_eq!(expired[0].utilization_permille, None);
assert_eq!(
expired[0].observed_at_unix_ms, 100,
"its age stays readable"
);
assert_eq!(expired[0].resets_at_unix_ms, RESET);
}
fn with_status(mut quota: PlanQuota, status: &str) -> PlanQuota {
quota.status = status.to_string();
quota
}
fn held(cell: &QuotaCell) -> (String, Option<u32>, u64) {
let window = cell.snapshot_at(250).windows.remove(0);
(
window.status,
window.utilization_permille,
window.observed_at_unix_ms,
)
}
#[test]
fn a_reading_older_than_the_held_one_is_dropped_and_an_equal_one_replaces() {
let cell = QuotaCell::new();
cell.observe_at(200, [quota("five_hour", 80, 0)]);
cell.observe_at(100, [quota("five_hour", 10, 0)]);
assert_eq!(held(&cell), ("allowed".to_string(), Some(80), 200));
cell.observe_at(200, [quota("five_hour", 90, 0)]);
assert_eq!(held(&cell), ("allowed".to_string(), Some(90), 200));
}
#[test]
fn a_newer_reading_lifts_a_rejection() {
let cell = QuotaCell::new();
cell.observe_at(100, [with_status(quota("five_hour", 1000, 0), "rejected")]);
cell.observe_at(200, [quota("five_hour", 300, 0)]);
assert_eq!(held(&cell), ("allowed".to_string(), Some(300), 200));
}
#[test]
fn the_live_clock_stamps_and_expires() {
let cell = QuotaCell::new();
let before = unix_ms();
let mut past = quota("old", 10, 0);
past.resets_at_unix_ms = 1;
cell.observe([past, quota("five_hour", 80, 0)]);
let after = unix_ms();
let windows = cell.snapshot().windows;
let stamp = windows[0].observed_at_unix_ms;
assert!((before..=after).contains(&stamp));
assert_eq!(windows[0].window, "five_hour");
assert_eq!(windows[0].utilization_permille, Some(80));
assert_eq!(windows[1].status, "expired");
}
const HOUR: u64 = 3_600_000;
#[test]
fn nobody_wants_the_plan_before_anyone_asks() {
let cell = Arc::new(QuotaCell::new());
assert!(!cell.wanted_at(0, Duration::from_secs(900)));
}
#[test]
fn a_lease_in_flight_or_held_is_wanted_for_as_long_as_it_lives() {
let cell = Arc::new(QuotaCell::new());
let lease = cell.asking_at(1_000);
let other = cell.asking_at(2_000);
let day = Duration::from_secs(86_400);
assert!(cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)));
drop(lease);
assert!(cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)), "one lease still lives");
drop(other);
assert!(!cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)));
assert!(cell.wanted_at(2_000 + 4 * HOUR, day), "within the window of the last ask");
}
#[test]
fn a_lease_let_go_is_wanted_until_exactly_the_period_after_its_ask() {
let cell = Arc::new(QuotaCell::new());
drop(cell.asking_at(10_000));
let period = Duration::from_millis(900);
assert!(cell.wanted_at(10_899, period));
assert!(!cell.wanted_at(10_900, period));
}
#[test]
fn each_ask_is_counted_and_wakes_a_sleeper_at_once() {
let cell = Arc::new(QuotaCell::new());
assert_eq!(cell.asks_so_far(), 0);
let sleeper = {
let cell = cell.clone();
std::thread::spawn(move || {
let started = Instant::now();
cell.sleep_until_asked(0, Duration::from_secs(30));
started.elapsed()
})
};
std::thread::sleep(Duration::from_millis(100));
drop(cell.asking());
assert!(sleeper.join().unwrap() < Duration::from_secs(10), "woken, not timed out");
assert_eq!(cell.asks_so_far(), 1);
// An ask that came after `seen` was read ends the sleep before it starts.
let started = Instant::now();
cell.sleep_until_asked(0, Duration::from_secs(30));
assert!(started.elapsed() < Duration::from_secs(10));
// Nothing new: the sleep is the whole limit.
let started = Instant::now();
cell.sleep_until_asked(1, Duration::from_millis(200));
assert!(started.elapsed() >= Duration::from_millis(200));
}
#[test]
fn a_metered_cell_with_no_week_gives_a_first_lease_the_reading_when_it_lands() {
let cell = Arc::new(QuotaCell::new());
cell.attach_meter();
let feeder = {
let cell = cell.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
cell.observe([quota(WEEK, 60, 0)]);
})
};
let plan = cell.snapshot_with_week(Duration::from_secs(20));
feeder.join().unwrap();
assert_eq!(plan.windows.len(), 1, "the lease waited for the week");
assert_eq!(plan.windows[0].window, WEEK);
}
#[test]
fn the_wait_for_the_first_reading_is_bounded() {
let cell = Arc::new(QuotaCell::new());
cell.attach_meter();
let started = Instant::now();
let plan = cell.snapshot_with_week(Duration::from_millis(300));
let waited = started.elapsed();
assert!(plan.windows.is_empty(), "no reading came: unobserved, not hung");
assert!(waited >= Duration::from_millis(300), "{waited:?}");
assert!(waited < Duration::from_secs(10), "{waited:?}");
}
#[test]
fn a_cell_nobody_meters_or_that_holds_the_week_is_never_waited_on() {
let bare = QuotaCell::new();
let started = Instant::now();
assert!(bare.snapshot_with_week(Duration::from_secs(20)).windows.is_empty());
let held = QuotaCell::new();
held.attach_meter();
held.observe([quota(WEEK, 60, 0)]);
assert_eq!(held.snapshot_with_week(Duration::from_secs(20)).windows.len(), 1);
assert!(started.elapsed() < Duration::from_secs(5));
}
#[test]
fn a_week_past_its_reset_is_waited_on_like_no_week() {
let cell = QuotaCell::new();
cell.attach_meter();
let mut over = quota(WEEK, 60, 0);
over.resets_at_unix_ms = 1;
cell.observe([over]);
let started = Instant::now();
cell.snapshot_with_week(Duration::from_millis(300));
assert!(started.elapsed() >= Duration::from_millis(300));
}
}

View file

@ -0,0 +1,765 @@
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,
price: None,
}
}
#[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]) {}
}
}

View file

@ -0,0 +1,447 @@
//! Reading the CLI's stream-json output. The format is foreign and moves with
//! the CLI, so every struct here ignores fields it does not name.
use std::collections::BTreeMap;
use model_connector::{FailureKind, PlanQuota, StopReason, Usage};
use serde::Deserialize;
use serde_json::Value;
use crate::quota::{PACED, QuotaCell};
/// The tool the CLI gives the model to deliver an answer that must match a
/// `--json-schema`. Its call is the structured output, not a tool exchange.
const STRUCTURED_OUTPUT_TOOL: &str = "StructuredOutput";
/// A call that cannot complete, with the stage that failed. `usage` is `None`
/// (unknown) unless a result event reported it or the
/// call never reached the provider (zero).
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Failure {
pub kind: FailureKind,
pub message: &'static str,
pub usage: Option<Usage>,
}
impl Failure {
/// A failure after the child ran: what the provider billed is unknown, so
/// the usage is unknown.
pub(crate) fn cost_unknown(kind: FailureKind, message: &'static str) -> Self {
Self {
kind,
message,
usage: None,
}
}
/// A failure before anything was sent to the provider: it bills nothing.
pub(crate) fn never_reached(kind: FailureKind, message: &'static str) -> Self {
Self {
kind,
message,
usage: Some(sum_usage(std::iter::empty())),
}
}
}
/// What the stream said, once its result event arrived.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Finished {
pub session_id: String,
/// The non-empty text blocks, in order.
pub texts: Vec<String>,
/// The id of the last assistant message.
pub message_id: Option<String>,
pub stop_reason: StopReason,
pub usage: Usage,
}
pub(crate) enum Step {
More,
Done(Box<Result<Finished, Failure>>),
}
#[derive(Deserialize)]
struct Line {
#[serde(rename = "type")]
kind: String,
subtype: Option<String>,
session_id: Option<String>,
model: Option<String>,
message: Option<Message>,
/// Read by hand: the shape moves with the CLI, and a field that changes
/// type must cost the quota reading, never the call.
rate_limit_info: Option<Value>,
is_error: Option<bool>,
stop_reason: Option<String>,
api_error_status: Option<Value>,
/// Milliseconds spent in API calls; zero means no call was made.
duration_api_ms: Option<u64>,
result: Option<Value>,
errors: Option<Value>,
/// The answer to a `--json-schema` request, an object.
structured_output: Option<Value>,
/// What this turn alone consumed. `modelUsage` is deliberately not read:
/// on a resumed session it carries every earlier turn too.
model_usage_since_last_result: Option<Value>,
}
#[derive(Deserialize)]
struct Message {
id: Option<String>,
content: Option<Vec<Block>>,
}
#[derive(Deserialize)]
struct Block {
#[serde(rename = "type")]
kind: String,
text: Option<String>,
name: Option<String>,
}
/// One model's entry. The four counts are required: an entry that lacks one
/// is a shape this reader does not know, and unknown usage is never zero.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModelUsage {
input_tokens: u64,
output_tokens: u64,
cache_read_input_tokens: u64,
cache_creation_input_tokens: u64,
thinking_tokens: Option<u64>,
}
/// One call's stream, line by line.
pub(crate) struct StreamState<'a> {
model: &'a str,
/// Whether the request carried an output schema, so the answer is the
/// result's structured output.
structured: bool,
/// Whether that schema's top type admits an object (absent counts): the
/// structured output must be an object, never a bare scalar or array.
schema_top_is_object: bool,
quota: Option<&'a QuotaCell>,
session_id: Option<String>,
texts: Vec<String>,
message_id: Option<String>,
plan_rejected: bool,
}
impl<'a> StreamState<'a> {
/// `schema` is the request's output schema text, when it carried one.
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: Option<&'a QuotaCell>) -> Self {
let top = schema
.and_then(|text| serde_json::from_str::<Value>(text).ok())
.and_then(|schema| schema.get("type").cloned());
Self {
model,
structured: schema.is_some(),
schema_top_is_object: top.is_none_or(|top| top.as_str() == Some("object")),
quota,
session_id: None,
texts: Vec::new(),
message_id: None,
plan_rejected: false,
}
}
pub(crate) fn feed(&mut self, raw: &[u8]) -> Step {
let Ok(line) = serde_json::from_slice::<Line>(raw) else {
return fail(
FailureKind::Provider,
"claude-code: a stream line did not parse",
);
};
match line.kind.as_str() {
"system" => match line.subtype.as_deref() {
Some("init") => {
if line.model.as_deref() != Some(self.model) {
return fail(
FailureKind::Provider,
"claude-code: the session model differs from the request",
);
}
self.session_id = line.session_id;
Step::More
}
Some("compact_boundary") => fail(
FailureKind::Provider,
"claude-code: the session was compacted",
),
_ => Step::More,
},
"assistant" => self.assistant(line.message),
"rate_limit_event" => {
if let Some(info) = &line.rate_limit_info {
self.plan_rejected |=
info.get("status").and_then(Value::as_str) == Some("rejected");
if let Some(quota) = self.quota {
quota.observe(plan_windows(info));
}
}
Step::More
}
"result" => Step::Done(Box::new(self.result(line))),
_ => Step::More,
}
}
fn assistant(&mut self, message: Option<Message>) -> Step {
let Some(message) = message else {
return Step::More;
};
if message.id.is_some() {
self.message_id = message.id;
}
for block in message.content.unwrap_or_default() {
match block.kind.as_str() {
"text" => {
if let Some(text) = block.text.filter(|text| !text.is_empty()) {
self.texts.push(text);
}
}
"tool_use"
if self.structured && block.name.as_deref() == Some(STRUCTURED_OUTPUT_TOOL) => {
}
"tool_use" => {
return fail(
FailureKind::Provider,
"claude-code: the model called a tool in a tool-less turn",
);
}
_ => {}
}
}
Step::More
}
fn result(&mut self, line: Line) -> Result<Finished, Failure> {
let success = line.subtype.as_deref() == Some("success") && line.is_error == Some(false);
let door_refusal = !success
&& matches!(
line.api_error_status.as_ref().and_then(Value::as_u64),
Some(401 | 403 | 429)
);
// The CLI found no credential and never called the API: an error with
// no status and no API time at all.
let no_call = !success
&& line.duration_api_ms == Some(0)
&& line.api_error_status.as_ref().is_none_or(Value::is_null);
let usage = read_usage(
line.model_usage_since_last_result,
door_refusal || no_call,
no_call,
);
if !success {
return Err(Failure {
kind: self.error_kind(&line.api_error_status, &line.result, &line.errors),
message: "claude-code: the result reported an error",
usage,
});
}
let Some(usage) = usage else {
return Err(Failure {
kind: FailureKind::Provider,
message: "claude-code: the result did not report usable usage",
usage: None,
});
};
let mut texts = std::mem::take(&mut self.texts);
if self.structured {
// The answer is the structured output alone; any prose around the
// tool call is not part of it.
let Some(output) = line
.structured_output
.filter(|value| value.is_object() && self.schema_top_is_object)
else {
return Err(Failure {
kind: FailureKind::Provider,
message: "claude-code: a schema was sent and the result carried no structured output object",
usage: Some(usage),
});
};
texts = vec![output.to_string()];
}
let stop_reason = match line.stop_reason.as_deref() {
Some("end_turn") => StopReason::EndTurn,
// The structured-output tool call is how such a turn ends.
Some("tool_use") if self.structured => StopReason::EndTurn,
Some("max_tokens") => StopReason::MaxOutputTokens,
Some("stop_sequence") => StopReason::StopSequence,
Some("refusal") => StopReason::Refusal,
Some("model_context_window_exceeded") => StopReason::ContextWindow,
_ => {
return Err(Failure {
kind: FailureKind::Provider,
message: "claude-code: the result has an unknown stop reason",
usage: Some(usage),
});
}
};
let Some(session_id) = self.session_id.take() else {
return Err(Failure {
kind: FailureKind::Provider,
message: "claude-code: the stream never announced its session",
usage: Some(usage),
});
};
Ok(Finished {
session_id,
texts,
message_id: self.message_id.take(),
stop_reason,
usage,
})
}
fn error_kind(
&self,
status: &Option<Value>,
result: &Option<Value>,
errors: &Option<Value>,
) -> FailureKind {
let status = status.as_ref().and_then(Value::as_u64);
let names_rate_limit = [result, errors].into_iter().flatten().any(|value| {
let text = value.to_string().to_lowercase();
text.contains("rate limit") || text.contains("rate_limit")
});
match status {
_ if self.plan_rejected || names_rate_limit || status == Some(429) => {
FailureKind::RateLimited
}
Some(401 | 403) => FailureKind::Authentication,
Some(400) => FailureKind::InvalidRequest,
Some(500..=599) => FailureKind::Unavailable,
_ => FailureKind::Provider,
}
}
}
/// The plan windows one `rate_limit_event` reports under
/// `rate_limit_info.unifiedWindows`: utilization as a fraction of the window,
/// reset as unix seconds. A window missing any of its three fields is skipped;
/// an unknown reading is never zero.
/// Only the windows pacing reads are taken ([`PACED`]): the event also names
/// per-model buckets, and one of those reading `rejected` must not close every
/// lease.
fn plan_windows(info: &Value) -> Vec<PlanQuota> {
let Some(windows) = info.get("unifiedWindows").and_then(Value::as_object) else {
return Vec::new();
};
windows
.iter()
.filter(|(window, _)| PACED.contains(&window.as_str()))
.filter_map(|(window, reading)| {
let utilization = reading.get("utilization")?.as_f64()?;
let resets_at = reading.get("resetsAt")?.as_u64()?;
let status = reading.get("status")?.as_str()?;
if !utilization.is_finite() || utilization < 0.0 {
return None;
}
Some(PlanQuota {
window: window.clone(),
// `as` saturates a float at the integer's bounds.
utilization_permille: Some((utilization * 1000.0).round() as u32),
resets_at_unix_ms: resets_at.saturating_mul(1000),
status: status.to_string(),
// Stamped by the cell that keeps it.
observed_at_unix_ms: 0,
})
})
.collect()
}
fn fail(kind: FailureKind, message: &'static str) -> Step {
Step::Done(Box::new(Err(Failure::cost_unknown(kind, message))))
}
/// What this turn consumed, summed over every model it used (harness side
/// calls included), or `None` when the result does not say: the field absent,
/// of another shape, or empty. An empty report is believed only where the
/// provider cannot have billed (`empty_is_zero`: a refusal at the door, 401,
/// 403 or 429, or a call never made); elsewhere the CLI also zeroes usage on
/// crashes after real work. A call never made (`absent_is_zero`) may also
/// omit the field. `None` is unknown usage.
fn read_usage(reported: Option<Value>, empty_is_zero: bool, absent_is_zero: bool) -> Option<Usage> {
let Some(reported) = reported else {
return absent_is_zero.then(|| sum_usage(std::iter::empty()));
};
let models: BTreeMap<String, ModelUsage> = serde_json::from_value(reported).ok()?;
if models.is_empty() {
return empty_is_zero.then(|| sum_usage(std::iter::empty()));
}
Some(sum_usage(models.into_values()))
}
fn sum_usage(models: impl Iterator<Item = ModelUsage>) -> Usage {
let mut usage = Usage {
input_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 0,
reasoning_tokens: None,
};
for model in models {
usage.input_tokens = usage.input_tokens.saturating_add(model.input_tokens);
usage.cache_read_tokens = usage
.cache_read_tokens
.saturating_add(model.cache_read_input_tokens);
usage.cache_write_tokens = usage
.cache_write_tokens
.saturating_add(model.cache_creation_input_tokens);
usage.output_tokens = usage.output_tokens.saturating_add(model.output_tokens);
if let Some(thinking) = model.thinking_tokens {
usage.reasoning_tokens =
Some(usage.reasoning_tokens.unwrap_or(0).saturating_add(thinking));
}
}
usage
}
#[cfg(test)]
mod tests {
use super::*;
fn windows(body: &str) -> Vec<(String, Option<u32>, u64)> {
let info: Value = serde_json::from_str(&format!(r#"{{"unifiedWindows":{body}}}"#)).unwrap();
plan_windows(&info)
.into_iter()
.map(|q| (q.window, q.utilization_permille, q.resets_at_unix_ms))
.collect()
}
#[test]
fn only_the_five_hour_and_seven_day_windows_are_taken() {
let taken = windows(
r#"{"five_hour":{"utilization":0.5,"resetsAt":2,"status":"allowed"},
"seven_day":{"utilization":0.25,"resetsAt":3,"status":"allowed"},
"seven_day_opus":{"utilization":0.1,"resetsAt":4,"status":"allowed"},
"seven_day_overage_included":{"utilization":1,"resetsAt":5,"status":"rejected"}}"#,
);
assert_eq!(
taken,
vec![
("five_hour".to_string(), Some(500), 2000),
("seven_day".to_string(), Some(250), 3000),
]
);
}
#[test]
fn a_window_missing_a_field_or_of_the_wrong_type_costs_only_itself() {
// Unknown is never zero: such a window is skipped, not read as empty.
for broken in [
r#"{"resetsAt":2,"status":"allowed"}"#,
r#"{"utilization":0.5,"status":"allowed"}"#,
r#"{"utilization":0.5,"resetsAt":2}"#,
r#"{"utilization":"high","resetsAt":2,"status":"allowed"}"#,
r#"{"utilization":-0.5,"resetsAt":2,"status":"allowed"}"#,
] {
let both = windows(&format!(
r#"{{"five_hour":{broken},"seven_day":{{"utilization":0,"resetsAt":3,"status":"allowed"}}}}"#
));
assert_eq!(both, vec![("seven_day".to_string(), Some(0), 3000)], "{broken}");
}
}
}

View file

@ -0,0 +1,360 @@
//! Which systemd unit invocation a process runs in, from the system's own
//! record: the process's cgroup says the unit, and the service manager says
//! that unit's current InvocationID. The lease listener asks this through the
//! `PeerUnits` port; the answer never comes from the peer.
//!
//! This is the one place the connector asks systemd anything. It runs
//! `systemctl show` for one read-only property of one unit and takes nothing
//! from the output but a 32-digit hex id.
use std::fs;
use std::io::Read;
use std::os::fd::{AsRawFd, BorrowedFd};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::lease::{PeerUnit, PeerUnits};
/// Answers `PeerUnits` from `<proc>/<pid>/cgroup` and `systemctl show`.
pub struct SystemdUnits {
proc_root: PathBuf,
systemctl: PathBuf,
/// How long the manager has to answer before the lease is refused.
deadline: Duration,
}
impl SystemdUnits {
/// The running system's `/proc` and `systemctl`.
pub fn system() -> Self {
Self {
proc_root: PathBuf::from("/proc"),
systemctl: PathBuf::from("/usr/bin/systemctl"),
deadline: Duration::from_secs(5),
}
}
/// The pid a process handle names now, from the handle's own record. The
/// handle holds the process's identity, so the number cannot have been
/// recycled; a process that has exited reads as `-1`.
fn pid_of(&self, process: BorrowedFd<'_>) -> Option<u32> {
let info = fs::read_to_string(
self.proc_root
.join("self/fdinfo")
.join(process.as_raw_fd().to_string()),
)
.ok()?;
info.lines()
.find_map(|line| line.strip_prefix("Pid:"))?
.trim()
.parse()
.ok()
}
fn unit_in_cgroup(&self, pid: u32) -> Option<String> {
let cgroup = fs::read_to_string(self.proc_root.join(pid.to_string()).join("cgroup"));
unit_of_cgroup(&cgroup.ok()?)
}
/// `systemctl show` of `unit`'s InvocationID, killed and refused if it has
/// not exited by the deadline.
fn invocation_of(&self, unit: &str) -> Option<String> {
let mut child = Command::new(&self.systemctl)
.env_clear()
.args(["show", "--property=InvocationID", "--value", "--", unit])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let give_up = Instant::now() + self.deadline;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if Instant::now() < give_up => {
std::thread::sleep(Duration::from_millis(10));
}
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
};
if !status.success() {
return None;
}
// The id is 33 bytes; anything past a small bound is not an answer.
let mut output = Vec::new();
child
.stdout
.take()?
.take(256)
.read_to_end(&mut output)
.ok()?;
invocation_id_of(std::str::from_utf8(&output).ok()?)
}
}
/// The service unit a cgroup file puts its process in: the last component of
/// the unified-hierarchy path, if it names a `.service`. A process in a
/// sub-cgroup, a scope, a slice or the root is in no service unit this
/// recognises.
pub fn unit_of_cgroup(cgroup: &str) -> Option<String> {
let path = cgroup.lines().find_map(|line| line.strip_prefix("0::"))?;
let unit = path.rsplit('/').next()?;
(unit.len() > ".service".len() && unit.ends_with(".service")).then(|| unit.to_string())
}
/// An InvocationID as `systemctl show --value` prints it: 32 lowercase hex
/// digits and a newline. Anything else (including the empty answer of a unit
/// that is not running) is not an invocation.
pub fn invocation_id_of(output: &str) -> Option<String> {
let id = output.strip_suffix('\n').unwrap_or(output);
(id.len() == 32 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
.then(|| id.to_string())
}
impl PeerUnits for SystemdUnits {
fn invocation_in(&self, process: BorrowedFd<'_>, unit: &str) -> Option<PeerUnit> {
let pid = self.pid_of(process)?;
// A process in any other unit is not asked about.
if self.unit_in_cgroup(pid).as_deref() != Some(unit) {
return None;
}
let invocation_id = self.invocation_of(unit)?;
// The same process must still be in that unit now: one that left (or
// died) while the manager was asked is not vouched for.
(self.pid_of(process) == Some(pid) && self.unit_in_cgroup(pid).as_deref() == Some(unit))
.then(|| PeerUnit {
unit: unit.to_string(),
invocation_id,
})
}
}
#[cfg(test)]
mod tests {
use std::os::fd::{AsFd, AsRawFd, OwnedFd};
use super::*;
#[test]
fn a_service_unit_is_the_last_cgroup_component() {
let service = "0::/system.slice/system-agent\\x2dpool.slice/agent@alice.service\n";
assert_eq!(
unit_of_cgroup(service).as_deref(),
Some("agent@alice.service")
);
// Several hierarchies listed: the unified one decides.
let hybrid = "12:cpu:/foo\n0::/system.slice/agent@a.service\n";
assert_eq!(unit_of_cgroup(hybrid).as_deref(), Some("agent@a.service"));
let plain = "0::/system.slice/other.service\n";
assert_eq!(unit_of_cgroup(plain).as_deref(), Some("other.service"));
}
#[test]
fn a_process_outside_a_service_unit_has_none() {
for cgroup in [
"0::/\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::/system.slice/agent@alice.service/sub\n",
"0::/system.slice/.service\n",
"1:name=systemd:/system.slice/a.service\n",
"",
] {
assert_eq!(unit_of_cgroup(cgroup), None, "{cgroup:?}");
}
}
#[test]
fn an_invocation_id_is_exactly_32_lowercase_hex_digits() {
let id = "0123456789abcdef0123456789abcdef";
assert_eq!(invocation_id_of(&format!("{id}\n")).as_deref(), Some(id));
assert_eq!(invocation_id_of(id).as_deref(), Some(id));
for bad in [
"",
"\n",
"0123456789ABCDEF0123456789ABCDEF\n",
"0123456789abcdef0123456789abcde\n",
"0123456789abcdef0123456789abcdef0\n",
"0123456789abcdef0123456789abcdeg\n",
"0123456789abcdef0123456789abcdef\n\n",
] {
assert_eq!(invocation_id_of(bad), None, "{bad:?}");
}
}
const ID: &str = "0123456789abcdef0123456789abcdef";
const UNIT: &str = "worker@node.service";
/// A fake `/proc` with one process in `cgroup`, and a fake `systemctl`
/// that records its arguments, runs `side_effect`, and exits `status`
/// after printing `output`.
struct Fake {
dir: PathBuf,
units: SystemdUnits,
// A script being written while another test forks is "text file
// busy" when it is run: fakes take turns.
_turn: std::sync::MutexGuard<'static, ()>,
}
static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
impl Fake {
fn new(name: &str, cgroup: &str, output: &str, status: i32, side_effect: &str) -> Self {
use std::os::unix::fs::PermissionsExt;
let turn = TURN
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = std::env::temp_dir().join(format!("unit-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let side_effect = side_effect.replace("{d}", &dir.display().to_string());
fs::create_dir_all(dir.join("proc/42")).unwrap();
fs::write(dir.join("proc/42/cgroup"), cgroup).unwrap();
let script = dir.join("systemctl");
fs::write(
&script,
format!(
"#!/bin/sh\nprintf '%s' \"$*\" > {d}/args\n{side_effect}\nprintf '%s' '{output}'\nexit {status}\n",
d = dir.display()
),
)
.unwrap();
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
let units = SystemdUnits {
proc_root: dir.join("proc"),
systemctl: script,
deadline: Duration::from_secs(5),
};
Self {
dir,
units,
_turn: turn,
}
}
/// A process handle that names process `pid`, as the kernel's own
/// record of the handle says (`-1` once the process has exited).
fn process(&self, pid: i64) -> OwnedFd {
let handle: OwnedFd = fs::File::open("/dev/null").unwrap().into();
let info = self.dir.join("proc/self/fdinfo");
fs::create_dir_all(&info).unwrap();
fs::write(
info.join(handle.as_raw_fd().to_string()),
format!("pos:\t0\nflags:\t02000002\nPid:\t{pid}\nNSpid:\t{pid}\n"),
)
.unwrap();
handle
}
fn invocation_in(&self, pid: i64, unit: &str) -> Option<PeerUnit> {
self.units.invocation_in(self.process(pid).as_fd(), unit)
}
fn args(&self) -> String {
fs::read_to_string(self.dir.join("args")).unwrap()
}
}
impl Drop for Fake {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.dir);
}
}
fn eureka_cgroup() -> String {
format!("0::/system.slice/{UNIT}\n")
}
#[test]
fn a_process_in_the_unit_is_that_unit_at_the_invocation_the_manager_reports() {
let fake = Fake::new("ok", &eureka_cgroup(), &format!("{ID}\n"), 0, "");
assert_eq!(
fake.invocation_in(42, UNIT),
Some(PeerUnit {
unit: UNIT.to_string(),
invocation_id: ID.to_string()
})
);
// The manager is asked for exactly the invocation of that unit.
assert_eq!(
fake.args(),
format!("show --property=InvocationID --value -- {UNIT}")
);
// A handle on a process that has exited, or on one with no cgroup
// record, is in no unit.
assert_eq!(fake.invocation_in(-1, UNIT), None);
assert_eq!(fake.invocation_in(43, UNIT), None);
}
#[test]
fn a_process_outside_the_unit_is_not_asked_about() {
let scope = Fake::new("scope", "0::/user.slice/session-3.scope\n", ID, 0, "");
assert_eq!(scope.invocation_in(42, UNIT), None);
assert!(!scope.dir.join("args").exists());
drop(scope);
// Another service, even a real one, is not the caller's unit: the
// manager is never spawned for it.
let other = Fake::new("other", "0::/system.slice/ssh.service\n", ID, 0, "");
assert_eq!(other.invocation_in(42, UNIT), None);
assert!(!other.dir.join("args").exists());
}
#[test]
fn a_manager_that_fails_or_names_no_invocation_vouches_for_nothing() {
let failed = Fake::new("fail", &eureka_cgroup(), ID, 1, "");
assert_eq!(failed.invocation_in(42, UNIT), None);
drop(failed);
let not_running = Fake::new("idle", &eureka_cgroup(), "\n", 0, "");
assert_eq!(not_running.invocation_in(42, UNIT), None);
let missing = SystemdUnits {
proc_root: not_running.dir.join("proc"),
systemctl: not_running.dir.join("no-such-systemctl"),
deadline: Duration::from_secs(5),
};
assert_eq!(
missing.invocation_in(not_running.process(42).as_fd(), UNIT),
None
);
}
#[test]
fn a_manager_that_does_not_answer_in_time_is_killed_and_the_lease_refused() {
let mut fake = Fake::new("hung", &eureka_cgroup(), ID, 0, "exec sleep 30");
fake.units.deadline = Duration::from_millis(200);
let started = Instant::now();
assert_eq!(fake.invocation_in(42, UNIT), None);
assert!(started.elapsed() < Duration::from_secs(5));
}
#[test]
fn a_process_that_left_its_unit_while_the_manager_was_asked_is_not_vouched_for() {
let fake = Fake::new(
"moves",
&eureka_cgroup(),
ID,
0,
"printf '0::/system.slice/other.service\n' > {d}/proc/42/cgroup",
);
assert_eq!(fake.invocation_in(42, UNIT), None);
}
#[test]
fn a_process_that_exited_while_the_manager_was_asked_is_not_vouched_for() {
let fake = Fake::new("dies", &eureka_cgroup(), ID, 0, "");
let handle = fake.process(42);
let side = fake
.dir
.join("proc/self/fdinfo")
.join(handle.as_raw_fd().to_string());
let mut script = fs::read_to_string(fake.dir.join("systemctl")).unwrap();
script = script.replace(
"exit 0",
&format!("printf 'Pid:\t-1\n' > {}\nexit 0", side.display()),
);
fs::write(fake.dir.join("systemctl"), script).unwrap();
assert_eq!(fake.units.invocation_in(handle.as_fd(), UNIT), None);
}
}

View file

@ -0,0 +1,797 @@
//! `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,
price: None,
}],
)
.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

View file

@ -0,0 +1,4 @@
{"type":"system","subtype":"init","cwd":"/tmp/meter-probe.Ye68uq/work","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","tools":[],"mcp_servers":[],"model":"claude-haiku-5-5","permissionMode":"bypassPermissions","slash_commands":[],"apiKeySource":"none","claude_code_version":"2.1.312","output_style":"default","agents":["claude","Explore","general-purpose","Plan","statusline-setup"],"skills":[],"plugins":[{"name":"cc-plugin-sec-default","path":"builtin","source":"cc-plugin-sec-default@builtin"},{"name":"cc-plugin-agents-md","path":"builtin","source":"cc-plugin-agents-md@builtin"},{"name":"cc-plugin-telemetry","path":"builtin","source":"cc-plugin-telemetry@builtin"},{"name":"cc-plugin-plugin-authoring","path":"builtin","source":"cc-plugin-plugin-authoring@builtin"}],"capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"analytics_disabled":false,"product_feedback_disabled":false,"uuid":"8ad7f8d7-2831-43f2-a221-8af6323dcbd9","memory_paths":{"auto":"/tmp/meter-probe.Ye68uq/home/projects/-tmp-meter-probe-Ye68uq-work/memory/"},"original_cwd":"/tmp/meter-probe.Ye68uq/work","additional_directories":[],"messaging_socket_path":"/tmp/cc-socks/2838104.sock","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","per_turn_effort_active":true,"view_mode":"default"}
{"type":"assistant","message":{"model":"claude-haiku-5-5","id":"msg_011Cgfu1sQvRAVmjwWNHc58s","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":384,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":4,"service_tier":"standard","inference_geo":"global","speed":"standard"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","uuid":"f80db687-b098-415c-ac44-51c40a6cb63a","timestamp":"2026-11-03T11:14:35.024Z","request_id":"req_011Cgfu1sCXBsDrfz8a1LoMd"}
{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1794261600,"rateLimitType":"seven_day","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false,"unifiedWindows":{"seven_day":{"utilization":0.06,"resetsAt":1794261600,"status":"allowed"}}},"uuid":"acb3b364-a218-4965-b967-f73028254f8b","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01"}
{"duration_api_ms":995,"stop_reason":"end_turn","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","total_cost_usd":0.000040400000000000006,"usage":{"input_tokens":384,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":4,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[{"input_tokens":384,"output_tokens":4,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-haiku-5-5":{"inputTokens":384,"outputTokens":4,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.000040400000000000006,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":0,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":false,"num_turns":1,"subtype":"success","api_error_status":null,"result":"ok","ttft_ms":1210,"type":"result","duration_ms":1228,"uuid":"d0b1b31b-1428-45aa-b90e-d35903c9b91b","ttft_stream_ms":1209,"time_to_request_ms":232,"first_content_frame_ms":1209,"queued_turn_count":0,"result_index":0,"model_usage_since_last_result":{"claude-haiku-5-5":{"inputTokens":384,"outputTokens":4,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.000040400000000000006,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":0,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}}}

View file

@ -0,0 +1,21 @@
# lease_v2 fixtures
The exact bytes of the claude lease protocol v2: each file is one whole frame (a u32
big-endian length, then the named-MessagePack map `{kind, value}`).
- `request.bin`: `claude_lease_request`.
- `refusal_unknown_caller.bin`, `refusal_expired.bin`, `refusal_busy.bin`,
`refusal_provider_rejected.bin`: `claude_lease_refusal`; `kind` is the variant name as a
PascalCase string.
- `grant.bin`: `claude_lease_grant` with `lease_id` and `plan_quota` carrying `five_hour` and
`seven_day` windows (utilization_permille, resets_at_unix_ms, status, observed_at_unix_ms).
On the wire the grant travels with one SCM_RIGHTS fd; the file holds the frame only.
- `usage_readout_request.bin`: `claude_usage_readout_request`, an empty map; opens no lease.
- `usage_readout.bin`: `claude_usage_readout`, the kit's `UsageReadout` v2 (`schema_id`,
`at_unix_ms`, `spend` rows of `CallerModelSpend`, and `plan_quota` with `five_hour` and
`seven_day` windows); no fd travels with it.
Huginn's lease client vendors these files from this repository and tests against the same
bytes. Generator: `tests/lease_wire_golden.rs`; run it with `LEASE_V2_REGENERATE=1`, then
review the diff: a changed byte is a wire change.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,911 @@
//! 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
//! 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.
#![cfg(target_os = "linux")]
use std::fs::File;
use std::io::{Read, Write};
use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use claude_connector::{
LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource,
decode_frame, encode_frame, serve_leases,
};
use model_connector::{
CallerAdmission, LeaseScope, PlanQuota, PriceRow, ProviderRequest, ProviderRoutes, StopReason,
TokenRates, TransportAdmission, TransportInvocation, TransportKey, TransportOutcome,
TransportService, Usage, UsageReadout, encrypt_invocation, provider_request_sha256,
};
use zeroize::Zeroizing;
const CALLER: &str = "eureka";
const MODEL: &str = "claude-opus-5-1";
const TOKEN: &str = "sk-canary-lease-4c1f9a";
const UNIT: &str = "agent@alice.service";
static SEQUENCE: AtomicUsize = AtomicUsize::new(0);
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64
}
fn own_uid() -> u32 {
// SAFETY: geteuid has no preconditions and cannot fail.
unsafe { libc::geteuid() }
}
/// The 32-digit invocation id of the test's `n`th unit invocation.
fn invocation(n: u64) -> String {
format!("{n:032x}")
}
type Probe = Box<dyn Fn() + Send + Sync>;
/// A token source that counts its reads and can run a probe at the moment of
/// each one.
struct FakeTokens {
token: Option<&'static str>,
reads: AtomicUsize,
probe: Mutex<Option<Probe>>,
}
impl TokenSource for FakeTokens {
fn read(&self) -> Option<Zeroizing<String>> {
self.reads.fetch_add(1, Ordering::SeqCst);
if let Some(probe) = self.probe.lock().unwrap().as_ref() {
probe();
}
self.token.map(|token| Zeroizing::new(token.to_string()))
}
}
/// The system's record of where every peer runs, as the test sets it, and the
/// pid each handle it was asked about names (by the kernel's own record).
struct FakeUnits {
peer: Mutex<Option<PeerUnit>>,
asked_about: Mutex<Vec<(String, String)>>,
}
impl PeerUnits for FakeUnits {
fn invocation_in(&self, process: BorrowedFd<'_>, unit: &str) -> Option<PeerUnit> {
let info =
std::fs::read_to_string(format!("/proc/self/fdinfo/{}", process.as_raw_fd())).unwrap();
let pid = info
.lines()
.find_map(|line| line.strip_prefix("Pid:"))
.unwrap()
.trim()
.to_string();
self.asked_about
.lock()
.unwrap()
.push((pid, unit.to_string()));
self.peer.lock().unwrap().clone()
}
}
struct Harness {
dir: PathBuf,
socket: PathBuf,
_service: Arc<Mutex<TransportService>>,
quota: Arc<QuotaCell>,
tokens: Arc<FakeTokens>,
/// The fake behind the listener, when it has one.
units: Option<Arc<FakeUnits>>,
}
impl Harness {
/// The peers connect from invocation `n` of the configured unit.
fn enter(&self, n: u64) {
self.run_in(UNIT, n);
}
fn run_in(&self, unit: &str, n: u64) {
*self.units.as_ref().unwrap().peer.lock().unwrap() = Some(PeerUnit {
unit: unit.to_string(),
invocation_id: invocation(n),
});
}
}
impl Drop for Harness {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn receive(stream: &UnixStream) -> (Vec<u8>, Vec<OwnedFd>) {
use std::os::fd::AsRawFd;
let mut buffer = vec![0_u8; 70_000];
let mut control = vec![0_u64; 32];
let mut vector = libc::iovec {
iov_base: buffer.as_mut_ptr().cast(),
iov_len: buffer.len(),
};
// SAFETY: the buffers outlive the call and the lengths describe them; the
// descriptors read out of the control messages were just installed in this
// process by the kernel and are owned by nothing else.
unsafe {
let mut message: libc::msghdr = std::mem::zeroed();
message.msg_iov = &mut vector;
message.msg_iovlen = 1;
message.msg_control = control.as_mut_ptr().cast();
message.msg_controllen = (control.len() * 8) as _;
let received = libc::recvmsg(stream.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC);
if received < 0 {
// A listener that drops a connection with our request unread
// resets it: that is end of file for this test's purposes.
let error = std::io::Error::last_os_error();
assert_eq!(error.kind(), std::io::ErrorKind::ConnectionReset, "{error}");
return (Vec::new(), Vec::new());
}
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 bytes = (*header).cmsg_len as usize - libc::CMSG_LEN(0) as usize;
let data = libc::CMSG_DATA(header).cast::<RawFd>();
for index in 0..bytes / std::mem::size_of::<RawFd>() {
fds.push(OwnedFd::from_raw_fd(data.add(index).read_unaligned()));
}
}
header = libc::CMSG_NXTHDR(&message, header);
}
buffer.truncate(received as usize);
(buffer, fds)
}
}
fn request(ttl_ms: u64) -> LeaseMessage {
LeaseMessage::ClaudeLeaseRequest(LeaseRequest {
expires_at_unix_ms: now_ms() + ttl_ms,
})
}
/// What one request to the listener came back with.
struct Answer {
_stream: UnixStream,
raw: Vec<u8>,
message: Option<LeaseMessage>,
fds: Vec<OwnedFd>,
}
fn ask(harness: &Harness, ttl_ms: u64) -> Answer {
ask_at(&harness.socket, ttl_ms)
}
fn ask_at(socket: &std::path::Path, ttl_ms: u64) -> Answer {
let mut stream = UnixStream::connect(socket).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
// A listener at its limit has already dropped us: the write may fail.
let _ = stream.write_all(&encode_frame(&request(ttl_ms)));
let (raw, fds) = receive(&stream);
let message = decode_frame(&raw);
Answer {
_stream: stream,
raw,
message,
fds,
}
}
fn refusal_of(answer: &Answer) -> Option<LeaseRefusalKind> {
match &answer.message {
Some(LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { kind, .. })) => Some(*kind),
_ => None,
}
}
fn granted(answer: &Answer) -> LeaseGranted {
match &answer.message {
Some(LeaseMessage::ClaudeLeaseGrant(grant)) => grant.clone(),
other => panic!("expected a grant, got {other:?}"),
}
}
fn granted_ok(answer: &Answer) -> bool {
matches!(answer.message, Some(LeaseMessage::ClaudeLeaseGrant(_))) && answer.fds.len() == 1
}
fn contains(haystack: &[u8], needle: &str) -> bool {
haystack
.windows(needle.len())
.any(|window| window == needle.as_bytes())
}
/// What a harness is built from.
struct Setup {
uid: u32,
scope: LeaseScope,
unit: &'static str,
token: Option<&'static str>,
max_connections: usize,
}
fn setup() -> Setup {
Setup {
uid: own_uid(),
scope: LeaseScope::PerCaller,
unit: UNIT,
token: Some(TOKEN),
max_connections: 8,
}
}
/// A listener serving `uid` as the caller `eureka`. Peers start in invocation
/// 1 of the configured unit.
fn start(setup: Setup) -> Harness {
start_with(
setup,
ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap(),
vec![
CallerAdmission::new(
CALLER,
"lease-test-connection-key",
1,
[MODEL.to_string()],
1,
65_536,
32_768,
)
.unwrap(),
],
)
}
fn start_with(setup: Setup, routes: ProviderRoutes, admissions: Vec<CallerAdmission>) -> Harness {
let units = Arc::new(FakeUnits {
peer: Mutex::new(None),
asked_about: Mutex::new(Vec::new()),
});
let dir = std::env::temp_dir().join(format!(
"claude-lease-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::SeqCst)
));
std::fs::create_dir_all(&dir).unwrap();
let socket = dir.join("lease.sock");
let opened =
TransportService::open(&dir.join("replay.cc"), routes, admissions, 300_000).unwrap();
let spend = opened.spend_snapshot();
let service = Arc::new(Mutex::new(opened));
let tokens = Arc::new(FakeTokens {
token: setup.token,
reads: AtomicUsize::new(0),
probe: Mutex::new(None),
});
let quota = Arc::new(QuotaCell::new());
let listener = UnixListener::bind(&socket).unwrap();
let serving = (
service.clone(),
spend,
quota.clone(),
tokens.clone(),
units.clone(),
);
let holder = LeaseHolder {
uid: setup.uid,
caller_id: CALLER.to_string(),
provider: "claude-code".to_string(),
unit: setup.unit.to_string(),
scope: setup.scope,
};
std::thread::spawn(move || {
let _ = serve_leases(
&listener,
vec![holder],
LeaseLimits {
socket_timeout: Duration::from_secs(2),
max_lease_ms: 3_600_000,
max_connections: setup.max_connections,
},
serving.0,
serving.1,
serving.2,
serving.3,
serving.4,
);
});
let harness = Harness {
dir,
socket,
_service: service,
quota,
tokens,
units: Some(units),
};
harness.enter(1);
harness
}
fn window(name: &str, permille: u32, status: &str, resets_at_unix_ms: u64) -> PlanQuota {
PlanQuota {
window: name.to_string(),
utilization_permille: Some(permille),
resets_at_unix_ms,
status: status.to_string(),
observed_at_unix_ms: 0,
}
}
/// Asks as fresh unit invocations until a lease is granted, or panics.
fn ask_until_granted(harness: &Harness, first_invocation: u64) -> Answer {
let deadline = Instant::now() + Duration::from_secs(8);
let mut n = first_invocation;
loop {
harness.enter(n);
let answer = ask(harness, 60_000);
if granted_ok(&answer) {
return answer;
}
assert!(Instant::now() < deadline, "no lease was ever granted");
n += 1;
std::thread::sleep(Duration::from_millis(100));
}
}
#[test]
fn a_grant_passes_one_fd_holding_the_token_then_end_of_file() {
let harness = start(setup());
let mut answer = ask(&harness, 60_000);
assert_eq!(
granted(&answer).lease_id,
format!("lease:{}", invocation(1))
);
assert_eq!(answer.fds.len(), 1);
let mut read = Vec::new();
File::from(answer.fds.remove(0))
.read_to_end(&mut read)
.unwrap();
assert_eq!(read, TOKEN.as_bytes());
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 1);
assert!(
!contains(&answer.raw, TOKEN),
"the token is in the pipe only"
);
}
#[test]
fn a_grant_carries_the_plan_usage_as_the_connector_last_saw_it() {
let harness = start(setup());
let reset = now_ms() + 3_600_000;
harness
.quota
.observe([window("five_hour", 420, "allowed", reset)]);
let answer = ask(&harness, 60_000);
let quota = granted(&answer).plan_quota;
assert_eq!(quota.len(), 1);
assert_eq!(quota[0].window, "five_hour");
assert_eq!(quota[0].utilization_permille, Some(420));
assert_eq!(quota[0].status, "allowed");
assert_eq!(quota[0].resets_at_unix_ms, reset);
}
#[test]
fn a_lease_ends_when_its_holder_closes() {
let harness = start(setup());
let first = ask(&harness, 60_000);
assert!(granted_ok(&first));
harness.enter(2);
let second = ask(&harness, 60_000);
assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy));
assert!(second.fds.is_empty());
drop(first);
let third = ask_until_granted(&harness, 3);
assert!(granted_ok(&third));
}
#[test]
fn a_lease_ends_when_its_unit_invocation_ends() {
let harness = start(setup());
let first = ask(&harness, 60_000);
assert!(granted_ok(&first));
// The invocation is over: the system no longer places the peer in it. The
// holder still has its socket open, and the lease does not outlive it.
*harness.units.as_ref().unwrap().peer.lock().unwrap() = None;
std::thread::sleep(Duration::from_millis(1_200));
harness.enter(2);
assert!(granted_ok(&ask(&harness, 60_000)));
drop(first);
}
#[test]
fn a_lease_ends_at_its_expiry_though_its_holder_is_still_there() {
let harness = start(setup());
let first = ask(&harness, 700);
assert!(granted_ok(&first));
let next = ask_until_granted(&harness, 2);
assert!(granted_ok(&next));
drop(first);
}
#[test]
fn a_rejected_window_refuses_the_lease_until_its_reset() {
let harness = start(setup());
let reset = now_ms() + 1_500;
harness
.quota
.observe([window("five_hour", 1_000, "rejected", reset)]);
let refused = ask(&harness, 60_000);
assert_eq!(
refusal_of(&refused),
Some(LeaseRefusalKind::ProviderRejected)
);
assert!(refused.fds.is_empty());
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
// At the provider's own reset the refusal lifts, with no one lifting it.
let lifted = ask_until_granted(&harness, 2);
assert!(granted_ok(&lifted));
assert!(now_ms() >= reset);
}
#[test]
fn high_utilization_refuses_nothing() {
let harness = start(setup());
let reset = now_ms() + 3_600_000;
harness.quota.observe([
window("five_hour", 999, "allowed", reset),
window("seven_day", 1_000, "allowed_warning", reset),
]);
assert!(granted_ok(&ask(&harness, 60_000)));
}
#[test]
fn a_peer_uid_outside_the_lease_holders_is_refused_and_nothing_is_read() {
let harness = start(Setup {
uid: own_uid().wrapping_add(1),
..setup()
});
let answer = ask(&harness, 60_000);
assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller));
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
}
#[test]
fn the_configured_uid_outside_the_configured_unit_is_refused_and_nothing_is_read() {
let harness = start(setup());
harness.run_in("other.service", 1);
let answer = ask(&harness, 60_000);
assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller));
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
}
#[test]
fn an_expiry_in_the_past_or_past_the_bound_is_refused() {
let harness = start(setup());
let past = ask(&harness, 0);
assert_eq!(refusal_of(&past), Some(LeaseRefusalKind::Expired));
let far = ask(&harness, 3_600_001 + 60_000);
assert_eq!(refusal_of(&far), Some(LeaseRefusalKind::Expired));
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
}
#[test]
fn a_token_that_cannot_be_read_is_never_lent_and_frees_the_lease() {
let harness = start(Setup {
token: None,
..setup()
});
let first = ask(&harness, 60_000);
assert!(first.raw.is_empty() && first.fds.is_empty());
harness.enter(2);
let again = ask(&harness, 60_000);
assert!(again.message.is_none() && again.fds.is_empty(), "not Busy");
assert!(harness.tokens.reads.load(Ordering::SeqCst) >= 2);
}
#[test]
fn the_protocol_has_no_settle_frame() {
let grant = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted {
lease_id: "lease:x".to_string(),
plan_quota: Vec::new(),
}));
let value: rmpv::Value = rmp_serde::from_slice(&grant[4..]).unwrap();
assert_eq!(
value,
rmpv::Value::Map(vec![
("kind".into(), "claude_lease_grant".into()),
(
"value".into(),
rmpv::Value::Map(vec![
("lease_id".into(), "lease:x".into()),
("plan_quota".into(), rmpv::Value::Array(Vec::new())),
])
),
])
);
// A frame of the old kind is no message at all.
let old = rmpv::Value::Map(vec![
("kind".into(), "claude_lease_settle".into()),
(
"value".into(),
rmpv::Value::Map(vec![
("lease_id".into(), "lease:x".into()),
("usage".into(), rmpv::Value::Array(Vec::new())),
]),
),
]);
let mut body = Vec::new();
rmpv::encode::write_value(&mut body, &old).unwrap();
let mut frame = (body.len() as u32).to_be_bytes().to_vec();
frame.extend(body);
assert_eq!(decode_frame(&frame), None);
}
#[test]
fn connections_past_the_limit_are_dropped_and_finished_ones_free_their_place() {
let harness = start(Setup {
max_connections: 1,
..setup()
});
let first = ask(&harness, 60_000);
assert!(granted_ok(&first));
let second = ask(&harness, 60_000);
assert!(second.message.is_none() && second.fds.is_empty());
drop(first);
assert!(granted_ok(&ask_until_granted(&harness, 2)));
}
#[test]
fn a_lease_survives_many_polls_while_its_holder_and_invocation_stay() {
let harness = start(setup());
let mut first = ask(&harness, 60_000);
assert!(granted_ok(&first));
// Three polls later the lease still holds: a second invocation is Busy.
std::thread::sleep(Duration::from_millis(1_700));
harness.enter(2);
let second = ask(&harness, 60_000);
assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy));
// The system still places the holder in invocation 1.
harness.enter(1);
// The holder talking does not end it either.
first._stream.write_all(b"x").unwrap();
std::thread::sleep(Duration::from_millis(1_200));
assert_eq!(
refusal_of(&ask(&harness, 60_000)),
Some(LeaseRefusalKind::Busy)
);
}
#[test]
fn a_lease_ends_when_the_unit_runs_a_different_invocation() {
let harness = start(setup());
let first = ask(&harness, 60_000);
assert!(granted_ok(&first));
// The same unit, a new invocation: the one that leased is over.
harness.enter(2);
std::thread::sleep(Duration::from_millis(1_200));
assert!(granted_ok(&ask(&harness, 60_000)));
drop(first);
}
#[test]
fn a_lease_asks_the_system_about_its_holders_process_for_its_own_unit() {
let harness = start(setup());
let first = ask(&harness, 60_000);
assert!(granted_ok(&first));
std::thread::sleep(Duration::from_millis(1_200));
let asked = harness
.units
.as_ref()
.unwrap()
.asked_about
.lock()
.unwrap()
.clone();
assert!(asked.len() >= 3, "the hold polled: {asked:?}");
assert!(asked.iter().all(|(_, unit)| unit == UNIT));
}
#[test]
fn an_account_resolves_to_its_uid_and_a_missing_one_to_none() {
assert_eq!(claude_connector::user_uid("root"), Some(0));
assert_eq!(claude_connector::user_uid("no-such-account-4c1f9a"), None);
assert_eq!(claude_connector::user_uid("bad\0name"), None);
}
#[test]
fn a_token_up_to_one_atomic_pipe_write_is_lent_and_a_longer_one_is_not() {
let exact: &'static str = Box::leak("a".repeat(4096).into_boxed_str());
let harness = start(Setup {
token: Some(exact),
..setup()
});
let mut answer = ask(&harness, 60_000);
assert!(granted_ok(&answer));
let mut read = Vec::new();
File::from(answer.fds.remove(0))
.read_to_end(&mut read)
.unwrap();
assert_eq!(read.len(), 4096);
let long: &'static str = Box::leak("a".repeat(4097).into_boxed_str());
let harness = start(Setup {
token: Some(long),
..setup()
});
let refused = ask(&harness, 60_000);
assert!(refused.message.is_none() && refused.fds.is_empty());
}
#[test]
fn a_request_trickled_past_the_socket_timeout_is_dropped_without_a_lease() {
let harness = start(setup());
let mut stream = UnixStream::connect(&harness.socket).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(8)))
.unwrap();
stream.write_all(&[0, 0]).unwrap();
let started = Instant::now();
let mut byte = [0_u8; 1];
let outcome = stream.read(&mut byte);
// The listener gave up at its own two-second bound and closed the
// connection: end of file or a reset, never our own read timing out.
assert!(
matches!(outcome, Ok(0))
|| outcome
.as_ref()
.is_err_and(|e| e.kind() == std::io::ErrorKind::ConnectionReset),
"{outcome:?}"
);
assert!(started.elapsed() < Duration::from_secs(6));
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
}
/// What a usage readout request came back with.
fn read_usage(harness: &Harness) -> Answer {
let mut stream = UnixStream::connect(&harness.socket).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
stream
.write_all(&encode_frame(&LeaseMessage::ClaudeUsageReadoutRequest(
LeaseUsageReadoutRequest {},
)))
.unwrap();
let (raw, fds) = receive(&stream);
let message = decode_frame(&raw);
Answer {
_stream: stream,
raw,
message,
fds,
}
}
fn usage_of(answer: &Answer) -> UsageReadout {
match &answer.message {
Some(LeaseMessage::ClaudeUsageReadout(readout)) => readout.clone(),
other => panic!("expected a usage readout, got {other:?}"),
}
}
#[test]
fn a_readout_returns_live_communal_spend_rows_across_callers() {
let price = PriceRow {
base: TokenRates {
input: 3_000_000,
cache_read: 300_000,
cache_write: 3_750_000,
output: 15_000_000,
},
bands: Vec::new(),
};
let routes = ProviderRoutes::with_prices([
(MODEL.to_string(), "claude-code".to_string(), Some(price)),
(
"unpriced-model".to_string(),
"claude-code".to_string(),
None,
),
])
.unwrap();
let admissions = vec![
CallerAdmission::new(
CALLER,
"lease-test-connection-key",
1,
[MODEL.to_string()],
1,
65_536,
32_768,
)
.unwrap(),
CallerAdmission::new(
"peer-caller",
"peer-test-connection-key",
1,
["unpriced-model".to_string()],
1,
65_536,
32_768,
)
.unwrap(),
];
let harness = start_with(setup(), routes, admissions);
let commit_call = |caller: &str, secret: &str, req_id: &str, model: &str| {
let now = now_ms();
let req = ProviderRequest::new(req_id, "conv-communal", model, "Be brief.", 100);
let hash = provider_request_sha256(&req).unwrap();
let inv = TransportInvocation::new(caller, now + 60_000, hash, req).unwrap();
let key = TransportKey::from_connection_secret(secret).unwrap();
let env = encrypt_invocation(&inv, &key).unwrap();
let mut service = harness._service.lock().unwrap();
let TransportAdmission::Execute(claim) = service.begin(&env, now, None, 65_536).unwrap()
else {
panic!("expected execute claim for {req_id}");
};
let result = claim.call().transported(
Vec::new(),
TransportOutcome::Completed {
provider_response_id: Some("resp-communal".to_string()),
stop_reason: StopReason::EndTurn,
usage: Usage {
input_tokens: 1_000_000,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 200_000,
reasoning_tokens: None,
},
},
);
service.complete(*claim, result, 65_536).unwrap();
};
commit_call(CALLER, "lease-test-connection-key", "req-communal-1", MODEL);
commit_call(
"peer-caller",
"peer-test-connection-key",
"req-communal-2",
"unpriced-model",
);
let reset = now_ms() + 3_600_000;
harness
.quota
.observe([window("five_hour", 310, "allowed", reset)]);
let answer = read_usage(&harness);
assert!(answer.fds.is_empty());
let readout = usage_of(&answer);
assert_eq!(readout.plan_quota, harness.quota.snapshot().windows);
assert_eq!(readout.spend.len(), 2);
let eureka_row = readout
.spend
.iter()
.find(|row| row.caller == CALLER)
.expect("eureka row");
assert_eq!(eureka_row.model, MODEL);
assert_eq!(eureka_row.calls, 1);
// 1M * 3_000_000 / 1M + 200k * 15_000_000 / 1M = 3_000_000 + 3_000_000 = 6_000_000
assert_eq!(eureka_row.cost_micro_usd, 6_000_000);
assert_eq!(eureka_row.calls_without_price, 0);
let peer_row = readout
.spend
.iter()
.find(|row| row.caller == "peer-caller")
.expect("peer row");
assert_eq!(peer_row.model, "unpriced-model");
assert_eq!(peer_row.calls, 1);
assert_eq!(peer_row.cost_micro_usd, 0);
assert_eq!(peer_row.calls_without_price, 1);
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
}
#[test]
fn a_readout_answers_the_cells_windows_and_lends_nothing() {
let harness = start(setup());
let reset = now_ms() + 3_600_000;
harness.quota.observe([
window("five_hour", 420, "allowed", reset),
window("seven_day", 999, "allowed_warning", reset + 86_400_000),
]);
let before = now_ms();
let answer = read_usage(&harness);
let readout = usage_of(&answer);
assert!(answer.fds.is_empty(), "a readout lends no descriptor");
assert_eq!(readout.plan_quota, harness.quota.snapshot().windows);
assert_eq!(readout.plan_quota.len(), 2);
assert!(readout.at_unix_ms >= before && readout.at_unix_ms <= now_ms());
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
// No lease was opened: the next request is granted.
assert!(granted_ok(&ask(&harness, 60_000)));
}
#[test]
fn a_peer_outside_the_lease_holders_still_reads_usage() {
let harness = start(Setup {
uid: own_uid().wrapping_add(1),
..setup()
});
harness
.quota
.observe([window("five_hour", 420, "allowed", now_ms() + 3_600_000)]);
let refused = ask(&harness, 60_000);
assert_eq!(refusal_of(&refused), Some(LeaseRefusalKind::UnknownCaller));
let readout = usage_of(&read_usage(&harness));
assert_eq!(readout.plan_quota.len(), 1);
assert_eq!(readout.plan_quota[0].utilization_permille, Some(420));
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
}
#[test]
fn a_readout_beside_a_held_lease_leaves_it_held() {
let harness = start(setup());
let held = ask(&harness, 60_000);
assert!(granted_ok(&held));
assert_eq!(usage_of(&read_usage(&harness)).plan_quota.len(), 0);
harness.enter(2);
let second = ask(&harness, 60_000);
assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy));
assert!(granted_ok(&held));
}
#[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))
);
}

View 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:?}");
}
}

View file

@ -0,0 +1,142 @@
//! Pins the bytes of the lease protocol v2: every frame a lease client sends
//! or receives. The fixtures in `fixtures/lease_v2` are the contract's bytes
//! for other implementations (Huginn's lease client vendors them and tests
//! against the same bytes); the types in `claude_connector::lease` own the
//! shape. Regenerate with `LEASE_V2_REGENERATE=1`, then review the diff.
#![cfg(target_os = "linux")]
use std::path::{Path, PathBuf};
use claude_connector::{
LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest,
LeaseUsageReadoutRequest, decode_frame, encode_frame,
};
use model_connector::{CallerModelSpend, PlanQuota, PlanQuotaSnapshot, UsageReadout};
const REGENERATE: &str = "LEASE_V2_REGENERATE";
fn fixtures() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lease_v2")
}
fn assert_frame(name: &str, message: &LeaseMessage) {
let path = fixtures().join(name);
let bytes = encode_frame(message);
if std::env::var_os(REGENERATE).is_some() {
std::fs::create_dir_all(fixtures()).unwrap();
std::fs::write(&path, &bytes).unwrap();
}
let committed = std::fs::read(&path).unwrap_or_else(|_| panic!("{name} is missing"));
assert_eq!(committed, bytes, "{name} is not what the types encode");
assert_eq!(decode_frame(&committed).as_ref(), Some(message), "{name}");
}
#[test]
fn the_request_frame_is_pinned() {
assert_frame(
"request.bin",
&LeaseMessage::ClaudeLeaseRequest(LeaseRequest {
expires_at_unix_ms: 1_793_307_000_000,
}),
);
}
#[test]
fn every_refusal_frame_is_pinned_with_its_kind_as_a_pascal_case_string() {
let kinds = [
(
"refusal_unknown_caller.bin",
LeaseRefusalKind::UnknownCaller,
"UnknownCaller",
),
("refusal_expired.bin", LeaseRefusalKind::Expired, "Expired"),
("refusal_busy.bin", LeaseRefusalKind::Busy, "Busy"),
(
"refusal_provider_rejected.bin",
LeaseRefusalKind::ProviderRejected,
"ProviderRejected",
),
];
for (name, kind, spelled) in kinds {
let message = LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
kind,
detail: "the reason".to_string(),
});
assert_frame(name, &message);
// The kind travels as the variant's name, which other runtimes read.
let bytes = encode_frame(&message);
let value: rmpv::Value = rmp_serde::from_slice(&bytes[4..]).unwrap();
let rmpv::Value::Map(outer) = value else {
panic!("a frame is a map")
};
let rmpv::Value::Map(inner) = &outer[1].1 else {
panic!("the value is a map")
};
assert_eq!(inner[0].0.as_str(), Some("kind"));
assert_eq!(inner[0].1.as_str(), Some(spelled));
}
}
#[test]
fn a_grant_with_both_usage_windows_is_pinned() {
let window = |name: &str, permille, status: &str, resets| PlanQuota {
window: name.to_string(),
utilization_permille: Some(permille),
resets_at_unix_ms: resets,
status: status.to_string(),
observed_at_unix_ms: 1_793_300_000_000,
};
assert_frame(
"grant.bin",
&LeaseMessage::ClaudeLeaseGrant(LeaseGranted {
lease_id: "lease:0123456789abcdef0123456789abcdef".to_string(),
plan_quota: vec![
window("five_hour", 420, "allowed", 1_793_307_000_000),
window("seven_day", 999, "allowed_warning", 1_793_800_000_000),
],
}),
);
}
#[test]
fn the_usage_readout_frames_are_pinned() {
let window = |name: &str, permille, status: &str, resets| PlanQuota {
window: name.to_string(),
utilization_permille: Some(permille),
resets_at_unix_ms: resets,
status: status.to_string(),
observed_at_unix_ms: 1_793_300_000_000,
};
let request = LeaseMessage::ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest {});
let answer = LeaseMessage::ClaudeUsageReadout(UsageReadout::new(
1_793_300_100_000,
vec![CallerModelSpend {
caller: "mind-self".to_string(),
model: "deepseek/deepseek-flash".to_string(),
month: "2026-12".to_string(),
calls: 42,
cost_micro_usd: 12_345,
calls_without_price: 0,
}],
PlanQuotaSnapshot {
windows: vec![
window("five_hour", 420, "allowed", 1_793_307_000_000),
window("seven_day", 999, "allowed_warning", 1_793_800_000_000),
],
},
));
assert_frame("usage_readout_request.bin", &request);
assert_frame("usage_readout.bin", &answer);
for (message, spelled) in [
(&request, "claude_usage_readout_request"),
(&answer, "claude_usage_readout"),
] {
let bytes = encode_frame(message);
let value: rmpv::Value = rmp_serde::from_slice(&bytes[4..]).unwrap();
let rmpv::Value::Map(outer) = value else {
panic!("a frame is a map")
};
assert_eq!(outer[0].0.as_str(), Some("kind"));
assert_eq!(outer[0].1.as_str(), Some(spelled));
}
}

View file

@ -26,3 +26,6 @@ serde_json = "1"
sha2 = "0.10" sha2 = "0.10"
thiserror = "2" thiserror = "2"
zeroize = "1" zeroize = "1"
[dev-dependencies]
anyhow = "1"

View file

@ -4,11 +4,16 @@ use std::time::Duration;
use thiserror::Error; use thiserror::Error;
use zeroize::Zeroizing; use zeroize::Zeroizing;
use rand_core::{OsRng, RngCore};
use crate::contract::{TransportInvocation, TransportKey, TransportResult}; use crate::contract::{TransportInvocation, TransportKey, TransportResult};
use crate::envelope::{ use crate::envelope::{
MAX_IDENTITY_BYTES, ServiceError, TransportFrameError, decode_result_frame, decrypt_result, MAX_IDENTITY_BYTES, ServiceError, TransportFrameError, decode_result_frame,
encode_invocation_frame, encrypt_invocation, read_transport_frame, write_transport_frame, decode_usage_readout_response_frame, decrypt_result, decrypt_usage_readout,
encode_invocation_frame, encode_usage_readout_request_frame, encrypt_invocation,
encrypt_usage_readout_request, read_transport_frame, write_transport_frame,
}; };
use crate::readout::UsageReadout;
#[derive(Clone)] #[derive(Clone)]
pub struct ConnectorClient { pub struct ConnectorClient {
@ -52,6 +57,36 @@ impl ConnectorClient {
return Err(ConnectorClientError::RequestIdTooLong); return Err(ConnectorClientError::RequestIdTooLong);
} }
let request = encode_invocation_frame(&encrypt_invocation(invocation, &self.security)?)?; let request = encode_invocation_frame(&encrypt_invocation(invocation, &self.security)?)?;
let response = self.exchange(&request)?;
let envelope = decode_result_frame(&response)?;
decrypt_result(&envelope, &self.security, invocation).map_err(Into::into)
}
/// Reads the connector's usage readout (`UsageReadout` v2: monthly
/// caller/model spend rows and the subscription plan's usage windows) as
/// `caller_runtime_id`, which must be a caller whose connection key this
/// client holds.
pub fn usage_readout(
&self,
caller_runtime_id: &str,
) -> Result<UsageReadout, ConnectorClientError> {
let mut nonce = [0_u8; 16];
OsRng.fill_bytes(&mut nonce);
let request_id = format!(
"usage-readout-{}",
nonce.iter().map(|b| format!("{b:02x}")).collect::<String>()
);
let sealed = encrypt_usage_readout_request(caller_runtime_id, &request_id, &self.security)?;
let response = self.exchange(&encode_usage_readout_request_frame(&sealed)?)?;
let envelope = decode_usage_readout_response_frame(&response)?;
if envelope.caller_runtime_id != caller_runtime_id || envelope.request_id != request_id {
return Err(ServiceError::OuterIdentity.into());
}
decrypt_usage_readout(&envelope, &self.security).map_err(Into::into)
}
/// Sends one frame on a fresh connection and reads the one answer.
fn exchange(&self, request: &[u8]) -> Result<Vec<u8>, ConnectorClientError> {
let connect_timeout = self let connect_timeout = self
.response_timeout .response_timeout
.unwrap_or(Duration::from_secs(10)) .unwrap_or(Duration::from_secs(10))
@ -62,12 +97,9 @@ impl ConnectorClient {
.set_read_timeout(self.response_timeout) .set_read_timeout(self.response_timeout)
.and_then(|()| stream.set_write_timeout(self.response_timeout)) .and_then(|()| stream.set_write_timeout(self.response_timeout))
.map_err(ConnectorClientError::Connection)?; .map_err(ConnectorClientError::Connection)?;
write_transport_frame(&mut stream, &request, self.max_frame_bytes) write_transport_frame(&mut stream, request, self.max_frame_bytes)
.map_err(client_frame_error)?; .map_err(client_frame_error)?;
let response = read_transport_frame(&mut stream, self.max_frame_bytes).map_err(client_frame_error)
read_transport_frame(&mut stream, self.max_frame_bytes).map_err(client_frame_error)?;
let envelope = decode_result_frame(&response)?;
decrypt_result(&envelope, &self.security, invocation).map_err(Into::into)
} }
} }
@ -226,4 +258,56 @@ mod fixture_tests {
"the client must not even connect" "the client must not even connect"
); );
} }
#[cfg(feature = "daemon")]
#[test]
fn a_readout_is_accepted_only_for_the_identity_that_asked() {
use crate::readout::PlanQuotaSnapshot;
// (caller the answer is sealed for, request id override, accepted)
let cases = [
("caller-1", None, true),
("caller-2", None, false),
("caller-1", Some("some-other-request"), false),
];
for (answer_caller, answer_request, accepted) in cases {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let endpoint = listener.local_addr().unwrap();
let key = security("readout-client-key");
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let request = read_transport_frame(&mut stream, 64 * 1024).unwrap();
let RequestFrame::UsageReadout(asked) = decode_request_frame(&request).unwrap()
else {
panic!("the client sent something other than a readout request");
};
let request_id = answer_request.unwrap_or(&asked.request_id);
let readout = UsageReadout::new(1, Vec::new(), PlanQuotaSnapshot::default());
let sealed =
encrypt_usage_readout(answer_caller, request_id, &readout, &key).unwrap();
write_transport_frame(
&mut stream,
&encode_usage_readout_response_frame(&sealed).unwrap(),
64 * 1024,
)
.unwrap();
});
let client = ConnectorClient::new(
endpoint,
"readout-client-key",
64 * 1024,
Some(Duration::from_secs(1)),
)
.unwrap();
let answer = client.usage_readout("caller-1");
if accepted {
assert_eq!(answer.unwrap().at_unix_ms, 1);
} else {
assert!(matches!(
answer,
Err(ConnectorClientError::Transport(ServiceError::OuterIdentity))
));
}
server.join().unwrap();
}
}
} }

View file

@ -9,11 +9,11 @@ use zeroize::Zeroize;
use crate::envelope::{ServiceError, binary_schema}; use crate::envelope::{ServiceError, binary_schema};
pub const PROVIDER_REQUEST_SCHEMA_ID: &str = "gamecult.model.provider_request.v3"; pub const PROVIDER_REQUEST_SCHEMA_ID: &str = "gamecult.model.provider_request.v5";
pub const INVOCATION_SCHEMA_ID: &str = "gamecult.model.transport_invocation.v3"; pub const INVOCATION_SCHEMA_ID: &str = "gamecult.model.transport_invocation.v5";
pub const RESULT_SCHEMA_ID: &str = "gamecult.model.transport_result.v3"; pub const RESULT_SCHEMA_ID: &str = "gamecult.model.transport_result.v5";
pub const RECEIPT_SCHEMA_ID: &str = "gamecult.model.transport_receipt.v3"; pub const RECEIPT_SCHEMA_ID: &str = "gamecult.model.transport_receipt.v5";
pub const ENVELOPE_SCHEMA_ID: &str = "gamecult.model.transport_envelope.v3"; pub const ENVELOPE_SCHEMA_ID: &str = "gamecult.model.transport_envelope.v5";
#[derive(Clone, PartialEq, Eq)] #[derive(Clone, PartialEq, Eq)]
pub struct TransportKey(pub(crate) [u8; 32]); pub struct TransportKey(pub(crate) [u8; 32]);
@ -190,9 +190,10 @@ pub enum FailureKind {
Provider, Provider,
} }
/// Token accounting for one completed request. Cache reads and writes are /// Token accounting for one request, as the backend reports it. Cache reads
/// counted apart from plain input; `reasoning_tokens` is absent when the /// and writes are counted apart from plain input.
/// provider does not report it. /// `output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail
/// (absent when the provider does not report it) and is never counted apart.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct Usage { pub struct Usage {
@ -475,6 +476,7 @@ pub struct TransportReceipt {
/// How many foreign `ReasoningState` items the service removed from the /// How many foreign `ReasoningState` items the service removed from the
/// request before the backend saw it. /// request before the backend saw it.
pub foreign_reasoning_dropped: u32, pub foreign_reasoning_dropped: u32,
pub cost_micro_usd: Option<u64>,
pub outcome: TransportOutcome, pub outcome: TransportOutcome,
} }
@ -496,6 +498,9 @@ impl TransportReceipt {
return Err(ContractError::NativeDigest); return Err(ContractError::NativeDigest);
} }
require_id(&self.provider, "receipt.provider")?; require_id(&self.provider, "receipt.provider")?;
if self.outcome.usage().is_none() && self.cost_micro_usd.is_some() {
return Err(ContractError::Invalid("receipt.cost_micro_usd"));
}
match &self.outcome { match &self.outcome {
TransportOutcome::Completed { TransportOutcome::Completed {
provider_response_id: Some(value), provider_response_id: Some(value),
@ -524,9 +529,22 @@ pub enum TransportOutcome {
Failed { Failed {
kind: FailureKind, kind: FailureKind,
message: String, message: String,
/// What the provider billed for the failed request: `Some` when it
/// reported usage (`Some` of zeros when it billed nothing), `None`
/// when unknown.
usage: Option<Usage>,
}, },
} }
impl TransportOutcome {
pub(crate) fn usage(&self) -> Option<&Usage> {
match self {
TransportOutcome::Completed { usage, .. } => Some(usage),
TransportOutcome::Failed { usage, .. } => usage.as_ref(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum Refusal { pub enum Refusal {
Expired, Expired,
@ -544,9 +562,12 @@ pub enum Refusal {
// exchange, where dropping it would break the provider's own rules. A plain // exchange, where dropping it would break the provider's own rules. A plain
// comment: a doc comment would split the published schema into a union. // comment: a doc comment would split the published schema into a union.
ForeignReasoningState, ForeignReasoningState,
// The provider itself is refusing right now: a plan window it reported
// `rejected` has not reached its own reset. Plain comments, as above.
ProviderRejected,
} }
/// The one wire codec of every v3 document: named MessagePack (struct fields /// The one wire codec of every v5 document: named MessagePack (struct fields
/// are keyed by name), with unknown fields refused by the types themselves. /// are keyed by name), with unknown fields refused by the types themselves.
pub(crate) fn wire_encode<T: Serialize + ?Sized>(document: &T) -> Result<Vec<u8>, ContractError> { pub(crate) fn wire_encode<T: Serialize + ?Sized>(document: &T) -> Result<Vec<u8>, ContractError> {
rmp_serde::to_vec_named(document).map_err(|_| ContractError::Encoding) rmp_serde::to_vec_named(document).map_err(|_| ContractError::Encoding)
@ -751,6 +772,26 @@ mod tests {
); );
} }
#[test]
fn the_invocations_identity_covers_its_request() {
let one = invocation();
let mut request = one.request.clone();
request.max_output_tokens += 1;
let other = TransportInvocation::new(
one.caller_runtime_id.clone(),
one.expires_at_unix_ms,
one.native_request_sha256,
request,
)
.unwrap();
assert_ne!(
canonical_invocation_bytes(&one).unwrap(),
canonical_invocation_bytes(&other).unwrap()
);
let decoded: TransportInvocation = wire_decode(&wire_encode(&one).unwrap()).unwrap();
assert_eq!(decoded, one);
}
#[test] #[test]
fn typed_tool_round_survives_messagepack() { fn typed_tool_round_survives_messagepack() {
let invocation = invocation(); let invocation = invocation();
@ -809,7 +850,7 @@ mod tests {
} }
#[test] #[test]
fn v3_documents_carry_their_v3_ids() { fn v5_documents_carry_their_v5_ids() {
assert_eq!( assert_eq!(
[ [
PROVIDER_REQUEST_SCHEMA_ID, PROVIDER_REQUEST_SCHEMA_ID,
@ -819,11 +860,11 @@ mod tests {
ENVELOPE_SCHEMA_ID ENVELOPE_SCHEMA_ID
], ],
[ [
"gamecult.model.provider_request.v3", "gamecult.model.provider_request.v5",
"gamecult.model.transport_invocation.v3", "gamecult.model.transport_invocation.v5",
"gamecult.model.transport_result.v3", "gamecult.model.transport_result.v5",
"gamecult.model.transport_receipt.v3", "gamecult.model.transport_receipt.v5",
"gamecult.model.transport_envelope.v3" "gamecult.model.transport_envelope.v5"
] ]
); );
let invocation = invocation(); let invocation = invocation();
@ -837,24 +878,27 @@ mod tests {
assert_eq!(sent.schema_id, RECEIPT_SCHEMA_ID); assert_eq!(sent.schema_id, RECEIPT_SCHEMA_ID);
let v2 = |name: &str| format!("{}{name}.v2", concat!("gamecult.", "codex.")); let v2 = |name: &str| format!("{}{name}.v2", concat!("gamecult.", "codex."));
let mut request = invocation.request.clone(); let v4 = |name: &str| format!("gamecult.model.{name}.v4");
request.schema_id = v2("provider_request"); for old_id in [v2, v4] {
assert_eq!(request.validate(), Err(ContractError::Schema)); let mut request = invocation.request.clone();
let mut stale = invocation.clone(); request.schema_id = old_id("provider_request");
stale.schema_id = v2("transport_invocation"); assert_eq!(request.validate(), Err(ContractError::Schema));
assert_eq!(stale.validate(1_000, 2_000), Err(ContractError::Schema)); let mut stale = invocation.clone();
let mut stale = result.clone(); stale.schema_id = old_id("transport_invocation");
stale.schema_id = v2("transport_result"); assert_eq!(stale.validate(1_000, 2_000), Err(ContractError::Schema));
assert_eq!( let mut stale = result.clone();
stale.validate_against(&invocation), stale.schema_id = old_id("transport_result");
Err(ContractError::Schema) assert_eq!(
); stale.validate_against(&invocation),
let mut stale = (**sent).clone(); Err(ContractError::Schema)
stale.schema_id = v2("transport_receipt"); );
assert_eq!( let mut stale = (**sent).clone();
stale.validate_against(&invocation), stale.schema_id = old_id("transport_receipt");
Err(ContractError::Schema) assert_eq!(
); stale.validate_against(&invocation),
Err(ContractError::Schema)
);
}
} }
/// `document` re-encoded as a named map with one more key at its top level. /// `document` re-encoded as a named map with one more key at its top level.
@ -862,7 +906,7 @@ mod tests {
let bytes = wire_encode(document).unwrap(); let bytes = wire_encode(document).unwrap();
let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap(); let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap();
let rmpv::Value::Map(entries) = &mut value else { let rmpv::Value::Map(entries) = &mut value else {
panic!("a v3 document is a named map"); panic!("a v5 document is a named map");
}; };
entries.push((rmpv::Value::from("unexpected_field"), rmpv::Value::from(1))); entries.push((rmpv::Value::from("unexpected_field"), rmpv::Value::from(1)));
let mut out = Vec::new(); let mut out = Vec::new();
@ -946,6 +990,7 @@ mod tests {
sent.outcome = TransportOutcome::Failed { sent.outcome = TransportOutcome::Failed {
kind, kind,
message: "failed".to_string(), message: "failed".to_string(),
usage: None,
}; };
assert_eq!(sent.validate_against(&invocation), Ok(())); assert_eq!(sent.validate_against(&invocation), Ok(()));
let decoded: TransportReceipt = wire_decode(&wire_encode(&sent).unwrap()).unwrap(); let decoded: TransportReceipt = wire_decode(&wire_encode(&sent).unwrap()).unwrap();
@ -955,6 +1000,7 @@ mod tests {
blank.outcome = TransportOutcome::Failed { blank.outcome = TransportOutcome::Failed {
kind: FailureKind::Provider, kind: FailureKind::Provider,
message: String::new(), message: String::new(),
usage: None,
}; };
assert_eq!( assert_eq!(
blank.validate_against(&invocation), blank.validate_against(&invocation),
@ -993,6 +1039,80 @@ mod tests {
} }
} }
#[test]
fn validate_against_refuses_each_binding_field_of_the_receipt() {
let invocation = invocation();
let good = receipt(&invocation);
assert_eq!(good.validate_against(&invocation), Ok(()));
let mut schema = good.clone();
schema.schema_id = "other".to_string();
assert_eq!(
schema.validate_against(&invocation),
Err(ContractError::Schema)
);
let mut provider_digest = good.clone();
provider_digest.provider_request_sha256 = [9; 32];
assert_eq!(
provider_digest.validate_against(&invocation),
Err(ContractError::ProviderDigest)
);
let mut native_digest = good.clone();
native_digest.native_request_sha256 = [9; 32];
assert_eq!(
native_digest.validate_against(&invocation),
Err(ContractError::NativeDigest)
);
let mut blank_provider = good.clone();
blank_provider.provider = " ".to_string();
assert_eq!(
blank_provider.validate_against(&invocation),
Err(ContractError::Invalid("receipt.provider"))
);
let mut blank_response = good.clone();
blank_response.outcome = TransportOutcome::Completed {
provider_response_id: Some(String::new()),
stop_reason: StopReason::EndTurn,
usage: Usage {
input_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 0,
reasoning_tokens: None,
},
};
assert_eq!(
blank_response.validate_against(&invocation),
Err(ContractError::Invalid("receipt.provider_response_id"))
);
let mut cost_without_usage = good.clone();
cost_without_usage.outcome = TransportOutcome::Failed {
kind: FailureKind::Provider,
message: "failed".to_string(),
usage: None,
};
cost_without_usage.cost_micro_usd = Some(0);
assert_eq!(
cost_without_usage.validate_against(&invocation),
Err(ContractError::Invalid("receipt.cost_micro_usd"))
);
cost_without_usage.cost_micro_usd = None;
assert_eq!(cost_without_usage.validate_against(&invocation), Ok(()));
cost_without_usage.outcome = TransportOutcome::Failed {
kind: FailureKind::RateLimited,
message: "limited".to_string(),
usage: Some(Usage {
input_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 0,
reasoning_tokens: None,
}),
};
cost_without_usage.cost_micro_usd = Some(0);
assert_eq!(cost_without_usage.validate_against(&invocation), Ok(()));
}
fn reasoning(state: &[u8]) -> TransportEventPayload { fn reasoning(state: &[u8]) -> TransportEventPayload {
TransportEventPayload::ReasoningState { TransportEventPayload::ReasoningState {
state: state.to_vec(), state: state.to_vec(),
@ -1067,6 +1187,7 @@ mod tests {
failed.outcome = TransportOutcome::Failed { failed.outcome = TransportOutcome::Failed {
kind: FailureKind::RateLimited, kind: FailureKind::RateLimited,
message: "slow down".to_string(), message: "slow down".to_string(),
usage: None,
}; };
let partial = TransportResult::transported( let partial = TransportResult::transported(
vec![event(0, text("half")), event(1, reasoning(&[1, 2, 3]))], vec![event(0, text("half")), event(1, reasoning(&[1, 2, 3]))],

View file

@ -17,11 +17,14 @@ use crate::contract::{
ContractError, ENVELOPE_SCHEMA_ID, TransportInvocation, TransportKey, TransportResult, ContractError, ENVELOPE_SCHEMA_ID, TransportInvocation, TransportKey, TransportResult,
canonical_invocation_bytes, require_id, wire_decode, wire_encode, canonical_invocation_bytes, require_id, wire_decode, wire_encode,
}; };
use crate::readout::UsageReadout;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum EnvelopeKind { pub enum EnvelopeKind {
Invocation, Invocation,
Result, Result,
UsageReadoutRequest,
UsageReadoutResult,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
@ -49,8 +52,10 @@ pub(crate) fn binary_schema(_: &mut schemars::SchemaGenerator) -> schemars::Sche
/// The CultNet service every frame of this connector addresses. /// The CultNet service every frame of this connector addresses.
pub const CONNECTOR_SERVICE_ID: &str = "gamecult.model.connector"; pub const CONNECTOR_SERVICE_ID: &str = "gamecult.model.connector";
/// The one operation of that service: run one sealed invocation. /// The operation that runs one sealed invocation.
pub const INVOKE_OPERATION: &str = "invoke"; pub const INVOKE_OPERATION: &str = "invoke";
/// The operation that reads the plan's usage.
pub const USAGE_READOUT_OPERATION: &str = "usage_readout";
const PAYLOAD_ENCODING: &str = "messagepack-base64"; const PAYLOAD_ENCODING: &str = "messagepack-base64";
const OK_STATUS: &str = "ok"; const OK_STATUS: &str = "ok";
@ -69,16 +74,39 @@ fn seal_payload(envelope: &TransportEnvelope) -> Result<String, ServiceError> {
Ok(STANDARD.encode(wire_encode(envelope)?)) Ok(STANDARD.encode(wire_encode(envelope)?))
} }
/// The CultNet frame an invocation travels in: a `cultnet.operation_request.v0` /// The two operations of the connector service.
/// for [`CONNECTOR_SERVICE_ID`] and [`INVOKE_OPERATION`], its `message_id` the #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Operation {
Invoke,
UsageReadout,
}
impl Operation {
fn name(self) -> &'static str {
match self {
Operation::Invoke => INVOKE_OPERATION,
Operation::UsageReadout => USAGE_READOUT_OPERATION,
}
}
pub(crate) fn from_name(name: &str) -> Option<Self> {
[Operation::Invoke, Operation::UsageReadout]
.into_iter()
.find(|operation| operation.name() == name)
}
}
/// The CultNet frame a request travels in: a `cultnet.operation_request.v0`
/// for [`CONNECTOR_SERVICE_ID`] and the named operation, its `message_id` the
/// request id and its payload the base64 of the named sealed envelope. /// request id and its payload the base64 of the named sealed envelope.
pub(crate) fn encode_invocation_frame( fn request_frame(
operation: Operation,
envelope: &TransportEnvelope, envelope: &TransportEnvelope,
) -> Result<Vec<u8>, ServiceError> { ) -> Result<Vec<u8>, ServiceError> {
carriage_bytes(&CultNetMessage::OperationRequest { carriage_bytes(&CultNetMessage::OperationRequest {
message_id: envelope.request_id.clone(), message_id: envelope.request_id.clone(),
service_id: CONNECTOR_SERVICE_ID.to_string(), service_id: CONNECTOR_SERVICE_ID.to_string(),
operation: INVOKE_OPERATION.to_string(), operation: operation.name().to_string(),
payload_schema: ENVELOPE_SCHEMA_ID.to_string(), payload_schema: ENVELOPE_SCHEMA_ID.to_string(),
payload_encoding: PAYLOAD_ENCODING.to_string(), payload_encoding: PAYLOAD_ENCODING.to_string(),
payload: seal_payload(envelope)?, payload: seal_payload(envelope)?,
@ -87,14 +115,17 @@ pub(crate) fn encode_invocation_frame(
}) })
} }
/// The CultNet frame a result travels in: a `cultnet.operation_response.v0` /// The CultNet frame a response travels in: a `cultnet.operation_response.v0`
/// with status `ok`, otherwise shaped like the invocation's. /// with status `ok`, otherwise shaped like the request's.
#[cfg(any(feature = "daemon", test))] #[cfg(any(feature = "daemon", test))]
pub(crate) fn encode_result_frame(envelope: &TransportEnvelope) -> Result<Vec<u8>, ServiceError> { fn response_frame(
operation: Operation,
envelope: &TransportEnvelope,
) -> Result<Vec<u8>, ServiceError> {
carriage_bytes(&CultNetMessage::OperationResponse { carriage_bytes(&CultNetMessage::OperationResponse {
message_id: envelope.request_id.clone(), message_id: envelope.request_id.clone(),
service_id: CONNECTOR_SERVICE_ID.to_string(), service_id: CONNECTOR_SERVICE_ID.to_string(),
operation: INVOKE_OPERATION.to_string(), operation: operation.name().to_string(),
status: OK_STATUS.to_string(), status: OK_STATUS.to_string(),
payload_schema: ENVELOPE_SCHEMA_ID.to_string(), payload_schema: ENVELOPE_SCHEMA_ID.to_string(),
payload_encoding: PAYLOAD_ENCODING.to_string(), payload_encoding: PAYLOAD_ENCODING.to_string(),
@ -104,20 +135,43 @@ pub(crate) fn encode_result_frame(envelope: &TransportEnvelope) -> Result<Vec<u8
}) })
} }
pub(crate) fn encode_invocation_frame(
envelope: &TransportEnvelope,
) -> Result<Vec<u8>, ServiceError> {
request_frame(Operation::Invoke, envelope)
}
pub(crate) fn encode_usage_readout_request_frame(
envelope: &TransportEnvelope,
) -> Result<Vec<u8>, ServiceError> {
request_frame(Operation::UsageReadout, envelope)
}
#[cfg(any(feature = "daemon", test))]
pub(crate) fn encode_result_frame(envelope: &TransportEnvelope) -> Result<Vec<u8>, ServiceError> {
response_frame(Operation::Invoke, envelope)
}
#[cfg(feature = "daemon")]
pub(crate) fn encode_usage_readout_response_frame(
envelope: &TransportEnvelope,
) -> Result<Vec<u8>, ServiceError> {
response_frame(Operation::UsageReadout, envelope)
}
/// Opens the carriage of one frame. Everything the carriage says is checked /// Opens the carriage of one frame. Everything the carriage says is checked
/// here, before any decryption: the service, the operation, the payload schema, /// here, before any decryption: the service, that the operation is one this
/// and that the message id is the sealed envelope's request id. /// service has, the payload schema, and that the message id is the sealed
/// envelope's request id.
fn open_carriage( fn open_carriage(
message_id: &str, message_id: &str,
service_id: &str, service_id: &str,
operation: &str, operation: &str,
payload_schema: &str, payload_schema: &str,
payload: &str, payload: &str,
) -> Result<TransportEnvelope, ServiceError> { ) -> Result<(Operation, TransportEnvelope), ServiceError> {
if service_id != CONNECTOR_SERVICE_ID let operation = Operation::from_name(operation).ok_or(ServiceError::Carriage)?;
|| operation != INVOKE_OPERATION if service_id != CONNECTOR_SERVICE_ID || payload_schema != ENVELOPE_SCHEMA_ID {
|| payload_schema != ENVELOPE_SCHEMA_ID
{
return Err(ServiceError::Carriage); return Err(ServiceError::Carriage);
} }
let bytes = STANDARD let bytes = STANDARD
@ -127,7 +181,7 @@ fn open_carriage(
if envelope.request_id != message_id { if envelope.request_id != message_id {
return Err(ServiceError::OuterIdentity); return Err(ServiceError::OuterIdentity);
} }
Ok(envelope) Ok((operation, envelope))
} }
fn read_carriage(bytes: &[u8]) -> Result<CultNetMessage, ServiceError> { fn read_carriage(bytes: &[u8]) -> Result<CultNetMessage, ServiceError> {
@ -135,8 +189,15 @@ fn read_carriage(bytes: &[u8]) -> Result<CultNetMessage, ServiceError> {
.map_err(|_| ServiceError::Carriage) .map_err(|_| ServiceError::Carriage)
} }
/// A request frame, by the operation it names.
#[cfg(any(feature = "daemon", test))] #[cfg(any(feature = "daemon", test))]
pub(crate) fn decode_invocation_frame(bytes: &[u8]) -> Result<TransportEnvelope, ServiceError> { pub(crate) enum RequestFrame {
Invoke(TransportEnvelope),
UsageReadout(TransportEnvelope),
}
#[cfg(any(feature = "daemon", test))]
pub(crate) fn decode_request_frame(bytes: &[u8]) -> Result<RequestFrame, ServiceError> {
match read_carriage(bytes)? { match read_carriage(bytes)? {
CultNetMessage::OperationRequest { CultNetMessage::OperationRequest {
message_id, message_id,
@ -145,18 +206,34 @@ pub(crate) fn decode_invocation_frame(bytes: &[u8]) -> Result<TransportEnvelope,
payload_schema, payload_schema,
payload, payload,
.. ..
} => open_carriage( } => {
&message_id, match open_carriage(
&service_id, &message_id,
&operation, &service_id,
&payload_schema, &operation,
&payload, &payload_schema,
), &payload,
)? {
(Operation::Invoke, envelope) => Ok(RequestFrame::Invoke(envelope)),
(Operation::UsageReadout, envelope) => Ok(RequestFrame::UsageReadout(envelope)),
}
}
_ => Err(ServiceError::Carriage), _ => Err(ServiceError::Carriage),
} }
} }
pub(crate) fn decode_result_frame(bytes: &[u8]) -> Result<TransportEnvelope, ServiceError> { #[cfg(test)]
pub(crate) fn decode_invocation_frame(bytes: &[u8]) -> Result<TransportEnvelope, ServiceError> {
match decode_request_frame(bytes)? {
RequestFrame::Invoke(envelope) => Ok(envelope),
RequestFrame::UsageReadout(_) => Err(ServiceError::Carriage),
}
}
fn decode_response_frame(
bytes: &[u8],
expected: Operation,
) -> Result<TransportEnvelope, ServiceError> {
match read_carriage(bytes)? { match read_carriage(bytes)? {
CultNetMessage::OperationResponse { CultNetMessage::OperationResponse {
message_id, message_id,
@ -166,17 +243,32 @@ pub(crate) fn decode_result_frame(bytes: &[u8]) -> Result<TransportEnvelope, Ser
payload_schema, payload_schema,
payload, payload,
.. ..
} if status == OK_STATUS => open_carriage( } if status == OK_STATUS => {
&message_id, match open_carriage(
&service_id, &message_id,
&operation, &service_id,
&payload_schema, &operation,
&payload, &payload_schema,
), &payload,
)? {
(found, envelope) if found == expected => Ok(envelope),
_ => Err(ServiceError::Carriage),
}
}
_ => Err(ServiceError::Carriage), _ => Err(ServiceError::Carriage),
} }
} }
pub(crate) fn decode_result_frame(bytes: &[u8]) -> Result<TransportEnvelope, ServiceError> {
decode_response_frame(bytes, Operation::Invoke)
}
pub(crate) fn decode_usage_readout_response_frame(
bytes: &[u8],
) -> Result<TransportEnvelope, ServiceError> {
decode_response_frame(bytes, Operation::UsageReadout)
}
/// The most bytes one frame holding a sealed envelope of `ciphertext_len` /// The most bytes one frame holding a sealed envelope of `ciphertext_len`
/// ciphertext bytes can occupy, with ids at their longest: the frame a caller /// ciphertext bytes can occupy, with ids at their longest: the frame a caller
/// payload bound (`CallerAdmission`'s `max_payload_bytes`, a bound on /// payload bound (`CallerAdmission`'s `max_payload_bytes`, a bound on
@ -324,6 +416,59 @@ pub fn decrypt_result(
Ok(result) Ok(result)
} }
/// A usage readout request carries no content: the sealed envelope's
/// authenticated identity and kind are the whole request.
pub(crate) fn encrypt_usage_readout_request(
caller_runtime_id: &str,
request_id: &str,
security: &TransportKey,
) -> Result<TransportEnvelope, ServiceError> {
encrypt_message(
caller_runtime_id,
request_id,
EnvelopeKind::UsageReadoutRequest,
&[],
security,
)
}
#[cfg(any(feature = "daemon", test))]
pub(crate) fn decrypt_usage_readout_request(
envelope: &TransportEnvelope,
security: &TransportKey,
) -> Result<(), ServiceError> {
validate_envelope(envelope, EnvelopeKind::UsageReadoutRequest)?;
decrypt_message(envelope, security).map(drop)
}
#[cfg(feature = "daemon")]
pub(crate) fn encrypt_usage_readout(
caller_runtime_id: &str,
request_id: &str,
readout: &UsageReadout,
security: &TransportKey,
) -> Result<TransportEnvelope, ServiceError> {
let plaintext = wire_encode(readout).map_err(|_| ServiceError::Encoding)?;
encrypt_message(
caller_runtime_id,
request_id,
EnvelopeKind::UsageReadoutResult,
&plaintext,
security,
)
}
pub(crate) fn decrypt_usage_readout(
envelope: &TransportEnvelope,
security: &TransportKey,
) -> Result<UsageReadout, ServiceError> {
validate_envelope(envelope, EnvelopeKind::UsageReadoutResult)?;
let plaintext = decrypt_message(envelope, security)?;
let readout: UsageReadout = wire_decode(&plaintext).map_err(|_| ServiceError::Encoding)?;
readout.validate()?;
Ok(readout)
}
#[derive(Debug)] #[derive(Debug)]
pub(crate) enum TransportFrameError { pub(crate) enum TransportFrameError {
Connection(std::io::Error), Connection(std::io::Error),
@ -925,7 +1070,7 @@ mod tests {
fn golden_frame() -> Vec<u8> { fn golden_frame() -> Vec<u8> {
std::fs::read( std::fs::read(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")) std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/wire_v3/carriage_invocation.frame"), .join("tests/fixtures/wire_v5/carriage_invocation.frame"),
) )
.expect("carriage_invocation.frame is committed") .expect("carriage_invocation.frame is committed")
} }
@ -962,7 +1107,7 @@ mod tests {
assert_eq!(text(&request, "operation"), "invoke"); assert_eq!(text(&request, "operation"), "invoke");
assert_eq!( assert_eq!(
text(&request, "payloadSchema"), text(&request, "payloadSchema"),
"gamecult.model.transport_envelope.v3" "gamecult.model.transport_envelope.v5"
); );
assert_eq!(text(&request, "payloadEncoding"), "messagepack-base64"); assert_eq!(text(&request, "payloadEncoding"), "messagepack-base64");
assert_eq!(text(&request, "messageId"), envelope.request_id); assert_eq!(text(&request, "messageId"), envelope.request_id);
@ -976,7 +1121,7 @@ mod tests {
assert_eq!(text(&response, "status"), "ok"); assert_eq!(text(&response, "status"), "ok");
assert_eq!( assert_eq!(
text(&response, "payloadSchema"), text(&response, "payloadSchema"),
"gamecult.model.transport_envelope.v3" "gamecult.model.transport_envelope.v5"
); );
assert_eq!(text(&response, "payloadEncoding"), "messagepack-base64"); assert_eq!(text(&response, "payloadEncoding"), "messagepack-base64");
assert_eq!(text(&response, "messageId"), envelope.request_id); assert_eq!(text(&response, "messageId"), envelope.request_id);
@ -1136,4 +1281,64 @@ mod tests {
); );
} }
} }
#[test]
fn a_readout_request_is_not_an_invocation_and_names_its_own_operation() {
let key = TransportKey::from_connection_secret("readout-test-key").unwrap();
let sealed = encrypt_usage_readout_request("caller-1", "readout-1", &key).unwrap();
let frame = encode_usage_readout_request_frame(&sealed).unwrap();
assert!(matches!(
decode_request_frame(&frame),
Ok(RequestFrame::UsageReadout(found)) if found == sealed
));
assert_eq!(decode_invocation_frame(&frame), Err(ServiceError::Carriage));
// Sealed as one kind, the authenticated data refuses it as another.
assert!(decrypt_usage_readout_request(&sealed, &key).is_ok());
assert_eq!(
decrypt_usage_readout(&sealed, &key).unwrap_err(),
ServiceError::Envelope
);
let mut relabelled = sealed.clone();
relabelled.message_kind = EnvelopeKind::UsageReadoutResult;
assert_eq!(
decrypt_usage_readout(&relabelled, &key).unwrap_err(),
ServiceError::Encryption
);
}
#[cfg(feature = "daemon")]
#[test]
fn a_response_is_read_as_its_own_operation_only() {
use crate::readout::{CallerModelSpend, PlanQuotaSnapshot};
let key = TransportKey::from_connection_secret("readout-test-key").unwrap();
let readout = UsageReadout::new(
1,
vec![CallerModelSpend {
caller: "caller-1".into(),
model: "gpt-5.4".into(),
month: "2026-12".into(),
calls: 2,
cost_micro_usd: 150,
calls_without_price: 0,
}],
PlanQuotaSnapshot::default(),
);
let sealed = encrypt_usage_readout("caller-1", "readout-1", &readout, &key).unwrap();
let readout_frame = encode_usage_readout_response_frame(&sealed).unwrap();
let invoke_frame = encode_result_frame(&sealed).unwrap();
assert_eq!(
decode_usage_readout_response_frame(&readout_frame).unwrap(),
sealed
);
assert_eq!(decode_result_frame(&invoke_frame).unwrap(), sealed);
assert_eq!(
decode_result_frame(&readout_frame),
Err(ServiceError::Carriage)
);
assert_eq!(
decode_usage_readout_response_frame(&invoke_frame),
Err(ServiceError::Carriage)
);
assert_eq!(decrypt_usage_readout(&sealed, &key).unwrap(), readout);
}
} }

View file

@ -4,8 +4,15 @@ use crate::contract::*;
#[cfg(feature = "daemon")] #[cfg(feature = "daemon")]
use crate::service::*; use crate::service::*;
#[cfg(feature = "daemon")]
use std::collections::BTreeMap;
#[cfg(feature = "daemon")] #[cfg(feature = "daemon")]
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
#[cfg(feature = "daemon")]
use std::sync::{Arc, Mutex};
#[cfg(feature = "daemon")]
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, PushAllOptions};
#[cfg(feature = "daemon")] #[cfg(feature = "daemon")]
static TEST_STORE_SEQUENCE: AtomicUsize = AtomicUsize::new(0); static TEST_STORE_SEQUENCE: AtomicUsize = AtomicUsize::new(0);
@ -37,6 +44,85 @@ impl Drop for TestStore {
} }
} }
/// An in-memory ledger that accepts a fixed number of writes and then refuses
/// every one, so a test can make the replay store fail where it chooses. A
/// store reopened from it sees what was written, like a restart.
#[cfg(feature = "daemon")]
#[derive(Clone)]
pub(crate) struct FlakyStore {
held: Arc<Mutex<BTreeMap<(String, String), CultCacheEnvelope>>>,
pushes_allowed: Arc<AtomicUsize>,
}
#[cfg(feature = "daemon")]
impl FlakyStore {
pub(crate) fn new(pushes_allowed: usize) -> Self {
Self {
held: Arc::default(),
pushes_allowed: Arc::new(AtomicUsize::new(pushes_allowed)),
}
}
/// The remaining writes this store accepts, shared with it after it has
/// been handed to a service.
pub(crate) fn allowance(&self) -> Arc<AtomicUsize> {
self.pushes_allowed.clone()
}
}
#[cfg(feature = "daemon")]
impl CacheBackingStore for FlakyStore {
fn pull_all(&self) -> anyhow::Result<Vec<CultCacheEnvelope>> {
Ok(self.held.lock().unwrap().values().cloned().collect())
}
fn push(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<()> {
if self
.pushes_allowed
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |allowed| {
allowed.checked_sub(1)
})
.is_err()
{
return Err(anyhow::anyhow!("ledger write refused"));
}
self.held
.lock()
.unwrap()
.insert((entry.r#type.clone(), entry.key.clone()), entry.clone());
Ok(())
}
fn delete(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<()> {
self.held
.lock()
.unwrap()
.remove(&(entry.r#type.clone(), entry.key.clone()));
Ok(())
}
fn push_all(
&mut self,
entries: &[CultCacheEnvelope],
_options: PushAllOptions,
) -> anyhow::Result<()> {
if self
.pushes_allowed
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |allowed| {
allowed.checked_sub(1)
})
.is_err()
{
return Err(anyhow::anyhow!("ledger write refused"));
}
let mut held = self.held.lock().unwrap();
for entry in entries {
held.insert((entry.r#type.clone(), entry.key.clone()), entry.clone());
}
Ok(())
}
}
pub(crate) fn request() -> ProviderRequest { pub(crate) fn request() -> ProviderRequest {
let mut request = ProviderRequest::new( let mut request = ProviderRequest::new(
"request-1", "request-1",
@ -70,6 +156,7 @@ pub(crate) fn receipt(invocation: &TransportInvocation) -> TransportReceipt {
model: invocation.request.model.clone(), model: invocation.request.model.clone(),
provider: "fixture-sse".to_string(), provider: "fixture-sse".to_string(),
foreign_reasoning_dropped: 0, foreign_reasoning_dropped: 0,
cost_micro_usd: None,
outcome: TransportOutcome::Completed { outcome: TransportOutcome::Completed {
provider_response_id: Some("response-1".to_string()), provider_response_id: Some("response-1".to_string()),
stop_reason: StopReason::EndTurn, stop_reason: StopReason::EndTurn,
@ -83,6 +170,7 @@ pub(crate) fn receipt(invocation: &TransportInvocation) -> TransportReceipt {
}, },
} }
} }
#[cfg(feature = "daemon")] #[cfg(feature = "daemon")]
pub(crate) fn caller( pub(crate) fn caller(
caller_runtime_id: &str, caller_runtime_id: &str,
@ -101,11 +189,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",

View file

@ -1,6 +1,8 @@
mod client; mod client;
mod contract; mod contract;
mod envelope; mod envelope;
mod price;
mod readout;
#[cfg(test)] #[cfg(test)]
mod fixtures; mod fixtures;
@ -13,6 +15,8 @@ mod service;
pub use client::*; pub use client::*;
pub use contract::*; pub use contract::*;
pub use envelope::*; pub use envelope::*;
pub use price::*;
pub use readout::*;
#[cfg(feature = "daemon")] #[cfg(feature = "daemon")]
pub use serve::*; pub use serve::*;

View file

@ -0,0 +1,461 @@
//! Per-model token pricing in micro-USD per million tokens, plus pure-integer
//! UTC calendar math for banded rates and monthly spend keys.
//!
//! Pricing exists solely for cost visibility on receipts and the communal usage
//! readout (`Q4`). Nothing in the connector compares a cost or monthly total
//! to refuse, delay, retry, or reorder a request.
use std::collections::HashSet;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::contract::{ContractError, Usage};
const MICRO_USD_SCALE: u128 = 1_000_000;
const SECS_PER_DAY: u64 = 86_400;
const SECS_PER_HOUR: u64 = 3_600;
/// Day of week in UTC.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
pub enum Weekday {
Mon,
Tue,
Wed,
Thu,
Fri,
Sat,
Sun,
}
/// Decomposed UTC calendar fields for a `unix_ms` timestamp.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UtcParts {
pub year: i64,
pub month: u8,
pub day: u8,
pub weekday: Weekday,
pub hour: u8,
}
/// Pure-integer UTC calendar decomposition from Unix milliseconds (proleptic
/// Gregorian calendar, no external date crate).
pub fn utc_parts(unix_ms: u64) -> UtcParts {
let total_secs = unix_ms / 1_000;
let total_days = total_secs / SECS_PER_DAY;
let sec_of_day = total_secs % SECS_PER_DAY;
let hour = (sec_of_day / SECS_PER_HOUR) as u8;
// 1970-01-01 was a Thursday (index 3 when Mon=0..Sun=6).
let weekday = match (total_days + 3) % 7 {
0 => Weekday::Mon,
1 => Weekday::Tue,
2 => Weekday::Wed,
3 => Weekday::Thu,
4 => Weekday::Fri,
5 => Weekday::Sat,
_ => Weekday::Sun,
};
// Howard Hinnant's `civil_from_days` algorithm.
let z = (total_days as i64) + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u8;
let month = (mp + if mp < 10 { 3 } else { -9 }) as u8;
let year = y + if month <= 2 { 1 } else { 0 };
UtcParts {
year,
month,
day,
weekday,
hour,
}
}
/// Formats the UTC calendar month of `unix_ms` as `YYYY-MM`.
pub fn utc_month_string(unix_ms: u64) -> String {
let parts = utc_parts(unix_ms);
format!("{:04}-{:02}", parts.year, parts.month)
}
/// Per-million-token rates in micro-USD (`1 USD = 1_000_000 micro-USD`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TokenRates {
pub input: u64,
pub cache_read: u64,
pub cache_write: u64,
pub output: u64,
}
impl TokenRates {
/// Computes `ceil(sum(tokens * rate) / 1_000_000)` in `u128`, clamping at
/// `u64::MAX`. `reasoning_tokens` is already included in `output_tokens`
/// and is never double-counted.
pub fn cost_micro_usd(&self, usage: &Usage) -> u64 {
let weighted = (u128::from(usage.input_tokens) * u128::from(self.input))
.saturating_add(u128::from(usage.cache_read_tokens) * u128::from(self.cache_read))
.saturating_add(u128::from(usage.cache_write_tokens) * u128::from(self.cache_write))
.saturating_add(u128::from(usage.output_tokens) * u128::from(self.output));
let micro_usd = weighted.div_ceil(MICRO_USD_SCALE);
u64::try_from(micro_usd).unwrap_or(u64::MAX)
}
}
/// Time-of-week UTC pricing band overriding [`PriceRow::base`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PriceBand {
pub weekdays: Vec<Weekday>,
pub utc_hours: Vec<u8>,
pub rates: TokenRates,
}
/// Per-model pricing table entry: base rates plus ordered UTC time bands
/// (first matching band wins, otherwise `base`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PriceRow {
pub base: TokenRates,
pub bands: Vec<PriceBand>,
}
impl PriceRow {
pub fn validate(&self) -> Result<(), ContractError> {
for band in &self.bands {
if band.weekdays.is_empty() {
return Err(ContractError::Invalid("price.band.weekdays"));
}
let mut seen_days = HashSet::with_capacity(band.weekdays.len());
for day in &band.weekdays {
if !seen_days.insert(*day) {
return Err(ContractError::Invalid("price.band.weekdays"));
}
}
if band.utc_hours.is_empty() {
return Err(ContractError::Invalid("price.band.utc_hours"));
}
let mut seen_hours = HashSet::with_capacity(band.utc_hours.len());
for &hour in &band.utc_hours {
if hour >= 24 || !seen_hours.insert(hour) {
return Err(ContractError::Invalid("price.band.utc_hours"));
}
}
}
Ok(())
}
pub fn rates_at(&self, unix_ms: u64) -> &TokenRates {
let parts = utc_parts(unix_ms);
self.bands
.iter()
.find(|band| {
band.weekdays.contains(&parts.weekday) && band.utc_hours.contains(&parts.hour)
})
.map_or(&self.base, |band| &band.rates)
}
pub fn cost_micro_usd(&self, usage: &Usage, unix_ms: u64) -> u64 {
self.rates_at(unix_ms).cost_micro_usd(usage)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn deepseek_price() -> PriceRow {
PriceRow {
base: TokenRates {
input: 270_000,
cache_read: 27_000,
cache_write: 0,
output: 1_100_000,
},
bands: vec![PriceBand {
weekdays: vec![
Weekday::Mon,
Weekday::Tue,
Weekday::Wed,
Weekday::Thu,
Weekday::Fri,
],
utc_hours: vec![1, 2, 3, 6, 7, 8, 9],
rates: TokenRates {
input: 540_000,
cache_read: 54_000,
cache_write: 0,
output: 2_200_000,
},
}],
}
}
#[test]
fn peak_and_off_peak_and_utc_calendar_math() {
assert_eq!(
utc_parts(0),
UtcParts {
year: 1970,
month: 1,
day: 1,
weekday: Weekday::Thu,
hour: 0,
}
);
assert_eq!(utc_month_string(0), "1970-01");
// All seven weekdays in order starting 1970-01-01 (Thu).
let expected_weekdays = [
Weekday::Thu,
Weekday::Fri,
Weekday::Sat,
Weekday::Sun,
Weekday::Mon,
Weekday::Tue,
Weekday::Wed,
];
for (offset, expected) in expected_weekdays.into_iter().enumerate() {
assert_eq!(
utc_parts((offset as u64) * 86_400 * 1_000).weekday,
expected
);
}
// 400-year leap boundary (2000-02-29, 2000-03-01) and 100-year non-leap boundary (2100-03-01).
assert_eq!(
utc_parts(11_016 * 86_400 * 1_000),
UtcParts {
year: 2000,
month: 2,
day: 29,
weekday: Weekday::Tue,
hour: 0,
}
);
assert_eq!(
utc_parts(11_017 * 86_400 * 1_000),
UtcParts {
year: 2000,
month: 3,
day: 1,
weekday: Weekday::Wed,
hour: 0,
}
);
assert_eq!(
utc_parts(47_541 * 86_400 * 1_000),
UtcParts {
year: 2100,
month: 3,
day: 1,
weekday: Weekday::Mon,
hour: 0,
}
);
// Non-zero cache_write rate and tokens.
let cache_write_rates = TokenRates {
input: 0,
cache_read: 0,
cache_write: 3_000,
output: 0,
};
assert_eq!(
cache_write_rates.cost_micro_usd(&Usage {
input_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 500,
output_tokens: 0,
reasoning_tokens: None,
}),
2
);
// 2024-02-29T23:59:59Z (leap day, Thursday)
let leap_day_ms = (19_782 * 86_400 + 23 * 3_600 + 59 * 60 + 59) * 1_000;
assert_eq!(
utc_parts(leap_day_ms),
UtcParts {
year: 2024,
month: 2,
day: 29,
weekday: Weekday::Thu,
hour: 23,
}
);
assert_eq!(utc_month_string(leap_day_ms), "2024-02");
// 2026-12-08T02:30:00Z (Tuesday 02:30 UTC -> peak band)
let tue_peak_ms = (20_795 * 86_400 + 2 * 3_600 + 30 * 60) * 1_000;
assert_eq!(
utc_parts(tue_peak_ms),
UtcParts {
year: 2026,
month: 12,
day: 8,
weekday: Weekday::Tue,
hour: 2,
}
);
assert_eq!(utc_month_string(tue_peak_ms), "2026-12");
// 2026-12-08T12:00:00Z (Tuesday 12:00 UTC -> off-peak base)
let tue_off_peak_ms = (20_795 * 86_400 + 12 * 3_600) * 1_000;
assert_eq!(
utc_parts(tue_off_peak_ms),
UtcParts {
year: 2026,
month: 12,
day: 8,
weekday: Weekday::Tue,
hour: 12,
}
);
// 2026-12-12T02:30:00Z (Saturday 02:30 UTC -> off-peak base despite peak hour)
let sat_ms = (20_799 * 86_400 + 2 * 3_600 + 30 * 60) * 1_000;
assert_eq!(utc_parts(sat_ms).weekday, Weekday::Sat);
let price = deepseek_price();
assert_eq!(price.validate(), Ok(()));
let usage = Usage {
input_tokens: 1_500,
cache_read_tokens: 4_000,
cache_write_tokens: 0,
output_tokens: 750,
reasoning_tokens: Some(300),
};
// Peak: (1500*540_000 + 4000*54_000 + 750*2_200_000) / 1_000_000
// = (810_000_000 + 216_000_000 + 1_650_000_000) / 1_000_000
// = 2_676_000_000 / 1_000_000 = 2_676 micro-USD.
assert_eq!(price.cost_micro_usd(&usage, tue_peak_ms), 2_676);
// Off-peak (half rates): 1_338 micro-USD.
assert_eq!(price.cost_micro_usd(&usage, tue_off_peak_ms), 1_338);
assert_eq!(price.cost_micro_usd(&usage, sat_ms), 1_338);
// reasoning_tokens is a detail inside output_tokens and never double-counted.
let without_detail = Usage {
reasoning_tokens: None,
..usage.clone()
};
assert_eq!(
price.cost_micro_usd(&without_detail, tue_peak_ms),
price.cost_micro_usd(&usage, tue_peak_ms)
);
}
#[test]
fn ceiling_rounding_saturation_and_band_validation() {
let unit = TokenRates {
input: 1,
cache_read: 0,
cache_write: 0,
output: 0,
};
let usage_for = |input_tokens| Usage {
input_tokens,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 0,
reasoning_tokens: None,
};
assert_eq!(unit.cost_micro_usd(&usage_for(0)), 0);
assert_eq!(unit.cost_micro_usd(&usage_for(1)), 1);
assert_eq!(unit.cost_micro_usd(&usage_for(1_000_000)), 1);
assert_eq!(unit.cost_micro_usd(&usage_for(1_000_001)), 2);
let huge_rates = TokenRates {
input: u64::MAX,
cache_read: u64::MAX,
cache_write: u64::MAX,
output: u64::MAX,
};
let huge_usage = Usage {
input_tokens: u64::MAX,
cache_read_tokens: u64::MAX,
cache_write_tokens: u64::MAX,
output_tokens: u64::MAX,
reasoning_tokens: Some(u64::MAX),
};
assert_eq!(huge_rates.cost_micro_usd(&huge_usage), u64::MAX);
// First matching band wins.
let base_rates = TokenRates {
input: 100,
cache_read: 0,
cache_write: 0,
output: 0,
};
let first_rates = TokenRates {
input: 200,
..base_rates.clone()
};
let second_rates = TokenRates {
input: 300,
..base_rates.clone()
};
let overlapping = PriceRow {
base: base_rates,
bands: vec![
PriceBand {
weekdays: vec![Weekday::Thu],
utc_hours: vec![0],
rates: first_rates.clone(),
},
PriceBand {
weekdays: vec![Weekday::Thu],
utc_hours: vec![0],
rates: second_rates,
},
],
};
assert_eq!(overlapping.validate(), Ok(()));
assert_eq!(overlapping.rates_at(0), &first_rates);
// Validation failures.
let mut bad = deepseek_price();
bad.bands[0].weekdays.clear();
assert_eq!(
bad.validate(),
Err(ContractError::Invalid("price.band.weekdays"))
);
let mut bad = deepseek_price();
bad.bands[0].weekdays = vec![Weekday::Mon, Weekday::Mon];
assert_eq!(
bad.validate(),
Err(ContractError::Invalid("price.band.weekdays"))
);
let mut bad = deepseek_price();
bad.bands[0].utc_hours.clear();
assert_eq!(
bad.validate(),
Err(ContractError::Invalid("price.band.utc_hours"))
);
let mut bad = deepseek_price();
bad.bands[0].utc_hours = vec![24];
assert_eq!(
bad.validate(),
Err(ContractError::Invalid("price.band.utc_hours"))
);
let mut bad = deepseek_price();
bad.bands[0].utc_hours = vec![1, 1];
assert_eq!(
bad.validate(),
Err(ContractError::Invalid("price.band.utc_hours"))
);
}
}

View file

@ -0,0 +1,130 @@
//! The usage readout: monthly caller/model spend visibility alongside the
//! subscription plan's own usage windows as the backend last saw them. The
//! connector gates nothing on cost; it publishes what it observed, and the
//! callers monitor their own quota.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::contract::ContractError;
pub const USAGE_READOUT_SCHEMA_ID: &str = "gamecult.model.usage_readout.v2";
/// One caller's committed monthly usage row for a single model in UTC `YYYY-MM`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CallerModelSpend {
pub caller: String,
pub model: String,
pub month: String,
pub calls: u64,
pub cost_micro_usd: u64,
pub calls_without_price: u64,
}
/// One window of the subscription plan, as the provider reported it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlanQuota {
pub window: String,
/// How much of the window was used when it was observed, in thousandths;
/// `None` once the window has reset (`status` is then `expired`), because
/// the old reading says nothing about the new window.
pub utilization_permille: Option<u32>,
pub resets_at_unix_ms: u64,
pub status: String,
/// When this window was last reported. Its age in a readout is the
/// readout's `at_unix_ms` minus this.
pub observed_at_unix_ms: u64,
}
/// What a backend last saw of the plan's windows, each stamped with its own
/// observation time. A backend with no plan to report returns the default.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PlanQuotaSnapshot {
pub windows: Vec<PlanQuota>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UsageReadout {
pub schema_id: String,
pub at_unix_ms: u64,
pub spend: Vec<CallerModelSpend>,
pub plan_quota: Vec<PlanQuota>,
}
impl UsageReadout {
pub fn new(at_unix_ms: u64, spend: Vec<CallerModelSpend>, plan: PlanQuotaSnapshot) -> Self {
Self {
schema_id: USAGE_READOUT_SCHEMA_ID.to_string(),
at_unix_ms,
spend,
plan_quota: plan.windows,
}
}
pub(crate) fn validate(&self) -> Result<(), ContractError> {
if self.schema_id != USAGE_READOUT_SCHEMA_ID {
return Err(ContractError::Schema);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::{wire_decode, wire_encode};
fn readout() -> UsageReadout {
UsageReadout::new(
1_000,
vec![CallerModelSpend {
caller: "caller-1".into(),
model: "deepseek/deepseek-flash".into(),
month: "2026-12".into(),
calls: 3,
cost_micro_usd: 4_014,
calls_without_price: 1,
}],
PlanQuotaSnapshot {
windows: vec![PlanQuota {
window: "five_hour".into(),
utilization_permille: Some(80),
resets_at_unix_ms: 1_793_307_000_000,
status: "allowed".into(),
observed_at_unix_ms: 999,
}],
},
)
}
#[test]
fn a_readout_is_a_named_map_that_decodes_to_itself() {
let bytes = wire_encode(&readout()).unwrap();
let value: rmpv::Value = rmp_serde::from_slice(&bytes).unwrap();
let rmpv::Value::Map(fields) = value else {
panic!("a readout is a map, not a positional array");
};
let names: Vec<&str> = fields.iter().filter_map(|(k, _)| k.as_str()).collect();
assert_eq!(names, ["schema_id", "at_unix_ms", "spend", "plan_quota"]);
assert_eq!(wire_decode::<UsageReadout>(&bytes).unwrap(), readout());
}
#[test]
fn an_unobserved_plan_is_none_not_zero() {
let bare = UsageReadout::new(1, Vec::new(), PlanQuotaSnapshot::default());
let decoded: UsageReadout = wire_decode(&wire_encode(&bare).unwrap()).unwrap();
assert!(decoded.spend.is_empty());
assert!(decoded.plan_quota.is_empty());
}
#[test]
fn a_readout_of_another_schema_is_refused() {
let mut other = readout();
other.schema_id = "gamecult.model.usage_readout.v1".into();
assert!(other.validate().is_err());
assert!(readout().validate().is_ok());
}
}

View file

@ -12,22 +12,31 @@ use zeroize::Zeroizing;
use crate::contract::TransportResult; use crate::contract::TransportResult;
use crate::envelope::{ use crate::envelope::{
ServiceError, TransportFrameError, decode_invocation_frame, encode_result_frame, RequestFrame, ServiceError, TransportFrameError, decode_request_frame, encode_result_frame,
frame_bytes_for_payload, read_transport_frame, write_transport_frame, encode_usage_readout_response_frame, frame_bytes_for_payload, read_transport_frame,
write_transport_frame,
};
use crate::readout::PlanQuotaSnapshot;
use crate::service::{
CallerAdmission, ProviderCall, ProviderRoutes, TransportAdmission, TransportService,
distinct_admissions,
}; };
use crate::service::{CallerAdmission, ProviderCall, TransportAdmission, TransportService};
/// 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. `serve` consults it once, before it /// Whether the provider can take work; `Err` names the backend field that
/// opens the replay store or accepts a connection; the request path does /// is not ready, never a value. `serve` consults it once, before it opens
/// not consult it. /// the replay store or accepts a connection; the request path does not
fn ready(&self) -> bool; /// consult it.
/// The tag of the provider this backend fronts. The service owns it from fn ready(&self) -> Result<(), &'static str>;
/// `serve` on: it names the provider on every receipt and decides which /// What one provider's own plan allows and has used together with that
/// reasoning state is foreign. /// provider's tag, for the usage readout and that provider's own refusals.
fn provider(&self) -> &str; /// A backend with no plan to report keeps `None`.
fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> {
None
}
/// 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
/// reasoning item and builds the result's receipt itself. /// reasoning item and builds the result's receipt itself.
@ -56,7 +65,7 @@ impl ServeLimits {
/// largest whose sealed frame, at its worst-case encoding, fits the frame. /// largest whose sealed frame, at its worst-case encoding, fits the frame.
/// An admitted payload therefore always fits, and `complete` is given the /// An admitted payload therefore always fits, and `complete` is given the
/// same frame bound to fit every result in. /// same frame bound to fit every result in.
fn validate(&self, admissions: &[CallerAdmission]) -> Result<(), ServeError> { pub fn validate(&self, admissions: &[CallerAdmission]) -> Result<(), ServeError> {
if self.max_frame_bytes == 0 if self.max_frame_bytes == 0
|| self.max_frame_bytes > u32::MAX as usize || self.max_frame_bytes > u32::MAX as usize
|| self.max_connections == 0 || self.max_connections == 0
@ -76,6 +85,7 @@ impl ServeLimits {
if admissions.is_empty() { if admissions.is_empty() {
return Err(ServeError::InvalidConfig("callers")); return Err(ServeError::InvalidConfig("callers"));
} }
distinct_admissions(admissions)?;
let slots = admissions let slots = admissions
.iter() .iter()
.try_fold(0_usize, |total, caller| { .try_fold(0_usize, |total, caller| {
@ -146,9 +156,37 @@ 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())?;
let service = Arc::new(Mutex::new(TransportService::open(
replay_store,
routes,
admissions,
limits.max_expiry_skew_ms,
)?));
accept_loop(|| listener.accept(), limits, service, backend)
}
/// `serve` over a service the caller opened and keeps a handle to, so another
/// front of the same service (the credential lease) shares its
/// replay store and plan. The limits must already have been validated against the
/// service's admissions.
pub fn serve_service(
listener: TcpListener,
limits: ServeLimits,
service: Arc<Mutex<TransportService>>,
backend: Arc<dyn ProviderBackend>,
) -> Result<(), ServeError> {
admit_listener(&listener, backend.as_ref())?;
accept_loop(|| listener.accept(), limits, service, backend)
}
/// What must be true before a serve loop touches the store: the listener is
/// on loopback and the backend can take work.
fn admit_listener(listener: &TcpListener, backend: &dyn ProviderBackend) -> Result<(), ServeError> {
if !listener if !listener
.local_addr() .local_addr()
.map_err(ServeError::Listen)? .map_err(ServeError::Listen)?
@ -157,16 +195,7 @@ pub fn serve(
{ {
return Err(ServeError::InvalidConfig("listener address")); return Err(ServeError::InvalidConfig("listener address"));
} }
if !backend.ready() { backend.ready().map_err(ServeError::BackendUnready)
return Err(ServeError::BackendUnready);
}
let service = Arc::new(Mutex::new(TransportService::open(
replay_store,
backend.provider(),
admissions,
limits.max_expiry_skew_ms,
)?));
accept_loop(|| listener.accept(), limits, service, backend)
} }
/// The accept loop over any source of connections, so a test can present a /// The accept loop over any source of connections, so a test can present a
@ -218,21 +247,42 @@ fn serve_connection(
.and_then(|()| stream.set_write_timeout(Some(timeout))) .and_then(|()| stream.set_write_timeout(Some(timeout)))
.map_err(ServeError::Connection)?; .map_err(ServeError::Connection)?;
let request = read_transport_frame(&mut stream, limits.max_frame_bytes).map_err(frame_error)?; let request = read_transport_frame(&mut stream, limits.max_frame_bytes).map_err(frame_error)?;
let response = execute_inference_frame(&request, service, backend, limits)?; let response = answer_frame(&request, service, backend, limits)?;
write_transport_frame(&mut stream, &response, limits.max_frame_bytes).map_err(frame_error) write_transport_frame(&mut stream, &response, limits.max_frame_bytes).map_err(frame_error)
} }
fn execute_inference_frame( fn answer_frame(
request: &[u8], request: &[u8],
service: &Mutex<TransportService>, service: &Mutex<TransportService>,
backend: &dyn ProviderBackend, backend: &dyn ProviderBackend,
limits: &ServeLimits, limits: &ServeLimits,
) -> Result<Vec<u8>, ServeError> { ) -> Result<Vec<u8>, ServeError> {
let envelope = decode_invocation_frame(request).map_err(|_| ServeError::FrameEncoding)?; let envelope = match decode_request_frame(request).map_err(|_| ServeError::FrameEncoding)? {
RequestFrame::Invoke(envelope) => envelope,
RequestFrame::UsageReadout(envelope) => {
let plan = backend
.plan_quota()
.map(|(_, snapshot)| snapshot)
.unwrap_or_default();
let response = service
.lock()
.map_err(|_| ServeError::ServicePoisoned)?
.usage_readout(&envelope, unix_ms()?, plan, limits.max_frame_bytes)?;
return encode_usage_readout_response_frame(&response)
.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(&envelope, unix_ms()?, limits.max_frame_bytes)?; .begin(
&envelope,
unix_ms()?,
plan.as_ref()
.map(|(provider, snapshot)| (*provider, snapshot)),
limits.max_frame_bytes,
)?;
let response = match admission { let response = match admission {
TransportAdmission::Reply(response) => response, TransportAdmission::Reply(response) => response,
TransportAdmission::Execute(claim) => { TransportAdmission::Execute(claim) => {
@ -307,8 +357,8 @@ pub enum ServeError {
ConnectionKey(#[source] std::io::Error), ConnectionKey(#[source] std::io::Error),
#[error(transparent)] #[error(transparent)]
Service(#[from] ServiceError), Service(#[from] ServiceError),
#[error("provider backend is not ready")] #[error("provider backend is not ready: {0}")]
BackendUnready, BackendUnready(&'static str),
#[error("connector service lock was poisoned")] #[error("connector service lock was poisoned")]
ServicePoisoned, ServicePoisoned,
#[error("connector listener failed")] #[error("connector listener failed")]
@ -336,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";
@ -361,13 +411,9 @@ mod tests {
} }
impl ProviderBackend for CountingBackend { impl ProviderBackend for CountingBackend {
fn ready(&self) -> bool { fn ready(&self) -> Result<(), &'static str> {
self.ready_calls.fetch_add(1, Ordering::SeqCst); self.ready_calls.fetch_add(1, Ordering::SeqCst);
self.ready 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 {
@ -412,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()
} }
@ -438,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)
@ -460,6 +513,247 @@ mod tests {
.collect() .collect()
} }
/// A counting backend that reports a plan, as a provider with one would.
struct PlanBackend {
inner: Arc<CountingBackend>,
provider: &'static str,
plan: PlanQuotaSnapshot,
}
impl ProviderBackend for PlanBackend {
fn ready(&self) -> Result<(), &'static str> {
self.inner.ready()
}
fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> {
Some((self.provider, self.plan.clone()))
}
fn execute(&self, call: &ProviderCall) -> TransportResult {
self.inner.execute(call)
}
}
#[test]
fn serve_reads_out_plan_usage_without_executing_anything() {
let store = TestStore::new();
let inner = CountingBackend::new(true);
let plan = PlanQuotaSnapshot {
windows: vec![crate::readout::PlanQuota {
window: "five_hour".into(),
utilization_permille: Some(80),
resets_at_unix_ms: 1_793_307_000_000,
status: "allowed".into(),
observed_at_unix_ms: 1_793_300_000_000,
}],
};
let backend = Arc::new(PlanBackend {
inner: inner.clone(),
provider: "fixture-sse",
plan: plan.clone(),
});
let (client, endpoint) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
client.execute(&fresh("request-1")).unwrap();
assert_eq!(inner.executions.load(Ordering::SeqCst), 1);
let before = now_ms();
let readout = client.usage_readout(CALLER).unwrap();
assert!(readout.at_unix_ms >= before && readout.at_unix_ms <= now_ms());
assert_eq!(readout.plan_quota, plan.windows);
assert_eq!(
inner.executions.load(Ordering::SeqCst),
1,
"a readout runs nothing"
);
// A client without the caller's key is dropped, not answered.
let stranger = ConnectorClient::new(
endpoint,
"some-other-key",
FRAME,
Some(Duration::from_secs(5)),
)
.unwrap();
assert!(stranger.usage_readout(CALLER).is_err());
}
#[test]
fn plan_quota_defaults_to_none() {
assert_eq!(CountingBackend::new(true).plan_quota(), None);
}
#[test]
fn a_backend_with_no_plan_reads_out_none() {
let store = TestStore::new();
let (client, _) = start(CountingBackend::new(true), &store);
let readout = client.usage_readout(CALLER).unwrap();
assert!(readout.plan_quota.is_empty());
assert!(readout.spend.is_empty());
}
#[test]
fn serve_usage_readout_includes_monthly_spend_communally() {
use crate::price::{PriceRow, TokenRates, utc_month_string};
use crate::readout::CallerModelSpend;
let store = TestStore::new();
let now = now_ms();
let month = utc_month_string(now);
let priced_routes = ProviderRoutes::with_prices([(
"gpt-5.4".to_string(),
"fixture-sse".to_string(),
Some(PriceRow {
base: TokenRates {
input: 1_000_000,
cache_read: 0,
cache_write: 0,
output: 1_000_000,
},
bands: Vec::new(),
}),
)])
.unwrap();
let backend = CountingBackend::new(true);
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let endpoint = listener.local_addr().unwrap();
let path = store.path.clone();
let backend_handle = backend.clone();
thread::spawn(move || {
serve(
listener,
limits(),
vec![
caller(CALLER, KEY, 4),
caller("ghostlight-yggdrasil", "ghostlight-distinct-test-key", 4),
],
&path,
priced_routes,
backend_handle,
)
});
let client_a =
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
let client_b = ConnectorClient::new(
endpoint,
"ghostlight-distinct-test-key",
FRAME,
Some(Duration::from_secs(5)),
)
.unwrap();
let inv_a = fresh("spend-a-1");
let res_a = client_a.execute(&inv_a).unwrap();
let TransportDisposition::Transported { receipt: rc_a, .. } = &res_a.disposition else {
panic!("expected transported result");
};
assert_eq!(rc_a.cost_micro_usd, Some(13));
// Replay must not double-count.
assert_eq!(client_a.execute(&inv_a).unwrap(), res_a);
assert_eq!(backend.executions.load(Ordering::SeqCst), 1);
let mut inv_b = invocation_for("ghostlight-yggdrasil", "spend-b-1");
inv_b.expires_at_unix_ms = now_ms() + 60_000;
let res_b = client_b.execute(&inv_b).unwrap();
let TransportDisposition::Transported { receipt: rc_b, .. } = &res_b.disposition else {
panic!("expected transported result");
};
assert_eq!(rc_b.cost_micro_usd, Some(13));
let expected = vec![
CallerModelSpend {
caller: CALLER.to_string(),
model: "gpt-5.4".to_string(),
month: month.clone(),
calls: 1,
cost_micro_usd: 13,
calls_without_price: 0,
},
CallerModelSpend {
caller: "ghostlight-yggdrasil".to_string(),
model: "gpt-5.4".to_string(),
month,
calls: 1,
cost_micro_usd: 13,
calls_without_price: 0,
},
];
assert_eq!(client_a.usage_readout(CALLER).unwrap().spend, expected);
assert_eq!(
client_b
.usage_readout("ghostlight-yggdrasil")
.unwrap()
.spend,
expected
);
}
fn window_plan(permille: u32, status: &str, resets_at_unix_ms: u64) -> PlanQuotaSnapshot {
PlanQuotaSnapshot {
windows: vec![crate::readout::PlanQuota {
window: "five_hour".into(),
utilization_permille: Some(permille),
resets_at_unix_ms,
status: status.into(),
observed_at_unix_ms: 1,
}],
}
}
#[test]
fn serve_repeats_the_providers_rejection_and_executes_nothing_while_it_stands() {
let store = TestStore::new();
let inner = CountingBackend::new(true);
let backend = Arc::new(PlanBackend {
inner: inner.clone(),
provider: "fixture-sse",
plan: window_plan(1_000, "rejected", now_ms() + 3_600_000),
});
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
let refused = client.execute(&fresh("request-rejected")).unwrap();
assert_eq!(
refused.disposition,
TransportDisposition::Refused(Refusal::ProviderRejected)
);
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]
fn serve_admits_a_full_window_the_provider_still_allows() {
let store = TestStore::new();
let inner = CountingBackend::new(true);
let backend = Arc::new(PlanBackend {
inner: inner.clone(),
provider: "fixture-sse",
plan: window_plan(999, "allowed", now_ms() + 3_600_000),
});
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
let admitted = client.execute(&fresh("request-full")).unwrap();
assert!(matches!(
admitted.disposition,
TransportDisposition::Transported { .. }
));
assert_eq!(inner.executions.load(Ordering::SeqCst), 1);
}
#[test] #[test]
fn serve_end_to_end_replays_without_a_second_execution() { fn serve_end_to_end_replays_without_a_second_execution() {
let store = TestStore::new(); let store = TestStore::new();
@ -577,18 +871,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) = let TransportAdmission::Execute(claim) =
service.begin(&envelope, now_ms(), 1 << 20).unwrap() service.begin(&envelope, now_ms(), None, 1 << 20).unwrap()
else { else {
panic!("a fresh request must execute"); panic!("a fresh request must execute");
}; };
@ -612,6 +902,7 @@ mod tests {
narrowed, narrowed,
vec![caller(CALLER, KEY, 4)], vec![caller(CALLER, KEY, 4)],
&path, &path,
routes(),
served, served,
) )
}); });
@ -646,7 +937,10 @@ mod tests {
&store.path, &store.path,
backend.clone(), backend.clone(),
); );
assert!(matches!(result, Some(Err(ServeError::BackendUnready)))); assert!(matches!(
result,
Some(Err(ServeError::BackendUnready("fixture")))
));
assert_eq!(backend.executions.load(Ordering::SeqCst), 0); assert_eq!(backend.executions.load(Ordering::SeqCst), 0);
assert!( assert!(
!store.path.exists(), !store.path.exists(),
@ -759,6 +1053,26 @@ mod tests {
)); ));
} }
#[test]
fn the_limits_refuse_callers_that_share_a_key_or_an_id() {
let limits = limits();
let shared_key = [
caller("one", "shared-key", 1),
caller("two", "shared-key", 1),
];
assert!(matches!(
limits.validate(&shared_key),
Err(ServeError::Service(ServiceError::SharedCallerKey))
));
let shared_id = [caller("one", "key-a", 1), caller("one", "key-b", 1)];
assert!(matches!(
limits.validate(&shared_id),
Err(ServeError::Service(ServiceError::DuplicateCaller))
));
let distinct = [caller("one", "key-a", 1), caller("two", "key-b", 1)];
assert!(limits.validate(&distinct).is_ok());
}
#[test] #[test]
fn only_loopback_peers_are_admitted() { fn only_loopback_peers_are_admitted() {
assert!(peer_admitted(IpAddr::from([127, 0, 0, 1]))); assert!(peer_admitted(IpAddr::from([127, 0, 0, 1])));
@ -887,7 +1201,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();
@ -935,12 +1249,8 @@ mod tests {
} }
impl ProviderBackend for SizedBackend { impl ProviderBackend for SizedBackend {
fn ready(&self) -> bool { fn ready(&self) -> Result<(), &'static str> {
true Ok(())
}
fn provider(&self) -> &str {
"fixture-sse"
} }
fn execute(&self, call: &ProviderCall) -> TransportResult { fn execute(&self, call: &ProviderCall) -> TransportResult {
@ -987,6 +1297,7 @@ mod tests {
&& receipt.outcome == TransportOutcome::Failed { && receipt.outcome == TransportOutcome::Failed {
kind: FailureKind::ResultSize, kind: FailureKind::ResultSize,
message: "provider result exceeded its byte bound".to_string(), message: "provider result exceeded its byte bound".to_string(),
usage: None,
} }
) )
} }
@ -998,20 +1309,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) = let TransportAdmission::Execute(claim) =
service.begin(&envelope, now_ms(), 1 << 20).unwrap() service.begin(&envelope, now_ms(), None, 1 << 20).unwrap()
else { else {
panic!("a fresh request must execute"); panic!("a fresh request must execute");
}; };
@ -1102,7 +1409,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,
) )
@ -1160,7 +1467,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();
@ -1189,11 +1496,54 @@ mod tests {
Err(TransportFrameError::Connection(_)) Err(TransportFrameError::Connection(_))
)); ));
assert_eq!(backend.executions.load(Ordering::SeqCst), 0); assert_eq!(backend.executions.load(Ordering::SeqCst), 0);
// The loop survives the v2 peer and serves a v3 one. // The loop survives the v2 peer and serves a v5 one.
client.execute(&fresh("request-after-v2")).unwrap(); client.execute(&fresh("request-after-v2")).unwrap();
assert_eq!(backend.executions.load(Ordering::SeqCst), 1); assert_eq!(backend.executions.load(Ordering::SeqCst), 1);
} }
#[test]
fn a_v4_frame_gets_no_answer() {
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cultnet_rs::{CultNetMessage, CultNetWireContract, encode_cultnet_message_to_vec};
let store = TestStore::new();
let backend = CountingBackend::new(true);
let (client, endpoint) = start(backend.clone(), &store);
let v4_envelope = crate::envelope::TransportEnvelope {
schema_id: format!("{}{}", "gamecult.model.transport_envelope.", "v4"),
caller_runtime_id: CALLER.to_string(),
request_id: "request-v4".to_string(),
message_kind: crate::envelope::EnvelopeKind::Invocation,
nonce: [0_u8; 12],
ciphertext: vec![1_u8; 40],
};
let v4_frame = encode_cultnet_message_to_vec(
&CultNetMessage::OperationRequest {
message_id: "request-v4".to_string(),
service_id: crate::envelope::CONNECTOR_SERVICE_ID.to_string(),
operation: crate::envelope::INVOKE_OPERATION.to_string(),
payload_schema: v4_envelope.schema_id.clone(),
payload_encoding: "messagepack-base64".to_string(),
payload: STANDARD.encode(crate::contract::wire_encode(&v4_envelope).unwrap()),
source_runtime_id: None,
target_runtime_id: None,
},
CultNetWireContract::CultNetSchemaV0,
)
.unwrap();
let mut stream = TcpStream::connect(endpoint).unwrap();
write_transport_frame(&mut stream, &v4_frame, FRAME).unwrap();
assert!(matches!(
read_transport_frame(&mut stream, FRAME),
Err(TransportFrameError::Connection(_))
));
assert_eq!(backend.executions.load(Ordering::SeqCst), 0);
// The loop survives the v4 peer and serves a v5 one.
client.execute(&fresh("request-after-v4")).unwrap();
assert_eq!(backend.executions.load(Ordering::SeqCst), 1);
}
#[test] #[test]
fn a_reply_echoes_the_request_id() { fn a_reply_echoes_the_request_id() {
use cultnet_rs::{CultNetMessage, CultNetWireContract, decode_cultnet_message_from_slice}; use cultnet_rs::{CultNetMessage, CultNetWireContract, decode_cultnet_message_from_slice};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,476 @@
//! A credential lease: a holder's hold on the token the connector lends.
//! The lease is memory bound to its holder's open connection, not a record and
//! not a charge: it decides `Busy` while it is held and nothing else. It ends
//! when its holder lets go (`end_lease`), when the unit invocation it served
//! ends, or when its expiry passes. Nothing is billed and nothing is reserved.
//! The only usage-derived refusal is the provider's own (`ProviderRejected`),
//! repeated with the provider's own expiry.
use super::*;
/// The request-id namespace of leases.
const LEASE_PREFIX: &str = "lease:";
/// What a per-invocation lease id adds to its invocation id, so a
/// per-invocation lease and a per-caller lease of one caller and one
/// invocation never share an id.
const INVOCATION_SUFFIX: &str = ":invocation";
/// Exclusivity scope of a lease. It is a property of the lease holder's
/// configured row, never of a request. A `PerCaller` holder keeps one lease open
/// 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)]
pub enum LeaseScope {
PerCaller,
PerInvocation,
}
/// What an admitted lease holds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LeaseGrant {
pub lease_id: String,
}
/// Why no lease was granted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LeaseRefusal {
UnknownCaller,
/// `PerCaller`: the caller holds a per-caller lease now. `PerInvocation`:
/// this invocation holds a lease now.
Busy,
/// The provider is refusing right now and has said until when.
ProviderRejected,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LeaseAdmission {
Granted(LeaseGrant),
Refused(LeaseRefusal),
}
impl TransportService {
/// Grants `caller_runtime_id` a lease for the unit invocation
/// `invocation_id` until `expires_at_unix_ms`. A `PerCaller` lease is
/// `lease:<invocation>` and one is open per caller; a `PerInvocation` lease
/// is `lease:<invocation>:invocation`, one open per invocation; neither
/// blocks the other. A lease takes no request slot. `plan` is the backend's
/// plan quota as it stands: a provider that is refusing right now refuses
/// the lease. A lease past its expiry no longer holds anything.
pub fn begin_lease(
&mut self,
caller_runtime_id: &str,
scope: LeaseScope,
invocation_id: &str,
expires_at_unix_ms: u64,
now_unix_ms: u64,
plan: &PlanQuotaSnapshot,
) -> Result<LeaseAdmission, ServiceError> {
if !self.callers.contains_key(caller_runtime_id) {
return Ok(LeaseAdmission::Refused(LeaseRefusal::UnknownCaller));
}
require_id(invocation_id, "invocation_id")?;
let suffix = match scope {
LeaseScope::PerCaller => "",
LeaseScope::PerInvocation => INVOCATION_SUFFIX,
};
let lease_id = format!("{LEASE_PREFIX}{invocation_id}{suffix}");
if lease_id.len() > MAX_IDENTITY_BYTES {
return Err(ContractError::Invalid("invocation_id").into());
}
self.leases
.retain(|_, lease| lease.expires_at_unix_ms > now_unix_ms);
let identity = RequestIdentity {
caller_runtime_id: caller_runtime_id.to_string(),
request_id: lease_id.clone(),
};
let busy = match scope {
LeaseScope::PerCaller => self.leases.iter().any(|(held, lease)| {
lease.scope == LeaseScope::PerCaller && held.caller_runtime_id == caller_runtime_id
}),
LeaseScope::PerInvocation => self.leases.contains_key(&identity),
};
if busy {
return Ok(LeaseAdmission::Refused(LeaseRefusal::Busy));
}
if plan_rejects(plan, now_unix_ms) {
return Ok(LeaseAdmission::Refused(LeaseRefusal::ProviderRejected));
}
self.leases.insert(
identity,
LiveLease {
scope,
expires_at_unix_ms,
},
);
Ok(LeaseAdmission::Granted(LeaseGrant { lease_id }))
}
/// Ends a lease its holder let go of. Ending one that is not held is a
/// no-op: a holder may close after its expiry already freed the lease.
pub fn end_lease(&mut self, caller_runtime_id: &str, lease_id: &str) {
self.leases.remove(&RequestIdentity {
caller_runtime_id: caller_runtime_id.to_string(),
request_id: lease_id.to_string(),
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fixtures::*;
use crate::readout::PlanQuota;
const CALLER: &str = "eureka";
const CALLER_TWO: &str = "caller-two";
const KEY: &str = "lease-distinct-test-key";
const KEY_TWO: &str = "lease-distinct-test-key-two";
const NOW: u64 = 7_200_500;
fn open(store: &TestStore) -> TransportService {
TransportService::open(
&store.path,
crate::fixtures::routes(),
[
CallerAdmission::new(CALLER, KEY, 1, ["gpt-5.4".to_string()], 1, 65_536, 32_768)
.unwrap(),
CallerAdmission::new(
CALLER_TWO,
KEY_TWO,
1,
["gpt-5.4".to_string()],
1,
65_536,
32_768,
)
.unwrap(),
],
5_000,
)
.unwrap()
}
fn none() -> PlanQuotaSnapshot {
PlanQuotaSnapshot::default()
}
fn window(permille: u32, status: &str, resets_at: u64) -> PlanQuotaSnapshot {
PlanQuotaSnapshot {
windows: vec![PlanQuota {
window: "five_hour".to_string(),
utilization_permille: Some(permille),
resets_at_unix_ms: resets_at,
status: status.to_string(),
observed_at_unix_ms: NOW,
}],
}
}
fn lease_in(
service: &mut TransportService,
scope: LeaseScope,
run: &str,
plan: &PlanQuotaSnapshot,
) -> LeaseAdmission {
service
.begin_lease(CALLER, scope, run, NOW + 60_000, NOW, plan)
.unwrap()
}
fn lease(service: &mut TransportService, run: &str) -> LeaseAdmission {
lease_in(service, LeaseScope::PerCaller, run, &none())
}
fn granted(admission: LeaseAdmission) -> LeaseGrant {
match admission {
LeaseAdmission::Granted(grant) => grant,
LeaseAdmission::Refused(why) => panic!("refused {why:?}"),
}
}
#[test]
fn a_lease_is_named_by_its_invocation() {
let store = TestStore::new();
let mut service = open(&store);
assert_eq!(
granted(lease(&mut service, "run-1")).lease_id,
"lease:run-1"
);
}
#[test]
fn a_per_caller_holder_holds_one_lease_at_a_time() {
let store = TestStore::new();
let mut service = open(&store);
granted(lease(&mut service, "run-1"));
assert_eq!(
lease(&mut service, "run-2"),
LeaseAdmission::Refused(LeaseRefusal::Busy)
);
assert_eq!(
lease(&mut service, "run-1"),
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]
fn a_lease_ends_when_its_holder_closes() {
let store = TestStore::new();
let mut service = open(&store);
let grant = granted(lease(&mut service, "run-1"));
service.end_lease(CALLER, &grant.lease_id);
// The same invocation may lease again: nothing remembers a closed
// lease, and nothing was billed for it.
granted(lease(&mut service, "run-1"));
service.end_lease(CALLER, "lease:not-held");
assert_eq!(
lease(&mut service, "run-2"),
LeaseAdmission::Refused(LeaseRefusal::Busy),
"ending a lease that is not held frees nothing else"
);
}
#[test]
fn a_lease_ends_at_its_expiry_without_its_holder() {
let store = TestStore::new();
let mut service = open(&store);
granted(
service
.begin_lease(
CALLER,
LeaseScope::PerCaller,
"run-1",
NOW + 10,
NOW,
&none(),
)
.unwrap(),
);
assert_eq!(
service
.begin_lease(
CALLER,
LeaseScope::PerCaller,
"run-2",
NOW + 99,
NOW + 9,
&none()
)
.unwrap(),
LeaseAdmission::Refused(LeaseRefusal::Busy),
"one millisecond before its expiry the lease still holds"
);
granted(
service
.begin_lease(
CALLER,
LeaseScope::PerCaller,
"run-2",
NOW + 99,
NOW + 10,
&none(),
)
.unwrap(),
);
}
#[test]
fn a_stranger_is_refused() {
let store = TestStore::new();
let mut service = open(&store);
assert_eq!(
service
.begin_lease(
"stranger",
LeaseScope::PerCaller,
"run-1",
NOW + 1,
NOW,
&none()
)
.unwrap(),
LeaseAdmission::Refused(LeaseRefusal::UnknownCaller)
);
}
#[test]
fn a_per_invocation_holder_holds_one_lease_per_invocation_and_never_blocks_per_caller() {
let store = TestStore::new();
let mut service = open(&store);
let per_invocation = |service: &mut TransportService, run: &str| {
lease_in(service, LeaseScope::PerInvocation, run, &none())
};
let first = granted(per_invocation(&mut service, "turn-1"));
assert_eq!(first.lease_id, "lease:turn-1:invocation");
assert_eq!(
per_invocation(&mut service, "turn-1"),
LeaseAdmission::Refused(LeaseRefusal::Busy)
);
granted(per_invocation(&mut service, "turn-2"));
granted(lease(&mut service, "turn-1"));
service.end_lease(CALLER, &first.lease_id);
granted(per_invocation(&mut service, "turn-1"));
}
#[test]
fn a_rejected_window_refuses_invoke_and_lease_until_its_reset() {
let store = TestStore::new();
let mut service = open(&store);
let rejected = window(1_000, "rejected", NOW + 5_000);
assert_eq!(
lease_in(&mut service, LeaseScope::PerCaller, "run-1", &rejected),
LeaseAdmission::Refused(LeaseRefusal::ProviderRejected)
);
let call = |service: &mut TransportService, now: u64, plan: &PlanQuotaSnapshot| {
let mut asked = request();
asked.request_id = format!("call-{now}");
let invocation = TransportInvocation::new(CALLER, now + 1_000, [7; 32], asked).unwrap();
let sealed = crate::envelope::encrypt_message(
CALLER,
invocation.request_id(),
crate::envelope::EnvelopeKind::Invocation,
&crate::contract::wire_encode(&invocation).unwrap(),
&security(KEY),
)
.unwrap();
let TransportAdmission::Reply(reply) = service
.begin(&sealed, now, Some(("fixture-sse", plan)), 1 << 20)
.unwrap()
else {
return None;
};
let result =
crate::envelope::decrypt_result(&reply, &security(KEY), &invocation).unwrap();
match result.disposition {
TransportDisposition::Refused(refusal) => Some(refusal),
other => panic!("unexpected {other:?}"),
}
};
assert_eq!(
call(&mut service, NOW, &rejected),
Some(Refusal::ProviderRejected)
);
assert_eq!(
call(&mut service, NOW + 4_999, &rejected),
Some(Refusal::ProviderRejected)
);
assert_eq!(call(&mut service, NOW + 5_000, &rejected), None);
assert!(matches!(
service
.begin_lease(
CALLER,
LeaseScope::PerCaller,
"run-1",
NOW + 9_000,
NOW + 5_000,
&rejected
)
.unwrap(),
LeaseAdmission::Granted(_)
));
}
#[test]
fn high_utilization_refuses_nothing() {
let store = TestStore::new();
let mut service = open(&store);
let full = window(999, "allowed", NOW + 5_000);
granted(lease_in(
&mut service,
LeaseScope::PerCaller,
"run-1",
&full,
));
let warned = window(1_000, "allowed_warning", NOW + 5_000);
granted(lease_in(
&mut service,
LeaseScope::PerInvocation,
"turn-1",
&warned,
));
}
#[test]
fn an_invocation_id_is_bounded_so_its_lease_id_fits_an_identity() {
let store = TestStore::new();
let mut service = open(&store);
let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len());
let grant = granted(lease(&mut service, &longest));
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES);
assert!(lease_try(&mut service, LeaseScope::PerCaller, &format!("{longest}r")).is_err());
}
#[test]
fn a_per_invocation_id_leaves_room_for_its_suffix() {
let store = TestStore::new();
let mut service = open(&store);
let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len() - INVOCATION_SUFFIX.len());
let grant = granted(lease_in(
&mut service,
LeaseScope::PerInvocation,
&longest,
&none(),
));
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES);
assert!(
lease_try(
&mut service,
LeaseScope::PerInvocation,
&format!("{longest}r")
)
.is_err()
);
}
fn lease_try(
service: &mut TransportService,
scope: LeaseScope,
run: &str,
) -> Result<LeaseAdmission, ServiceError> {
service.begin_lease(CALLER, scope, run, NOW + 60_000, NOW, &none())
}
#[test]
fn a_lease_takes_no_request_slot_from_the_callers_calls() {
// The caller admits one concurrent call; an open lease must not use it.
let store = TestStore::new();
let mut service = open(&store);
granted(lease(&mut service, "run-1"));
let mut call = request();
call.request_id = "call-1".to_string();
let invocation = TransportInvocation::new(CALLER, NOW + 1_000, [7; 32], call).unwrap();
let sealed = crate::envelope::encrypt_message(
CALLER,
"call-1",
crate::envelope::EnvelopeKind::Invocation,
&crate::contract::wire_encode(&invocation).unwrap(),
&security(KEY),
)
.unwrap();
assert!(matches!(
service.begin(&sealed, NOW, None, 1 << 20).unwrap(),
TransportAdmission::Execute(_)
));
// And a call in flight does not make the caller busy for a lease.
granted(lease_in(
&mut service,
LeaseScope::PerInvocation,
"turn-1",
&none(),
));
}
}

View file

@ -1,16 +0,0 @@
# wire_v3 fixtures
The named-MessagePack bytes of the v3 documents and one sealed carriage frame,
produced by the kit at the revision that added them. They pin drift; the types in
`src/contract.rs` own the shape, and `schemas/` publishes it.
- `provider_request.mp`, `transport_invocation.mp`, `transport_result_transported.mp`,
`transport_result_refused.mp`, `transport_receipt_failed.mp`, `transport_envelope.mp`,
`input_reasoning_state.mp` (an `InputItem::ReasoningState`, its state as MessagePack `bin`):
the plaintext documents.
- `carriage_invocation.frame`: a `cultnet.operation_request.v0` for service
`gamecult.model.connector`, operation `invoke`, whose payload is the base64 of an envelope
sealed under the fixed test key in `tests/wire_golden_v3.rs`.
Generator: `tests/wire_golden_v3.rs` itself. Run it with `WIRE_V3_REGENERATE=1` to rewrite
the files from the kit, then review the diff: a changed byte is a wire change.

View file

@ -1 +0,0 @@
<EFBFBD>messageIdョgolden-requestゥoperationヲinvokeァpayloadレ$hqlzY2hlbWFfaWTZJGdhbWVjdWx0Lm1vZGVsLnRyYW5zcG9ydF9lbnZlbG9wZS52M7FjYWxsZXJfcnVudGltZV9pZK1nb2xkZW4tY2FsbGVyqnJlcXVlc3RfaWSuZ29sZGVuLXJlcXVlc3SsbWVzc2FnZV9raW5kqkludm9jYXRpb26lbm9uY2WcS2XMwjgRzMrM9QTM037MsczmqmNpcGhlcnRleHTFAy8eYmQGV5JCOLETwqQE+wIz/6yyPltHTPywbakMD/mgkJUxAvKWLNljXa4RAVVITAb3GxklnGF8zoOX/9qGSM9r0JZ126s+0LqvsRNhllG1S0pfG49fQJy99pevHReOSvX/cNWs2cHppYNdJUbVVAkDuioEXwtEs/vRCsmD/ab0bKUX0XRzrNbmjMU4+dHUCus8yt+iNTK9GdjXbEQAweeKNehirXEgnngLnwylo/MDoI4G237du3PmwhMzyIHztoIbwD0Bv9x7WqY+jj90vqEBsOHl+FmYc+F8+OiP6NKTDNRHypUtdo32G/IgfMfbsP/XHiNpPHtLxDqZVIcYdYqLAvhDfLBReLzQVLuNJnE0a2P8xLVAkfbmQZNsxRqS14RjYVtRoDcacxH1h0afo9OWMSK8Sp8eEBAhAJ7ovhCMklc7xWB3o4ny4cmDSExx5zWRLdI14rC1CZ7nq8k3V8fIIHctSp6am35A5yyiTwDH0m3h7/hvXrzhOqtAwHd0jkfNv+qOXZCEPdtbzOXOz0fMVZwvTAJWhoEYmhfKcGvXu8SmEtZcZe0WjF4xpFIFCFsSxh8HcrDFvxKDa58bnimo6DE2VeEMolpaBvnIGEst6qNZ9VQQnQIpCGbbtFd7jMrncnfcq+36NI10qW30r8sqAqgORp8cAGP5fy2X9SQDmH13SXgSfIdr7uxAHhK0X1r0iopJn4XtVfBiTd+IfoLFN+KO/JTZvLc48e6Jl9QRnxkL/UCgT/5wENd9VRxP+oO1CXG3DthI882rVbZDkhhwxupM9J/EURONajVyVSkeju+r9vzHCgR5odRW8cwqY1RXoq6L6mhj4ph01MBkUugz8MFwBsem+8QpnGatyVbZB99knWjK/01o5J6SZihcXNowRdon6BTydFByJaV5bRvgIK7IGRct3BmC8xidyxN9p7QAZYMPscxhQ0hAM615w76Cy82kx6eAzREBQX3COKApXSlPA/xlOKa/iUUMWHvFKyf/n0KrOlVvHjoDzPflHi3hpxxWcQGt8CxxNdSQMufeqce/5/BCeEwRIJ99+k7CEqIqpFIs7cAsI1GpF+NO5w==ッpayloadEncodingイmessagepack-base64ュpayloadSchemaル$gamecult.model.transport_envelope.v3ュschemaVersionシcultnet.operation_request.v0ゥserviceIdクgamecult.model.connector

View file

@ -0,0 +1,16 @@
# wire_v5 fixtures
The named-MessagePack bytes of the v5 documents and one sealed carriage frame,
kept so a format drift breaks a test instead of passing silently:
- `provider_request.mp`: `ProviderRequest`.
- `transport_invocation.mp`: `TransportInvocation` over the same request.
- `input_reasoning_state.mp`: `InputItem::ReasoningState` carrying bytes `0x80..=0xff`.
- `transport_result_transported.mp`: `TransportResult` with `Transported` disposition and priced `cost_micro_usd`.
- `transport_result_refused.mp`: `TransportResult` with `Refused` disposition.
- `transport_receipt_failed.mp`: `TransportReceipt` with `Failed` outcome, usage, and `cost_micro_usd: Some(0)`.
- `transport_receipt_failed_no_usage.mp`: `TransportReceipt` with `Failed` outcome, `usage: None`, and `cost_micro_usd: None`.
- `transport_envelope.mp`: `TransportEnvelope` with non-ASCII nonce and ciphertext.
- `carriage_invocation.frame`: `cultnet.operation_request.v0` wrapping the v5 envelope sealed under the fixed test key in `tests/wire_golden_v5.rs`.
Generator: `tests/wire_golden_v5.rs` itself. Run it with `WIRE_V5_REGENERATE=1` to rewrite the files from the types, then review the diff: a changed byte is a wire change.

View file

@ -0,0 +1 @@
<EFBFBD>messageIdョgolden-requestゥoperationヲinvokeァpayloadレ(hqlzY2hlbWFfaWTZJGdhbWVjdWx0Lm1vZGVsLnRyYW5zcG9ydF9lbnZlbG9wZS52NbFjYWxsZXJfcnVudGltZV9pZK1nb2xkZW4tY2FsbGVyqnJlcXVlc3RfaWSuZ29sZGVuLXJlcXVlc3SsbWVzc2FnZV9raW5kqkludm9jYXRpb26lbm9uY2WczNNEzMAUzNnM6R7Mw8zLK2tVqmNpcGhlcnRleHTFAzP67vXYXmqhOshO0nXptUYY6bqoOX7fFNdJG9gOey20X58xRSDMpPUj6wDLIHrOnyl7ovYk+mGl42cVc9UO9q54Q84Oln6PKq+nueHuMzohIWG57u90UjYbVYeV+wYW/kcRXKupLFey43YDRPMf6PjBJ8JCZDj5Y4OACwy30jlb/JIzQlasR+QMfvP0CzE8DmO8WK6QPuSAxhWmlUpWelKjGcaVn5cb1vqNBA6sYfnUFwa2UweMFJcVhR2Sln3CRP/dG7vOTZFenrx2yHm3OVxOdi65cU5YgLlv1j6WtbOKNrHo05VNPITVBSIMlKTGM0Z+NM3HYt7wf+y2KWFvXcxmKojEoLeoyZG1PJIzmIL0isG/Y/UO8QTleKv/THoUyToHNRjoP7s7WxTvfndBHHvvuVcJjVDO8yJeiDAwB6Xqr19ZfyuDBLus9OwAoyzNaQhSDLi1z1d8Vb1ziyqvonV1yEjgLBOFUhmpvH5okNgUfaNxvMarOfdtidlkI7qxEt/xbGk2k5YVEricOmJFr5k5Etk4hKxlsL6yNBnDClUVoDv/FXhz2fc1El1UG0qUMLtPJgz9J81zc5EiTBGzkxTHAYQpDkZyWknMM02sfOyrDbIQp66MCT5kzsoRwuaQ5BkZJ1mnZsqk+3/kRTkouoz7huLTwCrlgIT0hNDtVSLxKzkJGJb4xqueNWVN2oD/Hko7tiGGYecgjkVo+mwMim6SJK2j9dxnTauMtRl1aqU46SRWOD88Kdi164v6VVD0TaW08pYaSTa1Jse4T9m4SahVsadiYIA3uMyP36ZkUUvq0czUep+8vGDiwNspvFDd5EvkgwyZ3GYUmwk62IQ5FOTTXKoTFwojQOxq66rnGC9084Kmv2RTCiZM3lIPU03q+U/qr67wIdnLSieMGtDYTOkNaCHOws5vFDVdCrDElmoTnMIx565GdU02tOzR9N2tumd1XOdtuEKJl+Y3FwkY74y8vRyCRoehKymN8kjc9+Jn1tXM9Z7OdWFa1xCJzJh37la8zz/Am4MBvgfSedNd34bVVdVgCBYwprsDc+eX1Ygx2OWBSV1RlpyznlnKDaU+Op5le2Q=ッpayloadEncodingイmessagepack-base64ュpayloadSchemaル$gamecult.model.transport_envelope.v5ュschemaVersionシcultnet.operation_request.v0ゥserviceIdクgamecult.model.connector

View file

@ -1 +1 @@
„©schema_idÙ"gamecult.model.transport_result.v3ªrequest_id®golden-request±caller_runtime_id­golden-caller«disposition<6F>§Refused«OutputBound „©schema_idÙ"gamecult.model.transport_result.v5ªrequest_id®golden-request±caller_runtime_id­golden-caller«disposition<6F>§Refused«OutputBound

View file

@ -1,4 +1,4 @@
//! `schemas/` at the repository root publishes one JSON Schema per v3 document, //! `schemas/` at the repository root publishes one JSON Schema per v5 document,
//! generated from the types. This test regenerates them and fails on any //! generated from the types. This test regenerates them and fails on any
//! difference; run it with `MODEL_CONNECTOR_REGENERATE_SCHEMAS=1` to rewrite the //! difference; run it with `MODEL_CONNECTOR_REGENERATE_SCHEMAS=1` to rewrite the
//! files from the types. //! files from the types.
@ -28,6 +28,7 @@ fn published_schemas_are_the_types() {
("transport_result", render::<TransportResult>()), ("transport_result", render::<TransportResult>()),
("transport_receipt", render::<TransportReceipt>()), ("transport_receipt", render::<TransportReceipt>()),
("transport_envelope", render::<TransportEnvelope>()), ("transport_envelope", render::<TransportEnvelope>()),
("usage_readout", render::<UsageReadout>()),
]; ];
let dir = schemas_dir(); let dir = schemas_dir();
if std::env::var_os(REGENERATE).is_some() { if std::env::var_os(REGENERATE).is_some() {
@ -53,7 +54,7 @@ fn published_schemas_are_the_types() {
expected.sort(); expected.sort();
assert_eq!( assert_eq!(
on_disk, expected, on_disk, expected,
"schemas/ holds exactly the five documents" "schemas/ holds exactly the six documents"
); );
} }
@ -63,6 +64,13 @@ fn a_published_schema_refuses_an_unknown_field() {
assert_eq!(schema["additionalProperties"], serde_json::json!(false)); assert_eq!(schema["additionalProperties"], serde_json::json!(false));
let required = schema["required"].as_array().unwrap(); let required = schema["required"].as_array().unwrap();
assert!(required.contains(&serde_json::json!("max_output_tokens"))); assert!(required.contains(&serde_json::json!("max_output_tokens")));
let receipt = serde_json::to_value(schema_for!(TransportReceipt)).unwrap();
assert!(receipt["properties"].get("cost_micro_usd").is_some());
let readout = serde_json::to_value(schema_for!(UsageReadout)).unwrap();
assert!(readout["properties"].get("spend").is_some());
assert!(readout["$defs"].get("CallerModelSpend").is_some());
} }
/// The schema and the wire agree on the ciphertext: the schema says binary, not /// The schema and the wire agree on the ciphertext: the schema says binary, not
@ -79,7 +87,7 @@ fn the_published_ciphertext_is_what_the_wire_sends() {
assert_eq!(&published["properties"]["ciphertext"], ciphertext); assert_eq!(&published["properties"]["ciphertext"], ciphertext);
let envelope = TransportEnvelope { let envelope = TransportEnvelope {
schema_id: "gamecult.model.transport_envelope.v3".to_string(), schema_id: "gamecult.model.transport_envelope.v5".to_string(),
caller_runtime_id: "caller".to_string(), caller_runtime_id: "caller".to_string(),
request_id: "request".to_string(), request_id: "request".to_string(),
message_kind: EnvelopeKind::Invocation, message_kind: EnvelopeKind::Invocation,
@ -110,6 +118,7 @@ fn the_refusal_schema_is_one_flat_string_enum() {
.iter() .iter()
.map(|value| value.as_str().unwrap()) .map(|value| value.as_str().unwrap())
.collect(); .collect();
assert_eq!(variants.len(), 12); assert_eq!(variants.len(), 13);
assert!(variants.contains(&"ForeignReasoningState")); assert!(variants.contains(&"ForeignReasoningState"));
assert!(variants.contains(&"ProviderRejected"));
} }

View file

@ -38,12 +38,8 @@ impl RecordingBackend {
} }
impl ProviderBackend for RecordingBackend { impl ProviderBackend for RecordingBackend {
fn ready(&self) -> bool { fn ready(&self) -> Result<(), &'static str> {
true Ok(())
}
fn provider(&self) -> &str {
PROVIDER
} }
fn execute(&self, call: &ProviderCall) -> TransportResult { fn execute(&self, call: &ProviderCall) -> TransportResult {
@ -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()
} }
@ -275,12 +273,8 @@ struct TamperingBackend {
} }
impl ProviderBackend for TamperingBackend { impl ProviderBackend for TamperingBackend {
fn ready(&self) -> bool { fn ready(&self) -> Result<(), &'static str> {
true Ok(())
}
fn provider(&self) -> &str {
PROVIDER
} }
fn execute(&self, call: &ProviderCall) -> TransportResult { fn execute(&self, call: &ProviderCall) -> TransportResult {
@ -313,9 +307,11 @@ impl ProviderBackend for TamperingBackend {
#[test] #[test]
fn a_refused_completion_reaches_the_caller_as_a_typed_failure_and_frees_the_slot() { fn a_refused_completion_reaches_the_caller_as_a_typed_failure_and_frees_the_slot() {
let edits: [fn(&mut TransportReceipt); 2] = [ let edits: [fn(&mut TransportReceipt); 4] = [
|receipt| receipt.provider = "another-provider".to_string(), |receipt| receipt.provider = "another-provider".to_string(),
|receipt| receipt.foreign_reasoning_dropped += 1, |receipt| receipt.foreign_reasoning_dropped += 1,
|receipt| receipt.request_id = "another-request".to_string(),
|receipt| receipt.cost_micro_usd = Some(999),
]; ];
for edit in edits { for edit in edits {
// One concurrent request: a wedged slot would refuse the next id. // One concurrent request: a wedged slot would refuse the next id.

View file

@ -1,5 +1,5 @@
//! Pins the bytes of the v3 wire so a drift is a failing test. The fixtures in //! Pins the bytes of the v5 wire so a drift is a failing test. The fixtures in
//! `fixtures/wire_v3` are produced by this file (see its README); they pin the //! `fixtures/wire_v5` are produced by this file (see its README); they pin the
//! kit against itself and are not a second contract: the types in //! kit against itself and are not a second contract: the types in
//! `model_connector::contract` own the shape. //! `model_connector::contract` own the shape.
@ -17,10 +17,10 @@ use serde::de::DeserializeOwned;
const KEY: &str = "golden-distinct-test-key"; const KEY: &str = "golden-distinct-test-key";
const CALLER: &str = "golden-caller"; const CALLER: &str = "golden-caller";
const REGENERATE: &str = "WIRE_V3_REGENERATE"; const REGENERATE: &str = "WIRE_V5_REGENERATE";
fn fixtures() -> PathBuf { fn fixtures() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/wire_v3") Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/wire_v5")
} }
fn named<T: Serialize>(value: &T) -> Vec<u8> { fn named<T: Serialize>(value: &T) -> Vec<u8> {
@ -28,7 +28,7 @@ fn named<T: Serialize>(value: &T) -> Vec<u8> {
} }
/// The value serializes to the committed bytes and the committed bytes decode /// The value serializes to the committed bytes and the committed bytes decode
/// back to it. With `WIRE_V3_REGENERATE` set, the committed bytes are rewritten /// back to it. With `WIRE_V5_REGENERATE` set, the committed bytes are rewritten
/// from the value first. /// from the value first.
fn assert_wire<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>( fn assert_wire<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(
name: &str, name: &str,
@ -84,7 +84,7 @@ fn invocation() -> TransportInvocation {
TransportInvocation::new(CALLER, 1_800_000_000_000, [7; 32], request()).unwrap() TransportInvocation::new(CALLER, 1_800_000_000_000, [7; 32], request()).unwrap()
} }
fn receipt(outcome: TransportOutcome) -> TransportReceipt { fn receipt(cost_micro_usd: Option<u64>, outcome: TransportOutcome) -> TransportReceipt {
let invocation = invocation(); let invocation = invocation();
TransportReceipt { TransportReceipt {
schema_id: RECEIPT_SCHEMA_ID.to_string(), schema_id: RECEIPT_SCHEMA_ID.to_string(),
@ -95,6 +95,7 @@ fn receipt(outcome: TransportOutcome) -> TransportReceipt {
model: invocation.request.model.clone(), model: invocation.request.model.clone(),
provider: "anthropic-messages".to_string(), provider: "anthropic-messages".to_string(),
foreign_reasoning_dropped: 2, foreign_reasoning_dropped: 2,
cost_micro_usd,
outcome, outcome,
} }
} }
@ -113,8 +114,17 @@ fn completed() -> TransportOutcome {
} }
} }
fn input_reasoning_state() -> InputItem {
let reasoning = (0x80..=0xff_u8).collect::<Vec<u8>>();
InputItem::ReasoningState {
provider: "anthropic-messages".to_string(),
model: "claude-opus-4-5".to_string(),
state: reasoning,
}
}
#[test] #[test]
fn wire_golden_v3() { fn wire_golden_v5() {
let invocation = invocation(); let invocation = invocation();
assert_wire("provider_request.mp", &invocation.request); assert_wire("provider_request.mp", &invocation.request);
assert_wire("transport_invocation.mp", &invocation); assert_wire("transport_invocation.mp", &invocation);
@ -122,14 +132,7 @@ fn wire_golden_v3() {
// The reasoning bytes are all >= 0x80 so a byte-array encoding cannot pass // The reasoning bytes are all >= 0x80 so a byte-array encoding cannot pass
// for MessagePack bin. // for MessagePack bin.
let reasoning = || (0x80..=0xff_u8).collect::<Vec<u8>>(); let reasoning = || (0x80..=0xff_u8).collect::<Vec<u8>>();
assert_wire( assert_wire("input_reasoning_state.mp", &input_reasoning_state());
"input_reasoning_state.mp",
&InputItem::ReasoningState {
provider: "anthropic-messages".to_string(),
model: "claude-opus-4-5".to_string(),
state: reasoning(),
},
);
let transported = TransportResult { let transported = TransportResult {
schema_id: RESULT_SCHEMA_ID.to_string(), schema_id: RESULT_SCHEMA_ID.to_string(),
@ -156,7 +159,7 @@ fn wire_golden_v3() {
}, },
}, },
], ],
receipt: Box::new(receipt(completed())), receipt: Box::new(receipt(Some(1_420), completed())),
}, },
}; };
assert_eq!(transported.validate_against(&invocation), Ok(())); assert_eq!(transported.validate_against(&invocation), Ok(()));
@ -165,12 +168,36 @@ fn wire_golden_v3() {
let refused = TransportResult::refused(&invocation, Refusal::OutputBound); let refused = TransportResult::refused(&invocation, Refusal::OutputBound);
assert_wire("transport_result_refused.mp", &refused); assert_wire("transport_result_refused.mp", &refused);
let failed = receipt(TransportOutcome::Failed { let failed_with_usage = receipt(
kind: FailureKind::RateLimited, Some(0),
message: "provider asked to slow down".to_string(), TransportOutcome::Failed {
}); kind: FailureKind::RateLimited,
assert_eq!(failed.validate_against(&invocation), Ok(())); message: "provider asked to slow down".to_string(),
assert_wire("transport_receipt_failed.mp", &failed); usage: Some(Usage {
input_tokens: 120,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 0,
reasoning_tokens: None,
}),
},
);
assert_eq!(failed_with_usage.validate_against(&invocation), Ok(()));
assert_wire("transport_receipt_failed.mp", &failed_with_usage);
let failed_without_usage = receipt(
None,
TransportOutcome::Failed {
kind: FailureKind::Unavailable,
message: "provider unavailable".to_string(),
usage: None,
},
);
assert_eq!(failed_without_usage.validate_against(&invocation), Ok(()));
assert_wire(
"transport_receipt_failed_no_usage.mp",
&failed_without_usage,
);
let envelope = TransportEnvelope { let envelope = TransportEnvelope {
schema_id: ENVELOPE_SCHEMA_ID.to_string(), schema_id: ENVELOPE_SCHEMA_ID.to_string(),
@ -224,7 +251,7 @@ fn the_golden_carriage_frame_decrypts_and_validates_under_the_fixed_key() {
}; };
assert_eq!(service_id, "gamecult.model.connector"); assert_eq!(service_id, "gamecult.model.connector");
assert_eq!(operation, "invoke"); assert_eq!(operation, "invoke");
assert_eq!(payload_schema, "gamecult.model.transport_envelope.v3"); assert_eq!(payload_schema, "gamecult.model.transport_envelope.v5");
assert_eq!(message_id, invocation.request_id()); assert_eq!(message_id, invocation.request_id());
let envelope: TransportEnvelope = let envelope: TransportEnvelope =
rmp_serde::from_slice(&STANDARD.decode(payload).unwrap()).unwrap(); rmp_serde::from_slice(&STANDARD.decode(payload).unwrap()).unwrap();
@ -238,6 +265,7 @@ fn the_golden_carriage_frame_decrypts_and_validates_under_the_fixed_key() {
/// as an array of integers. /// as an array of integers.
#[test] #[test]
fn reasoning_state_is_messagepack_bin() { fn reasoning_state_is_messagepack_bin() {
assert_wire("input_reasoning_state.mp", &input_reasoning_state());
let golden = std::fs::read(fixtures().join("input_reasoning_state.mp")).unwrap(); let golden = std::fs::read(fixtures().join("input_reasoning_state.mp")).unwrap();
let marker = golden.windows(3).any(|window| window == [0xc4, 0x80, 0x80]); let marker = golden.windows(3).any(|window| window == [0xc4, 0x80, 0x80]);
assert!(marker, "state must be a bin 8 of 128 bytes starting 0x80"); assert!(marker, "state must be a bin 8 of 128 bytes starting 0x80");

View file

@ -46,7 +46,9 @@
"type": "string", "type": "string",
"enum": [ "enum": [
"Invocation", "Invocation",
"Result" "Result",
"UsageReadoutRequest",
"UsageReadoutResult"
] ]
} }
} }

View file

@ -6,6 +6,14 @@
"caller_runtime_id": { "caller_runtime_id": {
"type": "string" "type": "string"
}, },
"cost_micro_usd": {
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 0
},
"foreign_reasoning_dropped": { "foreign_reasoning_dropped": {
"description": "How many foreign `ReasoningState` items the service removed from the\nrequest before the backend saw it.", "description": "How many foreign `ReasoningState` items the service removed from the\nrequest before the backend saw it.",
"type": "integer", "type": "integer",
@ -132,6 +140,17 @@
}, },
"message": { "message": {
"type": "string" "type": "string"
},
"usage": {
"description": "What the provider billed for the failed request: `Some` when it\nreported usage (`Some` of zeros when it billed nothing), `None`\nwhen unknown.",
"anyOf": [
{
"$ref": "#/$defs/Usage"
},
{
"type": "null"
}
]
} }
}, },
"additionalProperties": false, "additionalProperties": false,
@ -149,7 +168,7 @@
] ]
}, },
"Usage": { "Usage": {
"description": "Token accounting for one completed request. Cache reads and writes are\ncounted apart from plain input; `reasoning_tokens` is absent when the\nprovider does not report it.", "description": "Token accounting for one request, as the backend reports it. Cache reads\nand writes are counted apart from plain input.\n`output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail\n(absent when the provider does not report it) and is never counted apart.",
"type": "object", "type": "object",
"properties": { "properties": {
"cache_read_tokens": { "cache_read_tokens": {

View file

@ -51,7 +51,8 @@
"Indeterminate", "Indeterminate",
"ReplayConflict", "ReplayConflict",
"Malformed", "Malformed",
"ForeignReasoningState" "ForeignReasoningState",
"ProviderRejected"
] ]
}, },
"StopReason": { "StopReason": {
@ -250,6 +251,17 @@
}, },
"message": { "message": {
"type": "string" "type": "string"
},
"usage": {
"description": "What the provider billed for the failed request: `Some` when it\nreported usage (`Some` of zeros when it billed nothing), `None`\nwhen unknown.",
"anyOf": [
{
"$ref": "#/$defs/Usage"
},
{
"type": "null"
}
]
} }
}, },
"additionalProperties": false, "additionalProperties": false,
@ -272,6 +284,14 @@
"caller_runtime_id": { "caller_runtime_id": {
"type": "string" "type": "string"
}, },
"cost_micro_usd": {
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 0
},
"foreign_reasoning_dropped": { "foreign_reasoning_dropped": {
"description": "How many foreign `ReasoningState` items the service removed from the\nrequest before the backend saw it.", "description": "How many foreign `ReasoningState` items the service removed from the\nrequest before the backend saw it.",
"type": "integer", "type": "integer",
@ -330,7 +350,7 @@
] ]
}, },
"Usage": { "Usage": {
"description": "Token accounting for one completed request. Cache reads and writes are\ncounted apart from plain input; `reasoning_tokens` is absent when the\nprovider does not report it.", "description": "Token accounting for one request, as the backend reports it. Cache reads\nand writes are counted apart from plain input.\n`output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail\n(absent when the provider does not report it) and is never counted apart.",
"type": "object", "type": "object",
"properties": { "properties": {
"cache_read_tokens": { "cache_read_tokens": {

114
schemas/usage_readout.json Normal file
View file

@ -0,0 +1,114 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UsageReadout",
"type": "object",
"properties": {
"at_unix_ms": {
"type": "integer",
"format": "uint64",
"minimum": 0
},
"plan_quota": {
"type": "array",
"items": {
"$ref": "#/$defs/PlanQuota"
}
},
"schema_id": {
"type": "string"
},
"spend": {
"type": "array",
"items": {
"$ref": "#/$defs/CallerModelSpend"
}
}
},
"additionalProperties": false,
"required": [
"schema_id",
"at_unix_ms",
"spend",
"plan_quota"
],
"$defs": {
"CallerModelSpend": {
"description": "One caller's committed monthly usage row for a single model in UTC `YYYY-MM`.",
"type": "object",
"properties": {
"caller": {
"type": "string"
},
"calls": {
"type": "integer",
"format": "uint64",
"minimum": 0
},
"calls_without_price": {
"type": "integer",
"format": "uint64",
"minimum": 0
},
"cost_micro_usd": {
"type": "integer",
"format": "uint64",
"minimum": 0
},
"model": {
"type": "string"
},
"month": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"caller",
"model",
"month",
"calls",
"cost_micro_usd",
"calls_without_price"
]
},
"PlanQuota": {
"description": "One window of the subscription plan, as the provider reported it.",
"type": "object",
"properties": {
"observed_at_unix_ms": {
"description": "When this window was last reported. Its age in a readout is the\nreadout's `at_unix_ms` minus this.",
"type": "integer",
"format": "uint64",
"minimum": 0
},
"resets_at_unix_ms": {
"type": "integer",
"format": "uint64",
"minimum": 0
},
"status": {
"type": "string"
},
"utilization_permille": {
"description": "How much of the window was used when it was observed, in thousandths;\n`None` once the window has reset (`status` is then `expired`), because\nthe old reading says nothing about the new window.",
"type": [
"integer",
"null"
],
"format": "uint32",
"minimum": 0
},
"window": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"window",
"resets_at_unix_ms",
"status",
"observed_at_unix_ms"
]
}
}
}