repositories / smith
smith
There are many coding harnesses - but this one is fast
owned by bugabinga
smith-harness/src/rpc.rs
RawFile outline
- RpcState line 13
- RpcState line 17
- new line 19
- RpcRequest line 28
- RpcResponse line 39
- RpcResponse line 47
- to_line line 53
- merge line 66
- handle_line line 79
- line_or_empty line 115
- dispatch line 122
- run_prompt line 142
- result line 188
- error line 195
- tests line 202
- state line 210
- lines line 218
- ping_correlates_and_unknown_methods_error_with_the_same_id line 225
- prompt_streams_deltas_and_assembles_the_final_message line 238
- blank_lines_are_ignored line 262
//! LF-delimited JSON-RPC over standard input and output.
//!
//! Standard output carries protocol records only. Request IDs are preserved
//! on every response, streaming deltas are ordered between a start and an
//! authoritative end record, and unknown commands return correlated errors.
use smith::error::Result;
use smith_core::agent::{Agent, AgentEvent};
use std::sync::Arc;
use std::sync::Mutex;
/// The shared RPC session state.
pub struct RpcState {
agent: Arc<Mutex<Agent>>,
}
impl RpcState {
/// State over one agent.
#[must_use]
pub fn new(agent: Agent) -> Self {
Self {
agent: Arc::new(Mutex::new(agent)),
}
}
}
/// One incoming request line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RpcRequest {
/// Correlation ID; echoed on every response for this request.
pub id: serde_json::Value,
/// Command name.
pub method: String,
/// Command parameters, when present.
pub params: serde_json::Value,
}
/// One outgoing response line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RpcResponse {
/// Correlation ID of the owning request.
pub id: serde_json::Value,
/// Record payload: result or error.
pub record: serde_json::Value,
}
impl RpcResponse {
/// Serialize as one LF-terminated JSON line.
///
/// # Errors
///
/// Returns a serialization fault when the record cannot encode.
pub fn to_line(&self) -> Result<String> {
let mut value = serde_json::json!({"id": self.id});
merge(&mut value, &self.record);
let mut line =
serde_json::to_string(&value).map_err(|e| smith::error::SmithError::Session {
code: "RPC_ENCODE".to_string(),
message: e.to_string(),
})?;
line.push('\n');
Ok(line)
}
}
fn merge(target: &mut serde_json::Value, patch: &serde_json::Value) {
if let (Some(target), Some(patch)) = (target.as_object_mut(), patch.as_object()) {
for (key, value) in patch {
target.insert(key.clone(), value.clone());
}
}
}
/// Handle one input line, producing zero or more response lines.
///
/// # Errors
///
/// Returns an encode fault only when a response cannot serialize.
#[allow(clippy::print_stdout)]
pub fn handle_line(state: &RpcState, line: &str) -> Vec<String> {
let trimmed = line.trim();
if trimmed.is_empty() {
return Vec::new();
}
let parsed: serde_json::Value = match serde_json::from_str(trimmed) {
Ok(value) => value,
Err(err) => {
let response = RpcResponse {
id: serde_json::Value::Null,
record: serde_json::json!({
"error": {"code": "PARSE", "message": err.to_string()},
}),
};
return line_or_empty(&response);
}
};
let request = RpcRequest {
id: parsed.get("id").cloned().unwrap_or(serde_json::Value::Null),
method: parsed
.get("method")
.and_then(serde_json::Value::as_str)
.unwrap_or_default()
.to_string(),
params: parsed
.get("params")
.cloned()
.unwrap_or(serde_json::json!({})),
};
dispatch(state, request)
.into_iter()
.filter_map(|response| line_or_empty(&response).into_iter().next())
.collect()
}
fn line_or_empty(response: &RpcResponse) -> Vec<String> {
response
.to_line()
.map(|line| vec![line])
.unwrap_or_default()
}
fn dispatch(state: &RpcState, request: RpcRequest) -> Vec<RpcResponse> {
match request.method.as_str() {
"ping" => vec![result(&request, serde_json::json!({"pong": true}))],
"prompt" => run_prompt(state, &request),
"abort" => {
if let Ok(agent) = state.agent.lock() {
agent.cancel_handle().cancel();
}
vec![result(&request, serde_json::json!({"aborting": true}))]
}
"status" => vec![result(&request, serde_json::json!({"settled": true}))],
other => vec![RpcResponse {
id: request.id,
record: serde_json::json!({
"error": {"code": "METHOD_UNKNOWN", "message": format!("unknown method {other}")},
}),
}],
}
}
fn run_prompt(state: &RpcState, request: &RpcRequest) -> Vec<RpcResponse> {
let input = request
.params
.get("input")
.and_then(serde_json::Value::as_str)
.unwrap_or_default()
.to_string();
let mut responses = vec![result(request, serde_json::json!({"event": "start"}))];
let Ok(mut agent) = state.agent.lock() else {
return vec![error(request, "STATE", "agent state unavailable")];
};
// Drive the turn synchronously; deltas replay from the recorded events
// between the start and the authoritative end record.
match agent.run_turn(&input) {
Ok(outcome) => {
for event in &outcome.events {
if let AgentEvent::Streamed {
event: smith::stream::StreamEvent::TextDelta { delta, .. },
} = event
{
responses.push(result(
request,
serde_json::json!({"event": "delta", "text": delta}),
));
}
}
responses.push(result(
request,
serde_json::json!({
"event": "end",
"text": outcome.text,
"reason": format!("{:?}", outcome.reason),
"cost": {
"input_tokens": outcome.cost.input_tokens,
"output_tokens": outcome.cost.output_tokens,
},
}),
));
}
Err(err) => {
responses.push(error(request, "TURN_FAILED", &err.to_string()));
}
}
responses
}
fn result(request: &RpcRequest, record: serde_json::Value) -> RpcResponse {
RpcResponse {
id: request.id.clone(),
record,
}
}
fn error(request: &RpcRequest, code: &str, message: &str) -> RpcResponse {
RpcResponse {
id: request.id.clone(),
record: serde_json::json!({"error": {"code": code, "message": message}}),
}
}
#[cfg(test)]
#[expect(clippy::unwrap_used, reason = "rpc tests assert on scripted lines")]
mod tests {
use super::*;
use crate::mock_text_reply;
use crate::runtime::{RuntimeConfig, build_agent};
use smith_core::tools::ToolSession;
fn state() -> RpcState {
let dir = std::env::temp_dir().join(format!("smith_rpc_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let config = RuntimeConfig::mock(dir, vec![mock_text_reply("hello world")]);
RpcState::new(build_agent(&config).unwrap())
}
fn lines(state: &RpcState, input: &str) -> Vec<serde_json::Value> {
handle_line(state, input)
.iter()
.map(|line| serde_json::from_str(line.trim()).unwrap())
.collect()
}
#[test]
fn ping_correlates_and_unknown_methods_error_with_the_same_id() {
let state = state();
let pong = &lines(&state, r#"{"id": 7, "method": "ping"}"#)[0];
assert_eq!(pong["id"], 7);
assert_eq!(pong["pong"], true);
let unknown = &lines(&state, r#"{"id": "abc", "method": "explode"}"#)[0];
assert_eq!(unknown["id"], "abc");
assert_eq!(unknown["error"]["code"], "METHOD_UNKNOWN");
let malformed = &lines(&state, "not json")[0];
assert_eq!(malformed["error"]["code"], "PARSE");
}
#[test]
fn prompt_streams_deltas_and_assembles_the_final_message() {
let state = state();
let records = lines(
&state,
r#"{"id": 1, "method": "prompt", "params": {"input": "hi"}}"#,
);
assert_eq!(records[0]["event"], "start");
assert_eq!(records[1]["event"], "delta");
assert_eq!(records[1]["text"], "hello world");
let end = records.last().unwrap();
assert_eq!(end["event"], "end");
assert_eq!(end["text"], "hello world");
// The end record is authoritative and carries the whole message.
let assembled: String = records
.iter()
.filter(|record| record["event"] == "delta")
.filter_map(|record| record["text"].as_str().map(str::to_string))
.collect();
assert_eq!(assembled, end["text"].as_str().unwrap_or_default());
// Every record carries the request id.
assert!(records.iter().all(|record| record["id"] == 1));
}
#[test]
fn blank_lines_are_ignored() {
let state = state();
assert!(handle_line(&state, " ").is_empty());
let _ = ToolSession::new(std::env::temp_dir());
}
}