use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct SessionId(pub Uuid);
impl SessionId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
}
impl Default for SessionId {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Epoch(pub u64);
impl Epoch {
pub const GENESIS: Epoch = Epoch(0);
pub fn next(self) -> Epoch {
Epoch(self.0 + 1)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaseRecord {
pub session: SessionId,
pub epoch: Epoch,
pub holder: String,
pub ttl_ms: u64,
pub last_heartbeat: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Drain {
pub session: SessionId,
pub epoch: Epoch,
pub claim: LeaseRecord,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InputRow {
pub id: Uuid,
pub session: SessionId,
pub payload: serde_json::Value,
pub admitted_at: u64,
pub eligible_at: u64,
pub idempotency_key: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct SlotName(pub String);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelDialect {
#[serde(rename = "openai_chat")]
OpenAiChat,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningEffort {
Low,
High,
Max,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelProfile {
pub dialect: ModelDialect,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_window: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output: Option<u64>,
#[serde(default)]
pub reasoning: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thinking: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effort: Option<ReasoningEffort>,
#[serde(default)]
pub strict: bool,
#[serde(default = "default_cache")]
pub cache: bool,
#[serde(default)]
pub vision: bool,
}
fn default_cache() -> bool {
true
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlotTarget {
pub provider: String,
pub model: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<ModelProfile>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlotSpec {
pub provider: String,
pub model: String,
pub fallback: Vec<SlotTarget>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<ModelProfile>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Budgets {
pub tokens: Option<u64>,
pub wall_clock_ms: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Permission {
Allow,
Deny,
Ask,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentDef {
pub id: String,
pub version: u64,
pub model_slots: BTreeMap<SlotName, SlotSpec>,
pub tools: Vec<String>,
pub budgets: Budgets,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvSpec {
pub sandbox: String,
pub network_allowlist: Vec<String>,
pub deps: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Thread {
pub id: Uuid,
pub parent_session: SessionId,
pub pinned_version: u64,
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use serde_json::json;
use uuid::Uuid;
use super::{
AgentDef, Budgets, Drain, EnvSpec, Epoch, InputRow, LeaseRecord, Permission, SessionId,
SlotName, SlotSpec, SlotTarget, Thread,
};
#[test]
fn permission_is_a_closed_vocabulary_fail_closed() {
assert_eq!(
serde_json::to_value(Permission::Allow).unwrap(),
json!("allow")
);
assert_eq!(
serde_json::to_value(Permission::Deny).unwrap(),
json!("deny")
);
assert_eq!(serde_json::to_value(Permission::Ask).unwrap(), json!("ask"));
let allow: Permission = serde_json::from_value(json!("allow")).unwrap();
let deny: Permission = serde_json::from_value(json!("deny")).unwrap();
let ask: Permission = serde_json::from_value(json!("ask")).unwrap();
assert_eq!(allow, Permission::Allow);
assert_eq!(deny, Permission::Deny);
assert_eq!(ask, Permission::Ask);
for unknown in ["Allow", "ALLOW", "maybe", "", "ask_user"] {
assert!(
serde_json::from_value::<Permission>(json!(unknown)).is_err(),
"`{unknown}` must refuse to parse (closed vocabulary, fail-closed)"
);
}
}
#[test]
fn session_id_and_epoch_are_serde_transparent() {
let sid = SessionId(Uuid::nil());
assert_eq!(
serde_json::to_value(sid).unwrap(),
json!("00000000-0000-0000-0000-000000000000")
);
let back: SessionId =
serde_json::from_value(json!("00000000-0000-0000-0000-000000000000")).unwrap();
assert_eq!(back, sid);
assert_eq!(serde_json::to_value(Epoch(9)).unwrap(), json!(9));
}
#[test]
fn input_row_round_trips_and_idempotency_key_is_optional() {
let row = InputRow {
id: Uuid::nil(),
session: SessionId(Uuid::nil()),
payload: json!({"text": "hello"}),
admitted_at: 100,
eligible_at: 150,
idempotency_key: Some("key-1".into()),
};
let back: InputRow = serde_json::from_value(serde_json::to_value(&row).unwrap()).unwrap();
assert_eq!(back, row);
let row_no_key = InputRow {
idempotency_key: None,
..row
};
let back: InputRow =
serde_json::from_value(serde_json::to_value(&row_no_key).unwrap()).unwrap();
assert_eq!(back, row_no_key);
}
#[test]
fn agent_def_round_trips_with_slots_and_budgets() {
let def = AgentDef {
id: "researcher".into(),
version: 3,
model_slots: BTreeMap::from([(
SlotName("main".into()),
SlotSpec {
provider: "openai-compat".into(),
model: "kimi-k2".into(),
fallback: vec![SlotTarget {
provider: "openai-compat".into(),
model: "deepseek-v3".into(),
profile: None,
}],
profile: None,
},
)]),
tools: vec!["fs.read".into(), "fs.write".into()],
budgets: Budgets {
tokens: Some(1_000_000),
wall_clock_ms: Some(3_600_000),
},
};
let back: AgentDef = serde_json::from_value(serde_json::to_value(&def).unwrap()).unwrap();
assert_eq!(back, def);
}
#[test]
fn env_spec_thread_drain_lease_round_trip() {
let env = EnvSpec {
sandbox: "none".into(),
network_allowlist: vec!["api.example.com".into()],
deps: vec!["ripgrep".into()],
};
let thread = Thread {
id: Uuid::nil(),
parent_session: SessionId(Uuid::nil()),
pinned_version: 2,
};
let lease = LeaseRecord {
session: SessionId(Uuid::nil()),
epoch: Epoch(5),
holder: "kiand-1".into(),
ttl_ms: 30_000,
last_heartbeat: 1_761_900_000_000,
};
let drain = Drain {
session: lease.session,
epoch: Epoch(5),
claim: lease.clone(),
};
for (name, ser) in [
("env", serde_json::to_value(&env).unwrap()),
("thread", serde_json::to_value(&thread).unwrap()),
("lease", serde_json::to_value(&lease).unwrap()),
("drain", serde_json::to_value(&drain).unwrap()),
] {
match name {
"env" => assert_eq!(serde_json::from_value::<EnvSpec>(ser).unwrap(), env),
"thread" => assert_eq!(serde_json::from_value::<Thread>(ser).unwrap(), thread),
"lease" => assert_eq!(serde_json::from_value::<LeaseRecord>(ser).unwrap(), lease),
_ => assert_eq!(serde_json::from_value::<Drain>(ser).unwrap(), drain),
}
}
}
}