samagotchi 0.163.0 → 0.164.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +26 -1
  3. data/docs/architecture.md +1 -1
  4. data/docs/bundles.md +4 -2
  5. data/docs/cli.md +6 -1
  6. data/docs/internals/block-renderers.md +3 -1
  7. data/docs/internals/inline-widgets.md +5 -2
  8. data/docs/internals/remote-sessions.md +7 -2
  9. data/docs/sessions.md +3 -2
  10. data/docs/sub-agent.md +11 -0
  11. data/lib/samagotchi/block_renderers.rb +14 -4
  12. data/lib/samagotchi/bundles/inline-widgets/manifest.yml +2 -2
  13. data/lib/samagotchi/bundles/inline-widgets/plugin.rb +8 -4
  14. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  15. data/lib/samagotchi/cli/parent_wait.rb +5 -1
  16. data/lib/samagotchi/continue_intent.rb +48 -0
  17. data/lib/samagotchi/message_parts.rb +13 -0
  18. data/lib/samagotchi/note_command.rb +3 -6
  19. data/lib/samagotchi/parent_report.rb +3 -2
  20. data/lib/samagotchi/send_command/parent_gate.rb +8 -5
  21. data/lib/samagotchi/send_command.rb +139 -34
  22. data/lib/samagotchi/session_access/local.rb +6 -0
  23. data/lib/samagotchi/session_access/remote.rb +25 -0
  24. data/lib/samagotchi/session_continue.rb +5 -3
  25. data/lib/samagotchi/session_inbox_delivery.rb +54 -7
  26. data/lib/samagotchi/session_manager/delivery.rb +3 -1
  27. data/lib/samagotchi/version.rb +1 -1
  28. data/lib/samagotchi/web/message_display.rb +1 -9
  29. data/lib/samagotchi/web/public/apple-touch-icon.png +0 -0
  30. data/lib/samagotchi/web/public/favicon.svg +1 -1
  31. data/lib/samagotchi/web/public/icons/chi-180.png +0 -0
  32. data/lib/samagotchi/web/public/icons/chi-192.png +0 -0
  33. data/lib/samagotchi/web/public/icons/chi-512.png +0 -0
  34. data/lib/samagotchi/web/public/inline_widgets.js +4 -1
  35. data/lib/samagotchi/web/public/widget_walk.js +14 -4
  36. data/lib/samagotchi/web/session_access_routes.rb +8 -1
  37. metadata +2 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3d57e659db748e1c159bf12ee6bea47b2d0f15b23385ceeb52f7e97b74e15f10
4
- data.tar.gz: 68c4953fa92ad429a13b88ca27c88cd11cb4824199fbcbd5a41000e962618617
3
+ metadata.gz: d42e49a40293f88111644ce49d52c31c8d89d91e80ccee15e152725f174e010c
4
+ data.tar.gz: d4d795969b1c26ea0322607c990e554561e664d77ba6e25ddff9acae164fbb03
5
5
  SHA512:
6
- metadata.gz: 05d62b9520edc30b4171a2a04efb337750d28ad12ea3e596d14a010604f06a4e2762a7e29b223fcefefbe9bf27247984affa5734c83792adf140c4ff34a598ae
7
- data.tar.gz: 458cacd81cf57afcd8efd6be0115220bba4b5fd1183f3de39b23a5b5671740a0cadc17971f66994aa92a6e9ff1c1a4abfdb221fa746c4e38d6beb2a34c6a7a44
6
+ metadata.gz: d6751aa682714571296f5aba3b6f2878a8138796d9f6df35bb1bbdc54fff10497a50727ac7d1eeee05e89dc43abd27b3c5b005c0db4d2e417da0b9af53cc1d13
7
+ data.tar.gz: 57b54bf2f8e02e08248da5742c584fd922e30ad3aedbb8e53fa7b45c84e95e818d73e388b479922c611daf19cab9cd217402c4a72ac11c3ef223ad83ceae2047
data/CHANGELOG.md CHANGED
@@ -8,6 +8,30 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.164.0] - 2026-11-10
12
+
13
+ ### Changed
14
+
15
+ - `chi send` to a session that was continued goes to the newest link of its chain, as `chi note` does, and the old
16
+ link stays archived (it used to come back beside the new one): `3f9a1c2e → 7b2d41aa (continued) sent`. So a
17
+ chain's first id keeps working as its address. `--wait --format json` reports the link it waited on as `session_id`
18
+ and the id you gave as `asked`. A send while the continue is still running waits a moment for the new link. With
19
+ `--remote`, the other machine's chi web needs this release too; an older one sends to the id named, as before.
20
+ - chi web has a new icon: a white brushed χ on the same dark tile (tab, Home Screen app, notifications). An iOS
21
+ Home Screen app keeps the old icon until you remove it and add it again.
22
+
23
+ ### Fixed
24
+
25
+ - A review session (`chi review`) no longer teaches the model the `chi-ui` picks and walk widgets: its participants'
26
+ page doesn't draw them, so they read raw YAML. The owner's working sessions, paired ones too, keep them.
27
+ (inline-widgets 0.1.1)
28
+ - chi web behind an auth proxy: when the proxy answered the widgets' stylesheet with its login page, `chi-ui` widgets
29
+ stayed unstyled until a reload; the next widget drawn now fetches the stylesheet again.
30
+ - chi web: a `chi-ui` walk step whose only cases loop back (a retry from an earlier step) no longer hides Next, so
31
+ the walk can go on past it.
32
+
33
+ Update with `chi update` (it upgrades inline-widgets to 0.1.1), then restart chi web.
34
+
11
35
  ## [0.163.0] - 2026-11-10
12
36
 
13
37
  ### Added
@@ -6044,7 +6068,8 @@ and long-lived sessions.
6044
6068
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6045
6069
  hotkey panel that send selected text or the clipboard to your sessions.
6046
6070
 
6047
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.163.0...HEAD
6071
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.164.0...HEAD
6072
+ [0.164.0]: https://github.com/dm1try/samagotchi/compare/v0.163.0...v0.164.0
6048
6073
  [0.163.0]: https://github.com/dm1try/samagotchi/compare/v0.162.0...v0.163.0
6049
6074
  [0.162.0]: https://github.com/dm1try/samagotchi/compare/v0.161.0...v0.162.0
6050
6075
  [0.161.0]: https://github.com/dm1try/samagotchi/compare/v0.160.0...v0.161.0
data/docs/architecture.md CHANGED
@@ -199,7 +199,7 @@ log's last 4 MB). Rows: [configuration.md](configuration.md#checking-it-chi-home
199
199
  - **Starting:** every spawn marks the session starting (`<uuid>/starting`, `{pid, at}`, `StartingMarker`) until its worker holds the lock: `spawn_worker_for_session` writes it with its own pid before `Process.spawn` and the starter's after (the starter lives until the worker holds the lock, at most `WORKER_START_GRACE`; a spawn that raises or whose starter is gone leaves none), `spawn_session` before the new file is saved, and `Worker#start` removes it. It holds for 60 s at most, and only while the pid it names runs. A resume claims it (`StartingMarker.claim`, a link(2): of resumes racing from any processes one wins), then reads the owner again. A stop marker cancels the hold-off (`start_pending?` = starting and not stop-marked) for a start marked before the stop only: of two sends after a stop, the claim lets one spawn. The stop marker carries its own `at` (`{"at"}`, on the starting marker's clock; `Session.stopped_at`), an older chi's empty one its mtime. The sweep, archive (`:starting`) and delete (refused as an owned session) honour it. N-1: an older spawner writes none for a resume (the owner checks stay); an older worker never leaves one it was given (every worker clears it at start); a leftover one is stale by age or pid (a claim's temp files a kill left, `starting.*`, count as skeleton); a 0.160 spawner or chi web still holds off on a fresh marker under a stop (it reads `starting?` before the stop), until the start ends or 60 s. `SessionManager` keeps only its starters' pids, for chi web's restart to adopt (`live_spawn_pids`), and decides nothing from them.
200
200
  - **Deleting:** `delete_session`, the retention sweep and a failed continue's cleanup use `remove_files` for the session JSON, sidecar dir, plugin state, attached context, participant grants, System 1 runs and context-candidate records. The JSON and dir go through `remove_session_files`, holding the owner lock (kind `deleting`, which `stop_session` never signals; not waited for: a worker that took it since the check keeps the session) and reading the starting marker again under it (a resume that claimed the start just before keeps the session; one after it sees the lock held). N-1: an older chi's stop reading the owner then would TERM the deleter (chi web, the CLI) in that moment; an older reader shows the kind as unknown. `Session#save` of a session read from its file (or saved once) skips a file that is gone (log `save_skipped_deleted`) rather than recreate it; only a new session's first save creates one.
201
201
  - **Worker presence:** whether a worker is up, coming or held off is read once per decision as a `WorkerPresence` (`worker_presence.rb`, a `Data.define`), the deciders' one reader of those facts (display and list rows still read `session_owner` / `WorkerLink` themselves): the owner lock's holder, the stop marker (`stop_marked?`: the only "stopped" a decider reads, never the session file's status), the `starting` marker (`StartingMarker`, `starting?`, `start_pending?`: every spawn writes it, see Starting), the archive marker, the session file's existence, and the `WorkerLink` outcome when asked (never the file itself: a scratch session's flag is read by `WakePolicy`, last). The deciders read it: `resume_session` (tui, owned, `resume_held_off?`), the session inbox's `WakePolicy` (a ring, a push's wake, a note, a fresh verdict, `wake_for_report`, `deliver_turn`'s two liveness checks, `WorkerBoot`'s leave: below), `Local#wake`/`#worker`, `AttachLauncher`, `Schedules#busy_reason`, archive, delete and the retention sweep. Each keeps its own subset of the facts and their order.
202
- - **Session inbox:** a delivery into a session (`SessionInbox.deliver(kind, id) { |at| write }`, `session_inbox_delivery.rb`) runs one path: resolve the link (`SessionInbox::Head.resolve`: send, push and a fresh verdict are pinned to the id named; a note goes to the chain's newest link; a ring's file stays with the parent `parent.json` names and its wake goes one hop, to the link whose `ChildReports` reads that file; only an archived id is walked, with one `Session.list`), refuse before any write (a gone session; a one-turn run's or a scratch session for send and a note), write with the kind's own writer (formats unchanged), read `WorkerPresence` once, and apply the kind's `WakePolicy` row. `decide` reads in one order for every kind: gone, one-turn run (`:owned`), owned (`:live`), the stop marker (`:stopped`: the only "stopped", the file's status never decides; send un-stops), archived (send alone starts one), starting (`:starting`, never a second spawn), the kind never starts (`:none`: a note, a fresh verdict) or wasn't asked to (`:off`), scratch (the session file is read only here), else `:start` through `SessionManager.start_for_inbox` (`resume_session`, its claim on the starting marker; it answers `:woken` only when it spawned the worker, `:starting` when another start won the claim, `:live` when a worker took the lock since). N-1 gap: a session file that says `stopped` with no stop marker (stopped before the marker existed, or a resume whose spawn failed after it cleared the marker) is woken, and an older worker, which has no `Worker#settle_stale_status`, exits on its first pass; the wake still reads `:woken`, and each later ring or push spawns another such worker (bounded by the rings and pushes). Restarting chi on the new version (`chi web`, the workers) closes it. `SessionInbox.wake` is the wake half alone (`wake_for_report`, a failed continue's rings). On it: `ChildRing.ring` (its start on a thread), `Local#context_push`'s wake (its outcome is `ContextPush#wake`, the push line's ending), `NoteDelivery.deliver` (every note writer a person or another session drives: `chi note`, `send_note`, `chi broadcast`, chi web's notes route; `NoteDelivery::Result#id` is the link that has it, `#asked` the one named; `/objectives` passes `pin: true`: its list is its own session's) and `VerifyFresh.forward` (`:fresh_verdict`: the child's parent, pinned, no worker). Send keeps its Bridge/file flow in `SessionManager.deliver_turn` (pinned to the id it names: an archived link gets the message and comes back); its two liveness checks (before the post, after a file's write) read the `:send` row and leave the refusals to `resume_session`'s wording. One row is not a delivery: `:leave`, `WorkerBoot.run_session_loop`'s successor as a worker leaves (input left after a signal, an idle exit's or `/exit`'s input or rings, a restart), read on a fresh presence once the lock is free: a stop that landed as it left starts none for any way out (`resume_session` would clear the stop; logged `respawn_dropped`, `restart_dropped` for a restart, whose reminders go with it), the input and rings stay for the next start. The notes a spawn writes into the session it starts stay direct `SessionInbox.write_note` calls, pinned by construction: spawn_session's chain note, `ContextMove`'s notes, `Objectives.carry`, `ChildMove`'s note to a moved child. A continue moves the previous link's waiting notes to the new link last in its `before_spawn` (`NoteMove.move`), a failed one gives them back before the link goes (`NoteMove.give_back`), and the new link's worker adopts what the archived links before it get after their continue (`NoteMove.adoption`, from `WorkerInbound#absorb_notes` and `Worker#start`: back along the chain through up to 8 archived links, from each only notes from the creation of the link that continued it, never an objectives list). `write_note` refuses a session with no file and no folder (`Session::NotFound`), so a late writer can't bring back a deleted link's folder.
202
+ - **Session inbox:** a delivery into a session (`SessionInbox.deliver(kind, id) { |at| write }`, `session_inbox_delivery.rb`) runs one path: resolve the link (`SessionInbox::Head.resolve`: push and a fresh verdict are pinned to the id named; a send and a note go to the chain's newest link, and for a send (a kind that starts an archived link) a continue of the reached link in flight (`ContinueIntent.in_flight`: `continue.json` written, `continue.lock` held, the successor not saved yet) gives `:continuing` with the successor's id, which chi send asks again for a moment and then refuses; a note needs no such check (`NoteMove` moves or adopts it); a ring's file stays with the parent `parent.json` names and its wake goes one hop, to the link whose `ChildReports` reads that file; only an archived id is walked, with one `Session.list`), refuse before any write (a gone session; a one-turn run's or a scratch session for send and a note), write with the kind's own writer (formats unchanged), read `WorkerPresence` once, and apply the kind's `WakePolicy` row. `decide` reads in one order for every kind: gone, one-turn run (`:owned`), owned (`:live`), the stop marker (`:stopped`: the only "stopped", the file's status never decides; send un-stops), archived (send alone starts one), starting (`:starting`, never a second spawn), the kind never starts (`:none`: a note, a fresh verdict) or wasn't asked to (`:off`), scratch (the session file is read only here), else `:start` through `SessionManager.start_for_inbox` (`resume_session`, its claim on the starting marker; it answers `:woken` only when it spawned the worker, `:starting` when another start won the claim, `:live` when a worker took the lock since). N-1 gap: a session file that says `stopped` with no stop marker (stopped before the marker existed, or a resume whose spawn failed after it cleared the marker) is woken, and an older worker, which has no `Worker#settle_stale_status`, exits on its first pass; the wake still reads `:woken`, and each later ring or push spawns another such worker (bounded by the rings and pushes). Restarting chi on the new version (`chi web`, the workers) closes it. `SessionInbox.wake` is the wake half alone (`wake_for_report`, a failed continue's rings). On it: `ChildRing.ring` (its start on a thread), `Local#context_push`'s wake (its outcome is `ContextPush#wake`, the push line's ending), `NoteDelivery.deliver` (every note writer a person or another session drives: `chi note`, `send_note`, `chi broadcast`, chi web's notes route; `NoteDelivery::Result#id` is the link that has it, `#asked` the one named; `/objectives` passes `pin: true`: its list is its own session's) and `VerifyFresh.forward` (`:fresh_verdict`: the child's parent, pinned, no worker). Send keeps its Bridge/file flow in `SessionManager.deliver_turn`, which resolves nothing (it acts on the id it is given: an archived link gets the message and comes back); chi send resolves the head first (`SessionAccess#head`, remotely `GET /api/sessions/resolve?head=1`), while the web composer, a participant's turn, `delegate` follow-ups, `Plugin::Sessions` and `Schedules` stay on the id they name; its two liveness checks (before the post, after a file's write) read the `:send` row and leave the refusals to `resume_session`'s wording. One row is not a delivery: `:leave`, `WorkerBoot.run_session_loop`'s successor as a worker leaves (input left after a signal, an idle exit's or `/exit`'s input or rings, a restart), read on a fresh presence once the lock is free: a stop that landed as it left starts none for any way out (`resume_session` would clear the stop; logged `respawn_dropped`, `restart_dropped` for a restart, whose reminders go with it), the input and rings stay for the next start. The notes a spawn writes into the session it starts stay direct `SessionInbox.write_note` calls, pinned by construction: spawn_session's chain note, `ContextMove`'s notes, `Objectives.carry`, `ChildMove`'s note to a moved child. A continue moves the previous link's waiting notes to the new link last in its `before_spawn` (`NoteMove.move`), a failed one gives them back before the link goes (`NoteMove.give_back`), and the new link's worker adopts what the archived links before it get after their continue (`NoteMove.adoption`, from `WorkerInbound#absorb_notes` and `Worker#start`: back along the chain through up to 8 archived links, from each only notes from the creation of the link that continued it, never an objectives list). `write_note` refuses a session with no file and no folder (`Session::NotFound`), so a late writer can't bring back a deleted link's folder.
203
203
  - **Retention:** 14 days / 500 cap (env `SAMAGOTCHI_SESSION_RETENTION_DAYS`/`MAX_COUNT`, optional `KEEP_STATUS`), live-owner and starting guard (looked at again right before a session's files go), only when `*.json` present; lazy sweep at most once per `session.sweep_interval_hours` (default 24) from the session hub's full-probe tick (and on `GET /api/sessions`, which the page no longer calls), manual via `bin/chi sessions prune --dry-run`.
204
204
  - **Ordering:** `Session.list(sort:,order:,limit:,offset:)` and `GET /api/sessions?sort=&order=&limit=&offset=` default `updated_at desc`; Web UI sort/filter/pagination.
205
205
  - **Test hygiene:** `test_run` flag when `SAMAGOTCHI_ENV=test`/`RACK_ENV=test`/`CI`, targetable via `prune --test-only` / `clean`.
data/docs/bundles.md CHANGED
@@ -1376,8 +1376,10 @@ this API (`lib/samagotchi/bundles/inline-widgets/plugin.rb`) and has no settings
1376
1376
  choose from.
1377
1377
  - **Where it draws**: chi web, in the answers. The terminal shows the block's YAML, and a block chi can't read stays
1378
1378
  YAML with a short note under it.
1379
- - **Where the prompt has none**: a delegate child (its parent reads the report, nobody sees it drawn) and a one-shot
1380
- `chi -p … --non-interactive`. `/stats` lists the sections a session's prompt holds: `picks (inline-widgets), walk
1379
+ - **Where the prompt has none**: a delegate child (its parent reads the report, nobody sees it drawn), a one-shot
1380
+ `chi -p … --non-interactive`, and a review session (`chi review`: its participants' page draws no widgets, so they
1381
+ would read the YAML). A working session you pair in keeps them: your page draws them, and inviting someone later
1382
+ doesn't change the prompt. `/stats` lists the sections a session's prompt holds: `picks (inline-widgets), walk
1381
1383
  (inline-widgets)`.
1382
1384
  - **Cost**: about 2,900 characters in the stable part of the prompt, the same at every build, so the prompt cache keeps.
1383
1385
  - **Uninstall**: `chi bundle uninstall inline-widgets` takes the sections out of new sessions' prompts (a session you
data/docs/cli.md CHANGED
@@ -22,7 +22,7 @@
22
22
  - `chi broadcast [-m TEXT] [--all] [--dry-run]`, `chi broadcast log [--last N] [--format json]`, `chi broadcast deliver BROADCAST_ID (ID|PREFIX)...` — share one piece of information (TEXT or stdin) with every session it may concern, as a context note from `broadcast` (see [Broadcast](broadcast.md))
23
23
  - `chi context <add|push|ls|show|refresh|rm|mute|unmute> …` — attach live external text to sessions (a command chi runs every so often, or text pushed in); the model gets a short note when it changes and reads it with `context_read`; `chi context add <URL>` attaches a GitHub PR with the github-pr bundle; `chi context push NAME -m TEXT` (the long form is `--message TEXT`) gives a `--push` source its new text, read from stdin when no `-m` is given (see [Attached context](context.md))
24
24
  - `chi context report [--days N]` — the candidate judge's counts from `context_candidates.jsonl`: candidates proposed, mentioned, attached or declined by you; the judge's asks; what it would attach per threshold, and how that agrees with what you did (this machine only; see [The log and the report](context.md#the-log-and-the-report))
25
- - `chi send [-m TEXT] [--image PATH]... [--cut | --queue] (ID|PREFIX)...` — send a message to sessions as if typed there: a turn starts (or a running one takes it at its next step; `--cut` asks it to cut long thinking for it; `--queue` runs it as a turn of its own after the running one, and `--queue --wait` waits for that turn's own answer); piped stdin goes above `-m` as quoted context, and `--image` attaches images (see [Sessions: Sending a message](sessions.md#sending-a-message)); `--new` starts a session with it instead (`--new --continues ID|last:ID` the next link of that session's chain, see [Session chains](sessions.md#session-chains)), and `--wait` prints the answer (`--wait ID` with no message waits for the next reply without sending — to an idle session whose last turn already ended, that ended turn's reply or end comes back; `--wait --turn T ID` with no message waits for exactly turn T, whether running, queued or last ended; `--format json` includes its `turn_id` when known, for waiting again after exit 3 or 4; exit 3 a question waits, its options on stderr; exit 4 `--timeout` passed with the turn still running; see [Starting a session](sessions.md#starting-a-session))
25
+ - `chi send [-m TEXT] [--image PATH]... [--cut | --queue] (ID|PREFIX)...` — send a message to sessions as if typed there: a turn starts (or a running one takes it at its next step; `--cut` asks it to cut long thinking for it; `--queue` runs it as a turn of its own after the running one, and `--queue --wait` waits for that turn's own answer); piped stdin goes above `-m` as quoted context, and `--image` attaches images (see [Sessions: Sending a message](sessions.md#sending-a-message)); to a session that was continued it goes to its chain's newest link (`3f9a1c2e → 7b2d41aa (continued) sent`; the old link stays archived; one being continued right now waits up to 10 s for its new link, then `refused: being continued as 7b2d41aa; send again in a moment`), so a chain's first id is a stable address; `--new` starts a session with it instead (`--new --continues ID|last:ID` the next link of that session's chain, see [Session chains](sessions.md#session-chains)), and `--wait` prints the answer (`--wait ID` with no message waits for the next reply without sending — to an idle session whose last turn already ended, that ended turn's reply or end comes back; `--wait --turn T ID` with no message waits for exactly turn T, whether running, queued or last ended; `--format json` includes its `turn_id` when known, for waiting again after exit 3 or 4; exit 3 a question waits, its options on stderr; exit 4 `--timeout` passed with the turn still running; see [Starting a session](sessions.md#starting-a-session))
26
26
  - `chi answer ID --question QID (--option N|LABEL)... [--text T] [--timeout S] [--format json]` (or `--dismiss`) — answer the question a session waits on (the one `chi send --wait` exited 3 with), then wait and print what comes next as `chi send --wait` does: the reply (0), the next question (3), still running after `--timeout` (4). `--option` is 1-based or the label, repeated on a multi-select question; `--text` is free text, or a Deny's reason; `--dismiss` leaves it unanswered and the model finishes its reply. A question no longer open (the web answered first) isn't answered again: it waits for that turn's reply. An option the question doesn't offer exits 2; a worker that is gone exits 1 (`send the task again: chi send --wait -m "…" ID`). What a parent may pick follows `guardrails.parent_answers`, or the session's own `parent_answers` when stricter (`soft`, the default: a deny, a plain answer, Continue and "Allow once"; `standard`: no allow; `hard`: no Continue either), never a wider scope or an allow on chi's own config; a refused pick exits 1 with what to answer instead (a convention, not a security boundary; see [Guardrails](guardrails.md#answers-from-a-parent-agent))
27
27
  - `chi schedule <add|list|show|tick|run-now|enable|disable|cancel>` — durable schedules on this machine: a prompt with a clock that fires out of no worker (cron, systemd, or chi web's hub with `schedule.auto_tick`), as the next link of a session's chain or as a turn in the session itself (see [Scheduling](scheduling.md) and [Durable schedules](#durable-schedules-chi-schedule)). A usage error exits 2, an unknown session or schedule 1; `chi --remote X schedule list` exits 2
28
28
  - `chi remote add NAME URL [--token-file F | --token-stdin]`, `chi remote ls`, `chi remote rm NAME` — the other machines whose chi web the session commands reach with `--remote NAME` (see [Remote sessions](#remote-sessions))
@@ -1597,6 +1597,11 @@ CHI_REMOTE=studio chi context push claude-outbox ab12 < answer.json
1597
1597
  a loosening `/parent-answers`, images to a model that can't see them. Each
1598
1598
  target refuses its own (`ab12 refused: …`), where this machine refuses
1599
1599
  before sending to any.
1600
+ - `send` to a session that was continued asks that machine for its chain's
1601
+ newest link first (`GET /api/sessions/resolve?id=X&head=1`, `{id, asked,
1602
+ via}`) and sends there. An older chi web ignores `head=1` and answers
1603
+ `{id}`: the message goes to the id named, as before. A participant's token
1604
+ never asks (their grant is for one session).
1600
1605
  - Waits run on the server, 30 s at a time, until the answer or your own
1601
1606
  `--timeout`; exit codes are the same. The commands chi prints for what to
1602
1607
  do next work as pasted: they carry `--remote NAME` (`chi --remote studio
@@ -15,7 +15,9 @@ model. The TUI is untouched: it shows a fence as source.
15
15
  didn't know the key draws once a kept manifest is there) lists
16
16
  who draws what: `GET /api/block_renderers`, `:owner`. `GET /api/block_renderers/:bundle/:file` serves a file, `:owner`:
17
17
  the URL's names go through `BlockRenderers.script_path` (membership in a listed renderer's `load` before any path is
18
- made), then `Provenance.sha_matches?`; a changed file is 409 `renderer_changed`. ETag + `no-cache`, as static files.
18
+ made), then `Provenance.sha_matches?`; a file with no recorded sha, a missing one or a changed one is 409
19
+ `renderer_changed`, each with its own reason. ETag + `no-cache`, as static files. A `block_renderers:` list that
20
+ doesn't parse is logged once per bundle and problem (each list request and file fetch reads it).
19
21
  3. `block_watch.js` (`createBlockWatch`, made by `block_host.js`'s `createBlockHost`, wired in `app.js`; `participant.js`
20
22
  isn't) finds and watches the blocks; `block_host.js` is its frame drawer (`createFrameDrawer`). The watcher asks an
21
23
  ordered list of drawers, core ones first (`inline_widgets.js` for `chi-ui`: [inline-widgets.md](inline-widgets.md)), then the frame drawer, which waits for `/api/block_renderers`;
@@ -98,7 +98,8 @@ session switch, a turn's end, Revise's clones, the stage's hand-off to `#history
98
98
  - **Shadow DOM.** The host has an open shadow root holding the widget, with `widgets.css` adopted
99
99
  (`adoptedStyleSheets`): the page fetches it once into a constructable `CSSStyleSheet` (`loadWidgetSheet`), and `draw`
100
100
  returns a Promise that places the widget once it is there, so no widget flashes unstyled and the view held
101
- (`holdingView`) measures the styled one. A failed fetch draws unstyled and the next draw tries again. Its words are then out of the bubble's `textContent`, which the shown-texts dedupe (`seedSeenFromDom`), copy's
101
+ (`holdingView`) measures the styled one. A failed fetch (an error, a non-2xx, or an answer that isn't
102
+ `text/css`, such as an auth proxy's login page) draws unstyled and the next draw tries again. Its words are then out of the bubble's `textContent`, which the shown-texts dedupe (`seedSeenFromDom`), copy's
102
103
  fallback and an annotation's quote read, as with a renderer's `<img>`-only figure. chi's `:root` tokens reach it as
103
104
  inherited custom properties, so light and dark follow the page. Playwright's locators pierce an open shadow root;
104
105
  `page.evaluate`'s DOM calls don't. Whatever asks `document.activeElement` whether a field has the focus looks
@@ -115,7 +116,9 @@ session switch, a turn's end, Revise's clones, the stage's hand-off to `#history
115
116
  (a move that removes or hides the focused button leaves the focus on the widget; a click on the current step is no
116
117
  move). `walkRoutes`
117
118
  resolves where a step goes: its `next` (`end`: nowhere), else the step below; a fork's `cases` as written, a case whose `when` is no
118
- condition (round 1's `always`) reading as the usual path, alone it is the step's next. At a phone's width the
119
+ condition (round 1's `always`) reading as the usual path, alone it is the step's next. A fork none of whose cases
120
+ moves on (each loops back to an earlier step or its own) keeps Next beside them (`hasNext`): its unwritten usual
121
+ path, the step below or Start over, or the walk would be stuck there. At a phone's width the
119
122
  swimlane scrolls sideways inside the widget; the page doesn't.
120
123
  - **picks** (`widget_picks.js`): one row per item, its options as chips (`aria-pressed`), the recommended one marked
121
124
  and picked to start with, a "+ note" per row, and "Fill reply".
@@ -84,10 +84,15 @@ registry flag (`--recap-base-url` …) is this machine's config: `LOCAL_ONLY` wi
84
84
  1. **bin/chi → Dispatch.** The flag is removed. `send` and `send --message` / `--wait` are `SUPPORTED`. `Remotes.find("studio")`
85
85
  reads `$XDG_CONFIG_HOME/samagotchi/remotes.yml`. Then `SendCommand.new(argv, access: Remote.new(entry)).run`.
86
86
  2. **SendCommand.** The client-side checks (UI-only slash commands, image ingest) run. The machine-local ones are
87
- skipped (next section). `run_wait` → `ParentWait#resolve` → `Remote#resolve`.
87
+ skipped (next section). Every id is resolved once up front (`SendCommand#target`): `Remote#resolve`, then
88
+ `Remote#head`, where input for it goes (a continued session's chain's newest link).
88
89
  3. **Remote → HTTPTransport.** The first request on a `Remote` is preceded by `check_server!`, which sends
89
90
  `GET /api/info` and needs `app: "chi-web"` plus the `session_commands` feature. Next come
90
- `GET /api/sessions/resolve?id=ab12` and `POST …/wait/prepare {busy: true, queue:}` (`Remote#busy`), then
91
+ `GET /api/sessions/resolve?id=ab12`, `GET /api/sessions/resolve?id=<full id>&head=1` (`{id, asked, via}`:
92
+ `SessionInbox::Head.resolve(:send, …)` on the server, `via` `same`, `head` or `continuing`; an older chi web
93
+ ignores `head=1` and answers `{id}`, read as `same`, so the message goes to the id named as before; a participant's
94
+ token never asks, and the participant branch of the route answers `{id}` alone) and
95
+ `POST …/wait/prepare {busy: true, queue:}` (`Remote#busy`) on the id it answered, then
91
96
  `POST …/wait/prepare {turn, created}` for the `WaitStart`. `deliver` calls `Remote#show` and `#owner` (each
92
97
  `GET /api/sessions/:id?brief=1`), then
93
98
  `POST …/turn {prompt, client_id: "cli:send", history: false}`. A 202 ack becomes a `DeliverResult` with `via`
data/docs/sessions.md CHANGED
@@ -43,7 +43,7 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
43
43
 
44
44
  **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. 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}`; 409 `owned_by_tui` or `still_stopping`; 404).
45
45
 
46
- <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. 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`, none), 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. 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.
46
+ <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`, none), 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. 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.
47
47
 
48
48
  **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)).
49
49
 
@@ -303,6 +303,7 @@ pbpaste | chi send 3fa2 # the clipboard is the messa
303
303
  - Fire and forget: it returns once the message is queued and never prints the answer; that shows in whatever is attached. A guardrail "ask" waits for a UI to answer it, so with nothing attached the turn stalls there until one attaches (`chi --attach ID`).
304
304
  - `--image PATH` (repeatable, up to 20) sends images with the message, as the web composer's chips do. Each file is read once before anything is sent (bmp, tiff and heic converted to png, large ones downscaled, as for `@path`); a missing file or one that isn't an image stops the send (exit 1; with `--wait --format json`, an `error` line) and nothing is sent; more than 20 is a usage error (exit 2). Each session gets its own copy in `<session>/images/`. Text is still required (`-m` or stdin; context alone counts), also with `--wait`. The session's model must see images: one known not to (the host's model list says text-only, `vision: false` in `models:` or `hosts:`, a native llama.cpp without a vision model) is refused before anything is sent, with the reason (`<id> refused: gemma can't take images (…); send text only or switch the model (/model)`); the other sessions of the same send still get it, and the exit is 1. With `--new` nothing is started. When chi can't tell (a native host whose `/props` doesn't answer, a list that doesn't say), the message is sent as before and a text-only model fails the turn in the session. A running turn doesn't take images mid-turn: the message runs as the next turn, and the line says `(runs after the current turn)`. With `--new` the session starts idle with the message as its preview, then the message goes in as its first turn once its worker is up (`<id> started with 1 image`); if the worker doesn't come up in 5 s the session is kept, with its id on the `failed:` line.
305
305
  - A session command runs as the command, as typed in a terminal: `chi send -m "/model qwen" 3fa2` switches the model (`sent as a session command`), and the model never sees the line. What counts is what the session's worker knows (the built-ins, `!cmd`, its bundles' commands); an unknown `/word` (`/usr/bin/env is missing`) goes in as a message. A UI-only command (`/stats`, `/exit`, `/recap`, …) is refused instead: the worker doesn't run it, so the line would reach the model as a prompt (`<id> refused: /stats is a terminal and web command; use chi sessions stats <id8>`; exit 1, and nothing is sent). With `--new` a line starting with `/` or `!` starts the session idle and goes to its worker once it is up, which decides. With `--wait` a command has no reply to wait for: exit 0 at once, `<id> sent as a session command: no reply to wait for …` on stderr (`{"status":"command",…,"detail":…}` with `--format json`); its output shows where the session is open.
306
+ - A session that was **continued** (archived, with a later link): the message goes to its chain's newest link, as a note does (*Context notes*), and the old link stays archived. The line names both, in `chi note`'s wording: `3f9a1c2e → 7b2d41aa (continued) sent`. Every id is resolved once, before anything is sent (`SessionAccess#head`, `SessionInbox::Head`'s walk for the `send` row), so the parent-answers check, images, a session command, the UI-only refusal and `--wait` all act on that newest link, and `chi send OLD NEW` sends once. `--wait` waits there: its `--format json` `session_id` is the newest link's, and `asked` the id given (only when they differ). `--wait` without a message follows too, but `--wait --turn T` of the old link (a turn from before the continue) waits on the old one. A link archived and never continued is still brought back by a send. A link being continued right now (its intent written, its new link not saved yet: `SessionContinue`) is asked again for up to 10 s; still not there, it is refused and nothing is written: `3f9a1c2e refused: being continued as 7b2d41aa; send again in a moment`. A chain's first link's id is a stable address for the whole chain. What stays on the id it names: the web composer (typing on an archived link's page brings that link back), a participant's turn (a grant is for one session), `delegate(session:)`, a plugin's turn and a schedule (its own rule, *Schedules*).
306
307
  - One line per session: `sent`, `sent as a session command`, `sent with 2 images`, `sent (goes in at the running turn's next step)`, with `--cut` `sent (cut in now)`, `sent (cuts in once the thinking passes 20 s)` or `sent (cutting is off; goes in at the next step)`, with `--queue` `sent (queued: runs after the current turn)`, `sent (the running turn had ended: it runs now)` or `sent (nothing running: it runs now)`, `sent (started its worker)`, `refused: …` or `failed: …`. Exit 0 when all were sent, 1 when any was refused, failed or not found, 2 for a usage error. There is no `--all`.
307
308
 
308
309
  The Automator action above works for messages too: swap its last line for `pbpaste | "$chi" send -m "what do you make of this?" $(print -r -- "$picked" | cut -f1)`.
@@ -362,7 +363,7 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
362
363
  - **Web:** `POST /api/sessions` takes `continues: "<id, prefix or last:id>"`, with `idle: true` (a new link waiting for its first message, previewed by the previous link's, or `preview`) or a `prompt`, and `model` (or `model_name`) for the new link's model, but not `dir`, `llm_context`, `thinking`, `settings`, `toolkit`, `tools`, `no_tools` or `parent_answers` (400 `invalid_continues`: the previous link's are taken). 201 is the new session's summary, `continues` set, with `moved`: the ids of the delegates that moved to it (`[]` for none), and `model_warning`: the default-model fallback's warning, then any about the model id, joined by `; ` (`null` for none), and `opener`: the previous link's first typed message, in full, when that link continues one itself (`null` otherwise: a chain's first link's first message is its task), and `moved_context`: `{moved: [names], stayed: [{name, why}]}`, the attached context it took (`why` `pushed` or `not movable`); 404 `not_found`; 400 `ambiguous_id` for a prefix of several sessions, `invalid_model` for a given model whose host config.yml doesn't have (or a fallback with no default model); 409 `continued` with `next_id` (the link that continues it already, which the page opens instead), `open_children` with `ids` (open delegates that can't move), `folder_gone`, `busy`, `scratch` or `owned_by_tui`. Every session summary carries `continues`.
363
364
  - **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.
364
365
  - **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
365
- - **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: `chi send` to an archived link would bring it back (a human's input), not continue the chain. That is the rule: a message (`chi send`, the web composer, `delegate(session:)`) goes to the link it names; a note goes to the chain's newest link (*Context notes*). 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.
366
+ - **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 message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain. 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. 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.
366
367
 
367
368
  ## Schedules
368
369
 
data/docs/sub-agent.md CHANGED
@@ -233,6 +233,17 @@ answers from any local process.
233
233
  turn is the answer: its reply comes back (`answered`), or its end when it
234
234
  left no reply (`failed`, `canceled`, `limit`, …) — so a turn that finished
235
235
  in the gap between waits is reported, not waited for.
236
+ - A session you keep one id for (a coordinator, say) may be continued meanwhile
237
+ (`chi send --new --continues`, a chain schedule): `chi send` to that id goes
238
+ to its chain's newest link, and the old link stays archived. Keep the
239
+ chain's first id as its address. With `--format json`, `session_id` is the
240
+ link the message went to and `asked` the id you gave (only when they differ),
241
+ in every line after the id resolved (a refusal or an error too; a refused
242
+ send while the continue runs has `session_id` null and `asked`); the text
243
+ lines name both, `3f9a1c2e → 7b2d41aa (continued)`. `chi answer` and `--wait --turn T` take that `session_id` (a `--turn` of the
244
+ old link, from before the continue, waits on the old link). A send while the
245
+ continue itself runs waits a moment for the new link, else exits 1 with
246
+ `being continued as <id>; send again in a moment`.
236
247
  - An answer to a question that is no longer open (you answered it in the web
237
248
  first) isn't sent; `chi answer` says so and waits for what comes next. Its
238
249
  JSON then has `"answered_here": false` (absent when the answer went in), so
@@ -38,6 +38,9 @@ module Samagotchi
38
38
  # Languages core draws itself: a bundle's renderer for one would be a
39
39
  # second drawer for the same block.
40
40
  RESERVED = [InlineWidgets::LANG].freeze
41
+ # The [bundle, problem] pairs .renderers has logged in this process.
42
+ WARNED = Set.new
43
+ WARNED_LOCK = Mutex.new
41
44
 
42
45
  module_function
43
46
 
@@ -97,25 +100,32 @@ module Samagotchi
97
100
  # owner's browser, so it is checked as a plugin's load and a provider's
98
101
  # script are; a --dev install's links are not.
99
102
  # @return [String, nil] nil when no such renderer loads such a file
100
- # @raise [Invalid] the file is gone or changed
103
+ # @raise [Invalid] the file is gone, has no recorded sha, or changed
101
104
  def script_path(bundle, file)
102
105
  return nil unless for_installed.any? { |renderer| renderer.bundle == bundle && renderer.files.include?(file) }
103
106
 
104
107
  provenance = MemoryBundle::Provenance.new(name: bundle)
105
108
  path = File.join(provenance.scripts_dir, file)
106
109
  recorded = provenance.record&.scripts&.fetch(file, nil)
107
- return path if File.file?(path) && MemoryBundle::Provenance.sha_matches?(path, recorded)
110
+ raise Invalid, "bundle #{bundle}'s scripts/#{file} isn't among its installed scripts (reinstall the bundle)" if recorded.to_s.empty?
111
+ raise Invalid, "bundle #{bundle}'s scripts/#{file} is missing (reinstall the bundle)" unless File.file?(path)
112
+ return path if MemoryBundle::Provenance.sha_matches?(path, recorded)
108
113
 
109
114
  raise Invalid, "bundle #{bundle}'s scripts/#{file} differs from the installed one (reinstall the bundle)"
110
115
  end
111
116
 
112
- # Its parsed renderers; a list that doesn't parse is none (logged).
117
+ # Its parsed renderers; a kept list that doesn't parse is the record's
118
+ # mirror, else none. Logged once per bundle and problem: this runs on each
119
+ # list request and each renderer file fetch.
113
120
  def renderers(bundle, manifest)
114
- if (problem = manifest.problems["block_renderers"])
121
+ if (problem = manifest.problems["block_renderers"]) && WARNED_LOCK.synchronize { WARNED.add?([bundle, problem]) }
115
122
  Log.warn(:web, "block_renderers_unreadable", bundle: bundle, msg: problem)
116
123
  end
117
124
  manifest.block_renderers
118
125
  end
119
126
  private_class_method :renderers
127
+
128
+ # Forget what was logged (specs).
129
+ def reset_warnings! = WARNED_LOCK.synchronize { WARNED.clear }
120
130
  end
121
131
  end
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: inline-widgets
3
- version: 0.1.0
3
+ version: 0.1.1
4
4
  scope: system
5
5
  description: "Teaches the model the chi-ui blocks chi web draws: picks (rows of options that fill your reply) and walk (a scenario stepped through)"
6
6
  trust_level: reviewed
7
7
  plugin:
8
8
  file: plugin.rb
9
- sha256: sha256:24ad0c3f0ffb592826b4a7389111d76723e9f28ea4d94ab63abda7986d3311bb
9
+ sha256: sha256:e54a0096ba3b20ccf6bbca2798cb53afd86986a2cb7bee1c02e5520f2ddb5033
10
10
  # chi.prompt_section is 0.132.0's; the web draws chi-ui blocks only from the next release
11
11
  requires_chi: ">= 0.155.0"
@@ -9,8 +9,11 @@
9
9
  #
10
10
  # The text is eval 0013's round-2 hint, split in two. It is static, so the
11
11
  # prompt cache keeps: same text at every build. A delegate child's answer is
12
- # read by its parent, not drawn for a user, and a one-shot (-p --non-interactive)
13
- # prints to a terminal: neither gets a section.
12
+ # read by its parent, not drawn for a user, a one-shot (-p --non-interactive)
13
+ # prints to a terminal, and a review session (chi review) is read by its
14
+ # participants, whose page draws no widgets: none of them gets a section. A
15
+ # working session the owner pairs in keeps them: the owner's page draws them,
16
+ # and a participant invited later mustn't change the prompt (the cache).
14
17
  class Plugin
15
18
  PICKS = <<~TEXT
16
19
  The web UI draws fenced ```chi-ui code blocks (YAML inside) as interactive widgets; the terminal shows their source. Use one whenever it helps the user more than prose: a widget replaces the long explanation, it doesn't sit beside one. Never use one for what markdown shows well (tables, lists, key-value). At most one widget per answer; keep the prose around it to a few sentences and don't repeat the widget's content.
@@ -71,6 +74,7 @@ class Plugin
71
74
 
72
75
  private
73
76
 
74
- # Whether the session's answers reach a web page that draws them.
75
- def drawn?(ctx) = ctx.frontend != :one_shot && !ctx.delegate?
77
+ # Whether the session's answers reach a web page that draws them. Decided by
78
+ # the session's kind, so the same at every build.
79
+ def drawn?(ctx) = ctx.frontend != :one_shot && !ctx.delegate? && !ctx.review?
76
80
  end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.163.0
3
+ version: 0.164.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -38,7 +38,7 @@ module Samagotchi
38
38
  end
39
39
  if @json && !@reported && status == 1
40
40
  detail = @stderr.last.to_s.delete_prefix("#{command_name}: ")
41
- @stdout.puts(ParentReport.error_line(detail, session_id: @session_id))
41
+ @stdout.puts(ParentReport.error_line(detail, session_id: @session_id, extra: error_extra))
42
42
  @stdout.flush
43
43
  end
44
44
  status
@@ -89,6 +89,10 @@ module Samagotchi
89
89
  Exit::FAILED
90
90
  end
91
91
 
92
+ # More keys for the error object, after session_id: {} (chi send's
93
+ # names the id asked).
94
+ def error_extra = {}
95
+
92
96
  # More keys for the JSON object: answered_here: false when chi
93
97
  # answer's answer didn't go in (the question was no longer open).
94
98
  def report_extra
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "session"
5
+
6
+ module Samagotchi
7
+ # The files a continue (SessionContinue.run) keeps in the previous link's
8
+ # folder while it runs: LOCK, held for the whole continue, and FILE, its
9
+ # intent (the successor's id), written before the link is archived and
10
+ # removed once the successor is saved or the continue is undone. A send
11
+ # reads them (SessionInbox::Head) to tell a continue in flight from a link
12
+ # nobody continues.
13
+ module ContinueIntent
14
+ # One continue of a session at a time.
15
+ LOCK = "continue.lock"
16
+ # The intent: { successor_id:, previously_archived:, archived_ids: }.
17
+ FILE = "continue.json"
18
+
19
+ module_function
20
+
21
+ # The successor's id of a continue of +id+ in flight: its intent written
22
+ # and its lock held. nil when there is none, or the intent is stale (no
23
+ # continue holds the lock: a crash left it, and
24
+ # SessionContinue.repair_interrupted undoes it) or unreadable.
25
+ # @return [String, nil]
26
+ def in_flight(id, state_dir:)
27
+ return nil unless Session.valid_id?(id)
28
+
29
+ dir = Session.session_dir(id, state_dir: state_dir)
30
+ path = File.join(dir, FILE)
31
+ return nil unless File.file?(path) && locked?(File.join(dir, LOCK))
32
+
33
+ data = JSON.parse(File.read(path))
34
+ successor = data["successor_id"] if data.is_a?(Hash)
35
+ Session.valid_id?(successor) ? successor : nil
36
+ rescue JSON::ParserError, SystemCallError
37
+ nil
38
+ end
39
+
40
+ # Whether a continue holds the lock at +path+: a shared try that fails.
41
+ # The try is let go at once (the file is closed).
42
+ def locked?(path)
43
+ File.open(path, File::RDONLY) { |lock| !lock.flock(File::LOCK_SH | File::LOCK_NB) }
44
+ rescue Errno::ENOENT
45
+ false
46
+ end
47
+ end
48
+ end
@@ -73,6 +73,8 @@ module Samagotchi
73
73
  # @return [Hash, nil] { thinking:, tools: [{ tool:, params:, title:,
74
74
  # output:, output_truncated:, images:, tool_id:, edit: }] } with only what it found; nil for nothing
75
75
  def for_message(message, responses, registry: Tools::Builtins.default, cwd: nil, marks: {})
76
+ return nil unless something?(message)
77
+
76
78
  content = field(message, :content).to_s
77
79
  calls = field(message, :tool_calls)
78
80
  tools = if calls.is_a?(Array) && !calls.empty?
@@ -89,6 +91,17 @@ module Samagotchi
89
91
  nil
90
92
  end
91
93
 
94
+ # Whether +message+ can have parts (.for_message gives none without):
95
+ # a native call, content (its markup calls and thinking are read from
96
+ # it) or thinking. Cheap, nothing parsed: the owner show keeps a
97
+ # text-less step by it (Web::MessageDisplay), the participant review by
98
+ # its parts, so a new kind of part goes here for both.
99
+ def something?(message)
100
+ calls = field(message, :tool_calls)
101
+ (calls.is_a?(Array) && !calls.empty?) || !field(message, :content).to_s.strip.empty? ||
102
+ !field(message, :thinking).to_s.strip.empty?
103
+ end
104
+
92
105
  def thinking_of(content)
93
106
  blocks = content.scan(QWEN_THINK).flatten
94
107
  if blocks.empty? && !content.include?("<think>") && (open = content[QWEN_OPEN_THINK, 1])
@@ -121,12 +121,9 @@ module Samagotchi
121
121
  result.delivered?
122
122
  end
123
123
 
124
- # The id, or for a session that was continued the link that took it.
125
- def where(id, result)
126
- return id[0, 8] unless result.continued?
127
-
128
- "#{id[0, 8]} → #{result.id[0, 8]} (continued)"
129
- end
124
+ # The id, or for a session that was continued the link that took it
125
+ # (chi send's wording too).
126
+ def where(id, result) = SessionInbox::Resolved.label(id, result.id)
130
127
 
131
128
  def outcome(result)
132
129
  case result.status
@@ -173,8 +173,9 @@ module Samagotchi
173
173
  # A failure before any wait (no such session, a busy one, a message
174
174
  # that didn't go in) as the JSON object.
175
175
  # @param session_id [String, nil]
176
- def error_line(detail, session_id: nil)
177
- JSON.generate({ status: "error", session_id: session_id, detail: detail.to_s })
176
+ # @param extra [Hash] more keys after session_id (chi send's asked)
177
+ def error_line(detail, session_id: nil, extra: {})
178
+ JSON.generate({ status: "error", session_id: session_id, **extra, detail: detail.to_s })
178
179
  end
179
180
 
180
181
  # A pending question (Session#pending_question, a PendingQuestion) as a
@@ -24,10 +24,13 @@ module Samagotchi
24
24
  # goes.
25
25
  class ParentGate
26
26
  # @param options [Hash] chi send's parsed options (:new, :continues,
27
- # :parent_answers, :ids)
28
- def initialize(options, state_dir:)
27
+ # :parent_answers)
28
+ # @param ids [Array<String>, nil] the sessions the ids name, as chi send
29
+ # sends to them (a continued one's newest link); nil with --new
30
+ def initialize(options, state_dir:, ids: nil)
29
31
  @options = options
30
32
  @state_dir = state_dir
33
+ @ids = ids
31
34
  end
32
35
 
33
36
  # A /continue yes (or bare /continue) from a parent agent's process.
@@ -69,8 +72,8 @@ module Samagotchi
69
72
  private
70
73
 
71
74
  # The targets' own parent_answers values. An id that doesn't resolve
72
- # is skipped (SendCommand#resolve reports it later); none left is
73
- # config.yml's alone ([nil]).
75
+ # is skipped (SendCommand reports it later); none left is config.yml's
76
+ # alone ([nil]).
74
77
  def target_values
75
78
  @target_values ||= if @options[:new] && !@options[:continues]
76
79
  [@options[:parent_answers]]
@@ -78,7 +81,7 @@ module Samagotchi
78
81
  sessions = if @options[:new]
79
82
  [target_session { SessionChain.resolve(@options[:continues], state_dir: @state_dir) }]
80
83
  else
81
- @options[:ids].map { |given| target_session { Session.resolve_id(given, state_dir: @state_dir) } }
84
+ Array(@ids).map { |id| target_session { id } }
82
85
  end
83
86
  values = sessions.compact.map(&:parent_answers)
84
87
  values.empty? ? [nil] : values
@@ -46,6 +46,14 @@ module Samagotchi
46
46
  MAX_IMAGES = ImageStore::MAX_TURN_REFS
47
47
  # A cut's outcomes in the Bridge's ack (SteerCut#cut_for_steer).
48
48
  CUT_OUTCOMES = %w[now waits off].freeze
49
+ # How long a send to a link being continued waits for the new link to
50
+ # be saved (SessionInbox::Head's :continuing; the spawn is quick), and
51
+ # how often it asks again; then it is refused.
52
+ CONTINUING_WAIT = 10.0
53
+ CONTINUING_POLL = 0.2
54
+
55
+ # The pause between two looks at a continue in flight (a seam for specs).
56
+ def self.pause(seconds) = sleep(seconds)
49
57
 
50
58
  USAGE = <<~TEXT
51
59
  Usage: chi send [-m TEXT] [--image PATH]... [--cut | --queue] (ID|PREFIX)...
@@ -56,7 +64,10 @@ module Samagotchi
56
64
  chi send --wait [--timeout S] [--format json] [--turn T] ID
57
65
  Sends a message to each session, as if typed in it: a turn starts,
58
66
  or a running one takes it at its next step. A stopped session's
59
- worker starts.
67
+ worker starts. A session that was continued: the newest link of its
68
+ chain gets it (OLD → NEW (continued)), and the old link stays
69
+ archived; one being continued right now waits a moment for its new
70
+ link. A chain's first id is a stable address for it.
60
71
  A session command (/model x, !cmd) runs as the command; --wait
61
72
  then has no reply to wait for (exit 0, status command).
62
73
  -m TEXT the message; stdin, when piped too, goes above it as a
@@ -295,7 +306,7 @@ module Samagotchi
295
306
  # check the line chi send's client_id marks; the worker checks a
296
307
  # CLI_ANSWER /continue again).
297
308
  unless @access.remote?
298
- gate = ParentGate.new(options, state_dir: @state_dir)
309
+ gate = ParentGate.new(options, state_dir: @state_dir, ids: (resolved_ids(options) unless options[:new]))
299
310
  if prompt && (refusal = gate.continue_refusal(prompt))
300
311
  @stderr.puts("chi send: #{refusal}")
301
312
  return CLI::Exit::FAILED
@@ -313,15 +324,16 @@ module Samagotchi
313
324
  return run_new(prompt, options) if options[:new]
314
325
  return run_wait(prompt, options) if options[:wait]
315
326
 
316
- # One id at a time, so each line follows the order of the ids given.
327
+ # One id at a time, so each line follows the order of the ids given;
328
+ # two that reach the same link (an old id and its newest link) send
329
+ # once.
317
330
  seen = {}
318
- results = options[:ids].uniq.map do |given|
319
- id = resolve(given)
320
- next false unless id
321
- next true if seen[id]
331
+ results = targets(options).map do |target|
332
+ next unsent(target) unless target.is_a?(SessionInbox::Resolved)
333
+ next true if seen[target.id]
322
334
 
323
- seen[id] = true
324
- deliver(id, prompt)
335
+ seen[target.id] = true
336
+ deliver(target, prompt)
325
337
  end
326
338
  results.all? ? 0 : 1
327
339
  ensure
@@ -583,20 +595,21 @@ module Samagotchi
583
595
  # enqueued_id), whatever runs before it.
584
596
  # @return [Integer] the exit status
585
597
  def run_wait(prompt, options)
586
- id = resolve(options[:ids].first) or return 1
587
- return run_participant_wait(id, prompt, options) if @access.participant?
598
+ target = wait_target(options) or return 1
599
+ id = target.id
600
+ return run_participant_wait(target, prompt, options) if @access.participant?
588
601
 
589
602
  # Local: one read for the check and the baseline; remotely the
590
603
  # server's wait prepare route reads both (Busy's words).
591
604
  session = @access.show(id) unless @access.remote?
592
605
  if (busy = @access.busy(id, queue: @queue, session: session))
593
- error_line("#{id[0, 8]} #{busy.message(via: @access.invocation)}")
606
+ error_line("#{target.label} #{busy.message(via: @access.invocation)}")
594
607
  return 1
595
608
  end
596
609
 
597
610
  start = @access.prepare_wait(id, session: session)
598
- return 1 unless deliver(id, prompt)
599
- return report_command(id) if @sent_command
611
+ return 1 unless deliver(target, prompt)
612
+ return report_command(id, label: target.label) if @sent_command
600
613
 
601
614
  target = ReplyWait::Target.message(start, @delivered, queue: @queue)
602
615
  wait_for_reply(id, target: target, timeout: options[:timeout])
@@ -609,12 +622,13 @@ module Samagotchi
609
622
  # wait routes take only a turn of theirs: the wait is on the one just
610
623
  # queued, as --wait --turn T.
611
624
  # @return [Integer] the exit status
612
- def run_participant_wait(id, prompt, options)
613
- return 1 unless deliver(id, prompt)
625
+ def run_participant_wait(target, prompt, options)
626
+ id = target.id
627
+ return 1 unless deliver(target, prompt)
614
628
 
615
629
  turn = @delivered.enqueued_id.to_s
616
630
  if turn.empty?
617
- error_line("chi send: #{id[0, 8]}: the review turn's id didn't come back; chi --remote … send --wait --turn T waits once you have it")
631
+ error_line("chi send: #{target.label}: the review turn's id didn't come back; chi --remote … send --wait --turn T waits once you have it")
618
632
  return 1
619
633
  end
620
634
  start = @access.prepare_wait(id, turn: turn)
@@ -634,10 +648,17 @@ module Samagotchi
634
648
  # idle in the gap between waits: that turn's end is the answer — its
635
649
  # reply, or its no-reply outcome — so the wait returns it at once
636
650
  # (ReplyWait's ended_before:) instead of timing out "running" again.
651
+ # A continued session's wait is on its newest link, but --turn T of the
652
+ # old link (from before the continue) waits on the old one.
637
653
  # @return [Integer] the exit status
638
654
  def run_wait_only(options)
639
- id = resolve(options[:ids].first) or return 1
655
+ target = wait_target(options) or return 1
640
656
  requested_turn = options[:turn]&.to_s
657
+ id = target.id
658
+ if requested_turn && target.asked != id && @access.prepare_wait(target.asked, turn: requested_turn).known_turn
659
+ @wait_target = target = SessionInbox::Resolved.new(id: target.asked, asked: target.asked, via: :same)
660
+ @session_id = id = target.id
661
+ end
641
662
  start = @access.prepare_wait(id, turn: requested_turn)
642
663
  if requested_turn && !start.known_turn
643
664
  error_line("chi send: turn #{requested_turn} is not a running, queued, or last ended turn")
@@ -708,12 +729,13 @@ module Samagotchi
708
729
  elsif options[:wait]
709
730
  # --wait: the JSON line goes to stdout, @info is stderr; an unknown
710
731
  # or ambiguous id gets resolve's own error line.
711
- id = resolve(options[:ids].first) or return CLI::Exit::FAILED
712
- @stderr.puts("#{id[0, 8]} refused: #{local_refusal(entry.name, id)}")
732
+ target = wait_target(options) or return CLI::Exit::FAILED
733
+ @stderr.puts("#{target.label} refused: #{local_refusal(entry.name, target.id)}")
713
734
  else
714
- options[:ids].uniq.each do |given|
715
- id = resolve(given) or next
716
- @info.puts("#{id[0, 8]} refused: #{local_refusal(entry.name, id)}")
735
+ targets(options).each do |target|
736
+ next unsent(target) unless target.is_a?(SessionInbox::Resolved)
737
+
738
+ @info.puts("#{target.label} refused: #{local_refusal(entry.name, target.id)}")
717
739
  end
718
740
  end
719
741
  CLI::Exit::FAILED
@@ -723,22 +745,25 @@ module Samagotchi
723
745
 
724
746
  # --wait after a message that ran as a session command: no reply comes
725
747
  # for it. Its output shows where the session is open.
748
+ # @param label [String] how the line names it (a chain's label, #target)
726
749
  # @return [Integer] 0
727
- def report_command(id)
750
+ def report_command(id, label: id[0, 8])
728
751
  detail = "#{SENT_COMMAND}: no reply to wait for (its output shows in #{@access.invocation.open_it(id)})"
729
752
  if @json
730
- @stdout.puts(JSON.generate({ status: "command", session_id: id, detail: detail }))
753
+ @stdout.puts(JSON.generate({ status: "command", session_id: id, **asked_extra, detail: detail }))
731
754
  @stdout.flush
732
755
  @reported = true
733
756
  else
734
- @stderr.puts("#{id[0, 8]} #{detail}")
757
+ @stderr.puts("#{label} #{detail}")
735
758
  end
736
759
  CLI::Exit::OK
737
760
  end
738
761
 
762
+ # @param target [SessionInbox::Resolved] the session (#target)
739
763
  # @return [Boolean] whether the message was queued
740
- def deliver(id, prompt)
741
- short = id[0, 8]
764
+ def deliver(target, prompt)
765
+ id = target.id
766
+ short = target.label
742
767
  session = @access.show(id)
743
768
  # Machine-local (this machine's model registry): remotely the
744
769
  # server's (P2), as for --new.
@@ -776,7 +801,7 @@ module Samagotchi
776
801
  @sent_delivery = result.delivery || delivery
777
802
  @sent_cut = result.cut
778
803
  note = if @access.participant? then participant_note(id, result)
779
- else delivery_note(result, delivery: delivery, running: running, owner: owner)
804
+ else delivery_note(id, result, delivery: delivery, running: running, owner: owner)
780
805
  end
781
806
  @info.puts("#{short} sent#{with_images}#{note}")
782
807
  true
@@ -795,12 +820,14 @@ module Samagotchi
795
820
  # running turn's next step (nothing cuts by default); a --cut one names
796
821
  # the outcome from the ack (now, waits, off); a --queue one runs after
797
822
  # the turn (or now, when the turn ended before it went in); images keep
798
- # their own wording; an idle session's turn simply runs.
823
+ # their own wording; an idle session's turn simply runs. A link reached
824
+ # after waiting on its continue (#target) has the continue's own spawn
825
+ # starting its worker: no worker yet doesn't mean this send started it.
799
826
  # @param result [SessionManager::DeliverResult] the accepted delivery
800
827
  # (its ack is {} for the input file)
801
828
  # @return [String] "" or " (...)"
802
- def delivery_note(result, delivery:, running:, owner:)
803
- return " (started its worker)" if owner.nil?
829
+ def delivery_note(id, result, delivery:, running:, owner:)
830
+ return " (started its worker)" if owner.nil? && !@continued_here&.key?(id)
804
831
  return queue_note(result, running: running) if Delivery.queue?(delivery)
805
832
  return "" unless running
806
833
  # A participant's review turn was running: the worker queued it.
@@ -844,14 +871,92 @@ module Samagotchi
844
871
  # unchanged otherwise): the delivery the worker applied (next_step to
845
872
  # an idle session) and a cut's outcome (now, waits, off). --cut --wait
846
873
  # is refused for a running turn, so its json line says next_step.
874
+ # A continued session's names the id asked too (asked_extra).
847
875
  def report_extra
848
- return {} unless @cut || @queue
876
+ return asked_extra unless @cut || @queue
849
877
 
850
- extra = { delivery: @sent_delivery || Delivery::NEXT_STEP }
878
+ extra = asked_extra.merge(delivery: @sent_delivery || Delivery::NEXT_STEP)
851
879
  extra[:cut] = @sent_cut if @sent_cut
852
880
  extra
853
881
  end
854
882
 
883
+ # The sessions the ids name, each once and in the order given, resolved
884
+ # once up front (#target): what ParentGate checks, what the message
885
+ # goes to, what --wait waits on.
886
+ # @return [Array<SessionInbox::Resolved, Unsent>]
887
+ def targets(options)
888
+ @targets ||= options[:ids].uniq.map { |given| target(given) }
889
+ end
890
+
891
+ # The targets' ids, for ParentGate (one that names none is skipped:
892
+ # its line comes where it is sent).
893
+ def resolved_ids(options) = targets(options).grep(SessionInbox::Resolved).map(&:id)
894
+
895
+ # --wait's one target, kept for the JSON lines (@session_id: its id;
896
+ # asked_extra); nil after its line (an Unsent is kept too: a continue
897
+ # in flight's refusal names the id asked).
898
+ # @return [SessionInbox::Resolved, nil]
899
+ def wait_target(options)
900
+ target = targets(options).first
901
+ @wait_target = target
902
+ unless target.is_a?(SessionInbox::Resolved)
903
+ unsent(target)
904
+ return nil
905
+ end
906
+
907
+ @session_id = target.id
908
+ @wait_target = target
909
+ end
910
+
911
+ # The --format json line's asked, whatever the end once the id given
912
+ # resolved (an answer, a refusal, an error): that id, when it is not
913
+ # the line's session_id (the wait is on a later link of its chain, or a
914
+ # continue in flight refused it before there was one); {} otherwise.
915
+ def asked_extra
916
+ asked = @wait_target&.asked
917
+ asked && asked != @session_id ? { asked: asked } : {}
918
+ end
919
+
920
+ # ParentWait's error line: asked too (asked_extra).
921
+ def error_extra = asked_extra
922
+
923
+ # An id given that names no session to send to, and the line that says
924
+ # why: an error line (no such session, a prefix of several) or a
925
+ # refusal on the info stream (a continue in flight: +asked+ the full id
926
+ # given, nil for the others).
927
+ Unsent = Data.define(:line, :error, :asked) do
928
+ def initialize(line:, error:, asked: nil) = super
929
+ end
930
+
931
+ # +given+'s session (an id or a prefix), then where input for it goes
932
+ # (SessionAccess#head): a continued session's chain's newest link. A
933
+ # continue of it in flight (:continuing: the new link not saved yet)
934
+ # is asked again for up to CONTINUING_WAIT, then refused; the old link
935
+ # is never sent to (a send would un-archive it beside the new one).
936
+ # @return [SessionInbox::Resolved, Unsent]
937
+ def target(given)
938
+ id = @access.resolve(given)
939
+ head = @access.head(id)
940
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + self.class::CONTINUING_WAIT
941
+ waited = head.continuing?
942
+ while head.continuing? && Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
943
+ self.class.pause(self.class::CONTINUING_POLL)
944
+ head = @access.head(id)
945
+ end
946
+ return Unsent.new(line: "#{id[0, 8]} refused: #{head.continuing_refusal}", error: false, asked: id) if head.continuing?
947
+
948
+ (@continued_here ||= {})[head.id] = true if waited
949
+ head
950
+ rescue ArgumentError => e
951
+ Unsent.new(line: "#{command_name}: #{e.message}", error: true)
952
+ end
953
+
954
+ # Prints +unsent+'s line. @return [false]
955
+ def unsent(unsent)
956
+ unsent.error ? error_line(unsent.line) : @info.puts(unsent.line)
957
+ false
958
+ end
959
+
855
960
  # What to say when +model_name+ is known not to take images, or nil
856
961
  # (it does, or it is unknown: sent as before). Asked once per model.
857
962
  def vision_refusal(model_name, typed: nil)
@@ -81,6 +81,12 @@ module Samagotchi
81
81
  # @raise [ArgumentError] no such session
82
82
  def show(id) = Session.load(id, **dir)
83
83
 
84
+ # Where input for +id+ goes: its chain's newest link when it was
85
+ # continued (SessionInbox::Head's send walk; :continuing while a
86
+ # continue of it is in flight), else +id+.
87
+ # @return [SessionInbox::Resolved]
88
+ def head(id) = SessionInbox::Head.resolve(:send, id, state_dir: state_dir!)
89
+
84
90
  # @return [OwnerLock::Owner, nil] the worker or one-turn chi run that owns it
85
91
  def owner(id) = SessionManager.session_owner(id, **dir)
86
92
 
@@ -7,6 +7,7 @@ require_relative "../remotes"
7
7
  require_relative "../reply_wait"
8
8
  require_relative "../pending_question"
9
9
  require_relative "../note_delivery"
10
+ require_relative "../session_inbox"
10
11
  require_relative "../owner_lock"
11
12
  require_relative "../context_sources"
12
13
  require_relative "../bridge_client"
@@ -147,6 +148,30 @@ module Samagotchi
147
148
  id
148
149
  end
149
150
 
151
+ # Where input for +id+ goes, as chi web resolves it there
152
+ # (Local#head): GET /api/sessions/resolve?id=X&head=1. An older chi
153
+ # web ignores head=1 and answers {id}, and a refusal (the session
154
+ # gone since) is the send's to report: +id+ itself (:same, as before
155
+ # it followed). A participant never
156
+ # asks: their grant is for one session (:pinned).
157
+ # @return [SessionInbox::Resolved]
158
+ def head(id)
159
+ return SessionInbox::Resolved.new(id: id, asked: id, via: :pinned) if participant?
160
+
161
+ same = SessionInbox::Resolved.new(id: id, asked: id, via: :same)
162
+ reply = request(:get, "/api/sessions/resolve", query: { id: id.to_s, head: 1 })
163
+ return same unless reply.status == 200
164
+
165
+ json = reply.json
166
+ via = HEAD_VIAS[json["via"]] if json.is_a?(Hash)
167
+ return same unless via && Session.valid_id?(json["id"])
168
+
169
+ SessionInbox::Resolved.new(id: json["id"], asked: id, via: via)
170
+ end
171
+
172
+ # The ways resolve?head=1 answers (SessionInbox::Resolved#via).
173
+ HEAD_VIAS = { "same" => :same, "head" => :head, "continuing" => :continuing }.freeze
174
+
150
175
  # @return [SessionView]
151
176
  # @raise [ArgumentError] no such session
152
177
  def show(id)
@@ -14,6 +14,7 @@ require_relative "starting_marker"
14
14
  require_relative "context_move"
15
15
  require_relative "note_move"
16
16
  require_relative "archive_store"
17
+ require_relative "continue_intent"
17
18
  require_relative "recap_store"
18
19
  require_relative "bridge_client"
19
20
  require_relative "worker_link"
@@ -59,9 +60,10 @@ module Samagotchi
59
60
  # recap (IdleRecap's own request timeout).
60
61
  RECAP_WAIT = 30.0
61
62
  # In the previous link's folder: one continue of a session at a time.
62
- LOCK = "continue.lock"
63
- # A durable record in the previous link's folder, written before archive.
64
- CONTINUE_INTENT = "continue.json"
63
+ LOCK = ContinueIntent::LOCK
64
+ # A durable record in the previous link's folder, written before archive
65
+ # (a send in flight reads it: ContinueIntent.in_flight).
66
+ CONTINUE_INTENT = ContinueIntent::FILE
65
67
  # How often a last:<id> continue looks again when another continue
66
68
  # moved the chain's end while it waited for the lock.
67
69
  TRIES = 3
@@ -4,6 +4,7 @@ require_relative "session"
4
4
  require_relative "session_inbox"
5
5
  require_relative "archive_store"
6
6
  require_relative "worker_presence"
7
+ require_relative "continue_intent"
7
8
 
8
9
  module Samagotchi
9
10
  # Loaded on first use: this autoload keeps SessionManager and its ~80
@@ -18,9 +19,28 @@ module Samagotchi
18
19
  # (spec/samagotchi/testing/sandbox_spec.rb) stays as it was.
19
20
  module SessionInbox
20
21
  # Where a delivery for +asked+ goes: +id+, reached +via+ :pinned (the
21
- # kind never follows a chain), :same (followed, nothing to follow) or
22
- # :head (a later link of +asked+'s chain).
23
- Resolved = Data.define(:id, :asked, :via)
22
+ # kind never follows a chain), :same (followed, nothing to follow),
23
+ # :head (a later link of +asked+'s chain) or :continuing (a send whose
24
+ # link is being continued: +id+ is the successor, not saved yet; the
25
+ # sender asks again in a moment, Head.resolve).
26
+ Resolved = Data.define(:id, :asked, :via) do
27
+ # How a line names where it went: +asked+'s short id, or
28
+ # "OLD → NEW (continued)" when a later link took it (chi send's and
29
+ # chi note's one wording).
30
+ def self.label(asked, id)
31
+ return asked[0, 8] if asked == id
32
+
33
+ "#{asked[0, 8]} → #{id[0, 8]} (continued)"
34
+ end
35
+
36
+ def label = Resolved.label(asked, id)
37
+
38
+ def continuing? = via == :continuing
39
+
40
+ # The refusal of a send whose link is still being continued once the
41
+ # sender's wait is over.
42
+ def continuing_refusal = "being continued as #{id[0, 8]}; send again in a moment"
43
+ end
24
44
 
25
45
  # A delivery's outcome.
26
46
  # @!attribute kind [Symbol] the WakePolicy row
@@ -105,8 +125,15 @@ module Samagotchi
105
125
  private def scratch?(load) = load ? load.call.scratch == true : false
106
126
  end
107
127
 
128
+ # A send follows a chain as a note does: input for a continued link
129
+ # goes to its chain's newest link (chi send resolves it once up front,
130
+ # SessionAccess#head; SessionManager.deliver_turn resolves nothing).
131
+ # What stays on the id it names doesn't ask Head: the web composer (a
132
+ # person on that page means that session), a participant's grant (one
133
+ # session), delegate follow-ups, Plugin::Sessions and Schedules (their
134
+ # own rule).
108
135
  WakePolicy::ROWS = {
109
- send: WakePolicy.new(kind: :send, resolves: :pinned, starts: true, unstops: true, starts_archived: true,
136
+ send: WakePolicy.new(kind: :send, resolves: :head, starts: true, unstops: true, starts_archived: true,
110
137
  refuse_tui: true, refuse_scratch: true),
111
138
  note: WakePolicy.new(kind: :note, resolves: :head, starts: false, unstops: false, starts_archived: false,
112
139
  refuse_tui: true, refuse_scratch: true),
@@ -133,12 +160,22 @@ module Samagotchi
133
160
  # Else the walk forward over archived links that have a successor:
134
161
  # to the first link not archived, or the last (a loop a hand-edited
135
162
  # file could make ends where it started); a :reader kind goes one hop
136
- # at most.
163
+ # at most. Then, for a kind that would un-archive the link it reaches
164
+ # (a send: WakePolicy#starts_archived), a continue of that link in
165
+ # flight (ContinueIntent.in_flight: its successor not saved yet) gives
166
+ # :continuing, the successor's id. A note needs no such check: written
167
+ # to the link before NoteMove.move it moves, after it the new link's
168
+ # worker adopts it (NoteMove.adoption).
137
169
  # @return [Resolved]
138
170
  def resolve(kind, id, state_dir:)
139
- how = WakePolicy.for(kind).resolves
140
- return Resolved.new(id: id, asked: id, via: :pinned) if how == :pinned
171
+ policy = WakePolicy.for(kind)
172
+ return Resolved.new(id: id, asked: id, via: :pinned) if policy.resolves == :pinned
173
+
174
+ resolved = walk(policy.resolves, id, state_dir)
175
+ (continuing(resolved, state_dir) if policy.starts_archived) || resolved
176
+ end
141
177
 
178
+ def walk(how, id, state_dir)
142
179
  same = Resolved.new(id: id, asked: id, via: :same)
143
180
  return same unless archived?(id, state_dir)
144
181
 
@@ -151,6 +188,16 @@ module Samagotchi
151
188
  seen.size == 1 ? same : Resolved.new(id: seen.last, asked: id, via: :head)
152
189
  end
153
190
 
191
+ # +resolved+'s link being continued, its successor not saved yet: the
192
+ # successor, via :continuing; else nil (none in flight, or saved: the
193
+ # walk reached it).
194
+ def continuing(resolved, state_dir)
195
+ successor = ContinueIntent.in_flight(resolved.id, state_dir: state_dir)
196
+ return nil if successor.nil? || Session.exist?(successor, state_dir: state_dir)
197
+
198
+ Resolved.new(id: successor, asked: resolved.asked, via: :continuing)
199
+ end
200
+
154
201
  def archived?(id, state_dir)
155
202
  Session.valid_id?(id) && ArchiveStore.archived?(Session.session_dir(id, state_dir: state_dir))
156
203
  end
@@ -225,7 +225,9 @@ module Samagotchi
225
225
 
226
226
  # deliver_turn's two liveness checks, on the session inbox's send row
227
227
  # (SessionInbox::WakePolicy: send un-stops and starts an archived
228
- # link; it is pinned to the id it names): resume_session unless a
228
+ # link). The row follows a chain, deliver_turn doesn't: it acts on
229
+ # the id it is given, and a caller that follows (chi send) resolves
230
+ # the head first (SessionAccess#head): resume_session unless a
229
231
  # worker holds the session or one is being started. Its refusals (no
230
232
  # session, a one-turn run's, a scratch one) are resume_session's to
231
233
  # raise, in their one wording: +before+ the write, a session it would
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.163.0"
4
+ VERSION = "0.164.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -161,7 +161,7 @@ module Samagotchi
161
161
  stripped = Samagotchi::OutputFormatter.strip_markup(content)
162
162
  step = %w[model assistant].include?(role)
163
163
  did = parts && step ? message_parts(list, index, cwd, marks) : nil
164
- next if stripped.empty? && did.nil? && !(steps && step && did_something?(m, content))
164
+ next if stripped.empty? && did.nil? && !(steps && step && MessageParts.something?(m))
165
165
 
166
166
  norm_role = role == "model" ? "assistant" : role
167
167
  # normalize assistant vs model, keep user as is
@@ -234,14 +234,6 @@ module Samagotchi
234
234
  []
235
235
  end
236
236
 
237
- # Whether a text-less model message did something a drawing draws as
238
- # a step: a call or thinking (MessageParts' own read, without
239
- # parsing the calls).
240
- def did_something?(message, content)
241
- calls = message[:tool_calls] || message["tool_calls"]
242
- (calls.is_a?(Array) && !calls.empty?) || !content.strip.empty? || !(message[:thinking] || message["thinking"]).to_s.strip.empty?
243
- end
244
-
245
237
  # The ✂ marks of the outputs right after the model message at +index+,
246
238
  # by output id, as its parts have them (a stub's size from its own
247
239
  # output): its parts are read only when +marks+ (the session's, by
@@ -1 +1 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect x="1" y="1" width="30" height="30" rx="7.5" fill="#22262f"/><g fill="none" stroke="#0a84ff" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.8 9.6c2.3-1.3 4-.7 5.2 1.4l6 10.1c1.2 2.1 2.9 2.7 5.2 1.4"/><path d="M22.6 9.2 9.4 22.8"/></g></svg>
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect x="1" y="1" width="30" height="30" rx="7.5" fill="#22262f"/><path fill="#fff" d="M23.3 8.12L22.94 8.25L22.58 8.38L22.23 8.52L21.89 8.66L21.56 8.82L21.25 8.99L20.95 9.16L20.66 9.35L20.39 9.55L20.13 9.77L19.88 9.99L19.65 10.23L19.43 10.48L19.23 10.74L19.03 11.01L18.83 11.27L18.63 11.54L18.44 11.81L18.24 12.07L18.04 12.34L17.83 12.6L17.63 12.87L17.43 13.13L17.23 13.4L17.02 13.66L16.82 13.92L16.61 14.18L16.41 14.45L16.2 14.71L15.99 14.97L15.78 15.23L15.57 15.49L15.37 15.75L15.15 16.01L14.94 16.26L14.73 16.52L14.52 16.78L14.31 17.04L14.09 17.29L13.88 17.55L13.66 17.8L13.45 18.06L13.23 18.31L13.01 18.57L12.8 18.82L12.58 19.07L12.36 19.33L12.14 19.58L11.92 19.83L11.7 20.08L11.48 20.33L11.25 20.58L11.03 20.83L10.81 21.08L10.58 21.32L10.36 21.57L10.13 21.82L9.9 22.06L9.67 22.3L9.44 22.55L9.21 22.79L8.98 23.03L8.75 23.27L8.51 23.51L8.69 23.69L8.94 23.47L9.19 23.26L9.45 23.04L9.71 22.83L9.96 22.61L10.22 22.4L10.48 22.18L10.73 21.97L10.99 21.75L11.25 21.54L11.51 21.32L11.77 21.11L12.02 20.9L12.28 20.68L12.54 20.47L12.8 20.25L13.05 20.04L13.31 19.82L13.57 19.6L13.83 19.39L14.08 19.17L14.34 18.95L14.6 18.74L14.85 18.52L15.11 18.3L15.36 18.08L15.62 17.86L15.88 17.64L16.13 17.42L16.39 17.2L16.64 16.98L16.9 16.76L17.15 16.54L17.4 16.32L17.66 16.1L17.91 15.88L18.17 15.65L18.42 15.43L18.67 15.21L18.92 14.98L19.18 14.76L19.43 14.53L19.68 14.31L19.93 14.08L20.18 13.85L20.43 13.63L20.68 13.4L20.93 13.17L21.18 12.94L21.43 12.71L21.67 12.48L21.9 12.23L22.11 11.96L22.31 11.69L22.49 11.4L22.66 11.1L22.81 10.78L22.94 10.46L23.07 10.12L23.17 9.77L23.27 9.41L23.35 9.04L23.43 8.66L23.5 8.28Z"/><path fill="#fff" stroke="#22262f" stroke-width="1.7" stroke-linejoin="round" paint-order="stroke" d="M6.28 10.12L6.76 10.1L7.2 10.05L7.61 10.02L8 10L8.37 10.01L8.72 10.05L9.03 10.12L9.31 10.22L9.55 10.34L9.77 10.48L9.96 10.64L10.13 10.82L10.3 11.01L10.46 11.22L10.62 11.45L10.77 11.7L10.92 11.97L11.06 12.25L11.2 12.55L11.4 12.94L11.59 13.32L11.8 13.69L12 14.06L12.21 14.43L12.42 14.8L12.64 15.17L12.86 15.53L13.09 15.89L13.32 16.25L13.55 16.6L13.79 16.95L14.03 17.31L14.28 17.65L14.52 18L14.77 18.35L15.03 18.69L15.29 19.03L15.55 19.37L15.81 19.71L16.07 20.04L16.34 20.38L16.61 20.71L16.88 21.04L17.16 21.37L17.43 21.7L17.74 22.07L18.09 22.45L18.48 22.81L18.91 23.15L19.37 23.45L19.86 23.69L20.39 23.88L20.93 23.99L21.47 24.03L21.99 24L22.48 23.91L22.95 23.76L23.39 23.58L23.8 23.37L24.19 23.12L24.54 22.84L24.93 22.65L25.31 22.44L25.68 22.23L25.52 21.97L25.16 22.18L24.79 22.38L24.41 22.56L23.98 22.61L23.57 22.65L23.16 22.67L22.77 22.67L22.4 22.62L22.04 22.55L21.72 22.43L21.43 22.28L21.17 22.11L20.94 21.9L20.74 21.67L20.55 21.41L20.39 21.14L20.24 20.84L20.11 20.52L19.97 20.17L19.81 19.77L19.64 19.38L19.47 18.98L19.3 18.59L19.13 18.19L18.96 17.8L18.78 17.41L18.6 17.03L18.42 16.64L18.23 16.25L18.05 15.87L17.85 15.49L17.66 15.11L17.46 14.74L17.26 14.36L17.05 13.99L16.84 13.62L16.63 13.25L16.41 12.89L16.19 12.53L15.97 12.17L15.74 11.81L15.5 11.45L15.26 11.1L15.02 10.75L14.77 10.41L14.47 9.99L14.12 9.58L13.74 9.18L13.32 8.8L12.86 8.45L12.35 8.14L11.8 7.87L11.22 7.67L10.61 7.55L9.99 7.5L9.39 7.55L8.82 7.67L8.29 7.86L7.81 8.1L7.38 8.38L6.99 8.7L6.65 9.05L6.35 9.43L6.12 9.88Z"/></svg>
@@ -36,12 +36,15 @@ export const STYLESHEET = "/assets/widgets.css";
36
36
  export const TOGGLE_PICTURE = "Show the widget";
37
37
 
38
38
  // widgets.css as a constructable sheet, fetched once per page; a failed fetch
39
- // draws unstyled and is tried again by the next draw.
39
+ // draws unstyled and is tried again by the next draw. An answer that isn't CSS
40
+ // (an auth proxy's 200 login page) counts as failed.
40
41
  let shared = null;
41
42
  export function loadWidgetSheet(win = window) {
42
43
  shared ??= win.fetch(STYLESHEET, { headers: { Accept: "text/css" } })
43
44
  .then((res) => {
44
45
  if (!res.ok) throw new Error(`widgets.css answered ${res.status}`);
46
+ const type = res.headers.get("content-type") || "";
47
+ if (!type.startsWith("text/css")) throw new Error(`widgets.css answered ${type || "no Content-Type"}`);
45
48
  return res.text();
46
49
  })
47
50
  .catch((e) => {
@@ -2,7 +2,8 @@
2
2
  // one step at a time. On top a swimlane, one column per actor and one row per
3
3
  // step (the current, the seen and a case's target marked; a click jumps); under
4
4
  // it the step's card (the actor, what it does, "You see", the dashed "Behind
5
- // it"); a fork asks "Which case?" instead of Next; Back, Next and the path
5
+ // it"); a fork asks "Which case?" instead of Next (beside it when every case
6
+ // loops back); Back, Next and the path
6
7
  // taken, and the arrow keys while the widget has the focus. Ported from eval
7
8
  // 0013's viewer.
8
9
  //
@@ -30,6 +31,10 @@ const isAlways = (when) => ALWAYS.test(String(when ?? "").trim());
30
31
  // step), or null when k is no fork. A case that is no condition reads as
31
32
  // the usual path, and a step that names a next as well offers it first when
32
33
  // no case goes there (round 1's next + branches).
34
+ // - hasNext(k): whether Next shows at k: no fork, or a fork none of whose
35
+ // cases moves on (each loops back, a retry from an earlier step or its own,
36
+ // or names no step). Its unwritten usual path is then nextOf(k): the step
37
+ // below, or Start over at the end; without it the walk would be stuck there.
33
38
  export function walkRoutes(walk) {
34
39
  const steps = walk?.steps || [];
35
40
  const byId = new Map(steps.map((s, k) => [String(s.id), k]));
@@ -55,7 +60,12 @@ export function walkRoutes(walk) {
55
60
  return cases;
56
61
  }
57
62
 
58
- return { steps, nextOf, casesOf };
63
+ function hasNext(k) {
64
+ const cases = casesOf(k);
65
+ return !cases || !cases.some((c) => c.to != null && c.to > k);
66
+ }
67
+
68
+ return { steps, nextOf, casesOf, hasNext };
59
69
  }
60
70
 
61
71
  // The swimlane's cells: one per step, in its actor's column (1-based, after
@@ -121,7 +131,7 @@ function button(doc, className, text) {
121
131
  // The walk as an element, for a widget host's shadow root.
122
132
  export function drawWalk(walk, doc = document) {
123
133
  const routes = walkRoutes(walk);
124
- const { steps, nextOf, casesOf } = routes;
134
+ const { steps, nextOf, casesOf, hasNext } = routes;
125
135
  const actors = (walk.actors || []).map(String);
126
136
  const walker = createWalker(routes);
127
137
 
@@ -221,7 +231,7 @@ export function drawWalk(walk, doc = document) {
221
231
  });
222
232
  count.textContent = `step ${k + 1} of ${steps.length}`;
223
233
  prev.disabled = walker.path.length < 2;
224
- next.hidden = !!cases;
234
+ next.hidden = !hasNext(k);
225
235
  next.textContent = nextOf(k) == null ? "Start over" : "Next →";
226
236
  trail.textContent = trailText(walker.path);
227
237
  if (hadFocus && (!focused.isConnected || focused.hidden || focused.disabled)) box.focus({ preventScroll: true });
@@ -76,12 +76,19 @@ module Samagotchi
76
76
  # GET /api/sessions/resolve?id=PREFIX: the full id of the session an id
77
77
  # or a unique prefix names (SessionAccess::Local#resolve). 200 {id};
78
78
  # 404 not_found; 400 ambiguous_id with ids (the sessions it names).
79
+ # With head=1 (the owner's alone: a participant's answer stays {id}),
80
+ # where input for it goes (SessionAccess::Local#head): 200 {id, asked,
81
+ # via}, id the chain's newest link of a continued one.
79
82
  def handle_resolve(req)
80
83
  given = req.params["id"].to_s
81
84
  return session_not_found(given) unless Session.valid_id?(given)
82
85
  return participant_resolve(principal(req).grant, given) unless principal(req).owner?
83
86
 
84
- json_response(200, { id: session_access.resolve(given) })
87
+ id = session_access.resolve(given)
88
+ return json_response(200, { id: id }) unless truthy_param?(req.params["head"])
89
+
90
+ head = session_access.head(id)
91
+ json_response(200, { id: head.id, asked: head.asked, via: head.via.to_s })
85
92
  rescue Session::AmbiguousId => e
86
93
  refusal_response(400, "ambiguous_id", e, ids: e.ids)
87
94
  rescue ArgumentError # NotFound, a file that won't load
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: samagotchi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.163.0
4
+ version: 0.164.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -341,6 +341,7 @@ files:
341
341
  - lib/samagotchi/context_status.rb
342
342
  - lib/samagotchi/context_usage.rb
343
343
  - lib/samagotchi/context_window.rb
344
+ - lib/samagotchi/continue_intent.rb
344
345
  - lib/samagotchi/continue_offer.rb
345
346
  - lib/samagotchi/cut.rb
346
347
  - lib/samagotchi/cut_policy.rb