From 0ff494e2a44c0707b0ac74267a184d662249c138 Mon Sep 17 00:00:00 2001 From: daniel Date: Sat, 28 Nov 2026 19:51:31 +0000 Subject: [PATCH 01/19] feat(gateway): add multi-attachment --pinned-session mode --- docs/reference/gateway-protocol.md | 32 +- docs/user/gateway.md | 20 +- src/gateway.rs | 1676 ++++++++++++++++++++++++++- src/gateway/http_boundary.rs | 93 +- src/gateway/http_server.rs | 137 ++- src/gateway/pinned_tests.rs | 1709 ++++++++++++++++++++++++++++ src/gateway/tests.rs | 54 +- tests/gateway.rs | 98 ++ 8 files changed, 3688 insertions(+), 131 deletions(-) create mode 100644 src/gateway/pinned_tests.rs diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 9556d64e..0f57227b 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -85,7 +85,7 @@ Its `result._meta` explicitly identifies the experimental limits: {"kit/gateway":{"experimental":true,"transport":"bounded-http","maxFrameBytes":1048576,"coreBufferedBytesPerDirection":16777216,"httpEgressBytesPerConnection":4194304,"liveReplayLimitBytes":8388608,"liveReplayLimitEvents":4093}} ``` -Both connection and session SSE GETs return HTTP 200 with `Content-Type: text/event-stream`. The session stream echoes both ACP ID headers. Accepted subsequent POSTs and successful transport DELETE return HTTP 202; DELETE failures follow the rules above. SSE `data:` contains JSON-RPC replies or notifications, for example: +Both connection and session SSE GETs return HTTP 200 with `Content-Type: text/event-stream`. The session stream echoes both ACP ID headers. Open gateway SSE streams emit an SSE comment keep-alive (`:\n\n`) every 15 seconds while idle. Accepted subsequent POSTs and successful transport DELETE return HTTP 202; DELETE failures follow the rules above. SSE `data:` contains JSON-RPC replies or notifications, for example: ```text data: {"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"Invalid params"}} @@ -155,7 +155,7 @@ HTTP POST bodies are limited to 1 MiB, including streamed bodies. Supervisor que ## Replay retained messages from native Kit -This extension applies to direct native Kit ACP v2 connections (`kit acp --protocol-version 2` or `kit serve --remote-acp`), not the gateway. Gateway `session/resume` accepts replay from `start` only. +This extension applies to direct native Kit ACP v2 connections (`kit acp --protocol-version 2` or `kit serve --remote-acp`), and to `kit gateway --pinned-session` (see [Pinned-session mode](#pinned-session-mode)). Default single-controller gateway `session/resume` accepts replay from `start` only. To rebuild a conversation after reconnecting, send `session/resume` with `replayFrom: {"type":"start"}`. To replay only a suffix, use Kit's inclusive cursor with a durable user-message ID previously received from that session: @@ -166,3 +166,31 @@ To rebuild a conversation after reconnecting, send `session/resume` with `replay Set this object as `replayFrom`; its `sessionId` must match the request's `sessionId`. Replay includes the identified complete user message and all later retained updates. Store the cursor with the session ID and deduplicate complete messages by message ID. The cursor is not an HTTP SSE event ID and does not resume an interrupted model request. Only user messages with durable identities support partial replay. Agent-message and thought IDs cannot be used as boundaries because their content can accumulate across other messages in the same response; choose the preceding user message instead. Agent-message IDs, thought IDs, legacy offset-based replay IDs, tool-call IDs, unknown IDs, and IDs removed by compaction are rejected with JSON-RPC `-32602` (Invalid params), as are malformed or session-mismatched cursors. Retry explicitly with `{"type":"start"}` to rebuild from retained history; Kit does not silently fall back to a different position. + + + +## Pinned-session mode (`--pinned-session`) + +Start the gateway with `--pinned-session ` (and optionally `--client-request-timeout `, default `5m`) to serve one session to many simultaneous ACP HTTP attachments. Default single-controller gateway behavior is unchanged when `--pinned-session` is omitted. + +> [!WARNING] +> **Security boundary:** All attachments connected to a pinned-session gateway share the same session. Every attached client receives all session updates, can submit prompts or cancel foreground work, and can answer relayed agent-to-client requests. Because the gateway authenticates only with its single bearer credential, place an authenticating proxy in front of `kit gateway --pinned-session` whenever serving multiple users, browsers, or services. + +When pinned mode is active: + +- **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. `session/list` returns only that single pinned session entry, with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). +- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. +- **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. +- **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `data.reason = "queue_overflow"`, its pending requests fail with that reason, and its SSE stream closes cleanly without affecting other attachments or the active turn. +- **Fan-in and deduplication:** Responses to client requests are delivered only to the originating attachment. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). +- **Detach and cancel:** Disconnecting an attachment does not withdraw its already-submitted held prompts, so a deliverer may disconnect before insertion and retry with the same `idempotencyKey`. Explicit `$/cancel_request` from the originating attachment still withdraws its own held prompt. Any live attachment may send `session/cancel`. +- **Replay cursors for late joiners:** `session/resume` accepts: + - omitted / `null`: no history; delivers current config and state snapshots only (`historyAvailable: false`). + - `{"type":"start"}`: full retained journal from the beginning of the session (fails with `replay_unavailable` if earlier events were evicted). + - `{"type":"_kit_current_turn"}`: replays from the start of the current (or most recent) turn so a mid-turn joiner can render in-progress assistant output, even after older turns have been evicted from the journal. + - `{"type":"_kit_message","sessionId":"SESSION_ID","messageId":"MESSAGE_ID"}`: inclusive replay from a retained user message ID; rejects unknown, evicted, or session-mismatched cursors with JSON-RPC `-32602`. +- **Relayed agent-to-client requests:** In pinned mode the gateway advertises form elicitation to the child and relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`) to every live attachment. Clients that attach while a request is still pending receive it immediately after their startup response and become eligible targets. + - If no attachment is live when the request arrives, the gateway answers `-32601` immediately. + - The first valid `result` from any target attachment wins and is forwarded to the child; every other target receives `$/cancel_request` for that relayed request ID. + - A `-32601` error from an attachment that does not implement the method removes only that target; if no targets remain after `-32601` declines, the gateway answers `-32601` to the child. + - Target detach does not cancel a pending request (so transient reconnects such as browser reloads can still answer). If the request is neither answered nor cancelled by the agent before `--client-request-timeout` (default `5m`), the gateway answers the child with `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) and sends `$/cancel_request` to current targets. diff --git a/docs/user/gateway.md b/docs/user/gateway.md index 70387786..d064ac3b 100644 --- a/docs/user/gateway.md +++ b/docs/user/gateway.md @@ -107,6 +107,24 @@ Create or resume the session before querying gateway status. Treat a failed stat The gateway does not expose `session/fork`. When using native Kit transcript forks, stop concurrent submissions and wait for outstanding work to finish. If the fork reports `session must be settled before snapshot`, wait for background and delegated work to finish, or cancel it explicitly and wait for completion. If it reports `session changed during snapshot admission; retry`, wait for activity to settle before retrying the fork. A saved transcript is history, not a checkpoint that restarts interrupted tools. +## Share one session across multiple clients + +To host one long-lived session that multiple ACP HTTP clients (for example, a dashboard, an automated trigger, and an operator) attach to simultaneously, pin the gateway to a single session ID: + +```sh +kit gateway --credential-file "$HOME/.kit-gateway-token" \ + --project /absolute/server/project \ + --pinned-session my-thread-id \ + --client-request-timeout 5m +``` + +- **Shared session boundary:** All attachments share the pinned session: every connected client receives all live updates, can submit prompts or cancel work, and can answer relayed interactive questions or permission requests. Place an authenticating proxy in front of `kit gateway --pinned-session` when serving multiple users or services; the gateway itself verifies only its single bearer token. +- **Independent attachments:** Connecting a second client does not displace existing clients or withdraw their held prompts. Sending `session/close` detaches only the calling client without ending the session. If a slow client's output queue overflows, only that client is disconnected; other attachments and the active turn continue. +- **Late joiners and reconnects:** Clients can attach with `replayFrom: {"type":"_kit_current_turn"}` to catch up on the current or most recent turn, or `{"type":"_kit_message","sessionId":"...","messageId":"..."}` to resume from a retained user message, without replaying the entire session journal. +- **Interactive prompts (`--client-request-timeout`):** Agent-to-client requests (such as `ask_user` forms) are sent to all attached clients and to clients that attach while the request is pending; the first valid answer wins and the other clients receive a cancellation. If no client is attached when the request arrives, it fails immediately rather than blocking the turn. If clients detach mid-request, the request stays pending until answered, cancelled, or `--client-request-timeout` (default `5m`) expires. + +For exact wire behavior, cursors, and limits, see [Pinned-session mode](../reference/gateway-protocol.md#pinned-session-mode). + ## Standard ACP HTTP clients Use an ACP v2 HTTP/SSE client with the exact endpoint `http://HOST:7766/acp/v2`, a bearer credential on every request, and matching Kit versions. There is no separate Kit session REST API. See the [gateway protocol reference](../reference/gateway-protocol.md) for connection setup, supported operations, close requests, and transport limits. @@ -132,6 +150,6 @@ See [Implement an ACP HTTP client](../reference/gateway-protocol.md#implement-an - There is no fixed resident-session count ceiling. Provision memory and process capacity for your workload. Detaching does not stop a session, even when it is idle; use `session/close` to end resident work. Listing or creating sessions reclaims completed entries without deleting durable transcripts. - Transport saturation can disconnect a client without canceling accepted work. HTTP frames are limited to 1 MiB; child output frames to 8 MiB. Oversized or malformed child output stops that child. There is no idle connection expiration or body-read deadline: abandoned transports can retain connection slots, and exhaustion may require restarting the gateway. See [Transport limits](../reference/gateway-protocol.md#transport-limits) before sizing an integration. These bounds are not a hard process-memory ceiling or denial-of-service protection. - Use `Ctrl+C` on the gateway host for graceful shutdown. Kit waits for child cleanup and exit, then forcibly stops a child if it exceeds the 10-second timeout. That fallback can leave a stale transcript lock requiring operator intervention. Hard process termination has operating-system-dependent cleanup behavior; arbitrary tool descendants are not a managed process group. -- Client-side ACP services, arbitrary extra directories, session-scoped HTTP/SSE MCP servers, browser callbacks, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. +- In default single-controller mode, client-side ACP services are not supported (pinned-session mode relays agent-to-client requests such as `ask_user` forms to attached clients). Arbitrary extra directories, legacy SSE MCP servers, browser callbacks, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. The internal `gateway bridge` stdio command is a transport adapter for the bundled TUI, not a stable public protocol or general-purpose ACP proxy. The public transport is ACP HTTP at `/acp/v2`, implemented by the ACP SDK rather than a Kit-specific RPC protocol. diff --git a/src/gateway.rs b/src/gateway.rs index 433a6622..9ed55cda 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -14,7 +14,7 @@ use futures_util::future::{Either, select}; use serde::Deserialize; use serde_json::Value; use std::{ - collections::{HashMap, VecDeque}, + collections::{HashMap, HashSet, VecDeque}, io, net::SocketAddr, path::{Path, PathBuf}, @@ -30,9 +30,12 @@ use tokio::{ sync::{Mutex, mpsc, oneshot, watch}, }; const LEASE: Duration = Duration::from_secs(15); +const DEFAULT_CLIENT_REQUEST_TIMEOUT: Duration = Duration::from_secs(300); const MAX_REPLAY: usize = 8 * 1024 * 1024; const MAX_HTTP_FRAME: usize = 1024 * 1024; const MAX_QUEUE: usize = 4096; +const MAX_PINNED_CLIENT_REQUESTS: usize = 64; +const MAX_OVERFLOW_HISTORY: usize = 256; fn object(fields: [(&str, Value); N]) -> Value { Value::Object( @@ -50,6 +53,8 @@ pub struct Args { project: Vec, allow_private_network: bool, allow_wildcard_bind: bool, + pinned_session: Option, + client_request_timeout: Duration, command: Option, } #[derive(Debug)] @@ -113,6 +118,24 @@ impl Args { "Allow binding 0.0.0.0 or :: (all interfaces; requires network isolation)", ), ) + .arg( + Arg::new("pinned_session") + .long("pinned-session") + .value_name("SESSION_ID") + .help( + "Pin this gateway to a single multi-attachment session ID (all clients share the session; place an authenticating proxy in front)", + ), + ) + .arg( + Arg::new("client_request_timeout") + .long("client-request-timeout") + .value_name("DURATION") + .requires("pinned_session") + .value_parser(parse_duration) + .help( + "Timeout for relayed agent-to-client requests in pinned mode (e.g. 30s, 5m; default 5m)", + ), + ) .subcommand( client("list").about("List resident and restorable sessions in approved projects"), ) @@ -164,10 +187,41 @@ impl Args { .unwrap_or_default(), allow_private_network: required_arg(matches, "allow_private_network")?, allow_wildcard_bind: required_arg(matches, "allow_wildcard_bind")?, + pinned_session: optional_arg(matches, "pinned_session")?, + client_request_timeout: optional_arg(matches, "client_request_timeout")? + .unwrap_or(DEFAULT_CLIENT_REQUEST_TIMEOUT), command, }) } } + +fn parse_duration(raw: &str) -> Result { + let value = raw.trim(); + if value.is_empty() { + return Err("duration must not be empty".into()); + } + let (digits, unit_ms): (&str, u64) = if let Some(num) = value.strip_suffix("ms") { + (num, 1) + } else if let Some(num) = value.strip_suffix('s') { + (num, 1_000) + } else if let Some(num) = value.strip_suffix('m') { + (num, 60_000) + } else if let Some(num) = value.strip_suffix('h') { + (num, 3_600_000) + } else { + (value, 1_000) + }; + let count: u64 = digits + .parse() + .map_err(|_| format!("invalid duration '{raw}'; expected e.g. 30s, 5m, 500ms"))?; + if count == 0 { + return Err("duration must be greater than zero".into()); + } + let millis = count + .checked_mul(unit_ms) + .ok_or_else(|| format!("duration '{raw}' overflows"))?; + Ok(Duration::from_millis(millis)) +} fn optional_arg( matches: &clap::ArgMatches, name: &str, @@ -212,6 +266,91 @@ impl Remote { Ok(command) } } +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(test, derive(Deserialize))] +#[cfg_attr(test, serde(tag = "type", rename_all = "snake_case"))] +enum ReplayMode { + None, + Start, + CurrentTurn, + Message { message_id: String }, +} + +fn effective_replay_mode(replay: bool, replay_mode: Option) -> ReplayMode { + replay_mode.unwrap_or(if replay { + ReplayMode::Start + } else { + ReplayMode::None + }) +} + +fn parse_replay_mode( + cursor: Option<&Value>, + session_id: &str, + pinned: bool, + is_new: bool, +) -> Result { + let Some(cursor) = cursor.filter(|value| !value.is_null()) else { + return Ok(if is_new { + ReplayMode::Start + } else { + ReplayMode::None + }); + }; + if cursor == &object([("type", "start".into())]) { + return Ok(ReplayMode::Start); + } + if !pinned { + return Err(Failure::bad("unsupported replay cursor")); + } + let Some(map) = cursor.as_object() else { + return Err(Failure::invalid_params("unsupported replay cursor")); + }; + match map.get("type").and_then(Value::as_str) { + Some("_kit_current_turn") => { + if map.keys().any(|key| key != "type" && key != "_meta") { + return Err(Failure::invalid_params( + "invalid _kit_current_turn replay cursor", + )); + } + Ok(ReplayMode::CurrentTurn) + } + Some("_kit_message") => { + if map + .keys() + .any(|key| !matches!(key.as_str(), "type" | "sessionId" | "messageId" | "_meta")) + { + return Err(Failure::invalid_params( + "invalid _kit_message replay cursor", + )); + } + let Some(cursor_session) = map.get("sessionId").and_then(Value::as_str) else { + return Err(Failure::invalid_params( + "invalid _kit_message replay cursor", + )); + }; + let Some(message_id) = map + .get("messageId") + .and_then(Value::as_str) + .filter(|id| !id.is_empty()) + else { + return Err(Failure::invalid_params( + "invalid _kit_message replay cursor", + )); + }; + if cursor_session != session_id { + return Err(Failure::invalid_params( + "replay cursor sessionId does not match session", + )); + } + Ok(ReplayMode::Message { + message_id: message_id.to_owned(), + }) + } + _ => Err(Failure::invalid_params("unsupported replay cursor")), + } +} + // Actor mailbox commands, never a public transport or durable format. #[derive(Debug)] #[cfg_attr(test, derive(Deserialize))] @@ -233,6 +372,8 @@ enum Request { session: String, replay: bool, #[cfg_attr(test, serde(default))] + replay_mode: Option, + #[cfg_attr(test, serde(default))] replace: bool, #[cfg_attr(test, serde(default))] startup: Option, @@ -268,12 +409,22 @@ impl Failure { ("terminal", (self.2 != "unavailable").into()), ]) } + fn jsonrpc_code(&self) -> i64 { + if self.2 == "invalid_params" { + -32602 + } else { + -32000 + } + } fn root(message: impl Into) -> Self { Self(StatusCode::BAD_REQUEST, message.into(), "root_denied") } fn bad(message: impl Into) -> Self { Self(StatusCode::BAD_REQUEST, message.into(), "protocol") } + fn invalid_params(message: impl Into) -> Self { + Self(StatusCode::BAD_REQUEST, message.into(), "invalid_params") + } fn conflict(message: impl Into) -> Self { Self(StatusCode::CONFLICT, message.into(), "conflict") } @@ -294,12 +445,18 @@ impl IntoResponse for Failure { .into_response() } } +#[derive(Clone, Debug)] +struct PinnedConfig { + session_id: String, + client_request_timeout: Duration, +} struct Gateway { // Set only by shutdown while holding sessions; checked again under that // lock by create/restore so late HTTP requests cannot escape the drain. stopping: AtomicBool, token: BearerToken, roots: Vec, + pinned: Option, // Writers: create/restore inserts a fully spawned actor; reclamation removes // completed actors; shutdown takes all entries. No guard spans await or child // teardown. Before insertion Child is kill-on-drop; afterwards actor owns it. @@ -456,10 +613,21 @@ pub async fn run(args: Args) -> Result<(), Box> { if roots.is_empty() { return Err("at least one --project directory is required".into()); } + let pinned = match args.pinned_session { + Some(session_id) => { + crate::session::validate_id(&session_id)?; + Some(PinnedConfig { + session_id, + client_request_timeout: args.client_request_timeout, + }) + } + None => None, + }; let gateway = Arc::new(Gateway { stopping: AtomicBool::new(false), token: BearerToken::load(&path)?, roots, + pinned, sessions: Mutex::new(HashMap::new()), }); let listener = tokio::net::TcpListener::bind(args.listen).await?; @@ -559,7 +727,60 @@ async fn handle( gateway.reclaim_exited().await; let entries = gateway.sessions.lock().await.clone(); let roots = gateway.roots.clone(); + let pinned = gateway.pinned.clone(); let rows = tokio::task::spawn_blocking(move || { + if let Some(pinned) = pinned { + let id = pinned.session_id; + let resident = entries.get(&id); + let mut catalog_match = None; + for root in &roots { + let catalog = + crate::session::catalog(root).map_err(Failure::unavailable)?; + if let Some(entry) = catalog.into_iter().find(|entry| entry.id == id) { + catalog_match = Some((root.clone(), entry)); + break; + } + } + let row = if let Some(entry) = resident { + let state = if entry.sender.is_closed() { + "exited" + } else { + "resident" + }; + if let Some((_, catalog_entry)) = catalog_match { + object([ + ("session", id.into()), + ("root", entry.root.to_string_lossy().into_owned().into()), + ("title", catalog_entry.title.into()), + ("preview", catalog_entry.preview.into()), + ("state", state.into()), + ]) + } else { + object([ + ("session", id.into()), + ("root", entry.root.to_string_lossy().into_owned().into()), + ("state", state.into()), + ]) + } + } else if let Some((root, catalog_entry)) = catalog_match { + object([ + ("session", id.into()), + ("root", root.to_string_lossy().into_owned().into()), + ("title", catalog_entry.title.into()), + ("preview", catalog_entry.preview.into()), + ("state", "restorable".into()), + ]) + } else if let Some(root) = roots.first() { + object([ + ("session", id.into()), + ("root", root.to_string_lossy().into_owned().into()), + ("state", "new".into()), + ]) + } else { + return Ok::<_, Failure>(Vec::new()); + }; + return Ok::<_, Failure>(vec![row]); + } let mut rows = Vec::new(); for root in roots { let catalog = crate::session::catalog(&root).map_err(Failure::unavailable)?; @@ -616,6 +837,58 @@ async fn handle( return Err(Failure::root("project is not registered")); } gateway.reclaim_exited().await; + if let Some(pinned) = &gateway.pinned { + if let Some(requested) = &session + && requested != &pinned.session_id + { + return Err(Failure::bad(format!( + "gateway is pinned to session {}; other session ids are not allowed", + pinned.session_id + ))); + } + let id = pinned.session_id.clone(); + { + let entries = gateway.sessions.lock().await; + if let Some(entry) = entries.get(&id).filter(|e| !e.sender.is_closed()) { + if entry.root != root { + return Err(Failure::root("session belongs to another project")); + } + return Ok(Json(object([ + ("session", id.into()), + ("root", root.to_string_lossy().into_owned().into()), + ("state", "resident".into()), + ]))); + } + } + let restore = + crate::session::belongs_to_workspace(&root, &id).map_err(Failure::bad)?; + let mut entries = gateway.sessions.lock().await; + if gateway.stopping.load(Ordering::Acquire) { + return Err(Failure::unavailable("gateway is stopping")); + } + if let Some(entry) = entries.get(&id).filter(|e| !e.sender.is_closed()) { + if entry.root != root { + return Err(Failure::root("session belongs to another project")); + } + } else { + let entry = spawn( + &root, + &id, + restore, + force, + Some(pinned.client_request_timeout), + ) + .map_err(|error| Failure::unavailable(error.to_string()))?; + let replaced = entries.insert(id.clone(), entry); + drop(entries); + drop(replaced); + } + return Ok(Json(object([ + ("session", id.into()), + ("root", root.to_string_lossy().into_owned().into()), + ("state", "resident".into()), + ]))); + } let restore = session.is_some(); let id = session.unwrap_or_else(crate::session::new_id); if restore { @@ -644,7 +917,7 @@ async fn handle( return Err(Failure::root("session belongs to another project")); } } else { - let entry = spawn(&root, &id, restore, force) + let entry = spawn(&root, &id, restore, force, None) .map_err(|error| Failure::unavailable(error.to_string()))?; let replaced = entries.insert(id.clone(), entry); drop(entries); @@ -664,6 +937,14 @@ async fn handle( | Request::Detach { session, .. } => session, _ => return Err(Failure::bad("invalid operation")), }; + if let Some(pinned) = &gateway.pinned + && id != &pinned.session_id + { + return Err(Failure::bad(format!( + "gateway is pinned to session {}; other session ids are not allowed", + pinned.session_id + ))); + } let entry = gateway .sessions .lock() @@ -702,6 +983,7 @@ struct Attachment { events: VecDeque<(u64, Value)>, bytes: usize, live: bool, + closing: bool, } impl Attachment { fn push(&mut self, message: Value) -> bool { @@ -722,7 +1004,95 @@ struct Pending { explicit_delivery: bool, withdrawal_pending: bool, // The caller's policy, independent of full internal child cache seeding. - replay: bool, + replay: ReplayMode, +} +struct WaitingStartup { + attachment: String, + request_id: Value, + replay: ReplayMode, +} +struct PendingClientRequest { + seq: u64, + child_id: Value, + method: String, + params: Value, + targets: HashSet, + deadline: tokio::time::Instant, +} +struct PinnedState { + attachments: HashMap, + overflowed: VecDeque, + startup_driver: Option, + waiting_startups: Vec, + client_request_timeout: Duration, + next_relay_id: u64, + client_requests: HashMap, +} +impl PinnedState { + fn new(client_request_timeout: Duration) -> Self { + Self { + attachments: HashMap::new(), + overflowed: VecDeque::new(), + startup_driver: None, + waiting_startups: Vec::new(), + client_request_timeout, + next_relay_id: 0, + client_requests: HashMap::new(), + } + } + + fn record_overflow(&mut self, id: String) { + if self.overflowed.iter().any(|existing| existing == &id) { + return; + } + if self.overflowed.len() >= MAX_OVERFLOW_HISTORY { + self.overflowed.pop_front(); + } + self.overflowed.push_back(id); + } + + fn is_overflowed(&self, id: &str) -> bool { + self.overflowed.iter().any(|existing| existing == id) + } + + fn take_overflow(&mut self, id: &str) -> bool { + if let Some(pos) = self.overflowed.iter().position(|existing| existing == id) { + self.overflowed.remove(pos); + true + } else { + false + } + } + + fn remove_target_from_requests(&mut self, attachment_id: &str) { + for request in self.client_requests.values_mut() { + request.targets.remove(attachment_id); + } + } + + fn pending_request_messages(&self) -> Vec<(String, Value)> { + let mut items: Vec<_> = self + .client_requests + .iter() + .map(|(relay_id, req)| { + ( + req.seq, + relay_id.clone(), + object([ + ("jsonrpc", "2.0".into()), + ("id", relay_id.clone().into()), + ("method", req.method.clone().into()), + ("params", req.params.clone()), + ]), + ) + }) + .collect(); + items.sort_by_key(|(seq, _, _)| *seq); + items + .into_iter() + .map(|(_, relay_id, message)| (relay_id, message)) + .collect() + } } struct Actor { id: String, @@ -734,6 +1104,8 @@ struct Actor { attachment: Option, // Survives detach, expiry and replay overflow; only a committed claim replaces it. committed_owner: Option, + // Present only in `--pinned-session` mode; default single-controller mode leaves this None. + pinned: Option, serial: u64, pending: HashMap, initialized: Option, @@ -743,9 +1115,43 @@ struct Actor { state: Value, journal: VecDeque, journal_bytes: usize, + journal_base_seq: u64, + current_turn_start: Option, replay_complete: bool, } -fn spawn(root: &Path, id: &str, restore: bool, force: bool) -> io::Result { +impl Actor { + fn new(id: String, root: PathBuf, restore: bool, pinned_timeout: Option) -> Self { + Self { + id, + root, + restore, + closed: false, + attachment: None, + committed_owner: None, + pinned: pinned_timeout.map(PinnedState::new), + serial: 0, + pending: HashMap::new(), + initialized: None, + session_result: None, + state: object([ + ("sessionUpdate", "state_update".into()), + ("state", "idle".into()), + ]), + journal: VecDeque::new(), + journal_bytes: 0, + journal_base_seq: 0, + current_turn_start: None, + replay_complete: true, + } + } +} +fn spawn( + root: &Path, + id: &str, + restore: bool, + force: bool, + pinned_timeout: Option, +) -> io::Result { let mut command = tokio::process::Command::new(std::env::current_exe()?); command .args(["acp", "--protocol-version", "2", "--root"]) @@ -763,25 +1169,7 @@ fn spawn(root: &Path, id: &str, restore: bool, force: bool) -> io::Result } } let child = command.spawn()?; - let actor = Actor { - id: id.to_owned(), - root: root.to_owned(), - restore, - closed: false, - attachment: None, - committed_owner: None, - serial: 0, - pending: HashMap::new(), - initialized: None, - session_result: None, - state: object([ - ("sessionUpdate", "state_update".into()), - ("state", "idle".into()), - ]), - journal: VecDeque::new(), - journal_bytes: 0, - replay_complete: true, - }; + let actor = Actor::new(id.to_owned(), root.to_owned(), restore, pinned_timeout); let (sender, receiver) = mpsc::channel(32); let (completion, stopped) = watch::channel(()); tokio::spawn(async move { @@ -824,32 +1212,60 @@ impl Actor { let mut lines = framing::Lines::new(stdout); loop { let withdrawal = self.next_withdrawal(); + let expired_request = if withdrawal.is_none() { + self.next_expired_client_request() + } else { + None + }; + let next_deadline = if withdrawal.is_none() && expired_request.is_none() { + self.next_client_request_deadline() + } else { + None + }; + let needs_write = withdrawal.is_some() || expired_request.is_some(); let event = { - let withdrawal_permit = std::pin::pin!(async { - if withdrawal.is_some() { + let write_permit = std::pin::pin!(async { + if needs_write { writes.reserve().await } else { std::future::pending().await } }); + let deadline_wait = std::pin::pin!(async { + if let Some(deadline) = next_deadline { + tokio::time::sleep_until(deadline).await; + } else { + std::future::pending::<()>().await; + } + }); let command = std::pin::pin!(commands.recv()); let line = std::pin::pin!(lines.next_line()); let exited = std::pin::pin!(child.wait()); let written = std::pin::pin!(writer.join_next()); let io = std::pin::pin!(select(line, select(exited, written))); - match select(withdrawal_permit, std::pin::pin!(select(command, io))).await { + let work = std::pin::pin!(select(command, select(deadline_wait, io))); + match select(write_permit, work).await { Either::Left((permit, _)) => { - let (Some(id), Ok(permit)) = (withdrawal, permit) else { + let Ok(permit) = permit else { break; }; - self.send_withdrawal(id, permit); + if let Some(id) = withdrawal { + self.send_withdrawal(id, permit); + } else if let Some(relay_id) = expired_request { + self.expire_client_request(&relay_id, permit); + } continue; } Either::Right((Either::Left((command, _)), _)) => Either::Left(command), - Either::Right((Either::Right((Either::Left((line, _)), _)), _)) => { - Either::Right(Some(line)) - } - Either::Right((Either::Right((Either::Right(_), _)), _)) => Either::Right(None), + Either::Right((Either::Right((Either::Left(((), _)), _)), _)) => continue, + Either::Right(( + Either::Right((Either::Right((Either::Left((line, _)), _)), _)), + _, + )) => Either::Right(Some(line)), + Either::Right(( + Either::Right((Either::Right((Either::Right(_), _)), _)), + _, + )) => Either::Right(None), } }; match event { @@ -972,22 +1388,294 @@ impl Actor { } } } - fn remember(&mut self, message: Value) { + fn push_pinned_attachment(&mut self, attachment_id: &str, message: Value) -> bool { + let Some(pinned) = &mut self.pinned else { + return false; + }; + let overflowed = if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { + !attachment.push(message) + } else { + return false; + }; + if overflowed { + let mut failed_waiters = Vec::new(); + pinned.attachments.remove(attachment_id); + pinned.record_overflow(attachment_id.to_owned()); + pinned.remove_target_from_requests(attachment_id); + pinned + .waiting_startups + .retain(|waiter| waiter.attachment != attachment_id); + if pinned.startup_driver.as_deref() == Some(attachment_id) { + pinned.startup_driver = None; + let startup_sent = self + .pending + .values() + .any(|p| matches!(p.method.as_str(), "session/new" | "session/resume")); + if self.session_result.is_none() && !startup_sent { + failed_waiters = std::mem::take(&mut pinned.waiting_startups); + } + } + for waiter in failed_waiters { + self.push_pinned_startup_error( + &waiter.attachment, + waiter.request_id, + object([ + ("code", (-32000).into()), + ("message", "session startup interrupted; retry".into()), + ("data", Failure::unavailable("startup interrupted").data()), + ]), + ); + } + return false; + } + true + } + fn push_pinned_startup_error(&mut self, attachment_id: &str, request_id: Value, error: Value) { + let message = object([ + ("jsonrpc", "2.0".into()), + ("id", request_id), + ("error", error), + ]); + if self.push_pinned_attachment(attachment_id, message) + && let Some(pinned) = &mut self.pinned + && let Some(attachment) = pinned.attachments.get_mut(attachment_id) + { + attachment.live = false; + attachment.closing = true; + } + } + fn remember(&mut self, message: Value) -> u64 { + let seq = self.journal_base_seq + self.journal.len() as u64; self.journal_bytes += message.to_string().len(); self.journal.push_back(message); while self.journal_bytes > MAX_REPLAY || self.journal.len() > MAX_QUEUE - 3 { if let Some(old) = self.journal.pop_front() { self.journal_bytes -= old.to_string().len(); + self.journal_base_seq += 1; } self.replay_complete = false; } + seq + } + fn next_expired_client_request(&self) -> Option { + let pinned = self.pinned.as_ref()?; + let now = tokio::time::Instant::now(); + pinned + .client_requests + .iter() + .filter(|(_, req)| req.deadline <= now) + .min_by_key(|(_, req)| (req.deadline, req.seq)) + .map(|(relay_id, _)| relay_id.clone()) + } + fn next_client_request_deadline(&self) -> Option { + self.pinned + .as_ref()? + .client_requests + .values() + .map(|req| req.deadline) + .min() + } + fn expire_client_request(&mut self, relay_id: &str, permit: mpsc::Permit<'_, ChildWrite>) { + let Some(pinned) = &mut self.pinned else { + return; + }; + let Some(req) = pinned.client_requests.remove(relay_id) else { + return; + }; + permit.send(ChildWrite { + withdrawals: Vec::new(), + message: incoming_transport_closed_reply(req.child_id, &req.method), + _charge: None, + }); + let cancel = cancel_request_message(Value::String(relay_id.to_owned())); + for target in req.targets { + self.push_pinned_attachment(&target, cancel.clone()); + } + } + fn relay_client_request( + &mut self, + child_id: Value, + method: String, + params: Value, + ) -> Option { + let no_services = || { + object([ + ("jsonrpc", "2.0".into()), + ("id", child_id.clone()), + ( + "error", + object([ + ("code", (-32601).into()), + ("message", "gateway has no client-side services".into()), + ]), + ), + ]) + }; + let Some(pinned) = &mut self.pinned else { + return Some(no_services()); + }; + let live_targets: Vec = pinned + .attachments + .values() + .filter(|a| a.live && !a.closing) + .map(|a| a.id.clone()) + .collect(); + if live_targets.is_empty() { + return Some(no_services()); + } + if pinned.client_requests.len() >= MAX_PINNED_CLIENT_REQUESTS { + return Some(object([ + ("jsonrpc", "2.0".into()), + ("id", child_id), + ( + "error", + object([ + ("code", (-32603).into()), + ("message", "too many pending relayed client requests".into()), + ]), + ), + ])); + } + let Some(seq) = pinned.next_relay_id.checked_add(1) else { + return Some(no_services()); + }; + pinned.next_relay_id = seq; + let relay_id = format!("kit-gw-req-{seq}"); + let timeout = pinned.client_request_timeout; + let relayed = object([ + ("jsonrpc", "2.0".into()), + ("id", relay_id.clone().into()), + ("method", method.clone().into()), + ("params", params.clone()), + ]); + let mut delivered = HashSet::new(); + for target in live_targets { + if self.push_pinned_attachment(&target, relayed.clone()) { + delivered.insert(target); + } + } + if delivered.is_empty() { + return Some(no_services()); + } + if let Some(pinned) = &mut self.pinned { + pinned.client_requests.insert( + relay_id, + PendingClientRequest { + seq, + child_id, + method, + params, + targets: delivered, + deadline: tokio::time::Instant::now() + timeout, + }, + ); + } + None + } + fn cancel_relayed_client_request(&mut self, child_request_id: &Value) { + let Some(pinned) = &mut self.pinned else { + return; + }; + let Some(relay_id) = pinned.client_requests.iter().find_map(|(relay_id, req)| { + (&req.child_id == child_request_id).then(|| relay_id.clone()) + }) else { + return; + }; + let Some(req) = pinned.client_requests.remove(&relay_id) else { + return; + }; + let cancel = cancel_request_message(Value::String(relay_id)); + for target in req.targets { + self.push_pinned_attachment(&target, cancel.clone()); + } + } + fn deliver_pinned_startup( + &mut self, + attachment_id: &str, + result: Value, + request_id: Value, + replay: &ReplayMode, + ) { + let startup = self.startup_messages(result, request_id.clone(), replay, attachment_id); + match startup { + Ok(messages) => { + let pending_requests = self + .pinned + .as_ref() + .map(PinnedState::pending_request_messages) + .unwrap_or_default(); + let total_count = messages.len() + pending_requests.len(); + let total_bytes: usize = + messages.iter().map(|m| m.to_string().len()).sum::() + + pending_requests + .iter() + .map(|(_, m)| m.to_string().len()) + .sum::(); + let fits = self + .pinned + .as_ref() + .and_then(|p| p.attachments.get(attachment_id)) + .is_some_and(|a| { + a.events.len() + total_count <= MAX_QUEUE + && a.bytes + total_bytes <= MAX_REPLAY + }); + if fits { + for update in messages { + self.push_pinned_attachment(attachment_id, update); + } + for (relay_id, req_msg) in pending_requests { + if self.push_pinned_attachment(attachment_id, req_msg) + && let Some(pinned) = &mut self.pinned + && let Some(req) = pinned.client_requests.get_mut(&relay_id) + { + req.targets.insert(attachment_id.to_owned()); + } + } + if let Some(pinned) = &mut self.pinned + && let Some(attachment) = pinned.attachments.get_mut(attachment_id) + { + attachment.live = true; + } + return; + } + let error = Failure::replay("snapshot overflow"); + self.push_pinned_startup_error( + attachment_id, + request_id, + object([ + ("code", error.jsonrpc_code().into()), + ( + "message", + "session snapshot exceeds the gateway limit".into(), + ), + ("data", error.data()), + ]), + ); + } + Err(error) => { + self.push_pinned_startup_error( + attachment_id, + request_id, + object([ + ("code", error.jsonrpc_code().into()), + ("data", error.data()), + ("message", error.1.into()), + ]), + ); + } + } } fn output(&mut self, mut message: Value) -> Option { if message.get("method").is_some() { - if let Some(id) = message.get("id") { + if let Some(id) = message.get("id").cloned() { + if self.pinned.is_some() { + let method = message["method"].as_str().unwrap_or_default().to_owned(); + let params = message.get("params").cloned().unwrap_or_else(|| object([])); + return self.relay_client_request(id, method, params); + } return Some(object([ ("jsonrpc", "2.0".into()), - ("id", id.clone()), + ("id", id), ( "error", object([ @@ -997,10 +1685,23 @@ impl Actor { ), ])); } - if message["method"] == "session/update" - && message["params"]["sessionId"] == self.id - && message["params"]["update"]["sessionUpdate"] == "state_update" - { + if self.pinned.is_some() && message["method"] == "$/cancel_request" { + if let Some(req_id) = message["params"].get("requestId").cloned() { + self.cancel_relayed_client_request(&req_id); + } + return None; + } + let was_idle = self.state["state"] == "idle"; + let is_session_update = + message["method"] == "session/update" && message["params"]["sessionId"] == self.id; + let update_kind = if is_session_update { + message["params"]["update"]["sessionUpdate"] + .as_str() + .map(str::to_owned) + } else { + None + }; + if update_kind.as_deref() == Some("state_update") { self.state = message["params"]["update"].clone(); } if let Some(options) = message["params"]["update"].get("configOptions") @@ -1008,8 +1709,29 @@ impl Actor { { result["configOptions"] = options.clone(); } - self.remember(message.clone()); - if self.attachment.as_ref().is_some_and(|a| a.live) { + let seq = self.remember(message.clone()); + match update_kind.as_deref() { + Some("state_update") + if message["params"]["update"]["state"] == "running" && was_idle => + { + self.current_turn_start = Some(seq); + } + Some("user_message") if self.state["state"] == "idle" => { + self.current_turn_start = Some(seq); + } + _ => {} + } + if let Some(pinned) = &self.pinned { + let targets: Vec = pinned + .attachments + .values() + .filter(|a| a.live && !a.closing) + .map(|a| a.id.clone()) + .collect(); + for target in targets { + self.push_pinned_attachment(&target, message.clone()); + } + } else if self.attachment.as_ref().is_some_and(|a| a.live) { self.emit(message); } } else if let Some(id) = message["id"].as_u64() @@ -1040,6 +1762,85 @@ impl Actor { _ => (), } } + if self.pinned.is_some() { + let is_startup = + matches!(pending.method.as_str(), "session/new" | "session/resume"); + if is_startup { + let waiters = if let Some(pinned) = &mut self.pinned { + pinned.startup_driver = None; + std::mem::take(&mut pinned.waiting_startups) + } else { + Vec::new() + }; + if let Some(result) = message.get("result").cloned() { + if self.pinned.as_ref().is_some_and(|p| { + p.attachments + .get(&pending.attachment) + .is_some_and(|a| !a.closing) + }) { + self.deliver_pinned_startup( + &pending.attachment, + result.clone(), + pending.original, + &pending.replay, + ); + } + for waiter in waiters { + if self.pinned.as_ref().is_some_and(|p| { + p.attachments + .get(&waiter.attachment) + .is_some_and(|a| !a.closing) + }) { + self.deliver_pinned_startup( + &waiter.attachment, + result.clone(), + waiter.request_id, + &waiter.replay, + ); + } + } + } else { + let error_obj = message.get("error").cloned().unwrap_or_else(|| { + object([ + ("code", (-32000).into()), + ("message", "session startup failed".into()), + ]) + }); + if self.pinned.as_ref().is_some_and(|p| { + p.attachments + .get(&pending.attachment) + .is_some_and(|a| !a.closing) + }) { + self.push_pinned_startup_error( + &pending.attachment, + pending.original, + error_obj.clone(), + ); + } + for waiter in waiters { + if self.pinned.as_ref().is_some_and(|p| { + p.attachments + .get(&waiter.attachment) + .is_some_and(|a| !a.closing) + }) { + self.push_pinned_startup_error( + &waiter.attachment, + waiter.request_id, + error_obj.clone(), + ); + } + } + } + } else if self.pinned.as_ref().is_some_and(|p| { + p.attachments + .get(&pending.attachment) + .is_some_and(|a| !a.closing) + }) { + message["id"] = pending.original; + self.push_pinned_attachment(&pending.attachment, message); + } + return None; + } if self .attachment .as_ref() @@ -1052,7 +1853,7 @@ impl Actor { let messages = self.startup_messages( message["result"].clone(), message["id"].clone(), - pending.replay, + &pending.replay, &pending.attachment, ); match messages { @@ -1099,7 +1900,7 @@ impl Actor { ( "error", object([ - ("code", (-32000).into()), + ("code", error.jsonrpc_code().into()), ("data", error.data()), ("message", error.1.into()), ]), @@ -1117,16 +1918,43 @@ impl Actor { &self, mut result: Value, id: Value, - replay: bool, + replay: &ReplayMode, attachment: &str, ) -> Result, Failure> { - if replay && !self.replay_complete { - return Err(Failure::replay("full live replay is unavailable")); - } - let mut messages: Vec = if replay { - self.journal.iter().cloned().collect() - } else { - Vec::new() + let (mut messages, history_available): (Vec, bool) = match replay { + ReplayMode::None => (Vec::new(), false), + ReplayMode::Start => { + if !self.replay_complete { + return Err(Failure::replay("full live replay is unavailable")); + } + (self.journal.iter().cloned().collect(), true) + } + ReplayMode::CurrentTurn => { + if let Some(start_seq) = self.current_turn_start { + if start_seq < self.journal_base_seq { + return Err(Failure::replay("current turn replay is unavailable")); + } + let offset = (start_seq - self.journal_base_seq) as usize; + (self.journal.iter().skip(offset).cloned().collect(), true) + } else { + (Vec::new(), true) + } + } + ReplayMode::Message { message_id } => { + let position = self.journal.iter().position(|entry| { + entry["method"] == "session/update" + && entry["params"]["sessionId"] == self.id + && entry["params"]["update"]["sessionUpdate"] == "user_message" + && entry["params"]["update"]["messageId"].as_str() + == Some(message_id.as_str()) + }); + let Some(position) = position else { + return Err(Failure::invalid_params( + "invalid or no longer retained ACP replay cursor", + )); + }; + (self.journal.iter().skip(position).cloned().collect(), true) + } }; let options = result .get("configOptions") @@ -1151,7 +1979,7 @@ impl Actor { result["sessionId"] = self.id.clone().into(); result["_meta"]["kit/gateway"] = object([ ("attachment", attachment.into()), - ("historyAvailable", replay.into()), + ("historyAvailable", history_available.into()), ("stateSnapshot", true.into()), ("configSnapshot", true.into()), ]); @@ -1211,6 +2039,9 @@ impl Actor { } fn command(&mut self, request: Request, writes: &mpsc::Sender) -> ResultValue { + if self.pinned.is_some() { + return self.command_pinned(request, writes); + } let closing = self.closed || self.pending.values().any(|p| p.method == "session/close"); if closing && !matches!(request, Request::Poll { .. } | Request::Detach { .. }) @@ -1223,10 +2054,13 @@ impl Actor { if let Request::Attach { replace, replay, + replay_mode, startup, .. } = request { + let replay_mode = effective_replay_mode(replay, replay_mode); + let replay = matches!(replay_mode, ReplayMode::Start); // A live runtime owns its MCP configuration. Do not replace the // controller and then silently ignore a new configuration. if (self.session_result.is_some() @@ -1329,6 +2163,7 @@ impl Actor { events: VecDeque::new(), bytes: 0, live: false, + closing: false, }; let started = if let (Some(startup), Some(result)) = (startup, self.session_result.clone()) { @@ -1336,7 +2171,7 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - for message in self.startup_messages(result, request_id, replay, &id)? { + for message in self.startup_messages(result, request_id, &replay_mode, &id)? { if !attachment.push(message) { return Err(Failure::replay( "session snapshot exceeds the gateway limit", @@ -1530,9 +2365,14 @@ impl Actor { { return Err(Failure::conflict("duplicate pending request id")); } - let replay = method == "session/new" - || message["params"]["replayFrom"] == object([("type", "start".into())]); - if startup && replay && !self.replay_complete { + let replay = if method == "session/new" + || message["params"]["replayFrom"] == object([("type", "start".into())]) + { + ReplayMode::Start + } else { + ReplayMode::None + }; + if startup && matches!(replay, ReplayMode::Start) && !self.replay_complete { return Err(Failure::replay("full live replay is unavailable")); } let cached = match method.as_str() { @@ -1553,7 +2393,7 @@ impl Actor { let Some(id) = original else { return Err(Failure::bad("session startup requires a request id")); }; - let messages = self.startup_messages(result, id, replay, &attachment)?; + let messages = self.startup_messages(result, id, &replay, &attachment)?; let fits = self.attachment.as_ref().is_some_and(|a| { a.events.len() + messages.len() <= MAX_QUEUE && a.bytes @@ -1676,6 +2516,725 @@ impl Actor { _ => Err(Failure::bad("invalid actor operation")), } } + + fn command_pinned( + &mut self, + request: Request, + writes: &mpsc::Sender, + ) -> ResultValue { + if let Request::Attach { + replay, + replay_mode, + startup, + .. + } = request + { + let replay_mode = effective_replay_mode(replay, replay_mode); + let startup_in_flight = self + .pinned + .as_ref() + .is_some_and(|p| p.startup_driver.is_some()) + || self.pending.values().any(|pending| { + matches!(pending.method.as_str(), "session/new" | "session/resume") + }); + if (self.session_result.is_some() || startup_in_flight) + && startup.as_ref().is_some_and(|message| { + message["params"].get("mcpServers").is_some_and(|servers| { + !servers.is_null() && servers != &Value::Array(Vec::new()) + }) + }) + { + return Err(Failure::conflict( + "resident session retains its MCP servers; omit mcpServers or send an empty array; use _kit/session/update_mcp to add or update client servers", + )); + } + if matches!(replay_mode, ReplayMode::Start) && !self.replay_complete { + return Err(Failure::replay( + "live replay limit reached; transcript is durable but a full live reattach is unavailable", + )); + } + let id = crate::session::new_id(); + let mut attachment = Attachment { + id: id.clone(), + touched: Instant::now(), + next: 0, + events: VecDeque::new(), + bytes: 0, + live: false, + closing: false, + }; + let started = if let (Some(startup_msg), Some(result)) = + (startup.as_ref(), self.session_result.clone()) + { + let request_id = startup_msg + .get("id") + .cloned() + .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + let messages = self.startup_messages(result, request_id, &replay_mode, &id)?; + let pending_requests = self + .pinned + .as_ref() + .map(PinnedState::pending_request_messages) + .unwrap_or_default(); + let total_count = messages.len() + pending_requests.len(); + let total_bytes: usize = + messages.iter().map(|m| m.to_string().len()).sum::() + + pending_requests + .iter() + .map(|(_, m)| m.to_string().len()) + .sum::(); + if total_count > MAX_QUEUE || total_bytes > MAX_REPLAY { + return Err(Failure::replay( + "session snapshot exceeds the gateway limit", + )); + } + for message in messages { + if !attachment.push(message) { + return Err(Failure::replay( + "session snapshot exceeds the gateway limit", + )); + } + } + let mut registered_relays = Vec::new(); + for (relay_id, req_msg) in pending_requests { + if !attachment.push(req_msg) { + return Err(Failure::replay( + "session snapshot exceeds the gateway limit", + )); + } + registered_relays.push(relay_id); + } + attachment.live = true; + if let Some(pinned) = &mut self.pinned { + for relay_id in registered_relays { + if let Some(req) = pinned.client_requests.get_mut(&relay_id) { + req.targets.insert(id.clone()); + } + } + pinned.attachments.insert(id.clone(), attachment); + } + true + } else if let Some(startup_msg) = startup + && startup_in_flight + { + let request_id = startup_msg + .get("id") + .cloned() + .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + if let Some(pinned) = &mut self.pinned { + pinned.waiting_startups.push(WaitingStartup { + attachment: id.clone(), + request_id, + replay: replay_mode, + }); + pinned.attachments.insert(id.clone(), attachment); + } + true + } else { + if let Some(pinned) = &mut self.pinned { + if self.session_result.is_none() && pinned.startup_driver.is_none() { + pinned.startup_driver = Some(id.clone()); + } + pinned.attachments.insert(id.clone(), attachment); + } + false + }; + return Ok(object([ + ("started", started.into()), + ("attachment", id.into()), + ("lease_seconds", LEASE.as_secs().into()), + ])); + } + + let token = match &request { + Request::Poll { attachment, .. } + | Request::Send { attachment, .. } + | Request::Detach { attachment, .. } => attachment.clone(), + _ => return Err(Failure::bad("invalid actor operation")), + }; + + if let Request::Detach { .. } = request { + let mut failed_waiters = Vec::new(); + if let Some(pinned) = &mut self.pinned { + pinned.attachments.remove(&token); + pinned.take_overflow(&token); + pinned.waiting_startups.retain(|w| w.attachment != token); + pinned.remove_target_from_requests(&token); + if pinned.startup_driver.as_deref() == Some(token.as_str()) { + pinned.startup_driver = None; + let startup_sent = self + .pending + .values() + .any(|p| matches!(p.method.as_str(), "session/new" | "session/resume")); + if self.session_result.is_none() && !startup_sent { + failed_waiters = std::mem::take(&mut pinned.waiting_startups); + } + } + } + for waiter in failed_waiters { + self.push_pinned_startup_error( + &waiter.attachment, + waiter.request_id, + object([ + ("code", (-32000).into()), + ("message", "session startup interrupted; retry".into()), + ("data", Failure::unavailable("startup interrupted").data()), + ]), + ); + } + // Pinned mode never withdraws held prompts on detach. + return Ok(object([])); + } + + if !self + .pinned + .as_ref() + .is_some_and(|p| p.attachments.contains_key(&token)) + { + let overflowed = if matches!(request, Request::Poll { .. }) { + self.pinned + .as_mut() + .is_some_and(|p| p.take_overflow(&token)) + } else { + self.pinned + .as_ref() + .is_some_and(|p| p.is_overflowed(&token)) + }; + if overflowed { + return Err(Failure( + StatusCode::CONFLICT, + "attachment queue overflowed; reconnect".into(), + "queue_overflow", + )); + } + return Err(Failure( + StatusCode::CONFLICT, + "attachment is not active; reconnect".into(), + "attachment_closed", + )); + } + + match request { + Request::Poll { cursor, .. } => { + let Some(pinned) = &mut self.pinned else { + return Err(Failure::unavailable("pinned state missing")); + }; + let Some(attachment) = pinned.attachments.get_mut(&token) else { + return Err(Failure( + StatusCode::CONFLICT, + "attachment is not active; reconnect".into(), + "attachment_closed", + )); + }; + attachment.touched = Instant::now(); + if cursor > attachment.next { + return Err(Failure::bad("invalid event cursor")); + } + while attachment + .events + .front() + .is_some_and(|(sequence, _)| *sequence <= cursor) + { + if let Some((_, message)) = attachment.events.pop_front() { + attachment.bytes -= message.to_string().len(); + } + } + let events: Vec<_> = attachment + .events + .iter() + .take(128) + .map(|(sequence, message)| { + object([("cursor", (*sequence).into()), ("message", message.clone())]) + }) + .collect(); + let closed = (self.closed || attachment.closing) && attachment.events.len() <= 128; + if closed && attachment.closing { + pinned.attachments.remove(&token); + } + Ok(object([ + ("closed", closed.into()), + ("events", events.into()), + ])) + } + Request::Send { + attachment, + mut message, + charge, + .. + } => { + if let Some(pinned) = &mut self.pinned + && let Some(a) = pinned.attachments.get_mut(&attachment) + { + if a.closing { + return Err(Failure::conflict("attachment is closing")); + } + a.touched = Instant::now(); + } + if !message.is_object() || message["jsonrpc"] != "2.0" { + return Err(Failure::bad("invalid ACP message")); + } + // Client-to-agent JSON-RPC response for a relayed request. + if message.get("method").is_none() + && (message.get("result").is_some_and(|v| !v.is_null()) + || message.get("error").is_some_and(Value::is_object)) + { + return self.handle_pinned_client_response( + &attachment, + message, + charge, + writes, + ); + } + let method = message["method"] + .as_str() + .ok_or_else(|| Failure::bad("ACP method required"))? + .to_owned(); + let original = message.get("id").cloned(); + if !message["params"].is_object() { + return Err(Failure::bad("invalid ACP message")); + } + if let Some(session) = message["params"].get("sessionId") + && session != &Value::String(self.id.clone()) + { + return Err(Failure::bad("ACP session does not match gateway session")); + } + if method == "_kit/session/update_mcp" && message["params"]["sessionId"] != self.id + { + return Err(Failure::bad("ACP session does not match gateway session")); + } + if method == "kit/background/cancel" && message["params"]["session_id"] != self.id { + return Err(Failure::bad("ACP session does not match gateway session")); + } + // Explicit $/cancel_request still withdraws this attachment's own held prompt. + if method == "$/cancel_request" { + if original.is_some() { + return Err(Failure::bad("request cancellation must be a notification")); + } + let Some(id) = message["params"].get("requestId").filter(|id| { + id.is_string() || id.as_i64().is_some() || id.as_u64().is_some() + }) else { + return Err(Failure::bad("valid cancellation requestId required")); + }; + let Some((&child_id, pending)) = + self.pending.iter_mut().find(|(_, pending)| { + pending.attachment == attachment + && pending.original == *id + && pending.method == "session/prompt" + }) + else { + return Ok(object([])); + }; + match writes.try_reserve() { + Ok(permit) => self.send_withdrawal(child_id, permit), + Err(mpsc::error::TrySendError::Full(())) => { + pending.withdrawal_pending = true; + } + Err(mpsc::error::TrySendError::Closed(())) => { + return Err(Failure::unavailable("child input writer closed")); + } + } + return Ok(object([])); + } + // In pinned mode, session/close detaches ONLY this client and never ends the session. + if method == "session/close" { + let Some(id) = original else { + return Err(Failure::bad("session close requires a request id")); + }; + if let Some(pinned) = &mut self.pinned { + pinned.remove_target_from_requests(&attachment); + pinned + .waiting_startups + .retain(|w| w.attachment != attachment); + if pinned.startup_driver.as_deref() == Some(attachment.as_str()) { + pinned.startup_driver = None; + } + if let Some(a) = pinned.attachments.get_mut(&attachment) { + a.live = false; + a.closing = true; + } + } + self.push_pinned_attachment( + &attachment, + object([ + ("jsonrpc", "2.0".into()), + ("id", id), + ("result", object([])), + ]), + ); + return Ok(object([])); + } + if !matches!( + method.as_str(), + "initialize" + | "session/new" + | "session/resume" + | "session/prompt" + | "session/cancel" + | "kit/background/cancel" + | "kit/session/status" + | "session/set_config_option" + | "_kit/session/update_mcp" + ) { + return Err(Failure::bad( + "ACP method is not supported by the gateway; disconnect to detach", + )); + } + let startup = matches!(method.as_str(), "session/new" | "session/resume"); + let replay = if startup { + if original.is_none() { + return Err(Failure::bad("session startup requires a request id")); + } + if self + .pinned + .as_ref() + .and_then(|p| p.attachments.get(&attachment)) + .is_some_and(|a| a.live) + { + return Err(Failure::conflict("attachment already opened its session")); + } + parse_replay_mode( + message["params"].get("replayFrom"), + &self.id, + true, + method == "session/new", + )? + } else { + ReplayMode::None + }; + if let Some(id) = &original + && self + .pending + .values() + .any(|p| p.attachment == attachment && p.original == *id) + { + return Err(Failure::conflict("duplicate pending request id")); + } + if startup && matches!(replay, ReplayMode::Start) && !self.replay_complete { + return Err(Failure::replay("full live replay is unavailable")); + } + let cached = match method.as_str() { + "initialize" => self.initialized.clone(), + "session/new" | "session/resume" => self.session_result.clone(), + _ => None, + }; + if let Some(result) = cached { + if startup { + if message["params"].get("mcpServers").is_some_and(|servers| { + !servers.is_null() && servers != &Value::Array(Vec::new()) + }) { + return Err(Failure::conflict( + "resident session retains its MCP servers; omit mcpServers or send an empty array; use _kit/session/update_mcp to add or update client servers", + )); + } + let Some(id) = original else { + return Err(Failure::bad("session startup requires a request id")); + }; + let messages = self.startup_messages(result, id, &replay, &attachment)?; + let pending_requests = self + .pinned + .as_ref() + .map(PinnedState::pending_request_messages) + .unwrap_or_default(); + let total_count = messages.len() + pending_requests.len(); + let total_bytes: usize = + messages.iter().map(|m| m.to_string().len()).sum::() + + pending_requests + .iter() + .map(|(_, m)| m.to_string().len()) + .sum::(); + let fits = self + .pinned + .as_ref() + .and_then(|p| p.attachments.get(&attachment)) + .is_some_and(|a| { + a.events.len() + total_count <= MAX_QUEUE + && a.bytes + total_bytes <= MAX_REPLAY + }); + if !fits { + return Err(Failure::replay( + "session snapshot exceeds the gateway limit", + )); + } + for update in messages { + self.push_pinned_attachment(&attachment, update); + } + for (relay_id, req_msg) in pending_requests { + if self.push_pinned_attachment(&attachment, req_msg) + && let Some(pinned) = &mut self.pinned + && let Some(req) = pinned.client_requests.get_mut(&relay_id) + { + req.targets.insert(attachment.clone()); + } + } + if let Some(pinned) = &mut self.pinned + && let Some(a) = pinned.attachments.get_mut(&attachment) + { + a.live = true; + } + } else if let Some(id) = original { + self.push_pinned_attachment( + &attachment, + object([("jsonrpc", "2.0".into()), ("id", id), ("result", result)]), + ); + } + return Ok(object([])); + } + let stop = method == "session/cancel" && original.is_none(); + if !stop && self.pending.len() >= 128 { + return Err(Failure::unavailable("too many pending ACP requests")); + } + if startup { + if self + .pending + .values() + .any(|p| matches!(p.method.as_str(), "session/new" | "session/resume")) + { + if let Some(id) = original + && let Some(pinned) = &mut self.pinned + { + pinned.waiting_startups.push(WaitingStartup { + attachment, + request_id: id, + replay, + }); + return Ok(object([])); + } + return Err(Failure::conflict( + "session startup is pending; reconnect after it settles", + )); + } + message["params"]["cwd"] = + Value::String(self.root.to_string_lossy().into_owned()); + message["params"]["additionalDirectories"] = Value::Array(Vec::new()); + if message["params"]["mcpServers"].is_null() { + message["params"]["mcpServers"] = Value::Array(Vec::new()); + } + if self.restore { + message["method"] = Value::String("session/resume".into()); + message["params"]["sessionId"] = Value::String(self.id.clone()); + message["params"]["replayFrom"] = object([("type", "start".into())]); + } else { + message["method"] = Value::String("session/new".into()); + if let Some(params) = message["params"].as_object_mut() { + params.remove("sessionId"); + params.remove("replayFrom"); + } + } + } + // Advertise form elicitation capability to the child ONLY in pinned mode. + if method == "initialize" { + message["params"]["capabilities"] = + object([("elicitation", object([("form", object([]))]))]); + } + let pending = if let Some(original) = original { + self.serial = self + .serial + .checked_add(1) + .ok_or_else(|| Failure::unavailable("request id exhausted"))?; + message["id"] = Value::from(self.serial); + let explicit_delivery = method == "session/prompt" + && matches!( + message["params"]["delivery"].as_str(), + Some("steer" | "queue") + ); + Some(Pending { + attachment, + original, + method, + explicit_delivery, + withdrawal_pending: false, + replay, + }) + } else { + None + }; + let permit = loop { + let permit = writes.try_reserve().map_err(|_| { + Failure::unavailable("child input queue unavailable; message not accepted") + })?; + if stop { + break permit; + } + let Some(id) = self.next_withdrawal() else { + break permit; + }; + self.send_withdrawal(id, permit); + }; + let mut withdrawals = Vec::new(); + if stop { + withdrawals.extend( + self.pending + .iter() + .filter_map(|(&id, pending)| pending.withdrawal_pending.then_some(id)), + ); + withdrawals.sort_unstable(); + for id in &withdrawals { + if let Some(pending) = self.pending.get_mut(id) { + pending.withdrawal_pending = false; + } + } + } + permit.send(ChildWrite { + withdrawals, + message, + _charge: charge, + }); + if let Some(pending) = pending { + self.pending.insert(self.serial, pending); + } + Ok(object([])) + } + _ => Err(Failure::bad("invalid actor operation")), + } + } + + fn handle_pinned_client_response( + &mut self, + attachment: &str, + message: Value, + charge: Option>, + writes: &mpsc::Sender, + ) -> ResultValue { + let Some(relay_id) = message["id"].as_str().map(str::to_owned) else { + return Ok(object([])); + }; + let Some((method, is_target)) = self.pinned.as_ref().and_then(|p| { + p.client_requests + .get(&relay_id) + .map(|req| (req.method.clone(), req.targets.contains(attachment))) + }) else { + // Already resolved, cancelled, or expired; ignore late duplicate race. + return Ok(object([])); + }; + if !is_target { + return Ok(object([])); + } + if let Some(error) = message.get("error").filter(|v| v.is_object()) { + let code = error["code"].as_i64(); + let remaining_others = self + .pinned + .as_ref() + .and_then(|p| p.client_requests.get(&relay_id)) + .map(|req| req.targets.iter().any(|t| t != attachment)) + .unwrap_or(false); + if remaining_others { + if let Some(pinned) = &mut self.pinned + && let Some(req) = pinned.client_requests.get_mut(&relay_id) + { + req.targets.remove(attachment); + } + return Ok(object([])); + } + let permit = writes.try_reserve().map_err(|_| { + Failure::unavailable("child input queue unavailable; response not accepted") + })?; + let Some(req) = self + .pinned + .as_mut() + .and_then(|p| p.client_requests.remove(&relay_id)) + else { + return Ok(object([])); + }; + let child_error = if code == Some(-32601) { + object([ + ("code", (-32601).into()), + ("message", "gateway has no client-side services".into()), + ]) + } else { + error.clone() + }; + permit.send(ChildWrite { + withdrawals: Vec::new(), + message: object([ + ("jsonrpc", "2.0".into()), + ("id", req.child_id), + ("error", child_error), + ]), + _charge: charge, + }); + return Ok(object([])); + } + let Some(result) = message.get("result") else { + return Err(Failure::bad("invalid client response")); + }; + if !is_valid_client_result(&method, result) { + return Err(Failure::bad("invalid response for relayed client request")); + } + let permit = writes.try_reserve().map_err(|_| { + Failure::unavailable("child input queue unavailable; response not accepted") + })?; + let Some(req) = self + .pinned + .as_mut() + .and_then(|p| p.client_requests.remove(&relay_id)) + else { + return Ok(object([])); + }; + permit.send(ChildWrite { + withdrawals: Vec::new(), + message: object([ + ("jsonrpc", "2.0".into()), + ("id", req.child_id), + ("result", result.clone()), + ]), + _charge: charge, + }); + let cancel = cancel_request_message(Value::String(relay_id)); + for target in req.targets { + if target != attachment { + self.push_pinned_attachment(&target, cancel.clone()); + } + } + Ok(object([])) + } +} + +fn cancel_request_message(request_id: Value) -> Value { + object([ + ("jsonrpc", "2.0".into()), + ("method", "$/cancel_request".into()), + ("params", object([("requestId", request_id)])), + ]) +} + +fn incoming_transport_closed_reply(child_id: Value, method: &str) -> Value { + object([ + ("jsonrpc", "2.0".into()), + ("id", child_id), + ( + "error", + object([ + ("code", (-32603).into()), + ("message", "Incoming transport closed".into()), + ( + "data", + object([ + ("reason", "incoming_transport_closed".into()), + ("method", method.into()), + ]), + ), + ]), + ), + ]) +} + +fn is_valid_client_result(method: &str, result: &Value) -> bool { + match method { + "elicitation/create" => { + let Some(action) = result.get("action").and_then(Value::as_str) else { + return false; + }; + match action { + "accept" => result + .get("content") + .is_none_or(|value| value.is_object() || value.is_null()), + "decline" | "cancel" => true, + _ => false, + } + } + "session/request_permission" => result.get("outcome").is_some_and(Value::is_object), + _ => result.is_object(), + } } async fn write_message( stdin: &mut (impl tokio::io::AsyncWrite + Unpin), @@ -1688,5 +3247,8 @@ async fn write_message( .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "child stdin stalled"))? } #[cfg(test)] +#[path = "gateway/pinned_tests.rs"] +mod pinned_tests; +#[cfg(test)] #[path = "gateway/tests.rs"] mod tests; diff --git a/src/gateway/http_boundary.rs b/src/gateway/http_boundary.rs index cdea2614..8252a4e3 100644 --- a/src/gateway/http_boundary.rs +++ b/src/gateway/http_boundary.rs @@ -1,10 +1,67 @@ //! Bounded HTTP admission outside the SDK's native graceful teardown. use super::*; -use axum::http::{Method, header}; +use axum::{ + body::{Body, Bytes}, + http::{Method, header}, +}; +use std::{ + future::Future as _, + pin::Pin, + task::{Context, Poll}, +}; use tokio::sync::Semaphore; const MAX_BODY: usize = 1024 * 1024; const MAX_REQUESTS: usize = 32; +pub(super) const SSE_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15); + +struct SseKeepAliveStream { + inner: Pin>, + interval: Duration, + timer: Pin>, +} + +impl futures_util::Stream for SseKeepAliveStream +where + S: futures_util::Stream> + Send, +{ + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if let Poll::Ready(item) = self.inner.as_mut().poll_next(cx) { + if item.is_some() { + let deadline = tokio::time::Instant::now() + self.interval; + self.timer.as_mut().reset(deadline); + } + return Poll::Ready(item); + } + if self.timer.as_mut().poll(cx).is_ready() { + let deadline = tokio::time::Instant::now() + self.interval; + self.timer.as_mut().reset(deadline); + return Poll::Ready(Some(Ok(Bytes::from_static(b":\n\n")))); + } + Poll::Pending + } +} + +pub(super) fn wrap_sse_keep_alive(response: Response, interval: Duration) -> Response { + let is_sse = response.status() == StatusCode::OK + && response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("text/event-stream")); + if !is_sse { + return response; + } + let (parts, body) = response.into_parts(); + let stream = SseKeepAliveStream { + inner: Box::pin(body.into_data_stream()), + interval, + timer: Box::pin(tokio::time::sleep(interval)), + }; + Response::from_parts(parts, Body::from_stream(stream)) +} pub(super) struct Boundary { // Each outer POST/DELETE owns one permit until its HTTP future finishes @@ -29,7 +86,8 @@ pub(super) async fn handle( return next.run(request).await; } if !matches!(*request.method(), Method::POST | Method::DELETE) { - return next.run(request).await; + let response = next.run(request).await; + return wrap_sse_keep_alive(response, SSE_KEEP_ALIVE_INTERVAL); } let Ok(permit) = boundary.requests.clone().try_acquire_owned() else { return ( @@ -168,4 +226,35 @@ mod tests { StatusCode::ACCEPTED ); } + + #[tokio::test(start_paused = true)] + async fn idle_sse_stream_emits_keep_alive_comment_within_interval() { + use futures_util::StreamExt as _; + + let sse_handler = || async { + let body = + Body::from_stream(futures_util::stream::pending::>()); + let mut response = Response::new(body); + response.headers_mut().insert( + header::CONTENT_TYPE, + header::HeaderValue::from_static("text/event-stream"), + ); + response + }; + let app = wrapped(Router::new().route("/acp/v2", axum::routing::get(sse_handler))); + let response = app + .oneshot(request(Method::GET, Body::empty())) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let mut stream = response.into_body().into_data_stream(); + + let mut next_chunk = Box::pin(stream.next()); + assert!(futures_util::poll!(&mut next_chunk).is_pending()); + tokio::time::advance(SSE_KEEP_ALIVE_INTERVAL - Duration::from_secs(1)).await; + assert!(futures_util::poll!(&mut next_chunk).is_pending()); + tokio::time::advance(Duration::from_secs(1)).await; + let chunk = next_chunk.await.unwrap().unwrap(); + assert_eq!(&chunk[..], b":\n\n"); + } } diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 2714c2ee..66332a09 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -14,6 +14,7 @@ pub(super) struct Connection { gateway: Arc, initialize: Option<(Value, Arc)>, controls: HashMap, + closing_connection: bool, } struct Control { @@ -115,6 +116,7 @@ impl Connection { gateway, initialize: None, controls: HashMap::new(), + closing_connection: false, } } @@ -173,6 +175,20 @@ impl Connection { ); } self.initialize = Some((message.clone(), Arc::clone(charge))); + let mut gateway_meta = object([ + ("experimental", true.into()), + ("transport", "bounded-http".into()), + ("maxFrameBytes", 1_048_576.into()), + ("coreBufferedBytesPerDirection", 16_777_216.into()), + ("httpEgressBytesPerConnection", 4_194_304.into()), + ("liveReplayLimitBytes", MAX_REPLAY.into()), + ("liveReplayLimitEvents", (MAX_QUEUE - 3).into()), + ]); + if let Some(pinned) = &self.gateway.pinned + && let Some(meta) = gateway_meta.as_object_mut() + { + meta.insert("pinnedSession".into(), pinned.session_id.clone().into()); + } return Ok(Some(object([ ("protocolVersion", 2.into()), ( @@ -183,21 +199,7 @@ impl Connection { ]), ), ("capabilities", capabilities), - ( - "_meta", - object([( - "kit/gateway", - object([ - ("experimental", true.into()), - ("transport", "bounded-http".into()), - ("maxFrameBytes", 1_048_576.into()), - ("coreBufferedBytesPerDirection", 16_777_216.into()), - ("httpEgressBytesPerConnection", 4_194_304.into()), - ("liveReplayLimitBytes", MAX_REPLAY.into()), - ("liveReplayLimitEvents", (MAX_QUEUE - 3).into()), - ]), - )]), - ), + ("_meta", object([("kit/gateway", gateway_meta)])), ]))); } if self.initialize.is_none() { @@ -229,7 +231,12 @@ impl Connection { // A late withdrawal cannot affect a replaced or exited resident. // Let the normal flush settle only this session's pending calls. match control.send(message, Arc::clone(charge)).await { - Ok(_) | Err(Failure(_, _, "controller_replaced" | "unavailable")) => {} + Ok(_) + | Err(Failure( + _, + _, + "controller_replaced" | "unavailable" | "queue_overflow" | "attachment_closed", + )) => {} Err(error) => return Err(error), } return Ok(None); @@ -268,15 +275,23 @@ impl Connection { } if matches!(method.as_str(), "session/new" | "session/resume") { let resume = method == "session/resume"; + let pinned = self.gateway.pinned.as_ref(); let id = if resume { - Some( - message["params"]["sessionId"] - .as_str() - .ok_or_else(|| Failure::bad("sessionId required"))? - .to_owned(), - ) + let requested = message["params"]["sessionId"] + .as_str() + .ok_or_else(|| Failure::bad("sessionId required"))? + .to_owned(); + if let Some(pinned) = pinned + && requested != pinned.session_id + { + return Err(Failure::bad(format!( + "gateway is pinned to session {}; other session ids are not allowed", + pinned.session_id + ))); + } + Some(requested) } else { - None + pinned.map(|pinned| pinned.session_id.clone()) }; if id.as_ref().is_some_and(|id| self.controls.contains_key(id)) { return Err(Failure::conflict("connection already controls session")); @@ -306,14 +321,18 @@ impl Connection { { params.remove("replayFrom"); } - if message["params"] - .get("replayFrom") - .is_some_and(|v| v != &object([("type", "start".into())])) - { - return Err(Failure::bad("unsupported replay cursor")); - } + let replay_session_id = id.as_deref().unwrap_or(""); + let replay_mode = parse_replay_mode( + message["params"].get("replayFrom"), + replay_session_id, + pinned.is_some(), + !resume, + )?; let root = match message["params"]["cwd"].as_str() { Some(root) => PathBuf::from(root), + None if pinned.is_some() && self.gateway.roots.len() == 1 => { + self.gateway.roots[0].clone() + } None if resume => { let catalog = self.operation(Request::List).await?; catalog["sessions"] @@ -354,8 +373,9 @@ impl Connection { .send(Envelope { request: Request::Attach { session: session.clone(), - replace: resume, - replay: !resume || message["params"].get("replayFrom").is_some(), + replace: resume && pinned.is_none(), + replay: matches!(replay_mode, ReplayMode::Start), + replay_mode: Some(replay_mode), startup: Some(message.clone()), }, reply, @@ -425,6 +445,14 @@ impl Connection { let id = message["params"][session_field] .as_str() .ok_or_else(|| Failure::bad(format!("{session_field} required")))?; + if let Some(pinned) = &self.gateway.pinned + && id != pinned.session_id + { + return Err(Failure::bad(format!( + "gateway is pinned to session {}; other session ids are not allowed", + pinned.session_id + ))); + } let control = self .controls .get_mut(id) @@ -502,6 +530,8 @@ impl Connection { // Settle that controller's pending calls explicitly before forgetting it. for (id, error) in failed { if let Some(mut control) = self.controls.remove(&id) { + let overflowed_pinned = + self.gateway.pinned.is_some() && error.2 == "queue_overflow"; send( channel, object([ @@ -533,7 +563,7 @@ impl Connection { ( "error", object([ - ("code", (-32000).into()), + ("code", error.jsonrpc_code().into()), ("message", error.1.clone().into()), ("data", error.data()), ]), @@ -543,6 +573,9 @@ impl Connection { ) .await?; } + if overflowed_pinned { + self.closing_connection = true; + } } } Ok(()) @@ -571,6 +604,33 @@ impl Connection { _ => return Err(channel.tx.fail("unsupported ACP frame")), }; let message = serde_json::to_value(message).map_err(sdk_error)?; + // In pinned mode, forward client-to-agent JSON-RPC responses for relayed requests. + if self.gateway.pinned.is_some() + && message.get("method").is_none() + && (message.get("result").is_some_and(|v| !v.is_null()) + || message.get("error").is_some_and(Value::is_object)) + { + if let Some(control) = self + .gateway + .pinned + .as_ref() + .and_then(|pinned| self.controls.get_mut(&pinned.session_id)) + { + match control.send(message, Arc::clone(&charged_frame)).await { + Ok(_) | Err(Failure(_, _, "queue_overflow" | "attachment_closed")) => {} + Err(Failure(_, message, "unavailable")) => { + return Err(channel.tx.fail(&message)); + } + Err(_) => {} + } + } + self.flush(&channel).await?; + drop(charged_frame); + if self.closing_connection { + return Ok(()); + } + continue; + } let id = message.get("id").cloned(); let response = match self.request(message, &channel, &charged_frame).await { Ok(Some(result)) => id.map(|id| { @@ -590,7 +650,7 @@ impl Connection { ( "error", object([ - ("code", (-32000).into()), + ("code", error.jsonrpc_code().into()), ("data", error.data()), ("message", error.1.into()), ]), @@ -600,10 +660,16 @@ impl Connection { }; self.flush_with_response(&channel, response).await?; drop(charged_frame); + if self.closing_connection { + return Ok(()); + } } // Drain after every inbound frame as well as idle ticks; a busy // client cannot starve updates or let its own controller lease lapse. self.flush(&channel).await?; + if self.closing_connection { + return Ok(()); + } } } } @@ -695,6 +761,7 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), + pinned: None, sessions: Mutex::new(HashMap::new()), }); let connection = Connection::new(gateway); @@ -803,6 +870,7 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), + pinned: None, sessions: Mutex::new(HashMap::new()), }); let mut connection = Connection::new(gateway); @@ -935,6 +1003,7 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), + pinned: None, sessions: Mutex::new(HashMap::new()), }); let (sender, mut receiver) = mpsc::channel::(2); @@ -997,6 +1066,7 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), + pinned: None, sessions: Mutex::new(HashMap::new()), }); let mut connection = Connection::new(gateway); @@ -1109,6 +1179,7 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), + pinned: None, sessions: Mutex::new(HashMap::new()), }); let (mut channel, mut peer) = BoundedChannel::duplex(ChannelLimits::default()).unwrap(); diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs new file mode 100644 index 00000000..e51819e5 --- /dev/null +++ b/src/gateway/pinned_tests.rs @@ -0,0 +1,1709 @@ +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::disallowed_methods, + clippy::disallowed_macros +)] +use super::*; +use serde_json::json; +use tempfile::TempDir; + +struct PinnedHarness { + _directory: TempDir, + client: reqwest::Client, + url: String, + gateway: Arc, + server: tokio::task::JoinHandle<()>, +} + +impl Drop for PinnedHarness { + fn drop(&mut self) { + self.server.abort(); + } +} + +impl PinnedHarness { + async fn new(session_id: &str, client_request_timeout: Duration) -> Self { + let directory = tempfile::tempdir().unwrap(); + let token = directory.path().join("token"); + std::fs::write(&token, "pinned-secret").unwrap(); + let gateway = Arc::new(Gateway { + stopping: AtomicBool::new(false), + token: BearerToken::load(&token).unwrap(), + roots: vec![directory.path().canonicalize().unwrap()], + pinned: Some(PinnedConfig { + session_id: session_id.to_owned(), + client_request_timeout, + }), + sessions: Mutex::new(HashMap::new()), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/acp/v2", listener.local_addr().unwrap()); + let app = router(gateway.clone()).unwrap(); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + Self { + _directory: directory, + client: reqwest::Client::new(), + url, + gateway, + server, + } + } + + async fn child_source(&self, id: &str, source: &str, args: &[String]) { + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", source]) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let timeout = self + .gateway + .pinned + .as_ref() + .map(|p| p.client_request_timeout) + .unwrap_or(DEFAULT_CLIENT_REQUEST_TIMEOUT); + let actor = Actor::new( + id.to_owned(), + self.gateway.roots[0].clone(), + false, + Some(timeout), + ); + let (sender, receiver) = mpsc::channel(32); + let (completion, stopped) = watch::channel(()); + tokio::spawn(async move { + actor.run(child, receiver).await; + drop(completion); + }); + self.gateway.sessions.lock().await.insert( + id.to_owned(), + Entry { + root: self.gateway.roots[0].clone(), + sender, + stopped, + }, + ); + } + + async fn connect(&self, name: &str) -> HttpConn { + let response = self + .client + .post(&self.url) + .bearer_auth("pinned-secret") + .json(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": 2, + "info": { "name": name, "version": "1" }, + "capabilities": {} + } + })) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let connection_id = response.headers()["acp-connection-id"] + .to_str() + .unwrap() + .to_owned(); + let init_body: Value = response.json().await.unwrap(); + let conn_stream = self + .client + .get(&self.url) + .bearer_auth("pinned-secret") + .header("acp-connection-id", &connection_id) + .header("accept", "text/event-stream") + .send() + .await + .unwrap(); + assert_eq!(conn_stream.status(), StatusCode::OK); + HttpConn { + client: self.client.clone(), + url: self.url.clone(), + connection_id, + init_body, + conn_stream: SseReader::new(conn_stream), + } + } +} + +struct SseReader { + response: reqwest::Response, + buffer: String, +} + +impl SseReader { + fn new(response: reqwest::Response) -> Self { + Self { + response, + buffer: String::new(), + } + } + + async fn next_event(&mut self) -> Option { + loop { + if let Some(end) = self.buffer.find("\n\n") { + let frame: String = self.buffer.drain(..end + 2).collect(); + if let Some(data) = frame.lines().find_map(|line| line.strip_prefix("data: ")) { + return Some(serde_json::from_str(data).unwrap()); + } + // SSE comments (such as keep-alive `:\n\n`) are ignored by event readers. + continue; + } + let chunk = self.response.chunk().await.unwrap()?; + self.buffer.push_str(std::str::from_utf8(&chunk).unwrap()); + } + } + + async fn next_matching(&mut self, mut predicate: impl FnMut(&Value) -> bool) -> Value { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let event = self + .next_event() + .await + .expect("SSE stream ended before expected event"); + if predicate(&event) { + return event; + } + } + }) + .await + .unwrap() + } +} + +struct HttpConn { + client: reqwest::Client, + url: String, + connection_id: String, + init_body: Value, + conn_stream: SseReader, +} + +impl HttpConn { + async fn open_session_stream(&self, session_id: &str) -> SseReader { + let response = self + .client + .get(&self.url) + .bearer_auth("pinned-secret") + .header("acp-connection-id", &self.connection_id) + .header("acp-session-id", session_id) + .header("accept", "text/event-stream") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + SseReader::new(response) + } + + async fn post(&self, body: Value) -> StatusCode { + self.client + .post(&self.url) + .bearer_auth("pinned-secret") + .header("acp-connection-id", &self.connection_id) + .json(&body) + .send() + .await + .unwrap() + .status() + } + + async fn delete(self) -> StatusCode { + self.client + .delete(&self.url) + .bearer_auth("pinned-secret") + .header("acp-connection-id", &self.connection_id) + .send() + .await + .unwrap() + .status() + } +} + +fn pinned_actor(id: &str, timeout: Duration) -> Actor { + Actor::new(id.into(), PathBuf::from("/approved"), false, Some(timeout)) +} + +#[test] +fn pinned_cli_flags_and_duration_parsing() { + let matches = Args::command() + .try_get_matches_from([ + "gateway", + "--pinned-session", + "thread-123", + "--client-request-timeout", + "90s", + ]) + .unwrap(); + let args = Args::from_matches(&matches).unwrap(); + assert_eq!(args.pinned_session.as_deref(), Some("thread-123")); + assert_eq!(args.client_request_timeout, Duration::from_secs(90)); + + let default_matches = Args::command() + .try_get_matches_from(["gateway", "--pinned-session", "thread-123"]) + .unwrap(); + let default_args = Args::from_matches(&default_matches).unwrap(); + assert_eq!( + default_args.client_request_timeout, + DEFAULT_CLIENT_REQUEST_TIMEOUT + ); + + // --client-request-timeout requires --pinned-session + assert!( + Args::command() + .try_get_matches_from(["gateway", "--client-request-timeout", "30s"]) + .is_err() + ); + // Reject zero or invalid durations + assert!(parse_duration("0s").is_err()); + assert!(parse_duration("").is_err()); + assert!(parse_duration("abc").is_err()); + assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500)); + assert_eq!(parse_duration("5m").unwrap(), Duration::from_secs(300)); + assert_eq!(parse_duration("2h").unwrap(), Duration::from_secs(7200)); + assert_eq!(parse_duration("45").unwrap(), Duration::from_secs(45)); +} + +#[tokio::test] +async fn pinned_one_session_list_rejects_other_ids_and_local_close() { + let harness = PinnedHarness::new("pinned-1", Duration::from_secs(60)).await; + let c1 = harness.connect("client-1").await; + assert_eq!( + c1.init_body["result"]["_meta"]["kit/gateway"]["pinnedSession"], + "pinned-1" + ); + + // session/list before first use returns just the pinned session with state "new". + let mut c1 = c1; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":2,"method":"session/list","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let listed = c1.conn_stream.next_matching(|e| e["id"] == 2).await; + assert_eq!(listed["result"]["sessions"].as_array().unwrap().len(), 1); + assert_eq!(listed["result"]["sessions"][0]["sessionId"], "pinned-1"); + assert_eq!( + listed["result"]["sessions"][0]["_meta"]["kit.gateway.state"], + "new" + ); + + // Another session id is rejected on session/resume. + assert_eq!( + c1.post(json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/resume", + "params": { "sessionId": "other-session" } + })) + .await, + StatusCode::ACCEPTED + ); + let rejected = c1.conn_stream.next_matching(|e| e["id"] == 3).await; + assert!(rejected.get("error").is_some(), "{rejected}"); + assert!( + rejected["error"]["message"] + .as_str() + .unwrap() + .contains("pinned-1") + ); + + // Start fake child for the pinned session. + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-1','configOptions':[]}}) + elif m == 'session/close': + raise AssertionError('session/close must never reach child in pinned mode') + elif m == 'session/prompt': + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-1','update':{'sessionUpdate':'agent_message','messageId':'m-1','content':[]}}}) + emit({'jsonrpc':'2.0','id':req['id'],'result':{'messageId':'u-1'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-1", source, &[]).await; + + // Client 1 attaches via session/new; Client 2 attaches via session/resume. + let mut s1 = c1.open_session_stream("pinned-1").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":4,"method":"session/new","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let r1 = c1.conn_stream.next_matching(|e| e["id"] == 4).await; + assert_eq!(r1["result"]["sessionId"], "pinned-1"); + + let mut c2 = harness.connect("client-2").await; + let mut s2 = c2.open_session_stream("pinned-1").await; + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "id": 5, + "method": "session/resume", + "params": { "sessionId": "pinned-1" } + })) + .await, + StatusCode::ACCEPTED + ); + let r2 = s2.next_matching(|e| e["id"] == 5).await; + assert_eq!(r2["result"]["sessionId"], "pinned-1"); + + // session/list now reports state "resident" and still only that one session. + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":6,"method":"session/list","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let listed2 = c2.conn_stream.next_matching(|e| e["id"] == 6).await; + assert_eq!(listed2["result"]["sessions"].as_array().unwrap().len(), 1); + assert_eq!(listed2["result"]["sessions"][0]["sessionId"], "pinned-1"); + assert_eq!( + listed2["result"]["sessions"][0]["_meta"]["kit.gateway.state"], + "resident" + ); + + // Client 1 sends session/close -> detaches ONLY Client 1, does NOT end session. + assert_eq!( + c1.post(json!({ + "jsonrpc": "2.0", + "id": 7, + "method": "session/close", + "params": { "sessionId": "pinned-1" } + })) + .await, + StatusCode::ACCEPTED + ); + let closed1 = s1.next_matching(|e| e["id"] == 7).await; + assert_eq!(closed1["result"], json!({})); + + // Client 2 still works after Client 1 closed! + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "id": 8, + "method": "session/prompt", + "params": { "sessionId": "pinned-1", "prompt": [{"type":"text","text":"still alive"}] } + })) + .await, + StatusCode::ACCEPTED + ); + let p2 = s2.next_matching(|e| e["id"] == 8).await; + assert_eq!(p2["result"]["messageId"], "u-1"); + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[tokio::test] +async fn pinned_two_attachments_fan_out_updates_reply_only_to_sender_and_any_cancels() { + let harness = PinnedHarness::new("pinned-fanout", Duration::from_secs(60)).await; + let source = r#" +import sys, json +pending = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-fanout','configOptions':[]}}) + elif m == 'session/prompt': + pending = req + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-fanout','update':{'sessionUpdate':'state_update','state':'running'}}}) + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-fanout','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'working...'}}}}) + elif m == 'session/cancel': + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-fanout','update':{'sessionUpdate':'state_update','state':'idle'}}}) + if pending: + emit({'jsonrpc':'2.0','id':pending['id'],'result':{'stopReason':'cancelled'}}) + pending = None + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-fanout", source, &[]).await; + + let c1 = harness.connect("c1").await; + let mut s1 = c1.open_session_stream("pinned-fanout").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":10,"method":"session/resume","params":{"sessionId":"pinned-fanout"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 10).await; + + let c2 = harness.connect("c2").await; + let mut s2 = c2.open_session_stream("pinned-fanout").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":20,"method":"session/resume","params":{"sessionId":"pinned-fanout"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s2.next_matching(|e| e["id"] == 20).await; + + // Client 1 sends prompt. + assert_eq!( + c1.post(json!({ + "jsonrpc": "2.0", + "id": "prompt-from-c1", + "method": "session/prompt", + "params": { "sessionId": "pinned-fanout", "prompt": [{"type":"text","text":"hello"}] } + })) + .await, + StatusCode::ACCEPTED + ); + + // BOTH Client 1 and Client 2 receive the session/update chunk! + let u1 = s1 + .next_matching(|e| e["params"]["update"]["sessionUpdate"] == "agent_message_chunk") + .await; + let u2 = s2 + .next_matching(|e| e["params"]["update"]["sessionUpdate"] == "agent_message_chunk") + .await; + assert_eq!(u1["params"]["update"]["content"]["text"], "working..."); + assert_eq!(u2["params"]["update"]["content"]["text"], "working..."); + + // Client 2 (not the prompt sender) sends session/cancel! + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "method": "session/cancel", + "params": { "sessionId": "pinned-fanout" } + })) + .await, + StatusCode::ACCEPTED + ); + + // Client 1 receives the prompt reply; Client 2 receives the idle state update, NOT Client 1's reply. + let reply1 = s1.next_matching(|e| e["id"] == "prompt-from-c1").await; + assert_eq!(reply1["result"]["stopReason"], "cancelled"); + + let mut c2_seen = Vec::new(); + loop { + let ev = tokio::time::timeout(Duration::from_secs(5), s2.next_event()) + .await + .unwrap() + .unwrap(); + let is_idle = ev["params"]["update"]["state"] == "idle"; + c2_seen.push(ev); + if is_idle { + break; + } + } + // Give one brief tick to confirm no stray reply lands on c2. + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "id": "status-from-c2", + "method": "kit/session/status", + "params": { "sessionId": "pinned-fanout" } + })) + .await, + StatusCode::ACCEPTED + ); + let mut got_status = false; + while !got_status { + let ev = tokio::time::timeout(Duration::from_secs(5), s2.next_event()) + .await + .unwrap() + .unwrap(); + assert_ne!( + ev["id"], "prompt-from-c1", + "Client 2 must never receive Client 1's prompt reply" + ); + if ev["id"] == "status-from-c2" { + got_status = true; + } + } + assert!(!c2_seen.iter().any(|e| e["id"] == "prompt-from-c1")); + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[tokio::test] +async fn pinned_second_attach_and_detach_keep_held_steer_and_dedup_retry_by_idempotency_key() { + // Fake child models Kit's PendingPrompts idempotency-key grouping: + // - holds steers by idempotencyKey without inserting until 'kit/session/status' flushes them + // - deduplicates retries with the same idempotencyKey into one insertion with one messageId + // - honors explicit $/cancel_request to withdraw held steers + let harness = PinnedHarness::new("pinned-steer", Duration::from_secs(60)).await; + let source = r#" +import sys, json +groups = {} # key -> {'ids': [req_ids], 'inserted': False, 'msg_id': None} +insert_count = 0 +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-steer','configOptions':[]}}) + elif m == 'session/prompt': + key = req['params'].get('idempotencyKey') or f"anon-{req['id']}" + g = groups.setdefault(key, {'ids': [], 'inserted': False, 'msg_id': None}) + if g['inserted']: + emit({'jsonrpc':'2.0','id':req['id'],'result':{'messageId':g['msg_id']}}) + else: + g['ids'].append(req['id']) + count = len(g['ids']) + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-steer','update':{'sessionUpdate':'notice','message':f'held:{key}:{count}'}}}) + elif m == '$/cancel_request': + target = req['params']['requestId'] + for k, g in list(groups.items()): + if not g['inserted'] and target in g['ids']: + for rid in g['ids']: + emit({'jsonrpc':'2.0','id':rid,'error':{'code':-32800,'message':'Request cancelled'}}) + del groups[k] + elif m == 'kit/session/status': + for k, g in groups.items(): + if not g['inserted']: + insert_count += 1 + g['inserted'] = True + g['msg_id'] = f'msg-{insert_count}' + for rid in g['ids']: + emit({'jsonrpc':'2.0','id':rid,'result':{'messageId':g['msg_id']}}) + emit({'jsonrpc':'2.0','id':req['id'],'result':{'inserted':insert_count}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-steer", source, &[]).await; + + let c1 = harness.connect("deliverer-1").await; + let mut s1 = c1.open_session_stream("pinned-steer").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-steer"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + // Submit held steer with idempotencyKey "k-survive" AND another with "k-cancel". + assert_eq!( + c1.post(json!({ + "jsonrpc": "2.0", + "id": "steer-1", + "method": "session/prompt", + "params": { + "sessionId": "pinned-steer", + "delivery": "steer", + "idempotencyKey": "k-survive", + "prompt": [{"type":"text","text":"deliver once"}] + } + })) + .await, + StatusCode::ACCEPTED + ); + let _ = s1 + .next_matching(|e| e["params"]["update"]["message"] == "held:k-survive:1") + .await; + + // Second client attaches while steer-1 is held -> must NOT withdraw steer-1! + let c2 = harness.connect("deliverer-2").await; + let mut s2 = c2.open_session_stream("pinned-steer").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-steer"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s2.next_matching(|e| e["id"] == 2).await; + + // Also test explicit $/cancel_request on a separate held steer from c2. + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "id": "steer-cancel", + "method": "session/prompt", + "params": { + "sessionId": "pinned-steer", + "delivery": "steer", + "idempotencyKey": "k-cancel", + "prompt": [{"type":"text","text":"withdraw me"}] + } + })) + .await, + StatusCode::ACCEPTED + ); + let _ = s2 + .next_matching(|e| e["params"]["update"]["message"] == "held:k-cancel:1") + .await; + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "method": "$/cancel_request", + "params": { "requestId": "steer-cancel" } + })) + .await, + StatusCode::ACCEPTED + ); + let cancelled = s2.next_matching(|e| e["id"] == "steer-cancel").await; + assert_eq!(cancelled["error"]["code"], -32800); + + // Client 1 disconnects (DELETE) while "k-survive" is STILL held -> must NOT be withdrawn! + drop(s1); + assert_eq!(c1.delete().await, StatusCode::ACCEPTED); + + // Client 2 retries with the same idempotencyKey "k-survive" -> joins the held group (2 attempts, 1 insertion)! + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "id": "steer-retry", + "method": "session/prompt", + "params": { + "sessionId": "pinned-steer", + "delivery": "steer", + "idempotencyKey": "k-survive", + "prompt": [{"type":"text","text":"deliver once"}] + } + })) + .await, + StatusCode::ACCEPTED + ); + let _ = s2 + .next_matching(|e| e["params"]["update"]["message"] == "held:k-survive:2") + .await; + + // Trigger insertion flush via kit/session/status. + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "id": 99, + "method": "kit/session/status", + "params": { "sessionId": "pinned-steer" } + })) + .await, + StatusCode::ACCEPTED + ); + let retry_reply = s2.next_matching(|e| e["id"] == "steer-retry").await; + assert_eq!(retry_reply["result"]["messageId"], "msg-1"); + let status_reply = s2.next_matching(|e| e["id"] == 99).await; + assert_eq!( + status_reply["result"]["inserted"], 1, + "held steer + retry with same idempotencyKey must insert exactly once" + ); + + let _ = c2.delete().await; +} + +#[tokio::test] +async fn pinned_overflow_drops_only_one_attachment_without_withdrawing_or_affecting_others() { + let mut actor = pinned_actor("pinned-overflow", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-overflow", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let a1 = actor + .command( + Request::Attach { + session: "pinned-overflow".into(), + replay: false, + replay_mode: Some(ReplayMode::None), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-overflow"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let a2 = actor + .command( + Request::Attach { + session: "pinned-overflow".into(), + replay: false, + replay_mode: Some(ReplayMode::None), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-overflow"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + // Attachment 1 submits a held steer prompt. + actor + .command( + Request::Send { + session: "pinned-overflow".into(), + attachment: a1.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "held-1", + "method": "session/prompt", + "params": {"sessionId": "pinned-overflow", "delivery": "steer", "prompt": []} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let _prompt_written = child_rx.try_recv().unwrap(); + + // Drain a2 as updates arrive, while letting a1 never poll so a1 overflows MAX_QUEUE. + let mut cursor2 = 0u64; + for i in 0..=MAX_QUEUE { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "pinned-overflow", + "update": { "sessionUpdate": "agent_message_chunk", "content": {"type":"text","text": format!("c-{i}")} } + } + })); + if i % 64 == 0 { + let polled = actor + .command( + Request::Poll { + session: "pinned-overflow".into(), + attachment: a2.clone(), + cursor: cursor2, + }, + &writes, + ) + .unwrap(); + if let Some(last) = polled["events"].as_array().unwrap().last() { + cursor2 = last["cursor"].as_u64().unwrap(); + } + } + } + + // a1 is dropped with clear `queue_overflow` reason. + let err = actor + .command( + Request::Poll { + session: "pinned-overflow".into(), + attachment: a1.clone(), + cursor: 0, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(err.2, "queue_overflow"); + + // No $/cancel_request withdrawal was sent to child for a1's held steer! + assert!(actor.next_withdrawal().is_none()); + assert!(child_rx.try_recv().is_err()); + + // a2 is completely unaffected and receives subsequent updates. + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "pinned-overflow", + "update": { "sessionUpdate": "state_update", "state": "idle" } + } + })); + let mut saw_idle = false; + loop { + let polled = actor + .command( + Request::Poll { + session: "pinned-overflow".into(), + attachment: a2.clone(), + cursor: cursor2, + }, + &writes, + ) + .unwrap(); + let events = polled["events"].as_array().unwrap(); + if events.is_empty() { + break; + } + for ev in events { + cursor2 = ev["cursor"].as_u64().unwrap(); + if ev["message"]["params"]["update"]["state"] == "idle" { + saw_idle = true; + } + } + } + assert!(saw_idle); +} + +#[tokio::test] +async fn pinned_http_overflow_ends_only_overflowed_connection_stream_with_reason() { + let harness = PinnedHarness::new("pinned-http-ovf", Duration::from_secs(60)).await; + let (sender, mut receiver) = mpsc::channel::(16); + let (_tx, stopped) = watch::channel(()); + harness.gateway.sessions.lock().await.insert( + "pinned-http-ovf".into(), + Entry { + root: harness.gateway.roots[0].clone(), + sender, + stopped, + }, + ); + + // Fake actor that accepts attach and immediately responds `queue_overflow` on the second poll. + let actor_task = tokio::spawn(async move { + let mut polls = 0usize; + while let Some(envelope) = receiver.recv().await { + match envelope.request { + Request::Attach { .. } => { + let _ = envelope.reply.send(Ok(json!({ + "started": true, + "attachment": "att-ovf", + "lease_seconds": 15 + }))); + } + Request::Poll { .. } => { + polls += 1; + if polls == 1 { + let _ = envelope.reply.send(Ok(json!({ + "closed": false, + "events": [{ + "cursor": 1, + "message": { + "jsonrpc": "2.0", + "id": 10, + "result": { "sessionId": "pinned-http-ovf", "configOptions": [] } + } + }] + }))); + } else { + let _ = envelope.reply.send(Err(Failure( + StatusCode::CONFLICT, + "attachment queue overflowed; reconnect".into(), + "queue_overflow", + ))); + } + } + Request::Detach { .. } => { + let _ = envelope.reply.send(Ok(json!({}))); + } + _ => { + let _ = envelope.reply.send(Ok(json!({}))); + } + } + } + }); + + let c1 = harness.connect("slow-client").await; + let mut s1 = c1.open_session_stream("pinned-http-ovf").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":10,"method":"session/resume","params":{"sessionId":"pinned-http-ovf"}})) + .await, + StatusCode::ACCEPTED + ); + let resumed = s1.next_matching(|e| e["id"] == 10).await; + assert_eq!(resumed["result"]["sessionId"], "pinned-http-ovf"); + + // Next event is the `_gateway_controller` overflow notice, followed by clean EOF on the SSE stream. + let notice = s1 + .next_matching(|e| e["params"]["update"]["sessionUpdate"] == "_gateway_controller") + .await; + assert_eq!( + notice["params"]["update"]["_meta"]["kit/gateway"]["reason"], + "queue_overflow" + ); + let eof = tokio::time::timeout(Duration::from_secs(5), s1.next_event()) + .await + .unwrap(); + assert!( + eof.is_none(), + "overflowed attachment stream must end cleanly" + ); + actor_task.abort(); +} + +#[test] +fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_eviction() { + let mut actor = pinned_actor("pinned-replay", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-replay", "configOptions": []})); + let (writes, _rx) = mpsc::channel(4); + + // Turn 1 (completed). + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"state_update","state":"running"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"user_message","messageId":"u-1","content":[{"type":"text","text":"turn 1"}]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"agent_message","messageId":"a-1","content":[{"type":"text","text":"answer 1"}]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"state_update","state":"idle"}}})); + + // Turn 2 (currently mid-turn, in-progress assistant message!). + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"state_update","state":"running"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"user_message","messageId":"u-2","content":[{"type":"text","text":"turn 2"}]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"agent_message_chunk","content":[{"type":"text","text":"in-progress chunk"}]}}})); + + // Join mid-turn with `_kit_current_turn`: gets Turn 2 only (including in-progress chunk) + snapshot + result. + let a_turn = actor + .command( + Request::Attach { + session: "pinned-replay".into(), + replay: false, + replay_mode: Some(ReplayMode::CurrentTurn), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-replay","replayFrom":{"type":"_kit_current_turn"}}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let events_turn: Vec = actor.pinned.as_ref().unwrap().attachments[&a_turn] + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + !events_turn + .iter() + .any(|e| e["params"]["update"]["messageId"] == "u-1") + ); + assert!( + events_turn + .iter() + .any(|e| e["params"]["update"]["messageId"] == "u-2") + ); + assert!( + events_turn + .iter() + .any(|e| e["params"]["update"]["sessionUpdate"] == "agent_message_chunk") + ); + assert_eq!(events_turn.last().unwrap()["id"], 1); + assert_eq!( + events_turn.last().unwrap()["result"]["_meta"]["kit/gateway"]["historyAvailable"], + true + ); + + // Join with `_kit_message` pointing to u-1: gets Turn 1 + Turn 2. + let a_msg = actor + .command( + Request::Attach { + session: "pinned-replay".into(), + replay: false, + replay_mode: Some(ReplayMode::Message { + message_id: "u-1".into(), + }), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-replay","replayFrom":{"type":"_kit_message","sessionId":"pinned-replay","messageId":"u-1"}}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let events_msg: Vec = actor.pinned.as_ref().unwrap().attachments[&a_msg] + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert_eq!(events_msg[0]["params"]["update"]["messageId"], "u-1"); + assert!( + events_msg + .iter() + .any(|e| e["params"]["update"]["messageId"] == "u-2") + ); + + // Invalid / unknown `_kit_message` cursor returns -32602 (invalid_params). + let err = actor + .command( + Request::Attach { + session: "pinned-replay".into(), + replay: false, + replay_mode: Some(ReplayMode::Message { + message_id: "missing-msg".into(), + }), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), + }, + &writes, + ) + .unwrap_err(); + assert_eq!(err.jsonrpc_code(), -32602); + + // Mismatched sessionId in `_kit_message` parser also returns -32602. + let err = parse_replay_mode( + Some(&json!({"type":"_kit_message","sessionId":"wrong","messageId":"u-1"})), + "pinned-replay", + true, + false, + ) + .unwrap_err(); + assert_eq!(err.jsonrpc_code(), -32602); + + // Force eviction of Turn 1 so `replay_complete` becomes false, then start Turn 3. + // Full `start` replay fails, while `_kit_current_turn` and `_kit_message(u-3)` still succeed! + let big_pad = "x".repeat(MAX_HTTP_FRAME / 2); + for _ in 0..20 { + actor.remember(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"notice","message":big_pad}}})); + } + assert!(!actor.replay_complete); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"state_update","state":"idle"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"state_update","state":"running"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"user_message","messageId":"u-3","content":[{"type":"text","text":"turn 3"}]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-replay","update":{"sessionUpdate":"agent_message_chunk","content":[{"type":"text","text":"turn 3 partial"}]}}})); + + // Full start replay is unavailable after eviction. + let start_err = actor + .command( + Request::Attach { + session: "pinned-replay".into(), + replay: true, + replay_mode: Some(ReplayMode::Start), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), + }, + &writes, + ) + .unwrap_err(); + assert_eq!(start_err.2, "replay_unavailable"); + + // `_kit_current_turn` STILL succeeds and delivers Turn 3's in-progress output! + let a_turn3 = actor + .command( + Request::Attach { + session: "pinned-replay".into(), + replay: false, + replay_mode: Some(ReplayMode::CurrentTurn), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":5,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let events_turn3: Vec = actor.pinned.as_ref().unwrap().attachments[&a_turn3] + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + events_turn3 + .iter() + .any(|e| e["params"]["update"]["messageId"] == "u-3") + ); + assert!( + events_turn3 + .iter() + .any(|e| e["params"]["update"]["sessionUpdate"] == "agent_message_chunk") + ); +} + +#[tokio::test] +async fn pinned_relayed_ask_user_answered_by_one_and_cancelled_for_other_over_http() { + let harness = PinnedHarness::new("pinned-ask", Duration::from_secs(60)).await; + let source = r#" +import sys, json +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + # Response from gateway to our elicitation/create request! + if req['id'] == 'ask-42' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'answered': req.get('result')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + # Pinned mode MUST advertise elicitation.form capability to child. + assert req['params']['capabilities'].get('elicitation', {}).get('form') == {}, req + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-ask','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-ask','update':{'sessionUpdate':'state_update','state':'requires_action'}}}) + emit({ + 'jsonrpc':'2.0', + 'id':'ask-42', + 'method':'elicitation/create', + 'params':{ + 'sessionId':'pinned-ask', + 'mode':'form', + 'message':'Pick one', + 'requestedSchema':{'type':'object','properties':{}} + } + }) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-ask", source, &[]).await; + + let mut c1 = harness.connect("ui-1").await; + let mut s1 = c1.open_session_stream("pinned-ask").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-ask"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + let c2 = harness.connect("ui-2").await; + let mut s2 = c2.open_session_stream("pinned-ask").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-ask"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s2.next_matching(|e| e["id"] == 2).await; + + // Trigger prompt that causes child to emit elicitation/create. + assert_eq!( + c1.post(json!({ + "jsonrpc": "2.0", + "id": "p-ask", + "method": "session/prompt", + "params": { "sessionId": "pinned-ask", "prompt": [{"type":"text","text":"ask me"}] } + })) + .await, + StatusCode::ACCEPTED + ); + + // BOTH clients receive elicitation/create on their session streams. + let q1 = s1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let q2 = s2 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + assert_eq!(q1["id"], q2["id"]); + let relay_id = q1["id"].as_str().unwrap().to_owned(); + + // Client 2 answers first! + assert_eq!( + c2.post(json!({ + "jsonrpc": "2.0", + "id": relay_id, + "result": { "action": "accept", "content": { "question_0": "option_a" } } + })) + .await, + StatusCode::ACCEPTED + ); + + // Client 1's prompt completes with Client 2's answer! + let completed = s1.next_matching(|e| e["id"] == "p-ask").await; + assert_eq!( + completed["result"]["answered"], + json!({"action": "accept", "content": {"question_0": "option_a"}}) + ); + + // Client 1 receives $/cancel_request for that relayed request on its connection stream! + let cancelled = c1 + .conn_stream + .next_matching(|e| e["method"] == "$/cancel_request") + .await; + assert_eq!(cancelled["params"]["requestId"], relay_id); + + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[tokio::test(start_paused = true)] +async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout() { + let timeout = Duration::from_secs(10); + let mut actor = pinned_actor("pinned-req", timeout); + actor.session_result = Some(json!({"sessionId": "pinned-req", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + // 1. No attachment live -> immediately responds -32601. + let immediate = actor + .output(json!({ + "jsonrpc": "2.0", + "id": "no-clients", + "method": "elicitation/create", + "params": { "sessionId": "pinned-req", "mode": "form", "message": "anyone?" } + })) + .expect("must immediately reply -32601 when no attachment is live"); + assert_eq!(immediate["id"], "no-clients"); + assert_eq!(immediate["error"]["code"], -32601); + + // Attach c1 and c2. + let attach = |actor: &mut Actor, req_id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-req".into(), + replay: false, + replay_mode: Some(ReplayMode::None), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":req_id,"method":"session/resume","params":{"sessionId":"pinned-req"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + let c1 = attach(&mut actor, 1); + let c2 = attach(&mut actor, 2); + + // 2. One client replies -32601 (unsupported) -> only that target removed; other client still answers! + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-mixed", + "method": "elicitation/create", + "params": { "sessionId": "pinned-req", "mode": "form", "message": "mixed" } + })) + .is_none() + ); + let relay_id = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor + .command( + Request::Send { + session: "pinned-req".into(), + attachment: c1.clone(), + message: json!({"jsonrpc":"2.0","id":relay_id,"error":{"code":-32601,"message":"Method not found"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + // Request is still pending for c2! + assert!(child_rx.try_recv().is_err()); + assert!( + actor + .pinned + .as_ref() + .unwrap() + .client_requests + .contains_key(&relay_id) + ); + actor + .command( + Request::Send { + session: "pinned-req".into(), + attachment: c2.clone(), + message: json!({"jsonrpc":"2.0","id":relay_id,"result":{"action":"decline"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let forwarded = child_rx.try_recv().unwrap().message; + assert_eq!(forwarded["id"], "ask-mixed"); + assert_eq!(forwarded["result"]["action"], "decline"); + + // 3. All targets reply -32601 -> gateway replies -32601 to child! + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-all-32601", + "method": "elicitation/create", + "params": { "sessionId": "pinned-req", "mode": "form", "message": "none support" } + })) + .is_none() + ); + let relay_id2 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + for att in [&c1, &c2] { + actor + .command( + Request::Send { + session: "pinned-req".into(), + attachment: att.clone(), + message: json!({"jsonrpc":"2.0","id":relay_id2,"error":{"code":-32601,"message":"Method not found"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + } + let declined = child_rx.try_recv().unwrap().message; + assert_eq!(declined["id"], "ask-all-32601"); + assert_eq!(declined["error"]["code"], -32601); + + // 4. Browser reload: last target detaches -> request stays pending -> late joiner receives it and answers! + actor + .command( + Request::Detach { + session: "pinned-req".into(), + attachment: c2.clone(), + }, + &writes, + ) + .unwrap(); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-reload", + "method": "elicitation/create", + "params": { "sessionId": "pinned-req", "mode": "form", "message": "survives reload" } + })) + .is_none() + ); + let relay_reload = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + // Detach the only target c1 -> must NOT cancel ask-reload! + actor + .command( + Request::Detach { + session: "pinned-req".into(), + attachment: c1.clone(), + }, + &writes, + ) + .unwrap(); + assert!(child_rx.try_recv().is_err()); + assert!( + actor + .pinned + .as_ref() + .unwrap() + .client_requests + .contains_key(&relay_reload) + ); + // Reattach as c3 -> receives pending ask-reload right after startup and answers it! + let c3 = attach(&mut actor, 3); + let c3_events: Vec = actor.pinned.as_ref().unwrap().attachments[&c3] + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert_eq!(c3_events.last().unwrap()["method"], "elicitation/create"); + assert_eq!(c3_events.last().unwrap()["id"], relay_reload); + actor + .command( + Request::Send { + session: "pinned-req".into(), + attachment: c3.clone(), + message: json!({"jsonrpc":"2.0","id":relay_reload,"result":{"action":"accept","content":{"q":"reloaded"}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let reload_reply = child_rx.try_recv().unwrap().message; + assert_eq!(reload_reply["id"], "ask-reload"); + assert_eq!(reload_reply["result"]["content"]["q"], "reloaded"); + + // 5. Timeout expiry -> responds -32603 ("Incoming transport closed") to child and cancels target! + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-timeout", + "method": "elicitation/create", + "params": { "sessionId": "pinned-req", "mode": "form", "message": "expires" } + })) + .is_none() + ); + let relay_timeout = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + assert!(actor.next_expired_client_request().is_none()); + tokio::time::advance(timeout).await; + let expired_id = actor.next_expired_client_request().unwrap(); + assert_eq!(expired_id, relay_timeout); + let permit = writes.try_reserve().unwrap(); + actor.expire_client_request(&expired_id, permit); + + let timeout_reply = child_rx.try_recv().unwrap().message; + assert_eq!(timeout_reply["id"], "ask-timeout"); + assert_eq!(timeout_reply["error"]["code"], -32603); + assert_eq!( + timeout_reply["error"]["message"], + "Incoming transport closed" + ); + assert_eq!( + timeout_reply["error"]["data"]["reason"], + "incoming_transport_closed" + ); + assert_eq!( + timeout_reply["error"]["data"]["method"], + "elicitation/create" + ); + let c3_last = actor.pinned.as_ref().unwrap().attachments[&c3] + .events + .back() + .unwrap() + .1 + .clone(); + assert_eq!(c3_last["method"], "$/cancel_request"); + assert_eq!(c3_last["params"]["requestId"], relay_timeout); + + // 6. Child-originated $/cancel_request cancels relayed request for current targets. + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-agent-cancel", + "method": "elicitation/create", + "params": { "sessionId": "pinned-req", "mode": "form", "message": "agent cancels" } + })) + .is_none() + ); + let relay_cancel = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor.output(json!({ + "jsonrpc": "2.0", + "method": "$/cancel_request", + "params": { "requestId": "ask-agent-cancel" } + })); + assert!(actor.pinned.as_ref().unwrap().client_requests.is_empty()); + let c3_cancel = actor.pinned.as_ref().unwrap().attachments[&c3] + .events + .back() + .unwrap() + .1 + .clone(); + assert_eq!(c3_cancel["method"], "$/cancel_request"); + assert_eq!(c3_cancel["params"]["requestId"], relay_cancel); +} + +#[tokio::test] +async fn pinned_concurrent_cold_startup_serves_both_clients() { + use tokio::io::AsyncWriteExt as _; + + let harness = PinnedHarness::new("pinned-race", Duration::from_secs(60)).await; + let gate = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let source = r#" +import sys, json, socket +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + with socket.create_connection(('127.0.0.1', int(sys.argv[1]))) as sock: + assert sock.recv(1) == b'G' + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-race','configOptions':[]}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness + .child_source( + "pinned-race", + source, + &[gate.local_addr().unwrap().port().to_string()], + ) + .await; + + let c1 = harness.connect("first").await; + let mut s1 = c1.open_session_stream("pinned-race").await; + let c2 = harness.connect("second").await; + let mut s2 = c2.open_session_stream("pinned-race").await; + + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":11,"method":"session/resume","params":{"sessionId":"pinned-race"}})) + .await, + StatusCode::ACCEPTED + ); + // Wait until child has received c1's startup request and blocked on gate. + let (mut conn, _) = tokio::time::timeout(Duration::from_secs(5), gate.accept()) + .await + .unwrap() + .unwrap(); + + // While c1's startup is still in flight, c2 also attaches! + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":22,"method":"session/resume","params":{"sessionId":"pinned-race"}})) + .await, + StatusCode::ACCEPTED + ); + + // Release child startup; BOTH c1 and c2 receive their startup responses! + conn.write_all(b"G").await.unwrap(); + let r1 = s1.next_matching(|e| e["id"] == 11).await; + let r2 = s2.next_matching(|e| e["id"] == 22).await; + assert_eq!(r1["result"]["sessionId"], "pinned-race"); + assert_eq!(r2["result"]["sessionId"], "pinned-race"); + + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[test] +fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_error() { + let mut actor = pinned_actor("pinned-edge", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-edge", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + // 1. Send before Poll on an overflowed attachment must NOT consume the queue_overflow reason. + let a1 = actor + .command( + Request::Attach { + session: "pinned-edge".into(), + replay: false, + replay_mode: Some(ReplayMode::None), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + for i in 0..=MAX_QUEUE { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-edge", "update": {"sessionUpdate": "notice", "message": format!("m-{i}")}} + })); + } + let send_err = actor + .command( + Request::Send { + session: "pinned-edge".into(), + attachment: a1.clone(), + message: json!({"jsonrpc":"2.0","id":9,"method":"kit/session/status","params":{"sessionId":"pinned-edge"}}), + charge: None, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(send_err.2, "queue_overflow"); + let poll_err = actor + .command( + Request::Poll { + session: "pinned-edge".into(), + attachment: a1, + cursor: 0, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(poll_err.2, "queue_overflow"); + + // 2. session/close followed by Poll returns closed=true and removes the attachment immediately. + let a2 = actor + .command( + Request::Attach { + session: "pinned-edge".into(), + replay: false, + replay_mode: Some(ReplayMode::None), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + actor + .command( + Request::Send { + session: "pinned-edge".into(), + attachment: a2.clone(), + message: json!({"jsonrpc":"2.0","id":3,"method":"session/close","params":{"sessionId":"pinned-edge"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let polled = actor + .command( + Request::Poll { + session: "pinned-edge".into(), + attachment: a2.clone(), + cursor: 0, + }, + &writes, + ) + .unwrap(); + assert_eq!(polled["closed"], true); + assert!( + !actor.pinned.as_ref().unwrap().attachments.contains_key(&a2), + "closing attachment must be reclaimed on final Poll" + ); + + // 3. Relayed client response with `"error": null` alongside valid `"result"` is accepted as result. + let a3 = actor + .command( + Request::Attach { + session: "pinned-edge".into(), + replay: false, + replay_mode: Some(ReplayMode::None), + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-null-err", + "method": "elicitation/create", + "params": {"sessionId": "pinned-edge", "mode": "form", "message": "test"} + })) + .is_none() + ); + let relay_id = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor + .command( + Request::Send { + session: "pinned-edge".into(), + attachment: a3, + message: json!({"jsonrpc":"2.0","id":relay_id,"result":{"action":"decline"},"error":null}), + charge: None, + }, + &writes, + ) + .unwrap(); + let reply = child_rx.try_recv().unwrap().message; + assert_eq!(reply["id"], "ask-null-err"); + assert_eq!(reply["result"]["action"], "decline"); + assert!(reply.get("error").is_none()); +} diff --git a/src/gateway/tests.rs b/src/gateway/tests.rs index f50199a4..e82658f0 100644 --- a/src/gateway/tests.rs +++ b/src/gateway/tests.rs @@ -31,6 +31,7 @@ impl Harness { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: vec![directory.path().canonicalize().unwrap()], + pinned: None, sessions: Mutex::new(HashMap::new()), }); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -105,22 +106,7 @@ for line in sys.stdin: .kill_on_drop(true) .spawn() .unwrap(); - let actor = Actor { - id: id.to_owned(), - root: self.gateway.roots[0].clone(), - restore: false, - closed: false, - attachment: None, - committed_owner: None, - serial: 0, - pending: HashMap::new(), - initialized: None, - session_result: None, - state: json!({"sessionUpdate":"state_update","state":"idle"}), - journal: VecDeque::new(), - journal_bytes: 0, - replay_complete: true, - }; + let actor = Actor::new(id.to_owned(), self.gateway.roots[0].clone(), false, None); let (sender, receiver) = mpsc::channel(32); let (completion, stopped) = watch::channel(()); tokio::spawn(async move { @@ -447,22 +433,7 @@ fn bind_policy_requires_separate_explicit_opt_ins() { } pub(super) fn isolated_actor() -> Actor { - Actor { - id: "resident".into(), - root: PathBuf::from("/approved"), - restore: false, - closed: false, - attachment: None, - committed_owner: None, - serial: 0, - pending: HashMap::new(), - initialized: None, - session_result: None, - state: json!({"sessionUpdate":"state_update","state":"idle"}), - journal: VecDeque::new(), - journal_bytes: 0, - replay_complete: true, - } + Actor::new("resident".into(), PathBuf::from("/approved"), false, None) } #[tokio::test] @@ -491,6 +462,7 @@ async fn accepted_child_write_retains_charge_after_dequeue_until_consumed() { session: actor.id.clone(), replace: false, replay: true, + replay_mode: None, }, &writes, ) @@ -531,6 +503,7 @@ fn failed_child_enqueue_does_not_publish_pending_request() { session: actor.id.clone(), replace: false, replay: true, + replay_mode: None, }, &writes, ) @@ -569,6 +542,7 @@ fn failed_replay_claim_preserves_owner_and_stale_release_preserves_replacement() session: "resident".into(), replace, replay: true, + replay_mode: None, }; let first = actor.command(claim(false), &writes).unwrap()["attachment"] .as_str() @@ -650,6 +624,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { session: actor.id.clone(), replace: false, replay: true, + replay_mode: None, }, &writes, ) @@ -665,7 +640,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { method: "session/resume".into(), explicit_delivery: false, withdrawal_pending: false, - replay: true, + replay: ReplayMode::Start, }, ); actor.remember(json!({"payload":"x".repeat(MAX_REPLAY + 1)})); @@ -700,6 +675,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { session: actor.id.clone(), replace: true, replay: false, + replay_mode: None, }, &writes, ) @@ -715,7 +691,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { method: "session/resume".into(), explicit_delivery: false, withdrawal_pending: false, - replay: false, + replay: ReplayMode::None, }, ); actor.output(json!({"jsonrpc":"2.0","id":1,"result":{"sessionId":"resident"}})); @@ -737,6 +713,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { session: actor.id.clone(), replace: true, replay: true, + replay_mode: None, }, &writes ) @@ -1086,6 +1063,7 @@ pub(super) fn resident_claim(actor: &Actor, replay: bool, id: u64) -> Request { session: actor.id.clone(), replace: true, replay, + replay_mode: None, startup: Some( json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":actor.id}}), ), @@ -1382,7 +1360,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() method: "session/prompt".into(), explicit_delivery: false, withdrawal_pending: false, - replay: false, + replay: ReplayMode::None, }, ); actor @@ -1540,7 +1518,7 @@ fn stale_config_response_refreshes_snapshot_without_cross_generation_response() method: "session/set_config_option".into(), explicit_delivery: false, withdrawal_pending: false, - replay: false, + replay: ReplayMode::None, }, ); actor @@ -1873,6 +1851,7 @@ fn resident_startup_omitted_or_empty_mcp_retains_overlay() { session: actor.id.clone(), replace: true, replay: false, + replay_mode: None, startup: if via_attach { Some(startup.clone()) } else { @@ -1923,6 +1902,7 @@ fn initial_startup_preserves_mcp_servers() { session: actor.id.clone(), replace: false, replay: false, + replay_mode: None, startup: None, }, &writes, @@ -1965,6 +1945,7 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { session: actor.id.clone(), replace: true, replay: false, + replay_mode: None, startup: None, } }, @@ -1982,6 +1963,7 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { session: actor.id.clone(), replace: true, replay: false, + replay_mode: None, startup: Some(startup), } } else { diff --git a/tests/gateway.rs b/tests/gateway.rs index 35e13f38..8251b813 100644 --- a/tests/gateway.rs +++ b/tests/gateway.rs @@ -3187,3 +3187,101 @@ async fn standard_close_releases_residency_and_preserves_explicit_resume() { stop_gateway(&mut gateway).await; provider.abort(); } + +#[tokio::test] +async fn pinned_session_creates_fans_out_replays_current_turn_and_restores_across_restart() { + let (fixture, mut requests, provider) = controlled_provider().await; + let (mut gateway, url) = fixture + .gateway_with_bind("127.0.0.1:0", &["--pinned-session", "pinned-e2e"]) + .await; + + // Connect two real ACP HTTP SDK clients simultaneously. + let mut c1 = SdkClient::connect(&url).await; + let created = c1 + .request( + 2, + "session/new", + json!({"cwd": fixture.root, "mcpServers": []}), + ) + .await; + assert!(created.get("error").is_none(), "{created}"); + assert_eq!(created["result"]["sessionId"], "pinned-e2e"); + + let mut c2 = SdkClient::connect(&url).await; + let attached = c2 + .request( + 2, + "session/resume", + json!({"sessionId": "pinned-e2e", "cwd": fixture.root}), + ) + .await; + assert!(attached.get("error").is_none(), "{attached}"); + assert_eq!(attached["result"]["sessionId"], "pinned-e2e"); + + // Turn 1: submitted by c1, updates fan out to BOTH c1 and c2. + c1.start_prompt(10, "pinned-e2e", "First pinned question") + .await; + let (_, release1) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + release1.send("First pinned answer.").unwrap(); + c1.wait_idle().await; + c2.wait_idle().await; + assert_replayed_answer(&c1.updates, "First pinned answer."); + assert_replayed_answer(&c2.updates, "First pinned answer."); + + // Turn 2: submitted by c2; then c3 joins with `_kit_current_turn` and sees Turn 2 only. + c2.start_prompt(11, "pinned-e2e", "Second pinned question") + .await; + let (_, release2) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + release2.send("Second pinned answer.").unwrap(); + c1.wait_idle().await; + c2.wait_idle().await; + + let mut c3 = SdkClient::connect(&url).await; + let resumed_turn = c3 + .request( + 2, + "session/resume", + json!({ + "sessionId": "pinned-e2e", + "cwd": fixture.root, + "replayFrom": {"type": "_kit_current_turn"} + }), + ) + .await; + assert!(resumed_turn.get("error").is_none(), "{resumed_turn}"); + assert_replayed_answer(&c3.updates, "Second pinned answer."); + let c3_json = serde_json::to_string(&c3.updates).unwrap(); + assert!( + !c3_json.contains("First pinned answer."), + "current-turn replay should exclude Turn 1: {c3_json}" + ); + + c1.detach().await; + c2.detach().await; + c3.detach().await; + stop_gateway(&mut gateway).await; + + // Restart gateway pinned to the same ID -> restores existing transcript from disk! + let (mut gateway2, url2) = fixture + .gateway_with_bind("127.0.0.1:0", &["--pinned-session", "pinned-e2e"]) + .await; + let mut c4 = SdkClient::connect(&url2).await; + let restored = c4 + .request( + 2, + "session/resume", + json!({ + "sessionId": "pinned-e2e", + "cwd": fixture.root, + "replayFrom": {"type": "start"} + }), + ) + .await; + assert!(restored.get("error").is_none(), "{restored}"); + assert_eq!(restored["result"]["sessionId"], "pinned-e2e"); + assert_replayed_answer(&c4.updates, "First pinned answer.Second pinned answer."); + + c4.detach().await; + stop_gateway(&mut gateway2).await; + provider.abort(); +} From e1c9df1ebb852f7f074d778d2aeb36711eb33fca Mon Sep 17 00:00:00 2001 From: daniel Date: Sat, 28 Nov 2026 20:40:25 +0000 Subject: [PATCH 02/19] fix(gateway): harden pinned-session replay, caps, reaping, and relay handling Addresses review defects and simplifies pinned-session gateway implementation: - Default absent/null replayFrom to ReplayMode::None for both session/new and session/resume in pinned mode (including cold restore over large transcripts). - Isolate orphaned held prompts from the shared 128 active pending cap (bounded separately at 256) and enforce a 32 per-attachment cap after verifying agentkit-acp withdrawal cancels the entire idempotency group. - Truncate _kit_current_turn gracefully when the turn start is evicted, marking result._meta["kit/gateway"].replayTruncated = true. - Reap expired pinned attachments and leaked startup drivers on the actor deadline timer and bound parked cold-startup joiners. - Restrict unsupported-method target declines to -32601 only, buffer winning relayed client replies across child-stdin backpressure, and cancel pending relayed requests on child exit. - Fix session/list cwd filtering and foreign sessionId checks, update docs, deduplicate gateway actor paths, and add regression and real-child integration tests. --- docs/reference/gateway-protocol.md | 24 +- docs/user/gateway.md | 6 +- src/gateway.rs | 1620 +++++++++++++-------------- src/gateway/http_server.rs | 34 +- src/gateway/pinned_tests.rs | 1646 +++++++++++++++++++++++++++- src/gateway/tests.rs | 41 +- tests/gateway.rs | 115 ++ 7 files changed, 2580 insertions(+), 906 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 0f57227b..38ca3e0b 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -174,23 +174,23 @@ Only user messages with durable identities support partial replay. Agent-message Start the gateway with `--pinned-session ` (and optionally `--client-request-timeout `, default `5m`) to serve one session to many simultaneous ACP HTTP attachments. Default single-controller gateway behavior is unchanged when `--pinned-session` is omitted. > [!WARNING] -> **Security boundary:** All attachments connected to a pinned-session gateway share the same session. Every attached client receives all session updates, can submit prompts or cancel foreground work, and can answer relayed agent-to-client requests. Because the gateway authenticates only with its single bearer credential, place an authenticating proxy in front of `kit gateway --pinned-session` whenever serving multiple users, browsers, or services. +> **Security boundary:** All attachments connected to a pinned-session gateway share the same session. Every attached client receives all session updates, can submit prompts or cancel foreground work, can answer relayed agent-to-client requests, and can call `session/set_config_option` and `_kit/session/update_mcp`. Because `_kit/session/update_mcp` can register stdio MCP servers that execute commands in the host or sandbox, and the gateway authenticates only with its single bearer credential, place an authenticating proxy in front of `kit gateway --pinned-session` and filter methods for clients you do not trust with that level of control. When pinned mode is active: -- **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. `session/list` returns only that single pinned session entry, with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). -- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. +- **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. The first client's `initialize` `info` is what the child receives. `session/list` returns only that single pinned session entry (even if `params.cwd` does not match, while rejecting any foreign `params.sessionId`), with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). +- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach; an abandoned attachment holds its slot until reaped after the 15-second lease (including an abandoned cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. - **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. -- **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `data.reason = "queue_overflow"`, its pending requests fail with that reason, and its SSE stream closes cleanly without affecting other attachments or the active turn. -- **Fan-in and deduplication:** Responses to client requests are delivered only to the originating attachment. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). +- **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, its failed pending requests carry `error.data.reason = "queue_overflow"`, and its SSE stream closes cleanly without affecting other attachments or the active turn. +- **Fan-in, pending caps, and deduplication:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped at 32 per attachment and 128 active across all live attachments; orphaned held prompts left behind by detached deliverers do not count against the shared 128 cap and are bounded separately at 256. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). - **Detach and cancel:** Disconnecting an attachment does not withdraw its already-submitted held prompts, so a deliverer may disconnect before insertion and retry with the same `idempotencyKey`. Explicit `$/cancel_request` from the originating attachment still withdraws its own held prompt. Any live attachment may send `session/cancel`. -- **Replay cursors for late joiners:** `session/resume` accepts: - - omitted / `null`: no history; delivers current config and state snapshots only (`historyAvailable: false`). +- **Replay cursors for late joiners:** Both `session/new` and `session/resume` accept `replayFrom`: + - omitted / `null`: no history; delivers current config and state snapshots only (`historyAvailable: false`). This is the default for both `session/new` and `session/resume` in pinned mode (including cold restores whose transcript exceeds the replay buffer). - `{"type":"start"}`: full retained journal from the beginning of the session (fails with `replay_unavailable` if earlier events were evicted). - - `{"type":"_kit_current_turn"}`: replays from the start of the current (or most recent) turn so a mid-turn joiner can render in-progress assistant output, even after older turns have been evicted from the journal. + - `{"type":"_kit_current_turn"}`: replays from the start of the current (or most recent) turn so a mid-turn joiner can render in-progress assistant output, even after older turns have been evicted from the journal. If the current turn itself outgrew the journal and its start was evicted, the gateway replays from the oldest retained update of the current turn and sets `result._meta["kit/gateway"].replayTruncated = true`. - `{"type":"_kit_message","sessionId":"SESSION_ID","messageId":"MESSAGE_ID"}`: inclusive replay from a retained user message ID; rejects unknown, evicted, or session-mismatched cursors with JSON-RPC `-32602`. -- **Relayed agent-to-client requests:** In pinned mode the gateway advertises form elicitation to the child and relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`) to every live attachment. Clients that attach while a request is still pending receive it immediately after their startup response and become eligible targets. +- **Relayed agent-to-client requests:** In pinned mode the gateway advertises form elicitation (`{"elicitation":{"form":{}}}`) to the child and relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending) to every live attachment. Clients that attach while a request is still pending receive it immediately after their startup response and become eligible targets. - If no attachment is live when the request arrives, the gateway answers `-32601` immediately. - - The first valid `result` from any target attachment wins and is forwarded to the child; every other target receives `$/cancel_request` for that relayed request ID. - - A `-32601` error from an attachment that does not implement the method removes only that target; if no targets remain after `-32601` declines, the gateway answers `-32601` to the child. - - Target detach does not cancel a pending request (so transient reconnects such as browser reloads can still answer). If the request is neither answered nor cancelled by the agent before `--client-request-timeout` (default `5m`), the gateway answers the child with `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) and sends `$/cancel_request` to current targets. + - The first valid `result` from any target attachment wins and is forwarded to the child (buffered across transient child-stdin backpressure); every other target receives `$/cancel_request` for that relayed request ID. + - A `-32601` error from an attachment that does not implement the method removes only that target; if every target declined with `-32601` and none remain, the gateway answers `-32601` to the child. Any other error from a client removes only that client as a target without counting as a method-unsupported decline, keeping the request pending for remaining targets or late joiners until the timeout. + - Target detach does not cancel a pending request (so transient reconnects such as browser reloads can still answer). `--client-request-timeout` (default `5m`) is an absolute deadline measured from when the child request arrives. If the request is neither answered nor cancelled by the agent before the deadline, the gateway answers the child with `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. diff --git a/docs/user/gateway.md b/docs/user/gateway.md index d064ac3b..fa3b4b18 100644 --- a/docs/user/gateway.md +++ b/docs/user/gateway.md @@ -118,9 +118,9 @@ kit gateway --credential-file "$HOME/.kit-gateway-token" \ --client-request-timeout 5m ``` -- **Shared session boundary:** All attachments share the pinned session: every connected client receives all live updates, can submit prompts or cancel work, and can answer relayed interactive questions or permission requests. Place an authenticating proxy in front of `kit gateway --pinned-session` when serving multiple users or services; the gateway itself verifies only its single bearer token. +- **Shared session boundary:** All attachments share the pinned session: every connected client receives all live updates, can submit prompts or cancel work, can answer relayed interactive questions or permission requests, and can call `session/set_config_option` and `_kit/session/update_mcp` (which can register stdio MCP servers that run commands in the host or sandbox). Place an authenticating proxy in front of `kit gateway --pinned-session` when serving multiple users or services and filter methods for less-trusted clients; the gateway itself verifies only its single bearer token. - **Independent attachments:** Connecting a second client does not displace existing clients or withdraw their held prompts. Sending `session/close` detaches only the calling client without ending the session. If a slow client's output queue overflows, only that client is disconnected; other attachments and the active turn continue. -- **Late joiners and reconnects:** Clients can attach with `replayFrom: {"type":"_kit_current_turn"}` to catch up on the current or most recent turn, or `{"type":"_kit_message","sessionId":"...","messageId":"..."}` to resume from a retained user message, without replaying the entire session journal. +- **Late joiners and reconnects:** In pinned mode, both `session/new` and `session/resume` omit historical replay by default unless `replayFrom` is provided. Clients can attach with `replayFrom: {"type":"start"}` for full retained history, `{"type":"_kit_current_turn"}` to catch up on the current or most recent turn, or `{"type":"_kit_message","sessionId":"...","messageId":"..."}` to resume from a retained user message. - **Interactive prompts (`--client-request-timeout`):** Agent-to-client requests (such as `ask_user` forms) are sent to all attached clients and to clients that attach while the request is pending; the first valid answer wins and the other clients receive a cancellation. If no client is attached when the request arrives, it fails immediately rather than blocking the turn. If clients detach mid-request, the request stays pending until answered, cancelled, or `--client-request-timeout` (default `5m`) expires. For exact wire behavior, cursors, and limits, see [Pinned-session mode](../reference/gateway-protocol.md#pinned-session-mode). @@ -150,6 +150,6 @@ See [Implement an ACP HTTP client](../reference/gateway-protocol.md#implement-an - There is no fixed resident-session count ceiling. Provision memory and process capacity for your workload. Detaching does not stop a session, even when it is idle; use `session/close` to end resident work. Listing or creating sessions reclaims completed entries without deleting durable transcripts. - Transport saturation can disconnect a client without canceling accepted work. HTTP frames are limited to 1 MiB; child output frames to 8 MiB. Oversized or malformed child output stops that child. There is no idle connection expiration or body-read deadline: abandoned transports can retain connection slots, and exhaustion may require restarting the gateway. See [Transport limits](../reference/gateway-protocol.md#transport-limits) before sizing an integration. These bounds are not a hard process-memory ceiling or denial-of-service protection. - Use `Ctrl+C` on the gateway host for graceful shutdown. Kit waits for child cleanup and exit, then forcibly stops a child if it exceeds the 10-second timeout. That fallback can leave a stale transcript lock requiring operator intervention. Hard process termination has operating-system-dependent cleanup behavior; arbitrary tool descendants are not a managed process group. -- In default single-controller mode, client-side ACP services are not supported (pinned-session mode relays agent-to-client requests such as `ask_user` forms to attached clients). Arbitrary extra directories, legacy SSE MCP servers, browser callbacks, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. +- Client-side ACP services (outside pinned-session mode), arbitrary extra directories, session-scoped HTTP/SSE MCP servers, browser callbacks, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. The internal `gateway bridge` stdio command is a transport adapter for the bundled TUI, not a stable public protocol or general-purpose ACP proxy. The public transport is ACP HTTP at `/acp/v2`, implemented by the ACP SDK rather than a Kit-specific RPC protocol. diff --git a/src/gateway.rs b/src/gateway.rs index 9ed55cda..cbd15c08 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -23,19 +23,23 @@ use std::{ Arc, atomic::{AtomicBool, Ordering}, }, - time::{Duration, Instant}, + time::Duration, }; use tokio::{ io::AsyncWriteExt, sync::{Mutex, mpsc, oneshot, watch}, + time::Instant, }; const LEASE: Duration = Duration::from_secs(15); const DEFAULT_CLIENT_REQUEST_TIMEOUT: Duration = Duration::from_secs(300); const MAX_REPLAY: usize = 8 * 1024 * 1024; const MAX_HTTP_FRAME: usize = 1024 * 1024; const MAX_QUEUE: usize = 4096; +const MAX_PENDING_SHARED: usize = 128; +const MAX_PENDING_PER_ATTACHMENT: usize = 32; +const MAX_ORPHANED_PENDING: usize = 256; +const MAX_WAITING_STARTUPS: usize = 64; const MAX_PINNED_CLIENT_REQUESTS: usize = 64; -const MAX_OVERFLOW_HISTORY: usize = 256; fn object(fields: [(&str, Value); N]) -> Value { Value::Object( @@ -267,21 +271,47 @@ impl Remote { } } #[derive(Clone, Debug, PartialEq, Eq)] -#[cfg_attr(test, derive(Deserialize))] -#[cfg_attr(test, serde(tag = "type", rename_all = "snake_case"))] enum ReplayMode { None, Start, CurrentTurn, Message { message_id: String }, } - -fn effective_replay_mode(replay: bool, replay_mode: Option) -> ReplayMode { - replay_mode.unwrap_or(if replay { - ReplayMode::Start - } else { - ReplayMode::None - }) +#[cfg(test)] +impl<'de> Deserialize<'de> for ReplayMode { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(untagged)] + enum Wire { + Bool(bool), + Tagged { + #[serde(rename = "type")] + kind: String, + #[serde(default)] + message_id: Option, + }, + } + match Wire::deserialize(deserializer)? { + Wire::Bool(true) => Ok(Self::Start), + Wire::Bool(false) => Ok(Self::None), + Wire::Tagged { kind, message_id } => match kind.as_str() { + "none" => Ok(Self::None), + "start" => Ok(Self::Start), + "current_turn" => Ok(Self::CurrentTurn), + "message" => Ok(Self::Message { + message_id: message_id + .ok_or_else(|| serde::de::Error::missing_field("message_id"))?, + }), + other => Err(serde::de::Error::unknown_variant( + other, + &["none", "start", "current_turn", "message"], + )), + }, + } + } } fn parse_replay_mode( @@ -291,7 +321,7 @@ fn parse_replay_mode( is_new: bool, ) -> Result { let Some(cursor) = cursor.filter(|value| !value.is_null()) else { - return Ok(if is_new { + return Ok(if !pinned && is_new { ReplayMode::Start } else { ReplayMode::None @@ -370,9 +400,7 @@ enum Request { }, Attach { session: String, - replay: bool, - #[cfg_attr(test, serde(default))] - replay_mode: Option, + replay: ReplayMode, #[cfg_attr(test, serde(default))] replace: bool, #[cfg_attr(test, serde(default))] @@ -727,71 +755,19 @@ async fn handle( gateway.reclaim_exited().await; let entries = gateway.sessions.lock().await.clone(); let roots = gateway.roots.clone(); - let pinned = gateway.pinned.clone(); + let pinned_id = gateway.pinned.as_ref().map(|p| p.session_id.clone()); let rows = tokio::task::spawn_blocking(move || { - if let Some(pinned) = pinned { - let id = pinned.session_id; - let resident = entries.get(&id); - let mut catalog_match = None; - for root in &roots { - let catalog = - crate::session::catalog(root).map_err(Failure::unavailable)?; - if let Some(entry) = catalog.into_iter().find(|entry| entry.id == id) { - catalog_match = Some((root.clone(), entry)); - break; - } - } - let row = if let Some(entry) = resident { - let state = if entry.sender.is_closed() { - "exited" - } else { - "resident" - }; - if let Some((_, catalog_entry)) = catalog_match { - object([ - ("session", id.into()), - ("root", entry.root.to_string_lossy().into_owned().into()), - ("title", catalog_entry.title.into()), - ("preview", catalog_entry.preview.into()), - ("state", state.into()), - ]) - } else { - object([ - ("session", id.into()), - ("root", entry.root.to_string_lossy().into_owned().into()), - ("state", state.into()), - ]) - } - } else if let Some((root, catalog_entry)) = catalog_match { - object([ - ("session", id.into()), - ("root", root.to_string_lossy().into_owned().into()), - ("title", catalog_entry.title.into()), - ("preview", catalog_entry.preview.into()), - ("state", "restorable".into()), - ]) - } else if let Some(root) = roots.first() { - object([ - ("session", id.into()), - ("root", root.to_string_lossy().into_owned().into()), - ("state", "new".into()), - ]) - } else { - return Ok::<_, Failure>(Vec::new()); - }; - return Ok::<_, Failure>(vec![row]); - } let mut rows = Vec::new(); - for root in roots { - let catalog = crate::session::catalog(&root).map_err(Failure::unavailable)?; + for root in &roots { + let catalog = crate::session::catalog(root).map_err(Failure::unavailable)?; for entry in catalog { - let state = if entries - .get(&entry.id) - .is_some_and(|e| !e.sender.is_closed()) - { - "resident" - } else { - "restorable" + if pinned_id.as_deref().is_some_and(|id| id != entry.id) { + continue; + } + let state = match entries.get(&entry.id) { + Some(e) if !e.sender.is_closed() => "resident", + Some(_) if pinned_id.is_some() => "exited", + _ => "restorable", }; rows.push(object([ ("session", entry.id.into()), @@ -803,6 +779,9 @@ async fn handle( } } for (id, entry) in entries { + if pinned_id.as_deref().is_some_and(|pin| pin != id) { + continue; + } if !rows.iter().any(|row| row["session"] == id) { rows.push(object([ ("session", id.into()), @@ -819,6 +798,16 @@ async fn handle( ])); } } + if let Some(id) = pinned_id + && rows.is_empty() + && let Some(root) = roots.first() + { + rows.push(object([ + ("session", id.into()), + ("root", root.to_string_lossy().into_owned().into()), + ("state", "new".into()), + ])); + } Ok::<_, Failure>(rows) }) .await @@ -837,7 +826,7 @@ async fn handle( return Err(Failure::root("project is not registered")); } gateway.reclaim_exited().await; - if let Some(pinned) = &gateway.pinned { + let (id, check_workspace, pinned_timeout) = if let Some(pinned) = &gateway.pinned { if let Some(requested) = &session && requested != &pinned.session_id { @@ -846,52 +835,17 @@ async fn handle( pinned.session_id ))); } - let id = pinned.session_id.clone(); - { - let entries = gateway.sessions.lock().await; - if let Some(entry) = entries.get(&id).filter(|e| !e.sender.is_closed()) { - if entry.root != root { - return Err(Failure::root("session belongs to another project")); - } - return Ok(Json(object([ - ("session", id.into()), - ("root", root.to_string_lossy().into_owned().into()), - ("state", "resident".into()), - ]))); - } - } - let restore = - crate::session::belongs_to_workspace(&root, &id).map_err(Failure::bad)?; - let mut entries = gateway.sessions.lock().await; - if gateway.stopping.load(Ordering::Acquire) { - return Err(Failure::unavailable("gateway is stopping")); - } - if let Some(entry) = entries.get(&id).filter(|e| !e.sender.is_closed()) { - if entry.root != root { - return Err(Failure::root("session belongs to another project")); - } - } else { - let entry = spawn( - &root, - &id, - restore, - force, - Some(pinned.client_request_timeout), - ) - .map_err(|error| Failure::unavailable(error.to_string()))?; - let replaced = entries.insert(id.clone(), entry); - drop(entries); - drop(replaced); - } - return Ok(Json(object([ - ("session", id.into()), - ("root", root.to_string_lossy().into_owned().into()), - ("state", "resident".into()), - ]))); - } - let restore = session.is_some(); - let id = session.unwrap_or_else(crate::session::new_id); - if restore { + ( + pinned.session_id.clone(), + true, + Some(pinned.client_request_timeout), + ) + } else { + let check = session.is_some(); + (session.unwrap_or_else(crate::session::new_id), check, None) + }; + let mut restore = false; + if check_workspace { let entries = gateway.sessions.lock().await; if let Some(entry) = entries.get(&id).filter(|e| !e.sender.is_closed()) { if entry.root != root { @@ -904,9 +858,12 @@ async fn handle( ]))); } drop(entries); - if !crate::session::belongs_to_workspace(&root, &id).map_err(Failure::bad)? { + let belongs = + crate::session::belongs_to_workspace(&root, &id).map_err(Failure::bad)?; + if pinned_timeout.is_none() && !belongs { return Err(Failure::root("session does not belong to this project")); } + restore = belongs; } let mut entries = gateway.sessions.lock().await; if gateway.stopping.load(Ordering::Acquire) { @@ -917,7 +874,7 @@ async fn handle( return Err(Failure::root("session belongs to another project")); } } else { - let entry = spawn(&root, &id, restore, force, None) + let entry = spawn(&root, &id, restore, force, pinned_timeout) .map_err(|error| Failure::unavailable(error.to_string()))?; let replaced = entries.insert(id.clone(), entry); drop(entries); @@ -984,8 +941,21 @@ struct Attachment { bytes: usize, live: bool, closing: bool, + overflowed: bool, } impl Attachment { + fn new(id: String) -> Self { + Self { + id, + touched: Instant::now(), + next: 0, + events: VecDeque::new(), + bytes: 0, + live: false, + closing: false, + overflowed: false, + } + } fn push(&mut self, message: Value) -> bool { let bytes = message.to_string().len(); if self.events.len() >= MAX_QUEUE || self.bytes + bytes > MAX_REPLAY { @@ -1003,6 +973,9 @@ struct Pending { method: String, explicit_delivery: bool, withdrawal_pending: bool, + // In pinned mode, detached attachments leave held prompts pending without + // consuming the shared active cap. + orphaned: bool, // The caller's policy, independent of full internal child cache seeding. replay: ReplayMode, } @@ -1011,17 +984,30 @@ struct WaitingStartup { request_id: Value, replay: ReplayMode, } +struct PreparedPinnedStartup { + messages: Vec, + pending_requests: Vec<(String, Value)>, +} struct PendingClientRequest { seq: u64, child_id: Value, method: String, params: Value, targets: HashSet, - deadline: tokio::time::Instant, + deadline: Instant, + // True once any target failed with a non-(-32601) error; prevents treating + // remaining -32601 declines as "no attachment supports this". + had_client_error: bool, + // Buffered child-bound JSON-RPC reply when child stdin is backpressured. + resolved_reply: Option<(Value, Option>)>, +} +enum RetireMode { + Remove, + Overflow, + Closing, } struct PinnedState { attachments: HashMap, - overflowed: VecDeque, startup_driver: Option, waiting_startups: Vec, client_request_timeout: Duration, @@ -1032,7 +1018,6 @@ impl PinnedState { fn new(client_request_timeout: Duration) -> Self { Self { attachments: HashMap::new(), - overflowed: VecDeque::new(), startup_driver: None, waiting_startups: Vec::new(), client_request_timeout, @@ -1041,39 +1026,11 @@ impl PinnedState { } } - fn record_overflow(&mut self, id: String) { - if self.overflowed.iter().any(|existing| existing == &id) { - return; - } - if self.overflowed.len() >= MAX_OVERFLOW_HISTORY { - self.overflowed.pop_front(); - } - self.overflowed.push_back(id); - } - - fn is_overflowed(&self, id: &str) -> bool { - self.overflowed.iter().any(|existing| existing == id) - } - - fn take_overflow(&mut self, id: &str) -> bool { - if let Some(pos) = self.overflowed.iter().position(|existing| existing == id) { - self.overflowed.remove(pos); - true - } else { - false - } - } - - fn remove_target_from_requests(&mut self, attachment_id: &str) { - for request in self.client_requests.values_mut() { - request.targets.remove(attachment_id); - } - } - fn pending_request_messages(&self) -> Vec<(String, Value)> { let mut items: Vec<_> = self .client_requests .iter() + .filter(|(_, req)| req.resolved_reply.is_none()) .map(|(relay_id, req)| { ( req.seq, @@ -1211,18 +1168,19 @@ impl Actor { }); let mut lines = framing::Lines::new(stdout); loop { + self.reap_expired_pinned_attachments(); let withdrawal = self.next_withdrawal(); - let expired_request = if withdrawal.is_none() { - self.next_expired_client_request() + let ready_client_reply = if withdrawal.is_none() { + self.next_ready_client_reply() } else { None }; - let next_deadline = if withdrawal.is_none() && expired_request.is_none() { - self.next_client_request_deadline() + let next_deadline = if withdrawal.is_none() && ready_client_reply.is_none() { + self.next_pinned_deadline() } else { None }; - let needs_write = withdrawal.is_some() || expired_request.is_some(); + let needs_write = withdrawal.is_some() || ready_client_reply.is_some(); let event = { let write_permit = std::pin::pin!(async { if needs_write { @@ -1251,8 +1209,8 @@ impl Actor { }; if let Some(id) = withdrawal { self.send_withdrawal(id, permit); - } else if let Some(relay_id) = expired_request { - self.expire_client_request(&relay_id, permit); + } else if let Some(relay_id) = ready_client_reply { + self.flush_client_request_reply(&relay_id, permit); } continue; } @@ -1310,6 +1268,8 @@ impl Actor { break; } } + // Cancel any pending relayed requests for live targets when the child exits. + self.cancel_all_relayed_client_requests(); // EOF permits ACP's normal session cleanup to release transcript locks. // Abort the writer (including a stalled write) to close stdin, then drain // stdout concurrently with waiting: final notifications must not fill a @@ -1335,8 +1295,15 @@ impl Actor { continue; } let poll = matches!(command.request, Request::Poll { .. }); + let has_pinned_drain = poll + && !stopping + && self.pinned.as_ref().is_some_and(|p| { + p.attachments.values().any(|a| !a.events.is_empty()) + }); let result = if self.closed { self.command(command.request, &writes) + } else if has_pinned_drain { + Ok(object([])) } else { Err(Failure::unavailable("child exited; restore its transcript")) } @@ -1376,6 +1343,31 @@ impl Actor { } }; let _ = tokio::time::timeout(LEASE, drain).await; + } else if !stopping + && self + .pinned + .as_ref() + .is_some_and(|p| p.attachments.values().any(|a| !a.events.is_empty())) + { + // Briefly drain queued terminal notifications (such as $/cancel_request + // for relayed requests) before reporting child exit to pinned attachments. + let drain = async { + while let Some(command) = commands.recv().await { + if matches!(command.request, Request::Shutdown) { + break; + } + let result = self.drain_exited_pinned(command.request); + let _ = command.reply.send(result); + if !self + .pinned + .as_ref() + .is_some_and(|p| p.attachments.values().any(|a| !a.events.is_empty())) + { + break; + } + } + }; + let _ = tokio::time::timeout(Duration::from_secs(2), drain).await; } } fn emit(&mut self, message: Value) { @@ -1393,15 +1385,30 @@ impl Actor { return false; }; let overflowed = if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { + if attachment.overflowed { + return false; + } !attachment.push(message) } else { return false; }; if overflowed { - let mut failed_waiters = Vec::new(); - pinned.attachments.remove(attachment_id); - pinned.record_overflow(attachment_id.to_owned()); - pinned.remove_target_from_requests(attachment_id); + self.retire_pinned_attachment(attachment_id, RetireMode::Overflow); + return false; + } + true + } + fn retire_pinned_attachment(&mut self, attachment_id: &str, mode: RetireMode) { + let mut failed_waiters = Vec::new(); + for pending in self.pending.values_mut() { + if pending.attachment == attachment_id { + pending.orphaned = true; + } + } + if let Some(pinned) = &mut self.pinned { + for request in pinned.client_requests.values_mut() { + request.targets.remove(attachment_id); + } pinned .waiting_startups .retain(|waiter| waiter.attachment != attachment_id); @@ -1415,20 +1422,114 @@ impl Actor { failed_waiters = std::mem::take(&mut pinned.waiting_startups); } } - for waiter in failed_waiters { - self.push_pinned_startup_error( - &waiter.attachment, - waiter.request_id, - object([ - ("code", (-32000).into()), - ("message", "session startup interrupted; retry".into()), - ("data", Failure::unavailable("startup interrupted").data()), - ]), - ); + match mode { + RetireMode::Remove => { + pinned.attachments.remove(attachment_id); + } + RetireMode::Overflow => { + if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { + attachment.events.clear(); + attachment.bytes = 0; + attachment.live = false; + attachment.closing = false; + attachment.overflowed = true; + attachment.touched = Instant::now(); + } + } + RetireMode::Closing => { + if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { + attachment.live = false; + attachment.closing = true; + } + } } - return false; } - true + for waiter in failed_waiters { + self.push_pinned_startup_error( + &waiter.attachment, + waiter.request_id, + object([ + ("code", (-32000).into()), + ("message", "session startup interrupted; retry".into()), + ("data", Failure::unavailable("startup interrupted").data()), + ]), + ); + } + } + fn reap_expired_pinned_attachments(&mut self) { + let now = Instant::now(); + let expired: Vec = self + .pinned + .as_ref() + .map(|pinned| { + pinned + .attachments + .values() + .filter(|a| a.touched + LEASE <= now) + .map(|a| a.id.clone()) + .collect() + }) + .unwrap_or_default(); + for id in expired { + self.retire_pinned_attachment(&id, RetireMode::Remove); + } + } + fn drain_exited_pinned(&mut self, request: Request) -> ResultValue { + match request { + Request::Detach { attachment, .. } => { + if let Some(pinned) = &mut self.pinned { + pinned.attachments.remove(&attachment); + } + Ok(object([])) + } + Request::Poll { + attachment, cursor, .. + } => { + let Some(pinned) = &mut self.pinned else { + return Err(Failure::unavailable("child exited; restore its transcript")); + }; + let Some(entry) = pinned.attachments.get_mut(&attachment) else { + return Err(Failure::unavailable("child exited; restore its transcript")); + }; + if entry.overflowed { + pinned.attachments.remove(&attachment); + return Err(Failure( + StatusCode::CONFLICT, + "attachment queue overflowed; reconnect".into(), + "queue_overflow", + )); + } + if cursor > entry.next { + return Err(Failure::bad("invalid event cursor")); + } + while entry + .events + .front() + .is_some_and(|(sequence, _)| *sequence <= cursor) + { + if let Some((_, message)) = entry.events.pop_front() { + entry.bytes -= message.to_string().len(); + } + } + if entry.events.is_empty() { + pinned.attachments.remove(&attachment); + return Err(Failure::unavailable("child exited; restore its transcript")); + } + let events: Vec<_> = entry + .events + .iter() + .take(128) + .map(|(sequence, message)| { + object([("cursor", (*sequence).into()), ("message", message.clone())]) + }) + .collect(); + Ok(object([ + ("closed", false.into()), + ("events", events.into()), + ])) + } + _ => Err(Failure::unavailable("child exited; restore its transcript")), + } } fn push_pinned_startup_error(&mut self, attachment_id: &str, request_id: Value, error: Value) { let message = object([ @@ -1457,31 +1558,45 @@ impl Actor { } seq } - fn next_expired_client_request(&self) -> Option { + fn next_ready_client_reply(&self) -> Option { let pinned = self.pinned.as_ref()?; - let now = tokio::time::Instant::now(); + let now = Instant::now(); pinned .client_requests .iter() - .filter(|(_, req)| req.deadline <= now) - .min_by_key(|(_, req)| (req.deadline, req.seq)) + .filter(|(_, req)| req.resolved_reply.is_some() || req.deadline <= now) + .min_by_key(|(_, req)| (req.resolved_reply.is_none(), req.deadline, req.seq)) .map(|(relay_id, _)| relay_id.clone()) } - fn next_client_request_deadline(&self) -> Option { - self.pinned - .as_ref()? + fn next_pinned_deadline(&self) -> Option { + let pinned = self.pinned.as_ref()?; + let request_deadline = pinned .client_requests .values() + .filter(|req| req.resolved_reply.is_none()) .map(|req| req.deadline) - .min() + .min(); + let lease_deadline = pinned.attachments.values().map(|a| a.touched + LEASE).min(); + match (request_deadline, lease_deadline) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } } - fn expire_client_request(&mut self, relay_id: &str, permit: mpsc::Permit<'_, ChildWrite>) { + fn flush_client_request_reply(&mut self, relay_id: &str, permit: mpsc::Permit<'_, ChildWrite>) { let Some(pinned) = &mut self.pinned else { return; }; let Some(req) = pinned.client_requests.remove(relay_id) else { return; }; + if let Some((message, charge)) = req.resolved_reply { + permit.send(ChildWrite { + withdrawals: Vec::new(), + message, + _charge: charge, + }); + return; + } permit.send(ChildWrite { withdrawals: Vec::new(), message: incoming_transport_closed_reply(req.child_id, &req.method), @@ -1492,6 +1607,22 @@ impl Actor { self.push_pinned_attachment(&target, cancel.clone()); } } + fn cancel_all_relayed_client_requests(&mut self) { + let drained = if let Some(pinned) = &mut self.pinned { + std::mem::take(&mut pinned.client_requests) + } else { + return; + }; + for (relay_id, req) in drained { + if req.resolved_reply.is_some() { + continue; + } + let cancel = cancel_request_message(Value::String(relay_id)); + for target in req.targets { + self.push_pinned_attachment(&target, cancel.clone()); + } + } + } fn relay_client_request( &mut self, child_id: Value, @@ -1517,7 +1648,7 @@ impl Actor { let live_targets: Vec = pinned .attachments .values() - .filter(|a| a.live && !a.closing) + .filter(|a| a.live && !a.closing && !a.overflowed) .map(|a| a.id.clone()) .collect(); if live_targets.is_empty() { @@ -1566,7 +1697,9 @@ impl Actor { method, params, targets: delivered, - deadline: tokio::time::Instant::now() + timeout, + deadline: Instant::now() + timeout, + had_client_error: false, + resolved_reply: None, }, ); } @@ -1577,7 +1710,8 @@ impl Actor { return; }; let Some(relay_id) = pinned.client_requests.iter().find_map(|(relay_id, req)| { - (&req.child_id == child_request_id).then(|| relay_id.clone()) + (req.resolved_reply.is_none() && &req.child_id == child_request_id) + .then(|| relay_id.clone()) }) else { return; }; @@ -1589,6 +1723,58 @@ impl Actor { self.push_pinned_attachment(&target, cancel.clone()); } } + fn prepare_pinned_startup( + &self, + attachment_id: &str, + existing_events: usize, + existing_bytes: usize, + result: Value, + request_id: Value, + replay: &ReplayMode, + ) -> Result { + let messages = self.startup_messages(result, request_id, replay, attachment_id)?; + let pending_requests = self + .pinned + .as_ref() + .map(PinnedState::pending_request_messages) + .unwrap_or_default(); + let total_count = existing_events + messages.len() + pending_requests.len(); + let total_bytes: usize = existing_bytes + + messages.iter().map(|m| m.to_string().len()).sum::() + + pending_requests + .iter() + .map(|(_, m)| m.to_string().len()) + .sum::(); + if total_count > MAX_QUEUE || total_bytes > MAX_REPLAY { + return Err(Failure::replay( + "session snapshot exceeds the gateway limit", + )); + } + Ok(PreparedPinnedStartup { + messages, + pending_requests, + }) + } + fn apply_pinned_startup(&mut self, attachment_id: &str, prepared: PreparedPinnedStartup) { + for update in prepared.messages { + self.push_pinned_attachment(attachment_id, update); + } + for (relay_id, req_msg) in prepared.pending_requests { + if self.push_pinned_attachment(attachment_id, req_msg) + && let Some(pinned) = &mut self.pinned + && let Some(req) = pinned.client_requests.get_mut(&relay_id) + { + req.targets.insert(attachment_id.to_owned()); + } + } + if let Some(pinned) = &mut self.pinned + && let Some(attachment) = pinned.attachments.get_mut(attachment_id) + && !attachment.overflowed + && !attachment.closing + { + attachment.live = true; + } + } fn deliver_pinned_startup( &mut self, attachment_id: &str, @@ -1596,61 +1782,25 @@ impl Actor { request_id: Value, replay: &ReplayMode, ) { - let startup = self.startup_messages(result, request_id.clone(), replay, attachment_id); - match startup { - Ok(messages) => { - let pending_requests = self - .pinned - .as_ref() - .map(PinnedState::pending_request_messages) - .unwrap_or_default(); - let total_count = messages.len() + pending_requests.len(); - let total_bytes: usize = - messages.iter().map(|m| m.to_string().len()).sum::() - + pending_requests - .iter() - .map(|(_, m)| m.to_string().len()) - .sum::(); - let fits = self - .pinned - .as_ref() - .and_then(|p| p.attachments.get(attachment_id)) - .is_some_and(|a| { - a.events.len() + total_count <= MAX_QUEUE - && a.bytes + total_bytes <= MAX_REPLAY - }); - if fits { - for update in messages { - self.push_pinned_attachment(attachment_id, update); - } - for (relay_id, req_msg) in pending_requests { - if self.push_pinned_attachment(attachment_id, req_msg) - && let Some(pinned) = &mut self.pinned - && let Some(req) = pinned.client_requests.get_mut(&relay_id) - { - req.targets.insert(attachment_id.to_owned()); - } - } - if let Some(pinned) = &mut self.pinned - && let Some(attachment) = pinned.attachments.get_mut(attachment_id) - { - attachment.live = true; - } - return; - } - let error = Failure::replay("snapshot overflow"); - self.push_pinned_startup_error( - attachment_id, - request_id, - object([ - ("code", error.jsonrpc_code().into()), - ( - "message", - "session snapshot exceeds the gateway limit".into(), - ), - ("data", error.data()), - ]), - ); + let Some((existing_events, existing_bytes)) = self + .pinned + .as_ref() + .and_then(|p| p.attachments.get(attachment_id)) + .filter(|a| !a.closing && !a.overflowed) + .map(|a| (a.events.len(), a.bytes)) + else { + return; + }; + match self.prepare_pinned_startup( + attachment_id, + existing_events, + existing_bytes, + result, + request_id.clone(), + replay, + ) { + Ok(prepared) => { + self.apply_pinned_startup(attachment_id, prepared); } Err(error) => { self.push_pinned_startup_error( @@ -1725,7 +1875,7 @@ impl Actor { let targets: Vec = pinned .attachments .values() - .filter(|a| a.live && !a.closing) + .filter(|a| a.live && !a.closing && !a.overflowed) .map(|a| a.id.clone()) .collect(); for target in targets { @@ -1831,11 +1981,13 @@ impl Actor { } } } - } else if self.pinned.as_ref().is_some_and(|p| { - p.attachments - .get(&pending.attachment) - .is_some_and(|a| !a.closing) - }) { + } else if !pending.orphaned + && self.pinned.as_ref().is_some_and(|p| { + p.attachments + .get(&pending.attachment) + .is_some_and(|a| !a.closing && !a.overflowed) + }) + { message["id"] = pending.original; self.push_pinned_attachment(&pending.attachment, message); } @@ -1921,23 +2073,32 @@ impl Actor { replay: &ReplayMode, attachment: &str, ) -> Result, Failure> { - let (mut messages, history_available): (Vec, bool) = match replay { - ReplayMode::None => (Vec::new(), false), + let (mut replay_events, history_available, mut replay_truncated): ( + VecDeque, + bool, + bool, + ) = match replay { + ReplayMode::None => (VecDeque::new(), false, false), ReplayMode::Start => { if !self.replay_complete { return Err(Failure::replay("full live replay is unavailable")); } - (self.journal.iter().cloned().collect(), true) + (self.journal.clone(), true, false) } ReplayMode::CurrentTurn => { if let Some(start_seq) = self.current_turn_start { if start_seq < self.journal_base_seq { - return Err(Failure::replay("current turn replay is unavailable")); + (self.journal.clone(), true, true) + } else { + let offset = (start_seq - self.journal_base_seq) as usize; + ( + self.journal.iter().skip(offset).cloned().collect(), + true, + false, + ) } - let offset = (start_seq - self.journal_base_seq) as usize; - (self.journal.iter().skip(offset).cloned().collect(), true) } else { - (Vec::new(), true) + (VecDeque::new(), true, false) } } ReplayMode::Message { message_id } => { @@ -1953,13 +2114,18 @@ impl Actor { "invalid or no longer retained ACP replay cursor", )); }; - (self.journal.iter().skip(position).cloned().collect(), true) + ( + self.journal.iter().skip(position).cloned().collect(), + true, + false, + ) } }; let options = result .get("configOptions") .cloned() .unwrap_or_else(|| Value::Array(Vec::new())); + let mut snapshots = Vec::with_capacity(3); for update in [ object([ ("sessionUpdate", "config_option_update".into()), @@ -1967,7 +2133,7 @@ impl Actor { ]), self.state.clone(), ] { - messages.push(object([ + snapshots.push(object([ ("jsonrpc", "2.0".into()), ("method", "session/update".into()), ( @@ -1977,17 +2143,47 @@ impl Actor { ])); } result["sessionId"] = self.id.clone().into(); - result["_meta"]["kit/gateway"] = object([ - ("attachment", attachment.into()), - ("historyAvailable", history_available.into()), - ("stateSnapshot", true.into()), - ("configSnapshot", true.into()), - ]); - messages.push(object([ - ("jsonrpc", "2.0".into()), - ("id", id), - ("result", result), - ])); + let build_result = |result: &Value, truncated: bool| { + let mut result = result.clone(); + let mut meta = object([ + ("attachment", attachment.into()), + ("historyAvailable", history_available.into()), + ("stateSnapshot", true.into()), + ("configSnapshot", true.into()), + ]); + if truncated && let Some(map) = meta.as_object_mut() { + map.insert("replayTruncated".into(), true.into()); + } + result["_meta"]["kit/gateway"] = meta; + object([ + ("jsonrpc", "2.0".into()), + ("id", id.clone()), + ("result", result), + ]) + }; + if matches!(replay, ReplayMode::CurrentTurn) { + // For long turns, trim oldest retained updates so the joiner still + // receives the tail of the current turn plus snapshots. + let tail_bytes: usize = snapshots.iter().map(|m| m.to_string().len()).sum::() + + build_result(&result, true).to_string().len(); + let max_events = MAX_QUEUE.saturating_sub(snapshots.len() + 1); + let mut replay_bytes: usize = replay_events.iter().map(|m| m.to_string().len()).sum(); + while replay_events.len() > max_events + || replay_bytes.saturating_add(tail_bytes) > MAX_REPLAY + || replay_events + .front() + .is_some_and(|m| m.to_string().len() > MAX_HTTP_FRAME) + { + let Some(dropped) = replay_events.pop_front() else { + break; + }; + replay_bytes = replay_bytes.saturating_sub(dropped.to_string().len()); + replay_truncated = true; + } + } + let mut messages: Vec = replay_events.into_iter().collect(); + messages.extend(snapshots); + messages.push(build_result(&result, replay_truncated)); if messages .iter() .any(|message| message.to_string().len() > MAX_HTTP_FRAME) @@ -2038,12 +2234,210 @@ impl Actor { } } - fn command(&mut self, request: Request, writes: &mpsc::Sender) -> ResultValue { - if self.pinned.is_some() { - return self.command_pinned(request, writes); + fn validate_session_message(&self, method: &str, message: &Value) -> Result<(), Failure> { + if !message.is_object() || !message["params"].is_object() || message["jsonrpc"] != "2.0" { + return Err(Failure::bad("invalid ACP message")); } - let closing = self.closed || self.pending.values().any(|p| p.method == "session/close"); - if closing + if let Some(session) = message["params"].get("sessionId") + && session != &Value::String(self.id.clone()) + { + return Err(Failure::bad("ACP session does not match gateway session")); + } + if method == "_kit/session/update_mcp" && message["params"]["sessionId"] != self.id { + return Err(Failure::bad("ACP session does not match gateway session")); + } + if method == "kit/background/cancel" && message["params"]["session_id"] != self.id { + return Err(Failure::bad("ACP session does not match gateway session")); + } + Ok(()) + } + + fn handle_cancel_request( + &mut self, + attachment: &str, + original: Option<&Value>, + message: &Value, + closing: bool, + writes: &mpsc::Sender, + ) -> ResultValue { + if original.is_some() { + return Err(Failure::bad("request cancellation must be a notification")); + } + let Some(id) = message["params"] + .get("requestId") + .filter(|id| id.is_string() || id.as_i64().is_some() || id.as_u64().is_some()) + else { + return Err(Failure::bad("valid cancellation requestId required")); + }; + if closing { + return Ok(object([])); + } + let Some((&child_id, pending)) = self.pending.iter_mut().find(|(_, pending)| { + !pending.orphaned + && pending.attachment == attachment + && pending.original == *id + && pending.method == "session/prompt" + }) else { + return Ok(object([])); + }; + // The normalized child notification needs only the remapped ID. + match writes.try_reserve() { + Ok(permit) => self.send_withdrawal(child_id, permit), + Err(mpsc::error::TrySendError::Full(())) => { + pending.withdrawal_pending = true; + } + Err(mpsc::error::TrySendError::Closed(())) => { + return Err(Failure::unavailable("child input writer closed")); + } + } + Ok(object([])) + } + + #[allow(clippy::too_many_arguments)] + fn enqueue_child_message( + &mut self, + attachment: String, + original: Option, + method: String, + replay: ReplayMode, + mut message: Value, + charge: Option>, + writes: &mpsc::Sender, + ) -> ResultValue { + let pinned = self.pinned.is_some(); + let stop = method == "session/cancel" && original.is_none(); + if !stop { + if pinned { + let attachment_active = self + .pending + .values() + .filter(|p| !p.orphaned && p.attachment == attachment) + .count(); + if attachment_active >= MAX_PENDING_PER_ATTACHMENT { + return Err(Failure::unavailable( + "too many pending ACP requests for attachment", + )); + } + let shared_active = self.pending.values().filter(|p| !p.orphaned).count(); + if shared_active >= MAX_PENDING_SHARED { + return Err(Failure::unavailable("too many pending ACP requests")); + } + if self.pending.len() >= MAX_PENDING_SHARED + MAX_ORPHANED_PENDING { + return Err(Failure::unavailable( + "too many orphaned pending ACP requests", + )); + } + } else if self.pending.len() >= MAX_PENDING_SHARED { + return Err(Failure::unavailable("too many pending ACP requests")); + } + } + if matches!(method.as_str(), "session/new" | "session/resume") { + if self + .pending + .values() + .any(|p| matches!(p.method.as_str(), "session/new" | "session/resume")) + { + return Err(Failure::conflict( + "session startup is pending; reconnect after it settles", + )); + } + message["params"]["cwd"] = Value::String(self.root.to_string_lossy().into_owned()); + message["params"]["additionalDirectories"] = Value::Array(Vec::new()); + if message["params"]["mcpServers"].is_null() { + message["params"]["mcpServers"] = Value::Array(Vec::new()); + } + if self.restore { + message["method"] = Value::String("session/resume".into()); + message["params"]["sessionId"] = Value::String(self.id.clone()); + message["params"]["replayFrom"] = object([("type", "start".into())]); + } else if pinned { + message["method"] = Value::String("session/new".into()); + if let Some(params) = message["params"].as_object_mut() { + params.remove("sessionId"); + params.remove("replayFrom"); + } + } + } + if method == "initialize" { + // Advertise form elicitation capability to the child ONLY in pinned mode. + message["params"]["capabilities"] = if pinned { + object([("elicitation", object([("form", object([]))]))]) + } else { + object([]) + }; + } + let pending = if let Some(original) = original { + self.serial = self + .serial + .checked_add(1) + .ok_or_else(|| Failure::unavailable("request id exhausted"))?; + message["id"] = Value::from(self.serial); + let explicit_delivery = method == "session/prompt" + && matches!( + message["params"]["delivery"].as_str(), + Some("steer" | "queue") + ); + Some(Pending { + attachment, + original, + method, + explicit_delivery, + withdrawal_pending: false, + orphaned: false, + replay, + }) + } else { + None + }; + // Capacity can return after the withdrawal retry is polled. Stop + // must use that first slot without passing accepted withdrawals; + // other messages still let the withdrawals take available slots. + let permit = loop { + let permit = writes.try_reserve().map_err(|_| { + Failure::unavailable("child input queue unavailable; message not accepted") + })?; + if stop { + break permit; + } + let Some(id) = self.next_withdrawal() else { + break permit; + }; + self.send_withdrawal(id, permit); + }; + let mut withdrawals = Vec::new(); + if stop { + // At most one normalized ID per entry in the bounded pending + // map, and no new writer slots or transport charges for them. + withdrawals.extend( + self.pending + .iter() + .filter_map(|(&id, pending)| pending.withdrawal_pending.then_some(id)), + ); + withdrawals.sort_unstable(); + for id in &withdrawals { + if let Some(pending) = self.pending.get_mut(id) { + pending.withdrawal_pending = false; + } + } + } + // No await separates the accepted write from its pending record. + permit.send(ChildWrite { + withdrawals, + message, + _charge: charge, + }); + if let Some(pending) = pending { + self.pending.insert(self.serial, pending); + } + Ok(object([])) + } + + fn command(&mut self, request: Request, writes: &mpsc::Sender) -> ResultValue { + if self.pinned.is_some() { + return self.command_pinned(request, writes); + } + let closing = self.closed || self.pending.values().any(|p| p.method == "session/close"); + if closing && !matches!(request, Request::Poll { .. } | Request::Detach { .. }) && !matches!(&request, Request::Send { message, .. } if message["method"] == "$/cancel_request") { @@ -2053,13 +2447,11 @@ impl Actor { } if let Request::Attach { replace, - replay, - replay_mode, + replay: replay_mode, startup, .. } = request { - let replay_mode = effective_replay_mode(replay, replay_mode); let replay = matches!(replay_mode, ReplayMode::Start); // A live runtime owns its MCP configuration. Do not replace the // controller and then silently ignore a new configuration. @@ -2156,15 +2548,7 @@ impl Actor { )); } let id = crate::session::new_id(); - let mut attachment = Attachment { - id: id.clone(), - touched: Instant::now(), - next: 0, - events: VecDeque::new(), - bytes: 0, - live: false, - closing: false, - }; + let mut attachment = Attachment::new(id.clone()); let started = if let (Some(startup), Some(result)) = (startup, self.session_result.clone()) { let request_id = startup @@ -2257,7 +2641,7 @@ impl Actor { } Request::Send { attachment, - mut message, + message, charge, .. } => { @@ -2266,61 +2650,15 @@ impl Actor { .ok_or_else(|| Failure::bad("ACP method required"))? .to_owned(); let original = message.get("id").cloned(); - if !message.is_object() - || !message["params"].is_object() - || message["jsonrpc"] != "2.0" - { - return Err(Failure::bad("invalid ACP message")); - } - if let Some(session) = message["params"].get("sessionId") - && session != &Value::String(self.id.clone()) - { - return Err(Failure::bad("ACP session does not match gateway session")); - } - if method == "_kit/session/update_mcp" && message["params"]["sessionId"] != self.id - { - return Err(Failure::bad("ACP session does not match gateway session")); - } - if method == "kit/background/cancel" && message["params"]["session_id"] != self.id { - return Err(Failure::bad("ACP session does not match gateway session")); - } - // Only withdraw a prompt from the same attachment. A request - // cancellation never interrupts work for an inserted prompt. + self.validate_session_message(&method, &message)?; if method == "$/cancel_request" { - if original.is_some() { - return Err(Failure::bad("request cancellation must be a notification")); - } - let Some(id) = message["params"].get("requestId").filter(|id| { - id.is_string() || id.as_i64().is_some() || id.as_u64().is_some() - }) else { - return Err(Failure::bad("valid cancellation requestId required")); - }; - // Leave a validated late withdrawal to the admitted close - // instead of starting another child write. - if closing { - return Ok(object([])); - } - let Some((&child_id, pending)) = - self.pending.iter_mut().find(|(_, pending)| { - pending.attachment == attachment - && pending.original == *id - && pending.method == "session/prompt" - }) - else { - return Ok(object([])); - }; - // The normalized child notification needs only the remapped - // ID. Do not retain the transport charge with the retry bit. - match writes.try_reserve() { - Ok(permit) => self.send_withdrawal(child_id, permit), - Err(mpsc::error::TrySendError::Full(())) => { - pending.withdrawal_pending = true; - } - Err(mpsc::error::TrySendError::Closed(())) => { - return Err(Failure::unavailable("child input writer closed")); - } - } - return Ok(object([])); + return self.handle_cancel_request( + &attachment, + original.as_ref(), + &message, + closing, + writes, + ); } if !matches!( method.as_str(), @@ -2378,7 +2716,6 @@ impl Actor { let cached = match method.as_str() { "initialize" => self.initialized.clone(), "session/new" | "session/resume" => self.session_result.clone(), - _ => None, }; if let Some(result) = cached { @@ -2420,98 +2757,9 @@ impl Actor { } return Ok(object([])); } - let stop = method == "session/cancel" && original.is_none(); - if !stop && self.pending.len() >= 128 { - return Err(Failure::unavailable("too many pending ACP requests")); - } - if matches!(method.as_str(), "session/new" | "session/resume") { - if self - .pending - .values() - .any(|p| matches!(p.method.as_str(), "session/new" | "session/resume")) - { - return Err(Failure::conflict( - "session startup is pending; reconnect after it settles", - )); - } - message["params"]["cwd"] = - Value::String(self.root.to_string_lossy().into_owned()); - message["params"]["additionalDirectories"] = Value::Array(Vec::new()); - if message["params"]["mcpServers"].is_null() { - message["params"]["mcpServers"] = Value::Array(Vec::new()); - } - if self.restore { - message["method"] = Value::String("session/resume".into()); - message["params"]["sessionId"] = Value::String(self.id.clone()); - message["params"]["replayFrom"] = object([("type", "start".into())]); - } - } - if method == "initialize" { - message["params"]["capabilities"] = object([]); - } - let pending = if let Some(original) = original { - self.serial = self - .serial - .checked_add(1) - .ok_or_else(|| Failure::unavailable("request id exhausted"))?; - message["id"] = Value::from(self.serial); - let explicit_delivery = method == "session/prompt" - && matches!( - message["params"]["delivery"].as_str(), - Some("steer" | "queue") - ); - Some(Pending { - attachment, - original, - method, - explicit_delivery, - withdrawal_pending: false, - replay, - }) - } else { - None - }; - // Capacity can return after the withdrawal retry is polled. Stop - // must use that first slot without passing accepted withdrawals; - // other messages still let the withdrawals take available slots. - let permit = loop { - let permit = writes.try_reserve().map_err(|_| { - Failure::unavailable("child input queue unavailable; message not accepted") - })?; - if stop { - break permit; - } - let Some(id) = self.next_withdrawal() else { - break permit; - }; - self.send_withdrawal(id, permit); - }; - let mut withdrawals = Vec::new(); - if stop { - // At most one normalized ID per entry in the bounded pending - // map, and no new writer slots or transport charges for them. - withdrawals.extend( - self.pending - .iter() - .filter_map(|(&id, pending)| pending.withdrawal_pending.then_some(id)), - ); - withdrawals.sort_unstable(); - for id in &withdrawals { - if let Some(pending) = self.pending.get_mut(id) { - pending.withdrawal_pending = false; - } - } - } - // No await separates the accepted write from its pending record. - permit.send(ChildWrite { - withdrawals, - message, - _charge: charge, - }); - if let Some(pending) = pending { - self.pending.insert(self.serial, pending); - } - Ok(object([])) + self.enqueue_child_message( + attachment, original, method, replay, message, charge, writes, + ) } _ => Err(Failure::bad("invalid actor operation")), } @@ -2523,13 +2771,11 @@ impl Actor { writes: &mpsc::Sender, ) -> ResultValue { if let Request::Attach { - replay, - replay_mode, + replay: replay_mode, startup, .. } = request { - let replay_mode = effective_replay_mode(replay, replay_mode); let startup_in_flight = self .pinned .as_ref() @@ -2554,15 +2800,7 @@ impl Actor { )); } let id = crate::session::new_id(); - let mut attachment = Attachment { - id: id.clone(), - touched: Instant::now(), - next: 0, - events: VecDeque::new(), - bytes: 0, - live: false, - closing: false, - }; + let attachment = Attachment::new(id.clone()); let started = if let (Some(startup_msg), Some(result)) = (startup.as_ref(), self.session_result.clone()) { @@ -2570,49 +2808,12 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - let messages = self.startup_messages(result, request_id, &replay_mode, &id)?; - let pending_requests = self - .pinned - .as_ref() - .map(PinnedState::pending_request_messages) - .unwrap_or_default(); - let total_count = messages.len() + pending_requests.len(); - let total_bytes: usize = - messages.iter().map(|m| m.to_string().len()).sum::() - + pending_requests - .iter() - .map(|(_, m)| m.to_string().len()) - .sum::(); - if total_count > MAX_QUEUE || total_bytes > MAX_REPLAY { - return Err(Failure::replay( - "session snapshot exceeds the gateway limit", - )); - } - for message in messages { - if !attachment.push(message) { - return Err(Failure::replay( - "session snapshot exceeds the gateway limit", - )); - } - } - let mut registered_relays = Vec::new(); - for (relay_id, req_msg) in pending_requests { - if !attachment.push(req_msg) { - return Err(Failure::replay( - "session snapshot exceeds the gateway limit", - )); - } - registered_relays.push(relay_id); - } - attachment.live = true; + let prepared = + self.prepare_pinned_startup(&id, 0, 0, result, request_id, &replay_mode)?; if let Some(pinned) = &mut self.pinned { - for relay_id in registered_relays { - if let Some(req) = pinned.client_requests.get_mut(&relay_id) { - req.targets.insert(id.clone()); - } - } pinned.attachments.insert(id.clone(), attachment); } + self.apply_pinned_startup(&id, prepared); true } else if let Some(startup_msg) = startup && startup_in_flight @@ -2621,6 +2822,15 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + if self + .pinned + .as_ref() + .is_some_and(|p| p.waiting_startups.len() >= MAX_WAITING_STARTUPS) + { + return Err(Failure::unavailable( + "too many concurrent session startups; retry", + )); + } if let Some(pinned) = &mut self.pinned { pinned.waiting_startups.push(WaitingStartup { attachment: id.clone(), @@ -2654,64 +2864,33 @@ impl Actor { }; if let Request::Detach { .. } = request { - let mut failed_waiters = Vec::new(); - if let Some(pinned) = &mut self.pinned { - pinned.attachments.remove(&token); - pinned.take_overflow(&token); - pinned.waiting_startups.retain(|w| w.attachment != token); - pinned.remove_target_from_requests(&token); - if pinned.startup_driver.as_deref() == Some(token.as_str()) { - pinned.startup_driver = None; - let startup_sent = self - .pending - .values() - .any(|p| matches!(p.method.as_str(), "session/new" | "session/resume")); - if self.session_result.is_none() && !startup_sent { - failed_waiters = std::mem::take(&mut pinned.waiting_startups); - } - } - } - for waiter in failed_waiters { - self.push_pinned_startup_error( - &waiter.attachment, - waiter.request_id, - object([ - ("code", (-32000).into()), - ("message", "session startup interrupted; retry".into()), - ("data", Failure::unavailable("startup interrupted").data()), - ]), - ); - } - // Pinned mode never withdraws held prompts on detach. + self.retire_pinned_attachment(&token, RetireMode::Remove); return Ok(object([])); } - if !self + let Some(overflowed) = self .pinned .as_ref() - .is_some_and(|p| p.attachments.contains_key(&token)) - { - let overflowed = if matches!(request, Request::Poll { .. }) { - self.pinned - .as_mut() - .is_some_and(|p| p.take_overflow(&token)) - } else { - self.pinned - .as_ref() - .is_some_and(|p| p.is_overflowed(&token)) - }; - if overflowed { - return Err(Failure( - StatusCode::CONFLICT, - "attachment queue overflowed; reconnect".into(), - "queue_overflow", - )); - } + .and_then(|p| p.attachments.get(&token)) + .map(|a| a.overflowed) + else { return Err(Failure( StatusCode::CONFLICT, "attachment is not active; reconnect".into(), "attachment_closed", )); + }; + if overflowed { + if matches!(request, Request::Poll { .. }) + && let Some(pinned) = &mut self.pinned + { + pinned.attachments.remove(&token); + } + return Err(Failure( + StatusCode::CONFLICT, + "attachment queue overflowed; reconnect".into(), + "queue_overflow", + )); } match request { @@ -2758,7 +2937,7 @@ impl Actor { } Request::Send { attachment, - mut message, + message, charge, .. } => { @@ -2790,69 +2969,22 @@ impl Actor { .ok_or_else(|| Failure::bad("ACP method required"))? .to_owned(); let original = message.get("id").cloned(); - if !message["params"].is_object() { - return Err(Failure::bad("invalid ACP message")); - } - if let Some(session) = message["params"].get("sessionId") - && session != &Value::String(self.id.clone()) - { - return Err(Failure::bad("ACP session does not match gateway session")); - } - if method == "_kit/session/update_mcp" && message["params"]["sessionId"] != self.id - { - return Err(Failure::bad("ACP session does not match gateway session")); - } - if method == "kit/background/cancel" && message["params"]["session_id"] != self.id { - return Err(Failure::bad("ACP session does not match gateway session")); - } - // Explicit $/cancel_request still withdraws this attachment's own held prompt. + self.validate_session_message(&method, &message)?; if method == "$/cancel_request" { - if original.is_some() { - return Err(Failure::bad("request cancellation must be a notification")); - } - let Some(id) = message["params"].get("requestId").filter(|id| { - id.is_string() || id.as_i64().is_some() || id.as_u64().is_some() - }) else { - return Err(Failure::bad("valid cancellation requestId required")); - }; - let Some((&child_id, pending)) = - self.pending.iter_mut().find(|(_, pending)| { - pending.attachment == attachment - && pending.original == *id - && pending.method == "session/prompt" - }) - else { - return Ok(object([])); - }; - match writes.try_reserve() { - Ok(permit) => self.send_withdrawal(child_id, permit), - Err(mpsc::error::TrySendError::Full(())) => { - pending.withdrawal_pending = true; - } - Err(mpsc::error::TrySendError::Closed(())) => { - return Err(Failure::unavailable("child input writer closed")); - } - } - return Ok(object([])); + return self.handle_cancel_request( + &attachment, + original.as_ref(), + &message, + false, + writes, + ); } // In pinned mode, session/close detaches ONLY this client and never ends the session. if method == "session/close" { let Some(id) = original else { return Err(Failure::bad("session close requires a request id")); }; - if let Some(pinned) = &mut self.pinned { - pinned.remove_target_from_requests(&attachment); - pinned - .waiting_startups - .retain(|w| w.attachment != attachment); - if pinned.startup_driver.as_deref() == Some(attachment.as_str()) { - pinned.startup_driver = None; - } - if let Some(a) = pinned.attachments.get_mut(&attachment) { - a.live = false; - a.closing = true; - } - } + self.retire_pinned_attachment(&attachment, RetireMode::Closing); self.push_pinned_attachment( &attachment, object([ @@ -2884,11 +3016,12 @@ impl Actor { if original.is_none() { return Err(Failure::bad("session startup requires a request id")); } - if self - .pinned - .as_ref() - .and_then(|p| p.attachments.get(&attachment)) - .is_some_and(|a| a.live) + if self.session_result.is_some() + || self + .pinned + .as_ref() + .and_then(|p| p.attachments.get(&attachment)) + .is_some_and(|a| a.live) { return Err(Failure::conflict("attachment already opened its session")); } @@ -2905,73 +3038,14 @@ impl Actor { && self .pending .values() - .any(|p| p.attachment == attachment && p.original == *id) + .any(|p| !p.orphaned && p.attachment == attachment && p.original == *id) { return Err(Failure::conflict("duplicate pending request id")); } - if startup && matches!(replay, ReplayMode::Start) && !self.replay_complete { - return Err(Failure::replay("full live replay is unavailable")); - } - let cached = match method.as_str() { - "initialize" => self.initialized.clone(), - "session/new" | "session/resume" => self.session_result.clone(), - _ => None, - }; - if let Some(result) = cached { - if startup { - if message["params"].get("mcpServers").is_some_and(|servers| { - !servers.is_null() && servers != &Value::Array(Vec::new()) - }) { - return Err(Failure::conflict( - "resident session retains its MCP servers; omit mcpServers or send an empty array; use _kit/session/update_mcp to add or update client servers", - )); - } - let Some(id) = original else { - return Err(Failure::bad("session startup requires a request id")); - }; - let messages = self.startup_messages(result, id, &replay, &attachment)?; - let pending_requests = self - .pinned - .as_ref() - .map(PinnedState::pending_request_messages) - .unwrap_or_default(); - let total_count = messages.len() + pending_requests.len(); - let total_bytes: usize = - messages.iter().map(|m| m.to_string().len()).sum::() - + pending_requests - .iter() - .map(|(_, m)| m.to_string().len()) - .sum::(); - let fits = self - .pinned - .as_ref() - .and_then(|p| p.attachments.get(&attachment)) - .is_some_and(|a| { - a.events.len() + total_count <= MAX_QUEUE - && a.bytes + total_bytes <= MAX_REPLAY - }); - if !fits { - return Err(Failure::replay( - "session snapshot exceeds the gateway limit", - )); - } - for update in messages { - self.push_pinned_attachment(&attachment, update); - } - for (relay_id, req_msg) in pending_requests { - if self.push_pinned_attachment(&attachment, req_msg) - && let Some(pinned) = &mut self.pinned - && let Some(req) = pinned.client_requests.get_mut(&relay_id) - { - req.targets.insert(attachment.clone()); - } - } - if let Some(pinned) = &mut self.pinned - && let Some(a) = pinned.attachments.get_mut(&attachment) - { - a.live = true; - } - } else if let Some(id) = original { + if method == "initialize" + && let Some(result) = self.initialized.clone() + { + if let Some(id) = original { self.push_pinned_attachment( &attachment, object([("jsonrpc", "2.0".into()), ("id", id), ("result", result)]), @@ -2979,110 +3053,9 @@ impl Actor { } return Ok(object([])); } - let stop = method == "session/cancel" && original.is_none(); - if !stop && self.pending.len() >= 128 { - return Err(Failure::unavailable("too many pending ACP requests")); - } - if startup { - if self - .pending - .values() - .any(|p| matches!(p.method.as_str(), "session/new" | "session/resume")) - { - if let Some(id) = original - && let Some(pinned) = &mut self.pinned - { - pinned.waiting_startups.push(WaitingStartup { - attachment, - request_id: id, - replay, - }); - return Ok(object([])); - } - return Err(Failure::conflict( - "session startup is pending; reconnect after it settles", - )); - } - message["params"]["cwd"] = - Value::String(self.root.to_string_lossy().into_owned()); - message["params"]["additionalDirectories"] = Value::Array(Vec::new()); - if message["params"]["mcpServers"].is_null() { - message["params"]["mcpServers"] = Value::Array(Vec::new()); - } - if self.restore { - message["method"] = Value::String("session/resume".into()); - message["params"]["sessionId"] = Value::String(self.id.clone()); - message["params"]["replayFrom"] = object([("type", "start".into())]); - } else { - message["method"] = Value::String("session/new".into()); - if let Some(params) = message["params"].as_object_mut() { - params.remove("sessionId"); - params.remove("replayFrom"); - } - } - } - // Advertise form elicitation capability to the child ONLY in pinned mode. - if method == "initialize" { - message["params"]["capabilities"] = - object([("elicitation", object([("form", object([]))]))]); - } - let pending = if let Some(original) = original { - self.serial = self - .serial - .checked_add(1) - .ok_or_else(|| Failure::unavailable("request id exhausted"))?; - message["id"] = Value::from(self.serial); - let explicit_delivery = method == "session/prompt" - && matches!( - message["params"]["delivery"].as_str(), - Some("steer" | "queue") - ); - Some(Pending { - attachment, - original, - method, - explicit_delivery, - withdrawal_pending: false, - replay, - }) - } else { - None - }; - let permit = loop { - let permit = writes.try_reserve().map_err(|_| { - Failure::unavailable("child input queue unavailable; message not accepted") - })?; - if stop { - break permit; - } - let Some(id) = self.next_withdrawal() else { - break permit; - }; - self.send_withdrawal(id, permit); - }; - let mut withdrawals = Vec::new(); - if stop { - withdrawals.extend( - self.pending - .iter() - .filter_map(|(&id, pending)| pending.withdrawal_pending.then_some(id)), - ); - withdrawals.sort_unstable(); - for id in &withdrawals { - if let Some(pending) = self.pending.get_mut(id) { - pending.withdrawal_pending = false; - } - } - } - permit.send(ChildWrite { - withdrawals, - message, - _charge: charge, - }); - if let Some(pending) = pending { - self.pending.insert(self.serial, pending); - } - Ok(object([])) + self.enqueue_child_message( + attachment, original, method, replay, message, charge, writes, + ) } _ => Err(Failure::bad("invalid actor operation")), } @@ -3101,6 +3074,7 @@ impl Actor { let Some((method, is_target)) = self.pinned.as_ref().and_then(|p| { p.client_requests .get(&relay_id) + .filter(|req| req.resolved_reply.is_none()) .map(|req| (req.method.clone(), req.targets.contains(attachment))) }) else { // Already resolved, cancelled, or expired; ignore late duplicate race. @@ -3110,48 +3084,37 @@ impl Actor { return Ok(object([])); } if let Some(error) = message.get("error").filter(|v| v.is_object()) { - let code = error["code"].as_i64(); - let remaining_others = self - .pinned - .as_ref() - .and_then(|p| p.client_requests.get(&relay_id)) - .map(|req| req.targets.iter().any(|t| t != attachment)) - .unwrap_or(false); - if remaining_others { - if let Some(pinned) = &mut self.pinned - && let Some(req) = pinned.client_requests.get_mut(&relay_id) - { - req.targets.remove(attachment); + let is_unsupported = error["code"].as_i64() == Some(-32601); + let mut should_decline = None; + if let Some(pinned) = &mut self.pinned + && let Some(req) = pinned.client_requests.get_mut(&relay_id) + { + req.targets.remove(attachment); + if !is_unsupported { + // Client-side failure: drop only this target and keep pending + // for remaining targets or a late joiner until timeout. + req.had_client_error = true; + } else if req.targets.is_empty() && !req.had_client_error { + let reply = object([ + ("jsonrpc", "2.0".into()), + ("id", req.child_id.clone()), + ( + "error", + object([ + ("code", (-32601).into()), + ("message", "gateway has no client-side services".into()), + ]), + ), + ]); + req.resolved_reply = Some((reply, charge)); + should_decline = Some(relay_id.clone()); } - return Ok(object([])); } - let permit = writes.try_reserve().map_err(|_| { - Failure::unavailable("child input queue unavailable; response not accepted") - })?; - let Some(req) = self - .pinned - .as_mut() - .and_then(|p| p.client_requests.remove(&relay_id)) - else { - return Ok(object([])); - }; - let child_error = if code == Some(-32601) { - object([ - ("code", (-32601).into()), - ("message", "gateway has no client-side services".into()), - ]) - } else { - error.clone() - }; - permit.send(ChildWrite { - withdrawals: Vec::new(), - message: object([ - ("jsonrpc", "2.0".into()), - ("id", req.child_id), - ("error", child_error), - ]), - _charge: charge, - }); + if let Some(id) = should_decline + && let Ok(permit) = writes.try_reserve() + { + self.flush_client_request_reply(&id, permit); + } return Ok(object([])); } let Some(result) = message.get("result") else { @@ -3160,30 +3123,27 @@ impl Actor { if !is_valid_client_result(&method, result) { return Err(Failure::bad("invalid response for relayed client request")); } - let permit = writes.try_reserve().map_err(|_| { - Failure::unavailable("child input queue unavailable; response not accepted") - })?; - let Some(req) = self - .pinned - .as_mut() - .and_then(|p| p.client_requests.remove(&relay_id)) - else { - return Ok(object([])); - }; - permit.send(ChildWrite { - withdrawals: Vec::new(), - message: object([ + let mut other_targets = Vec::new(); + if let Some(pinned) = &mut self.pinned + && let Some(req) = pinned.client_requests.get_mut(&relay_id) + { + let reply = object([ ("jsonrpc", "2.0".into()), - ("id", req.child_id), + ("id", req.child_id.clone()), ("result", result.clone()), - ]), - _charge: charge, - }); + ]); + req.resolved_reply = Some((reply, charge)); + other_targets = std::mem::take(&mut req.targets) + .into_iter() + .filter(|target| target != attachment) + .collect(); + } + if let Ok(permit) = writes.try_reserve() { + self.flush_client_request_reply(&relay_id, permit); + } let cancel = cancel_request_message(Value::String(relay_id)); - for target in req.targets { - if target != attachment { - self.push_pinned_attachment(&target, cancel.clone()); - } + for target in other_targets { + self.push_pinned_attachment(&target, cancel.clone()); } Ok(object([])) } diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 66332a09..b5d6d4f7 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -248,6 +248,15 @@ impl Connection { { return Err(Failure::bad("unsupported session list cursor")); } + if let Some(pinned) = &self.gateway.pinned + && let Some(requested) = message["params"].get("sessionId").and_then(Value::as_str) + && requested != pinned.session_id + { + return Err(Failure::bad(format!( + "gateway is pinned to session {}; other session ids are not allowed", + pinned.session_id + ))); + } let result = self.operation(Request::List).await?; let rows = result["sessions"] .as_array() @@ -255,7 +264,9 @@ impl Connection { let cwd = message["params"]["cwd"].as_str(); let rows: Vec<_> = rows .iter() - .filter(|row| cwd.is_none_or(|cwd| row["root"] == cwd)) + .filter(|row| { + self.gateway.pinned.is_some() || cwd.is_none_or(|cwd| row["root"] == cwd) + }) .map(|row| { object([ ("sessionId", row["session"].clone()), @@ -291,6 +302,16 @@ impl Connection { } Some(requested) } else { + if let Some(pinned) = pinned + && let Some(requested) = + message["params"].get("sessionId").and_then(Value::as_str) + && requested != pinned.session_id + { + return Err(Failure::bad(format!( + "gateway is pinned to session {}; other session ids are not allowed", + pinned.session_id + ))); + } pinned.map(|pinned| pinned.session_id.clone()) }; if id.as_ref().is_some_and(|id| self.controls.contains_key(id)) { @@ -374,8 +395,7 @@ impl Connection { request: Request::Attach { session: session.clone(), replace: resume && pinned.is_none(), - replay: matches!(replay_mode, ReplayMode::Start), - replay_mode: Some(replay_mode), + replay: replay_mode, startup: Some(message.clone()), }, reply, @@ -616,13 +636,7 @@ impl Connection { .as_ref() .and_then(|pinned| self.controls.get_mut(&pinned.session_id)) { - match control.send(message, Arc::clone(&charged_frame)).await { - Ok(_) | Err(Failure(_, _, "queue_overflow" | "attachment_closed")) => {} - Err(Failure(_, message, "unavailable")) => { - return Err(channel.tx.fail(&message)); - } - Err(_) => {} - } + let _ = control.send(message, Arc::clone(&charged_frame)).await; } self.flush(&channel).await?; drop(charged_frame); diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index e51819e5..9276c571 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -164,7 +164,8 @@ impl SseReader { } async fn next_matching(&mut self, mut predicate: impl FnMut(&Value) -> bool) -> Value { - tokio::time::timeout(Duration::from_secs(5), async { + let mut seen = Vec::new(); + match tokio::time::timeout(Duration::from_secs(15), async { loop { let event = self .next_event() @@ -173,10 +174,14 @@ impl SseReader { if predicate(&event) { return event; } + seen.push(event); } }) .await - .unwrap() + { + Ok(ev) => ev, + Err(_) => panic!("timed out waiting for matching SSE event; saw: {seen:?}"), + } } } @@ -707,8 +712,7 @@ async fn pinned_overflow_drops_only_one_attachment_without_withdrawing_or_affect .command( Request::Attach { session: "pinned-overflow".into(), - replay: false, - replay_mode: Some(ReplayMode::None), + replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-overflow"}})), }, @@ -722,8 +726,7 @@ async fn pinned_overflow_drops_only_one_attachment_without_withdrawing_or_affect .command( Request::Attach { session: "pinned-overflow".into(), - replay: false, - replay_mode: Some(ReplayMode::None), + replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-overflow"}})), }, @@ -941,8 +944,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .command( Request::Attach { session: "pinned-replay".into(), - replay: false, - replay_mode: Some(ReplayMode::CurrentTurn), + replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-replay","replayFrom":{"type":"_kit_current_turn"}}})), }, @@ -983,10 +985,9 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .command( Request::Attach { session: "pinned-replay".into(), - replay: false, - replay_mode: Some(ReplayMode::Message { + replay: ReplayMode::Message { message_id: "u-1".into(), - }), + }, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-replay","replayFrom":{"type":"_kit_message","sessionId":"pinned-replay","messageId":"u-1"}}})), }, @@ -1013,10 +1014,9 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .command( Request::Attach { session: "pinned-replay".into(), - replay: false, - replay_mode: Some(ReplayMode::Message { + replay: ReplayMode::Message { message_id: "missing-msg".into(), - }), + }, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), }, @@ -1052,8 +1052,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .command( Request::Attach { session: "pinned-replay".into(), - replay: true, - replay_mode: Some(ReplayMode::Start), + replay: ReplayMode::Start, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), }, @@ -1067,8 +1066,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .command( Request::Attach { session: "pinned-replay".into(), - replay: false, - replay_mode: Some(ReplayMode::CurrentTurn), + replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":5,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), }, @@ -1230,8 +1228,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( .command( Request::Attach { session: "pinned-req".into(), - replay: false, - replay_mode: Some(ReplayMode::None), + replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":req_id,"method":"session/resume","params":{"sessionId":"pinned-req"}})), }, @@ -1430,12 +1427,12 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( .next() .unwrap() .clone(); - assert!(actor.next_expired_client_request().is_none()); + assert!(actor.next_ready_client_reply().is_none()); tokio::time::advance(timeout).await; - let expired_id = actor.next_expired_client_request().unwrap(); + let expired_id = actor.next_ready_client_reply().unwrap(); assert_eq!(expired_id, relay_timeout); let permit = writes.try_reserve().unwrap(); - actor.expire_client_request(&expired_id, permit); + actor.flush_client_request_reply(&expired_id, permit); let timeout_reply = child_rx.try_recv().unwrap().message; assert_eq!(timeout_reply["id"], "ask-timeout"); @@ -1571,8 +1568,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro .command( Request::Attach { session: "pinned-edge".into(), - replay: false, - replay_mode: Some(ReplayMode::None), + replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), }, @@ -1618,8 +1614,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro .command( Request::Attach { session: "pinned-edge".into(), - replay: false, - replay_mode: Some(ReplayMode::None), + replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), }, @@ -1661,8 +1656,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro .command( Request::Attach { session: "pinned-edge".into(), - replay: false, - replay_mode: Some(ReplayMode::None), + replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), }, @@ -1707,3 +1701,1597 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro assert_eq!(reply["result"]["action"], "decline"); assert!(reply.get("error").is_none()); } + +#[tokio::test] +async fn pinned_session_new_without_replay_from_defaults_to_none_and_survives_eviction() { + // Default mode still maps absent replayFrom on session/new to Start; pinned mode maps it to None. + assert_eq!( + parse_replay_mode(None, "s", false, true).unwrap(), + ReplayMode::Start + ); + assert_eq!( + parse_replay_mode(None, "s", true, true).unwrap(), + ReplayMode::None + ); + assert_eq!( + parse_replay_mode(None, "s", true, false).unwrap(), + ReplayMode::None + ); + assert_eq!( + parse_replay_mode(Some(&Value::Null), "s", true, true).unwrap(), + ReplayMode::None + ); + assert_eq!( + parse_replay_mode(Some(&json!({"type": "start"})), "s", true, true).unwrap(), + ReplayMode::Start + ); + + // 1. Cold restore with no cursor succeeds even when child replays more than MAX_REPLAY bytes. + let mut restore_actor = Actor::new( + "pinned-restore".into(), + PathBuf::from("/approved"), + true, + Some(Duration::from_secs(60)), + ); + let (writes, mut child_rx) = mpsc::channel(8); + let driver = restore_actor + .command( + Request::Attach { + session: "pinned-restore".into(), + replay: ReplayMode::None, + replace: false, + startup: None, + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + restore_actor + .command( + Request::Send { + session: "pinned-restore".into(), + attachment: driver.clone(), + message: json!({"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let forwarded = child_rx.try_recv().unwrap().message; + assert_eq!(forwarded["method"], "session/resume"); + let child_req_id = forwarded["id"].clone(); + // Child replays > MAX_REPLAY bytes of historical updates during cold restore. + let big = "h".repeat(MAX_HTTP_FRAME / 2); + for i in 0..20 { + restore_actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-restore", "update": {"sessionUpdate": "notice", "message": format!("{i}:{big}")}} + })); + } + assert!(!restore_actor.replay_complete); + restore_actor.output(json!({ + "jsonrpc": "2.0", + "id": child_req_id, + "result": {"sessionId": "pinned-restore", "configOptions": []} + })); + let events = restore_actor + .command( + Request::Poll { + session: "pinned-restore".into(), + attachment: driver, + cursor: 0, + }, + &writes, + ) + .unwrap(); + let last = events["events"].as_array().unwrap().last().unwrap()["message"].clone(); + assert_eq!(last["id"], 1); + assert!(last.get("error").is_none(), "{last}"); + assert_eq!( + last["result"]["_meta"]["kit/gateway"]["historyAvailable"], + false + ); + + // 2. Over HTTP, after journal eviction, session/new without replayFrom succeeds with no history, + // while explicit replayFrom: {"type":"start"} fails with replay_unavailable. + let harness = PinnedHarness::new("pinned-evict", Duration::from_secs(60)).await; + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-evict','configOptions':[]}}) + elif m == 'session/prompt': + pad = 'x' * (400 * 1024) + for i in range(25): + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-evict','update':{'sessionUpdate':'notice','message':f'{i}:{pad}'}}}) + emit({'jsonrpc':'2.0','id':req['id'],'result':{'stopReason':'end_turn'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-evict", source, &[]).await; + + let mut c1 = harness.connect("c1").await; + let mut s1 = c1.open_session_stream("pinned-evict").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/new","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let r1 = c1.conn_stream.next_matching(|e| e["id"] == 1).await; + assert_eq!(r1["result"]["sessionId"], "pinned-evict"); + + // Emit > 8 MiB so the journal evicts early events. + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":2,"method":"session/prompt","params":{"sessionId":"pinned-evict","prompt":[{"type":"text","text":"fill"}]}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 2).await; + + // A fresh client sending session/new with NO replayFrom succeeds with historyAvailable=false. + let mut c2 = harness.connect("c2").await; + let s2 = c2.open_session_stream("pinned-evict").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":3,"method":"session/new","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let r2 = c2.conn_stream.next_matching(|e| e["id"] == 3).await; + assert!(r2.get("error").is_none(), "{r2}"); + assert_eq!( + r2["result"]["_meta"]["kit/gateway"]["historyAvailable"], + false + ); + + // Explicit replayFrom: {"type":"start"} fails with replay_unavailable. + let mut c3 = harness.connect("c3").await; + assert_eq!( + c3.post(json!({"jsonrpc":"2.0","id":4,"method":"session/new","params":{"replayFrom":{"type":"start"}}})) + .await, + StatusCode::ACCEPTED + ); + let r3 = c3.conn_stream.next_matching(|e| e["id"] == 4).await; + assert_eq!(r3["error"]["data"]["reason"], "replay_unavailable"); + drop(s1); + drop(s2); + let _ = c1.delete().await; + let _ = c2.delete().await; + let _ = c3.delete().await; +} + +#[test] +fn pinned_orphaned_held_prompts_do_not_exhaust_shared_cap_and_per_attachment_cap_applies() { + let mut actor = pinned_actor("pinned-caps", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-caps", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(512); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-caps".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-caps"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + + // 1. Per-attachment pending cap (32) blocks one greedy client without blocking another attachment. + let greedy = attach(&mut actor, 1); + let other = attach(&mut actor, 2); + for i in 0..MAX_PENDING_PER_ATTACHMENT { + actor + .command( + Request::Send { + session: "pinned-caps".into(), + attachment: greedy.clone(), + message: json!({"jsonrpc":"2.0","id":format!("g-{i}"),"method":"session/prompt","params":{"sessionId":"pinned-caps","delivery":"steer","prompt":[]}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let _ = child_rx.try_recv().unwrap(); + } + let err = actor + .command( + Request::Send { + session: "pinned-caps".into(), + attachment: greedy.clone(), + message: json!({"jsonrpc":"2.0","id":"g-over","method":"session/prompt","params":{"sessionId":"pinned-caps","delivery":"steer","prompt":[]}}), + charge: None, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(err.2, "unavailable"); + + // Another attachment is NOT blocked by greedy's per-attachment cap. + actor + .command( + Request::Send { + session: "pinned-caps".into(), + attachment: other.clone(), + message: json!({"jsonrpc":"2.0","id":"o-1","method":"kit/session/status","params":{"sessionId":"pinned-caps"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let other_child_id = child_rx.try_recv().unwrap().message["id"].clone(); + actor.output(json!({"jsonrpc":"2.0","id":other_child_id,"result":{"settled":false}})); + + // Detach greedy -> its 32 held steers become orphaned (no withdrawal sent). + actor + .command( + Request::Detach { + session: "pinned-caps".into(), + attachment: greedy, + }, + &writes, + ) + .unwrap(); + assert!(actor.next_withdrawal().is_none()); + + // 2. Create > MAX_PENDING_SHARED (128) orphaned held prompts across detached deliverers. + for batch in 0..6 { + let deliverer = attach(&mut actor, 100 + batch); + for i in 0..25 { + actor + .command( + Request::Send { + session: "pinned-caps".into(), + attachment: deliverer.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": format!("d-{batch}-{i}"), + "method": "session/prompt", + "params": {"sessionId": "pinned-caps", "delivery": "steer", "idempotencyKey": format!("k-{batch}-{i}"), "prompt": []} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let _ = child_rx.try_recv().unwrap(); + } + actor + .command( + Request::Detach { + session: "pinned-caps".into(), + attachment: deliverer, + }, + &writes, + ) + .unwrap(); + } + let orphaned_count = actor.pending.values().filter(|p| p.orphaned).count(); + assert_eq!(orphaned_count, 32 + 150); + assert!(orphaned_count > MAX_PENDING_SHARED); + + // Live attachment `other` can STILL submit requests even with 182 orphans in pending! + actor + .command( + Request::Send { + session: "pinned-caps".into(), + attachment: other.clone(), + message: json!({"jsonrpc":"2.0","id":"still-works","method":"kit/session/status","params":{"sessionId":"pinned-caps"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let live_child_id = child_rx.try_recv().unwrap().message["id"].clone(); + actor.output(json!({"jsonrpc":"2.0","id":live_child_id,"result":{"settled":true}})); + assert!( + actor.pinned.as_ref().unwrap().attachments[&other] + .events + .iter() + .any(|(_, m)| m["id"] == "still-works") + ); + + // 3. Separate total cap (MAX_PENDING_SHARED + MAX_ORPHANED_PENDING) still bounds memory. + while actor.pending.len() < MAX_PENDING_SHARED + MAX_ORPHANED_PENDING { + let pending_count = actor.pending.len(); + let d = attach(&mut actor, 500 + pending_count as u64); + let remaining = (MAX_PENDING_SHARED + MAX_ORPHANED_PENDING - pending_count) + .min(MAX_PENDING_PER_ATTACHMENT); + for i in 0..remaining { + actor + .command( + Request::Send { + session: "pinned-caps".into(), + attachment: d.clone(), + message: json!({"jsonrpc":"2.0","id":format!("cap-{i}"),"method":"session/prompt","params":{"sessionId":"pinned-caps","delivery":"steer","prompt":[]}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let _ = child_rx.try_recv().unwrap(); + } + actor + .command( + Request::Detach { + session: "pinned-caps".into(), + attachment: d, + }, + &writes, + ) + .unwrap(); + } + let total_cap_err = actor + .command( + Request::Send { + session: "pinned-caps".into(), + attachment: other, + message: json!({"jsonrpc":"2.0","id":"past-total-cap","method":"kit/session/status","params":{"sessionId":"pinned-caps"}}), + charge: None, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(total_cap_err.2, "unavailable"); +} + +#[test] +fn pinned_current_turn_replay_truncates_gracefully_when_turn_start_evicted() { + let mut actor = pinned_actor("pinned-long-turn", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-long-turn", "configOptions": []})); + let (writes, _rx) = mpsc::channel(4); + + // Completed Turn 1. + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-long-turn","update":{"sessionUpdate":"state_update","state":"running"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-long-turn","update":{"sessionUpdate":"user_message","messageId":"u-1","content":[]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-long-turn","update":{"sessionUpdate":"state_update","state":"idle"}}})); + + // Non-truncated current turn does NOT set replayTruncated. + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-long-turn","update":{"sessionUpdate":"state_update","state":"running"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-long-turn","update":{"sessionUpdate":"user_message","messageId":"u-2","content":[]}}})); + let a_ok = actor + .command( + Request::Attach { + session: "pinned-long-turn".into(), + replay: ReplayMode::CurrentTurn, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-long-turn"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let ok_res = actor.pinned.as_ref().unwrap().attachments[&a_ok] + .events + .back() + .unwrap() + .1 + .clone(); + assert!( + ok_res["result"]["_meta"]["kit/gateway"] + .get("replayTruncated") + .is_none() + ); + + // Push Turn 2's own start out of the journal with large chunks during the SAME turn! + let big = "t".repeat(MAX_HTTP_FRAME / 2); + for i in 0..22 { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-long-turn", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": format!("chunk-{i}:{big}")}}} + })); + } + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-long-turn", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "tail-chunk"}}} + })); + assert!(actor.current_turn_start.unwrap() < actor.journal_base_seq); + + // `_kit_current_turn` MUST succeed, replay the retained suffix, and set replayTruncated = true! + let a_trunc = actor + .command( + Request::Attach { + session: "pinned-long-turn".into(), + replay: ReplayMode::CurrentTurn, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-long-turn"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let events: Vec = actor.pinned.as_ref().unwrap().attachments[&a_trunc] + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + events + .iter() + .any(|e| e["params"]["update"]["content"]["text"] == "tail-chunk") + ); + let result_msg = events.last().unwrap(); + assert_eq!(result_msg["id"], 2); + assert_eq!( + result_msg["result"]["_meta"]["kit/gateway"]["historyAvailable"], + true + ); + assert_eq!( + result_msg["result"]["_meta"]["kit/gateway"]["replayTruncated"], + true + ); +} + +#[tokio::test(start_paused = true)] +async fn pinned_reaper_cleans_up_abandoned_attachments_and_leaked_startup_driver() { + // 1. Unit check of MAX_WAITING_STARTUPS bound. + let mut bounded_actor = pinned_actor("pinned-wait-bound", Duration::from_secs(60)); + let (writes, _rx) = mpsc::channel(4); + let _driver = bounded_actor + .command( + Request::Attach { + session: "pinned-wait-bound".into(), + replay: ReplayMode::None, + replace: false, + startup: None, + }, + &writes, + ) + .unwrap(); + for i in 0..MAX_WAITING_STARTUPS { + bounded_actor + .command( + Request::Attach { + session: "pinned-wait-bound".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":i,"method":"session/resume","params":{"sessionId":"pinned-wait-bound"}})), + }, + &writes, + ) + .unwrap(); + } + let overflow_waiter = bounded_actor + .command( + Request::Attach { + session: "pinned-wait-bound".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":999,"method":"session/resume","params":{"sessionId":"pinned-wait-bound"}})), + }, + &writes, + ) + .unwrap_err(); + assert_eq!(overflow_waiter.2, "unavailable"); + + // 2. Real Actor::run timer reaping of leaked startup_driver + abandoned attachment. + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-reap','configOptions':[]}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", source]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let actor = pinned_actor("pinned-reap", Duration::from_secs(60)); + let (sender, receiver) = mpsc::channel(32); + let actor_task = tokio::spawn(async move { + actor.run(child, receiver).await; + }); + + let send_req = |request: Request| { + let sender = sender.clone(); + async move { + let (tx, rx) = oneshot::channel(); + sender.send(Envelope { request, reply: tx }).await.unwrap(); + rx.await.unwrap() + } + }; + + // Driver claims cold startup but abandons it without sending session/new! + let leaked_driver = send_req(Request::Attach { + session: "pinned-reap".into(), + replay: ReplayMode::None, + replace: false, + startup: None, + }) + .await + .unwrap(); + assert_eq!(leaked_driver["started"], false); + let driver_id = leaked_driver["attachment"].as_str().unwrap().to_owned(); + + // Joiner parks in waiting_startups while leaked_driver holds startup_driver. + let waiter = send_req(Request::Attach { + session: "pinned-reap".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":77,"method":"session/resume","params":{"sessionId":"pinned-reap"}})), + }) + .await + .unwrap(); + assert_eq!(waiter["started"], true); + let waiter_id = waiter["attachment"].as_str().unwrap().to_owned(); + + // Keep waiter alive by polling halfway through LEASE while driver stays silent. + tokio::time::advance(LEASE / 2).await; + tokio::task::yield_now().await; + let mid_poll = send_req(Request::Poll { + session: "pinned-reap".into(), + attachment: waiter_id.clone(), + cursor: 0, + }) + .await + .unwrap(); + assert!(mid_poll["events"].as_array().unwrap().is_empty()); + + // Advance past driver's LEASE -> Actor::run reaps leaked_driver and unblocks waiter with error! + tokio::time::advance(LEASE / 2 + Duration::from_secs(1)).await; + tokio::task::yield_now().await; + + let driver_err = send_req(Request::Poll { + session: "pinned-reap".into(), + attachment: driver_id, + cursor: 0, + }) + .await + .unwrap_err(); + assert_eq!(driver_err.2, "attachment_closed"); + + let waiter_poll = send_req(Request::Poll { + session: "pinned-reap".into(), + attachment: waiter_id.clone(), + cursor: 0, + }) + .await + .unwrap(); + let waiter_events = waiter_poll["events"].as_array().unwrap(); + assert_eq!(waiter_events.len(), 1); + assert_eq!(waiter_events[0]["message"]["id"], 77); + assert!(waiter_events[0]["message"].get("error").is_some()); + + // Session is NOT bricked: a fresh client can now become startup_driver and complete startup! + let fresh = send_req(Request::Attach { + session: "pinned-reap".into(), + replay: ReplayMode::None, + replace: false, + startup: None, + }) + .await + .unwrap(); + assert_eq!(fresh["started"], false); + let fresh_id = fresh["attachment"].as_str().unwrap().to_owned(); + // Leave waiter_id idle past LEASE -> it is also reaped! + tokio::time::advance(LEASE + Duration::from_secs(1)).await; + tokio::task::yield_now().await; + let reaped_waiter = send_req(Request::Poll { + session: "pinned-reap".into(), + attachment: waiter_id, + cursor: 0, + }) + .await + .unwrap_err(); + assert_eq!(reaped_waiter.2, "attachment_closed"); + let reaped_fresh = send_req(Request::Poll { + session: "pinned-reap".into(), + attachment: fresh_id, + cursor: 0, + }) + .await + .unwrap_err(); + assert_eq!(reaped_fresh.2, "attachment_closed"); + + let (tx, _rx) = oneshot::channel(); + let _ = sender + .send(Envelope { + request: Request::Shutdown, + reply: tx, + }) + .await; + actor_task.abort(); +} + +#[tokio::test(start_paused = true)] +async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_joiner() { + let timeout = Duration::from_secs(10); + let mut actor = pinned_actor("pinned-err-relay", timeout); + actor.session_result = Some(json!({"sessionId": "pinned-err-relay", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-err-relay".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-err-relay"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + let c1 = attach(&mut actor, 1); + let c2 = attach(&mut actor, 2); + + // Case 1: c1 fails with -32603 (internal client error), c2 declines with -32601. + // Because c1 did NOT decline with -32601, child must NOT get -32601; late joiner c3 answers! + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-err-1", + "method": "elicitation/create", + "params": {"sessionId": "pinned-err-relay", "mode": "form", "message": "pick"} + })) + .is_none() + ); + let relay1 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor + .command( + Request::Send { + session: "pinned-err-relay".into(), + attachment: c1.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"error":{"code":-32603,"message":"ui crashed"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + actor + .command( + Request::Send { + session: "pinned-err-relay".into(), + attachment: c2.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"error":{"code":-32601,"message":"Method not found"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert!( + child_rx.try_recv().is_err(), + "must NOT send -32601 after non-32601 error" + ); + assert!( + actor + .pinned + .as_ref() + .unwrap() + .client_requests + .contains_key(&relay1) + ); + + // Late joiner c3 receives the still-pending request and answers validly! + let c3 = attach(&mut actor, 3); + assert_eq!( + actor.pinned.as_ref().unwrap().attachments[&c3] + .events + .back() + .unwrap() + .1["id"], + relay1 + ); + actor + .command( + Request::Send { + session: "pinned-err-relay".into(), + attachment: c3.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"result":{"action":"accept","content":{"a":"ok"}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let reply = child_rx.try_recv().unwrap().message; + assert_eq!(reply["id"], "ask-err-1"); + assert_eq!(reply["result"]["content"]["a"], "ok"); + + // Case 2: Single client returns -32000 -> stays pending until timeout -> expires with -32603. + for att in [&c1, &c2] { + actor + .command( + Request::Detach { + session: "pinned-err-relay".into(), + attachment: att.clone(), + }, + &writes, + ) + .unwrap(); + } + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-err-timeout", + "method": "elicitation/create", + "params": {"sessionId": "pinned-err-relay", "mode": "form", "message": "wait"} + })) + .is_none() + ); + let relay2 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor + .command( + Request::Send { + session: "pinned-err-relay".into(), + attachment: c3, + message: json!({"jsonrpc":"2.0","id":relay2,"error":{"code":-32000,"message":"temporary error"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert!(child_rx.try_recv().is_err()); + assert!(actor.next_ready_client_reply().is_none()); + tokio::time::advance(timeout).await; + let ready = actor.next_ready_client_reply().unwrap(); + assert_eq!(ready, relay2); + actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); + let expired = child_rx.try_recv().unwrap().message; + assert_eq!(expired["id"], "ask-err-timeout"); + assert_eq!(expired["error"]["code"], -32603); + assert_eq!(expired["error"]["message"], "Incoming transport closed"); +} + +#[test] +fn pinned_relayed_response_buffers_under_child_backpressure_and_flushes() { + let mut actor = pinned_actor("pinned-bp", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-bp", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(1); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-bp".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-bp"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + let c1 = attach(&mut actor, 1); + let c2 = attach(&mut actor, 2); + + // Fill the single child-write slot so try_reserve() fails! + writes + .try_send(ChildWrite { + withdrawals: Vec::new(), + message: json!({"dummy": true}), + _charge: None, + }) + .unwrap(); + + // 1. Winning answer under backpressure: returns Ok, cancels c2 immediately, buffers reply. + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-bp-win", + "method": "elicitation/create", + "params": {"sessionId": "pinned-bp", "mode": "form", "message": "bp"} + })) + .is_none() + ); + let relay1 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor + .command( + Request::Send { + session: "pinned-bp".into(), + attachment: c1.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"result":{"action":"accept","content":{"k":"v"}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + // Loser c2 received $/cancel_request right away. + assert_eq!( + actor.pinned.as_ref().unwrap().attachments[&c2] + .events + .back() + .unwrap() + .1["method"], + "$/cancel_request" + ); + // Reply is ready to flush once writer slot opens. + let ready = actor.next_ready_client_reply().unwrap(); + assert_eq!(ready, relay1); + let _dummy = child_rx.try_recv().unwrap(); + actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); + let flushed = child_rx.try_recv().unwrap().message; + assert_eq!(flushed["id"], "ask-bp-win"); + assert_eq!(flushed["result"]["content"]["k"], "v"); + assert!(actor.pinned.as_ref().unwrap().client_requests.is_empty()); + + // 2. All-32601 decline also buffers under backpressure and flushes cleanly. + writes + .try_send(ChildWrite { + withdrawals: Vec::new(), + message: json!({"dummy": true}), + _charge: None, + }) + .unwrap(); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-bp-32601", + "method": "elicitation/create", + "params": {"sessionId": "pinned-bp", "mode": "form", "message": "bp2"} + })) + .is_none() + ); + let relay2 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + for att in [&c1, &c2] { + actor + .command( + Request::Send { + session: "pinned-bp".into(), + attachment: att.clone(), + message: json!({"jsonrpc":"2.0","id":relay2,"error":{"code":-32601,"message":"Method not found"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + } + let ready2 = actor.next_ready_client_reply().unwrap(); + assert_eq!(ready2, relay2); + let _dummy = child_rx.try_recv().unwrap(); + actor.flush_client_request_reply(&ready2, writes.try_reserve().unwrap()); + let flushed2 = child_rx.try_recv().unwrap().message; + assert_eq!(flushed2["id"], "ask-bp-32601"); + assert_eq!(flushed2["error"]["code"], -32601); +} + +#[tokio::test] +async fn pinned_child_crash_cancels_pending_relayed_requests_and_notifies_live_attachments() { + let harness = PinnedHarness::new("pinned-crash", Duration::from_secs(60)).await; + let source = r#" +import sys, json, os +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req.get('method') + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-crash','configOptions':[]}}) + elif m == 'session/prompt': + emit({ + 'jsonrpc':'2.0', + 'id':'ask-before-crash', + 'method':'elicitation/create', + 'params':{'sessionId':'pinned-crash','mode':'form','message':'crash incoming'} + }) + elif m == 'kit/session/status': + os._exit(1) +"#; + harness.child_source("pinned-crash", source, &[]).await; + + let mut c1 = harness.connect("c1").await; + let mut s1 = c1.open_session_stream("pinned-crash").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-crash"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + let mut c2 = harness.connect("c2").await; + let mut s2 = c2.open_session_stream("pinned-crash").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-crash"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s2.next_matching(|e| e["id"] == 2).await; + + // Trigger pending relayed elicitation/create. + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":"p1","method":"session/prompt","params":{"sessionId":"pinned-crash","prompt":[{"type":"text","text":"ask"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q1 = s1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let q2 = s2 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay_id = q1["id"].as_str().unwrap().to_owned(); + assert_eq!(q2["id"], relay_id); + + // Crash the child! + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":"crash-trigger","method":"kit/session/status","params":{"sessionId":"pinned-crash"}})) + .await, + StatusCode::ACCEPTED + ); + + // BOTH live attachments receive $/cancel_request for the pending relayed request! + let cancel1 = c1 + .conn_stream + .next_matching(|e| e["method"] == "$/cancel_request") + .await; + let cancel2 = c2 + .conn_stream + .next_matching(|e| e["method"] == "$/cancel_request") + .await; + assert_eq!(cancel1["params"]["requestId"], relay_id); + assert_eq!(cancel2["params"]["requestId"], relay_id); + + // Both live attachments also observe the child-exit controller notice on their session streams. + let notice1 = s1 + .next_matching(|e| e["params"]["update"]["sessionUpdate"] == "_gateway_controller") + .await; + let notice2 = s2 + .next_matching(|e| e["params"]["update"]["sessionUpdate"] == "_gateway_controller") + .await; + assert_eq!( + notice1["params"]["update"]["_meta"]["kit/gateway"]["reason"], + "unavailable" + ); + assert_eq!( + notice2["params"]["update"]["_meta"]["kit/gateway"]["reason"], + "unavailable" + ); + + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[test] +fn pinned_reply_dropped_when_sender_detached_never_leaks_to_other_attachment() { + let mut actor = pinned_actor("pinned-drop-reply", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-drop-reply", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-drop-reply".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-drop-reply"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + let c1 = attach(&mut actor, 1); + let c2 = attach(&mut actor, 2); + + // c1 submits a request, then detaches before child replies. + actor + .command( + Request::Send { + session: "pinned-drop-reply".into(), + attachment: c1.clone(), + message: json!({"jsonrpc":"2.0","id":"from-c1","method":"kit/session/status","params":{"sessionId":"pinned-drop-reply"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let child_id = child_rx.try_recv().unwrap().message["id"].clone(); + actor + .command( + Request::Detach { + session: "pinned-drop-reply".into(), + attachment: c1, + }, + &writes, + ) + .unwrap(); + + // Child replies to c1's request -> dropped silently, never delivered to c2! + let c2_before = actor.pinned.as_ref().unwrap().attachments[&c2].events.len(); + actor.output(json!({"jsonrpc":"2.0","id":child_id,"result":{"settled":true}})); + assert_eq!( + actor.pinned.as_ref().unwrap().attachments[&c2].events.len(), + c2_before + ); + assert!(actor.pending.is_empty()); +} + +#[tokio::test] +async fn pinned_real_actor_http_overflow_isolates_slow_client_while_fast_client_continues() { + let harness = PinnedHarness::new("pinned-real-ovf", Duration::from_secs(60)).await; + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-real-ovf','configOptions':[]}}) + elif m == 'session/prompt': + pad = 'z' * (32 * 1024) + for j in range(40): + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-real-ovf','update':{'sessionUpdate':'notice','message':f'{req["id"]}:{j}:{pad}'}}}) + emit({'jsonrpc':'2.0','id':req['id'],'result':{'stopReason':'end_turn'}}) + elif m == 'kit/session/status': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-real-ovf", source, &[]).await; + + // Client 1 (slow): attaches and then does NOT read its session stream during the flood! + let c1 = harness.connect("slow").await; + let mut s1 = c1.open_session_stream("pinned-real-ovf").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-real-ovf"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + // Client 2 (fast): attaches and actively drains each paced round (~1.28 MiB / 40 frames per + // round, well within SDK egress bounds for c2, while accumulating > 15 MiB for unread c1 so + // c1 saturates its 4 MiB SDK egress and then overflows its 8 MiB actor queue!). + let c2 = harness.connect("fast").await; + let mut s2 = c2.open_session_stream("pinned-real-ovf").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-real-ovf"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s2.next_matching(|e| e["id"] == 2).await; + + const ROUNDS: usize = 12; + for round in 0..ROUNDS { + let req_id = format!("burst-{round}"); + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":req_id,"method":"session/prompt","params":{"sessionId":"pinned-real-ovf","prompt":[{"type":"text","text":"flood"}]}})) + .await, + StatusCode::ACCEPTED + ); + let mut notices = 0usize; + let mut saw_reply = false; + while !saw_reply || notices < 40 { + let ev = tokio::time::timeout(Duration::from_secs(15), s2.next_event()) + .await + .unwrap() + .expect("fast client stream must stay open"); + if ev["params"]["update"]["sessionUpdate"] == "notice" { + notices += 1; + } + if ev["id"] == req_id { + saw_reply = true; + } + } + } + + // Client 2 continues working normally after slow Client 1 overflowed. + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":"after-burst","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf"}})) + .await, + StatusCode::ACCEPTED + ); + let status = s2.next_matching(|e| e["id"] == "after-burst").await; + assert_eq!(status["result"]["settled"], true); + + // Now drain slow Client 1's stream: it must receive `_gateway_controller` with `queue_overflow` + // and close cleanly without having disrupted Client 2! + let mut saw_overflow_notice = false; + let mut ended_cleanly = false; + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + while tokio::time::Instant::now() < deadline { + match tokio::time::timeout(Duration::from_secs(5), s1.next_event()).await { + Ok(Some(ev)) => { + if ev["params"]["update"]["sessionUpdate"] == "_gateway_controller" + && ev["params"]["update"]["_meta"]["kit/gateway"]["reason"] == "queue_overflow" + { + saw_overflow_notice = true; + } + } + Ok(None) => { + ended_cleanly = true; + break; + } + Err(_) => break, + } + } + assert!( + ended_cleanly && saw_overflow_notice, + "overflowed slow client stream must emit queue_overflow notice and close cleanly (ended={ended_cleanly}, notice={saw_overflow_notice})" + ); + + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[tokio::test] +async fn pinned_foreign_session_id_rejected_across_methods_and_list_ignores_cwd() { + let harness = PinnedHarness::new("pinned-only", Duration::from_secs(60)).await; + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-only','configOptions':[]}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-only", source, &[]).await; + + let mut c1 = harness.connect("c1").await; + let mut s1 = c1.open_session_stream("pinned-only").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-only"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + // session/list with a non-matching cwd STILL returns the pinned session. + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":2,"method":"session/list","params":{"cwd":"/unrelated/path"}})) + .await, + StatusCode::ACCEPTED + ); + let listed = c1.conn_stream.next_matching(|e| e["id"] == 2).await; + assert_eq!(listed["result"]["sessions"].as_array().unwrap().len(), 1); + assert_eq!(listed["result"]["sessions"][0]["sessionId"], "pinned-only"); + + // Foreign sessionId is rejected on session/new, session/resume, session/list, + // session/prompt, session/cancel, and session/set_config_option. + let foreign_requests = [ + (10, "session/new", json!({"sessionId": "foreign"})), + (11, "session/resume", json!({"sessionId": "foreign"})), + (12, "session/list", json!({"sessionId": "foreign"})), + ( + 13, + "session/prompt", + json!({"sessionId": "foreign", "prompt": [{"type":"text","text":"hi"}]}), + ), + (14, "session/cancel", json!({"sessionId": "foreign"})), + ( + 15, + "session/set_config_option", + json!({"sessionId": "foreign", "configId": "model", "value": "x"}), + ), + ]; + for (id, method, params) in foreign_requests { + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})) + .await, + StatusCode::ACCEPTED + ); + let reply = c1.conn_stream.next_matching(|e| e["id"] == id).await; + assert!( + reply.get("error").is_some(), + "{method} with foreign sessionId must fail, got {reply}" + ); + } + + let _ = c1.delete().await; +} + +#[tokio::test] +async fn pinned_client_request_timeout_fires_via_actor_run_timer() { + let harness = PinnedHarness::new("pinned-timer", Duration::from_millis(200)).await; + let source = r#" +import sys, json +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req['id'] == 'ask-timer' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'timeout_error': req.get('error')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-timer','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({ + 'jsonrpc':'2.0', + 'id':'ask-timer', + 'method':'elicitation/create', + 'params':{'sessionId':'pinned-timer','mode':'form','message':'nobody answers'} + }) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-timer", source, &[]).await; + + let mut c1 = harness.connect("timer-client").await; + let mut s1 = c1.open_session_stream("pinned-timer").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-timer"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":"p-timer","method":"session/prompt","params":{"sessionId":"pinned-timer","prompt":[{"type":"text","text":"ask"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q = s1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay_id = q["id"].as_str().unwrap().to_owned(); + + // Do NOT answer -> Actor::run's real deadline timer fires after 200ms! + let done = s1.next_matching(|e| e["id"] == "p-timer").await; + assert_eq!(done["result"]["timeout_error"]["code"], -32603); + assert_eq!( + done["result"]["timeout_error"]["message"], + "Incoming transport closed" + ); + let cancelled = c1 + .conn_stream + .next_matching(|e| e["method"] == "$/cancel_request") + .await; + assert_eq!(cancelled["params"]["requestId"], relay_id); + + let _ = c1.delete().await; +} + +#[tokio::test(start_paused = true)] +async fn pinned_relayed_request_race_late_answer_and_non_target_ignored() { + let timeout = Duration::from_secs(10); + let mut actor = pinned_actor("pinned-race-ans", timeout); + actor.session_result = Some(json!({"sessionId": "pinned-race-ans", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-race-ans".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-race-ans"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + let c1 = attach(&mut actor, 1); + let c2 = attach(&mut actor, 2); + + // 1. Two clients answer at once: first wins, second is ignored cleanly, loser gets $/cancel_request. + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-race", + "method": "elicitation/create", + "params": {"sessionId": "pinned-race-ans", "mode": "form", "message": "race"} + })) + .is_none() + ); + let relay1 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor + .command( + Request::Send { + session: "pinned-race-ans".into(), + attachment: c1.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"result":{"action":"accept","content":{"who":"c1"}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + actor + .command( + Request::Send { + session: "pinned-race-ans".into(), + attachment: c2.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"result":{"action":"accept","content":{"who":"c2"}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let winner = child_rx.try_recv().unwrap().message; + assert_eq!(winner["id"], "ask-race"); + assert_eq!(winner["result"]["content"]["who"], "c1"); + assert!( + child_rx.try_recv().is_err(), + "second answer must not reach child" + ); + assert_eq!( + actor.pinned.as_ref().unwrap().attachments[&c2] + .events + .back() + .unwrap() + .1["method"], + "$/cancel_request" + ); + + // 2. Non-target attachment answer is ignored cleanly, request remains pending for real target. + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-nontarget", + "method": "elicitation/create", + "params": {"sessionId": "pinned-race-ans", "mode": "form", "message": "target"} + })) + .is_none() + ); + let relay2 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + // Remove c1 from targets by having c1 reply -32601. + actor + .command( + Request::Send { + session: "pinned-race-ans".into(), + attachment: c1.clone(), + message: json!({"jsonrpc":"2.0","id":relay2,"error":{"code":-32601,"message":"Method not found"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + // c1 (now a non-target!) tries to answer -> ignored! + actor + .command( + Request::Send { + session: "pinned-race-ans".into(), + attachment: c1, + message: json!({"jsonrpc":"2.0","id":relay2,"result":{"action":"accept","content":{"spoof":true}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert!(child_rx.try_recv().is_err()); + assert!( + actor + .pinned + .as_ref() + .unwrap() + .client_requests + .contains_key(&relay2) + ); + + // 3. Timeout expires; late answer from c2 after timeout is ignored cleanly (no second child write). + tokio::time::advance(timeout).await; + let ready = actor.next_ready_client_reply().unwrap(); + actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); + let expired = child_rx.try_recv().unwrap().message; + assert_eq!(expired["error"]["code"], -32603); + actor + .command( + Request::Send { + session: "pinned-race-ans".into(), + attachment: c2, + message: json!({"jsonrpc":"2.0","id":relay2,"result":{"action":"accept","content":{"late":true}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert!( + child_rx.try_recv().is_err(), + "late answer after timeout must be ignored" + ); +} + +#[tokio::test] +async fn pinned_vs_default_forwarded_initialize_capabilities() { + let source = r#" +import sys, json +caps = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + caps = req['params']['capabilities'] + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':sys.argv[1],'configOptions':[],'_meta':{'seenCaps':caps}}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + + // Pinned mode advertises {"elicitation": {"form": {}}}. + let pinned_harness = PinnedHarness::new("cap-pinned", Duration::from_secs(60)).await; + pinned_harness + .child_source("cap-pinned", source, &["cap-pinned".into()]) + .await; + let mut pc = pinned_harness.connect("pc").await; + let _ps = pc.open_session_stream("cap-pinned").await; + assert_eq!( + pc.post(json!({"jsonrpc":"2.0","id":1,"method":"session/new","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let pr = pc.conn_stream.next_matching(|e| e["id"] == 1).await; + assert_eq!( + pr["result"]["_meta"]["seenCaps"], + json!({"elicitation": {"form": {}}}) + ); + let _ = pc.delete().await; + + // Default mode advertises {} (no elicitation capability). + let dir = tempfile::tempdir().unwrap(); + let token = dir.path().join("token"); + std::fs::write(&token, "default-secret").unwrap(); + let gateway = Arc::new(Gateway { + stopping: AtomicBool::new(false), + token: BearerToken::load(&token).unwrap(), + roots: vec![dir.path().canonicalize().unwrap()], + pinned: None, + sessions: Mutex::new(HashMap::new()), + }); + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", source, "cap-default"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let actor = Actor::new("cap-default".into(), gateway.roots[0].clone(), false, None); + let (sender, receiver) = mpsc::channel(32); + let (completion, stopped) = watch::channel(()); + tokio::spawn(async move { + actor.run(child, receiver).await; + drop(completion); + }); + gateway.sessions.lock().await.insert( + "cap-default".into(), + Entry { + root: gateway.roots[0].clone(), + sender, + stopped, + }, + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/acp/v2", listener.local_addr().unwrap()); + let app = router(gateway).unwrap(); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let client = reqwest::Client::new(); + let init = client + .post(&url) + .bearer_auth("default-secret") + .json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":2,"info":{"name":"dc","version":"1"},"capabilities":{"elicitation":{"form":{}}}}})) + .send() + .await + .unwrap(); + let conn_id = init.headers()["acp-connection-id"] + .to_str() + .unwrap() + .to_owned(); + let stream_resp = client + .get(&url) + .bearer_auth("default-secret") + .header("acp-connection-id", &conn_id) + .header("acp-session-id", "cap-default") + .header("accept", "text/event-stream") + .send() + .await + .unwrap(); + let mut s_default = SseReader::new(stream_resp); + assert_eq!( + client + .post(&url) + .bearer_auth("default-secret") + .header("acp-connection-id", &conn_id) + .json(&json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"cap-default"}})) + .send() + .await + .unwrap() + .status(), + StatusCode::ACCEPTED + ); + let dr = s_default.next_matching(|e| e["id"] == 2).await; + assert_eq!(dr["result"]["_meta"]["seenCaps"], json!({})); + server.abort(); +} diff --git a/src/gateway/tests.rs b/src/gateway/tests.rs index e82658f0..d5b83430 100644 --- a/src/gateway/tests.rs +++ b/src/gateway/tests.rs @@ -461,8 +461,7 @@ async fn accepted_child_write_retains_charge_after_dequeue_until_consumed() { startup: None, session: actor.id.clone(), replace: false, - replay: true, - replay_mode: None, + replay: ReplayMode::Start, }, &writes, ) @@ -502,8 +501,7 @@ fn failed_child_enqueue_does_not_publish_pending_request() { startup: None, session: actor.id.clone(), replace: false, - replay: true, - replay_mode: None, + replay: ReplayMode::Start, }, &writes, ) @@ -541,8 +539,7 @@ fn failed_replay_claim_preserves_owner_and_stale_release_preserves_replacement() startup: None, session: "resident".into(), replace, - replay: true, - replay_mode: None, + replay: ReplayMode::Start, }; let first = actor.command(claim(false), &writes).unwrap()["attachment"] .as_str() @@ -623,8 +620,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { startup: None, session: actor.id.clone(), replace: false, - replay: true, - replay_mode: None, + replay: ReplayMode::Start, }, &writes, ) @@ -640,6 +636,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { method: "session/resume".into(), explicit_delivery: false, withdrawal_pending: false, + orphaned: false, replay: ReplayMode::Start, }, ); @@ -674,8 +671,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { startup: None, session: actor.id.clone(), replace: true, - replay: false, - replay_mode: None, + replay: ReplayMode::None, }, &writes, ) @@ -691,6 +687,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { method: "session/resume".into(), explicit_delivery: false, withdrawal_pending: false, + orphaned: false, replay: ReplayMode::None, }, ); @@ -712,8 +709,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { startup: None, session: actor.id.clone(), replace: true, - replay: true, - replay_mode: None, + replay: ReplayMode::Start, }, &writes ) @@ -1062,8 +1058,11 @@ pub(super) fn resident_claim(actor: &Actor, replay: bool, id: u64) -> Request { Request::Attach { session: actor.id.clone(), replace: true, - replay, - replay_mode: None, + replay: if replay { + ReplayMode::Start + } else { + ReplayMode::None + }, startup: Some( json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":actor.id}}), ), @@ -1360,6 +1359,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() method: "session/prompt".into(), explicit_delivery: false, withdrawal_pending: false, + orphaned: false, replay: ReplayMode::None, }, ); @@ -1518,6 +1518,7 @@ fn stale_config_response_refreshes_snapshot_without_cross_generation_response() method: "session/set_config_option".into(), explicit_delivery: false, withdrawal_pending: false, + orphaned: false, replay: ReplayMode::None, }, ); @@ -1850,8 +1851,7 @@ fn resident_startup_omitted_or_empty_mcp_retains_overlay() { Request::Attach { session: actor.id.clone(), replace: true, - replay: false, - replay_mode: None, + replay: ReplayMode::None, startup: if via_attach { Some(startup.clone()) } else { @@ -1901,8 +1901,7 @@ fn initial_startup_preserves_mcp_servers() { Request::Attach { session: actor.id.clone(), replace: false, - replay: false, - replay_mode: None, + replay: ReplayMode::None, startup: None, }, &writes, @@ -1944,8 +1943,7 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { Request::Attach { session: actor.id.clone(), replace: true, - replay: false, - replay_mode: None, + replay: ReplayMode::None, startup: None, } }, @@ -1962,8 +1960,7 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { Request::Attach { session: actor.id.clone(), replace: true, - replay: false, - replay_mode: None, + replay: ReplayMode::None, startup: Some(startup), } } else { diff --git a/tests/gateway.rs b/tests/gateway.rs index 8251b813..4239601f 100644 --- a/tests/gateway.rs +++ b/tests/gateway.rs @@ -3285,3 +3285,118 @@ async fn pinned_session_creates_fans_out_replays_current_turn_and_restores_acros stop_gateway(&mut gateway2).await; provider.abort(); } + +#[tokio::test] +async fn pinned_real_child_detached_steer_retry_dedup_and_after_insertion_idempotency() { + let (fixture, mut requests, provider) = controlled_provider().await; + let (mut gateway, url) = fixture + .gateway_with_bind("127.0.0.1:0", &["--pinned-session", "pinned-steer-real"]) + .await; + + // Client 1 creates and starts a busy turn. + let mut c1 = SdkClient::connect(&url).await; + let created = c1 + .request( + 2, + "session/new", + json!({"cwd": fixture.root, "mcpServers": []}), + ) + .await; + assert!(created.get("error").is_none(), "{created}"); + c1.start_prompt(3, "pinned-steer-real", "Start initial turn") + .await; + let (_, release1) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + + // Client 2 (deliverer 1) attaches, submits a keyed steer while turn is busy, fences, and detaches! + let mut c2 = SdkClient::connect(&url).await; + let attached2 = c2 + .request( + 2, + "session/resume", + json!({"sessionId": "pinned-steer-real", "cwd": fixture.root}), + ) + .await; + assert!(attached2.get("error").is_none(), "{attached2}"); + assert!(c2.send(json!({ + "jsonrpc": "2.0", + "id": 10, + "method": "session/prompt", + "params": { + "sessionId": "pinned-steer-real", + "delivery": "steer", + "idempotencyKey": "real-key-1", + "prompt": [{"type": "text", "text": "Steered exactly once"}] + } + }))); + c2.fence_prompt_admission("pinned-steer-real").await; + c2.detach().await; + + // Client 3 (deliverer 2) attaches and retries with the SAME idempotencyKey while still held! + let mut c3 = SdkClient::connect(&url).await; + let attached3 = c3 + .request( + 2, + "session/resume", + json!({"sessionId": "pinned-steer-real", "cwd": fixture.root}), + ) + .await; + assert!(attached3.get("error").is_none(), "{attached3}"); + assert!(c3.send(json!({ + "jsonrpc": "2.0", + "id": 11, + "method": "session/prompt", + "params": { + "sessionId": "pinned-steer-real", + "delivery": "steer", + "idempotencyKey": "real-key-1", + "prompt": [{"type": "text", "text": "Steered exactly once"}] + } + }))); + c3.fence_prompt_admission("pinned-steer-real").await; + + // Release Turn 1 -> steer is inserted ONCE, c3 receives its receipt with messageId. + release1.send("First part.").unwrap(); + let steer_receipt = c3.response(11).await; + assert!(steer_receipt.get("error").is_none(), "{steer_receipt}"); + let message_id = steer_receipt["result"]["messageId"] + .as_str() + .expect("steer insertion receipt") + .to_owned(); + + let (body2, release2) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + let body2_str = body2["messages"].to_string(); + assert_eq!( + body2_str.matches("Steered exactly once").count(), + 1, + "held steer + detached retry must insert exactly once: {body2_str}" + ); + release2.send("Steered continuation.").unwrap(); + c1.wait_idle().await; + c3.wait_idle().await; + + // After-insertion idempotency across attachments: Client 1 replays the same idempotencyKey + // and receives the EXACT same messageId without invoking the provider again! + let replay_receipt = c1 + .request( + 20, + "session/prompt", + json!({ + "sessionId": "pinned-steer-real", + "delivery": "steer", + "idempotencyKey": "real-key-1", + "prompt": [{"type": "text", "text": "Steered exactly once"}] + }), + ) + .await; + assert!(replay_receipt.get("error").is_none(), "{replay_receipt}"); + assert_eq!(replay_receipt["result"]["messageId"], message_id); + assert!( + requests.try_recv().is_err(), + "after-insertion idempotent replay must not start a new provider turn" + ); + + c1.detach().await; + c3.detach().await; + stop_gateway(&mut gateway).await; + provider.abort(); +} From 05c07abd24e80a9aceda1745a38a7ed0964b5a1c Mon Sep 17 00:00:00 2001 From: daniel Date: Sat, 28 Nov 2026 21:04:40 +0000 Subject: [PATCH 03/19] fix(gateway): budget relay startup trim, reparent retries, and harden reaping Addresses second review of pinned-session gateway mode: - Budget pending relayed requests and existing queued events/bytes inside _kit_current_turn replay trimming so joining with a full journal and pending relay succeeds. - Record idempotencyKey on Pending and re-parent matching orphaned held session/prompt entries in place without forwarding duplicate attempts to the child. - Run pinned attachment reaping only on the actor deadline timer arm after draining ready commands so a paused process does not reap an attachment with a queued Poll. - Track detached relay targets so a -32601 from the last present target does not prematurely decline a request while another target is mid-reload. - Deduplicate Attachment::poll, resident MCP-server conflict checks, supported ACP method checks, and startup driver/waiter delivery in output(). - Restore default-mode sentence in docs/user/gateway.md verbatim to main and clarify group cancellation, reaper semantics, child PendingPrompts caps, re-parenting, and mid-message truncation in docs/reference/gateway-protocol.md. --- docs/reference/gateway-protocol.md | 10 +- docs/user/gateway.md | 4 +- src/gateway.rs | 421 ++++++++++--------- src/gateway/pinned_tests.rs | 646 ++++++++++++++++++++++++++++- src/gateway/tests.rs | 4 + tests/gateway.rs | 164 ++++++++ 6 files changed, 1039 insertions(+), 210 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 38ca3e0b..706eefe3 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -179,18 +179,18 @@ Start the gateway with `--pinned-session ` (and optionally `--client When pinned mode is active: - **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. The first client's `initialize` `info` is what the child receives. `session/list` returns only that single pinned session entry (even if `params.cwd` does not match, while rejecting any foreign `params.sessionId`), with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). -- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach; an abandoned attachment holds its slot until reaped after the 15-second lease (including an abandoned cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. +- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, so a quiet live client is never reaped by the 15-second lease, and a connection abandoned without `DELETE` is not reaped by the lease either (it holds its slot until its egress stalls/overflows or the TCP connection ends). The 15-second lease reaper cleans up attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. - **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. - **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, its failed pending requests carry `error.data.reason = "queue_overflow"`, and its SSE stream closes cleanly without affecting other attachments or the active turn. -- **Fan-in, pending caps, and deduplication:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped at 32 per attachment and 128 active across all live attachments; orphaned held prompts left behind by detached deliverers do not count against the shared 128 cap and are bounded separately at 256. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). -- **Detach and cancel:** Disconnecting an attachment does not withdraw its already-submitted held prompts, so a deliverer may disconnect before insertion and retry with the same `idempotencyKey`. Explicit `$/cancel_request` from the originating attachment still withdraws its own held prompt. Any live attachment may send `session/cancel`. +- **Fan-in, pending caps, and deduplication:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry, the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). +- **Detach and cancel:** Disconnecting an attachment does not withdraw its already-submitted held prompts, so a deliverer may disconnect before insertion and retry with the same `idempotencyKey`. Sending an explicit `$/cancel_request` withdraws **every** held attempt sharing that `idempotencyKey` (the entire unclaimed idempotency group in the child), not only the sender's attempt: every live attachment waiting on that key receives a JSON-RPC `-32800` (`Request cancelled`) error (detached attempts are dropped), the prompt is not inserted, and a deliverer must treat it as not delivered. Any live attachment may send `session/cancel`. - **Replay cursors for late joiners:** Both `session/new` and `session/resume` accept `replayFrom`: - omitted / `null`: no history; delivers current config and state snapshots only (`historyAvailable: false`). This is the default for both `session/new` and `session/resume` in pinned mode (including cold restores whose transcript exceeds the replay buffer). - `{"type":"start"}`: full retained journal from the beginning of the session (fails with `replay_unavailable` if earlier events were evicted). - - `{"type":"_kit_current_turn"}`: replays from the start of the current (or most recent) turn so a mid-turn joiner can render in-progress assistant output, even after older turns have been evicted from the journal. If the current turn itself outgrew the journal and its start was evicted, the gateway replays from the oldest retained update of the current turn and sets `result._meta["kit/gateway"].replayTruncated = true`. + - `{"type":"_kit_current_turn"}`: replays from the start of the current (or most recent) turn so a mid-turn joiner can render in-progress assistant output, even after older turns have been evicted from the journal. If the current turn itself outgrew the journal or must be trimmed to fit snapshots and pending relayed requests, the gateway replays from the oldest retained update that fits and sets `result._meta["kit/gateway"].replayTruncated = true`. When `replayTruncated` is `true`, earlier updates of the current turn were omitted and the first streamed assistant message or thought chunks replayed may be a partial tail rather than the start of that message. - `{"type":"_kit_message","sessionId":"SESSION_ID","messageId":"MESSAGE_ID"}`: inclusive replay from a retained user message ID; rejects unknown, evicted, or session-mismatched cursors with JSON-RPC `-32602`. - **Relayed agent-to-client requests:** In pinned mode the gateway advertises form elicitation (`{"elicitation":{"form":{}}}`) to the child and relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending) to every live attachment. Clients that attach while a request is still pending receive it immediately after their startup response and become eligible targets. - If no attachment is live when the request arrives, the gateway answers `-32601` immediately. - The first valid `result` from any target attachment wins and is forwarded to the child (buffered across transient child-stdin backpressure); every other target receives `$/cancel_request` for that relayed request ID. - - A `-32601` error from an attachment that does not implement the method removes only that target; if every target declined with `-32601` and none remain, the gateway answers `-32601` to the child. Any other error from a client removes only that client as a target without counting as a method-unsupported decline, keeping the request pending for remaining targets or late joiners until the timeout. + - A `-32601` error from an attachment that does not implement the method removes only that target; if every target declined with `-32601` and no target errored or detached mid-request, the gateway answers `-32601` to the child. Any other client error, or a target detaching without answering (such as a browser reloading), keeps the request pending for remaining targets or late joiners until the timeout even if other targets reply `-32601`. - Target detach does not cancel a pending request (so transient reconnects such as browser reloads can still answer). `--client-request-timeout` (default `5m`) is an absolute deadline measured from when the child request arrives. If the request is neither answered nor cancelled by the agent before the deadline, the gateway answers the child with `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. diff --git a/docs/user/gateway.md b/docs/user/gateway.md index fa3b4b18..97e9cefa 100644 --- a/docs/user/gateway.md +++ b/docs/user/gateway.md @@ -121,7 +121,7 @@ kit gateway --credential-file "$HOME/.kit-gateway-token" \ - **Shared session boundary:** All attachments share the pinned session: every connected client receives all live updates, can submit prompts or cancel work, can answer relayed interactive questions or permission requests, and can call `session/set_config_option` and `_kit/session/update_mcp` (which can register stdio MCP servers that run commands in the host or sandbox). Place an authenticating proxy in front of `kit gateway --pinned-session` when serving multiple users or services and filter methods for less-trusted clients; the gateway itself verifies only its single bearer token. - **Independent attachments:** Connecting a second client does not displace existing clients or withdraw their held prompts. Sending `session/close` detaches only the calling client without ending the session. If a slow client's output queue overflows, only that client is disconnected; other attachments and the active turn continue. - **Late joiners and reconnects:** In pinned mode, both `session/new` and `session/resume` omit historical replay by default unless `replayFrom` is provided. Clients can attach with `replayFrom: {"type":"start"}` for full retained history, `{"type":"_kit_current_turn"}` to catch up on the current or most recent turn, or `{"type":"_kit_message","sessionId":"...","messageId":"..."}` to resume from a retained user message. -- **Interactive prompts (`--client-request-timeout`):** Agent-to-client requests (such as `ask_user` forms) are sent to all attached clients and to clients that attach while the request is pending; the first valid answer wins and the other clients receive a cancellation. If no client is attached when the request arrives, it fails immediately rather than blocking the turn. If clients detach mid-request, the request stays pending until answered, cancelled, or `--client-request-timeout` (default `5m`) expires. +- **Interactive prompts (`--client-request-timeout`):** Unlike default single-controller mode (which does not support client-side ACP services), pinned-session mode relays agent-to-client requests (such as `ask_user` forms and permission requests) to all attached clients and to clients that attach while the request is pending; the first valid answer wins and the other clients receive a cancellation. If no client is attached when the request arrives, it fails immediately rather than blocking the turn. If clients detach mid-request, the request stays pending until answered, cancelled, or `--client-request-timeout` (default `5m`) expires. For exact wire behavior, cursors, and limits, see [Pinned-session mode](../reference/gateway-protocol.md#pinned-session-mode). @@ -150,6 +150,6 @@ See [Implement an ACP HTTP client](../reference/gateway-protocol.md#implement-an - There is no fixed resident-session count ceiling. Provision memory and process capacity for your workload. Detaching does not stop a session, even when it is idle; use `session/close` to end resident work. Listing or creating sessions reclaims completed entries without deleting durable transcripts. - Transport saturation can disconnect a client without canceling accepted work. HTTP frames are limited to 1 MiB; child output frames to 8 MiB. Oversized or malformed child output stops that child. There is no idle connection expiration or body-read deadline: abandoned transports can retain connection slots, and exhaustion may require restarting the gateway. See [Transport limits](../reference/gateway-protocol.md#transport-limits) before sizing an integration. These bounds are not a hard process-memory ceiling or denial-of-service protection. - Use `Ctrl+C` on the gateway host for graceful shutdown. Kit waits for child cleanup and exit, then forcibly stops a child if it exceeds the 10-second timeout. That fallback can leave a stale transcript lock requiring operator intervention. Hard process termination has operating-system-dependent cleanup behavior; arbitrary tool descendants are not a managed process group. -- Client-side ACP services (outside pinned-session mode), arbitrary extra directories, session-scoped HTTP/SSE MCP servers, browser callbacks, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. +- Client-side ACP services, arbitrary extra directories, session-scoped HTTP/SSE MCP servers, browser callbacks, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. The internal `gateway bridge` stdio command is a transport adapter for the bundled TUI, not a stable public protocol or general-purpose ACP proxy. The public transport is ACP HTTP at `/acp/v2`, implemented by the ACP SDK rather than a Kit-specific RPC protocol. diff --git a/src/gateway.rs b/src/gateway.rs index cbd15c08..e59f1215 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -966,6 +966,29 @@ impl Attachment { self.events.push_back((self.next, message)); true } + fn poll(&mut self, cursor: u64) -> Result<(Vec, bool), Failure> { + if cursor > self.next { + return Err(Failure::bad("invalid event cursor")); + } + while self + .events + .front() + .is_some_and(|(sequence, _)| *sequence <= cursor) + { + if let Some((_, message)) = self.events.pop_front() { + self.bytes -= message.to_string().len(); + } + } + let events: Vec<_> = self + .events + .iter() + .take(128) + .map(|(sequence, message)| { + object([("cursor", (*sequence).into()), ("message", message.clone())]) + }) + .collect(); + Ok((events, self.events.len() <= 128)) + } } struct Pending { attachment: String, @@ -974,8 +997,9 @@ struct Pending { explicit_delivery: bool, withdrawal_pending: bool, // In pinned mode, detached attachments leave held prompts pending without - // consuming the shared active cap. + // consuming the shared active cap; retries with the same key re-parent them. orphaned: bool, + idempotency_key: Option, // The caller's policy, independent of full internal child cache seeding. replay: ReplayMode, } @@ -998,6 +1022,9 @@ struct PendingClientRequest { // True once any target failed with a non-(-32601) error; prevents treating // remaining -32601 declines as "no attachment supports this". had_client_error: bool, + // True once any target detached without answering (e.g. mid-reload); keeps + // the request pending until timeout even if remaining targets reply -32601. + had_detached_target: bool, // Buffered child-bound JSON-RPC reply when child stdin is backpressured. resolved_reply: Option<(Value, Option>)>, } @@ -1168,7 +1195,6 @@ impl Actor { }); let mut lines = framing::Lines::new(stdout); loop { - self.reap_expired_pinned_attachments(); let withdrawal = self.next_withdrawal(); let ready_client_reply = if withdrawal.is_none() { self.next_ready_client_reply() @@ -1181,6 +1207,12 @@ impl Actor { None }; let needs_write = withdrawal.is_some() || ready_client_reply.is_some(); + enum LoopEvent { + Command(Option), + Deadline, + Line(io::Result>), + Exit, + } let event = { let write_permit = std::pin::pin!(async { if needs_write { @@ -1214,20 +1246,47 @@ impl Actor { } continue; } - Either::Right((Either::Left((command, _)), _)) => Either::Left(command), - Either::Right((Either::Right((Either::Left(((), _)), _)), _)) => continue, + Either::Right((Either::Left((command, _)), _)) => LoopEvent::Command(command), + Either::Right((Either::Right((Either::Left(((), _)), _)), _)) => { + LoopEvent::Deadline + } Either::Right(( Either::Right((Either::Right((Either::Left((line, _)), _)), _)), _, - )) => Either::Right(Some(line)), + )) => LoopEvent::Line(line), Either::Right(( Either::Right((Either::Right((Either::Right(_), _)), _)), _, - )) => Either::Right(None), + )) => LoopEvent::Exit, } }; match event { - Either::Left(command) => { + LoopEvent::Deadline => { + // Drain ready commands (such as a queued Poll after a process pause) + // before reaping attachments whose lease appears elapsed. + let mut stop_loop = false; + while let Ok(command) = commands.try_recv() { + if matches!(command.request, Request::Shutdown) { + stop_loop = true; + break; + } + let result = self.command(command.request, &writes); + let failed = result + .as_ref() + .is_err_and(|e| e.0 == StatusCode::BAD_GATEWAY); + let _ = command.reply.send(result); + if failed || self.closed { + stop_loop = true; + break; + } + } + if stop_loop { + break; + } + self.reap_expired_pinned_attachments(); + continue; + } + LoopEvent::Command(command) => { let Some(command) = command else { break; }; @@ -1243,7 +1302,7 @@ impl Actor { break; } } - Either::Right(Some(line)) => match line { + LoopEvent::Line(line) => match line { Ok(Some(line)) => match serde_json::from_str::(&line) { Ok(message) => { if let Some(reply) = self.output(message) @@ -1262,7 +1321,7 @@ impl Actor { }, _ => break, }, - Either::Right(None) => break, + LoopEvent::Exit => break, } if self.closed { break; @@ -1407,7 +1466,9 @@ impl Actor { } if let Some(pinned) = &mut self.pinned { for request in pinned.client_requests.values_mut() { - request.targets.remove(attachment_id); + if request.targets.remove(attachment_id) { + request.had_detached_target = true; + } } pinned .waiting_startups @@ -1499,30 +1560,11 @@ impl Actor { "queue_overflow", )); } - if cursor > entry.next { - return Err(Failure::bad("invalid event cursor")); - } - while entry - .events - .front() - .is_some_and(|(sequence, _)| *sequence <= cursor) - { - if let Some((_, message)) = entry.events.pop_front() { - entry.bytes -= message.to_string().len(); - } - } - if entry.events.is_empty() { + let (events, _) = entry.poll(cursor)?; + if events.is_empty() { pinned.attachments.remove(&attachment); return Err(Failure::unavailable("child exited; restore its transcript")); } - let events: Vec<_> = entry - .events - .iter() - .take(128) - .map(|(sequence, message)| { - object([("cursor", (*sequence).into()), ("message", message.clone())]) - }) - .collect(); Ok(object([ ("closed", false.into()), ("events", events.into()), @@ -1532,6 +1574,13 @@ impl Actor { } } fn push_pinned_startup_error(&mut self, attachment_id: &str, request_id: Value, error: Value) { + if !self.pinned.as_ref().is_some_and(|p| { + p.attachments + .get(attachment_id) + .is_some_and(|a| !a.closing && !a.overflowed) + }) { + return; + } let message = object([ ("jsonrpc", "2.0".into()), ("id", request_id), @@ -1699,6 +1748,7 @@ impl Actor { targets: delivered, deadline: Instant::now() + timeout, had_client_error: false, + had_detached_target: false, resolved_reply: None, }, ); @@ -1732,19 +1782,27 @@ impl Actor { request_id: Value, replay: &ReplayMode, ) -> Result { - let messages = self.startup_messages(result, request_id, replay, attachment_id)?; let pending_requests = self .pinned .as_ref() .map(PinnedState::pending_request_messages) .unwrap_or_default(); + let pending_bytes: usize = pending_requests + .iter() + .map(|(_, m)| m.to_string().len()) + .sum(); + let messages = self.startup_messages( + result, + request_id, + replay, + attachment_id, + existing_events.saturating_add(pending_requests.len()), + existing_bytes.saturating_add(pending_bytes), + )?; let total_count = existing_events + messages.len() + pending_requests.len(); let total_bytes: usize = existing_bytes + messages.iter().map(|m| m.to_string().len()).sum::() - + pending_requests - .iter() - .map(|(_, m)| m.to_string().len()) - .sum::(); + + pending_bytes; if total_count > MAX_QUEUE || total_bytes > MAX_REPLAY { return Err(Failure::replay( "session snapshot exceeds the gateway limit", @@ -1922,32 +1980,16 @@ impl Actor { } else { Vec::new() }; - if let Some(result) = message.get("result").cloned() { - if self.pinned.as_ref().is_some_and(|p| { - p.attachments - .get(&pending.attachment) - .is_some_and(|a| !a.closing) - }) { - self.deliver_pinned_startup( - &pending.attachment, - result.clone(), - pending.original, - &pending.replay, + let recipients = + std::iter::once((pending.attachment, pending.original, pending.replay)) + .chain( + waiters + .into_iter() + .map(|w| (w.attachment, w.request_id, w.replay)), ); - } - for waiter in waiters { - if self.pinned.as_ref().is_some_and(|p| { - p.attachments - .get(&waiter.attachment) - .is_some_and(|a| !a.closing) - }) { - self.deliver_pinned_startup( - &waiter.attachment, - result.clone(), - waiter.request_id, - &waiter.replay, - ); - } + if let Some(result) = message.get("result").cloned() { + for (att, req_id, replay) in recipients { + self.deliver_pinned_startup(&att, result.clone(), req_id, &replay); } } else { let error_obj = message.get("error").cloned().unwrap_or_else(|| { @@ -1956,29 +1998,8 @@ impl Actor { ("message", "session startup failed".into()), ]) }); - if self.pinned.as_ref().is_some_and(|p| { - p.attachments - .get(&pending.attachment) - .is_some_and(|a| !a.closing) - }) { - self.push_pinned_startup_error( - &pending.attachment, - pending.original, - error_obj.clone(), - ); - } - for waiter in waiters { - if self.pinned.as_ref().is_some_and(|p| { - p.attachments - .get(&waiter.attachment) - .is_some_and(|a| !a.closing) - }) { - self.push_pinned_startup_error( - &waiter.attachment, - waiter.request_id, - error_obj.clone(), - ); - } + for (att, req_id, _) in recipients { + self.push_pinned_startup_error(&att, req_id, error_obj.clone()); } } } else if !pending.orphaned @@ -2007,6 +2028,8 @@ impl Actor { message["id"].clone(), &pending.replay, &pending.attachment, + 0, + 0, ); match messages { Ok(messages) => { @@ -2072,6 +2095,8 @@ impl Actor { id: Value, replay: &ReplayMode, attachment: &str, + reserved_events: usize, + reserved_bytes: usize, ) -> Result, Failure> { let (mut replay_events, history_available, mut replay_truncated): ( VecDeque, @@ -2163,13 +2188,15 @@ impl Actor { }; if matches!(replay, ReplayMode::CurrentTurn) { // For long turns, trim oldest retained updates so the joiner still - // receives the tail of the current turn plus snapshots. + // receives the tail of the current turn plus snapshots and any + // already-queued events or pending relayed client requests. let tail_bytes: usize = snapshots.iter().map(|m| m.to_string().len()).sum::() + build_result(&result, true).to_string().len(); - let max_events = MAX_QUEUE.saturating_sub(snapshots.len() + 1); + let max_events = MAX_QUEUE.saturating_sub(snapshots.len() + 1 + reserved_events); + let max_bytes = MAX_REPLAY.saturating_sub(tail_bytes.saturating_add(reserved_bytes)); let mut replay_bytes: usize = replay_events.iter().map(|m| m.to_string().len()).sum(); while replay_events.len() > max_events - || replay_bytes.saturating_add(tail_bytes) > MAX_REPLAY + || replay_bytes > max_bytes || replay_events .front() .is_some_and(|m| m.to_string().len() > MAX_HTTP_FRAME) @@ -2377,6 +2404,15 @@ impl Actor { message["params"]["delivery"].as_str(), Some("steer" | "queue") ); + let idempotency_key = (method == "session/prompt") + .then(|| { + message["params"] + .get("idempotencyKey") + .and_then(Value::as_str) + .filter(|k| !k.is_empty()) + .map(str::to_owned) + }) + .flatten(); Some(Pending { attachment, original, @@ -2384,6 +2420,7 @@ impl Actor { explicit_delivery, withdrawal_pending: false, orphaned: false, + idempotency_key, replay, }) } else { @@ -2459,15 +2496,9 @@ impl Actor { || self.pending.values().any(|pending| { matches!(pending.method.as_str(), "session/new" | "session/resume") })) - && startup.as_ref().is_some_and(|message| { - message["params"].get("mcpServers").is_some_and(|servers| { - !servers.is_null() && servers != &Value::Array(Vec::new()) - }) - }) + && startup.as_ref().is_some_and(has_nonempty_mcp_servers) { - return Err(Failure::conflict( - "resident session retains its MCP servers; omit mcpServers or send an empty array; use _kit/session/update_mcp to add or update client servers", - )); + return Err(Failure::conflict(RESIDENT_MCP_CONFLICT)); } let metadata = startup .as_ref() @@ -2549,24 +2580,25 @@ impl Actor { } let id = crate::session::new_id(); let mut attachment = Attachment::new(id.clone()); - let started = - if let (Some(startup), Some(result)) = (startup, self.session_result.clone()) { - let request_id = startup - .get("id") - .cloned() - .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - for message in self.startup_messages(result, request_id, &replay_mode, &id)? { - if !attachment.push(message) { - return Err(Failure::replay( - "session snapshot exceeds the gateway limit", - )); - } + let started = if let (Some(startup), Some(result)) = + (startup, self.session_result.clone()) + { + let request_id = startup + .get("id") + .cloned() + .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + for message in self.startup_messages(result, request_id, &replay_mode, &id, 0, 0)? { + if !attachment.push(message) { + return Err(Failure::replay( + "session snapshot exceeds the gateway limit", + )); } - attachment.live = true; - true - } else { - false - }; + } + attachment.live = true; + true + } else { + false + }; // No fallible work after the ownership commit. The previous controller // survives every replay/snapshot preparation failure. if let Some(previous) = self.attachment.take() { @@ -2611,31 +2643,9 @@ impl Actor { Ok(object([])) } Request::Poll { cursor, .. } => { - if cursor > attachment.next { - return Err(Failure::bad("invalid event cursor")); - } - while attachment - .events - .front() - .is_some_and(|(sequence, _)| *sequence <= cursor) - { - if let Some((_, message)) = attachment.events.pop_front() { - attachment.bytes -= message.to_string().len(); - } - } - let events: Vec<_> = attachment - .events - .iter() - .take(128) - .map(|(sequence, message)| { - object([("cursor", (*sequence).into()), ("message", message.clone())]) - }) - .collect(); + let (events, drained) = attachment.poll(cursor)?; Ok(object([ - ( - "closed", - (self.closed && attachment.events.len() <= 128).into(), - ), + ("closed", (self.closed && drained).into()), ("events", events.into()), ])) } @@ -2660,19 +2670,7 @@ impl Actor { writes, ); } - if !matches!( - method.as_str(), - "initialize" - | "session/new" - | "session/resume" - | "session/prompt" - | "session/cancel" - | "session/close" - | "kit/background/cancel" - | "kit/session/status" - | "session/set_config_option" - | "_kit/session/update_mcp" - ) { + if !is_supported_acp_method(&method, true) { return Err(Failure::bad( "ACP method is not supported by the gateway; disconnect to detach", )); @@ -2720,17 +2718,14 @@ impl Actor { }; if let Some(result) = cached { if startup { - if message["params"].get("mcpServers").is_some_and(|servers| { - !servers.is_null() && servers != &Value::Array(Vec::new()) - }) { - return Err(Failure::conflict( - "resident session retains its MCP servers; omit mcpServers or send an empty array; use _kit/session/update_mcp to add or update client servers", - )); + if has_nonempty_mcp_servers(&message) { + return Err(Failure::conflict(RESIDENT_MCP_CONFLICT)); } let Some(id) = original else { return Err(Failure::bad("session startup requires a request id")); }; - let messages = self.startup_messages(result, id, &replay, &attachment)?; + let messages = + self.startup_messages(result, id, &replay, &attachment, 0, 0)?; let fits = self.attachment.as_ref().is_some_and(|a| { a.events.len() + messages.len() <= MAX_QUEUE && a.bytes @@ -2784,15 +2779,9 @@ impl Actor { matches!(pending.method.as_str(), "session/new" | "session/resume") }); if (self.session_result.is_some() || startup_in_flight) - && startup.as_ref().is_some_and(|message| { - message["params"].get("mcpServers").is_some_and(|servers| { - !servers.is_null() && servers != &Value::Array(Vec::new()) - }) - }) + && startup.as_ref().is_some_and(has_nonempty_mcp_servers) { - return Err(Failure::conflict( - "resident session retains its MCP servers; omit mcpServers or send an empty array; use _kit/session/update_mcp to add or update client servers", - )); + return Err(Failure::conflict(RESIDENT_MCP_CONFLICT)); } if matches!(replay_mode, ReplayMode::Start) && !self.replay_complete { return Err(Failure::replay( @@ -2906,27 +2895,8 @@ impl Actor { )); }; attachment.touched = Instant::now(); - if cursor > attachment.next { - return Err(Failure::bad("invalid event cursor")); - } - while attachment - .events - .front() - .is_some_and(|(sequence, _)| *sequence <= cursor) - { - if let Some((_, message)) = attachment.events.pop_front() { - attachment.bytes -= message.to_string().len(); - } - } - let events: Vec<_> = attachment - .events - .iter() - .take(128) - .map(|(sequence, message)| { - object([("cursor", (*sequence).into()), ("message", message.clone())]) - }) - .collect(); - let closed = (self.closed || attachment.closing) && attachment.events.len() <= 128; + let (events, drained) = attachment.poll(cursor)?; + let closed = (self.closed || attachment.closing) && drained; if closed && attachment.closing { pinned.attachments.remove(&token); } @@ -2995,18 +2965,7 @@ impl Actor { ); return Ok(object([])); } - if !matches!( - method.as_str(), - "initialize" - | "session/new" - | "session/resume" - | "session/prompt" - | "session/cancel" - | "kit/background/cancel" - | "kit/session/status" - | "session/set_config_option" - | "_kit/session/update_mcp" - ) { + if !is_supported_acp_method(&method, false) { return Err(Failure::bad( "ACP method is not supported by the gateway; disconnect to detach", )); @@ -3042,6 +3001,46 @@ impl Actor { { return Err(Failure::conflict("duplicate pending request id")); } + // Re-parent an orphaned held prompt matching the same idempotencyKey + // instead of forwarding a duplicate attempt to the child. + if method == "session/prompt" + && let Some(id) = &original + && let Some(key) = message["params"] + .get("idempotencyKey") + .and_then(Value::as_str) + .filter(|k| !k.is_empty()) + && let Some(orphan_serial) = self + .pending + .iter() + .filter(|(_, p)| { + p.orphaned + && p.method == "session/prompt" + && p.idempotency_key.as_deref() == Some(key) + }) + .map(|(&serial, _)| serial) + .min() + { + let attachment_active = self + .pending + .values() + .filter(|p| !p.orphaned && p.attachment == attachment) + .count(); + if attachment_active >= MAX_PENDING_PER_ATTACHMENT { + return Err(Failure::unavailable( + "too many pending ACP requests for attachment", + )); + } + let shared_active = self.pending.values().filter(|p| !p.orphaned).count(); + if shared_active >= MAX_PENDING_SHARED { + return Err(Failure::unavailable("too many pending ACP requests")); + } + if let Some(entry) = self.pending.get_mut(&orphan_serial) { + entry.attachment = attachment; + entry.original = id.clone(); + entry.orphaned = false; + } + return Ok(object([])); + } if method == "initialize" && let Some(result) = self.initialized.clone() { @@ -3094,7 +3093,10 @@ impl Actor { // Client-side failure: drop only this target and keep pending // for remaining targets or a late joiner until timeout. req.had_client_error = true; - } else if req.targets.is_empty() && !req.had_client_error { + } else if req.targets.is_empty() + && !req.had_client_error + && !req.had_detached_target + { let reply = object([ ("jsonrpc", "2.0".into()), ("id", req.child_id.clone()), @@ -3149,6 +3151,29 @@ impl Actor { } } +const RESIDENT_MCP_CONFLICT: &str = "resident session retains its MCP servers; omit mcpServers or send an empty array; use _kit/session/update_mcp to add or update client servers"; + +fn has_nonempty_mcp_servers(message: &Value) -> bool { + message["params"] + .get("mcpServers") + .is_some_and(|servers| !servers.is_null() && servers != &Value::Array(Vec::new())) +} + +fn is_supported_acp_method(method: &str, allow_close: bool) -> bool { + matches!( + method, + "initialize" + | "session/new" + | "session/resume" + | "session/prompt" + | "session/cancel" + | "kit/background/cancel" + | "kit/session/status" + | "session/set_config_option" + | "_kit/session/update_mcp" + ) || (allow_close && method == "session/close") +} + fn cancel_request_message(request_id: Value) -> Value { object([ ("jsonrpc", "2.0".into()), diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 9276c571..394ee2b6 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -660,7 +660,8 @@ for line in sys.stdin: drop(s1); assert_eq!(c1.delete().await, StatusCode::ACCEPTED); - // Client 2 retries with the same idempotencyKey "k-survive" -> joins the held group (2 attempts, 1 insertion)! + // Client 2 retries with the same idempotencyKey "k-survive" -> re-parents the orphaned + // entry without forwarding a duplicate attempt to the child (1 attempt, 1 insertion)! assert_eq!( c2.post(json!({ "jsonrpc": "2.0", @@ -676,11 +677,8 @@ for line in sys.stdin: .await, StatusCode::ACCEPTED ); - let _ = s2 - .next_matching(|e| e["params"]["update"]["message"] == "held:k-survive:2") - .await; - // Trigger insertion flush via kit/session/status. + // Trigger insertion flush via kit/session/status (ordered after steer-retry on c2). assert_eq!( c2.post(json!({ "jsonrpc": "2.0", @@ -3295,3 +3293,641 @@ for line in sys.stdin: assert_eq!(dr["result"]["_meta"]["seenCaps"], json!({})); server.abort(); } + +#[test] +fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_byte_bounds() { + // 1. Event-count bound: full journal (MAX_QUEUE - 3 events in current turn) + pending relay. + let mut actor = pinned_actor("pinned-trim-count", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-trim-count", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let c1 = actor + .command( + Request::Attach { + session: "pinned-trim-count".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-trim-count"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-trim-count","update":{"sessionUpdate":"state_update","state":"running"}}})); + for i in 0..MAX_QUEUE { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-trim-count", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": format!("e-{i}")}}} + })); + if i % 64 == 0 { + let cur = actor.pinned.as_ref().unwrap().attachments[&c1].next; + let _ = actor.command( + Request::Poll { + session: "pinned-trim-count".into(), + attachment: c1.clone(), + cursor: cur, + }, + &writes, + ); + } + } + assert_eq!(actor.journal.len(), MAX_QUEUE - 3); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-full-count", + "method": "elicitation/create", + "params": {"sessionId": "pinned-trim-count", "mode": "form", "message": "answer me"} + })) + .is_none() + ); + let relay_id = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + + let c2 = actor + .command( + Request::Attach { + session: "pinned-trim-count".into(), + replay: ReplayMode::CurrentTurn, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-trim-count"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let c2_att = &actor.pinned.as_ref().unwrap().attachments[&c2]; + assert!(c2_att.events.len() <= MAX_QUEUE); + let events: Vec = c2_att.events.iter().map(|(_, m)| m.clone()).collect(); + let result_msg = events.iter().find(|e| e["id"] == 2).unwrap(); + assert_eq!( + result_msg["result"]["_meta"]["kit/gateway"]["replayTruncated"], + true + ); + assert_eq!(events.last().unwrap()["method"], "elicitation/create"); + assert_eq!(events.last().unwrap()["id"], relay_id); + assert!( + actor.pinned.as_ref().unwrap().client_requests[&relay_id] + .targets + .contains(&c2) + ); + // Joiner can answer the pending relayed request! + actor + .command( + Request::Send { + session: "pinned-trim-count".into(), + attachment: c2, + message: json!({"jsonrpc":"2.0","id":relay_id,"result":{"action":"accept","content":{"ok":true}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let reply = child_rx.try_recv().unwrap().message; + assert_eq!(reply["id"], "ask-full-count"); + assert_eq!(reply["result"]["content"]["ok"], true); + + // 2. Byte-bound variant: journal near MAX_REPLAY bytes + large pending relay + existing bytes. + let mut byte_actor = pinned_actor("pinned-trim-bytes", Duration::from_secs(60)); + byte_actor.session_result = + Some(json!({"sessionId": "pinned-trim-bytes", "configOptions": []})); + let b1 = byte_actor + .command( + Request::Attach { + session: "pinned-trim-bytes".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-trim-bytes"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + byte_actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"pinned-trim-bytes","update":{"sessionUpdate":"state_update","state":"running"}}})); + let chunk_pad = "b".repeat(512 * 1024); + for i in 0..16 { + byte_actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-trim-bytes", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": format!("{i}:{chunk_pad}")}}} + })); + let cur = byte_actor.pinned.as_ref().unwrap().attachments[&b1].next; + let _ = byte_actor.command( + Request::Poll { + session: "pinned-trim-bytes".into(), + attachment: b1.clone(), + cursor: cur, + }, + &writes, + ); + } + assert!(byte_actor.journal_bytes > MAX_REPLAY - 600 * 1024); + let large_prompt = "q".repeat(200 * 1024); + assert!( + byte_actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-full-bytes", + "method": "elicitation/create", + "params": {"sessionId": "pinned-trim-bytes", "mode": "form", "message": large_prompt} + })) + .is_none() + ); + let byte_relay_id = byte_actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + // Verify both fresh attach (existing=0) and prepare_pinned_startup with non-zero existing bytes. + let prepared = byte_actor + .prepare_pinned_startup( + "existing-att", + 2, + 128 * 1024, + byte_actor.session_result.clone().unwrap(), + json!(99), + &ReplayMode::CurrentTurn, + ) + .unwrap(); + let prepared_bytes: usize = 128 * 1024 + + prepared + .messages + .iter() + .map(|m| m.to_string().len()) + .sum::() + + prepared + .pending_requests + .iter() + .map(|(_, m)| m.to_string().len()) + .sum::(); + assert!(prepared_bytes <= MAX_REPLAY); + assert_eq!(prepared.pending_requests.len(), 1); + assert_eq!( + prepared.messages.last().unwrap()["result"]["_meta"]["kit/gateway"]["replayTruncated"], + true + ); + + let b2 = byte_actor + .command( + Request::Attach { + session: "pinned-trim-bytes".into(), + replay: ReplayMode::CurrentTurn, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-trim-bytes"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let b2_att = &byte_actor.pinned.as_ref().unwrap().attachments[&b2]; + assert!(b2_att.bytes <= MAX_REPLAY); + assert_eq!(b2_att.events.back().unwrap().1["id"], byte_relay_id); + let b2_result = b2_att + .events + .iter() + .find(|(_, m)| m["id"] == 2) + .unwrap() + .1 + .clone(); + assert_eq!( + b2_result["result"]["_meta"]["kit/gateway"]["replayTruncated"], + true + ); +} + +#[test] +fn pinned_orphaned_idempotency_retry_reparents_without_forwarding_to_child() { + let mut actor = pinned_actor("pinned-reparent", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-reparent", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(32); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-reparent".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-reparent"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + + // Initial deliverer submits a keyed held steer and detaches. + let d0 = attach(&mut actor, 1); + actor + .command( + Request::Send { + session: "pinned-reparent".into(), + attachment: d0.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "try-0", + "method": "session/prompt", + "params": {"sessionId": "pinned-reparent", "delivery": "steer", "idempotencyKey": "k-reparent", "prompt": [{"type":"text","text":"once"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let child_serial = child_rx.try_recv().unwrap().message["id"].clone(); + actor + .command( + Request::Detach { + session: "pinned-reparent".into(), + attachment: d0, + }, + &writes, + ) + .unwrap(); + assert_eq!(actor.pending.len(), 1); + + // 50 retries from detached deliverers re-parent the SAME single pending entry and send ZERO new attempts to the child! + for i in 1..=50u64 { + let di = attach(&mut actor, 10 + i); + actor + .command( + Request::Send { + session: "pinned-reparent".into(), + attachment: di.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": format!("try-{i}"), + "method": "session/prompt", + "params": {"sessionId": "pinned-reparent", "delivery": "steer", "idempotencyKey": "k-reparent", "prompt": [{"type":"text","text":"once"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + assert_eq!(actor.pending.len(), 1, "retry {i} must re-parent in place"); + assert!( + child_rx.try_recv().is_err(), + "retry {i} must not forward a duplicate attempt to child" + ); + actor + .command( + Request::Detach { + session: "pinned-reparent".into(), + attachment: di, + }, + &writes, + ) + .unwrap(); + } + + // Final deliverer attaches, retries with "k-reparent", stays attached, and receives the child's reply! + let final_att = attach(&mut actor, 999); + actor + .command( + Request::Send { + session: "pinned-reparent".into(), + attachment: final_att.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "final-try", + "method": "session/prompt", + "params": {"sessionId": "pinned-reparent", "delivery": "steer", "idempotencyKey": "k-reparent", "prompt": [{"type":"text","text":"once"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + assert_eq!(actor.pending.len(), 1); + assert!(child_rx.try_recv().is_err()); + + // Meanwhile, two LIVE attachments submitting the same key still forward both to the child. + let live2 = attach(&mut actor, 1000); + actor + .command( + Request::Send { + session: "pinned-reparent".into(), + attachment: live2.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "live-dup", + "method": "session/prompt", + "params": {"sessionId": "pinned-reparent", "delivery": "steer", "idempotencyKey": "k-reparent", "prompt": [{"type":"text","text":"once"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + assert_eq!(actor.pending.len(), 2); + let _forwarded_live_dup = child_rx + .try_recv() + .expect("non-orphaned duplicate key must still forward to child"); + + // Child resolves the original serial -> reply arrives at final_att with id "final-try"! + actor + .output(json!({"jsonrpc":"2.0","id":child_serial,"result":{"messageId":"msg-reparented"}})); + let final_events = &actor.pinned.as_ref().unwrap().attachments[&final_att].events; + assert_eq!(final_events.back().unwrap().1["id"], "final-try"); + assert_eq!( + final_events.back().unwrap().1["result"]["messageId"], + "msg-reparented" + ); +} + +#[tokio::test(start_paused = true)] +async fn pinned_reaper_drains_queued_poll_before_reaping_after_process_freeze() { + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", source]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut actor = pinned_actor("pinned-freeze", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-freeze", "configOptions": []})); + let (sender, receiver) = mpsc::channel(32); + let actor_task = tokio::spawn(async move { + actor.run(child, receiver).await; + }); + + let send_req = |request: Request| { + let sender = sender.clone(); + async move { + let (tx, rx) = oneshot::channel(); + sender.send(Envelope { request, reply: tx }).await.unwrap(); + rx.await.unwrap() + } + }; + + let a1 = send_req(Request::Attach { + session: "pinned-freeze".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-freeze"}})), + }) + .await + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let a2 = send_req(Request::Attach { + session: "pinned-freeze".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-freeze"}})), + }) + .await + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + // Let Actor::run park on its deadline timer. + tokio::task::yield_now().await; + + // Simulate a process freeze > LEASE, then queue a1's Poll BEFORE Actor::run wakes! + tokio::time::advance(LEASE + Duration::from_secs(5)).await; + let (tx1, rx1) = oneshot::channel(); + sender + .try_send(Envelope { + request: Request::Poll { + session: "pinned-freeze".into(), + attachment: a1.clone(), + cursor: 0, + }, + reply: tx1, + }) + .unwrap(); + + // a1's queued Poll MUST succeed (not be reaped before Actor::run sees it)! + let a1_poll = rx1.await.unwrap(); + assert!( + a1_poll.is_ok(), + "queued Poll must refresh lease before reaping: {a1_poll:?}" + ); + + // Yield so Actor::run's timer arm runs and reaps a2 (which had no queued Poll). + tokio::task::yield_now().await; + tokio::task::yield_now().await; + + let a2_err = send_req(Request::Poll { + session: "pinned-freeze".into(), + attachment: a2, + cursor: 0, + }) + .await + .unwrap_err(); + assert_eq!(a2_err.2, "attachment_closed"); + + // a1 is STILL alive! + let a1_still_alive = send_req(Request::Poll { + session: "pinned-freeze".into(), + attachment: a1, + cursor: 0, + }) + .await; + assert!(a1_still_alive.is_ok(), "{a1_still_alive:?}"); + + let (tx, _rx) = oneshot::channel(); + let _ = sender + .send(Envelope { + request: Request::Shutdown, + reply: tx, + }) + .await; + actor_task.abort(); +} + +#[tokio::test(start_paused = true)] +async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { + let timeout = Duration::from_secs(10); + let mut actor = pinned_actor("pinned-detach-32601", timeout); + actor.session_result = Some(json!({"sessionId": "pinned-detach-32601", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-detach-32601".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-detach-32601"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + + // Case 1: Dashboard c1 detaches mid-reload, then trigger c2 replies -32601 -> + // request MUST stay pending so reloaded dashboard c3 can answer! + let c1 = attach(&mut actor, 1); + let c2 = attach(&mut actor, 2); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-reload-32601", + "method": "elicitation/create", + "params": {"sessionId": "pinned-detach-32601", "mode": "form", "message": "confirm"} + })) + .is_none() + ); + let relay1 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + + // Dashboard detaches without answering. + actor + .command( + Request::Detach { + session: "pinned-detach-32601".into(), + attachment: c1, + }, + &writes, + ) + .unwrap(); + // Remaining trigger client replies -32601 (does not implement elicitation). + actor + .command( + Request::Send { + session: "pinned-detach-32601".into(), + attachment: c2.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"error":{"code":-32601,"message":"Method not found"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert!( + child_rx.try_recv().is_err(), + "must NOT decline with -32601 when another target detached mid-request" + ); + assert!( + actor + .pinned + .as_ref() + .unwrap() + .client_requests + .contains_key(&relay1) + ); + + // Reloaded dashboard c3 attaches, receives the pending request, and answers! + let c3 = attach(&mut actor, 3); + assert_eq!( + actor.pinned.as_ref().unwrap().attachments[&c3] + .events + .back() + .unwrap() + .1["id"], + relay1 + ); + actor + .command( + Request::Send { + session: "pinned-detach-32601".into(), + attachment: c3.clone(), + message: json!({"jsonrpc":"2.0","id":relay1,"result":{"action":"accept","content":{"ok":"yes"}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + let answered = child_rx.try_recv().unwrap().message; + assert_eq!(answered["id"], "ask-reload-32601"); + assert_eq!(answered["result"]["content"]["ok"], "yes"); + + // Case 2: If no client reattaches before timeout, it expires with -32603 (not -32601). + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-reload-timeout", + "method": "elicitation/create", + "params": {"sessionId": "pinned-detach-32601", "mode": "form", "message": "confirm2"} + })) + .is_none() + ); + let relay2 = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + actor + .command( + Request::Detach { + session: "pinned-detach-32601".into(), + attachment: c3, + }, + &writes, + ) + .unwrap(); + actor + .command( + Request::Send { + session: "pinned-detach-32601".into(), + attachment: c2, + message: json!({"jsonrpc":"2.0","id":relay2,"error":{"code":-32601,"message":"Method not found"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert!(child_rx.try_recv().is_err()); + tokio::time::advance(timeout).await; + let ready = actor.next_ready_client_reply().unwrap(); + assert_eq!(ready, relay2); + actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); + let expired = child_rx.try_recv().unwrap().message; + assert_eq!(expired["id"], "ask-reload-timeout"); + assert_eq!(expired["error"]["code"], -32603); + assert_eq!(expired["error"]["message"], "Incoming transport closed"); +} diff --git a/src/gateway/tests.rs b/src/gateway/tests.rs index d5b83430..1c7adfef 100644 --- a/src/gateway/tests.rs +++ b/src/gateway/tests.rs @@ -637,6 +637,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { explicit_delivery: false, withdrawal_pending: false, orphaned: false, + idempotency_key: None, replay: ReplayMode::Start, }, ); @@ -688,6 +689,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { explicit_delivery: false, withdrawal_pending: false, orphaned: false, + idempotency_key: None, replay: ReplayMode::None, }, ); @@ -1360,6 +1362,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() explicit_delivery: false, withdrawal_pending: false, orphaned: false, + idempotency_key: None, replay: ReplayMode::None, }, ); @@ -1519,6 +1522,7 @@ fn stale_config_response_refreshes_snapshot_without_cross_generation_response() explicit_delivery: false, withdrawal_pending: false, orphaned: false, + idempotency_key: None, replay: ReplayMode::None, }, ); diff --git a/tests/gateway.rs b/tests/gateway.rs index 4239601f..a1c49b76 100644 --- a/tests/gateway.rs +++ b/tests/gateway.rs @@ -3400,3 +3400,167 @@ async fn pinned_real_child_detached_steer_retry_dedup_and_after_insertion_idempo stop_gateway(&mut gateway).await; provider.abort(); } + +#[tokio::test] +async fn pinned_real_child_retry_storm_reparents_and_does_not_block_other_client() { + let (fixture, mut requests, provider) = controlled_provider().await; + let (mut gateway, url) = fixture + .gateway_with_bind("127.0.0.1:0", &["--pinned-session", "pinned-storm"]) + .await; + + // Client 1 creates the session and starts a busy turn. + let mut c1 = SdkClient::connect(&url).await; + let created = c1 + .request( + 2, + "session/new", + json!({"cwd": fixture.root, "mcpServers": []}), + ) + .await; + assert!(created.get("error").is_none(), "{created}"); + c1.start_prompt(3, "pinned-storm", "Start busy turn").await; + let (_, release1) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + + // Initial deliverer submits a held steer with idempotencyKey "storm-key", fences, and detaches. + let mut first = SdkClient::connect(&url).await; + let attached = first + .request( + 2, + "session/resume", + json!({"sessionId": "pinned-storm", "cwd": fixture.root}), + ) + .await; + assert!(attached.get("error").is_none(), "{attached}"); + assert!(first.send(json!({ + "jsonrpc": "2.0", + "id": 10, + "method": "session/prompt", + "params": { + "sessionId": "pinned-storm", + "delivery": "steer", + "idempotencyKey": "storm-key", + "prompt": [{"type": "text", "text": "Storm message once"}] + } + }))); + first.fence_prompt_admission("pinned-storm").await; + first.detach().await; + + // 265 detached retries (> agentkit-acp's 256-attempt PendingPrompts ceiling!). + // Re-parenting ensures zero extra child attempts are created, so neither the gateway + // nor the real child's PendingPrompts table is exhausted. + let mut retry_client = SdkClient::connect(&url).await; + for attempt in 0..265u64 { + let base_id = 100 + attempt * 10; + let resumed = retry_client + .request( + base_id, + "session/resume", + json!({"sessionId": "pinned-storm", "cwd": fixture.root}), + ) + .await; + assert!( + resumed.get("error").is_none(), + "attempt {attempt}: {resumed}" + ); + assert!(retry_client.send(json!({ + "jsonrpc": "2.0", + "id": base_id + 1, + "method": "session/prompt", + "params": { + "sessionId": "pinned-storm", + "delivery": "steer", + "idempotencyKey": "storm-key", + "prompt": [{"type": "text", "text": "Storm message once"}] + } + }))); + // Local session/close detaches ONLY this attachment in FIFO order after session/prompt. + let closed = retry_client + .request( + base_id + 2, + "session/close", + json!({"sessionId": "pinned-storm"}), + ) + .await; + assert!(closed.get("error").is_none(), "attempt {attempt}: {closed}"); + } + retry_client.detach().await; + + // Final deliverer re-attaches, retries "storm-key", and stays attached for the receipt. + let mut final_deliverer = SdkClient::connect(&url).await; + let resumed_final = final_deliverer + .request( + 2, + "session/resume", + json!({"sessionId": "pinned-storm", "cwd": fixture.root}), + ) + .await; + assert!(resumed_final.get("error").is_none(), "{resumed_final}"); + assert!(final_deliverer.send(json!({ + "jsonrpc": "2.0", + "id": 50, + "method": "session/prompt", + "params": { + "sessionId": "pinned-storm", + "delivery": "steer", + "idempotencyKey": "storm-key", + "prompt": [{"type": "text", "text": "Storm message once"}] + } + }))); + final_deliverer.fence_prompt_admission("pinned-storm").await; + + // A second, completely different client submits a different steer -> must NOT be blocked! + let mut other_client = SdkClient::connect(&url).await; + let resumed_other = other_client + .request( + 2, + "session/resume", + json!({"sessionId": "pinned-storm", "cwd": fixture.root}), + ) + .await; + assert!(resumed_other.get("error").is_none(), "{resumed_other}"); + assert!(other_client.send(json!({ + "jsonrpc": "2.0", + "id": 60, + "method": "session/prompt", + "params": { + "sessionId": "pinned-storm", + "delivery": "steer", + "idempotencyKey": "other-client-key", + "prompt": [{"type": "text", "text": "Other client steer"}] + } + }))); + other_client.fence_prompt_admission("pinned-storm").await; + + // Release Turn 1 -> both distinct steers insert cleanly and each client gets its receipt! + release1.send("First turn done.").unwrap(); + let storm_receipt = final_deliverer.response(50).await; + assert!(storm_receipt.get("error").is_none(), "{storm_receipt}"); + assert!(storm_receipt["result"]["messageId"].as_str().is_some()); + + let other_receipt = other_client.response(60).await; + assert!(other_receipt.get("error").is_none(), "{other_receipt}"); + assert!(other_receipt["result"]["messageId"].as_str().is_some()); + + let (body2, release2) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + let body2_str = body2["messages"].to_string(); + assert_eq!( + body2_str.matches("Storm message once").count(), + 1, + "265 retries must insert storm message exactly once: {body2_str}" + ); + assert_eq!( + body2_str.matches("Other client steer").count(), + 1, + "second client's steer must also be inserted: {body2_str}" + ); + release2.send("Steered turn done.").unwrap(); + c1.wait_idle().await; + final_deliverer.wait_idle().await; + other_client.wait_idle().await; + + c1.detach().await; + final_deliverer.detach().await; + other_client.detach().await; + stop_gateway(&mut gateway).await; + provider.abort(); +} From 047289b69918b86b4fd5cef6a93c35a50e2e9a82 Mon Sep 17 00:00:00 2001 From: daniel Date: Sat, 28 Nov 2026 21:29:12 +0000 Subject: [PATCH 04/19] fix(gateway): reserve start-replay relay headroom, skip cancelled orphans, and deflake eviction test Addresses final review items for pinned-session gateway mode: - Deflake pinned_session_new_without_replay_from_defaults_to_none_and_survives_eviction by filling the journal across 6 client-acknowledged 1.6 MiB rounds instead of a single 10 MiB burst that could overflow c1 before polling. - Guard re-parenting against cancelled orphans (both withdrawal_pending and already-enqueued cancellations by clearing idempotency_key on cancel). - Reserve startup headroom for bounded pending relayed requests in start replay so a complete full journal with a pending relay succeeds and replay_unavailable is returned only when the history itself cannot be replayed in full. - Update docs/reference/gateway-protocol.md to document mandatory DELETE on client disconnect (no TCP-drop reaping) and that re-parented retries reuse the original held prompt body. --- docs/reference/gateway-protocol.md | 4 +- src/gateway.rs | 46 +++- src/gateway/pinned_tests.rs | 418 ++++++++++++++++++++++++++++- 3 files changed, 447 insertions(+), 21 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 706eefe3..0f57fe91 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -179,10 +179,10 @@ Start the gateway with `--pinned-session ` (and optionally `--client When pinned mode is active: - **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. The first client's `initialize` `info` is what the child receives. `session/list` returns only that single pinned session entry (even if `params.cwd` does not match, while rejecting any foreign `params.sessionId`), with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). -- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, so a quiet live client is never reaped by the 15-second lease, and a connection abandoned without `DELETE` is not reaped by the lease either (it holds its slot until its egress stalls/overflows or the TCP connection ends). The 15-second lease reaper cleans up attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. +- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. - **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. - **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, its failed pending requests carry `error.data.reason = "queue_overflow"`, and its SSE stream closes cleanly without affecting other attachments or the active turn. -- **Fan-in, pending caps, and deduplication:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry, the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). +- **Fan-in, pending caps, and deduplication:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry (whose withdrawal has not been requested), the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). A re-parented retry's prompt body is not re-validated or used: the original held prompt is what gets inserted, matching the child's duplicate-key semantics. - **Detach and cancel:** Disconnecting an attachment does not withdraw its already-submitted held prompts, so a deliverer may disconnect before insertion and retry with the same `idempotencyKey`. Sending an explicit `$/cancel_request` withdraws **every** held attempt sharing that `idempotencyKey` (the entire unclaimed idempotency group in the child), not only the sender's attempt: every live attachment waiting on that key receives a JSON-RPC `-32800` (`Request cancelled`) error (detached attempts are dropped), the prompt is not inserted, and a deliverer must treat it as not delivered. Any live attachment may send `session/cancel`. - **Replay cursors for late joiners:** Both `session/new` and `session/resume` accept `replayFrom`: - omitted / `null`: no history; delivers current config and state snapshots only (`historyAvailable: false`). This is the default for both `session/new` and `session/resume` in pinned mode (including cold restores whose transcript exceeds the replay buffer). diff --git a/src/gateway.rs b/src/gateway.rs index e59f1215..ae104274 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -961,10 +961,13 @@ impl Attachment { if self.events.len() >= MAX_QUEUE || self.bytes + bytes > MAX_REPLAY { return false; } - self.bytes += bytes; + self.push_reserved(message); + true + } + fn push_reserved(&mut self, message: Value) { + self.bytes += message.to_string().len(); self.next += 1; self.events.push_back((self.next, message)); - true } fn poll(&mut self, cursor: u64) -> Result<(Vec, bool), Failure> { if cursor > self.next { @@ -1791,19 +1794,26 @@ impl Actor { .iter() .map(|(_, m)| m.to_string().len()) .sum(); + let (reserved_events, reserved_bytes) = if matches!(replay, ReplayMode::CurrentTurn) { + ( + existing_events.saturating_add(pending_requests.len()), + existing_bytes.saturating_add(pending_bytes), + ) + } else { + (0, 0) + }; let messages = self.startup_messages( result, request_id, replay, attachment_id, - existing_events.saturating_add(pending_requests.len()), - existing_bytes.saturating_add(pending_bytes), + reserved_events, + reserved_bytes, )?; - let total_count = existing_events + messages.len() + pending_requests.len(); - let total_bytes: usize = existing_bytes - + messages.iter().map(|m| m.to_string().len()).sum::() - + pending_bytes; - if total_count > MAX_QUEUE || total_bytes > MAX_REPLAY { + let history_count = existing_events + messages.len(); + let history_bytes: usize = + existing_bytes + messages.iter().map(|m| m.to_string().len()).sum::(); + if history_count > MAX_QUEUE || history_bytes > MAX_REPLAY { return Err(Failure::replay( "session snapshot exceeds the gateway limit", )); @@ -1818,7 +1828,19 @@ impl Actor { self.push_pinned_attachment(attachment_id, update); } for (relay_id, req_msg) in prepared.pending_requests { - if self.push_pinned_attachment(attachment_id, req_msg) + let delivered = if let Some(pinned) = &mut self.pinned + && let Some(attachment) = pinned.attachments.get_mut(attachment_id) + && !attachment.overflowed + && !attachment.closing + { + // Relayed requests are already bounded by MAX_PINNED_CLIENT_REQUESTS; + // reserve startup headroom so a complete full journal never fails on them. + attachment.push_reserved(req_msg); + true + } else { + false + }; + if delivered && let Some(pinned) = &mut self.pinned && let Some(req) = pinned.client_requests.get_mut(&relay_id) { @@ -2307,6 +2329,9 @@ impl Actor { }) else { return Ok(object([])); }; + // Clear the idempotency key so a subsequent retry never re-parents onto + // a prompt whose cancellation is in flight or pending. + pending.idempotency_key = None; // The normalized child notification needs only the remapped ID. match writes.try_reserve() { Ok(permit) => self.send_withdrawal(child_id, permit), @@ -3014,6 +3039,7 @@ impl Actor { .iter() .filter(|(_, p)| { p.orphaned + && !p.withdrawal_pending && p.method == "session/prompt" && p.idempotency_key.as_deref() == Some(key) }) diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 394ee2b6..3518864a 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -1808,8 +1808,8 @@ for line in sys.stdin: emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-evict','configOptions':[]}}) elif m == 'session/prompt': pad = 'x' * (400 * 1024) - for i in range(25): - emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-evict','update':{'sessionUpdate':'notice','message':f'{i}:{pad}'}}}) + for i in range(4): + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-evict','update':{'sessionUpdate':'notice','message':f'{req["id"]}:{i}:{pad}'}}}) emit({'jsonrpc':'2.0','id':req['id'],'result':{'stopReason':'end_turn'}}) elif 'id' in req: emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) @@ -1826,13 +1826,31 @@ for line in sys.stdin: let r1 = c1.conn_stream.next_matching(|e| e["id"] == 1).await; assert_eq!(r1["result"]["sessionId"], "pinned-evict"); - // Emit > 8 MiB so the journal evicts early events. - assert_eq!( - c1.post(json!({"jsonrpc":"2.0","id":2,"method":"session/prompt","params":{"sessionId":"pinned-evict","prompt":[{"type":"text","text":"fill"}]}})) - .await, - StatusCode::ACCEPTED - ); - let _ = s1.next_matching(|e| e["id"] == 2).await; + // Emit > 8 MiB across 6 paced rounds (1.6 MiB per round, well under c1's 4 MiB SDK egress + // and 8 MiB attachment queue) so the journal deterministically evicts early events without + // overflowing c1. + for round in 0..6u64 { + let req_id = 10 + round; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":req_id,"method":"session/prompt","params":{"sessionId":"pinned-evict","prompt":[{"type":"text","text":"fill"}]}})) + .await, + StatusCode::ACCEPTED + ); + let mut notices = 0usize; + let mut saw_reply = false; + while !saw_reply || notices < 4 { + let ev = tokio::time::timeout(Duration::from_secs(15), s1.next_event()) + .await + .unwrap() + .expect("paced c1 stream must stay open"); + if ev["params"]["update"]["sessionUpdate"] == "notice" { + notices += 1; + } + if ev["id"] == req_id { + saw_reply = true; + } + } + } // A fresh client sending session/new with NO replayFrom succeeds with historyAvailable=false. let mut c2 = harness.connect("c2").await; @@ -3931,3 +3949,385 @@ async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { assert_eq!(expired["error"]["code"], -32603); assert_eq!(expired["error"]["message"], "Incoming transport closed"); } + +#[test] +fn pinned_cancelled_orphan_is_not_reparented_and_forwards_fresh_retry() { + let mut actor = pinned_actor("pinned-cancel-reparent", Duration::from_secs(60)); + actor.session_result = + Some(json!({"sessionId": "pinned-cancel-reparent", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(1); + + let attach = |actor: &mut Actor, id: u64| -> String { + actor + .command( + Request::Attach { + session: "pinned-cancel-reparent".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-cancel-reparent"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + + // Case 1: Deliverer submits keyed steer, cancels while child stdin is full + // (sets withdrawal_pending = true), then detaches. Retry MUST forward as a fresh attempt! + let d1 = attach(&mut actor, 1); + actor + .command( + Request::Send { + session: "pinned-cancel-reparent".into(), + attachment: d1.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "p-1", + "method": "session/prompt", + "params": {"sessionId": "pinned-cancel-reparent", "delivery": "steer", "idempotencyKey": "k-cancelled-bp", "prompt": [{"type":"text","text":"v1"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let orig_serial = child_rx.try_recv().unwrap().message["id"].as_u64().unwrap(); + // Saturate the single-slot writes channel so $/cancel_request sets withdrawal_pending = true. + writes + .try_send(ChildWrite { + withdrawals: Vec::new(), + message: json!({"blocker": true}), + _charge: None, + }) + .unwrap(); + actor + .command( + Request::Send { + session: "pinned-cancel-reparent".into(), + attachment: d1.clone(), + message: json!({"jsonrpc":"2.0","method":"$/cancel_request","params":{"requestId":"p-1"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert!(actor.pending[&orig_serial].withdrawal_pending); + actor + .command( + Request::Detach { + session: "pinned-cancel-reparent".into(), + attachment: d1, + }, + &writes, + ) + .unwrap(); + // Free the writes slot; next retry must flush the withdrawal and forward a NEW attempt! + let _blocker = child_rx.try_recv().unwrap(); + let d2 = attach(&mut actor, 2); + // Keep 2 slots so enqueue_child_message can flush the withdrawal then send the fresh retry. + let (writes2, mut child_rx2) = mpsc::channel(4); + actor + .command( + Request::Send { + session: "pinned-cancel-reparent".into(), + attachment: d2.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "p-2", + "method": "session/prompt", + "params": {"sessionId": "pinned-cancel-reparent", "delivery": "steer", "idempotencyKey": "k-cancelled-bp", "prompt": [{"type":"text","text":"v2"}]} + }), + charge: None, + }, + &writes2, + ) + .unwrap(); + let first_write = child_rx2.try_recv().unwrap().message; + assert_eq!(first_write["method"], "$/cancel_request"); + assert_eq!(first_write["params"]["requestId"], orig_serial); + let second_write = child_rx2.try_recv().unwrap().message; + assert_eq!(second_write["method"], "session/prompt"); + let fresh_serial = second_write["id"].as_u64().unwrap(); + assert_ne!(fresh_serial, orig_serial); + + // Original cancelled reply (-32800) is dropped (orphaned) and does NOT fail d2! + actor.output(json!({"jsonrpc":"2.0","id":orig_serial,"error":{"code":-32800,"message":"Request cancelled"}})); + actor.output(json!({"jsonrpc":"2.0","id":fresh_serial,"result":{"messageId":"msg-fresh"}})); + let d2_last = actor.pinned.as_ref().unwrap().attachments[&d2] + .events + .back() + .unwrap() + .1 + .clone(); + assert_eq!(d2_last["id"], "p-2"); + assert_eq!(d2_last["result"]["messageId"], "msg-fresh"); + + // Case 2: Cancel succeeds immediately into child stdin, deliverer detaches before -32800 + // arrives -> retry still MUST forward as a fresh attempt (not re-parent onto cancelled orphan)! + let d3 = attach(&mut actor, 3); + actor + .command( + Request::Send { + session: "pinned-cancel-reparent".into(), + attachment: d3.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "p-3", + "method": "session/prompt", + "params": {"sessionId": "pinned-cancel-reparent", "delivery": "steer", "idempotencyKey": "k-cancelled-imm", "prompt": [{"type":"text","text":"v1"}]} + }), + charge: None, + }, + &writes2, + ) + .unwrap(); + let imm_serial = child_rx2.try_recv().unwrap().message["id"] + .as_u64() + .unwrap(); + actor + .command( + Request::Send { + session: "pinned-cancel-reparent".into(), + attachment: d3.clone(), + message: json!({"jsonrpc":"2.0","method":"$/cancel_request","params":{"requestId":"p-3"}}), + charge: None, + }, + &writes2, + ) + .unwrap(); + let cancel_msg = child_rx2.try_recv().unwrap().message; + assert_eq!(cancel_msg["method"], "$/cancel_request"); + actor + .command( + Request::Detach { + session: "pinned-cancel-reparent".into(), + attachment: d3, + }, + &writes2, + ) + .unwrap(); + let d4 = attach(&mut actor, 4); + actor + .command( + Request::Send { + session: "pinned-cancel-reparent".into(), + attachment: d4.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "p-4", + "method": "session/prompt", + "params": {"sessionId": "pinned-cancel-reparent", "delivery": "steer", "idempotencyKey": "k-cancelled-imm", "prompt": [{"type":"text","text":"v2"}]} + }), + charge: None, + }, + &writes2, + ) + .unwrap(); + let fresh_imm = child_rx2.try_recv().unwrap().message; + assert_eq!(fresh_imm["method"], "session/prompt"); + assert_ne!(fresh_imm["id"].as_u64().unwrap(), imm_serial); +} + +#[test] +fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_relay() { + let (writes, mut child_rx) = mpsc::channel(8); + + // 1. Event-count full complete journal (exactly MAX_QUEUE - 3 events, replay_complete == true) + // + pending relayed request -> ReplayMode::Start MUST succeed and deliver both full history + // AND the relayed request! + let mut actor = pinned_actor("pinned-start-count", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-start-count", "configOptions": []})); + let c1 = actor + .command( + Request::Attach { + session: "pinned-start-count".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-start-count"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + for i in 0..(MAX_QUEUE - 3) { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-start-count", "update": {"sessionUpdate": "notice", "message": format!("m-{i}")}} + })); + if i % 64 == 0 { + let cur = actor.pinned.as_ref().unwrap().attachments[&c1].next; + let _ = actor.command( + Request::Poll { + session: "pinned-start-count".into(), + attachment: c1.clone(), + cursor: cur, + }, + &writes, + ); + } + } + assert!(actor.replay_complete); + assert_eq!(actor.journal.len(), MAX_QUEUE - 3); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-start-count", + "method": "elicitation/create", + "params": {"sessionId": "pinned-start-count", "mode": "form", "message": "confirm"} + })) + .is_none() + ); + let relay_id = actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + + let c2 = actor + .command( + Request::Attach { + session: "pinned-start-count".into(), + replay: ReplayMode::Start, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-start-count","replayFrom":{"type":"start"}}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let c2_att = &actor.pinned.as_ref().unwrap().attachments[&c2]; + // Full journal (MAX_QUEUE - 3) + 2 snapshots + 1 startup result + 1 pending relay = MAX_QUEUE + 1. + assert_eq!(c2_att.events.len(), MAX_QUEUE + 1); + assert_eq!(c2_att.events[0].1["params"]["update"]["message"], "m-0"); + assert_eq!(c2_att.events.back().unwrap().1["id"], relay_id); + assert!( + actor.pinned.as_ref().unwrap().client_requests[&relay_id] + .targets + .contains(&c2) + ); + // Joiner can answer the pending relayed request! + actor + .command( + Request::Send { + session: "pinned-start-count".into(), + attachment: c2, + message: json!({"jsonrpc":"2.0","id":relay_id,"result":{"action":"accept","content":{"ok":true}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert_eq!( + child_rx.try_recv().unwrap().message["id"], + "ask-start-count" + ); + + // One more event evicts m-0 so history itself is incomplete -> ReplayMode::Start fails! + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-start-count", "update": {"sessionUpdate": "notice", "message": "evict-first"}} + })); + assert!(!actor.replay_complete); + let err = actor + .command( + Request::Attach { + session: "pinned-start-count".into(), + replay: ReplayMode::Start, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"pinned-start-count","replayFrom":{"type":"start"}}})), + }, + &writes, + ) + .unwrap_err(); + assert_eq!(err.2, "replay_unavailable"); + + // 2. Byte-bound full complete journal (journal + snapshots + result fits MAX_REPLAY, + // but adding a large pending relay exceeds MAX_REPLAY) -> ReplayMode::Start MUST succeed! + let mut byte_actor = pinned_actor("pinned-start-bytes", Duration::from_secs(60)); + byte_actor.session_result = + Some(json!({"sessionId": "pinned-start-bytes", "configOptions": []})); + let b1 = byte_actor + .command( + Request::Attach { + session: "pinned-start-bytes".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-start-bytes"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + // Fill ~8 MiB - 8 KiB (complete, no eviction, history+snapshots+result fits MAX_REPLAY). + let chunk_pad = "s".repeat(512 * 1024 - 1024); + for i in 0..16 { + byte_actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "pinned-start-bytes", "update": {"sessionUpdate": "notice", "message": format!("{i}:{chunk_pad}")}} + })); + let cur = byte_actor.pinned.as_ref().unwrap().attachments[&b1].next; + let _ = byte_actor.command( + Request::Poll { + session: "pinned-start-bytes".into(), + attachment: b1.clone(), + cursor: cur, + }, + &writes, + ); + } + assert!(byte_actor.replay_complete); + assert!(byte_actor.journal_bytes > MAX_REPLAY - 32 * 1024); + let large_prompt = "r".repeat(128 * 1024); + assert!( + byte_actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-start-bytes", + "method": "elicitation/create", + "params": {"sessionId": "pinned-start-bytes", "mode": "form", "message": large_prompt} + })) + .is_none() + ); + let byte_relay_id = byte_actor + .pinned + .as_ref() + .unwrap() + .client_requests + .keys() + .next() + .unwrap() + .clone(); + let b2 = byte_actor + .command( + Request::Attach { + session: "pinned-start-bytes".into(), + replay: ReplayMode::Start, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-start-bytes","replayFrom":{"type":"start"}}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let b2_att = &byte_actor.pinned.as_ref().unwrap().attachments[&b2]; + assert_eq!(b2_att.events.len(), 16 + 3 + 1); + assert_eq!(b2_att.events.back().unwrap().1["id"], byte_relay_id); +} From be65c9f17fb86f688076bdaa31d2328ee387350f Mon Sep 17 00:00:00 2001 From: daniel Date: Sat, 28 Nov 2026 23:55:45 +0000 Subject: [PATCH 05/19] feat(gateway): universalize client-request relay, replay cursors, and subagent steer --- docs/reference/gateway-protocol.md | 41 +- docs/user/gateway.md | 6 +- src/gateway.rs | 730 +++++++++++------------ src/gateway/http_server.rs | 137 +++-- src/gateway/pinned_tests.rs | 912 +++++++++++++++++++---------- src/gateway/tests.rs | 19 +- tests/gateway.rs | 161 ++++- 7 files changed, 1236 insertions(+), 770 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 0f57fe91..d872b6e4 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -41,11 +41,12 @@ that controller's pending requests with errors without detaching its other sessi | `initialize` | Establish ACP v2 capabilities once per connection. | | `session/new` | Create a child in an approved host project and acquire control. | | `session/list` | List resident and restorable sessions; optional exact `cwd` filtering, no pagination cursor. | -| `session/resume` | Acquire or replace control of a session; optional replay from `start` only. | +| `session/resume` | Acquire or replace control of a session; optional replay from `start`, `_kit_current_turn`, or `_kit_message`. | | `session/prompt` | Submit work to the resident child. Use a `delivery` mode advertised under `capabilities.session.prompt.delivery` to steer or queue explicitly. The response acknowledges insertion, not receipt. | | `_kit/session/update_mcp` | Add or update the current controller's client-owned MCP servers; see [session MCP configuration](../user/mcp.md#acp-session-mcp-configuration). | | `$/cancel_request` | Withdraw a held prompt on this connection by its JSON-RPC request ID. A successful withdrawal returns `-32800` on the original request. | | `kit/session/status` | Read current outstanding work; see [Read session settlement](#read-session-settlement). | +| `kit/subagent/steer` | Steer one live direct subagent by generation (`session_id`, `id`, `generation`, `prompt`; snake_case `session_id`). | | `session/close` | Close the resident session and its outstanding work; retain the transcript for explicit resume. The close response follows child cleanup. A cleanup error is reported, but does not reopen a partially closed child; resume is an explicit new restoration. | | `session/cancel` | Interrupt the current response; ordinary top-level sessions retain detached background jobs. This is distinct from closing a connection. | | `kit/background/cancel` | Request cancellation of one detached call using the existing Kit extension. | @@ -76,7 +77,7 @@ Initialize POST body (send `Authorization: Bearer TOKEN` and `Content-Type: appl The response is HTTP 200 JSON with `Acp-Connection-Id`. Its `result` contains `protocolVersion: 2`, `info.name: "kit-gateway"`, the running Kit version, and these capabilities: ```json -{"_meta":{"kit/session/status":{}},"session":{"prompt":{"image":{},"audio":{},"embeddedContext":{},"delivery":{"steer":{},"queue":{}}},"list":{},"mcp":{"stdio":{},"http":{},"_meta":{"kit/updateMcp":{"method":"_kit/session/update_mcp","upsert":true}}}}} +{"_meta":{"kit/session/status":{},"kit/subagent/steer":{}},"session":{"prompt":{"image":{},"audio":{},"embeddedContext":{},"delivery":{"steer":{},"queue":{}}},"list":{},"mcp":{"stdio":{},"http":{},"_meta":{"kit/updateMcp":{"method":"_kit/session/update_mcp","upsert":true}}}}} ``` Its `result._meta` explicitly identifies the experimental limits: @@ -155,9 +156,14 @@ HTTP POST bodies are limited to 1 MiB, including streamed bodies. Supervisor que ## Replay retained messages from native Kit -This extension applies to direct native Kit ACP v2 connections (`kit acp --protocol-version 2` or `kit serve --remote-acp`), and to `kit gateway --pinned-session` (see [Pinned-session mode](#pinned-session-mode)). Default single-controller gateway `session/resume` accepts replay from `start` only. +This extension applies to direct native Kit ACP v2 connections (`kit acp --protocol-version 2` or `kit serve --remote-acp`) and to `kit gateway` in both default single-controller mode and `--pinned-session` mode. -To rebuild a conversation after reconnecting, send `session/resume` with `replayFrom: {"type":"start"}`. To replay only a suffix, use Kit's inclusive cursor with a durable user-message ID previously received from that session: +To rebuild a conversation after reconnecting, send `session/resume` with: + +- omitted / `null`: no historical replay; delivers current config and state snapshots only (`historyAvailable: false`). (In default mode, `session/new` creates a fresh session and defaults to `{"type":"start"}`; in pinned mode, both `session/new` and `session/resume` default to no history.) +- `{"type":"start"}`: full retained journal from the beginning of the session (fails with `replay_unavailable` if earlier events were evicted or history plus snapshots exceed the replay limit; pending relayed client requests use reserved startup headroom so they never cause a complete journal to fail). +- `{"type":"_kit_current_turn"}`: replays from the start of the current (or most recent) turn so a mid-turn joiner or reconnecting client can render in-progress assistant output, even after older turns have been evicted from the journal. If the current turn itself outgrew the journal or must be trimmed to fit snapshots and pending relayed requests, the gateway replays from the oldest retained update that fits and sets `result._meta["kit/gateway"].replayTruncated = true`. When `replayTruncated` is `true`, earlier updates of the current turn were omitted and the first streamed assistant message or thought chunks replayed may be a partial tail rather than the start of that message. +- `{"type":"_kit_message","sessionId":"SESSION_ID","messageId":"MESSAGE_ID"}`: inclusive suffix replay from a durable user-message ID previously received from that session: ```json {"type":"_kit_message","sessionId":"SESSION_ID","messageId":"MESSAGE_ID"} @@ -167,30 +173,29 @@ Set this object as `replayFrom`; its `sessionId` must match the request's `sessi Only user messages with durable identities support partial replay. Agent-message and thought IDs cannot be used as boundaries because their content can accumulate across other messages in the same response; choose the preceding user message instead. Agent-message IDs, thought IDs, legacy offset-based replay IDs, tool-call IDs, unknown IDs, and IDs removed by compaction are rejected with JSON-RPC `-32602` (Invalid params), as are malformed or session-mismatched cursors. Retry explicitly with `{"type":"start"}` to rebuild from retained history; Kit does not silently fall back to a different position. +## Relayed agent-to-client requests + +In both default single-controller mode and `--pinned-session` mode, the gateway relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending per session) to live attached clients and routes client-to-agent JSON-RPC responses back to the child. + +- **Client capabilities forwarded to the child:** In default mode, the gateway filters the connecting client's `initialize.params.capabilities` to forward only relayable capabilities (`elicitation.form`) and strips host-only or unsupported capabilities (`auth`, `elicitation.url`, `fs`, `terminal`). A client connecting with `capabilities: {}` therefore does not advertise `elicitation.form` and does not receive an `ask_user` tool. In `--pinned-session` mode, because multiple heterogeneous clients share one child initialized once, the gateway always advertises `{"elicitation":{"form":{}}}` to the child. +- **Delivery and reconnects:** If no attachment is live when the request arrives, the gateway answers `-32601` immediately. Otherwise the request is sent to every live target (the active controller in default mode, or all live attachments in pinned mode) and re-offered right after startup to any client that attaches or replaces the controller while the request is pending. +- **Resolution and errors:** The first valid `result` from a target attachment wins and is forwarded to the child (buffered across transient child-stdin backpressure); any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target errored or detached mid-request, the gateway answers `-32601` to the child. Any other client error, or a target detaching without answering (such as a browser reloading or a controller being replaced), keeps the request pending until answered, cancelled by the agent, or expired. In default mode, if a new controller replaces one that had declared `elicitation.form` and does not implement the relayed method, it can decline with `-32601` or let the timeout expire. +- **Timeout and child exit (`--client-request-timeout`):** `--client-request-timeout ` (default `5m`, valid in both modes) is an absolute deadline measured from when the child request arrives. On expiry the gateway answers the child with `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. + ## Pinned-session mode (`--pinned-session`) -Start the gateway with `--pinned-session ` (and optionally `--client-request-timeout `, default `5m`) to serve one session to many simultaneous ACP HTTP attachments. Default single-controller gateway behavior is unchanged when `--pinned-session` is omitted. +Start the gateway with `--pinned-session ` (and optionally `--client-request-timeout `, default `5m`) to serve one session to many simultaneous ACP HTTP attachments. Everything in [Replay retained messages from native Kit](#replay-retained-messages-from-native-kit) and [Relayed agent-to-client requests](#relayed-agent-to-client-requests) works in both modes; the behaviors below are specific to `--pinned-session`: > [!WARNING] > **Security boundary:** All attachments connected to a pinned-session gateway share the same session. Every attached client receives all session updates, can submit prompts or cancel foreground work, can answer relayed agent-to-client requests, and can call `session/set_config_option` and `_kit/session/update_mcp`. Because `_kit/session/update_mcp` can register stdio MCP servers that execute commands in the host or sandbox, and the gateway authenticates only with its single bearer credential, place an authenticating proxy in front of `kit gateway --pinned-session` and filter methods for clients you do not trust with that level of control. When pinned mode is active: -- **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. The first client's `initialize` `info` is what the child receives. `session/list` returns only that single pinned session entry (even if `params.cwd` does not match, while rejecting any foreign `params.sessionId`), with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). -- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. +- **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. The first client's `initialize` `info` is what the child receives, and the gateway always advertises `{"elicitation":{"form":{}}}` to the child. `session/list` returns only that single pinned session entry (even if `params.cwd` does not match, while rejecting any foreign `params.sessionId`), with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). +- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project) and default absent/`null` `replayFrom` to no history (`historyAvailable: false`). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. - **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. - **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, its failed pending requests carry `error.data.reason = "queue_overflow"`, and its SSE stream closes cleanly without affecting other attachments or the active turn. -- **Fan-in, pending caps, and deduplication:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry (whose withdrawal has not been requested), the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). A re-parented retry's prompt body is not re-validated or used: the original held prompt is what gets inserted, matching the child's duplicate-key semantics. +- **Fan-in, pending caps, and orphan re-parenting:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry (whose withdrawal has not been requested), the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). A re-parented retry's prompt body is not re-validated or used: the original held prompt is what gets inserted, matching the child's duplicate-key semantics. - **Detach and cancel:** Disconnecting an attachment does not withdraw its already-submitted held prompts, so a deliverer may disconnect before insertion and retry with the same `idempotencyKey`. Sending an explicit `$/cancel_request` withdraws **every** held attempt sharing that `idempotencyKey` (the entire unclaimed idempotency group in the child), not only the sender's attempt: every live attachment waiting on that key receives a JSON-RPC `-32800` (`Request cancelled`) error (detached attempts are dropped), the prompt is not inserted, and a deliverer must treat it as not delivered. Any live attachment may send `session/cancel`. -- **Replay cursors for late joiners:** Both `session/new` and `session/resume` accept `replayFrom`: - - omitted / `null`: no history; delivers current config and state snapshots only (`historyAvailable: false`). This is the default for both `session/new` and `session/resume` in pinned mode (including cold restores whose transcript exceeds the replay buffer). - - `{"type":"start"}`: full retained journal from the beginning of the session (fails with `replay_unavailable` if earlier events were evicted). - - `{"type":"_kit_current_turn"}`: replays from the start of the current (or most recent) turn so a mid-turn joiner can render in-progress assistant output, even after older turns have been evicted from the journal. If the current turn itself outgrew the journal or must be trimmed to fit snapshots and pending relayed requests, the gateway replays from the oldest retained update that fits and sets `result._meta["kit/gateway"].replayTruncated = true`. When `replayTruncated` is `true`, earlier updates of the current turn were omitted and the first streamed assistant message or thought chunks replayed may be a partial tail rather than the start of that message. - - `{"type":"_kit_message","sessionId":"SESSION_ID","messageId":"MESSAGE_ID"}`: inclusive replay from a retained user message ID; rejects unknown, evicted, or session-mismatched cursors with JSON-RPC `-32602`. -- **Relayed agent-to-client requests:** In pinned mode the gateway advertises form elicitation (`{"elicitation":{"form":{}}}`) to the child and relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending) to every live attachment. Clients that attach while a request is still pending receive it immediately after their startup response and become eligible targets. - - If no attachment is live when the request arrives, the gateway answers `-32601` immediately. - - The first valid `result` from any target attachment wins and is forwarded to the child (buffered across transient child-stdin backpressure); every other target receives `$/cancel_request` for that relayed request ID. - - A `-32601` error from an attachment that does not implement the method removes only that target; if every target declined with `-32601` and no target errored or detached mid-request, the gateway answers `-32601` to the child. Any other client error, or a target detaching without answering (such as a browser reloading), keeps the request pending for remaining targets or late joiners until the timeout even if other targets reply `-32601`. - - Target detach does not cancel a pending request (so transient reconnects such as browser reloads can still answer). `--client-request-timeout` (default `5m`) is an absolute deadline measured from when the child request arrives. If the request is neither answered nor cancelled by the agent before the deadline, the gateway answers the child with `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. diff --git a/docs/user/gateway.md b/docs/user/gateway.md index 97e9cefa..019460f3 100644 --- a/docs/user/gateway.md +++ b/docs/user/gateway.md @@ -120,8 +120,8 @@ kit gateway --credential-file "$HOME/.kit-gateway-token" \ - **Shared session boundary:** All attachments share the pinned session: every connected client receives all live updates, can submit prompts or cancel work, can answer relayed interactive questions or permission requests, and can call `session/set_config_option` and `_kit/session/update_mcp` (which can register stdio MCP servers that run commands in the host or sandbox). Place an authenticating proxy in front of `kit gateway --pinned-session` when serving multiple users or services and filter methods for less-trusted clients; the gateway itself verifies only its single bearer token. - **Independent attachments:** Connecting a second client does not displace existing clients or withdraw their held prompts. Sending `session/close` detaches only the calling client without ending the session. If a slow client's output queue overflows, only that client is disconnected; other attachments and the active turn continue. -- **Late joiners and reconnects:** In pinned mode, both `session/new` and `session/resume` omit historical replay by default unless `replayFrom` is provided. Clients can attach with `replayFrom: {"type":"start"}` for full retained history, `{"type":"_kit_current_turn"}` to catch up on the current or most recent turn, or `{"type":"_kit_message","sessionId":"...","messageId":"..."}` to resume from a retained user message. -- **Interactive prompts (`--client-request-timeout`):** Unlike default single-controller mode (which does not support client-side ACP services), pinned-session mode relays agent-to-client requests (such as `ask_user` forms and permission requests) to all attached clients and to clients that attach while the request is pending; the first valid answer wins and the other clients receive a cancellation. If no client is attached when the request arrives, it fails immediately rather than blocking the turn. If clients detach mid-request, the request stays pending until answered, cancelled, or `--client-request-timeout` (default `5m`) expires. +- **Late joiners and default replay:** Unlike default mode (where `session/new` defaults to full replay), pinned mode omits historical replay by default on both `session/new` and `session/resume` unless `replayFrom` is provided. Both modes support `{"type":"start"}`, `{"type":"_kit_current_turn"}`, and `{"type":"_kit_message","sessionId":"...","messageId":"..."}`. +- **Multi-client interactive prompts:** Both modes relay agent-to-client requests (such as `ask_user` forms and permission requests) using `--client-request-timeout` (default `5m`). In pinned mode, the gateway always advertises form elicitation to the child and broadcasts pending requests to every attached client (and late joiners); the first valid answer wins and the other clients receive a cancellation. For exact wire behavior, cursors, and limits, see [Pinned-session mode](../reference/gateway-protocol.md#pinned-session-mode). @@ -150,6 +150,6 @@ See [Implement an ACP HTTP client](../reference/gateway-protocol.md#implement-an - There is no fixed resident-session count ceiling. Provision memory and process capacity for your workload. Detaching does not stop a session, even when it is idle; use `session/close` to end resident work. Listing or creating sessions reclaims completed entries without deleting durable transcripts. - Transport saturation can disconnect a client without canceling accepted work. HTTP frames are limited to 1 MiB; child output frames to 8 MiB. Oversized or malformed child output stops that child. There is no idle connection expiration or body-read deadline: abandoned transports can retain connection slots, and exhaustion may require restarting the gateway. See [Transport limits](../reference/gateway-protocol.md#transport-limits) before sizing an integration. These bounds are not a hard process-memory ceiling or denial-of-service protection. - Use `Ctrl+C` on the gateway host for graceful shutdown. Kit waits for child cleanup and exit, then forcibly stops a child if it exceeds the 10-second timeout. That fallback can leave a stale transcript lock requiring operator intervention. Hard process termination has operating-system-dependent cleanup behavior; arbitrary tool descendants are not a managed process group. -- Client-side ACP services, arbitrary extra directories, session-scoped HTTP/SSE MCP servers, browser callbacks, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. +- Interactive agent-to-client requests (such as `ask_user` forms and permission requests) are relayed to attached clients when the client advertises support (always advertised in pinned mode), with a configurable `--client-request-timeout` (default `5m`). Client-side filesystem and terminal services, arbitrary extra directories, legacy SSE MCP servers, browser callbacks, host-side terminal authentication, and arbitrary ACP methods are not supported. Files, tool execution, and provider authentication belong to the gateway host. The internal `gateway bridge` stdio command is a transport adapter for the bundled TUI, not a stable public protocol or general-purpose ACP proxy. The public transport is ACP HTTP at `/acp/v2`, implemented by the ACP SDK rather than a Kit-specific RPC protocol. diff --git a/src/gateway.rs b/src/gateway.rs index ae104274..aa715c9d 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -39,7 +39,7 @@ const MAX_PENDING_SHARED: usize = 128; const MAX_PENDING_PER_ATTACHMENT: usize = 32; const MAX_ORPHANED_PENDING: usize = 256; const MAX_WAITING_STARTUPS: usize = 64; -const MAX_PINNED_CLIENT_REQUESTS: usize = 64; +const MAX_CLIENT_REQUESTS: usize = 64; fn object(fields: [(&str, Value); N]) -> Value { Value::Object( @@ -134,10 +134,9 @@ impl Args { Arg::new("client_request_timeout") .long("client-request-timeout") .value_name("DURATION") - .requires("pinned_session") .value_parser(parse_duration) .help( - "Timeout for relayed agent-to-client requests in pinned mode (e.g. 30s, 5m; default 5m)", + "Timeout for relayed agent-to-client requests (e.g. 30s, 5m; default 5m)", ), ) .subcommand( @@ -330,9 +329,6 @@ fn parse_replay_mode( if cursor == &object([("type", "start".into())]) { return Ok(ReplayMode::Start); } - if !pinned { - return Err(Failure::bad("unsupported replay cursor")); - } let Some(map) = cursor.as_object() else { return Err(Failure::invalid_params("unsupported replay cursor")); }; @@ -473,18 +469,14 @@ impl IntoResponse for Failure { .into_response() } } -#[derive(Clone, Debug)] -struct PinnedConfig { - session_id: String, - client_request_timeout: Duration, -} struct Gateway { // Set only by shutdown while holding sessions; checked again under that // lock by create/restore so late HTTP requests cannot escape the drain. stopping: AtomicBool, token: BearerToken, roots: Vec, - pinned: Option, + pinned_session: Option, + client_request_timeout: Duration, // Writers: create/restore inserts a fully spawned actor; reclamation removes // completed actors; shutdown takes all entries. No guard spans await or child // teardown. Before insertion Child is kill-on-drop; afterwards actor owns it. @@ -641,13 +633,10 @@ pub async fn run(args: Args) -> Result<(), Box> { if roots.is_empty() { return Err("at least one --project directory is required".into()); } - let pinned = match args.pinned_session { + let pinned_session = match args.pinned_session { Some(session_id) => { crate::session::validate_id(&session_id)?; - Some(PinnedConfig { - session_id, - client_request_timeout: args.client_request_timeout, - }) + Some(session_id) } None => None, }; @@ -655,7 +644,8 @@ pub async fn run(args: Args) -> Result<(), Box> { stopping: AtomicBool::new(false), token: BearerToken::load(&path)?, roots, - pinned, + pinned_session, + client_request_timeout: args.client_request_timeout, sessions: Mutex::new(HashMap::new()), }); let listener = tokio::net::TcpListener::bind(args.listen).await?; @@ -755,7 +745,7 @@ async fn handle( gateway.reclaim_exited().await; let entries = gateway.sessions.lock().await.clone(); let roots = gateway.roots.clone(); - let pinned_id = gateway.pinned.as_ref().map(|p| p.session_id.clone()); + let pinned_id = gateway.pinned_session.clone(); let rows = tokio::task::spawn_blocking(move || { let mut rows = Vec::new(); for root in &roots { @@ -826,23 +816,18 @@ async fn handle( return Err(Failure::root("project is not registered")); } gateway.reclaim_exited().await; - let (id, check_workspace, pinned_timeout) = if let Some(pinned) = &gateway.pinned { + let (id, check_workspace, pinned) = if let Some(pinned_id) = &gateway.pinned_session { if let Some(requested) = &session - && requested != &pinned.session_id + && requested != pinned_id { return Err(Failure::bad(format!( - "gateway is pinned to session {}; other session ids are not allowed", - pinned.session_id + "gateway is pinned to session {pinned_id}; other session ids are not allowed" ))); } - ( - pinned.session_id.clone(), - true, - Some(pinned.client_request_timeout), - ) + (pinned_id.clone(), true, true) } else { let check = session.is_some(); - (session.unwrap_or_else(crate::session::new_id), check, None) + (session.unwrap_or_else(crate::session::new_id), check, false) }; let mut restore = false; if check_workspace { @@ -860,7 +845,7 @@ async fn handle( drop(entries); let belongs = crate::session::belongs_to_workspace(&root, &id).map_err(Failure::bad)?; - if pinned_timeout.is_none() && !belongs { + if !pinned && !belongs { return Err(Failure::root("session does not belong to this project")); } restore = belongs; @@ -874,8 +859,15 @@ async fn handle( return Err(Failure::root("session belongs to another project")); } } else { - let entry = spawn(&root, &id, restore, force, pinned_timeout) - .map_err(|error| Failure::unavailable(error.to_string()))?; + let entry = spawn( + &root, + &id, + restore, + force, + pinned, + gateway.client_request_timeout, + ) + .map_err(|error| Failure::unavailable(error.to_string()))?; let replaced = entries.insert(id.clone(), entry); drop(entries); drop(replaced); @@ -894,12 +886,11 @@ async fn handle( | Request::Detach { session, .. } => session, _ => return Err(Failure::bad("invalid operation")), }; - if let Some(pinned) = &gateway.pinned - && id != &pinned.session_id + if let Some(pinned_id) = &gateway.pinned_session + && id != pinned_id { return Err(Failure::bad(format!( - "gateway is pinned to session {}; other session ids are not allowed", - pinned.session_id + "gateway is pinned to session {pinned_id}; other session ids are not allowed" ))); } let entry = gateway @@ -1011,7 +1002,7 @@ struct WaitingStartup { request_id: Value, replay: ReplayMode, } -struct PreparedPinnedStartup { +struct PreparedStartup { messages: Vec, pending_requests: Vec<(String, Value)>, } @@ -1025,8 +1016,9 @@ struct PendingClientRequest { // True once any target failed with a non-(-32601) error; prevents treating // remaining -32601 declines as "no attachment supports this". had_client_error: bool, - // True once any target detached without answering (e.g. mid-reload); keeps - // the request pending until timeout even if remaining targets reply -32601. + // True once any target detached without answering (e.g. mid-reload or + // controller replacement); keeps the request pending until timeout even if + // remaining targets reply -32601. had_detached_target: bool, // Buffered child-bound JSON-RPC reply when child stdin is backpressured. resolved_reply: Option<(Value, Option>)>, @@ -1040,46 +1032,15 @@ struct PinnedState { attachments: HashMap, startup_driver: Option, waiting_startups: Vec, - client_request_timeout: Duration, - next_relay_id: u64, - client_requests: HashMap, } impl PinnedState { - fn new(client_request_timeout: Duration) -> Self { + fn new() -> Self { Self { attachments: HashMap::new(), startup_driver: None, waiting_startups: Vec::new(), - client_request_timeout, - next_relay_id: 0, - client_requests: HashMap::new(), } } - - fn pending_request_messages(&self) -> Vec<(String, Value)> { - let mut items: Vec<_> = self - .client_requests - .iter() - .filter(|(_, req)| req.resolved_reply.is_none()) - .map(|(relay_id, req)| { - ( - req.seq, - relay_id.clone(), - object([ - ("jsonrpc", "2.0".into()), - ("id", relay_id.clone().into()), - ("method", req.method.clone().into()), - ("params", req.params.clone()), - ]), - ) - }) - .collect(); - items.sort_by_key(|(seq, _, _)| *seq); - items - .into_iter() - .map(|(_, relay_id, message)| (relay_id, message)) - .collect() - } } struct Actor { id: String, @@ -1093,6 +1054,9 @@ struct Actor { committed_owner: Option, // Present only in `--pinned-session` mode; default single-controller mode leaves this None. pinned: Option, + client_request_timeout: Duration, + next_relay_id: u64, + client_requests: HashMap, serial: u64, pending: HashMap, initialized: Option, @@ -1107,7 +1071,13 @@ struct Actor { replay_complete: bool, } impl Actor { - fn new(id: String, root: PathBuf, restore: bool, pinned_timeout: Option) -> Self { + fn new( + id: String, + root: PathBuf, + restore: bool, + pinned: bool, + client_request_timeout: Duration, + ) -> Self { Self { id, root, @@ -1115,7 +1085,10 @@ impl Actor { closed: false, attachment: None, committed_owner: None, - pinned: pinned_timeout.map(PinnedState::new), + pinned: pinned.then(PinnedState::new), + client_request_timeout, + next_relay_id: 0, + client_requests: HashMap::new(), serial: 0, pending: HashMap::new(), initialized: None, @@ -1137,7 +1110,8 @@ fn spawn( id: &str, restore: bool, force: bool, - pinned_timeout: Option, + pinned: bool, + client_request_timeout: Duration, ) -> io::Result { let mut command = tokio::process::Command::new(std::env::current_exe()?); command @@ -1156,7 +1130,13 @@ fn spawn( } } let child = command.spawn()?; - let actor = Actor::new(id.to_owned(), root.to_owned(), restore, pinned_timeout); + let actor = Actor::new( + id.to_owned(), + root.to_owned(), + restore, + pinned, + client_request_timeout, + ); let (sender, receiver) = mpsc::channel(32); let (completion, stopped) = watch::channel(()); tokio::spawn(async move { @@ -1205,7 +1185,7 @@ impl Actor { None }; let next_deadline = if withdrawal.is_none() && ready_client_reply.is_none() { - self.next_pinned_deadline() + self.next_deadline() } else { None }; @@ -1331,7 +1311,7 @@ impl Actor { } } // Cancel any pending relayed requests for live targets when the child exits. - self.cancel_all_relayed_client_requests(); + let cancelled_relays = self.cancel_all_relayed_client_requests(); // EOF permits ACP's normal session cleanup to release transcript locks. // Abort the writer (including a stalled write) to close stdin, then drain // stdout concurrently with waiting: final notifications must not fill a @@ -1357,14 +1337,13 @@ impl Actor { continue; } let poll = matches!(command.request, Request::Poll { .. }); - let has_pinned_drain = poll + let has_exit_drain = poll && !stopping - && self.pinned.as_ref().is_some_and(|p| { - p.attachments.values().any(|a| !a.events.is_empty()) - }); + && cancelled_relays + && self.has_queued_attachment_events(); let result = if self.closed { self.command(command.request, &writes) - } else if has_pinned_drain { + } else if has_exit_drain { Ok(object([])) } else { Err(Failure::unavailable("child exited; restore its transcript")) @@ -1405,26 +1384,17 @@ impl Actor { } }; let _ = tokio::time::timeout(LEASE, drain).await; - } else if !stopping - && self - .pinned - .as_ref() - .is_some_and(|p| p.attachments.values().any(|a| !a.events.is_empty())) - { + } else if !stopping && cancelled_relays && self.has_queued_attachment_events() { // Briefly drain queued terminal notifications (such as $/cancel_request - // for relayed requests) before reporting child exit to pinned attachments. + // for relayed requests) before reporting child exit to live attachments. let drain = async { while let Some(command) = commands.recv().await { if matches!(command.request, Request::Shutdown) { break; } - let result = self.drain_exited_pinned(command.request); + let result = self.drain_exited(command.request); let _ = command.reply.send(result); - if !self - .pinned - .as_ref() - .is_some_and(|p| p.attachments.values().any(|a| !a.events.is_empty())) - { + if !self.has_queued_attachment_events() { break; } } @@ -1439,9 +1409,81 @@ impl Actor { let retired = self.attachment.take().map(|attachment| attachment.id); if let Some(id) = retired { self.mark_withdrawals(&id); + self.mark_target_detached(&id); } } } + fn live_attachment_ids(&self) -> Vec { + if let Some(pinned) = &self.pinned { + pinned + .attachments + .values() + .filter(|a| a.live && !a.closing && !a.overflowed) + .map(|a| a.id.clone()) + .collect() + } else { + self.attachment + .as_ref() + .filter(|a| a.live && a.touched.elapsed() < LEASE) + .map(|a| a.id.clone()) + .into_iter() + .collect() + } + } + fn has_queued_attachment_events(&self) -> bool { + if let Some(pinned) = &self.pinned { + pinned.attachments.values().any(|a| !a.events.is_empty()) + } else { + self.attachment + .as_ref() + .is_some_and(|a| !a.events.is_empty()) + } + } + fn push_to_attachment(&mut self, attachment_id: &str, message: Value) -> bool { + if self.pinned.is_some() { + return self.push_pinned_attachment(attachment_id, message); + } + if self + .attachment + .as_ref() + .is_some_and(|a| a.id == attachment_id) + { + self.emit(message); + return self.attachment.is_some(); + } + false + } + fn mark_target_detached(&mut self, attachment_id: &str) { + for request in self.client_requests.values_mut() { + if request.targets.remove(attachment_id) { + request.had_detached_target = true; + } + } + } + fn pending_request_messages(&self) -> Vec<(String, Value)> { + let mut items: Vec<_> = self + .client_requests + .iter() + .filter(|(_, req)| req.resolved_reply.is_none()) + .map(|(relay_id, req)| { + ( + req.seq, + relay_id.clone(), + object([ + ("jsonrpc", "2.0".into()), + ("id", relay_id.clone().into()), + ("method", req.method.clone().into()), + ("params", req.params.clone()), + ]), + ) + }) + .collect(); + items.sort_by_key(|(seq, _, _)| *seq); + items + .into_iter() + .map(|(_, relay_id, message)| (relay_id, message)) + .collect() + } fn push_pinned_attachment(&mut self, attachment_id: &str, message: Value) -> bool { let Some(pinned) = &mut self.pinned else { return false; @@ -1467,12 +1509,8 @@ impl Actor { pending.orphaned = true; } } + self.mark_target_detached(attachment_id); if let Some(pinned) = &mut self.pinned { - for request in pinned.client_requests.values_mut() { - if request.targets.remove(attachment_id) { - request.had_detached_target = true; - } - } pinned .waiting_startups .retain(|waiter| waiter.attachment != attachment_id); @@ -1509,7 +1547,7 @@ impl Actor { } } for waiter in failed_waiters { - self.push_pinned_startup_error( + self.push_startup_error( &waiter.attachment, waiter.request_id, object([ @@ -1538,34 +1576,46 @@ impl Actor { self.retire_pinned_attachment(&id, RetireMode::Remove); } } - fn drain_exited_pinned(&mut self, request: Request) -> ResultValue { + fn drain_exited(&mut self, request: Request) -> ResultValue { match request { Request::Detach { attachment, .. } => { if let Some(pinned) = &mut self.pinned { pinned.attachments.remove(&attachment); + } else if self.attachment.as_ref().is_some_and(|a| a.id == attachment) { + self.attachment = None; } Ok(object([])) } Request::Poll { attachment, cursor, .. } => { - let Some(pinned) = &mut self.pinned else { - return Err(Failure::unavailable("child exited; restore its transcript")); - }; - let Some(entry) = pinned.attachments.get_mut(&attachment) else { - return Err(Failure::unavailable("child exited; restore its transcript")); + let entry = if let Some(pinned) = &mut self.pinned { + let Some(entry) = pinned.attachments.get_mut(&attachment) else { + return Err(Failure::unavailable("child exited; restore its transcript")); + }; + if entry.overflowed { + pinned.attachments.remove(&attachment); + return Err(Failure( + StatusCode::CONFLICT, + "attachment queue overflowed; reconnect".into(), + "queue_overflow", + )); + } + entry + } else { + let Some(entry) = self.attachment.as_mut().filter(|a| a.id == attachment) + else { + return Err(Failure::unavailable("child exited; restore its transcript")); + }; + entry }; - if entry.overflowed { - pinned.attachments.remove(&attachment); - return Err(Failure( - StatusCode::CONFLICT, - "attachment queue overflowed; reconnect".into(), - "queue_overflow", - )); - } let (events, _) = entry.poll(cursor)?; if events.is_empty() { - pinned.attachments.remove(&attachment); + if let Some(pinned) = &mut self.pinned { + pinned.attachments.remove(&attachment); + } else { + self.attachment = None; + } return Err(Failure::unavailable("child exited; restore its transcript")); } Ok(object([ @@ -1576,12 +1626,28 @@ impl Actor { _ => Err(Failure::unavailable("child exited; restore its transcript")), } } - fn push_pinned_startup_error(&mut self, attachment_id: &str, request_id: Value, error: Value) { - if !self.pinned.as_ref().is_some_and(|p| { - p.attachments + fn active_attachment(&self, attachment_id: &str) -> Option<&Attachment> { + if let Some(pinned) = &self.pinned { + pinned + .attachments .get(attachment_id) - .is_some_and(|a| !a.closing && !a.overflowed) - }) { + .filter(|a| !a.closing && !a.overflowed) + } else { + self.attachment.as_ref().filter(|a| a.id == attachment_id) + } + } + fn active_attachment_mut(&mut self, attachment_id: &str) -> Option<&mut Attachment> { + if let Some(pinned) = &mut self.pinned { + pinned + .attachments + .get_mut(attachment_id) + .filter(|a| !a.closing && !a.overflowed) + } else { + self.attachment.as_mut().filter(|a| a.id == attachment_id) + } + } + fn push_startup_error(&mut self, attachment_id: &str, request_id: Value, error: Value) { + if self.active_attachment(attachment_id).is_none() { return; } let message = object([ @@ -1589,9 +1655,9 @@ impl Actor { ("id", request_id), ("error", error), ]); - if self.push_pinned_attachment(attachment_id, message) - && let Some(pinned) = &mut self.pinned - && let Some(attachment) = pinned.attachments.get_mut(attachment_id) + if self.push_to_attachment(attachment_id, message) + && self.pinned.is_some() + && let Some(attachment) = self.active_attachment_mut(attachment_id) { attachment.live = false; attachment.closing = true; @@ -1611,34 +1677,31 @@ impl Actor { seq } fn next_ready_client_reply(&self) -> Option { - let pinned = self.pinned.as_ref()?; let now = Instant::now(); - pinned - .client_requests + self.client_requests .iter() .filter(|(_, req)| req.resolved_reply.is_some() || req.deadline <= now) .min_by_key(|(_, req)| (req.resolved_reply.is_none(), req.deadline, req.seq)) .map(|(relay_id, _)| relay_id.clone()) } - fn next_pinned_deadline(&self) -> Option { - let pinned = self.pinned.as_ref()?; - let request_deadline = pinned + fn next_deadline(&self) -> Option { + let request_deadline = self .client_requests .values() .filter(|req| req.resolved_reply.is_none()) .map(|req| req.deadline) .min(); - let lease_deadline = pinned.attachments.values().map(|a| a.touched + LEASE).min(); + let lease_deadline = self + .pinned + .as_ref() + .and_then(|pinned| pinned.attachments.values().map(|a| a.touched + LEASE).min()); match (request_deadline, lease_deadline) { (Some(a), Some(b)) => Some(a.min(b)), (a, b) => a.or(b), } } fn flush_client_request_reply(&mut self, relay_id: &str, permit: mpsc::Permit<'_, ChildWrite>) { - let Some(pinned) = &mut self.pinned else { - return; - }; - let Some(req) = pinned.client_requests.remove(relay_id) else { + let Some(req) = self.client_requests.remove(relay_id) else { return; }; if let Some((message, charge)) = req.resolved_reply { @@ -1656,24 +1719,22 @@ impl Actor { }); let cancel = cancel_request_message(Value::String(relay_id.to_owned())); for target in req.targets { - self.push_pinned_attachment(&target, cancel.clone()); + self.push_to_attachment(&target, cancel.clone()); } } - fn cancel_all_relayed_client_requests(&mut self) { - let drained = if let Some(pinned) = &mut self.pinned { - std::mem::take(&mut pinned.client_requests) - } else { - return; - }; + fn cancel_all_relayed_client_requests(&mut self) -> bool { + let drained = std::mem::take(&mut self.client_requests); + let mut notified = false; for (relay_id, req) in drained { if req.resolved_reply.is_some() { continue; } let cancel = cancel_request_message(Value::String(relay_id)); for target in req.targets { - self.push_pinned_attachment(&target, cancel.clone()); + notified |= self.push_to_attachment(&target, cancel.clone()); } } + notified } fn relay_client_request( &mut self, @@ -1694,19 +1755,11 @@ impl Actor { ), ]) }; - let Some(pinned) = &mut self.pinned else { - return Some(no_services()); - }; - let live_targets: Vec = pinned - .attachments - .values() - .filter(|a| a.live && !a.closing && !a.overflowed) - .map(|a| a.id.clone()) - .collect(); + let live_targets = self.live_attachment_ids(); if live_targets.is_empty() { return Some(no_services()); } - if pinned.client_requests.len() >= MAX_PINNED_CLIENT_REQUESTS { + if self.client_requests.len() >= MAX_CLIENT_REQUESTS { return Some(object([ ("jsonrpc", "2.0".into()), ("id", child_id), @@ -1719,12 +1772,12 @@ impl Actor { ), ])); } - let Some(seq) = pinned.next_relay_id.checked_add(1) else { + let Some(seq) = self.next_relay_id.checked_add(1) else { return Some(no_services()); }; - pinned.next_relay_id = seq; + self.next_relay_id = seq; let relay_id = format!("kit-gw-req-{seq}"); - let timeout = pinned.client_request_timeout; + let timeout = self.client_request_timeout; let relayed = object([ ("jsonrpc", "2.0".into()), ("id", relay_id.clone().into()), @@ -1733,50 +1786,45 @@ impl Actor { ]); let mut delivered = HashSet::new(); for target in live_targets { - if self.push_pinned_attachment(&target, relayed.clone()) { + if self.push_to_attachment(&target, relayed.clone()) { delivered.insert(target); } } if delivered.is_empty() { return Some(no_services()); } - if let Some(pinned) = &mut self.pinned { - pinned.client_requests.insert( - relay_id, - PendingClientRequest { - seq, - child_id, - method, - params, - targets: delivered, - deadline: Instant::now() + timeout, - had_client_error: false, - had_detached_target: false, - resolved_reply: None, - }, - ); - } + self.client_requests.insert( + relay_id, + PendingClientRequest { + seq, + child_id, + method, + params, + targets: delivered, + deadline: Instant::now() + timeout, + had_client_error: false, + had_detached_target: false, + resolved_reply: None, + }, + ); None } fn cancel_relayed_client_request(&mut self, child_request_id: &Value) { - let Some(pinned) = &mut self.pinned else { - return; - }; - let Some(relay_id) = pinned.client_requests.iter().find_map(|(relay_id, req)| { + let Some(relay_id) = self.client_requests.iter().find_map(|(relay_id, req)| { (req.resolved_reply.is_none() && &req.child_id == child_request_id) .then(|| relay_id.clone()) }) else { return; }; - let Some(req) = pinned.client_requests.remove(&relay_id) else { + let Some(req) = self.client_requests.remove(&relay_id) else { return; }; let cancel = cancel_request_message(Value::String(relay_id)); for target in req.targets { - self.push_pinned_attachment(&target, cancel.clone()); + self.push_to_attachment(&target, cancel.clone()); } } - fn prepare_pinned_startup( + fn prepare_startup( &self, attachment_id: &str, existing_events: usize, @@ -1784,12 +1832,8 @@ impl Actor { result: Value, request_id: Value, replay: &ReplayMode, - ) -> Result { - let pending_requests = self - .pinned - .as_ref() - .map(PinnedState::pending_request_messages) - .unwrap_or_default(); + ) -> Result { + let pending_requests = self.pending_request_messages(); let pending_bytes: usize = pending_requests .iter() .map(|(_, m)| m.to_string().len()) @@ -1818,44 +1862,28 @@ impl Actor { "session snapshot exceeds the gateway limit", )); } - Ok(PreparedPinnedStartup { + Ok(PreparedStartup { messages, pending_requests, }) } - fn apply_pinned_startup(&mut self, attachment_id: &str, prepared: PreparedPinnedStartup) { + fn apply_startup(&mut self, attachment_id: &str, prepared: PreparedStartup) { for update in prepared.messages { - self.push_pinned_attachment(attachment_id, update); + self.push_to_attachment(attachment_id, update); } for (relay_id, req_msg) in prepared.pending_requests { - let delivered = if let Some(pinned) = &mut self.pinned - && let Some(attachment) = pinned.attachments.get_mut(attachment_id) - && !attachment.overflowed - && !attachment.closing - { - // Relayed requests are already bounded by MAX_PINNED_CLIENT_REQUESTS; - // reserve startup headroom so a complete full journal never fails on them. + if let Some(attachment) = self.active_attachment_mut(attachment_id) { attachment.push_reserved(req_msg); - true - } else { - false - }; - if delivered - && let Some(pinned) = &mut self.pinned - && let Some(req) = pinned.client_requests.get_mut(&relay_id) - { - req.targets.insert(attachment_id.to_owned()); + if let Some(req) = self.client_requests.get_mut(&relay_id) { + req.targets.insert(attachment_id.to_owned()); + } } } - if let Some(pinned) = &mut self.pinned - && let Some(attachment) = pinned.attachments.get_mut(attachment_id) - && !attachment.overflowed - && !attachment.closing - { + if let Some(attachment) = self.active_attachment_mut(attachment_id) { attachment.live = true; } } - fn deliver_pinned_startup( + fn deliver_startup( &mut self, attachment_id: &str, result: Value, @@ -1863,15 +1891,12 @@ impl Actor { replay: &ReplayMode, ) { let Some((existing_events, existing_bytes)) = self - .pinned - .as_ref() - .and_then(|p| p.attachments.get(attachment_id)) - .filter(|a| !a.closing && !a.overflowed) + .active_attachment(attachment_id) .map(|a| (a.events.len(), a.bytes)) else { return; }; - match self.prepare_pinned_startup( + match self.prepare_startup( attachment_id, existing_events, existing_bytes, @@ -1880,10 +1905,10 @@ impl Actor { replay, ) { Ok(prepared) => { - self.apply_pinned_startup(attachment_id, prepared); + self.apply_startup(attachment_id, prepared); } Err(error) => { - self.push_pinned_startup_error( + self.push_startup_error( attachment_id, request_id, object([ @@ -1898,24 +1923,11 @@ impl Actor { fn output(&mut self, mut message: Value) -> Option { if message.get("method").is_some() { if let Some(id) = message.get("id").cloned() { - if self.pinned.is_some() { - let method = message["method"].as_str().unwrap_or_default().to_owned(); - let params = message.get("params").cloned().unwrap_or_else(|| object([])); - return self.relay_client_request(id, method, params); - } - return Some(object([ - ("jsonrpc", "2.0".into()), - ("id", id), - ( - "error", - object([ - ("code", (-32601).into()), - ("message", "gateway has no client-side services".into()), - ]), - ), - ])); + let method = message["method"].as_str().unwrap_or_default().to_owned(); + let params = message.get("params").cloned().unwrap_or_else(|| object([])); + return self.relay_client_request(id, method, params); } - if self.pinned.is_some() && message["method"] == "$/cancel_request" { + if message["method"] == "$/cancel_request" { if let Some(req_id) = message["params"].get("requestId").cloned() { self.cancel_relayed_client_request(&req_id); } @@ -2011,7 +2023,7 @@ impl Actor { ); if let Some(result) = message.get("result").cloned() { for (att, req_id, replay) in recipients { - self.deliver_pinned_startup(&att, result.clone(), req_id, &replay); + self.deliver_startup(&att, result.clone(), req_id, &replay); } } else { let error_obj = message.get("error").cloned().unwrap_or_else(|| { @@ -2021,7 +2033,7 @@ impl Actor { ]) }); for (att, req_id, _) in recipients { - self.push_pinned_startup_error(&att, req_id, error_obj.clone()); + self.push_startup_error(&att, req_id, error_obj.clone()); } } } else if !pending.orphaned @@ -2041,71 +2053,18 @@ impl Actor { .as_ref() .is_some_and(|a| a.id == pending.attachment) { - message["id"] = pending.original; if matches!(pending.method.as_str(), "session/new" | "session/resume") - && message.get("result").is_some() + && let Some(result) = message.get("result").cloned() { - let messages = self.startup_messages( - message["result"].clone(), - message["id"].clone(), - &pending.replay, + self.deliver_startup( &pending.attachment, - 0, - 0, + result, + pending.original, + &pending.replay, ); - match messages { - Ok(messages) => { - // Include any unpolled initialization response in admission. - let fits = self.attachment.as_ref().is_some_and(|a| { - a.events.len() + messages.len() <= MAX_QUEUE - && a.bytes - + messages - .iter() - .map(|m| m.to_string().len()) - .sum::() - <= MAX_REPLAY - }); - if fits { - for update in messages { - self.emit(update); - } - if let Some(attachment) = &mut self.attachment { - attachment.live = true; - } - return None; - } - message = object([ - ("jsonrpc", "2.0".into()), - ("id", message["id"].clone()), - ( - "error", - object([ - ("code", (-32000).into()), - ( - "message", - "session snapshot exceeds the gateway limit".into(), - ), - ("data", Failure::replay("snapshot overflow").data()), - ]), - ), - ]); - } - Err(error) => { - message = object([ - ("jsonrpc", "2.0".into()), - ("id", message["id"].clone()), - ( - "error", - object([ - ("code", error.jsonrpc_code().into()), - ("data", error.data()), - ("message", error.1.into()), - ]), - ), - ]); - } - } + return None; } + message["id"] = pending.original; self.emit(message); } } @@ -2295,7 +2254,9 @@ impl Actor { if method == "_kit/session/update_mcp" && message["params"]["sessionId"] != self.id { return Err(Failure::bad("ACP session does not match gateway session")); } - if method == "kit/background/cancel" && message["params"]["session_id"] != self.id { + if matches!(method, "kit/background/cancel" | "kit/subagent/steer") + && message["params"]["session_id"] != self.id + { return Err(Failure::bad("ACP session does not match gateway session")); } Ok(()) @@ -2411,12 +2372,8 @@ impl Actor { } } if method == "initialize" { - // Advertise form elicitation capability to the child ONLY in pinned mode. - message["params"]["capabilities"] = if pinned { - object([("elicitation", object([("form", object([]))]))]) - } else { - object([]) - }; + message["params"]["capabilities"] = + forwarded_client_capabilities(message["params"].get("capabilities"), pinned); } let pending = if let Some(original) = original { self.serial = self @@ -2604,30 +2561,23 @@ impl Actor { )); } let id = crate::session::new_id(); - let mut attachment = Attachment::new(id.clone()); - let started = if let (Some(startup), Some(result)) = - (startup, self.session_result.clone()) - { - let request_id = startup - .get("id") - .cloned() - .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - for message in self.startup_messages(result, request_id, &replay_mode, &id, 0, 0)? { - if !attachment.push(message) { - return Err(Failure::replay( - "session snapshot exceeds the gateway limit", - )); - } - } - attachment.live = true; - true - } else { - false - }; + let attachment = Attachment::new(id.clone()); + let prepared = + if let (Some(startup), Some(result)) = (startup, self.session_result.clone()) { + let request_id = startup + .get("id") + .cloned() + .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + Some(self.prepare_startup(&id, 0, 0, result, request_id, &replay_mode)?) + } else { + None + }; + let started = prepared.is_some(); // No fallible work after the ownership commit. The previous controller // survives every replay/snapshot preparation failure. if let Some(previous) = self.attachment.take() { self.mark_withdrawals(&previous.id); + self.mark_target_detached(&previous.id); self.flush_withdrawals(writes); } self.committed_owner = Some(CommittedOwner { @@ -2636,6 +2586,9 @@ impl Actor { recovery_attempt, }); self.attachment = Some(attachment); + if let Some(prepared) = prepared { + self.apply_startup(&id, prepared); + } return Ok(object([ ("started", started.into()), ("attachment", id.into()), @@ -2664,6 +2617,7 @@ impl Actor { Request::Detach { attachment, .. } => { self.attachment = None; self.mark_withdrawals(&attachment); + self.mark_target_detached(&attachment); self.flush_withdrawals(writes); Ok(object([])) } @@ -2680,6 +2634,12 @@ impl Actor { charge, .. } => { + if !message.is_object() || message["jsonrpc"] != "2.0" { + return Err(Failure::bad("invalid ACP message")); + } + if is_client_response(&message) { + return self.handle_client_response(&attachment, message, charge, writes); + } let method = message["method"] .as_str() .ok_or_else(|| Failure::bad("ACP method required"))? @@ -2704,20 +2664,22 @@ impl Actor { return Err(Failure::bad("session close requires a request id")); } let startup = matches!(method.as_str(), "session/new" | "session/resume"); - if startup { + let replay = if startup { if original.is_none() { return Err(Failure::bad("session startup requires a request id")); } if self.attachment.as_ref().is_some_and(|a| a.live) { return Err(Failure::conflict("attachment already opened its session")); } - if let Some(cursor) = message["params"].get("replayFrom") - && !cursor.is_null() - && cursor != &object([("type", "start".into())]) - { - return Err(Failure::bad("unsupported replay cursor")); - } - } + parse_replay_mode( + message["params"].get("replayFrom"), + &self.id, + false, + method == "session/new", + )? + } else { + ReplayMode::None + }; if let Some(id) = &original && self .pending @@ -2726,13 +2688,6 @@ impl Actor { { return Err(Failure::conflict("duplicate pending request id")); } - let replay = if method == "session/new" - || message["params"]["replayFrom"] == object([("type", "start".into())]) - { - ReplayMode::Start - } else { - ReplayMode::None - }; if startup && matches!(replay, ReplayMode::Start) && !self.replay_complete { return Err(Failure::replay("full live replay is unavailable")); } @@ -2749,25 +2704,19 @@ impl Actor { let Some(id) = original else { return Err(Failure::bad("session startup requires a request id")); }; - let messages = - self.startup_messages(result, id, &replay, &attachment, 0, 0)?; - let fits = self.attachment.as_ref().is_some_and(|a| { - a.events.len() + messages.len() <= MAX_QUEUE - && a.bytes - + messages.iter().map(|m| m.to_string().len()).sum::() - <= MAX_REPLAY - }); - if !fits { - return Err(Failure::replay( - "session snapshot exceeds the gateway limit", - )); - } - for update in messages { - self.emit(update); - } - if let Some(attachment) = &mut self.attachment { - attachment.live = true; - } + let (existing_events, existing_bytes) = self + .attachment + .as_ref() + .map_or((0, 0), |a| (a.events.len(), a.bytes)); + let prepared = self.prepare_startup( + &attachment, + existing_events, + existing_bytes, + result, + id, + &replay, + )?; + self.apply_startup(&attachment, prepared); } else if let Some(id) = original { self.emit(object([ ("jsonrpc", "2.0".into()), @@ -2822,12 +2771,11 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - let prepared = - self.prepare_pinned_startup(&id, 0, 0, result, request_id, &replay_mode)?; + let prepared = self.prepare_startup(&id, 0, 0, result, request_id, &replay_mode)?; if let Some(pinned) = &mut self.pinned { pinned.attachments.insert(id.clone(), attachment); } - self.apply_pinned_startup(&id, prepared); + self.apply_startup(&id, prepared); true } else if let Some(startup_msg) = startup && startup_in_flight @@ -2948,16 +2896,8 @@ impl Actor { return Err(Failure::bad("invalid ACP message")); } // Client-to-agent JSON-RPC response for a relayed request. - if message.get("method").is_none() - && (message.get("result").is_some_and(|v| !v.is_null()) - || message.get("error").is_some_and(Value::is_object)) - { - return self.handle_pinned_client_response( - &attachment, - message, - charge, - writes, - ); + if is_client_response(&message) { + return self.handle_client_response(&attachment, message, charge, writes); } let method = message["method"] .as_str() @@ -3086,7 +3026,7 @@ impl Actor { } } - fn handle_pinned_client_response( + fn handle_client_response( &mut self, attachment: &str, message: Value, @@ -3096,12 +3036,12 @@ impl Actor { let Some(relay_id) = message["id"].as_str().map(str::to_owned) else { return Ok(object([])); }; - let Some((method, is_target)) = self.pinned.as_ref().and_then(|p| { - p.client_requests - .get(&relay_id) - .filter(|req| req.resolved_reply.is_none()) - .map(|req| (req.method.clone(), req.targets.contains(attachment))) - }) else { + let Some((method, is_target)) = self + .client_requests + .get(&relay_id) + .filter(|req| req.resolved_reply.is_none()) + .map(|req| (req.method.clone(), req.targets.contains(attachment))) + else { // Already resolved, cancelled, or expired; ignore late duplicate race. return Ok(object([])); }; @@ -3111,9 +3051,7 @@ impl Actor { if let Some(error) = message.get("error").filter(|v| v.is_object()) { let is_unsupported = error["code"].as_i64() == Some(-32601); let mut should_decline = None; - if let Some(pinned) = &mut self.pinned - && let Some(req) = pinned.client_requests.get_mut(&relay_id) - { + if let Some(req) = self.client_requests.get_mut(&relay_id) { req.targets.remove(attachment); if !is_unsupported { // Client-side failure: drop only this target and keep pending @@ -3152,9 +3090,7 @@ impl Actor { return Err(Failure::bad("invalid response for relayed client request")); } let mut other_targets = Vec::new(); - if let Some(pinned) = &mut self.pinned - && let Some(req) = pinned.client_requests.get_mut(&relay_id) - { + if let Some(req) = self.client_requests.get_mut(&relay_id) { let reply = object([ ("jsonrpc", "2.0".into()), ("id", req.child_id.clone()), @@ -3171,7 +3107,7 @@ impl Actor { } let cancel = cancel_request_message(Value::String(relay_id)); for target in other_targets { - self.push_pinned_attachment(&target, cancel.clone()); + self.push_to_attachment(&target, cancel.clone()); } Ok(object([])) } @@ -3185,6 +3121,29 @@ fn has_nonempty_mcp_servers(message: &Value) -> bool { .is_some_and(|servers| !servers.is_null() && servers != &Value::Array(Vec::new())) } +fn is_client_response(message: &Value) -> bool { + message.get("method").is_none() + && (message.get("result").is_some_and(|v| !v.is_null()) + || message.get("error").is_some_and(Value::is_object)) +} + +fn forwarded_client_capabilities(client_caps: Option<&Value>, pinned: bool) -> Value { + // In pinned mode, many heterogeneous clients share one child initialized once, + // so always advertise form elicitation (relay handles declines). In default + // mode, forward only relayable capabilities declared by the connecting client + // (stripping host-only auth, browser-callback url elicitation, fs, terminal). + let advertise_form = pinned + || client_caps + .and_then(|caps| caps.get("elicitation")) + .and_then(|elicitation| elicitation.get("form")) + .is_some_and(Value::is_object); + if advertise_form { + object([("elicitation", object([("form", object([]))]))]) + } else { + object([]) + } +} + fn is_supported_acp_method(method: &str, allow_close: bool) -> bool { matches!( method, @@ -3194,6 +3153,7 @@ fn is_supported_acp_method(method: &str, allow_close: bool) -> bool { | "session/prompt" | "session/cancel" | "kit/background/cancel" + | "kit/subagent/steer" | "kit/session/status" | "session/set_config_option" | "_kit/session/update_mcp" diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index b5d6d4f7..f3cd3ef7 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -14,6 +14,7 @@ pub(super) struct Connection { gateway: Arc, initialize: Option<(Value, Arc)>, controls: HashMap, + relay_routes: HashMap, closing_connection: bool, } @@ -116,6 +117,7 @@ impl Connection { gateway, initialize: None, controls: HashMap::new(), + relay_routes: HashMap::new(), closing_connection: false, } } @@ -150,7 +152,10 @@ impl Connection { .delivery = Some(wire::PromptDeliveryCapabilities::new(true, true)); let mut capabilities = serde_json::to_value(capabilities) .map_err(|e| Failure::unavailable(e.to_string()))?; - capabilities["_meta"] = object([("kit/session/status", object([]))]); + capabilities["_meta"] = object([ + ("kit/session/status", object([])), + ("kit/subagent/steer", object([])), + ]); if let Some(session) = capabilities["session"].as_object_mut() { for name in ["delete", "fork"] { session.remove(name); @@ -184,10 +189,10 @@ impl Connection { ("liveReplayLimitBytes", MAX_REPLAY.into()), ("liveReplayLimitEvents", (MAX_QUEUE - 3).into()), ]); - if let Some(pinned) = &self.gateway.pinned + if let Some(pinned_id) = &self.gateway.pinned_session && let Some(meta) = gateway_meta.as_object_mut() { - meta.insert("pinnedSession".into(), pinned.session_id.clone().into()); + meta.insert("pinnedSession".into(), pinned_id.clone().into()); } return Ok(Some(object([ ("protocolVersion", 2.into()), @@ -248,13 +253,12 @@ impl Connection { { return Err(Failure::bad("unsupported session list cursor")); } - if let Some(pinned) = &self.gateway.pinned + if let Some(pinned_id) = &self.gateway.pinned_session && let Some(requested) = message["params"].get("sessionId").and_then(Value::as_str) - && requested != pinned.session_id + && requested != pinned_id { return Err(Failure::bad(format!( - "gateway is pinned to session {}; other session ids are not allowed", - pinned.session_id + "gateway is pinned to session {pinned_id}; other session ids are not allowed" ))); } let result = self.operation(Request::List).await?; @@ -265,7 +269,8 @@ impl Connection { let rows: Vec<_> = rows .iter() .filter(|row| { - self.gateway.pinned.is_some() || cwd.is_none_or(|cwd| row["root"] == cwd) + self.gateway.pinned_session.is_some() + || cwd.is_none_or(|cwd| row["root"] == cwd) }) .map(|row| { object([ @@ -286,33 +291,31 @@ impl Connection { } if matches!(method.as_str(), "session/new" | "session/resume") { let resume = method == "session/resume"; - let pinned = self.gateway.pinned.as_ref(); + let pinned = self.gateway.pinned_session.as_deref(); let id = if resume { let requested = message["params"]["sessionId"] .as_str() .ok_or_else(|| Failure::bad("sessionId required"))? .to_owned(); - if let Some(pinned) = pinned - && requested != pinned.session_id + if let Some(pinned_id) = pinned + && requested != pinned_id { return Err(Failure::bad(format!( - "gateway is pinned to session {}; other session ids are not allowed", - pinned.session_id + "gateway is pinned to session {pinned_id}; other session ids are not allowed" ))); } Some(requested) } else { - if let Some(pinned) = pinned + if let Some(pinned_id) = pinned && let Some(requested) = message["params"].get("sessionId").and_then(Value::as_str) - && requested != pinned.session_id + && requested != pinned_id { return Err(Failure::bad(format!( - "gateway is pinned to session {}; other session ids are not allowed", - pinned.session_id + "gateway is pinned to session {pinned_id}; other session ids are not allowed" ))); } - pinned.map(|pinned| pinned.session_id.clone()) + pinned.map(str::to_owned) }; if id.as_ref().is_some_and(|id| self.controls.contains_key(id)) { return Err(Failure::conflict("connection already controls session")); @@ -355,16 +358,31 @@ impl Connection { self.gateway.roots[0].clone() } None if resume => { - let catalog = self.operation(Request::List).await?; - catalog["sessions"] - .as_array() - .and_then(|rows| { - rows.iter() - .find(|row| row["session"].as_str() == id.as_deref()) - }) - .and_then(|row| row["root"].as_str()) - .map(PathBuf::from) - .ok_or_else(|| Failure::bad("session not found in approved projects"))? + let resident_root = if let Some(session_id) = id.as_deref() { + self.gateway + .sessions + .lock() + .await + .get(session_id) + .filter(|e| !e.sender.is_closed()) + .map(|e| e.root.clone()) + } else { + None + }; + if let Some(root) = resident_root { + root + } else { + let catalog = self.operation(Request::List).await?; + catalog["sessions"] + .as_array() + .and_then(|rows| { + rows.iter() + .find(|row| row["session"].as_str() == id.as_deref()) + }) + .and_then(|row| row["root"].as_str()) + .map(PathBuf::from) + .ok_or_else(|| Failure::bad("session not found in approved projects"))? + } } None => return Err(Failure::bad("cwd required")), }; @@ -456,8 +474,11 @@ impl Connection { self.controls.insert(session, control); return Ok(None); } - // Kit's existing background extension uses snake_case on the wire. - let session_field = if method == "kit/background/cancel" { + // Kit's existing background and subagent-steer extensions use snake_case on the wire. + let session_field = if matches!( + method.as_str(), + "kit/background/cancel" | "kit/subagent/steer" + ) { "session_id" } else { "sessionId" @@ -465,12 +486,11 @@ impl Connection { let id = message["params"][session_field] .as_str() .ok_or_else(|| Failure::bad(format!("{session_field} required")))?; - if let Some(pinned) = &self.gateway.pinned - && id != pinned.session_id + if let Some(pinned_id) = &self.gateway.pinned_session + && id != pinned_id { return Err(Failure::bad(format!( - "gateway is pinned to session {}; other session ids are not allowed", - pinned.session_id + "gateway is pinned to session {pinned_id}; other session ids are not allowed" ))); } let control = self @@ -516,6 +536,15 @@ impl Connection { match control.poll().await { Ok(messages) => { for message in messages { + if message.get("method").is_some() + && let Some(relay_id) = message.get("id").and_then(Value::as_str) + { + self.relay_routes.insert(relay_id.to_owned(), id.clone()); + } else if message["method"] == "$/cancel_request" + && let Some(relay_id) = message["params"]["requestId"].as_str() + { + self.relay_routes.remove(relay_id); + } send(channel, message, deadline).await?; } if control.closed { @@ -551,7 +580,7 @@ impl Connection { for (id, error) in failed { if let Some(mut control) = self.controls.remove(&id) { let overflowed_pinned = - self.gateway.pinned.is_some() && error.2 == "queue_overflow"; + self.gateway.pinned_session.is_some() && error.2 == "queue_overflow"; send( channel, object([ @@ -598,6 +627,8 @@ impl Connection { } } } + self.relay_routes + .retain(|_, session_id| self.controls.contains_key(session_id)); Ok(()) } @@ -624,17 +655,16 @@ impl Connection { _ => return Err(channel.tx.fail("unsupported ACP frame")), }; let message = serde_json::to_value(message).map_err(sdk_error)?; - // In pinned mode, forward client-to-agent JSON-RPC responses for relayed requests. - if self.gateway.pinned.is_some() - && message.get("method").is_none() - && (message.get("result").is_some_and(|v| !v.is_null()) - || message.get("error").is_some_and(Value::is_object)) - { - if let Some(control) = self - .gateway - .pinned - .as_ref() - .and_then(|pinned| self.controls.get_mut(&pinned.session_id)) + // Forward client-to-agent JSON-RPC responses for relayed requests in both modes. + if is_client_response(&message) { + let target_session = message + .get("id") + .and_then(Value::as_str) + .and_then(|relay_id| self.relay_routes.remove(relay_id)) + .or_else(|| self.gateway.pinned_session.clone()); + if let Some(control) = target_session + .as_deref() + .and_then(|session_id| self.controls.get_mut(session_id)) { let _ = control.send(message, Arc::clone(&charged_frame)).await; } @@ -775,7 +805,8 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), - pinned: None, + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, sessions: Mutex::new(HashMap::new()), }); let connection = Connection::new(gateway); @@ -884,7 +915,8 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), - pinned: None, + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, sessions: Mutex::new(HashMap::new()), }); let mut connection = Connection::new(gateway); @@ -1017,7 +1049,8 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), - pinned: None, + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, sessions: Mutex::new(HashMap::new()), }); let (sender, mut receiver) = mpsc::channel::(2); @@ -1080,7 +1113,8 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), - pinned: None, + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, sessions: Mutex::new(HashMap::new()), }); let mut connection = Connection::new(gateway); @@ -1193,7 +1227,8 @@ mod tests { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: Vec::new(), - pinned: None, + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, sessions: Mutex::new(HashMap::new()), }); let (mut channel, mut peer) = BoundedChannel::duplex(ChannelLimits::default()).unwrap(); diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 3518864a..109418a1 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -25,6 +25,14 @@ impl Drop for PinnedHarness { impl PinnedHarness { async fn new(session_id: &str, client_request_timeout: Duration) -> Self { + Self::with_mode(Some(session_id.to_owned()), client_request_timeout).await + } + + async fn default_mode(client_request_timeout: Duration) -> Self { + Self::with_mode(None, client_request_timeout).await + } + + async fn with_mode(pinned_session: Option, client_request_timeout: Duration) -> Self { let directory = tempfile::tempdir().unwrap(); let token = directory.path().join("token"); std::fs::write(&token, "pinned-secret").unwrap(); @@ -32,10 +40,8 @@ impl PinnedHarness { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: vec![directory.path().canonicalize().unwrap()], - pinned: Some(PinnedConfig { - session_id: session_id.to_owned(), - client_request_timeout, - }), + pinned_session, + client_request_timeout, sessions: Mutex::new(HashMap::new()), }); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -63,17 +69,12 @@ impl PinnedHarness { .kill_on_drop(true) .spawn() .unwrap(); - let timeout = self - .gateway - .pinned - .as_ref() - .map(|p| p.client_request_timeout) - .unwrap_or(DEFAULT_CLIENT_REQUEST_TIMEOUT); let actor = Actor::new( id.to_owned(), self.gateway.roots[0].clone(), false, - Some(timeout), + self.gateway.pinned_session.is_some(), + self.gateway.client_request_timeout, ); let (sender, receiver) = mpsc::channel(32); let (completion, stopped) = watch::channel(()); @@ -92,6 +93,10 @@ impl PinnedHarness { } async fn connect(&self, name: &str) -> HttpConn { + self.connect_with_capabilities(name, json!({})).await + } + + async fn connect_with_capabilities(&self, name: &str, capabilities: Value) -> HttpConn { let response = self .client .post(&self.url) @@ -103,7 +108,7 @@ impl PinnedHarness { "params": { "protocolVersion": 2, "info": { "name": name, "version": "1" }, - "capabilities": {} + "capabilities": capabilities } })) .send() @@ -234,7 +239,11 @@ impl HttpConn { } fn pinned_actor(id: &str, timeout: Duration) -> Actor { - Actor::new(id.into(), PathBuf::from("/approved"), false, Some(timeout)) + Actor::new(id.into(), PathBuf::from("/approved"), false, true, timeout) +} + +fn default_actor(id: &str, timeout: Duration) -> Actor { + Actor::new(id.into(), PathBuf::from("/approved"), false, false, timeout) } #[test] @@ -261,11 +270,15 @@ fn pinned_cli_flags_and_duration_parsing() { DEFAULT_CLIENT_REQUEST_TIMEOUT ); - // --client-request-timeout requires --pinned-session - assert!( - Args::command() - .try_get_matches_from(["gateway", "--client-request-timeout", "30s"]) - .is_err() + // --client-request-timeout is valid in default single-controller mode too + let non_pinned_matches = Args::command() + .try_get_matches_from(["gateway", "--client-request-timeout", "30s"]) + .unwrap(); + let non_pinned_args = Args::from_matches(&non_pinned_matches).unwrap(); + assert!(non_pinned_args.pinned_session.is_none()); + assert_eq!( + non_pinned_args.client_request_timeout, + Duration::from_secs(30) ); // Reject zero or invalid durations assert!(parse_duration("0s").is_err()); @@ -1251,15 +1264,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( })) .is_none() ); - let relay_id = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_id = actor.client_requests.keys().next().unwrap().clone(); actor .command( Request::Send { @@ -1273,14 +1278,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( .unwrap(); // Request is still pending for c2! assert!(child_rx.try_recv().is_err()); - assert!( - actor - .pinned - .as_ref() - .unwrap() - .client_requests - .contains_key(&relay_id) - ); + assert!(actor.client_requests.contains_key(&relay_id)); actor .command( Request::Send { @@ -1307,15 +1305,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( })) .is_none() ); - let relay_id2 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_id2 = actor.client_requests.keys().next().unwrap().clone(); for att in [&c1, &c2] { actor .command( @@ -1353,15 +1343,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( })) .is_none() ); - let relay_reload = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_reload = actor.client_requests.keys().next().unwrap().clone(); // Detach the only target c1 -> must NOT cancel ask-reload! actor .command( @@ -1373,14 +1355,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( ) .unwrap(); assert!(child_rx.try_recv().is_err()); - assert!( - actor - .pinned - .as_ref() - .unwrap() - .client_requests - .contains_key(&relay_reload) - ); + assert!(actor.client_requests.contains_key(&relay_reload)); // Reattach as c3 -> receives pending ask-reload right after startup and answers it! let c3 = attach(&mut actor, 3); let c3_events: Vec = actor.pinned.as_ref().unwrap().attachments[&c3] @@ -1416,15 +1391,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( })) .is_none() ); - let relay_timeout = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_timeout = actor.client_requests.keys().next().unwrap().clone(); assert!(actor.next_ready_client_reply().is_none()); tokio::time::advance(timeout).await; let expired_id = actor.next_ready_client_reply().unwrap(); @@ -1467,21 +1434,13 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( })) .is_none() ); - let relay_cancel = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_cancel = actor.client_requests.keys().next().unwrap().clone(); actor.output(json!({ "jsonrpc": "2.0", "method": "$/cancel_request", "params": { "requestId": "ask-agent-cancel" } })); - assert!(actor.pinned.as_ref().unwrap().client_requests.is_empty()); + assert!(actor.client_requests.is_empty()); let c3_cancel = actor.pinned.as_ref().unwrap().attachments[&c3] .events .back() @@ -1674,15 +1633,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro })) .is_none() ); - let relay_id = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_id = actor.client_requests.keys().next().unwrap().clone(); actor .command( Request::Send { @@ -1729,7 +1680,8 @@ async fn pinned_session_new_without_replay_from_defaults_to_none_and_survives_ev "pinned-restore".into(), PathBuf::from("/approved"), true, - Some(Duration::from_secs(60)), + true, + Duration::from_secs(60), ); let (writes, mut child_rx) = mpsc::channel(8); let driver = restore_actor @@ -2376,15 +2328,7 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo })) .is_none() ); - let relay1 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay1 = actor.client_requests.keys().next().unwrap().clone(); actor .command( Request::Send { @@ -2411,14 +2355,7 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo child_rx.try_recv().is_err(), "must NOT send -32601 after non-32601 error" ); - assert!( - actor - .pinned - .as_ref() - .unwrap() - .client_requests - .contains_key(&relay1) - ); + assert!(actor.client_requests.contains_key(&relay1)); // Late joiner c3 receives the still-pending request and answers validly! let c3 = attach(&mut actor, 3); @@ -2467,15 +2404,7 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo })) .is_none() ); - let relay2 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay2 = actor.client_requests.keys().next().unwrap().clone(); actor .command( Request::Send { @@ -2544,15 +2473,7 @@ fn pinned_relayed_response_buffers_under_child_backpressure_and_flushes() { })) .is_none() ); - let relay1 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay1 = actor.client_requests.keys().next().unwrap().clone(); actor .command( Request::Send { @@ -2581,7 +2502,7 @@ fn pinned_relayed_response_buffers_under_child_backpressure_and_flushes() { let flushed = child_rx.try_recv().unwrap().message; assert_eq!(flushed["id"], "ask-bp-win"); assert_eq!(flushed["result"]["content"]["k"], "v"); - assert!(actor.pinned.as_ref().unwrap().client_requests.is_empty()); + assert!(actor.client_requests.is_empty()); // 2. All-32601 decline also buffers under backpressure and flushes cleanly. writes @@ -2601,15 +2522,7 @@ fn pinned_relayed_response_buffers_under_child_backpressure_and_flushes() { })) .is_none() ); - let relay2 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay2 = actor.client_requests.keys().next().unwrap().clone(); for att in [&c1, &c2] { actor .command( @@ -3072,15 +2985,7 @@ async fn pinned_relayed_request_race_late_answer_and_non_target_ignored() { })) .is_none() ); - let relay1 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay1 = actor.client_requests.keys().next().unwrap().clone(); actor .command( Request::Send { @@ -3130,15 +3035,7 @@ async fn pinned_relayed_request_race_late_answer_and_non_target_ignored() { })) .is_none() ); - let relay2 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay2 = actor.client_requests.keys().next().unwrap().clone(); // Remove c1 from targets by having c1 reply -32601. actor .command( @@ -3164,14 +3061,7 @@ async fn pinned_relayed_request_race_late_answer_and_non_target_ignored() { ) .unwrap(); assert!(child_rx.try_recv().is_err()); - assert!( - actor - .pinned - .as_ref() - .unwrap() - .client_requests - .contains_key(&relay2) - ); + assert!(actor.client_requests.contains_key(&relay2)); // 3. Timeout expires; late answer from c2 after timeout is ignored cleanly (no second child write). tokio::time::advance(timeout).await; @@ -3214,7 +3104,7 @@ for line in sys.stdin: emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) "#; - // Pinned mode advertises {"elicitation": {"form": {}}}. + // 1. Pinned mode ALWAYS advertises {"elicitation": {"form": {}}}, even when the first client sends {}. let pinned_harness = PinnedHarness::new("cap-pinned", Duration::from_secs(60)).await; pinned_harness .child_source("cap-pinned", source, &["cap-pinned".into()]) @@ -3233,83 +3123,60 @@ for line in sys.stdin: ); let _ = pc.delete().await; - // Default mode advertises {} (no elicitation capability). - let dir = tempfile::tempdir().unwrap(); - let token = dir.path().join("token"); - std::fs::write(&token, "default-secret").unwrap(); - let gateway = Arc::new(Gateway { - stopping: AtomicBool::new(false), - token: BearerToken::load(&token).unwrap(), - roots: vec![dir.path().canonicalize().unwrap()], - pinned: None, - sessions: Mutex::new(HashMap::new()), - }); - let child = tokio::process::Command::new("python3") - .args(["-u", "-c", source, "cap-default"]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) - .kill_on_drop(true) - .spawn() - .unwrap(); - let actor = Actor::new("cap-default".into(), gateway.roots[0].clone(), false, None); - let (sender, receiver) = mpsc::channel(32); - let (completion, stopped) = watch::channel(()); - tokio::spawn(async move { - actor.run(child, receiver).await; - drop(completion); - }); - gateway.sessions.lock().await.insert( - "cap-default".into(), - Entry { - root: gateway.roots[0].clone(), - sender, - stopped, - }, + // 2. Default mode forwards ONLY relayable capabilities declared by the client (elicitation.form), + // stripping host-only auth, browser-callback elicitation.url, fs, and terminal. + let default_harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + default_harness + .child_source("cap-form", source, &["cap-form".into()]) + .await; + let c_form = default_harness + .connect_with_capabilities( + "dc-form", + json!({ + "elicitation": { "form": {}, "url": {} }, + "auth": { "terminal": {} }, + "fs": { "readTextFile": true }, + "terminal": true + }), + ) + .await; + let mut s_form = c_form.open_session_stream("cap-form").await; + assert_eq!( + c_form + .post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"cap-form"}})) + .await, + StatusCode::ACCEPTED ); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}/acp/v2", listener.local_addr().unwrap()); - let app = router(gateway).unwrap(); - let server = tokio::spawn(async move { - axum::serve(listener, app).await.unwrap(); - }); - let client = reqwest::Client::new(); - let init = client - .post(&url) - .bearer_auth("default-secret") - .json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":2,"info":{"name":"dc","version":"1"},"capabilities":{"elicitation":{"form":{}}}}})) - .send() - .await - .unwrap(); - let conn_id = init.headers()["acp-connection-id"] - .to_str() - .unwrap() - .to_owned(); - let stream_resp = client - .get(&url) - .bearer_auth("default-secret") - .header("acp-connection-id", &conn_id) - .header("acp-session-id", "cap-default") - .header("accept", "text/event-stream") - .send() - .await - .unwrap(); - let mut s_default = SseReader::new(stream_resp); + let dr_form = s_form.next_matching(|e| e["id"] == 2).await; assert_eq!( - client - .post(&url) - .bearer_auth("default-secret") - .header("acp-connection-id", &conn_id) - .json(&json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"cap-default"}})) - .send() - .await - .unwrap() - .status(), + dr_form["result"]["_meta"]["seenCaps"], + json!({"elicitation": {"form": {}}}) + ); + let _ = c_form.delete().await; + + // 3. Default mode forwards {} when the client sends {} (no unsolicited ask_user capability). + default_harness + .child_source("cap-empty", source, &["cap-empty".into()]) + .await; + let c_empty = default_harness + .connect_with_capabilities( + "dc-empty", + json!({ + "elicitation": { "url": {} }, + "auth": { "terminal": {} } + }), + ) + .await; + let mut s_empty = c_empty.open_session_stream("cap-empty").await; + assert_eq!( + c_empty + .post(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"cap-empty"}})) + .await, StatusCode::ACCEPTED ); - let dr = s_default.next_matching(|e| e["id"] == 2).await; - assert_eq!(dr["result"]["_meta"]["seenCaps"], json!({})); - server.abort(); + let dr_empty = s_empty.next_matching(|e| e["id"] == 3).await; + assert_eq!(dr_empty["result"]["_meta"]["seenCaps"], json!({})); + let _ = c_empty.delete().await; } #[test] @@ -3364,15 +3231,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by })) .is_none() ); - let relay_id = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_id = actor.client_requests.keys().next().unwrap().clone(); let c2 = actor .command( @@ -3398,11 +3257,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by ); assert_eq!(events.last().unwrap()["method"], "elicitation/create"); assert_eq!(events.last().unwrap()["id"], relay_id); - assert!( - actor.pinned.as_ref().unwrap().client_requests[&relay_id] - .targets - .contains(&c2) - ); + assert!(actor.client_requests[&relay_id].targets.contains(&c2)); // Joiner can answer the pending relayed request! actor .command( @@ -3467,18 +3322,10 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by })) .is_none() ); - let byte_relay_id = byte_actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let byte_relay_id = byte_actor.client_requests.keys().next().unwrap().clone(); // Verify both fresh attach (existing=0) and prepare_pinned_startup with non-zero existing bytes. let prepared = byte_actor - .prepare_pinned_startup( + .prepare_startup( "existing-att", 2, 128 * 1024, @@ -3829,15 +3676,7 @@ async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { })) .is_none() ); - let relay1 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay1 = actor.client_requests.keys().next().unwrap().clone(); // Dashboard detaches without answering. actor @@ -3865,14 +3704,7 @@ async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { child_rx.try_recv().is_err(), "must NOT decline with -32601 when another target detached mid-request" ); - assert!( - actor - .pinned - .as_ref() - .unwrap() - .client_requests - .contains_key(&relay1) - ); + assert!(actor.client_requests.contains_key(&relay1)); // Reloaded dashboard c3 attaches, receives the pending request, and answers! let c3 = attach(&mut actor, 3); @@ -3910,15 +3742,7 @@ async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { })) .is_none() ); - let relay2 = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay2 = actor.client_requests.keys().next().unwrap().clone(); actor .command( Request::Detach { @@ -4183,15 +4007,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela })) .is_none() ); - let relay_id = actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let relay_id = actor.client_requests.keys().next().unwrap().clone(); let c2 = actor .command( @@ -4212,11 +4028,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela assert_eq!(c2_att.events.len(), MAX_QUEUE + 1); assert_eq!(c2_att.events[0].1["params"]["update"]["message"], "m-0"); assert_eq!(c2_att.events.back().unwrap().1["id"], relay_id); - assert!( - actor.pinned.as_ref().unwrap().client_requests[&relay_id] - .targets - .contains(&c2) - ); + assert!(actor.client_requests[&relay_id].targets.contains(&c2)); // Joiner can answer the pending relayed request! actor .command( @@ -4304,15 +4116,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela })) .is_none() ); - let byte_relay_id = byte_actor - .pinned - .as_ref() - .unwrap() - .client_requests - .keys() - .next() - .unwrap() - .clone(); + let byte_relay_id = byte_actor.client_requests.keys().next().unwrap().clone(); let b2 = byte_actor .command( Request::Attach { @@ -4331,3 +4135,495 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela assert_eq!(b2_att.events.len(), 16 + 3 + 1); assert_eq!(b2_att.events.back().unwrap().1["id"], byte_relay_id); } + +#[tokio::test] +async fn default_mode_relays_ask_user_survives_controller_replace_timeout_and_child_crash() { + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source = r#" +import sys, json, os +prompt_req = None +expected_ask = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if expected_ask and req['id'] == expected_ask and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'reply': req.get('result'), 'error': req.get('error')}}) + prompt_req = None + expected_ask = None + continue + m = req['method'] + if m == 'initialize': + assert req['params']['capabilities'] == {'elicitation': {'form': {}}}, req + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':sys.argv[1],'configOptions':[]}}) + elif m == 'session/prompt': + text = req['params']['prompt'][0]['text'] + prompt_req = req + expected_ask = f'ask-{text}' + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':sys.argv[1],'update':{'sessionUpdate':'state_update','state':'running'}}}) + emit({ + 'jsonrpc':'2.0', + 'id':expected_ask, + 'method':'elicitation/create', + 'params':{'sessionId':sys.argv[1],'mode':'form','message':text} + }) + elif m == 'kit/session/status': + os._exit(1) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness + .child_source("def-relay", source, &["def-relay".into()]) + .await; + + // 1. Controller 1 declares elicitation.form, receives elicitation/create, answers it. + let c1 = harness + .connect_with_capabilities("ctrl-1", json!({"elicitation": {"form": {}}})) + .await; + let mut s1 = c1.open_session_stream("def-relay").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-relay"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":"p1","method":"session/prompt","params":{"sessionId":"def-relay","prompt":[{"type":"text","text":"direct"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q1 = s1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay1 = q1["id"].as_str().unwrap().to_owned(); + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":relay1,"result":{"action":"accept","content":{"ans":"from-c1"}}})) + .await, + StatusCode::ACCEPTED + ); + let done1 = s1.next_matching(|e| e["id"] == "p1").await; + assert_eq!(done1["result"]["reply"]["content"]["ans"], "from-c1"); + + // 2. Controller 1 triggers ask-replace, then Controller 2 replaces Controller 1 mid-request. + // Pending request survives replacement, is re-offered to Controller 2, and Controller 2 answers it! + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":"p2","method":"session/prompt","params":{"sessionId":"def-relay","prompt":[{"type":"text","text":"replace"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q2 = s1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay2 = q2["id"].as_str().unwrap().to_owned(); + + let mut c2 = harness + .connect_with_capabilities("ctrl-2", json!({"elicitation": {"form": {}}})) + .await; + let mut s2 = c2.open_session_stream("def-relay").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"def-relay"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s2.next_matching(|e| e["id"] == 2).await; + let reoffered = s2 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + assert_eq!(reoffered["id"], relay2); + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":relay2,"result":{"action":"accept","content":{"ans":"from-c2"}}})) + .await, + StatusCode::ACCEPTED + ); + + // 3. Child crash with pending relayed request cancels it via $/cancel_request in default mode! + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":"p4","method":"session/prompt","params":{"sessionId":"def-relay","prompt":[{"type":"text","text":"crash"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q4 = s2 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay4 = q4["id"].as_str().unwrap().to_owned(); + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":"crash","method":"kit/session/status","params":{"sessionId":"def-relay"}})) + .await, + StatusCode::ACCEPTED + ); + let cancel4 = c2 + .conn_stream + .next_matching(|e| e["method"] == "$/cancel_request") + .await; + assert_eq!(cancel4["params"]["requestId"], relay4); + + let _ = c1.delete().await; + let _ = c2.delete().await; + + // 4. Separate short-timeout default-mode gateway: unanswered ask expires via --client-request-timeout! + let timeout_harness = PinnedHarness::default_mode(Duration::from_millis(250)).await; + timeout_harness + .child_source("def-timeout", source, &["def-timeout".into()]) + .await; + let mut ct = timeout_harness + .connect_with_capabilities("ctrl-t", json!({"elicitation": {"form": {}}})) + .await; + let mut st = ct.open_session_stream("def-timeout").await; + assert_eq!( + ct.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-timeout"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = st.next_matching(|e| e["id"] == 1).await; + assert_eq!( + ct.post(json!({"jsonrpc":"2.0","id":"p3","method":"session/prompt","params":{"sessionId":"def-timeout","prompt":[{"type":"text","text":"timeout"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q3 = st + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay3 = q3["id"].as_str().unwrap().to_owned(); + let done3 = st.next_matching(|e| e["id"] == "p3").await; + assert_eq!(done3["result"]["error"]["code"], -32603); + assert_eq!( + done3["result"]["error"]["message"], + "Incoming transport closed" + ); + let cancel3 = ct + .conn_stream + .next_matching(|e| e["method"] == "$/cancel_request") + .await; + assert_eq!(cancel3["params"]["requestId"], relay3); + let _ = ct.delete().await; +} + +#[test] +fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_start_with_relay() { + let mut actor = default_actor("def-replay", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "def-replay", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + // Attach initial controller so updates & relays have a live target. + let c1 = actor + .command( + Request::Attach { + session: "def-replay".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-replay"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + // Turn 1 (completed). + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"def-replay","update":{"sessionUpdate":"state_update","state":"running"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"def-replay","update":{"sessionUpdate":"user_message","messageId":"u-1","content":[{"type":"text","text":"turn 1"}]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"def-replay","update":{"sessionUpdate":"agent_message","messageId":"a-1","content":[{"type":"text","text":"answer 1"}]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"def-replay","update":{"sessionUpdate":"state_update","state":"idle"}}})); + + // Turn 2 (mid-turn). + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"def-replay","update":{"sessionUpdate":"state_update","state":"running"}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"def-replay","update":{"sessionUpdate":"user_message","messageId":"u-2","content":[{"type":"text","text":"turn 2"}]}}})); + actor.output(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"def-replay","update":{"sessionUpdate":"agent_message_chunk","content":[{"type":"text","text":"turn 2 partial"}]}}})); + + // 1. `_kit_current_turn` in default mode replays Turn 2 only. + let _c2 = actor + .command( + Request::Attach { + session: "def-replay".into(), + replay: ReplayMode::CurrentTurn, + replace: true, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"def-replay","replayFrom":{"type":"_kit_current_turn"}}})), + }, + &writes, + ) + .unwrap(); + let events_turn: Vec = actor + .attachment + .as_ref() + .unwrap() + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + !events_turn + .iter() + .any(|e| e["params"]["update"]["messageId"] == "u-1") + ); + assert!( + events_turn + .iter() + .any(|e| e["params"]["update"]["messageId"] == "u-2") + ); + assert!( + events_turn + .iter() + .any(|e| e["params"]["update"]["sessionUpdate"] == "agent_message_chunk") + ); + assert!( + events_turn.last().unwrap()["result"]["_meta"]["kit/gateway"] + .get("replayTruncated") + .is_none() + ); + + // 2. `_kit_message` in default mode replays inclusively from u-1 and rejects unknown with -32602. + let _c3 = actor + .command( + Request::Attach { + session: "def-replay".into(), + replay: ReplayMode::Message { + message_id: "u-1".into(), + }, + replace: true, + startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"def-replay","replayFrom":{"type":"_kit_message","sessionId":"def-replay","messageId":"u-1"}}})), + }, + &writes, + ) + .unwrap(); + let events_msg: Vec = actor + .attachment + .as_ref() + .unwrap() + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert_eq!(events_msg[0]["params"]["update"]["messageId"], "u-1"); + assert!( + events_msg + .iter() + .any(|e| e["params"]["update"]["messageId"] == "u-2") + ); + + let bad_cursor = actor + .command( + Request::Attach { + session: "def-replay".into(), + replay: ReplayMode::Message { + message_id: "nope".into(), + }, + replace: true, + startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"def-replay"}})), + }, + &writes, + ) + .unwrap_err(); + assert_eq!(bad_cursor.jsonrpc_code(), -32602); + // Failed cursor preserves current controller! + assert_ne!(actor.attachment.as_ref().unwrap().id, c1); + + // 3. Exact full complete journal + pending relayed request succeeds with ReplayMode::Start in default mode! + let mut full_actor = default_actor("def-full-start", Duration::from_secs(60)); + full_actor.session_result = Some(json!({"sessionId": "def-full-start", "configOptions": []})); + let fc1 = full_actor + .command( + Request::Attach { + session: "def-full-start".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-full-start"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + for i in 0..(MAX_QUEUE - 3) { + full_actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "def-full-start", "update": {"sessionUpdate": "notice", "message": format!("d-{i}")}} + })); + if i % 64 == 0 { + let cur = full_actor.attachment.as_ref().unwrap().next; + let _ = full_actor.command( + Request::Poll { + session: "def-full-start".into(), + attachment: fc1.clone(), + cursor: cur, + }, + &writes, + ); + } + } + assert!(full_actor.replay_complete); + assert!( + full_actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-def-full", + "method": "elicitation/create", + "params": {"sessionId": "def-full-start", "mode": "form", "message": "ok?"} + })) + .is_none() + ); + let relay_id = full_actor.client_requests.keys().next().unwrap().clone(); + let fc2 = full_actor + .command( + Request::Attach { + session: "def-full-start".into(), + replay: ReplayMode::Start, + replace: true, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"def-full-start","replayFrom":{"type":"start"}}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!( + full_actor.attachment.as_ref().unwrap().events.len(), + MAX_QUEUE + 1 + ); + assert_eq!( + full_actor + .attachment + .as_ref() + .unwrap() + .events + .back() + .unwrap() + .1["id"], + relay_id + ); + full_actor + .command( + Request::Send { + session: "def-full-start".into(), + attachment: fc2, + message: json!({"jsonrpc":"2.0","id":relay_id,"result":{"action":"accept","content":{"ok":true}}}), + charge: None, + }, + &writes, + ) + .unwrap(); + assert_eq!(child_rx.try_recv().unwrap().message["id"], "ask-def-full"); + + // 4. `_kit_current_turn` truncation on evicted turn start in default mode sets replayTruncated = true! + let big = "x".repeat(MAX_HTTP_FRAME / 2); + for i in 0..22 { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "def-replay", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": format!("c-{i}:{big}")}}} + })); + } + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "def-replay", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "def-tail"}}} + })); + let _c4 = actor + .command( + Request::Attach { + session: "def-replay".into(), + replay: ReplayMode::CurrentTurn, + replace: true, + startup: Some(json!({"jsonrpc":"2.0","id":5,"method":"session/resume","params":{"sessionId":"def-replay"}})), + }, + &writes, + ) + .unwrap(); + let trunc_events: Vec = actor + .attachment + .as_ref() + .unwrap() + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + trunc_events + .iter() + .any(|e| e["params"]["update"]["content"]["text"] == "def-tail") + ); + assert_eq!( + trunc_events.last().unwrap()["result"]["_meta"]["kit/gateway"]["replayTruncated"], + true + ); +} + +#[tokio::test] +async fn default_and_pinned_mode_kit_subagent_steer_passthrough() { + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':sys.argv[1],'configOptions':[]}}) + elif m == 'kit/subagent/steer': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'receipt':{'subagent':req['params']['id'],'gen':req['params']['generation'],'text':req['params']['prompt']}}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + + for (is_pinned, sid) in [(false, "def-steer"), (true, "pin-steer")] { + let harness = if is_pinned { + PinnedHarness::new(sid, Duration::from_secs(60)).await + } else { + PinnedHarness::default_mode(Duration::from_secs(60)).await + }; + harness.child_source(sid, source, &[sid.into()]).await; + let mut c = harness.connect("steerer").await; + assert!( + c.init_body["result"]["capabilities"]["_meta"] + .get("kit/subagent/steer") + .is_some() + ); + let mut s = c.open_session_stream(sid).await; + assert_eq!( + c.post( + json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":sid}}) + ) + .await, + StatusCode::ACCEPTED + ); + let _ = s.next_matching(|e| e["id"] == 1).await; + + assert_eq!( + c.post(json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "kit/subagent/steer", + "params": {"session_id": sid, "id": "sub-1", "generation": 3, "prompt": "pivot"} + })) + .await, + StatusCode::ACCEPTED + ); + let steered = c.conn_stream.next_matching(|e| e["id"] == 2).await; + assert_eq!(steered["result"]["receipt"]["subagent"], "sub-1"); + assert_eq!(steered["result"]["receipt"]["gen"], 3); + assert_eq!(steered["result"]["receipt"]["text"], "pivot"); + + // Foreign / unattached session_id is rejected. + assert_eq!( + c.post(json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "kit/subagent/steer", + "params": {"session_id": "other-session", "id": "sub-1", "generation": 1, "prompt": "no"} + })) + .await, + StatusCode::ACCEPTED + ); + let rejected = c.conn_stream.next_matching(|e| e["id"] == 3).await; + assert!(rejected.get("error").is_some(), "{rejected}"); + + let _ = c.delete().await; + } +} diff --git a/src/gateway/tests.rs b/src/gateway/tests.rs index 1c7adfef..f862928c 100644 --- a/src/gateway/tests.rs +++ b/src/gateway/tests.rs @@ -31,7 +31,8 @@ impl Harness { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), roots: vec![directory.path().canonicalize().unwrap()], - pinned: None, + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, sessions: Mutex::new(HashMap::new()), }); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -106,7 +107,13 @@ for line in sys.stdin: .kill_on_drop(true) .spawn() .unwrap(); - let actor = Actor::new(id.to_owned(), self.gateway.roots[0].clone(), false, None); + let actor = Actor::new( + id.to_owned(), + self.gateway.roots[0].clone(), + false, + false, + DEFAULT_CLIENT_REQUEST_TIMEOUT, + ); let (sender, receiver) = mpsc::channel(32); let (completion, stopped) = watch::channel(()); tokio::spawn(async move { @@ -433,7 +440,13 @@ fn bind_policy_requires_separate_explicit_opt_ins() { } pub(super) fn isolated_actor() -> Actor { - Actor::new("resident".into(), PathBuf::from("/approved"), false, None) + Actor::new( + "resident".into(), + PathBuf::from("/approved"), + false, + false, + DEFAULT_CLIENT_REQUEST_TIMEOUT, + ) } #[tokio::test] diff --git a/tests/gateway.rs b/tests/gateway.rs index a1c49b76..83d1795a 100644 --- a/tests/gateway.rs +++ b/tests/gateway.rs @@ -158,6 +158,10 @@ struct SdkClient { impl SdkClient { async fn connect(url: &str) -> Self { + Self::connect_with_capabilities(url, json!({})).await + } + + async fn connect_with_capabilities(url: &str, capabilities: Value) -> Self { let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::AUTHORIZATION, @@ -176,7 +180,17 @@ impl SdkClient { transport: tokio::spawn(future.expect("HTTP transport requires a connection driver")), updates: Vec::new(), }; - let response = client.request(1, "initialize", json!({"protocolVersion":2,"info":{"name":"standard-sdk-test","version":"0"},"capabilities":{}})).await; + let response = client + .request( + 1, + "initialize", + json!({ + "protocolVersion": 2, + "info": {"name": "standard-sdk-test", "version": "0"}, + "capabilities": capabilities + }), + ) + .await; assert_eq!(response["result"]["protocolVersion"], 2, "{response}"); assert_eq!( response["result"]["capabilities"]["session"]["mcp"], @@ -2096,7 +2110,7 @@ async fn pinned_sdk_http_initialize_capabilities_and_session_stream_contract() { initialized, json!({"jsonrpc":"2.0","id":1,"result":{ "protocolVersion":2,"info":{"name":"kit-gateway","version":env!("CARGO_PKG_VERSION")}, - "capabilities":{"_meta":{"kit/session/status":{}},"session":{"prompt":{"image":{},"audio":{},"embeddedContext":{},"delivery":{"steer":{},"queue":{}}},"list":{},"mcp":{"stdio":{},"http":{},"_meta":{"kit/updateMcp":{"method":"_kit/session/update_mcp","upsert":true}}}}}, + "capabilities":{"_meta":{"kit/session/status":{},"kit/subagent/steer":{}},"session":{"prompt":{"image":{},"audio":{},"embeddedContext":{},"delivery":{"steer":{},"queue":{}}},"list":{},"mcp":{"stdio":{},"http":{},"_meta":{"kit/updateMcp":{"method":"_kit/session/update_mcp","upsert":true}}}}}, "_meta":{"kit/gateway":{"experimental":true,"transport":"bounded-http","maxFrameBytes":1048576,"coreBufferedBytesPerDirection":16777216,"httpEgressBytesPerConnection":4194304,"liveReplayLimitBytes":8388608,"liveReplayLimitEvents":4093}} }}) ); @@ -3564,3 +3578,146 @@ async fn pinned_real_child_retry_storm_reparents_and_does_not_block_other_client stop_gateway(&mut gateway).await; provider.abort(); } + +#[tokio::test] +async fn default_gateway_capability_forwarding_and_replay_cursors_with_real_child() { + let (fixture, mut requests, provider) = controlled_provider().await; + let (mut gateway, url) = fixture.gateway().await; + + // 1. Default-mode client with capabilities: {} (e.g. headless/Go client) must NOT see ask_user. + let mut headless = SdkClient::connect(&url).await; + let created_headless = headless + .request( + 2, + "session/new", + json!({"cwd": fixture.root, "mcpServers": []}), + ) + .await; + assert!( + created_headless.get("error").is_none(), + "{created_headless}" + ); + let headless_id = created_headless["result"]["sessionId"] + .as_str() + .unwrap() + .to_owned(); + headless + .start_prompt(3, &headless_id, "Check headless tools") + .await; + let (headless_body, release_h) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + let headless_has_ask_user = headless_body["tools"] + .as_array() + .is_some_and(|tools| tools.iter().any(|t| t["function"]["name"] == "ask_user")); + assert!( + !headless_has_ask_user, + "client with capabilities:{{}} must not receive ask_user tool: {headless_body}" + ); + release_h.send("Headless ok.").unwrap(); + headless.wait_idle().await; + headless.detach().await; + + // 2. Default-mode client declaring elicitation.form DOES see ask_user in the real child, + // AND can use _kit_current_turn and _kit_message replay cursors on session/resume! + let mut interactive = + SdkClient::connect_with_capabilities(&url, json!({"elicitation": {"form": {}}})).await; + let created_interactive = interactive + .request( + 2, + "session/new", + json!({"cwd": fixture.root, "mcpServers": []}), + ) + .await; + assert!( + created_interactive.get("error").is_none(), + "{created_interactive}" + ); + let sid = created_interactive["result"]["sessionId"] + .as_str() + .unwrap() + .to_owned(); + + // Turn 1 + interactive + .start_prompt(3, &sid, "First default turn") + .await; + let (interactive_body, release1) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + let interactive_has_ask_user = interactive_body["tools"] + .as_array() + .is_some_and(|tools| tools.iter().any(|t| t["function"]["name"] == "ask_user")); + assert!( + interactive_has_ask_user, + "client declaring elicitation.form must receive ask_user tool: {interactive_body}" + ); + release1.send("First default answer.").unwrap(); + interactive.wait_idle().await; + + // Turn 2 + interactive + .start_prompt(4, &sid, "Second default turn") + .await; + let (_, release2) = timeout(WAIT, requests.recv()).await.unwrap().unwrap(); + release2.send("Second default answer.").unwrap(); + interactive.wait_idle().await; + let turn2_user_msg_id = interactive + .updates + .iter() + .find_map(|u| { + (u["sessionUpdate"] == "user_message" + && u["content"].to_string().contains("Second default turn")) + .then(|| u["messageId"].as_str().map(str::to_owned)) + .flatten() + }) + .expect("Turn 2 user_message with messageId"); + interactive.detach().await; + + // Resume in default mode with _kit_current_turn -> Turn 2 only! + let mut resumer1 = SdkClient::connect(&url).await; + let resumed_turn = resumer1 + .request( + 2, + "session/resume", + json!({ + "sessionId": sid, + "cwd": fixture.root, + "replayFrom": {"type": "_kit_current_turn"} + }), + ) + .await; + assert!(resumed_turn.get("error").is_none(), "{resumed_turn}"); + assert_replayed_answer(&resumer1.updates, "Second default answer."); + assert!( + !serde_json::to_string(&resumer1.updates) + .unwrap() + .contains("First default answer.") + ); + resumer1.detach().await; + + // Resume in default mode with _kit_message(turn2_user_msg_id) -> Turn 2 inclusively! + let mut resumer2 = SdkClient::connect(&url).await; + let resumed_msg = resumer2 + .request( + 2, + "session/resume", + json!({ + "sessionId": sid, + "cwd": fixture.root, + "replayFrom": { + "type": "_kit_message", + "sessionId": sid, + "messageId": turn2_user_msg_id + } + }), + ) + .await; + assert!(resumed_msg.get("error").is_none(), "{resumed_msg}"); + assert_replayed_answer(&resumer2.updates, "Second default answer."); + assert!( + !serde_json::to_string(&resumer2.updates) + .unwrap() + .contains("First default answer.") + ); + resumer2.detach().await; + + stop_gateway(&mut gateway).await; + provider.abort(); +} From ee0e4877d9731afc4a13eedcf7924c65f925ac5c Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 00:27:35 +0000 Subject: [PATCH 06/19] fix(gateway): harden pinned workspace binding, keyed cancel, and relay handling --- docs/user/gateway.md | 2 +- src/gateway.rs | 392 ++++++++++++--- src/gateway/http_server.rs | 32 +- src/gateway/pinned_tests.rs | 951 ++++++++++++++++++++++++++++++++++++ tests/gateway.rs | 145 ++++++ 5 files changed, 1447 insertions(+), 75 deletions(-) diff --git a/docs/user/gateway.md b/docs/user/gateway.md index 019460f3..5891a29a 100644 --- a/docs/user/gateway.md +++ b/docs/user/gateway.md @@ -89,7 +89,7 @@ To start another session, exit and omit `--remote-session` on the next invocatio ## Close a session -Use standard ACP [`session/close`](../reference/gateway-protocol.md#close-a-resident-session) from the current controller to end a resident session and its outstanding work, including detached jobs and subagents. Closing a terminal or HTTP connection only detaches; it is not a substitute for closing the session. Interrupting a turn with `session/cancel` also leaves ordinary top-level detached jobs running. +Use standard ACP [`session/close`](../reference/gateway-protocol.md#close-a-resident-session) from the current controller to end a resident session and its outstanding work, including detached jobs and subagents. In `--pinned-session` mode, `session/close` detaches only the calling attachment and does not end the shared session (see [Share one session across multiple clients](#share-one-session-across-multiple-clients)). Closing a terminal or HTTP connection only detaches; it is not a substitute for closing the session. Interrupting a turn with `session/cancel` also leaves ordinary top-level detached jobs running. A successful close response follows session cleanup and child exit. Cleanup failure returns an error rather than reopening a partially closed child. A successful close also confirms that the session transcript has reached disk after cleanup. If writes remain buffered, persistence was disabled, or a transcript record was rejected, close returns an error instead of claiming durability. A storage failure can recover before the close check, but a record already lost cannot be repaired by a later successful disk write. After a successful close, the transcript remains available for explicit resume, which restores history rather than restarting the closed work. If the response is lost, do not assume either success or that the old child is still usable; list sessions and explicitly resume when ready to continue. diff --git a/src/gateway.rs b/src/gateway.rs index aa715c9d..6207c775 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -40,6 +40,7 @@ const MAX_PENDING_PER_ATTACHMENT: usize = 32; const MAX_ORPHANED_PENDING: usize = 256; const MAX_WAITING_STARTUPS: usize = 64; const MAX_CLIENT_REQUESTS: usize = 64; +const MAX_DEFERRED_CHILD_REPLIES: usize = 64; fn object(fields: [(&str, Value); N]) -> Value { Value::Object( @@ -748,15 +749,62 @@ async fn handle( let pinned_id = gateway.pinned_session.clone(); let rows = tokio::task::spawn_blocking(move || { let mut rows = Vec::new(); + if let Some(id) = pinned_id { + let owner = resolve_pinned_owner(&roots, &id)?; + if let Some(owner_root) = &owner { + let catalog = + crate::session::catalog(owner_root).map_err(Failure::unavailable)?; + for entry in catalog { + if entry.id != id { + continue; + } + let state = match entries.get(&entry.id) { + Some(e) if !e.sender.is_closed() => "resident", + Some(_) => "exited", + None => "restorable", + }; + rows.push(object([ + ("session", entry.id.into()), + ("root", owner_root.to_string_lossy().into_owned().into()), + ("title", entry.title.into()), + ("preview", entry.preview.into()), + ("state", state.into()), + ])); + } + } + if rows.is_empty() + && let Some(entry) = entries.get(&id) + { + rows.push(object([ + ("session", id.clone().into()), + ("root", entry.root.to_string_lossy().into_owned().into()), + ( + "state", + if entry.sender.is_closed() { + "exited" + } else { + "resident" + } + .into(), + ), + ])); + } + if rows.is_empty() + && let Some(root) = owner.as_ref().or_else(|| roots.first()) + { + rows.push(object([ + ("session", id.into()), + ("root", root.to_string_lossy().into_owned().into()), + ("state", "new".into()), + ])); + } + return Ok::<_, Failure>(rows); + } for root in &roots { let catalog = crate::session::catalog(root).map_err(Failure::unavailable)?; for entry in catalog { - if pinned_id.as_deref().is_some_and(|id| id != entry.id) { - continue; - } let state = match entries.get(&entry.id) { Some(e) if !e.sender.is_closed() => "resident", - Some(_) if pinned_id.is_some() => "exited", _ => "restorable", }; rows.push(object([ @@ -769,9 +817,6 @@ async fn handle( } } for (id, entry) in entries { - if pinned_id.as_deref().is_some_and(|pin| pin != id) { - continue; - } if !rows.iter().any(|row| row["session"] == id) { rows.push(object([ ("session", id.into()), @@ -788,16 +833,6 @@ async fn handle( ])); } } - if let Some(id) = pinned_id - && rows.is_empty() - && let Some(root) = roots.first() - { - rows.push(object([ - ("session", id.into()), - ("root", root.to_string_lossy().into_owned().into()), - ("state", "new".into()), - ])); - } Ok::<_, Failure>(rows) }) .await @@ -843,12 +878,21 @@ async fn handle( ]))); } drop(entries); - let belongs = - crate::session::belongs_to_workspace(&root, &id).map_err(Failure::bad)?; - if !pinned && !belongs { - return Err(Failure::root("session does not belong to this project")); + if pinned { + if let Some(owner) = resolve_pinned_owner(&gateway.roots, &id)? { + if owner != root { + return Err(Failure::root("session belongs to another project")); + } + restore = true; + } + } else { + let belongs = + crate::session::belongs_to_workspace(&root, &id).map_err(Failure::bad)?; + if !belongs { + return Err(Failure::root("session does not belong to this project")); + } + restore = true; } - restore = belongs; } let mut entries = gateway.sessions.lock().await; if gateway.stopping.load(Ordering::Acquire) { @@ -930,6 +974,11 @@ struct Attachment { next: u64, events: VecDeque<(u64, Value)>, bytes: usize, + // Startup-reserved relay requests are bounded by MAX_CLIENT_REQUESTS and + // excluded from live queue admission until polled so they cannot exhaust + // headroom needed for ordinary updates during a nearly full replay. + reserved: HashMap, + reserved_bytes: usize, live: bool, closing: bool, overflowed: bool, @@ -942,22 +991,35 @@ impl Attachment { next: 0, events: VecDeque::new(), bytes: 0, + reserved: HashMap::new(), + reserved_bytes: 0, live: false, closing: false, overflowed: false, } } + fn live_events(&self) -> usize { + self.events.len().saturating_sub(self.reserved.len()) + } + fn live_bytes(&self) -> usize { + self.bytes.saturating_sub(self.reserved_bytes) + } fn push(&mut self, message: Value) -> bool { let bytes = message.to_string().len(); - if self.events.len() >= MAX_QUEUE || self.bytes + bytes > MAX_REPLAY { + if self.live_events() >= MAX_QUEUE || self.live_bytes() + bytes > MAX_REPLAY { return false; } - self.push_reserved(message); + self.bytes += bytes; + self.next += 1; + self.events.push_back((self.next, message)); true } fn push_reserved(&mut self, message: Value) { - self.bytes += message.to_string().len(); + let bytes = message.to_string().len(); + self.bytes += bytes; self.next += 1; + self.reserved.insert(self.next, bytes); + self.reserved_bytes += bytes; self.events.push_back((self.next, message)); } fn poll(&mut self, cursor: u64) -> Result<(Vec, bool), Failure> { @@ -969,8 +1031,11 @@ impl Attachment { .front() .is_some_and(|(sequence, _)| *sequence <= cursor) { - if let Some((_, message)) = self.events.pop_front() { + if let Some((sequence, message)) = self.events.pop_front() { self.bytes -= message.to_string().len(); + if let Some(res_bytes) = self.reserved.remove(&sequence) { + self.reserved_bytes = self.reserved_bytes.saturating_sub(res_bytes); + } } } let events: Vec<_> = self @@ -1057,6 +1122,9 @@ struct Actor { client_request_timeout: Duration, next_relay_id: u64, client_requests: HashMap, + // Bounded deferred child replies (e.g. immediate relay rejections when child + // stdin is temporarily full) so transient saturation never stops the child. + deferred_child_replies: VecDeque, serial: u64, pending: HashMap, initialized: Option, @@ -1089,6 +1157,7 @@ impl Actor { client_request_timeout, next_relay_id: 0, client_requests: HashMap::new(), + deferred_child_replies: VecDeque::new(), serial: 0, pending: HashMap::new(), initialized: None, @@ -1178,18 +1247,18 @@ impl Actor { }); let mut lines = framing::Lines::new(stdout); loop { + self.expire_elapsed_client_requests(); let withdrawal = self.next_withdrawal(); - let ready_client_reply = if withdrawal.is_none() { + let has_deferred_reply = !self.deferred_child_replies.is_empty(); + let ready_client_reply = if withdrawal.is_none() && !has_deferred_reply { self.next_ready_client_reply() } else { None }; - let next_deadline = if withdrawal.is_none() && ready_client_reply.is_none() { - self.next_deadline() - } else { - None - }; - let needs_write = withdrawal.is_some() || ready_client_reply.is_some(); + let next_deadline = self.next_deadline(); + let needs_write = + withdrawal.is_some() || has_deferred_reply || ready_client_reply.is_some(); + let read_stdout = self.deferred_child_replies.len() < MAX_DEFERRED_CHILD_REPLIES; enum LoopEvent { Command(Option), Deadline, @@ -1212,7 +1281,13 @@ impl Actor { } }); let command = std::pin::pin!(commands.recv()); - let line = std::pin::pin!(lines.next_line()); + let line = std::pin::pin!(async { + if read_stdout { + lines.next_line().await + } else { + std::future::pending().await + } + }); let exited = std::pin::pin!(child.wait()); let written = std::pin::pin!(writer.join_next()); let io = std::pin::pin!(select(line, select(exited, written))); @@ -1224,6 +1299,12 @@ impl Actor { }; if let Some(id) = withdrawal { self.send_withdrawal(id, permit); + } else if let Some(reply) = self.deferred_child_replies.pop_front() { + permit.send(ChildWrite { + withdrawals: Vec::new(), + message: reply, + _charge: None, + }); } else if let Some(relay_id) = ready_client_reply { self.flush_client_request_reply(&relay_id, permit); } @@ -1245,6 +1326,9 @@ impl Actor { }; match event { LoopEvent::Deadline => { + // Settle expired relays before draining commands so late + // post-deadline answers cannot win even while stdin is full. + self.expire_elapsed_client_requests(); // Drain ready commands (such as a queued Poll after a process pause) // before reaping attachments whose lease appears elapsed. let mut stop_loop = false; @@ -1289,13 +1373,7 @@ impl Actor { Ok(Some(line)) => match serde_json::from_str::(&line) { Ok(message) => { if let Some(reply) = self.output(message) - && writes - .try_send(ChildWrite { - withdrawals: Vec::new(), - message: reply, - _charge: None, - }) - .is_err() + && !self.enqueue_immediate_child_reply(reply, &writes) { break; } @@ -1461,10 +1539,11 @@ impl Actor { } } fn pending_request_messages(&self) -> Vec<(String, Value)> { + let now = Instant::now(); let mut items: Vec<_> = self .client_requests .iter() - .filter(|(_, req)| req.resolved_reply.is_none()) + .filter(|(_, req)| req.resolved_reply.is_none() && req.deadline > now) .map(|(relay_id, req)| { ( req.seq, @@ -1532,6 +1611,8 @@ impl Actor { if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { attachment.events.clear(); attachment.bytes = 0; + attachment.reserved.clear(); + attachment.reserved_bytes = 0; attachment.live = false; attachment.closing = false; attachment.overflowed = true; @@ -1676,6 +1757,55 @@ impl Actor { } seq } + fn expire_elapsed_client_requests(&mut self) { + let now = Instant::now(); + let expired: Vec = self + .client_requests + .iter() + .filter(|(_, req)| req.resolved_reply.is_none() && req.deadline <= now) + .map(|(relay_id, _)| relay_id.clone()) + .collect(); + for relay_id in expired { + let targets = if let Some(req) = self.client_requests.get_mut(&relay_id) { + req.resolved_reply = Some(( + incoming_transport_closed_reply(req.child_id.clone(), &req.method), + None, + )); + std::mem::take(&mut req.targets) + } else { + continue; + }; + let cancel = cancel_request_message(Value::String(relay_id)); + for target in targets { + self.push_to_attachment(&target, cancel.clone()); + } + } + } + fn enqueue_immediate_child_reply( + &mut self, + reply: Value, + writes: &mpsc::Sender, + ) -> bool { + if writes.is_closed() { + return false; + } + if self.deferred_child_replies.is_empty() { + match writes.try_send(ChildWrite { + withdrawals: Vec::new(), + message: reply, + _charge: None, + }) { + Ok(()) => return true, + Err(mpsc::error::TrySendError::Full(write)) => { + self.deferred_child_replies.push_back(write.message); + return true; + } + Err(mpsc::error::TrySendError::Closed(_)) => return false, + } + } + self.deferred_child_replies.push_back(reply); + true + } fn next_ready_client_reply(&self) -> Option { let now = Instant::now(); self.client_requests @@ -1701,6 +1831,7 @@ impl Actor { } } fn flush_client_request_reply(&mut self, relay_id: &str, permit: mpsc::Permit<'_, ChildWrite>) { + self.expire_elapsed_client_requests(); let Some(req) = self.client_requests.remove(relay_id) else { return; }; @@ -1892,7 +2023,7 @@ impl Actor { ) { let Some((existing_events, existing_bytes)) = self .active_attachment(attachment_id) - .map(|a| (a.events.len(), a.bytes)) + .map(|a| (a.live_events(), a.live_bytes())) else { return; }; @@ -1921,6 +2052,7 @@ impl Actor { } } fn output(&mut self, mut message: Value) -> Option { + self.expire_elapsed_client_requests(); if message.get("method").is_some() { if let Some(id) = message.get("id").cloned() { let method = message["method"].as_str().unwrap_or_default().to_owned(); @@ -2282,27 +2414,42 @@ impl Actor { if closing { return Ok(object([])); } - let Some((&child_id, pending)) = self.pending.iter_mut().find(|(_, pending)| { - !pending.orphaned - && pending.attachment == attachment - && pending.original == *id - && pending.method == "session/prompt" - }) else { + let Some((child_id, cancelled_key)) = + self.pending.iter().find_map(|(&child_id, pending)| { + (!pending.orphaned + && pending.attachment == attachment + && pending.original == *id + && pending.method == "session/prompt") + .then(|| (child_id, pending.idempotency_key.clone())) + }) + else { return Ok(object([])); }; - // Clear the idempotency key so a subsequent retry never re-parents onto - // a prompt whose cancellation is in flight or pending. - pending.idempotency_key = None; // The normalized child notification needs only the remapped ID. match writes.try_reserve() { Ok(permit) => self.send_withdrawal(child_id, permit), Err(mpsc::error::TrySendError::Full(())) => { - pending.withdrawal_pending = true; + if let Some(pending) = self.pending.get_mut(&child_id) { + pending.withdrawal_pending = true; + } } Err(mpsc::error::TrySendError::Closed(())) => { return Err(Failure::unavailable("child input writer closed")); } } + // Clear the idempotency key on this attempt and any sibling attempts + // sharing the same key (the child withdraws the entire idempotency + // group), so a subsequent retry never re-parents onto a doomed sibling. + if let Some(key) = cancelled_key.as_deref() { + for entry in self.pending.values_mut() { + if entry.method == "session/prompt" && entry.idempotency_key.as_deref() == Some(key) + { + entry.idempotency_key = None; + } + } + } else if let Some(entry) = self.pending.get_mut(&child_id) { + entry.idempotency_key = None; + } Ok(object([])) } @@ -2452,6 +2599,7 @@ impl Actor { } fn command(&mut self, request: Request, writes: &mpsc::Sender) -> ResultValue { + self.expire_elapsed_client_requests(); if self.pinned.is_some() { return self.command_pinned(request, writes); } @@ -2707,7 +2855,7 @@ impl Actor { let (existing_events, existing_bytes) = self .attachment .as_ref() - .map_or((0, 0), |a| (a.events.len(), a.bytes)); + .map_or((0, 0), |a| (a.live_events(), a.live_bytes())); let prepared = self.prepare_startup( &attachment, existing_events, @@ -3036,11 +3184,17 @@ impl Actor { let Some(relay_id) = message["id"].as_str().map(str::to_owned) else { return Ok(object([])); }; - let Some((method, is_target)) = self + let Some((method, params, is_target)) = self .client_requests .get(&relay_id) .filter(|req| req.resolved_reply.is_none()) - .map(|req| (req.method.clone(), req.targets.contains(attachment))) + .map(|req| { + ( + req.method.clone(), + req.params.clone(), + req.targets.contains(attachment), + ) + }) else { // Already resolved, cancelled, or expired; ignore late duplicate race. return Ok(object([])); @@ -3086,7 +3240,7 @@ impl Actor { let Some(result) = message.get("result") else { return Err(Failure::bad("invalid client response")); }; - if !is_valid_client_result(&method, result) { + if !is_valid_client_result(&method, ¶ms, result) { return Err(Failure::bad("invalid response for relayed client request")); } let mut other_targets = Vec::new(); @@ -3189,21 +3343,129 @@ fn incoming_transport_closed_reply(child_id: Value, method: &str) -> Value { ]) } -fn is_valid_client_result(method: &str, result: &Value) -> bool { +fn resolve_pinned_owner(roots: &[PathBuf], id: &str) -> Result, Failure> { + let mut owners = Vec::new(); + for root in roots { + if crate::session::belongs_to_workspace(root, id).map_err(Failure::bad)? { + owners.push(root.clone()); + } + } + match owners.len() { + 0 => Ok(None), + 1 => Ok(owners.into_iter().next()), + _ => Err(Failure::conflict( + "pinned session belongs to multiple approved projects", + )), + } +} + +fn is_valid_client_result(method: &str, params: &Value, result: &Value) -> bool { + use agent_client_protocol::v2::schema as wire; match method { "elicitation/create" => { - let Some(action) = result.get("action").and_then(Value::as_str) else { + let Ok(response) = + serde_json::from_value::(result.clone()) + else { + return false; + }; + match response.action { + wire::ElicitationAction::Accept(accept) => { + let is_form = params.get("mode").and_then(Value::as_str) == Some("form") + || params.get("requestedSchema").is_some(); + if is_form { + let Some(content) = &accept.content else { + return false; + }; + if let Some(required) = params + .get("requestedSchema") + .and_then(|schema| schema.get("required")) + .and_then(Value::as_array) + && required + .iter() + .filter_map(Value::as_str) + .any(|key| !content.contains_key(key)) + { + return false; + } + if let Some(properties) = params + .get("requestedSchema") + .and_then(|schema| schema.get("properties")) + .and_then(Value::as_object) + { + for (key, value) in content { + if let Some(expected_type) = properties + .get(key) + .and_then(|prop| prop.get("type")) + .and_then(Value::as_str) + { + let valid_type = match expected_type { + "string" => { + matches!( + value, + wire::ElicitationContentValue::String(_) + ) + } + "integer" => { + matches!( + value, + wire::ElicitationContentValue::Integer(_) + ) + } + "number" => matches!( + value, + wire::ElicitationContentValue::Integer(_) + | wire::ElicitationContentValue::Number(_) + ), + "boolean" => { + matches!( + value, + wire::ElicitationContentValue::Boolean(_) + ) + } + "array" => matches!( + value, + wire::ElicitationContentValue::StringArray(_) + ), + _ => true, + }; + if !valid_type { + return false; + } + } + } + } + } + true + } + wire::ElicitationAction::Decline | wire::ElicitationAction::Cancel => true, + wire::ElicitationAction::Other(other) => !other.action.trim().is_empty(), + _ => false, + } + } + "session/request_permission" => { + let Ok(response) = + serde_json::from_value::(result.clone()) + else { return false; }; - match action { - "accept" => result - .get("content") - .is_none_or(|value| value.is_object() || value.is_null()), - "decline" | "cancel" => true, + match response.outcome { + wire::RequestPermissionOutcome::Cancelled(_) => true, + wire::RequestPermissionOutcome::Selected(selected) => { + if selected.option_id.0.is_empty() { + return false; + } + if let Some(options) = params.get("options").and_then(Value::as_array) { + return options.iter().any(|opt| { + opt.get("optionId").and_then(Value::as_str) + == Some(&*selected.option_id.0) + }); + } + true + } + wire::RequestPermissionOutcome::Other(other) => !other.outcome.trim().is_empty(), _ => false, } } - "session/request_permission" => result.get("outcome").is_some_and(Value::is_object), _ => result.is_object(), } } diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index f3cd3ef7..073e9792 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -357,7 +357,7 @@ impl Connection { None if pinned.is_some() && self.gateway.roots.len() == 1 => { self.gateway.roots[0].clone() } - None if resume => { + None if resume || pinned.is_some() => { let resident_root = if let Some(session_id) = id.as_deref() { self.gateway .sessions @@ -657,16 +657,30 @@ impl Connection { let message = serde_json::to_value(message).map_err(sdk_error)?; // Forward client-to-agent JSON-RPC responses for relayed requests in both modes. if is_client_response(&message) { - let target_session = message - .get("id") - .and_then(Value::as_str) - .and_then(|relay_id| self.relay_routes.remove(relay_id)) - .or_else(|| self.gateway.pinned_session.clone()); - if let Some(control) = target_session + let relay_id = message.get("id").and_then(Value::as_str).map(str::to_owned); + let target_session = relay_id .as_deref() - .and_then(|session_id| self.controls.get_mut(session_id)) + .and_then(|id| self.relay_routes.get(id).cloned()) + .or_else(|| self.gateway.pinned_session.clone()); + if let Some(session_id) = target_session.as_deref() + && let Some(control) = self.controls.get_mut(session_id) { - let _ = control.send(message, Arc::clone(&charged_frame)).await; + match control.send(message, Arc::clone(&charged_frame)).await { + Ok(_) => { + if let Some(id) = relay_id.as_deref() { + self.relay_routes.remove(id); + } + } + Err(error) => { + tracing::warn!( + session = %session_id, + relay_id = relay_id.as_deref().unwrap_or(""), + code = error.2, + "rejected client response for relayed request: {}", + error.1 + ); + } + } } self.flush(&channel).await?; drop(charged_frame); diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 109418a1..9f28920a 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -4627,3 +4627,954 @@ for line in sys.stdin: let _ = c.delete().await; } } + +#[test] +fn pinned_keyed_cancellation_invalidates_detached_sibling_from_reparenting() { + let mut actor = pinned_actor("pinned-sib", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-sib", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(16); + + let attach = |actor: &mut Actor, id: u64| { + actor + .command( + Request::Attach { + session: "pinned-sib".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-sib"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + + let a = attach(&mut actor, 1); + let b = attach(&mut actor, 2); + let c = attach(&mut actor, 3); + + // Attachment a and b both submit held prompts with the same idempotencyKey. + actor + .command( + Request::Send { + session: "pinned-sib".into(), + attachment: a.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "a-p", + "method": "session/prompt", + "params": {"sessionId": "pinned-sib", "delivery": "steer", "idempotencyKey": "k-sib", "prompt": [{"type":"text","text":"hi"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let orig_child_id = child_rx.try_recv().unwrap().message["id"].as_u64().unwrap(); + + actor + .command( + Request::Send { + session: "pinned-sib".into(), + attachment: b.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "b-p", + "method": "session/prompt", + "params": {"sessionId": "pinned-sib", "delivery": "steer", "idempotencyKey": "k-sib", "prompt": [{"type":"text","text":"hi"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let sib_child_id = child_rx.try_recv().unwrap().message["id"].as_u64().unwrap(); + assert_ne!(orig_child_id, sib_child_id); + + // Attachment a detaches, leaving orig_child_id orphaned. + actor + .command( + Request::Detach { + session: "pinned-sib".into(), + attachment: a, + }, + &writes, + ) + .unwrap(); + assert!(actor.pending[&orig_child_id].orphaned); + + // Attachment b explicitly cancels its sibling attempt -> child gets cancel ONLY for sib_child_id, + // and BOTH attempts lose their idempotencyKey so neither can be re-parented. + actor + .command( + Request::Send { + session: "pinned-sib".into(), + attachment: b, + message: json!({ + "jsonrpc": "2.0", + "method": "$/cancel_request", + "params": {"requestId": "b-p"} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let cancel_msg = child_rx.try_recv().unwrap().message; + assert_eq!(cancel_msg["method"], "$/cancel_request"); + assert_eq!(cancel_msg["params"]["requestId"], sib_child_id); + assert!(child_rx.try_recv().is_err()); + + // Attachment c retries with the same key BEFORE child replies -> MUST forward a fresh prompt, + // NOT re-parent onto a's doomed orphan! + actor + .command( + Request::Send { + session: "pinned-sib".into(), + attachment: c, + message: json!({ + "jsonrpc": "2.0", + "id": "c-p", + "method": "session/prompt", + "params": {"sessionId": "pinned-sib", "delivery": "steer", "idempotencyKey": "k-sib", "prompt": [{"type":"text","text":"hi"}]} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let fresh_child_id = child_rx.try_recv().unwrap().message["id"].as_u64().unwrap(); + assert_ne!(fresh_child_id, orig_child_id); + assert_ne!(fresh_child_id, sib_child_id); +} + +#[tokio::test(start_paused = true)] +async fn relay_expiration_is_terminal_even_when_child_writer_is_full() { + for is_pinned in [true, false] { + let timeout = Duration::from_secs(5); + let mut actor = if is_pinned { + pinned_actor("exp-full", timeout) + } else { + default_actor("exp-full", timeout) + }; + actor.session_result = Some(json!({"sessionId": "exp-full", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(1); + + let a1 = actor + .command( + Request::Attach { + session: "exp-full".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"exp-full"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + // Start a relayed elicitation/create request. + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-exp", + "method": "elicitation/create", + "params": {"sessionId": "exp-full", "mode": "form", "message": "decide"} + })) + .is_none() + ); + let relay_id = actor.client_requests.keys().next().unwrap().clone(); + + // Saturate the 1-slot child writer channel so timeout reply cannot be written yet. + writes + .try_send(ChildWrite { + withdrawals: Vec::new(), + message: json!({"jsonrpc": "2.0", "method": "dummy"}), + _charge: None, + }) + .unwrap(); + assert!(writes.try_reserve().is_err()); + + // Advance past the relay deadline while writer is still full. + tokio::time::advance(timeout + Duration::from_millis(1)).await; + + // A late valid answer arriving after deadline MUST NOT override expiration! + actor + .command( + Request::Send { + session: "exp-full".into(), + attachment: a1.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": relay_id, + "result": {"action": "accept", "content": {"ok": true}} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + + // Existing target received $/cancel_request when deadline settled. + let a1_events: Vec = actor + .active_attachment(&a1) + .unwrap() + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + a1_events + .iter() + .any(|e| e["method"] == "$/cancel_request" && e["params"]["requestId"] == relay_id), + "expected cancel on target for is_pinned={is_pinned}: {a1_events:?}" + ); + + // Late joiner attaching while writer is still full MUST NOT receive the expired relay. + let a2 = actor + .command( + Request::Attach { + session: "exp-full".into(), + replay: ReplayMode::None, + replace: !is_pinned, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"exp-full"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let a2_events: Vec = actor + .active_attachment(&a2) + .unwrap() + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + !a2_events + .iter() + .any(|e| e["method"] == "elicitation/create"), + "late joiner must not see expired relay (is_pinned={is_pinned}): {a2_events:?}" + ); + + // Free the blocked writer and flush -> child receives -32603 timeout, NEVER the late accept! + let _ = child_rx.try_recv().unwrap(); + let ready = actor.next_ready_client_reply().unwrap(); + assert_eq!(ready, relay_id); + let permit = writes.try_reserve().unwrap(); + actor.flush_client_request_reply(&ready, permit); + let reply = child_rx.try_recv().unwrap().message; + assert_eq!(reply["id"], "ask-exp"); + assert_eq!(reply["error"]["code"], -32603); + assert_eq!(reply["error"]["message"], "Incoming transport closed"); + } +} + +#[tokio::test] +async fn relay_rejection_under_saturated_child_writer_does_not_stop_child_and_preserves_order() { + use tokio::io::AsyncWriteExt; + + let gate = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let gate_port = gate.local_addr().unwrap().port(); + let harness = PinnedHarness::new("pinned-sat", Duration::from_secs(60)).await; + // Fake child initializes, opens session, then on trigger emits 66 elicitation/create + // requests (64 fill client_requests, 2 trigger immediate -32603 rejections) while NOT + // reading stdin until the test opens the gate (so the 16-slot writes channel is full!). + let source = r#" +import sys, json, socket +def emit(v): print(json.dumps(v), flush=True) +gate_port = int(sys.argv[1]) +triggered = False +for line in sys.stdin: + req = json.loads(line) + m = req.get('method') + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-sat','configOptions':[]}}) + elif m == 'kit/session/status' and not triggered: + triggered = True + # Stop reading stdin until gate releases so gateway's 16-slot writes queue fills up! + # Wait for the test to fill the writes channel first, then emit 66 relays. + with socket.create_connection(('127.0.0.1', gate_port)) as sock: + assert sock.recv(1) == b'E' + for i in range(66): + emit({ + 'jsonrpc':'2.0', + 'id':f'cap-{i}', + 'method':'elicitation/create', + 'params':{'sessionId':'pinned-sat','mode':'form','message':f'q-{i}'} + }) + # Keep stdin unread until test releases us to drain and report rejections! + assert sock.recv(1) == b'R' + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) + # Now collect the two deferred cap-rejection replies and report them on next status call. + rejections = [] + for line2 in sys.stdin: + r2 = json.loads(line2) + if 'method' not in r2 and isinstance(r2.get('id'), str) and r2['id'].startswith('cap-'): + rejections.append((r2['id'], r2.get('error', {}).get('code'))) + elif r2.get('method') == 'kit/session/status': + emit({'jsonrpc':'2.0','id':r2['id'],'result':{'rejections':rejections}}) + elif 'id' in r2: + emit({'jsonrpc':'2.0','id':r2['id'],'result':{}}) + break + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness + .child_source("pinned-sat", source, &[gate_port.to_string()]) + .await; + + let c1 = harness.connect("observer").await; + let mut s1 = c1.open_session_stream("pinned-sat").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-sat"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + // Trigger child to pause reading stdin at the gate. + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":100,"method":"kit/session/status","params":{"sessionId":"pinned-sat"}})) + .await, + StatusCode::ACCEPTED + ); + let (mut sock, _) = tokio::time::timeout(Duration::from_secs(5), gate.accept()) + .await + .unwrap() + .unwrap(); + + // Saturate the 16-slot child writer channel directly through the actor mailbox + // so HTTP connection frame limits never interfere: + // 1) Prompt 0 (256 KiB > OS pipe buffer) is popped by the writer task and blocks inside write_all. + // 2) Prompts 1..=16 fill all 16 slots of `writes` so `try_send` returns Full! + let entry = harness + .gateway + .sessions + .lock() + .await + .get("pinned-sat") + .cloned() + .unwrap(); + let actor_call = |request: Request| { + let sender = entry.sender.clone(); + async move { + let (reply, rx) = oneshot::channel(); + sender.send(Envelope { request, reply }).await.unwrap(); + rx.await.unwrap().unwrap() + } + }; + let filler = actor_call(Request::Attach { + session: "pinned-sat".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-sat"}})), + }) + .await["attachment"] + .as_str() + .unwrap() + .to_owned(); + let big = "p".repeat(256 * 1024); + let _ = actor_call(Request::Send { + session: "pinned-sat".into(), + attachment: filler.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": 200, + "method": "session/prompt", + "params": {"sessionId": "pinned-sat", "delivery": "queue", "prompt": [{"type": "text", "text": big}]} + }), + charge: None, + }) + .await; + tokio::time::sleep(Duration::from_millis(100)).await; + for i in 1..=16 { + let _ = actor_call(Request::Send { + session: "pinned-sat".into(), + attachment: filler.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": 200 + i, + "method": "session/prompt", + "params": {"sessionId": "pinned-sat", "delivery": "queue", "prompt": [{"type": "text", "text": format!("fill-{i}")}]} + }), + charge: None, + }) + .await; + } + let _ = actor_call(Request::Detach { + session: "pinned-sat".into(), + attachment: filler, + }) + .await; + + // Tell child to emit 66 elicitation/create requests while writes is FULL -> 64 accepted, + // cap-64 & cap-65 produce immediate -32603 rejections that MUST defer instead of killing child! + sock.write_all(b"E").await.unwrap(); + // Wait for the 64th relayed request to arrive on s1, ensuring cap-64 and cap-65 were processed too. + let _ = s1 + .next_matching(|e| e["method"] == "elicitation/create" && e["params"]["message"] == "q-63") + .await; + + // Release child stdin so writer drains; child MUST still be alive and receive cap-64, cap-65 in order! + sock.write_all(b"R").await.unwrap(); + let trigger_done = s1.next_matching(|e| e["id"] == 100).await; + assert_eq!(trigger_done["result"]["settled"], true); + + // Ask the still-living child for the rejections it received (after draining the queued prompts). + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":999,"method":"kit/session/status","params":{"sessionId":"pinned-sat"}})) + .await, + StatusCode::ACCEPTED + ); + let report = s1.next_matching(|e| e["id"] == 999).await; + assert_eq!( + report["result"]["rejections"], + json!([["cap-64", -32603], ["cap-65", -32603]]) + ); + + let _ = c1.delete().await; +} + +#[test] +fn relay_validates_permission_and_elicitation_answers_before_cancelling_others() { + let mut actor = pinned_actor("pinned-val", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "pinned-val", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let attach = |actor: &mut Actor, id: u64| { + actor + .command( + Request::Attach { + session: "pinned-val".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-val"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned() + }; + let c1 = attach(&mut actor, 1); + let c2 = attach(&mut actor, 2); + + // 1. Permission request with offered options. + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "perm-1", + "method": "session/request_permission", + "params": { + "sessionId": "pinned-val", + "toolCall": {"toolCallId": "tc-1"}, + "options": [ + {"optionId": "allow_once", "name": "Allow", "kind": "allow_once"}, + {"optionId": "reject_once", "name": "Reject", "kind": "reject_once"} + ] + } + })) + .is_none() + ); + let perm_relay = actor.client_requests.keys().next().unwrap().clone(); + + // Invalid outcomes MUST be rejected without resolving relay or cancelling c2. + for bad_result in [ + json!({"outcome": {}}), + json!({"outcome": {"outcome": "selected"}}), + json!({"outcome": {"outcome": "selected", "optionId": "not_offered"}}), + json!({"outcome": {"outcome": "selected", "optionId": ""}}), + json!({"outcome": {"outcome": ""}}), + ] { + let err = actor + .command( + Request::Send { + session: "pinned-val".into(), + attachment: c1.clone(), + message: json!({"jsonrpc": "2.0", "id": perm_relay, "result": bad_result}), + charge: None, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(err.0, StatusCode::BAD_REQUEST, "{bad_result}"); + assert!(child_rx.try_recv().is_err(), "{bad_result}"); + assert!(actor.client_requests[&perm_relay].resolved_reply.is_none()); + assert!(actor.client_requests[&perm_relay].targets.contains(&c2)); + } + + // Valid offered optionId from c2 wins and cancels c1. + actor + .command( + Request::Send { + session: "pinned-val".into(), + attachment: c2.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": perm_relay, + "result": {"outcome": {"outcome": "selected", "optionId": "allow_once"}} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let perm_reply = child_rx.try_recv().unwrap().message; + assert_eq!(perm_reply["id"], "perm-1"); + assert_eq!(perm_reply["result"]["outcome"]["optionId"], "allow_once"); + assert_eq!( + actor + .active_attachment(&c1) + .unwrap() + .events + .back() + .unwrap() + .1["method"], + "$/cancel_request" + ); + + // 2. Form elicitation with required field. + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "form-1", + "method": "elicitation/create", + "params": { + "sessionId": "pinned-val", + "mode": "form", + "message": "Pick", + "requestedSchema": { + "type": "object", + "required": ["question_0"], + "properties": {"question_0": {"type": "string"}} + } + } + })) + .is_none() + ); + let form_relay = actor.client_requests.keys().next().unwrap().clone(); + + // Missing content, null content, missing required key, and non-scalar content value MUST fail. + for bad_result in [ + json!({"action": "accept"}), + json!({"action": "accept", "content": null}), + json!({"action": "accept", "content": "not-an-object"}), + json!({"action": "accept", "content": {}}), + json!({"action": "accept", "content": {"question_0": {"nested": true}}}), + json!({"action": ""}), + ] { + let err = actor + .command( + Request::Send { + session: "pinned-val".into(), + attachment: c1.clone(), + message: json!({"jsonrpc": "2.0", "id": form_relay, "result": bad_result}), + charge: None, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(err.0, StatusCode::BAD_REQUEST, "{bad_result}"); + assert!(child_rx.try_recv().is_err(), "{bad_result}"); + assert!(actor.client_requests[&form_relay].resolved_reply.is_none()); + } + + // Valid form answer from c2 succeeds and cancels c1. + actor + .command( + Request::Send { + session: "pinned-val".into(), + attachment: c2, + message: json!({ + "jsonrpc": "2.0", + "id": form_relay, + "result": {"action": "accept", "content": {"question_0": "opt-a"}} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let form_reply = child_rx.try_recv().unwrap().message; + assert_eq!(form_reply["id"], "form-1"); + assert_eq!(form_reply["result"]["content"]["question_0"], "opt-a"); + assert_eq!( + actor + .active_attachment(&c1) + .unwrap() + .events + .back() + .unwrap() + .1["params"]["requestId"], + form_relay + ); +} + +#[tokio::test] +async fn relay_preserves_unknown_extension_actions_and_keeps_default_route_after_invalid_reply() { + // 1. Unit check: custom/future elicitation and permission actions forward immediately! + let mut actor = default_actor("ext-act", Duration::from_secs(300)); + actor.session_result = Some(json!({"sessionId": "ext-act", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + let a1 = actor + .command( + Request::Attach { + session: "ext-act".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"ext-act"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-ext", + "method": "elicitation/create", + "params": {"sessionId": "ext-act", "mode": "form", "message": "ext"} + })) + .is_none() + ); + let ask_relay = actor.client_requests.keys().next().unwrap().clone(); + actor + .command( + Request::Send { + session: "ext-act".into(), + attachment: a1.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": ask_relay, + "result": {"action": "_extension", "vendorFlag": true} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let ask_reply = child_rx.try_recv().unwrap().message; + assert_eq!(ask_reply["id"], "ask-ext"); + assert_eq!(ask_reply["result"]["action"], "_extension"); + assert_eq!(ask_reply["result"]["vendorFlag"], true); + + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "perm-ext", + "method": "session/request_permission", + "params": {"sessionId": "ext-act", "options": [{"optionId": "allow", "name": "Allow", "kind": "allow_once"}]} + })) + .is_none() + ); + let perm_relay = actor.client_requests.keys().next().unwrap().clone(); + actor + .command( + Request::Send { + session: "ext-act".into(), + attachment: a1, + message: json!({ + "jsonrpc": "2.0", + "id": perm_relay, + "result": {"outcome": {"outcome": "_policy_defer", "ttl": 30}} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let perm_reply = child_rx.try_recv().unwrap().message; + assert_eq!(perm_reply["id"], "perm-ext"); + assert_eq!(perm_reply["result"]["outcome"]["outcome"], "_policy_defer"); + assert_eq!(perm_reply["result"]["outcome"]["ttl"], 30); + + // 2. HTTP default-mode check: an invalid client reply does NOT consume relay_routes, + // so a subsequent valid reply from the same controller still routes and resolves! + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source = r#" +import sys, json +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req['id'] == 'ask-http' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'got': req.get('result')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'def-ext','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({'jsonrpc':'2.0','id':'ask-http','method':'elicitation/create','params':{'sessionId':'def-ext','mode':'form','message':'hi'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("def-ext", source, &[]).await; + let c = harness + .connect_with_capabilities("ctrl", json!({"elicitation": {"form": {}}})) + .await; + let mut s = c.open_session_stream("def-ext").await; + assert_eq!( + c.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-ext"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s.next_matching(|e| e["id"] == 1).await; + assert_eq!( + c.post(json!({"jsonrpc":"2.0","id":"p1","method":"session/prompt","params":{"sessionId":"def-ext","prompt":[{"type":"text","text":"go"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q = s + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let rid = q["id"].as_str().unwrap().to_owned(); + + // First send an invalid form accept (missing content) -> rejected silently with diagnostic, route preserved! + assert_eq!( + c.post(json!({"jsonrpc":"2.0","id":rid,"result":{"action":"accept"}})) + .await, + StatusCode::ACCEPTED + ); + // Then send a valid extension action -> succeeds immediately without waiting for timeout! + assert_eq!( + c.post(json!({"jsonrpc":"2.0","id":rid,"result":{"action":"_extension","k":"v"}})) + .await, + StatusCode::ACCEPTED + ); + let done = s.next_matching(|e| e["id"] == "p1").await; + assert_eq!(done["result"]["got"]["action"], "_extension"); + assert_eq!(done["result"]["got"]["k"], "v"); + let _ = c.delete().await; +} + +#[test] +fn startup_reserved_relays_do_not_exhaust_live_queue_before_first_poll() { + let (writes, _child_rx) = mpsc::channel(8); + + // 1. Event-count bound (both pinned and default modes): + // journal has MAX_QUEUE - 4 events (+ 2 snapshots + 1 startup result = MAX_QUEUE - 1, + // leaving 1 live slot). Appending 2 pending relays via push_reserved must NOT consume + // that 1 live slot when a live update arrives before the joiner's first poll! + for is_pinned in [true, false] { + let mut actor = if is_pinned { + pinned_actor("res-count", Duration::from_secs(60)) + } else { + default_actor("res-count", Duration::from_secs(60)) + }; + actor.session_result = Some(json!({"sessionId": "res-count", "configOptions": []})); + let c1 = actor + .command( + Request::Attach { + session: "res-count".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"res-count"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + for i in 0..(MAX_QUEUE - 4) { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "res-count", "update": {"sessionUpdate": "notice", "message": format!("e-{i}")}} + })); + if i % 64 == 0 { + let cur = actor.active_attachment(&c1).unwrap().next; + let _ = actor.command( + Request::Poll { + session: "res-count".into(), + attachment: c1.clone(), + cursor: cur, + }, + &writes, + ); + } + } + assert!(actor.replay_complete); + for k in 0..2 { + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": format!("ask-{k}"), + "method": "elicitation/create", + "params": {"sessionId": "res-count", "mode": "form", "message": format!("q-{k}")} + })) + .is_none() + ); + } + + let joiner = actor + .command( + Request::Attach { + session: "res-count".into(), + replay: ReplayMode::Start, + replace: !is_pinned, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"res-count","replayFrom":{"type":"start"}}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + // Emit an ordinary live update BEFORE the joiner's first poll! + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "res-count", "update": {"sessionUpdate": "notice", "message": "live-after-startup"}} + })); + + // Drain the joiner via Poll: MUST NOT overflow and MUST deliver startup result, + // both reserved relays, and the live update in order! + let mut cursor = 0; + let mut drained = Vec::new(); + loop { + let polled = actor + .command( + Request::Poll { + session: "res-count".into(), + attachment: joiner.clone(), + cursor, + }, + &writes, + ) + .unwrap(); + let batch = polled["events"].as_array().unwrap(); + if batch.is_empty() { + break; + } + for item in batch { + cursor = item["cursor"].as_u64().unwrap(); + drained.push(item["message"].clone()); + } + } + assert_eq!(drained.len(), (MAX_QUEUE - 1) + 2 + 1); + assert!(drained.iter().any(|m| m["id"] == 2)); + assert_eq!( + drained + .iter() + .filter(|m| m["method"] == "elicitation/create") + .count(), + 2 + ); + assert_eq!( + drained.last().unwrap()["params"]["update"]["message"], + "live-after-startup" + ); + // After draining past the reserved events, reserved counters return to 0. + let att = actor.active_attachment(&joiner).unwrap(); + assert!(att.reserved.is_empty()); + assert_eq!(att.reserved_bytes, 0); + } + + // 2. Byte-bound variant: replay leaves ~16 KiB headroom, 128 KiB reserved relay is appended, + // and a 1 KiB live update arrives before first poll -> MUST NOT overflow! + let mut byte_actor = pinned_actor("res-bytes", Duration::from_secs(60)); + byte_actor.session_result = Some(json!({"sessionId": "res-bytes", "configOptions": []})); + let b1 = byte_actor + .command( + Request::Attach { + session: "res-bytes".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"res-bytes"}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let pad = "b".repeat(512 * 1024 - 2048); + for i in 0..16 { + byte_actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "res-bytes", "update": {"sessionUpdate": "notice", "message": format!("{i}:{pad}")}} + })); + let cur = byte_actor.active_attachment(&b1).unwrap().next; + let _ = byte_actor.command( + Request::Poll { + session: "res-bytes".into(), + attachment: b1.clone(), + cursor: cur, + }, + &writes, + ); + } + let big_relay = "r".repeat(128 * 1024); + assert!( + byte_actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-big", + "method": "elicitation/create", + "params": {"sessionId": "res-bytes", "mode": "form", "message": big_relay} + })) + .is_none() + ); + let b2 = byte_actor + .command( + Request::Attach { + session: "res-bytes".into(), + replay: ReplayMode::Start, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"res-bytes","replayFrom":{"type":"start"}}})), + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + byte_actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "res-bytes", "update": {"sessionUpdate": "notice", "message": "small-live-update"}} + })); + let polled = byte_actor + .command( + Request::Poll { + session: "res-bytes".into(), + attachment: b2, + cursor: 0, + }, + &writes, + ) + .unwrap(); + let events = polled["events"].as_array().unwrap(); + assert_eq!(events.len(), 16 + 3 + 1 + 1); + assert_eq!( + events.last().unwrap()["message"]["params"]["update"]["message"], + "small-live-update" + ); +} diff --git a/tests/gateway.rs b/tests/gateway.rs index 83d1795a..905159ad 100644 --- a/tests/gateway.rs +++ b/tests/gateway.rs @@ -3721,3 +3721,148 @@ async fn default_gateway_capability_forwarding_and_replay_cursors_with_real_chil stop_gateway(&mut gateway).await; provider.abort(); } + +#[tokio::test] +async fn pinned_cold_start_binds_to_existing_workspace_and_rejects_conflicting_or_ambiguous_projects() + { + let (fixture, _started, release, provider) = delayed_provider("Workspace A answer.").await; + let _ = release.send(()); + let project_a = fixture.root.clone(); + let project_b = fixture.home.path().join("project-b"); + fs::create_dir(&project_b).unwrap(); + let project_b = project_b.canonicalize().unwrap(); + let project_b_str = project_b.to_string_lossy().into_owned(); + + // 1. Start pinned gateway with both approved projects A and B, persist transcript in A. + let (mut gw1, url1) = fixture + .gateway_with_bind( + "127.0.0.1:0", + &["--project", &project_b_str, "--pinned-session", "pinned-ws"], + ) + .await; + let mut c1 = SdkClient::connect(&url1).await; + let started = c1 + .request( + 2, + "session/new", + json!({"cwd": project_a, "mcpServers": []}), + ) + .await; + assert_eq!(started["result"]["sessionId"], "pinned-ws", "{started}"); + let prompted = c1 + .request( + 3, + "session/prompt", + json!({"sessionId": "pinned-ws", "prompt": [{"type": "text", "text": "Complete offline"}]}), + ) + .await; + assert!(prompted.get("error").is_none(), "{prompted}"); + c1.wait_idle().await; + c1.detach().await; + stop_gateway(&mut gw1).await; + + // 2. Cold restart with both approved projects A and B: + // - resume or new with conflicting cwd B MUST fail (not create a second empty session!) + // - session/list returns one row bound to project A + // - resume with project A restores the existing transcript. + let (mut gw2, url2) = fixture + .gateway_with_bind( + "127.0.0.1:0", + &["--project", &project_b_str, "--pinned-session", "pinned-ws"], + ) + .await; + let mut c2 = SdkClient::connect(&url2).await; + let wrong_resume = c2 + .request( + 2, + "session/resume", + json!({"sessionId": "pinned-ws", "cwd": project_b}), + ) + .await; + assert!( + wrong_resume.get("error").is_some(), + "resume in wrong project B must fail: {wrong_resume}" + ); + let wrong_new = c2 + .request( + 3, + "session/new", + json!({"cwd": project_b, "mcpServers": []}), + ) + .await; + assert!( + wrong_new.get("error").is_some(), + "new in wrong project B must fail: {wrong_new}" + ); + let listed = c2.request(4, "session/list", json!({})).await; + assert!(listed.get("error").is_none(), "{listed}"); + let sessions = listed["result"]["sessions"].as_array().unwrap(); + assert_eq!(sessions.len(), 1, "{listed}"); + assert_eq!(sessions[0]["sessionId"], "pinned-ws"); + assert_eq!(sessions[0]["cwd"], project_a.to_string_lossy().as_ref()); + assert_eq!(sessions[0]["_meta"]["kit.gateway.state"], "restorable"); + + let right_resume = c2 + .request( + 5, + "session/resume", + json!({ + "sessionId": "pinned-ws", + "cwd": project_a, + "replayFrom": {"type": "start"} + }), + ) + .await; + assert!(right_resume.get("error").is_none(), "{right_resume}"); + assert_replayed_answer(&c2.updates, "Workspace A answer."); + c2.detach().await; + stop_gateway(&mut gw2).await; + + // 3. Create an identical pinned transcript in project B to simulate ambiguous ownership + // across approved roots -> both session/list and session/resume MUST reject it! + let sessions_root = fixture.home.path().join(".kit/sessions"); + let mut transcript_a = None; + for entry in fs::read_dir(&sessions_root).unwrap() { + let path = entry.unwrap().path().join("pinned-ws.jsonl"); + if path.is_file() { + transcript_a = Some(path); + break; + } + } + let transcript_a = transcript_a.expect("persisted transcript in project A"); + let dir_b = project_b.join(".kit/sessions"); + fs::create_dir_all(&dir_b).unwrap(); + let mut contents = fs::read_to_string(&transcript_a).unwrap(); + contents = contents.replace( + project_a.to_string_lossy().as_ref(), + project_b.to_string_lossy().as_ref(), + ); + fs::write(dir_b.join("pinned-ws.jsonl"), contents).unwrap(); + + let (mut gw3, url3) = fixture + .gateway_with_bind( + "127.0.0.1:0", + &["--project", &project_b_str, "--pinned-session", "pinned-ws"], + ) + .await; + let mut c3 = SdkClient::connect(&url3).await; + let ambiguous_list = c3.request(2, "session/list", json!({})).await; + assert!( + ambiguous_list.get("error").is_some(), + "ambiguous ownership must fail session/list: {ambiguous_list}" + ); + let ambiguous_resume = c3 + .request( + 3, + "session/resume", + json!({"sessionId": "pinned-ws", "cwd": project_a}), + ) + .await; + assert!( + ambiguous_resume.get("error").is_some(), + "ambiguous ownership must fail session/resume: {ambiguous_resume}" + ); + c3.detach().await; + stop_gateway(&mut gw3).await; + provider.abort(); +} From efe420e318856f2006a6c5438abf07f8da46b1af Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 01:01:33 +0000 Subject: [PATCH 07/19] fix(gateway): scope relay ids, target elicitation by capability, and simplify actor --- docs/reference/gateway-protocol.md | 11 +- docs/user/gateway.md | 2 +- src/gateway.rs | 1257 ++++++++++++---------------- src/gateway/http_server.rs | 34 +- src/gateway/pinned_tests.rs | 1036 ++++++++++++++++------- src/gateway/tests.rs | 175 ++-- 6 files changed, 1421 insertions(+), 1094 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index d872b6e4..d6e10bbe 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -175,12 +175,12 @@ Only user messages with durable identities support partial replay. Agent-message ## Relayed agent-to-client requests -In both default single-controller mode and `--pinned-session` mode, the gateway relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending per session) to live attached clients and routes client-to-agent JSON-RPC responses back to the child. +In both default single-controller mode and `--pinned-session` mode, the gateway relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending per session) to eligible live attachments and routes client-to-agent JSON-RPC responses back to the child. Each relayed request carries an opaque gateway-assigned string `id` unique across the gateway process; clients must echo that exact `id` in their JSON-RPC response and must not parse or assume any internal format. - **Client capabilities forwarded to the child:** In default mode, the gateway filters the connecting client's `initialize.params.capabilities` to forward only relayable capabilities (`elicitation.form`) and strips host-only or unsupported capabilities (`auth`, `elicitation.url`, `fs`, `terminal`). A client connecting with `capabilities: {}` therefore does not advertise `elicitation.form` and does not receive an `ask_user` tool. In `--pinned-session` mode, because multiple heterogeneous clients share one child initialized once, the gateway always advertises `{"elicitation":{"form":{}}}` to the child. -- **Delivery and reconnects:** If no attachment is live when the request arrives, the gateway answers `-32601` immediately. Otherwise the request is sent to every live target (the active controller in default mode, or all live attachments in pinned mode) and re-offered right after startup to any client that attaches or replaces the controller while the request is pending. -- **Resolution and errors:** The first valid `result` from a target attachment wins and is forwarded to the child (buffered across transient child-stdin backpressure); any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target errored or detached mid-request, the gateway answers `-32601` to the child. Any other client error, or a target detaching without answering (such as a browser reloading or a controller being replaced), keeps the request pending until answered, cancelled by the agent, or expired. In default mode, if a new controller replaces one that had declared `elicitation.form` and does not implement the relayed method, it can decline with `-32601` or let the timeout expire. -- **Timeout and child exit (`--client-request-timeout`):** `--client-request-timeout ` (default `5m`, valid in both modes) is an absolute deadline measured from when the child request arrives. On expiry the gateway answers the child with `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. +- **Capability targeting and delivery:** Each attachment records whether its own connection's `initialize` declared `capabilities.elicitation.form`. An `elicitation/create` request is offered only to live attachments (and late joiners) that declared `elicitation.form`; if no live attachment declared it—including when a `capabilities: {}` controller replaces a declaring controller in default mode, or when only headless `capabilities: {}` clients are attached in pinned mode—the gateway answers `-32601` immediately and non-declaring clients receive nothing. Requests that require no client capability in ACP v2 (such as `session/request_permission`) are offered to all live attachments and late joiners. Pending requests are re-offered right after startup to any eligible client that attaches or replaces the controller while the request is pending, without consuming live-update queue headroom before the first poll. +- **Validation, resolution, and errors:** The gateway validates relayed results against the ACP v2 response types (`CreateElicitationResponse` with non-null `content` for form `accept`, and `RequestPermissionResponse` with an offered `optionId` for `selected`), while preserving schema-valid custom or future extension actions/outcomes and leaving form-schema field validation to the child. The first valid `result` from an eligible target wins and is forwarded to the child through a bounded FIFO reply queue; any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target failed or detached mid-request, the gateway answers `-32601` to the child. An answer that fails shape validation or a non-`-32601` client error is never forwarded: that target is dropped (with a warning logged at the HTTP boundary and no JSON-RPC reply sent to a response frame), and the request stays pending if another live target or a detached target remains; if the failing sender was the only remaining target and no target detached, the gateway resolves the request promptly toward the child with `-32603` (`data.reason`: `"invalid_client_response"` or `"client_error"`) rather than waiting for `--client-request-timeout`. A target detaching without answering (such as a browser reloading or a controller being replaced) keeps the request pending until answered by a remaining or rejoining eligible client, cancelled by the agent, or expired. +- **Timeout and child exit (`--client-request-timeout`):** `--client-request-timeout ` (default `5m`, valid in both modes) is an absolute deadline measured from when the child request arrives. Expiration settles even if child stdin is temporarily saturated: the gateway buffers a `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) reply to the child and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. @@ -194,7 +194,8 @@ Start the gateway with `--pinned-session ` (and optionally `--client When pinned mode is active: - **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. The first client's `initialize` `info` is what the child receives, and the gateway always advertises `{"elicitation":{"form":{}}}` to the child. `session/list` returns only that single pinned session entry (even if `params.cwd` does not match, while rejecting any foreign `params.sessionId`), with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). -- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in the approved project) and default absent/`null` `replayFrom` to no history (`historyAvailable: false`). Requests naming any other session ID fail with an error. If a single `--project` is configured, `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). At most 64 concurrent joiners may wait on an in-flight cold startup. +- **Workspace ownership binding:** Cold startup (`session/new` / `session/resume`) and `session/list` resolve the pinned session's existing owning workspace across all approved `--project` roots before spawning a child. A request whose `cwd` conflicts with the existing owning project is rejected (`root_denied`, `"session belongs to another project"`), and if transcripts for the pinned ID exist in more than one approved project, both discovery and startup fail (`conflict`, `"pinned session belongs to multiple approved projects"`). Creation is allowed only when no approved project already owns that ID. +- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in its owning project) and default absent/`null` `replayFrom` to no history (`historyAvailable: false`). Requests naming any other session ID fail with an error. If a single `--project` is configured (or the pinned session is already resident or bound to an existing workspace), `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). - **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. - **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, its failed pending requests carry `error.data.reason = "queue_overflow"`, and its SSE stream closes cleanly without affecting other attachments or the active turn. - **Fan-in, pending caps, and orphan re-parenting:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry (whose withdrawal has not been requested), the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). A re-parented retry's prompt body is not re-validated or used: the original held prompt is what gets inserted, matching the child's duplicate-key semantics. diff --git a/docs/user/gateway.md b/docs/user/gateway.md index 5891a29a..0b177e48 100644 --- a/docs/user/gateway.md +++ b/docs/user/gateway.md @@ -121,7 +121,7 @@ kit gateway --credential-file "$HOME/.kit-gateway-token" \ - **Shared session boundary:** All attachments share the pinned session: every connected client receives all live updates, can submit prompts or cancel work, can answer relayed interactive questions or permission requests, and can call `session/set_config_option` and `_kit/session/update_mcp` (which can register stdio MCP servers that run commands in the host or sandbox). Place an authenticating proxy in front of `kit gateway --pinned-session` when serving multiple users or services and filter methods for less-trusted clients; the gateway itself verifies only its single bearer token. - **Independent attachments:** Connecting a second client does not displace existing clients or withdraw their held prompts. Sending `session/close` detaches only the calling client without ending the session. If a slow client's output queue overflows, only that client is disconnected; other attachments and the active turn continue. - **Late joiners and default replay:** Unlike default mode (where `session/new` defaults to full replay), pinned mode omits historical replay by default on both `session/new` and `session/resume` unless `replayFrom` is provided. Both modes support `{"type":"start"}`, `{"type":"_kit_current_turn"}`, and `{"type":"_kit_message","sessionId":"...","messageId":"..."}`. -- **Multi-client interactive prompts:** Both modes relay agent-to-client requests (such as `ask_user` forms and permission requests) using `--client-request-timeout` (default `5m`). In pinned mode, the gateway always advertises form elicitation to the child and broadcasts pending requests to every attached client (and late joiners); the first valid answer wins and the other clients receive a cancellation. +- **Multi-client interactive prompts:** Both modes relay agent-to-client requests (such as `ask_user` forms and permission requests) using `--client-request-timeout` (default `5m`). `elicitation/create` requests are offered only to attached clients (and late joiners) whose connection declared `capabilities.elicitation.form` (so headless deliverers with `capabilities: {}` are never targeted), while permission requests are offered to all live attachments. The first valid answer wins and the other targets receive a cancellation. For exact wire behavior, cursors, and limits, see [Pinned-session mode](../reference/gateway-protocol.md#pinned-session-mode). diff --git a/src/gateway.rs b/src/gateway.rs index 6207c775..77a8f167 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -21,7 +21,7 @@ use std::{ process::Stdio, sync::{ Arc, - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicU64, Ordering}, }, time::Duration, }; @@ -38,10 +38,11 @@ const MAX_QUEUE: usize = 4096; const MAX_PENDING_SHARED: usize = 128; const MAX_PENDING_PER_ATTACHMENT: usize = 32; const MAX_ORPHANED_PENDING: usize = 256; -const MAX_WAITING_STARTUPS: usize = 64; const MAX_CLIENT_REQUESTS: usize = 64; const MAX_DEFERRED_CHILD_REPLIES: usize = 64; +static NEXT_RELAY_ID: AtomicU64 = AtomicU64::new(1); + fn object(fields: [(&str, Value); N]) -> Value { Value::Object( fields @@ -402,6 +403,8 @@ enum Request { replace: bool, #[cfg_attr(test, serde(default))] startup: Option, + #[cfg_attr(test, serde(default))] + elicitation_form: bool, }, Poll { session: String, @@ -979,12 +982,13 @@ struct Attachment { // headroom needed for ordinary updates during a nearly full replay. reserved: HashMap, reserved_bytes: usize, + elicitation_form: bool, live: bool, closing: bool, overflowed: bool, } impl Attachment { - fn new(id: String) -> Self { + fn new(id: String, elicitation_form: bool) -> Self { Self { id, touched: Instant::now(), @@ -993,11 +997,18 @@ impl Attachment { bytes: 0, reserved: HashMap::new(), reserved_bytes: 0, + elicitation_form, live: false, closing: false, overflowed: false, } } + fn can_receive_client_request(&self, method: &str) -> bool { + match method { + "elicitation/create" => self.elicitation_form, + _ => true, + } + } fn live_events(&self) -> usize { self.events.len().saturating_sub(self.reserved.len()) } @@ -1078,15 +1089,14 @@ struct PendingClientRequest { params: Value, targets: HashSet, deadline: Instant, - // True once any target failed with a non-(-32601) error; prevents treating - // remaining -32601 declines as "no attachment supports this". - had_client_error: bool, + // Set once any target fails with a non-(-32601) error or invalid answer; + // prevents treating remaining -32601 declines as "no client-side services" + // and drives the prompt -32603 failure when no target remains. + last_failure: Option<(&'static str, &'static str)>, // True once any target detached without answering (e.g. mid-reload or // controller replacement); keeps the request pending until timeout even if - // remaining targets reply -32601. + // remaining targets decline or fail. had_detached_target: bool, - // Buffered child-bound JSON-RPC reply when child stdin is backpressured. - resolved_reply: Option<(Value, Option>)>, } enum RetireMode { Remove, @@ -1094,14 +1104,12 @@ enum RetireMode { Closing, } struct PinnedState { - attachments: HashMap, startup_driver: Option, waiting_startups: Vec, } impl PinnedState { fn new() -> Self { Self { - attachments: HashMap::new(), startup_driver: None, waiting_startups: Vec::new(), } @@ -1114,17 +1122,17 @@ struct Actor { // Terminal after any standard session/close response: an error may mean // cleanup partially completed, so never reopen a half-closed child. closed: bool, - attachment: Option, + // Default mode holds at most one active controller; pinned mode holds many. + attachments: HashMap, // Survives detach, expiry and replay overflow; only a committed claim replaces it. committed_owner: Option, // Present only in `--pinned-session` mode; default single-controller mode leaves this None. pinned: Option, client_request_timeout: Duration, - next_relay_id: u64, client_requests: HashMap, - // Bounded deferred child replies (e.g. immediate relay rejections when child - // stdin is temporarily full) so transient saturation never stops the child. - deferred_child_replies: VecDeque, + // Single bounded FIFO queue for child-bound replies (immediate relay + // rejections, client answers, failures, and timeouts) when stdin is full. + pending_child_replies: VecDeque<(Value, Option>)>, serial: u64, pending: HashMap, initialized: Option, @@ -1151,13 +1159,12 @@ impl Actor { root, restore, closed: false, - attachment: None, + attachments: HashMap::new(), committed_owner: None, pinned: pinned.then(PinnedState::new), client_request_timeout, - next_relay_id: 0, client_requests: HashMap::new(), - deferred_child_replies: VecDeque::new(), + pending_child_replies: VecDeque::new(), serial: 0, pending: HashMap::new(), initialized: None, @@ -1249,16 +1256,10 @@ impl Actor { loop { self.expire_elapsed_client_requests(); let withdrawal = self.next_withdrawal(); - let has_deferred_reply = !self.deferred_child_replies.is_empty(); - let ready_client_reply = if withdrawal.is_none() && !has_deferred_reply { - self.next_ready_client_reply() - } else { - None - }; + let has_child_reply = !self.pending_child_replies.is_empty(); let next_deadline = self.next_deadline(); - let needs_write = - withdrawal.is_some() || has_deferred_reply || ready_client_reply.is_some(); - let read_stdout = self.deferred_child_replies.len() < MAX_DEFERRED_CHILD_REPLIES; + let needs_write = withdrawal.is_some() || has_child_reply; + let read_stdout = self.pending_child_replies.len() < MAX_DEFERRED_CHILD_REPLIES; enum LoopEvent { Command(Option), Deadline, @@ -1299,14 +1300,14 @@ impl Actor { }; if let Some(id) = withdrawal { self.send_withdrawal(id, permit); - } else if let Some(reply) = self.deferred_child_replies.pop_front() { + } else if let Some((message, charge)) = + self.pending_child_replies.pop_front() + { permit.send(ChildWrite { withdrawals: Vec::new(), - message: reply, - _charge: None, + message, + _charge: charge, }); - } else if let Some(relay_id) = ready_client_reply { - self.flush_client_request_reply(&relay_id, permit); } continue; } @@ -1373,7 +1374,7 @@ impl Actor { Ok(Some(line)) => match serde_json::from_str::(&line) { Ok(message) => { if let Some(reply) = self.output(message) - && !self.enqueue_immediate_child_reply(reply, &writes) + && !self.queue_child_reply(reply, None, &writes) { break; } @@ -1446,7 +1447,7 @@ impl Actor { let _ = child.kill().await; let _ = child.wait().await; } - if self.closed && !stopping && self.attachment.is_some() { + if self.closed && !stopping && !self.attachments.is_empty() { // Child cleanup precedes delivery of the close response. Keep only // bounded response history for one lease, even if the client vanished. let drain = async { @@ -1456,7 +1457,7 @@ impl Actor { } let result = self.command(command.request, &writes); let _ = command.reply.send(result); - if self.attachment.is_none() { + if self.attachments.is_empty() { break; } } @@ -1480,56 +1481,60 @@ impl Actor { let _ = tokio::time::timeout(Duration::from_secs(2), drain).await; } } - fn emit(&mut self, message: Value) { - if let Some(attachment) = &mut self.attachment - && !attachment.push(message) - { - let retired = self.attachment.take().map(|attachment| attachment.id); - if let Some(id) = retired { - self.mark_withdrawals(&id); - self.mark_target_detached(&id); - } - } + fn live_update_targets(&self) -> Vec { + self.attachments + .values() + .filter(|a| a.live && !a.closing && !a.overflowed) + .map(|a| a.id.clone()) + .collect() } - fn live_attachment_ids(&self) -> Vec { - if let Some(pinned) = &self.pinned { - pinned - .attachments - .values() - .filter(|a| a.live && !a.closing && !a.overflowed) - .map(|a| a.id.clone()) - .collect() - } else { - self.attachment - .as_ref() - .filter(|a| a.live && a.touched.elapsed() < LEASE) - .map(|a| a.id.clone()) - .into_iter() - .collect() - } + fn live_relay_targets(&self, method: &str) -> Vec { + let pinned = self.pinned.is_some(); + self.attachments + .values() + .filter(|a| { + a.live + && !a.closing + && !a.overflowed + && a.can_receive_client_request(method) + && (pinned || a.touched.elapsed() < LEASE) + }) + .map(|a| a.id.clone()) + .collect() } fn has_queued_attachment_events(&self) -> bool { - if let Some(pinned) = &self.pinned { - pinned.attachments.values().any(|a| !a.events.is_empty()) - } else { - self.attachment - .as_ref() - .is_some_and(|a| !a.events.is_empty()) - } + self.attachments.values().any(|a| !a.events.is_empty()) + } + fn active_attachment(&self, attachment_id: &str) -> Option<&Attachment> { + self.attachments + .get(attachment_id) + .filter(|a| !a.closing && !a.overflowed) + } + fn active_attachment_mut(&mut self, attachment_id: &str) -> Option<&mut Attachment> { + self.attachments + .get_mut(attachment_id) + .filter(|a| !a.closing && !a.overflowed) } fn push_to_attachment(&mut self, attachment_id: &str, message: Value) -> bool { - if self.pinned.is_some() { - return self.push_pinned_attachment(attachment_id, message); - } - if self - .attachment - .as_ref() - .is_some_and(|a| a.id == attachment_id) - { - self.emit(message); - return self.attachment.is_some(); + let overflowed = if let Some(attachment) = self.attachments.get_mut(attachment_id) { + if attachment.overflowed { + return false; + } + !attachment.push(message) + } else { + return false; + }; + if overflowed { + if self.pinned.is_some() { + self.retire_pinned_attachment(attachment_id, RetireMode::Overflow); + } else { + self.attachments.remove(attachment_id); + self.mark_withdrawals(attachment_id); + self.mark_target_detached(attachment_id); + } + return false; } - false + true } fn mark_target_detached(&mut self, attachment_id: &str) { for request in self.client_requests.values_mut() { @@ -1538,12 +1543,14 @@ impl Actor { } } } - fn pending_request_messages(&self) -> Vec<(String, Value)> { + fn pending_request_messages(&self, elicitation_form: bool) -> Vec<(String, Value)> { let now = Instant::now(); let mut items: Vec<_> = self .client_requests .iter() - .filter(|(_, req)| req.resolved_reply.is_none() && req.deadline > now) + .filter(|(_, req)| { + req.deadline > now && (req.method != "elicitation/create" || elicitation_form) + }) .map(|(relay_id, req)| { ( req.seq, @@ -1563,24 +1570,6 @@ impl Actor { .map(|(_, relay_id, message)| (relay_id, message)) .collect() } - fn push_pinned_attachment(&mut self, attachment_id: &str, message: Value) -> bool { - let Some(pinned) = &mut self.pinned else { - return false; - }; - let overflowed = if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { - if attachment.overflowed { - return false; - } - !attachment.push(message) - } else { - return false; - }; - if overflowed { - self.retire_pinned_attachment(attachment_id, RetireMode::Overflow); - return false; - } - true - } fn retire_pinned_attachment(&mut self, attachment_id: &str, mode: RetireMode) { let mut failed_waiters = Vec::new(); for pending in self.pending.values_mut() { @@ -1603,27 +1592,27 @@ impl Actor { failed_waiters = std::mem::take(&mut pinned.waiting_startups); } } - match mode { - RetireMode::Remove => { - pinned.attachments.remove(attachment_id); - } - RetireMode::Overflow => { - if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { - attachment.events.clear(); - attachment.bytes = 0; - attachment.reserved.clear(); - attachment.reserved_bytes = 0; - attachment.live = false; - attachment.closing = false; - attachment.overflowed = true; - attachment.touched = Instant::now(); - } + } + match mode { + RetireMode::Remove => { + self.attachments.remove(attachment_id); + } + RetireMode::Overflow => { + if let Some(attachment) = self.attachments.get_mut(attachment_id) { + attachment.events.clear(); + attachment.bytes = 0; + attachment.reserved.clear(); + attachment.reserved_bytes = 0; + attachment.live = false; + attachment.closing = false; + attachment.overflowed = true; + attachment.touched = Instant::now(); } - RetireMode::Closing => { - if let Some(attachment) = pinned.attachments.get_mut(attachment_id) { - attachment.live = false; - attachment.closing = true; - } + } + RetireMode::Closing => { + if let Some(attachment) = self.attachments.get_mut(attachment_id) { + attachment.live = false; + attachment.closing = true; } } } @@ -1640,19 +1629,16 @@ impl Actor { } } fn reap_expired_pinned_attachments(&mut self) { + if self.pinned.is_none() { + return; + } let now = Instant::now(); let expired: Vec = self - .pinned - .as_ref() - .map(|pinned| { - pinned - .attachments - .values() - .filter(|a| a.touched + LEASE <= now) - .map(|a| a.id.clone()) - .collect() - }) - .unwrap_or_default(); + .attachments + .values() + .filter(|a| a.touched + LEASE <= now) + .map(|a| a.id.clone()) + .collect(); for id in expired { self.retire_pinned_attachment(&id, RetireMode::Remove); } @@ -1660,43 +1646,26 @@ impl Actor { fn drain_exited(&mut self, request: Request) -> ResultValue { match request { Request::Detach { attachment, .. } => { - if let Some(pinned) = &mut self.pinned { - pinned.attachments.remove(&attachment); - } else if self.attachment.as_ref().is_some_and(|a| a.id == attachment) { - self.attachment = None; - } + self.attachments.remove(&attachment); Ok(object([])) } Request::Poll { attachment, cursor, .. } => { - let entry = if let Some(pinned) = &mut self.pinned { - let Some(entry) = pinned.attachments.get_mut(&attachment) else { - return Err(Failure::unavailable("child exited; restore its transcript")); - }; - if entry.overflowed { - pinned.attachments.remove(&attachment); - return Err(Failure( - StatusCode::CONFLICT, - "attachment queue overflowed; reconnect".into(), - "queue_overflow", - )); - } - entry - } else { - let Some(entry) = self.attachment.as_mut().filter(|a| a.id == attachment) - else { - return Err(Failure::unavailable("child exited; restore its transcript")); - }; - entry + let Some(entry) = self.attachments.get_mut(&attachment) else { + return Err(Failure::unavailable("child exited; restore its transcript")); }; + if entry.overflowed { + self.attachments.remove(&attachment); + return Err(Failure( + StatusCode::CONFLICT, + "attachment queue overflowed; reconnect".into(), + "queue_overflow", + )); + } let (events, _) = entry.poll(cursor)?; if events.is_empty() { - if let Some(pinned) = &mut self.pinned { - pinned.attachments.remove(&attachment); - } else { - self.attachment = None; - } + self.attachments.remove(&attachment); return Err(Failure::unavailable("child exited; restore its transcript")); } Ok(object([ @@ -1707,26 +1676,6 @@ impl Actor { _ => Err(Failure::unavailable("child exited; restore its transcript")), } } - fn active_attachment(&self, attachment_id: &str) -> Option<&Attachment> { - if let Some(pinned) = &self.pinned { - pinned - .attachments - .get(attachment_id) - .filter(|a| !a.closing && !a.overflowed) - } else { - self.attachment.as_ref().filter(|a| a.id == attachment_id) - } - } - fn active_attachment_mut(&mut self, attachment_id: &str) -> Option<&mut Attachment> { - if let Some(pinned) = &mut self.pinned { - pinned - .attachments - .get_mut(attachment_id) - .filter(|a| !a.closing && !a.overflowed) - } else { - self.attachment.as_mut().filter(|a| a.id == attachment_id) - } - } fn push_startup_error(&mut self, attachment_id: &str, request_id: Value, error: Value) { if self.active_attachment(attachment_id).is_none() { return; @@ -1759,107 +1708,87 @@ impl Actor { } fn expire_elapsed_client_requests(&mut self) { let now = Instant::now(); - let expired: Vec = self + let mut expired: Vec<(u64, String)> = self .client_requests .iter() - .filter(|(_, req)| req.resolved_reply.is_none() && req.deadline <= now) - .map(|(relay_id, _)| relay_id.clone()) + .filter(|(_, req)| req.deadline <= now) + .map(|(relay_id, req)| (req.seq, relay_id.clone())) .collect(); - for relay_id in expired { - let targets = if let Some(req) = self.client_requests.get_mut(&relay_id) { - req.resolved_reply = Some(( - incoming_transport_closed_reply(req.child_id.clone(), &req.method), - None, - )); - std::mem::take(&mut req.targets) - } else { + expired.sort_by_key(|(seq, _)| *seq); + for (_, relay_id) in expired { + let Some(req) = self.client_requests.remove(&relay_id) else { continue; }; + self.pending_child_replies.push_back(( + incoming_transport_closed_reply(req.child_id, &req.method), + None, + )); let cancel = cancel_request_message(Value::String(relay_id)); - for target in targets { + for target in req.targets { self.push_to_attachment(&target, cancel.clone()); } } } - fn enqueue_immediate_child_reply( + fn queue_child_reply( &mut self, - reply: Value, + message: Value, + charge: Option>, writes: &mpsc::Sender, ) -> bool { if writes.is_closed() { return false; } - if self.deferred_child_replies.is_empty() { + if self.pending_child_replies.is_empty() { match writes.try_send(ChildWrite { withdrawals: Vec::new(), - message: reply, - _charge: None, + message, + _charge: charge, }) { Ok(()) => return true, Err(mpsc::error::TrySendError::Full(write)) => { - self.deferred_child_replies.push_back(write.message); + self.pending_child_replies + .push_back((write.message, write._charge)); return true; } Err(mpsc::error::TrySendError::Closed(_)) => return false, } } - self.deferred_child_replies.push_back(reply); + self.pending_child_replies.push_back((message, charge)); true } - fn next_ready_client_reply(&self) -> Option { - let now = Instant::now(); - self.client_requests - .iter() - .filter(|(_, req)| req.resolved_reply.is_some() || req.deadline <= now) - .min_by_key(|(_, req)| (req.resolved_reply.is_none(), req.deadline, req.seq)) - .map(|(relay_id, _)| relay_id.clone()) + #[cfg(test)] + fn flush_child_replies(&mut self, writes: &mpsc::Sender) { + self.expire_elapsed_client_requests(); + while let Some((message, charge)) = self.pending_child_replies.front() { + let Ok(permit) = writes.try_reserve() else { + break; + }; + let _ = (message, charge); + if let Some((message, charge)) = self.pending_child_replies.pop_front() { + permit.send(ChildWrite { + withdrawals: Vec::new(), + message, + _charge: charge, + }); + } + } } fn next_deadline(&self) -> Option { - let request_deadline = self - .client_requests - .values() - .filter(|req| req.resolved_reply.is_none()) - .map(|req| req.deadline) - .min(); + let request_deadline = self.client_requests.values().map(|req| req.deadline).min(); let lease_deadline = self .pinned - .as_ref() - .and_then(|pinned| pinned.attachments.values().map(|a| a.touched + LEASE).min()); + .is_some() + .then(|| self.attachments.values().map(|a| a.touched + LEASE).min()) + .flatten(); match (request_deadline, lease_deadline) { (Some(a), Some(b)) => Some(a.min(b)), (a, b) => a.or(b), } } - fn flush_client_request_reply(&mut self, relay_id: &str, permit: mpsc::Permit<'_, ChildWrite>) { - self.expire_elapsed_client_requests(); - let Some(req) = self.client_requests.remove(relay_id) else { - return; - }; - if let Some((message, charge)) = req.resolved_reply { - permit.send(ChildWrite { - withdrawals: Vec::new(), - message, - _charge: charge, - }); - return; - } - permit.send(ChildWrite { - withdrawals: Vec::new(), - message: incoming_transport_closed_reply(req.child_id, &req.method), - _charge: None, - }); - let cancel = cancel_request_message(Value::String(relay_id.to_owned())); - for target in req.targets { - self.push_to_attachment(&target, cancel.clone()); - } - } fn cancel_all_relayed_client_requests(&mut self) -> bool { let drained = std::mem::take(&mut self.client_requests); let mut notified = false; for (relay_id, req) in drained { - if req.resolved_reply.is_some() { - continue; - } let cancel = cancel_request_message(Value::String(relay_id)); for target in req.targets { notified |= self.push_to_attachment(&target, cancel.clone()); @@ -1886,7 +1815,7 @@ impl Actor { ), ]) }; - let live_targets = self.live_attachment_ids(); + let live_targets = self.live_relay_targets(&method); if live_targets.is_empty() { return Some(no_services()); } @@ -1903,10 +1832,7 @@ impl Actor { ), ])); } - let Some(seq) = self.next_relay_id.checked_add(1) else { - return Some(no_services()); - }; - self.next_relay_id = seq; + let seq = NEXT_RELAY_ID.fetch_add(1, Ordering::Relaxed); let relay_id = format!("kit-gw-req-{seq}"); let timeout = self.client_request_timeout; let relayed = object([ @@ -1933,17 +1859,15 @@ impl Actor { params, targets: delivered, deadline: Instant::now() + timeout, - had_client_error: false, + last_failure: None, had_detached_target: false, - resolved_reply: None, }, ); None } fn cancel_relayed_client_request(&mut self, child_request_id: &Value) { let Some(relay_id) = self.client_requests.iter().find_map(|(relay_id, req)| { - (req.resolved_reply.is_none() && &req.child_id == child_request_id) - .then(|| relay_id.clone()) + (&req.child_id == child_request_id).then(|| relay_id.clone()) }) else { return; }; @@ -1955,16 +1879,18 @@ impl Actor { self.push_to_attachment(&target, cancel.clone()); } } + #[allow(clippy::too_many_arguments)] fn prepare_startup( &self, attachment_id: &str, + elicitation_form: bool, existing_events: usize, existing_bytes: usize, result: Value, request_id: Value, replay: &ReplayMode, ) -> Result { - let pending_requests = self.pending_request_messages(); + let pending_requests = self.pending_request_messages(elicitation_form); let pending_bytes: usize = pending_requests .iter() .map(|(_, m)| m.to_string().len()) @@ -2021,14 +1947,15 @@ impl Actor { request_id: Value, replay: &ReplayMode, ) { - let Some((existing_events, existing_bytes)) = self + let Some((elicitation_form, existing_events, existing_bytes)) = self .active_attachment(attachment_id) - .map(|a| (a.live_events(), a.live_bytes())) + .map(|a| (a.elicitation_form, a.live_events(), a.live_bytes())) else { return; }; match self.prepare_startup( attachment_id, + elicitation_form, existing_events, existing_bytes, result, @@ -2095,18 +2022,8 @@ impl Actor { } _ => {} } - if let Some(pinned) = &self.pinned { - let targets: Vec = pinned - .attachments - .values() - .filter(|a| a.live && !a.closing && !a.overflowed) - .map(|a| a.id.clone()) - .collect(); - for target in targets { - self.push_pinned_attachment(&target, message.clone()); - } - } else if self.attachment.as_ref().is_some_and(|a| a.live) { - self.emit(message); + for target in self.live_update_targets() { + self.push_to_attachment(&target, message.clone()); } } else if let Some(id) = message["id"].as_u64() && let Some(pending) = self.pending.remove(&id) @@ -2136,58 +2053,39 @@ impl Actor { _ => (), } } - if self.pinned.is_some() { - let is_startup = - matches!(pending.method.as_str(), "session/new" | "session/resume"); - if is_startup { - let waiters = if let Some(pinned) = &mut self.pinned { - pinned.startup_driver = None; - std::mem::take(&mut pinned.waiting_startups) - } else { - Vec::new() - }; - let recipients = - std::iter::once((pending.attachment, pending.original, pending.replay)) - .chain( - waiters - .into_iter() - .map(|w| (w.attachment, w.request_id, w.replay)), - ); - if let Some(result) = message.get("result").cloned() { - for (att, req_id, replay) in recipients { - self.deliver_startup(&att, result.clone(), req_id, &replay); - } - } else { - let error_obj = message.get("error").cloned().unwrap_or_else(|| { - object([ - ("code", (-32000).into()), - ("message", "session startup failed".into()), - ]) - }); - for (att, req_id, _) in recipients { - self.push_startup_error(&att, req_id, error_obj.clone()); - } + let is_startup = matches!(pending.method.as_str(), "session/new" | "session/resume"); + if is_startup && self.pinned.is_some() { + let waiters = if let Some(pinned) = &mut self.pinned { + pinned.startup_driver = None; + std::mem::take(&mut pinned.waiting_startups) + } else { + Vec::new() + }; + let recipients = + std::iter::once((pending.attachment, pending.original, pending.replay)).chain( + waiters + .into_iter() + .map(|w| (w.attachment, w.request_id, w.replay)), + ); + if let Some(result) = message.get("result").cloned() { + for (att, req_id, replay) in recipients { + self.deliver_startup(&att, result.clone(), req_id, &replay); + } + } else { + let error_obj = message.get("error").cloned().unwrap_or_else(|| { + object([ + ("code", (-32000).into()), + ("message", "session startup failed".into()), + ]) + }); + for (att, req_id, _) in recipients { + self.push_startup_error(&att, req_id, error_obj.clone()); } - } else if !pending.orphaned - && self.pinned.as_ref().is_some_and(|p| { - p.attachments - .get(&pending.attachment) - .is_some_and(|a| !a.closing && !a.overflowed) - }) - { - message["id"] = pending.original; - self.push_pinned_attachment(&pending.attachment, message); } return None; } - if self - .attachment - .as_ref() - .is_some_and(|a| a.id == pending.attachment) - { - if matches!(pending.method.as_str(), "session/new" | "session/resume") - && let Some(result) = message.get("result").cloned() - { + if !pending.orphaned && self.active_attachment(&pending.attachment).is_some() { + if is_startup && let Some(result) = message.get("result").cloned() { self.deliver_startup( &pending.attachment, result, @@ -2197,7 +2095,7 @@ impl Actor { return None; } message["id"] = pending.original; - self.emit(message); + self.push_to_attachment(&pending.attachment, message); } } None @@ -2616,6 +2514,7 @@ impl Actor { replace, replay: replay_mode, startup, + elicitation_form, .. } = request { @@ -2695,9 +2594,9 @@ impl Actor { } if !replace && self - .attachment - .as_ref() - .is_some_and(|a| a.touched.elapsed() < LEASE) + .attachments + .values() + .any(|a| a.touched.elapsed() < LEASE) { return Err(Failure::conflict( "session already has a controlling attachment", @@ -2709,23 +2608,32 @@ impl Actor { )); } let id = crate::session::new_id(); - let attachment = Attachment::new(id.clone()); + let attachment = Attachment::new(id.clone(), elicitation_form); let prepared = if let (Some(startup), Some(result)) = (startup, self.session_result.clone()) { let request_id = startup .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - Some(self.prepare_startup(&id, 0, 0, result, request_id, &replay_mode)?) + Some(self.prepare_startup( + &id, + elicitation_form, + 0, + 0, + result, + request_id, + &replay_mode, + )?) } else { None }; let started = prepared.is_some(); // No fallible work after the ownership commit. The previous controller // survives every replay/snapshot preparation failure. - if let Some(previous) = self.attachment.take() { - self.mark_withdrawals(&previous.id); - self.mark_target_detached(&previous.id); + let previous_ids: Vec = self.attachments.drain().map(|(id, _)| id).collect(); + for prev_id in previous_ids { + self.mark_withdrawals(&prev_id); + self.mark_target_detached(&prev_id); self.flush_withdrawals(writes); } self.committed_owner = Some(CommittedOwner { @@ -2733,7 +2641,7 @@ impl Actor { recovery_id, recovery_attempt, }); - self.attachment = Some(attachment); + self.attachments.insert(id.clone(), attachment); if let Some(prepared) = prepared { self.apply_startup(&id, prepared); } @@ -2750,9 +2658,9 @@ impl Actor { _ => return Err(Failure::bad("invalid actor operation")), }; let attachment = self - .attachment - .as_mut() - .filter(|a| a.id == *token && a.touched.elapsed() < LEASE) + .attachments + .get_mut(token) + .filter(|a| a.touched.elapsed() < LEASE) .ok_or_else(|| { Failure( StatusCode::CONFLICT, @@ -2763,7 +2671,7 @@ impl Actor { attachment.touched = Instant::now(); match request { Request::Detach { attachment, .. } => { - self.attachment = None; + self.attachments.remove(&attachment); self.mark_withdrawals(&attachment); self.mark_target_detached(&attachment); self.flush_withdrawals(writes); @@ -2781,103 +2689,7 @@ impl Actor { message, charge, .. - } => { - if !message.is_object() || message["jsonrpc"] != "2.0" { - return Err(Failure::bad("invalid ACP message")); - } - if is_client_response(&message) { - return self.handle_client_response(&attachment, message, charge, writes); - } - let method = message["method"] - .as_str() - .ok_or_else(|| Failure::bad("ACP method required"))? - .to_owned(); - let original = message.get("id").cloned(); - self.validate_session_message(&method, &message)?; - if method == "$/cancel_request" { - return self.handle_cancel_request( - &attachment, - original.as_ref(), - &message, - closing, - writes, - ); - } - if !is_supported_acp_method(&method, true) { - return Err(Failure::bad( - "ACP method is not supported by the gateway; disconnect to detach", - )); - } - if method == "session/close" && original.is_none() { - return Err(Failure::bad("session close requires a request id")); - } - let startup = matches!(method.as_str(), "session/new" | "session/resume"); - let replay = if startup { - if original.is_none() { - return Err(Failure::bad("session startup requires a request id")); - } - if self.attachment.as_ref().is_some_and(|a| a.live) { - return Err(Failure::conflict("attachment already opened its session")); - } - parse_replay_mode( - message["params"].get("replayFrom"), - &self.id, - false, - method == "session/new", - )? - } else { - ReplayMode::None - }; - if let Some(id) = &original - && self - .pending - .values() - .any(|p| p.attachment == attachment && p.original == *id) - { - return Err(Failure::conflict("duplicate pending request id")); - } - if startup && matches!(replay, ReplayMode::Start) && !self.replay_complete { - return Err(Failure::replay("full live replay is unavailable")); - } - let cached = match method.as_str() { - "initialize" => self.initialized.clone(), - "session/new" | "session/resume" => self.session_result.clone(), - _ => None, - }; - if let Some(result) = cached { - if startup { - if has_nonempty_mcp_servers(&message) { - return Err(Failure::conflict(RESIDENT_MCP_CONFLICT)); - } - let Some(id) = original else { - return Err(Failure::bad("session startup requires a request id")); - }; - let (existing_events, existing_bytes) = self - .attachment - .as_ref() - .map_or((0, 0), |a| (a.live_events(), a.live_bytes())); - let prepared = self.prepare_startup( - &attachment, - existing_events, - existing_bytes, - result, - id, - &replay, - )?; - self.apply_startup(&attachment, prepared); - } else if let Some(id) = original { - self.emit(object([ - ("jsonrpc", "2.0".into()), - ("id", id), - ("result", result), - ])); - } - return Ok(object([])); - } - self.enqueue_child_message( - attachment, original, method, replay, message, charge, writes, - ) - } + } => self.send_message(attachment, message, charge, closing, writes), _ => Err(Failure::bad("invalid actor operation")), } } @@ -2890,6 +2702,7 @@ impl Actor { if let Request::Attach { replay: replay_mode, startup, + elicitation_form, .. } = request { @@ -2911,7 +2724,7 @@ impl Actor { )); } let id = crate::session::new_id(); - let attachment = Attachment::new(id.clone()); + let attachment = Attachment::new(id.clone(), elicitation_form); let started = if let (Some(startup_msg), Some(result)) = (startup.as_ref(), self.session_result.clone()) { @@ -2919,10 +2732,16 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - let prepared = self.prepare_startup(&id, 0, 0, result, request_id, &replay_mode)?; - if let Some(pinned) = &mut self.pinned { - pinned.attachments.insert(id.clone(), attachment); - } + let prepared = self.prepare_startup( + &id, + elicitation_form, + 0, + 0, + result, + request_id, + &replay_mode, + )?; + self.attachments.insert(id.clone(), attachment); self.apply_startup(&id, prepared); true } else if let Some(startup_msg) = startup @@ -2932,31 +2751,23 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; - if self - .pinned - .as_ref() - .is_some_and(|p| p.waiting_startups.len() >= MAX_WAITING_STARTUPS) - { - return Err(Failure::unavailable( - "too many concurrent session startups; retry", - )); - } if let Some(pinned) = &mut self.pinned { pinned.waiting_startups.push(WaitingStartup { attachment: id.clone(), request_id, replay: replay_mode, }); - pinned.attachments.insert(id.clone(), attachment); } + self.attachments.insert(id.clone(), attachment); true } else { - if let Some(pinned) = &mut self.pinned { - if self.session_result.is_none() && pinned.startup_driver.is_none() { - pinned.startup_driver = Some(id.clone()); - } - pinned.attachments.insert(id.clone(), attachment); + if let Some(pinned) = &mut self.pinned + && self.session_result.is_none() + && pinned.startup_driver.is_none() + { + pinned.startup_driver = Some(id.clone()); } + self.attachments.insert(id.clone(), attachment); false }; return Ok(object([ @@ -2978,12 +2789,7 @@ impl Actor { return Ok(object([])); } - let Some(overflowed) = self - .pinned - .as_ref() - .and_then(|p| p.attachments.get(&token)) - .map(|a| a.overflowed) - else { + let Some(overflowed) = self.attachments.get(&token).map(|a| a.overflowed) else { return Err(Failure( StatusCode::CONFLICT, "attachment is not active; reconnect".into(), @@ -2991,10 +2797,8 @@ impl Actor { )); }; if overflowed { - if matches!(request, Request::Poll { .. }) - && let Some(pinned) = &mut self.pinned - { - pinned.attachments.remove(&token); + if matches!(request, Request::Poll { .. }) { + self.attachments.remove(&token); } return Err(Failure( StatusCode::CONFLICT, @@ -3005,10 +2809,7 @@ impl Actor { match request { Request::Poll { cursor, .. } => { - let Some(pinned) = &mut self.pinned else { - return Err(Failure::unavailable("pinned state missing")); - }; - let Some(attachment) = pinned.attachments.get_mut(&token) else { + let Some(attachment) = self.attachments.get_mut(&token) else { return Err(Failure( StatusCode::CONFLICT, "attachment is not active; reconnect".into(), @@ -3019,7 +2820,7 @@ impl Actor { let (events, drained) = attachment.poll(cursor)?; let closed = (self.closed || attachment.closing) && drained; if closed && attachment.closing { - pinned.attachments.remove(&token); + self.attachments.remove(&token); } Ok(object([ ("closed", closed.into()), @@ -3032,146 +2833,253 @@ impl Actor { charge, .. } => { - if let Some(pinned) = &mut self.pinned - && let Some(a) = pinned.attachments.get_mut(&attachment) - { + if let Some(a) = self.attachments.get_mut(&attachment) { if a.closing { return Err(Failure::conflict("attachment is closing")); } a.touched = Instant::now(); } - if !message.is_object() || message["jsonrpc"] != "2.0" { - return Err(Failure::bad("invalid ACP message")); + self.send_message(attachment, message, charge, false, writes) + } + _ => Err(Failure::bad("invalid actor operation")), + } + } + + fn send_message( + &mut self, + attachment: String, + message: Value, + charge: Option>, + closing: bool, + writes: &mpsc::Sender, + ) -> ResultValue { + if !message.is_object() || message["jsonrpc"] != "2.0" { + return Err(Failure::bad("invalid ACP message")); + } + if is_client_response(&message) { + return self.handle_client_response(&attachment, message, charge, writes); + } + let method = message["method"] + .as_str() + .ok_or_else(|| Failure::bad("ACP method required"))? + .to_owned(); + let original = message.get("id").cloned(); + self.validate_session_message(&method, &message)?; + if method == "$/cancel_request" { + return self.handle_cancel_request( + &attachment, + original.as_ref(), + &message, + closing, + writes, + ); + } + let pinned = self.pinned.is_some(); + if method == "session/close" { + let Some(id) = original.clone() else { + return Err(Failure::bad("session close requires a request id")); + }; + if pinned { + // In pinned mode, session/close detaches ONLY this client and never ends the session. + self.retire_pinned_attachment(&attachment, RetireMode::Closing); + self.push_to_attachment( + &attachment, + object([ + ("jsonrpc", "2.0".into()), + ("id", id), + ("result", object([])), + ]), + ); + return Ok(object([])); + } + } + if !is_supported_acp_method(&method, !pinned) { + return Err(Failure::bad( + "ACP method is not supported by the gateway; disconnect to detach", + )); + } + let startup = matches!(method.as_str(), "session/new" | "session/resume"); + let replay = if startup { + if original.is_none() { + return Err(Failure::bad("session startup requires a request id")); + } + if (pinned && self.session_result.is_some()) + || self.active_attachment(&attachment).is_some_and(|a| a.live) + { + return Err(Failure::conflict("attachment already opened its session")); + } + parse_replay_mode( + message["params"].get("replayFrom"), + &self.id, + pinned, + method == "session/new", + )? + } else { + ReplayMode::None + }; + if let Some(id) = &original + && self + .pending + .values() + .any(|p| !p.orphaned && p.attachment == attachment && p.original == *id) + { + return Err(Failure::conflict("duplicate pending request id")); + } + if pinned { + // Re-parent an orphaned held prompt matching the same idempotencyKey + // instead of forwarding a duplicate attempt to the child. + if method == "session/prompt" + && let Some(id) = &original + && let Some(key) = message["params"] + .get("idempotencyKey") + .and_then(Value::as_str) + .filter(|k| !k.is_empty()) + && let Some(orphan_serial) = self + .pending + .iter() + .filter(|(_, p)| { + p.orphaned + && !p.withdrawal_pending + && p.method == "session/prompt" + && p.idempotency_key.as_deref() == Some(key) + }) + .map(|(&serial, _)| serial) + .min() + { + let attachment_active = self + .pending + .values() + .filter(|p| !p.orphaned && p.attachment == attachment) + .count(); + if attachment_active >= MAX_PENDING_PER_ATTACHMENT { + return Err(Failure::unavailable( + "too many pending ACP requests for attachment", + )); + } + let shared_active = self.pending.values().filter(|p| !p.orphaned).count(); + if shared_active >= MAX_PENDING_SHARED { + return Err(Failure::unavailable("too many pending ACP requests")); } - // Client-to-agent JSON-RPC response for a relayed request. - if is_client_response(&message) { - return self.handle_client_response(&attachment, message, charge, writes); + if let Some(entry) = self.pending.get_mut(&orphan_serial) { + entry.attachment = attachment; + entry.original = id.clone(); + entry.orphaned = false; } - let method = message["method"] - .as_str() - .ok_or_else(|| Failure::bad("ACP method required"))? - .to_owned(); - let original = message.get("id").cloned(); - self.validate_session_message(&method, &message)?; - if method == "$/cancel_request" { - return self.handle_cancel_request( + return Ok(object([])); + } + if method == "initialize" + && let Some(result) = self.initialized.clone() + { + if let Some(id) = original { + self.push_to_attachment( &attachment, - original.as_ref(), - &message, - false, - writes, + object([("jsonrpc", "2.0".into()), ("id", id), ("result", result)]), ); } - // In pinned mode, session/close detaches ONLY this client and never ends the session. - if method == "session/close" { + return Ok(object([])); + } + } else { + if startup && matches!(replay, ReplayMode::Start) && !self.replay_complete { + return Err(Failure::replay("full live replay is unavailable")); + } + let cached = match method.as_str() { + "initialize" => self.initialized.clone(), + "session/new" | "session/resume" => self.session_result.clone(), + _ => None, + }; + if let Some(result) = cached { + if startup { + if has_nonempty_mcp_servers(&message) { + return Err(Failure::conflict(RESIDENT_MCP_CONFLICT)); + } let Some(id) = original else { - return Err(Failure::bad("session close requires a request id")); + return Err(Failure::bad("session startup requires a request id")); }; - self.retire_pinned_attachment(&attachment, RetireMode::Closing); - self.push_pinned_attachment( + let (elicitation_form, existing_events, existing_bytes) = self + .active_attachment(&attachment) + .map_or((false, 0, 0), |a| { + (a.elicitation_form, a.live_events(), a.live_bytes()) + }); + let prepared = self.prepare_startup( &attachment, - object([ - ("jsonrpc", "2.0".into()), - ("id", id), - ("result", object([])), - ]), + elicitation_form, + existing_events, + existing_bytes, + result, + id, + &replay, + )?; + self.apply_startup(&attachment, prepared); + } else if let Some(id) = original { + self.push_to_attachment( + &attachment, + object([("jsonrpc", "2.0".into()), ("id", id), ("result", result)]), ); - return Ok(object([])); } - if !is_supported_acp_method(&method, false) { - return Err(Failure::bad( - "ACP method is not supported by the gateway; disconnect to detach", - )); - } - let startup = matches!(method.as_str(), "session/new" | "session/resume"); - let replay = if startup { - if original.is_none() { - return Err(Failure::bad("session startup requires a request id")); - } - if self.session_result.is_some() - || self - .pinned - .as_ref() - .and_then(|p| p.attachments.get(&attachment)) - .is_some_and(|a| a.live) - { - return Err(Failure::conflict("attachment already opened its session")); - } - parse_replay_mode( - message["params"].get("replayFrom"), - &self.id, - true, - method == "session/new", - )? - } else { - ReplayMode::None - }; - if let Some(id) = &original - && self - .pending - .values() - .any(|p| !p.orphaned && p.attachment == attachment && p.original == *id) - { - return Err(Failure::conflict("duplicate pending request id")); - } - // Re-parent an orphaned held prompt matching the same idempotencyKey - // instead of forwarding a duplicate attempt to the child. - if method == "session/prompt" - && let Some(id) = &original - && let Some(key) = message["params"] - .get("idempotencyKey") - .and_then(Value::as_str) - .filter(|k| !k.is_empty()) - && let Some(orphan_serial) = self - .pending - .iter() - .filter(|(_, p)| { - p.orphaned - && !p.withdrawal_pending - && p.method == "session/prompt" - && p.idempotency_key.as_deref() == Some(key) - }) - .map(|(&serial, _)| serial) - .min() - { - let attachment_active = self - .pending - .values() - .filter(|p| !p.orphaned && p.attachment == attachment) - .count(); - if attachment_active >= MAX_PENDING_PER_ATTACHMENT { - return Err(Failure::unavailable( - "too many pending ACP requests for attachment", - )); - } - let shared_active = self.pending.values().filter(|p| !p.orphaned).count(); - if shared_active >= MAX_PENDING_SHARED { - return Err(Failure::unavailable("too many pending ACP requests")); - } - if let Some(entry) = self.pending.get_mut(&orphan_serial) { - entry.attachment = attachment; - entry.original = id.clone(); - entry.orphaned = false; - } - return Ok(object([])); - } - if method == "initialize" - && let Some(result) = self.initialized.clone() - { - if let Some(id) = original { - self.push_pinned_attachment( - &attachment, - object([("jsonrpc", "2.0".into()), ("id", id), ("result", result)]), - ); - } - return Ok(object([])); - } - self.enqueue_child_message( - attachment, original, method, replay, message, charge, writes, - ) + return Ok(object([])); } - _ => Err(Failure::bad("invalid actor operation")), } + self.enqueue_child_message( + attachment, original, method, replay, message, charge, writes, + ) + } + + #[allow(clippy::too_many_arguments)] + fn fail_client_target( + &mut self, + relay_id: &str, + attachment: &str, + unsupported: bool, + failure_reason: &'static str, + failure_message: &'static str, + charge: Option>, + writes: &mpsc::Sender, + ) { + let should_resolve = if let Some(req) = self.client_requests.get_mut(relay_id) { + req.targets.remove(attachment); + if !unsupported { + req.last_failure = Some((failure_reason, failure_message)); + } + req.targets.is_empty() && !req.had_detached_target + } else { + false + }; + if !should_resolve { + return; + } + let Some(req) = self.client_requests.remove(relay_id) else { + return; + }; + let reply = if let Some((reason, msg)) = req.last_failure { + object([ + ("jsonrpc", "2.0".into()), + ("id", req.child_id), + ( + "error", + object([ + ("code", (-32603).into()), + ("message", msg.into()), + ( + "data", + object([("reason", reason.into()), ("method", req.method.into())]), + ), + ]), + ), + ]) + } else { + object([ + ("jsonrpc", "2.0".into()), + ("id", req.child_id), + ( + "error", + object([ + ("code", (-32601).into()), + ("message", "gateway has no client-side services".into()), + ]), + ), + ]) + }; + let _ = self.queue_child_reply(reply, charge, writes); } fn handle_client_response( @@ -3184,18 +3092,13 @@ impl Actor { let Some(relay_id) = message["id"].as_str().map(str::to_owned) else { return Ok(object([])); }; - let Some((method, params, is_target)) = self - .client_requests - .get(&relay_id) - .filter(|req| req.resolved_reply.is_none()) - .map(|req| { - ( - req.method.clone(), - req.params.clone(), - req.targets.contains(attachment), - ) - }) - else { + let Some((method, params, is_target)) = self.client_requests.get(&relay_id).map(|req| { + ( + req.method.clone(), + req.params.clone(), + req.targets.contains(attachment), + ) + }) else { // Already resolved, cancelled, or expired; ignore late duplicate race. return Ok(object([])); }; @@ -3204,64 +3107,55 @@ impl Actor { } if let Some(error) = message.get("error").filter(|v| v.is_object()) { let is_unsupported = error["code"].as_i64() == Some(-32601); - let mut should_decline = None; - if let Some(req) = self.client_requests.get_mut(&relay_id) { - req.targets.remove(attachment); - if !is_unsupported { - // Client-side failure: drop only this target and keep pending - // for remaining targets or a late joiner until timeout. - req.had_client_error = true; - } else if req.targets.is_empty() - && !req.had_client_error - && !req.had_detached_target - { - let reply = object([ - ("jsonrpc", "2.0".into()), - ("id", req.child_id.clone()), - ( - "error", - object([ - ("code", (-32601).into()), - ("message", "gateway has no client-side services".into()), - ]), - ), - ]); - req.resolved_reply = Some((reply, charge)); - should_decline = Some(relay_id.clone()); - } - } - if let Some(id) = should_decline - && let Ok(permit) = writes.try_reserve() - { - self.flush_client_request_reply(&id, permit); - } + self.fail_client_target( + &relay_id, + attachment, + is_unsupported, + "client_error", + "client failed to answer relayed request", + charge, + writes, + ); return Ok(object([])); } let Some(result) = message.get("result") else { + self.fail_client_target( + &relay_id, + attachment, + false, + "invalid_client_response", + "client returned an invalid response for relayed request", + None, + writes, + ); return Err(Failure::bad("invalid client response")); }; if !is_valid_client_result(&method, ¶ms, result) { + self.fail_client_target( + &relay_id, + attachment, + false, + "invalid_client_response", + "client returned an invalid response for relayed request", + None, + writes, + ); return Err(Failure::bad("invalid response for relayed client request")); } - let mut other_targets = Vec::new(); - if let Some(req) = self.client_requests.get_mut(&relay_id) { - let reply = object([ - ("jsonrpc", "2.0".into()), - ("id", req.child_id.clone()), - ("result", result.clone()), - ]); - req.resolved_reply = Some((reply, charge)); - other_targets = std::mem::take(&mut req.targets) - .into_iter() - .filter(|target| target != attachment) - .collect(); - } - if let Ok(permit) = writes.try_reserve() { - self.flush_client_request_reply(&relay_id, permit); - } + let Some(req) = self.client_requests.remove(&relay_id) else { + return Ok(object([])); + }; + let reply = object([ + ("jsonrpc", "2.0".into()), + ("id", req.child_id), + ("result", result.clone()), + ]); + let _ = self.queue_child_reply(reply, charge, writes); let cancel = cancel_request_message(Value::String(relay_id)); - for target in other_targets { - self.push_to_attachment(&target, cancel.clone()); + for target in req.targets { + if target != attachment { + self.push_to_attachment(&target, cancel.clone()); + } } Ok(object([])) } @@ -3281,17 +3175,19 @@ fn is_client_response(message: &Value) -> bool { || message.get("error").is_some_and(Value::is_object)) } +fn declares_form_elicitation(client_caps: Option<&Value>) -> bool { + client_caps + .and_then(|caps| caps.get("elicitation")) + .and_then(|elicitation| elicitation.get("form")) + .is_some_and(Value::is_object) +} + fn forwarded_client_capabilities(client_caps: Option<&Value>, pinned: bool) -> Value { // In pinned mode, many heterogeneous clients share one child initialized once, // so always advertise form elicitation (relay handles declines). In default // mode, forward only relayable capabilities declared by the connecting client // (stripping host-only auth, browser-callback url elicitation, fs, terminal). - let advertise_form = pinned - || client_caps - .and_then(|caps| caps.get("elicitation")) - .and_then(|elicitation| elicitation.get("form")) - .is_some_and(Value::is_object); - if advertise_form { + if pinned || declares_form_elicitation(client_caps) { object([("elicitation", object([("form", object([]))]))]) } else { object([]) @@ -3372,70 +3268,7 @@ fn is_valid_client_result(method: &str, params: &Value, result: &Value) -> bool wire::ElicitationAction::Accept(accept) => { let is_form = params.get("mode").and_then(Value::as_str) == Some("form") || params.get("requestedSchema").is_some(); - if is_form { - let Some(content) = &accept.content else { - return false; - }; - if let Some(required) = params - .get("requestedSchema") - .and_then(|schema| schema.get("required")) - .and_then(Value::as_array) - && required - .iter() - .filter_map(Value::as_str) - .any(|key| !content.contains_key(key)) - { - return false; - } - if let Some(properties) = params - .get("requestedSchema") - .and_then(|schema| schema.get("properties")) - .and_then(Value::as_object) - { - for (key, value) in content { - if let Some(expected_type) = properties - .get(key) - .and_then(|prop| prop.get("type")) - .and_then(Value::as_str) - { - let valid_type = match expected_type { - "string" => { - matches!( - value, - wire::ElicitationContentValue::String(_) - ) - } - "integer" => { - matches!( - value, - wire::ElicitationContentValue::Integer(_) - ) - } - "number" => matches!( - value, - wire::ElicitationContentValue::Integer(_) - | wire::ElicitationContentValue::Number(_) - ), - "boolean" => { - matches!( - value, - wire::ElicitationContentValue::Boolean(_) - ) - } - "array" => matches!( - value, - wire::ElicitationContentValue::StringArray(_) - ), - _ => true, - }; - if !valid_type { - return false; - } - } - } - } - } - true + !is_form || accept.content.is_some() } wire::ElicitationAction::Decline | wire::ElicitationAction::Cancel => true, wire::ElicitationAction::Other(other) => !other.action.trim().is_empty(), diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 073e9792..23ccb845 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -405,6 +405,11 @@ impl Connection { .get(&session) .cloned() .ok_or_else(|| Failure::unavailable("resident child exited"))?; + let elicitation_form = declares_form_elicitation( + self.initialize + .as_ref() + .and_then(|(init, _)| init["params"].get("capabilities")), + ); // Pin the same resident actor for claim and subsequent control. let (reply, accepted) = oneshot::channel(); entry @@ -415,6 +420,7 @@ impl Connection { replace: resume && pinned.is_none(), replay: replay_mode, startup: Some(message.clone()), + elicitation_form, }, reply, }) @@ -660,27 +666,19 @@ impl Connection { let relay_id = message.get("id").and_then(Value::as_str).map(str::to_owned); let target_session = relay_id .as_deref() - .and_then(|id| self.relay_routes.get(id).cloned()) + .and_then(|id| self.relay_routes.remove(id)) .or_else(|| self.gateway.pinned_session.clone()); if let Some(session_id) = target_session.as_deref() && let Some(control) = self.controls.get_mut(session_id) + && let Err(error) = control.send(message, Arc::clone(&charged_frame)).await { - match control.send(message, Arc::clone(&charged_frame)).await { - Ok(_) => { - if let Some(id) = relay_id.as_deref() { - self.relay_routes.remove(id); - } - } - Err(error) => { - tracing::warn!( - session = %session_id, - relay_id = relay_id.as_deref().unwrap_or(""), - code = error.2, - "rejected client response for relayed request: {}", - error.1 - ); - } - } + tracing::warn!( + session = %session_id, + relay_id = relay_id.as_deref().unwrap_or(""), + code = error.2, + "rejected client response for relayed request: {}", + error.1 + ); } self.flush(&channel).await?; drop(charged_frame); @@ -1144,7 +1142,7 @@ mod tests { session: session.into(), attachment: attached["attachment"].as_str().unwrap().into(), entry: Entry { root: actor.root.clone(), sender, stopped }, - cursor: actor.attachment.as_ref().unwrap().next, + cursor: actor.attachments.values().next().unwrap().next, closed: false, pending: HashMap::new(), }); diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 9f28920a..a7fbc46c 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -726,6 +726,7 @@ async fn pinned_overflow_drops_only_one_attachment_without_withdrawing_or_affect replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-overflow"}})), + elicitation_form: true, }, &writes, ) @@ -740,6 +741,7 @@ async fn pinned_overflow_drops_only_one_attachment_without_withdrawing_or_affect replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-overflow"}})), + elicitation_form: true, }, &writes, ) @@ -958,6 +960,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-replay","replayFrom":{"type":"_kit_current_turn"}}})), + elicitation_form: true, }, &writes, ) @@ -965,7 +968,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .as_str() .unwrap() .to_owned(); - let events_turn: Vec = actor.pinned.as_ref().unwrap().attachments[&a_turn] + let events_turn: Vec = actor.attachments[&a_turn] .events .iter() .map(|(_, m)| m.clone()) @@ -1001,6 +1004,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio }, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-replay","replayFrom":{"type":"_kit_message","sessionId":"pinned-replay","messageId":"u-1"}}})), + elicitation_form: true, }, &writes, ) @@ -1008,7 +1012,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .as_str() .unwrap() .to_owned(); - let events_msg: Vec = actor.pinned.as_ref().unwrap().attachments[&a_msg] + let events_msg: Vec = actor.attachments[&a_msg] .events .iter() .map(|(_, m)| m.clone()) @@ -1030,6 +1034,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio }, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), + elicitation_form: true, }, &writes, ) @@ -1066,6 +1071,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio replay: ReplayMode::Start, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), + elicitation_form: true, }, &writes, ) @@ -1080,6 +1086,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":5,"method":"session/resume","params":{"sessionId":"pinned-replay"}})), + elicitation_form: true, }, &writes, ) @@ -1087,7 +1094,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio .as_str() .unwrap() .to_owned(); - let events_turn3: Vec = actor.pinned.as_ref().unwrap().attachments[&a_turn3] + let events_turn3: Vec = actor.attachments[&a_turn3] .events .iter() .map(|(_, m)| m.clone()) @@ -1145,7 +1152,9 @@ for line in sys.stdin: "#; harness.child_source("pinned-ask", source, &[]).await; - let mut c1 = harness.connect("ui-1").await; + let mut c1 = harness + .connect_with_capabilities("ui-1", json!({"elicitation": {"form": {}}})) + .await; let mut s1 = c1.open_session_stream("pinned-ask").await; assert_eq!( c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-ask"}})) @@ -1154,7 +1163,9 @@ for line in sys.stdin: ); let _ = s1.next_matching(|e| e["id"] == 1).await; - let c2 = harness.connect("ui-2").await; + let c2 = harness + .connect_with_capabilities("ui-2", json!({"elicitation": {"form": {}}})) + .await; let mut s2 = c2.open_session_stream("pinned-ask").await; assert_eq!( c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-ask"}})) @@ -1242,6 +1253,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":req_id,"method":"session/resume","params":{"sessionId":"pinned-req"}})), + elicitation_form: true, }, &writes, ) @@ -1358,7 +1370,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( assert!(actor.client_requests.contains_key(&relay_reload)); // Reattach as c3 -> receives pending ask-reload right after startup and answers it! let c3 = attach(&mut actor, 3); - let c3_events: Vec = actor.pinned.as_ref().unwrap().attachments[&c3] + let c3_events: Vec = actor.attachments[&c3] .events .iter() .map(|(_, m)| m.clone()) @@ -1392,12 +1404,10 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( .is_none() ); let relay_timeout = actor.client_requests.keys().next().unwrap().clone(); - assert!(actor.next_ready_client_reply().is_none()); + assert!(actor.pending_child_replies.is_empty()); tokio::time::advance(timeout).await; - let expired_id = actor.next_ready_client_reply().unwrap(); - assert_eq!(expired_id, relay_timeout); - let permit = writes.try_reserve().unwrap(); - actor.flush_client_request_reply(&expired_id, permit); + actor.flush_child_replies(&writes); + assert!(actor.client_requests.is_empty()); let timeout_reply = child_rx.try_recv().unwrap().message; assert_eq!(timeout_reply["id"], "ask-timeout"); @@ -1414,12 +1424,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( timeout_reply["error"]["data"]["method"], "elicitation/create" ); - let c3_last = actor.pinned.as_ref().unwrap().attachments[&c3] - .events - .back() - .unwrap() - .1 - .clone(); + let c3_last = actor.attachments[&c3].events.back().unwrap().1.clone(); assert_eq!(c3_last["method"], "$/cancel_request"); assert_eq!(c3_last["params"]["requestId"], relay_timeout); @@ -1441,12 +1446,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( "params": { "requestId": "ask-agent-cancel" } })); assert!(actor.client_requests.is_empty()); - let c3_cancel = actor.pinned.as_ref().unwrap().attachments[&c3] - .events - .back() - .unwrap() - .1 - .clone(); + let c3_cancel = actor.attachments[&c3].events.back().unwrap().1.clone(); assert_eq!(c3_cancel["method"], "$/cancel_request"); assert_eq!(c3_cancel["params"]["requestId"], relay_cancel); } @@ -1528,6 +1528,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), + elicitation_form: true, }, &writes, ) @@ -1574,6 +1575,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), + elicitation_form: true, }, &writes, ) @@ -1604,7 +1606,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro .unwrap(); assert_eq!(polled["closed"], true); assert!( - !actor.pinned.as_ref().unwrap().attachments.contains_key(&a2), + !actor.attachments.contains_key(&a2), "closing attachment must be reclaimed on final Poll" ); @@ -1616,6 +1618,7 @@ fn pinned_audit_edge_cases_send_before_poll_overflow_close_cleanup_and_null_erro replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"pinned-edge"}})), + elicitation_form: true, }, &writes, ) @@ -1691,6 +1694,7 @@ async fn pinned_session_new_without_replay_from_defaults_to_none_and_survives_ev replay: ReplayMode::None, replace: false, startup: None, + elicitation_form: true, }, &writes, ) @@ -1849,6 +1853,7 @@ fn pinned_orphaned_held_prompts_do_not_exhaust_shared_cap_and_per_attachment_cap replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-caps"}})), + elicitation_form: true, }, &writes, ) @@ -1966,7 +1971,7 @@ fn pinned_orphaned_held_prompts_do_not_exhaust_shared_cap_and_per_attachment_cap let live_child_id = child_rx.try_recv().unwrap().message["id"].clone(); actor.output(json!({"jsonrpc":"2.0","id":live_child_id,"result":{"settled":true}})); assert!( - actor.pinned.as_ref().unwrap().attachments[&other] + actor.attachments[&other] .events .iter() .any(|(_, m)| m["id"] == "still-works") @@ -2037,6 +2042,7 @@ fn pinned_current_turn_replay_truncates_gracefully_when_turn_start_evicted() { replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-long-turn"}})), + elicitation_form: true, }, &writes, ) @@ -2044,12 +2050,7 @@ fn pinned_current_turn_replay_truncates_gracefully_when_turn_start_evicted() { .as_str() .unwrap() .to_owned(); - let ok_res = actor.pinned.as_ref().unwrap().attachments[&a_ok] - .events - .back() - .unwrap() - .1 - .clone(); + let ok_res = actor.attachments[&a_ok].events.back().unwrap().1.clone(); assert!( ok_res["result"]["_meta"]["kit/gateway"] .get("replayTruncated") @@ -2080,6 +2081,7 @@ fn pinned_current_turn_replay_truncates_gracefully_when_turn_start_evicted() { replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-long-turn"}})), + elicitation_form: true, }, &writes, ) @@ -2087,7 +2089,7 @@ fn pinned_current_turn_replay_truncates_gracefully_when_turn_start_evicted() { .as_str() .unwrap() .to_owned(); - let events: Vec = actor.pinned.as_ref().unwrap().attachments[&a_trunc] + let events: Vec = actor.attachments[&a_trunc] .events .iter() .map(|(_, m)| m.clone()) @@ -2111,47 +2113,7 @@ fn pinned_current_turn_replay_truncates_gracefully_when_turn_start_evicted() { #[tokio::test(start_paused = true)] async fn pinned_reaper_cleans_up_abandoned_attachments_and_leaked_startup_driver() { - // 1. Unit check of MAX_WAITING_STARTUPS bound. - let mut bounded_actor = pinned_actor("pinned-wait-bound", Duration::from_secs(60)); - let (writes, _rx) = mpsc::channel(4); - let _driver = bounded_actor - .command( - Request::Attach { - session: "pinned-wait-bound".into(), - replay: ReplayMode::None, - replace: false, - startup: None, - }, - &writes, - ) - .unwrap(); - for i in 0..MAX_WAITING_STARTUPS { - bounded_actor - .command( - Request::Attach { - session: "pinned-wait-bound".into(), - replay: ReplayMode::None, - replace: false, - startup: Some(json!({"jsonrpc":"2.0","id":i,"method":"session/resume","params":{"sessionId":"pinned-wait-bound"}})), - }, - &writes, - ) - .unwrap(); - } - let overflow_waiter = bounded_actor - .command( - Request::Attach { - session: "pinned-wait-bound".into(), - replay: ReplayMode::None, - replace: false, - startup: Some(json!({"jsonrpc":"2.0","id":999,"method":"session/resume","params":{"sessionId":"pinned-wait-bound"}})), - }, - &writes, - ) - .unwrap_err(); - assert_eq!(overflow_waiter.2, "unavailable"); - - // 2. Real Actor::run timer reaping of leaked startup_driver + abandoned attachment. + // Real Actor::run timer reaping of leaked startup_driver + abandoned attachment. let source = r#" import sys, json def emit(v): print(json.dumps(v), flush=True) @@ -2194,6 +2156,7 @@ for line in sys.stdin: replay: ReplayMode::None, replace: false, startup: None, + elicitation_form: true, }) .await .unwrap(); @@ -2206,6 +2169,7 @@ for line in sys.stdin: replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":77,"method":"session/resume","params":{"sessionId":"pinned-reap"}})), + elicitation_form: true, }) .await .unwrap(); @@ -2255,6 +2219,7 @@ for line in sys.stdin: replay: ReplayMode::None, replace: false, startup: None, + elicitation_form: true, }) .await .unwrap(); @@ -2305,6 +2270,7 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-err-relay"}})), + elicitation_form: true, }, &writes, ) @@ -2316,8 +2282,9 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo let c1 = attach(&mut actor, 1); let c2 = attach(&mut actor, 2); - // Case 1: c1 fails with -32603 (internal client error), c2 declines with -32601. - // Because c1 did NOT decline with -32601, child must NOT get -32601; late joiner c3 answers! + // Case 1: c1 fails with -32603 (internal client error), c2 is still live -> stays pending for c2. + // Once c2 also declines with -32601 (no detached target remains), it fails promptly with -32603 + // rather than falsely reporting -32601 or waiting for timeout! assert!( actor .output(json!({ @@ -2340,6 +2307,11 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo &writes, ) .unwrap(); + assert!( + child_rx.try_recv().is_err(), + "must stay pending while c2 is still a live target" + ); + assert!(actor.client_requests.contains_key(&relay1)); actor .command( Request::Send { @@ -2351,54 +2323,80 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo &writes, ) .unwrap(); + let failed_reply = child_rx.try_recv().unwrap().message; + assert_eq!(failed_reply["id"], "ask-err-1"); + assert_eq!(failed_reply["error"]["code"], -32603); + assert_eq!(failed_reply["error"]["data"]["reason"], "client_error"); + assert!(!actor.client_requests.contains_key(&relay1)); + + // Case 2: c1 fails with -32603 AND c2 detaches (mid-reload) -> stays pending for late joiner c3! assert!( - child_rx.try_recv().is_err(), - "must NOT send -32601 after non-32601 error" + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-err-reload", + "method": "elicitation/create", + "params": {"sessionId": "pinned-err-relay", "mode": "form", "message": "reload"} + })) + .is_none() ); - assert!(actor.client_requests.contains_key(&relay1)); - - // Late joiner c3 receives the still-pending request and answers validly! + let relay_reload = actor.client_requests.keys().next().unwrap().clone(); + actor + .command( + Request::Send { + session: "pinned-err-relay".into(), + attachment: c1.clone(), + message: json!({"jsonrpc":"2.0","id":relay_reload,"error":{"code":-32603,"message":"ui crashed"}}), + charge: None, + }, + &writes, + ) + .unwrap(); + actor + .command( + Request::Detach { + session: "pinned-err-relay".into(), + attachment: c2, + }, + &writes, + ) + .unwrap(); + assert!(child_rx.try_recv().is_err()); let c3 = attach(&mut actor, 3); assert_eq!( - actor.pinned.as_ref().unwrap().attachments[&c3] - .events - .back() - .unwrap() - .1["id"], - relay1 + actor.attachments[&c3].events.back().unwrap().1["id"], + relay_reload ); actor .command( Request::Send { session: "pinned-err-relay".into(), attachment: c3.clone(), - message: json!({"jsonrpc":"2.0","id":relay1,"result":{"action":"accept","content":{"a":"ok"}}}), + message: json!({"jsonrpc":"2.0","id":relay_reload,"result":{"action":"accept","content":{"a":"ok"}}}), charge: None, }, &writes, ) .unwrap(); let reply = child_rx.try_recv().unwrap().message; - assert_eq!(reply["id"], "ask-err-1"); + assert_eq!(reply["id"], "ask-err-reload"); assert_eq!(reply["result"]["content"]["a"], "ok"); - // Case 2: Single client returns -32000 -> stays pending until timeout -> expires with -32603. - for att in [&c1, &c2] { - actor - .command( - Request::Detach { - session: "pinned-err-relay".into(), - attachment: att.clone(), - }, - &writes, - ) - .unwrap(); - } + // Case 3: Sole live client returns -32000 (no other live or detached target) -> fails promptly with -32603! + actor + .command( + Request::Detach { + session: "pinned-err-relay".into(), + attachment: c1, + }, + &writes, + ) + .unwrap(); assert!( actor .output(json!({ "jsonrpc": "2.0", - "id": "ask-err-timeout", + "id": "ask-err-sole", "method": "elicitation/create", "params": {"sessionId": "pinned-err-relay", "mode": "form", "message": "wait"} })) @@ -2416,16 +2414,10 @@ async fn pinned_non_32601_client_error_keeps_relayed_request_pending_for_late_jo &writes, ) .unwrap(); - assert!(child_rx.try_recv().is_err()); - assert!(actor.next_ready_client_reply().is_none()); - tokio::time::advance(timeout).await; - let ready = actor.next_ready_client_reply().unwrap(); - assert_eq!(ready, relay2); - actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); - let expired = child_rx.try_recv().unwrap().message; - assert_eq!(expired["id"], "ask-err-timeout"); - assert_eq!(expired["error"]["code"], -32603); - assert_eq!(expired["error"]["message"], "Incoming transport closed"); + let sole_err = child_rx.try_recv().unwrap().message; + assert_eq!(sole_err["id"], "ask-err-sole"); + assert_eq!(sole_err["error"]["code"], -32603); + assert_eq!(sole_err["error"]["data"]["reason"], "client_error"); } #[test] @@ -2442,6 +2434,7 @@ fn pinned_relayed_response_buffers_under_child_backpressure_and_flushes() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-bp"}})), + elicitation_form: true, }, &writes, ) @@ -2487,18 +2480,13 @@ fn pinned_relayed_response_buffers_under_child_backpressure_and_flushes() { .unwrap(); // Loser c2 received $/cancel_request right away. assert_eq!( - actor.pinned.as_ref().unwrap().attachments[&c2] - .events - .back() - .unwrap() - .1["method"], + actor.attachments[&c2].events.back().unwrap().1["method"], "$/cancel_request" ); - // Reply is ready to flush once writer slot opens. - let ready = actor.next_ready_client_reply().unwrap(); - assert_eq!(ready, relay1); + // Reply is buffered in pending_child_replies and flushes once writer slot opens. + assert_eq!(actor.pending_child_replies.len(), 1); let _dummy = child_rx.try_recv().unwrap(); - actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); + actor.flush_child_replies(&writes); let flushed = child_rx.try_recv().unwrap().message; assert_eq!(flushed["id"], "ask-bp-win"); assert_eq!(flushed["result"]["content"]["k"], "v"); @@ -2536,10 +2524,9 @@ fn pinned_relayed_response_buffers_under_child_backpressure_and_flushes() { ) .unwrap(); } - let ready2 = actor.next_ready_client_reply().unwrap(); - assert_eq!(ready2, relay2); + assert_eq!(actor.pending_child_replies.len(), 1); let _dummy = child_rx.try_recv().unwrap(); - actor.flush_client_request_reply(&ready2, writes.try_reserve().unwrap()); + actor.flush_child_replies(&writes); let flushed2 = child_rx.try_recv().unwrap().message; assert_eq!(flushed2["id"], "ask-bp-32601"); assert_eq!(flushed2["error"]["code"], -32601); @@ -2570,7 +2557,9 @@ for line in sys.stdin: "#; harness.child_source("pinned-crash", source, &[]).await; - let mut c1 = harness.connect("c1").await; + let mut c1 = harness + .connect_with_capabilities("c1", json!({"elicitation": {"form": {}}})) + .await; let mut s1 = c1.open_session_stream("pinned-crash").await; assert_eq!( c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-crash"}})) @@ -2579,7 +2568,9 @@ for line in sys.stdin: ); let _ = s1.next_matching(|e| e["id"] == 1).await; - let mut c2 = harness.connect("c2").await; + let mut c2 = harness + .connect_with_capabilities("c2", json!({"elicitation": {"form": {}}})) + .await; let mut s2 = c2.open_session_stream("pinned-crash").await; assert_eq!( c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-crash"}})) @@ -2656,6 +2647,7 @@ fn pinned_reply_dropped_when_sender_detached_never_leaks_to_other_attachment() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-drop-reply"}})), + elicitation_form: true, }, &writes, ) @@ -2691,12 +2683,9 @@ fn pinned_reply_dropped_when_sender_detached_never_leaks_to_other_attachment() { .unwrap(); // Child replies to c1's request -> dropped silently, never delivered to c2! - let c2_before = actor.pinned.as_ref().unwrap().attachments[&c2].events.len(); + let c2_before = actor.attachments[&c2].events.len(); actor.output(json!({"jsonrpc":"2.0","id":child_id,"result":{"settled":true}})); - assert_eq!( - actor.pinned.as_ref().unwrap().attachments[&c2].events.len(), - c2_before - ); + assert_eq!(actor.attachments[&c2].events.len(), c2_before); assert!(actor.pending.is_empty()); } @@ -2913,7 +2902,9 @@ for line in sys.stdin: "#; harness.child_source("pinned-timer", source, &[]).await; - let mut c1 = harness.connect("timer-client").await; + let mut c1 = harness + .connect_with_capabilities("timer-client", json!({"elicitation": {"form": {}}})) + .await; let mut s1 = c1.open_session_stream("pinned-timer").await; assert_eq!( c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-timer"}})) @@ -2963,6 +2954,7 @@ async fn pinned_relayed_request_race_late_answer_and_non_target_ignored() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-race-ans"}})), + elicitation_form: true, }, &writes, ) @@ -3016,11 +3008,7 @@ async fn pinned_relayed_request_race_late_answer_and_non_target_ignored() { "second answer must not reach child" ); assert_eq!( - actor.pinned.as_ref().unwrap().attachments[&c2] - .events - .back() - .unwrap() - .1["method"], + actor.attachments[&c2].events.back().unwrap().1["method"], "$/cancel_request" ); @@ -3065,8 +3053,7 @@ async fn pinned_relayed_request_race_late_answer_and_non_target_ignored() { // 3. Timeout expires; late answer from c2 after timeout is ignored cleanly (no second child write). tokio::time::advance(timeout).await; - let ready = actor.next_ready_client_reply().unwrap(); - actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); + actor.flush_child_replies(&writes); let expired = child_rx.try_recv().unwrap().message; assert_eq!(expired["error"]["code"], -32603); actor @@ -3193,6 +3180,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-trim-count"}})), + elicitation_form: true, }, &writes, ) @@ -3209,7 +3197,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by "params": {"sessionId": "pinned-trim-count", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": format!("e-{i}")}}} })); if i % 64 == 0 { - let cur = actor.pinned.as_ref().unwrap().attachments[&c1].next; + let cur = actor.attachments[&c1].next; let _ = actor.command( Request::Poll { session: "pinned-trim-count".into(), @@ -3240,6 +3228,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-trim-count"}})), + elicitation_form: true, }, &writes, ) @@ -3247,7 +3236,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by .as_str() .unwrap() .to_owned(); - let c2_att = &actor.pinned.as_ref().unwrap().attachments[&c2]; + let c2_att = &actor.attachments[&c2]; assert!(c2_att.events.len() <= MAX_QUEUE); let events: Vec = c2_att.events.iter().map(|(_, m)| m.clone()).collect(); let result_msg = events.iter().find(|e| e["id"] == 2).unwrap(); @@ -3285,6 +3274,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-trim-bytes"}})), + elicitation_form: true, }, &writes, ) @@ -3300,7 +3290,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by "method": "session/update", "params": {"sessionId": "pinned-trim-bytes", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": format!("{i}:{chunk_pad}")}}} })); - let cur = byte_actor.pinned.as_ref().unwrap().attachments[&b1].next; + let cur = byte_actor.attachments[&b1].next; let _ = byte_actor.command( Request::Poll { session: "pinned-trim-bytes".into(), @@ -3327,6 +3317,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by let prepared = byte_actor .prepare_startup( "existing-att", + true, 2, 128 * 1024, byte_actor.session_result.clone().unwrap(), @@ -3359,6 +3350,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by replay: ReplayMode::CurrentTurn, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-trim-bytes"}})), + elicitation_form: true, }, &writes, ) @@ -3366,7 +3358,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by .as_str() .unwrap() .to_owned(); - let b2_att = &byte_actor.pinned.as_ref().unwrap().attachments[&b2]; + let b2_att = &byte_actor.attachments[&b2]; assert!(b2_att.bytes <= MAX_REPLAY); assert_eq!(b2_att.events.back().unwrap().1["id"], byte_relay_id); let b2_result = b2_att @@ -3396,6 +3388,7 @@ fn pinned_orphaned_idempotency_retry_reparents_without_forwarding_to_child() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-reparent"}})), + elicitation_form: true, }, &writes, ) @@ -3517,7 +3510,7 @@ fn pinned_orphaned_idempotency_retry_reparents_without_forwarding_to_child() { // Child resolves the original serial -> reply arrives at final_att with id "final-try"! actor .output(json!({"jsonrpc":"2.0","id":child_serial,"result":{"messageId":"msg-reparented"}})); - let final_events = &actor.pinned.as_ref().unwrap().attachments[&final_att].events; + let final_events = &actor.attachments[&final_att].events; assert_eq!(final_events.back().unwrap().1["id"], "final-try"); assert_eq!( final_events.back().unwrap().1["result"]["messageId"], @@ -3564,6 +3557,7 @@ for line in sys.stdin: replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-freeze"}})), + elicitation_form: true, }) .await .unwrap()["attachment"] @@ -3575,6 +3569,7 @@ for line in sys.stdin: replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-freeze"}})), + elicitation_form: true, }) .await .unwrap()["attachment"] @@ -3653,6 +3648,7 @@ async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-detach-32601"}})), + elicitation_form: true, }, &writes, ) @@ -3709,11 +3705,7 @@ async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { // Reloaded dashboard c3 attaches, receives the pending request, and answers! let c3 = attach(&mut actor, 3); assert_eq!( - actor.pinned.as_ref().unwrap().attachments[&c3] - .events - .back() - .unwrap() - .1["id"], + actor.attachments[&c3].events.back().unwrap().1["id"], relay1 ); actor @@ -3765,9 +3757,7 @@ async fn pinned_detached_target_prevents_32601_decline_from_remaining_target() { .unwrap(); assert!(child_rx.try_recv().is_err()); tokio::time::advance(timeout).await; - let ready = actor.next_ready_client_reply().unwrap(); - assert_eq!(ready, relay2); - actor.flush_client_request_reply(&ready, writes.try_reserve().unwrap()); + actor.flush_child_replies(&writes); let expired = child_rx.try_recv().unwrap().message; assert_eq!(expired["id"], "ask-reload-timeout"); assert_eq!(expired["error"]["code"], -32603); @@ -3789,6 +3779,7 @@ fn pinned_cancelled_orphan_is_not_reparented_and_forwards_fresh_retry() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-cancel-reparent"}})), + elicitation_form: true, }, &writes, ) @@ -3879,12 +3870,7 @@ fn pinned_cancelled_orphan_is_not_reparented_and_forwards_fresh_retry() { // Original cancelled reply (-32800) is dropped (orphaned) and does NOT fail d2! actor.output(json!({"jsonrpc":"2.0","id":orig_serial,"error":{"code":-32800,"message":"Request cancelled"}})); actor.output(json!({"jsonrpc":"2.0","id":fresh_serial,"result":{"messageId":"msg-fresh"}})); - let d2_last = actor.pinned.as_ref().unwrap().attachments[&d2] - .events - .back() - .unwrap() - .1 - .clone(); + let d2_last = actor.attachments[&d2].events.back().unwrap().1.clone(); assert_eq!(d2_last["id"], "p-2"); assert_eq!(d2_last["result"]["messageId"], "msg-fresh"); @@ -3970,6 +3956,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-start-count"}})), + elicitation_form: true, }, &writes, ) @@ -3984,7 +3971,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela "params": {"sessionId": "pinned-start-count", "update": {"sessionUpdate": "notice", "message": format!("m-{i}")}} })); if i % 64 == 0 { - let cur = actor.pinned.as_ref().unwrap().attachments[&c1].next; + let cur = actor.attachments[&c1].next; let _ = actor.command( Request::Poll { session: "pinned-start-count".into(), @@ -4016,6 +4003,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela replay: ReplayMode::Start, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-start-count","replayFrom":{"type":"start"}}})), + elicitation_form: true, }, &writes, ) @@ -4023,7 +4011,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela .as_str() .unwrap() .to_owned(); - let c2_att = &actor.pinned.as_ref().unwrap().attachments[&c2]; + let c2_att = &actor.attachments[&c2]; // Full journal (MAX_QUEUE - 3) + 2 snapshots + 1 startup result + 1 pending relay = MAX_QUEUE + 1. assert_eq!(c2_att.events.len(), MAX_QUEUE + 1); assert_eq!(c2_att.events[0].1["params"]["update"]["message"], "m-0"); @@ -4060,6 +4048,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela replay: ReplayMode::Start, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"pinned-start-count","replayFrom":{"type":"start"}}})), + elicitation_form: true, }, &writes, ) @@ -4078,6 +4067,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-start-bytes"}})), + elicitation_form: true, }, &writes, ) @@ -4093,7 +4083,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela "method": "session/update", "params": {"sessionId": "pinned-start-bytes", "update": {"sessionUpdate": "notice", "message": format!("{i}:{chunk_pad}")}} })); - let cur = byte_actor.pinned.as_ref().unwrap().attachments[&b1].next; + let cur = byte_actor.attachments[&b1].next; let _ = byte_actor.command( Request::Poll { session: "pinned-start-bytes".into(), @@ -4124,6 +4114,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela replay: ReplayMode::Start, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-start-bytes","replayFrom":{"type":"start"}}})), + elicitation_form: true, }, &writes, ) @@ -4131,7 +4122,7 @@ fn pinned_start_replay_succeeds_on_exact_full_complete_journal_with_pending_rela .as_str() .unwrap() .to_owned(); - let b2_att = &byte_actor.pinned.as_ref().unwrap().attachments[&b2]; + let b2_att = &byte_actor.attachments[&b2]; assert_eq!(b2_att.events.len(), 16 + 3 + 1); assert_eq!(b2_att.events.back().unwrap().1["id"], byte_relay_id); } @@ -4315,6 +4306,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-replay"}})), + elicitation_form: true, }, &writes, ) @@ -4342,13 +4334,15 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star replay: ReplayMode::CurrentTurn, replace: true, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"def-replay","replayFrom":{"type":"_kit_current_turn"}}})), + elicitation_form: true, }, &writes, ) .unwrap(); let events_turn: Vec = actor - .attachment - .as_ref() + .attachments + .values() + .next() .unwrap() .events .iter() @@ -4385,13 +4379,15 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star }, replace: true, startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"def-replay","replayFrom":{"type":"_kit_message","sessionId":"def-replay","messageId":"u-1"}}})), + elicitation_form: true, }, &writes, ) .unwrap(); let events_msg: Vec = actor - .attachment - .as_ref() + .attachments + .values() + .next() .unwrap() .events .iter() @@ -4413,13 +4409,14 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star }, replace: true, startup: Some(json!({"jsonrpc":"2.0","id":4,"method":"session/resume","params":{"sessionId":"def-replay"}})), + elicitation_form: true, }, &writes, ) .unwrap_err(); assert_eq!(bad_cursor.jsonrpc_code(), -32602); // Failed cursor preserves current controller! - assert_ne!(actor.attachment.as_ref().unwrap().id, c1); + assert_ne!(actor.attachments.values().next().unwrap().id, c1); // 3. Exact full complete journal + pending relayed request succeeds with ReplayMode::Start in default mode! let mut full_actor = default_actor("def-full-start", Duration::from_secs(60)); @@ -4431,6 +4428,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-full-start"}})), + elicitation_form: true, }, &writes, ) @@ -4445,7 +4443,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star "params": {"sessionId": "def-full-start", "update": {"sessionUpdate": "notice", "message": format!("d-{i}")}} })); if i % 64 == 0 { - let cur = full_actor.attachment.as_ref().unwrap().next; + let cur = full_actor.attachments.values().next().unwrap().next; let _ = full_actor.command( Request::Poll { session: "def-full-start".into(), @@ -4475,6 +4473,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star replay: ReplayMode::Start, replace: true, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"def-full-start","replayFrom":{"type":"start"}}})), + elicitation_form: true, }, &writes, ) @@ -4483,13 +4482,14 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star .unwrap() .to_owned(); assert_eq!( - full_actor.attachment.as_ref().unwrap().events.len(), + full_actor.attachments.values().next().unwrap().events.len(), MAX_QUEUE + 1 ); assert_eq!( full_actor - .attachment - .as_ref() + .attachments + .values() + .next() .unwrap() .events .back() @@ -4531,13 +4531,15 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star replay: ReplayMode::CurrentTurn, replace: true, startup: Some(json!({"jsonrpc":"2.0","id":5,"method":"session/resume","params":{"sessionId":"def-replay"}})), + elicitation_form: true, }, &writes, ) .unwrap(); let trunc_events: Vec = actor - .attachment - .as_ref() + .attachments + .values() + .next() .unwrap() .events .iter() @@ -4642,6 +4644,7 @@ fn pinned_keyed_cancellation_invalidates_detached_sibling_from_reparenting() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-sib"}})), + elicitation_form: true, }, &writes, ) @@ -4769,6 +4772,7 @@ async fn relay_expiration_is_terminal_even_when_child_writer_is_full() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"exp-full"}})), + elicitation_form: true, }, &writes, ) @@ -4843,6 +4847,7 @@ async fn relay_expiration_is_terminal_even_when_child_writer_is_full() { replay: ReplayMode::None, replace: !is_pinned, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"exp-full"}})), + elicitation_form: true, }, &writes, ) @@ -4866,10 +4871,8 @@ async fn relay_expiration_is_terminal_even_when_child_writer_is_full() { // Free the blocked writer and flush -> child receives -32603 timeout, NEVER the late accept! let _ = child_rx.try_recv().unwrap(); - let ready = actor.next_ready_client_reply().unwrap(); - assert_eq!(ready, relay_id); - let permit = writes.try_reserve().unwrap(); - actor.flush_client_request_reply(&ready, permit); + assert_eq!(actor.pending_child_replies.len(), 1); + actor.flush_child_replies(&writes); let reply = child_rx.try_recv().unwrap().message; assert_eq!(reply["id"], "ask-exp"); assert_eq!(reply["error"]["code"], -32603); @@ -4933,7 +4936,9 @@ for line in sys.stdin: .child_source("pinned-sat", source, &[gate_port.to_string()]) .await; - let c1 = harness.connect("observer").await; + let c1 = harness + .connect_with_capabilities("observer", json!({"elicitation": {"form": {}}})) + .await; let mut s1 = c1.open_session_stream("pinned-sat").await; assert_eq!( c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-sat"}})) @@ -4978,6 +4983,7 @@ for line in sys.stdin: replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-sat"}})), + elicitation_form: true, }) .await["attachment"] .as_str() @@ -5059,6 +5065,7 @@ fn relay_validates_permission_and_elicitation_answers_before_cancelling_others() replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":"pinned-val"}})), + elicitation_form: true, }, &writes, ) @@ -5070,39 +5077,42 @@ fn relay_validates_permission_and_elicitation_answers_before_cancelling_others() let c1 = attach(&mut actor, 1); let c2 = attach(&mut actor, 2); - // 1. Permission request with offered options. - assert!( - actor - .output(json!({ - "jsonrpc": "2.0", - "id": "perm-1", - "method": "session/request_permission", - "params": { - "sessionId": "pinned-val", - "toolCall": {"toolCallId": "tc-1"}, - "options": [ - {"optionId": "allow_once", "name": "Allow", "kind": "allow_once"}, - {"optionId": "reject_once", "name": "Reject", "kind": "reject_once"} - ] - } - })) - .is_none() - ); - let perm_relay = actor.client_requests.keys().next().unwrap().clone(); - - // Invalid outcomes MUST be rejected without resolving relay or cancelling c2. - for bad_result in [ + // 1. Permission request with offered options: each invalid outcome drops that sender + // without resolving or cancelling c2; c2 can still answer validly. + for (idx, bad_result) in [ json!({"outcome": {}}), json!({"outcome": {"outcome": "selected"}}), json!({"outcome": {"outcome": "selected", "optionId": "not_offered"}}), json!({"outcome": {"outcome": "selected", "optionId": ""}}), json!({"outcome": {"outcome": ""}}), - ] { + ] + .into_iter() + .enumerate() + { + let bad_att = attach(&mut actor, 100 + idx as u64); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": format!("perm-{idx}"), + "method": "session/request_permission", + "params": { + "sessionId": "pinned-val", + "toolCall": {"toolCallId": "tc-1"}, + "options": [ + {"optionId": "allow_once", "name": "Allow", "kind": "allow_once"}, + {"optionId": "reject_once", "name": "Reject", "kind": "reject_once"} + ] + } + })) + .is_none() + ); + let perm_relay = actor.client_requests.keys().next().unwrap().clone(); let err = actor .command( Request::Send { session: "pinned-val".into(), - attachment: c1.clone(), + attachment: bad_att.clone(), message: json!({"jsonrpc": "2.0", "id": perm_relay, "result": bad_result}), charge: None, }, @@ -5111,76 +5121,92 @@ fn relay_validates_permission_and_elicitation_answers_before_cancelling_others() .unwrap_err(); assert_eq!(err.0, StatusCode::BAD_REQUEST, "{bad_result}"); assert!(child_rx.try_recv().is_err(), "{bad_result}"); - assert!(actor.client_requests[&perm_relay].resolved_reply.is_none()); + assert!(actor.client_requests.contains_key(&perm_relay)); + assert!( + !actor.client_requests[&perm_relay] + .targets + .contains(&bad_att) + ); assert!(actor.client_requests[&perm_relay].targets.contains(&c2)); - } - // Valid offered optionId from c2 wins and cancels c1. - actor - .command( - Request::Send { - session: "pinned-val".into(), - attachment: c2.clone(), - message: json!({ - "jsonrpc": "2.0", - "id": perm_relay, - "result": {"outcome": {"outcome": "selected", "optionId": "allow_once"}} - }), - charge: None, - }, - &writes, - ) - .unwrap(); - let perm_reply = child_rx.try_recv().unwrap().message; - assert_eq!(perm_reply["id"], "perm-1"); - assert_eq!(perm_reply["result"]["outcome"]["optionId"], "allow_once"); - assert_eq!( + // Valid offered optionId from c2 wins and cancels c1 (not bad_att, already dropped). actor - .active_attachment(&c1) - .unwrap() - .events - .back() - .unwrap() - .1["method"], - "$/cancel_request" - ); - - // 2. Form elicitation with required field. - assert!( + .command( + Request::Send { + session: "pinned-val".into(), + attachment: c2.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": perm_relay, + "result": {"outcome": {"outcome": "selected", "optionId": "allow_once"}} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let perm_reply = child_rx.try_recv().unwrap().message; + assert_eq!(perm_reply["id"], format!("perm-{idx}")); + assert_eq!(perm_reply["result"]["outcome"]["optionId"], "allow_once"); + assert_eq!( + actor + .active_attachment(&c1) + .unwrap() + .events + .back() + .unwrap() + .1["method"], + "$/cancel_request" + ); actor - .output(json!({ - "jsonrpc": "2.0", - "id": "form-1", - "method": "elicitation/create", - "params": { - "sessionId": "pinned-val", - "mode": "form", - "message": "Pick", - "requestedSchema": { - "type": "object", - "required": ["question_0"], - "properties": {"question_0": {"type": "string"}} - } - } - })) - .is_none() - ); - let form_relay = actor.client_requests.keys().next().unwrap().clone(); + .command( + Request::Detach { + session: "pinned-val".into(), + attachment: bad_att, + }, + &writes, + ) + .unwrap(); + } - // Missing content, null content, missing required key, and non-scalar content value MUST fail. - for bad_result in [ + // 2. Form elicitation shape checks: missing content, null content, non-object content, + // and empty action fail without cancelling c2; form-schema field checks (required/types) + // are NOT enforced by the gateway and forward straight to the child for tool-level validation. + for (idx, bad_result) in [ json!({"action": "accept"}), json!({"action": "accept", "content": null}), json!({"action": "accept", "content": "not-an-object"}), - json!({"action": "accept", "content": {}}), - json!({"action": "accept", "content": {"question_0": {"nested": true}}}), json!({"action": ""}), - ] { + ] + .into_iter() + .enumerate() + { + let bad_att = attach(&mut actor, 200 + idx as u64); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": format!("form-{idx}"), + "method": "elicitation/create", + "params": { + "sessionId": "pinned-val", + "mode": "form", + "message": "Pick", + "requestedSchema": { + "type": "object", + "required": ["question_0"], + "properties": {"question_0": {"type": "string"}} + } + } + })) + .is_none() + ); + let form_relay = actor.client_requests.keys().next().unwrap().clone(); let err = actor .command( Request::Send { session: "pinned-val".into(), - attachment: c1.clone(), + attachment: bad_att.clone(), message: json!({"jsonrpc": "2.0", "id": form_relay, "result": bad_result}), charge: None, }, @@ -5189,37 +5215,90 @@ fn relay_validates_permission_and_elicitation_answers_before_cancelling_others() .unwrap_err(); assert_eq!(err.0, StatusCode::BAD_REQUEST, "{bad_result}"); assert!(child_rx.try_recv().is_err(), "{bad_result}"); - assert!(actor.client_requests[&form_relay].resolved_reply.is_none()); + assert!(actor.client_requests.contains_key(&form_relay)); + + // Schema-incomplete object content IS accepted by the gateway and forwarded to the child + // so the child validates form fields and returns a tool error the model can react to! + actor + .command( + Request::Send { + session: "pinned-val".into(), + attachment: c2.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": form_relay, + "result": {"action": "accept", "content": {}} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let form_reply = child_rx.try_recv().unwrap().message; + assert_eq!(form_reply["id"], format!("form-{idx}")); + assert_eq!(form_reply["result"]["content"], json!({})); + assert_eq!( + actor + .active_attachment(&c1) + .unwrap() + .events + .back() + .unwrap() + .1["params"]["requestId"], + form_relay + ); + actor + .command( + Request::Detach { + session: "pinned-val".into(), + attachment: bad_att, + }, + &writes, + ) + .unwrap(); } - // Valid form answer from c2 succeeds and cancels c1. + // 3. When the sender is the ONLY remaining target (and no target detached), a shape-invalid + // answer forwards nothing invalid and resolves promptly toward the child with -32603! actor + .command( + Request::Detach { + session: "pinned-val".into(), + attachment: c1, + }, + &writes, + ) + .unwrap(); + assert!( + actor + .output(json!({ + "jsonrpc": "2.0", + "id": "form-sole-invalid", + "method": "elicitation/create", + "params": {"sessionId": "pinned-val", "mode": "form", "message": "sole"} + })) + .is_none() + ); + let sole_relay = actor.client_requests.keys().next().unwrap().clone(); + let err = actor .command( Request::Send { session: "pinned-val".into(), attachment: c2, - message: json!({ - "jsonrpc": "2.0", - "id": form_relay, - "result": {"action": "accept", "content": {"question_0": "opt-a"}} - }), + message: json!({"jsonrpc": "2.0", "id": sole_relay, "result": {"action": "accept"}}), charge: None, }, &writes, ) - .unwrap(); - let form_reply = child_rx.try_recv().unwrap().message; - assert_eq!(form_reply["id"], "form-1"); - assert_eq!(form_reply["result"]["content"]["question_0"], "opt-a"); + .unwrap_err(); + assert_eq!(err.0, StatusCode::BAD_REQUEST); + assert!(actor.client_requests.is_empty()); + let prompt_fail = child_rx.try_recv().unwrap().message; + assert_eq!(prompt_fail["id"], "form-sole-invalid"); + assert_eq!(prompt_fail["error"]["code"], -32603); assert_eq!( - actor - .active_attachment(&c1) - .unwrap() - .events - .back() - .unwrap() - .1["params"]["requestId"], - form_relay + prompt_fail["error"]["data"]["reason"], + "invalid_client_response" ); } @@ -5236,6 +5315,7 @@ async fn relay_preserves_unknown_extension_actions_and_keeps_default_route_after replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"ext-act"}})), + elicitation_form: true, }, &writes, ) @@ -5306,19 +5386,23 @@ async fn relay_preserves_unknown_extension_actions_and_keeps_default_route_after assert_eq!(perm_reply["result"]["outcome"]["outcome"], "_policy_defer"); assert_eq!(perm_reply["result"]["outcome"]["ttl"], 30); - // 2. HTTP default-mode check: an invalid client reply does NOT consume relay_routes, - // so a subsequent valid reply from the same controller still routes and resolves! + // 2. HTTP default-mode check: + // (a) a sole target sending a shape-invalid reply fails promptly toward the child (-32603) + // without waiting for the 60s timeout or forwarding invalid content; + // (b) a valid extension action forwards immediately over HTTP! let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; let source = r#" import sys, json prompt_req = None +expected = None def emit(v): print(json.dumps(v), flush=True) for line in sys.stdin: req = json.loads(line) if 'method' not in req: - if req['id'] == 'ask-http' and prompt_req: - emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'got': req.get('result')}}) + if expected and req['id'] == expected and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'got': req.get('result'), 'err': req.get('error')}}) prompt_req = None + expected = None continue m = req['method'] if m == 'initialize': @@ -5327,7 +5411,8 @@ for line in sys.stdin: emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'def-ext','configOptions':[]}}) elif m == 'session/prompt': prompt_req = req - emit({'jsonrpc':'2.0','id':'ask-http','method':'elicitation/create','params':{'sessionId':'def-ext','mode':'form','message':'hi'}}) + expected = f"ask-{req['params']['prompt'][0]['text']}" + emit({'jsonrpc':'2.0','id':expected,'method':'elicitation/create','params':{'sessionId':'def-ext','mode':'form','message':'hi'}}) elif 'id' in req: emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) "#; @@ -5342,31 +5427,47 @@ for line in sys.stdin: StatusCode::ACCEPTED ); let _ = s.next_matching(|e| e["id"] == 1).await; + + // (a) Invalid form accept from sole target -> fails promptly with -32603 (invalid_client_response). assert_eq!( - c.post(json!({"jsonrpc":"2.0","id":"p1","method":"session/prompt","params":{"sessionId":"def-ext","prompt":[{"type":"text","text":"go"}]}})) + c.post(json!({"jsonrpc":"2.0","id":"p-bad","method":"session/prompt","params":{"sessionId":"def-ext","prompt":[{"type":"text","text":"bad"}]}})) .await, StatusCode::ACCEPTED ); - let q = s + let q_bad = s .next_matching(|e| e["method"] == "elicitation/create") .await; - let rid = q["id"].as_str().unwrap().to_owned(); + let rid_bad = q_bad["id"].as_str().unwrap().to_owned(); + assert_eq!( + c.post(json!({"jsonrpc":"2.0","id":rid_bad,"result":{"action":"accept"}})) + .await, + StatusCode::ACCEPTED + ); + let done_bad = s.next_matching(|e| e["id"] == "p-bad").await; + assert_eq!(done_bad["result"]["err"]["code"], -32603); + assert_eq!( + done_bad["result"]["err"]["data"]["reason"], + "invalid_client_response" + ); - // First send an invalid form accept (missing content) -> rejected silently with diagnostic, route preserved! + // (b) Valid extension action -> succeeds immediately without waiting for timeout! assert_eq!( - c.post(json!({"jsonrpc":"2.0","id":rid,"result":{"action":"accept"}})) + c.post(json!({"jsonrpc":"2.0","id":"p-ext","method":"session/prompt","params":{"sessionId":"def-ext","prompt":[{"type":"text","text":"ext"}]}})) .await, StatusCode::ACCEPTED ); - // Then send a valid extension action -> succeeds immediately without waiting for timeout! + let q_ext = s + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let rid_ext = q_ext["id"].as_str().unwrap().to_owned(); assert_eq!( - c.post(json!({"jsonrpc":"2.0","id":rid,"result":{"action":"_extension","k":"v"}})) + c.post(json!({"jsonrpc":"2.0","id":rid_ext,"result":{"action":"_extension","k":"v"}})) .await, StatusCode::ACCEPTED ); - let done = s.next_matching(|e| e["id"] == "p1").await; - assert_eq!(done["result"]["got"]["action"], "_extension"); - assert_eq!(done["result"]["got"]["k"], "v"); + let done_ext = s.next_matching(|e| e["id"] == "p-ext").await; + assert_eq!(done_ext["result"]["got"]["action"], "_extension"); + assert_eq!(done_ext["result"]["got"]["k"], "v"); let _ = c.delete().await; } @@ -5392,6 +5493,7 @@ fn startup_reserved_relays_do_not_exhaust_live_queue_before_first_poll() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"res-count"}})), + elicitation_form: true, }, &writes, ) @@ -5438,6 +5540,7 @@ fn startup_reserved_relays_do_not_exhaust_live_queue_before_first_poll() { replay: ReplayMode::Start, replace: !is_pinned, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"res-count","replayFrom":{"type":"start"}}})), + elicitation_form: true, }, &writes, ) @@ -5507,6 +5610,7 @@ fn startup_reserved_relays_do_not_exhaust_live_queue_before_first_poll() { replay: ReplayMode::None, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"res-bytes"}})), + elicitation_form: true, }, &writes, ) @@ -5549,6 +5653,7 @@ fn startup_reserved_relays_do_not_exhaust_live_queue_before_first_poll() { replay: ReplayMode::Start, replace: false, startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"res-bytes","replayFrom":{"type":"start"}}})), + elicitation_form: true, }, &writes, ) @@ -5578,3 +5683,350 @@ fn startup_reserved_relays_do_not_exhaust_live_queue_before_first_poll() { "small-live-update" ); } + +#[tokio::test] +async fn multiplexed_sessions_on_one_connection_get_distinct_relay_ids_and_route_answers_independently() + { + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source = r#" +import sys, json +sid = sys.argv[1] +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req['id'] == f'ask-{sid}' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'session': sid, 'reply': req.get('result')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':sid,'configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({ + 'jsonrpc':'2.0', + 'id':f'ask-{sid}', + 'method':'elicitation/create', + 'params':{'sessionId':sid,'mode':'form','message':f'question for {sid}'} + }) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness + .child_source("mux-a", source, &["mux-a".into()]) + .await; + harness + .child_source("mux-b", source, &["mux-b".into()]) + .await; + + // One HTTP connection controls BOTH mux-a and mux-b simultaneously. + let conn = harness + .connect_with_capabilities("mux-client", json!({"elicitation": {"form": {}}})) + .await; + let mut sa = conn.open_session_stream("mux-a").await; + let mut sb = conn.open_session_stream("mux-b").await; + assert_eq!( + conn.post( + json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"mux-a"}}) + ) + .await, + StatusCode::ACCEPTED + ); + let _ = sa.next_matching(|e| e["id"] == 1).await; + assert_eq!( + conn.post( + json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"mux-b"}}) + ) + .await, + StatusCode::ACCEPTED + ); + let _ = sb.next_matching(|e| e["id"] == 2).await; + + // Trigger a pending relayed elicitation in EACH session concurrently. + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"pa","method":"session/prompt","params":{"sessionId":"mux-a","prompt":[{"type":"text","text":"a"}]}})) + .await, + StatusCode::ACCEPTED + ); + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"pb","method":"session/prompt","params":{"sessionId":"mux-b","prompt":[{"type":"text","text":"b"}]}})) + .await, + StatusCode::ACCEPTED + ); + let qa = sa + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let qb = sb + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let id_a = qa["id"].as_str().unwrap().to_owned(); + let id_b = qb["id"].as_str().unwrap().to_owned(); + assert_ne!( + id_a, id_b, + "relay IDs must never collide across sessions on one connection" + ); + + // Answer mux-b first and mux-a second; each child MUST receive its own answer! + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":id_b,"result":{"action":"accept","content":{"val":"for-b"}}})) + .await, + StatusCode::ACCEPTED + ); + let done_b = sb.next_matching(|e| e["id"] == "pb").await; + assert_eq!(done_b["result"]["session"], "mux-b"); + assert_eq!(done_b["result"]["reply"]["content"]["val"], "for-b"); + + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":id_a,"result":{"action":"accept","content":{"val":"for-a"}}})) + .await, + StatusCode::ACCEPTED + ); + let done_a = sa.next_matching(|e| e["id"] == "pa").await; + assert_eq!(done_a["result"]["session"], "mux-a"); + assert_eq!(done_a["result"]["reply"]["content"]["val"], "for-a"); + + let _ = conn.delete().await; +} + +#[tokio::test] +async fn default_mode_non_declaring_controller_gets_nothing_and_child_receives_32601() { + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source = r#" +import sys, json +prompt_req = None +expected = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if expected and req['id'] == expected and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'res': req.get('result'), 'err': req.get('error')}}) + prompt_req = None + expected = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'def-cap','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + kind = req['params']['prompt'][0]['text'] + if kind == 'ask': + expected = 'ask-1' + emit({'jsonrpc':'2.0','id':expected,'method':'elicitation/create','params':{'sessionId':'def-cap','mode':'form','message':'hi'}}) + elif kind == 'perm': + expected = 'perm-1' + emit({'jsonrpc':'2.0','id':expected,'method':'session/request_permission','params':{'sessionId':'def-cap','options':[{'optionId':'allow','name':'Allow','kind':'allow_once'}]}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("def-cap", source, &[]).await; + + // Client 1 declares elicitation.form and initializes the child with it. + let c1 = harness + .connect_with_capabilities("declarer", json!({"elicitation": {"form": {}}})) + .await; + let mut s1 = c1.open_session_stream("def-cap").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-cap"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + // Client 2 connects with capabilities: {} and replaces Client 1. + let c2 = harness.connect("non-declarer").await; + let mut s2 = c2.open_session_stream("def-cap").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"def-cap"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s2.next_matching(|e| e["id"] == 2).await; + + // Trigger elicitation/create while only {} Client 2 is attached -> child immediately gets -32601 + // and Client 2 receives NO elicitation/create frame! + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":"p-ask","method":"session/prompt","params":{"sessionId":"def-cap","prompt":[{"type":"text","text":"ask"}]}})) + .await, + StatusCode::ACCEPTED + ); + let mut saw_elicitation = false; + let ask_done = s2 + .next_matching(|e| { + if e["method"] == "elicitation/create" { + saw_elicitation = true; + } + e["id"] == "p-ask" + }) + .await; + assert!( + !saw_elicitation, + "non-declaring controller must never receive elicitation/create" + ); + assert_eq!(ask_done["result"]["err"]["code"], -32601); + + // Permission requests require no client capability in ACP v2 -> {} Client 2 IS offered them! + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":"p-perm","method":"session/prompt","params":{"sessionId":"def-cap","prompt":[{"type":"text","text":"perm"}]}})) + .await, + StatusCode::ACCEPTED + ); + let perm = s2 + .next_matching(|e| e["method"] == "session/request_permission") + .await; + let perm_id = perm["id"].as_str().unwrap().to_owned(); + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":perm_id,"result":{"outcome":{"outcome":"selected","optionId":"allow"}}})) + .await, + StatusCode::ACCEPTED + ); + let perm_done = s2.next_matching(|e| e["id"] == "p-perm").await; + assert_eq!(perm_done["result"]["res"]["outcome"]["optionId"], "allow"); + + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[tokio::test] +async fn pinned_mode_capability_targeted_elicitation_skips_headless_deliverers() { + let harness = PinnedHarness::new("pinned-cap", Duration::from_secs(60)).await; + let source = r#" +import sys, json +prompt_req = None +expected = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if expected and req['id'] == expected and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'res': req.get('result'), 'err': req.get('error')}}) + prompt_req = None + expected = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-cap','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + expected = f"ask-{req['params']['prompt'][0]['text']}" + emit({'jsonrpc':'2.0','id':expected,'method':'elicitation/create','params':{'sessionId':'pinned-cap','mode':'form','message':expected}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("pinned-cap", source, &[]).await; + + // 1. Only a headless deliverer (capabilities: {}) is attached -> elicitation/create gets -32601 + // immediately and headless deliverer receives nothing! + let deliverer = harness.connect("deliverer").await; + let mut s_deliv = deliverer.open_session_stream("pinned-cap").await; + assert_eq!( + deliverer + .post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-cap"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s_deliv.next_matching(|e| e["id"] == 1).await; + + assert_eq!( + deliverer + .post(json!({"jsonrpc":"2.0","id":"p-only-headless","method":"session/prompt","params":{"sessionId":"pinned-cap","prompt":[{"type":"text","text":"headless"}]}})) + .await, + StatusCode::ACCEPTED + ); + let mut deliv_saw_ask = false; + let only_headless = s_deliv + .next_matching(|e| { + if e["method"] == "elicitation/create" { + deliv_saw_ask = true; + } + e["id"] == "p-only-headless" + }) + .await; + assert!(!deliv_saw_ask); + assert_eq!(only_headless["result"]["err"]["code"], -32601); + + // 2. Attach a declaring UI alongside the headless deliverer -> ONLY the UI is offered! + let ui = harness + .connect_with_capabilities("ui", json!({"elicitation": {"form": {}}})) + .await; + let mut s_ui = ui.open_session_stream("pinned-cap").await; + assert_eq!( + ui.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-cap"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s_ui.next_matching(|e| e["id"] == 2).await; + + assert_eq!( + deliverer + .post(json!({"jsonrpc":"2.0","id":"p-both","method":"session/prompt","params":{"sessionId":"pinned-cap","prompt":[{"type":"text","text":"both"}]}})) + .await, + StatusCode::ACCEPTED + ); + let q_ui = s_ui + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay_id = q_ui["id"].as_str().unwrap().to_owned(); + + // A second headless late joiner attaching while the elicitation is pending MUST NOT receive it! + let late_headless = harness.connect("late-headless").await; + let mut s_late_h = late_headless.open_session_stream("pinned-cap").await; + assert_eq!( + late_headless + .post(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"pinned-cap"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s_late_h.next_matching(|e| e["id"] == 3).await; + assert_eq!( + late_headless + .post(json!({"jsonrpc":"2.0","id":4,"method":"kit/session/status","params":{"sessionId":"pinned-cap"}})) + .await, + StatusCode::ACCEPTED + ); + let mut late_h_saw_ask = false; + let _ = s_late_h + .next_matching(|e| { + if e["method"] == "elicitation/create" { + late_h_saw_ask = true; + } + e["id"] == 4 + }) + .await; + assert!( + !late_h_saw_ask, + "headless late joiner must not be offered pending elicitation" + ); + + // Declaring UI answers -> deliverer gets prompt result and NEVER saw elicitation/create! + assert_eq!( + ui.post(json!({"jsonrpc":"2.0","id":relay_id,"result":{"action":"accept","content":{"picked":"ok"}}})) + .await, + StatusCode::ACCEPTED + ); + let both_done = s_deliv + .next_matching(|e| { + if e["method"] == "elicitation/create" { + deliv_saw_ask = true; + } + e["id"] == "p-both" + }) + .await; + assert!( + !deliv_saw_ask, + "headless deliverer must never receive elicitation/create" + ); + assert_eq!(both_done["result"]["res"]["content"]["picked"], "ok"); + + let _ = deliverer.delete().await; + let _ = late_headless.delete().await; + let _ = ui.delete().await; +} diff --git a/src/gateway/tests.rs b/src/gateway/tests.rs index f862928c..3b963135 100644 --- a/src/gateway/tests.rs +++ b/src/gateway/tests.rs @@ -475,6 +475,7 @@ async fn accepted_child_write_retains_charge_after_dequeue_until_consumed() { session: actor.id.clone(), replace: false, replay: ReplayMode::Start, + elicitation_form: false, }, &writes, ) @@ -515,6 +516,7 @@ fn failed_child_enqueue_does_not_publish_pending_request() { session: actor.id.clone(), replace: false, replay: ReplayMode::Start, + elicitation_form: false, }, &writes, ) @@ -553,6 +555,7 @@ fn failed_replay_claim_preserves_owner_and_stale_release_preserves_replacement() session: "resident".into(), replace, replay: ReplayMode::Start, + elicitation_form: false, }; let first = actor.command(claim(false), &writes).unwrap()["attachment"] .as_str() @@ -574,12 +577,12 @@ fn failed_replay_claim_preserves_owner_and_stale_release_preserves_replacement() ) .is_err() ); - assert_eq!(actor.attachment.as_ref().unwrap().id, second); + assert_eq!(actor.attachments.values().next().unwrap().id, second); actor.remember(json!({"payload":"x".repeat(MAX_REPLAY + 1)})); assert!(!actor.replay_complete); assert!(actor.journal_bytes <= MAX_REPLAY); assert!(actor.command(claim(true), &writes).is_err()); - assert_eq!(actor.attachment.as_ref().unwrap().id, second); + assert_eq!(actor.attachments.values().next().unwrap().id, second); } #[tokio::test] @@ -634,6 +637,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { session: actor.id.clone(), replace: false, replay: ReplayMode::Start, + elicitation_form: false, }, &writes, ) @@ -670,7 +674,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { assert_eq!(response["id"], 42); assert!(response.get("error").is_some()); assert!(response.get("result").is_none()); - assert!(!actor.attachment.as_ref().unwrap().live); + assert!(!actor.attachments.values().next().unwrap().live); } #[test] @@ -686,6 +690,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { session: actor.id.clone(), replace: true, replay: ReplayMode::None, + elicitation_form: false, }, &writes, ) @@ -707,7 +712,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { }, ); actor.output(json!({"jsonrpc":"2.0","id":1,"result":{"sessionId":"resident"}})); - let owner = actor.attachment.as_ref().unwrap(); + let owner = actor.attachments.values().next().unwrap(); assert!(owner.live); assert_eq!(owner.events.len(), 3); assert_eq!(owner.events[2].1["id"], 42); @@ -725,12 +730,13 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { session: actor.id.clone(), replace: true, replay: ReplayMode::Start, + elicitation_form: false, }, &writes ) .is_err() ); - assert_eq!(actor.attachment.as_ref().unwrap().id, attachment); + assert_eq!(actor.attachments.values().next().unwrap().id, attachment); } #[tokio::test] @@ -1081,6 +1087,7 @@ pub(super) fn resident_claim(actor: &Actor, replay: bool, id: u64) -> Request { startup: Some( json!({"jsonrpc":"2.0","id":id,"method":"session/resume","params":{"sessionId":actor.id}}), ), + elicitation_form: false, } } @@ -1100,8 +1107,9 @@ fn resident_snapshot_follows_replay_and_precedes_success() { .command(resident_claim(&actor, true, 50), &writes) .unwrap(); let events: Vec<_> = actor - .attachment - .as_ref() + .attachments + .values() + .next() .unwrap() .events .iter() @@ -1117,7 +1125,7 @@ fn resident_snapshot_follows_replay_and_precedes_success() { assert_eq!(events[4]["id"], 50); assert_eq!( events[4]["result"]["_meta"]["kit/gateway"], - json!({"historyAvailable":true,"stateSnapshot":true,"configSnapshot":true,"attachment":actor.attachment.as_ref().unwrap().id}) + json!({"historyAvailable":true,"stateSnapshot":true,"configSnapshot":true,"attachment":actor.attachments.values().next().unwrap().id}) ); // Validate snapshots using the actual ACP v2 SDK, not an invented shape. for event in &events[2..4] { @@ -1140,7 +1148,7 @@ fn no_replay_snapshot_retains_running_state_and_current_config_after_eviction() actor .command(resident_claim(&actor, false, 51), &writes) .unwrap(); - let owner = actor.attachment.as_ref().unwrap(); + let owner = actor.attachments.values().next().unwrap(); assert_eq!(owner.events.len(), 3); assert_eq!( owner.events[0].1["params"]["update"]["configOptions"], @@ -1153,7 +1161,15 @@ fn no_replay_snapshot_retains_running_state_and_current_config_after_eviction() ); actor.output(state_update("idle")); assert_eq!( - actor.attachment.as_ref().unwrap().events.back().unwrap().1["params"]["update"]["state"], + actor + .attachments + .values() + .next() + .unwrap() + .events + .back() + .unwrap() + .1["params"]["update"]["state"], "idle" ); } @@ -1166,7 +1182,7 @@ fn replacing_a_controller_withdraws_only_its_explicit_pending_prompt() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let old = actor.attachment.as_ref().unwrap().id.clone(); + let old = actor.attachments.values().next().unwrap().id.clone(); for (id, delivery) in [(1, None), (2, Some("steer"))] { actor.command(Request::Send { session: "resident".into(), @@ -1200,7 +1216,7 @@ fn client_withdrawal_waits_for_writer_capacity_unless_the_prompt_settles() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let attachment = actor.attachment.as_ref().unwrap().id.clone(); + let attachment = actor.attachments.values().next().unwrap().id.clone(); actor.command(Request::Send { session: "resident".into(), attachment: attachment.clone(), @@ -1246,7 +1262,7 @@ async fn stop_uses_one_writer_slot_for_all_pending_withdrawals() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let attachment = actor.attachment.as_ref().unwrap().id.clone(); + let attachment = actor.attachments.values().next().unwrap().id.clone(); let send = |message, charge| Request::Send { session: "resident".into(), attachment: attachment.clone(), @@ -1327,18 +1343,18 @@ fn overflowing_the_controller_output_withdraws_its_held_prompt() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let attachment = actor.attachment.as_ref().unwrap().id.clone(); + let attachment = actor.attachments.values().next().unwrap().id.clone(); actor.command(Request::Send { session: "resident".into(), - attachment, + attachment: attachment.clone(), message: json!({"jsonrpc":"2.0","id":1,"method":"session/prompt","params":{"sessionId":"resident","delivery":"queue","prompt":[{"type":"text","text":"work"}]}}), charge: None, }, &writes).unwrap(); let prompt = received.try_recv().unwrap().message; for _ in 0..=MAX_QUEUE { - actor.emit(state_update("running")); + actor.push_to_attachment(&attachment, state_update("running")); } - assert!(actor.attachment.is_none()); + assert!(actor.attachments.is_empty()); actor.flush_withdrawals(&writes); let cancel = received.try_recv().unwrap().message; assert_eq!(cancel["method"], "$/cancel_request"); @@ -1353,7 +1369,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let old = actor.attachment.as_ref().unwrap().id.clone(); + let old = actor.attachments.values().next().unwrap().id.clone(); // Journal itself is below aggregate limits, but cannot cross HTTP as one frame. actor.remember(json!({"payload":"x".repeat(MAX_HTTP_FRAME)})); assert!(actor.replay_complete); @@ -1361,9 +1377,17 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() .command(resident_claim(&actor, true, 61), &writes) .unwrap_err(); assert_eq!(error.2, "replay_unavailable"); - assert_eq!(actor.attachment.as_ref().unwrap().id, old); + assert_eq!(actor.attachments.values().next().unwrap().id, old); assert_eq!( - actor.attachment.as_ref().unwrap().events.back().unwrap().1["id"], + actor + .attachments + .values() + .next() + .unwrap() + .events + .back() + .unwrap() + .1["id"], 60 ); actor.pending.insert( @@ -1383,9 +1407,9 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() .command(resident_claim(&actor, false, 62), &writes) .unwrap(); actor.output(json!({"jsonrpc":"2.0","id":9,"result":{"stopReason":"end_turn"}})); - let current = actor.attachment.as_ref().unwrap().id.clone(); + let current = actor.attachments.values().next().unwrap().id.clone(); assert_ne!(old, current); - assert_eq!(actor.attachment.as_ref().unwrap().events.len(), 3); + assert_eq!(actor.attachments.values().next().unwrap().events.len(), 3); let error = actor .command( Request::Detach { @@ -1396,7 +1420,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() ) .unwrap_err(); assert_eq!(error.2, "controller_replaced"); - assert_eq!(actor.attachment.as_ref().unwrap().id, current); + assert_eq!(actor.attachments.values().next().unwrap().id, current); } #[test] @@ -1407,7 +1431,7 @@ fn automatic_resume_is_conditioned_on_previous_controller_generation() { actor .command(resident_claim(&actor, false, 70), &writes) .unwrap(); - let old = actor.attachment.as_ref().unwrap().id.clone(); + let old = actor.attachments.values().next().unwrap().id.clone(); let mut recovery = resident_claim(&actor, false, 72); if let Request::Attach { startup: Some(message), @@ -1420,12 +1444,20 @@ fn automatic_resume_is_conditioned_on_previous_controller_generation() { actor .command(resident_claim(&actor, false, 71), &writes) .unwrap(); - let current = actor.attachment.as_ref().unwrap().id.clone(); + let current = actor.attachments.values().next().unwrap().id.clone(); let error = actor.command(recovery, &writes).unwrap_err(); assert_eq!(error.2, "controller_replaced"); - assert_eq!(actor.attachment.as_ref().unwrap().id, current); + assert_eq!(actor.attachments.values().next().unwrap().id, current); assert_eq!( - actor.attachment.as_ref().unwrap().events.back().unwrap().1["id"], + actor + .attachments + .values() + .next() + .unwrap() + .events + .back() + .unwrap() + .1["id"], 71 ); let mut recovery = resident_claim(&actor, false, 73); @@ -1437,13 +1469,20 @@ fn automatic_resume_is_conditioned_on_previous_controller_generation() { message["params"]["_meta"]["kit/gateway"]["previousAttachment"] = current.clone().into(); } actor.command(recovery, &writes).unwrap(); - assert_ne!(actor.attachment.as_ref().unwrap().id, current); + assert_ne!(actor.attachments.values().next().unwrap().id, current); assert_eq!( - actor.attachment.as_ref().unwrap().events.back().unwrap().1["result"]["_meta"]["kit/gateway"] - ["attachment"], - actor.attachment.as_ref().unwrap().id + actor + .attachments + .values() + .next() + .unwrap() + .events + .back() + .unwrap() + .1["result"]["_meta"]["kit/gateway"]["attachment"], + actor.attachments.values().next().unwrap().id ); - let newest = actor.attachment.as_ref().unwrap().id.clone(); + let newest = actor.attachments.values().next().unwrap().id.clone(); actor .command( Request::Detach { @@ -1472,7 +1511,7 @@ fn recovery_sequence_retries_own_unconfirmed_claim_but_not_manual_replacement() actor .command(resident_claim(&actor, false, 80), &writes) .unwrap(); - let old = actor.attachment.as_ref().unwrap().id.clone(); + let old = actor.attachments.values().next().unwrap().id.clone(); let recovery = |actor: &Actor, id| { let mut request = resident_claim(actor, false, id); if let Request::Attach { @@ -1485,19 +1524,19 @@ fn recovery_sequence_retries_own_unconfirmed_claim_but_not_manual_replacement() request }; actor.command(recovery(&actor, 81), &writes).unwrap(); - let unconfirmed = actor.attachment.as_ref().unwrap().id.clone(); + let unconfirmed = actor.attachments.values().next().unwrap().id.clone(); // The previous result was lost; reuse the same outage ID and old confirmed token. actor.command(recovery(&actor, 82), &writes).unwrap(); - assert_ne!(actor.attachment.as_ref().unwrap().id, unconfirmed); + assert_ne!(actor.attachments.values().next().unwrap().id, unconfirmed); actor .command(resident_claim(&actor, false, 83), &writes) .unwrap(); - let manual = actor.attachment.as_ref().unwrap().id.clone(); + let manual = actor.attachments.values().next().unwrap().id.clone(); assert_eq!( actor.command(recovery(&actor, 84), &writes).unwrap_err().2, "controller_replaced" ); - assert_eq!(actor.attachment.as_ref().unwrap().id, manual); + assert_eq!(actor.attachments.values().next().unwrap().id, manual); // Invalid recovery capabilities cannot mutate ownership either. for metadata in [ json!({"recoveryId":"orphan"}), @@ -1513,7 +1552,7 @@ fn recovery_sequence_retries_own_unconfirmed_claim_but_not_manual_replacement() message["params"]["_meta"]["kit/gateway"] = metadata; } assert_eq!(actor.command(request, &writes).unwrap_err().2, "protocol"); - assert_eq!(actor.attachment.as_ref().unwrap().id, manual); + assert_eq!(actor.attachments.values().next().unwrap().id, manual); } } @@ -1525,7 +1564,7 @@ fn stale_config_response_refreshes_snapshot_without_cross_generation_response() actor .command(resident_claim(&actor, false, 90), &writes) .unwrap(); - let old = actor.attachment.as_ref().unwrap().id.clone(); + let old = actor.attachments.values().next().unwrap().id.clone(); actor.pending.insert( 1, Pending { @@ -1544,12 +1583,12 @@ fn stale_config_response_refreshes_snapshot_without_cross_generation_response() .unwrap(); let options = json!([{"id":"model","name":"Model","type":"select","currentValue":"updated","options":[{"value":"updated","name":"Updated"}]}]); actor.output(json!({"jsonrpc":"2.0","id":1,"result":{"configOptions":options}})); - assert_eq!(actor.attachment.as_ref().unwrap().events.len(), 3); + assert_eq!(actor.attachments.values().next().unwrap().events.len(), 3); actor .command(resident_claim(&actor, false, 92), &writes) .unwrap(); assert_eq!( - actor.attachment.as_ref().unwrap().events[0].1["params"]["update"]["configOptions"], + actor.attachments.values().next().unwrap().events[0].1["params"]["update"]["configOptions"], options ); } @@ -1562,7 +1601,7 @@ fn aggregate_snapshot_overflow_preserves_prior_controller() { actor .command(resident_claim(&actor, false, 93), &writes) .unwrap(); - let old = actor.attachment.as_ref().unwrap().id.clone(); + let old = actor.attachments.values().next().unwrap().id.clone(); // Every frame fits, and the journal alone fits, but trailing snapshots do not. let frame = json!({"payload":"x".repeat(MAX_HTTP_FRAME / 2 - 100)}); for _ in 0..16 { @@ -1579,7 +1618,7 @@ fn aggregate_snapshot_overflow_preserves_prior_controller() { .2, "replay_unavailable" ); - assert_eq!(actor.attachment.as_ref().unwrap().id, old); + assert_eq!(actor.attachments.values().next().unwrap().id, old); } #[test] @@ -1590,7 +1629,7 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { actor .command(resident_claim(&actor, false, 100), &writes) .unwrap(); - let original = actor.attachment.as_ref().unwrap().id.clone(); + let original = actor.attachments.values().next().unwrap().id.clone(); let recovery = |actor: &Actor, previous: &str, attempt: u64| { let mut request = resident_claim(actor, false, 100 + attempt); if let Request::Attach { @@ -1609,14 +1648,14 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { actor .command(recovery(&actor, &original, 2), &writes) .unwrap(); - let second = actor.attachment.as_ref().unwrap().id.clone(); - let queued = actor.attachment.as_ref().unwrap().events.clone(); + let second = actor.attachments.values().next().unwrap().id.clone(); + let queued = actor.attachments.values().next().unwrap().events.clone(); assert_eq!( actor.command(late, &writes).unwrap_err().2, "stale_recovery" ); - assert_eq!(actor.attachment.as_ref().unwrap().id, second); - assert_eq!(actor.attachment.as_ref().unwrap().events, queued); + assert_eq!(actor.attachments.values().next().unwrap().id, second); + assert_eq!(actor.attachments.values().next().unwrap().events, queued); // Even the current attachment ID must not bypass duplicate/older fencing. for attempt in [1, 2] { let error = actor @@ -1626,12 +1665,12 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { error.data(), json!({"reason":"stale_recovery","terminal":true}) ); - assert_eq!(actor.attachment.as_ref().unwrap().events, queued); + assert_eq!(actor.attachments.values().next().unwrap().events, queued); } actor .command(recovery(&actor, &original, 3), &writes) .unwrap(); - assert_ne!(actor.attachment.as_ref().unwrap().id, second); + assert_ne!(actor.attachments.values().next().unwrap().id, second); assert_eq!( actor.committed_owner.as_ref().unwrap().recovery_attempt, Some(3) @@ -1639,7 +1678,7 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { actor .command(resident_claim(&actor, false, 104), &writes) .unwrap(); - let manual = actor.attachment.as_ref().unwrap().id.clone(); + let manual = actor.attachments.values().next().unwrap().id.clone(); assert!( actor .committed_owner @@ -1663,7 +1702,7 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { .2, "controller_replaced" ); - assert_eq!(actor.attachment.as_ref().unwrap().id, manual); + assert_eq!(actor.attachments.values().next().unwrap().id, manual); } #[test] @@ -1674,7 +1713,7 @@ fn recovery_attempt_metadata_is_paired_positive_and_bounded() { actor .command(resident_claim(&actor, false, 110), &writes) .unwrap(); - let owner = actor.attachment.as_ref().unwrap().id.clone(); + let owner = actor.attachments.values().next().unwrap().id.clone(); let mut invalid = vec![ json!({"previousAttachment":owner,"recoveryId":"missing-attempt"}), json!({"previousAttachment":owner,"recoveryAttempt":1}), @@ -1700,7 +1739,7 @@ fn recovery_attempt_metadata_is_paired_positive_and_bounded() { message["params"]["_meta"]["kit/gateway"] = metadata; } assert_eq!(actor.command(request, &writes).unwrap_err().2, "protocol"); - assert_eq!(actor.attachment.as_ref().unwrap().id, owner); + assert_eq!(actor.attachments.values().next().unwrap().id, owner); assert!( actor .committed_owner @@ -1735,13 +1774,13 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m actor .command(resident_claim(&actor, false, 200), &writes) .unwrap(); - let a = actor.attachment.as_ref().unwrap().id.clone(); + let a = actor.attachments.values().next().unwrap().id.clone(); actor .command(resident_claim(&actor, false, 201), &writes) .unwrap(); - let b = actor.attachment.as_ref().unwrap().id.clone(); + let b = actor.attachments.values().next().unwrap().id.clone(); if overflow { - actor.emit(json!({"payload":"x".repeat(MAX_REPLAY)})); + actor.push_to_attachment(&b, json!({"payload":"x".repeat(MAX_REPLAY)})); } else { actor .command( @@ -1753,7 +1792,7 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m ) .unwrap(); } - assert!(actor.attachment.is_none()); + assert!(actor.attachments.is_empty()); assert_eq!( actor .command(recovery_claim(&actor, &a, "a-outage", 1), &writes) @@ -1761,7 +1800,7 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m .2, "controller_replaced" ); - assert!(actor.attachment.is_none()); + assert!(actor.attachments.is_empty()); // Failed preparation of a manual replacement must not erase B's fence. let mut invalid = resident_claim(&actor, false, 202); @@ -1784,7 +1823,7 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m actor .command(recovery_claim(&actor, &b, "b-outage", 2), &writes) .unwrap(); - let recovered = actor.attachment.as_ref().unwrap().id.clone(); + let recovered = actor.attachments.values().next().unwrap().id.clone(); actor .command( Request::Detach { @@ -1802,7 +1841,7 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m .2, "stale_recovery" ); - assert!(actor.attachment.is_none()); + assert!(actor.attachments.is_empty()); } // Lost recovery result: original B token is still valid for the same outage. actor @@ -1874,6 +1913,7 @@ fn resident_startup_omitted_or_empty_mcp_retains_overlay() { } else { None }, + elicitation_form: false, }, &writes, ) @@ -1894,7 +1934,7 @@ fn resident_startup_omitted_or_empty_mcp_retains_overlay() { // No child request means the resident overlay is left untouched. assert!(actor.pending.is_empty()); assert!(receiver.try_recv().is_err()); - let attachment = actor.attachment.as_ref().unwrap(); + let attachment = actor.attachments.values().next().unwrap(); assert!(attachment.live); let response = &attachment.events.back().unwrap().1; assert_eq!(response["id"], 71); @@ -1920,6 +1960,7 @@ fn initial_startup_preserves_mcp_servers() { replace: false, replay: ReplayMode::None, startup: None, + elicitation_form: false, }, &writes, ) @@ -1962,13 +2003,14 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { replace: true, replay: ReplayMode::None, startup: None, + elicitation_form: false, } }, &writes, ) .unwrap(); - let owner = actor.attachment.as_ref().unwrap().id.clone(); - let events = actor.attachment.as_ref().unwrap().events.clone(); + let owner = actor.attachments.values().next().unwrap().id.clone(); + let events = actor.attachments.values().next().unwrap().events.clone(); let startup = json!({"jsonrpc":"2.0","id":76,"method":method,"params":{ "sessionId":"resident", "mcpServers":[{"name":"remote","type":"http","url":"https://example.com/mcp","headers":[]}] @@ -1979,6 +2021,7 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { replace: true, replay: ReplayMode::None, startup: Some(startup), + elicitation_form: false, } } else { Request::Send { @@ -1991,7 +2034,7 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { let error = actor.command(request, &writes).unwrap_err(); assert_eq!(error.0, StatusCode::CONFLICT); assert!(error.1.contains("_kit/session/update_mcp")); - let attachment = actor.attachment.as_ref().unwrap(); + let attachment = actor.attachments.values().next().unwrap(); assert_eq!(attachment.id, owner); assert_eq!(attachment.live, via_attach); assert_eq!(attachment.events, events); @@ -2035,7 +2078,7 @@ fn direct_mcp_update_keeps_owner_and_returns_extension_response() { json!({"jsonrpc":"2.0","id":update["id"],"result":{}}) }; actor.output(response); - let attachment = actor.attachment.as_ref().unwrap(); + let attachment = actor.attachments.values().next().unwrap(); assert_eq!(attachment.id, owner); assert!(attachment.live); let response = &attachment.events.back().unwrap().1; From c5dc937904db343169bbac116ce1096b2a86de81 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 01:33:19 +0000 Subject: [PATCH 08/19] fix(gateway): resolve ineligible pending relays on default-mode attach --- docs/reference/gateway-protocol.md | 4 +- src/gateway.rs | 66 ++++++++------ src/gateway/pinned_tests.rs | 134 +++++++++++++++++++++++++++++ 3 files changed, 176 insertions(+), 28 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index d6e10bbe..b600e684 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -178,8 +178,8 @@ Only user messages with durable identities support partial replay. Agent-message In both default single-controller mode and `--pinned-session` mode, the gateway relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending per session) to eligible live attachments and routes client-to-agent JSON-RPC responses back to the child. Each relayed request carries an opaque gateway-assigned string `id` unique across the gateway process; clients must echo that exact `id` in their JSON-RPC response and must not parse or assume any internal format. - **Client capabilities forwarded to the child:** In default mode, the gateway filters the connecting client's `initialize.params.capabilities` to forward only relayable capabilities (`elicitation.form`) and strips host-only or unsupported capabilities (`auth`, `elicitation.url`, `fs`, `terminal`). A client connecting with `capabilities: {}` therefore does not advertise `elicitation.form` and does not receive an `ask_user` tool. In `--pinned-session` mode, because multiple heterogeneous clients share one child initialized once, the gateway always advertises `{"elicitation":{"form":{}}}` to the child. -- **Capability targeting and delivery:** Each attachment records whether its own connection's `initialize` declared `capabilities.elicitation.form`. An `elicitation/create` request is offered only to live attachments (and late joiners) that declared `elicitation.form`; if no live attachment declared it—including when a `capabilities: {}` controller replaces a declaring controller in default mode, or when only headless `capabilities: {}` clients are attached in pinned mode—the gateway answers `-32601` immediately and non-declaring clients receive nothing. Requests that require no client capability in ACP v2 (such as `session/request_permission`) are offered to all live attachments and late joiners. Pending requests are re-offered right after startup to any eligible client that attaches or replaces the controller while the request is pending, without consuming live-update queue headroom before the first poll. -- **Validation, resolution, and errors:** The gateway validates relayed results against the ACP v2 response types (`CreateElicitationResponse` with non-null `content` for form `accept`, and `RequestPermissionResponse` with an offered `optionId` for `selected`), while preserving schema-valid custom or future extension actions/outcomes and leaving form-schema field validation to the child. The first valid `result` from an eligible target wins and is forwarded to the child through a bounded FIFO reply queue; any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target failed or detached mid-request, the gateway answers `-32601` to the child. An answer that fails shape validation or a non-`-32601` client error is never forwarded: that target is dropped (with a warning logged at the HTTP boundary and no JSON-RPC reply sent to a response frame), and the request stays pending if another live target or a detached target remains; if the failing sender was the only remaining target and no target detached, the gateway resolves the request promptly toward the child with `-32603` (`data.reason`: `"invalid_client_response"` or `"client_error"`) rather than waiting for `--client-request-timeout`. A target detaching without answering (such as a browser reloading or a controller being replaced) keeps the request pending until answered by a remaining or rejoining eligible client, cancelled by the agent, or expired. +- **Capability targeting and delivery:** Each attachment records whether its own connection's `initialize` declared `capabilities.elicitation.form`. An `elicitation/create` request is offered only to live attachments (and late joiners) that declared `elicitation.form`; if no live attachment declared it—including when a `capabilities: {}` controller replaces a declaring controller in default mode (even while an `elicitation/create` is already pending), or when only headless `capabilities: {}` clients are attached in pinned mode—the gateway answers `-32601` immediately and non-declaring clients receive nothing. Requests that require no client capability in ACP v2 (such as `session/request_permission`) are offered to all live attachments and late joiners. Pending requests are re-offered right after startup to any eligible client that attaches or replaces the controller while the request is pending, without consuming live-update queue headroom before the first poll. +- **Validation, resolution, and errors:** The gateway validates relayed results against the ACP v2 response types (`CreateElicitationResponse` with non-null `content` for form `accept`, and `RequestPermissionResponse` with an offered `optionId` for `selected`), while preserving schema-valid custom or future extension actions/outcomes and leaving form-schema field validation to the child. The first valid `result` from an eligible target wins and is forwarded to the child through a bounded FIFO reply queue; any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target failed or detached mid-request, the gateway answers `-32601` to the child. An answer that fails shape validation or a non-`-32601` client error is never forwarded: that target is dropped (with a warning logged at the HTTP boundary and no JSON-RPC reply sent to a response frame), and the request stays pending if another live target or a detached target remains; if the failing sender was the only remaining target and no target detached, the gateway resolves the request promptly toward the child with `-32603` (`data.reason`: `"invalid_client_response"` or `"client_error"`) rather than waiting for `--client-request-timeout`. A target detaching without answering (such as a browser reloading or a controller being replaced) keeps the request pending until answered by a remaining or rejoining eligible client, cancelled by the agent, replaced in default mode by an ineligible controller (which resolves the ineligible pending request immediately with `-32601`), or expired. - **Timeout and child exit (`--client-request-timeout`):** `--client-request-timeout ` (default `5m`, valid in both modes) is an absolute deadline measured from when the child request arrives. Expiration settles even if child stdin is temporarily saturated: the gateway buffers a `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) reply to the child and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. diff --git a/src/gateway.rs b/src/gateway.rs index 77a8f167..02d01391 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -1543,6 +1543,28 @@ impl Actor { } } } + fn resolve_ineligible_client_requests( + &mut self, + attachment_id: &str, + writes: &mpsc::Sender, + ) { + let Some(attachment) = self.attachments.get(attachment_id) else { + return; + }; + let mut ineligible: Vec<(u64, String)> = self + .client_requests + .iter() + .filter(|(_, req)| !attachment.can_receive_client_request(&req.method)) + .map(|(relay_id, req)| (req.seq, relay_id.clone())) + .collect(); + ineligible.sort_by_key(|(seq, _)| *seq); + for (_, relay_id) in ineligible { + let Some(req) = self.client_requests.remove(&relay_id) else { + continue; + }; + let _ = self.queue_child_reply(no_client_services_reply(req.child_id), None, writes); + } + } fn pending_request_messages(&self, elicitation_form: bool) -> Vec<(String, Value)> { let now = Instant::now(); let mut items: Vec<_> = self @@ -1802,22 +1824,9 @@ impl Actor { method: String, params: Value, ) -> Option { - let no_services = || { - object([ - ("jsonrpc", "2.0".into()), - ("id", child_id.clone()), - ( - "error", - object([ - ("code", (-32601).into()), - ("message", "gateway has no client-side services".into()), - ]), - ), - ]) - }; let live_targets = self.live_relay_targets(&method); if live_targets.is_empty() { - return Some(no_services()); + return Some(no_client_services_reply(child_id)); } if self.client_requests.len() >= MAX_CLIENT_REQUESTS { return Some(object([ @@ -1848,7 +1857,7 @@ impl Actor { } } if delivered.is_empty() { - return Some(no_services()); + return Some(no_client_services_reply(child_id)); } self.client_requests.insert( relay_id, @@ -2645,6 +2654,7 @@ impl Actor { if let Some(prepared) = prepared { self.apply_startup(&id, prepared); } + self.resolve_ineligible_client_requests(&id, writes); return Ok(object([ ("started", started.into()), ("attachment", id.into()), @@ -3067,17 +3077,7 @@ impl Actor { ), ]) } else { - object([ - ("jsonrpc", "2.0".into()), - ("id", req.child_id), - ( - "error", - object([ - ("code", (-32601).into()), - ("message", "gateway has no client-side services".into()), - ]), - ), - ]) + no_client_services_reply(req.child_id) }; let _ = self.queue_child_reply(reply, charge, writes); } @@ -3218,6 +3218,20 @@ fn cancel_request_message(request_id: Value) -> Value { ]) } +fn no_client_services_reply(child_id: Value) -> Value { + object([ + ("jsonrpc", "2.0".into()), + ("id", child_id), + ( + "error", + object([ + ("code", (-32601).into()), + ("message", "gateway has no client-side services".into()), + ]), + ), + ]) +} + fn incoming_transport_closed_reply(child_id: Value, method: &str) -> Value { object([ ("jsonrpc", "2.0".into()), diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index a7fbc46c..1dec4860 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -6030,3 +6030,137 @@ for line in sys.stdin: let _ = late_headless.delete().await; let _ = ui.delete().await; } + +#[tokio::test] +async fn default_mode_non_declaring_replacement_resolves_pending_elicitation_with_32601() { + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + emit({ + 'jsonrpc': '2.0', + 'method': 'session/update', + 'params': { + 'sessionId': 'def-replace-cap', + 'update': { + 'sessionUpdate': 'agent_message_chunk', + 'content': {'type': 'text', 'text': json.dumps(req)} + } + } + }) + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'def-replace-cap','configOptions':[]}}) + elif m == 'session/prompt': + emit({'jsonrpc':'2.0','id':'ask-1','method':'elicitation/create','params':{'sessionId':'def-replace-cap','mode':'form','message':'need form'}}) + emit({'jsonrpc':'2.0','id':'perm-1','method':'session/request_permission','params':{'sessionId':'def-replace-cap','options':[{'optionId':'allow','name':'Allow','kind':'allow_once'}]}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("def-replace-cap", source, &[]).await; + + // 1. Declaring controller attaches and triggers both elicitation/create and request_permission. + let c1 = harness + .connect_with_capabilities("declarer", json!({"elicitation": {"form": {}}})) + .await; + let mut s1 = c1.open_session_stream("def-replace-cap").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"def-replace-cap"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1.next_matching(|e| e["id"] == 1).await; + + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":"p1","method":"session/prompt","params":{"sessionId":"def-replace-cap","prompt":[{"type":"text","text":"go"}]}})) + .await, + StatusCode::ACCEPTED + ); + let _ = s1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let _ = s1 + .next_matching(|e| e["method"] == "session/request_permission") + .await; + + // 2. Non-declaring ({}) controller replaces Client 1 while both requests are pending. + let c2 = harness.connect("non-declarer").await; + let mut s2 = c2.open_session_stream("def-replace-cap").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"def-replace-cap"}})) + .await, + StatusCode::ACCEPTED + ); + + // Client 2 must NOT receive elicitation/create, MUST receive the child's echo of -32601 + // promptly (well before the 60s timeout), and MUST still be offered request_permission. + let mut saw_elicitation = false; + let mut saw_resume = false; + let mut ask_reply: Option = None; + let mut perm_relay_id: Option = None; + tokio::time::timeout(Duration::from_secs(5), async { + while !saw_resume || ask_reply.is_none() || perm_relay_id.is_none() { + let ev = s2.next_event().await.expect("SSE event"); + if ev["method"] == "elicitation/create" { + saw_elicitation = true; + } else if ev["id"] == 2 { + saw_resume = true; + } else if ev["method"] == "session/request_permission" { + perm_relay_id = ev["id"].as_str().map(str::to_owned); + } else if ev["method"] == "session/update" + && ev["params"]["update"]["sessionUpdate"] == "agent_message_chunk" + && let Some(text) = ev["params"]["update"]["content"]["text"].as_str() + && let Ok(parsed) = serde_json::from_str::(text) + && parsed["id"] == "ask-1" + { + ask_reply = Some(parsed); + } + } + }) + .await + .expect( + "child should receive -32601 for pending elicitation promptly upon {} controller attach", + ); + + assert!( + !saw_elicitation, + "non-declaring replacement controller must not receive elicitation/create" + ); + assert_eq!(ask_reply.unwrap()["error"]["code"], -32601); + + // Permission request remained pending and was re-offered to Client 2; answering it reaches child. + let perm_id = perm_relay_id.expect("permission request re-offered to {} controller"); + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":perm_id,"result":{"outcome":{"outcome":"selected","optionId":"allow"}}})) + .await, + StatusCode::ACCEPTED + ); + let perm_echo = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let ev = s2.next_event().await.expect("SSE event"); + if ev["method"] == "elicitation/create" { + panic!("non-declaring controller must never receive elicitation/create"); + } + if ev["method"] == "session/update" + && ev["params"]["update"]["sessionUpdate"] == "agent_message_chunk" + && let Some(text) = ev["params"]["update"]["content"]["text"].as_str() + && let Ok(parsed) = serde_json::from_str::(text) + && parsed["id"] == "perm-1" + { + break parsed; + } + } + }) + .await + .expect("permission answer should reach child"); + assert_eq!(perm_echo["result"]["outcome"]["optionId"], "allow"); + + let _ = c1.delete().await; + let _ = c2.delete().await; +} From 38492c66501ffb3f14d540f9788b2aa69affef0d Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 10:05:29 +0000 Subject: [PATCH 09/19] fix(gateway): harden relay framing, exit drain, pinned ownership, and tests --- docs/reference/gateway-protocol.md | 8 +- src/gateway.rs | 86 ++- src/gateway/http_server.rs | 11 +- src/gateway/pinned_tests.rs | 895 ++++++++++++++++++++++++++--- src/gateway/tests.rs | 116 ++-- src/session.rs | 61 ++ 6 files changed, 1019 insertions(+), 158 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index b600e684..febe977d 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -177,8 +177,8 @@ Only user messages with durable identities support partial replay. Agent-message In both default single-controller mode and `--pinned-session` mode, the gateway relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending per session) to eligible live attachments and routes client-to-agent JSON-RPC responses back to the child. Each relayed request carries an opaque gateway-assigned string `id` unique across the gateway process; clients must echo that exact `id` in their JSON-RPC response and must not parse or assume any internal format. -- **Client capabilities forwarded to the child:** In default mode, the gateway filters the connecting client's `initialize.params.capabilities` to forward only relayable capabilities (`elicitation.form`) and strips host-only or unsupported capabilities (`auth`, `elicitation.url`, `fs`, `terminal`). A client connecting with `capabilities: {}` therefore does not advertise `elicitation.form` and does not receive an `ask_user` tool. In `--pinned-session` mode, because multiple heterogeneous clients share one child initialized once, the gateway always advertises `{"elicitation":{"form":{}}}` to the child. -- **Capability targeting and delivery:** Each attachment records whether its own connection's `initialize` declared `capabilities.elicitation.form`. An `elicitation/create` request is offered only to live attachments (and late joiners) that declared `elicitation.form`; if no live attachment declared it—including when a `capabilities: {}` controller replaces a declaring controller in default mode (even while an `elicitation/create` is already pending), or when only headless `capabilities: {}` clients are attached in pinned mode—the gateway answers `-32601` immediately and non-declaring clients receive nothing. Requests that require no client capability in ACP v2 (such as `session/request_permission`) are offered to all live attachments and late joiners. Pending requests are re-offered right after startup to any eligible client that attaches or replaces the controller while the request is pending, without consuming live-update queue headroom before the first poll. +- **Client capabilities forwarded to the child:** In default mode, the gateway filters the connecting client's `initialize.params.capabilities` to forward only relayable capabilities (`elicitation.form`) and strips host-only or unsupported capabilities (`auth`, `elicitation.url`, `fs`, `terminal`). A client connecting with `capabilities: {}` therefore does not advertise `elicitation.form` and does not receive an `ask_user` tool. Because a resident child is initialized once at spawn and installs `ask_user` based on those initial capabilities, a form-capable controller that later resumes a resident default-mode session originally started by a `capabilities: {}` client will not expose `ask_user` until the child exits or is closed and restored by a form-capable controller. In `--pinned-session` mode, because multiple heterogeneous clients share one child initialized once, the gateway always advertises `{"elicitation":{"form":{}}}` to the child. +- **Capability targeting and delivery:** Each attachment records whether its own connection's `initialize` declared `capabilities.elicitation.form`. An `elicitation/create` request is offered only to live attachments (and late joiners) that declared `elicitation.form`; if no live attachment declared it—including when a `capabilities: {}` controller replaces a declaring controller in default mode (even while an `elicitation/create` is already pending), or when only headless `capabilities: {}` clients are attached in pinned mode—the gateway answers `-32601` immediately and non-declaring clients receive nothing. Requests that require no client capability in ACP v2 (such as `session/request_permission`) are offered to all live attachments and late joiners. A relayed request whose serialized frame (with its gateway-assigned `id`) exceeds the 1 MiB HTTP frame limit is rejected immediately toward the child with `-32603` (`data.reason: "frame_too_large"`) before enqueueing or recording as pending. Pending requests are re-offered right after startup to any eligible client that attaches or replaces the controller while the request is pending, without consuming live-update queue headroom before the first poll. - **Validation, resolution, and errors:** The gateway validates relayed results against the ACP v2 response types (`CreateElicitationResponse` with non-null `content` for form `accept`, and `RequestPermissionResponse` with an offered `optionId` for `selected`), while preserving schema-valid custom or future extension actions/outcomes and leaving form-schema field validation to the child. The first valid `result` from an eligible target wins and is forwarded to the child through a bounded FIFO reply queue; any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target failed or detached mid-request, the gateway answers `-32601` to the child. An answer that fails shape validation or a non-`-32601` client error is never forwarded: that target is dropped (with a warning logged at the HTTP boundary and no JSON-RPC reply sent to a response frame), and the request stays pending if another live target or a detached target remains; if the failing sender was the only remaining target and no target detached, the gateway resolves the request promptly toward the child with `-32603` (`data.reason`: `"invalid_client_response"` or `"client_error"`) rather than waiting for `--client-request-timeout`. A target detaching without answering (such as a browser reloading or a controller being replaced) keeps the request pending until answered by a remaining or rejoining eligible client, cancelled by the agent, replaced in default mode by an ineligible controller (which resolves the ineligible pending request immediately with `-32601`), or expired. - **Timeout and child exit (`--client-request-timeout`):** `--client-request-timeout ` (default `5m`, valid in both modes) is an absolute deadline measured from when the child request arrives. Expiration settles even if child stdin is temporarily saturated: the gateway buffers a `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) reply to the child and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. @@ -194,8 +194,8 @@ Start the gateway with `--pinned-session ` (and optionally `--client When pinned mode is active: - **Discovery (`initialize` and `session/list`):** `initialize.result._meta["kit/gateway"]` includes `"pinnedSession": ""`. The first client's `initialize` `info` is what the child receives, and the gateway always advertises `{"elicitation":{"form":{}}}` to the child. `session/list` returns only that single pinned session entry (even if `params.cwd` does not match, while rejecting any foreign `params.sessionId`), with `_meta["kit.gateway.state"]` set to `"resident"`, `"restorable"`, `"exited"`, or `"new"` (before first creation). -- **Workspace ownership binding:** Cold startup (`session/new` / `session/resume`) and `session/list` resolve the pinned session's existing owning workspace across all approved `--project` roots before spawning a child. A request whose `cwd` conflicts with the existing owning project is rejected (`root_denied`, `"session belongs to another project"`), and if transcripts for the pinned ID exist in more than one approved project, both discovery and startup fail (`conflict`, `"pinned session belongs to multiple approved projects"`). Creation is allowed only when no approved project already owns that ID. -- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in its owning project) and default absent/`null` `replayFrom` to no history (`historyAvailable: false`). Requests naming any other session ID fail with an error. If a single `--project` is configured (or the pinned session is already resident or bound to an existing workspace), `cwd` may be omitted. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). +- **Workspace ownership binding:** Cold startup (`session/new` / `session/resume`) and `session/list` resolve the pinned session's existing workspace-bound owner across all approved `--project` roots before discovery or spawning a child (an unbound legacy global transcript is not counted as a multi-project owner and restores into the explicitly selected approved root). For `session/new` and `session/resume`, a request whose `cwd` conflicts with the existing owning project is rejected (`root_denied`, `"session belongs to another project"`); `session/list` ignores `params.cwd` and still returns the pinned entry. If workspace-bound transcripts for the pinned ID exist in more than one approved project, both discovery and startup fail (`conflict`, `"pinned session belongs to multiple approved projects"`). Creation is allowed only when no approved project already owns that ID. +- **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in its owning project) and default absent/`null` `replayFrom` to no history (`historyAvailable: false`). Requests naming any other session ID fail with an error. If a single `--project` is configured (or the pinned session is already resident or bound to an existing workspace), `cwd` may be omitted; when multiple `--project` roots are configured and the pinned ID is not yet resident or bound to a workspace, `cwd` is required. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). - **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. - **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, its failed pending requests carry `error.data.reason = "queue_overflow"`, and its SSE stream closes cleanly without affecting other attachments or the active turn. - **Fan-in, pending caps, and orphan re-parenting:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry (whose withdrawal has not been requested), the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). A re-parented retry's prompt body is not re-validated or used: the original held prompt is what gets inserted, matching the child's duplicate-key semantics. diff --git a/src/gateway.rs b/src/gateway.rs index 02d01391..1a2a5d8f 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -795,10 +795,16 @@ async fn handle( if rows.is_empty() && let Some(root) = owner.as_ref().or_else(|| roots.first()) { + let restorable = owner.is_some() + || crate::session::belongs_to_workspace(root, &id) + .map_err(Failure::bad)?; rows.push(object([ ("session", id.into()), ("root", root.to_string_lossy().into_owned().into()), - ("state", "new".into()), + ( + "state", + if restorable { "restorable" } else { "new" }.into(), + ), ])); } return Ok::<_, Failure>(rows); @@ -887,6 +893,10 @@ async fn handle( return Err(Failure::root("session belongs to another project")); } restore = true; + } else if crate::session::belongs_to_workspace(&root, &id) + .map_err(Failure::bad)? + { + restore = true; } } else { let belongs = @@ -1390,7 +1400,7 @@ impl Actor { } } // Cancel any pending relayed requests for live targets when the child exits. - let cancelled_relays = self.cancel_all_relayed_client_requests(); + self.cancel_all_relayed_client_requests(); // EOF permits ACP's normal session cleanup to release transcript locks. // Abort the writer (including a stalled write) to close stdin, then drain // stdout concurrently with waiting: final notifications must not fill a @@ -1416,10 +1426,8 @@ impl Actor { continue; } let poll = matches!(command.request, Request::Poll { .. }); - let has_exit_drain = poll - && !stopping - && cancelled_relays - && self.has_queued_attachment_events(); + let has_exit_drain = + poll && !stopping && self.has_queued_relay_cancellations(); let result = if self.closed { self.command(command.request, &writes) } else if has_exit_drain { @@ -1463,9 +1471,10 @@ impl Actor { } }; let _ = tokio::time::timeout(LEASE, drain).await; - } else if !stopping && cancelled_relays && self.has_queued_attachment_events() { + } else if !stopping && self.has_queued_relay_cancellations() { // Briefly drain queued terminal notifications (such as $/cancel_request - // for relayed requests) before reporting child exit to live attachments. + // for relayed requests, including cancellations queued before child exit) + // before reporting child exit to live attachments. let drain = async { while let Some(command) = commands.recv().await { if matches!(command.request, Request::Shutdown) { @@ -1473,7 +1482,7 @@ impl Actor { } let result = self.drain_exited(command.request); let _ = command.reply.send(result); - if !self.has_queued_attachment_events() { + if !self.has_queued_relay_cancellations() { break; } } @@ -1502,8 +1511,13 @@ impl Actor { .map(|a| a.id.clone()) .collect() } - fn has_queued_attachment_events(&self) -> bool { - self.attachments.values().any(|a| !a.events.is_empty()) + fn has_queued_relay_cancellations(&self) -> bool { + self.attachments.values().any(|a| { + !a.overflowed + && a.events + .iter() + .any(|(_, m)| m["method"] == "$/cancel_request") + }) } fn active_attachment(&self, attachment_id: &str) -> Option<&Attachment> { self.attachments @@ -1807,16 +1821,14 @@ impl Actor { (a, b) => a.or(b), } } - fn cancel_all_relayed_client_requests(&mut self) -> bool { + fn cancel_all_relayed_client_requests(&mut self) { let drained = std::mem::take(&mut self.client_requests); - let mut notified = false; for (relay_id, req) in drained { let cancel = cancel_request_message(Value::String(relay_id)); for target in req.targets { - notified |= self.push_to_attachment(&target, cancel.clone()); + self.push_to_attachment(&target, cancel.clone()); } } - notified } fn relay_client_request( &mut self, @@ -1850,6 +1862,29 @@ impl Actor { ("method", method.clone().into()), ("params", params.clone()), ]); + if relayed.to_string().len() > MAX_HTTP_FRAME { + return Some(object([ + ("jsonrpc", "2.0".into()), + ("id", child_id), + ( + "error", + object([ + ("code", (-32603).into()), + ( + "message", + "relayed client request exceeds HTTP frame limit".into(), + ), + ( + "data", + object([ + ("reason", "frame_too_large".into()), + ("method", method.into()), + ]), + ), + ]), + ), + ])); + } let mut delivered = HashSet::new(); for target in live_targets { if self.push_to_attachment(&target, relayed.clone()) { @@ -2215,12 +2250,18 @@ impl Actor { let max_events = MAX_QUEUE.saturating_sub(snapshots.len() + 1 + reserved_events); let max_bytes = MAX_REPLAY.saturating_sub(tail_bytes.saturating_add(reserved_bytes)); let mut replay_bytes: usize = replay_events.iter().map(|m| m.to_string().len()).sum(); - while replay_events.len() > max_events - || replay_bytes > max_bytes - || replay_events - .front() - .is_some_and(|m| m.to_string().len() > MAX_HTTP_FRAME) + if let Some(last_oversized) = replay_events + .iter() + .rposition(|m| m.to_string().len() > MAX_HTTP_FRAME) { + for _ in 0..=last_oversized { + if let Some(dropped) = replay_events.pop_front() { + replay_bytes = replay_bytes.saturating_sub(dropped.to_string().len()); + } + } + replay_truncated = true; + } + while replay_events.len() > max_events || replay_bytes > max_bytes { let Some(dropped) = replay_events.pop_front() else { break; }; @@ -3171,8 +3212,7 @@ fn has_nonempty_mcp_servers(message: &Value) -> bool { fn is_client_response(message: &Value) -> bool { message.get("method").is_none() - && (message.get("result").is_some_and(|v| !v.is_null()) - || message.get("error").is_some_and(Value::is_object)) + && (message.get("result").is_some() || message.get("error").is_some_and(Value::is_object)) } fn declares_form_elicitation(client_caps: Option<&Value>) -> bool { @@ -3256,7 +3296,7 @@ fn incoming_transport_closed_reply(child_id: Value, method: &str) -> Value { fn resolve_pinned_owner(roots: &[PathBuf], id: &str) -> Result, Failure> { let mut owners = Vec::new(); for root in roots { - if crate::session::belongs_to_workspace(root, id).map_err(Failure::bad)? { + if crate::session::belongs_to_workspace_bound(root, id).map_err(Failure::bad)? { owners.push(root.clone()); } } diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 23ccb845..0541450f 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -371,6 +371,15 @@ impl Connection { }; if let Some(root) = resident_root { root + } else if let Some(pinned_id) = pinned { + let roots = self.gateway.roots.clone(); + let pinned_id = pinned_id.to_owned(); + tokio::task::spawn_blocking(move || { + super::resolve_pinned_owner(&roots, &pinned_id) + }) + .await + .map_err(|_| Failure::unavailable("catalog task failed"))?? + .ok_or_else(|| Failure::bad("cwd required"))? } else { let catalog = self.operation(Request::List).await?; catalog["sessions"] @@ -1142,7 +1151,7 @@ mod tests { session: session.into(), attachment: attached["attachment"].as_str().unwrap().into(), entry: Entry { root: actor.root.clone(), sender, stopped }, - cursor: actor.attachments.values().next().unwrap().next, + cursor: actor.sole_attachment().next, closed: false, pending: HashMap::new(), }); diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 1dec4860..3eaa0efe 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -34,12 +34,28 @@ impl PinnedHarness { async fn with_mode(pinned_session: Option, client_request_timeout: Duration) -> Self { let directory = tempfile::tempdir().unwrap(); + let root = directory.path().canonicalize().unwrap(); + Self::with_roots( + directory, + vec![root], + pinned_session, + client_request_timeout, + ) + .await + } + + async fn with_roots( + directory: TempDir, + roots: Vec, + pinned_session: Option, + client_request_timeout: Duration, + ) -> Self { let token = directory.path().join("token"); std::fs::write(&token, "pinned-secret").unwrap(); let gateway = Arc::new(Gateway { stopping: AtomicBool::new(false), token: BearerToken::load(&token).unwrap(), - roots: vec![directory.path().canonicalize().unwrap()], + roots, pinned_session, client_request_timeout, sessions: Mutex::new(HashMap::new()), @@ -60,6 +76,11 @@ impl PinnedHarness { } async fn child_source(&self, id: &str, source: &str, args: &[String]) { + self.child_source_in(id, self.gateway.roots[0].clone(), source, args) + .await; + } + + async fn child_source_in(&self, id: &str, root: PathBuf, source: &str, args: &[String]) { let child = tokio::process::Command::new("python3") .args(["-u", "-c", source]) .args(args) @@ -71,7 +92,7 @@ impl PinnedHarness { .unwrap(); let actor = Actor::new( id.to_owned(), - self.gateway.roots[0].clone(), + root.clone(), false, self.gateway.pinned_session.is_some(), self.gateway.client_request_timeout, @@ -85,7 +106,7 @@ impl PinnedHarness { self.gateway.sessions.lock().await.insert( id.to_owned(), Entry { - root: self.gateway.roots[0].clone(), + root, sender, stopped, }, @@ -2692,9 +2713,15 @@ fn pinned_reply_dropped_when_sender_detached_never_leaks_to_other_attachment() { #[tokio::test] async fn pinned_real_actor_http_overflow_isolates_slow_client_while_fast_client_continues() { let harness = PinnedHarness::new("pinned-real-ovf", Duration::from_secs(60)).await; + // Emit a single child response to client 1's request whose raw stdout line fits within + // MAX_REPLAY (8 MiB), but whose remapped client request id pushes the queued frame over + // MAX_REPLAY. That deterministically triggers `RetireMode::Overflow` on client 1's actor + // queue in one atomic step without racing the 25 ms poll tick or the SDK's 4 MiB HTTP + // egress cap, while leaving client 2 completely unaffected. let source = r#" import sys, json def emit(v): print(json.dumps(v), flush=True) +MAX_REPLAY = 8 * 1024 * 1024 for line in sys.stdin: req = json.loads(line) m = req['method'] @@ -2702,20 +2729,23 @@ for line in sys.stdin: emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) elif m in ('session/new', 'session/resume'): emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-real-ovf','configOptions':[]}}) - elif m == 'session/prompt': - pad = 'z' * (32 * 1024) - for j in range(40): - emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-real-ovf','update':{'sessionUpdate':'notice','message':f'{req["id"]}:{j}:{pad}'}}}) - emit({'jsonrpc':'2.0','id':req['id'],'result':{'stopReason':'end_turn'}}) elif m == 'kit/session/status': - emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) + if req['params'].get('hold'): + continue + if req['params'].get('overflow'): + shell = json.dumps({'jsonrpc':'2.0','id':req['id'],'result':{'pad':''}}, separators=(',',':')) + pad_len = MAX_REPLAY - len(shell) - 16 + out = json.dumps({'jsonrpc':'2.0','id':req['id'],'result':{'pad':'z' * pad_len}}, separators=(',',':')) + sys.stdout.write(out + '\n') + sys.stdout.flush() + else: + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) elif 'id' in req: emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) "#; harness.child_source("pinned-real-ovf", source, &[]).await; - // Client 1 (slow): attaches and then does NOT read its session stream during the flood! - let c1 = harness.connect("slow").await; + let c1 = harness.connect("overflower").await; let mut s1 = c1.open_session_stream("pinned-real-ovf").await; assert_eq!( c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-real-ovf"}})) @@ -2724,10 +2754,7 @@ for line in sys.stdin: ); let _ = s1.next_matching(|e| e["id"] == 1).await; - // Client 2 (fast): attaches and actively drains each paced round (~1.28 MiB / 40 frames per - // round, well within SDK egress bounds for c2, while accumulating > 15 MiB for unread c1 so - // c1 saturates its 4 MiB SDK egress and then overflows its 8 MiB actor queue!). - let c2 = harness.connect("fast").await; + let c2 = harness.connect("healthy").await; let mut s2 = c2.open_session_stream("pinned-real-ovf").await; assert_eq!( c2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pinned-real-ovf"}})) @@ -2736,42 +2763,22 @@ for line in sys.stdin: ); let _ = s2.next_matching(|e| e["id"] == 2).await; - const ROUNDS: usize = 12; - for round in 0..ROUNDS { - let req_id = format!("burst-{round}"); - assert_eq!( - c2.post(json!({"jsonrpc":"2.0","id":req_id,"method":"session/prompt","params":{"sessionId":"pinned-real-ovf","prompt":[{"type":"text","text":"flood"}]}})) - .await, - StatusCode::ACCEPTED - ); - let mut notices = 0usize; - let mut saw_reply = false; - while !saw_reply || notices < 40 { - let ev = tokio::time::timeout(Duration::from_secs(15), s2.next_event()) - .await - .unwrap() - .expect("fast client stream must stay open"); - if ev["params"]["update"]["sessionUpdate"] == "notice" { - notices += 1; - } - if ev["id"] == req_id { - saw_reply = true; - } - } - } - - // Client 2 continues working normally after slow Client 1 overflowed. + // Submit a held request on c1 so we also verify pending request settlement on queue_overflow. assert_eq!( - c2.post(json!({"jsonrpc":"2.0","id":"after-burst","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf"}})) + c1.post(json!({"jsonrpc":"2.0","id":"still-pending","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf","hold":true}})) + .await, + StatusCode::ACCEPTED + ); + // Trigger deterministic actor-queue overflow for c1 alone via a long client request id. + let long_id = "o".repeat(256); + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":long_id,"method":"kit/session/status","params":{"sessionId":"pinned-real-ovf","overflow":true}})) .await, StatusCode::ACCEPTED ); - let status = s2.next_matching(|e| e["id"] == "after-burst").await; - assert_eq!(status["result"]["settled"], true); - // Now drain slow Client 1's stream: it must receive `_gateway_controller` with `queue_overflow` - // and close cleanly without having disrupted Client 2! let mut saw_overflow_notice = false; + let mut saw_pending_overflow_error = false; let mut ended_cleanly = false; let deadline = tokio::time::Instant::now() + Duration::from_secs(15); while tokio::time::Instant::now() < deadline { @@ -2782,6 +2789,10 @@ for line in sys.stdin: { saw_overflow_notice = true; } + if ev["id"] == "still-pending" && ev["error"]["data"]["reason"] == "queue_overflow" + { + saw_pending_overflow_error = true; + } } Ok(None) => { ended_cleanly = true; @@ -2791,9 +2802,18 @@ for line in sys.stdin: } } assert!( - ended_cleanly && saw_overflow_notice, - "overflowed slow client stream must emit queue_overflow notice and close cleanly (ended={ended_cleanly}, notice={saw_overflow_notice})" + ended_cleanly && saw_overflow_notice && saw_pending_overflow_error, + "overflowed client stream must emit queue_overflow notice + pending errors and close cleanly (ended={ended_cleanly}, notice={saw_overflow_notice}, err={saw_pending_overflow_error})" + ); + + // Client 2 continues working normally after Client 1 overflowed. + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":"after-burst","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf"}})) + .await, + StatusCode::ACCEPTED ); + let status = s2.next_matching(|e| e["id"] == "after-burst").await; + assert_eq!(status["result"]["settled"], true); let _ = c1.delete().await; let _ = c2.delete().await; @@ -4299,7 +4319,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star let (writes, mut child_rx) = mpsc::channel(8); // Attach initial controller so updates & relays have a live target. - let c1 = actor + let _c1 = actor .command( Request::Attach { session: "def-replay".into(), @@ -4370,7 +4390,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star ); // 2. `_kit_message` in default mode replays inclusively from u-1 and rejects unknown with -32602. - let _c3 = actor + let c3 = actor .command( Request::Attach { session: "def-replay".into(), @@ -4383,12 +4403,12 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star }, &writes, ) - .unwrap(); - let events_msg: Vec = actor - .attachments - .values() - .next() + .unwrap()["attachment"] + .as_str() .unwrap() + .to_owned(); + let events_msg: Vec = actor + .sole_attachment() .events .iter() .map(|(_, m)| m.clone()) @@ -4416,7 +4436,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star .unwrap_err(); assert_eq!(bad_cursor.jsonrpc_code(), -32602); // Failed cursor preserves current controller! - assert_ne!(actor.attachments.values().next().unwrap().id, c1); + assert_eq!(actor.sole_attachment().id, c3); // 3. Exact full complete journal + pending relayed request succeeds with ReplayMode::Start in default mode! let mut full_actor = default_actor("def-full-start", Duration::from_secs(60)); @@ -4443,7 +4463,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star "params": {"sessionId": "def-full-start", "update": {"sessionUpdate": "notice", "message": format!("d-{i}")}} })); if i % 64 == 0 { - let cur = full_actor.attachments.values().next().unwrap().next; + let cur = full_actor.sole_attachment().next; let _ = full_actor.command( Request::Poll { session: "def-full-start".into(), @@ -4481,10 +4501,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star .as_str() .unwrap() .to_owned(); - assert_eq!( - full_actor.attachments.values().next().unwrap().events.len(), - MAX_QUEUE + 1 - ); + assert_eq!(full_actor.sole_attachment().events.len(), MAX_QUEUE + 1); assert_eq!( full_actor .attachments @@ -4924,6 +4941,8 @@ for line in sys.stdin: r2 = json.loads(line2) if 'method' not in r2 and isinstance(r2.get('id'), str) and r2['id'].startswith('cap-'): rejections.append((r2['id'], r2.get('error', {}).get('code'))) + if len(rejections) == 2: + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-sat','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'rejections-ready'}}}}) elif r2.get('method') == 'kit/session/status': emit({'jsonrpc':'2.0','id':r2['id'],'result':{'rejections':rejections}}) elif 'id' in r2: @@ -4970,14 +4989,18 @@ for line in sys.stdin: .get("pinned-sat") .cloned() .unwrap(); - let actor_call = |request: Request| { + let actor_try_call = |request: Request| { let sender = entry.sender.clone(); async move { let (reply, rx) = oneshot::channel(); sender.send(Envelope { request, reply }).await.unwrap(); - rx.await.unwrap().unwrap() + rx.await.unwrap() } }; + let actor_call = |request: Request| { + let fut = actor_try_call(request); + async move { fut.await.unwrap() } + }; let filler = actor_call(Request::Attach { session: "pinned-sat".into(), replay: ReplayMode::None, @@ -4989,7 +5012,15 @@ for line in sys.stdin: .as_str() .unwrap() .to_owned(); - let big = "p".repeat(256 * 1024); + // Deterministically saturate the 16-slot `writes` channel without a fixed sleep: + // 1) Prompt 0 (512 KiB, well above the OS pipe buffer while child is parked at `gate`) + // is enqueued first. + // 2) Enqueueing prompts 1..=16 (17 accepted messages total for a 16-slot channel) + // cannot complete until the writer task has popped prompt 0 and blocked inside + // `write_all`. If prompt 16 momentarily sees `unavailable` before the writer pops + // prompt 0, yield and retry until all 16 slots are filled. + // 3) Probe prompt 17 MUST fail with `unavailable`, proving `writes` is full. + let big = "p".repeat(512 * 1024); let _ = actor_call(Request::Send { session: "pinned-sat".into(), attachment: filler.clone(), @@ -5002,21 +5033,47 @@ for line in sys.stdin: charge: None, }) .await; - tokio::time::sleep(Duration::from_millis(100)).await; - for i in 1..=16 { - let _ = actor_call(Request::Send { - session: "pinned-sat".into(), - attachment: filler.clone(), - message: json!({ - "jsonrpc": "2.0", - "id": 200 + i, - "method": "session/prompt", - "params": {"sessionId": "pinned-sat", "delivery": "queue", "prompt": [{"type": "text", "text": format!("fill-{i}")}]} - }), - charge: None, - }) - .await; - } + tokio::time::timeout(Duration::from_secs(5), async { + for i in 1..=16 { + loop { + match actor_try_call(Request::Send { + session: "pinned-sat".into(), + attachment: filler.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": 200 + i, + "method": "session/prompt", + "params": {"sessionId": "pinned-sat", "delivery": "queue", "prompt": [{"type": "text", "text": format!("fill-{i}")}]} + }), + charge: None, + }) + .await + { + Ok(_) => break, + Err(err) if err.0 == StatusCode::SERVICE_UNAVAILABLE => { + tokio::task::yield_now().await; + } + Err(err) => panic!("unexpected filler send error: {err:?}"), + } + } + } + }) + .await + .expect("writer task should pop prompt 0 and allow all 16 channel slots to fill"); + let full = actor_try_call(Request::Send { + session: "pinned-sat".into(), + attachment: filler.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": 217, + "method": "session/prompt", + "params": {"sessionId": "pinned-sat", "delivery": "queue", "prompt": [{"type": "text", "text": "probe-full"}]} + }), + charge: None, + }) + .await + .expect_err("17th queued prompt must fail when writes channel is saturated"); + assert_eq!(full.0, StatusCode::SERVICE_UNAVAILABLE); let _ = actor_call(Request::Detach { session: "pinned-sat".into(), attachment: filler, @@ -5035,6 +5092,12 @@ for line in sys.stdin: sock.write_all(b"R").await.unwrap(); let trigger_done = s1.next_matching(|e| e["id"] == 100).await; assert_eq!(trigger_done["result"]["settled"], true); + let _ = s1 + .next_matching(|e| { + e["method"] == "session/update" + && e["params"]["update"]["content"]["text"] == "rejections-ready" + }) + .await; // Ask the still-living child for the rejections it received (after draining the queued prompts). assert_eq!( @@ -6164,3 +6227,679 @@ for line in sys.stdin: let _ = c1.delete().await; let _ = c2.delete().await; } + +#[test] +fn current_turn_replay_trims_past_oversized_interior_update() { + let mut actor = pinned_actor("oversized-interior", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "oversized-interior", "configOptions": []})); + let (writes, _rx) = mpsc::channel(8); + + // Build a turn that fits the 8 MiB aggregate budget and starts with a small update, + // has a >1 MiB interior update, and ends with a small usable tail update. + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "oversized-interior", "update": {"sessionUpdate": "state_update", "state": "running"}} + })); + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "oversized-interior", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "before-oversized"}}} + })); + let oversized = "x".repeat(MAX_HTTP_FRAME + 1024); + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "oversized-interior", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": oversized}}} + })); + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "oversized-interior", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "after-oversized"}}} + })); + + let c1 = actor + .command( + Request::Attach { + session: "oversized-interior".into(), + replay: ReplayMode::CurrentTurn, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"oversized-interior"}})), + elicitation_form: true, + }, + &writes, + ) + .expect("current-turn replay must trim past an oversized interior update") + ["attachment"] + .as_str() + .unwrap() + .to_owned(); + let events: Vec = actor.attachments[&c1] + .events + .iter() + .map(|(_, m)| m.clone()) + .collect(); + assert!( + events.iter().all(|m| m.to_string().len() <= MAX_HTTP_FRAME), + "every replayed frame must fit within MAX_HTTP_FRAME" + ); + assert!( + !events + .iter() + .any(|m| m["params"]["update"]["content"]["text"] == "before-oversized"), + "updates before the oversized interior frame must be trimmed" + ); + assert!( + events + .iter() + .any(|m| m["params"]["update"]["content"]["text"] == "after-oversized"), + "usable tail after the oversized interior frame must be preserved" + ); + let startup_reply = events.iter().find(|m| m["id"] == 1).unwrap(); + assert_eq!( + startup_reply["result"]["_meta"]["kit/gateway"]["replayTruncated"], + true + ); +} + +#[tokio::test] +async fn expired_relay_cancellation_drains_when_child_exits_before_next_poll() { + let gate = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let gate_port = gate.local_addr().unwrap().port(); + let source = r#" +import sys, json, socket +gate_port = int(sys.argv[1]) +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req.get('id') == 'ask-exp': + s = socket.create_connection(('127.0.0.1', gate_port)) + s.close() + sys.exit(0) + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'exp-exit','configOptions':[]}}) + elif m == 'session/prompt': + emit({'jsonrpc':'2.0','id':'ask-exp','method':'elicitation/create','params':{'sessionId':'exp-exit','mode':'form','message':'hurry'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", source, &gate_port.to_string()]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let actor = Actor::new( + "exp-exit".into(), + dir.path().canonicalize().unwrap(), + false, + true, + Duration::from_millis(150), + ); + let (sender, receiver) = mpsc::channel(32); + let actor_task = tokio::spawn(async move { + actor.run(child, receiver).await; + }); + let call = |request: Request| { + let sender = sender.clone(); + async move { + let (reply, rx) = oneshot::channel(); + sender.send(Envelope { request, reply }).await.unwrap(); + rx.await.unwrap() + } + }; + + let att = call(Request::Attach { + session: "exp-exit".into(), + replay: ReplayMode::None, + replace: false, + startup: None, + elicitation_form: true, + }) + .await + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + call(Request::Send { + session: "exp-exit".into(), + attachment: att.clone(), + message: json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":2,"capabilities":{"elicitation":{"form":{}}}}}), + charge: None, + }) + .await + .unwrap(); + call(Request::Send { + session: "exp-exit".into(), + attachment: att.clone(), + message: json!({"jsonrpc":"2.0","id":2,"method":"session/new","params":{"cwd": dir.path()}}), + charge: None, + }) + .await + .unwrap(); + + // Poll until startup completes, then send prompt and poll until elicitation/create arrives. + let mut cursor = 0u64; + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let res = call(Request::Poll { + session: "exp-exit".into(), + attachment: att.clone(), + cursor, + }) + .await + .unwrap(); + let mut started = false; + for ev in res["events"].as_array().unwrap() { + cursor = ev["cursor"].as_u64().unwrap(); + if ev["message"]["id"] == 2 { + started = true; + } + } + if started { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + + call(Request::Send { + session: "exp-exit".into(), + attachment: att.clone(), + message: json!({"jsonrpc":"2.0","id":"p1","method":"session/prompt","params":{"sessionId":"exp-exit","prompt":[{"type":"text","text":"ask"}]}}), + charge: None, + }) + .await + .unwrap(); + let relay_id = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let res = call(Request::Poll { + session: "exp-exit".into(), + attachment: att.clone(), + cursor, + }) + .await + .unwrap(); + for ev in res["events"].as_array().unwrap() { + cursor = ev["cursor"].as_u64().unwrap(); + if ev["message"]["method"] == "elicitation/create" { + return ev["message"]["id"].as_str().unwrap().to_owned(); + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + + // Wait for the relay to expire AND the child to receive -32603 and exit BEFORE we poll again. + let (mut sock, _) = tokio::time::timeout(Duration::from_secs(5), gate.accept()) + .await + .unwrap() + .unwrap(); + let mut eof = Vec::new(); + tokio::io::AsyncReadExt::read_to_end(&mut sock, &mut eof) + .await + .unwrap(); + + // Deterministically wait until the actor has left its main loop (child exit observed) + // before polling for the queued $/cancel_request. + tokio::time::timeout(Duration::from_secs(5), async { + let mut probe_id = 500u64; + loop { + probe_id += 1; + match call(Request::Send { + session: "exp-exit".into(), + attachment: att.clone(), + message: json!({"jsonrpc":"2.0","id":probe_id,"method":"kit/session/status","params":{"sessionId":"exp-exit"}}), + charge: None, + }) + .await + { + Err(err) if err.0 == StatusCode::SERVICE_UNAVAILABLE => break, + Ok(_) => tokio::time::sleep(Duration::from_millis(10)).await, + Err(err) => panic!("unexpected probe error: {err:?}"), + } + } + }) + .await + .expect("actor should observe child exit"); + + // Poll MUST still receive the queued $/cancel_request from the post-exit drain even though + // the relay expired before child exit. + let saw_cancel = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let res = call(Request::Poll { + session: "exp-exit".into(), + attachment: att.clone(), + cursor, + }) + .await + .expect("queued $/cancel_request must drain after child exit"); + for ev in res["events"].as_array().unwrap() { + cursor = ev["cursor"].as_u64().unwrap(); + if ev["message"]["method"] == "$/cancel_request" + && ev["message"]["params"]["requestId"] == relay_id + { + return true; + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert!(saw_cancel); + + // Acknowledge the cancellation cursor -> next poll reports child exit and actor finishes cleanly. + let err = call(Request::Poll { + session: "exp-exit".into(), + attachment: att, + cursor, + }) + .await + .unwrap_err(); + assert_eq!(err.0, StatusCode::SERVICE_UNAVAILABLE); + tokio::time::timeout(Duration::from_secs(5), actor_task) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn pinned_unbound_legacy_global_transcript_does_not_cause_false_multi_owner_conflict() { + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("first"); + let second = dir.path().join("second"); + std::fs::create_dir_all(&first).unwrap(); + std::fs::create_dir_all(&second).unwrap(); + let first = first.canonicalize().unwrap(); + let second = second.canonicalize().unwrap(); + + let session_id = format!("pinned-legacy-{}", crate::session::new_id()); + let home = std::env::var_os("HOME").expect("HOME set by test harness"); + let global_dir = PathBuf::from(home).join(".kit/sessions"); + std::fs::create_dir_all(&global_dir).unwrap(); + let global_transcript = global_dir.join(format!("{session_id}.jsonl")); + struct CleanupFile(PathBuf); + impl Drop for CleanupFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let _cleanup = CleanupFile(global_transcript.clone()); + + let legacy_record = json!({ + "schema_version": 2, + "session_id": session_id, + "generation": 1, + "item": agentkit_core::Item::text(agentkit_core::ItemKind::System, "legacy global"), + }); + std::fs::write(&global_transcript, format!("{legacy_record}\n")).unwrap(); + + let harness = PinnedHarness::with_roots( + dir, + vec![first.clone(), second.clone()], + Some(session_id.clone()), + Duration::from_secs(60), + ) + .await; + + // 1. Unbound global transcript alone MUST NOT report multiple approved projects! + assert_eq!( + resolve_pinned_owner(&[first.clone(), second.clone()], &session_id).unwrap(), + None + ); + let listed = handle(State(harness.gateway.clone()), Json(Request::List)) + .await + .expect("list must succeed with single unbound global transcript") + .0; + assert_eq!(listed["sessions"].as_array().unwrap().len(), 1); + assert_eq!(listed["sessions"][0]["session"], session_id); + assert_eq!(listed["sessions"][0]["state"], "restorable"); + + // 2. Adding a workspace-bound transcript in `first` alongside the unbound global transcript + // MUST resolve cleanly to `first` (not a multi-owner conflict). + let first_local = first.join(".kit/sessions"); + std::fs::create_dir_all(&first_local).unwrap(); + std::fs::write( + first_local.join(format!("{session_id}.jsonl")), + format!("{legacy_record}\n"), + ) + .unwrap(); + assert_eq!( + resolve_pinned_owner(&[first.clone(), second.clone()], &session_id).unwrap(), + Some(first.clone()) + ); + let listed_bound = handle(State(harness.gateway.clone()), Json(Request::List)) + .await + .expect("list must resolve to sole bound workspace owner") + .0; + assert_eq!( + listed_bound["sessions"][0]["root"], + first.to_string_lossy().as_ref() + ); + assert_eq!(listed_bound["sessions"][0]["state"], "restorable"); + + let wrong_root = handle( + State(harness.gateway.clone()), + Json(Request::Create { + root: second.clone(), + session: Some(session_id.clone()), + force: false, + }), + ) + .await + .unwrap_err(); + assert_eq!(wrong_root.2, "root_denied"); + + // 3. Adding a second distinct workspace-bound transcript in `second` MUST fail with conflict. + let second_local = second.join(".kit/sessions"); + std::fs::create_dir_all(&second_local).unwrap(); + std::fs::write( + second_local.join(format!("{session_id}.jsonl")), + format!("{legacy_record}\n"), + ) + .unwrap(); + let conflict = resolve_pinned_owner(&[first, second], &session_id).unwrap_err(); + assert_eq!(conflict.0, StatusCode::CONFLICT); +} + +#[tokio::test] +async fn pinned_multi_root_requires_explicit_cwd_before_first_creation() { + let dir = tempfile::tempdir().unwrap(); + let root1 = dir.path().join("proj-a"); + let root2 = dir.path().join("proj-b"); + std::fs::create_dir_all(&root1).unwrap(); + std::fs::create_dir_all(&root2).unwrap(); + let root1 = root1.canonicalize().unwrap(); + let root2 = root2.canonicalize().unwrap(); + + let harness = PinnedHarness::with_roots( + dir, + vec![root1.clone(), root2.clone()], + Some("multi-pin".into()), + Duration::from_secs(60), + ) + .await; + + let mut c1 = harness.connect("client-1").await; + // Before the pinned session exists in any project, omitting cwd MUST fail with "cwd required" + // rather than silently creating in roots[0] from the synthetic state="new" discovery row. + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":10,"method":"session/new","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let new_err = c1.conn_stream.next_matching(|e| e["id"] == 10).await; + assert_eq!(new_err["error"]["data"]["reason"], "protocol"); + assert!( + new_err["error"]["message"] + .as_str() + .unwrap() + .contains("cwd required"), + "unexpected error: {new_err}" + ); + + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":11,"method":"session/resume","params":{"sessionId":"multi-pin"}})) + .await, + StatusCode::ACCEPTED + ); + let resume_err = c1.conn_stream.next_matching(|e| e["id"] == 11).await; + assert_eq!(resume_err["error"]["data"]["reason"], "protocol"); + assert!( + resume_err["error"]["message"] + .as_str() + .unwrap() + .contains("cwd required"), + "unexpected error: {resume_err}" + ); + + // Once resident in root2, omitting cwd attaches to root2, and passing root1 is rejected. + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req.get('method') + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'multi-pin','configOptions':[]}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness + .child_source_in("multi-pin", root2.clone(), source, &[]) + .await; + + let _s1 = c1.open_session_stream("multi-pin").await; + assert_eq!( + c1.post(json!({"jsonrpc":"2.0","id":12,"method":"session/new","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let ok = c1.conn_stream.next_matching(|e| e["id"] == 12).await; + assert_eq!(ok["result"]["sessionId"], "multi-pin"); + + let mut c2 = harness.connect("client-2").await; + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":13,"method":"session/resume","params":{"sessionId":"multi-pin","cwd": root1}})) + .await, + StatusCode::ACCEPTED + ); + let wrong_cwd = c2.conn_stream.next_matching(|e| e["id"] == 13).await; + assert_eq!(wrong_cwd["error"]["data"]["reason"], "root_denied"); + + let _ = c1.delete().await; + let _ = c2.delete().await; +} + +#[tokio::test] +async fn oversized_relayed_request_is_rejected_before_enqueueing_and_keeps_connection_alive() { + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source_a = r#" +import sys, json +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req.get('id') == 'ask-huge' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'err': req.get('error')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'ov-a','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({'jsonrpc':'2.0','id':'ask-huge','method':'elicitation/create','params':{'sessionId':'ov-a','mode':'form','message':'x' * (1024 * 1024 + 1024)}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let source_b = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req.get('method') + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'ov-b','configOptions':[]}}) + elif m == 'session/prompt': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'ok': True}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("ov-a", source_a, &[]).await; + harness.child_source("ov-b", source_b, &[]).await; + + let conn = harness + .connect_with_capabilities("mux", json!({"elicitation": {"form": {}}})) + .await; + let mut sa = conn.open_session_stream("ov-a").await; + let mut sb = conn.open_session_stream("ov-b").await; + assert_eq!( + conn.post( + json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"ov-a"}}) + ) + .await, + StatusCode::ACCEPTED + ); + let _ = sa.next_matching(|e| e["id"] == 1).await; + assert_eq!( + conn.post( + json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"ov-b"}}) + ) + .await, + StatusCode::ACCEPTED + ); + let _ = sb.next_matching(|e| e["id"] == 2).await; + + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"p-huge","method":"session/prompt","params":{"sessionId":"ov-a","prompt":[{"type":"text","text":"huge"}]}})) + .await, + StatusCode::ACCEPTED + ); + let mut saw_elicitation = false; + let done_a = sa + .next_matching(|e| { + if e["method"] == "elicitation/create" { + saw_elicitation = true; + } + e["id"] == "p-huge" + }) + .await; + assert!( + !saw_elicitation, + "oversized relay must never be enqueued to attachments" + ); + assert_eq!(done_a["result"]["err"]["code"], -32603); + assert_eq!(done_a["result"]["err"]["data"]["reason"], "frame_too_large"); + + // Unrelated session on the same connection remains healthy. + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"p-b","method":"session/prompt","params":{"sessionId":"ov-b","prompt":[{"type":"text","text":"hi"}]}})) + .await, + StatusCode::ACCEPTED + ); + let done_b = sb.next_matching(|e| e["id"] == "p-b").await; + assert_eq!(done_b["result"]["ok"], true); + + let _ = conn.delete().await; +} + +#[tokio::test] +async fn null_relay_result_routes_through_response_validation_without_echoing_rpc_error() { + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source = r#" +import sys, json +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req.get('id') == 'ask-null' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'res': req.get('result'), 'err': req.get('error')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'null-res','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({'jsonrpc':'2.0','id':'ask-null','method':'elicitation/create','params':{'sessionId':'null-res','mode':'form','message':'answer'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("null-res", source, &[]).await; + + let mut conn = harness + .connect_with_capabilities("ui", json!({"elicitation": {"form": {}}})) + .await; + let mut stream = conn.open_session_stream("null-res").await; + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"null-res"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = stream.next_matching(|e| e["id"] == 1).await; + + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"p1","method":"session/prompt","params":{"sessionId":"null-res","prompt":[{"type":"text","text":"go"}]}})) + .await, + StatusCode::ACCEPTED + ); + let ask = stream + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let relay_id = ask["id"].as_str().unwrap().to_owned(); + + // Send explicit `result: null` response -> MUST route through response validation, + // resolve promptly toward the child with -32603 invalid_client_response, and NEVER + // echo a JSON-RPC error back to the client using relay_id. + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":relay_id,"result":null})) + .await, + StatusCode::ACCEPTED + ); + let mut echoed_relay_error = false; + let done = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let ev = stream.next_event().await.expect("SSE event"); + if ev.get("id").and_then(Value::as_str) == Some(relay_id.as_str()) { + echoed_relay_error = true; + } + if ev["id"] == "p1" { + break ev; + } + } + }) + .await + .expect("sole-responder null result must resolve promptly rather than waiting for timeout"); + assert!( + !echoed_relay_error, + "must not echo a JSON-RPC error back to a response frame" + ); + assert_eq!(done["result"]["err"]["code"], -32603); + assert_eq!( + done["result"]["err"]["data"]["reason"], + "invalid_client_response" + ); + + // Also verify conn_stream received no JSON-RPC error for relay_id by running a quick session/list. + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":99,"method":"session/list","params":{}})) + .await, + StatusCode::ACCEPTED + ); + let list_reply = conn + .conn_stream + .next_matching(|e| { + if e.get("id").and_then(Value::as_str) == Some(relay_id.as_str()) { + panic!("unexpected JSON-RPC reply to response frame on conn_stream: {e}"); + } + e["id"] == 99 + }) + .await; + assert!(list_reply["result"]["sessions"].is_array()); + + let _ = conn.delete().await; +} diff --git a/src/gateway/tests.rs b/src/gateway/tests.rs index 3b963135..a48345d1 100644 --- a/src/gateway/tests.rs +++ b/src/gateway/tests.rs @@ -9,6 +9,18 @@ use super::*; use serde_json::json; use tempfile::TempDir; +impl Actor { + pub(super) fn sole_attachment(&self) -> &Attachment { + assert_eq!( + self.attachments.len(), + 1, + "expected exactly one attachment, found {}", + self.attachments.len() + ); + self.attachments.values().next().unwrap() + } +} + struct Harness { _directory: TempDir, client: reqwest::Client, @@ -577,12 +589,12 @@ fn failed_replay_claim_preserves_owner_and_stale_release_preserves_replacement() ) .is_err() ); - assert_eq!(actor.attachments.values().next().unwrap().id, second); + assert_eq!(actor.sole_attachment().id, second); actor.remember(json!({"payload":"x".repeat(MAX_REPLAY + 1)})); assert!(!actor.replay_complete); assert!(actor.journal_bytes <= MAX_REPLAY); assert!(actor.command(claim(true), &writes).is_err()); - assert_eq!(actor.attachments.values().next().unwrap().id, second); + assert_eq!(actor.sole_attachment().id, second); } #[tokio::test] @@ -674,7 +686,7 @@ fn transcript_replay_overflow_returns_error_not_truncated_success() { assert_eq!(response["id"], 42); assert!(response.get("error").is_some()); assert!(response.get("result").is_none()); - assert!(!actor.attachments.values().next().unwrap().live); + assert!(!actor.sole_attachment().live); } #[test] @@ -712,7 +724,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { }, ); actor.output(json!({"jsonrpc":"2.0","id":1,"result":{"sessionId":"resident"}})); - let owner = actor.attachments.values().next().unwrap(); + let owner = actor.sole_attachment(); assert!(owner.live); assert_eq!(owner.events.len(), 3); assert_eq!(owner.events[2].1["id"], 42); @@ -736,7 +748,7 @@ fn no_replay_restore_and_claim_survive_incomplete_internal_cache() { ) .is_err() ); - assert_eq!(actor.attachments.values().next().unwrap().id, attachment); + assert_eq!(actor.sole_attachment().id, attachment); } #[tokio::test] @@ -1125,7 +1137,7 @@ fn resident_snapshot_follows_replay_and_precedes_success() { assert_eq!(events[4]["id"], 50); assert_eq!( events[4]["result"]["_meta"]["kit/gateway"], - json!({"historyAvailable":true,"stateSnapshot":true,"configSnapshot":true,"attachment":actor.attachments.values().next().unwrap().id}) + json!({"historyAvailable":true,"stateSnapshot":true,"configSnapshot":true,"attachment":actor.sole_attachment().id}) ); // Validate snapshots using the actual ACP v2 SDK, not an invented shape. for event in &events[2..4] { @@ -1148,7 +1160,7 @@ fn no_replay_snapshot_retains_running_state_and_current_config_after_eviction() actor .command(resident_claim(&actor, false, 51), &writes) .unwrap(); - let owner = actor.attachments.values().next().unwrap(); + let owner = actor.sole_attachment(); assert_eq!(owner.events.len(), 3); assert_eq!( owner.events[0].1["params"]["update"]["configOptions"], @@ -1182,7 +1194,7 @@ fn replacing_a_controller_withdraws_only_its_explicit_pending_prompt() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let old = actor.attachments.values().next().unwrap().id.clone(); + let old = actor.sole_attachment().id.clone(); for (id, delivery) in [(1, None), (2, Some("steer"))] { actor.command(Request::Send { session: "resident".into(), @@ -1216,7 +1228,7 @@ fn client_withdrawal_waits_for_writer_capacity_unless_the_prompt_settles() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let attachment = actor.attachments.values().next().unwrap().id.clone(); + let attachment = actor.sole_attachment().id.clone(); actor.command(Request::Send { session: "resident".into(), attachment: attachment.clone(), @@ -1262,7 +1274,7 @@ async fn stop_uses_one_writer_slot_for_all_pending_withdrawals() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let attachment = actor.attachments.values().next().unwrap().id.clone(); + let attachment = actor.sole_attachment().id.clone(); let send = |message, charge| Request::Send { session: "resident".into(), attachment: attachment.clone(), @@ -1343,7 +1355,7 @@ fn overflowing_the_controller_output_withdraws_its_held_prompt() { actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let attachment = actor.attachments.values().next().unwrap().id.clone(); + let attachment = actor.sole_attachment().id.clone(); actor.command(Request::Send { session: "resident".into(), attachment: attachment.clone(), @@ -1369,7 +1381,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() actor .command(resident_claim(&actor, false, 60), &writes) .unwrap(); - let old = actor.attachments.values().next().unwrap().id.clone(); + let old = actor.sole_attachment().id.clone(); // Journal itself is below aggregate limits, but cannot cross HTTP as one frame. actor.remember(json!({"payload":"x".repeat(MAX_HTTP_FRAME)})); assert!(actor.replay_complete); @@ -1377,7 +1389,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() .command(resident_claim(&actor, true, 61), &writes) .unwrap_err(); assert_eq!(error.2, "replay_unavailable"); - assert_eq!(actor.attachments.values().next().unwrap().id, old); + assert_eq!(actor.sole_attachment().id, old); assert_eq!( actor .attachments @@ -1407,9 +1419,9 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() .command(resident_claim(&actor, false, 62), &writes) .unwrap(); actor.output(json!({"jsonrpc":"2.0","id":9,"result":{"stopReason":"end_turn"}})); - let current = actor.attachments.values().next().unwrap().id.clone(); + let current = actor.sole_attachment().id.clone(); assert_ne!(old, current); - assert_eq!(actor.attachments.values().next().unwrap().events.len(), 3); + assert_eq!(actor.sole_attachment().events.len(), 3); let error = actor .command( Request::Detach { @@ -1420,7 +1432,7 @@ fn failed_resident_snapshot_preserves_owner_and_success_fences_old_generation() ) .unwrap_err(); assert_eq!(error.2, "controller_replaced"); - assert_eq!(actor.attachments.values().next().unwrap().id, current); + assert_eq!(actor.sole_attachment().id, current); } #[test] @@ -1431,7 +1443,7 @@ fn automatic_resume_is_conditioned_on_previous_controller_generation() { actor .command(resident_claim(&actor, false, 70), &writes) .unwrap(); - let old = actor.attachments.values().next().unwrap().id.clone(); + let old = actor.sole_attachment().id.clone(); let mut recovery = resident_claim(&actor, false, 72); if let Request::Attach { startup: Some(message), @@ -1444,10 +1456,10 @@ fn automatic_resume_is_conditioned_on_previous_controller_generation() { actor .command(resident_claim(&actor, false, 71), &writes) .unwrap(); - let current = actor.attachments.values().next().unwrap().id.clone(); + let current = actor.sole_attachment().id.clone(); let error = actor.command(recovery, &writes).unwrap_err(); assert_eq!(error.2, "controller_replaced"); - assert_eq!(actor.attachments.values().next().unwrap().id, current); + assert_eq!(actor.sole_attachment().id, current); assert_eq!( actor .attachments @@ -1469,7 +1481,7 @@ fn automatic_resume_is_conditioned_on_previous_controller_generation() { message["params"]["_meta"]["kit/gateway"]["previousAttachment"] = current.clone().into(); } actor.command(recovery, &writes).unwrap(); - assert_ne!(actor.attachments.values().next().unwrap().id, current); + assert_ne!(actor.sole_attachment().id, current); assert_eq!( actor .attachments @@ -1480,9 +1492,9 @@ fn automatic_resume_is_conditioned_on_previous_controller_generation() { .back() .unwrap() .1["result"]["_meta"]["kit/gateway"]["attachment"], - actor.attachments.values().next().unwrap().id + actor.sole_attachment().id ); - let newest = actor.attachments.values().next().unwrap().id.clone(); + let newest = actor.sole_attachment().id.clone(); actor .command( Request::Detach { @@ -1511,7 +1523,7 @@ fn recovery_sequence_retries_own_unconfirmed_claim_but_not_manual_replacement() actor .command(resident_claim(&actor, false, 80), &writes) .unwrap(); - let old = actor.attachments.values().next().unwrap().id.clone(); + let old = actor.sole_attachment().id.clone(); let recovery = |actor: &Actor, id| { let mut request = resident_claim(actor, false, id); if let Request::Attach { @@ -1524,19 +1536,19 @@ fn recovery_sequence_retries_own_unconfirmed_claim_but_not_manual_replacement() request }; actor.command(recovery(&actor, 81), &writes).unwrap(); - let unconfirmed = actor.attachments.values().next().unwrap().id.clone(); + let unconfirmed = actor.sole_attachment().id.clone(); // The previous result was lost; reuse the same outage ID and old confirmed token. actor.command(recovery(&actor, 82), &writes).unwrap(); - assert_ne!(actor.attachments.values().next().unwrap().id, unconfirmed); + assert_ne!(actor.sole_attachment().id, unconfirmed); actor .command(resident_claim(&actor, false, 83), &writes) .unwrap(); - let manual = actor.attachments.values().next().unwrap().id.clone(); + let manual = actor.sole_attachment().id.clone(); assert_eq!( actor.command(recovery(&actor, 84), &writes).unwrap_err().2, "controller_replaced" ); - assert_eq!(actor.attachments.values().next().unwrap().id, manual); + assert_eq!(actor.sole_attachment().id, manual); // Invalid recovery capabilities cannot mutate ownership either. for metadata in [ json!({"recoveryId":"orphan"}), @@ -1552,7 +1564,7 @@ fn recovery_sequence_retries_own_unconfirmed_claim_but_not_manual_replacement() message["params"]["_meta"]["kit/gateway"] = metadata; } assert_eq!(actor.command(request, &writes).unwrap_err().2, "protocol"); - assert_eq!(actor.attachments.values().next().unwrap().id, manual); + assert_eq!(actor.sole_attachment().id, manual); } } @@ -1564,7 +1576,7 @@ fn stale_config_response_refreshes_snapshot_without_cross_generation_response() actor .command(resident_claim(&actor, false, 90), &writes) .unwrap(); - let old = actor.attachments.values().next().unwrap().id.clone(); + let old = actor.sole_attachment().id.clone(); actor.pending.insert( 1, Pending { @@ -1583,12 +1595,12 @@ fn stale_config_response_refreshes_snapshot_without_cross_generation_response() .unwrap(); let options = json!([{"id":"model","name":"Model","type":"select","currentValue":"updated","options":[{"value":"updated","name":"Updated"}]}]); actor.output(json!({"jsonrpc":"2.0","id":1,"result":{"configOptions":options}})); - assert_eq!(actor.attachments.values().next().unwrap().events.len(), 3); + assert_eq!(actor.sole_attachment().events.len(), 3); actor .command(resident_claim(&actor, false, 92), &writes) .unwrap(); assert_eq!( - actor.attachments.values().next().unwrap().events[0].1["params"]["update"]["configOptions"], + actor.sole_attachment().events[0].1["params"]["update"]["configOptions"], options ); } @@ -1601,7 +1613,7 @@ fn aggregate_snapshot_overflow_preserves_prior_controller() { actor .command(resident_claim(&actor, false, 93), &writes) .unwrap(); - let old = actor.attachments.values().next().unwrap().id.clone(); + let old = actor.sole_attachment().id.clone(); // Every frame fits, and the journal alone fits, but trailing snapshots do not. let frame = json!({"payload":"x".repeat(MAX_HTTP_FRAME / 2 - 100)}); for _ in 0..16 { @@ -1618,7 +1630,7 @@ fn aggregate_snapshot_overflow_preserves_prior_controller() { .2, "replay_unavailable" ); - assert_eq!(actor.attachments.values().next().unwrap().id, old); + assert_eq!(actor.sole_attachment().id, old); } #[test] @@ -1629,7 +1641,7 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { actor .command(resident_claim(&actor, false, 100), &writes) .unwrap(); - let original = actor.attachments.values().next().unwrap().id.clone(); + let original = actor.sole_attachment().id.clone(); let recovery = |actor: &Actor, previous: &str, attempt: u64| { let mut request = resident_claim(actor, false, 100 + attempt); if let Request::Attach { @@ -1648,14 +1660,14 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { actor .command(recovery(&actor, &original, 2), &writes) .unwrap(); - let second = actor.attachments.values().next().unwrap().id.clone(); - let queued = actor.attachments.values().next().unwrap().events.clone(); + let second = actor.sole_attachment().id.clone(); + let queued = actor.sole_attachment().events.clone(); assert_eq!( actor.command(late, &writes).unwrap_err().2, "stale_recovery" ); - assert_eq!(actor.attachments.values().next().unwrap().id, second); - assert_eq!(actor.attachments.values().next().unwrap().events, queued); + assert_eq!(actor.sole_attachment().id, second); + assert_eq!(actor.sole_attachment().events, queued); // Even the current attachment ID must not bypass duplicate/older fencing. for attempt in [1, 2] { let error = actor @@ -1665,12 +1677,12 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { error.data(), json!({"reason":"stale_recovery","terminal":true}) ); - assert_eq!(actor.attachments.values().next().unwrap().events, queued); + assert_eq!(actor.sole_attachment().events, queued); } actor .command(recovery(&actor, &original, 3), &writes) .unwrap(); - assert_ne!(actor.attachments.values().next().unwrap().id, second); + assert_ne!(actor.sole_attachment().id, second); assert_eq!( actor.committed_owner.as_ref().unwrap().recovery_attempt, Some(3) @@ -1678,7 +1690,7 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { actor .command(resident_claim(&actor, false, 104), &writes) .unwrap(); - let manual = actor.attachments.values().next().unwrap().id.clone(); + let manual = actor.sole_attachment().id.clone(); assert!( actor .committed_owner @@ -1702,7 +1714,7 @@ fn recovery_attempt_high_water_mark_fences_delayed_and_duplicate_claims() { .2, "controller_replaced" ); - assert_eq!(actor.attachments.values().next().unwrap().id, manual); + assert_eq!(actor.sole_attachment().id, manual); } #[test] @@ -1713,7 +1725,7 @@ fn recovery_attempt_metadata_is_paired_positive_and_bounded() { actor .command(resident_claim(&actor, false, 110), &writes) .unwrap(); - let owner = actor.attachments.values().next().unwrap().id.clone(); + let owner = actor.sole_attachment().id.clone(); let mut invalid = vec![ json!({"previousAttachment":owner,"recoveryId":"missing-attempt"}), json!({"previousAttachment":owner,"recoveryAttempt":1}), @@ -1739,7 +1751,7 @@ fn recovery_attempt_metadata_is_paired_positive_and_bounded() { message["params"]["_meta"]["kit/gateway"] = metadata; } assert_eq!(actor.command(request, &writes).unwrap_err().2, "protocol"); - assert_eq!(actor.attachments.values().next().unwrap().id, owner); + assert_eq!(actor.sole_attachment().id, owner); assert!( actor .committed_owner @@ -1774,11 +1786,11 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m actor .command(resident_claim(&actor, false, 200), &writes) .unwrap(); - let a = actor.attachments.values().next().unwrap().id.clone(); + let a = actor.sole_attachment().id.clone(); actor .command(resident_claim(&actor, false, 201), &writes) .unwrap(); - let b = actor.attachments.values().next().unwrap().id.clone(); + let b = actor.sole_attachment().id.clone(); if overflow { actor.push_to_attachment(&b, json!({"payload":"x".repeat(MAX_REPLAY)})); } else { @@ -1823,7 +1835,7 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m actor .command(recovery_claim(&actor, &b, "b-outage", 2), &writes) .unwrap(); - let recovered = actor.attachments.values().next().unwrap().id.clone(); + let recovered = actor.sole_attachment().id.clone(); actor .command( Request::Detach { @@ -1934,7 +1946,7 @@ fn resident_startup_omitted_or_empty_mcp_retains_overlay() { // No child request means the resident overlay is left untouched. assert!(actor.pending.is_empty()); assert!(receiver.try_recv().is_err()); - let attachment = actor.attachments.values().next().unwrap(); + let attachment = actor.sole_attachment(); assert!(attachment.live); let response = &attachment.events.back().unwrap().1; assert_eq!(response["id"], 71); @@ -2009,8 +2021,8 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { &writes, ) .unwrap(); - let owner = actor.attachments.values().next().unwrap().id.clone(); - let events = actor.attachments.values().next().unwrap().events.clone(); + let owner = actor.sole_attachment().id.clone(); + let events = actor.sole_attachment().events.clone(); let startup = json!({"jsonrpc":"2.0","id":76,"method":method,"params":{ "sessionId":"resident", "mcpServers":[{"name":"remote","type":"http","url":"https://example.com/mcp","headers":[]}] @@ -2034,7 +2046,7 @@ fn resident_nonempty_mcp_rejected_without_replacing_controller() { let error = actor.command(request, &writes).unwrap_err(); assert_eq!(error.0, StatusCode::CONFLICT); assert!(error.1.contains("_kit/session/update_mcp")); - let attachment = actor.attachments.values().next().unwrap(); + let attachment = actor.sole_attachment(); assert_eq!(attachment.id, owner); assert_eq!(attachment.live, via_attach); assert_eq!(attachment.events, events); @@ -2078,7 +2090,7 @@ fn direct_mcp_update_keeps_owner_and_returns_extension_response() { json!({"jsonrpc":"2.0","id":update["id"],"result":{}}) }; actor.output(response); - let attachment = actor.attachments.values().next().unwrap(); + let attachment = actor.sole_attachment(); assert_eq!(attachment.id, owner); assert!(attachment.live); let response = &attachment.events.back().unwrap().1; diff --git a/src/session.rs b/src/session.rs index b20b0b73..6a56d536 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2730,6 +2730,10 @@ pub(crate) fn belongs_to_workspace(root: &Path, session_id: &str) -> Result Result { + belongs_to_workspace_bound_in(root, &default_directory()?, session_id) +} + fn belongs_to_workspace_in( root: &Path, global_directory: &Path, @@ -2740,6 +2744,24 @@ fn belongs_to_workspace_in( Ok(select_authority(global_directory, &root, session_id)?.is_some()) } +fn belongs_to_workspace_bound_in( + root: &Path, + global_directory: &Path, + session_id: &str, +) -> Result { + validate_id(session_id)?; + let root = canonical_workspace(root); + Ok(select_authority_with( + fs::best_effort_global(), + global_directory, + &root, + session_id, + false, + false, + )? + .is_some()) +} + fn list_ids_in_with(filesystem: &Fs, directory: &Path) -> Result, String> { let entries = match filesystem.read_dir(directory) { Ok(entries) => entries, @@ -7728,6 +7750,45 @@ mod tests { assert!(!belongs_to_workspace_in(&second, storage.path(), "legacy").unwrap()); } + #[test] + fn belongs_to_workspace_bound_excludes_unbound_global_fallback() { + let storage = tempfile::tempdir().unwrap(); + let roots = tempfile::tempdir().unwrap(); + let first = roots.path().join("first"); + let second = roots.path().join("second"); + fs::create_dir_all(&first).unwrap(); + fs::create_dir_all(&second).unwrap(); + + // 1. Only an unbound legacy global transcript exists -> explicit resume accepts both, + // but strict workspace-bound ownership reports neither. + let global = super::transcript_path(storage.path(), "unbound"); + write_history( + &global, + PREVIOUS_SCHEMA_VERSION, + "unbound", + &["legacy"], + None, + ); + assert!(belongs_to_workspace_in(&first, storage.path(), "unbound").unwrap()); + assert!(belongs_to_workspace_in(&second, storage.path(), "unbound").unwrap()); + assert!(!belongs_to_workspace_bound_in(&first, storage.path(), "unbound").unwrap()); + assert!(!belongs_to_workspace_bound_in(&second, storage.path(), "unbound").unwrap()); + + // 2. One workspace has a bound transcript AND an unbound global transcript shares the ID -> + // only the workspace with the bound transcript is reported as a bound owner. + let first_legacy = workspace_directory(&first); + fs::create_dir_all(&first_legacy).unwrap(); + write_history( + &first_legacy.join("unbound.jsonl"), + PREVIOUS_SCHEMA_VERSION, + "unbound", + &["bound-first"], + None, + ); + assert!(belongs_to_workspace_bound_in(&first, storage.path(), "unbound").unwrap()); + assert!(!belongs_to_workspace_bound_in(&second, storage.path(), "unbound").unwrap()); + } + #[cfg(not(windows))] #[test] fn writer_fails_closed_when_another_owner_wins_recovery_lock() { From 378d7e0d5f670b80283338a6138c3314b8b6cfa1 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 10:28:56 +0000 Subject: [PATCH 10/19] fix(gateway): cancel orphaned relays on control drop and isolate legacy test home --- src/gateway/http_server.rs | 18 +- src/gateway/pinned_tests.rs | 364 ++++++++++++++++++++++++++++-------- tests/gateway.rs | 119 ++++++++++++ 3 files changed, 416 insertions(+), 85 deletions(-) diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 0541450f..9eedcbc8 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -642,8 +642,22 @@ impl Connection { } } } - self.relay_routes - .retain(|_, session_id| self.controls.contains_key(session_id)); + let mut orphan_relays: Vec = self + .relay_routes + .iter() + .filter(|(_, session_id)| !self.controls.contains_key(*session_id)) + .map(|(relay_id, _)| relay_id.clone()) + .collect(); + orphan_relays.sort(); + for relay_id in orphan_relays { + self.relay_routes.remove(&relay_id); + send( + channel, + super::cancel_request_message(Value::String(relay_id)), + deadline, + ) + .await?; + } Ok(()) } diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 3eaa0efe..f8e9ee1c 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -6517,102 +6517,300 @@ for line in sys.stdin: } #[tokio::test] -async fn pinned_unbound_legacy_global_transcript_does_not_cause_false_multi_owner_conflict() { - let dir = tempfile::tempdir().unwrap(); - let first = dir.path().join("first"); - let second = dir.path().join("second"); - std::fs::create_dir_all(&first).unwrap(); - std::fs::create_dir_all(&second).unwrap(); - let first = first.canonicalize().unwrap(); - let second = second.canonicalize().unwrap(); - - let session_id = format!("pinned-legacy-{}", crate::session::new_id()); - let home = std::env::var_os("HOME").expect("HOME set by test harness"); - let global_dir = PathBuf::from(home).join(".kit/sessions"); - std::fs::create_dir_all(&global_dir).unwrap(); - let global_transcript = global_dir.join(format!("{session_id}.jsonl")); - struct CleanupFile(PathBuf); - impl Drop for CleanupFile { - fn drop(&mut self) { - let _ = std::fs::remove_file(&self.0); +async fn default_mode_displaced_controller_and_pinned_close_cancel_unanswered_relays() { + // 1. Default mode takeover on a multiplexed connection: displacing session A MUST cancel + // session A's unanswered relays on the old connection while leaving session B and the + // replacement controller's re-offered requests untouched. + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source_a = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + emit({ + 'jsonrpc': '2.0', + 'method': 'session/update', + 'params': { + 'sessionId': 'disp-a', + 'update': { + 'sessionUpdate': 'agent_message_chunk', + 'content': {'type': 'text', 'text': json.dumps(req)} + } + } + }) + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'disp-a','configOptions':[]}}) + elif m == 'session/prompt': + emit({'jsonrpc':'2.0','id':'ask-a','method':'elicitation/create','params':{'sessionId':'disp-a','mode':'form','message':'form-a'}}) + emit({'jsonrpc':'2.0','id':'perm-a','method':'session/request_permission','params':{'sessionId':'disp-a','options':[{'optionId':'allow','name':'Allow','kind':'allow_once'}]}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let source_b = r#" +import sys, json +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req.get('id') == 'ask-b' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'reply': req.get('result')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'disp-b','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({'jsonrpc':'2.0','id':'ask-b','method':'elicitation/create','params':{'sessionId':'disp-b','mode':'form','message':'form-b'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("disp-a", source_a, &[]).await; + harness.child_source("disp-b", source_b, &[]).await; + + let mut conn1 = harness + .connect_with_capabilities("old-mux", json!({"elicitation": {"form": {}}})) + .await; + let mut sa1 = conn1.open_session_stream("disp-a").await; + let mut sb1 = conn1.open_session_stream("disp-b").await; + assert_eq!( + conn1 + .post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"disp-a"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = sa1.next_matching(|e| e["id"] == 1).await; + assert_eq!( + conn1 + .post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"disp-b"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = sb1.next_matching(|e| e["id"] == 2).await; + + // Trigger unanswered relays on both disp-a (elicitation + permission) and disp-b (elicitation). + assert_eq!( + conn1 + .post(json!({"jsonrpc":"2.0","id":"pa","method":"session/prompt","params":{"sessionId":"disp-a","prompt":[{"type":"text","text":"go"}]}})) + .await, + StatusCode::ACCEPTED + ); + assert_eq!( + conn1 + .post(json!({"jsonrpc":"2.0","id":"pb","method":"session/prompt","params":{"sessionId":"disp-b","prompt":[{"type":"text","text":"go"}]}})) + .await, + StatusCode::ACCEPTED + ); + let ask_a = sa1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let perm_a = sa1 + .next_matching(|e| e["method"] == "session/request_permission") + .await; + let ask_b = sb1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let ask_a_id = ask_a["id"].as_str().unwrap().to_owned(); + let perm_a_id = perm_a["id"].as_str().unwrap().to_owned(); + let ask_b_id = ask_b["id"].as_str().unwrap().to_owned(); + + // conn2 takes over disp-a. + let conn2 = harness + .connect_with_capabilities("new-ctrl", json!({"elicitation": {"form": {}}})) + .await; + let mut sa2 = conn2.open_session_stream("disp-a").await; + assert_eq!( + conn2 + .post(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"disp-a"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = sa2.next_matching(|e| e["id"] == 3).await; + + // Old connection MUST receive controller_replaced on disp-a AND $/cancel_request for both + // disp-a relays on conn_stream, without cancelling disp-b's relay. + let replaced = sa1 + .next_matching(|e| { + e["params"]["update"]["sessionUpdate"] == "_gateway_controller" + && e["params"]["update"]["_meta"]["kit/gateway"]["reason"] == "controller_replaced" + }) + .await; + assert_eq!(replaced["params"]["sessionId"], "disp-a"); + + let mut cancelled_ids = HashSet::new(); + tokio::time::timeout(Duration::from_secs(5), async { + while cancelled_ids.len() < 2 { + let ev = conn1.conn_stream.next_event().await.expect("conn1 event"); + if ev["method"] == "$/cancel_request" + && let Some(rid) = ev["params"]["requestId"].as_str() + { + assert_ne!( + rid, ask_b_id, + "unrelated session B relay must not be cancelled" + ); + cancelled_ids.insert(rid.to_owned()); + } } - } - let _cleanup = CleanupFile(global_transcript.clone()); + }) + .await + .expect("displaced controller must receive $/cancel_request for both unanswered relays"); + assert!(cancelled_ids.contains(&ask_a_id)); + assert!(cancelled_ids.contains(&perm_a_id)); - let legacy_record = json!({ - "schema_version": 2, - "session_id": session_id, - "generation": 1, - "item": agentkit_core::Item::text(agentkit_core::ItemKind::System, "legacy global"), - }); - std::fs::write(&global_transcript, format!("{legacy_record}\n")).unwrap(); + // Unrelated session B on conn1 remains healthy and can still answer ask_b! + assert_eq!( + conn1 + .post(json!({"jsonrpc":"2.0","id":ask_b_id,"result":{"action":"accept","content":{"ok":"b"}}})) + .await, + StatusCode::ACCEPTED + ); + let done_b = sb1.next_matching(|e| e["id"] == "pb").await; + assert_eq!(done_b["result"]["reply"]["content"]["ok"], "b"); - let harness = PinnedHarness::with_roots( - dir, - vec![first.clone(), second.clone()], - Some(session_id.clone()), - Duration::from_secs(60), - ) - .await; + // Replacement controller conn2 receives re-offered ask-a and perm-a and can answer both! + let re_ask_a = sa2 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let re_perm_a = sa2 + .next_matching(|e| e["method"] == "session/request_permission") + .await; + assert_eq!(re_ask_a["id"], ask_a_id); + assert_eq!(re_perm_a["id"], perm_a_id); + assert_eq!( + conn2 + .post(json!({"jsonrpc":"2.0","id":ask_a_id,"result":{"action":"accept","content":{"ok":"a"}}})) + .await, + StatusCode::ACCEPTED + ); + assert_eq!( + conn2 + .post(json!({"jsonrpc":"2.0","id":perm_a_id,"result":{"outcome":{"outcome":"selected","optionId":"allow"}}})) + .await, + StatusCode::ACCEPTED + ); + let mut answered_a = HashSet::new(); + tokio::time::timeout(Duration::from_secs(5), async { + while answered_a.len() < 2 { + let ev = sa2.next_event().await.expect("sa2 event"); + if ev["method"] == "session/update" + && ev["params"]["update"]["sessionUpdate"] == "agent_message_chunk" + && let Some(text) = ev["params"]["update"]["content"]["text"].as_str() + && let Ok(parsed) = serde_json::from_str::(text) + && let Some(id) = parsed["id"].as_str() + { + answered_a.insert(id.to_owned()); + } + } + }) + .await + .expect("replacement controller answers must reach child"); + assert!(answered_a.contains("ask-a")); + assert!(answered_a.contains("perm-a")); + + let _ = conn1.delete().await; + let _ = conn2.delete().await; + + // 2. Sibling path: pinned client-local session/close drops control without killing the session; + // closing client MUST receive $/cancel_request for its unanswered relay while other client + // remains able to answer. + let pinned = PinnedHarness::new("pin-close-cancel", Duration::from_secs(60)).await; + let source_pin = r#" +import sys, json +prompt_req = None +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + if 'method' not in req: + if req.get('id') == 'ask-pin' and prompt_req: + emit({'jsonrpc':'2.0','id':prompt_req['id'],'result':{'reply': req.get('result')}}) + prompt_req = None + continue + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pin-close-cancel','configOptions':[]}}) + elif m == 'session/prompt': + prompt_req = req + emit({'jsonrpc':'2.0','id':'ask-pin','method':'elicitation/create','params':{'sessionId':'pin-close-cancel','mode':'form','message':'pin-q'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + pinned + .child_source("pin-close-cancel", source_pin, &[]) + .await; - // 1. Unbound global transcript alone MUST NOT report multiple approved projects! + let mut p1 = pinned + .connect_with_capabilities("p1", json!({"elicitation": {"form": {}}})) + .await; + let mut sp1 = p1.open_session_stream("pin-close-cancel").await; assert_eq!( - resolve_pinned_owner(&[first.clone(), second.clone()], &session_id).unwrap(), - None + p1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pin-close-cancel"}})) + .await, + StatusCode::ACCEPTED ); - let listed = handle(State(harness.gateway.clone()), Json(Request::List)) - .await - .expect("list must succeed with single unbound global transcript") - .0; - assert_eq!(listed["sessions"].as_array().unwrap().len(), 1); - assert_eq!(listed["sessions"][0]["session"], session_id); - assert_eq!(listed["sessions"][0]["state"], "restorable"); - - // 2. Adding a workspace-bound transcript in `first` alongside the unbound global transcript - // MUST resolve cleanly to `first` (not a multi-owner conflict). - let first_local = first.join(".kit/sessions"); - std::fs::create_dir_all(&first_local).unwrap(); - std::fs::write( - first_local.join(format!("{session_id}.jsonl")), - format!("{legacy_record}\n"), - ) - .unwrap(); + let _ = sp1.next_matching(|e| e["id"] == 1).await; + + let p2 = pinned + .connect_with_capabilities("p2", json!({"elicitation": {"form": {}}})) + .await; + let mut sp2 = p2.open_session_stream("pin-close-cancel").await; assert_eq!( - resolve_pinned_owner(&[first.clone(), second.clone()], &session_id).unwrap(), - Some(first.clone()) + p2.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"pin-close-cancel"}})) + .await, + StatusCode::ACCEPTED ); - let listed_bound = handle(State(harness.gateway.clone()), Json(Request::List)) - .await - .expect("list must resolve to sole bound workspace owner") - .0; + let _ = sp2.next_matching(|e| e["id"] == 2).await; + assert_eq!( - listed_bound["sessions"][0]["root"], - first.to_string_lossy().as_ref() + p2.post(json!({"jsonrpc":"2.0","id":"pp","method":"session/prompt","params":{"sessionId":"pin-close-cancel","prompt":[{"type":"text","text":"go"}]}})) + .await, + StatusCode::ACCEPTED ); - assert_eq!(listed_bound["sessions"][0]["state"], "restorable"); + let qp1 = sp1 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let qp2 = sp2 + .next_matching(|e| e["method"] == "elicitation/create") + .await; + let pin_relay_id = qp1["id"].as_str().unwrap().to_owned(); + assert_eq!(qp2["id"], pin_relay_id); - let wrong_root = handle( - State(harness.gateway.clone()), - Json(Request::Create { - root: second.clone(), - session: Some(session_id.clone()), - force: false, - }), + // p1 detaches via session/close -> receives close {} AND $/cancel_request for pin_relay_id. + assert_eq!( + p1.post(json!({"jsonrpc":"2.0","id":"close-1","method":"session/close","params":{"sessionId":"pin-close-cancel"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = sp1.next_matching(|e| e["id"] == "close-1").await; + let cancel_p1 = tokio::time::timeout( + Duration::from_secs(5), + p1.conn_stream + .next_matching(|e| e["method"] == "$/cancel_request"), ) .await - .unwrap_err(); - assert_eq!(wrong_root.2, "root_denied"); - - // 3. Adding a second distinct workspace-bound transcript in `second` MUST fail with conflict. - let second_local = second.join(".kit/sessions"); - std::fs::create_dir_all(&second_local).unwrap(); - std::fs::write( - second_local.join(format!("{session_id}.jsonl")), - format!("{legacy_record}\n"), - ) - .unwrap(); - let conflict = resolve_pinned_owner(&[first, second], &session_id).unwrap_err(); - assert_eq!(conflict.0, StatusCode::CONFLICT); + .expect("detaching pinned client must receive $/cancel_request for unanswered relay"); + assert_eq!(cancel_p1["params"]["requestId"], pin_relay_id); + + // p2 can still answer pin_relay_id and complete the prompt! + assert_eq!( + p2.post(json!({"jsonrpc":"2.0","id":pin_relay_id,"result":{"action":"accept","content":{"from":"p2"}}})) + .await, + StatusCode::ACCEPTED + ); + let done_pin = sp2.next_matching(|e| e["id"] == "pp").await; + assert_eq!(done_pin["result"]["reply"]["content"]["from"], "p2"); + + let _ = p1.delete().await; + let _ = p2.delete().await; } #[tokio::test] diff --git a/tests/gateway.rs b/tests/gateway.rs index 905159ad..f8b8829a 100644 --- a/tests/gateway.rs +++ b/tests/gateway.rs @@ -3866,3 +3866,122 @@ async fn pinned_cold_start_binds_to_existing_workspace_and_rejects_conflicting_o stop_gateway(&mut gw3).await; provider.abort(); } + +#[tokio::test] +async fn sdk_pinned_unbound_legacy_global_transcript_isolation() { + let fixture = Fixture::new(); + let project_a = fixture.root.canonicalize().unwrap(); + let project_b_dir = tempfile::tempdir().unwrap(); + let project_b = project_b_dir.path().canonicalize().unwrap(); + let project_b_str = project_b.to_string_lossy().into_owned(); + + let session_id = "pinned-legacy-global"; + let legacy_record = json!({ + "schema_version": 2, + "session_id": session_id, + "generation": 1, + "item": agentkit_core::Item::text(agentkit_core::ItemKind::System, "legacy global"), + }); + let global_dir = fixture.home.path().join(".kit/sessions"); + fs::create_dir_all(&global_dir).unwrap(); + fs::write( + global_dir.join(format!("{session_id}.jsonl")), + format!("{legacy_record}\n"), + ) + .unwrap(); + + // 1. Unbound legacy global transcript alone MUST NOT report multiple approved projects on a + // 2-project pinned gateway, reports state="restorable", and requires explicit cwd. + let (mut gw1, url1) = fixture + .gateway_with_bind( + "127.0.0.1:0", + &["--project", &project_b_str, "--pinned-session", session_id], + ) + .await; + let mut c1 = SdkClient::connect(&url1).await; + let listed = c1.request(2, "session/list", json!({})).await; + assert!(listed.get("error").is_none(), "{listed}"); + let rows = listed["result"]["sessions"].as_array().unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0]["sessionId"], session_id); + assert_eq!(rows[0]["_meta"]["kit.gateway.state"], "restorable"); + + let missing_cwd = c1 + .request(3, "session/resume", json!({"sessionId": session_id})) + .await; + assert!( + missing_cwd["error"]["message"] + .as_str() + .unwrap_or("") + .contains("cwd required"), + "unbound multi-project pinned resume without cwd must fail: {missing_cwd}" + ); + c1.detach().await; + stop_gateway(&mut gw1).await; + + // 2. Adding a workspace-bound transcript in project A alongside the unbound global transcript + // MUST resolve cleanly to project A (not multi-project conflict) and reject project B. + let dir_a = project_a.join(".kit/sessions"); + fs::create_dir_all(&dir_a).unwrap(); + fs::write( + dir_a.join(format!("{session_id}.jsonl")), + format!("{legacy_record}\n"), + ) + .unwrap(); + + let (mut gw2, url2) = fixture + .gateway_with_bind( + "127.0.0.1:0", + &["--project", &project_b_str, "--pinned-session", session_id], + ) + .await; + let mut c2 = SdkClient::connect(&url2).await; + let listed_bound = c2.request(2, "session/list", json!({})).await; + assert!(listed_bound.get("error").is_none(), "{listed_bound}"); + assert_eq!( + listed_bound["result"]["sessions"][0]["cwd"], + project_a.to_string_lossy().as_ref() + ); + assert_eq!( + listed_bound["result"]["sessions"][0]["_meta"]["kit.gateway.state"], + "restorable" + ); + + let wrong_project = c2 + .request( + 3, + "session/resume", + json!({"sessionId": session_id, "cwd": project_b}), + ) + .await; + assert_eq!(wrong_project["error"]["data"]["reason"], "root_denied"); + c2.detach().await; + stop_gateway(&mut gw2).await; + + // 3. Adding a second workspace-bound transcript in project B MUST fail with conflict. + let dir_b = project_b.join(".kit/sessions"); + fs::create_dir_all(&dir_b).unwrap(); + fs::write( + dir_b.join(format!("{session_id}.jsonl")), + format!("{legacy_record}\n"), + ) + .unwrap(); + + let (mut gw3, url3) = fixture + .gateway_with_bind( + "127.0.0.1:0", + &["--project", &project_b_str, "--pinned-session", session_id], + ) + .await; + let mut c3 = SdkClient::connect(&url3).await; + let conflict = c3.request(2, "session/list", json!({})).await; + assert!( + conflict["error"]["message"] + .as_str() + .unwrap_or("") + .contains("multiple approved projects"), + "two distinct bound owners must fail with conflict: {conflict}" + ); + c3.detach().await; + stop_gateway(&mut gw3).await; +} From 1dabce8ff9dd375d56da77fa6df4f6e6e126dbd2 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 10:56:32 +0000 Subject: [PATCH 11/19] fix(gateway): contain oversized live updates, share relay payloads, and clarify docs --- docs/reference/gateway-protocol.md | 4 +- src/gateway.rs | 96 +++++++---- src/gateway/pinned_tests.rs | 262 +++++++++++++++++++++++++++-- 3 files changed, 318 insertions(+), 44 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index febe977d..221b8c8e 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -175,11 +175,11 @@ Only user messages with durable identities support partial replay. Agent-message ## Relayed agent-to-client requests -In both default single-controller mode and `--pinned-session` mode, the gateway relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending per session) to eligible live attachments and routes client-to-agent JSON-RPC responses back to the child. Each relayed request carries an opaque gateway-assigned string `id` unique across the gateway process; clients must echo that exact `id` in their JSON-RPC response and must not parse or assume any internal format. +In both default single-controller mode and `--pinned-session` mode, the gateway relays agent-to-client requests (such as `elicitation/create` and `session/request_permission`, up to 64 concurrently pending and 8 MiB aggregate payload per session) to eligible live attachments and routes client-to-agent JSON-RPC responses back to the child. Each relayed request carries an opaque gateway-assigned string `id` unique across the gateway process; clients must echo that exact `id` in their JSON-RPC response and must not parse or assume any internal format. - **Client capabilities forwarded to the child:** In default mode, the gateway filters the connecting client's `initialize.params.capabilities` to forward only relayable capabilities (`elicitation.form`) and strips host-only or unsupported capabilities (`auth`, `elicitation.url`, `fs`, `terminal`). A client connecting with `capabilities: {}` therefore does not advertise `elicitation.form` and does not receive an `ask_user` tool. Because a resident child is initialized once at spawn and installs `ask_user` based on those initial capabilities, a form-capable controller that later resumes a resident default-mode session originally started by a `capabilities: {}` client will not expose `ask_user` until the child exits or is closed and restored by a form-capable controller. In `--pinned-session` mode, because multiple heterogeneous clients share one child initialized once, the gateway always advertises `{"elicitation":{"form":{}}}` to the child. - **Capability targeting and delivery:** Each attachment records whether its own connection's `initialize` declared `capabilities.elicitation.form`. An `elicitation/create` request is offered only to live attachments (and late joiners) that declared `elicitation.form`; if no live attachment declared it—including when a `capabilities: {}` controller replaces a declaring controller in default mode (even while an `elicitation/create` is already pending), or when only headless `capabilities: {}` clients are attached in pinned mode—the gateway answers `-32601` immediately and non-declaring clients receive nothing. Requests that require no client capability in ACP v2 (such as `session/request_permission`) are offered to all live attachments and late joiners. A relayed request whose serialized frame (with its gateway-assigned `id`) exceeds the 1 MiB HTTP frame limit is rejected immediately toward the child with `-32603` (`data.reason: "frame_too_large"`) before enqueueing or recording as pending. Pending requests are re-offered right after startup to any eligible client that attaches or replaces the controller while the request is pending, without consuming live-update queue headroom before the first poll. -- **Validation, resolution, and errors:** The gateway validates relayed results against the ACP v2 response types (`CreateElicitationResponse` with non-null `content` for form `accept`, and `RequestPermissionResponse` with an offered `optionId` for `selected`), while preserving schema-valid custom or future extension actions/outcomes and leaving form-schema field validation to the child. The first valid `result` from an eligible target wins and is forwarded to the child through a bounded FIFO reply queue; any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target failed or detached mid-request, the gateway answers `-32601` to the child. An answer that fails shape validation or a non-`-32601` client error is never forwarded: that target is dropped (with a warning logged at the HTTP boundary and no JSON-RPC reply sent to a response frame), and the request stays pending if another live target or a detached target remains; if the failing sender was the only remaining target and no target detached, the gateway resolves the request promptly toward the child with `-32603` (`data.reason`: `"invalid_client_response"` or `"client_error"`) rather than waiting for `--client-request-timeout`. A target detaching without answering (such as a browser reloading or a controller being replaced) keeps the request pending until answered by a remaining or rejoining eligible client, cancelled by the agent, replaced in default mode by an ineligible controller (which resolves the ineligible pending request immediately with `-32601`), or expired. +- **Validation, resolution, and errors:** The gateway validates relayed results against the ACP v2 response types (`CreateElicitationResponse` with non-null `content` for form `accept`, and `RequestPermissionResponse` with an offered `optionId` for `selected`), while preserving schema-valid custom or future extension actions/outcomes and leaving form-schema field validation to the child. The first valid `result` from an eligible target wins and is forwarded to the child through a bounded FIFO reply queue; any other live targets receive `$/cancel_request` for that relayed request ID. A `-32601` error from a target removes only that target; if every target declined with `-32601` and no target failed or detached mid-request, the gateway answers `-32601` to the child. An answer that fails shape validation or a non-`-32601` client error is never forwarded: that target is dropped with no JSON-RPC reply sent to the response frame (and a warning logged at the HTTP boundary for rejected result payloads), and the request stays pending if another live target or a detached target remains; if the failing sender was the only remaining target and no target detached, the gateway resolves the request promptly toward the child with `-32603` (`data.reason`: `"invalid_client_response"` or `"client_error"`) rather than waiting for `--client-request-timeout`. A target detaching without answering (such as a browser reloading or a controller being replaced) keeps the request pending until answered by a remaining or rejoining eligible client, cancelled by the agent, replaced in default mode by an ineligible controller (which resolves the ineligible pending request immediately with `-32601`), or expired. - **Timeout and child exit (`--client-request-timeout`):** `--client-request-timeout ` (default `5m`, valid in both modes) is an absolute deadline measured from when the child request arrives. Expiration settles even if child stdin is temporarily saturated: the gateway buffers a `-32603` (`Incoming transport closed`, matching native `kit serve` client disconnect semantics) reply to the child and sends `$/cancel_request` to current targets. If the child exits while relayed requests are pending, the gateway sends `$/cancel_request` to each request's live targets. diff --git a/src/gateway.rs b/src/gateway.rs index 1a2a5d8f..76c0cc6f 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -985,11 +985,13 @@ struct Attachment { id: String, touched: Instant, next: u64, - events: VecDeque<(u64, Value)>, + events: VecDeque<(u64, Arc)>, bytes: usize, - // Startup-reserved relay requests are bounded by MAX_CLIENT_REQUESTS and - // excluded from live queue admission until polled so they cannot exhaust - // headroom needed for ordinary updates during a nearly full replay. + // Startup-reserved relay requests share immutable Arc payloads with + // PendingClientRequest, are bounded by MAX_CLIENT_REQUESTS / MAX_REPLAY per + // session, and are excluded from live queue admission until polled so they + // cannot exhaust headroom needed for ordinary updates during a nearly full + // replay. reserved: HashMap, reserved_bytes: usize, elicitation_form: bool, @@ -1025,9 +1027,12 @@ impl Attachment { fn live_bytes(&self) -> usize { self.bytes.saturating_sub(self.reserved_bytes) } - fn push(&mut self, message: Value) -> bool { + fn push_shared(&mut self, message: Arc) -> bool { let bytes = message.to_string().len(); - if self.live_events() >= MAX_QUEUE || self.live_bytes() + bytes > MAX_REPLAY { + if bytes > MAX_HTTP_FRAME + || self.live_events() >= MAX_QUEUE + || self.live_bytes() + bytes > MAX_REPLAY + { return false; } self.bytes += bytes; @@ -1035,8 +1040,7 @@ impl Attachment { self.events.push_back((self.next, message)); true } - fn push_reserved(&mut self, message: Value) { - let bytes = message.to_string().len(); + fn push_reserved(&mut self, message: Arc, bytes: usize) { self.bytes += bytes; self.next += 1; self.reserved.insert(self.next, bytes); @@ -1064,7 +1068,10 @@ impl Attachment { .iter() .take(128) .map(|(sequence, message)| { - object([("cursor", (*sequence).into()), ("message", message.clone())]) + object([ + ("cursor", (*sequence).into()), + ("message", (**message).clone()), + ]) }) .collect(); Ok((events, self.events.len() <= 128)) @@ -1090,13 +1097,15 @@ struct WaitingStartup { } struct PreparedStartup { messages: Vec, - pending_requests: Vec<(String, Value)>, + pending_requests: Vec<(String, Arc, usize)>, } struct PendingClientRequest { seq: u64, child_id: Value, method: String, params: Value, + wire: Arc, + wire_bytes: usize, targets: HashSet, deadline: Instant, // Set once any target fails with a non-(-32601) error or invalid answer; @@ -1530,11 +1539,14 @@ impl Actor { .filter(|a| !a.closing && !a.overflowed) } fn push_to_attachment(&mut self, attachment_id: &str, message: Value) -> bool { + self.push_shared_to_attachment(attachment_id, Arc::new(message)) + } + fn push_shared_to_attachment(&mut self, attachment_id: &str, message: Arc) -> bool { let overflowed = if let Some(attachment) = self.attachments.get_mut(attachment_id) { if attachment.overflowed { return false; } - !attachment.push(message) + !attachment.push_shared(message) } else { return false; }; @@ -1579,7 +1591,7 @@ impl Actor { let _ = self.queue_child_reply(no_client_services_reply(req.child_id), None, writes); } } - fn pending_request_messages(&self, elicitation_form: bool) -> Vec<(String, Value)> { + fn pending_request_messages(&self, elicitation_form: bool) -> Vec<(String, Arc, usize)> { let now = Instant::now(); let mut items: Vec<_> = self .client_requests @@ -1591,19 +1603,15 @@ impl Actor { ( req.seq, relay_id.clone(), - object([ - ("jsonrpc", "2.0".into()), - ("id", relay_id.clone().into()), - ("method", req.method.clone().into()), - ("params", req.params.clone()), - ]), + Arc::clone(&req.wire), + req.wire_bytes, ) }) .collect(); - items.sort_by_key(|(seq, _, _)| *seq); + items.sort_by_key(|(seq, _, _, _)| *seq); items .into_iter() - .map(|(_, relay_id, message)| (relay_id, message)) + .map(|(_, relay_id, message, bytes)| (relay_id, message, bytes)) .collect() } fn retire_pinned_attachment(&mut self, attachment_id: &str, mode: RetireMode) { @@ -1862,7 +1870,8 @@ impl Actor { ("method", method.clone().into()), ("params", params.clone()), ]); - if relayed.to_string().len() > MAX_HTTP_FRAME { + let wire_bytes = relayed.to_string().len(); + if wire_bytes > MAX_HTTP_FRAME { return Some(object([ ("jsonrpc", "2.0".into()), ("id", child_id), @@ -1885,9 +1894,38 @@ impl Actor { ), ])); } + let pending_relay_bytes: usize = self + .client_requests + .values() + .map(|req| req.wire_bytes) + .sum(); + if pending_relay_bytes.saturating_add(wire_bytes) > MAX_REPLAY { + return Some(object([ + ("jsonrpc", "2.0".into()), + ("id", child_id), + ( + "error", + object([ + ("code", (-32603).into()), + ( + "message", + "pending relayed client request byte limit exceeded".into(), + ), + ( + "data", + object([ + ("reason", "pending_relay_budget_exceeded".into()), + ("method", method.into()), + ]), + ), + ]), + ), + ])); + } + let wire = Arc::new(relayed); let mut delivered = HashSet::new(); for target in live_targets { - if self.push_to_attachment(&target, relayed.clone()) { + if self.push_shared_to_attachment(&target, Arc::clone(&wire)) { delivered.insert(target); } } @@ -1901,6 +1939,8 @@ impl Actor { child_id, method, params, + wire, + wire_bytes, targets: delivered, deadline: Instant::now() + timeout, last_failure: None, @@ -1935,10 +1975,7 @@ impl Actor { replay: &ReplayMode, ) -> Result { let pending_requests = self.pending_request_messages(elicitation_form); - let pending_bytes: usize = pending_requests - .iter() - .map(|(_, m)| m.to_string().len()) - .sum(); + let pending_bytes: usize = pending_requests.iter().map(|(_, _, bytes)| *bytes).sum(); let (reserved_events, reserved_bytes) = if matches!(replay, ReplayMode::CurrentTurn) { ( existing_events.saturating_add(pending_requests.len()), @@ -1972,9 +2009,9 @@ impl Actor { for update in prepared.messages { self.push_to_attachment(attachment_id, update); } - for (relay_id, req_msg) in prepared.pending_requests { + for (relay_id, req_msg, bytes) in prepared.pending_requests { if let Some(attachment) = self.active_attachment_mut(attachment_id) { - attachment.push_reserved(req_msg); + attachment.push_reserved(req_msg, bytes); if let Some(req) = self.client_requests.get_mut(&relay_id) { req.targets.insert(attachment_id.to_owned()); } @@ -2066,8 +2103,9 @@ impl Actor { } _ => {} } + let shared = Arc::new(message); for target in self.live_update_targets() { - self.push_to_attachment(&target, message.clone()); + self.push_shared_to_attachment(&target, Arc::clone(&shared)); } } else if let Some(id) = message["id"].as_u64() && let Some(pending) = self.pending.remove(&id) diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index f8e9ee1c..99efcf67 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -992,7 +992,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio let events_turn: Vec = actor.attachments[&a_turn] .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( !events_turn @@ -1036,7 +1036,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio let events_msg: Vec = actor.attachments[&a_msg] .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert_eq!(events_msg[0]["params"]["update"]["messageId"], "u-1"); assert!( @@ -1118,7 +1118,7 @@ fn pinned_replay_current_turn_and_kit_message_cursors_mid_turn_and_after_evictio let events_turn3: Vec = actor.attachments[&a_turn3] .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( events_turn3 @@ -1394,7 +1394,7 @@ async fn pinned_relayed_request_no_clients_32601_late_joiner_reload_and_timeout( let c3_events: Vec = actor.attachments[&c3] .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert_eq!(c3_events.last().unwrap()["method"], "elicitation/create"); assert_eq!(c3_events.last().unwrap()["id"], relay_reload); @@ -2113,7 +2113,7 @@ fn pinned_current_turn_replay_truncates_gracefully_when_turn_start_evicted() { let events: Vec = actor.attachments[&a_trunc] .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( events @@ -3258,7 +3258,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by .to_owned(); let c2_att = &actor.attachments[&c2]; assert!(c2_att.events.len() <= MAX_QUEUE); - let events: Vec = c2_att.events.iter().map(|(_, m)| m.clone()).collect(); + let events: Vec = c2_att.events.iter().map(|(_, m)| (**m).clone()).collect(); let result_msg = events.iter().find(|e| e["id"] == 2).unwrap(); assert_eq!( result_msg["result"]["_meta"]["kit/gateway"]["replayTruncated"], @@ -3354,7 +3354,7 @@ fn pinned_current_turn_full_journal_with_pending_relay_succeeds_for_event_and_by + prepared .pending_requests .iter() - .map(|(_, m)| m.to_string().len()) + .map(|(_, _, bytes)| *bytes) .sum::(); assert!(prepared_bytes <= MAX_REPLAY); assert_eq!(prepared.pending_requests.len(), 1); @@ -4366,7 +4366,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star .unwrap() .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( !events_turn @@ -4411,7 +4411,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star .sole_attachment() .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert_eq!(events_msg[0]["params"]["update"]["messageId"], "u-1"); assert!( @@ -4560,7 +4560,7 @@ fn default_mode_replay_cursors_current_turn_truncation_kit_message_and_full_star .unwrap() .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( trunc_events @@ -4847,7 +4847,7 @@ async fn relay_expiration_is_terminal_even_when_child_writer_is_full() { .unwrap() .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( a1_events @@ -4877,7 +4877,7 @@ async fn relay_expiration_is_terminal_even_when_child_writer_is_full() { .unwrap() .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( !a2_events @@ -6277,7 +6277,7 @@ fn current_turn_replay_trims_past_oversized_interior_update() { let events: Vec = actor.attachments[&c1] .events .iter() - .map(|(_, m)| m.clone()) + .map(|(_, m)| (**m).clone()) .collect(); assert!( events.iter().all(|m| m.to_string().len() <= MAX_HTTP_FRAME), @@ -7101,3 +7101,239 @@ for line in sys.stdin: let _ = conn.delete().await; } + +#[tokio::test] +async fn oversized_live_update_is_contained_to_session_without_killing_multiplexed_connection() { + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source_a = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req.get('method') + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'live-ov-a','configOptions':[]}}) + elif m == 'session/prompt': + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'live-ov-a','update':{'sessionUpdate':'state_update','state':'running'}}}) + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'live-ov-a','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'x' * (1024 * 1024 + 4096)}}}}) + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'live-ov-a','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'tail-after-oversized'}}}}) + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'live-ov-a','update':{'sessionUpdate':'state_update','state':'idle'}}}) + emit({'jsonrpc':'2.0','id':req['id'],'result':{'stopReason':'end_turn'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let source_b = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req.get('method') + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'live-ov-b','configOptions':[]}}) + elif m == 'session/prompt': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'ok':'b-alive'}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("live-ov-a", source_a, &[]).await; + harness.child_source("live-ov-b", source_b, &[]).await; + + let conn = harness.connect("mux").await; + let mut sa = conn.open_session_stream("live-ov-a").await; + let mut sb = conn.open_session_stream("live-ov-b").await; + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"live-ov-a"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = sa.next_matching(|e| e["id"] == 1).await; + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"live-ov-b"}})) + .await, + StatusCode::ACCEPTED + ); + let _ = sb.next_matching(|e| e["id"] == 2).await; + + // Trigger >1 MiB live update on session A -> contained as a session-scoped delivery failure + // on session A without killing the shared HTTP connection! + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"pa","method":"session/prompt","params":{"sessionId":"live-ov-a","prompt":[{"type":"text","text":"big"}]}})) + .await, + StatusCode::ACCEPTED + ); + let notice = sa + .next_matching(|e| e["params"]["update"]["sessionUpdate"] == "_gateway_controller") + .await; + assert_eq!(notice["params"]["sessionId"], "live-ov-a"); + + // Unrelated session B on the SAME multiplexed HTTP connection remains completely healthy! + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"pb","method":"session/prompt","params":{"sessionId":"live-ov-b","prompt":[{"type":"text","text":"ping"}]}})) + .await, + StatusCode::ACCEPTED + ); + let done_b = sb.next_matching(|e| e["id"] == "pb").await; + assert_eq!(done_b["result"]["ok"], "b-alive"); + + // Reconnecting to session A with `_kit_current_turn` trims past the oversized update and + // recovers the usable tail from retained history! + let conn2 = harness.connect("rejoin").await; + let mut sa2 = conn2.open_session_stream("live-ov-a").await; + assert_eq!( + conn2 + .post(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"live-ov-a","replayFrom":{"type":"_kit_current_turn"}}})) + .await, + StatusCode::ACCEPTED + ); + let mut saw_tail = false; + let resumed = sa2 + .next_matching(|e| { + if e["params"]["update"]["content"]["text"] == "tail-after-oversized" { + saw_tail = true; + } + e["id"] == 3 + }) + .await; + assert!(saw_tail, "usable tail after oversized update must replay"); + assert_eq!( + resumed["result"]["_meta"]["kit/gateway"]["replayTruncated"], + true + ); + + let _ = conn.delete().await; + let _ = conn2.delete().await; +} + +#[test] +fn startup_relay_payloads_are_shared_and_aggregate_relay_bytes_are_bounded() { + let mut actor = pinned_actor("shared-relays", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "shared-relays", "configOptions": []})); + let (writes, _rx) = mpsc::channel(8); + + let c1 = actor + .command( + Request::Attach { + session: "shared-relays".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"shared-relays"}})), + elicitation_form: true, + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + // 1. Emit 8 relays of ~950 KiB each (~7.6 MiB <= 8 MiB MAX_REPLAY), draining c1's queue so + // live admission stays within MAX_REPLAY. + let big_msg = "r".repeat(950 * 1024); + for i in 0..8 { + let reply = actor.output(json!({ + "jsonrpc": "2.0", + "id": format!("ask-{i}"), + "method": "elicitation/create", + "params": {"sessionId": "shared-relays", "mode": "form", "message": big_msg} + })); + assert!( + reply.is_none(), + "relay {i} within 8 MiB budget must succeed" + ); + let cur = actor.attachments[&c1].next; + let _ = actor.command( + Request::Poll { + session: "shared-relays".into(), + attachment: c1.clone(), + cursor: cur, + }, + &writes, + ); + } + assert_eq!(actor.client_requests.len(), 8); + + // 2. A 9th 950 KiB relay would exceed MAX_REPLAY (8 MiB) aggregate pending relay bytes -> + // rejected immediately toward child with -32603 pending_relay_budget_exceeded! + let rejected = actor + .output(json!({ + "jsonrpc": "2.0", + "id": "ask-overflow-budget", + "method": "elicitation/create", + "params": {"sessionId": "shared-relays", "mode": "form", "message": big_msg} + })) + .expect("9th 950 KiB relay must be rejected by aggregate relay byte budget"); + assert_eq!(rejected["id"], "ask-overflow-budget"); + assert_eq!(rejected["error"]["code"], -32603); + assert_eq!( + rejected["error"]["data"]["reason"], + "pending_relay_budget_exceeded" + ); + assert_eq!(actor.client_requests.len(), 8); + + // 3. Multiple joining attachments share the exact same Arc allocations with + // PendingClientRequest.wire (zero deep clones) without consuming live-update headroom! + let c2 = actor + .command( + Request::Attach { + session: "shared-relays".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"shared-relays"}})), + elicitation_form: true, + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + let c3 = actor + .command( + Request::Attach { + session: "shared-relays".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({"jsonrpc":"2.0","id":3,"method":"session/resume","params":{"sessionId":"shared-relays"}})), + elicitation_form: true, + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + let att2 = &actor.attachments[&c2]; + let att3 = &actor.attachments[&c3]; + // Startup reservations remain excluded from live-update byte headroom! + assert!(att2.live_bytes() < 4096); + assert!(att3.live_bytes() < 4096); + + let mut matched = 0usize; + for (relay_id, req) in &actor.client_requests { + let ev2 = att2 + .events + .iter() + .find(|(_, m)| m.get("id").and_then(Value::as_str) == Some(relay_id.as_str())) + .expect("c2 has pending relay"); + let ev3 = att3 + .events + .iter() + .find(|(_, m)| m.get("id").and_then(Value::as_str) == Some(relay_id.as_str())) + .expect("c3 has pending relay"); + assert!( + Arc::ptr_eq(&req.wire, &ev2.1), + "c2 startup relay must share Arc with PendingClientRequest.wire" + ); + assert!( + Arc::ptr_eq(&req.wire, &ev3.1), + "c3 startup relay must share Arc with PendingClientRequest.wire" + ); + matched += 1; + } + assert_eq!(matched, 8); +} From 947a8c58f987b336bc350ce73636141710a6ef63 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 12:05:31 +0000 Subject: [PATCH 12/19] fix(gateway): preserve frame_too_large reason and document pinned fan-out frame limits --- docs/reference/gateway-protocol.md | 2 +- src/gateway.rs | 164 ++++++++++---- src/gateway/http_client/recovery.rs | 7 + src/gateway/http_client/recovery/tests.rs | 88 ++++++++ src/gateway/http_server.rs | 21 +- src/gateway/pinned_tests.rs | 254 +++++++++++++++++----- 6 files changed, 423 insertions(+), 113 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 221b8c8e..6c22d218 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -197,6 +197,6 @@ When pinned mode is active: - **Workspace ownership binding:** Cold startup (`session/new` / `session/resume`) and `session/list` resolve the pinned session's existing workspace-bound owner across all approved `--project` roots before discovery or spawning a child (an unbound legacy global transcript is not counted as a multi-project owner and restores into the explicitly selected approved root). For `session/new` and `session/resume`, a request whose `cwd` conflicts with the existing owning project is rejected (`root_denied`, `"session belongs to another project"`); `session/list` ignores `params.cwd` and still returns the pinned entry. If workspace-bound transcripts for the pinned ID exist in more than one approved project, both discovery and startup fail (`conflict`, `"pinned session belongs to multiple approved projects"`). Creation is allowed only when no approved project already owns that ID. - **One session, many attachments:** Both `session/new` and `session/resume` attach to the pinned session (creating it on first use or restoring its existing transcript in its owning project) and default absent/`null` `replayFrom` to no history (`historyAvailable: false`). Requests naming any other session ID fail with an error. If a single `--project` is configured (or the pinned session is already resident or bound to an existing workspace), `cwd` may be omitted; when multiple `--project` roots are configured and the pinned ID is not yet resident or bound to a workspace, `cwd` is required. New attachments never replace existing attachments, never trigger controller lease contention, and never withdraw another attachment's held prompts. Up to the SDK's 64 concurrent HTTP connections may attach. Each live HTTP connection's server-side poll loop refreshes its attachment's `touched` timestamp on every tick regardless of whether the remote peer reads SSE, and the SDK does no connection reaping on TCP drop. Therefore a client or fronting proxy **must** send HTTP `DELETE` when a client disconnects: otherwise the attachment stays live and is never orphaned (so retries from new connections are forwarded as fresh attempts instead of re-parenting), and the abandoned ghost continues to occupy one of the 64 connection slots until its outbound egress stalls or overflows. The 15-second lease reaper cleans up only attachments that no longer have a connection loop behind them (such as a leaked cold-startup driver, which fails parked joiners so subsequent clients can retry). - **Client-local `session/close`:** Sending `session/close` detaches only the calling attachment and returns `{}`; it never closes or terminates the pinned session. -- **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). If one attachment's queue overflows, only that attachment is dropped: its stream receives a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, its failed pending requests carry `error.data.reason = "queue_overflow"`, and its SSE stream closes cleanly without affecting other attachments or the active turn. +- **Fan-out and isolated overflow:** Every live attachment receives all `session/update` notifications through its own bounded queue (`4096` events / `8 MiB`). Attachment-local queue saturation is isolated to the slow attachment: only that attachment is dropped, receiving a `_gateway_controller` notification with `params.update._meta["kit/gateway"].reason = "queue_overflow"`, `error.data.reason = "queue_overflow"` on its failed pending requests, and a clean SSE stream close without affecting other attachments or the active turn. Separately, the `1 MiB` HTTP per-frame limit is enforced independently for each attachment: an ordinary request response exceeding `1 MiB` returns a bounded `-32603` (`data.reason = "frame_too_large"`, `terminal = false`) error on that request without retiring its attachment, whereas a single live `session/update` exceeding `1 MiB` fails per-frame admission on every live attachment receiving it (`reason = "frame_too_large"`, `terminal = false`), retiring those attachments without stopping the pinned child (retained history remains intact so clients can reconnect with `{"type":"_kit_current_turn"}` to trim past the oversized update). - **Fan-in, pending caps, and orphan re-parenting:** Responses to client requests are delivered only to the originating attachment (and dropped if that attachment has already detached). Pending client requests with IDs are capped in the gateway at `384` total (`128` active live requests across all attachments with at most `32` per attachment, plus up to `256` orphaned held prompts left behind by detached deliverers); for held prompts, the child's own `PendingPrompts` limits (`64` concurrent pending prompt groups and `256` pending attempts) bind first. `session/prompt` with `delivery: "steer"` or `"queue"` preserves native insertion semantics, and `idempotencyKey` deduplication holds across attachments (both while held and after insertion). When a deliverer retries a held `session/prompt` whose `idempotencyKey` matches an orphaned pending entry (whose withdrawal has not been requested), the gateway re-parents that entry to the new attachment and request ID without forwarding a duplicate attempt to the child, so retries consume neither extra gateway pending slots nor extra child attempt slots and orphan counts grow only with distinct uninserted messages (concurrent live attachments sharing the same key still forward as separate waiters). A re-parented retry's prompt body is not re-validated or used: the original held prompt is what gets inserted, matching the child's duplicate-key semantics. - **Detach and cancel:** Disconnecting an attachment does not withdraw its already-submitted held prompts, so a deliverer may disconnect before insertion and retry with the same `idempotencyKey`. Sending an explicit `$/cancel_request` withdraws **every** held attempt sharing that `idempotencyKey` (the entire unclaimed idempotency group in the child), not only the sender's attempt: every live attachment waiting on that key receives a JSON-RPC `-32800` (`Request cancelled`) error (detached attempts are dropped), the prompt is not inserted, and a deliverer must treat it as not delivered. Any live attachment may send `session/cancel`. diff --git a/src/gateway.rs b/src/gateway.rs index 76c0cc6f..19f25178 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -434,7 +434,10 @@ impl Failure { fn data(&self) -> Value { object([ ("reason", self.2.into()), - ("terminal", (self.2 != "unavailable").into()), + ( + "terminal", + (!matches!(self.2, "unavailable" | "frame_too_large")).into(), + ), ]) } fn jsonrpc_code(&self) -> i64 { @@ -981,6 +984,27 @@ struct CommittedOwner { recovery_id: Option, recovery_attempt: Option, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum AttachmentFailure { + QueueOverflow, + FrameTooLarge, +} +impl AttachmentFailure { + fn into_failure(self) -> Failure { + match self { + Self::QueueOverflow => Failure( + StatusCode::CONFLICT, + "attachment queue overflowed; reconnect".into(), + "queue_overflow", + ), + Self::FrameTooLarge => Failure( + StatusCode::CONFLICT, + "session frame exceeded HTTP frame limit; reconnect".into(), + "frame_too_large", + ), + } + } +} struct Attachment { id: String, touched: Instant, @@ -997,7 +1021,7 @@ struct Attachment { elicitation_form: bool, live: bool, closing: bool, - overflowed: bool, + failed: Option, } impl Attachment { fn new(id: String, elicitation_form: bool) -> Self { @@ -1012,7 +1036,7 @@ impl Attachment { elicitation_form, live: false, closing: false, - overflowed: false, + failed: None, } } fn can_receive_client_request(&self, method: &str) -> bool { @@ -1027,18 +1051,18 @@ impl Attachment { fn live_bytes(&self) -> usize { self.bytes.saturating_sub(self.reserved_bytes) } - fn push_shared(&mut self, message: Arc) -> bool { + fn push_shared(&mut self, message: Arc) -> Result<(), AttachmentFailure> { let bytes = message.to_string().len(); - if bytes > MAX_HTTP_FRAME - || self.live_events() >= MAX_QUEUE - || self.live_bytes() + bytes > MAX_REPLAY - { - return false; + if self.live_events() >= MAX_QUEUE || self.live_bytes() + bytes > MAX_REPLAY { + return Err(AttachmentFailure::QueueOverflow); + } + if bytes > MAX_HTTP_FRAME { + return Err(AttachmentFailure::FrameTooLarge); } self.bytes += bytes; self.next += 1; self.events.push_back((self.next, message)); - true + Ok(()) } fn push_reserved(&mut self, message: Arc, bytes: usize) { self.bytes += bytes; @@ -1119,7 +1143,7 @@ struct PendingClientRequest { } enum RetireMode { Remove, - Overflow, + Failed(AttachmentFailure), Closing, } struct PinnedState { @@ -1502,7 +1526,7 @@ impl Actor { fn live_update_targets(&self) -> Vec { self.attachments .values() - .filter(|a| a.live && !a.closing && !a.overflowed) + .filter(|a| a.live && !a.closing && a.failed.is_none()) .map(|a| a.id.clone()) .collect() } @@ -1513,7 +1537,7 @@ impl Actor { .filter(|a| { a.live && !a.closing - && !a.overflowed + && a.failed.is_none() && a.can_receive_client_request(method) && (pinned || a.touched.elapsed() < LEASE) }) @@ -1522,7 +1546,7 @@ impl Actor { } fn has_queued_relay_cancellations(&self) -> bool { self.attachments.values().any(|a| { - !a.overflowed + a.failed.is_none() && a.events .iter() .any(|(_, m)| m["method"] == "$/cancel_request") @@ -1531,28 +1555,41 @@ impl Actor { fn active_attachment(&self, attachment_id: &str) -> Option<&Attachment> { self.attachments .get(attachment_id) - .filter(|a| !a.closing && !a.overflowed) + .filter(|a| !a.closing && a.failed.is_none()) } fn active_attachment_mut(&mut self, attachment_id: &str) -> Option<&mut Attachment> { self.attachments .get_mut(attachment_id) - .filter(|a| !a.closing && !a.overflowed) + .filter(|a| !a.closing && a.failed.is_none()) } fn push_to_attachment(&mut self, attachment_id: &str, message: Value) -> bool { self.push_shared_to_attachment(attachment_id, Arc::new(message)) } fn push_shared_to_attachment(&mut self, attachment_id: &str, message: Arc) -> bool { - let overflowed = if let Some(attachment) = self.attachments.get_mut(attachment_id) { - if attachment.overflowed { + let failure = if let Some(attachment) = self.attachments.get_mut(attachment_id) { + if attachment.failed.is_some() { return false; } - !attachment.push_shared(message) + attachment.push_shared(message).err() } else { return false; }; - if overflowed { + if let Some(reason) = failure { if self.pinned.is_some() { - self.retire_pinned_attachment(attachment_id, RetireMode::Overflow); + self.retire_pinned_attachment(attachment_id, RetireMode::Failed(reason)); + } else if reason == AttachmentFailure::FrameTooLarge { + if let Some(attachment) = self.attachments.get_mut(attachment_id) { + attachment.events.clear(); + attachment.bytes = 0; + attachment.reserved.clear(); + attachment.reserved_bytes = 0; + attachment.live = false; + attachment.closing = false; + attachment.failed = Some(reason); + attachment.touched = Instant::now(); + } + self.mark_withdrawals(attachment_id); + self.mark_target_detached(attachment_id); } else { self.attachments.remove(attachment_id); self.mark_withdrawals(attachment_id); @@ -1641,7 +1678,7 @@ impl Actor { RetireMode::Remove => { self.attachments.remove(attachment_id); } - RetireMode::Overflow => { + RetireMode::Failed(reason) => { if let Some(attachment) = self.attachments.get_mut(attachment_id) { attachment.events.clear(); attachment.bytes = 0; @@ -1649,7 +1686,7 @@ impl Actor { attachment.reserved_bytes = 0; attachment.live = false; attachment.closing = false; - attachment.overflowed = true; + attachment.failed = Some(reason); attachment.touched = Instant::now(); } } @@ -1699,13 +1736,9 @@ impl Actor { let Some(entry) = self.attachments.get_mut(&attachment) else { return Err(Failure::unavailable("child exited; restore its transcript")); }; - if entry.overflowed { + if let Some(reason) = entry.failed { self.attachments.remove(&attachment); - return Err(Failure( - StatusCode::CONFLICT, - "attachment queue overflowed; reconnect".into(), - "queue_overflow", - )); + return Err(reason.into_failure()); } let (events, _) = entry.poll(cursor)?; if events.is_empty() { @@ -2177,7 +2210,32 @@ impl Actor { return None; } message["id"] = pending.original; - self.push_to_attachment(&pending.attachment, message); + if message.to_string().len() > MAX_HTTP_FRAME { + let error = object([ + ("jsonrpc", "2.0".into()), + ("id", message["id"].clone()), + ( + "error", + object([ + ("code", (-32603).into()), + ( + "message", + "session response exceeds HTTP frame limit".into(), + ), + ( + "data", + object([ + ("reason", "frame_too_large".into()), + ("terminal", false.into()), + ]), + ), + ]), + ), + ]); + self.push_to_attachment(&pending.attachment, error); + } else { + self.push_to_attachment(&pending.attachment, message); + } } } None @@ -2684,7 +2742,7 @@ impl Actor { && self .attachments .values() - .any(|a| a.touched.elapsed() < LEASE) + .any(|a| a.failed.is_none() && a.touched.elapsed() < LEASE) { return Err(Failure::conflict( "session already has a controlling attachment", @@ -2743,13 +2801,14 @@ impl Actor { let token = match &request { Request::Poll { attachment, .. } | Request::Send { attachment, .. } - | Request::Detach { attachment, .. } => attachment, + | Request::Detach { attachment, .. } => attachment.clone(), _ => return Err(Failure::bad("invalid actor operation")), }; - let attachment = self + let failed = self .attachments - .get_mut(token) + .get(&token) .filter(|a| a.touched.elapsed() < LEASE) + .map(|a| a.failed) .ok_or_else(|| { Failure( StatusCode::CONFLICT, @@ -2757,15 +2816,28 @@ impl Actor { "controller_replaced", ) })?; + if let Request::Detach { attachment, .. } = request { + self.attachments.remove(&attachment); + self.mark_withdrawals(&attachment); + self.mark_target_detached(&attachment); + self.flush_withdrawals(writes); + return Ok(object([])); + } + if let Some(reason) = failed { + if matches!(request, Request::Poll { .. }) { + self.attachments.remove(&token); + } + return Err(reason.into_failure()); + } + let attachment = self.attachments.get_mut(&token).ok_or_else(|| { + Failure( + StatusCode::CONFLICT, + "attachment expired or was replaced; reconnect".into(), + "controller_replaced", + ) + })?; attachment.touched = Instant::now(); match request { - Request::Detach { attachment, .. } => { - self.attachments.remove(&attachment); - self.mark_withdrawals(&attachment); - self.mark_target_detached(&attachment); - self.flush_withdrawals(writes); - Ok(object([])) - } Request::Poll { cursor, .. } => { let (events, drained) = attachment.poll(cursor)?; Ok(object([ @@ -2878,22 +2950,18 @@ impl Actor { return Ok(object([])); } - let Some(overflowed) = self.attachments.get(&token).map(|a| a.overflowed) else { + let Some(failed) = self.attachments.get(&token).map(|a| a.failed) else { return Err(Failure( StatusCode::CONFLICT, "attachment is not active; reconnect".into(), "attachment_closed", )); }; - if overflowed { + if let Some(reason) = failed { if matches!(request, Request::Poll { .. }) { self.attachments.remove(&token); } - return Err(Failure( - StatusCode::CONFLICT, - "attachment queue overflowed; reconnect".into(), - "queue_overflow", - )); + return Err(reason.into_failure()); } match request { diff --git a/src/gateway/http_client/recovery.rs b/src/gateway/http_client/recovery.rs index 974b253b..166d90e6 100644 --- a/src/gateway/http_client/recovery.rs +++ b/src/gateway/http_client/recovery.rs @@ -518,6 +518,13 @@ pub(super) async fn run( lost = true; break; } + if value["method"] == "session/update" + && value["params"]["sessionId"].as_str() == session.as_deref() + && value["params"]["update"]["sessionUpdate"] == "_gateway_controller" + { + lost = true; + break; + } if value.get("id").is_some() && value.get("method").is_none() && reserved(&value["id"]) diff --git a/src/gateway/http_client/recovery/tests.rs b/src/gateway/http_client/recovery/tests.rs index caf5d433..d6700073 100644 --- a/src/gateway/http_client/recovery/tests.rs +++ b/src/gateway/http_client/recovery/tests.rs @@ -67,6 +67,12 @@ fn terminal_classification_uses_structured_metadata_only() { terminal_reason(&json!({"error":{"data":{"terminal":true,"reason":"root_denied"}}})), Some("root_denied") ); + assert_eq!( + terminal_reason( + &json!({"method":"session/update","params":{"update":{"sessionUpdate":"_gateway_controller","_meta":{"kit/gateway":{"terminal":false,"reason":"frame_too_large"}}}}}) + ), + None + ); assert_eq!( terminal_reason( &json!({"method":"session/update","params":{"update":{"sessionUpdate":"_gateway_controller","_meta":{"kit/gateway":{"terminal":true,"reason":"controller_replaced"}}}}}) @@ -574,3 +580,85 @@ async fn recovered_initialize_accepts_follow_up_before_output_flush_returns() { result.unwrap(); assert!(server.requests.try_recv().is_err()); } + +#[tokio::test] +async fn non_terminal_frame_too_large_controller_notice_triggers_recovery() { + let mut server = Server::new(None).await; + let remote = server.remote.clone(); + let (send, lines) = mpsc::channel(16); + let (writer, mut output) = output_pipe(); + let scenario = async { + send.send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + let init = server.requests.recv().await.unwrap(); + assert_eq!(init["method"], "initialize"); + until_id(&mut output, json!(1)).await; + send.send(frame( + 2, + "session/new", + json!({"cwd":"/local","mcpServers":[]}), + )) + .await + .unwrap(); + let new = server.requests.recv().await.unwrap(); + server.result( + &new, + json!({"sessionId":"durable","configOptions":[],"_meta":{"kit/gateway":{"attachment":"owner-1"}}}), + "", + ); + until_id(&mut output, json!(2)).await; + + // Emit a non-terminal frame_too_large controller notice -> bundled client MUST enter + // automatic recovery rather than exiting as terminal controller_replaced! + server + .events + .send(( + "*".into(), + Some(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "durable", + "update": { + "sessionUpdate": "_gateway_controller", + "_meta": { + "kit/gateway": { + "reason": "frame_too_large", + "terminal": false + } + } + } + } + })), + )) + .unwrap(); + until_kind(&mut output, "begin").await; + + let reinit = server.requests.recv().await.unwrap(); + assert_eq!(reinit["method"], "initialize"); + let resume = server.requests.recv().await.unwrap(); + assert_eq!(resume["method"], "session/resume"); + assert_eq!(resume["params"]["sessionId"], "durable"); + assert_eq!( + resume["params"]["_meta"]["kit/gateway"]["previousAttachment"], + "owner-1" + ); + server.update(json!({"sessionUpdate":"config_option_update","configOptions":[]})); + server.update(json!({"sessionUpdate":"state_update","state":"idle"})); + server.result( + &resume, + json!({"_meta":{"kit/gateway":{"attachment":"owner-2","historyAvailable":true,"stateSnapshot":true,"configSnapshot":true}}}), + "durable", + ); + until_kind(&mut output, "commit").await; + drop(send); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(8), async { + tokio::join!(run(remote, "/remote".into(), lines, writer), scenario) + }) + .await + .unwrap(); + result.unwrap(); + assert!(server.requests.try_recv().is_err()); +} diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 9eedcbc8..d7a495a7 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -15,7 +15,7 @@ pub(super) struct Connection { initialize: Option<(Value, Arc)>, controls: HashMap, relay_routes: HashMap, - closing_connection: bool, + pub(super) closing_connection: bool, } struct Control { @@ -128,7 +128,7 @@ impl Connection { .map(|Json(value)| value) } - async fn request( + pub(super) async fn request( &mut self, mut message: Value, channel: &BoundedChannel, @@ -240,7 +240,11 @@ impl Connection { | Err(Failure( _, _, - "controller_replaced" | "unavailable" | "queue_overflow" | "attachment_closed", + "controller_replaced" + | "unavailable" + | "queue_overflow" + | "frame_too_large" + | "attachment_closed", )) => {} Err(error) => return Err(error), } @@ -516,7 +520,10 @@ impl Connection { Ok(None) } - async fn flush(&mut self, channel: &BoundedChannel) -> agent_client_protocol::Result<()> { + pub(super) async fn flush( + &mut self, + channel: &BoundedChannel, + ) -> agent_client_protocol::Result<()> { self.flush_with_response(channel, None).await } @@ -594,8 +601,8 @@ impl Connection { // Settle that controller's pending calls explicitly before forgetting it. for (id, error) in failed { if let Some(mut control) = self.controls.remove(&id) { - let overflowed_pinned = - self.gateway.pinned_session.is_some() && error.2 == "queue_overflow"; + let close_pinned = self.gateway.pinned_session.is_some() + && matches!(error.2, "queue_overflow" | "frame_too_large"); send( channel, object([ @@ -637,7 +644,7 @@ impl Connection { ) .await?; } - if overflowed_pinned { + if close_pinned { self.closing_connection = true; } } diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 99efcf67..99f8c14c 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -2712,16 +2712,20 @@ fn pinned_reply_dropped_when_sender_detached_never_leaks_to_other_attachment() { #[tokio::test] async fn pinned_real_actor_http_overflow_isolates_slow_client_while_fast_client_continues() { + use agent_client_protocol::{BoundedChannel, ChannelLimits, TransportFrame}; + use futures_util::StreamExt; + let harness = PinnedHarness::new("pinned-real-ovf", Duration::from_secs(60)).await; - // Emit a single child response to client 1's request whose raw stdout line fits within - // MAX_REPLAY (8 MiB), but whose remapped client request id pushes the queued frame over - // MAX_REPLAY. That deterministically triggers `RetireMode::Overflow` on client 1's actor - // queue in one atomic step without racing the 25 ms poll tick or the SDK's 4 MiB HTTP - // egress cap, while leaving client 2 completely unaffected. + // Client 1 drives the real `http_server::Connection` explicitly (stopping `flush` to model a + // stalled/slow attachment with zero wall-clock drain-timeout race), while Client 2 runs over + // real HTTP (`PinnedHarness`). Client 2 paces 82 x 50 = 4100 tiny `session/update` frames + // (> MAX_QUEUE = 4096, ~550 KiB total), draining every batch cleanly while Client 1's unpolled + // actor queue deterministically hits `QueueOverflow`, retires only Client 1, emits + // `_gateway_controller` (`queue_overflow`) + pending error on Client 1's next `flush`, and + // marks Client 1's connection for clean close while Client 2 continues unaffected. let source = r#" import sys, json def emit(v): print(json.dumps(v), flush=True) -MAX_REPLAY = 8 * 1024 * 1024 for line in sys.stdin: req = json.loads(line) m = req['method'] @@ -2730,14 +2734,13 @@ for line in sys.stdin: elif m in ('session/new', 'session/resume'): emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'pinned-real-ovf','configOptions':[]}}) elif m == 'kit/session/status': - if req['params'].get('hold'): + p = req['params'] + if p.get('hold') == 'pending': continue - if req['params'].get('overflow'): - shell = json.dumps({'jsonrpc':'2.0','id':req['id'],'result':{'pad':''}}, separators=(',',':')) - pad_len = MAX_REPLAY - len(shell) - 16 - out = json.dumps({'jsonrpc':'2.0','id':req['id'],'result':{'pad':'z' * pad_len}}, separators=(',',':')) - sys.stdout.write(out + '\n') - sys.stdout.flush() + if p.get('emit_tiny'): + for i in range(int(p['emit_tiny'])): + emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'pinned-real-ovf','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':f'm{i}'}}}}) + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) else: emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) elif 'id' in req: @@ -2745,14 +2748,82 @@ for line in sys.stdin: "#; harness.child_source("pinned-real-ovf", source, &[]).await; - let c1 = harness.connect("overflower").await; - let mut s1 = c1.open_session_stream("pinned-real-ovf").await; - assert_eq!( - c1.post(json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-real-ovf"}})) - .await, - StatusCode::ACCEPTED + let (mut peer1, mut channel1) = BoundedChannel::duplex(ChannelLimits::default()).unwrap(); + let mut c1 = http_server::Connection::new(harness.gateway.clone()); + + async fn send_request( + c1: &mut http_server::Connection, + peer_tx: &agent_client_protocol::BoundedSender, + channel: &mut BoundedChannel, + message: Value, + ) -> Option { + let raw = message.to_string(); + peer_tx + .send(TransportFrame::parse_json(&raw)) + .await + .unwrap(); + let charged = Arc::new(channel.rx.next().await.unwrap()); + let reply = c1.request(message, channel, &charged).await.unwrap(); + drop(charged); + reply + } + fn decode_frame(charged: agent_client_protocol::ChargedFrame) -> Value { + let value = match charged.decode() { + TransportFrame::Single(message) => serde_json::to_value(message).unwrap(), + other => panic!("unexpected frame on c1: {other:?}"), + }; + drop(charged); + value + } + async fn flush_until_id( + c1: &mut http_server::Connection, + channel: &BoundedChannel, + peer_rx: &mut agent_client_protocol::BoundedReceiver, + expected: Value, + ) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while tokio::time::Instant::now() < deadline { + c1.flush(channel).await.unwrap(); + while let Some(Some(charged)) = futures_util::FutureExt::now_or_never(peer_rx.next()) { + if decode_frame(charged)["id"] == expected { + return; + } + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("timed out waiting for c1 reply {expected}"); + } + + assert!( + send_request( + &mut c1, + &peer1.tx, + &mut channel1, + json!({ + "jsonrpc": "2.0", + "id": 0, + "method": "initialize", + "params": { + "protocolVersion": 2, + "info": {"name": "slow", "version": "1"}, + "capabilities": {} + } + }), + ) + .await + .is_some() ); - let _ = s1.next_matching(|e| e["id"] == 1).await; + assert!( + send_request( + &mut c1, + &peer1.tx, + &mut channel1, + json!({"jsonrpc":"2.0","id":1,"method":"session/resume","params":{"sessionId":"pinned-real-ovf"}}), + ) + .await + .is_none() + ); + flush_until_id(&mut c1, &channel1, &mut peer1.rx, json!(1)).await; let c2 = harness.connect("healthy").await; let mut s2 = c2.open_session_stream("pinned-real-ovf").await; @@ -2763,50 +2834,85 @@ for line in sys.stdin: ); let _ = s2.next_matching(|e| e["id"] == 2).await; - // Submit a held request on c1 so we also verify pending request settlement on queue_overflow. - assert_eq!( - c1.post(json!({"jsonrpc":"2.0","id":"still-pending","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf","hold":true}})) - .await, - StatusCode::ACCEPTED + // Register a held pending request on c1 and sync so it is guaranteed in-flight in the child. + assert!( + send_request( + &mut c1, + &peer1.tx, + &mut channel1, + json!({"jsonrpc":"2.0","id":"still-pending","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf","hold":"pending"}}), + ) + .await + .is_none() ); - // Trigger deterministic actor-queue overflow for c1 alone via a long client request id. - let long_id = "o".repeat(256); - assert_eq!( - c1.post(json!({"jsonrpc":"2.0","id":long_id,"method":"kit/session/status","params":{"sessionId":"pinned-real-ovf","overflow":true}})) - .await, - StatusCode::ACCEPTED + assert!( + send_request( + &mut c1, + &peer1.tx, + &mut channel1, + json!({"jsonrpc":"2.0","id":"sync-held","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf"}}), + ) + .await + .is_none() ); + flush_until_id(&mut c1, &channel1, &mut peer1.rx, json!("sync-held")).await; - let mut saw_overflow_notice = false; - let mut saw_pending_overflow_error = false; - let mut ended_cleanly = false; - let deadline = tokio::time::Instant::now() + Duration::from_secs(15); - while tokio::time::Instant::now() < deadline { - match tokio::time::timeout(Duration::from_secs(5), s1.next_event()).await { - Ok(Some(ev)) => { - if ev["params"]["update"]["sessionUpdate"] == "_gateway_controller" - && ev["params"]["update"]["_meta"]["kit/gateway"]["reason"] == "queue_overflow" - { - saw_overflow_notice = true; - } - if ev["id"] == "still-pending" && ev["error"]["data"]["reason"] == "queue_overflow" - { - saw_pending_overflow_error = true; - } + // Client 1 now stops polling. Client 2 paces 82 x 50 = 4100 tiny updates (> MAX_QUEUE = 4096, + // < 64 max_egress_frames per batch) over real HTTP and drains every batch cleanly. Once batch + // 81's reply arrives on Client 2, all 4100 updates have been processed by the actor and + // Client 1's unpolled queue has deterministically hit `QueueOverflow`. + for batch in 0..82 { + let req_id = format!("fill-{batch}"); + assert_eq!( + c2.post(json!({"jsonrpc":"2.0","id":req_id,"method":"kit/session/status","params":{"sessionId":"pinned-real-ovf","emit_tiny":50}})) + .await, + StatusCode::ACCEPTED + ); + let mut tiny_seen = 0usize; + let mut saw_reply = false; + while tiny_seen < 50 || !saw_reply { + let ev = tokio::time::timeout(Duration::from_secs(10), s2.next_event()) + .await + .unwrap() + .expect("fast client stream must remain open"); + if ev["method"] == "session/update" { + tiny_seen += 1; } - Ok(None) => { - ended_cleanly = true; - break; + if ev["id"] == req_id { + saw_reply = true; } - Err(_) => break, + } + } + + // Client 1's next flush polls the actor, observes `queue_overflow`, emits `_gateway_controller` + // (`reason == "queue_overflow"`) and settles `still-pending` with `queue_overflow`, and marks + // the connection for clean close. + c1.flush(&channel1).await.unwrap(); + assert!( + c1.closing_connection, + "overflowed pinned connection must mark itself for clean close" + ); + channel1.tx.close_channel(); + + let mut saw_overflow_notice = false; + let mut saw_pending_overflow_error = false; + while let Some(charged) = peer1.rx.next().await { + let ev = decode_frame(charged); + if ev["params"]["update"]["sessionUpdate"] == "_gateway_controller" + && ev["params"]["update"]["_meta"]["kit/gateway"]["reason"] == "queue_overflow" + { + saw_overflow_notice = true; + } + if ev["id"] == "still-pending" && ev["error"]["data"]["reason"] == "queue_overflow" { + saw_pending_overflow_error = true; } } assert!( - ended_cleanly && saw_overflow_notice && saw_pending_overflow_error, - "overflowed client stream must emit queue_overflow notice + pending errors and close cleanly (ended={ended_cleanly}, notice={saw_overflow_notice}, err={saw_pending_overflow_error})" + saw_overflow_notice && saw_pending_overflow_error, + "overflowed client stream must emit queue_overflow notice + pending errors (notice={saw_overflow_notice}, err={saw_pending_overflow_error})" ); - // Client 2 continues working normally after Client 1 overflowed. + // Client 2 continues working normally over real HTTP after Client 1 overflowed. assert_eq!( c2.post(json!({"jsonrpc":"2.0","id":"after-burst","method":"kit/session/status","params":{"sessionId":"pinned-real-ovf"}})) .await, @@ -2815,7 +2921,6 @@ for line in sys.stdin: let status = s2.next_matching(|e| e["id"] == "after-burst").await; assert_eq!(status["result"]["settled"], true); - let _ = c1.delete().await; let _ = c2.delete().await; } @@ -7115,6 +7220,11 @@ for line in sys.stdin: emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) elif m in ('session/new', 'session/resume'): emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'live-ov-a','configOptions':[]}}) + elif m == 'kit/session/status': + if req['params'].get('huge_response'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'pad':'y' * (1024 * 1024 + 4096)}}) + else: + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) elif m == 'session/prompt': emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'live-ov-a','update':{'sessionUpdate':'state_update','state':'running'}}}) emit({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'live-ov-a','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'x' * (1024 * 1024 + 4096)}}}}) @@ -7158,8 +7268,30 @@ for line in sys.stdin: ); let _ = sb.next_matching(|e| e["id"] == 2).await; - // Trigger >1 MiB live update on session A -> contained as a session-scoped delivery failure - // on session A without killing the shared HTTP connection! + // 1. An oversized ordinary response (> 1 MiB) returns a bounded -32603 frame_too_large error + // on the originating request WITHOUT retiring session A's attachment! + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"huge-res","method":"kit/session/status","params":{"sessionId":"live-ov-a","huge_response":true}})) + .await, + StatusCode::ACCEPTED + ); + let huge_err = sa.next_matching(|e| e["id"] == "huge-res").await; + assert_eq!(huge_err["error"]["code"], -32603); + assert_eq!(huge_err["error"]["data"]["reason"], "frame_too_large"); + assert_eq!(huge_err["error"]["data"]["terminal"], false); + + // Session A's attachment is STILL alive after the oversized ordinary response! + assert_eq!( + conn.post(json!({"jsonrpc":"2.0","id":"ok-after-huge","method":"kit/session/status","params":{"sessionId":"live-ov-a"}})) + .await, + StatusCode::ACCEPTED + ); + let ok_res = sa.next_matching(|e| e["id"] == "ok-after-huge").await; + assert_eq!(ok_res["result"]["settled"], true); + + // 2. Trigger >1 MiB live update on session A -> contained as a non-terminal frame_too_large + // session-scoped delivery failure (NOT terminal controller_replaced!) without killing the + // shared HTTP connection! assert_eq!( conn.post(json!({"jsonrpc":"2.0","id":"pa","method":"session/prompt","params":{"sessionId":"live-ov-a","prompt":[{"type":"text","text":"big"}]}})) .await, @@ -7169,6 +7301,14 @@ for line in sys.stdin: .next_matching(|e| e["params"]["update"]["sessionUpdate"] == "_gateway_controller") .await; assert_eq!(notice["params"]["sessionId"], "live-ov-a"); + assert_eq!( + notice["params"]["update"]["_meta"]["kit/gateway"]["reason"], + "frame_too_large" + ); + assert_eq!( + notice["params"]["update"]["_meta"]["kit/gateway"]["terminal"], + false + ); // Unrelated session B on the SAME multiplexed HTTP connection remains completely healthy! assert_eq!( From d2c4f250393bdd62bd8a9440b8d4ec658aa49e39 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 12:28:29 +0000 Subject: [PATCH 13/19] fix(gateway): check per-frame limit before queue capacity and retain frame_too_large recovery cause --- src/gateway.rs | 6 +- src/gateway/http_client/recovery.rs | 18 +- src/gateway/http_client/recovery/tests.rs | 190 ++++++++++++++++++++++ src/gateway/pinned_tests.rs | 78 +++++++++ src/gateway/tests.rs | 4 +- 5 files changed, 289 insertions(+), 7 deletions(-) diff --git a/src/gateway.rs b/src/gateway.rs index 19f25178..a5e9dc5e 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -1053,12 +1053,12 @@ impl Attachment { } fn push_shared(&mut self, message: Arc) -> Result<(), AttachmentFailure> { let bytes = message.to_string().len(); - if self.live_events() >= MAX_QUEUE || self.live_bytes() + bytes > MAX_REPLAY { - return Err(AttachmentFailure::QueueOverflow); - } if bytes > MAX_HTTP_FRAME { return Err(AttachmentFailure::FrameTooLarge); } + if self.live_events() >= MAX_QUEUE || self.live_bytes() + bytes > MAX_REPLAY { + return Err(AttachmentFailure::QueueOverflow); + } self.bytes += bytes; self.next += 1; self.events.push_back((self.next, message)); diff --git a/src/gateway/http_client/recovery.rs b/src/gateway/http_client/recovery.rs index 166d90e6..2b12fa47 100644 --- a/src/gateway/http_client/recovery.rs +++ b/src/gateway/http_client/recovery.rs @@ -220,6 +220,7 @@ pub(super) async fn run( let mut epoch = 1; let mut attempt = 0; let mut recovery_start = None; + let mut recovery_cause: Option = None; let mut gate = None; let mut terminal: Option = None; loop { @@ -512,9 +513,14 @@ pub(super) async fn run( )?; pending.remove(index); } - terminal = Some(format!( - "Gateway {reason}; submission outcome may be unknown. Inspect kit gateway list and restart explicitly; replay_unavailable requires explicit --remote-no-replay opt-in." - )); + terminal = Some(match (reason, recovery_cause.as_deref()) { + ("replay_unavailable", Some("frame_too_large")) => { + "Gateway replay_unavailable after frame_too_large (live update exceeded the 1 MiB HTTP frame limit); submission outcome may be unknown. Inspect kit gateway list and restart explicitly; replay_unavailable requires explicit --remote-no-replay opt-in.".into() + } + _ => format!( + "Gateway {reason}; submission outcome may be unknown. Inspect kit gateway list and restart explicitly; replay_unavailable requires explicit --remote-no-replay opt-in." + ), + }); lost = true; break; } @@ -522,6 +528,10 @@ pub(super) async fn run( && value["params"]["sessionId"].as_str() == session.as_deref() && value["params"]["update"]["sessionUpdate"] == "_gateway_controller" { + recovery_cause = + value["params"]["update"]["_meta"]["kit/gateway"]["reason"] + .as_str() + .map(str::to_owned); lost = true; break; } @@ -552,6 +562,7 @@ pub(super) async fn run( phase = "live"; gate = Some(Instant::now()); recovery_start = None; + recovery_cause = None; attempt = 0; // Initial initialize is safe to retry; preserve its original local ID. if let Some(index) = @@ -624,6 +635,7 @@ pub(super) async fn run( phase = "live"; gate = Some(Instant::now()); recovery_start = None; + recovery_cause = None; notice( &mut output, session.as_deref().ok_or("Missing durable target")?, diff --git a/src/gateway/http_client/recovery/tests.rs b/src/gateway/http_client/recovery/tests.rs index d6700073..136fd63e 100644 --- a/src/gateway/http_client/recovery/tests.rs +++ b/src/gateway/http_client/recovery/tests.rs @@ -662,3 +662,193 @@ async fn non_terminal_frame_too_large_controller_notice_triggers_recovery() { result.unwrap(); assert!(server.requests.try_recv().is_err()); } + +#[tokio::test] +async fn real_gateway_full_replay_preserves_frame_too_large_cause_and_keeps_explicit_no_replay_opt_in() + { + use super::super::super::{ + Actor, BearerToken, DEFAULT_CLIENT_REQUEST_TIMEOUT, Entry, Gateway, MAX_HTTP_FRAME, router, + }; + use std::{ + collections::HashMap, + process::Stdio, + sync::{Arc, atomic::AtomicBool}, + }; + use tokio::sync::{Mutex, watch}; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let mut credential = tempfile::NamedTempFile::new().unwrap(); + writeln!(credential, "test-token").unwrap(); + let token_path = credential.path().to_owned(); + let gateway = Arc::new(Gateway { + stopping: AtomicBool::new(false), + token: BearerToken::load(&token_path).unwrap(), + roots: vec![root.clone()], + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, + sessions: Mutex::new(HashMap::new()), + }); + + let source = format!( + r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +oversized = 'x' * ({} + 2048) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({{'jsonrpc':'2.0','id':req['id'],'result':{{'protocolVersion':2,'info':{{'name':'fake','version':'1'}},'capabilities':{{}}}}}}) + elif m in ('session/new', 'session/resume'): + emit({{'jsonrpc':'2.0','id':req['id'],'result':{{'sessionId':'oversized-replay','configOptions':[]}}}}) + elif m == 'kit/session/status': + if req['params'].get('emit_oversized'): + emit({{'jsonrpc':'2.0','method':'session/update','params':{{'sessionId':'oversized-replay','update':{{'sessionUpdate':'agent_message_chunk','content':{{'type':'text','text':oversized}}}}}}}}) + emit({{'jsonrpc':'2.0','id':req['id'],'result':{{'settled':True}}}}) + elif 'id' in req: + emit({{'jsonrpc':'2.0','id':req['id'],'result':{{}}}}) +"#, + MAX_HTTP_FRAME + ); + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", &source]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let actor = Actor::new( + "oversized-replay".into(), + root.clone(), + false, + false, + DEFAULT_CLIENT_REQUEST_TIMEOUT, + ); + let (actor_tx, actor_rx) = mpsc::channel(32); + let (completion, stopped) = watch::channel(()); + tokio::spawn(async move { + actor.run(child, actor_rx).await; + drop(completion); + }); + gateway.sessions.lock().await.insert( + "oversized-replay".into(), + Entry { + root: root.clone(), + sender: actor_tx, + stopped, + }, + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let app = router(gateway).unwrap(); + let server_task = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + // 1) Default client (no_replay: false) attaches, triggers an oversized live update, enters + // automatic recovery, and hits terminal `replay_unavailable` on real full replay -> both the + // emitted failure notice and returned error must preserve `frame_too_large` alongside + // `replay_unavailable` and the explicit `--remote-no-replay` opt-in. + let remote = super::super::super::Remote { + url: format!("http://{address}"), + credential_file: token_path.clone(), + session: Some("oversized-replay".into()), + no_replay: false, + }; + let (send, lines) = mpsc::channel(16); + let (writer, mut output) = output_pipe(); + let scenario = async { + send.send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + until_id(&mut output, json!(1)).await; + send.send(frame(2, "session/new", json!({"cwd":root,"mcpServers":[]}))) + .await + .unwrap(); + let initial_commit = until_kind(&mut output, "commit").await; + assert_eq!( + initial_commit["params"]["_meta"][META]["historyAvailable"], + true + ); + until_id(&mut output, json!(2)).await; + + send.send(frame( + 3, + "kit/session/status", + json!({"sessionId":"oversized-replay","emit_oversized":true}), + )) + .await + .unwrap(); + let begin = until_kind(&mut output, "begin").await; + assert!(begin["params"]["_meta"][META]["epoch"].as_u64().unwrap() >= 2); + let failed = until_kind(&mut output, "failed").await; + let failed_msg = failed["params"]["update"]["description"].as_str().unwrap(); + assert_eq!(failed["params"]["_meta"][META]["message"], failed_msg); + assert!( + failed_msg.contains("replay_unavailable") + && failed_msg.contains("frame_too_large") + && failed_msg.contains("--remote-no-replay"), + "failed notice must preserve both replay_unavailable and frame_too_large: {failed_msg}" + ); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(15), async { + tokio::join!(run(remote, root.clone(), lines, writer), scenario) + }) + .await + .unwrap(); + let err = result.unwrap_err().to_string(); + assert!( + err.contains("replay_unavailable") + && err.contains("frame_too_large") + && err.contains("--remote-no-replay"), + "returned error must preserve both replay_unavailable and frame_too_large: {err}" + ); + + // 2) Explicit --remote-no-replay opt-in attaches cleanly to the same resident session. + let remote_no_replay = super::super::super::Remote { + url: format!("http://{address}"), + credential_file: token_path, + session: Some("oversized-replay".into()), + no_replay: true, + }; + let (send2, lines2) = mpsc::channel(16); + let (writer2, mut output2) = output_pipe(); + let scenario2 = async { + send2 + .send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + until_id(&mut output2, json!(1)).await; + send2 + .send(frame(2, "session/new", json!({"cwd":root,"mcpServers":[]}))) + .await + .unwrap(); + let commit = until_kind(&mut output2, "commit").await; + assert_eq!(commit["params"]["_meta"][META]["historyAvailable"], false); + until_id(&mut output2, json!(2)).await; + send2 + .send(frame( + 3, + "kit/session/status", + json!({"sessionId":"oversized-replay"}), + )) + .await + .unwrap(); + let reply = until_id(&mut output2, json!(3)).await; + assert_eq!(reply["result"]["settled"], true); + drop(send2); + }; + let (result2, ()) = tokio::time::timeout(Duration::from_secs(15), async { + tokio::join!( + run(remote_no_replay, root.clone(), lines2, writer2), + scenario2 + ) + }) + .await + .unwrap(); + result2.unwrap(); + server_task.abort(); +} diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 99f8c14c..593982c9 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -7477,3 +7477,81 @@ fn startup_relay_payloads_are_shared_and_aggregate_relay_bytes_are_bounded() { } assert_eq!(matched, 8); } + +#[test] +fn oversized_live_update_exceeding_remaining_queue_budget_reports_frame_too_large() { + let mut actor = default_actor("overlap-frame-limit", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "overlap-frame-limit", "configOptions": []})); + let (writes, _child_rx) = mpsc::channel(8); + + let att = actor + .command( + Request::Attach { + session: "overlap-frame-limit".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/resume", + "params": {"sessionId": "overlap-frame-limit"} + })), + elicitation_form: true, + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + // Fill the attachment's valid queue near MAX_REPLAY (8 x 900 KiB = 7.2 MiB < 8 MiB) so an + // incoming > 1 MiB frame ALSO exceeds the remaining aggregate byte budget. + let valid_pad = "a".repeat(900 * 1024); + for i in 0..8 { + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "overlap-frame-limit", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": format!("{i}:{valid_pad}")} + } + } + })); + } + assert!( + actor.attachments[&att].failed.is_none(), + "valid <= 1 MiB frames within MAX_REPLAY must stay queued" + ); + + // Emit a single > 1 MiB live update that would also push live_bytes past MAX_REPLAY. + // Must classify as non-terminal `frame_too_large` rather than `queue_overflow` / `controller_replaced`. + let oversized_pad = "b".repeat(MAX_HTTP_FRAME + 1024); + actor.output(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "overlap-frame-limit", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": oversized_pad} + } + } + })); + + let err = actor + .command( + Request::Poll { + session: "overlap-frame-limit".into(), + attachment: att, + cursor: 0, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(err.2, "frame_too_large"); + assert_eq!(err.data()["reason"], "frame_too_large"); + assert_eq!(err.data()["terminal"], false); +} diff --git a/src/gateway/tests.rs b/src/gateway/tests.rs index a48345d1..be6aee9b 100644 --- a/src/gateway/tests.rs +++ b/src/gateway/tests.rs @@ -1792,7 +1792,9 @@ fn detached_owner_fences_replaced_controller_and_preserves_recovery_high_water_m .unwrap(); let b = actor.sole_attachment().id.clone(); if overflow { - actor.push_to_attachment(&b, json!({"payload":"x".repeat(MAX_REPLAY)})); + for _ in 0..=MAX_QUEUE { + actor.push_to_attachment(&b, state_update("running")); + } } else { actor .command( From 5c46e822405bdba4b3f2fb7cb994cc690e0b9636 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 12:43:31 +0000 Subject: [PATCH 14/19] fix(gateway): bound serialized request ids at admission --- src/gateway.rs | 14 +++ src/gateway/http_server.rs | 9 ++ src/gateway/pinned_tests.rs | 180 ++++++++++++++++++++++++++++++++++++ 3 files changed, 203 insertions(+) diff --git a/src/gateway.rs b/src/gateway.rs index a5e9dc5e..2bb104d5 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -34,6 +34,7 @@ const LEASE: Duration = Duration::from_secs(15); const DEFAULT_CLIENT_REQUEST_TIMEOUT: Duration = Duration::from_secs(300); const MAX_REPLAY: usize = 8 * 1024 * 1024; const MAX_HTTP_FRAME: usize = 1024 * 1024; +const MAX_REQUEST_ID_BYTES: usize = 4 * 1024; const MAX_QUEUE: usize = 4096; const MAX_PENDING_SHARED: usize = 128; const MAX_PENDING_PER_ATTACHMENT: usize = 32; @@ -1189,6 +1190,13 @@ struct Actor { current_turn_start: Option, replay_complete: bool, } +fn validate_request_id(id: &Value) -> Result<(), Failure> { + if id.to_string().len() > MAX_REQUEST_ID_BYTES { + return Err(Failure::bad("ACP request id exceeds gateway limit")); + } + Ok(()) +} + impl Actor { fn new( id: String, @@ -2422,6 +2430,9 @@ impl Actor { if !message.is_object() || !message["params"].is_object() || message["jsonrpc"] != "2.0" { return Err(Failure::bad("invalid ACP message")); } + if let Some(id) = message.get("id") { + validate_request_id(id)?; + } if let Some(session) = message["params"].get("sessionId") && session != &Value::String(self.id.clone()) { @@ -2761,6 +2772,7 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + validate_request_id(&request_id)?; Some(self.prepare_startup( &id, elicitation_form, @@ -2893,6 +2905,7 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + validate_request_id(&request_id)?; let prepared = self.prepare_startup( &id, elicitation_form, @@ -2912,6 +2925,7 @@ impl Actor { .get("id") .cloned() .ok_or_else(|| Failure::bad("session startup requires a request id"))?; + validate_request_id(&request_id)?; if let Some(pinned) = &mut self.pinned { pinned.waiting_startups.push(WaitingStartup { attachment: id.clone(), diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index d7a495a7..2aa3d710 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -138,6 +138,9 @@ impl Connection { .as_str() .ok_or_else(|| Failure::bad("ACP method required"))? .to_owned(); + if let Some(id) = message.get("id") { + validate_request_id(id)?; + } if method == "initialize" { if self.initialize.is_some() { return Err(Failure::conflict("connection already initialized")); @@ -718,6 +721,12 @@ impl Connection { continue; } let id = message.get("id").cloned(); + if id + .as_ref() + .is_some_and(|id| validate_request_id(id).is_err()) + { + return Err(channel.tx.fail("ACP request id exceeds gateway limit")); + } let response = match self.request(message, &channel, &charged_frame).await { Ok(Some(result)) => id.map(|id| { object([("jsonrpc", "2.0".into()), ("id", id), ("result", result)]) diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 593982c9..9594d20a 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -7555,3 +7555,183 @@ fn oversized_live_update_exceeding_remaining_queue_budget_reports_frame_too_larg assert_eq!(err.data()["reason"], "frame_too_large"); assert_eq!(err.data()["terminal"], false); } + +#[tokio::test] +async fn over_budget_request_id_rejected_at_admission_without_oversized_error_or_retiring_attachment() + { + use agent_client_protocol::{BoundedChannel, ChannelLimits, ConnectTo, TransportFrame}; + use futures_util::StreamExt; + + // 1) Actor rejects over-budget IDs on Send and Attach before forwarding, keeping the + // attachment alive; a max-budget admitted ID still fits in the frame_too_large fallback + // error envelope without retiring the attachment. + let mut actor = default_actor("id-budget", Duration::from_secs(60)); + actor.session_result = Some(json!({"sessionId": "id-budget", "configOptions": []})); + let (writes, mut child_rx) = mpsc::channel(8); + + let huge_id = "k".repeat(MAX_HTTP_FRAME - 160); + let attach_err = actor + .command( + Request::Attach { + session: "id-budget".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({ + "jsonrpc": "2.0", + "id": huge_id, + "method": "session/resume", + "params": {"sessionId": "id-budget"} + })), + elicitation_form: true, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(attach_err.2, "protocol"); + + let att = actor + .command( + Request::Attach { + session: "id-budget".into(), + replay: ReplayMode::None, + replace: false, + startup: Some(json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/resume", + "params": {"sessionId": "id-budget"} + })), + elicitation_form: true, + }, + &writes, + ) + .unwrap()["attachment"] + .as_str() + .unwrap() + .to_owned(); + + let send_err = actor + .command( + Request::Send { + session: "id-budget".into(), + attachment: att.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": huge_id, + "method": "kit/session/status", + "params": {"sessionId": "id-budget"} + }), + charge: None, + }, + &writes, + ) + .unwrap_err(); + assert_eq!(send_err.2, "protocol"); + assert!(child_rx.try_recv().is_err()); + assert!(actor.attachments[&att].failed.is_none()); + + // Exact max-budget serialized ID (`"..."` = MAX_REQUEST_ID_BYTES) is admitted and its + // oversized-response fallback error stays well within MAX_HTTP_FRAME without retiring att. + let max_id = "m".repeat(MAX_REQUEST_ID_BYTES - 2); + assert_eq!( + Value::String(max_id.clone()).to_string().len(), + MAX_REQUEST_ID_BYTES + ); + actor + .command( + Request::Send { + session: "id-budget".into(), + attachment: att.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": max_id, + "method": "kit/session/status", + "params": {"sessionId": "id-budget"} + }), + charge: None, + }, + &writes, + ) + .unwrap(); + let child_id = child_rx.try_recv().unwrap().message["id"].clone(); + actor.output(json!({ + "jsonrpc": "2.0", + "id": child_id, + "result": {"pad": "z".repeat(MAX_HTTP_FRAME + 1024)} + })); + assert!( + actor.attachments[&att].failed.is_none(), + "frame_too_large fallback error for admitted max-budget ID must not retire the attachment" + ); + let polled = actor + .command( + Request::Poll { + session: "id-budget".into(), + attachment: att, + cursor: 0, + }, + &writes, + ) + .unwrap(); + let fallback = polled["events"] + .as_array() + .unwrap() + .iter() + .find(|ev| ev["message"]["id"] == max_id) + .expect("fallback error must echo admitted max-budget ID"); + assert_eq!(fallback["message"]["error"]["code"], -32603); + assert_eq!( + fallback["message"]["error"]["data"]["reason"], + "frame_too_large" + ); + assert_eq!(fallback["message"]["error"]["data"]["terminal"], false); + assert!(fallback["message"].to_string().len() <= MAX_HTTP_FRAME); + + // 2) HTTP Connection::run rejects an over-budget ID at admission without emitting an + // oversized JSON-RPC error echoing that ID. + let directory = tempfile::tempdir().unwrap(); + let token = directory.path().join("token"); + std::fs::write(&token, "test-token").unwrap(); + let gateway = Arc::new(Gateway { + stopping: AtomicBool::new(false), + token: BearerToken::load(&token).unwrap(), + roots: Vec::new(), + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, + sessions: Mutex::new(HashMap::new()), + }); + let connection = http_server::Connection::new(gateway); + let (mut peer, endpoint) = BoundedChannel::duplex(ChannelLimits::default()).unwrap(); + let frame_str = json!({ + "jsonrpc": "2.0", + "id": huge_id, + "method": "initialize", + "params": { + "protocolVersion": 2, + "info": {"name": "huge-id", "version": "1"}, + "capabilities": {} + } + }) + .to_string(); + assert!( + frame_str.len() <= MAX_HTTP_FRAME, + "inbound request itself fits within MAX_HTTP_FRAME" + ); + peer.tx + .try_send(TransportFrame::parse_json(&frame_str)) + .unwrap(); + let error = tokio::time::timeout(Duration::from_secs(5), connection.connect_to(endpoint)) + .await + .unwrap() + .unwrap_err(); + assert!( + error.to_string().contains("request id exceeds"), + "expected over-budget ID rejection error, got: {error}" + ); + assert!( + futures_util::FutureExt::now_or_never(peer.rx.next()) + .flatten() + .is_none(), + "connection must not emit an oversized JSON-RPC error echoing the over-budget ID" + ); +} From 84afa90455aa96d6aaee34105a3173e9da68f6c3 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 13:12:13 +0000 Subject: [PATCH 15/19] fix(gateway): return correlated error for fitting over-budget request ids --- docs/reference/gateway-protocol.md | 2 +- src/gateway/http_server.rs | 16 ++--- src/gateway/pinned_tests.rs | 100 ++++++++++++++++++++++------- 3 files changed, 86 insertions(+), 32 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 6c22d218..50b7c606 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -149,7 +149,7 @@ For native stdio and Streamable HTTP entries, additive update semantics, and the ## Transport limits - Healthy HTTP connections have no cumulative output cap. The SDK instead limits each core direction to 16 MiB / 256 frames and each connection's HTTP egress to 4 MiB / 64 frames. Admission saturation fails explicitly and can terminate the connection; it does not silently drop output while claiming the stream is complete. Accepted resident work is not cancelled by transport failure. There is no delivery acknowledgement, and HTTP body handoff does not prove peer consumption. The bridge's stdin mailbox holds at most 16 capped frames; each frame is limited to 1 MiB before parsing. -- The server admits at most 64 connections, 32 concurrent SDK POSTs, and 8 MiB of aggregate body reservations. Each connection permits at most 256 pending routes, 64 session registrations, and 65 streams. JSON-RPC batches are not supported. HTTP/core frames are limited to 1 MiB; SSE encoding and the client's 1 MiB parser limits can reject a near-limit frame. The bundled client independently caps HTTP reservations at 64 MiB / 128 slots, pending RPCs at 128, each POST lane at 32, and SSE streams at 8. Transport exhaustion is terminal rather than an unbounded wait. The gateway admits at most 32 concurrent POST/DELETE operations. +- The server admits at most 64 connections, 32 concurrent SDK POSTs, and 8 MiB of aggregate body reservations. Each connection permits at most 256 pending routes, 64 session registrations, and 65 streams. JSON-RPC batches are not supported. HTTP/core frames are limited to 1 MiB; SSE encoding and the client's 1 MiB parser limits can reject a near-limit frame. Serialized JSON-RPC request IDs are capped at 4 KiB at admission so correlated error envelopes (including `frame_too_large` fallbacks) always fit within the 1 MiB frame limit; over-budget IDs are rejected before forwarding with a correlated JSON-RPC error when the encoded rejection fits within 1 MiB and fail the transport otherwise. The bundled client independently caps HTTP reservations at 64 MiB / 128 slots, pending RPCs at 128, each POST lane at 32, and SSE streams at 8. Transport exhaustion is terminal rather than an unbounded wait. The gateway admits at most 32 concurrent POST/DELETE operations. - These bounds exclude allocator overhead, transient JSON conversion, arbitrary application state, and HTTP/TLS/socket buffers. They are not a hard process-memory ceiling or a denial-of-service-hardening claim. The bounded transport supports HTTP/SSE, not WebSocket upgrades. SSE has no replay cursor: reopening a stream alone cannot recover lost events. Recovery uses fresh initialization and session-level resume, not SSE event IDs. There is no idle connection expiration or body-read deadline: disconnected peers that do not DELETE or otherwise terminate their transport can retain connection slots. Slot exhaustion may require restarting the gateway; do not expose it to untrusted clients. HTTP POST bodies are limited to 1 MiB, including streamed bodies. Supervisor queues and pending child requests are bounded. Child stdout frames are limited to 8 MiB before JSON parsing; oversized or malformed frames stop that child. There is no fixed resident-session count ceiling; provision host resources independently of transport limits. diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 2aa3d710..11396263 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -721,12 +721,6 @@ impl Connection { continue; } let id = message.get("id").cloned(); - if id - .as_ref() - .is_some_and(|id| validate_request_id(id).is_err()) - { - return Err(channel.tx.fail("ACP request id exceeds gateway limit")); - } let response = match self.request(message, &channel, &charged_frame).await { Ok(Some(result)) => id.map(|id| { object([("jsonrpc", "2.0".into()), ("id", id), ("result", result)]) @@ -739,7 +733,7 @@ impl Connection { let Some(id) = id else { return Err(channel.tx.fail(&error.1)); }; - Some(object([ + let response = object([ ("jsonrpc", "2.0".into()), ("id", id), ( @@ -747,10 +741,14 @@ impl Connection { object([ ("code", error.jsonrpc_code().into()), ("data", error.data()), - ("message", error.1.into()), + ("message", error.1.clone().into()), ]), ), - ])) + ]); + if response.to_string().len() > MAX_HTTP_FRAME { + return Err(channel.tx.fail(&error.1)); + } + Some(response) } }; self.flush_with_response(&channel, response).await?; diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index 9594d20a..fa0b8ac3 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -7687,35 +7687,91 @@ async fn over_budget_request_id_rejected_at_admission_without_oversized_error_or assert_eq!(fallback["message"]["error"]["data"]["terminal"], false); assert!(fallback["message"].to_string().len() <= MAX_HTTP_FRAME); - // 2) HTTP Connection::run rejects an over-budget ID at admission without emitting an - // oversized JSON-RPC error echoing that ID. - let directory = tempfile::tempdir().unwrap(); - let token = directory.path().join("token"); - std::fs::write(&token, "test-token").unwrap(); - let gateway = Arc::new(Gateway { - stopping: AtomicBool::new(false), - token: BearerToken::load(&token).unwrap(), - roots: Vec::new(), - pinned_session: None, - client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, - sessions: Mutex::new(HashMap::new()), - }); - let connection = http_server::Connection::new(gateway); + // 2) HTTP Connection::run rejects a moderately over-budget ID (> 4 KiB) with a normal + // correlated JSON-RPC error when the encoded rejection fits within 1 MiB, without + // dropping unrelated session controls on the same connection; only when the encoded + // rejection itself would exceed 1 MiB does it fail the transport without emitting a frame. + let harness = PinnedHarness::default_mode(Duration::from_secs(60)).await; + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'id-keepalive','configOptions':[]}}) + elif m == 'kit/session/status': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + harness.child_source("id-keepalive", source, &[]).await; + + let conn = harness.connect("id-client").await; + let mut stream = conn.open_session_stream("id-keepalive").await; + assert_eq!( + conn.post(json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/resume", + "params": {"sessionId": "id-keepalive"} + })) + .await, + StatusCode::ACCEPTED + ); + let _ = stream.next_matching(|e| e["id"] == 1).await; + + let fitting_over_budget_id = "o".repeat(MAX_REQUEST_ID_BYTES + 256); + assert_eq!( + conn.post(json!({ + "jsonrpc": "2.0", + "id": fitting_over_budget_id, + "method": "kit/session/status", + "params": {"sessionId": "id-keepalive"} + })) + .await, + StatusCode::ACCEPTED + ); + let correlated_err = stream + .next_matching(|e| e["id"] == fitting_over_budget_id) + .await; + assert_eq!(correlated_err["error"]["code"], -32000); + assert_eq!(correlated_err["error"]["data"]["reason"], "protocol"); + + // Connection and session control remain intact after the correlated rejection! + assert_eq!( + conn.post(json!({ + "jsonrpc": "2.0", + "id": "still-alive", + "method": "kit/session/status", + "params": {"sessionId": "id-keepalive"} + })) + .await, + StatusCode::ACCEPTED + ); + let alive = stream.next_matching(|e| e["id"] == "still-alive").await; + assert_eq!(alive["result"]["settled"], true); + let _ = conn.delete().await; + + // 3) When the over-budget ID is so large that the encoded JSON-RPC rejection itself would + // exceed MAX_HTTP_FRAME, Connection::run fails the transport without emitting an oversized + // error frame echoing that ID. + let connection = http_server::Connection::new(harness.gateway.clone()); let (mut peer, endpoint) = BoundedChannel::duplex(ChannelLimits::default()).unwrap(); + let max_inbound_id = "k".repeat(MAX_HTTP_FRAME - 80); let frame_str = json!({ "jsonrpc": "2.0", - "id": huge_id, - "method": "initialize", - "params": { - "protocolVersion": 2, - "info": {"name": "huge-id", "version": "1"}, - "capabilities": {} - } + "id": max_inbound_id, + "method": "session/list", + "params": {} }) .to_string(); assert!( frame_str.len() <= MAX_HTTP_FRAME, - "inbound request itself fits within MAX_HTTP_FRAME" + "inbound request itself fits within MAX_HTTP_FRAME (len={})", + frame_str.len() ); peer.tx .try_send(TransportFrame::parse_json(&frame_str)) From 4c43f5079f3a8a196fbd654bb6c8de75b52a2119 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 13:33:40 +0000 Subject: [PATCH 16/19] fix(gateway): mark request_id_too_large rejection non-terminal for bundled bridge --- docs/reference/gateway-protocol.md | 2 +- src/gateway.rs | 12 +- src/gateway/http_client/recovery/tests.rs | 171 ++++++++++++++++++++++ src/gateway/pinned_tests.rs | 12 +- 4 files changed, 191 insertions(+), 6 deletions(-) diff --git a/docs/reference/gateway-protocol.md b/docs/reference/gateway-protocol.md index 50b7c606..7fd4d29b 100644 --- a/docs/reference/gateway-protocol.md +++ b/docs/reference/gateway-protocol.md @@ -149,7 +149,7 @@ For native stdio and Streamable HTTP entries, additive update semantics, and the ## Transport limits - Healthy HTTP connections have no cumulative output cap. The SDK instead limits each core direction to 16 MiB / 256 frames and each connection's HTTP egress to 4 MiB / 64 frames. Admission saturation fails explicitly and can terminate the connection; it does not silently drop output while claiming the stream is complete. Accepted resident work is not cancelled by transport failure. There is no delivery acknowledgement, and HTTP body handoff does not prove peer consumption. The bridge's stdin mailbox holds at most 16 capped frames; each frame is limited to 1 MiB before parsing. -- The server admits at most 64 connections, 32 concurrent SDK POSTs, and 8 MiB of aggregate body reservations. Each connection permits at most 256 pending routes, 64 session registrations, and 65 streams. JSON-RPC batches are not supported. HTTP/core frames are limited to 1 MiB; SSE encoding and the client's 1 MiB parser limits can reject a near-limit frame. Serialized JSON-RPC request IDs are capped at 4 KiB at admission so correlated error envelopes (including `frame_too_large` fallbacks) always fit within the 1 MiB frame limit; over-budget IDs are rejected before forwarding with a correlated JSON-RPC error when the encoded rejection fits within 1 MiB and fail the transport otherwise. The bundled client independently caps HTTP reservations at 64 MiB / 128 slots, pending RPCs at 128, each POST lane at 32, and SSE streams at 8. Transport exhaustion is terminal rather than an unbounded wait. The gateway admits at most 32 concurrent POST/DELETE operations. +- The server admits at most 64 connections, 32 concurrent SDK POSTs, and 8 MiB of aggregate body reservations. Each connection permits at most 256 pending routes, 64 session registrations, and 65 streams. JSON-RPC batches are not supported. HTTP/core frames are limited to 1 MiB; SSE encoding and the client's 1 MiB parser limits can reject a near-limit frame. Serialized JSON-RPC request IDs are capped at 4 KiB at admission so correlated error envelopes (including `frame_too_large` fallbacks) always fit within the 1 MiB frame limit; over-budget IDs are rejected before forwarding with a correlated non-terminal JSON-RPC error (`data.reason = "request_id_too_large"`, `terminal = false`) when the encoded rejection fits within 1 MiB and fail the transport otherwise. The bundled client independently caps HTTP reservations at 64 MiB / 128 slots, pending RPCs at 128, each POST lane at 32, and SSE streams at 8. Transport exhaustion is terminal rather than an unbounded wait. The gateway admits at most 32 concurrent POST/DELETE operations. - These bounds exclude allocator overhead, transient JSON conversion, arbitrary application state, and HTTP/TLS/socket buffers. They are not a hard process-memory ceiling or a denial-of-service-hardening claim. The bounded transport supports HTTP/SSE, not WebSocket upgrades. SSE has no replay cursor: reopening a stream alone cannot recover lost events. Recovery uses fresh initialization and session-level resume, not SSE event IDs. There is no idle connection expiration or body-read deadline: disconnected peers that do not DELETE or otherwise terminate their transport can retain connection slots. Slot exhaustion may require restarting the gateway; do not expose it to untrusted clients. HTTP POST bodies are limited to 1 MiB, including streamed bodies. Supervisor queues and pending child requests are bounded. Child stdout frames are limited to 8 MiB before JSON parsing; oversized or malformed frames stop that child. There is no fixed resident-session count ceiling; provision host resources independently of transport limits. diff --git a/src/gateway.rs b/src/gateway.rs index 2bb104d5..459cd43e 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -437,7 +437,11 @@ impl Failure { ("reason", self.2.into()), ( "terminal", - (!matches!(self.2, "unavailable" | "frame_too_large")).into(), + (!matches!( + self.2, + "unavailable" | "frame_too_large" | "request_id_too_large" + )) + .into(), ), ]) } @@ -1192,7 +1196,11 @@ struct Actor { } fn validate_request_id(id: &Value) -> Result<(), Failure> { if id.to_string().len() > MAX_REQUEST_ID_BYTES { - return Err(Failure::bad("ACP request id exceeds gateway limit")); + return Err(Failure( + StatusCode::BAD_REQUEST, + "ACP request id exceeds gateway limit".into(), + "request_id_too_large", + )); } Ok(()) } diff --git a/src/gateway/http_client/recovery/tests.rs b/src/gateway/http_client/recovery/tests.rs index 136fd63e..8d1e8775 100644 --- a/src/gateway/http_client/recovery/tests.rs +++ b/src/gateway/http_client/recovery/tests.rs @@ -63,6 +63,12 @@ fn terminal_classification_uses_structured_metadata_only() { ), None ); + assert_eq!( + terminal_reason( + &json!({"error":{"data":{"terminal":false,"reason":"request_id_too_large"}}}) + ), + None + ); assert_eq!( terminal_reason(&json!({"error":{"data":{"terminal":true,"reason":"root_denied"}}})), Some("root_denied") @@ -852,3 +858,168 @@ for line in sys.stdin: result2.unwrap(); server_task.abort(); } + +#[tokio::test] +async fn bundled_bridge_stays_alive_and_completes_other_pending_after_request_id_too_large() { + use super::super::super::{ + Actor, BearerToken, DEFAULT_CLIENT_REQUEST_TIMEOUT, Entry, Gateway, MAX_REQUEST_ID_BYTES, + router, + }; + use std::{ + collections::HashMap, + process::Stdio, + sync::{Arc, atomic::AtomicBool}, + }; + use tokio::sync::{Mutex, watch}; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let mut credential = tempfile::NamedTempFile::new().unwrap(); + writeln!(credential, "test-token").unwrap(); + let token_path = credential.path().to_owned(); + let gateway = Arc::new(Gateway { + stopping: AtomicBool::new(false), + token: BearerToken::load(&token_path).unwrap(), + roots: vec![root.clone()], + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, + sessions: Mutex::new(HashMap::new()), + }); + + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +held = [] +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'bridge-id-limit','configOptions':[]}}) + elif m == 'kit/session/status': + if req['params'].get('hold'): + held.append(req['id']) + continue + if req['params'].get('release'): + for rid in held: + emit({'jsonrpc':'2.0','id':rid,'result':{'heldReleased':True}}) + held.clear() + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", source]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let actor = Actor::new( + "bridge-id-limit".into(), + root.clone(), + false, + false, + DEFAULT_CLIENT_REQUEST_TIMEOUT, + ); + let (actor_tx, actor_rx) = mpsc::channel(32); + let (completion, stopped) = watch::channel(()); + tokio::spawn(async move { + actor.run(child, actor_rx).await; + drop(completion); + }); + gateway.sessions.lock().await.insert( + "bridge-id-limit".into(), + Entry { + root: root.clone(), + sender: actor_tx, + stopped, + }, + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let app = router(gateway).unwrap(); + let server_task = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let remote = super::super::super::Remote { + url: format!("http://{address}"), + credential_file: token_path, + session: Some("bridge-id-limit".into()), + no_replay: false, + }; + let (send, lines) = mpsc::channel(16); + let (writer, mut output) = output_pipe(); + let over_budget_id = "o".repeat(MAX_REQUEST_ID_BYTES + 256); + let scenario = async { + send.send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + until_id(&mut output, json!(1)).await; + send.send(frame(2, "session/new", json!({"cwd":root,"mcpServers":[]}))) + .await + .unwrap(); + until_kind(&mut output, "commit").await; + until_id(&mut output, json!(2)).await; + + // Keep an unrelated request in flight across the over-budget ID rejection. + send.send(frame( + 3, + "kit/session/status", + json!({"sessionId":"bridge-id-limit","hold":true}), + )) + .await + .unwrap(); + send.send(( + Instant::now(), + Ok(json!({ + "jsonrpc": "2.0", + "id": over_budget_id, + "method": "kit/session/status", + "params": {"sessionId": "bridge-id-limit"} + }) + .to_string()), + )) + .await + .unwrap(); + let rejected = until_id(&mut output, json!(over_budget_id)).await; + assert_eq!(rejected["error"]["code"], -32000); + assert_eq!(rejected["error"]["data"]["reason"], "request_id_too_large"); + assert_eq!(rejected["error"]["data"]["terminal"], false); + + // Bridge stays alive: releasing the unrelated in-flight request completes it normally + // instead of failing it with `outcome_unknown`. + send.send(frame( + 4, + "kit/session/status", + json!({"sessionId":"bridge-id-limit","release":true}), + )) + .await + .unwrap(); + let mut saw_held = false; + let mut saw_release = false; + while !saw_held || !saw_release { + let msg = output.recv().await.unwrap(); + if msg["id"] == 3 { + assert_eq!(msg["result"]["heldReleased"], true); + saw_held = true; + } + if msg["id"] == 4 { + assert_eq!(msg["result"]["settled"], true); + saw_release = true; + } + } + drop(send); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(15), async { + tokio::join!(run(remote, root.clone(), lines, writer), scenario) + }) + .await + .unwrap(); + result.unwrap(); + server_task.abort(); +} diff --git a/src/gateway/pinned_tests.rs b/src/gateway/pinned_tests.rs index fa0b8ac3..0978423e 100644 --- a/src/gateway/pinned_tests.rs +++ b/src/gateway/pinned_tests.rs @@ -7587,7 +7587,8 @@ async fn over_budget_request_id_rejected_at_admission_without_oversized_error_or &writes, ) .unwrap_err(); - assert_eq!(attach_err.2, "protocol"); + assert_eq!(attach_err.2, "request_id_too_large"); + assert_eq!(attach_err.data()["terminal"], false); let att = actor .command( @@ -7626,7 +7627,8 @@ async fn over_budget_request_id_rejected_at_admission_without_oversized_error_or &writes, ) .unwrap_err(); - assert_eq!(send_err.2, "protocol"); + assert_eq!(send_err.2, "request_id_too_large"); + assert_eq!(send_err.data()["terminal"], false); assert!(child_rx.try_recv().is_err()); assert!(actor.attachments[&att].failed.is_none()); @@ -7738,7 +7740,11 @@ for line in sys.stdin: .next_matching(|e| e["id"] == fitting_over_budget_id) .await; assert_eq!(correlated_err["error"]["code"], -32000); - assert_eq!(correlated_err["error"]["data"]["reason"], "protocol"); + assert_eq!( + correlated_err["error"]["data"]["reason"], + "request_id_too_large" + ); + assert_eq!(correlated_err["error"]["data"]["terminal"], false); // Connection and session control remain intact after the correlated rejection! assert_eq!( From 269e583139253597fc7259ae8e174e9c8aee5f82 Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 13:52:12 +0000 Subject: [PATCH 17/19] fix(gateway): validate request id budget before bridge startup state changes --- src/gateway.rs | 16 ++ src/gateway/http_client/recovery.rs | 14 ++ src/gateway/http_client/recovery/tests.rs | 191 ++++++++++++++++++++++ src/gateway/http_server.rs | 16 +- 4 files changed, 223 insertions(+), 14 deletions(-) diff --git a/src/gateway.rs b/src/gateway.rs index 459cd43e..3a862284 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -1205,6 +1205,22 @@ fn validate_request_id(id: &Value) -> Result<(), Failure> { Ok(()) } +fn bounded_error_response(id: Value, error: &Failure) -> Option { + let response = object([ + ("jsonrpc", "2.0".into()), + ("id", id), + ( + "error", + object([ + ("code", error.jsonrpc_code().into()), + ("data", error.data()), + ("message", error.1.clone().into()), + ]), + ), + ]); + (response.to_string().len() <= MAX_HTTP_FRAME).then_some(response) +} + impl Actor { fn new( id: String, diff --git a/src/gateway/http_client/recovery.rs b/src/gateway/http_client/recovery.rs index 2b12fa47..c1c70c0b 100644 --- a/src/gateway/http_client/recovery.rs +++ b/src/gateway/http_client/recovery.rs @@ -369,6 +369,20 @@ pub(super) async fn run( reject(&mut output, &value, "not_sent", &session)?; continue; } + if value.get("method").is_some() + && let Some(id) = value.get("id") + && let Err(error) = super::super::validate_request_id(id) + { + if let Some(response) = + super::super::bounded_error_response(id.clone(), &error) + { + emit(&mut output, &response)?; + continue; + } + terminal = Some(error.1); + lost = true; + continue; + } if phase != "live" || resumed.is_some() || gate.is_some_and(|gate| admitted <= gate) diff --git a/src/gateway/http_client/recovery/tests.rs b/src/gateway/http_client/recovery/tests.rs index 8d1e8775..a374d280 100644 --- a/src/gateway/http_client/recovery/tests.rs +++ b/src/gateway/http_client/recovery/tests.rs @@ -1023,3 +1023,194 @@ for line in sys.stdin: result.unwrap(); server_task.abort(); } + +#[tokio::test] +async fn bundled_bridge_keeps_initialize_and_explicit_attach_retryable_after_request_id_too_large() +{ + use super::super::super::{ + Actor, BearerToken, DEFAULT_CLIENT_REQUEST_TIMEOUT, Entry, Gateway, MAX_HTTP_FRAME, + MAX_REQUEST_ID_BYTES, router, + }; + use std::{ + collections::HashMap, + process::Stdio, + sync::{Arc, atomic::AtomicBool}, + }; + use tokio::sync::{Mutex, watch}; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let mut credential = tempfile::NamedTempFile::new().unwrap(); + writeln!(credential, "test-token").unwrap(); + let token_path = credential.path().to_owned(); + let gateway = Arc::new(Gateway { + stopping: AtomicBool::new(false), + token: BearerToken::load(&token_path).unwrap(), + roots: vec![root.clone()], + pinned_session: None, + client_request_timeout: DEFAULT_CLIENT_REQUEST_TIMEOUT, + sessions: Mutex::new(HashMap::new()), + }); + + let source = r#" +import sys, json +def emit(v): print(json.dumps(v), flush=True) +for line in sys.stdin: + req = json.loads(line) + m = req['method'] + if m == 'initialize': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'protocolVersion':2,'info':{'name':'fake','version':'1'},'capabilities':{}}}) + elif m in ('session/new', 'session/resume'): + emit({'jsonrpc':'2.0','id':req['id'],'result':{'sessionId':'bridge-retry','configOptions':[]}}) + elif m == 'kit/session/status': + emit({'jsonrpc':'2.0','id':req['id'],'result':{'settled':True}}) + elif 'id' in req: + emit({'jsonrpc':'2.0','id':req['id'],'result':{}}) +"#; + let child = tokio::process::Command::new("python3") + .args(["-u", "-c", source]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let actor = Actor::new( + "bridge-retry".into(), + root.clone(), + false, + false, + DEFAULT_CLIENT_REQUEST_TIMEOUT, + ); + let (actor_tx, actor_rx) = mpsc::channel(32); + let (completion, stopped) = watch::channel(()); + tokio::spawn(async move { + actor.run(child, actor_rx).await; + drop(completion); + }); + gateway.sessions.lock().await.insert( + "bridge-retry".into(), + Entry { + root: root.clone(), + sender: actor_tx, + stopped, + }, + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let app = router(gateway).unwrap(); + let server_task = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let remote = super::super::super::Remote { + url: format!("http://{address}"), + credential_file: token_path, + session: Some("bridge-retry".into()), + no_replay: false, + }; + let (send, lines) = mpsc::channel(16); + let (writer, mut output) = output_pipe(); + let over_budget_id = "o".repeat(MAX_REQUEST_ID_BYTES + 256); + let unfitting_id = "u".repeat(MAX_HTTP_FRAME - 80); + let scenario = async { + // 1) Over-budget ID on initialize returns non-terminal rejection and leaves initialize retryable. + send.send(( + Instant::now(), + Ok(json!({ + "jsonrpc": "2.0", + "id": over_budget_id, + "method": "initialize", + "params": initialize_params().unwrap() + }) + .to_string()), + )) + .await + .unwrap(); + let init_err = until_id(&mut output, json!(over_budget_id)).await; + assert_eq!(init_err["error"]["data"]["reason"], "request_id_too_large"); + assert_eq!(init_err["error"]["data"]["terminal"], false); + + send.send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + let init_ok = until_id(&mut output, json!(1)).await; + assert!(init_ok.get("result").is_some()); + + // 2) Over-budget ID on the first explicit --remote-session attach returns non-terminal + // rejection without rewriting or terminating the bridge, so a valid retry attaches cleanly. + send.send(( + Instant::now(), + Ok(json!({ + "jsonrpc": "2.0", + "id": over_budget_id, + "method": "session/new", + "params": {"cwd": root, "mcpServers": []} + }) + .to_string()), + )) + .await + .unwrap(); + let attach_err = until_id(&mut output, json!(over_budget_id)).await; + assert_eq!( + attach_err["error"]["data"]["reason"], + "request_id_too_large" + ); + assert_eq!(attach_err["error"]["data"]["terminal"], false); + + send.send(frame(2, "session/new", json!({"cwd":root,"mcpServers":[]}))) + .await + .unwrap(); + until_kind(&mut output, "commit").await; + let attach_ok = until_id(&mut output, json!(2)).await; + assert!(attach_ok.get("result").is_some()); + + send.send(frame( + 3, + "kit/session/status", + json!({"sessionId":"bridge-retry"}), + )) + .await + .unwrap(); + let status = until_id(&mut output, json!(3)).await; + assert_eq!(status["result"]["settled"], true); + + // 3) An over-budget ID whose correlated rejection exceeds MAX_HTTP_FRAME fails the bridge + // cleanly without emitting an oversized error frame echoing that ID. + send.send(( + Instant::now(), + Ok(json!({ + "jsonrpc": "2.0", + "id": unfitting_id, + "method": "session/list", + "params": {} + }) + .to_string()), + )) + .await + .unwrap(); + let failed = until_kind(&mut output, "failed").await; + assert!( + failed["params"]["update"]["description"] + .as_str() + .unwrap() + .contains("request id exceeds") + ); + assert!( + output.try_recv().is_err(), + "must not emit an oversized error frame echoing the unfitting ID" + ); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(15), async { + tokio::join!(run(remote, root.clone(), lines, writer), scenario) + }) + .await + .unwrap(); + let err = result.unwrap_err().to_string(); + assert!( + err.contains("request id exceeds"), + "expected transport failure for unfitting ID, got: {err}" + ); + server_task.abort(); +} diff --git a/src/gateway/http_server.rs b/src/gateway/http_server.rs index 11396263..6b9b8d92 100644 --- a/src/gateway/http_server.rs +++ b/src/gateway/http_server.rs @@ -733,21 +733,9 @@ impl Connection { let Some(id) = id else { return Err(channel.tx.fail(&error.1)); }; - let response = object([ - ("jsonrpc", "2.0".into()), - ("id", id), - ( - "error", - object([ - ("code", error.jsonrpc_code().into()), - ("data", error.data()), - ("message", error.1.clone().into()), - ]), - ), - ]); - if response.to_string().len() > MAX_HTTP_FRAME { + let Some(response) = bounded_error_response(id, &error) else { return Err(channel.tx.fail(&error.1)); - } + }; Some(response) } }; From b6bddbfc27e4f9ff007370fc730d1e5218e350bf Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 14:08:48 +0000 Subject: [PATCH 18/19] fix(gateway): apply request id bounds during bridge reconnect backoff --- src/gateway/http_client/recovery.rs | 60 +++++-- src/gateway/http_client/recovery/tests.rs | 190 +++++++++++++++++++++- 2 files changed, 231 insertions(+), 19 deletions(-) diff --git a/src/gateway/http_client/recovery.rs b/src/gateway/http_client/recovery.rs index c1c70c0b..062d6872 100644 --- a/src/gateway/http_client/recovery.rs +++ b/src/gateway/http_client/recovery.rs @@ -23,6 +23,27 @@ fn entries(value: &Value) -> &[Value] { fn reserved(id: &Value) -> bool { id.as_str().is_some_and(|id| id.starts_with(PREFIX)) } +enum IdCheck { + Ok, + Rejected, + Unfitting(String), +} + +fn check_request_id(output: &mut impl io::Write, value: &Value) -> Result { + if !value.is_array() + && value.get("method").is_some() + && let Some(id) = value.get("id") + && let Err(error) = super::super::validate_request_id(id) + { + if let Some(response) = super::super::bounded_error_response(id.clone(), &error) { + emit(output, &response)?; + return Ok(IdCheck::Rejected); + } + return Ok(IdCheck::Unfitting(error.1)); + } + Ok(IdCheck::Ok) +} + fn reject( output: &mut impl io::Write, value: &Value, @@ -271,19 +292,29 @@ pub(super) async fn run( let delay = tokio::time::sleep(Duration::from_millis(250u64 << (attempt - 1)).min(remaining)); tokio::pin!(delay); + let mut aborted = false; loop { let line = std::pin::pin!(lines.recv()); match select(&mut delay, line).await { Either::Left(_) => break, - Either::Right((Some((_, line)), _)) => reject( - &mut output, - &serde_json::from_str::(&line?)?, - "not_sent", - &session, - )?, + Either::Right((Some((_, line)), _)) => { + let value = serde_json::from_str::(&line?)?; + match check_request_id(&mut output, &value)? { + IdCheck::Ok => reject(&mut output, &value, "not_sent", &session)?, + IdCheck::Rejected => {} + IdCheck::Unfitting(message) => { + terminal = Some(message); + aborted = true; + break; + } + } + } Either::Right((None, _)) => return Ok(()), } } + if aborted { + continue; + } } let (mut channel, mut transport) = client(&remote)?.into_bounded_channel_and_future(); let remaining = recovery_start.map_or(Duration::from_secs(30), |start: Instant| { @@ -369,19 +400,14 @@ pub(super) async fn run( reject(&mut output, &value, "not_sent", &session)?; continue; } - if value.get("method").is_some() - && let Some(id) = value.get("id") - && let Err(error) = super::super::validate_request_id(id) - { - if let Some(response) = - super::super::bounded_error_response(id.clone(), &error) - { - emit(&mut output, &response)?; + match check_request_id(&mut output, &value)? { + IdCheck::Ok => {} + IdCheck::Rejected => continue, + IdCheck::Unfitting(message) => { + terminal = Some(message); + lost = true; continue; } - terminal = Some(error.1); - lost = true; - continue; } if phase != "live" || resumed.is_some() diff --git a/src/gateway/http_client/recovery/tests.rs b/src/gateway/http_client/recovery/tests.rs index a374d280..72ca94ce 100644 --- a/src/gateway/http_client/recovery/tests.rs +++ b/src/gateway/http_client/recovery/tests.rs @@ -1190,7 +1190,18 @@ for line in sys.stdin: )) .await .unwrap(); - let failed = until_kind(&mut output, "failed").await; + let mut failed = None; + while failed.is_none() { + let value = output.recv().await.unwrap(); + assert!( + value.get("id") != Some(&json!(unfitting_id)), + "must not emit an oversized error frame echoing the unfitting ID" + ); + if value["params"]["_meta"][META]["kind"] == "failed" { + failed = Some(value); + } + } + let failed = failed.unwrap(); assert!( failed["params"]["update"]["description"] .as_str() @@ -1199,7 +1210,7 @@ for line in sys.stdin: ); assert!( output.try_recv().is_err(), - "must not emit an oversized error frame echoing the unfitting ID" + "must not emit any frame after terminal failure" ); }; let (result, ()) = tokio::time::timeout(Duration::from_secs(15), async { @@ -1214,3 +1225,178 @@ for line in sys.stdin: ); server_task.abort(); } + +#[tokio::test] +async fn reconnect_backoff_applies_request_id_bounds_and_preserves_not_sent_for_valid_ids() { + use super::super::super::{MAX_HTTP_FRAME, MAX_REQUEST_ID_BYTES}; + + // 1) During reconnect backoff: valid-ID requests still get `not_sent`, while fitting + // over-budget IDs get `request_id_too_large` (`terminal: false`), and recovery still commits. + let mut server = Server::new(None).await; + let remote = server.remote.clone(); + let (send, lines) = mpsc::channel(16); + let (writer, mut output) = output_pipe(); + let over_budget_id = "o".repeat(MAX_REQUEST_ID_BYTES + 256); + let scenario = async { + send.send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + assert_eq!( + server.requests.recv().await.unwrap()["method"], + "initialize" + ); + until_id(&mut output, json!(1)).await; + send.send(frame( + 2, + "session/new", + json!({"cwd":"/local","mcpServers":[]}), + )) + .await + .unwrap(); + let new = server.requests.recv().await.unwrap(); + server.result( + &new, + json!({"sessionId":"durable","configOptions":[],"_meta":{"kit/gateway":{"attachment":"owner-1"}}}), + "", + ); + until_id(&mut output, json!(2)).await; + + // Drop transport so bridge enters reconnect backoff (250 ms delay after `begin`). + server.events.send(("*".into(), None)).unwrap(); + until_kind(&mut output, "begin").await; + + // Immediately send both a valid-ID request and a fitting over-budget-ID request during backoff. + send.send(frame( + 3, + "kit/session/status", + json!({"sessionId":"durable"}), + )) + .await + .unwrap(); + send.send(( + Instant::now(), + Ok(json!({ + "jsonrpc": "2.0", + "id": over_budget_id, + "method": "kit/session/status", + "params": {"sessionId": "durable"} + }) + .to_string()), + )) + .await + .unwrap(); + let valid_rejected = until_id(&mut output, json!(3)).await; + assert_eq!(valid_rejected["error"]["data"]["reason"], "not_sent"); + let over_rejected = until_id(&mut output, json!(over_budget_id)).await; + assert_eq!( + over_rejected["error"]["data"]["reason"], + "request_id_too_large" + ); + assert_eq!(over_rejected["error"]["data"]["terminal"], false); + + // Recovery still completes normally after backoff. + assert_eq!( + server.requests.recv().await.unwrap()["method"], + "initialize" + ); + let resume = server.requests.recv().await.unwrap(); + assert_eq!(resume["method"], "session/resume"); + server.update(json!({"sessionUpdate":"config_option_update","configOptions":[]})); + server.update(json!({"sessionUpdate":"state_update","state":"idle"})); + server.result( + &resume, + json!({"_meta":{"kit/gateway":{"attachment":"owner-2","historyAvailable":true,"stateSnapshot":true,"configSnapshot":true}}}), + "durable", + ); + until_kind(&mut output, "commit").await; + drop(send); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(8), async { + tokio::join!(run(remote, "/remote".into(), lines, writer), scenario) + }) + .await + .unwrap(); + result.unwrap(); + assert!(server.requests.try_recv().is_err()); + + // 2) An unfitting over-budget ID received during reconnect backoff fails the bridge cleanly + // without emitting an oversized error frame echoing that ID. + let mut server2 = Server::new(None).await; + let remote2 = server2.remote.clone(); + let (send2, lines2) = mpsc::channel(16); + let (writer2, mut output2) = output_pipe(); + let unfitting_id = "u".repeat(MAX_HTTP_FRAME - 80); + let scenario2 = async { + send2 + .send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + assert_eq!( + server2.requests.recv().await.unwrap()["method"], + "initialize" + ); + until_id(&mut output2, json!(1)).await; + send2 + .send(frame( + 2, + "session/new", + json!({"cwd":"/local","mcpServers":[]}), + )) + .await + .unwrap(); + let new = server2.requests.recv().await.unwrap(); + server2.result( + &new, + json!({"sessionId":"durable","configOptions":[],"_meta":{"kit/gateway":{"attachment":"owner-1"}}}), + "", + ); + until_id(&mut output2, json!(2)).await; + + server2.events.send(("*".into(), None)).unwrap(); + until_kind(&mut output2, "begin").await; + + send2 + .send(( + Instant::now(), + Ok(json!({ + "jsonrpc": "2.0", + "id": unfitting_id, + "method": "session/list", + "params": {} + }) + .to_string()), + )) + .await + .unwrap(); + let mut failed = None; + while failed.is_none() { + let value = output2.recv().await.unwrap(); + assert!( + value.get("id") != Some(&json!(unfitting_id)), + "backoff must not emit an oversized error frame echoing the unfitting ID" + ); + if value["params"]["_meta"][META]["kind"] == "failed" { + failed = Some(value); + } + } + let failed = failed.unwrap(); + assert!( + failed["params"]["update"]["description"] + .as_str() + .unwrap() + .contains("request id exceeds") + ); + assert!(output2.try_recv().is_err()); + }; + let (result2, ()) = tokio::time::timeout(Duration::from_secs(8), async { + tokio::join!(run(remote2, "/remote".into(), lines2, writer2), scenario2) + }) + .await + .unwrap(); + let err2 = result2.unwrap_err().to_string(); + assert!( + err2.contains("request id exceeds"), + "expected backoff transport failure for unfitting ID, got: {err2}" + ); + assert!(server2.requests.try_recv().is_err()); +} From 596701900c6a05d6ff8ea9129ba4b6d561e2f82d Mon Sep 17 00:00:00 2001 From: daniel Date: Sun, 29 Nov 2026 14:26:51 +0000 Subject: [PATCH 19/19] fix(gateway): bound batch request ids in bridge admission and backoff --- src/gateway/http_client/recovery.rs | 61 ++++++--- src/gateway/http_client/recovery/tests.rs | 148 ++++++++++++++++++++++ 2 files changed, 190 insertions(+), 19 deletions(-) diff --git a/src/gateway/http_client/recovery.rs b/src/gateway/http_client/recovery.rs index 062d6872..7877c23b 100644 --- a/src/gateway/http_client/recovery.rs +++ b/src/gateway/http_client/recovery.rs @@ -29,19 +29,42 @@ enum IdCheck { Unfitting(String), } -fn check_request_id(output: &mut impl io::Write, value: &Value) -> Result { - if !value.is_array() - && value.get("method").is_some() - && let Some(id) = value.get("id") - && let Err(error) = super::super::validate_request_id(id) - { - if let Some(response) = super::super::bounded_error_response(id.clone(), &error) { - emit(output, &response)?; - return Ok(IdCheck::Rejected); +fn check_request_id( + output: &mut impl io::Write, + value: &Value, + session: &Option, +) -> Result { + let mut has_over_budget = false; + for entry in entries(value) { + if entry.get("method").is_some() + && let Some(id) = entry.get("id") + && let Err(error) = super::super::validate_request_id(id) + { + if super::super::bounded_error_response(id.clone(), &error).is_none() { + return Ok(IdCheck::Unfitting(error.1)); + } + has_over_budget = true; + } + } + if !has_over_budget { + return Ok(IdCheck::Ok); + } + for entry in entries(value) { + if entry.get("method").is_some() + && let Some(id) = entry.get("id") + { + match super::super::validate_request_id(id) { + Err(error) => { + if let Some(response) = super::super::bounded_error_response(id.clone(), &error) + { + emit(output, &response)?; + } + } + Ok(()) => reject(output, entry, "not_sent", session)?, + } } - return Ok(IdCheck::Unfitting(error.1)); } - Ok(IdCheck::Ok) + Ok(IdCheck::Rejected) } fn reject( @@ -299,7 +322,7 @@ pub(super) async fn run( Either::Left(_) => break, Either::Right((Some((_, line)), _)) => { let value = serde_json::from_str::(&line?)?; - match check_request_id(&mut output, &value)? { + match check_request_id(&mut output, &value, &session)? { IdCheck::Ok => reject(&mut output, &value, "not_sent", &session)?, IdCheck::Rejected => {} IdCheck::Unfitting(message) => { @@ -394,13 +417,7 @@ pub(super) async fn run( } Event::Line(Some((admitted, line))) => { let value: Value = serde_json::from_str(&line?)?; - if value.is_array() { - // The upstream SDK treats a batch as malformed. Reject - // it locally before registering any pending IDs. - reject(&mut output, &value, "not_sent", &session)?; - continue; - } - match check_request_id(&mut output, &value)? { + match check_request_id(&mut output, &value, &session)? { IdCheck::Ok => {} IdCheck::Rejected => continue, IdCheck::Unfitting(message) => { @@ -409,6 +426,12 @@ pub(super) async fn run( continue; } } + if value.is_array() { + // The upstream SDK treats a batch as malformed. Reject + // it locally before registering any pending IDs. + reject(&mut output, &value, "not_sent", &session)?; + continue; + } if phase != "live" || resumed.is_some() || gate.is_some_and(|gate| admitted <= gate) diff --git a/src/gateway/http_client/recovery/tests.rs b/src/gateway/http_client/recovery/tests.rs index 72ca94ce..56f2a48d 100644 --- a/src/gateway/http_client/recovery/tests.rs +++ b/src/gateway/http_client/recovery/tests.rs @@ -1400,3 +1400,151 @@ async fn reconnect_backoff_applies_request_id_bounds_and_preserves_not_sent_for_ ); assert!(server2.requests.try_recv().is_err()); } + +#[tokio::test] +async fn batch_request_id_bounds_apply_in_active_and_backoff_loops() { + use super::super::super::{MAX_HTTP_FRAME, MAX_REQUEST_ID_BYTES}; + + let over_budget_id = "o".repeat(MAX_REQUEST_ID_BYTES + 256); + let unfitting_id = "u".repeat(MAX_HTTP_FRAME - 80); + + // 1) Active loop: batch with a valid ID + fitting over-budget ID rejects each entry cleanly + // without failing the bridge; batch with an unfitting ID fails cleanly without echoing it. + let mut server = Server::new(None).await; + let remote = server.remote.clone(); + let (send, lines) = mpsc::channel(16); + let (writer, mut output) = output_pipe(); + let scenario = async { + send.send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + assert_eq!( + server.requests.recv().await.unwrap()["method"], + "initialize" + ); + until_id(&mut output, json!(1)).await; + + send.send(( + Instant::now(), + Ok(json!([ + {"jsonrpc": "2.0", "id": 10, "method": "session/list", "params": {}}, + {"jsonrpc": "2.0", "id": over_budget_id, "method": "session/list", "params": {}} + ]) + .to_string()), + )) + .await + .unwrap(); + let valid_err = until_id(&mut output, json!(10)).await; + assert_eq!(valid_err["error"]["data"]["reason"], "not_sent"); + let over_err = until_id(&mut output, json!(over_budget_id)).await; + assert_eq!(over_err["error"]["data"]["reason"], "request_id_too_large"); + assert_eq!(over_err["error"]["data"]["terminal"], false); + + send.send(( + Instant::now(), + Ok(json!([ + {"jsonrpc": "2.0", "id": 11, "method": "session/list", "params": {}}, + {"jsonrpc": "2.0", "id": unfitting_id, "method": "session/list", "params": {}} + ]) + .to_string()), + )) + .await + .unwrap(); + while let Some(value) = output.recv().await { + assert!( + value.get("id") != Some(&json!(unfitting_id)) + && value.get("id") != Some(&json!(11)), + "unfitting batch must fail cleanly without emitting any entry: {value}" + ); + } + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(8), async { + tokio::join!(run(remote, "/remote".into(), lines, writer), scenario) + }) + .await + .unwrap(); + let err = result.unwrap_err().to_string(); + assert!( + err.contains("request id exceeds"), + "expected unfitting batch failure in active loop, got: {err}" + ); + assert!(server.requests.try_recv().is_err()); + + // 2) Reconnect backoff loop: batch with an unfitting ID fails cleanly without echoing it. + let mut server2 = Server::new(None).await; + let remote2 = server2.remote.clone(); + let (send2, lines2) = mpsc::channel(16); + let (writer2, mut output2) = output_pipe(); + let scenario2 = async { + send2 + .send(frame(1, "initialize", initialize_params().unwrap())) + .await + .unwrap(); + assert_eq!( + server2.requests.recv().await.unwrap()["method"], + "initialize" + ); + until_id(&mut output2, json!(1)).await; + send2 + .send(frame( + 2, + "session/new", + json!({"cwd":"/local","mcpServers":[]}), + )) + .await + .unwrap(); + let new = server2.requests.recv().await.unwrap(); + server2.result( + &new, + json!({"sessionId":"durable","configOptions":[],"_meta":{"kit/gateway":{"attachment":"owner-1"}}}), + "", + ); + until_id(&mut output2, json!(2)).await; + + server2.events.send(("*".into(), None)).unwrap(); + until_kind(&mut output2, "begin").await; + + send2 + .send(( + Instant::now(), + Ok(json!([ + {"jsonrpc": "2.0", "id": 12, "method": "session/list", "params": {}}, + {"jsonrpc": "2.0", "id": unfitting_id, "method": "session/list", "params": {}} + ]) + .to_string()), + )) + .await + .unwrap(); + let mut failed = None; + while failed.is_none() { + let value = output2.recv().await.unwrap(); + assert!( + value.get("id") != Some(&json!(unfitting_id)) + && value.get("id") != Some(&json!(12)), + "backoff batch with unfitting ID must not emit any entry: {value}" + ); + if value["params"]["_meta"][META]["kind"] == "failed" { + failed = Some(value); + } + } + let failed = failed.unwrap(); + assert!( + failed["params"]["update"]["description"] + .as_str() + .unwrap() + .contains("request id exceeds") + ); + assert!(output2.try_recv().is_err()); + }; + let (result2, ()) = tokio::time::timeout(Duration::from_secs(8), async { + tokio::join!(run(remote2, "/remote".into(), lines2, writer2), scenario2) + }) + .await + .unwrap(); + let err2 = result2.unwrap_err().to_string(); + assert!( + err2.contains("request id exceeds"), + "expected unfitting batch failure in backoff loop, got: {err2}" + ); + assert!(server2.requests.try_recv().is_err()); +}