samagotchi 0.180.0 → 0.182.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 +71 -1
- data/bin/chi +11 -0
- data/docs/architecture.md +2 -2
- data/docs/bundles.md +7 -2
- data/docs/cli.md +46 -13
- data/docs/configuration.md +25 -4
- data/docs/internals/anthropic.md +4 -3
- data/docs/internals/background-tasks.md +2 -0
- data/docs/internals/block-renderers.md +123 -6
- data/docs/internals/bridge.md +10 -0
- data/docs/internals/engine.md +11 -0
- data/docs/internals/inline-widgets.md +3 -1
- data/docs/internals/objectives.md +9 -4
- data/docs/internals/prompt-caching.md +9 -1
- data/docs/internals/remote-sessions.md +14 -2
- data/docs/internals/web-frontend.md +100 -10
- data/docs/internals/working-set.md +24 -5
- data/docs/memory.md +3 -0
- data/docs/plugins.md +11 -4
- data/docs/sessions.md +8 -5
- data/docs/testing.md +1 -1
- data/lib/samagotchi/answer_display.rb +3 -2
- data/lib/samagotchi/block_fix/stamp.rb +49 -0
- data/lib/samagotchi/block_fix.rb +220 -0
- data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
- data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
- data/lib/samagotchi/bridge.rb +11 -2
- data/lib/samagotchi/bridge_client.rb +9 -0
- data/lib/samagotchi/bundle_command.rb +4 -1
- data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
- data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/client.rb +8 -1
- data/lib/samagotchi/config.rb +9 -1
- data/lib/samagotchi/continue_intent.rb +8 -0
- data/lib/samagotchi/core_notice.rb +44 -0
- data/lib/samagotchi/engine/block_fix.rb +332 -0
- data/lib/samagotchi/engine/side_requests.rb +7 -5
- data/lib/samagotchi/engine.rb +4 -0
- data/lib/samagotchi/events.rb +1 -0
- data/lib/samagotchi/host_address.rb +7 -0
- data/lib/samagotchi/host_config.rb +8 -5
- data/lib/samagotchi/host_registry.rb +26 -8
- data/lib/samagotchi/idle_client.rb +10 -6
- data/lib/samagotchi/inline_widgets.rb +12 -0
- data/lib/samagotchi/kernel_loop.rb +10 -7
- data/lib/samagotchi/llm/adapter_common.rb +3 -2
- data/lib/samagotchi/llm/adapters.rb +2 -1
- data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
- data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
- data/lib/samagotchi/llm/chat_loop.rb +8 -5
- data/lib/samagotchi/llm/errors.rb +41 -3
- data/lib/samagotchi/llm/http.rb +85 -22
- data/lib/samagotchi/llm/openai_chat.rb +20 -3
- data/lib/samagotchi/markdown_parser.rb +28 -0
- data/lib/samagotchi/memory_bundle/status.rb +2 -1
- data/lib/samagotchi/objectives.rb +7 -2
- data/lib/samagotchi/owner_lock.rb +2 -0
- data/lib/samagotchi/plugin/api.rb +4 -1
- data/lib/samagotchi/plugin/context.rb +9 -0
- data/lib/samagotchi/plugin/peer.rb +32 -15
- data/lib/samagotchi/plugin/tool_spec.rb +13 -2
- data/lib/samagotchi/row_refs.rb +14 -3
- data/lib/samagotchi/session_access/contract.rb +3 -0
- data/lib/samagotchi/session_access/delete_plan.rb +77 -0
- data/lib/samagotchi/session_access/local.rb +13 -0
- data/lib/samagotchi/session_access/remote.rb +19 -1
- data/lib/samagotchi/session_access.rb +1 -0
- data/lib/samagotchi/session_chain/delete.rb +45 -87
- data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
- data/lib/samagotchi/session_delete_command.rb +129 -3
- data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
- data/lib/samagotchi/session_manager/listing.rb +4 -4
- data/lib/samagotchi/session_manager/removal.rb +40 -14
- data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
- data/lib/samagotchi/session_manager.rb +1 -0
- data/lib/samagotchi/tool_ids.rb +19 -0
- data/lib/samagotchi/tool_runner.rb +8 -4
- data/lib/samagotchi/tools/registry.rb +3 -2
- data/lib/samagotchi/tools/task_runtime.rb +34 -0
- data/lib/samagotchi/turn_stages/objectives.rb +10 -5
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +13 -1
- data/lib/samagotchi/web/block_fix_routes.rb +39 -0
- data/lib/samagotchi/web/markdown_renderer.rb +24 -9
- data/lib/samagotchi/web/message_display.rb +6 -1
- data/lib/samagotchi/web/participant_view.rb +1 -1
- data/lib/samagotchi/web/public/app.js +15 -19
- data/lib/samagotchi/web/public/block_fix.js +270 -0
- data/lib/samagotchi/web/public/block_fix_note.js +104 -0
- data/lib/samagotchi/web/public/block_frame.js +6 -3
- data/lib/samagotchi/web/public/block_host.js +21 -21
- data/lib/samagotchi/web/public/block_renderers.css +17 -5
- data/lib/samagotchi/web/public/block_watch.js +16 -2
- data/lib/samagotchi/web/public/context_chips.js +3 -4
- data/lib/samagotchi/web/public/images.js +1 -1
- data/lib/samagotchi/web/public/index.html +24 -5
- data/lib/samagotchi/web/public/inline_widgets.js +1 -1
- data/lib/samagotchi/web/public/objectives_strip.js +16 -6
- data/lib/samagotchi/web/public/pan_zoom.js +121 -0
- data/lib/samagotchi/web/public/peer_chip.js +3 -3
- data/lib/samagotchi/web/public/peer_data.js +27 -15
- data/lib/samagotchi/web/public/picture_viewer.js +304 -0
- data/lib/samagotchi/web/public/popover_modal.js +3 -2
- data/lib/samagotchi/web/public/session_view.js +4 -0
- data/lib/samagotchi/web/public/stream_handlers.js +5 -1
- data/lib/samagotchi/web/public/turn_block.js +5 -2
- data/lib/samagotchi/web/public/working_set.js +9 -3
- data/lib/samagotchi/web/public/working_set_view.js +28 -11
- data/lib/samagotchi/web/public/ws_cards.js +36 -10
- data/lib/samagotchi/web/public/ws_markdown.js +129 -0
- data/lib/samagotchi/web/public/ws_order.js +48 -0
- data/lib/samagotchi/web/public/ws_peek.js +22 -5
- data/lib/samagotchi/web/public/ws_preview.css +41 -1
- data/lib/samagotchi/web/public/ws_reader.js +35 -6
- data/lib/samagotchi/web/public/ws_sections.js +24 -15
- data/lib/samagotchi/web/server.rb +6 -4
- data/lib/samagotchi/web/session_control.rb +53 -21
- data/lib/samagotchi/worker/block_fixes.rb +22 -0
- data/lib/samagotchi/worker.rb +10 -3
- metadata +17 -1
data/docs/sessions.md
CHANGED
|
@@ -8,6 +8,8 @@ continue; the new link starts empty. See [context storage](context.md#storage).
|
|
|
8
8
|
|
|
9
9
|
**Message times:** an entry of `messages` may carry `at`, when it happened: a local-offset ISO time with milliseconds (`2026-10-24T14:32:05.120+02:00`). User prompts, lines merged into a turn and steers, reminders, context and task notes, and the model's replies have one (a note's is its `created_at`); tool results, `!cmd` messages and chi's own turn notes don't, nor does anything saved before chi stamped messages (no backfill). It is for the UIs only (the gap dividers, a bubble's time): it never goes to the model, so it changes nothing in the requests or their prompt cache. The one time the model reads is the reminders': due reminders go into a turn as a system message headed `[SYSTEM: REMINDERS DUE 2026-10-24 14:32 local]` (the turn's local time; `ReminderQueue#inject!`), written into the saved content then, so a later request sends the same text.
|
|
10
10
|
|
|
11
|
+
**Block fixes:** an answer's model message may carry `block_fixes`, a list of `{key, fixed_key, state, reason, at}`, one per fenced block the owner's page couldn't draw and asked for again (`fixed` or `failed`; `key` is the failed block's, `fixed_key` its fix's: `BlockFix.key`). The fix itself is in the message's `content` (no turn had started since) or its `display` (one had). Display only, like `display` and `display_refs`: it never goes to a model, a hook or a plugin, and an older chi reads a message with it without complaint (a turn on an older worker drops the key). See [block-renderers.md](internals/block-renderers.md#a-failed-block-is-asked-for-again).
|
|
12
|
+
|
|
11
13
|
**Verify verdicts:** a web Verify turn stamps its opening user message with `verify: {turn_id, quote}` (the selected source turn and quote; metadata only, never added to the prompt). When that turn completes and the final assistant reply's last non-empty line is a valid `Verdict: confirmed|refuted|unclear — <reason>`, the session file appends `{anchor: {turn_id, quote}, verdict, reason, by, check_turn_id, at}` to its optional `verdicts` array. `by` is the turn's author (nil for the owner), `check_turn_id` names the Verify turn, and `at` is its timestamp. The array is append-only; older files without it have no saved verdicts. An `unclear` verdict can be checked again by **Verify fresh** (a delegate child that gets only the claim; see *Delegating*): its verdict is appended to the parent's `verdicts` with `fresh: true`, `of` (the verdict it checked again) and `child_id`, from the parent's `fresh_verdicts/` dir, which its worker takes between turns. Verdicts are display state: none enters a prompt.
|
|
12
14
|
|
|
13
15
|
**Revise stacks:** a web Revise turn (POST /turn `revises: {turn_id}`, the answer it rewrites) stamps its opening message (its prompt) with `revises: {turn_id}` at the turn's end, only when the turn completed with an answer (`AnswerTail`): a failed, canceled or empty turn revised nothing (`TurnStages::VerifyAnchors#stamp_opening`). A draft no prompt carries (a stale page, a rolled-back turn) is no target: no stamp. A draft a stamped turn already revised is re-targeted to its stack's top, the newest version, so a stack is a chain `v1 ← v2 ← v3`. Like `verify`, it is metadata only, never added to the prompt (no change to a request's bytes); chi web's history passes it on the opening message (and on a wake turn's note), and `:turn_completed` carries the stamped `revises` (the participant view's too). The history also marks a Verify turn's opening `verify: true`, and so does its live end event (`:turn_completed`'s `verify: true`, with its `turn_id`): the page offers no Revise on its answer. The web page draws the stacks from these stamps (docs/cli.md, Revise). Like a Verify turn's, a Revise message waits for the running turn's end (`SessionInbox.turn_end_data?`; the Bridge takes either as `delivery: queue`, so it never cuts and its ack and `:turn_enqueued` say it queues), is sent only to a worker whose `bridge.json` names the `revise` feature (else 409 `revise_unavailable`), and a failed turn gives it back (`:prompt_restored`'s `revises`). A participant's Revise is theirs only (`ParticipantRevise`, from the authors the server stamped): the answer to their own message (not a Verify turn's), with only their own turn openings after it (an owner's `!` line, which they never see, counts for nothing). chi web checks it at the send against the live worker's snapshot (403 `revise_not_own`, the same for a missing turn; 409 `revise_overtaken`; 409 `revise_unavailable` for a live worker without the `participant_revise` feature), and the worker checks it again at the stamp, up to the Revise turn itself. A Revise someone else's turn overtook after the send silently becomes a plain turn: it runs and answers, but nothing folds, no stack is drawn and neither they nor the owner get a notice; only a `revise_anchor_rejected` log line (reason `overtaken` or `not_own`) records it. It isn't refused at the start (a turn can overtake it after the send). A delivery to a live worker without `participant_revise` is refused too (`SessionManager::Delivery`, 409 `revise_unavailable` in their words). The owner's Revise is unchanged, of anyone's answer. Both anchors travel as one `TurnAnchors` inside chi; on the wire and in an input file each keeps its own key (`verify`, `revises`).
|
|
@@ -49,9 +51,9 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
|
|
|
49
51
|
|
|
50
52
|
**Stopping a worker:** `chi sessions stop ID` marks the session stopped (an `<id>/stopped` file holding when, `{"at"}`, not a session.json field, which a worker saving at that moment would write over; a resume removes it), sends its worker TERM, then CONT (a stopped worker, SIGSTOP or Ctrl-Z, runs its TERM handler only once continued, so it leaves at once instead of outliving the wait), and waits (up to 10 s) until the worker has let go of `owner.lock`. A running turn is canceled over the Bridge first, with reason `session_stopped` (the turn's line ends "(session stopped)", its note says `cancelled (session-stopped)`, and a command it was running says "stopped as the session was stopped"; a bare signal to the worker makes it "stopped by a signal to chi"; an older worker takes the reason as `manual`); 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 ⚙ panel, against a 0.39.0 worker) says the same, not `not a session command` (`SessionCommandCatalog.builtin_name`); a typo keeps its `400 unknown_command`. The web's `POST /api/sessions/:id/stop` waits the same way, for 2 s (the page's Stop shows the stop at once), or for the body's `wait` up to the same 10 s (`SessionManager::STOP_WAIT`): `chi --remote NAME sessions stop` sends it, so it waits as long as here. Before that stop, the page's `stop session` button asks what the worker still has that the user can stop: `GET /api/sessions/:id/holds` (owner-only) answers the worker's `holds` — the same list the exit ask's 409 carries — always an array, empty when there is no live worker, one from before the route, or one that did not answer. With something, a sheet (a bottom sheet on a phone, a popover at the button otherwise — `stop_sheet.js`) lists them, at most three of a kind named and `+N more`, and offers **Stop all** (`POST /api/sessions/:id/holds/stop` → `HoldStop#stop_all`, then the stop), **Stop session only** (the stop exactly as it was) or **Cancel**. Nothing to ask about is the plain confirm, one tap as before. Both buttons stay because a stop only TERMs the worker: its reminders die with it (a stop also deletes a restart's `reminders.json` no successor took yet, so a later resume doesn't bring them back), while a background task and a delegate are their own processes and keep running. A delete or an archive differs: it never leaves a task the session started running unasked (*Deleting a session*: refused, or `--stop-tasks` stops it), where Stop's "Stop session only" does. 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.
|
|
51
53
|
|
|
52
|
-
**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 one-turn `chi --non-interactive` run has (`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 page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`)
|
|
54
|
+
**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 one-turn `chi --non-interactive` run has (`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 page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) goes through `SessionChain::Delete.link` for every session, chained or not (*Session chains* → Deleting a link): **its delegates follow one rule** (`SessionManager::DELEGATES`): the stopped ones (archived ones too) go with it, deepest first, and a running one stays with its whole subtree, its file untouched; a stopped delegate with a running child goes and leaves that child without a parent. The delegates that would go bring their own refusals: one that is a schedule's target, anchor or head refuses the delete (`scheduled`, naming the delegate), as does one in a one-turn run, one a worker took after the plan was made (`worker_running`), and their running background tasks (below); their participant grants end with them. The result lists them in `deleted` (the session last) and the running ones with their subtrees in `left_running`; the CLI's line and `/exit --delete` say how many went. It is also refused while a continue of the session, or of the previous link it would bring back, is under way (`continuing`), and deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly (`delete_resolved`: they pass neither keyword and take no delegates); the retention sweep removes files directly (`remove_files`). **Background tasks still running:** a user's delete (these three, and `chi sessions delete`) asks first when tasks the deleted sessions started (their `task_create` tasks and the `execute` runs handed over at their limit, read from each session's transcript and `<working_directory>/tmp/tasks/<id>/task.json`: `SessionManager::RunningTasks`) still run: it is refused before anything changes (`tasks_running`), and the CLI's `--stop-tasks`, the web's `stop_tasks=true` (the delete's and the chain delete's query; with `&tasks=<id,id>`, the ones the sheet named, only those: `RunningTasks::Policy.stop(only:)`, see *Deleting a link*) stop them first (`stopped_by_user`, TERM then KILL after 3 s, all at once, about 4 s at most), under the deleting lock, after the starting-marker re-check, so no worker takes the session meanwhile; that last check refuses a task that started since the first (`worker_stopped: true` when the worker was stopped by then). One rule, fail-safe: a task whose pid still leads the group chi started at the start time it recorded is *running*; one whose record has no start time (before 2026-10-09) or whose start time reads nothing now, while its pid leads a group, is *unverified* ("may still be running"); a `task.json` that doesn't read is *unreadable*. All three refuse; a stop signals only the running ones (an unverified pid may belong to another process now) and reports the rest as not stopped, then deletes. A record left marked running whose pid is gone (a crashed worker's) isn't listed. The 409 is `{error: "tasks_running", reason, op: "delete", detail, session_id, tasks: {running, unverified, unreadable}, worker_stopped, stopped_worker, stopped_workers}` (`stopped_worker`: whose worker the delete stopped before the last check refused; `stopped_workers`: every worker the delete stopped), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
|
|
53
55
|
|
|
54
|
-
<a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}`, stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`. An archive takes no lock for it. Undo (unarchive) doesn't restart them. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
|
|
56
|
+
<a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. The 409 also says `sessions`: how many sessions the archive would hide (it and its delegates, across every project), plus `stopped_workers` (every stopped worker id). The refusal words name one stopped worker as "its worker was stopped" or "9d0e1f2a's worker was stopped", and several as "N workers were stopped: its own, 9d0e1f2a". `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}` (with `"tasks": [ids]` only those; a running one not named refuses, `tasks_running`, nothing archived: up front before any worker is stopped, and again after the workers let go), stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`. An archive takes no lock for it. Undo (unarchive) doesn't restart them. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
|
|
55
57
|
|
|
56
58
|
**System 1's saved runs** last as long as sessions: the sweep ages them by day file, and deleting a session purges its runs ([system-one.md](system-one.md)).
|
|
57
59
|
|
|
@@ -65,7 +67,7 @@ chi sessions list [--live] [--cwd PATH] [--limit N] [--format text|json|tsv] [--
|
|
|
65
67
|
chi sessions stop ID
|
|
66
68
|
chi sessions archive ID... # hide from every list, keep for good; unarchive ID... undoes it
|
|
67
69
|
chi sessions list --archived # archived sessions too, marked [archived]
|
|
68
|
-
chi sessions delete [--force] ID...
|
|
70
|
+
chi sessions delete [--force] [--dry-run] ID... # for good; --force stops a live worker first; --dry-run: what it would do
|
|
69
71
|
chi sessions prune [--dry-run] [--days N] [--keep N] [--keep-status running,...] [--test-only]
|
|
70
72
|
chi sessions clean [--dry-run] [--days N] [--all] # test sessions: all, or older than N days; --all: every kind, as prune
|
|
71
73
|
chi sessions stats ID [--format text|json] # cost, tokens and progress, without a model turn
|
|
@@ -110,7 +112,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
|
|
|
110
112
|
- `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.
|
|
111
113
|
- Web UI (`chi web`): the page's scope is in its URL. Started in a project (a git repository or a `chi project init` folder), `chi web` opens `/?dir=<that folder>`: that project's sessions, and new sessions start in that folder; the header chip says `<project> · all`, and `all` opens the same place as `?scope=all` (every session; a new session there starts in chi web's start folder, shown on the start page, and cards name their folder; `← <project>` goes back to the project view it came from, or to the start folder's project). A bare `/` (the LAN link, the Home Screen app) is the start folder's project too: the folder chi web runs in, or `web.start_dir` / `chi web --start-dir DIR`; outside a project (no repository or marked folder) it shows every session. A pushed notification opens its session in that session's own project (`/?dir=<its project>#/s/<id>`; `?scope=all` outside a 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, and the grip on the chat's top edge — the same thin handle as the composer's, its twin — puts them away and brings them back: a drag up (or a click, or Enter/Space on it) hides them, a drag down (or a click) shows them again, and the choice is remembered. A hidden strip leaves its status in the top bar (`N sessions · ● 1 live · ● 1 waiting`, from the cards), and a click on that pill opens All sessions, without showing the strip first; there the pill shows whatever the strip's state, pressed, and a click on it goes back to the chat (as Esc does). In a window under 900 px wide, where the strip scrolls sideways, the grip stays under it, outside the scroller; a window under 700 px tall hides the strip by itself, so a question or approval card in the stage keeps room, and the grip shows it 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; just `▸ 2 delegates` while the rows are open: they carry the marks then) 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`; its header is the top bar's right end: a search over preview, id and status, the count, an `archived` toggle and Select (on a phone a row of its own under the bar). Esc or the pressed pill returns; where the sessions are stored is a faint line under the list. A card is its title on one line (an untitled session reads `Untitled` over its first message), a line under it (its recap, else its first message) and its meta row, with one mark per state and no status dot: a waiting card has its warn outline and its `question` (or `approval`…) chip, an errored one an `error` badge, a session a worker runs the `live` badge (not on a waiting card: waiting means a worker), and idle, completed and stopped ones are unmarked; a family's and a chain's rows the same. 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` (`3 / 14` while a search narrows it), 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 session. 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's id copies the full session id on click ("Session id copied"), the id every CLI command takes (`chi --attach ID`, `chi send ID`). 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 ⚙ chip, after the model, holds the session's thinking level, reasoning history and LLM context: `⚙` alone while the session follows the model for all three, else `⚙` and what the session set, in the accent colour (`⚙ think low · ctx stale,forget`; a phone shows ⚙ with a dot; the tooltip gives each value and its source). Its panel is the start page's ⚙ panel for this session: a Thinking row (`/thinking`), on a chat host a Reasoning row (the reasoning history, `/reasoning-history`), and a Context row with its Apply and budget fields (`/llm-context`); a tap runs that row's command at once in the worker (one reply in the conversation, as a typed one) and changes that field alone, the Context row's `default` resets the strategy, apply rule and budget (`/llm-context reset`), and a tap while a turn runs is queued for after it (the panel's note says so). `GET /api/sessions/:id`'s `session.thinking`, `session.reasoning_history` (null on a native host) and `session.llm_context` carry the values (the live worker's, else resolved from the session file), and a `command_ran` that changed them carries the new ones. After ⚙, the 🧰 chip names the session's toolkit: `🧰` alone on the configured default (`toolkit.default`, `session.toolkit_default`), `🧰 lean` on another (see [Toolkits](configuration.md#toolkits); `/toolkit` changes it). A `/thinking` or `/reasoning-history` change typed in the composer that restarts the prompt cache asks first: the reply bubble has an **Apply (restarts the cache)** button that sends its `--yes` line (the ⚙ panel 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)`); after a `/model` switch the info bar's tooltip adds a `per model:` row per run of turns on one model above those totals (`splash:qwen3-35b · 6 turns · 96.0k in / 9.0k out · ~$0.02`, a switch's prefill under its row: `└ switch prefill 58.0k uncached prompt ≈$0.01`; the timing's `model_segments`, replaced by each `generation_completed`'s; the session cards stay as they were), and right after the switch its ctx % is the new model's window's; 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 session starts on, and a fresh chain link's (see [Session chains](#session-chains); there a pick shows as a `/model` command bubble in the link); 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`; `toolkits`: `{default, suggest, kits: [{name, description?}]}`, the start page's 🧰 list: the configured `toolkit.default`, `suggest` `on` only when a new session's first message may get a suggested kit (`toolkit.suggest.mode: on`, a System 1 host, two described kits; else `audit` or `off`), and the built-in and config kits a new session can start on, without `child` or `undecided`, a kit `groups:` refuses or one that doesn't resolve (a base that is a bundle kit), the default always listed; left out when it can't be read), and `POST /api/sessions` takes `model` (blank means the default). Beside it, ⚙ opens the new session's rarely used settings (thinking and LLM context, following each `GET /api/models` row's `thinking` and `llm_context`, ; see [configuration.md](configuration.md#llm-context-a-sessions-own-strategy)), and 🧰 its toolkit: **Auto** (with `toolkit.suggest.mode: on`: the first message may get a suggested kit, else the default) or a kit from the payload's `toolkits`, sent as `POST /api/sessions`'s `toolkit` (see [configuration.md](configuration.md#toolkits)); a refused kit (`400 toolkit_refused`) is said in the list, opened again. What is set shows on the row as an accent chip (`think high`, `tools: lean`; a dot on ⚙ or 🧰 on a phone); each is for the next new session only, never remembered. 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).
|
|
112
114
|
- 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).
|
|
113
|
-
- 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 `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `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), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `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), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height (on a phone no row: the line lies over the session bar's left while a turn runs and you type or have a choice armed): the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `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), `stage_view.js` (the stage view: the running turn pinned above the composer, with Stop turn in its status row while it runs, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model, three groups with hairlines between them, on one line above a phone's width (the folder gives way first): the setup (id, status, model, the ⚙ and 🧰 chips, notes, the memory or working-set chip), the relations (chain links, the parent as `↑ <id>`, delegates, participants; only when there is one) and the telemetry (folder, ctx, speed, the session's time, worker badge)), `settings_chip.js` (the session bar's ⚙ chip and its panel over `settings_panel.js`: a tap runs that row's command, one field), `toolkit_chip.js` (the session bar's 🧰 chip: the kit against `toolkit.default`), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts (the restarting set is `version_notices.js`'s) as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `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`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails
|
|
115
|
+
- 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 `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `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), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `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), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height (on a phone no row: the line lies over the session bar's left while a turn runs and you type or have a choice armed): the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `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), `stage_view.js` (the stage view: the running turn pinned above the composer, with Stop turn in its status row while it runs, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model, three groups with hairlines between them, on one line above a phone's width (the folder gives way first): the setup (id, status, model, the ⚙ and 🧰 chips, notes, the memory or working-set chip), the relations (chain links, the parent as `↑ <id>`, delegates, participants; only when there is one) and the telemetry (folder, ctx, speed, the session's time, worker badge)), `settings_chip.js` (the session bar's ⚙ chip and its panel over `settings_panel.js`: a tap runs that row's command, one field), `toolkit_chip.js` (the session bar's 🧰 chip: the kit against `toolkit.default`), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts (the restarting set is `version_notices.js`'s) as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `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`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails; a click on one opens it in `picture_viewer.js`), `composer_grip.js` (the composer's grip and fold: the drag, tap and keys, the fold per visit), `composer_mount.js` (the composer mounted on a page's markup: the message box and its height, the image chips from a paste, a drop or the image button, the grip and fold, ↑/↓ over the prompt history and the keys; the page's own parts come in as hooks: what Enter and Send do, keys taken first, Esc, where the history comes from, the info bar's drop while folded, typing anywhere to open it; its styles, the card it sits in (`.composer-card`, its footer and its line above the text field) included, are the shared `composer.css`, linked after `tokens.css` by `index.html`), `strip_grip.js` (the latest-sessions strip's grip, the composer grip's twin: hides and shows the strip), `strip_hidden.js` (the strip hidden or shown: the saved choice, the short window's own hide, the grip and the body's class), `storage.js` (the page's per-browser choices in localStorage, guarded: a choice that can't be read or written is not remembered), `unqueue.js` (the × on a message queued for after the turn: takes it back, its text into an empty composer or a toast), `toasts.js` (the page's toast stack: a timer each, sticky ones until acted on, the same text reusing its item), `toast_place.js` (where the toast sits: above the composer card, the stage and an open model panel), `dock_reserve.js` (what floats over the history: the history's bottom reserve (`--dock-h`) at the composer card's and the showing stage's height, a reader at the end kept there, and the toast's place measured for `toast_place.js`), `notice_links.js` (a hook notice line's http(s) URLs as links), `start_page.js` (the start page's model picker, its ⚙ panel's and 🧰 list's choices for the next new session only and their override chips; a fresh chain link's picker and its `/model`), `start_settings.js` (the start page's ⚙ panel: thinking and LLM context as rows of segments, applied at once, the Apply and budget disclosure; the override chips' words and ⚙'s dot), `settings_panel.js` (the panel's rows as lit-html templates, shared: the segments, the disclosure, a hidden row's sent-anyway line; the caller passes its rows and applies the picks), `start_toolkit.js` (the start page's 🧰 list: Auto with suggest on, the kits, the default marked; a pick closes it; its override chip and dot), `session_actions.js` (Continue, Archive and its Undo, Delete and Stop, and the start page when the open session is gone), `send_turn.js` (the composer's send: a new session first on the start page, the route, the echo, the image upload, the `/turn` ack, a fast failure's restore and each error's place). Unit-tested via `npm test` (`spec/web/public/*.test.js`).
|
|
114
116
|
- 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).
|
|
115
117
|
- The web session page's message box folds away for room to read. Drag the grip on its top edge (the pill that shows on hover; always on a phone) down, past the box by 32 px: the pill turns accent while releasing would hide it, and on release the box folds and the info bar stays as the page's bottom edge. The grip stays as a handle on the info bar's top edge, drawn always: pull it up (8 px opens it, and the box follows the pointer in the same gesture), click or tap it (opens it and focuses the box), or just type on the page (the key lands in the box) to bring it back; Enter or Space on the focused grip folds or opens too. A draft (text or images, which folding never clears) colours the handle with the accent, a session waiting on you with the attention colour; its tooltip says so. Stop turn isn't the message box's: it sits in the running turn's stage, at the right edge of its status row beside the fold caret (collapsed stage or not), while the turn runs, and goes when the turn ends A turn the page knows runs but has nothing of to draw (a reload whose session payload carries no current turn) shows that status row alone, `running` and Stop turn. The fold is each session's own, remembered per browser (`chi_composer_collapsed:<session>`: folding one session's box leaves the others' as they were), an archived session opens folded for the visit, and opening it there, like the page opening it itself (a restored line, a quote, continue →'s opener), is for that visit only. The fold keeps the height the grip set, also the session's own (`chi_composer_floor:<session>`; the start page's lasts until a reload): the box opens again at the height it had, and only a double-click on the grip forgets it. That height never takes more than half of the window the box is drawn in: a floor saved in a bigger window is held to that half in a smaller one (a rotated phone, a resized window, another device on the same origin), and the saved floor itself stays, so the height comes back when the room does. A click on the expanded grip hides the box as well: it folds 250 ms after the press, so a second click inside that window is read as a double-click and resets the height instead (a drag, Enter or Space act at once, and a drag after a click takes the wait back). The start page's grip only resizes.
|
|
116
118
|
|
|
@@ -392,7 +394,8 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
|
|
|
392
394
|
- **The page:** the info bar's `continue →` continues the open session (`continues: <id>, idle: true`; it reads `continuing…` through the recap wait) and opens the new link with an opener in the composer, not sent (a draft written in this session stays instead; one carried over from another session or the start page gives way to the opener, and the toast's **Restore draft** brings it back): the previous link's own first typed message when that link continues one (the 201's `opener`; a `!shell` line isn't taken), else `Continue where we left off.`. So whatever you sent on the last link comes back on the next one, and editing it once changes it for every later link; the previous link is archived, a toast says so (`Continued 3fa2c1d0 in 4b7e9a01; 3fa2c1d0 is archived; 1 open delegate moved`), and a moved delegate's card folds under the new link. When the previous link's model's host is gone the link starts on the default model and the toast carries the server's `model_warning` too, and then stays until closed. A fresh link (one with no turn yet, however it was made: `continue →`, `chi send --new --continues`, a reload) shows the model picker in its composer with the link's model, until its first turn starts (a failed or canceled first turn ends it too); a pick runs `/model <name>` in the link (a command bubble; the info bar follows) and changes neither the start page's remembered model nor its Recent list, and a Send right after it waits for the `/model` to be taken. A link a one-turn `chi --non-interactive` run has, or one continued already, shows none. A link continued already has no `continue →`: its `→` link goes to the next link (a stale page's continue answered 409 `continued` opens `next_id`). A continue refused for open delegates that can't move shows a toast that names each one (its preview and what the server says to do: `older chi worker 0.46.1; restart it`, `in use by a one-turn chi --non-interactive run or an older chi's terminal; let it finish`), each a link to its page; any other refusal shows the server's words. The info bar of a link carries `← 2026-10-08` (the previous link's day) and, on an earlier link, `2026-10-10 →`, each a link with its id, its full start (`2026-10-10 14:32`) and its preview in the tooltip; a neighbour that started on the open link's own day shows its time instead (`← 09:12`, `14:32 →`). A link made by `continue →` inherits the previous link's preview (and its title, if it has one) when it is created, so its card keeps its chain's title whatever opener it is sent, and its top bar and browser tab show its card's title. A link with a recap of its own reads its auto title, else its recap's first sentence, instead (a link without one reads its chain's name, and a first link's recap names its chain). A link whose title is the opener and nothing else (a `chi send --new --continues` link whose first message is `Continue where we left off.`) shows its chain's first link's title instead, on its card, in the popover and in its info bar's title line, display only (its messages and data keep the opener; its own title when the first link is gone). The lists fold a chain into the card of its latest listed link, whatever the earlier links' archived state (typing in an archived link brings it back, folded there still), their delegates with them: the card's `↩ #N` chip (`#N of M` when later links aren't listed; its tooltip `Session chain: link N of M`) opens a popover of the other links, newest first (`#N`, its date, with its time (`2026-10-17 14:32`) when another link of the chain started the same day, its own title when it differs from the card's (a link inherits its chain's, so mostly it doesn't), else its recap's first sentence, else its preview, `archived`), a click opens one; the chip shows a live dot or `waiting` for a link that has a worker or waits on the user, and a waiting link puts its chain's card first. All sessions folds nothing while a search is typed or the `archived` toggle is on: every link is a card of its own then, its chip `#N of M`, with its own delegates folded in, so a search finds an earlier link and its delegates.
|
|
393
395
|
- **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
|
|
394
396
|
- **Which link:** an id, a unique prefix, or `last:<id or prefix>`, the latest link of the chain that session is in. It walks the links that still exist: a deleted link in the middle (`chi sessions delete`, the retention sweep of an unarchived one) ends the walk before it, so `last:` of an earlier link then names that earlier link, and continuing it starts a second line beside the links after the gap; name a link after the gap instead. A trigger names the chain this way: a person's message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain; an unattended sender's is refused (*Who may wake a session*). That is the rule: `chi send` and a note go to the chain's newest link (*Sending a message*, *Context notes*); the web composer, a participant's turn and `delegate(session:)` go to the link they name. One walker answers every one of these (`SessionChain::Links`: one session listing, archive flags read once; the earliest created successor wins a fork a hand edit made, a loop ends where it would repeat), with two rules on it, not unified on purpose: `last:` and a schedule take the chain's **end** (`Links#latest`: a continue refuses a link continued already, and a schedule never un-archives a chain you retired), `chi send` and a note the **first link not archived** (`Links#first_live`: a person's input goes where the chain is live, and brings back an archived end). A chain pruned by a schedule keeps its `anchor`: the kept window's oldest link still names a link that is gone, so the walk simply stops there; the page's chip counts from the surviving root (pruning renumbers the links) and its popover says `earlier links pruned` where the walk stops, rather than linking to a deleted session.
|
|
395
|
-
- **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `
|
|
397
|
+
- **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionManager::DELEGATES` (`SessionManager::DelegateRule`; one shared preview row snapshot): a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is a link with nothing to undo: its delegates follow the same rule (*Deleting a session*). **The web asks first**: chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store) for any session, `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). A session in no chain answers `{chained: false, session_id, link}`, the same `link` a chained one gets (`previous_id` null, `earlier`/`later` 0, `next_id` null); an older page reads only `chained`. Each choice (`link`, `chain`) also carries `delegates` (`{delete: [ids], leave: [{id, running}]}`; `running` false for a stopped session left under a running delegate, beside the counts `deletes` and `left_running`), `tasks` (`{running, unverified, unreadable}`: `RunningTasks.of` the ids the choice deletes) and `worker` (a link's: `"turn"` when a worker owns it and a turn runs, `"idle"` when a worker owns it or is starting, null; a chain's `{idle, turn}` counts over its links). No titles: the page names each id from its own list. One shared session-row snapshot serves the link and chain choices; Links lists on its own, and a folder whose session file is gone answers too (the delete still takes it). Each call read-only checks each link's continue lock (a session in no chain too), and writes nothing else but the listing's own repair of an interrupted continue; an unknown id is the usual 404. chi web lists `delete_plan_all` in `/api/info`'s features (`Web::App::DELETE_PLAN_FEATURE`). **The tap stops only what the sheet named**: today the page sends only `stop_tasks=true`; it does not send `tasks=<id,id>` yet. The server accepts `tasks` only as a list of task/session ids to stop: for delete it accepts the query parameter `tasks=<id,id>`, and for archive it accepts `"tasks": [ids]` in the body. In both routes `tasks` works only with `stop_tasks` (`true`/`stop_tasks=true`); without `stop_tasks` it is ignored. `stop_tasks` without `tasks` takes every running task the operation can stop. Today a plain tap uses `stop_tasks` without `tasks`, so it stops whatever runs; the delete sheet's page phase that carries named ids will send `tasks=<id,id>` for the choice's running ids (and `tasks=` when it has only unverified or unreadable records, which a stop never signals). A chain stops link by link: a link refused that way leaves it and the earlier links whole. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself. Each choice carries a `digest` (`SessionChain::Delete.digest`: the sorted ids it deletes, leaves, revives and moves back); the sheet's DELETE sends it as `expect=`, and the delete compares it with the plan it runs (a link's under its holds, as `delete_link` starts; the chain's before its checks) and refuses `plan_changed` (409) before anything changes; a session in no chain is compared the same way (a sheet shown for a link whose chain is gone since deletes when its ids still match). Without `expect` (the CLI, an older page) it deletes as it plans then.
|
|
398
|
+
**The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
|
|
396
399
|
|
|
397
400
|
## Schedules
|
|
398
401
|
|
data/docs/testing.md
CHANGED
|
@@ -124,7 +124,7 @@ its case.
|
|
|
124
124
|
The web specs run in plain node. One that loads lit-html, itself or through a module it imports (`turn_block.js`,
|
|
125
125
|
`turn_html.js`, `card.js`, `copy.js`, `images.js`, `scope.js`, `command_view.js`, `diff_view.js`, `read_view.js`,
|
|
126
126
|
`question_cards.js`, `stream_handlers.js`, `stage_view.js`, `bubbles.js`, `cards_place.js`, the chips, `info_bar.js`, `info_bar_model.js`, `lists_view.js`, `context_chips.js`, `families_view.js`,
|
|
127
|
-
`chains.js`, `working_set_view.js`, `working_set_rail.js`, `unqueue.js`, `toasts.js`, `notice_links.js`, `start_page.js`, `start_settings.js`, `settings_panel.js`, `start_toolkit.js`, `session_actions.js`, `send_turn.js`, `composer_mount.js`, `dock_reserve.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`,
|
|
127
|
+
`chains.js`, `working_set_view.js`, `working_set_rail.js`, `ws_markdown.js`, `unqueue.js`, `toasts.js`, `notice_links.js`, `start_page.js`, `start_settings.js`, `settings_panel.js`, `start_toolkit.js`, `session_actions.js`, `send_turn.js`, `composer_mount.js`, `dock_reserve.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`,
|
|
128
128
|
`vendor/lit-html.js`) needs a DOM: `import "./dom_shim.js";` as its first import (happy-dom, a devDependency only,
|
|
129
129
|
never shipped; lit reads `document` as it loads). The shim's `markupOf(template)`,
|
|
130
130
|
`htmlOf(nodes)` and `canon(html)` compare markup without lit's marker comments; the DOM writes text with only `&`, `<`, `>`
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require_relative "block_fix/stamp"
|
|
3
4
|
require_relative "log"
|
|
4
5
|
|
|
5
6
|
module Samagotchi
|
|
@@ -25,8 +26,8 @@ module Samagotchi
|
|
|
25
26
|
# The same object when it has none.
|
|
26
27
|
# An empty-answer note's marker (TurnNote::EMPTY_ANSWER) and the
|
|
27
28
|
# 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
|
+
# they go the same way, and so does a block fix's stamp (BlockFix::STAMP).
|
|
30
|
+
DISPLAY_ONLY = [KEY.to_s, "empty_answer", "display_refs", BlockFix::STAMP.to_s].freeze
|
|
30
31
|
|
|
31
32
|
def self.strip(message)
|
|
32
33
|
return message unless message.is_a?(Hash) && DISPLAY_ONLY.any? { |key| message.key?(key.to_sym) || message.key?(key) }
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "time"
|
|
4
|
+
|
|
5
|
+
module Samagotchi
|
|
6
|
+
# BlockFix's stamp on an answer's model message, apart from the rest so the
|
|
7
|
+
# loops' allowlists (ChatLoop#plain, KernelLoop#sanitize_history) and
|
|
8
|
+
# AnswerDisplay can name it without loading the request's side.
|
|
9
|
+
module BlockFix
|
|
10
|
+
# The answer message's display-only key (AnswerDisplay::DISPLAY_ONLY):
|
|
11
|
+
# a list of {key:, fixed_key:, state:, reason:, at:}, one per block asked.
|
|
12
|
+
STAMP = :block_fixes
|
|
13
|
+
STATES = %w[fixed failed].freeze
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
# The answer message's stamp entries, with symbol keys (they come back
|
|
18
|
+
# from disk with string keys).
|
|
19
|
+
# @return [Array<Hash>]
|
|
20
|
+
def stamps(message)
|
|
21
|
+
return [] unless message.is_a?(Hash)
|
|
22
|
+
|
|
23
|
+
list = message[STAMP] || message[STAMP.to_s]
|
|
24
|
+
Array(list).filter_map do |entry|
|
|
25
|
+
next unless entry.is_a?(Hash)
|
|
26
|
+
|
|
27
|
+
entry.to_h { |k, v| [k.to_sym, v] }
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# The stamp entry that knows the block +key+ (by its key or its fixed
|
|
32
|
+
# key), nil when none does.
|
|
33
|
+
def stamp_for(message, key)
|
|
34
|
+
stamps(message).find { |entry| entry[:key] == key || entry[:fixed_key] == key }
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# A copy of +message+ with +entry+ added to a fresh stamp list.
|
|
38
|
+
def with_stamp(message, entry)
|
|
39
|
+
list = stamps(message).reject { |old| old[:key] == entry[:key] } + [entry]
|
|
40
|
+
copy = message.reject { |k, _| k.to_s == STAMP.to_s }
|
|
41
|
+
copy.merge(STAMP => list)
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# One stamp entry.
|
|
45
|
+
def entry(key:, state:, fixed_key: nil, reason: nil, at: Time.now)
|
|
46
|
+
{ key: key, fixed_key: fixed_key, state: state, reason: reason, at: at.utc.iso8601 }.compact
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "time"
|
|
5
|
+
require_relative "block_fix/stamp"
|
|
6
|
+
require_relative "block_renderers"
|
|
7
|
+
require_relative "inline_widgets"
|
|
8
|
+
require_relative "markdown_parser"
|
|
9
|
+
require_relative "plugin/side_question"
|
|
10
|
+
|
|
11
|
+
module Samagotchi
|
|
12
|
+
# A fenced block the page couldn't draw in the newest answer, asked for
|
|
13
|
+
# again once (docs/internals/block-renderers.md, A failed block is asked
|
|
14
|
+
# for again): where the block is in an answer's markdown, the side request
|
|
15
|
+
# that asks for it again, and the checks on what came back. Pure Ruby: the
|
|
16
|
+
# Engine's BlockFixPart runs the request and writes the conversation.
|
|
17
|
+
module BlockFix
|
|
18
|
+
# The side line's kind (SideUsage) and the asking source.
|
|
19
|
+
SOURCE = "block-fix"
|
|
20
|
+
# The Bridge feature (Bridge::FEATURES) a page checks before it asks.
|
|
21
|
+
FEATURE = "block_fix"
|
|
22
|
+
# IdleClient may retry a refused thinking setting: up to three requests.
|
|
23
|
+
TIMEOUT_SECONDS = 25
|
|
24
|
+
MAX_TOKENS = 6000
|
|
25
|
+
MAX_SOURCE_BYTES = 16 * 1024
|
|
26
|
+
# How much of the drawer's error goes into the request (model-influenced
|
|
27
|
+
# text, in the user part only).
|
|
28
|
+
MAX_REASON_CHARS = 300
|
|
29
|
+
# Asks in flight per Engine at once.
|
|
30
|
+
MAX_RUNNING = 2
|
|
31
|
+
# Blocks asked for per answer, ever (its stamp and its asks in flight).
|
|
32
|
+
PER_ANSWER = 2
|
|
33
|
+
|
|
34
|
+
# The route's refusals (one message per condition), by reason code.
|
|
35
|
+
REFUSALS = {
|
|
36
|
+
block_too_large: "the block is over #{MAX_SOURCE_BYTES / 1024} KB",
|
|
37
|
+
block_not_found: "that block isn't in the turn's answer",
|
|
38
|
+
fix_busy: "#{MAX_RUNNING} fixes are being asked for already",
|
|
39
|
+
fix_limit: "#{PER_ANSWER} blocks of this answer were asked for already",
|
|
40
|
+
fix_unavailable: "this session can't ask for a fix"
|
|
41
|
+
}.freeze
|
|
42
|
+
|
|
43
|
+
SYSTEM = "The last answer in the conversation below holds a fenced block a program could not draw. Answer " \
|
|
44
|
+
"with the corrected block only, in one fence of the same language, and nothing else. Keep what it " \
|
|
45
|
+
"shows and every id, label, option and text it has, unless the error requires a change."
|
|
46
|
+
|
|
47
|
+
# Where a block is in an answer's text: the body's lines (0-based, both
|
|
48
|
+
# ends inclusive; +last+ is first - 1 for an empty body) and the indent
|
|
49
|
+
# its lines have there (a list item's).
|
|
50
|
+
Place = Data.define(:first, :last, :indent)
|
|
51
|
+
|
|
52
|
+
# What #extract read from the model's answer: the fixed source, or why
|
|
53
|
+
# it is refused.
|
|
54
|
+
Extracted = Data.define(:source, :refusal) do
|
|
55
|
+
def ok? = refusal.nil?
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
module_function
|
|
59
|
+
|
|
60
|
+
# The block's identity: the first 32 hex characters of SHA-256 over the
|
|
61
|
+
# language and the normalised source.
|
|
62
|
+
def key(lang, source)
|
|
63
|
+
Digest::SHA256.hexdigest("#{lang}\0#{normalize(source)}")[0, 32]
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# +source+ with \r\n and \r as \n and one trailing newline removed.
|
|
67
|
+
def normalize(source)
|
|
68
|
+
source.to_s.gsub(/\r\n?/, "\n").delete_suffix("\n")
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Whether #locate can parse (commonmarker is installed).
|
|
72
|
+
def available? = MarkdownParser.available?
|
|
73
|
+
|
|
74
|
+
# The first code block of +text+ in +lang+ whose source is +source+, as
|
|
75
|
+
# commonmarker (the page's render's parser) reads it; nil when there is
|
|
76
|
+
# none, or it sits in a blockquote (its lines carry "> ").
|
|
77
|
+
# @return [Place, nil]
|
|
78
|
+
def locate(text, lang:, source:) = locate_all(text, lang: lang, source: source).first
|
|
79
|
+
|
|
80
|
+
# Every such block of +text+, in order (an answer may repeat one: a fix
|
|
81
|
+
# patches every copy, so none is asked for again).
|
|
82
|
+
# @return [Array<Place>]
|
|
83
|
+
def locate_all(text, lang:, source:)
|
|
84
|
+
return [] unless available?
|
|
85
|
+
|
|
86
|
+
text = text.to_s
|
|
87
|
+
want = normalize(source)
|
|
88
|
+
lines = text.lines
|
|
89
|
+
places = []
|
|
90
|
+
each_code_block(text) do |node|
|
|
91
|
+
next unless language_of(node.fence_info) == lang.to_s && normalize(node.string_content) == want
|
|
92
|
+
next if in_blockquote?(node)
|
|
93
|
+
|
|
94
|
+
place = place_of(node, lines)
|
|
95
|
+
places << place if place
|
|
96
|
+
end
|
|
97
|
+
places
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# +text+ with every block at +places+ holding +fixed+ (#replace from
|
|
101
|
+
# the last, so the earlier places' lines stay where they were).
|
|
102
|
+
def replace_all(text, places, fixed)
|
|
103
|
+
places.sort_by(&:first).reverse.reduce(text.to_s) { |out, place| replace(out, place, fixed) }
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# +text+ with the block at +place+ holding +fixed+: the fence lines kept,
|
|
107
|
+
# each new line given the old body's indent, the text's own line ends.
|
|
108
|
+
def replace(text, place, fixed)
|
|
109
|
+
lines = text.to_s.lines
|
|
110
|
+
eol = text.to_s.include?("\r\n") ? "\r\n" : "\n"
|
|
111
|
+
body = normalize(fixed).split("\n", -1).map { |line| line.empty? ? eol : "#{place.indent}#{line}#{eol}" }
|
|
112
|
+
before = lines[0...place.first]
|
|
113
|
+
# A body at the very end without a line end (an unclosed fence) keeps none.
|
|
114
|
+
after = lines[(place.last + 1)..] || []
|
|
115
|
+
body[-1] = body[-1].delete_suffix(eol) if after.empty? && !lines.last.to_s.end_with?("\n") && body.any?
|
|
116
|
+
(before + body + after).join
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# What Engine#ask_side_model takes: the conversation up to and including
|
|
120
|
+
# the answer as a transcript, then the failed block and its error.
|
|
121
|
+
# @param messages [Array<Hash>] the conversation, display-only keys gone
|
|
122
|
+
# @return [Array<Hash>]
|
|
123
|
+
def request(messages:, lang:, source:, reason:)
|
|
124
|
+
system = lang.to_s == InlineWidgets::LANG ? "#{SYSTEM}\n\n#{InlineWidgets::FIX_RULES}" : SYSTEM
|
|
125
|
+
Plugin::SideQuestion.request(messages: messages, prompt: prompt(lang, source, reason), system: system)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# The question: the language, the error and the block.
|
|
129
|
+
def prompt(lang, source, reason)
|
|
130
|
+
body = normalize(source)
|
|
131
|
+
fence = "`" * [3, (body.scan(/`+/).map(&:length).max || 0) + 1].max
|
|
132
|
+
error = reason.to_s.strip[0, MAX_REASON_CHARS]
|
|
133
|
+
"The #{lang} block below, from your last answer, could not be drawn.\nError: #{error}\n\n" \
|
|
134
|
+
"#{fence}#{lang}\n#{body}\n#{fence}\n\nAnswer with the corrected block only, in one #{lang} fence."
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# The fixed source in the model's +text+: the first fenced block, else
|
|
138
|
+
# the whole answer when it has no fence.
|
|
139
|
+
# @param cut_off [Boolean] the answer stopped at its token limit
|
|
140
|
+
# @param failed [String] the source that failed
|
|
141
|
+
# @return [Extracted]
|
|
142
|
+
def extract(text, cut_off:, failed:)
|
|
143
|
+
return Extracted.new(source: nil, refusal: "the fix was cut off") if cut_off
|
|
144
|
+
|
|
145
|
+
source = normalize(first_fence(text.to_s) || text.to_s.strip)
|
|
146
|
+
return Extracted.new(source: nil, refusal: "the fix was empty") if source.strip.empty?
|
|
147
|
+
return Extracted.new(source: nil, refusal: "the fix was the same block") if source == normalize(failed)
|
|
148
|
+
if source.bytesize > MAX_SOURCE_BYTES
|
|
149
|
+
return Extracted.new(source: nil, refusal: "the fix is over #{MAX_SOURCE_BYTES / 1024} KB")
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
Extracted.new(source: source, refusal: nil)
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# nil when +source+ may be tried, else the reason: a chi-ui block must
|
|
156
|
+
# parse; any other language passes (only the page can draw it).
|
|
157
|
+
def check(lang:, source:)
|
|
158
|
+
return nil unless lang.to_s == InlineWidgets::LANG
|
|
159
|
+
|
|
160
|
+
InlineWidgets.parse(source).error
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def each_code_block(text, &)
|
|
164
|
+
return unless text.include?("```") || text.include?("~~~")
|
|
165
|
+
|
|
166
|
+
nodes = []
|
|
167
|
+
Commonmarker.parse(text, options: { extension: { header_ids: nil } }).walk do |node|
|
|
168
|
+
nodes << node if node.type == :code_block
|
|
169
|
+
end
|
|
170
|
+
nodes.each(&)
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def language_of(info)
|
|
174
|
+
word = info.to_s.split.first.to_s.downcase
|
|
175
|
+
word if word.match?(BlockRenderers::LANG)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def in_blockquote?(node)
|
|
179
|
+
parent = node.parent
|
|
180
|
+
while parent
|
|
181
|
+
return true if parent.type == :block_quote
|
|
182
|
+
|
|
183
|
+
parent = parent.parent
|
|
184
|
+
end
|
|
185
|
+
false
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# The body's line range and indent from the node's source position; nil
|
|
189
|
+
# for an indented code block (no fence line).
|
|
190
|
+
def place_of(node, lines)
|
|
191
|
+
pos = node.source_position
|
|
192
|
+
start = pos[:start_line] - 1
|
|
193
|
+
fence_line = lines[start].to_s
|
|
194
|
+
column = pos[:start_column] - 1
|
|
195
|
+
fence = fence_line[column..].to_s[/\A(`{3,}|~{3,})/]
|
|
196
|
+
return nil unless fence
|
|
197
|
+
|
|
198
|
+
prefix = fence_line[0, column]
|
|
199
|
+
indent = prefix.match?(/\A[ \t]*\z/) ? prefix : " " * prefix.length
|
|
200
|
+
last = pos[:end_line] - 1
|
|
201
|
+
last -= 1 if last > start && closing?(lines[last].to_s, fence)
|
|
202
|
+
Place.new(first: start + 1, last: last, indent: indent)
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def closing?(line, fence)
|
|
206
|
+
mark = line.strip[/\A(`{3,}|~{3,})\z/]
|
|
207
|
+
!mark.nil? && mark[0] == fence[0] && mark.length >= fence.length
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
def first_fence(text)
|
|
211
|
+
return nil unless available?
|
|
212
|
+
|
|
213
|
+
lines = text.lines
|
|
214
|
+
each_code_block(text) do |node|
|
|
215
|
+
return node.string_content if place_of(node, lines)
|
|
216
|
+
end
|
|
217
|
+
nil
|
|
218
|
+
end
|
|
219
|
+
end
|
|
220
|
+
end
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../block_fix"
|
|
4
|
+
require_relative "../block_renderers"
|
|
5
|
+
|
|
6
|
+
module Samagotchi
|
|
7
|
+
class Bridge
|
|
8
|
+
# POST /session/:id/blocks/fix {turn_id, lang, source, reason}: a block
|
|
9
|
+
# the page couldn't draw in the newest answer, asked for again once
|
|
10
|
+
# (Engine#fix_block; docs/internals/block-renderers.md, A failed block is
|
|
11
|
+
# asked for again). Mixed into Bridge (#parse_json, #fetched, @engine).
|
|
12
|
+
module BlockFixRoute
|
|
13
|
+
# 400 missing_fields without a turn id, a language a fence can name or
|
|
14
|
+
# a source; else Engine#fix_block's status and body.
|
|
15
|
+
# @return [Array(Hash, Integer, Hash)]
|
|
16
|
+
def handle_block_fix(_session_id, body)
|
|
17
|
+
parsed = parse_json(body)
|
|
18
|
+
return [{ "Allow" => "POST" }, 400, { error: "invalid_json" }] unless parsed.is_a?(Hash)
|
|
19
|
+
|
|
20
|
+
turn_id, lang, source, reason = %w[turn_id lang source reason].map { |key| fetched(parsed, key) }
|
|
21
|
+
unless [turn_id, lang, source].all? { |v| v.is_a?(String) && !v.empty? } && lang.match?(BlockRenderers::LANG)
|
|
22
|
+
return [{ "Allow" => "POST" }, 400, { error: "missing_fields", detail: "turn_id, lang and source required" }]
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
status, answer = @engine.fix_block(turn_id: turn_id, lang: lang, source: source, reason: reason.to_s)
|
|
26
|
+
[{}, status, answer]
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|
|
@@ -104,6 +104,25 @@ module Samagotchi
|
|
|
104
104
|
Log.warn(:bridge, "turn_drawing_failed", error: "#{e.class}: #{e.message}")
|
|
105
105
|
end
|
|
106
106
|
|
|
107
|
+
# An observer of the Engine's events: a block fix that patched an
|
|
108
|
+
# answer's text (:block_fix, landed "answer") changes the digest its
|
|
109
|
+
# turn's line ends on, so that line is written again with the new end
|
|
110
|
+
# digest, only when it ended on the answer as it was (+was_digest+).
|
|
111
|
+
# A fix in the display only keeps the digest. Never raises.
|
|
112
|
+
def call(event)
|
|
113
|
+
return unless @path && event[:type] == :block_fix && event[:landed] == "answer"
|
|
114
|
+
|
|
115
|
+
id = event[:turn_id].to_s
|
|
116
|
+
line = [@last].compact.find { |l| l.turn_id == id } || self.class.read(File.dirname(@path)).reverse_each.find { |l| l.turn_id == id }
|
|
117
|
+
return unless line && line.to_digest == event[:was_digest]
|
|
118
|
+
|
|
119
|
+
restamped = line.with(to_digest: event[:digest], from_digest: line.from == line.to - 1 ? event[:digest] : line.from_digest)
|
|
120
|
+
write(restamped)
|
|
121
|
+
@last = restamped
|
|
122
|
+
rescue StandardError => e
|
|
123
|
+
Log.warn(:bridge, "turn_drawing_restamp_failed", error: "#{e.class}: #{e.message}")
|
|
124
|
+
end
|
|
125
|
+
|
|
107
126
|
def line_for(turn, end_event)
|
|
108
127
|
from = end_event[:kept_from]
|
|
109
128
|
to = end_event[:kept_to]
|