samagotchi 0.60.0 → 0.61.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 +41 -1
- data/docs/architecture.md +7 -4
- data/docs/hooks.md +72 -1
- data/docs/internals/engine.md +34 -5
- data/docs/internals/prompt-caching.md +3 -1
- data/docs/plugins.md +7 -3
- data/docs/sessions.md +7 -3
- 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/system/manifest.yml +1 -1
- data/lib/samagotchi/engine.rb +38 -9
- data/lib/samagotchi/hooks/registry.rb +3 -1
- data/lib/samagotchi/interrupted_turn.rb +39 -0
- data/lib/samagotchi/kernel_loop.rb +6 -4
- data/lib/samagotchi/llm/chat_loop.rb +5 -2
- data/lib/samagotchi/log_subscriber.rb +6 -3
- data/lib/samagotchi/ref.rb +25 -8
- data/lib/samagotchi/reply_wait.rb +6 -2
- data/lib/samagotchi/session.rb +40 -4
- data/lib/samagotchi/session_manager.rb +64 -6
- data/lib/samagotchi/terminal_ui.rb +4 -0
- data/lib/samagotchi/turn_checkpoint.rb +128 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +5 -0
- data/lib/samagotchi/web/public/answer_refs.js +217 -0
- data/lib/samagotchi/web/public/app.js +15 -18
- data/lib/samagotchi/web/public/index.html +5 -3
- data/lib/samagotchi/web/public/ref_menu.js +9 -1
- data/lib/samagotchi/web/public/ref_scan.js +5 -3
- data/lib/samagotchi/web/public/refs.js +28 -6
- data/lib/samagotchi/web/public/stream_handlers.js +5 -3
- data/lib/samagotchi/web/public/turn_view.js +17 -7
- data/lib/samagotchi/worker.rb +168 -21
- data/lib/samagotchi/worker_signals.rb +81 -0
- metadata +6 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: a3f828171b95ef34cef1b89706f21a34822ea73dae63e55b2219767961241f7c
|
|
4
|
+
data.tar.gz: b12760887f0613c4e087f824f653e8ccc20e0602de55ef69fd8aed69a897a33c
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: e68486688dfe56739e1d05a68549d050f3cb73c369536c5fa097d832baabcfb42ba41917580ad9d0a4707ab3933550247177e92b0184dee2493b467be5773bad
|
|
7
|
+
data.tar.gz: 630eca4f31585d00938ad89b77275d25969384301b43c71415e20fac95be9fb22dfa60695f59afd1fe612e4cad8de94ead8ab949464c6ab7f21eb18fb8667357
|
data/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,45 @@ and commands may change between minor versions. How releases are made:
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [0.61.0] - 2026-10-12
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- Hooks and plugins can attach refs to the answer: `event[:refs].call(match:, kind:, target:, label:, actions:)` on
|
|
16
|
+
`:after_turn`, stored as `display_refs` on the answer (display only: the model never sees them). The web pairs them
|
|
17
|
+
with the answer's links and text: their actions join the ref's menu, live and after a reload. Caps: 200 refs and
|
|
18
|
+
256 KiB per answer; a refused ref is logged as `refs_rejected`. See
|
|
19
|
+
[docs/hooks.md](docs/hooks.md#refs-on-the-answer-display-only).
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- A ref's values are capped (`Ref`, `RefAction`): a label at most 200 characters, at most 8 actions, a target id
|
|
24
|
+
200 and a path 4,096 characters; an action's id 64 and label 100. An action URL with userinfo
|
|
25
|
+
(`https://user:pass@host/`) is refused, and the web page refuses one too.
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- A worker that gets TERM, HUP or INT (`chi sessions stop`, a closed terminal, a process-tree teardown) stops its
|
|
30
|
+
running turn as a Stop with reason `signal` and saves it, then exits; before, the turn and its prompt were lost.
|
|
31
|
+
A stopped session's worker now saves the turn it kept too.
|
|
32
|
+
- A worker killed mid-turn (SIGKILL, a crash) no longer loses the whole turn: the worker writes the turn so far to
|
|
33
|
+
the session file with an `interrupted_turn` mark (the prompt as the turn starts, then its iteration boundaries,
|
|
34
|
+
at most every 10 s), so it loses only what came after its last written boundary. The next worker (or a
|
|
35
|
+
`--no-shared` REPL resuming the session) ends that turn as canceled with a note the model reads
|
|
36
|
+
(`cancelled (worker-stopped)`), so the session is idle again.
|
|
37
|
+
- Workers outlive whoever spawned them: a worker leaves the spawner's process tree (forked again, `setsid`,
|
|
38
|
+
reparented to init), so a tool tearing down a background `chi send --wait`, or a closing terminal, no longer
|
|
39
|
+
kills it mid-turn (run #43 lost a 169-step turn that way).
|
|
40
|
+
- A card shown during a turn by a worker that has since exited comes back read-only: no buttons. A stale check-in
|
|
41
|
+
card's Nudge steered the next worker's turn on every click. Cards shown between turns (github-pr's offer, btw,
|
|
42
|
+
coordinator) keep their buttons.
|
|
43
|
+
- check-in nudges once per check-in: repeated Nudge clicks (or `/checkin nudge`) on the same check-in answer
|
|
44
|
+
"check-in: already nudged at N tool calls" instead of steering the turn again. Run #43 got 12 identical nudges.
|
|
45
|
+
- Web: a ref's `▾` sits in room the ref makes on hover, never over the next words.
|
|
46
|
+
|
|
47
|
+
Update with `chi update`: the system bundle 0.61.0 and check-in 0.2.4 (nudges once per check-in). Then restart
|
|
48
|
+
`chi web`.
|
|
49
|
+
|
|
11
50
|
## [0.60.0] - 2026-10-11
|
|
12
51
|
|
|
13
52
|
### Added
|
|
@@ -2623,7 +2662,8 @@ and long-lived sessions.
|
|
|
2623
2662
|
- A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
|
|
2624
2663
|
hotkey panel that send selected text or the clipboard to your sessions.
|
|
2625
2664
|
|
|
2626
|
-
[Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.
|
|
2665
|
+
[Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.61.0...HEAD
|
|
2666
|
+
[0.61.0]: https://github.com/dm1try/samagotchi/compare/v0.60.0...v0.61.0
|
|
2627
2667
|
[0.60.0]: https://github.com/dm1try/samagotchi/compare/v0.59.0...v0.60.0
|
|
2628
2668
|
[0.59.0]: https://github.com/dm1try/samagotchi/compare/v0.58.0...v0.59.0
|
|
2629
2669
|
[0.58.0]: https://github.com/dm1try/samagotchi/compare/v0.57.0...v0.58.0
|
data/docs/architecture.md
CHANGED
|
@@ -97,7 +97,7 @@ terminal renders the events it gets over the Bridge.
|
|
|
97
97
|
| Adapters | `Samagotchi::Client`, `LLM::OpenAIChat`, `LLM::HTTP` | Raw-prompt servers, the OpenAI chat API, and the HTTP both share. |
|
|
98
98
|
| Tools | `lib/samagotchi/tools/*` | Execute, read, edit, write, memory, task_*, web_fetch, delegate/delegate_result, ask_user_question, reminders, send_note, list_sessions, context_read, forget_outputs, plus runtime/output-guardrails. |
|
|
99
99
|
| Bundles | `lib/samagotchi/memory_bundle/*`, `BundleCommand` | `chi bundle`: install/upgrade (3-way merge), build, uninstall; the install record under `.bundles/<name>/` that the hook, guardrail and plugin loaders read ([internals/bundles.md](internals/bundles.md)). |
|
|
100
|
-
| Background | `Samagotchi::Worker`, `Samagotchi::SessionManager` | `SessionManager` forks/spawns one worker process per session; its `Worker` builds the `Engine` and `Bridge` (no terminal rendering) and runs queued turns. |
|
|
100
|
+
| Background | `Samagotchi::Worker`, `Samagotchi::SessionManager` | `SessionManager` forks/spawns one worker process per session; its `Worker` builds the `Engine` and `Bridge` (no terminal rendering) and runs queued turns. The spawned process (own process group) forks the worker, which `setsid`s and is reparented to init once its starter exits (it waits until the worker holds `owner.lock`, so the spawner's `Process.detach` waiter tells a starting worker): nothing that walks the spawner's process tree reaches it (`SAMAGOTCHI_WORKER_DETACH=1`, `detach_from_spawner`). The lock's pid is the worker's; `spawn`'s `child_pid` is its starter's. |
|
|
101
101
|
| Web | `Samagotchi::Web::App`, `Samagotchi::Web::Server`, `Samagotchi::Web::SessionHub` | Rack+WEBrick single-port `127.0.0.1:4567` (index.html + `/api/*` + SSE). The hub is chi web's projection of the session list, pushed to every tab over `GET /api/events`. |
|
|
102
102
|
| Sessions | `Samagotchi::Session`, `SessionManager` | File `sessions/<uuid>.json` + sidecar `input/`/`output/`; retention 14d/500, `updated_at desc`, lazy sweep. |
|
|
103
103
|
|
|
@@ -297,7 +297,8 @@ process that already owns the `Engine`); every worker starts it, and it exposes:
|
|
|
297
297
|
(`GET /api/sessions/:id`, `?parts=1`) and the plugin's `list_sessions`; every message is copied.
|
|
298
298
|
- `GET /session/:id/tail` — the page's light re-read (`Bridge#tail_frame`): `session_state_snapshot`,
|
|
299
299
|
`answer` (the last message a UI shows as an answer, `AnswerTail`: the one message, copied alone),
|
|
300
|
-
`cards` (`CardStore#list
|
|
300
|
+
`cards` (`CardStore#list`; a card an earlier worker showed during a turn comes back read-only, with no
|
|
301
|
+
actions: its turn no longer runs), `event_seq`, `event_id`, all taken in one event-log hold; no message
|
|
301
302
|
list, so it costs the same however long the session is. `?turn_id=` answers that turn's answer
|
|
302
303
|
(an unknown or missing id: the newest); the only route that reads its query.
|
|
303
304
|
- `OPTIONS *` — CORS preflight (`Access-Control-Allow-Origin: *`).
|
|
@@ -318,11 +319,13 @@ it, so the web's info bar updates per generation without parsing chunk payloads.
|
|
|
318
319
|
|
|
319
320
|
The page's frequent reads of `GET /api/sessions/:id` stay light too:
|
|
320
321
|
- `?tail=1&recent=1` (each turn's end, a cancel, an answer display): `{tail, session: {id, status,
|
|
321
|
-
used_memory_names}, messages: [the answer], markdown_warning, timing}`, from the worker's `/tail`
|
|
322
|
+
used_memory_names}, messages: [the answer, with its display and display_refs (re-read on an `answer_display` with a display or refs)], markdown_warning, timing}`, from the worker's `/tail`
|
|
322
323
|
alone (no session file parsed, no `analytics.json`); `timing` carries the worker's recent records
|
|
323
324
|
and `turn_count` (finished turns). The page merges the records by id (`timing.js mergeTiming`) and
|
|
324
325
|
finishes the ended turn's own line by its `turn_id` (sent as `&turn_id=`, which also picks that
|
|
325
326
|
turn's answer). A plain `?tail=1` (a tab opened before this) gets the whole timing.
|
|
327
|
+
The page binds an answer's `display_refs` to its bubble (`answer_refs.js`: on a reload's render and on this
|
|
328
|
+
read's re-render) and pairs them with the bubble's links and text before the `path:line` scan.
|
|
326
329
|
- `?timing=1`: the whole timing (`analytics.json` merged with the worker's `/state`) and
|
|
327
330
|
`turn_count`, when the page's merge came up short.
|
|
328
331
|
- `?cards=1`: the cards, from `/tail`; the session file is only stat'ed for the 404.
|
|
@@ -451,7 +454,7 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
|
|
|
451
454
|
|
|
452
455
|
| Component | Main file(s) | What it is |
|
|
453
456
|
|---|---|---|
|
|
454
|
-
| Worker | `worker.rb` (`worker_idle_exit.rb`, `worker_inbound.rb`) | A session's background process: builds the `Engine` and `Bridge`, runs queued turns, exits when idle. |
|
|
457
|
+
| Worker | `worker.rb` (`worker_idle_exit.rb`, `worker_inbound.rb`, `worker_signals.rb`) | A session's background process: builds the `Engine` and `Bridge`, runs queued turns, exits when idle. A spawned one traps TERM, HUP and INT (`WorkerSignals`, installed by `run_session_loop` when `SAMAGOTCHI_WORKER_PROCESS=1`): the running turn stops as a Stop with reason `signal`, is saved, and the worker leaves (`:signal`, exit 0; a new worker only for input already queued). A running turn is checkpointed at its iteration boundaries (`TurnCheckpoint`, the `interrupted_turn` mark), and the next worker settles a turn its predecessor died in (`TurnCheckpoint.settle`). |
|
|
455
458
|
| Config | `config.rb` | Every setting as an `Entry`: env, config.yml and CLI layers ([configuration.md](configuration.md)). |
|
|
456
459
|
| MemoryBundle | `memory_bundle.rb`, `memory_bundle/{installer,builder,installed_bundle,plugin_ref,bundle_hook}.rb` (`Installer`, `Builder`, `InstalledBundle`, `PluginRef`, `BundleHook`) | Installing, building and reading bundles of memories, hooks and plugins. |
|
|
457
460
|
| Plugin API | `plugin/api.rb` (`Plugin::Api`), `plugin/loader.rb` | What a bundle's plugin registers: tools, commands, hooks, services ([plugins.md](plugins.md)). |
|
data/docs/hooks.md
CHANGED
|
@@ -51,7 +51,7 @@ The plugin class must respond to `#call(event)` — duck-typed, no base class re
|
|
|
51
51
|
|-------|--------------|---------------|
|
|
52
52
|
| `:session_start` | The first turn this chi process runs for the session (so again after `--resume`, a worker that idle-exited and woke, or a restart) | `{ type: :session_start, session_id: "..." }` |
|
|
53
53
|
| `:before_turn` | Before each turn starts | `{ type: :before_turn, session_id: "...", prompt: "..." (nil on a continue), resumed: true \| false (true on a step-limit Continue, which resumes the run before it; false on every other turn, a reminder's or a wake's too), messages: [...] (the history before this turn) }` |
|
|
54
|
-
| `:after_turn` | After a turn completed or was stopped once the model was asked (not after one that failed, was cut short by an interrupt signal (SIGINT), or was stopped before its `:before_turn` hooks) | `{ type: :after_turn, status: "completed" \| "canceled", present: (see [Presenting the answer](#presenting-the-answer-display-only)), messages: [...] (the conversation the turn stored; a cancelled or empty turn ends it with a `kind: turn_note` system message, and a context line is `kind: context`, see [sessions.md](sessions.md#notes-a-turn-leaves-for-the-model)) }` |
|
|
54
|
+
| `:after_turn` | After a turn completed or was stopped once the model was asked (not after one that failed, was cut short by an interrupt signal (SIGINT), or was stopped before its `:before_turn` hooks) | `{ type: :after_turn, status: "completed" \| "canceled", present: (see [Presenting the answer](#presenting-the-answer-display-only)), refs: (see [Refs on the answer](#refs-on-the-answer-display-only)), messages: [...] (the conversation the turn stored; a cancelled or empty turn ends it with a `kind: turn_note` system message, and a context line is `kind: context`, see [sessions.md](sessions.md#notes-a-turn-leaves-for-the-model)) }` |
|
|
55
55
|
| `:before_generation` | Before each LLM API call (both loops) | `{ type: :before_generation, iteration: N }` |
|
|
56
56
|
| `:after_generation` | After LLM returns (both loops); not after a generation a hook cut (`stop_generation`) | `{ type: :after_generation, iteration: N, response: "...", messages: [...] (the conversation as sent) }` |
|
|
57
57
|
| `:generation_progress` | While the response streams, in batches (see [Watching the stream](#watching-the-stream)) | `{ type: :generation_progress, iteration: N, thinking: "..." (new since the last fire), text: "..." (new visible text), thinking_chars: N, text_chars: N (this generation so far), elapsed_ms: N, restarted: true (only on the first fire after a dropped stream was asked again) }` |
|
|
@@ -275,6 +275,77 @@ end
|
|
|
275
275
|
|
|
276
276
|
A plugin gets the same from `chi.on(:after_turn) { |event, ctx| event[:present].call { … } }`.
|
|
277
277
|
|
|
278
|
+
## Refs on the answer (display only)
|
|
279
|
+
|
|
280
|
+
`:after_turn` also carries `refs:`, a callable that attaches a **ref** to the
|
|
281
|
+
turn's answer: a thing the answer mentions (an issue, a file, a commit) as
|
|
282
|
+
data, with links to open it. Like `present`, it is display only.
|
|
283
|
+
|
|
284
|
+
```ruby
|
|
285
|
+
class JiraRefs
|
|
286
|
+
def call(event)
|
|
287
|
+
return unless event[:type] == :after_turn
|
|
288
|
+
|
|
289
|
+
answer = event[:messages].last
|
|
290
|
+
return unless answer && answer[:role] == "model"
|
|
291
|
+
|
|
292
|
+
answer[:content].to_s.scan(/\b[A-Z][A-Z0-9]+-\d+\b/).uniq.each do |key|
|
|
293
|
+
event[:refs].call(match: key, kind: "issue", target: { id: key }, label: key,
|
|
294
|
+
actions: [{ id: "open", label: "Open in Jira", url: "https://jira.example.com/browse/#{key}" }])
|
|
295
|
+
end
|
|
296
|
+
end
|
|
297
|
+
end
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
- The call: `event[:refs].call(match:, kind:, target:, label: nil, actions: [])`,
|
|
301
|
+
keywords only (String or Symbol keys inside `target` and `actions`).
|
|
302
|
+
- `match`: the text in the answer the ref stands for (at most 500 characters).
|
|
303
|
+
- `kind`: a short lowercase word. `"file"` takes `target: {path:, line:, end_line:}`
|
|
304
|
+
(the lines optional); a relative path is resolved against the session's
|
|
305
|
+
folder, an absolute one is kept as given. Any other kind (`"issue"`,
|
|
306
|
+
`"commit"`, …) takes `target: {id:}`.
|
|
307
|
+
- `label`: what a UI shows for it (optional, at most 200 characters).
|
|
308
|
+
- `actions`: links a UI offers on top of the kind's own, each
|
|
309
|
+
`{id:, label:, url:}`; http(s) URLs only, without userinfo (`user:pass@`),
|
|
310
|
+
at most 8, opened in a new tab.
|
|
311
|
+
- It returns `true` when the ref is kept (or was there already: a duplicate
|
|
312
|
+
is kept once), `false` when it is refused, and `nil` when the turn has no
|
|
313
|
+
answer (as `present`: after a cancelled, failed or empty turn) or the call
|
|
314
|
+
comes after the hooks ran (a plugin that kept `event[:refs]`: the refs are
|
|
315
|
+
stored by then).
|
|
316
|
+
- Caps: 200 refs and 256 KiB (the list's JSON) per answer; an action's id
|
|
317
|
+
at most 64 characters and its label 100; a target id 200, a path 4,096.
|
|
318
|
+
- A refused ref is logged as `refs_rejected` with the hook's label and the
|
|
319
|
+
reason, each reason once per hook per answer (the same again is logged at
|
|
320
|
+
debug with its count). The call never raises into the hook.
|
|
321
|
+
- Refs are independent of `present`: a rejected `present` keeps them, and a
|
|
322
|
+
ref whose `match` isn't in the shown text is still stored (a UI drops it).
|
|
323
|
+
- They are kept as `display_refs` on the answer's model message in the
|
|
324
|
+
session file, next to `display`, and the `answer_display` event says how
|
|
325
|
+
many (`refs: N`). The model never sees them (as `display`), and a fork
|
|
326
|
+
(`chi.sessions.fork(messages: ctx.messages)`) starts without them.
|
|
327
|
+
- **The web** pairs each ref with the shown answer (its rendered markdown,
|
|
328
|
+
or the `present`ed display), live (with the turn-end read when the refs
|
|
329
|
+
are stored by then, else on the `answer_display` event) and on a reload. It looks, over all the answer's refs, for:
|
|
330
|
+
1. a link whose href is one of the ref's action URLs;
|
|
331
|
+
2. else a link whose text is `match`;
|
|
332
|
+
3. else `match` as a whole word inside one run of plain text (not in a
|
|
333
|
+
code block or another link), or an inline code that is `match` alone.
|
|
334
|
+
The word's edges are checked within that run only: text in the next
|
|
335
|
+
element doesn't count (`JIRA-1<em>2</em>` pairs `JIRA-1`).
|
|
336
|
+
|
|
337
|
+
The ref binds every occurrence its first finding step finds (a ref paired
|
|
338
|
+
with its link leaves a plain mention of the same text alone); a ref
|
|
339
|
+
nothing pairs is dropped. Markdown changes text: `__init__.py` renders
|
|
340
|
+
bold, escapes and entities differ, a match across emphasis or code isn't
|
|
341
|
+
one run, so keep a markdown link to the ref's URL, or match the rendered
|
|
342
|
+
text. The ref's actions join its menu (a link's own target is labelled by
|
|
343
|
+
the action with its URL); a `file` ref keeps the editor, show-in-turn and
|
|
344
|
+
copy targets; `label` is its hover title when it differs from the text.
|
|
345
|
+
**Terminals** ignore them.
|
|
346
|
+
|
|
347
|
+
A plugin gets the same from `chi.on(:after_turn) { |event, ctx| event[:refs].call(…) }`.
|
|
348
|
+
|
|
278
349
|
## Settings
|
|
279
350
|
|
|
280
351
|
A hook class whose `initialize` takes an argument gets its settings: **one
|
data/docs/internals/engine.md
CHANGED
|
@@ -56,9 +56,11 @@ Engine#run_turn(session, prompt, on_event:, max_iterations:, cancel_controller:,
|
|
|
56
56
|
│ # end_turn(turn, "completed" | "canceled"): under the event lock the session gets the kept
|
|
57
57
|
│ # messages, goes IDLE, records last_turn, and :turn_completed {result, turn_summary,
|
|
58
58
|
│ # display_pending} or :turn_canceled {cancellation_reason, cancelled_by, duration_ms} is emitted
|
|
59
|
-
│ # then the :after_turn hook (status, messages, present: the AnswerDisplay presenter
|
|
60
|
-
│ #
|
|
61
|
-
│ #
|
|
59
|
+
│ # then the :after_turn hook (status, messages, present: the AnswerDisplay presenter,
|
|
60
|
+
│ # refs: the AnswerRefs adder)
|
|
61
|
+
│ # store_answer_display (one replace of the answer: `display` and/or `display_refs`;
|
|
62
|
+
│ # :answer_display {display, refs: N} to the observers when a hook changed the answer or
|
|
63
|
+
│ # attached refs, or display: nil when the web was told to wait for it)
|
|
62
64
|
│ # then the :session_end hook
|
|
63
65
|
│
|
|
64
66
|
├── warm_up_next_turn(turn, result)
|
|
@@ -86,7 +88,7 @@ StandardError in run_turn:
|
|
|
86
88
|
# error_kind, retryable, host and summary.
|
|
87
89
|
→ re-raised
|
|
88
90
|
|
|
89
|
-
Interrupt (Ctrl-C):
|
|
91
|
+
Interrupt (Ctrl-C; the REPL only: a worker traps INT, see the signal row below):
|
|
90
92
|
→ if turn.ended: re-raised only
|
|
91
93
|
→ turn.controller.cancel!(:ctrl_c)
|
|
92
94
|
→ end_turn(turn, "canceled"): ctrl_c_messages keeps turn.messages with TurnNote.cancelled(:ctrl_c)
|
|
@@ -102,6 +104,17 @@ A Stop (Engine#cancel_current_turn!, e.g. the Bridge's POST cancel) or a hook's
|
|
|
102
104
|
→ complete_turn keeps the loop's conversation (tool iterations included) with a
|
|
103
105
|
TurnNote.cancelled note; a text streamed before the cancel stays, marked [interrupted]
|
|
104
106
|
|
|
107
|
+
A worker's TERM, HUP or INT (WorkerSignals, trapped by a spawned worker only):
|
|
108
|
+
→ a Stop with reason :signal (Worker#signalled, off the trap, retried until the loop leaves)
|
|
109
|
+
→ :turn_canceled {cancellation_reason: :signal}, saved by the Worker as after any turn;
|
|
110
|
+
Worker#run returns :signal (:stopped with the stop marker), takes no new work
|
|
111
|
+
→ not ended within Worker::SIGNAL_GRACE (a turn that ended and runs its after_turn hooks gets
|
|
112
|
+
SIGNAL_HARD_EXIT more, uncanceled): the session saved as it is, SignalException raised in the
|
|
113
|
+
loop's thread, only while the loop runs (never into start, serve or the teardown, which runs whole)
|
|
114
|
+
→ the process ends SIGNAL_HARD_EXIT (10 s) after that at the latest (exit!); a signal after the
|
|
115
|
+
loop left brings only that hard exit, and run_session_loop restores the default handlers
|
|
116
|
+
→ run_session_loop: exit 0, no discard; input queued behind the stopped turn wakes a new worker
|
|
117
|
+
|
|
105
118
|
Stopped before the model was asked (prepare_turn returned false):
|
|
106
119
|
→ stopped_before_model(turn) → end_turn(turn, "canceled")
|
|
107
120
|
→ nothing kept, :turn_canceled {cancellation_reason, cancelled_by, duration_ms}
|
|
@@ -299,6 +312,14 @@ end
|
|
|
299
312
|
turn through the Bridge (`POST cancel` → `Engine#cancel_current_turn!`).
|
|
300
313
|
- `on_event` is the turn's sink.
|
|
301
314
|
- `ended` is set by `end_turn`.
|
|
315
|
+
- The live conversation: both loops register the array they append to on the kernel
|
|
316
|
+
(`KernelLoop#llm_context_turn`, `LLMContextForget::Turn#conversation`; `KernelLoop#start_turn`,
|
|
317
|
+
`ChatLoop::Run#initialize`). `Engine#live_conversation` returns it while a turn runs (nil otherwise: the kernel
|
|
318
|
+
never clears it). A worker's drain (`Worker#pending_input_drain`, on the turn's thread at every iteration
|
|
319
|
+
boundary) copies it, with the lines that boundary merges, into `Session#turn_checkpoint` (`TurnCheckpoint`):
|
|
320
|
+
every save while the turn runs writes that copy with an `interrupted_turn` mark instead of the session's
|
|
321
|
+
messages, written at the first boundary and then at most every 10 s, so a killed worker loses at most that much
|
|
322
|
+
of its turn. `session.messages` itself is untouched until the turn ends.
|
|
302
323
|
|
|
303
324
|
### GenerationPhase
|
|
304
325
|
|
|
@@ -352,7 +373,7 @@ Turn events (the main ones; `Events` in `events.rb` keeps the shared sets):
|
|
|
352
373
|
| `:turn_completed` | normal end | `{result, turn_summary, display_pending}` |
|
|
353
374
|
| `:turn_canceled` | Stop, hook stop, Ctrl-C | `{cancellation_reason, cancelled_by?, duration_ms}` |
|
|
354
375
|
| `:turn_failed` | an error | `{error_class, message, duration_ms, error_kind?, retryable?, host?, summary?}` |
|
|
355
|
-
| `:answer_display` | after the after_turn hooks (observers only, not the sink) | `{display}` (a string, or nil) |
|
|
376
|
+
| `:answer_display` | after the after_turn hooks (observers only, not the sink) | `{display, refs?}` (display a string, or nil; refs the count of the answer's refs, only when a hook attached some) |
|
|
356
377
|
|
|
357
378
|
The boundary events (`:turn_started`, `:turn_completed`, `:turn_canceled`, `:turn_failed`) also carry `origin`
|
|
358
379
|
when the turn was queued with one.
|
|
@@ -410,6 +431,14 @@ puts the hook runtime on the event: `event[:hook]` (the hook's label) and five h
|
|
|
410
431
|
|
|
411
432
|
From `:after_turn` and `:session_end` there is no turn left: `stop_turn` and `steer` return false.
|
|
412
433
|
|
|
434
|
+
`:after_turn` adds two of its own, built by `complete_turn` on the stored conversation's last message when it is the
|
|
435
|
+
model's: `event[:present]` (`AnswerDisplay`, the answer's `display` text) and `event[:refs]` (`AnswerRefs`, refs kept
|
|
436
|
+
as `display_refs`: caps, validation, relative file paths resolved against the session's folder, `refs_rejected`
|
|
437
|
+
logged). Both are display only: `AnswerDisplay::DISPLAY_ONLY` lists `display`, `empty_answer` and `display_refs`, which
|
|
438
|
+
`strip`/`strip_all` drop from every model-facing copy (hooks' `messages:`, the recap, `ctx.messages`,
|
|
439
|
+
after_generation), while `KernelLoop#sanitize_history` and `ChatLoop#plain` copy them so the stored conversation keeps
|
|
440
|
+
them across turns. `Web::App#messages_for_display` sends `display_refs` re-validated (`AnswerRefs.for_display`).
|
|
441
|
+
|
|
413
442
|
### Hook lifecycle
|
|
414
443
|
|
|
415
444
|
- **Bundle hooks** (`Registry#register_bundle`) and **config hooks** (`register_persistent`, from config.yml)
|
|
@@ -127,7 +127,9 @@ is prefilled once. The native and the chat loop use the same plan.
|
|
|
127
127
|
a per-session value in the stable part. A guard spec checks that model, location and session are the last
|
|
128
128
|
sections (`spec/system_prompt_model_spec.rb`).
|
|
129
129
|
2. **History is append-only.** Never rewrite an earlier message. Add a note at the tail instead. If a model's
|
|
130
|
-
spec forces a rewrite (e.g. stripping previous-turn thinking), accept the re-prefill and note it.
|
|
130
|
+
spec forces a rewrite (e.g. stripping previous-turn thinking), accept the re-prefill and note it. A worker's
|
|
131
|
+
mid-turn checkpoint (`TurnCheckpoint`) is append-only too (the history plus what the loop appended) and
|
|
132
|
+
never changes the request bytes.
|
|
131
133
|
3. **Deterministic order.** Tools, memory lists and anything else that's rendered from a hash or a set needs a
|
|
132
134
|
fixed sort. Plugin tools are sorted by (bundle, name) whatever order their plugins finished starting in
|
|
133
135
|
(R5a).
|
data/docs/plugins.md
CHANGED
|
@@ -330,7 +330,8 @@ end
|
|
|
330
330
|
This is a bundle hook, the same as a `hooks/*.rb` file. See
|
|
331
331
|
[hooks.md](hooks.md#hook-events) for the events; on `:after_turn`,
|
|
332
332
|
`event[:present]` sets how the answer is shown in the web
|
|
333
|
-
([Presenting the answer](hooks.md#presenting-the-answer-display-only))
|
|
333
|
+
([Presenting the answer](hooks.md#presenting-the-answer-display-only)) and `event[:refs]`
|
|
334
|
+
attaches refs to it ([Refs on the answer](hooks.md#refs-on-the-answer-display-only)). Its label is
|
|
334
335
|
`plugin.rb (bundle my-bundle)`. The block may take only the event. If it
|
|
335
336
|
raises, the error is logged and the hook is skipped.
|
|
336
337
|
|
|
@@ -1127,13 +1128,16 @@ what it has found. check-in counts the turn's tool calls, and when there are
|
|
|
1127
1128
|
and its last few tools, and three actions:
|
|
1128
1129
|
- **Nudge** (`/checkin nudge`): puts `message` into the running turn
|
|
1129
1130
|
(`ctx.steer`); the model reads it at its next step and answers or says
|
|
1130
|
-
what is left. Every UI shows `check-in> nudged: …`.
|
|
1131
|
+
what is left. Every UI shows `check-in> nudged: …`. One nudge per
|
|
1132
|
+
check-in: another click (or a typed `/checkin nudge`) answers
|
|
1133
|
+
"check-in: already nudged at N tool calls".
|
|
1131
1134
|
- **Keep going** (`/checkin later`): closes the card until the next
|
|
1132
1135
|
check-in.
|
|
1133
1136
|
- **Stop** (`/checkin stop`): stops the turn.
|
|
1134
1137
|
|
|
1135
1138
|
When the turn ends the card loses its actions ("The turn ended after N tool
|
|
1136
|
-
calls"), so no stale buttons stay
|
|
1139
|
+
calls"), so no stale buttons stay; a card left by a worker that exited
|
|
1140
|
+
mid-turn comes back without them too. In the attached terminal the actions are
|
|
1137
1141
|
`→ /checkin nudge` lines to type; the command runs beside the turn.
|
|
1138
1142
|
- **`mode: nudge`**: nudges the model by itself, with a notice line.
|
|
1139
1143
|
- **`mode: notify`**: a notice line only.
|
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 (and the turn's metrics: `analytics.json` is written at a turn's end). 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; 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 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), `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), `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:**
|
|
@@ -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) }
|