samagotchi 0.187.0 → 0.189.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 (184) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +96 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +13 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +139 -120
  7. data/docs/cli.md +46 -8
  8. data/docs/configuration.md +4 -4
  9. data/docs/context.md +18 -162
  10. data/docs/guardrails.md +6 -3
  11. data/docs/hooks.md +2 -1
  12. data/docs/internals/attached-context.md +19 -37
  13. data/docs/internals/bridge.md +1 -0
  14. data/docs/internals/bundles.md +3 -3
  15. data/docs/internals/engine.md +2 -2
  16. data/docs/internals/llm-context-forget.md +5 -6
  17. data/docs/internals/objectives.md +1 -0
  18. data/docs/internals/pages.md +71 -21
  19. data/docs/internals/peers.md +149 -0
  20. data/docs/internals/remote-sessions.md +7 -4
  21. data/docs/internals/session-lifecycle.md +19 -6
  22. data/docs/internals/web-frontend.md +63 -39
  23. data/docs/internals/web-push.md +12 -6
  24. data/docs/memory.md +1 -1
  25. data/docs/pages.md +70 -16
  26. data/docs/peers.md +144 -0
  27. data/docs/plugins.md +77 -28
  28. data/docs/releasing.md +1 -1
  29. data/docs/scheduling.md +71 -8
  30. data/docs/sessions.md +12 -8
  31. data/docs/sub-agent.md +5 -5
  32. data/docs/testing.md +1 -1
  33. data/lib/samagotchi/bridge.rb +3 -3
  34. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  35. data/lib/samagotchi/bundle_command/check.rb +1 -1
  36. data/lib/samagotchi/bundle_manifest.rb +34 -5
  37. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  38. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  39. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  40. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  41. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  42. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  43. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  44. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  45. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  46. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  47. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  49. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
  50. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  51. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  52. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  53. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  54. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  55. data/lib/samagotchi/client_id.rb +15 -1
  56. data/lib/samagotchi/config.rb +8 -7
  57. data/lib/samagotchi/context_absorber.rb +23 -277
  58. data/lib/samagotchi/context_sources.rb +17 -69
  59. data/lib/samagotchi/engine/messages.rb +12 -1
  60. data/lib/samagotchi/engine/plugins.rb +1 -1
  61. data/lib/samagotchi/engine.rb +7 -6
  62. data/lib/samagotchi/engine_peers.rb +0 -3
  63. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  64. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  65. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  66. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  67. data/lib/samagotchi/inline_widgets.rb +11 -3
  68. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  69. data/lib/samagotchi/log_line.rb +1 -1
  70. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  71. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  72. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  73. data/lib/samagotchi/note_move.rb +3 -1
  74. data/lib/samagotchi/page_command.rb +25 -13
  75. data/lib/samagotchi/pages/builder.rb +7 -8
  76. data/lib/samagotchi/pages/bundled.rb +83 -0
  77. data/lib/samagotchi/pages/launch.rb +22 -4
  78. data/lib/samagotchi/pages/runner.rb +7 -2
  79. data/lib/samagotchi/pages/runtime.rb +83 -0
  80. data/lib/samagotchi/pages/store.rb +29 -7
  81. data/lib/samagotchi/pages.rb +47 -3
  82. data/lib/samagotchi/peer_command.rb +192 -0
  83. data/lib/samagotchi/peer_continue.rb +105 -0
  84. data/lib/samagotchi/peer_exchanges.rb +3 -3
  85. data/lib/samagotchi/peer_mailbox.rb +360 -0
  86. data/lib/samagotchi/peer_note.rb +208 -0
  87. data/lib/samagotchi/peer_receipts.rb +247 -0
  88. data/lib/samagotchi/peer_registry.rb +44 -0
  89. data/lib/samagotchi/peer_roster.rb +79 -0
  90. data/lib/samagotchi/peer_say.rb +168 -0
  91. data/lib/samagotchi/plugin/api.rb +29 -21
  92. data/lib/samagotchi/plugin/context.rb +7 -0
  93. data/lib/samagotchi/plugin/loader.rb +3 -3
  94. data/lib/samagotchi/plugin/peer.rb +175 -64
  95. data/lib/samagotchi/plugin/peers.rb +70 -0
  96. data/lib/samagotchi/run_options.rb +3 -2
  97. data/lib/samagotchi/schedule_command.rb +88 -39
  98. data/lib/samagotchi/schedule_display.rb +101 -0
  99. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  100. data/lib/samagotchi/schedules/edit_part.rb +120 -0
  101. data/lib/samagotchi/schedules/history_part.rb +51 -0
  102. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  103. data/lib/samagotchi/schedules/notices_part.rb +116 -0
  104. data/lib/samagotchi/schedules/protection_part.rb +103 -0
  105. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  106. data/lib/samagotchi/schedules.rb +134 -330
  107. data/lib/samagotchi/session_access/contract.rb +18 -1
  108. data/lib/samagotchi/session_access/local.rb +140 -14
  109. data/lib/samagotchi/session_access/remote.rb +6 -3
  110. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  111. data/lib/samagotchi/session_chain/delete.rb +7 -5
  112. data/lib/samagotchi/session_continue.rb +12 -0
  113. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  114. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  115. data/lib/samagotchi/session_lifecycle.rb +3 -2
  116. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  117. data/lib/samagotchi/session_manager/removal.rb +18 -9
  118. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  119. data/lib/samagotchi/session_manager.rb +1 -0
  120. data/lib/samagotchi/session_protection.rb +99 -0
  121. data/lib/samagotchi/session_retention.rb +21 -6
  122. data/lib/samagotchi/session_stores.rb +17 -0
  123. data/lib/samagotchi/sessions_command.rb +4 -0
  124. data/lib/samagotchi/steer.rb +1 -1
  125. data/lib/samagotchi/system_prompt.rb +1 -1
  126. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  127. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  128. data/lib/samagotchi/testing/boundary.rb +17 -13
  129. data/lib/samagotchi/testing/bundle.rb +40 -5
  130. data/lib/samagotchi/testing/install.rb +4 -4
  131. data/lib/samagotchi/testing/recording_api.rb +2 -1
  132. data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
  133. data/lib/samagotchi/tools/context_read.rb +0 -14
  134. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  135. data/lib/samagotchi/turn_outcome.rb +41 -0
  136. data/lib/samagotchi/version.rb +1 -1
  137. data/lib/samagotchi/web/app.rb +2 -13
  138. data/lib/samagotchi/web/message_display.rb +4 -2
  139. data/lib/samagotchi/web/page_routes.rb +13 -8
  140. data/lib/samagotchi/web/peer_routes.rb +133 -0
  141. data/lib/samagotchi/web/public/app.js +23 -29
  142. data/lib/samagotchi/web/public/bubbles.js +2 -2
  143. data/lib/samagotchi/web/public/cards_place.js +20 -1
  144. data/lib/samagotchi/web/public/context_chips.js +45 -46
  145. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  146. data/lib/samagotchi/web/public/history_shape.js +3 -2
  147. data/lib/samagotchi/web/public/index.html +24 -2
  148. data/lib/samagotchi/web/public/notify.js +1 -1
  149. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  150. data/lib/samagotchi/web/public/page_links.js +1 -1
  151. data/lib/samagotchi/web/public/page_view.js +10 -6
  152. data/lib/samagotchi/web/public/pages.css +9 -2
  153. data/lib/samagotchi/web/public/pages_group.js +21 -19
  154. data/lib/samagotchi/web/public/pages_list.js +73 -0
  155. data/lib/samagotchi/web/public/pages_model.js +54 -0
  156. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  157. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  158. data/lib/samagotchi/web/public/peer_data.js +13 -11
  159. data/lib/samagotchi/web/public/peer_links.js +12 -7
  160. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  161. data/lib/samagotchi/web/public/peer_note.js +7 -3
  162. data/lib/samagotchi/web/public/peer_text.js +4 -4
  163. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  164. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  165. data/lib/samagotchi/web/public/session_view.js +2 -2
  166. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  167. data/lib/samagotchi/web/public/turn_block.js +7 -3
  168. data/lib/samagotchi/web/public/turn_events.js +6 -0
  169. data/lib/samagotchi/web/public/views.js +77 -23
  170. data/lib/samagotchi/web/push/attention.rb +3 -2
  171. data/lib/samagotchi/web/push/notifier.rb +4 -3
  172. data/lib/samagotchi/web/server.rb +3 -1
  173. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  174. data/lib/samagotchi/web/session_hub.rb +64 -19
  175. data/lib/samagotchi/worker/leave.rb +3 -0
  176. data/lib/samagotchi/worker/mail.rb +73 -0
  177. data/lib/samagotchi/worker/startup.rb +3 -0
  178. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  179. data/lib/samagotchi/worker.rb +12 -6
  180. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  181. data/lib/samagotchi/worker_inbound.rb +43 -46
  182. data/lib/samagotchi/worker_wakes.rb +26 -21
  183. metadata +35 -2
  184. 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);
@@ -2,11 +2,12 @@
2
2
  // browser's back button leaves it, and the open session's #/s/<id>, so a
3
3
  // reload or a copied link opens it again. A hash typed, pasted or reached by
4
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).
5
+ // closes with history.back(). A page, #/p/NAME (page_view.js), and the Pages
6
+ // list, #/pages (pages_list.js), are read here before the session intent
7
+ // (hashIntent calls them "keep"): they show in place of the session area,
8
+ // and the session's hash isn't written while one is open. app.js makes this
9
+ // once its pieces exist and hands the functions on (lazily to anything made
10
+ // before it).
10
11
  //
11
12
  // +win+ / +doc+: the window (location, history, the hashchange listener) and
12
13
  // the document. +participant+: the participant's page (createParticipantMain),
@@ -16,24 +17,38 @@
16
17
  // +eventsLive()+: the hub's stream is open. +refresh()+, +updateSessionTitle()+,
17
18
  // +select(id)+, +clearSelection()+: the page's. +ownerClaim()+: owner_claim.js's
18
19
  // (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).
20
+ // without the pages capability (then no hash is a page). +pagesList+:
21
+ // pages_list.js's view, or null (without the capability, or an older cached
22
+ // app.js: then #/pages is no view). +allViewOpened()+: All sessions just
23
+ // opened (the page's list of pages is read again then).
21
24
  import { ALL_SESSIONS_HASH, sessionHash } from "./route.js";
22
25
  import { hashIntent } from "./hash_intent.js";
23
26
  import { claimFromHash } from "./claim_link.js";
24
27
  import { sortedByUpdated } from "./sessions_list.js";
25
28
  import { openPageName, pageHash } from "./page_route.js";
29
+ import { PAGES_HASH, pagesListOpen } from "./pages_list.js";
26
30
 
27
31
  export function createViews({
28
32
  win = globalThis, doc = globalThis.document, participant, store, lists, topStripEl, pictures, eventsLive,
29
- refresh, updateSessionTitle, select, clearSelection, ownerClaim, pages = null, allViewOpened = () => {},
33
+ refresh, updateSessionTitle, select, clearSelection, ownerClaim, pages = null, pagesList = null,
34
+ allViewOpened = () => {},
30
35
  }) {
31
36
  const { location, history } = win;
32
37
  const $ = (sel) => doc.querySelector(sel);
33
38
  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;
39
+ // A page or the Pages list this page opened itself is pushed with where it
40
+ // was opened from in its history entry (history.state.from: "pages",
41
+ // "sessions" or "back" for a page, "pill" for the list), so Back and its
42
+ // label stay right when Back or Forward comes to that entry again. An
43
+ // entry with no state (typed, reloaded, replaced) wasn't pushed by us.
44
+ const openedFrom = () => history.state?.from ?? null;
45
+ // Where a page goes when it has nowhere to go back to, or went.
46
+ const pagesHome = () => (pagesList ? PAGES_HASH : ALL_SESSIONS_HASH);
47
+ // Push +hash+ with +from+, and show it (pushState fires no hashchange).
48
+ function push(hash, from) {
49
+ history.pushState({ from }, "", location.pathname + location.search + hash);
50
+ applyView();
51
+ }
37
52
 
38
53
  // The page the hash opens, or null.
39
54
  function pageOpen() {
@@ -41,22 +56,51 @@ export function createViews({
41
56
  }
42
57
  function openPage(name) {
43
58
  if (pageOpen() === name) return;
44
- pagePushed = allViewOpen() ? "sessions" : "back";
45
- location.hash = pageHash(name);
59
+ push(pageHash(name), listOpen() ? "pages" : allViewOpen() ? "sessions" : "back");
46
60
  }
47
- // Back: where the page was opened from, else All sessions.
61
+ // Back: where the page was opened from, else the Pages list (in the
62
+ // page's own entry, so that list's Back leaves for the session's hash).
48
63
  function closePage() {
49
64
  if (!pageOpen()) return;
50
- if (pagePushed) history.back();
51
- else leaveAllView(ALL_SESSIONS_HASH);
65
+ if (openedFrom()) history.back();
66
+ else leaveAllView(pagesHome());
52
67
  }
53
- // The page went (deleted, or no such page on Refresh): All sessions, in
54
- // its history entry.
68
+ // The page went (deleted, or no such page on Refresh): back to the list it
69
+ // was opened from, else the Pages list in its history entry.
55
70
  function leavePage() {
56
- if (pageOpen()) leaveAllView(ALL_SESSIONS_HASH);
71
+ if (!pageOpen()) return;
72
+ if (openedFrom() === "pages") history.back();
73
+ else leaveAllView(pagesHome());
57
74
  }
58
75
  function pageBackLabel() {
59
- return pagePushed === "back" ? "Back" : "Sessions";
76
+ const from = openedFrom();
77
+ if (from === "back") return "Back";
78
+ if (from === "sessions" || !pagesList) return "Sessions";
79
+ return "Pages";
80
+ }
81
+
82
+ // The Pages list (the pill): opened from anywhere, pushed; already open,
83
+ // nothing; from a page opened from the list, back to that list's entry.
84
+ // Back: history.back() when pushed, else the session's own hash.
85
+ function listOpen() {
86
+ return pagesListOpen(location.hash, { participant, canPages: !!pagesList });
87
+ }
88
+ function openPagesList() {
89
+ if (listOpen()) return;
90
+ if (pageOpen() && openedFrom() === "pages") {
91
+ history.back();
92
+ return;
93
+ }
94
+ push(PAGES_HASH, "pill");
95
+ }
96
+ function closePagesList() {
97
+ if (!listOpen()) return;
98
+ if (openedFrom()) history.back();
99
+ else leaveAllView(sessionHash(store.selected));
100
+ }
101
+ // A page or the Pages list is open: the session's hash isn't written.
102
+ function pagesAreaOpen() {
103
+ return !!pageOpen() || listOpen();
60
104
  }
61
105
 
62
106
  function allViewOpen() {
@@ -90,7 +134,7 @@ export function createViews({
90
134
  // page for it; the selection cleared under it (a gone session) doesn't.
91
135
  function setSessionHash(id) {
92
136
  if (allViewOpen()) return;
93
- if (pageOpen()) {
137
+ if (pagesAreaOpen()) {
94
138
  if (id) leaveAllView(sessionHash(id));
95
139
  return;
96
140
  }
@@ -116,15 +160,22 @@ export function createViews({
116
160
  function applyView() {
117
161
  const open = allViewOpen();
118
162
  const page = pageOpen();
163
+ const list = listOpen();
119
164
  doc.body.classList.toggle("page-view", !!page);
165
+ doc.body.classList.toggle("pages-list", list);
166
+ if (list) {
167
+ pictures.close(); // #center is hidden there too
168
+ pagesList.open();
169
+ } else {
170
+ pagesList?.close();
171
+ }
120
172
  if (page) {
121
173
  pictures.close(); // #center, the picture viewer's parent, is hidden there
122
174
  pages.open(page);
123
175
  } else {
124
- pagePushed = null;
125
176
  pages?.close();
126
177
  }
127
- if (!open && !page) {
178
+ if (!open && !page && !list) {
128
179
  allViewPushed = false;
129
180
  }
130
181
  if (!open) {
@@ -135,6 +186,8 @@ export function createViews({
135
186
  doc.body.classList.toggle("all-view", open);
136
187
  // The sessions pill is the view's button there: pressed while it is open.
137
188
  $("#stripStatus").setAttribute("aria-pressed", String(open));
189
+ // The pages pill: pressed on the Pages list and on a page.
190
+ $("#pagesBtn")?.setAttribute("aria-pressed", String(!!page || list));
138
191
  updateSessionTitle();
139
192
  // Its chip was in the list just hidden (the strip, or all sessions).
140
193
  lists.chainPop.close();
@@ -157,5 +210,6 @@ export function createViews({
157
210
  return {
158
211
  allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView,
159
212
  pageOpen, openPage, closePage, leavePage, pageBackLabel,
213
+ listOpen, openPagesList, closePagesList, pagesAreaOpen,
160
214
  };
161
215
  }
@@ -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
@@ -263,9 +263,10 @@ module Samagotchi
263
263
  enqueue_update("chi:#{kind}:#{version}", title, body) if kind
264
264
  end
265
265
 
266
- # A recurring schedule chi web's tick turned off (SessionHub#publish_disabled).
267
- # The key's +at+ (the tick's time) lets a later disable of the same
268
- # schedule notify again; its chi: prefix keeps it out of WAITING_TAG.
266
+ # A recurring schedule a ticker (cron, run-now or chi web's own tick)
267
+ # turned off by its budget (SessionHub#publish_disabled). The key's +at+
268
+ # (the disabling tick's time) lets a later disable of the same schedule
269
+ # notify again; its chi: prefix keeps it out of WAITING_TAG.
269
270
  def notice_schedule_disabled(event)
270
271
  data = event.data
271
272
  id = data[:id]
@@ -25,6 +25,7 @@ require_relative "auto_update"
25
25
  require_relative "token"
26
26
  require_relative "tunnel"
27
27
  require_relative "../config"
28
+ require_relative "../pages"
28
29
  require_relative "../chi_home"
29
30
  require_relative "../child_env"
30
31
  require_relative "../installed_gem"
@@ -473,7 +474,8 @@ module Samagotchi
473
474
  host = resolve_host(host)
474
475
  url ||= "http://#{url_host(host)}:#{port}/"
475
476
 
476
- hub ||= SessionHub.new(state_dir: state_dir || Session.default_state_dir, manager: manager || SessionManager)
477
+ hub ||= SessionHub.new(state_dir: state_dir || Session.default_state_dir, manager: manager || SessionManager,
478
+ pages_dir: Pages.scripts_dir)
477
479
  update_check ||= UpdateCheck.new(hub: hub)
478
480
  Token.load_or_create(token_path) if lan || public_url
479
481
  lan_option = { ip: lan.ip, token: Token::Source.new(token_path) } if lan
@@ -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
@@ -47,14 +47,17 @@ module Samagotchi
47
47
  # opened an old session without saving it has no file signal until its first save).
48
48
  FULL_PROBE_INTERVAL = 10.0
49
49
  SCHEDULE_TICK_STOP_WAIT = 5.0
50
+ # The pages folder's stamp before the first look (nil is a folder that isn't there).
51
+ UNSEEN = Object.new.freeze
50
52
  SWEEP_STOP_WAIT = 5.0
51
53
 
52
54
  # What a subscriber gets: `session` with {session: summary} for an
53
55
  # upsert, `session_gone` with {id:} for a removal, `chi` with
54
56
  # the #chi_state fields when chi version state changes, `chi_notice`
55
- # (#publish_notice) and `schedule_disabled` (#publish_disabled) for
56
- # the Push::Notifier. seq is monotonic per
57
- # hub, for the log's sake: there is no replay.
57
+ # (#publish_notice) and `schedule_disabled` (#publish_disabled: any
58
+ # ticker's budget turn-off) for the Push::Notifier, and `pages` (no data)
59
+ # when the pages' scripts folder changed (#check_pages). seq is
60
+ # monotonic per hub, for the log's sake: there is no replay.
58
61
  Event = Struct.new(:type, :seq, :data, keyword_init: true)
59
62
 
60
63
  # The projection's entry: the summary the page sees, the parsed
@@ -88,10 +91,16 @@ module Samagotchi
88
91
  # @param update_auto [String] update.auto, said in the chi state (the page's wording)
89
92
  # @param update_restart [String] update.restart, said beside it (whether
90
93
  # a newer installed chi restarts by itself: no Restart toast)
94
+ # @param pages_dir [String, nil] the pages' scripts folder
95
+ # (Pages.scripts_dir, which Server.start passes), watched for the
96
+ # `pages` event; nil watches none
91
97
  def initialize(state_dir:, manager: SessionManager, now: nil, scan_interval: SCAN_INTERVAL,
92
98
  full_probe_interval: FULL_PROBE_INTERVAL, installed_versions: InstalledVersions.new,
93
- update_auto: Config.get("update.auto"), update_restart: Config.get("update.restart"))
99
+ update_auto: Config.get("update.auto"), update_restart: Config.get("update.restart"),
100
+ pages_dir: nil)
94
101
  @state_dir = state_dir
102
+ @pages_dir = pages_dir
103
+ @pages_stamp = UNSEEN
95
104
  @update_auto = update_auto
96
105
  @update_restart = update_restart
97
106
  @installed_versions = installed_versions
@@ -112,6 +121,7 @@ module Samagotchi
112
121
  @root_cache = {} # folder → project root, for sessions saved before project_root
113
122
  @next_full_probe = nil
114
123
  @next_schedule_tick = nil
124
+ @next_notice_claim = nil
115
125
  @schedule_tick_in_flight = false
116
126
  @schedule_tick_thread = nil
117
127
  @sweep_thread = nil
@@ -157,6 +167,7 @@ module Samagotchi
157
167
  full = full_probe_due?
158
168
  SessionContinue.repair_interrupted(state_dir: @state_dir)
159
169
  scan_files
170
+ check_pages
160
171
  @sessions.each_key { |id| refresh(id, probe: full) }
161
172
  if full
162
173
  check_installed
@@ -363,7 +374,12 @@ module Samagotchi
363
374
  # the same tick cron runs, gated by schedule.tick_interval_minutes and
364
375
  # sharing schedules.lock, so cron and the hub never both fire. The scan
365
376
  # loop only launches one tick at a time; it does not wait for a firing.
377
+ # The disabled notices any ticker left are pushed from here too, with
378
+ # auto_tick off as well (#claim_disabled_if_due). Only the scan(tick:
379
+ # true) path gets here: server.rb's seeding scan(tick: false) runs before
380
+ # the Notifier subscribes, and a notice claimed then would reach no one.
366
381
  def schedule_tick
382
+ claim_disabled_if_due
367
383
  return unless Config.get("schedule.auto_tick")
368
384
 
369
385
  now = @now.call
@@ -388,9 +404,9 @@ module Samagotchi
388
404
 
389
405
  def run_schedule_tick
390
406
  schedules = Samagotchi::Schedules.new(state_dir: @state_dir)
391
- now = Time.now
392
- result = schedules.tick(now: now)
393
- publish_disabled(result, now) if result.is_a?(Samagotchi::Schedules::Tick)
407
+ schedules.tick(now: Time.now)
408
+ # Right after the tick, so a turn-off of this tick is pushed now.
409
+ publish_disabled(schedules)
394
410
  rescue StandardError => e
395
411
  Log.warn(:web, "schedule_tick_failed", error: e.class.name, msg: e.message)
396
412
  ensure
@@ -400,21 +416,36 @@ module Samagotchi
400
416
  end
401
417
  end
402
418
 
403
- # A recurring schedule this tick turned off (Schedules::Outcome#disabled):
404
- # one `schedule_disabled` event each, for the Push::Notifier (the page has
405
- # no listener), emitted the way #publish_notice does. +at+ is the tick's
406
- # time; +session_id+ is the session the schedule acts on.
407
- def publish_disabled(result, now)
408
- result.outcomes.select(&:disabled).each do |outcome|
409
- entry = outcome.entry
410
- kind = outcome.status == "skipped" ? "skipped" : "failed"
411
- data = { id: outcome.id, title: outcome.title, kind: kind,
412
- count: kind == "skipped" ? entry.skips : entry.failures,
413
- reason: outcome.detail, session_id: outcome.session_id, at: now.utc.iso8601 }
419
+ # Once per schedule.tick_interval_minutes: a lock-free read of
420
+ # schedules.json (Schedules#claim_disabled_notices), so a cron tick's or
421
+ # a run-now's turn-off reaches the phone within one interval.
422
+ def claim_disabled_if_due
423
+ now = @now.call
424
+ due = @monitor.synchronize do
425
+ next false if @next_notice_claim && now < @next_notice_claim
426
+
427
+ @next_notice_claim = now + (Samagotchi::Schedules.tick_interval_minutes * 60)
428
+ true
429
+ end
430
+ publish_disabled(Samagotchi::Schedules.new(state_dir: @state_dir)) if due
431
+ end
432
+
433
+ # A recurring schedule a ticker turned off by its budget (any ticker: the
434
+ # notice is in schedules.json, Schedules#claim_disabled_notices): one
435
+ # `schedule_disabled` event each, for the Push::Notifier (the page has no
436
+ # listener), emitted the way #publish_notice does, after the claim let
437
+ # the lock go. +at+ is the disabling tick's time; +session_id+ is the
438
+ # session the schedule acts on. The claim clears each notice before it
439
+ # is emitted: the Notifier's dedupe is per process, so two chi webs on
440
+ # one state dir would otherwise both push it.
441
+ def publish_disabled(schedules)
442
+ schedules.claim_disabled_notices(now: Time.now).each do |data|
414
443
  @monitor.synchronize { emit("schedule_disabled", data) }
415
444
  rescue StandardError => e
416
- Log.warn(:web, "schedule_disabled_failed", id: outcome.id, error: e.class.name, msg: e.message)
445
+ Log.warn(:web, "schedule_disabled_failed", id: data[:id], error: e.class.name, msg: e.message)
417
446
  end
447
+ rescue StandardError => e
448
+ Log.warn(:web, "schedule_notices_failed", error: e.class.name, msg: e.message)
418
449
  end
419
450
 
420
451
  # A change (the first look too, unless it finds nothing) is a `chi`
@@ -444,6 +475,20 @@ module Samagotchi
444
475
  end
445
476
  end
446
477
 
478
+ # The pages' scripts folder: one stat a tick. Creating, renaming in or
479
+ # removing a script changes its mtime (a run doesn't: its output is
480
+ # under the state dir), and the page reads GET /api/pages again on the
481
+ # `pages` event. The first look only stores the stamp; a folder that
482
+ # appears or goes is a change.
483
+ def check_pages
484
+ return unless @pages_dir
485
+
486
+ stamp = dir_mtime(@pages_dir)
487
+ changed = !@pages_stamp.equal?(UNSEEN) && stamp != @pages_stamp
488
+ @pages_stamp = stamp
489
+ emit("pages", {}) if changed
490
+ end
491
+
447
492
  # The state dir's files: a new id is parsed and emitted, an id gone
448
493
  # from disk is dropped, a changed file is re-parsed. Skipped when the
449
494
  # dir's mtime says nothing was renamed in or unlinked since.
@@ -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