#![warn(missing_docs)]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
pub const ABI_VERSION: u32 = 2;
pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, &'static str> {
postcard::to_allocvec(value).map_err(|_| "envelope does not encode")
}
pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T, &'static str> {
postcard::from_bytes(bytes).map_err(|_| "malformed envelope")
}
pub fn pack(ptr: u32, len: u32) -> i64 {
(((ptr as u64) << 32) | len as u64) as i64
}
pub fn unpack(v: i64) -> (u32, u32) {
((v as u64 >> 32) as u32, (v as u64 & 0xffff_ffff) as u32)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FetchRequest {
pub method: String,
pub url: String,
#[serde(default)]
pub headers: Vec<(String, String)>,
#[serde(default)]
pub body: Vec<u8>,
#[serde(default)]
pub price_max: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Price {
pub actual: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct FetchResponse {
pub status: u16,
#[serde(default)]
pub headers: Vec<(String, String)>,
#[serde(default)]
pub body: Vec<u8>,
#[serde(default)]
pub pixie: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LlmChunk {
pub text: String,
#[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,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Delegation {
pub text: String,
#[serde(default)]
pub pixie: Option<u64>,
#[serde(default)]
pub served_by: Option<String>,
}
impl From<String> for Delegation {
fn from(text: String) -> Self {
Self {
text,
pixie: None,
served_by: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Seed {
pub now_unix_ms: u64,
pub seed: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Intent {
pub tier: Tier,
pub effort: Effort,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Tier {
Fast,
Balanced,
Best,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
Low,
Medium,
High,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InvokeRequest {
pub action: String,
pub input: Vec<u8>,
pub pixie_max: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvokeResponse {
pub output: Vec<u8>,
pub pixie: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GuestError {
pub code: String,
pub message: String,
#[serde(default)]
pub detail: Option<Vec<u8>>,
#[serde(default)]
pub retry_after_ms: Option<u64>,
}
impl GuestError {
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,
}
}
pub fn message(message: impl Into<String>) -> Self {
Self::new("failed", message)
}
#[must_use]
pub fn with_detail(mut self, detail: impl Into<Vec<u8>>) -> Self {
self.detail = Some(detail.into());
self
}
#[must_use]
pub fn with_retry_after_ms(mut self, retry_after_ms: u64) -> Self {
self.retry_after_ms = Some(retry_after_ms);
self
}
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)
}
}
pub type InvokeError = GuestError;
pub type InvokeResult = Result<Vec<u8>, InvokeError>;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum InvokeOutcome {
Output(InvokeResponse),
Error {
error: InvokeError,
pixie: u64,
},
}
impl InvokeOutcome {
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)
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Requirements {
pub hosts: Vec<String>,
pub secrets: Vec<SecretNeed>,
pub agents: Vec<String>,
pub invocable: Vec<String>,
pub max_fetches: u32,
pub max_delegations: u32,
pub max_llm_calls: u32,
pub max_invocations: u32,
pub max_log_bytes: u32,
pub max_payload_bytes: u32,
pub seed: bool,
pub invoke_pixie_max: u64,
pub intent: Option<Intent>,
pub price_max: u64,
pub fee: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecretNeed {
pub name: String,
pub host: String,
pub owner: Owner,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Owner {
Developer,
Installer,
Team,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DelegateRequest {
pub agent: String,
pub prompt: String,
#[serde(default)]
pub intent: Option<Intent>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LlmRequest {
pub prompt: String,
#[serde(default)]
pub system: Option<String>,
#[serde(default)]
pub max_output_bytes: Option<usize>,
#[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));
}
#[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', 14, b'h', b't', b't', b'p', b's', b':', b'/', b'/', b'h', b'.', b'i', b'o', b'/',
b'x', 1, 1, b'a', 1, b'b', 2, 1, 2, 0, ]
);
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', 2, 7, 8, 192, 184, 2, ]
);
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', 7, b'm', b'i', b's', b's', b'i', b'n', b'g', 0, 0, ]
);
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, 4, b'b', b'u', b's', b'y', 9, b's', b'l', b'o', b'w', b' ', b'd', b'o', b'w', b'n', 1, 2, b'{', b'}', 1, 244, 3, ]
);
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]
);
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, 1, b'K', 10, b'a', b'p', b'i', b'.', b'e', b'x', b'a', b'.', b'a', b'i', 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 192, 184, 2, 168, 195, 1, ]
);
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"
);
}
#[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);
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,
});
}
#[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);
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());
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());
}
}