samagotchi 0.182.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  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 +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
data/docs/sessions.md CHANGED
@@ -51,9 +51,9 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
51
51
 
52
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.
53
53
 
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'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.
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.
55
55
 
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 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.
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.
57
57
 
58
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)).
59
59
 
@@ -394,7 +394,7 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
394
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.
395
395
  - **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
396
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.
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**: today the page sends only `stop_tasks=true`; it does not send `tasks=<id,id>` yet. The server accepts `tasks` only as a list of task/session ids to stop: for delete it accepts the query parameter `tasks=<id,id>`, and for archive it accepts `"tasks": [ids]` in the body. In both routes `tasks` works only with `stop_tasks` (`true`/`stop_tasks=true`); without `stop_tasks` it is ignored. `stop_tasks` without `tasks` takes every running task the operation can stop. Today a plain tap uses `stop_tasks` without `tasks`, so it stops whatever runs; the delete sheet's page phase that carries named ids will send `tasks=<id,id>` for the choice's running ids (and `tasks=` when it has only unverified or unreadable records, which a stop never signals). 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.
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
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.
399
399
 
400
400
  ## Schedules
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).
@@ -4,11 +4,12 @@ require "json"
4
4
  require "fileutils"
5
5
  require_relative "../atomic_file"
6
6
  require_relative "../events"
7
+ require_relative "card_wait"
7
8
 
8
9
  module Samagotchi
9
10
  class Bridge
10
- # The running turn's open card with actions (check-in's Nudge / Keep
11
- # going / Stop) as a file in the session's folder, pending_card.json
11
+ # The running turn's open card with command actions (check-in's Nudge /
12
+ # Keep going / Stop; a url action alone doesn't ask, CardWait) as a file in the session's folder, pending_card.json
12
13
  # {id:, bundle:}, for `chi web`'s session hub: it watches files, not
13
14
  # workers, and a tab behind notifies from its summary (notify.js), as
14
15
  # for a pending question. A persistent observer, like CardStore.
@@ -63,7 +64,7 @@ module Samagotchi
63
64
  end
64
65
 
65
66
  def card(event)
66
- asks = Array(event[:actions]).any?
67
+ asks = Array(event[:actions]).any? { |action| CardWait.command?(action) }
67
68
  if event[:in_turn] && asks
68
69
  write(event[:id].to_s, event[:source].to_s)
69
70
  elsif @id && event[:id].to_s == @id
@@ -12,7 +12,7 @@ module Samagotchi
12
12
  # Per-connection SSE writer.
13
13
  #
14
14
  # This object doubles as the per-connection live observer wired into the
15
- # Engine via `Engine#subscribe`: its `#call` is invoked synchronously from
15
+ # event log via `SessionObserver#subscribe`: its `#call` is invoked synchronously from
16
16
  # `Engine#emit_event` inside the turn thread, so it must be strictly
17
17
  # non-blocking — it only enqueues onto a bounded queue and returns. A
18
18
  # dedicated writer thread (the connection's own thread) drains the queue
@@ -45,7 +45,7 @@ module Samagotchi
45
45
  # Queued by the hang-up watcher (#watch_hangup) to wake #drain!.
46
46
  HANGUP = Object.new.freeze
47
47
 
48
- # @param engine [Samagotchi::Engine] the owning engine (live fan-out)
48
+ # @param event_log [Samagotchi::SessionObserver] the Engine's event log (live fan-out)
49
49
  # @param ring [Samagotchi::Bridge::RingBuffer] shared capture buffer
50
50
  # @param session_id [String]
51
51
  # @param last_event_id [String, nil] reconnect cursor (or ?from_seq=):
@@ -58,23 +58,24 @@ module Samagotchi
58
58
  # to just the event_seq.
59
59
  # @param join_with_snapshot [Boolean] start with a snapshot frame rather
60
60
  # than a replay
61
- # @param bridge [Samagotchi::Bridge, nil] for stop signalling
61
+ # @param stopped [#call, nil] whether the stream should end (the
62
+ # Bridge's #stopped?): asked when an idle wait ends
62
63
  # @param max_queue [Integer] bounded-queue capacity
63
64
  # @param heartbeat_interval [Float] idle-seconds between `: ping` frames
64
65
  # @param raw [Boolean] write events as the engine emitted them, not as
65
66
  # clients get them (ClientEvent): `?raw=1`, for debugging
66
- def initialize(engine:, ring:, session_id:, last_event_id: nil, epoch: nil,
67
- frame_provider: nil, join_with_snapshot: false, bridge: nil,
67
+ def initialize(event_log:, ring:, session_id:, last_event_id: nil, epoch: nil,
68
+ frame_provider: nil, join_with_snapshot: false, stopped: nil,
68
69
  max_queue: DEFAULT_MAX_QUEUE,
69
70
  heartbeat_interval: DEFAULT_HEARTBEAT_INTERVAL, raw: false)
70
- @engine = engine
71
+ @event_log = event_log
71
72
  @ring = ring
72
73
  @session_id = session_id
73
74
  @last_event_id = last_event_id
74
75
  @epoch = epoch
75
- @frame_provider = frame_provider || -> { { snapshot: { event_seq: @engine.event_count }, session_state_snapshot: {} } }
76
+ @frame_provider = frame_provider || -> { { snapshot: { event_seq: @event_log.event_count }, session_state_snapshot: {} } }
76
77
  @join_with_snapshot = join_with_snapshot
77
- @bridge = bridge
78
+ @stopped = stopped
78
79
  @max_queue = max_queue
79
80
  @heartbeat_interval = heartbeat_interval
80
81
  @raw = raw
@@ -110,16 +111,16 @@ module Samagotchi
110
111
  begin
111
112
  if @join_with_snapshot
112
113
  # Subscribe and snapshot as one step of the event log, then go live.
113
- frame = @engine.synchronize_events do
114
- @handle = @engine.subscribe(observer: self)
114
+ frame = @event_log.synchronize do
115
+ @handle = @event_log.subscribe(observer: self)
115
116
  take_snapshot
116
117
  end
117
118
  write_snapshot_frame(io, :snapshot, frame)
118
119
  else
119
120
  # (1) subscribe the live queue FIRST.
120
- @handle = @engine.subscribe(observer: self)
121
+ @handle = @event_log.subscribe(observer: self)
121
122
  # (2) capture the snapshot sequence.
122
- snapshot_seq = @engine.event_count
123
+ snapshot_seq = @event_log.event_count
123
124
  # (3) replay buffered (from_seq, snapshot].
124
125
  replay!(io, snapshot_seq)
125
126
  end
@@ -128,7 +129,7 @@ module Samagotchi
128
129
  rescue Errno::EPIPE, Errno::ECONNRESET, IOError
129
130
  # Client hung up; nothing to do.
130
131
  ensure
131
- @engine.unsubscribe(handle: @handle) if @handle
132
+ @event_log.unsubscribe(handle: @handle) if @handle
132
133
  watcher&.kill
133
134
  end
134
135
  end
@@ -198,7 +199,7 @@ module Samagotchi
198
199
  # behind; nudge a reconnect rather than flooding more events.
199
200
  emit_reset(io) if @queue.overflow_dropped?
200
201
  @queue.clear_overflow!
201
- elsif @bridge&.stopped?
202
+ elsif @stopped&.call
202
203
  break
203
204
  else
204
205
  write_heartbeat(io)
@@ -258,7 +259,7 @@ module Samagotchi
258
259
  # Emit a control frame carrying the current snapshot so a client that
259
260
  # cannot replay can re-derive state, then continue live.
260
261
  def emit_reset(io)
261
- write_snapshot_frame(io, :reset, @engine.synchronize_events { take_snapshot })
262
+ write_snapshot_frame(io, :reset, @event_log.synchronize { take_snapshot })
262
263
  end
263
264
 
264
265
  # With the event log held: the snapshot frame's content (the snapshot