circlet_wire/lib.rs
1//! The Circlet wire contract — the one definition both sides compile.
2//!
3//! Everything that crosses the guest boundary is described here: the
4//! envelope for each host import, the codec that carries it, and the packed
5//! (pointer, length) layout results ride home in. The host crate
6//! (`circlet`) re-exports these types; the guest SDK (`circlet-guest`)
7//! consumes them. Neither side declares its own copy, so the contract
8//! cannot drift — and the encoded bytes are pinned by test in this crate,
9//! where a change has to announce itself.
10//!
11//! # One encoding
12//!
13//! Envelopes are [postcard](https://docs.rs/postcard): compact, no
14//! intermediate string, no field names on the wire, byte slices carried as
15//! bytes rather than arrays of decimal numbers. There is exactly one
16//! encoding and nothing to negotiate — an option whose weaker arm nobody
17//! should pick is not an option, it is a liability, and a codec chosen per
18//! artifact is a second wire to keep in step forever.
19//!
20//! Two things that are deliberately NOT this codec:
21//!
22//! - **Cast input and output.** Opaque bytes to Circlet, whatever the
23//! embedder puts there.
24//! - **Documents.** Receipts and recorded transcripts are JSON: they are
25//! read by people and by other systems, long after the run, at a
26//! standards edge. A live wire and a stored document want opposite
27//! things.
28//!
29//! This crate depends on `serde` and `postcard` alone: it compiles for
30//! `wasm32-unknown-unknown` inside every guest, so it assumes nothing beyond
31//! an allocator.
32
33#![warn(missing_docs)]
34
35extern crate alloc;
36
37use alloc::vec::Vec;
38use serde::{Deserialize, Serialize};
39
40// ── the codec ───────────────────────────────────────────────────────────
41
42/// Encode an envelope for the boundary.
43///
44/// Fails only if a type cannot be represented (a map with non-string keys,
45/// say) — no envelope here can, and the `Result` is here so the day one
46/// could, it says so instead of panicking inside a guest.
47pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, &'static str> {
48 postcard::to_allocvec(value).map_err(|_| "envelope does not encode")
49}
50
51/// Decode an envelope from the boundary.
52///
53/// Borrowing is available where a type allows it (`&'a str`, `&'a [u8]`):
54/// postcard hands out slices into `bytes` without copying. Today's envelopes
55/// are owned, because the copy they avoid has not been measured and API
56/// churn for an unmeasured microsecond is the wrong trade.
57pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T, &'static str> {
58 postcard::from_bytes(bytes).map_err(|_| "malformed envelope")
59}
60
61// ── the packed-pointer ABI ──────────────────────────────────────────────
62
63/// Pack a guest (pointer, length) pair into the one `i64` the ABI returns:
64/// pointer in the high 32 bits, length in the low 32.
65pub fn pack(ptr: u32, len: u32) -> i64 {
66 (((ptr as u64) << 32) | len as u64) as i64
67}
68
69/// The inverse of [`pack`].
70pub fn unpack(v: i64) -> (u32, u32) {
71 ((v as u64 >> 32) as u32, (v as u64 & 0xffff_ffff) as u32)
72}
73
74// ── envelopes ───────────────────────────────────────────────────────────
75
76/// An outbound HTTP request as the guest describes it. Circlet validates the
77/// host, substitutes secrets, and hands the finished request to the
78/// embedder's `Host`.
79///
80/// `{{secret.NAME}}` placeholders resolve in `url` and `headers` only —
81/// never in `body`, which is opaque bytes. That line is deliberate: it keeps
82/// substitution deterministic and keeps binary bodies binary.
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct FetchRequest {
85 /// HTTP method, verbatim.
86 pub method: String,
87 /// Full URL; the hostname must be in the grant's allowlist.
88 pub url: String,
89 /// Header pairs, verbatim after secret substitution.
90 #[serde(default)]
91 pub headers: Vec<(String, String)>,
92 /// Request body, passed through untouched.
93 #[serde(default)]
94 pub body: Vec<u8>,
95 /// The author's declared price for THIS call, in pixie — the
96 /// developer-priced bill line, the author's own margin on a call their
97 /// action performs. Reserved from the grant BEFORE the call performs,
98 /// gas-style, so estimation never breaks; the guest may price it lower
99 /// afterwards ([`Price`]), and a call never priced stands at its max.
100 /// `None` means the call carries no developer price.
101 #[serde(default)]
102 pub price_max: Option<u64>,
103}
104
105/// What the guest sends to `circlet.price`: what its most recent
106/// developer-priced fetch was actually worth, once the response has shown
107/// (per result returned, per byte delivered — the author's own pricing
108/// logic). Must be at or under the reserved `price_max`; the difference
109/// returns to the payer's grant. Above the max is a typed trap, never a
110/// bill.
111///
112/// Named for the family it belongs to — `price_max`, `price`,
113/// `developer_priced`. The word "settle" belongs to the payment rails
114/// (x402 spells its own wire verb that way), and one word may only mean one
115/// thing.
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117pub struct Price {
118 /// The price the author charged, in pixie.
119 pub actual: u64,
120}
121
122/// The response handed back into the circle.
123#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
124pub struct FetchResponse {
125 /// HTTP status code.
126 pub status: u16,
127 /// Response headers the host chose to pass through.
128 #[serde(default)]
129 pub headers: Vec<(String, String)>,
130 /// Response body.
131 #[serde(default)]
132 pub body: Vec<u8>,
133 /// What this call actually cost, in pixie, when the host knows better
134 /// than the schedule does — a paid API's real price, a metered egress
135 /// bill. `None` leaves it to the schedule.
136 #[serde(default)]
137 pub pixie: Option<u64>,
138}
139
140/// One chunk of a model stream, and what it cost.
141#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
142pub struct LlmChunk {
143 /// The chunk's text.
144 pub text: String,
145 /// What this chunk actually cost, in pixie. A host that sees real token
146 /// counts should report them here: tokens are the true unit, and the
147 /// schedule's per-KiB rate is only an approximation of them.
148 #[serde(default)]
149 pub pixie: Option<u64>,
150}
151
152impl From<String> for LlmChunk {
153 fn from(text: String) -> Self {
154 Self { text, pixie: None }
155 }
156}
157
158impl From<&str> for LlmChunk {
159 fn from(text: &str) -> Self {
160 Self {
161 text: text.to_string(),
162 pixie: None,
163 }
164 }
165}
166
167/// What a local agent returned, and what it cost.
168#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
169pub struct Delegation {
170 /// The agent's reply.
171 pub text: String,
172 /// What the agent run actually cost, in pixie. Often `None` on the
173 /// client venue: the user's own subscription paid, so the platform's
174 /// cost is the fixed overhead and nothing more.
175 #[serde(default)]
176 pub pixie: Option<u64>,
177 /// What actually served the run, host-reported (e.g. `claude-code`,
178 /// a provider's model id). The guest asked with an [`Intent`], never a
179 /// name; this is the honest record of how the host resolved it.
180 #[serde(default)]
181 pub served_by: Option<String>,
182}
183
184impl From<String> for Delegation {
185 fn from(text: String) -> Self {
186 Self {
187 text,
188 pixie: None,
189 served_by: None,
190 }
191 }
192}
193
194/// What `circlet.seed` hands the guest: the host-stamped wall clock and a
195/// random seed — the ONLY nondeterminism a guest can ever see, delivered as
196/// a recorded input rather than an ambient power. One pair per cast: every
197/// call inside one cast returns the same values (a reflex is conceptually
198/// instantaneous), the transcript records them once, and replay serves the
199/// recording — so "what time is it" stops being the reason a guest author
200/// reaches outside the circle, and determinism survives.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
202pub struct Seed {
203 /// The wall clock at the cast, unix milliseconds, host-stamped.
204 pub now_unix_ms: u64,
205 /// A random value, host-stamped. Feed it to any deterministic PRNG.
206 pub seed: u64,
207}
208
209/// The mind a call asks for — a **bounded vocabulary**, never a model name.
210///
211/// The guest states what kind of answer it needs; the host (Wandlet: the
212/// resolver's intent mapping) picks the provider, model, and parameters.
213/// Keeping model names out of guests is what lets the platform swap
214/// providers without touching a single published artifact — and it is why
215/// this is two small closed enums rather than open strings: an unknown
216/// value is refused at the boundary instead of silently falling through
217/// someone's mapping table.
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
219pub struct Intent {
220 /// The quality/latency corner to aim for.
221 pub tier: Tier,
222 /// How hard to think before answering.
223 pub effort: Effort,
224}
225
226/// The quality/latency corner an [`Intent`] aims for.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(rename_all = "lowercase")]
229pub enum Tier {
230 /// Cheapest acceptable answer, latency first.
231 Fast,
232 /// The sensible default.
233 Balanced,
234 /// The strongest mind available, cost second.
235 Best,
236}
237
238/// How much deliberation an [`Intent`] asks for.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(rename_all = "lowercase")]
241pub enum Effort {
242 /// A reflexive answer.
243 Low,
244 /// Ordinary consideration.
245 Medium,
246 /// Extended reasoning, where the provider offers it.
247 High,
248}
249
250/// What the guest sends to `circlet.invoke`: run another action and give me
251/// its output.
252///
253/// `action` is an **open string**. Circlet never learns what an action id
254/// means — it checks the id against the grant's allowlist and hands the
255/// request to the embedder, which is the only side that can resolve an id
256/// to something runnable. Depth and cycles are the embedder's policy too:
257/// it builds the sub-cast's grant, so it decides whether that grant may
258/// invoke anything at all.
259///
260/// `pixie_max` is reserved from the caller's grant BEFORE the sub-cast
261/// runs, gas-style, exactly like [`FetchRequest::price_max`]: a call the
262/// grant cannot pay for is never made, so composition never breaks a quote.
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264pub struct InvokeRequest {
265 /// The action to run, in whatever id space the embedder uses.
266 pub action: String,
267 /// The input bytes for it — opaque, exactly like a cast's own input.
268 pub input: Vec<u8>,
269 /// The ceiling this invocation may spend, in pixie, reserved up front.
270 pub pixie_max: u64,
271}
272
273/// What the embedder hands back: the sub-action's output and what it cost.
274///
275/// `pixie` is a **measurement, not an estimate** — the sub-cast produced its
276/// own receipt, and its total is the honest number. It must be at or under
277/// the reserved `pixie_max`; above it is a typed error, never a bill.
278#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
279pub struct InvokeResponse {
280 /// The sub-action's output bytes.
281 pub output: Vec<u8>,
282 /// What the sub-cast actually spent, in pixie.
283 pub pixie: u64,
284}
285
286// ── what an artifact says it needs ──────────────────────────────────────
287
288/// What an artifact requires to run, declared by the code that requires it.
289///
290/// Emitted by `circlet_guest::requirements!` into a wasm custom section
291/// named `circlet.requirements`, postcard-encoded. **The section rides
292/// inside the content address by construction**: the digest is taken over
293/// the whole module, so requirements cannot lie about the code they ship
294/// with — change either and the artifact is a different artifact.
295///
296/// Everything is optional and defaults to nothing: an artifact that
297/// declares no requirements needs no grant beyond compute.
298#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
299pub struct Requirements {
300 /// Destinations it will address, as `host` or `host:port`.
301 pub hosts: Vec<String>,
302 /// Credentials it will spend, by name, destination and who supplies it.
303 pub secrets: Vec<SecretNeed>,
304 /// Local agents it will ask.
305 pub agents: Vec<String>,
306 /// Actions it will invoke, by id.
307 pub invocable: Vec<String>,
308 /// Ceilings it needs — the same vocabulary as the grant, because the
309 /// grant is what an embedder builds from this.
310 pub max_fetches: u32,
311 /// Ceiling on delegations.
312 pub max_delegations: u32,
313 /// Ceiling on model calls.
314 pub max_llm_calls: u32,
315 /// Ceiling on invocations.
316 pub max_invocations: u32,
317 /// Ceiling on log bytes.
318 pub max_log_bytes: u32,
319 /// Largest payload it needs to move in one piece.
320 pub max_payload_bytes: u32,
321 /// Whether it reads the cast's seed.
322 pub seed: bool,
323 /// The most it will reserve for any one invocation.
324 pub invoke_pixie_max: u64,
325 /// The mind it asks for, when it asks for one.
326 pub intent: Option<Intent>,
327 /// The most it will charge for any one developer-priced call — the
328 /// ceiling a caller can be quoted before running anything.
329 pub price_max: u64,
330 /// The author's fee for a cast, in pixie.
331 pub fee: u64,
332}
333
334/// One credential an artifact needs, and who is expected to supply it.
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336pub struct SecretNeed {
337 /// The `{{secret.NAME}}` the code writes.
338 pub name: String,
339 /// The only destination it may be spent against.
340 pub host: String,
341 /// Whose credential it is.
342 pub owner: Owner,
343}
344
345/// Who supplies a secret. A bounded vocabulary, like every other one that
346/// crosses a boundary: an unknown word is refused rather than guessed at.
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(rename_all = "lowercase")]
349pub enum Owner {
350 /// The action's author ships it; callers never see it.
351 Developer,
352 /// Whoever installed the action supplies their own.
353 Installer,
354 /// The team the caller belongs to supplies it.
355 Team,
356}
357
358/// What the guest sends to `circlet.delegate`.
359#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
360pub struct DelegateRequest {
361 /// The agent to ask; must be in the grant's agent allowlist.
362 pub agent: String,
363 /// The prompt to hand over.
364 pub prompt: String,
365 /// The mind to ask for — passed to the host verbatim; the host resolves
366 /// it. `None` leaves the choice entirely to the host.
367 #[serde(default)]
368 pub intent: Option<Intent>,
369}
370
371/// What the guest sends to `circlet.llm_open`.
372#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
373pub struct LlmRequest {
374 /// The user-turn prompt.
375 pub prompt: String,
376 /// Optional system prompt.
377 #[serde(default)]
378 pub system: Option<String>,
379 /// Advisory output ceiling the embedder maps to its provider's parameter.
380 #[serde(default)]
381 pub max_output_bytes: Option<usize>,
382 /// The mind to ask for — passed to the host verbatim; the host resolves
383 /// it. `None` leaves the choice entirely to the host.
384 #[serde(default)]
385 pub intent: Option<Intent>,
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 #[test]
393 fn pack_roundtrip() {
394 assert_eq!(unpack(pack(0xDEAD, 0xBEEF)), (0xDEAD, 0xBEEF));
395 assert_eq!(unpack(pack(u32::MAX, u32::MAX)), (u32::MAX, u32::MAX));
396 }
397
398 /// The encoded bytes ARE the contract. A field added, reordered, or
399 /// retyped is a breaking change for every compiled guest in the world;
400 /// postcard writes fields positionally and carries no names, so nothing
401 /// but a pinned vector can make that change announce itself.
402 #[test]
403 fn the_encoded_bytes_are_the_contract() {
404 let req = FetchRequest {
405 method: "GET".into(),
406 url: "https://h.io/x".into(),
407 headers: vec![("a".into(), "b".into())],
408 body: vec![1, 2],
409 price_max: None,
410 };
411 assert_eq!(
412 encode(&req).unwrap(),
413 vec![
414 3, b'G', b'E', b'T', // method: len 3, "GET"
415 14, b'h', b't', b't', b'p', b's', b':', b'/', b'/', b'h', b'.', b'i', b'o', b'/',
416 b'x', // url: len 14
417 1, 1, b'a', 1, b'b', // headers: 1 pair, "a" -> "b"
418 2, 1, 2, // body: len 2, bytes 1 2 — bytes, not decimals
419 0, // price_max: None
420 ]
421 );
422 // Some(_) is one more byte of tag plus a varint, and the ONLY
423 // difference: an optional field never disappears from the wire,
424 // because postcard reads fields by position.
425 let priced = FetchRequest {
426 price_max: Some(40_000),
427 ..req.clone()
428 };
429 let bytes = encode(&priced).unwrap();
430 assert_eq!(
431 &bytes[..bytes.len() - 4],
432 &encode(&req).unwrap()[..bytes.len() - 4]
433 );
434 assert_eq!(
435 &bytes[bytes.len() - 4..],
436 &[1, 192, 184, 2],
437 "Some(40000): tag, then a base-128 varint"
438 );
439 assert_eq!(decode::<FetchRequest>(&bytes).unwrap(), priced);
440
441 assert_eq!(encode(&Price { actual: 7 }).unwrap(), vec![7]);
442 assert_eq!(
443 encode(&InvokeRequest {
444 action: "web3/get-block".into(),
445 input: vec![7, 8],
446 pixie_max: 40_000,
447 })
448 .unwrap(),
449 vec![
450 14, b'w', b'e', b'b', b'3', b'/', b'g', b'e', b't', b'-', b'b', b'l', b'o', b'c',
451 b'k', // action: len 14
452 2, 7, 8, // input: len 2, bytes — an action id carries no shape
453 192, 184, 2, // pixie_max: a base-128 varint, not an Option
454 ]
455 );
456 assert_eq!(
457 encode(&InvokeResponse {
458 output: vec![9],
459 pixie: 100,
460 })
461 .unwrap(),
462 vec![1, 9, 100]
463 );
464 assert_eq!(
465 encode(&Seed {
466 now_unix_ms: 1_756_252_800_000,
467 seed: 42,
468 })
469 .unwrap(),
470 vec![128, 136, 204, 198, 142, 51, 42]
471 );
472 assert_eq!(
473 encode(&FetchResponse {
474 status: 200,
475 headers: vec![],
476 body: vec![9],
477 pixie: None,
478 })
479 .unwrap(),
480 vec![200, 1, 0, 1, 9, 0]
481 );
482 // The requirements section: an artifact describing itself.
483 assert_eq!(
484 encode(&Requirements {
485 hosts: vec!["api.exa.ai".into()],
486 secrets: vec![SecretNeed {
487 name: "K".into(),
488 host: "api.exa.ai".into(),
489 owner: Owner::Developer,
490 }],
491 max_fetches: 2,
492 price_max: 40_000,
493 fee: 25_000,
494 ..Requirements::default()
495 })
496 .unwrap(),
497 vec![
498 1, 10, b'a', b'p', b'i', b'.', b'e', b'x', b'a', b'.', b'a', b'i', // 1 host
499 1, // 1 secret:
500 1, b'K', // its name,
501 10, b'a', b'p', b'i', b'.', b'e', b'x', b'a', b'.', b'a', b'i', // its host,
502 0, // and its owner: developer, an index like every enum here
503 0, 0, // agents, invocable: none
504 2, // max_fetches
505 0, 0, 0, 0, 0, // delegations, llm, invocations, log bytes, payload
506 0, // seed: false
507 0, // invoke_pixie_max
508 0, // intent: None
509 192, 184, 2, // price_max 40000, a base-128 varint
510 168, 195, 1, // fee 25000
511 ]
512 );
513 assert_eq!(
514 encode(&Intent {
515 tier: Tier::Best,
516 effort: Effort::High,
517 })
518 .unwrap(),
519 vec![2, 2],
520 "a bounded vocabulary is an index on the wire, in declaration order"
521 );
522 }
523
524 /// Every envelope, both directions, including the corners that a
525 /// positional codec gets wrong: `None` beside `Some`, empty vectors,
526 /// and non-ASCII text.
527 #[test]
528 fn every_envelope_round_trips() {
529 fn round_trip<T>(value: T)
530 where
531 T: serde::Serialize + for<'a> serde::Deserialize<'a> + PartialEq + core::fmt::Debug,
532 {
533 let bytes = encode(&value).unwrap();
534 assert_eq!(decode::<T>(&bytes).unwrap(), value);
535 // A truncated envelope is refused, never half-read.
536 if !bytes.is_empty() {
537 assert!(decode::<T>(&bytes[..bytes.len() - 1]).is_err());
538 }
539 }
540
541 for price_max in [None, Some(0), Some(u64::MAX)] {
542 round_trip(FetchRequest {
543 method: "POST".into(),
544 url: "https://h.io/π?x=1".into(),
545 headers: vec![("k".into(), "v".into()), ("k2".into(), String::new())],
546 body: vec![0, 255, 128],
547 price_max,
548 });
549 }
550 for pixie in [None, Some(1_u64)] {
551 round_trip(FetchResponse {
552 status: 404,
553 headers: vec![],
554 body: Vec::new(),
555 pixie,
556 });
557 round_trip(LlmChunk {
558 text: "hi π".into(),
559 pixie,
560 });
561 round_trip(Delegation {
562 text: String::new(),
563 pixie,
564 served_by: Some("claude-code".into()),
565 });
566 }
567 for intent in [
568 None,
569 Some(Intent {
570 tier: Tier::Fast,
571 effort: Effort::Low,
572 }),
573 Some(Intent {
574 tier: Tier::Balanced,
575 effort: Effort::Medium,
576 }),
577 ] {
578 round_trip(DelegateRequest {
579 agent: "claude".into(),
580 prompt: "p".into(),
581 intent,
582 });
583 round_trip(LlmRequest {
584 prompt: "p".into(),
585 system: Some("s".into()),
586 max_output_bytes: Some(4096),
587 intent,
588 });
589 }
590 round_trip(LlmRequest {
591 prompt: String::new(),
592 system: None,
593 max_output_bytes: None,
594 intent: None,
595 });
596 round_trip(Price { actual: 7 });
597 round_trip(Requirements::default());
598 round_trip(Requirements {
599 hosts: vec!["a".into(), "b:8443".into()],
600 secrets: vec![
601 SecretNeed {
602 name: "A".into(),
603 host: "a".into(),
604 owner: Owner::Installer,
605 },
606 SecretNeed {
607 name: "B".into(),
608 host: "b".into(),
609 owner: Owner::Team,
610 },
611 ],
612 agents: vec!["claude".into()],
613 invocable: vec!["pack/sub".into()],
614 max_fetches: u32::MAX,
615 max_delegations: 1,
616 max_llm_calls: 2,
617 max_invocations: 3,
618 max_log_bytes: 4,
619 max_payload_bytes: 5,
620 seed: true,
621 invoke_pixie_max: u64::MAX,
622 intent: Some(Intent {
623 tier: Tier::Best,
624 effort: Effort::High,
625 }),
626 price_max: 6,
627 fee: 7,
628 });
629 for pixie_max in [0, u64::MAX] {
630 round_trip(InvokeRequest {
631 action: String::new(),
632 input: Vec::new(),
633 pixie_max,
634 });
635 round_trip(InvokeRequest {
636 action: "pack/action π".into(),
637 input: vec![0, 255],
638 pixie_max,
639 });
640 }
641 round_trip(InvokeResponse {
642 output: Vec::new(),
643 pixie: 0,
644 });
645 round_trip(InvokeResponse {
646 output: vec![1, 2, 3],
647 pixie: u64::MAX,
648 });
649 round_trip(Seed {
650 now_unix_ms: 0,
651 seed: u64::MAX,
652 });
653 }
654
655 /// Intent also rides RECEIPTS and TRANSCRIPTS, which are documents and
656 /// stay JSON. There the spelling is the contract, and it is lowercase.
657 #[test]
658 fn the_intent_vocabulary_reads_the_same_in_a_document() {
659 let intent = Intent {
660 tier: Tier::Best,
661 effort: Effort::High,
662 };
663 assert_eq!(
664 serde_json::to_value(intent).unwrap(),
665 serde_json::json!({ "tier": "best", "effort": "high" })
666 );
667 let parsed: Intent = serde_json::from_str(r#"{"tier":"fast","effort":"low"}"#).unwrap();
668 assert_eq!(parsed.tier, Tier::Fast);
669 assert_eq!(parsed.effort, Effort::Low);
670 // A closed set: an unknown word is refused at the boundary, never
671 // passed through to somebody's mapping table.
672 assert!(serde_json::from_str::<Intent>(r#"{"tier":"gpt-5","effort":"low"}"#).is_err());
673 assert!(serde_json::from_str::<Intent>(r#"{"tier":"fast","effort":"max"}"#).is_err());
674
675 // Transcripts recorded before a field existed still parse.
676 let minimal: DelegateRequest =
677 serde_json::from_str(r#"{"agent":"claude","prompt":"p"}"#).unwrap();
678 assert!(minimal.intent.is_none());
679 let minimal: LlmRequest = serde_json::from_str(r#"{"prompt":"p"}"#).unwrap();
680 assert!(minimal.system.is_none() && minimal.max_output_bytes.is_none());
681 }
682}