samagotchi 0.178.0 → 0.180.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -1
  3. data/docs/architecture.md +4 -2
  4. data/docs/bundles.md +48 -8
  5. data/docs/cli.md +3 -1
  6. data/docs/configuration.md +1 -1
  7. data/docs/context.md +32 -1
  8. data/docs/guardrails.md +2 -1
  9. data/docs/internals/attached-context.md +26 -4
  10. data/docs/internals/background-tasks.md +5 -1
  11. data/docs/internals/block-renderers.md +4 -3
  12. data/docs/internals/bridge.md +11 -2
  13. data/docs/internals/bundles.md +65 -34
  14. data/docs/internals/engine.md +1 -1
  15. data/docs/internals/web-frontend.md +81 -3
  16. data/docs/plugins.md +20 -5
  17. data/docs/releasing.md +3 -3
  18. data/docs/scheduling.md +4 -0
  19. data/docs/sessions.md +8 -2
  20. data/docs/testing.md +8 -1
  21. data/lib/samagotchi/block_renderers.rb +33 -16
  22. data/lib/samagotchi/bootstrap/bundles.rb +2 -2
  23. data/lib/samagotchi/bootstrap_command.rb +1 -1
  24. data/lib/samagotchi/bridge/card_wait.rb +34 -0
  25. data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
  26. data/lib/samagotchi/bundle_command/check.rb +10 -10
  27. data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
  28. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  29. data/lib/samagotchi/bundle_command.rb +22 -18
  30. data/lib/samagotchi/bundle_manifest.rb +579 -0
  31. data/lib/samagotchi/bundle_needs.rb +9 -8
  32. data/lib/samagotchi/bundle_settings_check.rb +13 -9
  33. data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
  34. data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
  35. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  41. data/lib/samagotchi/config.rb +2 -2
  42. data/lib/samagotchi/context_absorber.rb +36 -6
  43. data/lib/samagotchi/context_note.rb +8 -5
  44. data/lib/samagotchi/context_providers.rb +30 -29
  45. data/lib/samagotchi/context_sources.rb +42 -12
  46. data/lib/samagotchi/engine/messages.rb +1 -1
  47. data/lib/samagotchi/events.rb +6 -5
  48. data/lib/samagotchi/guardrail_wiring.rb +20 -21
  49. data/lib/samagotchi/guardrails/approval.rb +3 -2
  50. data/lib/samagotchi/guardrails/outside.rb +3 -3
  51. data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
  52. data/lib/samagotchi/installed_bundles/dir.rb +91 -0
  53. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
  54. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
  55. data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
  56. data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
  57. data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
  58. data/lib/samagotchi/installed_bundles/sha.rb +41 -0
  59. data/lib/samagotchi/installed_bundles/standing.rb +65 -0
  60. data/lib/samagotchi/installed_bundles.rb +105 -0
  61. data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
  62. data/lib/samagotchi/memory_bundle/builder.rb +13 -13
  63. data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
  64. data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
  65. data/lib/samagotchi/memory_bundle/installer.rb +33 -33
  66. data/lib/samagotchi/memory_bundle/listing.rb +5 -5
  67. data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
  68. data/lib/samagotchi/memory_bundle/merger.rb +15 -15
  69. data/lib/samagotchi/memory_bundle/profile.rb +8 -8
  70. data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
  71. data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
  72. data/lib/samagotchi/memory_bundle/shas.rb +2 -2
  73. data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
  74. data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
  75. data/lib/samagotchi/memory_bundle/status.rb +19 -16
  76. data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
  77. data/lib/samagotchi/memory_bundle/trash.rb +2 -2
  78. data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
  79. data/lib/samagotchi/memory_bundle.rb +2 -2
  80. data/lib/samagotchi/memory_command.rb +4 -4
  81. data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
  82. data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
  83. data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
  84. data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
  85. data/lib/samagotchi/memory_usage.rb +5 -5
  86. data/lib/samagotchi/muted_memories.rb +1 -1
  87. data/lib/samagotchi/peer_exchanges.rb +76 -0
  88. data/lib/samagotchi/plugin/context.rb +4 -0
  89. data/lib/samagotchi/plugin/loader.rb +35 -33
  90. data/lib/samagotchi/plugin/peer.rb +42 -11
  91. data/lib/samagotchi/project_subfolders.rb +9 -9
  92. data/lib/samagotchi/reply_wait/target.rb +11 -4
  93. data/lib/samagotchi/self_report.rb +14 -14
  94. data/lib/samagotchi/session_access/local.rb +16 -1
  95. data/lib/samagotchi/session_access/remote.rb +2 -1
  96. data/lib/samagotchi/session_config.rb +29 -19
  97. data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
  98. data/lib/samagotchi/session_retention.rb +13 -4
  99. data/lib/samagotchi/session_stores.rb +3 -0
  100. data/lib/samagotchi/system_prompt.rb +4 -4
  101. data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
  102. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  103. data/lib/samagotchi/terminal_ui/formatting.rb +15 -5
  104. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  105. data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
  106. data/lib/samagotchi/terminal_ui.rb +4 -1
  107. data/lib/samagotchi/testing/bundle.rb +3 -3
  108. data/lib/samagotchi/testing/install.rb +3 -3
  109. data/lib/samagotchi/testing/sandbox.rb +2 -2
  110. data/lib/samagotchi/tool_runner.rb +14 -14
  111. data/lib/samagotchi/tools/memory.rb +22 -22
  112. data/lib/samagotchi/tools/task_runtime.rb +12 -3
  113. data/lib/samagotchi/update_command.rb +4 -4
  114. data/lib/samagotchi/version.rb +1 -1
  115. data/lib/samagotchi/web/app.rb +14 -1
  116. data/lib/samagotchi/web/message_display.rb +6 -0
  117. data/lib/samagotchi/web/participant_view.rb +1 -1
  118. data/lib/samagotchi/web/proxy_gate.rb +1 -0
  119. data/lib/samagotchi/web/public/app.js +13 -1
  120. data/lib/samagotchi/web/public/card_kinds.js +8 -3
  121. data/lib/samagotchi/web/public/cards_place.js +15 -1
  122. data/lib/samagotchi/web/public/context_chips.js +184 -49
  123. data/lib/samagotchi/web/public/ctx.js +1 -1
  124. data/lib/samagotchi/web/public/history_shape.js +8 -3
  125. data/lib/samagotchi/web/public/index.html +66 -0
  126. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  127. data/lib/samagotchi/web/public/peer_data.js +119 -0
  128. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  129. data/lib/samagotchi/web/public/peer_links.js +161 -0
  130. data/lib/samagotchi/web/public/peer_note.js +49 -0
  131. data/lib/samagotchi/web/public/session_view.js +6 -1
  132. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  133. data/lib/samagotchi/web/public/turn_block.js +46 -8
  134. data/lib/samagotchi/web/public/turn_html.js +11 -2
  135. data/lib/samagotchi/web/public/turn_settle.js +117 -0
  136. data/lib/samagotchi/web/push/notifier.rb +2 -2
  137. data/lib/samagotchi/web/session_access_routes.rb +21 -1
  138. data/lib/samagotchi/web/session_hub.rb +20 -4
  139. data/lib/samagotchi/worker_boot.rb +4 -1
  140. metadata +24 -12
  141. data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
@@ -8,10 +8,11 @@
8
8
 
9
9
  import { html, nothing, render } from "./vendor/lit-html.js";
10
10
  import { keepFocus } from "./keep_focus.js";
11
- import { popoverPlace } from "./chip_popover.js";
11
+ import { popoverPlace, SHEET_MAX, sheetPlace } from "./chip_popover.js";
12
12
  import { focusBack, modalDialog } from "./popover_modal.js";
13
13
  import { cantText } from "./format.js";
14
14
  import { createLatest } from "./latest.js";
15
+ import { peerChipModel, peerGroups, peerKey, peerPopoverTemplate, peerShown } from "./peer_chip.js";
15
16
 
16
17
  // "now", "3m", "2h", "4d" since an ISO time; "" for none.
17
18
  export function ageText(iso, now = Date.now()) {
@@ -45,12 +46,14 @@ export function chipModel(rows, now = Date.now()) {
45
46
  }
46
47
 
47
48
  // The chips (a lit-html template; attributes after a bound one are bound
48
- // too, so they keep their order). open: the chip whose popover is open (a
49
- // source's name).
49
+ // too, so they keep their order). open: the chip whose popover is open (its
50
+ // key: a source's name, or a peer chip's "peer:<name>", peer_chip.js). A
51
+ // peer chip (peerChipModel) is drawn as one: class "peer", its dot when it
52
+ // says answered.
50
53
  export function chipsTemplate(chips, { open = null } = {}) {
51
- return html`${chips.map((chip) => html`<button type="button" class=${`ctx-chip ${chip.state}${chip.name === open ? " open" : ""}`}
54
+ return html`${chips.map((chip) => html`<button type="button" class=${`ctx-chip${chip.peer ? " peer" : ""} ${chip.state}${chip.name === open ? " open" : ""}`}
52
55
  data-name=${chip.name} title=${chip.title} aria-haspopup=${"dialog"} aria-expanded=${chip.name === open ? "true" : "false"}>${
53
- chip.state === "unread" ? html`<span class="ctx-dot" aria-hidden="true"></span>` : nothing}${chip.label}</button>`)}`;
56
+ chip.state === "unread" || chip.dot ? html`<span class="ctx-dot" aria-hidden="true"></span>` : nothing}${chip.label}</button>`)}`;
54
57
  }
55
58
 
56
59
  // The popover's inside for one row (GET …/context's); +text+ the row's
@@ -87,35 +90,67 @@ export function popoverTemplate(row, { text = null, now = Date.now() } = {}) {
87
90
  // so focus stays. The
88
91
  // popover behaves as every popover does (popover_modal.js): a modal dialog, its chip's
89
92
  // aria-expanded, Esc closes it and focus goes back to the chip.
90
- export function createContextChips({ el, api, toast = () => {}, doc = document, win = window }) {
93
+ // A paired peer's two sources are one chip (peer_chip.js), drawn first:
94
+ // +peers+() the peers model (peer_data.js createPeers; null: none, the
95
+ // chips then read no exchanges), read again when a session's chips load or
96
+ // a peer appears among them, and the chips redrawn on its change
97
+ // (peersChanged); +peerActions+: {status(name): the status card's command
98
+ // line ("/claude") when the session has it, else null; run(line); drawn(id):
99
+ // whether that send's row is in the conversation; jump(id): to it}.
100
+ // +focusAway+(): where focus goes when a detach or Unpair took the last chip
101
+ // (the composer).
102
+ export function createContextChips({ el, api, toast = () => {}, peers = () => null, peerActions = {},
103
+ focusAway = () => doc.getElementById("prompt")?.focus?.({ preventScroll: true }),
104
+ doc = document, win = window }) {
91
105
  let sessionId = null;
92
106
  let rows = [];
93
- let openName = null;
107
+ // The chip whose popover is open: its key (a source's name, or "peer:<name>").
108
+ let openKey = null;
94
109
  // Only the newest list read for the open session is drawn (latest.js).
95
110
  const latest = createLatest(() => sessionId);
96
- // The open row's text once read (view text).
111
+ // The open popover's text once read (view text; a peer's: its outbox's).
97
112
  let text = null;
113
+ // The peers the last read named (a new one reads the peers model again).
114
+ let peerNames = "";
98
115
  const pop = doc.createElement("div");
99
116
  pop.id = "contextPopover";
100
117
  pop.className = "ctx-popover";
101
118
  pop.hidden = true;
102
119
  doc.body.appendChild(pop);
103
- modalDialog(pop, { isOpen: () => openName !== null, doc });
120
+ modalDialog(pop, { isOpen: () => openKey !== null, doc });
121
+
122
+ const groups = () => peerGroups(rows).peers.filter(peerShown);
123
+ const groupOf = (key) => groups().find((group) => group.key === key) || null;
124
+ const exchangesOf = (name) => peers()?.peer?.(name)?.exchanges || [];
125
+ const rowOf = (name) => rows.find((r) => r.name === name) || null;
126
+
127
+ function chips(now = Date.now()) {
128
+ const peerChips = groups().map((group) => peerChipModel(group, exchangesOf(group.name), now));
129
+ return [...peerChips, ...chipModel(peerGroups(rows).rest, now)];
130
+ }
104
131
 
105
132
  function drawChips() {
106
- const chips = chipModel(rows);
133
+ const drawn = chips();
107
134
  // A source inserted before the focused chip: the focus stays on its source.
108
- keepFocus(el, "data-name", () => render(chipsTemplate(chips, { open: openName }), el));
109
- el.hidden = chips.length === 0;
135
+ keepFocus(el, "data-name", () => render(chipsTemplate(drawn, { open: openKey }), el));
136
+ el.hidden = drawn.length === 0;
110
137
  }
111
138
 
112
- // The chips, and the open popover closed when what it is for has gone.
139
+ // The chips, and the open popover closed when its chip isn't drawn any more.
113
140
  function draw() {
114
- if (openName && !chipModel(rows).some((chip) => chip.name === openName)) close();
141
+ if (openKey && !chips().some((chip) => chip.name === openKey)) close();
115
142
  else drawChips();
116
143
  }
117
144
 
118
- async function refresh() {
145
+ // The open popover drawn again from what is known (not while it shows a text).
146
+ function follow() {
147
+ if (openKey === null || text !== null) return;
148
+ const group = groupOf(openKey);
149
+ const row = group ? null : rowOf(openKey);
150
+ if (group || row) fill(group, row);
151
+ }
152
+
153
+ async function refresh({ loading = false } = {}) {
119
154
  const id = sessionId;
120
155
  if (!id) return;
121
156
  const fresh = latest.begin();
@@ -130,34 +165,57 @@ export function createContextChips({ el, api, toast = () => {}, doc = document,
130
165
  }
131
166
  draw();
132
167
  // An open popover follows its row, but not while it shows the text.
133
- if (openName && text === null) {
134
- const row = rows.find((r) => r.name === openName);
135
- if (row) fill(row);
136
- }
168
+ follow();
169
+ // The peers' exchanges for the chips: at a session's open (the
170
+ // conversation's own read may have found no peer yet), and when a peer
171
+ // comes (a pairing while the session is open).
172
+ const names = groups().map((group) => group.name).join(" ");
173
+ if (names && (loading || names !== peerNames)) peers()?.refresh?.();
174
+ peerNames = names;
137
175
  }
138
176
 
139
177
  function load(id) {
140
178
  sessionId = id;
141
179
  rows = [];
180
+ peerNames = "";
142
181
  close();
143
- return refresh();
182
+ return refresh({ loading: true });
144
183
  }
145
184
 
146
185
  function clear() {
147
186
  sessionId = null;
148
187
  rows = [];
188
+ peerNames = "";
149
189
  close();
150
190
  }
151
191
 
152
- function fill(row) {
153
- render(popoverTemplate(row, { text }), pop);
192
+ function fill(group, row) {
193
+ if (group) {
194
+ const actions = peerActions;
195
+ render(peerPopoverTemplate(group, exchangesOf(group.name), {
196
+ text, status: actions.status?.(group.name) || null, drawn: (id) => !!actions.drawn?.(id),
197
+ }), pop);
198
+ } else render(popoverTemplate(row, { text }), pop);
154
199
  }
155
200
 
156
201
  // At the chip as the session bar's chips place theirs (popoverPlace):
157
202
  // above it, or below when the room above is short; capped to the room
158
- // (it scrolls), inside the window with a 16px gutter.
203
+ // (it scrolls), inside the window with a 16px gutter. A peer's popover in
204
+ // a phone's window is a bottom sheet (sheetPlace), as scene 2 has it.
159
205
  function place(chip) {
160
- const width = Math.min(380, win.innerWidth - 32);
206
+ const sheet = !!groupOf(openKey) && win.innerWidth < SHEET_MAX;
207
+ pop.classList.toggle("sheet", sheet);
208
+ if (sheet) {
209
+ const at = sheetPlace({ innerWidth: win.innerWidth, innerHeight: win.innerHeight });
210
+ pop.style.width = `${at.width}px`;
211
+ pop.style.left = `${at.left}px`;
212
+ pop.style.top = "";
213
+ pop.style.bottom = `calc(${at.bottom}px + var(--safe-b, 0px))`;
214
+ pop.style.maxHeight = `${at.maxHeight}px`;
215
+ return;
216
+ }
217
+ // A peer's is wider: its actions on one line (scene 2).
218
+ const width = Math.min(groupOf(openKey) ? 440 : 380, win.innerWidth - 32);
161
219
  pop.style.width = `${width}px`;
162
220
  pop.style.maxHeight = "";
163
221
  const at = popoverPlace(chip.getBoundingClientRect(), { width, height: pop.offsetHeight,
@@ -169,19 +227,21 @@ export function createContextChips({ el, api, toast = () => {}, doc = document,
169
227
  }
170
228
 
171
229
  function placeAtOpenChip() {
172
- const chip = openName && el.querySelector(".ctx-chip.open");
230
+ const chip = openKey && el.querySelector(".ctx-chip.open");
173
231
  if (chip) place(chip);
174
232
  }
175
233
 
176
- function open(name, chip) {
177
- const row = rows.find((r) => r.name === name);
178
- if (!row) return;
234
+ function open(key, chip) {
235
+ const group = groupOf(key);
236
+ const row = group ? null : rowOf(key);
237
+ if (!group && !row) return;
179
238
  // Another popover's nodes go, so this one starts fresh.
180
239
  render(nothing, pop);
181
- openName = name;
240
+ openKey = key;
182
241
  text = null;
183
- pop.setAttribute("aria-label", name);
184
- fill(row);
242
+ pop.setAttribute("aria-label", group ? group.label : key);
243
+ pop.classList.toggle("peer-pop", !!group);
244
+ fill(group, row);
185
245
  pop.hidden = false;
186
246
  place(chip);
187
247
  drawChips();
@@ -190,25 +250,29 @@ export function createContextChips({ el, api, toast = () => {}, doc = document,
190
250
  // Focus that was in it (or +refocus+: Esc) goes back to its chip.
191
251
  function close({ refocus = false } = {}) {
192
252
  const back = focusBack(pop, { refocus, doc });
193
- const name = openName;
194
- openName = null;
253
+ const key = openKey;
254
+ openKey = null;
195
255
  text = null;
196
256
  pop.hidden = true;
257
+ pop.classList.remove("sheet", "peer-pop");
197
258
  render(nothing, pop);
198
259
  drawChips();
199
- if (name !== null) back([...el.querySelectorAll(".ctx-chip[data-name]")].find((chip) => chip.dataset.name === name));
260
+ if (key !== null) back([...el.querySelectorAll(".ctx-chip[data-name]")].find((chip) => chip.dataset.name === key));
200
261
  }
201
262
 
202
263
  async function viewText() {
203
- const name = openName;
204
- if (!name) return;
264
+ const key = openKey;
265
+ if (!key) return;
266
+ // A peer's text is its outbox's: the latest answer.
267
+ const name = groupOf(key)?.outbox?.name || key;
205
268
  try {
206
269
  const data = await api.show(sessionId, name);
207
- if (name !== openName) return;
208
- const row = rows.find((r) => r.name === name);
209
- if (!row) return;
270
+ if (key !== openKey) return;
271
+ const group = groupOf(key);
272
+ const row = group ? null : rowOf(key);
273
+ if (!group && !row) return;
210
274
  text = data.text || "";
211
- fill(row);
275
+ fill(group, row);
212
276
  // The text makes it taller: placed again.
213
277
  placeAtOpenChip();
214
278
  } catch (e) {
@@ -216,7 +280,7 @@ export function createContextChips({ el, api, toast = () => {}, doc = document,
216
280
  }
217
281
  }
218
282
  async function detach() {
219
- const row = rows.find((r) => r.name === openName);
283
+ const row = rowOf(openKey);
220
284
  if (!row) return;
221
285
  const ask = row.scope === "project"
222
286
  ? `Mute ${row.name} for this session? It is the project's: other sessions keep it.`
@@ -226,35 +290,106 @@ export function createContextChips({ el, api, toast = () => {}, doc = document,
226
290
  await api.detach(sessionId, row.name);
227
291
  close();
228
292
  await refresh();
293
+ focusAfterRemoval();
229
294
  } catch (e) {
230
295
  toast(cantText(`detach ${row.name}`, e));
231
296
  }
232
297
  }
233
298
 
299
+ // Unpair: one confirm, then both legs detached, the outbox first; a leg
300
+ // that fails is named and stops it (the inbox stays: the chip doesn't turn
301
+ // into "answers only" over a half unpair).
302
+ async function unpair() {
303
+ const group = groupOf(openKey);
304
+ if (!group) return;
305
+ const legs = [group.outbox, group.inbox].filter(Boolean).map((leg) => leg.name);
306
+ if (!win.confirm(`Unpair ${group.label}? This detaches ${legs.join(" and ")} from this session.`)) return;
307
+ const id = sessionId;
308
+ close();
309
+ for (const name of legs) {
310
+ try {
311
+ await api.detach(id, name);
312
+ } catch (e) {
313
+ toast(cantText(`detach ${name}`, e));
314
+ break;
315
+ }
316
+ }
317
+ await refresh();
318
+ focusAfterRemoval();
319
+ }
320
+
321
+ // A chip the focus was given back to went with its source: the focus goes
322
+ // to the strip's first chip, else to +focusAway+ (the composer).
323
+ function focusAfterRemoval() {
324
+ const at = doc.activeElement;
325
+ if (at && at !== doc.body && at.isConnected) return;
326
+ const chip = el.querySelector(".ctx-chip");
327
+ if (chip) chip.focus();
328
+ else focusAway();
329
+ }
330
+
331
+ function act(name, target) {
332
+ const group = groupOf(openKey);
333
+ if (name === "close") close();
334
+ else if (name === "view") viewText();
335
+ else if (name === "detach") detach();
336
+ else if (name === "unpair") unpair();
337
+ else if (name === "status" && group) {
338
+ const line = peerActions.status?.(group.name);
339
+ close();
340
+ if (line) peerActions.run?.(line);
341
+ } else if (name === "jump") {
342
+ const id = target.dataset.peerId;
343
+ close();
344
+ if (id) peerActions.jump?.(id);
345
+ }
346
+ }
347
+
234
348
  el.addEventListener("click", (e) => {
235
349
  const chip = e.target.closest(".ctx-chip");
236
350
  if (!chip) return;
237
351
  // On to the document: a session-bar chip's popover closes (the close
238
352
  // below leaves clicks in +el+ alone).
239
- if (openName === chip.dataset.name) close();
353
+ if (openKey === chip.dataset.name) close();
240
354
  else open(chip.dataset.name, chip);
241
355
  });
242
356
  pop.addEventListener("click", (e) => {
243
- const act = e.target.closest("[data-act]")?.dataset.act;
244
- if (act === "close") close();
245
- else if (act === "view") viewText();
246
- else if (act === "detach") detach();
357
+ const target = e.target.closest("[data-act]");
358
+ if (target) act(target.dataset.act, target);
247
359
  });
248
360
  doc.addEventListener("click", (e) => {
249
- if (openName && !pop.contains(e.target) && !el.contains(e.target)) close();
361
+ if (openKey && !pop.contains(e.target) && !el.contains(e.target)) close();
250
362
  });
251
363
  doc.addEventListener("keydown", (e) => {
252
- if (e.key === "Escape" && openName) close({ refocus: true });
364
+ if (e.key === "Escape" && openKey) close({ refocus: true });
253
365
  });
254
366
  win.addEventListener("resize", placeAtOpenChip);
255
367
  win.addEventListener("focus", () => refresh());
256
368
  // The ages move on by themselves.
257
369
  win.setInterval(() => { if (rows.length) drawChips(); }, 60_000);
258
370
 
259
- return { load, clear, refresh, close, get rows() { return rows; } };
371
+ // +name+'s popover on its text (a peer answer's "Read the full answer",
372
+ // peer_links.js), at its chip: a peer's leg opens its peer's chip. In a
373
+ // task of its own: the click that asks would close it on its way to the
374
+ // document.
375
+ function showText(name) {
376
+ setTimeout(() => {
377
+ const leg = rowOf(name);
378
+ const key = leg?.peer && groupOf(peerKey(leg.peer)) ? peerKey(leg.peer) : name;
379
+ const chip = [...el.querySelectorAll(".ctx-chip[data-name]")].find((c) => c.dataset.name === key);
380
+ if (!chip) return;
381
+ chip.scrollIntoView?.({ block: "nearest", inline: "nearest" });
382
+ if (openKey !== key) open(key, chip);
383
+ if (openKey === key && text === null) viewText();
384
+ }, 0);
385
+ }
386
+
387
+ // The peers model read again: the chips and an open peer's popover follow it.
388
+ function peersChanged() {
389
+ if (!sessionId) return;
390
+ drawChips();
391
+ if (groupOf(openKey)) follow();
392
+ }
393
+
394
+ return { load, clear, refresh, close, showText, peersChanged, get rows() { return rows; } };
260
395
  }
@@ -90,7 +90,7 @@ function count(n) {
90
90
  }
91
91
 
92
92
  // A token count as the size readouts word it: "450", "2.0k". As
93
- // MemoryBundle::IndexSize.count_text.
93
+ // MemoryIndex::Size.count_text.
94
94
  function countK(n) {
95
95
  return n >= 1000 ? `${(Math.round(n / 100) / 10).toFixed(1)}k` : String(Math.round(n));
96
96
  }
@@ -55,12 +55,14 @@ function sameBut(a, b, key) {
55
55
  return JSON.stringify(strip(a)) === JSON.stringify(strip(b));
56
56
  }
57
57
 
58
- // What a reader reads of +el+: its text, without the copy button and the
59
- // time dividers, whitespace collapsed.
58
+ // What a reader reads of +el+: its text, without the copy button, the
59
+ // time dividers and a peer answer's late slots (peer_links.js fills them
60
+ // from GET …/peers, which an offscreen reload doesn't read), whitespace
61
+ // collapsed.
60
62
  function textOf(el) {
61
63
  if (!el) return "";
62
64
  const copy = el.cloneNode(true);
63
- copy.querySelectorAll(".copy-btn, .time-gap").forEach((node) => node.remove());
65
+ copy.querySelectorAll(".copy-btn, .time-gap, [data-peer-slot]").forEach((node) => node.remove());
64
66
  return copy.textContent.replace(/\s+/g, " ").trim();
65
67
  }
66
68
 
@@ -148,6 +150,9 @@ function childItems(el) {
148
150
  if (el.matches(".turn-timing")) return [item("timing", textOf(el))];
149
151
  if (el.matches(".bubble.cancel")) return [item(el.classList.contains("stopped") ? "cancel" : "failed", textOf(el))];
150
152
  if (el.matches(".bubble.question")) return [questionItem(el)];
153
+ // A drawn turn's question before its card came (turn_block.js
154
+ // questionSlot): a question (reload_check.js drops them with the cards).
155
+ if (el.matches("[data-question-slot]")) return [item("question")];
151
156
  if (el.matches(".plugin-card")) return [cardItem(el)];
152
157
  if (el.matches(".steer-row")) return [item("steer", textOf(el.querySelector("summary")))];
153
158
  return [otherItem(el)];
@@ -508,6 +508,44 @@ button.system-one-wrong,.system-one-wrong.marked{flex:none;padding:1px 6px;borde
508
508
  .bubble.note{border-left:3px dotted var(--text-faint);background:transparent;font-size:12px;color:var(--text-muted);opacity:.85}
509
509
  .note-line{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--text-faint);margin-bottom:2px}
510
510
  .note-text{white-space:pre-wrap;max-height:8em;overflow:auto}
511
+ /* A peer's answer (peer_note.js): a bubble from the peer, not a dotted system note; its verdict pill, the ↑ to its
512
+ send, "Read the full answer" (the newest answer only) and chi's instruction folded under "what chi told the agent".
513
+ A send's state (peer_exchange.js pillTemplate) is a pill in the chip's shape after the row's params. */
514
+ .bubble.note.peer-answer{border:1px solid var(--border-strong);border-radius:10px;background:var(--bg-panel);opacity:1;font-size:13px;color:var(--text);white-space:normal;display:flex;flex-direction:column;gap:8px}
515
+ .bubble.note.peer-answer .note-text{max-height:none;overflow:visible;line-height:1.5}
516
+ .peer-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 8px}
517
+ .peer-who{font-weight:700;color:var(--text-bright)}
518
+ .peer-mark{margin-left:auto;display:inline-flex;align-items:baseline;gap:8px}
519
+ .peer-closed{font-size:12px;color:var(--ok-text)}
520
+ :is(.peer-state,.peer-verdict){display:inline-block;padding:2px 9px;border-radius:999px;font:600 11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:nowrap;border:1px solid var(--border-strong);color:var(--text-3);background:transparent}
521
+ :is(.peer-state,.peer-verdict).changes{color:var(--warn-text);background:var(--warn-bg);border-color:var(--warn-border)}
522
+ :is(.peer-state,.peer-verdict).ok{color:var(--ok-text);background:var(--ok-bg);border-color:color-mix(in srgb,var(--ok) 45%,transparent)}
523
+ .peer-state.waiting{color:var(--accent);background:var(--accent-bg);border-color:var(--accent-border)}
524
+ .peer-state.failed{color:var(--danger-text);background:var(--danger-bg-dim);border-color:color-mix(in srgb,var(--danger) 45%,transparent)}
525
+ .peer-slot{margin-left:auto;display:inline-flex}
526
+ .peer-slot:empty{display:none}
527
+ button.peer-state{cursor:pointer}
528
+ @media(hover:hover){button.peer-state:hover{filter:brightness(1.15)}}
529
+ .peer-short{display:none}
530
+ :is(button.peer-up,button.peer-full){padding:0;border:0;background:none;color:var(--accent);font:inherit;font-size:12px;text-align:left;cursor:pointer}
531
+ @media(hover:hover){:is(button.peer-up,button.peer-full):hover{color:var(--text-hover);text-decoration:underline}}
532
+ .peer-foot{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px 14px;font-size:12px}
533
+ .peer-told>summary{cursor:pointer;color:var(--text-3);list-style:none;width:max-content}
534
+ .peer-told>summary::-webkit-details-marker{display:none}
535
+ .peer-told>summary::before{content:"\25B8 "}
536
+ .peer-told[open]{flex-basis:100%}
537
+ .peer-told[open]>summary::before{content:"\25BE "}
538
+ .peer-told-text{margin-top:6px;white-space:pre-wrap;color:var(--text-muted);max-height:16em;overflow:auto}
539
+ @media(max-width:600px){
540
+ .peer-short{display:inline}
541
+ :is(.peer-state,.peer-verdict) .peer-long:has(+.peer-short),.peer-verdict .peer-long{display:none}
542
+ .activity-row .peer-slot{order:1;flex:1 1 100%;margin:2px 0 0 var(--row-gutter)}
543
+ .activity-row:has(>.peer-slot:not(:empty))>.activity-duration{display:none}
544
+ .activity-row button.peer-state{min-height:44px;padding:10px 12px;font-size:12px;box-sizing:border-box}
545
+ .peer-head .peer-up-slot{flex:1 1 100%;order:3}
546
+ button.peer-up{padding:6px 0;min-height:32px}
547
+ button.peer-full{padding:12px 0}
548
+ }
511
549
  .bubble.command.busy{border-left-color:var(--warn)}
512
550
  .bubble.command.failed{border-left-color:var(--danger)}
513
551
  .bubble.command.queued{border-left-style:dashed}
@@ -1371,6 +1409,34 @@ body.has-session.composer-folded #infoBar{border-top-color:transparent}
1371
1409
  #infoBar .ctx-chip.empty{color:var(--text-faint);border-style:dashed}
1372
1410
  #infoBar .ctx-chip.error{color:var(--danger-text);border-color:color-mix(in srgb,var(--danger) 55%,transparent);background:var(--danger-bg-dim)}
1373
1411
  .ctx-dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 2px var(--accent-ring)}
1412
+ /* A paired peer's one chip (peer_chip.js): waiting in the accent, can't send in warn, answers only dashed. */
1413
+ #infoBar .ctx-chip.peer.waiting{color:var(--text);background:var(--accent-bg);border-color:var(--accent-border)}
1414
+ #infoBar .ctx-chip.peer.cant-send{color:var(--warn-text);background:var(--warn-bg);border-color:var(--warn-border)}
1415
+ #infoBar .ctx-chip.peer.answers-only{border-style:dashed}
1416
+ /* Its popover (scene 2): the two ways, the last exchanges, its actions; a bottom sheet on a phone. */
1417
+ .ctx-popover.peer-pop{gap:12px}
1418
+ .ctx-popover.peer-pop .ctx-pop-head strong{font-family:inherit;font-size:15px}
1419
+ .ctx-popover.peer-pop .ctx-pop-head .ctx-pop-kind{margin-left:auto;font-size:12px}
1420
+ .ctx-popover.peer-pop .ctx-pop-head .ctx-pop-close{margin-left:0}
1421
+ .ctx-popover.sheet{border-radius:14px}
1422
+ .peer-pop-legs{display:flex;flex-direction:column;gap:6px}
1423
+ .peer-pop-legs>div{display:flex;gap:8px}
1424
+ .peer-pop-legs>div>span:first-child{flex:0 0 78px;color:var(--text-muted)}
1425
+ .peer-pop-legs .warn{color:var(--warn-text)}
1426
+ .peer-pop-list{display:flex;flex-direction:column}
1427
+ .peer-pop-list-head{font-size:12px;font-weight:700;color:var(--text-muted);padding-bottom:4px}
1428
+ .peer-pop-x{display:flex;gap:10px;align-items:baseline;width:100%;box-sizing:border-box;padding:7px 0;margin:0;border:0;border-top:1px solid var(--border-strong);border-radius:0;background:transparent;color:inherit;font:inherit;text-align:left}
1429
+ button.peer-pop-x{cursor:pointer}@media(hover:hover){button.peer-pop-x:hover .pp-x-what{color:var(--text-hover);text-decoration:underline}}
1430
+ .pp-x-at{flex:none;font:11px ui-monospace,monospace;color:var(--text-muted)}
1431
+ .pp-x-what{flex:1;min-width:0;color:var(--text);overflow-wrap:anywhere}
1432
+ .pp-x-state{flex:none;color:var(--text-muted)}
1433
+ .pp-x-state.waiting{color:var(--accent)}
1434
+ .pp-x-state.changes{color:var(--warn-text)}
1435
+ .pp-x-state:is(.ok,.answered){color:var(--ok-text)}
1436
+ .pp-x-state.failed{color:var(--danger-text)}
1437
+ .ctx-popover.peer-pop .ctx-pop-actions{justify-content:flex-start;flex-wrap:wrap}
1438
+ .ctx-popover.peer-pop .ctx-pop-actions button{min-height:44px;padding:10px 12px;border-radius:8px}
1439
+ .ctx-popover.peer-pop .ctx-pop-actions .ctx-pop-detach{color:var(--danger-text)}
1374
1440
  .ctx-popover{position:fixed;z-index:60;max-height:min(60vh,520px);overflow:auto;padding:12px 14px;border-radius:12px;background:var(--bg-panel);color:var(--text-2);border:1px solid var(--border-strong);box-shadow:var(--toast-shadow);font-size:13px;line-height:1.45;display:flex;flex-direction:column;gap:6px}
1375
1441
  .ctx-popover[hidden]{display:none}
1376
1442
  /* The participants chip (info bar) and its panel (participants_panel.js). */
@@ -0,0 +1,171 @@
1
+ // A paired peer in the session bar: its two context sources (<name>-inbox,
2
+ // <name>-outbox) drawn as one chip that says how the pairing stands
3
+ // (paired, waiting, answered, can't send, answers only), and that chip's
4
+ // popover (how chi and the peer reach each other, the last exchanges, View
5
+ // latest answer, Status card, Unpair). Pure templates and models: the
6
+ // chips' controller (context_chips.js) draws them, the exchanges are the
7
+ // peers model's (peer_data.js, GET …/peers). docs/internals/web-frontend.md,
8
+ // The peer exchange. Its own module: new exports go in new modules.
9
+
10
+ import { html, nothing } from "./vendor/lit-html.js";
11
+ import { spanText, verdictWord } from "./peer_exchange.js";
12
+ import { wallClock } from "./format.js";
13
+
14
+ // A peer chip's key among the chips ("peer:claude"); an ordinary chip's is
15
+ // its source's name, which never holds a ":" (ContextSources' names).
16
+ export const peerKey = (name) => `peer:${name}`;
17
+
18
+ // How many exchanges the popover lists (the newest).
19
+ export const POPOVER_EXCHANGES = 8;
20
+
21
+ // GET …/context's rows split: the peer sources (a row with `peer` and its
22
+ // `leg`) grouped per peer, {key, name, label, inbox, outbox} (a leg's row
23
+ // or null; a muted leg stays in its group), in the order their first leg
24
+ // comes; and the rest, the ordinary rows, as they were.
25
+ export function peerGroups(rows) {
26
+ const peers = new Map();
27
+ const rest = [];
28
+ for (const row of rows || []) {
29
+ if (!row) continue;
30
+ if (!row.peer || !["inbox", "outbox"].includes(row.leg)) {
31
+ rest.push(row);
32
+ continue;
33
+ }
34
+ let group = peers.get(row.peer);
35
+ if (!group) {
36
+ group = { key: peerKey(row.peer), name: row.peer, label: row.label || row.peer, inbox: null, outbox: null };
37
+ peers.set(row.peer, group);
38
+ }
39
+ group[row.leg] = row;
40
+ }
41
+ return { peers: [...peers.values()], rest };
42
+ }
43
+
44
+ // A leg that counts: there and not muted.
45
+ const live = (leg) => (leg && !leg.muted ? leg : null);
46
+ // The group's legs as the chip reads them, and whether it shows at all
47
+ // (a group whose legs are all muted is gone from the bar, as a muted row is).
48
+ export const peerShown = (group) => !!(live(group.inbox) || live(group.outbox));
49
+
50
+ // The sends among +exchanges+ (newest first): an unclaimed answer has no id.
51
+ const sends = (exchanges) => (exchanges || []).filter((ex) => ex?.id);
52
+ const ASKS = ["validate", "question"];
53
+
54
+ // The newest send failed and the peer hasn't paired again since: pairing
55
+ // again (the pair script) pushes the inbox, which moves its row's
56
+ // fetched_at past the failed send's time.
57
+ export function cantSend(group, exchanges) {
58
+ const newest = sends(exchanges)[0];
59
+ if (newest?.state !== "failed") return false;
60
+ const paired = Date.parse(live(group.inbox)?.fetched_at || "");
61
+ const failed = Date.parse(newest.at || "");
62
+ return !(paired > failed);
63
+ }
64
+ const since = (iso, now) => {
65
+ const at = Date.parse(iso || "");
66
+ return Number.isNaN(at) ? null : now - at;
67
+ };
68
+
69
+ // The chip of +group+: the first state that applies.
70
+ // - answers-only: no inbox leg (a pairing through a remote: chi there can't send);
71
+ // - cant-send: the newest send failed (the transport refused it);
72
+ // - waiting: the newest validate or question send has no answer (its age the send's);
73
+ // - answered: the outbox has a text the agent hasn't read (its age the text's), with the dot;
74
+ // - paired otherwise.
75
+ // +exchanges+: the peer's from GET …/peers, newest first ([] when not read,
76
+ // an older chi web, a peer the read doesn't name: nothing then says failed).
77
+ // @return {key, name, state, label, title, dot}
78
+ export function peerChipModel(group, exchanges = [], now = Date.now()) {
79
+ const inbox = live(group.inbox);
80
+ const outbox = live(group.outbox);
81
+ const all = sends(exchanges);
82
+ const ask = all.find((ex) => ASKS.includes(ex.kind));
83
+ let state = "paired";
84
+ let words = "paired";
85
+ let why = "paired: chi can send to it and it answers into its outbox";
86
+ if (!inbox) {
87
+ state = "answers-only";
88
+ words = "answers only";
89
+ why = "paired through a remote: it answers, chi here can't send to it";
90
+ } else if (cantSend(group, exchanges)) {
91
+ state = "cant-send";
92
+ words = "can't send";
93
+ why = `the last send didn't go through: pair again from ${group.label}`;
94
+ } else if (ask?.state === "waiting") {
95
+ const age = since(ask.at, now);
96
+ state = "waiting";
97
+ words = age === null ? "waiting" : `waiting ${spanText(age)}`;
98
+ why = [ask.kind, ask.title].filter(Boolean).join(" · ") || "a send";
99
+ why = `waiting for its answer to ${why}`;
100
+ } else if (outbox?.unread && outbox.has_text) {
101
+ const age = since(outbox.fetched_at, now);
102
+ state = "answered";
103
+ words = age === null ? "answered" : `answered ${spanText(age)}`;
104
+ why = "an answer the agent hasn't read yet";
105
+ }
106
+ return { key: group.key, name: group.key, state, label: `${group.label} · ${words}`, title: why,
107
+ dot: state === "answered", peer: true };
108
+ }
109
+
110
+ // An exchange's state as the popover's list says it: "waiting 2m",
111
+ // "changes · 11m", "ok · 4m", "answered · 4m", "no answer expected",
112
+ // "not sent"; +kind+ its tint.
113
+ // @return {text, kind}
114
+ export function exchangeState(ex, now = Date.now()) {
115
+ if (ex.state === "failed") return { text: "not sent", kind: "failed" };
116
+ if (ex.state === "none_expected") return { text: "no answer expected", kind: "none" };
117
+ if (ex.state === "waiting") {
118
+ const age = since(ex.at, now);
119
+ return { text: age === null ? "waiting" : `waiting ${spanText(age)}`, kind: "waiting" };
120
+ }
121
+ const took = ex.answer?.at ? since(ex.at, Date.parse(ex.answer.at)) : null;
122
+ const verdict = verdictWord(ex.answer?.verdict);
123
+ const word = verdict || "answered";
124
+ return { text: took === null ? word : `${word} · ${spanText(took)}`, kind: verdict || "answered" };
125
+ }
126
+
127
+ // The popover's inside for +group+ (scene 2). +exchanges+ newest first;
128
+ // +text+ the outbox's text once View latest answer read it (null before);
129
+ // +status+ the status card's command ("/claude") when the session has it,
130
+ // else null; +drawn+(id) whether that send's row is in the conversation
131
+ // (its list row then jumps to it).
132
+ export function peerPopoverTemplate(group, exchanges = [], { text = null, status = null, drawn = () => false, now = Date.now() } = {}) {
133
+ const inbox = live(group.inbox);
134
+ const outbox = live(group.outbox);
135
+ const all = sends(exchanges);
136
+ const lastSent = all.find((ex) => ex.state !== "failed");
137
+ const sendsLine = !inbox
138
+ ? "can't: paired through a remote"
139
+ : cantSend(group, exchanges)
140
+ ? `the last send didn't go through: pair again from ${group.label}`
141
+ : [`to its inbox (${group.inbox.name})`, lastSent ? `last sent ${wallClock(lastSent.at, now)}` : ""].filter(Boolean).join(" · ");
142
+ const answersLine = outbox
143
+ ? [`into ${outbox.name}`, outbox.fetched_at ? `last ${wallClock(outbox.fetched_at, now)}` : "nothing yet"].join(" · ")
144
+ : "no outbox attached";
145
+ const list = all.slice(0, POPOVER_EXCHANGES);
146
+ const rowInside = (ex) => {
147
+ const state = exchangeState(ex, now);
148
+ return html`<span class="pp-x-at">${wallClock(ex.at, now)}</span><span class="pp-x-what">${
149
+ [ex.kind, ex.title].filter(Boolean).join(" · ") || "a send"}</span><span class=${`pp-x-state ${state.kind}`}>${state.text}</span>`;
150
+ };
151
+ const legs = [group.inbox, group.outbox].filter(Boolean);
152
+ return html`<div class="ctx-pop-head"><strong>${group.label}</strong
153
+ ><span class="ctx-pop-kind">paired peer</span
154
+ ><button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div
155
+ ><div class="peer-pop-legs"><div><span>chi sends</span><span class=${inbox && cantSend(group, exchanges) ? "warn" : ""}>${sendsLine}</span></div
156
+ ><div><span>it answers</span><span>${answersLine}</span></div></div
157
+ >${list.length ? html`<div class="peer-pop-list"><div class="peer-pop-list-head">Exchanges</div>${list.map((ex) => (drawn(ex.id)
158
+ ? html`<button type="button" class="peer-pop-x" data-act="jump" data-peer-id=${ex.id}>${rowInside(ex)}</button>`
159
+ : html`<div class="peer-pop-x">${rowInside(ex)}</div>`))}</div>` : nothing
160
+ }<pre class="ctx-pop-text" ?hidden=${text === null}>${text ?? ""}</pre
161
+ ><div class="ctx-pop-actions">${outbox?.has_text && text === null ? html`<button type="button" data-act="view">View latest answer</button>` : nothing
162
+ }${status ? html`<button type="button" data-act="status">Status card (${status})</button>` : nothing
163
+ }${legs.length ? html`<button type="button" class="ctx-pop-detach" data-act="unpair" title=${`Detach ${legs.map((l) => l.name).join(" and ")}`}>Unpair</button>` : nothing}</div>`;
164
+ }
165
+
166
+ // The peer's status card command ("/claude") when the session's commands
167
+ // (the session GET's `commands`) have it, else null.
168
+ export function peerStatusCommand(commands, name) {
169
+ const line = `/${name}`;
170
+ return (Array.isArray(commands) ? commands : []).some((c) => c?.name === line) ? line : null;
171
+ }