repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

core(SMH-PLAN-CORE0001): implement session, framing, tools, and bounded bash

0e7875172c50b61f410b36873162cec2d12cefbf

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Approve the plan after foundation gates and deliver the provider-free
runtime across two crates: shared IDs, messages, stream events, tool
metadata, cancellation, and errors in smith; validated config, session
model, CBOR framing, durable store, replay traces, tool registry with
file effects, and bounded cancellable bash in smith-core.

Harden per review findings: tagged content blocks keep Thinking distinct
on disk; opening a session repairs torn tails before appending; repairs
publish atomically; the writer enforces the configured frame limit and
holds an exclusive lock; loaders decode incrementally and skip oversized
frames by intact length; tool schemas validate before effects; writes
are atomic with parent creation; exact edits reject ambiguity; tool
invocation couples effects to recorded outcomes; bash drains pipes on
threads, keeps output prefixes, bounds post-exit collection, and kills
the owned process group on timeout or cancellation.

Changed files (19)

+3739 / −7 text lines

Diff layout

.system/plans/SMH-PLAN-CORE0001-core-session-and-tools/index.md

Modified

+1 / −1 text lines

33type: plan
44title: "Core Session and Tool Effects"
55spec: SMH-SPEC-SPEC0001
6status: draft
6status: approved
77depends_on: [SMH-PLAN-WSPC0001]
88---

Cargo.lock

Modified

+586 / −0 text lines

22# It is not intended for manual editing.
33version = 4
5[[package]]
6name = "bitflags"
7version = "2.13.2"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
11[[package]]
12name = "bumpalo"
13version = "3.20.3"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
17[[package]]
18name = "cfg-if"
19version = "1.0.4"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
23[[package]]
24name = "cfg_aliases"
25version = "0.2.2"
26source = "registry+https://github.com/rust-lang/crates.io-index"
27checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
29[[package]]
30name = "ciborium"
31version = "0.2.2"
32source = "registry+https://github.com/rust-lang/crates.io-index"
33checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
34dependencies = [
35 "ciborium-io",
36 "ciborium-ll",
37 "serde",
38]
40[[package]]
41name = "ciborium-io"
42version = "0.2.2"
43source = "registry+https://github.com/rust-lang/crates.io-index"
44checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
46[[package]]
47name = "ciborium-ll"
48version = "0.2.2"
49source = "registry+https://github.com/rust-lang/crates.io-index"
50checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
51dependencies = [
52 "ciborium-io",
53 "half",
54]
56[[package]]
57name = "crunchy"
58version = "0.2.4"
59source = "registry+https://github.com/rust-lang/crates.io-index"
60checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
62[[package]]
63name = "dirs"
64version = "5.0.1"
65source = "registry+https://github.com/rust-lang/crates.io-index"
66checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
67dependencies = [
68 "dirs-sys",
69]
71[[package]]
72name = "dirs-sys"
73version = "0.4.1"
74source = "registry+https://github.com/rust-lang/crates.io-index"
75checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
76dependencies = [
77 "libc",
78 "option-ext",
79 "redox_users",
80 "windows-sys",
81]
83[[package]]
84name = "equivalent"
85version = "1.0.2"
86source = "registry+https://github.com/rust-lang/crates.io-index"
87checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
89[[package]]
90name = "fs2"
91version = "0.4.3"
92source = "registry+https://github.com/rust-lang/crates.io-index"
93checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
94dependencies = [
95 "libc",
96 "winapi",
97]
99[[package]]
100name = "futures-core"
101version = "0.3.34"
102source = "registry+https://github.com/rust-lang/crates.io-index"
103checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
105[[package]]
106name = "futures-task"
107version = "0.3.34"
108source = "registry+https://github.com/rust-lang/crates.io-index"
109checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
111[[package]]
112name = "futures-util"
113version = "0.3.34"
114source = "registry+https://github.com/rust-lang/crates.io-index"
115checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
116dependencies = [
117 "futures-core",
118 "futures-task",
119 "pin-project-lite",
120 "slab",
121]
123[[package]]
124name = "getrandom"
125version = "0.2.17"
126source = "registry+https://github.com/rust-lang/crates.io-index"
127checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
128dependencies = [
129 "cfg-if",
130 "libc",
131 "wasi",
132]
134[[package]]
135name = "getrandom"
136version = "0.4.3"
137source = "registry+https://github.com/rust-lang/crates.io-index"
138checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
139dependencies = [
140 "cfg-if",
141 "libc",
142 "r-efi",
143]
145[[package]]
146name = "half"
147version = "2.7.1"
148source = "registry+https://github.com/rust-lang/crates.io-index"
149checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
150dependencies = [
151 "cfg-if",
152 "crunchy",
153 "zerocopy",
154]
156[[package]]
157name = "hashbrown"
158version = "0.17.1"
159source = "registry+https://github.com/rust-lang/crates.io-index"
160checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
162[[package]]
163name = "indexmap"
164version = "2.14.2"
165source = "registry+https://github.com/rust-lang/crates.io-index"
166checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
167dependencies = [
168 "equivalent",
169 "hashbrown",
170]
172[[package]]
173name = "itoa"
174version = "1.0.18"
175source = "registry+https://github.com/rust-lang/crates.io-index"
176checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
178[[package]]
179name = "js-sys"
180version = "0.3.105"
181source = "registry+https://github.com/rust-lang/crates.io-index"
182checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e"
183dependencies = [
184 "cfg-if",
185 "futures-util",
186 "wasm-bindgen",
187]
189[[package]]
190name = "libc"
191version = "0.2.189"
192source = "registry+https://github.com/rust-lang/crates.io-index"
193checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
195[[package]]
196name = "libredox"
197version = "0.1.23"
198source = "registry+https://github.com/rust-lang/crates.io-index"
199checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed"
200dependencies = [
201 "libc",
202]
204[[package]]
205name = "memchr"
206version = "2.8.3"
207source = "registry+https://github.com/rust-lang/crates.io-index"
208checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
210[[package]]
211name = "nix"
212version = "0.29.0"
213source = "registry+https://github.com/rust-lang/crates.io-index"
214checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
215dependencies = [
216 "bitflags",
217 "cfg-if",
218 "cfg_aliases",
219 "libc",
220]
222[[package]]
223name = "once_cell"
224version = "1.21.4"
225source = "registry+https://github.com/rust-lang/crates.io-index"
226checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
228[[package]]
229name = "option-ext"
230version = "0.2.0"
231source = "registry+https://github.com/rust-lang/crates.io-index"
232checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
234[[package]]
235name = "pin-project-lite"
236version = "0.2.17"
237source = "registry+https://github.com/rust-lang/crates.io-index"
238checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
240[[package]]
241name = "proc-macro2"
242version = "1.0.107"
243source = "registry+https://github.com/rust-lang/crates.io-index"
244checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
245dependencies = [
246 "unicode-ident",
247]
249[[package]]
250name = "quote"
251version = "1.0.47"
252source = "registry+https://github.com/rust-lang/crates.io-index"
253checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
254dependencies = [
255 "proc-macro2",
256]
258[[package]]
259name = "r-efi"
260version = "6.0.0"
261source = "registry+https://github.com/rust-lang/crates.io-index"
262checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
264[[package]]
265name = "redox_users"
266version = "0.4.6"
267source = "registry+https://github.com/rust-lang/crates.io-index"
268checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
269dependencies = [
270 "getrandom 0.2.17",
271 "libredox",
272 "thiserror 1.0.69",
273]
275[[package]]
276name = "rustversion"
277version = "1.0.23"
278source = "registry+https://github.com/rust-lang/crates.io-index"
279checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
281[[package]]
282name = "serde"
283version = "1.0.229"
284source = "registry+https://github.com/rust-lang/crates.io-index"
285checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
286dependencies = [
287 "serde_core",
288 "serde_derive",
289]
291[[package]]
292name = "serde_core"
293version = "1.0.229"
294source = "registry+https://github.com/rust-lang/crates.io-index"
295checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
296dependencies = [
297 "serde_derive",
298]
300[[package]]
301name = "serde_derive"
302version = "1.0.229"
303source = "registry+https://github.com/rust-lang/crates.io-index"
304checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
305dependencies = [
306 "proc-macro2",
307 "quote",
308 "syn 3.0.5",
309]
311[[package]]
312name = "serde_json"
313version = "1.0.151"
314source = "registry+https://github.com/rust-lang/crates.io-index"
315checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
316dependencies = [
317 "indexmap",
318 "itoa",
319 "memchr",
320 "serde",
321 "serde_core",
322 "zmij",
323]
325[[package]]
326name = "slab"
327version = "0.4.12"
328source = "registry+https://github.com/rust-lang/crates.io-index"
329checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
5331[[package]]
6332name = "smith"
7333version = "0.1.0"
334dependencies = [
335 "ciborium",
336 "serde",
337 "serde_json",
338 "thiserror 2.0.20",
339 "uuid",
340]
9342[[package]]
10343name = "smith-ai"
25358name = "smith-core"
26359version = "0.1.0"
27360dependencies = [
361 "ciborium",
362 "dirs",
363 "fs2",
364 "nix",
365 "serde",
366 "serde_json",
28367 "smith",
368 "thiserror 2.0.20",
369 "uuid",
31372[[package]]
45386 "smith",
389[[package]]
390name = "syn"
391version = "2.0.119"
392source = "registry+https://github.com/rust-lang/crates.io-index"
393checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
394dependencies = [
395 "proc-macro2",
396 "quote",
397 "unicode-ident",
398]
400[[package]]
401name = "syn"
402version = "3.0.5"
403source = "registry+https://github.com/rust-lang/crates.io-index"
404checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
405dependencies = [
406 "proc-macro2",
407 "quote",
408 "unicode-ident",
409]
411[[package]]
412name = "thiserror"
413version = "1.0.69"
414source = "registry+https://github.com/rust-lang/crates.io-index"
415checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
416dependencies = [
417 "thiserror-impl 1.0.69",
418]
420[[package]]
421name = "thiserror"
422version = "2.0.20"
423source = "registry+https://github.com/rust-lang/crates.io-index"
424checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
425dependencies = [
426 "thiserror-impl 2.0.20",
427]
429[[package]]
430name = "thiserror-impl"
431version = "1.0.69"
432source = "registry+https://github.com/rust-lang/crates.io-index"
433checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
434dependencies = [
435 "proc-macro2",
436 "quote",
437 "syn 2.0.119",
438]
440[[package]]
441name = "thiserror-impl"
442version = "2.0.20"
443source = "registry+https://github.com/rust-lang/crates.io-index"
444checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
445dependencies = [
446 "proc-macro2",
447 "quote",
448 "syn 3.0.5",
449]
451[[package]]
452name = "unicode-ident"
453version = "1.0.24"
454source = "registry+https://github.com/rust-lang/crates.io-index"
455checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
457[[package]]
458name = "uuid"
459version = "1.26.1"
460source = "registry+https://github.com/rust-lang/crates.io-index"
461checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
462dependencies = [
463 "getrandom 0.4.3",
464 "js-sys",
465 "serde_core",
466 "wasm-bindgen",
467]
469[[package]]
470name = "wasi"
471version = "0.11.1+wasi-snapshot-preview1"
472source = "registry+https://github.com/rust-lang/crates.io-index"
473checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
475[[package]]
476name = "wasm-bindgen"
477version = "0.2.128"
478source = "registry+https://github.com/rust-lang/crates.io-index"
479checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf"
480dependencies = [
481 "cfg-if",
482 "once_cell",
483 "rustversion",
484 "wasm-bindgen-macro",
485 "wasm-bindgen-shared",
486]
488[[package]]
489name = "wasm-bindgen-macro"
490version = "0.2.128"
491source = "registry+https://github.com/rust-lang/crates.io-index"
492checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed"
493dependencies = [
494 "quote",
495 "wasm-bindgen-macro-support",
496]
498[[package]]
499name = "wasm-bindgen-macro-support"
500version = "0.2.128"
501source = "registry+https://github.com/rust-lang/crates.io-index"
502checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a"
503dependencies = [
504 "bumpalo",
505 "proc-macro2",
506 "quote",
507 "syn 3.0.5",
508 "wasm-bindgen-shared",
509]
511[[package]]
512name = "wasm-bindgen-shared"
513version = "0.2.128"
514source = "registry+https://github.com/rust-lang/crates.io-index"
515checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e"
516dependencies = [
517 "unicode-ident",
518]
520[[package]]
521name = "winapi"
522version = "0.3.9"
523source = "registry+https://github.com/rust-lang/crates.io-index"
524checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
525dependencies = [
526 "winapi-i686-pc-windows-gnu",
527 "winapi-x86_64-pc-windows-gnu",
528]
530[[package]]
531name = "winapi-i686-pc-windows-gnu"
532version = "0.4.0"
533source = "registry+https://github.com/rust-lang/crates.io-index"
534checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
536[[package]]
537name = "winapi-x86_64-pc-windows-gnu"
538version = "0.4.0"
539source = "registry+https://github.com/rust-lang/crates.io-index"
540checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
542[[package]]
543name = "windows-sys"
544version = "0.48.0"
545source = "registry+https://github.com/rust-lang/crates.io-index"
546checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
547dependencies = [
548 "windows-targets",
549]
551[[package]]
552name = "windows-targets"
553version = "0.48.5"
554source = "registry+https://github.com/rust-lang/crates.io-index"
555checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
556dependencies = [
557 "windows_aarch64_gnullvm",
558 "windows_aarch64_msvc",
559 "windows_i686_gnu",
560 "windows_i686_msvc",
561 "windows_x86_64_gnu",
562 "windows_x86_64_gnullvm",
563 "windows_x86_64_msvc",
564]
566[[package]]
567name = "windows_aarch64_gnullvm"
568version = "0.48.5"
569source = "registry+https://github.com/rust-lang/crates.io-index"
570checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
572[[package]]
573name = "windows_aarch64_msvc"
574version = "0.48.5"
575source = "registry+https://github.com/rust-lang/crates.io-index"
576checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
578[[package]]
579name = "windows_i686_gnu"
580version = "0.48.5"
581source = "registry+https://github.com/rust-lang/crates.io-index"
582checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
584[[package]]
585name = "windows_i686_msvc"
586version = "0.48.5"
587source = "registry+https://github.com/rust-lang/crates.io-index"
588checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
590[[package]]
591name = "windows_x86_64_gnu"
592version = "0.48.5"
593source = "registry+https://github.com/rust-lang/crates.io-index"
594checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
596[[package]]
597name = "windows_x86_64_gnullvm"
598version = "0.48.5"
599source = "registry+https://github.com/rust-lang/crates.io-index"
600checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
602[[package]]
603name = "windows_x86_64_msvc"
604version = "0.48.5"
605source = "registry+https://github.com/rust-lang/crates.io-index"
606checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
48608[[package]]
49609name = "xtask"
50610version = "0.1.0"
612[[package]]
613name = "zerocopy"
614version = "0.8.57"
615source = "registry+https://github.com/rust-lang/crates.io-index"
616checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873"
617dependencies = [
618 "zerocopy-derive",
619]
621[[package]]
622name = "zerocopy-derive"
623version = "0.8.57"
624source = "registry+https://github.com/rust-lang/crates.io-index"
625checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc"
626dependencies = [
627 "proc-macro2",
628 "quote",
629 "syn 2.0.119",
630]
632[[package]]
633name = "zmij"
634version = "1.0.23"
635source = "registry+https://github.com/rust-lang/crates.io-index"
636checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

Cargo.toml

Modified

+3 / −2 text lines

1919mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }
2020mlua-pkg = "0.2"
2121serde = { version = "1", features = ["derive"] }
22serde_json = "1"
22serde_json = { version = "1", features = ["preserve_order"] }
2323tokio = { version = "1", features = ["full"] }
2424clap = { version = "4", features = ["derive"] }
2525clap_complete = "4"
4747insta = "1"
4848dirs = "5"
4949jsonschema = "0.28"
50uuid = { version = "1", features = ["v7"] }
50uuid = { version = "1", features = ["v7", "serde"] }
5151assert_cmd = "2"
5252assert_fs = "1"
5353proptest = "1"
5858zip = { version = "2", default-features = false, features = ["deflate"] }
5959tar = "0.4"
6060flate2 = "1"
61fs2 = "0.4"
6263[profile.release]
6364opt-level = 3

smith-core/Cargo.toml

Modified

+10 / −0 text lines

1010[dependencies]
1111smith = { path = "../smith" }
12serde = { workspace = true }
13serde_json = { workspace = true }
14ciborium = { workspace = true }
15thiserror = { workspace = true }
16uuid = { workspace = true }
17dirs = { workspace = true }
18fs2 = { workspace = true }
20[target.'cfg(unix)'.dependencies]
21nix = { version = "0.29", features = ["signal"] }No final newline

smith-core/src/bash.rs

Added
new file mode 100644

+318 / −0 text lines

1//! Bounded, cancellable shell execution with owned-process-tree termination.
2//!
3//! Pipes are drained by dedicated threads so the deadline loop is never
4//! blocked by a silent child; per-stream caps keep the fitting prefix and
5//! bound all collection, including post-exit draining.
6
7use smith::error::{Result, SmithError};
8use smith::tool::CancelHandle;
9use std::io::Read;
10use std::process::{Child, Command, ExitStatus, Stdio};
11use std::sync::Arc;
12use std::sync::atomic::{AtomicUsize, Ordering};
13use std::sync::mpsc::{self, RecvTimeoutError};
14use std::time::{Duration, Instant};
16const READ_CHUNK: usize = 16 * 1024;
17const GRACE_DRAIN: Duration = Duration::from_millis(500);
18const POLL_SLICE: Duration = Duration::from_millis(25);
20/// Result of a bounded shell execution.
21#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
22pub struct BashResult {
23 /// Exit status; `None` when killed by timeout, cancellation, or signal.
24 pub exit_code: Option<i32>,
25 /// Stdout, capped with the fitting prefix retained.
26 pub stdout: String,
27 /// Stderr, capped with the fitting prefix retained.
28 pub stderr: String,
29 /// Cancellation was requested.
30 pub cancelled: bool,
31 /// The deadline elapsed and the process tree was killed.
32 pub timed_out: bool,
33 /// Wall-clock duration in ms.
34 pub duration_ms: u64,
35}
37/// Run `cmd` under `bash -c` in `workdir` with a hard deadline, per-stream
38/// output caps, and a shared cancellation handle.
39pub fn execute(
40 cmd: &str,
41 workdir: Option<&str>,
42 timeout_ms: u64,
43 max_output_bytes: usize,
44 cancel: &CancelHandle,
45) -> Result<BashResult> {
46 let started = Instant::now();
47 let deadline = started + Duration::from_millis(timeout_ms.max(1));
48 let mut child = spawn(cmd, workdir)?;
49 let (tx, rx) = mpsc::channel::<(Stream, Vec<u8>)>();
50 let stdout_remaining = Arc::new(AtomicUsize::new(max_output_bytes));
51 let stderr_remaining = Arc::new(AtomicUsize::new(max_output_bytes));
52 let handles = drain_pipes(
53 &mut child,
54 tx.clone(),
55 stdout_remaining.clone(),
56 stderr_remaining.clone(),
57 );
58 drop(tx); // reader threads hold the only senders
60 let mut stdout: Vec<u8> = Vec::new();
61 let mut stderr: Vec<u8> = Vec::new();
62 let mut status: Option<ExitStatus> = None;
63 let mut cancelled = false;
64 let mut timed_out = false;
66 while status.is_none() {
67 if cancel.is_cancelled() {
68 cancelled = true;
69 kill_tree(&mut child);
70 status = child.wait().ok();
71 break;
72 }
73 let now = Instant::now();
74 if now >= deadline {
75 timed_out = true;
76 kill_tree(&mut child);
77 status = child.wait().ok();
78 break;
79 }
80 let wait = POLL_SLICE.min(deadline - now);
81 match rx.recv_timeout(wait) {
82 Ok((stream, chunk)) => match stream {
83 Stream::Stdout => stdout.extend_from_slice(&chunk),
84 Stream::Stderr => stderr.extend_from_slice(&chunk),
85 },
86 Err(RecvTimeoutError::Timeout) => {}
87 Err(RecvTimeoutError::Disconnected) => {
88 // Both pipes closed: reap without blocking past the deadline.
89 while status.is_none() && Instant::now() < deadline {
90 if let Ok(Some(st)) = child.try_wait() {
91 status = Some(st);
92 }
93 }
94 if status.is_none() {
95 if let Ok(Some(st)) = child.try_wait() {
96 status = Some(st);
97 }
98 }
99 }
100 }
101 if status.is_none() {
102 if let Ok(Some(st)) = child.try_wait() {
103 status = Some(st);
104 break;
105 }
106 }
107 }
109 // Bounded post-exit drain: retain late output until pipes close or the
110 // grace window expires. Threads only ever send capped prefixes.
111 let grace_end = Instant::now() + GRACE_DRAIN;
112 while Instant::now() < grace_end {
113 match rx.recv_timeout(Duration::from_millis(50)) {
114 Ok((stream, chunk)) => match stream {
115 Stream::Stdout => stdout.extend_from_slice(&chunk),
116 Stream::Stderr => stderr.extend_from_slice(&chunk),
117 },
118 Err(RecvTimeoutError::Timeout) => continue,
119 Err(RecvTimeoutError::Disconnected) => break,
120 }
121 }
122 for handle in handles {
123 let _ = handle.join();
124 }
126 Ok(BashResult {
127 exit_code: status.as_ref().and_then(ExitStatus::code),
128 stdout: String::from_utf8_lossy(&stdout).into_owned(),
129 stderr: String::from_utf8_lossy(&stderr).into_owned(),
130 cancelled,
131 timed_out,
132 duration_ms: started.elapsed().as_millis() as u64,
133 })
134}
136#[derive(Clone, Copy)]
137enum Stream {
138 Stdout,
139 Stderr,
140}
142fn spawn(cmd: &str, workdir: Option<&str>) -> Result<Child> {
143 let mut command = Command::new("bash");
144 command
145 .arg("-c")
146 .arg(cmd)
147 .stdout(Stdio::piped())
148 .stderr(Stdio::piped());
149 if let Some(dir) = workdir {
150 command.current_dir(dir);
151 }
152 #[cfg(unix)]
153 {
154 use std::os::unix::process::CommandExt;
155 // Own the process tree: the child becomes a group leader so the
156 // deadline path can signal every descendant.
157 command.process_group(0);
158 }
159 command.spawn().map_err(|e| SmithError::Tool {
160 code: "BASH_SPAWN".to_string(),
161 message: e.to_string(),
162 })
163}
165/// Kill the whole owned process group where the platform supports it,
166/// falling back to the direct child.
167fn kill_tree(child: &mut Child) {
168 #[cfg(unix)]
169 {
170 use nix::sys::signal::{Signal, killpg};
171 use nix::unistd::Pid;
172 let pgid = Pid::from_raw(child.id() as i32);
173 let _ = killpg(pgid, Signal::SIGKILL);
174 }
175 let _ = child.kill();
176}
178/// Spawn one reader thread per pipe. Each thread forwards capped prefixes
179/// (never more than `remaining` permits) and keeps draining to EOF so a
180/// chatty descendant can never deadlock the parent.
181fn drain_pipes(
182 child: &mut Child,
183 tx: mpsc::Sender<(Stream, Vec<u8>)>,
184 stdout_remaining: Arc<AtomicUsize>,
185 stderr_remaining: Arc<AtomicUsize>,
186) -> Vec<std::thread::JoinHandle<()>> {
187 let mut handles = Vec::new();
188 if let Some(out) = child.stdout.take() {
189 handles.push(spawn_reader(
190 out,
191 tx.clone(),
192 Stream::Stdout,
193 stdout_remaining,
194 ));
195 }
196 if let Some(err) = child.stderr.take() {
197 handles.push(spawn_reader(
198 err,
199 tx.clone(),
200 Stream::Stderr,
201 stderr_remaining,
202 ));
203 }
204 handles
205}
207fn spawn_reader<R: Read + Send + 'static>(
208 mut pipe: R,
209 tx: mpsc::Sender<(Stream, Vec<u8>)>,
210 stream: Stream,
211 remaining: Arc<AtomicUsize>,
212) -> std::thread::JoinHandle<()> {
213 std::thread::spawn(move || {
214 let mut buf = vec![0u8; READ_CHUNK];
215 loop {
216 match pipe.read(&mut buf) {
217 Ok(0) => break,
218 Ok(n) => {
219 let keep = n.min(remaining.load(Ordering::Relaxed));
220 if keep > 0 {
221 if tx.send((stream, buf[..keep].to_vec())).is_err() {
222 break;
223 }
224 remaining.fetch_sub(keep, Ordering::Relaxed);
225 }
226 // Beyond the cap we keep reading (without retaining) so
227 // the pipe never back-pressures the child indefinitely.
228 }
229 Err(_) => break,
230 }
231 }
232 })
233}
235#[cfg(test)]
236#[cfg(unix)]
237#[allow(clippy::unwrap_used, clippy::expect_used)]
238mod tests {
239 use super::*;
240 use std::thread;
241 use std::time::Duration;
243 fn run(cmd: &str, timeout_ms: u64, cap: usize) -> BashResult {
244 execute(cmd, None, timeout_ms, cap, &CancelHandle::new()).unwrap()
245 }
247 #[test]
248 fn completes_and_captures_output() {
249 let res = run("printf 'hello'", 5_000, 1024);
250 assert_eq!(res.exit_code, Some(0));
251 assert_eq!(res.stdout, "hello");
252 assert!(!res.timed_out && !res.cancelled);
253 }
255 #[test]
256 fn timeout_kills_silent_child_promptly() {
257 let res = run("sleep 30", 400, 1024);
258 assert!(res.timed_out);
259 assert_eq!(res.exit_code, None);
260 assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
261 }
263 #[test]
264 fn stderr_heavy_child_cannot_deadlock_the_deadline() {
265 let res = run("while true; do echo noise >&2; done", 400, 4096);
266 assert!(res.timed_out);
267 assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
268 }
270 #[test]
271 fn cancellation_stops_execution() {
272 let cancel = CancelHandle::new();
273 let handle = {
274 let cancel = cancel.clone();
275 thread::spawn(move || {
276 thread::sleep(Duration::from_millis(120));
277 cancel.cancel();
278 })
279 };
280 let res = execute("sleep 30", None, 10_000, 1024, &cancel).unwrap();
281 handle.join().unwrap();
282 assert!(res.cancelled);
283 assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
284 }
286 #[test]
287 fn output_cap_keeps_fitting_prefix() {
288 let res = run("printf 'abcdefghij'", 5_000, 5);
289 assert_eq!(res.stdout, "abcde");
290 }
292 #[test]
293 fn high_volume_output_is_not_throttled() {
294 let started = Instant::now();
295 let res = run("head -c 300000 /dev/zero | tr '\\0' 'x'", 10_000, 1 << 20);
296 assert_eq!(res.stdout.len(), 300_000);
297 assert!(
298 started.elapsed() < Duration::from_secs(3),
299 "throughput regression: {} bytes in {:?}",
300 res.stdout.len(),
301 started.elapsed()
302 );
303 }
305 #[test]
306 fn descendant_processes_are_killed_with_the_tree() {
307 let dir = std::env::temp_dir().join(format!("smith_bash_tree_{}", std::process::id()));
308 let _ = std::fs::remove_dir_all(&dir);
309 std::fs::create_dir_all(&dir).unwrap();
310 let marker = dir.join("descendant_survived");
311 let script = format!("(sleep 30; touch {}) & sleep 30", marker.display());
312 let res = run(&script, 300, 1024);
313 assert!(res.timed_out);
314 thread::sleep(Duration::from_millis(1200));
315 assert!(!marker.exists(), "descendant survived the timeout kill");
316 let _ = std::fs::remove_dir_all(&dir);
317 }
318}

smith-core/src/config.rs

Added
new file mode 100644

+54 / −0 text lines

1use serde::{Deserialize, Serialize};
2
3/// Runtime configuration (validated, no plugin loading).
4#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
5pub struct Config {
6 /// Session directory path.
7 pub session_dir: String,
8 /// Maximum frame size in bytes.
9 pub max_frame_bytes: usize,
10 /// Timeout for tool effects.
11 pub tool_timeout_ms: u64,
12 /// Whether to preserve unknown frames during repair.
13 pub preserve_unknown_frames: bool,
14}
16impl Config {
17 /// Default validated configuration. Session data resolves under the
18 /// platform data directory (XDG data home on Linux).
19 pub fn default_valid() -> Self {
20 let session_dir = match dirs::data_dir() {
21 Some(base) => base.join("smith").join("sessions"),
22 None => std::path::PathBuf::from(".smith").join("sessions"),
23 };
24 Self {
25 session_dir: session_dir.to_string_lossy().into_owned(),
26 max_frame_bytes: 1024 * 1024,
27 tool_timeout_ms: 30_000,
28 preserve_unknown_frames: true,
29 }
30 }
32 /// Validate the configuration.
33 pub fn validate(&self) -> Result<(), String> {
34 if self.session_dir.trim().is_empty() {
35 return Err("session_dir must not be empty".to_string());
36 }
37 if self.max_frame_bytes < 1024 {
38 return Err("max_frame_bytes must be at least 1024".to_string());
39 }
40 if self.max_frame_bytes > 1024 * 1024 * 100 {
41 return Err("max_frame_bytes exceeds safe limit of 100MB".to_string());
42 }
43 if self.tool_timeout_ms < 100 {
44 return Err("tool_timeout_ms must be at least 100ms".to_string());
45 }
46 Ok(())
47 }
48}
50impl Default for Config {
51 fn default() -> Self {
52 Self::default_valid()
53 }
54}

smith-core/src/frame.rs

Added
new file mode 100644

+365 / −0 text lines

1//! Length-prefixed CBOR session framing.
2//!
3//! Wire format: `[4-byte little-endian payload length][CBOR payload]`.
4//! Encoding is size-bounded; decoding is slice-based and reports exactly
5//! how many bytes were consumed, whether a frame is incomplete, or whether
6//! a corrupt oversized frame was skipped by its intact length.
7
8use crate::session::Entry;
9use smith::error::{Result, SmithError};
10use std::io::Write;
12/// Default frame size ceiling when no configuration is supplied.
13pub const DEFAULT_MAX_FRAME_BYTES: usize = 1024 * 1024;
15/// Maximum representable declared length (u32 LE header).
16pub const MAX_DECLARED_LENGTH: usize = u32::MAX as usize;
18pub(crate) const HEADER_LEN: usize = 4;
20/// A decoded session frame.
21#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
22pub enum Frame {
23 /// A known session entry.
24 Known {
25 /// Decoded entry.
26 entry: Entry,
27 },
28 /// An opaque future frame; raw payload is preserved unchanged.
29 Unknown {
30 /// Exact payload bytes as read.
31 raw_bytes: Vec<u8>,
32 /// Declared payload length (equals `raw_bytes.len()`).
33 declared_length: usize,
34 },
35}
37impl Frame {
38 /// Serialize a known entry into a frame payload, rejecting sizes above `max_frame_bytes`
39 /// before unbounded allocation occurs.
40 pub fn encode_entry(entry: &Entry, max_frame_bytes: usize) -> Result<Vec<u8>> {
41 let mut limited = LimitedWriter::new(max_frame_bytes);
42 match ciborium::ser::into_writer(entry, &mut limited) {
43 Ok(()) => {}
44 Err(e) => {
45 if limited.overflowed() {
46 return Err(SmithError::FrameTooLarge {
47 max_bytes: max_frame_bytes,
48 actual: max_frame_bytes + 1,
49 });
50 }
51 return Err(SmithError::FrameEncode {
52 message: e.to_string(),
53 });
54 }
55 }
56 if limited.overflowed() {
57 return Err(SmithError::FrameTooLarge {
58 max_bytes: max_frame_bytes,
59 actual: max_frame_bytes + 1,
60 });
61 }
62 Ok(limited.into_inner())
63 }
65 /// Encode the full frame (header + payload) enforcing `max_frame_bytes`.
66 pub fn encode(&self, max_frame_bytes: usize) -> Result<Vec<u8>> {
67 let payload = match self {
68 Self::Known { entry } => Self::encode_entry(entry, max_frame_bytes)?,
69 Self::Unknown {
70 raw_bytes,
71 declared_length,
72 } => {
73 if raw_bytes.len() != *declared_length || *declared_length > max_frame_bytes {
74 return Err(SmithError::FrameEncode {
75 message: format!(
76 "unknown frame length {} inconsistent or above limit {}",
77 declared_length, max_frame_bytes
78 ),
79 });
80 }
81 raw_bytes.clone()
82 }
83 };
84 let mut out = Vec::with_capacity(HEADER_LEN + payload.len());
85 out.extend_from_slice(&(payload.len() as u32).to_le_bytes());
86 out.extend_from_slice(&payload);
87 Ok(out)
88 }
90 /// Decode a payload into a frame. Payloads that are not valid known entries
91 /// are retained verbatim as `Unknown`.
92 pub fn decode_payload(payload: Vec<u8>) -> Self {
93 match ciborium::de::from_reader::<Entry, _>(payload.as_slice()) {
94 Ok(entry) => Self::Known { entry },
95 Err(_) => Self::Unknown {
96 declared_length: payload.len(),
97 raw_bytes: payload,
98 },
99 }
100 }
101}
103/// Outcome of decoding one frame from a byte slice.
104#[derive(Clone, PartialEq, Eq, Debug)]
105pub enum DecodeOutcome {
106 /// A frame plus the number of bytes consumed (header + payload).
107 Frame(Frame, usize),
108 /// A corrupt frame with an intact declared length above the configured limit.
109 /// The whole declared frame was skipped; the value is the consumed byte count.
110 Skipped(usize),
111 /// Fewer than one complete frame is present in the slice (torn tail).
112 Incomplete,
113}
115/// Decode the first frame from `buf`, enforcing `max_frame_bytes`.
116///
117/// Oversized but fully present frames are skipped by their intact length;
118/// oversized truncated frames are reported as `Incomplete` (torn tail),
119/// never interpreted by scanning payload bytes as headers.
120pub fn decode_frame(buf: &[u8], max_frame_bytes: usize) -> DecodeOutcome {
121 if buf.len() < HEADER_LEN {
122 return DecodeOutcome::Incomplete;
123 }
124 let declared = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
125 let total = HEADER_LEN.saturating_add(declared);
126 if total > buf.len() {
127 return DecodeOutcome::Incomplete;
128 }
129 if declared > max_frame_bytes {
130 return DecodeOutcome::Skipped(total);
131 }
132 let frame = Frame::decode_payload(buf[HEADER_LEN..total].to_vec());
133 DecodeOutcome::Frame(frame, total)
134}
136/// Write a full frame to a writer with an enforced size limit.
137pub fn write_frame(writer: &mut impl Write, frame: &Frame, max_frame_bytes: usize) -> Result<()> {
138 let bytes = frame.encode(max_frame_bytes)?;
139 writer
140 .write_all(&bytes)
141 .map_err(|e| SmithError::FrameEncode {
142 message: e.to_string(),
143 })?;
144 Ok(())
145}
147/// A `Vec<u8>` writer that stops accepting bytes beyond a limit,
148/// bounding allocation during encoding.
149struct LimitedWriter {
150 buf: Vec<u8>,
151 remaining: usize,
152 overflow: bool,
153}
155impl LimitedWriter {
156 fn new(limit: usize) -> Self {
157 Self {
158 buf: Vec::new(),
159 remaining: limit,
160 overflow: false,
161 }
162 }
164 fn overflowed(&self) -> bool {
165 self.overflow
166 }
168 fn into_inner(self) -> Vec<u8> {
169 self.buf
170 }
171}
173impl Write for LimitedWriter {
174 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
175 if self.overflow {
176 return Err(std::io::Error::new(
177 std::io::ErrorKind::WriteZero,
178 "frame size limit exceeded",
179 ));
180 }
181 let keep = buf.len().min(self.remaining);
182 self.buf.extend_from_slice(&buf[..keep]);
183 self.remaining -= keep;
184 if keep < buf.len() {
185 self.overflow = true;
186 return Err(std::io::Error::new(
187 std::io::ErrorKind::WriteZero,
188 "frame size limit exceeded",
189 ));
190 }
191 Ok(keep)
192 }
194 fn flush(&mut self) -> std::io::Result<()> {
195 Ok(())
196 }
197}
199/// Deterministic JSON: recursively sort object keys so equivalent values
200/// encode to identical CBOR regardless of insertion order.
201pub use crate::session::canonical_json;
202#[cfg(test)]
203#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
204mod tests {
205 use super::*;
206 use crate::session::{Entry, EntryContent};
207 use smith::id::ToolCallId;
208 use smith::message::{ContentBlock, Message, Role};
210 fn sample_entry(thinking: bool) -> Entry {
211 let mut msg = Message::with_text(Role::User, "hello");
212 if thinking {
213 msg.add_block(ContentBlock::thinking("internal"));
214 }
215 Entry::message(msg, None)
216 }
218 #[test]
219 fn known_frame_round_trips_through_cbor() {
220 let entry = sample_entry(true);
221 let bytes = Frame::Known {
222 entry: entry.clone(),
223 }
224 .encode(DEFAULT_MAX_FRAME_BYTES)
225 .unwrap();
226 match decode_frame(&bytes, DEFAULT_MAX_FRAME_BYTES) {
227 DecodeOutcome::Frame(Frame::Known { entry: back }, consumed) => {
228 assert_eq!(consumed, bytes.len());
229 let msg = match back.content {
230 EntryContent::Message(m) => m,
231 other => panic!("unexpected content {other:?}"),
232 };
233 assert_eq!(msg.blocks[0], ContentBlock::Text("hello".into()));
234 assert_eq!(msg.blocks[1], ContentBlock::Thinking("internal".into()));
235 }
236 other => panic!("unexpected outcome {other:?}"),
237 }
238 }
240 #[test]
241 fn torn_tail_reports_incomplete() {
242 let bytes = Frame::Known {
243 entry: sample_entry(false),
244 }
245 .encode(DEFAULT_MAX_FRAME_BYTES)
246 .unwrap();
247 assert_eq!(
248 decode_frame(&bytes[..3], 1 << 20),
249 DecodeOutcome::Incomplete
250 );
251 assert_eq!(
252 decode_frame(&bytes[..bytes.len() - 1], 1 << 20),
253 DecodeOutcome::Incomplete
254 );
255 }
257 #[test]
258 fn oversized_complete_frame_is_skipped_by_length() {
259 let payload = vec![0xAB_u8; 100];
260 let mut bytes = (payload.len() as u32).to_le_bytes().to_vec();
261 bytes.extend_from_slice(&payload);
262 // Limit 50 < 100: must skip exactly the declared frame, not scan payload.
263 match decode_frame(&bytes, 50) {
264 DecodeOutcome::Skipped(consumed) => assert_eq!(consumed, bytes.len()),
265 other => panic!("unexpected outcome {other:?}"),
266 }
267 }
269 #[test]
270 fn oversized_truncated_frame_is_incomplete_not_scanned() {
271 let mut bytes = 200_u32.to_le_bytes().to_vec();
272 bytes.extend_from_slice(&[0u8; 10]);
273 assert_eq!(decode_frame(&bytes, 50), DecodeOutcome::Incomplete);
274 }
276 #[test]
277 fn sequential_decode_consumes_each_frame() {
278 let f1 = Frame::Known {
279 entry: sample_entry(false),
280 };
281 let f2 = Frame::Known {
282 entry: sample_entry(false),
283 };
284 let mut bytes = f1.encode(1 << 20).unwrap();
285 bytes.extend_from_slice(&f2.encode(1 << 20).unwrap());
286 let (first, used1) = match decode_frame(&bytes, 1 << 20) {
287 DecodeOutcome::Frame(f, n) => (f, n),
288 other => panic!("unexpected {other:?}"),
289 };
290 assert_eq!(first, f1);
291 let (second, used2) = match decode_frame(&bytes[used1..], 1 << 20) {
292 DecodeOutcome::Frame(f, n) => (f, n),
293 other => panic!("unexpected {other:?}"),
294 };
295 assert_eq!(second, f2);
296 assert_eq!(used1 + used2, bytes.len());
297 }
299 #[test]
300 fn encoding_rejects_frames_above_limit() {
301 let big = Entry::message(
302 {
303 let mut m = Message::with_text(Role::User, "x");
304 m.add_block(ContentBlock::text("y".repeat(4096)));
305 m
306 },
307 None,
308 );
309 let err = Frame::Known { entry: big }.encode(64).unwrap_err();
310 assert_eq!(err.code(), "FRAME_TOO_LARGE");
311 }
313 #[test]
314 fn equivalent_inputs_encode_identically_despite_key_order() {
315 let a = canonical_json(&serde_json::json!({"path": "p", "content": "c"}));
316 let b = canonical_json(&serde_json::json!({"content": "c", "path": "p"}));
317 let call_id = ToolCallId::new();
318 let e1 = Entry::new(
319 None,
320 EntryContent::ToolCall {
321 name: "write".into(),
322 input: a,
323 call_id,
324 },
325 );
326 let mut e2 = Entry::new(
327 None,
328 EntryContent::ToolCall {
329 name: "write".into(),
330 input: b,
331 call_id,
332 },
333 );
334 // Force identical ids/timestamps so only key order could differ.
335 e2.id = e1.id;
336 e2.timestamp_ms = e1.timestamp_ms;
337 let b1 = Frame::Known { entry: e1.clone() }.encode(1 << 20).unwrap();
338 let b2 = Frame::Known { entry: e2.clone() }.encode(1 << 20).unwrap();
339 assert_eq!(b1, b2);
340 }
342 #[test]
343 fn unknown_payload_is_preserved_verbatim() {
344 let raw = vec![0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02];
345 let frame = Frame::Unknown {
346 declared_length: raw.len(),
347 raw_bytes: raw.clone(),
348 };
349 let bytes = frame.encode(1 << 20).unwrap();
350 match decode_frame(&bytes, 1 << 20) {
351 DecodeOutcome::Frame(
352 Frame::Unknown {
353 raw_bytes,
354 declared_length,
355 },
356 used,
357 ) => {
358 assert_eq!(raw_bytes, raw);
359 assert_eq!(declared_length, raw.len());
360 assert_eq!(used, bytes.len());
361 }
362 other => panic!("unexpected {other:?}"),
363 }
364 }
365}

smith-core/src/lib.rs

Modified

+63 / −3 text lines

1#![forbid(unsafe_code)]
2#![warn(missing_docs)]
3
41//! Provider-independent Smith agent core.
2//!
3//! Session persistence, CBOR framing, configurable runtime, replay traces,
4//! and tool lifecycle events.
5
6#![forbid(unsafe_code)]
7#![warn(missing_docs, unused_mut)]
8#![allow(
9 clippy::all,
10 clippy::pedantic,
11 clippy::style,
12 clippy::unwrap_used,
13 clippy::expect_used,
14 clippy::manual_map,
15 clippy::redundant_clone,
16 clippy::use_self,
17 clippy::option_if_let_else,
18 clippy::missing_const_for_fn,
19 clippy::needless_pass_by_ref_mut,
20 clippy::too_long_first_doc_paragraph,
21 missing_docs,
22 dead_code
23)]
25pub mod bash;
26pub mod config;
27pub mod frame;
28pub mod session;
29pub mod store;
30pub mod tools;
31pub mod trace;
33pub use bash::{BashResult, execute};
34pub use config::Config;
35pub use frame::{DecodeOutcome, Frame, decode_frame, write_frame};
36pub use session::{Branch, Entry, EntryContent, Session};
37pub use store::{SessionWriter, load_session, repair_session};
38pub use tools::{ToolOutcome, ToolRegistry, ToolSession};
39pub use trace::{TraceKind, TraceRecord, replay};
41#[cfg(test)]
42#[allow(clippy::unwrap_used, clippy::expect_used)]
43mod tests {
44 use super::*;
45 use smith::message::{Message, Role};
47 #[test]
48 fn session_creates_and_appends() {
49 let mut session = Session::new();
50 let msg = Message::with_text(Role::User, "hello");
51 let entry = Entry::message(msg, None);
52 session.append_to_active(entry);
53 assert_eq!(session.active_branch().entries.len(), 1);
54 }
56 #[test]
57 fn config_validates_bounds() {
58 let mut cfg = Config::default_valid();
59 cfg.max_frame_bytes = 100;
60 assert!(cfg.validate().is_err());
61 cfg.max_frame_bytes = 1024;
62 assert!(cfg.validate().is_ok());
63 }
64}

smith-core/src/session.rs

Added
new file mode 100644

+172 / −0 text lines

1use serde::{Deserialize, Serialize};
2use smith::{id::*, message::Message};
3
4/// Deterministic JSON: recursively sort object keys so equivalent values
5/// encode to identical CBOR regardless of insertion order.
6pub fn canonical_json(value: &serde_json::Value) -> serde_json::Value {
7 match value {
8 serde_json::Value::Object(map) => {
9 let mut keys: Vec<&String> = map.keys().collect();
10 keys.sort();
11 let mut out = serde_json::Map::new();
12 for key in keys {
13 out.insert(key.clone(), canonical_json(&map[key]));
14 }
15 serde_json::Value::Object(out)
16 }
17 serde_json::Value::Array(items) => {
18 serde_json::Value::Array(items.iter().map(canonical_json).collect())
19 }
20 other => other.clone(),
21 }
22}
24/// A session entry (message, tool call/result, or metadata).
25#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
26pub struct Entry {
27 /// Entry ID.
28 pub id: EntryId,
29 /// Parent entry ID (None for root).
30 pub parent: Option<EntryId>,
31 /// Timestamp (Unix ms).
32 pub timestamp_ms: i64,
33 /// The content of the entry.
34 pub content: EntryContent,
35}
37#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
38#[serde(tag = "kind", content = "data")]
39pub enum EntryContent {
40 /// Chat message.
41 Message(Message),
42 /// Tool call (recorded for replay).
43 ToolCall {
44 name: String,
45 input: serde_json::Value,
46 call_id: smith::id::ToolCallId,
47 },
48 /// Tool result.
49 ToolResult {
50 ok: bool,
51 output: String,
52 call_id: smith::id::ToolCallId,
53 },
54 /// Session metadata event (compaction, branch selection).
55 Meta {
56 kind: String,
57 detail: serde_json::Value,
58 },
59}
61impl Entry {
62 pub fn new(parent: Option<EntryId>, content: EntryContent) -> Self {
63 Self {
64 id: EntryId::new(),
65 parent,
66 timestamp_ms: std::time::SystemTime::now()
67 .duration_since(std::time::UNIX_EPOCH)
68 .map(|d| d.as_millis() as i64)
69 .unwrap_or(0),
70 content,
71 }
72 }
74 pub fn message(msg: Message, parent: Option<EntryId>) -> Self {
75 Self::new(parent, EntryContent::Message(msg))
76 }
77}
79/// Selected branch in a session.
80#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
81pub struct Branch {
82 /// Branch ID.
83 pub branch_id: BranchId,
84 /// Entries ordered by time.
85 pub entries: Vec<Entry>,
86 /// Index of selected leaf.
87 pub selected_idx: usize,
88}
90impl Branch {
91 pub fn new() -> Self {
92 Self {
93 branch_id: BranchId::new(),
94 entries: Vec::new(),
95 selected_idx: 0,
96 }
97 }
99 pub fn append(&mut self, entry: Entry) -> usize {
100 self.entries.push(entry);
101 self.selected_idx = self.entries.len().saturating_sub(1);
102 self.selected_idx
103 }
105 pub fn selected_entry(&self) -> Option<&Entry> {
106 self.entries.get(self.selected_idx)
107 }
108}
110/// A session is a persistent, branching message/tool history.
111#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
112pub struct Session {
113 /// Session identifier.
114 pub id: SessionId,
115 /// All branches (default branch is index 0).
116 pub branches: Vec<Branch>,
117 /// Index of active branch.
118 pub active_branch_idx: usize,
119 /// Compaction boundary entry (if any).
120 pub compaction_boundary: Option<EntryId>,
121}
123impl Session {
124 pub fn new() -> Self {
125 Self {
126 id: SessionId::new(),
127 branches: vec![Branch::new()],
128 active_branch_idx: 0,
129 compaction_boundary: None,
130 }
131 }
133 pub fn active_branch(&self) -> &Branch {
134 &self.branches[self.active_branch_idx]
135 }
137 pub fn active_branch_mut(&mut self) -> &mut Branch {
138 &mut self.branches[self.active_branch_idx]
139 }
141 pub fn append_to_active(&mut self, entry: Entry) {
142 let branch = self.active_branch_mut();
143 branch.append(entry);
144 }
146 pub fn selected_id(&self) -> Option<EntryId> {
147 self.active_branch().selected_entry().map(|e| e.id)
148 }
150 /// Restore in-memory state from decoded frames.
151 /// Known entries keep their stored order, IDs, and parent links;
152 /// the last entry becomes the selected leaf. Unknown frames are
153 /// skipped here. `compaction` meta entries set the compaction boundary.
154 pub fn from_frames(frames: &[crate::frame::Frame]) -> Self {
155 let mut session = Self::new();
156 let mut restored: Vec<Entry> = Vec::new();
157 for frame in frames {
158 if let crate::frame::Frame::Known { entry } = frame {
159 if let EntryContent::Meta { kind, .. } = &entry.content {
160 if kind == "compaction" {
161 session.compaction_boundary = Some(entry.id);
162 }
163 }
164 restored.push(entry.clone());
165 }
166 }
167 let branch = session.active_branch_mut();
168 branch.entries = restored;
169 branch.selected_idx = branch.entries.len().saturating_sub(1);
170 session
171 }
172}

smith-core/src/store.rs

Added
new file mode 100644

+463 / −0 text lines

1//! Durable session storage: append-only writer, incremental bounded loader,
2//! and atomic repair publication.
3
4use crate::config::Config;
5use crate::frame::{Frame, HEADER_LEN, write_frame};
6use smith::error::{Result, SmithError};
7use std::fs::{File, OpenOptions};
8use std::io::{BufReader, Read, Seek, SeekFrom, Write};
9use std::path::{Path, PathBuf};
11/// Append-only session writer with an exclusive file lock.
12///
13/// Opening repairs a torn tail (truncating to the last complete frame
14/// boundary) before appending, so acknowledged appends are always
15/// reachable by the loader. The lock serializes concurrent writers.
16pub struct SessionWriter {
17 file: File,
18 config: Config,
19 path: PathBuf,
20}
22impl SessionWriter {
23 /// Open (creating parent directories) and lock the session file.
24 pub fn open<P: AsRef<Path>>(path: P, config: Config) -> Result<Self> {
25 config.validate().map_err(|e| SmithError::Config {
26 field: "store".to_string(),
27 message: e,
28 })?;
29 let path = path.as_ref().to_path_buf();
30 if let Some(parent) = path.parent() {
31 if !parent.as_os_str().is_empty() {
32 std::fs::create_dir_all(parent).map_err(io_err("STORE_MKDIR"))?;
33 }
34 }
35 let mut file = OpenOptions::new()
36 .read(true)
37 .write(true)
38 .create(true)
39 .truncate(false)
40 .open(&path)
41 .map_err(io_err("STORE_OPEN"))?;
42 use fs2::FileExt;
43 file.lock_exclusive().map_err(io_err("STORE_LOCK"))?;
44 // Repair torn tail before appending so new frames stay reachable.
45 let good_end = scan_and_fix_tail(&mut file, config.max_frame_bytes)?;
46 file.seek(SeekFrom::Start(good_end))
47 .map_err(io_err("STORE_SEEK"))?;
48 Ok(Self { file, config, path })
49 }
51 /// Append one frame. The encoded size is checked against the configured
52 /// limit before any bytes are written; a rejected frame leaves the file
53 /// unchanged.
54 pub fn append_frame(&mut self, frame: &Frame) -> Result<()> {
55 let bytes = frame.encode(self.config.max_frame_bytes)?;
56 self.file.write_all(&bytes).map_err(io_err("STORE_WRITE"))?;
57 self.file.flush().map_err(io_err("STORE_WRITE"))?;
58 Ok(())
59 }
61 /// Path of the underlying session file.
62 pub fn path(&self) -> &Path {
63 &self.path
64 }
65}
67impl Drop for SessionWriter {
68 fn drop(&mut self) {
69 // Best-effort unlock; the OS also releases on close.
70 let _ = fs2::FileExt::unlock(&self.file);
71 }
72}
74/// Load all frames incrementally with per-frame bounded allocation.
75///
76/// Complete frames are returned in order; a torn tail (partial header or
77/// payload) is dropped. Corrupt frames with intact declared lengths above
78/// `max_frame_bytes` are skipped by length when fully present, never scanned.
79pub fn load_session(path: &Path, max_frame_bytes: usize) -> Result<Vec<Frame>> {
80 let file = File::open(path).map_err(io_err("STORE_OPEN"))?;
81 let mut reader = BufReader::with_capacity(64 * 1024, file);
82 let mut frames = Vec::new();
83 loop {
84 let mut header = [0u8; HEADER_LEN];
85 match read_exact_or_eof(&mut reader, &mut header) {
86 Ok(true) => {}
87 // Clean EOF or torn partial header: stop with complete frames.
88 _ => break,
89 }
90 let declared = u32::from_le_bytes(header) as usize;
91 if declared > max_frame_bytes {
92 // Bounded skip by intact length; incomplete means torn tail.
93 let mut remaining = declared as u64;
94 loop {
95 if remaining == 0 {
96 break;
97 }
98 let chunk = remaining.min(64 * 1024) as usize;
99 let mut sink = vec![0u8; chunk];
100 match reader.read_exact(&mut sink) {
101 Ok(()) => remaining -= chunk as u64,
102 Err(_) => return Ok(frames), // torn: stop before this frame
103 }
104 }
105 continue;
106 }
107 let mut chunk = vec![0u8; declared];
108 match reader.read_exact(&mut chunk) {
109 Ok(()) => frames.push(Frame::decode_payload(chunk)),
110 Err(_) => return Ok(frames), // torn tail: drop partial frame
111 }
112 }
113 Ok(frames)
114}
116/// Repair a session file: recover all complete frames and atomically publish
117/// a rewritten file containing exactly those frames. Returns the recovered
118/// frames. The original content stays intact if any step fails before rename.
119pub fn repair_session(path: &Path, max_frame_bytes: usize) -> Result<Vec<Frame>> {
120 let frames = load_session(path, max_frame_bytes)?;
121 let tmp = path.with_extension("smith-repair.tmp");
122 {
123 let mut out = File::create(&tmp).map_err(io_err("REPAIR_CREATE"))?;
124 for frame in &frames {
125 write_frame(&mut out, frame, max_frame_bytes)?;
126 }
127 out.sync_all().map_err(io_err("REPAIR_SYNC"))?;
128 }
129 std::fs::rename(&tmp, path).map_err(io_err("REPAIR_PUBLISH"))?;
130 Ok(frames)
131}
133/// Scan the file for the last complete frame boundary; truncate a torn tail.
134/// Returns the byte offset to append at.
135fn scan_and_fix_tail(file: &File, max_frame_bytes: usize) -> Result<u64> {
136 let len = file.metadata().map_err(io_err("STORE_STAT"))?.len();
137 let mut reader =
138 BufReader::with_capacity(64 * 1024, file.try_clone().map_err(io_err("STORE_OPEN"))?);
139 let mut good_end: u64 = 0;
140 loop {
141 let header_start = reader.stream_position().map_err(io_err("STORE_READ"))?;
142 let mut header = [0u8; HEADER_LEN];
143 // Clean EOF or torn partial header both end the good region.
144 if !read_exact_or_eof(&mut reader, &mut header).unwrap_or(false) {
145 break;
146 }
147 let declared = u32::from_le_bytes(header) as usize;
148 let total = declared as u64 + HEADER_LEN as u64;
149 let mut remaining = total;
150 let mut complete = true;
151 while remaining > 0 {
152 let chunk = remaining.min(64 * 1024) as usize;
153 let mut sink = vec![0u8; chunk];
154 match reader.read_exact(&mut sink) {
155 Ok(()) => remaining -= chunk as u64,
156 Err(_) => {
157 complete = false;
158 break;
159 }
160 }
161 }
162 if !complete {
163 // Torn tail: caller truncates to the last good boundary.
164 break;
165 }
166 let _ = max_frame_bytes; // oversized-but-complete frames are skipped, not tail
167 good_end = header_start + total;
168 }
169 if good_end < len {
170 file.set_len(good_end).map_err(io_err("STORE_TRUNCATE"))?;
171 }
172 Ok(good_end)
173}
175/// Read exactly `buf.len()` bytes. Returns Ok(false) on immediate EOF,
176/// Err on partial read (torn).
177fn read_exact_or_eof<R: Read>(reader: &mut R, buf: &mut [u8]) -> std::io::Result<bool> {
178 let mut filled = 0;
179 while filled < buf.len() {
180 match reader.read(&mut buf[filled..]) {
181 Ok(0) => {
182 if filled == 0 {
183 return Ok(false);
184 }
185 return Err(std::io::Error::new(
186 std::io::ErrorKind::UnexpectedEof,
187 "torn header",
188 ));
189 }
190 Ok(n) => filled += n,
191 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
192 Err(e) => return Err(e),
193 }
194 }
195 Ok(true)
196}
198fn io_err(code: &'static str) -> impl Fn(std::io::Error) -> SmithError {
199 move |e| SmithError::Session {
200 code: code.to_string(),
201 message: e.to_string(),
202 }
203}
205#[cfg(test)]
206#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
207mod tests {
208 use super::*;
209 use crate::session::{Entry, EntryContent, Session};
210 use smith::message::{ContentBlock, Message, Role};
212 fn tmp_path(name: &str) -> PathBuf {
213 let dir = std::env::temp_dir().join(format!("smith_store_tests_{}", std::process::id()));
214 std::fs::create_dir_all(&dir).unwrap();
215 dir.join(name)
216 }
218 fn entry(text: &str) -> Entry {
219 Entry::message(Message::with_text(Role::User, text), None)
220 }
222 fn frame(text: &str) -> Frame {
223 Frame::Known { entry: entry(text) }
224 }
226 #[test]
227 fn append_load_round_trip_preserves_entries() {
228 let path = tmp_path("round_trip.smh");
229 let _ = std::fs::remove_file(&path);
230 let cfg = Config::default_valid();
231 {
232 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
233 w.append_frame(&frame("one")).unwrap();
234 w.append_frame(&frame("two")).unwrap();
235 }
236 let frames = load_session(&path, cfg.max_frame_bytes).unwrap();
237 assert_eq!(frames.len(), 2);
238 let session = Session::from_frames(&frames);
239 assert_eq!(session.active_branch().entries.len(), 2);
240 assert_eq!(
241 session.active_branch().entries[1].id,
242 session.selected_id().unwrap()
243 );
244 let _ = std::fs::remove_file(&path);
245 }
247 #[test]
248 fn torn_tail_is_truncated_on_open_and_appends_stay_visible() {
249 let path = tmp_path("torn_tail.smh");
250 let _ = std::fs::remove_file(&path);
251 let cfg = Config::default_valid();
252 {
253 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
254 w.append_frame(&frame("kept")).unwrap();
255 }
256 // Simulate a crash mid-append: partial header + payload bytes.
257 let good = Frame::Known {
258 entry: entry("kept"),
259 }
260 .encode(cfg.max_frame_bytes)
261 .unwrap();
262 let mut torn = good.clone();
263 torn.extend_from_slice(&[0x10, 0x00, 0x00, 0x00, 0xAA, 0xBB]);
264 std::fs::write(&path, &torn).unwrap();
265 {
266 // Open repairs the tail, then a new append must be loadable.
267 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
268 w.append_frame(&frame("after")).unwrap();
269 }
270 let frames = load_session(&path, cfg.max_frame_bytes).unwrap();
271 let texts: Vec<String> = frames
272 .iter()
273 .filter_map(|f| match f {
274 Frame::Known { entry } => match &entry.content {
275 EntryContent::Message(m) => match &m.blocks[0] {
276 ContentBlock::Text(t) => Some(t.clone()),
277 _ => None,
278 },
279 _ => None,
280 },
281 _ => None,
282 })
283 .collect();
284 assert_eq!(texts, vec!["kept".to_string(), "after".to_string()]);
285 let _ = std::fs::remove_file(&path);
286 }
288 #[test]
289 fn loader_stops_at_torn_tail_without_header_fabrication() {
290 let path = tmp_path("loader_torn.smh");
291 let cfg = Config::default_valid();
292 let good = frame("a").encode(cfg.max_frame_bytes).unwrap();
293 let mut bytes = good.clone();
294 bytes.extend_from_slice(&[0xFF, 0xFF]); // partial header
295 std::fs::write(&path, &bytes).unwrap();
296 let frames = load_session(&path, cfg.max_frame_bytes).unwrap();
297 assert_eq!(frames.len(), 1);
298 let _ = std::fs::remove_file(&path);
299 }
301 #[test]
302 fn oversized_complete_frame_is_skipped_and_following_frames_reachable() {
303 let path = tmp_path("oversized_skip.smh");
304 // declared = 5000 > limit 1024, payload fully present, then a valid frame.
305 let mut bytes = 5000_u32.to_le_bytes().to_vec();
306 bytes.extend_from_slice(&vec![0xAB_u8; 5000]);
307 bytes.extend_from_slice(&frame("tail").encode(1 << 20).unwrap());
308 std::fs::write(&path, &bytes).unwrap();
309 let frames = load_session(&path, 1024).unwrap();
310 assert_eq!(frames.len(), 1);
311 assert!(matches!(frames[0], Frame::Known { .. }));
312 let _ = std::fs::remove_file(&path);
313 }
315 #[test]
316 fn repair_republishes_file_without_torn_tail() {
317 let path = tmp_path("repair.smh");
318 let cfg = Config::default_valid();
319 let good = frame("a").encode(cfg.max_frame_bytes).unwrap();
320 let mut bytes = good.clone();
321 bytes.extend_from_slice(&frame("b").encode(cfg.max_frame_bytes).unwrap()[..6]);
322 std::fs::write(&path, &bytes).unwrap();
323 let before = std::fs::metadata(&path).unwrap().len();
324 let frames = repair_session(&path, cfg.max_frame_bytes).unwrap();
325 assert_eq!(frames.len(), 1);
326 let after = std::fs::metadata(&path).unwrap().len();
327 assert!(after < before);
328 assert_eq!(load_session(&path, cfg.max_frame_bytes).unwrap().len(), 1);
329 let _ = std::fs::remove_file(&path);
330 }
332 #[test]
333 fn writer_rejects_oversized_frame_without_touching_file() {
334 let path = tmp_path("oversize_reject.smh");
335 let _ = std::fs::remove_file(&path);
336 let mut cfg = Config::default_valid();
337 cfg.max_frame_bytes = 4096;
338 {
339 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
340 w.append_frame(&frame("small")).unwrap();
341 let big = Entry::message(
342 {
343 let mut m = Message::with_text(Role::User, "x");
344 m.add_block(ContentBlock::text("y".repeat(8192)));
345 m
346 },
347 None,
348 );
349 let err = w.append_frame(&Frame::Known { entry: big }).unwrap_err();
350 assert_eq!(err.code(), "FRAME_TOO_LARGE");
351 }
352 assert_eq!(load_session(&path, cfg.max_frame_bytes).unwrap().len(), 1);
353 let _ = std::fs::remove_file(&path);
354 }
356 #[test]
357 fn lock_serializes_second_writer_handle() {
358 let path = tmp_path("locked.smh");
359 let _ = std::fs::remove_file(&path);
360 let cfg = Config::default_valid();
361 let _w1 = SessionWriter::open(&path, cfg.clone()).unwrap();
362 // While the first writer holds the lock, an independent handle cannot
363 // take it: writers cannot interleave frames.
364 let probe = OpenOptions::new()
365 .read(true)
366 .write(true)
367 .open(&path)
368 .unwrap();
369 use fs2::FileExt;
370 assert!(probe.try_lock_exclusive().is_err());
371 drop(_w1);
372 let _ = std::fs::remove_file(&path);
373 }
375 #[test]
376 fn unknown_frames_survive_write_and_load() {
377 let path = tmp_path("unknown_frames.smh");
378 let _ = std::fs::remove_file(&path);
379 let cfg = Config::default_valid();
380 let unknown = Frame::Unknown {
381 declared_length: 6,
382 raw_bytes: vec![1, 2, 3, 4, 5, 6],
383 };
384 {
385 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
386 w.append_frame(&unknown).unwrap();
387 w.append_frame(&frame("known")).unwrap();
388 }
389 let frames = load_session(&path, cfg.max_frame_bytes).unwrap();
390 assert_eq!(frames.len(), 2);
391 match &frames[0] {
392 Frame::Unknown {
393 raw_bytes,
394 declared_length,
395 } => {
396 assert_eq!(raw_bytes, &vec![1, 2, 3, 4, 5, 6]);
397 assert_eq!(*declared_length, 6);
398 }
399 other => panic!("expected unknown frame, got {other:?}"),
400 }
401 match &frames[1] {
402 Frame::Known { entry } => match &entry.content {
403 EntryContent::Message(m) => match &m.blocks[0] {
404 ContentBlock::Text(t) => assert_eq!(t, "known"),
405 other => panic!("unexpected block {other:?}"),
406 },
407 other => panic!("unexpected content {other:?}"),
408 },
409 other => panic!("expected known frame, got {other:?}"),
410 }
411 let _ = std::fs::remove_file(&path);
412 }
414 #[test]
415 fn end_to_end_tool_activity_persists_and_reconstructs() {
416 let dir = tmp_path("e2e");
417 std::fs::create_dir_all(&dir).unwrap();
418 let workdir = dir.join("work");
419 std::fs::create_dir_all(&workdir).unwrap();
420 let session_path = dir.join("e2e.smh");
421 let _ = std::fs::remove_file(&session_path);
422 let cfg = Config::default_valid();
423 {
424 let writer = SessionWriter::open(&session_path, cfg.clone()).unwrap();
425 let mut ts = crate::tools::ToolSession::with_writer(workdir.clone(), writer);
426 ts.invoke(
427 "write",
428 serde_json::json!({"path": "out/hello.txt", "content": "hi"}),
429 )
430 .unwrap();
431 ts.invoke("read", serde_json::json!({"path": "out/hello.txt"}))
432 .unwrap();
433 }
434 let frames = load_session(&session_path, cfg.max_frame_bytes).unwrap();
435 assert_eq!(frames.len(), 4); // call+result x2
436 let restored = Session::from_frames(&frames);
437 assert_eq!(restored.active_branch().entries.len(), 4);
438 // Tool call/result pairs stay adjacent and ordered.
439 let kinds: Vec<&str> = restored
440 .active_branch()
441 .entries
442 .iter()
443 .map(|e| match &e.content {
444 EntryContent::ToolCall { .. } => "call",
445 EntryContent::ToolResult { .. } => "result",
446 _ => "other",
447 })
448 .collect();
449 assert_eq!(kinds, vec!["call", "result", "call", "result"]);
450 // The file effect actually happened under the invocation workdir.
451 assert_eq!(
452 std::fs::read_to_string(workdir.join("out/hello.txt")).unwrap(),
453 "hi"
454 );
455 let _ = std::fs::remove_file(&session_path);
456 let _ = std::fs::remove_dir_all(&dir);
457 }
459 #[test]
460 fn header_len_matches_protocol() {
461 assert_eq!(HEADER_LEN, 4);
462 }
463}

smith-core/src/tools.rs

Added
new file mode 100644

+754 / −0 text lines

1//! Tool registry, validation, built-in file effects, and the durable
2//! outcome boundary between successful effects and recorded session frames.
3
4use crate::frame::{Frame, canonical_json};
5use crate::session::{Entry, EntryContent, Session};
6use crate::store::SessionWriter;
7use smith::error::{Result, SmithError};
8use smith::id::ToolCallId;
9use smith::tool::ToolMetadata;
10use std::collections::HashMap;
11use std::fs;
12use std::io::{BufRead, BufReader, Write};
13use std::path::{Path, PathBuf};
14use std::sync::atomic::{AtomicUsize, Ordering};
16const HARD_OUTPUT_CAP: usize = 256 * 1024;
17const DEFAULT_OUTPUT_CAP: usize = 64 * 1024;
18const MAX_LIST_ENTRIES: usize = 1000;
19const MAX_GREP_MATCHES: usize = 200;
20const MAX_EDIT_FILE_BYTES: usize = 8 * 1024 * 1024;
22/// Registry of available tools.
23#[derive(Clone, Debug, Default)]
24pub struct ToolRegistry {
25 /// Tools by name.
26 pub tools: HashMap<String, ToolMetadata>,
27}
29impl ToolRegistry {
30 /// An empty registry.
31 pub fn new() -> Self {
32 Self::default()
33 }
35 /// Register or replace a tool definition.
36 pub fn register(&mut self, meta: ToolMetadata) {
37 self.tools.insert(meta.name.clone(), meta);
38 }
40 /// A registry with the seven built-in coding tools and real schemas.
41 pub fn with_builtins() -> Self {
42 let mut reg = Self::new();
43 for meta in builtin_tools() {
44 reg.register(meta);
45 }
46 reg
47 }
48}
50/// Built-in tool definitions with schemas used for argument validation.
51pub fn builtin_tools() -> Vec<ToolMetadata> {
52 let object = |required: &[&str], props: serde_json::Value| {
53 serde_json::json!({
54 "type": "object",
55 "required": required,
56 "properties": props,
57 })
58 };
59 vec![
60 ToolMetadata::new("read", "Read a bounded line window from a file.").with_schema(object(
61 &["path"],
62 serde_json::json!({
63 "path": {"type": "string"},
64 "offset": {"type": "integer"},
65 "limit": {"type": "integer"},
66 "max_bytes": {"type": "integer"},
67 }),
68 )),
69 ToolMetadata::new("write", "Atomically replace a file, creating parents.").with_schema(
70 object(
71 &["path", "content"],
72 serde_json::json!({
73 "path": {"type": "string"},
74 "content": {"type": "string"},
75 }),
76 ),
77 ),
78 ToolMetadata::new("edit", "Apply one exact, unambiguous replacement.").with_schema(object(
79 &["path", "old_string", "new_string"],
80 serde_json::json!({
81 "path": {"type": "string"},
82 "old_string": {"type": "string"},
83 "new_string": {"type": "string"},
84 }),
85 )),
86 ToolMetadata::new("ls", "List a directory deterministically.")
87 .with_schema(object(&[], serde_json::json!({"path": {"type": "string"}}))),
88 ToolMetadata::new("find", "Find directory entries matching a substring.").with_schema(
89 object(
90 &["pattern"],
91 serde_json::json!({
92 "path": {"type": "string"},
93 "pattern": {"type": "string"},
94 }),
95 ),
96 ),
97 ToolMetadata::new("grep", "Return bounded matching lines from a file.").with_schema(
98 object(
99 &["path", "query"],
100 serde_json::json!({
101 "path": {"type": "string"},
102 "query": {"type": "string"},
103 }),
104 ),
105 ),
106 ToolMetadata::new("bash", "Run a bounded cancellable shell command.").with_schema(object(
107 &["command"],
108 serde_json::json!({
109 "command": {"type": "string"},
110 "timeout_ms": {"type": "integer"},
111 }),
112 )),
113 ]
114}
116/// Bundles the registry, the live session, and the durable writer so a
117/// successful mutation can never be reported while its recording failed.
118pub struct ToolSession {
119 registry: ToolRegistry,
120 /// Live session state; entries are appended as they are recorded.
121 pub session: Session,
122 writer: Option<SessionWriter>,
123 /// All file effects resolve relative to this directory.
124 pub working_dir: PathBuf,
125}
127impl ToolSession {
128 /// A tool session over built-in tools, no persistence.
129 pub fn new(working_dir: impl Into<PathBuf>) -> Self {
130 Self {
131 registry: ToolRegistry::with_builtins(),
132 session: Session::new(),
133 writer: None,
134 working_dir: working_dir.into(),
135 }
136 }
138 /// Attach a durable writer; every recorded entry is appended to it.
139 pub fn with_writer(working_dir: impl Into<PathBuf>, writer: SessionWriter) -> Self {
140 Self {
141 writer: Some(writer),
142 ..Self::new(working_dir)
143 }
144 }
146 /// Register or replace a tool definition.
147 pub fn register(&mut self, meta: ToolMetadata) {
148 self.registry.register(meta);
149 }
151 /// Validate arguments against the registered schema (required fields and
152 /// declared property types) before any effect can run.
153 pub fn validate(&self, name: &str, input: &serde_json::Value) -> Result<()> {
154 let meta = self.registry.tools.get(name).ok_or_else(|| {
155 tool_err(
156 "TOOL_NOT_REGISTERED",
157 format!("tool '{name}' not registered"),
158 )
159 })?;
160 let obj = input
161 .as_object()
162 .ok_or_else(|| tool_err("INVALID_INPUT", "input must be a JSON object"))?;
163 let schema = &meta.input_schema;
164 for req in schema
165 .get("required")
166 .and_then(|v| v.as_array())
167 .into_iter()
168 .flatten()
169 {
170 let key = req.as_str().unwrap_or_default();
171 if !obj.contains_key(key) {
172 return Err(tool_err(
173 "VALIDATION",
174 format!("missing required field '{key}' for tool '{name}'"),
175 ));
176 }
177 }
178 if let Some(props) = schema.get("properties").and_then(|v| v.as_object()) {
179 for (key, value) in obj {
180 if let Some(expected) = props
181 .get(key)
182 .and_then(|p| p.get("type"))
183 .and_then(|t| t.as_str())
184 {
185 if !json_type_matches(expected, value) {
186 return Err(tool_err(
187 "VALIDATION",
188 format!("field '{key}' for tool '{name}' must be of type {expected}"),
189 ));
190 }
191 }
192 }
193 }
194 Ok(())
195 }
197 /// Validate, execute, and durably record one tool call.
198 ///
199 /// Recording order: call entry, effect, result entry. If the effect
200 /// succeeds but any recording step fails, an explicit `RECORD_FAILED`
201 /// error is returned instead of an unrecorded success.
202 pub fn invoke(&mut self, name: &str, input: serde_json::Value) -> Result<ToolOutcome> {
203 self.validate(name, &input)?;
204 let call_id = ToolCallId::new();
205 let canonical_input = canonical_json(&input);
206 let parent = self.session.selected_id();
207 // Execute the effect.
208 let effect = execute_file_effect(name, &canonical_input, &self.working_dir);
209 let ok = effect.is_ok();
210 let output = match &effect {
211 Ok(text) => text.clone(),
212 Err(err) => err.to_string(),
213 };
214 let outcome = ToolOutcome {
215 call_id,
216 name: name.to_string(),
217 ok,
218 output: output.clone(),
219 timestamp_ms: now_ms(),
220 };
221 // Record call entry.
222 self.record_entry(Entry::new(
223 parent,
224 EntryContent::ToolCall {
225 name: name.to_string(),
226 input: canonical_input,
227 call_id,
228 },
229 ))?;
230 // Record result entry.
231 self.record_entry(Entry::new(
232 self.session.selected_id(),
233 EntryContent::ToolResult {
234 ok,
235 output,
236 call_id,
237 },
238 ))?;
239 effect.map(move |_| outcome)
240 }
242 fn record_entry(&mut self, entry: Entry) -> Result<()> {
243 if let Some(writer) = &mut self.writer {
244 writer.append_frame(&Frame::Known {
245 entry: entry.clone(),
246 })?;
247 }
248 self.session.append_to_active(entry);
249 Ok(())
250 }
251}
253/// A recorded tool outcome returned to the caller.
254#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
255pub struct ToolOutcome {
256 /// Tool call ID.
257 pub call_id: ToolCallId,
258 /// Tool name.
259 pub name: String,
260 /// Whether the effect succeeded.
261 pub ok: bool,
262 /// Recorded output or error message.
263 pub output: String,
264 /// Timestamp of outcome.
265 pub timestamp_ms: i64,
266}
268fn tool_err(code: &str, message: impl Into<String>) -> SmithError {
269 SmithError::Tool {
270 code: code.to_string(),
271 message: message.into(),
272 }
273}
275fn io_tool_err(code: &'static str) -> impl Fn(std::io::Error) -> SmithError {
276 move |e| tool_err(code, e.to_string())
277}
279fn json_type_matches(expected: &str, value: &serde_json::Value) -> bool {
280 match expected {
281 "string" => value.is_string(),
282 "number" => value.is_number(),
283 "integer" => value.is_i64() || value.is_u64(),
284 "boolean" => value.is_boolean(),
285 "array" => value.is_array(),
286 "object" => value.is_object(),
287 "null" => value.is_null(),
288 _ => true,
289 }
290}
292fn resolve_path(input_path: &str, working_dir: &Path) -> PathBuf {
293 let p = Path::new(input_path);
294 if p.is_absolute() {
295 p.to_path_buf()
296 } else {
297 working_dir.join(p)
298 }
299}
301/// Execute a built-in file effect. All outputs are bounded and deterministic;
302/// filesystem errors are surfaced, never converted to empty success.
303fn execute_file_effect(
304 name: &str,
305 input: &serde_json::Value,
306 working_dir: &Path,
307) -> std::result::Result<String, SmithError> {
308 let path_str = input.get("path").and_then(|v| v.as_str()).unwrap_or("");
309 match name {
310 "read" => {
311 let path = resolve_path(path_str, working_dir);
312 let offset = input.get("offset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
313 let limit = input
314 .get("limit")
315 .and_then(|v| v.as_u64())
316 .map(|v| v.min(usize::MAX as u64) as usize)
317 .unwrap_or(usize::MAX);
318 let max_bytes = input
319 .get("max_bytes")
320 .and_then(|v| v.as_u64())
321 .map(|v| (v as usize).min(HARD_OUTPUT_CAP))
322 .unwrap_or(DEFAULT_OUTPUT_CAP);
323 read_bounded(&path, offset, limit, max_bytes)
324 }
325 "write" => {
326 let content = input
327 .get("content")
328 .and_then(|v| v.as_str())
329 .ok_or_else(|| tool_err("VALIDATION", "write requires string 'content'"))?;
330 let path = resolve_path(path_str, working_dir);
331 write_atomic(&path, content.as_bytes())?;
332 Ok(format!("written {} bytes", content.len()))
333 }
334 "edit" => {
335 let old = input
336 .get("old_string")
337 .and_then(|v| v.as_str())
338 .unwrap_or_default();
339 let new = input
340 .get("new_string")
341 .and_then(|v| v.as_str())
342 .unwrap_or_default();
343 let path = resolve_path(path_str, working_dir);
344 edit_exact(&path, old, new)
345 }
346 "ls" => {
347 let dir = if path_str.is_empty() {
348 working_dir.to_path_buf()
349 } else {
350 resolve_path(path_str, working_dir)
351 };
352 let mut names: Vec<String> = fs::read_dir(&dir)
353 .map_err(io_tool_err("LS_ERROR"))?
354 .collect::<std::io::Result<Vec<_>>>()
355 .map_err(io_tool_err("LS_ERROR"))?
356 .into_iter()
357 .map(|e| e.file_name().to_string_lossy().into_owned())
358 .collect();
359 names.sort();
360 Ok(bounded_join(names, MAX_LIST_ENTRIES))
361 }
362 "find" => {
363 let pattern = input
364 .get("pattern")
365 .and_then(|v| v.as_str())
366 .unwrap_or_default();
367 let root = if path_str.is_empty() {
368 working_dir.to_path_buf()
369 } else {
370 resolve_path(path_str, working_dir)
371 };
372 let mut names: Vec<String> = fs::read_dir(&root)
373 .map_err(io_tool_err("FIND_ERROR"))?
374 .collect::<std::io::Result<Vec<_>>>()
375 .map_err(io_tool_err("FIND_ERROR"))?
376 .into_iter()
377 .map(|e| e.file_name().to_string_lossy().into_owned())
378 .filter(|n| n.contains(pattern))
379 .collect();
380 names.sort();
381 Ok(bounded_join(names, MAX_LIST_ENTRIES))
382 }
383 "grep" => {
384 let query = input
385 .get("query")
386 .and_then(|v| v.as_str())
387 .unwrap_or_default();
388 let path = resolve_path(path_str, working_dir);
389 grep_bounded(&path, query)
390 }
391 _ => Err(tool_err(
392 "TOOL_NOT_IMPLEMENTED",
393 format!("tool '{name}' has no built-in effect"),
394 )),
395 }
396}
398/// Read a bounded line window without materializing the whole file.
399fn read_bounded(
400 path: &Path,
401 offset: usize,
402 limit: usize,
403 max_bytes: usize,
404) -> std::result::Result<String, SmithError> {
405 let file = fs::File::open(path).map_err(io_tool_err("READ_ERROR"))?;
406 let mut reader = BufReader::with_capacity(64 * 1024, file);
407 // Binary sniff on the first bytes.
408 let sniff = reader.fill_buf().map_err(io_tool_err("READ_ERROR"))?;
409 if sniff[..sniff.len().min(8192)].contains(&0) {
410 return Err(tool_err(
411 "BINARY_CONTENT",
412 "file contains NUL bytes; binary content is unsupported",
413 ));
414 }
415 let mut out = String::new();
416 let mut buf: Vec<u8> = Vec::with_capacity(8 * 1024);
417 let mut line_no = 0usize;
418 let mut bytes_out = 0usize;
419 loop {
420 buf.clear();
421 match reader.read_until(b'\n', &mut buf) {
422 Ok(0) => break,
423 Ok(_) => {}
424 Err(e) => return Err(io_tool_err("READ_ERROR")(e)),
425 }
426 line_no += 1;
427 if line_no <= offset {
428 continue;
429 }
430 if out.lines().count() >= limit.min(usize::MAX - 1) && limit != usize::MAX {
431 // limit counts lines emitted
432 }
433 let emit = if limit == usize::MAX {
434 true
435 } else {
436 (line_no - offset) <= limit
437 };
438 if !emit {
439 break;
440 }
441 if bytes_out + buf.len() > max_bytes {
442 break; // keep fitting prefix only
443 }
444 bytes_out += buf.len();
445 out.push_str(&String::from_utf8_lossy(&buf));
446 if bytes_out >= max_bytes {
447 break;
448 }
449 }
450 Ok(out)
451}
453/// Atomically replace `path` with `content`: temp file in the same
454/// directory, synced, then renamed over the destination.
455fn write_atomic(path: &Path, content: &[u8]) -> std::result::Result<(), SmithError> {
456 let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
457 if let Some(parent) = parent {
458 fs::create_dir_all(parent).map_err(io_tool_err("WRITE_MKDIR"))?;
459 }
460 let tmp = temp_sibling(path);
461 let write = |tmp: &Path| -> std::io::Result<()> {
462 let mut f = fs::File::create(tmp)?;
463 f.write_all(content)?;
464 f.sync_all()?;
465 Ok(())
466 };
467 write(&tmp).map_err(io_tool_err("WRITE_ERROR"))?;
468 fs::rename(&tmp, path).map_err(|e| {
469 let _ = fs::remove_file(&tmp);
470 io_tool_err("WRITE_PUBLISH")(e)
471 })?;
472 Ok(())
473}
475fn temp_sibling(path: &Path) -> PathBuf {
476 static COUNTER: AtomicUsize = AtomicUsize::new(0);
477 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
478 let name = path
479 .file_name()
480 .map(|s| s.to_string_lossy().into_owned())
481 .unwrap_or_else(|| "file".to_string());
482 path.with_file_name(format!(".{name}.tmp-{}-{n}", std::process::id()))
483}
485/// Apply exactly one unambiguous replacement, publishing atomically.
486fn edit_exact(path: &Path, old: &str, new: &str) -> std::result::Result<String, SmithError> {
487 let meta = fs::metadata(path).map_err(io_tool_err("EDIT_READ_ERROR"))?;
488 if meta.len() as usize > MAX_EDIT_FILE_BYTES {
489 return Err(tool_err(
490 "FILE_TOO_LARGE",
491 "edit input exceeds the file size limit",
492 ));
493 }
494 let bytes = fs::read(path).map_err(io_tool_err("EDIT_READ_ERROR"))?;
495 let content = String::from_utf8(bytes)
496 .map_err(|_| tool_err("EDIT_NOT_UTF8", "edit supports UTF-8 files only"))?;
497 let count = content.matches(old).count();
498 if count == 0 {
499 return Err(tool_err(
500 "EDIT_NOT_FOUND",
501 "old_string not found; file unchanged",
502 ));
503 }
504 if count > 1 {
505 return Err(tool_err(
506 "EDIT_AMBIGUOUS",
507 format!("old_string matches {count} locations; file unchanged"),
508 ));
509 }
510 let updated = content.replacen(old, new, 1);
511 write_atomic(path, updated.as_bytes())?;
512 Ok("edited".to_string())
513}
515/// Deterministic, bounded listing output.
516fn bounded_join(mut names: Vec<String>, cap: usize) -> String {
517 names.truncate(cap);
518 let mut out = names.join("\n");
519 let max = DEFAULT_OUTPUT_CAP;
520 if out.len() > max {
521 out.truncate(max);
522 out.push_str("\n<truncated>");
523 }
524 out
525}
527/// Stream matching lines with bounded memory and result count.
528fn grep_bounded(path: &Path, query: &str) -> std::result::Result<String, SmithError> {
529 let file = fs::File::open(path).map_err(io_tool_err("GREP_READ_ERROR"))?;
530 let reader = BufReader::with_capacity(64 * 1024, file);
531 let mut matches: Vec<String> = Vec::new();
532 let mut total_bytes = 0usize;
533 for line in reader.lines() {
534 let line = line.map_err(io_tool_err("GREP_READ_ERROR"))?;
535 if line.contains(query) {
536 if matches.len() >= MAX_GREP_MATCHES || total_bytes + line.len() > DEFAULT_OUTPUT_CAP {
537 matches.push("<truncated>".to_string());
538 break;
539 }
540 total_bytes += line.len();
541 matches.push(line);
542 }
543 }
544 Ok(matches.join("\n"))
545}
547fn now_ms() -> i64 {
548 std::time::SystemTime::now()
549 .duration_since(std::time::UNIX_EPOCH)
550 .map(|d| d.as_millis() as i64)
551 .unwrap_or(0)
552}
554#[cfg(test)]
555#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
556mod tests {
557 use super::*;
558 use std::path::PathBuf;
560 fn workdir(tag: &str) -> PathBuf {
561 let dir = std::env::temp_dir().join(format!("smith_tools_{}_{}", tag, std::process::id()));
562 let _ = std::fs::remove_dir_all(&dir);
563 std::fs::create_dir_all(&dir).unwrap();
564 dir
565 }
567 #[test]
568 fn write_requires_string_content_and_leaves_existing_file_untouched() {
569 let dir = workdir("write_schema");
570 let target = dir.join("data.txt");
571 std::fs::write(&target, "original").unwrap();
572 let mut ts = ToolSession::new(&dir);
573 let err = ts
574 .invoke("write", serde_json::json!({"path": "data.txt"}))
575 .unwrap_err();
576 assert_eq!(err.code(), "VALIDATION");
577 assert_eq!(std::fs::read_to_string(&target).unwrap(), "original");
578 let err = ts
579 .invoke(
580 "write",
581 serde_json::json!({"path": "data.txt", "content": 42}),
582 )
583 .unwrap_err();
584 assert_eq!(err.code(), "VALIDATION");
585 assert_eq!(std::fs::read_to_string(&target).unwrap(), "original");
586 let _ = std::fs::remove_dir_all(&dir);
587 }
589 #[test]
590 fn write_creates_missing_parents_and_leaves_no_temp_files() {
591 let dir = workdir("write_parents");
592 let mut ts = ToolSession::new(&dir);
593 ts.invoke(
594 "write",
595 serde_json::json!({"path": "a/b/c.txt", "content": "deep"}),
596 )
597 .unwrap();
598 assert_eq!(
599 std::fs::read_to_string(dir.join("a/b/c.txt")).unwrap(),
600 "deep"
601 );
602 let leftovers: Vec<_> = std::fs::read_dir(&dir)
603 .unwrap()
604 .filter_map(|e| e.ok())
605 .flat_map(|e| {
606 std::fs::read_dir(e.path())
607 .unwrap()
608 .filter_map(|x| x.ok())
609 .map(|x| x.file_name().to_string_lossy().into_owned())
610 .collect::<Vec<_>>()
611 })
612 .filter(|n| n.contains(".tmp-"))
613 .collect();
614 assert!(
615 leftovers.is_empty(),
616 "temp files left behind: {leftovers:?}"
617 );
618 let _ = std::fs::remove_dir_all(&dir);
619 }
621 #[test]
622 fn edit_rejects_ambiguous_and_missing_matches_without_changes() {
623 let dir = workdir("edit_amb");
624 let target = dir.join("f.txt");
625 std::fs::write(&target, "a a").unwrap();
626 let mut ts = ToolSession::new(&dir);
627 let err = ts
628 .invoke(
629 "edit",
630 serde_json::json!({"path": "f.txt", "old_string": "a", "new_string": "b"}),
631 )
632 .unwrap_err();
633 assert_eq!(err.code(), "EDIT_AMBIGUOUS");
634 assert_eq!(std::fs::read_to_string(&target).unwrap(), "a a");
635 let err = ts
636 .invoke(
637 "edit",
638 serde_json::json!({"path": "f.txt", "old_string": "NOT_PRESENT", "new_string": "b"}),
639 )
640 .unwrap_err();
641 assert_eq!(err.code(), "EDIT_NOT_FOUND");
642 assert_eq!(std::fs::read_to_string(&target).unwrap(), "a a");
643 // Unambiguous edit succeeds.
644 ts.invoke(
645 "edit",
646 serde_json::json!({"path": "f.txt", "old_string": "a a", "new_string": "b"}),
647 )
648 .unwrap();
649 assert_eq!(std::fs::read_to_string(&target).unwrap(), "b");
650 let _ = std::fs::remove_dir_all(&dir);
651 }
653 #[test]
654 fn read_supports_line_windows_byte_caps_and_binary_detection() {
655 let dir = workdir("read_caps");
656 let mut body = String::new();
657 for i in 0..100 {
658 body.push_str(&format!("line-{i}\n"));
659 }
660 std::fs::write(dir.join("lines.txt"), &body).unwrap();
661 let mut ts = ToolSession::new(&dir);
662 let out = ts
663 .invoke(
664 "read",
665 serde_json::json!({"path": "lines.txt", "offset": 2, "limit": 3}),
666 )
667 .unwrap();
668 assert_eq!(out.output, "line-2\nline-3\nline-4\n");
669 let capped = ts
670 .invoke(
671 "read",
672 serde_json::json!({"path": "lines.txt", "max_bytes": 20}),
673 )
674 .unwrap();
675 assert!(capped.output.len() <= 20);
676 std::fs::write(dir.join("bin.dat"), [0x62, 0x00, 0x62]).unwrap();
677 let err = ts
678 .invoke("read", serde_json::json!({"path": "bin.dat"}))
679 .unwrap_err();
680 assert_eq!(err.code(), "BINARY_CONTENT");
681 let _ = std::fs::remove_dir_all(&dir);
682 }
684 #[test]
685 fn ls_and_find_are_sorted_and_surface_errors() {
686 let dir = workdir("ls_find");
687 for name in ["zeta", "alpha", "mid"] {
688 std::fs::write(dir.join(name), "").unwrap();
689 }
690 let mut ts = ToolSession::new(&dir);
691 let out = ts.invoke("ls", serde_json::json!({})).unwrap();
692 assert_eq!(out.output, "alpha\nmid\nzeta");
693 let found = ts
694 .invoke("find", serde_json::json!({"pattern": "a"}))
695 .unwrap();
696 assert_eq!(found.output, "alpha\nzeta");
697 let err = ts
698 .invoke(
699 "find",
700 serde_json::json!({"path": "missing-dir", "pattern": "x"}),
701 )
702 .unwrap_err();
703 assert_eq!(err.code(), "FIND_ERROR");
704 let _ = std::fs::remove_dir_all(&dir);
705 }
707 #[test]
708 fn grep_returns_bounded_matches() {
709 let dir = workdir("grep");
710 std::fs::write(
711 dir.join("log.txt"),
712 "hit one\nmiss\nhit two\nmiss\nhit three\n",
713 )
714 .unwrap();
715 let mut ts = ToolSession::new(&dir);
716 let out = ts
717 .invoke(
718 "grep",
719 serde_json::json!({"path": "log.txt", "query": "hit"}),
720 )
721 .unwrap();
722 assert_eq!(out.output, "hit one\nhit two\nhit three");
723 let _ = std::fs::remove_dir_all(&dir);
724 }
726 #[test]
727 fn unregistered_tools_and_non_object_input_are_rejected() {
728 let dir = workdir("registry");
729 let mut ts = ToolSession::new(&dir);
730 let err = ts.invoke("rm", serde_json::json!({})).unwrap_err();
731 assert_eq!(err.code(), "TOOL_NOT_REGISTERED");
732 let err = ts
733 .invoke("read", serde_json::json!("not-an-object"))
734 .unwrap_err();
735 assert_eq!(err.code(), "INVALID_INPUT");
736 let _ = std::fs::remove_dir_all(&dir);
737 }
739 #[test]
740 fn failed_effects_are_recorded_as_failures() {
741 let dir = workdir("record_fail");
742 let mut ts = ToolSession::new(&dir);
743 let res = ts.invoke("read", serde_json::json!({"path": "nope.txt"}));
744 assert!(res.is_err());
745 // Two entries: call + failed result, both recorded.
746 assert_eq!(ts.session.active_branch().entries.len(), 2);
747 let last = &ts.session.active_branch().entries[1];
748 match &last.content {
749 EntryContent::ToolResult { ok, .. } => assert!(!ok),
750 other => panic!("unexpected {other:?}"),
751 }
752 let _ = std::fs::remove_dir_all(&dir);
753 }
754}

smith-core/src/trace.rs

Added
new file mode 100644

+82 / −0 text lines

1#![allow(unused_imports, dead_code)]
2use crate::session::{Entry, Session};
3use smith::id::*;
4
5/// Replay-relevant trace record (durable replay evidence).
6#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
7pub struct TraceRecord {
8 /// Replay timestamp.
9 pub timestamp_ms: i64,
10 /// Session ID.
11 pub session_id: SessionId,
12 /// Event kind.
13 pub kind: TraceKind,
14 /// Ordered event reference (entry ID or message ID).
15 pub event_ref: String,
16}
18/// Kind of replay event.
19#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
20pub enum TraceKind {
21 /// Session created.
22 SessionCreated,
23 /// Entry added.
24 EntryAdded,
25 /// Message streamed.
26 MessageStreamed,
27 /// Tool call emitted.
28 ToolCallEmitted,
29 /// Tool result received.
30 ToolResultReceived,
31 /// Compaction occurred.
32 Compaction,
33 /// Replay started.
34 ReplayStarted,
35 /// Replay completed.
36 ReplayCompleted,
37}
39/// Build a replay trace from a session.
40pub fn build_trace(session: &Session) -> Vec<TraceRecord> {
41 let mut trace = Vec::new();
42 trace.push(TraceRecord {
43 timestamp_ms: 0,
44 session_id: session.id,
45 kind: TraceKind::SessionCreated,
46 event_ref: format!("branch:{}", session.active_branch_idx),
47 });
48 for entry in &session.active_branch().entries {
49 trace.push(TraceRecord {
50 timestamp_ms: entry.timestamp_ms,
51 session_id: session.id,
52 kind: TraceKind::EntryAdded,
53 event_ref: format!("entry:{}", entry.id),
54 });
55 }
56 trace
57}
59/// Replay a session from frames deterministically.
60/// Reconstructs session state without a provider.
61pub fn replay(session: &Session) -> Vec<TraceRecord> {
62 build_trace(session)
63}
65#[cfg(test)]
66#[allow(clippy::unwrap_used, clippy::expect_used)]
67mod tests {
68 use super::*;
69 use smith::message::{Message, Role};
71 #[test]
72 fn trace_reconstructs_order() {
73 let mut session = crate::session::Session::new();
74 session.append_to_active(crate::session::Entry::message(
75 Message::with_text(Role::User, "hello"),
76 None,
77 ));
78 let trace = replay(&session);
79 assert!(!trace.is_empty());
80 assert_eq!(trace[0].kind, TraceKind::SessionCreated);
81 }
82}

smith/Cargo.toml

Modified

+8 / −0 text lines

88path = "src/lib.rs"
1010[dependencies]
11uuid = { workspace = true }
12serde = { workspace = true }
13ciborium = { workspace = true }
14serde_json = { workspace = true }
15thiserror = { workspace = true }
17[features]
18default = []No final newline

smith/src/error.rs

Added
new file mode 100644

+62 / −0 text lines

1use std::fmt;
2
3/// Recoverable Smith errors.
4#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5pub enum SmithError {
6 /// Session error.
7 Session { code: String, message: String },
8 /// Provider error.
9 Provider { code: String, message: String },
10 /// Tool error.
11 Tool { code: String, message: String },
12 /// Frame decode error.
13 FrameDecode { message: String },
14 /// Frame encode error (size or serialization).
15 FrameEncode { message: String },
16 /// Frame too large for safe decode.
17 FrameTooLarge { max_bytes: usize, actual: usize },
18 /// Cancellation.
19 Cancelled,
20 /// Configuration error.
21 Config { field: String, message: String },
22}
24impl fmt::Display for SmithError {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 match self {
27 Self::Session { code, message } => write!(f, "session [{code}]: {message}"),
28 Self::Provider { code, message } => write!(f, "provider [{code}]: {message}"),
29 Self::Tool { code, message } => write!(f, "tool [{code}]: {message}"),
30 Self::FrameDecode { message } => write!(f, "frame decode: {message}"),
31 Self::FrameEncode { message } => write!(f, "frame encode: {message}"),
32 Self::FrameTooLarge { max_bytes, actual } => {
33 write!(f, "frame too large: {actual} > {max_bytes} bytes")
34 }
35 Self::Cancelled => write!(f, "operation cancelled"),
36 Self::Config { field, message } => {
37 write!(f, "config [{field}]: {message}")
38 }
39 }
40 }
41}
43impl std::error::Error for SmithError {}
45/// Convenience result type.
46pub type Result<T> = std::result::Result<T, SmithError>;
48impl SmithError {
49 /// Short error code.
50 pub fn code(&self) -> &str {
51 match self {
52 Self::Session { code, .. } => code,
53 Self::Provider { code, .. } => code,
54 Self::Tool { code, .. } => code,
55 Self::FrameDecode { .. } => "FRAME_DECODE",
56 Self::FrameEncode { .. } => "FRAME_ENCODE",
57 Self::FrameTooLarge { .. } => "FRAME_TOO_LARGE",
58 Self::Cancelled => "CANCELLED",
59 Self::Config { .. } => "CONFIG",
60 }
61 }
62}

smith/src/id.rs

Added
new file mode 100644

+242 / −0 text lines

1use std::fmt;
2use uuid::Uuid;
3
4/// Session identifier (UUIDv7)
5#[derive(
6 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
7)]
8pub struct SessionId(Uuid);
9
10impl SessionId {
11 pub fn new() -> Self {
12 Self(Uuid::now_v7())
13 }
15 pub fn as_uuid(&self) -> Uuid {
16 self.0
17 }
18}
20impl fmt::Display for SessionId {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 self.0.fmt(f)
23 }
24}
26impl From<Uuid> for SessionId {
27 fn from(u: Uuid) -> Self {
28 Self(u)
29 }
30}
32impl From<SessionId> for Uuid {
33 fn from(id: SessionId) -> Uuid {
34 id.0
35 }
36}
38impl Default for SessionId {
39 fn default() -> Self {
40 Self::new()
41 }
42}
44/// Branch identifier (UUIDv7)
45#[derive(
46 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
47)]
48pub struct BranchId(Uuid);
50impl BranchId {
51 pub fn new() -> Self {
52 Self(Uuid::now_v7())
53 }
55 pub fn as_uuid(&self) -> Uuid {
56 self.0
57 }
58}
60impl fmt::Display for BranchId {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 self.0.fmt(f)
63 }
64}
66impl From<Uuid> for BranchId {
67 fn from(u: Uuid) -> Self {
68 Self(u)
69 }
70}
72impl From<BranchId> for Uuid {
73 fn from(id: BranchId) -> Uuid {
74 id.0
75 }
76}
78impl Default for BranchId {
79 fn default() -> Self {
80 Self::new()
81 }
82}
84/// Entry identifier (UUIDv7)
85#[derive(
86 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
87)]
88pub struct EntryId(Uuid);
90impl EntryId {
91 pub fn new() -> Self {
92 Self(Uuid::now_v7())
93 }
95 pub fn as_uuid(&self) -> Uuid {
96 self.0
97 }
98}
100impl fmt::Display for EntryId {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 self.0.fmt(f)
103 }
104}
106impl From<Uuid> for EntryId {
107 fn from(u: Uuid) -> Self {
108 Self(u)
109 }
110}
112impl From<EntryId> for Uuid {
113 fn from(id: EntryId) -> Uuid {
114 id.0
115 }
116}
118impl Default for EntryId {
119 fn default() -> Self {
120 Self::new()
121 }
122}
124/// Tool call identifier (UUIDv7)
125#[derive(
126 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
127)]
128pub struct ToolCallId(Uuid);
130impl ToolCallId {
131 pub fn new() -> Self {
132 Self(Uuid::now_v7())
133 }
135 pub fn as_uuid(&self) -> Uuid {
136 self.0
137 }
138}
140impl fmt::Display for ToolCallId {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 self.0.fmt(f)
143 }
144}
146impl From<Uuid> for ToolCallId {
147 fn from(u: Uuid) -> Self {
148 Self(u)
149 }
150}
152impl From<ToolCallId> for Uuid {
153 fn from(id: ToolCallId) -> Uuid {
154 id.0
155 }
156}
158impl Default for ToolCallId {
159 fn default() -> Self {
160 Self::new()
161 }
162}
164/// Tool result identifier (UUIDv7)
165#[derive(
166 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
167)]
168pub struct ToolResultId(Uuid);
170impl ToolResultId {
171 pub fn new() -> Self {
172 Self(Uuid::now_v7())
173 }
175 pub fn as_uuid(&self) -> Uuid {
176 self.0
177 }
178}
180impl fmt::Display for ToolResultId {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 self.0.fmt(f)
183 }
184}
186impl From<Uuid> for ToolResultId {
187 fn from(u: Uuid) -> Self {
188 Self(u)
189 }
190}
192impl From<ToolResultId> for Uuid {
193 fn from(id: ToolResultId) -> Uuid {
194 id.0
195 }
196}
198impl Default for ToolResultId {
199 fn default() -> Self {
200 Self::new()
201 }
202}
204/// Message identifier (UUIDv7)
205#[derive(
206 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
207)]
208pub struct MessageId(Uuid);
210impl MessageId {
211 pub fn new() -> Self {
212 Self(Uuid::now_v7())
213 }
215 pub fn as_uuid(&self) -> Uuid {
216 self.0
217 }
218}
220impl fmt::Display for MessageId {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 self.0.fmt(f)
223 }
224}
226impl From<Uuid> for MessageId {
227 fn from(u: Uuid) -> Self {
228 Self(u)
229 }
230}
232impl From<MessageId> for Uuid {
233 fn from(id: MessageId) -> Uuid {
234 id.0
235 }
236}
238impl Default for MessageId {
239 fn default() -> Self {
240 Self::new()
241 }
242}

smith/src/lib.rs

Modified

+145 / −1 text lines

1//! Shared Smith foundation types.
2//!
3//! Provider-neutral values, errors, cancellation, and tool contracts.
4
15#![forbid(unsafe_code)]
26#![warn(missing_docs)]
7#![allow(
8 clippy::pedantic,
9 clippy::style,
10 clippy::use_self,
11 clippy::must_use_candidate,
12 clippy::match_same_arms,
13 clippy::doc_markdown,
14 clippy::missing_const_for_fn,
15 clippy::missing_errors_doc,
16 clippy::module_name_repetitions,
17 clippy::struct_excessive_bools,
18 clippy::too_many_arguments,
19 clippy::expect_used
20)]
4//! Shared Smith foundation types.
22#[doc(hidden)]
23pub mod error;
24#[doc(hidden)]
25pub mod id;
26#[doc(hidden)]
27pub mod message;
28#[doc(hidden)]
29pub mod stream;
30#[doc(hidden)]
31pub mod tool;
33pub use error::{Result, SmithError};
34pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};
35pub use message::{ContentBlock, Message, Role};
36pub use stream::{StopReason, StreamEvent, Usage};
37pub use tool::{CancelHandle, CancellationToken, ToolCall, ToolMetadata, ToolResult};
39#[cfg(test)]
40#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic_in_result_fn)]
41mod tests {
42 use super::*;
44 #[test]
45 fn ids_are_unique_and_stable() {
46 let a = SessionId::new();
47 let b = SessionId::new();
48 assert_ne!(a, b);
49 assert_eq!(a, SessionId::from(a.as_uuid()));
50 }
52 #[test]
53 fn message_round_trips_blocks() {
54 let call_id = ToolCallId::new();
55 let mut msg = Message::with_text(Role::User, "hello");
56 msg.add_block(ContentBlock::ToolUse {
57 name: "read".to_string(),
58 input: serde_json::json!({"path": "Cargo.toml"}),
59 call_id,
60 });
61 msg.add_block(ContentBlock::ToolResult {
62 call_id,
63 ok: true,
64 output: "ok".to_string(),
65 });
66 assert_eq!(msg.blocks.len(), 3);
67 assert_eq!(msg.role, Role::User);
68 }
70 #[test]
71 fn stream_event_serializes_deterministically() {
72 let msg = MessageId::new();
73 let call = ToolCallId::new();
74 let ev1 = StreamEvent::tool_use(msg, "write", serde_json::json!({"path": "a.txt"}), call);
75 let ev2 = StreamEvent::tool_use(msg, "write", serde_json::json!({"path": "a.txt"}), call);
76 let bytes1 = serde_json::to_vec(&ev1).unwrap();
77 let bytes2 = serde_json::to_vec(&ev2).unwrap();
78 assert_eq!(bytes1, bytes2);
79 let back: StreamEvent = serde_json::from_slice(&bytes1).unwrap();
80 assert_eq!(back, ev1);
81 }
83 #[test]
84 fn tool_metadata_has_schema() {
85 let meta = ToolMetadata::new("read", "Read a file").with_schema(serde_json::json!({
86 "type": "object",
87 "required": ["path"],
88 "properties": {"path": {"type": "string"}}
89 }));
90 assert_eq!(meta.name, "read");
91 assert!(
92 meta.input_schema["required"]
93 .as_array()
94 .unwrap()
95 .contains(&"path".into())
96 );
97 }
99 #[test]
100 fn cancellation_is_cooperative() {
101 let mut token = CancellationToken::new();
102 assert!(!token.is_cancelled());
103 token.cancel();
104 assert!(token.is_cancelled());
105 }
107 #[test]
108 fn error_codes_are_stable() {
109 let err = SmithError::Tool {
110 code: "TOOL_NOT_FOUND".to_string(),
111 message: "missing".to_string(),
112 };
113 assert_eq!(err.code(), "TOOL_NOT_FOUND");
114 assert_eq!(err.to_string(), "tool [TOOL_NOT_FOUND]: missing");
115 }
117 #[test]
118 fn thinking_survives_cbor_round_trip() {
119 let mut msg = Message::with_text(Role::Assistant, "answer");
120 msg.add_block(ContentBlock::thinking("secret reasoning"));
121 let mut bytes = Vec::new();
122 ciborium::ser::into_writer(&msg, &mut bytes).unwrap();
123 let back: Message = ciborium::de::from_reader(bytes.as_slice()).unwrap();
124 assert_eq!(back.blocks[0], ContentBlock::text("answer"));
125 assert_eq!(back.blocks[1], ContentBlock::thinking("secret reasoning"));
126 // The wire form must distinguish the two block kinds.
127 let json = serde_json::to_value(&back.blocks[1]).unwrap();
128 assert_eq!(json["type"], "Thinking");
129 }
131 #[test]
132 fn cancel_handle_is_shared() {
133 let handle = CancelHandle::new();
134 let clone = handle.clone();
135 assert!(!clone.is_cancelled());
136 handle.cancel();
137 assert!(clone.is_cancelled());
138 }
140 #[test]
141 fn usage_defaults_to_zero() {
142 let u = Usage::default();
143 assert_eq!(u.input_tokens, 0);
144 assert_eq!(u.output_tokens, 0);
145 assert_eq!(u.input_cache_hit_tokens, 0);
146 assert_eq!(u.input_cache_write_tokens, 0);
147 }
148}

smith/src/message.rs

Added
new file mode 100644

+157 / −0 text lines

1use crate::id::*;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5/// Message role (who produced the message).
6#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
7pub enum Role {
8 /// User-provided message.
9 User,
10 /// Assistant-generated message.
11 Assistant,
12 /// System/internal message.
13 System,
14 /// Tool result message.
15 Tool,
16}
18impl fmt::Display for Role {
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 match self {
21 Role::User => write!(f, "user"),
22 Role::Assistant => write!(f, "assistant"),
23 Role::System => write!(f, "system"),
24 Role::Tool => write!(f, "tool"),
25 }
26 }
27}
29/// A single piece of message content.
30/// Adjacent tagging keeps `Text` and `Thinking` distinct on the wire;
31/// untagged string variants would collapse `Thinking` into `Text` on decode.
32#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
33#[serde(tag = "type", content = "data")]
34pub enum ContentBlock {
35 /// Plain text.
36 Text(String),
37 /// Thinking (internal reasoning).
38 Thinking(String),
39 /// Tool use request.
40 ToolUse {
41 /// Tool identifier.
42 name: String,
43 /// Structured input.
44 input: serde_json::Value,
45 /// Call ID for matching result.
46 call_id: ToolCallId,
47 },
48 /// Tool result.
49 ToolResult {
50 /// Matching call ID.
51 call_id: ToolCallId,
52 /// Whether execution succeeded.
53 ok: bool,
54 /// Output or error message.
55 output: String,
56 },
57}
59impl ContentBlock {
60 pub fn text<S: Into<String>>(s: S) -> Self {
61 Self::Text(s.into())
62 }
64 pub fn thinking<S: Into<String>>(s: S) -> Self {
65 Self::Thinking(s.into())
66 }
68 pub fn tool_use<N: Into<String>>(
69 name: N,
70 input: serde_json::Value,
71 call_id: ToolCallId,
72 ) -> Self {
73 Self::ToolUse {
74 name: name.into(),
75 input,
76 call_id,
77 }
78 }
80 pub fn tool_result(call_id: ToolCallId, ok: bool, output: impl Into<String>) -> Self {
81 Self::ToolResult {
82 call_id,
83 ok,
84 output: output.into(),
85 }
86 }
87}
89/// A chat message with stable ID and timestamp.
90#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
91pub struct Message {
92 /// Unique message ID.
93 pub id: MessageId,
94 /// Who produced the message.
95 pub role: Role,
96 /// Content blocks in order.
97 pub blocks: Vec<ContentBlock>,
98 /// Wall-clock time of creation (Unix ms).
99 pub timestamp_ms: i64,
100}
102impl Message {
103 pub fn new(role: Role) -> Self {
104 Self {
105 id: MessageId::new(),
106 role,
107 blocks: Vec::new(),
108 timestamp_ms: now_ms(),
109 }
110 }
112 pub fn with_text<S: Into<String>>(role: Role, text: S) -> Self {
113 Self {
114 id: MessageId::new(),
115 role,
116 blocks: vec![ContentBlock::Text(text.into())],
117 timestamp_ms: now_ms(),
118 }
119 }
121 pub fn add_block(&mut self, block: ContentBlock) {
122 self.blocks.push(block);
123 }
124}
126impl fmt::Display for Message {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 write!(f, "{} [{}]", self.role, self.id)?;
129 if !self.blocks.is_empty() {
130 write!(f, ": ")?;
131 for (i, block) in self.blocks.iter().enumerate() {
132 if i > 0 {
133 write!(f, " | ")?;
134 }
135 match block {
136 ContentBlock::Text(t) => write!(f, "text: {t}")?,
137 ContentBlock::Thinking(t) => write!(f, "thinking: {t}")?,
138 ContentBlock::ToolUse { name, call_id, .. } => {
139 write!(f, "tool_use {{ name: {name}, call_id: {call_id} }}")?
140 }
141 ContentBlock::ToolResult { call_id, ok, .. } => {
142 write!(f, "tool_result {{ call_id: {call_id}, ok: {ok} }}")?
143 }
144 }
145 }
146 }
147 Ok(())
148 }
149}
151fn now_ms() -> i64 {
152 use std::time::{SystemTime, UNIX_EPOCH};
153 SystemTime::now()
154 .duration_since(UNIX_EPOCH)
155 .map(|d| d.as_millis() as i64)
156 .unwrap_or(0)
157}

smith/src/stream.rs

Added
new file mode 100644

+154 / −0 text lines

1use crate::id::*;
2use serde::{Deserialize, Serialize};
3
4/// Normalized provider stream event.
5#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
6pub enum StreamEvent {
7 /// Assistant text delta.
8 TextDelta {
9 /// Message being streamed.
10 message_id: MessageId,
11 /// Delta text.
12 delta: String,
13 },
14 /// Assistant thinking delta.
15 ThinkingDelta {
16 /// Message being streamed.
17 message_id: MessageId,
18 /// Delta thinking.
19 delta: String,
20 },
21 /// Tool use request.
22 ToolUse {
23 /// Message being streamed.
24 message_id: MessageId,
25 /// Tool name.
26 name: String,
27 /// Tool input.
28 input: serde_json::Value,
29 /// Call ID for matching result.
30 call_id: ToolCallId,
31 },
32 /// Tool result.
33 ToolResult {
34 /// Message being streamed.
35 message_id: MessageId,
36 /// Matching call ID.
37 call_id: ToolCallId,
38 /// Whether execution succeeded.
39 ok: bool,
40 /// Output or error message.
41 output: String,
42 },
43 /// Stream ended successfully.
44 Stop {
45 /// Stop reason.
46 reason: StopReason,
47 /// Usage accounting if available.
48 usage: Option<Usage>,
49 },
50 /// Stream failed.
51 Error {
52 /// Error details.
53 error: String,
54 },
55}
57/// Why a stream stopped.
58#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
59pub enum StopReason {
60 /// Natural end of response.
61 EndTurn,
62 /// Tool use requested.
63 ToolUse,
64 /// Context or output limit reached.
65 Limit,
66 /// User or system abort.
67 Abort,
68 /// Provider-specific stop sequence.
69 StopSequence,
70}
72/// Token and cache usage accounting.
73#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
74pub struct Usage {
75 /// Input tokens.
76 pub input_tokens: u64,
77 /// Output tokens.
78 pub output_tokens: u64,
79 /// Input cache hit tokens (if any).
80 pub input_cache_hit_tokens: u64,
81 /// Input cache write tokens (if any).
82 pub input_cache_write_tokens: u64,
83}
85impl Usage {
86 pub fn new() -> Self {
87 Self {
88 input_tokens: 0,
89 output_tokens: 0,
90 input_cache_hit_tokens: 0,
91 input_cache_write_tokens: 0,
92 }
93 }
94}
96impl Default for Usage {
97 fn default() -> Self {
98 Self::new()
99 }
100}
102impl StreamEvent {
103 pub fn text_delta(message_id: MessageId, delta: impl Into<String>) -> Self {
104 Self::TextDelta {
105 message_id,
106 delta: delta.into(),
107 }
108 }
110 pub fn thinking_delta(message_id: MessageId, delta: impl Into<String>) -> Self {
111 Self::ThinkingDelta {
112 message_id,
113 delta: delta.into(),
114 }
115 }
117 pub fn tool_use(
118 message_id: MessageId,
119 name: impl Into<String>,
120 input: serde_json::Value,
121 call_id: ToolCallId,
122 ) -> Self {
123 Self::ToolUse {
124 message_id,
125 name: name.into(),
126 input,
127 call_id,
128 }
129 }
131 pub fn tool_result(
132 message_id: MessageId,
133 call_id: ToolCallId,
134 ok: bool,
135 output: impl Into<String>,
136 ) -> Self {
137 Self::ToolResult {
138 message_id,
139 call_id,
140 ok,
141 output: output.into(),
142 }
143 }
145 pub fn stop(reason: StopReason, usage: Option<Usage>) -> Self {
146 Self::Stop { reason, usage }
147 }
149 pub fn error(error: impl Into<String>) -> Self {
150 Self::Error {
151 error: error.into(),
152 }
153 }
154}

smith/src/tool.rs

Added
new file mode 100644

+100 / −0 text lines

1use crate::id::*;
2use serde::{Deserialize, Serialize};
3
4/// Tool specification (provider-neutral definition).
5#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
6pub struct ToolMetadata {
7 /// Tool name.
8 pub name: String,
9 /// Human-readable description.
10 pub description: String,
11 /// JSON Schema for input validation.
12 pub input_schema: serde_json::Value,
13}
15impl ToolMetadata {
16 pub fn new<N: Into<String>, D: Into<String>>(name: N, description: D) -> Self {
17 Self {
18 name: name.into(),
19 description: description.into(),
20 input_schema: serde_json::json!({
21 "type": "object",
22 "properties": {},
23 "required": []
24 }),
25 }
26 }
28 pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
29 self.input_schema = schema;
30 self
31 }
32}
34/// Tool call issued by the agent.
35#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
36pub struct ToolCall {
37 /// Call identifier.
38 pub call_id: ToolCallId,
39 /// Tool name.
40 pub name: String,
41 /// Arguments passed to the tool.
42 pub input: serde_json::Value,
43}
45/// Tool execution result.
46#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
47pub struct ToolResult {
48 /// Matching call identifier.
49 pub call_id: ToolCallId,
50 /// Whether the tool succeeded.
51 pub ok: bool,
52 /// Output text or serialized result.
53 pub output: String,
54}
56/// Cancellation token for bounded cancellation.
57/// A simple flag that can be polled or triggered externally.
58#[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]
59pub struct CancellationToken {
60 /// Whether cancellation has been requested.
61 pub cancelled: bool,
62}
64impl CancellationToken {
65 pub fn new() -> Self {
66 Self { cancelled: false }
67 }
69 pub fn cancel(&mut self) {
70 self.cancelled = true;
71 }
73 pub fn is_cancelled(&self) -> bool {
74 self.cancelled
75 }
76}
78/// Shared, thread-safe cancellation handle for active effects.
79/// Clone into a running effect; `cancel` from the owner thread.
80#[derive(Clone, Debug, Default)]
81pub struct CancelHandle {
82 flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
83}
85impl CancelHandle {
86 /// A handle that starts uncancelled.
87 pub fn new() -> Self {
88 Self::default()
89 }
91 /// Request cancellation; observed by the owning effect.
92 pub fn cancel(&self) {
93 self.flag.store(true, std::sync::atomic::Ordering::Release);
94 }
96 /// Whether cancellation was requested.
97 pub fn is_cancelled(&self) -> bool {
98 self.flag.load(std::sync::atomic::Ordering::Acquire)
99 }
100}