From 7521cf28d8b052e8e79907c109fe7b3595609904 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 16:57:30 -0500 Subject: [PATCH 01/27] =?UTF-8?q?SERVING-ENGINE=20=C2=A71a:=20MindMemory,?= =?UTF-8?q?=20the=20one=20owner=20of=20a=20mind's=20KV=20memory,=20before?= =?UTF-8?q?=20any=20more=20path=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 2026-10-27 inventory: 41 paths, 9 decisions made in 2-6 places each, four gaps (idle retirement saves nobody, cache_probe pages outside the ledger, an in-place gene change keeps stale KV restorable, a dead page-store trim). The seq_table and pager of §1 are built first over today's llama-server: seat / pause / resume / adopt / forget, each decision once inside, every lifecycle path a request, the guards deleted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/SERVING-ENGINE.md | 60 +++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/docs/architecture/SERVING-ENGINE.md b/docs/architecture/SERVING-ENGINE.md index 9b4986aab3..a0442f9061 100644 --- a/docs/architecture/SERVING-ENGINE.md +++ b/docs/architecture/SERVING-ENGINE.md @@ -46,6 +46,66 @@ **Page format.** Disk pages stay `llama_state_seq_save_file` output plus the `.ckpt` (0x434B5054) and `.lora` sidecars (2716-2826). `a-.bin` and `LEDGER_FORMAT 2` (saved_ledger.rs:36-62) then carry over unchanged. One gap: the `.bin` holds only `ctx_tgt` (2809), so the MTP draft KV comes back cold. +## 1a. `MindMemory`: the `seq_table` and `pager` owner over today's llama-server (2026-10-27) + +**Why now.** On 2026-10-27 a mind's KV memory broke four ways in one afternoon on the M5: +- the tool head changed at launch; +- a save was cut by the core's exit; +- a resident was left unsaved in her slot at the stop; +- the boot plan was computed before the ledger was credited. + +Each was patched in one lifecycle path (#5538, #5540). The inventory that followed, at canary 107af9167, found 41 paths and 9 decisions made in 2 to 6 places each: +- who may evict a resident; +- when a page is restorable; +- the save-the-evictee procedure, written three times; +- save-all before the engine dies, four times, and missing in idle retirement; +- recording residents lost unsaved; +- quarantine; +- slot ownership; +- scratch policy; +- page-dir ownership. + +Joel: "you can't get anything to work unless there is one daemon and centralized location." So `seq_table` and `pager` (§1) are built FIRST, as one owner speaking HTTP to today's llama-server (step 1 of §2). When S1–S5 land, its mechanism changes and its callers do not. + +**One owner per engine endpoint: `MindMemory`.** It holds the slot attribution, the saved set, the ledger file, page IO and the quarantine. Nothing else calls `/slots/*` or writes the ledger. It runs as a `ServiceModule` in the canonical shape (CONCURRENCY-STYLE-GUIDE). Its stop is its own `SettleBeforeStop`. + +| Request | Replaces | Contract | +|---|---|---| +| `seat(PageKey, Purpose) -> Seat` | `lease` + `pin_slot` + `plan_paging` + the turn's paging closure (turn_admission.rs:344-472); `borrow_slot_for_transient` (:517); `warm_ahead`'s paging; `cache_probe`'s raw `/slots` IO | RAII. She holds a pinned slot with her KV in it (resident, or restored from her page), or the seat says why she starts cold. `Purpose` is Turn, WarmAhead or Transient: a Transient seat may borrow the cheapest resident's slot, which is saved first. | +| `pause(Why) -> PauseReceipt` | `checkpoint_before_replacement`, `checkpoint_owned_restore`, `checkpoint_adopted_before_replacement`, `checkpoint_every_endpoint` (stop), and the missing save in `idle_if_current` | Closes seating and drains the seats, then saves every resident with a confirmed save. A resident whose save fails is recorded as lost, by name. Every engine retirement goes through it: relaunch, academy, idle, adopted retirement, stop. | +| `resume(PauseReceipt, Generation)` / `adopt(Generation)` | `ready()`'s pool swap and ledger carry or load; `adopt_engine_ledger`; `resume_suspension` | Boot, relaunch and adopt load the one ledger by the one rule (fingerprint plus incarnation), and seat nothing. | +| `forget(PageKey, Why)` | `note_page_lost` on a refused restore; nothing today on an in-place gene change | A page whose KV no longer means what it did (a gene change, a refused restore) stops being restorable. | + +**Inside it, each decision exactly once:** +- `evict(slot)`: the single save-the-evictee procedure (invalidate, save, confirm). +- `restorable(key)`: the single rule for when a page is offered. +- the ledger written only on its own transitions; +- quarantine owned and cleared by it; +- the scratch policy decided once, in `seat`. + +**Deleted when callers move:** +- the paging block of `turn_admission.rs` and `borrow_slot_for_transient`; +- `slots/page_io.rs` (#5540's gate, which becomes `MindMemory`'s own stop); +- the four `checkpoint_*` variants; +- public `take_resident` / `forget_resident` / `plan_paging` / `note_saved` / `note_page_lost`; +- `trim_page_store_after_save`, which has no caller; the page store's trim moves into the owner or is deleted. + +**Validator (S0 for this owner).** `turn_admission/tests/lifecycle.rs` already runs a fake engine whose slots hold `mind:tokens`, through turns, a stop and a boot. It moves to `MindMemory`'s own tests and gains: +- a relaunch; +- an adoption; +- idle retirement; +- an in-place gene change; +- transient borrowing. + +Each scenario asserts where every mind resumes, in seconds, before any live read. + +**Order and owners.** +1. `MindMemory` with `seat` and its own stop, with turn, warm-ahead and transient moved onto it (Fable). +2. `pause` and `resume`, with relaunch, academy, idle and adopted retirement moved onto them (Codex: the relaunch call sites are S4's). +3. `forget` on gene change (Fable). + +Each step deletes what it replaces in the same PR, and the lifecycle validator gains that step's scenario first. + ## 2. Reuse versus write | Option | Speed | Effort | Risk | From 4ee13ad9f749fd2874677db1940d5704845a69f0 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 17:08:27 -0500 Subject: [PATCH 02/27] DRIVER-GATEWAY.md: one door every agent can call, with warm memory and learning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plan line 16, the Serving seam of REPO-GENOME-AND-COURSES §17. One Gateway module on a stable port; Anthropic Messages, OpenAI Chat Completions and OpenAI Responses as adapters holding only the diff; a session is a driver mind seated through MindMemory (warm KV, never transient, one scheduler); every exchange captured as perception under scope rules. Slices G0-G4 with validators and live gates; G0-G1 start now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/DRIVER-GATEWAY.md | 83 +++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 docs/architecture/DRIVER-GATEWAY.md diff --git a/docs/architecture/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md new file mode 100644 index 0000000000..8bc11e1a96 --- /dev/null +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -0,0 +1,83 @@ + + +# The driver gateway: one door every agent can call + +## Why + +The agents people use already exist: Claude Code, Codex CLI, Grok Build (xAI's agent, Apache 2.0 since July 2026, read-only reference at `~/.continuum/reference/grok-build`), Hermes and opencode. Each one re-sends its whole conversation on every step to a model behind an API. Each one keeps what it learns as notes reread into context: Grok Build's `xai-grok-memory` is markdown plus a consolidation pass, the same mechanism as Claude's MEMORY.md. + +On 2026-10-27 that mechanism visibly failed. A correction already written in notes ("one owner per resource") was repeated within an afternoon. + +Continuum can give these agents two things a stock endpoint cannot: +- **Speed.** Each session's KV stays warm across steps and pages instead of being re-prefilled. A stock server keeps one LRU slot cache, so an agent loses its prefix whenever another session runs. +- **Learning.** Every exchange is perception for the user's genes. A correction then lands in weights that persist across restarts, not in a note. + +The agent changes nothing but its base URL. + +## What exists today (canary 107af9167) + +- `continuum-core/src/http/` serves only the Anthropic `POST /v1/messages`, on a dynamic port, started on demand for Claude Code sentinels (`mod.rs`, `anthropic_compat.rs`, 442 + 262 lines). +- Requests carry no session identity, so a call is anonymous transient traffic. On a busy node that means it borrows a resident's slot (`borrow_slot_for_transient`) and evicts her. +- There is no OpenAI surface. An agent could only reach llama-server directly, which bypasses paging, scheduling and learning. + +## Design: one gateway, wire formats as adapters + +**One module: `Gateway`.** It is a `ServiceModule` in the canonical shape and the only door for external agents. It folds in and deletes `http/mod.rs`'s Anthropic-only server. + +The port is stable and configured, never dynamic, because an agent needs a URL it can keep. The listener is loopback by default; a LAN or grid listener needs a bearer token. + +`continuum gateway env ` prints exactly what to set: +- `ANTHROPIC_BASE_URL` for Claude Code; +- `OPENAI_BASE_URL` for Hermes, opencode and Codex; +- `--xai-api-base-url` for Grok Build. + +**Wire formats are adapters holding only the diff.** Each one is a decoder into the one internal request (`TextGenerationRequest`) and an encoder out of its stream, with SSE included. + +| Wire format | Path | Agents | +|---|---|---| +| Anthropic Messages | `POST /v1/messages` | Claude Code | +| OpenAI Chat Completions | `POST /v1/chat/completions` | Hermes, opencode, most others | +| OpenAI Responses | `POST /v1/responses` (incl. `previous_response_id`) | Grok Build, Codex CLI | +| Discovery | `GET /v1/models` | all | + +Tools pass straight through. The agent executes its own tools; the gateway never does. Tool-call parsing and rendering stays the engine's one template owner (SERVING-ENGINE §1 `template`). + +**A session is a mind.** Each agent session maps to a driver mind, `PageKey::driver(user, session)`. +- The session id comes from the protocol when it carries one: `previous_response_id`, an `x-session-id` header, or OpenAI's `user` field. +- Otherwise it is the hash of the conversation's stable head: the system prompt plus the first user message. + +A driver mind is seated by `MindMemory::seat` (SERVING-ENGINE §1a) exactly like a resident: +- it keeps its warm KV and pages to RAM or disk; +- it is never anonymous transient traffic, so it never evicts a resident unsaved; +- it is scheduled by the one scheduler (plan goal 9) by its activity temperature, so a busy agent and four residents share the engine fairly. + +The `Responses` API's server-side state is exactly this: the response id names the mind's frontier. + +**Learning (ships at plan step 4, wired now).** +- Every exchange is captured by the existing recorder, with request, tool calls, results and reply, into the same perception stream residents use. +- The corrections are the user's next message, a rejected edit, or a reverted change (§17). +- Genes are selected by what the session is on, and one genome serves drivers and residents. +- `.continuum/scope` decides per repo what may be learned from. +- Credentials and secrets never enter perception, captures or genes. +- A private session trains only on the user's own nodes. + +**What the gateway does not do.** It does not run an agent loop, grade work, or rewrite the agent's prompt. It is the model behind the agent, with memory and learning. + +## Build order (each slice lands with its validator first, and deletes what it replaces) + +| # | Slice | Validator (seconds, no residents) | Live gate | Owner | +|---|---|---|---|---| +| G0 | `Gateway` module on a stable port. The Anthropic adapter moved into it; `http/mod.rs`'s server deleted. | Claude Code's captured requests decode to the same `TextGenerationRequest` as today. | Claude Code on the M5 answers through it. | Fable | +| G1 | OpenAI Chat Completions and Responses adapters, SSE. `GET /v1/models`. | Round-trip fixtures from each agent's captured traffic (Grok Build's `mock_server_tests` show its shapes). | Hermes, opencode and Grok Build each complete a coding task on the M5. | Fable | +| G2 | Session identity: `PageKey::driver`, seated through `MindMemory::seat` (needs §1a step 1). | Replay a captured agent session: prefix reuse per step at least 90%, and no resident evicted unsaved. | **The speed gate:** the same agent and model on the gateway vs stock llama-server, with four residents running. Time per agent step and re-prefilled tokens. | Fable (seat), Codex (scheduling temperature) | +| G3 | Capture to the perception stream, under the scope rules. | A captured session yields perception rows and no secret. | — | Cormac (learning side) | +| G4 | Driver genes: selected by what the session is on, served to the session. | — | **The learning gate** (§17's proof): correct an agent once, restart, give it an unseen related task. It succeeds; without the gene it fails. | Cormac, Fable | + +G0 and G1 can start now. G2 waits on MindMemory's `seat`, and G4 on the residents passing the learning acceptance test (plan pipeline step 3). + +## Measured before and after + +- Per agent step: submit-to-first-token, total time, tokens re-prefilled, and tokens appended. +- Per node: residents' acts per hour with N driver sessions running. Drivers must never starve residents, and residents must never starve drivers. +- Per gene: the acceptance test above, and the same task without the gene. From c218f311a14d24a5d229b4a521099bb8e7eddbf3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 17:31:18 -0500 Subject: [PATCH 03/27] =?UTF-8?q?SERVING-ENGINE=20=C2=A71a:=20the=20MindMe?= =?UTF-8?q?mory=20API,=20with=20Codex's=20seam=20requirements=20in=20its?= =?UTF-8?q?=20types?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PauseReceipt bound to the engine (generation plus verified incarnation), never replayable; seats close before detach or save; pause returns only with no page IO in flight (unresolved IO named and quarantined); receipts separate confirmed saves, named losses and unresolved IO; resume refuses a Stop pause; attach verifies an adopted engine's incarnation; snapshot for the one scheduler. Validator drives the real retirement callers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/http/anthropic_compat.rs | 262 ------------------ .../src/http/local_inference_module.rs | 54 ---- .../COMMAND-CENSUS-AND-CURATION.md | 2 +- docs/architecture/SERVING-ENGINE.md | 75 +++++ 4 files changed, 76 insertions(+), 317 deletions(-) delete mode 100644 core/continuum-core/src/http/anthropic_compat.rs delete mode 100644 core/continuum-core/src/http/local_inference_module.rs diff --git a/core/continuum-core/src/http/anthropic_compat.rs b/core/continuum-core/src/http/anthropic_compat.rs deleted file mode 100644 index be57a53385..0000000000 --- a/core/continuum-core/src/http/anthropic_compat.rs +++ /dev/null @@ -1,262 +0,0 @@ -//! Anthropic Messages API compatible request/response types. -//! -//! Claude Code uses `@anthropic-ai/sdk` which sends `POST /v1/messages` -//! in Anthropic's native format. We translate to/from our TextGenerationRequest. - -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -/// Anthropic Messages API request -#[derive(Debug, Clone, Deserialize)] -pub struct MessagesRequest { - pub model: String, - pub messages: Vec, - pub max_tokens: u32, - #[serde(default)] - pub stream: bool, - #[serde(default)] - pub system: Option, - #[serde(default)] - pub temperature: Option, - #[serde(default)] - pub top_p: Option, - #[serde(default)] - pub top_k: Option, - #[serde(default)] - pub repeat_penalty: Option, - #[serde(default)] - pub stop_sequences: Option>, - #[serde(default)] - pub tools: Option>, - #[serde(default)] - pub tool_choice: Option, - #[serde(default)] - pub metadata: Option, -} - -/// System content — can be a string or array of content blocks -#[derive(Debug, Clone, Deserialize)] -#[serde(untagged)] -pub enum SystemContent { - Text(String), - Blocks(Vec), -} - -#[derive(Debug, Clone, Deserialize)] -pub struct SystemBlock { - #[serde(rename = "type")] - pub block_type: String, - pub text: String, -} - -impl SystemContent { - pub fn as_text(&self) -> String { - match self { - SystemContent::Text(s) => s.clone(), - SystemContent::Blocks(blocks) => blocks - .iter() - .map(|b| b.text.as_str()) - .collect::>() - .join("\n"), - } - } -} - -/// Anthropic message (role + content) -#[derive(Debug, Clone, Deserialize)] -pub struct AnthropicMessage { - pub role: String, - pub content: AnthropicContent, -} - -/// Content can be a plain string or array of content blocks -#[derive(Debug, Clone, Deserialize)] -#[serde(untagged)] -pub enum AnthropicContent { - Text(String), - Blocks(Vec), -} - -impl AnthropicContent { - /// Extract plain text from content (ignoring tool blocks) - pub fn as_text(&self) -> String { - match self { - AnthropicContent::Text(s) => s.clone(), - AnthropicContent::Blocks(blocks) => blocks - .iter() - .filter_map(|b| { - if let ContentBlock::Text { text } = b { - Some(text.as_str()) - } else { - None - } - }) - .collect::>() - .join("\n"), - } - } -} - -/// Content block variants -#[derive(Debug, Clone, Deserialize)] -#[serde(tag = "type")] -pub enum ContentBlock { - #[serde(rename = "text")] - Text { text: String }, - #[serde(rename = "tool_use")] - ToolUse { - id: String, - name: String, - input: Value, - }, - #[serde(rename = "tool_result")] - ToolResult { - tool_use_id: String, - content: Value, - #[serde(default)] - is_error: Option, - }, - #[serde(rename = "image")] - Image { source: Value }, -} - -// ─── Response Types ────────────────────────────────────────────────────────── - -/// Non-streaming response -#[derive(Debug, Clone, Serialize)] -pub struct MessagesResponse { - pub id: String, - #[serde(rename = "type")] - pub response_type: String, - pub role: String, - pub content: Vec, - pub model: String, - pub stop_reason: Option, - pub stop_sequence: Option, - pub usage: Usage, -} - -#[derive(Debug, Clone, Serialize)] -pub struct ResponseContentBlock { - #[serde(rename = "type")] - pub block_type: String, - pub text: String, -} - -#[derive(Debug, Clone, Serialize)] -pub struct Usage { - pub input_tokens: u64, - pub output_tokens: u64, -} - -// ─── SSE Event Types ───────────────────────────────────────────────────────── - -/// Build SSE events for a complete response (single burst, not token-by-token). -/// -/// Phase 1: Return full text as one SSE burst. -/// Phase 2 (future): Token-by-token streaming from inference loop callback. -pub fn build_sse_events(response: &MessagesResponse) -> Vec { - let mut events = Vec::new(); - - // message_start - events.push(SseEvent { - event: "message_start".to_string(), - data: serde_json::json!({ - "type": "message_start", - "message": { - "id": response.id, - "type": "message", - "role": "assistant", - "content": [], - "model": response.model, - "stop_reason": null, - "stop_sequence": null, - "usage": { - "input_tokens": response.usage.input_tokens, - "output_tokens": 0 - } - } - }), - }); - - // For each content block - for (idx, block) in response.content.iter().enumerate() { - // content_block_start - events.push(SseEvent { - event: "content_block_start".to_string(), - data: serde_json::json!({ - "type": "content_block_start", - "index": idx, - "content_block": { - "type": "text", - "text": "" - } - }), - }); - - // content_block_delta (full text in one delta) - events.push(SseEvent { - event: "content_block_delta".to_string(), - data: serde_json::json!({ - "type": "content_block_delta", - "index": idx, - "delta": { - "type": "text_delta", - "text": block.text - } - }), - }); - - // content_block_stop - events.push(SseEvent { - event: "content_block_stop".to_string(), - data: serde_json::json!({ - "type": "content_block_stop", - "index": idx - }), - }); - } - - // message_delta - events.push(SseEvent { - event: "message_delta".to_string(), - data: serde_json::json!({ - "type": "message_delta", - "delta": { - "stop_reason": response.stop_reason, - "stop_sequence": response.stop_sequence - }, - "usage": { - "output_tokens": response.usage.output_tokens - } - }), - }); - - // message_stop - events.push(SseEvent { - event: "message_stop".to_string(), - data: serde_json::json!({ - "type": "message_stop" - }), - }); - - events -} - -/// SSE event for serialization -#[derive(Debug, Clone)] -pub struct SseEvent { - pub event: String, - pub data: Value, -} - -impl SseEvent { - /// Format as SSE wire format - pub fn to_sse_string(&self) -> String { - format!( - "event: {}\ndata: {}\n\n", - self.event, - serde_json::to_string(&self.data).unwrap_or_default() - ) - } -} diff --git a/core/continuum-core/src/http/local_inference_module.rs b/core/continuum-core/src/http/local_inference_module.rs deleted file mode 100644 index 9905d82cf4..0000000000 --- a/core/continuum-core/src/http/local_inference_module.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! The `sentinel/local-inference-*` commands: they report and start THIS crate's local -//! inference HTTP server (`super::port` / `super::start_if_needed`), so they live beside it. -//! The command names are unchanged. The longer prefix wins over the sentinel module's -//! `sentinel/` (the registry routes longest-match-first). - -use async_trait::async_trait; -use serde_json::{json, Value}; - -use crate::runtime::{CommandResult, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; - -pub struct LocalInferenceModule; - -fn endpoint(port: u16) -> Value { - json!({ "success": true, "port": port, "url": format!("http://127.0.0.1:{}", port) }) -} - -#[async_trait] -impl ServiceModule for LocalInferenceModule { - fn config(&self) -> ModuleConfig { - ModuleConfig { - name: "local-inference-http", - priority: ModulePriority::Normal, - command_prefixes: &["sentinel/local-inference-"], - event_subscriptions: &[], - needs_dedicated_thread: false, - max_concurrency: 0, - tick_interval: None, - } - } - - async fn initialize(&self, _ctx: &ModuleContext) -> Result<(), String> { - Ok(()) - } - - async fn handle_command(&self, command: &str, _params: Value) -> Result { - match command { - "sentinel/local-inference-port" => Ok(CommandResult::Json(match super::port().await { - Some(port) => endpoint(port), - None => json!({ "success": false, "error": "HTTP inference server not started" }), - })), - "sentinel/local-inference-start" => { - Ok(CommandResult::Json(match super::start_if_needed().await { - Ok(port) => endpoint(port), - Err(e) => json!({ "success": false, "error": e }), - })) - } - _ => Err(format!("Unknown local-inference command: {command}")), - } - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } -} diff --git a/docs/architecture/COMMAND-CENSUS-AND-CURATION.md b/docs/architecture/COMMAND-CENSUS-AND-CURATION.md index 4994f54cc7..38d66d8985 100644 --- a/docs/architecture/COMMAND-CENSUS-AND-CURATION.md +++ b/docs/architecture/COMMAND-CENSUS-AND-CURATION.md @@ -105,7 +105,7 @@ Of the 50 `cognition/*` arms, ~30 exist **only** because TypeScript used to driv - inference-coordinator: no commands (bootstrap) — nothing to migrate. ### genome-loop cluster (37) → KEEP, collapse sentinel aliases -- **KEEP:** forge/run,train,train-status,export,health,probe,decide; dataset/import-csv,from-turns,from-captures,import-realclasseval,list,info; genome/job-create,job-status,job-cancel; genome/training-trigger/submit,flush,status; plasticity/analyze,compact,compress,topology,pipeline; sentinel/await,status,list,cancel,resume,list-checkpoints,extend-budget,approve,logs/{list,read,tail},local-inference-port,local-inference-start. +- **KEEP:** forge/run,train,train-status,export,health,probe,decide; dataset/import-csv,from-turns,from-captures,import-realclasseval,list,info; genome/job-create,job-status,job-cancel; genome/training-trigger/submit,flush,status; plasticity/analyze,compact,compress,topology,pipeline; sentinel/await,status,list,cancel,resume,list-checkpoints,extend-budget,approve,logs/{list,read,tail}; gateway/status,env (the driver gateway replaced sentinel/local-inference-port,start, 2026-10-27). - **DELETE aliases:** sentinel/execute, sentinel/pipeline (→sentinel/run, finding #6). - **Receives (finding #3):** genome/activate-skill, genome/state, genome/evict, genome/coverage, genome/select-model from cognition/*. - **Access:** forge/train, genome/job-*, dataset/* → Privileged; reads (status/list/info/probe) → AiSafe. diff --git a/docs/architecture/SERVING-ENGINE.md b/docs/architecture/SERVING-ENGINE.md index a0442f9061..80ac12db40 100644 --- a/docs/architecture/SERVING-ENGINE.md +++ b/docs/architecture/SERVING-ENGINE.md @@ -90,6 +90,79 @@ Joel: "you can't get anything to work unless there is one daemon and centralized - public `take_resident` / `forget_resident` / `plan_paging` / `note_saved` / `note_page_lost`; - `trim_page_store_after_save`, which has no caller; the page store's trim moves into the owner or is deleted. +**The API (published for the callers' migration; Codex's review of 2bd37de22 is built into the types).** + +```rust +/// Which engine process a receipt or seat belongs to: its generation, and for an adopted +/// engine the OS incarnation (pid, start time) verified independently of any launch handle. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct EngineIdentity { pub generation: Uuid, pub incarnation: Option<(u32, u64)> } + +pub enum Purpose { Turn, WarmAhead, Transient } + +/// Where a seated mind's KV came from. Every cold seat names why. +pub enum Resumed { Resident, Restored, Cold(ColdCause) } +pub enum ColdCause { FirstVisit, PageRefused, DiscardedUnsaved(LossCause), Quarantined } + +/// RAII. The slot is pinned while the seat lives. `completed` commits the mind's attribution +/// (and her tail size, the eviction price); a seat dropped without it detaches the slot. +/// A Transient seat never holds a mind: it borrows the cheapest resident's slot, which is +/// saved (confirmed) before the seat is granted, and is not a driver session (drivers seat +/// as Turn with `PageKey::driver`). +pub struct Seat { /* slot, key, resumed, engine */ } +impl Seat { + pub fn slot(&self) -> u32; + pub fn resumed(&self) -> &Resumed; + pub fn engine(&self) -> EngineIdentity; + pub fn completed(self, tail_tokens: u64); +} + +pub enum PauseWhy { Relaunch, Academy, Idle, AdoptedRetirement, Stop } +pub enum LossCause { SaveFailed(String), DeadlineSpent, EngineExited, PagingUncertain } + +/// Not Clone, not serializable: one pause, one consumer. Bound to the engine it paused. +pub struct PauseReceipt { /* engine, why, ... */ } +impl PauseReceipt { + pub fn engine(&self) -> EngineIdentity; + pub fn saved(&self) -> &[PageKey]; // confirmed by the engine's ack + pub fn lost(&self) -> &[(PageKey, LossCause)]; // named, and recorded for the successor + pub fn unresolved(&self) -> &[PageKey]; // IO whose outcome is unknown: quarantined +} + +pub enum Attach { Launched, Adopted { incarnation: (u32, u64) } } + +impl MindMemory { + /// The only way onto a slot. Refused while paused, or once the deadline passes. + pub async fn seat(&self, key: Option, purpose: Purpose, deadline: Instant) -> Result; + + /// Close seating, wait for every open seat to close (a seat closes BEFORE its slot is + /// detached or saved), then save every resident with a confirmed save. Returns only when + /// no page IO it started is in flight: IO still running at the deadline is listed + /// `unresolved` and the endpoint is quarantined, so a retirement can never race it. + pub async fn pause(&self, why: PauseWhy, deadline: Instant) -> Result; + + /// Reopen the SAME engine (an academy batch done). Refused for a receipt of another + /// engine, for a quarantined endpoint, and for a Stop pause (an operator stop stays stopped). + pub fn resume(&self, receipt: PauseReceipt) -> Result<(), ResumeRefused>; + + /// The engine may now be killed. Consumes the receipt; its losses go to the ledger the + /// successor reads. Refused for a receipt whose engine is not the current one. + pub fn retire(&self, receipt: PauseReceipt) -> Result; + + /// Boot, relaunch or adopt: bind a new engine and load the one ledger by the one rule + /// (page-format fingerprint; residents in place only for an Adopted engine whose + /// incarnation matches the ledger's). Seats nothing. + pub async fn attach(&self, engine: EngineIdentity, how: Attach) -> Result; + + /// A page whose KV no longer means what it did is never offered again. + pub fn forget(&self, key: PageKey, why: ForgetWhy); + + /// For the one scheduler (G2, Codex): per mind, residency, frontier and last activity, + /// residents and drivers alike, as a watched snapshot. + pub fn snapshot(&self) -> tokio::sync::watch::Receiver; +} +``` + **Validator (S0 for this owner).** `turn_admission/tests/lifecycle.rs` already runs a fake engine whose slots hold `mind:tokens`, through turns, a stop and a boot. It moves to `MindMemory`'s own tests and gains: - a relaunch; - an adoption; @@ -97,6 +170,8 @@ Joel: "you can't get anything to work unless there is one daemon and centralized - an in-place gene change; - transient borrowing. +The validator drives the actual retirement callers (relaunch, academy, idle, adopted retirement, stop) through `pause` and then `retire` or `resume`, never the checkpoint helper alone, including a second stop after an adoption (Codex). + Each scenario asserts where every mind resumes, in seconds, before any live read. **Order and owners.** From f400559680c89532bdd2b409bdcf6eaae9a5f6a4 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 17:40:58 -0500 Subject: [PATCH 04/27] continuum-gateway: one door every external agent calls (DRIVER-GATEWAY G0-G1) Anthropic Messages (Claude Code), OpenAI Chat Completions (Hermes, opencode) and OpenAI Responses (Grok Build, Codex CLI) as adapters holding only their diff over the engine's one request and stream; real SSE streaming; tools pass through both ways; GET /v1/models; a stable port (CONTINUUM_GATEWAY_PORT, default 8976); gateway/status and gateway/env. Replaces continuum-core/src/http's Anthropic-only endpoint, which dropped every tool and faked streaming (758 lines deleted with its commands). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-core/Cargo.toml | 1 + core/continuum-core/src/http/mod.rs | 442 +----------------- .../src/ipc/start_server/closing_modules.rs | 4 +- core/continuum-gateway/Cargo.toml | 16 + core/continuum-gateway/src/lib.rs | 17 + core/continuum-gateway/src/module.rs | 92 ++++ core/continuum-gateway/src/route.rs | 59 +++ core/continuum-gateway/src/server.rs | 100 ++++ core/continuum-gateway/src/wire/anthropic.rs | 214 +++++++++ core/continuum-gateway/src/wire/chat.rs | 224 +++++++++ core/continuum-gateway/src/wire/mod.rs | 140 ++++++ core/continuum-gateway/src/wire/responses.rs | 249 ++++++++++ core/continuum-gateway/src/wire/tests.rs | 153 ++++++ 13 files changed, 1269 insertions(+), 442 deletions(-) create mode 100644 core/continuum-gateway/Cargo.toml create mode 100644 core/continuum-gateway/src/lib.rs create mode 100644 core/continuum-gateway/src/module.rs create mode 100644 core/continuum-gateway/src/route.rs create mode 100644 core/continuum-gateway/src/server.rs create mode 100644 core/continuum-gateway/src/wire/anthropic.rs create mode 100644 core/continuum-gateway/src/wire/chat.rs create mode 100644 core/continuum-gateway/src/wire/mod.rs create mode 100644 core/continuum-gateway/src/wire/responses.rs create mode 100644 core/continuum-gateway/src/wire/tests.rs diff --git a/core/continuum-core/Cargo.toml b/core/continuum-core/Cargo.toml index f610f046dc..3f9f00ba3d 100644 --- a/core/continuum-core/Cargo.toml +++ b/core/continuum-core/Cargo.toml @@ -71,6 +71,7 @@ continuum-engine = { path = "../continuum-engine" } continuum-service = { path = "../continuum-service" } # each resident's window judged, and the alarm the beacon carries (card 1c157668) continuum-models = { path = "../continuum-models" } continuum-serving = { path = "../continuum-serving" } +continuum-gateway = { path = "../continuum-gateway" } continuum-embedding = { path = "../continuum-embedding" } continuum-store = { path = "../continuum-store" } # the data layer and its commands (card 2709ec6d) continuum-grid = { path = "../continuum-grid" } # grid discovery, trust and routing with their commands (plan phase 2) diff --git a/core/continuum-core/src/http/mod.rs b/core/continuum-core/src/http/mod.rs index bd775c671b..b7478592b8 100644 --- a/core/continuum-core/src/http/mod.rs +++ b/core/continuum-core/src/http/mod.rs @@ -1,442 +1,4 @@ -//! HTTP server for Anthropic-compatible local inference endpoint. -//! -//! Claude Code sends `POST /v1/messages` in Anthropic format when -//! `ANTHROPIC_BASE_URL` is set. This module serves that endpoint, -//! routing through the SAME `AdapterRegistry::select()` path as the -//! default persona chat — DMR / Vulkan GPU adapters preferred, -//! hard-fails when no GPU adapter can serve the model. -//! -//! GPU-always contract (matches Joel's "no silent CPU fallback" rule): -//! - This endpoint NEVER silently falls back to CandleAdapter for -//! inference. Candle's role is LoRA training on GPU, not chat. -//! - If select() returns None, the response is 503 with a remediation -//! hint (pull model into DMR, or install the right GPU backend). -//! - Historic note: an earlier version had explicit -//! `or_else(|| select(Some(PROVIDER_CANDLE_QUANTIZED), ...))` chained -//! onto select(), which bypassed the GPU device check by hitting -//! tier-1 explicit-provider match. Removed because Candle inference -//! is currently slower than CPU+DMR and shipping it as a silent -//! fallback gave users a "Continuum feels broken" first-chat tier -//! surface even when the right GPU backend was available. -//! -//! Architecture: -//! - Axum HTTP server on dynamic port (127.0.0.1:0) -//! - Shared GLOBAL_REGISTRY from AIProviderModule (same adapters) -//! - Translates Anthropic request → TextGenerationRequest → response -//! - Supports both streaming (SSE) and non-streaming responses -//! -//! Lifecycle: -//! - Started on first local-claude-code request via `start_if_needed()` -//! - Runs as tokio task, shared across all sentinels -//! - Port stored in SERVER_PORT for IPC query +//! The core's own HTTP surfaces. External agents call the driver gateway +//! (`continuum-gateway`, docs/architecture/DRIVER-GATEWAY.md), not this module. pub mod desktop; - -mod local_inference_module; -pub use local_inference_module::LocalInferenceModule; - -pub mod anthropic_compat; - -use anthropic_compat::{ - build_sse_events, AnthropicContent, ContentBlock, MessagesRequest, MessagesResponse, - ResponseContentBlock, Usage, -}; - -use crate::ai::{ - adapter::InferenceDevice, ActiveAdapterRequest, ChatMessage, MessageContent, - TextGenerationRequest, -}; - -use axum::{ - http::StatusCode, - response::{IntoResponse, Json}, - routing::{get, post}, - Router, -}; -use once_cell::sync::Lazy; -use serde_json::{json, Value}; -use std::sync::Arc; -use tokio::sync::{OnceCell, RwLock}; -use tower_http::cors::CorsLayer; - -/// Global server port — set after bind, read by IPC command -static SERVER_PORT: Lazy>>> = Lazy::new(|| Arc::new(RwLock::new(None))); - -/// Ensure the server is started exactly once -static SERVER_INIT: OnceCell<()> = OnceCell::const_new(); - -/// Get the current server port (None if not started) -pub async fn port() -> Option { - *SERVER_PORT.read().await -} - -/// Start the HTTP server if not already running. -/// -/// Binds to 127.0.0.1:0 (dynamic port), stores the assigned port. -/// Returns the port number. -pub async fn start_if_needed() -> Result { - SERVER_INIT - .get_or_try_init(|| async { start_server().await }) - .await - .map_err(|e| format!("HTTP server failed to start: {}", e))?; - - port() - .await - .ok_or_else(|| "HTTP server started but port not set".to_string()) -} - -/// Internal: start the axum server -async fn start_server() -> Result<(), String> { - let app = Router::new() - .route("/v1/messages", post(messages_handler)) - .route("/health", get(health_handler)) - .layer(CorsLayer::permissive()) - .with_state(()); - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .map_err(|e| format!("Failed to bind HTTP server: {}", e))?; - - let addr = listener - .local_addr() - .map_err(|e| format!("Failed to get local addr: {}", e))?; - - let port = addr.port(); - *SERVER_PORT.write().await = Some(port); - - eprintln!( - "[http] Anthropic-compat inference server started on http://127.0.0.1:{}", - port - ); - - // Spawn the server as a background task - tokio::spawn(async move { - if let Err(e) = axum::serve(listener, app).await { - eprintln!("[http] Server error: {}", e); - } - }); - - Ok(()) -} - -/// Health check endpoint -async fn health_handler() -> impl IntoResponse { - Json(json!({ - "status": "ok", - "type": "continuum-local-inference", - "api": "anthropic-compat" - })) -} - -/// POST /v1/messages — Anthropic Messages API handler -/// -/// Pass-through proxy: converts Anthropic format → internal format, routes to -/// the selected adapter. The adapter/backend validates context length and returns -/// errors if input exceeds the model's capacity. No artificial truncation here — -/// the model's own definition is the single source of truth for its limits. -/// Anthropic-shaped 500 body: one place for the error envelope. -fn api_error(message: String) -> (StatusCode, Json) { - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({ - "type": "error", - "error": { "type": "api_error", "message": message } - })), - ) -} - -async fn messages_handler( - Json(req): Json, -) -> Result)> { - let start = std::time::Instant::now(); - - // Resolve model spec → provider + model + optional LoRA adapter - let spec = parse_model_spec(&req.model); - - // Resolve the adapter - let registry = crate::ai::adapter::global_registry(); - let registry_guard = registry.read().await; - - // GPU-always contract: route through select() with the requested - // provider/model, accept what select() returns, fail loud if - // nothing matches. NO silent fallback to Candle (or anything CPU) - // — Candle is for LoRA training on GPU, not for inference. See the - // module-level docstring above for the historic note on why the - // explicit candle fallback chain was removed. - let (provider_id, adapter) = registry_guard - .select(Some(&spec.provider), spec.model.as_deref(), InferenceDevice::default()) - .ok_or_else(|| { - let available = registry_guard.available(); - ( - StatusCode::SERVICE_UNAVAILABLE, - Json(json!({ - "type": "error", - "error": { - "type": "overloaded_error", - "message": format!( - "No GPU-capable adapter supports model '{}' (provider='{}'). \ - Available adapters: {:?}. \ - Pull the model into Docker Model Runner (`docker model pull `) \ - or install the right GPU backend (Metal on Mac via Docker Desktop AI \ - toggle, CUDA on Linux/WSL2 via nvidia-container-toolkit + Docker \ - Desktop AI toggle). Falling back to Candle (CPU-tier speed) was \ - intentionally disabled — see docs/SETUP.md for per-OS install steps.", - spec.model.as_deref().unwrap_or("(unspecified)"), - spec.provider, - available - ) - } - })), - ) - })?; - - // Log request sizes for debugging - let context_window = adapter - .capabilities() - .max_context_window - .map_or_else(|| "undeclared".to_string(), |w| w.to_string()); - let system_chars = req.system.as_ref().map(|s| s.as_text().len()).unwrap_or(0); - let msg_chars: usize = req.messages.iter().map(|m| m.content.as_text().len()).sum(); - let tools_count = req.tools.as_ref().map(|t| t.len()).unwrap_or(0); - eprintln!( - "[http] Request: model={}, context_window={}, system={}chars, messages={}chars ({}msgs), tools={}, max_tokens={}", - req.model, - context_window, - system_chars, - msg_chars, - req.messages.len(), - tools_count, - req.max_tokens - ); - - // Convert Anthropic messages → internal format (no truncation — pass through faithfully) - let system_prompt = req.system.as_ref().map(|s| s.as_text()); - let messages = convert_messages(&req.messages); - - // Build LoRA adapter request if persona was specified - let active_adapters = spec.adapter.as_ref().map(|name| { - vec![ActiveAdapterRequest { - name: name.clone(), - path: String::new(), // CandleAdapter resolves from AdapterStore - domain: "coding".to_string(), - scale: 1.0, - }] - }); - - let gen_request = TextGenerationRequest { - messages, - system_prompt, - model: spec.model.clone(), - provider: Some(spec.provider.clone()), - temperature: req.temperature, - max_tokens: Some(req.max_tokens), - top_p: req.top_p, - top_k: req.top_k, - repeat_penalty: req.repeat_penalty, - frequency_penalty: None, - repeat_last_n: None, - stop_sequences: req.stop_sequences.clone(), - tools: None, // Tool calls handled by Claude Code, not the local model - tail_tools: None, - view_messages: None, - tool_choice: None, - response_format: None, - active_adapters, - request_id: Some(format!( - "msg_{}", - uuid::Uuid::new_v4().to_string().replace('-', "") - )), - user_id: None, - room_id: None, - purpose: Some("local-coding-agent".to_string()), - // External coding-agent caller (not a persona-owned conversation). - persona_id: None, - turn_bound: None, - }; - - let response = adapter - .generate_text(gen_request) - .await - .map_err(|e| api_error(format!("Inference error: {}", e)))?; - - let response_time_ms = start.elapsed().as_millis() as u64; - let request_id = response.request_id.clone(); - - // Build Anthropic-format response - let anthropic_response = MessagesResponse { - id: request_id, - response_type: "message".to_string(), - role: "assistant".to_string(), - content: vec![ResponseContentBlock { - block_type: "text".to_string(), - text: response.text.clone(), - }], - model: response.model.clone(), - stop_reason: Some(format!("{}", response.finish_reason)), - stop_sequence: None, - usage: Usage { - input_tokens: response.usage.input_tokens as u64, - output_tokens: response.usage.output_tokens as u64, - }, - }; - - eprintln!( - "[http] {} → {} ({}ms, {} in / {} out tokens)", - req.model, - provider_id, - response_time_ms, - response.usage.input_tokens, - response.usage.output_tokens - ); - - if req.stream { - // SSE streaming response (single burst for now — full text in one event sequence) - let events = build_sse_events(&anthropic_response); - let body = events.iter().map(|e| e.to_sse_string()).collect::(); - - Ok(axum::response::Response::builder() - .status(StatusCode::OK) - .header("content-type", "text/event-stream") - .header("cache-control", "no-cache") - .body(axum::body::Body::from(body)) - .map_err(|e| api_error(format!("SSE response build error: {e}")))? - .into_response()) - } else { - // Non-streaming JSON response - let value = serde_json::to_value(&anthropic_response) - .map_err(|e| api_error(format!("Response serialization error: {e}")))?; - Ok(Json(value).into_response()) - } -} - -/// Parsed model specification from the Anthropic API request. -/// -/// Model strings map as follows: -/// "local/default" → provider=candle, model=None (base model), adapter=None -/// "local/helper" → provider=candle, model=None (base model), adapter=Some("helper") -/// "candle" → provider=candle, model=None (base model), adapter=None -/// "meta-llama/Llama-3.2" → provider=candle, model=Some("meta-llama/Llama-3.2"), adapter=None -/// -/// The "local/" prefix is the convention for routing through Candle. -/// Anything after "local/" that isn't "default" is treated as a persona -/// name whose LoRA adapter should be activated. -struct ModelSpec { - provider: String, - /// Explicit model name (None = use adapter's default_model) - model: Option, - /// LoRA adapter to activate (persona name) - adapter: Option, -} - -const LOCAL_PREFIX: &str = "local/"; -const DEFAULT_PERSONA: &str = "default"; -/// Provider ID for quantized GGUF backend (large context, no LoRA). -const PROVIDER_CANDLE_QUANTIZED: &str = "candle-q"; -/// Provider ID for safetensors BF16 backend (LoRA support, smaller context). -const PROVIDER_CANDLE_SAFETENSORS: &str = "candle"; - -fn parse_model_spec(raw: &str) -> ModelSpec { - if let Some(persona) = raw.strip_prefix(LOCAL_PREFIX) { - if persona == DEFAULT_PERSONA || persona.is_empty() { - // No LoRA needed → use quantized (larger context window) - ModelSpec { - provider: PROVIDER_CANDLE_QUANTIZED.to_string(), - model: None, - adapter: None, - } - } else { - // Persona specified → use safetensors (LoRA support) - ModelSpec { - provider: PROVIDER_CANDLE_SAFETENSORS.to_string(), - model: None, - adapter: Some(persona.to_string()), - } - } - } else if raw == "candle" || raw == "candle-q" { - ModelSpec { - provider: raw.to_string(), - model: None, - adapter: None, - } - } else { - // Treat as explicit model name (e.g. "meta-llama/Llama-3.2-3B-Instruct") - // Default to quantized for large context - ModelSpec { - provider: PROVIDER_CANDLE_QUANTIZED.to_string(), - model: Some(raw.to_string()), - adapter: None, - } - } -} - -/// Convert Anthropic messages to our ChatMessage format -fn convert_messages(messages: &[anthropic_compat::AnthropicMessage]) -> Vec { - messages - .iter() - .map(|msg| { - let content = match &msg.content { - AnthropicContent::Text(s) => MessageContent::Text(s.clone()), - AnthropicContent::Blocks(blocks) => { - // If all blocks are text, flatten to single text - let all_text = blocks - .iter() - .all(|b| matches!(b, ContentBlock::Text { .. })); - if all_text { - let text = blocks - .iter() - .filter_map(|b| { - if let ContentBlock::Text { text } = b { - Some(text.as_str()) - } else { - None - } - }) - .collect::>() - .join("\n"); - MessageContent::Text(text) - } else { - // Mixed content — convert to Parts - let parts = blocks - .iter() - .filter_map(|b| match b { - ContentBlock::Text { text } => { - Some(crate::ai::ContentPart::Text { text: text.clone() }) - } - ContentBlock::ToolUse { id, name, input } => { - Some(crate::ai::ContentPart::ToolUse { - id: id.clone(), - name: name.clone(), - input: input.clone(), - }) - } - ContentBlock::ToolResult { - tool_use_id, - content, - is_error, - } => { - let content_str = match content { - Value::String(s) => s.clone(), - other => serde_json::to_string(other).unwrap_or_default(), - }; - Some(crate::ai::ContentPart::ToolResult { - tool_use_id: tool_use_id.clone(), - content: content_str, - is_error: *is_error, - }) - } - _ => None, - }) - .collect(); - MessageContent::Parts(parts) - } - } - }; - - ChatMessage { - role: msg.role.clone(), - content, - name: None, - } - }) - .collect() -} diff --git a/core/continuum-core/src/ipc/start_server/closing_modules.rs b/core/continuum-core/src/ipc/start_server/closing_modules.rs index c12eb97430..f1e69d702b 100644 --- a/core/continuum-core/src/ipc/start_server/closing_modules.rs +++ b/core/continuum-core/src/ipc/start_server/closing_modules.rs @@ -16,8 +16,8 @@ pub(super) fn register_closing_modules( let sentinel_module = Arc::new(SentinelModule::new()); runtime.register(sentinel_module.clone()); continuum_sentinel::register_for_shutdown(sentinel_module); - // The local-inference HTTP endpoint commands (sentinel/local-inference-*) live beside http/. - runtime.register(Arc::new(crate::http::LocalInferenceModule)); + // The driver gateway: the one door external agents call (docs/architecture/DRIVER-GATEWAY.md). + runtime.register(Arc::new(continuum_gateway::GatewayModule::default())); // PlasticityModule: Adaptive neural plasticity optimization engine // Provides plasticity/analyze, plasticity/compact, plasticity/topology diff --git a/core/continuum-gateway/Cargo.toml b/core/continuum-gateway/Cargo.toml new file mode 100644 index 0000000000..107a43e404 --- /dev/null +++ b/core/continuum-gateway/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "continuum-gateway" +version = "0.1.0" +edition = "2021" +description = "The driver gateway (docs/architecture/DRIVER-GATEWAY.md): one door every external agent calls, wire formats as adapters over the one engine." + +[dependencies] +continuum-engine = { path = "../continuum-engine" } +continuum-base = { path = "../continuum-base" } +async-trait = "0.1" +axum = "0.8" +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +tokio-stream.workspace = true +uuid.workspace = true diff --git a/core/continuum-gateway/src/lib.rs b/core/continuum-gateway/src/lib.rs new file mode 100644 index 0000000000..4ec83f3557 --- /dev/null +++ b/core/continuum-gateway/src/lib.rs @@ -0,0 +1,17 @@ +//! The driver gateway: one door every external agent calls (docs/architecture/DRIVER-GATEWAY.md). +//! +//! Claude Code, Codex CLI, Grok Build, Hermes and opencode each speak one of three APIs. +//! Each API is an adapter here holding only its diff ([`wire`]): it decodes the agent's body +//! into the engine's one request and encodes the engine's stream back. Selection and +//! generation go through the same adapter registry the residents use ([`route`]). Tools +//! pass straight through: the agent runs its own tools. +//! +//! Slices G0-G1. A session becomes a driver mind seated by `MindMemory` in G2; until then a +//! call is admitted as anonymous traffic. + +mod module; +mod route; +mod server; +mod wire; + +pub use module::GatewayModule; diff --git a/core/continuum-gateway/src/module.rs b/core/continuum-gateway/src/module.rs new file mode 100644 index 0000000000..a6704fd26f --- /dev/null +++ b/core/continuum-gateway/src/module.rs @@ -0,0 +1,92 @@ +//! The gateway as a `ServiceModule`: one listener on a stable port, and the commands that +//! report it and print what each agent sets. + +use async_trait::async_trait; +use continuum_engine::runtime::{CommandResult, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; +use serde_json::{json, Value}; + +/// The gateway's port when nothing configures one: beside the desktop's 8975. +const DEFAULT_PORT: u16 = 8976; + +pub struct GatewayModule { + port: std::sync::OnceLock, +} + +impl Default for GatewayModule { + fn default() -> Self { + Self { port: std::sync::OnceLock::new() } + } +} + +/// `CONTINUUM_GATEWAY_PORT` from the environment, then config.env, then the default. +fn configured_port() -> Result { + match std::env::var("CONTINUUM_GATEWAY_PORT").ok().or_else(|| continuum_base::config_env::read("CONTINUUM_GATEWAY_PORT")) { + Some(raw) => raw.trim().parse().map_err(|_| format!("CONTINUUM_GATEWAY_PORT={raw} is not a port")), + None => Ok(DEFAULT_PORT), + } +} + +/// What each agent sets to call the gateway at `base`. +fn env(base: &str) -> Value { + json!({ + "claude-code": {"ANTHROPIC_BASE_URL": base, "ANTHROPIC_AUTH_TOKEN": "continuum"}, + "codex": {"OPENAI_BASE_URL": format!("{base}/v1")}, + "grok-build": {"--xai-api-base-url": format!("{base}/v1")}, + "hermes": {"OPENAI_BASE_URL": format!("{base}/v1")}, + "opencode": {"baseURL": format!("{base}/v1")}, + }) +} + +#[async_trait] +impl ServiceModule for GatewayModule { + fn config(&self) -> ModuleConfig { + ModuleConfig { + name: "gateway", + priority: ModulePriority::Normal, + command_prefixes: &["gateway/"], + event_subscriptions: &[], + needs_dedicated_thread: false, + max_concurrency: 0, + tick_interval: None, + } + } + + /// Bind on loopback; a node that cannot bind says why and serves its residents anyway. + async fn initialize(&self, _ctx: &ModuleContext) -> Result<(), String> { + let port = configured_port()?; + let listener = match tokio::net::TcpListener::bind(("127.0.0.1", port)).await { + Ok(listener) => listener, + Err(error) => { + continuum_base::probe!(class = "gateway.unbound", port = port as u64, error = %error, + "the gateway could not bind its port; agents cannot reach this node until it does"); + return Ok(()); + } + }; + let _ = self.port.set(port); + continuum_base::probe!(class = "gateway.listening", port = port as u64, "agents can call this node's engine"); + tokio::spawn(async move { + if let Err(error) = axum::serve(listener, crate::server::router()).await { + continuum_base::probe!(class = "gateway.stopped", error = %error, "the gateway's listener ended"); + } + }); + Ok(()) + } + + async fn handle_command(&self, command: &str, _params: Value) -> Result { + let base = self.port.get().map(|port| format!("http://127.0.0.1:{port}")); + match command { + "gateway/status" => Ok(CommandResult::Json(json!({ + "listening": base.is_some(), "url": base, "models": crate::route::served_models().await, + }))), + "gateway/env" => match base { + Some(base) => Ok(CommandResult::Json(env(&base))), + None => Err("the gateway is not listening; see probe gateway.unbound".into()), + }, + _ => Err(format!("unknown gateway command: {command}")), + } + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } +} diff --git a/core/continuum-gateway/src/route.rs b/core/continuum-gateway/src/route.rs new file mode 100644 index 0000000000..3249ea936e --- /dev/null +++ b/core/continuum-gateway/src/route.rs @@ -0,0 +1,59 @@ +//! One route from a decoded call to the engine: select the adapter the residents use, then +//! generate. No fallback: an unserved model is refused with what is served. + +use std::sync::Arc; + +use continuum_engine::ai::adapter::{GenerationChunk, InferenceDevice}; +use continuum_engine::ai::{AIProviderAdapter, TextGenerationRequest, TextGenerationResponse}; + +/// Why a call could not be served, as the status an agent understands. +#[derive(Debug)] +pub(crate) enum RouteError { + /// The model named is not served here; carries what is. + UnknownModel { model: String, served: Vec }, + /// The engine refused or failed mid-generation. + Engine(String), +} + +/// The adapter that serves `model` on this node, held without the registry lock. +pub(crate) async fn select(model: &str) -> Result, RouteError> { + let registry = continuum_engine::ai::adapter::global_registry(); + let registry = registry.read().await; + match registry.select_arc(Some("local"), Some(model), InferenceDevice::Auto) { + Some((_, adapter)) => Ok(adapter), + None => Err(RouteError::UnknownModel { model: model.to_owned(), served: served_models_of(®istry) }), + } +} + +/// Every model this node serves, for `GET /v1/models` and for a refusal. +pub(crate) async fn served_models() -> Vec { + let registry = continuum_engine::ai::adapter::global_registry(); + let registry = registry.read().await; + served_models_of(®istry) +} + +fn served_models_of(registry: &continuum_engine::ai::AdapterRegistry) -> Vec { + let mut models: Vec = registry + .available() + .into_iter() + .filter_map(|id| registry.get(id)) + .flat_map(|adapter| adapter.served_model_ids()) + .collect(); + models.sort(); + models.dedup(); + models +} + +/// Generate the whole answer. +pub(crate) async fn generate(adapter: &Arc, request: TextGenerationRequest) -> Result { + adapter.generate_text(request).await.map_err(RouteError::Engine) +} + +/// Generate, sending each chunk to `sink` as the engine decodes it. +pub(crate) async fn stream( + adapter: &Arc, + request: TextGenerationRequest, + sink: tokio::sync::mpsc::UnboundedSender, +) -> Result { + adapter.generate_stream(request, sink).await.map_err(RouteError::Engine) +} diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs new file mode 100644 index 0000000000..28933249c8 --- /dev/null +++ b/core/continuum-gateway/src/server.rs @@ -0,0 +1,100 @@ +//! The one HTTP server: every format's route through the same handler. + +use crate::route::{self, RouteError}; +use crate::wire::{anthropic::Anthropic, chat::Chat, responses::Responses, BadRequest, ErrorKind, Wire}; +use axum::http::StatusCode; +use axum::response::sse::{KeepAlive, Sse}; +use axum::response::{IntoResponse, Json, Response}; +use axum::routing::{get, post}; +use axum::Router; +use serde_json::{json, Value}; + +pub(crate) fn router() -> Router { + Router::new() + .route("/v1/messages", post(serve::)) + .route("/v1/chat/completions", post(serve::)) + .route("/v1/responses", post(serve::)) + .route("/v1/models", get(models)) + .route("/health", get(|| async { Json(json!({"status": "ok", "service": "continuum-gateway"})) })) +} + +/// `GET /v1/models`: what this node serves, in the shape every format's clients read. +async fn models() -> Json { + let data: Vec = route::served_models() + .await + .into_iter() + .map(|id| json!({"id": id, "object": "model", "type": "model", "display_name": id, "owned_by": "continuum"})) + .collect(); + Json(json!({"object": "list", "data": data})) +} + +/// Decode, select, generate, encode: the same for every format. +async fn serve(Json(body): Json) -> Response { + let call = match W::decode(body) { + Ok(call) => call, + Err(BadRequest(why)) => return refuse::(StatusCode::BAD_REQUEST, ErrorKind::InvalidRequest, &why), + }; + let model = call.request.model.clone().unwrap_or_default(); // unwrap_or_default: every decoder requires a model + let adapter = match route::select(&model).await { + Ok(adapter) => adapter, + Err(error) => return refused::(error), + }; + let id = format!("{}_{}", prefix::(), uuid::Uuid::new_v4().simple()); + continuum_base::probe!(class = "gateway.call", wire = W::NAME, model = %model, stream = call.stream, + tools = call.request.tools.as_ref().map_or(0, Vec::len) as u64, messages = call.request.messages.len() as u64, + "an agent's call reached the engine through the gateway"); + if !call.stream { + return match route::generate(&adapter, call.request).await { + Ok(response) => Json(W::answer(&response, &id)).into_response(), + Err(error) => refused::(error), + }; + } + let (chunks, mut received) = tokio::sync::mpsc::unbounded_channel(); + let (events, out) = tokio::sync::mpsc::unbounded_channel(); + tokio::spawn(async move { + let mut encoder = W::streamer(&model, &id); + let generation = tokio::spawn(async move { route::stream(&adapter, call.request, chunks).await }); + let send = |batch: Vec| batch.into_iter().all(|f| events.send(Ok::<_, std::convert::Infallible>(f.into_event())).is_ok()); + if !send(encoder.opened()) { + return; // the agent left; the generation runs to completion and is dropped + } + while let Some(chunk) = received.recv().await { + if !send(encoder.chunk(&chunk)) { + return; + } + } + let closing = match generation.await { + Ok(Ok(response)) => encoder.finished(&response), + Ok(Err(RouteError::Engine(why))) => encoder.failed(&why), + Ok(Err(RouteError::UnknownModel { model, .. })) => encoder.failed(&format!("model `{model}` is not served here")), + Err(join) => encoder.failed(&format!("generation task ended: {join}")), + }; + send(closing); + }); + Sse::new(tokio_stream::wrappers::UnboundedReceiverStream::new(out)).keep_alive(KeepAlive::default()).into_response() +} + +fn refused(error: RouteError) -> Response { + match error { + RouteError::UnknownModel { model, served } => refuse::( + StatusCode::NOT_FOUND, + ErrorKind::NotFound, + &format!("model `{model}` is not served here; served: {}", served.join(", ")), + ), + RouteError::Engine(why) => refuse::(StatusCode::BAD_GATEWAY, ErrorKind::Engine, &why), + } +} + +fn refuse(status: StatusCode, kind: ErrorKind, message: &str) -> Response { + continuum_base::probe!(class = "gateway.refused", wire = W::NAME, status = status.as_u16() as u64, reason = message, + "the gateway refused an agent's call"); + (status, Json(W::error(kind, message))).into_response() +} + +fn prefix() -> &'static str { + match W::NAME { + "anthropic_messages" => "msg", + "openai_responses" => "resp", + _ => "chatcmpl", + } +} diff --git a/core/continuum-gateway/src/wire/anthropic.rs b/core/continuum-gateway/src/wire/anthropic.rs new file mode 100644 index 0000000000..48253d5532 --- /dev/null +++ b/core/continuum-gateway/src/wire/anthropic.rs @@ -0,0 +1,214 @@ +//! Anthropic Messages (`POST /v1/messages`): Claude Code, via `ANTHROPIC_BASE_URL`. + +use super::{event, input_schema, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use continuum_engine::ai::adapter::GenerationChunk; +use continuum_engine::ai::types::ImageInput; +use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; +use serde_json::{json, Value}; + +/// One streamed answer: the open content block with its index, and the next index. +pub(crate) struct Anthropic { + model: String, + id: String, + open: Option<(Block, u32)>, + next: u32, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Block { + Thinking, + Text, +} + +impl Wire for Anthropic { + const NAME: &'static str = "anthropic_messages"; + + fn decode(body: Value) -> Result { + let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; + let max_tokens = body.get("max_tokens").and_then(Value::as_u64).ok_or_else(|| BadRequest("`max_tokens` is required".into()))?; + let messages = body.get("messages").and_then(Value::as_array).ok_or_else(|| BadRequest("`messages` is required".into()))?; + let mut request = TextGenerationRequest { + model: Some(model.to_owned()), + max_tokens: Some(max_tokens as u32), + top_k: body.get("top_k").and_then(Value::as_u64).map(|k| k as u32), + system_prompt: body.get("system").map(text_of).filter(|s| !s.is_empty()), + messages: messages.iter().map(message).collect::>()?, + tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), + tool_choice: body.get("tool_choice").and_then(tool_choice), + purpose: Some("driver".into()), + ..Default::default() + }; + sampling(&body, &mut request); + Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed + } + + fn answer(response: &TextGenerationResponse, id: &str) -> Value { + let mut content = Vec::new(); + if let Some(reasoning) = response.reasoning.as_deref().filter(|r| !r.is_empty()) { + content.push(json!({"type": "thinking", "thinking": reasoning, "signature": ""})); + } + if !response.text.is_empty() { + content.push(json!({"type": "text", "text": response.text})); + } + for (call_id, name, input) in tool_calls(response) { + content.push(json!({"type": "tool_use", "id": call_id, "name": name, "input": input})); + } + json!({ + "id": id, "type": "message", "role": "assistant", "model": response.model, + "content": content, + "stop_reason": stop_reason(response), "stop_sequence": null, + "usage": {"input_tokens": response.usage.input_tokens, "output_tokens": response.usage.output_tokens}, + }) + } + + fn error(kind: ErrorKind, message: &str) -> Value { + let kind = match kind { + ErrorKind::InvalidRequest => "invalid_request_error", + ErrorKind::NotFound => "not_found_error", + ErrorKind::Engine => "api_error", + }; + json!({"type": "error", "error": {"type": kind, "message": message}}) + } + + fn streamer(model: &str, id: &str) -> Self { + Self { model: model.to_owned(), id: id.to_owned(), open: None, next: 0 } + } + + fn opened(&mut self) -> Vec { + vec![event( + Some("message_start"), + &json!({"type": "message_start", "message": { + "id": self.id, "type": "message", "role": "assistant", "model": self.model, "content": [], + "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 0, "output_tokens": 0}, + }}), + )] + } + + fn chunk(&mut self, chunk: &GenerationChunk) -> Vec { + let (block, delta) = match chunk { + GenerationChunk::Token(text) => (Block::Text, json!({"type": "text_delta", "text": text})), + GenerationChunk::Reasoning(text) => (Block::Thinking, json!({"type": "thinking_delta", "thinking": text})), + _ => return Vec::new(), // prefill progress has no Anthropic form + }; + let (mut events, index) = self.switch_to(block); + events.push(event(Some("content_block_delta"), &json!({"type": "content_block_delta", "index": index, "delta": delta}))); + events + } + + fn finished(&mut self, response: &TextGenerationResponse) -> Vec { + let mut events = self.close(); + for (call_id, name, input) in tool_calls(response) { + let index = self.next_index(); + events.push(event(Some("content_block_start"), &json!({"type": "content_block_start", "index": index, + "content_block": {"type": "tool_use", "id": call_id, "name": name, "input": {}}}))); + events.push(event(Some("content_block_delta"), &json!({"type": "content_block_delta", "index": index, + "delta": {"type": "input_json_delta", "partial_json": input.to_string()}}))); + events.push(event(Some("content_block_stop"), &json!({"type": "content_block_stop", "index": index}))); + } + events.push(event(Some("message_delta"), &json!({"type": "message_delta", + "delta": {"stop_reason": stop_reason(response), "stop_sequence": null}, + "usage": {"input_tokens": response.usage.input_tokens, "output_tokens": response.usage.output_tokens}}))); + events.push(event(Some("message_stop"), &json!({"type": "message_stop"}))); + events + } + + fn failed(&mut self, message: &str) -> Vec { + let mut events = self.close(); + events.push(event(Some("error"), &Self::error(ErrorKind::Engine, message))); + events + } +} + +impl Anthropic { + /// Close the open block if it is another kind, open `block`, and return its index. + fn switch_to(&mut self, block: Block) -> (Vec, u32) { + if let Some((open, index)) = self.open { + if open == block { + return (Vec::new(), index); + } + } + let mut events = self.close(); + let index = self.next_index(); + let content_block = match block { + Block::Text => json!({"type": "text", "text": ""}), + Block::Thinking => json!({"type": "thinking", "thinking": ""}), + }; + events.push(event(Some("content_block_start"), &json!({"type": "content_block_start", "index": index, "content_block": content_block}))); + self.open = Some((block, index)); + (events, index) + } + + fn close(&mut self) -> Vec { + match self.open.take() { + Some((_, index)) => vec![event(Some("content_block_stop"), &json!({"type": "content_block_stop", "index": index}))], + None => Vec::new(), + } + } + + fn next_index(&mut self) -> u32 { + let index = self.next; + self.next += 1; + index + } +} + +fn stop_reason(response: &TextGenerationResponse) -> &'static str { + if stopped_for_tools(response) { + "tool_use" + } else if response.finish_reason == continuum_engine::ai::FinishReason::Length { + "max_tokens" + } else { + "end_turn" + } +} + +fn message(value: &Value) -> Result { + let role = value.get("role").and_then(Value::as_str).ok_or_else(|| BadRequest("a message has no `role`".into()))?; + let content = match value.get("content") { + Some(Value::String(text)) => MessageContent::Text(text.clone()), + Some(Value::Array(blocks)) => MessageContent::Parts(blocks.iter().filter_map(part).collect()), + _ => return Err(BadRequest("a message has no `content`".into())), + }; + Ok(ChatMessage { role: role.to_owned(), content, name: None }) +} + +/// One content block. A prior thinking block is not sent back to the engine. +fn part(block: &Value) -> Option { + match block.get("type").and_then(Value::as_str)? { + "text" => Some(ContentPart::Text { text: block.get("text").and_then(Value::as_str)?.to_owned() }), + "image" => { + let source = block.get("source")?; + Some(ContentPart::Image { image: ImageInput { + url: source.get("url").and_then(Value::as_str).map(str::to_owned), + base64: source.get("data").and_then(Value::as_str).map(str::to_owned), + mime_type: source.get("media_type").and_then(Value::as_str).map(str::to_owned), + }}) + } + "tool_use" => Some(ContentPart::ToolUse { + id: block.get("id").and_then(Value::as_str)?.to_owned(), + name: block.get("name").and_then(Value::as_str)?.to_owned(), + input: block.get("input").cloned().unwrap_or_else(|| json!({})), // unwrap_or_else: a call with no input has an empty one + }), + "tool_result" => Some(ContentPart::ToolResult { + tool_use_id: block.get("tool_use_id").and_then(Value::as_str)?.to_owned(), + content: block.get("content").map(text_of).unwrap_or_default(), // unwrap_or_default: an empty result + is_error: block.get("is_error").and_then(Value::as_bool), + }), + _ => None, + } +} + +fn tool(value: &Value) -> Option { + Some(NativeToolSpec { + name: value.get("name").and_then(Value::as_str)?.to_owned(), + description: value.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description + input_schema: input_schema(value.get("input_schema")?), + }) +} + +fn tool_choice(value: &Value) -> Option { + match value.get("type").and_then(Value::as_str)? { + "tool" => Some(ToolChoice::Specific { name: value.get("name").and_then(Value::as_str)?.to_owned() }), + mode => Some(ToolChoice::Mode(mode.to_owned())), + } +} diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs new file mode 100644 index 0000000000..38b21dded6 --- /dev/null +++ b/core/continuum-gateway/src/wire/chat.rs @@ -0,0 +1,224 @@ +//! OpenAI Chat Completions (`POST /v1/chat/completions`): Hermes, opencode, and most agents. + +use super::{event, input_schema, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use continuum_engine::ai::adapter::GenerationChunk; +use continuum_engine::ai::types::ImageInput; +use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; +use serde_json::{json, Value}; + +/// One streamed answer. +pub(crate) struct Chat { + model: String, + id: String, + created: u64, +} + +impl Wire for Chat { + const NAME: &'static str = "openai_chat"; + + fn decode(body: Value) -> Result { + let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; + let messages = body.get("messages").and_then(Value::as_array).ok_or_else(|| BadRequest("`messages` is required".into()))?; + let (system_prompt, messages) = conversation(messages)?; + let mut request = TextGenerationRequest { + model: Some(model.to_owned()), + max_tokens: body + .get("max_completion_tokens") + .or_else(|| body.get("max_tokens")) + .and_then(Value::as_u64) + .map(|t| t as u32), + system_prompt, + messages, + tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), + tool_choice: body.get("tool_choice").and_then(tool_choice), + purpose: Some("driver".into()), + ..Default::default() + }; + sampling(&body, &mut request); + Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed + } + + fn answer(response: &TextGenerationResponse, id: &str) -> Value { + let mut message = json!({"role": "assistant", "content": if response.text.is_empty() { Value::Null } else { json!(response.text) }}); + if let Some(reasoning) = response.reasoning.as_deref().filter(|r| !r.is_empty()) { + message["reasoning_content"] = json!(reasoning); + } + let calls: Vec = tool_calls(response).iter().map(function_call).collect(); + if !calls.is_empty() { + message["tool_calls"] = json!(calls); + } + json!({ + "id": id, "object": "chat.completion", "created": now_s(), "model": response.model, + "choices": [{"index": 0, "message": message, "finish_reason": finish_reason(response)}], + "usage": usage(response), + }) + } + + fn error(kind: ErrorKind, message: &str) -> Value { + let (kind, code) = match kind { + ErrorKind::InvalidRequest => ("invalid_request_error", "invalid_request"), + ErrorKind::NotFound => ("invalid_request_error", "model_not_found"), + ErrorKind::Engine => ("server_error", "engine_error"), + }; + json!({"error": {"message": message, "type": kind, "code": code}}) + } + + fn streamer(model: &str, id: &str) -> Self { + Self { model: model.to_owned(), id: id.to_owned(), created: now_s() } + } + + fn opened(&mut self) -> Vec { + vec![self.delta(json!({"role": "assistant", "content": ""}), Value::Null)] + } + + fn chunk(&mut self, chunk: &GenerationChunk) -> Vec { + match chunk { + GenerationChunk::Token(text) => vec![self.delta(json!({"content": text}), Value::Null)], + GenerationChunk::Reasoning(text) => vec![self.delta(json!({"reasoning_content": text}), Value::Null)], + _ => Vec::new(), // prefill progress has no Chat Completions form + } + } + + fn finished(&mut self, response: &TextGenerationResponse) -> Vec { + let mut events = Vec::new(); + let calls: Vec = tool_calls(response) + .iter() + .enumerate() + .map(|(index, call)| { + let mut call = function_call(call); + call["index"] = json!(index); + call + }) + .collect(); + if !calls.is_empty() { + events.push(self.delta(json!({"tool_calls": calls}), Value::Null)); + } + events.push(self.delta(json!({}), json!(finish_reason(response)))); + events.push(event(None, &json!({"id": self.id, "object": "chat.completion.chunk", "created": self.created, + "model": self.model, "choices": [], "usage": usage(response)}))); + events.push(Frame::done()); + events + } + + fn failed(&mut self, message: &str) -> Vec { + vec![event(None, &Self::error(ErrorKind::Engine, message)), Frame::done()] + } +} + +impl Chat { + fn delta(&self, delta: Value, finish_reason: Value) -> Frame { + event(None, &json!({"id": self.id, "object": "chat.completion.chunk", "created": self.created, "model": self.model, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}]})) + } +} + +fn now_s() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) // map_or: a clock before 1970 reads 0 +} + +fn finish_reason(response: &TextGenerationResponse) -> &'static str { + if stopped_for_tools(response) { + "tool_calls" + } else if response.finish_reason == continuum_engine::ai::FinishReason::Length { + "length" + } else { + "stop" + } +} + +fn usage(response: &TextGenerationResponse) -> Value { + json!({"prompt_tokens": response.usage.input_tokens, "completion_tokens": response.usage.output_tokens, + "total_tokens": response.usage.input_tokens + response.usage.output_tokens}) +} + +fn function_call((id, name, input): &(String, String, Value)) -> Value { + json!({"id": id, "type": "function", "function": {"name": name, "arguments": input.to_string()}}) +} + +/// The leading system messages become the system prompt. A system message later in the +/// conversation is kept, in order, as a user turn marked as system text: the engine's chat +/// templates accept a system message only at the start. +fn conversation(messages: &[Value]) -> Result<(Option, Vec), BadRequest> { + let mut system = Vec::new(); + let mut out = Vec::new(); + for m in messages { + let role = m.get("role").and_then(Value::as_str).ok_or_else(|| BadRequest("a message has no `role`".into()))?; + let content = m.get("content").unwrap_or(&Value::Null); + match role { + "system" | "developer" if out.is_empty() => system.push(text_of(content)), + "system" | "developer" => out.push(ChatMessage { role: "user".into(), content: MessageContent::Text(format!("[system] {}", text_of(content))), name: None }), + "assistant" => { + let mut parts = Vec::new(); + let text = text_of(content); + if !text.is_empty() { + parts.push(ContentPart::Text { text }); + } + for call in m.get("tool_calls").and_then(Value::as_array).into_iter().flatten() { + let function = call.get("function").ok_or_else(|| BadRequest("a tool call has no `function`".into()))?; + let arguments = function.get("arguments").and_then(Value::as_str).unwrap_or("{}"); // unwrap_or: a call with no arguments + parts.push(ContentPart::ToolUse { + id: call.get("id").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: an unnamed call keeps an empty id + name: function.get("name").and_then(Value::as_str).ok_or_else(|| BadRequest("a tool call has no name".into()))?.to_owned(), + input: serde_json::from_str(arguments).unwrap_or_else(|_| Value::String(arguments.to_owned())), // unwrap_or_else: arguments that are not JSON pass through as written + }); + } + out.push(ChatMessage { role: "assistant".into(), content: MessageContent::Parts(parts), name: None }); + } + "tool" => out.push(ChatMessage { + role: "tool".into(), + content: MessageContent::Parts(vec![ContentPart::ToolResult { + tool_use_id: m.get("tool_call_id").and_then(Value::as_str).ok_or_else(|| BadRequest("a tool message has no `tool_call_id`".into()))?.to_owned(), + content: text_of(content), + is_error: None, + }]), + name: None, + }), + _ => out.push(ChatMessage { role: role.to_owned(), content: user_content(content), name: None }), + } + } + let system = system.join("\n\n"); + Ok(((!system.is_empty()).then_some(system), out)) +} + +fn user_content(content: &Value) -> MessageContent { + match content { + Value::Array(parts) => MessageContent::Parts( + parts + .iter() + .filter_map(|p| match p.get("type").and_then(Value::as_str)? { + "text" => Some(ContentPart::Text { text: p.get("text").and_then(Value::as_str)?.to_owned() }), + "image_url" => Some(ContentPart::Image { image: image(p.get("image_url")?.get("url")?.as_str()?) }), + _ => None, + }) + .collect(), + ), + other => MessageContent::Text(text_of(other)), + } +} + +/// An image URL, or a `data:` URL carrying its bytes. +pub(super) fn image(url: &str) -> ImageInput { + match url.strip_prefix("data:").and_then(|rest| rest.split_once(";base64,")) { + Some((mime, data)) => ImageInput { url: None, base64: Some(data.to_owned()), mime_type: Some(mime.to_owned()) }, + None => ImageInput { url: Some(url.to_owned()), base64: None, mime_type: None }, + } +} + +fn tool(value: &Value) -> Option { + let function = value.get("function")?; + Some(NativeToolSpec { + name: function.get("name").and_then(Value::as_str)?.to_owned(), + description: function.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description + input_schema: input_schema(function.get("parameters").unwrap_or(&json!({}))), + }) +} + +pub(super) fn tool_choice(value: &Value) -> Option { + match value { + Value::String(mode) => Some(ToolChoice::Mode(if mode == "required" { "any".into() } else { mode.clone() })), + Value::Object(_) => Some(ToolChoice::Specific { + name: value.get("function").and_then(|f| f.get("name")).or_else(|| value.get("name")).and_then(Value::as_str)?.to_owned(), + }), + _ => None, + } +} diff --git a/core/continuum-gateway/src/wire/mod.rs b/core/continuum-gateway/src/wire/mod.rs new file mode 100644 index 0000000000..d7c5f7a925 --- /dev/null +++ b/core/continuum-gateway/src/wire/mod.rs @@ -0,0 +1,140 @@ +//! The APIs agents speak, each an adapter holding only its diff. +//! +//! A format decodes the agent's body into one [`Call`] and encodes the engine's answer back, +//! whole or as a stream. Everything they share (selection, generation, the SSE transport, +//! errors) lives once in `route` and `server`. + +pub(crate) mod anthropic; +pub(crate) mod chat; +pub(crate) mod responses; + +use continuum_engine::ai::adapter::GenerationChunk; +use continuum_engine::ai::{ContentPart, FinishReason, TextGenerationRequest, TextGenerationResponse}; +use serde_json::Value; + +/// One decoded call: the engine's request, and whether the agent wants it streamed. +pub(crate) struct Call { + pub request: TextGenerationRequest, + pub stream: bool, +} + +/// A body the format cannot read, with the reason the agent is told. +#[derive(Debug)] +pub(crate) struct BadRequest(pub String); + +/// One API an agent speaks. `Self` is the encoder of one streamed answer. +pub(crate) trait Wire: Send + 'static { + /// The format's name, for probes. + const NAME: &'static str; + fn decode(body: Value) -> Result; + /// The whole answer, for a call that did not ask to stream. + fn answer(response: &TextGenerationResponse, id: &str) -> Value; + /// The body of a refusal, in the format's own error shape. + fn error(kind: ErrorKind, message: &str) -> Value; + /// A new encoder for one streamed answer. + fn streamer(model: &str, id: &str) -> Self; + /// What the stream opens with, before any token. + fn opened(&mut self) -> Vec; + fn chunk(&mut self, chunk: &GenerationChunk) -> Vec; + /// What closes a completed answer: its tool calls, stop reason and usage. + fn finished(&mut self, response: &TextGenerationResponse) -> Vec; + /// What closes an answer the engine failed mid-stream. + fn failed(&mut self, message: &str) -> Vec; +} + +/// The refusals every format can express. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ErrorKind { + InvalidRequest, + NotFound, + Engine, +} + +/// One server-sent event of a streamed answer: its name, if the format names events, and data. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Frame { + pub name: Option, + pub data: String, +} + +impl Frame { + /// The OpenAI terminator. + pub(crate) fn done() -> Self { + Self { name: None, data: "[DONE]".into() } + } + + pub(crate) fn into_event(self) -> axum::response::sse::Event { + let event = axum::response::sse::Event::default().data(self.data); + match self.name { + Some(name) => event.event(name), + None => event, + } + } + + #[cfg(test)] + pub(crate) fn json(&self) -> Value { + serde_json::from_str(&self.data).expect("test: a JSON frame") + } +} + +/// A JSON frame, optionally named. +pub(crate) fn event(name: Option<&str>, data: &Value) -> Frame { + Frame { name: name.map(str::to_owned), data: data.to_string() } +} + +/// The tool calls of an answer as (id, name, input), from either place the engine puts them. +pub(crate) fn tool_calls(response: &TextGenerationResponse) -> Vec<(String, String, Value)> { + if let Some(calls) = &response.tool_calls { + return calls.iter().map(|c| (c.id.clone(), c.name.clone(), c.input.clone())).collect(); + } + response + .content + .iter() + .flatten() + .filter_map(|part| match part { + ContentPart::ToolUse { id, name, input } => Some((id.clone(), name.clone(), input.clone())), + _ => None, + }) + .collect() +} + +/// Whether the answer stopped to call tools. +pub(crate) fn stopped_for_tools(response: &TextGenerationResponse) -> bool { + response.finish_reason == FinishReason::ToolUse || !tool_calls(response).is_empty() +} + +/// A text field that is a string, or an array of `{type: "text", text}` blocks. +pub(crate) fn text_of(value: &Value) -> String { + match value { + Value::String(text) => text.clone(), + Value::Array(blocks) => blocks.iter().filter_map(|b| b.get("text").and_then(Value::as_str)).collect::>().join("\n"), + _ => String::new(), + } +} + +/// A JSON-schema object as the engine's tool input schema. +pub(crate) fn input_schema(schema: &Value) -> continuum_engine::ai::ToolInputSchema { + continuum_engine::ai::ToolInputSchema { + schema_type: "object".into(), + properties: schema.get("properties").cloned().unwrap_or_else(|| Value::Object(Default::default())), // unwrap_or_else: a tool with no parameters has empty properties + required: schema + .get("required") + .and_then(Value::as_array) + .map(|r| r.iter().filter_map(Value::as_str).map(str::to_owned).collect()), + definitions: schema.get("$defs").or_else(|| schema.get("definitions")).cloned(), + } +} + +/// The sampling fields every format names the same way: temperature, top_p, stop. +pub(crate) fn sampling(body: &Value, request: &mut TextGenerationRequest) { + request.temperature = body.get("temperature").and_then(Value::as_f64).map(|t| t as f32); + request.top_p = body.get("top_p").and_then(Value::as_f64).map(|t| t as f32); + request.stop_sequences = match body.get("stop").or_else(|| body.get("stop_sequences")) { + Some(Value::String(s)) => Some(vec![s.clone()]), + Some(Value::Array(a)) => Some(a.iter().filter_map(Value::as_str).map(str::to_owned).collect()), + _ => None, + }; +} + +#[cfg(test)] +mod tests; diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs new file mode 100644 index 0000000000..0f3240adaf --- /dev/null +++ b/core/continuum-gateway/src/wire/responses.rs @@ -0,0 +1,249 @@ +//! OpenAI Responses (`POST /v1/responses`): Grok Build (`--xai-api-base-url`) and Codex CLI. +//! +//! `previous_response_id` names server-side conversation state. That state is a driver +//! mind's memory, which arrives with session identity (DRIVER-GATEWAY.md G2); until then a +//! call that names one is refused rather than answered without its history. + +use super::{chat, event, input_schema, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use continuum_engine::ai::adapter::GenerationChunk; +use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse}; +use serde_json::{json, Value}; + +/// One streamed answer: the text item, once opened, and the event sequence. +pub(crate) struct Responses { + model: String, + id: String, + created: u64, + sequence: u64, + text: Option, +} + +impl Wire for Responses { + const NAME: &'static str = "openai_responses"; + + fn decode(body: Value) -> Result { + let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; + if body.get("previous_response_id").is_some_and(|v| !v.is_null()) { + return Err(BadRequest( + "`previous_response_id` needs server-side session memory, which this gateway does not keep yet; send the full `input` with `store: false`".into(), + )); + } + let messages = match body.get("input") { + Some(Value::String(text)) => vec![ChatMessage { role: "user".into(), content: MessageContent::Text(text.clone()), name: None }], + Some(Value::Array(items)) => items_to_messages(items)?, + _ => return Err(BadRequest("`input` is required".into())), + }; + let mut request = TextGenerationRequest { + model: Some(model.to_owned()), + max_tokens: body.get("max_output_tokens").and_then(Value::as_u64).map(|t| t as u32), + system_prompt: body.get("instructions").and_then(Value::as_str).map(str::to_owned), + messages, + tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), + tool_choice: body.get("tool_choice").and_then(chat::tool_choice), + purpose: Some("driver".into()), + ..Default::default() + }; + sampling(&body, &mut request); + Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed + } + + fn answer(response: &TextGenerationResponse, id: &str) -> Value { + envelope(id, &response.model, now_s(), "completed", output(response, id), Some(response)) + } + + fn error(kind: ErrorKind, message: &str) -> Value { + let code = match kind { + ErrorKind::InvalidRequest => "invalid_request", + ErrorKind::NotFound => "model_not_found", + ErrorKind::Engine => "server_error", + }; + json!({"error": {"message": message, "type": "invalid_request_error", "code": code}}) + } + + fn streamer(model: &str, id: &str) -> Self { + Self { model: model.to_owned(), id: id.to_owned(), created: now_s(), sequence: 0, text: None } + } + + fn opened(&mut self) -> Vec { + let response = envelope(&self.id, &self.model, self.created, "in_progress", Vec::new(), None); + vec![self.emit("response.created", json!({"response": response}))] + } + + fn chunk(&mut self, chunk: &GenerationChunk) -> Vec { + let GenerationChunk::Token(delta) = chunk else { + return Vec::new(); // reasoning and prefill progress are not streamed in this format + }; + let mut events = Vec::new(); + if self.text.is_none() { + self.text = Some(String::new()); + let item = json!({"type": "message", "id": self.message_id(), "status": "in_progress", "role": "assistant", "content": []}); + events.push(self.emit("response.output_item.added", json!({"output_index": 0, "item": item}))); + events.push(self.emit("response.content_part.added", json!({"item_id": self.message_id(), "output_index": 0, + "content_index": 0, "part": {"type": "output_text", "text": "", "annotations": []}}))); + } + if let Some(text) = self.text.as_mut() { + text.push_str(delta); + } + events.push(self.emit("response.output_text.delta", json!({"item_id": self.message_id(), "output_index": 0, "content_index": 0, "delta": delta}))); + events + } + + fn finished(&mut self, response: &TextGenerationResponse) -> Vec { + let mut events = Vec::new(); + let mut index = 0; + if let Some(text) = self.text.take() { + let part = json!({"type": "output_text", "text": text, "annotations": []}); + events.push(self.emit("response.output_text.done", json!({"item_id": self.message_id(), "output_index": 0, "content_index": 0, "text": text}))); + events.push(self.emit("response.content_part.done", json!({"item_id": self.message_id(), "output_index": 0, "content_index": 0, "part": part}))); + let item = json!({"type": "message", "id": self.message_id(), "status": "completed", "role": "assistant", "content": [part]}); + events.push(self.emit("response.output_item.done", json!({"output_index": 0, "item": item}))); + index = 1; + } + for call in tool_calls(response) { + let item = function_call(&call); + let arguments = item["arguments"].clone(); + let mut added = item.clone(); + added["arguments"] = json!(""); + added["status"] = json!("in_progress"); + events.push(self.emit("response.output_item.added", json!({"output_index": index, "item": added}))); + events.push(self.emit("response.function_call_arguments.delta", json!({"item_id": item["id"], "output_index": index, "delta": arguments}))); + events.push(self.emit("response.function_call_arguments.done", json!({"item_id": item["id"], "output_index": index, "arguments": arguments}))); + events.push(self.emit("response.output_item.done", json!({"output_index": index, "item": item}))); + index += 1; + } + let response = envelope(&self.id, &self.model, self.created, "completed", output(response, &self.id), Some(response)); + events.push(self.emit("response.completed", json!({"response": response}))); + events + } + + fn failed(&mut self, message: &str) -> Vec { + let mut response = envelope(&self.id, &self.model, self.created, "failed", Vec::new(), None); + response["error"] = json!({"code": "server_error", "message": message}); + vec![self.emit("response.failed", json!({"response": response}))] + } +} + +impl Responses { + fn emit(&mut self, kind: &str, mut data: Value) -> Frame { + data["type"] = json!(kind); + data["sequence_number"] = json!(self.sequence); + self.sequence += 1; + event(Some(kind), &data) + } + + fn message_id(&self) -> String { + message_id(&self.id) + } +} + +fn message_id(response_id: &str) -> String { + format!("msg_{}", response_id.trim_start_matches("resp_")) +} + +fn now_s() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) // map_or: a clock before 1970 reads 0 +} + +fn envelope(id: &str, model: &str, created: u64, status: &str, output: Vec, response: Option<&TextGenerationResponse>) -> Value { + json!({ + "id": id, "object": "response", "created_at": created, "status": status, "model": model, + "output": output, + "usage": response.map(|r| json!({"input_tokens": r.usage.input_tokens, "output_tokens": r.usage.output_tokens, + "total_tokens": r.usage.input_tokens + r.usage.output_tokens})), + "incomplete_details": response.filter(|r| r.finish_reason == continuum_engine::ai::FinishReason::Length && !stopped_for_tools(r)) + .map(|_| json!({"reason": "max_output_tokens"})), + }) +} + +fn output(response: &TextGenerationResponse, id: &str) -> Vec { + let mut output = Vec::new(); + if !response.text.is_empty() { + output.push(json!({"type": "message", "id": message_id(id), "status": "completed", "role": "assistant", + "content": [{"type": "output_text", "text": response.text, "annotations": []}]})); + } + output.extend(tool_calls(response).iter().map(function_call)); + output +} + +fn function_call((call_id, name, input): &(String, String, Value)) -> Value { + json!({"type": "function_call", "id": format!("fc_{call_id}"), "call_id": call_id, "name": name, + "arguments": input.to_string(), "status": "completed"}) +} + +/// Input items to messages: consecutive function calls make one assistant turn, and each +/// call's output is a tool reply. Reasoning items are not sent back to the engine. +fn items_to_messages(items: &[Value]) -> Result, BadRequest> { + let mut out: Vec = Vec::new(); + for item in items { + let kind = item.get("type").and_then(Value::as_str).unwrap_or("message"); // unwrap_or: an item with only a role is a message + match kind { + "message" => { + let role = item.get("role").and_then(Value::as_str).ok_or_else(|| BadRequest("a message item has no `role`".into()))?; + let role = if role == "developer" { "system" } else { role }; + out.push(ChatMessage { role: role.to_owned(), content: content(item.get("content").unwrap_or(&Value::Null)), name: None }); + } + "function_call" => { + let arguments = item.get("arguments").and_then(Value::as_str).unwrap_or("{}"); // unwrap_or: a call with no arguments + let call = ContentPart::ToolUse { + id: item.get("call_id").and_then(Value::as_str).ok_or_else(|| BadRequest("a function_call has no `call_id`".into()))?.to_owned(), + name: item.get("name").and_then(Value::as_str).ok_or_else(|| BadRequest("a function_call has no `name`".into()))?.to_owned(), + input: serde_json::from_str(arguments).unwrap_or_else(|_| Value::String(arguments.to_owned())), // unwrap_or_else: arguments that are not JSON pass through as written + }; + match out.last_mut() { + Some(ChatMessage { role, content: MessageContent::Parts(parts), .. }) + if role == "assistant" && parts.iter().any(|p| matches!(p, ContentPart::ToolUse { .. })) => parts.push(call), + _ => out.push(ChatMessage { role: "assistant".into(), content: MessageContent::Parts(vec![call]), name: None }), + } + } + "function_call_output" => out.push(ChatMessage { + role: "tool".into(), + content: MessageContent::Parts(vec![ContentPart::ToolResult { + tool_use_id: item.get("call_id").and_then(Value::as_str).ok_or_else(|| BadRequest("a function_call_output has no `call_id`".into()))?.to_owned(), + content: item.get("output").map(text_of).unwrap_or_default(), // unwrap_or_default: an empty output + is_error: None, + }]), + name: None, + }), + _ => {} // reasoning and other items carry nothing the engine renders + } + } + // The engine's templates take one system message, at the start (as in Chat Completions). + let mut kept = Vec::with_capacity(out.len()); + for (i, mut m) in out.into_iter().enumerate() { + if m.role == "system" && i > 0 { + m.role = "user".into(); + if let MessageContent::Text(text) = &m.content { + m.content = MessageContent::Text(format!("[system] {text}")); + } + } + kept.push(m); + } + Ok(kept) +} + +fn content(value: &Value) -> MessageContent { + match value { + Value::Array(parts) => MessageContent::Parts( + parts + .iter() + .filter_map(|p| match p.get("type").and_then(Value::as_str)? { + "input_text" | "output_text" | "text" => Some(ContentPart::Text { text: p.get("text").and_then(Value::as_str)?.to_owned() }), + "input_image" => Some(ContentPart::Image { image: chat::image(p.get("image_url").and_then(Value::as_str)?) }), + _ => None, + }) + .collect(), + ), + other => MessageContent::Text(text_of(other)), + } +} + +fn tool(value: &Value) -> Option { + if value.get("type").and_then(Value::as_str) != Some("function") { + return None; // built-in tools (web search, file search) are the provider's, not ours + } + Some(NativeToolSpec { + name: value.get("name").and_then(Value::as_str)?.to_owned(), + description: value.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description + input_schema: input_schema(value.get("parameters").unwrap_or(&json!({}))), + }) +} diff --git a/core/continuum-gateway/src/wire/tests.rs b/core/continuum-gateway/src/wire/tests.rs new file mode 100644 index 0000000000..81c3fe87bf --- /dev/null +++ b/core/continuum-gateway/src/wire/tests.rs @@ -0,0 +1,153 @@ +//! Each format round-trips an agent's tool-using turn, whole and streamed. +use super::anthropic::Anthropic; +use super::chat::Chat; +use super::responses::Responses; +use super::*; +use continuum_engine::ai::{MessageContent, ToolCall, UsageMetrics}; +use serde_json::json; + +/// An answer that says a word and calls one tool. +fn tool_answer() -> TextGenerationResponse { + TextGenerationResponse { + text: "Reading it.".into(), + finish_reason: FinishReason::ToolUse, + model: "qwen".into(), + provider: "local".into(), + usage: UsageMetrics { input_tokens: 120, output_tokens: 9, total_tokens: 129, estimated_cost: None }, + response_time_ms: 0, + request_id: "r1".into(), + content: None, + tool_calls: Some(vec![ToolCall { id: "call_1".into(), name: "read_file".into(), input: json!({"path": "a.rs"}) }]), + reasoning: None, + routing: None, + error: None, + timing: None, + } +} + +fn parts(m: &continuum_engine::ai::ChatMessage) -> &[ContentPart] { + match &m.content { + MessageContent::Parts(parts) => parts, + MessageContent::Text(_) => panic!("test: expected parts in {m:?}"), + } +} + +// what this catches: Claude Code's tools and tool results reaching the engine as text, or a +// tool call coming back without its id (Claude Code then cannot answer it). +#[test] +fn anthropic_carries_tools_both_ways_and_streams_blocks_in_order() { + let call = Anthropic::decode(json!({ + "model": "qwen", "max_tokens": 512, "stream": true, + "system": [{"type": "text", "text": "You are a coder."}], + "tools": [{"name": "read_file", "description": "Read", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}], + "messages": [ + {"role": "user", "content": "open a.rs"}, + {"role": "assistant", "content": [{"type": "tool_use", "id": "call_0", "name": "read_file", "input": {"path": "b.rs"}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_0", "content": [{"type": "text", "text": "fn b() {}"}]}]}, + ], + })) + .expect("test: decodes"); + assert!(call.stream); + assert_eq!(call.request.system_prompt.as_deref(), Some("You are a coder.")); + assert_eq!(call.request.tools.as_ref().map(|t| t[0].input_schema.required.clone()), Some(Some(vec!["path".to_string()]))); + assert!(matches!(&parts(&call.request.messages[1])[0], ContentPart::ToolUse { id, .. } if id == "call_0")); + assert!(matches!(&parts(&call.request.messages[2])[0], ContentPart::ToolResult { content, .. } if content == "fn b() {}")); + + let whole = Anthropic::answer(&tool_answer(), "msg_1"); + assert_eq!(whole["stop_reason"], "tool_use"); + assert_eq!(whole["content"][1]["id"], "call_1"); + + let mut s = Anthropic::streamer("qwen", "msg_1"); + let mut frames = s.opened(); + frames.extend(s.chunk(&GenerationChunk::Reasoning("hmm".into()))); + frames.extend(s.chunk(&GenerationChunk::Token("Reading".into()))); + frames.extend(s.chunk(&GenerationChunk::Token(" it.".into()))); + frames.extend(s.finished(&tool_answer())); + let names: Vec<_> = frames.iter().map(|f| f.name.clone().expect("test: named")).collect(); + assert_eq!(names, [ + "message_start", + "content_block_start", "content_block_delta", "content_block_stop", // thinking, index 0 + "content_block_start", "content_block_delta", "content_block_delta", "content_block_stop", // text, index 1 + "content_block_start", "content_block_delta", "content_block_stop", // tool_use, index 2 + "message_delta", "message_stop", + ]); + assert_eq!(frames[4].json()["index"], 1); + assert_eq!(frames[8].json()["content_block"]["id"], "call_1"); + assert_eq!(frames[11].json()["delta"]["stop_reason"], "tool_use"); +} + +// what this catches: a mid-conversation system message reaching a template that rejects it, +// tool-call arguments left as a string, and a stream that never terminates. +#[test] +fn chat_completions_keeps_one_leading_system_and_ends_its_stream() { + let call = Chat::decode(json!({ + "model": "qwen", + "messages": [ + {"role": "system", "content": "Be terse."}, + {"role": "user", "content": "go"}, + {"role": "assistant", "content": null, "tool_calls": [{"id": "call_0", "type": "function", "function": {"name": "ls", "arguments": "{\"dir\":\".\"}"}}]}, + {"role": "tool", "tool_call_id": "call_0", "content": "a.rs"}, + {"role": "system", "content": "Budget: 10 steps left."}, + ], + "tools": [{"type": "function", "function": {"name": "ls", "parameters": {"type": "object", "properties": {"dir": {"type": "string"}}}}}], + "tool_choice": "required", + })) + .expect("test: decodes"); + assert_eq!(call.request.system_prompt.as_deref(), Some("Be terse.")); + assert!(matches!(&parts(&call.request.messages[1])[0], ContentPart::ToolUse { input, .. } if input["dir"] == ".")); + assert!(matches!(&parts(&call.request.messages[2])[0], ContentPart::ToolResult { tool_use_id, .. } if tool_use_id == "call_0")); + assert_eq!(call.request.messages[3].role, "user", "a later system message is not sent as system"); + assert!(matches!(&call.request.tool_choice, Some(ToolChoice::Mode(m)) if m == "any")); + + let whole = Chat::answer(&tool_answer(), "chatcmpl_1"); + assert_eq!(whole["choices"][0]["finish_reason"], "tool_calls"); + assert_eq!(whole["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"], "{\"path\":\"a.rs\"}"); + + let mut s = Chat::streamer("qwen", "chatcmpl_1"); + let mut frames = s.opened(); + frames.extend(s.chunk(&GenerationChunk::Token("Reading it.".into()))); + frames.extend(s.finished(&tool_answer())); + assert_eq!(frames.last(), Some(&Frame::done())); + assert_eq!(frames[2].json()["choices"][0]["delta"]["tool_calls"][0]["index"], 0); + assert_eq!(frames[3].json()["choices"][0]["finish_reason"], "tool_calls"); + assert_eq!(frames[4].json()["usage"]["prompt_tokens"], 120); +} + +// what this catches: Grok Build's and Codex's items mis-grouped (two calls as two assistant +// turns), a stale `previous_response_id` answered without its history, and an event stream +// whose sequence numbers skip or that never completes. +#[test] +fn responses_groups_items_refuses_missing_state_and_numbers_its_events() { + let refused = Responses::decode(json!({"model": "qwen", "input": "hi", "previous_response_id": "resp_9"})); + assert!(refused.is_err(), "no session memory yet: refuse, never answer without history"); + + let call = Responses::decode(json!({ + "model": "qwen", "instructions": "You are Grok.", "stream": true, + "input": [ + {"role": "user", "content": [{"type": "input_text", "text": "fix it"}]}, + {"type": "function_call", "call_id": "c1", "name": "read", "arguments": "{\"p\":\"a\"}"}, + {"type": "function_call", "call_id": "c2", "name": "read", "arguments": "{\"p\":\"b\"}"}, + {"type": "function_call_output", "call_id": "c1", "output": "A"}, + {"type": "function_call_output", "call_id": "c2", "output": "B"}, + {"type": "reasoning", "summary": []}, + ], + "tools": [{"type": "function", "name": "read", "parameters": {"type": "object", "properties": {"p": {"type": "string"}}}}, {"type": "web_search"}], + })) + .expect("test: decodes"); + assert_eq!(call.request.system_prompt.as_deref(), Some("You are Grok.")); + assert_eq!(call.request.messages.len(), 4, "user, one assistant turn with both calls, two tool replies"); + assert_eq!(parts(&call.request.messages[1]).len(), 2); + assert_eq!(call.request.tools.as_ref().map(Vec::len), Some(1), "provider built-ins are not ours"); + + let mut s = Responses::streamer("qwen", "resp_1"); + let mut frames = s.opened(); + frames.extend(s.chunk(&GenerationChunk::Token("Reading".into()))); + frames.extend(s.chunk(&GenerationChunk::Token(" it.".into()))); + frames.extend(s.finished(&tool_answer())); + let sequence: Vec = frames.iter().map(|f| f.json()["sequence_number"].as_u64().expect("test: numbered")).collect(); + assert_eq!(sequence, (0..frames.len() as u64).collect::>()); + let last = frames.last().expect("test: frames").json(); + assert_eq!(last["type"], "response.completed"); + assert_eq!(last["response"]["output"][0]["content"][0]["text"], "Reading it."); + assert_eq!(last["response"]["output"][1]["call_id"], "call_1"); +} From b964ce3d431e33f9e8adfcfaf1778f3ef2e95877 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 17:43:38 -0500 Subject: [PATCH 05/27] continuum-gateway: tracing for its probes; the test imports ToolChoice Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/Cargo.toml | 1 + core/continuum-gateway/src/wire/tests.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/core/continuum-gateway/Cargo.toml b/core/continuum-gateway/Cargo.toml index 107a43e404..f34580a45f 100644 --- a/core/continuum-gateway/Cargo.toml +++ b/core/continuum-gateway/Cargo.toml @@ -14,3 +14,4 @@ serde_json.workspace = true tokio.workspace = true tokio-stream.workspace = true uuid.workspace = true +tracing.workspace = true diff --git a/core/continuum-gateway/src/wire/tests.rs b/core/continuum-gateway/src/wire/tests.rs index 81c3fe87bf..27b659bc1c 100644 --- a/core/continuum-gateway/src/wire/tests.rs +++ b/core/continuum-gateway/src/wire/tests.rs @@ -3,7 +3,7 @@ use super::anthropic::Anthropic; use super::chat::Chat; use super::responses::Responses; use super::*; -use continuum_engine::ai::{MessageContent, ToolCall, UsageMetrics}; +use continuum_engine::ai::{MessageContent, ToolCall, ToolChoice, UsageMetrics}; use serde_json::json; /// An answer that says a word and calls one tool. From 434ffb2f53b7533bd6021b082ec8642f72b0a618 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 17:56:38 -0500 Subject: [PATCH 06/27] continuum-gateway: one rule for where system text goes, for every format Claude Code sends a system message after the user's turn (its hook and environment context), Codex sends developer items, Hermes mid-run notices; the engine's templates take one system message, first ('System message must be at the beginning', the M5, 2026-10-27 22:48Z). place_system: leading system/developer text joins the system prompt, a later one stays in order as a user turn marked as system text. Replaces the two copies chat and responses each had. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/src/wire/anthropic.rs | 3 +- core/continuum-gateway/src/wire/chat.rs | 16 +++---- core/continuum-gateway/src/wire/mod.rs | 44 +++++++++++++++++++- core/continuum-gateway/src/wire/responses.rs | 17 ++------ core/continuum-gateway/src/wire/tests.rs | 9 ++-- 5 files changed, 59 insertions(+), 30 deletions(-) diff --git a/core/continuum-gateway/src/wire/anthropic.rs b/core/continuum-gateway/src/wire/anthropic.rs index 48253d5532..ca50d85ecc 100644 --- a/core/continuum-gateway/src/wire/anthropic.rs +++ b/core/continuum-gateway/src/wire/anthropic.rs @@ -1,6 +1,6 @@ //! Anthropic Messages (`POST /v1/messages`): Claude Code, via `ANTHROPIC_BASE_URL`. -use super::{event, input_schema, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{event, input_schema, place_system, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::types::ImageInput; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; @@ -39,6 +39,7 @@ impl Wire for Anthropic { ..Default::default() }; sampling(&body, &mut request); + (request.system_prompt, request.messages) = place_system(request.system_prompt.take(), std::mem::take(&mut request.messages)); Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed } diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs index 38b21dded6..ec2d6878ce 100644 --- a/core/continuum-gateway/src/wire/chat.rs +++ b/core/continuum-gateway/src/wire/chat.rs @@ -1,6 +1,6 @@ //! OpenAI Chat Completions (`POST /v1/chat/completions`): Hermes, opencode, and most agents. -use super::{event, input_schema, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{event, input_schema, place_system, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::types::ImageInput; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; @@ -19,7 +19,7 @@ impl Wire for Chat { fn decode(body: Value) -> Result { let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; let messages = body.get("messages").and_then(Value::as_array).ok_or_else(|| BadRequest("`messages` is required".into()))?; - let (system_prompt, messages) = conversation(messages)?; + let (system_prompt, messages) = place_system(None, conversation(messages)?); let mut request = TextGenerationRequest { model: Some(model.to_owned()), max_tokens: body @@ -135,18 +135,13 @@ fn function_call((id, name, input): &(String, String, Value)) -> Value { json!({"id": id, "type": "function", "function": {"name": name, "arguments": input.to_string()}}) } -/// The leading system messages become the system prompt. A system message later in the -/// conversation is kept, in order, as a user turn marked as system text: the engine's chat -/// templates accept a system message only at the start. -fn conversation(messages: &[Value]) -> Result<(Option, Vec), BadRequest> { - let mut system = Vec::new(); +/// The messages as the engine reads them; `place_system` then decides where system text goes. +fn conversation(messages: &[Value]) -> Result, BadRequest> { let mut out = Vec::new(); for m in messages { let role = m.get("role").and_then(Value::as_str).ok_or_else(|| BadRequest("a message has no `role`".into()))?; let content = m.get("content").unwrap_or(&Value::Null); match role { - "system" | "developer" if out.is_empty() => system.push(text_of(content)), - "system" | "developer" => out.push(ChatMessage { role: "user".into(), content: MessageContent::Text(format!("[system] {}", text_of(content))), name: None }), "assistant" => { let mut parts = Vec::new(); let text = text_of(content); @@ -176,8 +171,7 @@ fn conversation(messages: &[Value]) -> Result<(Option, Vec) _ => out.push(ChatMessage { role: role.to_owned(), content: user_content(content), name: None }), } } - let system = system.join("\n\n"); - Ok(((!system.is_empty()).then_some(system), out)) + Ok(out) } fn user_content(content: &Value) -> MessageContent { diff --git a/core/continuum-gateway/src/wire/mod.rs b/core/continuum-gateway/src/wire/mod.rs index d7c5f7a925..19f6c04d47 100644 --- a/core/continuum-gateway/src/wire/mod.rs +++ b/core/continuum-gateway/src/wire/mod.rs @@ -9,7 +9,7 @@ pub(crate) mod chat; pub(crate) mod responses; use continuum_engine::ai::adapter::GenerationChunk; -use continuum_engine::ai::{ContentPart, FinishReason, TextGenerationRequest, TextGenerationResponse}; +use continuum_engine::ai::{ChatMessage, ContentPart, FinishReason, MessageContent, TextGenerationRequest, TextGenerationResponse}; use serde_json::Value; /// One decoded call: the engine's request, and whether the agent wants it streamed. @@ -125,6 +125,48 @@ pub(crate) fn input_schema(schema: &Value) -> continuum_engine::ai::ToolInputSch } } +/// Where system text may go. The engine's chat templates accept one system message, first +/// (Qwen's raises "System message must be at the beginning"), and agents send more: Claude +/// Code a `system` message after the user's turn (its hook and environment context), Codex +/// `developer` items, Hermes mid-run notices. System and developer messages before any +/// turn join the system prompt; a later one stays in order as a user turn marked as system +/// text. One rule for every format. +pub(crate) fn place_system(system_prompt: Option, messages: Vec) -> (Option, Vec) { + let mut system = system_prompt.filter(|s| !s.is_empty()); + let mut out = Vec::with_capacity(messages.len()); + for message in messages { + if message.role != "system" && message.role != "developer" { + out.push(message); + continue; + } + let text = plain_text(&message.content); + if out.is_empty() { + system = Some(match system { + Some(head) => format!("{head}\n\n{text}"), + None => text, + }); + } else { + out.push(ChatMessage { role: "user".into(), content: MessageContent::Text(format!("[system] {text}")), name: None }); + } + } + (system, out) +} + +/// The text of a message's content, its text parts joined. +fn plain_text(content: &MessageContent) -> String { + match content { + MessageContent::Text(text) => text.clone(), + MessageContent::Parts(parts) => parts + .iter() + .filter_map(|p| match p { + ContentPart::Text { text } => Some(text.as_str()), + _ => None, + }) + .collect::>() + .join("\n"), + } +} + /// The sampling fields every format names the same way: temperature, top_p, stop. pub(crate) fn sampling(body: &Value, request: &mut TextGenerationRequest) { request.temperature = body.get("temperature").and_then(Value::as_f64).map(|t| t as f32); diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs index 0f3240adaf..25e943419b 100644 --- a/core/continuum-gateway/src/wire/responses.rs +++ b/core/continuum-gateway/src/wire/responses.rs @@ -4,7 +4,7 @@ //! mind's memory, which arrives with session identity (DRIVER-GATEWAY.md G2); until then a //! call that names one is refused rather than answered without its history. -use super::{chat, event, input_schema, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{chat, event, input_schema, place_system, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse}; use serde_json::{json, Value}; @@ -44,6 +44,7 @@ impl Wire for Responses { ..Default::default() }; sampling(&body, &mut request); + (request.system_prompt, request.messages) = place_system(request.system_prompt.take(), std::mem::take(&mut request.messages)); Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed } @@ -179,7 +180,6 @@ fn items_to_messages(items: &[Value]) -> Result, BadRequest> { match kind { "message" => { let role = item.get("role").and_then(Value::as_str).ok_or_else(|| BadRequest("a message item has no `role`".into()))?; - let role = if role == "developer" { "system" } else { role }; out.push(ChatMessage { role: role.to_owned(), content: content(item.get("content").unwrap_or(&Value::Null)), name: None }); } "function_call" => { @@ -207,18 +207,7 @@ fn items_to_messages(items: &[Value]) -> Result, BadRequest> { _ => {} // reasoning and other items carry nothing the engine renders } } - // The engine's templates take one system message, at the start (as in Chat Completions). - let mut kept = Vec::with_capacity(out.len()); - for (i, mut m) in out.into_iter().enumerate() { - if m.role == "system" && i > 0 { - m.role = "user".into(); - if let MessageContent::Text(text) = &m.content { - m.content = MessageContent::Text(format!("[system] {text}")); - } - } - kept.push(m); - } - Ok(kept) + Ok(out) } fn content(value: &Value) -> MessageContent { diff --git a/core/continuum-gateway/src/wire/tests.rs b/core/continuum-gateway/src/wire/tests.rs index 27b659bc1c..6b0f56e3b3 100644 --- a/core/continuum-gateway/src/wire/tests.rs +++ b/core/continuum-gateway/src/wire/tests.rs @@ -42,6 +42,7 @@ fn anthropic_carries_tools_both_ways_and_streams_blocks_in_order() { "tools": [{"name": "read_file", "description": "Read", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}], "messages": [ {"role": "user", "content": "open a.rs"}, + {"role": "system", "content": [{"type": "text", "text": "SessionStart hook context"}]}, {"role": "assistant", "content": [{"type": "tool_use", "id": "call_0", "name": "read_file", "input": {"path": "b.rs"}}]}, {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_0", "content": [{"type": "text", "text": "fn b() {}"}]}]}, ], @@ -50,8 +51,9 @@ fn anthropic_carries_tools_both_ways_and_streams_blocks_in_order() { assert!(call.stream); assert_eq!(call.request.system_prompt.as_deref(), Some("You are a coder.")); assert_eq!(call.request.tools.as_ref().map(|t| t[0].input_schema.required.clone()), Some(Some(vec!["path".to_string()]))); - assert!(matches!(&parts(&call.request.messages[1])[0], ContentPart::ToolUse { id, .. } if id == "call_0")); - assert!(matches!(&parts(&call.request.messages[2])[0], ContentPart::ToolResult { content, .. } if content == "fn b() {}")); + assert_eq!(call.request.messages[1].role, "user", "Claude Code's mid-list system message is not sent as system"); + assert!(matches!(&parts(&call.request.messages[2])[0], ContentPart::ToolUse { id, .. } if id == "call_0")); + assert!(matches!(&parts(&call.request.messages[3])[0], ContentPart::ToolResult { content, .. } if content == "fn b() {}")); let whole = Anthropic::answer(&tool_answer(), "msg_1"); assert_eq!(whole["stop_reason"], "tool_use"); @@ -124,6 +126,7 @@ fn responses_groups_items_refuses_missing_state_and_numbers_its_events() { let call = Responses::decode(json!({ "model": "qwen", "instructions": "You are Grok.", "stream": true, "input": [ + {"type": "message", "role": "developer", "content": [{"type": "input_text", "text": "Sandbox: workspace-write."}]}, {"role": "user", "content": [{"type": "input_text", "text": "fix it"}]}, {"type": "function_call", "call_id": "c1", "name": "read", "arguments": "{\"p\":\"a\"}"}, {"type": "function_call", "call_id": "c2", "name": "read", "arguments": "{\"p\":\"b\"}"}, @@ -134,7 +137,7 @@ fn responses_groups_items_refuses_missing_state_and_numbers_its_events() { "tools": [{"type": "function", "name": "read", "parameters": {"type": "object", "properties": {"p": {"type": "string"}}}}, {"type": "web_search"}], })) .expect("test: decodes"); - assert_eq!(call.request.system_prompt.as_deref(), Some("You are Grok.")); + assert_eq!(call.request.system_prompt.as_deref(), Some("You are Grok.\n\nSandbox: workspace-write."), "a leading developer item joins the instructions"); assert_eq!(call.request.messages.len(), 4, "user, one assistant turn with both calls, two tool replies"); assert_eq!(parts(&call.request.messages[1]).len(), 2); assert_eq!(call.request.tools.as_ref().map(Vec::len), Some(1), "provider built-ins are not ours"); From 7a5aa7ad3ccb111d7661de50b2bc9dba2b3ff7ad Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 18:25:52 -0500 Subject: [PATCH 07/27] DRIVER-GATEWAY: one glass box for every system (G1.5, before G2) Joel: replay and glass boxing should be straightforward regardless of system. The capture owner moves below cognition, keyed by mind; the deliberation faculty and the gateway both write schema-v4 submitted/completed records, so the act inspector, replay and playback work on Claude Code, Codex, Grok Build, Hermes or opencode unchanged, and a captured agent session becomes a dyno validator for our engine. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/DRIVER-GATEWAY.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/docs/architecture/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md index 8bc11e1a96..cb247ccf36 100644 --- a/docs/architecture/DRIVER-GATEWAY.md +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -64,12 +64,33 @@ The `Responses` API's server-side state is exactly this: the response id names t **What the gateway does not do.** It does not run an agent loop, grade work, or rewrite the agent's prompt. It is the model behind the agent, with memory and learning. +## One glass box for every system (Joel, 2026-10-27) + +"We should have built our replay and glass boxing around this … so that this is straightforward regardless of system." + +**The seam.** Every step of every agent (Claude Code, Codex, Grok Build, Hermes, opencode) crosses the gateway. Every act of every resident crosses the deliberation faculty. Both write ONE capture, so everything we built for residents works on any system unchanged: +- the act inspector: per-act prefill, decode, reuse, view layers and divergence; +- the replay; +- the glass-box playback. + +**What moves.** The capture owner (`continuum-cognition/src/cognition/prompt_capture.rs`, 940 lines, schema v4, `fixtures/prompt-captures/.jsonl`) moves down, below both callers: Serving's floor, `continuum-engine` or its own small crate. +- It is keyed by mind (`PageKey`): resident, fork, or `driver(user, session)`. +- The deliberation faculty and the gateway are its two writers, by the same `submitted`/`completed` records. +- The private-room withholding rule moves with it. +- Scope rules (§17) decide what a driver session may record at all. + +**Why it is the tuning loop.** +- A captured Claude Code or Codex session replays against our engine on the dyno, with no live agent and no residents, under any engine config. Their loop becomes our validator: prefill per step, reuse, and time to a passing test. +- A resident's captured act is read by the same inspector beside an agent's step on the same task, so the gap is visible act by act, not argued: context size, layers, act count, reasoning length. +- Tuning our system to match theirs is then a replay comparison, and glass-boxing any system that calls us is free. + ## Build order (each slice lands with its validator first, and deletes what it replaces) | # | Slice | Validator (seconds, no residents) | Live gate | Owner | |---|---|---|---|---| | G0 | `Gateway` module on a stable port. The Anthropic adapter moved into it; `http/mod.rs`'s server deleted. | Claude Code's captured requests decode to the same `TextGenerationRequest` as today. | Claude Code on the M5 answers through it. | Fable | | G1 | OpenAI Chat Completions and Responses adapters, SSE. `GET /v1/models`. | Round-trip fixtures from each agent's captured traffic (Grok Build's `mock_server_tests` show its shapes). | Hermes, opencode and Grok Build each complete a coding task on the M5. | Fable | +| G1.5 | **One capture for every system:** `prompt_capture` moved below cognition, keyed by mind. The gateway writes the same schema-v4 records as residents. | The act inspector and `serving-replay` read a captured Claude Code session exactly as a resident's. | The four-agent median-bug run glass-boxed beside Benchy's run on the same task. | Fable | | G2 | Session identity: `PageKey::driver`, seated through `MindMemory::seat` (needs §1a step 1). | Replay a captured agent session: prefix reuse per step at least 90%, and no resident evicted unsaved. | **The speed gate:** the same agent and model on the gateway vs stock llama-server, with four residents running. Time per agent step and re-prefilled tokens. | Fable (seat), Codex (scheduling temperature) | | G3 | Capture to the perception stream, under the scope rules. | A captured session yields perception rows and no secret. | — | Cormac (learning side) | | G4 | Driver genes: selected by what the session is on, served to the session. | — | **The learning gate** (§17's proof): correct an agent once, restart, give it an unseen related task. It succeeds; without the gene it fails. | Cormac, Fable | From ab4fb33f245c0aa39b34bd4773a5e5f928f67fc4 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 18:26:09 -0500 Subject: [PATCH 08/27] DRIVER-GATEWAY: learning and the genome ride the same capture seam (layering table) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/DRIVER-GATEWAY.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/architecture/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md index cb247ccf36..df2d97d460 100644 --- a/docs/architecture/DRIVER-GATEWAY.md +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -79,6 +79,17 @@ The `Responses` API's server-side state is exactly this: the response id names t - The private-room withholding rule moves with it. - Scope rules (§17) decide what a driver session may record at all. +**The layering: learning and the genome ride the same seam** (Joel: "learning and genome must work anyway. All about proper layering"). + +| Layer | Owners | Rule | +|---|---|---| +| 1. Serving floor | the engine; `MindMemory` (SERVING-ENGINE §1a); the capture owner | One identity, the mind (`PageKey`), for a resident, a fork or a driver session. | +| 2. Writers | the residents' deliberation faculty; the gateway (every external agent) | Both write the same capture. Neither knows the readers. | +| 3. Readers of the capture | glass box and replay (act inspector, playback, `serving-replay`); Dreaming (`dataset/from_captures` → training → genes) | They read records, never which system produced them. | +| 4. Genome | genes selected by what a mind is on, served at `MindMemory::seat` | A gene change calls `forget`, so KV computed under the old genome is never restored. | + +A driver session is perception like a resident's act. It is learned from under the scope rules and served genes the same way. Nothing above layer 1 special-cases a system. + **Why it is the tuning loop.** - A captured Claude Code or Codex session replays against our engine on the dyno, with no live agent and no residents, under any engine config. Their loop becomes our validator: prefill per step, reuse, and time to a passing test. - A resident's captured act is read by the same inspector beside an agent's step on the same task, so the gap is visible act by act, not argued: context size, layers, act count, reasoning length. From 5d381684bc23b9aa8cde18bcfc6b6aeef1d03854 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 18:29:19 -0500 Subject: [PATCH 09/27] DRIVER-GATEWAY G-lean: a Serving-only continuum-serve binary for drivers, learning opt-in Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/DRIVER-GATEWAY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/architecture/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md index df2d97d460..f7ce6a0280 100644 --- a/docs/architecture/DRIVER-GATEWAY.md +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -102,6 +102,7 @@ A driver session is perception like a resident's act. It is learned from under t | G0 | `Gateway` module on a stable port. The Anthropic adapter moved into it; `http/mod.rs`'s server deleted. | Claude Code's captured requests decode to the same `TextGenerationRequest` as today. | Claude Code on the M5 answers through it. | Fable | | G1 | OpenAI Chat Completions and Responses adapters, SSE. `GET /v1/models`. | Round-trip fixtures from each agent's captured traffic (Grok Build's `mock_server_tests` show its shapes). | Hermes, opencode and Grok Build each complete a coding task on the M5. | Fable | | G1.5 | **One capture for every system:** `prompt_capture` moved below cognition, keyed by mind. The gateway writes the same schema-v4 records as residents. | The act inspector and `serving-replay` read a captured Claude Code session exactly as a resident's. | The four-agent median-bug run glass-boxed beside Benchy's run on the same task. | Fable | +| G-lean | **A lean install for drivers** (Joel: "only install these features, reducing bloat"). A `continuum-serve` binary built from the Serving seam only: gateway, `continuum-serving` (the engine lifecycle), `continuum-engine` with `MindMemory`, and the capture owner. Learning is opt-in by adding `continuum-dreaming`. No personas, rooms, airc, desktop or academy. The provider registration moves down from the core's AI module, so both binaries share it. | `cargo tree` shows no `continuum-core`, `continuum-mind` or `continuum-cognition`. The four-agent run passes on the lean binary. | Binary size, build time and RSS at idle against the full core. The same four agents on a machine with only the lean install. | Fable (binary), Codex (engine lifecycle seam) | | G2 | Session identity: `PageKey::driver`, seated through `MindMemory::seat` (needs §1a step 1). | Replay a captured agent session: prefix reuse per step at least 90%, and no resident evicted unsaved. | **The speed gate:** the same agent and model on the gateway vs stock llama-server, with four residents running. Time per agent step and re-prefilled tokens. | Fable (seat), Codex (scheduling temperature) | | G3 | Capture to the perception stream, under the scope rules. | A captured session yields perception rows and no secret. | — | Cormac (learning side) | | G4 | Driver genes: selected by what the session is on, served to the session. | — | **The learning gate** (§17's proof): correct an agent once, restart, give it an unseen related task. It succeeds; without the gene it fails. | Cormac, Fable | From c7bee295635a6c3bb6298632d8c88db7774f97a5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 18:30:08 -0500 Subject: [PATCH 10/27] Plan lines 3b and 16: MindMemory first, the driver gateway live; continuum-gateway a declared workspace member MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 3b: MindMemory (SERVING-ENGINE §1a) comes before the fork verbs, Codex owning the lifecycle callers. 16: the gateway is live on the M5 (four agents fixed a real bug through it); next G1.5 one capture for every system, then G2 warm sessions; a lean continuum-serve install. Root Cargo.toml and Cargo.lock now carry the gateway crate the earlier commits added under core/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- CLAUDE.md | 4 ++-- Cargo.lock | 17 +++++++++++++++++ Cargo.toml | 1 + 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 358de0408b..4c73083c59 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -159,7 +159,7 @@ wait, a wait means start your next line; update this table when a line lands or | 1 | The build loop: split the monolith BY THE PLACEMENT MAP (MODULE-ARCHITECTURE.md §9.2: each major module runs on any node); build with serving down or on an available non-serving executor/CI, use every grid machine | Fable (cuts), Codex (crate graph, parallel cut order) | #5194 continuum-base + gates cover split crates (CI); #5195 deletes 13,275 dead lines (CI); next: parallel cuts by several agents, own worktrees and target dirs | edit-to-checked < 2 min | | 2 | A mind's context as an epoch (reuse 48% -> 90%+) | Fable + Codex | continuum-context slices 1-2 pushed (replay: 92-95% reuse, ~3x less fresh); next: wire the faculty's render path into Epoch | live reuse >= 80% | | 3 | `EngineConfig` and KV capacity (#5188), incl. unrecorded backend -> f16/no-FA/half budget (Cormac's item 10) | Fable | resolve-then-adopt owner in inference/planning | no queue wait; warm-ahead runs | -| 3b | One live engine, minds' memory moved by us (Joel, 10-23: "It's supposed to be quite dynamic and adapt to concerns, not be killing and starting servers. You can't optimize if you're killing and restarting."). Serving drives libllama in-process (`continuum-engine` `llamacpp_scheduler`): weights load once; context and slots resize live; each mind's KV pages GPU <-> RAM <-> disk per sequence (`llama_state_seq_*`); shared prefixes are copied (`seq_cp`), never re-prefilled; one memory budget. llama-server becomes the OpenAI-compatible adapter for external drivers (line 16); relaunch only a dead engine. Launch flags carry startup facts only | Fable (engine, paging), Codex (admission, relaunch call sites) | design: `docs/architecture/SERVING-ENGINE.md` (2026-10-24): add page/reconfigure/priority verbs to the fork's server (S1-S3, proven over today's endpoint), then a separate `continuum-serving` process hosts it with Rust policy (S5); slices S0-S7 each land with a seconds-scale validator | median act at 4 residents beats llama-server, reuse >= 80%, no relaunch while serving, footprint flat over 100 resize cycles | +| 3b | One live engine, minds' memory moved by us (Joel, 10-23: "It's supposed to be quite dynamic and adapt to concerns, not be killing and starting servers. You can't optimize if you're killing and restarting."). Serving drives libllama in-process (`continuum-engine` `llamacpp_scheduler`): weights load once; context and slots resize live; each mind's KV pages GPU <-> RAM <-> disk per sequence (`llama_state_seq_*`); shared prefixes are copied (`seq_cp`), never re-prefilled; one memory budget. llama-server becomes the OpenAI-compatible adapter for external drivers (line 16); relaunch only a dead engine. Launch flags carry startup facts only | Fable (engine, paging), Codex (admission, relaunch call sites) | FIRST (10-27): MindMemory, the one owner of every mind's KV (SERVING-ENGINE §1a, API published, Codex accepted): seat/pause/retire/resume/attach/forget replace 41 paths; Fable builds seat + its stop, Codex moves relaunch/academy/idle/adopt onto pause. Then the fork verbs: design `docs/architecture/SERVING-ENGINE.md` (2026-10-24): add page/reconfigure/priority verbs to the fork's server (S1-S3, proven over today's endpoint), then a separate `continuum-serving` process hosts it with Rust policy (S5); slices S0-S7 each land with a seconds-scale validator | median act at 4 residents beats llama-server, reuse >= 80%, no relaunch while serving, footprint flat over 100 resize cycles | | 4 | Engine flags | Fable | DONE e678bb30c: prefill 105 -> 175-206 tok/s; decode drop under builds is line 1's | receipts on 9b9f3b59 | | 5 | Core CPU: cosine owner (#5189), revisioned vector corpus + BLAS + cascade, rayon spin | Codex | #5189: drop the two re-exports, then the corpus | idle-core sample near zero | | 6 | Every fast-path miss loud | Cormac | #5190: count resident_prefix_lost; #5191: probe wording; then the rest of the 24 | each miss class has a fixture | @@ -172,7 +172,7 @@ wait, a wait means start your next line; update this table when a line lands or | 13 | Prefill during tool calls; the instant voice | Fable, Codex | after lines 2-3 | submit-to-first-token | | 14 | Learned policies on our own receipts; residents review docs PRs; Atlas silent; Aiko gaps | open / residents | after the validators | each beats its constant offline | | 15 | Distributable modules: headless default (`default = []`; avatar-3d and livekit enabled per node by deploy profile), grid trust (every node reads `blocked` on 10-19), checks dispatched to idle grid nodes | Fable (default + profiles), Codex (trust), peers on the 5090/IntelMac (take checks) | profiles first, then flip the default with a before/after check time | a node joins by capability; an AWS box builds the core with no renderer | -| 16 | Be the addendum: a Hermes driver on our seams. (a) Serving: Hermes on our engine vs Hermes on a stock server, same model and tasks, speed before/after; (b) Learning: once the acceptance test passes (a reviewed correction on unseen tasks, retained after restart, vs the base without the gene), Hermes sessions become perception and its corrections become genes. Drivers reach seams, not machines, so this is cross-grid by placement; and the agents developing continuum (Claude Code, Codex) are drivers too: our own dev sessions become the Matrix Dojo curriculum and we are the seams' first heavy users (Joel: "a good way to develop our own system") | OPEN: claim it after the queue clears | (a) first, needs no learning claim | Hermes users get our speed, then learning, by pointing at continuum | +| 16 | Be the addendum: one gateway every agent calls (`docs/architecture/DRIVER-GATEWAY.md`, 10-27). Claude Code (Anthropic Messages), Hermes and opencode (Chat Completions), Grok Build and Codex CLI (Responses) point at continuum by base URL only. A session is a mind seated by MindMemory; every exchange is ONE capture (residents' too), read by the glass box, replay and Dreaming, and the genome serves any mind. A lean `continuum-serve` install carries only the Serving seam (learning opt-in). Learning for drivers ships after the residents pass the acceptance test | Fable (gateway, capture, lean), Codex (scheduling temperature, engine lifecycle), Cormac (capture under scope, driver genes) | G0-G1 LIVE on the M5 10-27 (f124f30b8): Claude Code, Hermes, opencode and Codex each fixed a real bug through it on our Qwen3.6-35B. Next: G1.5 one capture for every system (the capture owner moves below cognition, keyed by mind), then G2 session = warm mind, timed against stock llama-server | Hermes users get our speed, then learning, by pointing at continuum | **The speed path** (Joel, 10-26: "we know what to work on to get speed ups... including the brainstormed work we can just iterate forward"). Rows are priorities, not a strict sequence: the offline diff --git a/Cargo.lock b/Cargo.lock index cd9f9cb12d..2521a606a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2975,6 +2975,7 @@ dependencies = [ "continuum-embedding", "continuum-engine", "continuum-experience", + "continuum-gateway", "continuum-genome", "continuum-git", "continuum-grid", @@ -3206,6 +3207,22 @@ dependencies = [ "tokio", ] +[[package]] +name = "continuum-gateway" +version = "0.1.0" +dependencies = [ + "async-trait", + "axum", + "continuum-base", + "continuum-engine", + "serde", + "serde_json", + "tokio", + "tokio-stream", + "tracing", + "uuid", +] + [[package]] name = "continuum-genome" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 2f1441fc98..3ad7b6aa37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ members = [ # its only spawn wiring pointed at a dir that no longer exists. "core/continuum-cli-lifecycle", "core/continuum-tool-protocol", + "core/continuum-gateway", "core/continuum-base", "core/continuum-flow", "core/continuum-git", From 8a8df77d18dbacc8e30409060684461eb0f59142 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 18:48:07 -0500 Subject: [PATCH 11/27] DRIVER-GATEWAY G5: org genomes, a repo's gene learned from every member's sessions and worn by all Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/DRIVER-GATEWAY.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/architecture/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md index f7ce6a0280..24beb77da1 100644 --- a/docs/architecture/DRIVER-GATEWAY.md +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -106,9 +106,22 @@ A driver session is perception like a resident's act. It is learned from under t | G2 | Session identity: `PageKey::driver`, seated through `MindMemory::seat` (needs §1a step 1). | Replay a captured agent session: prefix reuse per step at least 90%, and no resident evicted unsaved. | **The speed gate:** the same agent and model on the gateway vs stock llama-server, with four residents running. Time per agent step and re-prefilled tokens. | Fable (seat), Codex (scheduling temperature) | | G3 | Capture to the perception stream, under the scope rules. | A captured session yields perception rows and no secret. | — | Cormac (learning side) | | G4 | Driver genes: selected by what the session is on, served to the session. | — | **The learning gate** (§17's proof): correct an agent once, restart, give it an unseen related task. It succeeds; without the gene it fails. | Cormac, Fable | +| G5 | **Org genomes** (Joel, 2026-10-27: "genome is also given to them; shared … learned repos shared within an org"). A repo's gene is learned from every developer's agent sessions in that repo, plus the repo's history (REPO-GENOME-AND-COURSES §17). Every org member's agent wears it the first time it works there. Private repos' genes stay on the org's own nodes over the grid; publishing beyond the org is an explicit act; secrets never enter. Fitness is usage across the org; revocation removes the skill. | A gene learned from one member's corrected session passes the acceptance test on another member's agent in the same repo. | An org of two (two machines, two agents, one repo): a correction made on one machine is applied on an unseen task by the other's agent after a restart. | Cormac (genome), Codex (grid trust), Fable (gateway serving) | G0 and G1 can start now. G2 waits on MindMemory's `seat`, and G4 on the residents passing the learning acceptance test (plan pipeline step 3). +## Crate divisions this work exposes (Joel: "if you see more crate divisions note or build them") + +| Crate | State | From | Why it is its own crate | +|---|---|---|---| +| `continuum-gateway` | BUILT 10-27 | `continuum-core/src/http` (Anthropic-only endpoint deleted) | The Serving seam's door; depends only on the engine and capture. | +| `continuum-capture` | BUILT 10-27 | `continuum-cognition`: `prompt_capture`, its store and owner, `mind_room`, `fixture_dir` (1,920 lines moved with history, 38 callers) | One capture and one privacy gate below every writer (faculty, gateway) and reader (inspector, replay, Dreaming). | +| `continuum-mind-memory` | NEXT | `continuum-engine/src/inference/slots/*` plus the paging block of `turn_admission.rs` | SERVING-ENGINE §1a's owner. A crate keeps every other path from reaching `holders` or the ledger again. | +| `continuum-providers` | NOTED | the AI provider module's registration in `continuum-core` | The lean `continuum-serve` and the full core must register adapters the same way, without the core. | +| `continuum-serve` (bin) | NOTED | — | G-lean: the Serving seam alone, learning opt-in. | +| `*-types` crates | NOTED | wire types shared by two crates (for example `TextGenerationRequest` and the capture records) | Grok Build's pattern (`xai-grok-config-types`): consumers depend on types, not on the engine. Cut where a reader such as `serving-replay` or the act inspector needs records without the engine. | +| `wire_tap` | NOTED | `continuum-engine/src/inference/wire_tap.rs` | The raw-stream tap is armed only by the capture lease: it may belong in `continuum-capture`, behind a trait the engine calls. | + ## Measured before and after - Per agent step: submit-to-first-token, total time, tokens re-prefilled, and tokens appended. From ecfd38dfd11a87aacc7a354adcadc98e2f364c09 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 19:09:05 -0500 Subject: [PATCH 12/27] A driver session is a mind: warm, paged and recorded in the one capture (G2-lite) - `driver` is a Turn in the engine's one purpose->class map (DRIVER_PURPOSE), and the gateway sends the session id as the request's mind: a session gets a leased, pinned slot, a confirmed save on eviction and a restore on return, as a resident does. - The session id is the conversation's stable head (system prompt + first user turn), until MindMemory seats sessions explicitly; `x-continuum-session: off` opts out. - Every call is recorded through continuum-capture, keyed by session, so the act inspector and replay read an agent's session as they read a resident's acts. - Usage reports reuse in each format's own field: prompt_tokens_details.cached_tokens (Chat), cache_read_input_tokens (Anthropic), input_tokens_details.cached_tokens (Responses). Tested: continuum-gateway 4 passed (incl. one session per agent session, another task another session); continuum-engine slots 43 passed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/inference/request_body.rs | 3 + .../src/inference/slots/citizen_slots.rs | 3 +- core/continuum-gateway/src/lib.rs | 1 + core/continuum-gateway/src/server.rs | 39 +++++++-- core/continuum-gateway/src/session.rs | 79 +++++++++++++++++++ core/continuum-gateway/src/wire/anthropic.rs | 13 ++- core/continuum-gateway/src/wire/chat.rs | 10 ++- core/continuum-gateway/src/wire/mod.rs | 7 +- core/continuum-gateway/src/wire/responses.rs | 5 +- 9 files changed, 143 insertions(+), 17 deletions(-) create mode 100644 core/continuum-gateway/src/session.rs diff --git a/core/continuum-engine/src/inference/request_body.rs b/core/continuum-engine/src/inference/request_body.rs index b7ee12cb73..e0eeb409af 100644 --- a/core/continuum-engine/src/inference/request_body.rs +++ b/core/continuum-engine/src/inference/request_body.rs @@ -50,6 +50,9 @@ pub const DELIBERATION_PURPOSE: &str = "cognition/deliberation"; /// beside the living one. The same reasoning budgets as [`ACT_PURPOSE`] and /// [`DELIBERATION_PURPOSE`]; only the page differs: a fork warms its own page per room, /// never the mind's one page (`slots::PageKey::Fork`), and never waits on her act gate. +/// An external agent's call through the driver gateway: a Turn of its session's mind, so the +/// session keeps a warm, paged page exactly as a resident does (DRIVER-GATEWAY.md G2). +pub const DRIVER_PURPOSE: &str = "driver"; pub const FORK_ACT_PURPOSE: &str = "cognition/fork-act"; pub const FORK_DELIBERATION_PURPOSE: &str = "cognition/fork-deliberation"; diff --git a/core/continuum-engine/src/inference/slots/citizen_slots.rs b/core/continuum-engine/src/inference/slots/citizen_slots.rs index 3b42cf7fbc..2eed3bb500 100644 --- a/core/continuum-engine/src/inference/slots/citizen_slots.rs +++ b/core/continuum-engine/src/inference/slots/citizen_slots.rs @@ -65,7 +65,8 @@ pub fn class_for(purpose: Option<&str>) -> SlotClass { Some("cognition/deliberation") | Some("cognition/act") | Some("persona-respond") - | Some("persona_decide_and_respond") => SlotClass::Turn, + | Some("persona_decide_and_respond") + | Some(crate::inference::request_body::DRIVER_PURPOSE) => SlotClass::Turn, Some("cognition/should-respond") | Some("cognition/generate-response") | Some("cognition/validate-response-decision") diff --git a/core/continuum-gateway/src/lib.rs b/core/continuum-gateway/src/lib.rs index 4ec83f3557..8619d98f7b 100644 --- a/core/continuum-gateway/src/lib.rs +++ b/core/continuum-gateway/src/lib.rs @@ -12,6 +12,7 @@ mod module; mod route; mod server; +mod session; mod wire; pub use module::GatewayModule; diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs index 28933249c8..a90fa5183c 100644 --- a/core/continuum-gateway/src/server.rs +++ b/core/continuum-gateway/src/server.rs @@ -29,8 +29,8 @@ async fn models() -> Json { } /// Decode, select, generate, encode: the same for every format. -async fn serve(Json(body): Json) -> Response { - let call = match W::decode(body) { +async fn serve(headers: axum::http::HeaderMap, Json(body): Json) -> Response { + let mut call = match W::decode(body) { Ok(call) => call, Err(BadRequest(why)) => return refuse::(StatusCode::BAD_REQUEST, ErrorKind::InvalidRequest, &why), }; @@ -40,11 +40,26 @@ async fn serve(Json(body): Json) -> Response { Err(error) => return refused::(error), }; let id = format!("{}_{}", prefix::(), uuid::Uuid::new_v4().simple()); - continuum_base::probe!(class = "gateway.call", wire = W::NAME, model = %model, stream = call.stream, + let session = crate::session::session_of(&call.request); + // The session is a mind: its id keys a warm page the engine pins, saves and restores. + // `x-continuum-session: off` asks for no session memory (a one-shot call). + let remembered = headers.get("x-continuum-session").and_then(|v| v.to_str().ok()) != Some("off"); + if remembered { + call.request.persona_id = Some(session.to_string()); + } + continuum_base::probe!(class = "gateway.call", wire = W::NAME, model = %model, stream = call.stream, session = %session, remembered = remembered, tools = call.request.tools.as_ref().map_or(0, Vec::len) as u64, messages = call.request.messages.len() as u64, "an agent's call reached the engine through the gateway"); + let mut lease = crate::session::record(session, &id, W::NAME, &call.request); if !call.stream { - return match route::generate(&adapter, call.request).await { + let outcome = route::generate(&adapter, call.request).await; + if let Some(lease) = lease.as_mut() { + match &outcome { + Ok(response) => lease.finish(Some(response), None), + Err(error) => lease.finish(None, Some(&format!("{error:?}"))), + }; + } + return match outcome { Ok(response) => Json(W::answer(&response, &id)).into_response(), Err(error) => refused::(error), }; @@ -56,7 +71,7 @@ async fn serve(Json(body): Json) -> Response { let generation = tokio::spawn(async move { route::stream(&adapter, call.request, chunks).await }); let send = |batch: Vec| batch.into_iter().all(|f| events.send(Ok::<_, std::convert::Infallible>(f.into_event())).is_ok()); if !send(encoder.opened()) { - return; // the agent left; the generation runs to completion and is dropped + return; // the agent left; the lease records the call as cancelled when dropped } while let Some(chunk) = received.recv().await { if !send(encoder.chunk(&chunk)) { @@ -64,8 +79,18 @@ async fn serve(Json(body): Json) -> Response { } } let closing = match generation.await { - Ok(Ok(response)) => encoder.finished(&response), - Ok(Err(RouteError::Engine(why))) => encoder.failed(&why), + Ok(Ok(response)) => { + if let Some(lease) = lease.as_mut() { + lease.finish(Some(&response), None); + } + encoder.finished(&response) + } + Ok(Err(RouteError::Engine(why))) => { + if let Some(lease) = lease.as_mut() { + lease.finish(None, Some(&why)); + } + encoder.failed(&why) + } Ok(Err(RouteError::UnknownModel { model, .. })) => encoder.failed(&format!("model `{model}` is not served here")), Err(join) => encoder.failed(&format!("generation task ended: {join}")), }; diff --git a/core/continuum-gateway/src/session.rs b/core/continuum-gateway/src/session.rs new file mode 100644 index 0000000000..c212996843 --- /dev/null +++ b/core/continuum-gateway/src/session.rs @@ -0,0 +1,79 @@ +//! Which session a call belongs to, and its capture. +//! +//! Until a session is seated as a mind (DRIVER-GATEWAY.md G2), its identity is its stable +//! head: the system prompt and the first user turn, which an agent re-sends unchanged on +//! every step of one session. Every call is recorded in the one capture the residents use +//! (`continuum-capture`), keyed by that id, so the act inspector, replay and Dreaming read an +//! agent's session exactly as they read a resident's acts. + +use std::sync::Arc; + +use continuum_capture::{CaptureLease, JsonlPromptCaptureSink, PromptCall, PromptCaptureSink}; +use continuum_engine::ai::TextGenerationRequest; +use uuid::Uuid; + +/// The namespace driver session ids are derived in. Fixed forever: changing it would split +/// every recorded session from its later calls. +const DRIVER_SESSIONS: Uuid = Uuid::from_bytes(*b"driver-sessions!"); + +/// The session a call belongs to: the same id for every step of one agent session. +pub(crate) fn session_of(request: &TextGenerationRequest) -> Uuid { + let mut head = request.system_prompt.clone().unwrap_or_default(); // unwrap_or_default: an agent may send no system prompt + if let Some(first) = request.messages.iter().find(|m| m.role == "user") { + head.push('\u{1f}'); + head.push_str(&crate::wire::plain_text(&first.content)); + } + Uuid::new_v5(&DRIVER_SESSIONS, head.as_bytes()) +} + +/// Start recording one call of `session`. `None` when the capture home cannot be opened, +/// said in a probe: an unrecorded call is still served. +pub(crate) fn record(session: Uuid, request_id: &str, wire: &'static str, request: &TextGenerationRequest) -> Option { + let sink: Arc = match JsonlPromptCaptureSink::open_for_persona(session) { + Ok(sink) => Arc::new(sink), + Err(error) => { + continuum_base::probe!(class = "gateway.capture_unavailable", session = %session, error = %error, + "this agent call is served but not recorded"); + return None; + } + }; + let call = PromptCall { + request_id: request_id.to_owned(), + persona_id: session, + room_id: Uuid::nil(), + cycle_id: None, + context_window: None, + cause: wire, + cause_root: None, + replay_of: None, + }; + Some(CaptureLease::start(sink, &call, request)) +} + +#[cfg(test)] +mod tests { + use super::*; + use continuum_engine::ai::{ChatMessage, MessageContent}; + + fn request(system: &str, turns: &[(&str, &str)]) -> TextGenerationRequest { + TextGenerationRequest { + system_prompt: Some(system.into()), + messages: turns + .iter() + .map(|(role, text)| ChatMessage { role: (*role).into(), content: MessageContent::Text((*text).into()), name: None }) + .collect(), + ..Default::default() + } + } + + // what this catches: one agent session recorded as many (its later steps keep the same + // head and append), or two sessions merged (a different task is a different head). + #[test] + fn every_step_of_a_session_is_one_session_and_another_task_is_another() { + let first = request("You are a coder.", &[("user", "fix median")]); + let later = request("You are a coder.", &[("user", "fix median"), ("assistant", "reading"), ("user", "[tool] ok")]); + let other = request("You are a coder.", &[("user", "add a mode() function")]); + assert_eq!(session_of(&first), session_of(&later)); + assert_ne!(session_of(&first), session_of(&other)); + } +} diff --git a/core/continuum-gateway/src/wire/anthropic.rs b/core/continuum-gateway/src/wire/anthropic.rs index ca50d85ecc..676a7d1fac 100644 --- a/core/continuum-gateway/src/wire/anthropic.rs +++ b/core/continuum-gateway/src/wire/anthropic.rs @@ -35,7 +35,7 @@ impl Wire for Anthropic { messages: messages.iter().map(message).collect::>()?, tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), tool_choice: body.get("tool_choice").and_then(tool_choice), - purpose: Some("driver".into()), + purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), ..Default::default() }; sampling(&body, &mut request); @@ -58,7 +58,7 @@ impl Wire for Anthropic { "id": id, "type": "message", "role": "assistant", "model": response.model, "content": content, "stop_reason": stop_reason(response), "stop_sequence": null, - "usage": {"input_tokens": response.usage.input_tokens, "output_tokens": response.usage.output_tokens}, + "usage": usage(response), }) } @@ -108,7 +108,7 @@ impl Wire for Anthropic { } events.push(event(Some("message_delta"), &json!({"type": "message_delta", "delta": {"stop_reason": stop_reason(response), "stop_sequence": null}, - "usage": {"input_tokens": response.usage.input_tokens, "output_tokens": response.usage.output_tokens}}))); + "usage": usage(response)}))); events.push(event(Some("message_stop"), &json!({"type": "message_stop"}))); events } @@ -153,6 +153,13 @@ impl Anthropic { } } +/// Anthropic counts cache reads apart from fresh input: `input_tokens` is what was prefilled. +fn usage(response: &TextGenerationResponse) -> Value { + let cached = super::cached_tokens(response).unwrap_or(0); // unwrap_or: no measured reuse reads as none + json!({"input_tokens": response.usage.input_tokens.saturating_sub(cached), "output_tokens": response.usage.output_tokens, + "cache_read_input_tokens": cached}) +} + fn stop_reason(response: &TextGenerationResponse) -> &'static str { if stopped_for_tools(response) { "tool_use" diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs index ec2d6878ce..410f5d9412 100644 --- a/core/continuum-gateway/src/wire/chat.rs +++ b/core/continuum-gateway/src/wire/chat.rs @@ -31,7 +31,7 @@ impl Wire for Chat { messages, tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), tool_choice: body.get("tool_choice").and_then(tool_choice), - purpose: Some("driver".into()), + purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), ..Default::default() }; sampling(&body, &mut request); @@ -127,8 +127,12 @@ fn finish_reason(response: &TextGenerationResponse) -> &'static str { } fn usage(response: &TextGenerationResponse) -> Value { - json!({"prompt_tokens": response.usage.input_tokens, "completion_tokens": response.usage.output_tokens, - "total_tokens": response.usage.input_tokens + response.usage.output_tokens}) + let mut usage = json!({"prompt_tokens": response.usage.input_tokens, "completion_tokens": response.usage.output_tokens, + "total_tokens": response.usage.input_tokens + response.usage.output_tokens}); + if let Some(cached) = super::cached_tokens(response) { + usage["prompt_tokens_details"] = json!({"cached_tokens": cached}); + } + usage } fn function_call((id, name, input): &(String, String, Value)) -> Value { diff --git a/core/continuum-gateway/src/wire/mod.rs b/core/continuum-gateway/src/wire/mod.rs index 19f6c04d47..eb53881887 100644 --- a/core/continuum-gateway/src/wire/mod.rs +++ b/core/continuum-gateway/src/wire/mod.rs @@ -153,7 +153,7 @@ pub(crate) fn place_system(system_prompt: Option, messages: Vec String { +pub(crate) fn plain_text(content: &MessageContent) -> String { match content { MessageContent::Text(text) => text.clone(), MessageContent::Parts(parts) => parts @@ -167,6 +167,11 @@ fn plain_text(content: &MessageContent) -> String { } } +/// Prompt tokens the engine reused from a warm page this call, when it measured them. +pub(crate) fn cached_tokens(response: &TextGenerationResponse) -> Option { + response.timing.as_ref().map(|t| t.cached_tokens) +} + /// The sampling fields every format names the same way: temperature, top_p, stop. pub(crate) fn sampling(body: &Value, request: &mut TextGenerationRequest) { request.temperature = body.get("temperature").and_then(Value::as_f64).map(|t| t as f32); diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs index 25e943419b..9a596e61ed 100644 --- a/core/continuum-gateway/src/wire/responses.rs +++ b/core/continuum-gateway/src/wire/responses.rs @@ -40,7 +40,7 @@ impl Wire for Responses { messages, tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), tool_choice: body.get("tool_choice").and_then(chat::tool_choice), - purpose: Some("driver".into()), + purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), ..Default::default() }; sampling(&body, &mut request); @@ -150,7 +150,8 @@ fn envelope(id: &str, model: &str, created: u64, status: &str, output: Vec Date: Tue, 27 Oct 2026 21:30:19 -0500 Subject: [PATCH 13/27] The MTP draft runs only while a turn decodes alone (adaptive speculation) Measured on the M5 2026-10-28 02:21Z, our llama-server alone, Qwen3.6-35B-A3B: one stream 80 t/s with the draft vs 57 without; two streams 84 vs 89 aggregate; four 91 vs 122. Stock llama.cpp batches like our server without a draft (llama-batched-bench 59/90/124), so nothing serializes: the draft's extra verify tokens make a bigger MoE batch read more experts. The adapter sets speculative.n_max = 0 per request when other turns hold the engine (permit_target - available - 1), inside the block that only runs against our own engine; alone, the engine's draft stays. Policy and receipts in inference::speculation. Tested: continuum-engine speculation/openai_adapter/request_body 46 passed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/ai/openai_adapter/stream.rs | 8 +++++ core/continuum-engine/src/inference/mod.rs | 1 + .../src/inference/speculation.rs | 36 +++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 core/continuum-engine/src/inference/speculation.rs diff --git a/core/continuum-engine/src/ai/openai_adapter/stream.rs b/core/continuum-engine/src/ai/openai_adapter/stream.rs index 3ff6b0b76f..8712288477 100644 --- a/core/continuum-engine/src/ai/openai_adapter/stream.rs +++ b/core/continuum-engine/src/ai/openai_adapter/stream.rs @@ -243,6 +243,14 @@ impl OpenAICompatibleAdapter { } let placement = decided.slot; _admission = Some(adm); + // The draft only while this turn decodes alone (`inference::speculation`). + let others = self + .permit_target + .load(std::sync::atomic::Ordering::Relaxed) + .saturating_sub(self.concurrency.available_permits() + 1); + if let (Some(limit), Some(obj)) = (crate::inference::speculation::draft_limit(others), body.as_object_mut()) { + obj.insert("speculative.n_max".to_string(), json!(limit)); + } // GLASS BOX (KV-reuse 0% hunt 2026-08-26): the whole cache-reuse win // rides on placement. Report class + room so a cached:0 streak names // WHICH activity thrashed — or which class strayed off scratch. diff --git a/core/continuum-engine/src/inference/mod.rs b/core/continuum-engine/src/inference/mod.rs index 39296e047d..0ba5c34d7c 100644 --- a/core/continuum-engine/src/inference/mod.rs +++ b/core/continuum-engine/src/inference/mod.rs @@ -70,6 +70,7 @@ pub mod ort_providers; pub mod placement_capture; pub mod recipe_budget; pub mod request_body; +pub(crate) mod speculation; pub mod governed_budget; pub mod resource_admission; pub mod serving_footprints; diff --git a/core/continuum-engine/src/inference/speculation.rs b/core/continuum-engine/src/inference/speculation.rs new file mode 100644 index 0000000000..6fe275623b --- /dev/null +++ b/core/continuum-engine/src/inference/speculation.rs @@ -0,0 +1,36 @@ +//! Adaptive speculation: the MTP draft runs only while a turn decodes alone. +//! +//! Measured on the M5, 2026-10-28 02:21Z (engine-c 741b0175b, Qwen3.6-35B-A3B Q4_K_M, our +//! llama-server alone, 256-token decodes, t/s per stream / aggregate): +//! +//! | streams | draft (MTP n_max 4) | no draft | +//! |---|---|---| +//! | 1 | 80 / 80 | 57 / 57 | +//! | 2 | 42 / 84 | 44 / 89 | +//! | 4 | 23 / 91 | 31 / 122 | +//! +//! Stock llama.cpp batches as well as our server without a draft (llama-batched-bench: 59, 90, +//! 124 aggregate), so nothing serializes: the draft adds tokens every stream verifies, and on +//! this MoE model a bigger batch reads more experts, so drafting under concurrency costs more +//! than it saves. Set per request (`speculative.n_max`), never by relaunching the engine. The +//! crossover is this node's; a node with another model or backend measures its own. + +/// The draft limit for a turn admitted while `others` other turns hold the engine: `None` +/// keeps the engine's own draft (this turn decodes alone), `Some(0)` drafts nothing. +pub(crate) fn draft_limit(others: usize) -> Option { + (others > 0).then_some(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: drafting while other minds decode (the M5: 91 against 122 t/s at four + // streams), or losing the draft when a turn decodes alone (80 against 57 t/s). + #[test] + fn a_turn_drafts_alone_and_never_beside_another() { + assert_eq!(draft_limit(0), None); + assert_eq!(draft_limit(1), Some(0)); + assert_eq!(draft_limit(3), Some(0)); + } +} From 7245bbc97d8a8dfe1c54d021a67d8bd9ca46c3f5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 22:21:27 -0500 Subject: [PATCH 14/27] =?UTF-8?q?SERVING-ENGINE=20=C2=A71b:=20what=20concu?= =?UTF-8?q?rrent=20minds=20cost=20on=20the=20M5,=20measured=20by=20layer?= =?UTF-8?q?=20(decode,=20draft,=20page=20IO,=20memory)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/SERVING-ENGINE.md | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/docs/architecture/SERVING-ENGINE.md b/docs/architecture/SERVING-ENGINE.md index 80ac12db40..1d250ead7e 100644 --- a/docs/architecture/SERVING-ENGINE.md +++ b/docs/architecture/SERVING-ENGINE.md @@ -181,6 +181,55 @@ Each scenario asserts where every mind resumes, in seconds, before any live read Each step deletes what it replaces in the same PR, and the lifecycle validator gains that step's scenario first. +## 1b. What concurrent minds cost on the M5: measured 2026-10-28 + +These findings come from engine-c 741b0175b with Qwen3.6-35B-A3B Q4_K_M, on 64 GB of unified memory. Every number is a receipt, and each one answers "is it llama.cpp, the server, or continuum?" + +**Decode across layers** (short prompts, 256-token decodes; t/s per stream / aggregate): + +| Streams | llama-batched-bench (no server) | Our server, no draft | Our server, MTP draft n_max 4 | +|---|---|---|---| +| 1 | 59 / 59 | 57 / 57 | 80 / 80 | +| 2 | 45 / 90 | 44 / 89 | 42 / 84 | +| 4 | 31 / 124 | 31 / 122 | 23 / 91 | + +- Nothing serializes: the server batches like stock llama.cpp. +- Batching amortizes weight reads, so the aggregate climbs. On this MoE model it reaches only about 2.1× at four streams, because each sequence routes to its own experts. +- The MTP draft spends the same spare capacity that batching does. It wins alone and loses under concurrency. +- Fix: `inference::speculation` drafts only while a turn decodes alone, set per request. + +**Live decode by concurrent engine work** (16k `tg_3s` samples, 2026-10-27): + +| What else is running | Median t/s | +|---|---| +| Nothing | 20.6 | +| 1 other decoding | 11.2 | +| 2 others decoding | 8.7 | +| 3 others decoding | 8.3 | +| Another slot prefilling | 14.7 | +| Any page save or restore | 4.6–5.6 | + +A page save or restore stalls every stream, because SLOT_SAVE and SLOT_RESTORE run on the server's main loop. + +**Page IO, isolated against live:** + +| | Bytes | Save | Restore | +|---|---|---|---| +| Isolated (99k tokens, SSD) | 0.7 GB | 0.22 s (3.3 GB/s) | 0.1 s | +| Live (92 saves, 95 restores) | 1.88 GB, of which 1.24 GB is checkpoint sidecar | 3.05 s median (0.59 GB/s) | 1.38 s (1.32 GB/s) | + +- The engine's IO code is fast. +- Live pages carry about 2.5× the bytes, mostly checkpoints of the hybrid model's recurrent state. +- Live pages also move 5–6× slower. The suspect is memory pressure: 8.4 GB of swap in use, with the engine's 17 GB `--cache-ram` and `--ctx-checkpoints 32` beside the 22 GB model and 4 × 159k KV. This is being sampled. +- The size quote is cheap and is ruled out. + +**What follows:** +1. Size the prompt cache and checkpoint retention from one measured memory budget, so the engine never pushes the machine into swap. +2. Pages carry only the checkpoints a resume needs. +3. Page IO goes RAM-first and off the main loop (S1), so a switch never stalls the other minds. +4. Expert paging for capacity on unified memory (card 5eedda3e). +5. A long-context sweep: per-sequence KV reads are what batching cannot amortize. + ## 2. Reuse versus write | Option | Speed | Effort | Risk | From 6c39d22bb5c7c762c2356a8bb6a9d54f7ead992d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 04:15:14 -0500 Subject: [PATCH 15/27] The gateway's wire reads the clock through EpochMs and missing fields through serde's index, and the selector test knows the gateway's crates Source hygiene: the two private now_s() clocks become EpochMs::now().secs() (the same pre-1970 policy); get(k).unwrap_or(&Value::Null) becomes &v[k], which is Null for a missing key by definition; wire/tests.rs is marked #![cfg(test)] and owns its Frame::json helper, so test expects stop counting as production (unwraps 1936 -> 1942 becomes a net fall). Selector: an engine change now also runs continuum-gateway and continuum-capture, which build on the engine. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/src/wire/chat.rs | 12 ++++-------- core/continuum-gateway/src/wire/mod.rs | 5 ----- core/continuum-gateway/src/wire/responses.rs | 12 ++++-------- core/continuum-gateway/src/wire/tests.rs | 7 +++++++ tools/scripts/tests/ci-change-scope.test.cjs | 2 +- 5 files changed, 16 insertions(+), 22 deletions(-) diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs index 410f5d9412..66cb3fbc86 100644 --- a/core/continuum-gateway/src/wire/chat.rs +++ b/core/continuum-gateway/src/wire/chat.rs @@ -48,7 +48,7 @@ impl Wire for Chat { message["tool_calls"] = json!(calls); } json!({ - "id": id, "object": "chat.completion", "created": now_s(), "model": response.model, + "id": id, "object": "chat.completion", "created": continuum_base::time::EpochMs::now().secs(), "model": response.model, "choices": [{"index": 0, "message": message, "finish_reason": finish_reason(response)}], "usage": usage(response), }) @@ -64,7 +64,7 @@ impl Wire for Chat { } fn streamer(model: &str, id: &str) -> Self { - Self { model: model.to_owned(), id: id.to_owned(), created: now_s() } + Self { model: model.to_owned(), id: id.to_owned(), created: continuum_base::time::EpochMs::now().secs() } } fn opened(&mut self) -> Vec { @@ -112,10 +112,6 @@ impl Chat { } } -fn now_s() -> u64 { - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) // map_or: a clock before 1970 reads 0 -} - fn finish_reason(response: &TextGenerationResponse) -> &'static str { if stopped_for_tools(response) { "tool_calls" @@ -144,7 +140,7 @@ fn conversation(messages: &[Value]) -> Result, BadRequest> { let mut out = Vec::new(); for m in messages { let role = m.get("role").and_then(Value::as_str).ok_or_else(|| BadRequest("a message has no `role`".into()))?; - let content = m.get("content").unwrap_or(&Value::Null); + let content = &m["content"]; match role { "assistant" => { let mut parts = Vec::new(); @@ -207,7 +203,7 @@ fn tool(value: &Value) -> Option { Some(NativeToolSpec { name: function.get("name").and_then(Value::as_str)?.to_owned(), description: function.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description - input_schema: input_schema(function.get("parameters").unwrap_or(&json!({}))), + input_schema: input_schema(&function["parameters"]), }) } diff --git a/core/continuum-gateway/src/wire/mod.rs b/core/continuum-gateway/src/wire/mod.rs index eb53881887..84ac32c196 100644 --- a/core/continuum-gateway/src/wire/mod.rs +++ b/core/continuum-gateway/src/wire/mod.rs @@ -70,11 +70,6 @@ impl Frame { None => event, } } - - #[cfg(test)] - pub(crate) fn json(&self) -> Value { - serde_json::from_str(&self.data).expect("test: a JSON frame") - } } /// A JSON frame, optionally named. diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs index 9a596e61ed..c7f510b4f4 100644 --- a/core/continuum-gateway/src/wire/responses.rs +++ b/core/continuum-gateway/src/wire/responses.rs @@ -49,7 +49,7 @@ impl Wire for Responses { } fn answer(response: &TextGenerationResponse, id: &str) -> Value { - envelope(id, &response.model, now_s(), "completed", output(response, id), Some(response)) + envelope(id, &response.model, continuum_base::time::EpochMs::now().secs(), "completed", output(response, id), Some(response)) } fn error(kind: ErrorKind, message: &str) -> Value { @@ -62,7 +62,7 @@ impl Wire for Responses { } fn streamer(model: &str, id: &str) -> Self { - Self { model: model.to_owned(), id: id.to_owned(), created: now_s(), sequence: 0, text: None } + Self { model: model.to_owned(), id: id.to_owned(), created: continuum_base::time::EpochMs::now().secs(), sequence: 0, text: None } } fn opened(&mut self) -> Vec { @@ -141,10 +141,6 @@ fn message_id(response_id: &str) -> String { format!("msg_{}", response_id.trim_start_matches("resp_")) } -fn now_s() -> u64 { - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) // map_or: a clock before 1970 reads 0 -} - fn envelope(id: &str, model: &str, created: u64, status: &str, output: Vec, response: Option<&TextGenerationResponse>) -> Value { json!({ "id": id, "object": "response", "created_at": created, "status": status, "model": model, @@ -181,7 +177,7 @@ fn items_to_messages(items: &[Value]) -> Result, BadRequest> { match kind { "message" => { let role = item.get("role").and_then(Value::as_str).ok_or_else(|| BadRequest("a message item has no `role`".into()))?; - out.push(ChatMessage { role: role.to_owned(), content: content(item.get("content").unwrap_or(&Value::Null)), name: None }); + out.push(ChatMessage { role: role.to_owned(), content: content(&item["content"]), name: None }); } "function_call" => { let arguments = item.get("arguments").and_then(Value::as_str).unwrap_or("{}"); // unwrap_or: a call with no arguments @@ -234,6 +230,6 @@ fn tool(value: &Value) -> Option { Some(NativeToolSpec { name: value.get("name").and_then(Value::as_str)?.to_owned(), description: value.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description - input_schema: input_schema(value.get("parameters").unwrap_or(&json!({}))), + input_schema: input_schema(&value["parameters"]), }) } diff --git a/core/continuum-gateway/src/wire/tests.rs b/core/continuum-gateway/src/wire/tests.rs index 6b0f56e3b3..0466ee5674 100644 --- a/core/continuum-gateway/src/wire/tests.rs +++ b/core/continuum-gateway/src/wire/tests.rs @@ -1,4 +1,5 @@ //! Each format round-trips an agent's tool-using turn, whole and streamed. +#![cfg(test)] use super::anthropic::Anthropic; use super::chat::Chat; use super::responses::Responses; @@ -6,6 +7,12 @@ use super::*; use continuum_engine::ai::{MessageContent, ToolCall, ToolChoice, UsageMetrics}; use serde_json::json; +impl Frame { + fn json(&self) -> Value { + serde_json::from_str(&self.data).expect("test: a JSON frame") + } +} + /// An answer that says a word and calls one tool. fn tool_answer() -> TextGenerationResponse { TextGenerationResponse { diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index eb95a0b3b4..12c9b61342 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -145,7 +145,7 @@ test('a crate-local change runs that crate and every crate that depends on it', assert.deepEqual(scope(['core/continuum-memory/src/lib.rs']), crates('continuum-memory', 'continuum-embedding', 'continuum-store', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); assert.deepEqual(scope(['core/continuum-experience/src/lib.rs']), crates('continuum-experience', 'continuum-rooms', 'continuum-vitals', 'continuum-capture', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); assert.deepEqual(scope(['core/continuum-cognition/src/lib.rs']), crates('continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); - const belowMind = crates('continuum-engine', 'continuum-vitals', 'continuum-prompt', 'continuum-engram', 'continuum-capture', 'continuum-embedding', 'continuum-store', 'continuum-models', 'continuum-hands', 'continuum-live', 'continuum-perception', 'continuum-genome', 'continuum-memory', 'continuum-cognition', 'continuum-academy', 'continuum-sentinel', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core'); + const belowMind = crates('continuum-engine', 'continuum-vitals', 'continuum-prompt', 'continuum-engram', 'continuum-capture', 'continuum-embedding', 'continuum-store', 'continuum-models', 'continuum-hands', 'continuum-live', 'continuum-perception', 'continuum-genome', 'continuum-memory', 'continuum-cognition', 'continuum-academy', 'continuum-sentinel', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core', 'continuum-gateway'); assert.deepEqual(scope(['core/continuum-engine/src/lib.rs']), belowMind); // The floor crates (base, host, git) sit below the kernel: a kernel change runs everything above them. const aboveFloor = TESTED_CRATES.filter(n => !BELOW_KERNEL.includes(n)); From 12e50719f1ebe9b85dd446f63293bc62d6a80163 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 07:11:36 -0500 Subject: [PATCH 16/27] The gateway's session memory is opt-in until MindMemory seats driver minds: on by default it queued drivers behind resident pins (61 s vs 18 s a step) Cormac's change request on #5541 at 6f102b6d0, on Fable's own measurement (card e3ce65f9). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/src/server.rs | 6 ++++-- docs/architecture/DRIVER-GATEWAY.md | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs index a90fa5183c..e0131318e9 100644 --- a/core/continuum-gateway/src/server.rs +++ b/core/continuum-gateway/src/server.rs @@ -42,8 +42,10 @@ async fn serve(headers: axum::http::HeaderMap, Json(body): Json) let id = format!("{}_{}", prefix::(), uuid::Uuid::new_v4().simple()); let session = crate::session::session_of(&call.request); // The session is a mind: its id keys a warm page the engine pins, saves and restores. - // `x-continuum-session: off` asks for no session memory (a one-shot call). - let remembered = headers.get("x-continuum-session").and_then(|v| v.to_str().ok()) != Some("off"); + // Opt-in (`x-continuum-session: on`) until a driver mind is seated by MindMemory instead of + // queueing behind resident pins: on by default it measured a 61 s steady-state step against + // 18 s without (card e3ce65f9, M5 2026-10-27). + let remembered = headers.get("x-continuum-session").and_then(|v| v.to_str().ok()) == Some("on"); if remembered { call.request.persona_id = Some(session.to_string()); } diff --git a/docs/architecture/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md index 24beb77da1..2ffa4ad7f8 100644 --- a/docs/architecture/DRIVER-GATEWAY.md +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -44,6 +44,7 @@ The port is stable and configured, never dynamic, because an agent needs a URL i Tools pass straight through. The agent executes its own tools; the gateway never does. Tool-call parsing and rendering stays the engine's one template owner (SERVING-ENGINE §1 `template`). **A session is a mind.** Each agent session maps to a driver mind, `PageKey::driver(user, session)`. +- Session memory is opt-in (`x-continuum-session: on`) until G2 seats driver minds through `MindMemory::seat`: switched on by default, a driver session queued behind resident pins, a 61 s steady-state step against 18 s without (card e3ce65f9). - The session id comes from the protocol when it carries one: `previous_response_id`, an `x-session-id` header, or OpenAI's `user` field. - Otherwise it is the hash of the conversation's stable head: the system prompt plus the first user message. From 08c68fffe0767aa38a82cdf4b2d09daae5519ae2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 08:18:31 -0500 Subject: [PATCH 17/27] =?UTF-8?q?SERVING-ENGINE=20=C2=A71c:=20the=20engine?= =?UTF-8?q?=20is=20fed=20by=20queues=20and=20signals,=20never=20held=20by?= =?UTF-8?q?=20permits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/SERVING-ENGINE.md | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/architecture/SERVING-ENGINE.md b/docs/architecture/SERVING-ENGINE.md index 1d250ead7e..86ce036614 100644 --- a/docs/architecture/SERVING-ENGINE.md +++ b/docs/architecture/SERVING-ENGINE.md @@ -230,6 +230,39 @@ A page save or restore stalls every stream, because SLOT_SAVE and SLOT_RESTORE r 4. Expert paging for capacity on unified memory (card 5eedda3e). 5. A long-context sweep: per-sequence KV reads are what batching cannot amortize. +## 1c. The engine is fed by queues and signals, never held by permits (2026-10-28) + +Joel, 2026-10-28: "Its got to flow or have MANY queues"; "Semaphore really only exists for queue +inserts and signals typically. Otherwise you lock up every thread." The CBAR shape applied to +serving: stages run concurrently, work is submitted, the engine drains what is ready. + +**What it replaces, measured on the M5 (176 acts, build 7ace74020).** A resident's model call +passed four permit layers that each counted the same engine slots and were held for the whole +call: cognition's serving lane (one of four reserved for directed calls, lent only to calls under +60 s, which a 71 s median act never is), a prefill throttle (1 to 2 permits for 72% of the time, +guarding a compute-buffer spike one engine never draws), the adapter's concurrency permit, and the +slot pool. Waiting on the first two: a median 25.7 s plus 24.6 s, in a 155 s median act, while the +engine itself was occupied 99.6% of the time and four streams decode 3.4x one stream at 64k. The +locks, not the engine, made minds wait. Each was added after an incident instead of fixing it. + +**The rule.** +- A mind *submits* a generation (request plus a reply handle) and keeps flowing: tools, + perception and the prefill of her appended items run while she waits. +- **One dispatcher per engine**, woken by events only: a submission arrived, a slot finished, a + page landed. It fills free slots from per-class queues (directed, work, background), oldest first + within a class with aging, so nothing starves. Priority is queue order, never a reserved slot. +- **Admission is memory, once.** `MindMemory::seat` admits a mind by KV bytes. No per-call permit + counts slots a second time. +- A semaphore only signals: an item entered a queue, or a slot freed. No permit is held across a + model call, a tool, or an await on another subsystem. +- The engine's own continuous batching is the concurrency: every seated sequence with tokens to + process rides the same forward pass. + +**Done so far** (`fable/lanes-flow`): the reserved lane is lent whenever nothing directed is +pending; the prefill throttle is deleted; deliberation and dreams take no lane. Left: the adapter's +concurrency permit and the slot pool become the dispatcher above, the ambient anti-stampede permit +becomes a class in it, and the act clock's queue-time registration goes with the lane. + ## 2. Reuse versus write | Option | Speed | Effort | Risk | From 51e988b07088759704daee14f373bb9b78e53d54 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 08:46:46 -0500 Subject: [PATCH 18/27] =?UTF-8?q?SERVING-ENGINE=20=C2=A71c:=20GCD-style=20?= =?UTF-8?q?classes,=20every=20task=20completes,=20background=20is=20thrott?= =?UTF-8?q?led=20never=20starved?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/SERVING-ENGINE.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/docs/architecture/SERVING-ENGINE.md b/docs/architecture/SERVING-ENGINE.md index 86ce036614..c4ab71cd9b 100644 --- a/docs/architecture/SERVING-ENGINE.md +++ b/docs/architecture/SERVING-ENGINE.md @@ -258,6 +258,27 @@ locks, not the engine, made minds wait. Each was added after an incident instead - The engine's own continuous batching is the concurrency: every seated sequence with tokens to process rides the same forward pass. +**Classes, the GCD way** (Joel, 2026-10-28: "no one is ever not getting their task done so a dream +still happens just irregularly and doesn't eat into work"). Each mind is a serial queue (one act at +a time) that targets a quality-of-service class; the engine is the concurrent pool beneath them. + +| class | work | rule | +|---|---|---| +| interactive | a directed reply | the next free slot; preempts a lower class at a decode-step boundary | +| work | a resident's act on her card, with her tools | runs whenever ready; never waits behind the classes below | +| utility | ambient thought, perception, gene exams | fills what the two above leave | +| background | dreams, training, consolidation | runs in the gaps; yields at the next step to anything above | + +Background is throttled, never starved: a waiting task's effective priority ages upward, so a dream +gets its step even on a busy node, irregularly and in small pieces, and it only ever takes a slot +no higher class wants now (preempted by `page_out`, ~0.1 s, the moment one does). Training is the +same: the engine's idle task, never a hold on serving. + +**One owner, one heap.** The dispatcher task owns its ready heap and receives events over a channel +(submitted, slot freed, page landed, priority aged); it pops only when a slot is free. The kernel's +`concurrency::ConcurrentPriorityQueue` forwards each item to an unbounded output channel as soon as +it is signalled, so it does not keep priority order under load; the dispatcher does not build on it. + **Done so far** (`fable/lanes-flow`): the reserved lane is lent whenever nothing directed is pending; the prefill throttle is deleted; deliberation and dreams take no lane. Left: the adapter's concurrency permit and the slot pool become the dispatcher above, the ambient anti-stampede permit From bc60dcc2d1e52eeeac36e319cd950e186e6ea5c2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 11:33:41 -0500 Subject: [PATCH 19/27] The gateway records into canary's one capture crate (continuum_capture::prompt_capture) #5541 had cut its own continuum-capture on 10-28; #5588 cut the same modules into canary's. This branch replays #5541 onto canary without its duplicate cut (fbbb222c1); the gateway's one import moves to canary's path, and its manifest names the crate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/Cargo.toml | 1 + core/continuum-gateway/src/session.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/core/continuum-gateway/Cargo.toml b/core/continuum-gateway/Cargo.toml index f34580a45f..65a9ce35b1 100644 --- a/core/continuum-gateway/Cargo.toml +++ b/core/continuum-gateway/Cargo.toml @@ -7,6 +7,7 @@ description = "The driver gateway (docs/architecture/DRIVER-GATEWAY.md): one doo [dependencies] continuum-engine = { path = "../continuum-engine" } continuum-base = { path = "../continuum-base" } +continuum-capture = { path = "../continuum-capture" } # the one capture of every mind's calls async-trait = "0.1" axum = "0.8" serde.workspace = true diff --git a/core/continuum-gateway/src/session.rs b/core/continuum-gateway/src/session.rs index c212996843..0c5b627387 100644 --- a/core/continuum-gateway/src/session.rs +++ b/core/continuum-gateway/src/session.rs @@ -8,7 +8,7 @@ use std::sync::Arc; -use continuum_capture::{CaptureLease, JsonlPromptCaptureSink, PromptCall, PromptCaptureSink}; +use continuum_capture::prompt_capture::{CaptureLease, JsonlPromptCaptureSink, PromptCall, PromptCaptureSink}; use continuum_engine::ai::TextGenerationRequest; use uuid::Uuid; From cfbb288c7a3fc10dcf986a97be200a2fd38b29a8 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 16:37:11 -0500 Subject: [PATCH 20/27] The gateway's streamed answer owns its generation: an agent that leaves cancels it, a slow one holds it, an unopened capture refuses the call (Codex on #5541 at 34672ec73) - answer.rs: the SSE body polls the generation itself, with no spawned task and no gateway queue. The agent leaving drops the body, which drops the generation future: the engine's one cancellation path (the adapter future's TurnAdmission releases its slot pin and permit on Drop; llama-server answers the closed connection with `srv stop: cancel task`), and the capture lease inside it records the call cancelled at that moment, never while the engine still runs. - Backpressure: the generation is polled only once the agent has taken every encoded frame, so what waits is one poll's chunks (one read of the engine's SSE connection, one token per event) plus one chunk's frames. The engine's sink stays its contract's unbounded sender, drained before every poll; the unbounded event channel is gone. - session::record refuses the call (503, `capture_unavailable` in each format's error shape) when its capture cannot be opened, instead of serving it unrecorded. Tests (gateway): disconnect before the first chunk and midstream each free the generation's slot permit; a stalled agent holds generation within one chunk; a finished answer sends its last chunks before its close; an unopened capture refuses the call. Not compiled here (serving node): to be run in the test window. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/src/answer.rs | 274 +++++++++++++++++++ core/continuum-gateway/src/lib.rs | 1 + core/continuum-gateway/src/server.rs | 63 ++--- core/continuum-gateway/src/session.rs | 59 +++- core/continuum-gateway/src/wire/anthropic.rs | 2 +- core/continuum-gateway/src/wire/chat.rs | 1 + core/continuum-gateway/src/wire/mod.rs | 7 +- core/continuum-gateway/src/wire/responses.rs | 1 + 8 files changed, 357 insertions(+), 51 deletions(-) create mode 100644 core/continuum-gateway/src/answer.rs diff --git a/core/continuum-gateway/src/answer.rs b/core/continuum-gateway/src/answer.rs new file mode 100644 index 0000000000..9cf7daf0fa --- /dev/null +++ b/core/continuum-gateway/src/answer.rs @@ -0,0 +1,274 @@ +//! A streamed answer: the SSE body OWNS the generation, so the agent's connection is the +//! generation's lifetime. +//! +//! Codex on #5541 (34672ec73): a generation spawned beside the body outlived a departed agent +//! (the engine request and its lane kept running) while its capture said cancelled, and two +//! unbounded queues let a slow agent accumulate a whole answer in memory. Here there is no +//! task and no gateway queue. The body polls the generation itself, and only when the agent +//! has taken every frame already encoded: +//! +//! - **The agent leaves:** hyper drops the body, which drops the generation future. That is +//! the engine's one cancellation path, the same one a resident's abandoned turn takes +//! (`continuum-cognition` `generation_drop.rs`): the adapter's future owns its +//! `TurnAdmission` (`continuum-engine` `ai/openai_adapter/stream.rs`, `_admission`), whose +//! `Drop` releases the slot pin and permit (`inference/turn_admission.rs`, `impl Drop`), and +//! its HTTP response, whose close llama-server answers with `srv stop: cancel task`. The +//! capture lease rides inside the generation future, so its `Drop` records the call as +//! cancelled at the same moment, never while the engine still runs. +//! - **The agent is slow:** the generation is not polled until the frames of the last chunk +//! are taken, so the engine reads no further from its stream. What waits is bounded by the +//! engine's own stream batching unit: the chunks ONE poll of the generation produced (one +//! read of the engine's SSE connection; llama-server sends one token per event), plus the +//! frames one chunk encodes to. Behind that, the agent's socket and hyper's write buffer +//! push back on the body, and the engine's connection's receive window on llama-server. + +use std::collections::VecDeque; +use std::future::Future; +use std::pin::Pin; +use std::task::{Context, Poll}; + +use continuum_engine::ai::adapter::GenerationChunk; +use continuum_engine::ai::TextGenerationResponse; +use tokio::sync::mpsc::error::TryRecvError; +use tokio::sync::mpsc::UnboundedReceiver; + +use crate::route::RouteError; +use crate::wire::{Frame, Wire}; + +type Generation = Pin> + Send>>; + +/// One streamed answer's frames, in order: what the format opens with, each chunk as the +/// engine decodes it, then what closes it. Ends after the closing frames. +pub(crate) struct Answer { + encoder: W, + /// `None` once it has returned (its closing frames are queued). + generation: Option, + /// The engine's sink for this generation (its streaming contract is an unbounded sender); + /// emptied before the generation is polled again, so it holds one poll's chunks at most. + received: UnboundedReceiver, + /// The frames of one chunk (or the opening or closing), until the agent takes them. + encoded: VecDeque, +} + +impl Answer { + /// `generation` sends its chunks to the sender `received` drains, and owns everything that + /// must end with it (the engine request and its admission, the capture lease). + pub(crate) fn new( + mut encoder: W, + generation: impl Future> + Send + 'static, + received: UnboundedReceiver, + ) -> Self { + let encoded = encoder.opened().into(); + Self { + encoder, + generation: Some(Box::pin(generation)), + received, + encoded, + } + } + + /// The frames that close an answer the generation returned. + fn closing(&mut self, outcome: Result) -> Vec { + match outcome { + Ok(response) => self.encoder.finished(&response), + Err(RouteError::Engine(why)) => self.encoder.failed(&why), + Err(RouteError::UnknownModel { model, .. }) => self + .encoder + .failed(&format!("model `{model}` is not served here")), + } + } +} + +impl tokio_stream::Stream for Answer { + type Item = Frame; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + if let Some(frame) = this.encoded.pop_front() { + return Poll::Ready(Some(frame)); + } + match this.received.try_recv() { + Ok(chunk) => { + this.encoded.extend(this.encoder.chunk(&chunk)); + continue; + } + // Empty: nothing decoded is waiting. Disconnected: the generation returned and + // dropped its sender; every chunk it sent was taken above. + Err(TryRecvError::Empty | TryRecvError::Disconnected) => {} + } + let Some(generation) = this.generation.as_mut() else { + return Poll::Ready(None); + }; + match generation.as_mut().poll(cx) { + // It may have sent chunks before pending: the loop encodes them first. + Poll::Pending if this.received.is_empty() => return Poll::Pending, + Poll::Pending => {} + Poll::Ready(outcome) => { + this.generation = None; + // Its last chunks precede its closing frames. + while let Ok(chunk) = this.received.try_recv() { + this.encoded.extend(this.encoder.chunk(&chunk)); + } + let closing = this.closing(outcome); + this.encoded.extend(closing); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wire::chat::Chat; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + use tokio::sync::mpsc::UnboundedSender; + use tokio::sync::{OwnedSemaphorePermit, Semaphore}; + use tokio_stream::Stream; + + /// Poll the body once, as hyper does when it can write. + fn poll(answer: &mut Answer) -> Poll> { + let mut cx = Context::from_waker(std::task::Waker::noop()); + Pin::new(answer).poll_next(&mut cx) + } + + /// Pending exactly once, then ready: an engine step between two chunks. + async fn step() { + let mut stepped = false; + std::future::poll_fn(|cx| { + if stepped { + return Poll::Ready(()); + } + stepped = true; + cx.waker().wake_by_ref(); + Poll::Pending + }) + .await + } + + /// A generation shaped as the engine's: it holds a slot permit for its whole life (the + /// adapter's `TurnAdmission`), sends `chunks` tokens counting each, then waits forever (a + /// long decode). Returns the answer, the permit's pool and the sent count. + fn generation(chunks: usize) -> (Answer, Arc, Arc) { + let slots = Arc::new(Semaphore::new(1)); + let permit: OwnedSemaphorePermit = slots + .clone() + .try_acquire_owned() + .expect("test: one free slot"); + let sent = Arc::new(AtomicUsize::new(0)); + let (sink, received): (UnboundedSender, _) = + tokio::sync::mpsc::unbounded_channel(); + let counted = sent.clone(); + let generation = async move { + let _admission = permit; + for i in 0..chunks { + if sink.send(GenerationChunk::Token(format!("t{i}"))).is_err() { + return Err(RouteError::Engine("test: sink closed".into())); + } + counted.fetch_add(1, Ordering::SeqCst); + step().await; + } + std::future::pending::<()>().await; + Err(RouteError::Engine("test: unreachable".into())) + }; + ( + Answer::new(Chat::streamer("qwen", "chatcmpl_1"), generation, received), + slots, + sent, + ) + } + + // what this catches: an agent that leaves during prefill (before any token) leaving its + // generation running and its slot held, as the spawned generation of 34672ec73 did. + #[tokio::test] + async fn an_agent_gone_before_the_first_chunk_cancels_the_generation_and_frees_its_slot() { + let (mut answer, slots, sent) = generation(0); + assert!( + matches!(poll(&mut answer), Poll::Ready(Some(_))), + "the opening frame" + ); + assert!( + poll(&mut answer).is_pending(), + "prefilling: nothing to send yet" + ); + assert_eq!( + slots.available_permits(), + 0, + "the generation holds its slot while it runs" + ); + drop(answer); + assert_eq!( + slots.available_permits(), + 1, + "the agent left: the generation was dropped with its slot" + ); + assert_eq!(sent.load(Ordering::SeqCst), 0); + } + + // what this catches: an agent that leaves midstream leaving the decode running to its end. + #[tokio::test] + async fn an_agent_gone_midstream_cancels_the_generation_and_frees_its_slot() { + let (mut answer, slots, sent) = generation(3); + let mut frames = 0; + while let Poll::Ready(Some(_)) = poll(&mut answer) { + frames += 1; + } + assert_eq!(frames, 4, "the opening frame and three tokens"); + assert_eq!(slots.available_permits(), 0, "still decoding"); + drop(answer); + assert_eq!( + slots.available_permits(), + 1, + "the agent left: the slot is free" + ); + assert_eq!(sent.load(Ordering::SeqCst), 3); + } + + // what this catches: a slow agent letting generation run ahead and pile its answer up in + // memory (the unbounded chunk and event queues of 34672ec73). + #[tokio::test] + async fn a_stalled_agent_stops_generation_at_one_chunk_ahead() { + let (mut answer, _slots, sent) = generation(10_000); + for _ in 0..3 { + assert!(matches!(poll(&mut answer), Poll::Ready(Some(_)))); + } + let taken = 2; // the opening frame, then two tokens + // The agent stops reading. Nothing else may drive the generation. + for _ in 0..1_000 { + tokio::task::yield_now().await; + } + let ahead = sent.load(Ordering::SeqCst) - taken; + assert!( + ahead <= 1, + "generation ran {ahead} chunks ahead of a stalled agent" + ); + } + + // what this catches: a finished generation's last chunks arriving after its closing frames, + // or the stream never ending. + #[tokio::test] + async fn a_finished_answer_sends_its_last_chunks_then_closes_and_ends() { + let (sink, received) = tokio::sync::mpsc::unbounded_channel(); + let generation = async move { + sink.send(GenerationChunk::Token("done".into())) + .map_err(|_| RouteError::Engine("test: closed".into()))?; + Err(RouteError::Engine("lane died".into())) + }; + let mut answer = Answer::new(Chat::streamer("qwen", "chatcmpl_1"), generation, received); + let mut frames = Vec::new(); + while let Poll::Ready(Some(frame)) = poll(&mut answer) { + frames.push(frame.data); + } + assert!(poll(&mut answer).is_ready(), "ended, not pending"); + assert!( + frames[1].contains("done"), + "the token before the close: {frames:?}" + ); + assert!( + frames[2..].iter().any(|f| f.contains("lane died")), + "the failure closes it: {frames:?}" + ); + } +} diff --git a/core/continuum-gateway/src/lib.rs b/core/continuum-gateway/src/lib.rs index 8619d98f7b..5da18adc1f 100644 --- a/core/continuum-gateway/src/lib.rs +++ b/core/continuum-gateway/src/lib.rs @@ -9,6 +9,7 @@ //! Slices G0-G1. A session becomes a driver mind seated by `MindMemory` in G2; until then a //! call is admitted as anonymous traffic. +mod answer; mod module; mod route; mod server; diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs index e0131318e9..ae7bdffbd9 100644 --- a/core/continuum-gateway/src/server.rs +++ b/core/continuum-gateway/src/server.rs @@ -52,53 +52,36 @@ async fn serve(headers: axum::http::HeaderMap, Json(body): Json) continuum_base::probe!(class = "gateway.call", wire = W::NAME, model = %model, stream = call.stream, session = %session, remembered = remembered, tools = call.request.tools.as_ref().map_or(0, Vec::len) as u64, messages = call.request.messages.len() as u64, "an agent's call reached the engine through the gateway"); - let mut lease = crate::session::record(session, &id, W::NAME, &call.request); + // Recorded or refused: an agent's call is never served outside the one capture. + let opened = continuum_capture::prompt_capture::JsonlPromptCaptureSink::open_for_persona(session); + let mut lease = match crate::session::record(opened, session, &id, W::NAME, &call.request) { + Ok(lease) => lease, + Err(unavailable) => return capture_refused::(&unavailable), + }; if !call.stream { let outcome = route::generate(&adapter, call.request).await; - if let Some(lease) = lease.as_mut() { - match &outcome { - Ok(response) => lease.finish(Some(response), None), - Err(error) => lease.finish(None, Some(&format!("{error:?}"))), - }; - } + crate::session::settle(&mut lease, &outcome); return match outcome { Ok(response) => Json(W::answer(&response, &id)).into_response(), Err(error) => refused::(error), }; } - let (chunks, mut received) = tokio::sync::mpsc::unbounded_channel(); - let (events, out) = tokio::sync::mpsc::unbounded_channel(); - tokio::spawn(async move { - let mut encoder = W::streamer(&model, &id); - let generation = tokio::spawn(async move { route::stream(&adapter, call.request, chunks).await }); - let send = |batch: Vec| batch.into_iter().all(|f| events.send(Ok::<_, std::convert::Infallible>(f.into_event())).is_ok()); - if !send(encoder.opened()) { - return; // the agent left; the lease records the call as cancelled when dropped - } - while let Some(chunk) = received.recv().await { - if !send(encoder.chunk(&chunk)) { - return; - } - } - let closing = match generation.await { - Ok(Ok(response)) => { - if let Some(lease) = lease.as_mut() { - lease.finish(Some(&response), None); - } - encoder.finished(&response) - } - Ok(Err(RouteError::Engine(why))) => { - if let Some(lease) = lease.as_mut() { - lease.finish(None, Some(&why)); - } - encoder.failed(&why) - } - Ok(Err(RouteError::UnknownModel { model, .. })) => encoder.failed(&format!("model `{model}` is not served here")), - Err(join) => encoder.failed(&format!("generation task ended: {join}")), - }; - send(closing); - }); - Sse::new(tokio_stream::wrappers::UnboundedReceiverStream::new(out)).keep_alive(KeepAlive::default()).into_response() + // The body owns the generation and its lease: the agent leaving drops both (`answer`). + let (chunks, received) = tokio::sync::mpsc::unbounded_channel(); + let generation = async move { + let outcome = route::stream(&adapter, call.request, chunks).await; + crate::session::settle(&mut lease, &outcome); + outcome + }; + let answer = crate::answer::Answer::new(W::streamer(&model, &id), generation, received); + let events = tokio_stream::StreamExt::map(answer, |frame| Ok::<_, std::convert::Infallible>(frame.into_event())); + Sse::new(events).keep_alive(KeepAlive::default()).into_response() +} + +/// The capture could not be opened: the call is refused, since serving it would leave a +/// generation the act inspector, replay and Dreaming can never read. +pub(crate) fn capture_refused(unavailable: &crate::session::CaptureUnavailable) -> Response { + refuse::(StatusCode::SERVICE_UNAVAILABLE, ErrorKind::CaptureUnavailable, &unavailable.to_string()) } fn refused(error: RouteError) -> Response { diff --git a/core/continuum-gateway/src/session.rs b/core/continuum-gateway/src/session.rs index 0c5b627387..c9f1ce429c 100644 --- a/core/continuum-gateway/src/session.rs +++ b/core/continuum-gateway/src/session.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use continuum_capture::prompt_capture::{CaptureLease, JsonlPromptCaptureSink, PromptCall, PromptCaptureSink}; -use continuum_engine::ai::TextGenerationRequest; +use continuum_engine::ai::{TextGenerationRequest, TextGenerationResponse}; use uuid::Uuid; /// The namespace driver session ids are derived in. Fixed forever: changing it would split @@ -26,15 +26,35 @@ pub(crate) fn session_of(request: &TextGenerationRequest) -> Uuid { Uuid::new_v5(&DRIVER_SESSIONS, head.as_bytes()) } -/// Start recording one call of `session`. `None` when the capture home cannot be opened, -/// said in a probe: an unrecorded call is still served. -pub(crate) fn record(session: Uuid, request_id: &str, wire: &'static str, request: &TextGenerationRequest) -> Option { - let sink: Arc = match JsonlPromptCaptureSink::open_for_persona(session) { +/// The capture could not be opened, so the call is refused rather than served unrecorded +/// (the capture contract: no call outside the one capture, `continuum-capture`). +#[derive(Debug)] +pub(crate) struct CaptureUnavailable { + session: Uuid, + error: std::io::Error, +} + +impl std::fmt::Display for CaptureUnavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "this node cannot record session {} ({}); the call is refused rather than served unrecorded", self.session, self.error) + } +} + +/// Start recording one call of `session` in the capture `opened` for it. A capture that +/// could not be opened refuses the call, said in a probe and to the agent. +pub(crate) fn record( + opened: std::io::Result, + session: Uuid, + request_id: &str, + wire: &'static str, + request: &TextGenerationRequest, +) -> Result { + let sink: Arc = match opened { Ok(sink) => Arc::new(sink), Err(error) => { continuum_base::probe!(class = "gateway.capture_unavailable", session = %session, error = %error, - "this agent call is served but not recorded"); - return None; + "this agent call is refused: its capture cannot be opened"); + return Err(CaptureUnavailable { session, error }); } }; let call = PromptCall { @@ -47,7 +67,16 @@ pub(crate) fn record(session: Uuid, request_id: &str, wire: &'static str, reques cause_root: None, replay_of: None, }; - Some(CaptureLease::start(sink, &call, request)) + Ok(CaptureLease::start(sink, &call, request)) +} + +/// End a recorded call with the generation's outcome. A call that never reaches this (the +/// agent left, dropping the generation) is recorded as cancelled by the lease's `Drop`. +pub(crate) fn settle(lease: &mut CaptureLease, outcome: &Result) { + match outcome { + Ok(response) => lease.finish(Some(response), None), + Err(error) => lease.finish(None, Some(&format!("{error:?}"))), + }; } #[cfg(test)] @@ -76,4 +105,18 @@ mod tests { assert_eq!(session_of(&first), session_of(&later)); assert_ne!(session_of(&first), session_of(&other)); } + + // what this catches: a call served unrecorded when its capture cannot be opened (the + // probe-only path of 34672ec73), invisible to the act inspector, replay and Dreaming. + #[test] + fn a_capture_that_cannot_open_refuses_the_call() { + let call = request("You are a coder.", &[("user", "fix median")]); + let opened = Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "capture home read-only")); + let Err(unavailable) = record(opened, session_of(&call), "chatcmpl_1", "openai_chat", &call) else { + panic!("test: an unopened capture must refuse the call"); + }; + let refused = crate::server::capture_refused::(&unavailable); + assert_eq!(refused.status(), axum::http::StatusCode::SERVICE_UNAVAILABLE); + assert!(unavailable.to_string().contains("capture home read-only"), "the agent is told why: {unavailable}"); + } } diff --git a/core/continuum-gateway/src/wire/anthropic.rs b/core/continuum-gateway/src/wire/anthropic.rs index 676a7d1fac..84a0f276d8 100644 --- a/core/continuum-gateway/src/wire/anthropic.rs +++ b/core/continuum-gateway/src/wire/anthropic.rs @@ -66,7 +66,7 @@ impl Wire for Anthropic { let kind = match kind { ErrorKind::InvalidRequest => "invalid_request_error", ErrorKind::NotFound => "not_found_error", - ErrorKind::Engine => "api_error", + ErrorKind::Engine | ErrorKind::CaptureUnavailable => "api_error", }; json!({"type": "error", "error": {"type": kind, "message": message}}) } diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs index 66cb3fbc86..22efe2b58c 100644 --- a/core/continuum-gateway/src/wire/chat.rs +++ b/core/continuum-gateway/src/wire/chat.rs @@ -59,6 +59,7 @@ impl Wire for Chat { ErrorKind::InvalidRequest => ("invalid_request_error", "invalid_request"), ErrorKind::NotFound => ("invalid_request_error", "model_not_found"), ErrorKind::Engine => ("server_error", "engine_error"), + ErrorKind::CaptureUnavailable => ("server_error", "capture_unavailable"), }; json!({"error": {"message": message, "type": kind, "code": code}}) } diff --git a/core/continuum-gateway/src/wire/mod.rs b/core/continuum-gateway/src/wire/mod.rs index 84ac32c196..52a00ff95d 100644 --- a/core/continuum-gateway/src/wire/mod.rs +++ b/core/continuum-gateway/src/wire/mod.rs @@ -22,8 +22,9 @@ pub(crate) struct Call { #[derive(Debug)] pub(crate) struct BadRequest(pub String); -/// One API an agent speaks. `Self` is the encoder of one streamed answer. -pub(crate) trait Wire: Send + 'static { +/// One API an agent speaks. `Self` is the encoder of one streamed answer, held in place by +/// the answer's body ([`crate::answer::Answer`]). +pub(crate) trait Wire: Send + Unpin + 'static { /// The format's name, for probes. const NAME: &'static str; fn decode(body: Value) -> Result; @@ -48,6 +49,8 @@ pub(crate) enum ErrorKind { InvalidRequest, NotFound, Engine, + /// The call's capture cannot be opened: refused rather than served unrecorded. + CaptureUnavailable, } /// One server-sent event of a streamed answer: its name, if the format names events, and data. diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs index c7f510b4f4..15acf3f2a9 100644 --- a/core/continuum-gateway/src/wire/responses.rs +++ b/core/continuum-gateway/src/wire/responses.rs @@ -57,6 +57,7 @@ impl Wire for Responses { ErrorKind::InvalidRequest => "invalid_request", ErrorKind::NotFound => "model_not_found", ErrorKind::Engine => "server_error", + ErrorKind::CaptureUnavailable => "capture_unavailable", }; json!({"error": {"message": message, "type": "invalid_request_error", "code": code}}) } From 9ecb7a6b85f4667fa1840670548a1760432c0a5c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 16:37:36 -0500 Subject: [PATCH 21/27] The CI selector fixture: an experience change also selects the gateway (it rides capture, which rides rooms) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/scripts/tests/ci-change-scope.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index 12c9b61342..e6c28d9edf 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -143,7 +143,7 @@ test('a crate-local change runs that crate and every crate that depends on it', assert.deepEqual(scope(['core/continuum-perception/src/lib.rs']), crates('continuum-perception', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); assert.deepEqual(scope(['core/continuum-genome/src/lib.rs']), crates('continuum-genome', 'continuum-store', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); assert.deepEqual(scope(['core/continuum-memory/src/lib.rs']), crates('continuum-memory', 'continuum-embedding', 'continuum-store', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); - assert.deepEqual(scope(['core/continuum-experience/src/lib.rs']), crates('continuum-experience', 'continuum-rooms', 'continuum-vitals', 'continuum-capture', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-experience/src/lib.rs']), crates('continuum-experience', 'continuum-rooms', 'continuum-vitals', 'continuum-capture', 'continuum-cognition', 'continuum-academy', 'continuum-gateway', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); assert.deepEqual(scope(['core/continuum-cognition/src/lib.rs']), crates('continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); const belowMind = crates('continuum-engine', 'continuum-vitals', 'continuum-prompt', 'continuum-engram', 'continuum-capture', 'continuum-embedding', 'continuum-store', 'continuum-models', 'continuum-hands', 'continuum-live', 'continuum-perception', 'continuum-genome', 'continuum-memory', 'continuum-cognition', 'continuum-academy', 'continuum-sentinel', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core', 'continuum-gateway'); assert.deepEqual(scope(['core/continuum-engine/src/lib.rs']), belowMind); From 0a0bee16f3f658f7091bde6e480b3d986a23e23a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 17:34:22 -0500 Subject: [PATCH 22/27] The gateway owns its listener, refuses what it cannot read, and bounds a slow agent at the engine's producer (Codex on 856ee2b69) Listener lifecycle (continuum-gateway listener.rs, module.rs): the module holds the serve task's JoinHandle with a graceful-shutdown signal in its own state. A bind failure fails initialization. Status reads the live task, so it reads false once the listener exits. drain closes admission and waits for the calls in flight; shutdown abandons what is still in flight (each agent is told the node is stopping; the generation is dropped, the engine's cancellation path) and joins the task. A dropped listener aborts its task, and a reinitialize after a stop binds the same port. Checked decoders (wire/decode.rs): every format's tools, token limits, sampling, stream flag and tool_choice go through shared decoders. A malformed or unserved tool entry, a token limit outside 1..=u32::MAX, a non-string stop member, or an out-of-range temperature/top_p refuses the call before selection or generation. The per-format adapters keep only the real differences: tool shapes, field names and the temperature ceiling. Backpressure (continuum-engine ai/stream_sinks.rs deliver): every producer on the local serving path (sse_stream, the trait's default generate_stream) yields after each chunk it sends, so one poll of a generation sends at most one chunk. A ready burst of 64 events in one network read, through the real consume_sse_stream, never leaves more than one chunk waiting. The gateway's Answer tests now drive a ready-burst producer through deliver. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/ai/adapter/inference_device.rs | 4 +- ...reaches_the_consumer_one_chunk_per_poll.rs | 70 ++++ .../src/ai/openai_adapter/tests/mod.rs | 1 + core/continuum-engine/src/ai/stream_sinks.rs | 23 ++ .../src/inference/sse_stream.rs | 21 +- core/continuum-gateway/src/answer.rs | 154 ++++++--- core/continuum-gateway/src/lib.rs | 1 + core/continuum-gateway/src/listener.rs | 141 ++++++++ core/continuum-gateway/src/module.rs | 146 +++++++-- core/continuum-gateway/src/server.rs | 21 +- core/continuum-gateway/src/wire/anthropic.rs | 49 +-- core/continuum-gateway/src/wire/chat.rs | 54 ++-- core/continuum-gateway/src/wire/decode.rs | 305 ++++++++++++++++++ core/continuum-gateway/src/wire/mod.rs | 29 +- core/continuum-gateway/src/wire/responses.rs | 39 ++- core/continuum-gateway/src/wire/tests.rs | 91 +++++- docs/architecture/DRIVER-GATEWAY.md | 2 +- 17 files changed, 987 insertions(+), 164 deletions(-) create mode 100644 core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs create mode 100644 core/continuum-gateway/src/listener.rs create mode 100644 core/continuum-gateway/src/wire/decode.rs diff --git a/core/continuum-engine/src/ai/adapter/inference_device.rs b/core/continuum-engine/src/ai/adapter/inference_device.rs index f40ccd0190..39d9efe8bf 100644 --- a/core/continuum-engine/src/ai/adapter/inference_device.rs +++ b/core/continuum-engine/src/ai/adapter/inference_device.rs @@ -590,11 +590,11 @@ pub trait AIProviderAdapter: Send + Sync { } if let Some(reasoning) = response.reasoning.as_ref() { if !reasoning.is_empty() { - let _ = sink.send(GenerationChunk::Reasoning(reasoning.clone())); + crate::ai::stream_sinks::deliver(&sink, GenerationChunk::Reasoning(reasoning.clone())).await; } } if !response.text.is_empty() { - let _ = sink.send(GenerationChunk::Token(response.text.clone())); + crate::ai::stream_sinks::deliver(&sink, GenerationChunk::Token(response.text.clone())).await; } Ok(response) } diff --git a/core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs b/core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs new file mode 100644 index 0000000000..a59f94a416 --- /dev/null +++ b/core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs @@ -0,0 +1,70 @@ +#![cfg(test)] + +//! The engine's stream producer honours `stream_sinks::deliver` against a real burst: one +//! network read carrying many events reaches the consumer one chunk per poll. + +use super::*; + +// what this catches: the real adapter turning one network read into a burst of chunks in +// a single poll (llama-server sends many events per read, and `consume_sse_stream` parsed +// them all before returning), so a consumer that polls the generation only when it can +// take more (the gateway's streamed answer) still holds a whole read: a one-chunk bound +// claimed from a synthetic producer that yields would not hold. Here 64 tokens arrive READY +// in ONE body chunk, through the real `consume_sse_stream`, with nothing else yielding. +#[tokio::test] +async fn a_ready_burst_reaches_the_consumer_one_chunk_per_poll() { + use std::future::Future; + use std::task::{Context, Poll}; + const TOKENS: usize = 64; + let mut body = String::new(); + for i in 0..TOKENS { + body.push_str(&format!( + "data: {}\n\n", + serde_json::json!({"choices": [{"delta": {"content": format!("t{i}")}}]}) + )); + } + body.push_str( + "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n", + ); + let response = reqwest::Response::from(axum::http::Response::new(body)); + let (sink, mut received) = tokio::sync::mpsc::unbounded_channel(); + let adapter = test_adapter(); + let request = crate::ai::types::TextGenerationRequest::default(); + let mut generation = std::pin::pin!(crate::inference::sse_stream::consume_sse_stream( + &adapter.config, + &request, + false, + response, + &sink + )); + let mut cx = Context::from_waker(std::task::Waker::noop()); + let mut tokens = 0; + let mut polls = 0; + let outcome = loop { + polls += 1; + assert!( + polls <= 10 * TOKENS, + "test: the in-memory stream must finish" + ); + let polled = generation.as_mut().poll(&mut cx); + assert!( + received.len() <= 1, + "one poll left {} chunks waiting", + received.len() + ); + while let Ok(chunk) = received.try_recv() { + if matches!(chunk, GenerationChunk::Token(_)) { + tokens += 1; + } + } + if let Poll::Ready(outcome) = polled { + break outcome; + } + }; + let outcome = outcome.expect("test: the stream completes"); // JUSTIFIED: the invariant under test + assert_eq!(tokens, TOKENS, "every token reached the consumer"); + assert!( + outcome.acc_content.starts_with("t0t1") && outcome.acc_content.ends_with("t63"), + "the answer is whole" + ); +} diff --git a/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs b/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs index b3ae242dbb..a869067f4d 100644 --- a/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs +++ b/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs @@ -14,6 +14,7 @@ use crate::ai::types::{ChatMessage, ImageInput, MessageContent}; use super::embedding::{build_embedding_body, parse_embedding_response, parse_embedding_usage}; +mod a_ready_burst_reaches_the_consumer_one_chunk_per_poll; mod lane_transport; mod lora_page_in; mod prefill_progress_is_liveness; diff --git a/core/continuum-engine/src/ai/stream_sinks.rs b/core/continuum-engine/src/ai/stream_sinks.rs index 747f984256..aea644e93b 100644 --- a/core/continuum-engine/src/ai/stream_sinks.rs +++ b/core/continuum-engine/src/ai/stream_sinks.rs @@ -79,6 +79,29 @@ pub fn take(stream_id: Uuid) -> Option> { sinks().remove(&stream_id).map(|(_, s)| s) } +/// Hand one chunk to a generation's consumer, then give the consumer the turn before the +/// producer parses further. Every producer the local serving path runs sends through this: +/// `inference::sse_stream` (llama-server's stream) and `AIProviderAdapter`'s default +/// `generate_stream` (a one-shot backend's whole answer). +/// +/// The sink is unbounded so decode never blocks on a reader, but an unbounded send never +/// returns `Pending` either: one network read of llama-server's stream carries many events, +/// and a producer that parsed them all in one poll left a whole read's worth of chunks +/// waiting before its consumer ran. Yielding after each send makes every chunk its own poll, +/// so a consumer that polls the generation only when it can take more (the driver gateway's +/// streamed answer) holds at most one chunk; the rest stays unread in the engine's stream, +/// where the socket's receive window pushes back on the server. A resident's generation +/// pays one reschedule per chunk. Pinned against a ready burst through the real producer by +/// `ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs`. +/// +/// A send to a closed sink is not a failure: a caller that wants only the assembled answer +/// drops its receiver, and generation continues for the response it returns. +pub async fn deliver(sink: &UnboundedSender, chunk: GenerationChunk) { + if sink.send(chunk).is_ok() { + tokio::task::yield_now().await; + } +} + /// The stream id a caller stamped on the params, if any. pub fn stream_id_of(params: &serde_json::Value) -> Option { params diff --git a/core/continuum-engine/src/inference/sse_stream.rs b/core/continuum-engine/src/inference/sse_stream.rs index 54b6c50be1..3ba5c42d91 100644 --- a/core/continuum-engine/src/inference/sse_stream.rs +++ b/core/continuum-engine/src/inference/sse_stream.rs @@ -312,7 +312,8 @@ pub(crate) async fn consume_sse_stream( response: reqwest::Response, sink: &tokio::sync::mpsc::UnboundedSender, ) -> Result { - // Consume the SSE stream: every token reaches `sink` the INSTANT it arrives. + // Consume the SSE stream: every token reaches `sink` the INSTANT it arrives, and its + // consumer gets the turn before the next is parsed (`stream_sinks::deliver`). // Liveness is the per-token idle watchdog ([`STREAM_IDLE_TIMEOUT_SECS`]) — // silence means the backend died, NOT that generation is simply long. use futures::StreamExt; @@ -783,11 +784,15 @@ pub(crate) async fn consume_sse_stream( if local_lane { crate::inference::llama_server::note_real_prefill_progress(); } - let _ = sink.send(GenerationChunk::Prefill { - processed: p.processed, - total: p.total, - cached: p.cache, - }); + crate::ai::stream_sinks::deliver( + sink, + GenerationChunk::Prefill { + processed: p.processed, + total: p.total, + cached: p.cache, + }, + ) + .await; } } // Any REAL output (token, reasoning, tool delta, finish) means @@ -805,14 +810,14 @@ pub(crate) async fn consume_sse_stream( if let Some(c) = delta.content { if !c.is_empty() { acc_content.push_str(&c); - let _ = sink.send(GenerationChunk::Token(c)); + crate::ai::stream_sinks::deliver(sink, GenerationChunk::Token(c)).await; last_progress = Instant::now(); } } if let Some(r) = delta.reasoning_content { if !r.is_empty() { acc_reasoning.push_str(&r); - let _ = sink.send(GenerationChunk::Reasoning(r)); + crate::ai::stream_sinks::deliver(sink, GenerationChunk::Reasoning(r)).await; last_progress = Instant::now(); } } diff --git a/core/continuum-gateway/src/answer.rs b/core/continuum-gateway/src/answer.rs index 9cf7daf0fa..5869789ebb 100644 --- a/core/continuum-gateway/src/answer.rs +++ b/core/continuum-gateway/src/answer.rs @@ -4,8 +4,8 @@ //! Codex on #5541 (34672ec73): a generation spawned beside the body outlived a departed agent //! (the engine request and its lane kept running) while its capture said cancelled, and two //! unbounded queues let a slow agent accumulate a whole answer in memory. Here there is no -//! task and no gateway queue. The body polls the generation itself, and only when the agent -//! has taken every frame already encoded: +//! task. The body polls the generation itself, and only when the agent has taken every frame +//! already encoded: //! //! - **The agent leaves:** hyper drops the body, which drops the generation future. That is //! the engine's one cancellation path, the same one a resident's abandoned turn takes @@ -16,11 +16,17 @@ //! capture lease rides inside the generation future, so its `Drop` records the call as //! cancelled at the same moment, never while the engine still runs. //! - **The agent is slow:** the generation is not polled until the frames of the last chunk -//! are taken, so the engine reads no further from its stream. What waits is bounded by the -//! engine's own stream batching unit: the chunks ONE poll of the generation produced (one -//! read of the engine's SSE connection; llama-server sends one token per event), plus the -//! frames one chunk encodes to. Behind that, the agent's socket and hyper's write buffer -//! push back on the body, and the engine's connection's receive window on llama-server. +//! are taken, and every producer on the local serving path yields after each chunk it sends +//! (`continuum-engine` `ai/stream_sinks.rs`, `deliver`), so one poll sends at most one +//! chunk. The gateway holds that chunk and the frames it encodes to, nothing more. What +//! else waits is the engine's own and is bytes, not chunks: the unparsed rest of its last +//! network read (the adapter's SSE buffer, hyper's read buffer). Behind that the engine +//! connection's receive window stops llama-server writing, and the agent's socket and +//! hyper's write buffer push back on this body. The engine's sink type is unbounded +//! (`AIProviderAdapter::generate_stream`); the bound comes from `deliver`, so a producer +//! that sent around it would break it. Pinned against the real producer by +//! `continuum-engine` `ai/openai_adapter/tests/a_ready_burst_*` and here by +//! `a_stalled_agent_stops_a_ready_burst_at_one_chunk_ahead`. use std::collections::VecDeque; use std::future::Future; @@ -44,19 +50,25 @@ pub(crate) struct Answer { /// `None` once it has returned (its closing frames are queued). generation: Option, /// The engine's sink for this generation (its streaming contract is an unbounded sender); - /// emptied before the generation is polled again, so it holds one poll's chunks at most. + /// emptied before the generation is polled again, and one poll sends at most one chunk + /// (`stream_sinks::deliver`), so it holds one chunk at most. received: UnboundedReceiver, /// The frames of one chunk (or the opening or closing), until the agent takes them. encoded: VecDeque, + /// Resolves when the module stops the gateway (`crate::listener`); polled only while the + /// generation runs. + abandoned: Pin + Send>>, } impl Answer { /// `generation` sends its chunks to the sender `received` drains, and owns everything that - /// must end with it (the engine request and its admission, the capture lease). + /// must end with it (the engine request and its admission, the capture lease). When + /// `abandoned` resolves first, the generation is dropped and the answer closes as failed. pub(crate) fn new( mut encoder: W, generation: impl Future> + Send + 'static, received: UnboundedReceiver, + abandoned: impl Future + Send + 'static, ) -> Self { let encoded = encoder.opened().into(); Self { @@ -64,6 +76,14 @@ impl Answer { generation: Some(Box::pin(generation)), received, encoded, + abandoned: Box::pin(abandoned), + } + } + + /// Encode every chunk the generation already sent. + fn encode_received(&mut self) { + while let Ok(chunk) = self.received.try_recv() { + self.encoded.extend(self.encoder.chunk(&chunk)); } } @@ -97,6 +117,15 @@ impl tokio_stream::Stream for Answer { // dropped its sender; every chunk it sent was taken above. Err(TryRecvError::Empty | TryRecvError::Disconnected) => {} } + if this.generation.is_some() && this.abandoned.as_mut().poll(cx).is_ready() { + // The node is stopping. Dropping the generation is the engine's one + // cancellation path, and its lease records the call as cancelled. + this.generation = None; + this.encode_received(); + this.encoded + .extend(this.encoder.failed(crate::server::STOPPING)); + continue; + } let Some(generation) = this.generation.as_mut() else { return Poll::Ready(None); }; @@ -107,9 +136,7 @@ impl tokio_stream::Stream for Answer { Poll::Ready(outcome) => { this.generation = None; // Its last chunks precede its closing frames. - while let Ok(chunk) = this.received.try_recv() { - this.encoded.extend(this.encoder.chunk(&chunk)); - } + this.encode_received(); let closing = this.closing(outcome); this.encoded.extend(closing); } @@ -122,6 +149,7 @@ impl tokio_stream::Stream for Answer { mod tests { use super::*; use crate::wire::chat::Chat; + use continuum_engine::ai::stream_sinks::deliver; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use tokio::sync::mpsc::UnboundedSender; @@ -134,24 +162,16 @@ mod tests { Pin::new(answer).poll_next(&mut cx) } - /// Pending exactly once, then ready: an engine step between two chunks. - async fn step() { - let mut stepped = false; - std::future::poll_fn(|cx| { - if stepped { - return Poll::Ready(()); - } - stepped = true; - cx.waker().wake_by_ref(); - Poll::Pending - }) - .await - } - /// A generation shaped as the engine's: it holds a slot permit for its whole life (the - /// adapter's `TurnAdmission`), sends `chunks` tokens counting each, then waits forever (a - /// long decode). Returns the answer, the permit's pool and the sent count. - fn generation(chunks: usize) -> (Answer, Arc, Arc) { + /// adapter's `TurnAdmission`), sends `chunks` tokens through the engine's `deliver` with + /// nothing else between them (a READY burst: every token already decoded, as one network + /// read of many events is), counting each, then waits forever (a long decode); the node + /// stops when `abandoned` resolves. Returns the answer, the permit's pool and the sent + /// count. + fn stopping_generation( + chunks: usize, + abandoned: impl Future + Send + 'static, + ) -> (Answer, Arc, Arc) { let slots = Arc::new(Semaphore::new(1)); let permit: OwnedSemaphorePermit = slots .clone() @@ -164,22 +184,29 @@ mod tests { let generation = async move { let _admission = permit; for i in 0..chunks { - if sink.send(GenerationChunk::Token(format!("t{i}"))).is_err() { - return Err(RouteError::Engine("test: sink closed".into())); - } counted.fetch_add(1, Ordering::SeqCst); - step().await; + deliver(&sink, GenerationChunk::Token(format!("t{i}"))).await; } std::future::pending::<()>().await; Err(RouteError::Engine("test: unreachable".into())) }; ( - Answer::new(Chat::streamer("qwen", "chatcmpl_1"), generation, received), + Answer::new( + Chat::streamer("qwen", "chatcmpl_1"), + generation, + received, + abandoned, + ), slots, sent, ) } + /// The same, on a node that keeps serving. + fn generation(chunks: usize) -> (Answer, Arc, Arc) { + stopping_generation(chunks, std::future::pending()) + } + // what this catches: an agent that leaves during prefill (before any token) leaving its // generation running and its slot held, as the spawned generation of 34672ec73 did. #[tokio::test] @@ -227,15 +254,21 @@ mod tests { } // what this catches: a slow agent letting generation run ahead and pile its answer up in - // memory (the unbounded chunk and event queues of 34672ec73). + // memory (the unbounded chunk and event queues of 34672ec73), including when the engine + // has many chunks READY at once (one network read of many events) and nothing yields + // between them but the engine's own `deliver`. #[tokio::test] - async fn a_stalled_agent_stops_generation_at_one_chunk_ahead() { + async fn a_stalled_agent_stops_a_ready_burst_at_one_chunk_ahead() { let (mut answer, _slots, sent) = generation(10_000); for _ in 0..3 { assert!(matches!(poll(&mut answer), Poll::Ready(Some(_)))); } let taken = 2; // the opening frame, then two tokens - // The agent stops reading. Nothing else may drive the generation. + assert!( + answer.received.len() <= 1, + "the gateway holds at most one chunk" + ); + // The agent stops reading. Nothing else may drive the generation. for _ in 0..1_000 { tokio::task::yield_now().await; } @@ -256,7 +289,12 @@ mod tests { .map_err(|_| RouteError::Engine("test: closed".into()))?; Err(RouteError::Engine("lane died".into())) }; - let mut answer = Answer::new(Chat::streamer("qwen", "chatcmpl_1"), generation, received); + let mut answer = Answer::new( + Chat::streamer("qwen", "chatcmpl_1"), + generation, + received, + std::future::pending(), + ); let mut frames = Vec::new(); while let Poll::Ready(Some(frame)) = poll(&mut answer) { frames.push(frame.data); @@ -271,4 +309,44 @@ mod tests { "the failure closes it: {frames:?}" ); } + + // what this catches: a gateway stop that leaves an answer in flight decoding on (its + // engine slot held, its agent waiting) after the module let the listener go, or that + // cuts the stream without telling the agent why. + #[tokio::test] + async fn a_stopping_node_ends_an_answer_in_flight_and_frees_its_slot() { + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let abandoned = async move { + // Err: the test dropped its sender, which stops the node all the same. + match stopped.await { + Ok(()) | Err(_) => {} + } + }; + let (mut answer, slots, _sent) = stopping_generation(1, abandoned); + assert!( + matches!(poll(&mut answer), Poll::Ready(Some(_))), + "the opening frame" + ); + assert!( + matches!(poll(&mut answer), Poll::Ready(Some(_))), + "the token" + ); + assert!(poll(&mut answer).is_pending(), "decoding on"); + assert_eq!(slots.available_permits(), 0); + stop.send(()).expect("test: the answer is listening"); + let mut closing = Vec::new(); + while let Poll::Ready(Some(frame)) = poll(&mut answer) { + closing.push(frame.data); + } + assert_eq!( + slots.available_permits(), + 1, + "stopped: the generation and its slot are gone" + ); + assert!( + closing.iter().any(|f| f.contains(crate::server::STOPPING)), + "the agent is told why: {closing:?}" + ); + assert!(poll(&mut answer).is_ready(), "the answer ended"); + } } diff --git a/core/continuum-gateway/src/lib.rs b/core/continuum-gateway/src/lib.rs index 5da18adc1f..64bae5a977 100644 --- a/core/continuum-gateway/src/lib.rs +++ b/core/continuum-gateway/src/lib.rs @@ -10,6 +10,7 @@ //! call is admitted as anonymous traffic. mod answer; +mod listener; mod module; mod route; mod server; diff --git a/core/continuum-gateway/src/listener.rs b/core/continuum-gateway/src/listener.rs new file mode 100644 index 0000000000..f5ec097f84 --- /dev/null +++ b/core/continuum-gateway/src/listener.rs @@ -0,0 +1,141 @@ +//! The gateway's listener as a resource its module owns (CONCURRENCY-STYLE-GUIDE.md: owned +//! tasks, nothing detached). `initialize` binds it or fails; `drain` closes admission and lets +//! the calls in flight finish; `shutdown` abandons whatever is still in flight and joins the +//! serve task. Codex on #5541 (856ee2b69): a detached `axum::serve` with its port kept in a +//! `OnceLock` reported `listening` after the listener died, could not be stopped, and left a +//! reinitialize colliding with the old socket. + +use std::future::Future; + +use tokio::sync::watch; +use tokio::task::JoinHandle; + +/// One raise-once signal from the module to what it governs. Its receiver resolves when the +/// module raises it, or when the module is gone (which ends what it guards all the same). +#[derive(Clone)] +pub(crate) struct Signal(watch::Receiver); + +impl Signal { + fn pair() -> (watch::Sender, Self) { + let (raise, raised) = watch::channel(false); + (raise, Self(raised)) + } + + /// Resolves once the signal is raised or its owner dropped it. + pub(crate) fn raised(&self) -> impl Future + Send + 'static { + let mut signal = self.0.clone(); + async move { + match signal.wait_for(|raised| *raised).await { + Ok(_) => {} + // The owner dropped its sender: the listener it governs is gone. + Err(_) => {} + } + } + } +} + +/// A bound listener and the task serving it. +pub(crate) struct Listener { + port: u16, + /// Raised: axum stops accepting connections and lets the open ones finish. + close: watch::Sender, + /// Raised: every answer still in flight is stopped (`crate::answer`). + abandon: watch::Sender, + /// Raised by the serve task as it returns, for whoever waits on the drain. + exited: Signal, + serving: JoinHandle<()>, +} + +impl Listener { + /// Bind `port` on loopback (0: any free port) and serve the gateway on it. A port that + /// cannot be bound is the error; there is no listener that only says it is one. + pub(crate) async fn bind(port: u16) -> Result { + let socket = tokio::net::TcpListener::bind(("127.0.0.1", port)) + .await + .map_err(|error| format!("the gateway cannot bind 127.0.0.1:{port}: {error}"))?; + let port = socket + .local_addr() + .map_err(|error| { + format!("the gateway's socket on port {port} has no address: {error}") + })? + .port(); + let (close, closed) = Signal::pair(); + let (abandon, abandoned) = Signal::pair(); + let (exit, exited) = Signal::pair(); + let serving = tokio::spawn(async move { + let outcome = axum::serve(socket, crate::server::router(abandoned)) + .with_graceful_shutdown(closed.raised()) + .await; + match outcome { + Ok(()) => continuum_base::probe!( + class = "gateway.stopped", + port = port as u64, + "the gateway's listener closed" + ), + Err(error) => { + continuum_base::probe!(class = "gateway.stopped", port = port as u64, error = %error, "the gateway's listener failed") + } + } + exit.send_replace(true); + }); + Ok(Self { + port, + close, + abandon, + exited, + serving, + }) + } + + pub(crate) fn port(&self) -> u16 { + self.port + } + + /// Whether it still serves: false once the serve task returned, however it ended. + pub(crate) fn is_live(&self) -> bool { + !self.serving.is_finished() + } + + /// Stop accepting connections; the calls in flight run on. Idempotent. + pub(crate) fn close(&self) { + self.close.send_replace(true); + } + + /// Stop every answer still in flight (the agent is told the node is stopping). + pub(crate) fn abandon(&self) { + self.abandon.send_replace(true); + } + + /// Resolves once the serve task has returned (every connection closed). + pub(crate) fn exited(&self) -> impl Future + Send + 'static { + self.exited.raised() + } + + /// Join the serve task. Called after it exited it returns at once; otherwise the task is + /// aborted first (the bound of a stop ran out), which the probe says. + pub(crate) async fn join(mut self) -> Result<(), String> { + if self.is_live() { + continuum_base::probe!( + class = "gateway.aborted", + port = self.port as u64, + "the gateway's listener did not finish within its stop bound; aborted" + ); + self.serving.abort(); + } + match (&mut self.serving).await { + Ok(()) => Ok(()), + Err(error) if error.is_cancelled() => Ok(()), + Err(error) => Err(format!( + "the gateway's listener on port {} panicked: {error}", + self.port + )), + } + } +} + +impl Drop for Listener { + /// A listener its module let go of never serves on detached. + fn drop(&mut self) { + self.serving.abort(); + } +} diff --git a/core/continuum-gateway/src/module.rs b/core/continuum-gateway/src/module.rs index a6704fd26f..2967a0dfe9 100644 --- a/core/continuum-gateway/src/module.rs +++ b/core/continuum-gateway/src/module.rs @@ -1,20 +1,49 @@ -//! The gateway as a `ServiceModule`: one listener on a stable port, and the commands that -//! report it and print what each agent sets. +//! The gateway as a `ServiceModule`: one listener on a stable port that the module owns +//! through its whole lifecycle ([`crate::listener`]), and the commands that report it and +//! print what each agent sets. use async_trait::async_trait; use continuum_engine::runtime::{CommandResult, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; use serde_json::{json, Value}; +use crate::listener::Listener; + /// The gateway's port when nothing configures one: beside the desktop's 8975. const DEFAULT_PORT: u16 = 8976; +#[derive(Default)] pub struct GatewayModule { - port: std::sync::OnceLock, + /// The listener: `None` before `initialize` and after `shutdown`. Whether it serves is + /// read from its task each time (`Listener::is_live`), never remembered. + listener: tokio::sync::Mutex>, } -impl Default for GatewayModule { - fn default() -> Self { - Self { port: std::sync::OnceLock::new() } +impl GatewayModule { + /// Bind `port` (0: any free port) and serve on it, returning the port bound. Refused while + /// a listener still serves; one that exited is joined first, so a reinitialize after a + /// stop or a failure binds cleanly. + async fn listen(&self, port: u16) -> Result { + let mut slot = self.listener.lock().await; + if let Some(live) = slot.as_ref().filter(|listener| listener.is_live()) { + return Err(format!("the gateway is already listening on port {}", live.port())); + } + if let Some(ended) = slot.take() { + ended.join().await?; + } + let listener = Listener::bind(port).await.inspect_err(|error| { + continuum_base::probe!(class = "gateway.unbound", port = port as u64, error = %error, + "the gateway could not bind its port; agents cannot reach this node until it does"); + })?; + let bound = listener.port(); + continuum_base::probe!(class = "gateway.listening", port = bound as u64, "agents can call this node's engine"); + *slot = Some(listener); + Ok(bound) + } + + /// Where agents reach the gateway, while its listener serves. + async fn url(&self) -> Option { + let slot = self.listener.lock().await; + slot.as_ref().filter(|listener| listener.is_live()).map(|listener| format!("http://127.0.0.1:{}", listener.port())) } } @@ -51,42 +80,107 @@ impl ServiceModule for GatewayModule { } } - /// Bind on loopback; a node that cannot bind says why and serves its residents anyway. + /// Bind on loopback, or fail: a node whose gateway cannot bind reports it as this + /// module's initialization failure (the runtime boots the rest and names it). async fn initialize(&self, _ctx: &ModuleContext) -> Result<(), String> { - let port = configured_port()?; - let listener = match tokio::net::TcpListener::bind(("127.0.0.1", port)).await { - Ok(listener) => listener, - Err(error) => { - continuum_base::probe!(class = "gateway.unbound", port = port as u64, error = %error, - "the gateway could not bind its port; agents cannot reach this node until it does"); - return Ok(()); - } - }; - let _ = self.port.set(port); - continuum_base::probe!(class = "gateway.listening", port = port as u64, "agents can call this node's engine"); - tokio::spawn(async move { - if let Err(error) = axum::serve(listener, crate::server::router()).await { - continuum_base::probe!(class = "gateway.stopped", error = %error, "the gateway's listener ended"); - } - }); - Ok(()) + self.listen(configured_port()?).await.map(|_| ()) } async fn handle_command(&self, command: &str, _params: Value) -> Result { - let base = self.port.get().map(|port| format!("http://127.0.0.1:{port}")); + let base = self.url().await; match command { "gateway/status" => Ok(CommandResult::Json(json!({ "listening": base.is_some(), "url": base, "models": crate::route::served_models().await, }))), "gateway/env" => match base { Some(base) => Ok(CommandResult::Json(env(&base))), - None => Err("the gateway is not listening; see probe gateway.unbound".into()), + None => Err("the gateway is not listening; see probe gateway.unbound or gateway.stopped".into()), }, _ => Err(format!("unknown gateway command: {command}")), } } + /// Close admission and let the calls in flight finish, within the runtime's bound. The + /// listener stays owned here; `shutdown` joins it. + async fn drain(&self) -> Result { + let exited = { + let slot = self.listener.lock().await; + let Some(listener) = slot.as_ref() else { + return Ok(0); + }; + listener.close(); + listener.exited() + }; + exited.await; + Ok(0) + } + + /// Stop what is still in flight (its agents are told the node is stopping), wait for the + /// listener to return, and join it. Cancelled by the runtime's bound, the listener is + /// dropped, which aborts its task. + async fn shutdown(&self) -> Result<(), String> { + let Some(listener) = self.listener.lock().await.take() else { + return Ok(()); + }; + listener.close(); + listener.abandon(); + listener.exited().await; + listener.join().await + } + fn as_any(&self) -> &dyn std::any::Any { self } } + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: a listener the module cannot stop (the detached `axum::serve` of + // 856ee2b69), a stop that leaves status saying `listening`, and a reinitialize that + // collides with the old socket: initialize, stop (drain + shutdown, as the runtime + // does), then initialize again on the SAME port. + #[tokio::test] + async fn a_stopped_gateway_reports_it_and_rebinds_its_port() { + let gateway = GatewayModule::default(); + let port = gateway.listen(0).await.expect("test: binds a free port"); + assert_eq!(gateway.url().await, Some(format!("http://127.0.0.1:{port}"))); + assert!(gateway.listen(0).await.is_err(), "a second listener while one serves is refused"); + assert_eq!(gateway.drain().await, Ok(0), "nothing in flight: drained"); + assert_eq!(gateway.url().await, None, "admission closed: not listening"); + assert_eq!(gateway.shutdown().await, Ok(())); + assert_eq!(gateway.listen(port).await, Ok(port), "the same port binds again after a stop"); + assert_eq!(gateway.shutdown().await, Ok(()), "a stop without a drain abandons and joins"); + assert!(gateway.handle_command("gateway/env", Value::Null).await.is_err(), "stopped: no env to print"); + } + + // what this catches: a port that cannot be bound logged and initialization reported Ok, + // so the node said it was ready while no agent could reach it. + #[tokio::test] + async fn a_port_that_cannot_be_bound_fails_initialization() { + let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("test: a port to occupy"); + let port = taken.local_addr().expect("test: its address").port(); + let gateway = GatewayModule::default(); + let refused = gateway.listen(port).await.expect_err("test: the port is taken"); + assert!(refused.contains(&port.to_string()), "names the port: {refused}"); + assert_eq!(gateway.url().await, None); + } + + // what this catches: status remembered from the bind (the `OnceLock` port) instead of + // read from the listener, so a listener that ended still reads as listening. + #[tokio::test] + async fn status_reads_false_once_the_listener_has_exited() { + let gateway = GatewayModule::default(); + gateway.listen(0).await.expect("test: binds"); + let exited = { + let slot = gateway.listener.lock().await; + let listener = slot.as_ref().expect("test: listening"); + listener.close(); // the serve task returns, as it would on its own failure + listener.exited() + }; + exited.await; + assert_eq!(gateway.url().await, None, "an exited listener is not listening"); + assert!(gateway.listen(0).await.is_ok(), "an exited listener is joined and a new one binds"); + } +} diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs index ae7bdffbd9..a502d08cc5 100644 --- a/core/continuum-gateway/src/server.rs +++ b/core/continuum-gateway/src/server.rs @@ -1,7 +1,9 @@ //! The one HTTP server: every format's route through the same handler. +use crate::listener::Signal; use crate::route::{self, RouteError}; use crate::wire::{anthropic::Anthropic, chat::Chat, responses::Responses, BadRequest, ErrorKind, Wire}; +use axum::extract::State; use axum::http::StatusCode; use axum::response::sse::{KeepAlive, Sse}; use axum::response::{IntoResponse, Json, Response}; @@ -9,15 +11,21 @@ use axum::routing::{get, post}; use axum::Router; use serde_json::{json, Value}; -pub(crate) fn router() -> Router { +/// The routes, serving until the module raises `abandoned` (`crate::listener`): then every +/// call still in flight is stopped and its agent told why. +pub(crate) fn router(abandoned: Signal) -> Router { Router::new() .route("/v1/messages", post(serve::)) .route("/v1/chat/completions", post(serve::)) .route("/v1/responses", post(serve::)) .route("/v1/models", get(models)) .route("/health", get(|| async { Json(json!({"status": "ok", "service": "continuum-gateway"})) })) + .with_state(abandoned) } +/// What an agent whose call was in flight is told when the node stops. +pub(crate) const STOPPING: &str = "this node's gateway is stopping; the call was stopped before it finished"; + /// `GET /v1/models`: what this node serves, in the shape every format's clients read. async fn models() -> Json { let data: Vec = route::served_models() @@ -29,7 +37,7 @@ async fn models() -> Json { } /// Decode, select, generate, encode: the same for every format. -async fn serve(headers: axum::http::HeaderMap, Json(body): Json) -> Response { +async fn serve(State(abandoned): State, headers: axum::http::HeaderMap, Json(body): Json) -> Response { let mut call = match W::decode(body) { Ok(call) => call, Err(BadRequest(why)) => return refuse::(StatusCode::BAD_REQUEST, ErrorKind::InvalidRequest, &why), @@ -59,7 +67,12 @@ async fn serve(headers: axum::http::HeaderMap, Json(body): Json) Err(unavailable) => return capture_refused::(&unavailable), }; if !call.stream { - let outcome = route::generate(&adapter, call.request).await; + // Abandoned: the generation is dropped (the engine's cancellation path) and so is the + // lease, which records the call as cancelled. + let outcome = tokio::select! { + outcome = route::generate(&adapter, call.request) => outcome, + () = abandoned.raised() => return refuse::(StatusCode::SERVICE_UNAVAILABLE, ErrorKind::Engine, STOPPING), + }; crate::session::settle(&mut lease, &outcome); return match outcome { Ok(response) => Json(W::answer(&response, &id)).into_response(), @@ -73,7 +86,7 @@ async fn serve(headers: axum::http::HeaderMap, Json(body): Json) crate::session::settle(&mut lease, &outcome); outcome }; - let answer = crate::answer::Answer::new(W::streamer(&model, &id), generation, received); + let answer = crate::answer::Answer::new(W::streamer(&model, &id), generation, received, abandoned.raised()); let events = tokio_stream::StreamExt::map(answer, |frame| Ok::<_, std::convert::Infallible>(frame.into_event())); Sse::new(events).keep_alive(KeepAlive::default()).into_response() } diff --git a/core/continuum-gateway/src/wire/anthropic.rs b/core/continuum-gateway/src/wire/anthropic.rs index 84a0f276d8..d722e562b0 100644 --- a/core/continuum-gateway/src/wire/anthropic.rs +++ b/core/continuum-gateway/src/wire/anthropic.rs @@ -1,11 +1,14 @@ //! Anthropic Messages (`POST /v1/messages`): Claude Code, via `ANTHROPIC_BASE_URL`. -use super::{event, input_schema, place_system, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{decode, event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::types::ImageInput; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; use serde_json::{json, Value}; +/// Anthropic's documented ceiling for `temperature`. +const ANTHROPIC_TEMPERATURE_MAX: f64 = 1.0; + /// One streamed answer: the open content block with its index, and the next index. pub(crate) struct Anthropic { model: String, @@ -25,22 +28,22 @@ impl Wire for Anthropic { fn decode(body: Value) -> Result { let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; - let max_tokens = body.get("max_tokens").and_then(Value::as_u64).ok_or_else(|| BadRequest("`max_tokens` is required".into()))?; + let max_tokens = decode::token_limit(&body, &["max_tokens"])?.ok_or_else(|| BadRequest("`max_tokens` is required".into()))?; let messages = body.get("messages").and_then(Value::as_array).ok_or_else(|| BadRequest("`messages` is required".into()))?; let mut request = TextGenerationRequest { model: Some(model.to_owned()), - max_tokens: Some(max_tokens as u32), - top_k: body.get("top_k").and_then(Value::as_u64).map(|k| k as u32), + max_tokens: Some(max_tokens), + top_k: decode::count(&body, "top_k", 0)?, system_prompt: body.get("system").map(text_of).filter(|s| !s.is_empty()), messages: messages.iter().map(message).collect::>()?, - tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), - tool_choice: body.get("tool_choice").and_then(tool_choice), + tools: decode::tools(&body, tool)?, + tool_choice: tool_choice(&body)?, purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), ..Default::default() }; - sampling(&body, &mut request); + decode::sampling(&body, &mut request, ANTHROPIC_TEMPERATURE_MAX)?; (request.system_prompt, request.messages) = place_system(request.system_prompt.take(), std::mem::take(&mut request.messages)); - Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed + Ok(Call { request, stream: decode::streamed(&body)? }) } fn answer(response: &TextGenerationResponse, id: &str) -> Value { @@ -206,17 +209,27 @@ fn part(block: &Value) -> Option { } } -fn tool(value: &Value) -> Option { - Some(NativeToolSpec { - name: value.get("name").and_then(Value::as_str)?.to_owned(), - description: value.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description - input_schema: input_schema(value.get("input_schema")?), - }) +/// An Anthropic tool: `{name, description, input_schema}`, untyped or `type: "custom"`. A +/// server tool (`web_search_*`, `bash_*`, `text_editor_*`) is refused, never dropped: Claude +/// Code would expect a tool the model was never shown. +fn tool(entry: &Value) -> Result { + match decode::tool_type(entry)? { + None | Some("custom") => { + let schema = entry.get("input_schema").filter(|s| !s.is_null()).ok_or("has no `input_schema`")?; + decode::tool_spec(entry.get("name"), entry.get("description"), Some(schema)) + } + Some(other) => Err(decode::unserved(other, "custom")), + } } -fn tool_choice(value: &Value) -> Option { - match value.get("type").and_then(Value::as_str)? { - "tool" => Some(ToolChoice::Specific { name: value.get("name").and_then(Value::as_str)?.to_owned() }), - mode => Some(ToolChoice::Mode(mode.to_owned())), +/// The Anthropic `tool_choice`: `{type: auto | any | none}`, or `{type: "tool", name}`. +fn tool_choice(body: &Value) -> Result, BadRequest> { + let Some(choice) = decode::present(body, "tool_choice") else { + return Ok(None); + }; + match choice.get("type").and_then(Value::as_str) { + Some("tool") => decode::choice_named(choice.get("name")).map(Some), + Some(mode) => decode::choice_mode(mode, &[("auto", "auto"), ("any", "any"), ("none", "none")]).map(Some), + None => Err(BadRequest("`tool_choice` has no `type`".into())), } } diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs index 22efe2b58c..50d661508a 100644 --- a/core/continuum-gateway/src/wire/chat.rs +++ b/core/continuum-gateway/src/wire/chat.rs @@ -1,11 +1,15 @@ //! OpenAI Chat Completions (`POST /v1/chat/completions`): Hermes, opencode, and most agents. -use super::{event, input_schema, place_system, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::decode::{self, present}; +use super::{event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::types::ImageInput; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; use serde_json::{json, Value}; +/// OpenAI's documented ceiling for `temperature` (Chat Completions and Responses alike). +pub(super) const OPENAI_TEMPERATURE_MAX: f64 = 2.0; + /// One streamed answer. pub(crate) struct Chat { model: String, @@ -22,20 +26,16 @@ impl Wire for Chat { let (system_prompt, messages) = place_system(None, conversation(messages)?); let mut request = TextGenerationRequest { model: Some(model.to_owned()), - max_tokens: body - .get("max_completion_tokens") - .or_else(|| body.get("max_tokens")) - .and_then(Value::as_u64) - .map(|t| t as u32), + max_tokens: decode::token_limit(&body, &["max_completion_tokens", "max_tokens"])?, system_prompt, messages, - tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), - tool_choice: body.get("tool_choice").and_then(tool_choice), + tools: decode::tools(&body, tool)?, + tool_choice: tool_choice(&body)?, purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), ..Default::default() }; - sampling(&body, &mut request); - Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed + decode::sampling(&body, &mut request, OPENAI_TEMPERATURE_MAX)?; + Ok(Call { request, stream: decode::streamed(&body)? }) } fn answer(response: &TextGenerationResponse, id: &str) -> Value { @@ -199,21 +199,27 @@ pub(super) fn image(url: &str) -> ImageInput { } } -fn tool(value: &Value) -> Option { - let function = value.get("function")?; - Some(NativeToolSpec { - name: function.get("name").and_then(Value::as_str)?.to_owned(), - description: function.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description - input_schema: input_schema(&function["parameters"]), - }) +/// A Chat Completions tool: `{type: "function", function: {name, description, parameters}}`. +fn tool(entry: &Value) -> Result { + match decode::tool_type(entry)? { + Some("function") => {} + Some(other) => return Err(decode::unserved(other, "`function`")), + None => return Err("has no `type`".into()), + } + let function = entry.get("function").filter(|f| f.is_object()).ok_or("has no `function` object")?; + decode::tool_spec(function.get("name"), function.get("description"), function.get("parameters")) } -pub(super) fn tool_choice(value: &Value) -> Option { - match value { - Value::String(mode) => Some(ToolChoice::Mode(if mode == "required" { "any".into() } else { mode.clone() })), - Value::Object(_) => Some(ToolChoice::Specific { - name: value.get("function").and_then(|f| f.get("name")).or_else(|| value.get("name")).and_then(Value::as_str)?.to_owned(), - }), - _ => None, +/// The OpenAI `tool_choice`: a mode (`required` is the engine's `any`), or one function by +/// name (`{type: "function", function: {name}}` here, `{type: "function", name}` in +/// Responses). +pub(super) fn tool_choice(body: &Value) -> Result, BadRequest> { + match present(body, "tool_choice") { + None => Ok(None), + Some(Value::String(mode)) => decode::choice_mode(mode, &[("none", "none"), ("auto", "auto"), ("required", "any")]).map(Some), + Some(choice @ Value::Object(_)) => { + decode::choice_named(choice.get("function").and_then(|f| f.get("name")).or_else(|| choice.get("name"))).map(Some) + } + Some(other) => Err(BadRequest(format!("`tool_choice` must be a mode or an object, got {}", decode::kind(other)))), } } diff --git a/core/continuum-gateway/src/wire/decode.rs b/core/continuum-gateway/src/wire/decode.rs new file mode 100644 index 0000000000..8a12aaa40c --- /dev/null +++ b/core/continuum-gateway/src/wire/decode.rs @@ -0,0 +1,305 @@ +//! The checked decoders every format shares. A field the agent sent is read whole or the call +//! is refused with why, before anything is selected or generated: a malformed tool never +//! disappears from the list, a token limit is never wrapped into range, a stop sequence is +//! never dropped. Absent (or `null`) means not sent, which each API defines; each format's +//! adapter holds only where its API really differs (field names, tool shapes, ranges). + +use super::BadRequest; +use continuum_engine::ai::{NativeToolSpec, TextGenerationRequest, ToolChoice, ToolInputSchema}; +use serde_json::{Map, Value}; + +/// The field `key`, when the agent sent it: absent and `null` are both not sent. +pub(crate) fn present<'a>(body: &'a Value, key: &str) -> Option<&'a Value> { + body.get(key).filter(|value| !value.is_null()) +} + +/// The JSON type of a value, for a refusal (the value itself can be a whole schema). +pub(crate) fn kind(value: &Value) -> &'static str { + match value { + Value::Null => "null", + Value::Bool(_) => "a boolean", + Value::Number(_) => "a number", + Value::String(_) => "a string", + Value::Array(_) => "an array", + Value::Object(_) => "an object", + } +} + +/// `key` as a whole count of at least `min`, refused past what the engine's `u32` holds. +pub(crate) fn count(body: &Value, key: &str, min: u32) -> Result, BadRequest> { + let Some(value) = present(body, key) else { + return Ok(None); + }; + let wide = value + .as_u64() + .ok_or_else(|| BadRequest(format!("`{key}` must be a whole number, got {value}")))?; + let count = u32::try_from(wide).map_err(|_| { + BadRequest(format!( + "`{key}` = {wide} is past the largest this engine accepts ({})", + u32::MAX + )) + })?; + if count < min { + return Err(BadRequest(format!( + "`{key}` must be at least {min}, got {count}" + ))); + } + Ok(Some(count)) +} + +/// The answer's token limit from whichever of `keys` the agent sent (the APIs name it +/// differently and some accept an older name). Every key sent is checked; the first wins. +/// A limit is at least one token. +pub(crate) fn token_limit(body: &Value, keys: &[&str]) -> Result, BadRequest> { + let mut limit = None; + for key in keys { + let checked = count(body, key, 1)?; + limit = limit.or(checked); + } + Ok(limit) +} + +/// Whether the agent asked to stream. Not sent means no: every API's default. +pub(crate) fn streamed(body: &Value) -> Result { + match present(body, "stream") { + None => Ok(false), + Some(Value::Bool(stream)) => Ok(*stream), + Some(other) => Err(BadRequest(format!( + "`stream` must be a boolean, got {}", + kind(other) + ))), + } +} + +/// A real number in `range`, narrowed to the engine's `f32`. +fn real( + body: &Value, + key: &str, + range: std::ops::RangeInclusive, +) -> Result, BadRequest> { + let Some(value) = present(body, key) else { + return Ok(None); + }; + let number = value + .as_f64() + .ok_or_else(|| BadRequest(format!("`{key}` must be a number, got {}", kind(value))))?; + if !range.contains(&number) { + return Err(BadRequest(format!( + "`{key}` must be within {}..={}, got {number}", + range.start(), + range.end() + ))); + } + Ok(Some(number as f32)) +} + +/// The sampling fields every format names the same way: temperature (whose ceiling is the +/// format's: 2 for OpenAI, 1 for Anthropic), top_p, and the stop sequences under `stop` or +/// `stop_sequences`, one string or an array of strings. +pub(crate) fn sampling( + body: &Value, + request: &mut TextGenerationRequest, + temperature_max: f64, +) -> Result<(), BadRequest> { + request.temperature = real(body, "temperature", 0.0..=temperature_max)?; + request.top_p = real(body, "top_p", 0.0..=1.0)?; + let key = if present(body, "stop").is_some() { + "stop" + } else { + "stop_sequences" + }; + request.stop_sequences = match present(body, key) { + None => None, + Some(Value::String(stop)) => Some(vec![stop.clone()]), + Some(Value::Array(stops)) => Some( + stops + .iter() + .enumerate() + .map(|(at, stop)| { + stop.as_str().map(str::to_owned).ok_or_else(|| { + BadRequest(format!( + "`{key}[{at}]` must be a string, got {}", + kind(stop) + )) + }) + }) + .collect::>()?, + ), + Some(other) => { + return Err(BadRequest(format!( + "`{key}` must be a string or an array of strings, got {}", + kind(other) + ))) + } + }; + Ok(()) +} + +/// The agent's `tools`, each entry read by the format's `one`. Any entry it cannot read (a +/// malformed one, or a type this gateway does not serve) refuses the whole call, naming the +/// entry: a tool the agent declared and the model never sees is a silent wrong answer. +pub(crate) fn tools( + body: &Value, + one: impl Fn(&Value) -> Result, +) -> Result>, BadRequest> { + let Some(value) = present(body, "tools") else { + return Ok(None); + }; + let Value::Array(entries) = value else { + return Err(BadRequest(format!( + "`tools` must be an array, got {}", + kind(value) + ))); + }; + entries + .iter() + .enumerate() + .map(|(at, entry)| one(entry).map_err(|why| BadRequest(format!("`tools[{at}]` {why}")))) + .collect::, _>>() + .map(Some) +} + +/// A tool's type, which a format's adapter matches against the types it serves. +pub(crate) fn tool_type(entry: &Value) -> Result, String> { + match entry.get("type") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(kind)) => Ok(Some(kind.as_str())), + Some(other) => Err(format!( + "has a `type` that is {}, not a string", + kind(other) + )), + } +} + +/// The refusal for a tool type this gateway does not serve: its tools are the agent's own +/// functions, never a provider's built-ins (web search, a hosted shell). +pub(crate) fn unserved(kind: &str, served: &str) -> String { + format!("has type `{kind}`, which this gateway does not serve (it serves {served} tools: the agent's own functions)") +} + +/// One tool from its parts as every format names them: a name, an optional description, +/// and an optional JSON-schema object for its input (no schema is a tool with no input). +pub(crate) fn tool_spec( + name: Option<&Value>, + description: Option<&Value>, + schema: Option<&Value>, +) -> Result { + let name = match name { + Some(Value::String(name)) if !name.is_empty() => name.clone(), + Some(Value::String(_)) => return Err("has an empty `name`".into()), + Some(other) if !other.is_null() => { + return Err(format!( + "has a `name` that is {}, not a string", + kind(other) + )) + } + _ => return Err("has no `name`".into()), + }; + let description = match description { + None | Some(Value::Null) => String::new(), + Some(Value::String(description)) => description.clone(), + Some(other) => { + return Err(format!( + "has a `description` that is {}, not a string", + kind(other) + )) + } + }; + let input_schema = match schema { + None | Some(Value::Null) => input_schema(&Map::new())?, + Some(Value::Object(schema)) => input_schema(schema)?, + Some(other) => { + return Err(format!( + "has an input schema that is {}, not an object", + kind(other) + )) + } + }; + Ok(NativeToolSpec { + name, + description, + input_schema, + }) +} + +/// A JSON-schema object as the engine's tool input schema, which is always an object. +fn input_schema(schema: &Map) -> Result { + match schema.get("type") { + None | Some(Value::Null) => {} + Some(Value::String(kind)) if kind == "object" => {} + Some(other) => { + return Err(format!( + "has an input schema of type {other}; a tool's input is an object" + )) + } + } + let properties = match schema.get("properties") { + None | Some(Value::Null) => Value::Object(Map::new()), + Some(properties @ Value::Object(_)) => properties.clone(), + Some(other) => { + return Err(format!( + "has schema `properties` that are {}, not an object", + kind(other) + )) + } + }; + let required = match schema.get("required") { + None | Some(Value::Null) => None, + Some(Value::Array(names)) => Some( + names + .iter() + .map(|name| { + name.as_str().map(str::to_owned).ok_or_else(|| { + format!( + "has a schema `required` entry that is {}, not a name", + kind(name) + ) + }) + }) + .collect::>()?, + ), + Some(other) => { + return Err(format!( + "has schema `required` that is {}, not an array", + kind(other) + )) + } + }; + Ok(ToolInputSchema { + schema_type: "object".into(), + properties, + required, + definitions: schema + .get("$defs") + .or_else(|| schema.get("definitions")) + .cloned(), + }) +} + +/// A tool choice the agent named: a mode from `modes` (each API's own vocabulary, mapped to +/// the engine's), or one tool by `name`. Anything else refuses the call. +pub(crate) fn choice_mode(mode: &str, modes: &[(&str, &str)]) -> Result { + modes + .iter() + .find(|(said, _)| *said == mode) + .map(|(_, engine)| ToolChoice::Mode((*engine).to_owned())) + .ok_or_else(|| { + let known: Vec<&str> = modes.iter().map(|(said, _)| *said).collect(); + BadRequest(format!( + "`tool_choice` `{mode}` is not one of {}", + known.join(", ") + )) + }) +} + +/// A tool choice that names one tool. +pub(crate) fn choice_named(name: Option<&Value>) -> Result { + match name { + Some(Value::String(name)) if !name.is_empty() => { + Ok(ToolChoice::Specific { name: name.clone() }) + } + _ => Err(BadRequest( + "`tool_choice` names a tool without a `name`".into(), + )), + } +} diff --git a/core/continuum-gateway/src/wire/mod.rs b/core/continuum-gateway/src/wire/mod.rs index 52a00ff95d..9d4bd7e43d 100644 --- a/core/continuum-gateway/src/wire/mod.rs +++ b/core/continuum-gateway/src/wire/mod.rs @@ -1,11 +1,12 @@ //! The APIs agents speak, each an adapter holding only its diff. //! //! A format decodes the agent's body into one [`Call`] and encodes the engine's answer back, -//! whole or as a stream. Everything they share (selection, generation, the SSE transport, -//! errors) lives once in `route` and `server`. +//! whole or as a stream. Everything they share lives once: the checked field decoders in +//! [`decode`], selection, generation, the SSE transport and errors in `route` and `server`. pub(crate) mod anthropic; pub(crate) mod chat; +pub(crate) mod decode; pub(crate) mod responses; use continuum_engine::ai::adapter::GenerationChunk; @@ -110,19 +111,6 @@ pub(crate) fn text_of(value: &Value) -> String { } } -/// A JSON-schema object as the engine's tool input schema. -pub(crate) fn input_schema(schema: &Value) -> continuum_engine::ai::ToolInputSchema { - continuum_engine::ai::ToolInputSchema { - schema_type: "object".into(), - properties: schema.get("properties").cloned().unwrap_or_else(|| Value::Object(Default::default())), // unwrap_or_else: a tool with no parameters has empty properties - required: schema - .get("required") - .and_then(Value::as_array) - .map(|r| r.iter().filter_map(Value::as_str).map(str::to_owned).collect()), - definitions: schema.get("$defs").or_else(|| schema.get("definitions")).cloned(), - } -} - /// Where system text may go. The engine's chat templates accept one system message, first /// (Qwen's raises "System message must be at the beginning"), and agents send more: Claude /// Code a `system` message after the user's turn (its hook and environment context), Codex @@ -170,16 +158,5 @@ pub(crate) fn cached_tokens(response: &TextGenerationResponse) -> Option { response.timing.as_ref().map(|t| t.cached_tokens) } -/// The sampling fields every format names the same way: temperature, top_p, stop. -pub(crate) fn sampling(body: &Value, request: &mut TextGenerationRequest) { - request.temperature = body.get("temperature").and_then(Value::as_f64).map(|t| t as f32); - request.top_p = body.get("top_p").and_then(Value::as_f64).map(|t| t as f32); - request.stop_sequences = match body.get("stop").or_else(|| body.get("stop_sequences")) { - Some(Value::String(s)) => Some(vec![s.clone()]), - Some(Value::Array(a)) => Some(a.iter().filter_map(Value::as_str).map(str::to_owned).collect()), - _ => None, - }; -} - #[cfg(test)] mod tests; diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs index 15acf3f2a9..a9b8de4021 100644 --- a/core/continuum-gateway/src/wire/responses.rs +++ b/core/continuum-gateway/src/wire/responses.rs @@ -4,7 +4,7 @@ //! mind's memory, which arrives with session identity (DRIVER-GATEWAY.md G2); until then a //! call that names one is refused rather than answered without its history. -use super::{chat, event, input_schema, place_system, sampling, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{chat, decode, event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse}; use serde_json::{json, Value}; @@ -35,17 +35,17 @@ impl Wire for Responses { }; let mut request = TextGenerationRequest { model: Some(model.to_owned()), - max_tokens: body.get("max_output_tokens").and_then(Value::as_u64).map(|t| t as u32), - system_prompt: body.get("instructions").and_then(Value::as_str).map(str::to_owned), + max_tokens: decode::token_limit(&body, &["max_output_tokens"])?, + system_prompt: instructions(&body)?, messages, - tools: body.get("tools").and_then(Value::as_array).map(|tools| tools.iter().filter_map(tool).collect()), - tool_choice: body.get("tool_choice").and_then(chat::tool_choice), + tools: decode::tools(&body, tool)?, + tool_choice: chat::tool_choice(&body)?, purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), ..Default::default() }; - sampling(&body, &mut request); + decode::sampling(&body, &mut request, chat::OPENAI_TEMPERATURE_MAX)?; (request.system_prompt, request.messages) = place_system(request.system_prompt.take(), std::mem::take(&mut request.messages)); - Ok(Call { request, stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false) }) // unwrap_or: the API's default is not streamed + Ok(Call { request, stream: decode::streamed(&body)? }) } fn answer(response: &TextGenerationResponse, id: &str) -> Value { @@ -224,13 +224,22 @@ fn content(value: &Value) -> MessageContent { } } -fn tool(value: &Value) -> Option { - if value.get("type").and_then(Value::as_str) != Some("function") { - return None; // built-in tools (web search, file search) are the provider's, not ours +/// The `instructions`, a string when sent. +fn instructions(body: &Value) -> Result, BadRequest> { + match decode::present(body, "instructions") { + None => Ok(None), + Some(Value::String(text)) => Ok(Some(text.clone())), + Some(other) => Err(BadRequest(format!("`instructions` must be a string, got {}", decode::kind(other)))), + } +} + +/// A Responses tool: `{type: "function", name, description, parameters}`. A provider's +/// built-in (web search, file search, a hosted shell) is refused, never dropped: the agent +/// would expect a tool the model was never shown. +fn tool(entry: &Value) -> Result { + match decode::tool_type(entry)? { + Some("function") => decode::tool_spec(entry.get("name"), entry.get("description"), entry.get("parameters")), + Some(other) => Err(decode::unserved(other, "`function`")), + None => Err("has no `type`".into()), } - Some(NativeToolSpec { - name: value.get("name").and_then(Value::as_str)?.to_owned(), - description: value.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), // unwrap_or_default: a tool may have no description - input_schema: input_schema(&value["parameters"]), - }) } diff --git a/core/continuum-gateway/src/wire/tests.rs b/core/continuum-gateway/src/wire/tests.rs index 0466ee5674..eb0831d7fa 100644 --- a/core/continuum-gateway/src/wire/tests.rs +++ b/core/continuum-gateway/src/wire/tests.rs @@ -141,13 +141,13 @@ fn responses_groups_items_refuses_missing_state_and_numbers_its_events() { {"type": "function_call_output", "call_id": "c2", "output": "B"}, {"type": "reasoning", "summary": []}, ], - "tools": [{"type": "function", "name": "read", "parameters": {"type": "object", "properties": {"p": {"type": "string"}}}}, {"type": "web_search"}], + "tools": [{"type": "function", "name": "read", "parameters": {"type": "object", "properties": {"p": {"type": "string"}}}}], })) .expect("test: decodes"); assert_eq!(call.request.system_prompt.as_deref(), Some("You are Grok.\n\nSandbox: workspace-write."), "a leading developer item joins the instructions"); assert_eq!(call.request.messages.len(), 4, "user, one assistant turn with both calls, two tool replies"); assert_eq!(parts(&call.request.messages[1]).len(), 2); - assert_eq!(call.request.tools.as_ref().map(Vec::len), Some(1), "provider built-ins are not ours"); + assert_eq!(call.request.tools.as_ref().map(Vec::len), Some(1)); let mut s = Responses::streamer("qwen", "resp_1"); let mut frames = s.opened(); @@ -161,3 +161,90 @@ fn responses_groups_items_refuses_missing_state_and_numbers_its_events() { assert_eq!(last["response"]["output"][0]["content"][0]["text"], "Reading it."); assert_eq!(last["response"]["output"][1]["call_id"], "call_1"); } + +/// Decode `body` in each format with `fields` merged in; every one must refuse. +fn refused_by_every_format(fields: Value) -> Vec { + let merge = |mut body: Value| { + for (key, value) in fields.as_object().expect("test: fields are an object") { + body[key] = value.clone(); + } + body + }; + let anthropic = merge(json!({"model": "qwen", "max_tokens": 64, "messages": [{"role": "user", "content": "go"}]})); + let chat = merge(json!({"model": "qwen", "messages": [{"role": "user", "content": "go"}]})); + let responses = merge(json!({"model": "qwen", "input": "go"})); + [ + Anthropic::decode(anthropic).err().map(|BadRequest(why)| why), + Chat::decode(chat).err().map(|BadRequest(why)| why), + Responses::decode(responses).err().map(|BadRequest(why)| why), + ] + .into_iter() + .map(|why| why.unwrap_or_else(|| panic!("test: {fields} must refuse in every format"))) + .collect() +} + +// what this catches: a malformed tool entry filtered out of the list (`filter_map`), so the +// model runs without a tool the agent declared and the agent never learns why. Decode is the +// first step of `server::serve`, so a refusal here is before selection and generation. +#[test] +fn a_malformed_tool_entry_refuses_the_call_in_every_format() { + let anthropic = Anthropic::decode(json!({"model": "qwen", "max_tokens": 64, "messages": [{"role": "user", "content": "go"}], + "tools": [{"name": "ls", "input_schema": {"type": "object"}}, {"description": "no name", "input_schema": {"type": "object"}}]})); + let chat = Chat::decode(json!({"model": "qwen", "messages": [{"role": "user", "content": "go"}], + "tools": [{"type": "function", "function": {"name": "ls", "parameters": {"type": "object", "required": ["dir", 7]}}}]})); + let responses = Responses::decode(json!({"model": "qwen", "input": "go", + "tools": [{"type": "function", "name": "ls", "parameters": "not a schema"}]})); + for (format, outcome) in [("anthropic", anthropic), ("chat", chat), ("responses", responses)] { + let Err(BadRequest(why)) = outcome else { panic!("test: {format} must refuse a malformed tool") }; + assert!(why.starts_with("`tools["), "{format} names the entry: {why}"); + } + let whys = refused_by_every_format(json!({"tools": {"name": "ls"}})); + assert!(whys.iter().all(|why| why.contains("must be an array")), "{whys:?}"); +} + +// what this catches: a provider built-in tool (web search, a server tool) silently dropped, +// so the agent expects a capability the model was never shown. +#[test] +fn an_unsupported_tool_type_refuses_the_call() { + let anthropic = Anthropic::decode(json!({"model": "qwen", "max_tokens": 64, "messages": [{"role": "user", "content": "go"}], + "tools": [{"type": "web_search_20250305", "name": "web_search"}]})); + let chat = Chat::decode(json!({"model": "qwen", "messages": [{"role": "user", "content": "go"}], + "tools": [{"type": "custom", "custom": {"name": "apply_patch"}}]})); + let responses = Responses::decode(json!({"model": "qwen", "input": "go", "tools": [{"type": "web_search"}]})); + for (format, outcome) in [("anthropic", anthropic), ("chat", chat), ("responses", responses)] { + let Err(BadRequest(why)) = outcome else { panic!("test: {format} must refuse an unserved tool type") }; + assert!(why.contains("does not serve"), "{format} says why: {why}"); + } +} + +// what this catches: `u64 as u32` wrapping a token limit (4294967296 became 0, 4294967297 +// became 1) and a zero limit reaching the engine. +#[test] +fn an_out_of_range_token_limit_refuses_the_call() { + for limit in [json!(4_294_967_296u64), json!(0), json!(-1), json!(1.5), json!("64")] { + let anthropic = Anthropic::decode(json!({"model": "qwen", "max_tokens": limit, "messages": [{"role": "user", "content": "go"}]})); + let chat = Chat::decode(json!({"model": "qwen", "max_completion_tokens": limit, "messages": [{"role": "user", "content": "go"}]})); + let older = Chat::decode(json!({"model": "qwen", "max_completion_tokens": 64, "max_tokens": limit, "messages": [{"role": "user", "content": "go"}]})); + let responses = Responses::decode(json!({"model": "qwen", "max_output_tokens": limit, "input": "go"})); + for (format, outcome) in [("anthropic", anthropic), ("chat", chat), ("chat max_tokens", older), ("responses", responses)] { + assert!(outcome.is_err(), "{format} must refuse a token limit of {limit}"); + } + } + let largest = Chat::decode(json!({"model": "qwen", "max_tokens": u32::MAX, "messages": [{"role": "user", "content": "go"}]})); + assert_eq!(largest.expect("test: the largest u32 is a limit").request.max_tokens, Some(u32::MAX)); +} + +// what this catches: a stop sequence that is not a string dropped from the list, so the +// answer runs past where the agent asked it to stop; and other sampling fields of the wrong +// type or range ignored instead of refused. +#[test] +fn malformed_sampling_refuses_the_call() { + let whys = refused_by_every_format(json!({"stop": ["END", 7]})); + assert!(whys.iter().all(|why| why.contains("`stop[1]`")), "{whys:?}"); + refused_by_every_format(json!({"stop_sequences": {"END": true}})); + refused_by_every_format(json!({"temperature": "warm"})); + refused_by_every_format(json!({"top_p": 1.5})); + refused_by_every_format(json!({"stream": "yes"})); + let call = Chat::decode(json!({"model": "qwen", "stop": ["END", "STOP"], "messages": [{"role": "user", "content": "go"}]})); + assert_eq!(call.expect("test: decodes").request.stop_sequences, Some(vec!["END".to_string(), "STOP".to_string()])); +} diff --git a/docs/architecture/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md index 2ffa4ad7f8..e43008bf4f 100644 --- a/docs/architecture/DRIVER-GATEWAY.md +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -32,7 +32,7 @@ The port is stable and configured, never dynamic, because an agent needs a URL i - `OPENAI_BASE_URL` for Hermes, opencode and Codex; - `--xai-api-base-url` for Grok Build. -**Wire formats are adapters holding only the diff.** Each one is a decoder into the one internal request (`TextGenerationRequest`) and an encoder out of its stream, with SSE included. +**Wire formats are adapters holding only the diff.** Each one is a decoder into the one internal request (`TextGenerationRequest`) and an encoder out of its stream, with SSE included. A field the agent sent is read whole or the call is refused before anything is generated (`continuum-gateway` `wire/decode.rs`): a malformed tool or a provider's built-in one, a token limit outside the engine's range, a stop sequence that is not a string. Nothing an agent declared is dropped. | Wire format | Path | Agents | |---|---|---| From bf92b6177065749e2f8c68ea7b3aa01249650fd6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 17:45:56 -0500 Subject: [PATCH 23/27] A gateway stop cuts every connection, so an agent that stops reading cannot hold its generation past it (Codex on f2a3600fe) An agent that stays connected but stops reading fills its socket, hyper stops polling the response body, and the abandon signal the body would read is never read. Its generation (the engine's TurnAdmission, the capture lease) and its connection task then outlived the stop. Every accepted socket is now wrapped in a Severable connection (continuum-gateway sever.rs) that polls the listener's abandon signal on every read and write. Shutdown raises the signal, so a stalled connection's task is woken and its writes fail. Hyper ends the connection and drops the body, with the generation inside it. axum's graceful serve returns only after every connection task has ended, so the listener's exit means no connection, body or lease survived. The generation stays owned by the body; no producer is detached. Regression over real HTTP (module.rs): a long streamed answer through the real Answer and SSE response; a client that sends its request and never reads until both sockets are full; then drain and shutdown, each under the runtime's SHUTDOWN_PHASE. Drain runs to its bound. Shutdown completes within it with the admission released, the capture stand-in settled and no live task left. The disconnect and ready-burst tests are kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/src/answer.rs | 3 + core/continuum-gateway/src/lib.rs | 1 + core/continuum-gateway/src/listener.rs | 25 +++-- core/continuum-gateway/src/module.rs | 112 +++++++++++++++++++-- core/continuum-gateway/src/server.rs | 6 +- core/continuum-gateway/src/sever.rs | 134 +++++++++++++++++++++++++ 6 files changed, 267 insertions(+), 14 deletions(-) create mode 100644 core/continuum-gateway/src/sever.rs diff --git a/core/continuum-gateway/src/answer.rs b/core/continuum-gateway/src/answer.rs index 5869789ebb..30c5ff3c00 100644 --- a/core/continuum-gateway/src/answer.rs +++ b/core/continuum-gateway/src/answer.rs @@ -27,6 +27,9 @@ //! that sent around it would break it. Pinned against the real producer by //! `continuum-engine` `ai/openai_adapter/tests/a_ready_burst_*` and here by //! `a_stalled_agent_stops_a_ready_burst_at_one_chunk_ahead`. +//! - **The node stops:** `abandoned` ends an answer that is being read, with the reason. An +//! agent that stopped reading never polls this body again, so the stop also cuts its +//! connection (`crate::sever`): hyper drops the body and the generation with it. use std::collections::VecDeque; use std::future::Future; diff --git a/core/continuum-gateway/src/lib.rs b/core/continuum-gateway/src/lib.rs index 64bae5a977..555fbcde51 100644 --- a/core/continuum-gateway/src/lib.rs +++ b/core/continuum-gateway/src/lib.rs @@ -14,6 +14,7 @@ mod listener; mod module; mod route; mod server; +mod sever; mod session; mod wire; diff --git a/core/continuum-gateway/src/listener.rs b/core/continuum-gateway/src/listener.rs index f5ec097f84..fd6cd19389 100644 --- a/core/continuum-gateway/src/listener.rs +++ b/core/continuum-gateway/src/listener.rs @@ -1,6 +1,7 @@ //! The gateway's listener as a resource its module owns (CONCURRENCY-STYLE-GUIDE.md: owned //! tasks, nothing detached). `initialize` binds it or fails; `drain` closes admission and lets -//! the calls in flight finish; `shutdown` abandons whatever is still in flight and joins the +//! the calls in flight finish; `shutdown` abandons whatever is still in flight, cutting every +//! connection (`crate::sever`) so one whose agent stopped reading ends too, and joins the //! serve task. Codex on #5541 (856ee2b69): a detached `axum::serve` with its port kept in a //! `OnceLock` reported `listening` after the listener died, could not be stopped, and left a //! reinitialize colliding with the old socket. @@ -39,7 +40,8 @@ pub(crate) struct Listener { port: u16, /// Raised: axum stops accepting connections and lets the open ones finish. close: watch::Sender, - /// Raised: every answer still in flight is stopped (`crate::answer`). + /// Raised: every call still in flight is stopped (`crate::answer`, `crate::server`) and + /// every connection is cut (`crate::sever`), whether or not its agent is reading. abandon: watch::Sender, /// Raised by the serve task as it returns, for whoever waits on the drain. exited: Signal, @@ -47,9 +49,13 @@ pub(crate) struct Listener { } impl Listener { - /// Bind `port` on loopback (0: any free port) and serve the gateway on it. A port that + /// Bind `port` on loopback (0: any free port) and serve `routes` on it (the gateway's are + /// `crate::server::router`), each given the signal that abandons its calls. A port that /// cannot be bound is the error; there is no listener that only says it is one. - pub(crate) async fn bind(port: u16) -> Result { + pub(crate) async fn bind( + port: u16, + routes: impl FnOnce(Signal) -> axum::Router, + ) -> Result { let socket = tokio::net::TcpListener::bind(("127.0.0.1", port)) .await .map_err(|error| format!("the gateway cannot bind 127.0.0.1:{port}: {error}"))?; @@ -62,8 +68,13 @@ impl Listener { let (close, closed) = Signal::pair(); let (abandon, abandoned) = Signal::pair(); let (exit, exited) = Signal::pair(); + let connections = crate::sever::Severing { + socket, + cut: abandoned.clone(), + }; + let router = routes(abandoned); let serving = tokio::spawn(async move { - let outcome = axum::serve(socket, crate::server::router(abandoned)) + let outcome = axum::serve(connections, router) .with_graceful_shutdown(closed.raised()) .await; match outcome { @@ -101,7 +112,9 @@ impl Listener { self.close.send_replace(true); } - /// Stop every answer still in flight (the agent is told the node is stopping). + /// Stop every call still in flight and cut every connection. An answer being read is + /// told the node is stopping as its connection closes; one whose agent stopped reading is + /// cut all the same, dropping its generation, admission and capture lease. pub(crate) fn abandon(&self) { self.abandon.send_replace(true); } diff --git a/core/continuum-gateway/src/module.rs b/core/continuum-gateway/src/module.rs index 2967a0dfe9..4f55427aed 100644 --- a/core/continuum-gateway/src/module.rs +++ b/core/continuum-gateway/src/module.rs @@ -19,10 +19,14 @@ pub struct GatewayModule { } impl GatewayModule { - /// Bind `port` (0: any free port) and serve on it, returning the port bound. Refused while - /// a listener still serves; one that exited is joined first, so a reinitialize after a - /// stop or a failure binds cleanly. + /// Bind `port` (0: any free port) and serve the gateway on it, returning the port bound. async fn listen(&self, port: u16) -> Result { + self.listen_with(port, crate::server::router).await + } + + /// Bind `port` and serve `routes` on it. Refused while a listener still serves; one that + /// exited is joined first, so a reinitialize after a stop or a failure binds cleanly. + async fn listen_with(&self, port: u16, routes: impl FnOnce(crate::listener::Signal) -> axum::Router) -> Result { let mut slot = self.listener.lock().await; if let Some(live) = slot.as_ref().filter(|listener| listener.is_live()) { return Err(format!("the gateway is already listening on port {}", live.port())); @@ -30,7 +34,7 @@ impl GatewayModule { if let Some(ended) = slot.take() { ended.join().await?; } - let listener = Listener::bind(port).await.inspect_err(|error| { + let listener = Listener::bind(port, routes).await.inspect_err(|error| { continuum_base::probe!(class = "gateway.unbound", port = port as u64, error = %error, "the gateway could not bind its port; agents cannot reach this node until it does"); })?; @@ -115,9 +119,11 @@ impl ServiceModule for GatewayModule { Ok(0) } - /// Stop what is still in flight (its agents are told the node is stopping), wait for the - /// listener to return, and join it. Cancelled by the runtime's bound, the listener is - /// dropped, which aborts its task. + /// Stop what is still in flight and cut every connection, so even an agent that stopped + /// reading releases its generation, admission and capture lease (`crate::sever`); wait + /// for the listener to return, which axum does only once every connection task ended, + /// and join it. Cancelled by the runtime's bound, the listener is dropped, which aborts + /// its task. async fn shutdown(&self) -> Result<(), String> { let Some(listener) = self.listener.lock().await.take() else { return Ok(()); @@ -183,4 +189,96 @@ mod tests { assert_eq!(gateway.url().await, None, "an exited listener is not listening"); assert!(gateway.listen(0).await.is_ok(), "an exited listener is joined and a new one binds"); } + + /// Sets its flag when dropped: stands for the capture lease, which rides in the same + /// generation future and records the call when that future is dropped. + struct Settles(std::sync::Arc); + + impl Drop for Settles { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::SeqCst); + } + } + + // what this catches: an agent that stays CONNECTED but stops reading. Its socket fills, + // hyper stops polling the body, and a stop the body would notice is never noticed, so the + // generation it owns (its slot's admission, its capture lease) and the connection's task + // outlive the stop (Codex on f2a3600fe). Over real HTTP: a long streamed answer through + // the real `Answer` and SSE response, a client that never reads, then the module's drain + // and shutdown each under the runtime's own per-phase bound, as `Runtime::shutdown` runs + // them. + #[tokio::test] + async fn an_agent_that_stops_reading_is_cut_and_everything_it_held_settles_within_the_stop() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::Arc; + use tokio::io::AsyncWriteExt; + + use continuum_engine::ai::adapter::GenerationChunk; + use continuum_engine::ai::stream_sinks::deliver; + + let slots = Arc::new(tokio::sync::Semaphore::new(1)); + let settled = Arc::new(AtomicBool::new(false)); + let sent = Arc::new(AtomicUsize::new(0)); + let (held, recorded, counted) = (slots.clone(), settled.clone(), sent.clone()); + let routes = move |abandoned: crate::listener::Signal| { + axum::Router::new().route( + "/v1/long", + axum::routing::get(move || { + let (held, recorded, counted, abandoned) = (held.clone(), recorded.clone(), counted.clone(), abandoned.clone()); + async move { + let admission = held.try_acquire_owned().expect("test: one free slot"); + let (sink, received) = tokio::sync::mpsc::unbounded_channel(); + let generation = async move { + let _admission = admission; + let _lease = Settles(recorded); + let token = "x".repeat(64 * 1024); + for _ in 0..usize::MAX { + counted.fetch_add(1, Ordering::SeqCst); + deliver(&sink, GenerationChunk::Token(token.clone())).await; + } + Err(crate::route::RouteError::Engine("test: a decode longer than the test".into())) + }; + let encoder = ::streamer("qwen", "chatcmpl_1"); + crate::server::streamed(crate::answer::Answer::new(encoder, generation, received, abandoned.raised())) + } + }), + ) + }; + let gateway = GatewayModule::default(); + let port = gateway.listen_with(0, routes).await.expect("test: binds"); + let mut agent = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.expect("test: connects"); + agent + .write_all(b"GET /v1/long HTTP/1.1\r\nhost: 127.0.0.1\r\n\r\n") + .await + .expect("test: sends its request"); + // The agent never reads. Wait for the generation to stop advancing: both sockets full. + let mut last = 0; + let mut still = 0; + for _ in 0..400 { + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + let now = sent.load(Ordering::SeqCst); + still = if now == last && now > 1 { still + 1 } else { 0 }; + last = now; + if still == 4 { + break; + } + } + assert_eq!(still, 4, "test: the stream must stall against a client that does not read"); + assert_eq!(slots.available_permits(), 0, "the stalled generation holds its slot"); + assert!(!settled.load(Ordering::SeqCst)); + + let bound = continuum_engine::runtime::runtime::SHUTDOWN_PHASE; + let drained = tokio::time::timeout(bound, gateway.drain()).await; + assert!(drained.is_err(), "the agent is still connected: the drain runs to its bound"); + let stopped = tokio::time::timeout(bound, gateway.shutdown()).await; + assert!(matches!(stopped, Ok(Ok(()))), "the stop completes within its bound: {stopped:?}"); + assert_eq!(slots.available_permits(), 1, "the generation's admission was released before the stop returned"); + assert!(settled.load(Ordering::SeqCst), "its capture lease settled before the stop returned"); + assert_eq!( + tokio::runtime::Handle::current().metrics().num_alive_tasks(), + 0, + "no connection task survives the stop" + ); + drop(agent); + } } diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs index a502d08cc5..ad3c77a8a5 100644 --- a/core/continuum-gateway/src/server.rs +++ b/core/continuum-gateway/src/server.rs @@ -86,7 +86,11 @@ async fn serve(State(abandoned): State, headers: axum::http::He crate::session::settle(&mut lease, &outcome); outcome }; - let answer = crate::answer::Answer::new(W::streamer(&model, &id), generation, received, abandoned.raised()); + streamed(crate::answer::Answer::new(W::streamer(&model, &id), generation, received, abandoned.raised())) +} + +/// A streamed answer as the SSE response its body is. +pub(crate) fn streamed(answer: crate::answer::Answer) -> Response { let events = tokio_stream::StreamExt::map(answer, |frame| Ok::<_, std::convert::Infallible>(frame.into_event())); Sse::new(events).keep_alive(KeepAlive::default()).into_response() } diff --git a/core/continuum-gateway/src/sever.rs b/core/continuum-gateway/src/sever.rs new file mode 100644 index 0000000000..a5ffcc4668 --- /dev/null +++ b/core/continuum-gateway/src/sever.rs @@ -0,0 +1,134 @@ +//! Connections the gateway's module can cut. +//! +//! Codex on #5541 (f2a3600fe): an agent that stays connected but stops reading fills its +//! socket, hyper stops polling the response body, and a stop signal the body would read is +//! never read, so the generation it owns (the engine's `TurnAdmission`, the capture lease) +//! outlives the stop. Cancellation has to reach the connection without the agent reading. +//! +//! Every accepted socket is wrapped in [`Severable`]. When the module raises `cut`, the +//! connection's task is woken and every read and write it makes fails; hyper ends the +//! connection and drops the body with the generation inside it, the engine's one +//! cancellation path. axum's graceful serve returns only after every connection task has +//! ended (`close_tx.closed()` in `axum::serve`), so the listener's exit is the proof that no +//! connection, body or lease survives the stop. + +use std::future::Future; +use std::io; +use std::pin::Pin; +use std::task::{Context, Poll}; + +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::net::{TcpListener, TcpStream}; + +use crate::listener::Signal; + +/// The gateway's socket, whose every connection is cut when `cut` is raised. +pub(crate) struct Severing { + pub(crate) socket: TcpListener, + pub(crate) cut: Signal, +} + +impl axum::serve::Listener for Severing { + type Io = Severable; + type Addr = std::net::SocketAddr; + + async fn accept(&mut self) -> (Self::Io, Self::Addr) { + let (stream, addr) = axum::serve::Listener::accept(&mut self.socket).await; + let cut = Box::pin(self.cut.raised()); + ( + Severable { + stream, + cut, + severed: false, + }, + addr, + ) + } + + fn local_addr(&self) -> io::Result { + self.socket.local_addr() + } +} + +/// One agent's connection. Its `cut` is polled on every read and write, so the task that +/// owns the connection is woken when it is raised, however the agent behaves. +pub(crate) struct Severable { + stream: TcpStream, + /// Polled until it resolves, never after (`severed`). + cut: Pin + Send>>, + severed: bool, +} + +impl Severable { + /// Whether the module cut this connection; registers the task to be woken when it does. + fn severed(&mut self, cx: &mut Context<'_>) -> bool { + if !self.severed && self.cut.as_mut().poll(cx).is_ready() { + self.severed = true; + } + self.severed + } + + fn cut_error() -> io::Error { + io::Error::new(io::ErrorKind::ConnectionAborted, crate::server::STOPPING) + } +} + +impl AsyncRead for Severable { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if this.severed(cx) { + return Poll::Ready(Err(Self::cut_error())); + } + Pin::new(&mut this.stream).poll_read(cx, buf) + } +} + +impl AsyncWrite for Severable { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let this = self.get_mut(); + if this.severed(cx) { + return Poll::Ready(Err(Self::cut_error())); + } + Pin::new(&mut this.stream).poll_write(cx, buf) + } + + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[io::IoSlice<'_>], + ) -> Poll> { + let this = self.get_mut(); + if this.severed(cx) { + return Poll::Ready(Err(Self::cut_error())); + } + Pin::new(&mut this.stream).poll_write_vectored(cx, bufs) + } + + fn is_write_vectored(&self) -> bool { + self.stream.is_write_vectored() + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.severed(cx) { + return Poll::Ready(Err(Self::cut_error())); + } + Pin::new(&mut this.stream).poll_flush(cx) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.severed(cx) { + return Poll::Ready(Err(Self::cut_error())); + } + Pin::new(&mut this.stream).poll_shutdown(cx) + } +} From 9562f56807f06ee285aae2fa492d7ded3e74d76e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 20:10:06 -0500 Subject: [PATCH 24/27] The gateway's stop signal and words move to a bottom module, breaking the four-module cycle; the burst test counts events modules_in_cycles rose 26 -> 30 at 0a93607a8. The gateway's production graph had one strongly connected component {answer, server, listener, sever}: answer -> server -> answer (answer read server::STOPPING) listener -> sever -> listener (sever read listener::Signal) server -> listener -> sever -> server (server read Signal, sever read STOPPING) Signal and STOPPING are what the module says to everything it stops. They now live in stop.rs, which depends on no crate module. answer, sever, listener and server import them from there, and the graph is acyclic: answer -> {route, stop, wire}, sever -> {stop}, listener -> {sever, stop}, server -> {answer, route, session, stop, wire}, module -> {listener, route, server, stop}. The source guard read the burst test's `TOKENS = 64` as a context-size constant. It counts SSE events in the burst, so it is now BURST_EVENTS. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- ...reaches_the_consumer_one_chunk_per_poll.rs | 8 ++-- core/continuum-gateway/src/answer.rs | 4 +- core/continuum-gateway/src/lib.rs | 1 + core/continuum-gateway/src/listener.rs | 24 +----------- core/continuum-gateway/src/module.rs | 4 +- core/continuum-gateway/src/server.rs | 5 +-- core/continuum-gateway/src/sever.rs | 4 +- core/continuum-gateway/src/stop.rs | 37 +++++++++++++++++++ 8 files changed, 50 insertions(+), 37 deletions(-) create mode 100644 core/continuum-gateway/src/stop.rs diff --git a/core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs b/core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs index a59f94a416..08a259718c 100644 --- a/core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs +++ b/core/continuum-engine/src/ai/openai_adapter/tests/a_ready_burst_reaches_the_consumer_one_chunk_per_poll.rs @@ -15,9 +15,9 @@ use super::*; async fn a_ready_burst_reaches_the_consumer_one_chunk_per_poll() { use std::future::Future; use std::task::{Context, Poll}; - const TOKENS: usize = 64; + const BURST_EVENTS: usize = 64; let mut body = String::new(); - for i in 0..TOKENS { + for i in 0..BURST_EVENTS { body.push_str(&format!( "data: {}\n\n", serde_json::json!({"choices": [{"delta": {"content": format!("t{i}")}}]}) @@ -43,7 +43,7 @@ async fn a_ready_burst_reaches_the_consumer_one_chunk_per_poll() { let outcome = loop { polls += 1; assert!( - polls <= 10 * TOKENS, + polls <= 10 * BURST_EVENTS, "test: the in-memory stream must finish" ); let polled = generation.as_mut().poll(&mut cx); @@ -62,7 +62,7 @@ async fn a_ready_burst_reaches_the_consumer_one_chunk_per_poll() { } }; let outcome = outcome.expect("test: the stream completes"); // JUSTIFIED: the invariant under test - assert_eq!(tokens, TOKENS, "every token reached the consumer"); + assert_eq!(tokens, BURST_EVENTS, "every token reached the consumer"); assert!( outcome.acc_content.starts_with("t0t1") && outcome.acc_content.ends_with("t63"), "the answer is whole" diff --git a/core/continuum-gateway/src/answer.rs b/core/continuum-gateway/src/answer.rs index 30c5ff3c00..661f751462 100644 --- a/core/continuum-gateway/src/answer.rs +++ b/core/continuum-gateway/src/answer.rs @@ -126,7 +126,7 @@ impl tokio_stream::Stream for Answer { this.generation = None; this.encode_received(); this.encoded - .extend(this.encoder.failed(crate::server::STOPPING)); + .extend(this.encoder.failed(crate::stop::STOPPING)); continue; } let Some(generation) = this.generation.as_mut() else { @@ -347,7 +347,7 @@ mod tests { "stopped: the generation and its slot are gone" ); assert!( - closing.iter().any(|f| f.contains(crate::server::STOPPING)), + closing.iter().any(|f| f.contains(crate::stop::STOPPING)), "the agent is told why: {closing:?}" ); assert!(poll(&mut answer).is_ready(), "the answer ended"); diff --git a/core/continuum-gateway/src/lib.rs b/core/continuum-gateway/src/lib.rs index 555fbcde51..d0fc5dfc4f 100644 --- a/core/continuum-gateway/src/lib.rs +++ b/core/continuum-gateway/src/lib.rs @@ -16,6 +16,7 @@ mod route; mod server; mod sever; mod session; +mod stop; mod wire; pub use module::GatewayModule; diff --git a/core/continuum-gateway/src/listener.rs b/core/continuum-gateway/src/listener.rs index fd6cd19389..cd3bbd62ff 100644 --- a/core/continuum-gateway/src/listener.rs +++ b/core/continuum-gateway/src/listener.rs @@ -11,29 +11,7 @@ use std::future::Future; use tokio::sync::watch; use tokio::task::JoinHandle; -/// One raise-once signal from the module to what it governs. Its receiver resolves when the -/// module raises it, or when the module is gone (which ends what it guards all the same). -#[derive(Clone)] -pub(crate) struct Signal(watch::Receiver); - -impl Signal { - fn pair() -> (watch::Sender, Self) { - let (raise, raised) = watch::channel(false); - (raise, Self(raised)) - } - - /// Resolves once the signal is raised or its owner dropped it. - pub(crate) fn raised(&self) -> impl Future + Send + 'static { - let mut signal = self.0.clone(); - async move { - match signal.wait_for(|raised| *raised).await { - Ok(_) => {} - // The owner dropped its sender: the listener it governs is gone. - Err(_) => {} - } - } - } -} +use crate::stop::Signal; /// A bound listener and the task serving it. pub(crate) struct Listener { diff --git a/core/continuum-gateway/src/module.rs b/core/continuum-gateway/src/module.rs index 4f55427aed..2a426466ff 100644 --- a/core/continuum-gateway/src/module.rs +++ b/core/continuum-gateway/src/module.rs @@ -26,7 +26,7 @@ impl GatewayModule { /// Bind `port` and serve `routes` on it. Refused while a listener still serves; one that /// exited is joined first, so a reinitialize after a stop or a failure binds cleanly. - async fn listen_with(&self, port: u16, routes: impl FnOnce(crate::listener::Signal) -> axum::Router) -> Result { + async fn listen_with(&self, port: u16, routes: impl FnOnce(crate::stop::Signal) -> axum::Router) -> Result { let mut slot = self.listener.lock().await; if let Some(live) = slot.as_ref().filter(|listener| listener.is_live()) { return Err(format!("the gateway is already listening on port {}", live.port())); @@ -220,7 +220,7 @@ mod tests { let settled = Arc::new(AtomicBool::new(false)); let sent = Arc::new(AtomicUsize::new(0)); let (held, recorded, counted) = (slots.clone(), settled.clone(), sent.clone()); - let routes = move |abandoned: crate::listener::Signal| { + let routes = move |abandoned: crate::stop::Signal| { axum::Router::new().route( "/v1/long", axum::routing::get(move || { diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs index ad3c77a8a5..7e53ce2410 100644 --- a/core/continuum-gateway/src/server.rs +++ b/core/continuum-gateway/src/server.rs @@ -1,6 +1,6 @@ //! The one HTTP server: every format's route through the same handler. -use crate::listener::Signal; +use crate::stop::{Signal, STOPPING}; use crate::route::{self, RouteError}; use crate::wire::{anthropic::Anthropic, chat::Chat, responses::Responses, BadRequest, ErrorKind, Wire}; use axum::extract::State; @@ -23,9 +23,6 @@ pub(crate) fn router(abandoned: Signal) -> Router { .with_state(abandoned) } -/// What an agent whose call was in flight is told when the node stops. -pub(crate) const STOPPING: &str = "this node's gateway is stopping; the call was stopped before it finished"; - /// `GET /v1/models`: what this node serves, in the shape every format's clients read. async fn models() -> Json { let data: Vec = route::served_models() diff --git a/core/continuum-gateway/src/sever.rs b/core/continuum-gateway/src/sever.rs index a5ffcc4668..7921d81d3c 100644 --- a/core/continuum-gateway/src/sever.rs +++ b/core/continuum-gateway/src/sever.rs @@ -20,7 +20,7 @@ use std::task::{Context, Poll}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::net::{TcpListener, TcpStream}; -use crate::listener::Signal; +use crate::stop::Signal; /// The gateway's socket, whose every connection is cut when `cut` is raised. pub(crate) struct Severing { @@ -69,7 +69,7 @@ impl Severable { } fn cut_error() -> io::Error { - io::Error::new(io::ErrorKind::ConnectionAborted, crate::server::STOPPING) + io::Error::new(io::ErrorKind::ConnectionAborted, crate::stop::STOPPING) } } diff --git a/core/continuum-gateway/src/stop.rs b/core/continuum-gateway/src/stop.rs new file mode 100644 index 0000000000..398f72f7dc --- /dev/null +++ b/core/continuum-gateway/src/stop.rs @@ -0,0 +1,37 @@ +//! What the gateway's module says to everything it stops: the raise-once signal it governs +//! its listener, connections and calls with, and the words an agent is told. The bottom of +//! the crate's module graph: `answer`, `sever`, `listener` and `server` all depend on it, and +//! it on none of them. + +use std::future::Future; + +use tokio::sync::watch; + +/// What an agent whose call was in flight is told when the node stops. +pub(crate) const STOPPING: &str = + "this node's gateway is stopping; the call was stopped before it finished"; + +/// One raise-once signal from the module to what it governs. Its receiver resolves when the +/// module raises it, or when the module is gone (which ends what it guards all the same). +#[derive(Clone)] +pub(crate) struct Signal(watch::Receiver); + +impl Signal { + /// The sender the owner raises, and the signal it governs. + pub(crate) fn pair() -> (watch::Sender, Self) { + let (raise, raised) = watch::channel(false); + (raise, Self(raised)) + } + + /// Resolves once the signal is raised or its owner dropped it. + pub(crate) fn raised(&self) -> impl Future + Send + 'static { + let mut signal = self.0.clone(); + async move { + match signal.wait_for(|raised| *raised).await { + Ok(_) => {} + // The owner dropped its sender: the listener it governs is gone. + Err(_) => {} + } + } + } +} From e9cf9a26729c5ddeab2c2de663c86e94b3b0a785 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 09:24:40 -0600 Subject: [PATCH 25/27] The gateway presents only a finish the engine reported: an engine error or a stream with no finish reason fails the call, never `end_turn` / `stop` Canary's `FinishReason::Unreported` (#5638) says a stream ended without the backend saying why; the gateway's `stop_reason` / `finish_reason` mapped it (and `Error`) to `end_turn` / `stop`, the false stop #5638 removed (the triage of this PR against canary, 11-03). A typed `Finish { Stop, Length, ToolUse }` is now the only ending an encoder's `answer` / `finished` takes, built once by `Finish::reported`; `Error` and `Unreported` take the failed path (a streamed `failed`, or 502 with the engine's kind). Each format maps `Finish` exhaustively. Test: neither is a finish, and Stop / Length map to each format's own word. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-gateway/src/answer.rs | 5 ++- core/continuum-gateway/src/server.rs | 5 ++- core/continuum-gateway/src/wire/anthropic.rs | 22 ++++++------- core/continuum-gateway/src/wire/chat.rs | 22 ++++++------- core/continuum-gateway/src/wire/mod.rs | 34 +++++++++++++++++--- core/continuum-gateway/src/wire/responses.rs | 16 ++++----- core/continuum-gateway/src/wire/tests.rs | 29 ++++++++++++++--- 7 files changed, 90 insertions(+), 43 deletions(-) diff --git a/core/continuum-gateway/src/answer.rs b/core/continuum-gateway/src/answer.rs index 661f751462..82b6b8fe34 100644 --- a/core/continuum-gateway/src/answer.rs +++ b/core/continuum-gateway/src/answer.rs @@ -93,7 +93,10 @@ impl Answer { /// The frames that close an answer the generation returned. fn closing(&mut self, outcome: Result) -> Vec { match outcome { - Ok(response) => self.encoder.finished(&response), + Ok(response) => match crate::wire::Finish::reported(&response) { + Ok(finish) => self.encoder.finished(&response, finish), + Err(why) => self.encoder.failed(&why), + }, Err(RouteError::Engine(why)) => self.encoder.failed(&why), Err(RouteError::UnknownModel { model, .. }) => self .encoder diff --git a/core/continuum-gateway/src/server.rs b/core/continuum-gateway/src/server.rs index 7e53ce2410..51be252cf7 100644 --- a/core/continuum-gateway/src/server.rs +++ b/core/continuum-gateway/src/server.rs @@ -72,7 +72,10 @@ async fn serve(State(abandoned): State, headers: axum::http::He }; crate::session::settle(&mut lease, &outcome); return match outcome { - Ok(response) => Json(W::answer(&response, &id)).into_response(), + Ok(response) => match crate::wire::Finish::reported(&response) { + Ok(finish) => Json(W::answer(&response, finish, &id)).into_response(), + Err(why) => refuse::(StatusCode::BAD_GATEWAY, ErrorKind::Engine, &why), + }, Err(error) => refused::(error), }; } diff --git a/core/continuum-gateway/src/wire/anthropic.rs b/core/continuum-gateway/src/wire/anthropic.rs index d722e562b0..6defca0540 100644 --- a/core/continuum-gateway/src/wire/anthropic.rs +++ b/core/continuum-gateway/src/wire/anthropic.rs @@ -1,6 +1,6 @@ //! Anthropic Messages (`POST /v1/messages`): Claude Code, via `ANTHROPIC_BASE_URL`. -use super::{decode, event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{decode, event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Finish, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::types::ImageInput; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; @@ -46,7 +46,7 @@ impl Wire for Anthropic { Ok(Call { request, stream: decode::streamed(&body)? }) } - fn answer(response: &TextGenerationResponse, id: &str) -> Value { + fn answer(response: &TextGenerationResponse, finish: Finish, id: &str) -> Value { let mut content = Vec::new(); if let Some(reasoning) = response.reasoning.as_deref().filter(|r| !r.is_empty()) { content.push(json!({"type": "thinking", "thinking": reasoning, "signature": ""})); @@ -60,7 +60,7 @@ impl Wire for Anthropic { json!({ "id": id, "type": "message", "role": "assistant", "model": response.model, "content": content, - "stop_reason": stop_reason(response), "stop_sequence": null, + "stop_reason": stop_reason(response, finish), "stop_sequence": null, "usage": usage(response), }) } @@ -99,7 +99,7 @@ impl Wire for Anthropic { events } - fn finished(&mut self, response: &TextGenerationResponse) -> Vec { + fn finished(&mut self, response: &TextGenerationResponse, finish: Finish) -> Vec { let mut events = self.close(); for (call_id, name, input) in tool_calls(response) { let index = self.next_index(); @@ -110,7 +110,7 @@ impl Wire for Anthropic { events.push(event(Some("content_block_stop"), &json!({"type": "content_block_stop", "index": index}))); } events.push(event(Some("message_delta"), &json!({"type": "message_delta", - "delta": {"stop_reason": stop_reason(response), "stop_sequence": null}, + "delta": {"stop_reason": stop_reason(response, finish), "stop_sequence": null}, "usage": usage(response)}))); events.push(event(Some("message_stop"), &json!({"type": "message_stop"}))); events @@ -163,13 +163,11 @@ fn usage(response: &TextGenerationResponse) -> Value { "cache_read_input_tokens": cached}) } -fn stop_reason(response: &TextGenerationResponse) -> &'static str { - if stopped_for_tools(response) { - "tool_use" - } else if response.finish_reason == continuum_engine::ai::FinishReason::Length { - "max_tokens" - } else { - "end_turn" +fn stop_reason(response: &TextGenerationResponse, finish: Finish) -> &'static str { + match finish { + _ if stopped_for_tools(response, finish) => "tool_use", + Finish::Length => "max_tokens", + Finish::Stop | Finish::ToolUse => "end_turn", } } diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs index 50d661508a..d7542d3e74 100644 --- a/core/continuum-gateway/src/wire/chat.rs +++ b/core/continuum-gateway/src/wire/chat.rs @@ -1,7 +1,7 @@ //! OpenAI Chat Completions (`POST /v1/chat/completions`): Hermes, opencode, and most agents. use super::decode::{self, present}; -use super::{event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Finish, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::types::ImageInput; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; @@ -38,7 +38,7 @@ impl Wire for Chat { Ok(Call { request, stream: decode::streamed(&body)? }) } - fn answer(response: &TextGenerationResponse, id: &str) -> Value { + fn answer(response: &TextGenerationResponse, finish: Finish, id: &str) -> Value { let mut message = json!({"role": "assistant", "content": if response.text.is_empty() { Value::Null } else { json!(response.text) }}); if let Some(reasoning) = response.reasoning.as_deref().filter(|r| !r.is_empty()) { message["reasoning_content"] = json!(reasoning); @@ -49,7 +49,7 @@ impl Wire for Chat { } json!({ "id": id, "object": "chat.completion", "created": continuum_base::time::EpochMs::now().secs(), "model": response.model, - "choices": [{"index": 0, "message": message, "finish_reason": finish_reason(response)}], + "choices": [{"index": 0, "message": message, "finish_reason": finish_reason(response, finish)}], "usage": usage(response), }) } @@ -80,7 +80,7 @@ impl Wire for Chat { } } - fn finished(&mut self, response: &TextGenerationResponse) -> Vec { + fn finished(&mut self, response: &TextGenerationResponse, finish: Finish) -> Vec { let mut events = Vec::new(); let calls: Vec = tool_calls(response) .iter() @@ -94,7 +94,7 @@ impl Wire for Chat { if !calls.is_empty() { events.push(self.delta(json!({"tool_calls": calls}), Value::Null)); } - events.push(self.delta(json!({}), json!(finish_reason(response)))); + events.push(self.delta(json!({}), json!(finish_reason(response, finish)))); events.push(event(None, &json!({"id": self.id, "object": "chat.completion.chunk", "created": self.created, "model": self.model, "choices": [], "usage": usage(response)}))); events.push(Frame::done()); @@ -113,13 +113,11 @@ impl Chat { } } -fn finish_reason(response: &TextGenerationResponse) -> &'static str { - if stopped_for_tools(response) { - "tool_calls" - } else if response.finish_reason == continuum_engine::ai::FinishReason::Length { - "length" - } else { - "stop" +fn finish_reason(response: &TextGenerationResponse, finish: Finish) -> &'static str { + match finish { + _ if stopped_for_tools(response, finish) => "tool_calls", + Finish::Length => "length", + Finish::Stop | Finish::ToolUse => "stop", } } diff --git a/core/continuum-gateway/src/wire/mod.rs b/core/continuum-gateway/src/wire/mod.rs index 9d4bd7e43d..d5cb715932 100644 --- a/core/continuum-gateway/src/wire/mod.rs +++ b/core/continuum-gateway/src/wire/mod.rs @@ -30,7 +30,7 @@ pub(crate) trait Wire: Send + Unpin + 'static { const NAME: &'static str; fn decode(body: Value) -> Result; /// The whole answer, for a call that did not ask to stream. - fn answer(response: &TextGenerationResponse, id: &str) -> Value; + fn answer(response: &TextGenerationResponse, finish: Finish, id: &str) -> Value; /// The body of a refusal, in the format's own error shape. fn error(kind: ErrorKind, message: &str) -> Value; /// A new encoder for one streamed answer. @@ -39,7 +39,7 @@ pub(crate) trait Wire: Send + Unpin + 'static { fn opened(&mut self) -> Vec; fn chunk(&mut self, chunk: &GenerationChunk) -> Vec; /// What closes a completed answer: its tool calls, stop reason and usage. - fn finished(&mut self, response: &TextGenerationResponse) -> Vec; + fn finished(&mut self, response: &TextGenerationResponse, finish: Finish) -> Vec; /// What closes an answer the engine failed mid-stream. fn failed(&mut self, message: &str) -> Vec; } @@ -97,9 +97,35 @@ pub(crate) fn tool_calls(response: &TextGenerationResponse) -> Vec<(String, Stri .collect() } +/// How an answer the engine finished ended: the only endings an answer may claim. An engine +/// error or a stream that ended without a finish reason is not one (#5638: an absent marker +/// read as a stop made reasoning-only completions look answered), so it never reaches an +/// encoder's `answer`/`finished`; the call fails with why. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Finish { + Stop, + Length, + ToolUse, +} + +impl Finish { + /// The finish the engine reported, or why the response is not a finished answer. + pub(crate) fn reported(response: &TextGenerationResponse) -> Result { + match response.finish_reason { + FinishReason::Stop => Ok(Self::Stop), + FinishReason::Length => Ok(Self::Length), + FinishReason::ToolUse => Ok(Self::ToolUse), + FinishReason::Error => Err("the engine reported an error finishing this answer".into()), + FinishReason::Unreported => { + Err("the engine ended this answer without reporting why (no finish reason), so it is not presented as finished".into()) + } + } + } +} + /// Whether the answer stopped to call tools. -pub(crate) fn stopped_for_tools(response: &TextGenerationResponse) -> bool { - response.finish_reason == FinishReason::ToolUse || !tool_calls(response).is_empty() +pub(crate) fn stopped_for_tools(response: &TextGenerationResponse, finish: Finish) -> bool { + finish == Finish::ToolUse || !tool_calls(response).is_empty() } /// A text field that is a string, or an array of `{type: "text", text}` blocks. diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs index a9b8de4021..64806e5cd4 100644 --- a/core/continuum-gateway/src/wire/responses.rs +++ b/core/continuum-gateway/src/wire/responses.rs @@ -4,7 +4,7 @@ //! mind's memory, which arrives with session identity (DRIVER-GATEWAY.md G2); until then a //! call that names one is refused rather than answered without its history. -use super::{chat, decode, event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Frame, Wire}; +use super::{chat, decode, event, place_system, stopped_for_tools, text_of, tool_calls, BadRequest, Call, ErrorKind, Finish, Frame, Wire}; use continuum_engine::ai::adapter::GenerationChunk; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse}; use serde_json::{json, Value}; @@ -48,8 +48,8 @@ impl Wire for Responses { Ok(Call { request, stream: decode::streamed(&body)? }) } - fn answer(response: &TextGenerationResponse, id: &str) -> Value { - envelope(id, &response.model, continuum_base::time::EpochMs::now().secs(), "completed", output(response, id), Some(response)) + fn answer(response: &TextGenerationResponse, finish: Finish, id: &str) -> Value { + envelope(id, &response.model, continuum_base::time::EpochMs::now().secs(), "completed", output(response, id), Some((response, finish))) } fn error(kind: ErrorKind, message: &str) -> Value { @@ -90,7 +90,7 @@ impl Wire for Responses { events } - fn finished(&mut self, response: &TextGenerationResponse) -> Vec { + fn finished(&mut self, response: &TextGenerationResponse, finish: Finish) -> Vec { let mut events = Vec::new(); let mut index = 0; if let Some(text) = self.text.take() { @@ -113,7 +113,7 @@ impl Wire for Responses { events.push(self.emit("response.output_item.done", json!({"output_index": index, "item": item}))); index += 1; } - let response = envelope(&self.id, &self.model, self.created, "completed", output(response, &self.id), Some(response)); + let response = envelope(&self.id, &self.model, self.created, "completed", output(response, &self.id), Some((response, finish))); events.push(self.emit("response.completed", json!({"response": response}))); events } @@ -142,14 +142,14 @@ fn message_id(response_id: &str) -> String { format!("msg_{}", response_id.trim_start_matches("resp_")) } -fn envelope(id: &str, model: &str, created: u64, status: &str, output: Vec, response: Option<&TextGenerationResponse>) -> Value { +fn envelope(id: &str, model: &str, created: u64, status: &str, output: Vec, response: Option<(&TextGenerationResponse, Finish)>) -> Value { json!({ "id": id, "object": "response", "created_at": created, "status": status, "model": model, "output": output, - "usage": response.map(|r| json!({"input_tokens": r.usage.input_tokens, "output_tokens": r.usage.output_tokens, + "usage": response.map(|(r, _)| json!({"input_tokens": r.usage.input_tokens, "output_tokens": r.usage.output_tokens, "total_tokens": r.usage.input_tokens + r.usage.output_tokens, "input_tokens_details": {"cached_tokens": super::cached_tokens(r).unwrap_or(0)}})), // unwrap_or: no measured reuse reads as none - "incomplete_details": response.filter(|r| r.finish_reason == continuum_engine::ai::FinishReason::Length && !stopped_for_tools(r)) + "incomplete_details": response.filter(|&(r, finish)| finish == Finish::Length && !stopped_for_tools(r, finish)) .map(|_| json!({"reason": "max_output_tokens"})), }) } diff --git a/core/continuum-gateway/src/wire/tests.rs b/core/continuum-gateway/src/wire/tests.rs index eb0831d7fa..61b30a2e92 100644 --- a/core/continuum-gateway/src/wire/tests.rs +++ b/core/continuum-gateway/src/wire/tests.rs @@ -62,7 +62,7 @@ fn anthropic_carries_tools_both_ways_and_streams_blocks_in_order() { assert!(matches!(&parts(&call.request.messages[2])[0], ContentPart::ToolUse { id, .. } if id == "call_0")); assert!(matches!(&parts(&call.request.messages[3])[0], ContentPart::ToolResult { content, .. } if content == "fn b() {}")); - let whole = Anthropic::answer(&tool_answer(), "msg_1"); + let whole = Anthropic::answer(&tool_answer(), Finish::ToolUse, "msg_1"); assert_eq!(whole["stop_reason"], "tool_use"); assert_eq!(whole["content"][1]["id"], "call_1"); @@ -71,7 +71,7 @@ fn anthropic_carries_tools_both_ways_and_streams_blocks_in_order() { frames.extend(s.chunk(&GenerationChunk::Reasoning("hmm".into()))); frames.extend(s.chunk(&GenerationChunk::Token("Reading".into()))); frames.extend(s.chunk(&GenerationChunk::Token(" it.".into()))); - frames.extend(s.finished(&tool_answer())); + frames.extend(s.finished(&tool_answer(), Finish::ToolUse)); let names: Vec<_> = frames.iter().map(|f| f.name.clone().expect("test: named")).collect(); assert_eq!(names, [ "message_start", @@ -108,14 +108,14 @@ fn chat_completions_keeps_one_leading_system_and_ends_its_stream() { assert_eq!(call.request.messages[3].role, "user", "a later system message is not sent as system"); assert!(matches!(&call.request.tool_choice, Some(ToolChoice::Mode(m)) if m == "any")); - let whole = Chat::answer(&tool_answer(), "chatcmpl_1"); + let whole = Chat::answer(&tool_answer(), Finish::ToolUse, "chatcmpl_1"); assert_eq!(whole["choices"][0]["finish_reason"], "tool_calls"); assert_eq!(whole["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"], "{\"path\":\"a.rs\"}"); let mut s = Chat::streamer("qwen", "chatcmpl_1"); let mut frames = s.opened(); frames.extend(s.chunk(&GenerationChunk::Token("Reading it.".into()))); - frames.extend(s.finished(&tool_answer())); + frames.extend(s.finished(&tool_answer(), Finish::ToolUse)); assert_eq!(frames.last(), Some(&Frame::done())); assert_eq!(frames[2].json()["choices"][0]["delta"]["tool_calls"][0]["index"], 0); assert_eq!(frames[3].json()["choices"][0]["finish_reason"], "tool_calls"); @@ -153,7 +153,7 @@ fn responses_groups_items_refuses_missing_state_and_numbers_its_events() { let mut frames = s.opened(); frames.extend(s.chunk(&GenerationChunk::Token("Reading".into()))); frames.extend(s.chunk(&GenerationChunk::Token(" it.".into()))); - frames.extend(s.finished(&tool_answer())); + frames.extend(s.finished(&tool_answer(), Finish::ToolUse)); let sequence: Vec = frames.iter().map(|f| f.json()["sequence_number"].as_u64().expect("test: numbered")).collect(); assert_eq!(sequence, (0..frames.len() as u64).collect::>()); let last = frames.last().expect("test: frames").json(); @@ -248,3 +248,22 @@ fn malformed_sampling_refuses_the_call() { let call = Chat::decode(json!({"model": "qwen", "stop": ["END", "STOP"], "messages": [{"role": "user", "content": "go"}]})); assert_eq!(call.expect("test: decodes").request.stop_sequences, Some(vec!["END".to_string(), "STOP".to_string()])); } + +// what this catches (#5638 on the gateway): a stream that ended without a finish reason, or an +// engine error, presented to an agent as a finished answer (`end_turn` / `stop`). Neither is a +// finish: the call fails with why, and only reported finishes map to a wire stop. +#[test] +fn only_a_finish_the_engine_reported_is_an_answer() { + let with = |finish_reason| TextGenerationResponse { finish_reason, tool_calls: None, ..tool_answer() }; + assert!(Finish::reported(&with(FinishReason::Unreported)).is_err(), "no finish reason is not a stop"); + assert!(Finish::reported(&with(FinishReason::Error)).is_err(), "an engine error is not a stop"); + for (reason, finish, chat, anthropic) in [ + (FinishReason::Stop, Finish::Stop, "stop", "end_turn"), + (FinishReason::Length, Finish::Length, "length", "max_tokens"), + ] { + let response = with(reason); + assert_eq!(Finish::reported(&response), Ok(finish)); + assert_eq!(Chat::answer(&response, finish, "c")["choices"][0]["finish_reason"], chat); + assert_eq!(Anthropic::answer(&response, finish, "m")["stop_reason"], anthropic); + } +} From ec1ba319338fd43c02770613fc37cec18678c0b6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 10:11:55 -0600 Subject: [PATCH 26/27] Cargo.lock: continuum-gateway depends on continuum-capture (the lock the rebase left unstaged) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 2521a606a2..9c29d4b0ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3214,6 +3214,7 @@ dependencies = [ "async-trait", "axum", "continuum-base", + "continuum-capture", "continuum-engine", "serde", "serde_json", From c896a22a43f24b439bbd6a8c2e8e269f7ca3f799 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 10:36:11 -0600 Subject: [PATCH 27/27] Driver gateway meets the ratchets: required request fields decoded by type, no re-imposed temperature ceilings, DRIVER_PURPOSE beside the one purpose->class map - decode::fields deserializes each wire's Required struct (model, messages, max_tokens as NonZeroU32, Responses' input as Text | Items): a missing field fails in serde, never a hand-written presence check (required_input_complaints 82 -> 76, its base). - temperature: any non-negative value the engine's f32 sampler holds; the engine owns what it can sample, so ANTHROPIC/OPENAI_TEMPERATURE_MAX are gone (self_sized in touched files -> 0). - DRIVER_PURPOSE moves from request_body.rs (left untouched with its reasoning budgets) into citizen_slots.rs beside the map that classifies it; one clippy nonminimal_bool fixed there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/inference/request_body.rs | 3 -- .../src/inference/slots/citizen_slots.rs | 8 +++-- core/continuum-gateway/src/wire/anthropic.rs | 24 +++++++++----- core/continuum-gateway/src/wire/chat.rs | 22 ++++++++----- core/continuum-gateway/src/wire/decode.rs | 17 +++++++--- core/continuum-gateway/src/wire/responses.rs | 33 ++++++++++++++----- 6 files changed, 72 insertions(+), 35 deletions(-) diff --git a/core/continuum-engine/src/inference/request_body.rs b/core/continuum-engine/src/inference/request_body.rs index e0eeb409af..b7ee12cb73 100644 --- a/core/continuum-engine/src/inference/request_body.rs +++ b/core/continuum-engine/src/inference/request_body.rs @@ -50,9 +50,6 @@ pub const DELIBERATION_PURPOSE: &str = "cognition/deliberation"; /// beside the living one. The same reasoning budgets as [`ACT_PURPOSE`] and /// [`DELIBERATION_PURPOSE`]; only the page differs: a fork warms its own page per room, /// never the mind's one page (`slots::PageKey::Fork`), and never waits on her act gate. -/// An external agent's call through the driver gateway: a Turn of its session's mind, so the -/// session keeps a warm, paged page exactly as a resident does (DRIVER-GATEWAY.md G2). -pub const DRIVER_PURPOSE: &str = "driver"; pub const FORK_ACT_PURPOSE: &str = "cognition/fork-act"; pub const FORK_DELIBERATION_PURPOSE: &str = "cognition/fork-deliberation"; diff --git a/core/continuum-engine/src/inference/slots/citizen_slots.rs b/core/continuum-engine/src/inference/slots/citizen_slots.rs index 2eed3bb500..3d3475c7a4 100644 --- a/core/continuum-engine/src/inference/slots/citizen_slots.rs +++ b/core/continuum-engine/src/inference/slots/citizen_slots.rs @@ -57,6 +57,10 @@ impl SlotClass { } } +/// An external agent's call through the driver gateway: a Turn of its session's mind, so the +/// session keeps a warm, paged page exactly as a resident does (DRIVER-GATEWAY.md G2). +pub const DRIVER_PURPOSE: &str = "driver"; + /// The ONE purpose→class map. Unknown purposes default to `Background` — /// scratch placement — so a new producer can never clobber a citizen slot by /// omission; promoting it to `Turn` is an explicit edit here. @@ -66,7 +70,7 @@ pub fn class_for(purpose: Option<&str>) -> SlotClass { | Some("cognition/act") | Some("persona-respond") | Some("persona_decide_and_respond") - | Some(crate::inference::request_body::DRIVER_PURPOSE) => SlotClass::Turn, + | Some(DRIVER_PURPOSE) => SlotClass::Turn, Some("cognition/should-respond") | Some("cognition/generate-response") | Some("cognition/validate-response-decision") @@ -290,7 +294,7 @@ pub(super) fn pages_in(dir: &std::path::Path) -> Result, + #[serde(flatten)] + rest: serde_json::Map, +} /// One streamed answer: the open content block with its index, and the next index. pub(crate) struct Anthropic { @@ -27,21 +34,20 @@ impl Wire for Anthropic { const NAME: &'static str = "anthropic_messages"; fn decode(body: Value) -> Result { - let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; - let max_tokens = decode::token_limit(&body, &["max_tokens"])?.ok_or_else(|| BadRequest("`max_tokens` is required".into()))?; - let messages = body.get("messages").and_then(Value::as_array).ok_or_else(|| BadRequest("`messages` is required".into()))?; + let Required { model, max_tokens, messages, rest } = decode::fields(body)?; + let body = Value::Object(rest); let mut request = TextGenerationRequest { - model: Some(model.to_owned()), - max_tokens: Some(max_tokens), + model: Some(model), + max_tokens: Some(max_tokens.get()), top_k: decode::count(&body, "top_k", 0)?, system_prompt: body.get("system").map(text_of).filter(|s| !s.is_empty()), messages: messages.iter().map(message).collect::>()?, tools: decode::tools(&body, tool)?, tool_choice: tool_choice(&body)?, - purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), + purpose: Some(continuum_engine::inference::slots::DRIVER_PURPOSE.into()), ..Default::default() }; - decode::sampling(&body, &mut request, ANTHROPIC_TEMPERATURE_MAX)?; + decode::sampling(&body, &mut request)?; (request.system_prompt, request.messages) = place_system(request.system_prompt.take(), std::mem::take(&mut request.messages)); Ok(Call { request, stream: decode::streamed(&body)? }) } diff --git a/core/continuum-gateway/src/wire/chat.rs b/core/continuum-gateway/src/wire/chat.rs index d7542d3e74..ee32ed745e 100644 --- a/core/continuum-gateway/src/wire/chat.rs +++ b/core/continuum-gateway/src/wire/chat.rs @@ -7,8 +7,14 @@ use continuum_engine::ai::types::ImageInput; use continuum_engine::ai::{ChatMessage, ContentPart, MessageContent, NativeToolSpec, TextGenerationRequest, TextGenerationResponse, ToolChoice}; use serde_json::{json, Value}; -/// OpenAI's documented ceiling for `temperature` (Chat Completions and Responses alike). -pub(super) const OPENAI_TEMPERATURE_MAX: f64 = 2.0; +/// A Chat Completions request's required fields; everything else stays in `rest`. +#[derive(serde::Deserialize)] +struct Required { + model: String, + messages: Vec, + #[serde(flatten)] + rest: serde_json::Map, +} /// One streamed answer. pub(crate) struct Chat { @@ -21,20 +27,20 @@ impl Wire for Chat { const NAME: &'static str = "openai_chat"; fn decode(body: Value) -> Result { - let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; - let messages = body.get("messages").and_then(Value::as_array).ok_or_else(|| BadRequest("`messages` is required".into()))?; - let (system_prompt, messages) = place_system(None, conversation(messages)?); + let Required { model, messages, rest } = decode::fields(body)?; + let body = Value::Object(rest); + let (system_prompt, messages) = place_system(None, conversation(&messages)?); let mut request = TextGenerationRequest { - model: Some(model.to_owned()), + model: Some(model), max_tokens: decode::token_limit(&body, &["max_completion_tokens", "max_tokens"])?, system_prompt, messages, tools: decode::tools(&body, tool)?, tool_choice: tool_choice(&body)?, - purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), + purpose: Some(continuum_engine::inference::slots::DRIVER_PURPOSE.into()), ..Default::default() }; - decode::sampling(&body, &mut request, OPENAI_TEMPERATURE_MAX)?; + decode::sampling(&body, &mut request)?; Ok(Call { request, stream: decode::streamed(&body)? }) } diff --git a/core/continuum-gateway/src/wire/decode.rs b/core/continuum-gateway/src/wire/decode.rs index 8a12aaa40c..55c9a6f7c4 100644 --- a/core/continuum-gateway/src/wire/decode.rs +++ b/core/continuum-gateway/src/wire/decode.rs @@ -93,15 +93,22 @@ fn real( Ok(Some(number as f32)) } -/// The sampling fields every format names the same way: temperature (whose ceiling is the -/// format's: 2 for OpenAI, 1 for Anthropic), top_p, and the stop sequences under `stop` or -/// `stop_sequences`, one string or an array of strings. +/// A request's required fields, decoded by their type: a body without them fails here with +/// serde's own `missing field` error, never a hand-written presence check. `rest` is every +/// other field, read by the optional decoders below. +pub(crate) fn fields(body: Value) -> Result { + serde_json::from_value(body).map_err(|error| BadRequest(error.to_string())) +} + +/// The sampling fields every format names the same way: temperature (any non-negative value the +/// engine's sampler holds; the engine owns what it can sample, so no format's documented ceiling +/// is re-imposed here), top_p, and the stop sequences under `stop` or `stop_sequences`, one string +/// or an array of strings. pub(crate) fn sampling( body: &Value, request: &mut TextGenerationRequest, - temperature_max: f64, ) -> Result<(), BadRequest> { - request.temperature = real(body, "temperature", 0.0..=temperature_max)?; + request.temperature = real(body, "temperature", 0.0..=f64::from(f32::MAX))?; request.top_p = real(body, "top_p", 0.0..=1.0)?; let key = if present(body, "stop").is_some() { "stop" diff --git a/core/continuum-gateway/src/wire/responses.rs b/core/continuum-gateway/src/wire/responses.rs index 64806e5cd4..69cd4d45ba 100644 --- a/core/continuum-gateway/src/wire/responses.rs +++ b/core/continuum-gateway/src/wire/responses.rs @@ -18,32 +18,49 @@ pub(crate) struct Responses { text: Option, } +/// A Responses request's required fields; everything else stays in `rest`. +#[derive(serde::Deserialize)] +struct Required { + model: String, + input: Input, + #[serde(flatten)] + rest: serde_json::Map, +} + +/// `input`: one user text, or a list of items. +#[derive(serde::Deserialize)] +#[serde(untagged)] +enum Input { + Text(String), + Items(Vec), +} + impl Wire for Responses { const NAME: &'static str = "openai_responses"; fn decode(body: Value) -> Result { - let model = body.get("model").and_then(Value::as_str).ok_or_else(|| BadRequest("`model` is required".into()))?; + let Required { model, input, rest } = decode::fields(body)?; + let body = Value::Object(rest); if body.get("previous_response_id").is_some_and(|v| !v.is_null()) { return Err(BadRequest( "`previous_response_id` needs server-side session memory, which this gateway does not keep yet; send the full `input` with `store: false`".into(), )); } - let messages = match body.get("input") { - Some(Value::String(text)) => vec![ChatMessage { role: "user".into(), content: MessageContent::Text(text.clone()), name: None }], - Some(Value::Array(items)) => items_to_messages(items)?, - _ => return Err(BadRequest("`input` is required".into())), + let messages = match input { + Input::Text(text) => vec![ChatMessage { role: "user".into(), content: MessageContent::Text(text), name: None }], + Input::Items(items) => items_to_messages(&items)?, }; let mut request = TextGenerationRequest { - model: Some(model.to_owned()), + model: Some(model), max_tokens: decode::token_limit(&body, &["max_output_tokens"])?, system_prompt: instructions(&body)?, messages, tools: decode::tools(&body, tool)?, tool_choice: chat::tool_choice(&body)?, - purpose: Some(continuum_engine::inference::request_body::DRIVER_PURPOSE.into()), + purpose: Some(continuum_engine::inference::slots::DRIVER_PURPOSE.into()), ..Default::default() }; - decode::sampling(&body, &mut request, chat::OPENAI_TEMPERATURE_MAX)?; + decode::sampling(&body, &mut request)?; (request.system_prompt, request.messages) = place_system(request.system_prompt.take(), std::mem::take(&mut request.messages)); Ok(Call { request, stream: decode::streamed(&body)? }) }