samagotchi 0.182.0 → 0.183.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 39e6d208e1727e50fcb10c903c2c8cfc2bcb5c659f769de03916a52a527fc216
4
- data.tar.gz: d9b8cca3456163bcec4c133e9559a7ef6e87a60eb6bcbd18537016e4afb4927a
3
+ metadata.gz: fee40e66b9c582b2356f5aa8e4a103f075281afa1a6ceb8fdb2bbc60390333cd
4
+ data.tar.gz: daf41bfd8202356dfa7a6a74b9b79456f88014d15327a84dc95b5849286eb0ae
5
5
  SHA512:
6
- metadata.gz: 5737d57d34e0a8b8c49e776f1a771354a1f5abb2afaff856cc29b73fe0adf6c1740048c3b32df19087a23580d38b6532b5203b286de4fe96c84022a5b684eef9
7
- data.tar.gz: 92dd02c054a4353dfd7ce245b3c6c11ceecbf571922704af64b0cffcde5fc95615309f96165242dac203d05f6b3c6372d372226fcc5afd92ff0a1686edde8619
6
+ metadata.gz: f3476b26b5927a238fc954c298600e5ede566abd73458178c82612ea8736767443289c40a8dd7f578fef15c24984addc0d6d156c2c91e56750c0d7aee01bebe0
7
+ data.tar.gz: e30b31c44bd83c093d4fb60abdd9fae39965fc577cc16e682597d5361e104b68f600bc4c9023187a0470be32ff9a629f4fcf202acc9199eaedd63dbf07ac463a
data/CHANGELOG.md CHANGED
@@ -8,6 +8,72 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.183.0] - 2026-11-22
12
+
13
+ ### Added
14
+
15
+ - chi as an MCP server: `claude mcp add chi -- chi mcp serve` lets Claude Code (or Codex, any MCP host) drive your
16
+ sessions with four tools: list them, ask one and wait for its answer, answer the question it waits on. `chi
17
+ --remote NAME mcp serve` reaches another machine's; chi web serves the same at `POST /api/mcp`. The host counts
18
+ as a parent agent (`guardrails.parent_answers`). See docs/mcp-server.md.
19
+ - The mcp bundle takes remote MCP servers: `url: https://mcp.context7.com/mcp` in place of `command:` under
20
+ `bundles: mcp: servers: <name>:`, with `bearer_token_env: VAR` for a token (sent as `Authorization: Bearer`) and
21
+ optional `headers:`. They work like local ones (the cached tools, `find_tools`, `call_tool`, guardrail names);
22
+ `/mcp` shows `connected (https://host)`. Run `chi update`.
23
+ - The mcp bundle signs in to a remote server that asks (OAuth): a server with no token that answers 401 shows
24
+ `needs sign-in` in `/mcp` and a card with a **Sign in** button; `/mcp login NAME` registers chi with its provider
25
+ and opens the sign-in page (or `/callback` the address from another device). The token is kept per address for
26
+ every session, renewed by itself, and `/mcp logout NAME` forgets it. A client of your own: `oauth: client_id:`
27
+ with `issuer:`. A provider that takes a client id metadata document gets chi's own
28
+ (`https://dmitry.it/samagotchi/oauth/client.json`) with no registration; `client_metadata_url:` names another,
29
+ `false` none. Nothing signs in by itself. See docs/bundles.md (The mcp bundle, Sign-in).
30
+ - For bundle authors: `ctx.card(…, between_turns: true)`, a card from a thread of your own that never lands in a
31
+ running turn's block; `chi.tool_source` groups take `state: :needs_user` (a search and a call say the source's
32
+ line); `Samagotchi::Plugin::Secrets::Busy` and `Unavailable` are stable to rescue.
33
+ - For bundle authors: `ctx.http.stream(method, url, …) { |res| … }`, a streamed answer: the status and headers
34
+ first, then the body as it arrives (`res.each_event` reads Server-Sent Events, `res.each_chunk` the raw pieces).
35
+ Leaving the block closes the connection. The test kit's `bundle.http.stub` takes `events:` and `chunks:`.
36
+ - For bundle authors: a plugin can be split into several files, listed under `plugin: parts:` in manifest.yml
37
+ (each with its sha256; `chi bundle check --fix` fills them). chi checks and loads them in order before the plugin
38
+ file, into the same namespace; `chi bundle status`, `diff`, `build` and `check` know them. See
39
+ [plugins.md](docs/plugins.md#a-plugin-in-several-files).
40
+ - For bundle authors: `ctx.cancel_controller`, the Stop `ctx.cancelled?` reads on this thread (an init task's own, else
41
+ the running turn's), to hand to `ctx.http`'s `cancel:` or a thread of your own.
42
+ - chi web takes a message and answers it in one call (`POST /api/sessions/ID/ask`), for a thin client such as an
43
+ iOS Shortcut or a script: the answer comes back within 35 s, or a wait token to send to `…/wait` until it does.
44
+ `…/answer` takes `wait`, and a new session's 201 has a token too. See docs/thin-clients.md.
45
+ - In the web's picture viewer, a diagram's nodes can be pointed at, when its bundle reports them (chi-mermaid 0.2.0
46
+ 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
47
+ arrow or its label selects the arrow, a tap on empty space clears. On a phone a tap takes the nearest node within a
48
+ fingertip, unless an arrow or its label is right under it. Tab, the arrow keys and Enter reach the nodes; Esc
49
+ clears, then closes. A drag, a pinch and a double tap work as before. For bundle authors: `render` may return
50
+ `{ svg, regions }` when `chi.features.regions` is set ([plugins.md](docs/plugins.md#block-renderers)).
51
+ - For bundle authors: a card action can open an address, `{label:, url:}` (an http(s) one with a host): the web
52
+ draws a link to a new tab with the host named under the buttons, the terminal prints the address whole. It sends
53
+ nothing to the session and doesn't make a card ask. Set `requires_chi: ">= 0.183.0"` by hand.
54
+ - For bundle authors: `ctx.secrets` (`get`, `set`, `delete`, `update`), the bundle's tokens in 0600 files under the
55
+ state dir, apart per bundle; `update` reads, changes and writes under a lock that holds across workers. The test
56
+ kit keeps them in memory (`bundle.secrets`, `bundle.set(secrets: …)`). chi's model is kept off them by accident
57
+ guards: its file tools are refused there, and a shell command naming the folder asks you once.
58
+ - For bundle authors: `ctx.sign_in(title:, button:) { |redirect_uri| address }`, a browser round trip: a card with a
59
+ button to the address, a listener on 127.0.0.1 for the browser's return, and `flow.wait` for its query. A browser
60
+ on another device ends on an address that doesn't load: `/callback <address>` (a new session command) finishes it
61
+ there, shown as `/callback …` everywhere. Timeout, cancel and the worker leaving replace the card; `cancel:`
62
+ (a tool's `ctx.cancel_controller`) lets the turn's Stop end it.
63
+
64
+ ### Changed
65
+
66
+ - chi web asks about a delete in one sheet that says what goes, what is stopped first and what stays, with one button
67
+ that names the outcome (no browser dialog, no second ask). Archive asks in the same sheet when background tasks still
68
+ run, or says why it can't archive now. The tap stops only the tasks the sheet named.
69
+ - In the picture viewer, a double tap whose finger moved a little (up to 10 px) now counts as one.
70
+ - `chi bundle install` and `chi bundle upgrade` (`--dry-run` too) start with the bundle's version: `mcp 0.8.0 → 0.9.0`
71
+ 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.
72
+
73
+ After updating, reload any open chi web page: one still on 0.182.0 shows the mcp sign-in card without its button.
74
+
75
+ Update with `chi update` (bundles: mcp 0.9.0, the dev profile 0.7.9).
76
+
11
77
  ## [0.182.0] - 2026-11-21
12
78
 
13
79
  ### Added
@@ -6644,7 +6710,8 @@ and long-lived sessions.
6644
6710
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6645
6711
  hotkey panel that send selected text or the clipboard to your sessions.
6646
6712
 
6647
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.182.0...HEAD
6713
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.183.0...HEAD
6714
+ [0.183.0]: https://github.com/dm1try/samagotchi/compare/v0.182.0...v0.183.0
6648
6715
  [0.182.0]: https://github.com/dm1try/samagotchi/compare/v0.181.0...v0.182.0
6649
6716
  [0.181.0]: https://github.com/dm1try/samagotchi/compare/v0.180.0...v0.181.0
6650
6717
  [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
 
@@ -348,7 +348,13 @@ engine.unsubscribe(handle: handle)
348
348
  engine.session_state_snapshot # => { status:, message_count:, last_prompt:, event_seq: }
349
349
  ```
350
350
 
351
- `Engine#subscribe` is the seam the SSE bridge (`Samagotchi::Bridge`) rides on. The bridge
351
+ `Engine#subscribe` forwards to the Engine's event log (`SessionObserver`, shown as `Engine#event_log`), and that log
352
+ is the seam the SSE bridge (`Samagotchi::Bridge`) rides on: the Worker reads it once after it built the Engine and hands
353
+ it to the Bridge and to its own collaborators (`ContinueOffer`, `WorkerParticipantGate`, `WorkerTaskWakes`,
354
+ `WorkerInbound`), which subscribe, announce and take the event lock on it directly. The same goes for the turn state,
355
+ the question desk and the steer cut (`Engine#turn_state`, `#question_desk`, `#steer_cut`): the Worker hands them to the
356
+ Bridge (which hands the desk on to `RelayVerifier` and `RelayWatcher`) and to `WorkerInbound`, `WorkerIdleExit` and
357
+ `ContinueOffer`, which call them directly instead of the Engine's forwards. The bridge
352
358
  is the **single live transport** and runs **inside the forked session worker** (the same
353
359
  process that already owns the `Engine`); every worker starts it. It keeps what a client that joins late needs
354
360
  (`RingBuffer` of recent events, `TurnAccumulator` for the turn in progress, `CardStore` for cards and notices), writes
@@ -498,10 +504,13 @@ model: [internals/remote-sessions.md](internals/remote-sessions.md).
498
504
  | `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
505
  | `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
506
  | `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` |
507
+ | `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
508
  | `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
509
  | `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` |
510
+ | `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` |
511
+ | `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`) | 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`; 200 `{status: command, session_id}` for a session command. 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`; 403 `parent_continue_refused`, `parent_answers_refused`; 409 `busy`, `waiting` (neutral words, Busy's fields), `continuing`, `owned_by_tui`, the turn route's delivery refusals (`queue_unavailable`, …); 504 `worker_timeout`; 503 `server_stopping` |
512
+ | `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 |
513
+ | `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
514
  | `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
515
  | `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
516
  | `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` |
@@ -670,12 +679,13 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
670
679
  | 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
680
  | 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
681
  | 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). |
682
+ | 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
683
  | Idle work | `idle_scheduler.rb` (`IdleScheduler`), `idle_recap.rb` (`IdleRecap`), `idle_reminders.rb` | One poller for an idle session's recap and reminders. |
675
684
  | 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
685
  | 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
686
  | 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. |
687
+ | 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`). |
688
+ | 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
689
  | 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
690
  | 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
691
  | 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`, `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
 
data/docs/guardrails.md CHANGED
@@ -252,7 +252,8 @@ the user's alone (`user_only`): `chi answer` and the worker refuse the allow
252
252
  with `only the user can allow it`. The same holds for the guardrails bundle's
253
253
  other user-only rules (`chi-context-cmd`, `chi-broadcast`,
254
254
  `prompt-memory-write`, `model-overlay-write`, and `chi-answer-piped` /
255
- `chi-answer-http`, which answer a grandchild's question as the user).
255
+ `chi-answer-http`, which answer a grandchild's question as the user), and core's
256
+ `bundle-secrets-shell` (a command naming a bundle's secrets).
256
257
 
257
258
  `child-boundary` isn't one of them: an ask before a delegate child acts outside
258
259
  its folder follows the level, so a `soft` parent may give Allow once. If that
@@ -341,6 +342,20 @@ with `writes: true` (symlinks resolved; see
341
342
  `execute` can still reach them; the guardrails bundle asks about shell
342
343
  commands that name them.
343
344
 
345
+ A bundle's secrets ([`ctx.secrets`](plugins.md#secrets-ctxsecrets):
346
+ `<state dir>/plugins/<bundle>/secrets/`) are kept from chi's model whatever
347
+ the call does, reads too:
348
+
349
+ - deny (`bundle-secrets`): `read`, `write`, `edit` and a plugin tool's
350
+ `targets:` paths there (symlinks resolved);
351
+ - ask, once, the user only (`bundle-secrets-shell`, a protected rule): an
352
+ `execute` or `task_create` command that names the folder
353
+ (`…/samagotchi/plugins/<bundle or a glob>/secrets`, or this state dir's
354
+ path spelled out), `ls` and `cat` included.
355
+
356
+ It is an accident guard, not a sandbox: a command that doesn't name the
357
+ folder (one that `cd`s there first, a variable, a script) still reads it.
358
+
344
359
  ## A delegate child's boundary
345
360
 
346
361
  Built in, for [delegate](sessions.md#delegating) children only, in every