feat(harness): typed http effect, provider records durable, single engine owner
456de5fbcdc23841a8e41cac2073753e79aafb42
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 387f8cbbc90c
There are many coding harnesses - but this one is fast
456de5fbcdc23841a8e41cac2073753e79aafb42
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+577 / −164 text lines
deleted file mode 100644+0 / −71 text lines
---name: prototypedescription: Verify specs by proving or disproving claims with isolated coding prototypes.argument-hint: <spec or claim to prove>---# PioneerYou are a coding agent that validates specifications with small, disposableprototypes.## MissionProve whether spec claims are implementable before production code is written.Use prototypes to expose missing interfaces, bad assumptions, API friction,dependency risks, test gaps, and contradictory requirements.Focus on $ARGUMENTS.## Operating Rules- Read `AGENTS.md` first, then relevant specs/design docs.- Build only isolated proofs under `prototypes/` or a temporary directory.- Do not edit production crates or canonical specs unless explicitly asked.- Keep prototypes tiny: one claim, one risk, one repro.- Prefer compile checks, focused tests, and minimal runnable examples over broad implementation.- Delete or mark throwaway work when done unless user asks to keep it.- Report spec defects from prototype evidence, not taste.## Rust Quality Bar- Verify predictable APIs, type safety, and dependency fit.- Check error paths use explicit results, not casual `unwrap`, `expect`, or `panic`.- Encode invariants with types/newtypes where the spec requires domain safety.- Test behavior boundaries and failure modes.- Benchmark only when performance claims exist.## Output ContractReturn Markdown, not JSON.Use this shape:```markdown## Statuscomplete | blocked | failed## Proved- spec claims supported by prototype evidence## Disproved- spec claims contradicted by prototype evidence## Spec Issues- `path` - Issue: what spec must clarify or change - Evidence: prototype path, command, compiler/test result - Severity: P0 | P1 | P2 | P3## Prototype Artifacts- paths created## Commands- commands run## Next Steps- concrete spec or design actions```deleted file mode 100644+0 / −46 text lines
---name: specdescription: Create or refine smith spec docs. No code.argument-hint: "[topic]"---Create or edit `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md` only.Only markdown.No `.rs`, `.toml`, scripts.Focus on $ARGUMENTS.Spec content must state desired project behavior:- purpose,- interfaces,- data types,- error handling,- test strategy.Read `.system/MISSION.md`, `.system/RULES.md`, `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md`, and related `.system/research/` docs first.Stay consistent with `.system/RULES.md`.Stop and ask on architectural decisions.Do not guess.End with Markdown, not JSON:```markdown## Statuscomplete | blocked | needs-user-input## Summary...## Files- `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md`## Actions- Updated SPEC## Not Done- ...## Next Steps- ...```+1 / −1 text lines
+2 / −1 text lines
"reqwest",+0 / −1 text lines
+112 / −40 text lines
use smith::http::{HttpExchange, HttpExecutorRef, HttpHeader, HttpMethod};use smith::provider::{ProviderRequest, StreamFn};use smith::provider::{ProviderRequest, RecordSpool, StreamFn}; let client = reqwest::blocking::Client::new(); let mut prepared = client .post(endpoint_url(endpoint)) .json(&body) .timeout(std::time::Duration::from_secs(600)); for (name, value) in endpoint_headers(endpoint) { prepared = prepared.header(name, value); } let response = prepared .send() .map_err(|e| transport_fault(&e.to_string()))?; let status = response.status(); if !status.is_success() { let body = response.text().unwrap_or_default(); let headers = endpoint_headers(endpoint) .into_iter() .map(|(name, value)| HttpHeader { name, value }) .collect::<Vec<_>>(); let exchange = HttpExchange { method: HttpMethod::Post, url: endpoint_url(endpoint), headers: headers.clone(), body: serde_json::to_vec(&body).unwrap_or_default(), }; spool_record( &endpoint.records, serde_json::json!({ "phase": "intent", "method": exchange.method.as_str(), "url": exchange.url, "headers": smith::http::redact_headers(&headers), "request_bytes": exchange.body.len(), }), ); let response = endpoint.executor.execute(exchange, cancel.clone())?; if !(200..300).contains(&response.head.status) { let mut body = Vec::new(); for chunk in response.chunks { body.extend_from_slice(&chunk.bytes); } let message = String::from_utf8_lossy(&body).into_owned(); spool_record( &endpoint.records, serde_json::json!({ "phase": "outcome", "status": response.head.status, "response_bytes": body.len(), "outcome": "failed", }), ); 401 | 403 => ProviderFault::Authentication { message: body }, 401 | 403 => ProviderFault::Authentication { message }, executor: std::sync::Arc::new(RefusesExecutor), records: smith::provider::new_record_spool(), } } /// Body-builder tests never execute exchanges. struct RefusesExecutor; impl smith::http::HttpExecutor for RefusesExecutor { fn execute( &self, _exchange: smith::http::HttpExchange, _cancel: smith::tool::CancelHandle, ) -> smith::error::Result<smith::http::HttpResponse> { Err(SmithError::Provider { fault: ProviderFault::Invalid { field: None, message: "executor must not run in body tests".to_string(), }, })+2 / −0 text lines
+44 / −0 text lines
Self::with_provider_records(stream, tools, model, None) } /// An agent whose provider rounds drain redacted effect records into /// the session after each round. #[must_use] pub fn with_provider_records( stream: StreamFn, tools: ToolSession, model: impl Into<String>, records: Option<smith::provider::RecordSpool>, ) -> Self { provider_records: records, self.drain_provider_records()?; /// Drain spooled provider effect records into the session as metadata /// entries; every round's records land before its assistant message. fn drain_provider_records(&mut self) -> Result<()> { let Some(spool) = self.provider_records.clone() else { return Ok(()); }; let drained = spool .lock() .map(|mut guard| std::mem::take(&mut *guard)) .unwrap_or_default(); for detail in drained { let entry = crate::session::Entry::new( self.tools.session.selected_id(), crate::session::EntryContent::Meta { kind: crate::session::PROVIDER_HTTP_KIND.to_string(), detail, }, ); if let Some(writer) = self.tools.writer_mut() { writer.append_frame(&crate::frame::Frame::Known { entry: entry.clone(), })?; } self.tools.session.append_to_active(entry); } Ok(()) }+3 / −0 text lines
+4 / −0 text lines
new file mode 100644+136 / −0 text lines
//! Host-owned HTTP engine over the `smith::http` vocabulary.//!//! One executor serves provider traffic today and plugin net-scope//! effects later; every call is bounded, cancellable, and recordable.use smith::error::{ProviderFault, Result, SmithError};use smith::http::{HttpChunk, HttpExchange, HttpExecutor, HttpExecutorRef, HttpHead, HttpResponse};use smith::tool::CancelHandle;use std::io::Read;use std::sync::Arc;use std::sync::mpsc;use std::time::Duration;/// Largest accepted response body, in bytes.pub const MAX_BODY_BYTES: u64 = 64 * 1024 * 1024;/// Largest accepted single request body, in bytes.pub const MAX_REQUEST_BYTES: usize = 16 * 1024 * 1024;/// Timeout for the response head.pub const HEAD_TIMEOUT: Duration = Duration::from_secs(120);/// Deadline for one chunk gap.pub const CHUNK_TIMEOUT: Duration = Duration::from_secs(300);/// `reqwest`-backed executor; the only HTTP engine in the workspace.#[derive(Clone)]pub struct ReqwestHttpExecutor { client: reqwest::blocking::Client,}impl ReqwestHttpExecutor { /// A default executor with head and chunk timeouts. #[must_use] pub fn new() -> Self { Self { client: reqwest::blocking::Client::builder() .timeout(HEAD_TIMEOUT + CHUNK_TIMEOUT) .build() .unwrap_or_default(), } } /// Wrap an existing client, primarily for tests. #[must_use] pub const fn with_client(client: reqwest::blocking::Client) -> Self { Self { client } }}impl Default for ReqwestHttpExecutor { fn default() -> Self { Self::new() }}impl HttpExecutor for ReqwestHttpExecutor { fn execute(&self, exchange: HttpExchange, cancel: CancelHandle) -> Result<HttpResponse> { if exchange.body.len() > MAX_REQUEST_BYTES { return Err(bounded("request body exceeds the size bound")); } if cancel.is_cancelled() { return Err(SmithError::Cancelled); } let method = match exchange.method { smith::http::HttpMethod::Post => reqwest::Method::POST, }; let mut prepared = self .client .request(method, &exchange.url) .body(exchange.body.clone()) .timeout(HEAD_TIMEOUT); for header in &exchange.headers { prepared = prepared.header(&header.name, &header.value); } let mut response = prepared .send() .map_err(|e| transport_fault(&e.to_string()))?; let head = HttpHead { status: response.status().as_u16(), }; let (sender, receiver) = mpsc::channel(); let cancel_stream = cancel; std::thread::spawn(move || { let mut buffer = [0u8; 16 * 1024]; let mut total: u64 = 0; loop { if cancel_stream.is_cancelled() { return; } let read = match response.read(&mut buffer) { Ok(0) | Err(_) => return, Ok(read) => read, }; total += u64::try_from(read).unwrap_or(u64::MAX); if total > MAX_BODY_BYTES { return; } if sender .send(HttpChunk { bytes: buffer[..read].to_vec(), }) .is_err() { return; } } }); Ok(HttpResponse { head, chunks: receiver, }) }}/// The shared default executor.#[must_use]pub fn default_executor() -> HttpExecutorRef { Arc::new(ReqwestHttpExecutor::new())}fn transport_fault(message: &str) -> SmithError { SmithError::Provider { fault: ProviderFault::Transient { message: message.to_string(), }, }}fn bounded(message: &str) -> SmithError { SmithError::Provider { fault: ProviderFault::Transient { message: format!("http effect: {message}"), }, }}+1 / −0 text lines
+20 / −4 text lines
use smith::provider::RecordSpool; api_key: None, let tools = ToolSession::with_session(config.workdir.clone(), opened.session, opened.writer); Some(records),fn resolve_stream(provider: &RuntimeProvider) -> Result<StreamFn> { let api_key = resolve_credential(kind)?; api_key: None,new file mode 100644+126 / −0 text lines
//! End-to-end provider traffic through the typed HTTP effect.//! Integration tests drive a real socket, a real executor, and the//! durable session store.#![expect(clippy::unwrap_used, reason = "integration tests assert on outcomes")]use smith_harness::runtime::{RuntimeConfig, RuntimeProvider, build_agent};use std::io::{Read, Write};use std::net::TcpListener;use smith_core::frame::{Frame, read_frames};use smith_core::session::{EntryContent, PROVIDER_HTTP_KIND};/// Serve one OpenAI-shaped SSE response and return the port.fn spawn_sse_server(body: &'static str) -> u16 { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); std::thread::spawn(move || { let (mut socket, _) = listener.accept().unwrap(); let mut buffer = [0u8; 8192]; let _ = socket.read(&mut buffer); let response = format!( "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}" ); socket.write_all(response.as_bytes()).unwrap(); }); port}fn provider_http_records(path: &std::path::Path) -> Vec<serde_json::Value> { let bytes = std::fs::read(path).unwrap(); let config = smith::config::Config::default_valid(); read_frames(&mut bytes.as_slice(), config.max_frame_bytes) .frames .into_iter() .filter_map(|frame| match frame { Frame::Known { entry } => match entry.content { EntryContent::Meta { kind, detail } if kind == PROVIDER_HTTP_KIND => Some(detail), _ => None, }, Frame::Unknown { .. } | smith_core::Frame::Header { .. } => None, }) .collect()}#[test]fn provider_round_trips_through_http_effect_with_durable_redacted_records() { let dir = std::env::temp_dir().join(format!("smith_http_effect_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"hello \"}}]}\n\n\ data: {\"choices\":[{\"delta\":{\"content\":\"world\"}}]}\n\n\ data: {\"choices\":[{\"finish_reason\":\"stop\",\"delta\":{}}],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2}}\n\n\ data: [DONE]\n\n"; let port = spawn_sse_server(sse); let session_path = dir.join("session.smh"); let config = RuntimeConfig { provider: RuntimeProvider::OpenAiCompatible { base_url: format!("http://127.0.0.1:{port}/v1"), model: "gpt-test".to_string(), }, workdir: dir.clone(), session_path: session_path.clone(), api_key: Some("sk-integration-secret".to_string()), }; let mut agent = build_agent(&config).unwrap(); let outcome = agent.run_turn("say it").unwrap(); assert_eq!(outcome.text, "hello world"); let records = provider_http_records(&session_path); assert_eq!(records.len(), 2, "intent and outcome records"); let intent = &records[0]; assert_eq!(intent["phase"], "intent"); assert_eq!( intent["url"], format!("http://127.0.0.1:{port}/v1/chat/completions") ); let headers = intent["headers"].as_array().unwrap(); let authorization = headers .iter() .find(|header| { header["name"] .as_str() .unwrap_or_default() .eq_ignore_ascii_case("authorization") }) .unwrap(); assert_eq!(authorization["value"], "<redacted>"); let outcome_record = &records[1]; assert_eq!(outcome_record["phase"], "outcome"); assert_eq!(outcome_record["status"], 200); assert_eq!(outcome_record["outcome"], "completed"); let _ = std::fs::remove_dir_all(&dir);}#[test]fn explicit_credential_wins_over_missing_env() { // No store, no env: only the explicit override can resolve. let dir = std::env::temp_dir().join(format!("smith_http_explicit_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let store = smith_ai::auth::AuthStore::at(dir.join("empty-store")); assert!( store .load(smith_ai::models::ProviderKind::Anthropic) .unwrap() .is_none() ); let config = RuntimeConfig { provider: RuntimeProvider::Anthropic { base_url: "https://example.test".to_string(), model: "m".to_string(), }, workdir: dir.clone(), session_path: dir.join("s.smh"), api_key: Some("sk-explicit".to_string()), }; let _agent = build_agent(&config).unwrap(); let _ = std::fs::remove_dir_all(&dir);}new file mode 100644+114 / −0 text lines
//! Typed HTTP effect vocabulary.//!//! The core defines the shape; exactly one engine crate provides the//! executor. Provider traffic flows through this boundary so every call//! can be bounded, cancelled, recorded, and replayed without any//! engine types leaking upward.use crate::error::Result;use crate::tool::CancelHandle;use std::sync::Arc;use std::sync::mpsc::Receiver;/// One HTTP header, ordered.#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct HttpHeader { /// Header name. pub name: String, /// Header value; credential-bearing values are recorded redacted. pub value: String,}/// A bounded request description.#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct HttpExchange { /// Request method. pub method: HttpMethod, /// Endpoint URL. pub url: String, /// Ordered headers. pub headers: Vec<HttpHeader>, /// Request body bytes, bounded by the executor. pub body: Vec<u8>,}/// Supported request methods.#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub enum HttpMethod { /// HTTP POST. Post,}impl HttpMethod { /// Wire representation. #[must_use] pub const fn as_str(self) -> &'static str { match self { Self::Post => "POST", } }}/// The response head, delivered before body chunks.#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct HttpHead { /// HTTP status code. pub status: u16,}/// One streaming body chunk.#[derive(Clone, Debug, PartialEq, Eq)]pub struct HttpChunk { /// Bytes received in order. pub bytes: Vec<u8>,}/// A streaming HTTP response: head first, chunks in order, end of channel/// means the body is complete.pub struct HttpResponse { /// Response head. pub head: HttpHead, /// Ordered body chunks; the channel closes at end of body. pub chunks: Receiver<HttpChunk>,}/// Executes [`HttpExchange`]s.////// Implementations apply timeouts, size bounds, and cooperative/// cancellation between chunks.pub trait HttpExecutor: Send + Sync { /// Execute one exchange. /// /// # Errors /// /// Returns a provider fault on transport failure, cancellation, or /// exceeded bounds. fn execute(&self, exchange: HttpExchange, cancel: CancelHandle) -> Result<HttpResponse>;}/// Shared executor handle.pub type HttpExecutorRef = Arc<dyn HttpExecutor>;/// Redact credential-bearing header values for records and diagnostics.////// Authorization and proxy-authorization values never appear in plaintext.#[must_use]pub fn redact_headers(headers: &[HttpHeader]) -> Vec<HttpHeader> { headers .iter() .map(|header| { let sensitive = matches!( header.name.to_ascii_lowercase().as_str(), "authorization" | "proxy-authorization" | "x-api-key" ); HttpHeader { name: header.name.clone(), value: if sensitive { "<redacted>".to_string() } else { header.value.clone() }, } }) .collect()}+2 / −0 text lines
+10 / −0 text lines
/// Redacted provider effect records spooled between the transport and the/// session writer.pub type RecordSpool = std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>>;/// A fresh empty spool.#[must_use]pub fn new_record_spool() -> RecordSpool { std::sync::Arc::new(std::sync::Mutex::new(Vec::new()))}