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
@@ -21,17 +21,21 @@ module Samagotchi
21
21
  # @param registry [HostRegistry] the Engine's (never replaced)
22
22
  # @param choice [#call] → the ModelChoice turns run on now (/model moves it)
23
23
  # @param session [#call] → the Engine's Session, nil before one
24
- def initialize(registry:, choice:, session:)
24
+ # @param served_id [#call] (choice) → the id a served choice is pinned to
25
+ # (ModelBinding#served_id_for), nil for none
26
+ def initialize(registry:, choice:, session:, served_id: ->(_choice) {})
25
27
  @registry = registry
26
28
  @choice = choice
27
29
  @session = session
30
+ @served_id = served_id
28
31
  end
29
32
 
30
33
  # The effective model now (EffectiveModel.of): resolved on each call,
31
34
  # never kept (config.yml, a model listing and another process's saved
32
- # lists all move a resolve). Raises as HostRegistry#resolve does.
35
+ # lists all move a resolve), a served choice on the id its turn pinned.
36
+ # Raises as HostRegistry#resolve does.
33
37
  # @return [EffectiveModel]
34
- def effective_model(choice = @choice.call) = EffectiveModel.of(@registry, choice)
38
+ def effective_model(choice = @choice.call) = EffectiveModel.of(@registry, choice, served_id: @served_id.call(choice))
35
39
 
36
40
  # The block's answer for the effective model, or +fallback+ when the
37
41
  # model doesn't resolve: the readers whose rescue always covered the
@@ -2,8 +2,11 @@
2
2
 
3
3
  module Samagotchi
4
4
  # The files that hold state for a session, including stores outside its
5
- # sidecar directory. `corpus_dir` is relative to the compatibility corpus.
6
- # A `file` ending in "/" is a folder of files (PeerMailbox's in/).
5
+ # sidecar directory. `corpus_dir` is relative to the compatibility corpus;
6
+ # STATE is its root, the state dir beside `sessions/`, where the stores
7
+ # that keep every session's lines sit (SystemOne::RunsStore's
8
+ # system_one/runs/, ContextCandidatesLog's file).
9
+ # A `file` ending in "/" is a folder of files (PeerMailbox's in/, the runs).
7
10
  # A Symbol in `continue` names the carry step; a String explains why it stays.
8
11
  module SessionStores
9
12
  Store = Data.define(:file, :owner, :removal, :cross_version, :continue, :corpus_dir, :corpus_exception) do
@@ -19,11 +22,12 @@ module Samagotchi
19
22
  SIDE_CAR = "sessions/compat-session"
20
23
  CONTEXT = "context/sessions/compat-session"
21
24
  MAILBOX = "mailbox/compat-session/claude"
22
- # A continue leaves the mailbox with the previous link (the peer pairs
23
- # again with the next one, owner 2026-11-24); its :peers step only reads
24
- # it, for the one note.
25
- MAILBOX_STAYS = "the mailbox stays with the previous link (its unread messages reach the next one as one note, " \
26
- "SessionContinue :peers); a say there is refused with the next id"
25
+ STATE = "."
26
+ # A continue leaves the messages with the previous link: its :peers
27
+ # step only reads them, for the one note. The pairing (link.json) is
28
+ # carried: copied to the new link, so a say follows the chain.
29
+ MAILBOX_STAYS = "the messages stay with the previous link (its unread ones reach the next one as one note, " \
30
+ "SessionContinue :peers); a say there goes to the chain's live link"
27
31
 
28
32
  STORES = [
29
33
  Store.new(file: "archived", owner: "ArchiveStore", removal: :session_files, cross_version: true,
@@ -38,10 +42,10 @@ module Samagotchi
38
42
  continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
39
43
  Store.new(file: "participant_prompts.json", owner: "ParticipantPrompts", removal: :session_files, cross_version: true,
40
44
  continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
41
- Store.new(file: "judgments.jsonl", owner: "SystemOne::RunsStore", removal: :system_one_runs, cross_version: false,
42
- continue: "saved judgments belong to the previous link", corpus_dir: nil),
45
+ Store.new(file: "runs/", owner: "SystemOne::RunsStore", removal: :system_one_runs, cross_version: true,
46
+ continue: "saved judgments belong to the previous link", corpus_dir: "system_one"),
43
47
  Store.new(file: "context_candidates.jsonl", owner: "ContextCandidatesLog", removal: :context_candidates_log,
44
- cross_version: false, continue: "candidate records belong to the previous link", corpus_dir: nil),
48
+ cross_version: true, continue: "candidate records belong to the previous link", corpus_dir: STATE),
45
49
  Store.new(file: "bridge.json", owner: "WorkerSidecar", removal: :session_files, cross_version: true,
46
50
  continue: "the bridge endpoint belongs to the old worker", corpus_dir: SIDE_CAR),
47
51
  Store.new(file: "cards.json", owner: "Bridge::CardStore", removal: :session_files, cross_version: true,
@@ -68,12 +72,22 @@ module Samagotchi
68
72
  continue: "exchanges stay with the previous link; the new pairing starts empty", corpus_dir: nil,
69
73
  corpus_exception: "older readers do not read peer exchange metadata"),
70
74
  # A peer's side of the session (PeerMailbox): <state>/mailbox/<id>/<peer>/.
75
+ # The pairing is copied to the new link (SessionContinue :peers).
71
76
  Store.new(file: "link.json", owner: "PeerMailbox", removal: :peer_mailbox, cross_version: true,
72
- continue: MAILBOX_STAYS, corpus_dir: MAILBOX),
77
+ continue: :peers, corpus_dir: MAILBOX),
73
78
  Store.new(file: "in/", owner: "PeerMailbox", removal: :peer_mailbox, cross_version: true,
74
79
  continue: MAILBOX_STAYS, corpus_dir: MAILBOX),
75
80
  Store.new(file: "lock", owner: "PeerMailbox", removal: :peer_mailbox, cross_version: false,
76
81
  continue: "a lock is not session data", corpus_dir: nil),
82
+ # Who is here and who waits (PeerPresence): <state>/mailbox/.here/<peer>/.
83
+ # A wait follows a continue (SessionContinue :peers); a pairing's file
84
+ # names the link that paired.
85
+ Store.new(file: "waiting/<id>.json", owner: "PeerPresence", removal: :peer_presence, cross_version: false,
86
+ continue: :peers, corpus_dir: nil,
87
+ corpus_exception: "a 10-minute mark, outside the session's folder: no older reader"),
88
+ Store.new(file: "paired/<peer session>/<id>", owner: "PeerPresence", removal: :peer_presence, cross_version: false,
89
+ continue: "a pairing's file names the link that paired; a resume pairs through the chain's live link",
90
+ corpus_dir: nil, corpus_exception: "an empty file outside the session's folder: no older reader"),
77
91
  # What the worker did with each peer message (PeerReceipts).
78
92
  Store.new(file: "peer_receipts.json", owner: "PeerReceipts", removal: :session_files, cross_version: true,
79
93
  continue: MAILBOX_STAYS, corpus_dir: SIDE_CAR),
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require_relative "agent_caller"
4
5
  require_relative "session"
5
6
  require_relative "session_row"
6
7
  require_relative "session_manager"
@@ -86,8 +87,9 @@ module Samagotchi
86
87
  # @param access [SessionAccess::Local, nil] where the sessions are;
87
88
  # default this machine's (delete, archive and unarchive build their
88
89
  # own unless one is given)
89
- def initialize(argv, stdout: $stdout, stderr: $stderr, access: nil)
90
+ def initialize(argv, stdout: $stdout, stderr: $stderr, access: nil, env: ENV)
90
91
  @argv = argv.dup
92
+ @env = env
91
93
  @stdout = stdout
92
94
  @stderr = stderr
93
95
  @given_access = access
@@ -316,17 +318,23 @@ module Samagotchi
316
318
  def restart(ids)
317
319
  return usage_error("give session ids") if ids.empty?
318
320
 
321
+ # Who asked (AgentCaller, as chi send tells): a person's restart starts a
322
+ # stopped session again; an agent's is refused, its next step to ask its user.
323
+ agent = !AgentCaller.send_name(as: nil, env: @env).first.nil?
319
324
  ok = ids.uniq.map do |given|
320
325
  begin
321
326
  id = @access.resolve_id(given)
322
- result = @access.restart(id)
327
+ result = @access.restart(id, start_stopped: !agent)
323
328
  rescue Samagotchi::SessionManager::OwnedByTUI => e
324
329
  @stdout.flush
325
330
  @stderr.puts e.message
326
331
  next false
327
332
  rescue Samagotchi::SessionManager::RestartRefused => e
328
333
  @stdout.flush
329
- @stderr.puts %i[not_running unsupported fallback_held stopped stop_marked deleting failed].include?(e.reason) ? e.message : "session #{id}: #{e.message}"
334
+ # The next step by who asked.
335
+ words = e.words_for(agent: agent, via: @access.invocation)
336
+ named = %i[not_running unsupported fallback_held stopped stop_marked still_stopping deleting failed].include?(e.reason)
337
+ @stderr.puts named ? words : "session #{id}: #{words}"
330
338
  next false
331
339
  rescue ArgumentError => e
332
340
  @stdout.flush
@@ -340,6 +348,11 @@ module Samagotchi
340
348
  end
341
349
 
342
350
  def restarted_line(result)
351
+ if result.was_stopped
352
+ return "Starting session #{result.session_id} again; its worker is still starting." unless result.version
353
+
354
+ return "Started session #{result.session_id} again on chi #{result.version}."
355
+ end
343
356
  return "Restarting session #{result.session_id}; its new worker is still starting." unless result.version
344
357
 
345
358
  from = result.from_version && result.from_version != result.version ? " (was #{result.from_version})" : ""
@@ -4,7 +4,9 @@ require "json"
4
4
  require "uri"
5
5
  require_relative "../config"
6
6
  require_relative "../llm/api_key"
7
+ require_relative "../llm/errors"
7
8
  require_relative "../llm/http"
9
+ require_relative "../log"
8
10
  require_relative "answer"
9
11
  require_relative "question"
10
12
  require_relative "errors"
@@ -19,8 +21,41 @@ module Samagotchi
19
21
  # Works for Splash (a local `api: openai` host serving /v1/systemone)
20
22
  # and for the hosted Jev API the same way; a host whose api isn't
21
23
  # openai is refused.
24
+ #
25
+ # `system_one.model: served` (ServedRef's bare word) judges with the one
26
+ # model system_one.host lists now: #target reads the registry's lookup
27
+ # (no request), #ask lists at most every SERVED_MAX_AGE seconds within
28
+ # its deadline, and a 422 "not served" (the host swapped models) is
29
+ # asked again once with the id a re-list names, while RETRY_MIN_MS of
30
+ # the deadline is left. Any other model is sent as written, never
31
+ # retried.
22
32
  class HttpBackend
23
33
  DEFAULT_TIMEOUT_MS = 2000
34
+ # ServedRef::WORD, as ConfigFile has it (served_ref.rb isn't loaded
35
+ # here: the testing kit loads this file and counts its requires).
36
+ SERVED = ConfigFile::SERVED_WORD
37
+ # How old a `served` listing may be before an ask lists again.
38
+ SERVED_MAX_AGE = 30
39
+ # The least time left (ms) a not-served retry is still worth.
40
+ RETRY_MIN_MS = 300
41
+
42
+ # host => the served id System 1 last asked with, in this process: a
43
+ # change logs system_one_model_changed once (the clean record stays
44
+ # model-blind; the log says when the judge changed).
45
+ @served_seen = {}
46
+ @served_seen_mutex = Mutex.new
47
+
48
+ # Records +id+ as +host+'s served judge; logs when it changed.
49
+ def self.note_served(host, id)
50
+ was = @served_seen_mutex.synchronize { @served_seen.fetch(host, nil).tap { @served_seen[host] = id } }
51
+ return if was.nil? || was == id
52
+
53
+ Samagotchi::Log.warn(:guardrails, "system_one_model_changed", host: host, was: was, now: id,
54
+ echo: "[samagotchi:guardrails] system one: host #{host} now serves #{id} (was #{was})")
55
+ end
56
+
57
+ # Forget what note_served saw (specs).
58
+ def self.reset_served_seen! = @served_seen_mutex.synchronize { @served_seen.clear }
24
59
 
25
60
  # @param host_registry [HostRegistry] where the host is looked up
26
61
  # @param host [String] the hosts: entry name
@@ -37,7 +72,9 @@ module Samagotchi
37
72
  end
38
73
 
39
74
  # @param observer [#call, nil] told (**facts) the model it resolved,
40
- # before the request, then what the response said beside the parsed
75
+ # before the request (again with the retried id after a not-served
76
+ # 422: the last one told is the one that answered), then what the
77
+ # response said beside the parsed
41
78
  # answers: served_model:, raw: (each answer as sent, score legends
42
79
  # and all) and usage: (Splash's input_tokens, output_tokens)
43
80
  # @return [Hash{String => Answer}] one Answer per question, nil for a
@@ -47,20 +84,33 @@ module Samagotchi
47
84
  # @raise [BackendError] the request failed, the status isn't 200, or
48
85
  # the body isn't a usable response
49
86
  def ask(state:, questions:, cancel_controller: nil, observer: nil)
87
+ started = now
50
88
  entry, model = target
89
+ model = served_model(started, cancel_controller) if served?
51
90
  observer&.call(model: model)
52
91
  url = "#{entry.openai_base_url.to_s.chomp("/")}/systemone"
53
92
  questions = SystemOne.normalize_questions(questions)
54
- body = { model: model, state: state, questions: questions.to_h { |question| [question.id, question.to_wire] } }
55
- request = json_post(url, body)
56
- response = http(entry).fetch(URI(url), request, retries: false, check_status: false, cancel_controller: cancel_controller,
57
- log_fields: { purpose: "system_one", model: model })
93
+ wire = questions.to_h { |question| [question.id, question.to_wire] }
94
+ post = lambda do |asked|
95
+ http(entry, remaining(started)).fetch(URI(url), json_post(url, { model: asked, state: state, questions: wire }),
96
+ retries: false, check_status: false, cancel_controller: cancel_controller,
97
+ log_fields: { purpose: "system_one", model: asked })
98
+ end
99
+ response = post.call(model)
58
100
 
59
101
  status = response.code.to_i
102
+ if (retried = not_served_retry(status, response.body, model, started, cancel_controller))
103
+ model = retried
104
+ observer&.call(model: model)
105
+ response = post.call(model)
106
+ status = response.code.to_i
107
+ end
60
108
  unless status == 200
61
109
  raise BackendError, "#{@host}: #{status} #{error_detail(response.body)}"
62
110
  end
63
111
 
112
+ self.class.note_served(@host, model) if served?
113
+
64
114
  data = reply_of(response.body)
65
115
  answers = data["answers"]
66
116
  observer&.call(served_model: data["model"], raw: answers, usage: data["usage"])
@@ -84,12 +134,64 @@ module Samagotchi
84
134
 
85
135
  model = @model || host_model(entry)
86
136
  raise UnsupportedHost, "host #{@host} names no model for System One" if model.nil? || model.empty?
137
+ return [entry, model] unless served?
87
138
 
88
- [entry, model]
139
+ refusal = @host_registry.cached_served_refusal(SERVED, host: @host)
140
+ raise UnsupportedHost, refusal if refusal
141
+
142
+ # Nothing known yet: the word, and the ask lists.
143
+ [entry, @host_registry.cached_served_id(SERVED, host: @host) || model]
89
144
  end
90
145
 
91
146
  private
92
147
 
148
+ # Whether the model is ServedRef's word (`served`, any case).
149
+ def served? = !@model.nil? && @model.casecmp?(SERVED)
150
+
151
+ # The id the host serves now, listed when the lookup's is older than
152
+ # SERVED_MAX_AGE, within what is left of the deadline.
153
+ # @raise [UnsupportedHost] it lists none or several models
154
+ # @raise [BackendError] the listing failed and no id is known
155
+ # A run whose listing failed or was refused records `served` as its
156
+ # model (the configured value; nothing was asked).
157
+ def served_model(started, cancel_controller)
158
+ resolution = @host_registry.refresh_served!(SERVED, max_age: SERVED_MAX_AGE, host: @host,
159
+ timeout: remaining(started), cancel_controller: cancel_controller)
160
+ raise UnsupportedHost, resolution.refusal if resolution.refusal
161
+ return resolution.id if resolution.id
162
+
163
+ raise BackendError, "#{@host}: couldn't list its models (#{resolution.error&.message.to_s[0, 200]})"
164
+ end
165
+
166
+ # The id to ask again with after a 422 "not served"
167
+ # (LLM::ProviderErrors::NOT_SERVED_RE) for a served model: a forced
168
+ # re-list's, when it names another single id and RETRY_MIN_MS of the
169
+ # deadline is left; else nil (the 422 stands).
170
+ def not_served_retry(status, body, model, started, cancel_controller)
171
+ return nil unless served? && status == 422 && LLM::ProviderErrors::NOT_SERVED_RE.match?(error_detail(body))
172
+
173
+ now_id = nil
174
+ if time_left?(started)
175
+ now_id = @host_registry.refresh_served!(SERVED, max_age: 0, host: @host, timeout: remaining(started),
176
+ cancel_controller: cancel_controller)&.id
177
+ end
178
+ retry_id = now_id if now_id && now_id != model && time_left?(started)
179
+ Samagotchi::Log.info(:guardrails, "system_one_not_served", host: @host, model: model, now: now_id, retried: !retry_id.nil?)
180
+ retry_id
181
+ end
182
+
183
+ # Whether RETRY_MIN_MS of the deadline is left.
184
+ def time_left?(started) = remaining(started) * 1000 >= RETRY_MIN_MS
185
+
186
+ # The ask's whole limit, in seconds.
187
+ def limit_seconds = (@timeout_ms.positive? ? @timeout_ms : DEFAULT_TIMEOUT_MS) / 1000.0
188
+
189
+ # Seconds left of the ask's limit, measured from +started+ (never
190
+ # below a millisecond: a request still gets a timeout).
191
+ def remaining(started) = [limit_seconds - (now - started), 0.001].max
192
+
193
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
194
+
93
195
  # The host's first model: whatever hosts.<name>.models holds, in the
94
196
  # shape the registry has it in (HostModel by id, or as written).
95
197
  def host_model(entry)
@@ -100,10 +202,9 @@ module Samagotchi
100
202
  first.respond_to?(:id) ? first.id : first.to_s
101
203
  end
102
204
 
103
- # One attempt, closed on the timeout: a judgment is worth at most
104
- # timeout_ms, not a retry chain.
105
- def http(entry)
106
- seconds = @timeout_ms.positive? ? @timeout_ms / 1000.0 : DEFAULT_TIMEOUT_MS / 1000.0
205
+ # One attempt, closed on +seconds+ (what is left of timeout_ms): a
206
+ # judgment is worth at most timeout_ms, not a retry chain.
207
+ def http(entry, seconds)
107
208
  open_timeout = [seconds, Config.positive_seconds("server.open_timeout")].min
108
209
  LLM::HTTP.new(label: entry.name, open_timeout: open_timeout, read_timeout: seconds,
109
210
  retry_policy: LLM::HTTP::RetryPolicy.none,
@@ -119,8 +119,11 @@ module Samagotchi
119
119
  end
120
120
 
121
121
  # @param store [#append, #version, nil] nil: nothing is saved
122
- def initialize(store: nil)
122
+ # @param clock [#call] the time a line is stamped with (its "at", which
123
+ # names its day file)
124
+ def initialize(store: nil, clock: -> { Time.now })
123
125
  @store = store
126
+ @clock = clock
124
127
  end
125
128
 
126
129
  def on? = !@store.nil?
@@ -178,7 +181,7 @@ module Samagotchi
178
181
  false
179
182
  end
180
183
 
181
- def now = Time.now.utc.iso8601(3)
184
+ def now = @clock.call.utc.iso8601(3)
182
185
  end
183
186
  end
184
187
  end
@@ -44,8 +44,11 @@ module Samagotchi
44
44
  # what a llama.cpp server says it serves when that differs (else nil).
45
45
  # fallback_key: the key an alias typed for the model used to key overlays
46
46
  # by (read when +key+ has none, as memory_read does); not shown.
47
- ModelIdentity = Data.define(:ref, :host, :key, :served, :fallback_key) do
48
- def initialize(ref:, host:, key:, served: nil, fallback_key: nil) = super
47
+ # served_ref: the session's ref when it is a served one (main:served:
48
+ # whatever the host serves now), +ref+ then the host and the id it
49
+ # resolved to; else nil.
50
+ ModelIdentity = Data.define(:ref, :host, :key, :served, :fallback_key, :served_ref) do
51
+ def initialize(ref:, host:, key:, served: nil, fallback_key: nil, served_ref: nil) = super
49
52
  end
50
53
 
51
54
  # Always auto-loaded from the system scope unless muted (B-light).
@@ -929,12 +932,16 @@ module Samagotchi
929
932
  model = @model_lookup.call
930
933
  return nil unless model && !model.ref.to_s.empty?
931
934
 
932
- details = [model.host, model.key && "model key #{model.key}", model.served && "the server says it serves #{model.served}"]
935
+ served_ref = model.respond_to?(:served_ref) ? model.served_ref : nil
936
+ served_host = served_ref.to_s.include?(":") ? "host #{served_ref.split(":").first}" : "its host"
937
+ details = [served_ref && "#{served_ref}: whatever #{served_host} serves",
938
+ model.host, model.key && "model key #{model.key}", model.served && "the server says it serves #{model.served}"]
933
939
  details = details.compact.reject(&:empty?)
934
940
  where = details.empty? ? "" : " (#{details.join("; ")})"
941
+ changes = served_ref ? "it changes when the host's model does, or with /model" : "it changes only with /model"
935
942
  "Model: this session runs on #{model.ref}#{where}.\n" \
936
943
  "Asked which model you are, answer with this line, not from training: a fine-tuned model often knows only " \
937
- "its base model's name, but this session runs what is named here; it changes only with /model. " \
944
+ "its base model's name, but this session runs what is named here; #{changes}. " \
938
945
  "Guidance for this model only goes in a model note: a memory named model_notes_<name> whose first line is " \
939
946
  "`models: <glob on this model's id or key>`."
940
947
  end
@@ -69,7 +69,8 @@ module Samagotchi
69
69
 
70
70
  # After the output, so the status row changes with the line saying why.
71
71
  served = @status[:model] == event[:model_name] ? @status[:served] : nil
72
- @status.update(model: event[:model_name], default_model: default_model_name, served: served)
72
+ @status.update(model: event[:model_name], default_model: default_model_name, served: served,
73
+ model_served: event[:model_served])
73
74
  end
74
75
 
75
76
  # Our change that asks first (CacheConfirm) puts its --yes line in the
@@ -373,7 +373,7 @@ module Samagotchi
373
373
  # source, the body as wrapped plain text (no terminal markdown), and
374
374
  # one `→ <command>` line per action, the label after it when it says
375
375
  # more. +updated+: a card shown again under its id.
376
- # @param card [Hash] title:, source:, body:, level:, actions:
376
+ # @param card [Hash] title:, source:, body:, level:, actions:, rows:
377
377
  # @param width [Integer, nil] columns (#card_width by default)
378
378
  def card_block(card, updated: false, width: nil)
379
379
  width = [(width || card_width).to_i, 24].max
@@ -385,19 +385,28 @@ module Samagotchi
385
385
  head += paint(" · #{source}", 90) unless source.empty?
386
386
  lines = [head]
387
387
  wrap_plain(strip_markdown(card[:body].to_s), width - 2).each { |line| lines << (line.empty? ? rail : "#{rail} #{line}") }
388
- Array(card[:actions]).each do |action|
389
- next lines.concat(card_url_lines(action, rail)) if action[:url] && !action[:command]
390
-
391
- command = action[:command].to_s
392
- label = action[:label].to_s
393
- line = "#{rail} #{paint("→ #{command}", 36)}"
394
- line += paint(" #{label}", 90) unless label.empty? || label == command
395
- lines << line
388
+ actions = Array(card[:actions])
389
+ Array(card[:rows]).each_with_index do |row, index|
390
+ lines << "#{rail} #{[row[:title], row[:sub]].map(&:to_s).reject(&:empty?).join(" · ")}"
391
+ actions.select { |action| action[:row] == index }.each { |action| lines.concat(card_action_lines(action, rail, " ")) }
396
392
  end
393
+ actions.reject { |action| action[:row] }.each { |action| lines.concat(card_action_lines(action, rail)) }
397
394
  lines << paint("└", 90)
398
395
  lines.join("\n")
399
396
  end
400
397
 
398
+ # One action's lines: `→ <command>`, the label after it when it says
399
+ # more (+indent+: a row's).
400
+ def card_action_lines(action, rail, indent = "")
401
+ return card_url_lines(action, rail) if action[:url] && !action[:command]
402
+
403
+ command = action[:command].to_s
404
+ label = action[:label].to_s
405
+ line = "#{rail} #{indent}#{paint("→ #{command}", 36)}"
406
+ line += paint(" #{label}", 90) unless label.empty? || label == command
407
+ [line]
408
+ end
409
+
401
410
  # A url action: "→ <label>" on the rail, then the address on its own
402
411
  # line with no rail, no paint and no wrapping by chi, so a terminal's
403
412
  # own click or a copy gets the whole address. One that isn't http(s)
@@ -635,14 +644,16 @@ module Samagotchi
635
644
  # +served+ / +served_for+: the model the server said it served for the
636
645
  # name asked (see Engine#served_model); shown first when it's another
637
646
  # model, unless +expected+ (the host's served: names it).
638
- def status_model_text(model, default_model, served: nil, served_for: nil, expected: false)
647
+ # +model_served+: a served model's id now (main:served·<id>).
648
+ def status_model_text(model, default_model, served: nil, served_for: nil, expected: false, model_served: nil)
639
649
  if !expected && ServedModel.differs?(served_for, served)
640
650
  asked = model.to_s.length > STATUS_ASKED_MAX ? "#{model.to_s[0, STATUS_ASKED_MAX - 1]}…" : model
641
651
  return "model=#{served} (served; asked #{asked})"
642
652
  end
643
- return "model=#{model}" if default_model.nil? || model == default_model
653
+ shown = model_served ? "#{model}·#{model_served}" : model
654
+ return "model=#{shown}" if default_model.nil? || model == default_model
644
655
 
645
- "model=#{model} (default: #{default_model})"
656
+ "model=#{shown} (default: #{default_model})"
646
657
  end
647
658
 
648
659
  # @param estimate [Hash, nil] the kernel's estimate ({est_pct:, bucket:})
@@ -714,6 +725,9 @@ module Samagotchi
714
725
  end
715
726
 
716
727
  lines = []
728
+ # A served model (main:served): the id it runs on now; the segments
729
+ # below are per id.
730
+ lines << "model: #{snapshot[:served_ref]} (now #{snapshot[:model_served]})" if snapshot[:model_served]
717
731
  lines << "turns: #{snapshot[:turns]}"
718
732
  lines << "tool calls: #{snapshot[:tool_calls_total]} (#{snapshot[:tool_errors]} errors)"
719
733
  unless snapshot[:tool_calls_by_tool].to_a.empty?
@@ -19,6 +19,8 @@ module Samagotchi
19
19
  # the first message's preview), or nil
20
20
  # model, default_model the model in use, and the config's default
21
21
  # (named beside another model)
22
+ # model_served the id a served model (main:served) runs on
23
+ # now, or nil (shown as main:served·<id>)
22
24
  # served [served, asked, expected]: what the server said it
23
25
  # served for the name asked (ServedModel), and
24
26
  # the host whose served: expects it (or nil)
@@ -32,7 +34,7 @@ module Samagotchi
32
34
  # records them as used)
33
35
  # muted its --mute list
34
36
  # running a turn runs: the row trails STEER_HINT
35
- FIELDS = %i[title model default_model served parent_id children participants context used_memories preloaded muted
37
+ FIELDS = %i[title model default_model model_served served parent_id children participants context used_memories preloaded muted
36
38
  running].freeze
37
39
 
38
40
  # The tail while a turn runs: where a typed line goes (the next step)
@@ -73,7 +75,8 @@ module Samagotchi
73
75
  # another model
74
76
  def take_state(state, default_model: nil)
75
77
  fields = { served: state[:served_model] ? [state[:served_model], state[:served_model_for], state[:served_expected_by]] : nil }
76
- fields.merge!(model: state[:model_name], default_model: default_model) if state[:model_name]
78
+ # model_served: an older worker's state has none (the plain ref shows).
79
+ fields.merge!(model: state[:model_name], default_model: default_model, model_served: state[:model_served]) if state[:model_name]
77
80
  STATE_LISTS.each { |field, key| fields[field] = Array(state[key]) if state.key?(key) }
78
81
  fields[:parent_id] = state[:parent_id] if state.key?(:parent_id)
79
82
  fields[:title] = state[:title] if state.key?(:title)
@@ -98,11 +101,24 @@ module Samagotchi
98
101
  when :used_memories_updated then update(used_memories: Array(event[:used_memory_names]))
99
102
  when :generation_completed
100
103
  update(served: [event[:served_model], event[:requested_model], event[:served_expected_by]]) if event[:served_model]
104
+ # A served model's generation was asked for the id it runs on now.
105
+ update(model_served: event[:requested_model]) if event[:requested_model] && served_model?
101
106
  when :turn_started then update(running: true)
102
107
  when *TURN_END_EVENTS then update(running: false)
103
108
  end
104
109
  end
105
110
 
111
+ # Whether the row's model is a served one: a served ref (main:served),
112
+ # or one the worker named an id for (an alias of main:served, whose
113
+ # command_ran model_name is the alias typed). Required here, not at
114
+ # load: the testing kit loads this file (sandbox_spec's count).
115
+ def served_model?
116
+ return true if @values[:model_served]
117
+
118
+ require_relative "../served_ref"
119
+ ServedRef.stored?(@values[:model])
120
+ end
121
+
106
122
  # Whether the row is drawn at all (status.line): a UI computes what
107
123
  # only the row shows (the children's counts) only then.
108
124
  def enabled? = status_line_enabled?
@@ -127,7 +143,8 @@ module Samagotchi
127
143
  model_text = ""
128
144
  if model
129
145
  model_text = status_model_text(model, @values[:default_model], served: served, served_for: served_for,
130
- expected: expected.is_a?(String))
146
+ expected: expected.is_a?(String),
147
+ model_served: @values[:model_served])
131
148
  end
132
149
  segments = [title_text(@values[:title], width),
133
150
  model_text,
@@ -280,7 +280,7 @@ module Samagotchi
280
280
  begin
281
281
  result = @engine.run_turn(session, prompt, on_event: events, max_iterations: max_iterations,
282
282
  cancel_controller: nil, images: ImageInput.extract(prompt))
283
- rescue LLM::ProviderError, ImageStore::Error => e
283
+ rescue LLM::ProviderError, ImageStore::Error, ServedLookup::Refused => e
284
284
  return one_shot_failed(session, e)
285
285
  rescue Interrupt
286
286
  return one_shot_interrupted(session)
@@ -109,7 +109,6 @@ module Samagotchi
109
109
  "Samagotchi::ProcessGroup.stop" => "stops a server's process group: needs a ctx process API",
110
110
  'require "samagotchi/token_usage"' => "for CHARS_PER_TOKEN",
111
111
  "Samagotchi::TokenUsage::CHARS_PER_TOKEN" => "estimates a tool's tokens: could be a stable constant",
112
- 'require "samagotchi/tool_declarations"' => "loaded for Api.tool_spec's schemas",
113
112
  "Samagotchi::ProjectEnv" => "checks the worker has a project env (an older chi doesn't)",
114
113
  "Samagotchi::ProjectEnv.current" => "starts a server in the session's project env: needs a ctx tools-env API",
115
114
  "Samagotchi::ProjectEnv.respond_to?" => "checks the worker has ProjectEnv.spawn_env (an older chi doesn't)",
@@ -280,13 +280,17 @@ module Samagotchi
280
280
  # @param confirm [Boolean] sent by a person at a web tab or a TUI, who
281
281
  # can answer ctx.cache_confirm (false: chi send, a delegate); a line
282
282
  # with --yes never asks, as in chi
283
- def command(line, confirm: false)
283
+ # @param user_typed [Boolean] typed by a person at a UI (ctx.user_typed?;
284
+ # false: chi send, a tool call, a delegate)
285
+ def command(line, confirm: false, user_typed: false)
284
286
  entry = commands.lookup(line)
285
287
  raise ArgumentError, "no command matches #{line.inspect}" unless entry
286
288
  raise ArgumentError, "#{entry.name} is chi's own command, not the bundle's" if entry.source == "core"
287
289
 
288
290
  args = line.to_s.strip.delete_prefix(entry.name).strip
289
- failing { CacheConfirm.asking(confirm && !CacheConfirm.split(args).last) { entry.handler.call(args) } }
291
+ failing do
292
+ UserTyped.as(user_typed) { CacheConfirm.asking(confirm && !CacheConfirm.split(args).last) { entry.handler.call(args) } }
293
+ end
290
294
  end
291
295
 
292
296
  # Call a registered tool as chi's dispatch does: its handler gets the
@@ -65,6 +65,7 @@ module Samagotchi
65
65
  cost: -> { cost(recorder[:cost]) },
66
66
  usage: -> { usage(recorder[:usage]) },
67
67
  turn_author: -> { recorder[:turn_author] },
68
+ turn_interactive: -> { recorder[:turn_interactive] == true },
68
69
  cache_confirm: lambda { |line, changed|
69
70
  CacheConfirm.ask(line: line, cost: :full, changed: changed,
70
71
  engine: CacheEngine.new(recorder[:history], recorder[:context_tokens]))
@@ -45,6 +45,9 @@ module Samagotchi
45
45
  usage: nil,
46
46
  # ctx.turn_author and the hooks' author: (a participant's "p:<id>"), nil for the owner.
47
47
  turn_author: nil,
48
+ # ctx.turn_interactive?: the running turn is the owner's from a web tab
49
+ # or a TUI (false: a schedule's, a delegate's, a wake turn, chi send's).
50
+ turn_interactive: true,
48
51
  # ctx.cache_confirm: whether the session has a model reply (a cache
49
52
  # to restart), and the context size its confirm names (nil: none).
50
53
  history: false, context_tokens: nil,
@@ -22,8 +22,11 @@ module Samagotchi
22
22
  def self.failure_line(error) = FailureLine.for(error)
23
23
 
24
24
  # @param failure_summary [#call] (error) → a failed turn's one line (Engine#failure_summary)
25
- def initialize(failure_summary:)
25
+ # @param served_line [#call] (error) → a served model's not-served line
26
+ # (it serves Y now: send again), else nil; the turn's note takes it too
27
+ def initialize(failure_summary:, served_line: ->(_error) {})
26
28
  @failure_summary = failure_summary
29
+ @served_line = served_line
27
30
  end
28
31
 
29
32
  # Why a turn stopped, from its end event (LastTurn::STOP_FACTS), for a
@@ -103,7 +106,8 @@ module Samagotchi
103
106
 
104
107
  steps = LLM::FailedTurn.progress(turn.session.messages, kept)
105
108
  error.kept_steps = steps if steps && error.is_a?(LLM::FailedTurn) && LLM::FailedTurn.keeps_work?(error)
106
- TurnNote.replace_trailing(kept, TurnNote.failed(self.class.failure_line(error), continued: turn.continue, steps: steps))
109
+ line = @served_line.call(error) || self.class.failure_line(error)
110
+ TurnNote.replace_trailing(kept, TurnNote.failed(line, continued: turn.continue, steps: steps))
107
111
  end
108
112
 
109
113
  # Called after #failed_messages, which marks the error's kept steps.