circlet-wire 0.2.0

The Circlet guest ABI wire contract: envelope types, their postcard encoding, and the packed-pointer layout, shared by host and guests.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! The Circlet wire contract — the one definition both sides compile.
//!
//! Everything that crosses the guest boundary is described here: the
//! envelope for each host import, the codec that carries it, and the packed
//! (pointer, length) layout results ride home in. The host crate
//! (`circlet`) re-exports these types; the guest SDK (`circlet-guest`)
//! consumes them. Neither side declares its own copy, so the contract
//! cannot drift — and the encoded bytes are pinned by test in this crate,
//! where a change has to announce itself.
//!
//! # One encoding
//!
//! Envelopes are [postcard](https://docs.rs/postcard): compact, no
//! intermediate string, no field names on the wire, byte slices carried as
//! bytes rather than arrays of decimal numbers. There is exactly one
//! encoding and nothing to negotiate — an option whose weaker arm nobody
//! should pick is not an option, it is a liability, and a codec chosen per
//! artifact is a second wire to keep in step forever.
//!
//! Two things that are deliberately NOT this codec:
//!
//! - **Cast input and output.** Opaque bytes to Circlet, whatever the
//!   embedder puts there.
//! - **Documents.** Receipts and recorded transcripts are JSON: they are
//!   read by people and by other systems, long after the run, at a
//!   standards edge. A live wire and a stored document want opposite
//!   things.
//!
//! This crate depends on `serde` and `postcard` alone: it compiles for
//! `wasm32-unknown-unknown` inside every guest, so it assumes nothing beyond
//! an allocator.

#![warn(missing_docs)]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

/// The Circlet guest ABI version this wire crate defines.
///
/// Embedded into every guest built with `circlet_guest::guest_main!` inside
/// the `circlet.abi` custom section so hosts refuse an incompatible artifact
/// at `seal()` instead of misreading a boundary envelope at runtime.
///
/// - Version 1: `circlet.invoke` returned raw output bytes and guests had no
///   typed error exit channel.
/// - Version 2: `circlet.invoke` returns postcard-encoded [`InvokeResult`]
///   (`Result<Vec<u8>, InvokeError>`) and guests may exit with a structured
///   [`GuestError`] through `circlet.fail`.
pub const ABI_VERSION: u32 = 2;

// ── the codec ───────────────────────────────────────────────────────────

/// Encode an envelope for the boundary.
///
/// Fails only if a type cannot be represented (a map with non-string keys,
/// say) — no envelope here can, and the `Result` is here so the day one
/// could, it says so instead of panicking inside a guest.
pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, &'static str> {
    postcard::to_allocvec(value).map_err(|_| "envelope does not encode")
}

/// Decode an envelope from the boundary.
///
/// Borrowing is available where a type allows it (`&'a str`, `&'a [u8]`):
/// postcard hands out slices into `bytes` without copying. Today's envelopes
/// are owned, because the copy they avoid has not been measured and API
/// churn for an unmeasured microsecond is the wrong trade.
pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T, &'static str> {
    postcard::from_bytes(bytes).map_err(|_| "malformed envelope")
}

// ── the packed-pointer ABI ──────────────────────────────────────────────

/// Pack a guest (pointer, length) pair into the one `i64` the ABI returns:
/// pointer in the high 32 bits, length in the low 32.
pub fn pack(ptr: u32, len: u32) -> i64 {
    (((ptr as u64) << 32) | len as u64) as i64
}

/// The inverse of [`pack`].
pub fn unpack(v: i64) -> (u32, u32) {
    ((v as u64 >> 32) as u32, (v as u64 & 0xffff_ffff) as u32)
}

// ── envelopes ───────────────────────────────────────────────────────────

/// An outbound HTTP request as the guest describes it. Circlet validates the
/// host, substitutes secrets, and hands the finished request to the
/// embedder's `Host`.
///
/// `{{secret.NAME}}` placeholders resolve in `url` and `headers` only —
/// never in `body`, which is opaque bytes. That line is deliberate: it keeps
/// substitution deterministic and keeps binary bodies binary.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FetchRequest {
    /// HTTP method, verbatim.
    pub method: String,
    /// Full URL; the hostname must be in the grant's allowlist.
    pub url: String,
    /// Header pairs, verbatim after secret substitution.
    #[serde(default)]
    pub headers: Vec<(String, String)>,
    /// Request body, passed through untouched.
    #[serde(default)]
    pub body: Vec<u8>,
    /// The author's declared price for THIS call, in pixie — the
    /// developer-priced bill line, the author's own margin on a call their
    /// action performs. Reserved from the grant BEFORE the call performs,
    /// gas-style, so estimation never breaks; the guest may price it lower
    /// afterwards ([`Price`]), and a call never priced stands at its max.
    /// `None` means the call carries no developer price.
    #[serde(default)]
    pub price_max: Option<u64>,
}

/// What the guest sends to `circlet.price`: what its most recent
/// developer-priced fetch was actually worth, once the response has shown
/// (per result returned, per byte delivered — the author's own pricing
/// logic). Must be at or under the reserved `price_max`; the difference
/// returns to the payer's grant. Above the max is a typed trap, never a
/// bill.
///
/// Named for the family it belongs to — `price_max`, `price`,
/// `developer_priced`. The word "settle" belongs to the payment rails
/// (x402 spells its own wire verb that way), and one word may only mean one
/// thing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Price {
    /// The price the author charged, in pixie.
    pub actual: u64,
}

/// The response handed back into the circle.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct FetchResponse {
    /// HTTP status code.
    pub status: u16,
    /// Response headers the host chose to pass through.
    #[serde(default)]
    pub headers: Vec<(String, String)>,
    /// Response body.
    #[serde(default)]
    pub body: Vec<u8>,
    /// What this call actually cost, in pixie, when the host knows better
    /// than the schedule does — a paid API's real price, a metered egress
    /// bill. `None` leaves it to the schedule.
    #[serde(default)]
    pub pixie: Option<u64>,
}

/// One chunk of a model stream, and what it cost.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LlmChunk {
    /// The chunk's text.
    pub text: String,
    /// What this chunk actually cost, in pixie. A host that sees real token
    /// counts should report them here: tokens are the true unit, and the
    /// schedule's per-KiB rate is only an approximation of them.
    #[serde(default)]
    pub pixie: Option<u64>,
}

impl From<String> for LlmChunk {
    fn from(text: String) -> Self {
        Self { text, pixie: None }
    }
}

impl From<&str> for LlmChunk {
    fn from(text: &str) -> Self {
        Self {
            text: text.to_string(),
            pixie: None,
        }
    }
}

/// What a local agent returned, and what it cost.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Delegation {
    /// The agent's reply.
    pub text: String,
    /// What the agent run actually cost, in pixie. Often `None` on the
    /// client venue: the user's own subscription paid, so the platform's
    /// cost is the fixed overhead and nothing more.
    #[serde(default)]
    pub pixie: Option<u64>,
    /// What actually served the run, host-reported (e.g. `claude-code`,
    /// a provider's model id). The guest asked with an [`Intent`], never a
    /// name; this is the honest record of how the host resolved it.
    #[serde(default)]
    pub served_by: Option<String>,
}

impl From<String> for Delegation {
    fn from(text: String) -> Self {
        Self {
            text,
            pixie: None,
            served_by: None,
        }
    }
}

/// What `circlet.seed` hands the guest: the host-stamped wall clock and a
/// random seed — the ONLY nondeterminism a guest can ever see, delivered as
/// a recorded input rather than an ambient power. One pair per cast: every
/// call inside one cast returns the same values (a reflex is conceptually
/// instantaneous), the transcript records them once, and replay serves the
/// recording — so "what time is it" stops being the reason a guest author
/// reaches outside the circle, and determinism survives.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Seed {
    /// The wall clock at the cast, unix milliseconds, host-stamped.
    pub now_unix_ms: u64,
    /// A random value, host-stamped. Feed it to any deterministic PRNG.
    pub seed: u64,
}

/// The mind a call asks for — a **bounded vocabulary**, never a model name.
///
/// The guest states what kind of answer it needs; the host (Wandlet: the
/// resolver's intent mapping) picks the provider, model, and parameters.
/// Keeping model names out of guests is what lets the platform swap
/// providers without touching a single published artifact — and it is why
/// this is two small closed enums rather than open strings: an unknown
/// value is refused at the boundary instead of silently falling through
/// someone's mapping table.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Intent {
    /// The quality/latency corner to aim for.
    pub tier: Tier,
    /// How hard to think before answering.
    pub effort: Effort,
}

/// The quality/latency corner an [`Intent`] aims for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Tier {
    /// Cheapest acceptable answer, latency first.
    Fast,
    /// The sensible default.
    Balanced,
    /// The strongest mind available, cost second.
    Best,
}

/// How much deliberation an [`Intent`] asks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
    /// A reflexive answer.
    Low,
    /// Ordinary consideration.
    Medium,
    /// Extended reasoning, where the provider offers it.
    High,
}

/// What the guest sends to `circlet.invoke`: run another action and give me
/// its output.
///
/// `action` is an **open string**. Circlet never learns what an action id
/// means — it checks the id against the grant's allowlist and hands the
/// request to the embedder, which is the only side that can resolve an id
/// to something runnable. Depth and cycles are the embedder's policy too:
/// it builds the sub-cast's grant, so it decides whether that grant may
/// invoke anything at all.
///
/// `pixie_max` is reserved from the caller's grant BEFORE the sub-cast
/// runs, gas-style, exactly like [`FetchRequest::price_max`]: a call the
/// grant cannot pay for is never made, so composition never breaks a quote.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InvokeRequest {
    /// The action to run, in whatever id space the embedder uses.
    pub action: String,
    /// The input bytes for it — opaque, exactly like a cast's own input.
    pub input: Vec<u8>,
    /// The ceiling this invocation may spend, in pixie, reserved up front.
    pub pixie_max: u64,
}

/// What the embedder hands back: the sub-action's output and what it cost.
///
/// `pixie` is a **measurement, not an estimate** — the sub-cast produced its
/// own receipt, and its total is the honest number. It must be at or under
/// the reserved `pixie_max`; above it is a typed error, never a bill.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvokeResponse {
    /// The sub-action's output bytes.
    pub output: Vec<u8>,
    /// What the sub-cast actually spent, in pixie.
    pub pixie: u64,
}

/// A structured error crossing the guest boundary — returned by a guest
/// through `circlet.fail`, or handed back to a caller by `circlet.invoke`
/// ([`InvokeError`]).
///
/// Circlet itself is policy-free and payload-agnostic: it never interprets
/// `code` or `detail`. The embedder owns the error vocabulary (`code`) and
/// the encoding of `detail` bytes (JSON, CBOR, or none), while Circlet
/// guarantees the structured error crosses the Wasm boundary intact without
/// colliding with output payloads or flattening to a single string.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GuestError {
    /// Machine-readable error code in the embedder's vocabulary
    /// (for example `"invalid"`, `"not_found"`, `"conflict"`, `"busy"`).
    pub code: String,
    /// Human-readable explanation of what failed.
    pub message: String,
    /// Optional structured detail bytes, opaque to Circlet.
    #[serde(default)]
    pub detail: Option<Vec<u8>>,
    /// Optional hint of how long to wait before retrying, in milliseconds.
    #[serde(default)]
    pub retry_after_ms: Option<u64>,
}

impl GuestError {
    /// Construct a structured error with a machine-readable `code` and
    /// explanation `message`.
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            detail: None,
            retry_after_ms: None,
        }
    }

    /// Construct a plain failure with code `"failed"`.
    pub fn message(message: impl Into<String>) -> Self {
        Self::new("failed", message)
    }

    /// Attach opaque structured detail bytes to this error.
    #[must_use]
    pub fn with_detail(mut self, detail: impl Into<Vec<u8>>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// Attach a retry hint in milliseconds to this error.
    #[must_use]
    pub fn with_retry_after_ms(mut self, retry_after_ms: u64) -> Self {
        self.retry_after_ms = Some(retry_after_ms);
        self
    }

    /// View `detail` as UTF-8 text when present and valid UTF-8.
    pub fn detail_str(&self) -> Option<&str> {
        self.detail
            .as_deref()
            .and_then(|bytes| core::str::from_utf8(bytes).ok())
    }
}

impl core::fmt::Display for GuestError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if self.code.is_empty() || self.code == "failed" {
            f.write_str(&self.message)
        } else {
            write!(f, "{}: {}", self.code, self.message)
        }
    }
}

impl core::error::Error for GuestError {}

impl From<String> for GuestError {
    fn from(message: String) -> Self {
        Self::message(message)
    }
}

impl From<&str> for GuestError {
    fn from(message: &str) -> Self {
        Self::message(message)
    }
}

/// A structured error returned to a guest by `circlet.invoke`.
///
/// The exact same shape as [`GuestError`], so a caller that invokes another
/// action can propagate `invoke(...)?;` directly out of a fallible
/// `guest_main!` handler without copying or losing fields.
pub type InvokeError = GuestError;

/// The postcard-encoded value `circlet.invoke` writes back into guest memory:
/// either the sub-action's opaque output bytes or a structured [`InvokeError`].
pub type InvokeResult = Result<Vec<u8>, InvokeError>;

/// What `Host::invoke` returns when the host itself did not fault: either the
/// sub-action's output or a structured [`InvokeError`], each carrying what
/// the sub-action actually spent in `pixie`.
///
/// A host/policy/security denial still returns `Err(String)` from
/// `Host::invoke` and traps the calling cast as `HostFailed`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum InvokeOutcome {
    /// The sub-action produced output bytes.
    Output(InvokeResponse),
    /// The sub-action returned a structured error handed back to guest code.
    Error {
        /// The structured error returned to the guest.
        error: InvokeError,
        /// What the sub-cast actually spent, in pixie (`<= pixie_max`).
        pixie: u64,
    },
}

impl InvokeOutcome {
    /// What the sub-action spent in pixie, whether it returned output or a
    /// structured error.
    pub fn pixie(&self) -> u64 {
        match self {
            Self::Output(resp) => resp.pixie,
            Self::Error { pixie, .. } => *pixie,
        }
    }
}

impl From<InvokeResponse> for InvokeOutcome {
    fn from(resp: InvokeResponse) -> Self {
        Self::Output(resp)
    }
}

// ── what an artifact says it needs ──────────────────────────────────────

/// What an artifact requires to run, declared by the code that requires it.
///
/// Emitted by `circlet_guest::requirements!` into a wasm custom section
/// named `circlet.requirements`, postcard-encoded. **The section rides
/// inside the content address by construction**: the digest is taken over
/// the whole module, so requirements cannot lie about the code they ship
/// with — change either and the artifact is a different artifact.
///
/// Everything is optional and defaults to nothing: an artifact that
/// declares no requirements needs no grant beyond compute.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Requirements {
    /// Destinations it will address, as `host` or `host:port`.
    pub hosts: Vec<String>,
    /// Credentials it will spend, by name, destination and who supplies it.
    pub secrets: Vec<SecretNeed>,
    /// Local agents it will ask.
    pub agents: Vec<String>,
    /// Actions it will invoke, by id.
    pub invocable: Vec<String>,
    /// Ceilings it needs — the same vocabulary as the grant, because the
    /// grant is what an embedder builds from this.
    pub max_fetches: u32,
    /// Ceiling on delegations.
    pub max_delegations: u32,
    /// Ceiling on model calls.
    pub max_llm_calls: u32,
    /// Ceiling on invocations.
    pub max_invocations: u32,
    /// Ceiling on log bytes.
    pub max_log_bytes: u32,
    /// Largest payload it needs to move in one piece.
    pub max_payload_bytes: u32,
    /// Whether it reads the cast's seed.
    pub seed: bool,
    /// The most it will reserve for any one invocation.
    pub invoke_pixie_max: u64,
    /// The mind it asks for, when it asks for one.
    pub intent: Option<Intent>,
    /// The most it will charge for any one developer-priced call — the
    /// ceiling a caller can be quoted before running anything.
    pub price_max: u64,
    /// The author's fee for a cast, in pixie.
    pub fee: u64,
}

/// One credential an artifact needs, and who is expected to supply it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecretNeed {
    /// The `{{secret.NAME}}` the code writes.
    pub name: String,
    /// The only destination it may be spent against.
    pub host: String,
    /// Whose credential it is.
    pub owner: Owner,
}

/// Who supplies a secret. A bounded vocabulary, like every other one that
/// crosses a boundary: an unknown word is refused rather than guessed at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Owner {
    /// The action's author ships it; callers never see it.
    Developer,
    /// Whoever installed the action supplies their own.
    Installer,
    /// The team the caller belongs to supplies it.
    Team,
}

/// What the guest sends to `circlet.delegate`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DelegateRequest {
    /// The agent to ask; must be in the grant's agent allowlist.
    pub agent: String,
    /// The prompt to hand over.
    pub prompt: String,
    /// The mind to ask for — passed to the host verbatim; the host resolves
    /// it. `None` leaves the choice entirely to the host.
    #[serde(default)]
    pub intent: Option<Intent>,
}

/// What the guest sends to `circlet.llm_open`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LlmRequest {
    /// The user-turn prompt.
    pub prompt: String,
    /// Optional system prompt.
    #[serde(default)]
    pub system: Option<String>,
    /// Advisory output ceiling the embedder maps to its provider's parameter.
    #[serde(default)]
    pub max_output_bytes: Option<usize>,
    /// The mind to ask for — passed to the host verbatim; the host resolves
    /// it. `None` leaves the choice entirely to the host.
    #[serde(default)]
    pub intent: Option<Intent>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pack_roundtrip() {
        assert_eq!(unpack(pack(0xDEAD, 0xBEEF)), (0xDEAD, 0xBEEF));
        assert_eq!(unpack(pack(u32::MAX, u32::MAX)), (u32::MAX, u32::MAX));
    }

    /// The encoded bytes ARE the contract. A field added, reordered, or
    /// retyped is a breaking change for every compiled guest in the world;
    /// postcard writes fields positionally and carries no names, so nothing
    /// but a pinned vector can make that change announce itself.
    #[test]
    fn the_encoded_bytes_are_the_contract() {
        let req = FetchRequest {
            method: "GET".into(),
            url: "https://h.io/x".into(),
            headers: vec![("a".into(), "b".into())],
            body: vec![1, 2],
            price_max: None,
        };
        assert_eq!(
            encode(&req).unwrap(),
            vec![
                3, b'G', b'E', b'T', // method: len 3, "GET"
                14, b'h', b't', b't', b'p', b's', b':', b'/', b'/', b'h', b'.', b'i', b'o', b'/',
                b'x', // url: len 14
                1, 1, b'a', 1, b'b', // headers: 1 pair, "a" -> "b"
                2, 1, 2, // body: len 2, bytes 1 2 — bytes, not decimals
                0, // price_max: None
            ]
        );
        // Some(_) is one more byte of tag plus a varint, and the ONLY
        // difference: an optional field never disappears from the wire,
        // because postcard reads fields by position.
        let priced = FetchRequest {
            price_max: Some(40_000),
            ..req.clone()
        };
        let bytes = encode(&priced).unwrap();
        assert_eq!(
            &bytes[..bytes.len() - 4],
            &encode(&req).unwrap()[..bytes.len() - 4]
        );
        assert_eq!(
            &bytes[bytes.len() - 4..],
            &[1, 192, 184, 2],
            "Some(40000): tag, then a base-128 varint"
        );
        assert_eq!(decode::<FetchRequest>(&bytes).unwrap(), priced);

        assert_eq!(encode(&Price { actual: 7 }).unwrap(), vec![7]);
        assert_eq!(
            encode(&InvokeRequest {
                action: "web3/get-block".into(),
                input: vec![7, 8],
                pixie_max: 40_000,
            })
            .unwrap(),
            vec![
                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',
                b'k', // action: len 14
                2, 7, 8, // input: len 2, bytes — an action id carries no shape
                192, 184, 2, // pixie_max: a base-128 varint, not an Option
            ]
        );
        assert_eq!(
            encode(&InvokeResponse {
                output: vec![9],
                pixie: 100,
            })
            .unwrap(),
            vec![1, 9, 100]
        );
        assert_eq!(
            encode(&GuestError::new("not_found", "missing")).unwrap(),
            vec![
                9, b'n', b'o', b't', b'_', b'f', b'o', b'u', b'n', b'd', // code
                7, b'm', b'i', b's', b's', b'i', b'n', b'g', // message
                0, // detail: None
                0, // retry_after_ms: None
            ]
        );
        assert_eq!(
            encode(&InvokeResult::Ok(vec![9, 10])).unwrap(),
            vec![0, 2, 9, 10],
            "Ok variant tag 0, then byte length and bytes"
        );
        assert_eq!(
            encode(&InvokeResult::Err(
                InvokeError::new("busy", "slow down")
                    .with_detail(b"{}".to_vec())
                    .with_retry_after_ms(500)
            ))
            .unwrap(),
            vec![
                1, // Err variant tag
                4, b'b', b'u', b's', b'y', // code
                9, b's', b'l', b'o', b'w', b' ', b'd', b'o', b'w', b'n', // message
                1, 2, b'{', b'}', // detail: Some(b"{}")
                1, 244, 3, // retry_after_ms: Some(500)
            ]
        );
        assert_eq!(
            encode(&Seed {
                now_unix_ms: 1_756_252_800_000,
                seed: 42,
            })
            .unwrap(),
            vec![128, 136, 204, 198, 142, 51, 42]
        );
        assert_eq!(
            encode(&FetchResponse {
                status: 200,
                headers: vec![],
                body: vec![9],
                pixie: None,
            })
            .unwrap(),
            vec![200, 1, 0, 1, 9, 0]
        );
        // The requirements section: an artifact describing itself.
        assert_eq!(
            encode(&Requirements {
                hosts: vec!["api.exa.ai".into()],
                secrets: vec![SecretNeed {
                    name: "K".into(),
                    host: "api.exa.ai".into(),
                    owner: Owner::Developer,
                }],
                max_fetches: 2,
                price_max: 40_000,
                fee: 25_000,
                ..Requirements::default()
            })
            .unwrap(),
            vec![
                1, 10, b'a', b'p', b'i', b'.', b'e', b'x', b'a', b'.', b'a', b'i', // 1 host
                1,    // 1 secret:
                1, b'K', // its name,
                10, b'a', b'p', b'i', b'.', b'e', b'x', b'a', b'.', b'a', b'i', // its host,
                0,    // and its owner: developer, an index like every enum here
                0, 0, // agents, invocable: none
                2, // max_fetches
                0, 0, 0, 0, 0, // delegations, llm, invocations, log bytes, payload
                0, // seed: false
                0, // invoke_pixie_max
                0, // intent: None
                192, 184, 2, // price_max 40000, a base-128 varint
                168, 195, 1, // fee 25000
            ]
        );
        assert_eq!(
            encode(&Intent {
                tier: Tier::Best,
                effort: Effort::High,
            })
            .unwrap(),
            vec![2, 2],
            "a bounded vocabulary is an index on the wire, in declaration order"
        );
    }

    /// Every envelope, both directions, including the corners that a
    /// positional codec gets wrong: `None` beside `Some`, empty vectors,
    /// and non-ASCII text.
    #[test]
    fn every_envelope_round_trips() {
        fn round_trip<T>(value: T)
        where
            T: serde::Serialize + for<'a> serde::Deserialize<'a> + PartialEq + core::fmt::Debug,
        {
            let bytes = encode(&value).unwrap();
            assert_eq!(decode::<T>(&bytes).unwrap(), value);
            // A truncated envelope is refused, never half-read.
            if !bytes.is_empty() {
                assert!(decode::<T>(&bytes[..bytes.len() - 1]).is_err());
            }
        }

        for price_max in [None, Some(0), Some(u64::MAX)] {
            round_trip(FetchRequest {
                method: "POST".into(),
                url: "https://h.io/π?x=1".into(),
                headers: vec![("k".into(), "v".into()), ("k2".into(), String::new())],
                body: vec![0, 255, 128],
                price_max,
            });
        }
        for pixie in [None, Some(1_u64)] {
            round_trip(FetchResponse {
                status: 404,
                headers: vec![],
                body: Vec::new(),
                pixie,
            });
            round_trip(LlmChunk {
                text: "hi π".into(),
                pixie,
            });
            round_trip(Delegation {
                text: String::new(),
                pixie,
                served_by: Some("claude-code".into()),
            });
        }
        for intent in [
            None,
            Some(Intent {
                tier: Tier::Fast,
                effort: Effort::Low,
            }),
            Some(Intent {
                tier: Tier::Balanced,
                effort: Effort::Medium,
            }),
        ] {
            round_trip(DelegateRequest {
                agent: "claude".into(),
                prompt: "p".into(),
                intent,
            });
            round_trip(LlmRequest {
                prompt: "p".into(),
                system: Some("s".into()),
                max_output_bytes: Some(4096),
                intent,
            });
        }
        round_trip(LlmRequest {
            prompt: String::new(),
            system: None,
            max_output_bytes: None,
            intent: None,
        });
        round_trip(Price { actual: 7 });
        round_trip(Requirements::default());
        round_trip(Requirements {
            hosts: vec!["a".into(), "b:8443".into()],
            secrets: vec![
                SecretNeed {
                    name: "A".into(),
                    host: "a".into(),
                    owner: Owner::Installer,
                },
                SecretNeed {
                    name: "B".into(),
                    host: "b".into(),
                    owner: Owner::Team,
                },
            ],
            agents: vec!["claude".into()],
            invocable: vec!["pack/sub".into()],
            max_fetches: u32::MAX,
            max_delegations: 1,
            max_llm_calls: 2,
            max_invocations: 3,
            max_log_bytes: 4,
            max_payload_bytes: 5,
            seed: true,
            invoke_pixie_max: u64::MAX,
            intent: Some(Intent {
                tier: Tier::Best,
                effort: Effort::High,
            }),
            price_max: 6,
            fee: 7,
        });
        for pixie_max in [0, u64::MAX] {
            round_trip(InvokeRequest {
                action: String::new(),
                input: Vec::new(),
                pixie_max,
            });
            round_trip(InvokeRequest {
                action: "pack/action π".into(),
                input: vec![0, 255],
                pixie_max,
            });
        }
        round_trip(InvokeResponse {
            output: Vec::new(),
            pixie: 0,
        });
        round_trip(InvokeResponse {
            output: vec![1, 2, 3],
            pixie: u64::MAX,
        });
        round_trip(GuestError::new("", ""));
        round_trip(
            GuestError::new("conflict", "already moved π")
                .with_detail(vec![0, 123, 255])
                .with_retry_after_ms(u64::MAX),
        );
        round_trip(InvokeResult::Ok(Vec::new()));
        round_trip(InvokeResult::Ok(vec![1, 2, 3]));
        round_trip(InvokeResult::Err(GuestError::new("invalid", "bad")));
        round_trip(Seed {
            now_unix_ms: 0,
            seed: u64::MAX,
        });
    }

    /// Intent also rides RECEIPTS and TRANSCRIPTS, which are documents and
    /// stay JSON. There the spelling is the contract, and it is lowercase.
    #[test]
    fn the_intent_vocabulary_reads_the_same_in_a_document() {
        let intent = Intent {
            tier: Tier::Best,
            effort: Effort::High,
        };
        assert_eq!(
            serde_json::to_value(intent).unwrap(),
            serde_json::json!({ "tier": "best", "effort": "high" })
        );
        let parsed: Intent = serde_json::from_str(r#"{"tier":"fast","effort":"low"}"#).unwrap();
        assert_eq!(parsed.tier, Tier::Fast);
        assert_eq!(parsed.effort, Effort::Low);
        // A closed set: an unknown word is refused at the boundary, never
        // passed through to somebody's mapping table.
        assert!(serde_json::from_str::<Intent>(r#"{"tier":"gpt-5","effort":"low"}"#).is_err());
        assert!(serde_json::from_str::<Intent>(r#"{"tier":"fast","effort":"max"}"#).is_err());

        // Transcripts recorded before a field existed still parse.
        let minimal: DelegateRequest =
            serde_json::from_str(r#"{"agent":"claude","prompt":"p"}"#).unwrap();
        assert!(minimal.intent.is_none());
        let minimal: LlmRequest = serde_json::from_str(r#"{"prompt":"p"}"#).unwrap();
        assert!(minimal.system.is_none() && minimal.max_output_bytes.is_none());
    }
}