samagotchi 0.60.0 → 0.62.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 +99 -1
- data/docs/architecture.md +10 -4
- data/docs/cli.md +22 -8
- data/docs/configuration.md +32 -19
- data/docs/context.md +8 -0
- data/docs/guardrails.md +2 -1
- data/docs/hooks.md +80 -1
- data/docs/internals/engine.md +57 -15
- data/docs/internals/prompt-caching.md +8 -1
- data/docs/plugins.md +49 -6
- data/docs/sessions.md +7 -3
- data/docs/testing.md +4 -1
- data/lib/samagotchi/answer_display.rb +4 -3
- data/lib/samagotchi/answer_refs.rb +210 -0
- data/lib/samagotchi/bridge/card_store.rb +6 -1
- data/lib/samagotchi/bundles/check-in/manifest.yml +2 -2
- data/lib/samagotchi/bundles/check-in/plugin.rb +27 -3
- data/lib/samagotchi/bundles/github-pr/manifest.yml +3 -3
- data/lib/samagotchi/bundles/github-pr/plugin.rb +70 -14
- data/lib/samagotchi/bundles/slow-commands/manifest.yml +2 -2
- data/lib/samagotchi/bundles/slow-commands/plugin.rb +5 -1
- data/lib/samagotchi/bundles/source-links/hooks/source_links.rb +58 -3
- data/lib/samagotchi/bundles/source-links/manifest.yml +4 -4
- data/lib/samagotchi/bundles/source-links/source_links.md +1 -1
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/engine.rb +47 -9
- data/lib/samagotchi/engine_peers.rb +1 -0
- data/lib/samagotchi/hooks/registry.rb +3 -1
- data/lib/samagotchi/interrupted_turn.rb +39 -0
- data/lib/samagotchi/kernel_loop.rb +13 -20
- data/lib/samagotchi/llm/chat_loop.rb +28 -17
- data/lib/samagotchi/log_subscriber.rb +6 -3
- data/lib/samagotchi/plugin/api.rb +36 -18
- data/lib/samagotchi/reasoning_history.rb +22 -4
- data/lib/samagotchi/ref.rb +25 -8
- data/lib/samagotchi/reply_wait.rb +6 -2
- data/lib/samagotchi/row_refs.rb +126 -0
- data/lib/samagotchi/session.rb +40 -4
- data/lib/samagotchi/session_manager.rb +64 -6
- data/lib/samagotchi/session_metrics.rb +24 -2
- data/lib/samagotchi/terminal_ui/formatting.rb +1 -1
- data/lib/samagotchi/terminal_ui.rb +30 -3
- data/lib/samagotchi/tool_activity.rb +8 -4
- data/lib/samagotchi/tool_response.rb +5 -4
- data/lib/samagotchi/tool_row_fields.rb +4 -2
- data/lib/samagotchi/tool_runner.rb +16 -3
- data/lib/samagotchi/tools/builtins.rb +9 -2
- data/lib/samagotchi/tools/execute.rb +15 -3
- data/lib/samagotchi/tools/peers.rb +3 -2
- data/lib/samagotchi/tools/registry.rb +5 -3
- data/lib/samagotchi/turn_checkpoint.rb +128 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +19 -1
- data/lib/samagotchi/web/message_parts.rb +17 -9
- data/lib/samagotchi/web/public/activity.js +4 -1
- data/lib/samagotchi/web/public/answer_refs.js +217 -0
- data/lib/samagotchi/web/public/app.js +74 -33
- data/lib/samagotchi/web/public/chains.js +18 -20
- data/lib/samagotchi/web/public/context_chips.js +92 -64
- data/lib/samagotchi/web/public/families_view.js +51 -39
- data/lib/samagotchi/web/public/index.html +66 -13
- data/lib/samagotchi/web/public/keep_focus.js +24 -0
- data/lib/samagotchi/web/public/lists_view.js +13 -13
- data/lib/samagotchi/web/public/llm_context_chip.js +55 -34
- data/lib/samagotchi/web/public/question_card.js +11 -0
- data/lib/samagotchi/web/public/question_cards.js +60 -5
- data/lib/samagotchi/web/public/ref_menu.js +24 -3
- data/lib/samagotchi/web/public/ref_scan.js +5 -3
- data/lib/samagotchi/web/public/refs.js +140 -20
- data/lib/samagotchi/web/public/scroll.js +42 -0
- data/lib/samagotchi/web/public/stage_model.js +22 -3
- data/lib/samagotchi/web/public/stage_view.js +299 -70
- data/lib/samagotchi/web/public/stream_handlers.js +5 -3
- data/lib/samagotchi/web/public/timing.js +1 -1
- data/lib/samagotchi/web/public/turn_html.js +5 -4
- data/lib/samagotchi/web/public/turn_model.js +49 -0
- data/lib/samagotchi/web/public/turn_view.js +121 -17
- data/lib/samagotchi/worker.rb +169 -21
- data/lib/samagotchi/worker_inbound.rb +5 -3
- data/lib/samagotchi/worker_signals.rb +81 -0
- metadata +8 -1
data/docs/plugins.md
CHANGED
|
@@ -144,7 +144,7 @@ chi's own, each bundle's with the bundle's name, and the terminal UIs' own
|
|
|
144
144
|
`attached only`, `repl only`, or `terminal and web only` (`/cut`).
|
|
145
145
|
It works in all three UIs.
|
|
146
146
|
|
|
147
|
-
### `chi.tool(name, description, params:, schema:, label:, preview:, targets:) { |args, ctx| … }`
|
|
147
|
+
### `chi.tool(name, description, params:, schema:, label:, preview:, targets:, refs:) { |args, ctx| … }`
|
|
148
148
|
|
|
149
149
|
This adds a tool the model can call. It is declared in the system prompt and
|
|
150
150
|
in the chat path's `tools:`, after chi's own tools.
|
|
@@ -166,6 +166,8 @@ in the chat path's `tools:`, after chi's own tools.
|
|
|
166
166
|
plugins.
|
|
167
167
|
- `targets`: `->(args) { { paths: [...], command: "…", cwd: "…", acts_as: "…", args: {…}, label: "…" } }`,
|
|
168
168
|
each key optional, says what a call acts on, for [guardrails](#guardrails).
|
|
169
|
+
- `refs`: `->(args) { [{ kind:, target:, label:, actions: [] }, …] }`, what the call's row traces to in the web
|
|
170
|
+
(display only, the model never sees them). See [Refs on a tool's row](#refs-on-a-tools-row).
|
|
169
171
|
|
|
170
172
|
The block returns the result text. If it starts with `Error:`, it counts as
|
|
171
173
|
a failure. If it raises, the model gets `Error: <message>`. To return images
|
|
@@ -174,7 +176,7 @@ too, see [Returning images](#returning-images).
|
|
|
174
176
|
#### `args`
|
|
175
177
|
|
|
176
178
|
`args` is a frozen Hash with **string keys**: the arguments the model gave,
|
|
177
|
-
by name (`args["text"]`). The same Hash goes to `preview` and `
|
|
179
|
+
by name (`args["text"]`). The same Hash goes to `preview`, `targets` and `refs`.
|
|
178
180
|
|
|
179
181
|
Each parser gives them structured: Gemma's native values (strings, numbers,
|
|
180
182
|
booleans, lists, nested objects), Qwen's `<parameter=…>` text, and the chat
|
|
@@ -261,6 +263,42 @@ does loop-guard's `ignore_tools`.
|
|
|
261
263
|
A tool without `targets:` is matched by its name only. A `targets:` that
|
|
262
264
|
raises counts as nothing (it is logged). See [guardrails.md](guardrails.md).
|
|
263
265
|
|
|
266
|
+
#### Refs on a tool's row
|
|
267
|
+
|
|
268
|
+
`refs:` gives the call's web row its refs: a ticket the tool looked up, the PR it opened, a file it wrote.
|
|
269
|
+
Each is a ref as on the answer ([Refs on the answer](hooks.md#refs-on-the-answer-display-only), without
|
|
270
|
+
`match:`):
|
|
271
|
+
|
|
272
|
+
```ruby
|
|
273
|
+
chi.tool "ticket", "Look up a Jira ticket", params: { id: { type: "string", required: true } },
|
|
274
|
+
refs: ->(args) {
|
|
275
|
+
[{ kind: "issue", target: { id: args["id"] }, label: "#{args["id"]} in Jira",
|
|
276
|
+
actions: [{ id: "open", label: "Open in Jira", url: "https://jira.example/browse/#{args["id"]}" }] }]
|
|
277
|
+
} do |args, ctx|
|
|
278
|
+
# …
|
|
279
|
+
end
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
- `kind`: `"file"` with `target: { path:, line:, end_line: }`, or any short lowercase word (`issue`,
|
|
283
|
+
`commit`, …) with `target: { id: }`.
|
|
284
|
+
- A file's `path` is absolute or relative to the session's folder, and must be **under** it (its own
|
|
285
|
+
spelling or its real path: `/tmp/x` or `/private/tmp/x`): a file elsewhere is dropped. It is kept under
|
|
286
|
+
the folder's real path.
|
|
287
|
+
- `actions`: up to 8 `{ id:, label:, url: }`, each URL `http(s)` only. A file ref keeps the editor, show in
|
|
288
|
+
turn and copy; its actions add to them.
|
|
289
|
+
- The web puts the row's **first** ref on its title (a click runs its first action) and the others in the
|
|
290
|
+
title's `▾` menu, each as `<its label> · <action>` with the URL on hover. URL actions show for every viewer,
|
|
291
|
+
the phone too; a file's "Open in editor" only where the editor opens (this machine).
|
|
292
|
+
- It runs **once per call, on the tool path**, before the call runs: keep it cheap, with no I/O (no
|
|
293
|
+
network, no file reads); build the refs from `args` alone.
|
|
294
|
+
- If it raises or returns something other than a list, the row gets no refs and the tool still runs; a bad
|
|
295
|
+
ref (an unknown kind, a `javascript:` URL, a file outside the folder) is dropped. Both are logged (tag
|
|
296
|
+
`plugins`, `tool_refs_failed` / `tool_refs_rejected`).
|
|
297
|
+
- At most 20 refs per row (64 KiB of them). They are saved with the result (`tool_refs`), so a reload shows them without the
|
|
298
|
+
plugin, checked again.
|
|
299
|
+
- `chi.replace_tools` swaps a kept tool's block, `preview:`, `targets:` and `refs:` in place: none of them is a
|
|
300
|
+
change to the prompt.
|
|
301
|
+
|
|
264
302
|
#### Returning images
|
|
265
303
|
|
|
266
304
|
A tool can hand the model images too. The block returns a
|
|
@@ -330,7 +368,8 @@ end
|
|
|
330
368
|
This is a bundle hook, the same as a `hooks/*.rb` file. See
|
|
331
369
|
[hooks.md](hooks.md#hook-events) for the events; on `:after_turn`,
|
|
332
370
|
`event[:present]` sets how the answer is shown in the web
|
|
333
|
-
([Presenting the answer](hooks.md#presenting-the-answer-display-only))
|
|
371
|
+
([Presenting the answer](hooks.md#presenting-the-answer-display-only)) and `event[:refs]`
|
|
372
|
+
attaches refs to it ([Refs on the answer](hooks.md#refs-on-the-answer-display-only)). Its label is
|
|
334
373
|
`plugin.rb (bundle my-bundle)`. The block may take only the event. If it
|
|
335
374
|
raises, the error is logged and the hook is skipped.
|
|
336
375
|
|
|
@@ -1127,13 +1166,16 @@ what it has found. check-in counts the turn's tool calls, and when there are
|
|
|
1127
1166
|
and its last few tools, and three actions:
|
|
1128
1167
|
- **Nudge** (`/checkin nudge`): puts `message` into the running turn
|
|
1129
1168
|
(`ctx.steer`); the model reads it at its next step and answers or says
|
|
1130
|
-
what is left. Every UI shows `check-in> nudged: …`.
|
|
1169
|
+
what is left. Every UI shows `check-in> nudged: …`. One nudge per
|
|
1170
|
+
check-in: another click (or a typed `/checkin nudge`) answers
|
|
1171
|
+
"check-in: already nudged at N tool calls".
|
|
1131
1172
|
- **Keep going** (`/checkin later`): closes the card until the next
|
|
1132
1173
|
check-in.
|
|
1133
1174
|
- **Stop** (`/checkin stop`): stops the turn.
|
|
1134
1175
|
|
|
1135
1176
|
When the turn ends the card loses its actions ("The turn ended after N tool
|
|
1136
|
-
calls"), so no stale buttons stay
|
|
1177
|
+
calls"), so no stale buttons stay; a card left by a worker that exited
|
|
1178
|
+
mid-turn comes back without them too. In the attached terminal the actions are
|
|
1137
1179
|
`→ /checkin nudge` lines to type; the command runs beside the turn.
|
|
1138
1180
|
- **`mode: nudge`**: nudges the model by itself, with a notice line.
|
|
1139
1181
|
- **`mode: notify`**: a notice line only.
|
|
@@ -1377,7 +1419,8 @@ and a summary of what changed in counts, authors and states only; it wakes
|
|
|
1377
1419
|
the session for a review requesting changes, checks turning red, or the PR
|
|
1378
1420
|
merged or closed. In the web, a `path:line` in a worker's answer links to
|
|
1379
1421
|
that line of the session's PR ([Line links](context.md#line-links); `line_links:
|
|
1380
|
-
always` for the REPL and `chi -p` too)
|
|
1422
|
+
always` for the REPL and `chi -p` too), and its ref menu offers the file
|
|
1423
|
+
here and a "PR diff" action (`event[:refs]`). `auto_attach:
|
|
1381
1424
|
offer` asks with a card first (`/pr-attach N`, `/pr-decline N`), `off`
|
|
1382
1425
|
attaches nothing ([Attach, offer or off](context.md#attach-offer-or-off)).
|
|
1383
1426
|
See [Attached context](context.md#github-prs-the-github-pr-bundle).
|
data/docs/sessions.md
CHANGED
|
@@ -21,7 +21,11 @@ A session is deleted if **expired by age OR overflow by count** (unless `keep_st
|
|
|
21
21
|
|
|
22
22
|
**Which chi a worker runs:** a new or woken worker runs the newest chi installed for this Ruby (`gem 'samagotchi', '>= 0.a'`, prereleases count), whoever starts it: a `chi web` or terminal still on an older chi starts it on the newest one, so a stale process doesn't spread old code. A worker already running keeps its version until it is restarted. Should the newest install fail to load, the worker runs the starter's own version and logs `boot_fallback` (its stdio is `/dev/null`). Under `bundle exec` the worker drops Bundler's env first, so it activates the newest gem too. Two consequences: a wrapper pin (`chi _0.17.0_ web`) pins only that process, not the workers it starts; and a source checkout (`bin/chi` in a worktree, `bundle exec`) starts its workers on its own `lib/`, but a session it made that is later woken by an installed chi (`chi web`, `chi send`) runs the installed code. The names an older starter hands a newer worker (the boot line, its env keys, `input/` files, the session JSON fields and the Bridge routes sessions use on each other) are pinned in `spec/worker_contract_spec.rb`.
|
|
23
23
|
|
|
24
|
-
**
|
|
24
|
+
**A worker outlives whoever started it:** a spawned worker leaves its spawner's process tree (it is forked again, in a session of its own, and reparented to init), so closing the terminal of a `chi web`, or a tool tearing down a background `chi send --wait` and its children, no longer takes the worker and its turn with it.
|
|
25
|
+
|
|
26
|
+
**A worker killed mid-turn:** while a turn runs, its worker keeps it on disk (`TurnCheckpoint`): the session file has the turn so far (the prompt from the turn's start, then the finished tool steps and lines merged into it) and `interrupted_turn: {id, started_at, at, iteration}`, written as the turn starts, at the loop's first iteration boundary and then at most every 10 s (`updated_at` moves with it). The turn's end saves the real messages without the mark. A worker that died without ending its turn (SIGKILL, a crash of the process) leaves the mark, and loses what came after its last written boundary: at most the last 10 s of steps, plus the step in flight. Each checkpoint write also saves the turn's metrics so far to `analytics.json` (tokens, speeds, timings, its finished tool calls), as the record a killed turn leaves: canceled, `cancellation_reason: worker_stopped`; the turn's own end writes over it. The next worker to start for the session (a `chi send`, `--resume`, `--attach`, the web), or a `--no-shared` REPL resuming it, settles the turn before anything else (`TurnCheckpoint.settle`, log `interrupted_turn_settled`): a note `the previous turn was cancelled (worker-stopped) after Ns` goes at the tail, the status goes idle and the mark goes; `last_turn` stays the previous turn's (a new one saved before the turn a `chi send --wait` woke the worker for would end that wait at once). The session shows the turn's prompt and steps with that note; the dead turn is not run again, and the model reads on its next turn that it was cut.
|
|
27
|
+
|
|
28
|
+
**Stopping a worker:** `chi sessions stop ID` marks the session stopped (an empty `<id>/stopped` file, not a session.json field, which a worker saving at that moment would write over; a resume removes it), sends its worker TERM and waits (up to 10 s) until the worker has let go of `owner.lock`. A running turn is canceled over the Bridge first (so a command it was running says "stopped by the user"; only a bare signal to the worker makes it "stopped by a signal to chi"); the TERM stops whatever still runs as a Stop with reason `signal` and saves it (a spawned worker traps TERM, HUP and INT: `WorkerSignals`; a turn not ended within 3 s, 0.5 s after a stop or a second signal, is cut and the session saved as it was), and a stopped worker still saves its kept turn, since the marker, not the saved status, says stopped. Any TERM, HUP or INT does the same to a worker outside a stop: it leaves (log `worker stop reason=signal`) and the next send wakes a new one, so a `chi --resume ID` right after spawns a fresh worker. That is also how to restart a worker still running an older chi, which the attached terminal reports when a command or a question dismiss gets a 404, and the web when an answer, a dismiss, a command or a cancel does (`501 not_supported`; `BridgeClient.stale_worker_message`). A command this chi has that the older worker doesn't (`/llm-context`, the web's `llm ctx` chip, against a 0.39.0 worker) says the same, not `not a session command` (`SessionCommands.builtin_name`); a typo keeps its `400 unknown_command`. The web's `POST /api/sessions/:id/stop` waits the same way, for 2 s. A command sent during a turn that waits for its end (`/model X`, `!cmd`; see *Typing during a turn* in [cli.md](cli.md)) and hasn't run when the worker leaves (a stop, a crash) is answered `command_ran {status: "dropped"}`, so no UI keeps showing it waiting.
|
|
25
29
|
|
|
26
30
|
**Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a plain REPL has open (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. The web's route is `DELETE /api/sessions/:id` (200 `{status: "deleted", session_id, stopped}`; 409 `owned_by_tui` or `still_stopping`; 404).
|
|
27
31
|
|
|
@@ -68,9 +72,9 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
|
|
|
68
72
|
**Ordering:**
|
|
69
73
|
|
|
70
74
|
- `Session.list` / `SessionManager.list_sessions` / `GET /api/sessions?sort=&order=&limit=&offset=` default to `updated_at desc` (newest activity first). Also supports `created_at`, `asc`. `X-Total-Count` header when paginated.
|
|
71
|
-
- Web UI (`chi web`): the page's scope is in its URL. Started in a git repo, `chi web` opens `/?dir=<that folder>`: that project's sessions, and new chats start in that folder; the header chip says `<project> · all`, and `all` opens the same place without `?dir` (every session; a new chat there starts in the server's own folder, shown on the start page, and cards name their folder; `← <project>` goes back to the project view it came from, or to the server's own project). One server serves every project: a second `chi web` (from another repo) finds it through `GET /api/info` and prints (with `--open`, opens) its page for its own folder instead of starting another. The 3 latest sessions sit above the chat (`hide ▴` puts them away behind a `▾ N sessions` pill, remembered; in a window under 900 px wide, where the strip scrolls sideways, `▴ hide` sits in the top bar where the pill comes back; a window under 700 px tall hides them by itself, so a question or approval card in the stage keeps room, and the pill shows them until the window is tall again). A parent and its delegates are one card there: its `▸ 2 delegates · 1 live · 1 waiting` chip (the waiting part in the attention colour, the card's border too) opens their rows in a popover under it (a row per delegate at any depth, indented; a click opens that one, Esc or a click outside closes it, and the strip's order holds while it is open). A fork is a card of its own, and so is a delegate whose parent isn't listed (archived, another project), with its `↳ <parent>` chip; the pill counts cards, and every live or waiting session. "All sessions" (or `/`) opens every session at `#/sessions`, with a search over preview, id and status (Esc or Back returns). There a parent's card holds its delegates the same way, the chip opening their rows inside the card (each with an archive button on hover), open by itself while one of them waits on you; the count says `14 (+7 delegates)`, a search that matches a delegate shows its parent's card with the list open and the matching rows marked, and select mode picks cards (archiving a parent takes its delegates). The open session is in the URL (`#/s/<id>`), so a reload or a copied link opens it again; the chi logo top left goes back to the empty start for a new chat. The message box grows with its text; drag its top edge to keep it taller (double-click resets). A file in a tool row (a read, edit or write's title) and its diff lines are refs: hover one and click to open the current file in your editor at that line, on this machine only (`web.editor`; the browser's "always allow" for the page's port and VS Code's "allow opening local files" are asked once; see [Opening files from chi web](configuration.md#opening-files-from-chi-web)). So are an edit or write approval card's paths (at the first line the dry run changes) and its diff lines, before you approve, and the numbered lines of a read's output: `lines 40–60` under it opens the text as read, numbered, when the output is the file as-is (not the head/tail preview of a big file, an error or an image; no numbers after a cut). A `path:line` (or `path:line-line`) in an answer or a step's text is one too once the turn has ended, and after a reload, when it names a file a row or card on the page touched: the path under the session's folder, else the one touched file it ends with (a bare `app.js:12` when only one touched file is named so; two such files make it none); a path without a line counts only when it is a touched file exactly. Code blocks, links, bare URLs and inline code with more than the ref in it are left alone, and a file the session didn't touch is never linked; a link whose text is such a ref alone (github-pr's link to the PR diff) becomes a ref too, and its plain click still goes to the PR. A ref with more than one target shows a small `▾` on hover: it opens a menu of them, in order **PR diff** (a link's), **Open in editor**, **Show in turn** and **Copy path**, and a plain click runs the first (a link's own, else the editor, else show in turn). **Show in turn** scrolls to the tool row that touched the file (looked for in the ref's own step, then its own turn, then the rows before it, then the nearest after it; there, the last one showing the ref's line, else the last one), opens the steps, the stage's steps and the row's diff (or the read showing the line) and flashes the row and the line; an answer's or a step's ref and an approval card's path have it, not a row's own title or lines. It needs no editor, so a viewer without one (a phone on the LAN) gets an answer's refs with **Show in turn** as their click; a row's title and diff lines stay plain text there. On a touch screen a tap opens the menu. A ref with a target is a tab stop: Enter runs its first target, ↓ opens the menu (↑/↓ move, Enter picks, Esc closes back to the ref). Diff and read lines have their click only. The info bar copies `chi --attach <id>` for a terminal. A session whose prompt carried model notes has a `notes: deepseek` chip there (the names without `model_notes_`; the tooltip lists each with its scope and size; `session.prompt_notes` in `GET /api/sessions/:id`, the live worker's, else the session file's; see [Memory](memory.md#model-notes)). Its `llm ctx` chip names the LLM context strategy the next turn runs under (`llm ctx stale,forget · session`, in the accent colour when the session set its own; the tooltip gives each value's source), and its popover sets the session's own strategy, apply rule and budget, or follows the model again, by running `/llm-context` in the worker (the reply shows as a command bubble); `GET /api/sessions/:id`'s `session.llm_context` carries the values (the live worker's, else resolved from the session file), and a `command_ran` that changed them carries the new ones. Its `think` chip does the same for the thinking level (`/thinking`), and on a chat host its `reasoning` chip for the reasoning history (`reasoning all · session`, `/reasoning-history`; `session.reasoning_history`, null on a native host). A `/thinking` or `/reasoning-history` change that restarts the prompt cache asks first: the reply bubble has an **Apply (restarts the cache)** button that sends its `--yes` line (the chips' Set sends that line itself; see [Changes that restart the prompt cache](configuration.md#changes-that-restart-the-prompt-cache)). It shows the context used (`ctx 42%`) and the last generation's decode speed (`87 tok/s`, `~64 tok/s` when estimated; see `/stats` in [cli.md](cli.md#session-commands)); hovering `ctx` there or on a session card lists the session's tokens in (summed over every request, with the cached share), out (with reasoning) and the cost when the provider reports one, for this session only (one estimated from a `hosts.<name>.models` price shows with `~`: `cost: ~$0.54 ($0.42 reported, ~$0.12 estimated)`), and the memory indexes its prompt holds (`memory index: ~3.4k tokens in this session's prompt (system 2.0k, project 1.4k)`; see [Memory](memory.md#the-indexs-size)). The start page's model picker (bottom left of the composer, the chosen name `▾`) chooses the model a new chat starts on; it opens a search list over the conversation (↓ or a click; downward when the start page leaves no room above): an empty search shows the last 5 picks (Recent) and then each host's model ids A–Z under the host, the default host first (an id the host declares under `hosts.<name>.models` first, noted `config`, its tooltip `served by config (hosts.<name>.models)`; a host that failed to list its models keeps those ids, greyed and noted `host down`, still pickable; a remembered or default model stays chosen even then, greyed on the button); typed words must each match the host or the id (a substring, else for 3+ characters the letters in order, so `deepseek4.1 fla` finds `openrouter · deepseek/deepseek-v4.1-flash`), ⏎ picks, Esc/Tab close, a pick puts the focus in the message box: `GET /api/models` lists the hosts' models as chi spells them (`{default, models: [{name, host, id, configured?, unavailable?, sampling?, llm_context?}], warning?}`; `configured: true` marks an id declared under `hosts.<name>.models`, listed first under its host, `unavailable: true` one whose host failed to list its models; `sampling` is the model's configured request parameters as `/model` words them, the row's tooltip in the list; bare for the default host, `host:model` for the others, from the same cached lists as `/models`, a bounded wait, a host that is down noted in `warning`), and `POST /api/sessions` takes `model` (blank means the default). Beside it, an `llm ctx` chip shows the LLM context the picked model starts under (each `GET /api/models` row's `llm_context`, as the info bar's); its form sets one for the new chat only, sent as `POST /api/sessions`'s `llm_context` and never remembered (see [configuration.md](configuration.md#llm-context-a-sessions-own-strategy)). The start page's first message goes as later ones do: `POST /api/sessions` with `idle: true` and `preview` (the message, which names the session until its turn is saved), then `POST /api/sessions/:id/turn`, so a failed first turn puts its prompt back in the composer too; a first line that is one of the new session's commands (`/model …`) goes to `POST /api/sessions/:id/command` instead, as later ones do. The browser remembers the last model picked; a running session's model is in the info bar and changes only with `/model`. In the composer a line is a command when it is `!…` or starts with one of the session's command names (its `commands` list; `/stats`, `/exit` and the other terminal words get the page's own reply); an unknown `/word` (`/usr/bin/env is missing`) goes to the model as a prompt, as in a terminal; a one-word `/word` no command answers (`/modle`) is not sent: the page shows `Unknown command /modle. Did you mean /model? /help lists the commands.` (the "Did you mean" part only when a name is close). A `POST /turn` (or a session's first `prompt`) that is one of the worker's commands runs as that command too (`202 {status, command_id, session_id}`), so `chi send`, `chi -p` and a page whose command list lags all get the command. ↑/↓ in the composer walk the prompt history the TUI's ↑ walks ([Persistent Prompt History](cli.md#persistent-prompt-history)): ↑ with the caret on the first line, ↓ from the last line while browsing, ↓ past the newest brings the draft back; `GET /api/history` returns `{entries: [...]}`, oldest first (the page fetches it on focus and after each send). The server records a sent line in the routes once the worker took it (`POST /turn` accepted, a `!command` through `POST /command` or as a session's first line); `"history": false` in the body keeps it out (an image-only send).
|
|
75
|
+
- Web UI (`chi web`): the page's scope is in its URL. Started in a git repo, `chi web` opens `/?dir=<that folder>`: that project's sessions, and new chats start in that folder; the header chip says `<project> · all`, and `all` opens the same place without `?dir` (every session; a new chat there starts in the server's own folder, shown on the start page, and cards name their folder; `← <project>` goes back to the project view it came from, or to the server's own project). One server serves every project: a second `chi web` (from another repo) finds it through `GET /api/info` and prints (with `--open`, opens) its page for its own folder instead of starting another. The 3 latest sessions sit above the chat (`hide ▴` puts them away behind a `▾ N sessions` pill, remembered; in a window under 900 px wide, where the strip scrolls sideways, `▴ hide` sits in the top bar where the pill comes back; a window under 700 px tall hides them by itself, so a question or approval card in the stage keeps room, and the pill shows them until the window is tall again). A parent and its delegates are one card there: its `▸ 2 delegates · 1 live · 1 waiting` chip (the waiting part in the attention colour, the card's border too) opens their rows in a popover under it (a row per delegate at any depth, indented; a click opens that one, Esc or a click outside closes it, and the strip's order holds while it is open). A fork is a card of its own, and so is a delegate whose parent isn't listed (archived, another project), with its `↳ <parent>` chip; the pill counts cards, and every live or waiting session. "All sessions" (or `/`) opens every session at `#/sessions`, with a search over preview, id and status (Esc or Back returns). There a parent's card holds its delegates the same way, the chip opening their rows inside the card (each with an archive button on hover), open by itself while one of them waits on you; the count says `14 (+7 delegates)`, a search that matches a delegate shows its parent's card with the list open and the matching rows marked, and select mode picks cards (archiving a parent takes its delegates). The open session is in the URL (`#/s/<id>`), so a reload or a copied link opens it again; the chi logo top left goes back to the empty start for a new chat. The message box grows with its text; drag its top edge to keep it taller (double-click resets). A file in a tool row (a read, edit or write's title) and its diff lines are refs: hover one and click to open the current file in your editor at that line, on this machine only (`web.editor`; the browser's "always allow" for the page's port and VS Code's "allow opening local files" are asked once; see [Opening files from chi web](configuration.md#opening-files-from-chi-web)). So are an edit or write approval card's paths (at the first line the dry run changes) and its diff lines, before you approve, and the numbered lines of a read's output: `lines 40–60` under it opens the text as read, numbered, when the output is the file as-is (not the head/tail preview of a big file, an error or an image; no numbers after a cut). A `path:line` (or `path:line-line`) in an answer or a step's text is one too once the turn has ended, and after a reload, when it names a file a row or card on the page touched: the path under the session's folder, else the one touched file it ends with (a bare `app.js:12` when only one touched file is named so; two such files make it none); a path without a line counts only when it is a touched file exactly. Code blocks, links, bare URLs and inline code with more than the ref in it are left alone, and a file the session didn't touch is never linked; a link whose text is such a ref alone (github-pr's link to the PR diff) becomes a ref too, and its plain click still goes to the PR. A plugin's refs on an answer (an `after_turn` hook's, see [Refs on the answer](hooks.md#refs-on-the-answer-display-only)) are paired with its links and text whatever the rows touched: they can link a file the session didn't touch, or an issue or a commit, and add their own actions to the ref's menu. A plugin tool's row carries the refs its `refs:` gives (see [Refs on a tool's row](plugins.md#refs-on-a-tools-row)): its title opens the first, and its `▾` menu adds the others as `<ref> · <action>` (the URL on hover); their URL actions work on a phone too. A ref with more than one target shows a small `▾` on hover: it opens a menu of them, in order **PR diff** (a link's), **Open in editor**, **Show in turn** and **Copy path**, and a plain click runs the first (a link's own, else the editor, else show in turn). **Show in turn** scrolls to the tool row that touched the file (looked for in the ref's own step, then its own turn, then the rows before it, then the nearest after it; there, the last one showing the ref's line, else the last one), opens the steps, the stage's steps and the row's diff (or the read showing the line) and flashes the row and the line; an answer's or a step's ref and an approval card's path have it, not a row's own title or lines. It needs no editor, so a viewer without one (a phone on the LAN) gets an answer's refs with **Show in turn** as their click; a row's title and diff lines stay plain text there. On a touch screen a tap opens the menu. A ref with a target is a tab stop: Enter runs its first target, ↓ opens the menu (↑/↓ move, Enter picks, Esc closes back to the ref). Diff and read lines have their click only. The info bar copies `chi --attach <id>` for a terminal. A session whose prompt carried model notes has a `notes: deepseek` chip there (the names without `model_notes_`; the tooltip lists each with its scope and size; `session.prompt_notes` in `GET /api/sessions/:id`, the live worker's, else the session file's; see [Memory](memory.md#model-notes)). Its `llm ctx` chip names the LLM context strategy the next turn runs under (`llm ctx stale,forget · session`, in the accent colour when the session set its own; the tooltip gives each value's source), and its popover sets the session's own strategy, apply rule and budget, or follows the model again, by running `/llm-context` in the worker (the reply shows as a command bubble); `GET /api/sessions/:id`'s `session.llm_context` carries the values (the live worker's, else resolved from the session file), and a `command_ran` that changed them carries the new ones. Its `think` chip does the same for the thinking level (`/thinking`), and on a chat host its `reasoning` chip for the reasoning history (`reasoning all · session`, `/reasoning-history`; `session.reasoning_history`, null on a native host). A `/thinking` or `/reasoning-history` change that restarts the prompt cache asks first: the reply bubble has an **Apply (restarts the cache)** button that sends its `--yes` line (the chips' Set sends that line itself; see [Changes that restart the prompt cache](configuration.md#changes-that-restart-the-prompt-cache)). It shows the context used (`ctx 42%`) and the last generation's decode speed (`87 tok/s`, `~64 tok/s` when estimated; see `/stats` in [cli.md](cli.md#session-commands)); hovering `ctx` there or on a session card lists the session's tokens in (summed over every request, with the cached share), out (with reasoning) and the cost when the provider reports one, for this session only (one estimated from a `hosts.<name>.models` price shows with `~`: `cost: ~$0.54 ($0.42 reported, ~$0.12 estimated)`), and the memory indexes its prompt holds (`memory index: ~3.4k tokens in this session's prompt (system 2.0k, project 1.4k)`; see [Memory](memory.md#the-indexs-size)). The start page's model picker (bottom left of the composer, the chosen name `▾`) chooses the model a new chat starts on; it opens a search list over the conversation (↓ or a click; downward when the start page leaves no room above): an empty search shows the last 5 picks (Recent) and then each host's model ids A–Z under the host, the default host first (an id the host declares under `hosts.<name>.models` first, noted `config`, its tooltip `served by config (hosts.<name>.models)`; a host that failed to list its models keeps those ids, greyed and noted `host down`, still pickable; a remembered or default model stays chosen even then, greyed on the button); typed words must each match the host or the id (a substring, else for 3+ characters the letters in order, so `deepseek4.1 fla` finds `openrouter · deepseek/deepseek-v4.1-flash`), ⏎ picks, Esc/Tab close, a pick puts the focus in the message box: `GET /api/models` lists the hosts' models as chi spells them (`{default, models: [{name, host, id, configured?, unavailable?, sampling?, llm_context?}], warning?}`; `configured: true` marks an id declared under `hosts.<name>.models`, listed first under its host, `unavailable: true` one whose host failed to list its models; `sampling` is the model's configured request parameters as `/model` words them, the row's tooltip in the list; bare for the default host, `host:model` for the others, from the same cached lists as `/models`, a bounded wait, a host that is down noted in `warning`), and `POST /api/sessions` takes `model` (blank means the default). Beside it, an `llm ctx` chip shows the LLM context the picked model starts under (each `GET /api/models` row's `llm_context`, as the info bar's); its form sets one for the new chat only, sent as `POST /api/sessions`'s `llm_context` and never remembered (see [configuration.md](configuration.md#llm-context-a-sessions-own-strategy)). The start page's first message goes as later ones do: `POST /api/sessions` with `idle: true` and `preview` (the message, which names the session until its turn is saved), then `POST /api/sessions/:id/turn`, so a failed first turn puts its prompt back in the composer too; a first line that is one of the new session's commands (`/model …`) goes to `POST /api/sessions/:id/command` instead, as later ones do. The browser remembers the last model picked; a running session's model is in the info bar and changes only with `/model`. In the composer a line is a command when it is `!…` or starts with one of the session's command names (its `commands` list; `/stats`, `/exit` and the other terminal words get the page's own reply); an unknown `/word` (`/usr/bin/env is missing`) goes to the model as a prompt, as in a terminal; a one-word `/word` no command answers (`/modle`) is not sent: the page shows `Unknown command /modle. Did you mean /model? /help lists the commands.` (the "Did you mean" part only when a name is close). A `POST /turn` (or a session's first `prompt`) that is one of the worker's commands runs as that command too (`202 {status, command_id, session_id}`), so `chi send`, `chi -p` and a page whose command list lags all get the command. ↑/↓ in the composer walk the prompt history the TUI's ↑ walks ([Persistent Prompt History](cli.md#persistent-prompt-history)): ↑ with the caret on the first line, ↓ from the last line while browsing, ↓ past the newest brings the draft back; `GET /api/history` returns `{entries: [...]}`, oldest first (the page fetches it on focus and after each send). The server records a sent line in the routes once the worker took it (`POST /turn` accepted, a `!command` through `POST /command` or as a session's first line); `"history": false` in the body keeps it out (an image-only send).
|
|
72
76
|
- Web notifications: when a session needs you while the tab is hidden or behind another window (a question or a guardrail approval, a plugin card with buttons during a turn such as check-in's, a failed turn, a turn done after 10 s or more; a delegated session only for its questions, a canceled turn never), the page title counts it, `(N) Chi`, until you come back to the tab. The bell at the right of the top bar also turns on OS notifications ("needs an answer", "needs approval", "needs you", "turn failed", "done in 42 s", under the session's first message; a click opens the session): its first click asks the browser for the permission, and the choice is kept per browser. Any session of the page's scope counts, not only the open one. What was already so when the page loaded never counts, and several chi tabs show one notification per event. A chi tab in front tells the others (a `BroadcastChannel`), so while you look at one, the ones behind neither notify nor count what it shows; coming back to a tab clears those events in the other tabs' titles too. The hub's `session` frames carry what this needs: `pending_question` (`{id, kind}`, kind `question` or `approval`), `pending_card` (`{id, bundle}`: the running turn's card with actions, from `pending_card.json` that the worker keeps in the session's folder while one is open; a card without actions, such as loop-guard's, never counts) and `last_turn` (`{outcome, ended_at, seconds, origin}`, saved in the session's JSON as the engine ends each turn).
|
|
73
|
-
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `day N` chip and rows, the info bar's ← → links, a refused continue), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `format.js` (pure formatters such as `previewOf`), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `info_bar.js` (the session bar's info line as a lit-html template over a plain model: id, status, model, chain links, chips, ctx, speed, clock, worker badge), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu). Unit-tested via `npm test` (`node --test spec/web/public/*.test.js`).
|
|
77
|
+
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `day N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `format.js` (pure formatters such as `previewOf`), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `info_bar.js` (the session bar's info line as a lit-html template over a plain model: id, status, model, chain links, chips, ctx, speed, clock, worker badge), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`). Unit-tested via `npm test` (`node --test spec/web/public/*.test.js`).
|
|
74
78
|
- Selecting a session in the web UI is read-only: `GET /api/sessions/:id` never spawns a worker (it reads a live worker's snapshot when one runs, else the session file). A prompt (`POST /turn`) or a command (`POST /command`) wakes the worker, and `/stream` briefly waits for a freshly-spawned bridge before answering. A caught-up SSE reconnect holds the stream open; `reset` markers are only sent for reconnects behind the ring window, or with a cursor from another worker (event ids are `<event_seq>-<epoch>`, one epoch per worker).
|
|
75
79
|
|
|
76
80
|
**Test-session hygiene:**
|
data/docs/testing.md
CHANGED
|
@@ -16,10 +16,13 @@ No spec reads your own setup. The suite points `XDG_CONFIG_HOME` and `XDG_STATE_
|
|
|
16
16
|
clears your `SAMAGOTCHI_*` environment, and keeps every spec off the network (WebMock).
|
|
17
17
|
|
|
18
18
|
The web specs run in plain node. One that loads lit-html (`turn_view.js`, `thinking_chip.js`, `llm_context_chip.js`,
|
|
19
|
-
`info_bar.js`, `lists_view.js`, `vendor/lit-html.js`) needs a DOM: `import "./dom_shim.js";` as its first import (happy-dom, a
|
|
19
|
+
`info_bar.js`, `lists_view.js`, `context_chips.js`, `families_view.js`, `chains.js`, `vendor/lit-html.js`) needs a DOM: `import "./dom_shim.js";` as its first import (happy-dom, a
|
|
20
20
|
devDependency only, never shipped; about 0.3 s per spec file that loads it). The shim's `htmlOf(nodes)` and `canon(html)` compare markup
|
|
21
21
|
without lit's marker comments. happy-dom 20 picks the wrong option of a `<select>` whose options lit inserted with
|
|
22
22
|
`?selected`: read the option marked `selected` (`option[selected]`), not `select.value`; the browser follows the mark.
|
|
23
|
+
A select bound with `.value` instead reads right in both, but lit sets it before the options exist on a first render:
|
|
24
|
+
`llm_context_chip.js`'s `renderForm` draws twice then. Assert a kept node with `assert.ok(a === b)`: a failing
|
|
25
|
+
`assert.equal` on two DOM nodes inspects the whole DOM (huge output, can stall the run).
|
|
23
26
|
|
|
24
27
|
## While you work: affected specs
|
|
25
28
|
|
|
@@ -23,9 +23,10 @@ module Samagotchi
|
|
|
23
23
|
|
|
24
24
|
# A message as a model-facing reader may see it: without `display`.
|
|
25
25
|
# The same object when it has none.
|
|
26
|
-
# An empty-answer note's marker (TurnNote::EMPTY_ANSWER)
|
|
27
|
-
#
|
|
28
|
-
|
|
26
|
+
# An empty-answer note's marker (TurnNote::EMPTY_ANSWER) and the
|
|
27
|
+
# answer's refs (AnswerRefs::KEY, display_refs) are display only too:
|
|
28
|
+
# they go the same way.
|
|
29
|
+
DISPLAY_ONLY = [KEY.to_s, "empty_answer", "display_refs"].freeze
|
|
29
30
|
|
|
30
31
|
def self.strip(message)
|
|
31
32
|
return message unless message.is_a?(Hash) && DISPLAY_ONLY.any? { |key| message.key?(key.to_sym) || message.key?(key) }
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require_relative "log"
|
|
5
|
+
require_relative "ref"
|
|
6
|
+
|
|
7
|
+
module Samagotchi
|
|
8
|
+
# One ref on the answer: the text it stands for (+match+, what the page
|
|
9
|
+
# pairs it with) and the Ref itself. +to_h+ is the stored and sent shape,
|
|
10
|
+
# {match:, kind:, target:, label:, actions:}.
|
|
11
|
+
AnswerRef = Data.define(:match, :ref) do
|
|
12
|
+
# @raise [ArgumentError] an empty match, one over MAX_MATCH, or a ref
|
|
13
|
+
# that isn't a Ref
|
|
14
|
+
def initialize(match:, ref:)
|
|
15
|
+
match = match.to_s.strip
|
|
16
|
+
raise ArgumentError, "a ref needs a match (the text it stands for)" if match.empty?
|
|
17
|
+
raise ArgumentError, "a ref's match is at most #{AnswerRef::MAX_MATCH} characters" if match.length > AnswerRef::MAX_MATCH
|
|
18
|
+
raise ArgumentError, "not a Ref" unless ref.is_a?(Ref)
|
|
19
|
+
|
|
20
|
+
super
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def to_h = { match: match, **ref.to_h }
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
class AnswerRef
|
|
27
|
+
MAX_MATCH = 500
|
|
28
|
+
|
|
29
|
+
# A hook's {match:, kind:, target:, label:, actions:}, or a stored
|
|
30
|
+
# entry (String or Symbol keys, nested ones too). A file ref's relative
|
|
31
|
+
# path is resolved against +cwd+, so the stored path is absolute; with
|
|
32
|
+
# no +cwd+ it is refused. An absolute path stays as given.
|
|
33
|
+
# @raise [ArgumentError] anything invalid
|
|
34
|
+
def self.from(value, cwd: nil)
|
|
35
|
+
raise ArgumentError, "a ref is a Hash {match:, kind:, target:, label:, actions:}" unless value.is_a?(Hash)
|
|
36
|
+
|
|
37
|
+
value = value.transform_keys(&:to_sym)
|
|
38
|
+
ref = Ref.new(kind: value[:kind], target: value[:target], label: value[:label], actions: value[:actions] || [])
|
|
39
|
+
new(match: value[:match], ref: absolute(ref, cwd))
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def self.absolute(ref, cwd)
|
|
43
|
+
return ref unless ref.kind == Ref::FILE
|
|
44
|
+
|
|
45
|
+
path = ref.target[:path]
|
|
46
|
+
return ref if File.absolute_path?(path)
|
|
47
|
+
raise ArgumentError, "relative path, no session folder" if cwd.to_s.empty?
|
|
48
|
+
|
|
49
|
+
# absolute_path, not expand_path: a leading ~ is a name, never a home.
|
|
50
|
+
Ref.new(kind: ref.kind, target: ref.target.merge(path: File.absolute_path(path, cwd.to_s)), label: ref.label,
|
|
51
|
+
actions: ref.actions)
|
|
52
|
+
end
|
|
53
|
+
private_class_method :absolute
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# The refs after_turn hooks attach to a turn's answer (event[:refs]),
|
|
57
|
+
# kept as `display_refs` on the answer's model message next to its
|
|
58
|
+
# `display` (AnswerDisplay). Display only, like `display`: the model
|
|
59
|
+
# never sees them (AnswerDisplay::DISPLAY_ONLY), and a UI pairs each with
|
|
60
|
+
# its +match+ in the shown answer (or drops it).
|
|
61
|
+
#
|
|
62
|
+
# The target is AnswerDisplay's: the stored conversation's last message
|
|
63
|
+
# when it is the model's. The list starts from the refs it already has
|
|
64
|
+
# (re-validated), so a later hook run never loses them.
|
|
65
|
+
class AnswerRefs
|
|
66
|
+
KEY = :display_refs
|
|
67
|
+
MAX_REFS = 200
|
|
68
|
+
# The list's JSON; a ref that would cross it is refused.
|
|
69
|
+
MAX_BYTES = 256 * 1024
|
|
70
|
+
|
|
71
|
+
# Stored refs (+raw+, as read from session.json or a snapshot), each
|
|
72
|
+
# rebuilt and checked again, the caps applied; what isn't valid any
|
|
73
|
+
# more is dropped. Never raises: a reload must show the conversation.
|
|
74
|
+
# A relative file path is dropped (there is no folder to resolve it).
|
|
75
|
+
# @return [Array<Hash>] the refs to send ({match:, kind:, target:, …})
|
|
76
|
+
def self.for_display(raw)
|
|
77
|
+
return [] if raw.nil?
|
|
78
|
+
|
|
79
|
+
kept = new([{ role: "model", KEY => raw }], cwd: nil).to_a
|
|
80
|
+
dropped = raw.is_a?(Array) ? raw.length - kept.length : 1
|
|
81
|
+
Log.debug(:web, "display_refs_dropped", count: dropped) if dropped.positive?
|
|
82
|
+
kept
|
|
83
|
+
rescue StandardError
|
|
84
|
+
[]
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# @return [Hash, nil] the message event[:refs] adds to
|
|
88
|
+
attr_reader :target
|
|
89
|
+
|
|
90
|
+
# @param messages [Array<Hash>] the conversation the turn stored
|
|
91
|
+
# @param cwd [String, nil] the session's folder, for relative file paths
|
|
92
|
+
def initialize(messages, cwd:)
|
|
93
|
+
last = Array(messages).last
|
|
94
|
+
@target = last if last.is_a?(Hash) && (last[:role] || last["role"]).to_s == "model"
|
|
95
|
+
@cwd = cwd
|
|
96
|
+
@refs = []
|
|
97
|
+
@seen = {}
|
|
98
|
+
@bytes = 2 # the list's []
|
|
99
|
+
@added = false
|
|
100
|
+
@closed = false
|
|
101
|
+
@rejections = Hash.new(0)
|
|
102
|
+
seed(@target) if @target
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# True when a hook added a ref the answer didn't have.
|
|
106
|
+
def added? = @added
|
|
107
|
+
|
|
108
|
+
def count = @refs.length
|
|
109
|
+
|
|
110
|
+
# @return [Array<Hash>] the refs as stored ({match:, kind:, target:, …})
|
|
111
|
+
def to_a = @refs.dup
|
|
112
|
+
|
|
113
|
+
# The list is stored (Engine#store_answer_display): a later call (a
|
|
114
|
+
# plugin that kept event[:refs]) would be lost, so it returns nil.
|
|
115
|
+
def close! = @closed = true
|
|
116
|
+
|
|
117
|
+
def closed? = @closed
|
|
118
|
+
|
|
119
|
+
# event[:refs]: call it with the ref's keywords,
|
|
120
|
+
# +call(match:, kind:, target:, label: nil, actions: [])+.
|
|
121
|
+
# @param event [Hash] the after_turn event (for its :hook label)
|
|
122
|
+
# The hook's label is read at call time: one adder serves every hook of
|
|
123
|
+
# the fire, and the registry sets event[:hook] before each.
|
|
124
|
+
# @return [Proc] true when the ref is kept (or was already there), false
|
|
125
|
+
# when it is refused (logged, named by event[:hook]), nil when the
|
|
126
|
+
# turn has no answer or the list was already stored (#close!)
|
|
127
|
+
def adder(event)
|
|
128
|
+
lambda do |*args, **ref|
|
|
129
|
+
next nil unless @target
|
|
130
|
+
next late(event[:hook]) if @closed
|
|
131
|
+
next reject(event[:hook], "takes keywords (match:, kind:, target:, label:, actions:)") unless args.empty?
|
|
132
|
+
|
|
133
|
+
add(ref, event[:hook])
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
private
|
|
138
|
+
|
|
139
|
+
KEYS = %i[match kind target label actions].freeze
|
|
140
|
+
REASON_VALUES = /\(.*?\)|\[.*?\]|".*?"|\d+/
|
|
141
|
+
private_constant :KEYS, :REASON_VALUES
|
|
142
|
+
|
|
143
|
+
def seed(target)
|
|
144
|
+
raw = target[KEY] || target[KEY.to_s]
|
|
145
|
+
raw.each { |entry| keep(entry) } if raw.is_a?(Array)
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def add(value, hook)
|
|
149
|
+
unknown = value.keys - KEYS
|
|
150
|
+
return reject(hook, "has unknown keys #{unknown.map(&:to_s).inspect}") unless unknown.empty?
|
|
151
|
+
|
|
152
|
+
entry = AnswerRef.from(value, cwd: @cwd).to_h
|
|
153
|
+
return true if @seen.key?(entry)
|
|
154
|
+
return over_cap(hook, "#{MAX_REFS} refs") if @refs.length >= MAX_REFS
|
|
155
|
+
|
|
156
|
+
size = JSON.generate(entry).bytesize + (@refs.empty? ? 0 : 1)
|
|
157
|
+
return over_cap(hook, "#{MAX_BYTES / 1024} KiB") if @bytes + size > MAX_BYTES
|
|
158
|
+
|
|
159
|
+
push(entry, size)
|
|
160
|
+
@added = true
|
|
161
|
+
rescue StandardError => e
|
|
162
|
+
reject(hook, e.message)
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# A stored entry back in the list, checked again (a relative path is
|
|
166
|
+
# dropped: it was stored absolute). Duplicates and what is over the
|
|
167
|
+
# caps go quietly.
|
|
168
|
+
# @return [Boolean] kept
|
|
169
|
+
def keep(raw)
|
|
170
|
+
entry = AnswerRef.from(raw, cwd: nil).to_h
|
|
171
|
+
return false if @seen.key?(entry) || @refs.length >= MAX_REFS
|
|
172
|
+
|
|
173
|
+
size = JSON.generate(entry).bytesize + (@refs.empty? ? 0 : 1)
|
|
174
|
+
return false if @bytes + size > MAX_BYTES
|
|
175
|
+
|
|
176
|
+
push(entry, size)
|
|
177
|
+
true
|
|
178
|
+
rescue StandardError
|
|
179
|
+
false
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def push(entry, size)
|
|
183
|
+
@refs << entry
|
|
184
|
+
@seen[entry] = true
|
|
185
|
+
@bytes += size
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def over_cap(hook, cap) = reject(hook, "over the cap (#{cap})")
|
|
189
|
+
|
|
190
|
+
def late(hook)
|
|
191
|
+
Log.debug(:hooks, "refs_late", hook: hook.to_s)
|
|
192
|
+
nil
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# Each reason is said once per hook per answer (a warn and its echo);
|
|
196
|
+
# the same again goes to debug with its count, so a hook looping over
|
|
197
|
+
# bad refs can't flood the terminal. The reason's values (a kind, a
|
|
198
|
+
# key list, a cap) don't make it a new one.
|
|
199
|
+
def reject(hook, why)
|
|
200
|
+
count = @rejections[[hook.to_s, why.gsub(REASON_VALUES, "")]] += 1
|
|
201
|
+
if count == 1
|
|
202
|
+
Log.warn(:hooks, "refs_rejected", echo: "[samagotchi:hooks] #{hook}: ref #{why}; dropped",
|
|
203
|
+
hook: hook.to_s, reason: why)
|
|
204
|
+
else
|
|
205
|
+
Log.debug(:hooks, "refs_rejected", hook: hook.to_s, reason: why, count: count)
|
|
206
|
+
end
|
|
207
|
+
false
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
end
|
|
@@ -45,7 +45,11 @@ module Samagotchi
|
|
|
45
45
|
# its own), and a question still open when the worker went waits for no
|
|
46
46
|
# one: neither is saved or seeded. Same caps as in memory. An entry from
|
|
47
47
|
# an earlier worker lists with +earlier+: true (an attached TUI's resync
|
|
48
|
-
# onto a new worker doesn't print those again).
|
|
48
|
+
# onto a new worker doesn't print those again). An earlier card shown
|
|
49
|
+
# during a turn (+in_turn+) comes back without its actions: they belong
|
|
50
|
+
# to a turn no worker runs any more (check-in's Nudge would steer the
|
|
51
|
+
# new worker's turn). A card shown between turns (github-pr's offer,
|
|
52
|
+
# btw, coordinator) keeps its buttons.
|
|
49
53
|
class CardStore
|
|
50
54
|
CAPACITY = 20
|
|
51
55
|
NOTICE_TYPES = %i[hook_notice guardrail_warning empty_answer_retry steer_cut].freeze
|
|
@@ -137,6 +141,7 @@ module Samagotchi
|
|
|
137
141
|
next unless entry.is_a?(Hash) && entry[:type].is_a?(String) && entry[:turns].is_a?(Integer)
|
|
138
142
|
|
|
139
143
|
entry = entry.merge(type: entry[:type].to_sym, earlier: true)
|
|
144
|
+
entry = entry.merge(actions: []) if entry[:type] == :card && entry[:in_turn] && entry.key?(:actions)
|
|
140
145
|
entry unless entry[:type] == :guardrail_warning || open_question?(entry)
|
|
141
146
|
end
|
|
142
147
|
settle_during(after_turn: false)
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: check-in
|
|
3
|
-
version: 0.2.
|
|
3
|
+
version: 0.2.4
|
|
4
4
|
scope: system
|
|
5
5
|
description: "Checks on a long turn: after N tool calls with no answer, a card asks the user (Nudge / Keep going / Stop), or the model is nudged to say what it has found"
|
|
6
6
|
trust_level: reviewed
|
|
7
7
|
plugin:
|
|
8
8
|
file: plugin.rb
|
|
9
|
-
sha256: sha256:
|
|
9
|
+
sha256: sha256:42fe075c664d256ecb8623b76a25d5c389e42c0534a41c56fe17b073d521e095
|
|
10
10
|
requires_chi: ">= 0.3.0"
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
# final answer is dropped: the card's Nudge then says so at the turn's end
|
|
12
12
|
# (after_turn's messages have no steer with its text).
|
|
13
13
|
#
|
|
14
|
+
# One nudge per check-in: a second Nudge (a repeat click, a stale card's
|
|
15
|
+
# button, a typed /checkin nudge) for the same check-in only says it was
|
|
16
|
+
# already nudged; before the turn's first check-in, one nudge in all.
|
|
17
|
+
#
|
|
14
18
|
# The count is per turn: before_turn resets it (and closes a card left open
|
|
15
19
|
# by a turn that failed or was interrupted, where after_turn doesn't fire);
|
|
16
20
|
# steering merged mid-turn does not. The /checkin commands are anytime ones
|
|
@@ -76,6 +80,8 @@ class Plugin
|
|
|
76
80
|
@card_id = nil # this turn's card, once shown
|
|
77
81
|
@card_open = false
|
|
78
82
|
@nudge = nil # the card's Nudge this turn: { text:, count: }
|
|
83
|
+
@checked_in = nil # the count at this turn's latest check-in
|
|
84
|
+
@nudged_for = nil # the check-in (its count, :none before one) nudged
|
|
79
85
|
end
|
|
80
86
|
|
|
81
87
|
def before_turn(ctx)
|
|
@@ -97,6 +103,7 @@ class Plugin
|
|
|
97
103
|
next nil unless @enabled && @count >= @next_at
|
|
98
104
|
|
|
99
105
|
@next_at = @count + @every
|
|
106
|
+
@checked_in = @count
|
|
100
107
|
[@count, @mode]
|
|
101
108
|
end
|
|
102
109
|
check_in(ctx, *due) if due
|
|
@@ -107,7 +114,10 @@ class Plugin
|
|
|
107
114
|
when "nudge"
|
|
108
115
|
text = message(count)
|
|
109
116
|
if ctx.steer(text)
|
|
110
|
-
@mutex.synchronize
|
|
117
|
+
@mutex.synchronize do
|
|
118
|
+
@nudge = { text: text, count: count }
|
|
119
|
+
@nudged_for = count
|
|
120
|
+
end
|
|
111
121
|
ctx.notify("nudged the model after #{count} tool calls")
|
|
112
122
|
end
|
|
113
123
|
when "notify"
|
|
@@ -232,10 +242,24 @@ class Plugin
|
|
|
232
242
|
"check-in after #{n} tool calls, then every #{n}, for this session"
|
|
233
243
|
end
|
|
234
244
|
|
|
245
|
+
# At most one nudge per check-in; the slot is taken before the steer (two
|
|
246
|
+
# clicks race on the anytime command's threads) and given back when no
|
|
247
|
+
# turn took it.
|
|
235
248
|
def nudge(ctx)
|
|
236
|
-
count =
|
|
249
|
+
count, key, earlier = @mutex.synchronize do
|
|
250
|
+
key = @checked_in || :none
|
|
251
|
+
next [nil, nil, @nudge&.dig(:count) || @count] if @nudged_for == key
|
|
252
|
+
|
|
253
|
+
@nudged_for = key
|
|
254
|
+
[@count, key, nil]
|
|
255
|
+
end
|
|
256
|
+
return "check-in: already nudged at #{earlier} tool calls" if earlier
|
|
257
|
+
|
|
237
258
|
text = message(count)
|
|
238
|
-
|
|
259
|
+
unless ctx.steer(text)
|
|
260
|
+
@mutex.synchronize { @nudged_for = nil if @nudged_for == key }
|
|
261
|
+
return "check-in: no turn running"
|
|
262
|
+
end
|
|
239
263
|
|
|
240
264
|
@mutex.synchronize { @nudge = { text: text, count: count } }
|
|
241
265
|
close_card(ctx, "Nudged the model at #{count} tool calls.")
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: github-pr
|
|
3
|
-
version: 0.
|
|
3
|
+
version: 0.5.0
|
|
4
4
|
scope: system
|
|
5
5
|
description: Attaches the branch's open GitHub pull request to a session as context (and any PR URL with chi context add or the web's "+ URL"); the agent gets a note when reviews, comments, checks or its state change; in the web, a path:line in an answer links to that line of the PR; the auto_attach setting can offer the PR with a card first, or attach nothing
|
|
6
6
|
trust_level: reviewed
|
|
7
|
-
requires_chi: ">= 0.
|
|
7
|
+
requires_chi: ">= 0.61.0"
|
|
8
8
|
needs:
|
|
9
9
|
- command: gh
|
|
10
10
|
why: reads the pull request
|
|
11
11
|
hint: brew install gh, then gh auth login
|
|
12
12
|
plugin:
|
|
13
13
|
file: plugin.rb
|
|
14
|
-
sha256: sha256:
|
|
14
|
+
sha256: sha256:b9e3d7a837ecaa2b0e53f3d62d2ccedd532f4d1b5d6faefd5adc9570cb3c4efe
|
|
15
15
|
scripts:
|
|
16
16
|
pr_context.rb: sha256:a883d2780e89c68c0d7b6d5e0fcb22c273f17bb167e79064e0e99db6bd2ee6f0
|
|
17
17
|
context_providers:
|