Skip to main content

kian_core/
seams.rs

1//! Seam trait definitions (DESIGN §6.2 "Seam three roles").
2//!
3//! The built-in seam traits — `ModelProvider`, `LoopDriver`, `ToolProvider`,
4//! `ExecBackend`, `RecoveryPolicySource` — plus the bundle additions
5//! `ChannelAdapter` and `WatchdogSource` — are *definitions only*:
6//! no impls here; implementation crates (kian-llm, kian-loop,
7//! kian-superagent, kian-exec, …) implement and re-export them. Living in
8//! `kian-core` keeps the orchestrator dependency tree clean (constraint
9//! 10).
10
11use std::collections::BTreeMap;
12
13use futures::future::BoxFuture;
14use futures::stream::BoxStream;
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17
18use crate::model::SlotName;
19use crate::secrets::Redaction;
20
21// ---------------------------------------------------------------------------
22// ModelProvider
23// ---------------------------------------------------------------------------
24
25/// A model request: slot + opaque provider-shaped body. The body is built
26/// and serialized by the provider implementation (its serialization format
27/// is frozen stable content); the core stays provider-agnostic.
28///
29/// Persist-what-you-send (A2): the *caller* persists the request bytes as a
30/// `step/request` event before invoking [`ModelProvider::complete`] — the
31/// ordering obligation lives at the call site, not inside the provider.
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct ModelRequest {
34    pub slot: SlotName,
35    pub body: Value,
36}
37
38/// One streamed response chunk; the delta shape is provider-defined and
39/// opaque to the core.
40///
41/// a chunk may instead (or additionally) carry the provider's
42/// `usage` object **verbatim** — a usage-only frame has `delta: null`
43/// and `usage: Some(…)`; consumers must skip null deltas when
44/// assembling content. The field is additive (serde default, omitted
45/// when `None`).
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct ModelChunk {
48    pub delta: Value,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub usage: Option<Value>,
51}
52
53impl ModelChunk {
54    /// A delta-bearing chunk with no usage report.
55    #[must_use]
56    pub fn new(delta: Value) -> Self {
57        Self { delta, usage: None }
58    }
59
60    /// A chunk carrying a (possibly null) delta plus the provider's
61    /// usage object verbatim.
62    #[must_use]
63    pub fn with_usage(delta: Value, usage: Value) -> Self {
64        Self {
65            delta,
66            usage: Some(usage),
67        }
68    }
69}
70
71/// Provider-side failures. Variants pre-align with the pure error
72/// classifier so classification never needs to parse error strings.
73#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
74pub enum ProviderError {
75    #[error("rate limited")]
76    RateLimited,
77    #[error("context overflow")]
78    ContextOverflow,
79    #[error("provider unavailable: {0}")]
80    Unavailable(String),
81    #[error("transport error: {0}")]
82    Transport(String),
83    /// A soft failure (constraint 7): never mappable onto `completed`.
84    #[error("empty response")]
85    EmptyResponse,
86    /// The request itself is too large (ADR-068): an operator
87    /// `max_request_bytes` bound refused it before sending, or the
88    /// provider answered HTTP 413. Re-sending the same bytes cannot
89    /// succeed, so this is its own class — never `provider_down`.
90    #[error("request too large: {detail}")]
91    RequestTooLarge {
92        /// Serialized body size, in bytes.
93        size: usize,
94        /// The configured outbound bound; `None` when no local bound is
95        /// configured and the verdict came from the provider's 413.
96        limit: Option<u64>,
97        /// Operator-facing detail: bound or status, snippet, and whether
98        /// any request byte left this process.
99        detail: String,
100    },
101    #[error("invalid response: {0}")]
102    InvalidResponse(String),
103    #[error("{0}")]
104    Other(String),
105}
106
107/// Seam (DESIGN §6.2): model completion as a stream of chunks. Built-in
108/// provider: openai-compat (kian-llm); any third-party may replace it.
109pub trait ModelProvider: Send + Sync {
110    fn complete(&self, req: ModelRequest) -> BoxStream<'static, Result<ModelChunk, ProviderError>>;
111}
112
113// ---------------------------------------------------------------------------
114// ToolProvider
115// ---------------------------------------------------------------------------
116
117/// A model-visible tool schema. Serialized into the request prefix; the
118/// serialization format is frozen stable content (constraint 3).
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120pub struct ToolSchema {
121    pub name: String,
122    pub description: String,
123    /// JSON-Schema-shaped parameter description (opaque to the core).
124    pub parameters: Value,
125}
126
127/// A tool invocation requested by the model.
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129pub struct ToolCall {
130    pub id: String,
131    pub name: String,
132    pub arguments: Value,
133}
134
135/// A tool invocation result.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct ToolResult {
138    pub call_id: String,
139    pub output: Value,
140    /// Distinguishes tool-level errors from successful outputs honestly
141    /// (constraint 7).
142    pub is_error: bool,
143    /// redaction provenance: what the exec redactor scrubbed from
144    /// this result (aggregate counts, never secret values). Additive
145    /// seam field — legacy JSON parses with an empty vec, an empty vec
146    /// serializes without the key, and the report never enters the
147    /// model-visible `output`.
148    #[serde(default, skip_serializing_if = "Vec::is_empty")]
149    pub redactions: Vec<Redaction>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
153pub enum ToolError {
154    #[error("invalid tool call: {0}")]
155    InvalidCall(String),
156    #[error("tool execution failed: {0}")]
157    Execution(String),
158    #[error("tool timed out")]
159    Timeout,
160}
161
162/// Seam (DESIGN §6.2): model-visible tools. Built-ins: fs/exec/kiand
163/// (kian-loop). Side-effecting invocations must be *logged before
164/// execution* (invariant 1) — the caller appends the `tool/call` event
165/// before `invoke` runs.
166pub trait ToolProvider: Send + Sync {
167    fn schemas(&self) -> Vec<ToolSchema>;
168    fn invoke(&self, call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>>;
169}
170
171// ---------------------------------------------------------------------------
172// ExecBackend
173// ---------------------------------------------------------------------------
174
175/// A command execution request (argv vector, never a shell string).
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
177pub struct ExecCommand {
178    pub argv: Vec<String>,
179    pub env: BTreeMap<String, String>,
180    pub cwd: Option<String>,
181    pub timeout_ms: Option<u64>,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185pub struct ExecResult {
186    /// `None` when the process was killed / did not exit normally.
187    pub exit_code: Option<i32>,
188    pub stdout: String,
189    pub stderr: String,
190    pub timed_out: bool,
191    /// redaction provenance, produced by the redaction pass that
192    /// scrubbed `stdout`/`stderr` (the report travels with the result so
193    /// tool layers can attach it to the `tool/result` event payload).
194    /// Additive: legacy JSON parses with an empty vec; empty serializes
195    /// without the key.
196    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197    pub redactions: Vec<Redaction>,
198}
199
200#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
201pub enum ExecError {
202    #[error("failed to spawn: {0}")]
203    Spawn(String),
204    #[error("execution timed out")]
205    Timeout,
206    #[error("io error: {0}")]
207    Io(String),
208}
209
210/// Seam (DESIGN §6.2): environment command execution. Built-ins: local
211/// (built-) and remote endpoint via KiandProto (bundle).
212pub trait ExecBackend: Send + Sync {
213    fn exec(&self, cmd: ExecCommand) -> BoxFuture<'static, Result<ExecResult, ExecError>>;
214}
215
216// ---------------------------------------------------------------------------
217// LoopDriver
218// ---------------------------------------------------------------------------
219
220/// What a loop iteration reports back to the drain. A soft failure is
221/// routed to the recovery policy and is *never* settled as `completed`
222/// (constraint 7).
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub enum LoopOutcome {
225    /// One provider turn finished (events were appended during it).
226    TurnDone,
227    /// No eligible input remains; the drain may settle and release.
228    Settled,
229    /// A stop condition ended the loop intentionally.
230    Stopped { reason: String },
231    /// Soft failure (e.g. empty model response) — consult the recovery
232    /// policy table.
233    SoftFailed { reason: String },
234    /// The session-lifetime token budget refused the next provider
235    /// request (ADR-055): the drain ends `awaiting_budget` (resumable,
236    /// running -> idle) instead of spending past the limit. `budget` is
237    /// the projection the gate evaluated (`limit`, `raised`, `spent`,
238    /// `estimate`), carried for the end-of-drain audit line.
239    AwaitingBudget { budget: Value },
240}
241
242/// Stop reason prefix a resident loop (the Router, the watchdog) emits
243/// when its **per-episode** iteration budget is exhausted. The
244/// `RouterDriver` recognizes it and parks the resident instead of ending
245/// the session (ADR-024); it is an in-process contract, not an event or a
246/// wire value.
247pub const EPISODE_BUDGET_STOP_REASON_PREFIX: &str = "episode iteration budget exhausted";
248/// Stop reason a resident loop (the Router) emits when its rotation
249/// threshold is met at a park boundary: the engine ends the session
250/// `rotated` (ADR-040 phase 2). The **hold owner** ends its own session
251/// — a parked resident holds the drain, so an outside closer cannot
252/// claim an idle session. In-process contract only, not an event or wire
253/// value.
254pub const ROTATION_STOP_REASON: &str = "resident rotation requested";
255/// Terminal-cancel stop reason emitted by a conductor after it has committed
256/// the authoritative cancelled verdict. The engine maps this reason to a
257/// terminal `cancelled` end even when an interrupt flag is also set.
258pub const TERMINAL_CANCEL_STOP_REASON: &str = "terminal cancel requested";
259
260/// Seam (DESIGN §6.2): the agent loop as control flow inside a drain.
261/// Built-in: the async ReAct loop (kian-loop). The context type is
262/// left abstract on purpose — it is the drain handle surface (inbox take,
263/// event append, …) that the orchestrator provides; the core does not model
264/// execution internals (layered iron rule).
265pub trait LoopDriver: Send + Sync {
266    type Ctx: Send;
267    fn drive(&self, ctx: Self::Ctx) -> BoxStream<'static, LoopOutcome>;
268}
269
270// ---------------------------------------------------------------------------
271// RecoveryPolicySource
272// ---------------------------------------------------------------------------
273
274/// One declarative policy rule (A4): a classifier class name → action.
275/// `class` strings follow the pure classifier's names (
276/// `provider_down`, `rate_limited`, `context_overflow`, …).
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278pub struct PolicyRule {
279    pub class: String,
280    pub action: RecoveryAction,
281}
282
283/// Recovery actions (DESIGN §2.4). Every action is one-shot-guarded and
284/// budgeted with refund semantics; none may loop unboundedly (constraint 8).
285#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
286pub enum RecoveryAction {
287    BackoffRetry { delay_ms: u64 },
288    CompressThenRetry,
289    Failover,
290    InterruptAsk,
291    Fail,
292}
293
294/// Seam (DESIGN §6.2): supplies the declarative recovery table. Built-in:
295/// config file (`kian.yaml`). Disposition stays owned by the
296/// caller — this source is pure data.
297pub trait RecoveryPolicySource: Send + Sync {
298    fn table(&self) -> Vec<PolicyRule>;
299}
300
301// ---------------------------------------------------------------------------
302// ChannelAdapter (bundle — definition only; impls live in the
303// super-agent bundle, never in core)
304// ---------------------------------------------------------------------------
305
306/// One inbound channel event, surfaced by a [`ChannelAdapter`]. The
307/// payload is verbatim channel JSON (it rides inside the admitted input's
308/// `content`, so the frozen message-payload contract is untouched).
309#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
310pub struct ChannelEvent {
311    /// Channel name (e.g. `mock-im`, `lark`, `github`).
312    pub channel: String,
313    /// Adapter-side unique id — the idempotency key for admission
314    /// (one inbox row per event, never two).
315    pub event_id: String,
316    /// Optional routing topic (subscription rules may match on it).
317    pub topic: Option<String>,
318    /// Optional sender provenance (adapter-defined identity — the id,
319    /// name, or object the channel reports). Opaque to the core; the
320    /// bundle's admission-class vocabulary keys on it.
321    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
322    #[serde(default)]
323    pub sender: Option<Value>,
324    /// Optional group/chat provenance (adapter-defined — the chat or
325    /// group the event arrived in, when distinct from the routing
326    /// topic). Opaque to the core.
327    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
328    #[serde(default)]
329    pub group: Option<String>,
330    /// Verbatim event payload, opaque to the core.
331    pub payload: Value,
332    /// Observed at, unix epoch milliseconds.
333    pub ts_ms: u64,
334}
335
336/// One outbound channel delivery, handed to a [`ChannelAdapter`]. Output
337/// policies (word limits, structured sections) are applied by the caller
338/// *before* the send; the adapter delivers what it is given and returns
339/// an honest [`SendReceipt`] or error.
340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
341pub struct ChannelDelivery {
342    pub channel: String,
343    /// Channel-defined delivery target (chat id, issue ref, …) — opaque
344    /// to everything upstream of the adapter.
345    pub target: Value,
346    /// The message content to deliver, already policy-shaped.
347    pub content: Value,
348    /// Optional caller-chosen logical delivery identity (ADR-089): a
349    /// non-empty opaque string of at most 256 UTF-8 bytes. Two deliveries
350    /// carrying the same key are the same logical message, so an adapter
351    /// that implements idempotency must not send it twice. Absent on every
352    /// unkeyed delivery; None serializes to nothing, so the unkeyed wire
353    /// form is unchanged.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub delivery_key: Option<String>,
356    /// Optional exact-byte attachment. It is absent from every text
357    /// delivery, preserving the pre-ADR-092 serialized shape.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub attachment: Option<ChannelAttachment>,
360}
361
362/// One exact-byte outbound attachment (ADR-092).
363#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
364pub struct ChannelAttachment {
365    pub media_type: String,
366    pub bytes: Vec<u8>,
367}
368
369/// Proof that a delivery landed: the adapter's own id for the sent
370/// message plus the delivery timestamp. Recorded in the audit stream via
371/// the caller's `channel/delivered` event.
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373pub struct SendReceipt {
374    pub message_id: String,
375    pub ts_ms: u64,
376}
377
378/// Adapter-side failures, pre-aligned with the pure error classifier's
379/// vocabulary so classification never parses error strings.
380#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
381pub enum ChannelError {
382    #[error("channel unavailable: {0}")]
383    Unavailable(String),
384    #[error("delivery failed: {0}")]
385    DeliveryFailed(String),
386    #[error("delivery timed out")]
387    Timeout,
388}
389
390/// Seam (DESIGN §6.2, bundle): an inbound/outbound channel (IM, issue
391/// tracker, …). Definition only in core — the first impl is the
392/// production-quality in-memory mock channel (kian-superagent); real
393/// lark/GitHub adapters are ecosystem. Subscribe streams must be
394/// independently cloneable consumers of the adapter's own choosing.
395pub trait ChannelAdapter: Send + Sync {
396    /// Inbound events. Each event must be surfaced exactly once per
397    /// subscriber; admission dedupes on `event_id` as the durable guard.
398    fn subscribe(&self) -> BoxStream<'static, ChannelEvent>;
399    /// Outbound delivery. Resolves only after the channel accepted the
400    /// message — an honest error never masquerades as a receipt.
401    fn send(&self, out: ChannelDelivery) -> BoxFuture<'static, Result<SendReceipt, ChannelError>>;
402    /// Whether a delivery carrying a logical delivery key is deduplicated
403    /// by this adapter (ADR-089). The default is false: an adapter is
404    /// unkeyed unless it explicitly implements the capability, and a keyed
405    /// delivery to an unkeyed adapter is refused before send.
406    fn supports_delivery_idempotency(&self) -> bool {
407        false
408    }
409
410    /// Whether this adapter can deliver an exact-byte attachment of the
411    /// given non-empty media type (ADR-092). The default is false.
412    fn supports_media(&self, _media_type: &str) -> bool {
413        false
414    }
415}
416
417// ---------------------------------------------------------------------------
418// WatchdogSource (bundle — definition only)
419// ---------------------------------------------------------------------------
420
421/// Endpoint health as the watchdog observes it. Edge-triggered: a source
422/// reports *changes*, not heartbeats.
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
424#[serde(rename_all = "lowercase")]
425pub enum EndpointHealth {
426    Online,
427    Offline,
428}
429
430/// One edge-triggered health transition for a registered endpoint. A
431/// dead daemon cannot report its own death — the authoritative v1 view
432/// is the server's heartbeat-absence observation (DESIGN §4.3).
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
434pub struct HealthEvent {
435    pub endpoint_id: String,
436    pub status: EndpointHealth,
437    pub ts_ms: u64,
438    pub detail: Option<String>,
439}
440
441/// Seam (DESIGN §6.2, bundle): an edge-triggered health monitor.
442/// Definition only in core — the v1 impl is the server-side heartbeat
443/// watchdog over the endpoint registry (kian-exec). The stream
444/// carries state changes only (no flapping, no periodic noise); health
445/// events reach sessions exclusively via Admit — the watchdog never
446/// writes session streams itself (layered iron rule).
447pub trait WatchdogSource: Send + Sync {
448    fn health(&self) -> BoxStream<'static, HealthEvent>;
449}
450
451#[cfg(test)]
452mod tests {
453    use serde_json::json;
454
455    use super::{
456        ExecCommand, ExecResult, LoopOutcome, ModelChunk, ModelRequest, PolicyRule, RecoveryAction,
457        ToolCall, ToolResult, ToolSchema,
458    };
459    use crate::model::SlotName;
460
461    /// All built-in seams are object-safe so the orchestrator can hold
462    /// plugin-registered `Arc<dyn _>` impls (DESIGN §6.2, §7).
463    #[test]
464    fn seam_traits_are_object_safe() {
465        fn assert_object_safe(
466            _: &dyn super::ModelProvider,
467            _: &dyn super::ToolProvider,
468            _: &dyn super::ExecBackend,
469            _: &dyn super::RecoveryPolicySource,
470            _: &dyn super::LoopDriver<Ctx = ()>,
471        ) {
472        }
473        let _ = assert_object_safe;
474    }
475
476    /// The bundle seams are object-safe for the same reason the
477    /// built-in seams are: assembly holds `Arc<dyn ChannelAdapter>` /
478    /// `Arc<dyn WatchdogSource>` registered by plugins.
479    #[test]
480    fn bundle_seam_traits_are_object_safe() {
481        fn assert_object_safe(_: &dyn super::ChannelAdapter, _: &dyn super::WatchdogSource) {}
482        let _ = assert_object_safe;
483    }
484
485    /// The bundle seam support types round-trip through JSON; the
486    /// health status serializes as the lowercase tabled form.
487    #[test]
488    fn bundle_seam_support_types_round_trip() {
489        use super::{
490            ChannelDelivery, ChannelError, ChannelEvent, EndpointHealth, HealthEvent, SendReceipt,
491        };
492
493        let event = ChannelEvent {
494            channel: "mock-im".into(),
495            event_id: "evt-7".into(),
496            topic: Some("worker-1".into()),
497            sender: Some(json!({"id": "u-42", "name": "yifei"})),
498            group: Some("chat-9".into()),
499            payload: json!({"text": "@kian deploy"}),
500            ts_ms: 1_762_000_000_000,
501        };
502        let delivery = ChannelDelivery {
503            channel: "mock-im".into(),
504            target: json!({"chat_id": 42}),
505            content: json!({"text": "done"}),
506            delivery_key: None,
507            attachment: None,
508        };
509        let unkeyed = serde_json::to_value(&delivery).unwrap();
510        assert!(unkeyed.get("delivery_key").is_none());
511        assert_eq!(
512            serde_json::to_string(&delivery).unwrap(),
513            r#"{"channel":"mock-im","target":{"chat_id":42},"content":{"text":"done"}}"#
514        );
515        let keyed = ChannelDelivery {
516            delivery_key: Some("job:deliver:run-1:notify".into()),
517            ..delivery.clone()
518        };
519        assert_eq!(
520            serde_json::to_value(&keyed).unwrap()["delivery_key"],
521            "job:deliver:run-1:notify"
522        );
523        let binary = ChannelDelivery {
524            attachment: Some(super::ChannelAttachment {
525                media_type: "application/octet-stream".into(),
526                bytes: vec![0, 255, 1],
527            }),
528            ..delivery.clone()
529        };
530        assert_eq!(
531            serde_json::to_value(&binary).unwrap()["attachment"],
532            json!({
533                "media_type": "application/octet-stream",
534                "bytes": [0, 255, 1]
535            })
536        );
537        let receipt = SendReceipt {
538            message_id: "msg-9".into(),
539            ts_ms: 1_762_000_000_001,
540        };
541        let health = HealthEvent {
542            endpoint_id: "ep-laptop".into(),
543            status: EndpointHealth::Offline,
544            ts_ms: 1_762_000_000_002,
545            detail: Some("heartbeat stale".into()),
546        };
547
548        fn rt<T>(val: &T)
549        where
550            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
551        {
552            let ser = serde_json::to_value(val).unwrap();
553            let back: T = serde_json::from_value(ser).unwrap();
554            assert_eq!(&back, val);
555        }
556        rt(&event);
557        rt(&delivery);
558        rt(&receipt);
559        rt(&health);
560
561        // Tabled serde forms: lowercase status words.
562        assert_eq!(
563            serde_json::to_value(EndpointHealth::Online).unwrap(),
564            json!("online")
565        );
566        assert_eq!(
567            serde_json::to_value(EndpointHealth::Offline).unwrap(),
568            json!("offline")
569        );
570        // Errors stay display-stable (classification reads kinds, not
571        // strings, but the messages are human-facing).
572        assert_eq!(ChannelError::Timeout.to_string(), "delivery timed out");
573    }
574
575    /// Old `ChannelEvent` JSON (legacy, no `sender`/`group`) parses
576    /// unchanged with `None` defaults for the new fields, and the new
577    /// fields serialize as explicit nulls — additive, never breaking.
578    #[test]
579    fn old_channel_event_json_parses_with_default_provenance() {
580        use super::ChannelEvent;
581
582        let old = json!({
583            "channel": "mock-im",
584            "event_id": "evt-legacy",
585            "topic": null,
586            "payload": {"text": "hi"},
587            "ts_ms": 1_762_000_000_000u64,
588        });
589        let event: ChannelEvent = serde_json::from_value(old).unwrap();
590        assert_eq!(event.channel, "mock-im");
591        assert_eq!(event.event_id, "evt-legacy");
592        assert_eq!(event.topic, None);
593        assert_eq!(event.sender, None);
594        assert_eq!(event.group, None);
595
596        // The new fields serialize as nulls (serde default visibility):
597        // a round trip preserves equality either way.
598        let ser = serde_json::to_value(&event).unwrap();
599        assert_eq!(ser["sender"], serde_json::Value::Null);
600        assert_eq!(ser["group"], serde_json::Value::Null);
601        let back: ChannelEvent = serde_json::from_value(ser).unwrap();
602        assert_eq!(back, event);
603    }
604
605    /// `ModelChunk.usage` is additive — legacy JSON (no `usage`
606    /// key) parses with `None`, `None` serializes without the key, and
607    /// a usage-carrying chunk round-trips with `delta: null`.
608    #[test]
609    fn model_chunk_usage_is_additive() {
610        let plain = ModelChunk::new(json!({"content": "hi"}));
611        let ser = serde_json::to_value(&plain).unwrap();
612        assert_eq!(ser, json!({"delta": {"content": "hi"}}));
613        let legacy: ModelChunk =
614            serde_json::from_value(json!({"delta": {"content": "hi"}})).unwrap();
615        assert_eq!(legacy, plain);
616        assert_eq!(legacy.usage, None);
617
618        let with = ModelChunk::with_usage(serde_json::Value::Null, json!({"prompt_tokens": 3}));
619        let ser = serde_json::to_value(&with).unwrap();
620        assert_eq!(ser, json!({"delta": null, "usage": {"prompt_tokens": 3}}));
621        let back: ModelChunk = serde_json::from_value(ser).unwrap();
622        assert_eq!(back, with);
623    }
624
625    /// The seam support types round-trip through JSON; policy rules come
626    /// from declarative config and must be serde-shaped.
627    #[test]
628    fn seam_support_types_round_trip() {
629        let req = ModelRequest {
630            slot: SlotName("main".into()),
631            body: json!({"messages": []}),
632        };
633        let chunk = ModelChunk::new(json!({"text": "hi"}));
634        let schema = ToolSchema {
635            name: "fs.read".into(),
636            description: "read a file".into(),
637            parameters: json!({"type": "object"}),
638        };
639        let call = ToolCall {
640            id: "call-1".into(),
641            name: "fs.read".into(),
642            arguments: json!({"path": "/tmp/x"}),
643        };
644        let result = ToolResult {
645            call_id: "call-1".into(),
646            output: json!({"content": "…"}),
647            is_error: false,
648            redactions: Vec::new(),
649        };
650        let cmd = ExecCommand {
651            argv: vec!["rg".into(), "-n".into(), "pat".into()],
652            env: [("HOME".to_string(), "/tmp".to_string())]
653                .into_iter()
654                .collect(),
655            cwd: Some("/tmp".into()),
656            timeout_ms: Some(5_000),
657        };
658        let exec = ExecResult {
659            exit_code: Some(0),
660            stdout: "match".into(),
661            stderr: String::new(),
662            timed_out: false,
663            redactions: Vec::new(),
664        };
665        let rule = PolicyRule {
666            class: "rate_limited".into(),
667            action: RecoveryAction::BackoffRetry { delay_ms: 500 },
668        };
669
670        fn rt<T>(val: &T)
671        where
672            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
673        {
674            let ser = serde_json::to_value(val).unwrap();
675            let back: T = serde_json::from_value(ser).unwrap();
676            assert_eq!(&back, val);
677        }
678        rt(&req);
679        rt(&chunk);
680        rt(&schema);
681        rt(&call);
682        rt(&result);
683        rt(&cmd);
684        rt(&exec);
685        rt(&rule);
686
687        let outcome = LoopOutcome::SoftFailed {
688            reason: "empty model response".into(),
689        };
690        // LoopOutcome uses default serde variant naming (it is a seam type,
691        // not part of the frozen event schema).
692        assert_eq!(
693            serde_json::to_value(&outcome).unwrap(),
694            json!({"SoftFailed": {"reason": "empty model response"}})
695        );
696    }
697}