samagotchi 0.186.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 (153) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +4 -0
  4. data/docs/architecture.md +8 -4
  5. data/docs/bundles.md +124 -120
  6. data/docs/cli.md +26 -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/inline-widgets.md +18 -0
  15. data/docs/internals/llm-context-forget.md +5 -6
  16. data/docs/internals/objectives.md +1 -0
  17. data/docs/internals/pages.md +175 -0
  18. data/docs/internals/peers.md +149 -0
  19. data/docs/internals/remote-sessions.md +7 -4
  20. data/docs/internals/web-frontend.md +65 -40
  21. data/docs/internals/web-push.md +1 -1
  22. data/docs/memory.md +8 -1
  23. data/docs/pages.md +151 -0
  24. data/docs/peers.md +141 -0
  25. data/docs/plugins.md +52 -27
  26. data/docs/sessions.md +8 -4
  27. data/docs/sub-agent.md +5 -5
  28. data/lib/samagotchi/bridge.rb +3 -3
  29. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  30. data/lib/samagotchi/bundle_command/check.rb +1 -1
  31. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  32. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  33. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  34. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  35. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  39. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  40. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  41. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  42. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  43. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  44. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  45. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  46. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  47. data/lib/samagotchi/client_id.rb +15 -1
  48. data/lib/samagotchi/config.rb +8 -7
  49. data/lib/samagotchi/context_absorber.rb +23 -277
  50. data/lib/samagotchi/context_sources.rb +17 -69
  51. data/lib/samagotchi/engine/messages.rb +12 -1
  52. data/lib/samagotchi/engine/plugins.rb +1 -1
  53. data/lib/samagotchi/engine.rb +7 -6
  54. data/lib/samagotchi/engine_peers.rb +0 -3
  55. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  56. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  57. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  58. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  59. data/lib/samagotchi/inline_widgets.rb +73 -0
  60. data/lib/samagotchi/log_line.rb +1 -1
  61. data/lib/samagotchi/note_move.rb +3 -1
  62. data/lib/samagotchi/page_command.rb +243 -0
  63. data/lib/samagotchi/pages/builder.rb +186 -0
  64. data/lib/samagotchi/pages/launch.rb +193 -0
  65. data/lib/samagotchi/pages/runner.rb +154 -0
  66. data/lib/samagotchi/pages/store.rb +152 -0
  67. data/lib/samagotchi/pages.rb +119 -0
  68. data/lib/samagotchi/peer_command.rb +192 -0
  69. data/lib/samagotchi/peer_continue.rb +99 -0
  70. data/lib/samagotchi/peer_exchanges.rb +3 -3
  71. data/lib/samagotchi/peer_mailbox.rb +360 -0
  72. data/lib/samagotchi/peer_note.rb +208 -0
  73. data/lib/samagotchi/peer_receipts.rb +247 -0
  74. data/lib/samagotchi/peer_registry.rb +44 -0
  75. data/lib/samagotchi/peer_roster.rb +79 -0
  76. data/lib/samagotchi/peer_say.rb +168 -0
  77. data/lib/samagotchi/plugin/api.rb +29 -21
  78. data/lib/samagotchi/plugin/context.rb +7 -0
  79. data/lib/samagotchi/plugin/loader.rb +3 -3
  80. data/lib/samagotchi/plugin/peer.rb +175 -64
  81. data/lib/samagotchi/plugin/peers.rb +70 -0
  82. data/lib/samagotchi/run_options.rb +3 -1
  83. data/lib/samagotchi/schedule_command.rb +10 -3
  84. data/lib/samagotchi/schedule_display.rb +32 -0
  85. data/lib/samagotchi/session_access/contract.rb +19 -2
  86. data/lib/samagotchi/session_access/local.rb +132 -14
  87. data/lib/samagotchi/session_access/remote.rb +4 -2
  88. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  89. data/lib/samagotchi/session_continue.rb +12 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  92. data/lib/samagotchi/session_manager/removal.rb +2 -0
  93. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  94. data/lib/samagotchi/session_manager.rb +1 -0
  95. data/lib/samagotchi/session_stores.rb +17 -0
  96. data/lib/samagotchi/steer.rb +1 -1
  97. data/lib/samagotchi/system_prompt.rb +1 -1
  98. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  99. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  100. data/lib/samagotchi/testing/boundary.rb +4 -13
  101. data/lib/samagotchi/testing/bundle.rb +40 -5
  102. data/lib/samagotchi/testing/install.rb +4 -4
  103. data/lib/samagotchi/testing/recording_api.rb +2 -1
  104. data/lib/samagotchi/tools/context_read.rb +0 -14
  105. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  106. data/lib/samagotchi/version.rb +1 -1
  107. data/lib/samagotchi/web/app.rb +7 -18
  108. data/lib/samagotchi/web/message_display.rb +4 -2
  109. data/lib/samagotchi/web/page_routes.rb +116 -0
  110. data/lib/samagotchi/web/peer_routes.rb +133 -0
  111. data/lib/samagotchi/web/public/app.js +35 -95
  112. data/lib/samagotchi/web/public/bubbles.js +2 -2
  113. data/lib/samagotchi/web/public/cards_place.js +20 -1
  114. data/lib/samagotchi/web/public/context_chips.js +45 -46
  115. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  116. data/lib/samagotchi/web/public/history_shape.js +3 -2
  117. data/lib/samagotchi/web/public/index.html +16 -0
  118. data/lib/samagotchi/web/public/notify.js +1 -1
  119. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  120. data/lib/samagotchi/web/public/page_links.js +33 -0
  121. data/lib/samagotchi/web/public/page_model.js +68 -0
  122. data/lib/samagotchi/web/public/page_route.js +24 -0
  123. data/lib/samagotchi/web/public/page_table.js +74 -0
  124. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  125. data/lib/samagotchi/web/public/page_view.js +219 -0
  126. data/lib/samagotchi/web/public/pages.css +77 -0
  127. data/lib/samagotchi/web/public/pages_group.js +65 -0
  128. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  129. data/lib/samagotchi/web/public/peer_data.js +13 -11
  130. data/lib/samagotchi/web/public/peer_links.js +12 -7
  131. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  132. data/lib/samagotchi/web/public/peer_note.js +7 -3
  133. data/lib/samagotchi/web/public/peer_text.js +4 -4
  134. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  135. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  136. data/lib/samagotchi/web/public/session_view.js +2 -2
  137. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  138. data/lib/samagotchi/web/public/turn_block.js +7 -3
  139. data/lib/samagotchi/web/public/turn_events.js +6 -0
  140. data/lib/samagotchi/web/public/views.js +161 -0
  141. data/lib/samagotchi/web/push/attention.rb +3 -2
  142. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  143. data/lib/samagotchi/web/viewer.rb +1 -1
  144. data/lib/samagotchi/worker/leave.rb +3 -0
  145. data/lib/samagotchi/worker/mail.rb +73 -0
  146. data/lib/samagotchi/worker/startup.rb +3 -0
  147. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  148. data/lib/samagotchi/worker.rb +12 -6
  149. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  150. data/lib/samagotchi/worker_inbound.rb +43 -46
  151. data/lib/samagotchi/worker_wakes.rb +26 -21
  152. metadata +39 -2
  153. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -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);
@@ -0,0 +1,161 @@
1
+ // The page's views by hash: All sessions, its own view at #/sessions so the
2
+ // browser's back button leaves it, and the open session's #/s/<id>, so a
3
+ // reload or a copied link opens it again. A hash typed, pasted or reached by
4
+ // back selects what it names (hashIntent). Opened from the page, All sessions
5
+ // closes with history.back(). A page, #/p/NAME (page_view.js), is read here
6
+ // before the session intent (hashIntent calls it "keep"): it shows in place
7
+ // of the session area, and the session's hash isn't written while it is
8
+ // open. app.js makes this once its pieces exist and hands the functions on
9
+ // (lazily to anything made before it).
10
+ //
11
+ // +win+ / +doc+: the window (location, history, the hashchange listener) and
12
+ // the document. +participant+: the participant's page (createParticipantMain),
13
+ // or null on the owner's. +store+: the session store (selected, sessions,
14
+ // update). +lists+: lists_view.js (selecting, leaveSelect, chainPop,
15
+ // familyPop). +topStripEl+: #topStrip. +pictures+: the picture viewer.
16
+ // +eventsLive()+: the hub's stream is open. +refresh()+, +updateSessionTitle()+,
17
+ // +select(id)+, +clearSelection()+: the page's. +ownerClaim()+: owner_claim.js's
18
+ // (made after this, so a getter). +pages+: page_view.js's view, or null
19
+ // without the pages capability (then no hash is a page). +allViewOpened()+:
20
+ // All sessions just opened (the Pages group reads its list then).
21
+ import { ALL_SESSIONS_HASH, sessionHash } from "./route.js";
22
+ import { hashIntent } from "./hash_intent.js";
23
+ import { claimFromHash } from "./claim_link.js";
24
+ import { sortedByUpdated } from "./sessions_list.js";
25
+ import { openPageName, pageHash } from "./page_route.js";
26
+
27
+ export function createViews({
28
+ win = globalThis, doc = globalThis.document, participant, store, lists, topStripEl, pictures, eventsLive,
29
+ refresh, updateSessionTitle, select, clearSelection, ownerClaim, pages = null, allViewOpened = () => {},
30
+ }) {
31
+ const { location, history } = win;
32
+ const $ = (sel) => doc.querySelector(sel);
33
+ let allViewPushed = false;
34
+ // A page this page opened itself (a Pages card, an answer's link): Back is
35
+ // history.back(), to where it was opened from ("sessions" or "back").
36
+ let pagePushed = null;
37
+
38
+ // The page the hash opens, or null.
39
+ function pageOpen() {
40
+ return openPageName(location.hash, { participant, canPages: !!pages });
41
+ }
42
+ function openPage(name) {
43
+ if (pageOpen() === name) return;
44
+ pagePushed = allViewOpen() ? "sessions" : "back";
45
+ location.hash = pageHash(name);
46
+ }
47
+ // Back: where the page was opened from, else All sessions.
48
+ function closePage() {
49
+ if (!pageOpen()) return;
50
+ if (pagePushed) history.back();
51
+ else leaveAllView(ALL_SESSIONS_HASH);
52
+ }
53
+ // The page went (deleted, or no such page on Refresh): All sessions, in
54
+ // its history entry.
55
+ function leavePage() {
56
+ if (pageOpen()) leaveAllView(ALL_SESSIONS_HASH);
57
+ }
58
+ function pageBackLabel() {
59
+ return pagePushed === "back" ? "Back" : "Sessions";
60
+ }
61
+
62
+ function allViewOpen() {
63
+ return !participant && location.hash === ALL_SESSIONS_HASH;
64
+ }
65
+ function openAllView() {
66
+ if (allViewOpen()) return;
67
+ allViewPushed = true;
68
+ location.hash = ALL_SESSIONS_HASH;
69
+ }
70
+ function closeAllView() {
71
+ if (!allViewOpen()) return;
72
+ if (allViewPushed) {
73
+ history.back();
74
+ } else {
75
+ leaveAllView(sessionHash(store.selected));
76
+ }
77
+ }
78
+ // Leave all sessions, or a page, for a place of our own (a picked session,
79
+ // a new session, All sessions after a page's Delete): replace its history
80
+ // entry, since history.back() would come back later with the session the
81
+ // view was opened from.
82
+ function leaveAllView(hash) {
83
+ history.replaceState(null, "", location.pathname + location.search + hash);
84
+ allViewPushed = false;
85
+ applyView();
86
+ }
87
+ // The open session in the URL, so a reload or a copied link opens it again.
88
+ // Switching sessions replaces the entry; only all sessions pushes one.
89
+ // A page open: a session picked (a continue, a created session) leaves the
90
+ // page for it; the selection cleared under it (a gone session) doesn't.
91
+ function setSessionHash(id) {
92
+ if (allViewOpen()) return;
93
+ if (pageOpen()) {
94
+ if (id) leaveAllView(sessionHash(id));
95
+ return;
96
+ }
97
+ const hash = sessionHash(id);
98
+ if (location.hash === hash || (!hash && !location.hash)) return;
99
+ history.replaceState(null, "", location.pathname + location.search + hash);
100
+ }
101
+ // A #/s/<id> typed or pasted into the address bar, or reached by back.
102
+ // A claim link (claim_link.js; #/s/<id>?t=…&q=…, or the participant's
103
+ // #s=<id>&t=… opened in this browser) opens its session and, once drawn,
104
+ // shows the claim. The start page's own hash ("#/", or none) while one is
105
+ // open is the start page: the same clear the + button does, so the page and
106
+ // the composer stop addressing the session the URL has left behind.
107
+ function selectFromHash() {
108
+ const claim = claimFromHash(location.hash);
109
+ if (claim) ownerClaim().pending(claim);
110
+ // A participant's page has one session, whatever the hash names.
111
+ const intent = participant ? { kind: "session", id: participant.sessionId } : hashIntent(location.hash, { selected: store.selected, claim });
112
+ if (intent.kind === "session" && intent.id !== store.selected) select(intent.id);
113
+ else if (claim) ownerClaim().showPending();
114
+ else if (intent.kind === "start") clearSelection();
115
+ }
116
+ function applyView() {
117
+ const open = allViewOpen();
118
+ const page = pageOpen();
119
+ doc.body.classList.toggle("page-view", !!page);
120
+ if (page) {
121
+ pictures.close(); // #center, the picture viewer's parent, is hidden there
122
+ pages.open(page);
123
+ } else {
124
+ pagePushed = null;
125
+ pages?.close();
126
+ }
127
+ if (!open && !page) {
128
+ allViewPushed = false;
129
+ }
130
+ if (!open) {
131
+ // A running batch ends on its own and clears the picks then.
132
+ if (lists.selecting.on && !lists.selecting.running) lists.leaveSelect();
133
+ topStripEl.scrollLeft = 0; // a phone's strip scrolls sideways to the tile
134
+ }
135
+ doc.body.classList.toggle("all-view", open);
136
+ // The sessions pill is the view's button there: pressed while it is open.
137
+ $("#stripStatus").setAttribute("aria-pressed", String(open));
138
+ updateSessionTitle();
139
+ // Its chip was in the list just hidden (the strip, or all sessions).
140
+ lists.chainPop.close();
141
+ if (open) {
142
+ lists.familyPop.close(); pictures.close(); // the strip and #center (the picture viewer's parent) are hidden there
143
+ // The list is live; only its order can lag (upserts keep cards in
144
+ // place), so the all view opens in the server's order.
145
+ // A new list: the lists' redraw draws the all view (lists.render).
146
+ store.update({ sessions: sortedByUpdated(store.sessions) });
147
+ if (!eventsLive()) refresh();
148
+ allViewOpened();
149
+ $("#filter").select();
150
+ }
151
+ }
152
+ win.addEventListener("hashchange", () => {
153
+ applyView();
154
+ selectFromHash();
155
+ });
156
+
157
+ return {
158
+ allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView,
159
+ pageOpen, openPage, closePage, leavePage, pageBackLabel,
160
+ };
161
+ }
@@ -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
@@ -48,7 +48,7 @@ module Samagotchi
48
48
  # docs/internals/web-frontend.md, The viewer).
49
49
  Viewer::CAPABILITIES = %w[
50
50
  sessions models prompt_history push context working_set working_set_items participants_admin rename images
51
- session_controls revise answer_cards render block_renderers stop_any_turn steer_any_turn
51
+ session_controls revise answer_cards render block_renderers stop_any_turn steer_any_turn pages
52
52
  ].freeze
53
53
 
54
54
  # A participant's capabilities: names of their own (the owner's are
@@ -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