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
data/docs/guardrails.md CHANGED
@@ -252,7 +252,8 @@ the user's alone (`user_only`): `chi answer` and the worker refuse the allow
252
252
  with `only the user can allow it`. The same holds for the guardrails bundle's
253
253
  other user-only rules (`chi-context-cmd`, `chi-broadcast`,
254
254
  `prompt-memory-write`, `model-overlay-write`, and `chi-answer-piped` /
255
- `chi-answer-http`, which answer a grandchild's question as the user).
255
+ `chi-answer-http`, which answer a grandchild's question as the user), and core's
256
+ `bundle-secrets-shell` (a command naming a bundle's secrets).
256
257
 
257
258
  `child-boundary` isn't one of them: an ask before a delegate child acts outside
258
259
  its folder follows the level, so a `soft` parent may give Allow once. If that
@@ -341,6 +342,20 @@ with `writes: true` (symlinks resolved; see
341
342
  `execute` can still reach them; the guardrails bundle asks about shell
342
343
  commands that name them.
343
344
 
345
+ A bundle's secrets ([`ctx.secrets`](plugins.md#secrets-ctxsecrets):
346
+ `<state dir>/plugins/<bundle>/secrets/`) are kept from chi's model whatever
347
+ the call does, reads too:
348
+
349
+ - deny (`bundle-secrets`): `read`, `write`, `edit` and a plugin tool's
350
+ `targets:` paths there (symlinks resolved);
351
+ - ask, once, the user only (`bundle-secrets-shell`, a protected rule): an
352
+ `execute` or `task_create` command that names the folder
353
+ (`…/samagotchi/plugins/<bundle or a glob>/secrets`, or this state dir's
354
+ path spelled out), `ls` and `cat` included.
355
+
356
+ It is an accident guard, not a sandbox: a command that doesn't name the
357
+ folder (one that `cd`s there first, a variable, a script) still reads it.
358
+
344
359
  ## A delegate child's boundary
345
360
 
346
361
  Built in, for [delegate](sessions.md#delegating) children only, in every
@@ -19,7 +19,7 @@ model. The TUI is untouched: it shows a fence as source.
19
19
  `renderer_changed`, each with its own reason. ETag + `no-cache`, as static files. A `block_renderers:` list that
20
20
  doesn't parse is logged once per bundle and problem (each list request and file fetch reads it); a bundle this chi is
21
21
  too old for (`requires_chi`) draws nothing, logged once per bundle and version (`block_renderers_too_new`).
22
- 3. `block_watch.js` (`createBlockWatch`, made by `block_host.js`'s `createBlockHost`, wired in `app.js`; a participant's page
22
+ 3. `block_watch.js` (`createBlockWatch`, made by `block_host.js`'s `createBlockHost`, wired by `diagram_wiring.js wireDiagrams` from `app.js`; a participant's page
23
23
  gets the core drawers only, no bundle's renderers: `block_renderers`) finds and watches the blocks; `block_host.js` is its frame drawer (`createFrameDrawer`). The watcher asks an
24
24
  ordered list of drawers, core ones first (`inline_widgets.js` for `chi-ui`: [inline-widgets.md](inline-widgets.md)), then the frame drawer, which waits for `/api/block_renderers`;
25
25
  the first that `claims` the block's language draws it, and a language none claims is left alone. The contract
@@ -35,7 +35,14 @@ model. The TUI is untouched: it shows a fence as source.
35
35
  4. `block_frame.js` (`createBlockFrame`): one hidden frame per language, made on first need, one render at a time, 15 s per
36
36
  call, the renderer files' fetch included (browser `fetch` has no timeout; a fetch past it is a failed load). A timeout, a
37
37
  dead frame or a session switch drops it, and a drop rejects whatever is pending, the load too. Handshake `loaded` → `code {files}` → `ready | failed`,
38
- then `render {id, source, theme}` → `done {id, svg} | error {id, message}`.
38
+ then `render {id, source, theme}` → `done {id, svg, regions?} | error {id, message, bundle?}`. The bootstrap's
39
+ `window.chi` is `{ defineRenderer, features: { regions: true } }`: a renderer returns the SVG, or `{ svg, regions }`
40
+ ([Regions](#regions)). An object without a string `svg` is the bundle's bug, `error {bundle: true}`: its
41
+ `FrameError` isn't `renderer`, so the block fails with its line and no fix is asked; a renderer that throws, or
42
+ returns no object at all (`undefined`, `null`, a number), is as before: a failed render that may be the model's
43
+ (a renderer can return nothing for a source it can't draw), so `renderer` and fixable. Kept so on purpose: the
44
+ bundle flag is for what only a bundle returns (an object), and a bundle's measuring stays inside its own `try`.
45
+ `createBlockFrame`'s `draw` resolves `{svg, regions}` (`render`, its SVG alone, stays); `block_host.js` uses `render` when a cached older `block_frame.js` has no `draw`.
39
46
  5. On success a `<figure class="block-drawn">` goes right before the `<pre>`, which stays in the DOM, `hidden`, so whatever
40
47
  reads text (copy, a claim's walk, fold thresholds) sees what it did. **The DOM is the state** (`block_source.js`): a Revise
41
48
  clone arrives with both. On failure the `<pre>` stays, marked `data-block-failed`, with one muted line: an attribute CSS
@@ -48,7 +55,9 @@ model. The TUI is untouched: it shows a fence as source.
48
55
  movable there; without `openPicture` (an older app.js) a click does nothing. The same is a `.block-zoom` button
49
56
  ("Open in the viewer": icon, `aria-label`) for the keyboard: before the toggle, shown on keyboard focus only, and
50
57
  taking no pointer while hidden; Esc in the viewer gives it the focus back.
51
- 6. Cache: a `Map` on `lang + theme + source`, about 200 entries, holding the `data:` URL; a later `bubble.innerHTML` wipes the
58
+ 6. Cache: a `Map` on `lang + theme + source`, about 200 entries, holding the `data:` URL and, when the renderer reported
59
+ some, the cleaned regions (so a cache hit, a Revise clone and a theme's redraw carry their own; a click finds the
60
+ entry by the `<img>`'s `src`, `pictureOfFigure`, at most 200 compares: an evicted entry gives the picture alone); a later `bubble.innerHTML` wipes the
52
61
  figure and the observer redraws in the same pass. No `crypto.subtle`: it's undefined on a plain-http LAN address. A system
53
62
  theme change redraws through the figure (a hidden `<pre>` never intersects).
54
63
  7. The view: a viewer at the bottom stays there (`scroll.js keepFollowing`); a block drawn above a reader's view keeps
@@ -63,6 +72,51 @@ model. The TUI is untouched: it shows a fence as source.
63
72
  `max-height` says the same number, a backstop whatever the parsing gets wrong. The decode is bounded too
64
73
  (15 s, the mark on until it ends). A very wide picture stays at least 120 px tall and scrolls sideways instead of a sliver.
65
74
 
75
+ ## Regions
76
+
77
+ A renderer may report where a diagram's parts are, so the picture viewer can make them tappable
78
+ ([web-frontend.md](web-frontend.md#picture-viewer)). What it returns beside its SVG, and what the page keeps:
79
+
80
+ ```js
81
+ { kind: "node" | "group" | "edge" | "note",
82
+ id: "BR", // the source's own name, text; "" when none
83
+ label: "Bridge", // what the picture shows, text; "" when none
84
+ box: [x, y, w, h], // fractions of the picture, 0..1; required but for an edge (its label's box)
85
+ points: [[x, y], …], // edge only: 2..16 points along its line
86
+ from: "BR", to: "EN" // edge only, optional: its ends' ids
87
+ }
88
+ ```
89
+
90
+ **Regions are untrusted**: the bundle is trusted, its input is model-written, and a renderer bug must not reach the
91
+ page or stall it. Two gates:
92
+
93
+ 1. **In the frame** (`BOOTSTRAP`): `regions` is sent only when it is an array of at most 600 (`MAX_REGIONS`); otherwise
94
+ the `done` carries none and nothing of it is cloned (a 2M-entry array took 0.4 s in Chromium and 1.4 s in WebKit to
95
+ post, on the page's thread). And what is posted is the frame's **bounded copy** of each entry: its known keys only,
96
+ strings cut to 200 characters (anything else `""`), a box only of 4, at most 16 points, numbers only (else `NaN`),
97
+ a non-object entry `null`; so nothing vast or uncloneable is ever cloned (600 regions with one-megabyte labels,
98
+ posted as they were, crashed a Chromium tab; copied, the render took 2.6 ms in Chromium and 1 ms in WebKit against
99
+ 0.2 and 0 without regions). Regions that throw when read (a proxy) are dropped, and a post that throws anyway is
100
+ sent again without them.
101
+ 2. **In the page**, `block_regions.js cleanRegions` (pure), before the picture is cached: not an array, or over 600 →
102
+ none; a running budget of 128 KB over the *cleaned* fields (kept strings' lengths, 12 per number), past it → none
103
+ (`MAX_REGION_BYTES`); an entry that isn't a plain object or whose `kind` isn't one of the four → skipped; `box`
104
+ exactly 4 finite numbers, clamped to 0..1 and cut to the picture, no area → skipped (an edge loses its box);
105
+ `points` 2..16 pairs of finite numbers, clamped, else the edge is skipped; `id`, `label`, `from`, `to` strings only
106
+ (never `String()` of an object), controls and line separators a space, bidi, zero-width and lone surrogates gone,
107
+ whitespace runs one space, cut by code points to 80 (`label` 120); only own keys of known names are read, and the
108
+ result is new objects. A region left with no name is skipped (a node, note or group with neither `label` nor
109
+ `id`; an edge with no `label` and not both ends): the card and a button name a region by the diagram's own text
110
+ only, and the page never makes one up (a "node 3" means nothing in the source, nor to the model). Nothing stringifies the raw data (structured clone keeps cycles and BigInt). A list dropped
111
+ whole is said once per language (`console.warn`, its count, no model text). **Never cut**: past a cap the picture
112
+ shows with nothing tappable.
113
+
114
+ **What the page does with a region's text: `textContent`, an `aria-label`, composer text. Never markup, a selector, a
115
+ URL, a `data-*` value another module reads back, or a key into an object.** Numbers become percent offsets in
116
+ `style` and the points of the page's own `<polyline>`, through lit bindings. Nothing reaches the server, a session
117
+ file, the DOM of an answer or the model. Cost: 1–2 ms per render in the frame (measuring is the bundle's), one
118
+ `cleanRegions` per render in the page, 1–4 KB a real diagram in the cache.
119
+
66
120
  ## A failed block is asked for again
67
121
 
68
122
  One mechanism for every drawn block, a `chi-ui` picks or walk (core's drawer) and a bundle's renderer (chi-mermaid's
@@ -189,6 +243,7 @@ is model-written**, so a renderer bug or an injected diagram must not reach a pa
189
243
  | Page header `frame-src 'none'` (`App::FRAME_HEADERS`; srcdoc frames still load and run under it) | self-navigation, meta refresh, anchor click, which leak past the frame's CSP in both browsers |
190
244
  | `delete window.RTCPeerConnection` + `webkitRTCPeerConnection` in the bootstrap, before any bundle code | the plain WebRTC call only |
191
245
  | Output only as `<img src="data:…">` | scripts and remote images inside the SVG don't run or load |
246
+ | Regions capped in the frame, cleaned in the page (`block_regions.js`), used as text and numbers only | a renderer's regions as markup, a selector or a URL; a vast or uncloneable list stalling the page |
192
247
 
193
248
  **Hard rules.**
194
249
 
@@ -5,12 +5,19 @@ localhost HTTP server in the worker's process, next to the `Engine` it reads and
5
5
  terminal are its clients; no browser reaches it. [architecture.md](../architecture.md) places it among the layers;
6
6
  this page is the surface: what it keeps, how a client joins and catches up, and every route.
7
7
 
8
- Bridge Engine calls are listed with their reasons in `Bridge::ENGINE_CALLS`; add each new Engine call there.
8
+ Bridge Engine calls are listed with their reasons in `Bridge::ENGINE_CALLS`; add each new Engine call there. Four of
9
+ the Engine's parts are not among them: `Bridge.new` takes them as `event_log:`, `turn_state:`, `question_desk:` and
10
+ `steer_cut:` (the Engine's own `SessionObserver`, `TurnState`, `QuestionDesk` and `SteerCut`: `Engine#event_log`,
11
+ `#turn_state`, `#question_desk`, `#steer_cut`, handed on by the Worker) and calls them directly: `subscribe`,
12
+ `unsubscribe`, `event_count`, `announce` and `synchronize` on the log; `running?`, `controller`, `cancel!` and the
13
+ enqueued-id ledger on the turn state; `pending`, `answer`, `cancel` and `annotate` on the desk; `input_epoch`,
14
+ `cut_for_steer` and `generation_snapshot` on the cut. `ENGINE_CALLS` lists what is left.
9
15
 
10
16
  ## What a Bridge keeps
11
17
 
12
- `Bridge#start` binds a port (OS-assigned, `127.0.0.1`), then subscribes four persistent observers to the Engine
13
- (`Engine#subscribe`, the thread-safe fan-out whose events all carry a monotonic `event_seq`). Each is cheap and
18
+ `Bridge#start` binds a port (OS-assigned, `127.0.0.1`), then subscribes five persistent observers to the event log
19
+ (`SessionObserver#subscribe`, the thread-safe fan-out whose events all carry a monotonic `event_seq`): the capture
20
+ observer (feeding the ring), the accumulator, the drawings, the cards and the pending card. Each is cheap and
14
21
  rescues its own errors: an observer must never break the running turn.
15
22
 
16
23
  | Piece | File (`bridge/`) | Holds |
@@ -20,7 +27,7 @@ rescues its own errors: an observer must never break the running turn.
20
27
  | `CardStore` | `card_store.rb` | The last cards and notices, saved in `cards.json`, each anchored to its turn. |
21
28
  | `TurnDrawings` | `turn_drawings.rb` | Each finished turn as live drew it (`turn_drawings.jsonl`): written by the accumulator's `on_turn_end` hook, read by chi web's show. |
22
29
  | `CardPlaces` | `card_places.rb` | Pure: where `CardStore`'s entries sit in the messages the page draws (`turns_since`, and the `opening_id` stamp). |
23
- | `PendingCard` | `pending_card.rb` | `pending_card.json` `{id:, bundle:}`: the running turn's open card with actions (check-in's Nudge), written and removed with that card, so chi web's hub, which watches files and not workers, can notify. |
30
+ | `PendingCard` | `pending_card.rb` | `pending_card.json` `{id:, bundle:}`: the running turn's open card with command actions (check-in's Nudge); a URL-only card does not ask (`CardWait`), so it writes no pending card, and it is removed with the card, for chi web's file-watching hub. |
24
31
 
25
32
  Per connection there is an `SSEWriter` (with a `BoundedQueue`); `ClientEvent` and `EventId` are pure helpers. The
26
33
  Bridge also owns its **epoch** (`SecureRandom.hex(4)`: `event_seq` starts over in each worker, so the epoch says
@@ -265,7 +272,8 @@ the "asking again" and steer-cut rows, ✂ rows and questions (with how they wer
265
272
 
266
273
  ## SSEWriter
267
274
 
268
- One per `GET /session/:id/stream` connection, and itself that connection's observer: `Engine#emit_event` calls
275
+ One per `GET /session/:id/stream` connection, and itself that connection's observer (it takes the event log, no
276
+ Engine): `Engine#emit_event` calls
269
277
  `#call` on the turn's thread, so it only pushes onto a `BoundedQueue` (when full, the oldest entry goes and an
270
278
  overflow flag is set). The connection's own thread (`#serve!`) drains the queue onto the socket, so a slow client
271
279
  cannot stall a turn or another subscriber. An event holding bytes JSON can't take goes out scrubbed
@@ -278,7 +286,7 @@ ring holds the event. `serve!` orders a join so that nothing is missed or double
278
286
  4. drain the queue for `seq > snapshot`; a per-connection high-water mark drops what step 3 already wrote.
279
287
 
280
288
  `?snapshot=1` replaces 2-3: subscribe and `Bridge#snapshot_frame` happen as one step with the event log held
281
- (`Engine#synchronize_events`), the client gets one `snapshot` frame, and live events follow from the next seq.
289
+ (`SessionObserver#synchronize`), the client gets one `snapshot` frame, and live events follow from the next seq.
282
290
 
283
291
  A **`reset`** frame (the same content, numbered with its own seq) is written when a cursor cannot be replayed: it is
284
292
  from another epoch, ahead of the engine (a restarted worker), behind the ring's window (a cursor at `oldest - 1` has
@@ -41,7 +41,7 @@ read side, never the reverse.
41
41
  | Piece | Role |
42
42
  |---|---|
43
43
  | `InstalledBundles` (`installed_bundles.rb`) | `.each(holding:, dir:)` (each installed bundle by name, its `Record`; one whose `manifest.json` doesn't read with `error` set, and with `holding:` only those with that key, or that dir when it doesn't read), `.claimants` (which bundles own a memory file), `.dir` (`MemoryPaths.bundles_dir`) |
44
- | `InstalledBundles::Dir` (installed_bundles/dir.rb) | one bundle's `.bundles/<name>/` as the runtime reads it: `Dir.new(name:, dir:)`, `#record`, `#plugin_dir`, `#plugin_path`, `#scripts_dir`, `#guardrails_dir`, `#kept_manifest_path`, `#file_refusal(kind, file, recorded)` (the one "is this installed file as installed" check: `:plugin`, `:scripts`, `:guardrails`, one order (no sha recorded, missing, changed) and one wording, `bundle X's <folder>/<file> isn't recorded / is missing / differs from the installed one (reinstall the bundle)`, a `Refusal`). Its only state is the name and the folder; `Provenance` is one |
44
+ | `InstalledBundles::Dir` (installed_bundles/dir.rb) | one bundle's `.bundles/<name>/` as the runtime reads it: `Dir.new(name:, dir:)`, `#record`, `#plugin_dir`, `#plugin_path`, `#scripts_dir`, `#guardrails_dir`, `#kept_manifest_path`, `#plugin_part_paths`, `#plugin_refusal(record)` (the whole plugin: the file's `file_refusal`, then each part's in load order, then `:parts_missing`, below; the loader, `Status.plugin_status` and `SessionConfig#unloadable` ask it), `#file_refusal(kind, file, recorded)` (the one "is this installed file as installed" check: `:plugin`, `:scripts`, `:guardrails`, one order (no sha recorded, missing, changed) and one wording, `bundle X's <folder>/<file> isn't recorded / is missing / differs from the installed one (reinstall the bundle)`, a `Refusal`). Its only state is the name and the folder; `Provenance` is one |
45
45
  | `InstalledBundles::Standing`, `Refusal` (installed_bundles/standing.rb) | the usability verdict: `.standings(holding:, dir:)` (the walk, each bundle's `Standing`), `.standing(name, dir:)` (one record; a `manifest.json` that doesn't parse is `:unreadable`, in the walk's words), `Standing.of(name, record)`: `#refusal` is `:unreadable` (the record; `Standing.warn_unreadable` logs `bundle_unreadable` once per process per bundle and reason, whichever reader came across it, `.claimants` too) or `:too_new` (requires_chi), nil when chi may use it; none of the bundle's own files is hashed (a manifest cache miss hashes the kept `manifest.yml`, as `Manifest.of` does). A `Refusal` has `kind`, `text` and, for `:file_changed`, the `actual` and `expected` shas. Each reader keeps only its reaction (below) |
46
46
  | `InstalledBundles::Sha` (installed_bundles/sha.rb) | the record's shas: `.recorded` (either format, `""` for none), `.of_file`, `DEV` (a dev install's `sha256:dev`), `.unchecked?`, `.matches?` |
47
47
  | `BundleCommand` (`lib/samagotchi/bundle_command.rb`) | `chi bundle install/upgrade/uninstall/status/diff/list/build/trash/new/test/check/try` (`install --dev`: the Installer's `dev:`, links and `InstalledBundles::Sha::DEV`); runs the Installer, prints its summary, runs the conflict agent step; refuses a source already installed under another name (`installed_under_another_name?`: a git URL bundle recorded under its repo's name before the manifest named it). `upgrade` resolves its argument by `upgrade_source`: a git URL or an existing path, then a shipped name, then the bare name of an installed bundle — whose record's source it then uses (a git URL with its `#ref`, a dir or an archive that is still there), printed as `Upgrading NAME from SOURCE`; a dev record is refused with `Installer.dev_install_line`, a recorded source that is relative, empty or gone says so and asks for the path or URL of a copy (`Installer.source_gone_line`, the words `ManifestStanding` uses too). After an upgrade or uninstall that changed the bundle's plugin (or brought one in), one line names the sessions still running its old code (`LiveVersions.workers`, the ones whose worker takes a restart) and `chi sessions restart ID` for each: only the plugin stays in memory, since a bundle's rules reload by their stamp and its scripts run from the replaced files. |
@@ -50,7 +50,7 @@ read side, never the reverse.
50
50
  | `BundleCommand::ApiCalls` (bundle_command/api_calls.rb) | what a plugin's source calls of the API, by Prism: `#findings` (a call or keyword the API's classes lack, `check`'s `api`), `#keywords` (the floor check's `call(keyword:)`). Its only list is `MEMBERS`, which object a member gives (`ctx.sessions` → `Plugin::Sessions`); a new such object joins it |
51
51
  | `BundleCommand::Scaffold` (bundle_command/scaffold.rb) | `chi bundle new NAME`: the starting files (block-form `plugin:` entry, `requires_chi` at this chi, a kit test that passes as written); the manifest's shas are filled through `Shas.refresh` |
52
52
  | `BundleCommand::TestRun` (bundle_command/test_run.rb) | `chi bundle test`: `RbConfig.ruby -I <chi's lib>` on `test/**/*_test.rb` (Minitest) or `spec/` (RSpec, as `rake bundles:specs`), under `Bundler.with_unbundled_env` when Bundler's runtime is loaded |
53
- | `Shas` (shas.rb) | a manifest's `sha256:` lines: `.refresh(dir[, text])` rewrites them line by line (the layout kept; a `files:` entry it can't place raises `Shas::Error`), `.stale` → `[Stale(file, old, new)]` (`old` `""` for a placeholder, nil for a plugin / script entry with no sha line), `.parseable` (a placeholder `sha256: sha256:` isn't YAML). Plain Ruby: `rake bundles:sha` / `bundles:check` (`script/release/release_tools.rb`) and `chi bundle check --fix` share it |
53
+ | `Shas` (shas.rb) | a manifest's `sha256:` lines (a plugin part's is a four-space `name.rb: sha256:<hex>` line under `plugin:` `parts:`, the file being the part's name in the bundle dir): `.refresh(dir[, text])` rewrites them line by line (the layout kept; a `files:` entry it can't place raises `Shas::Error`), `.stale` → `[Stale(file, old, new)]` (`old` `""` for a placeholder, nil for a plugin / script entry with no sha line), `.parseable` (a placeholder `sha256: sha256:` isn't YAML). Plain Ruby: `rake bundles:sha` / `bundles:check` (`script/release/release_tools.rb`) and `chi bundle check --fix` share it |
54
54
  | `InstalledBundles::FileDigest` (installed_bundles/file_digest.rb) | the one digest of a file on disk: `.hex(path)` (its bytes, streamed; nil when the path isn't a file, a raise for one that can't be read), `.sha256(path)` = `"sha256:<hex>"`, nil with no file — the shape a record writes for a rule, plugin or script. `InstalledBundles::Sha.of_file`, `Merger.digest`, `Status.checksum`, `InstalledBundles::Record#source_sha`, `FileStanding.differs?` and the Installer's checksum verifiers all go through it; a digest of bytes already in memory (a merge's text, a memory's content that is also its base) stays with the code holding them |
55
55
  | `SourceNormalizer` (source.rb) | source → local dir; a git/zip/tar extract is *owned* and removed after the install |
56
56
  | `SourceIdentity` (source.rb) | what a source is, for comparing two installs of one name: `shipped:<dir>` (any gem or checkout), `git:<url>` (no `#ref`, trailing `/` or `.git`), `path:<realpath>`; nil when it can't place one |
@@ -126,9 +126,10 @@ A guardrail plugin (`plugin:` `required: true`) is known from `InstalledBundles:
126
126
  unparsable kept manifest.yml never drops it (an older chi's `PluginRef` ignores the key):
127
127
  its failure goes to the hook failures as required (`ExtensionLoad#load_plugins` passes them as `guardrail_failures:`),
128
128
  where the gate denies every tool call; a `chi.on(on_error: :fail_closed)` hook is wrapped `Hooks.wrap(policy: :deny)`.
129
- `Plugin::Loader.load_bundle` asks the verdict (`InstalledBundles::Standing`, then `Dir#file_refusal(:plugin, …)`) and reacts (`.namespace_for` is the bundle's
129
+ `Plugin::Loader.load_bundle` asks the verdict (`InstalledBundles::Standing`, then `Dir#plugin_refusal`) and reacts (`.namespace_for` is the bundle's
130
130
  `Samagotchi::Bundles::<bundle>` module); the loading itself is `Plugin::Loader.register_file` (one
131
- plugin file: build, `register`, `commit!`), which raises instead of logging: the bundle test kit
131
+ plugin: its `parts:` `module_eval`'d in order, each with its own path, then the file, into one fresh module; build,
132
+ `register`, `commit!`), which raises instead of logging: the bundle test kit
132
133
  (`Samagotchi::Testing::Bundle`) loads a bundle's source through them, unchecked. `Samagotchi::Testing::Install` is the
133
134
  checked path in a sandbox: the Installer, then `ExtensionLoad` (config hooks, then `load_plugins`), returning the
134
135
  Installer's warnings, this bundle's load failures and what it registered (`Install.registered`, an `Install::Registered` value, also the parity
@@ -136,6 +137,22 @@ spec's shape). A load failure carries `LoadFailures::Failure#location` (the firs
136
137
  bundle, or a SyntaxError's own line), which `Install` maps from the installed copy (`.bundles/<name>/plugin/`)
137
138
  back to the source dir.
138
139
 
140
+ Plugin parts (`plugin:` `parts:`, docs/plugins.md "A plugin in several files"). `BundleManifest#plugin_files` is the
141
+ one ordered list (parts as listed, then the file; nothing sorts it: not the parser, `Provenance#write` or the
142
+ builder). The record keeps them under its plugin, `{"file": …, "sha256": …, "parts": {"client.rb": "sha256:…"}}`
143
+ (`PluginRef#parts`, `{}` without; `Record#plugin_shas` has every file, so `AssetInstaller`, the `Uninstaller` and
144
+ `ShippedUpdate#trash_bound` treat parts as recorded files), each with a base at `bases/plugin/<part>`.
145
+ `BundleManifest::SINCE` has `"plugin.parts"` (0.183.0). What other chis do:
146
+ - The previous release ignores `parts:` in a manifest and in a record. It installs a too-new plugin with only a
147
+ warning, copying the plugin file alone; after `chi update` this chi refuses that record: `Dir#plugin_refusal`'s
148
+ `:parts_missing` (`bundle X's plugin parts aren't installed (reinstall the bundle)`, status `[parts missing]`), read
149
+ from `InstalledBundles::Manifest#plugin_parts` (the kept manifest's part names, the record's when it isn't read: no
150
+ kept file, or an edited one, is no refusal of this kind).
151
+ - On its own uninstall or upgrade of a record with parts, the parts in `plugin/` are files its record doesn't name:
152
+ `AssetState.in` lists every file in the folder, so they count as edited, get a copy in the trash, and go with the
153
+ folder. Harmless.
154
+ - This chi reads an older record with no `parts` key as no parts: nothing to migrate.
155
+
139
156
  Class-file hooks (retired). A record an older chi installed may still have a `hooks` map and `hooks/*.rb`
140
157
  (`InstalledBundles::Record#hooks`). Nothing loads them, and nothing announces them any more (the first turn, `chi bundle
141
158
  status` and `chi update` did from 0.158 to 0.166). A source with
@@ -234,7 +251,11 @@ summarised by `#summary` by word: a file that already holds the bundle's bytes (
234
251
  rule/plugin/script, in a dry run as in the real run) is listed as `Up to date:`, and only the files really left
235
252
  out (`:kept_own`, a memory's dry-run `:would_skip`) as `Skipped:`. A memory's dry-run word is its action's through
236
253
  `Installer::DRY_WORDS`. A dry run's `would_update` (a plugin or script an upgrade would change) is `Would update:`; an asset
237
- row is never `would_skip`. A plain install over a bundle already installed from the same source ends with `NAME was already
254
+ row is never `would_skip`.
255
+ `BundleCommand#version_line` heads the summary. It reads the old version from the installed record before the run and
256
+ the new one from the manifest: `NAME OLD → NEW` for a change, `NAME VER` otherwise, or `NAME VER (already current)` when
257
+ nothing changed and `Installer#current?` is true. In that case `Installer#summary(current: true)` leaves out `Up to date:`.
258
+ A plain install over a bundle already installed from the same source ends with `NAME was already
238
259
  installed from SOURCE: its rules, plugin and scripts now match it and its record was rewritten`, plus
239
260
  `; your own copies of its memories were kept (chi bundle upgrade NAME merges the bundle's changes into them)` when
240
261
  a memory was left out as the user's (`:kept_own`: an edited one, or one the bundle doesn't own; a never-edited one takes the new text and isn't named there). An upgrade with conflicts keeps an
@@ -124,7 +124,7 @@ Interrupt (Ctrl-C; a one-shot only, a worker traps INT):
124
124
  interrupted result (ToolResponse.run_batch), so no call is kept without its result; a half-streamed reply is
125
125
  not kept; :turn_canceled {cancellation_reason: :ctrl_c}; re-raised (the caller decides whether to exit)
126
126
 
127
- A Stop (Engine#cancel_current_turn!, the Bridge's POST cancel) or a hook's stop_turn:
127
+ A Stop (TurnState#cancel!: the Bridge's POST cancel, Engine#cancel_current_turn!) or a hook's stop_turn:
128
128
  → not an error: LLM::ModelResult(canceled: true, conversation:); complete_turn keeps the conversation with a
129
129
  TurnNote.cancelled note; text streamed before the cancel stays, marked [interrupted]
130
130
 
@@ -331,7 +331,12 @@ only input (`entries`, `reachable_names`, `left_out_names`, `removed_names`, `st
331
331
  One object (`turn_state.rb`), guarded by a `Monitor`, that the turn thread writes (`begin_turn`, `release_turn`)
332
332
  and other threads read: the idle scheduler, the Bridge's request threads, plugin threads, the UIs. It holds
333
333
  running, `context` (nil between turns), `last_context`, `controller`, the turn's thread and `ended`, the sink,
334
- steers and carried steers, and the activity clock.
334
+ steers and carried steers, and the activity clock. The hosts hold it (`Engine#turn_state`): the Worker reads it once
335
+ after it built the Engine and hands it to the Bridge and its own collaborators (`WorkerInbound`, `WorkerIdleExit`,
336
+ `ContinueOffer`), and the Engine hands it to its idle jobs (`IdleReminders`, `IdleRecap`). They call its readers,
337
+ `cancel!`, `record_activity` and the enqueued-id ledger; only the turn thread calls the writers (`begin!`,
338
+ `replace_context`, `ended!`, `finish!`). spec/bridge/turn_state_calls_spec.rb lists, per host file, the TurnState
339
+ methods it may call.
335
340
 
336
341
  - `begin!(context:, controller:, sink:, input_waiting:)`: all of it in one step, carried steers become steers. The
337
342
  context is built whole before (mode and git included), **so no reader sees a running turn with the last turn's
@@ -439,7 +444,7 @@ KernelLoop has its own `Turn` struct, a run's.
439
444
  TurnContext.**
440
445
  - Specs: `run_context(settings: …)` and `attach_services(kernel, tools: …)` (spec/support/test_kernel.rb).
441
446
  - `controller` is an in-process signal; another process stops a worker's turn through the Bridge (`POST cancel` →
442
- `Engine#cancel_current_turn!`).
447
+ `TurnState#cancel!`, on the Engine's TurnState the Worker handed the Bridge).
443
448
 
444
449
  **The live conversation and the checkpoint.** Both loops register the array they append to on the kernel
445
450
  (`KernelLoop#llm_context_turn`, `LLMContextForget::Turn#conversation`, tagged with the run's `turn_id`).
@@ -453,8 +458,9 @@ as a killed turn's (canceled, `worker_stopped`); the turn's end writes over it.
453
458
 
454
459
  ### SteerCut, GenerationPhase and WaitingSteer
455
460
 
456
- The Engine's one `SteerCut` (`steer_cut.rb`) owns a `GenerationPhase` and a `WaitingSteer`. The Bridge and the TUI
457
- ask it (`Engine#cut_for_steer`, `#input_epoch`, `#generation_snapshot`), the stream handler feeds it
461
+ The Engine's one `SteerCut` (`steer_cut.rb`) owns a `GenerationPhase` and a `WaitingSteer`. The Bridge holds it
462
+ (`Engine#steer_cut`, handed on by the Worker) and asks it (`#cut_for_steer`, `#input_epoch`, `#generation_snapshot`;
463
+ the Engine forwards the same three), the stream handler feeds it
458
464
  (`SteerCut#observe`), a drain that took input calls `#delivered!`, and `release_turn` calls `#finished!`.
459
465
 
460
466
  - `GenerationPhase`: whether a steer sent as a cut (`/cut TEXT`, `chi send --cut`) may cut the running generation.
@@ -486,11 +492,15 @@ observers (`Engine#subscribe`), which get a copy with a monotonic `event_seq`: t
486
492
  thinking tails, and in a worker the Bridge ([bridge.md](bridge.md)). **Errors in the sink or an observer are
487
493
  caught; they never break the turn.**
488
494
 
489
- `Engine#announce` puts an event that belongs to no turn (`Engine::ANNOUNCEABLE_EVENTS`: `turn_enqueued`,
495
+ `Engine#announce` puts an event that belongs to no turn (`SessionObserver::ANNOUNCEABLE_EVENTS`: `turn_enqueued`,
490
496
  `turn_dequeued` (`{enqueued_id, client_id}`: the remover's), `card`, `hook_notice`, `guardrail_warning`, `participants_changed`
491
497
  ([participants](participants.md#the-owners-terminal)), and more) to the observers only. `:side_usage` (a side
492
498
  request's usage and the session's side sums) goes to the observers the same way from `Engine#note_side_usage` (any
493
- thread), without being announceable.
499
+ thread), without being announceable. The list and the check are the event log's (`SessionObserver#announce`, the
500
+ same ArgumentError before anything is numbered); `Engine#announce` forwards to it. The Engine creates the log and
501
+ shows it (`Engine#event_log`): a worker's hosts (the Bridge, the Worker and its collaborators) hold that one log and
502
+ call it directly, so `Engine#subscribe`/`#unsubscribe`/`#event_count`/`#announce`/`#synchronize_events` stay for the
503
+ Engine's own parts, the one-shot host and Engine-only specs.
494
504
 
495
505
  Turn events (the main ones; `events.rb` keeps the shared sets):
496
506
 
@@ -774,7 +784,7 @@ are in [architecture.md](../architecture.md)'s file table.
774
784
  | `engine/models.rb` | `Engine::ModelsPart`: model names, identity, notes, `switch_model!`, the profile, `backend` |
775
785
  | `engine/model_settings.rb` | `Engine::ModelSettingsPart`: SessionModelSettings and EngineSnapshots, forwarded |
776
786
  | `engine/events.rb` | `Engine::EventsPart`: observers, `#announce`, the event lock, held announcements |
777
- | `engine/cards.rb` | `Engine::CardsPart`: `#show_card`, anytime commands |
787
+ | `engine/cards.rb` | `Engine::CardsPart`: `#show_card` (and `between_turns:`), anytime commands |
778
788
  | `engine/objectives.rb` | `Engine::ObjectivesPart`: the objectives stage's builder and forwards (`announce_objectives`, `show_objective_proposals`, `track_objectives_after`), Check this's and the tracker's side requests (`ask_objective_check`, `ask_objective_track`) |
779
789
  | `engine/messages.rb` | `Engine::MessagesPart`: out-of-turn message edits, checkpoints, the live conversation |
780
790
  | `engine/plugins.rb` | `Engine::PluginsPart`: plugins, init tasks, staged tools, `Plugin::Host` |
@@ -783,7 +793,8 @@ are in [architecture.md](../architecture.md)'s file table.
783
793
  | `engine/participants.rb` | `Engine::ParticipantsPart`: the turn's author, a pair turn's stop, the participants line |
784
794
  | `engine/session.rb` | `Engine::SessionPart`: `#session=`, the state dir, the relay's view, the system prompt |
785
795
  | `engine/verify.rb` | `Engine::VerifyPart`: the Verify/Revise anchors' stage builder |
786
- | `engine/questions.rb` | `Engine::QuestionsPart`: ask-user-question (QuestionDesk, forwarded) |
796
+ | `engine/questions.rb` | `Engine::QuestionsPart`: ask-user-question (QuestionDesk, forwarded: the hosts hold `Engine#question_desk`; the forwards stay for the Engine's parts, the one-shot and Engine-only specs) |
797
+ | `engine/sign_in.rb` | `Engine::SignInPart`: `ctx.sign_in` flows and cards, `/callback`, and ending flows at shutdown (idle exit waits for a waiting flow) |
787
798
  | `engine/toolkit.rb` | `Engine::ToolkitPart`: the toolkit, `ctx.load_tools`, the toolkit suggestion's builder |
788
799
  | `engine/context_judge.rb` | `Engine::ContextJudgePart`: the candidate judge's builder and `judge_late_candidates` |
789
800
  | `engine/turn_helpers.rb` | `Engine::TurnHelpersPart`: turn settings, images, model ref, used memories, the warm-up's builder |
@@ -201,7 +201,7 @@ row answers another session's id 404, so a new route is covered without a new ex
201
201
  | `POST /api/sessions/:id/turn/:eid/dequeue` | participant | their own queued turn back; another's (the owner's included) is 403 `not_permitted` |
202
202
  | `POST /api/sessions/:id/verdicts/:check_turn_id/fresh` | participant | a fresh child to check an unclear verdict, running as the requester under pair rules and counted toward their cap ([Verify fresh](#what-a-participant-sees)) |
203
203
  | `GET /api/sessions/resolve?id=` | participant | their session for its id or a prefix of it; anything else 404 as no session (never an ambiguity listing others) |
204
- | `POST /api/sessions/:id/wait/prepare`, `…/wait` | participant | only for a turn of theirs (`turn`: the enqueued id `POST …/turn` answered; else 403); `wait/prepare` answers only what that wait needs, `{session_id, baseline: {last_turn}, known_turn, live, last_turn_id}` (`last_turn_id` only when it is their turn), never the owner's cursor, message count, question or running turn; the answer trimmed to `{status, text, turn_id, outcome, cancel_reason}`, the reply's `text` through `ParticipantView.reply` (no thinking or tool call, redacted) and any other text (an error's exception, a failed turn's summary) `ParticipantMessages::TURN_FAILED`; a question or approval their turn raised, or their turn held by the owner's step-limit Continue offer ([Turns](#turns)), is `{status: "waiting_for_owner", detail: "waiting for the session's owner"}` with nothing of it; a revoke or the expiry ends a `wait` already running (401 `token_revoked` / `token_expired`), as it ends their stream |
204
+ | `POST /api/sessions/:id/wait/prepare`, `…/wait` | participant | only for a turn of theirs (`turn`: the enqueued id `POST …/turn` answered; else 403); a wait token (`{token}`) is the owner's: a participant's token wait is 400 `invalid_wait` (`a participant's wait takes a turn, not a token`); `wait/prepare` answers only what that wait needs, `{session_id, baseline: {last_turn}, known_turn, live, last_turn_id}` (`last_turn_id` only when it is their turn), never the owner's cursor, message count, question or running turn; the answer trimmed to `{status, text, turn_id, outcome, cancel_reason}`, the reply's `text` through `ParticipantView.reply` (no thinking or tool call, redacted) and any other text (an error's exception, a failed turn's summary) `ParticipantMessages::TURN_FAILED`; a question or approval their turn raised, or their turn held by the owner's step-limit Continue offer ([Turns](#turns)), is `{status: "waiting_for_owner", detail: "waiting for the session's owner"}` with nothing of it; a revoke or the expiry ends a `wait` already running (401 `token_revoked` / `token_expired`), as it ends their stream |
205
205
  | `GET /` | participant | the main page (`index.html`) stamped for them (`App#participant_index_data`: their viewer, the grant's session and its title; [web-frontend.md](web-frontend.md#the-participants-page)); the page reads the rest through the show and the stream below |
206
206
  | `POST /api/token` | participant | trade a link's one-time code or a pasted token for the `chi_token` cookie (the token is not left in the page URL) |
207
207
  | `GET /api/sessions/:id/stream` | participant | the session's stream through `ParticipantStreamFilter` (only `from_seq` and `snapshot` reach the Bridge); it ends within a poll of a revoke or the expiry |
@@ -65,7 +65,14 @@ right-hand column happens.
65
65
 
66
66
  - The sections above are recorded as `prompt_parts` (`SystemPrompt#prompt_parts`, `PromptPart`: kind, label, chars,
67
67
  tokens at `TokenUsage::CHARS_PER_TOKEN`, ref, a memory part's scope; one per memory, file and plugin section, plus a
68
- `tools` part): sizes only, worked out once with the build and saved on the session; the prompt's text is unchanged.
68
+ `tools` part): sizes, and each part's place in the built prompt (`at`, `len`, `lead`, a 12-hex `digest` of its own
69
+ text, the prompt's 16-hex `head` digest, `params` to fetch it again), worked out once with the build
70
+ (`PromptLayout`) and saved on the session; the prompt's text is unchanged. Each builder returns its `Section` with
71
+ its `Item`s (lead and text) where it renders them; the parts derive from the items, so their places can't drift
72
+ from the bytes. `spec/prompt_parts_spec.rb` holds today's parts to a golden and every slice to its item. The text
73
+ itself is not copied: the head is the session's `messages[0]`, which a part's place points into
74
+ ([working-set.md](working-set.md#prompt-parts-as-sent)). `Engine#system_prompt` reads prompt, parts, notes and
75
+ index from the one `Built` (`SystemPrompt#built_for`), and the turn-end warm-up builds with `record: false`.
69
76
  - The system prompt is built **once per key** and kept (`SystemPrompt#build`, keyed by `[chat, thinking, layers]`:
70
77
  the loop, the thinking level, the turn's LLM context layers; a `/thinking` change builds under another key). All
71
78
  of them are dropped only on `@prompt_builder.reset!`: a model switch (`Engine#switch_model!`), a plugin's
@@ -77,6 +77,41 @@ exist. **A new session command or flag fails that spec until you choose one.**
77
77
  registry flag (`--recap-base-url` …) is this machine's config: `LOCAL_ONLY` without being listed
78
78
  (`Contract.run_status`). The contract spec fails on a run flag in neither.
79
79
 
80
+ ## Exchange
81
+
82
+ `SessionAccess::Exchange` (`session_access/exchange.rb`) holds the stateless pieces of "send one message and bind its
83
+ wait", over either backend (it calls only their public methods): `locate` (resolve, head, the poll while a continue
84
+ is in flight: `Located` or `Unsent`), `relocate` (located again after a continue took the link), `attempt` (one
85
+ delivery: show, the caller's check, owner, images, the delivery choice, `deliver_turn`: `Attempted` or `Stopped`),
86
+ `bind` (`ReplyWait::Target.message`) and `wait` (the backend's wait, the turn id and the UTF-8 text). It prints
87
+ nothing, keeps no state between calls, never retries and lets the backend's errors raise. `SendCommand` keeps its
88
+ retry loop, rescues and lines and calls these pieces (its Exchange reads `CONTINUING_WAIT` and `pause` when built, the
89
+ specs' stubs); `CLI::ParentWait` (chi send's and chi answer's wait) calls `wait`. `SessionAccess::Ask`
90
+ (`session_access/ask.rb`) is its own short loop over the same pieces for one message and one wait slice on one
91
+ deadline (chi web's starts with the request: `locate`'s `deadline:` and `relocate`'s `bounded: true` end the continue
92
+ waits `Ask::MIN_SLICE` before it, a continue that takes the link after it gets no second delivery, and the Bridge wait
93
+ of a worker starting draws on it too, as does the post to a live worker: `AskRoutes#ask_bridge`, used by `POST …/ask`
94
+ and `POST /api/mcp` (one deadline per POST, `Tools::CAP`), gives the BridgeClient a read of what is left but
95
+ `MIN_SLICE`, within `POST_FLOOR` (8 s, so a loaded worker still reads it) and `READ_TIMEOUT`; the body's `deadline`
96
+ is a `DEADLINE_SHARE` of that read and at least `POST_MARGIN` (2.5 s) short of it (BridgeClient's `deadline_margin`,
97
+ so a worker that took the turn just in time still answers its 202 before the client gives up), so a worker that reads the turn late drops it (408 `deadline_passed`, the route's
98
+ 504 `worker_timeout`) rather than run it after the call gave up: about 44 s at worst; chi web stopping cuts the continue waits at the next look, `Refused :canceled`,
99
+ 503 `server_stopping`; a client that goes away is not seen (WEBrick), so its handler runs on to that deadline),
100
+ answering `Reply` (with an `Exchange::Token` on timeout), `Ran` or `Refused` (a `/continue yes` the worker ran as a
101
+ command, on an idle session with its offer standing and a live worker, is bound with `ReplyWait::Target.answer(start)`
102
+ instead, the offer's turn id from `ReplyWait.own_turn`, as chi answer follows it; the worker's ack is not read): chi web's `POST …/ask`
103
+ builds one per request over a `Local` that delivers through chi web's own manager and Bridge (`Web::AskRoutes::
104
+ AskAccess`), and `McpServer::Tools` reuses `SessionAccess::Ask` / `Exchange` through the MCP server without chi web.
105
+ An ask's `request_id` becomes its turn's enqueued id (`SessionInbox.enqueued_id_for("ask:" + it)`, a UUID v5 shape a
106
+ Bridge keeps): `Ask#call` first reads `prepare_wait(turn: E)`, and a `known_turn` (running, a queued input file, the
107
+ last to end, a reply file, settled, merged) is waited on again with `Target.wait_only(start, requested: E).with(queued:)`, nothing
108
+ sent (`Reply#rebound`, so the route skips the history line), unless E only waits as an input file and no worker runs
109
+ (`Local#waiting_turn?`): then it is sent again with E, which wakes one (the worker runs an id once: `input_taken?`,
110
+ `TurnState#claim_enqueued_id`); else `Exchange#attempt(enqueued_id: E)` carries it to
111
+ `deliver_turn`, and the Bridge's H6 dedupe answers a copy it still remembers with the original ack (409
112
+ `enqueued_id_conflict` for another prompt; a known turn is rebound without a prompt check). A retry on a newer link (a continue) is not deduped.
113
+ The routes: [thin-clients.md](../thin-clients.md); the MCP protocol: [mcp-server.md](../mcp-server.md).
114
+
80
115
  ## One request, end to end
81
116
 
82
117
  `chi --remote studio send ab12 -m "fix it" --wait`:
@@ -84,8 +119,8 @@ registry flag (`--recap-base-url` …) is this machine's config: `LOCAL_ONLY` wi
84
119
  1. **bin/chi → Dispatch.** The flag is removed. `send` and `send --message` / `--wait` are `SUPPORTED`. `Remotes.find("studio")`
85
120
  reads `$XDG_CONFIG_HOME/samagotchi/remotes.yml`. Then `SendCommand.new(argv, access: Remote.new(entry)).run`.
86
121
  2. **SendCommand.** The client-side checks (UI-only slash commands, image ingest) run. The machine-local ones are
87
- skipped (next section). Every id is resolved once up front (`SendCommand#target`): `Remote#resolve`, then
88
- `Remote#head`, where input for it goes (a continued session's chain's newest link).
122
+ skipped (next section). Every id is resolved once up front (`SendCommand#target` → `Exchange#locate`):
123
+ `Remote#resolve`, then `Remote#head`, where input for it goes (a continued session's chain's newest link).
89
124
  3. **Remote → HTTPTransport.** The first request on a `Remote` is preceded by `check_server!`, which sends
90
125
  `GET /api/info` and needs `app: "chi-web"` plus the `session_commands` feature. Next come
91
126
  `GET /api/sessions/resolve?id=ab12`, `GET /api/sessions/resolve?id=<full id>&head=1` (`{id, asked, via}`:
@@ -93,8 +128,8 @@ registry flag (`--recap-base-url` …) is this machine's config: `LOCAL_ONLY` wi
93
128
  ignores `head=1` and answers `{id}`, read as `same`, so the message goes to the id named as before; a participant's
94
129
  token never asks, and the participant branch of the route answers `{id}` alone) and
95
130
  `POST …/wait/prepare {busy: true, queue:}` (`Remote#busy`) on the id it answered, then
96
- `POST …/wait/prepare {turn, created}` for the `WaitStart`. `deliver` calls `Remote#show` and `#owner` (each
97
- `GET /api/sessions/:id?brief=1`), then
131
+ `POST …/wait/prepare {turn, created}` for the `WaitStart`. `deliver`'s pass (`Exchange#attempt`) calls
132
+ `Remote#show` and `#owner` (each `GET /api/sessions/:id?brief=1`), then
98
133
  `POST …/turn {prompt, client_id: "cli:send", history: false}`. A 202 ack becomes a `DeliverResult` with `via`
99
134
  (`bridge` or `file`).
100
135
  4. **chi web.** `Web::App#route` runs the Host check (`local_host_header?`), then `cross_site?`, then in LAN mode for a
@@ -102,7 +137,7 @@ registry flag (`--recap-base-url` …) is this machine's config: `LOCAL_ONLY` wi
102
137
  before any handler runs. A `:session` route turns an `ArgumentError` into its unknown-session 404. The handlers in
103
138
  `SessionAccessRoutes` call `session_access`, a `SessionAccess::Local` on chi web's own state dir. The page's older
104
139
  routes (`/turn`, `/answer`, `/stop`, …) call `SessionManager` and the Bridge directly, as before.
105
- 5. **The wait.** `ParentWait#wait_for_reply` → `Remote#wait_reply` loops on `POST …/wait` with
140
+ 5. **The wait.** `ParentWait#wait_for_reply` → `Exchange#wait` → `Remote#wait_reply` loops on `POST …/wait` with
106
141
  `timeout: min(time left, WAIT_SLICE)` (30 s). The server runs `ReplyWait.call` for at most `WAIT_MAX_SECONDS` (30 s)
107
142
  and returns the `ReplyWait::Result` fields plus `parent_strategy`. On a `timeout` status the client asks again until
108
143
  its own `--timeout` runs out, at which point it builds the `timeout` result itself. Each slice is a fresh `ReplyWait`