kaynine-runtime 0.1.0

Runtime actors, durable runs, approval flows, and policy chains for Kaynine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! AgentRuntime: the host-facing facade over per-session actors (SPEC §3.2,
//! §12). Each session has at most one actor task holding the writer lease,
//! which serializes all authoritative writes for that session.

use crate::actor::{self, ActorCommand, ActorHandle};
use crate::run;
use kaynine_core::budget::BudgetPolicy;
use kaynine_core::compaction::{CompactionConfig, CompactionModelSelector};
use kaynine_core::error::KaynineError;
use kaynine_core::event::{EventEnvelope, RealtimeEvent};
use kaynine_core::ids::{BranchId, ModelId, RunId, SessionId};
use kaynine_core::message::ContentBlock;
use kaynine_core::policy::Policy;
use kaynine_core::provider::{
    CredentialProvider, ModelCapabilities, ModelProvider, ReasoningLevel, TokenCounter,
};
use kaynine_core::store::{
    BranchRecord, CreateSessionRequest, EntryRecord, RunState, SessionRecord, SessionStore,
    SteerRecord,
};
use kaynine_core::tool::Tool;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{broadcast, mpsc, oneshot};

pub struct AgentRuntime {
    store: Arc<dyn SessionStore>,
    actors: Arc<Mutex<HashMap<SessionId, ActorHandle>>>,
    actor_seq: AtomicU64,
    shutting_down: AtomicBool,
}

#[derive(Clone)]
pub struct StartRunRequest {
    pub command_id: String,
    pub session_id: SessionId,
    pub branch_id: BranchId,
    pub content: Vec<ContentBlock>,
    pub model_override: Option<ModelId>,
    pub reasoning_override: Option<ReasoningLevel>,
    pub capabilities: ModelCapabilities,
    pub system_prompt: String,
    pub provider: Arc<dyn ModelProvider>,
    pub token_counter: Arc<dyn TokenCounter>,
    pub credentials: Arc<dyn CredentialProvider>,
    pub tools: Vec<Arc<dyn Tool>>,
    pub budget: BudgetPolicy,
    pub max_turns: Option<u32>,
    /// Policy gate evaluated before every tool execution (SPEC §8). Defaults
    /// to `AllowAllPolicy` for trusted hosts.
    pub policy: Arc<dyn Policy>,
    /// When set, the run gets an InteractiveApprovalHandler with this
    /// per-decision timeout; Ask decisions wait for `resolve_approval`.
    /// None → approval mode DisabledFailClosed: Ask fails closed.
    pub approval_timeout: Option<Duration>,
    /// When set, the loop composes the system prompt through this composer
    /// at every turn (SPEC §9); None falls back to `system_prompt`.
    pub prompt: Option<Arc<kaynine_core::prompt::PromptComposer>>,
    /// Compaction thresholds (SPEC §10); None disables compaction.
    pub compaction: Option<CompactionConfig>,
    /// Model selector for summary generation; None → current model.
    pub compaction_selector: Option<Arc<dyn CompactionModelSelector>>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunAccepted {
    pub run_id: RunId,
    pub user_entry_id: kaynine_core::ids::EntryId,
    pub revision: u64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CancelRequest {
    pub command_id: String,
    pub session_id: SessionId,
    pub run_id: RunId,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CancelOutcome {
    Cancelled { revision: u64 },
    AlreadyTerminal { state: RunState },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SessionSnapshot {
    pub session: SessionRecord,
    pub branches: Vec<BranchRecord>,
    pub chains: HashMap<BranchId, Vec<EntryRecord>>,
    /// Only reflects a live actor's run. A `Running` row left behind by a
    /// crashed process is surfaced after recovery-on-next-actor, not here.
    pub active_run: Option<ActiveRunInfo>,
    pub current_revision: u64,
    pub last_run_seq: Option<u64>,
    pub unapplied_steers: Vec<SteerRecord>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActiveRunInfo {
    pub run_id: RunId,
    pub branch_id: BranchId,
    pub model: ModelId,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReleaseOutcome {
    Released,
    RunAlreadyActive,
    NotFound,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ShutdownReport {
    pub cancelled_runs: Vec<RunId>,
    pub interrupted_runs: Vec<RunId>,
    pub released_sessions: usize,
}

/// Items a subscription yields: the authoritative `Snapshot` first, then
/// live `Event`s. `ResyncRequired` appears when the consumer lagged past the
/// broadcast capacity; the following `next()` returns a fresh `Snapshot`.
/// Events between the initial registration and the snapshot (or spanning a
/// resync) can be delivered both in a snapshot and as events; consumers
/// dedupe by (revision, run_seq) (SPEC §5.3 allows this interpretation).
pub enum SubscriptionItem {
    Snapshot(Box<SessionSnapshot>),
    Event(EventEnvelope<RealtimeEvent>),
    ResyncRequired,
}

pub struct SessionSubscription {
    store: Arc<dyn SessionStore>,
    session_id: SessionId,
    receiver: broadcast::Receiver<EventEnvelope<RealtimeEvent>>,
    pending_snapshot: Option<Box<SessionSnapshot>>,
    resynced: bool,
}

impl SessionSubscription {
    pub async fn next(&mut self) -> Option<SubscriptionItem> {
        if let Some(snapshot) = self.pending_snapshot.take() {
            return Some(SubscriptionItem::Snapshot(snapshot));
        }
        if self.resynced {
            self.resynced = false;
            let snapshot =
                run::build_snapshot(self.store.as_ref(), &self.session_id, None, None, None)
                    .await
                    .ok()?;
            return Some(SubscriptionItem::Snapshot(Box::new(snapshot)));
        }
        match self.receiver.recv().await {
            Ok(envelope) => Some(SubscriptionItem::Event(envelope)),
            Err(broadcast::error::RecvError::Lagged(_)) => {
                self.resynced = true;
                Some(SubscriptionItem::ResyncRequired)
            }
            Err(broadcast::error::RecvError::Closed) => None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateSessionRequest {
    pub command_id: Option<String>,
    pub session_id: SessionId,
    pub default_model: Option<ModelId>,
    pub reasoning: Option<ReasoningLevel>,
    pub metadata: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SteerRequest {
    pub command_id: String,
    pub session_id: SessionId,
    pub run_id: RunId,
    pub content: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SteerAccepted {
    pub steer_id: String,
    pub revision: u64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApprovalResolution {
    pub command_id: String,
    pub session_id: SessionId,
    pub run_id: RunId,
    pub call_id: kaynine_core::ids::ToolCallId,
    pub approved: bool,
}

/// Result of submitting an approval decision (SPEC §8.3): Delivered reached a
/// live waiter; Expired arrived after the deadline lapsed; NotFound is an
/// unknown or already-resolved call.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ApprovalOutcome {
    Delivered,
    Expired,
    NotFound,
}

impl AgentRuntime {
    pub fn new(store: Arc<dyn SessionStore>) -> Self {
        Self {
            store,
            actors: Arc::new(Mutex::new(HashMap::new())),
            actor_seq: AtomicU64::new(0),
            shutting_down: AtomicBool::new(false),
        }
    }

    pub async fn create_session(
        &self,
        request: CreateSessionRequest,
    ) -> Result<SessionRecord, KaynineError> {
        self.store.create_session(request).await
    }

    pub async fn list_sessions(&self) -> Result<Vec<SessionRecord>, KaynineError> {
        self.store.list_sessions().await
    }

    pub async fn list_branches(
        &self,
        session_id: &SessionId,
    ) -> Result<Vec<BranchRecord>, KaynineError> {
        self.store.list_branches(session_id).await
    }

    pub async fn get_snapshot(
        &self,
        session_id: &SessionId,
    ) -> Result<SessionSnapshot, KaynineError> {
        let handle = {
            let actors = self.actors.lock().expect("actor registry mutex poisoned");
            actors.get(session_id).cloned()
        };
        if let Some(handle) = handle {
            let (tx, rx) = oneshot::channel();
            if handle
                .tx
                .send(ActorCommand::Snapshot { reply: tx })
                .await
                .is_ok()
            {
                if let Ok(result) = rx.await {
                    return result;
                }
            }
            // The actor died mid-command; drop the stale registration and
            // fall through to reading store truth directly.
            self.remove_actor(session_id, &handle);
        }
        run::build_snapshot(self.store.as_ref(), session_id, None, None, None).await
    }

    pub async fn start_run(&self, request: StartRunRequest) -> Result<RunAccepted, KaynineError> {
        self.check_shutting_down()?;
        let session_id = request.session_id.clone();
        let request = Box::new(request);
        self.with_actor(&session_id, move |reply| ActorCommand::StartRun {
            request: request.clone(),
            reply,
        })
        .await
    }

    pub async fn cancel(&self, request: CancelRequest) -> Result<CancelOutcome, KaynineError> {
        self.check_shutting_down()?;
        let session_id = request.session_id.clone();
        self.with_actor(&session_id, move |reply| ActorCommand::Cancel {
            request: request.clone(),
            reply,
        })
        .await
    }

    /// Watches a session. Spawns (or reuses) the session actor, so if another
    /// process holds the writer lease this returns `SessionBusy` — v0.1
    /// targets single-process desktop use, where multi-process watching can
    /// read the store directly instead of via a live feed.
    pub async fn watch_session(
        &self,
        session_id: &SessionId,
    ) -> Result<SessionSubscription, KaynineError> {
        // Register the receiver BEFORE requesting the snapshot so no event
        // between the two is missed (duplicates in the other direction are
        // possible; consumers dedupe by revision/run_seq).
        let receiver = self
            .with_actor(session_id, |reply| ActorCommand::Subscribe { reply })
            .await?;
        let snapshot = self
            .with_actor(session_id, |reply| ActorCommand::Snapshot { reply })
            .await?;
        Ok(SessionSubscription {
            store: self.store.clone(),
            session_id: session_id.clone(),
            receiver,
            pending_snapshot: Some(Box::new(snapshot)),
            resynced: false,
        })
    }

    pub async fn steer(&self, request: SteerRequest) -> Result<SteerAccepted, KaynineError> {
        self.check_shutting_down()?;
        let session_id = request.session_id.clone();
        self.with_actor(&session_id, move |reply| ActorCommand::Steer {
            request: request.clone(),
            reply,
        })
        .await
    }

    pub async fn resolve_approval(
        &self,
        request: ApprovalResolution,
    ) -> Result<ApprovalOutcome, KaynineError> {
        self.check_shutting_down()?;
        let session_id = request.session_id.clone();
        self.with_actor(&session_id, move |reply| ActorCommand::ResolveApproval {
            request: request.clone(),
            reply,
        })
        .await
    }

    pub async fn update_session(
        &self,
        request: UpdateSessionRequest,
    ) -> Result<SessionRecord, KaynineError> {
        self.check_shutting_down()?;
        let session_id = request.session_id.clone();
        self.with_actor(&session_id, move |reply| ActorCommand::UpdateSession {
            request: request.clone(),
            reply,
        })
        .await
    }

    pub async fn release_session(
        &self,
        session_id: &SessionId,
    ) -> Result<ReleaseOutcome, KaynineError> {
        let handle = {
            let actors = self.actors.lock().expect("actor registry mutex poisoned");
            actors.get(session_id).cloned()
        };
        let Some(handle) = handle else {
            return Ok(ReleaseOutcome::NotFound);
        };
        let (tx, rx) = oneshot::channel();
        if handle
            .tx
            .send(ActorCommand::Release { reply: tx })
            .await
            .is_err()
        {
            self.remove_actor(session_id, &handle);
            return Ok(ReleaseOutcome::NotFound);
        }
        match rx.await {
            Ok(result) => result,
            Err(_) => {
                self.remove_actor(session_id, &handle);
                Ok(ReleaseOutcome::NotFound)
            }
        }
    }

    pub async fn shutdown(&self, grace: Duration) -> Result<ShutdownReport, KaynineError> {
        self.shutting_down.store(true, Ordering::SeqCst);
        let handles: Vec<(SessionId, ActorHandle)> = {
            let actors = self.actors.lock().expect("actor registry mutex poisoned");
            actors
                .iter()
                .map(|(id, h)| (id.clone(), h.clone()))
                .collect()
        };
        let mut report = ShutdownReport::default();
        for (session_id, handle) in handles {
            let (tx, rx) = oneshot::channel();
            if handle
                .tx
                .send(ActorCommand::Shutdown { grace, reply: tx })
                .await
                .is_err()
            {
                self.remove_actor(&session_id, &handle);
                continue;
            }
            if let Ok(Ok((cancelled, interrupted))) = rx.await {
                report.cancelled_runs.extend(cancelled);
                report.interrupted_runs.extend(interrupted);
                report.released_sessions += 1;
            }
            self.remove_actor(&session_id, &handle);
        }
        Ok(report)
    }

    fn check_shutting_down(&self) -> Result<(), KaynineError> {
        if self.shutting_down.load(Ordering::SeqCst) {
            return Err(KaynineError::InvalidRequest);
        }
        Ok(())
    }

    /// Sends a command to the session's actor, spawning one if needed. If the
    /// actor task already exited (e.g. its lease acquisition failed and it
    /// replied SessionBusy to queued commands before this send), the stale
    /// registration is dropped and a fresh actor is tried once.
    async fn with_actor<T>(
        &self,
        session_id: &SessionId,
        build: impl Fn(oneshot::Sender<Result<T, KaynineError>>) -> ActorCommand,
    ) -> Result<T, KaynineError> {
        let mut handle = self.get_or_spawn_actor(session_id)?;
        for attempt in 0..2 {
            let (tx, rx) = oneshot::channel();
            if handle.tx.send(build(tx)).await.is_ok() {
                return match rx.await {
                    Ok(result) => result,
                    Err(_) => {
                        if attempt == 0 {
                            self.remove_actor(session_id, &handle);
                            handle = self.get_or_spawn_actor(session_id)?;
                            continue;
                        }
                        Err(KaynineError::Internal)
                    }
                };
            }
            if attempt == 0 {
                self.remove_actor(session_id, &handle);
                handle = self.get_or_spawn_actor(session_id)?;
                continue;
            }
            return Err(KaynineError::Internal);
        }
        Err(KaynineError::Internal)
    }

    fn get_or_spawn_actor(&self, session_id: &SessionId) -> Result<ActorHandle, KaynineError> {
        self.check_shutting_down()?;
        let mut actors = self.actors.lock().expect("actor registry mutex poisoned");
        if let Some(handle) = actors.get(session_id) {
            return Ok(handle.clone());
        }
        let (tx, rx) = mpsc::channel(64);
        let handle = ActorHandle {
            actor_id: self.actor_seq.fetch_add(1, Ordering::SeqCst),
            tx,
        };
        actors.insert(session_id.clone(), handle.clone());
        drop(actors);
        actor::spawn(
            self.store.clone(),
            self.actors.clone(),
            session_id.clone(),
            handle.clone(),
            rx,
        );
        Ok(handle)
    }

    fn remove_actor(&self, session_id: &SessionId, handle: &ActorHandle) {
        let mut actors = self.actors.lock().expect("actor registry mutex poisoned");
        if actors
            .get(session_id)
            .is_some_and(|current| current.actor_id == handle.actor_id)
        {
            actors.remove(session_id);
        }
    }
}