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    /// The session-lifetime token budget refused the next provider
220    /// request (ADR-055): the drain ends `awaiting_budget` (resumable,
221    /// running -> idle) instead of spending past the limit. `budget` is
222    /// the projection the gate evaluated (`limit`, `raised`, `spent`,
223    /// `estimate`), carried for the end-of-drain audit line.
224    AwaitingBudget { budget: Value },
225}
226
227/// Stop reason prefix a resident loop (the Router, the watchdog) emits
228/// when its **per-episode** iteration budget is exhausted. The
229/// `RouterDriver` recognizes it and parks the resident instead of ending
230/// the session (ADR-024); it is an in-process contract, not an event or a
231/// wire value.
232pub const EPISODE_BUDGET_STOP_REASON_PREFIX: &str = "episode iteration budget exhausted";
233/// Stop reason a resident loop (the Router) emits when its rotation
234/// threshold is met at a park boundary: the engine ends the session
235/// `rotated` (ADR-040 phase 2). The **hold owner** ends its own session
236/// — a parked resident holds the drain, so an outside closer cannot
237/// claim an idle session. In-process contract only, not an event or wire
238/// value.
239pub const ROTATION_STOP_REASON: &str = "resident rotation requested";
240
241/// Seam (DESIGN §6.2): the agent loop as control flow inside a drain.
242/// Built-in: the async ReAct loop (kian-loop). The context type is
243/// left abstract on purpose — it is the drain handle surface (inbox take,
244/// event append, …) that the orchestrator provides; the core does not model
245/// execution internals (layered iron rule).
246pub trait LoopDriver: Send + Sync {
247    type Ctx: Send;
248    fn drive(&self, ctx: Self::Ctx) -> BoxStream<'static, LoopOutcome>;
249}
250
251// ---------------------------------------------------------------------------
252// RecoveryPolicySource
253// ---------------------------------------------------------------------------
254
255/// One declarative policy rule (A4): a classifier class name → action.
256/// `class` strings follow the pure classifier's names (
257/// `provider_down`, `rate_limited`, `context_overflow`, …).
258#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
259pub struct PolicyRule {
260    pub class: String,
261    pub action: RecoveryAction,
262}
263
264/// Recovery actions (DESIGN §2.4). Every action is one-shot-guarded and
265/// budgeted with refund semantics; none may loop unboundedly (constraint 8).
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
267pub enum RecoveryAction {
268    BackoffRetry { delay_ms: u64 },
269    CompressThenRetry,
270    Failover,
271    InterruptAsk,
272    Fail,
273}
274
275/// Seam (DESIGN §6.2): supplies the declarative recovery table. Built-in:
276/// config file (`kian.yaml`). Disposition stays owned by the
277/// caller — this source is pure data.
278pub trait RecoveryPolicySource: Send + Sync {
279    fn table(&self) -> Vec<PolicyRule>;
280}
281
282// ---------------------------------------------------------------------------
283// ChannelAdapter (bundle — definition only; impls live in the
284// super-agent bundle, never in core)
285// ---------------------------------------------------------------------------
286
287/// One inbound channel event, surfaced by a [`ChannelAdapter`]. The
288/// payload is verbatim channel JSON (it rides inside the admitted input's
289/// `content`, so the frozen message-payload contract is untouched).
290#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
291pub struct ChannelEvent {
292    /// Channel name (e.g. `mock-im`, `lark`, `github`).
293    pub channel: String,
294    /// Adapter-side unique id — the idempotency key for admission
295    /// (one inbox row per event, never two).
296    pub event_id: String,
297    /// Optional routing topic (subscription rules may match on it).
298    pub topic: Option<String>,
299    /// Optional sender provenance (adapter-defined identity — the id,
300    /// name, or object the channel reports). Opaque to the core; the
301    /// bundle's admission-class vocabulary keys on it.
302    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
303    #[serde(default)]
304    pub sender: Option<Value>,
305    /// Optional group/chat provenance (adapter-defined — the chat or
306    /// group the event arrived in, when distinct from the routing
307    /// topic). Opaque to the core.
308    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
309    #[serde(default)]
310    pub group: Option<String>,
311    /// Verbatim event payload, opaque to the core.
312    pub payload: Value,
313    /// Observed at, unix epoch milliseconds.
314    pub ts_ms: u64,
315}
316
317/// One outbound channel delivery, handed to a [`ChannelAdapter`]. Output
318/// policies (word limits, structured sections) are applied by the caller
319/// *before* the send; the adapter delivers what it is given and returns
320/// an honest [`SendReceipt`] or error.
321#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
322pub struct ChannelDelivery {
323    pub channel: String,
324    /// Channel-defined delivery target (chat id, issue ref, …) — opaque
325    /// to everything upstream of the adapter.
326    pub target: Value,
327    /// The message content to deliver, already policy-shaped.
328    pub content: Value,
329}
330
331/// Proof that a delivery landed: the adapter's own id for the sent
332/// message plus the delivery timestamp. Recorded in the audit stream via
333/// the caller's `channel/delivered` event.
334#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
335pub struct SendReceipt {
336    pub message_id: String,
337    pub ts_ms: u64,
338}
339
340/// Adapter-side failures, pre-aligned with the pure error classifier's
341/// vocabulary so classification never parses error strings.
342#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
343pub enum ChannelError {
344    #[error("channel unavailable: {0}")]
345    Unavailable(String),
346    #[error("delivery failed: {0}")]
347    DeliveryFailed(String),
348    #[error("delivery timed out")]
349    Timeout,
350}
351
352/// Seam (DESIGN §6.2, bundle): an inbound/outbound channel (IM, issue
353/// tracker, …). Definition only in core — the first impl is the
354/// production-quality in-memory mock channel (kian-superagent); real
355/// lark/GitHub adapters are ecosystem. Subscribe streams must be
356/// independently cloneable consumers of the adapter's own choosing.
357pub trait ChannelAdapter: Send + Sync {
358    /// Inbound events. Each event must be surfaced exactly once per
359    /// subscriber; admission dedupes on `event_id` as the durable guard.
360    fn subscribe(&self) -> BoxStream<'static, ChannelEvent>;
361    /// Outbound delivery. Resolves only after the channel accepted the
362    /// message — an honest error never masquerades as a receipt.
363    fn send(&self, out: ChannelDelivery) -> BoxFuture<'static, Result<SendReceipt, ChannelError>>;
364}
365
366// ---------------------------------------------------------------------------
367// WatchdogSource (bundle — definition only)
368// ---------------------------------------------------------------------------
369
370/// Endpoint health as the watchdog observes it. Edge-triggered: a source
371/// reports *changes*, not heartbeats.
372#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
373#[serde(rename_all = "lowercase")]
374pub enum EndpointHealth {
375    Online,
376    Offline,
377}
378
379/// One edge-triggered health transition for a registered endpoint. A
380/// dead daemon cannot report its own death — the authoritative v1 view
381/// is the server's heartbeat-absence observation (DESIGN §4.3).
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
383pub struct HealthEvent {
384    pub endpoint_id: String,
385    pub status: EndpointHealth,
386    pub ts_ms: u64,
387    pub detail: Option<String>,
388}
389
390/// Seam (DESIGN §6.2, bundle): an edge-triggered health monitor.
391/// Definition only in core — the v1 impl is the server-side heartbeat
392/// watchdog over the endpoint registry (kian-exec). The stream
393/// carries state changes only (no flapping, no periodic noise); health
394/// events reach sessions exclusively via Admit — the watchdog never
395/// writes session streams itself (layered iron rule).
396pub trait WatchdogSource: Send + Sync {
397    fn health(&self) -> BoxStream<'static, HealthEvent>;
398}
399
400#[cfg(test)]
401mod tests {
402    use serde_json::json;
403
404    use super::{
405        ExecCommand, ExecResult, LoopOutcome, ModelChunk, ModelRequest, PolicyRule, RecoveryAction,
406        ToolCall, ToolResult, ToolSchema,
407    };
408    use crate::model::SlotName;
409
410    /// All built-in seams are object-safe so the orchestrator can hold
411    /// plugin-registered `Arc<dyn _>` impls (DESIGN §6.2, §7).
412    #[test]
413    fn seam_traits_are_object_safe() {
414        fn assert_object_safe(
415            _: &dyn super::ModelProvider,
416            _: &dyn super::ToolProvider,
417            _: &dyn super::ExecBackend,
418            _: &dyn super::RecoveryPolicySource,
419            _: &dyn super::LoopDriver<Ctx = ()>,
420        ) {
421        }
422        let _ = assert_object_safe;
423    }
424
425    /// The bundle seams are object-safe for the same reason the
426    /// built-in seams are: assembly holds `Arc<dyn ChannelAdapter>` /
427    /// `Arc<dyn WatchdogSource>` registered by plugins.
428    #[test]
429    fn bundle_seam_traits_are_object_safe() {
430        fn assert_object_safe(_: &dyn super::ChannelAdapter, _: &dyn super::WatchdogSource) {}
431        let _ = assert_object_safe;
432    }
433
434    /// The bundle seam support types round-trip through JSON; the
435    /// health status serializes as the lowercase tabled form.
436    #[test]
437    fn bundle_seam_support_types_round_trip() {
438        use super::{
439            ChannelDelivery, ChannelError, ChannelEvent, EndpointHealth, HealthEvent, SendReceipt,
440        };
441
442        let event = ChannelEvent {
443            channel: "mock-im".into(),
444            event_id: "evt-7".into(),
445            topic: Some("worker-1".into()),
446            sender: Some(json!({"id": "u-42", "name": "yifei"})),
447            group: Some("chat-9".into()),
448            payload: json!({"text": "@kian deploy"}),
449            ts_ms: 1_762_000_000_000,
450        };
451        let delivery = ChannelDelivery {
452            channel: "mock-im".into(),
453            target: json!({"chat_id": 42}),
454            content: json!({"text": "done"}),
455        };
456        let receipt = SendReceipt {
457            message_id: "msg-9".into(),
458            ts_ms: 1_762_000_000_001,
459        };
460        let health = HealthEvent {
461            endpoint_id: "ep-laptop".into(),
462            status: EndpointHealth::Offline,
463            ts_ms: 1_762_000_000_002,
464            detail: Some("heartbeat stale".into()),
465        };
466
467        fn rt<T>(val: &T)
468        where
469            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
470        {
471            let ser = serde_json::to_value(val).unwrap();
472            let back: T = serde_json::from_value(ser).unwrap();
473            assert_eq!(&back, val);
474        }
475        rt(&event);
476        rt(&delivery);
477        rt(&receipt);
478        rt(&health);
479
480        // Tabled serde forms: lowercase status words.
481        assert_eq!(
482            serde_json::to_value(EndpointHealth::Online).unwrap(),
483            json!("online")
484        );
485        assert_eq!(
486            serde_json::to_value(EndpointHealth::Offline).unwrap(),
487            json!("offline")
488        );
489        // Errors stay display-stable (classification reads kinds, not
490        // strings, but the messages are human-facing).
491        assert_eq!(ChannelError::Timeout.to_string(), "delivery timed out");
492    }
493
494    /// Old `ChannelEvent` JSON (legacy, no `sender`/`group`) parses
495    /// unchanged with `None` defaults for the new fields, and the new
496    /// fields serialize as explicit nulls — additive, never breaking.
497    #[test]
498    fn old_channel_event_json_parses_with_default_provenance() {
499        use super::ChannelEvent;
500
501        let old = json!({
502            "channel": "mock-im",
503            "event_id": "evt-legacy",
504            "topic": null,
505            "payload": {"text": "hi"},
506            "ts_ms": 1_762_000_000_000u64,
507        });
508        let event: ChannelEvent = serde_json::from_value(old).unwrap();
509        assert_eq!(event.channel, "mock-im");
510        assert_eq!(event.event_id, "evt-legacy");
511        assert_eq!(event.topic, None);
512        assert_eq!(event.sender, None);
513        assert_eq!(event.group, None);
514
515        // The new fields serialize as nulls (serde default visibility):
516        // a round trip preserves equality either way.
517        let ser = serde_json::to_value(&event).unwrap();
518        assert_eq!(ser["sender"], serde_json::Value::Null);
519        assert_eq!(ser["group"], serde_json::Value::Null);
520        let back: ChannelEvent = serde_json::from_value(ser).unwrap();
521        assert_eq!(back, event);
522    }
523
524    /// `ModelChunk.usage` is additive — legacy JSON (no `usage`
525    /// key) parses with `None`, `None` serializes without the key, and
526    /// a usage-carrying chunk round-trips with `delta: null`.
527    #[test]
528    fn model_chunk_usage_is_additive() {
529        let plain = ModelChunk::new(json!({"content": "hi"}));
530        let ser = serde_json::to_value(&plain).unwrap();
531        assert_eq!(ser, json!({"delta": {"content": "hi"}}));
532        let legacy: ModelChunk =
533            serde_json::from_value(json!({"delta": {"content": "hi"}})).unwrap();
534        assert_eq!(legacy, plain);
535        assert_eq!(legacy.usage, None);
536
537        let with = ModelChunk::with_usage(serde_json::Value::Null, json!({"prompt_tokens": 3}));
538        let ser = serde_json::to_value(&with).unwrap();
539        assert_eq!(ser, json!({"delta": null, "usage": {"prompt_tokens": 3}}));
540        let back: ModelChunk = serde_json::from_value(ser).unwrap();
541        assert_eq!(back, with);
542    }
543
544    /// The seam support types round-trip through JSON; policy rules come
545    /// from declarative config and must be serde-shaped.
546    #[test]
547    fn seam_support_types_round_trip() {
548        let req = ModelRequest {
549            slot: SlotName("main".into()),
550            body: json!({"messages": []}),
551        };
552        let chunk = ModelChunk::new(json!({"text": "hi"}));
553        let schema = ToolSchema {
554            name: "fs.read".into(),
555            description: "read a file".into(),
556            parameters: json!({"type": "object"}),
557        };
558        let call = ToolCall {
559            id: "call-1".into(),
560            name: "fs.read".into(),
561            arguments: json!({"path": "/tmp/x"}),
562        };
563        let result = ToolResult {
564            call_id: "call-1".into(),
565            output: json!({"content": "…"}),
566            is_error: false,
567            redactions: Vec::new(),
568        };
569        let cmd = ExecCommand {
570            argv: vec!["rg".into(), "-n".into(), "pat".into()],
571            env: [("HOME".to_string(), "/tmp".to_string())]
572                .into_iter()
573                .collect(),
574            cwd: Some("/tmp".into()),
575            timeout_ms: Some(5_000),
576        };
577        let exec = ExecResult {
578            exit_code: Some(0),
579            stdout: "match".into(),
580            stderr: String::new(),
581            timed_out: false,
582            redactions: Vec::new(),
583        };
584        let rule = PolicyRule {
585            class: "rate_limited".into(),
586            action: RecoveryAction::BackoffRetry { delay_ms: 500 },
587        };
588
589        fn rt<T>(val: &T)
590        where
591            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
592        {
593            let ser = serde_json::to_value(val).unwrap();
594            let back: T = serde_json::from_value(ser).unwrap();
595            assert_eq!(&back, val);
596        }
597        rt(&req);
598        rt(&chunk);
599        rt(&schema);
600        rt(&call);
601        rt(&result);
602        rt(&cmd);
603        rt(&exec);
604        rt(&rule);
605
606        let outcome = LoopOutcome::SoftFailed {
607            reason: "empty model response".into(),
608        };
609        // LoopOutcome uses default serde variant naming (it is a seam type,
610        // not part of the frozen event schema).
611        assert_eq!(
612            serde_json::to_value(&outcome).unwrap(),
613            json!({"SoftFailed": {"reason": "empty model response"}})
614        );
615    }
616}