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
<script>
  import { onMount, tick } from 'svelte';
  import { api, follow, SignedOut } from './lib/api.js';
  import { applyEvent, fromHistory, newTurnState } from './lib/transcript.js';
  import Sidebar from './components/Sidebar.svelte';
  import Thread from './components/Thread.svelte';
  import Composer from './components/Composer.svelte';
  import Welcome from './components/Welcome.svelte';
  import SignIn from './components/SignIn.svelte';
  import Schedules from './components/Schedules.svelte';
  import Memory from './components/Memory.svelte';
  import Settings from './components/Settings.svelte';
  import Icon from './components/Icon.svelte';
  import Mark from './components/Mark.svelte';

  let signedIn = $state(null);
  let status = $state(null);
  let conversations = $state([]);
  let current = $state(null);
  let turn = $state(newTurnState([]));
  let busy = $state(false);
  let summary = $state(null);
  let loading = $state(false);
  let draft = $state('');
  let drawer = $state(false);
  let trouble = $state('');
  let atBottom = $state(true);
  // 'chat', or one of PAGES.
  let page = $state('chat');

  // The pages besides chat, by their address.
  const PAGES = { schedules: 'Schedules', memory: 'Memory', settings: 'Settings' };

  let scroller = $state();
  let composer = $state();
  let unfollow = null;
  // Ignores replies to requests for a conversation the user has left.
  let visit = 0;

  let title = $derived(
    page !== 'chat'
      ? PAGES[page]
      : conversations.find((c) => c.id === current)?.title || (current ? 'Conversation' : 'Kjarni'),
  );

  function idFromPath() {
    const m = location.pathname.match(/^\/c\/([A-Za-z0-9_-]{1,64})$/);
    return m ? m[1] : null;
  }

  function guard(e) {
    if (e instanceof SignedOut) {
      signedIn = false;
      return;
    }
    trouble = e.message || String(e);
    setTimeout(() => (trouble = ''), 6000);
  }

  async function boot() {
    try {
      status = await api.status();
      signedIn = true;
    } catch (e) {
      if (e instanceof SignedOut) signedIn = false;
      else trouble = 'Kjarni is not answering. Is the daemon running?';
      return;
    }
    await refreshList();
    await route();
  }

  /** Shows the page the address names. */
  async function route() {
    const name = location.pathname.slice(1);
    if (Object.hasOwn(PAGES, name)) openPage(name, false);
    else await show(idFromPath(), false);
  }

  function openPage(name, push = true) {
    ++visit;
    stopFollowing();
    drawer = false;
    current = null;
    busy = false;
    page = name;
    if (push && location.pathname !== `/${name}`) history.pushState(null, '', `/${name}`);
  }

  async function refreshStatus() {
    try {
      status = await api.status();
    } catch (e) {
      guard(e);
    }
  }

  async function refreshList() {
    try {
      conversations = await api.conversations();
    } catch (e) {
      guard(e);
    }
  }

  function stopFollowing() {
    unfollow?.();
    unfollow = null;
  }

  function startFollowing(id, after) {
    stopFollowing();
    const mine = visit;
    unfollow = follow(
      id,
      after,
      (event) => {
        if (mine !== visit) return;
        onEvent(event);
      },
      () => {
        // The browser retries by itself; a closed stream means it gave up.
        if (mine === visit && busy) trouble = 'Lost the connection to Kjarni; retrying.';
      },
    );
  }

  /** Shows conversation `id`, or the welcome page for none. */
  async function show(id, push = true) {
    const mine = ++visit;
    stopFollowing();
    drawer = false;
    page = 'chat';
    current = id;
    busy = false;
    summary = null;
    turn = newTurnState([]);
    if (push && location.pathname !== (id ? `/c/${id}` : '/')) {
      history.pushState(null, '', id ? `/c/${id}` : '/');
    }
    if (!id) {
      await tick();
      composer?.focus();
      return;
    }
    loading = true;
    try {
      const c = await api.conversation(id);
      if (mine !== visit) return;
      const state = newTurnState(fromHistory(c.messages));
      for (const e of c.events ?? []) applyEvent(state, e);
      turn = state;
      summary = c.summary;
      busy = c.busy;
      if (busy) startFollowing(id, turn.lastSeq);
      await scrollToEnd(true);
    } catch (e) {
      if (mine !== visit) return;
      if (e.message?.startsWith('there is no')) {
        await show(null);
        return;
      }
      guard(e);
    } finally {
      if (mine === visit) loading = false;
    }
  }

  function onEvent(event) {
    // The page shows the user's message as soon as it is sent.
    const last = turn.blocks.at(-1);
    if (event.type === 'user' && last?.type === 'user' && last.pending && last.text === event.text.trim()) {
      last.pending = false;
      turn.lastSeq = Math.max(turn.lastSeq, event.seq);
      return;
    }
    applyEvent(turn, event);
    trouble = '';
    if (turn.ended) {
      busy = false;
      stopFollowing();
      refreshList();
    }
    scrollToEnd();
  }

  async function send(text) {
    try {
      let id = current;
      if (!id) {
        id = await api.create();
        ++visit;
        current = id;
        history.pushState(null, '', `/c/${id}`);
        turn = newTurnState([]);
        summary = null;
      }
      turn.blocks.push({ type: 'user', text, pending: true });
      turn.ended = null;
      busy = true;
      await scrollToEnd(true);
      await api.send(id, text);
      // The turn's log starts with this message, so following from the
      // start misses nothing.
      startFollowing(id, 0);
      refreshList();
    } catch (e) {
      busy = false;
      const last = turn.blocks.at(-1);
      if (last?.pending) turn.blocks.pop();
      draft = text;
      guard(e);
    }
  }

  async function answer(approval, decision) {
    try {
      await api.answer(current, approval, decision);
    } catch (e) {
      guard(e);
    }
  }

  async function stop() {
    try {
      await api.stop(current);
    } catch (e) {
      guard(e);
    }
  }

  async function remove(id) {
    try {
      await api.remove(id);
      conversations = conversations.filter((c) => c.id !== id);
      if (id === current) await show(null);
    } catch (e) {
      guard(e);
    }
  }

  function pick(prompt) {
    draft = prompt;
    composer?.focus();
  }

  function onScroll() {
    if (!scroller) return;
    atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 80;
  }

  async function scrollToEnd(force = false) {
    if (!force && !atBottom) return;
    await tick();
    if (scroller) {
      scroller.scrollTop = scroller.scrollHeight;
      atBottom = true;
    }
  }

  onMount(() => {
    boot();
    const onPop = () => route();
    addEventListener('popstate', onPop);
    return () => {
      removeEventListener('popstate', onPop);
      stopFollowing();
    };
  });
</script>

<svelte:head>
  <title>{current || page !== 'chat' ? `${title} ยท Kjarni` : 'Kjarni'}</title>
</svelte:head>

{#if signedIn === false}
  <SignIn onsignedin={boot} />
{:else if signedIn === null}
  <div class="splash">
    <Mark size={40} blink />
    {#if trouble}<p>{trouble}</p>{/if}
  </div>
{:else}
  <div class="app" class:drawer>
    <div class="side">
      <Sidebar
        {conversations}
        {current}
        {status}
        {page}
        onselect={(id) => show(id)}
        onnew={() => show(null)}
        onpage={(name) => openPage(name)}
        ondelete={remove}
      />
    </div>
    <button class="scrim" onclick={() => (drawer = false)} aria-label="Close menu" tabindex="-1"></button>

    <main>
      <header>
        <button class="icon-button" onclick={() => (drawer = true)} aria-label="Conversations"><Icon name="menu" size={20} /></button>
        <div class="title">{title}</div>
        <button class="icon-button" onclick={() => show(null)} aria-label="New conversation"><Icon name="plus" size={20} /></button>
      </header>

      {#if page !== 'chat'}
        <div class="scroll">
          <div class="column">
            {#if page === 'schedules'}
              <Schedules onopen={(id) => (refreshList(), show(id))} onsignedout={() => (signedIn = false)} />
            {:else if page === 'memory'}
              <Memory onsignedout={() => (signedIn = false)} />
            {:else}
              <Settings {status} onchange={refreshStatus} onsignedout={() => (signedIn = false)} />
            {/if}
          </div>
        </div>
      {:else}
      <div class="scroll" bind:this={scroller} onscroll={onScroll}>
        <div class="column">
          {#if !current}
            <Welcome {status} onpick={pick} />
          {:else if loading}
            <div class="loading"><Mark size={28} blink /></div>
          {:else}
            <Thread blocks={turn.blocks} {busy} {summary} onanswer={answer} workdir={status?.workdir} />
          {/if}
        </div>
      </div>

      <div class="dock">
        <div class="column">
          {#if !atBottom}
            <button class="jump" onclick={() => scrollToEnd(true)} aria-label="Jump to the latest"><Icon name="arrowdown" size={17} /></button>
          {/if}
          {#if trouble}<div class="trouble"><Icon name="alert" size={15} /> {trouble}</div>{/if}
          <Composer bind:this={composer} bind:value={draft} {busy} onsend={send} onstop={stop} />
          <div class="footnote">Runs on your computer. Nothing leaves it.</div>
        </div>
      </div>
      {/if}
    </main>
  </div>
{/if}

<style>
  .splash {
    height: 100%;
    display: grid;
    place-content: center;
    justify-items: center;
    gap: 16px;
    color: var(--muted);
    text-align: center;
    padding: 16px;
  }
  .app {
    height: 100%;
    display: grid;
    grid-template-columns: var(--sidebar) 1fr;
  }
  .side {
    min-height: 0;
  }
  .scrim {
    display: none;
  }
  main {
    min-width: 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
    position: relative;
  }
  header {
    display: none;
  }
  .scroll {
    flex: 1;
    overflow-y: auto;
    overscroll-behavior: contain;
    scrollbar-gutter: stable;
  }
  .column {
    width: 100%;
    max-width: var(--column);
    margin: 0 auto;
    padding: 0 24px;
  }
  .scroll .column {
    padding-top: 40px;
    padding-bottom: 24px;
  }
  .loading {
    display: grid;
    place-items: center;
    padding: 20vh 0;
  }
  .dock {
    padding: 0 0 max(12px, env(safe-area-inset-bottom));
    background: linear-gradient(transparent, var(--bg) 24px);
    margin-top: -24px;
    position: relative;
  }
  .dock .column {
    position: relative;
    padding-top: 24px;
  }
  .footnote {
    text-align: center;
    font-size: 12px;
    color: var(--subtle);
    padding-top: 8px;
  }
  .jump {
    position: absolute;
    top: -22px;
    left: 50%;
    transform: translateX(-50%);
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: grid;
    place-items: center;
    background: var(--bg3);
    border: 1px solid var(--border-strong);
    color: var(--text2);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
  }
  .trouble {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13.5px;
    color: var(--bad);
    padding: 0 6px 10px;
  }
  .icon-button {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: grid;
    place-items: center;
    color: var(--text2);
  }
  .icon-button:hover {
    background: var(--bg3);
  }

  @media (max-width: 860px) {
    .app {
      grid-template-columns: 1fr;
    }
    .side {
      position: fixed;
      inset: 0 auto 0 0;
      width: min(86vw, 320px);
      z-index: 20;
      transform: translateX(-100%);
      transition: transform 0.22s cubic-bezier(0.2, 0.8, 0.2, 1);
      box-shadow: 0 0 40px rgba(0, 0, 0, 0.5);
    }
    .drawer .side {
      transform: none;
    }
    .scrim {
      display: block;
      position: fixed;
      inset: 0;
      z-index: 10;
      background: rgba(0, 0, 0, 0.5);
      opacity: 0;
      pointer-events: none;
      transition: opacity 0.2s;
    }
    .drawer .scrim {
      opacity: 1;
      pointer-events: auto;
    }
    header {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 6px 8px;
      padding-top: max(6px, env(safe-area-inset-top));
      border-bottom: 1px solid var(--border);
      background: var(--bg);
    }
    .title {
      flex: 1;
      min-width: 0;
      text-align: center;
      font-weight: 600;
      font-size: 15px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .column {
      padding: 0 14px;
    }
    .scroll .column {
      padding-top: 20px;
    }
  }
</style>