samagotchi 0.182.0 → 0.184.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 (197) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +22 -11
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +4 -2
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +14 -6
  12. data/docs/internals/bundles.md +26 -5
  13. data/docs/internals/engine.md +20 -9
  14. data/docs/internals/participants.md +1 -1
  15. data/docs/internals/prompt-caching.md +8 -1
  16. data/docs/internals/remote-sessions.md +40 -5
  17. data/docs/internals/web-frontend.md +96 -31
  18. data/docs/internals/web-push.md +11 -0
  19. data/docs/internals/working-set.md +239 -7
  20. data/docs/mcp-server.md +84 -0
  21. data/docs/memory.md +2 -1
  22. data/docs/plugins.md +309 -22
  23. data/docs/scheduling.md +14 -0
  24. data/docs/sessions.md +4 -4
  25. data/docs/sub-agent.md +9 -0
  26. data/docs/testing.md +3 -1
  27. data/docs/thin-clients.md +165 -0
  28. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  29. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  30. data/lib/samagotchi/bridge.rb +59 -68
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  33. data/lib/samagotchi/bundle_command/check.rb +55 -20
  34. data/lib/samagotchi/bundle_command.rb +50 -21
  35. data/lib/samagotchi/bundle_manifest.rb +105 -4
  36. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  37. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  38. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  39. data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
  40. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  41. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  42. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  43. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  44. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  45. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  46. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  47. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  48. data/lib/samagotchi/command_intake.rb +7 -0
  49. data/lib/samagotchi/commands/registry.rb +8 -3
  50. data/lib/samagotchi/continue_offer.rb +24 -15
  51. data/lib/samagotchi/engine/block_fix.rb +4 -4
  52. data/lib/samagotchi/engine/cards.rb +14 -5
  53. data/lib/samagotchi/engine/events.rb +10 -15
  54. data/lib/samagotchi/engine/models.rb +1 -1
  55. data/lib/samagotchi/engine/plugins.rb +3 -0
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/session.rb +14 -6
  58. data/lib/samagotchi/engine/side_requests.rb +1 -1
  59. data/lib/samagotchi/engine/sign_in.rb +142 -0
  60. data/lib/samagotchi/engine/turn_end.rb +3 -3
  61. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  62. data/lib/samagotchi/engine.rb +43 -27
  63. data/lib/samagotchi/engine_snapshots.rb +1 -1
  64. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  65. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  66. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  67. data/lib/samagotchi/hold_stop.rb +4 -4
  68. data/lib/samagotchi/idle_recap.rb +19 -11
  69. data/lib/samagotchi/idle_reminders.rb +7 -5
  70. data/lib/samagotchi/idle_scheduler.rb +7 -10
  71. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  72. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  73. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  74. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  75. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  76. data/lib/samagotchi/llm/http.rb +96 -5
  77. data/lib/samagotchi/mcp_command.rb +110 -0
  78. data/lib/samagotchi/mcp_server/http.rb +112 -0
  79. data/lib/samagotchi/mcp_server/protocol.rb +263 -0
  80. data/lib/samagotchi/mcp_server/stdio.rb +93 -0
  81. data/lib/samagotchi/mcp_server/text.rb +155 -0
  82. data/lib/samagotchi/mcp_server/tools.rb +246 -0
  83. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  84. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  85. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  86. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  87. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  88. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  89. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  90. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  91. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  92. data/lib/samagotchi/model_notes.rb +34 -12
  93. data/lib/samagotchi/plugin/api.rb +6 -1
  94. data/lib/samagotchi/plugin/card.rb +36 -11
  95. data/lib/samagotchi/plugin/context.rb +63 -6
  96. data/lib/samagotchi/plugin/http.rb +40 -15
  97. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  98. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  99. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  100. data/lib/samagotchi/plugin/loader.rb +18 -11
  101. data/lib/samagotchi/plugin/secrets.rb +266 -0
  102. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  103. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  104. data/lib/samagotchi/prompt_files.rb +11 -4
  105. data/lib/samagotchi/prompt_layout.rb +88 -0
  106. data/lib/samagotchi/prompt_part.rb +82 -20
  107. data/lib/samagotchi/queued_command.rb +28 -4
  108. data/lib/samagotchi/recap_setup.rb +13 -4
  109. data/lib/samagotchi/ref.rb +3 -2
  110. data/lib/samagotchi/relay_verifier.rb +8 -7
  111. data/lib/samagotchi/relay_watcher.rb +4 -4
  112. data/lib/samagotchi/reply_wait.rb +6 -3
  113. data/lib/samagotchi/run_options.rb +2 -1
  114. data/lib/samagotchi/schedule_command.rb +18 -4
  115. data/lib/samagotchi/schedules.rb +40 -8
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +285 -0
  118. data/lib/samagotchi/session_access/contract.rb +5 -0
  119. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  120. data/lib/samagotchi/session_access/exchange.rb +176 -0
  121. data/lib/samagotchi/session_access/local.rb +34 -6
  122. data/lib/samagotchi/session_access/remote.rb +4 -1
  123. data/lib/samagotchi/session_command_catalog.rb +10 -0
  124. data/lib/samagotchi/session_commands.rb +17 -0
  125. data/lib/samagotchi/session_config.rb +4 -4
  126. data/lib/samagotchi/session_inbox.rb +15 -0
  127. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  128. data/lib/samagotchi/session_observer.rb +27 -0
  129. data/lib/samagotchi/steer_cut.rb +4 -3
  130. data/lib/samagotchi/system_prompt.rb +196 -161
  131. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  132. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  133. data/lib/samagotchi/testing/boundary.rb +4 -0
  134. data/lib/samagotchi/testing/bundle.rb +48 -2
  135. data/lib/samagotchi/testing/fake_http.rb +60 -15
  136. data/lib/samagotchi/testing/host.rb +4 -1
  137. data/lib/samagotchi/testing/recorder.rb +45 -5
  138. data/lib/samagotchi/tools/memory.rb +11 -3
  139. data/lib/samagotchi/tools/tool_index.rb +14 -3
  140. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  141. data/lib/samagotchi/version.rb +1 -1
  142. data/lib/samagotchi/web/app.rb +9 -8
  143. data/lib/samagotchi/web/ask_routes.rb +362 -0
  144. data/lib/samagotchi/web/mcp_route.rb +91 -0
  145. data/lib/samagotchi/web/public/app.js +2 -3
  146. data/lib/samagotchi/web/public/block_frame.js +72 -11
  147. data/lib/samagotchi/web/public/block_host.js +44 -8
  148. data/lib/samagotchi/web/public/block_regions.js +126 -0
  149. data/lib/samagotchi/web/public/card.js +22 -9
  150. data/lib/samagotchi/web/public/card_actions.js +21 -0
  151. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  152. data/lib/samagotchi/web/public/card_registry.js +3 -2
  153. data/lib/samagotchi/web/public/data.js +15 -12
  154. data/lib/samagotchi/web/public/delete_sheet.js +231 -169
  155. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  156. data/lib/samagotchi/web/public/format.js +3 -0
  157. data/lib/samagotchi/web/public/index.html +52 -7
  158. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  159. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  160. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  161. data/lib/samagotchi/web/public/refs.js +5 -3
  162. data/lib/samagotchi/web/public/region_hit.js +144 -0
  163. data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
  164. data/lib/samagotchi/web/public/running_tasks.js +3 -17
  165. data/lib/samagotchi/web/public/session_actions.js +96 -100
  166. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  167. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  168. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  169. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  170. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  171. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  172. data/lib/samagotchi/web/push/notifier.rb +33 -6
  173. data/lib/samagotchi/web/server.rb +1 -1
  174. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  175. data/lib/samagotchi/web/session_control.rb +31 -9
  176. data/lib/samagotchi/web/session_create.rb +2 -2
  177. data/lib/samagotchi/web/session_hub.rb +26 -4
  178. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  179. data/lib/samagotchi/worker/child_side.rb +3 -2
  180. data/lib/samagotchi/worker/command_queue.rb +13 -13
  181. data/lib/samagotchi/worker/leave.rb +3 -3
  182. data/lib/samagotchi/worker/scratch.rb +6 -6
  183. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  184. data/lib/samagotchi/worker/startup.rb +3 -3
  185. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  186. data/lib/samagotchi/worker.rb +32 -21
  187. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  188. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  189. data/lib/samagotchi/worker_inbound.rb +12 -7
  190. data/lib/samagotchi/worker_link.rb +2 -2
  191. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  192. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  193. data/lib/samagotchi/working_set.rb +162 -90
  194. data/lib/samagotchi/working_set_locator.rb +221 -0
  195. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  196. data/lib/samagotchi/working_set_part.rb +281 -0
  197. metadata +36 -1
@@ -13,6 +13,7 @@
13
13
 
14
14
  import { html, render as litRender } from "./vendor/lit-html.js";
15
15
  import { createBlockFrame, FRAME_TIMEOUT_MS } from "./block_frame.js";
16
+ import { cleanRegions } from "./block_regions.js";
16
17
  import { DRAWN, figureOf, setSourceShown } from "./block_source.js";
17
18
  import { createBlockWatch, failBlock, holdingView } from "./block_watch.js";
18
19
  import { copyText } from "./copy.js";
@@ -155,6 +156,8 @@ export function createFrameDrawer({
155
156
  // render has its blocks wait for that one, and each draws into whichever is connected.
156
157
  const coming = new Map();
157
158
  const retries = new WeakMap();
159
+ // The languages whose regions were cleaned away whole once: said once each.
160
+ const regionsDropped = new Set();
158
161
  // What needsDraw checked, so draw draws that: pre => {lang, source, renderer}.
159
162
  const checked = new WeakMap();
160
163
  let list = null;
@@ -294,7 +297,12 @@ export function createFrameDrawer({
294
297
  async function rendered(key, lang, source, renderer, now) {
295
298
  const mark = markKey(lang, source);
296
299
  try {
297
- const svg = await frameFor(lang, renderer).render(source, now, { onStart: () => setMark(mark) });
300
+ const frame = frameFor(lang, renderer);
301
+ const onStart = () => setMark(mark);
302
+ // draw: {svg, regions}; an older cached block_frame.js has render alone.
303
+ const out = frame.draw ? await frame.draw(source, now, { onStart }) : { svg: await frame.render(source, now, { onStart }) };
304
+ const svg = out.svg;
305
+ const regions = keptRegions(lang, out.regions);
298
306
  const started = inFlight.get(mark);
299
307
  const picture = pictureOf(svg, win);
300
308
  const tooLarge = oversize(picture.width, picture.height);
@@ -305,7 +313,9 @@ export function createFrameDrawer({
305
313
  if (tooLargeShown) throw new Error(tooLargeShown);
306
314
  if (Date.now() - started > SLOW_RENDER_MS) inFlight.delete(mark);
307
315
  else clearMark(mark);
308
- const shown = picture.width ? picture : { ...picture, width: natural.width, height: natural.height };
316
+ const sized = picture.width ? picture : { ...picture, width: natural.width, height: natural.height };
317
+ // Only when there are some: a picture without regions has no such field.
318
+ const shown = regions ? { ...sized, regions } : sized;
309
319
  remember(key, shown);
310
320
  return shown;
311
321
  } catch (e) {
@@ -316,6 +326,19 @@ export function createFrameDrawer({
316
326
  }
317
327
  }
318
328
 
329
+ // The renderer's regions, cleaned (block_regions.js), or null; a list cleaned
330
+ // away whole is said once per language, with its count and no model text.
331
+ function keptRegions(lang, raw) {
332
+ if (raw == null) return null;
333
+ const regions = cleanRegions(raw);
334
+ if (regions?.length) return regions;
335
+ if (!regions && !regionsDropped.has(lang)) {
336
+ regionsDropped.add(lang);
337
+ console.warn(`chi: the ${lang} renderer's regions were dropped (${Array.isArray(raw) ? raw.length : typeof raw} reported, over the caps or not a list)`);
338
+ }
339
+ return null;
340
+ }
341
+
319
342
  // A claimed language has a renderer: the list is loaded by then.
320
343
  function needsDraw(pre, figure) {
321
344
  const lang = langOf(pre);
@@ -359,19 +382,32 @@ export function createFrameDrawer({
359
382
  else failBlock(pre, lang, "its renderer keeps stopping");
360
383
  }
361
384
 
385
+ // A figure's picture for the viewer: its <img>'s URL, size from the viewBox
386
+ // (showPicture's attributes) and alt, plus what else the cache holds for that
387
+ // URL (a data: URL reads back from img.src as it was set; a Revise clone has
388
+ // the same). An evicted entry, or a figure an older page drew: the picture alone.
389
+ // At most CACHE_SIZE compares, on a click only.
390
+ function pictureOfFigure(figure) {
391
+ const img = figure?.querySelector(".block-img");
392
+ if (!img) return null;
393
+ const size = (name) => Number(img.getAttribute(name)) || null;
394
+ const picture = { url: img.src, width: size("width"), height: size("height"), alt: img.alt };
395
+ const held = [...cache.values()].find((p) => p.url === picture.url);
396
+ for (const [key, value] of Object.entries(held || {})) if (!(key in picture)) picture[key] = value;
397
+ return picture;
398
+ }
399
+
362
400
  for (const root of roots) {
363
401
  root.addEventListener("mousedown", (e) => {
364
402
  if (e.target.closest?.(".block-zoom")) e.preventDefault();
365
403
  });
366
- // Delegated, so a Revise clone's work too: the picture in the viewer, at its
367
- // size from the viewBox (showPicture's attributes), the focus back on the button.
404
+ // Delegated, so a Revise clone's work too: the picture in the viewer, the
405
+ // focus back on the button.
368
406
  root.addEventListener("click", (e) => {
369
407
  if (!openPicture || !e.target.closest?.(".block-zoom, .block-img")) return;
370
408
  const figure = e.target.closest(`.${DRAWN}`);
371
- const img = figure?.querySelector(".block-img");
372
- if (!img) return;
373
- const size = (name) => Number(img.getAttribute(name)) || null;
374
- openPicture({ url: img.src, width: size("width"), height: size("height"), alt: img.alt }, { opener: figure.querySelector(":scope > .block-zoom") });
409
+ const picture = pictureOfFigure(figure);
410
+ if (picture) openPicture(picture, { opener: figure.querySelector(":scope > .block-zoom") });
375
411
  });
376
412
  }
377
413
 
@@ -0,0 +1,126 @@
1
+ // A drawn diagram's regions, cleaned: what a renderer reported beside its SVG
2
+ // (block_frame.js), made safe to keep. Pure: no DOM, `node --test`.
3
+ // docs/internals/block-renderers.md, Regions.
4
+ //
5
+ // A region: {kind, id, label, box?, points?, from?, to?}; boxes and points are
6
+ // fractions of the picture (0..1). The bundle is trusted, its input is
7
+ // model-written: so nothing here stringifies the raw data (structured clone keeps
8
+ // cycles and BigInt), only an own key of a known name is read, strings are only
9
+ // ever strings, and the result is new objects. Over the caps the list goes whole
10
+ // (null), never cut: a picture with half its nodes tappable lies.
11
+ //
12
+ // What the page may do with a region's text: textContent, an aria-label, and
13
+ // composer text. Never markup, a selector, a URL, a data-* value another module
14
+ // reads back, or a key into an object.
15
+ //
16
+ // A module of its own: its exports are new (docs/internals/web-frontend.md).
17
+
18
+ export const REGION_KINDS = new Set(["node", "group", "edge", "note"]);
19
+ export const MAX_REGIONS = 600;
20
+ // The budget over the cleaned fields: the kept strings' lengths, plus 12 per number.
21
+ export const MAX_REGION_BYTES = 128 * 1024;
22
+ const NUMBER_BYTES = 12;
23
+ const ID_CHARS = 80;
24
+ const LABEL_CHARS = 120;
25
+ const MIN_POINTS = 2;
26
+ const MAX_POINTS = 16;
27
+
28
+ const own = (obj, key) => (Object.hasOwn(obj, key) ? obj[key] : undefined);
29
+
30
+ function plainObject(v) {
31
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
32
+ const proto = Object.getPrototypeOf(v);
33
+ return proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null;
34
+ }
35
+
36
+ const clamp = (n) => Math.min(1, Math.max(0, n));
37
+ const finite = (n) => typeof n === "number" && Number.isFinite(n);
38
+
39
+ // One line of text, or "": controls and line separators a space, bidi and
40
+ // zero-width format characters and lone surrogates gone, whitespace runs one
41
+ // space, cut by code points (a cut never splits a pair: Ruby's JSON refuses a
42
+ // lone surrogate, and the text can reach a prompt). The raw string is sliced
43
+ // first, so a megabyte label costs what a short one does.
44
+ export function cleanText(raw, max) {
45
+ if (typeof raw !== "string") return "";
46
+ const text = raw.slice(0, max * 8)
47
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, " ")
48
+ .replace(/[\p{Cf}\p{Cs}]/gu, "")
49
+ .replace(/\s+/gu, " ")
50
+ .trim();
51
+ const points = Array.from(text);
52
+ return points.length > max ? points.slice(0, max).join("").trimEnd() : text;
53
+ }
54
+
55
+ // [x, y, w, h] clamped and cut to the picture, or null: no area, or not 4
56
+ // finite numbers.
57
+ function cleanBox(raw) {
58
+ if (!Array.isArray(raw) || raw.length !== 4 || !raw.every(finite)) return null;
59
+ const x = clamp(raw[0]);
60
+ const y = clamp(raw[1]);
61
+ const w = Math.min(clamp(raw[2]), 1 - x);
62
+ const h = Math.min(clamp(raw[3]), 1 - y);
63
+ return w > 0 && h > 0 ? [x, y, w, h] : null;
64
+ }
65
+
66
+ function cleanPoints(raw) {
67
+ if (!Array.isArray(raw) || raw.length < MIN_POINTS || raw.length > MAX_POINTS) return null;
68
+ const out = [];
69
+ for (const p of raw) {
70
+ if (!Array.isArray(p) || p.length !== 2 || !finite(p[0]) || !finite(p[1])) return null;
71
+ out.push([clamp(p[0]), clamp(p[1])]);
72
+ }
73
+ return out;
74
+ }
75
+
76
+ function cleanRegion(raw) {
77
+ if (!plainObject(raw)) return null;
78
+ const kind = own(raw, "kind");
79
+ if (typeof kind !== "string" || !REGION_KINDS.has(kind)) return null;
80
+ const region = { kind, id: cleanText(own(raw, "id"), ID_CHARS), label: cleanText(own(raw, "label"), LABEL_CHARS) };
81
+ const box = cleanBox(own(raw, "box"));
82
+ if (kind !== "edge") {
83
+ if (!box) return null;
84
+ region.box = box;
85
+ return region;
86
+ }
87
+ const points = cleanPoints(own(raw, "points"));
88
+ if (!points) return null;
89
+ region.points = points;
90
+ if (box) region.box = box;
91
+ region.from = cleanText(own(raw, "from"), ID_CHARS);
92
+ region.to = cleanText(own(raw, "to"), ID_CHARS);
93
+ return region;
94
+ }
95
+
96
+ // Something the card and a button can call it by, from the diagram's own text: a
97
+ // node, note or group its label or id, an edge its label or both its ends. A
98
+ // nameless one is skipped: the page never makes up a name ("node 3" means
99
+ // nothing in the source, nor to the model in composer text).
100
+ function namedRegion(r) {
101
+ return r.kind === "edge" ? !!(r.label || (r.from && r.to)) : !!(r.label || r.id);
102
+ }
103
+
104
+ function weight(region) {
105
+ const texts = region.id.length + region.label.length + (region.from?.length ?? 0) + (region.to?.length ?? 0);
106
+ const numbers = (region.box ? 4 : 0) + (region.points ? region.points.length * 2 : 0);
107
+ return texts + numbers * NUMBER_BYTES;
108
+ }
109
+
110
+ // @param raw what the frame's done carried (any value)
111
+ // @return a new array of clean regions, or null: none sent, not an array, over
112
+ // MAX_REGIONS entries or past MAX_REGION_BYTES; entries that aren't regions, or
113
+ // are nameless (namedRegion), are skipped
114
+ export function cleanRegions(raw) {
115
+ if (!Array.isArray(raw) || raw.length > MAX_REGIONS) return null;
116
+ const out = [];
117
+ let budget = MAX_REGION_BYTES;
118
+ for (let i = 0; i < raw.length; i++) {
119
+ const region = cleanRegion(raw[i]);
120
+ if (!region || !namedRegion(region)) continue;
121
+ budget -= weight(region);
122
+ if (budget < 0) return null;
123
+ out.push(region);
124
+ }
125
+ return out;
126
+ }
@@ -1,10 +1,12 @@
1
1
  // A plugin's card (docs/plugins.md, Cards): a title, a body and actions,
2
- // each action a command line the session runs. app.js places and updates
3
- // the element; this module draws it (lit-html templates) and says where it
4
- // goes.
2
+ // each action a command line the session runs or an address opened in a new
3
+ // tab (a url action, card_actions.js: it sends nothing to the session).
4
+ // app.js places and updates the element; this module draws it (lit-html
5
+ // templates) and says where it goes.
5
6
  import { html, nothing, render } from "./vendor/lit-html.js";
6
7
  import { unsafeHTML } from "./vendor/directives/unsafe-html.js";
7
8
  import { recapPlace } from "./format.js";
9
+ import { cardActions, cardActionUrl } from "./card_actions.js";
8
10
 
9
11
  // The card's class: a warn card wears the warning colour; a notice is a
10
12
  // one-line row.
@@ -22,7 +24,7 @@ export const NOTICE_CHARS = 160;
22
24
  // one that asks (actions) and one with more to read stay cards.
23
25
  export function isNoticeCard(card) {
24
26
  if (!card || card.level === "warn") return false;
25
- if ((card.actions || []).some((a) => a && a.command)) return false;
27
+ if (cardActions(card).length) return false;
26
28
  const body = String(card.body ?? "").trim();
27
29
  return !body.includes("\n") && body.length <= NOTICE_CHARS;
28
30
  }
@@ -69,17 +71,28 @@ export function cardBodyTemplate(card) {
69
71
 
70
72
  // The card: its head (title, the command that showed it after a reload,
71
73
  // source), body and one button per action (the command as its tooltip and
72
- // data), then the line a failed action writes.
74
+ // data; a url action an anchor to a new tab, its host as the tooltip, with
75
+ // a line under the row naming each host the url actions open, so a label
76
+ // can't hide where it leads), then the line a failed action writes. The
77
+ // anchor is .card-link, never .card-action: what selects .card-action posts
78
+ // the command or counts the card as asking.
73
79
  export function cardTemplate(card) {
74
80
  const source = card.source ? html`<span class="card-source">${card.source}</span>` : nothing;
75
81
  const label = card.label ? html`<span class="card-label">${card.label}</span>` : nothing;
76
82
  const body = cardBodyTemplate(card);
77
- const actions = (card.actions || []).filter((a) => a && a.command);
83
+ const actions = cardActions(card);
84
+ const hosts = [];
78
85
  const buttons = actions.length
79
- ? html`<div class="card-actions">${actions.map((a) =>
80
- html`<button type="button" class="card-action ghost" data-command=${a.command} title=${a.command}>${a.label || a.command}</button>`)}</div>`
86
+ ? html`<div class="card-actions">${actions.map((a) => {
87
+ if (a.command) return html`<button type="button" class="card-action ghost" data-command=${a.command} title=${a.command}>${a.label || a.command}</button>`;
88
+ const url = cardActionUrl(a);
89
+ const host = new URL(url).host;
90
+ if (!hosts.includes(host)) hosts.push(host);
91
+ return html`<a class="card-link ghost" href=${url} target="_blank" rel="noopener noreferrer" title=${host}>${a.label}</a>`;
92
+ })}</div>`
81
93
  : nothing;
82
- return html`<div class="card-head"><span class="card-title">${card.title || ""}</span>${label}${source}</div>${body ? html`<div class="card-body">${body}</div>` : nothing}${buttons}<div class="card-error hidden"></div>`;
94
+ const opens = hosts.length ? html`<div class="card-opens">opens ${hosts.join(", ")}</div>` : nothing;
95
+ return html`<div class="card-head"><span class="card-title">${card.title || ""}</span>${label}${source}</div>${body ? html`<div class="card-body">${body}</div>` : nothing}${buttons}${opens}<div class="card-error hidden"></div>`;
83
96
  }
84
97
 
85
98
  // A card element → the card it shows, as drawCard drew it.
@@ -0,0 +1,21 @@
1
+ // A card's actions as the page draws them (card.js): a command one, which
2
+ // the session runs, or a url one, an address opened in a new tab.
3
+ import { httpUrl } from "./refs.js";
4
+
5
+ // The longest address a card's url action opens: the server's
6
+ // Plugin::Card::MAX_URL (an authorize address can be long).
7
+ export const CARD_MAX_URL = 4096;
8
+
9
+ // A url action's address as the page opens it, else null: re-checked here,
10
+ // as a saved cards.json is seeded without the server's check and lit-html
11
+ // doesn't sanitize href. A url action needs its label (never the address).
12
+ export function cardActionUrl(action) {
13
+ if (!action || action.command || !String(action.label ?? "").trim()) return null;
14
+ return httpUrl(action.url, { max: CARD_MAX_URL });
15
+ }
16
+
17
+ // The card's actions the page draws: a command one, or a url one whose
18
+ // address passes cardActionUrl.
19
+ export function cardActions(card) {
20
+ return (card?.actions || []).filter((a) => a && (a.command || cardActionUrl(a)));
21
+ }
@@ -33,7 +33,7 @@ export function continueWait() {
33
33
  return { kind: "continue", approval: false, summary: "" };
34
34
  }
35
35
 
36
- // A plugin card's wait: a running turn's card with an action asks (as
36
+ // A plugin card's wait: a running turn's card with a command action asks (as
37
37
  // check-in's), a warning stays in sight; null: it doesn't wait. The one rule
38
38
  // cards_place.js upsertCard and turn_block.js drawnTurnNodes ask; the DOM
39
39
  // readers (stage_cards.js, stage_waiting.js waitingKind, card.js
@@ -45,8 +45,9 @@ export const CARD_EVENTS = [
45
45
  "continue_offered", "continue_resolved", "card",
46
46
  ];
47
47
 
48
- // A card's actions as the entry keeps them: label and command only.
49
- const actionsOf = (card) => (Array.isArray(card?.actions) ? card.actions.filter(Boolean).map((a) => ({ label: a.label ?? null, command: a.command ?? null })) : []);
48
+ // A card's actions as the entry keeps them: label and command, or label
49
+ // and url for a url action.
50
+ const actionsOf = (card) => (Array.isArray(card?.actions) ? card.actions.filter(Boolean).map((a) => (a.url && !a.command ? { label: a.label ?? null, url: a.url } : { label: a.label ?? null, command: a.command ?? null })) : []);
50
51
 
51
52
  export function createCardRegistry() {
52
53
  const entries = new Map();
@@ -271,10 +271,11 @@ export function restartSession(id, opts = {}) {
271
271
  // Hides the session (and its delegates) from the lists, kept for good; the
272
272
  // server stops a live idle worker first and answers 409 while a turn runs.
273
273
  // stopTasks: stop the background tasks it and its delegates started first
274
- // (without it, a session whose tasks still run is refused: 409 tasks_running).
274
+ // (without it, a session whose tasks still run is refused: 409 tasks_running);
275
+ // with +tasks+ (the ids the sheet named) only those, and a refusal on another.
275
276
  export function archiveSession(id, opts = {}) {
276
- const { stopTasks, ...apiOpts } = opts;
277
- const body = JSON.stringify(stopTasks ? { stop_tasks: true } : {});
277
+ const { stopTasks, tasks, ...apiOpts } = opts;
278
+ const body = JSON.stringify(stopTasks ? { stop_tasks: true, ...(Array.isArray(tasks) ? { tasks } : {}) } : {});
278
279
  return api(`/api/sessions/${encodeURIComponent(id)}/archive`, { method: "POST", body, ...apiOpts });
279
280
  }
280
281
 
@@ -285,30 +286,32 @@ export function unarchiveSession(id, opts = {}) {
285
286
 
286
287
  // A delete's query after force=true: the plan digest the user confirmed
287
288
  // (expect), and stop_tasks (stop the background tasks the deleted sessions
288
- // started first; without it, 409 tasks_running while one runs).
289
- function deleteQuery({ expect, stopTasks }) {
289
+ // started first; without it, 409 tasks_running while one runs); +tasks+ (the
290
+ // ids the sheet named, "tasks=" for none) has the stop take only those.
291
+ function deleteQuery({ expect, stopTasks, tasks }) {
290
292
  const plan = expect == null ? "" : `&expect=${encodeURIComponent(expect)}`;
291
- return `${plan}${stopTasks ? "&stop_tasks=true" : ""}`;
293
+ const named = stopTasks && Array.isArray(tasks) ? `&tasks=${tasks.map(encodeURIComponent).join(",")}` : "";
294
+ return `${plan}${stopTasks ? "&stop_tasks=true" : ""}${named}`;
292
295
  }
293
296
 
294
297
  // Deletes the session for good; force=true has the server stop a live
295
298
  // worker first (the page's confirm says so; without it, 409 worker_running).
296
299
  export function deleteSession(id, opts = {}) {
297
- const { expect, stopTasks, ...apiOpts } = opts;
298
- return api(`/api/sessions/${encodeURIComponent(id)}?force=true${deleteQuery({ expect, stopTasks })}`,
300
+ const { expect, stopTasks, tasks, ...apiOpts } = opts;
301
+ return api(`/api/sessions/${encodeURIComponent(id)}?force=true${deleteQuery({ expect, stopTasks, tasks })}`,
299
302
  { method: "DELETE", ...apiOpts });
300
303
  }
301
304
 
302
305
  // Deletes every link of the session's chain with their delegates (running
303
306
  // ones are left running); force: the links' workers are stopped first.
304
307
  export function deleteChain(id, opts = {}) {
305
- const { expect, stopTasks, ...apiOpts } = opts;
306
- return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true${deleteQuery({ expect, stopTasks })}`,
308
+ const { expect, stopTasks, tasks, ...apiOpts } = opts;
309
+ return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true${deleteQuery({ expect, stopTasks, tasks })}`,
307
310
  { method: "DELETE", ...apiOpts });
308
311
  }
309
312
 
310
- // What deleting a chained session would do, for the delete sheet
311
- // (delete_sheet.js): the server's own plan and refusals, read now.
313
+ // What deleting a session would do, for the delete sheet (delete_sheet.js):
314
+ // the server's own plan and refusals, read now.
312
315
  export function deletePlan(id, opts = {}) {
313
316
  return api(`/api/sessions/${encodeURIComponent(id)}/delete_plan`, opts);
314
317
  }