samagotchi 0.181.0 → 0.183.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -1
data/docs/sessions.md CHANGED
@@ -8,6 +8,8 @@ continue; the new link starts empty. See [context storage](context.md#storage).
8
8
 
9
9
  **Message times:** an entry of `messages` may carry `at`, when it happened: a local-offset ISO time with milliseconds (`2026-10-24T14:32:05.120+02:00`). User prompts, lines merged into a turn and steers, reminders, context and task notes, and the model's replies have one (a note's is its `created_at`); tool results, `!cmd` messages and chi's own turn notes don't, nor does anything saved before chi stamped messages (no backfill). It is for the UIs only (the gap dividers, a bubble's time): it never goes to the model, so it changes nothing in the requests or their prompt cache. The one time the model reads is the reminders': due reminders go into a turn as a system message headed `[SYSTEM: REMINDERS DUE 2026-10-24 14:32 local]` (the turn's local time; `ReminderQueue#inject!`), written into the saved content then, so a later request sends the same text.
10
10
 
11
+ **Block fixes:** an answer's model message may carry `block_fixes`, a list of `{key, fixed_key, state, reason, at}`, one per fenced block the owner's page couldn't draw and asked for again (`fixed` or `failed`; `key` is the failed block's, `fixed_key` its fix's: `BlockFix.key`). The fix itself is in the message's `content` (no turn had started since) or its `display` (one had). Display only, like `display` and `display_refs`: it never goes to a model, a hook or a plugin, and an older chi reads a message with it without complaint (a turn on an older worker drops the key). See [block-renderers.md](internals/block-renderers.md#a-failed-block-is-asked-for-again).
12
+
11
13
  **Verify verdicts:** a web Verify turn stamps its opening user message with `verify: {turn_id, quote}` (the selected source turn and quote; metadata only, never added to the prompt). When that turn completes and the final assistant reply's last non-empty line is a valid `Verdict: confirmed|refuted|unclear — <reason>`, the session file appends `{anchor: {turn_id, quote}, verdict, reason, by, check_turn_id, at}` to its optional `verdicts` array. `by` is the turn's author (nil for the owner), `check_turn_id` names the Verify turn, and `at` is its timestamp. The array is append-only; older files without it have no saved verdicts. An `unclear` verdict can be checked again by **Verify fresh** (a delegate child that gets only the claim; see *Delegating*): its verdict is appended to the parent's `verdicts` with `fresh: true`, `of` (the verdict it checked again) and `child_id`, from the parent's `fresh_verdicts/` dir, which its worker takes between turns. Verdicts are display state: none enters a prompt.
12
14
 
13
15
  **Revise stacks:** a web Revise turn (POST /turn `revises: {turn_id}`, the answer it rewrites) stamps its opening message (its prompt) with `revises: {turn_id}` at the turn's end, only when the turn completed with an answer (`AnswerTail`): a failed, canceled or empty turn revised nothing (`TurnStages::VerifyAnchors#stamp_opening`). A draft no prompt carries (a stale page, a rolled-back turn) is no target: no stamp. A draft a stamped turn already revised is re-targeted to its stack's top, the newest version, so a stack is a chain `v1 ← v2 ← v3`. Like `verify`, it is metadata only, never added to the prompt (no change to a request's bytes); chi web's history passes it on the opening message (and on a wake turn's note), and `:turn_completed` carries the stamped `revises` (the participant view's too). The history also marks a Verify turn's opening `verify: true`, and so does its live end event (`:turn_completed`'s `verify: true`, with its `turn_id`): the page offers no Revise on its answer. The web page draws the stacks from these stamps (docs/cli.md, Revise). Like a Verify turn's, a Revise message waits for the running turn's end (`SessionInbox.turn_end_data?`; the Bridge takes either as `delivery: queue`, so it never cuts and its ack and `:turn_enqueued` say it queues), is sent only to a worker whose `bridge.json` names the `revise` feature (else 409 `revise_unavailable`), and a failed turn gives it back (`:prompt_restored`'s `revises`). A participant's Revise is theirs only (`ParticipantRevise`, from the authors the server stamped): the answer to their own message (not a Verify turn's), with only their own turn openings after it (an owner's `!` line, which they never see, counts for nothing). chi web checks it at the send against the live worker's snapshot (403 `revise_not_own`, the same for a missing turn; 409 `revise_overtaken`; 409 `revise_unavailable` for a live worker without the `participant_revise` feature), and the worker checks it again at the stamp, up to the Revise turn itself. A Revise someone else's turn overtook after the send silently becomes a plain turn: it runs and answers, but nothing folds, no stack is drawn and neither they nor the owner get a notice; only a `revise_anchor_rejected` log line (reason `overtaken` or `not_own`) records it. It isn't refused at the start (a turn can overtake it after the send). A delivery to a live worker without `participant_revise` is refused too (`SessionManager::Delivery`, 409 `revise_unavailable` in their words). The owner's Revise is unchanged, of anyone's answer. Both anchors travel as one `TurnAnchors` inside chi; on the wire and in an input file each keeps its own key (`verify`, `revises`).
@@ -49,9 +51,9 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
49
51
 
50
52
  **Stopping a worker:** `chi sessions stop ID` marks the session stopped (an `<id>/stopped` file holding when, `{"at"}`, not a session.json field, which a worker saving at that moment would write over; a resume removes it), sends its worker TERM, then CONT (a stopped worker, SIGSTOP or Ctrl-Z, runs its TERM handler only once continued, so it leaves at once instead of outliving the wait), and waits (up to 10 s) until the worker has let go of `owner.lock`. A running turn is canceled over the Bridge first, with reason `session_stopped` (the turn's line ends "(session stopped)", its note says `cancelled (session-stopped)`, and a command it was running says "stopped as the session was stopped"; a bare signal to the worker makes it "stopped by a signal to chi"; an older worker takes the reason as `manual`); the TERM stops whatever still runs as a Stop with reason `signal` and saves it (a spawned worker traps TERM, HUP and INT: `WorkerSignals`; a turn not ended within 3 s, 0.5 s after a stop or a second signal, is cut and the session saved as it was), and a stopped worker still saves its kept turn, since the marker, not the saved status, says stopped. Any TERM, HUP or INT does the same to a worker outside a stop: it leaves (log `worker stop reason=signal`) and the next send wakes a new one, so a `chi --resume ID` right after spawns a fresh worker. That is also how to restart a worker still running an older chi, which the attached terminal reports when a command or a question dismiss gets a 404, and the web when an answer, a dismiss, a command or a cancel does (`501 not_supported`; `BridgeClient.stale_worker_message`). A command this chi has that the older worker doesn't (`/llm-context`, the web's ⚙ panel, against a 0.39.0 worker) says the same, not `not a session command` (`SessionCommandCatalog.builtin_name`); a typo keeps its `400 unknown_command`. The web's `POST /api/sessions/:id/stop` waits the same way, for 2 s (the page's Stop shows the stop at once), or for the body's `wait` up to the same 10 s (`SessionManager::STOP_WAIT`): `chi --remote NAME sessions stop` sends it, so it waits as long as here. Before that stop, the page's `stop session` button asks what the worker still has that the user can stop: `GET /api/sessions/:id/holds` (owner-only) answers the worker's `holds` — the same list the exit ask's 409 carries — always an array, empty when there is no live worker, one from before the route, or one that did not answer. With something, a sheet (a bottom sheet on a phone, a popover at the button otherwise — `stop_sheet.js`) lists them, at most three of a kind named and `+N more`, and offers **Stop all** (`POST /api/sessions/:id/holds/stop` → `HoldStop#stop_all`, then the stop), **Stop session only** (the stop exactly as it was) or **Cancel**. Nothing to ask about is the plain confirm, one tap as before. Both buttons stay because a stop only TERMs the worker: its reminders die with it (a stop also deletes a restart's `reminders.json` no successor took yet, so a later resume doesn't bring them back), while a background task and a delegate are their own processes and keep running. A delete or an archive differs: it never leaves a task the session started running unasked (*Deleting a session*: refused, or `--stop-tasks` stops it), where Stop's "Stop session only" does. A command sent during a turn that waits for its end (`/model X`, `!cmd`; see *Typing during a turn* in [cli.md](cli.md)) and hasn't run when the worker leaves (a stop, a crash) is answered `command_ran {status: "dropped"}`, so no UI keeps showing it waiting.
51
53
 
52
- **Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) also knows about chains (`SessionChain::Delete`, *Session chains* → Deleting a link): it is refused while a continue of the session, or of the previous link it would bring back, is under way (`continuing`), and deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly; the retention sweep removes files directly (`remove_files`). **Background tasks still running:** a user's delete (these three, and `chi sessions delete`) asks first when tasks the deleted sessions started (their `task_create` tasks and the `execute` runs handed over at their limit, read from each session's transcript and `<working_directory>/tmp/tasks/<id>/task.json`: `SessionManager::RunningTasks`) still run: it is refused before anything changes (`tasks_running`), and the CLI's `--stop-tasks`, the web's `stop_tasks=true` (the delete's and the chain delete's query) stop them first (`stopped_by_user`, TERM then KILL after 3 s, all at once, about 4 s at most), under the deleting lock, after the starting-marker re-check, so no worker takes the session meanwhile; that last check refuses a task that started since the first (`worker_stopped: true` when the worker was stopped by then). One rule, fail-safe: a task whose pid still leads the group chi started at the start time it recorded is *running*; one whose record has no start time (before 2026-10-09) or whose start time reads nothing now, while its pid leads a group, is *unverified* ("may still be running"); a `task.json` that doesn't read is *unreadable*. All three refuse; a stop signals only the running ones (an unverified pid may belong to another process now) and reports the rest as not stopped, then deletes. A record left marked running whose pid is gone (a crashed worker's) isn't listed. The 409 is `{error: "tasks_running", reason, op: "delete", detail, session_id, tasks: {running, unverified, unreadable}, worker_stopped, stopped_worker}` (`stopped_worker`: whose worker the delete stopped before the last check refused), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
54
+ **Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web asks in one sheet first (*Session chains* → Deleting a link, the page side in docs/internals/web-frontend.md, The delete sheet): what goes, what is stopped first and what stays, one button naming the outcome, no browser confirm. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) goes through `SessionChain::Delete.link` for every session, chained or not (*Session chains* → Deleting a link): **its delegates follow one rule** (`SessionManager::DELEGATES`): the stopped ones (archived ones too) go with it, deepest first, and a running one stays with its whole subtree, its file untouched; a stopped delegate with a running child goes and leaves that child without a parent. The delegates that would go bring their own refusals: one that is a schedule's target, anchor or head refuses the delete (`scheduled`, naming the delegate), as does one in a one-turn run, one a worker took after the plan was made (`worker_running`), and their running background tasks (below); their participant grants end with them. The result lists them in `deleted` (the session last) and the running ones with their subtrees in `left_running`; the CLI's line and `/exit --delete` say how many went. It is also refused while a continue of the session, or of the previous link it would bring back, is under way (`continuing`), and deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly (`delete_resolved`: they pass neither keyword and take no delegates); the retention sweep removes files directly (`remove_files`). **Background tasks still running:** a user's delete (these three, and `chi sessions delete`) asks first when tasks the deleted sessions started (their `task_create` tasks and the `execute` runs handed over at their limit, read from each session's transcript and `<working_directory>/tmp/tasks/<id>/task.json`: `SessionManager::RunningTasks`) still run: it is refused before anything changes (`tasks_running`), and the CLI's `--stop-tasks`, the web's `stop_tasks=true` (the delete's and the chain delete's query; with `&tasks=<id,id>`, the ones the sheet named, only those: `RunningTasks::Policy.stop(only:)`, see *Deleting a link*) stop them first (`stopped_by_user`, TERM then KILL after 3 s, all at once, about 4 s at most), under the deleting lock, after the starting-marker re-check, so no worker takes the session meanwhile; that last check refuses a task that started since the first (`worker_stopped: true` when the worker was stopped by then). One rule, fail-safe: a task whose pid still leads the group chi started at the start time it recorded is *running*; one whose record has no start time (before 2026-10-09) or whose start time reads nothing now, while its pid leads a group, is *unverified* ("may still be running"); a `task.json` that doesn't read is *unreadable*. All three refuse; a stop signals only the running ones (an unverified pid may belong to another process now) and reports the rest as not stopped, then deletes. A record left marked running whose pid is gone (a crashed worker's) isn't listed. The 409 is `{error: "tasks_running", reason, op: "delete", detail, session_id, tasks: {running, unverified, unreadable}, worker_stopped, stopped_worker, stopped_workers}` (`stopped_worker`: whose worker the delete stopped before the last check refused; `stopped_workers`: every worker the delete stopped), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
53
55
 
54
- <a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}`, stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`. An archive takes no lock for it. Undo (unarchive) doesn't restart them. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
56
+ <a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. The web's Archive stays one tap (the toast's Undo) when nothing is in the way; its 409 opens the delete sheet in Archive's words (what is hidden, the tasks it stops first, `Stop them and archive`, which sends the tasks it named), and any other refusal is that sheet's "Can't archive … now". The 409 also says `sessions`: how many sessions the archive would hide (it and its delegates, across every project), plus `stopped_workers` (every stopped worker id). The refusal words name one stopped worker as "its worker was stopped" or "9d0e1f2a's worker was stopped", and several as "N workers were stopped: its own, 9d0e1f2a". `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}` (with `"tasks": [ids]` only those; a running one not named refuses, `tasks_running`, nothing archived: up front before any worker is stopped, and again after the workers let go), stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`. An archive takes no lock for it. Undo (unarchive) doesn't restart them. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
55
57
 
56
58
  **System 1's saved runs** last as long as sessions: the sweep ages them by day file, and deleting a session purges its runs ([system-one.md](system-one.md)).
57
59
 
@@ -65,7 +67,7 @@ chi sessions list [--live] [--cwd PATH] [--limit N] [--format text|json|tsv] [--
65
67
  chi sessions stop ID
66
68
  chi sessions archive ID... # hide from every list, keep for good; unarchive ID... undoes it
67
69
  chi sessions list --archived # archived sessions too, marked [archived]
68
- chi sessions delete [--force] ID... # for good; --force stops a live worker first
70
+ chi sessions delete [--force] [--dry-run] ID... # for good; --force stops a live worker first; --dry-run: what it would do
69
71
  chi sessions prune [--dry-run] [--days N] [--keep N] [--keep-status running,...] [--test-only]
70
72
  chi sessions clean [--dry-run] [--days N] [--all] # test sessions: all, or older than N days; --all: every kind, as prune
71
73
  chi sessions stats ID [--format text|json] # cost, tokens and progress, without a model turn
@@ -392,7 +394,8 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
392
394
  - **The page:** the info bar's `continue →` continues the open session (`continues: <id>, idle: true`; it reads `continuing…` through the recap wait) and opens the new link with an opener in the composer, not sent (a draft written in this session stays instead; one carried over from another session or the start page gives way to the opener, and the toast's **Restore draft** brings it back): the previous link's own first typed message when that link continues one (the 201's `opener`; a `!shell` line isn't taken), else `Continue where we left off.`. So whatever you sent on the last link comes back on the next one, and editing it once changes it for every later link; the previous link is archived, a toast says so (`Continued 3fa2c1d0 in 4b7e9a01; 3fa2c1d0 is archived; 1 open delegate moved`), and a moved delegate's card folds under the new link. When the previous link's model's host is gone the link starts on the default model and the toast carries the server's `model_warning` too, and then stays until closed. A fresh link (one with no turn yet, however it was made: `continue →`, `chi send --new --continues`, a reload) shows the model picker in its composer with the link's model, until its first turn starts (a failed or canceled first turn ends it too); a pick runs `/model <name>` in the link (a command bubble; the info bar follows) and changes neither the start page's remembered model nor its Recent list, and a Send right after it waits for the `/model` to be taken. A link a one-turn `chi --non-interactive` run has, or one continued already, shows none. A link continued already has no `continue →`: its `→` link goes to the next link (a stale page's continue answered 409 `continued` opens `next_id`). A continue refused for open delegates that can't move shows a toast that names each one (its preview and what the server says to do: `older chi worker 0.46.1; restart it`, `in use by a one-turn chi --non-interactive run or an older chi's terminal; let it finish`), each a link to its page; any other refusal shows the server's words. The info bar of a link carries `← 2026-10-08` (the previous link's day) and, on an earlier link, `2026-10-10 →`, each a link with its id, its full start (`2026-10-10 14:32`) and its preview in the tooltip; a neighbour that started on the open link's own day shows its time instead (`← 09:12`, `14:32 →`). A link made by `continue →` inherits the previous link's preview (and its title, if it has one) when it is created, so its card keeps its chain's title whatever opener it is sent, and its top bar and browser tab show its card's title. A link with a recap of its own reads its auto title, else its recap's first sentence, instead (a link without one reads its chain's name, and a first link's recap names its chain). A link whose title is the opener and nothing else (a `chi send --new --continues` link whose first message is `Continue where we left off.`) shows its chain's first link's title instead, on its card, in the popover and in its info bar's title line, display only (its messages and data keep the opener; its own title when the first link is gone). The lists fold a chain into the card of its latest listed link, whatever the earlier links' archived state (typing in an archived link brings it back, folded there still), their delegates with them: the card's `↩ #N` chip (`#N of M` when later links aren't listed; its tooltip `Session chain: link N of M`) opens a popover of the other links, newest first (`#N`, its date, with its time (`2026-10-17 14:32`) when another link of the chain started the same day, its own title when it differs from the card's (a link inherits its chain's, so mostly it doesn't), else its recap's first sentence, else its preview, `archived`), a click opens one; the chip shows a live dot or `waiting` for a link that has a worker or waits on the user, and a waiting link puts its chain's card first. All sessions folds nothing while a search is typed or the `archived` toggle is on: every link is a card of its own then, its chip `#N of M`, with its own delegates folded in, so a search finds an earlier link and its delegates.
393
395
  - **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
394
396
  - **Which link:** an id, a unique prefix, or `last:<id or prefix>`, the latest link of the chain that session is in. It walks the links that still exist: a deleted link in the middle (`chi sessions delete`, the retention sweep of an unarchived one) ends the walk before it, so `last:` of an earlier link then names that earlier link, and continuing it starts a second line beside the links after the gap; name a link after the gap instead. A trigger names the chain this way: a person's message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain; an unattended sender's is refused (*Who may wake a session*). That is the rule: `chi send` and a note go to the chain's newest link (*Sending a message*, *Context notes*); the web composer, a participant's turn and `delegate(session:)` go to the link they name. One walker answers every one of these (`SessionChain::Links`: one session listing, archive flags read once; the earliest created successor wins a fork a hand edit made, a loop ends where it would repeat), with two rules on it, not unified on purpose: `last:` and a schedule take the chain's **end** (`Links#latest`: a continue refuses a link continued already, and a schedule never un-archives a chain you retired), `chi send` and a note the **first link not archived** (`Links#first_live`: a person's input goes where the chain is live, and brings back an archived end). A chain pruned by a schedule keeps its `anchor`: the kept window's oldest link still names a link that is gone, so the walk simply stops there; the page's chip counts from the surviving root (pruning renumbers the links) and its popover says `earlier links pruned` where the walk stops, rather than linking to a deleted session.
395
- - **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionChain::Delete::DELEGATES`: a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is deleted as before. **The web asks first**: for a chained session, chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store), `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). One session listing walk per call; the page asks only for a chained session as the sheet opens. It takes and releases each link's continue lock (shared, as the delete does), creating its empty file where there was none, and writes nothing else; an unknown id is the usual 404. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself. Each choice carries a `digest` (`SessionChain::Delete.digest`: the sorted ids it deletes, leaves, revives and moves back); the sheet's DELETE sends it as `expect=`, and the delete compares it with the plan it runs (a link's under its holds, as `delete_link` starts; the chain's before its checks) and refuses `plan_changed` (409) before anything changes, a session no longer chained too. Without `expect` (the CLI, an older page) it deletes as it plans then. **The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
397
+ - **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionManager::DELEGATES` (`SessionManager::DelegateRule`; one shared preview row snapshot): a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is a link with nothing to undo: its delegates follow the same rule (*Deleting a session*). **The web asks first**: chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store) for any session, `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). A session in no chain answers `{chained: false, session_id, link}`, the same `link` a chained one gets (`previous_id` null, `earlier`/`later` 0, `next_id` null); an older page reads only `chained`. Each choice (`link`, `chain`) also carries `delegates` (`{delete: [ids], leave: [{id, running}]}`; `running` false for a stopped session left under a running delegate, beside the counts `deletes` and `left_running`), `tasks` (`{running, unverified, unreadable}`: `RunningTasks.of` the ids the choice deletes) and `worker` (a link's: `"turn"` when a worker owns it and a turn runs, `"idle"` when a worker owns it or is starting, null; a chain's `{idle, turn}` counts over its links). No titles: the page names each id from its own list. One shared session-row snapshot serves the link and chain choices; Links lists on its own, and a folder whose session file is gone answers too (the delete still takes it). Each call read-only checks each link's continue lock (a session in no chain too), and writes nothing else but the listing's own repair of an interrupted continue; an unknown id is the usual 404. chi web lists `delete_plan_all` in `/api/info`'s features (`Web::App::DELETE_PLAN_FEATURE`). **The tap stops only what the sheet named**: whenever the choice lists any task, the page sends `stop_tasks=true&tasks=<id,id>`, the choice's running ids (`tasks=` when it has only unverified or unreadable records, which a stop never signals, so such a session can still be deleted); archive's sheet sends `{"stop_tasks": true, "tasks": [ids]}` in its body. `tasks` works only with `stop_tasks`; without it, it is ignored, and `stop_tasks` without `tasks` (the CLI's `--stop-tasks`, an older page) takes every running task the operation can stop. A running task not named refuses (`tasks_running`), and the sheet reads the plan again and shows it with "changed; check again". A chain stops link by link: a link refused that way leaves it and the earlier links whole. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself. Each choice carries a `digest` (`SessionChain::Delete.digest`: the sorted ids it deletes, leaves, revives and moves back); the sheet's DELETE sends it as `expect=`, and the delete compares it with the plan it runs (a link's under its holds, as `delete_link` starts; the chain's before its checks) and refuses `plan_changed` (409) before anything changes; a session in no chain is compared the same way (a sheet shown for a link whose chain is gone since deletes when its ids still match). Without `expect` (the CLI, an older page) it deletes as it plans then.
398
+ **The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
396
399
 
397
400
  ## Schedules
398
401
 
data/docs/sub-agent.md CHANGED
@@ -34,6 +34,15 @@ answers wake chi in a short loop (fix or disagree, send again) until it says
34
34
  or after `context.peer_turns` turns: [Waking: peer
35
35
  sources](context.md#peer-sources-the-peer-loop).
36
36
 
37
+ A client with no chi of its own (an iOS Shortcut, a script) can do the same
38
+ over HTTP: one `POST …/ask` to chi web, then a wait token until the answer
39
+ comes ([Thin clients](thin-clients.md)). An agent uses `chi send` and `chi
40
+ answer` (with `--remote NAME` for another machine) whenever it can run chi.
41
+ Over HTTP it must send `"client_id": "cli:send"` on an ask and
42
+ `"client_id": "cli:answer"` on an answer: without them its lines are the
43
+ owner's and `guardrails.parent_answers` does not hold them ([An agent over
44
+ HTTP](thin-clients.md#an-agent-over-http)).
45
+
37
46
  ## The commands
38
47
 
39
48
  ```sh
data/docs/testing.md CHANGED
@@ -376,7 +376,8 @@ see [internals/bridge.md](internals/bridge.md)). A spec that writes its own requ
376
376
  socket) names it too: `include BridgeAuth` (spec/support/bridge_auth.rb, required by the spec that needs it) gives
377
377
  `bridge_auth(session_dir_or_sidecar)`, the header as a Hash, and `bridge_auth_line(...)` for a raw request; or read
378
378
  `port` and `secret` from the sidecar in one go, as `WorkerLink.client` does. A client made with `BridgeClient.new`
379
- takes `secret:` (nil for a fake Bridge that doesn't check it).
379
+ takes `secret:` (nil for a fake Bridge that doesn't check it). A spec that builds a Bridge passes the Engine's parts
380
+ with `include BridgeParts` (spec/support/bridge_parts.rb): `Bridge.new(engine: engine, **bridge_parts(engine), …)`.
380
381
 
381
382
  ### Support files
382
383
 
@@ -387,6 +388,7 @@ any other file requires it, so a spec file run alone still finds its requires. E
387
388
  |---|---|
388
389
  | `bounded_capture.rb` | `BoundedCapture.capture3`: `Open3.capture3` with a deadline, in its own process group killed on expiry |
389
390
  | `bridge_auth.rb` | `BridgeAuth`: the Bridge secret's header for a hand-written request (above) |
391
+ | `bridge_parts.rb` | `BridgeParts`: `bridge_parts(engine)`, a real Engine's event log, turn state, question desk and steer cut for `Bridge.new`; `idle_engine_parts`, real idle ones for the Worker specs' `instance_double(Samagotchi::Engine, …)` only |
390
392
  | `chi_cli.rb` | *helper*: `run_chi` (bin/chi in a child process), `fork_chi` (in a fork: no Ruby boot), `isolated_chi_env` |
391
393
  | `effective_model_configs.rb` | `EffectiveModelConfigs`: one config.yml holding every host the effective-model characterization pins, and its goldens |
392
394
  | `env.rb` | *helper*: `with_env` sets ENV for a block and puts it back (nil unsets) |
@@ -0,0 +1,146 @@
1
+ # Thin clients
2
+
3
+ A thin client is anything small that talks to chi web over HTTP: an iOS
4
+ Shortcut, a shell script, a watch app. It sends a message to a session and gets
5
+ the answer back, without running chi itself. The session is an ordinary one:
6
+ you can watch it in `chi web` while the client talks to it.
7
+
8
+ Every call below is the owner's: it needs chi web's access token, the same one
9
+ `chi remote add` takes (the part of chi web's LAN link after `token=`, or its
10
+ `$XDG_STATE_HOME/samagotchi/web-token` file), sent as
11
+ `Authorization: Bearer <token>`. To reach chi web from your phone outside the
12
+ LAN, use [Tailscale Serve](configuration.md#tailscale-serve-your-tailnet) or
13
+ an [auth proxy](configuration.md#behind-an-auth-proxy) (`web.public_url`).
14
+ A client holding the token can do anything you can do in chi web, so keep it
15
+ safe.
16
+
17
+ Check that chi web has these routes first: `GET /api/info` lists `"ask"` in
18
+ its `features`. An older chi web lacks it (and answers 404 for `/ask`): update
19
+ chi there (`chi update`).
20
+
21
+ ## Ask
22
+
23
+ ```sh
24
+ T=$(cat ~/.local/state/samagotchi/web-token)
25
+ curl -s -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
26
+ -X POST http://192.168.1.29:4567/api/sessions/3fa2/ask -d '{"prompt": "what changed today?"}'
27
+ # {"status": "done", "session_id": "3fa2…", "text": "…", "turn_id": "…", …}
28
+ ```
29
+
30
+ The id can be a prefix. A continued session's message goes to the newest link
31
+ of its chain; `session_id` is where it ran, and `asked` is the id you gave when
32
+ another link ran it. Body fields:
33
+
34
+ - `prompt` (required): the message, at most 16 KiB. A terminal-only command such
35
+ as `/stats` is refused (400 `local_command`); a session command such as
36
+ `/model x` runs and answers `{"status": "command"}`, with no token. That
37
+ holds for `/continue yes` too, although it starts a turn: the worker's answer
38
+ to a command doesn't name that turn, so there is nothing to wait on. A
39
+ continue offered as a question (an answer's `waiting_for_answer`, or 409
40
+ `waiting`) is better answered through `/answer` with `wait` (below), which
41
+ follows the turn.
42
+ - `timeout`: seconds to wait for the answer, at most 30 (the default).
43
+ - `queue`: `true` (the default) means a session running a turn queues your
44
+ message as its own turn, and you get that turn's answer. `false` refuses a
45
+ running session with 409 `busy`.
46
+ - `client_id`: who is asking. Leave it out for yourself (the line is the
47
+ owner's, as from the web composer). An agent sends `"cli:send"`: see
48
+ [An agent over HTTP](#an-agent-over-http).
49
+
50
+ A question that is waiting for an answer refuses the ask with 409 `waiting` and
51
+ the `question`. Answer it first (below).
52
+
53
+ ## When the answer takes longer
54
+
55
+ Each call answers within **35 seconds** of its request, whatever it waits for
56
+ (a continue in flight, a worker starting, the answer), so a proxy or a Shortcut
57
+ with a 60 s limit is safe. The one exception is a worker that hangs while it
58
+ takes the message in: chi web gives it up to 25 s more, then answers 504
59
+ `worker_timeout`. A turn still running then answers
60
+ `"status": "timeout"` with a `"token": "w1.…"`. Send that token back until the
61
+ status is something else:
62
+
63
+ ```sh
64
+ curl -s -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
65
+ -X POST http://192.168.1.29:4567/api/sessions/<session_id>/wait -d '{"token": "w1.…"}'
66
+ ```
67
+
68
+ That is the whole protocol: one string to carry and no order to get wrong. A
69
+ token is for its own session only (400 `invalid_wait` for another's); the id
70
+ in the URL can be a prefix of it.
71
+
72
+ ## The answers
73
+
74
+ `status` is one of:
75
+
76
+ - `done`: `text` is the reply.
77
+ - `waiting_for_answer`: the turn asks something. `question` has its `id`,
78
+ `question` and `options`.
79
+ - `no_reply`: the turn ended without a reply. `outcome` says how (`failed`,
80
+ `canceled`, `exhausted`, …).
81
+ - `timeout`: still running. Wait with the `token`.
82
+ - `error`, `stopped`, `worker_gone`: the session's worker failed or went away.
83
+
84
+ ## Answering a question
85
+
86
+ ```sh
87
+ curl -s -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
88
+ -X POST http://192.168.1.29:4567/api/sessions/<session_id>/answer \
89
+ -d '{"id": "<question id>", "selected": ["Yes"], "wait": 30}'
90
+ # {"status": "answered", "session_id": "…", "id": "…", "reply": {"status": "done", "text": "…"}}
91
+ ```
92
+
93
+ With `wait`, the answer also waits for what comes next. `reply` holds the same
94
+ fields as an ask's answer, with a `token` while the turn is still running. If
95
+ someone answered the question first, you get `"status": "not_pending"` and
96
+ `reply` holds what came after their answer.
97
+
98
+ The answer goes in before the wait starts, so a wait that fails afterwards
99
+ (chi web stopping, the session deleted meanwhile) still answers 200 with your
100
+ `status`, and a `wait_error` (`error`: `server_stopping`, `not_found` or
101
+ `wait_failed`, and a `detail`) in place of `reply`. Don't answer again (that
102
+ would be 409): ask or wait on the session instead.
103
+
104
+ ## An agent over HTTP
105
+
106
+ An agent (Claude Code, Codex, a script acting on its own) should drive chi
107
+ with `chi send --wait` and `chi answer` first, and `chi --remote NAME` for
108
+ another machine's chi web ([chi as a sub-agent](sub-agent.md)): they name
109
+ the sender for it. An MCP host can add chi as an MCP server instead
110
+ ([chi as an MCP server](mcp-server.md): `chi mcp serve`, or `POST /api/mcp`
111
+ on chi web), which names it too. An agent that calls these routes itself must name itself
112
+ the same way:
113
+
114
+ - `"client_id": "cli:send"` on every ask (and on `POST /api/sessions`);
115
+ - `"client_id": "cli:answer"` on every answer.
116
+
117
+ Then `guardrails.parent_answers` applies as it does to `chi send` and `chi
118
+ answer` ([Answers from a parent agent](guardrails.md#answers-from-a-parent-agent)):
119
+ a `/continue yes` is held to it (403 `parent_continue_refused`), a
120
+ `/parent-answers` that loosens it is refused (403 `parent_answers_refused`),
121
+ and the worker checks an answer's option (403 `parent_answer_refused`).
122
+ Without a `client_id`, the ask and the answer are the owner's (`web:unnamed`)
123
+ and none of this holds: the token can do anything you can. It is a
124
+ convention for an honest agent, not a barrier, so tell your agent to send it.
125
+
126
+ ## A new session
127
+
128
+ `POST /api/sessions {"prompt": "…", "dir": "/Users/me/projects/app"}` starts a
129
+ session. Its 201 carries a `token`: `POST /api/sessions/<id>/wait {"token": …}`
130
+ answers the first turn.
131
+
132
+ ## iOS Shortcut recipe
133
+
134
+ 1. **Dictate Text** (or **Ask for Input**).
135
+ 2. **Get Contents of URL**: `https://<your chi web>/api/sessions/<id>/ask`,
136
+ method POST, header `Authorization: Bearer <token>`, JSON body `prompt` =
137
+ the dictated text.
138
+ 3. **Repeat** while the answer's `status` is `timeout`: **Get Contents of URL**
139
+ for `…/api/sessions/<session_id>/wait` with the JSON body `token` = the
140
+ answer's `token`.
141
+ 4. **Get Dictionary Value** `text`, then **Speak Text**.
142
+
143
+ For running chi from another agent instead (`chi send --wait`, `chi answer`),
144
+ see [chi as a sub-agent](sub-agent.md). The routes in full are in
145
+ [architecture.md](architecture.md) (chi web's routes for the session
146
+ commands).
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "block_fix/stamp"
3
4
  require_relative "log"
4
5
 
5
6
  module Samagotchi
@@ -25,8 +26,8 @@ module Samagotchi
25
26
  # The same object when it has none.
26
27
  # An empty-answer note's marker (TurnNote::EMPTY_ANSWER) and the
27
28
  # answer's refs (AnswerRefs::KEY, display_refs) are display only too:
28
- # they go the same way.
29
- DISPLAY_ONLY = [KEY.to_s, "empty_answer", "display_refs"].freeze
29
+ # they go the same way, and so does a block fix's stamp (BlockFix::STAMP).
30
+ DISPLAY_ONLY = [KEY.to_s, "empty_answer", "display_refs", BlockFix::STAMP.to_s].freeze
30
31
 
31
32
  def self.strip(message)
32
33
  return message unless message.is_a?(Hash) && DISPLAY_ONLY.any? { |key| message.key?(key.to_sym) || message.key?(key) }
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Samagotchi
6
+ # BlockFix's stamp on an answer's model message, apart from the rest so the
7
+ # loops' allowlists (ChatLoop#plain, KernelLoop#sanitize_history) and
8
+ # AnswerDisplay can name it without loading the request's side.
9
+ module BlockFix
10
+ # The answer message's display-only key (AnswerDisplay::DISPLAY_ONLY):
11
+ # a list of {key:, fixed_key:, state:, reason:, at:}, one per block asked.
12
+ STAMP = :block_fixes
13
+ STATES = %w[fixed failed].freeze
14
+
15
+ module_function
16
+
17
+ # The answer message's stamp entries, with symbol keys (they come back
18
+ # from disk with string keys).
19
+ # @return [Array<Hash>]
20
+ def stamps(message)
21
+ return [] unless message.is_a?(Hash)
22
+
23
+ list = message[STAMP] || message[STAMP.to_s]
24
+ Array(list).filter_map do |entry|
25
+ next unless entry.is_a?(Hash)
26
+
27
+ entry.to_h { |k, v| [k.to_sym, v] }
28
+ end
29
+ end
30
+
31
+ # The stamp entry that knows the block +key+ (by its key or its fixed
32
+ # key), nil when none does.
33
+ def stamp_for(message, key)
34
+ stamps(message).find { |entry| entry[:key] == key || entry[:fixed_key] == key }
35
+ end
36
+
37
+ # A copy of +message+ with +entry+ added to a fresh stamp list.
38
+ def with_stamp(message, entry)
39
+ list = stamps(message).reject { |old| old[:key] == entry[:key] } + [entry]
40
+ copy = message.reject { |k, _| k.to_s == STAMP.to_s }
41
+ copy.merge(STAMP => list)
42
+ end
43
+
44
+ # One stamp entry.
45
+ def entry(key:, state:, fixed_key: nil, reason: nil, at: Time.now)
46
+ { key: key, fixed_key: fixed_key, state: state, reason: reason, at: at.utc.iso8601 }.compact
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "time"
5
+ require_relative "block_fix/stamp"
6
+ require_relative "block_renderers"
7
+ require_relative "inline_widgets"
8
+ require_relative "markdown_parser"
9
+ require_relative "plugin/side_question"
10
+
11
+ module Samagotchi
12
+ # A fenced block the page couldn't draw in the newest answer, asked for
13
+ # again once (docs/internals/block-renderers.md, A failed block is asked
14
+ # for again): where the block is in an answer's markdown, the side request
15
+ # that asks for it again, and the checks on what came back. Pure Ruby: the
16
+ # Engine's BlockFixPart runs the request and writes the conversation.
17
+ module BlockFix
18
+ # The side line's kind (SideUsage) and the asking source.
19
+ SOURCE = "block-fix"
20
+ # The Bridge feature (Bridge::FEATURES) a page checks before it asks.
21
+ FEATURE = "block_fix"
22
+ # IdleClient may retry a refused thinking setting: up to three requests.
23
+ TIMEOUT_SECONDS = 25
24
+ MAX_TOKENS = 6000
25
+ MAX_SOURCE_BYTES = 16 * 1024
26
+ # How much of the drawer's error goes into the request (model-influenced
27
+ # text, in the user part only).
28
+ MAX_REASON_CHARS = 300
29
+ # Asks in flight per Engine at once.
30
+ MAX_RUNNING = 2
31
+ # Blocks asked for per answer, ever (its stamp and its asks in flight).
32
+ PER_ANSWER = 2
33
+
34
+ # The route's refusals (one message per condition), by reason code.
35
+ REFUSALS = {
36
+ block_too_large: "the block is over #{MAX_SOURCE_BYTES / 1024} KB",
37
+ block_not_found: "that block isn't in the turn's answer",
38
+ fix_busy: "#{MAX_RUNNING} fixes are being asked for already",
39
+ fix_limit: "#{PER_ANSWER} blocks of this answer were asked for already",
40
+ fix_unavailable: "this session can't ask for a fix"
41
+ }.freeze
42
+
43
+ SYSTEM = "The last answer in the conversation below holds a fenced block a program could not draw. Answer " \
44
+ "with the corrected block only, in one fence of the same language, and nothing else. Keep what it " \
45
+ "shows and every id, label, option and text it has, unless the error requires a change."
46
+
47
+ # Where a block is in an answer's text: the body's lines (0-based, both
48
+ # ends inclusive; +last+ is first - 1 for an empty body) and the indent
49
+ # its lines have there (a list item's).
50
+ Place = Data.define(:first, :last, :indent)
51
+
52
+ # What #extract read from the model's answer: the fixed source, or why
53
+ # it is refused.
54
+ Extracted = Data.define(:source, :refusal) do
55
+ def ok? = refusal.nil?
56
+ end
57
+
58
+ module_function
59
+
60
+ # The block's identity: the first 32 hex characters of SHA-256 over the
61
+ # language and the normalised source.
62
+ def key(lang, source)
63
+ Digest::SHA256.hexdigest("#{lang}\0#{normalize(source)}")[0, 32]
64
+ end
65
+
66
+ # +source+ with \r\n and \r as \n and one trailing newline removed.
67
+ def normalize(source)
68
+ source.to_s.gsub(/\r\n?/, "\n").delete_suffix("\n")
69
+ end
70
+
71
+ # Whether #locate can parse (commonmarker is installed).
72
+ def available? = MarkdownParser.available?
73
+
74
+ # The first code block of +text+ in +lang+ whose source is +source+, as
75
+ # commonmarker (the page's render's parser) reads it; nil when there is
76
+ # none, or it sits in a blockquote (its lines carry "> ").
77
+ # @return [Place, nil]
78
+ def locate(text, lang:, source:) = locate_all(text, lang: lang, source: source).first
79
+
80
+ # Every such block of +text+, in order (an answer may repeat one: a fix
81
+ # patches every copy, so none is asked for again).
82
+ # @return [Array<Place>]
83
+ def locate_all(text, lang:, source:)
84
+ return [] unless available?
85
+
86
+ text = text.to_s
87
+ want = normalize(source)
88
+ lines = text.lines
89
+ places = []
90
+ each_code_block(text) do |node|
91
+ next unless language_of(node.fence_info) == lang.to_s && normalize(node.string_content) == want
92
+ next if in_blockquote?(node)
93
+
94
+ place = place_of(node, lines)
95
+ places << place if place
96
+ end
97
+ places
98
+ end
99
+
100
+ # +text+ with every block at +places+ holding +fixed+ (#replace from
101
+ # the last, so the earlier places' lines stay where they were).
102
+ def replace_all(text, places, fixed)
103
+ places.sort_by(&:first).reverse.reduce(text.to_s) { |out, place| replace(out, place, fixed) }
104
+ end
105
+
106
+ # +text+ with the block at +place+ holding +fixed+: the fence lines kept,
107
+ # each new line given the old body's indent, the text's own line ends.
108
+ def replace(text, place, fixed)
109
+ lines = text.to_s.lines
110
+ eol = text.to_s.include?("\r\n") ? "\r\n" : "\n"
111
+ body = normalize(fixed).split("\n", -1).map { |line| line.empty? ? eol : "#{place.indent}#{line}#{eol}" }
112
+ before = lines[0...place.first]
113
+ # A body at the very end without a line end (an unclosed fence) keeps none.
114
+ after = lines[(place.last + 1)..] || []
115
+ body[-1] = body[-1].delete_suffix(eol) if after.empty? && !lines.last.to_s.end_with?("\n") && body.any?
116
+ (before + body + after).join
117
+ end
118
+
119
+ # What Engine#ask_side_model takes: the conversation up to and including
120
+ # the answer as a transcript, then the failed block and its error.
121
+ # @param messages [Array<Hash>] the conversation, display-only keys gone
122
+ # @return [Array<Hash>]
123
+ def request(messages:, lang:, source:, reason:)
124
+ system = lang.to_s == InlineWidgets::LANG ? "#{SYSTEM}\n\n#{InlineWidgets::FIX_RULES}" : SYSTEM
125
+ Plugin::SideQuestion.request(messages: messages, prompt: prompt(lang, source, reason), system: system)
126
+ end
127
+
128
+ # The question: the language, the error and the block.
129
+ def prompt(lang, source, reason)
130
+ body = normalize(source)
131
+ fence = "`" * [3, (body.scan(/`+/).map(&:length).max || 0) + 1].max
132
+ error = reason.to_s.strip[0, MAX_REASON_CHARS]
133
+ "The #{lang} block below, from your last answer, could not be drawn.\nError: #{error}\n\n" \
134
+ "#{fence}#{lang}\n#{body}\n#{fence}\n\nAnswer with the corrected block only, in one #{lang} fence."
135
+ end
136
+
137
+ # The fixed source in the model's +text+: the first fenced block, else
138
+ # the whole answer when it has no fence.
139
+ # @param cut_off [Boolean] the answer stopped at its token limit
140
+ # @param failed [String] the source that failed
141
+ # @return [Extracted]
142
+ def extract(text, cut_off:, failed:)
143
+ return Extracted.new(source: nil, refusal: "the fix was cut off") if cut_off
144
+
145
+ source = normalize(first_fence(text.to_s) || text.to_s.strip)
146
+ return Extracted.new(source: nil, refusal: "the fix was empty") if source.strip.empty?
147
+ return Extracted.new(source: nil, refusal: "the fix was the same block") if source == normalize(failed)
148
+ if source.bytesize > MAX_SOURCE_BYTES
149
+ return Extracted.new(source: nil, refusal: "the fix is over #{MAX_SOURCE_BYTES / 1024} KB")
150
+ end
151
+
152
+ Extracted.new(source: source, refusal: nil)
153
+ end
154
+
155
+ # nil when +source+ may be tried, else the reason: a chi-ui block must
156
+ # parse; any other language passes (only the page can draw it).
157
+ def check(lang:, source:)
158
+ return nil unless lang.to_s == InlineWidgets::LANG
159
+
160
+ InlineWidgets.parse(source).error
161
+ end
162
+
163
+ def each_code_block(text, &)
164
+ return unless text.include?("```") || text.include?("~~~")
165
+
166
+ nodes = []
167
+ Commonmarker.parse(text, options: { extension: { header_ids: nil } }).walk do |node|
168
+ nodes << node if node.type == :code_block
169
+ end
170
+ nodes.each(&)
171
+ end
172
+
173
+ def language_of(info)
174
+ word = info.to_s.split.first.to_s.downcase
175
+ word if word.match?(BlockRenderers::LANG)
176
+ end
177
+
178
+ def in_blockquote?(node)
179
+ parent = node.parent
180
+ while parent
181
+ return true if parent.type == :block_quote
182
+
183
+ parent = parent.parent
184
+ end
185
+ false
186
+ end
187
+
188
+ # The body's line range and indent from the node's source position; nil
189
+ # for an indented code block (no fence line).
190
+ def place_of(node, lines)
191
+ pos = node.source_position
192
+ start = pos[:start_line] - 1
193
+ fence_line = lines[start].to_s
194
+ column = pos[:start_column] - 1
195
+ fence = fence_line[column..].to_s[/\A(`{3,}|~{3,})/]
196
+ return nil unless fence
197
+
198
+ prefix = fence_line[0, column]
199
+ indent = prefix.match?(/\A[ \t]*\z/) ? prefix : " " * prefix.length
200
+ last = pos[:end_line] - 1
201
+ last -= 1 if last > start && closing?(lines[last].to_s, fence)
202
+ Place.new(first: start + 1, last: last, indent: indent)
203
+ end
204
+
205
+ def closing?(line, fence)
206
+ mark = line.strip[/\A(`{3,}|~{3,})\z/]
207
+ !mark.nil? && mark[0] == fence[0] && mark.length >= fence.length
208
+ end
209
+
210
+ def first_fence(text)
211
+ return nil unless available?
212
+
213
+ lines = text.lines
214
+ each_code_block(text) do |node|
215
+ return node.string_content if place_of(node, lines)
216
+ end
217
+ nil
218
+ end
219
+ end
220
+ end