Skip to main content

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::string::String;
38use alloc::vec::Vec;
39use serde::{Deserialize, Serialize};
40
41/// The Circlet guest ABI version this wire crate defines.
42///
43/// Embedded into every guest built with `circlet_guest::guest_main!` inside
44/// the `circlet.abi` custom section so hosts refuse an incompatible artifact
45/// at `seal()` instead of misreading a boundary envelope at runtime.
46///
47/// - Version 1: `circlet.invoke` returned raw output bytes and guests had no
48///   typed error exit channel.
49/// - Version 2: `circlet.invoke` returns postcard-encoded [`InvokeResult`]
50///   (`Result<Vec<u8>, InvokeError>`) and guests may exit with a structured
51///   [`GuestError`] through `circlet.fail`.
52pub const ABI_VERSION: u32 = 2;
53
54// ── the codec ───────────────────────────────────────────────────────────
55
56/// Encode an envelope for the boundary.
57///
58/// Fails only if a type cannot be represented (a map with non-string keys,
59/// say) — no envelope here can, and the `Result` is here so the day one
60/// could, it says so instead of panicking inside a guest.
61pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, &'static str> {
62    postcard::to_allocvec(value).map_err(|_| "envelope does not encode")
63}
64
65/// Decode an envelope from the boundary.
66///
67/// Borrowing is available where a type allows it (`&'a str`, `&'a [u8]`):
68/// postcard hands out slices into `bytes` without copying. Today's envelopes
69/// are owned, because the copy they avoid has not been measured and API
70/// churn for an unmeasured microsecond is the wrong trade.
71pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T, &'static str> {
72    postcard::from_bytes(bytes).map_err(|_| "malformed envelope")
73}
74
75// ── the packed-pointer ABI ──────────────────────────────────────────────
76
77/// Pack a guest (pointer, length) pair into the one `i64` the ABI returns:
78/// pointer in the high 32 bits, length in the low 32.
79pub fn pack(ptr: u32, len: u32) -> i64 {
80    (((ptr as u64) << 32) | len as u64) as i64
81}
82
83/// The inverse of [`pack`].
84pub fn unpack(v: i64) -> (u32, u32) {
85    ((v as u64 >> 32) as u32, (v as u64 & 0xffff_ffff) as u32)
86}
87
88// ── envelopes ───────────────────────────────────────────────────────────
89
90/// An outbound HTTP request as the guest describes it. Circlet validates the
91/// host, substitutes secrets, and hands the finished request to the
92/// embedder's `Host`.
93///
94/// `{{secret.NAME}}` placeholders resolve in `url` and `headers` only —
95/// never in `body`, which is opaque bytes. That line is deliberate: it keeps
96/// substitution deterministic and keeps binary bodies binary.
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98pub struct FetchRequest {
99    /// HTTP method, verbatim.
100    pub method: String,
101    /// Full URL; the hostname must be in the grant's allowlist.
102    pub url: String,
103    /// Header pairs, verbatim after secret substitution.
104    #[serde(default)]
105    pub headers: Vec<(String, String)>,
106    /// Request body, passed through untouched.
107    #[serde(default)]
108    pub body: Vec<u8>,
109    /// The author's declared price for THIS call, in pixie — the
110    /// developer-priced bill line, the author's own margin on a call their
111    /// action performs. Reserved from the grant BEFORE the call performs,
112    /// gas-style, so estimation never breaks; the guest may price it lower
113    /// afterwards ([`Price`]), and a call never priced stands at its max.
114    /// `None` means the call carries no developer price.
115    #[serde(default)]
116    pub price_max: Option<u64>,
117}
118
119/// What the guest sends to `circlet.price`: what its most recent
120/// developer-priced fetch was actually worth, once the response has shown
121/// (per result returned, per byte delivered — the author's own pricing
122/// logic). Must be at or under the reserved `price_max`; the difference
123/// returns to the payer's grant. Above the max is a typed trap, never a
124/// bill.
125///
126/// Named for the family it belongs to — `price_max`, `price`,
127/// `developer_priced`. The word "settle" belongs to the payment rails
128/// (x402 spells its own wire verb that way), and one word may only mean one
129/// thing.
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub struct Price {
132    /// The price the author charged, in pixie.
133    pub actual: u64,
134}
135
136/// The response handed back into the circle.
137#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
138pub struct FetchResponse {
139    /// HTTP status code.
140    pub status: u16,
141    /// Response headers the host chose to pass through.
142    #[serde(default)]
143    pub headers: Vec<(String, String)>,
144    /// Response body.
145    #[serde(default)]
146    pub body: Vec<u8>,
147    /// What this call actually cost, in pixie, when the host knows better
148    /// than the schedule does — a paid API's real price, a metered egress
149    /// bill. `None` leaves it to the schedule.
150    #[serde(default)]
151    pub pixie: Option<u64>,
152}
153
154/// One chunk of a model stream, and what it cost.
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct LlmChunk {
157    /// The chunk's text.
158    pub text: String,
159    /// What this chunk actually cost, in pixie. A host that sees real token
160    /// counts should report them here: tokens are the true unit, and the
161    /// schedule's per-KiB rate is only an approximation of them.
162    #[serde(default)]
163    pub pixie: Option<u64>,
164}
165
166impl From<String> for LlmChunk {
167    fn from(text: String) -> Self {
168        Self { text, pixie: None }
169    }
170}
171
172impl From<&str> for LlmChunk {
173    fn from(text: &str) -> Self {
174        Self {
175            text: text.to_string(),
176            pixie: None,
177        }
178    }
179}
180
181/// What a local agent returned, and what it cost.
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
183pub struct Delegation {
184    /// The agent's reply.
185    pub text: String,
186    /// What the agent run actually cost, in pixie. Often `None` on the
187    /// client venue: the user's own subscription paid, so the platform's
188    /// cost is the fixed overhead and nothing more.
189    #[serde(default)]
190    pub pixie: Option<u64>,
191    /// What actually served the run, host-reported (e.g. `claude-code`,
192    /// a provider's model id). The guest asked with an [`Intent`], never a
193    /// name; this is the honest record of how the host resolved it.
194    #[serde(default)]
195    pub served_by: Option<String>,
196}
197
198impl From<String> for Delegation {
199    fn from(text: String) -> Self {
200        Self {
201            text,
202            pixie: None,
203            served_by: None,
204        }
205    }
206}
207
208/// What `circlet.seed` hands the guest: the host-stamped wall clock and a
209/// random seed — the ONLY nondeterminism a guest can ever see, delivered as
210/// a recorded input rather than an ambient power. One pair per cast: every
211/// call inside one cast returns the same values (a reflex is conceptually
212/// instantaneous), the transcript records them once, and replay serves the
213/// recording — so "what time is it" stops being the reason a guest author
214/// reaches outside the circle, and determinism survives.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
216pub struct Seed {
217    /// The wall clock at the cast, unix milliseconds, host-stamped.
218    pub now_unix_ms: u64,
219    /// A random value, host-stamped. Feed it to any deterministic PRNG.
220    pub seed: u64,
221}
222
223/// The mind a call asks for — a **bounded vocabulary**, never a model name.
224///
225/// The guest states what kind of answer it needs; the host (Wandlet: the
226/// resolver's intent mapping) picks the provider, model, and parameters.
227/// Keeping model names out of guests is what lets the platform swap
228/// providers without touching a single published artifact — and it is why
229/// this is two small closed enums rather than open strings: an unknown
230/// value is refused at the boundary instead of silently falling through
231/// someone's mapping table.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
233pub struct Intent {
234    /// The quality/latency corner to aim for.
235    pub tier: Tier,
236    /// How hard to think before answering.
237    pub effort: Effort,
238}
239
240/// The quality/latency corner an [`Intent`] aims for.
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(rename_all = "lowercase")]
243pub enum Tier {
244    /// Cheapest acceptable answer, latency first.
245    Fast,
246    /// The sensible default.
247    Balanced,
248    /// The strongest mind available, cost second.
249    Best,
250}
251
252/// How much deliberation an [`Intent`] asks for.
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(rename_all = "lowercase")]
255pub enum Effort {
256    /// A reflexive answer.
257    Low,
258    /// Ordinary consideration.
259    Medium,
260    /// Extended reasoning, where the provider offers it.
261    High,
262}
263
264/// What the guest sends to `circlet.invoke`: run another action and give me
265/// its output.
266///
267/// `action` is an **open string**. Circlet never learns what an action id
268/// means — it checks the id against the grant's allowlist and hands the
269/// request to the embedder, which is the only side that can resolve an id
270/// to something runnable. Depth and cycles are the embedder's policy too:
271/// it builds the sub-cast's grant, so it decides whether that grant may
272/// invoke anything at all.
273///
274/// `pixie_max` is reserved from the caller's grant BEFORE the sub-cast
275/// runs, gas-style, exactly like [`FetchRequest::price_max`]: a call the
276/// grant cannot pay for is never made, so composition never breaks a quote.
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278pub struct InvokeRequest {
279    /// The action to run, in whatever id space the embedder uses.
280    pub action: String,
281    /// The input bytes for it — opaque, exactly like a cast's own input.
282    pub input: Vec<u8>,
283    /// The ceiling this invocation may spend, in pixie, reserved up front.
284    pub pixie_max: u64,
285}
286
287/// What the embedder hands back: the sub-action's output and what it cost.
288///
289/// `pixie` is a **measurement, not an estimate** — the sub-cast produced its
290/// own receipt, and its total is the honest number. It must be at or under
291/// the reserved `pixie_max`; above it is a typed error, never a bill.
292#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
293pub struct InvokeResponse {
294    /// The sub-action's output bytes.
295    pub output: Vec<u8>,
296    /// What the sub-cast actually spent, in pixie.
297    pub pixie: u64,
298}
299
300/// A structured error crossing the guest boundary — returned by a guest
301/// through `circlet.fail`, or handed back to a caller by `circlet.invoke`
302/// ([`InvokeError`]).
303///
304/// Circlet itself is policy-free and payload-agnostic: it never interprets
305/// `code` or `detail`. The embedder owns the error vocabulary (`code`) and
306/// the encoding of `detail` bytes (JSON, CBOR, or none), while Circlet
307/// guarantees the structured error crosses the Wasm boundary intact without
308/// colliding with output payloads or flattening to a single string.
309#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
310pub struct GuestError {
311    /// Machine-readable error code in the embedder's vocabulary
312    /// (for example `"invalid"`, `"not_found"`, `"conflict"`, `"busy"`).
313    pub code: String,
314    /// Human-readable explanation of what failed.
315    pub message: String,
316    /// Optional structured detail bytes, opaque to Circlet.
317    #[serde(default)]
318    pub detail: Option<Vec<u8>>,
319    /// Optional hint of how long to wait before retrying, in milliseconds.
320    #[serde(default)]
321    pub retry_after_ms: Option<u64>,
322}
323
324impl GuestError {
325    /// Construct a structured error with a machine-readable `code` and
326    /// explanation `message`.
327    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
328        Self {
329            code: code.into(),
330            message: message.into(),
331            detail: None,
332            retry_after_ms: None,
333        }
334    }
335
336    /// Construct a plain failure with code `"failed"`.
337    pub fn message(message: impl Into<String>) -> Self {
338        Self::new("failed", message)
339    }
340
341    /// Attach opaque structured detail bytes to this error.
342    #[must_use]
343    pub fn with_detail(mut self, detail: impl Into<Vec<u8>>) -> Self {
344        self.detail = Some(detail.into());
345        self
346    }
347
348    /// Attach a retry hint in milliseconds to this error.
349    #[must_use]
350    pub fn with_retry_after_ms(mut self, retry_after_ms: u64) -> Self {
351        self.retry_after_ms = Some(retry_after_ms);
352        self
353    }
354
355    /// View `detail` as UTF-8 text when present and valid UTF-8.
356    pub fn detail_str(&self) -> Option<&str> {
357        self.detail
358            .as_deref()
359            .and_then(|bytes| core::str::from_utf8(bytes).ok())
360    }
361}
362
363impl core::fmt::Display for GuestError {
364    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
365        if self.code.is_empty() || self.code == "failed" {
366            f.write_str(&self.message)
367        } else {
368            write!(f, "{}: {}", self.code, self.message)
369        }
370    }
371}
372
373impl core::error::Error for GuestError {}
374
375impl From<String> for GuestError {
376    fn from(message: String) -> Self {
377        Self::message(message)
378    }
379}
380
381impl From<&str> for GuestError {
382    fn from(message: &str) -> Self {
383        Self::message(message)
384    }
385}
386
387/// A structured error returned to a guest by `circlet.invoke`.
388///
389/// The exact same shape as [`GuestError`], so a caller that invokes another
390/// action can propagate `invoke(...)?;` directly out of a fallible
391/// `guest_main!` handler without copying or losing fields.
392pub type InvokeError = GuestError;
393
394/// The postcard-encoded value `circlet.invoke` writes back into guest memory:
395/// either the sub-action's opaque output bytes or a structured [`InvokeError`].
396pub type InvokeResult = Result<Vec<u8>, InvokeError>;
397
398/// What `Host::invoke` returns when the host itself did not fault: either the
399/// sub-action's output or a structured [`InvokeError`], each carrying what
400/// the sub-action actually spent in `pixie`.
401///
402/// A host/policy/security denial still returns `Err(String)` from
403/// `Host::invoke` and traps the calling cast as `HostFailed`.
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
405pub enum InvokeOutcome {
406    /// The sub-action produced output bytes.
407    Output(InvokeResponse),
408    /// The sub-action returned a structured error handed back to guest code.
409    Error {
410        /// The structured error returned to the guest.
411        error: InvokeError,
412        /// What the sub-cast actually spent, in pixie (`<= pixie_max`).
413        pixie: u64,
414    },
415}
416
417impl InvokeOutcome {
418    /// What the sub-action spent in pixie, whether it returned output or a
419    /// structured error.
420    pub fn pixie(&self) -> u64 {
421        match self {
422            Self::Output(resp) => resp.pixie,
423            Self::Error { pixie, .. } => *pixie,
424        }
425    }
426}
427
428impl From<InvokeResponse> for InvokeOutcome {
429    fn from(resp: InvokeResponse) -> Self {
430        Self::Output(resp)
431    }
432}
433
434// ── what an artifact says it needs ──────────────────────────────────────
435
436/// What an artifact requires to run, declared by the code that requires it.
437///
438/// Emitted by `circlet_guest::requirements!` into a wasm custom section
439/// named `circlet.requirements`, postcard-encoded. **The section rides
440/// inside the content address by construction**: the digest is taken over
441/// the whole module, so requirements cannot lie about the code they ship
442/// with — change either and the artifact is a different artifact.
443///
444/// Everything is optional and defaults to nothing: an artifact that
445/// declares no requirements needs no grant beyond compute.
446#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
447pub struct Requirements {
448    /// Destinations it will address, as `host` or `host:port`.
449    pub hosts: Vec<String>,
450    /// Credentials it will spend, by name, destination and who supplies it.
451    pub secrets: Vec<SecretNeed>,
452    /// Local agents it will ask.
453    pub agents: Vec<String>,
454    /// Actions it will invoke, by id.
455    pub invocable: Vec<String>,
456    /// Ceilings it needs — the same vocabulary as the grant, because the
457    /// grant is what an embedder builds from this.
458    pub max_fetches: u32,
459    /// Ceiling on delegations.
460    pub max_delegations: u32,
461    /// Ceiling on model calls.
462    pub max_llm_calls: u32,
463    /// Ceiling on invocations.
464    pub max_invocations: u32,
465    /// Ceiling on log bytes.
466    pub max_log_bytes: u32,
467    /// Largest payload it needs to move in one piece.
468    pub max_payload_bytes: u32,
469    /// Whether it reads the cast's seed.
470    pub seed: bool,
471    /// The most it will reserve for any one invocation.
472    pub invoke_pixie_max: u64,
473    /// The mind it asks for, when it asks for one.
474    pub intent: Option<Intent>,
475    /// The most it will charge for any one developer-priced call — the
476    /// ceiling a caller can be quoted before running anything.
477    pub price_max: u64,
478    /// The author's fee for a cast, in pixie.
479    pub fee: u64,
480}
481
482/// One credential an artifact needs, and who is expected to supply it.
483#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
484pub struct SecretNeed {
485    /// The `{{secret.NAME}}` the code writes.
486    pub name: String,
487    /// The only destination it may be spent against.
488    pub host: String,
489    /// Whose credential it is.
490    pub owner: Owner,
491}
492
493/// Who supplies a secret. A bounded vocabulary, like every other one that
494/// crosses a boundary: an unknown word is refused rather than guessed at.
495#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
496#[serde(rename_all = "lowercase")]
497pub enum Owner {
498    /// The action's author ships it; callers never see it.
499    Developer,
500    /// Whoever installed the action supplies their own.
501    Installer,
502    /// The team the caller belongs to supplies it.
503    Team,
504}
505
506/// What the guest sends to `circlet.delegate`.
507#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
508pub struct DelegateRequest {
509    /// The agent to ask; must be in the grant's agent allowlist.
510    pub agent: String,
511    /// The prompt to hand over.
512    pub prompt: String,
513    /// The mind to ask for — passed to the host verbatim; the host resolves
514    /// it. `None` leaves the choice entirely to the host.
515    #[serde(default)]
516    pub intent: Option<Intent>,
517}
518
519/// What the guest sends to `circlet.llm_open`.
520#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
521pub struct LlmRequest {
522    /// The user-turn prompt.
523    pub prompt: String,
524    /// Optional system prompt.
525    #[serde(default)]
526    pub system: Option<String>,
527    /// Advisory output ceiling the embedder maps to its provider's parameter.
528    #[serde(default)]
529    pub max_output_bytes: Option<usize>,
530    /// The mind to ask for — passed to the host verbatim; the host resolves
531    /// it. `None` leaves the choice entirely to the host.
532    #[serde(default)]
533    pub intent: Option<Intent>,
534}
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539
540    #[test]
541    fn pack_roundtrip() {
542        assert_eq!(unpack(pack(0xDEAD, 0xBEEF)), (0xDEAD, 0xBEEF));
543        assert_eq!(unpack(pack(u32::MAX, u32::MAX)), (u32::MAX, u32::MAX));
544    }
545
546    /// The encoded bytes ARE the contract. A field added, reordered, or
547    /// retyped is a breaking change for every compiled guest in the world;
548    /// postcard writes fields positionally and carries no names, so nothing
549    /// but a pinned vector can make that change announce itself.
550    #[test]
551    fn the_encoded_bytes_are_the_contract() {
552        let req = FetchRequest {
553            method: "GET".into(),
554            url: "https://h.io/x".into(),
555            headers: vec![("a".into(), "b".into())],
556            body: vec![1, 2],
557            price_max: None,
558        };
559        assert_eq!(
560            encode(&req).unwrap(),
561            vec![
562                3, b'G', b'E', b'T', // method: len 3, "GET"
563                14, b'h', b't', b't', b'p', b's', b':', b'/', b'/', b'h', b'.', b'i', b'o', b'/',
564                b'x', // url: len 14
565                1, 1, b'a', 1, b'b', // headers: 1 pair, "a" -> "b"
566                2, 1, 2, // body: len 2, bytes 1 2 — bytes, not decimals
567                0, // price_max: None
568            ]
569        );
570        // Some(_) is one more byte of tag plus a varint, and the ONLY
571        // difference: an optional field never disappears from the wire,
572        // because postcard reads fields by position.
573        let priced = FetchRequest {
574            price_max: Some(40_000),
575            ..req.clone()
576        };
577        let bytes = encode(&priced).unwrap();
578        assert_eq!(
579            &bytes[..bytes.len() - 4],
580            &encode(&req).unwrap()[..bytes.len() - 4]
581        );
582        assert_eq!(
583            &bytes[bytes.len() - 4..],
584            &[1, 192, 184, 2],
585            "Some(40000): tag, then a base-128 varint"
586        );
587        assert_eq!(decode::<FetchRequest>(&bytes).unwrap(), priced);
588
589        assert_eq!(encode(&Price { actual: 7 }).unwrap(), vec![7]);
590        assert_eq!(
591            encode(&InvokeRequest {
592                action: "web3/get-block".into(),
593                input: vec![7, 8],
594                pixie_max: 40_000,
595            })
596            .unwrap(),
597            vec![
598                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',
599                b'k', // action: len 14
600                2, 7, 8, // input: len 2, bytes — an action id carries no shape
601                192, 184, 2, // pixie_max: a base-128 varint, not an Option
602            ]
603        );
604        assert_eq!(
605            encode(&InvokeResponse {
606                output: vec![9],
607                pixie: 100,
608            })
609            .unwrap(),
610            vec![1, 9, 100]
611        );
612        assert_eq!(
613            encode(&GuestError::new("not_found", "missing")).unwrap(),
614            vec![
615                9, b'n', b'o', b't', b'_', b'f', b'o', b'u', b'n', b'd', // code
616                7, b'm', b'i', b's', b's', b'i', b'n', b'g', // message
617                0, // detail: None
618                0, // retry_after_ms: None
619            ]
620        );
621        assert_eq!(
622            encode(&InvokeResult::Ok(vec![9, 10])).unwrap(),
623            vec![0, 2, 9, 10],
624            "Ok variant tag 0, then byte length and bytes"
625        );
626        assert_eq!(
627            encode(&InvokeResult::Err(
628                InvokeError::new("busy", "slow down")
629                    .with_detail(b"{}".to_vec())
630                    .with_retry_after_ms(500)
631            ))
632            .unwrap(),
633            vec![
634                1, // Err variant tag
635                4, b'b', b'u', b's', b'y', // code
636                9, b's', b'l', b'o', b'w', b' ', b'd', b'o', b'w', b'n', // message
637                1, 2, b'{', b'}', // detail: Some(b"{}")
638                1, 244, 3, // retry_after_ms: Some(500)
639            ]
640        );
641        assert_eq!(
642            encode(&Seed {
643                now_unix_ms: 1_756_252_800_000,
644                seed: 42,
645            })
646            .unwrap(),
647            vec![128, 136, 204, 198, 142, 51, 42]
648        );
649        assert_eq!(
650            encode(&FetchResponse {
651                status: 200,
652                headers: vec![],
653                body: vec![9],
654                pixie: None,
655            })
656            .unwrap(),
657            vec![200, 1, 0, 1, 9, 0]
658        );
659        // The requirements section: an artifact describing itself.
660        assert_eq!(
661            encode(&Requirements {
662                hosts: vec!["api.exa.ai".into()],
663                secrets: vec![SecretNeed {
664                    name: "K".into(),
665                    host: "api.exa.ai".into(),
666                    owner: Owner::Developer,
667                }],
668                max_fetches: 2,
669                price_max: 40_000,
670                fee: 25_000,
671                ..Requirements::default()
672            })
673            .unwrap(),
674            vec![
675                1, 10, b'a', b'p', b'i', b'.', b'e', b'x', b'a', b'.', b'a', b'i', // 1 host
676                1,    // 1 secret:
677                1, b'K', // its name,
678                10, b'a', b'p', b'i', b'.', b'e', b'x', b'a', b'.', b'a', b'i', // its host,
679                0,    // and its owner: developer, an index like every enum here
680                0, 0, // agents, invocable: none
681                2, // max_fetches
682                0, 0, 0, 0, 0, // delegations, llm, invocations, log bytes, payload
683                0, // seed: false
684                0, // invoke_pixie_max
685                0, // intent: None
686                192, 184, 2, // price_max 40000, a base-128 varint
687                168, 195, 1, // fee 25000
688            ]
689        );
690        assert_eq!(
691            encode(&Intent {
692                tier: Tier::Best,
693                effort: Effort::High,
694            })
695            .unwrap(),
696            vec![2, 2],
697            "a bounded vocabulary is an index on the wire, in declaration order"
698        );
699    }
700
701    /// Every envelope, both directions, including the corners that a
702    /// positional codec gets wrong: `None` beside `Some`, empty vectors,
703    /// and non-ASCII text.
704    #[test]
705    fn every_envelope_round_trips() {
706        fn round_trip<T>(value: T)
707        where
708            T: serde::Serialize + for<'a> serde::Deserialize<'a> + PartialEq + core::fmt::Debug,
709        {
710            let bytes = encode(&value).unwrap();
711            assert_eq!(decode::<T>(&bytes).unwrap(), value);
712            // A truncated envelope is refused, never half-read.
713            if !bytes.is_empty() {
714                assert!(decode::<T>(&bytes[..bytes.len() - 1]).is_err());
715            }
716        }
717
718        for price_max in [None, Some(0), Some(u64::MAX)] {
719            round_trip(FetchRequest {
720                method: "POST".into(),
721                url: "https://h.io/π?x=1".into(),
722                headers: vec![("k".into(), "v".into()), ("k2".into(), String::new())],
723                body: vec![0, 255, 128],
724                price_max,
725            });
726        }
727        for pixie in [None, Some(1_u64)] {
728            round_trip(FetchResponse {
729                status: 404,
730                headers: vec![],
731                body: Vec::new(),
732                pixie,
733            });
734            round_trip(LlmChunk {
735                text: "hi π".into(),
736                pixie,
737            });
738            round_trip(Delegation {
739                text: String::new(),
740                pixie,
741                served_by: Some("claude-code".into()),
742            });
743        }
744        for intent in [
745            None,
746            Some(Intent {
747                tier: Tier::Fast,
748                effort: Effort::Low,
749            }),
750            Some(Intent {
751                tier: Tier::Balanced,
752                effort: Effort::Medium,
753            }),
754        ] {
755            round_trip(DelegateRequest {
756                agent: "claude".into(),
757                prompt: "p".into(),
758                intent,
759            });
760            round_trip(LlmRequest {
761                prompt: "p".into(),
762                system: Some("s".into()),
763                max_output_bytes: Some(4096),
764                intent,
765            });
766        }
767        round_trip(LlmRequest {
768            prompt: String::new(),
769            system: None,
770            max_output_bytes: None,
771            intent: None,
772        });
773        round_trip(Price { actual: 7 });
774        round_trip(Requirements::default());
775        round_trip(Requirements {
776            hosts: vec!["a".into(), "b:8443".into()],
777            secrets: vec![
778                SecretNeed {
779                    name: "A".into(),
780                    host: "a".into(),
781                    owner: Owner::Installer,
782                },
783                SecretNeed {
784                    name: "B".into(),
785                    host: "b".into(),
786                    owner: Owner::Team,
787                },
788            ],
789            agents: vec!["claude".into()],
790            invocable: vec!["pack/sub".into()],
791            max_fetches: u32::MAX,
792            max_delegations: 1,
793            max_llm_calls: 2,
794            max_invocations: 3,
795            max_log_bytes: 4,
796            max_payload_bytes: 5,
797            seed: true,
798            invoke_pixie_max: u64::MAX,
799            intent: Some(Intent {
800                tier: Tier::Best,
801                effort: Effort::High,
802            }),
803            price_max: 6,
804            fee: 7,
805        });
806        for pixie_max in [0, u64::MAX] {
807            round_trip(InvokeRequest {
808                action: String::new(),
809                input: Vec::new(),
810                pixie_max,
811            });
812            round_trip(InvokeRequest {
813                action: "pack/action π".into(),
814                input: vec![0, 255],
815                pixie_max,
816            });
817        }
818        round_trip(InvokeResponse {
819            output: Vec::new(),
820            pixie: 0,
821        });
822        round_trip(InvokeResponse {
823            output: vec![1, 2, 3],
824            pixie: u64::MAX,
825        });
826        round_trip(GuestError::new("", ""));
827        round_trip(
828            GuestError::new("conflict", "already moved π")
829                .with_detail(vec![0, 123, 255])
830                .with_retry_after_ms(u64::MAX),
831        );
832        round_trip(InvokeResult::Ok(Vec::new()));
833        round_trip(InvokeResult::Ok(vec![1, 2, 3]));
834        round_trip(InvokeResult::Err(GuestError::new("invalid", "bad")));
835        round_trip(Seed {
836            now_unix_ms: 0,
837            seed: u64::MAX,
838        });
839    }
840
841    /// Intent also rides RECEIPTS and TRANSCRIPTS, which are documents and
842    /// stay JSON. There the spelling is the contract, and it is lowercase.
843    #[test]
844    fn the_intent_vocabulary_reads_the_same_in_a_document() {
845        let intent = Intent {
846            tier: Tier::Best,
847            effort: Effort::High,
848        };
849        assert_eq!(
850            serde_json::to_value(intent).unwrap(),
851            serde_json::json!({ "tier": "best", "effort": "high" })
852        );
853        let parsed: Intent = serde_json::from_str(r#"{"tier":"fast","effort":"low"}"#).unwrap();
854        assert_eq!(parsed.tier, Tier::Fast);
855        assert_eq!(parsed.effort, Effort::Low);
856        // A closed set: an unknown word is refused at the boundary, never
857        // passed through to somebody's mapping table.
858        assert!(serde_json::from_str::<Intent>(r#"{"tier":"gpt-5","effort":"low"}"#).is_err());
859        assert!(serde_json::from_str::<Intent>(r#"{"tier":"fast","effort":"max"}"#).is_err());
860
861        // Transcripts recorded before a field existed still parse.
862        let minimal: DelegateRequest =
863            serde_json::from_str(r#"{"agent":"claude","prompt":"p"}"#).unwrap();
864        assert!(minimal.intent.is_none());
865        let minimal: LlmRequest = serde_json::from_str(r#"{"prompt":"p"}"#).unwrap();
866        assert!(minimal.system.is_none() && minimal.max_output_bytes.is_none());
867    }
868}