samagotchi 0.78.0 → 0.80.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 (77) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/README.md +7 -5
  4. data/docs/cli.md +24 -7
  5. data/docs/configuration.md +11 -6
  6. data/docs/internals/anthropic.md +12 -5
  7. data/docs/internals/bundles.md +4 -0
  8. data/docs/internals/engine.md +15 -5
  9. data/docs/plugins.md +144 -3
  10. data/docs/releasing.md +2 -2
  11. data/docs/sessions.md +1 -1
  12. data/docs/testing.md +32 -2
  13. data/lib/samagotchi/bootstrap/config_writer.rb +13 -3
  14. data/lib/samagotchi/bootstrap/probe.rb +153 -31
  15. data/lib/samagotchi/bootstrap_command.rb +92 -15
  16. data/lib/samagotchi/bridge.rb +1 -1
  17. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/system/self_map.md +1 -1
  19. data/lib/samagotchi/continue_offer.rb +5 -5
  20. data/lib/samagotchi/engine.rb +40 -37
  21. data/lib/samagotchi/guardrails/approval.rb +6 -4
  22. data/lib/samagotchi/guardrails/gate.rb +7 -3
  23. data/lib/samagotchi/hooks/bundle_loader.rb +31 -16
  24. data/lib/samagotchi/hooks/registry.rb +44 -3
  25. data/lib/samagotchi/host_registry.rb +12 -4
  26. data/lib/samagotchi/llm/adapter_common.rb +8 -4
  27. data/lib/samagotchi/llm/anthropic_binding_recovery.rb +198 -0
  28. data/lib/samagotchi/llm/anthropic_messages.rb +39 -178
  29. data/lib/samagotchi/llm/anthropic_wire.rb +7 -1
  30. data/lib/samagotchi/llm/chat_loop.rb +21 -12
  31. data/lib/samagotchi/llm/http.rb +12 -7
  32. data/lib/samagotchi/llm/model_listing.rb +29 -1
  33. data/lib/samagotchi/llm/refusal_memo.rb +3 -2
  34. data/lib/samagotchi/plugin/card.rb +44 -0
  35. data/lib/samagotchi/plugin/context.rb +53 -8
  36. data/lib/samagotchi/plugin/http.rb +154 -0
  37. data/lib/samagotchi/plugin/http_transport.rb +77 -0
  38. data/lib/samagotchi/plugin/loader.rb +29 -10
  39. data/lib/samagotchi/question_answer.rb +29 -0
  40. data/lib/samagotchi/question_desk.rb +30 -22
  41. data/lib/samagotchi/reasoning_history.rb +2 -1
  42. data/lib/samagotchi/relay_verifier.rb +1 -1
  43. data/lib/samagotchi/testing/boundary.rb +156 -0
  44. data/lib/samagotchi/testing/bundle.rb +349 -0
  45. data/lib/samagotchi/testing/fake_executable.rb +42 -0
  46. data/lib/samagotchi/testing/fake_http.rb +137 -0
  47. data/lib/samagotchi/testing/helpers.rb +56 -0
  48. data/lib/samagotchi/testing/host.rb +76 -0
  49. data/lib/samagotchi/testing/minitest.rb +31 -0
  50. data/lib/samagotchi/testing/recorder.rb +138 -0
  51. data/lib/samagotchi/testing/recording_api.rb +27 -0
  52. data/lib/samagotchi/testing/rspec.rb +31 -0
  53. data/lib/samagotchi/testing/sandbox.rb +163 -0
  54. data/lib/samagotchi/testing/sessions.rb +77 -0
  55. data/lib/samagotchi/testing/verdict.rb +28 -0
  56. data/lib/samagotchi/testing/waiting.rb +36 -0
  57. data/lib/samagotchi/testing.rb +26 -0
  58. data/lib/samagotchi/tools/delegate_relay.rb +7 -6
  59. data/lib/samagotchi/tools/tool_index.rb +3 -0
  60. data/lib/samagotchi/turn_state.rb +28 -1
  61. data/lib/samagotchi/version.rb +1 -1
  62. data/lib/samagotchi/web/public/app.js +79 -245
  63. data/lib/samagotchi/web/public/composer_grip.js +231 -0
  64. data/lib/samagotchi/web/public/images.js +33 -0
  65. data/lib/samagotchi/web/public/index.html +73 -40
  66. data/lib/samagotchi/web/public/level_chip.js +11 -11
  67. data/lib/samagotchi/web/public/lists_view.js +19 -14
  68. data/lib/samagotchi/web/public/llm_context_chip.js +15 -15
  69. data/lib/samagotchi/web/public/model_picker.js +5 -6
  70. data/lib/samagotchi/web/public/scope.js +3 -3
  71. data/lib/samagotchi/web/public/stage_view.js +3 -2
  72. data/lib/samagotchi/web/public/storage.js +23 -0
  73. data/lib/samagotchi/web/public/strip.js +35 -9
  74. data/lib/samagotchi/web/public/strip_grip.js +76 -0
  75. data/lib/samagotchi/web/public/thinking_chip.js +5 -5
  76. data/lib/samagotchi/web/public/toasts.js +5 -4
  77. metadata +24 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1b19c3433cc4f46956563a8e4e6532d8b60061084b8050b534b9230b3c608c54
4
- data.tar.gz: 97b8e078c43e1c9901139f1f937d16e43b57b6147cd8298fbb9b77abb37c0b96
3
+ metadata.gz: 5e8f390119025dcb6df095574fb9e59e94952c709a69ae6bc6e02ffa037e1a0d
4
+ data.tar.gz: c67e91b18d0ef7ac8916b03045c214c12ebcf98b469f84b0ae355bb41491388e
5
5
  SHA512:
6
- metadata.gz: '0022706491e62a2d7f603a5290fd4c5525b17c6712af6d31dc5ce163b36c4e4414074d7b4da609f890ec5e243ea89b33a5ba0621528d8face6c5226108d0a443'
7
- data.tar.gz: da23fef030284a3401d5ec17017ef2a7d1165d30909f4a96e095823315bc38bbbe1eaf1bdfd76eefe604af19cd160c5f68fd19cb3c4ccb478b28bd9ea1de57eb
6
+ metadata.gz: 4c936b332ee7cafb74cb4e09b7f3b80acac7ba1247988e755078c61e72c201489b1a48f8970c6c3d70d88b7cedc31cf432d01c5b14018073a517b65f76e45de6
7
+ data.tar.gz: dc77457ac7bf6a0018966bef40ccaa67da732a43edbe21e0fbcef1193583a3e00934c70c4230d3fcf14f5dd23012730f9c41bb16be8d7a64754f361ff3c2ab4a
data/CHANGELOG.md CHANGED
@@ -8,6 +8,47 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.80.0] - 2026-10-17
12
+
13
+ ### Added
14
+
15
+ - Web: the message box has an image button next to Start / Send that opens a file picker (on a phone, the camera or
16
+ the photo library); the picked images are added like pasted ones. A message now takes at most 20 images of up to
17
+ 20 MB each as you add them, pasted, dropped or picked, and a toast names the files left out, instead of the send
18
+ failing.
19
+ - Bundles: `samagotchi/testing` (experimental), a test kit for bundles: load a bundle in a sandbox, fire its hooks, run its commands and tools, record steers, notices and cards (RSpec `:bundle` groups or Minitest `Testing::Case`; docs/plugins.md "Testing a bundle"). The shipped bundles' specs now live in each bundle's own `spec/` and use it; a boundary spec keeps bundles on the stable surface.
20
+ - Plugins: `ctx.http`, an HTTP client for calling services (`get`, `post_json`, `request`): short default timeouts, one error type (`Samagotchi::Plugin::HttpError`), a 4xx/5xx returned as a Response, one INFO `http` log line per call without query, headers or body (`purpose=plugin`, `bundle=`), and a call made for the turn stops when the turn is stopped (docs/plugins.md "Calling services"; experimental until 1.0). The test kit fakes it: `bundle.http.stub(…)`, `requests`, `unmatched`, and a request no stub answered fails the test.
21
+ - `chi bootstrap` sets up Anthropic Messages hosts: a server that refuses the OpenAI model list but lists Anthropic's
22
+ way (api.anthropic.com, a Messages-only gateway) is written as `api: anthropic` (the url without `/v1`, `auth: bearer`
23
+ when only Bearer worked), with `dialect: fireworks` for Fireworks' host or model ids. `--api openai|anthropic` and
24
+ `--dialect standard|fireworks` override the detection; direct Fireworks stays `api: openai` with a hint, and a test
25
+ turn's 404 on `/chat/completions` hints `--api anthropic`. A hand-written urlless `api: anthropic` host counts as
26
+ api.anthropic.com, so bootstrapping it again writes nothing.
27
+ - Plugins: `ctx.ask_model(model: "host:id")` asks a configured model (a host:id ref, an alias, or a model one of the hosts lists) instead of the session's; an unknown ref raises `ArgumentError`.
28
+
29
+ ### Changed
30
+
31
+ - Web: the start page says "+ new session" (and "new session in …") instead of "+ new chat", matching the rest of the UI.
32
+ - Web: the latest-sessions strip hides and shows with the same edge grip as the composer's (a drag up hides it, a drag
33
+ down or a click shows it, Enter/Space on the focused grip toggles, and the choice is remembered): the tile's `hide ▴`
34
+ and the top bar's `▴ hide` are gone, and while the strip is hidden its pill — now only its status — opens All
35
+ sessions in one click instead of showing the strip first.
36
+
37
+ Update with `chi update` (the system bundle 0.80.0), then restart `chi web`.
38
+
39
+ ## [0.79.0] - 2026-10-17
40
+
41
+ ### Fixed
42
+
43
+ - Web: a repeated toast cannot unstick a sticky error and make it time out.
44
+ - Anthropic: `api: anthropic` hosts on the Claude API now read their model list, including 1M-token windows and image
45
+ input, so `chi models` and model validation work.
46
+ - Anthropic: on Claude 5.x models, which turn thinking off by `between_tools` and refuse `disabled`, recaps, side
47
+ answers and `--thinking off` sessions now send `thinking: {type: "between_tools"}` after that 400 (a recap used to
48
+ fall back to adaptive thinking at low effort, a `--thinking off` session to the provider's default thinking). Each
49
+ side-answer client learns it once for itself.
50
+ - A host whose model list fails is asked again at most once a minute (it was asked on every context-window lookup).
51
+
11
52
  ## [0.78.0] - 2026-10-17
12
53
 
13
54
  ### Added
@@ -3269,7 +3310,9 @@ and long-lived sessions.
3269
3310
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
3270
3311
  hotkey panel that send selected text or the clipboard to your sessions.
3271
3312
 
3272
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.78.0...HEAD
3313
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.80.0...HEAD
3314
+ [0.80.0]: https://github.com/dm1try/samagotchi/compare/v0.79.0...v0.80.0
3315
+ [0.79.0]: https://github.com/dm1try/samagotchi/compare/v0.78.0...v0.79.0
3273
3316
  [0.78.0]: https://github.com/dm1try/samagotchi/compare/v0.77.0...v0.78.0
3274
3317
  [0.77.0]: https://github.com/dm1try/samagotchi/compare/v0.76.0...v0.77.0
3275
3318
  [0.76.0]: https://github.com/dm1try/samagotchi/compare/v0.75.0...v0.76.0
data/README.md CHANGED
@@ -69,10 +69,12 @@ Point chi at your model server; it works out the rest and writes
69
69
  chi bootstrap 192.168.1.29:8081 # llama.cpp on another machine
70
70
  chi bootstrap localhost:11434 # any OpenAI-compatible server
71
71
  chi bootstrap https://openrouter.ai/api/v1 --key-env OPENROUTER_API_KEY
72
+ chi bootstrap https://api.anthropic.com --key-env ANTHROPIC_API_KEY
72
73
  chi bootstrap # look on this machine's usual ports
73
74
  ```
74
75
 
75
- It finds out whether the server is llama.cpp or OpenAI-compatible, picks the
76
+ It finds out whether the server is llama.cpp, OpenAI-compatible or Anthropic's
77
+ Messages API, picks the
76
78
  model (or asks, when there are several), sends one test request and writes
77
79
  the config. With a config already there, it adds a `hosts:` entry and keeps
78
80
  the rest of the file. Then it installs the `core` bundles (loop-guard,
@@ -127,7 +129,7 @@ pbpaste | chi send -m "same bug?" <id> # a message to a session, the clipboar
127
129
  chi send --new --wait -m "review feat/x" # a new session you can watch in the web; prints the answer
128
130
  ```
129
131
 
130
- `@shot.png` in a prompt (or a pasted/dropped image in the web UI) shows the model an image, when it can see them; see [Images](docs/cli.md#images).
132
+ `@shot.png` in a prompt (or a pasted, dropped or picked image in the web UI) shows the model an image, when it can see them; see [Images](docs/cli.md#images).
131
133
 
132
134
  `/model` switches models, Ctrl-C cancels a turn, and Ctrl-D or `/detach` detaches (the session keeps running; `chi --attach ID` comes back). `/exit` detaches and stops the session's worker too, unless something still needs it (a running turn, another UI); `chi --resume ID` picks the conversation up again. `/exit --delete` also deletes the session once the worker has gone; `chi sessions delete ID` deletes one from the shell. `/archive` (or `chi sessions archive ID`) hides a session from every list and keeps it for good; `chi sessions list --archived` finds it again.
133
135
 
@@ -220,9 +222,9 @@ once, for the session, for the repo, or for the whole rule in the repo.
220
222
  ## Development
221
223
 
222
224
  ```sh
223
- bundle exec rspec # Ruby specs
224
- npm test # web frontend specs
225
- npm run e2e # web UI happy paths in Chromium, fake model (once: npx playwright install chromium)
225
+ bundle exec rspec spec lib/samagotchi/bundles/*/spec # Ruby specs (chi's and the shipped bundles' own)
226
+ npm test # web frontend specs
227
+ npm run e2e # web UI happy paths in Chromium, fake model (once: npx playwright install chromium)
226
228
  ```
227
229
 
228
230
  Integration specs against a live model server, and what the suite isolates: [docs/testing.md](docs/testing.md).
data/docs/cli.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Commands
4
4
 
5
- - `chi bootstrap [HOST[:PORT]|URL]` — first setup: find the model server (llama.cpp or OpenAI-compatible), pick the model, send a test request and write config.yml, or add a `hosts:` entry to an existing one (see [First setup](#first-setup))
5
+ - `chi bootstrap [HOST[:PORT]|URL]` — first setup: find the model server (llama.cpp, OpenAI-compatible or Anthropic Messages), pick the model, send a test request and write config.yml, or add a `hosts:` entry to an existing one (see [First setup](#first-setup))
6
6
  - `chi` — start a session in a background worker and attach the terminal to it, so the Web UI (or another terminal) can share it (see [Sharing a session](#sharing-a-session))
7
7
  - `chi -p "your prompt"` — run a prompt, then stay attached
8
8
  - `chi -p "your prompt" --non-interactive` — run a prompt, print the answer, exit
@@ -33,12 +33,23 @@
33
33
  ```sh
34
34
  chi bootstrap 192.168.1.29:8081 # host:port (an IP or localhost: port 8080 when none; a domain: https 443, then http 80)
35
35
  chi bootstrap https://openrouter.ai/api/v1 --key-env OPENROUTER_API_KEY
36
+ chi bootstrap https://api.anthropic.com --key-env ANTHROPIC_API_KEY
36
37
  chi bootstrap # try localhost 8080, 11434, 1234, 8000
37
38
  ```
38
39
 
39
40
  - **What it is.** llama.cpp's `/props` answering means the native API (no
40
41
  `api:`); otherwise `GET /v1/models` answering means an OpenAI-compatible
41
- server (`api: openai`). A URL with a path is the API base as given
42
+ server (`api: openai`). Only when that list is refused with 400, 401 or 403
43
+ does chi ask Anthropic's way (`anthropic-version`, the key in `x-api-key`,
44
+ once more as Bearer after a 401/403): a list there means Anthropic's
45
+ Messages API (`api: anthropic`, the url without `/v1`; `auth: bearer` when
46
+ only Bearer worked). A server that serves both, such as Splash, stays
47
+ `api: openai`. Fireworks (its host, or model ids under `accounts/fireworks/`)
48
+ on the Messages API gets `dialect: fireworks`; direct Fireworks is found as
49
+ OpenAI-compatible first and stays `api: openai`, with a line saying
50
+ `--api anthropic` takes its Messages API instead. `--api openai|anthropic`
51
+ and `--dialect standard|fireworks` (which implies `--api anthropic`) skip the
52
+ detection. A URL with a path is the API base as given
42
53
  (`…/api/v1`); a domain without a scheme is tried over https, then http.
43
54
  Each request is tried once, with 5 s timeouts, so a refused port answers
44
55
  at once.
@@ -51,8 +62,11 @@ chi bootstrap # try localhost 8080, 11434, 1234, 8000
51
62
  (a terminal gets a numbered list, a script the ids and exit 2). A llama.cpp
52
63
  server also shows its context size and the prompt profile its chat template
53
64
  matches.
54
- - **The test.** One short chat request ("test: answered in 1.1 s"); `--no-test`
55
- skips it. A failed test still writes the config, says so and exits 1.
65
+ - **The test.** One short chat request ("test: answered in 1.1 s"; `POST /v1/messages`
66
+ on `api: anthropic`); `--no-test` skips it. A failed test still writes the config,
67
+ says so and exits 1. A server found as OpenAI-compatible whose `/chat/completions`
68
+ answers 404 gets the hint `try --api anthropic` (a gateway's Messages url that also
69
+ lists the OpenAI way).
56
70
  - **The file.** With no config.yml it writes a small commented one:
57
71
  `default.model` as `<host>:<model>` and one `hosts:` entry named `local`
58
72
  (localhost), `lan` (an IP) or after the domain (`openrouter`); `--name`
@@ -662,9 +676,12 @@ A model that can see images gets them these ways:
662
676
  - **A path in plain words**: "check /home/me/shot.png and describe it". The
663
677
  model calls `read` on it and sees the picture; the tool line ends in
664
678
  `→ image 1280×800`.
665
- - **The Web UI**: paste or drop images into the composer. Each shows as a chip
666
- (× removes it) and is sent with the message; an image alone is sent as
667
- `[image: name]`. Messages show thumbnails; a click opens one full size.
679
+ - **The Web UI**: paste or drop images into the composer, or pick them with
680
+ its image button (left of Start / Send; on a phone it offers the camera and
681
+ the photo library, and is hidden while a turn runs). Each shows as a chip (× removes it) and is sent with the
682
+ message; an image alone is sent as `[image: name]`. A message takes up to 20
683
+ images of up to 20 MB each; a toast names the files left out (over a cap, or
684
+ not an image). Messages show thumbnails; a click opens one full size.
668
685
  - **`chi send --image PATH`** (repeatable, up to 20) with a message, from a
669
686
  script or another terminal: `chi send --image shot.png -m "why is this red?"
670
687
  3fa2`. The attached terminal and the web show it like an image typed there.
@@ -10,8 +10,8 @@ Chi reads its settings from three places; the first that sets a value wins:
10
10
 
11
11
  then the built-in default. [All settings](#all-settings) lists them.
12
12
 
13
- `chi bootstrap HOST[:PORT]` writes a first config for a model server, or adds
14
- it to this file as a `hosts:` entry (see [First setup](cli.md#first-setup)).
13
+ `chi bootstrap HOST[:PORT]` writes a first config for a model server (llama.cpp, OpenAI-compatible or Anthropic
14
+ Messages), or adds it to this file as a `hosts:` entry (see [First setup](cli.md#first-setup)).
15
15
 
16
16
  Default path:
17
17
 
@@ -343,6 +343,9 @@ hosts:
343
343
 
344
344
  `auth:` works on any host (`bearer` is the default everywhere but `api: anthropic`).
345
345
 
346
+ `chi bootstrap https://api.anthropic.com --key-env ANTHROPIC_API_KEY` writes such an entry (a gateway: its url;
347
+ `--api anthropic` / `--dialect fireworks` when the detection can't tell, see [First setup](cli.md#first-setup)).
348
+
346
349
  **Claude 5.x preserved thinking:** Claude 5.x models (Opus, Sonnet and Haiku 5.5, Fable 5.1) bind each thinking
347
350
  block to everything before it: the system prompt, the tools and the earlier messages. chi keeps the history
348
351
  append-only, but the system prompt or the tools can change under a session: a resume or a worker respawn after
@@ -644,8 +647,10 @@ What each backend gets:
644
647
  | Messages host, `dialect: fireworks` | `thinking: {type: "disabled"}` | `thinking: {type: "adaptive"}` and `output_config: {effort: <level>}` (no `display`) |
645
648
 
646
649
  On a Messages host `default` sends nothing: the provider's own default, which differs by model (some Claude models
647
- think adaptively but show no thinking text, their blocks still going back; others, and Splash, don't think at all). A model that refuses `disabled` (current
648
- Claude models) gets the request again without it, as on any chat host. A model that refuses adaptive thinking
650
+ think adaptively but show no thinking text, their blocks still going back; others, and Splash, don't think at all). A model that refuses `disabled` and names `between_tools` in the 400 (Claude 5.x) gets `thinking: {type:
651
+ "between_tools"}` wherever `off` asked for `disabled`, from then on: the adapter keeps that per model for as long as it
652
+ lives, so a worker's turns keep it, and each side-answer client (recap, `ctx.ask_model`, a broadcast's triage) learns it
653
+ once for itself. One that refuses `disabled` without naming it gets the request again without it, as on any chat host. A model that refuses adaptive thinking
649
654
  (older Claude: Haiku 4.5) is switched, once and for the worker's life, to the budget form: `thinking: {type:
650
655
  "enabled", budget_tokens: B}` with B 2048 / 8192 / 24576 for low / medium / high and no effort; `max_tokens` always
651
656
  stays above the budget (the budget is lowered to leave 1024 for the answer, or `max_tokens` raised to 2048). A
@@ -1465,8 +1470,8 @@ its own). The first target is a long session such as a day-long coordinator, whe
1465
1470
  (the same flags on `chi send --new`), in the session with `/llm-context strategy … apply … budget …`
1466
1471
  (docs/cli.md, "Session commands"), or from the web's `llm ctx` chip in the info bar.
1467
1472
  - **A new web chat:** the start page's `llm ctx` chip, beside the model picker, shows the picked model's values
1468
- and follows a model pick. Its form (titled "new chat") sets a choice for that one chat: the chip reads
1469
- `llm ctx stale · new chat` in the accent colour, and the create sends it as `POST /api/sessions`'s
1473
+ and follows a model pick. Its form (titled "new session") sets a choice for that one chat: the chip reads
1474
+ `llm ctx stale · new session` in the accent colour, and the create sends it as `POST /api/sessions`'s
1470
1475
  `llm_context` (`{"strategy": "stale,forget", "apply": "turn_end", "budget": "64k"}`, each a word as
1471
1476
  `/llm-context` takes it, `default` for unset; anything else answers `400 invalid_llm_context` and starts
1472
1477
  nothing), so the session file holds it before the first turn runs. It is not remembered: it resets after a
@@ -17,7 +17,7 @@ ChatLoop::Run#generate
17
17
  → POST {base}/v1/messages # LLM::HTTP: retries, cancel, first-token limit
18
18
  → AnthropicAssembly#add per SSE event # → ChatResponse (text, reasoning, tool_calls, usage,
19
19
  # finish_reason, provider_content)
20
- → a signature 400 (Claude 5.x preserved thinking): #binding_recovery, then the same
20
+ → a signature 400 (Claude 5.x preserved thinking): AnthropicBindingRecovery#advance, then the same
21
21
  request with drop_block or the blocks stripped; ChatResponse#thinking_drop names them
22
22
  → a 400 it can fix: #refusal_fix, then the same request again (once per kind)
23
23
  → ChatLoop#settle_dropped_thinking! # the dropped blocks leave the stored model entries
@@ -31,6 +31,7 @@ Paths are under `lib/samagotchi/llm/`.
31
31
  |---|---|
32
32
  | `adapters.rb` | `Adapters::BY_API` (`openai`, `anthropic`), `.for(entry)`, `.build(api:, …)` for side requests (`IdleClient`) |
33
33
  | `anthropic_messages.rb` | `AnthropicMessages`: the request body, `#chat` (streamed or not), the 400 fixes, `#list_models`, `#thinking_fields`, `#replays_content?` |
34
+ | `anthropic_binding_recovery.rb` | `AnthropicBindingRecovery`: the preserved-thinking recovery (`#advance` picks drop_block or strip for a signature 400, `#recovered_body`, `#with_thinking_drop`); one per adapter |
34
35
  | `anthropic_wire.rb` | `AnthropicWire`: ChatLoop's wire messages as Messages' `system` and `messages`, the two breakpoints, tool ids and names |
35
36
  | `anthropic_assembly.rb` | `AnthropicAssembly`: a response from a whole body (`.from_message`) or stream events (`#add`), its usage in the OpenAI shape |
36
37
  | `dialect.rb` | `Dialect` (`STANDARD`, `FIREWORKS`): what a provider's `/v1/messages` does differently |
@@ -54,7 +55,8 @@ with `tool_choice: {type: "auto"}` (when any), then the loop's options. The opti
54
55
  (`default.max_tokens`), else the model list's `max_tokens` capped at `DEFAULT_MAX_TOKENS` (64000), and never over an
55
56
  output cap a 400 named. `#with_budget_room` keeps `max_tokens` above a budget-form `budget_tokens` plus `MIN_BUDGET`.
56
57
 
57
- `#thinking_fields(level)` is the thinking level on this wire: `off` is `thinking: {type: "disabled"}`; `low`, `medium`
58
+ `#thinking_fields(level)` is the thinking level on this wire: `off` is `thinking: {type: "disabled"}` (sent as `{type:
59
+ "between_tools"}` to a model whose 400 for `disabled` names that form, Claude 5.x: see the 400 fallbacks); `low`, `medium`
58
60
  and `high` are `thinking: {type: "adaptive", display: <dialect's>}` with `output_config: {effort: <level>}`; `default`
59
61
  sends nothing. `#thinking_off_refused_fields` (low effort) is what `IdleClient` sends a side ask whose model refused
60
62
  thinking off.
@@ -137,7 +139,7 @@ A model switch never 400s: the API drops blocks another model can't read silentl
137
139
 
138
140
  **Recover on the 400, then settle.** Normal requests carry no beta header and no `block_binding`, so Fireworks,
139
141
  Splash and gateways see the same bytes as before. On a signature 400, before anything streamed,
140
- `AnthropicMessages#binding_recovery` picks the next step, once each per request:
142
+ `AnthropicBindingRecovery#advance` (one per adapter, `anthropic_binding_recovery.rb`) picks the next step, once each per request:
141
143
 
142
144
  - **drop_block**: the same body with `thinking.block_binding: {prefix_mismatch_behavior: "drop_block"}` (the body's
143
145
  adaptive or enabled thinking, `display` as sent; adaptive when the level sends none) and the header
@@ -178,7 +180,9 @@ Why not send drop_block on every request: it needs adaptive or enabled thinking
178
180
  thinking field, `off` sends disabled), it would put a beta header on every request to every host, and it would drop
179
181
  the same blocks again on every request until something pruned them. The reactive form does the same work in one
180
182
  place, for one extra 400 round trip per break. The `anthropic-thinking-prefix-mismatch` diagnosis header (on the
181
- 400, undocumented) is kept on the provider error and logged as `diagnosis` on `thinking_recovered`.
183
+ 400, undocumented) is named by the adapter to its `LLM::HTTP` (`diagnosis_header:`, from
184
+ `AnthropicBindingRecovery::DIAGNOSIS_HEADER`), which keeps it on the provider error; it is logged as `diagnosis` on
185
+ `thinking_recovered`. The shared transport reads no provider header of its own.
182
186
 
183
187
  ## Cache breakpoints
184
188
 
@@ -209,12 +213,15 @@ thinking, nil for none), `cache_breakpoints` and `session_header`.
209
213
 
210
214
  `AnthropicMessages#chat` handles the 400s it can fix itself, once each per request, and remembers the fix for the
211
215
  adapter's life, so ChatLoop's broader paths never see them (`#refusal_fix`, logged under `http`; kept in an
212
- `LLM::RefusalMemo`, locked, since the turn, side-ask and recap threads share the host's adapter):
216
+ `LLM::RefusalMemo`, locked, since the turn thread and the model-list reads share the host's adapter; `IdleClient`,
217
+ whose recap, side answers and triage each build their own adapter (`Adapters.build`), keeps what it learned for that
218
+ client's life only):
213
219
 
214
220
  | 400 about | Fix | Remembered |
215
221
  |---|---|---|
216
222
  | `thinking.display` (`DISPLAY_RE`) | no `display` from now on (`#without_display`), the thinking kept | per host (`thinking_display_refused`) |
217
223
  | adaptive thinking or its effort (`ADAPTIVE_REFUSED_RE`) | the budget form: `thinking: {type: "enabled", budget_tokens: BUDGETS[level]}`, no effort (`#budget_form`) | per model (`thinking_form_switched`) |
224
+ | `thinking: {type: "disabled"}` where the 400 names `between_tools` (`THINKING_OFF_FORM_RE`; Claude 5.x) | `thinking: {type: "between_tools"}` wherever `disabled` was asked (`#thinking_between_tools`), so a recap or side answer (`IdleClient` step 0) and a `--thinking off` session never fall back to adaptive low or to no thinking fields; a model that refuses `between_tools` too raises the 400 as before | per model (`thinking_off_form_switched`) |
218
225
  | `cache_control` | no breakpoints | per host (`cache_control_refused`) |
219
226
  | `max_tokens: N > M` (`OUTPUT_CAP_RE`) | `max_tokens` capped at M | per model (`output_cap`) |
220
227
  | `block_binding` or the binding beta, on a drop_block retry (`thinking_binding_unsupported?`) | the strip instead (Preserved thinking) | per host (`binding_controls_refused`) |
@@ -44,6 +44,10 @@ user-facing side (what a bundle owns, profiles, needs) is in [memory.md](../memo
44
44
  Readers of the installed state: `Hooks::BundleLoader` (Engine), `GuardrailWiring#bundle_rules`, `Plugin::Loader`,
45
45
  `ContextProviders` (scripts), `BundleNeeds` (index markers). Each goes through `Provenance.each_installed` / `#record`
46
46
  and checks the recorded sha256 (and `requires_chi`) before loading.
47
+ The checks live in `Hooks::BundleLoader.load` and `Plugin::Loader.load_bundle`; the loading itself is
48
+ `BundleLoader.load_hook_file` (one hook file, into a given `namespace:`) and `Plugin::Loader.register_file` (one
49
+ plugin file: build, `register`, `commit!`), which raise instead of logging: the bundle test kit
50
+ (`Samagotchi::Testing::Bundle`) loads a bundle's source through them, unchecked.
47
51
 
48
52
  ## Installer#run, in order
49
53
 
@@ -273,8 +273,8 @@ One iteration with tool calls:
273
273
  → an ask verdict: Gate#settle_ask (asks the user, records waited_ms)
274
274
  → KernelLoop#dispatch_tool_call, or the denial text
275
275
  → :tool_call_completed, then the :after_tool_call hook
276
- → returns {output:, capped_output:, truncated:, activity:, images:, shown_params:,
277
- shown_label:, diff:}
276
+ → returns a ToolRun value object with output, capped_output, truncated, activity, images, shown_params,
277
+ shown_label, refs, diff and output_file; fields a call doesn't produce are nil
278
278
  → :tool_dispatch_completed {iteration, call_count}
279
279
  → native: ToolResponse.joined(runs, ids:), one entry with the capped outputs
280
280
  chat: ToolResponse.single(run, tool_call_id:, ids:) as each call finishes (the block), with the
@@ -350,14 +350,22 @@ read: the idle scheduler, the Bridge's request threads, plugin threads, the UIs.
350
350
  TurnState
351
351
  ├── running?
352
352
  ├── controller (the running turn's CancellationController)
353
+ ├── thread, ended (the turn's own thread; its end event is out: post-turn work)
353
354
  ├── sink (the turn's on_event)
354
355
  ├── steers (plugin steers for the running turn's next boundary)
355
356
  ├── carried_steers (for the next turn that begins)
356
357
  └── activity clock (last_activity_at, activity_seq)
357
358
  ```
358
359
 
359
- - `begin!(controller:, sink:)`: running, with controller and sink, in one step; carried steers become steers.
360
- - `finish!`: not running, controller and sink cleared; returns the steers never taken (logged as dropped).
360
+ - `begin!(controller:, sink:)`: running, with controller and sink (and the calling thread, the turn's own), in one
361
+ step; carried steers become steers.
362
+ - `ended!`: the turn's end is decided (`end_turn`, next to `turn.ended`): its after_turn / session_end hooks run
363
+ after it and before `finish!`.
364
+ - `own_controller(handler:)`: the controller for work done for the turn itself, which a plugin's `ctx.http` call
365
+ without `cancel:` stops with (`Plugin::Host#cancel_controller`, `Engine#plugin_cancel_controller`): the turn's, on
366
+ its thread or inside a plugin handler, until `ended!`; nil elsewhere (an anytime command, a service, a plugin's
367
+ own thread) and outside a turn. An init task's own controller wins inside one.
368
+ - `finish!`: not running, controller, thread and sink cleared; returns the steers never taken (logged as dropped).
361
369
  - `steer(text, source:)`: queues a steer for the running turn (false with no turn).
362
370
  - `steer_next_turn(text, source:)`: queues a steer for the next turn that begins.
363
371
 
@@ -515,7 +523,8 @@ Engine initialization (in this order, among other things):
515
523
  @tools = Tools::Builtins.registry; @command_registry (SessionCommands' built-ins); @plugin_tasks
516
524
  @toolkit_binding (ToolkitBinding: the kits, the plugins' among them, and the turn-start apply)
517
525
  @thinking_notices (ThinkingNotices); @tool_index = Tools::ToolIndex.new; @peer_sources = PeerSources.new
518
- the bundles' plugins load (load_plugins → ExtensionLoad#load_plugins),
526
+ the bundles' plugins load (load_plugins → ExtensionLoad#load_plugins; each plugin's ctx is a
527
+ Plugin::Context over plugin_host, whose ctx.sessions it builds itself: the test kit passes its own, sessions:),
519
528
  then (plugins or not) @tool_index.declare(@tools): find_tools + call_tool (source "index", not core),
520
529
  declared per toolkit by Registry#declared? (a source registered at load, or a reachable built-in) and
521
530
  sets call_tool's unwrap (Tools::ToolIndex: the chi group from Registry#reachable_names, the sources'
@@ -728,6 +737,7 @@ Paths are under `lib/samagotchi/`.
728
737
  | `toolkit_binding.rb` | `ToolkitBinding`: the Engine's toolkit seam (the kits, `#explained`, `ctx.use_toolkit`, the turn-start `#apply!` behind `Engine#apply_toolkit!`) |
729
738
  | `hooks/registry.rb` | Hook registry, fire order, `Hooks::Runtime` |
730
739
  | `hook_routes.rb` | `HookRoutes`: the Engine's routes for a hook's or plugin's notice (`:hook_notice`, `fallback_for:`), question, stop and steer, and the guardrails' after-load line |
740
+ | `question_desk.rb`, `pending_question.rb`, `question_answer.rb` | `QuestionDesk`: the one open question (ask, post, answer, cancel, relay mark); `PendingQuestion` and `QuestionAnswer`, its values (Hashes only in events, Bridge JSON, the session file and the hook/plugin `ask_user` result) |
731
741
  | `event_routes.rb` | `EventRoutes`: where a card (`Engine#show_card`), a notice (`HookRoutes#notify`) and a guardrails line (`#guardrail_notify`, turn or between turns only) go: held while the plugins load, an anytime command's, an init task's, a running turn's event, else announced or held for `holding_announcements` |
732
742
  | `engine_peers.rb`, `peer_sources.rb` | `Engine::PeerView` (what the kernel's peer tools see of the Engine) and `Engine::RelayPeer` (a delegate's approval relay); `PeerSources`: the attached context sources a peer bundle declares as its peer's answers (`chi.peer_source`) |
733
743
  | `extension_load.rb` | What an Engine loads at start: config.yml and bundle hooks, plugins, `bundles:` settings; events held while plugins load |
data/docs/plugins.md CHANGED
@@ -744,6 +744,7 @@ full label, `plugin.rb (bundle my-bundle)`.
744
744
  | `ctx.stop_turn(reason)` | stop the running turn after a warn notice with the reason; true when it stopped one now. In a `:before_tool_call` block it also denies that call |
745
745
  | `ctx.stop_generation(reason)` | cut the generation that is streaming: the turn goes on and the model is asked again ([hooks.md](hooks.md#watching-the-stream)). Shows nothing: post your own notice. True when it cut one now |
746
746
  | `ctx.ask_model(messages:, prompt:, …)` | a side answer from the session's model: see [Side answers](#side-answers-ctxask_model) |
747
+ | `ctx.http` | an HTTP client for calling services (`get`, `post_json`, `request`): see [Calling services](#calling-services-ctxhttp) |
747
748
  | `ctx.sessions` | fork, send to, read, list and stop other sessions: see [Other sessions](#other-sessions-ctxsessions) |
748
749
  | `ctx.toolkit` | the name of the session's toolkit (`full` for a session from before toolkits); nil with no session |
749
750
  | `ctx.declared_tools` | the tool names the session's next turn declares (its toolkit resolved, with its own adds and removes): ask this, not the name, whether a tool is there |
@@ -842,6 +843,10 @@ next turn never see it, and no hook fires. It returns the answer text.
842
843
  - `max_tokens:` defaults to 1024. An answer cut off by it ends with `…`.
843
844
  - `cancel:` takes a `Samagotchi::CancellationController`; cancelling it
844
845
  aborts the request.
846
+ - `model:` names a configured model instead of the session's: `"host:id"` for a host in config.yml `hosts:`, an
847
+ alias from `models:`, or a bare id one of the hosts lists or declares. The host's own key and settings are used;
848
+ a plugin never names a URL or a key here (that is [`ctx.http`](#calling-services-ctxhttp)). A ref that names
849
+ nothing configured raises `ArgumentError`, asking nothing: a typo never goes to another model.
845
850
  - It blocks until the answer comes, so call it from an anytime command or a
846
851
  thread of your own. A local server that runs one request at a time
847
852
  (llama.cpp with one slot) answers it after a running turn's current
@@ -853,6 +858,78 @@ next turn never see it, and no hook fires. It returns the answer text.
853
858
  It goes through the host's OpenAI API (`/v1/chat/completions`), which
854
859
  llama.cpp serves on a native host too.
855
860
 
861
+ ## Calling services: `ctx.http`
862
+
863
+ ```ruby
864
+ # The http-echo bundle (spec fixture, docs/plugins.md "Calling services"):
865
+ # one tool that asks a local HTTP service and returns its answer.
866
+ class Plugin
867
+ def initialize(settings)
868
+ @url = settings.fetch("url", "http://127.0.0.1:9000/ask")
869
+ end
870
+
871
+ def register(chi)
872
+ chi.tool "ask_service", "Ask the local question service and return its answer",
873
+ params: { question: { type: "string", description: "What to ask", required: true } },
874
+ label: "asking" do |args, ctx|
875
+ res = ctx.http.post_json(@url, { question: args["question"] }, timeout: 5)
876
+ if res.ok?
877
+ res.json["answer"].to_s
878
+ else
879
+ ctx.log.warn(:ask_failed, status: res.status)
880
+ "the service answered #{res.status}"
881
+ end
882
+ rescue Samagotchi::Plugin::HttpError => e
883
+ "the service is not reachable: #{e.message}"
884
+ end
885
+ end
886
+ end
887
+ ```
888
+
889
+ That is `spec/fixtures/http_echo_bundle` (a spec keeps the two the same; `chi bundle install` it to try it): the
890
+ shape to copy for a plugin that calls a service, tested on `bundle.http` as in
891
+ `spec/samagotchi/plugin/http_echo_bundle_spec.rb`.
892
+
893
+ One way to call an HTTP service, with timeouts, errors, logging and Stop handled the same for every bundle.
894
+ `Net::HTTP` stays available for what this doesn't do (streaming, multipart, redirects, connection reuse).
895
+
896
+ | | |
897
+ |---|---|
898
+ | `ctx.http.get(url, headers: {}, timeout: 10)` | GET |
899
+ | `ctx.http.post_json(url, body, headers: {}, timeout: 10)` | POST `body` encoded as JSON, with `Content-Type` and `Accept: application/json` (unless `headers` names them) |
900
+ | `ctx.http.request(method, url, body: nil, headers: {}, timeout: 10)` | GET, POST, PUT, PATCH, DELETE or HEAD; `body` is a String sent as is (set your own `Content-Type`) |
901
+
902
+ Every call also takes `cancel:`, a `Samagotchi::CancellationController`, which replaces the default (below).
903
+
904
+ - `url` is a String or URI, `http` or `https`. A bad URL, another scheme, an unknown method, a bad header, a
905
+ `timeout` that isn't a positive number, or a body `post_json` can't encode as JSON raises **ArgumentError**
906
+ before any request.
907
+ - `timeout` (seconds) is the connect, the write and the **per-read** timeout, not a total deadline: a server that dribbles
908
+ bytes can take longer.
909
+ - It returns a `Samagotchi::Plugin::Http::Response`: `status` (Integer), `headers` (frozen, lower-case names,
910
+ repeated values joined with `", "`), `body` (a String, `""` for HEAD or no body), `ok?` (2xx) and `json`. A
911
+ **4xx or 5xx is returned, not raised**: check `ok?`. A redirect is not followed: the 3xx comes back with its
912
+ `location` header.
913
+ - `body` is tagged UTF-8 when its bytes are valid UTF-8, else left binary: `body.scrub` it before handing unknown
914
+ text to the model. There is no size limit: don't read an endpoint you don't trust to be small.
915
+ - `json` parses the body on each call and raises `HttpError` ("not JSON: …") when it isn't JSON.
916
+ - **One error type.** `Samagotchi::Plugin::HttpError` means the request didn't complete: refused, timed out, DNS,
917
+ TLS, reset, a malformed response, a bad compressed body, or `json` on a body that isn't JSON. No raw `Errno`,
918
+ `Net::` or `Zlib` error escapes (the original is the error's `cause`). The message says what and where
919
+ (`"POST 127.0.0.1:9000: connection refused"`), never headers or a body. `Samagotchi::Plugin::HttpCancelled`
920
+ (a subclass) means the call was cancelled.
921
+ - `http_proxy`, `https_proxy` and `no_proxy` are honoured as for chi's model calls (loopback is never proxied).
922
+ chi's own `User-Agent` is always sent: yours is replaced.
923
+ - **Stop.** A call made for the turn (a tool, a hook's handler) stops when the turn is stopped, and a call inside an
924
+ init task when chi shuts down; a call from your own thread, a `chi.service` or an anytime command has only its
925
+ timeout unless you pass `cancel:`. After the turn has ended (an `:after_turn` or `:session_end` hook of a
926
+ stopped turn) a call is not cancelled by that stop.
927
+ - **The log.** Each call writes one `http` line to the debug log: INFO (ERROR when it fails) with `bundle=`,
928
+ `purpose=plugin`, the method, the URL **without its query**, the status and the time. Never headers or bodies.
929
+ A plugin that polls a dead service therefore logs an ERROR per poll.
930
+
931
+ `ctx.http` is experimental until 1.0, like the test kit.
932
+
856
933
  ## Other sessions: `ctx.sessions`
857
934
 
858
935
  ```ruby
@@ -1003,7 +1080,9 @@ CHANGELOG line and bumps the shipped bundles that use it. Anything else under
1003
1080
  `Samagotchi::Plugin::ToolResult`, `Samagotchi::Plugin::ModelError` (and its
1004
1081
  subclass `Samagotchi::Plugin::ModelCancelled`),
1005
1082
  `Samagotchi::Plugin::Service::Stopped`, `Samagotchi::Plugin::Sessions::Error`
1006
- and `Samagotchi::Plugin::AttachedContext::Error`.
1083
+ and `Samagotchi::Plugin::AttachedContext::Error`. `ctx.http` and its
1084
+ `Samagotchi::Plugin::HttpError` (with the subclass `HttpCancelled`) and
1085
+ `Samagotchi::Plugin::Http::Response` are **experimental until 1.0**, like the test kit.
1007
1086
  2. `Samagotchi::Plugin::Peer` as a base class. A subclass defines `post`,
1008
1087
  `check_hint!`, `paired_lines`, `transport_line`, `peer_dir` and
1009
1088
  `setup_paragraph` (optionally `skill_substitutions`), and sets `NAME`,
@@ -1020,6 +1099,12 @@ CHANGELOG line and bumps the shipped bundles that use it. Anything else under
1020
1099
  `Samagotchi::Log.debug`, `Samagotchi::Config.get` and
1021
1100
  `Samagotchi::VERSION`.
1022
1101
 
1102
+ `Samagotchi::Testing::Boundary::ALLOWED` is the checked copy of this list,
1103
+ and `Boundary::EXCEPTIONS` the per-bundle list of what each shipped bundle
1104
+ (and its specs) reaches beyond it, each with why: the APIs to design before
1105
+ that bundle could leave chi's repo. `spec/samagotchi/testing/boundary_spec.rb`
1106
+ fails on a reference in neither (docs/testing.md).
1107
+
1023
1108
  **Used by shipped bundles today, but internal** (may change without notice; a
1024
1109
  bundle that needs one should ask for an API instead):
1025
1110
 
@@ -1032,6 +1117,62 @@ bundle that needs one should ask for an API instead):
1032
1117
  `Samagotchi::Guardrails::GitInfo`.
1033
1118
  - `Samagotchi::Tools::Execute.const_get` reflection.
1034
1119
 
1120
+ ## Testing a bundle (experimental)
1121
+
1122
+ `samagotchi/testing` loads a bundle the way chi does and records what it does at chi's edges, so a test
1123
+ needs no fake `chi` or `ctx`. It is **experimental**: it may change in any release before 1.0.0 and is not
1124
+ part of "Stable for bundles".
1125
+
1126
+ ```ruby
1127
+ require "samagotchi/testing"
1128
+
1129
+ bundle = Samagotchi::Testing::Bundle.load("path/to/my-bundle", settings: { "every" => 3 },
1130
+ host: { session_id: "s1", cwd: Dir.pwd })
1131
+ bundle.fire(:after_turn, status: "completed") # → the event, after the hooks
1132
+ bundle.command("/mine stop") # → what the command returned
1133
+ bundle.tool("my_tool", path: "a.txt") # → the text the model reads
1134
+ verdict = bundle.tool_call({ name: "execute", content: "rm -rf /" })
1135
+ verdict.deny? # a real Guardrails::Verdict (votes: verdict.votes)
1136
+ bundle.notices.map(&:text) # also cards, steers, stops, generation_stops, questions
1137
+ bundle.answer({ selected: "yes" }) # the next ask_user's answer
1138
+ bundle.model_answers << "a summary" # the next ask_model's answer
1139
+ bundle.sessions.on(:children) { |all:| [] } # ctx.sessions, scripted and recorded
1140
+ bundle.http.stub(:post, "http://127.0.0.1:9000/classify", json: { label: "safe" }) # ctx.http, never the network
1141
+ bundle.set(running: false) # the session's values: cwd:, messages:, cancelled: …
1142
+ bundle.shutdown
1143
+ ```
1144
+
1145
+ - **Real seams.** The plugin loads through `Plugin::Loader.register_file` (the real `chi` API and a real `ctx`),
1146
+ the hook files through `Hooks::BundleLoader.load_hook_file`, into registries that already hold chi's own
1147
+ commands and tools: a name chi has fails the load as it would in chi. `tool_call` runs a real
1148
+ `Guardrails::Gate` (context and targets computed for the call; `verdict:` starts from one with a vote in it).
1149
+ Only the edges are recorded: the session (`Testing::Host`), the hook helpers (`Testing::Runtime`),
1150
+ `ctx.sessions`, `chi.init` tasks (`bundle.run_inits`) and `chi.replace_tools` sets
1151
+ (`bundle.apply_staged_tools!`). No sha256 or `requires_chi` check: it loads the source as it is.
1152
+ - **More:** `bundle.plugin` (the instance `register` ran on, for its own methods), `bundle.declarations` (the
1153
+ `chi.*` calls `register` made, in order, as made), `bundle.namespace`, `bundle.hook_names(event)`,
1154
+ `bundle.run_inits`, `sandbox.write_memory(name, text, scope:)` / `memory_dir`, `sandbox.fake_executable(name,
1155
+ body)` (first on `PATH`), `wait_until { }`.
1156
+ - **`ctx.http` is faked.** `bundle.http.stub(method, url_or_regexp, status: 200, headers: {}, body: nil, json: nil,
1157
+ error: nil) { |request| … }` answers it: a String URL matches exactly (query included), a Regexp the full URL, later
1158
+ stubs win, and a stub answers every matching call (a block that counts makes a sequence). `error: :refused` or
1159
+ `:timeout` raises the `HttpError` the real client would; `bundle.http.requests` lists what the plugin sent
1160
+ (`method`, `url`, `headers`, `body`, `json`) and `bundle.http.unmatched` what no stub answered. A request no stub
1161
+ answered raises `Samagotchi::Testing::UnstubbedRequest` (not an `HttpError`, but a plugin may rescue it anyway) and
1162
+ **fails the test at teardown** (RSpec and Minitest adapters: after the cleanup, and only a test that passed), so a
1163
+ spec can't reach the network. With plain `Bundle.load` there is no teardown: check `bundle.http.unmatched`.
1164
+ `bundle.set(cancelled: true)` makes a call without `cancel:` raise `HttpCancelled`.
1165
+ - **A hook that raises fails the call** (`Testing::HookFailed`, with the hook's error) where chi would log it and
1166
+ go on; `bundle.lenient { … }` collects them in `bundle.errors` instead.
1167
+ - **Sandbox.** A test runs with temp config and state homes (config.yml, memories, `ctx.data_dir`, the debug
1168
+ log), `HOME`, `CLAUDE_CONFIG_DIR` and `CODEX_HOME`, no git config of yours, no Keychain and none of your
1169
+ `SAMAGOTCHI_*` settings; `sandbox.config(hash)` writes its config.yml.
1170
+ - **RSpec:** `require "samagotchi/testing/rspec"`; example groups tagged `:bundle` (a spec under a bundle's own
1171
+ `spec/` is tagged by itself) get `load_bundle(dir)`, `shipped_bundle(name)` and `sandbox`, each example in its
1172
+ own sandbox, its bundles shut down after it (chi's shipped bundles keep theirs in `<bundle>/spec/`,
1173
+ docs/testing.md). **Minitest:** `require "samagotchi/testing/minitest"` and subclass
1174
+ `Samagotchi::Testing::Case` (the same helpers).
1175
+
1035
1176
  ## The btw bundle
1036
1177
 
1037
1178
  `chi bundle install btw` (or the `dev` profile) installs the bundle shipped with chi. It is written
@@ -1097,7 +1238,7 @@ bundles:
1097
1238
  and values: only the digest is stored) and `cwd`. A session with a saved
1098
1239
  list can search its tools at once and **doesn't start the server**: the
1099
1240
  first call of one of its tools does (the call's row shows the wait). So a
1100
- session that never uses MCP spawns nothing, and a new chat opens without
1241
+ session that never uses MCP spawns nothing, and a new session opens without
1101
1242
  waiting for `npx`. If the live list differs from the saved one, the saved
1102
1243
  one is replaced, and so is what a search finds. The model's tools never
1103
1244
  change, so the prompt cache keeps. The saved file also keeps the first
@@ -1127,7 +1268,7 @@ bundles:
1127
1268
  you want at once.
1128
1269
  - **`npx -y …@latest` checks the npm registry on every start** (~3.4 s for
1129
1270
  `chrome-devtools-mcp`, against ~0.9 s for the installed binary). The cache
1130
- hides it from new chats, but not from the first call. For a faster first
1271
+ hides it from new sessions, but not from the first call. For a faster first
1131
1272
  call, install the server once and run it directly:
1132
1273
 
1133
1274
  ```yaml
data/docs/releasing.md CHANGED
@@ -63,7 +63,7 @@ as the GitHub release body.
63
63
  | `rake 'bundles:check[ci]'` | The CI workflow's (every push and PR): the same, except the version check leaves out the system bundle, which is changed and unbumped between releases (`release:bump` moves its version with VERSION). A task argument, not `CI=1`: GitHub sets `CI` in the release workflow too. |
64
64
  | `rake release:draft_changelog` | A draft Unreleased section from the commit subjects since the last tag, grouped. Stdout only. |
65
65
  | `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped). No commit. |
66
- | `rake release:check` | Clean tracked tree, VERSION == system bundle, a CHANGELOG section, no `requires_chi_next` left, `bundles:check`, `rake lint` (RuboCop), rspec + npm test, `gem build`, then a clean install into a temp GEM_HOME that runs `chi --version`, `chi self` and `chi bundle list` with a temp HOME. Needs the network (gem dependencies). |
66
+ | `rake release:check` | Clean tracked tree, VERSION == system bundle, a CHANGELOG section, no `requires_chi_next` left, `bundles:check`, `rake lint` (RuboCop), rspec (both roots: `spec` and the bundles' own `spec/`) + `rake bundles:specs` + npm test, `gem build`, then a clean install into a temp GEM_HOME that runs `chi --version`, `chi self` and `chi bundle list` with a temp HOME. Needs the network (gem dependencies). |
67
67
  | `rake release:notes[X.Y.Z]` | Prints the CHANGELOG section (default: the current VERSION). |
68
68
 
69
69
  ## Runbook
@@ -165,4 +165,4 @@ things differ there, and a new spec that trips on them fails only on CI:
165
165
  To run it locally, use Docker with the Ruby build CI uses
166
166
  (`ruby-X.Y.Z-ubuntu-24.04-x64.tar.gz` from ruby/ruby-builder's releases) on
167
167
  `ubuntu:24.04` with `LANG=C.UTF-8`, `zip` and `git`, and run
168
- `CI=1 BUNDLE_PATH=… bundle exec rspec`.
168
+ `CI=1 BUNDLE_PATH=… bundle exec rspec spec lib/samagotchi/bundles/*/spec`.