samagotchi 0.187.0 → 0.188.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 (137) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +55 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +8 -4
  5. data/docs/bundles.md +124 -120
  6. data/docs/cli.md +25 -5
  7. data/docs/configuration.md +4 -4
  8. data/docs/context.md +18 -162
  9. data/docs/guardrails.md +3 -1
  10. data/docs/hooks.md +2 -1
  11. data/docs/internals/attached-context.md +19 -37
  12. data/docs/internals/bridge.md +1 -0
  13. data/docs/internals/engine.md +2 -2
  14. data/docs/internals/llm-context-forget.md +5 -6
  15. data/docs/internals/objectives.md +1 -0
  16. data/docs/internals/pages.md +6 -3
  17. data/docs/internals/peers.md +149 -0
  18. data/docs/internals/remote-sessions.md +7 -4
  19. data/docs/internals/web-frontend.md +61 -37
  20. data/docs/internals/web-push.md +1 -1
  21. data/docs/memory.md +1 -1
  22. data/docs/pages.md +2 -1
  23. data/docs/peers.md +141 -0
  24. data/docs/plugins.md +52 -27
  25. data/docs/sessions.md +8 -4
  26. data/docs/sub-agent.md +5 -5
  27. data/lib/samagotchi/bridge.rb +3 -3
  28. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  29. data/lib/samagotchi/bundle_command/check.rb +1 -1
  30. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  31. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  32. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  33. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  34. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  35. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  36. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  37. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  38. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  39. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  40. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  41. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  42. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  43. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  44. data/lib/samagotchi/client_id.rb +15 -1
  45. data/lib/samagotchi/config.rb +8 -7
  46. data/lib/samagotchi/context_absorber.rb +23 -277
  47. data/lib/samagotchi/context_sources.rb +17 -69
  48. data/lib/samagotchi/engine/messages.rb +12 -1
  49. data/lib/samagotchi/engine/plugins.rb +1 -1
  50. data/lib/samagotchi/engine.rb +7 -6
  51. data/lib/samagotchi/engine_peers.rb +0 -3
  52. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  53. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  54. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  55. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  56. data/lib/samagotchi/inline_widgets.rb +11 -3
  57. data/lib/samagotchi/log_line.rb +1 -1
  58. data/lib/samagotchi/note_move.rb +3 -1
  59. data/lib/samagotchi/page_command.rb +18 -9
  60. data/lib/samagotchi/pages/builder.rb +7 -8
  61. data/lib/samagotchi/pages/launch.rb +8 -2
  62. data/lib/samagotchi/pages/store.rb +11 -2
  63. data/lib/samagotchi/peer_command.rb +192 -0
  64. data/lib/samagotchi/peer_continue.rb +99 -0
  65. data/lib/samagotchi/peer_exchanges.rb +3 -3
  66. data/lib/samagotchi/peer_mailbox.rb +360 -0
  67. data/lib/samagotchi/peer_note.rb +208 -0
  68. data/lib/samagotchi/peer_receipts.rb +247 -0
  69. data/lib/samagotchi/peer_registry.rb +44 -0
  70. data/lib/samagotchi/peer_roster.rb +79 -0
  71. data/lib/samagotchi/peer_say.rb +168 -0
  72. data/lib/samagotchi/plugin/api.rb +29 -21
  73. data/lib/samagotchi/plugin/context.rb +7 -0
  74. data/lib/samagotchi/plugin/loader.rb +3 -3
  75. data/lib/samagotchi/plugin/peer.rb +175 -64
  76. data/lib/samagotchi/plugin/peers.rb +70 -0
  77. data/lib/samagotchi/run_options.rb +2 -1
  78. data/lib/samagotchi/schedule_command.rb +10 -3
  79. data/lib/samagotchi/schedule_display.rb +32 -0
  80. data/lib/samagotchi/session_access/contract.rb +18 -1
  81. data/lib/samagotchi/session_access/local.rb +132 -14
  82. data/lib/samagotchi/session_access/remote.rb +4 -2
  83. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  84. data/lib/samagotchi/session_continue.rb +12 -0
  85. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  86. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  87. data/lib/samagotchi/session_manager/removal.rb +2 -0
  88. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  89. data/lib/samagotchi/session_manager.rb +1 -0
  90. data/lib/samagotchi/session_stores.rb +17 -0
  91. data/lib/samagotchi/steer.rb +1 -1
  92. data/lib/samagotchi/system_prompt.rb +1 -1
  93. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  94. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  95. data/lib/samagotchi/testing/boundary.rb +4 -13
  96. data/lib/samagotchi/testing/bundle.rb +40 -5
  97. data/lib/samagotchi/testing/install.rb +4 -4
  98. data/lib/samagotchi/testing/recording_api.rb +2 -1
  99. data/lib/samagotchi/tools/context_read.rb +0 -14
  100. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  101. data/lib/samagotchi/version.rb +1 -1
  102. data/lib/samagotchi/web/app.rb +2 -13
  103. data/lib/samagotchi/web/message_display.rb +4 -2
  104. data/lib/samagotchi/web/peer_routes.rb +133 -0
  105. data/lib/samagotchi/web/public/app.js +11 -11
  106. data/lib/samagotchi/web/public/bubbles.js +2 -2
  107. data/lib/samagotchi/web/public/cards_place.js +20 -1
  108. data/lib/samagotchi/web/public/context_chips.js +45 -46
  109. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  110. data/lib/samagotchi/web/public/history_shape.js +3 -2
  111. data/lib/samagotchi/web/public/index.html +13 -0
  112. data/lib/samagotchi/web/public/notify.js +1 -1
  113. data/lib/samagotchi/web/public/page_view.js +2 -1
  114. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  115. data/lib/samagotchi/web/public/peer_data.js +13 -11
  116. data/lib/samagotchi/web/public/peer_links.js +12 -7
  117. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  118. data/lib/samagotchi/web/public/peer_note.js +7 -3
  119. data/lib/samagotchi/web/public/peer_text.js +4 -4
  120. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  121. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  122. data/lib/samagotchi/web/public/session_view.js +2 -2
  123. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  124. data/lib/samagotchi/web/public/turn_block.js +7 -3
  125. data/lib/samagotchi/web/public/turn_events.js +6 -0
  126. data/lib/samagotchi/web/push/attention.rb +3 -2
  127. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  128. data/lib/samagotchi/worker/leave.rb +3 -0
  129. data/lib/samagotchi/worker/mail.rb +73 -0
  130. data/lib/samagotchi/worker/startup.rb +3 -0
  131. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  132. data/lib/samagotchi/worker.rb +12 -6
  133. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  134. data/lib/samagotchi/worker_inbound.rb +43 -46
  135. data/lib/samagotchi/worker_wakes.rb +26 -21
  136. metadata +19 -2
  137. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -0,0 +1,199 @@
1
+ // The history's background items fold into one closed row per stretch:
2
+ // anything nobody says in the conversation (a plugin's or chi's own line
3
+ // shown on its own, a context note that starts nothing, an objectives line,
4
+ // a plugin's nudge) folds; what someone says stays (the prompt, the answer,
5
+ // a peer's answer, a note that opens a wake turn). A stretch is a run of
6
+ // those items side by side among #history's children; the turn's timing
7
+ // line passes through one, anything else ends it. Its row reads
8
+ // "▸ 3 notes · claude-inbox, source-links, skills" (and "⚠ N" for its warn
9
+ // lines), closed; a click (Enter/Space: it is a button) opens it and the
10
+ // items show under it as they are.
11
+ //
12
+ // Modelled on answer_fold.js: the row is a sibling just before the
13
+ // stretch's first item, never a wrapper (the bubbles keep their place,
14
+ // copy text and observers); the items are hidden by a class
15
+ // (`.quiet-hidden`, CSS). Each row is tied to its first item (rowOf /
16
+ // firstOf), so a row something was placed after (a recap, a snapshot's
17
+ // card) goes back before its item, open or not. The open state is the
18
+ // row's class only, never stored: a re-render draws the rows closed.
19
+ //
20
+ // One observer on #history (its own children only) settles every path that
21
+ // fills it; a settle that changes nothing writes nothing (the other
22
+ // observers on #history see class and subtree writes).
23
+ //
24
+ // A module of its own: static JS is cached at unversioned URLs, and a new
25
+ // export on an old module would blank the page.
26
+ import { html, render, nothing } from "./vendor/lit-html.js";
27
+
28
+ // What folds: a direct child of #history that is one of these.
29
+ export const QUIET = ".bubble.hook-notice:not(.empty-answer), .bubble.note:not(.turn-start):not(.peer-answer), .bubble.steer-row";
30
+ // What a stretch passes over (it stays visible).
31
+ export const PASS = ".turn-timing";
32
+ export const ROW_CLASS = "quiet-notes";
33
+ export const HIDDEN_CLASS = "quiet-hidden";
34
+
35
+ const ARRIVE = "ts-arrive";
36
+ const ROW = `.${ROW_CLASS}`;
37
+
38
+ // The stretches over +children+ (an element list, in order): [{ items }].
39
+ // Pure.
40
+ export function quietRuns(children) {
41
+ const runs = [];
42
+ let run = null;
43
+ for (const el of children) {
44
+ if (el.nodeType !== 1 || el.matches(ROW) || el.matches(PASS)) continue;
45
+ if (!el.matches(QUIET)) {
46
+ run = null;
47
+ continue;
48
+ }
49
+ if (!run) runs.push((run = { items: [] }));
50
+ run.items.push(el);
51
+ }
52
+ return runs;
53
+ }
54
+
55
+ const squash = (text) => String(text ?? "").replace(/\s+/g, " ").trim();
56
+
57
+ // One item's name on the row.
58
+ function itemName(el) {
59
+ if (el.matches(".objectives-entry")) return "objectives";
60
+ if (el.matches(".steer-row")) {
61
+ const said = squash(el.querySelector("summary")?.textContent);
62
+ return said.endsWith(" nudged the model") ? said.slice(0, -" nudged the model".length) : "nudge";
63
+ }
64
+ if (el.matches(".hook-notice")) {
65
+ // "<bundle or hook>: text"; chi's own lines ("↻ empty answer, asking
66
+ // again") name no one.
67
+ const text = squash(el.textContent);
68
+ const at = text.indexOf(": ");
69
+ const who = at > 0 ? text.slice(0, at) : "";
70
+ return /^[A-Za-z0-9][\w./-]*$/.test(who) ? who : "chi";
71
+ }
72
+ const line = squash(el.querySelector(".note-line")?.textContent) || "note";
73
+ if (line === "note") return "context";
74
+ const from = line.replace(/^note from /, "").replace(/^context /, "");
75
+ // Another session's note (ContextNote.label): "session <id6> (<~cwd>)".
76
+ const session = /^(session \S+) \(.*\)$/.exec(from);
77
+ return session ? session[1] : from;
78
+ }
79
+
80
+ // A row's words: how many items, their names (unique, in order) and how
81
+ // many are warnings (the `warn` class, never the text). Pure.
82
+ export function rowLabel(items) {
83
+ const names = [];
84
+ let warn = 0;
85
+ for (const el of items) {
86
+ const name = itemName(el);
87
+ if (!names.includes(name)) names.push(name);
88
+ if (el.classList.contains("warn")) warn += 1;
89
+ }
90
+ return { count: items.length, names, warn };
91
+ }
92
+
93
+ export function rowTemplate({ count, names, warn }) {
94
+ return html`<span class="qn-count">${count} ${count === 1 ? "note" : "notes"}</span><span class="qn-names">· ${names.join(", ")}</span>${warn > 0 ? html`<span class="qn-warn">⚠ ${warn}</span>` : nothing}`;
95
+ }
96
+
97
+ // +el+ hidden in a closed row: that row opens. Nothing otherwise. A jump
98
+ // goes through history_reveal.js revealInHistory, which calls this.
99
+ export function revealQuiet(el) {
100
+ const hidden = el?.closest?.(`.${HIDDEN_CLASS}`);
101
+ if (!hidden) return;
102
+ let row = hidden.previousElementSibling;
103
+ while (row && !row.matches(ROW)) row = row.previousElementSibling;
104
+ if (row && !row.classList.contains("open")) row.click();
105
+ }
106
+
107
+ // @param historyEl the history (#history)
108
+ // @return {settle()} (the observer runs it; specs call it)
109
+ export function installQuietNotes({ historyEl }) {
110
+ // Each stretch's first item's row, and each row's first item.
111
+ const rowOf = new WeakMap();
112
+ const firstOf = new WeakMap();
113
+ // The words a row was last drawn with.
114
+ const drawn = new WeakMap();
115
+
116
+ function makeRow(first) {
117
+ const row = historyEl.ownerDocument.createElement("button");
118
+ row.type = "button";
119
+ row.className = ROW_CLASS;
120
+ row.setAttribute("aria-expanded", "false");
121
+ // The stretch's arrival plays on its row (its items are hidden).
122
+ if (first.classList.contains(ARRIVE)) {
123
+ row.classList.add(ARRIVE);
124
+ row.addEventListener("animationend", () => row.classList.remove(ARRIVE), { once: true });
125
+ }
126
+ return row;
127
+ }
128
+
129
+ // A row already in the stretch's span (between its items, or just before
130
+ // its first) that no other stretch took: the stretch's first item changed.
131
+ function rowInSpan(items, taken) {
132
+ const last = items[items.length - 1];
133
+ const before = items[0].previousElementSibling;
134
+ if (before?.matches(ROW) && firstOf.has(before) && !taken.has(before)) return before;
135
+ for (let el = items[0]; el && el !== last; el = el.nextElementSibling) {
136
+ if (el.matches(ROW) && firstOf.has(el) && !taken.has(el)) return el;
137
+ }
138
+ return null;
139
+ }
140
+
141
+ function drawRow(row, items) {
142
+ const label = rowLabel(items);
143
+ const words = JSON.stringify(label);
144
+ if (drawn.get(row) !== words) {
145
+ render(rowTemplate(label), row);
146
+ drawn.set(row, words);
147
+ }
148
+ const open = row.classList.contains("open");
149
+ const expanded = open ? "true" : "false";
150
+ if (row.getAttribute("aria-expanded") !== expanded) row.setAttribute("aria-expanded", expanded);
151
+ if (row.classList.contains("warn") !== label.warn > 0) row.classList.toggle("warn", label.warn > 0);
152
+ for (const item of items) {
153
+ if (item.classList.contains(HIDDEN_CLASS) === !open) continue;
154
+ item.classList.toggle(HIDDEN_CLASS, !open);
155
+ // A hidden element never fires animationend: its slide-up would play
156
+ // the first time the row opens.
157
+ if (!open && item.classList.contains(ARRIVE)) item.classList.remove(ARRIVE);
158
+ }
159
+ }
160
+
161
+ function settle() {
162
+ const taken = new Set();
163
+ const shown = new Set();
164
+ for (const { items } of quietRuns(historyEl.children)) {
165
+ const first = items[0];
166
+ let row = rowOf.get(first);
167
+ if (!row || row.parentElement !== historyEl || taken.has(row)) row = rowInSpan(items, taken);
168
+ if (!row) row = makeRow(first);
169
+ if (firstOf.get(row) !== first) {
170
+ firstOf.set(row, first);
171
+ rowOf.set(first, row);
172
+ }
173
+ if (first.previousElementSibling !== row) historyEl.insertBefore(row, first);
174
+ taken.add(row);
175
+ drawRow(row, items);
176
+ for (const item of items) shown.add(item);
177
+ }
178
+ for (const row of historyEl.querySelectorAll(`:scope > ${ROW}`)) if (!taken.has(row)) row.remove();
179
+ // An item no stretch holds any more (it changed kind): shown again.
180
+ for (const el of historyEl.querySelectorAll(`:scope > .${HIDDEN_CLASS}`)) if (!shown.has(el)) el.classList.remove(HIDDEN_CLASS);
181
+ }
182
+
183
+ const ours = (n) => n.nodeType !== 1 || n.classList.contains(ROW_CLASS);
184
+ new MutationObserver((records) => {
185
+ if (records.some((r) => [...r.addedNodes, ...r.removedNodes].some((n) => !ours(n)))) settle();
186
+ }).observe(historyEl, { childList: true });
187
+ settle();
188
+
189
+ historyEl.addEventListener("click", (e) => {
190
+ const row = e.target.closest?.(ROW);
191
+ if (!row || row.parentElement !== historyEl || !firstOf.has(row)) return;
192
+ e.preventDefault();
193
+ const open = !row.classList.contains("open");
194
+ row.classList.toggle("open", open);
195
+ settle();
196
+ });
197
+
198
+ return { settle };
199
+ }
@@ -34,6 +34,7 @@ import { clip } from "./format.js";
34
34
  import { NOTE_BOUNDARY } from "./turn_range.js";
35
35
  import { workerPredates } from "./worker_features.js";
36
36
  import { SWAPPED_CLASS, VIEW_CLASS, stepVersion, switcherTemplate, viewOf } from "./revise_switch.js";
37
+ import { ROW_CLASS as QUIET_ROW } from "./quiet_notes.js";
37
38
 
38
39
  // The classes and attributes this module puts on the history.
39
40
  export const HIDDEN_CLASS = "stack-hidden";
@@ -154,7 +155,7 @@ function promptLabel(opening) {
154
155
  // {id, opening, els (after the opening, up to the next opening or note, a
155
156
  // trailing gap divider left to the next), answer (its final answer), wake
156
157
  // (a note opened it), stopped (it was canceled or failed)}. Our own rows
157
- // aren't part of any.
158
+ // and the notes rows (quiet_notes.js: never stack-hidden) aren't part of any.
158
159
  export function historyTurns(historyEl) {
159
160
  const turns = [];
160
161
  let turn = null;
@@ -163,7 +164,7 @@ export function historyTurns(historyEl) {
163
164
  while (turn.els.at(-1)?.classList.contains("time-gap")) turn.els.pop();
164
165
  };
165
166
  for (const el of historyEl.children) {
166
- if (el.classList.contains(STUB_CLASS) || el.classList.contains(ROW_CLASS) || el.classList.contains(VIEW_CLASS)) continue;
167
+ if ([STUB_CLASS, ROW_CLASS, VIEW_CLASS, QUIET_ROW].some((c) => el.classList.contains(c))) continue;
167
168
  if (el.classList.contains(FOLD_ROW) && el.nextElementSibling?.matches(OPENING)) continue;
168
169
  const opening = el.matches(OPENING) ? el : el.querySelector(OPENING);
169
170
  if (opening || el.matches(NOTE_BOUNDARY)) {
@@ -411,7 +412,7 @@ export function installReviseStacks({
411
412
  // answer's key or its end (its class).
412
413
  observer = new MutationObserver((records) => {
413
414
  const news = records.some((r) => (r.type === "childList" ? r.target === historyEl
414
- && [...r.addedNodes, ...r.removedNodes].some((n) => n.nodeType === 1 && ![STUB_CLASS, ROW_CLASS, VIEW_CLASS].some((c) => n.classList.contains(c)))
415
+ && [...r.addedNodes, ...r.removedNodes].some((n) => n.nodeType === 1 && ![STUB_CLASS, ROW_CLASS, VIEW_CLASS, QUIET_ROW].some((c) => n.classList.contains(c)))
415
416
  : r.attributeName !== "class" || r.target.matches?.(`.bubble.output, .${STUB_CLASS}`)));
416
417
  if (news) decorate();
417
418
  });
@@ -57,7 +57,7 @@ import { applyView, captureView, createStageViewMemory } from "./stage_view_memo
57
57
 
58
58
  export function createSessionView(deps) {
59
59
  const {
60
- store, historyEl, getSession,
60
+ store, historyEl, getSession, clientId = null,
61
61
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, wsPreview = null, gapClock,
62
62
  bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null, peerLinks = null,
63
63
  pictures = null,
@@ -250,7 +250,7 @@ export function createSessionView(deps) {
250
250
  // (its prompt has no drawing yet: a plain row, no miss).
251
251
  const historyOpts = (data = {}) => ({ thumbs: (images) => thumbsTemplate(store.selected, images), workingSet: !!workingSet,
252
252
  drawings: data.turn_drawings || null, cards: data.cards || null, capabilities: capabilities(),
253
- runningTurnId: data.current_turn?.turn_id || null });
253
+ runningTurnId: data.current_turn?.turn_id || null, clientId });
254
254
 
255
255
  // A read drawn the way a reload draws it: the turn blocks only, nothing
256
256
  // placed after them (the opt-in reload check, reload_check.js, compares
@@ -368,12 +368,13 @@ export function createStreamHandlers(deps) {
368
368
  addCommandBubble({ label: null, line: reminderText(data), text: "", at: data.at, turnId: liveTurn.timing.turnId || null });
369
369
  },
370
370
  // A context note joined the conversation (between turns; no turn runs).
371
- // A note is activity of its own: it starts nothing, so it ends there too.
371
+ // A plain note is activity of its own: it starts nothing, so it ends there too.
372
372
  context_added: (data) => {
373
373
  const at = data.at || data.created_at || null;
374
374
  gapBefore(at);
375
+ // A wake's note opens its turn (turn_start, turn_id), as a reload draws it.
375
376
  addNoteBubble({ label: data.label, content: data.text || "", at, objectives: data.objectives, peer: data.peer,
376
- context_source: data.context_source });
377
+ context_source: data.context_source, turn_start: data.turn_start, turn_id: data.turn_id });
377
378
  // An attached context source's note: its chip changed; a peer's answer: its exchange.
378
379
  if (data.context_source) contextChips?.refresh();
379
380
  if (data.peer) peers?.refresh();
@@ -37,7 +37,8 @@ import { drawnKind } from "./turn_drawing.js";
37
37
  import { failedTurnText, fullTime, normalize, sourceLabel } from "./format.js";
38
38
  import { thumbsTemplate } from "./images.js";
39
39
  import { shouldFollowScroll } from "./scroll.js";
40
- import { emptyRetryLine, hookNoticeLabel, llmContextNotice, reminderText, steerCutLine } from "./turn_events.js";
40
+ import { clientLabel, emptyRetryLine, hookNoticeLabel, isOwn, llmContextNotice, reminderText, steerCutLine } from "./turn_events.js";
41
+ import { viewerSelf } from "./viewer_self.js";
41
42
  import {
42
43
  answerBubbleTemplate, commandBubbleTemplate, elementOf, emptyAnswerTemplate, noteBubbleTemplate, shellCommandMessage,
43
44
  steerRowTemplate, toolRowInnerTemplate, userBubbleTemplate,
@@ -1016,10 +1017,12 @@ function pairStepTexts(els, group, items) {
1016
1017
  // web.working_set): each block stamped with its
1017
1018
  // turn's ordinal and its rows with theirs (working_set_view.js), and the
1018
1019
  // turn's footprint on its summary line.
1020
+ const historyClientLabel = (clientId, myId) => viewerSelf() || isOwn(clientId, myId) ? null : clientLabel(clientId);
1021
+
1019
1022
  // +cards+ the snapshot's cards (a drawn card's body), +capabilities+ the
1020
1023
  // page's (a notice shown elsewhere).
1021
1024
  export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, now = Date.now(), drawings = null, cards = null, capabilities = {},
1022
- runningTurnId = null }) {
1025
+ runningTurnId = null, clientId = null }) {
1023
1026
  const timingTemplate = (group) => {
1024
1027
  const record = group.record;
1025
1028
  // Numbered by its place in the turn records, as live (a failed turn
@@ -1040,7 +1043,8 @@ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, no
1040
1043
  const userTemplate = (m, opts = {}) => {
1041
1044
  const shell = shellCommandMessage(m?.content);
1042
1045
  if (shell) return commandBubbleTemplate({ ...shell, at: m?.at });
1043
- return userBubbleTemplate(m, { label: sourceLabel(m?.source), thumbs: thumbs(m.images), author: authorBadge(m?.author, m?.author_name, m?.participant_mode || READ_ONLY), ...opts });
1046
+ const label = sourceLabel(m?.source) || historyClientLabel(m?.client_id, clientId);
1047
+ return userBubbleTemplate(m, { label, thumbs: thumbs(m.images), author: authorBadge(m?.author, m?.author_name, m?.participant_mode || READ_ONLY), ...opts });
1044
1048
  };
1045
1049
  // The first text after a delegate report merged mid-turn, unless it is
1046
1050
  // the turn's answer (shown anyway). Its key (answer_fold.js): the turn's
@@ -150,6 +150,11 @@ const SCHEDULE_CLIENT = "system:schedule:";
150
150
  // as it typed it): lowercase letters, digits, - and _, up to 32; none left
151
151
  // is "agent".
152
152
  const AGENT_CLIENT = "agent:";
153
+ // A peer agent's message that started a turn (a mail wake): peer:<name>.
154
+ const PEER_CLIENT = "peer:";
155
+ function peerName(id) {
156
+ return id.slice(PEER_CLIENT.length).toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 24) || "?";
157
+ }
153
158
  function agentName(id) {
154
159
  const name = id.slice(AGENT_CLIENT.length).toLowerCase().replace(/[^a-z0-9_-]/g, "").slice(0, 32);
155
160
  return name || "agent";
@@ -178,6 +183,7 @@ export function clientLabel(clientId) {
178
183
  if (id.startsWith(TASK_CLIENT) && id.length > TASK_CLIENT.length) return `task ${shortTaskId(id.slice(TASK_CLIENT.length))} finished`;
179
184
  if (id.startsWith(SCHEDULE_CLIENT)) return "schedule";
180
185
  if (id.startsWith(AGENT_CLIENT)) return `agent ${agentName(id)}`;
186
+ if (id.startsWith(PEER_CLIENT)) return `peer ${peerName(id)}`;
181
187
  if (id.startsWith(SESSION_CLIENT)) return `session ${sessionName(id)}`;
182
188
  const colon = id.indexOf(":");
183
189
  let label = labelFor(id);
@@ -31,9 +31,10 @@ module Samagotchi
31
31
  WAITING = %w[approval question continue card].freeze
32
32
  # notify.js DONE_MIN_SECONDS, UNWATCHED_ORIGINS: a finished turn
33
33
  # shorter than this was watched (no "done"), unless nobody started
34
- # it (a delegate child's report, a context change, a finished task).
34
+ # it (a delegate child's report, a context change, a peer's message, a
35
+ # finished task).
35
36
  DONE_MIN_SECONDS = 10
36
- UNWATCHED_ORIGINS = %w[delegate_report context task].freeze
37
+ UNWATCHED_ORIGINS = %w[delegate_report context peer task].freeze
37
38
  TITLE_MAX = 61
38
39
  BODIES = { "question" => "needs an answer", "approval" => "needs approval", "continue" => "hit its step limit",
39
40
  "card" => "needs you", "failed" => "turn failed" }.freeze
@@ -8,7 +8,6 @@ require_relative "../pending_question"
8
8
  require_relative "../plain_reply"
9
9
  require_relative "../reply_for"
10
10
  require_relative "../context_sources"
11
- require_relative "../peer_exchanges"
12
11
  require_relative "../context_command"
13
12
  require_relative "../send_command"
14
13
  require_relative "../launch_mode"
@@ -21,6 +20,7 @@ require_relative "request_body"
21
20
  require_relative "session_hub"
22
21
  require_relative "ask_routes"
23
22
  require_relative "mcp_route"
23
+ require_relative "peer_routes"
24
24
 
25
25
  module Samagotchi
26
26
  module Web
@@ -36,6 +36,8 @@ module Samagotchi
36
36
  module SessionAccessRoutes
37
37
  include AskRoutes
38
38
  include McpRoute
39
+ # chi peer's (a remote's pair and say) and the page's peers model.
40
+ include PeerRoutes
39
41
 
40
42
  # WAIT_MAX_SECONDS (a wait route's slice) is AskRoutes', included above.
41
43
 
@@ -489,25 +491,6 @@ module Samagotchi
489
491
  error_response(400, "note_rejected", e.message)
490
492
  end
491
493
 
492
- # GET /api/sessions/:id/peers: the owner's peer exchanges from files.
493
- def handle_peers(_req, id)
494
- @session_class.load(id, state_dir: default_state_dir)
495
- own = ContextSources.session_location(id, state_dir: default_state_dir)
496
- entries = PeerExchanges.read(id, state_dir: default_state_dir).group_by { |entry| entry["peer"] }
497
- peers = {}
498
- own.sources.each do |source|
499
- next unless source.push?
500
-
501
- peer, leg = ContextSources.peer_leg(source.name)
502
- next unless peer
503
-
504
- row = (peers[peer] ||= { name: peer, label: ContextSources.peer_label(peer), inbox: false, outbox: false })
505
- row[leg.to_sym] = true
506
- end
507
- peers.each_value { |row| row[:exchanges] = PeerExchanges.joined(entries.fetch(row[:name], [])) }
508
- json_response(200, { peers: peers.values })
509
- end
510
-
511
494
  # POST /api/sessions/:id/context/:name/push {text, summary, wake,
512
495
  # hint}: new text for the session's --push source (chi context push;
513
496
  # the fields as a source's JSON output gives them, checked the same
@@ -244,6 +244,9 @@ module Samagotchi
244
244
  # /exit --delete deletes next: its save could land after the delete and
245
245
  # write the session back.
246
246
  absorb_context unless deleting
247
+ # A peer's message that came in the same gap: a note, held (the
248
+ # worker leaves; it reads it at its next start).
249
+ absorb_mail(hold: result == :exit_requested ? :exit : :leaving) unless deleting
247
250
  # The watch goes with this process: a task that finished since the
248
251
  # last look (nothing held the exit for it: queue, a note-only task,
249
252
  # /exit) is a plain note for the next turn, not lost. Not into a
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../log"
4
+ require_relative "../peer_receipts"
5
+
6
+ module Samagotchi
7
+ class Worker
8
+ # A peer's mail on the worker's side: the absorb and the mail wake turn
9
+ # it may start (WorkerInbound#absorb_mail), the hold a pass gives, and
10
+ # the receipts' end of every turn (PeerReceipts#turn_ended). Reads
11
+ # @inbound, @exit_claim and @peer_receipts, and @unmarked_this_turn
12
+ # (#run_wake sets it). See docs/internals/peers.md.
13
+ module MailPart
14
+ private
15
+
16
+ # A peer's mail (WorkerInbound#absorb_mail), and the mail wake turn it
17
+ # may start. A failure to read or write it (or in that turn) is logged:
18
+ # the next pass tries again.
19
+ # @param hold [Symbol, nil] why a wake can't run now (MailPart::CALLER_HOLDS)
20
+ # @return [Boolean] whether a wake turn ran
21
+ def absorb_mail(hold: nil)
22
+ mail_wake = @inbound.absorb_mail(hold: hold)
23
+ return false unless mail_wake
24
+
25
+ run_mail_wake_turn(mail_wake)
26
+ true
27
+ rescue SystemCallError, IOError => e
28
+ Log.exception(:worker, "mail_failed", e)
29
+ false
30
+ end
31
+
32
+ # Why a pass's mail can't wake chi: an exit a client asked for, or
33
+ # input queued (its turn reads the mail); nil when it may.
34
+ def pass_hold
35
+ return :exit if @exit_claim.taken?
36
+
37
+ :queued unless nothing_queued?
38
+ end
39
+
40
+ # A turn +id+ starts: the peer notes waiting are read by it
41
+ # (PeerReceipts#turn_started); whether a wake's note goes back plain
42
+ # (#run_wake sets it) starts false.
43
+ # Logged, never raised: the turn runs without it.
44
+ def peer_turn_started(id)
45
+ @unmarked_this_turn = false
46
+ @peer_receipts.turn_started(id)
47
+ rescue SystemCallError, IOError => e
48
+ Log.exception(:worker, "peer_receipts_failed", e)
49
+ end
50
+
51
+ def settle_peer_turn(id, result, error)
52
+ yielded = false
53
+ yield
54
+ yielded = true
55
+ ensure
56
+ peer_receipts_ended(id, result, error || (yielded ? nil : $!))
57
+ end
58
+
59
+ # The receipts the turn +id+ woke or read (PeerReceipts#turn_ended): how
60
+ # it ended, or held when a wake's note went back plain. Logged, never
61
+ # raised: the turn's own save comes next.
62
+ def peer_receipts_ended(id, result, error)
63
+ outcome = if error then :failed
64
+ elsif result&.canceled? then :canceled
65
+ else :completed
66
+ end
67
+ @peer_receipts.turn_ended(id, outcome: outcome, unmarked: @unmarked_this_turn)
68
+ rescue SystemCallError, IOError => e
69
+ Log.exception(:worker, "peer_receipts_failed", e)
70
+ end
71
+ end
72
+ end
73
+ end
@@ -23,6 +23,9 @@ module Samagotchi
23
23
  # serves the session (TurnCheckpoint.settle). Its queued id's wait
24
24
  # (chi send --queue --wait) reads the end it records in the session dir.
25
25
  def settle_interrupted_turn
26
+ # No turn runs yet: a peer receipt left woke or read is a dead
27
+ # worker's turn's (the mark's, or one that never began), ended failed.
28
+ @peer_receipts&.settle_open
26
29
  mark = TurnCheckpoint.settle(@session, session_dir: @session_dir)
27
30
  return unless mark
28
31
 
@@ -6,6 +6,7 @@ require_relative "../child_reports"
6
6
  require_relative "../client_id"
7
7
  require_relative "../iteration_limit"
8
8
  require_relative "../log"
9
+ require_relative "../peer_mailbox"
9
10
  require_relative "../session_inbox"
10
11
  require_relative "../turn_origin"
11
12
 
@@ -102,12 +103,12 @@ module Samagotchi
102
103
  max_iterations: IterationLimit.for) do |result, error|
103
104
  if error
104
105
  steps_kept = @turn_flow.prompt_turn_failed(error: error, wake: failed, wake_kept: kept) == :kept
105
- @inbound.unmark_wake(mark) if mark && !steps_kept
106
+ @unmarked_this_turn = @inbound.unmark_wake(mark) if mark && !steps_kept
106
107
  @wakes.pause!
107
108
  else
108
109
  @continue_offer.after_turn(result)
109
110
  if result.canceled? && @turn_flow.restores != restores
110
- @inbound.unmark_wake(mark) if mark
111
+ @unmarked_this_turn = @inbound.unmark_wake(mark) if mark
111
112
  @wakes.pause!
112
113
  end
113
114
  end
@@ -118,15 +119,27 @@ module Samagotchi
118
119
  # turn from context:<name> whose first message is the wake note already
119
120
  # in the conversation (named by +turn_id+), on the same rules as a
120
121
  # delegate report's wake turn (#run_wake): it counts toward
121
- # session.max_wakes (a peer's answer toward context.peer_turns too,
122
+ # session.max_wakes (a peer's answer toward peer.turns too,
122
123
  # unless it agrees).
123
124
  # +context_wake+: a WorkerInbound::ContextWake.
124
125
  def run_context_wake_turn(context_wake)
125
126
  name = context_wake.name
126
- Log.info(:worker, "context_wake_turn", name: name, in_a_row: @wakes.count!(peer: context_wake.peer_turn?))
127
+ Log.info(:worker, "context_wake_turn", name: name, in_a_row: @wakes.count!)
127
128
  run_wake(origin: context_wake.origin, failed: "the change in attached context #{name}", mark: context_wake)
128
129
  end
129
130
 
131
+ # A turn nobody typed for a peer's message that asked (a mail wake): a
132
+ # continue turn from peer:<name> whose first message is the batch's
133
+ # last note, already in the conversation (named by its turn id), on
134
+ # #run_wake's rules. It counts toward session.max_wakes and, unless the
135
+ # message agrees, toward peer.turns.
136
+ # +mail_wake+: a WorkerInbound::MailWake.
137
+ def run_mail_wake_turn(mail_wake)
138
+ Log.info(:worker, "mail_wake_turn", peer: mail_wake.peer, in_a_row: @wakes.count!(peer: !mail_wake.agreed))
139
+ run_wake(origin: mail_wake.origin, failed: "the message from your peer agent #{PeerMailbox.label(mail_wake.peer)}",
140
+ mark: mail_wake)
141
+ end
142
+
130
143
  # The background tasks this session started that finished unseen, as
131
144
  # notes (WorkerTaskWakes#take), and the wake turn the first one may
132
145
  # start.
@@ -184,7 +197,9 @@ module Samagotchi
184
197
 
185
198
  # The idle loop's sleep: the fallback tick, or less while reports or
186
199
  # attached-context wakes wait out the start grace.
187
- def idle_wait = @wakes.idle_wait(@poll_interval) { wake_state == :due || @inbound.context_wake_waiting? }
200
+ def idle_wait
201
+ @wakes.idle_wait(@poll_interval) { wake_state == :due || @inbound.context_wake_waiting? || @inbound.mail_wake_waiting? }
202
+ end
188
203
  end
189
204
  end
190
205
  end
@@ -51,6 +51,7 @@ require_relative "worker/child_side"
51
51
  require_relative "worker/command_queue"
52
52
  require_relative "worker/block_fixes"
53
53
  require_relative "worker/senders"
54
+ require_relative "worker/mail"
54
55
 
55
56
  module Samagotchi
56
57
  # The loop of a background session worker, once it owns the session (see
@@ -103,6 +104,7 @@ module Samagotchi
103
104
  include CommandQueuePart
104
105
  include BlockFixesPart
105
106
  include SendersPart
107
+ include MailPart
106
108
 
107
109
  FALLBACK_TICK_SECONDS = 5
108
110
  # A worker just started runs no wake turn for delegate reports this
@@ -291,6 +293,8 @@ module Samagotchi
291
293
  @event_log.announce(type: :hook_notice, hook: "config", text: message, level: :warn, between_turns: true)
292
294
  end
293
295
  prune_tombstones
296
+ # What this worker did with each peer message (PeerReceipts, read once).
297
+ @peer_receipts = PeerReceipts.new(session_id: @session_id, state_dir: @state_dir)
294
298
  settle_interrupted_turn
295
299
  settle_stale_status
296
300
  # Before the Bridge serves anything: a UI joining a resumed worker's
@@ -350,17 +354,16 @@ module Samagotchi
350
354
  # This session's own delegate children's news (rings in children/).
351
355
  @child_reports = ChildReports.new(session_id: @session_id, state_dir: @state_dir,
352
356
  predecessor: @session.continues)
353
- # Its attached context's notes (ContextSources); a peer's text goes in
354
- # its note up to the tool output cap, as a task's does (WorkerTaskWakes).
357
+ # Its attached context's notes (ContextSources).
355
358
  @context_absorber = ContextAbsorber.new(session_id: @session_id, state_dir: @state_dir,
356
- project_root: @session.project_root, project_id: @session.project_id,
357
- peer_sources: @engine.peer_sources, peer_turns: -> { @wakes.peer_turns },
358
- cap: -> { ToolOutputCut.max_chars(nil) })
359
+ project_root: @session.project_root, project_id: @session.project_id)
359
360
  # What comes in between turns, and how each kind is saved.
360
361
  @inbound = WorkerInbound.new(session: @session, state_dir: @state_dir, session_dir: @session_dir, engine: @engine,
361
362
  event_log: @event_log, turn_state: @turn_state, context_absorber: @context_absorber, wakes: @wakes,
362
363
  awaiting_continue: -> { @turn_flow.awaiting_continue? },
363
364
  stopped: -> { stopped_on_disk? },
365
+ peer_registry: @engine.peer_registry, peer_receipts: @peer_receipts,
366
+ mail_cap: -> { ToolOutputCut.max_chars(nil) },
364
367
  queue_command: lambda { |line, client_id, after_file, enqueued_id, author: nil|
365
368
  @bridge.queue_command(line, client_id: client_id, after_file: after_file,
366
369
  enqueued_id: enqueued_id, author: author)
@@ -507,6 +510,7 @@ module Samagotchi
507
510
  # ahead of an exit or restart a client asked for: it is a note then.
508
511
  @inbound.absorb_notes
509
512
  absorb_fresh_verdicts
513
+ return if absorb_mail(hold: pass_hold)
510
514
  return if absorb_context(wake: nothing_queued? && !@exit_claim.taken?)
511
515
 
512
516
  if (prompt = @inbound.take_initial_prompt)
@@ -708,6 +712,7 @@ module Samagotchi
708
712
  # A first turn sees the context attached before it, and any turn the
709
713
  # background tasks that finished since the last look.
710
714
  absorb_context(before_turn: true)
715
+ absorb_mail(hold: :before_turn)
711
716
  @task_wakes.absorb
712
717
  user_input(origin.client_id)
713
718
  @continue_offer.drop(origin)
@@ -763,6 +768,7 @@ module Samagotchi
763
768
  @turn_author = origin.participant_author
764
769
  restores = @turn_flow.restores
765
770
  begin
771
+ peer_turn_started(turn_args[:id])
766
772
  @checkpoint.begin_turn(prompt: prompt, turn_id: turn_args[:id], enqueued_id: origin.enqueued_id, author: turn_author_fields(origin),
767
773
  source: turn_args[:opener_source], reply: ReplyFor.opener_fields(@session.messages, turn_args[:reply_for]))
768
774
  @session.status = Session::STATUS_RUNNING
@@ -788,7 +794,7 @@ module Samagotchi
788
794
  @checkpoint.end_turn
789
795
  refuse_queued_commands
790
796
  end
791
- yield result, error
797
+ settle_peer_turn(turn_args[:id], result, error) { yield result, error }
792
798
  response = result&.output
793
799
  # A turn that ran out of iterations and asks whether to continue left
794
800
  # no reply: its text is what came before its last tool calls, and a