samagotchi 0.180.0 → 0.182.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 (123) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -1
  3. data/bin/chi +11 -0
  4. data/docs/architecture.md +2 -2
  5. data/docs/bundles.md +7 -2
  6. data/docs/cli.md +46 -13
  7. data/docs/configuration.md +25 -4
  8. data/docs/internals/anthropic.md +4 -3
  9. data/docs/internals/background-tasks.md +2 -0
  10. data/docs/internals/block-renderers.md +123 -6
  11. data/docs/internals/bridge.md +10 -0
  12. data/docs/internals/engine.md +11 -0
  13. data/docs/internals/inline-widgets.md +3 -1
  14. data/docs/internals/objectives.md +9 -4
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +14 -2
  17. data/docs/internals/web-frontend.md +100 -10
  18. data/docs/internals/working-set.md +24 -5
  19. data/docs/memory.md +3 -0
  20. data/docs/plugins.md +11 -4
  21. data/docs/sessions.md +8 -5
  22. data/docs/testing.md +1 -1
  23. data/lib/samagotchi/answer_display.rb +3 -2
  24. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  25. data/lib/samagotchi/block_fix.rb +220 -0
  26. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  27. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  28. data/lib/samagotchi/bridge.rb +11 -2
  29. data/lib/samagotchi/bridge_client.rb +9 -0
  30. data/lib/samagotchi/bundle_command.rb +4 -1
  31. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  32. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  33. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  34. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  35. data/lib/samagotchi/client.rb +8 -1
  36. data/lib/samagotchi/config.rb +9 -1
  37. data/lib/samagotchi/continue_intent.rb +8 -0
  38. data/lib/samagotchi/core_notice.rb +44 -0
  39. data/lib/samagotchi/engine/block_fix.rb +332 -0
  40. data/lib/samagotchi/engine/side_requests.rb +7 -5
  41. data/lib/samagotchi/engine.rb +4 -0
  42. data/lib/samagotchi/events.rb +1 -0
  43. data/lib/samagotchi/host_address.rb +7 -0
  44. data/lib/samagotchi/host_config.rb +8 -5
  45. data/lib/samagotchi/host_registry.rb +26 -8
  46. data/lib/samagotchi/idle_client.rb +10 -6
  47. data/lib/samagotchi/inline_widgets.rb +12 -0
  48. data/lib/samagotchi/kernel_loop.rb +10 -7
  49. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  50. data/lib/samagotchi/llm/adapters.rb +2 -1
  51. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  52. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  53. data/lib/samagotchi/llm/chat_loop.rb +8 -5
  54. data/lib/samagotchi/llm/errors.rb +41 -3
  55. data/lib/samagotchi/llm/http.rb +85 -22
  56. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  57. data/lib/samagotchi/markdown_parser.rb +28 -0
  58. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  59. data/lib/samagotchi/objectives.rb +7 -2
  60. data/lib/samagotchi/owner_lock.rb +2 -0
  61. data/lib/samagotchi/plugin/api.rb +4 -1
  62. data/lib/samagotchi/plugin/context.rb +9 -0
  63. data/lib/samagotchi/plugin/peer.rb +32 -15
  64. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  65. data/lib/samagotchi/row_refs.rb +14 -3
  66. data/lib/samagotchi/session_access/contract.rb +3 -0
  67. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  68. data/lib/samagotchi/session_access/local.rb +13 -0
  69. data/lib/samagotchi/session_access/remote.rb +19 -1
  70. data/lib/samagotchi/session_access.rb +1 -0
  71. data/lib/samagotchi/session_chain/delete.rb +45 -87
  72. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  73. data/lib/samagotchi/session_delete_command.rb +129 -3
  74. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  75. data/lib/samagotchi/session_manager/listing.rb +4 -4
  76. data/lib/samagotchi/session_manager/removal.rb +40 -14
  77. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  78. data/lib/samagotchi/session_manager.rb +1 -0
  79. data/lib/samagotchi/tool_ids.rb +19 -0
  80. data/lib/samagotchi/tool_runner.rb +8 -4
  81. data/lib/samagotchi/tools/registry.rb +3 -2
  82. data/lib/samagotchi/tools/task_runtime.rb +34 -0
  83. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  84. data/lib/samagotchi/version.rb +1 -1
  85. data/lib/samagotchi/web/app.rb +13 -1
  86. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  87. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  88. data/lib/samagotchi/web/message_display.rb +6 -1
  89. data/lib/samagotchi/web/participant_view.rb +1 -1
  90. data/lib/samagotchi/web/public/app.js +15 -19
  91. data/lib/samagotchi/web/public/block_fix.js +270 -0
  92. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  93. data/lib/samagotchi/web/public/block_frame.js +6 -3
  94. data/lib/samagotchi/web/public/block_host.js +21 -21
  95. data/lib/samagotchi/web/public/block_renderers.css +17 -5
  96. data/lib/samagotchi/web/public/block_watch.js +16 -2
  97. data/lib/samagotchi/web/public/context_chips.js +3 -4
  98. data/lib/samagotchi/web/public/images.js +1 -1
  99. data/lib/samagotchi/web/public/index.html +24 -5
  100. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  101. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  102. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  103. data/lib/samagotchi/web/public/peer_chip.js +3 -3
  104. data/lib/samagotchi/web/public/peer_data.js +27 -15
  105. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  106. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  107. data/lib/samagotchi/web/public/session_view.js +4 -0
  108. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  109. data/lib/samagotchi/web/public/turn_block.js +5 -2
  110. data/lib/samagotchi/web/public/working_set.js +9 -3
  111. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  112. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  113. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  114. data/lib/samagotchi/web/public/ws_order.js +48 -0
  115. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  116. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  117. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  118. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  119. data/lib/samagotchi/web/server.rb +6 -4
  120. data/lib/samagotchi/web/session_control.rb +53 -21
  121. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  122. data/lib/samagotchi/worker.rb +10 -3
  123. metadata +17 -1
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../block_fix"
3
4
  require_relative "../idle_client"
4
5
  require_relative "../idle_target"
5
6
  require_relative "../log"
@@ -50,9 +51,9 @@ module Samagotchi
50
51
  # command's ask_model between turns).
51
52
  # @return [String, nil]
52
53
  def side_author(kind)
53
- # Check this and the tracker are only ever the owner's, whichever turn
54
+ # Check this, the tracker and a block fix are only ever the owner's, whichever turn
54
55
  # runs as they end.
55
- return nil if [ObjectivesCheck::SOURCE, ObjectivesTrack::SOURCE].include?(kind.to_s)
56
+ return nil if [ObjectivesCheck::SOURCE, ObjectivesTrack::SOURCE, BlockFix::SOURCE].include?(kind.to_s)
56
57
 
57
58
  # One read each of the published contexts (TurnState): any thread.
58
59
  running = turn_context
@@ -102,8 +103,9 @@ module Samagotchi
102
103
  # refused thinking-off, holds for the next request); the session's id
103
104
  # goes with the request. Its usage counts in the session's side line
104
105
  # (#note_side_usage) under +source+, the asking bundle's name.
105
- # @return [String] the answer
106
- def ask_side_model(request, timeout:, max_tokens:, cancel_controller:, model: nil, source: nil)
106
+ # @param whole [Boolean] return the IdleClient::Summary (its cut_off)
107
+ # @return [String, IdleClient::Summary] the answer
108
+ def ask_side_model(request, timeout:, max_tokens:, cancel_controller:, model: nil, source: nil, whole: false)
107
109
  target = model.nil? ? session_model_recap_target : configured_side_target(model)
108
110
  client = side_model_client(target, timeout)
109
111
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
@@ -111,7 +113,7 @@ module Samagotchi
111
113
  kind: source.to_s.empty? ? "ask" : source.to_s, on_usage: method(:note_side_usage))
112
114
  Log.info(:plugins, "ask_model", model: target.label, answer_model: answer.model, chars: answer.text.length,
113
115
  ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round)
114
- answer.text
116
+ whole ? answer : answer.text
115
117
  end
116
118
  private :ask_side_model
117
119
 
@@ -138,6 +138,7 @@ require_relative "engine/toolkit"
138
138
  require_relative "engine/context_judge"
139
139
  require_relative "engine/turn_helpers"
140
140
  require_relative "engine/turn_end"
141
+ require_relative "engine/block_fix"
141
142
 
142
143
  module Samagotchi
143
144
  # Engine owns the core agent logic: system prompt construction, tool
@@ -174,6 +175,7 @@ module Samagotchi
174
175
  include ContextJudgePart
175
176
  include TurnHelpersPart
176
177
  include TurnEndPart
178
+ include BlockFixPart
177
179
 
178
180
  # Raised by #answer_question when the question it targets is no longer
179
181
  # open (never asked, superseded, already answered or cancelled). A subclass
@@ -230,6 +232,7 @@ module Samagotchi
230
232
  @chat_backend = nil
231
233
  @chat_backend_mutex = Mutex.new
232
234
  @side_judgments = SideJudgments.new
235
+ init_block_fix
233
236
  @judgments = build_judgments
234
237
  # Taken once: a running worker keeps the hosts it started with. A
235
238
  # client (specs) goes on a registry of its own, never the shared one.
@@ -1153,6 +1156,7 @@ module Samagotchi
1153
1156
  # so a Ctrl-C or a failure meanwhile keeps what is there.
1154
1157
  def turn_messages(turn, image_refs)
1155
1158
  session = turn.session
1159
+ note_block_fix_turn
1156
1160
  turn.messages = session.messages.dup
1157
1161
  # Built once per Engine (and again after a model switch) so the prompt
1158
1162
  # prefix, and the model server's KV cache for it, stay stable.
@@ -31,6 +31,7 @@ module Samagotchi
31
31
  after_tool_call: :internal,
32
32
  after_turn: :internal,
33
33
  answer_display: :state,
34
+ block_fix: :state,
34
35
  before_generation: :internal,
35
36
  before_tool_call: :internal,
36
37
  before_turn: :internal,
@@ -48,5 +48,12 @@ module Samagotchi
48
48
  rescue StandardError # degrade-ok: no configured limit; the host's own or the remote default applies
49
49
  nil
50
50
  end
51
+
52
+ # server.stream_idle_timeout, or nil when unset or unreadable.
53
+ def self.configured_stream_idle_timeout
54
+ Config.get("server.stream_idle_timeout")
55
+ rescue StandardError # degrade-ok: no configured limit; the host's own or the remote default applies
56
+ nil
57
+ end
51
58
  end
52
59
  end
@@ -20,7 +20,7 @@ module Samagotchi
20
20
  # HostRegistry::HostEntry describes them, nil when unset; models:
21
21
  # {downcased id => HostModel}.
22
22
  HostConfig = Data.define(:name, :host, :port, :scheme, :url, :api, :api_key_env, :auth, :dialect, :profile,
23
- :first_token_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
23
+ :first_token_timeout, :stream_idle_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
24
24
  :window_tokens, :steer_cut_after, :llm_context_strategy, :llm_context_apply, :llm_context_budget_tokens,
25
25
  :models) do
26
26
  # Every field but name may be left out: nil, models {}.
@@ -120,6 +120,7 @@ module Samagotchi
120
120
  # Kept as written; ModelProfile.resolve warns about an unknown one.
121
121
  profile: value.call(:profile).to_s.strip.downcase.then { |v| v.empty? ? nil : v },
122
122
  first_token_timeout: value.call(:first_token_timeout),
123
+ stream_idle_timeout: value.call(:stream_idle_timeout),
123
124
  vision: ConfigFile.vision_flag(value.call(:vision), where),
124
125
  remote: ConfigFile.bool_flag(value.call(:remote), where, "remote"),
125
126
  window_tokens: ConfigFile.window_tokens(value.call(:window_tokens), where),
@@ -132,10 +133,12 @@ module Samagotchi
132
133
  models: HostModel.parse_map(value.call(:models), name),
133
134
  llm_context_budget_tokens: LLMContextStrategy.parse_budget(value.call(LLMContextStrategy::BUDGET_KEY), where)
134
135
  }
135
- timeout = fields[:first_token_timeout]
136
- unless timeout.nil? || (timeout.is_a?(Numeric) && !timeout.negative?)
137
- ConfigFile.warn_once "Warning: #{where}: first_token_timeout must be seconds (0 = off); using the default"
138
- fields[:first_token_timeout] = nil
136
+ %i[first_token_timeout stream_idle_timeout].each do |key|
137
+ timeout = fields[key]
138
+ next if timeout.nil? || (timeout.is_a?(Numeric) && !timeout.negative?)
139
+
140
+ ConfigFile.warn_once "Warning: #{where}: #{key} must be seconds (0 = off); using the default"
141
+ fields[key] = nil
139
142
  end
140
143
  api_key_env = fields[:api_key_env]
141
144
  unless api_key_env.nil? || api_key_env.match?(ConfigFile::ENV_NAME_RE)
@@ -28,6 +28,9 @@ module Samagotchi
28
28
  # Seconds a remote host's stream may take to show something (a queued
29
29
  # free model on OpenRouter can send only keep-alives for minutes).
30
30
  REMOTE_FIRST_TOKEN_TIMEOUT = 120
31
+ # Seconds a remote host's stream that showed something may go without
32
+ # showing more (keep-alives alone can hold it until the read timeout).
33
+ REMOTE_STREAM_IDLE_TIMEOUT = 120
31
34
 
32
35
  # One host's answer in list_all_models: the host it was listed from and
33
36
  # its port; models: the LLM::ModelInfo list it served ([] when it failed
@@ -42,6 +45,7 @@ module Samagotchi
42
45
  # dialect: an api: anthropic host's LLM::Dialect name (#dialect_profile), nil when unset;
43
46
  # profile: the configured prompt profile name, if any;
44
47
  # first_token_timeout: the configured first-token limit (see #first_token_limit);
48
+ # stream_idle_timeout: the configured stream-idle limit (see #stream_idle_limit);
45
49
  # vision: the configured true/false (VisionSupport), nil when unset;
46
50
  # sampling: the configured request parameters (SamplingSettings), nil when unset;
47
51
  # thinking: the configured level (Thinking), nil when unset;
@@ -54,7 +58,7 @@ module Samagotchi
54
58
  # llm_context_budget_tokens: the configured context budget (LLMContextStrategy), nil when unset;
55
59
  # models: the ids the host serves whatever it lists, {downcased id => HostModel} ({} when none).
56
60
  HostEntry = Struct.new(:name, :host, :port, :client, :api, :scheme, :url, :api_key_env, :auth, :dialect,
57
- :profile, :first_token_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
61
+ :profile, :first_token_timeout, :stream_idle_timeout, :vision, :sampling, :thinking, :reasoning_history, :remote,
58
62
  :window_tokens, :steer_cut_after, :llm_context_strategy, :llm_context_apply, :llm_context_budget_tokens,
59
63
  :models, keyword_init: true) do
60
64
  # Talks a chat API through an adapter (LLM::Adapters: the chat loop);
@@ -106,6 +110,18 @@ module Samagotchi
106
110
  seconds = remote? ? REMOTE_FIRST_TOKEN_TIMEOUT : nil if seconds.nil?
107
111
  seconds&.positive? ? seconds : nil
108
112
  end
113
+
114
+ # Seconds a streamed answer that showed something may go without
115
+ # showing more, or nil: the host's stream_idle_timeout, else
116
+ # server.stream_idle_timeout, else 120 for a remote host (a local
117
+ # server may buffer a long tool call's arguments, and read_timeout
118
+ # catches a dead one). 0 turns it off.
119
+ def stream_idle_limit
120
+ seconds = stream_idle_timeout
121
+ seconds = HostAddress.configured_stream_idle_timeout if seconds.nil?
122
+ seconds = remote? ? REMOTE_STREAM_IDLE_TIMEOUT : nil if seconds.nil?
123
+ seconds&.positive? ? seconds : nil
124
+ end
109
125
  end
110
126
 
111
127
  # Where a model's requests go: the host entry, the client to use and the
@@ -139,11 +155,11 @@ module Samagotchi
139
155
  # it was built from (HostConfig.all, compared as read: the YAML read is
140
156
  # mtime-cached), so a host added while chi web runs is listed on the next
141
157
  # read, and its model lists, index and adapters are kept while hosts:
142
- # stay. It doesn't rebuild on server.first_token_timeout or the
143
- # server.host/port fallback entry: those are read at construction. It
144
- # refuses a client override (Shared). An Engine and the TerminalUI take
145
- # it once, at their start: a running worker keeps the hosts it started
146
- # with.
158
+ # stay. It doesn't rebuild on server.first_token_timeout,
159
+ # server.stream_idle_timeout or the server.host/port fallback entry:
160
+ # those are read at construction. It refuses a client override (Shared).
161
+ # An Engine and the TerminalUI take it once, at their start: a running
162
+ # worker keeps the hosts it started with.
147
163
  # For any env but the process ENV (chi self's spec envs): a fresh
148
164
  # registry on that env, never kept.
149
165
  # @return [HostRegistry]
@@ -182,7 +198,8 @@ module Samagotchi
182
198
  fields = cfg.to_h.merge(name: key.to_s.downcase, port: cfg.port.to_i, api: cfg.api&.to_sym, models: cfg.models || {})
183
199
  entry = HostEntry.new(**fields)
184
200
  entry.client = Client.new(host: cfg.host, port: cfg.port, scheme: cfg.scheme,
185
- first_token_timeout: entry.first_token_limit, name: entry.name,
201
+ first_token_timeout: entry.first_token_limit,
202
+ stream_idle_timeout: entry.stream_idle_limit, name: entry.name,
186
203
  api_key_env: entry.api_key_env, auth: entry.auth_scheme, env: env)
187
204
  @entries[entry.name] = entry
188
205
  end
@@ -272,7 +289,8 @@ module Samagotchi
272
289
  def adapter_for(entry)
273
290
  @mutex.synchronize do
274
291
  @adapters[entry.name] ||= LLM::Adapters.for(entry, models_ttl: entry.models_ttl,
275
- first_token_timeout: entry.first_token_limit)
292
+ first_token_timeout: entry.first_token_limit,
293
+ stream_idle_timeout: entry.stream_idle_limit)
276
294
  end
277
295
  end
278
296
 
@@ -29,9 +29,10 @@ module Samagotchi
29
29
  # answered (the server's name for it; nil when the reply names none).
30
30
  # +top_logprobs+: the first token's alternatives (LLM::TokenLogprob)
31
31
  # when #ask asked for logprobs and the server sent them, else [].
32
- # #to_s is the text.
33
- Summary = Data.define(:text, :model, :top_logprobs) do
34
- def initialize(top_logprobs: [].freeze, **) = super
32
+ # +cut_off+: the reply stopped at max_tokens (its finish reason is
33
+ # "length"). #to_s is the text.
34
+ Summary = Data.define(:text, :model, :top_logprobs, :cut_off) do
35
+ def initialize(top_logprobs: [].freeze, cut_off: false, **) = super
35
36
 
36
37
  def to_s = text
37
38
  end
@@ -139,7 +140,8 @@ module Samagotchi
139
140
  def ask(messages, max_tokens: MAX_TOKENS, cancel_controller: nil, kind: "ask", options: {}, session_id: nil, on_usage: nil)
140
141
  response = generate(messages, max_tokens: max_tokens, cancel_controller: cancel_controller, whole_sentences: false,
141
142
  kind: kind, options: options, session_id: session_id, on_usage: on_usage)
142
- Summary.new(text: response.text.to_s.strip, model: response.model, top_logprobs: response.top_logprobs)
143
+ Summary.new(text: response.text.to_s.strip, model: response.model, top_logprobs: response.top_logprobs,
144
+ cut_off: response.cut_off)
143
145
  rescue SummarizeError, LLM::RequestCancelled
144
146
  raise
145
147
  rescue StandardError => e
@@ -174,7 +176,9 @@ module Samagotchi
174
176
  cut_off = response.finish_reason == "length"
175
177
  # Reasoning cut off by max_tokens is the model's thinking, not a recap
176
178
  # (a server that ignores the thinking switch thinks until the limit).
177
- return Summary.new(text: "", model: response.model, top_logprobs: response.top_logprobs) if content.empty? && cut_off
179
+ if content.empty? && cut_off
180
+ return Summary.new(text: "", model: response.model, top_logprobs: response.top_logprobs, cut_off: true)
181
+ end
178
182
 
179
183
  # Prefer content, fall back to a finished reasoning_content (e.g.
180
184
  # Qwen3.6), and strip thinking tokens some models (Qwen, Gemma) leave
@@ -182,7 +186,7 @@ module Samagotchi
182
186
  text = self.class.strip_thinking(content.empty? ? reasoning : content)
183
187
  # Cut off by max_tokens: keep the sentences that finished ("" if none).
184
188
  text = whole_sentences ? self.class.full_sentences(text) : "#{text}…" if cut_off && !text.empty?
185
- Summary.new(text: text, model: response.model, top_logprobs: response.top_logprobs)
189
+ Summary.new(text: text, model: response.model, top_logprobs: response.top_logprobs, cut_off: cut_off)
186
190
  rescue LLM::ProtocolError => e
187
191
  raise SummarizeError, "server returned no parseable assistant content (#{e.message})"
188
192
  end
@@ -51,6 +51,18 @@ module Samagotchi
51
51
  COMMAND_LEAD = %r{\A[!/\s]+}
52
52
  # How much of a bad type value an error repeats.
53
53
  MAX_ECHO = 40
54
+ # The schemas (docs/internals/inline-widgets.md, The schemas) as a block
55
+ # fix's request states them (BlockFix.request): core can't read the
56
+ # inline-widgets bundle's prompt sections.
57
+ FIX_RULES = <<~RULES.chomp
58
+ A chi-ui block is YAML with `type:` first, picks or walk. Quote a value that holds a colon.
59
+ picks: `rows`, each with `id`, `text` and `options` (2 to 4 texts); optional `title`, and on a row
60
+ `recommended` (one of its options) and `why`. Row ids are unique, a row's options are unique.
61
+ walk: `title`, `actors` (2 to 5 unique texts) and `steps`, each with `id`, `actor` (one of the actors)
62
+ and `does` or `sees`; optional on a step `behind`, `next` (another step's id, or `end`) and `cases`
63
+ (each `when` and `goto`, a step's id). Step ids are unique and none is `end`.
64
+ No anchors, aliases or tags; at most #{MAX_ROWS} rows, #{MAX_STEPS} steps.
65
+ RULES
54
66
 
55
67
  module_function
56
68
 
@@ -38,6 +38,7 @@ require_relative "llm_context_forget"
38
38
  require_relative "working_set"
39
39
  require_relative "llm_context_notice"
40
40
  require_relative "answer_display"
41
+ require_relative "block_fix/stamp"
41
42
  require_relative "message_time"
42
43
  require_relative "llm/model_result"
43
44
  require_relative "llm/turn_settings"
@@ -511,7 +512,8 @@ module Samagotchi
511
512
 
512
513
  # One generation's request, asking again on a mid-stream drop (LLM::HTTP
513
514
  # raises RetryExhausted once a stream that already showed something
514
- # fails, where a retry would repeat output) up to MAX_STREAM_DROPS
515
+ # fails, where a retry would repeat output; StreamStalled, one that went
516
+ # quiet past stream_idle_timeout, is one) up to MAX_STREAM_DROPS
515
517
  # times after the transport's backoff: the partial reply is dropped and
516
518
  # the step restarts from the same conversation, as generation_retrying
517
519
  # with restarted: true. A cancel (before or during the wait) never
@@ -573,7 +575,7 @@ module Samagotchi
573
575
  if count.drops >= limit || !streamed_any
574
576
  raise if count.requests == e.attempts.to_i
575
577
 
576
- raise LLM::RetryExhausted.new(attempts: count.requests, last_error: e.last_error, label: e.host)
578
+ raise e.recounted(count.requests)
577
579
  end
578
580
 
579
581
  count.drops += 1
@@ -1089,17 +1091,18 @@ module Samagotchi
1089
1091
  # +keep_thought_from+: model messages from this index on keep their
1090
1092
  # thought blocks (a resumed run's); nil strips every one.
1091
1093
  # A model message is rebuilt from an allow-list: `display`,
1092
- # `display_refs` and its wall time (MessageTime::KEY) ride along so the
1093
- # stored conversation keeps them; the prompt formatter never reads them
1094
- # (AnswerDisplay, AnswerRefs, MessageTime).
1094
+ # `display_refs`, a block fix's stamp and its wall time (MessageTime::KEY)
1095
+ # ride along so the stored conversation keeps them; the prompt formatter
1096
+ # never reads them (AnswerDisplay, AnswerRefs, BlockFix::STAMP, MessageTime).
1095
1097
  def sanitize_history(messages, keep_thought_from: nil)
1096
1098
  messages.each_with_index.map do |m, index|
1097
1099
  if m[:role] == "model" && keep_thought_from && index >= keep_thought_from
1098
1100
  { role: m[:role], content: m[:content].to_s, display: m[:display], display_refs: m[:display_refs],
1099
- MessageTime::KEY => m[MessageTime::KEY] }.compact
1101
+ BlockFix::STAMP => m[BlockFix::STAMP], MessageTime::KEY => m[MessageTime::KEY] }.compact
1100
1102
  elsif m[:role] == "model"
1101
1103
  { role: m[:role], content: strip_thought_blocks(m[:content].to_s), display: m[:display],
1102
- display_refs: m[:display_refs], MessageTime::KEY => m[MessageTime::KEY] }.compact
1104
+ display_refs: m[:display_refs], BlockFix::STAMP => m[BlockFix::STAMP],
1105
+ MessageTime::KEY => m[MessageTime::KEY] }.compact
1103
1106
  else
1104
1107
  m.dup
1105
1108
  end
@@ -25,11 +25,12 @@ module Samagotchi
25
25
  # The adapter's LLM::HTTP: the timeouts (#timeouts), one attempt when
26
26
  # +retries+ is false and no +retry_policy+ is given.
27
27
  def build_http(timeout:, open_timeout:, retries:, retry_policy:, sleeper:, first_token_timeout:, api_key:,
28
- diagnosis_header: nil)
28
+ stream_idle_timeout: nil, diagnosis_header: nil)
29
29
  open_timeout, read_timeout = timeouts(timeout, open_timeout)
30
30
  policy = retry_policy || (retries ? nil : HTTP::RetryPolicy.none)
31
31
  HTTP.new(label: @host_name, open_timeout: open_timeout, read_timeout: read_timeout, retry_policy: policy,
32
- sleeper: sleeper, first_token_timeout: first_token_timeout, api_key: api_key,
32
+ sleeper: sleeper, first_token_timeout: first_token_timeout, stream_idle_timeout: stream_idle_timeout,
33
+ api_key: api_key,
33
34
  diagnosis_header: diagnosis_header)
34
35
  end
35
36
 
@@ -17,7 +17,8 @@ module Samagotchi
17
17
 
18
18
  # A host entry's adapter (its api, API base, name, key and remoteness).
19
19
  # @param entry [HostRegistry::HostEntry]
20
- # @param options [Hash] more adapter options (models_ttl:, first_token_timeout:, ...)
20
+ # @param options [Hash] more adapter options (models_ttl:, first_token_timeout:,
21
+ # stream_idle_timeout:, ...)
21
22
  # @raise [ArgumentError] the entry's api has no chat adapter
22
23
  def self.for(entry, **)
23
24
  adapter_class(entry.api).for(entry, **)
@@ -91,6 +91,11 @@ module Samagotchi
91
91
  # what the first-token limit waits for.
92
92
  def self.shows?(event) = %w[content_block_start content_block_delta].include?(event["type"])
93
93
 
94
+ # Whether a streamed +event+ ends the message (message_delta,
95
+ # message_stop): it restarts the stream-idle clock without counting as
96
+ # shown.
97
+ def self.ending?(event) = %w[message_delta message_stop].include?(event["type"])
98
+
94
99
  # Whether a streamed +event+ carries part of a tool call.
95
100
  def self.tool_call_delta?(event)
96
101
  case event["type"]
@@ -100,7 +100,7 @@ module Samagotchi
100
100
  DROPPED_OPTIONS = %i[reasoning_effort chat_template_kwargs stream_options prompt_cache_key logprobs top_logprobs
101
101
  max_completion_tokens].freeze
102
102
 
103
- attr_reader :base_url, :host_name, :api_key_env, :models_ttl, :first_token_timeout, :dialect
103
+ attr_reader :base_url, :host_name, :api_key_env, :models_ttl, :first_token_timeout, :stream_idle_timeout, :dialect
104
104
 
105
105
  # The Messages API root a base URL names: without a trailing / and a
106
106
  # trailing /v1 (as ANTHROPIC_BASE_URL), so requests never go to
@@ -120,11 +120,12 @@ module Samagotchi
120
120
  # The rest as OpenAIChat#initialize takes them.
121
121
  def initialize(base_url:, host_name:, api_key_env: nil, auth: nil, dialect: nil, stream: true, retries: true,
122
122
  timeout: nil, env: ENV, sleeper: nil, retry_policy: nil, models_ttl: DEFAULT_MODELS_TTL, remote: false,
123
- first_token_timeout: nil, purpose: "chat", open_timeout: nil)
123
+ first_token_timeout: nil, stream_idle_timeout: nil, purpose: "chat", open_timeout: nil)
124
124
  @dialect = Dialect.for(dialect)
125
125
  @remote = remote
126
126
  @purpose = purpose
127
127
  @first_token_timeout = first_token_timeout
128
+ @stream_idle_timeout = stream_idle_timeout
128
129
  @base_url = base_url.to_s.chomp("/")
129
130
  @host_name = host_name.to_s
130
131
  @api_key_env = api_key_env
@@ -136,6 +137,7 @@ module Samagotchi
136
137
  @binding = AnthropicBindingRecovery.new(refusals: @refusals, host_name: @host_name, budget_form: method(:budget_form?))
137
138
  @http = build_http(timeout: timeout, open_timeout: open_timeout, retries: retries, retry_policy: retry_policy,
138
139
  sleeper: sleeper, first_token_timeout: first_token_timeout,
140
+ stream_idle_timeout: stream_idle_timeout,
139
141
  api_key: ApiKey.for(api_key_env, host: @host_name, env: env, scheme: auth || @dialect.auth),
140
142
  diagnosis_header: AnthropicBindingRecovery::DIAGNOSIS_HEADER)
141
143
  end
@@ -463,6 +465,8 @@ module Samagotchi
463
465
  if AnthropicAssembly.shows?(event)
464
466
  shown.call
465
467
  on_shown&.call
468
+ elsif AnthropicAssembly.ending?(event)
469
+ shown.call(ending: true)
466
470
  end
467
471
  on_delta&.call(content: content, reasoning: reasoning, payload: assembly.with_usage(event)) unless event["type"] == "ping"
468
472
  end
@@ -15,6 +15,7 @@ require_relative "stray_tool_call"
15
15
  require_relative "../kernel_loop"
16
16
  require_relative "../answer_display"
17
17
  require_relative "../answer_refs"
18
+ require_relative "../block_fix/stamp"
18
19
  require_relative "../cut"
19
20
  require_relative "../cut_policy"
20
21
  require_relative "../context_status"
@@ -497,6 +498,7 @@ module Samagotchi
497
498
  message[TurnNote::EMPTY_ANSWER] = marker if marker
498
499
  message[AnswerDisplay::KEY] = entry[AnswerDisplay::KEY] if entry[AnswerDisplay::KEY]
499
500
  message[AnswerRefs::KEY] = entry[AnswerRefs::KEY] if entry[AnswerRefs::KEY]
501
+ message[BlockFix::STAMP] = entry[BlockFix::STAMP] if entry[BlockFix::STAMP]
500
502
  ContextNote::KEYS.each { |key| message[key] = entry[key] if entry.key?(key) }
501
503
  Steer::AUTHOR_KEYS.each { |key| message[key] = entry[key] if entry[key] }
502
504
  message[ToolResponse::LOADED] = entry[ToolResponse::LOADED] if entry[ToolResponse::LOADED].is_a?(Array)
@@ -965,10 +967,11 @@ module Samagotchi
965
967
 
966
968
  # A dropped stream (LLM::HTTP raises RetryExhausted once a stream
967
969
  # that already showed something fails, where a retry would repeat
968
- # output) is asked again here, from the same conversation, up to
969
- # MAX_STREAM_DROPS times per step (fewer under a smaller retry.max;
970
- # none with 0), after the transport's backoff: the partial reply is
971
- # dropped and the step restarts. A refusal or a first-token timeout
970
+ # output; StreamStalled, one that went quiet past
971
+ # stream_idle_timeout, is one) is asked again here, from the same
972
+ # conversation, up to MAX_STREAM_DROPS times per step (fewer under a
973
+ # smaller retry.max; none with 0), after the transport's backoff: the
974
+ # partial reply is dropped and the step restarts. A refusal or a first-token timeout
972
975
  # fails as before, and a cancel (before or during the wait) never
973
976
  # retries. +count+ (a DropCount) carries on across calls for one
974
977
  # step.
@@ -986,7 +989,7 @@ module Samagotchi
986
989
  if count.drops >= limit || !streamed_any
987
990
  raise if count.requests == e.attempts.to_i
988
991
 
989
- raise RetryExhausted.new(attempts: count.requests, last_error: e.last_error, label: e.host)
992
+ raise e.recounted(count.requests)
990
993
  end
991
994
 
992
995
  count.drops += 1
@@ -260,10 +260,12 @@ module Samagotchi
260
260
  class RetryExhausted < ConnectionError
261
261
  attr_reader :last_error
262
262
 
263
- def initialize(attempts:, last_error:, label: "llama.cpp")
263
+ # @param message [String, nil] a subclass's own message; nil: "request
264
+ # failed after …" with +last_error+
265
+ def initialize(attempts:, last_error:, label: "llama.cpp", message: nil)
264
266
  @last_error = last_error
265
- super("#{label} request failed after #{self.class.count(attempts)}: #{last_error.class}: #{last_error.message}",
266
- host: label, retryable: false, attempts: attempts)
267
+ message ||= "#{label} request failed after #{self.class.count(attempts)}: #{last_error.class}: #{last_error.message}"
268
+ super(message, host: label, retryable: false, attempts: attempts)
267
269
  end
268
270
 
269
271
  def summary = "network error after #{self.class.count(attempts)} (host #{host}: #{last_error.class})"
@@ -271,10 +273,46 @@ module Samagotchi
271
273
  # The message without its leading "host ": "request failed after …".
272
274
  def detail = host ? message.delete_prefix("#{host} ") : message
273
275
 
276
+ # The same failure counting +attempts+ requests: what the loops raise
277
+ # once a dropped stream's step has been asked again (every request
278
+ # counts, not only the last one's).
279
+ def recounted(attempts) = RetryExhausted.new(attempts: attempts, last_error: last_error, label: host)
280
+
274
281
  # "1 attempt", "3 attempts".
275
282
  def self.count(attempts) = "#{attempts} attempt#{"s" unless attempts == 1}"
276
283
  end
277
284
 
285
+ # A stream that showed something, then nothing more (no text, reasoning
286
+ # or tool call) for the host's stream_idle_timeout, while keep-alives
287
+ # could hold it open until the read timeout. A RetryExhausted, so the
288
+ # loops ask the step again as they do a dropped stream.
289
+ class StreamStalled < RetryExhausted
290
+ attr_reader :limit
291
+
292
+ def initialize(limit:, host:, attempts: 1, last_error: nil)
293
+ @limit = limit
294
+ super(attempts: attempts, last_error: last_error, label: host,
295
+ message: "#{host}: the model's stream stalled: no output for #{format_seconds(limit)}s")
296
+ end
297
+
298
+ def kind = :stream_stalled
299
+
300
+ def summary
301
+ "the model's stream stalled on host #{host}: no output for #{format_seconds(limit)}s (stream_idle_timeout)" \
302
+ "#{", after #{self.class.count(attempts)}" if attempts.to_i > 1}; try again later or pick another model (/model)"
303
+ end
304
+
305
+ # The message without its leading "host: ".
306
+ def detail = host ? message.delete_prefix("#{host}: ") : message
307
+
308
+ # Keeps its class and limit (RetryExhausted#recounted would not).
309
+ def recounted(attempts) = StreamStalled.new(limit: limit, host: host, attempts: attempts, last_error: last_error)
310
+
311
+ private
312
+
313
+ def format_seconds(seconds) = seconds == seconds.to_i ? seconds.to_i.to_s : seconds.to_s
314
+ end
315
+
278
316
  # A refused connection: nothing listens at the host's address. Not
279
317
  # retried (a server that isn't running rarely starts within the backoff).
280
318
  class ConnectionRefused < ConnectionError