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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +68 -1
- data/bin/chi +3 -1
- data/docs/architecture.md +16 -6
- data/docs/bundle-authoring.md +1 -1
- data/docs/bundles.md +103 -4
- data/docs/cli.md +28 -6
- data/docs/configuration.md +2 -1
- data/docs/guardrails.md +16 -1
- data/docs/internals/block-renderers.md +58 -3
- data/docs/internals/bridge.md +13 -5
- data/docs/internals/bundles.md +21 -4
- data/docs/internals/engine.md +18 -8
- data/docs/internals/remote-sessions.md +24 -5
- data/docs/internals/web-frontend.md +88 -28
- data/docs/internals/working-set.md +1 -1
- data/docs/mcp-server.md +80 -0
- data/docs/plugins.md +308 -21
- data/docs/sessions.md +3 -3
- data/docs/sub-agent.md +9 -0
- data/docs/testing.md +3 -1
- data/docs/thin-clients.md +146 -0
- data/lib/samagotchi/bridge/pending_card.rb +4 -3
- data/lib/samagotchi/bridge/sse_writer.rb +16 -15
- data/lib/samagotchi/bridge.rb +59 -68
- data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
- data/lib/samagotchi/bundle_command/check.rb +36 -19
- data/lib/samagotchi/bundle_command.rb +50 -21
- data/lib/samagotchi/bundle_manifest.rb +101 -4
- data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
- data/lib/samagotchi/bundles/mcp/client.rb +260 -0
- data/lib/samagotchi/bundles/mcp/content.rb +107 -0
- data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
- data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
- data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
- data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
- data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/cli/parent_wait.rb +5 -3
- data/lib/samagotchi/command_intake.rb +7 -0
- data/lib/samagotchi/commands/registry.rb +8 -3
- data/lib/samagotchi/continue_offer.rb +24 -15
- data/lib/samagotchi/engine/block_fix.rb +4 -4
- data/lib/samagotchi/engine/cards.rb +14 -5
- data/lib/samagotchi/engine/events.rb +10 -15
- data/lib/samagotchi/engine/models.rb +1 -1
- data/lib/samagotchi/engine/plugins.rb +3 -0
- data/lib/samagotchi/engine/recap.rb +1 -1
- data/lib/samagotchi/engine/side_requests.rb +1 -1
- data/lib/samagotchi/engine/sign_in.rb +142 -0
- data/lib/samagotchi/engine/turn_end.rb +3 -3
- data/lib/samagotchi/engine.rb +43 -27
- data/lib/samagotchi/engine_snapshots.rb +1 -1
- data/lib/samagotchi/guardrail_wiring.rb +3 -1
- data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
- data/lib/samagotchi/guardrails/verdict.rb +3 -2
- data/lib/samagotchi/hold_stop.rb +4 -4
- data/lib/samagotchi/idle_recap.rb +19 -11
- data/lib/samagotchi/idle_reminders.rb +7 -5
- data/lib/samagotchi/idle_scheduler.rb +7 -10
- data/lib/samagotchi/installed_bundles/dir.rb +37 -0
- data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
- data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
- data/lib/samagotchi/installed_bundles/record.rb +3 -2
- data/lib/samagotchi/installed_bundles/standing.rb +3 -1
- data/lib/samagotchi/llm/http.rb +96 -5
- data/lib/samagotchi/mcp_command.rb +110 -0
- data/lib/samagotchi/mcp_server/http.rb +112 -0
- data/lib/samagotchi/mcp_server/protocol.rb +244 -0
- data/lib/samagotchi/mcp_server/stdio.rb +92 -0
- data/lib/samagotchi/mcp_server/text.rb +155 -0
- data/lib/samagotchi/mcp_server/tools.rb +245 -0
- data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
- data/lib/samagotchi/memory_bundle/builder.rb +20 -2
- data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
- data/lib/samagotchi/memory_bundle/installer.rb +16 -3
- data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
- data/lib/samagotchi/memory_bundle/shas.rb +6 -4
- data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
- data/lib/samagotchi/memory_bundle/status.rb +15 -6
- data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
- data/lib/samagotchi/plugin/api.rb +6 -1
- data/lib/samagotchi/plugin/card.rb +36 -11
- data/lib/samagotchi/plugin/context.rb +63 -6
- data/lib/samagotchi/plugin/http.rb +40 -15
- data/lib/samagotchi/plugin/http_errors.rb +15 -0
- data/lib/samagotchi/plugin/http_stream.rb +86 -0
- data/lib/samagotchi/plugin/http_transport.rb +58 -16
- data/lib/samagotchi/plugin/loader.rb +18 -11
- data/lib/samagotchi/plugin/secrets.rb +266 -0
- data/lib/samagotchi/plugin/sign_in.rb +392 -0
- data/lib/samagotchi/plugin/sse_reader.rb +103 -0
- data/lib/samagotchi/queued_command.rb +28 -4
- data/lib/samagotchi/recap_setup.rb +13 -4
- data/lib/samagotchi/ref.rb +3 -2
- data/lib/samagotchi/relay_verifier.rb +8 -7
- data/lib/samagotchi/relay_watcher.rb +4 -4
- data/lib/samagotchi/run_options.rb +2 -1
- data/lib/samagotchi/send_command.rb +54 -41
- data/lib/samagotchi/session_access/ask.rb +244 -0
- data/lib/samagotchi/session_access/contract.rb +5 -0
- data/lib/samagotchi/session_access/exchange/token.rb +101 -0
- data/lib/samagotchi/session_access/exchange.rb +173 -0
- data/lib/samagotchi/session_access/local.rb +25 -6
- data/lib/samagotchi/session_access/remote.rb +4 -1
- data/lib/samagotchi/session_command_catalog.rb +10 -0
- data/lib/samagotchi/session_commands.rb +17 -0
- data/lib/samagotchi/session_config.rb +4 -4
- data/lib/samagotchi/session_observer.rb +27 -0
- data/lib/samagotchi/steer_cut.rb +4 -3
- data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
- data/lib/samagotchi/testing/boundary.rb +4 -0
- data/lib/samagotchi/testing/bundle.rb +48 -2
- data/lib/samagotchi/testing/fake_http.rb +60 -15
- data/lib/samagotchi/testing/host.rb +4 -1
- data/lib/samagotchi/testing/recorder.rb +45 -5
- data/lib/samagotchi/tools/tool_index.rb +14 -3
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +8 -6
- data/lib/samagotchi/web/ask_routes.rb +292 -0
- data/lib/samagotchi/web/mcp_route.rb +88 -0
- data/lib/samagotchi/web/public/app.js +2 -3
- data/lib/samagotchi/web/public/block_frame.js +72 -11
- data/lib/samagotchi/web/public/block_host.js +44 -8
- data/lib/samagotchi/web/public/block_regions.js +126 -0
- data/lib/samagotchi/web/public/card.js +22 -9
- data/lib/samagotchi/web/public/card_actions.js +21 -0
- data/lib/samagotchi/web/public/card_kinds.js +1 -1
- data/lib/samagotchi/web/public/card_registry.js +3 -2
- data/lib/samagotchi/web/public/data.js +15 -12
- data/lib/samagotchi/web/public/delete_sheet.js +222 -162
- data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
- data/lib/samagotchi/web/public/format.js +3 -0
- data/lib/samagotchi/web/public/index.html +52 -7
- data/lib/samagotchi/web/public/more_sheet.js +6 -4
- data/lib/samagotchi/web/public/picture_regions.js +243 -0
- data/lib/samagotchi/web/public/picture_viewer.js +113 -12
- data/lib/samagotchi/web/public/refs.js +5 -3
- data/lib/samagotchi/web/public/region_hit.js +144 -0
- data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
- data/lib/samagotchi/web/public/running_tasks.js +6 -4
- data/lib/samagotchi/web/public/session_actions.js +105 -100
- data/lib/samagotchi/web/session_access_routes.rb +14 -11
- data/lib/samagotchi/web/session_control.rb +31 -9
- data/lib/samagotchi/web/session_create.rb +2 -2
- data/lib/samagotchi/worker/child_side.rb +3 -2
- data/lib/samagotchi/worker/command_queue.rb +13 -13
- data/lib/samagotchi/worker/leave.rb +3 -3
- data/lib/samagotchi/worker/scratch.rb +6 -6
- data/lib/samagotchi/worker/signal_grace.rb +6 -5
- data/lib/samagotchi/worker/startup.rb +3 -3
- data/lib/samagotchi/worker/wake_turns.rb +4 -4
- data/lib/samagotchi/worker.rb +32 -21
- data/lib/samagotchi/worker_exit_claim.rb +1 -1
- data/lib/samagotchi/worker_idle_exit.rb +18 -9
- data/lib/samagotchi/worker_inbound.rb +12 -7
- data/lib/samagotchi/worker_participant_gate.rb +9 -7
- data/lib/samagotchi/worker_task_wakes.rb +7 -5
- metadata +31 -1
data/docs/mcp-server.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# chi as an MCP server
|
|
2
|
+
|
|
3
|
+
An MCP host (Claude Code, Codex, any client of the Model Context Protocol) can drive chi sessions as tools: list
|
|
4
|
+
them, send one a message and read its answer, answer the question it waits on. The sessions are ordinary ones: you
|
|
5
|
+
watch them in `chi web` or attach to them while the host talks to them.
|
|
6
|
+
|
|
7
|
+
This is chi as an MCP **server**. The `mcp` bundle is the other direction: chi as an MCP client, using other
|
|
8
|
+
servers' tools in its own sessions (see [Bundles](bundles.md)).
|
|
9
|
+
|
|
10
|
+
## Adding it to a host
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
claude mcp add chi -- chi mcp serve # this machine's sessions, stdio
|
|
14
|
+
claude mcp add chi-cloud -- chi --remote cloud mcp serve # another machine's, through its chi web
|
|
15
|
+
claude mcp add --transport http chi http://127.0.0.1:4567/api/mcp # chi web, loopback
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Codex, in its `config.toml`:
|
|
19
|
+
|
|
20
|
+
```toml
|
|
21
|
+
[mcp_servers.chi]
|
|
22
|
+
command = "chi"
|
|
23
|
+
args = ["mcp", "serve"]
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- **stdio** (`chi mcp serve`): the host starts chi; JSON-RPC lines on its stdin and stdout. Under `chi --remote
|
|
27
|
+
NAME` (see [Remote sessions](cli.md#remote-sessions)) the tools reach that machine's sessions through its chi web.
|
|
28
|
+
- **HTTP** (`POST /api/mcp` on chi web): on loopback with no `web.public_url`, no token, as every owner route of
|
|
29
|
+
chi web. On the LAN, or a public URL chi web serves directly, send chi web's access token:
|
|
30
|
+
`--header "Authorization: Bearer <token>"` (a request without it gets a 401 with `WWW-Authenticate: Bearer`).
|
|
31
|
+
A participant's token is refused. `GET /api/info` lists `"mcp"` in its `features`; an older chi web answers 404.
|
|
32
|
+
- **Behind an auth proxy** (Okta, oauth2-proxy): not yet. The proxy stops an MCP host before chi sees it: use `chi
|
|
33
|
+
--remote NAME mcp serve` there.
|
|
34
|
+
|
|
35
|
+
Both revisions of the protocol are served: the current one (2026-07-28, stateless: Claude Code) and the earlier
|
|
36
|
+
`initialize` one (2025-11-25, 2025-06-18: Codex). The answers are plain JSON, never a stream. 2025-03-26 is not
|
|
37
|
+
offered (a client naming it is answered 2025-11-25): it allows JSON-RPC batches, and chi answers a batch with one
|
|
38
|
+
`-32600` error. A message that isn't JSON in UTF-8 is a `-32700` with its request's id when chi can read one, so the
|
|
39
|
+
host isn't left waiting on that call.
|
|
40
|
+
|
|
41
|
+
## The tools
|
|
42
|
+
|
|
43
|
+
| Tool | Arguments | What it does |
|
|
44
|
+
|---|---|---|
|
|
45
|
+
| `chi_sessions` | `dir?`, `live?`, `limit?` | the sessions, newest first: id, title, status, whether a question waits, project |
|
|
46
|
+
| `chi_ask` | `session`, `prompt` | sends the prompt as its own turn (queued behind a running one) and waits for the answer |
|
|
47
|
+
| `chi_wait` | `token` | keeps waiting for a turn that was still running |
|
|
48
|
+
| `chi_answer` | `session`, `question_id`, `option?` / `options?` / `text?` | answers the question a session waits on, then waits |
|
|
49
|
+
|
|
50
|
+
A call waits at most 25 seconds (a `chi_ask` or `chi_answer` 35 in all, under Claude Code HTTP's 60 s). Then:
|
|
51
|
+
|
|
52
|
+
- the turn still runs: `Still running. Call chi_wait with this token to keep waiting.` with a `token`;
|
|
53
|
+
- a question waits: the question, its numbered options and `Call chi_answer with session, question_id and option
|
|
54
|
+
(or text).` An option is its label or its number (1-based); several only on a question that takes several.
|
|
55
|
+
- `chi_answer` on a question no longer open (answered elsewhere first, a newer one waits, or a stale
|
|
56
|
+
`question_id`): nothing is sent. The text starts `Question <id> is no longer open …; not answered here.`, then
|
|
57
|
+
says what came next (`answered_here: false` in `structuredContent`).
|
|
58
|
+
|
|
59
|
+
Every result is text plus the same facts, the text included, as `structuredContent` (`status`: `done`, `running`, `waiting_for_answer`,
|
|
60
|
+
`command`, or `error` with `detail`). A refusal, a bad argument and a turn that ended without a reply are results
|
|
61
|
+
with `isError: true` and chi's own words; only an unknown tool is a protocol error.
|
|
62
|
+
|
|
63
|
+
## Who the caller is
|
|
64
|
+
|
|
65
|
+
The host is an agent driving a session, as `chi send --wait` and `chi answer` are (see [chi as a
|
|
66
|
+
sub-agent](sub-agent.md)): its messages go in as `chi send`'s, its answers and a `/continue yes` as `chi answer`'s.
|
|
67
|
+
So `guardrails.parent_answers` holds it (see [Guardrails](guardrails.md#answers-from-a-parent-agent)): what it may
|
|
68
|
+
pick on an approval or a step-limit question, and whether it may continue a turn that ran out of iterations. The
|
|
69
|
+
page shows its turns with the "chi send" label.
|
|
70
|
+
|
|
71
|
+
`chi_ask` takes a message for the model, not a command: a line starting with `!` (a shell line) or with `/` (a
|
|
72
|
+
session command; `/continue …` is the one exception) is refused. That is narrower than `chi send` on purpose: a
|
|
73
|
+
host approves an MCP tool once, not each line.
|
|
74
|
+
|
|
75
|
+
## Not yet
|
|
76
|
+
|
|
77
|
+
Starting a session (`chi_new`), stopping, archiving or deleting one; OAuth (claude.ai and ChatGPT connectors, a chi
|
|
78
|
+
web behind an auth proxy); progress notifications and streamed answers; resources and prompts; images; a
|
|
79
|
+
participant's token. A second `chi_ask` while the first still runs queues another turn: nothing stops a model from
|
|
80
|
+
asking twice.
|
data/docs/plugins.md
CHANGED
|
@@ -30,6 +30,8 @@ plugin:
|
|
|
30
30
|
sha256: sha256:6a1a7022… # shasum -a 256 plugin.rb
|
|
31
31
|
# required: true # optional: a guardrail plugin; if it fails to load, every tool call is
|
|
32
32
|
# denied (see chi.on's on_error: :fail_closed; chi 0.157.0 or newer)
|
|
33
|
+
# parts: # optional: more .rb files of the plugin, loaded in this order before file:
|
|
34
|
+
# client.rb: sha256:… # (see "A plugin in several files" below; needs the chi after 0.182.0)
|
|
33
35
|
requires_chi: ">= 0.1.28" # optional: a gem-style requirement (">= 0.1.28, < 0.2"); the bundle's rules check it too
|
|
34
36
|
# every key below has a chi floor: check warns when requires_chi admits a chi that never read it
|
|
35
37
|
# requires_chi_next: true # shipped bundles only, ignored by chi: rake release:bump raises requires_chi
|
|
@@ -89,6 +91,38 @@ A config.yml `bundles:` name that no installed bundle has shows a warning when a
|
|
|
89
91
|
so does a key or a value's type the manifest's `settings:` rules out. It warns only: the session goes on, and a
|
|
90
92
|
bundle with no `settings:` has its keys left alone. `chi bundle check --set` warns the same way (`settings`).
|
|
91
93
|
|
|
94
|
+
### A plugin in several files
|
|
95
|
+
|
|
96
|
+
A plugin too big for one file lists its other files under `plugin: parts:`, each with its sha256 (`chi bundle check
|
|
97
|
+
--fix` fills them in):
|
|
98
|
+
|
|
99
|
+
```yaml
|
|
100
|
+
plugin:
|
|
101
|
+
file: plugin.rb
|
|
102
|
+
sha256: sha256:…
|
|
103
|
+
parts:
|
|
104
|
+
client.rb: sha256:…
|
|
105
|
+
http_client.rb: sha256:…
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
- A part is a `.rb` name in the bundle's top directory, not the plugin file's own nor another part's, in any case
|
|
109
|
+
(`Plugin.rb` beside `plugin.rb` is one file on a case-insensitive disk), listed once; at most 16. It is installed
|
|
110
|
+
beside the plugin file in `plugin/`, checked like it at every load, and listed by `chi bundle status`, `diff`,
|
|
111
|
+
`build` and `uninstall`.
|
|
112
|
+
- chi evaluates the parts **in the listed order**, then the plugin file, all into the same fresh module, so they
|
|
113
|
+
share one namespace. Only the plugin file names the class chi builds; a part usually reopens it
|
|
114
|
+
(`class Plugin; class HttpClient …`).
|
|
115
|
+
- Order matters only for what a class or module body uses as it is read: a superclass, an `include`d module, a
|
|
116
|
+
constant set from another file's. A method body resolves constants when it runs, after every file is loaded.
|
|
117
|
+
- A part that reopens `class Plugin` before a plugin file that declares `class Plugin < Base` raises "superclass
|
|
118
|
+
mismatch": the part must name the same superclass (and so must load after the file that defines `Base`).
|
|
119
|
+
- Not `require_relative`: a file pulled in that way skips the sha256 check, is cached by Ruby across reloads (a
|
|
120
|
+
reload would keep the old classes) and defines its constants outside the bundle's namespace.
|
|
121
|
+
- A bundle that uses `parts:` should require a chi that reads them (`requires_chi`): an older chi would install the
|
|
122
|
+
plugin file alone. `chi bundle check` warns of a lower `requires_chi` from the chi release that brings parts on
|
|
123
|
+
(until then the key has no release to name). A record written that way is refused at load with `bundle NAME's
|
|
124
|
+
plugin parts aren't installed (reinstall the bundle)`.
|
|
125
|
+
|
|
92
126
|
## The API: `register(chi)`
|
|
93
127
|
|
|
94
128
|
### `chi.command(name, description, anytime: false) { |args, ctx| … }`
|
|
@@ -660,7 +694,9 @@ end
|
|
|
660
694
|
- **`quiet: true`**: nothing is shown unless it fails (a background
|
|
661
695
|
refresh).
|
|
662
696
|
- **`ctx.cancelled?`** in the block says chi is shutting down: the block
|
|
663
|
-
should stop then. It is the task's own, not the running turn's
|
|
697
|
+
should stop then. It is the task's own, not the running turn's, on the
|
|
698
|
+
task's thread: a thread the block starts reads the turn's, so hand it
|
|
699
|
+
`ctx.cancel_controller` (read in the block) instead.
|
|
664
700
|
- `ctx.notify` and `ctx.card` from the block show between turns, even while
|
|
665
701
|
a turn runs.
|
|
666
702
|
- Each task runs once per session start. A `-p … --non-interactive` run
|
|
@@ -795,7 +831,9 @@ index = Samagotchi::Tools::ToolIndex
|
|
|
795
831
|
list or the new one, never half. A `Group` has a `summary` (its line in
|
|
796
832
|
`find_tools`' description), a `state` (`:ready`; `:starting`, its tools may
|
|
797
833
|
still come: a call to it waits on `wait`, a search says "starting, try
|
|
798
|
-
again"; `:failed` with its `error
|
|
834
|
+
again"; `:failed` with its `error`; `:needs_user`, it can't be used until the user does something, its `error`
|
|
835
|
+
the source's own line, which a search notes and a call that misses its tools answers, after asking `wait` (the
|
|
836
|
+
user may have done it meanwhile): the mcp bundle's "needs sign-in") and its tools. A group exists before its
|
|
799
837
|
tools do. A `Tool`'s `refusal` says why `call_tool` refuses it (nil: it can
|
|
800
838
|
be called), its `mark` what a search shows beside its name: the plugin
|
|
801
839
|
decides both (the mcp bundle: a bad schema, a name clash) and publishes
|
|
@@ -894,7 +932,7 @@ full label, `plugin.rb (bundle my-bundle)`.
|
|
|
894
932
|
| `ctx.model_names` | the names chi's own per-model config looks that model up under (a `models:` map in config.yml): as typed (an alias), the alias's target, the resolved ref, without the host, the bare id; deduped, most specific first, frozen (`[]` when it doesn't resolve). Match a map of yours over them downcased, first hit, as chi does. Needs chi 0.132.0 |
|
|
895
933
|
| `ctx.cost` | the session's spend so far, read now, as a frozen value: `total` (USD, reported + estimated, side requests included; 0.0 before any), `reported` (by providers, `usage.cost`), `estimated` (from `hosts.<name>.models` prices; a generation is one or the other, never both), `side` (recap, `/btw`, `ask_model`: their share of `total`) and `known?` (false while generations or side requests ran but none was reported or priced, so a limit on it can't be enforced; a session with some priced generations reads known, the unpriced ones counting 0). It includes the running turn's finished generations and what earlier workers of the session spent. Use its methods, not its class. Needs chi 0.83.0 |
|
|
896
934
|
| `ctx.usage` | the session's work so far, read now, as a frozen value: `turns` (finished ones and the running one), `tool_calls` and `tool_calls_by_tool` (every call, running ones included; canonical names: an alias counts under its tool, a `call_tool` call under the inner tool), `steps` (the loop rounds that dispatched tools, `/stats`' iterations) and `active_ms` (`active_minutes` too): work time, the generations' time plus the finished tool calls' time, never the waits between them (a question, an approval, the user's answer to `ask_user_question`), with `tool_ms_by_tool` its tool part by tool, so a waiting tool's time (`task_wait`) can be left out. Its counts are the ones `/stats` and `chi sessions stats` show, earlier workers' included. Use its methods, not its class. Needs chi 0.100.0 (guard it with `ctx.respond_to?(:usage)`) |
|
|
897
|
-
| `ctx.turn_author` | who wrote the running turn when it isn't the session's owner: a participant's `"p:<id>"` (`chi share`); nil for the owner's turns and between turns. Every hook event of such a turn carries the same as `author:`. The handler runs with the owner's power whatever the author ([hooks](hooks.md#participants-turns)). Needs chi 0.105.0 (guard it with `ctx.respond_to?(:turn_author)`) |
|
|
935
|
+
| `ctx.turn_author` | who wrote the running turn when it isn't the session's owner: a participant's `"p:<id>"` (`chi share`); nil for the owner's turns and between turns. Every hook event of such a turn carries the same as `author:`. The handler runs with the owner's power whatever the author ([hooks](hooks.md#participants-turns)): `ctx.secrets` works there, so don't start a sign-in on such a turn. Needs chi 0.105.0 (guard it with `ctx.respond_to?(:turn_author)`) |
|
|
898
936
|
| `ctx.tool_id` | inside a tool's block, the run's own id (chi's tool id, `"t41"`), the one a two-arg `refs:` lambda got for its row ([Refs on a tool's row](#refs-on-a-tools-row)); nil anywhere else (a hook, a command, a thread the block started) and for a run with none. Needs chi 0.181.0 (guard it with `ctx.respond_to?(:tool_id)`) |
|
|
899
937
|
| `ctx.settings` | the bundle's settings, frozen: config.yml's `bundles: <bundle>:` with the session's own `--set` values laid over it ([Per-session settings](#per-session-settings)); the config alone until the session is bound (in `register` and `chi.ctx`) |
|
|
900
938
|
| `ctx.data_dir` | `$XDG_STATE_HOME/samagotchi/plugins/<bundle>/`, created on first use: what the bundle keeps across sessions |
|
|
@@ -906,15 +944,18 @@ full label, `plugin.rb (bundle my-bundle)`.
|
|
|
906
944
|
| `ctx.prompt_files` | the files whose text is in the session's system prompt now: the AGENTS.md chain (the work tree top down to the cwd) and the appended files (`append_system_prompt:`, `--append-system-prompt`); absolute paths, in prompt order, `[]` before the first build |
|
|
907
945
|
| `ctx.objectives` | the session's [objectives](internals/objectives.md), read now, as a frozen value: `empty?`, `items` (each `id`, `text`, `status` `"active"`, `"done"` or `"dropped"`, `done_when`), `find(id)`, `text` (the lines the model is shown) and `moves` (the latest move per id; mid-turn, a worker's leaves the running turn's out). An edit not yet absorbed counts. Empty when the session has none. Use its methods, not its class. Needs chi newer than 0.148.0 |
|
|
908
946
|
| `ctx.notify(text, level: :info, fallback_for: nil)` | one line to the user, labelled by the bundle (`my-bundle> …`). Every UI shows it, during a turn (a tool, a hook) or between turns (a command). `fallback_for: :display` marks a line that repeats the answer's display (`event[:present]`), which a UI that renders the display leaves out (`fallback_for: :editor`: a file the viewer could open from a ref in its editor): see [Hooks](hooks.md#what-a-hook-can-do-the-runtime). The keyword needs chi 0.35.0 (it raises on an older chi) |
|
|
909
|
-
| `ctx.card(title:, body: "", actions: [], level: :info, id: nil)` | a card in every UI, returning its id: see [Cards](#cards) |
|
|
947
|
+
| `ctx.card(title:, body: "", actions: [], level: :info, id: nil, between_turns: false)` | a card in every UI, returning its id: see [Cards](#cards) (`between_turns:`: never a running turn's) |
|
|
910
948
|
| `ctx.ask_user(question:, options:, header: nil, allow_freeform: false, effects: nil)` | a single-select question through the question flow: `{selected:, freeform:, selected_indices:}`, or nil (no one to ask, cancelled, bad options or effects). `effects:` tags the options a parent agent's answer is held to (label => `:spend`, `:permit`, `:permit_wide` or `:deny`; untagged = `:answer`): tag every option that spends or permits, and never let text alone or a dismissal do either ([hooks.md](hooks.md#what-a-hook-can-do-the-runtime)). It needs a chi newer than 0.85.0 |
|
|
911
949
|
| `ctx.cancelled?` | whether the running turn was cancelled (a long tool should stop) |
|
|
950
|
+
| `ctx.cancel_controller` | the `Samagotchi::CancellationController` `ctx.cancelled?` reads **on this thread**: inside an init task the task's own, else the running turn's; nil when neither. Read it on the thread that does the work, then hand it on: as `ctx.http`'s `cancel:` (it is the turn's inside a service's start block too, where `ctx.http`'s default is none) or to a thread of yours that polls it. A thread of yours that calls `ctx.cancelled?` itself gets its own thread's answer (the turn's), never the init task's. Experimental until 1.0; needs chi 0.183.0 or newer (`ctx.respond_to?(:cancel_controller)`) |
|
|
912
951
|
| `ctx.turn_running?` | whether a turn runs now. An `:after_turn` hook runs inside its turn, so a card a thread shows before the turn is over belongs to that turn's block, which the web collapses: wait for this to go false. Needs chi newer than 0.148.0 |
|
|
913
952
|
| `ctx.steer(text)` | put text into the running turn: its own user message at the loop's next boundary, shown as `my-bundle> nudged: …`. The model reads it with a header naming your bundle (`[Steer from the my-bundle plugin, mid-task. …]`); the session keeps the raw text. Returns true when queued, false with no turn running (it never starts one; that is `ctx.sessions`' send). Dropped (logged) if the model answers or the turn ends first. Safe from any thread: an anytime command, a hook (false from `:after_turn`), your own |
|
|
914
953
|
| `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 |
|
|
915
954
|
| `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 |
|
|
916
955
|
| `ctx.ask_model(messages:, prompt:, …)` | a side answer from the session's model: see [Side answers](#side-answers-ctxask_model) |
|
|
917
956
|
| `ctx.judge(name, state:)`, `ctx.judge_later(name, state:) { |result| … }`, `ctx.judgments` | a cheap System 1 question this bundle declared, saved as a run: see [Judgments](#judgments-chijudgment-and-ctxjudge) |
|
|
957
|
+
| `ctx.sign_in(title:, button:, timeout: 300, port: nil, path: "/callback", cancel: nil) { \|redirect_uri\| address }` | send the owner to an address and get back where the browser was sent: see [Sign-in](#sign-in-ctxsign_in) |
|
|
958
|
+
| `ctx.secrets` | the bundle's tokens, kept apart from its data files (`get`, `set`, `delete`, `update`): see [Secrets](#secrets-ctxsecrets) |
|
|
918
959
|
| `ctx.http` | an HTTP client for calling services (`get`, `post_json`, `request`): see [Calling services](#calling-services-ctxhttp) |
|
|
919
960
|
| `ctx.sessions` | fork, send to, read, list and stop other sessions: see [Other sessions](#other-sessions-ctxsessions) |
|
|
920
961
|
| `ctx.toolkit` | the name of the session's toolkit (`full` for a session from before toolkits); nil with no session |
|
|
@@ -970,6 +1011,20 @@ ctx.card(id: id, title: "Build finished", body: "no warnings left") # replaces
|
|
|
970
1011
|
`command_queued` and `command_ran` carry `card: true`, and no UI shows
|
|
971
1012
|
its line; the web shows a bubble only when the command answers with
|
|
972
1013
|
text or fails.
|
|
1014
|
+
- An action can open an address instead: `{label:, url:}` (exactly one of
|
|
1015
|
+
`command:` / `url:`; both or neither raise). The `url` is an absolute
|
|
1016
|
+
`http(s)` address with a host and no userinfo (`https://linear.app@evil.example`
|
|
1017
|
+
is refused), at most 4096 characters, and `label:` is required. The web
|
|
1018
|
+
draws a link that opens it in a new tab, its host as the tooltip, with a
|
|
1019
|
+
muted line under the buttons naming each host the card's links open
|
|
1020
|
+
(`opens linear.app`), so a label can't hide where it leads; the terminal
|
|
1021
|
+
prints `→ <label>`, then the address whole on its own line (no frame, not
|
|
1022
|
+
wrapped) for a click or a copy. Opening it sends nothing to the session,
|
|
1023
|
+
and a url action doesn't make a card ask: a running turn's card with only
|
|
1024
|
+
url actions doesn't hold the turn's stage or the "needs you" badge. It
|
|
1025
|
+
needs chi 0.183.0: set `requires_chi: ">= 0.183.0"` in the bundle by hand
|
|
1026
|
+
(`chi bundle check` can't see an action's keys); an older chi refuses the
|
|
1027
|
+
card with `ArgumentError`.
|
|
973
1028
|
- `level:` is `:info` or `:warn` (the warning colour).
|
|
974
1029
|
- An `:info` card with no actions and a body of one short line (up to 160
|
|
975
1030
|
characters) is a notice: the web shows it as a one-line row,
|
|
@@ -1006,6 +1061,12 @@ its line being gone.
|
|
|
1006
1061
|
An [anytime command](#anytime-true)'s cards show as it shows them, after its
|
|
1007
1062
|
line, in every UI, whether a turn runs or not.
|
|
1008
1063
|
|
|
1064
|
+
A card from a thread of your own (a sign-in's result, a server's state) that a turn happens to be running beside
|
|
1065
|
+
lands in that turn's block, which the web collapses when the turn ends. `between_turns: true` keeps it out: while a
|
|
1066
|
+
turn runs it is shown as an anytime command's card is (outside the turn's block, marked `anytime: true`), else as
|
|
1067
|
+
any card between turns. It is the rule chi's own sign-in cards follow. The test kit records it on the card
|
|
1068
|
+
(`between_turns: true`). The keyword needs a chi newer than 0.182.0 (an older one raises `ArgumentError`).
|
|
1069
|
+
|
|
1009
1070
|
A worker keeps its last 20 cards (questions included) and, apart, its
|
|
1010
1071
|
last 20 hook notices, for a UI that joins later; a question still waiting
|
|
1011
1072
|
for its answer is always kept. The web shows them where they arrived after a reload (a turn's
|
|
@@ -1018,7 +1079,8 @@ then a new turn) starts from them. Load warnings and a question still
|
|
|
1018
1079
|
waiting when the worker went are not saved.
|
|
1019
1080
|
|
|
1020
1081
|
The event is `{type: :card, id:, source:, title:, body:, level:, actions:,
|
|
1021
|
-
in_turn:}` (`source` is the bundle
|
|
1082
|
+
in_turn:}` (`source` is the bundle; each action `{label:, command:}` or
|
|
1083
|
+
`{label:, url:}`), plus `command:` when a session command
|
|
1022
1084
|
showed it (`"/short"`), logged as `card` with its source, id and title.
|
|
1023
1085
|
|
|
1024
1086
|
## Side answers: `ctx.ask_model`
|
|
@@ -1187,13 +1249,14 @@ shape to copy for a plugin that calls a service, tested on `bundle.http` as in
|
|
|
1187
1249
|
`spec/samagotchi/plugin/http_echo_bundle_spec.rb`.
|
|
1188
1250
|
|
|
1189
1251
|
One way to call an HTTP service, with timeouts, errors, logging and Stop handled the same for every bundle.
|
|
1190
|
-
`Net::HTTP` stays available for what this doesn't do (
|
|
1252
|
+
`Net::HTTP` stays available for what this doesn't do (multipart, redirects, connection reuse).
|
|
1191
1253
|
|
|
1192
1254
|
| | |
|
|
1193
1255
|
|---|---|
|
|
1194
1256
|
| `ctx.http.get(url, headers: {}, timeout: 10)` | GET |
|
|
1195
1257
|
| `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) |
|
|
1196
1258
|
| `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`) |
|
|
1259
|
+
| `ctx.http.stream(method, url, body: nil, headers: {}, timeout: 10) { \|res\| … }` | as `request`, the answer streamed to the block (below); returns the block's value |
|
|
1197
1260
|
|
|
1198
1261
|
Every call also takes `cancel:`, a `Samagotchi::CancellationController`, which replaces the default (below).
|
|
1199
1262
|
|
|
@@ -1225,8 +1288,212 @@ Every call also takes `cancel:`, a `Samagotchi::CancellationController`, which r
|
|
|
1225
1288
|
`purpose=plugin`, the method, the URL **without its query**, the status and the time. Never headers or bodies.
|
|
1226
1289
|
A plugin that polls a dead service therefore logs an ERROR per poll.
|
|
1227
1290
|
|
|
1291
|
+
**Streaming: `ctx.http.stream`** (chi 0.183.0 or newer: guard it with `ctx.http.respond_to?(:stream)`). The block
|
|
1292
|
+
gets a `Samagotchi::Plugin::Http::Stream` as soon as the headers are in:
|
|
1293
|
+
|
|
1294
|
+
```ruby
|
|
1295
|
+
ctx.http.stream("POST", url, body: JSON.generate(question), headers: { "Accept" => "text/event-stream" }) do |res|
|
|
1296
|
+
next "the service answered #{res.status}" unless res.ok? # status and headers before any body
|
|
1297
|
+
|
|
1298
|
+
res.each_event do |event| # event.type ("message" by default), event.data, event.id
|
|
1299
|
+
break event.data if event.type == "done" # leaving the block closes the connection
|
|
1300
|
+
end
|
|
1301
|
+
end
|
|
1302
|
+
```
|
|
1303
|
+
|
|
1304
|
+
- `res.status`, `res.headers` (as `Response`'s), `res.ok?`; then the body, read **once**, by one of
|
|
1305
|
+
`res.each_event { |event| … }` (Server-Sent Events), `res.each_chunk { |bytes| … }` (the raw pieces as they arrive),
|
|
1306
|
+
`res.body` (the rest, read to the end) or `res.json` (`res.body` parsed). After one has read it, another read gives
|
|
1307
|
+
nothing (`body` is `""`).
|
|
1308
|
+
- **Leaving the block closes the connection**, however it is left: its end, `break`, `return`, a raise (which goes on
|
|
1309
|
+
to you as it is). That is how you stop early or keep a total deadline of your own: `timeout` is per read here too,
|
|
1310
|
+
so a stream that sends something every few seconds runs as long as the server likes.
|
|
1311
|
+
- Errors as for `request`: before the block, and **from inside** a read once it started (`HttpError`, `HttpCancelled`
|
|
1312
|
+
on a Stop); a 4xx or 5xx is handed to the block. No retries. The log line is one `http` `stream` line, whatever way
|
|
1313
|
+
the block was left.
|
|
1314
|
+
- The SSE reader: fields `event`, `data`, `id`; several `data:` lines join with `"\n"`; lines starting with `:` are
|
|
1315
|
+
comments; an event is yielded at its blank line (one cut off by the end of the body is dropped, one without `data` too).
|
|
1316
|
+
|
|
1228
1317
|
`ctx.http` is experimental until 1.0, like the test kit.
|
|
1229
1318
|
|
|
1319
|
+
## Secrets: `ctx.secrets`
|
|
1320
|
+
|
|
1321
|
+
What a bundle keeps that must not sit in a plain data file: tokens.
|
|
1322
|
+
|
|
1323
|
+
```ruby
|
|
1324
|
+
ctx.secrets.get("linear") # => String or nil
|
|
1325
|
+
ctx.secrets.set("linear", json_string) # => true
|
|
1326
|
+
ctx.secrets.delete("linear") # => true if there was one
|
|
1327
|
+
ctx.secrets.update("linear") { |old| new_or_nil } # read-change-write under a lock; nil deletes
|
|
1328
|
+
ctx.secrets.backend # => :file (:memory in the test kit), for a status line
|
|
1329
|
+
```
|
|
1330
|
+
|
|
1331
|
+
- Per bundle: bundle `mcp`'s `linear` and another bundle's `linear` are different secrets. A name matches
|
|
1332
|
+
`/\A[a-z0-9][a-z0-9._-]{0,63}\z/` and doesn't end in `.tmp`; a value is a String of at most 16 KB (encode JSON yourself). Anything else
|
|
1333
|
+
raises `ArgumentError`, whose message never holds the value. chi never logs a value, nor shows it in `inspect`.
|
|
1334
|
+
- Where it is: one file per secret, `$XDG_STATE_HOME/samagotchi/plugins/<bundle>/secrets/<name>`, mode 0600 in a
|
|
1335
|
+
0700 folder, written whole. On macOS too: the login Keychain can't take a value through `/usr/bin/security`
|
|
1336
|
+
without it showing in a process list (its stdin mode cuts a line at about 4 KB and its prompt at 128
|
|
1337
|
+
characters), so chi doesn't use it for these.
|
|
1338
|
+
- `update` holds an exclusive lock on the secret for the whole block, across processes: two workers refreshing the
|
|
1339
|
+
same token don't each spend the refresh token, the second one's block gets the first one's new value as `old`.
|
|
1340
|
+
`set` and `delete` take the same lock (kept apart from the values, in `secrets/.locks/`). A `set`, `delete` or
|
|
1341
|
+
`update` of the same secret inside its own `update` block raises `ArgumentError` at once (it would wait for
|
|
1342
|
+
itself): return the new value from the block. The wait has a deadline (`timeout:`, default 30 s), after which it raises
|
|
1343
|
+
`Samagotchi::Plugin::Secrets::Busy`. A store failure (the disk, permissions) raises
|
|
1344
|
+
`Samagotchi::Plugin::Secrets::Unavailable`, naming the store and the secret's name only.
|
|
1345
|
+
- No caching: `get` reads the file each time. Keep the token in memory and read it again on a 401.
|
|
1346
|
+
- What protects the file: a participant's turn never reads chi's state dir, and System 1 never answers for it.
|
|
1347
|
+
chi's own model is kept off it too ([Protected paths](guardrails.md#protected-paths)): `read`, `write`, `edit` and a
|
|
1348
|
+
plugin tool's `targets:` paths under `plugins/<bundle>/secrets/` are denied, and a shell command that names that
|
|
1349
|
+
folder asks the user once. That is an accident guard, not a sandbox: a command that doesn't name the folder (one
|
|
1350
|
+
that `cd`s there first, a variable, a script) still reads it, as the owner's own processes can.
|
|
1351
|
+
- On a participant's turn (`ctx.turn_author` set) a plugin runs with the owner's power, so `ctx.secrets` works
|
|
1352
|
+
there. Using a token you already have is the same as a stdio server's env secret today; don't start a sign-in on
|
|
1353
|
+
a participant's turn.
|
|
1354
|
+
- `chi bundle uninstall` leaves `plugins/<bundle>/` in place, secrets included. Offer a command that forgets them
|
|
1355
|
+
(`ctx.secrets.delete`).
|
|
1356
|
+
- In the test kit `ctx.secrets` is in memory: `bundle.set(secrets: { "linear" => "..." })` (or `host:` on load)
|
|
1357
|
+
seeds it, `bundle.secrets` reads what the plugin kept. A bundle's specs never touch the disk for it.
|
|
1358
|
+
|
|
1359
|
+
Needs chi 0.183.0 (`ctx.respond_to?(:secrets)`).
|
|
1360
|
+
|
|
1361
|
+
## Sign-in: `ctx.sign_in`
|
|
1362
|
+
|
|
1363
|
+
Send the session's owner to an address and get back the address the browser was sent to. OAuth is the first use;
|
|
1364
|
+
core knows nothing of OAuth but one check (`state`, below).
|
|
1365
|
+
|
|
1366
|
+
```ruby
|
|
1367
|
+
flow = ctx.sign_in(title: "Sign in to Linear", button: "Open sign-in page", timeout: 300) do |redirect_uri|
|
|
1368
|
+
authorize_url(redirect_uri) # the bundle builds it; it holds its own state / PKCE
|
|
1369
|
+
end
|
|
1370
|
+
flow.card_id # the card core showed; the bundle replaces it with its result
|
|
1371
|
+
flow.redirect_uri # "http://127.0.0.1:53123/callback"
|
|
1372
|
+
Thread.new do
|
|
1373
|
+
result = flow.wait # blocks: => {"code"=>"…", "state"=>"…", "iss"=>"…"} (the callback's query), or nil
|
|
1374
|
+
next ctx.card(id: flow.card_id, title: "Sign-in failed", body: flow.outcome.to_s) unless result
|
|
1375
|
+
|
|
1376
|
+
token = exchange(result["code"]) # check iss / error yourself
|
|
1377
|
+
ctx.secrets.set("linear", token)
|
|
1378
|
+
ctx.card(id: flow.card_id, title: "Signed in to Linear")
|
|
1379
|
+
end
|
|
1380
|
+
flow.outcome # :done, :timed_out, :cancelled, :stopped (the worker leaving), nil while waiting
|
|
1381
|
+
flow.cancel
|
|
1382
|
+
```
|
|
1383
|
+
|
|
1384
|
+
What the user sees: a card with the title, one button that opens the address in a new tab (the terminal prints it
|
|
1385
|
+
whole), and the line "If the browser ends on a page that doesn't load, copy that page's address and run
|
|
1386
|
+
`/callback <address>`."
|
|
1387
|
+
|
|
1388
|
+
- `ctx.sign_in` returns at once; `flow.wait` blocks, so call it on a thread of your own (a session command must not
|
|
1389
|
+
sit for minutes). `timeout:` is 60..900 seconds (default 300); `port:` asks for a fixed port when the provider's
|
|
1390
|
+
registered redirect address is exact (a taken one raises `ArgumentError` naming it); `path:` defaults to
|
|
1391
|
+
`/callback`. A block that raises, an address that isn't an http(s) one a card takes, or one without `state`
|
|
1392
|
+
(below), raises and leaves nothing open.
|
|
1393
|
+
- The browser comes back to a listener on `127.0.0.1` only, in the worker: it answers `GET <path>?…` and nothing
|
|
1394
|
+
else (a 404, and the wait goes on), reads at most 8 KB within 5 s per connection, reads several connections at
|
|
1395
|
+
once (a silent one, such as a browser's preconnect, never holds the callback up; one that breaks is dropped
|
|
1396
|
+
alone), answers the callback with a static "Signed in. You can close this tab." page and stops listening. Should
|
|
1397
|
+
the listener fail anyway, its port closes and the flow ends `:cancelled`. A browser on another device
|
|
1398
|
+
ends on that address, which doesn't load there: the user pastes it with `/callback` ([cli.md](cli.md)), which
|
|
1399
|
+
settles the flow the same way.
|
|
1400
|
+
- Your address must have a `state` query parameter, a fresh random one per sign-in: `ctx.sign_in` raises
|
|
1401
|
+
`ArgumentError` (and leaves nothing open) when it hasn't, since without it any local process, or a page in the
|
|
1402
|
+
owner's browser, could finish the flow with its own code. A callback whose `state` differs is ignored, browser or
|
|
1403
|
+
pasted. Check everything else (`iss`, `error`) yourself.
|
|
1404
|
+
- On `:done` core leaves the card for you: replace `flow.card_id` with your result, as a command's card is
|
|
1405
|
+
replaced. On `:timed_out`, `:cancelled` and `:stopped` core replaces it ("Sign-in timed out" / "Sign-in
|
|
1406
|
+
cancelled", no button). The flow's cards are never a running turn's.
|
|
1407
|
+
- A flow never outlives its worker: an exit, a restart or a crash's shutdown stops it, its card replaced first, so a
|
|
1408
|
+
card a later worker loads never offers a dead sign-in. An idle exit waits for a waiting flow.
|
|
1409
|
+
- A flow is tied to no turn by default: the session's Stop doesn't end it (`flow.cancel` and its timeout do). To let
|
|
1410
|
+
Stop end it, pass `cancel:` a `Samagotchi::CancellationController`, the flow polls it (about once a second) and ends
|
|
1411
|
+
`:cancelled` with the cancelled card. A tool that signs in mid-turn passes `ctx.cancel_controller` read on its own
|
|
1412
|
+
thread (a tool's is its turn's); a session command between turns has none (`nil`, the default).
|
|
1413
|
+
|
|
1414
|
+
```ruby
|
|
1415
|
+
chi.tool "linear_search", "…", params: {} do |args, ctx|
|
|
1416
|
+
flow = ctx.sign_in(title: "Sign in to Linear", cancel: ctx.cancel_controller) { |uri| authorize_url(uri) }
|
|
1417
|
+
result = flow.wait # on the turn's thread: Stop ends it (nil, flow.outcome == :cancelled)
|
|
1418
|
+
next "sign-in #{flow.outcome}" unless result
|
|
1419
|
+
# …
|
|
1420
|
+
end
|
|
1421
|
+
```
|
|
1422
|
+
- No one to ask: a one-shot run (`ctx.frontend == :one_shot`), a `:generation_progress` handler, and any call once
|
|
1423
|
+
the worker has begun to leave (a command still running at an exit, a thread of yours) get a flow that is
|
|
1424
|
+
`:stopped` already (`wait` → nil), with no card and no port.
|
|
1425
|
+
- The pasted address holds a one-time code: chi shows the line as `/callback …` in every event, UI and log. Best
|
|
1426
|
+
effort is enough there: the code is single-use and, with PKCE, useless without the verifier that never leaves the
|
|
1427
|
+
worker. chi logs the address's host and path only (an authorize address can carry a login hint).
|
|
1428
|
+
A `/callback` line is always the command, never a message: one with more lines is refused (one line only), and
|
|
1429
|
+
one that can't run as a command (with images, from a delegate, a schedule or a plugin) is refused, not sent to the
|
|
1430
|
+
model. A trailing `#fragment` is dropped. The shared prompt history (history.json) keeps no `/callback` line, a
|
|
1431
|
+
`/cut` or `/queue` one in the terminal neither; a chi web older than 0.183.0 in front of this worker does record
|
|
1432
|
+
one sent from its page.
|
|
1433
|
+
- A participant never sees the card (their view has no cards) and can't send `/callback`; a parent agent's
|
|
1434
|
+
`chi answer` can't either. Don't start a sign-in on a participant's turn (`ctx.turn_author`).
|
|
1435
|
+
- In the test kit `ctx.sign_in` opens no port: `bundle.sign_ins` lists the flows (`title`, `address` the block
|
|
1436
|
+
built, `redirect_uri`, `card_id`, `outcome`), `bundle.complete_sign_in("code" => "c1", "state" => "…")` and
|
|
1437
|
+
`bundle.fail_sign_in(:timed_out)` settle the newest.
|
|
1438
|
+
|
|
1439
|
+
Needs chi 0.183.0 (`ctx.respond_to?(:sign_in)`).
|
|
1440
|
+
|
|
1441
|
+
### A whole bundle: sign-in-echo
|
|
1442
|
+
|
|
1443
|
+
`spec/fixtures/sign_in_echo_bundle` (chi's own specs test it the way a bundle's spec would): `/echo-login` sends you
|
|
1444
|
+
to a provider's page, keeps the code the browser brings back with `ctx.secrets` (it exchanges nothing: a real
|
|
1445
|
+
bundle trades the code for a token there), and replaces the card; the `echo_token` tool reads it back.
|
|
1446
|
+
|
|
1447
|
+
```ruby
|
|
1448
|
+
# The sign-in-echo bundle (spec fixture, docs/plugins.md "Sign-in"):
|
|
1449
|
+
# /echo-login sends you to a provider's sign-in page, keeps the code the
|
|
1450
|
+
# browser brings back as a secret (it exchanges nothing), and the
|
|
1451
|
+
# echo_token tool reads it back.
|
|
1452
|
+
require "securerandom"
|
|
1453
|
+
require "uri"
|
|
1454
|
+
|
|
1455
|
+
class Plugin
|
|
1456
|
+
def initialize(settings)
|
|
1457
|
+
@authorize = settings.fetch("authorize_url", "http://127.0.0.1:9100/authorize")
|
|
1458
|
+
end
|
|
1459
|
+
|
|
1460
|
+
def register(chi)
|
|
1461
|
+
chi.command "/echo-login", "sign in to the echo provider" do |_args, ctx|
|
|
1462
|
+
state = SecureRandom.hex(16)
|
|
1463
|
+
flow = ctx.sign_in(title: "Sign in to Echo", button: "Open sign-in page", timeout: 300) do |redirect_uri|
|
|
1464
|
+
"#{@authorize}?#{URI.encode_www_form(redirect_uri: redirect_uri, state: state)}"
|
|
1465
|
+
end
|
|
1466
|
+
next "sign-in needs the web or a terminal" if flow.outcome == :stopped
|
|
1467
|
+
|
|
1468
|
+
# flow.wait blocks: never on the command's thread.
|
|
1469
|
+
Thread.new do
|
|
1470
|
+
result = flow.wait
|
|
1471
|
+
if result && result["code"]
|
|
1472
|
+
ctx.secrets.update("echo") { result["code"] }
|
|
1473
|
+
ctx.card(id: flow.card_id, title: "Signed in to Echo", body: "The echo_token tool reads it.")
|
|
1474
|
+
end
|
|
1475
|
+
end
|
|
1476
|
+
nil
|
|
1477
|
+
end
|
|
1478
|
+
|
|
1479
|
+
chi.tool "echo_token", "Read back the code the echo sign-in kept", params: {}, label: "reading" do |_args, ctx|
|
|
1480
|
+
code = ctx.secrets.get("echo")
|
|
1481
|
+
code ? "signed in: #{code}" : "not signed in (run /echo-login)"
|
|
1482
|
+
end
|
|
1483
|
+
end
|
|
1484
|
+
end
|
|
1485
|
+
```
|
|
1486
|
+
|
|
1487
|
+
Its spec, on the kit:
|
|
1488
|
+
|
|
1489
|
+
```ruby
|
|
1490
|
+
bundle.command("/echo-login")
|
|
1491
|
+
state = URI.decode_www_form(URI(bundle.sign_ins.last.address).query).to_h["state"]
|
|
1492
|
+
bundle.complete_sign_in("code" => "C1", "state" => state)
|
|
1493
|
+
wait_for("the code") { bundle.secrets["echo"] }
|
|
1494
|
+
expect(bundle.tool("echo_token")).to eq("signed in: C1")
|
|
1495
|
+
```
|
|
1496
|
+
|
|
1230
1497
|
## Other sessions: `ctx.sessions`
|
|
1231
1498
|
|
|
1232
1499
|
```ruby
|
|
@@ -1431,7 +1698,19 @@ block_renderers:
|
|
|
1431
1698
|
replies, a lead-in bubble, delegate reports and the doc viewer show the source, and so does the terminal.
|
|
1432
1699
|
- **The script's side:** the last file calls `chi.defineRenderer({ init, render })`. `init()` (optional, may be async)
|
|
1433
1700
|
runs once; `render(source, theme)` returns the SVG as a string, or a promise of one. Throw to keep the block as
|
|
1434
|
-
source
|
|
1701
|
+
source (the model's diagram is wrong: chi may ask it for a fixed one). **Regions:** when `chi.features?.regions` is
|
|
1702
|
+
true (an older chi's frame takes a string only, so check it), `render` may return
|
|
1703
|
+
`{ svg, regions }`: the diagram's parts, so the picture viewer can make them tappable. A region is
|
|
1704
|
+
`{ kind: "node" | "group" | "edge" | "note", id, label, box: [x, y, w, h], points, from, to }`: `id` the source's
|
|
1705
|
+
own name, `label` the text shown, `box` and `points` fractions of the picture (0..1); `box` is required but for an
|
|
1706
|
+
edge, whose optional `box` is its label's; an edge has 2..16 `points` along its line and, when the bundle can name
|
|
1707
|
+
them, the ids of its ends in `from` and `to`. A region with nothing to call it by (no `label` and no `id`; an
|
|
1708
|
+
edge, no `label` and not both ends) isn't tappable. Two regions with one kind and id (a sequence participant's top and
|
|
1709
|
+
bottom box) select together. Past 600 regions none are taken; chi cleans and caps the rest
|
|
1710
|
+
([internals/block-renderers.md](internals/block-renderers.md#regions)), and uses them as text and numbers only.
|
|
1711
|
+
An object without a string `svg` is the bundle's own bug: the block stays source with its line, and no fix is
|
|
1712
|
+
asked of the model. Returning no object (`undefined`, a number) is a failed render as before, which chi may ask
|
|
1713
|
+
the model to fix. A measuring failure should return the SVG with no regions, never throw. `theme` is `{name, bg, panel, text, muted, border, accent, font}`, from the page's tokens. The script runs in
|
|
1435
1714
|
a sandboxed frame with no cookie and no access to the page, and the CSP closes its network, but for WebRTC (what the
|
|
1436
1715
|
frame holds, the diagrams it rendered, could leave that way). The SVG is shown as an `<img>`, so its scripts, links
|
|
1437
1716
|
and remote images don't run: it has to stand alone (no `foreignObject`, every namespace prefix bound) and stay under 50,000 px a
|
|
@@ -1456,7 +1735,10 @@ that calls it, or for a real external bundle that does. No method on the chance
|
|
|
1456
1735
|
`Samagotchi::Plugin::Service::Stopped`, `Samagotchi::Plugin::Sessions::Error`
|
|
1457
1736
|
and `Samagotchi::Plugin::AttachedContext::Error`. `ctx.http` and its
|
|
1458
1737
|
`Samagotchi::Plugin::HttpError` (with the subclass `HttpCancelled`) and
|
|
1459
|
-
`Samagotchi::Plugin::Http::Response`
|
|
1738
|
+
`Samagotchi::Plugin::Http::Response`, `Http::Stream` (what `ctx.http.stream` yields) and
|
|
1739
|
+
`Http::SseReader` (its SSE reader, `SseReader.new.feed(bytes) { |event| … }`, for an `each_chunk` loop that checks
|
|
1740
|
+
a deadline of its own) are **experimental until 1.0**, like the test kit. So are `ctx.secrets`' errors,
|
|
1741
|
+
`Samagotchi::Plugin::Secrets::Busy` and `Samagotchi::Plugin::Secrets::Unavailable` (a bundle rescues them by name).
|
|
1460
1742
|
2. `Samagotchi::Plugin::Peer` as a base class. A subclass defines `post`,
|
|
1461
1743
|
`check_hint!`, `paired_lines`, `transport_line`, `peer_dir` and
|
|
1462
1744
|
`setup_paragraph` (optionally `skill_substitutions`), and sets `NAME`,
|
|
@@ -1495,8 +1777,8 @@ that calls it, or for a real external bundle that does. No method on the chance
|
|
|
1495
1777
|
upgraded.
|
|
1496
1778
|
- A bundle declares its floor with `requires_chi`, and an install below it is refused (`--force` aside).
|
|
1497
1779
|
There is no `api_version:`.
|
|
1498
|
-
- `block_renderers
|
|
1499
|
-
of it. Neither is Ruby, so the scan below doesn't see them.
|
|
1780
|
+
- `block_renderers:`, the frame's `chi.defineRenderer` and `chi.features` (`regions`: `render` may return
|
|
1781
|
+
`{ svg, regions }`) ([Block renderers](#block-renderers)) are part of it. Neither is Ruby, so the scan below doesn't see them.
|
|
1500
1782
|
|
|
1501
1783
|
`Samagotchi::Testing::Boundary::ALLOWED` is the checked copy of items 1-6,
|
|
1502
1784
|
and `Boundary::EXCEPTIONS` the per-bundle list of what each shipped bundle
|
|
@@ -1592,7 +1874,10 @@ bundle.shutdown
|
|
|
1592
1874
|
answered raises `Samagotchi::Testing::UnstubbedRequest` (not an `HttpError`, but a plugin may rescue it anyway) and
|
|
1593
1875
|
**fails the test at teardown** (RSpec and Minitest adapters: after the cleanup, and only a test that passed), so a
|
|
1594
1876
|
spec can't reach the network. With plain `Bundle.load` there is no teardown: check `bundle.http.unmatched`.
|
|
1595
|
-
`bundle.set(cancelled: true)` makes a call without `cancel:` raise `HttpCancelled
|
|
1877
|
+
`bundle.set(cancelled: true)` makes a call without `cancel:` raise `HttpCancelled` (and `ctx.cancel_controller` a cancelled controller). For `ctx.http.stream`,
|
|
1878
|
+
`events:` (an Array of `{ data:, event: nil, id: nil }` or plain Strings for `data`, served as `text/event-stream`)
|
|
1879
|
+
and `chunks:` (Strings, the body in those pieces) answer it; a `body:` / `json:` stub answers a stream as one chunk,
|
|
1880
|
+
and an `events:` stub answers a plain request with the events' SSE text. A block may return them too.
|
|
1596
1881
|
- **`ctx.cost`** is zero and known unless the test sets it: `bundle.set(cost: 2.5)` (reported USD), a Hash of the
|
|
1597
1882
|
parts (`reported:`, `estimated:`, `side:`, `known:`; `total` is reported + estimated) or a callable giving either,
|
|
1598
1883
|
called at each read (a counting lambda shows whether the bundle read it).
|
|
@@ -1653,12 +1938,14 @@ When a session's worker exits (an idle exit, `/exit`, a crash, TERM), or a
|
|
|
1653
1938
|
Plugins load when a session starts (`Engine.new`, in a worker or a
|
|
1654
1939
|
`--non-interactive` one-shot), after the config hooks. The steps are:
|
|
1655
1940
|
|
|
1656
|
-
1.
|
|
1941
|
+
1. Every file of the plugin (its parts, then the plugin file) must match the sha256 recorded at install (not
|
|
1942
|
+
checked for a bundle installed with `--dev`); the first that doesn't fails the whole plugin.
|
|
1657
1943
|
2. chi must meet `requires_chi`. A bundle whose `requires_chi` this chi doesn't
|
|
1658
1944
|
meet is refused at install, so this step is reached only by one installed
|
|
1659
1945
|
with `--force` or by a chi that has since been downgraded.
|
|
1660
|
-
3. The file
|
|
1661
|
-
(`Samagotchi::Bundles::<bundle>`, `Plugin::Loader.namespace_for`)
|
|
1946
|
+
3. The parts, in the manifest's order, then the file are `module_eval`'d into one new module in the bundle's
|
|
1947
|
+
namespace (`Samagotchi::Bundles::<bundle>`, `Plugin::Loader.namespace_for`); a failure names the file and line
|
|
1948
|
+
it happened in.
|
|
1662
1949
|
4. The class is built, and `register(chi)` runs.
|
|
1663
1950
|
|
|
1664
1951
|
What `register` adds takes effect only when it returns. A plugin that raises
|
|
@@ -1685,11 +1972,11 @@ A plugin is Ruby code that runs inside chi with your permissions.
|
|
|
1685
1972
|
gem.
|
|
1686
1973
|
|
|
1687
1974
|
- The sha256 is an integrity check, not proof of who wrote the file. A file
|
|
1688
|
-
edited after install is not loaded until you reinstall the bundle: the plugin,
|
|
1975
|
+
edited after install is not loaded until you reinstall the bundle: the plugin (any of its parts),
|
|
1689
1976
|
a rule or a script that isn't recorded, is missing or changed is refused in one
|
|
1690
1977
|
wording, checked in that order (`bundle NAME's plugin/plugin.rb differs from
|
|
1691
1978
|
the installed one (reinstall the bundle)`), and `chi bundle status NAME` shows
|
|
1692
|
-
the plugin `[unrecorded]`, `[missing]` or `[modified]
|
|
1979
|
+
the plugin `[unrecorded]`, `[missing]` or `[modified]` (a part on its own line under it). A
|
|
1693
1980
|
`--dev` install skips that check for its own bundle: its files are the
|
|
1694
1981
|
source directory's, and an edit loads at the next start.
|
|
1695
1982
|
- Install only copies the file (`--dev` links it). The code first runs at the
|
|
@@ -1704,8 +1991,8 @@ gem.
|
|
|
1704
1991
|
|
|
1705
1992
|
## The bundle commands
|
|
1706
1993
|
|
|
1707
|
-
- `chi bundle install <dir>`: copies the plugin to
|
|
1708
|
-
`<memories>/.bundles/<name>/plugin/`. It records
|
|
1994
|
+
- `chi bundle install <dir>`: copies the plugin (and its parts) to
|
|
1995
|
+
`<memories>/.bundles/<name>/plugin/`. It records each file's sha256 and
|
|
1709
1996
|
`requires_chi`, and refuses a plugin or script whose bytes disagree with its
|
|
1710
1997
|
declared sha256 (`--force` installs it anyway, with the `Checksum mismatch`
|
|
1711
1998
|
warning; an automatic `chi update` of a shipped bundle only warns). A bundle whose
|
|
@@ -1723,9 +2010,9 @@ gem.
|
|
|
1723
2010
|
new one and says `Source changes: old → new`. A dev install is refused: it
|
|
1724
2011
|
already follows its source.
|
|
1725
2012
|
- `chi bundle status [<name>]`: shows `plugin=plugin.rb` in the list. For
|
|
1726
|
-
one bundle it shows `Plugin: plugin.rb [ok|modified|missing]
|
|
1727
|
-
`requires_chi` failure.
|
|
1728
|
-
- `chi bundle diff <name> [plugin.rb]`: shows the installed base and the
|
|
2013
|
+
one bundle it shows `Plugin: plugin.rb [ok|modified|missing]`, a line per part that isn't ok
|
|
2014
|
+
(`part client.rb [modified]`) and a `requires_chi` failure.
|
|
2015
|
+
- `chi bundle diff <name> [plugin.rb | <part>]`: shows the installed base and the
|
|
1729
2016
|
file on disk; for a memory file that stays behind, also the bundle's new text.
|
|
1730
2017
|
- `chi bundle build --name <name>`: puts the installed plugin (and
|
|
1731
2018
|
`requires_chi`, its `scripts/` and `context_providers:`) into the built
|