repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

Give the skeleton the vocabulary its seams are written in (#131)

ac7bfdc350f6cad7aa8506dbc9235ce787fd3e62

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Walking-skeleton steps 3 through 7 all speak in the same shapes — a message, a
provider event, a tool result — and none of them could start while those shapes
did not exist. This defines exactly the §5.1-§5.4 and §5.6 surface the skeleton
consumes and nothing else; the Lua runtime, model resolution, and the full error
taxonomy stay unwritten until the slices that own them are built against.

`AgentTool::execute` returns a boxed future rather than reading as an `async
fn`, because the registry stores tools as shared handles by name (§6.10) so the
trait must survive `dyn`, and the usual fix — an `async-trait` dependency — is
absent from the §2.3 registry, where adding a name is the spec owner's decision.
`Thinking.provider_metadata` got no transport invented for it either: §5.2's
stream is text-only at the reasoning variant, so that gap is filed as #132.

`smith/src`, six modules, 20 tests covering the CBOR and JSON round-trips the
session codec depends on.

Closes #119

Changed files (10)

+1365 / −1 text lines

Diff layout

Cargo.lock

Modified

+319 / −1 text lines

22# It is not intended for manual editing.
33version = 4
5[[package]]
6name = "bumpalo"
7version = "3.20.3"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
11[[package]]
12name = "cfg-if"
13version = "1.0.4"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
17[[package]]
18name = "ciborium"
19version = "0.2.2"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
22dependencies = [
23 "ciborium-io",
24 "ciborium-ll",
25 "serde",
26]
28[[package]]
29name = "ciborium-io"
30version = "0.2.2"
31source = "registry+https://github.com/rust-lang/crates.io-index"
32checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
34[[package]]
35name = "ciborium-ll"
36version = "0.2.2"
37source = "registry+https://github.com/rust-lang/crates.io-index"
38checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
39dependencies = [
40 "ciborium-io",
41 "half",
42]
44[[package]]
45name = "crunchy"
46version = "0.2.4"
47source = "registry+https://github.com/rust-lang/crates.io-index"
48checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
50[[package]]
51name = "futures"
52version = "0.3.33"
53source = "registry+https://github.com/rust-lang/crates.io-index"
54checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218"
55dependencies = [
56 "futures-channel",
57 "futures-core",
58 "futures-executor",
59 "futures-io",
60 "futures-sink",
61 "futures-task",
62 "futures-util",
63]
65[[package]]
66name = "futures-channel"
67version = "0.3.33"
68source = "registry+https://github.com/rust-lang/crates.io-index"
69checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae"
70dependencies = [
71 "futures-core",
72 "futures-sink",
73]
75[[package]]
76name = "futures-core"
77version = "0.3.33"
78source = "registry+https://github.com/rust-lang/crates.io-index"
79checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
81[[package]]
82name = "futures-executor"
83version = "0.3.33"
84source = "registry+https://github.com/rust-lang/crates.io-index"
85checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458"
86dependencies = [
87 "futures-core",
88 "futures-task",
89 "futures-util",
90]
92[[package]]
93name = "futures-io"
94version = "0.3.33"
95source = "registry+https://github.com/rust-lang/crates.io-index"
96checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"
98[[package]]
99name = "futures-macro"
100version = "0.3.33"
101source = "registry+https://github.com/rust-lang/crates.io-index"
102checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b"
103dependencies = [
104 "proc-macro2",
105 "quote",
106 "syn 2.0.119",
107]
109[[package]]
110name = "futures-sink"
111version = "0.3.33"
112source = "registry+https://github.com/rust-lang/crates.io-index"
113checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307"
115[[package]]
116name = "futures-task"
117version = "0.3.33"
118source = "registry+https://github.com/rust-lang/crates.io-index"
119checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"
121[[package]]
122name = "futures-util"
123version = "0.3.33"
124source = "registry+https://github.com/rust-lang/crates.io-index"
125checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
126dependencies = [
127 "futures-channel",
128 "futures-core",
129 "futures-io",
130 "futures-macro",
131 "futures-sink",
132 "futures-task",
133 "memchr",
134 "pin-project-lite",
135 "slab",
136]
138[[package]]
139name = "getrandom"
140version = "0.4.3"
141source = "registry+https://github.com/rust-lang/crates.io-index"
142checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
143dependencies = [
144 "cfg-if",
145 "libc",
146 "r-efi",
147]
149[[package]]
150name = "half"
151version = "2.7.1"
152source = "registry+https://github.com/rust-lang/crates.io-index"
153checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
154dependencies = [
155 "cfg-if",
156 "crunchy",
157 "zerocopy",
158]
5160[[package]]
6161name = "itoa"
7162version = "1.0.18"
8163source = "registry+https://github.com/rust-lang/crates.io-index"
9164checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
166[[package]]
167name = "js-sys"
168version = "0.3.103"
169source = "registry+https://github.com/rust-lang/crates.io-index"
170checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
171dependencies = [
172 "cfg-if",
173 "futures-util",
174 "wasm-bindgen",
175]
177[[package]]
178name = "libc"
179version = "0.2.189"
180source = "registry+https://github.com/rust-lang/crates.io-index"
181checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
11183[[package]]
12184name = "memchr"
13185version = "2.8.3"
14186source = "registry+https://github.com/rust-lang/crates.io-index"
15187checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
189[[package]]
190name = "once_cell"
191version = "1.21.4"
192source = "registry+https://github.com/rust-lang/crates.io-index"
193checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
195[[package]]
196name = "pin-project-lite"
197version = "0.2.17"
198source = "registry+https://github.com/rust-lang/crates.io-index"
199checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
17201[[package]]
18202name = "proc-macro2"
19203version = "1.0.107"
32216 "proc-macro2",
219[[package]]
220name = "r-efi"
221version = "6.0.0"
222source = "registry+https://github.com/rust-lang/crates.io-index"
223checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
225[[package]]
226name = "rustversion"
227version = "1.0.23"
228source = "registry+https://github.com/rust-lang/crates.io-index"
229checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
35231[[package]]
36232name = "serde"
37233version = "1.0.229"
39235checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
40236dependencies = [
41237 "serde_core",
238 "serde_derive",
44241[[package]]
58255dependencies = [
59256 "proc-macro2",
60257 "quote",
61 "syn",
258 "syn 3.0.3",
64261[[package]]
74271 "zmij",
274[[package]]
275name = "slab"
276version = "0.4.12"
277source = "registry+https://github.com/rust-lang/crates.io-index"
278checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
77280[[package]]
78281name = "smith"
79282version = "0.1.0"
283dependencies = [
284 "ciborium",
285 "futures",
286 "serde",
287 "serde_json",
288 "thiserror",
289 "uuid",
290]
81292[[package]]
82293name = "smith-ai"
98309name = "smith-tui"
99310version = "0.1.0"
312[[package]]
313name = "syn"
314version = "2.0.119"
315source = "registry+https://github.com/rust-lang/crates.io-index"
316checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
317dependencies = [
318 "proc-macro2",
319 "quote",
320 "unicode-ident",
321]
101323[[package]]
102324name = "syn"
103325version = "3.0.3"
109331 "unicode-ident",
334[[package]]
335name = "thiserror"
336version = "2.0.19"
337source = "registry+https://github.com/rust-lang/crates.io-index"
338checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
339dependencies = [
340 "thiserror-impl",
341]
343[[package]]
344name = "thiserror-impl"
345version = "2.0.19"
346source = "registry+https://github.com/rust-lang/crates.io-index"
347checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
348dependencies = [
349 "proc-macro2",
350 "quote",
351 "syn 3.0.3",
352]
112354[[package]]
113355name = "unicode-ident"
114356version = "1.0.24"
115357source = "registry+https://github.com/rust-lang/crates.io-index"
116358checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
360[[package]]
361name = "uuid"
362version = "1.24.0"
363source = "registry+https://github.com/rust-lang/crates.io-index"
364checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239"
365dependencies = [
366 "getrandom",
367 "js-sys",
368 "wasm-bindgen",
369]
371[[package]]
372name = "wasm-bindgen"
373version = "0.2.126"
374source = "registry+https://github.com/rust-lang/crates.io-index"
375checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
376dependencies = [
377 "cfg-if",
378 "once_cell",
379 "rustversion",
380 "wasm-bindgen-macro",
381 "wasm-bindgen-shared",
382]
384[[package]]
385name = "wasm-bindgen-macro"
386version = "0.2.126"
387source = "registry+https://github.com/rust-lang/crates.io-index"
388checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
389dependencies = [
390 "quote",
391 "wasm-bindgen-macro-support",
392]
394[[package]]
395name = "wasm-bindgen-macro-support"
396version = "0.2.126"
397source = "registry+https://github.com/rust-lang/crates.io-index"
398checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
399dependencies = [
400 "bumpalo",
401 "proc-macro2",
402 "quote",
403 "syn 2.0.119",
404 "wasm-bindgen-shared",
405]
407[[package]]
408name = "wasm-bindgen-shared"
409version = "0.2.126"
410source = "registry+https://github.com/rust-lang/crates.io-index"
411checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
412dependencies = [
413 "unicode-ident",
414]
118416[[package]]
119417name = "xtask"
120418version = "0.1.0"
122420 "serde_json",
423[[package]]
424name = "zerocopy"
425version = "0.8.55"
426source = "registry+https://github.com/rust-lang/crates.io-index"
427checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
428dependencies = [
429 "zerocopy-derive",
430]
432[[package]]
433name = "zerocopy-derive"
434version = "0.8.55"
435source = "registry+https://github.com/rust-lang/crates.io-index"
436checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
437dependencies = [
438 "proc-macro2",
439 "quote",
440 "syn 2.0.119",
441]
125443[[package]]
126444name = "zmij"
127445version = "1.0.23"

Cargo.toml

Modified

+12 / −0 text lines

2222version = "0.1.0"
2323license = "Apache-2.0"
25# Versions are quoted from the SPEC §2.3 canonical dependency registry, which is
26# the only place a crate may be added or removed. Entries appear here as the
27# slices that need them land, so this table is a subset of the registry and
28# never a superset — a name absent from §2.3 must not appear below.
29[workspace.dependencies]
30serde = { version = "1", features = ["derive"] }
31serde_json = "1"
32uuid = { version = "1", features = ["v7"] }
33futures = "0.3"
34thiserror = "2"
35ciborium = "0.2"
2537# The lint wall. It lives here, not in .cargo/config.toml rustflags, because a
2638# [target.*] rustflags key REPLACES [build].rustflags rather than merging — so a
2739# per-target stanza silently disabled every lint below for that target alone.

smith/Cargo.toml

Modified

+12 / −0 text lines

77[lib]
88path = "src/lib.rs"
10[dependencies]
11serde = { workspace = true }
12serde_json = { workspace = true }
13uuid = { workspace = true }
14futures = { workspace = true }
15thiserror = { workspace = true }
17[dev-dependencies]
18# The session codec is CBOR (§6.6), so the round-trip properties this crate
19# promises are asserted against the encoder that will actually carry them.
20ciborium = { workspace = true }
1022[lints]
1123workspace = true

smith/src/config.rs

Added
new file mode 100644

+71 / −0 text lines

1//! Configuration schema (SPEC §5.6).
2//!
3//! Lua is the configuration language: Rust defines the schema, Lua supplies the
4//! values, and the cascade (Rust defaults → built-in Lua → plugins → user config
5//! → CLI flags) resolves them. This type is the Rust-defaults layer, and only
6//! the part of it the walking skeleton needs — the cascade itself, the Lua
7//! loader, and strict-context key checking arrive with the harness (§9.19).
8
9use serde::{Deserialize, Serialize};
11/// The resolved configuration the skeleton runs against.
12///
13/// Deliberately two fields. Every key here is one the walking skeleton reads to
14/// run a turn; anything broader would be schema written ahead of a consumer,
15/// which is what the §5.6 cascade would then have to keep honest for no gain.
16/// Unknown top-level keys are tolerated rather than rejected. §5.6 says they
17/// *warn* in the top-level schema context and *fail* only in strict contexts
18/// (`models.*`, `compaction.*`), and this slice defines neither a strict
19/// context nor the diagnostic channel a warning needs — both arrive with the
20/// config loader (§9.19). Denying them here would be stricter than the spec and
21/// would reject a valid wider config against this deliberately minimal schema.
22#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(default)]
24pub struct Config {
25 /// The model to run, as a resolver name (§5.7) or a raw `provider/model`.
26 pub model: String,
27 /// Names of the tools to make available.
28 pub tools: Vec<String>,
29}
31#[cfg(test)]
32#[expect(
33 clippy::unwrap_used,
34 reason = "Test fixtures use unwrap so setup failures report their exact operation."
35)]
36mod tests {
37 use super::Config;
39 #[test]
40 fn a_partial_config_fills_from_defaults() {
41 // The cascade overrides layer by layer, so a layer that sets one key
42 // must not blank the others.
43 let config: Config =
44 serde_json::from_str(r#"{ "model": "anthropic/claude-sonnet-4" }"#).unwrap();
45 assert_eq!(config.model, "anthropic/claude-sonnet-4");
46 assert!(config.tools.is_empty());
47 }
49 #[test]
50 fn an_unknown_top_level_key_does_not_reject_the_config() {
51 // §5.6 warns on unknown top-level keys rather than failing; failing is
52 // reserved for strict contexts. A wider config than this minimal schema
53 // knows about must therefore still load, with the keys it does know
54 // intact. Emitting the warning belongs to the loader (§9.19).
55 let config: Config = serde_json::from_str(
56 r#"{ "model": "anthropic/claude-sonnet-4", "theme": "catppuccin" }"#,
57 )
58 .unwrap();
59 assert_eq!(config.model, "anthropic/claude-sonnet-4");
60 }
62 #[test]
63 fn a_config_round_trips() {
64 let config = Config {
65 model: "anthropic/claude-sonnet-4".to_owned(),
66 tools: vec!["read".to_owned(), "bash".to_owned()],
67 };
68 let json = serde_json::to_string(&config).unwrap();
69 assert_eq!(serde_json::from_str::<Config>(&json).unwrap(), config);
70 }
71}

smith/src/ids.rs

Added
new file mode 100644

+165 / −0 text lines

1//! Identifier newtypes (SPEC §5.1).
2//!
3//! Each identifier is a distinct type over `String` so that an entry id cannot
4//! be passed where a session id is wanted.
5//!
6//! Only some of them are Smith's to mint. [`EntryId`] is specified as UUID v7
7//! (§5.1), which is time-sortable: ordering ids lexically orders them by
8//! creation, so session entries sort without a separate sequence number, and
9//! [`SessionId`] is generated the same way. [`SecretId`] and [`VcsOpId`] have
10//! no constructor here on purpose — a secret id is allocated numerically by the
11//! secret proxy, which resumes past the highest id it has seen (§6.7), and a
12//! VCS operation id names an operation the VCS performed (§9.13). Inventing
13//! either here would produce a value the owning subsystem cannot honor.
15use serde::{Deserialize, Serialize};
16use uuid::Uuid;
18/// Builds the shared body of an identifier newtype.
19///
20/// The identifiers differ only in name and documentation, so the shape is
21/// written once rather than four times over, where the copies could drift.
22macro_rules! identifier {
23 ($(#[$meta:meta])* $name:ident) => {
24 $(#[$meta])*
25 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
26 #[serde(transparent)]
27 pub struct $name(String);
29 impl $name {
30 /// Wraps an existing identifier string.
31 ///
32 /// Used when reading an identifier generated elsewhere — a
33 /// persisted session, a provider payload, the VCS — where the value
34 /// must be preserved exactly rather than regenerated.
35 #[must_use]
36 pub const fn from_string(value: String) -> Self {
37 Self(value)
38 }
40 /// Borrows the underlying string.
41 #[must_use]
42 pub fn as_str(&self) -> &str {
43 &self.0
44 }
46 /// Unwraps to the owned string.
47 #[must_use]
48 pub fn into_string(self) -> String {
49 self.0
50 }
51 }
53 impl std::fmt::Display for $name {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 f.write_str(&self.0)
56 }
57 }
58 };
59}
61/// Builds an identifier that Smith mints itself, as UUID v7.
62macro_rules! generated_identifier {
63 ($(#[$meta:meta])* $name:ident) => {
64 identifier! { $(#[$meta])* $name }
66 impl $name {
67 /// Generates a fresh time-sortable identifier.
68 #[must_use]
69 pub fn new() -> Self {
70 Self(Uuid::now_v7().to_string())
71 }
72 }
74 impl Default for $name {
75 fn default() -> Self {
76 Self::new()
77 }
78 }
79 };
80}
82generated_identifier! {
83 /// Identifies one entry within a session (SPEC §6.5).
84 EntryId
85}
87generated_identifier! {
88 /// Identifies one session.
89 SessionId
90}
92identifier! {
93 /// Identifies one secret held by the secret proxy (SPEC §6.7).
94 ///
95 /// Allocated by the proxy as a number, rendered in content as a
96 /// `smith:sec:<digits>` placeholder; on resume the allocator continues past
97 /// the highest id seen, because a reused id silently aliases older
98 /// placeholders. That allocator owns minting, so this type only carries a
99 /// value it was given.
100 SecretId
101}
103identifier! {
104 /// Identifies one recorded version-control operation (SPEC §9.13).
105 ///
106 /// Names an operation the VCS performed, so the VCS supplies the value.
107 VcsOpId
108}
110#[cfg(test)]
111#[expect(
112 clippy::unwrap_used,
113 reason = "Test fixtures use unwrap so setup failures report their exact operation."
114)]
115mod tests {
116 use super::{EntryId, SecretId, SessionId};
118 #[test]
119 fn generated_ids_are_unique() {
120 assert_ne!(EntryId::new(), EntryId::new());
121 }
123 #[test]
124 fn generated_ids_sort_by_creation_order() {
125 // UUID v7 places a millisecond timestamp in its leading bits, so
126 // lexical order is creation order. Sessions rely on this to sort
127 // entries without a separate sequence field.
128 let mut previous = EntryId::new();
129 for _ in 0..64 {
130 let next = EntryId::new();
131 assert!(
132 previous.as_str() <= next.as_str(),
133 "v7 ids must be non-decreasing: {previous} then {next}"
134 );
135 previous = next;
136 }
137 }
139 #[test]
140 fn an_id_survives_a_string_round_trip() {
141 let id = SessionId::new();
142 let restored = SessionId::from_string(id.as_str().to_owned());
143 assert_eq!(id, restored);
144 }
146 #[test]
147 fn a_secret_id_carries_the_allocator_s_value_verbatim() {
148 // The proxy allocates numerically and content carries
149 // `smith:sec:<digits>` (§6.7), so this type must not reshape what it is
150 // handed — a placeholder id parses as the maximal digit run.
151 let id = SecretId::from_string("12".to_owned());
152 assert_eq!(id.as_str(), "12");
153 assert_eq!(format!("smith:sec:{id}"), "smith:sec:12");
154 }
156 #[test]
157 fn ids_serialize_as_bare_strings() {
158 // `serde(transparent)` keeps the wire form a string rather than a
159 // one-field map, which is what session files and provider payloads
160 // carry.
161 let id = SessionId::from_string("abc".to_owned());
162 let json = serde_json::to_string(&id).unwrap();
163 assert_eq!(json, "\"abc\"");
164 }
165}

smith/src/lib.rs

Modified

+40 / −0 text lines

11//! Foundation types and interfaces for Smith.
2//!
3//! This crate owns the shapes every other crate shares and holds no business
4//! logic. It has no dependency on any other workspace crate — the architecture
5//! gate enforces that (SPEC §2.2) — which is what lets `smith-core` and
6//! `smith-ai` be built and tested independently of each other.
7//!
8//! What is here, per SPEC §5:
9//!
10//! - identifiers and content (§5.1): [`EntryId`], [`SessionId`], [`SecretId`],
11//! [`VcsOpId`], [`Role`], [`ContentBlock`], [`Message`],
12//! - the provider boundary (§5.2): [`ProviderUsage`], [`StopReason`],
13//! [`ThinkingLevel`], [`ProviderEvent`], [`ProviderError`],
14//! [`ProviderRequest`],
15//! - tools (§5.3): [`AgentTool`], [`ToolDefinition`], [`ToolDefinitionSpec`],
16//! [`AgentToolResult`], [`AgentToolUpdate`], [`ToolExecutionMode`],
17//! - the provider abstraction (§5.4): [`StreamFn`],
18//! - the configuration schema (§5.6): [`Config`].
19//!
20//! Still to come, in the sections that own them: the Lua runtime (§5.5), model
21//! resolution (§5.7), and the full error taxonomy (§5.8). Until those land,
22//! [`ProviderError`] is the only error type this crate defines.
324#![forbid(unsafe_code)]
425#![warn(missing_docs)]
27pub mod config;
28pub mod ids;
29pub mod message;
30pub mod provider;
31pub mod stream;
32pub mod tool;
34pub use config::Config;
35pub use ids::{EntryId, SecretId, SessionId, VcsOpId};
36pub use message::{ContentBlock, Message, Role};
37pub use provider::{
38 ProviderError, ProviderEvent, ProviderRequest, ProviderUsage, StopReason, ThinkingLevel,
39};
40pub use stream::StreamFn;
41pub use tool::{
42 AgentTool, AgentToolResult, AgentToolUpdate, ToolDefinition, ToolDefinitionSpec,
43 ToolExecutionMode,
44};

smith/src/message.rs

Added
new file mode 100644

+202 / −0 text lines

1//! Roles, content blocks, and messages (SPEC §5.1).
2//!
3//! [`ContentBlock`] is the authoritative content representation: every other
4//! shape in Smith that carries model-visible content carries these. Roles say
5//! *who speaks*; what *happened* is a session entry kind (§6.5), not a role.
6//! Tool results are therefore [`Role::Tool`] messages holding
7//! [`ContentBlock::ToolResult`] — there is no separate tool-result role.
8
9use serde::{Deserialize, Serialize};
11/// Who is speaking in a [`Message`].
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum Role {
15 /// The system prompt.
16 System,
17 /// The person using Smith.
18 User,
19 /// The model.
20 Assistant,
21 /// A tool reporting back; carries [`ContentBlock::ToolResult`].
22 Tool,
23}
25/// One unit of model-visible content.
26///
27/// Variants are externally tagged, which keeps each one self-describing on the
28/// wire. Telling *unknown* from *corrupt* is not this tagging's doing — §6.6
29/// decides that at the entry level, by decoding raw CBOR first and typed
30/// second, so a well-formed entry carrying a variant this build has no name for
31/// is preserved rather than skipped.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum ContentBlock {
35 /// Plain text.
36 Text(String),
37 /// An image, carried inline.
38 Image {
39 /// Encoded image bytes, as supplied by the provider or the user.
40 data: String,
41 /// The IANA media type describing `data`, e.g. `image/png`.
42 media_type: String,
43 },
44 /// The model asking for a tool to run.
45 ToolCall {
46 /// Correlates this call with its [`ContentBlock::ToolResult`].
47 id: String,
48 /// The tool being called.
49 name: String,
50 /// Arguments as JSON, validated against the tool's schema (§5.3).
51 arguments: serde_json::Value,
52 },
53 /// The outcome of a tool call.
54 ToolResult {
55 /// The `id` of the [`ContentBlock::ToolCall`] this answers.
56 id: String,
57 /// What the tool produced, rendered for the model.
58 result: String,
59 /// Whether `result` describes a failure.
60 is_error: bool,
61 },
62 /// Model reasoning.
63 Thinking {
64 /// The reasoning text.
65 content: String,
66 /// Provider-attached data that Smith never interprets.
67 ///
68 /// Anthropic's thinking signatures travel here. Smith stores the value
69 /// untouched and replays it on later requests (§7.2) so that signed
70 /// thinking round-trips across turns; a provider adapter is the only
71 /// thing that may read it.
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 provider_metadata: Option<serde_json::Value>,
74 },
75}
77/// One message in a conversation.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct Message {
80 /// Who is speaking.
81 pub role: Role,
82 /// What was said, in order.
83 pub content: Vec<ContentBlock>,
84}
86impl Message {
87 /// Builds a message from a role and its content.
88 #[must_use]
89 pub const fn new(role: Role, content: Vec<ContentBlock>) -> Self {
90 Self { role, content }
91 }
93 /// Builds a single-block text message.
94 #[must_use]
95 pub fn text(role: Role, text: impl Into<String>) -> Self {
96 Self::new(role, vec![ContentBlock::Text(text.into())])
97 }
98}
100#[cfg(test)]
101#[expect(
102 clippy::unwrap_used,
103 clippy::panic,
104 reason = "Test fixtures use unwrap and panic so failures report their exact operation."
105)]
106mod tests {
107 use super::{ContentBlock, Message, Role};
109 /// Encodes to CBOR and back, which is the codec sessions are stored in
110 /// (§6.6) and therefore the one that has to preserve these shapes.
111 fn cbor_round_trip(message: &Message) -> Message {
112 let mut bytes = Vec::new();
113 ciborium::into_writer(message, &mut bytes).unwrap();
114 ciborium::from_reader(bytes.as_slice()).unwrap()
115 }
117 #[test]
118 fn every_block_kind_survives_cbor() {
119 let message = Message::new(
120 Role::Assistant,
121 vec![
122 ContentBlock::Text("hello".to_owned()),
123 ContentBlock::Image {
124 data: "AAAA".to_owned(),
125 media_type: "image/png".to_owned(),
126 },
127 ContentBlock::ToolCall {
128 id: "call-1".to_owned(),
129 name: "read".to_owned(),
130 arguments: serde_json::json!({ "path": "src/lib.rs" }),
131 },
132 ContentBlock::ToolResult {
133 id: "call-1".to_owned(),
134 result: "contents".to_owned(),
135 is_error: false,
136 },
137 ContentBlock::Thinking {
138 content: "considering".to_owned(),
139 provider_metadata: None,
140 },
141 ],
142 );
144 assert_eq!(cbor_round_trip(&message), message);
145 }
147 #[test]
148 fn thinking_provider_metadata_is_preserved_opaquely() {
149 // Smith never reads this value, so the test asserts only that whatever
150 // the provider attached comes back byte-for-byte — including a nested
151 // shape Smith has no type for.
152 let metadata = serde_json::json!({
153 "signature": "sig-abc",
154 "nested": { "unknown_to_smith": [1, 2, 3] },
155 });
156 let message = Message::new(
157 Role::Assistant,
158 vec![ContentBlock::Thinking {
159 content: "considering".to_owned(),
160 provider_metadata: Some(metadata.clone()),
161 }],
162 );
164 let restored = cbor_round_trip(&message);
165 let ContentBlock::Thinking {
166 provider_metadata, ..
167 } = &restored.content[0]
168 else {
169 panic!("the thinking block must decode as a thinking block");
170 };
171 assert_eq!(provider_metadata.as_ref(), Some(&metadata));
172 }
174 #[test]
175 fn absent_provider_metadata_stays_absent() {
176 // The field is skipped when empty rather than written as null, so a
177 // block that never had metadata does not grow a field on every rewrite.
178 let message = Message::new(
179 Role::Assistant,
180 vec![ContentBlock::Thinking {
181 content: "considering".to_owned(),
182 provider_metadata: None,
183 }],
184 );
185 let json = serde_json::to_string(&message).unwrap();
186 assert!(
187 !json.contains("provider_metadata"),
188 "empty metadata must not be written: {json}"
189 );
190 assert_eq!(cbor_round_trip(&message), message);
191 }
193 #[test]
194 fn messages_survive_json_as_well() {
195 // `smith session dump` emits JSONL (§6.6), so the same shapes have to
196 // survive JSON, not only CBOR.
197 let message = Message::text(Role::User, "hello");
198 let json = serde_json::to_string(&message).unwrap();
199 let restored: Message = serde_json::from_str(&json).unwrap();
200 assert_eq!(restored, message);
201 }
202}

smith/src/provider.rs

Added
new file mode 100644

+259 / −0 text lines

1//! Provider-facing request, event, and error types (SPEC §5.2).
2//!
3//! These describe what a provider is *asked* and what it *emits*, without
4//! naming any provider. `smith-core` consumes them through [`StreamFn`]
5//! (§5.4), which is why the agent loop can be built and tested with no
6//! provider present.
7//!
8//! [`StreamFn`]: crate::StreamFn
9
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
13use crate::message::Message;
14use crate::tool::ToolDefinition;
16/// Token accounting for one exchange.
17///
18/// Cache counters are separate because providers price them separately; a
19/// total that folded them in could not be re-derived.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
21pub struct ProviderUsage {
22 /// Tokens in the request.
23 pub input: u64,
24 /// Tokens the model produced.
25 pub output: u64,
26 /// Tokens served from a prompt cache.
27 pub cache_read: u64,
28 /// Tokens written into a prompt cache.
29 pub cache_write: u64,
30 /// Total tokens attributed to the exchange.
31 pub total: u64,
32}
34/// Why a provider stopped producing output.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "snake_case")]
37pub enum StopReason {
38 /// The model finished its turn.
39 EndTurn,
40 /// The model wants a tool to run.
41 ToolUse,
42 /// The token limit was reached first.
43 OverMaxTokens,
44 /// The run was cancelled.
45 Aborted,
46 /// A configured stop sequence matched.
47 StopSequence,
48 /// The run ended in an error.
49 Error,
50}
52/// How much reasoning to request.
53#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
54#[serde(rename_all = "snake_case")]
55pub enum ThinkingLevel {
56 /// No reasoning requested.
57 #[default]
58 Off,
59 /// The smallest budget the provider offers.
60 Minimal,
61 /// A low budget.
62 Low,
63 /// A moderate budget.
64 Medium,
65 /// A high budget.
66 High,
67 /// The largest budget the provider offers.
68 XHigh,
69}
71/// One item in the stream a provider produces.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum ProviderEvent {
75 /// A fragment of assistant text.
76 TextDelta {
77 /// The fragment.
78 text: String,
79 },
80 /// A fragment of model reasoning.
81 ThinkingDelta {
82 /// The fragment.
83 text: String,
84 },
85 /// A complete tool call.
86 ///
87 /// Assembled and whole: providers stream tool arguments in fragments, and
88 /// those are joined at the provider boundary (§7.2). Nothing downstream
89 /// ever sees a partial call, so no consumer needs reassembly logic.
90 ToolCall {
91 /// Correlates with the eventual tool result.
92 id: String,
93 /// The tool being called.
94 name: String,
95 /// Complete JSON arguments.
96 arguments: serde_json::Value,
97 },
98 /// The stream finished.
99 Done {
100 /// Token accounting for the exchange.
101 usage: ProviderUsage,
102 /// Why it stopped.
103 stop_reason: StopReason,
104 },
105 /// The stream failed.
106 Error(ProviderError),
107}
109/// A provider failure, classified by what a caller can do about it.
110///
111/// The variants are the failover-relevant classification `MuxProvider` reads
112/// (§7.5): they distinguish *try another provider* from *stop and tell the
113/// user*, which a single opaque error could not.
114#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
115#[serde(rename_all = "snake_case", tag = "kind", content = "message")]
116pub enum ProviderError {
117 /// The provider is rate-limiting the caller.
118 #[error("rate limited: {0}")]
119 RateLimit(String),
120 /// Credentials were missing, malformed, or rejected.
121 #[error("authentication failed: {0}")]
122 AuthFailed(String),
123 /// The request never completed at the transport layer.
124 #[error("network error: {0}")]
125 Network(String),
126 /// The provider reported a fault on its side.
127 #[error("server error: {0}")]
128 ServerError(String),
129 /// The request was malformed or unacceptable.
130 #[error("invalid request: {0}")]
131 InvalidRequest(String),
132 /// The named model does not exist for this provider.
133 #[error("model not found: {0}")]
134 ModelNotFound(String),
135 /// The request exceeded its time budget.
136 #[error("timed out: {0}")]
137 Timeout(String),
138}
140/// Everything a provider needs to answer one turn.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142pub struct ProviderRequest {
143 /// Conversation so far, oldest first.
144 pub messages: Vec<Message>,
145 /// System prompt, when one applies.
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub system: Option<String>,
148 /// Which provider to address.
149 pub provider_id: String,
150 /// Which model to address on that provider.
151 pub model_id: String,
152 /// Tools the model may call.
153 #[serde(default, skip_serializing_if = "Vec::is_empty")]
154 pub tools: Vec<ToolDefinition>,
155 /// How much reasoning to request.
156 #[serde(default)]
157 pub thinking: ThinkingLevel,
158 /// Cap on tokens the model may produce.
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub max_tokens: Option<u32>,
161 /// Sequences that end the turn when produced.
162 #[serde(default, skip_serializing_if = "Vec::is_empty")]
163 pub stop_sequences: Vec<String>,
164}
166impl ProviderRequest {
167 /// Builds a request addressing `model_id` on `provider_id`.
168 ///
169 /// The optional fields default to empty; a caller sets only what it needs,
170 /// which keeps the skeleton's call sites honest about what they rely on.
171 #[must_use]
172 pub fn new(
173 provider_id: impl Into<String>,
174 model_id: impl Into<String>,
175 messages: Vec<Message>,
176 ) -> Self {
177 Self {
178 messages,
179 system: None,
180 provider_id: provider_id.into(),
181 model_id: model_id.into(),
182 tools: Vec::new(),
183 thinking: ThinkingLevel::Off,
184 max_tokens: None,
185 stop_sequences: Vec::new(),
186 }
187 }
188}
190#[cfg(test)]
191#[expect(
192 clippy::unwrap_used,
193 reason = "Test fixtures use unwrap so setup failures report their exact operation."
194)]
195mod tests {
196 use super::{ProviderError, ProviderEvent, ProviderRequest, ProviderUsage, StopReason};
197 use crate::message::{Message, Role};
199 #[test]
200 fn events_survive_cbor() {
201 let events = vec![
202 ProviderEvent::TextDelta {
203 text: "hel".to_owned(),
204 },
205 ProviderEvent::ThinkingDelta {
206 text: "hmm".to_owned(),
207 },
208 ProviderEvent::ToolCall {
209 id: "call-1".to_owned(),
210 name: "read".to_owned(),
211 arguments: serde_json::json!({ "path": "x" }),
212 },
213 ProviderEvent::Done {
214 usage: ProviderUsage {
215 input: 10,
216 output: 5,
217 cache_read: 1,
218 cache_write: 2,
219 total: 18,
220 },
221 stop_reason: StopReason::EndTurn,
222 },
223 ProviderEvent::Error(ProviderError::RateLimit("slow down".to_owned())),
224 ];
226 let mut bytes = Vec::new();
227 ciborium::into_writer(&events, &mut bytes).unwrap();
228 let restored: Vec<ProviderEvent> = ciborium::from_reader(bytes.as_slice()).unwrap();
229 assert_eq!(restored, events);
230 }
232 #[test]
233 fn provider_errors_carry_their_message() {
234 // The classification drives failover; the message is what reaches the
235 // user, so it must not be swallowed by the variant name.
236 let error = ProviderError::AuthFailed("no ANTHROPIC_API_KEY".to_owned());
237 assert_eq!(
238 error.to_string(),
239 "authentication failed: no ANTHROPIC_API_KEY"
240 );
241 }
243 #[test]
244 fn a_request_omits_what_it_does_not_set() {
245 let request = ProviderRequest::new(
246 "anthropic",
247 "claude-sonnet-4",
248 vec![Message::text(Role::User, "hi")],
249 );
250 let json = serde_json::to_string(&request).unwrap();
251 assert!(!json.contains("system"), "unset system must not appear");
252 assert!(
253 !json.contains("stop_sequences"),
254 "empty lists must not appear"
255 );
256 let restored: ProviderRequest = serde_json::from_str(&json).unwrap();
257 assert_eq!(restored, request);
258 }
259}

smith/src/stream.rs

Added
new file mode 100644

+59 / −0 text lines

1//! The provider abstraction the agent loop consumes (SPEC §5.4).
2
3use std::sync::Arc;
4
5use futures::stream::BoxStream;
6
7use crate::provider::{ProviderEvent, ProviderRequest};
8
9/// Turns a request into a stream of provider events.
10///
11/// This is the whole of what `smith-core` knows about providers: a function
12/// from [`ProviderRequest`] to an async stream of [`ProviderEvent`]. It names
13/// no provider and does not depend on `smith-ai`, which is what lets the two
14/// crates build and be tested independently — and what lets the walking
15/// skeleton run its agent loop against a scripted stream with no network.
16///
17/// It is an `Arc` because the loop shares one provider across tasks, and
18/// `Send + Sync` for the same reason. The returned stream is `'static` so it
19/// can outlive the call that produced it.
20pub type StreamFn = Arc<dyn Fn(ProviderRequest) -> BoxStream<'static, ProviderEvent> + Send + Sync>;
22#[cfg(test)]
23mod tests {
24 use std::sync::Arc;
26 use futures::StreamExt as _;
28 use super::StreamFn;
29 use crate::message::{Message, Role};
30 use crate::provider::{ProviderEvent, ProviderRequest, ProviderUsage, StopReason};
32 #[test]
33 fn a_scripted_stream_satisfies_the_alias() {
34 // This is the shape SM-007 supplies for the walking skeleton: a fixture
35 // sequence replayed with no network. If a scripted function cannot
36 // satisfy the alias, the hermetic end-to-end test has nothing to run
37 // against.
38 let script = vec![
39 ProviderEvent::TextDelta {
40 text: "hello".to_owned(),
41 },
42 ProviderEvent::Done {
43 usage: ProviderUsage::default(),
44 stop_reason: StopReason::EndTurn,
45 },
46 ];
48 let stream_fn: StreamFn = Arc::new(move |_request: ProviderRequest| {
49 futures::stream::iter(script.clone()).boxed()
50 });
52 let request =
53 ProviderRequest::new("scripted", "fixture", vec![Message::text(Role::User, "hi")]);
54 let events: Vec<ProviderEvent> = futures::executor::block_on(stream_fn(request).collect());
56 assert_eq!(events.len(), 2);
57 assert!(matches!(events[1], ProviderEvent::Done { .. }));
58 }
59}

smith/src/tool.rs

Added
new file mode 100644

+226 / −0 text lines

1//! Tool definition and execution types (SPEC §5.3).
2//!
3//! [`AgentTool`] is deliberately object-safe: the tool registry stores tools as
4//! shared handles by name (§6.10), so the trait has to survive `dyn`. That is
5//! why [`AgentTool::execute`] returns a boxed future rather than being written
6//! as an `async fn` — an async method is not callable through `dyn`.
7
8use futures::future::BoxFuture;
9use serde::{Deserialize, Serialize};
11use crate::message::ContentBlock;
13/// Whether a tool may run alongside others in the same turn.
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum ToolExecutionMode {
17 /// Run alone, in call order.
18 ///
19 /// The default: a tool that mutates the workspace is only safe this way,
20 /// and a tool that has not said otherwise is assumed to mutate.
21 #[default]
22 Sequential,
23 /// May run concurrently with other parallel-safe tools.
24 Parallel,
25}
27/// Serializable tool metadata.
28///
29/// This is the form handed to a provider for function calling and published to
30/// plugins; it holds no behavior, so it can cross a wire or a Lua boundary.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct ToolDefinitionSpec {
33 /// The name the model calls.
34 pub name: String,
35 /// What the tool does, written for the model.
36 pub description: String,
37 /// JSON Schema for the arguments, validated with `jsonschema` (§5.3).
38 pub parameters: serde_json::Value,
39 /// Whether the tool may run in parallel.
40 #[serde(default)]
41 pub execution_mode: ToolExecutionMode,
42}
44/// Runtime tool definition, as used by providers and the agent loop.
45///
46/// Distinct from [`ToolDefinitionSpec`] so that runtime-only fields can be
47/// added later without changing the serialized shape that plugins and
48/// providers already depend on.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct ToolDefinition {
51 /// The serializable metadata.
52 #[serde(flatten)]
53 pub spec: ToolDefinitionSpec,
54}
56impl ToolDefinition {
57 /// Wraps a spec as a runtime definition.
58 #[must_use]
59 pub const fn new(spec: ToolDefinitionSpec) -> Self {
60 Self { spec }
61 }
63 /// The name the model calls.
64 #[must_use]
65 pub fn name(&self) -> &str {
66 &self.spec.name
67 }
68}
70/// Progress a tool recorded while it ran.
71///
72/// §5.3 surfaces these only inside the completed [`AgentToolResult`], so they
73/// are a record of what happened rather than a live feed — nothing here moves a
74/// progress indicator mid-run. Whether a long tool should be able to report
75/// before it finishes is the open question on #132.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct AgentToolUpdate {
78 /// Human-readable progress.
79 pub message: String,
80}
82/// What a tool produced.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84pub struct AgentToolResult {
85 /// The output, as content the model can read.
86 pub content: Vec<ContentBlock>,
87 /// Whether `content` describes a failure.
88 ///
89 /// A failed tool is not an error for the agent loop: the model is told and
90 /// decides what to do next, which is why this is a flag rather than a
91 /// `Result`.
92 pub is_error: bool,
93 /// Progress emitted while running.
94 #[serde(default, skip_serializing_if = "Vec::is_empty")]
95 pub updates: Vec<AgentToolUpdate>,
96}
98impl AgentToolResult {
99 /// A successful result carrying one text block.
100 #[must_use]
101 pub fn text(text: impl Into<String>) -> Self {
102 Self {
103 content: vec![ContentBlock::Text(text.into())],
104 is_error: false,
105 updates: Vec::new(),
106 }
107 }
109 /// A failed result carrying one text block.
110 #[must_use]
111 pub fn error(text: impl Into<String>) -> Self {
112 Self {
113 content: vec![ContentBlock::Text(text.into())],
114 is_error: true,
115 updates: Vec::new(),
116 }
117 }
118}
120/// A tool the agent loop can call.
121///
122/// `Send + Sync` because tools are shared across tasks by the registry
123/// (§6.10). Arguments arrive as JSON and are validated against
124/// [`ToolDefinitionSpec::parameters`] before `execute` is reached, so an
125/// implementation reads its arguments rather than re-checking them.
126pub trait AgentTool: Send + Sync {
127 /// How this tool presents itself to the model.
128 fn definition(&self) -> ToolDefinition;
130 /// Runs the tool.
131 ///
132 /// Returns a boxed future so the trait stays object-safe; see the module
133 /// documentation.
134 fn execute(&self, arguments: serde_json::Value) -> BoxFuture<'_, AgentToolResult>;
135}
137#[cfg(test)]
138#[expect(
139 clippy::unwrap_used,
140 reason = "Test fixtures use unwrap so setup failures report their exact operation."
141)]
142mod tests {
143 use std::sync::Arc;
145 use futures::FutureExt as _;
146 use futures::future::BoxFuture;
148 use super::{
149 AgentTool, AgentToolResult, ToolDefinition, ToolDefinitionSpec, ToolExecutionMode,
150 };
151 use crate::message::ContentBlock;
153 struct Echo;
155 impl AgentTool for Echo {
156 fn definition(&self) -> ToolDefinition {
157 ToolDefinition::new(ToolDefinitionSpec {
158 name: "echo".to_owned(),
159 description: "Returns its argument.".to_owned(),
160 parameters: serde_json::json!({
161 "type": "object",
162 "properties": { "text": { "type": "string" } },
163 "required": ["text"],
164 }),
165 execution_mode: ToolExecutionMode::Parallel,
166 })
167 }
169 fn execute(&self, arguments: serde_json::Value) -> BoxFuture<'_, AgentToolResult> {
170 async move {
171 let text = arguments
172 .get("text")
173 .and_then(serde_json::Value::as_str)
174 .unwrap_or_default()
175 .to_owned();
176 AgentToolResult::text(text)
177 }
178 .boxed()
179 }
180 }
182 #[test]
183 fn a_tool_is_usable_behind_dyn() {
184 // The registry stores tools as shared handles by name (§6.10), so the
185 // trait has to survive both `dyn` and `Arc`. If this stops compiling,
186 // the registry cannot be built on it.
187 let tool: Arc<dyn AgentTool> = Arc::new(Echo);
188 assert_eq!(tool.definition().name(), "echo");
190 let result =
191 futures::executor::block_on(tool.execute(serde_json::json!({ "text": "hello" })));
192 assert!(!result.is_error);
193 assert_eq!(result.content, vec![ContentBlock::Text("hello".to_owned())]);
194 }
196 #[test]
197 fn a_definition_serializes_flat() {
198 // Providers receive the spec's fields directly; a nested `spec` key
199 // would not match any provider's function-calling shape.
200 let definition = Echo.definition();
201 let json = serde_json::to_value(&definition).unwrap();
202 assert_eq!(
203 json.get("name").and_then(serde_json::Value::as_str),
204 Some("echo")
205 );
206 assert!(json.get("spec").is_none(), "the spec must flatten: {json}");
208 let restored: ToolDefinition = serde_json::from_value(json).unwrap();
209 assert_eq!(restored, definition);
210 }
212 #[test]
213 fn tools_are_sequential_unless_they_say_otherwise() {
214 assert_eq!(ToolExecutionMode::default(), ToolExecutionMode::Sequential);
215 }
217 #[test]
218 fn an_error_result_is_still_content() {
219 let result = AgentToolResult::error("no such file");
220 assert!(result.is_error);
221 assert_eq!(
222 result.content,
223 vec![ContentBlock::Text("no such file".to_owned())]
224 );
225 }
226}