kjarni-cli 0.7.0

Kjarni from the shell: classification, embeddings, reranking, search, chat, summarization, translation and speech-to-text as commands, and an MCP server for AI agents. Same output as PyTorch.
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Conversations the daemon holds: an agent for each, the events of its
//! current turn for clients to follow, and approvals answered from a client.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};

use anyhow::{Result, anyhow};
use async_trait::async_trait;
use kjarni::agent::{
    Access, Agent, AgentConfig, AgentEvents, AgentModel, Approval, Memory, Session, SessionInfo,
    ToolCall, ToolOutcome, tools,
};
use serde::Serialize;
use serde_json::{Value as Json, json};
use tokio::sync::{broadcast, oneshot};

/// One thing that happened in a turn. `seq` grows across the daemon's life,
/// so a client that reconnects asks for what came after the last it saw.
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct Event {
    pub seq: u64,
    #[serde(flatten)]
    pub kind: EventKind,
}

#[derive(Clone, Debug, Serialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EventKind {
    /// A turn started with this message from the user.
    User {
        text: String,
    },
    /// Reply text as it is generated, reasoning included.
    Text {
        delta: String,
    },
    /// The model asked for a tool call. `call` numbers the calls of a turn.
    ToolCall {
        call: u32,
        name: String,
        summary: String,
        access: &'static str,
        arguments: Json,
    },
    /// Call `call` waits for the user to answer approval `approval`.
    Approval {
        approval: u64,
        call: u32,
        summary: String,
        access: &'static str,
    },
    /// The user answered.
    Approved {
        approval: u64,
        decision: &'static str,
    },
    ToolResult {
        call: u32,
        ok: bool,
        denied: bool,
        output: String,
    },
    Notice {
        message: String,
    },
    /// The turn ended with this answer.
    Done {
        text: String,
        steps: usize,
        tool_calls: usize,
        stopped_early: bool,
    },
    /// The turn ended with an error.
    Error {
        message: String,
    },
    /// The user stopped the turn.
    Stopped,
}

impl EventKind {
    pub fn ends_turn(&self) -> bool {
        matches!(
            self,
            EventKind::Done { .. } | EventKind::Error { .. } | EventKind::Stopped
        )
    }
}

fn decision_name(a: Approval) -> &'static str {
    match a {
        Approval::Once => "once",
        Approval::Always => "always",
        Approval::Deny => "deny",
    }
}

/// The part of a conversation that changes during a turn.
struct Turn {
    busy: bool,
    /// The events of the current or last turn.
    events: Vec<Event>,
    pending: Option<(u64, oneshot::Sender<Approval>)>,
    task: Option<tokio::task::AbortHandle>,
    /// The saved messages as a client shows them, up to the start of the
    /// current turn. The agent is locked for a whole turn, so this copy is
    /// what a client opening the conversation mid-turn reads.
    transcript: Json,
}

/// What a client opening a conversation is shown.
pub struct Snapshot {
    pub transcript: Json,
    pub busy: bool,
    /// The current turn's events; empty when no turn is running, since the
    /// transcript then holds the last one.
    pub events: Vec<Event>,
    pub pending_approval: Option<u64>,
}

fn transcript_of(agent: &Agent) -> Json {
    let specs = agent.tools();
    let messages: Vec<Json> = agent
        .messages()
        .iter()
        .map(|m| super::display::message(m, specs))
        .collect();
    json!({ "summary": agent.summary(), "messages": messages })
}

/// A conversation with its agent.
pub struct Live {
    pub id: String,
    agent: tokio::sync::Mutex<Agent>,
    turn: Mutex<Turn>,
    tx: broadcast::Sender<Event>,
    hub: Arc<Hub>,
}

/// What the conversations share: the sequence numbers of events and
/// approvals, and whether new turns are held back.
#[derive(Default)]
struct Hub {
    seq: Mutex<u64>,
    /// True while new turns wait, such as during a change of model. A turn
    /// starts under a read lock, so taking the write lock waits out turns
    /// that are starting.
    held: RwLock<bool>,
}

impl Hub {
    fn next(&self) -> u64 {
        let mut seq = self.seq.lock().expect("event counter lock");
        *seq += 1;
        *seq
    }
}

/// Who answers a turn's approvals.
#[derive(Clone)]
pub enum Answers {
    /// The user, from a client.
    User,
    /// A list fixed in advance, for a turn nobody is watching: calls to these
    /// tools run, any other call that needs approval is declined.
    Allowed(Arc<HashSet<String>>),
}

/// A user's message could not start a turn.
#[derive(Debug, PartialEq)]
pub enum SendError {
    Busy,
    Empty,
    /// New turns are held back for now.
    Held,
}

/// Holds new turns back until dropped.
pub struct Hold(Arc<Hub>);

impl Drop for Hold {
    fn drop(&mut self) {
        *self.0.held.write().expect("hold lock") = false;
    }
}

impl Live {
    fn emit(&self, kind: EventKind) -> Event {
        self.emit_with(kind, None)
    }

    /// Emits `kind`, first setting the transcript to `transcript` when given.
    fn emit_with(&self, kind: EventKind, transcript: Option<Json>) -> Event {
        let event = Event {
            seq: self.hub.next(),
            kind,
        };
        let mut turn = self.turn.lock().expect("turn lock");
        if let Some(t) = transcript {
            turn.transcript = t;
        }
        if event.kind.ends_turn() {
            turn.busy = false;
            turn.task = None;
            turn.pending = None;
        }
        turn.events.push(event.clone());
        // No subscribers is fine: the event is in the log.
        let _ = self.tx.send(event.clone());
        event
    }

    /// The events of the current or last turn after `after`, and a receiver
    /// for those still to come, with none missed or repeated between them.
    pub fn follow(&self, after: u64) -> (Vec<Event>, broadcast::Receiver<Event>) {
        let turn = self.turn.lock().expect("turn lock");
        let rx = self.tx.subscribe();
        let past = turn
            .events
            .iter()
            .filter(|e| e.seq > after)
            .cloned()
            .collect();
        (past, rx)
    }

    pub fn busy(&self) -> bool {
        self.turn.lock().expect("turn lock").busy
    }

    pub fn snapshot(&self) -> Snapshot {
        let turn = self.turn.lock().expect("turn lock");
        Snapshot {
            transcript: turn.transcript.clone(),
            busy: turn.busy,
            events: if turn.busy {
                turn.events.clone()
            } else {
                Vec::new()
            },
            pending_approval: turn.pending.as_ref().map(|(id, _)| *id),
        }
    }

    /// Starts a turn answering `text`. Its events follow on [`follow`](Self::follow).
    pub fn send(self: &Arc<Self>, text: &str) -> Result<(), SendError> {
        self.send_with(text, Answers::User)
    }

    /// Starts a turn answering `text`, with its approvals answered by `answers`.
    pub fn send_with(self: &Arc<Self>, text: &str, answers: Answers) -> Result<(), SendError> {
        let text = text.trim().to_string();
        if text.is_empty() {
            return Err(SendError::Empty);
        }
        {
            let held = self.hub.held.read().expect("hold lock");
            if *held {
                return Err(SendError::Held);
            }
            let mut turn = self.turn.lock().expect("turn lock");
            if turn.busy {
                return Err(SendError::Busy);
            }
            turn.busy = true;
            turn.events.clear();
        }
        self.emit(EventKind::User { text: text.clone() });
        let live = self.clone();
        let task = tokio::spawn(async move {
            let mut agent = live.agent.lock().await;
            let mut events = Relay {
                live: live.clone(),
                call: 0,
                answers,
            };
            let kind = match agent.send(&text, &mut events).await {
                Ok(reply) => EventKind::Done {
                    text: super::display::split_reasoning(&reply.text).1.to_string(),
                    steps: reply.steps,
                    tool_calls: reply.tool_calls,
                    stopped_early: reply.stopped_early,
                },
                Err(e) => EventKind::Error {
                    message: format!("{e:#}"),
                },
            };
            let transcript = transcript_of(&agent);
            live.emit_with(kind, Some(transcript));
        });
        let mut turn = self.turn.lock().expect("turn lock");
        // A turn that already finished has cleared `busy`; its handle is moot.
        if turn.busy {
            turn.task = Some(task.abort_handle());
        }
        Ok(())
    }

    /// Answers approval `id`. False when it is not the one waiting.
    pub fn answer(&self, id: u64, decision: Approval) -> bool {
        let sender = {
            let mut turn = self.turn.lock().expect("turn lock");
            match turn.pending.take() {
                Some((pending, sender)) if pending == id => sender,
                other => {
                    turn.pending = other;
                    return false;
                }
            }
        };
        self.emit(EventKind::Approved {
            approval: id,
            decision: decision_name(decision),
        });
        sender.send(decision).is_ok()
    }

    /// Stops the turn in progress. False when there is none.
    pub fn stop(self: &Arc<Self>) -> bool {
        let task = {
            let mut turn = self.turn.lock().expect("turn lock");
            if !turn.busy {
                return false;
            }
            turn.pending = None;
            turn.task.take()
        };
        if let Some(task) = task {
            task.abort();
        }
        self.emit(EventKind::Stopped);
        // The stopped turn kept what it had saved; show that once its task
        // has let go of the agent.
        let live = self.clone();
        tokio::spawn(async move {
            let agent = live.agent.lock().await;
            let transcript = transcript_of(&agent);
            drop(agent);
            live.turn.lock().expect("turn lock").transcript = transcript;
        });
        true
    }
}

/// Reports a turn's events to a conversation's followers, and waits for
/// approvals from them.
struct Relay {
    live: Arc<Live>,
    call: u32,
    answers: Answers,
}

#[async_trait]
impl AgentEvents for Relay {
    async fn text(&mut self, delta: &str) {
        self.live.emit(EventKind::Text {
            delta: delta.to_string(),
        });
    }

    async fn tool_call(&mut self, call: &ToolCall, summary: &str, access: Access) {
        self.call += 1;
        self.live.emit(EventKind::ToolCall {
            call: self.call,
            name: call.name.clone(),
            summary: summary.to_string(),
            access: access.as_str(),
            arguments: Json::Object(call.arguments.clone()),
        });
    }

    async fn approve(&mut self, call: &ToolCall, summary: &str, access: Access) -> Approval {
        let id = self.live.hub.next();
        // Announced like any approval, so clients show a call answered in
        // advance the same way as one the user answered.
        let asked = EventKind::Approval {
            approval: id,
            call: self.call,
            summary: summary.to_string(),
            access: access.as_str(),
        };
        if let Answers::Allowed(allowed) = &self.answers {
            self.live.emit(asked);
            let decision = if allowed.contains(&call.name) {
                Approval::Once
            } else {
                self.live.emit(EventKind::Notice {
                    message: format!(
                        "{} is not allowed in this schedule, so the call was declined.",
                        call.name
                    ),
                });
                Approval::Deny
            };
            self.live.emit(EventKind::Approved {
                approval: id,
                decision: decision_name(decision),
            });
            return decision;
        }
        let (tx, rx) = oneshot::channel();
        self.live.turn.lock().expect("turn lock").pending = Some((id, tx));
        self.live.emit(asked);
        rx.await.unwrap_or(Approval::Deny)
    }

    async fn tool_result(&mut self, _call: &ToolCall, outcome: &ToolOutcome) {
        self.live.emit(EventKind::ToolResult {
            call: self.call,
            ok: outcome.ok,
            denied: outcome.denied,
            output: outcome.output.clone(),
        });
    }

    async fn notice(&mut self, message: &str) {
        self.live.emit(EventKind::Notice {
            message: message.to_string(),
        });
    }
}

/// Everything a conversation's agent is made from.
pub struct AgentSetup {
    pub model: Arc<dyn AgentModel>,
    pub memory: Option<Arc<Memory>>,
    pub workdir: PathBuf,
    pub max_steps: usize,
    /// Run every call without asking, as `kjarni agent --yes` does.
    pub approve_all: bool,
}

/// The daemon's conversations, loaded from disk as they are used.
pub struct Conversations {
    setup: AgentSetup,
    sessions_dir: PathBuf,
    live: Mutex<HashMap<String, Arc<Live>>>,
    hub: Arc<Hub>,
}

/// Whether `id` can name a session file: no separators, no `..`.
pub fn valid_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 64
        && id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

impl Conversations {
    pub fn new(setup: AgentSetup, sessions_dir: PathBuf) -> Self {
        Self {
            setup,
            sessions_dir,
            live: Mutex::new(HashMap::new()),
            hub: Arc::new(Hub::default()),
        }
    }

    pub fn setup(&self) -> &AgentSetup {
        &self.setup
    }

    /// Saved conversations, most recent first.
    pub fn list(&self) -> Result<Vec<SessionInfo>> {
        Session::list(&self.sessions_dir)
    }

    /// Whether conversation `id` is in the middle of a turn.
    pub fn busy(&self, id: &str) -> bool {
        self.live
            .lock()
            .expect("conversations lock")
            .get(id)
            .is_some_and(|l| l.busy())
    }

    /// Whether any conversation is in the middle of a turn.
    pub fn any_busy(&self) -> bool {
        self.live
            .lock()
            .expect("conversations lock")
            .values()
            .any(|l| l.busy())
    }

    /// Whether new turns are held back now.
    pub fn held(&self) -> bool {
        *self.hub.held.read().expect("hold lock")
    }

    /// Holds new turns back until the returned [`Hold`] is dropped. `None`
    /// while a turn is running, or turns are held already.
    pub fn hold(&self) -> Option<Hold> {
        let mut held = self.hub.held.write().expect("hold lock");
        if *held || self.any_busy() {
            return None;
        }
        *held = true;
        Some(Hold(self.hub.clone()))
    }

    /// A new, empty conversation.
    pub fn create(&self) -> Result<Arc<Live>> {
        let session = Session::create(&self.sessions_dir)?;
        let id = session.id().to_string();
        let live = self.wrap(id.clone(), self.agent().with_session(session));
        self.live
            .lock()
            .expect("conversations lock")
            .insert(id, live.clone());
        Ok(live)
    }

    /// Conversation `id`, read from disk if it is not loaded. `None` when
    /// there is no such conversation.
    pub fn get(&self, id: &str) -> Result<Option<Arc<Live>>> {
        if !valid_id(id) {
            return Ok(None);
        }
        if let Some(live) = self.live.lock().expect("conversations lock").get(id) {
            return Ok(Some(live.clone()));
        }
        if !self.sessions_dir.join(format!("{id}.jsonl")).exists() {
            return Ok(None);
        }
        let session = Session::open(&self.sessions_dir, id)?;
        let restored = session.load()?;
        let agent = self.agent().with_session(session).with_history(restored);
        let mut live = self.live.lock().expect("conversations lock");
        // Another request may have loaded it meanwhile; keep that one.
        let entry = live
            .entry(id.to_string())
            .or_insert_with(|| self.wrap(id.to_string(), agent));
        Ok(Some(entry.clone()))
    }

    /// Deletes conversation `id`'s file. False when there is no such
    /// conversation; an error while it is mid-turn.
    pub fn delete(&self, id: &str) -> Result<bool> {
        if !valid_id(id) {
            return Ok(false);
        }
        let mut live = self.live.lock().expect("conversations lock");
        if live.get(id).is_some_and(|l| l.busy()) {
            return Err(anyhow!("the conversation is answering; stop it first"));
        }
        let path = self.sessions_dir.join(format!("{id}.jsonl"));
        if !path.exists() {
            return Ok(false);
        }
        std::fs::remove_file(&path)?;
        live.remove(id);
        Ok(true)
    }

    fn agent(&self) -> Agent {
        let workdir = &self.setup.workdir;
        let notes = kjarni::agent::project_notes(workdir);
        let config = AgentConfig {
            max_steps: self.setup.max_steps,
            workdir: Some(workdir.display().to_string()),
            project_notes: notes.map(|n| n.text),
            ..Default::default()
        };
        let workspace = Arc::new(tools::Workspace::new(workdir));
        let mut agent = Agent::new(
            self.setup.model.clone(),
            tools::builtin(workspace, self.setup.memory.clone()),
            config,
        );
        if let Some(memory) = &self.setup.memory {
            agent = agent.with_memory(memory.clone());
        }
        if self.setup.approve_all {
            for access in [Access::Write, Access::Execute, Access::Network] {
                agent.approve_access(access);
            }
        }
        agent
    }

    fn wrap(&self, id: String, agent: Agent) -> Arc<Live> {
        let (tx, _) = broadcast::channel(1024);
        let transcript = transcript_of(&agent);
        Arc::new(Live {
            id,
            agent: tokio::sync::Mutex::new(agent),
            turn: Mutex::new(Turn {
                busy: false,
                events: Vec::new(),
                pending: None,
                task: None,
                transcript,
            }),
            tx,
            hub: self.hub.clone(),
        })
    }
}