samagotchi 0.178.0 → 0.180.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 (141) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -1
  3. data/docs/architecture.md +4 -2
  4. data/docs/bundles.md +48 -8
  5. data/docs/cli.md +3 -1
  6. data/docs/configuration.md +1 -1
  7. data/docs/context.md +32 -1
  8. data/docs/guardrails.md +2 -1
  9. data/docs/internals/attached-context.md +26 -4
  10. data/docs/internals/background-tasks.md +5 -1
  11. data/docs/internals/block-renderers.md +4 -3
  12. data/docs/internals/bridge.md +11 -2
  13. data/docs/internals/bundles.md +65 -34
  14. data/docs/internals/engine.md +1 -1
  15. data/docs/internals/web-frontend.md +81 -3
  16. data/docs/plugins.md +20 -5
  17. data/docs/releasing.md +3 -3
  18. data/docs/scheduling.md +4 -0
  19. data/docs/sessions.md +8 -2
  20. data/docs/testing.md +8 -1
  21. data/lib/samagotchi/block_renderers.rb +33 -16
  22. data/lib/samagotchi/bootstrap/bundles.rb +2 -2
  23. data/lib/samagotchi/bootstrap_command.rb +1 -1
  24. data/lib/samagotchi/bridge/card_wait.rb +34 -0
  25. data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
  26. data/lib/samagotchi/bundle_command/check.rb +10 -10
  27. data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
  28. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  29. data/lib/samagotchi/bundle_command.rb +22 -18
  30. data/lib/samagotchi/bundle_manifest.rb +579 -0
  31. data/lib/samagotchi/bundle_needs.rb +9 -8
  32. data/lib/samagotchi/bundle_settings_check.rb +13 -9
  33. data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
  34. data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
  35. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  41. data/lib/samagotchi/config.rb +2 -2
  42. data/lib/samagotchi/context_absorber.rb +36 -6
  43. data/lib/samagotchi/context_note.rb +8 -5
  44. data/lib/samagotchi/context_providers.rb +30 -29
  45. data/lib/samagotchi/context_sources.rb +42 -12
  46. data/lib/samagotchi/engine/messages.rb +1 -1
  47. data/lib/samagotchi/events.rb +6 -5
  48. data/lib/samagotchi/guardrail_wiring.rb +20 -21
  49. data/lib/samagotchi/guardrails/approval.rb +3 -2
  50. data/lib/samagotchi/guardrails/outside.rb +3 -3
  51. data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
  52. data/lib/samagotchi/installed_bundles/dir.rb +91 -0
  53. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
  54. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
  55. data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
  56. data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
  57. data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
  58. data/lib/samagotchi/installed_bundles/sha.rb +41 -0
  59. data/lib/samagotchi/installed_bundles/standing.rb +65 -0
  60. data/lib/samagotchi/installed_bundles.rb +105 -0
  61. data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
  62. data/lib/samagotchi/memory_bundle/builder.rb +13 -13
  63. data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
  64. data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
  65. data/lib/samagotchi/memory_bundle/installer.rb +33 -33
  66. data/lib/samagotchi/memory_bundle/listing.rb +5 -5
  67. data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
  68. data/lib/samagotchi/memory_bundle/merger.rb +15 -15
  69. data/lib/samagotchi/memory_bundle/profile.rb +8 -8
  70. data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
  71. data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
  72. data/lib/samagotchi/memory_bundle/shas.rb +2 -2
  73. data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
  74. data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
  75. data/lib/samagotchi/memory_bundle/status.rb +19 -16
  76. data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
  77. data/lib/samagotchi/memory_bundle/trash.rb +2 -2
  78. data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
  79. data/lib/samagotchi/memory_bundle.rb +2 -2
  80. data/lib/samagotchi/memory_command.rb +4 -4
  81. data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
  82. data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
  83. data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
  84. data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
  85. data/lib/samagotchi/memory_usage.rb +5 -5
  86. data/lib/samagotchi/muted_memories.rb +1 -1
  87. data/lib/samagotchi/peer_exchanges.rb +76 -0
  88. data/lib/samagotchi/plugin/context.rb +4 -0
  89. data/lib/samagotchi/plugin/loader.rb +35 -33
  90. data/lib/samagotchi/plugin/peer.rb +42 -11
  91. data/lib/samagotchi/project_subfolders.rb +9 -9
  92. data/lib/samagotchi/reply_wait/target.rb +11 -4
  93. data/lib/samagotchi/self_report.rb +14 -14
  94. data/lib/samagotchi/session_access/local.rb +16 -1
  95. data/lib/samagotchi/session_access/remote.rb +2 -1
  96. data/lib/samagotchi/session_config.rb +29 -19
  97. data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
  98. data/lib/samagotchi/session_retention.rb +13 -4
  99. data/lib/samagotchi/session_stores.rb +3 -0
  100. data/lib/samagotchi/system_prompt.rb +4 -4
  101. data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
  102. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  103. data/lib/samagotchi/terminal_ui/formatting.rb +15 -5
  104. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  105. data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
  106. data/lib/samagotchi/terminal_ui.rb +4 -1
  107. data/lib/samagotchi/testing/bundle.rb +3 -3
  108. data/lib/samagotchi/testing/install.rb +3 -3
  109. data/lib/samagotchi/testing/sandbox.rb +2 -2
  110. data/lib/samagotchi/tool_runner.rb +14 -14
  111. data/lib/samagotchi/tools/memory.rb +22 -22
  112. data/lib/samagotchi/tools/task_runtime.rb +12 -3
  113. data/lib/samagotchi/update_command.rb +4 -4
  114. data/lib/samagotchi/version.rb +1 -1
  115. data/lib/samagotchi/web/app.rb +14 -1
  116. data/lib/samagotchi/web/message_display.rb +6 -0
  117. data/lib/samagotchi/web/participant_view.rb +1 -1
  118. data/lib/samagotchi/web/proxy_gate.rb +1 -0
  119. data/lib/samagotchi/web/public/app.js +13 -1
  120. data/lib/samagotchi/web/public/card_kinds.js +8 -3
  121. data/lib/samagotchi/web/public/cards_place.js +15 -1
  122. data/lib/samagotchi/web/public/context_chips.js +184 -49
  123. data/lib/samagotchi/web/public/ctx.js +1 -1
  124. data/lib/samagotchi/web/public/history_shape.js +8 -3
  125. data/lib/samagotchi/web/public/index.html +66 -0
  126. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  127. data/lib/samagotchi/web/public/peer_data.js +119 -0
  128. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  129. data/lib/samagotchi/web/public/peer_links.js +161 -0
  130. data/lib/samagotchi/web/public/peer_note.js +49 -0
  131. data/lib/samagotchi/web/public/session_view.js +6 -1
  132. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  133. data/lib/samagotchi/web/public/turn_block.js +46 -8
  134. data/lib/samagotchi/web/public/turn_html.js +11 -2
  135. data/lib/samagotchi/web/public/turn_settle.js +117 -0
  136. data/lib/samagotchi/web/push/notifier.rb +2 -2
  137. data/lib/samagotchi/web/session_access_routes.rb +21 -1
  138. data/lib/samagotchi/web/session_hub.rb +20 -4
  139. data/lib/samagotchi/worker_boot.rb +4 -1
  140. metadata +24 -12
  141. data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
@@ -0,0 +1,119 @@
1
+ // The open session's peers as the page knows them: GET …/peers (owner only,
2
+ // read from the session's files: its peer sources and the exchange log), and
3
+ // one small model of it that the conversation (peer_links.js) and, later,
4
+ // the peer chips share. docs/internals/web-frontend.md, The peer exchange.
5
+ // Its own module: new exports go in new modules (web-frontend.md).
6
+
7
+ import { api } from "./data.js";
8
+ import { createLatest } from "./latest.js";
9
+
10
+ // GET /api/sessions/:id/peers → {peers: [{name, label, inbox, outbox,
11
+ // exchanges: [newest first]}]}. An older chi web has no route: its 404 is
12
+ // an empty list here, on its own (any other failure throws).
13
+ export async function listPeers(id, opts = {}) {
14
+ try {
15
+ return await api(`/api/sessions/${encodeURIComponent(id)}/peers`, opts);
16
+ } catch (error) {
17
+ if (error?.status === 404) return { peers: [] };
18
+ throw error;
19
+ }
20
+ }
21
+
22
+ // How often a waiting exchange is read again (its age moves on).
23
+ export const WAITING_TICK_MS = 60_000;
24
+
25
+ // How many exchanges GET …/peers gives a peer at most (PeerExchanges.joined
26
+ // last: 20): a full list may leave older sends out.
27
+ export const EXCHANGES_CAP = 20;
28
+
29
+ // The model. +sessionId+() the open session; +hasPeer+() whether it has a
30
+ // peer at all (a context row with `peer`, a drawn send or answer): without
31
+ // one, refresh asks nothing. +onChange+() after each read for the open
32
+ // session (also a failed one: what is drawn may follow it). +list+: the
33
+ // fetch (listPeers). +win+: focus and the waiting tick.
34
+ //
35
+ // @return {refresh(), exchange(id), answer(name, serial, re), peer(name), touch(), loaded(), clear(), peers()}
36
+ export function createPeers({ sessionId, hasPeer = () => false, onChange = () => {}, list = listPeers,
37
+ win = globalThis, tickMs = WAITING_TICK_MS } = {}) {
38
+ // The last read: {id: the session it is for, peers}.
39
+ let data = null;
40
+ let tick = null;
41
+ // Only the newest read for the open session is kept (latest.js).
42
+ const latest = createLatest(() => sessionId());
43
+
44
+ const current = () => (data && data.id === sessionId() ? data.peers : []);
45
+
46
+ function stopTick() {
47
+ if (tick !== null) win.clearInterval?.(tick);
48
+ tick = null;
49
+ }
50
+
51
+ // One interval while an exchange waits, none otherwise.
52
+ function syncTick() {
53
+ const waiting = current().some((peer) => (peer.exchanges || []).some((ex) => ex?.state === "waiting"));
54
+ if (!waiting) stopTick();
55
+ else if (tick === null && win.setInterval) tick = win.setInterval(() => refresh(), tickMs);
56
+ }
57
+
58
+ async function refresh() {
59
+ const id = sessionId();
60
+ if (!id || !hasPeer()) return false;
61
+ const fresh = latest.begin();
62
+ try {
63
+ const answer = await list(id);
64
+ if (!fresh()) return false;
65
+ data = { id, peers: Array.isArray(answer?.peers) ? answer.peers : [] };
66
+ } catch {
67
+ // Unreachable for now: what was read stays.
68
+ if (!fresh()) return false;
69
+ }
70
+ syncTick();
71
+ onChange();
72
+ return true;
73
+ }
74
+
75
+ // The newest exchange of send +id+ (a resend has one id), with its
76
+ // peer's name; null when none is read.
77
+ function exchange(id) {
78
+ if (!id) return null;
79
+ let found = null;
80
+ for (const peer of current()) {
81
+ for (const ex of peer.exchanges || []) {
82
+ if (ex?.id === id && (!found || Date.parse(ex.at || "") > Date.parse(found.at || ""))) found = { ...ex, peer: peer.name };
83
+ }
84
+ }
85
+ return found;
86
+ }
87
+
88
+ // The send answer +serial+ of peer +name+ answers: the exchange its
89
+ // serial (its outbox revision's, the note's) is in, when that one is a
90
+ // send's; else the send +re+ names (a second answer to one send is an
91
+ // unclaimed row of its own on the server); null for an answer no send
92
+ // claims.
93
+ function answer(name, serial, re = null) {
94
+ const peer = current().find((p) => p.name === name);
95
+ if (!peer) return null;
96
+ const exchanges = peer.exchanges || [];
97
+ const bySerial = serial !== null && serial !== undefined && serial !== ""
98
+ ? exchanges.find((ex) => ex?.answer && String(ex.answer.serial) === String(serial)) : null;
99
+ const ex = bySerial?.id ? bySerial : (re ? exchanges.find((e) => e?.id === re) : null);
100
+ return ex ? { ...ex, peer: peer.name } : null;
101
+ }
102
+
103
+ function clear() {
104
+ latest.drop();
105
+ data = null;
106
+ stopTick();
107
+ }
108
+
109
+ win.addEventListener?.("focus", () => refresh());
110
+
111
+ return {
112
+ refresh, exchange, answer, clear, peers: current,
113
+ loaded: () => !!data && data.id === sessionId(),
114
+ // Peer +name+ as the last read gives it, or null (not paired, detached).
115
+ peer: (name) => current().find((p) => p.name === name) || null,
116
+ // What is drawn follows the read again without a fetch (a turn ended).
117
+ touch: () => { if (data && data.id === sessionId()) onChange(); },
118
+ };
119
+ }
@@ -0,0 +1,83 @@
1
+ // A peer exchange as the conversation shows it (docs/internals/web-frontend.md,
2
+ // The peer exchange): a send row's peer ref, the exchange's state as words
3
+ // ("waiting 2m", "changes · answered after 6m") and the send row's pill. Pure:
4
+ // no fetch, no DOM; the state and the verdict come from the server
5
+ // (GET …/peers: PeerExchanges.joined), never joined or parsed here.
6
+ // Its own module: new exports go in new modules (web-frontend.md).
7
+
8
+ import { html, nothing } from "./vendor/lit-html.js";
9
+
10
+ // The ref of kind peer on a tool row (a peer tool's send: Plugin::Peer's
11
+ // refs, {kind: "peer", target: {id}}), or null.
12
+ export function peerRef(row) {
13
+ const refs = Array.isArray(row?.refs) ? row.refs : [];
14
+ return refs.find((ref) => ref?.kind === "peer" && typeof ref.target?.id === "string" && ref.target.id) || null;
15
+ }
16
+
17
+ // A stretch of time as the pill says it: "<1m", "6m", "2h", "3d".
18
+ export function spanText(ms) {
19
+ const s = Math.max(0, Math.floor(Number(ms) / 1000) || 0);
20
+ if (s < 60) return "<1m";
21
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
22
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
23
+ return `${Math.floor(s / 86400)}d`;
24
+ }
25
+
26
+ const since = (from, to) => {
27
+ const a = Date.parse(from || "");
28
+ const b = typeof to === "number" ? to : Date.parse(to || "");
29
+ return Number.isNaN(a) || Number.isNaN(b) ? null : b - a;
30
+ };
31
+
32
+ // The verdict word of an answer (the server's, one of OK, CHANGES,
33
+ // UNSURE), lower case; "" for none.
34
+ export function verdictWord(verdict) {
35
+ return ["OK", "CHANGES", "UNSURE"].includes(verdict) ? verdict.toLowerCase() : "";
36
+ }
37
+
38
+ // The exchange's state in words. +ended+: the row's turn has ended (a row
39
+ // whose id has no exchange then reads "not sent": the send never went out);
40
+ // +short+: the phone's words. "" when there is nothing to say (a context
41
+ // send expects no answer; an exchange not read yet in a running turn).
42
+ export function stateText(exchange, { now = Date.now(), short = false, ended = false } = {}) {
43
+ if (!exchange) return ended ? "not sent" : "";
44
+ if (exchange.state === "failed") return "not sent";
45
+ if (exchange.state === "none_expected") return "";
46
+ if (exchange.state === "waiting") {
47
+ const age = since(exchange.at, now);
48
+ return age === null ? "waiting" : `waiting ${spanText(age)}`;
49
+ }
50
+ if (exchange.state !== "answered") return "";
51
+ const took = since(exchange.at, exchange.answer?.at);
52
+ const verdict = verdictWord(exchange.answer?.verdict);
53
+ const after = took === null ? "" : `after ${spanText(took)}`;
54
+ if (!verdict) return after ? `answered ${after}` : "answered";
55
+ if (short) return after ? `${verdict} · ${after}` : verdict;
56
+ return after ? `${verdict} · answered ${after}` : `${verdict} · answered`;
57
+ }
58
+
59
+ // The pill's tint: the verdict's for an answer, else the state's.
60
+ function pillKind(exchange, text) {
61
+ if (!exchange) return text ? "failed" : "";
62
+ if (exchange.state === "answered") return verdictWord(exchange.answer?.verdict) || "answered";
63
+ return exchange.state;
64
+ }
65
+
66
+ // The send row's pill: a button that jumps to the answer (↓) once answered,
67
+ // a span otherwise, nothing when stateText has no words. Its long and short
68
+ // words both drawn (CSS shows the phone's under 600 px). +title+: the row's
69
+ // output text (its output line is hidden on a send that went out).
70
+ export function pillTemplate(exchange, { now = Date.now(), ended = false, title = "" } = {}) {
71
+ const long = stateText(exchange, { now, ended });
72
+ if (!long) return nothing;
73
+ const short = stateText(exchange, { now, ended, short: true });
74
+ const cls = `peer-state ${pillKind(exchange, long)}`;
75
+ const words = short === long
76
+ ? html`<span class="peer-long">${long}</span>`
77
+ : html`<span class="peer-long">${long}</span><span class="peer-short">${short}</span>`;
78
+ if (exchange?.state === "answered") {
79
+ return html`<button type="button" class=${cls} data-peer-jump="answer" title=${title || nothing}
80
+ aria-label=${`${long}: go to the answer`}>${words}<span aria-hidden="true"> ↓</span></button>`;
81
+ }
82
+ return html`<span class=${cls} title=${title || nothing}>${words}</span>`;
83
+ }
@@ -0,0 +1,161 @@
1
+ // The peer exchange in the conversation: the controller that draws what the
2
+ // peers model (peer_data.js) knows into the slots the templates leave
3
+ // (turn_html.js: a send row's `.peer-slot`; peer_note.js: an answer's ↑ and
4
+ // "Read the full answer"), and the jumps between a send and its answer.
5
+ // Finished rows are never drawn again and a reload makes them anew, so the
6
+ // state that comes later is drawn here: after each history draw
7
+ // (session_view.js renderSessionView) and on the model's onChange.
8
+ // docs/internals/web-frontend.md, The peer exchange.
9
+ // Its own module: new exports go in new modules (web-frontend.md).
10
+
11
+ import { html, nothing, render } from "./vendor/lit-html.js";
12
+ import { pillTemplate } from "./peer_exchange.js";
13
+ import { EXCHANGES_CAP } from "./peer_data.js";
14
+ import { showRow } from "./refs.js";
15
+ import { revealInHistory } from "./history_reveal.js";
16
+
17
+ const SLOTS = ".peer-slot[data-peer-ref]";
18
+ const ANSWERS = ".bubble.note.peer-answer";
19
+
20
+ // +a+ comes before +b+ in the page.
21
+ const precedes = (a, b) => !!(a.compareDocumentPosition(b) & 4 /* DOCUMENT_POSITION_FOLLOWING */);
22
+
23
+ // The answer's ↑: back to the send it answers (kind · title), nothing for
24
+ // an answer no send claims (or one not read yet).
25
+ export function upTemplate(exchange) {
26
+ if (!exchange?.id) return nothing;
27
+ const what = [exchange.kind, exchange.title].filter(Boolean).join(" · ") || "the send";
28
+ return html`<button type="button" class="peer-up" data-peer-jump="send" data-peer-id=${exchange.id}
29
+ aria-label=${`${what}: go to the send`}>${what}<span aria-hidden="true"> ↑</span></button>`;
30
+ }
31
+
32
+ // "Read the full answer": the newest answer of a peer only (its outbox keeps
33
+ // one text).
34
+ export function fullTemplate(newest) {
35
+ return newest ? html`<button type="button" class="peer-full" data-peer-full="1">Read the full answer</button>` : nothing;
36
+ }
37
+
38
+ // +peers+ the model (peer_data.js); +roots+() the elements a turn's rows can
39
+ // be in (the history and the stage); +running+() whether a turn runs;
40
+ // +showText+(source) opens that context source's text (context_chips.js);
41
+ // +behavior+() the scroll's.
42
+ //
43
+ // @return {draw(), drawn(), hasPeer(), hasSend(id), showSend(id), reset()}
44
+ export function createPeerLinks({ peers, roots, running = () => false, showText = () => {}, behavior = smooth } = {}) {
45
+ const all = (selector) => roots().filter(Boolean).flatMap((root) => [...root.querySelectorAll(selector)]);
46
+
47
+ // A slot of the running turn (the stage's, or a turn opened in the history).
48
+ const live = (slot) => running() && !!slot.closest(".turn-stage, [data-opened-turn]");
49
+
50
+ // A send whose id the read doesn't have: did it not go out ("not sent"),
51
+ // or is it only not in the read (unknown: no pill)? Not sent when the row
52
+ // says it failed, or, once its turn has ended, when its peer's list is
53
+ // whole (under the server's cap) or holds a send drawn before this row
54
+ // (the list is the newest exchanges, so this row is among them). A peer
55
+ // the read doesn't name (detached, an older chi web) is unknown.
56
+ function notSent(slot, slots) {
57
+ const row = slot.closest(".activity-row");
58
+ if (/^Error:/.test(slot.getAttribute("title") || "") || row?.querySelector(":scope > .activity-status.error")) return true;
59
+ if (!peers.loaded() || live(slot)) return false;
60
+ const tool = row?.dataset.tool || "";
61
+ const peer = tool.endsWith("_send") ? peers.peer(tool.slice(0, -"_send".length)) : null;
62
+ if (!peer) return false;
63
+ const listed = (peer.exchanges || []).filter((ex) => ex?.id);
64
+ if ((peer.exchanges || []).length < EXCHANGES_CAP) return true;
65
+ const ids = new Set(listed.map((ex) => ex.id));
66
+ return slots.some((other) => other !== slot && ids.has(other.dataset.peerRef) && precedes(other, slot));
67
+ }
68
+
69
+ function draw() {
70
+ const now = Date.now();
71
+ const slots = all(SLOTS);
72
+ for (const slot of slots) {
73
+ const exchange = peers.exchange(slot.dataset.peerRef);
74
+ const ended = !exchange && notSent(slot, slots);
75
+ render(pillTemplate(exchange, { now, ended, title: slot.getAttribute("title") || "" }), slot);
76
+ }
77
+ const notes = all(ANSWERS);
78
+ const newest = new Map();
79
+ for (const note of notes) newest.set(note.dataset.peerSource || "", note);
80
+ for (const note of notes) {
81
+ const up = note.querySelector(":scope > .peer-head > .peer-up-slot");
82
+ if (up) render(upTemplate(answerOf(note)), up);
83
+ const full = note.querySelector(":scope > .peer-foot > .peer-full-slot");
84
+ if (full) render(fullTemplate(newest.get(note.dataset.peerSource || "") === note && !!note.dataset.peerSource), full);
85
+ }
86
+ }
87
+
88
+ function answerOf(note) {
89
+ const { peerName, peerSerial, peerRe } = note.dataset;
90
+ return peers.answer(peerName, peerSerial ?? null, peerRe || null);
91
+ }
92
+
93
+ // Focus lands on the jump's target (it isn't focusable by itself).
94
+ function land(el) {
95
+ if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "-1");
96
+ el.focus?.({ preventScroll: true });
97
+ }
98
+
99
+ // ↓: the send's answer, the last bubble drawn for its serial.
100
+ function toAnswer(slot) {
101
+ const ex = peers.exchange(slot.dataset.peerRef);
102
+ const serial = ex?.answer?.serial;
103
+ if (serial === undefined || serial === null) return;
104
+ const note = all(ANSWERS).filter((n) => n.dataset.peerName === ex.peer && n.dataset.peerSerial === String(serial)).at(-1);
105
+ if (!note) return;
106
+ revealInHistory(note);
107
+ note.scrollIntoView?.({ block: "center", behavior: behavior() });
108
+ land(note);
109
+ }
110
+
111
+ // ↑: the send's row, the last one with its id before the answer (a resend
112
+ // has one id), else the last one.
113
+ function toSend(button) {
114
+ showSend(button.dataset.peerId, button.closest(ANSWERS));
115
+ }
116
+
117
+ // The row of send +id+ (the last before +before+, when given), shown and
118
+ // focused; false when none is drawn.
119
+ function showSend(id, before = null) {
120
+ const slots = all(SLOTS).filter((s) => s.dataset.peerRef === id);
121
+ const slot = (before && slots.filter((s) => precedes(s, before)).at(-1)) || slots.at(-1);
122
+ const row = slot?.closest(".activity-row");
123
+ if (!row) return false;
124
+ showRow(row, { behavior: behavior() });
125
+ land(row);
126
+ return true;
127
+ }
128
+
129
+ function onClick(e) {
130
+ const jump = e.target.closest?.("[data-peer-jump]");
131
+ if (jump?.dataset.peerJump === "answer") {
132
+ const slot = jump.closest(SLOTS);
133
+ if (slot) toAnswer(slot);
134
+ } else if (jump?.dataset.peerJump === "send") toSend(jump);
135
+ else if (e.target.closest?.("[data-peer-full]")) {
136
+ const source = e.target.closest(ANSWERS)?.dataset.peerSource;
137
+ if (source) showText(source);
138
+ }
139
+ }
140
+ for (const root of roots().filter(Boolean)) root.addEventListener("click", onClick);
141
+
142
+ return {
143
+ draw,
144
+ // A history drawn (a session's read): its slots filled with what is
145
+ // known, then read again.
146
+ drawn() {
147
+ draw();
148
+ return peers.refresh();
149
+ },
150
+ hasPeer: () => all(SLOTS).length > 0 || all(ANSWERS).length > 0,
151
+ // Whether send +id+'s row is drawn, and a jump to it (the peer chip's
152
+ // exchange list, peer_chip.js).
153
+ hasSend: (id) => all(SLOTS).some((s) => s.dataset.peerRef === id),
154
+ showSend: (id) => showSend(id),
155
+ reset: () => peers.clear(),
156
+ };
157
+ }
158
+
159
+ function smooth() {
160
+ return globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth";
161
+ }
@@ -0,0 +1,49 @@
1
+ // A peer's answer in the conversation (turn_html.js noteBubbleTemplate
2
+ // draws a note with `peer` here): a bubble from the peer, its verdict and
3
+ // summary, and chi's instruction to the model folded behind "what chi told
4
+ // the agent". It keeps what a note that opens a wake turn carries (the
5
+ // classes `bubble note` and `turn-start`, data-opening-id, the time title):
6
+ // TURN_PROMPT (bubbles.js), card_stamps.js, stage_handoff.js OPENING,
7
+ // reload_check.js and revise_stack.js (its `.note-text`, the summary) read
8
+ // it as any wake note. The ↑ to the send and "Read the full answer" are
9
+ // slots peer_links.js fills (data-peer-slot: history_shape.js leaves them
10
+ // out, so live and an offscreen reload read alike).
11
+ // Its own module: new exports go in new modules (web-frontend.md).
12
+
13
+ import { html, nothing } from "./vendor/lit-html.js";
14
+ import { fullTime } from "./format.js";
15
+
16
+ const VERDICT_CLASS = { OK: "ok", CHANGES: "changes", UNSURE: "unsure" };
17
+
18
+ // The answer's verdict pill (the note's peer.verdict, the server's word):
19
+ // "VERDICT OK" with "round closed" when the peer agreed, CHANGES, UNSURE;
20
+ // nothing for none. The phone shows the bare word (CSS).
21
+ export function verdictTemplate(peer) {
22
+ const kind = VERDICT_CLASS[peer?.verdict];
23
+ if (!kind) return nothing;
24
+ const closed = peer.agreed && peer.verdict === "OK"
25
+ ? html`<span class="peer-closed">round closed</span>` : nothing;
26
+ return html`<span class="peer-mark">${closed}<span class=${`peer-verdict ${kind}`}><span class="peer-long">VERDICT </span>${peer.verdict}</span></span>`;
27
+ }
28
+
29
+ // What the bubble says the peer answered: its summary, else the note's
30
+ // first line that says something (a quote's `> ` dropped), else "(no
31
+ // summary)". revise_stack.js labels a Revise version with it.
32
+ export function peerSummaryText(note) {
33
+ const summary = String(note?.peer?.summary ?? "").trim();
34
+ if (summary) return summary;
35
+ const line = String(note?.content ?? "").split("\n").map((l) => l.replace(/^\s*>\s?/, "").trim()).find(Boolean);
36
+ return line || "(no summary)";
37
+ }
38
+
39
+ // The bubble for +note+ (a context note with `peer`: {peer, label, re,
40
+ // summary, serial, verdict, agreed}).
41
+ export function peerNoteTemplate(note) {
42
+ const peer = note.peer || {};
43
+ const name = peer.label || peer.peer || "Your peer";
44
+ const cls = note.turn_start ? "bubble note turn-start peer-answer" : "bubble note peer-answer";
45
+ const opening = note.turn_start && note.turn_id ? String(note.turn_id) : nothing;
46
+ const source = note.context_source || (peer.peer ? `${peer.peer}-outbox` : "");
47
+ const attr = (value) => (value === null || value === undefined || value === "" ? nothing : String(value));
48
+ return html`<div class=${cls} title=${fullTime(note.at) || nothing} data-opening-id=${opening} data-peer-source=${attr(source)} data-peer-name=${attr(peer.peer)} data-peer-re=${attr(peer.re)} data-peer-serial=${attr(peer.serial)}><div class="peer-head"><span class="peer-who">${name} answered</span><span class="peer-up-slot" data-peer-slot="up"></span>${verdictTemplate(peer)}</div><div class="note-text">${peerSummaryText(note)}</div><div class="peer-foot"><span class="peer-full-slot" data-peer-slot="full"></span><details class="peer-told"><summary>what chi told the agent</summary><div class="peer-told-text">${note.content ?? ""}</div></details></div></div>`;
49
+ }
@@ -23,6 +23,8 @@
23
23
  // from a read before its replay, reset with the session; null: none
24
24
  // stageMissing the stage's running-with-no-turn check (stage_missing.js);
25
25
  // null: no check (the render then says nothing)
26
+ // peerLinks the peer exchange's slots (peer_links.js): filled after a
27
+ // read is drawn, reset with the session; null: none
26
28
  // markdown markdown_place.js (linkTextRefs, applyFinalMarkdown)
27
29
  // capabilities() the page's capabilities (card.js shownElsewhere, the history's cards)
28
30
  // page: {setReviseAnchor(anchor), renderInitRow(), setMarkdownWarning(warning),
@@ -56,7 +58,7 @@ export function createSessionView(deps) {
56
58
  const {
57
59
  store, historyEl, getSession,
58
60
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, wsPreview = null, gapClock,
59
- bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null,
61
+ bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null, peerLinks = null,
60
62
  } = deps;
61
63
  const { makeUserBubble, addEndBubble, showGuardrailWarning, showRecap } = bubbles;
62
64
  const { placeSnapshotCards, upsertCard } = cards;
@@ -98,6 +100,7 @@ export function createSessionView(deps) {
98
100
  later.commandList().close();
99
101
  later.resetTurnView();
100
102
  cardRegistry?.reset();
103
+ peerLinks?.reset();
101
104
  objectives.reset();
102
105
  seedInitTasks(later.initTasks(), []);
103
106
  renderInitRow();
@@ -213,6 +216,8 @@ export function createSessionView(deps) {
213
216
  stageMissing.note(data);
214
217
  stageMissing.check();
215
218
  }
219
+ // The peer sends and answers drawn: their state, then read again.
220
+ peerLinks?.drawn();
216
221
  // The same running turn as when the page left it: what was opened, back.
217
222
  applyView(viewMemory.take(store.selected, data.current_turn?.turn_id || null), { stage: turnDom, reader: wsPreview });
218
223
  // A whole view drawn: the composer and the bar once more (the working
@@ -22,6 +22,8 @@
22
22
  // (contextChips null for a viewer without them, viewer.js)
23
23
  // workingSet the stage view's working set (web.working_set),
24
24
  // null when off
25
+ // peers the open session's peers (peer_data.js createPeers),
26
+ // read again on a peer's note, send or command; null: none
25
27
  // participantsControl the owner's participants panel (participants_panel.js),
26
28
  // null for none
27
29
  // sentIds, earlyRestores restore.js's bookkeeping
@@ -62,12 +64,13 @@ import { keepEarlyRestore, restoreAction } from "./restore.js";
62
64
  import { setBadgeMode } from "./participant_names.js";
63
65
  import { isParticipantAuthor } from "./participant_model.js";
64
66
  import { stillOn } from "./latest.js";
67
+ import { peerRef } from "./peer_exchange.js";
65
68
 
66
69
  export function createStreamHandlers(deps) {
67
70
  const {
68
71
  selected, store, clientId, capabilities, historyEl,
69
72
  liveTurn, turnDom, shownTexts, questionCards, contextChips,
70
- workingSet = null, participantsControl = null, sentIds, earlyRestores, stream, composer, getSession,
73
+ workingSet = null, participantsControl = null, peers = null, sentIds, earlyRestores, stream, composer, getSession,
71
74
  resync, applyPromptOps, showSteers, markRecapStale, setTurnRunning, setLiveStatus, endTurnView,
72
75
  appendChunk, readTurnEnd, applyFinalMarkdown, refreshTimingFromSession, makeUserBubble, addEndBubble,
73
76
  commandBubble, addCommandBubble, addNoteBubble, findInTurnRoots, setUsedMemories, showRecap,
@@ -191,6 +194,8 @@ export function createStreamHandlers(deps) {
191
194
  // A participant's turn: their spend and turns in the panel moved.
192
195
  if (data.origin?.author) participantsControl?.reload();
193
196
  endTurnView("completed", null, { emptyAnswer: data.turn_summary?.empty_answer || null });
197
+ // Its peer sends' state as an ended turn's (no fetch).
198
+ peers?.touch?.();
194
199
  const out = turnOutput(data);
195
200
  if (out) appendChunk(out);
196
201
  if (data.verdict) deps.placeVerdict?.(data.verdict);
@@ -297,6 +302,8 @@ export function createStreamHandlers(deps) {
297
302
  const id = selected();
298
303
  // A queued /working-set line is no longer pending (the list's pill).
299
304
  workingSet?.commandRan(data);
305
+ // A /claude validate … may have sent to a peer.
306
+ peers?.refresh();
300
307
  const view = commandView(data, clientId);
301
308
  // What the command changed, in one patch: the bar and the chips'
302
309
  // popovers redraw once (the store; the working set's list follows
@@ -364,9 +371,11 @@ export function createStreamHandlers(deps) {
364
371
  context_added: (data) => {
365
372
  const at = data.at || data.created_at || null;
366
373
  gapBefore(at);
367
- addNoteBubble({ label: data.label, content: data.text || "", at, objectives: data.objectives });
368
- // An attached context source's note: its chip changed.
374
+ addNoteBubble({ label: data.label, content: data.text || "", at, objectives: data.objectives, peer: data.peer,
375
+ context_source: data.context_source });
376
+ // An attached context source's note: its chip changed; a peer's answer: its exchange.
369
377
  if (data.context_source) contextChips?.refresh();
378
+ if (data.peer) peers?.refresh();
370
379
  },
371
380
  // The session's list changed (objectives_strip.js): an edit waiting, a
372
381
  // list note in, a turn's moves.
@@ -379,7 +388,11 @@ export function createStreamHandlers(deps) {
379
388
  continue_offered: (data) => questionCards.renderContinue(data),
380
389
  continue_resolved: (data) => questionCards.resolveContinue(data),
381
390
  tool_call_started: (data) => turnDom.toolStarted(data),
382
- tool_call_completed: (data) => turnDom.toolCompleted(data),
391
+ tool_call_completed: (data) => {
392
+ turnDom.toolCompleted(data);
393
+ // A peer send: its exchange went out (or didn't).
394
+ if (peerRef(data)) peers?.refresh();
395
+ },
383
396
  // The engine's list, after every memory read and at a turn's end.
384
397
  used_memories_updated: (data) => {
385
398
  if (Array.isArray(data.used_memory_names)) setUsedMemories(data.used_memory_names);
@@ -29,6 +29,7 @@ import { answerRefsOf, setAnswerRefs } from "./answer_refs.js";
29
29
  import { bindRowRefs } from "./refs.js";
30
30
  import { openAfterEnd } from "./block_open.js";
31
31
  import { drawCard, isNoticeCard, leavesBlock, shownElsewhere } from "./card.js";
32
+ import { settleOrder } from "./turn_settle.js";
32
33
  import { routeChunk } from "./chunk_router.js";
33
34
  import { drawCommandBubble } from "./commands.js";
34
35
  import { endBubbleTemplate } from "./bubbles.js";
@@ -842,6 +843,30 @@ function drawnCardEl(event, cards) {
842
843
  return el;
843
844
  }
844
845
 
846
+ // A drawn turn's question, before its card is placed (cards_place.js
847
+ // placeResolvedQuestion replaces it; placeSnapshotCards drops one whose
848
+ // question never came).
849
+ function questionSlot(id) {
850
+ const el = document.createElement("div");
851
+ el.className = "question-slot";
852
+ el.dataset.questionSlot = String(id);
853
+ return el;
854
+ }
855
+
856
+ // +pieces+ (turn_settle.js settleOrder) as their entries, with each +loose+
857
+ // card (one that waited later, or no step took) before the first piece that
858
+ // arrived after it.
859
+ function placedPieces(pieces, els, loose) {
860
+ const out = [];
861
+ const rest = [...loose];
862
+ for (const piece of pieces) {
863
+ while (rest.length && rest[0].at < piece.at) out.push(rest.shift().entry);
864
+ const entry = els.get(piece.at);
865
+ if (entry) out.push(entry);
866
+ }
867
+ return [...out, ...rest.map((x) => x.entry)];
868
+ }
869
+
845
870
  // A drawn turn's pieces (+group+: turnGroups' drawn group, its drawing
846
871
  // {events, end}), drawn by the live turn block itself: its events go
847
872
  // through the block's own handlers as the stream handlers send them live
@@ -869,10 +894,15 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
869
894
  },
870
895
  });
871
896
  const merged = [...(group.merged || [])];
897
+ // What live put beside the block, in the order it left (turn_settle.js):
898
+ // each piece's element by its event's index; a loose card (no step took it).
899
+ const settled = settleOrder(events);
900
+ const pieceEls = new Map();
901
+ const loose = [];
872
902
  // The ✂ marks a strategy saved on the turn's outputs since (its items'
873
903
  // marks, by output id): an overlay on the rows, as a reload's.
874
904
  const marks = Object.assign({}, ...items.filter((it) => it?.drawn === group.drawn && it.marks).map((it) => it.marks));
875
- for (const event of events) {
905
+ for (const [at, event] of events.entries()) {
876
906
  switch (event?.type) {
877
907
  case "turn_started": view.turnStarted(event); break;
878
908
  case "generation_started": view.generationStarted(event, null); break;
@@ -885,28 +915,36 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
885
915
  case "steer_cut": view.notice({ line: steerCutLine(event), cls: "steer-cut" }); break;
886
916
  case "llm_context_edited": view.notice(llmContextNotice(event)); break;
887
917
  case "pending_input_merged": (event.steers || []).forEach((steer) => view.steer(steer)); break;
888
- case "merged_input": extras.push({ merged: merged.shift() ?? null }); break;
918
+ case "merged_input": pieceEls.set(at, { merged: merged.shift() ?? null }); break;
889
919
  case "reminder_injected": {
890
920
  const el = document.createElement("div");
891
921
  drawCommandBubble(el, { label: null, line: reminderText(event), text: "" });
892
922
  const when = fullTime(event.at);
893
923
  if (when) el.title = when;
894
- extras.push({ el });
924
+ pieceEls.set(at, { el });
895
925
  break;
896
926
  }
897
927
  case "card": {
898
- // Live: a card that asks (its actions run commands) or warns stays
899
- // in sight beside the block (cards_place.js upsertCard, the
900
- // stage's card); any other is a row of its step.
928
+ // Live: a card that waited when it arrived (it asked, or warned)
929
+ // stays in sight beside the block (cards_place.js upsertCard, the
930
+ // stage's card) until it leaves (turn_settle.js); any other is a row
931
+ // of its step. Kept with the block's when it still warns: read off
932
+ // the drawn element (CardStore's latest).
901
933
  const el = drawnCardEl(event, cards);
902
- const asks = (event.actions || []).some((a) => a && a.command);
903
934
  const warn = el.classList.contains("warn");
904
- if (asks || warn || !view.card(el)) extras.push({ el, warn });
935
+ if (settled.cards.has(at)) pieceEls.set(at, { el, warn });
936
+ else if (warn || !view.card(el)) loose.push({ at, entry: { el, warn } });
905
937
  break;
906
938
  }
907
939
  default: break;
908
940
  }
909
941
  }
942
+ // A question is an empty slot: cards_place.js placeResolvedQuestion puts
943
+ // the answered card there.
944
+ for (const piece of settled.pieces) {
945
+ if (piece.kind === "question") pieceEls.set(piece.at, { el: questionSlot(piece.id) });
946
+ }
947
+ extras.push(...placedPieces(settled.pieces, pieceEls, loose));
910
948
  const empty = kind === "completed" && (group.emptyAnswer != null || end.turn_summary?.empty_answer);
911
949
  const endNote = empty ? elementOf(emptyAnswerTemplate(group.emptyAnswer != null ? items[group.emptyAnswer] : end.turn_summary.empty_answer)) : null;
912
950
  // The answer's key (data-answer-turn: Revise, the fold) is the turn's own
@@ -19,6 +19,8 @@ import { STOPPED_LINE_CLASS, cancelLineText, formatDuration } from "./timing.js"
19
19
  import { emptyAnswerLine } from "./turn_events.js";
20
20
  import { authorBadge, authorBadgeText, authorBadgeTitle } from "./participant_names.js";
21
21
  import { ownerLabel, viewerSelf } from "./viewer_self.js";
22
+ import { peerRef } from "./peer_exchange.js";
23
+ import { peerNoteTemplate } from "./peer_note.js";
22
24
 
23
25
  // A row's status (live, or a saved tool record's on reload): running,
24
26
  // error, stopped (a task_wait the user's Stop ended), blocked (a guardrail
@@ -181,11 +183,16 @@ export function toolRowInnerTemplate(row, { thumbs = () => nothing, stop = nothi
181
183
  : nothing;
182
184
  const duration = formatDuration(row.duration_ms);
183
185
  const full = row.status === "running" ? "" : String(row.output || "").replace(/^\[[^\]]*\]\s*/, "");
184
- const output = full
186
+ // A peer send (its peer ref): an empty slot peer_links.js draws the
187
+ // exchange's state into, the output (chi's advice to the model) its hover
188
+ // instead of a line, unless the send failed.
189
+ const peer = peerRef(row);
190
+ const peerSlot = peer ? html`<span class="peer-slot" data-peer-ref=${peer.target.id} title=${full || nothing}></span>` : nothing;
191
+ const output = full && !(peer && row.status === "ok" && !/^Error:/.test(full))
185
192
  ? html`<div class=${tailMode(row.tool, full) ? "activity-output tail" : "activity-output"} title=${full}>${inlineOutput(row.tool, full)}</div>`
186
193
  : nothing;
187
194
  const status = statusParts(row.status, { noMatch: !!row.no_match });
188
- return html`${statusMarkTemplate(status)}<span class="activity-tool">${toolName(row)}</span>${params}${stop}${alias}${statusWordTemplate(status)}${row.status === "ok" ? wayInTemplate(row) : nothing}${auto}${wrong}${duration ? html`<span class="activity-duration">${duration}</span>` : nothing}${commandBlockTemplate(row.view, row.title)}${llmEditTemplate(row)}${output}${full ? readLinesTemplate(row) : nothing}${row.images?.length ? thumbs(row.images) : nothing}${row.diff ? activityDiffTemplate(row.diff) : nothing}`;
195
+ return html`${statusMarkTemplate(status)}<span class="activity-tool">${toolName(row)}</span>${params}${peerSlot}${stop}${alias}${statusWordTemplate(status)}${row.status === "ok" ? wayInTemplate(row) : nothing}${auto}${wrong}${duration ? html`<span class="activity-duration">${duration}</span>` : nothing}${commandBlockTemplate(row.view, row.title)}${llmEditTemplate(row)}${output}${full ? readLinesTemplate(row) : nothing}${row.images?.length ? thumbs(row.images) : nothing}${row.diff ? activityDiffTemplate(row.diff) : nothing}`;
189
196
  }
190
197
 
191
198
  // A prompt bubble's states and their badges: queued (waiting for its
@@ -286,6 +293,8 @@ export function answerBubbleTemplate(message, { cls = "", at = null, turnId = nu
286
293
  // text.
287
294
  export function noteBubbleTemplate(note) {
288
295
  if (note?.objectives) return objectivesEntryTemplate(note, timeTitle(note.at));
296
+ // A peer's answer: a bubble from the peer (peer_note.js).
297
+ if (note?.peer && typeof note.peer === "object") return peerNoteTemplate(note);
289
298
  const from = note?.label ? `note from ${note.label}` : "note";
290
299
  // A wake turn's note opens that turn (TURN_PROMPT, bubbles.js); a class, not
291
300
  // data-turn-id, which marks a claim's anchor (claim_link.js). Its turn's id