use std::collections::BTreeMap;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::model::SlotName;
use crate::secrets::Redaction;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModelRequest {
pub slot: SlotName,
pub body: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModelChunk {
pub delta: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<Value>,
}
impl ModelChunk {
#[must_use]
pub fn new(delta: Value) -> Self {
Self { delta, usage: None }
}
#[must_use]
pub fn with_usage(delta: Value, usage: Value) -> Self {
Self {
delta,
usage: Some(usage),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
pub enum ProviderError {
#[error("rate limited")]
RateLimited,
#[error("context overflow")]
ContextOverflow,
#[error("provider unavailable: {0}")]
Unavailable(String),
#[error("transport error: {0}")]
Transport(String),
#[error("empty response")]
EmptyResponse,
#[error("request too large: {detail}")]
RequestTooLarge {
size: usize,
limit: Option<u64>,
detail: String,
},
#[error("invalid response: {0}")]
InvalidResponse(String),
#[error("{0}")]
Other(String),
}
pub trait ModelProvider: Send + Sync {
fn complete(&self, req: ModelRequest) -> BoxStream<'static, Result<ModelChunk, ProviderError>>;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSchema {
pub name: String,
pub description: String,
pub parameters: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
pub id: String,
pub name: String,
pub arguments: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolResult {
pub call_id: String,
pub output: Value,
pub is_error: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub redactions: Vec<Redaction>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ToolError {
#[error("invalid tool call: {0}")]
InvalidCall(String),
#[error("tool execution failed: {0}")]
Execution(String),
#[error("tool timed out")]
Timeout,
}
pub trait ToolProvider: Send + Sync {
fn schemas(&self) -> Vec<ToolSchema>;
fn invoke(&self, call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>>;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecCommand {
pub argv: Vec<String>,
pub env: BTreeMap<String, String>,
pub cwd: Option<String>,
pub timeout_ms: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecResult {
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
pub timed_out: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub redactions: Vec<Redaction>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ExecError {
#[error("failed to spawn: {0}")]
Spawn(String),
#[error("execution timed out")]
Timeout,
#[error("io error: {0}")]
Io(String),
}
pub trait ExecBackend: Send + Sync {
fn exec(&self, cmd: ExecCommand) -> BoxFuture<'static, Result<ExecResult, ExecError>>;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum LoopOutcome {
TurnDone,
Settled,
Stopped { reason: String },
SoftFailed { reason: String },
AwaitingBudget { budget: Value },
}
pub const EPISODE_BUDGET_STOP_REASON_PREFIX: &str = "episode iteration budget exhausted";
pub const ROTATION_STOP_REASON: &str = "resident rotation requested";
pub trait LoopDriver: Send + Sync {
type Ctx: Send;
fn drive(&self, ctx: Self::Ctx) -> BoxStream<'static, LoopOutcome>;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PolicyRule {
pub class: String,
pub action: RecoveryAction,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RecoveryAction {
BackoffRetry { delay_ms: u64 },
CompressThenRetry,
Failover,
InterruptAsk,
Fail,
}
pub trait RecoveryPolicySource: Send + Sync {
fn table(&self) -> Vec<PolicyRule>;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChannelEvent {
pub channel: String,
pub event_id: String,
pub topic: Option<String>,
#[serde(default)]
pub sender: Option<Value>,
#[serde(default)]
pub group: Option<String>,
pub payload: Value,
pub ts_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChannelDelivery {
pub channel: String,
pub target: Value,
pub content: Value,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SendReceipt {
pub message_id: String,
pub ts_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
pub enum ChannelError {
#[error("channel unavailable: {0}")]
Unavailable(String),
#[error("delivery failed: {0}")]
DeliveryFailed(String),
#[error("delivery timed out")]
Timeout,
}
pub trait ChannelAdapter: Send + Sync {
fn subscribe(&self) -> BoxStream<'static, ChannelEvent>;
fn send(&self, out: ChannelDelivery) -> BoxFuture<'static, Result<SendReceipt, ChannelError>>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EndpointHealth {
Online,
Offline,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HealthEvent {
pub endpoint_id: String,
pub status: EndpointHealth,
pub ts_ms: u64,
pub detail: Option<String>,
}
pub trait WatchdogSource: Send + Sync {
fn health(&self) -> BoxStream<'static, HealthEvent>;
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::{
ExecCommand, ExecResult, LoopOutcome, ModelChunk, ModelRequest, PolicyRule, RecoveryAction,
ToolCall, ToolResult, ToolSchema,
};
use crate::model::SlotName;
#[test]
fn seam_traits_are_object_safe() {
fn assert_object_safe(
_: &dyn super::ModelProvider,
_: &dyn super::ToolProvider,
_: &dyn super::ExecBackend,
_: &dyn super::RecoveryPolicySource,
_: &dyn super::LoopDriver<Ctx = ()>,
) {
}
let _ = assert_object_safe;
}
#[test]
fn bundle_seam_traits_are_object_safe() {
fn assert_object_safe(_: &dyn super::ChannelAdapter, _: &dyn super::WatchdogSource) {}
let _ = assert_object_safe;
}
#[test]
fn bundle_seam_support_types_round_trip() {
use super::{
ChannelDelivery, ChannelError, ChannelEvent, EndpointHealth, HealthEvent, SendReceipt,
};
let event = ChannelEvent {
channel: "mock-im".into(),
event_id: "evt-7".into(),
topic: Some("worker-1".into()),
sender: Some(json!({"id": "u-42", "name": "yifei"})),
group: Some("chat-9".into()),
payload: json!({"text": "@kian deploy"}),
ts_ms: 1_762_000_000_000,
};
let delivery = ChannelDelivery {
channel: "mock-im".into(),
target: json!({"chat_id": 42}),
content: json!({"text": "done"}),
};
let receipt = SendReceipt {
message_id: "msg-9".into(),
ts_ms: 1_762_000_000_001,
};
let health = HealthEvent {
endpoint_id: "ep-laptop".into(),
status: EndpointHealth::Offline,
ts_ms: 1_762_000_000_002,
detail: Some("heartbeat stale".into()),
};
fn rt<T>(val: &T)
where
T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
{
let ser = serde_json::to_value(val).unwrap();
let back: T = serde_json::from_value(ser).unwrap();
assert_eq!(&back, val);
}
rt(&event);
rt(&delivery);
rt(&receipt);
rt(&health);
assert_eq!(
serde_json::to_value(EndpointHealth::Online).unwrap(),
json!("online")
);
assert_eq!(
serde_json::to_value(EndpointHealth::Offline).unwrap(),
json!("offline")
);
assert_eq!(ChannelError::Timeout.to_string(), "delivery timed out");
}
#[test]
fn old_channel_event_json_parses_with_default_provenance() {
use super::ChannelEvent;
let old = json!({
"channel": "mock-im",
"event_id": "evt-legacy",
"topic": null,
"payload": {"text": "hi"},
"ts_ms": 1_762_000_000_000u64,
});
let event: ChannelEvent = serde_json::from_value(old).unwrap();
assert_eq!(event.channel, "mock-im");
assert_eq!(event.event_id, "evt-legacy");
assert_eq!(event.topic, None);
assert_eq!(event.sender, None);
assert_eq!(event.group, None);
let ser = serde_json::to_value(&event).unwrap();
assert_eq!(ser["sender"], serde_json::Value::Null);
assert_eq!(ser["group"], serde_json::Value::Null);
let back: ChannelEvent = serde_json::from_value(ser).unwrap();
assert_eq!(back, event);
}
#[test]
fn model_chunk_usage_is_additive() {
let plain = ModelChunk::new(json!({"content": "hi"}));
let ser = serde_json::to_value(&plain).unwrap();
assert_eq!(ser, json!({"delta": {"content": "hi"}}));
let legacy: ModelChunk =
serde_json::from_value(json!({"delta": {"content": "hi"}})).unwrap();
assert_eq!(legacy, plain);
assert_eq!(legacy.usage, None);
let with = ModelChunk::with_usage(serde_json::Value::Null, json!({"prompt_tokens": 3}));
let ser = serde_json::to_value(&with).unwrap();
assert_eq!(ser, json!({"delta": null, "usage": {"prompt_tokens": 3}}));
let back: ModelChunk = serde_json::from_value(ser).unwrap();
assert_eq!(back, with);
}
#[test]
fn seam_support_types_round_trip() {
let req = ModelRequest {
slot: SlotName("main".into()),
body: json!({"messages": []}),
};
let chunk = ModelChunk::new(json!({"text": "hi"}));
let schema = ToolSchema {
name: "fs.read".into(),
description: "read a file".into(),
parameters: json!({"type": "object"}),
};
let call = ToolCall {
id: "call-1".into(),
name: "fs.read".into(),
arguments: json!({"path": "/tmp/x"}),
};
let result = ToolResult {
call_id: "call-1".into(),
output: json!({"content": "…"}),
is_error: false,
redactions: Vec::new(),
};
let cmd = ExecCommand {
argv: vec!["rg".into(), "-n".into(), "pat".into()],
env: [("HOME".to_string(), "/tmp".to_string())]
.into_iter()
.collect(),
cwd: Some("/tmp".into()),
timeout_ms: Some(5_000),
};
let exec = ExecResult {
exit_code: Some(0),
stdout: "match".into(),
stderr: String::new(),
timed_out: false,
redactions: Vec::new(),
};
let rule = PolicyRule {
class: "rate_limited".into(),
action: RecoveryAction::BackoffRetry { delay_ms: 500 },
};
fn rt<T>(val: &T)
where
T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
{
let ser = serde_json::to_value(val).unwrap();
let back: T = serde_json::from_value(ser).unwrap();
assert_eq!(&back, val);
}
rt(&req);
rt(&chunk);
rt(&schema);
rt(&call);
rt(&result);
rt(&cmd);
rt(&exec);
rt(&rule);
let outcome = LoopOutcome::SoftFailed {
reason: "empty model response".into(),
};
assert_eq!(
serde_json::to_value(&outcome).unwrap(),
json!({"SoftFailed": {"reason": "empty model response"}})
);
}
}