samagotchi 0.192.0 → 0.194.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 (190) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +128 -1
  3. data/docs/architecture.md +3 -3
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +82 -40
  6. data/docs/cli.md +47 -17
  7. data/docs/configuration.md +75 -8
  8. data/docs/context.md +8 -5
  9. data/docs/desktop.md +3 -0
  10. data/docs/guardrails.md +20 -5
  11. data/docs/hooks.md +1 -0
  12. data/docs/internals/bridge.md +3 -1
  13. data/docs/internals/bundles.md +2 -2
  14. data/docs/internals/engine.md +46 -3
  15. data/docs/internals/pages.md +4 -4
  16. data/docs/internals/panes.md +66 -0
  17. data/docs/internals/participants.md +5 -3
  18. data/docs/internals/peers.md +176 -27
  19. data/docs/internals/prompt-caching.md +6 -1
  20. data/docs/internals/remote-sessions.md +6 -0
  21. data/docs/internals/session-lifecycle.md +12 -4
  22. data/docs/internals/web-frontend.md +106 -22
  23. data/docs/internals/working-set.md +5 -1
  24. data/docs/peers.md +150 -27
  25. data/docs/plugins.md +48 -7
  26. data/docs/releasing.md +30 -2
  27. data/docs/scheduling.md +3 -2
  28. data/docs/sessions.md +16 -7
  29. data/docs/sub-agent.md +6 -4
  30. data/docs/system-one.md +4 -0
  31. data/docs/testing.md +38 -3
  32. data/docs/thin-clients.md +27 -11
  33. data/lib/samagotchi/bridge/card_store.rb +1 -1
  34. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  35. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  36. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  37. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +61 -24
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  39. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  40. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  41. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +57 -19
  42. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  43. data/lib/samagotchi/bundles/coordinator/manifest.yml +2 -2
  44. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +31 -0
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  47. data/lib/samagotchi/bundles/mcp/plugin.rb +0 -7
  48. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  49. data/lib/samagotchi/chi_invocation.rb +7 -0
  50. data/lib/samagotchi/client.rb +18 -0
  51. data/lib/samagotchi/codex_rollout.rb +93 -0
  52. data/lib/samagotchi/compat.rb +8 -1
  53. data/lib/samagotchi/config.rb +19 -6
  54. data/lib/samagotchi/continue_offer.rb +13 -1
  55. data/lib/samagotchi/delivery.rb +2 -2
  56. data/lib/samagotchi/effective_model.rb +28 -2
  57. data/lib/samagotchi/engine/cards.rb +9 -4
  58. data/lib/samagotchi/engine/hooks.rb +8 -0
  59. data/lib/samagotchi/engine/models.rb +197 -7
  60. data/lib/samagotchi/engine/plugins.rb +2 -0
  61. data/lib/samagotchi/engine/side_requests.rb +72 -13
  62. data/lib/samagotchi/engine/toolkit.rb +1 -1
  63. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  64. data/lib/samagotchi/engine.rb +11 -8
  65. data/lib/samagotchi/engine_snapshots.rb +16 -3
  66. data/lib/samagotchi/events.rb +1 -0
  67. data/lib/samagotchi/guardrails/pair_boundary.rb +49 -18
  68. data/lib/samagotchi/hooks.rb +3 -1
  69. data/lib/samagotchi/host_registry.rb +146 -16
  70. data/lib/samagotchi/idle_client.rb +13 -2
  71. data/lib/samagotchi/idle_recap.rb +33 -3
  72. data/lib/samagotchi/idle_target.rb +27 -7
  73. data/lib/samagotchi/jsonl_store.rb +13 -2
  74. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  75. data/lib/samagotchi/llm/anthropic_messages.rb +14 -2
  76. data/lib/samagotchi/llm/errors.rb +35 -4
  77. data/lib/samagotchi/llm/model_listing.rb +19 -0
  78. data/lib/samagotchi/llm/openai_chat.rb +8 -2
  79. data/lib/samagotchi/llm/prompt_cache.rb +5 -0
  80. data/lib/samagotchi/model_binding.rb +46 -4
  81. data/lib/samagotchi/model_catalog.rb +68 -8
  82. data/lib/samagotchi/model_profile.rb +35 -0
  83. data/lib/samagotchi/models_command.rb +8 -4
  84. data/lib/samagotchi/pages/launch.rb +1 -1
  85. data/lib/samagotchi/panes/kitty.rb +122 -0
  86. data/lib/samagotchi/panes.rb +185 -0
  87. data/lib/samagotchi/peer_announce.rb +245 -0
  88. data/lib/samagotchi/peer_cold.rb +92 -0
  89. data/lib/samagotchi/peer_command.rb +121 -20
  90. data/lib/samagotchi/peer_continue.rb +42 -16
  91. data/lib/samagotchi/peer_exchanges.rb +7 -0
  92. data/lib/samagotchi/peer_mailbox.rb +50 -10
  93. data/lib/samagotchi/peer_pair_here.rb +149 -0
  94. data/lib/samagotchi/peer_presence.rb +434 -0
  95. data/lib/samagotchi/peer_receipts.rb +33 -6
  96. data/lib/samagotchi/peer_say.rb +46 -21
  97. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  98. data/lib/samagotchi/plugin/api.rb +13 -1
  99. data/lib/samagotchi/plugin/card.rb +68 -11
  100. data/lib/samagotchi/plugin/context.rb +33 -2
  101. data/lib/samagotchi/plugin/panes.rb +54 -0
  102. data/lib/samagotchi/plugin/peer.rb +170 -63
  103. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  104. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  105. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  106. data/lib/samagotchi/plugin/peers.rb +89 -9
  107. data/lib/samagotchi/recap_setup.rb +40 -3
  108. data/lib/samagotchi/self_report.rb +25 -6
  109. data/lib/samagotchi/send_command.rb +6 -6
  110. data/lib/samagotchi/served_lookup.rb +225 -0
  111. data/lib/samagotchi/served_ref.rb +41 -0
  112. data/lib/samagotchi/session_access/contract.rb +6 -0
  113. data/lib/samagotchi/session_access/local.rb +149 -40
  114. data/lib/samagotchi/session_access/remote.rb +4 -4
  115. data/lib/samagotchi/session_access/remote_peers.rb +8 -5
  116. data/lib/samagotchi/session_chain/links.rb +8 -3
  117. data/lib/samagotchi/session_commands.rb +40 -8
  118. data/lib/samagotchi/session_continue.rb +11 -6
  119. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  120. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  121. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  122. data/lib/samagotchi/session_manager/removal.rb +3 -0
  123. data/lib/samagotchi/session_manager/spawn.rb +6 -1
  124. data/lib/samagotchi/session_model_settings.rb +7 -3
  125. data/lib/samagotchi/session_stores.rb +25 -11
  126. data/lib/samagotchi/sessions_command.rb +16 -3
  127. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  128. data/lib/samagotchi/system_one/runs.rb +5 -2
  129. data/lib/samagotchi/system_prompt.rb +11 -4
  130. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  131. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  132. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  133. data/lib/samagotchi/terminal_ui.rb +1 -1
  134. data/lib/samagotchi/testing/boundary.rb +0 -1
  135. data/lib/samagotchi/testing/bundle.rb +6 -2
  136. data/lib/samagotchi/testing/host.rb +1 -0
  137. data/lib/samagotchi/testing/recorder.rb +3 -0
  138. data/lib/samagotchi/turn_endings.rb +6 -2
  139. data/lib/samagotchi/user_typed.rb +29 -0
  140. data/lib/samagotchi/version.rb +1 -1
  141. data/lib/samagotchi/web/app.rb +8 -20
  142. data/lib/samagotchi/web/participant_review.rb +1 -1
  143. data/lib/samagotchi/web/participant_view.rb +1 -1
  144. data/lib/samagotchi/web/peer_routes.rb +40 -15
  145. data/lib/samagotchi/web/public/agent_rows.js +206 -0
  146. data/lib/samagotchi/web/public/agent_runs.js +595 -0
  147. data/lib/samagotchi/web/public/answer_fold.js +41 -44
  148. data/lib/samagotchi/web/public/app.js +4 -4
  149. data/lib/samagotchi/web/public/block_fix.js +1 -1
  150. data/lib/samagotchi/web/public/card.js +26 -10
  151. data/lib/samagotchi/web/public/cards_place.js +6 -4
  152. data/lib/samagotchi/web/public/context_chips.js +24 -2
  153. data/lib/samagotchi/web/public/copy.js +8 -2
  154. data/lib/samagotchi/web/public/data.js +2 -1
  155. data/lib/samagotchi/web/public/format.js +9 -1
  156. data/lib/samagotchi/web/public/history_reveal.js +5 -2
  157. data/lib/samagotchi/web/public/index.html +56 -2
  158. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  159. data/lib/samagotchi/web/public/model_pick.js +18 -5
  160. data/lib/samagotchi/web/public/model_picker.js +1 -1
  161. data/lib/samagotchi/web/public/page_view.js +1 -1
  162. data/lib/samagotchi/web/public/pages.css +1 -7
  163. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  164. data/lib/samagotchi/web/public/peer_data.js +4 -2
  165. data/lib/samagotchi/web/public/peer_mailbox_api.js +2 -1
  166. data/lib/samagotchi/web/public/peer_note.js +4 -2
  167. data/lib/samagotchi/web/public/peer_row.js +37 -0
  168. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  169. data/lib/samagotchi/web/public/quiet_notes.js +12 -1
  170. data/lib/samagotchi/web/public/revise_stack.js +5 -2
  171. data/lib/samagotchi/web/public/send_turn.js +11 -3
  172. data/lib/samagotchi/web/public/served_ref.js +9 -0
  173. data/lib/samagotchi/web/public/session_fields.js +1 -0
  174. data/lib/samagotchi/web/public/session_state.js +4 -0
  175. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  176. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  177. data/lib/samagotchi/web/public/turn_block.js +4 -0
  178. data/lib/samagotchi/web/public/version_notices.js +7 -1
  179. data/lib/samagotchi/web/session_control.rb +19 -10
  180. data/lib/samagotchi/web/session_show.rb +20 -0
  181. data/lib/samagotchi/web/update_ops.rb +2 -2
  182. data/lib/samagotchi/worker/command_queue.rb +3 -0
  183. data/lib/samagotchi/worker/mail.rb +24 -1
  184. data/lib/samagotchi/worker.rb +8 -5
  185. data/lib/samagotchi/worker_inbound/mail.rb +34 -6
  186. data/lib/samagotchi/worker_inbound.rb +11 -3
  187. data/lib/samagotchi/worker_link.rb +13 -1
  188. data/lib/samagotchi/worker_wakes.rb +33 -5
  189. metadata +22 -2
  190. data/lib/samagotchi/web/public/pages_group.js +0 -67
@@ -31,13 +31,16 @@ module Samagotchi
31
31
  # credential printers, git config writes (reads only), home sweeps
32
32
  # and links to them, and a program named by a $var or a glob); a
33
33
  # write or edit of git's hooks (GIT_HOOKS);
34
- # - owner-voiced tools (OWNER_VOICED, and any delegate_* tool): what
35
- # speaks or acts in the owner's name beyond this turn (a delegate, a
36
- # reminder, a note to another session, a background task, a
37
- # forgotten output, the session's loaded tools, a move on the owner's
38
- # objectives); the tools that read
39
- # the owner's background tasks (OWNER_TASK_READERS); and memory_write:
40
- # a memory reaches the owner's later sessions;
34
+ # - owner-voiced tools (TOOL_CLASSES' :owner_voiced, and any delegate_*
35
+ # tool): what speaks or acts in the owner's name beyond this turn (a
36
+ # delegate, a reminder, a schedule, a note to another session, a
37
+ # background task, a forgotten output, the session's loaded tools, a
38
+ # move on the owner's objectives); the tools that read the owner's
39
+ # background tasks (:owner_tasks); the readers of the owner's other
40
+ # sessions, reminders and schedules and of the session's attached
41
+ # context (:owner_reader: list_sessions, list_reminders,
42
+ # list_schedules, context_read); and memory_write: a memory reaches
43
+ # the owner's later sessions;
41
44
  # - ask_user_question: there is no one on the participant's side to
42
45
  # answer it here; the model asks in its reply instead.
43
46
  # And it asks the owner, always (Verdict#fresh_ask: no stored approval
@@ -51,14 +54,36 @@ module Samagotchi
51
54
  class PairBoundary
52
55
  RULE = "pair-boundary"
53
56
  SOURCE = "core"
54
- OWNER_VOICED = %w[delegate register_reminder cancel_reminder send_note ask_session forget_outputs task_create task_stop
55
- find_tools objectives schedule_task list_schedules cancel_schedule].freeze
57
+ # Every built-in tool (ToolNames::NAMES, spec/guardrails/pair_boundary_spec.rb
58
+ # fails on one missing here) and find_tools (Tools::ToolIndex::FIND_NAME)
59
+ # by what a participant's turn may do with it:
60
+ # :owner_voiced denied (OWNER_ONLY): it speaks or acts in the owner's name beyond this turn
61
+ # :owner_tasks denied (OWNER_TASKS): it reads the owner's background tasks (a pair turn
62
+ # starts none: task_create is owner-voiced, and its execute is never handed over)
63
+ # :owner_reader denied (OWNER_READS): it reads the owner's other sessions, reminders,
64
+ # schedules or the session's attached context
65
+ # :memory_write denied (MEMORY_WRITE)
66
+ # :ask denied (ASK)
67
+ # :checked goes on to the path and command checks below
68
+ # A name not here (a plugin's or an MCP server's tool) goes on to them
69
+ # too, but a delegate_* one (OWNER_VOICED_PREFIX). call_tool isn't
70
+ # here: ToolIndex#unwrap renames call_tool(chi/list_sessions) to
71
+ # list_sessions before the guardrails see it.
72
+ TOOL_CLASSES = {
73
+ "execute" => :checked, "read" => :checked, "write" => :checked, "edit" => :checked,
74
+ "memory_read" => :checked, "web_fetch" => :checked,
75
+ "memory_write" => :memory_write,
76
+ "ask_user_question" => :ask,
77
+ "task_wait" => :owner_tasks, "task_get" => :owner_tasks, "task_list" => :owner_tasks,
78
+ "list_sessions" => :owner_reader, "list_reminders" => :owner_reader, "list_schedules" => :owner_reader,
79
+ "context_read" => :owner_reader,
80
+ "delegate" => :owner_voiced, "delegate_result" => :owner_voiced, "register_reminder" => :owner_voiced,
81
+ "cancel_reminder" => :owner_voiced, "send_note" => :owner_voiced, "ask_session" => :owner_voiced,
82
+ "forget_outputs" => :owner_voiced, "task_create" => :owner_voiced, "task_stop" => :owner_voiced,
83
+ "find_tools" => :owner_voiced, "objectives" => :owner_voiced, "schedule_task" => :owner_voiced,
84
+ "cancel_schedule" => :owner_voiced
85
+ }.freeze
56
86
  OWNER_VOICED_PREFIX = "delegate_"
57
- # The background task tools that read the owner's tasks (a pair turn
58
- # starts none: task_create is owner-voiced, and its execute is never
59
- # handed over).
60
- OWNER_TASK_READERS = %w[task_wait task_get task_list].freeze
61
- ASK_TOOL = "ask_user_question"
62
87
  WRITE_TOOLS = %w[write edit].freeze
63
88
 
64
89
  ADVICE = "This is a participant's turn: work with this session's other tools, and say in your reply what " \
@@ -69,6 +94,12 @@ module Samagotchi
69
94
  MEMORY_WRITE = "a participant's turn writes no memories: they reach the owner's later sessions; say in your " \
70
95
  "reply what to remember"
71
96
  ASK = "a participant's turn can't ask the user: ask in your reply"
97
+ OWNER_READS = "a participant's turn can't use %s: the owner's other sessions, reminders, schedules and " \
98
+ "attached context are the owner's to read"
99
+ # A denied kind of TOOL_CLASSES → its refusal (one with %s names the
100
+ # tool).
101
+ KIND_TEXTS = { owner_voiced: OWNER_ONLY, owner_tasks: OWNER_TASKS, owner_reader: OWNER_READS,
102
+ memory_write: MEMORY_WRITE, ask: ASK }.freeze
72
103
  OUTSIDE_WRITE = "a participant's turn writes outside the session's project"
73
104
  NO_PROJECT = "a participant's turn writes, and this session's folder is the home folder or above it (or none): " \
74
105
  "there is no project to keep it in"
@@ -185,10 +216,10 @@ module Samagotchi
185
216
  def refusal(verdict)
186
217
  call = verdict.call || {}
187
218
  tool = call[:name].to_s
188
- return ASK if tool == ASK_TOOL
189
- return format(OWNER_ONLY, tool) if OWNER_VOICED.include?(tool) || tool.start_with?(OWNER_VOICED_PREFIX)
190
- return format(OWNER_TASKS, tool) if OWNER_TASK_READERS.include?(tool)
191
- return MEMORY_WRITE if tool == "memory_write"
219
+ kind = TOOL_CLASSES.fetch(tool) { :owner_voiced if tool.start_with?(OWNER_VOICED_PREFIX) }
220
+ if (text = KIND_TEXTS[kind])
221
+ return text.include?("%s") ? format(text, tool) : text
222
+ end
192
223
 
193
224
  targets = verdict.targets
194
225
  return nil unless targets
@@ -27,11 +27,13 @@ module Samagotchi
27
27
  # call is about to open: event[:refs] attaches refs to the asking
28
28
  # reply (QuestionAsked)
29
29
  # :after_tool_call — after tool execution, before result injection
30
+ # :peer_wait_ended — between turns: a /<peer> pair wait ran out with no peer
31
+ # (PeerWaitExpiry): {peer:, session_id:, minutes:}
30
32
  module Hooks
31
33
  # Every event a hook can be registered for, in a turn's order
32
34
  # (docs/hooks.md). Plugin::Api#on takes any symbol: `chi bundle check`
33
35
  # warns on one not here.
34
36
  EVENTS = %i[session_start before_turn before_generation generation_progress after_generation before_tool_call
35
- question_asked after_tool_call after_turn session_end].freeze
37
+ question_asked after_tool_call after_turn session_end peer_wait_ended].freeze
36
38
  end
37
39
  end
@@ -6,6 +6,8 @@ require_relative "log"
6
6
  require_relative "model_ref"
7
7
  require_relative "client"
8
8
  require_relative "model_list_store"
9
+ require_relative "served_lookup"
10
+ require_relative "served_ref"
9
11
  require_relative "llm/adapters"
10
12
  require_relative "llm/dialect"
11
13
 
@@ -216,6 +218,9 @@ module Samagotchi
216
218
  @cache = nil
217
219
  @cache_at = nil
218
220
  @model_index = nil # downcased model_id => [host_name] in hosts: order
221
+ # What each host serves now, for a `served` ref (ServedLookup).
222
+ @served = ServedLookup.new(lister: ->(entry, **opts) { probe_models(entry, **opts) }, adapter: ->(entry) { listing_adapter(entry) },
223
+ env: env, clock: @clock)
219
224
  end
220
225
 
221
226
  attr_reader :entries
@@ -245,10 +250,14 @@ module Samagotchi
245
250
  # Thinking, SamplingSettings, VisionSupport and ModelProfile all take these.
246
251
  # @param target [ModelTarget, nil] the resolved model's target (resolved when not given)
247
252
  # @return [Array<String>]
253
+ # A served ref's own names (`served`, `main:served`) are left out: the
254
+ # resolved id (the target's bare model) is what its models: entry is
255
+ # under. An alias of main:served stays (its entry applies to any model).
248
256
  def lookup_names(typed, resolved: nil, target: nil)
249
257
  target ||= resolve(resolved || typed)
250
258
  [typed, model_ref(typed).ref, resolved, parse_qualified_model(typed).last, target.bare_model]
251
- .map { |name| name.to_s.strip }.reject(&:empty?).uniq
259
+ .map { |name| name.to_s.strip }.reject(&:empty?)
260
+ .reject { |name| ServedRef.literal?(name, hosts: @entries) }.uniq
252
261
  end
253
262
 
254
263
  # The host a model name, alias or host:model ref goes to and the model
@@ -260,8 +269,14 @@ module Samagotchi
260
269
  # process's listing: a worker spawned with --model never lists) has
261
270
  # it, the same way; else the default host (no discovery here, the
262
271
  # latency budget). Never by a substring.
263
- def host_for_model(raw_model)
272
+ #
273
+ # A served ref (ServedRef: main:served; a bare one is the default
274
+ # host's) goes to its host with +served_id+ when given (a turn's pin),
275
+ # else the id ServedLookup#cached knows, else the word itself: never a
276
+ # request, never a raise.
277
+ def host_for_model(raw_model, served_id: nil)
264
278
  ref = model_ref(raw_model)
279
+ return served_target(ref, served_id) if ServedRef.served?(ref)
265
280
  # ModelRef names a host only when it is one of ours
266
281
  return [find_entry(ref.host_name), ref.id] if ref.host_name
267
282
 
@@ -299,14 +314,7 @@ module Samagotchi
299
314
  def list_models_for(entry)
300
315
  return adapter_for(entry).list_models if entry.chat? && !@client_override
301
316
 
302
- Array(client_for(entry).list_models).map do |raw|
303
- if raw.is_a?(Hash)
304
- id = raw["id"] || raw[:id] || raw["model"] || raw["name"]
305
- LLM::ModelInfo.new(id: id.to_s, context_window: nil, supports_tools: nil, raw: raw)
306
- else
307
- LLM::ModelInfo.new(id: raw.to_s, context_window: nil, supports_tools: nil, raw: {})
308
- end
309
- end
317
+ raw_infos(client_for(entry).list_models)
310
318
  end
311
319
 
312
320
  # List one host's models and save them to ModelListStore: what
@@ -338,11 +346,78 @@ module Samagotchi
338
346
  # the name sent to the server (host_for_model).
339
347
  # @param raw_model [String] a model name, alias or host:model ref
340
348
  # @return [ModelTarget]
341
- def resolve(raw_model)
342
- entry, bare = host_for_model(raw_model)
349
+ # @param served_id [String, nil] a served ref's id as the turn pinned it
350
+ # (ignored for any other ref)
351
+ def resolve(raw_model, served_id: nil)
352
+ entry, bare = host_for_model(raw_model, served_id: served_id)
343
353
  ModelTarget.new(model: raw_model, entry: entry, bare_model: bare, client: client_for(entry))
344
354
  end
345
355
 
356
+ # The host entry a served ref goes to: its own host, else the default
357
+ # one (a bare `served`, or +host+: a hosts: name a side setting gives).
358
+ # @return [HostEntry]
359
+ def served_entry(raw, host: nil)
360
+ ref = raw.is_a?(ModelRef) ? raw : model_ref(raw)
361
+ (ref.host_name && find_entry(ref.host_name)) || (host && find_entry(host)) || default_entry
362
+ end
363
+
364
+ # Whether +raw+ is a served ref (ServedRef.served?, the alias applied).
365
+ def served?(raw) = ServedRef.served?(model_ref(raw))
366
+
367
+ # A served ref's id with no request (ServedLookup#cached), nil when
368
+ # nothing is known or +raw+ isn't one.
369
+ # @return [String, nil]
370
+ def cached_served_id(raw, host: nil)
371
+ ref = model_ref(raw)
372
+ ServedRef.served?(ref) ? @served.cached(served_entry(ref, host: host)) : nil
373
+ end
374
+
375
+ # Lists a served ref's host unless it was listed less than +max_age+
376
+ # seconds ago (ServedLookup#refresh!; bounded, no retry).
377
+ # +timeout+ (seconds) caps the listing's timeouts (System 1's deadline);
378
+ # +cancel_controller+ cuts it (a judgment's Stop).
379
+ # @return [ServedLookup::Resolution, nil] nil when +raw+ isn't a served ref
380
+ def refresh_served!(raw, max_age: 0, host: nil, timeout: nil, cancel_controller: nil)
381
+ ref = model_ref(raw)
382
+ return nil unless ServedRef.served?(ref)
383
+
384
+ @served.refresh!(served_entry(ref, host: host), max_age: max_age, timeout: timeout, cancel_controller: cancel_controller)
385
+ end
386
+
387
+ # Why a served ref can't run, as this registry's last listing of its host
388
+ # said (none or several models; ServedLookup#cached_refusal), with no
389
+ # request; nil when it can, nothing was listed yet, or +raw+ isn't one.
390
+ # @return [String, nil]
391
+ def cached_served_refusal(raw, host: nil)
392
+ ref = model_ref(raw)
393
+ ServedRef.served?(ref) ? @served.cached_refusal(served_entry(ref, host: host)) : nil
394
+ end
395
+
396
+ # Forget a served ref's listing (the next turn's start lists again).
397
+ def invalidate_served!(raw, host: nil)
398
+ ref = model_ref(raw)
399
+ @served.invalidate!(served_entry(ref, host: host)) if ServedRef.served?(ref)
400
+ end
401
+
402
+ # The models +entry+'s host lists now, as one bounded request: a probe
403
+ # adapter (short timeouts, no retry, as SelfReport's) on a chat host, the
404
+ # Client's #list_models_probe on a native one. Never the turn adapter's
405
+ # list (its retries and turn timeouts). A Stop cuts it (the thread's
406
+ # Client.probe_cancel: a turn's controller). Raises on failure.
407
+ # +timeout+ (seconds) lowers the chat probe's timeouts; +cancel_controller+
408
+ # (a judgment's) cuts it instead of the thread's.
409
+ # @return [Array<LLM::ModelInfo>]
410
+ def probe_models(entry, timeout: nil, cancel_controller: nil)
411
+ if entry.chat? && !@client_override
412
+ return LLM::Adapters.for(entry, open_timeout: [Client::CONTEXT_WINDOW_PROBE_OPEN_TIMEOUT, timeout].compact.min,
413
+ timeout: [Client::CONTEXT_WINDOW_PROBE_READ_TIMEOUT, timeout].compact.min, retries: false,
414
+ env: @env).list_models(cancel_controller: cancel_controller || Client.probe_cancel)
415
+ end
416
+
417
+ client = client_for(entry)
418
+ raw_infos(client.respond_to?(:list_models_probe) ? client.list_models_probe : client.list_models)
419
+ end
420
+
346
421
  # What the alias +raw_model+ became, for an error that names only the
347
422
  # host ("splash is an alias: gemma-x on host main"), or nil when it
348
423
  # isn't an alias. An alias without a host of its own goes where a bare
@@ -356,10 +431,41 @@ module Samagotchi
356
431
  "#{ref.alias_name} is an alias: #{target.bare_model} on host #{target.entry.name}"
357
432
  end
358
433
 
359
- # The model id sent for +full_ref+: its alias applied, a known host
360
- # prefix stripped ("box:gemma" → "gemma").
361
- def bare_name(full_ref)
362
- model_ref(full_ref).id
434
+ # The model id a host is sent for +raw+ (and what readers that name the
435
+ # model compare or key by: the wire, the guardrails' models: rules, the
436
+ # memory overlay key, the served-model mismatch, a side target): its
437
+ # alias applied, a known host prefix stripped ("box:gemma" → "gemma").
438
+ # The one source of that id, read from the parsed ref only: no resolve,
439
+ # no model index or saved list, never a request, so it answers when a
440
+ # resolve breaks. Equal to resolve(raw).bare_model.
441
+ # @param raw [String] a model name, alias or host:model ref
442
+ # @return [String]
443
+ #
444
+ # A served ref's id is +served_id+ (a turn's pin) when given, else the
445
+ # one ServedLookup#cached knows (on its host, or +host+'s for a bare
446
+ # one), else the word `served`.
447
+ # @return [String]
448
+ def sent_model_id(raw, served_id: nil, host: nil)
449
+ ref = model_ref(raw)
450
+ return ref.id unless ServedRef.served?(ref)
451
+
452
+ served_id || @served.cached(served_entry(ref, host: host)) || ref.id
453
+ end
454
+ alias bare_name sent_model_id
455
+
456
+ # The ref a turn's generations are counted under (SessionMetrics'
457
+ # per-model segments, the switch check) for +raw+: the stored ref
458
+ # (ModelRef#ref), or for a served ref the host and the id it resolves to
459
+ # ("main:q8"; the stored ref while nothing is known). Like
460
+ # #sent_model_id, never resolving. See EffectiveModel#turn_ref, its value
461
+ # on a resolved model.
462
+ # @return [String]
463
+ def turn_ref(raw, served_id: nil)
464
+ ref = model_ref(raw)
465
+ return ref.ref unless ServedRef.served?(ref)
466
+
467
+ id = served_id || @served.cached(served_entry(ref))
468
+ id ? "#{served_entry(ref).name}:#{id}" : ref.ref
363
469
  end
364
470
 
365
471
  # +raw+ parsed against these hosts and config.yml's aliases.
@@ -475,6 +581,30 @@ module Samagotchi
475
581
  # that shows it names the host itself.
476
582
  def list_error(error) = error.is_a?(LLM::ProviderError) ? error.detail : error.message
477
583
 
584
+ # A raw server list (Client#list_models: the server's own shape) as ModelInfo.
585
+ def raw_infos(list)
586
+ Array(list).map do |raw|
587
+ if raw.is_a?(Hash)
588
+ id = raw["id"] || raw[:id] || raw["model"] || raw["name"]
589
+ LLM::ModelInfo.new(id: id.to_s, context_window: nil, supports_tools: nil, raw: raw)
590
+ else
591
+ LLM::ModelInfo.new(id: raw.to_s, context_window: nil, supports_tools: nil, raw: {})
592
+ end
593
+ end
594
+ end
595
+
596
+ # [entry, id] for a served +ref+ (#host_for_model).
597
+ def served_target(ref, served_id)
598
+ entry = served_entry(ref)
599
+ [entry, served_id || @served.cached(entry) || ref.id]
600
+ end
601
+
602
+ # A chat host's turn adapter, whose cached list the served lookup reads
603
+ # and primes; nil on a native host or under a client override.
604
+ def listing_adapter(entry)
605
+ entry.chat? && !@client_override ? adapter_for(entry) : nil
606
+ end
607
+
478
608
  # Save a host's just-listed models on disk, for the processes that spawn
479
609
  # a worker without listing (`chi send --new --model`, delegate):
480
610
  # ModelListStore is what they check an id against.
@@ -25,6 +25,15 @@ module Samagotchi
25
25
  # Raised when summarization fails (server down, timeout, malformed body…).
26
26
  class SummarizeError < StandardError; end
27
27
 
28
+ # Whether +error+ (a SummarizeError) is the host refusing the model as
29
+ # not served now (its cause's LLM::BadRequest#model_not_served?): the
30
+ # host swapped models, and a side ask on a served ref re-lists and asks
31
+ # once more.
32
+ def self.not_served?(error)
33
+ cause = error&.cause
34
+ cause.respond_to?(:model_not_served?) && cause.model_not_served? ? true : false
35
+ end
36
+
28
37
  # What #summarize and #ask return: the text and the model that
29
38
  # answered (the server's name for it; nil when the reply names none).
30
39
  # +top_logprobs+: the first token's alternatives (LLM::TokenLogprob)
@@ -53,19 +62,21 @@ module Samagotchi
53
62
  # summarize thread can't outlive the recap attempt by minutes.
54
63
  # @param purpose [String] what the requests are for, in the HTTP log
55
64
  # lines and error messages ("recap", "broadcast")
65
+ # @param label [String] names the requests in error messages ("block-fix
66
+ # request failed …": an Engine side request's kind); default: +purpose+
56
67
  # @param api [Symbol] the wire to talk (LLM::Adapters; IdleTarget#api)
57
68
  # @param auth [Symbol, nil] the header the key goes in (IdleTarget#auth)
58
69
  # @param dialect [String, nil] a Messages host's dialect (IdleTarget#dialect)
59
70
  # @param price [ModelPrice, nil] the model's price on its host
60
71
  # (IdleTarget#price), on each SideUsage the on_usage callbacks get
61
72
  def initialize(model:, base_url: nil, api_key_env: nil, timeout: DEFAULT_TIMEOUT_SECONDS, env: ENV, purpose: "recap",
62
- api: :openai, auth: nil, dialect: nil, price: nil)
73
+ label: purpose, api: :openai, auth: nil, dialect: nil, price: nil)
63
74
  @model = model
64
75
  @price = price
65
76
  # A recap is best-effort: one short attempt, no retries. The idle job
66
77
  # tries again after the next activity, never on its own. Only the
67
78
  # Messages adapter takes a dialect.
68
- @chat = LLM::Adapters.build(api: api, base_url: base_url.to_s, host_name: purpose, api_key_env: api_key_env,
79
+ @chat = LLM::Adapters.build(api: api, base_url: base_url.to_s, host_name: label, api_key_env: api_key_env,
69
80
  auth: auth, stream: false, retries: false, timeout: timeout, env: env, purpose: purpose,
70
81
  **(dialect ? { dialect: dialect } : {}))
71
82
  end
@@ -34,6 +34,8 @@ module Samagotchi
34
34
  DEFAULT_INACTIVITY_SECONDS = 180.0
35
35
  DEFAULT_TIMEOUT_SECONDS = 30.0
36
36
  DEFAULT_MIN_USER_TURNS = 2
37
+ # The least time left (seconds) a not-served retry is worth.
38
+ RETRY_MIN_SECONDS = 1
37
39
  # Above this many tool calls we ask only for a goal/achievement summary
38
40
  # (never enumerate calls).
39
41
  LARGE_TOOL_THRESHOLD = 10
@@ -314,6 +316,9 @@ module Samagotchi
314
316
  # string (Engine#messages_json_for_recap)
315
317
  # @param emit_recap [#call] (recap:, generation:, covered:, created_at:)
316
318
  # announces a written recap (Engine#emit_recap)
319
+ # @param retarget [#call, nil] → IdleTarget, called once when the host
320
+ # refuses the asked model as not served (IdleClient.not_served?): a
321
+ # target naming another model is asked once more
317
322
  def initialize(turn_state:, messages_json:, emit_recap:, model: nil, base_url: nil, api_key_env: nil, target: nil,
318
323
  inactivity: DEFAULT_INACTIVITY_SECONDS,
319
324
  min_user_turns: DEFAULT_MIN_USER_TURNS,
@@ -323,6 +328,7 @@ module Samagotchi
323
328
  store: nil,
324
329
  session_id: -> {},
325
330
  on_usage: nil,
331
+ retarget: nil,
326
332
  clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
327
333
  raise ArgumentError, "IdleRecap requires a turn state" unless turn_state
328
334
 
@@ -335,6 +341,9 @@ module Samagotchi
335
341
  # a dropped recap's too: it was billed (RecapSetup: the Engine's
336
342
  # side line).
337
343
  @on_usage = on_usage
344
+ # → a fresh target after the host refused the asked model as not
345
+ # served (RecapSetup: a served model listed again); nil: no retry.
346
+ @retarget = retarget
338
347
  @target = target || lambda {
339
348
  IdleTarget.new(base_url: base_url, api_key_env: api_key_env, model: model, label: model)
340
349
  }
@@ -500,7 +509,7 @@ module Samagotchi
500
509
  return :nothing_new if prompt.nil?
501
510
 
502
511
  asked = target
503
- @in_flight = { thread: spawn_summarize(client_for(asked), prompt), generation: gen, deadline: @clock.call + @timeout,
512
+ @in_flight = { thread: spawn_summarize(client_for(asked), prompt, asked), generation: gen, deadline: @clock.call + @timeout,
504
513
  covered: parsed.size, covered_digest: self.class.digest(parsed.last), model: asked.label,
505
514
  previous_title: previous&.dig(:title) }
506
515
  :started
@@ -600,9 +609,9 @@ module Samagotchi
600
609
  # any kind (a LoadError, a stack overflow too) ends it quietly, logged:
601
610
  # no recap this time, and no dead thread's trace on the worker's
602
611
  # stderr. A real exit or interrupt goes on as raised.
603
- def spawn_summarize(client, prompt)
612
+ def spawn_summarize(client, prompt, asked)
604
613
  Thread.new do
605
- client.summarize(prompt, session_id: @session_id.call, on_usage: @on_usage)
614
+ summarize(client, prompt, asked)
606
615
  rescue SystemExit, SignalException
607
616
  raise
608
617
  rescue Exception => e # rubocop:disable Lint/RescueException -- a recap's failure, whatever it is, is no recap
@@ -612,6 +621,27 @@ module Samagotchi
612
621
  end
613
622
  end
614
623
 
624
+ # One summarize, and once more on a retarget naming another model when
625
+ # the host refused +asked+'s as not served (it swapped models). On the
626
+ # summarize thread: the retry's client is its own (@client stays the
627
+ # scheduler thread's).
628
+ # The retry gets what is left of the timeout (the attempt's deadline).
629
+ def summarize(client, prompt, asked)
630
+ started = @clock.call
631
+ client.summarize(prompt, session_id: @session_id.call, on_usage: @on_usage)
632
+ rescue IdleClient::SummarizeError => e
633
+ raise unless @retarget && IdleClient.not_served?(e)
634
+
635
+ retried = @retarget.call
636
+ raise if retried.nil? || retried.model == asked.model
637
+
638
+ left = @timeout - (@clock.call - started)
639
+ raise if left < RETRY_MIN_SECONDS
640
+
641
+ Log.info(:recap, "recap_not_served", was: asked.model, now: retried.model)
642
+ (@client_override || IdleClient.for(retried, timeout: left)).summarize(prompt, session_id: @session_id.call, on_usage: @on_usage)
643
+ end
644
+
615
645
  def safe_value(worker)
616
646
  worker.value
617
647
  rescue StandardError
@@ -73,7 +73,7 @@ module Samagotchi
73
73
 
74
74
  label = model.to_s
75
75
  parsed = model && host_registry.model_ref(model)
76
- return of_model(host_registry, model) unless host_named?(model: model, host_ref: host_ref, base_url: base_url,
76
+ return of_model(host_registry, model) unless fixes_host?(model: model, host_ref: host_ref, base_url: base_url,
77
77
  host_registry: host_registry)
78
78
 
79
79
  host_ref ||= parsed.host_name if parsed && base_url.nil?
@@ -96,9 +96,10 @@ module Samagotchi
96
96
  raise self::Unresolved.new(:model_host_mismatch, model: model, host_ref: host_ref, named: named)
97
97
  end
98
98
 
99
- model = parsed.id if parsed
99
+ # A bare `served` is host_ref's own (ServedLookup on that host).
100
+ model = host_registry.sent_model_id(model, host: entry.name) if parsed
100
101
  elsif parsed && !parsed.host_name
101
- model = parsed.id
102
+ model = host_registry.sent_model_id(model)
102
103
  end
103
104
  raise self::Unresolved.new(:incomplete, model: model, host_ref: host_ref) if blank(base_url).nil? || blank(model).nil?
104
105
 
@@ -106,16 +107,35 @@ module Samagotchi
106
107
  dialect: dialect, price: entry && price_of(entry, model))
107
108
  end
108
109
 
109
- # Whether the settings fix a host (+base_url+, +host_ref+, or a model
110
- # ref naming one), so resolving them once holds; a model alone that
111
- # names none goes where a bare --model goes, which a host's model list
112
- # decides (resolve it at each request).
110
+ # Whether resolving the settings once holds: they fix a host
111
+ # (+base_url+, +host_ref+, or a model ref naming one) and the model isn't
112
+ # a served one (ServedRef: its id is whatever the host serves now, so it
113
+ # is resolved at each request, as a model alone that names no host is:
114
+ # that goes where a bare --model goes, which a host's model list decides).
113
115
  def self.host_named?(model:, host_ref:, base_url:, host_registry:)
116
+ return false if blank(base_url).nil? && served_model?(model, host_registry)
117
+
118
+ fixes_host?(model: model, host_ref: host_ref, base_url: base_url, host_registry: host_registry)
119
+ end
120
+
121
+ # Whether +model+ is a served ref (main:served, a bare served;
122
+ # HostRegistry#served?, so this file requires nothing: the testing kit
123
+ # loads it).
124
+ def self.served_model?(model, host_registry)
125
+ model = blank(model)
126
+ !model.nil? && host_registry.served?(model)
127
+ end
128
+
129
+ # Whether the settings fix a host (+base_url+, +host_ref+, or a model
130
+ # ref naming one): #resolve then goes by that host, else where a bare
131
+ # --model goes.
132
+ def self.fixes_host?(model:, host_ref:, base_url:, host_registry:)
114
133
  return true if blank(base_url) || blank(host_ref)
115
134
 
116
135
  model = blank(model)
117
136
  !model.nil? && !host_registry.model_ref(model).host_name.nil?
118
137
  end
138
+ private_class_method :fixes_host?
119
139
 
120
140
  def self.blank(value)
121
141
  text = value.to_s.strip
@@ -25,16 +25,27 @@ module Samagotchi
25
25
  end
26
26
  end
27
27
 
28
- # Every line that reads as a Hash, oldest first; none with no file.
28
+ # Every line that reads as a Hash, oldest first; none with no file, or
29
+ # one that can't be read.
29
30
  # @return [Array<Hash>]
30
31
  def lines(session_dir)
32
+ lines!(session_dir)
33
+ rescue SystemCallError
34
+ []
35
+ end
36
+
37
+ # #lines, but a file that is there and can't be read raises: for a
38
+ # reader that must tell "nothing logged" from "can't tell".
39
+ # @return [Array<Hash>]
40
+ # @raise [SystemCallError] anything but a missing file
41
+ def lines!(session_dir)
31
42
  File.readlines(File.join(session_dir, file), chomp: true).filter_map do |raw|
32
43
  line = JSON.parse(raw)
33
44
  line if line.is_a?(Hash)
34
45
  rescue JSON::ParserError
35
46
  nil
36
47
  end
37
- rescue SystemCallError
48
+ rescue Errno::ENOENT, Errno::ENOTDIR
38
49
  []
39
50
  end
40
51
 
@@ -49,14 +49,16 @@ module Samagotchi
49
49
  # Every page of the host's model list (MAX_MODEL_PAGES at most): the
50
50
  # block gives a page's URI for the last page's last_id (nil first).
51
51
  # @return [Array<ModelInfo>]
52
- def list_model_pages(headers: {})
52
+ # @param cancel_controller [CancellationController, nil] a Stop cuts the listing
53
+ def list_model_pages(headers: {}, cancel_controller: nil)
53
54
  models = []
54
55
  after = nil
55
56
  MAX_MODEL_PAGES.times do
56
57
  uri = yield(after)
57
58
  request = Net::HTTP::Get.new(uri)
58
59
  headers.each { |name, value| request[name] = value }
59
- body = parse_json(@http.fetch(uri, request, log_fields: { purpose: "models" }).body, "model list")
60
+ body = parse_json(@http.fetch(uri, request, cancel_controller: cancel_controller, log_fields: { purpose: "models" }).body,
61
+ "model list")
60
62
  models.concat(model_entries(body).map { |raw| model_info(raw) })
61
63
  break unless body.is_a?(Hash) && body["has_more"] && body["last_id"]
62
64
 
@@ -228,13 +228,25 @@ module Samagotchi
228
228
  # Whether +model+ gets the budget form (it refused adaptive thinking).
229
229
  def budget_form?(model) = @refusals.refused?(:thinking_form, model.to_s)
230
230
 
231
+ # Whether this client's chat requests for +model+ count as carrying a
232
+ # remote host's prompt-cache breakpoints, so its cache has a TTL
233
+ # (cache.ttl; the peer mail's cold hold): a Claude model on a remote
234
+ # host whose dialect sends them (#request_body's cache) and didn't
235
+ # refuse them. A local Messages server (no remote TTL) and a
236
+ # non-Claude model don't.
237
+ def cache_breakpoints?(model)
238
+ @remote && @purpose == "chat" && PromptCache.claude?(model) && @dialect.cache_breakpoints &&
239
+ !@refusals.refused?(:cache_control)
240
+ end
241
+
231
242
  # The host's models, every page: GET {base}/v1/models with
232
243
  # limit=1000 and after_id paging (has_more/last_id). Anthropic's shape
233
244
  # (max_input_tokens, max_tokens, capabilities) and the OpenAI shape a
234
245
  # gateway or Splash serves here are both read (ModelListing).
235
246
  # @return [Array<ModelInfo>]
236
- def list_models
237
- list_model_pages(headers: { "anthropic-version" => API_VERSION }) do |after|
247
+ # @param cancel_controller [CancellationController, nil] a Stop cuts it
248
+ def list_models(cancel_controller: nil)
249
+ list_model_pages(headers: { "anthropic-version" => API_VERSION }, cancel_controller: cancel_controller) do |after|
238
250
  URI("#{@base_url}/v1/models?#{URI.encode_www_form({ limit: 1000, after_id: after }.compact)}")
239
251
  end
240
252
  end