Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 11 additions & 21 deletions crates/engram-agentd/src/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}")))
}
Expand All @@ -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)]
Expand Down
1 change: 1 addition & 0 deletions crates/engram-egress-proto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 5 additions & 27 deletions crates/engram-egress-proto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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))
}
Expand All @@ -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
}

Expand All @@ -218,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))
}
Expand All @@ -237,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()
}

Expand Down
135 changes: 26 additions & 109 deletions crates/engram-harness-claude/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
#[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;
Expand All @@ -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<ManifestTool>;

#[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<String>,
}

fn parse_tool_manifest(raw: &str) -> serde_json::Result<ToolManifest> {
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<Item = &ManifestTool> {
manifest
.iter()
Expand Down Expand Up @@ -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<HarnessEvent>, 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
Expand Down Expand Up @@ -1920,7 +1852,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,
});
Expand Down Expand Up @@ -2251,31 +2183,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<String>,
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<String>,
}

/// 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 {
Expand Down Expand Up @@ -2562,8 +2469,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
Expand Down Expand Up @@ -2897,7 +2811,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"
);
Expand All @@ -2912,7 +2826,7 @@ mod adapter {
evt_tx,
s,
cli,
qp.prompt_id,
Some(qp.prompt_id),
&qp.text,
current_run_id,
)
Expand Down Expand Up @@ -3077,7 +2991,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,
});
Expand Down Expand Up @@ -3181,7 +3095,7 @@ mod adapter {
)
.await;
pending.push_back(QueuedPrompt {
prompt_id: Some(prompt_id),
prompt_id,
text,
mode,
});
Expand Down Expand Up @@ -3266,7 +3180,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;
Expand All @@ -3287,7 +3201,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 {
Expand Down Expand Up @@ -7284,6 +7198,7 @@ mod adapter {
execution: ToolExecution::Deferred,
native_bindings: NativeBindings {
claude: Some("AskUserQuestion".into()),
..Default::default()
},
}
}
Expand Down Expand Up @@ -8854,6 +8769,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]
Expand Down Expand Up @@ -9709,6 +9625,7 @@ mod tests {
execution: ToolExecution::Deferred,
native_bindings: NativeBindings {
claude: Some("ExitPlanMode".into()),
..Default::default()
},
}];
let deferred_names = deferred_tool_names(&manifest);
Expand Down
Loading
Loading