samagotchi 0.190.1 → 0.191.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +22 -1
- data/docs/architecture.md +8 -7
- data/docs/cli.md +6 -3
- data/docs/context.md +8 -1
- data/docs/internals/attached-context.md +3 -1
- data/docs/internals/peers.md +15 -3
- data/docs/internals/remote-sessions.md +2 -2
- data/docs/internals/session-lifecycle.md +213 -12
- data/docs/peers.md +3 -1
- data/docs/plugins.md +2 -1
- data/docs/scheduling.md +24 -6
- data/docs/sessions.md +10 -10
- data/docs/sub-agent.md +1 -1
- data/lib/samagotchi/bridge.rb +1 -1
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/context_command.rb +5 -1
- data/lib/samagotchi/context_sources.rb +28 -0
- data/lib/samagotchi/continue_intent.rb +23 -43
- data/lib/samagotchi/hold_stop.rb +5 -2
- data/lib/samagotchi/participants.rb +13 -5
- data/lib/samagotchi/peer_say.rb +29 -14
- data/lib/samagotchi/plugin/sessions.rb +9 -5
- data/lib/samagotchi/schedule_command.rb +5 -1
- data/lib/samagotchi/schedules/prune_part.rb +130 -41
- data/lib/samagotchi/schedules.rb +18 -6
- data/lib/samagotchi/send_command.rb +6 -6
- data/lib/samagotchi/session_access/ask.rb +9 -3
- data/lib/samagotchi/session_access/exchange.rb +6 -2
- data/lib/samagotchi/session_access/local.rb +103 -32
- data/lib/samagotchi/session_access/remote.rb +10 -9
- data/lib/samagotchi/session_access/remote_peers.rb +2 -2
- data/lib/samagotchi/session_access.rb +17 -7
- data/lib/samagotchi/session_chain/delete.rb +100 -47
- data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
- data/lib/samagotchi/session_chain/successor.rb +78 -0
- data/lib/samagotchi/session_continue.rb +105 -42
- data/lib/samagotchi/session_inbox.rb +1 -1
- data/lib/samagotchi/session_inbox_delivery.rb +111 -25
- data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
- data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
- data/lib/samagotchi/session_lifecycle.rb +13 -2
- data/lib/samagotchi/session_manager/delivery.rb +61 -23
- data/lib/samagotchi/session_manager/emptiness.rb +5 -2
- data/lib/samagotchi/session_manager/lifecycle.rb +50 -14
- data/lib/samagotchi/session_manager/removal.rb +65 -13
- data/lib/samagotchi/session_manager/spawn.rb +14 -6
- data/lib/samagotchi/session_retention.rb +28 -7
- data/lib/samagotchi/session_transition.rb +315 -0
- data/lib/samagotchi/sessions_command.rb +1 -1
- data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +10 -2
- data/lib/samagotchi/web/peer_routes.rb +5 -2
- data/lib/samagotchi/web/session_access_routes.rb +5 -2
- data/lib/samagotchi/web/session_control.rb +6 -1
- data/lib/samagotchi/web/session_create.rb +1 -1
- data/lib/samagotchi/worker_boot.rb +28 -6
- metadata +3 -1
data/docs/scheduling.md
CHANGED
|
@@ -173,8 +173,12 @@ are the refusals that mean "not this moment": `ArchiveRefused` with `busy`, `que
|
|
|
173
173
|
or `offer`, or `busy_child`/`queued_child`/`offer_child` (a chain's own running
|
|
174
174
|
delegate refuses the archive, since `archivable!` walks the whole descendant tree),
|
|
175
175
|
`SessionContinue::Refused(:continued)` (a human continued it while we were
|
|
176
|
-
resolving)
|
|
177
|
-
|
|
176
|
+
resolving), `:open_children` and `:transition_busy` (another continue of the
|
|
177
|
+
chain's end held its transition lock past the continue's 10 s on each of its tries), and a
|
|
178
|
+
same-mode turn its target's transition lock refused (`transition_busy`, or `link_continued` naming a
|
|
179
|
+
continue's new link: the turn's own hold, nothing written).
|
|
180
|
+
So is an archived target that a continue is still
|
|
181
|
+
making the next link of (`session 3f9a1c2e is being continued as 7b2d41aa-…; retry at the next tick`): a
|
|
178
182
|
person's `chi send --new --continues` or web `continue →` archives the link before
|
|
179
183
|
its successor is saved, and a tick in that moment sees an archived end
|
|
180
184
|
(`ContinueIntent.in_flight`: the intent written, its lock held). It is checked before
|
|
@@ -277,8 +281,10 @@ is refused with exit 2, naming the matches.
|
|
|
277
281
|
The tick's lock covers the file only, never the action: the clock advances before
|
|
278
282
|
the work starts — for `every` and `weekday` to the next occurrence, for a `date`
|
|
279
283
|
one-off to none — so a tick killed mid-continue cannot fire the same entry twice.
|
|
280
|
-
If a later tick finds a firing older than
|
|
281
|
-
counts an `interrupted` failure
|
|
284
|
+
If a later tick finds a firing older than 70 seconds without an accepted turn, it
|
|
285
|
+
counts an `interrupted` failure (a chain firing's continue can wait 30 s for the
|
|
286
|
+
recap, 10 s for the transition lock on each of its three tries, 5 s for the
|
|
287
|
+
archive). This 70-second limit covers only the firing
|
|
282
288
|
step, not an accepted turn or its pending question. The action may already have
|
|
283
289
|
taken effect before the process died, so that occurrence is not replayed; a
|
|
284
290
|
`date` one-off stays disabled with the failure visible, and recurring schedules
|
|
@@ -388,8 +394,20 @@ whole subtree only when every session in it is archived and no worker owns any o
|
|
|
388
394
|
it, deepest child first and the link last, oldest link first. The delete itself is
|
|
389
395
|
`SessionManager.delete_ids` (the prune keeps its own checks and log tags): each id
|
|
390
396
|
through `delete_session`, and System 1's saved runs and the candidate log purged once
|
|
391
|
-
per link's batch, not once per session.
|
|
392
|
-
|
|
397
|
+
per link's batch, not once per session. Each link goes under the transition
|
|
398
|
+
locks of it and the link after it (`SessionTransition`, one try, kind `delete`).
|
|
399
|
+
**A link that can't go now holds the prune there**: one not archived (brought back
|
|
400
|
+
by hand), one whose subtree holds a schedule's anchor, head or target (another
|
|
401
|
+
enabled schedule anchored inside the chain, as `schedule_task` from a link does), a
|
|
402
|
+
live worker or an unarchived descendant in its subtree, or its or the next link's
|
|
403
|
+
transition lock held (a send, a continue, a delete). The prune stops below it: that
|
|
404
|
+
link and every newer one stay, and nothing is deleted around it. The entry records
|
|
405
|
+
where it waits (`prune_waiting` in schedules.json: link, reason, since when; no
|
|
406
|
+
history row), `chi schedule list` adds `pruning held at <id>` to the row and `show` a
|
|
407
|
+
line `pruning held at <id>: <reason> (since …)`, the log says `prune_waiting` once
|
|
408
|
+
per link (not every tick), and every tick tries again, not only after a firing; once
|
|
409
|
+
it gets past, the record goes. A schedule anchored inside the chain holds it until
|
|
410
|
+
that schedule is cancelled. Pruning a link alone would leave its finished
|
|
393
411
|
delegates archived forever with a dangling `parent_id`: archiving a session archives
|
|
394
412
|
its descendants, and archived sessions are outside the retention sweep
|
|
395
413
|
([sessions.md](sessions.md)), so the delegate pile is the bulk of the archived
|
data/docs/sessions.md
CHANGED
|
@@ -31,19 +31,19 @@ unread messages reach the new link as one note); a delete removes them. See
|
|
|
31
31
|
| `SAMAGOTCHI_SESSION_KEEP_STATUS` | (none) | CSV of statuses never auto-pruned |
|
|
32
32
|
| `SAMAGOTCHI_SESSION_SWEEP_INTERVAL_HOURS` | `24` | Throttle lazy sweep |
|
|
33
33
|
|
|
34
|
-
A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes its `*.json` and sidecar dir under the deleting owner lock, along with its plugin state, attached context, participant grants, System 1 runs and context-candidate records. Explicit delete and retention use the same cleanup path. Set both `DAYS=0` and `MAX=0` to retain forever. A session something protects is kept whatever its age or place: an enabled schedule's anchor, head and resolved target (`SessionProtection.protected_ids`; schedules are its one protector, *Deleting a session*). A protector that can't answer stops the sweep's deletes for that round: a `schedules.json` that is there but doesn't read (not JSON, not a schedules document, a file chi can't open, or a schedule in it that doesn't read) protects everyone until it is fixed (one `retention_skipped` line per sweep interval, the next try at the next interval; the skeleton-only dirs and saved runs are still swept), and `chi sessions prune`/`clean` exit 1 with its words; a missing one is no schedules ([scheduling.md](scheduling.md#keeping-the-chain-short): `chi schedule cancel <id>` removes one schedule that doesn't read).
|
|
34
|
+
A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes its `*.json` and sidecar dir under the deleting owner lock, along with its plugin state, attached context, participant grants, System 1 runs and context-candidate records. Explicit delete and retention use the same cleanup path. Set both `DAYS=0` and `MAX=0` to retain forever. A session whose transition lock is held when its turn comes (a continue, a delete, a send's shared hold: one try, `SessionTransition`) is kept for the next sweep. A session something protects is kept whatever its age or place: an enabled schedule's anchor, head and resolved target (`SessionProtection.protected_ids`; schedules are its one protector, *Deleting a session*). A protector that can't answer stops the sweep's deletes for that round: a `schedules.json` that is there but doesn't read (not JSON, not a schedules document, a file chi can't open, or a schedule in it that doesn't read) protects everyone until it is fixed (one `retention_skipped` line per sweep interval, the next try at the next interval; the skeleton-only dirs and saved runs are still swept), and `chi sessions prune`/`clean` exit 1 with its words; a missing one is no schedules ([scheduling.md](scheduling.md#keeping-the-chain-short): `chi schedule cancel <id>` removes one schedule that doesn't read).
|
|
35
35
|
|
|
36
36
|
Retention and manual prune/clean silently stop each deleted session's verified background tasks under its deleting lock, with `by: retention` (`stopped_by_retention`). Sessions are processed sequentially, their tasks in parallel. Unverified or unreadable tasks are not signalled; stops and failures are logged per task as `retention_task_stopped` / `retention_task_not_stopped`, without commands. A scratch session's own cleanup does the same with `by: scratch` and `scratch_task_stopped` / `scratch_task_not_stopped`.
|
|
37
37
|
|
|
38
38
|
**Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running or waiting for its wake turn (with `session.task_wakes: wake`; not one whose turn you stopped) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `WorkerBoot.run_session_loop`). As its Bridge stops, the worker marks the lock leaving (`OwnerLock#mark_leaving`: `leaving_at`, and `leave_wait`, its `recap.timeout`), since it keeps the lock while it writes the recap on leave: an `--attach` or `--resume` meanwhile (here, or a remote one through chi web's wake) prints `(waiting for the session to finish its recap…)` (`LaunchMode::RECAP_WAIT`) and waits for the release, up to that budget plus `OwnerLock::LEAVE_MARGIN` (5 s), before starting the new worker (`OwnerLock.await_release`). A lock held by a worker that isn't leaving (a live one, a stuck one) is left as before. A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). When every hold is one the user can stop — reminders, a watched task still running, a delegate with a live worker — the 409 also carries `holds: [{kind:, items: [{id:, label:, detail:}]}]` (a reminder's detail is its schedule, `every 20m`/`every 1h`, `, due now` when it is already due), and an attached terminal asks what to do with them; its "stop them and exit" posts `{"stop": "all"}`, which clears the reminders, stops those tasks (`TaskRuntime.stop_task`, as `task_stop`) and stops those children (`SessionManager.stop_session`) before leaving, re-checking first that nothing the user can't stop appeared meanwhile (`HoldStop`). A delegate counts only for that ask: it never holds the idle exit, and an exit that deletes or archives the session does not ask about it. The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). Reminders go along: as it leaves, the worker writes them to `<id>/reminders.json` (0600: `session_id`, `written_at`, and each reminder's id, name, description, interval and next fire as wall-clock time; `ReminderCarry`), and its successor reads and deletes the file as it starts, before its idle scheduler runs. A restored reminder keeps its id and schedule; one that came due meanwhile fires once at once, and one further ahead than its interval (a clock that jumped) is due one interval from now. The file counts only for the same session within 2 minutes of `written_at`, and not once the session is stopped: otherwise it is deleted unread (log `reminders_carry_dropped`, at warn unless the session was stopped). A stop that lands while the worker leaves for a restart wins: the worker writes no file, and no successor starts (`WorkerBoot.run_session_loop`, log `restart_dropped`). So does one that lands as it leaves any other way (an idle exit, `/exit`, a signal) with input queued or delegate reports waiting: no new worker un-stops it (log `respawn_dropped`), and what waits stays for the next start. A person's send after the stop (chi send, a web tab, a terminal) still un-stops it, as a person's send always does (see *Who may wake a session* below): one that reaches a leaving worker clears the stop, so the leave's new worker runs it (log `send_unstopped_leaving`); an archive deletes the file of each session it archives. Once an exit or restart is taken (claimed before a stop-all stops anything), the first one decides how the worker leaves: a later request of the same kind is answered as that exit, one of another kind (a stop-all from another terminal after a restart, chi web's "Restart workers" after a `/exit`) gets 409 `held` with `reason` `leaving_exit`, `leaving_delete` or `leaving_restart`, and a restart says it was refused rather than "restarted". A write that fails keeps the worker up with its reminders (log `reminders_carry_failed`), and the caller reports no new worker. A reminder already due when the restart is asked runs its turn first, so the restart's wait (10 s) may report no new worker yet though the hand-off follows. A worker from before this still refuses a restart for its reminders (409 `reminders`). Only an asked restart carries them: the fallback's TERM (a worker that can't be asked, below), a stop, an idle exit (which reminders hold anyway) and a crash drop them as before. What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
|
|
39
39
|
|
|
40
|
-
**Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first and once more under the delete's lock (a prompt or note that went in before that keeps it). The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
|
|
40
|
+
**Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first and once more under the delete's lock (a prompt or note that went in before that keeps it); a send, a continue or a delete holding its transition lock then keeps it too (one try; the sweep takes it later). The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
|
|
41
41
|
|
|
42
42
|
**Participants:** a session its owner invited participants into (`chi share`, see [CLI: Participants](cli.md#participants)) has two more files in its dir, neither in the session JSON: `participants.json` (0600), who is or was invited (`{participants: [{id, kind, name, role, added_at, expires_at, removed_at}]}`, never a token), which chi web and `chi share` write and the worker reads (`Participants.read`); and `participants.jsonl` (0600, append-only), the audit trail (grants issued, revoked and expired, each new peer, refused routes). A session nobody was invited to has neither. A continue, a fork or a delegate starts with no participants. Archiving or deleting the session revokes its links. See [internals/participants.md](internals/participants.md).
|
|
43
43
|
|
|
44
44
|
**Always attached:** every interactive `chi` (plain, `-p`, `--resume ID`, `--attach ID`, `chi scratch`) runs its session in a background worker and attaches to it; there is no setting for it. The worker runs in the session's `working_directory`, so `!commands` and tools see the directory the session was started in. Only `chi -p TEXT --non-interactive` runs its one turn in this process; while it does, the session can't be attached ("in use by a one-turn chi --non-interactive run or an older chi's terminal"). See [CLI: Sharing a session](cli.md#sharing-a-session).
|
|
45
45
|
|
|
46
|
-
**Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. Nobody's message goes into a session being deleted (409 `session_deleting`, *Deleting a session* above). A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn, an agent's `chi send` (`agent:<name>`, [driver and visitor](sub-agent.md#an-agents-messages-driver-and-visitor)), another session's `ask_session` and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
|
|
46
|
+
**Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. Nobody's message goes into a session being deleted (409 `session_deleting`, *Deleting a session* above), nor into one a transition holds right now (a continue's critical part: 409 `link_continued` naming the new link, else `transition_busy`; chi send and an ask try again, a schedule skips; docs/internals/session-lifecycle.md, Arrivals declare their hold). A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn, an agent's `chi send` (`agent:<name>`, [driver and visitor](sub-agent.md#an-agents-messages-driver-and-visitor)), another session's `ask_session` and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
|
|
47
47
|
|
|
48
48
|
**Which chi a worker runs:** a new or woken worker runs the newest chi installed for this Ruby (`gem 'samagotchi', '>= 0.a'`, prereleases count), whoever starts it: a `chi web` or terminal still on an older chi starts it on the newest one, so a stale process doesn't spread old code. A worker already running keeps its version until it is restarted. Should the newest install fail to load, the worker runs the starter's own version and logs `boot_fallback` (its stdio is `/dev/null`). Under `bundle exec` the worker drops Bundler's env first, so it activates the newest gem too. Two consequences: a wrapper pin (`chi _0.17.0_ web`) pins only that process, not the workers it starts; and a source checkout (`bin/chi` in a worktree, `bundle exec`) starts its workers on its own `lib/`, but a session it made that is later woken by an installed chi (`chi web`, `chi send`) runs the installed code. The names an older starter hands a newer worker (the boot line, its env keys, `input/` files, the session JSON fields and the Bridge routes sessions use on each other) are pinned in `spec/worker_contract_spec.rb`. A chi newer than 0.130.0 keeps the top-level keys it doesn't know (a newer chi's fields) when it saves a session, after its own, and doesn't act on them; `written_by` names the chi that saved the file last, and a worker woken on a file a newer chi saved logs `newer_writer`. chi 0.130.0 and older drop those keys: a session a newer chi made loses its newer fields when an older chi wakes or saves it (for example `chi --attach` from a project whose Ruby has an older chi). Keep the chi in every Ruby you run it from newer than 0.130.0.
|
|
49
49
|
|
|
@@ -55,9 +55,9 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
|
|
|
55
55
|
|
|
56
56
|
**Stopping a worker:** `chi sessions stop ID` marks the session stopped (an `<id>/stopped` file holding when, `{"at"}`, not a session.json field, which a worker saving at that moment would write over; a resume removes it), sends its worker TERM, then CONT (a stopped worker, SIGSTOP or Ctrl-Z, runs its TERM handler only once continued, so it leaves at once instead of outliving the wait), and waits (up to 10 s) until the worker has let go of `owner.lock`. A running turn is canceled over the Bridge first, with reason `session_stopped` (the turn's line ends "(session stopped)", its note says `cancelled (session-stopped)`, and a command it was running says "stopped as the session was stopped"; a bare signal to the worker makes it "stopped by a signal to chi"; an older worker takes the reason as `manual`); the TERM stops whatever still runs as a Stop with reason `signal` and saves it (a spawned worker traps TERM, HUP and INT: `WorkerSignals`; a turn not ended within 3 s, 0.5 s after a stop or a second signal, is cut and the session saved as it was), and a stopped worker still saves its kept turn, since the marker, not the saved status, says stopped. Any TERM, HUP or INT does the same to a worker outside a stop: it leaves (log `worker stop reason=signal`) and the next send wakes a new one, so a `chi --resume ID` right after spawns a fresh worker. That is also how to restart a worker still running an older chi, which the attached terminal reports when a command or a question dismiss gets a 404, and the web when an answer, a dismiss, a command or a cancel does (`501 not_supported`; `BridgeClient.stale_worker_message`). A command this chi has that the older worker doesn't (`/llm-context`, the web's ⚙ panel, against a 0.39.0 worker) says the same, not `not a session command` (`SessionCommandCatalog.builtin_name`); a typo keeps its `400 unknown_command`. The web's `POST /api/sessions/:id/stop` waits the same way, for 2 s (the page's Stop shows the stop at once), or for the body's `wait` up to the same 10 s (`SessionManager::STOP_WAIT`): `chi --remote NAME sessions stop` sends it, so it waits as long as here. Before that stop, the page's `stop session` button asks what the worker still has that the user can stop: `GET /api/sessions/:id/holds` (owner-only) answers the worker's `holds` — the same list the exit ask's 409 carries — always an array, empty when there is no live worker, one from before the route, or one that did not answer. With something, a sheet (a bottom sheet on a phone, a popover at the button otherwise — `stop_sheet.js`) lists them, at most three of a kind named and `+N more`, and offers **Stop all** (`POST /api/sessions/:id/holds/stop` → `HoldStop#stop_all`, then the stop), **Stop session only** (the stop exactly as it was) or **Cancel**. Nothing to ask about is the plain confirm, one tap as before. Both buttons stay because a stop only TERMs the worker: its reminders die with it (a stop also deletes a restart's `reminders.json` no successor took yet, so a later resume doesn't bring them back), while a background task and a delegate are their own processes and keep running. A delete or an archive differs: it never leaves a task the session started running unasked (*Deleting a session*: refused, or `--stop-tasks` stops it), where Stop's "Stop session only" does. A command sent during a turn that waits for its end (`/model X`, `!cmd`; see *Typing during a turn* in [cli.md](cli.md)) and hasn't run when the worker leaves (a stop, a crash) is answered `command_ran {status: "dropped"}`, so no UI keeps showing it waiting.
|
|
57
57
|
|
|
58
|
-
**Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web asks in one sheet first (*Session chains* → Deleting a link, the page side in docs/internals/web-frontend.md, The delete sheet): what goes, what is stopped first and what stays, one button naming the outcome, no browser confirm. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. Who refuses a delete is one question, `SessionProtection` (`session_protection.rb`, beside `SessionStores`, which says what a delete removes): every protector in `PROTECTORS` is asked (`hold` for a session, `chain_hold` for a chain, `protected_ids` for retention), schedules the one there is (`Schedules::ProtectionPart`), and the first hold is the refusal (`SessionManager.refuse_protected!`, `DeleteRefused` with the hold's reason and its `schedule_id`). It fails closed: a protector that raises is logged (`protector_failed`) and the error raised, so nothing is deleted; a store that is there but doesn't read (`SessionProtection::Unreadable`) refuses every delete, `protection_unreadable`, "schedules.json is unreadable (…): fix or remove it before deleting sessions" (the delete sheet shows it as the choice's refusal). An archive asks no protector. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) goes through `SessionChain::Delete.link` for every session, chained or not (*Session chains* → Deleting a link): **its delegates follow one rule** (`SessionManager::DELEGATES`): the stopped ones (archived ones too) go with it, deepest first, and a running one stays with its whole subtree, its file untouched; a stopped delegate with a running child goes and leaves that child without a parent. The delegates that would go bring their own refusals: one that is a schedule's target, anchor or head refuses the delete (`scheduled`, naming the delegate), as does one in a one-turn run, one a worker took after the plan was made (`worker_running`), and their running background tasks (below); their participant grants end with them. The result lists them in `deleted` (the session last) and the running ones with their subtrees in `left_running`; the CLI's line and `/exit --delete` say how many went. It is
|
|
58
|
+
**Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web asks in one sheet first (*Session chains* → Deleting a link, the page side in docs/internals/web-frontend.md, The delete sheet): what goes, what is stopped first and what stays, one button naming the outcome, no browser confirm. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. Who refuses a delete is one question, `SessionProtection` (`session_protection.rb`, beside `SessionStores`, which says what a delete removes): every protector in `PROTECTORS` is asked (`hold` for a session, `chain_hold` for a chain, `protected_ids` for retention), schedules the one there is (`Schedules::ProtectionPart`), and the first hold is the refusal (`SessionManager.refuse_protected!`, `DeleteRefused` with the hold's reason and its `schedule_id`). It fails closed: a protector that raises is logged (`protector_failed`) and the error raised, so nothing is deleted; a store that is there but doesn't read (`SessionProtection::Unreadable`) refuses every delete, `protection_unreadable`, "schedules.json is unreadable (…): fix or remove it before deleting sessions" (the delete sheet shows it as the choice's refusal). An archive asks no protector. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) goes through `SessionChain::Delete.link` for every session, chained or not (*Session chains* → Deleting a link): **its delegates follow one rule** (`SessionManager::DELEGATES`): the stopped ones (archived ones too) go with it, deepest first, and a running one stays with its whole subtree, its file untouched; a stopped delegate with a running child goes and leaves that child without a parent. The delegates that would go bring their own refusals: one that is a schedule's target, anchor or head refuses the delete (`scheduled`, naming the delegate), as does one in a one-turn run, one a worker took after the plan was made (`worker_running`), and their running background tasks (below); their participant grants end with them. The result lists them in `deleted` (the session last) and the running ones with their subtrees in `left_running`; the CLI's line and `/exit --delete` say how many went. It holds the transition locks (`continue.lock`, `SessionTransition`) of the session, the previous link it would bring back and the delegates that go, exclusively and from before the stop to the end: it waits up to 10 s for them (`SessionChain::Delete::LOCK_WAIT`; a send's short hold is waited out), and is refused when one is still held then, `continuing` while a continue of the session or of that previous link is under way, else `transition_held` ("session X is being deleted" or "is busy with another change; try again in a moment": the holder named). While it holds them a send, a push or a peer say to the session is refused 409 `transition_busy`, "session X is being deleted; try again in a moment" (`chi send` retries), for the stop and task-stop time too. Deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly (`delete_resolved`: they pass neither keyword and take no delegates); the retention sweep removes files directly (`remove_files`). **Background tasks still running:** a user's delete (these three, and `chi sessions delete`) asks first when tasks the deleted sessions started (their `task_create` tasks and the `execute` runs handed over at their limit, read from each session's transcript and `<working_directory>/tmp/tasks/<id>/task.json`: `SessionManager::RunningTasks`) still run: it is refused before anything changes (`tasks_running`), and the CLI's `--stop-tasks`, the web's `stop_tasks=true` (the delete's and the chain delete's query; with `&tasks=<id,id>`, the ones the sheet named, only those: `RunningTasks::Policy.stop(only:)`, see *Deleting a link*) stop them first (`stopped_by_user`, TERM then KILL after 3 s, all at once, about 4 s at most), under the deleting lock, after the starting-marker re-check, so no worker takes the session meanwhile; that last check refuses a task that started since the first (`worker_stopped: true` when the worker was stopped by then). One rule, fail-safe: a task whose pid still leads the group chi started at the start time it recorded is *running*; one whose record has no start time (before 2026-10-09) or whose start time reads nothing now, while its pid leads a group, is *unverified* ("may still be running"); a `task.json` that doesn't read is *unreadable*. All three refuse; a stop signals only the running ones (an unverified pid may belong to another process now) and reports the rest as not stopped, then deletes. A record left marked running whose pid is gone (a crashed worker's) isn't listed. The 409 is `{error: "tasks_running", reason, op: "delete", detail, session_id, tasks: {running, unverified, unreadable}, worker_stopped, stopped_worker, stopped_workers}` (`stopped_worker`: whose worker the delete stopped before the last check refused; `stopped_workers`: every worker the delete stopped), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
|
|
59
59
|
|
|
60
|
-
<a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. The web's Archive stays one tap (the toast's Undo) when nothing is in the way; its 409 opens the delete sheet in Archive's words (what is hidden, the tasks it stops first, `Stop them and archive`, which sends the tasks it named), and any other refusal is that sheet's "Can't archive … now". The 409 also says `sessions`: how many sessions the archive would hide (it and its delegates, across every project), plus `stopped_workers` (every stopped worker id). The refusal words name one stopped worker as "its worker was stopped" or "9d0e1f2a's worker was stopped", and several as "N workers were stopped: its own, 9d0e1f2a". `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}` (with `"tasks": [ids]` only those; a running one not named refuses, `tasks_running`, nothing archived: up front before any worker is stopped, and again after the workers let go), stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`.
|
|
60
|
+
<a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. The web's Archive stays one tap (the toast's Undo) when nothing is in the way; its 409 opens the delete sheet in Archive's words (what is hidden, the tasks it stops first, `Stop them and archive`, which sends the tasks it named), and any other refusal is that sheet's "Can't archive … now". The 409 also says `sessions`: how many sessions the archive would hide (it and its delegates, across every project), plus `stopped_workers` (every stopped worker id). The refusal words name one stopped worker as "its worker was stopped" or "9d0e1f2a's worker was stopped", and several as "N workers were stopped: its own, 9d0e1f2a". `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}` (with `"tasks": [ids]` only those; a running one not named refuses, `tasks_running`, nothing archived: up front before any worker is stopped, and again after the workers let go), stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`. The task stop and the markers run under the sessions' transition locks (kind `archive`, after the workers' stops; a send meanwhile is refused "being archived"); another change holding one of them for longer than 10 s (a continue, a delete) refuses the archive in its words (409 `busy`, reason `transition_held`). Undo (unarchive) doesn't restart them. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
|
|
61
61
|
|
|
62
62
|
**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)).
|
|
63
63
|
|
|
@@ -346,7 +346,7 @@ pbpaste | chi send 3fa2 # the clipboard is the messa
|
|
|
346
346
|
- 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`).
|
|
347
347
|
- `--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.
|
|
348
348
|
- 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.
|
|
349
|
-
- 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 schedule's anchor whose successor a prune deleted counts as continued: the send goes to the schedule's head, *Session chains* → Which link). 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
|
|
349
|
+
- 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 schedule's anchor whose successor a prune deleted counts as continued: the send goes to the schedule's head, *Session chains* → Which link). 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: session 3f9a1c2e is being continued as 7b2d41aa-…; send again in a moment`. A continue that ends or starts after that resolve still never gets the old link: chi send's delivery says it follows (`deliver_turn`'s `follow:`, `follow: true` on chi web's turn route for `chi --remote`), and an archived link with a saved successor, or one a continue holds the lock of, refuses it (409 `link_continued`, nothing written; the check and the input go in under a shared hold of that lock, so no continue starts between them); chi send resolves again and sends to the new link (taking back the `--image` copies it made in the old one, on this machine; `chi send OLD NEW` still sends once), for up to 10 s, then the same refusal, or `refused: session 3f9a1c2e is busy with another change; try again in a moment` when the lock's holder names no new link (409 `transition_busy`; chi send tries that same link again after a pause, within the same 10 s). Every sender's turn takes that hold, not only a followed one: the web composer, a participant, a delegate follow-up, a plugin and a schedule (which skips the firing) are refused the same way while a transition holds the session (an older chi web ignores `follow` and sends as before). 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*).
|
|
350
350
|
- 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`.
|
|
351
351
|
|
|
352
352
|
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)`.
|
|
@@ -398,18 +398,18 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
|
|
|
398
398
|
- **The carry note:** the new link starts with a context note from `session chain` (shown in its transcript as `note from session chain`), queued before its worker spawns, so its first turn sees it: `This session continues 3fa2c1d0 (2026-10-08 09:12), the previous link of its chain. Its recap, as of 2026-10-08 18:02:` and the previous link's recap (`recap.json`; cut at 8000 characters). No recap (fewer user turns than a recap needs, recaps off, none written in time): `… It left no recap.` Then `Its last answer:` and the previous link's last answer, read after the recap wait, so its exact shas, paths and next steps survive: a longer one keeps its last 4000 characters, after a `…` (a wrap-up closes on what comes next). There is none when the newest bubble was a step that asked for tools, when a later turn failed or was cut before it answered; `session.carry_last_answer: false` leaves it out of every note. No other transcript. The note never makes a continue fail: it stays within the 16 KiB a note may hold, the answer taking what the head and recap leave, and a session file that can't be read gives no answer. An idle new link holding only the note is kept, not discarded as empty.
|
|
399
399
|
- **Its attached context:** the previous link's movable sources (a command source by default; a pushed one stays) are copied to the new link before its worker starts, with their last text and the removed and muted markers, and a second note (`attached context`, after the carry note) names what moved and what stayed. A push into the archived link is then refused with the new link's id. See [Movable context](context.md#movable-context).
|
|
400
400
|
- **Its waiting notes:** the previous link's unabsorbed context notes move to the new link (`NoteMove.move`, the continue's last step before the worker starts, after the objectives' carry, which reads a pending `/objectives` edit from them first), file names kept, so they keep their ids and order and come ahead of the carry note. An `/objectives` note stays (the carry took its list), and so do the notes an earlier continue wrote into the previous link itself (a link continued before it ever started: its own carry note is replaced by the new one). A note an old worker had claimed and not deleted (`*.json.processing`) moves too, un-claimed (logged `notes_moved_claimed`): the previous link is archived, so left there it would be lost; if that worker had already added it to its conversation, the new link sees it once more, a rare duplicate rather than a loss. A note sent to the previous link after that goes to the new one (*Context notes*). One that still lands in an earlier link (sent just as the continue saved the new link, or by an older chi that knows no chain) is adopted by the new link's worker on its next pass: it looks back along the chain, one listing at its start, through up to 8 archived links, each one whose next link is the one after it, stopping at a link back in the lists or gone, and takes from each only the notes from the creation of the link that continued it on, never an `/objectives` note; older ones (left by a continue before notes moved) stay with the archived link, logged once (`notes_left_old`). An earlier link that is brought back (input un-archives it) keeps its notes while it is back; archived again, the newest link's running worker adopts from it again, so a note it got meanwhile and never absorbed comes to the newest link.
|
|
401
|
-
- **The recap first:** a previous link with a live worker is asked for a recap (the Bridge's `POST /recap`) and given up to 30 s to write it; one with none wrote its recap when its worker left.
|
|
401
|
+
- **The recap first:** a previous link with a live worker is asked for a recap (the Bridge's `POST /recap`) and given up to 30 s to write it; one with none wrote its recap when its worker left. Only then does the continue take the link's transition lock (`continue.lock`, with the new link's), waiting up to 10 s for another continue or change of it, and check everything again: one continued or deleted during the wait is refused then. A lock still held after 10 s refuses the continue `transition_busy` ("busy with another change; try again in a moment"); `last:<id>` looks again first, so it follows the other continue's new link.
|
|
402
402
|
- **The previous link is archived** before the new one starts, by the archive's own rules (see *Archiving a session*): a turn running, a prompt queued or the step-limit question refuse it, a live idle worker is stopped, a session a one-turn `chi --non-interactive` run has is refused. Its finished delegates are archived with it, as any archive does. Before archiving, the continue writes `<previous>/continue.json` with the reserved successor id. Session lists and the next continue repair an interrupted operation under `continue.lock`: if that successor's session file was not saved, they unarchive the previous link and remove the intent; if it was saved as its successor, they clear the intent and keep the archive.
|
|
403
403
|
- **Its open delegates move to the new link** instead: each direct delegate that is running, waiting for an answer, has a live worker or a reply its parent wasn't given, or has such a delegate below it (checked again after the recap wait, so one delegated meanwhile moves too). It moves with its own delegates, stays unarchived, and from then on is the new link's: its card folds under the new link, its reports ring the new link (an idle one runs a wake turn for them, as for its own delegates), `delegate_result` and the `⑂` chip count it there, and what its parent was already told (`delegates.json`) and any report still waiting come along, so nothing is reported twice. A moved delegate gets a context note from `session chain`, `Your parent session is now 4b7e9a01 (…), the next link of its session chain: …`, as its system prompt keeps naming the parent it started with. The move writes `<child>/parent.json` (`{parent_id, from, at}`) beside the child's session file, never the file itself, so a live child worker saving its own copy changes nothing; every reader applies it (a later move overwrites it; it is never removed). A continue is **refused for an open delegate that can't move** (`SessionContinue::Refused`, naming it): one whose live worker runs an older chi (`older chi worker 0.46.1; restart it`: `chi sessions restart <id>`, or stop it) or that a one-turn `chi --non-interactive` run has (`in use by a one-turn chi --non-interactive run or an older chi's terminal; let it finish`). An older `chi web` or CLI still running shows a moved delegate under the archived link until it is restarted.
|
|
404
404
|
- **What it records:** `<new link>/continued_from.json` (`ContinuedFrom`: `{previous_id, archived_ids, moved_ids}`), written first in the new link's `before_spawn`: the ids its archive hid (the previous link and the delegates archived with it, not ones archived before) and the delegates it moved. Deleting the link reads it to undo the continue. A link from an older chi has none.
|
|
405
405
|
- **If the continue fails part-way:** what a continue carries (its delegates, attached context, objectives and notes, in that order) and how each is given back is one list, `SessionContinue::CARRY` (the per-session stores it leaves behind, and why, are `SessionContinue::NOT_CARRIED`). A new link that fails to start gives its moved delegates back before it is deleted (each gets a note saying so; its worker is stopped first, if one started, and a worker that won't stop is reported, the link left), with any report one of them rang it with meanwhile, and the notes it moved with any sent to it meanwhile (never the continue's own: the carry note, the attached-context note, the objectives' list): its session file goes first, so a note sent to the previous link from then on stays there, then the notes go back, then its folder goes, and a note an older chi writes into it after that is given back too (a note for a session with no file and no folder is refused, never a stray folder); the previous link, back in the lists, is woken for reports waiting. A continue that dies in the middle leaves a `move.json` in the new link's folder: the new link's next worker finishes that move (only the delegates it names, and without a second note to one already told) as it starts. Its `continue.json` intent remains in the previous link's folder too, so a later list can restore it if the successor was never saved. Until the new link's own worker holds it, a ring from a moved delegate doesn't start another (a `starting` marker in its folder, which that worker removes; a stale one, over 60 s old or from a process that is gone, is ignored). An open delegate below an archived delegate refuses the continue (`under archived …`): unarchive that one, or archive this one.
|
|
406
|
-
- **Refused too:** a link that is continued already (
|
|
407
|
-
- **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`.
|
|
406
|
+
- **Refused too:** a link that is continued already (`session 3f9a1c2e was continued as 7b2d41aa-…; continue that one (or last:3f9a1c2e)`; a schedule's anchor whose successor a prune deleted counts as continued by the schedule's head, so no second line starts beside the chain), a previous link whose folder is gone, and one whose model's host can't run it when no default model is configured to fall back to. A refusal starts nothing and archives nothing; a new link that fails to start puts back what was archived. Every refusal that can be known up front (the archive's ones included) comes before the recap wait. One continue of a session runs at a time (a lock in its folder; other chains don't wait), so a double click finds the first one's link and is refused, while a `last:<id>` continue that waited follows the chain to its new end.
|
|
407
|
+
- **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`, `transition_busy` (another continue or change of it held its transition lock past 10 s), `busy`, `scratch` or `owned_by_tui`. Every session summary carries `continues`.
|
|
408
408
|
- **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.
|
|
409
409
|
- **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
|
|
410
410
|
- **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. The one exception is a schedule's anchor (below). A trigger names the chain this way: a person's message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain; an unattended sender's is refused (*Who may wake a session*). That is the rule: `chi send` and a note go to the chain's newest link (*Sending a message*, *Context notes*); the web composer, a participant's turn and `delegate(session:)` go to the link they name. One walker answers every one of these (`SessionChain::Links`: one session listing, archive flags read once; the earliest created successor wins a fork a hand edit made, a loop ends where it would repeat), with two rules on it, not unified on purpose: `last:` and a schedule take the chain's **end** (`Links#latest`: a continue refuses a link continued already, and a schedule never un-archives a chain you retired), `chi send` and a note the **first link not archived** (`Links#first_live`: a person's input goes where the chain is live, and brings back an archived end). A chain pruned by a schedule keeps its `anchor`, and the prune deletes the links behind its window, the anchor's successor among them, so nobody continues the anchor any more. The addressing walks bridge that gap: at an archived link nobody continues, `last:`, `chi send`, a note and the peer/context refusals' `next_id` go on at the head of a schedule anchored there (`Links#anchor_forward`; the first entry in `schedules.json` whose head still exists and isn't the anchor, disabled ones too), so `last:<anchor>` names the chain's end and a send to the anchor reaches the live link (`3f9a1c2e → 7b2d41aa (continued)`), as for any continued link; a continue of the anchor itself (without `last:`) is refused as continued already, naming the head. The graph stays raw: `next_of`, the chain's links (`Links#chain`: the anchor alone), the deletes and a delegate's ring never cross the gap. With the head gone (no forward) the walk stops at the anchor, as before; an anchor a person's send brought back before this (no longer archived) isn't bridged either. Backward, the kept window's oldest link still names a link that is gone, so the walk back 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.
|
|
411
411
|
- **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one through `SessionProtection.hold`, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionManager::DELEGATES` (`SessionManager::DelegateRule`; one shared preview row snapshot): a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is a link with nothing to undo: its delegates follow the same rule (*Deleting a session*). **The web asks first**: chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store) for any session, `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). A session in no chain answers `{chained: false, session_id, link}`, the same `link` a chained one gets (`previous_id` null, `earlier`/`later` 0, `next_id` null); an older page reads only `chained`. Each choice (`link`, `chain`) also carries `delegates` (`{delete: [ids], leave: [{id, running}]}`; `running` false for a stopped session left under a running delegate, beside the counts `deletes` and `left_running`), `tasks` (`{running, unverified, unreadable}`: `RunningTasks.of` the ids the choice deletes) and `worker` (a link's: `"turn"` when a worker owns it and a turn runs, `"idle"` when a worker owns it or is starting, null; a chain's `{idle, turn}` counts over its links). No titles: the page names each id from its own list. One shared session-row snapshot serves the link and chain choices; Links lists on its own, and a folder whose session file is gone answers too (the delete still takes it). Each call read-only checks each link's continue lock (a session in no chain too), and writes nothing else but the listing's own repair of an interrupted continue; an unknown id is the usual 404. chi web lists `delete_plan_all` in `/api/info`'s features (`Web::App::DELETE_PLAN_FEATURE`). **The tap stops only what the sheet named**: whenever the choice lists any task, the page sends `stop_tasks=true&tasks=<id,id>`, the choice's running ids (`tasks=` when it has only unverified or unreadable records, which a stop never signals, so such a session can still be deleted); archive's sheet sends `{"stop_tasks": true, "tasks": [ids]}` in its body. `tasks` works only with `stop_tasks`; without it, it is ignored, and `stop_tasks` without `tasks` (the CLI's `--stop-tasks`, an older page) takes every running task the operation can stop. A running task not named refuses (`tasks_running`), and the sheet reads the plan again and shows it with "changed; check again". A chain stops link by link: a link refused that way leaves it and the earlier links whole. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself. Each choice carries a `digest` (`SessionChain::Delete.digest`: the sorted ids it deletes, leaves, revives and moves back); the sheet's DELETE sends it as `expect=`, and the delete compares it with the plan it runs (a link's under its holds, as `delete_link` starts; the chain's before its checks) and refuses `plan_changed` (409) before anything changes; a session in no chain is compared the same way (a sheet shown for a link whose chain is gone since deletes when its ids still match). Without `expect` (the CLI, an older page) it deletes as it plans then.
|
|
412
|
-
**The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`, `SessionProtection.chain_hold`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
|
|
412
|
+
**The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`, `SessionProtection.chain_hold`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`; another change holding a link's or a doomed delegate's transition lock past the 10 s wait: `transition_held`; the locks are held, and sends refused as being deleted, until the last link went), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
|
|
413
413
|
|
|
414
414
|
## Schedules
|
|
415
415
|
|
data/docs/sub-agent.md
CHANGED
|
@@ -297,7 +297,7 @@ answers from any local process.
|
|
|
297
297
|
lines name both, `3f9a1c2e → 7b2d41aa (continued)`. `chi answer` and `--wait --turn T` take that `session_id` (a `--turn` of the
|
|
298
298
|
old link, from before the continue, waits on the old link). A send while the
|
|
299
299
|
continue itself runs waits a moment for the new link, else exits 1 with
|
|
300
|
-
`being continued as <id>; send again in a moment`.
|
|
300
|
+
`session <old> is being continued as <id>; send again in a moment`.
|
|
301
301
|
- An answer to a question that is no longer open (you answered it in the web
|
|
302
302
|
first) isn't sent; `chi answer` says so and waits for what comes next. Its
|
|
303
303
|
JSON then has `"answered_here": false` (absent when the answer went in), so
|
data/lib/samagotchi/bridge.rb
CHANGED
|
@@ -1613,7 +1613,7 @@ module Samagotchi
|
|
|
1613
1613
|
end
|
|
1614
1614
|
|
|
1615
1615
|
# Write a turn into this session's input dir, reusing the file IPC the
|
|
1616
|
-
# worker polls. Never calls run_turn across the boundary.
|
|
1616
|
+
# worker polls. Never calls run_turn across the boundary. Hold: worker-side.
|
|
1617
1617
|
def enqueue_turn(prompt:, client_id: nil, enqueued_id: nil, no_interrupt: false, images: [], delivery: nil, author: nil,
|
|
1618
1618
|
anchors: nil)
|
|
1619
1619
|
SessionInbox.write_input(session_dir, prompt: prompt, client_id: client_id, enqueued_id: enqueued_id,
|
|
@@ -237,7 +237,11 @@ module Samagotchi
|
|
|
237
237
|
error_line("#{command_name}: #{SessionAccess::ContextPush.not_push_message(name)}")
|
|
238
238
|
next false
|
|
239
239
|
when :continued
|
|
240
|
-
error_line("#{command_name}: #{SessionAccess::ContextPush.continued_message(name, target.session_id, pushed.next_id
|
|
240
|
+
error_line("#{command_name}: #{SessionAccess::ContextPush.continued_message(name, target.session_id, pushed.next_id,
|
|
241
|
+
in_flight: pushed.in_flight)}")
|
|
242
|
+
next false
|
|
243
|
+
when :busy
|
|
244
|
+
error_line("#{command_name}: #{SessionAccess::ContextPush.busy_message(target.session_id)}")
|
|
241
245
|
next false
|
|
242
246
|
end
|
|
243
247
|
|
|
@@ -52,6 +52,12 @@ module Samagotchi
|
|
|
52
52
|
# A name, a command, a value the store can't take.
|
|
53
53
|
class Invalid < ArgumentError; end
|
|
54
54
|
|
|
55
|
+
# A change to a session's own sources refused while a transition holds
|
|
56
|
+
# the session's lock (#changing): a continue copies them to its new
|
|
57
|
+
# link, so one written then would stay behind. Its words name the
|
|
58
|
+
# continue's new link, or say busy; try again in a moment.
|
|
59
|
+
class Held < Invalid; end
|
|
60
|
+
|
|
55
61
|
# A source's definition. +cmd+ nil: pushed only (chi context push).
|
|
56
62
|
# +provider+: the bundle whose context provider made it (a URL), whose
|
|
57
63
|
# folder its cmd's {bundle_dir} names (ContextProviders.command_for).
|
|
@@ -597,6 +603,28 @@ module Samagotchi
|
|
|
597
603
|
File.join(File.dirname(state_dir || SessionPaths.default_state_dir), DIR)
|
|
598
604
|
end
|
|
599
605
|
|
|
606
|
+
# The block (a change to session +session_id+'s own sources: an add, a
|
|
607
|
+
# remove) under a shared hold of the session's transition lock
|
|
608
|
+
# (SessionTransition.shared), so a continue (ContextSources.move) can't
|
|
609
|
+
# copy them in between. A session whose file is gone takes no hold (its
|
|
610
|
+
# folder is not made again).
|
|
611
|
+
# @param state_dir [String] the sessions dir
|
|
612
|
+
# @raise [Held] a transition holds it now (nothing written)
|
|
613
|
+
def changing(session_id, state_dir:)
|
|
614
|
+
return yield unless Session.exist?(session_id, state_dir: state_dir)
|
|
615
|
+
|
|
616
|
+
require_relative "session_transition"
|
|
617
|
+
require_relative "session_chain/successor"
|
|
618
|
+
SessionTransition.shared(session_id, state_dir: state_dir) do |free|
|
|
619
|
+
next yield if free
|
|
620
|
+
|
|
621
|
+
successor = SessionChain::Successor.in_flight(session_id, state_dir: state_dir)
|
|
622
|
+
raise Held, SessionTransition::Busy.held(session_id, state_dir: state_dir).message unless successor
|
|
623
|
+
|
|
624
|
+
raise Held, "#{SessionChain::Continued.for(session_id, successor).message}; try again in a moment"
|
|
625
|
+
end
|
|
626
|
+
end
|
|
627
|
+
|
|
600
628
|
def session_location(session_id, state_dir: nil)
|
|
601
629
|
Location.new(scope: "session", dir: File.join(root(state_dir: state_dir), "sessions", SessionPaths.check_id!(session_id)),
|
|
602
630
|
key: session_id)
|
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "fileutils"
|
|
4
3
|
require "json"
|
|
5
4
|
require_relative "atomic_file"
|
|
6
5
|
require_relative "session"
|
|
6
|
+
require_relative "session_transition"
|
|
7
7
|
|
|
8
8
|
module Samagotchi
|
|
9
9
|
# The files a continue (SessionContinue.run) keeps in the previous link's
|
|
10
|
-
# folder while it runs: LOCK, held for
|
|
10
|
+
# folder while it runs: LOCK, held for its transition, from after the
|
|
11
|
+
# recap to the end (SessionTransition, the one code that flocks it; the
|
|
12
|
+
# new link's own is held with it), and FILE, its
|
|
11
13
|
# intent (the successor's id), written before the link is archived and
|
|
12
14
|
# removed once the successor is saved or the continue is undone. A send
|
|
13
15
|
# (SessionInbox::Head) and a schedule tick (Schedules#continuing_reason)
|
|
14
16
|
# read them to tell a continue in flight from a link nobody continues.
|
|
15
17
|
module ContinueIntent
|
|
16
|
-
# One continue of a session at a time.
|
|
17
|
-
LOCK =
|
|
18
|
+
# One continue of a session at a time (SessionTransition::LOCK).
|
|
19
|
+
LOCK = SessionTransition::LOCK
|
|
18
20
|
# The intent: { successor_id:, previously_archived:, archived_ids: }.
|
|
19
21
|
FILE = "continue.json"
|
|
20
22
|
|
|
@@ -48,54 +50,32 @@ module Samagotchi
|
|
|
48
50
|
archived_ids: archived)
|
|
49
51
|
end
|
|
50
52
|
|
|
51
|
-
# The successor's id of a continue of +id+ in flight: its intent written
|
|
52
|
-
#
|
|
53
|
-
# continue holds
|
|
54
|
-
#
|
|
53
|
+
# The successor's id of a continue of +id+ in flight: its intent written,
|
|
54
|
+
# its lock held, and the successor saved or its lock held too (a
|
|
55
|
+
# continue holds both). nil when there is none, or the intent is stale
|
|
56
|
+
# or unreadable: no continue holds the lock (a crash left it, and
|
|
57
|
+
# SessionContinue.repair_interrupted undoes it), or another transition
|
|
58
|
+
# holds it over a crashed continue's intent whose successor was never
|
|
59
|
+
# saved and nobody holds (that continue is not coming back), or the
|
|
60
|
+
# holder recorded another kind (a delete, a stop, an archive holding it
|
|
61
|
+
# over a crashed continue's intent: SessionTransition.holder).
|
|
55
62
|
# @return [String, nil]
|
|
56
63
|
def in_flight(id, state_dir:)
|
|
57
64
|
return nil unless Session.valid_id?(id)
|
|
58
65
|
|
|
59
66
|
dir = Session.session_dir(id, state_dir: state_dir)
|
|
60
67
|
path = File.join(dir, FILE)
|
|
61
|
-
return nil unless File.file?(path) &&
|
|
68
|
+
return nil unless File.file?(path) && SessionTransition.held?(id, state_dir: state_dir)
|
|
69
|
+
return nil if SessionTransition.other_than_continue?(SessionTransition.holder(id, state_dir: state_dir))
|
|
62
70
|
|
|
63
|
-
read(path).successor_id
|
|
71
|
+
successor = read(path).successor_id
|
|
72
|
+
return nil unless successor
|
|
73
|
+
return successor if Session.exist?(successor, state_dir: state_dir) ||
|
|
74
|
+
SessionTransition.held?(successor, state_dir: state_dir)
|
|
75
|
+
|
|
76
|
+
nil
|
|
64
77
|
rescue JSON::ParserError, SystemCallError
|
|
65
78
|
nil
|
|
66
79
|
end
|
|
67
|
-
|
|
68
|
-
# The block under a shared hold of +id+'s continue lock, so no continue
|
|
69
|
-
# of it starts until the block returns (its exclusive lock waits); the
|
|
70
|
-
# block's argument is false when a continue holds the lock now (not
|
|
71
|
-
# waited for: nothing is held then). A followed send's check and the
|
|
72
|
-
# resume that would un-archive the link run inside it
|
|
73
|
-
# (SessionManager.deliver_turn's follow:).
|
|
74
|
-
# @yieldparam held [Boolean]
|
|
75
|
-
def hold(id, state_dir:)
|
|
76
|
-
return yield(false) unless Session.valid_id?(id)
|
|
77
|
-
|
|
78
|
-
dir = Session.session_dir(id, state_dir: state_dir)
|
|
79
|
-
FileUtils.mkdir_p(dir)
|
|
80
|
-
File.open(File.join(dir, LOCK), File::RDWR | File::CREAT, 0o600) do |lock|
|
|
81
|
-
yield(lock.flock(File::LOCK_SH | File::LOCK_NB) ? true : false)
|
|
82
|
-
end
|
|
83
|
-
end
|
|
84
|
-
|
|
85
|
-
# Whether +id+'s continue lock is held now, without creating its
|
|
86
|
-
# session folder or lock file. Read-only callers use this for a preview.
|
|
87
|
-
def lock_held?(id, state_dir:)
|
|
88
|
-
return false unless Session.valid_id?(id)
|
|
89
|
-
|
|
90
|
-
locked?(File.join(Session.session_dir(id, state_dir: state_dir), LOCK))
|
|
91
|
-
end
|
|
92
|
-
|
|
93
|
-
# Whether a continue holds the lock at +path+: a shared try that fails.
|
|
94
|
-
# The try is let go at once (the file is closed).
|
|
95
|
-
def locked?(path)
|
|
96
|
-
File.open(path, File::RDONLY) { |lock| !lock.flock(File::LOCK_SH | File::LOCK_NB) }
|
|
97
|
-
rescue Errno::ENOENT
|
|
98
|
-
false
|
|
99
|
-
end
|
|
100
80
|
end
|
|
101
81
|
end
|
data/lib/samagotchi/hold_stop.rb
CHANGED
|
@@ -75,10 +75,13 @@ module Samagotchi
|
|
|
75
75
|
|
|
76
76
|
# The delegate children, stopped as `chi sessions stop` stops a session
|
|
77
77
|
# (SessionManager.stop_session: its turn canceled, its worker TERMed).
|
|
78
|
-
# One owned by another terminal
|
|
78
|
+
# One owned by another terminal, or one whose transition lock another
|
|
79
|
+
# change holds (one try: this worker holds its own owner.lock, so it
|
|
80
|
+
# never waits for a transition lock), is left running and said so in
|
|
81
|
+
# the log.
|
|
79
82
|
def stop_delegates
|
|
80
83
|
@delegates.call.filter_map do |child|
|
|
81
|
-
SessionManager.stop_session(child.id, state_dir: @state_dir)
|
|
84
|
+
SessionManager.stop_session(child.id, state_dir: @state_dir, lock_wait: 0)
|
|
82
85
|
child.short_id
|
|
83
86
|
rescue StandardError => e
|
|
84
87
|
Log.warn(:worker, "exit_stop_delegate_failed", child: child.short_id, error: e.class.name, msg: e.message)
|
|
@@ -7,6 +7,7 @@ require_relative "atomic_file"
|
|
|
7
7
|
require_relative "participant_messages"
|
|
8
8
|
require_relative "archive_store"
|
|
9
9
|
require_relative "session"
|
|
10
|
+
require_relative "session_transition"
|
|
10
11
|
require_relative "grants"
|
|
11
12
|
require_relative "participant_turn_mode"
|
|
12
13
|
|
|
@@ -122,12 +123,19 @@ module Samagotchi
|
|
|
122
123
|
|
|
123
124
|
identity = Grants.clean_identity(identity) unless identity.nil?
|
|
124
125
|
raise Grants::Unbindable if !identity.nil? && public_url&.identity_header.nil?
|
|
125
|
-
if ArchiveStore.archived?(Session.session_dir(session_id, state_dir: state_dir))
|
|
126
|
-
raise Grants::Invalid, "session #{session_id[0, 8]} is archived: unarchive it to invite anyone"
|
|
127
|
-
end
|
|
128
126
|
|
|
129
|
-
|
|
130
|
-
|
|
127
|
+
# Checked and issued under the session's transition lock shared: a
|
|
128
|
+
# continue archives the link and ends its grants (end_sessions), so
|
|
129
|
+
# one issued between the two would outlive the archive.
|
|
130
|
+
issued = SessionTransition.shared(session_id, state_dir: state_dir) do |free|
|
|
131
|
+
raise Grants::Invalid, SessionTransition::Busy.held(session_id, state_dir: state_dir).message unless free
|
|
132
|
+
if ArchiveStore.archived?(Session.session_dir(session_id, state_dir: state_dir))
|
|
133
|
+
raise Grants::Invalid, "session #{session_id[0, 8]} is archived: unarchive it to invite anyone"
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
grants.issue(session_id: session_id, name: name, ttl: ttl, cap: cap, identity: identity,
|
|
137
|
+
on_write: sidecar_writer(state_dir, [session_id]))
|
|
138
|
+
end
|
|
131
139
|
grant = issued.grant
|
|
132
140
|
log(session_id, :issued, state_dir: state_dir, participant: grant.id, name: grant.name,
|
|
133
141
|
role: grant.role, expires_at: grant.expires_at, cap: grant.spend_cap,
|