samagotchi 0.180.0 → 0.181.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +46 -1
  3. data/bin/chi +10 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/bundles.md +7 -2
  6. data/docs/cli.md +16 -9
  7. data/docs/configuration.md +24 -4
  8. data/docs/internals/anthropic.md +4 -3
  9. data/docs/internals/background-tasks.md +2 -0
  10. data/docs/internals/block-renderers.md +9 -6
  11. data/docs/internals/objectives.md +9 -4
  12. data/docs/internals/web-frontend.md +67 -7
  13. data/docs/internals/working-set.md +24 -5
  14. data/docs/memory.md +3 -0
  15. data/docs/plugins.md +11 -4
  16. data/docs/sessions.md +1 -1
  17. data/docs/testing.md +1 -1
  18. data/lib/samagotchi/bundle_command.rb +4 -1
  19. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  21. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  22. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  23. data/lib/samagotchi/client.rb +8 -1
  24. data/lib/samagotchi/config.rb +6 -1
  25. data/lib/samagotchi/core_notice.rb +44 -0
  26. data/lib/samagotchi/host_address.rb +7 -0
  27. data/lib/samagotchi/host_config.rb +8 -5
  28. data/lib/samagotchi/host_registry.rb +26 -8
  29. data/lib/samagotchi/kernel_loop.rb +3 -2
  30. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  31. data/lib/samagotchi/llm/adapters.rb +2 -1
  32. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  33. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  34. data/lib/samagotchi/llm/chat_loop.rb +6 -5
  35. data/lib/samagotchi/llm/errors.rb +41 -3
  36. data/lib/samagotchi/llm/http.rb +85 -22
  37. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  38. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  39. data/lib/samagotchi/objectives.rb +7 -2
  40. data/lib/samagotchi/owner_lock.rb +2 -0
  41. data/lib/samagotchi/plugin/api.rb +4 -1
  42. data/lib/samagotchi/plugin/context.rb +9 -0
  43. data/lib/samagotchi/plugin/peer.rb +32 -15
  44. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  45. data/lib/samagotchi/row_refs.rb +14 -3
  46. data/lib/samagotchi/session_chain/delete.rb +6 -6
  47. data/lib/samagotchi/session_manager/removal.rb +2 -2
  48. data/lib/samagotchi/tool_ids.rb +19 -0
  49. data/lib/samagotchi/tool_runner.rb +8 -4
  50. data/lib/samagotchi/tools/registry.rb +3 -2
  51. data/lib/samagotchi/tools/task_runtime.rb +34 -0
  52. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  53. data/lib/samagotchi/version.rb +1 -1
  54. data/lib/samagotchi/web/public/app.js +10 -14
  55. data/lib/samagotchi/web/public/block_host.js +20 -20
  56. data/lib/samagotchi/web/public/block_renderers.css +5 -5
  57. data/lib/samagotchi/web/public/context_chips.js +3 -4
  58. data/lib/samagotchi/web/public/images.js +1 -1
  59. data/lib/samagotchi/web/public/index.html +24 -5
  60. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  61. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  62. data/lib/samagotchi/web/public/peer_chip.js +3 -3
  63. data/lib/samagotchi/web/public/peer_data.js +27 -15
  64. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  65. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  66. data/lib/samagotchi/web/public/session_view.js +4 -0
  67. data/lib/samagotchi/web/public/working_set.js +9 -3
  68. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  69. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  70. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  71. data/lib/samagotchi/web/public/ws_order.js +48 -0
  72. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  73. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  74. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  75. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  76. metadata +6 -1
@@ -53,6 +53,7 @@ import {
53
53
  steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
54
54
  } from "./working_set.js";
55
55
  import { serverSig } from "./ws_item_sig.js";
56
+ import { heldOrder, recencyOrder } from "./ws_order.js";
56
57
 
57
58
  // The popover's files fold to this many lines (groups open in place, one at
58
59
  // a time), its memories past this many to one group.
@@ -177,6 +178,10 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
177
178
  // lit on the session's list), the group open in it.
178
179
  let lens = null;
179
180
  let openGroup = null;
181
+ // The list's order taken at the open (ws_order.js): the item keys, last
182
+ // touched first. Held while it is open (rows that come go on top, the
183
+ // others stay); every open takes it again (null: closed).
184
+ let openKeys = null;
180
185
  // What the drawn list shows of the context's tokens (tokenText): a chunk's
181
186
  // new count redraws it only when that text changes.
182
187
  let shownTokens = null;
@@ -224,11 +229,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
224
229
  session,
225
230
  // Opened: the server's set asked again (a file changed while the
226
231
  // session sat idle shows stale).
232
+ // The order is taken again at each open (a footprint or the rail while
233
+ // it is open too: they open it again).
227
234
  show: (_data, opening) => {
235
+ if (opening) openKeys = recencyOrder(sessionSet().items).map(itemKey);
228
236
  draw();
229
237
  if (opening) fetchServer();
230
238
  },
231
- onClose: () => { openGroup = null; peek?.close(); onChange(); },
239
+ onClose: () => { openGroup = null; openKeys = null; peek?.close(); onChange(); },
232
240
  // The foot's + add (the popover's submit): one KEY as typed (quoted
233
241
  // when it has spaces).
234
242
  onSubmit: (form) => {
@@ -298,11 +306,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
298
306
  // the words, the edited mark) and nothing else.
299
307
  const item = touched ? lensItem(row0, touched) : row0;
300
308
  const lensClass = touched && !row0.added ? (touched.has(itemKey(row0)) ? " lit" : " dim") : "";
301
- // A dimmed row's entry is the session's (its first, "t1·s1"); a lit row's the turn's.
309
+ // A dimmed row's tag is the session's last touch ("t3·s4"; an older
310
+ // page's item: its first entry); a lit row's the turn's entry ("s3").
311
+ // By the lens class: a lit row carries the session's `last` too.
302
312
  const whole = inSession || lensClass === " dim";
313
+ const place = whole ? row0.last || row0.at : item.at;
303
314
  const fresh = isFresh(seenAt(row0), now);
304
315
  // A lit preloaded memory the turn read shows the turn's step, not "prompt".
305
- const tag = stepTag(lensClass === " lit" && item.at ? { ...item, preloaded: false } : item, { session: whole });
316
+ const tag = stepTag(lensClass === " lit" && item.at ? { ...item, preloaded: false } : { ...item, at: place }, { session: whole });
306
317
  const note = start && touched ? heldTwiceNote(row0, touched.get(itemKey(row0))) : "";
307
318
  // An added row's words: what it is (a phone's tap on them opens its strip).
308
319
  const what = start ? [memoryPartWords(row0), row0.state && row0.state !== "live" ? row0.state : ""].filter(Boolean).join(" · ") : opsText(item);
@@ -323,9 +334,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
323
334
  if (start && inSession && heldTwice(row0)) tagEl = html`<span class="ws-twice" title="already in the prompt and read again: held twice">held twice</span>`;
324
335
  else if (tag === "prompt") tagEl = start ? nothing : html`<span class="ws-step p" title="in the system prompt">prompt</span>`;
325
336
  else if (tag) {
326
- const prompt = whole ? promptOf(item.at.turn) : "";
327
- const where = whole ? `turn ${item.at.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${item.at.step + 1}` : `step ${item.at.step + 1}`;
328
- tagEl = html`<button type="button" class=${`ws-step${item.kind === "memory" ? " p" : ""}${note ? " twice" : ""}`} data-ws="jump" data-at=${atAttr(item.at)} title=${`entered at ${where}: go to the call`}>${tag}</button>`;
337
+ const prompt = whole ? promptOf(place.turn) : "";
338
+ const where = whole ? `turn ${place.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${place.step + 1}` : `step ${place.step + 1}`;
339
+ tagEl = html`<button type="button" class=${`ws-step${item.kind === "memory" ? " p" : ""}${note ? " twice" : ""}`} data-ws="jump" data-at=${atAttr(place)} title=${`${whole ? "last touched" : "entered"} at ${where}: go to the call`}>${tag}</button>`;
329
340
  }
330
341
  const edited = item.kind === "file" && item.ops.includes("edit");
331
342
  const state = row0.state && row0.state !== "live" ? ` ${row0.state}` : "";
@@ -367,8 +378,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
367
378
  const startRow = (row, opts) => (row.kind === "memory" ? rowTemplate(row, { ...opts, start: true }) : partRowTemplate(row, opts));
368
379
  const isLit = (item, opts) => !!opts.touched && opts.touched.has(itemKey(item));
369
380
 
370
- // The head view's sections (ws_sections.js headSections): each header
371
- // folds (per session, session_prefs.js WS_SECTION_FOLD); folded, a section
381
+ // The head view's sections (ws_sections.js headSections), read · talk ·
382
+ // start: each header folds (per session, session_prefs.js WS_SECTION_FOLD;
383
+ // none stored: start folded); folded, a section
372
384
  // shows only the rows the lens lights. Conversation is one row, no header,
373
385
  // no fold (a stored fold naming it is ignored).
374
386
  function headTemplate(sections, opts, folded) {
@@ -376,7 +388,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
376
388
  if (section.key === "talk") return html`<div class="ws-sec talk">${talkTemplate(section, opts)}</div>`;
377
389
  const open = !folded.has(section.key);
378
390
  const tokens = tokensText(section.tokens);
379
- const head = html`<button type="button" class="ws-sec-head" data-ws="section" data-id=${section.key} aria-expanded=${String(open)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${section.title}</span>${section.meta ? html`<span class="n">${section.meta}</span>` : nothing}${tokens ? html`<span class="tk">${tokens}</span>` : nothing}</button>`;
391
+ const head = html`<button type="button" class="ws-sec-head" data-ws="section" data-id=${section.key} aria-expanded=${String(open)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${section.title}</span>${section.meta ? html`<span class="n">${section.meta}</span>` : nothing}${section.twice ? html`<span class="w" title="in the prompt and read again: held twice">· ${section.twice} held twice</span>` : nothing}${tokens ? html`<span class="tk">${tokens}</span>` : nothing}</button>`;
380
392
  let body;
381
393
  if (section.inner) {
382
394
  body = open
@@ -409,7 +421,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
409
421
  }
410
422
 
411
423
  // The session's folded sections, and a toggle of one.
412
- const foldedNow = () => foldedSections(readPref(WS_SECTION_FOLD, session(), "[]"));
424
+ // Nothing stored (null, told from a stored []) is the default fold.
425
+ const foldedNow = () => foldedSections(readPref(WS_SECTION_FOLD, session(), null));
413
426
  function toggleSection(key) {
414
427
  const folded = foldedNow();
415
428
  if (folded.has(key)) folded.delete(key);
@@ -442,10 +455,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
442
455
  // session and is kept: the turn coming back lights it again.
443
456
  const at = curLens();
444
457
  const inSession = at === null;
445
- const set = sessionSet();
458
+ const full = sessionSet();
446
459
  const pend = pending();
447
460
  const forget = forgetOn(st.llmContext);
448
461
  const last = lastTurn();
462
+ // The list's order: last touched first, held while it is open
463
+ // (ws_order.js). Only the list's: rowItem, steer and the rail read the
464
+ // set as it is.
465
+ const set = { ...full, items: heldOrder(full.items, openKeys) };
449
466
  // The head view (no parts: today's list); a turn's read of `system/x`
450
467
  // lights the start row of `x`, and a prompt memory is never new.
451
468
  const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession });
@@ -3,10 +3,14 @@
3
3
  // read's lines draw as a read row's do (.read-line, numbered); an edit's
4
4
  // diff with diff_view.js, the same renderer as the tool row's and the
5
5
  // approval card's. A card chi no longer has is greyed, its text folded.
6
+ // A memory's text and a whole read of an .md file render as markdown once
7
+ // their HTML is there (ws_markdown.js; the +md+ option), with a
8
+ // "rendered | source" switch in the card's header.
6
9
 
7
10
  import { html, nothing } from "./vendor/lit-html.js";
8
11
  import { diffCounts, diffTemplate } from "./diff_view.js";
9
12
  import { eventTag, goneText, linesText, placeOf, SLICE_FOLD_LINES, tagsText } from "./ws_timeline.js";
13
+ import { markdownTemplate, renderable, sourceText } from "./ws_markdown.js";
10
14
 
11
15
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
12
16
 
@@ -34,23 +38,40 @@ export function callTemplate(event, item, label = "go to the call") {
34
38
  return html`<button type="button" class="wsr-call" data-ws="jump" data-at=${`${at.turn}.${at.step}.${at.row}`}>${label}</button>`;
35
39
  }
36
40
 
37
- function goneBody(card, rows, undrop) {
41
+ // The card's "rendered | source" switch (+view+ the one pressed).
42
+ function viewTemplate(view) {
43
+ const button = (name) => html`<button type="button" class=${view === name ? "on" : ""} aria-pressed=${String(view === name)} data-wsr="view" data-view=${name}>${name}</button>`;
44
+ return html`<span class="wsr-view" role="group" aria-label="Show as">${button("rendered")}${button("source")}</span>`;
45
+ }
46
+
47
+ // A text, rendered when +shown+ holds its markdown (else as sent).
48
+ const textOr = (text, shown) => shown ?? textTemplate(text);
49
+
50
+ function goneBody(card, rows, undrop, shown = null) {
38
51
  const words = goneText(card.state);
39
52
  const what = card.type === "slice" ? plural(rows.length, "line") : "its text";
40
53
  const offer = card.state === "dropped" && undrop !== nothing ? html` · ${undrop}` : nothing;
41
- return html`<div class="wsr-gone">${what} · ${words}${offer}</div><details class="wsr-had"><summary>what it was</summary>${card.type === "slice" ? linesTemplate(rows) : textTemplate(card.event.text)}</details>`;
54
+ const had = shown ?? (card.type === "slice" ? linesTemplate(rows) : textTemplate(card.event.text));
55
+ return html`<div class="wsr-gone">${what} · ${words}${offer}</div><details class="wsr-had"><summary>what it was</summary>${had}</details>`;
42
56
  }
43
57
 
44
- // A memory read's overlay part (ws_timeline: event.memory.overlay).
45
- function overlayTemplate(memory) {
58
+ // A memory read's overlay part (ws_timeline: event.memory.overlay),
59
+ // rendered with its card (+md+, +on+: the card shows rendered).
60
+ function overlayTemplate(memory, md = null, on = false) {
46
61
  if (!memory?.overlay) return nothing;
47
62
  const name = String(memory.overlay_path || "").split("/").pop();
48
- return html`<div class="wsr-overlay"><div class="wsr-overlay-h">+ overlay for this model${name ? ` · ${name}` : ""}</div>${textTemplate(memory.overlay)}</div>`;
63
+ // Asked with its card's text, so both come together.
64
+ const rendered = md ? markdownTemplate(memory.overlay, md) : null;
65
+ const shown = on ? rendered : null;
66
+ return html`<div class="wsr-overlay"><div class="wsr-overlay-h">+ overlay for this model${name ? ` · ${name}` : ""}</div>${textOr(memory.overlay, shown)}</div>`;
49
67
  }
50
68
 
51
69
  // One card. +item+: the open item (its runs: the step tags); +undrop+: the
52
- // greyed card's undrop button (a template), or nothing.
53
- export function cardTemplate(card, { item, undrop = nothing } = {}) {
70
+ // greyed card's undrop button (a template), or nothing; +md+ ({view,
71
+ // html(text)}: the reader's): a renderable card whose HTML is there gets
72
+ // the switch and, with +view+ "rendered", its markdown. Without it (an old
73
+ // reader), today's source.
74
+ export function cardTemplate(card, { item, undrop = nothing, md = null } = {}) {
54
75
  const gone = card.state && card.state !== "sent";
55
76
  const pill = gone ? html`<span class="wsr-pill gone">chi no longer has this</span>`
56
77
  : card.latest ? html`<span class="wsr-pill latest">latest</span>` : nothing;
@@ -58,10 +79,13 @@ export function cardTemplate(card, { item, undrop = nothing } = {}) {
58
79
  let meta = "";
59
80
  let body;
60
81
  let call;
82
+ const rendered = md && renderable(card, item) ? markdownTemplate(sourceText(card), md) : null;
83
+ const on = rendered !== null && md.view !== "source";
84
+ const shown = on ? rendered : null;
61
85
  if (card.type === "slice") {
62
86
  title = linesText(card);
63
87
  meta = `${plural(card.reads.length, "read")} · ${tagsText(card.reads, item)}`;
64
- body = gone ? goneBody(card, card.rows, undrop) : linesTemplate(card.rows);
88
+ body = gone ? goneBody(card, card.rows, undrop, shown) : shown ?? linesTemplate(card.rows);
65
89
  call = callTemplate(card.reads[0], item);
66
90
  } else {
67
91
  const { event } = card;
@@ -81,9 +105,11 @@ export function cardTemplate(card, { item, undrop = nothing } = {}) {
81
105
  title = `${words} · ${tag}`;
82
106
  const shared = event.shared_with?.length ? `read with ${event.shared_with.join(", ")}` : "";
83
107
  meta = shared;
84
- body = gone ? goneBody(card, [], undrop) : html`${textTemplate(event.text)}${card.type === "memory" ? overlayTemplate(event.memory) : nothing}`;
108
+ body = gone ? goneBody(card, [], undrop, shown) : html`${textOr(event.text, shown)}${card.type === "memory" ? overlayTemplate(event.memory, md, on) : nothing}`;
85
109
  }
86
110
  }
87
111
  const classes = `wsr-card ${card.type}${gone ? ` gone ${card.state}` : ""}${card.latest ? " latest" : ""}`;
88
- return html`<article class=${classes} data-newest=${card.newest}><header class="wsr-card-h"><span class="wsr-card-t">${title}</span>${meta ? html`<span class="wsr-card-m">${meta}</span>` : nothing}${pill}${call}</header>${body}</article>`;
112
+ const view = rendered !== null ? viewTemplate(on ? "rendered" : "source") : nothing;
113
+ const first = card.type === "slice" ? card.first : nothing;
114
+ return html`<article class=${classes} data-newest=${card.newest} data-first=${first}><header class="wsr-card-h"><span class="wsr-card-t">${title}</span>${meta ? html`<span class="wsr-card-m">${meta}</span>` : nothing}${pill}<span class="wsr-card-actions">${view}${call}</span></header>${body}</article>`;
89
115
  }
@@ -0,0 +1,129 @@
1
+ // Markdown in the working set's reader and peek (ws_cards.js, ws_reader.js,
2
+ // ws_peek.js): which texts render, the text to send, a leading front
3
+ // matter taken off, the HTML of each text kept for the page, and its
4
+ // template (lit: its spec loads dom_shim.js). The HTML comes from markdown_place.js
5
+ // renderMarkdown (POST /api/render, sanitised there); null is markdown off,
6
+ // a viewer that may not render, or a failed read: the source stays.
7
+ //
8
+ // What renders (docs/internals/web-frontend.md, The working set's reader):
9
+ // a memory's text (read, written, its overlay, the greyed "what it was") and
10
+ // a whole read of an .md file. A slice stays numbered source (it can start
11
+ // inside a fence or a list, and its line numbers are the strip's jumps); an
12
+ // edit or a write stays its diff; a fetch's text is not rendered.
13
+
14
+ import { html, nothing } from "./vendor/lit-html.js";
15
+ import { unsafeHTML } from "./vendor/directives/unsafe-html.js";
16
+
17
+ // The route's cap on its JSON body (web/message_display.rb MAX_RENDER_BYTES;
18
+ // block_host.js MAX_SOURCE_BYTES mirrors it too).
19
+ export const RENDER_MAX_BYTES = 64 * 1024;
20
+ // About how many texts the page keeps the HTML of.
21
+ const CACHE_MAX = 50;
22
+
23
+ const MD_FILE = /\.(md|markdown)$/i;
24
+ const MEMORY_CARDS = new Set(["memory", "written"]);
25
+ const MEMORY_OPS = new Set(["memory_read", "memory_write"]);
26
+
27
+ const markdownFile = (item) => item?.kind === "file" && MD_FILE.test(String(item.key || ""));
28
+
29
+ // A card (ws_timeline.js timelineCards) of +item+ that renders: a memory's,
30
+ // or a slice of an .md file that is the whole file (from line 1, one of its
31
+ // reads a whole one).
32
+ export function renderable(card, item) {
33
+ if (!card) return false;
34
+ if (MEMORY_CARDS.has(card.type)) return true;
35
+ if (card.type !== "slice" || card.first !== 1 || !markdownFile(item)) return false;
36
+ return (card.reads || []).some((read) => read?.lines?.whole);
37
+ }
38
+
39
+ // The same rule for the peek's event (ws_timeline.js peekOf): a memory read
40
+ // or write; a whole read of an .md file, not a preview of it.
41
+ export function renderableEvent(event, item) {
42
+ if (!event) return false;
43
+ if (MEMORY_OPS.has(event.op)) return true;
44
+ return event.op === "read" && !!event.lines?.whole && !event.lines?.partial && markdownFile(item);
45
+ }
46
+
47
+ // The text a card renders: a slice's lines, else its event's text.
48
+ export function sourceText(card) {
49
+ if (card?.type === "slice") return (card.rows || []).map((r) => r.text).join("\n");
50
+ return String(card?.event?.text ?? "");
51
+ }
52
+
53
+ const FRONT = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
54
+
55
+ // A leading YAML front matter block (a --- line closed by a --- line):
56
+ // {front, body}, +front+ without its last newline; "" when there is none.
57
+ export function splitFrontMatter(text) {
58
+ const all = String(text ?? "");
59
+ const found = all.match(FRONT);
60
+ if (!found) return { front: "", body: all };
61
+ return { front: found[0].replace(/\r?\n$/, ""), body: all.slice(found[0].length) };
62
+ }
63
+
64
+ // The peek's source and rendered body omit a leading front matter block.
65
+ // The reader uses splitFrontMatter separately so it keeps that block above
66
+ // the rendered body.
67
+ export function peekText(text) {
68
+ return splitFrontMatter(text).body;
69
+ }
70
+
71
+ const tooBig = (text) => new TextEncoder().encode(JSON.stringify({ text })).length > RENDER_MAX_BYTES;
72
+
73
+ // The page's HTML of each text: +html(text)+ answers the HTML, null (too big
74
+ // for the route: no request) or undefined while its one request is on its
75
+ // way (+onReady()+ runs when HTML comes). A null answer (markdown off, a
76
+ // failed read) is not kept, so the next draw asks again; at most one
77
+ // request per text at a time. Bounded (+max+), the least recently used
78
+ // text going first.
79
+ export function createRenderCache(renderMarkdown, onReady = () => {}, { max = CACHE_MAX } = {}) {
80
+ const kept = new Map();
81
+ const asking = new Set();
82
+
83
+ function html(text) {
84
+ const key = String(text ?? "");
85
+ if (kept.has(key)) {
86
+ const found = kept.get(key);
87
+ kept.delete(key);
88
+ kept.set(key, found);
89
+ return found;
90
+ }
91
+ if (tooBig(key)) return null;
92
+ if (asking.has(key)) return undefined;
93
+ asking.add(key);
94
+ let asked;
95
+ try {
96
+ asked = Promise.resolve(renderMarkdown(key));
97
+ } catch {
98
+ asked = Promise.resolve(null);
99
+ }
100
+ asked
101
+ .catch(() => null)
102
+ .then((answer) => {
103
+ asking.delete(key);
104
+ if (typeof answer !== "string" || !answer) return;
105
+ kept.set(key, answer);
106
+ while (kept.size > max) kept.delete(kept.keys().next().value);
107
+ onReady();
108
+ });
109
+ return undefined;
110
+ }
111
+
112
+ return { html };
113
+ }
114
+
115
+ // +text+ as markdown: its front matter as source, then the HTML (sanitised
116
+ // on the server, POST /api/render); null while its HTML isn't there
117
+ // (+md.html+: undefined on its way, null off or failed).
118
+ export function markdownTemplate(text, md) {
119
+ if (!md?.html) return null;
120
+ const { front, body } = splitFrontMatter(text);
121
+ const found = md.html(body);
122
+ if (typeof found !== "string") return null;
123
+ return html`${front ? html`<pre class="wsr-front">${front}</pre>` : nothing}<div class="wsr-md">${unsafeHTML(found)}</div>`;
124
+ }
125
+
126
+ // The peek renders only the front matter's body, without source above it.
127
+ export function peekMarkdownTemplate(text, md) {
128
+ return markdownTemplate(peekText(text), md);
129
+ }
@@ -0,0 +1,48 @@
1
+ // The working-set list's order (docs/internals/working-set.md, The list's
2
+ // order): last touched first, and held still while the list is open.
3
+ // recencyOrder newest `last` (else `at`) first: turn, then step, then
4
+ // row; the items with neither (a preloaded memory never
5
+ // read, a used memory no row explains) after the rest, in
6
+ // the order they came.
7
+ // heldOrder the order taken at the open (+openKeys+, the item keys
8
+ // drawn then): the items not in it on top, newest first,
9
+ // the others where they stood.
10
+ // Only the popover's list is ordered this way; the rail, the footprints and
11
+ // the reader's side list keep the set's entry order.
12
+ //
13
+ // No DOM: `node --test` covers the rules; working_set_view.js uses them.
14
+ // A module of its own: static JS is cached at unversioned URLs, and a new
15
+ // export on an old module would blank the page.
16
+ import { itemKey } from "./working_set.js";
17
+
18
+ // An item's newest place: its last touch, else its first entry (an older
19
+ // page's item has no `last`), else null.
20
+ const placeOf = (item) => item?.last || item?.at || null;
21
+
22
+ // Which of two places is newer: > 0 when +a+ is.
23
+ function newer(a, b) {
24
+ return (a.turn - b.turn) || (a.step - b.step) || (a.row - b.row);
25
+ }
26
+
27
+ // +items+ newest first (a copy; stable on ties).
28
+ export function recencyOrder(items) {
29
+ return (items || [])
30
+ .map((item, i) => ({ item, i, at: placeOf(item) }))
31
+ .sort((x, y) => {
32
+ if (x.at && y.at) return newer(y.at, x.at) || x.i - y.i;
33
+ if (x.at || y.at) return x.at ? -1 : 1;
34
+ return x.i - y.i;
35
+ })
36
+ .map((x) => x.item);
37
+ }
38
+
39
+ // +items+ in the order of +openKeys+ (the keys drawn at the open), the ones
40
+ // it doesn't hold before them, newest first; an item that left the set is
41
+ // simply not there. Without +openKeys+: recencyOrder.
42
+ export function heldOrder(items, openKeys) {
43
+ if (!Array.isArray(openKeys)) return recencyOrder(items);
44
+ const place = new Map(openKeys.map((key, i) => [key, i]));
45
+ const fresh = recencyOrder((items || []).filter((item) => !place.has(itemKey(item))));
46
+ const kept = (items || []).filter((item) => place.has(itemKey(item))).sort((a, b) => place.get(itemKey(a)) - place.get(itemKey(b)));
47
+ return [...fresh, ...kept];
48
+ }
@@ -14,6 +14,11 @@
14
14
  // asks again (refresh) only when the item's server signature changed
15
15
  // (+sigOf+: working_set.js serverSig): mid-turn the route answers the
16
16
  // running turn's view as of its last step.
17
+ //
18
+ // A memory's text and a whole read of an .md file show rendered, the whole
19
+ // text in the peek's scroll box, once their HTML is in the reader's cache
20
+ // (+md+: ws_markdown.js createRenderCache); else, and without +md+, the
21
+ // first lines as source.
17
22
 
18
23
  import { html, nothing } from "./vendor/lit-html.js";
19
24
  import { createLatest } from "./latest.js";
@@ -21,6 +26,11 @@ import { diffCounts, diffTemplate } from "./diff_view.js";
21
26
  import { callTemplate, linesTemplate, textTemplate } from "./ws_cards.js";
22
27
  import { countsText, eventTag, eventWords, peekOf } from "./ws_timeline.js";
23
28
  import { olderAnswer } from "./ws_item_sig.js";
29
+ import { peekMarkdownTemplate, peekText, renderableEvent } from "./ws_markdown.js";
30
+
31
+ // No events while a turn runs (the answer's +running+): the read is in the
32
+ // step whose tool batch hasn't ended.
33
+ const STEP_RUNNING = "chi read this in the step still running. It shows here when that step's tools finish.";
24
34
 
25
35
  // The popover's width while a row is peeked (it is 420 otherwise).
26
36
  export const PEEK_WIDTH = 520;
@@ -28,8 +38,9 @@ export const PEEK_WIDTH = 520;
28
38
  // +session()+: the open session's id; +getItem(id, kind, key, opts)+: the item
29
39
  // route's answer; +sigOf(item)+: its server signature (undefined: always ask
30
40
  // again); +onChange()+: the peek's content changed (the popover redraws and
31
- // places itself again).
32
- export function createPeek({ session, getItem, sigOf = () => undefined, onChange = () => {} }) {
41
+ // places itself again); +md+: the reader's markdown cache ({html(text)}),
42
+ // null: none.
43
+ export function createPeek({ session, getItem, sigOf = () => undefined, onChange = () => {}, md = null }) {
33
44
  let openId = null;
34
45
  let item = null;
35
46
  let data = null;
@@ -98,16 +109,22 @@ export function createPeek({ session, getItem, sigOf = () => undefined, onChange
98
109
  if (!data) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">Loading…</div></div>`;
99
110
  const events = data.events || [];
100
111
  const peek = peekOf(events);
101
- if (!peek) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">Nothing of it in the conversation yet.</div></div>`;
112
+ if (!peek) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">${data.running ? STEP_RUNNING : "Nothing of it in the conversation yet."}</div></div>`;
102
113
  const { event } = peek;
103
114
  const counts = peek.kind === "diff" && event.diff?.text && !event.diff.error && !event.diff.skipped ? diffCounts(event.diff) : "";
104
115
  const after = peek.after ? html`<span class="ws-peek-after">then ${eventWords(peek.after)} at ${eventTag(peek.after, row)}</span>` : nothing;
105
116
  const gone = event.sent === false ? html`<span class="wsr-pill gone">chi no longer has this</span>` : nothing;
106
117
  const head = html`<div class="ws-peek-h"><span class="ws-peek-t">latest · ${eventWords(event)} at ${eventTag(event, row)}</span>${counts ? html`<span class="ws-peek-c">${counts}</span>` : nothing}${gone}${after}</div>`;
107
118
  let body;
108
- if (peek.kind === "diff") body = diffTemplate(event.diff, { fold: 12 });
119
+ const markdown = peek.kind !== "diff" && renderableEvent(event, row);
120
+ const rendered = md && markdown ? peekMarkdownTemplate(event.text, md) : null;
121
+ if (rendered) body = rendered;
122
+ else if (peek.kind === "diff") body = diffTemplate(event.diff, { fold: 12 });
109
123
  else if (peek.kind === "lines") body = linesTemplate(peek.rows, { fold: Infinity });
110
- else body = textTemplate(peek.rows.map((r) => r.text).join("\n"), { fold: Infinity });
124
+ else {
125
+ const text = peek.rows.map((r) => r.text).join("\n");
126
+ body = textTemplate(markdown ? peekText(text) : text, { fold: Infinity });
127
+ }
111
128
  const words = countsText(events, data.counts);
112
129
  const foot = html`<div class="ws-peek-f"><button type="button" class="ws-peek-open" data-ws="timeline" data-ws-id=${openId}>Open the timeline${words ? html`<span class="ws-peek-n"> · ${words}</span>` : nothing}</button>${callTemplate(event, row)}</div>`;
113
130
  return html`<div class="ws-peek" role="region" aria-label="What chi has">${head}<div class="ws-peek-b">${body}</div>${foot}</div>`;
@@ -69,7 +69,8 @@
69
69
  .wsr-card-h{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:6px 12px;border-bottom:1px solid var(--border);background:var(--bg-raised);font-size:12px}
70
70
  .wsr-card-t{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--text)}
71
71
  .wsr-card-m{color:var(--ws-faint)}
72
- .wsr-card-h .wsr-call{margin-left:auto;font-size:12px}
72
+ .wsr-card-actions{display:inline-flex;align-items:center;gap:6px;margin-left:auto;white-space:nowrap}
73
+ .wsr-card-h .wsr-call{margin-left:0;font-size:12px}
73
74
  .wsr-pill{padding:0 6px;border-radius:4px;font-size:11px}
74
75
  .wsr-pill.latest{background:var(--accent-bg);color:var(--accent)}
75
76
  .wsr-pill.gone{background:var(--badge-bg);color:var(--text-muted)}
@@ -81,6 +82,37 @@
81
82
  .wsr-had>summary{cursor:pointer}
82
83
  .wsr-overlay{margin:0 10px 10px;padding:6px 0 0;border:1px dashed var(--border-strong);border-radius:6px}
83
84
  .wsr-overlay-h{padding:0 10px;font-size:11.5px;color:var(--ws-muted)}
85
+ /* Markdown (ws_markdown.js): a memory's text, a whole read of an .md file; the answers' values, scoped here. */
86
+ .wsr-md{padding:10px 14px;font-size:13.5px;line-height:1.55;color:var(--text-2);white-space:normal;overflow-wrap:anywhere}
87
+ .wsr-md :is(h1,h2,h3,h4,h5,h6){margin:16px 0 6px;font-weight:600;line-height:1.3;color:var(--text-bright)}
88
+ .wsr-md>:is(h1,h2,h3,h4,h5,h6):first-child{margin-top:2px}
89
+ .wsr-md h1{font-size:18px}
90
+ .wsr-md h2{font-size:16px}
91
+ .wsr-md h3{font-size:15px}
92
+ .wsr-md :is(h4,h5,h6){font-size:14px;color:var(--text-2)}
93
+ .wsr-md :is(p,ul,ol,blockquote,table,pre){margin:0 0 10px}
94
+ .wsr-md>:last-child{margin-bottom:0}
95
+ .wsr-md :is(ul,ol){padding-left:1.5em}
96
+ .wsr-md li+li{margin-top:3px}
97
+ .wsr-md li>:is(ul,ol){margin:3px 0 0}
98
+ .wsr-md strong{color:var(--text-bright)}
99
+ .wsr-md a{color:var(--accent)}
100
+ .wsr-md hr{border:0;border-top:1px solid var(--border);margin:12px 0}
101
+ .wsr-md code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.88em}
102
+ .wsr-md :not(pre)>code{padding:1px 4px;border:1px solid var(--border);border-radius:4px;background:var(--bg-inset);color:var(--text)}
103
+ .wsr-md pre{overflow-x:auto;padding:8px 10px;border:1px solid var(--border);border-radius:6px;background:var(--bg-inset);font-size:12.5px;line-height:1.45;white-space:pre;overflow-wrap:normal}
104
+ .wsr-md blockquote{padding-left:12px;border-left:3px solid var(--border-strong);color:var(--text-muted)}
105
+ .wsr-md table{display:block;max-width:100%;overflow-x:auto;border-collapse:collapse}
106
+ .wsr-md :is(th,td){padding:4px 8px;border:1px solid var(--border-strong);font-size:13px;overflow-wrap:normal}
107
+ .wsr-md th{background:var(--bg-inset);font-weight:600}
108
+ .wsr-front{margin:0;padding:6px 14px;border-bottom:1px solid var(--border);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px;line-height:16px;white-space:pre-wrap;word-break:break-word;color:var(--text-faint)}
109
+ /* The card's "rendered | source" switch, as the list's lens. */
110
+ .wsr-view{display:inline-flex;gap:2px}
111
+ .wsr-view button{padding:1px 8px;border:1px solid transparent;border-radius:999px;background:transparent;color:var(--text-muted);font-size:11px;line-height:16px;cursor:pointer}
112
+ .wsr-view button.on{color:var(--text-2);border-color:var(--border-strong);background:var(--bg-inset)}
113
+ .wsr-view button:hover:not(:disabled){filter:none}@media(hover:hover){.wsr-view button:hover{color:var(--text)}}
114
+ .ws-peek-b .wsr-md{max-height:220px;overflow:auto;font-size:12.5px}
115
+ .ws-peek-b .wsr-front{font-size:11px}
84
116
  .wsr-banner{flex:none;margin:10px 20px 0;padding:8px 10px;border:1px solid var(--warn-border);border-radius:8px;background:var(--warn-bg);color:var(--warn-text);font-size:12.5px;line-height:18px}
85
117
  .wsr-tabs{flex:none;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));margin:10px 20px 0;padding:2px;border-radius:8px;background:var(--bg-inset);max-width:420px}
86
118
  .wsr-tabs button{height:32px;border:0;border-radius:6px;background:transparent;color:var(--text-muted);font-size:13px;cursor:pointer}
@@ -116,8 +148,16 @@
116
148
  .wsr-bar{height:8px}
117
149
  .wsr-body{padding:10px 0;gap:10px}
118
150
  .wsr-card{border-left:0;border-right:0;border-radius:0}
151
+ .wsr-card-h{flex-wrap:wrap;gap:6px;padding:6px 8px}
152
+ .wsr-card-t{flex:1 1 160px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
153
+ .wsr-card-actions{flex:none;margin-left:auto}
154
+ .wsr-card-h .wsr-call{white-space:nowrap}
119
155
  .wsr-lines{font-size:11.5px;line-height:18px}
120
156
  .wsr-card .read-lines code{min-width:max-content}
157
+ .wsr-view{flex:none}
158
+ .wsr-view button{position:relative;min-height:20px;padding:1px 8px}
159
+ .wsr-view button::after{content:"";position:absolute;inset:-12px 0}
160
+ .wsr-md{padding:10px 14px}
121
161
  .wsr-banner,.wsr-tabs{margin:10px 12px 0}
122
162
  .wsr-tabs{max-width:none}
123
163
  .wsr-from{padding:8px 14px}
@@ -22,6 +22,11 @@
22
22
  // the running turn's view as of its last step. Leaving the
23
23
  // session (another one, the start page) resets it: session_view.js
24
24
  // forgetSession calls reset(), so #center is never left inert under it.
25
+ //
26
+ // Markdown (+renderMarkdown+, markdown_place.js): a memory's text and a
27
+ // whole read of an .md file render, in the reader and the peek, from one
28
+ // cache (ws_markdown.js); the reader's cards carry a "rendered | source"
29
+ // switch, one choice per open item, back to rendered when another opens.
25
30
 
26
31
  import { html, nothing, render } from "./vendor/lit-html.js";
27
32
  import { api } from "./data.js";
@@ -32,6 +37,7 @@ import { setTimelineWayIn } from "./ws_way_in.js";
32
37
  import { cardTemplate } from "./ws_cards.js";
33
38
  import { bandBox, countsText, eventTag, fileStrip, itemPath, linesText, timelineCards } from "./ws_timeline.js";
34
39
  import { olderAnswer } from "./ws_item_sig.js";
40
+ import { createRenderCache } from "./ws_markdown.js";
35
41
  import { GLYPHS, leafText, opsText, steerId, steerLine, tokensText } from "./working_set.js";
36
42
 
37
43
  // The item route's answer for session +id+ (+now+: a memory's text now;
@@ -41,6 +47,10 @@ export function getWorkingSetItem(id, kind, key, { now = false, latest = false }
41
47
  }
42
48
 
43
49
  const PHONE_MAX = 600;
50
+ // An item with no events while a turn runs (the answer's +running+): its
51
+ // read is in the step whose tool batch hasn't ended (the route answers the
52
+ // turn as of its last step).
53
+ const STEP_RUNNING = "chi read this in the step still running. It shows here when that step's tools finish.";
44
54
 
45
55
  // The head's pill: what is true of the item as a whole.
46
56
  function itemPill(item, events) {
@@ -62,9 +72,10 @@ function itemName(item) {
62
72
  // +centerEl+: what the reader covers (#center); +session()+, +state()+: the
63
73
  // open session's id and fields (its folder: the undrop line); +getItem+: the
64
74
  // item route (tests pass a stand-in); +sendLine(line)+: a steer line
65
- // (undrop; null: none).
75
+ // (undrop; null: none); +renderMarkdown(text)+: a text's markdown HTML or
76
+ // null (none: every text as its source).
66
77
  export function createWorkingSetPreview({ centerEl, session, state = () => ({}), getItem = getWorkingSetItem, sendLine = null,
67
- doc = document, win = window }) {
78
+ renderMarkdown = null, doc = document, win = window }) {
68
79
  let workingSet = null;
69
80
  // The open item ({kind, key}), its answer, the memory's now, the tab.
70
81
  let open = null;
@@ -73,9 +84,16 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
73
84
  let tab = "has";
74
85
  let openFor = null;
75
86
  let askedSig;
87
+ // The open item's "rendered | source".
88
+ let view = "rendered";
76
89
  const latest = createLatest(() => `${session()}|${open ? `${open.kind}:${open.key}` : ""}`);
77
90
  const sigOf = (it) => workingSet?.serverSig?.(it);
78
- const peek = createPeek({ session, getItem, sigOf, onChange: () => workingSet?.peekChanged() });
91
+ // One cache for both places: HTML that came redraws the open one(s).
92
+ const cache = renderMarkdown ? createRenderCache(renderMarkdown, () => {
93
+ if (open && !el.hidden) draw();
94
+ if (peek.any()) workingSet?.peekChanged();
95
+ }) : null;
96
+ const peek = createPeek({ session, getItem, sigOf, onChange: () => workingSet?.peekChanged(), md: cache });
79
97
 
80
98
  const el = doc.createElement("section");
81
99
  el.className = "ws-reader";
@@ -169,9 +187,12 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
169
187
  let body;
170
188
  if (failed) body = html`<div class="wsr-note">Couldn't load what chi has of it.</div>`;
171
189
  else if (!data) body = html`<div class="wsr-note">Loading…</div>`;
172
- else if (!cards.length) body = html`<div class="wsr-note">Nothing of it in the conversation yet: a running turn's reads show at its next step.</div>`;
190
+ else if (!cards.length) body = html`<div class="wsr-note">${data.running ? STEP_RUNNING : "Nothing of it in the conversation yet: a running turn's reads show at its next step."}</div>`;
173
191
  else if (memory?.nowBody) body = memory.nowBody;
174
- else body = cards.map((card) => cardTemplate(card, { item, undrop }));
192
+ else {
193
+ const md = cache ? { view, html: cache.html } : null;
194
+ body = cards.map((card) => cardTemplate(card, { item, undrop, md }));
195
+ }
175
196
  const list = shown();
176
197
  const at = list.findIndex((it) => it.kind === item.kind && it.key === item.key);
177
198
  const tpl = html`<div class="wsr-main">
@@ -200,6 +221,7 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
200
221
  data = null;
201
222
  failed = false;
202
223
  tab = "has";
224
+ view = "rendered";
203
225
  }
204
226
  if (el.hidden) {
205
227
  const active = doc.activeElement;
@@ -262,9 +284,16 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
262
284
  else if (what === "tab") {
263
285
  tab = act.dataset.tab === "now" ? "now" : "has";
264
286
  draw();
287
+ } else if (what === "view") {
288
+ view = act.dataset.view === "source" ? "source" : "rendered";
289
+ draw();
265
290
  } else if (what === "band") {
291
+ // The slice holding the band's first line; a rendered one has no
292
+ // numbered lines: the slice its first line falls in (data-first).
266
293
  const first = Number(act.dataset.first);
267
- const card = [...el.querySelectorAll(".wsr-card.slice")].find((c) => c.querySelector(`.read-line[data-line="${first}"]`));
294
+ const slices = [...el.querySelectorAll(".wsr-card.slice")];
295
+ const card = slices.find((c) => c.querySelector(`.read-line[data-line="${first}"]`))
296
+ || slices.filter((c) => Number(c.dataset.first) <= first).sort((a, b) => Number(b.dataset.first) - Number(a.dataset.first))[0];
268
297
  card?.scrollIntoView?.({ block: "start" });
269
298
  } else if (what === "undrop" && sendLine) {
270
299
  const item = current();