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
@@ -1,14 +1,17 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../config"
4
+ require_relative "../degrade"
4
5
  require_relative "../effective_model"
5
6
  require_relative "../failure_line"
6
7
  require_relative "../llm/backend"
7
8
  require_relative "../llm/errors"
9
+ require_relative "../llm/prompt_cache"
8
10
  require_relative "../log"
9
11
  require_relative "../model_notes"
10
12
  require_relative "../model_profile"
11
13
  require_relative "../prompt_note"
14
+ require_relative "../served_lookup"
12
15
  require_relative "../system_prompt"
13
16
 
14
17
  module Samagotchi
@@ -16,7 +19,8 @@ module Samagotchi
16
19
  # The model: its names and refs, identity and notes, /model's switch (and
17
20
  # the context it shows after), the profile (ModelBinding's, forwarded) and
18
21
  # the loop it runs on. Writes @client, @default_model_name,
19
- # @last_context_status, @chat_backend; reads @model_binding, @host_registry,
22
+ # @last_context_status, @chat_backend, @served_start_choice, @served_failure;
23
+ # reads @model_binding, @host_registry,
20
24
  # @kernel, @metrics, @prompt_builder.
21
25
  module ModelsPart
22
26
  # The backend for the next turn: the loop the effective model's host speaks.
@@ -36,6 +40,12 @@ module Samagotchi
36
40
  model_ref_for(effective_model_name)
37
41
  end
38
42
 
43
+ # The id a served model (main:served) runs on now (EffectiveModel#served_id:
44
+ # the turn's pin, else the host's last listing; no request), nil for
45
+ # any other model, while nothing is known, or when it doesn't resolve.
46
+ # A :command_ran's model_served.
47
+ def served_model_id = @model_settings.model_setting(nil, &:served_id)
48
+
39
49
  # The effective model as the system prompt names it (SystemPrompt::ModelIdentity):
40
50
  # the ref, its host, the overlay key and, for a local llama.cpp host
41
51
  # only, the model its /props names when that differs. Never a new
@@ -44,8 +54,9 @@ module Samagotchi
44
54
  model = effective_model
45
55
  entry = model.entry
46
56
  host = entry && "host #{entry.name}, #{entry.url || "#{entry.host}:#{entry.port}"}"
47
- SystemPrompt::ModelIdentity.new(ref: model.ref, host: host, key: @model_binding.model_key,
48
- served: model.prompt_served, fallback_key: @model_binding.fallback_model_key)
57
+ SystemPrompt::ModelIdentity.new(ref: model.turn_ref, host: host, key: @model_binding.model_key,
58
+ served: model.prompt_served, fallback_key: @model_binding.fallback_model_key,
59
+ served_ref: model.served_ref? ? model.ref : nil)
49
60
  end
50
61
 
51
62
  # The model notes for the effective model (ModelNotes): matched on its
@@ -101,12 +112,84 @@ module Samagotchi
101
112
  summary = FailureLine.for(error)
102
113
  return summary unless error.is_a?(LLM::ProviderError) && error.host
103
114
 
115
+ served = served_failure_line(error)
116
+ return served if served
117
+
104
118
  note = @host_registry.alias_note(effective_model_name)
105
- note && note.end_with?("on host #{error.host}") ? "#{summary} (#{note})" : summary
119
+ summary = "#{summary} (#{note})" if note&.end_with?("on host #{error.host}")
120
+ "#{summary}#{explicit_served_hint(error)}"
106
121
  rescue StandardError => e
107
122
  EffectiveModel::Unresolved.fallback(:alias_note_failed, effective_model_name, e, summary)
108
123
  end
109
124
 
125
+ # A served model's turn the host refused as not served
126
+ # (BadRequest#model_not_served?: it swapped models mid-turn): one forced
127
+ # re-list names what it serves now, and the next turn's start follows
128
+ # it. nil for any other failure or model.
129
+ # @return [String, nil]
130
+ # Kept for its error: the turn's note and its end event (and the
131
+ # one-shot's line) ask for the same failure, and one re-list answers.
132
+ def served_failure_line(error)
133
+ return nil unless error.is_a?(LLM::BadRequest) && error.model_not_served?
134
+
135
+ kept_error, kept_line = @served_failure
136
+ return kept_line if kept_error.equal?(error)
137
+
138
+ line = served_failure_text
139
+ @served_failure = [error, line]
140
+ line
141
+ rescue StandardError => e
142
+ EffectiveModel::Unresolved.fallback(:served_failure_line_failed, effective_model_name, e, nil)
143
+ end
144
+ private :served_failure_line
145
+
146
+ def served_failure_text
147
+ name = effective_model_name
148
+ return nil unless @host_registry.served?(name)
149
+
150
+ was = @model_binding.served_id
151
+ now = @host_registry.refresh_served!(name, max_age: 0)
152
+ host = @host_registry.served_entry(name).name
153
+ line = "host #{host} no longer serves #{was || ServedRef::WORD}"
154
+ return "#{line} (it serves #{now.id} now): send again to continue on #{now.id}" if now&.id && now.id != was
155
+
156
+ "#{line}: #{now&.refusal || "send again once it serves a model"}"
157
+ end
158
+ private :served_failure_text
159
+
160
+ # An explicit id's turn the host refused as not served
161
+ # (BadRequest#model_not_served?): when the host lists one other model
162
+ # now, "; host main serves Y now: /model main:served follows it".
163
+ # Nothing switches. One bounded listing (an explicit session lists
164
+ # nothing at its turns, so a cached or saved id could be stale), kept
165
+ # per error as #served_failure_line is. "" for anything else.
166
+ # @return [String]
167
+ def explicit_served_hint(error)
168
+ return "" unless error.is_a?(LLM::BadRequest) && error.model_not_served?
169
+
170
+ kept_error, kept_hint = @served_hint
171
+ return kept_hint if kept_error.equal?(error)
172
+
173
+ hint = explicit_served_hint_text(error)
174
+ @served_hint = [error, hint]
175
+ hint
176
+ end
177
+ private :explicit_served_hint
178
+
179
+ def explicit_served_hint_text(error)
180
+ name = effective_model_name
181
+ entry = @host_registry.find_entry(error.host.to_s)
182
+ return "" if entry.nil? || @host_registry.served?(name)
183
+
184
+ # A failed listing's id is an older one (the saved list): no hint.
185
+ listed = @host_registry.refresh_served!(ServedRef::WORD, max_age: 30, host: entry.name)
186
+ now = listed&.id
187
+ return "" if listed.nil? || listed.error || now.nil? || now == bare_model_name(name)
188
+
189
+ "; host #{entry.name} serves #{now} now: /model #{entry.name}:served follows it"
190
+ end
191
+ private :explicit_served_hint_text
192
+
110
193
  # +name+'s resolved ref (ModelRef#ref).
111
194
  def model_ref_for(name)
112
195
  @host_registry.model_ref(name).ref
@@ -145,9 +228,12 @@ module Samagotchi
145
228
  # @return [ModelProfile::Resolution]
146
229
  def profile_resolution = @model_binding.profile_resolution
147
230
 
148
- # The model id sent for +full_ref+ (its alias applied, the host prefix off).
231
+ # The model id sent for +full_ref+ (its alias applied, the host prefix
232
+ # off): HostRegistry#sent_model_id, never resolving.
149
233
  def bare_model_name(full_ref)
150
- @host_registry.bare_name(full_ref)
234
+ # The effective model's own served pin: the id the turn runs on.
235
+ served_id = full_ref == effective_model_name ? @model_binding.served_id : nil
236
+ @host_registry.sent_model_id(full_ref, served_id: served_id)
151
237
  end
152
238
 
153
239
  # The memory overlay keys follow the model sent (ModelBinding#sync_model_key!).
@@ -181,6 +267,8 @@ module Samagotchi
181
267
  resolved = ModelProfile.check_host!(ModelProfile.required_model_name(model_name), hosts: @host_registry.entries)
182
268
  choice = ModelChoice.new(name: resolved, typed: typed.to_s.strip.empty? ? model_name : typed.to_s.strip)
183
269
  @model_binding.switch!(choice)
270
+ # A served ref keys with the id known now; the next turn start compares with it.
271
+ @model_binding.pin_served!(@host_registry.cached_served_id(resolved))
184
272
  sync_model_key!
185
273
  @prompt_builder.reset!
186
274
  # The notes the new model's prompt loads at its next build, so /model,
@@ -201,6 +289,87 @@ module Samagotchi
201
289
  ref
202
290
  end
203
291
 
292
+ # A turn's start on a served model (main:served): the host listed now
293
+ # (HostRegistry#refresh_served!, max_age 0: one bounded GET), and a
294
+ # change since the id the session keyed with works as a /model nobody
295
+ # typed (#follow_served!). Run before :turn_started, so its cut_after is
296
+ # the new model's; the caller calls the answer after the emit, where
297
+ # it raises an image error.
298
+ # @return [#call] raises what the turn fails with, else sends the
299
+ # notice of a change (if any)
300
+ def served_turn_start
301
+ notice = follow_served!
302
+ # The choice this start listed and pinned for (#generate_model).
303
+ @served_start_choice = @model_binding.choice
304
+ -> { hook_notify(notice, :info, "model") if notice }
305
+ rescue StandardError => e
306
+ -> { raise e }
307
+ end
308
+ private :served_turn_start
309
+
310
+ # Lists a served model's host and follows a change: a refusal (it
311
+ # lists none or several) raises ServedLookup::Refused, a failed listing
312
+ # with nothing known raises its error (today's host-down line); a
313
+ # failed listing with an id known keeps it (the request then fails or
314
+ # retries on today's path). A change pins the new id (ModelBinding#follow!:
315
+ # a --profile stays) and resets what /model resets, without writing
316
+ # the session's model or config.yml.
317
+ # @return [String, nil] the notice "host main now serves Y (was X)",
318
+ # nil without a change or when nothing was known before
319
+ def follow_served!
320
+ name = effective_model_name
321
+ now = @host_registry.refresh_served!(name, max_age: 0)
322
+ return nil unless now
323
+ raise ServedLookup::Refused, now.refusal if now.refusal
324
+ # A Stop cut the listing: the turn's stop checks end it.
325
+ return nil if now.error.is_a?(LLM::RequestCancelled)
326
+ raise served_listing_error(name, now.error) if now.id.nil? && now.error
327
+
328
+ was = @model_binding.served_id
329
+ return nil if now.id.nil? || now.id == was
330
+
331
+ @model_binding.follow!(now.id)
332
+ sync_model_key!
333
+ @prompt_builder.reset!
334
+ record_prompt_notes(model_notes) if @session
335
+ record_prompt_parts([])
336
+ sync_kernel_client!
337
+ @client.invalidate_context_window!
338
+ @metrics.forget_model_reports!
339
+ @last_context_status = nil
340
+ announce_switched_context!
341
+ Log.info(:model, "served_changed", host: @host_registry.served_entry(name).name, id: now.id, was: was)
342
+ was && "host #{@host_registry.served_entry(name).name} now serves #{now.id} (was #{was})"
343
+ end
344
+ private :follow_served!
345
+
346
+ # What a turn-start listing that failed with nothing known raises: a
347
+ # provider error as it is (its own line: can't reach host …),
348
+ # anything else (a native host's "model listing failed") as a refusal
349
+ # naming the host, never a chi error.
350
+ def served_listing_error(name, error)
351
+ return error if error.is_a?(LLM::ProviderError)
352
+
353
+ ServedLookup::Refused.new("host #{@host_registry.served_entry(name).name} couldn't list its models: " \
354
+ "#{error.message.to_s[0, 200]}")
355
+ end
356
+ private :served_listing_error
357
+
358
+ # The model generate sends with (#effective_model). A served model
359
+ # this turn's start didn't list for (a hook switched to main:served
360
+ # after it: its pin came from a cache, maybe a week-old saved list) is
361
+ # listed first (max_age 30) and pinned, so generate's reads agree.
362
+ # @return [EffectiveModel]
363
+ def generate_model
364
+ name = effective_model_name
365
+ if !@model_binding.choice.equal?(@served_start_choice) && @host_registry.served?(name)
366
+ @model_binding.pin_served!(@host_registry.refresh_served!(name, max_age: 30)&.id)
367
+ sync_model_key!
368
+ end
369
+ effective_model
370
+ end
371
+ private :generate_model
372
+
204
373
  # After /model: how full the context is on the new model's window,
205
374
  # before its first turn: the last turn's count (the old model's
206
375
  # tokenizer's, replaced at the next generation) against the new model's
@@ -241,13 +410,34 @@ module Samagotchi
241
410
  # the effective model; false before any (or when the ref can't be told).
242
411
  def model_switched_since_last_turn?
243
412
  last = @metrics.last_model_ref
244
- !last.nil? && last != effective_model_ref
413
+ name = effective_model_name
414
+ # A served model nothing is known of yet: not switched (an unknown ref's answer).
415
+ return false if @host_registry.served?(name) && @model_binding.served_id.nil? && @host_registry.cached_served_id(name).nil?
416
+
417
+ # The ref generations are counted under (#generation_model_ref), read
418
+ # without a resolve: session= calls this, and it must hold on a broken one.
419
+ !last.nil? && last != @host_registry.turn_ref(name, served_id: @model_binding.served_id)
245
420
  rescue StandardError => e
246
421
  Log.warn(:model, "switch_check_failed", error: e.class.name, msg: e.message.to_s[0, 200])
247
422
  false
248
423
  end
249
424
  private :model_switched_since_last_turn?
250
425
 
426
+ # How long the effective model's host keeps this session's prompt
427
+ # cache, in seconds (cache.ttl: PromptCache.ttl_seconds), when its chat
428
+ # requests carry breakpoints (its chat host's adapter's
429
+ # cache_breakpoints?); nil when they carry none: a local model, a host
430
+ # that sends none, no model. The peer mail's cold hold reads it
431
+ # (WorkerInbound::MailPart).
432
+ # @return [Integer, nil]
433
+ def remote_cache_ttl
434
+ Degrade.call(:model, "remote_cache_ttl_unknown") do
435
+ model = effective_model
436
+ adapter = model.chat? ? @host_registry.adapter_for(model.entry) : nil
437
+ LLM::PromptCache.ttl_seconds if adapter.respond_to?(:cache_breakpoints?) && adapter.cache_breakpoints?(model.bare)
438
+ end
439
+ end
440
+
251
441
  private
252
442
 
253
443
  # Pick the loop for +model+ (EffectiveModel); the chat loop is pointed
@@ -3,6 +3,7 @@
3
3
  require_relative "../answer_display"
4
4
  require_relative "../bundle_settings_check"
5
5
  require_relative "../cache_confirm"
6
+ require_relative "../client_id"
6
7
  require_relative "../log"
7
8
  require_relative "../plugin/context"
8
9
  require_relative "../plugin/loader"
@@ -186,6 +187,7 @@ module Samagotchi
186
187
  cost: -> { @metrics.cost },
187
188
  usage: -> { @metrics.usage },
188
189
  turn_author: -> { turn_author },
190
+ turn_interactive: -> { ClientId.interactive?(turn_context&.origin&.client_id) },
189
191
  # A plugin's prompt section is in the stable part: a full re-read.
190
192
  cache_confirm: ->(line, changed) { CacheConfirm.ask(line: line, cost: :full, changed: changed, engine: self) },
191
193
  candidate_proposed: ->(_candidate) { judge_late_candidates },
@@ -6,6 +6,7 @@ require_relative "../idle_target"
6
6
  require_relative "../log"
7
7
  require_relative "../objectives_check"
8
8
  require_relative "../objectives_track"
9
+ require_relative "../served_ref"
9
10
  require_relative "../session"
10
11
  require_relative "../system_one/recorder"
11
12
  require_relative "../system_one/runs"
@@ -18,6 +19,11 @@ module Samagotchi
18
19
  # @side_client_mutex); reads @metrics, @session, @host_registry.
19
20
  # The recorder (SystemOne::Recorder) is the turn stages' recording seam.
20
21
  module SideRequestsPart
22
+ # How old a served listing a side ask may go by (seconds).
23
+ SIDE_SERVED_MAX_AGE = 30
24
+ # The least time left (seconds) a side ask's not-served retry is worth.
25
+ SIDE_RETRY_MIN_SECONDS = 1
26
+
21
27
  # Count one side request (a recap, a plugin's ctx.ask_model: IdleClient's
22
28
  # on_usage) in the session's side line, apart from its turns' totals.
23
29
  # Folded and announced as :side_usage under the event lock, so the side
@@ -105,18 +111,65 @@ module Samagotchi
105
111
  # (#note_side_usage) under +source+, the asking bundle's name.
106
112
  # @param whole [Boolean] return the IdleClient::Summary (its cut_off)
107
113
  # @return [String, IdleClient::Summary] the answer
114
+ #
115
+ # A served model (ServedRef: the session's, or +model+) is listed first
116
+ # when the last listing is SIDE_SERVED_MAX_AGE old; a host that refuses
117
+ # it as not served (it swapped models) is re-listed and asked once
118
+ # more when the listing names another id. Any other model is asked as
119
+ # it is, once.
120
+ # @raise [IdleClient::SummarizeError] the request failed, or a served
121
+ # host lists none or several models
108
122
  def ask_side_model(request, timeout:, max_tokens:, cancel_controller:, model: nil, source: nil, whole: false)
109
- target = model.nil? ? session_model_recap_target : configured_side_target(model)
110
- client = side_model_client(target, timeout)
123
+ target = side_target(model, max_age: SIDE_SERVED_MAX_AGE)
124
+ kind = source.to_s.empty? ? "ask" : source.to_s
111
125
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
112
- answer = client.ask(request, max_tokens: max_tokens, cancel_controller: cancel_controller, session_id: @session&.id,
113
- kind: source.to_s.empty? ? "ask" : source.to_s, on_usage: method(:note_side_usage))
126
+ ask = lambda do |asked, limit|
127
+ side_model_client(asked, limit, kind).ask(request, max_tokens: max_tokens, cancel_controller: cancel_controller,
128
+ session_id: @session&.id, kind: kind, on_usage: method(:note_side_usage))
129
+ end
130
+ answer = begin
131
+ ask.call(target, timeout)
132
+ rescue IdleClient::SummarizeError => e
133
+ raise unless IdleClient.not_served?(e) && (retried = side_target(model, max_age: 0)).model != target.model
134
+
135
+ # The retry gets what is left of +timeout+, not a second one.
136
+ left = timeout.to_f - (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started)
137
+ raise if left < SIDE_RETRY_MIN_SECONDS
138
+
139
+ Log.info(:plugins, "ask_model_not_served", model: target.label, was: target.model, now: retried.model)
140
+ ask.call(target = retried, left)
141
+ end
114
142
  Log.info(:plugins, "ask_model", model: target.label, answer_model: answer.model, chars: answer.text.length,
115
143
  ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round)
116
144
  whole ? answer : answer.text
117
145
  end
118
146
  private :ask_side_model
119
147
 
148
+ # A side ask's target: the session's model (+model+ nil) or +model+, a
149
+ # served one listed unless that is less than +max_age+ old.
150
+ def side_target(model, max_age:)
151
+ return session_model_recap_target(max_age: max_age) if model.nil?
152
+
153
+ side_served!(model, max_age)
154
+ configured_side_target(model)
155
+ end
156
+ private :side_target
157
+
158
+ # Lists +name+'s host when it is a served ref (HostRegistry#refresh_served!).
159
+ # @raise [IdleClient::SummarizeError] the host lists none or several
160
+ # models (the word `served` is never sent)
161
+ # +max_age+ nil: no listing, the last one's refusal only (the recap's
162
+ # attempt, on the idle scheduler's thread).
163
+ def side_served!(name, max_age)
164
+ refusal = if max_age.nil?
165
+ @host_registry.cached_served_refusal(name)
166
+ else
167
+ @host_registry.refresh_served!(name, max_age: max_age)&.refusal
168
+ end
169
+ raise IdleClient::SummarizeError, refusal if refusal
170
+ end
171
+ private :side_served!
172
+
120
173
  # The target of ctx.ask_model(model:): +model+ as a turn resolves it,
121
174
  # once it is known to name something configured. IdleTarget.of_model
122
175
  # never raises (an unknown host falls to the default host, an unknown id
@@ -125,7 +178,7 @@ module Samagotchi
125
178
  # host's model (cached, declared or saved lists; nothing is asked)
126
179
  def configured_side_target(model)
127
180
  ref = @host_registry.model_ref(model)
128
- unless ref.host_name || ref.alias_name || @host_registry.hosts_with_model(ref.id).any?
181
+ unless ref.host_name || ref.alias_name || ServedRef.served?(ref) || @host_registry.hosts_with_model(ref.id).any?
129
182
  raise ArgumentError, "ask_model: unknown model #{model.to_s.inspect} (use a configured host:id, an alias, " \
130
183
  "or a model id one of your hosts lists)"
131
184
  end
@@ -134,13 +187,14 @@ module Samagotchi
134
187
  end
135
188
  private :configured_side_target
136
189
 
137
- # The IdleClient for +target+ at +timeout+: the last one when both are
138
- # the same, else a new one.
139
- def side_model_client(target, timeout)
190
+ # The IdleClient for +target+ at +timeout+, its errors naming +kind+
191
+ # ("block-fix request failed …"; its HTTP log lines stay the recap's
192
+ # purpose): the last one when all three are the same, else a new one.
193
+ def side_model_client(target, timeout, kind)
140
194
  @side_client_mutex.synchronize do
141
- key = [target, timeout]
195
+ key = [target, timeout, kind]
142
196
  unless @side_client && @side_client_key == key
143
- @side_client = IdleClient.for(target, timeout: timeout)
197
+ @side_client = IdleClient.for(target, timeout: timeout, label: kind)
144
198
  @side_client_key = key
145
199
  end
146
200
  @side_client
@@ -150,10 +204,15 @@ module Samagotchi
150
204
 
151
205
  # The session's current model as a recap target: its host's OpenAI API
152
206
  # (native llama.cpp hosts serve /v1/chat/completions too), key variable
153
- # and bare model name, as a turn resolves them.
207
+ # and bare model name, as a turn resolves them. A served model's host is
208
+ # listed when its last listing is +max_age+ old (a recap after a swap
209
+ # between turns asks the new id).
154
210
  # @return [IdleTarget]
155
- def session_model_recap_target
156
- IdleTarget.of_model(@host_registry, effective_model_name)
211
+ # @raise [IdleClient::SummarizeError] a served host lists none or several
212
+ def session_model_recap_target(max_age: SIDE_SERVED_MAX_AGE)
213
+ name = effective_model_name
214
+ side_served!(name, max_age)
215
+ IdleTarget.of_model(@host_registry, name)
157
216
  end
158
217
  end
159
218
  end
@@ -69,7 +69,7 @@ module Samagotchi
69
69
  host = backend(model)
70
70
  staged = @tool_loads.take
71
71
  added = ToolLoads.added(turn.messages)
72
- unless host.respond_to?(:tool_changes?) && host.tool_changes?(bare_model_name(model.name))
72
+ unless host.respond_to?(:tool_changes?) && host.tool_changes?(model.bare)
73
73
  Log.info(:plugins, "tool_loads_not_sent", tools: staged.values.flatten.join(","), model: model.name.to_s)
74
74
  return
75
75
  end
@@ -64,7 +64,7 @@ module Samagotchi
64
64
  # SessionMetrics keys its per-model segments on it. nil when it can't be
65
65
  # named (the turn's record then has none).
66
66
  def generation_model_ref(model)
67
- model.ref
67
+ model.turn_ref
68
68
  rescue StandardError => e
69
69
  Log.warn(:turn, "model_ref_failed", error: e.class.name, msg: e.message.to_s[0, 200])
70
70
  nil
@@ -261,7 +261,7 @@ module Samagotchi
261
261
  # The session's settings on its effective model (SessionModelSettings),
262
262
  # read at use: /model moves the choice, #session= the session.
263
263
  @model_settings = SessionModelSettings.new(registry: @host_registry, choice: -> { @model_binding.choice },
264
- session: -> { @session })
264
+ session: -> { @session }, served_id: ->(choice) { @model_binding.served_id_for(choice) })
265
265
  # An injected client (specs) stands in for every host's client.
266
266
  @host_registry.client_override = client if client
267
267
  @client = effective_model.client
@@ -590,7 +590,7 @@ module Samagotchi
590
590
 
591
591
  # The turn endings' builders (see #initialize for when).
592
592
  def build_turn_endings
593
- TurnEndings.new(failure_summary: ->(error) { failure_summary(error) })
593
+ TurnEndings.new(failure_summary: ->(error) { failure_summary(error) }, served_line: ->(error) { served_failure_line(error) })
594
594
  end
595
595
  private :build_turn_endings
596
596
 
@@ -831,7 +831,7 @@ module Samagotchi
831
831
  recap = RecapSetup.build(@recap_kwarg, turn_state: @turn_state, messages_json: -> { messages_json_for_recap },
832
832
  emit_recap: ->(**fields) { emit_recap(**fields) },
833
833
  on_usage: ->(usage) { note_side_usage(usage) }, host_registry: @host_registry,
834
- session_target: -> { session_model_recap_target },
834
+ session_target: ->(**opts) { session_model_recap_target(**opts) },
835
835
  session_id: -> { @session&.id }, state_dir: -> { session_state_dir },
836
836
  session_config: -> { @session&.settings&.core })
837
837
  recap.awaiting_continue = @recap_awaiting_continue if recap && @recap_awaiting_continue
@@ -1102,6 +1102,7 @@ module Samagotchi
1102
1102
  image_refs, image_error = turn_image_refs(session, images)
1103
1103
  # Emit turn_started event
1104
1104
  bind_metrics(session)
1105
+ served_started = served_turn_start # a served model's host listed, a change followed: cut_after is the new model's
1105
1106
  turn_started = { type: :turn_started, session_id: session.id, prompt: turn.prompt, turn_id: turn.id, at: turn.at }
1106
1107
  turn_started[:continue] = true if turn.continue
1107
1108
  turn_started[:resumed] = true if turn.resumed?
@@ -1114,6 +1115,8 @@ module Samagotchi
1114
1115
  emit_event(turn.on_event, turn.tag(turn_started))
1115
1116
  raise image_error if image_error
1116
1117
 
1118
+ served_started.call
1119
+
1117
1120
  # On mode's ask starts here too; the turn joins it before
1118
1121
  # apply_toolkit! below, so its latency hides behind the probes and
1119
1122
  # the init wait.
@@ -1234,12 +1237,12 @@ module Samagotchi
1234
1237
  # Ask the effective model's backend.
1235
1238
  def generate(turn, max_iterations:, max_tool_output_chars:, pending_input:)
1236
1239
  # One resolve for the request: nothing runs between these reads that
1237
- # could change what a resolve gives (the hooks ran before).
1238
- model = effective_model
1240
+ # could change what a resolve gives (the hooks ran before; a served model is pinned first).
1241
+ model = generate_model
1239
1242
  sync_kernel_client!(model)
1240
- # Route model name as bare (without host prefix) to the server;
1241
- # host selection already done via active client.
1242
- bare_for_backend = bare_model_name(model.name)
1243
+ # The id the host is sent (HostRegistry#sent_model_id's, from this
1244
+ # resolve); host selection already done via active client.
1245
+ bare_for_backend = model.bare
1243
1246
  # The turn's settings, set once here into its context (with the model
1244
1247
  # key and name the gate and memory_read use: frozen now, after the
1245
1248
  # hooks that may switch the model), which goes down the backend's
@@ -79,6 +79,9 @@ module Samagotchi
79
79
  **setting_chips(SessionSetting::STATS, model),
80
80
  prompt_notes: prompt_notes.map(&:to_h), prompt_files: prompt_builder.prompt_files,
81
81
  price_host: model.host_name)
82
+ # A served model: its ref and the id it runs on now (/stats' model line).
83
+ served_id = served_id_of(model)
84
+ snapshot = snapshot.merge(served_ref: model.ref, model_served: served_id) if served_id
82
85
  kit_prompt = kit_prompt_stats
83
86
  snapshot = snapshot.merge(kit_prompt: kit_prompt) if kit_prompt
84
87
  # The plugins' prompt sections the built prompt holds ({bundle:, name:}).
@@ -133,6 +136,8 @@ module Samagotchi
133
136
  # without the probe)
134
137
  # :served_expected_by [String, nil] the host whose models: entry names
135
138
  # that served model under served: (#served_expected_by)
139
+ # :model_served [String, nil] the id a served model (main:served) runs
140
+ # on now (EffectiveModel#served_id), nil for any other model
136
141
  # :recap_enabled [Boolean] whether an idle recap is configured, with
137
142
  # :recap_min_user_turns and :recap_inactivity_seconds (nil when not)
138
143
  # :participants [Array<Hash>] who is in the review now ({id:, name:,
@@ -162,6 +167,7 @@ module Samagotchi
162
167
  served_model: served_pair[0],
163
168
  served_model_for: served_pair[1],
164
169
  served_expected_by: model&.served_expected_by(served_pair[0]),
170
+ model_served: served_id_of(model),
165
171
  context_status: last_context_status&.dup || saved_context_status(metrics[:context], model: model),
166
172
  **setting_chips(SessionSetting::ALL, model),
167
173
  recap_enabled: !recap.nil?,
@@ -173,13 +179,14 @@ module Samagotchi
173
179
 
174
180
  # See Engine#served_model. A report for another name (before a /model switch)
175
181
  # doesn't count. Without a model (EffectiveModel), no probe. A remote
176
- # chat host has no /props: nil until a turn. The name asked is never
177
- # resolved (HostRegistry#bare_name), so it holds on a broken resolve.
182
+ # chat host has no /props: nil until a turn. The name asked is the id
183
+ # sent: the model's own (EffectiveModel#bare) when given, else never
184
+ # resolved (HostRegistry#sent_model_id), so it holds on a broken resolve.
178
185
  # Only bare_model_name and the snapshot lookup are left to fail here:
179
186
  # the probe's failure is EffectiveModel#served_from_props's.
180
187
  def served_model_for(snapshot, model: nil)
181
188
  Degrade.call(:model, "served_model_unreadable", fallback: [nil, nil]) do
182
- asked = bare_model_name(model ? model.name : effective_model_name)
189
+ asked = model ? model.bare : bare_model_name(effective_model_name)
183
190
  return [snapshot[:served_model], asked] if snapshot[:served_model] && snapshot[:served_model_for] == asked
184
191
  return [nil, nil] unless model
185
192
 
@@ -187,6 +194,12 @@ module Samagotchi
187
194
  end
188
195
  end
189
196
 
197
+ # +model+'s served id (EffectiveModel#served_id), nil for none or when
198
+ # +model+ is nil or can't say (never raises: the session state).
199
+ def served_id_of(model)
200
+ Degrade.call(:model, "served_id_unreadable") { model&.served_id }
201
+ end
202
+
190
203
  # The next turn's kit prompt text for /stats: its kit and its estimated
191
204
  # tokens (chars / 4), nil when its toolkit has none.
192
205
  def kit_prompt_stats
@@ -56,6 +56,7 @@ module Samagotchi
56
56
  merged_input: :row,
57
57
  objectives_updated: :state,
58
58
  participants_changed: :state,
59
+ peer_wait_ended: :internal,
59
60
  pending_input_merged: :row,
60
61
  plugin_init_finished: :state,
61
62
  plugin_init_started: :state,