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    #[error("invalid response: {0}")]
87    InvalidResponse(String),
88    #[error("{0}")]
89    Other(String),
90}
91
92/// Seam (DESIGN §6.2): model completion as a stream of chunks. Built-in
93/// provider: openai-compat (kian-llm); any third-party may replace it.
94pub trait ModelProvider: Send + Sync {
95    fn complete(&self, req: ModelRequest) -> BoxStream<'static, Result<ModelChunk, ProviderError>>;
96}
97
98// ---------------------------------------------------------------------------
99// ToolProvider
100// ---------------------------------------------------------------------------
101
102/// A model-visible tool schema. Serialized into the request prefix; the
103/// serialization format is frozen stable content (constraint 3).
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct ToolSchema {
106    pub name: String,
107    pub description: String,
108    /// JSON-Schema-shaped parameter description (opaque to the core).
109    pub parameters: Value,
110}
111
112/// A tool invocation requested by the model.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct ToolCall {
115    pub id: String,
116    pub name: String,
117    pub arguments: Value,
118}
119
120/// A tool invocation result.
121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
122pub struct ToolResult {
123    pub call_id: String,
124    pub output: Value,
125    /// Distinguishes tool-level errors from successful outputs honestly
126    /// (constraint 7).
127    pub is_error: bool,
128    /// redaction provenance: what the exec redactor scrubbed from
129    /// this result (aggregate counts, never secret values). Additive
130    /// seam field — legacy JSON parses with an empty vec, an empty vec
131    /// serializes without the key, and the report never enters the
132    /// model-visible `output`.
133    #[serde(default, skip_serializing_if = "Vec::is_empty")]
134    pub redactions: Vec<Redaction>,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
138pub enum ToolError {
139    #[error("invalid tool call: {0}")]
140    InvalidCall(String),
141    #[error("tool execution failed: {0}")]
142    Execution(String),
143    #[error("tool timed out")]
144    Timeout,
145}
146
147/// Seam (DESIGN §6.2): model-visible tools. Built-ins: fs/exec/kiand
148/// (kian-loop). Side-effecting invocations must be *logged before
149/// execution* (invariant 1) — the caller appends the `tool/call` event
150/// before `invoke` runs.
151pub trait ToolProvider: Send + Sync {
152    fn schemas(&self) -> Vec<ToolSchema>;
153    fn invoke(&self, call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>>;
154}
155
156// ---------------------------------------------------------------------------
157// ExecBackend
158// ---------------------------------------------------------------------------
159
160/// A command execution request (argv vector, never a shell string).
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162pub struct ExecCommand {
163    pub argv: Vec<String>,
164    pub env: BTreeMap<String, String>,
165    pub cwd: Option<String>,
166    pub timeout_ms: Option<u64>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170pub struct ExecResult {
171    /// `None` when the process was killed / did not exit normally.
172    pub exit_code: Option<i32>,
173    pub stdout: String,
174    pub stderr: String,
175    pub timed_out: bool,
176    /// redaction provenance, produced by the redaction pass that
177    /// scrubbed `stdout`/`stderr` (the report travels with the result so
178    /// tool layers can attach it to the `tool/result` event payload).
179    /// Additive: legacy JSON parses with an empty vec; empty serializes
180    /// without the key.
181    #[serde(default, skip_serializing_if = "Vec::is_empty")]
182    pub redactions: Vec<Redaction>,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
186pub enum ExecError {
187    #[error("failed to spawn: {0}")]
188    Spawn(String),
189    #[error("execution timed out")]
190    Timeout,
191    #[error("io error: {0}")]
192    Io(String),
193}
194
195/// Seam (DESIGN §6.2): environment command execution. Built-ins: local
196/// (built-) and remote endpoint via KiandProto (bundle).
197pub trait ExecBackend: Send + Sync {
198    fn exec(&self, cmd: ExecCommand) -> BoxFuture<'static, Result<ExecResult, ExecError>>;
199}
200
201// ---------------------------------------------------------------------------
202// LoopDriver
203// ---------------------------------------------------------------------------
204
205/// What a loop iteration reports back to the drain. A soft failure is
206/// routed to the recovery policy and is *never* settled as `completed`
207/// (constraint 7).
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209pub enum LoopOutcome {
210    /// One provider turn finished (events were appended during it).
211    TurnDone,
212    /// No eligible input remains; the drain may settle and release.
213    Settled,
214    /// A stop condition ended the loop intentionally.
215    Stopped { reason: String },
216    /// Soft failure (e.g. empty model response) — consult the recovery
217    /// policy table.
218    SoftFailed { reason: String },
219}
220
221/// Stop reason prefix a resident loop (the Router, the watchdog) emits
222/// when its **per-episode** iteration budget is exhausted. The
223/// `RouterDriver` recognizes it and parks the resident instead of ending
224/// the session (ADR-024); it is an in-process contract, not an event or a
225/// wire value.
226pub const EPISODE_BUDGET_STOP_REASON_PREFIX: &str = "episode iteration budget exhausted";
227/// Stop reason a resident loop (the Router) emits when its rotation
228/// threshold is met at a park boundary: the engine ends the session
229/// `rotated` (ADR-040 phase 2). The **hold owner** ends its own session
230/// — a parked resident holds the drain, so an outside closer cannot
231/// claim an idle session. In-process contract only, not an event or wire
232/// value.
233pub const ROTATION_STOP_REASON: &str = "resident rotation requested";
234
235/// Seam (DESIGN §6.2): the agent loop as control flow inside a drain.
236/// Built-in: the async ReAct loop (kian-loop). The context type is
237/// left abstract on purpose — it is the drain handle surface (inbox take,
238/// event append, …) that the orchestrator provides; the core does not model
239/// execution internals (layered iron rule).
240pub trait LoopDriver: Send + Sync {
241    type Ctx: Send;
242    fn drive(&self, ctx: Self::Ctx) -> BoxStream<'static, LoopOutcome>;
243}
244
245// ---------------------------------------------------------------------------
246// RecoveryPolicySource
247// ---------------------------------------------------------------------------
248
249/// One declarative policy rule (A4): a classifier class name → action.
250/// `class` strings follow the pure classifier's names (
251/// `provider_down`, `rate_limited`, `context_overflow`, …).
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253pub struct PolicyRule {
254    pub class: String,
255    pub action: RecoveryAction,
256}
257
258/// Recovery actions (DESIGN §2.4). Every action is one-shot-guarded and
259/// budgeted with refund semantics; none may loop unboundedly (constraint 8).
260#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
261pub enum RecoveryAction {
262    BackoffRetry { delay_ms: u64 },
263    CompressThenRetry,
264    Failover,
265    InterruptAsk,
266    Fail,
267}
268
269/// Seam (DESIGN §6.2): supplies the declarative recovery table. Built-in:
270/// config file (`kian.yaml`). Disposition stays owned by the
271/// caller — this source is pure data.
272pub trait RecoveryPolicySource: Send + Sync {
273    fn table(&self) -> Vec<PolicyRule>;
274}
275
276// ---------------------------------------------------------------------------
277// ChannelAdapter (bundle — definition only; impls live in the
278// super-agent bundle, never in core)
279// ---------------------------------------------------------------------------
280
281/// One inbound channel event, surfaced by a [`ChannelAdapter`]. The
282/// payload is verbatim channel JSON (it rides inside the admitted input's
283/// `content`, so the frozen message-payload contract is untouched).
284#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
285pub struct ChannelEvent {
286    /// Channel name (e.g. `mock-im`, `lark`, `github`).
287    pub channel: String,
288    /// Adapter-side unique id — the idempotency key for admission
289    /// (one inbox row per event, never two).
290    pub event_id: String,
291    /// Optional routing topic (subscription rules may match on it).
292    pub topic: Option<String>,
293    /// Optional sender provenance (adapter-defined identity — the id,
294    /// name, or object the channel reports). Opaque to the core; the
295    /// bundle's admission-class vocabulary keys on it.
296    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
297    #[serde(default)]
298    pub sender: Option<Value>,
299    /// Optional group/chat provenance (adapter-defined — the chat or
300    /// group the event arrived in, when distinct from the routing
301    /// topic). Opaque to the core.
302    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
303    #[serde(default)]
304    pub group: Option<String>,
305    /// Verbatim event payload, opaque to the core.
306    pub payload: Value,
307    /// Observed at, unix epoch milliseconds.
308    pub ts_ms: u64,
309}
310
311/// One outbound channel delivery, handed to a [`ChannelAdapter`]. Output
312/// policies (word limits, structured sections) are applied by the caller
313/// *before* the send; the adapter delivers what it is given and returns
314/// an honest [`SendReceipt`] or error.
315#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
316pub struct ChannelDelivery {
317    pub channel: String,
318    /// Channel-defined delivery target (chat id, issue ref, …) — opaque
319    /// to everything upstream of the adapter.
320    pub target: Value,
321    /// The message content to deliver, already policy-shaped.
322    pub content: Value,
323}
324
325/// Proof that a delivery landed: the adapter's own id for the sent
326/// message plus the delivery timestamp. Recorded in the audit stream via
327/// the caller's `channel/delivered` event.
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
329pub struct SendReceipt {
330    pub message_id: String,
331    pub ts_ms: u64,
332}
333
334/// Adapter-side failures, pre-aligned with the pure error classifier's
335/// vocabulary so classification never parses error strings.
336#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
337pub enum ChannelError {
338    #[error("channel unavailable: {0}")]
339    Unavailable(String),
340    #[error("delivery failed: {0}")]
341    DeliveryFailed(String),
342    #[error("delivery timed out")]
343    Timeout,
344}
345
346/// Seam (DESIGN §6.2, bundle): an inbound/outbound channel (IM, issue
347/// tracker, …). Definition only in core — the first impl is the
348/// production-quality in-memory mock channel (kian-superagent); real
349/// lark/GitHub adapters are ecosystem. Subscribe streams must be
350/// independently cloneable consumers of the adapter's own choosing.
351pub trait ChannelAdapter: Send + Sync {
352    /// Inbound events. Each event must be surfaced exactly once per
353    /// subscriber; admission dedupes on `event_id` as the durable guard.
354    fn subscribe(&self) -> BoxStream<'static, ChannelEvent>;
355    /// Outbound delivery. Resolves only after the channel accepted the
356    /// message — an honest error never masquerades as a receipt.
357    fn send(&self, out: ChannelDelivery) -> BoxFuture<'static, Result<SendReceipt, ChannelError>>;
358}
359
360// ---------------------------------------------------------------------------
361// WatchdogSource (bundle — definition only)
362// ---------------------------------------------------------------------------
363
364/// Endpoint health as the watchdog observes it. Edge-triggered: a source
365/// reports *changes*, not heartbeats.
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
367#[serde(rename_all = "lowercase")]
368pub enum EndpointHealth {
369    Online,
370    Offline,
371}
372
373/// One edge-triggered health transition for a registered endpoint. A
374/// dead daemon cannot report its own death — the authoritative v1 view
375/// is the server's heartbeat-absence observation (DESIGN §4.3).
376#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
377pub struct HealthEvent {
378    pub endpoint_id: String,
379    pub status: EndpointHealth,
380    pub ts_ms: u64,
381    pub detail: Option<String>,
382}
383
384/// Seam (DESIGN §6.2, bundle): an edge-triggered health monitor.
385/// Definition only in core — the v1 impl is the server-side heartbeat
386/// watchdog over the endpoint registry (kian-exec). The stream
387/// carries state changes only (no flapping, no periodic noise); health
388/// events reach sessions exclusively via Admit — the watchdog never
389/// writes session streams itself (layered iron rule).
390pub trait WatchdogSource: Send + Sync {
391    fn health(&self) -> BoxStream<'static, HealthEvent>;
392}
393
394#[cfg(test)]
395mod tests {
396    use serde_json::json;
397
398    use super::{
399        ExecCommand, ExecResult, LoopOutcome, ModelChunk, ModelRequest, PolicyRule, RecoveryAction,
400        ToolCall, ToolResult, ToolSchema,
401    };
402    use crate::model::SlotName;
403
404    /// All built-in seams are object-safe so the orchestrator can hold
405    /// plugin-registered `Arc<dyn _>` impls (DESIGN §6.2, §7).
406    #[test]
407    fn seam_traits_are_object_safe() {
408        fn assert_object_safe(
409            _: &dyn super::ModelProvider,
410            _: &dyn super::ToolProvider,
411            _: &dyn super::ExecBackend,
412            _: &dyn super::RecoveryPolicySource,
413            _: &dyn super::LoopDriver<Ctx = ()>,
414        ) {
415        }
416        let _ = assert_object_safe;
417    }
418
419    /// The bundle seams are object-safe for the same reason the
420    /// built-in seams are: assembly holds `Arc<dyn ChannelAdapter>` /
421    /// `Arc<dyn WatchdogSource>` registered by plugins.
422    #[test]
423    fn bundle_seam_traits_are_object_safe() {
424        fn assert_object_safe(_: &dyn super::ChannelAdapter, _: &dyn super::WatchdogSource) {}
425        let _ = assert_object_safe;
426    }
427
428    /// The bundle seam support types round-trip through JSON; the
429    /// health status serializes as the lowercase tabled form.
430    #[test]
431    fn bundle_seam_support_types_round_trip() {
432        use super::{
433            ChannelDelivery, ChannelError, ChannelEvent, EndpointHealth, HealthEvent, SendReceipt,
434        };
435
436        let event = ChannelEvent {
437            channel: "mock-im".into(),
438            event_id: "evt-7".into(),
439            topic: Some("worker-1".into()),
440            sender: Some(json!({"id": "u-42", "name": "yifei"})),
441            group: Some("chat-9".into()),
442            payload: json!({"text": "@kian deploy"}),
443            ts_ms: 1_762_000_000_000,
444        };
445        let delivery = ChannelDelivery {
446            channel: "mock-im".into(),
447            target: json!({"chat_id": 42}),
448            content: json!({"text": "done"}),
449        };
450        let receipt = SendReceipt {
451            message_id: "msg-9".into(),
452            ts_ms: 1_762_000_000_001,
453        };
454        let health = HealthEvent {
455            endpoint_id: "ep-laptop".into(),
456            status: EndpointHealth::Offline,
457            ts_ms: 1_762_000_000_002,
458            detail: Some("heartbeat stale".into()),
459        };
460
461        fn rt<T>(val: &T)
462        where
463            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
464        {
465            let ser = serde_json::to_value(val).unwrap();
466            let back: T = serde_json::from_value(ser).unwrap();
467            assert_eq!(&back, val);
468        }
469        rt(&event);
470        rt(&delivery);
471        rt(&receipt);
472        rt(&health);
473
474        // Tabled serde forms: lowercase status words.
475        assert_eq!(
476            serde_json::to_value(EndpointHealth::Online).unwrap(),
477            json!("online")
478        );
479        assert_eq!(
480            serde_json::to_value(EndpointHealth::Offline).unwrap(),
481            json!("offline")
482        );
483        // Errors stay display-stable (classification reads kinds, not
484        // strings, but the messages are human-facing).
485        assert_eq!(ChannelError::Timeout.to_string(), "delivery timed out");
486    }
487
488    /// Old `ChannelEvent` JSON (legacy, no `sender`/`group`) parses
489    /// unchanged with `None` defaults for the new fields, and the new
490    /// fields serialize as explicit nulls — additive, never breaking.
491    #[test]
492    fn old_channel_event_json_parses_with_default_provenance() {
493        use super::ChannelEvent;
494
495        let old = json!({
496            "channel": "mock-im",
497            "event_id": "evt-legacy",
498            "topic": null,
499            "payload": {"text": "hi"},
500            "ts_ms": 1_762_000_000_000u64,
501        });
502        let event: ChannelEvent = serde_json::from_value(old).unwrap();
503        assert_eq!(event.channel, "mock-im");
504        assert_eq!(event.event_id, "evt-legacy");
505        assert_eq!(event.topic, None);
506        assert_eq!(event.sender, None);
507        assert_eq!(event.group, None);
508
509        // The new fields serialize as nulls (serde default visibility):
510        // a round trip preserves equality either way.
511        let ser = serde_json::to_value(&event).unwrap();
512        assert_eq!(ser["sender"], serde_json::Value::Null);
513        assert_eq!(ser["group"], serde_json::Value::Null);
514        let back: ChannelEvent = serde_json::from_value(ser).unwrap();
515        assert_eq!(back, event);
516    }
517
518    /// `ModelChunk.usage` is additive — legacy JSON (no `usage`
519    /// key) parses with `None`, `None` serializes without the key, and
520    /// a usage-carrying chunk round-trips with `delta: null`.
521    #[test]
522    fn model_chunk_usage_is_additive() {
523        let plain = ModelChunk::new(json!({"content": "hi"}));
524        let ser = serde_json::to_value(&plain).unwrap();
525        assert_eq!(ser, json!({"delta": {"content": "hi"}}));
526        let legacy: ModelChunk =
527            serde_json::from_value(json!({"delta": {"content": "hi"}})).unwrap();
528        assert_eq!(legacy, plain);
529        assert_eq!(legacy.usage, None);
530
531        let with = ModelChunk::with_usage(serde_json::Value::Null, json!({"prompt_tokens": 3}));
532        let ser = serde_json::to_value(&with).unwrap();
533        assert_eq!(ser, json!({"delta": null, "usage": {"prompt_tokens": 3}}));
534        let back: ModelChunk = serde_json::from_value(ser).unwrap();
535        assert_eq!(back, with);
536    }
537
538    /// The seam support types round-trip through JSON; policy rules come
539    /// from declarative config and must be serde-shaped.
540    #[test]
541    fn seam_support_types_round_trip() {
542        let req = ModelRequest {
543            slot: SlotName("main".into()),
544            body: json!({"messages": []}),
545        };
546        let chunk = ModelChunk::new(json!({"text": "hi"}));
547        let schema = ToolSchema {
548            name: "fs.read".into(),
549            description: "read a file".into(),
550            parameters: json!({"type": "object"}),
551        };
552        let call = ToolCall {
553            id: "call-1".into(),
554            name: "fs.read".into(),
555            arguments: json!({"path": "/tmp/x"}),
556        };
557        let result = ToolResult {
558            call_id: "call-1".into(),
559            output: json!({"content": "…"}),
560            is_error: false,
561            redactions: Vec::new(),
562        };
563        let cmd = ExecCommand {
564            argv: vec!["rg".into(), "-n".into(), "pat".into()],
565            env: [("HOME".to_string(), "/tmp".to_string())]
566                .into_iter()
567                .collect(),
568            cwd: Some("/tmp".into()),
569            timeout_ms: Some(5_000),
570        };
571        let exec = ExecResult {
572            exit_code: Some(0),
573            stdout: "match".into(),
574            stderr: String::new(),
575            timed_out: false,
576            redactions: Vec::new(),
577        };
578        let rule = PolicyRule {
579            class: "rate_limited".into(),
580            action: RecoveryAction::BackoffRetry { delay_ms: 500 },
581        };
582
583        fn rt<T>(val: &T)
584        where
585            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
586        {
587            let ser = serde_json::to_value(val).unwrap();
588            let back: T = serde_json::from_value(ser).unwrap();
589            assert_eq!(&back, val);
590        }
591        rt(&req);
592        rt(&chunk);
593        rt(&schema);
594        rt(&call);
595        rt(&result);
596        rt(&cmd);
597        rt(&exec);
598        rt(&rule);
599
600        let outcome = LoopOutcome::SoftFailed {
601            reason: "empty model response".into(),
602        };
603        // LoopOutcome uses default serde variant naming (it is a seam type,
604        // not part of the frozen event schema).
605        assert_eq!(
606            serde_json::to_value(&outcome).unwrap(),
607            json!({"SoftFailed": {"reason": "empty model response"}})
608        );
609    }
610}