repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

feat(harness): typed http effect, provider records durable, single engine owner

456de5fbcdc23841a8e41cac2073753e79aafb42

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (17)

+577 / −164 text lines

Diff layout

.pi/prompts/prototype.md

Deleted
deleted file mode 100644

+0 / −71 text lines

1---
2name: prototype
3description: Verify specs by proving or disproving claims with isolated coding prototypes.
4argument-hint: <spec or claim to prove>
5---
6
7# Pioneer
8
9You are a coding agent that validates specifications with small, disposable
10prototypes.
12## Mission
14Prove whether spec claims are implementable before production code is written.
15Use prototypes to expose missing interfaces, bad assumptions, API friction,
16dependency risks, test gaps, and contradictory requirements.
18Focus on $ARGUMENTS.
20## Operating Rules
22- Read `AGENTS.md` first, then relevant specs/design docs.
23- Build only isolated proofs under `prototypes/` or a temporary directory.
24- Do not edit production crates or canonical specs unless explicitly asked.
25- Keep prototypes tiny:
26 one claim, one risk, one repro.
27- Prefer compile checks, focused tests, and minimal runnable examples over broad
28 implementation.
29- Delete or mark throwaway work when done unless user asks to keep it.
30- Report spec defects from prototype evidence, not taste.
32## Rust Quality Bar
34- Verify predictable APIs, type safety, and dependency fit.
35- Check error paths use explicit results, not casual `unwrap`, `expect`, or
36 `panic`.
37- Encode invariants with types/newtypes where the spec requires domain safety.
38- Test behavior boundaries and failure modes.
39- Benchmark only when performance claims exist.
41## Output Contract
43Return Markdown, not JSON.
45Use this shape:
47```markdown
48## Status
49complete | blocked | failed
51## Proved
52- spec claims supported by prototype evidence
54## Disproved
55- spec claims contradicted by prototype evidence
57## Spec Issues
58- `path`
59 - Issue: what spec must clarify or change
60 - Evidence: prototype path, command, compiler/test result
61 - Severity: P0 | P1 | P2 | P3
63## Prototype Artifacts
64- paths created
66## Commands
67- commands run
69## Next Steps
70- concrete spec or design actions
71```

.pi/prompts/spec.md

Deleted
deleted file mode 100644

+0 / −46 text lines

1---
2name: spec
3description: Create or refine smith spec docs. No code.
4argument-hint: "[topic]"
5---
6
7Create or edit `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md` only.
8Only markdown.
9No `.rs`, `.toml`, scripts.
11Focus on $ARGUMENTS.
13Spec content must state desired project behavior:
14- purpose,
15- interfaces,
16- data types,
17- error handling,
18- test strategy.
20Read `.system/MISSION.md`, `.system/RULES.md`, `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md`, and related `.system/research/` docs first.
21Stay consistent with `.system/RULES.md`.
23Stop and ask on architectural decisions.
24Do not guess.
26End with Markdown, not JSON:
28```markdown
29## Status
30complete | blocked | needs-user-input
32## Summary
33...
35## Files
36- `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md`
38## Actions
39- Updated SPEC
41## Not Done
42- ...
44## Next Steps
45- ...
46```

.system/plans/SMH-PLAN-PLUG0001-plugin-harness/index.md

Modified

+1 / −1 text lines

33type: plan
44title: "Sandboxed Plugin Harness"
55spec: SMH-SPEC-SPEC0001
6status: draft
6status: approved
77depends_on: []
88research: [SMH-RESEARCH-WASM0001]
99---

Cargo.lock

Modified

+2 / −1 text lines

14001400version = "0.1.0"
14011401dependencies = [
14021402 "futures",
1403 "reqwest",
14041403 "serde",
14051404 "serde_json",
14061405 "smith",
14381437version = "0.1.0"
14391438dependencies = [
14401439 "futures",
1440 "reqwest",
1441 "serde_json",
14411442 "smith",
14421443 "smith-ai",
14431444 "smith-core",

smith-ai/Cargo.toml

Modified

+0 / −1 text lines

1010[dependencies]
1111smith = { path = "../smith", version = "0.1.0" }
1212futures = { workspace = true }
13reqwest = { workspace = true }
1413serde = { workspace = true }
1514serde_json = { workspace = true }

smith-ai/src/transport.rs

Modified

+112 / −40 text lines

1212use crate::openai::OpenAiDecoder;
1313use futures::StreamExt;
1414use smith::error::{ProviderFault, Result, SmithError};
15use smith::http::{HttpExchange, HttpExecutorRef, HttpHeader, HttpMethod};
1516use smith::message::{ContentBlock, Role};
16use smith::provider::{ProviderRequest, StreamFn};
17use smith::provider::{ProviderRequest, RecordSpool, StreamFn};
1718use smith::tool::CancelHandle;
18use std::io::Read;
19use std::collections::VecDeque;
1920use std::sync::Arc;
22/// Where provider effect records spool until the agent drains them into
23/// the session.
24pub type ProviderRecordSpool = RecordSpool;
26fn spool_record(spool: &ProviderRecordSpool, record: serde_json::Value) {
27 if let Ok(mut guard) = spool.lock() {
28 guard.push(record);
29 }
30}
2132/// Vendor endpoint description for one model.
22#[derive(Clone, Debug, PartialEq, Eq)]
33#[derive(Clone)]
2334pub struct VendorEndpoint {
2435 /// Adapter family.
2536 pub kind: ProviderKind,
2940 pub model: String,
3041 /// Bearer or key credential value.
3142 pub api_key: String,
43 /// The host HTTP engine; provider traffic never posts directly.
44 pub executor: HttpExecutorRef,
45 /// Redacted effect records, drained by the agent into the session.
46 pub records: ProviderRecordSpool,
3449/// Build the vendor request body for one provider request.
380395 sender: &std::sync::mpsc::Sender<smith::provider::StreamItem>,
381396) -> Result<()> {
382397 let body = build_body(endpoint, request)?;
383 let client = reqwest::blocking::Client::new();
384 let mut prepared = client
385 .post(endpoint_url(endpoint))
386 .json(&body)
387 .timeout(std::time::Duration::from_secs(600));
388 for (name, value) in endpoint_headers(endpoint) {
389 prepared = prepared.header(name, value);
390 }
391 let response = prepared
392 .send()
393 .map_err(|e| transport_fault(&e.to_string()))?;
394 let status = response.status();
395 if !status.is_success() {
396 let body = response.text().unwrap_or_default();
398 let headers = endpoint_headers(endpoint)
399 .into_iter()
400 .map(|(name, value)| HttpHeader { name, value })
401 .collect::<Vec<_>>();
402 let exchange = HttpExchange {
403 method: HttpMethod::Post,
404 url: endpoint_url(endpoint),
405 headers: headers.clone(),
406 body: serde_json::to_vec(&body).unwrap_or_default(),
407 };
408 spool_record(
409 &endpoint.records,
410 serde_json::json!({
411 "phase": "intent",
412 "method": exchange.method.as_str(),
413 "url": exchange.url,
414 "headers": smith::http::redact_headers(&headers),
415 "request_bytes": exchange.body.len(),
416 }),
417 );
418 let response = endpoint.executor.execute(exchange, cancel.clone())?;
419 if !(200..300).contains(&response.head.status) {
420 let mut body = Vec::new();
421 for chunk in response.chunks {
422 body.extend_from_slice(&chunk.bytes);
423 }
424 let message = String::from_utf8_lossy(&body).into_owned();
425 spool_record(
426 &endpoint.records,
427 serde_json::json!({
428 "phase": "outcome",
429 "status": response.head.status,
430 "response_bytes": body.len(),
431 "outcome": "failed",
432 }),
433 );
397434 return Err(SmithError::Provider {
398 fault: match status.as_u16() {
435 fault: match response.head.status {
399436 429 => ProviderFault::RateLimit {
400437 retry_after_ms: None,
401438 },
402 401 | 403 => ProviderFault::Authentication { message: body },
439 401 | 403 => ProviderFault::Authentication { message },
403440 400 | 404 => ProviderFault::Invalid {
404441 field: None,
405 message: body,
442 message,
406443 },
407 503 => ProviderFault::Overloaded { message: body },
408 _ => ProviderFault::Transient { message: body },
444 503 => ProviderFault::Overloaded { message },
445 _ => ProviderFault::Transient { message },
409446 },
410447 });
411448 }
412449 let mut decoder = make_decoder(endpoint.kind);
413 let mut reader = response;
414 let mut buffer = [0u8; 16 * 1024];
450 let mut received: u64 = 0;
451 let mut chunk_queue = VecDeque::new();
415452 loop {
416453 if cancel.is_cancelled() {
454 spool_record(
455 &endpoint.records,
456 serde_json::json!({
457 "phase": "outcome",
458 "status": response.head.status,
459 "response_bytes": received,
460 "outcome": "cancelled",
461 }),
462 );
417463 return Err(SmithError::Cancelled);
418464 }
419 let read = reader
420 .read(&mut buffer)
421 .map_err(|e| transport_fault(&e.to_string()))?;
422 if read == 0 {
423 break;
465 if chunk_queue.is_empty() {
466 match response.chunks.recv() {
467 Ok(chunk) => {
468 received += u64::try_from(chunk.bytes.len()).unwrap_or(u64::MAX);
469 chunk_queue.push_back(chunk.bytes);
470 }
471 Err(_) => break,
472 }
424473 }
425 for event in decoder.push(&buffer[..read])? {
426 if sender.send(Ok(event)).is_err() {
427 return Ok(());
474 if let Some(bytes) = chunk_queue.pop_front() {
475 for event in decoder.push(&bytes)? {
476 if sender.send(Ok(event)).is_err() {
477 return Ok(());
478 }
428479 }
429480 }
430481 }
433484 return Ok(());
434485 }
435486 }
487 spool_record(
488 &endpoint.records,
489 serde_json::json!({
490 "phase": "outcome",
491 "status": response.head.status,
492 "response_bytes": received,
493 "outcome": "completed",
494 }),
495 );
436496 Ok(())
439fn transport_fault(message: &str) -> SmithError {
440 SmithError::Provider {
441 fault: ProviderFault::Transient {
442 message: message.to_string(),
443 },
444 }
445}
447499#[cfg(test)]
448500#[expect(clippy::unwrap_used, reason = "body builders assert on fixed requests")]
449501mod tests {
459511 base_url: "https://example.test".to_string(),
460512 model: model.to_string(),
461513 api_key: "k".to_string(),
514 executor: std::sync::Arc::new(RefusesExecutor),
515 records: smith::provider::new_record_spool(),
516 }
517 }
519 /// Body-builder tests never execute exchanges.
520 struct RefusesExecutor;
522 impl smith::http::HttpExecutor for RefusesExecutor {
523 fn execute(
524 &self,
525 _exchange: smith::http::HttpExchange,
526 _cancel: smith::tool::CancelHandle,
527 ) -> smith::error::Result<smith::http::HttpResponse> {
528 Err(SmithError::Provider {
529 fault: ProviderFault::Invalid {
530 field: None,
531 message: "executor must not run in body tests".to_string(),
532 },
533 })
462534 }
463535 }

smith-cli/src/main.rs

Modified

+2 / −0 text lines

341341 provider: runtime_provider,
342342 workdir: dir.clone(),
343343 session_path: dir.join("eval.smh"),
344 api_key: None,
344345 };
345346 let mut agent = build_agent(&config)?;
346347 let outcome = agent.run_turn(prompt)?;
378379 provider: runtime_provider,
379380 workdir: dir.clone(),
380381 session_path: dir.join("rpc.smh"),
382 api_key: None,
381383 };
382384 let state = RpcState::new(build_agent(&config)?);
383385 let (input_tx, input_rx) = std::sync::mpsc::channel();

smith-core/src/agent.rs

Modified

+44 / −0 text lines

8181 queue: VecDeque<QueuedInput>,
8282 /// Secret placeholder prefix used by [`SecretProxy`]-masked content.
8383 secrets: SecretProxy,
84 /// Redacted provider effect records spooled by the transport.
85 provider_records: Option<smith::provider::RecordSpool>,
8688/// Replacement and masking of registered secrets.
343345 /// An agent over a stream function and a recorded tool session.
344346 #[must_use]
345347 pub fn new(stream: StreamFn, tools: ToolSession, model: impl Into<String>) -> Self {
348 Self::with_provider_records(stream, tools, model, None)
349 }
351 /// An agent whose provider rounds drain redacted effect records into
352 /// the session after each round.
353 #[must_use]
354 pub fn with_provider_records(
355 stream: StreamFn,
356 tools: ToolSession,
357 model: impl Into<String>,
358 records: Option<smith::provider::RecordSpool>,
359 ) -> Self {
346360 let cancel = tools.cancel_handle();
347361 Self {
348362 stream,
351365 cancel,
352366 queue: VecDeque::new(),
353367 secrets: SecretProxy::new(),
368 provider_records: records,
354369 }
355370 }
460475 tools: pending_tools,
461476 terminal,
462477 } = self.consume(stream, events)?;
478 self.drain_provider_records()?;
463479 let Some((reason, usage)) = terminal else {
464480 return Err(SmithError::Provider {
465481 fault: smith::error::ProviderFault::Incomplete,
651667 Ok(())
652668 }
670 /// Drain spooled provider effect records into the session as metadata
671 /// entries; every round's records land before its assistant message.
672 fn drain_provider_records(&mut self) -> Result<()> {
673 let Some(spool) = self.provider_records.clone() else {
674 return Ok(());
675 };
676 let drained = spool
677 .lock()
678 .map(|mut guard| std::mem::take(&mut *guard))
679 .unwrap_or_default();
680 for detail in drained {
681 let entry = crate::session::Entry::new(
682 self.tools.session.selected_id(),
683 crate::session::EntryContent::Meta {
684 kind: crate::session::PROVIDER_HTTP_KIND.to_string(),
685 detail,
686 },
687 );
688 if let Some(writer) = self.tools.writer_mut() {
689 writer.append_frame(&crate::frame::Frame::Known {
690 entry: entry.clone(),
691 })?;
692 }
693 self.tools.session.append_to_active(entry);
694 }
695 Ok(())
696 }
654698 fn deliver_between_request_queue(&mut self) -> Result<()> {
655699 loop {
656700 let next = self

smith-core/src/session.rs

Modified

+3 / −0 text lines

99/// Meta entry kind that marks a compaction boundary.
1010pub const COMPACTION_KIND: &str = "compaction";
12/// Metadata kind for one redacted provider HTTP effect record.
13pub const PROVIDER_HTTP_KIND: &str = "provider-http";
1215/// Deterministic JSON: recursively sort object keys so equivalent values
1316/// encode to identical CBOR regardless of insertion order.
1417#[must_use]

smith-harness/Cargo.toml

Modified

+4 / −0 text lines

1212smith-core = { path = "../smith-core", version = "0.1.0" }
1313smith-ai = { path = "../smith-ai", version = "0.1.0" }
1414futures = { workspace = true }
15reqwest = { workspace = true }
17[dev-dependencies]
18serde_json = { workspace = true }

smith-harness/src/http.rs

Added
new file mode 100644

+136 / −0 text lines

1//! Host-owned HTTP engine over the `smith::http` vocabulary.
2//!
3//! One executor serves provider traffic today and plugin net-scope
4//! effects later; every call is bounded, cancellable, and recordable.
5
6use smith::error::{ProviderFault, Result, SmithError};
7use smith::http::{HttpChunk, HttpExchange, HttpExecutor, HttpExecutorRef, HttpHead, HttpResponse};
8use smith::tool::CancelHandle;
9use std::io::Read;
10use std::sync::Arc;
11use std::sync::mpsc;
12use std::time::Duration;
14/// Largest accepted response body, in bytes.
15pub const MAX_BODY_BYTES: u64 = 64 * 1024 * 1024;
17/// Largest accepted single request body, in bytes.
18pub const MAX_REQUEST_BYTES: usize = 16 * 1024 * 1024;
20/// Timeout for the response head.
21pub const HEAD_TIMEOUT: Duration = Duration::from_secs(120);
23/// Deadline for one chunk gap.
24pub const CHUNK_TIMEOUT: Duration = Duration::from_secs(300);
26/// `reqwest`-backed executor; the only HTTP engine in the workspace.
27#[derive(Clone)]
28pub struct ReqwestHttpExecutor {
29 client: reqwest::blocking::Client,
30}
32impl ReqwestHttpExecutor {
33 /// A default executor with head and chunk timeouts.
34 #[must_use]
35 pub fn new() -> Self {
36 Self {
37 client: reqwest::blocking::Client::builder()
38 .timeout(HEAD_TIMEOUT + CHUNK_TIMEOUT)
39 .build()
40 .unwrap_or_default(),
41 }
42 }
44 /// Wrap an existing client, primarily for tests.
45 #[must_use]
46 pub const fn with_client(client: reqwest::blocking::Client) -> Self {
47 Self { client }
48 }
49}
51impl Default for ReqwestHttpExecutor {
52 fn default() -> Self {
53 Self::new()
54 }
55}
57impl HttpExecutor for ReqwestHttpExecutor {
58 fn execute(&self, exchange: HttpExchange, cancel: CancelHandle) -> Result<HttpResponse> {
59 if exchange.body.len() > MAX_REQUEST_BYTES {
60 return Err(bounded("request body exceeds the size bound"));
61 }
62 if cancel.is_cancelled() {
63 return Err(SmithError::Cancelled);
64 }
65 let method = match exchange.method {
66 smith::http::HttpMethod::Post => reqwest::Method::POST,
67 };
68 let mut prepared = self
69 .client
70 .request(method, &exchange.url)
71 .body(exchange.body.clone())
72 .timeout(HEAD_TIMEOUT);
73 for header in &exchange.headers {
74 prepared = prepared.header(&header.name, &header.value);
75 }
76 let mut response = prepared
77 .send()
78 .map_err(|e| transport_fault(&e.to_string()))?;
79 let head = HttpHead {
80 status: response.status().as_u16(),
81 };
82 let (sender, receiver) = mpsc::channel();
83 let cancel_stream = cancel;
84 std::thread::spawn(move || {
85 let mut buffer = [0u8; 16 * 1024];
86 let mut total: u64 = 0;
87 loop {
88 if cancel_stream.is_cancelled() {
89 return;
90 }
91 let read = match response.read(&mut buffer) {
92 Ok(0) | Err(_) => return,
93 Ok(read) => read,
94 };
95 total += u64::try_from(read).unwrap_or(u64::MAX);
96 if total > MAX_BODY_BYTES {
97 return;
98 }
99 if sender
100 .send(HttpChunk {
101 bytes: buffer[..read].to_vec(),
102 })
103 .is_err()
104 {
105 return;
106 }
107 }
108 });
109 Ok(HttpResponse {
110 head,
111 chunks: receiver,
112 })
113 }
114}
116/// The shared default executor.
117#[must_use]
118pub fn default_executor() -> HttpExecutorRef {
119 Arc::new(ReqwestHttpExecutor::new())
120}
122fn transport_fault(message: &str) -> SmithError {
123 SmithError::Provider {
124 fault: ProviderFault::Transient {
125 message: message.to_string(),
126 },
127 }
128}
130fn bounded(message: &str) -> SmithError {
131 SmithError::Provider {
132 fault: ProviderFault::Transient {
133 message: format!("http effect: {message}"),
134 },
135 }
136}

smith-harness/src/lib.rs

Modified

+1 / −0 text lines

88//! provider-independent agent. `mock` provides a scripted provider for
99//! offline runs and tests.
11pub mod http;
1112pub mod runtime;
1314pub use runtime::{RuntimeConfig, RuntimeProvider, build_agent};

smith-harness/src/runtime.rs

Modified

+20 / −4 text lines

77use smith::config::Config;
88use smith::error::Result;
9use smith::provider::RecordSpool;
910use smith::provider::StreamFn;
1011use smith_ai::auth::AuthStore;
1112use smith_ai::models::ProviderKind;
7374 pub workdir: PathBuf,
7475 /// Session file path; created when missing.
7576 pub session_path: PathBuf,
77 /// Explicit credential override; the highest-precedence source.
78 pub api_key: Option<String>,
7881impl RuntimeConfig {
8588 provider: RuntimeProvider::Mock(script),
8689 workdir,
8790 session_path,
91 api_key: None,
8892 }
8993 }
116120 let smith_config = Config::default_valid();
117121 let opened = open_session(Path::new(&config.session_path), smith_config)?;
118122 let tools = ToolSession::with_session(config.workdir.clone(), opened.session, opened.writer);
119 let stream = resolve_stream(&config.provider)?;
120 Ok(Agent::new(
123 let records = smith::provider::new_record_spool();
124 let stream = resolve_stream(&config.provider, config.api_key.clone(), records.clone())?;
125 Ok(Agent::with_provider_records(
121126 stream,
122127 tools,
123128 config.provider.model().to_string(),
129 Some(records),
124130 ))
127fn resolve_stream(provider: &RuntimeProvider) -> Result<StreamFn> {
133fn resolve_stream(
134 provider: &RuntimeProvider,
135 api_key: Option<String>,
136 records: RecordSpool,
137) -> Result<StreamFn> {
128138 match provider {
129139 RuntimeProvider::Mock(script) => {
130140 let (stream, _seen) = crate::mock_stream(script.clone());
134144 | RuntimeProvider::Anthropic { base_url, model }
135145 | RuntimeProvider::Google { base_url, model } => {
136146 let kind = provider.vendor_kind();
137 let api_key = resolve_credential(kind)?;
147 let api_key = match api_key {
148 Some(explicit) => explicit,
149 None => resolve_credential(kind)?,
150 };
138151 Ok(transport(VendorEndpoint {
139152 kind,
140153 base_url: base_url.clone(),
141154 model: model.clone(),
142155 api_key,
156 executor: crate::http::default_executor(),
157 records,
143158 }))
144159 }
145160 }
214229 },
215230 workdir: dir.clone(),
216231 session_path: dir.join("s.smh"),
232 api_key: None,
217233 };
218234 let Err(err) = build_agent(&config) else {
219235 unreachable!("no credential must fail assembly");

smith-harness/tests/http_effect.rs

Added
new file mode 100644

+126 / −0 text lines

1//! End-to-end provider traffic through the typed HTTP effect.
2
3//! Integration tests drive a real socket, a real executor, and the
4//! durable session store.
5#![expect(clippy::unwrap_used, reason = "integration tests assert on outcomes")]
6
7use smith_harness::runtime::{RuntimeConfig, RuntimeProvider, build_agent};
8use std::io::{Read, Write};
9use std::net::TcpListener;
11use smith_core::frame::{Frame, read_frames};
12use smith_core::session::{EntryContent, PROVIDER_HTTP_KIND};
14/// Serve one OpenAI-shaped SSE response and return the port.
15fn spawn_sse_server(body: &'static str) -> u16 {
16 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
17 let port = listener.local_addr().unwrap().port();
18 std::thread::spawn(move || {
19 let (mut socket, _) = listener.accept().unwrap();
20 let mut buffer = [0u8; 8192];
21 let _ = socket.read(&mut buffer);
22 let response = format!(
23 "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}"
24 );
25 socket.write_all(response.as_bytes()).unwrap();
26 });
27 port
28}
30fn provider_http_records(path: &std::path::Path) -> Vec<serde_json::Value> {
31 let bytes = std::fs::read(path).unwrap();
32 let config = smith::config::Config::default_valid();
33 read_frames(&mut bytes.as_slice(), config.max_frame_bytes)
34 .frames
35 .into_iter()
36 .filter_map(|frame| match frame {
37 Frame::Known { entry } => match entry.content {
38 EntryContent::Meta { kind, detail } if kind == PROVIDER_HTTP_KIND => Some(detail),
39 _ => None,
40 },
41 Frame::Unknown { .. } | smith_core::Frame::Header { .. } => None,
42 })
43 .collect()
44}
46#[test]
47fn provider_round_trips_through_http_effect_with_durable_redacted_records() {
48 let dir = std::env::temp_dir().join(format!("smith_http_effect_{}", std::process::id()));
49 let _ = std::fs::remove_dir_all(&dir);
50 std::fs::create_dir_all(&dir).unwrap();
52 let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"hello \"}}]}\n\n\
53 data: {\"choices\":[{\"delta\":{\"content\":\"world\"}}]}\n\n\
54 data: {\"choices\":[{\"finish_reason\":\"stop\",\"delta\":{}}],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2}}\n\n\
55 data: [DONE]\n\n";
56 let port = spawn_sse_server(sse);
58 let session_path = dir.join("session.smh");
59 let config = RuntimeConfig {
60 provider: RuntimeProvider::OpenAiCompatible {
61 base_url: format!("http://127.0.0.1:{port}/v1"),
62 model: "gpt-test".to_string(),
63 },
64 workdir: dir.clone(),
65 session_path: session_path.clone(),
66 api_key: Some("sk-integration-secret".to_string()),
67 };
68 let mut agent = build_agent(&config).unwrap();
69 let outcome = agent.run_turn("say it").unwrap();
70 assert_eq!(outcome.text, "hello world");
72 let records = provider_http_records(&session_path);
73 assert_eq!(records.len(), 2, "intent and outcome records");
75 let intent = &records[0];
76 assert_eq!(intent["phase"], "intent");
77 assert_eq!(
78 intent["url"],
79 format!("http://127.0.0.1:{port}/v1/chat/completions")
80 );
81 let headers = intent["headers"].as_array().unwrap();
82 let authorization = headers
83 .iter()
84 .find(|header| {
85 header["name"]
86 .as_str()
87 .unwrap_or_default()
88 .eq_ignore_ascii_case("authorization")
89 })
90 .unwrap();
91 assert_eq!(authorization["value"], "<redacted>");
93 let outcome_record = &records[1];
94 assert_eq!(outcome_record["phase"], "outcome");
95 assert_eq!(outcome_record["status"], 200);
96 assert_eq!(outcome_record["outcome"], "completed");
98 let _ = std::fs::remove_dir_all(&dir);
99}
101#[test]
102fn explicit_credential_wins_over_missing_env() {
103 // No store, no env: only the explicit override can resolve.
104 let dir = std::env::temp_dir().join(format!("smith_http_explicit_{}", std::process::id()));
105 let _ = std::fs::remove_dir_all(&dir);
106 std::fs::create_dir_all(&dir).unwrap();
107 let store = smith_ai::auth::AuthStore::at(dir.join("empty-store"));
108 assert!(
109 store
110 .load(smith_ai::models::ProviderKind::Anthropic)
111 .unwrap()
112 .is_none()
113 );
115 let config = RuntimeConfig {
116 provider: RuntimeProvider::Anthropic {
117 base_url: "https://example.test".to_string(),
118 model: "m".to_string(),
119 },
120 workdir: dir.clone(),
121 session_path: dir.join("s.smh"),
122 api_key: Some("sk-explicit".to_string()),
123 };
124 let _agent = build_agent(&config).unwrap();
125 let _ = std::fs::remove_dir_all(&dir);
126}

smith/src/http.rs

Added
new file mode 100644

+114 / −0 text lines

1//! Typed HTTP effect vocabulary.
2//!
3//! The core defines the shape; exactly one engine crate provides the
4//! executor. Provider traffic flows through this boundary so every call
5//! can be bounded, cancelled, recorded, and replayed without any
6//! engine types leaking upward.
7
8use crate::error::Result;
9use crate::tool::CancelHandle;
10use std::sync::Arc;
11use std::sync::mpsc::Receiver;
13/// One HTTP header, ordered.
14#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15pub struct HttpHeader {
16 /// Header name.
17 pub name: String,
18 /// Header value; credential-bearing values are recorded redacted.
19 pub value: String,
20}
22/// A bounded request description.
23#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
24pub struct HttpExchange {
25 /// Request method.
26 pub method: HttpMethod,
27 /// Endpoint URL.
28 pub url: String,
29 /// Ordered headers.
30 pub headers: Vec<HttpHeader>,
31 /// Request body bytes, bounded by the executor.
32 pub body: Vec<u8>,
33}
35/// Supported request methods.
36#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37pub enum HttpMethod {
38 /// HTTP POST.
39 Post,
40}
42impl HttpMethod {
43 /// Wire representation.
44 #[must_use]
45 pub const fn as_str(self) -> &'static str {
46 match self {
47 Self::Post => "POST",
48 }
49 }
50}
52/// The response head, delivered before body chunks.
53#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
54pub struct HttpHead {
55 /// HTTP status code.
56 pub status: u16,
57}
59/// One streaming body chunk.
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct HttpChunk {
62 /// Bytes received in order.
63 pub bytes: Vec<u8>,
64}
66/// A streaming HTTP response: head first, chunks in order, end of channel
67/// means the body is complete.
68pub struct HttpResponse {
69 /// Response head.
70 pub head: HttpHead,
71 /// Ordered body chunks; the channel closes at end of body.
72 pub chunks: Receiver<HttpChunk>,
73}
75/// Executes [`HttpExchange`]s.
76///
77/// Implementations apply timeouts, size bounds, and cooperative
78/// cancellation between chunks.
79pub trait HttpExecutor: Send + Sync {
80 /// Execute one exchange.
81 ///
82 /// # Errors
83 ///
84 /// Returns a provider fault on transport failure, cancellation, or
85 /// exceeded bounds.
86 fn execute(&self, exchange: HttpExchange, cancel: CancelHandle) -> Result<HttpResponse>;
87}
89/// Shared executor handle.
90pub type HttpExecutorRef = Arc<dyn HttpExecutor>;
92/// Redact credential-bearing header values for records and diagnostics.
93///
94/// Authorization and proxy-authorization values never appear in plaintext.
95#[must_use]
96pub fn redact_headers(headers: &[HttpHeader]) -> Vec<HttpHeader> {
97 headers
98 .iter()
99 .map(|header| {
100 let sensitive = matches!(
101 header.name.to_ascii_lowercase().as_str(),
102 "authorization" | "proxy-authorization" | "x-api-key"
103 );
104 HttpHeader {
105 name: header.name.clone(),
106 value: if sensitive {
107 "<redacted>".to_string()
108 } else {
109 header.value.clone()
110 },
111 }
112 })
113 .collect()
114}

smith/src/lib.rs

Modified

+2 / −0 text lines

88pub mod config;
99/// Recoverable error taxonomy.
1010pub mod error;
12pub mod http;
1113/// Stable identifiers.
1214pub mod id;
1315/// Messages and content blocks.

smith/src/provider.rs

Modified

+10 / −0 text lines

7272/// The provider boundary itself: send a request, get a normalized stream.
7373pub type StreamFn = Arc<dyn Fn(ProviderRequest, CancelHandle) -> ProviderStream + Send + Sync>;
75/// Redacted provider effect records spooled between the transport and the
76/// session writer.
77pub type RecordSpool = std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>>;
79/// A fresh empty spool.
80#[must_use]
81pub fn new_record_spool() -> RecordSpool {
82 std::sync::Arc::new(std::sync::Mutex::new(Vec::new()))
83}
7585/// Build a [`StreamFn`] from a callable that produces the stream.
7686pub fn stream_fn<F, Fut>(f: F) -> StreamFn
7787where