samagotchi 0.180.0 → 0.181.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 +46 -1
- data/bin/chi +10 -0
- data/docs/architecture.md +1 -1
- data/docs/bundles.md +7 -2
- data/docs/cli.md +16 -9
- data/docs/configuration.md +24 -4
- data/docs/internals/anthropic.md +4 -3
- data/docs/internals/background-tasks.md +2 -0
- data/docs/internals/block-renderers.md +9 -6
- data/docs/internals/objectives.md +9 -4
- data/docs/internals/web-frontend.md +67 -7
- data/docs/internals/working-set.md +24 -5
- data/docs/memory.md +3 -0
- data/docs/plugins.md +11 -4
- data/docs/sessions.md +1 -1
- data/docs/testing.md +1 -1
- data/lib/samagotchi/bundle_command.rb +4 -1
- data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
- data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/client.rb +8 -1
- data/lib/samagotchi/config.rb +6 -1
- data/lib/samagotchi/core_notice.rb +44 -0
- data/lib/samagotchi/host_address.rb +7 -0
- data/lib/samagotchi/host_config.rb +8 -5
- data/lib/samagotchi/host_registry.rb +26 -8
- data/lib/samagotchi/kernel_loop.rb +3 -2
- data/lib/samagotchi/llm/adapter_common.rb +3 -2
- data/lib/samagotchi/llm/adapters.rb +2 -1
- data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
- data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
- data/lib/samagotchi/llm/chat_loop.rb +6 -5
- data/lib/samagotchi/llm/errors.rb +41 -3
- data/lib/samagotchi/llm/http.rb +85 -22
- data/lib/samagotchi/llm/openai_chat.rb +20 -3
- data/lib/samagotchi/memory_bundle/status.rb +2 -1
- data/lib/samagotchi/objectives.rb +7 -2
- data/lib/samagotchi/owner_lock.rb +2 -0
- data/lib/samagotchi/plugin/api.rb +4 -1
- data/lib/samagotchi/plugin/context.rb +9 -0
- data/lib/samagotchi/plugin/peer.rb +32 -15
- data/lib/samagotchi/plugin/tool_spec.rb +13 -2
- data/lib/samagotchi/row_refs.rb +14 -3
- data/lib/samagotchi/session_chain/delete.rb +6 -6
- data/lib/samagotchi/session_manager/removal.rb +2 -2
- data/lib/samagotchi/tool_ids.rb +19 -0
- data/lib/samagotchi/tool_runner.rb +8 -4
- data/lib/samagotchi/tools/registry.rb +3 -2
- data/lib/samagotchi/tools/task_runtime.rb +34 -0
- data/lib/samagotchi/turn_stages/objectives.rb +10 -5
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/public/app.js +10 -14
- data/lib/samagotchi/web/public/block_host.js +20 -20
- data/lib/samagotchi/web/public/block_renderers.css +5 -5
- data/lib/samagotchi/web/public/context_chips.js +3 -4
- data/lib/samagotchi/web/public/images.js +1 -1
- data/lib/samagotchi/web/public/index.html +24 -5
- data/lib/samagotchi/web/public/objectives_strip.js +16 -6
- data/lib/samagotchi/web/public/pan_zoom.js +121 -0
- data/lib/samagotchi/web/public/peer_chip.js +3 -3
- data/lib/samagotchi/web/public/peer_data.js +27 -15
- data/lib/samagotchi/web/public/picture_viewer.js +304 -0
- data/lib/samagotchi/web/public/popover_modal.js +3 -2
- data/lib/samagotchi/web/public/session_view.js +4 -0
- data/lib/samagotchi/web/public/working_set.js +9 -3
- data/lib/samagotchi/web/public/working_set_view.js +28 -11
- data/lib/samagotchi/web/public/ws_cards.js +36 -10
- data/lib/samagotchi/web/public/ws_markdown.js +129 -0
- data/lib/samagotchi/web/public/ws_order.js +48 -0
- data/lib/samagotchi/web/public/ws_peek.js +22 -5
- data/lib/samagotchi/web/public/ws_preview.css +41 -1
- data/lib/samagotchi/web/public/ws_reader.js +35 -6
- data/lib/samagotchi/web/public/ws_sections.js +24 -15
- metadata +6 -1
data/docs/plugins.md
CHANGED
|
@@ -400,6 +400,10 @@ end
|
|
|
400
400
|
the phone too; a file's "Open in editor" only where the editor opens (this machine).
|
|
401
401
|
- It runs **once per call, on the tool path**, before the call runs: keep it cheap, with no I/O (no
|
|
402
402
|
network, no file reads); build the refs from `args` alone.
|
|
403
|
+
- A lambda that takes two args, `->(args, tool_id) { … }`, gets the run's own id too (chi's tool id, `"t41"`;
|
|
404
|
+
nil when the run has none, a [bundle test](bundle-authoring.md)'s `bundle.tool` for one), and the block reads
|
|
405
|
+
the same id as `ctx.tool_id`: what makes an id for the row that differs between two calls with equal args (the
|
|
406
|
+
peer bundles' send id). A one-arg lambda gets the args alone. Needs chi 0.181.0.
|
|
403
407
|
- If it raises or returns something other than a list, the row gets no refs and the tool still runs; a bad
|
|
404
408
|
ref (an unknown kind, a `javascript:` URL, a file outside the folder) is dropped. Both are logged (tag
|
|
405
409
|
`plugins`, `tool_refs_failed` / `tool_refs_rejected`).
|
|
@@ -891,6 +895,7 @@ full label, `plugin.rb (bundle my-bundle)`.
|
|
|
891
895
|
| `ctx.cost` | the session's spend so far, read now, as a frozen value: `total` (USD, reported + estimated, side requests included; 0.0 before any), `reported` (by providers, `usage.cost`), `estimated` (from `hosts.<name>.models` prices; a generation is one or the other, never both), `side` (recap, `/btw`, `ask_model`: their share of `total`) and `known?` (false while generations or side requests ran but none was reported or priced, so a limit on it can't be enforced; a session with some priced generations reads known, the unpriced ones counting 0). It includes the running turn's finished generations and what earlier workers of the session spent. Use its methods, not its class. Needs chi 0.83.0 |
|
|
892
896
|
| `ctx.usage` | the session's work so far, read now, as a frozen value: `turns` (finished ones and the running one), `tool_calls` and `tool_calls_by_tool` (every call, running ones included; canonical names: an alias counts under its tool, a `call_tool` call under the inner tool), `steps` (the loop rounds that dispatched tools, `/stats`' iterations) and `active_ms` (`active_minutes` too): work time, the generations' time plus the finished tool calls' time, never the waits between them (a question, an approval, the user's answer to `ask_user_question`), with `tool_ms_by_tool` its tool part by tool, so a waiting tool's time (`task_wait`) can be left out. Its counts are the ones `/stats` and `chi sessions stats` show, earlier workers' included. Use its methods, not its class. Needs chi 0.100.0 (guard it with `ctx.respond_to?(:usage)`) |
|
|
893
897
|
| `ctx.turn_author` | who wrote the running turn when it isn't the session's owner: a participant's `"p:<id>"` (`chi share`); nil for the owner's turns and between turns. Every hook event of such a turn carries the same as `author:`. The handler runs with the owner's power whatever the author ([hooks](hooks.md#participants-turns)). Needs chi 0.105.0 (guard it with `ctx.respond_to?(:turn_author)`) |
|
|
898
|
+
| `ctx.tool_id` | inside a tool's block, the run's own id (chi's tool id, `"t41"`), the one a two-arg `refs:` lambda got for its row ([Refs on a tool's row](#refs-on-a-tools-row)); nil anywhere else (a hook, a command, a thread the block started) and for a run with none. Needs chi 0.181.0 (guard it with `ctx.respond_to?(:tool_id)`) |
|
|
894
899
|
| `ctx.settings` | the bundle's settings, frozen: config.yml's `bundles: <bundle>:` with the session's own `--set` values laid over it ([Per-session settings](#per-session-settings)); the config alone until the session is bound (in `register` and `chi.ctx`) |
|
|
895
900
|
| `ctx.data_dir` | `$XDG_STATE_HOME/samagotchi/plugins/<bundle>/`, created on first use: what the bundle keeps across sessions |
|
|
896
901
|
| `ctx.session_dir` | this session's own folder there, created on use, read now; nil with no session yet. `ctx.session_dir(create: false)` is the same path with no folder made, for a read, so a session that saved nothing leaves none (a `File.read` of what isn't there raises `Errno::ENOENT`); needs chi newer than 0.143.0. chi removes it when the session is deleted, discarded or pruned, so don't build the path yourself. A `sessions/<id>.json` an older version of your bundle kept moves in as `state.json` (chi still removes one left there). Needs chi newer than 0.142.0 |
|
|
@@ -1456,10 +1461,12 @@ that calls it, or for a real external bundle that does. No method on the chance
|
|
|
1456
1461
|
`check_hint!`, `paired_lines`, `transport_line`, `peer_dir` and
|
|
1457
1462
|
`setup_paragraph` (optionally `skill_substitutions`), and sets `NAME`,
|
|
1458
1463
|
`APP`, `COMMAND`, `USAGE`, `OUTBOX` and `SCRIPTS_DIRS`. These constants are
|
|
1459
|
-
read as `self.class::X`. The base names each send: `Peer.send_id(kind, title, text)` (`s-` and 6 hex
|
|
1460
|
-
of SHA-256 over the args as given
|
|
1461
|
-
|
|
1462
|
-
|
|
1464
|
+
read as `self.class::X`. The base names each send: `Peer.send_id(kind, title, text, salt)` (`s-` and 6 hex
|
|
1465
|
+
of SHA-256 over the args as given and the send's salt: the tool run's `ctx.tool_id`, a random one for a
|
|
1466
|
+
`/<peer>` command's, so each send has its own id; a nil salt gives an older chi's id, over the args alone) is the
|
|
1467
|
+
message's second line (`ref: <id>`), the tool row's `peer` ref (display only, no actions; computed from the args
|
|
1468
|
+
and the run's id before the call runs, a two-arg `refs:`, so a send that then fails has it too) and the last
|
|
1469
|
+
send's `id`; the peer's answer echoes it as `re` ([context.md](context.md#the-command-contract)).
|
|
1463
1470
|
Successful sends and transport failures are recorded in the session's peer exchange log; answer pushes add
|
|
1464
1471
|
summaries, not answer texts. The log does not enter the model's context.
|
|
1465
1472
|
See the [claude-peer](bundles.md#the-claude-peer-bundle) and
|
data/docs/sessions.md
CHANGED
|
@@ -110,7 +110,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
|
|
|
110
110
|
- `Session.list` / `SessionManager.list_sessions` / `GET /api/sessions?sort=&order=&limit=&offset=` default to `updated_at desc` (newest activity first). Also supports `created_at`, `asc`. `X-Total-Count` header when paginated.
|
|
111
111
|
- Web UI (`chi web`): the page's scope is in its URL. Started in a project (a git repository or a `chi project init` folder), `chi web` opens `/?dir=<that folder>`: that project's sessions, and new sessions start in that folder; the header chip says `<project> · all`, and `all` opens the same place as `?scope=all` (every session; a new session there starts in chi web's start folder, shown on the start page, and cards name their folder; `← <project>` goes back to the project view it came from, or to the start folder's project). A bare `/` (the LAN link, the Home Screen app) is the start folder's project too: the folder chi web runs in, or `web.start_dir` / `chi web --start-dir DIR`; outside a project (no repository or marked folder) it shows every session. A pushed notification opens its session in that session's own project (`/?dir=<its project>#/s/<id>`; `?scope=all` outside a project). One server serves every project: a second `chi web` (from another repo) finds it through `GET /api/info` and prints (with `--open`, opens) its page for its own folder instead of starting another. The 3 latest sessions sit above the chat, and the grip on the chat's top edge — the same thin handle as the composer's, its twin — puts them away and brings them back: a drag up (or a click, or Enter/Space on it) hides them, a drag down (or a click) shows them again, and the choice is remembered. A hidden strip leaves its status in the top bar (`N sessions · ● 1 live · ● 1 waiting`, from the cards), and a click on that pill opens All sessions, without showing the strip first; there the pill shows whatever the strip's state, pressed, and a click on it goes back to the chat (as Esc does). In a window under 900 px wide, where the strip scrolls sideways, the grip stays under it, outside the scroller; a window under 700 px tall hides the strip by itself, so a question or approval card in the stage keeps room, and the grip shows it until the window is tall again. A parent and its delegates are one card there: its `▸ 2 delegates · 1 live · 1 waiting` chip (the waiting part in the attention colour, the card's border too; just `▸ 2 delegates` while the rows are open: they carry the marks then) opens their rows in a popover under it (a row per delegate at any depth, indented; a click opens that one, Esc or a click outside closes it, and the strip's order holds while it is open). A fork is a card of its own, and so is a delegate whose parent isn't listed (archived, another project), with its `↳ <parent>` chip; the pill counts cards, and every live or waiting session. "All sessions" (or `/`) opens every session at `#/sessions`; its header is the top bar's right end: a search over preview, id and status, the count, an `archived` toggle and Select (on a phone a row of its own under the bar). Esc or the pressed pill returns; where the sessions are stored is a faint line under the list. A card is its title on one line (an untitled session reads `Untitled` over its first message), a line under it (its recap, else its first message) and its meta row, with one mark per state and no status dot: a waiting card has its warn outline and its `question` (or `approval`…) chip, an errored one an `error` badge, a session a worker runs the `live` badge (not on a waiting card: waiting means a worker), and idle, completed and stopped ones are unmarked; a family's and a chain's rows the same. There a parent's card holds its delegates the same way, the chip opening their rows inside the card (each with an archive button on hover), open by itself while one of them waits on you; the count says `14 · 7 delegates` (`3 / 14` while a search narrows it), a search that matches a delegate shows its parent's card with the list open and the matching rows marked, and select mode picks cards (archiving a parent takes its delegates). The open session is in the URL (`#/s/<id>`), so a reload or a copied link opens it again; the chi logo top left goes back to the empty start for a new session. The message box grows with its text; drag its top edge to keep it taller (double-click resets). A file in a tool row (a read, edit or write's title) and its diff lines are refs: hover one and click to open the current file in your editor at that line, on this machine only (`web.editor`; the browser's "always allow" for the page's port and VS Code's "allow opening local files" are asked once; see [Opening files from chi web](configuration.md#opening-files-from-chi-web)). So are an edit or write approval card's paths (at the first line the dry run changes) and its diff lines, before you approve, and the numbered lines of a read's output: `lines 40–60` under it opens the text as read, numbered, when the output is the file as-is (not the head/tail preview of a big file, an error or an image; no numbers after a cut). A `path:line` (or `path:line-line`) in an answer or a step's text is one too once the turn has ended, and after a reload, when it names a file a row or card on the page touched: the path under the session's folder, else the one touched file it ends with (a bare `app.js:12` when only one touched file is named so; two such files make it none); a path without a line counts only when it is a touched file exactly. Code blocks, links, bare URLs and inline code with more than the ref in it are left alone, and a file the session didn't touch is never linked; a link whose text is such a ref alone (github-pr's link to the PR diff) becomes a ref too, and its plain click still goes to the PR. A plugin's refs on an answer (an `after_turn` hook's, see [Refs on the answer](hooks.md#refs-on-the-answer-display-only)) are paired with its links and text whatever the rows touched: they can link a file the session didn't touch, or an issue or a commit, and add their own actions to the ref's menu. A plugin tool's row carries the refs its `refs:` gives (see [Refs on a tool's row](plugins.md#refs-on-a-tools-row)): its title opens the first, and its `▾` menu adds the others as `<ref> · <action>` (the URL on hover); their URL actions work on a phone too. A ref with more than one target shows a small `▾` on hover: it opens a menu of them, in order **PR diff** (a link's), **Open in editor**, **Show in turn** and **Copy path**, and a plain click runs the first (a link's own, else the editor, else show in turn). **Show in turn** scrolls to the tool row that touched the file (looked for in the ref's own step, then its own turn, then the rows before it, then the nearest after it; there, the last one showing the ref's line, else the last one), opens the steps, the stage's steps and the row's diff (or the read showing the line) and flashes the row and the line; an answer's or a step's ref and an approval card's path have it, not a row's own title or lines. It needs no editor, so a viewer without one (a phone on the LAN) gets an answer's refs with **Show in turn** as their click; a row's title and diff lines stay plain text there. On a touch screen a tap opens the menu. A ref with a target is a tab stop: Enter runs its first target, ↓ opens the menu (↑/↓ move, Enter picks, Esc closes back to the ref). Diff and read lines have their click only. The info bar's id copies the full session id on click ("Session id copied"), the id every CLI command takes (`chi --attach ID`, `chi send ID`). A session whose prompt carried model notes has a `notes: deepseek` chip there (the names without `model_notes_`; the tooltip lists each with its scope and size; `session.prompt_notes` in `GET /api/sessions/:id`, the live worker's, else the session file's; see [Memory](memory.md#model-notes)). Its ⚙ chip, after the model, holds the session's thinking level, reasoning history and LLM context: `⚙` alone while the session follows the model for all three, else `⚙` and what the session set, in the accent colour (`⚙ think low · ctx stale,forget`; a phone shows ⚙ with a dot; the tooltip gives each value and its source). Its panel is the start page's ⚙ panel for this session: a Thinking row (`/thinking`), on a chat host a Reasoning row (the reasoning history, `/reasoning-history`), and a Context row with its Apply and budget fields (`/llm-context`); a tap runs that row's command at once in the worker (one reply in the conversation, as a typed one) and changes that field alone, the Context row's `default` resets the strategy, apply rule and budget (`/llm-context reset`), and a tap while a turn runs is queued for after it (the panel's note says so). `GET /api/sessions/:id`'s `session.thinking`, `session.reasoning_history` (null on a native host) and `session.llm_context` carry the values (the live worker's, else resolved from the session file), and a `command_ran` that changed them carries the new ones. After ⚙, the 🧰 chip names the session's toolkit: `🧰` alone on the configured default (`toolkit.default`, `session.toolkit_default`), `🧰 lean` on another (see [Toolkits](configuration.md#toolkits); `/toolkit` changes it). A `/thinking` or `/reasoning-history` change typed in the composer that restarts the prompt cache asks first: the reply bubble has an **Apply (restarts the cache)** button that sends its `--yes` line (the ⚙ panel sends that line itself; see [Changes that restart the prompt cache](configuration.md#changes-that-restart-the-prompt-cache)). It shows the context used (`ctx 42%`) and the last generation's decode speed (`87 tok/s`, `~64 tok/s` when estimated; see `/stats` in [cli.md](cli.md#session-commands)); hovering `ctx` there or on a session card lists the session's tokens in (summed over every request, with the cached share), out (with reasoning) and the cost when the provider reports one, for this session only (one estimated from a `hosts.<name>.models` price shows with `~`: `cost: ~$0.54 ($0.42 reported, ~$0.12 estimated)`); after a `/model` switch the info bar's tooltip adds a `per model:` row per run of turns on one model above those totals (`splash:qwen3-35b · 6 turns · 96.0k in / 9.0k out · ~$0.02`, a switch's prefill under its row: `└ switch prefill 58.0k uncached prompt ≈$0.01`; the timing's `model_segments`, replaced by each `generation_completed`'s; the session cards stay as they were), and right after the switch its ctx % is the new model's window's; and the memory indexes its prompt holds (`memory index: ~3.4k tokens in this session's prompt (system 2.0k, project 1.4k)`; see [Memory](memory.md#the-indexs-size)). The start page's model picker (bottom left of the composer, the chosen name `▾`) chooses the model a new session starts on, and a fresh chain link's (see [Session chains](#session-chains); there a pick shows as a `/model` command bubble in the link); it opens a search list over the conversation (↓ or a click; downward when the start page leaves no room above): an empty search shows the last 5 picks (Recent) and then each host's model ids A–Z under the host, the default host first (an id the host declares under `hosts.<name>.models` first, noted `config`, its tooltip `served by config (hosts.<name>.models)`; a host that failed to list its models keeps those ids, greyed and noted `host down`, still pickable; a remembered or default model stays chosen even then, greyed on the button); typed words must each match the host or the id (a substring, else for 3+ characters the letters in order, so `deepseek4.1 fla` finds `openrouter · deepseek/deepseek-v4.1-flash`), ⏎ picks, Esc/Tab close, a pick puts the focus in the message box: `GET /api/models` lists the hosts' models as chi spells them (`{default, models: [{name, host, id, configured?, unavailable?, sampling?, llm_context?}], warning?}`; `configured: true` marks an id declared under `hosts.<name>.models`, listed first under its host, `unavailable: true` one whose host failed to list its models; `sampling` is the model's configured request parameters as `/model` words them, the row's tooltip in the list; bare for the default host, `host:model` for the others, from the same cached lists as `/models`, a bounded wait, a host that is down noted in `warning`; `toolkits`: `{default, suggest, kits: [{name, description?}]}`, the start page's 🧰 list: the configured `toolkit.default`, `suggest` `on` only when a new session's first message may get a suggested kit (`toolkit.suggest.mode: on`, a System 1 host, two described kits; else `audit` or `off`), and the built-in and config kits a new session can start on, without `child` or `undecided`, a kit `groups:` refuses or one that doesn't resolve (a base that is a bundle kit), the default always listed; left out when it can't be read), and `POST /api/sessions` takes `model` (blank means the default). Beside it, ⚙ opens the new session's rarely used settings (thinking and LLM context, following each `GET /api/models` row's `thinking` and `llm_context`, ; see [configuration.md](configuration.md#llm-context-a-sessions-own-strategy)), and 🧰 its toolkit: **Auto** (with `toolkit.suggest.mode: on`: the first message may get a suggested kit, else the default) or a kit from the payload's `toolkits`, sent as `POST /api/sessions`'s `toolkit` (see [configuration.md](configuration.md#toolkits)); a refused kit (`400 toolkit_refused`) is said in the list, opened again. What is set shows on the row as an accent chip (`think high`, `tools: lean`; a dot on ⚙ or 🧰 on a phone); each is for the next new session only, never remembered. The start page's first message goes as later ones do: `POST /api/sessions` with `idle: true` and `preview` (the message, which names the session until its turn is saved), then `POST /api/sessions/:id/turn`, so a failed first turn puts its prompt back in the composer too; a first line that is one of the new session's commands (`/model …`) goes to `POST /api/sessions/:id/command` instead, as later ones do. The browser remembers the last model picked; a running session's model is in the info bar and changes only with `/model`. In the composer a line is a command when it is `!…` or starts with one of the session's command names (its `commands` list; `/stats`, `/exit` and the other terminal words get the page's own reply); an unknown `/word` (`/usr/bin/env is missing`) goes to the model as a prompt, as in a terminal; a one-word `/word` no command answers (`/modle`) is not sent: the page shows `Unknown command /modle. Did you mean /model? /help lists the commands.` (the "Did you mean" part only when a name is close). A `POST /turn` (or a session's first `prompt`) that is one of the worker's commands runs as that command too (`202 {status, command_id, session_id}`), so `chi send`, `chi -p` and a page whose command list lags all get the command. ↑/↓ in the composer walk the prompt history the TUI's ↑ walks ([Persistent Prompt History](cli.md#persistent-prompt-history)): ↑ with the caret on the first line, ↓ from the last line while browsing, ↓ past the newest brings the draft back; `GET /api/history` returns `{entries: [...]}`, oldest first (the page fetches it on focus and after each send). The server records a sent line in the routes once the worker took it (`POST /turn` accepted, a `!command` through `POST /command` or as a session's first line); `"history": false` in the body keeps it out (an image-only send).
|
|
112
112
|
- Web notifications: when a session needs you while the tab is hidden or behind another window (a question or a guardrail approval, a plugin card with buttons during a turn such as check-in's, a failed turn, a turn done after 10 s or more; a delegated session only for its questions, a canceled turn never), the page title counts it, `(N) Chi`, until you come back to the tab. The bell at the right of the top bar also turns on OS notifications ("needs an answer", "needs approval", "needs you", "turn failed", "done in 42 s", under the session's first message; a click opens the session): its first click asks the browser for the permission, and the choice is kept per browser. Any session of the page's scope counts, not only the open one. What was already so when the page loaded never counts, and several chi tabs show one notification per event. A chi tab in front tells the others (a `BroadcastChannel`), so while you look at one, the ones behind neither notify nor count what it shows; coming back to a tab clears those events in the other tabs' titles too. The hub's `session` frames carry what this needs: `pending_question` (`{id, kind}`, kind `question` or `approval`), `pending_card` (`{id, bundle}`: the running turn's card with actions, from `pending_card.json` that the worker keeps in the session's folder while one is open; a card without actions, such as loop-guard's, never counts) and `last_turn` (`{outcome, ended_at, seconds, origin}`, saved in the session's JSON as the engine ends each turn).
|
|
113
|
-
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height (on a phone no row: the line lies over the session bar's left while a turn runs and you type or have a choice armed): the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `stage_view.js` (the stage view: the running turn pinned above the composer, with Stop turn in its status row while it runs, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model, three groups with hairlines between them, on one line above a phone's width (the folder gives way first): the setup (id, status, model, the ⚙ and 🧰 chips, notes, the memory or working-set chip), the relations (chain links, the parent as `↑ <id>`, delegates, participants; only when there is one) and the telemetry (folder, ctx, speed, the session's time, worker badge)), `settings_chip.js` (the session bar's ⚙ chip and its panel over `settings_panel.js`: a tap runs that row's command, one field), `toolkit_chip.js` (the session bar's 🧰 chip: the kit against `toolkit.default`), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts (the restarting set is `version_notices.js`'s) as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails
|
|
113
|
+
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height (on a phone no row: the line lies over the session bar's left while a turn runs and you type or have a choice armed): the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `stage_view.js` (the stage view: the running turn pinned above the composer, with Stop turn in its status row while it runs, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model, three groups with hairlines between them, on one line above a phone's width (the folder gives way first): the setup (id, status, model, the ⚙ and 🧰 chips, notes, the memory or working-set chip), the relations (chain links, the parent as `↑ <id>`, delegates, participants; only when there is one) and the telemetry (folder, ctx, speed, the session's time, worker badge)), `settings_chip.js` (the session bar's ⚙ chip and its panel over `settings_panel.js`: a tap runs that row's command, one field), `toolkit_chip.js` (the session bar's 🧰 chip: the kit against `toolkit.default`), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts (the restarting set is `version_notices.js`'s) as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails; a click on one opens it in `picture_viewer.js`), `composer_grip.js` (the composer's grip and fold: the drag, tap and keys, the fold per visit), `composer_mount.js` (the composer mounted on a page's markup: the message box and its height, the image chips from a paste, a drop or the image button, the grip and fold, ↑/↓ over the prompt history and the keys; the page's own parts come in as hooks: what Enter and Send do, keys taken first, Esc, where the history comes from, the info bar's drop while folded, typing anywhere to open it; its styles, the card it sits in (`.composer-card`, its footer and its line above the text field) included, are the shared `composer.css`, linked after `tokens.css` by `index.html`), `strip_grip.js` (the latest-sessions strip's grip, the composer grip's twin: hides and shows the strip), `strip_hidden.js` (the strip hidden or shown: the saved choice, the short window's own hide, the grip and the body's class), `storage.js` (the page's per-browser choices in localStorage, guarded: a choice that can't be read or written is not remembered), `unqueue.js` (the × on a message queued for after the turn: takes it back, its text into an empty composer or a toast), `toasts.js` (the page's toast stack: a timer each, sticky ones until acted on, the same text reusing its item), `toast_place.js` (where the toast sits: above the composer card, the stage and an open model panel), `dock_reserve.js` (what floats over the history: the history's bottom reserve (`--dock-h`) at the composer card's and the showing stage's height, a reader at the end kept there, and the toast's place measured for `toast_place.js`), `notice_links.js` (a hook notice line's http(s) URLs as links), `start_page.js` (the start page's model picker, its ⚙ panel's and 🧰 list's choices for the next new session only and their override chips; a fresh chain link's picker and its `/model`), `start_settings.js` (the start page's ⚙ panel: thinking and LLM context as rows of segments, applied at once, the Apply and budget disclosure; the override chips' words and ⚙'s dot), `settings_panel.js` (the panel's rows as lit-html templates, shared: the segments, the disclosure, a hidden row's sent-anyway line; the caller passes its rows and applies the picks), `start_toolkit.js` (the start page's 🧰 list: Auto with suggest on, the kits, the default marked; a pick closes it; its override chip and dot), `session_actions.js` (Continue, Archive and its Undo, Delete and Stop, and the start page when the open session is gone), `send_turn.js` (the composer's send: a new session first on the start page, the route, the echo, the image upload, the `/turn` ack, a fast failure's restore and each error's place). Unit-tested via `npm test` (`spec/web/public/*.test.js`).
|
|
114
114
|
- Selecting a session in the web UI is read-only: `GET /api/sessions/:id` never spawns a worker (it reads a live worker's snapshot when one runs, else the session file). A prompt (`POST /turn`) or a command (`POST /command`) wakes the worker, and `/stream` briefly waits for a freshly-spawned bridge before answering. A caught-up SSE reconnect holds the stream open; `reset` markers are only sent for reconnects behind the ring window, or with a cursor from another worker (event ids are `<event_seq>-<epoch>`, one epoch per worker).
|
|
115
115
|
- The web session page's message box folds away for room to read. Drag the grip on its top edge (the pill that shows on hover; always on a phone) down, past the box by 32 px: the pill turns accent while releasing would hide it, and on release the box folds and the info bar stays as the page's bottom edge. The grip stays as a handle on the info bar's top edge, drawn always: pull it up (8 px opens it, and the box follows the pointer in the same gesture), click or tap it (opens it and focuses the box), or just type on the page (the key lands in the box) to bring it back; Enter or Space on the focused grip folds or opens too. A draft (text or images, which folding never clears) colours the handle with the accent, a session waiting on you with the attention colour; its tooltip says so. Stop turn isn't the message box's: it sits in the running turn's stage, at the right edge of its status row beside the fold caret (collapsed stage or not), while the turn runs, and goes when the turn ends A turn the page knows runs but has nothing of to draw (a reload whose session payload carries no current turn) shows that status row alone, `running` and Stop turn. The fold is each session's own, remembered per browser (`chi_composer_collapsed:<session>`: folding one session's box leaves the others' as they were), an archived session opens folded for the visit, and opening it there, like the page opening it itself (a restored line, a quote, continue →'s opener), is for that visit only. The fold keeps the height the grip set, also the session's own (`chi_composer_floor:<session>`; the start page's lasts until a reload): the box opens again at the height it had, and only a double-click on the grip forgets it. That height never takes more than half of the window the box is drawn in: a floor saved in a bigger window is held to that half in a smaller one (a rotated phone, a resized window, another device on the same origin), and the saved floor itself stays, so the height comes back when the room does. A click on the expanded grip hides the box as well: it folds 250 ms after the press, so a second click inside that window is read as a double-click and resets the height instead (a drag, Enter or Space act at once, and a drag after a click takes the wait back). The start page's grip only resizes.
|
|
116
116
|
|
data/docs/testing.md
CHANGED
|
@@ -124,7 +124,7 @@ its case.
|
|
|
124
124
|
The web specs run in plain node. One that loads lit-html, itself or through a module it imports (`turn_block.js`,
|
|
125
125
|
`turn_html.js`, `card.js`, `copy.js`, `images.js`, `scope.js`, `command_view.js`, `diff_view.js`, `read_view.js`,
|
|
126
126
|
`question_cards.js`, `stream_handlers.js`, `stage_view.js`, `bubbles.js`, `cards_place.js`, the chips, `info_bar.js`, `info_bar_model.js`, `lists_view.js`, `context_chips.js`, `families_view.js`,
|
|
127
|
-
`chains.js`, `working_set_view.js`, `working_set_rail.js`, `unqueue.js`, `toasts.js`, `notice_links.js`, `start_page.js`, `start_settings.js`, `settings_panel.js`, `start_toolkit.js`, `session_actions.js`, `send_turn.js`, `composer_mount.js`, `dock_reserve.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`,
|
|
127
|
+
`chains.js`, `working_set_view.js`, `working_set_rail.js`, `ws_markdown.js`, `unqueue.js`, `toasts.js`, `notice_links.js`, `start_page.js`, `start_settings.js`, `settings_panel.js`, `start_toolkit.js`, `session_actions.js`, `send_turn.js`, `composer_mount.js`, `dock_reserve.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`,
|
|
128
128
|
`vendor/lit-html.js`) needs a DOM: `import "./dom_shim.js";` as its first import (happy-dom, a devDependency only,
|
|
129
129
|
never shipped; lit reads `document` as it loads). The shim's `markupOf(template)`,
|
|
130
130
|
`htmlOf(nodes)` and `canon(html)` compare markup without lit's marker comments; the DOM writes text with only `&`, `<`, `>`
|
|
@@ -626,7 +626,10 @@ module Samagotchi
|
|
|
626
626
|
return if states.empty?
|
|
627
627
|
|
|
628
628
|
@stdout.puts " #{heading} (#{states.size}):"
|
|
629
|
-
states.each
|
|
629
|
+
states.each do |file, state|
|
|
630
|
+
note = state == "unrecorded" ? PLUGIN_NOTES.fetch(state) : (modified if state == "modified")
|
|
631
|
+
@stdout.puts " #{file} [#{state}]#{note}"
|
|
632
|
+
end
|
|
630
633
|
end
|
|
631
634
|
|
|
632
635
|
# "Manifest: [kept]", or "[from the install record]", and what its case
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: known-names
|
|
3
|
-
version: 0.2.
|
|
3
|
+
version: 0.2.1
|
|
4
4
|
requires_chi: ">= 0.150.0"
|
|
5
5
|
scope: system
|
|
6
6
|
description: Catches a near-miss of a protected name (home folder, login, git name, repo name, names from config) in a tool call and rejects it with the right spelling; mode ask / correct optional
|
|
@@ -9,6 +9,6 @@ files:
|
|
|
9
9
|
known_names.md: sha256:d5348b95b6c655017b541910b36e384220da280818160201f6ec9a50e1e4287c
|
|
10
10
|
plugin:
|
|
11
11
|
file: plugin.rb
|
|
12
|
-
sha256: sha256:
|
|
12
|
+
sha256: sha256:f519ec42023a6857f87fba9ff8a8db5d261dccfd88e3a9b58310ae3293b3cbdc
|
|
13
13
|
# config.yml bundles: known-names: (another key warns; an older chi ignores this)
|
|
14
14
|
settings: [names, ignore, mode, derive, min_length, max_distance]
|
|
@@ -24,9 +24,10 @@ class KnownNames
|
|
|
24
24
|
DERIVATIONS = %w[home user git repo].freeze
|
|
25
25
|
DEFAULT_MIN_LENGTH = 6
|
|
26
26
|
# Splits a command or path into tokens; each token's [-_.] parts are
|
|
27
|
-
# candidates too. "
|
|
28
|
-
# name
|
|
29
|
-
|
|
27
|
+
# candidates too. Backticks, "$" and "!" split: shell/markdown wrappers
|
|
28
|
+
# and prefixes, not part of a name. "#" and "~" split: in "~name" (that
|
|
29
|
+
# user's home) the name after it is what is checked.
|
|
30
|
+
TOKEN_SPLIT = %r{[/\s"'=:,;|&()<>@~#!$`]+}
|
|
30
31
|
PART_SPLIT = /[-_.]+/
|
|
31
32
|
# Separators at a token's start or end, dropped before it is compared.
|
|
32
33
|
EDGE_SEPARATORS = /\A[-_.]+|[-_.]+\z/
|
|
@@ -18,7 +18,7 @@ Single registry `Samagotchi::Config` (`Config::ENTRIES` in `lib/samagotchi/confi
|
|
|
18
18
|
|
|
19
19
|
Sections forbid `_`/`-` (`SECTION_RE` `/\A[a-z0-9]+\z/`), since an env or CLI name is derived from them; a config-only section (`system_one`: `expose: [:config]`, no derived name) may carry `_`. Leaves keep `snake_case` in YAML (`base_url`) and become kebab in CLI (`base-url`) via registry derivation — no generic string split, registry lookup avoids flat vs nested collision.
|
|
20
20
|
|
|
21
|
-
**Universal entries** (`expose: [:env,:config,:cli]`): `default.model`, `server.host/port/open_timeout/read_timeout`, `server.first_token_timeout` (env and config only), `recap.model/base_url/host_ref/inactivity/timeout/min_user_turns/sentences`, `session.retention_days/max_count/keep_status/sweep_interval_hours/idle_exit_minutes`, `session.keep_empty/max_children` (env and config only), `log.file/disable`, `status.line`, `context.status/window_tokens/chars_per_token/status_thresholds`, `memory.index_warn_tokens/entry_warn_tokens/read_max_chars`, `default.max_tokens`, `max_tool_output_chars`, `retry.max/base_delay/max_delay`, `read.*`, `execute.*`, `web.port/host`, `no_interrupt`, `no_default_input` etc. (`Config::ENTRIES`; `expose` says which of env/config/cli each takes). Precedence is `CLI > ENV > file > default`.
|
|
21
|
+
**Universal entries** (`expose: [:env,:config,:cli]`): `default.model`, `server.host/port/open_timeout/read_timeout`, `server.first_token_timeout`, `server.stream_idle_timeout` (env and config only), `recap.model/base_url/host_ref/inactivity/timeout/min_user_turns/sentences`, `session.retention_days/max_count/keep_status/sweep_interval_hours/idle_exit_minutes`, `session.keep_empty/max_children` (env and config only), `log.file/disable`, `status.line`, `context.status/window_tokens/chars_per_token/status_thresholds`, `memory.index_warn_tokens/entry_warn_tokens/read_max_chars`, `default.max_tokens`, `max_tool_output_chars`, `retry.max/base_delay/max_delay`, `read.*`, `execute.*`, `web.port/host`, `no_interrupt`, `no_default_input` etc. (`Config::ENTRIES`; `expose` says which of env/config/cli each takes). Precedence is `CLI > ENV > file > default`.
|
|
22
22
|
|
|
23
23
|
Example `config.yml` (new nested form, preferred):
|
|
24
24
|
|
|
@@ -30,6 +30,7 @@ server:
|
|
|
30
30
|
host: localhost
|
|
31
31
|
port: 8080
|
|
32
32
|
first_token_timeout: 120 # seconds a request may wait for its first token; 0 = off; unset: 120 for remote hosts, none for local
|
|
33
|
+
stream_idle_timeout: 120 # seconds a stream that showed something may go without more; 0 = off; unset: 120 for remote hosts, none for local
|
|
33
34
|
recap:
|
|
34
35
|
host_ref: small-box # a name under hosts:, or base_url: http://...
|
|
35
36
|
model: your-small-model-id
|
|
@@ -55,7 +56,7 @@ Only the nested form is read. An env name used as a top-level key (`SAMAGOTCHI_D
|
|
|
55
56
|
**Excluded maps** (YAML-only, not part of the flat registry; skipped by scalar loader):
|
|
56
57
|
|
|
57
58
|
- `model_aliases:` map of alias → model id (`ModelRef.parse`, through `HostRegistry#resolve`). Keys lowercased on write (`ConfigFile.write_model_alias!`). Values may be bare `model` or qualified `host:model` (hybrid; only `:` names a host, `org/model` is an id). Aliases apply once: never point an alias at another alias.
|
|
58
|
-
- `hosts:` map of `name → {host, port | url, api, api_key_env, auth, dialect, profile, first_token_timeout, vision, sampling, thinking, enabled, models}` (`HostConfig.all`, `host_registry.rb` `HostEntry`). Names lowercased; `url:` (http/https, optional path) replaces host/port, never both; `api_key_env:` names the env var holding the API key (never write a key into config.yml); `auth:` (`bearer|x-api-key`) is the header the key goes in (default `x-api-key` on `api: anthropic`, Bearer elsewhere); `dialect:` (`fireworks`, or `standard` for the default; `api: anthropic` only) adjusts the Messages wire for that provider (Bearer by default, no thinking `display`, no `cache_control`, `x-session-affinity`; `LLM::Dialect`, docs/configuration.md "Anthropic Messages hosts"); `first_token_timeout` (seconds, `0` = off; a negative or non-number warns and is ignored) overrides `server.first_token_timeout` for that host
|
|
59
|
+
- `hosts:` map of `name → {host, port | url, api, api_key_env, auth, dialect, profile, first_token_timeout, stream_idle_timeout, vision, sampling, thinking, enabled, models}` (`HostConfig.all`, `host_registry.rb` `HostEntry`). Names lowercased; `url:` (http/https, optional path) replaces host/port, never both; `api_key_env:` names the env var holding the API key (never write a key into config.yml); `auth:` (`bearer|x-api-key`) is the header the key goes in (default `x-api-key` on `api: anthropic`, Bearer elsewhere); `dialect:` (`fireworks`, or `standard` for the default; `api: anthropic` only) adjusts the Messages wire for that provider (Bearer by default, no thinking `display`, no `cache_control`, `x-session-affinity`; `LLM::Dialect`, docs/configuration.md "Anthropic Messages hosts"); `first_token_timeout` (seconds, `0` = off; a negative or non-number warns and is ignored) overrides `server.first_token_timeout` for that host, as `stream_idle_timeout` does `server.stream_idle_timeout`; `models:` (a map of model ids, or a plain list) declares ids the host serves whatever its `/v1/models` lists: no "doesn't list" warning, and a bare id routes there as if listed (`HostModel`); an entry may hold `price: {input, output, cache_read?, cache_write?}` in USD per 1M tokens (`ModelPrice`; an unset cache rate is the input rate), which estimates a cost the provider doesn't report or reports as 0 (`cost_estimate`, shown as `~$`), and `served: [ids] | any`, the models a gateway may answer that id with (no served-model warning for them); model settings stay in the root `models:`; a worker reads `hosts:` from the file as it starts (no environment variable sets hosts).
|
|
59
60
|
- `models:` map of model id or alias → `{profile, vision, sampling, thinking, reasoning_history}` (`ModelSettings.all`). `thinking:` (here, on a host, or `thinking.level` for every model) is `off|low|medium|high|default` (`Thinking`; unquoted `off` works, `on` is not a level; `default` = send nothing). Precedence: the session's own level (`/thinking LEVEL`, saved in the session; `chi --thinking` on a session run, `chi send --new --thinking`) > `chi web --thinking`/`SAMAGOTCHI_THINKING_LEVEL` > `models:` > `hosts.<name>.thinking` > `thinking.level` in config.yml > `default`. A `sampling:` key wins over the fields a level sends (`null` drops one); `docs/configuration.md` "Thinking". `reasoning_history:` (here or on a host) is `drop|turn|all`, which of its reasoning a chat host's model gets back. Precedence: the session's own level (`/reasoning-history LEVEL`, saved in the session) > `SAMAGOTCHI_REASONING_HISTORY` > `models:` > `hosts.<name>.reasoning_history` > `turn`; `docs/configuration.md` "Reasoning history". `/thinking` and `/reasoning-history` ask before a change that restarts the prompt cache; `--yes` applies it (`chi send` commands apply directly). `sampling:` (here or on a host) is a map of request fields passed to the provider as written (`temperature`, `top_p`, `presence_penalty`, `repeat_penalty`, …; a model's fields win over its host's per field; `null` = don't send; chi's own fields like `max_tokens`/`stream` are refused with a warning; `docs/configuration.md` "Sampling"). Keys match case-insensitively. `profile` (here or on a host) is `qwen36|gemma4`: the raw prompt format for native hosts. Precedence: `--profile`/`SAMAGOTCHI_MODEL_PROFILE` > `models:` > `hosts.<name>.profile` > the llama.cpp server's chat template > the name (`qwen`/`gemma`) > `qwen36` (`ModelProfile.resolve`). Set one when a model's name hides its family (e.g. a Qwen fine-tune under another name whose server publishes no template).
|
|
60
61
|
- `hooks:` map of `hooks_dir` + per-event lists `{path, on_error}` (`Hooks::Loader.load`). `hooks_dir` may start with `~`.
|
|
61
62
|
- `guardrails:` tool-call rules (`docs/guardrails.md`; read in `Engine#guardrail_rules`, parsed by `Guardrails::Rules.parse`): `enabled` (bool, default true; `false` drops rules and hooks' asks, a deny still applies; config.yml only, like every `guardrails` setting: no env variable), `parent_answers` (`soft`, the default: a parent agent's `chi answer` may deny, answer, Continue and give "Allow once"; `standard`: no allow; `hard`: deny, Stop and plain answers only; never a wider scope; replaces `parent_approvals` and `turn.parent_continue`; a convention for an honest parent, not a security boundary, and the user's choice: set it only when the user asks), `rules:` (list), `disable:` (a rule id or a list of them, `id` or `bundle:id`, switching off a bundle's or config rule without editing it), `small_models` (`auto`, the default: small = 32B or less read from the name; a glob or list of globs; `[]` for none). A rule takes only `id`, `tool`, `command`, `path`, `git`, `models`, `verdict`, `reason`, `scopes`: `id` required; at least one of `tool` (a name, `shell` = execute + task_create, a `File.fnmatch` glob like `"mcp_*"`, or a list), `command` (a Ruby regex on the shell command), `path` (a glob, or `outside_repo`: outside the session's repo, tmp folders and memory files excepted), `git` (only `outside_repo`: a shell call runs commit/add/reset/… in another checkout); `models` (optional: `small`, a model-name glob, or a list; without it the rule is for every model); `verdict` `ask|deny`; `scopes` (for `ask`) a subset of `once, session, repo, rule`. **Any parse error (an unknown key, a bad regex, no verdict) makes chi deny every tool call** until fixed, so validate with `YAML.safe_load` and keep the list shape. Rules are read again on the next tool call after config.yml or a bundle's rules change: no restart needed. Installed bundles' rule files (`chi bundle install guardrails`) add to them; `/guardrails` lists what loaded.
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: samagotchi-system
|
|
3
|
-
version: 0.
|
|
3
|
+
version: 0.181.0
|
|
4
4
|
scope: system
|
|
5
5
|
description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
|
|
6
6
|
files:
|
|
7
7
|
identity.md: sha256:29c2f7df9f6c5acbc5ec17000a4490741e55e426af15ca0d81c8706edd9bd027
|
|
8
8
|
self_map.md: sha256:750822b3488b302c6e32638e6224f270d8e06b50ea85cd6e0bb5a6ff12eed1d8
|
|
9
|
-
config_modification_protocol.md: sha256:
|
|
9
|
+
config_modification_protocol.md: sha256:7bced9b4e03f50c215e1c0bb786a9bfb51f5c1b71ace961ba16ccf6890270f72
|
|
10
10
|
memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
|
|
11
11
|
delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
|
data/lib/samagotchi/client.rb
CHANGED
|
@@ -126,6 +126,8 @@ module Samagotchi
|
|
|
126
126
|
# @param scheme [String, nil] "https" for a TLS server (default http)
|
|
127
127
|
# @param first_token_timeout [Numeric, nil] seconds a completion may take
|
|
128
128
|
# to stream its first text (LLM::HTTP); nil: no limit
|
|
129
|
+
# @param stream_idle_timeout [Numeric, nil] seconds a completion that
|
|
130
|
+
# streamed text may go without more (LLM::HTTP); nil: no limit
|
|
129
131
|
# @param name [String, nil] the host's config name, for error lines
|
|
130
132
|
# (default: LABEL)
|
|
131
133
|
# @param api_key_env [String, nil] the variable holding the host's API
|
|
@@ -135,7 +137,7 @@ module Samagotchi
|
|
|
135
137
|
# HostEntry#auth_scheme), nil: Bearer
|
|
136
138
|
# @param env [Hash] where the key variable is read
|
|
137
139
|
def initialize(host: nil, port: nil, open_timeout: nil, read_timeout: nil, sleeper: nil, scheme: nil,
|
|
138
|
-
first_token_timeout: nil, name: nil, api_key_env: nil, auth: nil, env: ENV)
|
|
140
|
+
first_token_timeout: nil, stream_idle_timeout: nil, name: nil, api_key_env: nil, auth: nil, env: ENV)
|
|
139
141
|
# Unified config precedence: CLI > ENV > file > default (via Samagotchi::Config)
|
|
140
142
|
@host = host || Samagotchi::Config.get("server.host")
|
|
141
143
|
@port = (port || Samagotchi::Config.get("server.port")).to_i
|
|
@@ -150,16 +152,21 @@ module Samagotchi
|
|
|
150
152
|
@props_failures = @props_entry[:failures]
|
|
151
153
|
@props_mutex = @props_entry[:mutex]
|
|
152
154
|
@first_token_timeout = first_token_timeout
|
|
155
|
+
@stream_idle_timeout = stream_idle_timeout
|
|
153
156
|
@host_name = name
|
|
154
157
|
@label = name.to_s.empty? ? LABEL : name.to_s
|
|
155
158
|
@http = LLM::HTTP.new(label: @label, open_timeout: @open_timeout, read_timeout: @read_timeout,
|
|
156
159
|
sleeper: sleeper, first_token_timeout: first_token_timeout,
|
|
160
|
+
stream_idle_timeout: stream_idle_timeout,
|
|
157
161
|
api_key: LLM::ApiKey.for(api_key_env, host: @label, env: env, scheme: auth))
|
|
158
162
|
end
|
|
159
163
|
|
|
160
164
|
# Seconds a completion may take to stream its first text, or nil.
|
|
161
165
|
attr_reader :first_token_timeout
|
|
162
166
|
|
|
167
|
+
# Seconds a completion that streamed text may go without more, or nil.
|
|
168
|
+
attr_reader :stream_idle_timeout
|
|
169
|
+
|
|
163
170
|
# The host's config name, or nil when built without one.
|
|
164
171
|
attr_reader :host_name
|
|
165
172
|
|
data/lib/samagotchi/config.rb
CHANGED
|
@@ -112,6 +112,11 @@ module Samagotchi
|
|
|
112
112
|
# or tool call, for every host; 0 = off. Unset: 120 on remote hosts,
|
|
113
113
|
# off on local ones. hosts.<name>.first_token_timeout wins.
|
|
114
114
|
Entry.new(key: "server.first_token_timeout", yaml_path: %w[server first_token_timeout], type: :integer, default: nil, expose: %i[env config], lifecycle: :worker_start),
|
|
115
|
+
# Seconds a streamed answer that showed something may go without
|
|
116
|
+
# showing more (keep-alives don't count), for every host; 0 = off.
|
|
117
|
+
# Unset: 120 on remote hosts, off on local ones.
|
|
118
|
+
# hosts.<name>.stream_idle_timeout wins.
|
|
119
|
+
Entry.new(key: "server.stream_idle_timeout", yaml_path: %w[server stream_idle_timeout], type: :integer, default: nil, expose: %i[env config], lifecycle: :worker_start),
|
|
115
120
|
|
|
116
121
|
# Both session-settable (chi --set recap.enabled=false): RecapSetup reads them through the session's layer.
|
|
117
122
|
Entry.new(key: "recap.enabled", yaml_path: %w[recap enabled], type: :bool, default: nil, expose: %i[env config], lifecycle: :worker_start,
|
|
@@ -431,7 +436,7 @@ module Samagotchi
|
|
|
431
436
|
# Maps of named entries and the keys an entry may hold
|
|
432
437
|
# (HostConfig.all, ModelSettings.all).
|
|
433
438
|
MAP_ENTRY_KEYS = {
|
|
434
|
-
"hosts" => %w[host port url api api_key_env auth dialect profile first_token_timeout vision sampling thinking
|
|
439
|
+
"hosts" => %w[host port url api api_key_env auth dialect profile first_token_timeout stream_idle_timeout vision sampling thinking
|
|
435
440
|
reasoning_history enabled remote window_tokens steer_cut_after llm_context_strategy llm_context_apply llm_context_budget_tokens models].freeze,
|
|
436
441
|
"models" => %w[profile vision sampling thinking reasoning_history window_tokens steer_cut_after llm_context_strategy llm_context_apply
|
|
437
442
|
llm_context_budget_tokens].freeze
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require_relative "bundle_manifest"
|
|
5
|
+
require_relative "installed_bundles"
|
|
6
|
+
require_relative "log"
|
|
7
|
+
require_relative "paths"
|
|
8
|
+
|
|
9
|
+
module Samagotchi
|
|
10
|
+
# A first session's reminder when none of the core profile's members is installed.
|
|
11
|
+
module CoreNotice
|
|
12
|
+
STAMP_FILE = "core_noticed"
|
|
13
|
+
LINE = "chi: the core safety bundles (loop-guard, guardrails, cost-cap…) aren't installed: chi bundle install core"
|
|
14
|
+
CORE_DIR = File.join(__dir__, "bundles", "core")
|
|
15
|
+
|
|
16
|
+
module_function
|
|
17
|
+
|
|
18
|
+
def show(env: ENV, io: $stderr)
|
|
19
|
+
return if env["SAMAGOTCHI_CORE_NOTICE"] == "off" || env.key?("SAMAGOTCHI_PROJECT_ENV")
|
|
20
|
+
|
|
21
|
+
stamp = File.join(Paths.state_dir(env: env), STAMP_FILE)
|
|
22
|
+
return if File.exist?(stamp)
|
|
23
|
+
|
|
24
|
+
members = BundleManifest.read(dir: CORE_DIR).includes
|
|
25
|
+
installed = InstalledBundles.each(dir: MemoryPaths.bundles_dir(env: env)).any? { |name, _| members.include?(name) }
|
|
26
|
+
return if installed
|
|
27
|
+
|
|
28
|
+
FileUtils.mkdir_p(File.dirname(stamp))
|
|
29
|
+
File.open(stamp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
|
|
30
|
+
io.puts(LINE)
|
|
31
|
+
file.write("shown\n")
|
|
32
|
+
rescue StandardError
|
|
33
|
+
File.unlink(stamp)
|
|
34
|
+
raise
|
|
35
|
+
end
|
|
36
|
+
LINE
|
|
37
|
+
rescue Errno::EEXIST
|
|
38
|
+
nil
|
|
39
|
+
rescue StandardError => e
|
|
40
|
+
Log.warn(:turn, "core_notice_failed", error: e.class.name, msg: e.message)
|
|
41
|
+
nil
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -48,5 +48,12 @@ module Samagotchi
|
|
|
48
48
|
rescue StandardError # degrade-ok: no configured limit; the host's own or the remote default applies
|
|
49
49
|
nil
|
|
50
50
|
end
|
|
51
|
+
|
|
52
|
+
# server.stream_idle_timeout, or nil when unset or unreadable.
|
|
53
|
+
def self.configured_stream_idle_timeout
|
|
54
|
+
Config.get("server.stream_idle_timeout")
|
|
55
|
+
rescue StandardError # degrade-ok: no configured limit; the host's own or the remote default applies
|
|
56
|
+
nil
|
|
57
|
+
end
|
|
51
58
|
end
|
|
52
59
|
end
|
|
@@ -20,7 +20,7 @@ module Samagotchi
|
|
|
20
20
|
# HostRegistry::HostEntry describes them, nil when unset; models:
|
|
21
21
|
# {downcased id => HostModel}.
|
|
22
22
|
HostConfig = Data.define(:name, :host, :port, :scheme, :url, :api, :api_key_env, :auth, :dialect, :profile,
|
|
23
|
-
:first_token_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
|
|
23
|
+
:first_token_timeout, :stream_idle_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
|
|
24
24
|
:window_tokens, :steer_cut_after, :llm_context_strategy, :llm_context_apply, :llm_context_budget_tokens,
|
|
25
25
|
:models) do
|
|
26
26
|
# Every field but name may be left out: nil, models {}.
|
|
@@ -120,6 +120,7 @@ module Samagotchi
|
|
|
120
120
|
# Kept as written; ModelProfile.resolve warns about an unknown one.
|
|
121
121
|
profile: value.call(:profile).to_s.strip.downcase.then { |v| v.empty? ? nil : v },
|
|
122
122
|
first_token_timeout: value.call(:first_token_timeout),
|
|
123
|
+
stream_idle_timeout: value.call(:stream_idle_timeout),
|
|
123
124
|
vision: ConfigFile.vision_flag(value.call(:vision), where),
|
|
124
125
|
remote: ConfigFile.bool_flag(value.call(:remote), where, "remote"),
|
|
125
126
|
window_tokens: ConfigFile.window_tokens(value.call(:window_tokens), where),
|
|
@@ -132,10 +133,12 @@ module Samagotchi
|
|
|
132
133
|
models: HostModel.parse_map(value.call(:models), name),
|
|
133
134
|
llm_context_budget_tokens: LLMContextStrategy.parse_budget(value.call(LLMContextStrategy::BUDGET_KEY), where)
|
|
134
135
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
136
|
+
%i[first_token_timeout stream_idle_timeout].each do |key|
|
|
137
|
+
timeout = fields[key]
|
|
138
|
+
next if timeout.nil? || (timeout.is_a?(Numeric) && !timeout.negative?)
|
|
139
|
+
|
|
140
|
+
ConfigFile.warn_once "Warning: #{where}: #{key} must be seconds (0 = off); using the default"
|
|
141
|
+
fields[key] = nil
|
|
139
142
|
end
|
|
140
143
|
api_key_env = fields[:api_key_env]
|
|
141
144
|
unless api_key_env.nil? || api_key_env.match?(ConfigFile::ENV_NAME_RE)
|
|
@@ -28,6 +28,9 @@ module Samagotchi
|
|
|
28
28
|
# Seconds a remote host's stream may take to show something (a queued
|
|
29
29
|
# free model on OpenRouter can send only keep-alives for minutes).
|
|
30
30
|
REMOTE_FIRST_TOKEN_TIMEOUT = 120
|
|
31
|
+
# Seconds a remote host's stream that showed something may go without
|
|
32
|
+
# showing more (keep-alives alone can hold it until the read timeout).
|
|
33
|
+
REMOTE_STREAM_IDLE_TIMEOUT = 120
|
|
31
34
|
|
|
32
35
|
# One host's answer in list_all_models: the host it was listed from and
|
|
33
36
|
# its port; models: the LLM::ModelInfo list it served ([] when it failed
|
|
@@ -42,6 +45,7 @@ module Samagotchi
|
|
|
42
45
|
# dialect: an api: anthropic host's LLM::Dialect name (#dialect_profile), nil when unset;
|
|
43
46
|
# profile: the configured prompt profile name, if any;
|
|
44
47
|
# first_token_timeout: the configured first-token limit (see #first_token_limit);
|
|
48
|
+
# stream_idle_timeout: the configured stream-idle limit (see #stream_idle_limit);
|
|
45
49
|
# vision: the configured true/false (VisionSupport), nil when unset;
|
|
46
50
|
# sampling: the configured request parameters (SamplingSettings), nil when unset;
|
|
47
51
|
# thinking: the configured level (Thinking), nil when unset;
|
|
@@ -54,7 +58,7 @@ module Samagotchi
|
|
|
54
58
|
# llm_context_budget_tokens: the configured context budget (LLMContextStrategy), nil when unset;
|
|
55
59
|
# models: the ids the host serves whatever it lists, {downcased id => HostModel} ({} when none).
|
|
56
60
|
HostEntry = Struct.new(:name, :host, :port, :client, :api, :scheme, :url, :api_key_env, :auth, :dialect,
|
|
57
|
-
:profile, :first_token_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
|
|
61
|
+
:profile, :first_token_timeout, :stream_idle_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
|
|
58
62
|
:window_tokens, :steer_cut_after, :llm_context_strategy, :llm_context_apply, :llm_context_budget_tokens,
|
|
59
63
|
:models, keyword_init: true) do
|
|
60
64
|
# Talks a chat API through an adapter (LLM::Adapters: the chat loop);
|
|
@@ -106,6 +110,18 @@ module Samagotchi
|
|
|
106
110
|
seconds = remote? ? REMOTE_FIRST_TOKEN_TIMEOUT : nil if seconds.nil?
|
|
107
111
|
seconds&.positive? ? seconds : nil
|
|
108
112
|
end
|
|
113
|
+
|
|
114
|
+
# Seconds a streamed answer that showed something may go without
|
|
115
|
+
# showing more, or nil: the host's stream_idle_timeout, else
|
|
116
|
+
# server.stream_idle_timeout, else 120 for a remote host (a local
|
|
117
|
+
# server may buffer a long tool call's arguments, and read_timeout
|
|
118
|
+
# catches a dead one). 0 turns it off.
|
|
119
|
+
def stream_idle_limit
|
|
120
|
+
seconds = stream_idle_timeout
|
|
121
|
+
seconds = HostAddress.configured_stream_idle_timeout if seconds.nil?
|
|
122
|
+
seconds = remote? ? REMOTE_STREAM_IDLE_TIMEOUT : nil if seconds.nil?
|
|
123
|
+
seconds&.positive? ? seconds : nil
|
|
124
|
+
end
|
|
109
125
|
end
|
|
110
126
|
|
|
111
127
|
# Where a model's requests go: the host entry, the client to use and the
|
|
@@ -139,11 +155,11 @@ module Samagotchi
|
|
|
139
155
|
# it was built from (HostConfig.all, compared as read: the YAML read is
|
|
140
156
|
# mtime-cached), so a host added while chi web runs is listed on the next
|
|
141
157
|
# read, and its model lists, index and adapters are kept while hosts:
|
|
142
|
-
# stay. It doesn't rebuild on server.first_token_timeout
|
|
143
|
-
# server.host/port fallback entry:
|
|
144
|
-
# refuses a client override (Shared).
|
|
145
|
-
# it once, at their start: a running
|
|
146
|
-
# with.
|
|
158
|
+
# stay. It doesn't rebuild on server.first_token_timeout,
|
|
159
|
+
# server.stream_idle_timeout or the server.host/port fallback entry:
|
|
160
|
+
# those are read at construction. It refuses a client override (Shared).
|
|
161
|
+
# An Engine and the TerminalUI take it once, at their start: a running
|
|
162
|
+
# worker keeps the hosts it started with.
|
|
147
163
|
# For any env but the process ENV (chi self's spec envs): a fresh
|
|
148
164
|
# registry on that env, never kept.
|
|
149
165
|
# @return [HostRegistry]
|
|
@@ -182,7 +198,8 @@ module Samagotchi
|
|
|
182
198
|
fields = cfg.to_h.merge(name: key.to_s.downcase, port: cfg.port.to_i, api: cfg.api&.to_sym, models: cfg.models || {})
|
|
183
199
|
entry = HostEntry.new(**fields)
|
|
184
200
|
entry.client = Client.new(host: cfg.host, port: cfg.port, scheme: cfg.scheme,
|
|
185
|
-
first_token_timeout: entry.first_token_limit,
|
|
201
|
+
first_token_timeout: entry.first_token_limit,
|
|
202
|
+
stream_idle_timeout: entry.stream_idle_limit, name: entry.name,
|
|
186
203
|
api_key_env: entry.api_key_env, auth: entry.auth_scheme, env: env)
|
|
187
204
|
@entries[entry.name] = entry
|
|
188
205
|
end
|
|
@@ -272,7 +289,8 @@ module Samagotchi
|
|
|
272
289
|
def adapter_for(entry)
|
|
273
290
|
@mutex.synchronize do
|
|
274
291
|
@adapters[entry.name] ||= LLM::Adapters.for(entry, models_ttl: entry.models_ttl,
|
|
275
|
-
first_token_timeout: entry.first_token_limit
|
|
292
|
+
first_token_timeout: entry.first_token_limit,
|
|
293
|
+
stream_idle_timeout: entry.stream_idle_limit)
|
|
276
294
|
end
|
|
277
295
|
end
|
|
278
296
|
|
|
@@ -511,7 +511,8 @@ module Samagotchi
|
|
|
511
511
|
|
|
512
512
|
# One generation's request, asking again on a mid-stream drop (LLM::HTTP
|
|
513
513
|
# raises RetryExhausted once a stream that already showed something
|
|
514
|
-
# fails, where a retry would repeat output
|
|
514
|
+
# fails, where a retry would repeat output; StreamStalled, one that went
|
|
515
|
+
# quiet past stream_idle_timeout, is one) up to MAX_STREAM_DROPS
|
|
515
516
|
# times after the transport's backoff: the partial reply is dropped and
|
|
516
517
|
# the step restarts from the same conversation, as generation_retrying
|
|
517
518
|
# with restarted: true. A cancel (before or during the wait) never
|
|
@@ -573,7 +574,7 @@ module Samagotchi
|
|
|
573
574
|
if count.drops >= limit || !streamed_any
|
|
574
575
|
raise if count.requests == e.attempts.to_i
|
|
575
576
|
|
|
576
|
-
raise
|
|
577
|
+
raise e.recounted(count.requests)
|
|
577
578
|
end
|
|
578
579
|
|
|
579
580
|
count.drops += 1
|
|
@@ -25,11 +25,12 @@ module Samagotchi
|
|
|
25
25
|
# The adapter's LLM::HTTP: the timeouts (#timeouts), one attempt when
|
|
26
26
|
# +retries+ is false and no +retry_policy+ is given.
|
|
27
27
|
def build_http(timeout:, open_timeout:, retries:, retry_policy:, sleeper:, first_token_timeout:, api_key:,
|
|
28
|
-
diagnosis_header: nil)
|
|
28
|
+
stream_idle_timeout: nil, diagnosis_header: nil)
|
|
29
29
|
open_timeout, read_timeout = timeouts(timeout, open_timeout)
|
|
30
30
|
policy = retry_policy || (retries ? nil : HTTP::RetryPolicy.none)
|
|
31
31
|
HTTP.new(label: @host_name, open_timeout: open_timeout, read_timeout: read_timeout, retry_policy: policy,
|
|
32
|
-
sleeper: sleeper, first_token_timeout: first_token_timeout,
|
|
32
|
+
sleeper: sleeper, first_token_timeout: first_token_timeout, stream_idle_timeout: stream_idle_timeout,
|
|
33
|
+
api_key: api_key,
|
|
33
34
|
diagnosis_header: diagnosis_header)
|
|
34
35
|
end
|
|
35
36
|
|
|
@@ -17,7 +17,8 @@ module Samagotchi
|
|
|
17
17
|
|
|
18
18
|
# A host entry's adapter (its api, API base, name, key and remoteness).
|
|
19
19
|
# @param entry [HostRegistry::HostEntry]
|
|
20
|
-
# @param options [Hash] more adapter options (models_ttl:, first_token_timeout:,
|
|
20
|
+
# @param options [Hash] more adapter options (models_ttl:, first_token_timeout:,
|
|
21
|
+
# stream_idle_timeout:, ...)
|
|
21
22
|
# @raise [ArgumentError] the entry's api has no chat adapter
|
|
22
23
|
def self.for(entry, **)
|
|
23
24
|
adapter_class(entry.api).for(entry, **)
|
|
@@ -91,6 +91,11 @@ module Samagotchi
|
|
|
91
91
|
# what the first-token limit waits for.
|
|
92
92
|
def self.shows?(event) = %w[content_block_start content_block_delta].include?(event["type"])
|
|
93
93
|
|
|
94
|
+
# Whether a streamed +event+ ends the message (message_delta,
|
|
95
|
+
# message_stop): it restarts the stream-idle clock without counting as
|
|
96
|
+
# shown.
|
|
97
|
+
def self.ending?(event) = %w[message_delta message_stop].include?(event["type"])
|
|
98
|
+
|
|
94
99
|
# Whether a streamed +event+ carries part of a tool call.
|
|
95
100
|
def self.tool_call_delta?(event)
|
|
96
101
|
case event["type"]
|
|
@@ -100,7 +100,7 @@ module Samagotchi
|
|
|
100
100
|
DROPPED_OPTIONS = %i[reasoning_effort chat_template_kwargs stream_options prompt_cache_key logprobs top_logprobs
|
|
101
101
|
max_completion_tokens].freeze
|
|
102
102
|
|
|
103
|
-
attr_reader :base_url, :host_name, :api_key_env, :models_ttl, :first_token_timeout, :dialect
|
|
103
|
+
attr_reader :base_url, :host_name, :api_key_env, :models_ttl, :first_token_timeout, :stream_idle_timeout, :dialect
|
|
104
104
|
|
|
105
105
|
# The Messages API root a base URL names: without a trailing / and a
|
|
106
106
|
# trailing /v1 (as ANTHROPIC_BASE_URL), so requests never go to
|
|
@@ -120,11 +120,12 @@ module Samagotchi
|
|
|
120
120
|
# The rest as OpenAIChat#initialize takes them.
|
|
121
121
|
def initialize(base_url:, host_name:, api_key_env: nil, auth: nil, dialect: nil, stream: true, retries: true,
|
|
122
122
|
timeout: nil, env: ENV, sleeper: nil, retry_policy: nil, models_ttl: DEFAULT_MODELS_TTL, remote: false,
|
|
123
|
-
first_token_timeout: nil, purpose: "chat", open_timeout: nil)
|
|
123
|
+
first_token_timeout: nil, stream_idle_timeout: nil, purpose: "chat", open_timeout: nil)
|
|
124
124
|
@dialect = Dialect.for(dialect)
|
|
125
125
|
@remote = remote
|
|
126
126
|
@purpose = purpose
|
|
127
127
|
@first_token_timeout = first_token_timeout
|
|
128
|
+
@stream_idle_timeout = stream_idle_timeout
|
|
128
129
|
@base_url = base_url.to_s.chomp("/")
|
|
129
130
|
@host_name = host_name.to_s
|
|
130
131
|
@api_key_env = api_key_env
|
|
@@ -136,6 +137,7 @@ module Samagotchi
|
|
|
136
137
|
@binding = AnthropicBindingRecovery.new(refusals: @refusals, host_name: @host_name, budget_form: method(:budget_form?))
|
|
137
138
|
@http = build_http(timeout: timeout, open_timeout: open_timeout, retries: retries, retry_policy: retry_policy,
|
|
138
139
|
sleeper: sleeper, first_token_timeout: first_token_timeout,
|
|
140
|
+
stream_idle_timeout: stream_idle_timeout,
|
|
139
141
|
api_key: ApiKey.for(api_key_env, host: @host_name, env: env, scheme: auth || @dialect.auth),
|
|
140
142
|
diagnosis_header: AnthropicBindingRecovery::DIAGNOSIS_HEADER)
|
|
141
143
|
end
|
|
@@ -463,6 +465,8 @@ module Samagotchi
|
|
|
463
465
|
if AnthropicAssembly.shows?(event)
|
|
464
466
|
shown.call
|
|
465
467
|
on_shown&.call
|
|
468
|
+
elsif AnthropicAssembly.ending?(event)
|
|
469
|
+
shown.call(ending: true)
|
|
466
470
|
end
|
|
467
471
|
on_delta&.call(content: content, reasoning: reasoning, payload: assembly.with_usage(event)) unless event["type"] == "ping"
|
|
468
472
|
end
|