From bd784c0760837ee5c9982e497d750c09bd1dbc17 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 1 Dec 2026 12:33:53 -0800 Subject: [PATCH 1/3] refactor(harness,transport,tui): share SDK manifest and wire framing, enforce TUI attached state --- Cargo.lock | 2 + crates/engram-agentd/src/proto.rs | 32 +- crates/engram-egress-proto/Cargo.toml | 1 + crates/engram-egress-proto/src/lib.rs | 17 +- crates/engram-harness-claude/src/main.rs | 155 +++------ crates/engram-harness-codex/src/main.rs | 123 +------ crates/engram-harness-proto/Cargo.toml | 1 + crates/engram-harness-proto/src/lib.rs | 36 +-- crates/engram-harness-sdk/src/lib.rs | 9 +- .../engram-harness-sdk/src/tool_manifest.rs | 248 ++++++++++++++ crates/engram-transport/Cargo.toml | 4 +- crates/engram-transport/src/framing.rs | 80 +++++ crates/engram-transport/src/lib.rs | 68 ++-- crates/engram-tui/src/app.rs | 26 +- crates/engram-tui/src/render.rs | 304 +++++++++--------- crates/engram-tui/tests/new_session.rs | 53 ++- crates/engram-tui/tests/slash.rs | 2 +- 17 files changed, 662 insertions(+), 499 deletions(-) create mode 100644 crates/engram-harness-sdk/src/tool_manifest.rs create mode 100644 crates/engram-transport/src/framing.rs diff --git a/Cargo.lock b/Cargo.lock index b1a2286a4..fe774f554 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2619,6 +2619,7 @@ name = "engram-egress-proto" version = "0.1.0" dependencies = [ "engram-core", + "engram-transport", "nix 0.32.0", "serde", "serde_json", @@ -2803,6 +2804,7 @@ dependencies = [ "bincode", "chrono", "engram-ids", + "engram-transport", "proptest", "serde", "serde_json", diff --git a/crates/engram-agentd/src/proto.rs b/crates/engram-agentd/src/proto.rs index cce19c580..8f9272596 100644 --- a/crates/engram-agentd/src/proto.rs +++ b/crates/engram-agentd/src/proto.rs @@ -608,17 +608,13 @@ where R: AsyncReadExt + Unpin, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(std::io::Error::new( + let body = engram_transport::framing::read(r, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!("frame length {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), - )); - } - let mut body = vec![0u8; len]; - r.read_exact(&mut body).await?; + ) + }) + .await?; bincode::deserialize(&body) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}"))) } @@ -632,19 +628,13 @@ where let body = bincode::serialize(msg).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}")) })?; - if body.len() > MAX_MSG_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::write(w, &body, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, - format!( - "encoded frame {} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})", - body.len() - ), - )); - } - let len = (body.len() as u32).to_be_bytes(); - w.write_all(&len).await?; - w.write_all(&body).await?; - Ok(()) + format!("encoded frame {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), + ) + }) + .await } #[cfg(test)] diff --git a/crates/engram-egress-proto/Cargo.toml b/crates/engram-egress-proto/Cargo.toml index d763853e6..ee29acdd2 100644 --- a/crates/engram-egress-proto/Cargo.toml +++ b/crates/engram-egress-proto/Cargo.toml @@ -23,6 +23,7 @@ unused_dependencies = "allow" disallowed_methods = "deny" [dependencies] +engram-transport.workspace = true engram-core.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/engram-egress-proto/src/lib.rs b/crates/engram-egress-proto/src/lib.rs index 8f316467e..82d59b4aa 100644 --- a/crates/engram-egress-proto/src/lib.rs +++ b/crates/engram-egress-proto/src/lib.rs @@ -40,7 +40,7 @@ pub mod manifest; use engram_core::types::egress::SessionEgressPolicy; use engram_core::{SandboxId, SessionId}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; /// Bump on any wire-incompatible change. A mismatch in `Hello` /// position is never adopted — the caller kills and respawns. @@ -184,14 +184,7 @@ where R: AsyncRead + Unpin, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(oversize(len)); - } - let mut buf = vec![0u8; len]; - r.read_exact(&mut buf).await?; + let buf = engram_transport::framing::read(r, MAX_MSG_BYTES, oversize).await?; serde_json::from_slice(&buf) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } @@ -203,11 +196,7 @@ where T: Serialize, { let body = serde_json::to_vec(msg)?; - if body.len() > MAX_MSG_BYTES { - return Err(oversize(body.len())); - } - w.write_all(&(body.len() as u32).to_be_bytes()).await?; - w.write_all(&body).await?; + engram_transport::framing::write(w, &body, MAX_MSG_BYTES, oversize).await?; w.flush().await } diff --git a/crates/engram-harness-claude/src/main.rs b/crates/engram-harness-claude/src/main.rs index ad462ba2c..abdcd15fb 100644 --- a/crates/engram-harness-claude/src/main.rs +++ b/crates/engram-harness-claude/src/main.rs @@ -53,6 +53,13 @@ mod adapter { use engram_harness_sdk::browser_view; use engram_harness_sdk::questions::{Answers, Question}; use engram_harness_sdk::state::StateDir; + use engram_harness_sdk::tool_manifest::{manifest_from_env, ToolProvider}; + #[cfg(test)] + use engram_harness_sdk::tool_manifest::{ + parse_tool_manifest, with_browser_view, NativeBindings, + }; + pub use engram_harness_sdk::tool_manifest::{ManifestTool, ToolExecution, ToolManifest}; + use engram_harness_sdk::{emit, QueuedPrompt}; use nix::sys::signal::{kill, Signal}; use nix::unistd::Pid; use serde_json::Value; @@ -75,71 +82,6 @@ mod adapter { StateDir::new(&cli.state_dir) } - /// ADR 0089 P2: the orchestrator's model-facing tool manifest. The main - /// harness parses `ENGRAM_TOOLS` once at startup and carries this typed - /// value across every claude respawn. The transient MCP bridge parses its - /// own inherited copy because it is a self-invoked process with no shared - /// address space. - pub type ToolManifest = Vec; - - #[derive(Clone, Debug, serde::Deserialize)] - #[serde(rename_all = "camelCase")] - pub struct ManifestTool { - pub name: String, - pub description: String, - pub input_schema: Value, - pub execution: ToolExecution, - #[serde(default)] - pub native_bindings: NativeBindings, - } - - #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] - #[serde(rename_all = "snake_case")] - pub enum ToolExecution { - Sync, - Deferred, - } - - #[derive(Clone, Debug, Default, serde::Deserialize)] - pub struct NativeBindings { - pub claude: Option, - } - - fn parse_tool_manifest(raw: &str) -> serde_json::Result { - serde_json::from_str(raw) - } - - fn manifest_from_env() -> ToolManifest { - let manifest = match std::env::var("ENGRAM_TOOLS") { - Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(&raw) { - Ok(manifest) => manifest, - Err(e) => { - tracing::error!(error = %e, "invalid ENGRAM_TOOLS manifest; exposing no injected tools"); - Vec::new() - } - }, - _ => Vec::new(), - }; - with_browser_view(manifest, browser_view::enabled()) - } - - fn with_browser_view(mut manifest: ToolManifest, enabled: bool) -> ToolManifest { - if enabled - && !manifest - .iter() - .any(|tool| tool.name == browser_view::TOOL_NAME) - { - manifest.push(ManifestTool { - name: browser_view::TOOL_NAME.into(), - description: browser_view::TOOL_DESCRIPTION.into(), - input_schema: browser_view::input_schema(), - execution: ToolExecution::Sync, - native_bindings: NativeBindings::default(), - }); - } - manifest - } - fn injected_tools(manifest: &ToolManifest) -> impl Iterator { manifest .iter() @@ -413,7 +355,7 @@ mod adapter { .init(); let mut cli = Cli::parse(); - cli.tool_manifest = manifest_from_env(); + cli.tool_manifest = manifest_from_env(ToolProvider::Claude); // Materialise the resolved claude binary path so the rest of // the code can treat `cli.claude_bin` as a known value. cli.claude_bin = Some(resolve_claude_bin(cli.claude_bin.as_deref())); @@ -488,16 +430,6 @@ mod adapter { .await } - /// Push an event to the connection pump. Bounded send: while - /// disconnected the pump can't drain, so this backpressures — - /// pausing the engine (and, transitively, claude via its stdout - /// pipe) rather than losing events. The run resumes when a - /// connection reattaches. Errors only if the receiver is gone, - /// i.e. the process is tearing down; treat as a debug no-op. - async fn emit(evt_tx: &mpsc::Sender, ev: HarnessEvent) { - engram_harness_sdk::emit(evt_tx, ev).await; - } - /// ADR 0054 Flavor B: the hook↔harness socket server and its shared /// state. The harness is a long-lived **server**; each `PreToolUse` /// hook invocation (the `hook-bridge` subcommand) is a transient @@ -1095,10 +1027,11 @@ mod adapter { } pub(super) fn native_roundtrip_names() -> std::collections::HashSet { - let mut names: std::collections::HashSet = super::manifest_from_env() - .iter() - .filter_map(|tool| tool.native_bindings.claude.clone()) - .collect(); + let mut names: std::collections::HashSet = + super::manifest_from_env(super::ToolProvider::Claude) + .iter() + .filter_map(|tool| tool.native_bindings.claude.clone()) + .collect(); names.insert("AskUserQuestion".to_string()); names } @@ -1275,6 +1208,7 @@ mod adapter { pub mod mcp_bridge { use super::{ browser_view, injected_tools, manifest_from_env, BufReader, StateDir, ToolManifest, + ToolProvider, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -1296,7 +1230,7 @@ mod adapter { } pub async fn run() -> std::process::ExitCode { - let manifest = manifest_from_env(); + let manifest = manifest_from_env(ToolProvider::Claude); let socket_path = std::env::var_os("ENGRAM_MCP_SOCK") .filter(|value| !value.is_empty()) .map(PathBuf::from) @@ -1920,7 +1854,7 @@ mod adapter { apply_prompt_mode(&cli, mode.as_deref()); seen_prompt_ids.insert(prompt_id.clone()); pending.push_back(QueuedPrompt { - prompt_id: Some(prompt_id), + prompt_id, text, mode, }); @@ -2251,31 +2185,6 @@ mod adapter { generations: GenerationLedger, } - /// A prompt waiting in the harness-owned queue (Phase 1b — type-ahead - /// / steering). The harness is the single-writer owner: it buffers - /// these in memory and writes one to claude's stdin only at the - /// consumption boundary (the running turn's `result`). `prompt_id` - /// carries the client/coord-minted id used to correlate the queue - /// events and the eventual `RunStarted{prompt_id}` — issue #535 (d): - /// every prompt, first or follow-up, now arrives via `HarnessCommand:: - /// Prompt`, so this is always `Some` in practice (the historical `None` - /// case was the env-seeded initial prompt, deleted). Kept `Option` - /// rather than force-unwrapping at each read site — a defensive `None` - /// costs nothing here and this isn't a wire type. - struct QueuedPrompt { - prompt_id: Option, - text: String, - /// ADR 0107: the mode directive THIS prompt carried, applied when its - /// turn starts. It has to ride the prompt rather than a process-global - /// latch: with type-ahead the queue holds several prompts, so latching - /// on arrival let a later prompt's mode decide an earlier prompt's turn - /// — including the unsafe direction, where a prompt sent during a - /// read-only pass ran with full write access because a later prompt had - /// switched back to build (PR #927 review). `None` = "no directive", - /// which inherits the session's current mode rather than resetting it. - mode: Option, - } - /// Latch a prompt's mode directive at the moment its turn begins. Returns /// the mode the next turn must run under (the stamp, post-write). fn apply_prompt_mode(cli: &Cli, mode: Option<&str>) -> String { @@ -2562,8 +2471,15 @@ mod adapter { Some(qp) => { if let Some(s) = stdin.as_mut() { turn = Some( - start_turn(evt_tx, s, cli, qp.prompt_id, &qp.text, current_run_id) - .await, + start_turn( + evt_tx, + s, + cli, + Some(qp.prompt_id), + &qp.text, + current_run_id, + ) + .await, ); } // A respawn-surviving queue can hold more than one @@ -2897,7 +2813,7 @@ mod adapter { { tracing::info!( prompt_id = - qp.prompt_id.as_deref().unwrap_or(""), + qp.prompt_id.as_str(), current = %process_mode, "mode change at consumption boundary: clean respawn" ); @@ -2912,7 +2828,7 @@ mod adapter { evt_tx, s, cli, - qp.prompt_id, + Some(qp.prompt_id), &qp.text, current_run_id, ) @@ -3077,7 +2993,7 @@ mod adapter { // process picks its argv off the stamp. apply_prompt_mode(cli, mode.as_deref()); pending.push_front(QueuedPrompt { - prompt_id: Some(prompt_id), + prompt_id, text, mode, }); @@ -3181,7 +3097,7 @@ mod adapter { ) .await; pending.push_back(QueuedPrompt { - prompt_id: Some(prompt_id), + prompt_id, text, mode, }); @@ -3266,7 +3182,7 @@ mod adapter { let summary = Some(truncate_str(&text, MAX_ARGS_SUMMARY_BYTES)); let found = match pending .iter_mut() - .find(|q| q.prompt_id.as_deref() == Some(prompt_id.as_str())) + .find(|q| q.prompt_id == prompt_id) { Some(qp) => { qp.text = text; @@ -3287,7 +3203,7 @@ mod adapter { Some(HarnessCommand::DequeueQueued { prompt_id }) => { let before = pending.len(); pending - .retain(|q| q.prompt_id.as_deref() != Some(prompt_id.as_str())); + .retain(|q| q.prompt_id != prompt_id); if pending.len() != before { emit(evt_tx, HarnessEvent::PromptDequeued { prompt_id }).await; } else { @@ -4924,7 +4840,7 @@ mod adapter { .join(format!("engram-mcp-config-test-{}", uuid::Uuid::new_v4())); tokio::fs::create_dir_all(&dir).await.unwrap(); let path = dir.join("mcp-config.json"); - let manifest = parse_tool_manifest( + let manifest = parse_tool_manifest(ToolProvider::Claude, r#"[ {"name":"save_memory","description":"Save it","inputSchema":{"type":"object"},"execution":"sync","nativeBindings":{}}, {"name":"ask_user_question","description":"Ask","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"claude":"AskUserQuestion"}} @@ -4956,7 +4872,7 @@ mod adapter { }) ); - let native_only = parse_tool_manifest( + let native_only = parse_tool_manifest(ToolProvider::Claude, r#"[{"name":"ask_user_question","description":"Ask","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"claude":"AskUserQuestion"}}]"#, ) .unwrap(); @@ -4971,7 +4887,7 @@ mod adapter { } fn mcp_fixture_manifest() -> ToolManifest { - parse_tool_manifest( + parse_tool_manifest(ToolProvider::Claude, r#"[ {"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object","properties":{"text":{"type":"string"}}},"execution":"sync","nativeBindings":{}}, {"name":"ask_user_question","description":"Ask","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"claude":"AskUserQuestion"}} @@ -7284,6 +7200,7 @@ mod adapter { execution: ToolExecution::Deferred, native_bindings: NativeBindings { claude: Some("AskUserQuestion".into()), + ..Default::default() }, } } @@ -8854,6 +8771,7 @@ async fn main() -> std::process::ExitCode { mod tests { use super::adapter::*; use engram_harness_proto::{FileChange, HarnessEvent}; + use engram_harness_sdk::tool_manifest::NativeBindings; use std::collections::HashMap; #[test] @@ -9709,6 +9627,7 @@ mod tests { execution: ToolExecution::Deferred, native_bindings: NativeBindings { claude: Some("ExitPlanMode".into()), + ..Default::default() }, }]; let deferred_names = deferred_tool_names(&manifest); diff --git a/crates/engram-harness-codex/src/main.rs b/crates/engram-harness-codex/src/main.rs index dad0c4e00..53b06e8d1 100644 --- a/crates/engram-harness-codex/src/main.rs +++ b/crates/engram-harness-codex/src/main.rs @@ -13,6 +13,11 @@ use engram_harness_sdk::browser_view; use engram_harness_sdk::parked::{ParkedCall, ParkedCallKind, ParkedCallStore}; use engram_harness_sdk::questions::{Answers, Question, QuestionOption}; use engram_harness_sdk::state::StateDir; +use engram_harness_sdk::tool_manifest::{ + manifest_from_env, ToolExecution, ToolManifest, ToolProvider, +}; +#[cfg(test)] +use engram_harness_sdk::tool_manifest::{parse_tool_manifest, with_browser_view}; use engram_harness_sdk::{emit, Channels, ConnectionConfig, QueuedPrompt}; use serde_json::{json, Value}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; @@ -23,107 +28,11 @@ const MAX_SUMMARY: usize = 4096; const MAX_OAUTH_BUNDLE_BYTES: usize = 256 * 1024; const OPENAI_CODEX_PROVIDER: &str = "openai-codex"; -type ToolManifest = Vec; - -#[derive(Clone, Debug)] -struct ManifestTool { - name: String, - description: String, - input_schema: Value, - execution: ToolExecution, - codex_native_binding: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ToolExecution { - Sync, - Deferred, -} - -fn parse_tool_manifest(raw: &str) -> Result { - let value: Value = serde_json::from_str(raw).map_err(|error| error.to_string())?; - let entries = value - .as_array() - .ok_or("ENGRAM_TOOLS must be a JSON array")?; - entries - .iter() - .map(|entry| { - let object = entry - .as_object() - .ok_or("ENGRAM_TOOLS entries must be objects")?; - let required_string = |field: &str| { - object - .get(field) - .and_then(Value::as_str) - .map(str::to_owned) - .ok_or_else(|| format!("ENGRAM_TOOLS entry missing string {field}")) - }; - let execution = match required_string("execution")?.as_str() { - "sync" => ToolExecution::Sync, - "deferred" => ToolExecution::Deferred, - other => return Err(format!("invalid ENGRAM_TOOLS execution {other}")), - }; - let codex_native_binding = match object.get("nativeBindings") { - None => None, - Some(Value::Object(bindings)) => match bindings.get("codex") { - None | Some(Value::Null) => None, - Some(Value::String(binding)) => Some(binding.clone()), - Some(_) => { - return Err("ENGRAM_TOOLS nativeBindings.codex must be a string".to_string()) - } - }, - Some(_) => return Err("ENGRAM_TOOLS nativeBindings must be an object".to_string()), - }; - Ok(ManifestTool { - name: required_string("name")?, - description: required_string("description")?, - input_schema: object - .get("inputSchema") - .cloned() - .ok_or("ENGRAM_TOOLS entry missing inputSchema")?, - execution, - codex_native_binding, - }) - }) - .collect() -} - -fn manifest_from_env() -> ToolManifest { - let manifest = match std::env::var("ENGRAM_TOOLS") { - Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(&raw) { - Ok(manifest) => manifest, - Err(error) => { - tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no dynamic tools"); - Vec::new() - } - }, - _ => Vec::new(), - }; - with_browser_view(manifest, browser_view::enabled()) -} - -fn with_browser_view(mut manifest: ToolManifest, enabled: bool) -> ToolManifest { - if enabled - && !manifest - .iter() - .any(|tool| tool.name == browser_view::TOOL_NAME) - { - manifest.push(ManifestTool { - name: browser_view::TOOL_NAME.into(), - description: browser_view::TOOL_DESCRIPTION.into(), - input_schema: browser_view::input_schema(), - execution: ToolExecution::Sync, - codex_native_binding: None, - }); - } - manifest -} - fn dynamic_tools(manifest: &ToolManifest) -> Value { Value::Array( manifest .iter() - .filter(|tool| tool.codex_native_binding.is_none()) + .filter(|tool| tool.native_bindings.codex.is_none()) .map(|tool| { json!({ "name": tool.name, @@ -215,7 +124,7 @@ async fn main() -> ExitCode { ) .init(); let mut cli = Cli::parse(); - cli.tool_manifest = manifest_from_env(); + cli.tool_manifest = manifest_from_env(ToolProvider::Codex); if !((cli.connect.is_some()) ^ (cli.port.is_some())) { tracing::error!("provide exactly one of --connect or --port"); return ExitCode::from(2); @@ -1329,7 +1238,7 @@ async fn handle_dynamic_tool_call( }; let Some(tool) = manifest .iter() - .find(|tool| tool.name == tool_name && tool.codex_native_binding.is_none()) + .find(|tool| tool.name == tool_name && tool.native_bindings.codex.is_none()) else { tracing::error!(%call_id, %tool_name, "Codex requested an undeclared dynamic tool"); let _ = server @@ -1870,7 +1779,7 @@ async fn handle_message( let native_tool = tools .manifest .iter() - .find(|tool| tool.codex_native_binding.as_deref() == Some("requestUserInput")) + .find(|tool| tool.native_bindings.codex.as_deref() == Some("requestUserInput")) .map(|tool| tool.name.clone()); let tool_name = native_tool.unwrap_or_else(|| { tracing::warn!( @@ -2774,14 +2683,14 @@ done codex_bin: Some(codex_bin), state_dir, codex_home: None, - tool_manifest: manifest_from_env(), + tool_manifest: manifest_from_env(ToolProvider::Codex), test_api_key: Some("test-api-key".into()), test_credential_control: None, } } fn native_question_manifest() -> ToolManifest { - parse_tool_manifest( + parse_tool_manifest(ToolProvider::Codex, r#"[{"name":"ask_user_question","description":"Ask the user one or more structured questions.","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"codex":"requestUserInput"}}]"#, ) .unwrap() @@ -3118,7 +3027,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-1","tool":"save_memory","arguments":{"text":"remember this"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, _) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest( + cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, r#"[{"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); @@ -3228,7 +3137,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-plan","tool":"exit_plan_mode","arguments":{"plan":"draft plan"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, record) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest( + cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, r#"[{"name":"exit_plan_mode","description":"Present the plan","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); @@ -3319,7 +3228,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-plan","tool":"exit_plan_mode","arguments":{"plan":"draft"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, record) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest( + cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, r#"[{"name":"exit_plan_mode","description":"Present the plan","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); @@ -3432,7 +3341,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-1","tool":"save_memory","arguments":{"text":"remember this"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, record) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest( + cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, r#"[{"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object"},"execution":"sync","nativeBindings":{}}]"#, ) .unwrap(); @@ -3727,7 +3636,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-1","tool":"save_memory","arguments":{"text":"remember this"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, _) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest( + cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, r#"[{"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); diff --git a/crates/engram-harness-proto/Cargo.toml b/crates/engram-harness-proto/Cargo.toml index cad31e375..d281b7f79 100644 --- a/crates/engram-harness-proto/Cargo.toml +++ b/crates/engram-harness-proto/Cargo.toml @@ -14,6 +14,7 @@ workspace = true path = "src/lib.rs" [dependencies] +engram-transport.workspace = true async-trait.workspace = true bincode.workspace = true chrono.workspace = true diff --git a/crates/engram-harness-proto/src/lib.rs b/crates/engram-harness-proto/src/lib.rs index ac9f5c1f2..2c5019778 100644 --- a/crates/engram-harness-proto/src/lib.rs +++ b/crates/engram-harness-proto/src/lib.rs @@ -875,25 +875,19 @@ pub struct RelayAck { // ---- Framing ----------------------------------------------------------- -/// Read one length-prefixed bincode frame. Mirrors -/// `engram-agentd::proto::read_msg` so adapters can share a single -/// codec. +/// Read one length-prefixed bincode frame. pub async fn read_msg(r: &mut R) -> std::io::Result where R: AsyncReadExt + Unpin, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(std::io::Error::new( + let body = engram_transport::framing::read(r, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!("harness frame length {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), - )); - } - let mut body = vec![0u8; len]; - r.read_exact(&mut body).await?; + ) + }) + .await?; bincode::deserialize(&body) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}"))) } @@ -907,19 +901,13 @@ where let body = bincode::serialize(msg).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}")) })?; - if body.len() > MAX_MSG_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::write(w, &body, MAX_MSG_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, - format!( - "encoded harness frame {} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})", - body.len() - ), - )); - } - let len = (body.len() as u32).to_be_bytes(); - w.write_all(&len).await?; - w.write_all(&body).await?; - Ok(()) + format!("encoded harness frame {len} exceeds MAX_MSG_BYTES ({MAX_MSG_BYTES})"), + ) + }) + .await } #[cfg(test)] diff --git a/crates/engram-harness-sdk/src/lib.rs b/crates/engram-harness-sdk/src/lib.rs index cf4152d82..c46240c49 100644 --- a/crates/engram-harness-sdk/src/lib.rs +++ b/crates/engram-harness-sdk/src/lib.rs @@ -12,6 +12,7 @@ pub mod parked; pub mod plan; pub mod questions; pub mod state; +pub mod tool_manifest; pub mod turn_context; use std::collections::{HashSet, VecDeque}; @@ -674,13 +675,7 @@ async fn pump_events( pub struct QueuedPrompt { pub prompt_id: String, pub text: String, - /// ADR 0107: the mode directive THIS prompt carried, applied when its turn - /// starts. It rides the prompt rather than a process-global latch because - /// the queue holds several prompts under type-ahead: latching on arrival - /// let a later prompt's mode decide an earlier prompt's turn, including - /// the unsafe direction where a prompt sent during a read-only pass ran - /// with full write access (PR #927 review). `None` inherits the session's - /// current mode rather than resetting it. + /// Applied when this prompt starts. `None` inherits the session mode. pub mode: Option, } diff --git a/crates/engram-harness-sdk/src/tool_manifest.rs b/crates/engram-harness-sdk/src/tool_manifest.rs new file mode 100644 index 000000000..c23ac099a --- /dev/null +++ b/crates/engram-harness-sdk/src/tool_manifest.rs @@ -0,0 +1,248 @@ +//! Tool manifests and built-in browser tools shared by harness adapters. + +use crate::browser_view; +use serde_json::Value; + +pub type ToolManifest = Vec; + +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ManifestTool { + pub name: String, + pub description: String, + pub input_schema: Value, + pub execution: ToolExecution, + #[serde(default)] + pub native_bindings: B, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolExecution { + Sync, + Deferred, +} + +#[derive(Clone, Debug, Default, serde::Deserialize)] +pub struct NativeBindings { + pub claude: Option, + pub codex: Option, +} + +#[derive(Default, serde::Deserialize)] +struct ClaudeBindings { + claude: Option, +} + +#[derive(Clone, Copy, Debug)] +pub enum ToolProvider { + Claude, + Codex, +} + +pub fn parse_tool_manifest(provider: ToolProvider, raw: &str) -> Result { + match provider { + ToolProvider::Claude => { + let tools: Vec> = + serde_json::from_str(raw).map_err(|error| error.to_string())?; + Ok(tools + .into_iter() + .map(|tool| ManifestTool { + name: tool.name, + description: tool.description, + input_schema: tool.input_schema, + execution: tool.execution, + native_bindings: NativeBindings { + claude: tool.native_bindings.claude, + codex: None, + }, + }) + .collect()) + } + ToolProvider::Codex => parse_codex_manifest(raw), + } +} + +fn parse_codex_manifest(raw: &str) -> Result { + let value: Value = serde_json::from_str(raw).map_err(|error| error.to_string())?; + let entries = value + .as_array() + .ok_or("ENGRAM_TOOLS must be a JSON array")?; + entries + .iter() + .map(|entry| { + let object = entry + .as_object() + .ok_or("ENGRAM_TOOLS entries must be objects")?; + let required_string = |field: &str| { + object + .get(field) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| format!("ENGRAM_TOOLS entry missing string {field}")) + }; + let execution = match required_string("execution")?.as_str() { + "sync" => ToolExecution::Sync, + "deferred" => ToolExecution::Deferred, + other => return Err(format!("invalid ENGRAM_TOOLS execution {other}")), + }; + let codex_native_binding = match object.get("nativeBindings") { + None => None, + Some(Value::Object(bindings)) => match bindings.get("codex") { + None | Some(Value::Null) => None, + Some(Value::String(binding)) => Some(binding.clone()), + Some(_) => { + return Err("ENGRAM_TOOLS nativeBindings.codex must be a string".to_string()) + } + }, + Some(_) => return Err("ENGRAM_TOOLS nativeBindings must be an object".to_string()), + }; + Ok(ManifestTool { + name: required_string("name")?, + description: required_string("description")?, + input_schema: object + .get("inputSchema") + .cloned() + .ok_or("ENGRAM_TOOLS entry missing inputSchema")?, + execution, + native_bindings: NativeBindings { + codex: codex_native_binding, + ..Default::default() + }, + }) + }) + .collect() +} + +pub fn manifest_from_env(provider: ToolProvider) -> ToolManifest { + let manifest = match std::env::var("ENGRAM_TOOLS") { + Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(provider, &raw) { + Ok(manifest) => manifest, + Err(error) => { + match provider { + ToolProvider::Claude => { + tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no injected tools") + } + ToolProvider::Codex => { + tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no dynamic tools") + } + } + Vec::new() + } + }, + _ => Vec::new(), + }; + with_browser_view(manifest, browser_view::enabled()) +} + +pub fn with_browser_view(mut manifest: ToolManifest, enabled: bool) -> ToolManifest { + if enabled + && !manifest + .iter() + .any(|tool| tool.name == browser_view::TOOL_NAME) + { + manifest.push(ManifestTool { + name: browser_view::TOOL_NAME.into(), + description: browser_view::TOOL_DESCRIPTION.into(), + input_schema: browser_view::input_schema(), + execution: ToolExecution::Sync, + native_bindings: NativeBindings::default(), + }); + } + manifest +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn tool() -> Value { + json!({"name":"ask", "description":"Ask a question", "inputSchema":{}, + "execution":"deferred", "nativeBindings":{ + "claude":"AskUserQuestion", "codex":"requestUserInput" + }}) + } + + #[test] + fn manifests_keep_each_providers_native_binding() { + for provider in [ToolProvider::Claude, ToolProvider::Codex] { + let manifest = parse_tool_manifest(provider, &json!([tool()]).to_string()).unwrap(); + assert_eq!(manifest[0].name, "ask"); + assert_eq!(manifest[0].execution, ToolExecution::Deferred); + match provider { + ToolProvider::Claude => assert_eq!( + manifest[0].native_bindings.claude.as_deref(), + Some("AskUserQuestion") + ), + ToolProvider::Codex => assert_eq!( + manifest[0].native_bindings.codex.as_deref(), + Some("requestUserInput") + ), + } + } + } + + #[test] + fn only_the_selected_providers_binding_is_validated() { + for (provider, other, selected) in [ + (ToolProvider::Claude, "codex", "claude"), + (ToolProvider::Codex, "claude", "codex"), + ] { + let mut entry = tool(); + entry["nativeBindings"][other] = json!(123); + assert!(parse_tool_manifest(provider, &json!([entry.clone()]).to_string()).is_ok()); + entry["nativeBindings"][selected] = json!(123); + assert!(parse_tool_manifest(provider, &json!([entry]).to_string()).is_err()); + } + } + + #[test] + fn malformed_manifests_are_rejected() { + for provider in [ToolProvider::Claude, ToolProvider::Codex] { + for raw in ["not json", "{}", "[null]", "[{}]"] { + assert!(parse_tool_manifest(provider, raw).is_err()); + } + for field in ["name", "description", "execution", "nativeBindings"] { + let mut entry = tool(); + entry[field] = json!(123); + assert!(parse_tool_manifest(provider, &json!([entry]).to_string()).is_err()); + } + } + let error = parse_tool_manifest(ToolProvider::Codex, "{}").unwrap_err(); + assert_eq!(error, "ENGRAM_TOOLS must be a JSON array"); + } + + #[test] + fn optional_bindings_and_schema_keep_provider_decode_rules() { + let mut entry = tool(); + entry.as_object_mut().unwrap().remove("nativeBindings"); + for provider in [ToolProvider::Claude, ToolProvider::Codex] { + let manifest = + parse_tool_manifest(provider, &json!([entry.clone()]).to_string()).unwrap(); + assert!(manifest[0].native_bindings.claude.is_none()); + assert!(manifest[0].native_bindings.codex.is_none()); + } + entry.as_object_mut().unwrap().remove("inputSchema"); + let raw = json!([entry]).to_string(); + assert!(parse_tool_manifest(ToolProvider::Claude, &raw).is_err()); + assert_eq!( + parse_tool_manifest(ToolProvider::Codex, &raw).unwrap_err(), + "ENGRAM_TOOLS entry missing inputSchema" + ); + } + + #[test] + fn browser_tool_is_optional_and_never_replaces_an_existing_entry() { + assert!(with_browser_view(Vec::new(), false).is_empty()); + let mut manifest = with_browser_view(Vec::new(), true); + assert_eq!(manifest.len(), 1); + assert_eq!(manifest[0].name, browser_view::TOOL_NAME); + assert_eq!(manifest[0].input_schema, browser_view::input_schema()); + manifest[0].description = "Custom browser tool".into(); + let manifest = with_browser_view(manifest, true); + assert_eq!(manifest.len(), 1); + assert_eq!(manifest[0].description, "Custom browser tool"); + assert_eq!(with_browser_view(manifest, false).len(), 1); + } +} diff --git a/crates/engram-transport/Cargo.toml b/crates/engram-transport/Cargo.toml index 179624a60..7f6476988 100644 --- a/crates/engram-transport/Cargo.toml +++ b/crates/engram-transport/Cargo.toml @@ -16,8 +16,6 @@ tokio.workspace = true tracing.workspace = true workspace-hack = { version = "0.1", path = "../../workspace-hack" } -# vsock is a Linux-only kernel feature. The transport compiles only on -# Linux; on macOS / other hosts the crate is an empty shell so the -# workspace cargo check stays green everywhere. +# Vsock requires Linux. Framing and transport traits are cross-platform. [target.'cfg(target_os = "linux")'.dependencies] tokio-vsock = "0.7" diff --git a/crates/engram-transport/src/framing.rs b/crates/engram-transport/src/framing.rs new file mode 100644 index 000000000..8bcd55b39 --- /dev/null +++ b/crates/engram-transport/src/framing.rs @@ -0,0 +1,80 @@ +//! Four-byte big-endian length prefixes with caller-owned limits and errors. + +use std::io; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + +/// Read a frame. Reject the length before allocating or reading the body. +pub async fn read( + reader: &mut R, + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result> { + let mut prefix = [0; 4]; + reader.read_exact(&mut prefix).await?; + let len = u32::from_be_bytes(prefix) as usize; + if len > max_bytes { + return Err(oversize(len)); + } + let mut body = vec![0; len]; + reader.read_exact(&mut body).await?; + Ok(body) +} + +/// Write a frame without flushing. Reject oversized bodies before writing. +pub async fn write( + writer: &mut W, + body: &[u8], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result<()> { + let len = body.len(); + if len > max_bytes || len > u32::MAX as usize { + return Err(oversize(len)); + } + writer.write_all(&(len as u32).to_be_bytes()).await?; + writer.write_all(body).await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn oversize(len: usize) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, format!("too large: {len}")) + } + + #[tokio::test] + async fn frames_keep_the_wire_bytes_and_boundaries() { + let mut wire = Vec::new(); + write(&mut wire, b"abc", 3, oversize).await.unwrap(); + write(&mut wire, b"", 3, oversize).await.unwrap(); + assert_eq!(wire, b"\0\0\0\x03abc\0\0\0\0"); + let mut reader = wire.as_slice(); + assert_eq!(read(&mut reader, 3, oversize).await.unwrap(), b"abc"); + assert!(read(&mut reader, 3, oversize).await.unwrap().is_empty()); + assert!(reader.is_empty()); + } + + #[tokio::test] + async fn limits_reject_before_body_io() { + let mut reader = &b"\0\0\0\x04body"[..]; + let error = read(&mut reader, 3, oversize).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(error.to_string(), "too large: 4"); + assert_eq!(reader, b"body"); + let mut wire = Vec::new(); + let error = write(&mut wire, b"body", 3, oversize).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(error.to_string(), "too large: 4"); + assert!(wire.is_empty()); + } + + #[tokio::test] + async fn truncated_frames_preserve_io_errors() { + let wire = b"\0\0\0\x03abc"; + for end in 0..wire.len() { + let error = read(&mut &wire[..end], 3, oversize).await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + } + } +} diff --git a/crates/engram-transport/src/lib.rs b/crates/engram-transport/src/lib.rs index 2f1494dfa..b2f4dad75 100644 --- a/crates/engram-transport/src/lib.rs +++ b/crates/engram-transport/src/lib.rs @@ -5,21 +5,6 @@ //! bind / dial without knowing which VMM is hosting the VM. One impl //! ships: `VsockTransport` (virtio-vsock), used by **both** backends. //! -//! # Why vsock everywhere -//! -//! - **Firecracker** exposes virtio-vsock as its only host↔guest -//! programmatic channel. (FC also has a 16550A serial UART, but no -//! virtio-console device — see the FAQ.) -//! -//! - **Apple Virtualization.framework (VZ)** exposes a real -//! `VZVirtioSocketDevice`. VZ briefly bridged these channels over a -//! multi-port virtio-console (single byte stream per port → head-of-line -//! blocking on the ADR 0066 port relay) because generic arm64 -//! cloud-image kernels ship `CONFIG_VIRTIO_VSOCKETS` as a *module*. -//! But the Kata guest kernel VZ actually boots (`just pull-kernel`) -//! ships it built-in, so ADR 0066 Phase 2 migrated VZ back to real -//! vsock — the console transport is retired. -//! //! # Selection //! //! The [`from_env`] factory reads `ENGRAM_TRANSPORT` (default @@ -34,15 +19,9 @@ //! per connection) with no head-of-line blocking — the property the //! ADR 0066 port relay depends on. //! -//! # Cross-platform shell +//! # Platform support //! -//! The impl is Linux-only. On macOS / other hosts the crate compiles -//! to an empty shell — the in-VM binaries themselves are Linux-only -//! too (the workspace's `engram-agentd` / `engram-harness-*` binaries -//! already wrap their `main` in `#[cfg(target_os = "linux")]`), so -//! this just keeps `cargo check --workspace` green on Apple Silicon. - -#![cfg_attr(not(target_os = "linux"), allow(dead_code))] +//! Vsock is Linux-only. Framing and transport traits are available on all hosts. use std::io; use std::pin::Pin; @@ -53,6 +32,8 @@ use tokio::io::{AsyncRead, AsyncWrite}; #[cfg(target_os = "linux")] mod vsock; +pub mod framing; + #[cfg(target_os = "linux")] pub use vsock::VsockTransport; @@ -66,10 +47,7 @@ impl AsyncReadWrite for T {} /// Owned duplex byte stream over the chosen transport. pub type BoxedStream = Pin>; -/// Connection-accepting half of a [`Transport`]. Yields a fresh -/// stream per [`accept`](Listener::accept) call on transports that -/// support it (vsock); yields the stream once then EOFs on those -/// that don't (virtio-console). +/// Connection-accepting half of a [`Transport`]. Each accept yields a fresh stream. #[async_trait] pub trait Listener: Send { async fn accept(&mut self) -> io::Result; @@ -88,15 +66,18 @@ pub trait Transport: Send + Sync { /// Build a [`Transport`] from the `ENGRAM_TRANSPORT` env var. /// -/// Defaults to `vsock` if unset. Every bake sets `ENGRAM_TRANSPORT=vsock`; -/// the knob stays a seam for a future non-vsock backend but today only -/// `vsock` is valid (the virtio-console transport was retired in ADR 0066 -/// Phase 2). +/// Defaults to `vsock` if unset. Only `vsock` is supported. #[cfg(target_os = "linux")] pub fn from_env() -> io::Result> { - let raw = std::env::var("ENGRAM_TRANSPORT").unwrap_or_else(|_| "vsock".into()); - match raw.as_str() { - "vsock" => Ok(Box::new(VsockTransport)), + let raw = std::env::var("ENGRAM_TRANSPORT").ok(); + parse_transport(raw.as_deref())?; + Ok(Box::new(VsockTransport)) +} + +#[cfg(any(target_os = "linux", test))] +fn parse_transport(raw: Option<&str>) -> io::Result<()> { + match raw.unwrap_or("vsock") { + "vsock" => Ok(()), other => Err(io::Error::new( io::ErrorKind::InvalidInput, format!("unknown ENGRAM_TRANSPORT={other:?}; expected vsock"), @@ -115,7 +96,6 @@ pub fn from_env() -> io::Result> { } #[cfg(test)] -#[cfg(target_os = "linux")] mod tests { use super::*; @@ -123,18 +103,22 @@ mod tests { /// reject unknown values with a clear error message. #[test] fn from_env_defaults_to_vsock_and_rejects_garbage() { - // SAFETY for std::env::set_var: this test is single-threaded - // (one #[test] per module call), but cargo test runs tests in - // parallel by default. We avoid races by not actually reading - // env in this test — we'd test the parse logic separately if - // we exposed it. For now the contract is documented and the - // dispatch is trivial. - // The doc-test above is the actual coverage. + assert!(parse_transport(None).is_ok()); + assert!(parse_transport(Some("vsock")).is_ok()); + for raw in ["", "garbage", "console", "VSOCK", " vsock"] { + let error = parse_transport(Some(raw)).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + assert_eq!( + error.to_string(), + format!("unknown ENGRAM_TRANSPORT={raw:?}; expected vsock") + ); + } } /// Smoke: VsockTransport impls Send+Sync so it can ride in /// `Box`. #[test] + #[cfg(target_os = "linux")] fn transports_are_send_sync() { fn assert_send_sync() {} assert_send_sync::(); diff --git a/crates/engram-tui/src/app.rs b/crates/engram-tui/src/app.rs index 2d0487fa1..75a508580 100644 --- a/crates/engram-tui/src/app.rs +++ b/crates/engram-tui/src/app.rs @@ -695,7 +695,6 @@ pub enum Screen { #[derive(Debug)] pub struct App { - pub screen: Screen, pub sessions: SessionList, pub attached: Option, /// The palette overlay (Ctrl+P) reuses the session list with this @@ -737,9 +736,16 @@ pub struct App { } impl App { + /// The attached session is the single source of screen state. + pub fn screen(&self) -> Screen { + match self.attached { + Some(_) => Screen::Attached, + None => Screen::Sessions, + } + } + pub fn new(inline: bool, width: u16, height: u16) -> Self { App { - screen: Screen::Sessions, sessions: SessionList { loading: true, ..Default::default() @@ -786,7 +792,7 @@ impl App { /// is on screen, 15 s for the terminal's records alone, doubled per /// failed load in a row up to a minute. pub fn poll_interval(&self) -> Duration { - let base = if self.screen == Screen::Sessions || self.palette { + let base = if self.screen() == Screen::Sessions || self.palette { 5 } else { 15 @@ -797,7 +803,7 @@ impl App { /// Is anything showing the session list: the terminal's records, the /// list, or the palette? pub fn wants_poll(&self) -> bool { - self.program_status || self.screen == Screen::Sessions || self.palette + self.program_status || self.screen() == Screen::Sessions || self.palette } pub fn note(&mut self, text: impl Into) { @@ -828,7 +834,6 @@ impl App { .as_ref() .is_some_and(|a| a.session_id == session_id) { - self.screen = Screen::Attached; self.palette = false; return; } @@ -848,7 +853,6 @@ impl App { self.attach_seq += 1; self.unseen = None; self.inbox.opened(session_id); - self.screen = Screen::Attached; self.palette = false; self.cmds.push(Cmd::Attach { session_id: session_id.to_string(), @@ -861,7 +865,6 @@ impl App { } self.attach_seq += 1; self.unseen = None; - self.screen = Screen::Sessions; self.sessions.filter.clear(); self.sessions.loading = true; self.cmds.push(Cmd::LoadSessions); @@ -948,7 +951,7 @@ impl App { NewStage::Prompt => ns.composer.paste(&text), NewStage::Pick => ns.filter.push_str(text.trim()), } - } else if self.screen == Screen::Attached && !self.palette { + } else if self.screen() == Screen::Attached && !self.palette { if let Some(a) = &mut self.attached { if let Some(sh) = a.shell.as_ref().filter(|s| s.focused && s.connected) { let mut out = Vec::with_capacity(text.len() + 12); @@ -973,9 +976,6 @@ impl App { let Some(a) = &mut self.attached else { return; }; - if self.screen != Screen::Attached { - return; - } // The transcript row under the pointer, clamped into the rows // the last frame showed (a drag past the edge keeps selecting). let hit = |a: &Attached, clamp: bool| -> Option<(usize, u16, u16)> { @@ -1054,7 +1054,7 @@ impl App { } return; } - if self.screen == Screen::Attached + if self.screen() == Screen::Attached && !self.palette && self .attached @@ -1093,7 +1093,7 @@ impl App { } if self.new_session.is_some() { self.new_session_key(action); - } else if self.screen == Screen::Sessions || self.palette { + } else if self.screen() == Screen::Sessions || self.palette { self.list_key(action); } else if self.attached.as_ref().is_some_and(|a| a.search.is_some()) { self.search_key(action); diff --git a/crates/engram-tui/src/render.rs b/crates/engram-tui/src/render.rs index 4797dd145..ac2e628d6 100644 --- a/crates/engram-tui/src/render.rs +++ b/crates/engram-tui/src/render.rs @@ -8,7 +8,7 @@ use ratatui::layout::{Position, Rect}; use ratatui::style::{Color, Modifier, Style}; use unicode_segmentation::UnicodeSegmentation; -use crate::app::{shell_pane_rows, App, Attached, NewSession, NewStage, Screen}; +use crate::app::{shell_pane_rows, App, Attached, NewSession, NewStage}; use crate::keymap::BINDINGS; use crate::markdown::{flags, Run}; use crate::palette::{is_light, Palette}; @@ -1408,8 +1408,8 @@ fn draw_footer(buf: &mut Buffer, area: Rect, app: &App, th: &Theme) { put(buf, area.x, y, hint, w, th.dim); return; } - match (&app.attached, app.screen) { - (Some(a), Screen::Attached) => { + match &app.attached { + Some(a) => { let s = status_word(a); let st = if a.reducer.awaiting_decision() { th.warn @@ -1461,7 +1461,7 @@ fn draw_footer(buf: &mut Buffer, area: Rect, app: &App, th: &Theme) { put(buf, area.x + cx, y, short, avail, th.dim); } } - _ => { + None => { let n = app.sessions.rows.len(); cx += put(buf, area.x, y, " ", 1, th.dim); cx += put_num(buf, area.x + cx, y, n as u64, th.dim); @@ -1813,6 +1813,98 @@ fn draw_help(buf: &mut Buffer, area: Rect, th: &Theme) { shade(buf, r, th); } +fn draw_attached_fullscreen( + buf: &mut Buffer, + body: Rect, + footer: Rect, + a: &mut Attached, + th: &Theme, + scratch: &mut Vec<(usize, u16)>, +) -> (Option, bool) { + let width = body.width.saturating_sub(2).max(1); + a.composer.layout(width); + let composer_rows = a.composer.rows().len().clamp(1, 8) as u16; + let queue_rows = (a.reducer.queued.len() as u16).min(4); + // The composer and its queue sit between two rules when the + // screen has the rows for them. + let rules = u16::from(body.height >= 8); + let rule_below = Rect { + y: body.bottom().saturating_sub(1), + height: rules, + ..body + }; + let composer = Rect { + y: body.bottom().saturating_sub(rules + composer_rows), + height: composer_rows.min(body.height), + ..body + }; + let queue = Rect { + y: composer.y.saturating_sub(queue_rows), + height: queue_rows.min(composer.y - body.y), + ..body + }; + let rule_above = Rect { + y: queue.y.saturating_sub(rules), + height: rules, + ..body + }; + let title_h = u16::from(body.height > 4); + let shell_rows = if a.shell.is_some() { + shell_pane_rows(body.height).min(rule_above.y.saturating_sub(body.y + title_h)) + } else { + 0 + }; + let shell = Rect { + y: rule_above.y.saturating_sub(shell_rows), + height: shell_rows, + ..body + }; + let slash_h = slash_rows(a.composer.text()).min(shell.y.saturating_sub(body.y + title_h)); + let slash = Rect { + y: shell.y.saturating_sub(slash_h), + height: slash_h, + ..body + }; + let transcript = Rect { + y: body.y + title_h, + height: slash.y.saturating_sub(body.y + title_h), + ..body + }; + a.page_rows = transcript.height; + if title_h == 1 { + put( + buf, + body.x + 1, + body.y, + &a.title, + body.width.saturating_sub(1), + th.accent, + ); + } + let want_older = draw_transcript(buf, transcript, a, th, scratch); + if slash.height > 0 { + draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); + shade(buf, slash, th); + } + draw_rule(buf, rule_above, th); + draw_queue(buf, queue, a, th); + let mut cursor = Some(draw_composer(buf, composer, a, th)); + draw_rule(buf, rule_below, th); + if shell.height > 0 { + if let Some(c) = draw_shell(buf, shell, a, th) { + cursor = Some(c); + } + } + if let Some(s) = &a.search { + let qx = 2 + display_width(&s.query) as u16; + cursor = Some(Position::new( + footer.x + qx.min(footer.width.saturating_sub(1)), + footer.y, + )); + } + (cursor, want_older) +} + /// Fullscreen frame: transcript, queue rail, composer, footer; the /// session list or palette over it. Returns the cursor position and /// whether the transcript walk wants older history. @@ -1836,99 +1928,13 @@ pub fn draw_fullscreen( height: area.height - 1, ..area }; - let mut cursor = None; - let mut want_older = false; - match app.screen { - Screen::Sessions => draw_sessions(buf, body, app, th, "engrams · sessions"), - Screen::Attached => { - let a = app - .attached - .as_mut() - .expect("attached screen has a session"); - let width = body.width.saturating_sub(2).max(1); - a.composer.layout(width); - let composer_rows = a.composer.rows().len().clamp(1, 8) as u16; - let queue_rows = (a.reducer.queued.len() as u16).min(4); - // The composer and its queue sit between two rules when the - // screen has the rows for them. - let rules = u16::from(body.height >= 8); - let rule_below = Rect { - y: body.bottom().saturating_sub(1), - height: rules, - ..body - }; - let composer = Rect { - y: body.bottom().saturating_sub(rules + composer_rows), - height: composer_rows.min(body.height), - ..body - }; - let queue = Rect { - y: composer.y.saturating_sub(queue_rows), - height: queue_rows.min(composer.y - body.y), - ..body - }; - let rule_above = Rect { - y: queue.y.saturating_sub(rules), - height: rules, - ..body - }; - let title_h = u16::from(body.height > 4); - let shell_rows = if a.shell.is_some() { - shell_pane_rows(body.height).min(rule_above.y.saturating_sub(body.y + title_h)) - } else { - 0 - }; - let shell = Rect { - y: rule_above.y.saturating_sub(shell_rows), - height: shell_rows, - ..body - }; - let slash_h = - slash_rows(a.composer.text()).min(shell.y.saturating_sub(body.y + title_h)); - let slash = Rect { - y: shell.y.saturating_sub(slash_h), - height: slash_h, - ..body - }; - let transcript = Rect { - y: body.y + title_h, - height: slash.y.saturating_sub(body.y + title_h), - ..body - }; - a.page_rows = transcript.height; - if title_h == 1 { - put( - buf, - body.x + 1, - body.y, - &a.title, - body.width.saturating_sub(1), - th.accent, - ); - } - want_older = draw_transcript(buf, transcript, a, th, scratch); - if slash.height > 0 { - draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); - shade(buf, slash, th); - } - draw_rule(buf, rule_above, th); - draw_queue(buf, queue, a, th); - cursor = Some(draw_composer(buf, composer, a, th)); - draw_rule(buf, rule_below, th); - if shell.height > 0 { - if let Some(c) = draw_shell(buf, shell, a, th) { - cursor = Some(c); - } - } - if let Some(s) = &a.search { - let qx = 2 + display_width(&s.query) as u16; - cursor = Some(Position::new( - footer.x + qx.min(footer.width.saturating_sub(1)), - footer.y, - )); - } + let (mut cursor, want_older) = match app.attached.as_mut() { + None => { + draw_sessions(buf, body, app, th, "engrams · sessions"); + (None, false) } - } + Some(a) => draw_attached_fullscreen(buf, body, footer, a, th, scratch), + }; draw_footer(buf, footer, app, th); if app.palette { let h = (app.sessions.rows.len() as u16 + 2).clamp(3, body.height.saturating_sub(2).max(3)); @@ -1964,6 +1970,56 @@ pub fn draw_fullscreen( (cursor, want_older) } +fn draw_attached_inline( + buf: &mut Buffer, + body: Rect, + a: &mut Attached, + th: &Theme, + scratch: &mut Vec<(usize, u16)>, +) -> Option { + let width = body.width.saturating_sub(2).max(1); + a.composer.layout(width); + let composer_rows = a.composer.rows().len().clamp(1, 6) as u16; + let queue_rows = (a.reducer.queued.len() as u16).min(2); + let composer = Rect { + y: body.bottom().saturating_sub(composer_rows), + height: composer_rows.min(body.height), + ..body + }; + let queue = Rect { + y: composer.y.saturating_sub(queue_rows), + height: queue_rows.min(composer.y - body.y), + ..body + }; + // One rule above the composer; the viewport is short. + let rule_above = Rect { + y: queue.y.saturating_sub(1), + height: u16::from(body.height >= 4 && queue.y > body.y), + ..body + }; + let slash_h = slash_rows(a.composer.text()).min(rule_above.y.saturating_sub(body.y)); + let slash = Rect { + y: rule_above.y.saturating_sub(slash_h), + height: slash_h, + ..body + }; + let live = Rect { + y: body.y, + height: slash.y.saturating_sub(body.y), + ..body + }; + a.scroll_up = 0; + a.page_rows = live.height; + draw_transcript(buf, live, a, th, scratch); + if slash.height > 0 { + draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); + shade(buf, slash, th); + } + draw_rule(buf, rule_above, th); + draw_queue(buf, queue, a, th); + Some(draw_composer(buf, composer, a, th)) +} + /// Inline (native scrollback) viewport: the in-flight cells, the queue /// rail, the composer and the footer. Finalized cells were already /// written above it by `commit_inline`. @@ -1987,57 +2043,13 @@ pub fn draw_inline( height: area.height - 1, ..area }; - let mut cursor = None; - match app.screen { - Screen::Sessions => draw_sessions(buf, body, app, th, "engrams · sessions"), - Screen::Attached => { - let a = app - .attached - .as_mut() - .expect("attached screen has a session"); - let width = body.width.saturating_sub(2).max(1); - a.composer.layout(width); - let composer_rows = a.composer.rows().len().clamp(1, 6) as u16; - let queue_rows = (a.reducer.queued.len() as u16).min(2); - let composer = Rect { - y: body.bottom().saturating_sub(composer_rows), - height: composer_rows.min(body.height), - ..body - }; - let queue = Rect { - y: composer.y.saturating_sub(queue_rows), - height: queue_rows.min(composer.y - body.y), - ..body - }; - // One rule above the composer; the viewport is short. - let rule_above = Rect { - y: queue.y.saturating_sub(1), - height: u16::from(body.height >= 4 && queue.y > body.y), - ..body - }; - let slash_h = slash_rows(a.composer.text()).min(rule_above.y.saturating_sub(body.y)); - let slash = Rect { - y: rule_above.y.saturating_sub(slash_h), - height: slash_h, - ..body - }; - let live = Rect { - y: body.y, - height: slash.y.saturating_sub(body.y), - ..body - }; - a.scroll_up = 0; - a.page_rows = live.height; - draw_transcript(buf, live, a, th, scratch); - if slash.height > 0 { - draw_slash(buf, slash, a.composer.text(), a.slash_sel, th); - shade(buf, slash, th); - } - draw_rule(buf, rule_above, th); - draw_queue(buf, queue, a, th); - cursor = Some(draw_composer(buf, composer, a, th)); + let mut cursor = match app.attached.as_mut() { + None => { + draw_sessions(buf, body, app, th, "engrams · sessions"); + None } - } + Some(a) => draw_attached_inline(buf, body, a, th, scratch), + }; draw_footer(buf, footer, app, th); if app.palette { fill(buf, body, Style::new()); diff --git a/crates/engram-tui/tests/new_session.rs b/crates/engram-tui/tests/new_session.rs index 4707c7748..343cb958b 100644 --- a/crates/engram-tui/tests/new_session.rs +++ b/crates/engram-tui/tests/new_session.rs @@ -85,7 +85,7 @@ fn n_lists_profiles_and_enter_creates_the_task() { "Write the release notes.".into(), ))))); assert!(app.new_session.is_none()); - assert_eq!(app.screen, Screen::Attached); + assert_eq!(app.screen(), Screen::Attached); let a = app.attached.as_ref().unwrap(); assert_eq!(a.session_id, "s-new"); assert_eq!(a.title, "Write the release notes."); @@ -119,7 +119,7 @@ fn a_failed_create_reopens_the_prompt_with_the_error() { assert_eq!(app.new_session.as_ref().unwrap().stage, NewStage::Pick); key(&mut app, KeyCode::Esc, KeyModifiers::NONE); assert!(app.new_session.is_none()); - assert_eq!(app.screen, Screen::Sessions); + assert_eq!(app.screen(), Screen::Sessions); } #[test] @@ -133,5 +133,52 @@ fn the_picker_opens_over_an_attached_session_too() { // Ctrl+C closes it and the draft underneath is untouched. key(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL); assert!(app.new_session.is_none()); - assert_eq!(app.screen, Screen::Attached); + assert_eq!(app.screen(), Screen::Attached); +} + +#[test] +fn screen_and_both_renderers_follow_attach_switch_and_detach() { + use engram_tui::render::draw_inline; + use ratatui::buffer::Buffer; + use ratatui::layout::Rect; + + let mut app = App::new(false, 60, 16); + let area = Rect::new(0, 0, 60, 16); + let theme = Theme::new(false); + let mut scratch = Vec::new(); + for session in [ + None, + Some("s-first"), + Some("s-first"), + Some("s-second"), + None, + ] { + match session { + Some(id) => app.attach(id), + None if app.attached.is_some() => { + key(&mut app, KeyCode::Char('d'), KeyModifiers::CONTROL); + } + None => {} + } + assert_eq!( + app.attached.as_ref().map(|a| a.session_id.as_str()), + session + ); + assert_eq!( + app.screen(), + if session.is_some() { + Screen::Attached + } else { + Screen::Sessions + } + ); + let mut fullscreen = Buffer::empty(area); + let mut inline = Buffer::empty(area); + let (cursor, _) = draw_fullscreen(&mut fullscreen, area, &mut app, &theme, &mut scratch); + assert_eq!(cursor.is_some(), session.is_some()); + assert_eq!( + draw_inline(&mut inline, area, &mut app, &theme, &mut scratch).is_some(), + session.is_some() + ); + } } diff --git a/crates/engram-tui/tests/slash.rs b/crates/engram-tui/tests/slash.rs index 38d43dd9a..88c0cdd44 100644 --- a/crates/engram-tui/tests/slash.rs +++ b/crates/engram-tui/tests/slash.rs @@ -112,7 +112,7 @@ fn enter_runs_the_named_command() { type_str(&mut app, "/sessions"); key(&mut app, KeyCode::Enter); - assert_eq!(app.screen, Screen::Sessions); + assert_eq!(app.screen(), Screen::Sessions); } #[test] From 65181b4c7b613dd947309805060285979ffa5895 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:09:45 -0800 Subject: [PATCH 2/3] refactor(transport): route the remaining length-prefixed codecs through framing The egress-proto blocking codec and the host-agent async migrate codec kept their own copies of the 4-byte big-endian framing. Add blocking read_sync/write_sync to engram_transport::framing and use them, so one place owns the length check before allocation and the prefix encoding. The bytes on the wire and the error kinds and messages do not change. framing::read now states that it is not cancel safe. The prefix counts the body only. The u32 check uses try_from. Review pass: engram-migrate-proto (blocking, no tokio) and engram-substrate-proto (one write per frame) keep their own codecs; a dependency on engram-transport would pull tokio into both. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/engram-egress-proto/src/lib.rs | 15 +--- crates/engram-host-agent/Cargo.toml | 1 + crates/engram-host-agent/src/migrate_peer.rs | 31 +++----- crates/engram-transport/src/framing.rs | 83 +++++++++++++++++--- 5 files changed, 90 insertions(+), 41 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fe774f554..60b0995b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2868,6 +2868,7 @@ dependencies = [ "engram-telemetry", "engram-testkit", "engram-tls", + "engram-transport", "engram-uffd-handler", "futures", "futures-util", diff --git a/crates/engram-egress-proto/src/lib.rs b/crates/engram-egress-proto/src/lib.rs index 82d59b4aa..b3ec1d2f8 100644 --- a/crates/engram-egress-proto/src/lib.rs +++ b/crates/engram-egress-proto/src/lib.rs @@ -207,14 +207,7 @@ where R: std::io::Read, T: DeserializeOwned, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf)?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > MAX_MSG_BYTES { - return Err(oversize(len)); - } - let mut buf = vec![0u8; len]; - r.read_exact(&mut buf)?; + let buf = engram_transport::framing::read_sync(r, MAX_MSG_BYTES, oversize)?; serde_json::from_slice(&buf) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } @@ -226,11 +219,7 @@ where T: Serialize, { let body = serde_json::to_vec(msg)?; - if body.len() > MAX_MSG_BYTES { - return Err(oversize(body.len())); - } - w.write_all(&(body.len() as u32).to_be_bytes())?; - w.write_all(&body)?; + engram_transport::framing::write_sync(w, &body, MAX_MSG_BYTES, oversize)?; w.flush() } diff --git a/crates/engram-host-agent/Cargo.toml b/crates/engram-host-agent/Cargo.toml index e94602d74..496ce9105 100644 --- a/crates/engram-host-agent/Cargo.toml +++ b/crates/engram-host-agent/Cargo.toml @@ -42,6 +42,7 @@ engram-chunk-store.workspace = true engram-fill.workspace = true engram-substrate-proto.workspace = true engram-migrate-proto.workspace = true +engram-transport.workspace = true engram-storage-local.workspace = true engram-blob-client.workspace = true engram-cloud-sql.workspace = true diff --git a/crates/engram-host-agent/src/migrate_peer.rs b/crates/engram-host-agent/src/migrate_peer.rs index 54aa54a95..5acf9e9d5 100644 --- a/crates/engram-host-agent/src/migrate_peer.rs +++ b/crates/engram-host-agent/src/migrate_peer.rs @@ -41,7 +41,7 @@ use engram_migrate_proto::{ read_frame, write_frame, FromSource, SealBitmap, ToSource, PROTO_VERSION, }; use sha2::{Digest, Sha256}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::AsyncWriteExt; use tokio::sync::{Notify, Semaphore}; use crate::dirty_map::GuestVma; @@ -724,21 +724,16 @@ pub(crate) async fn read_body_async(r: &mut R) -> std::io::Result> where R: tokio::io::AsyncRead + Unpin, { - let mut len_buf = [0u8; 4]; - r.read_exact(&mut len_buf).await?; - let len = u32::from_be_bytes(len_buf) as usize; - if len > engram_migrate_proto::MAX_FRAME_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::read(r, engram_migrate_proto::MAX_FRAME_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!( "frame length {len} exceeds MAX_FRAME_BYTES ({})", engram_migrate_proto::MAX_FRAME_BYTES ), - )); - } - let mut body = vec![0u8; len]; - r.read_exact(&mut body).await?; - Ok(body) + ) + }) + .await } /// Write one length-prefixed frame asynchronously (mirror of @@ -753,18 +748,16 @@ where let body = bincode::serialize(msg).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bincode: {e}")) })?; - if body.len() > engram_migrate_proto::MAX_FRAME_BYTES { - return Err(std::io::Error::new( + engram_transport::framing::write(w, &body, engram_migrate_proto::MAX_FRAME_BYTES, |len| { + std::io::Error::new( std::io::ErrorKind::InvalidData, format!( - "encoded frame {} exceeds MAX_FRAME_BYTES ({})", - body.len(), + "encoded frame {len} exceeds MAX_FRAME_BYTES ({})", engram_migrate_proto::MAX_FRAME_BYTES ), - )); - } - w.write_all(&(body.len() as u32).to_be_bytes()).await?; - w.write_all(&body).await?; + ) + }) + .await?; w.flush().await?; Ok(()) } diff --git a/crates/engram-transport/src/framing.rs b/crates/engram-transport/src/framing.rs index 8bcd55b39..00d37af31 100644 --- a/crates/engram-transport/src/framing.rs +++ b/crates/engram-transport/src/framing.rs @@ -1,9 +1,11 @@ //! Four-byte big-endian length prefixes with caller-owned limits and errors. +//! The prefix counts the body only, not itself. use std::io; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; /// Read a frame. Reject the length before allocating or reading the body. +/// Not cancel safe: dropping the future mid-frame loses the stream position. pub async fn read( reader: &mut R, max_bytes: usize, @@ -11,11 +13,7 @@ pub async fn read( ) -> io::Result> { let mut prefix = [0; 4]; reader.read_exact(&mut prefix).await?; - let len = u32::from_be_bytes(prefix) as usize; - if len > max_bytes { - return Err(oversize(len)); - } - let mut body = vec![0; len]; + let mut body = vec![0; body_len(prefix, max_bytes, oversize)?]; reader.read_exact(&mut body).await?; Ok(body) } @@ -27,12 +25,58 @@ pub async fn write( max_bytes: usize, oversize: impl FnOnce(usize) -> io::Error, ) -> io::Result<()> { - let len = body.len(); - if len > max_bytes || len > u32::MAX as usize { + writer + .write_all(&prefix(body, max_bytes, oversize)?) + .await?; + writer.write_all(body).await +} + +/// Blocking [`read`]. +pub fn read_sync( + reader: &mut R, + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result> { + let mut prefix = [0; 4]; + reader.read_exact(&mut prefix)?; + let mut body = vec![0; body_len(prefix, max_bytes, oversize)?]; + reader.read_exact(&mut body)?; + Ok(body) +} + +/// Blocking [`write`]. +pub fn write_sync( + writer: &mut W, + body: &[u8], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result<()> { + writer.write_all(&prefix(body, max_bytes, oversize)?)?; + writer.write_all(body) +} + +fn body_len( + prefix: [u8; 4], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result { + let len = u32::from_be_bytes(prefix) as usize; + if len > max_bytes { return Err(oversize(len)); } - writer.write_all(&(len as u32).to_be_bytes()).await?; - writer.write_all(body).await + Ok(len) +} + +fn prefix( + body: &[u8], + max_bytes: usize, + oversize: impl FnOnce(usize) -> io::Error, +) -> io::Result<[u8; 4]> { + let len = body.len(); + match u32::try_from(len) { + Ok(wire) if len <= max_bytes => Ok(wire.to_be_bytes()), + _ => Err(oversize(len)), + } } #[cfg(test)] @@ -77,4 +121,25 @@ mod tests { assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); } } + + #[test] + fn sync_and_async_frames_share_the_wire_format() { + let mut wire = Vec::new(); + write_sync(&mut wire, b"abc", 3, oversize).unwrap(); + assert_eq!(wire, b"\0\0\0\x03abc"); + assert_eq!( + read_sync(&mut wire.as_slice(), 3, oversize).unwrap(), + b"abc" + ); + let error = write_sync(&mut Vec::new(), b"body", 3, oversize).unwrap_err(); + assert_eq!(error.to_string(), "too large: 4"); + let mut reader = &b"\0\0\0\x04body"[..]; + let error = read_sync(&mut reader, 3, oversize).unwrap_err(); + assert_eq!(error.to_string(), "too large: 4"); + assert_eq!(reader, b"body"); + for end in 0..wire.len() { + let error = read_sync(&mut &wire[..end], 3, oversize).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + } + } } From 0128adbbee314e0380067305aaf058bfa7c006fc Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:09:45 -0800 Subject: [PATCH 3/3] refactor(harness-sdk): parse the tool manifest with one decoder The shared module still held two decoders for ENGRAM_TOOLS: serde for Claude and a hand-written parser for Codex, chosen by a ToolProvider argument, with a generic ManifestTool and a private ClaudeBindings shim. Both decode the same orchestrator type, where every binding is an optional string. Use one serde decoder for both harnesses and remove ToolProvider, the generic parameter, and the shim. A non-string binding for the other provider now makes the manifest invalid. The orchestrator never sends one. Co-Authored-By: Claude Opus 5.5 --- crates/engram-harness-claude/src/main.rs | 22 +- crates/engram-harness-codex/src/main.rs | 20 +- .../engram-harness-sdk/src/tool_manifest.rs | 195 +++++------------- 3 files changed, 65 insertions(+), 172 deletions(-) diff --git a/crates/engram-harness-claude/src/main.rs b/crates/engram-harness-claude/src/main.rs index abdcd15fb..f92834bac 100644 --- a/crates/engram-harness-claude/src/main.rs +++ b/crates/engram-harness-claude/src/main.rs @@ -53,7 +53,7 @@ mod adapter { use engram_harness_sdk::browser_view; use engram_harness_sdk::questions::{Answers, Question}; use engram_harness_sdk::state::StateDir; - use engram_harness_sdk::tool_manifest::{manifest_from_env, ToolProvider}; + use engram_harness_sdk::tool_manifest::manifest_from_env; #[cfg(test)] use engram_harness_sdk::tool_manifest::{ parse_tool_manifest, with_browser_view, NativeBindings, @@ -355,7 +355,7 @@ mod adapter { .init(); let mut cli = Cli::parse(); - cli.tool_manifest = manifest_from_env(ToolProvider::Claude); + cli.tool_manifest = manifest_from_env(); // Materialise the resolved claude binary path so the rest of // the code can treat `cli.claude_bin` as a known value. cli.claude_bin = Some(resolve_claude_bin(cli.claude_bin.as_deref())); @@ -1027,11 +1027,10 @@ mod adapter { } pub(super) fn native_roundtrip_names() -> std::collections::HashSet { - let mut names: std::collections::HashSet = - super::manifest_from_env(super::ToolProvider::Claude) - .iter() - .filter_map(|tool| tool.native_bindings.claude.clone()) - .collect(); + let mut names: std::collections::HashSet = super::manifest_from_env() + .iter() + .filter_map(|tool| tool.native_bindings.claude.clone()) + .collect(); names.insert("AskUserQuestion".to_string()); names } @@ -1208,7 +1207,6 @@ mod adapter { pub mod mcp_bridge { use super::{ browser_view, injected_tools, manifest_from_env, BufReader, StateDir, ToolManifest, - ToolProvider, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -1230,7 +1228,7 @@ mod adapter { } pub async fn run() -> std::process::ExitCode { - let manifest = manifest_from_env(ToolProvider::Claude); + let manifest = manifest_from_env(); let socket_path = std::env::var_os("ENGRAM_MCP_SOCK") .filter(|value| !value.is_empty()) .map(PathBuf::from) @@ -4840,7 +4838,7 @@ mod adapter { .join(format!("engram-mcp-config-test-{}", uuid::Uuid::new_v4())); tokio::fs::create_dir_all(&dir).await.unwrap(); let path = dir.join("mcp-config.json"); - let manifest = parse_tool_manifest(ToolProvider::Claude, + let manifest = parse_tool_manifest( r#"[ {"name":"save_memory","description":"Save it","inputSchema":{"type":"object"},"execution":"sync","nativeBindings":{}}, {"name":"ask_user_question","description":"Ask","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"claude":"AskUserQuestion"}} @@ -4872,7 +4870,7 @@ mod adapter { }) ); - let native_only = parse_tool_manifest(ToolProvider::Claude, + let native_only = parse_tool_manifest( r#"[{"name":"ask_user_question","description":"Ask","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"claude":"AskUserQuestion"}}]"#, ) .unwrap(); @@ -4887,7 +4885,7 @@ mod adapter { } fn mcp_fixture_manifest() -> ToolManifest { - parse_tool_manifest(ToolProvider::Claude, + parse_tool_manifest( r#"[ {"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object","properties":{"text":{"type":"string"}}},"execution":"sync","nativeBindings":{}}, {"name":"ask_user_question","description":"Ask","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"claude":"AskUserQuestion"}} diff --git a/crates/engram-harness-codex/src/main.rs b/crates/engram-harness-codex/src/main.rs index 53b06e8d1..40d29f305 100644 --- a/crates/engram-harness-codex/src/main.rs +++ b/crates/engram-harness-codex/src/main.rs @@ -13,9 +13,7 @@ use engram_harness_sdk::browser_view; use engram_harness_sdk::parked::{ParkedCall, ParkedCallKind, ParkedCallStore}; use engram_harness_sdk::questions::{Answers, Question, QuestionOption}; use engram_harness_sdk::state::StateDir; -use engram_harness_sdk::tool_manifest::{ - manifest_from_env, ToolExecution, ToolManifest, ToolProvider, -}; +use engram_harness_sdk::tool_manifest::{manifest_from_env, ToolExecution, ToolManifest}; #[cfg(test)] use engram_harness_sdk::tool_manifest::{parse_tool_manifest, with_browser_view}; use engram_harness_sdk::{emit, Channels, ConnectionConfig, QueuedPrompt}; @@ -124,7 +122,7 @@ async fn main() -> ExitCode { ) .init(); let mut cli = Cli::parse(); - cli.tool_manifest = manifest_from_env(ToolProvider::Codex); + cli.tool_manifest = manifest_from_env(); if !((cli.connect.is_some()) ^ (cli.port.is_some())) { tracing::error!("provide exactly one of --connect or --port"); return ExitCode::from(2); @@ -2683,14 +2681,14 @@ done codex_bin: Some(codex_bin), state_dir, codex_home: None, - tool_manifest: manifest_from_env(ToolProvider::Codex), + tool_manifest: manifest_from_env(), test_api_key: Some("test-api-key".into()), test_credential_control: None, } } fn native_question_manifest() -> ToolManifest { - parse_tool_manifest(ToolProvider::Codex, + parse_tool_manifest( r#"[{"name":"ask_user_question","description":"Ask the user one or more structured questions.","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{"codex":"requestUserInput"}}]"#, ) .unwrap() @@ -3027,7 +3025,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-1","tool":"save_memory","arguments":{"text":"remember this"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, _) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, + cli.tool_manifest = parse_tool_manifest( r#"[{"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); @@ -3137,7 +3135,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-plan","tool":"exit_plan_mode","arguments":{"plan":"draft plan"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, record) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, + cli.tool_manifest = parse_tool_manifest( r#"[{"name":"exit_plan_mode","description":"Present the plan","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); @@ -3228,7 +3226,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-plan","tool":"exit_plan_mode","arguments":{"plan":"draft"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, record) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, + cli.tool_manifest = parse_tool_manifest( r#"[{"name":"exit_plan_mode","description":"Present the plan","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); @@ -3341,7 +3339,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-1","tool":"save_memory","arguments":{"text":"remember this"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, record) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, + cli.tool_manifest = parse_tool_manifest( r#"[{"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object"},"execution":"sync","nativeBindings":{}}]"#, ) .unwrap(); @@ -3636,7 +3634,7 @@ done let tool_call = r#"{"id":77,"method":"item/tool/call","params":{"callId":"call-1","tool":"save_memory","arguments":{"text":"remember this"},"threadId":"t1","turnId":"turn-1"}}"#; let (script, _) = write_fake_codex(&[tool_call]).await; let mut cli = test_cli(script); - cli.tool_manifest = parse_tool_manifest(ToolProvider::Codex, + cli.tool_manifest = parse_tool_manifest( r#"[{"name":"save_memory","description":"Save a memory","inputSchema":{"type":"object"},"execution":"deferred","nativeBindings":{}}]"#, ) .unwrap(); diff --git a/crates/engram-harness-sdk/src/tool_manifest.rs b/crates/engram-harness-sdk/src/tool_manifest.rs index c23ac099a..f78906422 100644 --- a/crates/engram-harness-sdk/src/tool_manifest.rs +++ b/crates/engram-harness-sdk/src/tool_manifest.rs @@ -5,15 +5,16 @@ use serde_json::Value; pub type ToolManifest = Vec; +/// One entry of the orchestrator's `ENGRAM_TOOLS` manifest. #[derive(Clone, Debug, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ManifestTool { +pub struct ManifestTool { pub name: String, pub description: String, pub input_schema: Value, pub execution: ToolExecution, #[serde(default)] - pub native_bindings: B, + pub native_bindings: NativeBindings, } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] @@ -23,110 +24,25 @@ pub enum ToolExecution { Deferred, } +/// The provider-native tool that stands in for a manifest tool. #[derive(Clone, Debug, Default, serde::Deserialize)] pub struct NativeBindings { pub claude: Option, pub codex: Option, } -#[derive(Default, serde::Deserialize)] -struct ClaudeBindings { - claude: Option, +pub fn parse_tool_manifest(raw: &str) -> serde_json::Result { + serde_json::from_str(raw) } -#[derive(Clone, Copy, Debug)] -pub enum ToolProvider { - Claude, - Codex, -} - -pub fn parse_tool_manifest(provider: ToolProvider, raw: &str) -> Result { - match provider { - ToolProvider::Claude => { - let tools: Vec> = - serde_json::from_str(raw).map_err(|error| error.to_string())?; - Ok(tools - .into_iter() - .map(|tool| ManifestTool { - name: tool.name, - description: tool.description, - input_schema: tool.input_schema, - execution: tool.execution, - native_bindings: NativeBindings { - claude: tool.native_bindings.claude, - codex: None, - }, - }) - .collect()) - } - ToolProvider::Codex => parse_codex_manifest(raw), - } -} - -fn parse_codex_manifest(raw: &str) -> Result { - let value: Value = serde_json::from_str(raw).map_err(|error| error.to_string())?; - let entries = value - .as_array() - .ok_or("ENGRAM_TOOLS must be a JSON array")?; - entries - .iter() - .map(|entry| { - let object = entry - .as_object() - .ok_or("ENGRAM_TOOLS entries must be objects")?; - let required_string = |field: &str| { - object - .get(field) - .and_then(Value::as_str) - .map(str::to_owned) - .ok_or_else(|| format!("ENGRAM_TOOLS entry missing string {field}")) - }; - let execution = match required_string("execution")?.as_str() { - "sync" => ToolExecution::Sync, - "deferred" => ToolExecution::Deferred, - other => return Err(format!("invalid ENGRAM_TOOLS execution {other}")), - }; - let codex_native_binding = match object.get("nativeBindings") { - None => None, - Some(Value::Object(bindings)) => match bindings.get("codex") { - None | Some(Value::Null) => None, - Some(Value::String(binding)) => Some(binding.clone()), - Some(_) => { - return Err("ENGRAM_TOOLS nativeBindings.codex must be a string".to_string()) - } - }, - Some(_) => return Err("ENGRAM_TOOLS nativeBindings must be an object".to_string()), - }; - Ok(ManifestTool { - name: required_string("name")?, - description: required_string("description")?, - input_schema: object - .get("inputSchema") - .cloned() - .ok_or("ENGRAM_TOOLS entry missing inputSchema")?, - execution, - native_bindings: NativeBindings { - codex: codex_native_binding, - ..Default::default() - }, - }) - }) - .collect() -} - -pub fn manifest_from_env(provider: ToolProvider) -> ToolManifest { +/// The `ENGRAM_TOOLS` manifest plus the built-in browser tool. An invalid +/// manifest exposes no injected tools. +pub fn manifest_from_env() -> ToolManifest { let manifest = match std::env::var("ENGRAM_TOOLS") { - Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(provider, &raw) { + Ok(raw) if !raw.trim().is_empty() => match parse_tool_manifest(&raw) { Ok(manifest) => manifest, Err(error) => { - match provider { - ToolProvider::Claude => { - tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no injected tools") - } - ToolProvider::Codex => { - tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no dynamic tools") - } - } + tracing::error!(%error, "invalid ENGRAM_TOOLS manifest; exposing no injected tools"); Vec::new() } }, @@ -165,71 +81,52 @@ mod tests { } #[test] - fn manifests_keep_each_providers_native_binding() { - for provider in [ToolProvider::Claude, ToolProvider::Codex] { - let manifest = parse_tool_manifest(provider, &json!([tool()]).to_string()).unwrap(); - assert_eq!(manifest[0].name, "ask"); - assert_eq!(manifest[0].execution, ToolExecution::Deferred); - match provider { - ToolProvider::Claude => assert_eq!( - manifest[0].native_bindings.claude.as_deref(), - Some("AskUserQuestion") - ), - ToolProvider::Codex => assert_eq!( - manifest[0].native_bindings.codex.as_deref(), - Some("requestUserInput") - ), - } - } + fn manifests_keep_every_providers_native_binding() { + let manifest = parse_tool_manifest(&json!([tool()]).to_string()).unwrap(); + assert_eq!(manifest[0].name, "ask"); + assert_eq!(manifest[0].execution, ToolExecution::Deferred); + assert_eq!( + manifest[0].native_bindings.claude.as_deref(), + Some("AskUserQuestion") + ); + assert_eq!( + manifest[0].native_bindings.codex.as_deref(), + Some("requestUserInput") + ); } #[test] - fn only_the_selected_providers_binding_is_validated() { - for (provider, other, selected) in [ - (ToolProvider::Claude, "codex", "claude"), - (ToolProvider::Codex, "claude", "codex"), - ] { + fn malformed_manifests_are_rejected() { + for raw in ["not json", "{}", "[null]", "[{}]"] { + assert!(parse_tool_manifest(raw).is_err()); + } + for field in ["name", "description", "execution", "nativeBindings"] { let mut entry = tool(); - entry["nativeBindings"][other] = json!(123); - assert!(parse_tool_manifest(provider, &json!([entry.clone()]).to_string()).is_ok()); - entry["nativeBindings"][selected] = json!(123); - assert!(parse_tool_manifest(provider, &json!([entry]).to_string()).is_err()); + entry[field] = json!(123); + assert!(parse_tool_manifest(&json!([entry]).to_string()).is_err()); } - } - - #[test] - fn malformed_manifests_are_rejected() { - for provider in [ToolProvider::Claude, ToolProvider::Codex] { - for raw in ["not json", "{}", "[null]", "[{}]"] { - assert!(parse_tool_manifest(provider, raw).is_err()); - } - for field in ["name", "description", "execution", "nativeBindings"] { - let mut entry = tool(); - entry[field] = json!(123); - assert!(parse_tool_manifest(provider, &json!([entry]).to_string()).is_err()); - } + for provider in ["claude", "codex"] { + let mut entry = tool(); + entry["nativeBindings"][provider] = json!(123); + assert!(parse_tool_manifest(&json!([entry]).to_string()).is_err()); } - let error = parse_tool_manifest(ToolProvider::Codex, "{}").unwrap_err(); - assert_eq!(error, "ENGRAM_TOOLS must be a JSON array"); + let mut entry = tool(); + entry.as_object_mut().unwrap().remove("inputSchema"); + assert!(parse_tool_manifest(&json!([entry]).to_string()).is_err()); } #[test] - fn optional_bindings_and_schema_keep_provider_decode_rules() { + fn bindings_are_optional() { let mut entry = tool(); entry.as_object_mut().unwrap().remove("nativeBindings"); - for provider in [ToolProvider::Claude, ToolProvider::Codex] { - let manifest = - parse_tool_manifest(provider, &json!([entry.clone()]).to_string()).unwrap(); - assert!(manifest[0].native_bindings.claude.is_none()); - assert!(manifest[0].native_bindings.codex.is_none()); - } - entry.as_object_mut().unwrap().remove("inputSchema"); - let raw = json!([entry]).to_string(); - assert!(parse_tool_manifest(ToolProvider::Claude, &raw).is_err()); - assert_eq!( - parse_tool_manifest(ToolProvider::Codex, &raw).unwrap_err(), - "ENGRAM_TOOLS entry missing inputSchema" - ); + let manifest = parse_tool_manifest(&json!([entry]).to_string()).unwrap(); + assert!(manifest[0].native_bindings.claude.is_none()); + assert!(manifest[0].native_bindings.codex.is_none()); + let mut entry = tool(); + entry["nativeBindings"] = json!({"codex": null, "other": {"x": 1}}); + let manifest = parse_tool_manifest(&json!([entry]).to_string()).unwrap(); + assert!(manifest[0].native_bindings.claude.is_none()); + assert!(manifest[0].native_bindings.codex.is_none()); } #[test]