Skip to main content

cuttlefish_abi/
lib.rs

1//! The contract between the cuttlefish host and its guest proc-blocks.
2//!
3//! Both sides depend on this crate precisely so that they cannot drift: a block
4//! is compiled separately from the host, often at a different time by a
5//! different person, and the only thing keeping them able to talk is that they
6//! agreed on these types.
7//!
8//! # Why a command loop, not function calls
9//!
10//! A block does not call the host. It *returns* a [`Command`] describing what it
11//! wants done, and the host — after doing it — hands back an [`Event`] and asks
12//! for the next command. Control is inverted relative to the obvious design, and
13//! not for taste:
14//!
15//! - A core-wasm guest is single-threaded and offers no execution context the
16//!   host could call back into while the guest is blocked. A "call the host and
17//!   wait" design has nowhere to deliver the answer.
18//! - Inference must run on a different thread from the wasm store, which is
19//!   `!Sync` and cannot be touched from there.
20//! - Because the host decides whether to take the next step, cancellation needs
21//!   no cooperation from the guest at all: the host simply stops stepping. A
22//!   guest cannot ignore, delay, or trap its way out of being cancelled.
23//!
24//! Everything crosses the boundary as JSON. That is slower than a packed binary
25//! layout, deliberately: the boundary stays inspectable, a mismatch produces a
26//! legible error rather than a misread integer, and the volume is low because
27//! bulk data does not cross it. Revisit only if profiling says to.
28//!
29//! # Why bulk data does not cross this boundary
30//!
31//! No command hands a block the contents of a file. A block [`Command::Open`]s a
32//! path, receives a [`Handle`] and a length, then pulls bounded windows with
33//! [`Command::Slice`].
34//!
35//! This keeps guest memory proportional to the window a block chooses rather
36//! than to the size of its input. A block written against a small file behaves
37//! identically against a huge one, and the 4 GiB ceiling of 32-bit wasm stops
38//! being something block authors must reason about — which is what lets this
39//! project stay on `wasm32` instead of paying for `wasm64`.
40
41#![forbid(unsafe_code)]
42#![warn(missing_docs)]
43
44use serde::{Deserialize, Serialize};
45
46/// A job-scoped reference to something the host holds open for a guest.
47///
48/// Job-scoping is a security property, not bookkeeping. A handle table lives and
49/// dies with a single job, so a handle from one job names nothing in another.
50/// That is why [`Command::Slice`] carries no path and needs no capability check
51/// of its own: the check happened once, at [`Command::Open`], and a handle
52/// cannot be forged into a reference to another job's data.
53pub type Handle = u32;
54
55/// The shape of a value flowing through a pipeline.
56///
57/// Deliberately small. This exists to catch the mistake that actually happens
58/// when blocks are composed — one block emitting a summary string into another
59/// expecting a list of chunks — not to be a general-purpose type system. A
60/// richer one would need inference, and inference over a language with no
61/// expressions is machinery without a use.
62/// Written and read as a compact string — `text`, `[text]`, `{path: text}` —
63/// rather than as a nested tagged object.
64///
65/// Two reasons, and the second is the one that forced it. It reads well in an
66/// error message and in a spec, so one syntax serves the wire, the diagnostics,
67/// and the DSL. And a recursive enum serialized structurally makes serde's
68/// generic serializer recurse deeply enough to blow rustc's recursion limit in
69/// the *guest* crate — which would have meant every block author adding
70/// `#![recursion_limit]` to work around a detail of this type.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum Ty {
73    /// A UTF-8 string.
74    Text,
75    /// Opaque bytes, base64-encoded on the wire.
76    Bytes,
77    /// A handle naming an image the host holds.
78    Image,
79    /// A handle naming a paged document.
80    Document,
81    /// Any JSON value. The top type: everything is assignable to it.
82    ///
83    /// An escape hatch, and one worth using sparingly — a pipeline of `Json`
84    /// seams typechecks unconditionally, which is the same as not checking.
85    Json,
86    /// An ordered sequence.
87    List(Box<Ty>),
88    /// A fixed set of named fields.
89    ///
90    /// A `BTreeMap` so that two records written in different field orders are
91    /// the same type, and so error messages list fields the same way twice.
92    Record(std::collections::BTreeMap<String, Ty>),
93}
94
95impl Ty {
96    /// Whether a value of this type can be fed where `expected` is required.
97    ///
98    /// Not equality: [`Ty::Json`] accepts anything, and a record with *extra*
99    /// fields satisfies one that needs fewer. Both directions of that matter —
100    /// a block that adds a field should not break its consumer, and a block
101    /// that requires a field its producer never emits should fail loudly.
102    pub fn assignable_to(&self, expected: &Ty) -> bool {
103        match (self, expected) {
104            (_, Ty::Json) => true,
105            (Ty::List(a), Ty::List(b)) => a.assignable_to(b),
106            (Ty::Record(have), Ty::Record(need)) => need
107                .iter()
108                .all(|(name, want)| have.get(name).is_some_and(|got| got.assignable_to(want))),
109            (a, b) => a == b,
110        }
111    }
112
113    /// Whether a live JSON value could plausibly be an instance of this
114    /// type — a runtime counterpart to [`Self::assignable_to`], which only
115    /// ever compares two declared `Ty`s against each other. Nothing in the
116    /// host checked a block's *actual* output against what it declared
117    /// until this existed: a block could claim `{summary: text}` and return
118    /// `{text: "..."}` and nothing downstream would notice until whatever
119    /// consumed `summary` got `null`.
120    ///
121    /// Deliberately permissive, not a full validator: [`Ty::Bytes`],
122    /// [`Ty::Image`], and [`Ty::Document`] have no fixed JSON shape defined
123    /// anywhere in this protocol (unlike [`Ty::Text`]/[`Ty::List`]/
124    /// [`Ty::Record`], which map onto JSON strings/arrays/objects
125    /// unambiguously) — inventing a shape for them here risks rejecting
126    /// legitimate values a real block already produces. Those three, like
127    /// [`Ty::Json`], accept anything.
128    pub fn matches_value(&self, value: &serde_json::Value) -> bool {
129        match self {
130            Ty::Json | Ty::Bytes | Ty::Image | Ty::Document => true,
131            Ty::Text => value.is_string(),
132            Ty::List(inner) => value
133                .as_array()
134                .is_some_and(|items| items.iter().all(|v| inner.matches_value(v))),
135            Ty::Record(fields) => value.as_object().is_some_and(|obj| {
136                fields
137                    .iter()
138                    .all(|(name, want)| obj.get(name).is_some_and(|v| want.matches_value(v)))
139            }),
140        }
141    }
142
143    /// A short human-readable rendering, for error messages.
144    pub fn describe(&self) -> String {
145        match self {
146            Ty::Text => "text".into(),
147            Ty::Bytes => "bytes".into(),
148            Ty::Image => "image".into(),
149            Ty::Document => "document".into(),
150            Ty::Json => "json".into(),
151            Ty::List(inner) => format!("[{}]", inner.describe()),
152            Ty::Record(fields) => {
153                let body = fields
154                    .iter()
155                    .map(|(k, v)| format!("{k}: {}", v.describe()))
156                    .collect::<Vec<_>>()
157                    .join(", ");
158                format!("{{{body}}}")
159            }
160        }
161    }
162}
163
164impl std::fmt::Display for Ty {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        f.write_str(&self.describe())
167    }
168}
169
170impl std::str::FromStr for Ty {
171    type Err = String;
172
173    fn from_str(s: &str) -> Result<Self, Self::Err> {
174        parse_ty(s.trim())
175    }
176}
177
178impl Serialize for Ty {
179    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
180        s.serialize_str(&self.describe())
181    }
182}
183
184impl<'de> Deserialize<'de> for Ty {
185    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
186        let raw = String::deserialize(d)?;
187        raw.parse().map_err(serde::de::Error::custom)
188    }
189}
190
191/// Parse the type syntax [`Ty::describe`] produces.
192fn parse_ty(s: &str) -> Result<Ty, String> {
193    let s = s.trim();
194    match s {
195        "text" => return Ok(Ty::Text),
196        "bytes" => return Ok(Ty::Bytes),
197        "image" => return Ok(Ty::Image),
198        "document" => return Ok(Ty::Document),
199        "json" => return Ok(Ty::Json),
200        _ => {}
201    }
202
203    if let Some(inner) = s.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
204        return Ok(Ty::List(Box::new(parse_ty(inner)?)));
205    }
206
207    if let Some(body) = s.strip_prefix('{').and_then(|r| r.strip_suffix('}')) {
208        let mut fields = std::collections::BTreeMap::new();
209        if !body.trim().is_empty() {
210            for part in split_fields(body) {
211                let (name, ty) = part
212                    .split_once(':')
213                    .ok_or_else(|| format!("expected `name: type` in `{part}`"))?;
214                fields.insert(name.trim().to_string(), parse_ty(ty)?);
215            }
216        }
217        return Ok(Ty::Record(fields));
218    }
219
220    Err(format!("`{s}` is not a type"))
221}
222
223/// Split record fields on commas that are not inside a nested `[]` or `{}`.
224///
225/// A plain `split(',')` would cut `{a: [x, y]}` in the wrong place.
226fn split_fields(body: &str) -> Vec<String> {
227    let (mut out, mut depth, mut current) = (Vec::new(), 0i32, String::new());
228    for c in body.chars() {
229        match c {
230            '[' | '{' => {
231                depth += 1;
232                current.push(c);
233            }
234            ']' | '}' => {
235                depth -= 1;
236                current.push(c);
237            }
238            ',' if depth == 0 => out.push(std::mem::take(&mut current)),
239            _ => current.push(c),
240        }
241    }
242    if !current.trim().is_empty() {
243        out.push(current);
244    }
245    out
246}
247
248/// What a block accepts and produces.
249///
250/// Declared by the block itself, through a `cf_signature` export, rather than in
251/// a sidecar file beside it. A sidecar can disagree with the code it describes
252/// and nothing forces anyone to notice; a declaration compiled into the module
253/// travels with it, cannot go stale, and leaves one artifact to ship rather than
254/// two to keep in step.
255///
256/// `Display`/`FromStr` render and parse it as `"{input} -> {output}"` —
257/// each side is a [`Ty`], and this is the compact form the catalog caches
258/// and a bundle manifest embeds. Splitting on `" -> "` is unambiguous only
259/// because `Ty::describe()` never produces that substring itself.
260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
261pub struct Signature {
262    /// What the block needs as input.
263    pub input: Ty,
264    /// What it produces.
265    pub output: Ty,
266}
267
268impl std::fmt::Display for Signature {
269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270        write!(f, "{} -> {}", self.input, self.output)
271    }
272}
273
274impl std::str::FromStr for Signature {
275    type Err = String;
276
277    fn from_str(s: &str) -> Result<Self, Self::Err> {
278        let (input, output) = s
279            .split_once(" -> ")
280            .ok_or_else(|| format!("`{s}` is not a signature (expected `input -> output`)"))?;
281        Ok(Signature {
282            input: input.parse()?,
283            output: output.parse()?,
284        })
285    }
286}
287
288/// What kind of thing a handle refers to, reported by [`Event::Opened`].
289///
290/// A block needs this to know which commands are worth issuing: [`Command::Slice`]
291/// on a PNG is a mistake, and [`Command::PageText`] on a plain text file is
292/// meaningless. Reporting it up front means a block can branch on what it
293/// actually got rather than guessing from a file extension.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295#[serde(tag = "kind", rename_all = "snake_case")]
296pub enum MediaKind {
297    /// Valid UTF-8. Both [`Command::Slice`] and [`Command::SliceBytes`] work.
298    Text,
299    /// An image the host recognised. Usable as an [`Command::Infer`] image.
300    Image {
301        /// Format as detected from content, e.g. `png`, `jpeg`.
302        format: String,
303    },
304    /// A paged document — a PDF, say.
305    Document {
306        /// How many pages it has.
307        pages: u32,
308        /// Whether it carries an extractable text layer.
309        ///
310        /// False for a scanned document, where the only way to read it is to
311        /// rasterize pages and hand them to a vision model. A block that checks
312        /// this can pick the cheap path when it exists and the expensive one
313        /// when it must, instead of silently extracting nothing.
314        has_text_layer: bool,
315    },
316    /// Bytes the host could not classify. Only [`Command::SliceBytes`] applies.
317    Binary,
318}
319
320/// One transformation [`Command::ImageOp`] can apply.
321///
322/// Deliberately a closed set rather than a general filter language: each of
323/// these answers a question an analysis pipeline actually asks, and a closed
324/// set is one a host can implement completely and a block can rely on.
325#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
326#[serde(tag = "op", rename_all = "snake_case")]
327pub enum ImageOperation {
328    /// Scale to fit within these bounds, preserving aspect ratio.
329    ///
330    /// The common case before handing an image to a vision model, which
331    /// resamples to a fixed size anyway — sending a 48-megapixel original
332    /// costs encode time and tokens for detail the model cannot use.
333    Resize {
334        /// Maximum width in pixels.
335        max_width: u32,
336        /// Maximum height in pixels.
337        max_height: u32,
338    },
339    /// Cut out a region, for asking about part of an image rather than all
340    /// of it.
341    Crop {
342        /// Left edge, in pixels from the origin.
343        x: u32,
344        /// Top edge, in pixels from the origin.
345        y: u32,
346        /// Region width.
347        width: u32,
348        /// Region height.
349        height: u32,
350    },
351}
352
353/// What a guest asks the host to do, returned from its `init`/`step` exports.
354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
355#[serde(tag = "cmd", rename_all = "snake_case")]
356pub enum Command {
357    /// Run a prompt against the job's model.
358    Infer {
359        /// The prompt to generate from.
360        prompt: String,
361        /// Upper bound on tokens generated. A guest can also end generation
362        /// early by returning [`TokenAction::Stop`] from its `on_token` export.
363        max_tokens: u32,
364        /// Images to accompany the prompt, named by handle.
365        ///
366        /// Handles rather than bytes, for the same reason file contents are not
367        /// handed over: an image can be tens of megabytes, and routing it
368        /// through guest memory would put the 4 GiB wasm32 ceiling back in play
369        /// for no benefit. The host already holds the bytes; it can pass them to
370        /// the model directly.
371        ///
372        /// Requires a model with vision capability. Empty for ordinary
373        /// text-only inference, which is why it is `#[serde(default)]` — a block
374        /// compiled before this field existed still deserializes.
375        #[serde(default)]
376        images: Vec<Handle>,
377    },
378    /// Open a file. Capability-checked against the job's spec.
379    ///
380    /// Yields a handle and a length rather than contents — see the crate docs on
381    /// why bulk data does not cross this boundary.
382    Open {
383        /// Path to open. Denied unless the spec grants read access to it.
384        path: String,
385    },
386    /// Pull one bounded window of an open file into guest memory.
387    ///
388    /// The guest picks `len`, so the guest sets its own memory ceiling.
389    Slice {
390        /// Handle from a previous [`Command::Open`].
391        handle: Handle,
392        /// Byte offset to read from. `u64` so that files far larger than a guest
393        /// could hold remain fully addressable.
394        offset: u64,
395        /// Maximum bytes to return. The host may return fewer; see
396        /// [`Event::Sliced`].
397        len: u64,
398    },
399    /// Pull one bounded window of an open file as raw bytes.
400    ///
401    /// The binary counterpart to [`Command::Slice`]. Prefer `Slice` for text:
402    /// it needs no encoding, and it handles the character-boundary problem for
403    /// you. This exists for blocks that genuinely need bytes — inspecting an
404    /// image header, say — and pays base64's cost to carry them.
405    SliceBytes {
406        /// Handle from a previous [`Command::Open`].
407        handle: Handle,
408        /// Byte offset to read from.
409        offset: u64,
410        /// Maximum bytes to return.
411        len: u64,
412    },
413    /// Extract one page of a document as text.
414    ///
415    /// Fails when the document has no text layer; check
416    /// [`MediaKind::Document::has_text_layer`] first.
417    PageText {
418        /// Handle from a previous [`Command::Open`].
419        handle: Handle,
420        /// Zero-based page number.
421        page: u32,
422    },
423    /// Render one page of a document to an image.
424    ///
425    /// Yields a *new* handle referring to the rendered image, which can then be
426    /// named in [`Command::Infer`]. That indirection is deliberate: the image
427    /// stays host-side like every other bulk value, and a rendered page is
428    /// usable exactly wherever a file-backed image is.
429    PageImage {
430        /// Handle from a previous [`Command::Open`].
431        handle: Handle,
432        /// Zero-based page number.
433        page: u32,
434    },
435    /// Embed one or more texts, returning a vector each.
436    ///
437    /// Batched by construction: the guest hands over every text it wants
438    /// embedded in one command. Embedding a corpus means tens of thousands
439    /// of chunks, and a round trip per chunk is the difference between
440    /// minutes and hours — so the batch is the primitive and a single text
441    /// is just a batch of one.
442    ///
443    /// Served by the spec's `embedding_model`, which is deliberately not the
444    /// job's chat model: they are different models, and asking a chat model
445    /// to embed either fails or returns something that is not an embedding.
446    Embed {
447        /// The texts to embed, in order. Vectors come back in the same order.
448        texts: Vec<String>,
449    },
450    /// Download a URL and hand back a handle to it.
451    ///
452    /// Answers with [`Event::Opened`], the same event [`Command::Open`]
453    /// produces, so everything downstream is unchanged: a fetched resource
454    /// can be sliced, identified, extracted from, or handed to a vision
455    /// model exactly as a local file can. One new command, no new surface.
456    ///
457    /// Requires a matching `Fetch` prefix in the spec's `capabilities`. A
458    /// corpus on the web is still a corpus, and the capability list has to
459    /// describe reaching it.
460    Fetch {
461        /// The URL to retrieve. Must begin with a granted prefix.
462        url: String,
463    },
464    /// Every character of text in a document, in one call.
465    ///
466    /// What most callers reading a PDF actually want, and the direct way to
467    /// ask for it. Before this existed the only route was
468    /// [`Command::PageText`] with `page: 0`, which reads like "the first
469    /// page" and quietly means "everything" whenever the extractor emitted
470    /// no page breaks — a gap that cost a real user two iterations and
471    /// nearly a wrong conclusion about whether cuttlefish could read their
472    /// corpus at all.
473    ///
474    /// Prefer this over walking pages unless the pages are genuinely needed
475    /// separately: the whole document is one extraction either way.
476    DocumentText {
477        /// Handle from a previous [`Command::Open`].
478        handle: Handle,
479    },
480    /// Transform an image handle, yielding a *new* image handle.
481    ///
482    /// Same indirection as [`Command::PageImage`], and for the same reason:
483    /// pixels stay host-side, and the result is usable exactly wherever a
484    /// file-backed image is — including as an [`Command::Infer`] image.
485    ///
486    /// This is the one image operation that needs a decoder, which is why it
487    /// lives here rather than in the guest. Metadata (dimensions, EXIF,
488    /// chunk structure) is header parsing and is available to any script
489    /// without a host round trip or a feature flag; *looking at the pixels*
490    /// is not.
491    ///
492    /// Hosts built without the `image-ops` feature reject this with a clear
493    /// message rather than pretending to succeed.
494    ImageOp {
495        /// Handle from a previous [`Command::Open`] or [`Command::PageImage`].
496        handle: Handle,
497        /// What to do to it.
498        op: ImageOperation,
499    },
500    /// Report progress to whoever is watching the job's event stream.
501    Emit {
502        /// Arbitrary JSON, forwarded verbatim to the job's subscribers.
503        progress: serde_json::Value,
504    },
505    /// Finish successfully with this payload.
506    Done {
507        /// The job's result, shaped by the spec's declared output.
508        result: serde_json::Value,
509    },
510    /// Give up. The job ends with this code and message, and no result.
511    Fail {
512        /// Machine-readable code; see [`error_codes`].
513        code: String,
514        /// Human-readable explanation.
515        message: String,
516    },
517}
518
519/// What the host feeds back into the guest's `step` export after carrying out a
520/// [`Command`].
521#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
522#[serde(tag = "event", rename_all = "snake_case")]
523pub enum Event {
524    /// Generation finished.
525    InferDone {
526        /// The generated text.
527        text: String,
528        /// How many tokens were produced. May be fewer than the requested
529        /// `max_tokens` if the guest ended generation early.
530        tokens_out: u32,
531    },
532    /// A file was opened.
533    Opened {
534        /// Use this in subsequent [`Command::Slice`] calls.
535        handle: Handle,
536        /// Total size of the file, in bytes.
537        len: u64,
538        /// What the host made of the contents; see [`MediaKind`].
539        ///
540        /// `#[serde(default)]` so a block built before this field existed still
541        /// deserializes, treating anything it opens as text.
542        #[serde(default)]
543        kind: MediaKind,
544    },
545    /// A window of a file was read.
546    Sliced {
547        /// The window's contents.
548        text: String,
549        /// Where the returned text actually ended.
550        ///
551        /// This is **not** always `offset + len` from the request: the host cuts
552        /// a window back to a UTF-8 character boundary, because a caller picking
553        /// window sizes has no idea where characters begin, and a naive split
554        /// would corrupt a multi-byte character at nearly every seam. A guest
555        /// walking a file must resume from this value rather than advancing by
556        /// the length it asked for.
557        next_offset: u64,
558    },
559    /// A window of a file was read as raw bytes.
560    SlicedBytes {
561        /// The window's contents, base64-encoded.
562        ///
563        /// Base64 rather than a binary side channel: the boundary is JSON, and
564        /// keeping it inspectable is worth more than the third it costs on a
565        /// path blocks are not expected to use in bulk.
566        bytes_base64: String,
567        /// Where the returned bytes ended. Unlike [`Event::Sliced`] there is no
568        /// truncation, so this is always `offset + len` clamped to the file.
569        next_offset: u64,
570    },
571    /// One vector per text handed to [`Command::Embed`], in the same order.
572    Embedded {
573        /// The vectors, each the model's full dimensionality.
574        vectors: Vec<Vec<f32>>,
575    },
576    /// Text extracted from a document — one page, or the whole thing.
577    ///
578    /// Shared by [`Command::PageText`] and [`Command::DocumentText`]: both
579    /// answer with text and nothing else, so a second variant carrying an
580    /// identical payload would add surface without adding information. The
581    /// *command* is what names the intent.
582    PageTexted {
583        /// The page's text.
584        text: String,
585    },
586    /// A document page was rendered to an image.
587    PageImaged {
588        /// A new handle referring to the rendered image; name it in
589        /// [`Command::Infer`].
590        handle: Handle,
591        /// Its size in bytes.
592        len: u64,
593    },
594    /// Progress was forwarded. Carries nothing; it exists so `Emit` has a reply
595    /// and the command loop keeps its shape.
596    Emitted,
597}
598
599/// A guest's verdict on each streamed token, returned from its `on_token`
600/// export.
601#[derive(Debug, Clone, Copy, PartialEq, Eq)]
602pub enum TokenAction {
603    /// Keep generating.
604    Continue,
605    /// Stop generating now.
606    ///
607    /// A token or two may still arrive after this, because the verdict has to
608    /// travel back to the thread doing the generating.
609    Stop,
610}
611
612impl TokenAction {
613    /// Decode the raw `i32` a guest's `on_token` export returns.
614    ///
615    /// Anything that is not an explicit `Continue` reads as `Stop`. A guest
616    /// returning a value this crate does not recognise is malfunctioning, and
617    /// the safe reading of a malfunctioning guest is "stop", never "keep
618    /// spending tokens" — the same fail-closed posture as the capability checks.
619    pub fn from_i32(v: i32) -> Self {
620        if v == 0 {
621            Self::Continue
622        } else {
623            Self::Stop
624        }
625    }
626
627    /// Encode for the wasm boundary.
628    ///
629    /// These integers are part of the ABI: renumbering them silently changes the
630    /// meaning of every already-compiled block.
631    pub fn as_i32(self) -> i32 {
632        match self {
633            Self::Continue => 0,
634            Self::Stop => 1,
635        }
636    }
637}
638
639/// Where a job is in its lifecycle.
640#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
641#[serde(rename_all = "snake_case")]
642pub enum JobStatus {
643    /// Accepted, not yet started.
644    Queued,
645    /// Executing.
646    Running,
647    /// Finished with a result.
648    Completed,
649    /// Finished with an error and no result.
650    Failed,
651    /// Stopped by request.
652    Cancelled,
653    /// Was running when the daemon last stopped; not resumed automatically.
654    Interrupted,
655}
656
657impl JobStatus {
658    /// Whether this status is final — nothing further will happen to the job.
659    ///
660    /// Clients poll until this is true. Adding a new non-terminal status is
661    /// therefore safe, while a new terminal one that is missing from this match
662    /// leaves callers waiting forever.
663    pub fn is_terminal(self) -> bool {
664        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
665    }
666}
667
668/// What a job cost.
669#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
670pub struct Usage {
671    /// Tokens consumed by prompts.
672    pub tokens_in: u32,
673    /// Tokens generated.
674    pub tokens_out: u32,
675    /// Wall-clock duration of the job.
676    pub duration_ms: u64,
677    /// Which model served the job's inference.
678    pub model: String,
679}
680
681/// The fixed, spec-independent envelope handed back to the calling agent.
682///
683/// Every job returns this shape regardless of what it did, so an agent can
684/// handle results without knowing anything about the block that produced them.
685/// Only `result` varies, and its shape is that job's business.
686#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
687pub struct Envelope {
688    /// Lifecycle state; see [`JobStatus::is_terminal`].
689    pub status: JobStatus,
690    /// Present only when the job completed.
691    ///
692    /// A failed or cancelled job never carries a partial result: a caller must
693    /// never have to guess whether a payload is trustworthy.
694    #[serde(skip_serializing_if = "Option::is_none")]
695    pub result: Option<serde_json::Value>,
696    /// Present only when the job failed or was cancelled.
697    #[serde(skip_serializing_if = "Option::is_none")]
698    pub error: Option<JobError>,
699    /// Cost accounting, populated even for failed jobs — work already spent
700    /// still counts.
701    pub usage: Usage,
702}
703
704/// Why a job did not complete.
705#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
706pub struct JobError {
707    /// Machine-readable; see [`error_codes`].
708    pub code: String,
709    /// Human-readable detail.
710    pub message: String,
711}
712
713/// The error codes the daemon emits in [`JobError::code`].
714///
715/// These are string constants rather than an enum so the set can grow without
716/// breaking clients that match on strings, and so a client built against an
717/// older version meets an unfamiliar code rather than a decode failure.
718pub mod error_codes {
719    /// The job's model could not be loaded or served.
720    pub const MODEL_LOAD_FAILED: &str = "model_load_failed";
721    /// A guest tried to reach something its spec does not grant.
722    pub const CAPABILITY_DENIED: &str = "capability_denied";
723    /// Job input did not match the spec's declared shape.
724    pub const SCHEMA_VALIDATION_FAILED: &str = "schema_validation_failed";
725    /// A Script-kind block's own logic failed at run time — a Rhai runtime
726    /// error (e.g. an out-of-bounds index, a missing function) surfacing
727    /// from inside the script itself. `catalog add` rejects a script whose
728    /// body doesn't *parse*, so this is specifically a failure that only
729    /// shows up once the script actually runs; it is not a schema mismatch,
730    /// so it does not reuse [`SCHEMA_VALIDATION_FAILED`].
731    pub const SCRIPT_ERROR: &str = "script_error";
732    /// The guest trapped — a panic, a bad export signature, or malformed wasm.
733    pub const WASM_TRAP: &str = "wasm_trap";
734    /// The job exceeded its time budget.
735    pub const TIMEOUT: &str = "timeout";
736    /// The job was cancelled by request.
737    pub const CANCELLED: &str = "cancelled";
738    /// A command needed a capability this build does not have — asking for a
739    /// page image without document rendering compiled in, say.
740    pub const UNSUPPORTED: &str = "unsupported";
741}
742
743impl Default for MediaKind {
744    /// Text, because that is what every command predating [`MediaKind`]
745    /// assumed, and because it keeps an older block's behaviour unchanged.
746    fn default() -> Self {
747        Self::Text
748    }
749}
750
751#[cfg(test)]
752mod tests {
753    use super::*;
754
755    #[test]
756    fn a_signature_round_trips_through_its_compact_string() {
757        let sig = Signature {
758            input: Ty::Record([("path".to_string(), Ty::Text)].into_iter().collect()),
759            output: Ty::List(Box::new(Ty::Text)),
760        };
761        let s = sig.to_string();
762        assert_eq!(s, "{path: text} -> [text]");
763        assert_eq!(s.parse::<Signature>().unwrap(), sig);
764    }
765
766    #[test]
767    fn a_signature_without_an_arrow_is_rejected() {
768        assert!("just-a-type".parse::<Signature>().is_err());
769    }
770
771    #[test]
772    fn a_signature_with_an_unparseable_side_is_rejected() {
773        assert!("text -> not a type".parse::<Signature>().is_err());
774    }
775
776    #[test]
777    fn text_matches_a_json_string_only() {
778        assert!(Ty::Text.matches_value(&serde_json::json!("hello")));
779        assert!(!Ty::Text.matches_value(&serde_json::json!(42)));
780    }
781
782    #[test]
783    fn json_matches_anything() {
784        assert!(Ty::Json.matches_value(&serde_json::json!(null)));
785        assert!(Ty::Json.matches_value(&serde_json::json!([1, "two", {}])));
786    }
787
788    #[test]
789    fn a_record_missing_a_declared_field_does_not_match() {
790        let ty = Ty::Record([("summary".to_string(), Ty::Text)].into_iter().collect());
791        assert!(!ty.matches_value(&serde_json::json!({"text": "hello world"})));
792    }
793
794    #[test]
795    fn a_record_with_the_declared_field_present_and_well_typed_matches() {
796        let ty = Ty::Record([("summary".to_string(), Ty::Text)].into_iter().collect());
797        assert!(ty.matches_value(&serde_json::json!({"summary": "hi", "extra": 1})));
798    }
799
800    #[test]
801    fn a_record_with_a_wrong_typed_declared_field_does_not_match() {
802        let ty = Ty::Record([("summary".to_string(), Ty::Text)].into_iter().collect());
803        assert!(!ty.matches_value(&serde_json::json!({"summary": 42})));
804    }
805
806    #[test]
807    fn a_list_matches_only_when_every_element_matches_the_inner_type() {
808        let ty = Ty::List(Box::new(Ty::Text));
809        assert!(ty.matches_value(&serde_json::json!(["a", "b"])));
810        assert!(!ty.matches_value(&serde_json::json!(["a", 2])));
811        assert!(!ty.matches_value(&serde_json::json!("not a list")));
812    }
813
814    #[test]
815    fn bytes_image_and_document_accept_anything() {
816        for ty in [Ty::Bytes, Ty::Image, Ty::Document] {
817            assert!(ty.matches_value(&serde_json::json!(123)));
818        }
819    }
820}