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..9c29d4b0ea 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,23 @@ dependencies = [ "tokio", ] +[[package]] +name = "continuum-gateway" +version = "0.1.0" +dependencies = [ + "async-trait", + "axum", + "continuum-base", + "continuum-capture", + "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", 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/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/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-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/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/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..08a259718c --- /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 BURST_EVENTS: usize = 64; + let mut body = String::new(); + for i in 0..BURST_EVENTS { + 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 * BURST_EVENTS, + "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, 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-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/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/slots/citizen_slots.rs b/core/continuum-engine/src/inference/slots/citizen_slots.rs index 3b42cf7fbc..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. @@ -65,7 +69,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(DRIVER_PURPOSE) => SlotClass::Turn, Some("cognition/should-respond") | Some("cognition/generate-response") | Some("cognition/validate-response-decision") @@ -289,7 +294,7 @@ pub(super) fn pages_in(dir: &std::path::Path) -> Result 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)); + } +} 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/Cargo.toml b/core/continuum-gateway/Cargo.toml new file mode 100644 index 0000000000..65a9ce35b1 --- /dev/null +++ b/core/continuum-gateway/Cargo.toml @@ -0,0 +1,18 @@ +[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" } +continuum-capture = { path = "../continuum-capture" } # the one capture of every mind's calls +async-trait = "0.1" +axum = "0.8" +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +tokio-stream.workspace = true +uuid.workspace = true +tracing.workspace = true diff --git a/core/continuum-gateway/src/answer.rs b/core/continuum-gateway/src/answer.rs new file mode 100644 index 0000000000..82b6b8fe34 --- /dev/null +++ b/core/continuum-gateway/src/answer.rs @@ -0,0 +1,358 @@ +//! 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. 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, 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`. +//! - **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; +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, 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). 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 { + encoder, + 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)); + } + } + + /// The frames that close an answer the generation returned. + fn closing(&mut self, outcome: Result) -> Vec { + match outcome { + 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 + .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) => {} + } + 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::stop::STOPPING)); + continue; + } + 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. + this.encode_received(); + let closing = this.closing(outcome); + this.encoded.extend(closing); + } + } + } + } +} + +#[cfg(test)] +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; + 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) + } + + /// A generation shaped as the engine's: it holds a slot permit for its whole life (the + /// 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() + .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 { + counted.fetch_add(1, Ordering::SeqCst); + 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, + 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] + 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), 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_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 + 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; + } + 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, + std::future::pending(), + ); + 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:?}" + ); + } + + // 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::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 new file mode 100644 index 0000000000..d0fc5dfc4f --- /dev/null +++ b/core/continuum-gateway/src/lib.rs @@ -0,0 +1,22 @@ +//! 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 answer; +mod listener; +mod module; +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 new file mode 100644 index 0000000000..cd3bbd62ff --- /dev/null +++ b/core/continuum-gateway/src/listener.rs @@ -0,0 +1,132 @@ +//! 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, 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. + +use std::future::Future; + +use tokio::sync::watch; +use tokio::task::JoinHandle; + +use crate::stop::Signal; + +/// 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 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, + serving: JoinHandle<()>, +} + +impl Listener { + /// 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, + 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}"))?; + 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 connections = crate::sever::Severing { + socket, + cut: abandoned.clone(), + }; + let router = routes(abandoned); + let serving = tokio::spawn(async move { + let outcome = axum::serve(connections, router) + .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 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); + } + + /// 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 new file mode 100644 index 0000000000..2a426466ff --- /dev/null +++ b/core/continuum-gateway/src/module.rs @@ -0,0 +1,284 @@ +//! 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 { + /// 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 GatewayModule { + /// 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::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())); + } + if let Some(ended) = slot.take() { + ended.join().await?; + } + 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"); + })?; + 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())) + } +} + +/// `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, 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> { + self.listen(configured_port()?).await.map(|_| ()) + } + + async fn handle_command(&self, command: &str, _params: Value) -> Result { + 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 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 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(()); + }; + 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"); + } + + /// 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::stop::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/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..51be252cf7 --- /dev/null +++ b/core/continuum-gateway/src/server.rs @@ -0,0 +1,127 @@ +//! The one HTTP server: every format's route through the same handler. + +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; +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}; + +/// 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) +} + +/// `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(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), + }; + 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()); + 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. + // 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()); + } + 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"); + // 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 { + // 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) => 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), + }; + } + // 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 + }; + 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() +} + +/// 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 { + 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/session.rs b/core/continuum-gateway/src/session.rs new file mode 100644 index 0000000000..c9f1ce429c --- /dev/null +++ b/core/continuum-gateway/src/session.rs @@ -0,0 +1,122 @@ +//! 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::prompt_capture::{CaptureLease, JsonlPromptCaptureSink, PromptCall, PromptCaptureSink}; +use continuum_engine::ai::{TextGenerationRequest, TextGenerationResponse}; +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()) +} + +/// 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 refused: its capture cannot be opened"); + return Err(CaptureUnavailable { session, error }); + } + }; + 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, + }; + 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)] +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)); + } + + // 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/sever.rs b/core/continuum-gateway/src/sever.rs new file mode 100644 index 0000000000..7921d81d3c --- /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::stop::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::stop::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) + } +} 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(_) => {} + } + } + } +} diff --git a/core/continuum-gateway/src/wire/anthropic.rs b/core/continuum-gateway/src/wire/anthropic.rs new file mode 100644 index 0000000000..e4926eb5d2 --- /dev/null +++ b/core/continuum-gateway/src/wire/anthropic.rs @@ -0,0 +1,239 @@ +//! 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, 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}; +use serde_json::{json, Value}; + +/// A Messages request's required fields; everything else stays in `rest`. +#[derive(serde::Deserialize)] +struct Required { + model: String, + max_tokens: std::num::NonZeroU32, + messages: Vec, + #[serde(flatten)] + rest: serde_json::Map, +} + +/// 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 Required { model, max_tokens, messages, rest } = decode::fields(body)?; + let body = Value::Object(rest); + let mut request = TextGenerationRequest { + 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::slots::DRIVER_PURPOSE.into()), + ..Default::default() + }; + 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)? }) + } + + 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": ""})); + } + 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, finish), "stop_sequence": null, + "usage": usage(response), + }) + } + + fn error(kind: ErrorKind, message: &str) -> Value { + let kind = match kind { + ErrorKind::InvalidRequest => "invalid_request_error", + ErrorKind::NotFound => "not_found_error", + ErrorKind::Engine | ErrorKind::CaptureUnavailable => "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, finish: Finish) -> 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, finish), "stop_sequence": null}, + "usage": usage(response)}))); + 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 + } +} + +/// 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, finish: Finish) -> &'static str { + match finish { + _ if stopped_for_tools(response, finish) => "tool_use", + Finish::Length => "max_tokens", + Finish::Stop | Finish::ToolUse => "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, + } +} + +/// 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")), + } +} + +/// 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 new file mode 100644 index 0000000000..ee32ed745e --- /dev/null +++ b/core/continuum-gateway/src/wire/chat.rs @@ -0,0 +1,229 @@ +//! 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, 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}; +use serde_json::{json, Value}; + +/// 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 { + model: String, + id: String, + created: u64, +} + +impl Wire for Chat { + const NAME: &'static str = "openai_chat"; + + fn decode(body: Value) -> Result { + 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), + 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::slots::DRIVER_PURPOSE.into()), + ..Default::default() + }; + decode::sampling(&body, &mut request)?; + Ok(Call { request, stream: decode::streamed(&body)? }) + } + + 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); + } + 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": continuum_base::time::EpochMs::now().secs(), "model": response.model, + "choices": [{"index": 0, "message": message, "finish_reason": finish_reason(response, finish)}], + "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"), + ErrorKind::CaptureUnavailable => ("server_error", "capture_unavailable"), + }; + 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: continuum_base::time::EpochMs::now().secs() } + } + + 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, finish: Finish) -> 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, 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()); + 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 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", + } +} + +fn usage(response: &TextGenerationResponse) -> Value { + 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 { + json!({"id": id, "type": "function", "function": {"name": name, "arguments": input.to_string()}}) +} + +/// 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["content"]; + match role { + "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 }), + } + } + Ok(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 }, + } +} + +/// 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")) +} + +/// 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..55c9a6f7c4 --- /dev/null +++ b/core/continuum-gateway/src/wire/decode.rs @@ -0,0 +1,312 @@ +//! 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)) +} + +/// 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, +) -> Result<(), BadRequest> { + 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" + } 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 new file mode 100644 index 0000000000..d5cb715932 --- /dev/null +++ b/core/continuum-gateway/src/wire/mod.rs @@ -0,0 +1,188 @@ +//! 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 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; +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. +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, 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; + /// The whole answer, for a call that did not ask to stream. + 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. + 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, finish: Finish) -> 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, + /// 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. +#[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, + } + } +} + +/// 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() +} + +/// 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, 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. +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(), + } +} + +/// 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. +pub(crate) 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"), + } +} + +/// 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) +} + +#[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..69cd4d45ba --- /dev/null +++ b/core/continuum-gateway/src/wire/responses.rs @@ -0,0 +1,262 @@ +//! 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, 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}; + +/// 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, +} + +/// 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 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 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), + 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::slots::DRIVER_PURPOSE.into()), + ..Default::default() + }; + 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)? }) + } + + 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 { + let code = match kind { + 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}}) + } + + fn streamer(model: &str, id: &str) -> Self { + 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 { + 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, finish: Finish) -> 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, finish))); + 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 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, + "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, finish)| finish == Finish::Length && !stopped_for_tools(r, finish)) + .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()))?; + 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 + 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 + } + } + Ok(out) +} + +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)), + } +} + +/// 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()), + } +} diff --git a/core/continuum-gateway/src/wire/tests.rs b/core/continuum-gateway/src/wire/tests.rs new file mode 100644 index 0000000000..61b30a2e92 --- /dev/null +++ b/core/continuum-gateway/src/wire/tests.rs @@ -0,0 +1,269 @@ +//! 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; +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 { + 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": "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() {}"}]}]}, + ], + })) + .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_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(), Finish::ToolUse, "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(), Finish::ToolUse)); + 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(), 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(), 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"); + 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": [ + {"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\"}"}, + {"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"}}}}], + })) + .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)); + + 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(), 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(); + 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"); +} + +/// 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()])); +} + +// 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); + } +} 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/DRIVER-GATEWAY.md b/docs/architecture/DRIVER-GATEWAY.md new file mode 100644 index 0000000000..e43008bf4f --- /dev/null +++ b/docs/architecture/DRIVER-GATEWAY.md @@ -0,0 +1,130 @@ + + +# 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. 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 | +|---|---|---| +| 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)`. +- 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. + +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. + +## 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. + +**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. +- 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 | +| 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 | +| 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. +- 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. diff --git a/docs/architecture/SERVING-ENGINE.md b/docs/architecture/SERVING-ENGINE.md index 9b4986aab3..c4ab71cd9b 100644 --- a/docs/architecture/SERVING-ENGINE.md +++ b/docs/architecture/SERVING-ENGINE.md @@ -46,6 +46,244 @@ **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. + +**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; +- idle retirement; +- 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.** +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. + +## 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. + +## 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. + +**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 +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 | diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index eb95a0b3b4..e6c28d9edf 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -143,9 +143,9 @@ 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'); + 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));