samagotchi 0.182.0 → 0.184.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +22 -11
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +4 -2
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +14 -6
  12. data/docs/internals/bundles.md +26 -5
  13. data/docs/internals/engine.md +20 -9
  14. data/docs/internals/participants.md +1 -1
  15. data/docs/internals/prompt-caching.md +8 -1
  16. data/docs/internals/remote-sessions.md +40 -5
  17. data/docs/internals/web-frontend.md +96 -31
  18. data/docs/internals/web-push.md +11 -0
  19. data/docs/internals/working-set.md +239 -7
  20. data/docs/mcp-server.md +84 -0
  21. data/docs/memory.md +2 -1
  22. data/docs/plugins.md +309 -22
  23. data/docs/scheduling.md +14 -0
  24. data/docs/sessions.md +4 -4
  25. data/docs/sub-agent.md +9 -0
  26. data/docs/testing.md +3 -1
  27. data/docs/thin-clients.md +165 -0
  28. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  29. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  30. data/lib/samagotchi/bridge.rb +59 -68
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  33. data/lib/samagotchi/bundle_command/check.rb +55 -20
  34. data/lib/samagotchi/bundle_command.rb +50 -21
  35. data/lib/samagotchi/bundle_manifest.rb +105 -4
  36. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  37. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  38. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  39. data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
  40. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  41. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  42. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  43. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  44. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  45. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  46. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  47. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  48. data/lib/samagotchi/command_intake.rb +7 -0
  49. data/lib/samagotchi/commands/registry.rb +8 -3
  50. data/lib/samagotchi/continue_offer.rb +24 -15
  51. data/lib/samagotchi/engine/block_fix.rb +4 -4
  52. data/lib/samagotchi/engine/cards.rb +14 -5
  53. data/lib/samagotchi/engine/events.rb +10 -15
  54. data/lib/samagotchi/engine/models.rb +1 -1
  55. data/lib/samagotchi/engine/plugins.rb +3 -0
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/session.rb +14 -6
  58. data/lib/samagotchi/engine/side_requests.rb +1 -1
  59. data/lib/samagotchi/engine/sign_in.rb +142 -0
  60. data/lib/samagotchi/engine/turn_end.rb +3 -3
  61. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  62. data/lib/samagotchi/engine.rb +43 -27
  63. data/lib/samagotchi/engine_snapshots.rb +1 -1
  64. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  65. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  66. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  67. data/lib/samagotchi/hold_stop.rb +4 -4
  68. data/lib/samagotchi/idle_recap.rb +19 -11
  69. data/lib/samagotchi/idle_reminders.rb +7 -5
  70. data/lib/samagotchi/idle_scheduler.rb +7 -10
  71. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  72. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  73. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  74. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  75. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  76. data/lib/samagotchi/llm/http.rb +96 -5
  77. data/lib/samagotchi/mcp_command.rb +110 -0
  78. data/lib/samagotchi/mcp_server/http.rb +112 -0
  79. data/lib/samagotchi/mcp_server/protocol.rb +263 -0
  80. data/lib/samagotchi/mcp_server/stdio.rb +93 -0
  81. data/lib/samagotchi/mcp_server/text.rb +155 -0
  82. data/lib/samagotchi/mcp_server/tools.rb +246 -0
  83. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  84. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  85. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  86. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  87. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  88. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  89. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  90. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  91. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  92. data/lib/samagotchi/model_notes.rb +34 -12
  93. data/lib/samagotchi/plugin/api.rb +6 -1
  94. data/lib/samagotchi/plugin/card.rb +36 -11
  95. data/lib/samagotchi/plugin/context.rb +63 -6
  96. data/lib/samagotchi/plugin/http.rb +40 -15
  97. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  98. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  99. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  100. data/lib/samagotchi/plugin/loader.rb +18 -11
  101. data/lib/samagotchi/plugin/secrets.rb +266 -0
  102. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  103. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  104. data/lib/samagotchi/prompt_files.rb +11 -4
  105. data/lib/samagotchi/prompt_layout.rb +88 -0
  106. data/lib/samagotchi/prompt_part.rb +82 -20
  107. data/lib/samagotchi/queued_command.rb +28 -4
  108. data/lib/samagotchi/recap_setup.rb +13 -4
  109. data/lib/samagotchi/ref.rb +3 -2
  110. data/lib/samagotchi/relay_verifier.rb +8 -7
  111. data/lib/samagotchi/relay_watcher.rb +4 -4
  112. data/lib/samagotchi/reply_wait.rb +6 -3
  113. data/lib/samagotchi/run_options.rb +2 -1
  114. data/lib/samagotchi/schedule_command.rb +18 -4
  115. data/lib/samagotchi/schedules.rb +40 -8
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +285 -0
  118. data/lib/samagotchi/session_access/contract.rb +5 -0
  119. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  120. data/lib/samagotchi/session_access/exchange.rb +176 -0
  121. data/lib/samagotchi/session_access/local.rb +34 -6
  122. data/lib/samagotchi/session_access/remote.rb +4 -1
  123. data/lib/samagotchi/session_command_catalog.rb +10 -0
  124. data/lib/samagotchi/session_commands.rb +17 -0
  125. data/lib/samagotchi/session_config.rb +4 -4
  126. data/lib/samagotchi/session_inbox.rb +15 -0
  127. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  128. data/lib/samagotchi/session_observer.rb +27 -0
  129. data/lib/samagotchi/steer_cut.rb +4 -3
  130. data/lib/samagotchi/system_prompt.rb +196 -161
  131. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  132. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  133. data/lib/samagotchi/testing/boundary.rb +4 -0
  134. data/lib/samagotchi/testing/bundle.rb +48 -2
  135. data/lib/samagotchi/testing/fake_http.rb +60 -15
  136. data/lib/samagotchi/testing/host.rb +4 -1
  137. data/lib/samagotchi/testing/recorder.rb +45 -5
  138. data/lib/samagotchi/tools/memory.rb +11 -3
  139. data/lib/samagotchi/tools/tool_index.rb +14 -3
  140. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  141. data/lib/samagotchi/version.rb +1 -1
  142. data/lib/samagotchi/web/app.rb +9 -8
  143. data/lib/samagotchi/web/ask_routes.rb +362 -0
  144. data/lib/samagotchi/web/mcp_route.rb +91 -0
  145. data/lib/samagotchi/web/public/app.js +2 -3
  146. data/lib/samagotchi/web/public/block_frame.js +72 -11
  147. data/lib/samagotchi/web/public/block_host.js +44 -8
  148. data/lib/samagotchi/web/public/block_regions.js +126 -0
  149. data/lib/samagotchi/web/public/card.js +22 -9
  150. data/lib/samagotchi/web/public/card_actions.js +21 -0
  151. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  152. data/lib/samagotchi/web/public/card_registry.js +3 -2
  153. data/lib/samagotchi/web/public/data.js +15 -12
  154. data/lib/samagotchi/web/public/delete_sheet.js +231 -169
  155. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  156. data/lib/samagotchi/web/public/format.js +3 -0
  157. data/lib/samagotchi/web/public/index.html +52 -7
  158. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  159. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  160. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  161. data/lib/samagotchi/web/public/refs.js +5 -3
  162. data/lib/samagotchi/web/public/region_hit.js +144 -0
  163. data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
  164. data/lib/samagotchi/web/public/running_tasks.js +3 -17
  165. data/lib/samagotchi/web/public/session_actions.js +96 -100
  166. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  167. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  168. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  169. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  170. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  171. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  172. data/lib/samagotchi/web/push/notifier.rb +33 -6
  173. data/lib/samagotchi/web/server.rb +1 -1
  174. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  175. data/lib/samagotchi/web/session_control.rb +31 -9
  176. data/lib/samagotchi/web/session_create.rb +2 -2
  177. data/lib/samagotchi/web/session_hub.rb +26 -4
  178. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  179. data/lib/samagotchi/worker/child_side.rb +3 -2
  180. data/lib/samagotchi/worker/command_queue.rb +13 -13
  181. data/lib/samagotchi/worker/leave.rb +3 -3
  182. data/lib/samagotchi/worker/scratch.rb +6 -6
  183. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  184. data/lib/samagotchi/worker/startup.rb +3 -3
  185. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  186. data/lib/samagotchi/worker.rb +32 -21
  187. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  188. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  189. data/lib/samagotchi/worker_inbound.rb +12 -7
  190. data/lib/samagotchi/worker_link.rb +2 -2
  191. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  192. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  193. data/lib/samagotchi/working_set.rb +162 -90
  194. data/lib/samagotchi/working_set_locator.rb +221 -0
  195. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  196. data/lib/samagotchi/working_set_part.rb +281 -0
  197. metadata +36 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 39e6d208e1727e50fcb10c903c2c8cfc2bcb5c659f769de03916a52a527fc216
4
- data.tar.gz: d9b8cca3456163bcec4c133e9559a7ef6e87a60eb6bcbd18537016e4afb4927a
3
+ metadata.gz: 4fa7ea0128fca17683c36d4351d46709ad875b456ec70f654c32ea5cd03ae195
4
+ data.tar.gz: df253a823daf0b25c60eac2feadde85d42f0be804a3af01baf334c690971c5f4
5
5
  SHA512:
6
- metadata.gz: 5737d57d34e0a8b8c49e776f1a771354a1f5abb2afaff856cc29b73fe0adf6c1740048c3b32df19087a23580d38b6532b5203b286de4fe96c84022a5b684eef9
7
- data.tar.gz: 92dd02c054a4353dfd7ce245b3c6c11ceecbf571922704af64b0cffcde5fc95615309f96165242dac203d05f6b3c6372d372226fcc5afd92ff0a1686edde8619
6
+ metadata.gz: 516793e450b783e6adb6ebb3b12b35f47562e32ebb31684b050da2ab8c489fe137e7429806506b25213897773aef64645c60cacf912cb82c212b211408a5ef2c
7
+ data.tar.gz: a12c2786b0df4ce77496b4721a21591f330dc66929b853fcfc0a83f5e5c9fd35b8379b2890c70c1d28a07d3129b0a49134d0f86ff8ca10b7d2e9d4ae6153ea4e
data/CHANGELOG.md CHANGED
@@ -8,6 +8,110 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.184.0] - 2026-11-22
12
+
13
+ ### Added
14
+
15
+ - The web's working set: every "From the start" row has a ▸ that shows the text chi was sent for that part of its
16
+ prompt (a memory, AGENTS.md, the base prompt, the tools' names and sizes), with a tab per hold when a memory is in
17
+ the prompt twice or was also read. The list is 520 wide always, so opening a row no longer moves the others.
18
+ - The web's working set: a "From the start" row whose memory or AGENTS.md changed after chi was sent it says `stale`,
19
+ and its "now · changed" tab shows the difference and when chi gets the new text (a stopped session too). When chi
20
+ changed it itself, the row says `✎ edited` and links the call instead: chi has the new text in its conversation.
21
+ - The phone gets a notification when chi web's schedule tick turns off a recurring schedule that kept failing or
22
+ being skipped, with the last reason and the `chi schedule enable` that turns it back on.
23
+ - A thin client's ask takes an optional `request_id`: the same ask sent again (a retry after a dropped connection)
24
+ answers the first one's turn instead of running it twice.
25
+
26
+ ### Changed
27
+
28
+ - An ask of `/continue yes` (a thin client's `POST …/ask`, an MCP host's `chi_ask`) waits for the continued turn and
29
+ answers its reply, or a wait token while it runs, instead of `status: command`.
30
+ - The web's working set: a memory chi read and then edited itself no longer says `read · stale`.
31
+ - For bundle authors, nested plugin-part names say how to list the file; `chi bundle check` warns when an unlisted
32
+ `.rb` under a subdirectory won't be installed (but not under `spec/` or `test/`).
33
+
34
+ ### Fixed
35
+
36
+ - A thin client's ask and an MCP host's `chi_ask` over `POST /api/mcp` answer within about 45 s even when the
37
+ session's worker hangs taking the message in (it could take more than a minute, past Claude Code's 60 s limit).
38
+ - The mcp bundle: concurrent tool calls whose remote session expired wait for one new session instead of failing with
39
+ "the session expired (404)" or sending a half-initialized request.
40
+ - chi as an MCP server refuses a request id that is an object, an array or a boolean (JSON-RPC -32600) instead of
41
+ echoing it, and answers a message with an id but no method with -32600 instead of leaving the host waiting.
42
+ - The web's delete sheet: closing it during "Stop its worker, then delete" no longer leaves the worker stopped and the
43
+ session in place; the delete goes on and a toast says how it went.
44
+ - `chi schedule enable` resets a schedule's skip and failure counts, so its next skip no longer turns it off again;
45
+ `chi schedule list --all` says whether skips or failures turned a schedule off.
46
+
47
+ Update with `chi update` (the mcp bundle is now 0.9.1).
48
+
49
+ ## [0.183.0] - 2026-11-22
50
+
51
+ ### Added
52
+
53
+ - chi as an MCP server: `claude mcp add chi -- chi mcp serve` lets Claude Code (or Codex, any MCP host) drive your
54
+ sessions with four tools: list them, ask one and wait for its answer, answer the question it waits on. `chi
55
+ --remote NAME mcp serve` reaches another machine's; chi web serves the same at `POST /api/mcp`. The host counts
56
+ as a parent agent (`guardrails.parent_answers`). See docs/mcp-server.md.
57
+ - The mcp bundle takes remote MCP servers: `url: https://mcp.context7.com/mcp` in place of `command:` under
58
+ `bundles: mcp: servers: <name>:`, with `bearer_token_env: VAR` for a token (sent as `Authorization: Bearer`) and
59
+ optional `headers:`. They work like local ones (the cached tools, `find_tools`, `call_tool`, guardrail names);
60
+ `/mcp` shows `connected (https://host)`. Run `chi update`.
61
+ - The mcp bundle signs in to a remote server that asks (OAuth): a server with no token that answers 401 shows
62
+ `needs sign-in` in `/mcp` and a card with a **Sign in** button; `/mcp login NAME` registers chi with its provider
63
+ and opens the sign-in page (or `/callback` the address from another device). The token is kept per address for
64
+ every session, renewed by itself, and `/mcp logout NAME` forgets it. A client of your own: `oauth: client_id:`
65
+ with `issuer:`. A provider that takes a client id metadata document gets chi's own
66
+ (`https://dmitry.it/samagotchi/oauth/client.json`) with no registration; `client_metadata_url:` names another,
67
+ `false` none. Nothing signs in by itself. See docs/bundles.md (The mcp bundle, Sign-in).
68
+ - For bundle authors: `ctx.card(…, between_turns: true)`, a card from a thread of your own that never lands in a
69
+ running turn's block; `chi.tool_source` groups take `state: :needs_user` (a search and a call say the source's
70
+ line); `Samagotchi::Plugin::Secrets::Busy` and `Unavailable` are stable to rescue.
71
+ - For bundle authors: `ctx.http.stream(method, url, …) { |res| … }`, a streamed answer: the status and headers
72
+ first, then the body as it arrives (`res.each_event` reads Server-Sent Events, `res.each_chunk` the raw pieces).
73
+ Leaving the block closes the connection. The test kit's `bundle.http.stub` takes `events:` and `chunks:`.
74
+ - For bundle authors: a plugin can be split into several files, listed under `plugin: parts:` in manifest.yml
75
+ (each with its sha256; `chi bundle check --fix` fills them). chi checks and loads them in order before the plugin
76
+ file, into the same namespace; `chi bundle status`, `diff`, `build` and `check` know them. See
77
+ [plugins.md](docs/plugins.md#a-plugin-in-several-files).
78
+ - For bundle authors: `ctx.cancel_controller`, the Stop `ctx.cancelled?` reads on this thread (an init task's own, else
79
+ the running turn's), to hand to `ctx.http`'s `cancel:` or a thread of your own.
80
+ - chi web takes a message and answers it in one call (`POST /api/sessions/ID/ask`), for a thin client such as an
81
+ iOS Shortcut or a script: the answer comes back within 35 s, or a wait token to send to `…/wait` until it does.
82
+ `…/answer` takes `wait`, and a new session's 201 has a token too. See docs/thin-clients.md.
83
+ - In the web's picture viewer, a diagram's nodes can be pointed at, when its bundle reports them (chi-mermaid 0.2.0
84
+ and later): the mouse over a node outlines it, a tap or click selects it and a card above the zoom bar names it, an
85
+ arrow or its label selects the arrow, a tap on empty space clears. On a phone a tap takes the nearest node within a
86
+ fingertip, unless an arrow or its label is right under it. Tab, the arrow keys and Enter reach the nodes; Esc
87
+ clears, then closes. A drag, a pinch and a double tap work as before. For bundle authors: `render` may return
88
+ `{ svg, regions }` when `chi.features.regions` is set ([plugins.md](docs/plugins.md#block-renderers)).
89
+ - For bundle authors: a card action can open an address, `{label:, url:}` (an http(s) one with a host): the web
90
+ draws a link to a new tab with the host named under the buttons, the terminal prints the address whole. It sends
91
+ nothing to the session and doesn't make a card ask. Set `requires_chi: ">= 0.183.0"` by hand.
92
+ - For bundle authors: `ctx.secrets` (`get`, `set`, `delete`, `update`), the bundle's tokens in 0600 files under the
93
+ state dir, apart per bundle; `update` reads, changes and writes under a lock that holds across workers. The test
94
+ kit keeps them in memory (`bundle.secrets`, `bundle.set(secrets: …)`). chi's model is kept off them by accident
95
+ guards: its file tools are refused there, and a shell command naming the folder asks you once.
96
+ - For bundle authors: `ctx.sign_in(title:, button:) { |redirect_uri| address }`, a browser round trip: a card with a
97
+ button to the address, a listener on 127.0.0.1 for the browser's return, and `flow.wait` for its query. A browser
98
+ on another device ends on an address that doesn't load: `/callback <address>` (a new session command) finishes it
99
+ there, shown as `/callback …` everywhere. Timeout, cancel and the worker leaving replace the card; `cancel:`
100
+ (a tool's `ctx.cancel_controller`) lets the turn's Stop end it.
101
+
102
+ ### Changed
103
+
104
+ - chi web asks about a delete in one sheet that says what goes, what is stopped first and what stays, with one button
105
+ that names the outcome (no browser dialog, no second ask). Archive asks in the same sheet when background tasks still
106
+ run, or says why it can't archive now. The tap stops only the tasks the sheet named.
107
+ - In the picture viewer, a double tap whose finger moved a little (up to 10 px) now counts as one.
108
+ - `chi bundle install` and `chi bundle upgrade` (`--dry-run` too) start with the bundle's version: `mcp 0.8.0 → 0.9.0`
109
+ when it changes, `mcp 0.9.0` when it doesn't, and `mcp 0.9.0 (already current)` when the upgrade has nothing to write.
110
+
111
+ After updating, reload any open chi web page: one still on 0.182.0 shows the mcp sign-in card without its button.
112
+
113
+ Update with `chi update` (bundles: mcp 0.9.0, the dev profile 0.7.9).
114
+
11
115
  ## [0.182.0] - 2026-11-21
12
116
 
13
117
  ### Added
@@ -6644,7 +6748,9 @@ and long-lived sessions.
6644
6748
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6645
6749
  hotkey panel that send selected text or the clipboard to your sessions.
6646
6750
 
6647
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.182.0...HEAD
6751
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.184.0...HEAD
6752
+ [0.184.0]: https://github.com/dm1try/samagotchi/compare/v0.183.0...v0.184.0
6753
+ [0.183.0]: https://github.com/dm1try/samagotchi/compare/v0.182.0...v0.183.0
6648
6754
  [0.182.0]: https://github.com/dm1try/samagotchi/compare/v0.181.0...v0.182.0
6649
6755
  [0.181.0]: https://github.com/dm1try/samagotchi/compare/v0.180.0...v0.181.0
6650
6756
  [0.180.0]: https://github.com/dm1try/samagotchi/compare/v0.179.0...v0.180.0
data/bin/chi CHANGED
@@ -106,7 +106,9 @@ SUBCOMMANDS = {
106
106
  # this folder's project; init marks a folder in no git repository (.chi/project.yml)
107
107
  "project" => ["samagotchi/project_command", "ProjectCommand"],
108
108
  # durable schedules that outlive every worker (add, list, show, tick, run-now, …)
109
- "schedule" => ["samagotchi/schedule_command", "ScheduleCommand"]
109
+ "schedule" => ["samagotchi/schedule_command", "ScheduleCommand"],
110
+ # chi as an MCP server on stdio, for an MCP host (serve)
111
+ "mcp" => ["samagotchi/mcp_command", "McpCommand"]
110
112
  }.freeze
111
113
  # chi --remote NAME <command> (or CHI_REMOTE=NAME): the session commands
112
114
  # against another machine's chi web; what runs here only is refused (exit 2).
data/docs/architecture.md CHANGED
@@ -246,7 +246,7 @@ agent logic and can be used without any terminal rendering; the UI is a thin lay
246
246
  | Core | `Samagotchi::Engine` | System prompt, memory injection, tool declarations, session lifecycle, the model↔tool loop (`run_turn`). No terminal coupling. |
247
247
  | UI | `Samagotchi::TerminalUI`, `TerminalUI::AttachLauncher` / `AttachedLoop` | The attached TUI: rendering (ANSI, spinner, status line) and the terminal's own commands over the worker's Bridge. `TerminalUI`: the `--non-interactive` one-shot host, which delegates all core work to its `Engine`. |
248
248
  | Model loops and adapters | `KernelLoop`, `LLM::ChatLoop`, `Samagotchi::Client`, `LLM::OpenAIChat`, `LLM::AnthropicMessages`, `LLM::HTTP` | The model↔tool loops and the HTTP adapters they talk through (see "Model loops and adapters"). |
249
- | Bridge (SSE/HTTP) ([internals/bridge.md](internals/bridge.md)) | `Samagotchi::Bridge`, `SessionManager` | The **single live client transport**: an SSE read stream + HTTP POST turn/cancel/answer surface that attaches to a worker's existing `Engine` via `Engine#subscribe`. Every session worker starts it (bound `127.0.0.1`, localhost-only), and it answers only a request that names its secret (`X-Chi-Bridge`, from the worker's 0600 `bridge.json`). |
249
+ | Bridge (SSE/HTTP) ([internals/bridge.md](internals/bridge.md)) | `Samagotchi::Bridge`, `SessionManager` | The **single live client transport**: an SSE read stream + HTTP POST turn/cancel/answer surface that attaches to a worker's existing `Engine` through its event log, turn state, question desk and steer cut (`Engine#event_log`, `#turn_state`, `#question_desk`, `#steer_cut`, which the Worker hands it). Every session worker starts it (bound `127.0.0.1`, localhost-only), and it answers only a request that names its secret (`X-Chi-Bridge`, from the worker's 0600 `bridge.json`). |
250
250
  | Web (Rack) | `Samagotchi::Web::App`, `SessionManager` | Single-port `127.0.0.1:4567` control plane via `rack`+`webrick` (serve `index.html` + `/api/*`). With `web.host: lan` (or one of this machine's IPv4 addresses) the server also listens on that address, where every request needs the access token, this machine's on loopback too (`App#token_gate`: the `chi_token` cookie, on loopback a value derived from the token (`Token.loopback_cookie`), or `Authorization: Bearer`; chi web prints a `Local:` link with a one-time code; [CLI](cli.md#chi-web-on-your-phone)). Experimental: behind an auth proxy (`web.public_url`, `Web::ProxyGate`) every request needs the token, this machine's too, and one that came through the proxy also the configured identity header for the owner ([configuration.md](configuration.md#behind-an-auth-proxy)). A request goes through, in order: the Host check (`local_host_header?`: loopback names, the LAN address, the public host), the cross-site check (`cross_site?`: Origin this server's or the public origin, no `Sec-Fetch-Site` cross-site/same-site on a POST or `/api`), the frame check (`framed?`: a frame/embed/object load from another origin, 403 `framed`; every HTML answer carries `X-Frame-Options: DENY` and `frame-ancestors 'none'; frame-src 'none'`, so a page's own frames can't navigate either), the token gate (`token_gate` → `principal_for`, `proxied_principal` for a proxied request; the `?token=` / `POST /api/token` trade sets the cookie, `__Host-chi_token` through the proxy; with `web.public_url` a direct request takes Bearer only, and with it or LAN mode chi's token-less `/api/info` probe gets `probe_info`), then the route's permission (`Principal#permits?`). It talks to each worker's Bridge (`App#relay`, `bridge_get`; `/stream` proxies it) and reads the session files; no `Engine` of its own. Markdown (`web.markdown`) is rendered here only (`Web::MarkdownRenderer`): the answers it serves, card bodies, and `POST /api/render` for a text the page already shows. `App` keeps the gate, `ROUTES` and the helpers the handlers share; its handlers live in mixins it includes, each a `Web::` module with private methods: `SessionAccessRoutes` (`web/session_access_routes.rb`), `ParticipantAccess` (`web/participant_access.rb`), `ParticipantsAdmin` (`web/participants_admin.rb`), `ParticipantReview` (`web/participant_review.rb`), `MessageDisplay` (`web/message_display.rb`), `SessionShow` (`web/session_show.rb`), `SessionCreate` (`web/session_create.rb`), `SessionControl` (`web/session_control.rb`), `PushRoutes` (`web/push_routes.rb`) and `ProxyGate` (`web/proxy_gate.rb`). Exact paths in `GATE_FREE_PATHS` are served before the token gate (the fragment trade's script, and the Home Screen app's manifest, service worker and icons). `bin/chi web` entrypoint. |
251
251
  | Sessions | `Samagotchi::Session`, `SessionManager` | File-based `~/.local/state/samagotchi/sessions/<uuid>.json` + sidecar `input/`/`output/`; retention (14d/500) + ordering (`updated_at desc`). |
252
252
 
@@ -338,17 +338,24 @@ The full request layout, what breaks the cache and the rules for changes:
338
338
 
339
339
  #### Subscribing to the live stream (and the bridge)
340
340
 
341
- For an **always-on** consumer (an external SSE client, a second UI), use
342
- `Engine#subscribe` rather than passing `on_event:` to a single turn. It is a thread-safe,
341
+ For an **always-on** worker-side consumer (an external SSE client, a second UI), take the
342
+ Worker's `Engine#event_log` and subscribe directly to that `SessionObserver`. It is a thread-safe,
343
343
  error-isolated fan-out with a monotonic `event_seq` on every event:
344
344
 
345
345
  ```ruby
346
- handle = engine.subscribe(observer: ->(event) { ... }) # observer receives {..., event_seq:}
347
- engine.unsubscribe(handle: handle)
346
+ log = engine.event_log
347
+ handle = log.subscribe(observer: ->(event) { ... }) # observer receives {..., event_seq:}
348
+ log.unsubscribe(handle: handle)
348
349
  engine.session_state_snapshot # => { status:, message_count:, last_prompt:, event_seq: }
349
350
  ```
350
351
 
351
- `Engine#subscribe` is the seam the SSE bridge (`Samagotchi::Bridge`) rides on. The bridge
352
+ `Engine#subscribe` forwards to this event log for the Engine's own parts and the one-shot host, but worker hosts hold
353
+ `Engine#event_log` directly. The Worker reads it once after it built the Engine and hands it to the Bridge and to its
354
+ own collaborators (`ContinueOffer`, `WorkerParticipantGate`, `WorkerTaskWakes`, `WorkerInbound`), which subscribe,
355
+ announce and take the event lock on it directly. The same goes for the turn state,
356
+ the question desk and the steer cut (`Engine#turn_state`, `#question_desk`, `#steer_cut`): the Worker hands them to the
357
+ Bridge (which hands the desk on to `RelayVerifier` and `RelayWatcher`) and to `WorkerInbound`, `WorkerIdleExit` and
358
+ `ContinueOffer`, which call them directly instead of the Engine's forwards. The bridge
352
359
  is the **single live transport** and runs **inside the forked session worker** (the same
353
360
  process that already owns the `Engine`); every worker starts it. It keeps what a client that joins late needs
354
361
  (`RingBuffer` of recent events, `TurnAccumulator` for the turn in progress, `CardStore` for cards and notices), writes
@@ -498,10 +505,13 @@ model: [internals/remote-sessions.md](internals/remote-sessions.md).
498
505
  | `GET /api/sessions/summaries` | owner | `dir` (a folder: its project; none: every project), `cwd`, `live=1`, `archived=1`, `tests=0`, `sort`, `order`, `limit` | 200: the rows `chi sessions list` prints (`SessionRow#to_summary_h`, 28 keys in a fixed order: `status`, `live`, `busy`, `owner`, `recap`, `ctx_pct`, `waiting`, `waiting_id`, `title`, `preview`, …) | 400 `invalid_dir`, `invalid_cwd` |
499
506
  | `GET /api/projects?dir=` | owner | optional page-scope folder | 200: project rows (`Web::ProjectList`: the hub's projects plus the start project and current project, even without sessions) with counts, roots, default/current marks; no `dir`: no current project | 400 `invalid_dir`; 503 `no_hub` |
500
507
  | `POST /api/projects` | owner | `{dir}` (absolute folder; `~` and `~/` expand against the server's home) | 200 `{outcome, root, dir}` (`created`, `already_marked`, or `git`) | 400 `invalid_json`, `invalid_dir`; 422 `above_home`, `write_failed` |
501
- | `POST /api/sessions` (more fields) | owner | `toolkit`, `tools`, `no_tools`, `parent_answers`; `client_id` (`cli:send`/`cli:answer`: the first line is checked as chi send checks it); `check_vision: true` (images follow) | 201 adds `model_warning`, `parent_answers_warning` (a level looser than config.yml's, capped) and `first_turn_id` (the id the prompt it starts with gets for its turn; null for an `idle` create) | 400 `invalid_toolkit`, `invalid_parent_answers`, `invalid_continues` (beside `continues`); 403 `parent_answers_refused`, `parent_continue_refused`; 422 `no_vision` |
508
+ | `POST /api/sessions` (more fields) | owner | `toolkit`, `tools`, `no_tools`, `parent_answers`; `client_id` (`cli:send`/`cli:answer`: the first line is checked as chi send checks it); `check_vision: true` (images follow) | 201 adds `model_warning`, `parent_answers_warning` (a level looser than config.yml's, capped) and `first_turn_id` (the id the prompt it starts with gets for its turn; null for an `idle` create); with a `first_turn_id`, a wait `token` for that turn (none for an `idle` create) | 400 `invalid_toolkit`, `invalid_parent_answers`, `invalid_continues` (beside `continues`); 403 `parent_answers_refused`, `parent_continue_refused`; 422 `no_vision` |
502
509
  | `POST /api/sessions/:id/turn` (more fields) | owner | `client_id` as above; `check_vision: true` with `images` | as before | 403 `parent_answers_refused`, `parent_continue_refused`; 422 `no_vision` |
503
510
  | `POST /api/sessions/:id/wait/prepare` | owner | `question_id` (absent: the pending one; `null`: none), `turn`, `created`, `busy` (+ `queue`) | 200 `{session_id, cursor, baseline: {messages, question_id, last_turn}, own_turn, known_turn, running, live, settled, last_turn_id}` (`WaitStart`) | 409 `busy`, `waiting` (`SendCommand::Busy`'s words, and its fields: `question`, `parent_strategy`) |
504
- | `POST /api/sessions/:id/wait` | owner | `cursor`, `baseline`, `turn`, `queued`, `ended_before`, `owner_grace`, `timeout` (capped at 30 s) | 200: `ReplyWait::Result`'s fields (`status`: `done`, `waiting_for_answer`, `no_reply`, `error`, `stopped`, `worker_gone`, or `timeout`: ask again; `text`, `file`, `question` as `PendingQuestion#to_file`, `outcome`, `limit`, `error_kind`, `retryable`, `cancel_reason`, `stopped_by`, `kept_steps`, `turn_id`, `origin`; never the session) and `parent_strategy` `{name, allowed, origin}` (`ParentReport.strategy_for`, this server's config.yml) | 400 `invalid_wait`; 503 `server_stopping` |
511
+ | `POST /api/sessions/:id/wait` | owner | `cursor`, `baseline`, `turn`, `queued`, `ended_before`, `owner_grace`, `timeout` (capped at 30 s); or `{token, timeout}` (a wait token, `SessionAccess::Exchange::Token`: the answer adds `session_id`, and `token` again while the status is `timeout`; a token beside the other fields, another session's, one that isn't one or a participant's: 400 `invalid_wait`) | 200: `ReplyWait::Result`'s fields (`status`: `done`, `waiting_for_answer`, `no_reply`, `error`, `stopped`, `worker_gone`, or `timeout`: ask again; `text`, `file`, `question` as `PendingQuestion#to_file`, `outcome`, `limit`, `error_kind`, `retryable`, `cancel_reason`, `stopped_by`, `kept_steps`, `turn_id`, `origin`; never the session) and `parent_strategy` `{name, allowed, origin}` (`ParentReport.strategy_for`, this server's config.yml) | 400 `invalid_wait`; 503 `server_stopping` |
512
+ | `POST /api/sessions/:id/ask` | owner | `prompt` (16 KiB), `timeout` (default and most 30 s), `queue` (default `true`: a running session queues it as its own turn; `false` refuses it), `client_id` (absent: `web:unnamed`; `cli:send`'s `/continue yes` goes in as `cli:answer` and is parent-gated as on `…/turn`), `request_id` (optional, 1-128 printable ASCII, messages only: a retry with it answers the first ask's turn, `SessionInbox.enqueued_id_for`) | 200: the wait's fields + `session_id` (where it ran), `asked` (the id given, when another link ran it), `token` when the status is `timeout`, `request_id` echoed when given; 200 `{status: command, session_id}` for a session command (`/continue yes` with an offer standing answers the continued turn's fields instead). The whole call answers within `AskRoutes::ASK_MAX_SECONDS` (35) (`Web::AskRoutes`, `SessionAccess::Ask`, [thin-clients.md](thin-clients.md)) | 404 `not_found`; 400 `ambiguous_id`, `missing_fields`, `invalid_prompt`, `local_command`, `invalid_ask` (also a `request_id` on a session command); 403 `parent_continue_refused`, `parent_answers_refused`; 409 `busy`, `waiting` (neutral words, Busy's fields), `continuing`, `owned_by_tui`, `enqueued_id_conflict` (the same `request_id`, another prompt, a turn the session no longer names but the worker remembers), the turn route's delivery refusals (`queue_unavailable`, …); 504 `worker_timeout`; 503 `server_stopping` |
513
+ | `POST /api/mcp` (`GET`, `DELETE`) | owner | one JSON-RPC message of MCP (112 KiB: a 16 KiB prompt JSON-escaped), either revision: the current one with `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` headers matching the body, the earlier one with the `Mcp-Session-Id` its `initialize` handed out (and an `MCP-Protocol-Version`, if any, that chi serves) | 200 the JSON-RPC answer (a tool's refusal is a result with `isError`), 202 for a notification; `GET` 405 (`Allow: POST, DELETE`, no stream), `DELETE` 200. Each call within `McpServer::Tools::SLICE` (25 s) (`Web::McpRoute`, `McpServer::Http`, [mcp-server.md](mcp-server.md)) | 400 `-32020` (headers unlike the body), `-32022` (an unsupported revision), `-32700` (not JSON or not UTF-8; with the request's id when one can be read)/`-32600` (not an object: a batch is one), `Missing session ID`, an unsupported legacy `MCP-Protocol-Version`; 404 `-32601`; the gate's 401 adds `WWW-Authenticate: Bearer` here |
514
+ | `POST /api/sessions/:id/answer` (`wait`) | owner | `wait: N` (seconds, at most 30) beside `id`, `selected`, `freeform` | 200 `{status: answered, session_id, id, reply: {the wait's fields, token while it is timeout}}`; a question answered elsewhere first: 200 `{status: not_pending, answered_here: false, …, reply}` (as `chi answer` still waits); a wait that fails after the answer went in: 200 with that `status` and `wait_error` `{error: server_stopping \| not_found \| wait_failed, detail}` in place of `reply`; without `wait` every answer is as before | 400 `invalid_wait`; 404 |
505
515
  | `POST /api/sessions/:id/notes` | owner | `text`, `source` (default `cli`, never `broadcast`) | 200 `{status: queued \| waits, session_id, queued}` (`NoteDelivery`) | 409 `owned_by_tui` (`status: refused`); 400 `note_rejected`, `missing_fields`, `invalid_source` |
506
516
  | `POST /api/sessions/:id/context` (more bodies) | owner | `{name, push: true, why, hint}` or `{name, cmd, every, why, hint}` beside the page's `{url, why, hint}`; `added_by` `cli`/`agent` (else `web`); `movable` (any body) | 201 `{status: attached, name, movable}` | 400 `invalid_source`; 409 `exists` |
507
517
  | `POST /api/sessions/:id/context/:name/push` | owner | `text`, `summary`, `wake`, `hint`, `re` (a source's JSON output, checked the same way) | 200 `{status: pushed, name, before, revision, changed}` | 404 `not_found`; 409 `not_push`; 410 `context_continued` (`next_id`); 400 `invalid_text` |
@@ -661,7 +671,7 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
661
671
  | Bundle authoring | `bundle_command.rb` (`BundleCommand`), `bundle_command/{scaffold,check,test_run}.rb`, `bundle_command/try/{run,sandbox,trace}.rb`, `testing.rb` + `testing/` (the test kit) | `chi bundle new`, `check`, `test` and `try`, and the kit a bundle's tests load it with ([bundle-authoring.md](bundle-authoring.md), [internals/bundles.md](internals/bundles.md)). |
662
672
  | Session file | `session.rb` (`Session`, `Session::FIELDS`), `session_field.rb` (`SessionField`), `session_paths.rb` (`SessionPaths`), `session_setup.rb` (`SessionSetup`) | A session's `<uuid>.json`: one `SessionField` row per key (default, cast, what the file gets; the codec on its type), from which `Session.new`, `.from_h` and `#to_h` are built; `SessionPaths` is where the file and the session's dir are and the id rule, a leaf `Session` extends (so `ArchiveStore` and `ContextSources` name no `Session` constant; both still require session.rb at load); `SessionSetup` the settings a fork and a continue carry (`.of`), applied by member name; every new-session request (chi's run flags, the one-shot, `chi send --new`, chi web's create) builds its setup with `SessionSetup.from_request`, and `spec/session_setup_entrypoints_spec.rb` holds each entrypoint's cell for each member. See [sessions.md](sessions.md#session-file). |
663
673
  | Session config (`--set`) | `session_config.rb` (`SessionConfig`, `SessionConfig::Settings`) | A session's own settings as one value (`Session#settings`, `SessionSetup#settings`): `core`, the `--set KEY=VALUE` values of the core keys marked `session: true` (`Config::Entry`), typed by `Config.coerce!` and read first through `Config.get(key, session:)` (`RecapSetup`; `Engine#session=` rebuilds the recap job, `IdleScheduler#replace_job`), file key `config_settings`; `bundles`, the `--set BUNDLE.KEY=VALUE` values, checked against the manifest's `session_settings:`, laid over `bundles: <name>:` in `ctx.settings` ([plugins.md](plugins.md)), file key `bundle_settings`. `SessionConfig.clash` refuses a bundle setting named like a core one (install, `chi bundle check`). See [configuration.md](configuration.md#per-session-settings). |
664
- | Plugin API | `plugin/api.rb` (`Plugin::Api`), `plugin/tool_spec.rb` (`Plugin::ToolSpec`: a checked tool declaration, how it is registered), `plugin/loader.rb`, `plugin/context.rb` (`ctx`), `plugin/http.rb` + `plugin/http_transport.rb` (`ctx.http`), `plugin/card.rb` (`Plugin::Card`) | What a bundle's plugin registers: tools, commands, annotation actions, hooks, services, toolkits, peer sources; what its handlers get as `ctx` ([plugins.md](plugins.md)). |
674
+ | Plugin API | `plugin/api.rb` (`Plugin::Api`), `plugin/tool_spec.rb` (`Plugin::ToolSpec`: a checked tool declaration, how it is registered), `plugin/loader.rb`, `plugin/context.rb` (`ctx`), `plugin/http.rb` + `plugin/http_transport.rb` (`ctx.http`), `plugin/http_stream.rb` (`ctx.http.stream`) + `plugin/sse_reader.rb`, `plugin/http_errors.rb`, `plugin/secrets.rb` (`Plugin::Secrets`, `ctx.secrets`) + `plugin/sign_in.rb` (`Plugin::SignIn`, `ctx.sign_in`), `plugin/card.rb` (`Plugin::Card`) | What a bundle's plugin registers: tools, commands, annotation actions, hooks, services, toolkits, peer sources; what its handlers get as `ctx` ([plugins.md](plugins.md)). |
665
675
  | Peer bundles' base | `plugin/peer.rb` (`Plugin::Peer`) | What claude-peer and codex-peer share (the send tool, the command, the cards, payloads); each bundle's subclass sets its strings and transport ([bundles.md](bundles.md#the-claude-peer-bundle)). |
666
676
  | Shipped bundles | `bundles/` (`mcp`, `github-pr`, `loop-guard`, `skills`, `source-links`, …) | Bundles that ship with chi. |
667
677
  | Hooks | `hooks/registry.rb` (`Hooks::Registry`), `hooks/loader.rb`, `hook_routes.rb` (`HookRoutes`), `event_routes.rb` (`EventRoutes`) | Hook registration and dispatch; what a hook or plugin does beyond reading its event (notice, question, stop, steer) routed to the UIs (cards and notices through one set of routes) ([hooks.md](hooks.md)). |
@@ -670,12 +680,13 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
670
680
  | Delegation | `tools/delegate.rb`, `tools/delegate_result.rb`, `tools/delegate_wait.rb`, `child_reports.rb`, `tools/delegate_relay.rb`, `relay_desk.rb`, `relay_verifier.rb`, `relay_watcher.rb` | Child sessions a session starts and waits on, and their approval relay ([sessions.md](sessions.md#delegating)). |
671
681
  | send / broadcast | `send_command.rb` (`SendCommand`), `broadcast_command.rb` (`BroadcastCommand`), `broadcast/` | `chi send` and `chi broadcast` ([broadcast.md](broadcast.md), [sub-agent.md](sub-agent.md)). |
672
682
  | Worker link | `worker_link.rb` (`WorkerLink`: `Live`, `Starting`, `Leaving`, `Skew`, `Stale`, `None`), `worker_sidecar.rb` (`WorkerSidecar`) | Whether a session's worker can be reached and the client for it: every Bridge client asks `WorkerLink.resolve` / `.client` / `.await` (*Worker link* above); `WorkerSidecar` is the `bridge.json` it reads. |
673
- | Session access | `session_access.rb` (`SessionAccess`: `NewSession`, `SetupWords`, `WaitStart`, `SessionView`, `Created`, `ContextEntry`, `ContextPush`, the errors `RemoteFailed`, `RemoteTooOld`, `Refused`, `BadRequest`), `session_access/local.rb` (`SessionAccess::Local`), `session_access/remote.rb` (`SessionAccess::Remote`), `session_access/http_transport.rb`, `session_access/web_bridge_client.rb` (`SessionAccess::WebBridgeClient`, a remote attach's worker through chi web), `session_access/dispatch.rb` (`SessionAccess::Dispatch`), `session_access/contract.rb` (`SessionAccess::Contract`), `remotes.rb` (`Remotes`), `remote_command.rb` (`chi remote`), `web/session_access_routes.rb` (`Web::SessionAccessRoutes`) | The seam between the session commands and where the sessions live: `Local` is this machine's (the `SessionManager`, `ReplyWait`, `NoteDelivery`, `ContextSources` and Bridge calls the commands made); `Remote` is another machine's, the same methods as requests to its chi web's routes of the same name (Bearer token, `HTTPTransport`), results as Local's value objects and refusals as the classes Local's callees raise, built from the fields chi web sends; waits and prefixes run on the server, a wait asked again per 30 s slice. `Dispatch` is bin/chi's front for `--remote NAME` / `CHI_REMOTE` (taken off before the subcommand lookup): it refuses what the contract table lists `local_only` (exit 2, one message) and runs the command with a `Remote` on the `Remotes` entry (`$XDG_CONFIG_HOME/samagotchi/remotes.yml`, 0600). chi web's routes answer from `Local` (*chi web's routes for the session commands* above). Checks that read this machine's config or files (vision, parent answers, the cwd's project, `SAMAGOTCHI_PARENT_SESSION`) stay in the commands and are skipped under a `Remote`, where chi web's create, turn and wait routes run the vision, parent-answers and busy checks with the server's config and the worker checks a parent's answer. See [internals/remote-sessions.md](internals/remote-sessions.md). |
683
+ | Session access | `session_access.rb` (`SessionAccess`: `NewSession`, `SetupWords`, `WaitStart`, `SessionView`, `Created`, `ContextEntry`, `ContextPush`, the errors `RemoteFailed`, `RemoteTooOld`, `Refused`, `BadRequest`), `session_access/local.rb` (`SessionAccess::Local`), `session_access/remote.rb` (`SessionAccess::Remote`), `session_access/http_transport.rb`, `session_access/web_bridge_client.rb` (`SessionAccess::WebBridgeClient`, a remote attach's worker through chi web), `session_access/dispatch.rb` (`SessionAccess::Dispatch`), `session_access/contract.rb` (`SessionAccess::Contract`), `remotes.rb` (`Remotes`), `remote_command.rb` (`chi remote`), `web/session_access_routes.rb` (`Web::SessionAccessRoutes`), `session_access/exchange.rb` (`SessionAccess::Exchange`: the stateless pieces of a send and its wait, for chi send, chi answer and the ask), `session_access/exchange/token.rb` (`Exchange::Token`: a wait as one string), `session_access/ask.rb` (`SessionAccess::Ask`: one message in, its answer out), `web/ask_routes.rb` (`Web::AskRoutes`: the thin-client routes) | The seam between the session commands and where the sessions live: `Local` is this machine's (the `SessionManager`, `ReplyWait`, `NoteDelivery`, `ContextSources` and Bridge calls the commands made); `Remote` is another machine's, the same methods as requests to its chi web's routes of the same name (Bearer token, `HTTPTransport`), results as Local's value objects and refusals as the classes Local's callees raise, built from the fields chi web sends; waits and prefixes run on the server, a wait asked again per 30 s slice. `Dispatch` is bin/chi's front for `--remote NAME` / `CHI_REMOTE` (taken off before the subcommand lookup): it refuses what the contract table lists `local_only` (exit 2, one message) and runs the command with a `Remote` on the `Remotes` entry (`$XDG_CONFIG_HOME/samagotchi/remotes.yml`, 0600). chi web's routes answer from `Local` (*chi web's routes for the session commands* above). Checks that read this machine's config or files (vision, parent answers, the cwd's project, `SAMAGOTCHI_PARENT_SESSION`) stay in the commands and are skipped under a `Remote`, where chi web's create, turn and wait routes run the vision, parent-answers and busy checks with the server's config and the worker checks a parent's answer. See [internals/remote-sessions.md](internals/remote-sessions.md). |
674
684
  | Idle work | `idle_scheduler.rb` (`IdleScheduler`), `idle_recap.rb` (`IdleRecap`), `idle_reminders.rb` | One poller for an idle session's recap and reminders. |
675
685
  | Attached context | `context_sources.rb` (`ContextSources`), `context_poller.rb`, `context_absorber.rb`, `context_candidates.rb` (`ContextCandidates`: proposed sources, attached on the owner's mention at a turn's start, before the worker's absorb, or in a one-shot's turn; `owner_prompt.rb` decides whose words count), `peer_sources.rb` (`PeerSources`: the sources peer bundles declare) | External sources a session keeps fresh, and the peer loop's wakes ([context.md](context.md)). |
676
686
  | LLM context strategies | `llm_context_strategy.rb`, `llm_context_view.rb`, `llm_context_stale.rb`, `llm_context_forget.rb` | What a request sends of the history (none, stale, forget) ([internals/llm-context-forget.md](internals/llm-context-forget.md)). |
677
687
  | Session chains | `session_continue.rb` (`SessionContinue`), `session_chain.rb` (`SessionChain`), `session_chain/links.rb` (`SessionChain::Links`), `session_chain/delete.rb` (`SessionChain::Delete`), `session_chain/delete_preview.rb` (`SessionChain::Delete::Preview`), `continued_from.rb` (`ContinuedFrom`) | A session that continues an earlier one. `SessionChain::Links` is the one chain walker (one listing; `latest`, `first_live`, `root`, `next_of`): `SessionChain.latest`/`.next_of`, `SessionInbox::Head` and the schedule tick all ask it. `SessionChain.opener_for` gives the text web `continue →` prefills in the new link: the previous link's own first typed message when that link continues one itself, else nil (the 201's `opener`; not saved). `SessionChain::Delete` plans and deletes a link or its chain; `Delete::Preview` supplies the web delete sheet, and `ContinuedFrom` records what a continue must undo ([sessions.md](sessions.md)). |
678
- | chi web's routes | `web/app.rb` (`Web::App`: the gate, `ROUTES`, the shared helpers), `web/request_body.rb` (`Web::RequestBody`: bounded body reads), `web/message_display.rb` (`Web::MessageDisplay`: saved messages and cards as display items, the owner show's stamped with their turns' drawings and carrying no parts (a step's ✂ marks only), the participant show's with their parts, `POST /api/render`), `web/session_show.rb` (`Web::SessionShow`: `GET /api/sessions/:id` with its `cards`, `tail` and `timing` re-reads, `GET …/output`, the timing payload), `web/session_create.rb` (`Web::SessionCreate`: `POST /api/sessions`, a continue), `web/session_control.rb` (`Web::SessionControl`: answer, command, turn and images, cancel, stop, restart, archive, delete), `web/session_access_routes.rb` (`Web::SessionAccessRoutes`: the session-command routes), `web/verify_fresh_routes.rb` (`Web::VerifyFreshRoutes`: Verify fresh children), `web/working_set_routes.rb` (`Web::WorkingSetRoutes`: the working set routes), `web/viewer.rb` (`Web::Viewer`: page capabilities), `web/push_routes.rb` (`Web::PushRoutes`: `/api/push`, its subscriptions, prefs, test and presence), `web/block_renderer_routes.rb` (`Web::BlockRendererRoutes`: `GET /api/block_renderers` and one renderer's file, [internals/block-renderers.md](internals/block-renderers.md)), `web/reload_check_route.rb` (`Web::ReloadCheckRoute`: `POST /api/sessions/:id/reload_check`, the opt-in `web.reload_check`'s counts from the page's `reload_check.js`, 204 and one `reload_checked` log line, with `reload_mismatch`, its `kinds`, `excused` (ACCEPTED ids) and `explained` when the turn read otherwise after a reload; the worker's version is chi web's own view, its sidecar) | The handlers `App`'s `ROUTES` name, in the file that holds their kind; each mixin is included in `App` and reads its helpers and ivars, so `app.send(:handle_show, …)` and the specs that stub `App` methods work as before. The shared body reader caps incoming requests. |
688
+ | MCP server | `mcp_server/protocol.rb` (`McpServer::Protocol`: JSON-RPC in both revisions, no transport, no chi), `mcp_server/tools.rb` (`McpServer::Tools`: `chi_sessions`, `chi_ask`, `chi_wait`, `chi_answer` over a SessionAccess backend through `SessionAccess::Ask` and `Exchange`), `mcp_server/text.rb` (`McpServer::Text`: the results' words), `mcp_server/stdio.rb` (`McpServer::Stdio`), `mcp_server/http.rb` (`McpServer::Http`), `mcp_command.rb` (`chi mcp serve`), `web/mcp_route.rb` (`Web::McpRoute`: `POST /api/mcp`, included through SessionAccessRoutes) | chi as an MCP server ([mcp-server.md](mcp-server.md)); not the `mcp` bundle (chi as a client). Only `tools.rb` names `SessionAccess`: another front builds `Protocol.new(tools: Tools.new(access))`. The caller is a parent agent (`cli:send` / `cli:answer`, `SessionAccess::Ask#agent_line`). |
689
+ | chi web's routes | `web/app.rb` (`Web::App`: the gate, `ROUTES`, the shared helpers), `web/request_body.rb` (`Web::RequestBody`: bounded body reads), `web/message_display.rb` (`Web::MessageDisplay`: saved messages and cards as display items, the owner show's stamped with their turns' drawings and carrying no parts (a step's ✂ marks only), the participant show's with their parts, `POST /api/render`), `web/session_show.rb` (`Web::SessionShow`: `GET /api/sessions/:id` with its `cards`, `tail` and `timing` re-reads, `GET …/output`, the timing payload), `web/session_create.rb` (`Web::SessionCreate`: `POST /api/sessions`, a continue), `web/session_control.rb` (`Web::SessionControl`: answer, command, turn and images, cancel, stop, restart, archive, delete), `web/session_access_routes.rb` (`Web::SessionAccessRoutes`: the session-command routes), `web/ask_routes.rb` (`Web::AskRoutes`: ask, wait tokens, the answer's wait, included through SessionAccessRoutes), `web/verify_fresh_routes.rb` (`Web::VerifyFreshRoutes`: Verify fresh children), `web/working_set_routes.rb` (`Web::WorkingSetRoutes`: the working set routes), `web/viewer.rb` (`Web::Viewer`: page capabilities), `web/push_routes.rb` (`Web::PushRoutes`: `/api/push`, its subscriptions, prefs, test and presence), `web/block_renderer_routes.rb` (`Web::BlockRendererRoutes`: `GET /api/block_renderers` and one renderer's file, [internals/block-renderers.md](internals/block-renderers.md)), `web/reload_check_route.rb` (`Web::ReloadCheckRoute`: `POST /api/sessions/:id/reload_check`, the opt-in `web.reload_check`'s counts from the page's `reload_check.js`, 204 and one `reload_checked` log line, with `reload_mismatch`, its `kinds`, `excused` (ACCEPTED ids) and `explained` when the turn read otherwise after a reload; the worker's version is chi web's own view, its sidecar) | The handlers `App`'s `ROUTES` name, in the file that holds their kind; each mixin is included in `App` and reads its helpers and ivars, so `app.send(:handle_show, …)` and the specs that stub `App` methods work as before. The shared body reader caps incoming requests. |
679
690
  | Web Push | `web/push.rb` (`Web::Push`: `Runtime`, `preflight!`, the `web.push.*` settings), `web/push/crypto.rb` (`Push::Crypto`: RFC 8291 aes128gcm, RFC 8292 VAPID), `web/push/store.rb` (`Push::Store`, `Store::Sub`: `web-push/vapid.pem`, `subscriptions.json`), `web/push/client.rb` (`Push::Client`, `Client::Result`), `web/push/attention.rb` (`Push::Attention`: notify.js's rules in Ruby, shared cases in `spec/fixtures/attention_cases.json`), `web/push/presence.rb` (`Push::Presence`: the pages' "in front" reports), `web/push/notifier.rb` (`Push::Notifier`, a hub subscriber with a sender thread), `web/push_routes.rb` (`Web::PushRoutes`), `private_files.rb` (`PrivateFiles`, shared with the grants), `public/sw.js`, `public/push.js`, `public/manifest.webmanifest` | chi web pushes what the tab notifies for (approvals, questions, step-limit questions, cards, failed turns; done turns to a device that asks) to the owner's Home Screen app over an https public URL: the Notifier turns the hub's new attentions into show pushes after a hold, unless a chi web page is in front, at most 30 an hour, with one retry and a restart catch-up (`sent.json`) (each carries the keys still open, and the badge; no close push: every push shows a notification); the bell (`notifications.js`) subscribes the device, and the service worker and the page close the answered ones. See [internals/web-push.md](internals/web-push.md). |
680
691
  | chi web's updates | `web/update_check.rb` (`Web::UpdateCheck`), `web/update_ops.rb` (`Web::UpdateOps`), `web/auto_update.rb` (`Web::AutoUpdate`) | The RubyGems checker and its `update_check.json`; the install, worker-restart and chi-web-restart operations (one at a time) the owner's routes and AutoUpdate share; `update.auto: install`'s thread (install when no turn runs, then idle workers and chi web). See [configuration](configuration.md#unattended-updates-updateauto). |
681
692
  | Behind an auth proxy | `web/public_url.rb` (`Web::PublicUrl`: `web.public_url`, `web.proxy.identity_header`, `web.proxy.owner`), `web/proxy_gate.rb` (`Web::ProxyGate`, mixed into App; `RawHeaderNames`, prepended to WEBrick's request by `Web::Server`), `web/link_codes.rb` (`Web::LinkCodes`: the links' one-time codes), `proxy_trace.rb` (`ProxyTrace`), `web/public/token_fragment.js`, `web/public/auth_lost.js`, `web/tunnel.rb` + `web/tunnel/tailscale.rb` (`Web::Tunnel`, `Web::Tunnel::Tailscale`: `chi web --tunnel tailscale`, Tailscale Serve set for one run and the PublicUrl it makes) | Experimental: chi web behind an auth proxy. Every request needs the token; a proxied one's owner also needs the identity header (one clean value under one name); the `__Host-` cookie, an absolute `Location` from the public URL, https links with a one-time code in the fragment; the page's lost-sign-in banner. Bridges refuse proxy traces ([configuration.md](configuration.md#behind-an-auth-proxy)). |
@@ -58,7 +58,7 @@ plugin:
58
58
  `bundles: my-bundle:` as a Hash with string keys, once, when the plugin loads. A value a session may set
59
59
  (`chi --set my-bundle.KEY=V`, listed in the manifest's `session_settings:`, typed with `{KEY: number}` so a
60
60
  value of another type is refused) is read from `ctx.settings` at call time. List what config.yml may set in `settings:`
61
- (`[greeting]`, or `{greeting: string}`): a typo there then warns. `chi bundle check --set KEY=VALUE` gives the sandboxed load a setting. A bundle can also draw a fenced block in chi web's answers, with no plugin code: `block_renderers:` and a script calling `chi.defineRenderer` ([plugins.md](plugins.md#block-renderers)).
61
+ (`[greeting]`, or `{greeting: string}`): a typo there then warns. `chi bundle check --set KEY=VALUE` gives the sandboxed load a setting. A bundle can also draw a fenced block in chi web's answers, with no plugin code: `block_renderers:` and a script calling `chi.defineRenderer` ([plugins.md](plugins.md#block-renderers)). A plugin that outgrows one file lists its other top-level `.rb` files under `plugin: parts:` (`client.rb: sha256:`, at most 16; `check --fix` fills the shas, and warns of a top-level `.rb` they don't list): chi loads them in that order, then `plugin.rb`, into one namespace, so a part reopens `class Plugin` and a class body uses only what an earlier part defines; never `require_relative` one ([plugins.md](plugins.md#a-plugin-in-several-files)).
62
62
 
63
63
  ## What a hook sees
64
64
 
data/docs/bundles.md CHANGED
@@ -37,8 +37,11 @@ only against this API (`lib/samagotchi/bundles/btw/plugin.rb`).
37
37
 
38
38
  ## The mcp bundle
39
39
 
40
+ (The other direction, chi as an MCP server that a host such as Claude Code drives, is in core: see [chi as an MCP
41
+ server](mcp-server.md).)
42
+
40
43
  `chi bundle install mcp` (or the `dev` profile) installs the bundle shipped with chi. It is written
41
- only against this API (`lib/samagotchi/bundles/mcp/plugin.rb`), and gives
44
+ only against this API (`lib/samagotchi/bundles/mcp/`: `plugin.rb` and its parts `client.rb`, `http_client.rb`, `oauth.rb`, `tools.rb`, `content.rb`), and gives
42
45
  the model the tools of [MCP](https://modelcontextprotocol.io) servers. It
43
46
  has no memory file, and the servers' tools aren't declared to the model one
44
47
  by one: the bundle publishes them into chi's tool index
@@ -47,7 +50,7 @@ per server), and the model has its two tools, `find_tools` and `call_tool` (~250
47
50
  every request plus a line per server, whatever the servers have; `/mcp`
48
51
  says how many). On `api: anthropic` each tool also goes out deferred as
49
52
  `mcp_<server>_<tool>`, so a `find_tools` hit loads it and the model calls it
50
- by that name, as `call_tool` would run it. Stdio servers only, for now.
53
+ by that name, as `call_tool` would run it. A server is a local command (stdio) or a remote one (`url:`, HTTP).
51
54
 
52
55
  ```yaml
53
56
  # config.yml
@@ -69,12 +72,108 @@ bundles:
69
72
  command: [npx, -y, "chrome-devtools-mcp@latest", --slim, --headless]
70
73
  attach_image_paths: true # the default; false leaves a path as text
71
74
  start: lazy # the default; eager: start it with every session
75
+ context7:
76
+ url: https://mcp.context7.com/mcp # a remote server: url instead of command
77
+ linear:
78
+ url: https://mcp.linear.app/mcp # nothing else: chi offers sign-in when the server asks (below)
79
+ github:
80
+ url: https://api.githubcopilot.com/mcp/
81
+ bearer_token_env: GITHUB_MCP_TOKEN # sent as Authorization: Bearer <its value>
82
+ headers: {X-Example: "1"} # optional, sent as given (not for secrets; not chi's own:
83
+ # Accept, Content-Type, Host, Content-Length, Mcp-*…)
84
+ tools: [get_*, list_*] # tools, description, timeout, start: as for a local server
72
85
  ```
73
86
 
87
+ - **Remote servers** (`url:`, http or https; `command:` and `url:` together are a config error). They behave
88
+ like local ones everywhere you look: the first run lists the tools in an init task, later sessions search the
89
+ cache and connect on the first call, and `find_tools`, `call_tool` and the `mcp_<server>_<tool>` guardrail names
90
+ are the same. `/mcp` shows `connected (https://mcp.context7.com)` where a local one shows `running (pid N)`:
91
+ the scheme, host and a non-default port only.
92
+ - **A token:** `bearer_token_env` names the variable that holds it, looked up at each request (never kept or
93
+ saved): the server's `env:`, then the session's project env (its mise env, as `execute` commands get it), then
94
+ the worker's environment. A value with a line break (an env file saved with CRLF ends) is refused, and nothing
95
+ is sent. A worker has the environment of the chi that
96
+ started it, so a new `export` needs a restarted worker (`chi sessions restart`). Keys belong there, not in the
97
+ URL: the debug log's `http` line for each request keeps the URL's path (only the query is cut).
98
+ - **What it says:** with a static token, a 401 is `MCP server github didn't connect: refused the token (401)`
99
+ (a server without one signs in: below); an unset or empty variable is
100
+ `… didn't connect: GITHUB_MCP_TOKEN is not set`, and nothing is sent. A cached server that doesn't connect
101
+ (the network, a token you are about to fix) stays cached: the call answers the error, there is one notice per
102
+ distinct message, and the next call tries again in the same session (a `start: eager` one too: its init card
103
+ says `its next call tries again`). A redirect is never followed: the error
104
+ names the new origin.
105
+ - chi speaks the current MCP revision (2026-07-28) first and falls back to the older handshake (`initialize`,
106
+ with its session when the server gives one) for a server that doesn't answer it; answers may be JSON or an SSE
107
+ stream.
108
+ - Not there yet: live tool-list changes from a remote server (its saved list is refreshed
109
+ daily, as for a local one), and asking for more scope on a 403 `insufficient_scope` (the spec's step-up: chi
110
+ shows `refused (403)`). A remote server's text never attaches a local image (`attach_image_paths` is off
111
+ for it); its image blocks attach as usual.
112
+
113
+ - **Sign-in (OAuth)** for a remote server with no static token (no `bearer_token_env`, no `Authorization` in
114
+ `headers:`) that answers 401, as Linear's, Sentry's and other hosted servers do (the MCP spec's authorization).
115
+ Nothing happens by itself:
116
+ - `/mcp` shows `linear: needs sign-in (/mcp login linear)`, and one card per session worker says **linear needs
117
+ sign-in** with a **Sign in** button (it runs `/mcp login linear`). It shows outside a turn's block, never on a
118
+ one-shot (`-p --non-interactive`); a 401 on a participant's turn holds it for the owner's next turn end or
119
+ command. A tool call answers at once, `linear needs sign-in: the user runs /mcp login linear` (on a
120
+ participant's turn `… the session's owner signs in`), and never waits for a browser; a search's note, and a call
121
+ to a server whose tools aren't known yet, say `linear needs sign-in (the session's owner runs /mcp login
122
+ linear)`. A session that needs sign-in finds one made in another session: its next call connects (`/mcp` says
123
+ `signed in from another session`, and `/mcp login` there answers that it is signed in already).
124
+ - `/mcp login linear` answers `Opening sign-in for linear…` and does the rest on a thread of its own: it asks the
125
+ server's sign-in data (the 401's `resource_metadata`, else the well-known addresses), its provider's metadata,
126
+ and registers chi there (dynamic registration, kept per provider and reused) unless you configured a client
127
+ (below). Then the sign-in card: **Open sign-in page**, or the address printed in the terminal; a browser on
128
+ another device ends on a page that doesn't load: paste its address with `/callback`. After you approve, the card
129
+ becomes **Signed in to linear** (the tool count) and the server connects. A sign-in waits 5 minutes.
130
+ - The token is kept per address for the whole machine (every session and project with that `url:`), in chi's
131
+ secrets (`$XDG_STATE_HOME/samagotchi/plugins/mcp/secrets/`, 0600 files kept from chi's own file tools), never in
132
+ a log, a card or the session. A kept token goes only to the address it was given for. It is renewed by itself:
133
+ shortly before it runs out (a minute, or half its life), and once when the server answers 401; two workers
134
+ spend one refresh token between them (the second takes the first one's new token). A refused renewal (the
135
+ provider says `invalid_grant`) forgets it: needs sign-in again, and its card again. Another failure keeps it and
136
+ the call says the server isn't reachable; the next call tries again. A renewal takes at most 30 s (12 s for the
137
+ request, 18 s waiting for another worker's), outside the call's `timeout`.
138
+ - `/mcp logout linear` forgets the token (and asks the provider to revoke it, best effort); chi's registration
139
+ with the provider stays. Other sessions keep the access token they hold until it runs out or is refused, then
140
+ need sign-in.
141
+ - What it refuses, each on the card: sign-in data for another address, a provider whose metadata names another
142
+ one, one without PKCE (S256), an address that isn't https (http only when the server itself is on a loopback
143
+ host: 127.0.0.1, ::1, localhost), an address discovery names that is a private, shared (100.64/10), loopback or
144
+ link-local one (the server's own `url:` host and a configured `issuer:` host may be: a server on your network
145
+ or tailnet signs in), a redirect, a document over 256 KB, a callback naming another provider (`iss`). A `url:`
146
+ with a query (`?key=…`) can't sign in.
147
+ - **A client you registered yourself**, for a provider that has no dynamic registration (`oauth:`, all optional;
148
+ `oauth:` and a static token are one or the other):
149
+
150
+ ```yaml
151
+ github:
152
+ url: https://api.githubcopilot.com/mcp/
153
+ oauth:
154
+ client_id: Iv1.abc # your client at the provider
155
+ issuer: https://github.com/login/oauth # required with client_id: the provider it was made at
156
+ client_secret_env: GITHUB_MCP_CLIENT_SECRET # sent to the token endpoint only
157
+ scopes: [repo, read:org] # else the 401's scope, else the server's own list
158
+ redirect_port: 8765 # when the provider wants one exact redirect (http://127.0.0.1:8765/callback)
159
+ ```
160
+
161
+ A server that now names another provider than `issuer:` is refused, so it can't collect the secret; a renew
162
+ sends the secret only for a sign-in made as that client at that provider. GitHub's
163
+ remote server: use a personal access token (`bearer_token_env`); `oauth:` there is untested.
164
+ - `client_metadata_url:` (under `bundles: mcp:`) is the address of chi's client document (`pages/oauth/client.json`
165
+ in chi's repository, a client id metadata document): a provider that says it takes one gets it as chi's client
166
+ id, with no registration; one that refuses it gets a registration (for that session worker). The Pages
167
+ workflow (`.github/workflows/pages.yml`) publishes `pages/` from main, so it is served at
168
+ `https://dmitry.it/samagotchi/oauth/client.json` (the owner's custom domain: GitHub Pages redirects github.io
169
+ there, and a client id must equal the address it is fetched from). That address is the default; set your own
170
+ document's address to use it instead, or `client_metadata_url: false` for none (every provider gets a registration).
171
+
74
172
  - **Start: from a cache, on the first call.** A server's `tools/list` is
75
173
  saved in the bundle's data dir (`$XDG_STATE_HOME/samagotchi/plugins/mcp/
76
174
  tools-<server>.json`), keyed by a digest of its `command`, `env` (names
77
- and values: only the digest is stored) and `cwd`. A session with a saved
175
+ and values: only the digest is stored) and `cwd` (a remote server's: its
176
+ `url`, `headers` and `bearer_token_env`, never the token's value). A session with a saved
78
177
  list can search its tools at once and **doesn't start the server**: the
79
178
  first call of one of its tools does (the call's row shows the wait). So a
80
179
  session that never uses MCP spawns nothing, and a new session opens without
@@ -186,7 +285,7 @@ bundles:
186
285
  server a second, then TERMs and KILLs its group (the server's helpers
187
286
  too). A server that leaves its group (`setsid`) is out of its reach.
188
287
  - **`/mcp`** (anytime) shows a card with the servers, their state (cached
189
- (not started), running with its pid, failed with its count, stopped) and
288
+ (not started), running with its pid, connected with its origin for a remote one, failed with its count, stopped) and
190
289
  their tools as `<server>/<tool>`, the name `call_tool` takes.
191
290
  A cached or running server's line says roughly how many tokens its tool
192
291
  definitions take (`~4,232 tokens`), which only a search's answer carries
data/docs/cli.md CHANGED
@@ -28,7 +28,8 @@
28
28
  - `chi schedule <add|list|show|tick|run-now|enable|disable|cancel>` — durable schedules on this machine: a prompt with a clock that fires out of no worker (cron, systemd, or chi web's hub with `schedule.auto_tick`), as the next link of a session's chain or as a turn in the session itself (see [Scheduling](scheduling.md) and [Durable schedules](#durable-schedules-chi-schedule)). A usage error exits 2, an unknown session or schedule 1; `chi --remote X schedule list` exits 2
29
29
  - `chi remote add NAME URL [--token-file F | --token-stdin]`, `chi remote ls`, `chi remote rm NAME` — the other machines whose chi web the session commands reach with `--remote NAME` (see [Remote sessions](#remote-sessions))
30
30
  - `chi share ID --name NAME [--identity EMAIL] [--expires 3d] [--cap 2]`, `chi share ls [ID]`, `chi share cap ID P DOLLARS`, `chi share revoke ID [P] | --all` — invite a participant into a session through chi web on the LAN, whose turns act under your guardrails (a link of their own, 7 days, a $2 spending cap), list them, change one's cap, revoke them (see [Participants](#participants))
31
- - `chi --remote NAME send|answer|note|context|sessions|share …` (or `CHI_REMOTE=NAME`) — those commands on that machine's sessions, through its chi web (see [Remote sessions](#remote-sessions))
31
+ - `chi mcp serve` — chi as an MCP server on stdio: an MCP host (Claude Code, Codex) drives the sessions with four tools (`chi_sessions`, `chi_ask`, `chi_wait`, `chi_answer`); `claude mcp add chi -- chi mcp serve`. chi web serves the same at `POST /api/mcp` (see [chi as an MCP server](mcp-server.md))
32
+ - `chi --remote NAME send|answer|note|context|sessions|share|mcp …` (or `CHI_REMOTE=NAME`) — those commands on that machine's sessions, through its chi web (see [Remote sessions](#remote-sessions))
32
33
  - `chi --remote NAME --attach ID` (`--resume ID`, `--dir DIR [-p TEXT]`) — the attached TUI on a session of that machine (see [Remote sessions](#remote-sessions))
33
34
  - `chi memory ls [--scope project|system] [--format text|json]` — the memories of both scopes (this folder's project first), one row each: scope, name, size, date, `from <bundle>`, the index description and its model overlays; `chi memory rm NAME [--scope project|system]` removes one as `memory_write` with `remove: true` does: its file and model overlays go to the bundle trash (the line names the dir; `chi bundle trash` lists and empties it) and its index line is dropped. NAME in both scopes without `--scope` exits 2 naming both; a missing NAME or a bundle's memory (`chi bundle uninstall` removes it) exits 1. `chi memory usage [--scope project|system] [--top N] [--format text|json]` reports what the memories cost over the saved sessions: each scope's index tokens and how many of its lines name a memory nobody read, the memories read most by tokens, and the user's own memories no saved session read (`--top` caps the rows per section, 10; no sessions says so and exits 0) — see [Memory: What the memories cost](memory.md#what-the-memories-cost)
34
35
  - `chi desktop install|upgrade|uninstall|status` — the macOS "Send to chi" helper: a Service and a ⌃⌥⌘N hotkey that send text or images to a session (live, stopped or new) as a message (⏎, a turn runs) or a context note (⌘⏎) (see [Desktop helper](desktop.md))
@@ -37,7 +38,7 @@
37
38
  - `chi update [--dry-run] [--to VERSION] [--json] [--no-gem] [--no-bundles] [--no-desktop]` — update an installed chi: the gem, the system bundle, the shipped bundles you installed and the desktop helper, and check the bundles from elsewhere, in one table (see [Updating](#updating))
38
39
  - `chi home`, `chi home set [--ruby PATH]`, `chi home doctor` — the chi home: the one Ruby (and its gem path) every chi launch boots, whoever launches it. `chi home` shows it (its Ruby, the newest chi in it, gem home and path, `mise`, when and by which chi it was set, and the chi you ran when that is another one; exit 1 with the problem when it can't boot chi), `set` records this chi's Ruby and gem path (or `--ruby PATH`'s own; it must have samagotchi), `doctor` checks it and what should follow it, one row each with `ok`, `warn` or `fail` and what to run (exit 1 on a `fail`; see [Checking it](configuration.md#checking-it-chi-home-doctor)). At a terminal, a chi on another Ruby than the home's says so in one dim line a day. This machine only (see [The chi home](configuration.md#the-chi-home))
39
40
  - `chi project`, `chi project init [--new-id | --merge-subfolders] [DIR]` — this folder's project, and making a folder in no git repository one. `chi project` prints how its project was found (`kind` `git`, `marker` or `none`), its `root`, its `top` (where the AGENTS.md chain starts), a marked project's `id` (what its memories and project context are keyed on; else the root's path is) and its project `memories` folder, with a `note` for a marker a repository makes ignored, or a `$HOME` that is a git repository. `init` writes `DIR/.chi/project.yml` with a new `id:` (DIR defaults to this folder and is created when missing), so DIR and every subfolder share one memories folder (kept when DIR moves or is renamed), group their sessions and take `chi context --project`; it writes nothing in a git repository (the repository already is the project, exit 0), says so (with the id) for a folder already marked, refuses `$HOME`, a folder above it and `/` (exit 1), and marks a folder inside another marked project as its own, nested one. On a folder marked without an id (an older chi's marker) it adopts one: the folders keyed by its path move to the id, each leaving a link by its old name, and it says what moved and names memories an earlier path left (refused, exit 1, while a session of the project runs). `--new-id` gives a marked folder a fresh id with a copy of its memories and project context (a copied folder going its own way; refused elsewhere, exit 1). Memories a session on this machine saved in a subfolder before init (keyed by that subfolder's path) are named by `init` and by `chi project` (a `note`); `--merge-subfolders` moves them into the project's memories folder (marking DIR first when it isn't yet): a memory the project has by that name, or a bundle's, stays and is named, an emptied folder is removed; refused, exit 1, while a session in DIR runs; not with `--new-id` (exit 2). It prints the root, the id and the memories folder (with the memories already there: a folder chi ran in at its top keeps them, moved to the id), the running sessions in DIR to restart (`chi sessions restart ID`: their prompt keeps the old project) and, when DIR has saved sessions, that a running chi web groups them after its restart. This machine only. See [Projects without git](memory.md#projects-without-git)
40
- - `chi bundle install|upgrade|uninstall|status|diff|list|build|trash|new|test|check` — manage memory bundles (see [Plugins](plugins.md) and [Bundle hooks](hooks.md#bundle-hooks)); `list` shows the installed ones and the ones shipped with chi, which `install <name>` installs; `upgrade <name>` upgrades an installed bundle by name from the source it came from (its folder, archive or git URL), `upgrade <source>` from a new one; `core` and `dev` are profiles that install a set of them (see [Bundle profiles](memory.md#bundle-profiles-core-and-dev), [Guardrails](guardrails.md), [Bundles](bundles.md#the-btw-bundle), [the mcp bundle](bundles.md#the-mcp-bundle) [the loop-guard bundle](bundles.md#the-loop-guard-bundle), [the check-in bundle](bundles.md#the-check-in-bundle) and [the skills bundle](bundles.md#the-skills-bundle)). `trash` lists and empties the bundle trash (moved files from uninstalls/upgrades). `install`/`upgrade` `--force` overwrites existing entries and also installs a bundle whose `requires_chi` this chi doesn't meet and a memory, plugin or script whose bytes disagree with its manifest `sha256`; without it such a bundle or file is refused (exit 1), nothing written. A plain `install` of a bundle that is already installed from the same source rewrites its rules, plugin, scripts and record: the summary lists a file that already holds the bundle's bytes as `Up to date: …`, one you wrote as `Skipped: …`, and ends with `NAME was already installed from SOURCE: its rules, plugin and scripts now match it and its record was rewritten` (plus, when a memory was kept, `your own copies of its memories were kept (chi bundle upgrade NAME merges the bundle's changes into them)`). A source with class-file hooks (`hooks/*.rb` or a manifest `hooks:` entry) is refused, `--dry-run` too; an older install's hooks are removed by the next install or upgrade (`Removed (chi no longer loads class-file bundle hooks): …`, an edited one copied to the trash first; see [Class-file hooks are retired](hooks.md#class-file-hooks-are-retired)). `status NAME` lists the bundle's guardrail rules and scripts beside its plugin, each `[ok]`, `[missing]` or `[modified]` (edited: the next install replaces it, its copy kept in the trash; an edited rule doesn't load, so it counts in `issues=`), and `diff NAME` names an edited rule or script with its recorded and current sha256 (chi keeps no base text for them). A usage error (an unknown subcommand or flag, a missing argument, a bad `build --scope`) exits 2, as for the other subcommands. Plain `chi` and `chi web` exit 1 on an unknown flag, a flag missing its value or a stray argument. `new`, `test` and `check` are for writing one: see [Writing a bundle](#writing-a-bundle-new-test-check)
41
+ - `chi bundle install|upgrade|uninstall|status|diff|list|build|trash|new|test|check` — manage memory bundles (see [Plugins](plugins.md) and [Bundle hooks](hooks.md#bundle-hooks)); `list` shows the installed ones and the ones shipped with chi, which `install <name>` installs; `upgrade <name>` upgrades an installed bundle by name from the source it came from (its folder, archive or git URL), `upgrade <source>` from a new one; `core` and `dev` are profiles that install a set of them (see [Bundle profiles](memory.md#bundle-profiles-core-and-dev), [Guardrails](guardrails.md), [Bundles](bundles.md#the-btw-bundle), [the mcp bundle](bundles.md#the-mcp-bundle) [the loop-guard bundle](bundles.md#the-loop-guard-bundle), [the check-in bundle](bundles.md#the-check-in-bundle) and [the skills bundle](bundles.md#the-skills-bundle)). `trash` lists and empties the bundle trash (moved files from uninstalls/upgrades). `install`/`upgrade` `--force` overwrites existing entries and also installs a bundle whose `requires_chi` this chi doesn't meet and a memory, plugin or script whose bytes disagree with its manifest `sha256`; without it such a bundle or file is refused (exit 1), nothing written. `install` and `upgrade` (`--dry-run` too) start with the bundle and its version: `NAME OLD → NEW` when it changes, `NAME VERSION` when it doesn't (or for a new install), and `NAME VERSION (already current)` when the run writes nothing, in place of the `Up to date: …` line. A plain `install` of a bundle that is already installed from the same source rewrites its rules, plugin, scripts and record: the summary lists a file that already holds the bundle's bytes as `Up to date: …`, one you wrote as `Skipped: …`, and ends with `NAME was already installed from SOURCE: its rules, plugin and scripts now match it and its record was rewritten` (plus, when a memory was kept, `your own copies of its memories were kept (chi bundle upgrade NAME merges the bundle's changes into them)`). A source with class-file hooks (`hooks/*.rb` or a manifest `hooks:` entry) is refused, `--dry-run` too; an older install's hooks are removed by the next install or upgrade (`Removed (chi no longer loads class-file bundle hooks): …`, an edited one copied to the trash first; see [Class-file hooks are retired](hooks.md#class-file-hooks-are-retired)). `status NAME` lists the bundle's guardrail rules and scripts beside its plugin, each `[ok]`, `[missing]` or `[modified]` (edited: the next install replaces it, its copy kept in the trash; an edited rule doesn't load, so it counts in `issues=`), and `diff NAME` names an edited rule or script with its recorded and current sha256 (chi keeps no base text for them). A usage error (an unknown subcommand or flag, a missing argument, a bad `build --scope`) exits 2, as for the other subcommands. Plain `chi` and `chi web` exit 1 on an unknown flag, a flag missing its value or a stray argument. `new`, `test` and `check` are for writing one: see [Writing a bundle](#writing-a-bundle-new-test-check)
41
42
 
42
43
  - `chi guardrails replay [--dry-run] [--threshold T] [--model M]` — seed System 1's record from the approvals this machine's sessions already answered: each ask is judged by the configured model and written to `guardrails/judgments.jsonl` with the answer the user gave, then a per-rule table prints (asks, allowed, denied, would-be auto-allows, false allows, asks with no judgment). A parent agent's answer is not the user's: only its deny is replayed, and only where the parent could have allowed. `--dry-run` judges without writing, `--threshold` overrides `guardrails.system_one.threshold` for the table, `--model` the configured model for this run. Exit 2 when `guardrails.system_one.mode` is off or no `host` is set; a usage error exits 2 (see [System 1](guardrails.md#system-1-experimental))
43
44
  - `chi guardrails rule <id>` — print exactly `asks` when that rule is loaded, not disabled and votes `ask` in this `guardrails.mode` for every model; any other line says why not (no such rule, disabled, another mode, it denies, for some models only, rules that failed to load, `guardrails.enabled: false`). Exit 0 either way, 2 for a usage error. It reads config.yml and the installed bundles as a worker does (`GuardrailWiring#rules`) and takes the rule's id, never a command; the [coordinator skill](bundles.md#the-coordinator-bundle) reads it before it merges without asking
@@ -150,7 +151,7 @@ The loop for a bundle you're writing (the whole path: [bundle-authoring.md](bund
150
151
  so run it (and `test`) on code you'd install. The codes, in order: `manifest` (a parse error, verbatim; the run
151
152
  stops), `hooks-retired` (error: a manifest `hooks:` entry, or `hooks/*.rb` files: class-file hooks are retired,
152
153
  hook events from `plugin.rb` with `chi.on`; the run stops), `missing-file`, `unlisted` (warn: a file an install leaves out, by `MemoryFiles`' rules, so a README
153
- isn't one), `sha` (a stale or placeholder sha, or a plugin / script entry with no sha line; `--fix`
154
+ isn't one; with a plugin, a top-level `.rb` its `parts:` don't list), `sha` (a stale or placeholder sha, or a plugin, part or script entry with no sha line; `--fix`
154
155
  rewrites the first two and prints `fixed sha FILE → sha256:…`), `unknown-key` (warn: a manifest key this chi's
155
156
  parser never reads, so it ignores it, one row per key at its line; the install keeps the manifest, so a newer
156
157
  chi reads the key from it with no reinstall, and `chi update`'s re-check names it too), `requires-chi` (this chi doesn't satisfy it:
@@ -771,7 +772,7 @@ them (`ab12cd34 refused: background tasks it started are still running: npm
771
772
  run dev (--stop-tasks stops them first)`, exit 1); `archive --stop-tasks`
772
773
  stops them first (TERM, then KILL) and says so (`archived (stopped its
773
774
  worker; stopped 1 background task)`). `/archive` says the same and names
774
- `chi sessions archive --stop-tasks ID`; the web asks a second confirm. See
775
+ `chi sessions archive --stop-tasks ID`; the web asks in its delete sheet. See
775
776
  [Sessions](sessions.md#archiving-a-session).
776
777
 
777
778
  `chi sessions delete [--force] [--chain] [--stop-tasks] [--dry-run] ID...` deletes sessions for good: the
@@ -1058,6 +1059,14 @@ runs don't back, `not backed: the last command failed` or `not backed: edited af
1058
1059
  All of them run mid-turn too. An edit answers with the new list at once and goes into the conversation between turns.
1059
1060
  Refused while a `--non-interactive` run has the session, as `chi note` is.
1060
1061
 
1062
+ `/callback ADDRESS` finishes a sign-in a bundle started (`ctx.sign_in`: plan 4's `/mcp login` is the first) when
1063
+ the browser ran on another device (a phone, a laptop reaching chi web over the network or SSH) and ended on an
1064
+ `http://127.0.0.1:…` page that doesn't load: copy that page's address and send it here. It runs at once, a turn
1065
+ running or not, and answers `Got it.` or one line why not (`no sign-in is waiting`, `that isn't this sign-in's
1066
+ address`). The address holds a one-time code, so chi shows the line as `/callback …` everywhere (the other UIs, the
1067
+ events, the logs, the shared prompt history); your own terminal's ↑ still has it. A participant can't send it, nor
1068
+ can a parent agent's `chi answer`.
1069
+
1061
1070
  A `/model`, `/llm-context`, `/thinking`, `/reasoning-history` or `/toolkit` change that restarts the prompt cache
1062
1071
  asks first: the reply says what it costs, changes nothing, and names the line
1063
1072
  that applies it (`/thinking low --yes`, `/model qwen --default --yes`). `--yes` (or `-y`) applies it at once.
@@ -1264,6 +1273,15 @@ its code; a prompt copies the text as you typed it. On a phone or a touch
1264
1273
  screen a code block's button sits in a strip above its first line, clear of
1265
1274
  the code.
1266
1275
 
1276
+ A fenced block a bundle draws (```` ```mermaid ```` with chi-mermaid installed) shows as a picture; a click on it
1277
+ opens the picture viewer. When the bundle reports the diagram's parts (its regions), its nodes can be pointed at in
1278
+ the viewer: the mouse over a node outlines it, a tap or click selects it and a card above the zoom bar names it (its
1279
+ label, and its name in the source), a tap on an arrow or its label selects the arrow ("Bridge → Engine · events"), a
1280
+ tap on empty space clears. On a phone a tap takes the nearest node within a fingertip, unless an arrow or its label is
1281
+ right under it. Tab reaches the nodes as one stop, the arrow keys go to the nearest node that way, Enter selects, Esc
1282
+ clears the selection and a second Esc closes. A drag, a pinch and a double tap work as before. A photo, a diagram from
1283
+ a bundle that reports no regions, or one with over 600 parts: the viewer as before, nothing tappable.
1284
+
1267
1285
  A long answer (over 25 lines or 2,000 characters of its text) can be folded
1268
1286
  by hand: a "▾ N lines" row is its top edge once its turn has ended. Click
1269
1287
  it and the answer closes to one line in its own box,
@@ -1640,6 +1658,9 @@ The attached context's chips keep their own second line under the row.
1640
1658
 
1641
1659
  ### Remote sessions
1642
1660
 
1661
+ (For a phone or a script that only needs to send a message and read its answer over HTTP, without chi on that side,
1662
+ see [Thin clients](thin-clients.md).)
1663
+
1643
1664
  The session commands also reach another machine's sessions, through its chi
1644
1665
  web on the LAN: the sessions, workers, memories and code stay there. On the
1645
1666
  other machine (the Studio), run `chi web --web-host lan`; on this one (the
@@ -1669,8 +1690,9 @@ CHI_REMOTE=studio chi context push claude-outbox ab12 < answer.json
1669
1690
  An unknown name exits 2.
1670
1691
  - What runs there: `send` (every form: `--new`, `--wait`, `--queue`,
1671
1692
  `--cut`, `--image`, a session command), `answer`, `note`, a session's
1672
- `context add|push|ls|show|rm` and `sessions
1673
- list|stop|restart|archive|unarchive|delete`. The rest runs on this machine
1693
+ `context add|push|ls|show|rm`, `sessions
1694
+ list|stop|restart|archive|unarchive|delete` and `mcp serve` (an MCP host
1695
+ on this machine driving that one's sessions). The rest runs on this machine
1674
1696
  only and exits 2 with `chi <command> runs on this machine only: run it on
1675
1697
  <remote>`: `context refresh|mute|unmute` and `--project`, `sessions
1676
1698
  stats|prune|clean`, `broadcast` and the machine's own commands (`bundle`,
@@ -409,7 +409,8 @@ made in Keychain Access or by another app may raise an "allow access" dialog the
409
409
  deadline (or add `-T /usr/bin/security`). An unset key's error names the `security` command;
410
410
  `chi self` says `VAR (keychain)`, `chi desktop status` which keys the helper gets.
411
411
  `SAMAGOTCHI_KEYCHAIN=off` turns the Keychain off for a process and everything it starts (the spec suite sets it).
412
- Linux has no fallback: the variable only.
412
+ Linux has no fallback: the variable only. A bundle's own tokens (`ctx.secrets`, a sign-in's) aren't kept here but in
413
+ 0600 files under the state dir ([docs/plugins.md](plugins.md#secrets-ctxsecrets) says why).
413
414
 
414
415
  ### Anthropic Messages hosts
415
416
 
@@ -2122,7 +2123,8 @@ Tailnet Lock is off: a device Tailscale's servers add to your tailnet could reac
2122
2123
 
2123
2124
  chi web as an app on your iPhone's Home Screen that buzzes (the Watch too) when a session needs you: an
2124
2125
  **approval**, a **question**, a **step-limit** question, a **card** that asks (check-in's Nudge / Keep going / Stop),
2125
- or a **failed turn**, also while the app is closed. A tap opens that session; once it is answered anywhere (the Mac,
2126
+ or a **failed turn**, also while the app is closed; chi web's schedule tick also says when it turned off a
2127
+ recurring schedule that kept failing or being skipped ([docs/scheduling.md](scheduling.md#skip-not-failure)). A tap opens that session; once it is answered anywhere (the Mac,
2126
2128
  the phone, `chi answer`), its notification goes when you open the app (or swipe it away; a failed turn's stays until
2127
2129
  you do). Every push shows a notification: iOS turns off an app's pushes after a few that show none.
2128
2130