samagotchi 0.193.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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +77 -1
  3. data/docs/bundle-authoring.md +1 -1
  4. data/docs/bundles.md +37 -12
  5. data/docs/cli.md +26 -10
  6. data/docs/configuration.md +71 -5
  7. data/docs/desktop.md +3 -0
  8. data/docs/guardrails.md +11 -1
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/engine.md +46 -3
  11. data/docs/internals/panes.md +66 -0
  12. data/docs/internals/peers.md +101 -5
  13. data/docs/internals/prompt-caching.md +4 -0
  14. data/docs/internals/session-lifecycle.md +9 -2
  15. data/docs/internals/web-frontend.md +16 -4
  16. data/docs/peers.md +79 -5
  17. data/docs/plugins.md +42 -4
  18. data/docs/sessions.md +15 -6
  19. data/docs/sub-agent.md +6 -4
  20. data/docs/system-one.md +4 -0
  21. data/docs/testing.md +3 -0
  22. data/lib/samagotchi/bridge/card_store.rb +1 -1
  23. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  24. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  25. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  26. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +28 -7
  27. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  28. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  29. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  30. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +23 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  32. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  33. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  34. data/lib/samagotchi/chi_invocation.rb +7 -0
  35. data/lib/samagotchi/client.rb +18 -0
  36. data/lib/samagotchi/codex_rollout.rb +93 -0
  37. data/lib/samagotchi/config.rb +15 -6
  38. data/lib/samagotchi/effective_model.rb +28 -2
  39. data/lib/samagotchi/engine/cards.rb +9 -4
  40. data/lib/samagotchi/engine/hooks.rb +8 -0
  41. data/lib/samagotchi/engine/models.rb +180 -7
  42. data/lib/samagotchi/engine/side_requests.rb +72 -13
  43. data/lib/samagotchi/engine/toolkit.rb +1 -1
  44. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  45. data/lib/samagotchi/engine.rb +11 -8
  46. data/lib/samagotchi/engine_snapshots.rb +16 -3
  47. data/lib/samagotchi/events.rb +1 -0
  48. data/lib/samagotchi/hooks.rb +3 -1
  49. data/lib/samagotchi/host_registry.rb +146 -16
  50. data/lib/samagotchi/idle_client.rb +13 -2
  51. data/lib/samagotchi/idle_recap.rb +33 -3
  52. data/lib/samagotchi/idle_target.rb +27 -7
  53. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  54. data/lib/samagotchi/llm/anthropic_messages.rb +3 -2
  55. data/lib/samagotchi/llm/errors.rb +35 -4
  56. data/lib/samagotchi/llm/model_listing.rb +19 -0
  57. data/lib/samagotchi/llm/openai_chat.rb +3 -2
  58. data/lib/samagotchi/model_binding.rb +46 -4
  59. data/lib/samagotchi/model_catalog.rb +68 -8
  60. data/lib/samagotchi/model_profile.rb +35 -0
  61. data/lib/samagotchi/models_command.rb +8 -4
  62. data/lib/samagotchi/panes/kitty.rb +122 -0
  63. data/lib/samagotchi/panes.rb +185 -0
  64. data/lib/samagotchi/peer_announce.rb +245 -0
  65. data/lib/samagotchi/peer_command.rb +97 -11
  66. data/lib/samagotchi/peer_continue.rb +10 -0
  67. data/lib/samagotchi/peer_mailbox.rb +30 -7
  68. data/lib/samagotchi/peer_pair_here.rb +149 -0
  69. data/lib/samagotchi/peer_presence.rb +434 -0
  70. data/lib/samagotchi/peer_say.rb +17 -10
  71. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  72. data/lib/samagotchi/plugin/api.rb +12 -1
  73. data/lib/samagotchi/plugin/card.rb +68 -11
  74. data/lib/samagotchi/plugin/context.rb +20 -1
  75. data/lib/samagotchi/plugin/panes.rb +54 -0
  76. data/lib/samagotchi/plugin/peer.rb +52 -10
  77. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  78. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  79. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  80. data/lib/samagotchi/plugin/peers.rb +76 -3
  81. data/lib/samagotchi/recap_setup.rb +40 -3
  82. data/lib/samagotchi/self_report.rb +25 -6
  83. data/lib/samagotchi/send_command.rb +6 -6
  84. data/lib/samagotchi/served_lookup.rb +225 -0
  85. data/lib/samagotchi/served_ref.rb +41 -0
  86. data/lib/samagotchi/session_access/contract.rb +6 -0
  87. data/lib/samagotchi/session_access/local.rb +54 -6
  88. data/lib/samagotchi/session_access/remote.rb +4 -4
  89. data/lib/samagotchi/session_access/remote_peers.rb +7 -4
  90. data/lib/samagotchi/session_commands.rb +40 -8
  91. data/lib/samagotchi/session_continue.rb +6 -2
  92. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  93. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  94. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  95. data/lib/samagotchi/session_manager/removal.rb +3 -0
  96. data/lib/samagotchi/session_model_settings.rb +7 -3
  97. data/lib/samagotchi/session_stores.rb +9 -0
  98. data/lib/samagotchi/sessions_command.rb +16 -3
  99. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  100. data/lib/samagotchi/system_prompt.rb +11 -4
  101. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  102. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  103. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  104. data/lib/samagotchi/terminal_ui.rb +1 -1
  105. data/lib/samagotchi/testing/bundle.rb +6 -2
  106. data/lib/samagotchi/turn_endings.rb +6 -2
  107. data/lib/samagotchi/user_typed.rb +29 -0
  108. data/lib/samagotchi/version.rb +1 -1
  109. data/lib/samagotchi/web/app.rb +8 -20
  110. data/lib/samagotchi/web/participant_review.rb +1 -1
  111. data/lib/samagotchi/web/participant_view.rb +1 -1
  112. data/lib/samagotchi/web/peer_routes.rb +33 -13
  113. data/lib/samagotchi/web/public/app.js +1 -1
  114. data/lib/samagotchi/web/public/card.js +26 -10
  115. data/lib/samagotchi/web/public/context_chips.js +24 -2
  116. data/lib/samagotchi/web/public/copy.js +8 -2
  117. data/lib/samagotchi/web/public/data.js +2 -1
  118. data/lib/samagotchi/web/public/format.js +9 -1
  119. data/lib/samagotchi/web/public/index.html +18 -0
  120. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  121. data/lib/samagotchi/web/public/model_pick.js +18 -5
  122. data/lib/samagotchi/web/public/model_picker.js +1 -1
  123. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  124. data/lib/samagotchi/web/public/peer_data.js +4 -2
  125. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  126. data/lib/samagotchi/web/public/served_ref.js +9 -0
  127. data/lib/samagotchi/web/public/session_fields.js +1 -0
  128. data/lib/samagotchi/web/public/session_state.js +4 -0
  129. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  130. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  131. data/lib/samagotchi/web/public/version_notices.js +7 -1
  132. data/lib/samagotchi/web/session_control.rb +19 -10
  133. data/lib/samagotchi/web/session_show.rb +20 -0
  134. data/lib/samagotchi/web/update_ops.rb +2 -2
  135. data/lib/samagotchi/worker/command_queue.rb +3 -0
  136. data/lib/samagotchi/worker/mail.rb +14 -1
  137. data/lib/samagotchi/worker.rb +1 -0
  138. metadata +18 -1
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Samagotchi
6
+ # Whether a Codex SessionStart hook comes from a fresh interactive Codex
7
+ # (the TUI's first message), read from the first line of its rollout file
8
+ # (the hook's `transcript_path`, `type: session_meta`). codex-peer's start
9
+ # hook (`chi peer announce codex`) takes a waiting mark only then, never
10
+ # for a `codex exec`, an `exec resume` or a subagent. The rule is an
11
+ # allowlist: `payload.originator == "codex-tui"`, `payload.thread_source
12
+ # == "user"`, a string `payload.source`, `payload.id` the hook's
13
+ # session_id; anything else, missing or unreadable: no.
14
+ #
15
+ # The format is Codex's own, undocumented: checked on Codex 0.172.0.
16
+ # Line 1 is big (about 19 KB: `payload.base_instructions`), so it is read
17
+ # to the first newline within LINE_MAX_BYTES; the hook fires a second or
18
+ # so after the file is born, so a missing file, a 0-byte one or a line
19
+ # with no newline yet is tried again (TRIES × TRY_SECONDS), then given up.
20
+ # The file must be a regular file (no link followed) whose real path is
21
+ # under <codex home>/sessions. See docs/internals/peers.md.
22
+ module CodexRollout
23
+ CHECKED_ON = "Codex 0.172.0"
24
+ LINE_MAX_BYTES = 1_048_576
25
+ TRIES = 10
26
+ TRY_SECONDS = 0.1
27
+ ORIGINATOR = "codex-tui"
28
+ THREAD_SOURCE = "user"
29
+
30
+ module_function
31
+
32
+ # @param path [String] the hook's transcript_path
33
+ # @param session [String] the hook's session_id
34
+ # @param codex_home [String] CODEX_HOME, else ~/.codex
35
+ # @param sleeper [#call] waits between tries (specs: no real sleep)
36
+ # @return [Boolean]
37
+ def interactive_start?(path, session:, codex_home:, sleeper: ->(seconds) { sleep(seconds) })
38
+ return false unless path.is_a?(String) && path.start_with?("/") && session.is_a?(String) && !session.empty?
39
+
40
+ line = nil
41
+ TRIES.times do |try|
42
+ line = first_line(path, codex_home)
43
+ break unless line == :again
44
+
45
+ sleeper.call(TRY_SECONDS) if try < TRIES - 1
46
+ end
47
+ line.is_a?(String) && interactive_meta?(line, session)
48
+ end
49
+
50
+ # Line 1 of +path+ (newline-terminated), :again (not there yet, empty or
51
+ # still being written), or nil (never: a link, not a file, outside the
52
+ # sessions folder, unreadable, over LINE_MAX_BYTES).
53
+ def first_line(path, codex_home)
54
+ stat = File.lstat(path)
55
+ return nil unless stat.file? && under?(path, codex_home)
56
+
57
+ # NONBLOCK and the open file's own stat: a FIFO (or anything but a
58
+ # regular file) swapped in after the lstat can't block the hook.
59
+ line = File.open(path, File::RDONLY | File::NOFOLLOW | File::NONBLOCK) do |io|
60
+ next :not_file unless io.stat.file?
61
+
62
+ io.binmode
63
+ io.gets("\n", LINE_MAX_BYTES + 1)
64
+ end
65
+ return nil if line == :not_file
66
+ return :again if line.nil?
67
+ return line if line.end_with?("\n")
68
+
69
+ line.bytesize > LINE_MAX_BYTES ? nil : :again
70
+ rescue Errno::ENOENT
71
+ :again
72
+ rescue SystemCallError, IOError
73
+ nil
74
+ end
75
+
76
+ # +path+'s real path is under <codex_home>/sessions.
77
+ def under?(path, codex_home)
78
+ root = File.realpath(File.join(codex_home.to_s, "sessions"))
79
+ File.realpath(path).start_with?("#{root}/")
80
+ rescue SystemCallError, ArgumentError
81
+ false
82
+ end
83
+
84
+ def interactive_meta?(line, session)
85
+ data = JSON.parse(line.dup.force_encoding(Encoding::UTF_8))
86
+ payload = data.is_a?(Hash) && data["type"] == "session_meta" ? data["payload"] : nil
87
+ payload.is_a?(Hash) && payload["id"] == session && payload["originator"] == ORIGINATOR &&
88
+ payload["thread_source"] == THREAD_SOURCE && payload["source"].is_a?(String)
89
+ rescue JSON::ParserError, EncodingError
90
+ false
91
+ end
92
+ end
93
+ end
@@ -89,7 +89,7 @@ module Samagotchi
89
89
  new_session session_creation worker_start next_broadcast next_retention_sweep next_invocation next_lifecycle_decision
90
90
  next_matching_use next_tool_or_approval process_start next_context_poll prompt_rebuild next_turn_start
91
91
  next_request_or_turn_end next_update desktop_update web_start next_cli_run next_empty_answer_retry
92
- next_history_access next_matching_turn_display_poll_write
92
+ next_history_access next_matching_turn_display_poll_write next_pane_lookup
93
93
  ].freeze
94
94
 
95
95
  # llm_context.policy's default: the sentence forget_outputs' description
@@ -365,8 +365,9 @@ module Samagotchi
365
365
  check: ->(value) { "at least 0" unless value >= 0 }),
366
366
  # The desktop helper's kitty targets (Desktop::MacOS.kitty_settings, one of its terminal_settings): listen_on copied from kitty.conf (unset = none),
367
367
  # the kitty binary, and the foreground programs listed, "|"-separated (a YAML list works too; "*" = every window).
368
- Entry.new(key: "kitty.listen_on", yaml_path: %w[kitty listen_on], type: :string, default: nil, expose: %i[env config], lifecycle: :desktop_update),
369
- Entry.new(key: "kitty.binary", yaml_path: %w[kitty binary], type: :string, default: "/Applications/kitty.app/Contents/MacOS/kitty", expose: %i[env config], lifecycle: :desktop_update),
368
+ # listen_on and binary are also read live by a worker's Panes (/claude show, the sessions here list).
369
+ Entry.new(key: "kitty.listen_on", yaml_path: %w[kitty listen_on], type: :string, default: nil, expose: %i[env config], lifecycle: :next_pane_lookup),
370
+ Entry.new(key: "kitty.binary", yaml_path: %w[kitty binary], type: :string, default: "/Applications/kitty.app/Contents/MacOS/kitty", expose: %i[env config], lifecycle: :next_pane_lookup),
370
371
  Entry.new(key: "kitty.agents", yaml_path: %w[kitty agents], type: :string, default: DESKTOP_AGENTS, expose: %i[env config], lifecycle: :desktop_update),
371
372
  # Its tmux targets (Desktop::MacOS.tmux_settings): off until enabled; the tmux binary (unset = the tmux on
372
373
  # chi's PATH when the launch file is written) and the foreground programs listed, as kitty.agents.
@@ -828,7 +829,10 @@ module Samagotchi
828
829
 
829
830
  "config: model_aliases.#{name} points to the alias '#{inner}'; aliases don't chain, so '#{inner}' is sent as written"
830
831
  end
831
- slash + chains + hosts.keys.filter_map { |name| family_host_problem(name.to_s) }
832
+ served = aliases.keys.select { |name| name.to_s.strip.casecmp?(ConfigFile::SERVED_WORD) }.map do |name|
833
+ "config: model_aliases.#{name}: `served` is reserved (the model a host serves now); alias ignored"
834
+ end
835
+ slash + chains + served + hosts.keys.filter_map { |name| family_host_problem(name.to_s) }
832
836
  end
833
837
 
834
838
  # Model families whose ids carry a ':' tag on Ollama and friends
@@ -1396,7 +1400,8 @@ module Samagotchi
1396
1400
 
1397
1401
  raw.each_with_object({}) do |(k, v), result|
1398
1402
  key = k.to_s.strip
1399
- next if key.empty?
1403
+ # `served` is reserved (ServedRef): main:served never goes through an alias.
1404
+ next if key.empty? || key.casecmp?(SERVED_WORD)
1400
1405
 
1401
1406
  val = v.to_s.strip
1402
1407
  next if val.empty?
@@ -1410,6 +1415,10 @@ module Samagotchi
1410
1415
  # Words /model takes as arguments (clear/default/none/off reset the
1411
1416
  # runtime model), so no alias may be named after one.
1412
1417
  RESERVED_MODEL_ALIASES = %w[clear default none off].freeze
1418
+ # The model value "whatever the host serves now" (ServedRef::WORD, kept
1419
+ # equal by its spec; not required here, the config loads light): never
1420
+ # an alias name.
1421
+ SERVED_WORD = "served"
1413
1422
 
1414
1423
  # What is wrong with +alias_name+ as an alias for +target+, or nil.
1415
1424
  def model_alias_error(alias_name, target)
@@ -1417,7 +1426,7 @@ module Samagotchi
1417
1426
  return "alias name is required" if alias_key.empty?
1418
1427
 
1419
1428
  lowered_key = alias_key.downcase
1420
- return "alias name '#{alias_key}' is reserved" if RESERVED_MODEL_ALIASES.include?(lowered_key)
1429
+ return "alias name '#{alias_key}' is reserved" if RESERVED_MODEL_ALIASES.include?(lowered_key) || lowered_key == SERVED_WORD
1421
1430
  return "alias name must not contain whitespace" if alias_key.match?(/\s/)
1422
1431
  return "alias name must not start with '-'" if alias_key.start_with?("-")
1423
1432
  return "alias name must not contain '/'" if alias_key.include?("/")
@@ -9,6 +9,7 @@ require_relative "model_profile"
9
9
  require_relative "reasoning_history"
10
10
  require_relative "sampling_settings"
11
11
  require_relative "served_model"
12
+ require_relative "served_ref"
12
13
  require_relative "steer_cut"
13
14
  require_relative "steer_cut_after"
14
15
  require_relative "thinking"
@@ -39,9 +40,12 @@ module Samagotchi
39
40
  # @param choice [ModelChoice]
40
41
  # @param models [Hash{String => ModelSettings}, nil] one models: map for
41
42
  # many models (a picker); ModelSettings.all at each read by default
43
+ # @param served_id [String, nil] a served ref's id as the turn pinned it
44
+ # (ModelBinding#served_id): it wins over the registry's lookup
42
45
  # @raise what HostRegistry#resolve raises
43
- def self.of(registry, choice, models: nil)
44
- target = registry.resolve(choice.name)
46
+ def self.of(registry, choice, models: nil, served_id: nil)
47
+ # Only with a pin: a registry stand-in (a picker's, a spec's) takes the name alone.
48
+ target = served_id ? registry.resolve(choice.name, served_id: served_id) : registry.resolve(choice.name)
45
49
  names = registry.lookup_names(choice.typed, resolved: choice.name, target: target)
46
50
  new(registry: registry, name: choice.name, typed: choice.typed, target: target, names: names,
47
51
  lookup: ModelLookup.for(target, names: names, models: models, env: registry.env))
@@ -85,6 +89,8 @@ module Samagotchi
85
89
 
86
90
  def entry = target.entry
87
91
  def client = target.client
92
+ # The id the host is sent (HostRegistry#sent_model_id's, from this
93
+ # resolve): what a turn's wire, settings and checks name.
88
94
  def bare = target.bare_model
89
95
  def host_name = entry.name
90
96
 
@@ -94,6 +100,26 @@ module Samagotchi
94
100
  # The resolved ref a session stores (ModelRef#ref): no resolve.
95
101
  def ref = registry.model_ref(name).ref
96
102
 
103
+ # Whether the model is a served ref (main:served: whatever its host
104
+ # serves now; ServedRef).
105
+ def served_ref? = ServedRef.served?(registry.model_ref(name))
106
+
107
+ # The ref this model's generations are counted under (SessionMetrics'
108
+ # per-model segments, Engine#generation_model_ref): #ref, or for a
109
+ # served ref the host and the id it resolved to ("main:q8"; #ref while
110
+ # nothing is known).
111
+ def turn_ref
112
+ id = served_id
113
+ id ? "#{host_name}:#{id}" : ref
114
+ end
115
+
116
+ # A served ref's id as resolved (the turn's pin, else what its host's
117
+ # last listing knows; no request), nil for any other model or while
118
+ # nothing is known: the UIs' "served · <id>" (session state's
119
+ # model_served).
120
+ # @return [String, nil]
121
+ def served_id = served_ref? && !ServedRef.word?(bare) ? bare : nil
122
+
97
123
  # The configured request parameters (hosts: and models: sampling).
98
124
  def sampling
99
125
  SamplingSettings.for(lookup)
@@ -24,15 +24,20 @@ module Samagotchi
24
24
  # @param source [String] who shows it (a bundle's name)
25
25
  # @param actions [Array<Hash>] {label:, command:}, a line the session
26
26
  # runs as typed (D3), or {label:, url:}, an http(s) address a UI opens
27
- # (it sends nothing; Plugin::Card.build checks it)
27
+ # (it sends nothing; Plugin::Card.build checks it); row: N makes it
28
+ # row N's button
29
+ # @param rows [Array<Hash>, nil] {title:, sub:}: a list to pick from
28
30
  # @return [String] the card's id
29
31
  # @raise [ArgumentError] a card without a title, or a bad action
30
- def show_card(source:, title:, body: "", actions: [], level: :info, id: nil, between_turns: false)
32
+ def show_card(source:, title:, body: "", actions: [], level: :info, id: nil, between_turns: false, rows: nil)
31
33
  if between_turns && turn_running?
32
- return running_anytime { show_card(source: source, title: title, body: body, actions: actions, level: level, id: id) }
34
+ return running_anytime do
35
+ show_card(source: source, title: title, body: body, actions: actions, level: level, id: id, rows: rows)
36
+ end
33
37
  end
34
38
 
35
- card = Plugin::Card.build(source: source, title: title, body: body, actions: actions, level: level, id: id)
39
+ card = Plugin::Card.build(source: source, title: title, body: body, actions: actions, level: level, id: id,
40
+ rows: rows)
36
41
  command = Thread.current[running_command_key]
37
42
  card[:command] = command if command
38
43
  @event_routes.route(card, **EventRoutes::CARD_MARKS)
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../answer_display"
4
4
  require_relative "../hooks/registry"
5
+ require_relative "../peer_presence"
5
6
 
6
7
  module Samagotchi
7
8
  class Engine
@@ -62,6 +63,13 @@ module Samagotchi
62
63
  @hooks.clear_all
63
64
  end
64
65
 
66
+ # A wait for a peer ran out (PeerWaitExpiry, between turns): the peer
67
+ # bundle's hook says so (ctx.notify).
68
+ # @param peer [String] the peer's name ("claude")
69
+ def peer_wait_ended(peer, minutes: PeerPresence::WAIT_SECONDS / 60)
70
+ @hooks.fire(:peer_wait_ended, { type: :peer_wait_ended, peer: peer.to_s, session_id: @session&.id, minutes: minutes })
71
+ end
72
+
65
73
  # ── Reminders API ────────────────────────────────────────────────────────────
66
74
  #
67
75
  # Each turn injects the reminders due then (#turn_messages,
@@ -11,6 +11,7 @@ require_relative "../log"
11
11
  require_relative "../model_notes"
12
12
  require_relative "../model_profile"
13
13
  require_relative "../prompt_note"
14
+ require_relative "../served_lookup"
14
15
  require_relative "../system_prompt"
15
16
 
16
17
  module Samagotchi
@@ -18,7 +19,8 @@ module Samagotchi
18
19
  # The model: its names and refs, identity and notes, /model's switch (and
19
20
  # the context it shows after), the profile (ModelBinding's, forwarded) and
20
21
  # the loop it runs on. Writes @client, @default_model_name,
21
- # @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,
22
24
  # @kernel, @metrics, @prompt_builder.
23
25
  module ModelsPart
24
26
  # The backend for the next turn: the loop the effective model's host speaks.
@@ -38,6 +40,12 @@ module Samagotchi
38
40
  model_ref_for(effective_model_name)
39
41
  end
40
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
+
41
49
  # The effective model as the system prompt names it (SystemPrompt::ModelIdentity):
42
50
  # the ref, its host, the overlay key and, for a local llama.cpp host
43
51
  # only, the model its /props names when that differs. Never a new
@@ -46,8 +54,9 @@ module Samagotchi
46
54
  model = effective_model
47
55
  entry = model.entry
48
56
  host = entry && "host #{entry.name}, #{entry.url || "#{entry.host}:#{entry.port}"}"
49
- SystemPrompt::ModelIdentity.new(ref: model.ref, host: host, key: @model_binding.model_key,
50
- 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)
51
60
  end
52
61
 
53
62
  # The model notes for the effective model (ModelNotes): matched on its
@@ -103,12 +112,84 @@ module Samagotchi
103
112
  summary = FailureLine.for(error)
104
113
  return summary unless error.is_a?(LLM::ProviderError) && error.host
105
114
 
115
+ served = served_failure_line(error)
116
+ return served if served
117
+
106
118
  note = @host_registry.alias_note(effective_model_name)
107
- 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)}"
108
121
  rescue StandardError => e
109
122
  EffectiveModel::Unresolved.fallback(:alias_note_failed, effective_model_name, e, summary)
110
123
  end
111
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
+
112
193
  # +name+'s resolved ref (ModelRef#ref).
113
194
  def model_ref_for(name)
114
195
  @host_registry.model_ref(name).ref
@@ -147,9 +228,12 @@ module Samagotchi
147
228
  # @return [ModelProfile::Resolution]
148
229
  def profile_resolution = @model_binding.profile_resolution
149
230
 
150
- # 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.
151
233
  def bare_model_name(full_ref)
152
- @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)
153
237
  end
154
238
 
155
239
  # The memory overlay keys follow the model sent (ModelBinding#sync_model_key!).
@@ -183,6 +267,8 @@ module Samagotchi
183
267
  resolved = ModelProfile.check_host!(ModelProfile.required_model_name(model_name), hosts: @host_registry.entries)
184
268
  choice = ModelChoice.new(name: resolved, typed: typed.to_s.strip.empty? ? model_name : typed.to_s.strip)
185
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))
186
272
  sync_model_key!
187
273
  @prompt_builder.reset!
188
274
  # The notes the new model's prompt loads at its next build, so /model,
@@ -203,6 +289,87 @@ module Samagotchi
203
289
  ref
204
290
  end
205
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
+
206
373
  # After /model: how full the context is on the new model's window,
207
374
  # before its first turn: the last turn's count (the old model's
208
375
  # tokenizer's, replaced at the next generation) against the new model's
@@ -243,7 +410,13 @@ module Samagotchi
243
410
  # the effective model; false before any (or when the ref can't be told).
244
411
  def model_switched_since_last_turn?
245
412
  last = @metrics.last_model_ref
246
- !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)
247
420
  rescue StandardError => e
248
421
  Log.warn(:model, "switch_check_failed", error: e.class.name, msg: e.message.to_s[0, 200])
249
422
  false
@@ -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