samagotchi 0.132.0 → 0.134.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 +109 -1
- data/bin/chi +16 -0
- data/docs/architecture.md +28 -1
- data/docs/cli.md +12 -1
- data/docs/configuration.md +62 -15
- data/docs/desktop.md +2 -1
- data/docs/guardrails.md +107 -12
- data/docs/internals/background-tasks.md +1 -0
- data/docs/internals/participants.md +6 -5
- data/docs/internals/tool-guardrails.md +2 -0
- data/docs/plugins.md +2 -1
- data/docs/sessions.md +61 -6
- data/docs/testing.md +8 -3
- data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
- data/lib/samagotchi/bundles/mcp/plugin.rb +10 -3
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/chi_home.rb +12 -2
- data/lib/samagotchi/chi_shim.rb +77 -0
- data/lib/samagotchi/child_env.rb +5 -3
- data/lib/samagotchi/config.rb +2 -0
- data/lib/samagotchi/context_fetch.rb +4 -2
- data/lib/samagotchi/desktop/macos.rb +45 -4
- data/lib/samagotchi/engine.rb +13 -0
- data/lib/samagotchi/guardrails/implicit_writers.rb +143 -0
- data/lib/samagotchi/guardrails/pair_boundary.rb +27 -6
- data/lib/samagotchi/guardrails/pair_command.rb +546 -57
- data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
- data/lib/samagotchi/guardrails/read_only_shell.rb +34 -2
- data/lib/samagotchi/guardrails/review_paths.rb +7 -4
- data/lib/samagotchi/guardrails/shell_git_dirs.rb +6 -1
- data/lib/samagotchi/guardrails/shell_lex.rb +23 -0
- data/lib/samagotchi/guardrails/shell_paths.rb +3 -2
- data/lib/samagotchi/guardrails/targets.rb +8 -3
- data/lib/samagotchi/home_command.rb +33 -21
- data/lib/samagotchi/home_doctor.rb +210 -0
- data/lib/samagotchi/home_notice.rb +87 -0
- data/lib/samagotchi/hooks/loader.rb +5 -0
- data/lib/samagotchi/log_line.rb +12 -0
- data/lib/samagotchi/project_env.rb +352 -0
- data/lib/samagotchi/self_report.rb +35 -0
- data/lib/samagotchi/session_commands.rb +4 -2
- data/lib/samagotchi/session_manager.rb +18 -0
- data/lib/samagotchi/system_one/self_protect.rb +58 -2
- data/lib/samagotchi/testing/boundary.rb +3 -1
- data/lib/samagotchi/testing/waiting.rb +13 -0
- data/lib/samagotchi/toolkit_binding.rb +16 -0
- data/lib/samagotchi/tools/builtins.rb +13 -2
- data/lib/samagotchi/update_command.rb +7 -3
- data/lib/samagotchi/update_hint.rb +6 -1
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +50 -0
- data/lib/samagotchi/web/public/answer_fold.js +262 -0
- data/lib/samagotchi/web/public/answer_refs.js +2 -0
- data/lib/samagotchi/web/public/app.js +22 -2
- data/lib/samagotchi/web/public/cards_place.js +5 -2
- data/lib/samagotchi/web/public/chip_popover.js +77 -12
- data/lib/samagotchi/web/public/claim_link.js +4 -2
- data/lib/samagotchi/web/public/composer.css +13 -1
- data/lib/samagotchi/web/public/data.js +8 -4
- data/lib/samagotchi/web/public/history_reveal.js +23 -0
- data/lib/samagotchi/web/public/index.html +68 -14
- data/lib/samagotchi/web/public/level_chip.js +22 -38
- data/lib/samagotchi/web/public/llm_context_chip.js +28 -80
- data/lib/samagotchi/web/public/refs.js +6 -7
- data/lib/samagotchi/web/public/review_start.js +13 -57
- data/lib/samagotchi/web/public/send_turn.js +3 -2
- data/lib/samagotchi/web/public/start_page.js +117 -97
- data/lib/samagotchi/web/public/start_settings.js +309 -0
- data/lib/samagotchi/web/public/start_toolkit.js +158 -0
- data/lib/samagotchi/web/public/thinking_chip.js +9 -22
- data/lib/samagotchi/web/public/timing.js +5 -1
- data/lib/samagotchi/web/public/turn_html.js +12 -6
- data/lib/samagotchi/web/public/turn_range.js +32 -0
- data/lib/samagotchi/web/public/turn_view.js +21 -11
- data/lib/samagotchi/web/public/verdict_card.js +5 -13
- data/lib/samagotchi/web/public/verify_target.js +7 -10
- metadata +11 -1
|
@@ -195,11 +195,12 @@ Everything else is `:owner`: `/answer`, `/command`, `/images` (an image a prompt
|
|
|
195
195
|
to act: the turn only reads (`Guardrails::ReviewBoundary`), and proposes what the owner applies ([Apply](#apply)).
|
|
196
196
|
- **`:pair`**, a working session's participant invited to act: the turn acts with the session's tools under the
|
|
197
197
|
owner's guardrails, its asks go to the owner and offer once only, and `Guardrails::PairBoundary` denies secrets,
|
|
198
|
-
chi itself and chi web on loopback, background and scheduled jobs, the environment and credential printers, git
|
|
199
|
-
hooks, owner-voiced tools and the owner's task outputs, and the model's own question, and asks before a command
|
|
200
|
-
that makes a link and before a write that may land outside the project, failing closed (a
|
|
201
|
-
|
|
202
|
-
|
|
198
|
+
chi itself and chi web on loopback, background and scheduled jobs, the environment and credential printers, git
|
|
199
|
+
config writes (reads only) and git's hooks, owner-voiced tools and the owner's task outputs, and the model's own question, and asks before a command
|
|
200
|
+
that makes a link and before a write that may land outside the project, failing closed (a global install or a
|
|
201
|
+
user config write that names no path, `Guardrails::ImplicitWriters`, and a script read from stdin count; a
|
|
202
|
+
session at or above home has none: every write asks) ([guardrails](../guardrails.md#a-participants-pair-boundary)).
|
|
203
|
+
No Apply: it acted itself.
|
|
203
204
|
|
|
204
205
|
`ParticipantMode.of(session, features:)` is the session's: what a participant invited now gets. No session is
|
|
205
206
|
`:review`. A worker names `pair_turns` (`Delivery::PAIR_FEATURE`) when it runs pair turns; one without it runs
|
|
@@ -50,6 +50,8 @@ Configuration (config.yml `execute.*` keys and CLI flags too, as for `read`):
|
|
|
50
50
|
- `SAMAGOTCHI_EXECUTE_TIMEOUT_SEC` (`execute.timeout_sec`, default `120`): what a command still running then gets is `execute.on_timeout`.
|
|
51
51
|
- `SAMAGOTCHI_EXECUTE_ON_TIMEOUT` (`execute.on_timeout`, default `task`): `task` hands the command over as a background task, not killed; the result starts `Still running at the 120s limit: moved to a background task, not killed.` (`Execute::HANDED_OVER`), then its `task_id:` and the tails of stdout and stderr so far, and `task_wait` waits for it. `kill` stops it and answers `Error: command timed out after …s` (`Execute::TIMEOUT_PREFIX`) with the hint to use `task_create`. The `!cmd` bang always kills. See [Background tasks](background-tasks.md).
|
|
52
52
|
|
|
53
|
+
The env a command runs in (the session's project env, `ProjectEnv.tools_env`, then the Ruby/Bundler scrub and chi's markers) is the same for `execute`, `task_create`, `!cmd` and context sources: see [Background tasks](background-tasks.md).
|
|
54
|
+
|
|
53
55
|
Implementation note:
|
|
54
56
|
|
|
55
57
|
- Shared logic lives in `lib/samagotchi/tools/output_guardrails.rb` and is used by `read` and `execute`, and by `edit` (its env switches) and `delegate_wait` (the head+tail preview of a child's long reply).
|
data/docs/plugins.md
CHANGED
|
@@ -1310,7 +1310,8 @@ bundle.shutdown
|
|
|
1310
1310
|
value, or raises `Samagotchi::Testing::Waiting::TimedOut` ("timed out after 5 s waiting for <what>", plus
|
|
1311
1311
|
`; last saw: <value>` from the `seen:` callable). `join!(thread, what)` and `pop!(queue, what)` are
|
|
1312
1312
|
`Thread#join` and `Queue#pop` with that deadline and message; `wait_until { }` returns the block's last value
|
|
1313
|
-
instead of raising, for a wait whose timeout is fine; `process_gone?(pid)
|
|
1313
|
+
instead of raising, for a wait whose timeout is fine; `process_gone?(pid)`; `time_bound(seconds, below: nil)`, a
|
|
1314
|
+
wall-clock upper bound scaled the same way and kept under `below:` (the unscaled deadline it tells apart from). Every deadline is multiplied by
|
|
1314
1315
|
`SPEC_TIME_SCALE` (default 1, at least 1; chi's CI sets 2), so a slow runner gets headroom.
|
|
1315
1316
|
- **Model notes:** `sandbox.model_notes_for(model_id, small: nil, cwd: nil)` lists the model notes chi would load
|
|
1316
1317
|
into the prompt for a bare model id (`deepseek/deepseek-v4.1-flash`, no host prefix), from the sandbox's
|
data/docs/sessions.md
CHANGED
|
@@ -96,9 +96,9 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
|
|
|
96
96
|
- The web header's project chip opens a picker. The start project is the default row (including its start folder); other rows show their root, session and waiting counts. **All projects** opens every session, and choosing a project drops the open-session hash while keeping `?view=`.
|
|
97
97
|
|
|
98
98
|
- `Session.list` / `SessionManager.list_sessions` / `GET /api/sessions?sort=&order=&limit=&offset=` default to `updated_at desc` (newest activity first). Also supports `created_at`, `asc`. `X-Total-Count` header when paginated.
|
|
99
|
-
- Web UI (`chi web`): the page's scope is in its URL. Started in a git repo, `chi web` opens `/?dir=<that folder>`: that project's sessions, and new sessions start in that folder; the header chip says `<project> · all`, and `all` opens the same place as `?scope=all` (every session; a new session there starts in chi web's start folder, shown on the start page, and cards name their folder; `← <project>` goes back to the project view it came from, or to the start folder's project). A bare `/` (the LAN link, the Home Screen app) is the start folder's project too: the folder chi web runs in, or `web.start_dir` / `chi web --start-dir DIR`; outside a repo it shows every session. A pushed notification opens its session in that session's own project (`/?dir=<its project>#/s/<id>`; `?scope=all` outside a repo). One server serves every project: a second `chi web` (from another repo) finds it through `GET /api/info` and prints (with `--open`, opens) its page for its own folder instead of starting another. The 3 latest sessions sit above the chat, and the grip on the chat's top edge — the same thin handle as the composer's, its twin — puts them away and brings them back: a drag up (or a click, or Enter/Space on it) hides them, a drag down (or a click) shows them again, and the choice is remembered. A hidden strip leaves its status in the top bar (`N sessions · ● 1 live · ● 1 waiting`, from the cards), and a click on that pill opens All sessions, without showing the strip first. In a window under 900 px wide, where the strip scrolls sideways, the grip stays under it, outside the scroller; a window under 700 px tall hides the strip by itself, so a question or approval card in the stage keeps room, and the grip shows it until the window is tall again. A parent and its delegates are one card there: its `▸ 2 delegates · 1 live · 1 waiting` chip (the waiting part in the attention colour, the card's border too) opens their rows in a popover under it (a row per delegate at any depth, indented; a click opens that one, Esc or a click outside closes it, and the strip's order holds while it is open). A fork is a card of its own, and so is a delegate whose parent isn't listed (archived, another project), with its `↳ <parent>` chip; the pill counts cards, and every live or waiting session. "All sessions" (or `/`) opens every session at `#/sessions`, with a search over preview, id and status (Esc or Back returns). There a parent's card holds its delegates the same way, the chip opening their rows inside the card (each with an archive button on hover), open by itself while one of them waits on you; the count says `14 (+7 delegates)`, a search that matches a delegate shows its parent's card with the list open and the matching rows marked, and select mode picks cards (archiving a parent takes its delegates). The open session is in the URL (`#/s/<id>`), so a reload or a copied link opens it again; the chi logo top left goes back to the empty start for a new session. The message box grows with its text; drag its top edge to keep it taller (double-click resets). A file in a tool row (a read, edit or write's title) and its diff lines are refs: hover one and click to open the current file in your editor at that line, on this machine only (`web.editor`; the browser's "always allow" for the page's port and VS Code's "allow opening local files" are asked once; see [Opening files from chi web](configuration.md#opening-files-from-chi-web)). So are an edit or write approval card's paths (at the first line the dry run changes) and its diff lines, before you approve, and the numbered lines of a read's output: `lines 40–60` under it opens the text as read, numbered, when the output is the file as-is (not the head/tail preview of a big file, an error or an image; no numbers after a cut). A `path:line` (or `path:line-line`) in an answer or a step's text is one too once the turn has ended, and after a reload, when it names a file a row or card on the page touched: the path under the session's folder, else the one touched file it ends with (a bare `app.js:12` when only one touched file is named so; two such files make it none); a path without a line counts only when it is a touched file exactly. Code blocks, links, bare URLs and inline code with more than the ref in it are left alone, and a file the session didn't touch is never linked; a link whose text is such a ref alone (github-pr's link to the PR diff) becomes a ref too, and its plain click still goes to the PR. A plugin's refs on an answer (an `after_turn` hook's, see [Refs on the answer](hooks.md#refs-on-the-answer-display-only)) are paired with its links and text whatever the rows touched: they can link a file the session didn't touch, or an issue or a commit, and add their own actions to the ref's menu. A plugin tool's row carries the refs its `refs:` gives (see [Refs on a tool's row](plugins.md#refs-on-a-tools-row)): its title opens the first, and its `▾` menu adds the others as `<ref> · <action>` (the URL on hover); their URL actions work on a phone too. A ref with more than one target shows a small `▾` on hover: it opens a menu of them, in order **PR diff** (a link's), **Open in editor**, **Show in turn** and **Copy path**, and a plain click runs the first (a link's own, else the editor, else show in turn). **Show in turn** scrolls to the tool row that touched the file (looked for in the ref's own step, then its own turn, then the rows before it, then the nearest after it; there, the last one showing the ref's line, else the last one), opens the steps, the stage's steps and the row's diff (or the read showing the line) and flashes the row and the line; an answer's or a step's ref and an approval card's path have it, not a row's own title or lines. It needs no editor, so a viewer without one (a phone on the LAN) gets an answer's refs with **Show in turn** as their click; a row's title and diff lines stay plain text there. On a touch screen a tap opens the menu. A ref with a target is a tab stop: Enter runs its first target, ↓ opens the menu (↑/↓ move, Enter picks, Esc closes back to the ref). Diff and read lines have their click only. The info bar copies `chi --attach <id>` for a terminal. A session whose prompt carried model notes has a `notes: deepseek` chip there (the names without `model_notes_`; the tooltip lists each with its scope and size; `session.prompt_notes` in `GET /api/sessions/:id`, the live worker's, else the session file's; see [Memory](memory.md#model-notes)). Its `llm ctx` chip names the LLM context strategy the next turn runs under (`llm ctx stale,forget · session`, in the accent colour when the session set its own; the tooltip gives each value's source), and its popover sets the session's own strategy, apply rule and budget, or follows the model again, by running `/llm-context` in the worker (the reply shows as a command bubble); `GET /api/sessions/:id`'s `session.llm_context` carries the values (the live worker's, else resolved from the session file), and a `command_ran` that changed them carries the new ones. Its `think` chip does the same for the thinking level (`/thinking`), and on a chat host its `reasoning` chip for the reasoning history (`reasoning all · session`, `/reasoning-history`; `session.reasoning_history`, null on a native host). A `/thinking` or `/reasoning-history` change that restarts the prompt cache asks first: the reply bubble has an **Apply (restarts the cache)** button that sends its `--yes` line (the chips' Set sends that line itself; see [Changes that restart the prompt cache](configuration.md#changes-that-restart-the-prompt-cache)). It shows the context used (`ctx 42%`) and the last generation's decode speed (`87 tok/s`, `~64 tok/s` when estimated; see `/stats` in [cli.md](cli.md#session-commands)); hovering `ctx` there or on a session card lists the session's tokens in (summed over every request, with the cached share), out (with reasoning) and the cost when the provider reports one, for this session only (one estimated from a `hosts.<name>.models` price shows with `~`: `cost: ~$0.54 ($0.42 reported, ~$0.12 estimated)`); after a `/model` switch the info bar's tooltip adds a `per model:` row per run of turns on one model above those totals (`splash:qwen3-35b · 6 turns · 96.0k in / 9.0k out · ~$0.02`, a switch's prefill under its row: `└ switch prefill 58.0k uncached prompt ≈$0.01`; the timing's `model_segments`, replaced by each `generation_completed`'s; the session cards stay as they were), and right after the switch its ctx % is the new model's window's; and the memory indexes its prompt holds (`memory index: ~3.4k tokens in this session's prompt (system 2.0k, project 1.4k)`; see [Memory](memory.md#the-indexs-size)). The start page's model picker (bottom left of the composer, the chosen name `▾`) chooses the model a new session starts on, and a fresh chain link's (see [Session chains](#session-chains); there a pick shows as a `/model` command bubble in the link); it opens a search list over the conversation (↓ or a click; downward when the start page leaves no room above): an empty search shows the last 5 picks (Recent) and then each host's model ids A–Z under the host, the default host first (an id the host declares under `hosts.<name>.models` first, noted `config`, its tooltip `served by config (hosts.<name>.models)`; a host that failed to list its models keeps those ids, greyed and noted `host down`, still pickable; a remembered or default model stays chosen even then, greyed on the button); typed words must each match the host or the id (a substring, else for 3+ characters the letters in order, so `deepseek4.1 fla` finds `openrouter · deepseek/deepseek-v4.1-flash`), ⏎ picks, Esc/Tab close, a pick puts the focus in the message box: `GET /api/models` lists the hosts' models as chi spells them (`{default, models: [{name, host, id, configured?, unavailable?, sampling?, llm_context?}], warning?}`; `configured: true` marks an id declared under `hosts.<name>.models`, listed first under its host, `unavailable: true` one whose host failed to list its models; `sampling` is the model's configured request parameters as `/model` words them, the row's tooltip in the list; bare for the default host, `host:model` for the others, from the same cached lists as `/models`, a bounded wait, a host that is down noted in `warning`), and `POST /api/sessions` takes `model` (blank means the default). Beside it, an `llm ctx` chip shows the LLM context the picked model starts under (each `GET /api/models` row's `llm_context`, as the info bar's); its form sets one for the new session only, sent as `POST /api/sessions`'s `llm_context` and never remembered (see [configuration.md](configuration.md#llm-context-a-sessions-own-strategy)). The start page's first message goes as later ones do: `POST /api/sessions` with `idle: true` and `preview` (the message, which names the session until its turn is saved), then `POST /api/sessions/:id/turn`, so a failed first turn puts its prompt back in the composer too; a first line that is one of the new session's commands (`/model …`) goes to `POST /api/sessions/:id/command` instead, as later ones do. The browser remembers the last model picked; a running session's model is in the info bar and changes only with `/model`. In the composer a line is a command when it is `!…` or starts with one of the session's command names (its `commands` list; `/stats`, `/exit` and the other terminal words get the page's own reply); an unknown `/word` (`/usr/bin/env is missing`) goes to the model as a prompt, as in a terminal; a one-word `/word` no command answers (`/modle`) is not sent: the page shows `Unknown command /modle. Did you mean /model? /help lists the commands.` (the "Did you mean" part only when a name is close). A `POST /turn` (or a session's first `prompt`) that is one of the worker's commands runs as that command too (`202 {status, command_id, session_id}`), so `chi send`, `chi -p` and a page whose command list lags all get the command. ↑/↓ in the composer walk the prompt history the TUI's ↑ walks ([Persistent Prompt History](cli.md#persistent-prompt-history)): ↑ with the caret on the first line, ↓ from the last line while browsing, ↓ past the newest brings the draft back; `GET /api/history` returns `{entries: [...]}`, oldest first (the page fetches it on focus and after each send). The server records a sent line in the routes once the worker took it (`POST /turn` accepted, a `!command` through `POST /command` or as a session's first line); `"history": false` in the body keeps it out (an image-only send).
|
|
99
|
+
- Web UI (`chi web`): the page's scope is in its URL. Started in a git repo, `chi web` opens `/?dir=<that folder>`: that project's sessions, and new sessions start in that folder; the header chip says `<project> · all`, and `all` opens the same place as `?scope=all` (every session; a new session there starts in chi web's start folder, shown on the start page, and cards name their folder; `← <project>` goes back to the project view it came from, or to the start folder's project). A bare `/` (the LAN link, the Home Screen app) is the start folder's project too: the folder chi web runs in, or `web.start_dir` / `chi web --start-dir DIR`; outside a repo it shows every session. A pushed notification opens its session in that session's own project (`/?dir=<its project>#/s/<id>`; `?scope=all` outside a repo). One server serves every project: a second `chi web` (from another repo) finds it through `GET /api/info` and prints (with `--open`, opens) its page for its own folder instead of starting another. The 3 latest sessions sit above the chat, and the grip on the chat's top edge — the same thin handle as the composer's, its twin — puts them away and brings them back: a drag up (or a click, or Enter/Space on it) hides them, a drag down (or a click) shows them again, and the choice is remembered. A hidden strip leaves its status in the top bar (`N sessions · ● 1 live · ● 1 waiting`, from the cards), and a click on that pill opens All sessions, without showing the strip first. In a window under 900 px wide, where the strip scrolls sideways, the grip stays under it, outside the scroller; a window under 700 px tall hides the strip by itself, so a question or approval card in the stage keeps room, and the grip shows it until the window is tall again. A parent and its delegates are one card there: its `▸ 2 delegates · 1 live · 1 waiting` chip (the waiting part in the attention colour, the card's border too) opens their rows in a popover under it (a row per delegate at any depth, indented; a click opens that one, Esc or a click outside closes it, and the strip's order holds while it is open). A fork is a card of its own, and so is a delegate whose parent isn't listed (archived, another project), with its `↳ <parent>` chip; the pill counts cards, and every live or waiting session. "All sessions" (or `/`) opens every session at `#/sessions`, with a search over preview, id and status (Esc or Back returns). There a parent's card holds its delegates the same way, the chip opening their rows inside the card (each with an archive button on hover), open by itself while one of them waits on you; the count says `14 (+7 delegates)`, a search that matches a delegate shows its parent's card with the list open and the matching rows marked, and select mode picks cards (archiving a parent takes its delegates). The open session is in the URL (`#/s/<id>`), so a reload or a copied link opens it again; the chi logo top left goes back to the empty start for a new session. The message box grows with its text; drag its top edge to keep it taller (double-click resets). A file in a tool row (a read, edit or write's title) and its diff lines are refs: hover one and click to open the current file in your editor at that line, on this machine only (`web.editor`; the browser's "always allow" for the page's port and VS Code's "allow opening local files" are asked once; see [Opening files from chi web](configuration.md#opening-files-from-chi-web)). So are an edit or write approval card's paths (at the first line the dry run changes) and its diff lines, before you approve, and the numbered lines of a read's output: `lines 40–60` under it opens the text as read, numbered, when the output is the file as-is (not the head/tail preview of a big file, an error or an image; no numbers after a cut). A `path:line` (or `path:line-line`) in an answer or a step's text is one too once the turn has ended, and after a reload, when it names a file a row or card on the page touched: the path under the session's folder, else the one touched file it ends with (a bare `app.js:12` when only one touched file is named so; two such files make it none); a path without a line counts only when it is a touched file exactly. Code blocks, links, bare URLs and inline code with more than the ref in it are left alone, and a file the session didn't touch is never linked; a link whose text is such a ref alone (github-pr's link to the PR diff) becomes a ref too, and its plain click still goes to the PR. A plugin's refs on an answer (an `after_turn` hook's, see [Refs on the answer](hooks.md#refs-on-the-answer-display-only)) are paired with its links and text whatever the rows touched: they can link a file the session didn't touch, or an issue or a commit, and add their own actions to the ref's menu. A plugin tool's row carries the refs its `refs:` gives (see [Refs on a tool's row](plugins.md#refs-on-a-tools-row)): its title opens the first, and its `▾` menu adds the others as `<ref> · <action>` (the URL on hover); their URL actions work on a phone too. A ref with more than one target shows a small `▾` on hover: it opens a menu of them, in order **PR diff** (a link's), **Open in editor**, **Show in turn** and **Copy path**, and a plain click runs the first (a link's own, else the editor, else show in turn). **Show in turn** scrolls to the tool row that touched the file (looked for in the ref's own step, then its own turn, then the rows before it, then the nearest after it; there, the last one showing the ref's line, else the last one), opens the steps, the stage's steps and the row's diff (or the read showing the line) and flashes the row and the line; an answer's or a step's ref and an approval card's path have it, not a row's own title or lines. It needs no editor, so a viewer without one (a phone on the LAN) gets an answer's refs with **Show in turn** as their click; a row's title and diff lines stay plain text there. On a touch screen a tap opens the menu. A ref with a target is a tab stop: Enter runs its first target, ↓ opens the menu (↑/↓ move, Enter picks, Esc closes back to the ref). Diff and read lines have their click only. The info bar copies `chi --attach <id>` for a terminal. A session whose prompt carried model notes has a `notes: deepseek` chip there (the names without `model_notes_`; the tooltip lists each with its scope and size; `session.prompt_notes` in `GET /api/sessions/:id`, the live worker's, else the session file's; see [Memory](memory.md#model-notes)). Its `llm ctx` chip names the LLM context strategy the next turn runs under (`llm ctx stale,forget · session`, in the accent colour when the session set its own; the tooltip gives each value's source), and its popover sets the session's own strategy, apply rule and budget, or follows the model again, by running `/llm-context` in the worker (the reply shows as a command bubble); `GET /api/sessions/:id`'s `session.llm_context` carries the values (the live worker's, else resolved from the session file), and a `command_ran` that changed them carries the new ones. Its `think` chip does the same for the thinking level (`/thinking`), and on a chat host its `reasoning` chip for the reasoning history (`reasoning all · session`, `/reasoning-history`; `session.reasoning_history`, null on a native host). A `/thinking` or `/reasoning-history` change that restarts the prompt cache asks first: the reply bubble has an **Apply (restarts the cache)** button that sends its `--yes` line (the chips' Set sends that line itself; see [Changes that restart the prompt cache](configuration.md#changes-that-restart-the-prompt-cache)). It shows the context used (`ctx 42%`) and the last generation's decode speed (`87 tok/s`, `~64 tok/s` when estimated; see `/stats` in [cli.md](cli.md#session-commands)); hovering `ctx` there or on a session card lists the session's tokens in (summed over every request, with the cached share), out (with reasoning) and the cost when the provider reports one, for this session only (one estimated from a `hosts.<name>.models` price shows with `~`: `cost: ~$0.54 ($0.42 reported, ~$0.12 estimated)`); after a `/model` switch the info bar's tooltip adds a `per model:` row per run of turns on one model above those totals (`splash:qwen3-35b · 6 turns · 96.0k in / 9.0k out · ~$0.02`, a switch's prefill under its row: `└ switch prefill 58.0k uncached prompt ≈$0.01`; the timing's `model_segments`, replaced by each `generation_completed`'s; the session cards stay as they were), and right after the switch its ctx % is the new model's window's; and the memory indexes its prompt holds (`memory index: ~3.4k tokens in this session's prompt (system 2.0k, project 1.4k)`; see [Memory](memory.md#the-indexs-size)). The start page's model picker (bottom left of the composer, the chosen name `▾`) chooses the model a new session starts on, and a fresh chain link's (see [Session chains](#session-chains); there a pick shows as a `/model` command bubble in the link); it opens a search list over the conversation (↓ or a click; downward when the start page leaves no room above): an empty search shows the last 5 picks (Recent) and then each host's model ids A–Z under the host, the default host first (an id the host declares under `hosts.<name>.models` first, noted `config`, its tooltip `served by config (hosts.<name>.models)`; a host that failed to list its models keeps those ids, greyed and noted `host down`, still pickable; a remembered or default model stays chosen even then, greyed on the button); typed words must each match the host or the id (a substring, else for 3+ characters the letters in order, so `deepseek4.1 fla` finds `openrouter · deepseek/deepseek-v4.1-flash`), ⏎ picks, Esc/Tab close, a pick puts the focus in the message box: `GET /api/models` lists the hosts' models as chi spells them (`{default, models: [{name, host, id, configured?, unavailable?, sampling?, llm_context?}], warning?}`; `configured: true` marks an id declared under `hosts.<name>.models`, listed first under its host, `unavailable: true` one whose host failed to list its models; `sampling` is the model's configured request parameters as `/model` words them, the row's tooltip in the list; bare for the default host, `host:model` for the others, from the same cached lists as `/models`, a bounded wait, a host that is down noted in `warning`; `toolkits`: `{default, suggest, kits: [{name, description?}]}`, the start page's 🧰 list: the configured `toolkit.default`, `suggest` `on` only when a new session's first message may get a suggested kit (`toolkit.suggest.mode: on`, a System 1 host, two described kits; else `audit` or `off`), and the built-in and config kits a new session can start on, without `review`, `child`, `undecided`, a kit `groups:` refuses or one that doesn't resolve (a base that is a bundle kit), the default always listed; left out when it can't be read), and `POST /api/sessions` takes `model` (blank means the default). Beside it, ⚙ opens the new session's rarely used settings (thinking and LLM context, following each `GET /api/models` row's `thinking` and `llm_context`, and the review files; see [configuration.md](configuration.md#llm-context-a-sessions-own-strategy)), and 🧰 its toolkit: **Auto** (with `toolkit.suggest.mode: on`: the first message may get a suggested kit, else the default) or a kit from the payload's `toolkits`, sent as `POST /api/sessions`'s `toolkit` (see [configuration.md](configuration.md#toolkits)); a refused kit (`400 toolkit_refused`) is said in the list, opened again. What is set shows on the row as an accent chip (`think high`, `tools: lean`; a dot on ⚙ or 🧰 on a phone); each is for the next new session only, never remembered. The start page's first message goes as later ones do: `POST /api/sessions` with `idle: true` and `preview` (the message, which names the session until its turn is saved), then `POST /api/sessions/:id/turn`, so a failed first turn puts its prompt back in the composer too; a first line that is one of the new session's commands (`/model …`) goes to `POST /api/sessions/:id/command` instead, as later ones do. The browser remembers the last model picked; a running session's model is in the info bar and changes only with `/model`. In the composer a line is a command when it is `!…` or starts with one of the session's command names (its `commands` list; `/stats`, `/exit` and the other terminal words get the page's own reply); an unknown `/word` (`/usr/bin/env is missing`) goes to the model as a prompt, as in a terminal; a one-word `/word` no command answers (`/modle`) is not sent: the page shows `Unknown command /modle. Did you mean /model? /help lists the commands.` (the "Did you mean" part only when a name is close). A `POST /turn` (or a session's first `prompt`) that is one of the worker's commands runs as that command too (`202 {status, command_id, session_id}`), so `chi send`, `chi -p` and a page whose command list lags all get the command. ↑/↓ in the composer walk the prompt history the TUI's ↑ walks ([Persistent Prompt History](cli.md#persistent-prompt-history)): ↑ with the caret on the first line, ↓ from the last line while browsing, ↓ past the newest brings the draft back; `GET /api/history` returns `{entries: [...]}`, oldest first (the page fetches it on focus and after each send). The server records a sent line in the routes once the worker took it (`POST /turn` accepted, a `!command` through `POST /command` or as a session's first line); `"history": false` in the body keeps it out (an image-only send).
|
|
100
100
|
- Web notifications: when a session needs you while the tab is hidden or behind another window (a question or a guardrail approval, a plugin card with buttons during a turn such as check-in's, a failed turn, a turn done after 10 s or more; a delegated session only for its questions, a canceled turn never), the page title counts it, `(N) Chi`, until you come back to the tab. The bell at the right of the top bar also turns on OS notifications ("needs an answer", "needs approval", "needs you", "turn failed", "done in 42 s", under the session's first message; a click opens the session): its first click asks the browser for the permission, and the choice is kept per browser. Any session of the page's scope counts, not only the open one. What was already so when the page loaded never counts, and several chi tabs show one notification per event. A chi tab in front tells the others (a `BroadcastChannel`), so while you look at one, the ones behind neither notify nor count what it shows; coming back to a tab clears those events in the other tabs' titles too. The hub's `session` frames carry what this needs: `pending_question` (`{id, kind}`, kind `question` or `approval`), `pending_card` (`{id, bundle}`: the running turn's card with actions, from `pending_card.json` that the worker keeps in the session's folder while one is open; a card without actions, such as loop-guard's, never counts) and `last_turn` (`{outcome, ended_at, seconds, origin}`, saved in the session's JSON as the engine ends each turn).
|
|
101
|
-
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height: the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `stage_view.js` (the stage view: the running turn pinned above the composer, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model: id, status, model, chain links, chips, ctx, speed, clock, worker badge), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails and the lightbox), `composer_grip.js` (the composer's grip and fold: the drag, tap and keys, the fold per visit), `composer_mount.js` (the composer mounted on a page's markup: the message box and its height, the image chips from a paste, a drop or the image button, the grip and fold, ↑/↓ over the prompt history and the keys; the page's own parts come in as hooks: what Enter and Send do, keys taken first, Esc, where the history comes from, the info bar's Stop turn and drop while folded, typing anywhere to open it; its styles, the card it sits in (`.composer-card`, its footer and its line above the text field) included, are the shared `composer.css`, linked after `tokens.css` by `index.html` and `participant.html`), `strip_grip.js` (the latest-sessions strip's grip, the composer grip's twin: hides and shows the strip), `review_history.js` (a participant's ↑/↓ list on the participant page: their own comments, in localStorage per grant, never the owner's `/api/history`; `participant.js` mounts `composer_mount.js` with it, no `/` list, no delivery choices, images off), `storage.js` (the page's per-browser choices in localStorage, guarded: a choice that can't be read or written is not remembered), `unqueue.js` (the × on a message queued for after the turn: takes it back, its text into an empty composer or a toast), `toasts.js` (the page's toast stack: a timer each, sticky ones until acted on, the same text reusing its item), `toast_place.js` (where the toast sits: above the composer card, the stage and an open model panel), `dock_reserve.js` (what floats over the history: the history's bottom reserve (`--dock-h`) at the composer card's and the showing stage's height, a reader at the end kept there, and the toast's place measured for `toast_place.js`), `notice_links.js` (a hook notice line's http(s) URLs as links), `start_page.js` (the start page's model picker
|
|
101
|
+
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height: the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `stage_view.js` (the stage view: the running turn pinned above the composer, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model: id, status, model, chain links, chips, ctx, speed, clock, worker badge), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails and the lightbox), `composer_grip.js` (the composer's grip and fold: the drag, tap and keys, the fold per visit), `composer_mount.js` (the composer mounted on a page's markup: the message box and its height, the image chips from a paste, a drop or the image button, the grip and fold, ↑/↓ over the prompt history and the keys; the page's own parts come in as hooks: what Enter and Send do, keys taken first, Esc, where the history comes from, the info bar's Stop turn and drop while folded, typing anywhere to open it; its styles, the card it sits in (`.composer-card`, its footer and its line above the text field) included, are the shared `composer.css`, linked after `tokens.css` by `index.html` and `participant.html`), `strip_grip.js` (the latest-sessions strip's grip, the composer grip's twin: hides and shows the strip), `review_history.js` (a participant's ↑/↓ list on the participant page: their own comments, in localStorage per grant, never the owner's `/api/history`; `participant.js` mounts `composer_mount.js` with it, no `/` list, no delivery choices, images off), `storage.js` (the page's per-browser choices in localStorage, guarded: a choice that can't be read or written is not remembered), `unqueue.js` (the × on a message queued for after the turn: takes it back, its text into an empty composer or a toast), `toasts.js` (the page's toast stack: a timer each, sticky ones until acted on, the same text reusing its item), `toast_place.js` (where the toast sits: above the composer card, the stage and an open model panel), `dock_reserve.js` (what floats over the history: the history's bottom reserve (`--dock-h`) at the composer card's and the showing stage's height, a reader at the end kept there, and the toast's place measured for `toast_place.js`), `notice_links.js` (a hook notice line's http(s) URLs as links), `start_page.js` (the start page's model picker, its ⚙ panel's and 🧰 list's choices for the next new session only and their override chips; a fresh chain link's picker and its `/model`), `start_settings.js` (the start page's ⚙ panel: thinking and LLM context as rows of segments, applied at once, the Apply and budget disclosure, the review files' view; the override chips' words and ⚙'s dot), `start_toolkit.js` (the start page's 🧰 list: Auto with suggest on, the kits, the default marked; a pick closes it; its override chip and dot), `session_actions.js` (Continue, Archive and its Undo, Delete and Stop, and the start page when the open session is gone), `send_turn.js` (the composer's send: a new session first on the start page, the route, the echo, the image upload, the `/turn` ack, a fast failure's restore and each error's place). Unit-tested via `npm test` (`spec/web/public/*.test.js`).
|
|
102
102
|
- Selecting a session in the web UI is read-only: `GET /api/sessions/:id` never spawns a worker (it reads a live worker's snapshot when one runs, else the session file). A prompt (`POST /turn`) or a command (`POST /command`) wakes the worker, and `/stream` briefly waits for a freshly-spawned bridge before answering. A caught-up SSE reconnect holds the stream open; `reset` markers are only sent for reconnects behind the ring window, or with a cursor from another worker (event ids are `<event_seq>-<epoch>`, one epoch per worker).
|
|
103
103
|
- The web session page's message box folds away for room to read. Drag the grip on its top edge (the pill that shows on hover; always on a phone) down, past the box by 32 px: the pill turns accent while releasing would hide it, and on release the box folds and the info bar stays as the page's bottom edge. The grip stays as a handle on the info bar's top edge, drawn always: pull it up (8 px opens it, and the box follows the pointer in the same gesture), click or tap it (opens it and focuses the box), or just type on the page (the key lands in the box) to bring it back; Enter or Space on the focused grip folds or opens too. A draft (text or images, which folding never clears) colours the handle with the accent, a session waiting on you with the attention colour; its tooltip says so. Stop turn moves into the info bar while it is folded. The fold is remembered per browser (`chi_composer_collapsed`), an archived session opens folded for the visit, and opening it there, like the page opening it itself (a restored line, a quote, continue →'s opener), is for that visit only. The fold keeps the height the grip set (`chi_composer_floor`): the box opens again at the height it had, and only a double-click on the grip forgets it. That height never takes more than half of the window the box is drawn in: a floor saved in a bigger window is held to that half in a smaller one (a rotated phone, a resized window, another device on the same origin), and the saved floor itself stays, so the height comes back when the room does. A click on the expanded grip hides the box as well: it folds 250 ms after the press, so a second click inside that window is read as a double-click and resets the height instead (a drag, Enter or Space act at once, and a drag after a click takes the wait back). The start page's grip only resizes.
|
|
104
104
|
|
|
@@ -296,10 +296,10 @@ sessions](cli.md#review-sessions)); both start idle and print the `chi share` li
|
|
|
296
296
|
folder and setup are taken (`dir` and the setup fields beside it are 400 `invalid_review`) and `model` is the
|
|
297
297
|
only choice. A subject refused, or the source's folder gone, is 400 `invalid_review` with the one message; an
|
|
298
298
|
unknown source 404 `not_found`.
|
|
299
|
-
- **The page:** the start page's
|
|
300
|
-
space-separated, relative to the page's folder; a path with a space in double quotes, `"docs/my plan.md"`):
|
|
301
|
-
|
|
302
|
-
turn; with none it starts idle). A refused file shows the server's one message in the
|
|
299
|
+
- **The page:** the start page's ⚙ panel, **Review files…**, takes the files (comma- or
|
|
300
|
+
space-separated, relative to the page's folder; a path with a space in double quotes, `"docs/my plan.md"`): the
|
|
301
|
+
row then shows a `review: plan.md +1` chip, and Start makes a review session (the message typed, if any, is its first
|
|
302
|
+
turn; with none it starts idle). A refused file shows the server's one message in the panel's review view, opened again. On a session that isn't a review session the participants panel (the session bar's
|
|
303
303
|
participants chip) says so before its Invite, with the share warning (that a participant's turns act there, writes
|
|
304
304
|
included and asks to the owner, or only read while an older worker holds it; how many tool outputs its history holds)
|
|
305
305
|
and **Start a review of it**: a review fork of it, opened, with a toast (`Review 4b7e9a01 started from 3f9a1c2e's
|
|
@@ -364,6 +364,61 @@ otherwise; `settings` beside `continues` is refused). A respawned or woken worke
|
|
|
364
364
|
delegate child starts without (a bundle has its own setting for children, such as cost-cap's `child:`), so its recap
|
|
365
365
|
follows config.yml. `/stats` names them on a `settings:` line, and `chi sessions stats --format json` as `settings`.
|
|
366
366
|
|
|
367
|
+
## Project env
|
|
368
|
+
|
|
369
|
+
The commands a session's worker starts for the session (`execute`, tasks, `!cmd`, MCP servers, context sources)
|
|
370
|
+
follow the session's project, not whoever started the worker (a terminal on another Ruby, chi web, the macOS helper
|
|
371
|
+
under launchd). At start a worker runs `mise env -C <session folder> --json` once (`ProjectEnv`,
|
|
372
|
+
`session.project_env: mise`, the default) and merges the answer into the env of those commands: a project whose
|
|
373
|
+
mise.toml pins Ruby 3.4 gets that `ruby`, `gem` and `bundle` in its tools while chi itself runs on the
|
|
374
|
+
[chi home](configuration.md#the-chi-home).
|
|
375
|
+
|
|
376
|
+
- **Tools only.** The worker's own process keeps the env it was started with: chi's model calls and API keys, its
|
|
377
|
+
proxies, config, dirs, hooks and plugins never see the project's `[env]` (a mise.toml that sets
|
|
378
|
+
`ANTHROPIC_API_KEY` or `https_proxy` changes only what its tools see). Hooks run with the worker's env, not the
|
|
379
|
+
project's. A `chi` a tool runs (`chi -p`, `chi models`, `chi send`) takes the worker's values back first thing, so
|
|
380
|
+
it too runs on your keys and proxies, not the project's.
|
|
381
|
+
- **Once per worker.** A mise.toml edit (or a `mise use` in a tool) reaches the session at its next worker:
|
|
382
|
+
`chi sessions restart ID` (or the web's restart) picks it up.
|
|
383
|
+
- **GEM_HOME/GEM_PATH.** The starter's are dropped from the tools' env when the project's `ruby` is another one (they
|
|
384
|
+
belong to the starter's Ruby), unless mise sets its own; kept when the Ruby stays the same.
|
|
385
|
+
- **Never what a `chi` in a tool reads.** The tools' env never takes `HOME`, any `XDG_*`, any `SAMAGOTCHI_*`,
|
|
386
|
+
`CHI_REMOTE`, `RACK_ENV` or `CI` from the project (a `chi` run there would read another config or state dir, or
|
|
387
|
+
send its session commands to another machine): they are dropped
|
|
388
|
+
and the debug log names them once (`project_env_reserved`). `mise env` runs without `MISE_YES` (it would trust an
|
|
389
|
+
untrusted mise.toml for you) and `CI`; your `MISE_TRUSTED_CONFIG_PATHS` stays.
|
|
390
|
+
- **Only this session.** A worker started from this one (a restart, a delegate child) starts on the worker's own
|
|
391
|
+
env. One started from a tool (`chi send --new --dir other/project`) too: the tools' env carries the worker's values
|
|
392
|
+
(`SAMAGOTCHI_PROJECT_ENV_ORIG`) and that `chi` takes them back, so project A's PATH, `[env]` values, GEM_* and
|
|
393
|
+
library paths never reach a session in B.
|
|
394
|
+
- **Context sources** run in the project env of the worker that fetches them: the same source can read differently
|
|
395
|
+
from another session's worker (or a REPL, which has none).
|
|
396
|
+
- **Pair turns** (a participant's, see [Participants](internals/participants.md)) run their `execute` without the
|
|
397
|
+
project env. MCP servers are the session's, started once in the project env, so a pair turn's MCP calls do use
|
|
398
|
+
it. A participant's command that runs `mise` or `direnv`, and any write to mise's config (`mise.toml`,
|
|
399
|
+
`.mise.toml`, `mise.<env>.toml`, `.config/mise.toml`, `.config/mise/…`, `mise/` or `.mise/config*.toml`, and
|
|
400
|
+
`.tool-versions`: your next worker start runs it, and its `[env]` can run commands), a delete or move of one
|
|
401
|
+
included, asks you first; a read-only mention (`find . -name mise.toml`) doesn't. `.envrc` and mise's local files
|
|
402
|
+
(`mise.local.toml`, `mise.<env>.local.toml`, dotted or not, and `config.local.toml` / `config.<env>.local.toml` in
|
|
403
|
+
`.config/mise/`, `mise/`, `.mise/`) are secrets to them, as `.env` is.
|
|
404
|
+
- **What tools still drop**: every `execute`, task and `!cmd` takes no `RUBYOPT`, `RUBYLIB`, `BUNDLE_GEMFILE`,
|
|
405
|
+
`BUNDLE_BIN_PATH` or `BUNDLER_VERSION` from the project's mise env: it runs without `RUBYLIB` and Bundler's
|
|
406
|
+
variables, and with the worker's own `RUBYOPT`, Bundler's part removed (`TaskRuntime`).
|
|
407
|
+
- **`chi` in a tool** stays the home's: with a chi home the tools' PATH starts with `$XDG_STATE_HOME/samagotchi/bin`,
|
|
408
|
+
a dir holding only a `chi` script that boots the home (rewritten at each worker start when the home changed; it
|
|
409
|
+
unsets `RUBYOPT`, `RUBYLIB`, `RUBYGEMS_GEMDEPS`, `GEMRC` and `BUNDLE*` before it runs, so a `bundle exec` around it
|
|
410
|
+
doesn't load the project's gems into chi; and `LD_PRELOAD`, `LD_LIBRARY_PATH` and their `DYLD_*` kin). The project's `ruby`, `gem` and `bundle` stay the project's; `bin/chi`, a
|
|
411
|
+
checkout path or `bundle exec chi` stay themselves. Without a home there is no script and no PATH change.
|
|
412
|
+
- **When it does nothing**: `session.project_env: off` (mise isn't asked; with a chi home the `chi` script still
|
|
413
|
+
goes first on the tools' PATH); a session without a folder (`none (no_dir)`); no `mise` (looked up as home.json's `mise`, then PATH, then
|
|
414
|
+
`/opt/homebrew/bin`, `/usr/local/bin`, `~/.local/bin`); the session's folder is gone (the worker runs elsewhere).
|
|
415
|
+
A `mise env` that fails (an untrusted mise.toml: run `mise trust` there; a pinned Ruby not installed), takes over
|
|
416
|
+
5 s or doesn't answer JSON changes nothing and leaves one `project_env` warning in the debug log; `chi home doctor`
|
|
417
|
+
run in that folder shows it, with the fix, until a later worker there applies the env.
|
|
418
|
+
- `chi self` run in a tool shows what the worker computed (`project env`: `mise (ruby PATH)` or `none (why)`) and the
|
|
419
|
+
chi home (`home`).
|
|
420
|
+
- The REPL modes (`--no-shared`, `--non-interactive`, `--verbose`) run no worker: their tools keep the shell's env.
|
|
421
|
+
|
|
367
422
|
## Delegating
|
|
368
423
|
|
|
369
424
|
The `delegate` tool hands a task to a **child session**: an ordinary chi session in a worker of its own, started in the parent's `working_directory` with the task, verbatim, as its first user message, on the parent's model unless the call names one (`model:` takes a name or an alias, resolved as `--model` is; an unknown host comes back as the tool's `Error:` line; an id the host's saved model list doesn't have starts the child with a `Warning: host 'h' doesn't list model 'x' (did you mean: …?)` line in the result). Children run in parallel and only their **final reply** comes back to the parent: the child's newest `output/<timestamp>.txt` file, which the worker writes at the end of each turn that produced visible text, cut head-and-tail above 64 KB (`DelegateWait.cut`); a reply longer than `max_tool_output_chars` keeps its start and its end (the conclusion), with a gap line naming that `output/` file, where the whole reply is (`ToolOutputCut`'s `:head_tail_ref`; see [Tool output guardrails](internals/tool-guardrails.md#the-runners-cut-max_tool_output_chars)). Nothing of the child's trace enters the parent's context. Nothing is hidden: a child shows in `chi sessions list` (`↳ <parent>`), the web (folded into its parent's card on the strip and in all sessions, whose `▸ N delegates` chip lists the delegates at any depth, see Web UI above; a card of its own with a `↳` chip when its parent isn't listed; `delegated by` in its info bar; the parent's info bar carries a `⑂ N` chip counting its delegates, with how many run, wait, are done, failed, stopped or idle in the tooltip and the waiting ones named in the attention colour; a click opens all sessions), the terminal's status row (a parent's `⑂ 2 running · 1 waiting`, see [Status Line](cli.md#status-line)) and the `list_sessions` tool (`child`; the parent shows as `parent` in the child's own list); the user can `chi --attach <child id>` and steer it mid-run, and `chi send` and `send_note` reach it like any session.
|
data/docs/testing.md
CHANGED
|
@@ -44,7 +44,7 @@ exception's text changes between Ruby versions: write the string yourself).
|
|
|
44
44
|
The web specs run in plain node. One that loads lit-html, itself or through a module it imports (`turn_view.js`,
|
|
45
45
|
`turn_html.js`, `card.js`, `copy.js`, `images.js`, `scope.js`, `command_view.js`, `diff_view.js`, `read_view.js`,
|
|
46
46
|
`question_cards.js`, `stream_handlers.js`, `stage_view.js`, `bubbles.js`, `cards_place.js`, the chips, `info_bar.js`, `info_bar_model.js`, `lists_view.js`, `context_chips.js`, `families_view.js`,
|
|
47
|
-
`chains.js`, `working_set_view.js`, `working_set_rail.js`, `unqueue.js`, `toasts.js`, `notice_links.js`, `start_page.js`, `session_actions.js`, `send_turn.js`, `composer_mount.js`, `dock_reserve.js`,
|
|
47
|
+
`chains.js`, `working_set_view.js`, `working_set_rail.js`, `unqueue.js`, `toasts.js`, `notice_links.js`, `start_page.js`, `start_settings.js`, `start_toolkit.js`, `session_actions.js`, `send_turn.js`, `composer_mount.js`, `dock_reserve.js`,
|
|
48
48
|
`vendor/lit-html.js`) needs a DOM: `import "./dom_shim.js";` as its first import (happy-dom, a devDependency only,
|
|
49
49
|
never shipped; lit reads `document` as it loads). The shim's `markupOf(template)`,
|
|
50
50
|
`htmlOf(nodes)` and `canon(html)` compare markup without lit's marker comments; the DOM writes text with only `&`, `<`, `>`
|
|
@@ -95,6 +95,9 @@ run, CI) and too long on a fast one. The contract a new spec follows:
|
|
|
95
95
|
4. **"Nothing happens" is shown by counting passes** (the worker's loop rounds, spec/support/worker_loop_rounds.rb;
|
|
96
96
|
a class's ticks), not by a pause.
|
|
97
97
|
5. **A wall-clock bound** only as "not the full N s", with at least 5× headroom measured on the slow (x86) laptop.
|
|
98
|
+
Write it `be < time_bound(3, below: 5)`: the bound scaled like a helper's deadline, and kept under the unscaled
|
|
99
|
+
deadline it tells apart from (here a 5 s read timeout), so the check still fails on the full wait at any scale. A
|
|
100
|
+
cost bound with nothing to tell apart from ("no quadratic blow-up") takes no `below:`.
|
|
98
101
|
|
|
99
102
|
The helpers are the bundle test kit's (`Samagotchi::Testing::Waiting`, [plugins.md](plugins.md#testing-a-bundle-experimental)),
|
|
100
103
|
so core and bundle specs share one copy; `SpecWaiting` (spec/support/waiting.rb) includes them in every example
|
|
@@ -107,6 +110,7 @@ group and also answers them as module calls (`SpecWaiting.pop!`, for a stubbed l
|
|
|
107
110
|
same deadline and message. A gate a stubbed lib thread waits on takes `timeout: 30`: it only ends a hang.
|
|
108
111
|
- `wait_until(timeout:) { … }` returns the block's last value (falsy at the deadline): for a value the example
|
|
109
112
|
checks after, or a `wait-ok` wait.
|
|
113
|
+
- `time_bound(seconds, below: nil)`: a wall-clock upper bound, scaled and kept under `below:` (rule 5).
|
|
110
114
|
- `eventually(timeout: 5) { expect(…) }` (spec only) retries until the expectations hold, then re-raises the last
|
|
111
115
|
failure prefixed `still failing after 5 s:`, so the matcher's own expected/got is in the message.
|
|
112
116
|
|
|
@@ -129,8 +133,8 @@ Every example also runs under a 120 s limit (`spec_helper`'s `around`; `integrat
|
|
|
129
133
|
limit, `0` turns it off (a debugger session). The limit is not scaled.
|
|
130
134
|
|
|
131
135
|
**The cops.** `Samagotchi/SpecSleep` (an untagged `sleep` in a spec) and `Samagotchi/SilentWait` (a `wait_until`
|
|
132
|
-
whose value is dropped, an example's last line included, `expect(wait_until { … }).to be(true)`,
|
|
133
|
-
`Timeout.timeout`) live in `rubocop/` and run in `rake lint`, so CI fails on them. RSpec counts `wait_for`,
|
|
136
|
+
whose value is dropped, an example's last line included, `expect(wait_until { … }).to be(true)`, an untagged
|
|
137
|
+
`Timeout.timeout`, or a statement `thread.join(N)`, whose N is unscaled and whose nil is dropped: use `join!`) live in `rubocop/` and run in `rake lint`, so CI fails on them. RSpec counts `wait_for`,
|
|
134
138
|
`eventually`, `join!` and `pop!` as an example's expectation (`RSpec/NoExpectationExample`), so a wait can be an
|
|
135
139
|
example's last line. What the cops can't see, `script/affected-specs` hints at (`timing:`, below).
|
|
136
140
|
|
|
@@ -184,6 +188,7 @@ any other file requires it, so a spec file run alone still finds its requires. E
|
|
|
184
188
|
| `fake_provider_server.rb` | `FakeProviderServer`: an in-process HTTP provider replaying spec/fixtures/providers, recording requests |
|
|
185
189
|
| `fake_tailscale.rb` | A fake `tailscale` for `Web::Tunnel::Tailscale` (status, serve, lock from JSON files; argv.log) |
|
|
186
190
|
| `git_repo.rb` | *helper*: `git_repo`, a temp folder with `git init`, removed after the example |
|
|
191
|
+
| `lock_holder.rb` | *helper*: `spawn_lock_holder(session_dir)`, a stand-in worker process holding a session's owner lock, which says so on a pipe |
|
|
187
192
|
| `integration_server.rb` | *helper*: the live model server `:integration` examples use, from `SAMAGOTCHI_INTEGRATION_*` ([Integration specs](#integration-specs)) |
|
|
188
193
|
| `mcp_bundle.rb` | The shipped mcp bundle's path and the fake MCP server its specs start (`MCP_FAKE_COMMAND`, no RubyGems) |
|
|
189
194
|
| `no_console.rb` | Loaded first (`ruby -r`) by spawned bin/chi children: `IO.console` is nil, so output never wraps at a terminal's width |
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: mcp
|
|
3
|
-
version: 0.7.
|
|
3
|
+
version: 0.7.3
|
|
4
4
|
scope: system
|
|
5
5
|
description: "Tools from MCP servers (stdio): each server in config.yml bundles: mcp: servers: runs for the session; their tools go into chi's tool index: the model searches them with find_tools and calls one with call_tool (<server>/<tool>); /mcp lists them"
|
|
6
6
|
trust_level: reviewed
|
|
7
7
|
files: {}
|
|
8
8
|
plugin:
|
|
9
9
|
file: plugin.rb
|
|
10
|
-
sha256: sha256:
|
|
10
|
+
sha256: sha256:65532b75b33fa7a58b4a35f9ed32e2705f4e3d323c6f770e71448da5cc9314d0
|
|
11
11
|
# 0.67.0 is the release with chi.tool_source (the core tool index the bundle publishes into).
|
|
12
12
|
requires_chi: ">= 0.121.0"
|
|
@@ -107,7 +107,7 @@ class Plugin
|
|
|
107
107
|
@next_id = 0
|
|
108
108
|
@dead = nil
|
|
109
109
|
@closing = false
|
|
110
|
-
@stdin, @stdout, @stderr, @wait = Open3.popen3(env.to_h { |k, v| [k.to_s, v
|
|
110
|
+
@stdin, @stdout, @stderr, @wait = Open3.popen3(env.to_h { |k, v| [k.to_s, v&.to_s] }, *command,
|
|
111
111
|
chdir: cwd, pgroup: true)
|
|
112
112
|
@pid = @wait.pid
|
|
113
113
|
start_watchdog
|
|
@@ -433,7 +433,7 @@ class Plugin
|
|
|
433
433
|
def spawn(server, ctx)
|
|
434
434
|
cancelled = -> { ctx.cancelled? }
|
|
435
435
|
client = server.client = Client.new(
|
|
436
|
-
server.command, env: server
|
|
436
|
+
server.command, env: server_env(server), cwd: server.cwd,
|
|
437
437
|
log: ->(event, **fields) { ctx.log.debug("mcp_#{event}", server: server.name, **fields) },
|
|
438
438
|
on_exit: ->(reason) { exited(server, reason, ctx) },
|
|
439
439
|
on_notification: lambda { |method, _params|
|
|
@@ -454,6 +454,13 @@ class Plugin
|
|
|
454
454
|
client
|
|
455
455
|
end
|
|
456
456
|
|
|
457
|
+
# A server's env: the session's project env (the worker's mise env, on a
|
|
458
|
+
# chi that has it: Samagotchi::ProjectEnv) under the server's own keys.
|
|
459
|
+
def server_env(server)
|
|
460
|
+
project = defined?(Samagotchi::ProjectEnv) ? Samagotchi::ProjectEnv.current.env : {}
|
|
461
|
+
project.merge(server.env)
|
|
462
|
+
end
|
|
463
|
+
|
|
457
464
|
# The first sentence of initialize's instructions (at most
|
|
458
465
|
# DESCRIPTION_CHARS), nil when there are none.
|
|
459
466
|
def info_of(result)
|
|
@@ -494,7 +501,7 @@ class Plugin
|
|
|
494
501
|
return nil unless lock.flock(File::LOCK_EX | File::LOCK_NB)
|
|
495
502
|
|
|
496
503
|
cancelled = -> { ctx.cancelled? }
|
|
497
|
-
client = Client.new(server.command, env: server
|
|
504
|
+
client = Client.new(server.command, env: server_env(server), cwd: server.cwd,
|
|
498
505
|
log: ->(event, **fields) { ctx.log.debug("mcp_#{event}", server: server.name, **fields) })
|
|
499
506
|
begin
|
|
500
507
|
initialized = client.request("initialize", { protocolVersion: PROTOCOL_VERSION, capabilities: {},
|
data/lib/samagotchi/chi_home.rb
CHANGED
|
@@ -42,6 +42,15 @@ module Samagotchi
|
|
|
42
42
|
class Invalid < StandardError
|
|
43
43
|
end
|
|
44
44
|
|
|
45
|
+
# A record of this process under Bundler (`bundle exec chi home set`)
|
|
46
|
+
# would name the bundle's Ruby and gems as the home every launch boots.
|
|
47
|
+
class UnderBundler < StandardError
|
|
48
|
+
def initialize(msg = "under Bundler (bundle exec) this chi's gem path is the bundle's, not a chi home: " \
|
|
49
|
+
"run chi itself, or name another Ruby with --ruby")
|
|
50
|
+
super
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
|
|
45
54
|
# home.json's fields. +gem_path+ is what `Gem.paths=` takes (dirs joined
|
|
46
55
|
# by File::PATH_SEPARATOR); +mise+ an absolute path or nil.
|
|
47
56
|
Record = Data.define(:ruby, :gem_home, :gem_path, :mise, :set_at, :set_by_version) do
|
|
@@ -274,8 +283,9 @@ module Samagotchi
|
|
|
274
283
|
nil
|
|
275
284
|
end
|
|
276
285
|
|
|
277
|
-
#
|
|
278
|
-
#
|
|
286
|
+
# Whether this process runs under Bundler (`bundle exec`), where a
|
|
287
|
+
# record of it would name the bundle's gems: record_first!, chi home
|
|
288
|
+
# set (UnderBundler) and chi update's @bundler.
|
|
279
289
|
def under_bundler?(env = ENV) = !!(defined?(::Bundler) || !env["BUNDLE_GEMFILE"].to_s.empty?)
|
|
280
290
|
|
|
281
291
|
# mise's absolute path: on +env+'s PATH, else in MISE_DIRS; nil without.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "shellwords"
|
|
5
|
+
require_relative "atomic_file"
|
|
6
|
+
require_relative "chi_home"
|
|
7
|
+
require_relative "log"
|
|
8
|
+
require_relative "paths"
|
|
9
|
+
|
|
10
|
+
module Samagotchi
|
|
11
|
+
# The `chi` a worker's tools run: $XDG_STATE_HOME/samagotchi/bin/chi, a
|
|
12
|
+
# shell script that execs the chi home's Ruby with its boot
|
|
13
|
+
# (ChiHome::Record#boot_argv, CHI_BOOT). ProjectEnv puts its dir first on
|
|
14
|
+
# the worker's PATH, so after the project env (whose PATH would find the
|
|
15
|
+
# project Ruby's chi, an old one or none) an agent's `chi send`, `chi self`
|
|
16
|
+
# or `chi answer` still runs the home's chi. The dir holds `chi` only: the
|
|
17
|
+
# project's ruby, gem and bundle stay the project's; bin/chi, a checkout
|
|
18
|
+
# path or `bundle exec chi` stay themselves.
|
|
19
|
+
module ChiShim
|
|
20
|
+
NAME = "chi"
|
|
21
|
+
HEADER = "# chi's own chi for its tools (ChiShim): rewritten at each worker start from the chi home.\n"
|
|
22
|
+
# A project's RUBYOPT/RUBYLIB/RUBYGEMS_GEMDEPS/GEMRC/BUNDLE_* (a `bundle
|
|
23
|
+
# exec` the tool runs under, a mise [env]) would load the project's gems
|
|
24
|
+
# or settings into the home's chi, its LD_*/DYLD_* libraries into its
|
|
25
|
+
# ruby: unset before the exec.
|
|
26
|
+
UNSET = "unset RUBYOPT RUBYLIB RUBYGEMS_GEMDEPS GEMRC LD_PRELOAD LD_LIBRARY_PATH DYLD_INSERT_LIBRARIES " \
|
|
27
|
+
"DYLD_LIBRARY_PATH\n" \
|
|
28
|
+
"for v in $(/usr/bin/env | /usr/bin/sed -n 's/^\\(BUNDLE[A-Za-z0-9_]*\\)=.*/\\1/p'); do unset \"$v\"; done\n"
|
|
29
|
+
|
|
30
|
+
module_function
|
|
31
|
+
|
|
32
|
+
# @return [String] $XDG_STATE_HOME/samagotchi/bin
|
|
33
|
+
def dir(env: ENV) = File.join(Paths.state_dir(env: env), "bin")
|
|
34
|
+
|
|
35
|
+
def path(dir: self.dir) = File.join(dir, NAME)
|
|
36
|
+
|
|
37
|
+
# The script for +home+.
|
|
38
|
+
# @param home [ChiHome::Record]
|
|
39
|
+
def content(home)
|
|
40
|
+
argv = home.boot_argv(run: ChiHome::CHI_BOOT) + ["--"]
|
|
41
|
+
"#!/bin/sh\n#{HEADER}#{UNSET}exec #{argv.map { |arg| Shellwords.escape(arg) }.join(" ")} \"$@\"\n"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Writes the shim for +home+ unless it is already that (atomically: a
|
|
45
|
+
# tool running `chi` meanwhile gets the old one or the new one).
|
|
46
|
+
# @return [Boolean] whether the shim is there and current
|
|
47
|
+
def ensure!(home, dir: self.dir)
|
|
48
|
+
file = path(dir: dir)
|
|
49
|
+
want = content(home)
|
|
50
|
+
return true if current?(file, want)
|
|
51
|
+
|
|
52
|
+
FileUtils.mkdir_p(dir)
|
|
53
|
+
AtomicFile.write(file, want, perm: 0o755)
|
|
54
|
+
true
|
|
55
|
+
rescue SystemCallError => e
|
|
56
|
+
Log.warn(:worker, "chi_shim_failed", path: file, error: e.class.name, msg: e.message)
|
|
57
|
+
false
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Why the shim isn't +home+'s (chi home doctor), or nil: nil too
|
|
61
|
+
# without one (the first worker start writes it).
|
|
62
|
+
# @return [String, nil]
|
|
63
|
+
def problem(home, dir: self.dir)
|
|
64
|
+
file = path(dir: dir)
|
|
65
|
+
return nil if !File.exist?(file) || current?(file, content(home))
|
|
66
|
+
|
|
67
|
+
"the chi script tools run (#{Paths.tilde(file)}) boots another chi than the home: " \
|
|
68
|
+
"the next worker start rewrites it (chi sessions restart ID for a running session)"
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def current?(file, want)
|
|
72
|
+
File.file?(file) && File.executable?(file) && File.read(file) == want
|
|
73
|
+
rescue SystemCallError
|
|
74
|
+
false
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
data/lib/samagotchi/child_env.rb
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
require_relative "installed_gem"
|
|
4
4
|
require_relative "installed_versions"
|
|
5
|
+
require_relative "project_env"
|
|
5
6
|
|
|
6
7
|
module Samagotchi
|
|
7
8
|
# What a chi process another chi starts must not take from its spawner's
|
|
@@ -23,11 +24,12 @@ module Samagotchi
|
|
|
23
24
|
module_function
|
|
24
25
|
|
|
25
26
|
# The keys of +env+ a child chi must not inherit: the guardrails
|
|
26
|
-
# settings, the session markers
|
|
27
|
-
# (InstalledVersions::ENV_KEY, for the spawner's notices only)
|
|
27
|
+
# settings, the session markers, a smoke's fake "newest installed"
|
|
28
|
+
# (InstalledVersions::ENV_KEY, for the spawner's notices only) and the
|
|
29
|
+
# worker's project env marker and record (a child worker applies its own).
|
|
28
30
|
# @return [Array<String>]
|
|
29
31
|
def spawner_keys(env = ENV)
|
|
30
|
-
env.each_key.select { |key| key.start_with?(GUARDRAILS_PREFIX) } + SESSION_MARKERS + [InstalledVersions::ENV_KEY]
|
|
32
|
+
env.each_key.select { |key| key.start_with?(GUARDRAILS_PREFIX) } + SESSION_MARKERS + [InstalledVersions::ENV_KEY, ProjectEnv::MARKER_ENV, ProjectEnv::ORIG_ENV]
|
|
31
33
|
end
|
|
32
34
|
|
|
33
35
|
# #spawner_keys mapped to nil: Process.spawn unsets a key mapped to nil.
|
data/lib/samagotchi/config.rb
CHANGED
|
@@ -138,6 +138,8 @@ module Samagotchi
|
|
|
138
138
|
Entry.new(key: "session.keep_status", yaml_path: %w[session keep_status], type: :string, default: "", expose: %i[env config cli], lifecycle: :next_retention_sweep),
|
|
139
139
|
Entry.new(key: "session.sweep_interval_hours", yaml_path: %w[session sweep_interval_hours], type: :integer, default: 24, expose: %i[env config cli], lifecycle: :next_retention_sweep),
|
|
140
140
|
Entry.new(key: "session.idle_exit_minutes", yaml_path: %w[session idle_exit_minutes], type: :float, default: 30.0, expose: %i[env config cli], lifecycle: :worker_start),
|
|
141
|
+
# Tools follow the project: a worker applies its folder's `mise env` at start (ProjectEnv); off keeps the spawner's env.
|
|
142
|
+
Entry.new(key: "session.project_env", yaml_path: %w[session project_env], type: :enum, default: "mise", expose: %i[env config], enum_values: %w[mise off], lifecycle: :worker_start),
|
|
141
143
|
# Plain `chi` runs like `chi --shared` (bin/chi, LaunchMode); false, or --no-shared per run, keeps the plain REPL. No CLI flag: that would duplicate --shared.
|
|
142
144
|
Entry.new(key: "session.shared", yaml_path: %w[session shared], type: :bool, default: true, expose: %i[env config], lifecycle: :next_invocation),
|
|
143
145
|
# false: a session nothing happened in is deleted when it is left (SessionManager.discardable?).
|
|
@@ -5,6 +5,7 @@ require_relative "context_sources"
|
|
|
5
5
|
require_relative "context_providers"
|
|
6
6
|
require_relative "log"
|
|
7
7
|
require_relative "process_group"
|
|
8
|
+
require_relative "project_env"
|
|
8
9
|
|
|
9
10
|
module Samagotchi
|
|
10
11
|
# Runs an attached context source's command once and records the result
|
|
@@ -108,8 +109,9 @@ module Samagotchi
|
|
|
108
109
|
|
|
109
110
|
def env_for(location, name)
|
|
110
111
|
previous = location.snapshot_path(name)
|
|
111
|
-
|
|
112
|
-
|
|
112
|
+
# The session's project env (ProjectEnv) under the source's own keys.
|
|
113
|
+
ProjectEnv.tools_env.merge("SAMAGOTCHI_CONTEXT_NAME" => name,
|
|
114
|
+
"SAMAGOTCHI_CONTEXT_PREVIOUS" => File.exist?(previous) ? previous : nil)
|
|
113
115
|
end
|
|
114
116
|
|
|
115
117
|
# @return [Run]
|
|
@@ -233,6 +233,50 @@ module Samagotchi
|
|
|
233
233
|
argv && argv_problem(argv)
|
|
234
234
|
end
|
|
235
235
|
|
|
236
|
+
# Why the launch file doesn't boot +home+ (chi home doctor), or nil:
|
|
237
|
+
# it runs [ruby, chi] (installed before the home), boots another Ruby
|
|
238
|
+
# or gem path (the home was set since), or bakes GEM_HOME/GEM_PATH
|
|
239
|
+
# under the home's boot. Each fixed by chi desktop upgrade. nil without
|
|
240
|
+
# a launch file.
|
|
241
|
+
# @param home [ChiHome::Record]
|
|
242
|
+
# @return [String, nil]
|
|
243
|
+
def home_problem(home)
|
|
244
|
+
launch = read_launch
|
|
245
|
+
argv = usable_argv(launch)
|
|
246
|
+
return nil unless argv
|
|
247
|
+
|
|
248
|
+
unless home_boot?(argv)
|
|
249
|
+
return "the desktop helper runs #{argv.first(2).join(" ")}, not the chi home's boot: chi desktop upgrade"
|
|
250
|
+
end
|
|
251
|
+
unless ChiHome.real(argv[0]) == ChiHome.real(home.ruby) && argv[2].to_s.start_with?("#{home.prelude};")
|
|
252
|
+
return "the desktop helper boots the chi home as it was (#{argv[0]}), not as it is now: chi desktop upgrade"
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
env = launch["env"]
|
|
256
|
+
baked = env.is_a?(Hash) ? GEM_ENV.select { |key| env.key?(key) } : []
|
|
257
|
+
return nil if baked.empty?
|
|
258
|
+
|
|
259
|
+
"the desktop helper's launch file sets #{baked.join(", ")} for its sessions' tools: chi desktop upgrade"
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
# The config dir the helper's chi reads (its home.json, config.yml):
|
|
263
|
+
# the launch file's XDG_CONFIG_HOME when baked, else ~/.config.
|
|
264
|
+
# @return [String]
|
|
265
|
+
def launch_config_home
|
|
266
|
+
baked = read_launch["env"]
|
|
267
|
+
dir = baked["XDG_CONFIG_HOME"] if baked.is_a?(Hash)
|
|
268
|
+
# Spelled out: Paths.config_home's ~ is this process's HOME, not @env's.
|
|
269
|
+
dir.to_s.empty? ? File.join(@env["HOME"] || Dir.home, ".config") : dir
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
# Whether the helper's chi reads this chi's config dir (home.json,
|
|
273
|
+
# config.yml): false for a run with XDG_CONFIG_HOME elsewhere (a spec,
|
|
274
|
+
# a smoke run), whose home and bundles the helper never sees, though
|
|
275
|
+
# its launch file sits under the real ~/Library.
|
|
276
|
+
def reads_this_config?
|
|
277
|
+
File.expand_path(launch_config_home) == Paths.config_home(env: @env)
|
|
278
|
+
end
|
|
279
|
+
|
|
236
280
|
# The chi version the launch file names, nil without one.
|
|
237
281
|
def launch_version = read_launch["version"]
|
|
238
282
|
|
|
@@ -290,10 +334,7 @@ module Samagotchi
|
|
|
290
334
|
# reads: the launch file's XDG_CONFIG_HOME when baked; disabled hosts
|
|
291
335
|
# are left out. @return [Array<Hash>] name:, hosts:, state:
|
|
292
336
|
def host_keys
|
|
293
|
-
|
|
294
|
-
dir = baked["XDG_CONFIG_HOME"] if baked.is_a?(Hash)
|
|
295
|
-
# Spelled out: Paths.config_home's ~ is this process's HOME, not @env's.
|
|
296
|
-
config_env = { "XDG_CONFIG_HOME" => dir.to_s.empty? ? File.join(@env["HOME"] || Dir.home, ".config") : dir }
|
|
337
|
+
config_env = { "XDG_CONFIG_HOME" => launch_config_home }
|
|
297
338
|
hosts = ConfigFile.hosts_config(env: config_env).values.select(&:api_key_env).group_by(&:api_key_env)
|
|
298
339
|
hosts.map do |name, entries|
|
|
299
340
|
state = if HostKeys.from_keychain(name, env: @env) then :keychain
|
data/lib/samagotchi/engine.rb
CHANGED
|
@@ -3044,6 +3044,15 @@ module Samagotchi
|
|
|
3044
3044
|
return if pending.nil?
|
|
3045
3045
|
|
|
3046
3046
|
outcome, judged = pending.wait(turn.controller)
|
|
3047
|
+
if outcome == :timeout
|
|
3048
|
+
# The session starts on its default without a word otherwise: a
|
|
3049
|
+
# slow System 1 host (a local one) is the usual cause.
|
|
3050
|
+
timeout_ms = SystemOne::Client.configured_timeout_ms
|
|
3051
|
+
Log.warn(:toolkit, "toolkit_suggest_timeout", session_id: turn.session.id, timeout_ms: timeout_ms,
|
|
3052
|
+
reason: "System 1 gave no answer within guardrails.system_one.timeout_ms")
|
|
3053
|
+
@toolkit_binding.fell_back(turn.session, "System 1 took over #{timeout_ms} ms")
|
|
3054
|
+
return
|
|
3055
|
+
end
|
|
3047
3056
|
unless outcome == :answered
|
|
3048
3057
|
Log.info(:toolkit, "toolkit_suggest_#{outcome}", session_id: turn.session.id)
|
|
3049
3058
|
return
|
|
@@ -3070,6 +3079,10 @@ module Samagotchi
|
|
|
3070
3079
|
deferred: ToolkitSuggest.model_reply?(session.messages))
|
|
3071
3080
|
switched ? "suggested" : "chosen"
|
|
3072
3081
|
when "defer" then "defer"
|
|
3082
|
+
when "no_judgment"
|
|
3083
|
+
# System 1 failed (its own warn) or answered nothing usable.
|
|
3084
|
+
@toolkit_binding.fell_back(session, "System 1 gave no answer")
|
|
3085
|
+
"default"
|
|
3073
3086
|
else "default"
|
|
3074
3087
|
end
|
|
3075
3088
|
end
|