rusty_agent_server/lib.rs
1//! # rusty-agent-server
2//!
3//! The network face of [`rusty_agent_runtime`]: an axum-based HTTP + SSE server
4//! implementing a pragmatic Agent-Protocol subset (see
5//! `docs/rusty-server-design.md`). The server ships as a **library** —
6//! users build their graphs, register them in a [`GraphRegistry`], and call
7//! [`serve`] (or [`router`] to embed the routes in a larger application):
8//!
9//! ```no_run
10//! use rusty_agent_runtime::prelude::*;
11//! use rusty_agent_server::{serve, GraphRegistry, ServerConfig};
12//!
13//! # async fn demo(graph: Graph, spec: StateSpec) -> std::io::Result<()> {
14//! let mut registry = GraphRegistry::new();
15//! registry.register("my_agent", graph, spec);
16//!
17//! let config = ServerConfig::new(
18//! "127.0.0.1:8080".parse().unwrap(),
19//! "./data/checkpoints",
20//! );
21//! serve(registry, config).await
22//! # }
23//! ```
24//!
25//! ## Endpoint inventory (v0.5)
26//!
27//! | Endpoint | Purpose |
28//! |---|---|
29//! | `GET /ok` | liveness |
30//! | `GET /info` | service version + registered graphs and their channels |
31//! | `POST /threads` | create a thread bound to a registered graph |
32//! | `POST /threads/{id}/fork` | time travel: copy the thread's checkpoint history (full or up to `checkpoint_id`) into a new thread |
33//! | `GET /threads/{id}/state` | latest checkpoint as `{values, next, checkpoint}` (the checkpoint ref carries its pinned `policy_version`, R0.8 wave 4) |
34//! | `POST /threads/{id}/state` | write a new checkpoint (`update_state` analog; `as_node` is accepted for LangGraph compatibility but not recorded; optional `enqueue: [...]` submits tasks atomically with the checkpoint through the R0.6 wave-2b transactional outbox — one transaction on Postgres, outbox-first best-effort ordering on the JSON-file backend) |
35//! | `POST /threads/{id}/history` | checkpoint list, newest first, `limit`/`before` |
36//! | `POST /threads/{id}/runs` | background run: `202 + run_id` |
37//! | `POST /threads/{id}/runs/wait` | blocking run: terminal result as JSON |
38//! | `POST /threads/{id}/runs/stream` | run with SSE streaming (`updates`/`values`/`messages`/`metadata`/`error`/`end`); a fresh run starts a new frame sequence, so `Last-Event-ID` is ignored here |
39//! | `GET /runs/{id}/stream` | attach to an existing run's SSE stream: replay honoring `Last-Event-ID`, then live frames |
40//! | `GET /runs/{id}/events` | Flight Recorder: the run's journaled `RunEvent`s as `{run_id, events, complete}` (snapshot flushed per checkpoint boundary and at run completion; persisted under `{store_path}/journals/` or the `server_journals` table; fetchable by run id even after the live run record is evicted or the process restarts) |
41//! | `GET /runs/{id}/fixture` | Flight Recorder: download the run as a portable `ReplayFixture` bundle (journal + graph topology hash + final checkpoint) for CI replay |
42//! | `POST /runs/replay` | Flight Recorder: re-drive a journaled run against its registered graph and verify the replayed evidence → `{run_id, verified, expected_events, actual_events, first_divergence}` (`422` when the graph is not registered in this process or the journal carries recorded effect calls) |
43//! | `GET /runs/diff?base=&branch=` | Flight Recorder: structural diff of two runs' journals (core's `BranchDiff` shape: `first_divergent_seq`, `added`/`removed` events, per-step channel diffs, token/cost totals) |
44//! | `DELETE /threads/{id}/runs/{run_id}` | rollback: delete a finished run's checkpoints (JSON-file checkpointer only; `409` on Postgres) |
45//! | `GET /runs/{run_id}` | run status polling (plus `output`/`error`/`interrupt` once terminal) |
46//! | `POST /assistants` | create a named graph alias with config metadata |
47//! | `GET /assistants` / `GET /assistants/{id}` | list / fetch assistants |
48//! | `POST /assistants/{id}/archive` / `POST /assistants/{id}/restore` | reversibly retire or return an assistant using an expected-active-version guard; archived assistants retain their immutable lineage and history but reject new runs |
49//! | `GET /assistants/{id}/versions` | list the bounded immutable configuration lineage and active serving pointer |
50//! | `POST /assistants/{id}/versions` | stage an immutable child version against the exact active base (never activates it) |
51//! | `GET /assistants/{id}/versions/{version_id}` | fetch one exact immutable configuration version for review |
52//! | `POST /assistants/{id}/versions/{version_id}/activate` | atomically activate or roll back to a reviewed version using an expected-active guard |
53//! | `POST /crons` | schedule recurring runs (interval secs or 5-field cron expr) |
54//! | `GET /crons` / `DELETE /crons/{id}` | list / delete crons |
55//! | `POST /triggers` | create an event-driven trigger: name, target (assistant or thread), action (`start_run` / `resume_thread` / `send_message`), `{{event.*}}` input template, per-trigger webhook secret, optional debounce window |
56//! | `GET /triggers` / `GET /triggers/{id}` / `PATCH /triggers/{id}` / `DELETE /triggers/{id}` | trigger registry (tenant-scoped) |
57//! | `POST /triggers/{id}/webhook` | signed event ingress: HMAC-SHA256 over the raw body, `X-Rusty-Signature: sha256=<hex>`, constant-time compare; `401` unsigned/invalid. Not behind the API-key layer — the signature is the credential and resolves the owning tenant |
58//! | `GET /triggers/{id}/events` | the trigger's event log (payload hash, action, run id, status), newest first |
59//! | `GET /triggers/{id}/dead-letter` | failed events, inspectable and replayable |
60//! | `POST /triggers/{id}/events/{event_id}/replay` | re-execute a logged event immediately (the replay is itself logged) |
61//! | `PUT /store/{ns}/{key}` | upsert a JSON value in a namespace (`201` create, `200` replace) |
62//! | `GET /store/{ns}/{key}` / `DELETE /store/{ns}/{key}` | fetch / delete one item |
63//! | `GET /store/{ns}` | list a namespace's items |
64//! | `POST /tasks` | R0.6 durable task queue: enqueue a task `{kind, payload, pool?, max_attempts?, idempotency_key?, worker_version?}` → `201 {task_id, deduplicated}` (`200` + `deduplicated: true` when the idempotency key already names a live task in this tenant; `429 quota_exceeded` when the tenant is over its wave-3 task quota — see `ServerConfig::with_task_quota`) |
65//! | `POST /tasks/outbox` | R0.6 wave 2b: enqueue through the transactional outbox (same payload as `POST /tasks`, same quota gate) → `202 {task_id, deduplicated}`; the relay publishes the task into the queue within one poll interval, at-least-once, deduped on the idempotency key |
66//! | `POST /tasks/claim` | R0.6: claim the oldest claimable task `{worker_id, pools?, worker_version?, lease_ms}` → `200 {task}` with a fresh lease, `204` when nothing is claimable. Wave 3: pools at their configured concurrency limit (`ServerConfig::with_pool_limit`) hand out nothing, and a task pinned with `worker_version` is leased only to a worker advertising that exact version |
67//! | `GET /tasks/metrics` | R0.6 wave 3: the autoscaling signals, tenant-scoped — per-pool queue depth, live leases, lease saturation against the configured limit, and oldest-visible-task age. Metrics, not a mechanism: the autoscaler is the operator's |
68//! | `POST /tasks/{id}/heartbeat` | R0.6: extend the held lease `{worker_id, lease_ms}` → `{lease_expires_at}`; `409` when the lease is lost |
69//! | `POST /tasks/{id}/complete` | R0.6: settle the held lease `{worker_id, result, receipt?}` → updated task record; `409` when the lease is lost. The optional `receipt` (wave 2b: `{provider, provider_id, idempotency_key, task_id?}`) is the worker's report of an idempotent effect's provider confirmation; the server journals it into the task's run as an `effect_receipt` event |
70//! | `POST /tasks/{id}/fail` | R0.6: record a failed attempt `{worker_id, error_class, message, retryable}` → `{requeued, next_attempt_at, dead, escalation}` (backoff + jitter requeue, or dead-letter); `409` when the lease is lost. R0.7 wave 2: a failed agent turn (non-`cancelled`) also feeds the agent's supervision policy — `escalation` reports where the escalation notice landed when the restart intensity was exceeded |
71//! | `GET /tasks/{id}` | R0.6: the task record (404 unknown/cross-tenant) |
72//! | `GET /tasks?status=…` | R0.6: the tenant's tasks, oldest first; `status=dead` is the DLQ listing |
73//! | `POST /agents` | R0.7 Agent Fabric (wave 1): register an agent `{agent_id, manifest, metadata?}` — the manifest is a core `CapabilityManifest` (`agent_kind`, `manifest_version`, `accepts`, …) → `201`; `409` when the id is taken |
74//! | `GET /agents` / `GET /agents/{id}` | R0.7: list the tenant's agents / fetch one registration (404 unknown/cross-tenant) |
75//! | `POST /agents/{id}/mailbox` | R0.7: send a message into the agent's mailbox `{kind, payload, idempotency_key?, …}` → `201 {task_id, deduplicated}` (`200` when the key already names a live message); `400` when the manifest's `accepts` does not declare the kind; same quota gate as `POST /tasks` |
76//! | `GET /agents/{id}/status` | R0.7: the agent's activation lease plus mailbox gauges (`queued` / `in_flight` / `dead` message counts) |
77//! | `POST /agents/{id}/activate` | R0.7: claim the agent's single activation lease `{worker_id, lease_ms}` → `200 {owner, fencing, lease_expires_at}`; `409` + the current lease when another host holds it live (expired leases are stolen, fencing bumped) |
78//! | `POST /agents/{id}/activate/heartbeat` | R0.7: renew the held activation `{worker_id, fencing, lease_ms}`; `409` on fencing loss |
79//! | `POST /agents/{id}/activate/release` | R0.7: drop the held activation `{worker_id, fencing}` so a draining host's replacement activates promptly; `409` on fencing loss |
80//! | `POST /agents/{id}/mailbox/next` | R0.7: claim the oldest queued mailbox message as one turn `{worker_id, fencing, lease_ms}` → `200 {task}` leased to the worker, `204` when empty or a turn is already in flight (one message at a time per agent is server-enforced), `409` when the activation lease is not held. The turn settles through the ordinary `/tasks/{id}/heartbeat|complete|fail` protocol |
81//! | `GET /agents/{id}/supervision` | R0.7 wave 2: the agent's supervision evidence — declared policy, latches, full attempt history, and the journaled `SupervisionEvent` / `AgentExit` events of its supervision journal (integrity re-verified on read) |
82//! | `POST /agents/{id}/cancel` | R0.7 wave 2: cancel the agent's outstanding mailbox traffic — queued/retry-scheduled messages go terminal-`cancelled`, the leased turn keeps its lease with `cancel_requested` set — and journal an `AgentExit`; idempotent (`200` with empty lists when nothing is outstanding) |
83//! | `POST /agents/{id}/restart` | R0.7 wave 2: the operator's manual restart — records a `manual_restart` supervision attempt, clears the escalation/deadline latches, and journals the event so the agent's next turn runs fresh |
84//! | `POST /teams/{team_id}/cancel` | R0.7 wave 2: cancel every agent registered with the `team_id` label, member by member with the agent-cancel semantics; `404` when no tenant agent declares the team |
85//! | `POST /memory` | R0.8 Rusty Learn (wave 1): write a governed memory record `{kind, scope, content, author, key?, tags?, priority?, confidence?, written_at?, valid_from?, valid_until?, expires_at?, supersedes?, evidence?, run_id?, parent?}` → `201 {memory_id, created, record}` (`200` + `created: false` when the content address is already stored — writes are idempotent by construction). Gates: `run` scope is runtime-only (`400`); `agent` scope requires the agent registered with `StateScope::Private` declared (`404` / `403`); `tenant` scope id must be the caller's tenant (`403`); confidence defaults to `1.0` for human authors and is required otherwise (`400`). With `run_id`, the write is journaled into that run as a `memory_write` event (best-effort) |
86//! | `GET /memory/{memory_id}` | R0.8: fetch one record by content address (`404` unknown/cross-tenant); artifact-spilled bodies are re-inlined, so the served record is self-contained |
87//! | `POST /memory/query` | R0.8: structured retrieval — the `MemoryQuery` filters plus optional `budget`, `run_id`, `parent`. `as_of` resolves at read time. With `budget`, answers the deterministic token-bounded `MemoryAssembly` (`422` when a hard budget overflows); without, the rank-ordered records. With `run_id` (budget required), the read is journaled into that run as a `memory_read` event (best-effort) |
88//! | `POST /memory/corrections` | R0.8 (wave 2): submit a human correction `{correction_id, author, target, corrected, scope, rationale?, run_id?, parent?}` → `201 {correction_id, attribution, candidate, memory_id, created, record, superseded, example_id}`. Author attribution is mandatory (validated at deserialization). Run scope adopts directly; agent scope or wider yields an attributed candidate (`candidacy: pending`, queryable via `candidates_only`). A `run_event` target additionally yields an `example`-kind record — the journaled input plus the corrected behavior — journaled into the corrected run through the memory-write seam; a `memory` target inherits the target's key, and same-key correction writes auto-supersede the prior record |
89//! | `POST /memory/consolidate` | R0.8 (wave 2): enqueue a consolidation as a durable `memory_consolidation` task `{scope, memory_ids, distiller, key?, tags?, priority?, pool?, run_id?, parent?}` → `201 {task_id, deduplicated, kind}` (deduped on scope + sorted source set). The claiming worker owns the distillation semantics and writes the `summary` record through the governed write path with the sources in `evidence.source_memory_ids` (which supersedes them) and the task payload's `written_at`; the task settles through the unchanged lease protocol |
90//! | `POST /memory/conflicts` | R0.8 (wave 2): the conflict review listing `{scope?}` → `{conflicts: [{scope, key, memory_ids, overlap}]}` — live same-key records with overlapping validity and contradictory content. Flags only; nothing is resolved |
91//! | `POST /memory/forget` | R0.8 (wave 2): erase one record `{memory_id, reason, run_id?, parent?}` → `200 {forgotten, invalidated, tombstone}`. Real deletion; dependent summaries are invalidated (deleted) transitively; a metadata-only `memory_forget` tombstone is journaled into the named run (best-effort) |
92//! | `POST /memory/forget_scope` | R0.8 (wave 2): erase every record at a scope address `{scope, reason, run_id?, parent?}` → `200 {forgotten, invalidated, tombstones}` — one tombstone per forgotten record; idempotent (empty scope → `200` with empty lists); tenant scope is self-only (`403`) |
93//! | `POST /learn/candidates` | R0.8 (wave 3): register a distilled candidate `{candidate, run_id, parent?}` → `201 {candidate_id, created, record}` (`200` + `created: false` when the content address is already stored — creation converges). The address is verified (`422`); the `candidate_created` event is journaled into `run_id`'s journal before the store write — hard-fail: an unresolvable run stops the transition (`404`) |
94//! | `GET /learn/candidates` / `GET /learn/candidates/{id}` | R0.8 (wave 3): the tenant's candidates (sorted by id) / fetch one record (`404` unknown/cross-tenant) |
95//! | `POST /learn/candidates/{id}/evaluate` | R0.8 (wave 3): drive the configured `CandidateEvaluator` `{request, run_id, parent?}` → `200 {candidate_id, status, evaluation}`; `409` when no evaluator is configured or the lifecycle forbids re-evaluation; `422` when the evaluation fails or violates the seam contract (it must name this candidate and the request's dataset version) |
96//! | `POST /learn/candidates/{id}/promote` | R0.8 (wave 3): run the promotion gate `{run_id, approval?, parent?}` → `200 {candidate_id, status, receipt, pointer}`. `403` on approval failures (out-of-envelope promotion needs an `ApprovalToken` scoped to the candidate's promotion effect id — non-transferable), `422` on evidence failures, `409` when the candidate is not `evaluated`. The status flip and the version-pointer move are one store transition |
97//! | `POST /learn/candidates/{id}/rollback` | R0.8 (wave 3): re-point the surface to the displaced version `{run_id, cause, parent?}` → `200 {candidate_id, status, receipt, pointer}`; `409` when the candidate is not `promoted` or the pointer no longer serves it. Byte-exact: the pointer's `to` is the promotion's recorded `previous`, and candidates are content-addressed — the restored version is the version that served |
98//! | `GET /learn/versions` | R0.8 (wave 3): the tenant's version pointers, sorted by surface |
99//! | `POST /policy/versions` | R0.8 (wave 4): register an immutable executor policy body `{version?, policy}` → `201 {version, record}` (`200` converged when the version already names exactly this body; `409` when it names a different one — registry immutability; `400` invalid version). Without `version`, the content-derived `policy-{hash12}` name is minted. The reserved `static-v0` floor is never registerable |
100//! | `GET /policy/versions` / `GET /policy/versions/{version}` | R0.8 (wave 4): the tenant's registered policy bodies (sorted by version) / fetch one (`404` unknown/cross-tenant; the floor resolves as a synthetic record) |
101//! | `POST /policy/activations` | R0.8 (wave 4): move the active-version pointer `{version}` → `200 {version, active}`; `422` when the version is not registered (the floor is always activatable — reverting to pre-learning behavior needs no candidate) |
102//! | `GET /policy/active` | R0.8 (wave 4): the tenant's active policy — the last activation's body, or the floor when the registry never moved |
103//! | `GET /policy/epochs` | R0.8 (wave 4): the epoch history — each activation's reign window plus the admission bindings recorded inside it (and the implicit floor epoch covering pre-activation bindings) |
104//! | `GET /policy/drift` | R0.10 (wave 4): the drift check — the named (default active) candidate-derived version's journaled production decisions measured against the twin baseline it was promoted on; `422` for the floor and API-registered bodies (no promotion baseline) |
105//! | `POST /capsules` | R0.9 Rusty Capsules (wave 1): register an immutable capsule manifest `{manifest}` → `201 {capsule_id, record}` (`200` converged when the content address already names exactly this manifest; `409` when the `(name, version)` pin is claimed by a different address — registry immutability; `422` when the manifest fails validation). The manifest's content address is derived; callers never mint ids |
106//! | `GET /capsules` / `GET /capsules/{id}` | R0.9 (wave 1): the tenant's registered capsule manifests (sorted by content address) / fetch one (`404` unknown/cross-tenant) |
107//! | `POST /capsules/resolve` | R0.9 (wave 1): resolve a run's capsule pins `{pins: {name: version}, run_id, parent?}` → `200 {resolutions}` — each pin's stored manifest re-derives its content address before answering (a tampered record fails closed, `422`; an unknown pin is `404`), and one `capsule_resolved` event per pin is journaled into `run_id`'s journal (hard-fail: an unresolvable run is `404`). R0.9 wave 2 adds the optional `budget` field and, with the `capsules` feature, the admission composition: Cedar decides the admission and each declared grant (`403` on refusal, one journaled `capsule_denied` per forbidden grant), overlays intersect the effective grants, and budgets compose (`422` on a token/cost overspend) |
108//! | `POST /capsule_policies/versions` / `GET /capsule_policies/versions` / `GET /capsule_policies/versions/{version}` | R0.9 (wave 2, feature `capsules`): register an immutable Cedar policy body `{policy_text, version?}` → `201 {version, record}` (`200` converged; `409` when the version names a different body; `422` unparseable) / list the tenant's bodies (sorted by version) / fetch one (`404` unknown/cross-tenant). Without the feature: `503 capsule_policy_unavailable` |
109//! | `GET /capsule_policies/active` / `POST /capsule_policies/active` | R0.9 (wave 2, feature `capsules`): the tenant's active policy body (`404` in the unconfigured posture) / move the active-version pointer `{version}` → `200 {active}` (`422` unregistered version); the move eagerly refreshes the revocation cache. Without the feature: `503 capsule_policy_unavailable` |
110//! | `POST /capsules/overlays` / `GET /capsules/overlays` / `GET /capsules/overlays/{name}` | R0.9 (wave 2, feature `capsules`): attach (or replace) a tenant overlay `{overlay}` → `201` new / `200` replaced (`403` when the active policy refuses a widening attach; `422` invalid) / list the tenant's overlays (sorted by name) / fetch one (`404` unknown/cross-tenant). Without the feature: `503 capsule_policy_unavailable` |
111//! | `GET /runs/{id}/receipt` | R0.9 (wave 3): the run's signed `RunReceipt` — minted on first request over the run's reverified journal (manifest and executor policy read back from its last checkpoint header), then stored and served while the journal's head stands; a run whose journal advanced gets a fresh receipt. `409` when nothing is persisted yet (queued or pre-checkpoint); `404` unknown/cross-tenant |
112//! | `POST /receipts/verify` | R0.9 (wave 3): verify caller-supplied evidence `{snapshot, receipt, key_id?}` → `200` with the typed `VerifiedRun` summary, or `422 receipt_verification_failed` naming the mismatched component (`journal_head` / `manifest_digest` / `effect_ledger` / `denials_ledger` / `capsule_resolutions` / `capsule_policies` / `signer_key_id` / `signature`). The public key resolves from the deployment's key history by `key_id` (default: the receipt's `signer`); an unknown key id is `404` |
113//! | `GET /receipt_keys` | R0.9 (wave 3): the deployment's signing-key history (public keys, registration and retirement instants) plus the active key id — what an auditor needs to verify receipts offline |
114//! | `POST /receipt_keys/rotate` | R0.9 (wave 3): rotate the signing key → `201 {previous_key_id, key_id, public_key, event_id}`; the new key id is journaled as a `signing_key_rotated` event in the deployment's receipts journal, and receipts signed by the retired key keep verifying against the history |
115//! | `GET /receipt_keys/journal` | R0.9 (wave 3): the deployment's key-lineage journal — the chained `signing_key_rotated` events, integrity re-verified on read |
116//! | `POST /mcp` | R0.9 (wave 4): the MCP bridge (pinned revision `2025-03-26`) — every registered graph as one tool. `initialize` / `ping` / `notifications/*` / `tools/list` (tool schemas derived from each graph's state spec: append channels are arrays, deep-merge channels objects) / `tools/call` (runs the graph on a fresh thread; plain-JSON answer, or SSE `notifications/progress` + the final response when the request accepts `text/event-stream`; a mid-stream disconnect cancels the run). JSON-RPC errors in the envelope with HTTP 200; notifications answer `202` |
117//! | `GET /.well-known/agent-card.json` | R0.9 (wave 4): the A2A agent card (pinned spec `0.3.0`), derived from the registry on every read — one skill per registered graph; deterministic, no timestamps |
118//! | `POST /a2a` | R0.9 (wave 4): the A2A JSON-RPC task surface — `message/send` (enqueue a durable task, `kind = "a2a"`, idempotent on `messageId`; a capsule data part `{"capsule": {name, version}, "input"}` routes to the in-process executor over the `a2a-capsule` pool, plain messages queue on `a2a` for external workers) / `message/stream` (the same plus SSE status events) / `tasks/get` / `tasks/cancel`. The context id maps to one Flight Recorder journal (`a2a-{tenant}-{contextId}`), so capsule executions leave their evidence on the native `/runs/{id}/events` and `/fixture` endpoints |
119//! | `PUT /capsules/{id}/blob` | R0.9 (wave 4): upload the component bytes a registered manifest's `build_digest` commits to (raw body) → `201 {capsule_id, sha256, bytes}`; `404` unknown capsule, `422` digest mismatch, `409` different bytes under a taken address (registry immutability over bytes) |
120//!
121//! Runs support `command.resume` (HITL), `config.recursion_limit`, the
122//! `reject` / `enqueue` multitask strategies (one active run per thread),
123//! `assistant_id` (resolved to its bound graph, with the assistant's
124//! `config.recursion_limit` as a default), and `checkpoint.checkpoint_id`
125//! (time-travel replay from that checkpoint instead of the latest).
126
127mod a2a;
128mod agents;
129mod assistants;
130mod auth;
131pub mod capsule_policy;
132mod capsules;
133mod coordination;
134mod crons;
135mod error;
136mod journals;
137mod learn;
138mod mcp_bridge;
139mod memory;
140mod outbox;
141mod policy;
142mod receipts;
143mod replay;
144mod routes;
145mod runs;
146mod server_store;
147mod sse;
148mod store;
149mod supervision;
150mod tasks;
151mod threads;
152mod triggers;
153
154use std::collections::HashMap;
155use std::net::SocketAddr;
156use std::path::PathBuf;
157use std::sync::Arc;
158
159use axum::Router;
160use rusty_agent_runtime::capsule::ResourceBudget;
161use rusty_agent_runtime::graph::Graph;
162use rusty_agent_runtime::learn::{CandidateEvaluator, PromotionEnvelope};
163use rusty_agent_runtime::state::StateSpec;
164use tokio_util::sync::CancellationToken;
165
166pub use error::ApiError;
167pub use learn::{DatasetSource, DirectoryDatasetSource, EvalCandidateEvaluator, EvaluationAgent};
168pub use runs::RunStatus;
169
170/// Default bound on graceful shutdown (25 s): how long
171/// [`serve_with_shutdown`] lets in-flight requests, runs, and the outbox
172/// relay finish after the shutdown signal before the server stops anyway.
173///
174/// Chosen to fit under two outer backstops: Kubernetes' default 30 s
175/// pod-termination grace (so the drain finishes before SIGKILL would
176/// arrive) and the task queue's default 30 s lease (so a drained server has
177/// released its work well before lease expiry would reassign it). The
178/// durable machinery — checkpoint resume, lease expiry — remains the
179/// correctness net; the grace bound only decides how *fast* the common
180/// case is. Override with [`ServerConfig::with_shutdown_grace`].
181pub const DEFAULT_SHUTDOWN_GRACE: std::time::Duration = std::time::Duration::from_secs(25);
182
183/// Names the JSON-file layout already owns at the store root
184/// (`agent_leases/`, `agents/`, `assistants/`, `capsules/`,
185/// `capsule_policies/`, `coordinations/`, `crons/`, `journals/`, `learn/`,
186/// `memory/`, `memory_artifacts/`, `outbox/`, `policy/`, `store/`,
187/// `tasks/`, `threads/`, `trigger_events/`, `triggers/`, plus the
188/// `latest` pointer file inside each thread's checkpoint dir).
189/// Client-chosen ids and tenant ids claiming one of these would write
190/// checkpoints into platform directories (or platform records into
191/// checkpoint dirs), so both `validate_client_id` and
192/// [`ServerConfig::with_tenant_key`] reject them.
193pub(crate) const RESERVED_NAMES: &[&str] = &[
194 "agent_leases",
195 "agents",
196 "assistants",
197 "capsules",
198 "capsule_policies",
199 "coordinations",
200 "crons",
201 "journals",
202 "keys",
203 "learn",
204 "memory",
205 "memory_artifacts",
206 "outbox",
207 "policy",
208 "receipts",
209 "store",
210 "tasks",
211 "threads",
212 "trigger_events",
213 "triggers",
214 "latest",
215];
216
217/// One registered graph: the compiled topology plus the state schema the
218/// executor needs to drive it.
219#[derive(Debug, Clone)]
220struct GraphEntry {
221 graph: Graph,
222 spec: StateSpec,
223}
224
225/// The set of graphs this server hosts — the Rust analog of the `graphs` map
226/// in LangGraph's `langgraph.json`. Registration is compile-checked in user
227/// code; a `GraphRegistry` is heterogeneous (each entry carries its own
228/// [`StateSpec`]), which is safe because `State` is a JSON map at runtime.
229#[derive(Debug, Default, Clone)]
230pub struct GraphRegistry {
231 entries: HashMap<String, GraphEntry>,
232}
233
234impl GraphRegistry {
235 pub fn new() -> Self {
236 Self::default()
237 }
238
239 /// Register a compiled graph under `name`, together with the state spec
240 /// the executor should merge its node updates through. Re-registering a
241 /// name replaces the previous entry.
242 pub fn register(
243 &mut self,
244 name: impl Into<String>,
245 graph: Graph,
246 spec: StateSpec,
247 ) -> &mut Self {
248 self.entries.insert(name.into(), GraphEntry { graph, spec });
249 self
250 }
251
252 /// `true` if a graph is registered under `name`.
253 pub fn contains(&self, name: &str) -> bool {
254 self.entries.contains_key(name)
255 }
256
257 /// All registered graph names, sorted for stable output.
258 pub fn names(&self) -> Vec<String> {
259 let mut names: Vec<String> = self.entries.keys().cloned().collect();
260 names.sort_unstable();
261 names
262 }
263
264 /// The declared channel names of a registered graph's spec, sorted.
265 pub fn channel_names(&self, name: &str) -> Vec<String> {
266 let mut channels: Vec<String> = self
267 .entries
268 .get(name)
269 .map(|entry| entry.spec.channel_names().map(str::to_owned).collect())
270 .unwrap_or_default();
271 channels.sort_unstable();
272 channels
273 }
274
275 pub(crate) fn get(&self, name: &str) -> Option<(Graph, StateSpec)> {
276 self.entries
277 .get(name)
278 .map(|entry| (entry.graph.clone(), entry.spec.clone()))
279 }
280}
281
282/// Tenant quota for the durable task queue (R0.6 wave 3): three gauges,
283/// each capped independently — tasks queued, tasks in flight, dead-letter
284/// depth — enforced at **submission** (`POST /tasks`, `POST /tasks/outbox`,
285/// and `update_state`'s atomic `enqueue` list). Over quota answers `429
286/// quota_exceeded`, the honest shape for "retry this submission later".
287///
288/// The gauges are the store's `TaskUsage` definitions: the backlog
289/// counts scheduled retries *and* outbox rows pending publication (a flood
290/// through the outbox must not bypass the quota), in flight counts every
291/// `leased` record, and the DLQ counts because an unbounded dead-letter
292/// queue is a quiet disk-full outage. `None` (the default for every field)
293/// means unlimited, preserving pre-wave-3 behavior.
294#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
295pub struct TaskQuota {
296 /// Cap on the tenant's backlog (queued + retry-scheduled + pending
297 /// outbox rows). A submission that would push the backlog past the cap
298 /// is rejected.
299 pub max_queued: Option<usize>,
300
301 /// Cap on tasks in flight (status `leased`). Pure backpressure: a
302 /// tenant already at the cap has its new submissions rejected until
303 /// workers settle.
304 pub max_in_flight: Option<usize>,
305
306 /// Cap on dead-letter depth. A tenant at the cap must inspect and
307 /// re-drive its DLQ before more work is accepted.
308 pub max_dlq: Option<usize>,
309}
310
311impl TaskQuota {
312 /// Every gauge capped: `TaskQuota { max_queued: Some(q),
313 /// max_in_flight: Some(f), max_dlq: Some(d) }`. Field-by-field
314 /// construction works too — the struct's fields are public and each
315 /// `None` means unlimited.
316 pub fn capped(max_queued: usize, max_in_flight: usize, max_dlq: usize) -> Self {
317 Self {
318 max_queued: Some(max_queued),
319 max_in_flight: Some(max_in_flight),
320 max_dlq: Some(max_dlq),
321 }
322 }
323
324 /// `true` when no gauge is capped — the quota gate short-circuits
325 /// without a store read (the default configuration's fast path).
326 pub(crate) fn is_unlimited(&self) -> bool {
327 self.max_queued.is_none() && self.max_in_flight.is_none() && self.max_dlq.is_none()
328 }
329}
330
331/// Server configuration.
332///
333/// Checkpointing is rooted at `store_path` via
334/// [`rusty_agent_runtime::checkpoint::JsonFileCheckpointer`]. Auth maps static API
335/// keys (checked against the `X-Api-Key` header) to tenants: the legacy
336/// single [`ServerConfig::with_api_key`] maps its key to the `default`
337/// tenant, while [`ServerConfig::with_tenant_key`] adds `(tenant, key)`
338/// pairs for multi-tenant deployments. With no keys configured the server
339/// runs in open (dev) mode — no header required, everything lives in the
340/// `default` tenant. Every tenant-scoped resource (threads + checkpoints,
341/// assistants, crons, KV namespaces) is isolated per tenant; cross-tenant
342/// access answers `404`. With the `postgres` feature,
343/// `ServerConfig::with_postgres` switches **both** the run checkpointer
344/// (core's `PostgresCheckpointer`) and the server store (assistants /
345/// crons / threads / KV) to Postgres.
346#[derive(Debug, Clone)]
347pub struct ServerConfig {
348 /// Address to bind when using [`serve`] (default `0.0.0.0:8080`).
349 pub bind_addr: SocketAddr,
350
351 /// Root directory for checkpoint files
352 /// (`{store_path}/{thread_id}/{checkpoint_id}.json`). Also roots the
353 /// JSON-file assistants/crons/threads/KV persistence. Unused for
354 /// checkpointing when `database_url` is set (still used as the
355 /// `store_path` reported by `GET /info`).
356 pub store_path: PathBuf,
357
358 /// Postgres connection URL. When set (requires the `postgres` feature —
359 /// see `ServerConfig::with_postgres`), checkpoints live in core's
360 /// `rusty_checkpoints` table and the platform surface in the
361 /// `server_assistants` / `server_crons` / `server_threads` /
362 /// `server_kv` / `server_journals` tables, all auto-migrated on
363 /// connect. Connections are established lazily on first use.
364 pub database_url: Option<String>,
365
366 /// Per-thread in-flight run cap used as the **enqueue queue depth**
367 /// (default 1). There is always at most one *active* run per thread.
368 pub max_concurrent_runs_per_thread: usize,
369
370 /// Static API key required via the `X-Api-Key` header, mapped to the
371 /// `default` tenant (legacy single-key mode). `None` (the default) with
372 /// an empty [`ServerConfig::api_keys`] is dev mode: no authentication.
373 pub api_key: Option<String>,
374
375 /// Additional `(api_key, tenant)` pairs for multi-tenant deployments
376 /// (see [`ServerConfig::with_tenant_key`]). Each key maps to exactly one
377 /// tenant; every tenant's threads, assistants, crons, and KV namespaces
378 /// are isolated from all others (cross-tenant access answers `404`).
379 pub api_keys: Vec<(String, String)>,
380
381 /// Per-run SSE event-log capacity (frames retained for replay, default
382 /// 1000).
383 pub event_log_capacity: usize,
384
385 /// How often the transactional-outbox relay publishes pending rows into
386 /// the task queue (R0.6 wave 2b, default 250 ms). The relay is
387 /// crash-safe at any interval — pending rows survive restarts and
388 /// publishing dedupes on the task's idempotency key — so this only
389 /// tunes outbox-to-queue latency, not correctness.
390 pub outbox_relay_interval: std::time::Duration,
391
392 /// Bound on graceful shutdown (R0.6 wave 2c, default
393 /// [`DEFAULT_SHUTDOWN_GRACE`]): after the shutdown signal, in-flight
394 /// requests and runs get this long to finish before the server stops
395 /// regardless. Runs stopped by the drain are resumable from their last
396 /// checkpoint, so a short grace costs a resume, never work.
397 pub shutdown_grace: std::time::Duration,
398
399 /// Per-pool in-flight caps for the durable task queue (R0.6 wave 3):
400 /// pool name → maximum live leases. The claim path counts a pool's
401 /// unexpired leases and stops handing out new ones at the cap, so
402 /// pools coexist without starving each other (a saturated GPU pool
403 /// never blocks IO-pool claims). Pools without an entry are
404 /// uncapped — the pre-wave-3 behavior. See
405 /// [`ServerConfig::with_pool_limit`].
406 pub task_pool_limits: HashMap<String, usize>,
407
408 /// The default tenant quota (R0.6 wave 3), applied to every tenant
409 /// without an entry in [`ServerConfig::tenant_task_quotas`]. All
410 /// gauges uncapped by default. See [`TaskQuota`].
411 pub task_quota: TaskQuota,
412
413 /// Per-tenant quota overrides (R0.6 wave 3), replacing
414 /// [`ServerConfig::task_quota`] wholesale for the named tenant (an
415 /// override *is* the tenant's quota, not a patch on the default).
416 /// See [`ServerConfig::with_tenant_quota`].
417 pub tenant_task_quotas: HashMap<String, TaskQuota>,
418
419 /// The promotion envelope (R0.8 Rusty Learn, wave 3): the declared,
420 /// per-deployment standing approval the promotion gate evaluates
421 /// every promotion against. Defaults to
422 /// [`PromotionEnvelope::r08_default`] — memory-set candidates at
423 /// run/agent scope auto-promote on cleared evidence; everything else
424 /// requires an approval token. See
425 /// [`ServerConfig::with_promotion_envelope`].
426 pub promotion_envelope: PromotionEnvelope,
427
428 /// The candidate evaluator (R0.8 wave 3): the evaluation
429 /// composition `POST /learn/candidates/{id}/evaluate` drives. `None`
430 /// (the default) answers `409` — a deployment without an evaluator
431 /// can hold and inspect candidates, but promotion is gated on
432 /// evidence, and evidence requires an evaluator. See
433 /// [`ServerConfig::with_candidate_evaluator`].
434 pub candidate_evaluator: Option<Arc<dyn CandidateEvaluator>>,
435
436 /// Operator-authored Cedar policy files (R0.9 Rusty Capsules, wave
437 /// 2), loaded for the `default` tenant at startup — the deployment's
438 /// standing authorization, the way static API keys are its standing
439 /// authentication. Requires the `capsules` feature; each file is
440 /// registered under its content-derived version
441 /// (`cedar-{sha256[..12]}`), never activated — activation is an
442 /// explicit operator move through `POST /capsule_policies/active`. See
443 /// [`ServerConfig::with_capsule_policy_file`].
444 pub capsule_policy_files: Vec<PathBuf>,
445
446 /// The tenant-wide budget ceiling (R0.9 wave 2): the outermost bound
447 /// every capsule budget composes under. Fuel, memory, wall time, and
448 /// output bytes clamp down to it; a run declaring more `max_tokens`
449 /// or `max_cost_usd` than the ceiling (or than the run's own budget)
450 /// is refused `422` — token and cost bounds cannot be retrofitted
451 /// mid-run the way fuel can, so admission refuses the overspend. See
452 /// [`ServerConfig::with_capsule_budget_ceiling`].
453 pub capsule_budget_ceiling: Option<ResourceBudget>,
454
455 /// The deployment's network-egress seam for capsules the A2A bridge
456 /// executes in-process (R0.9 wave 4): the [`NetworkConnector`] every
457 /// bridge-built capsule host is constructed with. Without one, A2A
458 /// tasks carrying a capsule payload fail closed with
459 /// `capsule_execution_unavailable` — the bridge never executes guest
460 /// code against an egress path the operator did not explicitly wire.
461 /// Requires the `capsules` feature. See
462 /// [`ServerConfig::with_capsule_connector`].
463 #[cfg(feature = "capsules")]
464 pub capsule_connector: Option<Arc<dyn rusty_agent_runtime::capsule_host::NetworkConnector>>,
465}
466
467impl Default for ServerConfig {
468 fn default() -> Self {
469 Self {
470 bind_addr: SocketAddr::from(([0, 0, 0, 0], 8080)),
471 store_path: PathBuf::from("./data/checkpoints"),
472 database_url: None,
473 max_concurrent_runs_per_thread: 1,
474 api_key: None,
475 api_keys: Vec::new(),
476 event_log_capacity: 1000,
477 outbox_relay_interval: crate::outbox::DEFAULT_RELAY_INTERVAL,
478 shutdown_grace: DEFAULT_SHUTDOWN_GRACE,
479 task_pool_limits: HashMap::new(),
480 task_quota: TaskQuota::default(),
481 tenant_task_quotas: HashMap::new(),
482 promotion_envelope: PromotionEnvelope::r08_default(),
483 candidate_evaluator: None,
484 capsule_policy_files: Vec::new(),
485 capsule_budget_ceiling: None,
486 #[cfg(feature = "capsules")]
487 capsule_connector: None,
488 }
489 }
490}
491
492impl ServerConfig {
493 /// A config with the given bind address and checkpoint store root;
494 /// everything else at its default.
495 pub fn new(bind_addr: SocketAddr, store_path: impl Into<PathBuf>) -> Self {
496 Self {
497 bind_addr,
498 store_path: store_path.into(),
499 ..Self::default()
500 }
501 }
502
503 /// Builder-style: require an API key on every request. The key maps to
504 /// the `default` tenant (legacy single-tenant mode).
505 pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
506 self.api_key = Some(key.into());
507 self
508 }
509
510 /// Builder-style: map an API key to a tenant (multi-tenant mode). Every
511 /// request presenting `key` via `X-Api-Key` runs as `tenant`, fully
512 /// isolated from all other tenants. Tenant ids must match
513 /// `[A-Za-z0-9._-]` (1–64 chars) and must not be a reserved layout name
514 /// (`assistants`, `crons`, `store`, `threads`, `latest`) — they become a
515 /// path segment in the JSON-file layout and a `{tenant}/` id prefix
516 /// everywhere else.
517 ///
518 /// # Panics
519 ///
520 /// Panics on an empty key or an invalid tenant id (configuration is a
521 /// programmer error, caught at startup).
522 pub fn with_tenant_key(mut self, tenant: impl Into<String>, key: impl Into<String>) -> Self {
523 let tenant = tenant.into();
524 let key = key.into();
525 let valid = !tenant.is_empty()
526 && tenant.len() <= 64
527 && tenant
528 .chars()
529 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
530 && !RESERVED_NAMES.contains(&tenant.as_str());
531 assert!(
532 valid,
533 "invalid tenant id `{tenant}` (allowed: [A-Za-z0-9._-], 1..=64 chars, not a reserved name)"
534 );
535 assert!(
536 !key.is_empty(),
537 "API key for tenant `{tenant}` must not be empty"
538 );
539 self.api_keys.push((key, tenant));
540 self
541 }
542
543 /// `true` when at least one API key is configured (legacy `api_key` or
544 /// any tenant key), i.e. requests must authenticate.
545 pub fn auth_enabled(&self) -> bool {
546 self.api_key.is_some() || !self.api_keys.is_empty()
547 }
548
549 /// The tenant a presented API key maps to, or `None` for unknown keys.
550 /// Tenant keys are checked first (last registration wins on duplicate
551 /// keys); the legacy `api_key` maps to the `default` tenant.
552 pub fn tenant_for_key(&self, key: &str) -> Option<&str> {
553 if let Some((_, tenant)) = self.api_keys.iter().rev().find(|(k, _)| k == key) {
554 return Some(tenant.as_str());
555 }
556 if self.api_key.as_deref() == Some(key) {
557 return Some("default");
558 }
559 None
560 }
561
562 /// Builder-style: persist everything in Postgres at `url` (e.g.
563 /// `postgres://user:pass@localhost/rusty`). Switches the run
564 /// checkpointer to [`rusty_agent_runtime::checkpoint_postgres::PostgresCheckpointer`]
565 /// **and** the assistants/crons/threads/KV/journals server store to the
566 /// `server_*` tables. Schemas auto-migrate on (lazy) connect.
567 #[cfg(feature = "postgres")]
568 pub fn with_postgres(mut self, url: impl Into<String>) -> Self {
569 self.database_url = Some(url.into());
570 self
571 }
572
573 /// Builder-style: set the per-thread enqueue queue depth cap. Values
574 /// below 1 are clamped to 1 (a zero-deep queue would reject every
575 /// `enqueue` run).
576 pub fn with_max_concurrent_runs_per_thread(mut self, cap: usize) -> Self {
577 self.max_concurrent_runs_per_thread = cap;
578 self
579 }
580
581 /// Builder-style: set the per-run SSE event-log capacity. Values below
582 /// 16 are clamped to 16 (replay needs room for at least the
583 /// metadata/updates/end frames of a minimal run).
584 pub fn with_event_log_capacity(mut self, capacity: usize) -> Self {
585 self.event_log_capacity = capacity;
586 self
587 }
588
589 /// Builder-style: set the transactional-outbox relay's poll interval
590 /// (R0.6 wave 2b). Tests can set a long interval to drive publishing
591 /// deterministically; correctness never depends on the interval.
592 pub fn with_outbox_relay_interval(mut self, interval: std::time::Duration) -> Self {
593 self.outbox_relay_interval = interval;
594 self
595 }
596
597 /// Builder-style: set the graceful-shutdown bound (R0.6 wave 2c; see
598 /// [`DEFAULT_SHUTDOWN_GRACE`] for the default's rationale). Past this
599 /// window the server stops even if requests or runs are still in flight
600 /// — durability (checkpoint resume, lease expiry) is the backstop.
601 pub fn with_shutdown_grace(mut self, grace: std::time::Duration) -> Self {
602 self.shutdown_grace = grace;
603 self
604 }
605
606 /// Builder-style: cap the named pool's live leases (R0.6 wave 3). The
607 /// claim path counts a pool's unexpired leases and stops handing out
608 /// new ones at `max_in_flight`, so a saturated pool (GPU-bound work)
609 /// never starves the others (IO-bound work). A cap of `0` pauses the
610 /// pool: nothing is leased from it until the cap is raised. Pools
611 /// without an entry stay uncapped.
612 ///
613 /// # Panics
614 ///
615 /// Panics on an invalid pool name (configuration is a programmer error,
616 /// caught at startup); names must match `[A-Za-z0-9._-]` (1–128 chars),
617 /// the same rule the enqueue and claim paths validate.
618 pub fn with_pool_limit(mut self, pool: impl Into<String>, max_in_flight: usize) -> Self {
619 let pool = pool.into();
620 assert!(
621 crate::tasks::validate_pool(&pool).is_ok(),
622 "invalid pool name `{pool}` (allowed: [A-Za-z0-9._-], 1..=128 chars)"
623 );
624 self.task_pool_limits.insert(pool, max_in_flight);
625 self
626 }
627
628 /// Builder-style: set the default tenant quota for the durable task
629 /// queue (R0.6 wave 3), applied to every tenant without a
630 /// [`ServerConfig::with_tenant_quota`] override. Over quota, task
631 /// submissions answer `429 quota_exceeded`. The default is uncapped on
632 /// every gauge. See [`TaskQuota`] for the gauge definitions.
633 pub fn with_task_quota(mut self, quota: TaskQuota) -> Self {
634 self.task_quota = quota;
635 self
636 }
637
638 /// Builder-style: override the task quota for one tenant (R0.6 wave 3).
639 /// The override replaces [`ServerConfig::task_quota`] wholesale for
640 /// that tenant — an uncapped gauge in the override is unlimited even if
641 /// the default caps it.
642 ///
643 /// # Panics
644 ///
645 /// Panics on an invalid tenant id (same rule as
646 /// [`ServerConfig::with_tenant_key`]).
647 pub fn with_tenant_quota(mut self, tenant: impl Into<String>, quota: TaskQuota) -> Self {
648 let tenant = tenant.into();
649 let valid = !tenant.is_empty()
650 && tenant.len() <= 64
651 && tenant
652 .chars()
653 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
654 && !RESERVED_NAMES.contains(&tenant.as_str());
655 assert!(
656 valid,
657 "invalid tenant id `{tenant}` (allowed: [A-Za-z0-9._-], 1..=64 chars, not a reserved name)"
658 );
659 self.tenant_task_quotas.insert(tenant, quota);
660 self
661 }
662
663 /// The quota governing `tenant`: its override when one is configured,
664 /// else the server-wide default ([`ServerConfig::task_quota`]).
665 pub(crate) fn quota_for(&self, tenant: &str) -> &TaskQuota {
666 self.tenant_task_quotas
667 .get(tenant)
668 .unwrap_or(&self.task_quota)
669 }
670
671 /// Builder-style: set the promotion envelope (R0.8 Rusty Learn, wave
672 /// 3) — the declared, per-deployment standing approval the promotion
673 /// gate evaluates every promotion against. Replaces
674 /// [`PromotionEnvelope::r08_default`].
675 ///
676 /// # Panics
677 ///
678 /// Panics when the envelope fails [`PromotionEnvelope::validate`]
679 /// (a canary fraction outside `(0, 1]`, a negative improvement bar —
680 /// configuration is a programmer error, caught at startup).
681 pub fn with_promotion_envelope(mut self, envelope: PromotionEnvelope) -> Self {
682 if let Err(error) = envelope.validate() {
683 panic!("invalid promotion envelope: {error}");
684 }
685 self.promotion_envelope = envelope;
686 self
687 }
688
689 /// Builder-style: register the candidate evaluator (R0.8 wave 3) —
690 /// the evaluation composition `POST /learn/candidates/{id}/evaluate`
691 /// drives. Without one the route answers `409`: promotion is gated
692 /// on evidence, and evidence requires an evaluator.
693 pub fn with_candidate_evaluator(mut self, evaluator: Arc<dyn CandidateEvaluator>) -> Self {
694 self.candidate_evaluator = Some(evaluator);
695 self
696 }
697
698 /// Builder-style: add one operator-authored Cedar policy file (R0.9
699 /// Rusty Capsules, wave 2), loaded for the `default` tenant at
700 /// startup. Files are *registered*, never activated — moving a
701 /// tenant's active pointer is an explicit operator move through
702 /// `POST /capsule_policies/active`, so a restart can never silently
703 /// change what serves. Without the `capsules` feature the files are
704 /// ignored (the plane's routes answer `503` either way).
705 pub fn with_capsule_policy_file(mut self, path: impl Into<PathBuf>) -> Self {
706 self.capsule_policy_files.push(path.into());
707 self
708 }
709
710 /// Builder-style: set the tenant-wide capsule budget ceiling (R0.9
711 /// wave 2) — the outermost bound every capsule budget composes
712 /// under. `None` (the default) leaves budgets bounded only by the
713 /// run's own declaration and each capsule's manifest.
714 pub fn with_capsule_budget_ceiling(mut self, ceiling: ResourceBudget) -> Self {
715 self.capsule_budget_ceiling = Some(ceiling);
716 self
717 }
718
719 /// Builder-style: set the network connector for capsules the A2A
720 /// bridge executes in-process (R0.9 wave 4) — the deployment's
721 /// explicit egress seam. `None` (the default) refuses capsule
722 /// execution over A2A with `capsule_execution_unavailable`: guest
723 /// code never runs against an egress path the operator did not wire.
724 #[cfg(feature = "capsules")]
725 pub fn with_capsule_connector(
726 mut self,
727 connector: Arc<dyn rusty_agent_runtime::capsule_host::NetworkConnector>,
728 ) -> Self {
729 self.capsule_connector = Some(connector);
730 self
731 }
732}
733
734/// Build the axum [`Router`] for a registry and config. Use this to embed the
735/// rusty-agent-server routes into a larger application, or to drive the API in tests
736/// via `tower::ServiceExt::oneshot`.
737///
738/// The router's drain control is internal and never fires (embedders who
739/// want cooperative drain should use [`router_with_shutdown`]).
740pub fn router(registry: GraphRegistry, config: ServerConfig) -> Router {
741 router_with_shutdown(registry, config, CancellationToken::new())
742}
743
744/// Build the axum [`Router`] with an explicit drain control (R0.6 wave 2c).
745///
746/// Cancelling `shutdown` starts the cooperative drain **inside** the
747/// application — in-flight runs stop at their next checkpoint boundary, the
748/// outbox relay finishes its current pass and stops, the cron scheduler
749/// stops firing, and new run submissions are rejected with `503` — while
750/// the HTTP surface keeps serving so in-flight requests can complete.
751/// Stopping HTTP itself is the embedder's job (axum's
752/// `with_graceful_shutdown`); [`serve_with_shutdown`] wires both halves
753/// together.
754pub fn router_with_shutdown(
755 registry: GraphRegistry,
756 config: ServerConfig,
757 shutdown: CancellationToken,
758) -> Router {
759 routes::router_with_shutdown(registry, config, shutdown)
760}
761
762/// Build the router and bind it to `config.bind_addr`. Blocks until the
763/// server shuts down: SIGINT or SIGTERM starts the graceful drain described
764/// on [`serve_with_shutdown`].
765pub async fn serve(registry: GraphRegistry, config: ServerConfig) -> std::io::Result<()> {
766 serve_with_shutdown(registry, config, shutdown_signal()).await
767}
768
769/// Build the router, bind it to `config.bind_addr`, and serve until
770/// `shutdown` resolves, then drain gracefully (R0.6 wave 2c). The drain is
771/// ordered so the common case of a rolling deploy strands nothing:
772///
773/// 1. **Stop taking new work.** axum stops accepting connections; the
774/// server's shared drain token fires, so new run submissions answer
775/// `503` and the cron scheduler stops firing.
776/// 2. **Let in-flight work land.** In-flight requests complete (axum waits
777/// for them); in-flight runs are cooperatively cancelled at their next
778/// super-step boundary — where a checkpoint was just persisted — and
779/// end terminal-`cancelled`, resumable by re-running the thread; the
780/// outbox relay finishes its current publish pass and stops (pending
781/// rows are durable and publish on the next process's first pass).
782/// 3. **Stop, bounded.** The whole drain is capped at
783/// [`ServerConfig::shutdown_grace`]. Past it the server returns anyway:
784/// anything still in flight is abandoned mid-step, which is exactly the
785/// crash case the durable machinery already covers — runs resume from
786/// their last checkpoint and leased tasks return to visibility within
787/// one lease period. Grace makes the common case fast; it is never the
788/// correctness mechanism.
789pub async fn serve_with_shutdown(
790 registry: GraphRegistry,
791 config: ServerConfig,
792 shutdown: impl std::future::Future<Output = ()> + Send + 'static,
793) -> std::io::Result<()> {
794 let addr = config.bind_addr;
795 let grace = config.shutdown_grace;
796 // Open (dev) mode on a non-loopback address exposes the full API — run
797 // creation, KV writes, checkpoint deletion — to the network. That's a
798 // legitimate dev choice, but it must never be a quiet one.
799 if !config.auth_enabled() && !addr.ip().is_loopback() {
800 tracing::warn!(
801 %addr,
802 "serving WITHOUT authentication on a non-loopback address; \
803 configure `with_api_key`/`with_tenant_key` or bind 127.0.0.1"
804 );
805 }
806 let draining = CancellationToken::new();
807 let app = router_with_shutdown(registry, config, draining.clone());
808 let listener = tokio::net::TcpListener::bind(addr).await?;
809 tracing::info!(%addr, "rusty-server listening");
810 let server = axum::serve(listener, app).with_graceful_shutdown({
811 let draining = draining.clone();
812 async move {
813 shutdown.await;
814 tracing::info!(
815 grace_ms = grace.as_millis() as u64,
816 "shutdown requested; draining"
817 );
818 // One token drives the whole cooperative drain: runs stop at
819 // their next checkpoint boundary, the relay finishes its pass,
820 // the cron scheduler stops, new runs are rejected.
821 draining.cancel();
822 }
823 });
824 tokio::select! {
825 // `WithGracefulShutdown` is `IntoFuture`, not `Future`, so it needs
826 // this async wrapper to sit in a `select!` arm.
827 result = async { server.await } => result,
828 () = async {
829 // The grace clock starts when the drain does. axum's graceful
830 // shutdown waits for in-flight connections without a bound of
831 // its own, so this arm is the bound.
832 draining.cancelled().await;
833 tokio::time::sleep(grace).await;
834 } => {
835 tracing::warn!(
836 grace_ms = grace.as_millis() as u64,
837 "drain grace expired; forcing shutdown — in-flight runs resume \
838 from their last checkpoint and leased tasks return at lease expiry"
839 );
840 Ok(())
841 }
842 }
843}
844
845/// The default shutdown signal for [`serve`]: resolves on SIGINT or SIGTERM
846/// (the two signals orchestrators and terminals actually send). Exposed so
847/// binaries that compose their own shutdown logic can reuse it.
848pub async fn shutdown_signal() {
849 let ctrl_c = tokio::signal::ctrl_c();
850 #[cfg(unix)]
851 {
852 // Signal-handler installation only fails when the fd limit is
853 // exhausted; a server that cannot hear SIGTERM must not start
854 // pretending it drains gracefully.
855 let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
856 .expect("installing the SIGTERM handler must succeed");
857 tokio::select! {
858 _ = ctrl_c => {},
859 _ = sigterm.recv() => {},
860 }
861 }
862 #[cfg(not(unix))]
863 {
864 let _ = ctrl_c.await;
865 }
866}