samagotchi 0.179.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.
Files changed (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/bin/chi +10 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/bundles.md +39 -3
  6. data/docs/cli.md +16 -9
  7. data/docs/configuration.md +25 -5
  8. data/docs/context.md +7 -0
  9. data/docs/internals/anthropic.md +4 -3
  10. data/docs/internals/background-tasks.md +4 -1
  11. data/docs/internals/block-renderers.md +11 -7
  12. data/docs/internals/bundles.md +12 -10
  13. data/docs/internals/objectives.md +9 -4
  14. data/docs/internals/web-frontend.md +127 -6
  15. data/docs/internals/working-set.md +24 -5
  16. data/docs/memory.md +3 -0
  17. data/docs/plugins.md +17 -6
  18. data/docs/sessions.md +1 -1
  19. data/docs/testing.md +5 -1
  20. data/lib/samagotchi/block_renderers.rb +22 -3
  21. data/lib/samagotchi/bundle_command.rb +9 -2
  22. data/lib/samagotchi/bundle_needs.rb +1 -1
  23. data/lib/samagotchi/bundle_settings_check.rb +5 -2
  24. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  25. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  26. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  27. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  28. data/lib/samagotchi/client.rb +8 -1
  29. data/lib/samagotchi/config.rb +6 -1
  30. data/lib/samagotchi/context_providers.rb +6 -8
  31. data/lib/samagotchi/core_notice.rb +44 -0
  32. data/lib/samagotchi/host_address.rb +7 -0
  33. data/lib/samagotchi/host_config.rb +8 -5
  34. data/lib/samagotchi/host_registry.rb +26 -8
  35. data/lib/samagotchi/installed_bundles/dir.rb +17 -55
  36. data/lib/samagotchi/installed_bundles/standing.rb +23 -3
  37. data/lib/samagotchi/installed_bundles.rb +26 -11
  38. data/lib/samagotchi/kernel_loop.rb +3 -2
  39. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  40. data/lib/samagotchi/llm/adapters.rb +2 -1
  41. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  42. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  43. data/lib/samagotchi/llm/chat_loop.rb +6 -5
  44. data/lib/samagotchi/llm/errors.rb +41 -3
  45. data/lib/samagotchi/llm/http.rb +85 -22
  46. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  47. data/lib/samagotchi/memory_bundle/status.rb +10 -6
  48. data/lib/samagotchi/objectives.rb +7 -2
  49. data/lib/samagotchi/owner_lock.rb +2 -0
  50. data/lib/samagotchi/plugin/api.rb +4 -1
  51. data/lib/samagotchi/plugin/context.rb +9 -0
  52. data/lib/samagotchi/plugin/peer.rb +32 -15
  53. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  54. data/lib/samagotchi/row_refs.rb +14 -3
  55. data/lib/samagotchi/session_chain/delete.rb +6 -6
  56. data/lib/samagotchi/session_config.rb +15 -9
  57. data/lib/samagotchi/session_manager/removal.rb +2 -2
  58. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  59. data/lib/samagotchi/terminal_ui/formatting.rb +13 -3
  60. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  61. data/lib/samagotchi/tool_ids.rb +19 -0
  62. data/lib/samagotchi/tool_runner.rb +8 -4
  63. data/lib/samagotchi/tools/registry.rb +3 -2
  64. data/lib/samagotchi/tools/task_runtime.rb +46 -3
  65. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  66. data/lib/samagotchi/version.rb +1 -1
  67. data/lib/samagotchi/web/public/app.js +22 -14
  68. data/lib/samagotchi/web/public/block_host.js +20 -20
  69. data/lib/samagotchi/web/public/block_renderers.css +5 -5
  70. data/lib/samagotchi/web/public/context_chips.js +183 -49
  71. data/lib/samagotchi/web/public/history_shape.js +5 -3
  72. data/lib/samagotchi/web/public/images.js +1 -1
  73. data/lib/samagotchi/web/public/index.html +90 -5
  74. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  75. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  76. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  77. data/lib/samagotchi/web/public/peer_data.js +131 -0
  78. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  79. data/lib/samagotchi/web/public/peer_links.js +161 -0
  80. data/lib/samagotchi/web/public/peer_note.js +49 -0
  81. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  82. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  83. data/lib/samagotchi/web/public/session_view.js +10 -1
  84. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  85. data/lib/samagotchi/web/public/turn_html.js +11 -2
  86. data/lib/samagotchi/web/public/working_set.js +9 -3
  87. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  88. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  89. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  90. data/lib/samagotchi/web/public/ws_order.js +48 -0
  91. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  92. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  93. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  94. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  95. metadata +11 -1
@@ -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. "#" and "~" split: in "~name" (that user's home) the
28
- # name after it is what is checked.
29
- TOKEN_SPLIT = %r{[/\s"'=:,;|&()<>@~#]+}
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; `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
+ - `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.179.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:44cf7bdac8e526805bff36b76b54fefecd41db30ca525c2ed661d78fe9155dd8
9
+ config_modification_protocol.md: sha256:7bced9b4e03f50c215e1c0bb786a9bfb51f5c1b71ace961ba16ccf6890270f72
10
10
  memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
11
11
  delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
@@ -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
 
@@ -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
@@ -151,21 +151,19 @@ module Samagotchi
151
151
  # installed (they run outside the guardrails gate, as a plugin loads:
152
152
  # checked the same way).
153
153
  # @return [String]
154
- # @raise [Invalid] the bundle is gone, a script is gone, unrecorded or
155
- # changed (InstalledBundles::Dir#file_refusal), or this chi doesn't meet
156
- # the bundle's requires_chi
157
- # @raise [JSON::ParserError] the bundle's manifest.json doesn't parse (the
158
- # plan's D7: kept as it is). One that parses but isn't an object reads
159
- # as a record with no scripts, and the command runs (D8: kept too)
154
+ # @raise [Invalid] the bundle is gone, its manifest.json doesn't read,
155
+ # this chi doesn't meet its requires_chi, or a script is unrecorded,
156
+ # gone or changed (InstalledBundles::Dir#file_refusal)
160
157
  def command_for(source)
161
158
  return source.cmd unless source.provider
162
159
 
163
160
  standing = InstalledBundles.standing(source.provider)
164
161
  raise Invalid, "bundle #{source.provider} isn't installed" unless standing
165
162
 
166
- # Its bundle is too new for this chi (installed with --force, or chi
163
+ # Its record doesn't read (nothing to check its scripts against), or
164
+ # its bundle is too new for this chi (installed with --force, or chi
167
165
  # was downgraded): its script won't run, as its plugin wouldn't load.
168
- raise Invalid, "bundle #{source.provider}: #{standing.refusal.text}" if standing.too_new?
166
+ raise Invalid, "bundle #{source.provider}: #{standing.refusal.text}" unless standing.usable?
169
167
 
170
168
  installed = InstalledBundles::Dir.new(name: source.provider)
171
169
  standing.record.scripts.each do |file, sha|
@@ -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
- timeout = fields[:first_token_timeout]
136
- unless timeout.nil? || (timeout.is_a?(Numeric) && !timeout.negative?)
137
- ConfigFile.warn_once "Warning: #{where}: first_token_timeout must be seconds (0 = off); using the default"
138
- fields[:first_token_timeout] = nil
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 or the
143
- # server.host/port fallback entry: those are read at construction. It
144
- # refuses a client override (Shared). An Engine and the TerminalUI take
145
- # it once, at their start: a running worker keeps the hosts it started
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, name: entry.name,
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
 
@@ -12,6 +12,9 @@ module Samagotchi
12
12
  # manifest.yml are. Its only state is the name and the folder; writing
13
13
  # the record is MemoryBundle::Provenance's (a Dir too).
14
14
  class Dir
15
+ # Each kind of file Dir#file_refusal checks, and its folder.
16
+ FOLDERS = { plugin: "plugin", scripts: "scripts", guardrails: "guardrails" }.freeze
17
+
15
18
  attr_reader :name, :bundle_dir
16
19
 
17
20
  # @param dir [String] the bundles dir (InstalledBundles.dir by default)
@@ -52,77 +55,36 @@ module Samagotchi
52
55
  # installed: the one "is this file as installed" check of what chi loads
53
56
  # (the plugin), runs (a provider's scripts), serves (a renderer's
54
57
  # scripts) or reads (the rules). A --dev install's links pass. Hashes
55
- # only the file asked about. Each kind keeps its own order of checks and
56
- # its words (the plan's D6 makes them one):
57
- # :plugin missing, then no sha recorded, then changed
58
- # :scripts no sha recorded, then missing, then changed
59
- # :guardrails missing, then changed (no sha recorded reads as changed)
58
+ # only the file asked about. One order and one wording for every kind:
59
+ # no sha recorded, then missing, then changed, each "bundle X's
60
+ # <folder>/<file> … (reinstall the bundle)".
60
61
  # @param kind [Symbol] :plugin, :scripts or :guardrails
61
62
  # @param file [String, nil] its name in that folder (nil: a plugin the
62
63
  # record names no file of, which is missing)
63
64
  # @param recorded [String, nil] the record's sha256 for it
64
65
  # @return [Refusal, nil]
65
66
  def file_refusal(kind, file, recorded)
66
- case kind
67
- when :plugin then plugin_refusal(file, recorded)
68
- when :scripts then script_refusal(file, recorded)
69
- when :guardrails then rules_refusal(file, recorded)
70
- else raise ArgumentError, "no installed files of kind #{kind.inspect}"
71
- end
72
- end
73
-
74
- # The installed bundle's record, nil when it isn't installed.
75
- # @return [Record, nil]
76
- # @raise [JSON::ParserError] manifest.json doesn't parse
77
- def record
78
- Record.read(@name, File.join(@bundle_dir, "manifest.json"))
79
- end
80
-
81
- private
82
-
83
- def plugin_refusal(file, recorded)
84
- path = file && File.join(plugin_dir, file)
85
- return Refusal.new(kind: :file_missing, text: "the file is missing") unless path && File.file?(path)
86
- return nil if Sha.unchecked?(recorded)
87
-
67
+ folder = FOLDERS.fetch(kind) { raise ArgumentError, "no installed files of kind #{kind.inspect}" }
68
+ what = "bundle #{@name}'s #{folder}#{"/#{file}" if file}"
88
69
  expected = Sha.recorded(recorded)
89
- return Refusal.new(kind: :file_unrecorded, text: "no sha256 recorded for it (reinstall the bundle)") if expected.empty?
70
+ return Refusal.new(kind: :file_unrecorded, text: "#{what} isn't recorded (reinstall the bundle)") if expected.empty?
90
71
 
91
- actual = Sha.of_file(path)
92
- return nil if actual == expected
93
-
94
- Refusal.new(kind: :file_changed, actual: actual, expected: expected,
95
- text: "its sha256 #{actual[0, 12]}… differs from the installed #{expected[0, 12]}… " \
96
- "(edited after install? reinstall the bundle)")
97
- end
98
-
99
- def script_refusal(file, recorded)
100
- path = File.join(scripts_dir, file)
101
- expected = Sha.recorded(recorded)
102
- if expected.empty?
103
- return Refusal.new(kind: :file_unrecorded,
104
- text: "bundle #{@name}'s scripts/#{file} isn't among its installed scripts (reinstall the bundle)")
105
- end
106
- return Refusal.new(kind: :file_missing, text: "bundle #{@name}'s scripts/#{file} is missing (reinstall the bundle)") unless File.file?(path)
72
+ path = file && File.join(@bundle_dir, folder, file)
73
+ return Refusal.new(kind: :file_missing, text: "#{what} is missing (reinstall the bundle)") unless path && File.file?(path)
107
74
  return nil if Sha.unchecked?(recorded)
108
75
 
109
76
  actual = Sha.of_file(path)
110
77
  return nil if actual == expected
111
78
 
112
79
  Refusal.new(kind: :file_changed, actual: actual, expected: expected,
113
- text: "bundle #{@name}'s scripts/#{file} differs from the installed one (reinstall the bundle)")
80
+ text: "#{what} differs from the installed one (reinstall the bundle)")
114
81
  end
115
82
 
116
- def rules_refusal(file, recorded)
117
- path = File.join(guardrails_dir, file)
118
- return Refusal.new(kind: :file_missing, text: "the file is missing") unless File.file?(path)
119
- return nil if Sha.unchecked?(recorded)
120
-
121
- actual = Sha.of_file(path)
122
- return nil if actual == Sha.recorded(recorded)
123
-
124
- Refusal.new(kind: :file_changed, actual: actual, expected: Sha.recorded(recorded),
125
- text: "its sha256 differs from the installed one (edited after install? reinstall the bundle)")
83
+ # The installed bundle's record, nil when it isn't installed.
84
+ # @return [Record, nil]
85
+ # @raise [JSON::ParserError] manifest.json doesn't parse
86
+ def record
87
+ Record.read(@name, File.join(@bundle_dir, "manifest.json"))
126
88
  end
127
89
  end
128
90
  end
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
+ autoload :Log, File.expand_path("../log", __dir__)
5
+
4
6
  module InstalledBundles
5
7
  # Why chi won't use an installed bundle, or one of its files: the verdict's
6
8
  # answer, which each reader reacts to in its own way (fail closed, a note,
@@ -17,17 +19,23 @@ module Samagotchi
17
19
  def initialize(kind:, text:, actual: nil, expected: nil) = super
18
20
  end
19
21
 
22
+ # The [bundle, reason] pairs Standing.warn_unreadable has logged.
23
+ UNREADABLE_WARNED = Set.new
24
+ UNREADABLE_LOCK = Mutex.new
25
+
20
26
  # One installed bundle as the verdict sees it, before any of its files is
21
27
  # looked at: its record (one with error set when it doesn't read) and why
22
28
  # chi won't use it, nil when it may.
23
29
  Standing = Data.define(:name, :record, :refusal) do
24
- # The bundle-level gate, on a record already read: an unreadable record,
25
- # then requires_chi. Reads the record's manifest (cached); a cache miss
26
- # hashes the kept manifest.yml (Manifest.of), and no other file.
30
+ # The bundle-level gate, on a record already read: an unreadable record
31
+ # (warned of once, .warn_unreadable), then requires_chi. Reads the
32
+ # record's manifest (cached); a cache miss hashes the kept manifest.yml
33
+ # (Manifest.of), and no other file.
27
34
  # @param record [Record]
28
35
  # @return [Standing]
29
36
  def self.of(name, record)
30
37
  refusal = if record.error?
38
+ warn_unreadable(name, record.error)
31
39
  Refusal.new(kind: :unreadable, text: record.error)
32
40
  elsif (failure = record.manifest.requires_chi_failure)
33
41
  Refusal.new(kind: :too_new, text: failure)
@@ -35,6 +43,18 @@ module Samagotchi
35
43
  new(name: name, record: record, refusal: refusal)
36
44
  end
37
45
 
46
+ # A record that doesn't read, said in the log once per process per
47
+ # bundle (and reason), whichever reader came across it: most readers
48
+ # only skip it (providers, renderers, settings, needs, memory owners).
49
+ def self.warn_unreadable(name, text)
50
+ return unless UNREADABLE_LOCK.synchronize { UNREADABLE_WARNED.add?([name, text]) }
51
+
52
+ Log.warn(:memory, "bundle_unreadable", bundle: name, msg: text)
53
+ end
54
+
55
+ # Forget what was warned of (specs).
56
+ def self.reset_warnings! = UNREADABLE_LOCK.synchronize { UNREADABLE_WARNED.clear }
57
+
38
58
  def usable? = refusal.nil?
39
59
 
40
60
  def unreadable? = refusal&.kind == :unreadable
@@ -16,6 +16,10 @@ module Samagotchi
16
16
  # removing a bundle is MemoryBundle's, which builds on this and never the
17
17
  # reverse (docs/internals/bundles.md).
18
18
  module InstalledBundles
19
+ # What reading a manifest.json may raise: it doesn't parse, it holds a
20
+ # key that isn't UTF-8 (which can't be a symbol), or it can't be read.
21
+ UNREADABLE = [JSON::ParserError, EncodingError, SystemCallError].freeze
22
+
19
23
  def self.dir
20
24
  MemoryPaths.bundles_dir
21
25
  end
@@ -41,10 +45,8 @@ module Samagotchi
41
45
 
42
46
  begin
43
47
  data = JSON.parse(File.read(mjson), symbolize_names: true)
44
- rescue JSON::ParserError, EncodingError, SystemCallError => e # a key that isn't UTF-8 can't be a symbol
45
- if holding.nil? || ::Dir.exist?(File.join(dir, name, holding.to_s))
46
- yield name, Record.unreadable(name, "manifest.json is unreadable: #{e.message}")
47
- end
48
+ rescue *UNREADABLE => e
49
+ yield name, unreadable(name, e) if holding.nil? || ::Dir.exist?(File.join(dir, name, holding.to_s))
48
50
  next
49
51
  end
50
52
  next if holding && !(data.is_a?(Hash) && data[holding].is_a?(Hash) && !data[holding].empty?)
@@ -63,24 +65,37 @@ module Samagotchi
63
65
  each(holding: holding, dir: dir) { |name, record| yield Standing.of(name, record) }
64
66
  end
65
67
 
66
- # One installed bundle's Standing, by name (one record read, no walk).
68
+ # One installed bundle's Standing, by name (one record read, no walk); a
69
+ # manifest.json that doesn't read is :unreadable, in .each's words.
67
70
  # @return [Standing, nil] nil when it isn't installed
68
- # @raise [JSON::ParserError] manifest.json doesn't parse (as Dir#record:
69
- # ContextProviders.command_for lets it out today, the plan's D7)
70
71
  def self.standing(name, dir: InstalledBundles.dir)
71
- record = Dir.new(name: name, dir: dir).record
72
+ record = begin
73
+ Dir.new(name: name, dir: dir).record
74
+ rescue *UNREADABLE => e
75
+ unreadable(name, e)
76
+ end
72
77
  record && Standing.of(name, record)
73
78
  end
74
79
 
80
+ # The one record of a manifest.json that raised +error+ when read.
81
+ def self.unreadable(name, error) = Record.unreadable(name, "manifest.json is unreadable: #{error.message}")
82
+ private_class_method :unreadable
83
+
75
84
  # The other installed bundles of +scope+ whose record lists the memory
76
85
  # file +file_key+, by name (a manifest that doesn't read is left out).
77
86
  # A project-scoped record doesn't say which project: one from another
78
87
  # repo counts too, which errs on keeping the file.
79
- # A record that doesn't read is skipped off the record itself: a claimant
80
- # check reads no manifest (Standing's requires_chi is no question here).
88
+ # A record that doesn't read is skipped off the record itself (warned of
89
+ # once, as Standing.of does): a claimant check reads no manifest
90
+ # (Standing's requires_chi is no question here).
81
91
  def self.claimants(file_key, scope:, except: nil, dir: InstalledBundles.dir)
82
92
  each(dir: dir).filter_map do |name, record|
83
- next if name == except || record.error?
93
+ next if name == except
94
+
95
+ if record.error?
96
+ Standing.warn_unreadable(name, record.error)
97
+ next
98
+ end
84
99
  next unless record.effective_scope == scope.to_s && record.owns?(file_key)
85
100
 
86
101
  name
@@ -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) up to MAX_STREAM_DROPS
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 LLM::RetryExhausted.new(attempts: count.requests, last_error: e.last_error, label: e.host)
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, api_key: api_key,
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"]