samagotchi 0.179.0 → 0.181.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +76 -1
- data/bin/chi +10 -0
- data/docs/architecture.md +1 -1
- data/docs/bundles.md +39 -3
- data/docs/cli.md +16 -9
- data/docs/configuration.md +25 -5
- data/docs/context.md +7 -0
- data/docs/internals/anthropic.md +4 -3
- data/docs/internals/background-tasks.md +4 -1
- data/docs/internals/block-renderers.md +11 -7
- data/docs/internals/bundles.md +12 -10
- data/docs/internals/objectives.md +9 -4
- data/docs/internals/web-frontend.md +127 -6
- data/docs/internals/working-set.md +24 -5
- data/docs/memory.md +3 -0
- data/docs/plugins.md +17 -6
- data/docs/sessions.md +1 -1
- data/docs/testing.md +5 -1
- data/lib/samagotchi/block_renderers.rb +22 -3
- data/lib/samagotchi/bundle_command.rb +9 -2
- data/lib/samagotchi/bundle_needs.rb +1 -1
- data/lib/samagotchi/bundle_settings_check.rb +5 -2
- data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
- data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/client.rb +8 -1
- data/lib/samagotchi/config.rb +6 -1
- data/lib/samagotchi/context_providers.rb +6 -8
- data/lib/samagotchi/core_notice.rb +44 -0
- data/lib/samagotchi/host_address.rb +7 -0
- data/lib/samagotchi/host_config.rb +8 -5
- data/lib/samagotchi/host_registry.rb +26 -8
- data/lib/samagotchi/installed_bundles/dir.rb +17 -55
- data/lib/samagotchi/installed_bundles/standing.rb +23 -3
- data/lib/samagotchi/installed_bundles.rb +26 -11
- data/lib/samagotchi/kernel_loop.rb +3 -2
- data/lib/samagotchi/llm/adapter_common.rb +3 -2
- data/lib/samagotchi/llm/adapters.rb +2 -1
- data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
- data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
- data/lib/samagotchi/llm/chat_loop.rb +6 -5
- data/lib/samagotchi/llm/errors.rb +41 -3
- data/lib/samagotchi/llm/http.rb +85 -22
- data/lib/samagotchi/llm/openai_chat.rb +20 -3
- data/lib/samagotchi/memory_bundle/status.rb +10 -6
- data/lib/samagotchi/objectives.rb +7 -2
- data/lib/samagotchi/owner_lock.rb +2 -0
- data/lib/samagotchi/plugin/api.rb +4 -1
- data/lib/samagotchi/plugin/context.rb +9 -0
- data/lib/samagotchi/plugin/peer.rb +32 -15
- data/lib/samagotchi/plugin/tool_spec.rb +13 -2
- data/lib/samagotchi/row_refs.rb +14 -3
- data/lib/samagotchi/session_chain/delete.rb +6 -6
- data/lib/samagotchi/session_config.rb +15 -9
- data/lib/samagotchi/session_manager/removal.rb +2 -2
- data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +13 -3
- data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
- data/lib/samagotchi/tool_ids.rb +19 -0
- data/lib/samagotchi/tool_runner.rb +8 -4
- data/lib/samagotchi/tools/registry.rb +3 -2
- data/lib/samagotchi/tools/task_runtime.rb +46 -3
- data/lib/samagotchi/turn_stages/objectives.rb +10 -5
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/public/app.js +22 -14
- data/lib/samagotchi/web/public/block_host.js +20 -20
- data/lib/samagotchi/web/public/block_renderers.css +5 -5
- data/lib/samagotchi/web/public/context_chips.js +183 -49
- data/lib/samagotchi/web/public/history_shape.js +5 -3
- data/lib/samagotchi/web/public/images.js +1 -1
- data/lib/samagotchi/web/public/index.html +90 -5
- data/lib/samagotchi/web/public/objectives_strip.js +16 -6
- data/lib/samagotchi/web/public/pan_zoom.js +121 -0
- data/lib/samagotchi/web/public/peer_chip.js +171 -0
- data/lib/samagotchi/web/public/peer_data.js +131 -0
- data/lib/samagotchi/web/public/peer_exchange.js +83 -0
- data/lib/samagotchi/web/public/peer_links.js +161 -0
- data/lib/samagotchi/web/public/peer_note.js +49 -0
- data/lib/samagotchi/web/public/picture_viewer.js +304 -0
- data/lib/samagotchi/web/public/popover_modal.js +3 -2
- data/lib/samagotchi/web/public/session_view.js +10 -1
- data/lib/samagotchi/web/public/stream_handlers.js +17 -4
- data/lib/samagotchi/web/public/turn_html.js +11 -2
- data/lib/samagotchi/web/public/working_set.js +9 -3
- data/lib/samagotchi/web/public/working_set_view.js +28 -11
- data/lib/samagotchi/web/public/ws_cards.js +36 -10
- data/lib/samagotchi/web/public/ws_markdown.js +129 -0
- data/lib/samagotchi/web/public/ws_order.js +48 -0
- data/lib/samagotchi/web/public/ws_peek.js +22 -5
- data/lib/samagotchi/web/public/ws_preview.css +41 -1
- data/lib/samagotchi/web/public/ws_reader.js +35 -6
- data/lib/samagotchi/web/public/ws_sections.js +24 -15
- metadata +11 -1
|
@@ -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
|
|
@@ -965,10 +965,11 @@ module Samagotchi
|
|
|
965
965
|
|
|
966
966
|
# A dropped stream (LLM::HTTP raises RetryExhausted once a stream
|
|
967
967
|
# that already showed something fails, where a retry would repeat
|
|
968
|
-
# output
|
|
969
|
-
#
|
|
970
|
-
#
|
|
971
|
-
#
|
|
968
|
+
# output; StreamStalled, one that went quiet past
|
|
969
|
+
# stream_idle_timeout, is one) is asked again here, from the same
|
|
970
|
+
# conversation, up to MAX_STREAM_DROPS times per step (fewer under a
|
|
971
|
+
# smaller retry.max; none with 0), after the transport's backoff: the
|
|
972
|
+
# partial reply is dropped and the step restarts. A refusal or a first-token timeout
|
|
972
973
|
# fails as before, and a cancel (before or during the wait) never
|
|
973
974
|
# retries. +count+ (a DropCount) carries on across calls for one
|
|
974
975
|
# step.
|
|
@@ -986,7 +987,7 @@ module Samagotchi
|
|
|
986
987
|
if count.drops >= limit || !streamed_any
|
|
987
988
|
raise if count.requests == e.attempts.to_i
|
|
988
989
|
|
|
989
|
-
raise
|
|
990
|
+
raise e.recounted(count.requests)
|
|
990
991
|
end
|
|
991
992
|
|
|
992
993
|
count.drops += 1
|
|
@@ -260,10 +260,12 @@ module Samagotchi
|
|
|
260
260
|
class RetryExhausted < ConnectionError
|
|
261
261
|
attr_reader :last_error
|
|
262
262
|
|
|
263
|
-
|
|
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
|
-
|
|
266
|
-
|
|
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
|
data/lib/samagotchi/llm/http.rb
CHANGED
|
@@ -102,18 +102,22 @@ module Samagotchi
|
|
|
102
102
|
# @param sleeper [#call] waits the given seconds (specs pass a no-op)
|
|
103
103
|
# @param first_token_timeout [Numeric, nil] seconds a stream may take to
|
|
104
104
|
# show something (see #stream_lines); nil: no limit
|
|
105
|
+
# @param stream_idle_timeout [Numeric, nil] seconds a stream that showed
|
|
106
|
+
# something may go without showing more (see #stream_lines); nil or
|
|
107
|
+
# 0: no limit
|
|
105
108
|
# @param api_key [ApiKey, nil] sent on every request; nil: no
|
|
106
109
|
# Authorization header (a local server)
|
|
107
110
|
# @param diagnosis_header [String, nil] a response header the adapter
|
|
108
111
|
# wants kept on a ProviderError as its diagnosis; nil: none
|
|
109
112
|
def initialize(label:, open_timeout:, read_timeout:, retry_policy: nil, sleeper: nil, first_token_timeout: nil,
|
|
110
|
-
api_key: nil, diagnosis_header: nil)
|
|
113
|
+
stream_idle_timeout: nil, api_key: nil, diagnosis_header: nil)
|
|
111
114
|
@label = label
|
|
112
115
|
@api_key = api_key
|
|
113
116
|
@diagnosis_header = diagnosis_header
|
|
114
117
|
@open_timeout = open_timeout
|
|
115
118
|
@read_timeout = read_timeout
|
|
116
119
|
@first_token_timeout = first_token_timeout&.positive? ? first_token_timeout : nil
|
|
120
|
+
@stream_idle_timeout = stream_idle_timeout&.positive? ? stream_idle_timeout : nil
|
|
117
121
|
@retry_policy = retry_policy || RetryPolicy.from_config
|
|
118
122
|
@sleeper = sleeper || ->(seconds) { sleep(seconds) }
|
|
119
123
|
end
|
|
@@ -136,6 +140,14 @@ module Samagotchi
|
|
|
136
140
|
# timeout, so without this a queued request can wait silently for as
|
|
137
141
|
# long as the provider keeps it open.
|
|
138
142
|
#
|
|
143
|
+
# With a stream_idle_timeout, an attempt that called +shown+ and then
|
|
144
|
+
# doesn't call it again within the limit is closed the same way and
|
|
145
|
+
# raises StreamStalled (a RetryExhausted: the loops ask the step again
|
|
146
|
+
# as they do a dropped stream). +shown.call(ending: true)+, for a
|
|
147
|
+
# stream's end-of-answer chunks (a finish reason, the usage), restarts
|
|
148
|
+
# that clock without counting as shown, so a slow trailing usage chunk
|
|
149
|
+
# doesn't void a complete answer.
|
|
150
|
+
#
|
|
139
151
|
# @param on_retry [Proc, nil] called before each backoff wait with
|
|
140
152
|
# attempt:, max_retries:, next_delay:, error_class:, error_message:
|
|
141
153
|
# @param on_network_error [Proc, nil] called with each network error
|
|
@@ -143,6 +155,7 @@ module Samagotchi
|
|
|
143
155
|
# @raise [RetryExhausted] when the retries run out
|
|
144
156
|
# @raise [ProviderError] for an error status
|
|
145
157
|
# @raise [FirstTokenTimeout] when nothing was shown in time
|
|
158
|
+
# @raise [StreamStalled] when the stream showed nothing more in time
|
|
146
159
|
# @param log_fields [Hash] what the log line says about the request
|
|
147
160
|
# (model:, purpose: chat/recap/warmup/probe/models); never its body
|
|
148
161
|
def stream_lines(uri, request, cancel_controller: nil, on_retry: nil, on_network_error: nil, log_fields: {}, &on_line)
|
|
@@ -158,11 +171,18 @@ module Samagotchi
|
|
|
158
171
|
def stream_attempt(uri, request, current, &)
|
|
159
172
|
# Time to first token is the answering attempt's, not the retries'.
|
|
160
173
|
current[:attempt_started_at] = monotonic_now
|
|
161
|
-
|
|
174
|
+
current[:last_shown_at] = nil
|
|
175
|
+
# Lock-free: the watchdog reads last_shown_at, and rechecks it under
|
|
176
|
+
# the mutex before it closes anything.
|
|
177
|
+
shown = lambda do |ending: false|
|
|
178
|
+
now = monotonic_now
|
|
179
|
+
current[:last_shown_at] = now
|
|
180
|
+
next if ending
|
|
181
|
+
|
|
162
182
|
current[:streamed] = true
|
|
163
|
-
current[:first_shown_at] ||=
|
|
183
|
+
current[:first_shown_at] ||= now
|
|
164
184
|
end
|
|
165
|
-
|
|
185
|
+
watch_stream(current) do
|
|
166
186
|
start(uri) do |http|
|
|
167
187
|
current[:http] = http
|
|
168
188
|
http.request(request) do |response|
|
|
@@ -287,6 +307,7 @@ module Samagotchi
|
|
|
287
307
|
rescue StandardError => e
|
|
288
308
|
raise RequestCancelled, cancel_controller.reason if cancel_controller&.cancelled?
|
|
289
309
|
raise first_token_timeout if current[:first_token_expired]
|
|
310
|
+
raise stream_stalled(attempts, e) if current[:stalled]
|
|
290
311
|
raise unless self.class.network_error?(e)
|
|
291
312
|
|
|
292
313
|
on_network_error&.call(e)
|
|
@@ -312,29 +333,28 @@ module Samagotchi
|
|
|
312
333
|
end
|
|
313
334
|
end
|
|
314
335
|
|
|
315
|
-
# Runs one attempt (the block) under the first-token
|
|
316
|
-
# thread closes the attempt's socket when the
|
|
317
|
-
#
|
|
318
|
-
#
|
|
336
|
+
# Runs one attempt (the block) under the first-token and stream-idle
|
|
337
|
+
# limits: a watchdog thread closes the attempt's socket when the
|
|
338
|
+
# deadline passes (first_token_timeout after the attempt started while
|
|
339
|
+
# nothing was shown, then stream_idle_timeout after the last shown
|
|
340
|
+
# chunk), so the read fails and #with_retries raises FirstTokenTimeout
|
|
341
|
+
# or StreamStalled; while still connecting, it raises that in the
|
|
319
342
|
# requesting thread, as a cancel does.
|
|
320
|
-
def
|
|
321
|
-
return yield unless @first_token_timeout
|
|
343
|
+
def watch_stream(current)
|
|
344
|
+
return yield unless @first_token_timeout || @stream_idle_timeout
|
|
322
345
|
|
|
323
346
|
requesting_thread = Thread.current
|
|
324
347
|
current[:mutex].synchronize { current[:attempt_over] = false }
|
|
325
348
|
watchdog = Thread.new do
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
#
|
|
332
|
-
|
|
333
|
-
if
|
|
334
|
-
|
|
335
|
-
else
|
|
336
|
-
requesting_thread.raise(first_token_timeout)
|
|
337
|
-
end
|
|
349
|
+
loop do
|
|
350
|
+
deadline = watch_deadline(current)
|
|
351
|
+
break if deadline == :off
|
|
352
|
+
|
|
353
|
+
# No deadline yet (no first-token limit, nothing shown): look
|
|
354
|
+
# again after the idle limit.
|
|
355
|
+
wait = deadline ? deadline - monotonic_now : @stream_idle_timeout
|
|
356
|
+
next sleep(wait) if wait.positive?
|
|
357
|
+
break if expire(current, requesting_thread)
|
|
338
358
|
end
|
|
339
359
|
rescue IOError
|
|
340
360
|
nil
|
|
@@ -347,8 +367,49 @@ module Samagotchi
|
|
|
347
367
|
end
|
|
348
368
|
end
|
|
349
369
|
|
|
370
|
+
# When the attempt's current limit passes: the first-token one before
|
|
371
|
+
# anything was shown, the idle one after; nil while neither applies
|
|
372
|
+
# yet, :off once nothing is left to watch.
|
|
373
|
+
def watch_deadline(current)
|
|
374
|
+
if current[:streamed]
|
|
375
|
+
return :off unless @stream_idle_timeout
|
|
376
|
+
|
|
377
|
+
(current[:last_shown_at] || current[:attempt_started_at]) + @stream_idle_timeout
|
|
378
|
+
elsif @first_token_timeout
|
|
379
|
+
current[:attempt_started_at] + @first_token_timeout
|
|
380
|
+
end
|
|
381
|
+
end
|
|
382
|
+
|
|
383
|
+
# Ends the attempt if its deadline (rechecked under the mutex) has
|
|
384
|
+
# passed: true once it is over (expired, finished or done), false when
|
|
385
|
+
# a chunk came since and the watch goes on.
|
|
386
|
+
def expire(current, requesting_thread)
|
|
387
|
+
current[:mutex].synchronize do
|
|
388
|
+
next true if current[:attempt_over] || current[:done]
|
|
389
|
+
|
|
390
|
+
deadline = watch_deadline(current)
|
|
391
|
+
next true if deadline == :off
|
|
392
|
+
next false if deadline.nil? || deadline > monotonic_now
|
|
393
|
+
|
|
394
|
+
stalled = current[:streamed]
|
|
395
|
+
current[stalled ? :stalled : :first_token_expired] = true
|
|
396
|
+
# No Net::HTTP yet: still connecting. One whose socket is closed
|
|
397
|
+
# has finished, and the attempt returns on its own.
|
|
398
|
+
if current[:http]
|
|
399
|
+
socket_io(current[:http])&.close
|
|
400
|
+
else
|
|
401
|
+
requesting_thread.raise(stalled ? stream_stalled(current[:attempts].to_i) : first_token_timeout)
|
|
402
|
+
end
|
|
403
|
+
true
|
|
404
|
+
end
|
|
405
|
+
end
|
|
406
|
+
|
|
350
407
|
def first_token_timeout = FirstTokenTimeout.new(limit: @first_token_timeout, host: @label)
|
|
351
408
|
|
|
409
|
+
def stream_stalled(attempts, last_error = nil)
|
|
410
|
+
StreamStalled.new(limit: @stream_idle_timeout, host: @label, attempts: attempts, last_error: last_error)
|
|
411
|
+
end
|
|
412
|
+
|
|
352
413
|
def monotonic_now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
353
414
|
|
|
354
415
|
# The per-request state the attempts share (the Net::HTTP a cancel
|
|
@@ -385,11 +446,13 @@ module Samagotchi
|
|
|
385
446
|
failure_level = current[:level] == :info ? :error : :debug
|
|
386
447
|
event = case e
|
|
387
448
|
when FirstTokenTimeout then "first_token_timeout"
|
|
449
|
+
when StreamStalled then "stream_stalled"
|
|
388
450
|
when RetryExhausted then "retry_exhausted"
|
|
389
451
|
else "failed"
|
|
390
452
|
end
|
|
391
453
|
Log.public_send(failure_level, :http, event, **log_base(current), status: e.is_a?(ProviderError) ? e.status : nil,
|
|
392
454
|
ms: elapsed_ms(current), attempts: current[:attempts], error: e.class.name,
|
|
455
|
+
idle_s: e.is_a?(StreamStalled) ? e.limit : nil,
|
|
393
456
|
msg: log_message(e.respond_to?(:summary) ? e.summary : e.message))
|
|
394
457
|
raise
|
|
395
458
|
end
|
|
@@ -90,7 +90,8 @@ module Samagotchi
|
|
|
90
90
|
# limit holds less. 32k leaves room for any one step's answer.
|
|
91
91
|
OPENROUTER_MAX_TOKENS = 32_768
|
|
92
92
|
|
|
93
|
-
attr_reader :base_url, :host_name, :api_key_env, :models_ttl, :first_token_timeout, :
|
|
93
|
+
attr_reader :base_url, :host_name, :api_key_env, :models_ttl, :first_token_timeout, :stream_idle_timeout,
|
|
94
|
+
:default_max_tokens
|
|
94
95
|
|
|
95
96
|
# @param entry [HostRegistry::HostEntry]
|
|
96
97
|
def self.for(entry, **)
|
|
@@ -147,16 +148,20 @@ module Samagotchi
|
|
|
147
148
|
# @param remote [Boolean] a provider on the network, not a local server
|
|
148
149
|
# @param first_token_timeout [Numeric, nil] seconds a streamed answer
|
|
149
150
|
# may take to show something (LLM::HTTP); nil: no limit
|
|
151
|
+
# @param stream_idle_timeout [Numeric, nil] seconds a streamed answer
|
|
152
|
+
# that showed something may go without more (LLM::HTTP); nil: no limit
|
|
150
153
|
# @param default_max_tokens [Integer, nil] max_tokens for a request
|
|
151
154
|
# whose options name none (OPENROUTER_MAX_TOKENS); nil sends none
|
|
152
155
|
def initialize(base_url:, host_name:, api_key_env: nil, auth: nil, stream: true, retries: true, timeout: nil,
|
|
153
156
|
env: ENV, sleeper: nil, retry_policy: nil, models_ttl: DEFAULT_MODELS_TTL, remote: false,
|
|
154
|
-
first_token_timeout: nil, purpose: "chat", default_max_tokens: nil,
|
|
157
|
+
first_token_timeout: nil, stream_idle_timeout: nil, purpose: "chat", default_max_tokens: nil,
|
|
158
|
+
open_timeout: nil)
|
|
155
159
|
@remote = remote
|
|
156
160
|
@default_max_tokens = default_max_tokens
|
|
157
161
|
# What its requests are for, in the log (LLM::HTTP::LOGGED_PURPOSES).
|
|
158
162
|
@purpose = purpose
|
|
159
163
|
@first_token_timeout = first_token_timeout
|
|
164
|
+
@stream_idle_timeout = stream_idle_timeout
|
|
160
165
|
@base_url = base_url.to_s.chomp("/")
|
|
161
166
|
@host_name = host_name.to_s
|
|
162
167
|
@api_key_env = api_key_env
|
|
@@ -164,6 +169,7 @@ module Samagotchi
|
|
|
164
169
|
init_model_listing(models_ttl)
|
|
165
170
|
@http = build_http(timeout: timeout, open_timeout: open_timeout, retries: retries, retry_policy: retry_policy,
|
|
166
171
|
sleeper: sleeper, first_token_timeout: first_token_timeout,
|
|
172
|
+
stream_idle_timeout: stream_idle_timeout,
|
|
167
173
|
api_key: ApiKey.for(api_key_env, host: @host_name, env: env, scheme: auth))
|
|
168
174
|
end
|
|
169
175
|
|
|
@@ -189,7 +195,11 @@ module Samagotchi
|
|
|
189
195
|
stream_assembled(request, cancel_controller, on_retry, log_fields, assembly_class: Assembly,
|
|
190
196
|
what: "stream chunk") do |assembly, payload, shown|
|
|
191
197
|
content, reasoning = assembly.add(payload)
|
|
192
|
-
|
|
198
|
+
if !content.empty? || !reasoning.empty? || Assembly.tool_call_delta?(payload)
|
|
199
|
+
shown.call
|
|
200
|
+
elsif Assembly.ending?(payload)
|
|
201
|
+
shown.call(ending: true)
|
|
202
|
+
end
|
|
193
203
|
on_delta&.call(content: content, reasoning: reasoning, payload: payload)
|
|
194
204
|
end
|
|
195
205
|
end
|
|
@@ -343,6 +353,13 @@ module Samagotchi
|
|
|
343
353
|
choice.is_a?(Hash) && choice["delta"].is_a?(Hash) && !Array(choice["delta"]["tool_calls"]).empty?
|
|
344
354
|
end
|
|
345
355
|
|
|
356
|
+
# The chunk ends the answer (a finish reason, the usage): it restarts
|
|
357
|
+
# the stream-idle clock without counting as shown.
|
|
358
|
+
def self.ending?(payload)
|
|
359
|
+
choice = payload["choices"].is_a?(Array) ? payload["choices"].first : nil
|
|
360
|
+
payload["usage"].is_a?(Hash) || (choice.is_a?(Hash) && !choice["finish_reason"].nil?)
|
|
361
|
+
end
|
|
362
|
+
|
|
346
363
|
def initialize
|
|
347
364
|
@text = +""
|
|
348
365
|
@reasoning = +""
|
|
@@ -82,7 +82,7 @@ module Samagotchi
|
|
|
82
82
|
def self.digest_or_nil(digest) = digest == :unreadable ? nil : digest
|
|
83
83
|
private_class_method :digest_or_nil
|
|
84
84
|
|
|
85
|
-
# Each recorded rule or script: "missing" (not there), "modified" (its
|
|
85
|
+
# Each recorded rule or script: "unrecorded" (no sha256), "missing" (not there), "modified" (its
|
|
86
86
|
# AssetState is edited: the next install replaces it, a copy kept in
|
|
87
87
|
# the trash; an edited rule doesn't load) or "ok"; {} for none.
|
|
88
88
|
# @return [Hash{String => String}]
|
|
@@ -90,6 +90,7 @@ module Samagotchi
|
|
|
90
90
|
recorded.keys.sort.to_h do |name|
|
|
91
91
|
asset = AssetState.of(File.join(dir, name), kind_of_file: kind_of_file, recorded: recorded[name], name: name)
|
|
92
92
|
[name, if asset.state == :missing then "missing"
|
|
93
|
+
elsif recorded[name].to_s.empty? then "unrecorded"
|
|
93
94
|
elsif asset.edited? then "modified"
|
|
94
95
|
else "ok"
|
|
95
96
|
end]
|
|
@@ -113,17 +114,20 @@ module Samagotchi
|
|
|
113
114
|
"needs #{need[:command]}#{why} #{state}#{hint}"
|
|
114
115
|
end
|
|
115
116
|
|
|
117
|
+
# A plugin's state word in `chi bundle status`, by its file refusal's kind.
|
|
118
|
+
PLUGIN_STATES = { nil => "ok", file_unrecorded: "unrecorded", file_missing: "missing", file_changed: "modified" }.freeze
|
|
119
|
+
|
|
116
120
|
# The installed plugin: {file:, path:, state:, requires_chi:,
|
|
117
|
-
# requires_failure:}; state is "ok", "
|
|
118
|
-
#
|
|
119
|
-
#
|
|
120
|
-
# InstalledBundles::Standing). nil without one.
|
|
121
|
+
# requires_failure:}; state is "ok", "unrecorded" (no sha256 recorded
|
|
122
|
+
# for it), "missing" or "modified" (its sha256 differs from the
|
|
123
|
+
# installed one), from the verdict (Dir#file_refusal(:plugin),
|
|
124
|
+
# InstalledBundles::Standing): any but "ok" won't load. nil without one.
|
|
121
125
|
def self.plugin_status(provenance, bundle)
|
|
122
126
|
path = provenance.plugin_path(bundle)
|
|
123
127
|
return nil unless path
|
|
124
128
|
|
|
125
129
|
refusal = provenance.file_refusal(:plugin, bundle.plugin.file, bundle.plugin.sha256)
|
|
126
|
-
state =
|
|
130
|
+
state = PLUGIN_STATES.fetch(refusal&.kind)
|
|
127
131
|
standing = InstalledBundles::Standing.of(provenance.name, bundle)
|
|
128
132
|
{ file: File.basename(path), path: path, state: state, requires_chi: bundle.manifest.requires_chi,
|
|
129
133
|
requires_failure: standing.too_new? ? standing.refusal.text : nil }
|
|
@@ -171,6 +171,10 @@ module Samagotchi
|
|
|
171
171
|
# Nothing was ever set.
|
|
172
172
|
def empty? = items.empty?
|
|
173
173
|
|
|
174
|
+
# Something still meant: an active or a done objective (an
|
|
175
|
+
# only-dropped list has none).
|
|
176
|
+
def meant? = items.any? { |item| item.status != DROPPED }
|
|
177
|
+
|
|
174
178
|
def find(id) = items.find { |item| item.id == id }
|
|
175
179
|
|
|
176
180
|
# @param text [String]
|
|
@@ -402,13 +406,14 @@ module Samagotchi
|
|
|
402
406
|
end
|
|
403
407
|
|
|
404
408
|
# A continue's copy: +previous+'s list as a note file in the new link,
|
|
405
|
-
# read fresh, its unabsorbed newest file included
|
|
409
|
+
# read fresh, its unabsorbed newest file included; a list with nothing
|
|
410
|
+
# active or done (List#meant?) isn't carried. It runs inside the
|
|
406
411
|
# continue's rollback, and a link without the list is still a good link:
|
|
407
412
|
# a failure is logged.
|
|
408
413
|
# @return [String, nil] the note file's path
|
|
409
414
|
def carry(previous, to:, state_dir:)
|
|
410
415
|
list = current(previous.id, Session.load(previous.id, state_dir: state_dir).messages, state_dir: state_dir)
|
|
411
|
-
return nil
|
|
416
|
+
return nil unless list.meant?
|
|
412
417
|
|
|
413
418
|
SessionInbox.write_note(to, text: list.text, source: SOURCE, objectives: list.to_payload, state_dir: state_dir)
|
|
414
419
|
rescue StandardError => e
|
|
@@ -26,6 +26,8 @@ module Samagotchi
|
|
|
26
26
|
# The kind a deleter holds the lock as while a session's files go.
|
|
27
27
|
DELETING = "deleting"
|
|
28
28
|
RETRY_INTERVAL = 0.05
|
|
29
|
+
# Let a delete retry past an owner's momentary shared-lock probe.
|
|
30
|
+
PROBE_WAIT = 2 * RETRY_INTERVAL
|
|
29
31
|
OWNER_READ_ATTEMPTS = 10
|
|
30
32
|
# Seconds .await_release waits past a leaving worker's own budget: its
|
|
31
33
|
# last save, the task watch's absorb, its exit.
|
|
@@ -161,7 +161,10 @@ module Samagotchi
|
|
|
161
161
|
# command) and cwd:, each optional
|
|
162
162
|
# @param refs [#call, nil] args → the call's row's refs, display only:
|
|
163
163
|
# a list of {kind:, target:, label:, actions:} (RowRefs, Ref). Run
|
|
164
|
-
# once per call on the tool path, so it must be cheap (no I/O)
|
|
164
|
+
# once per call on the tool path, so it must be cheap (no I/O). One
|
|
165
|
+
# that takes two args, (args, tool_id), gets the run's id too (nil
|
|
166
|
+
# when it has none): the block reads the same one as ctx.tool_id,
|
|
167
|
+
# so an id made from it is the row's and the handler's alike
|
|
165
168
|
def tool(name, description, **, &)
|
|
166
169
|
spec = ToolSpec.build(name, description, **, &)
|
|
167
170
|
if (taken = @registries.tools[spec.name])
|
|
@@ -8,6 +8,7 @@ require_relative "../session_metrics/usage"
|
|
|
8
8
|
require_relative "../guardrails/context"
|
|
9
9
|
require_relative "../hook_question"
|
|
10
10
|
require_relative "../idle_client"
|
|
11
|
+
require_relative "../tool_ids"
|
|
11
12
|
require_relative "../cache_confirm"
|
|
12
13
|
require_relative "service"
|
|
13
14
|
require_relative "side_question"
|
|
@@ -172,6 +173,14 @@ module Samagotchi
|
|
|
172
173
|
# @return [String, nil] the session's id (nil before the first one)
|
|
173
174
|
def session_id = @host.session_id.call
|
|
174
175
|
|
|
176
|
+
# The id of the tool run whose handler runs now (chi's ToolIds,
|
|
177
|
+
# "t41"), the one the tool's two-arg refs: lambda got for its row:
|
|
178
|
+
# what ties a row to what the handler did. Only on the handler's own
|
|
179
|
+
# thread while it runs; nil elsewhere (a hook, a command, a thread
|
|
180
|
+
# the handler started) and for a run with no id.
|
|
181
|
+
# @return [String, nil]
|
|
182
|
+
def tool_id = ToolIds.current
|
|
183
|
+
|
|
175
184
|
# @api private
|
|
176
185
|
# The session store's root, as used by the host.
|
|
177
186
|
def session_state_dir = @host.state_dir&.call || Session.default_state_dir
|
|
@@ -4,6 +4,7 @@ require "digest"
|
|
|
4
4
|
require "fileutils"
|
|
5
5
|
require "json"
|
|
6
6
|
require "open3"
|
|
7
|
+
require "securerandom"
|
|
7
8
|
require "tempfile"
|
|
8
9
|
require "time"
|
|
9
10
|
require_relative "../paths"
|
|
@@ -25,8 +26,9 @@ module Samagotchi
|
|
|
25
26
|
# part inline, or a long one's file under the bundle's data dir
|
|
26
27
|
# (sessions/<id>/, removed with the session), named in the message
|
|
27
28
|
# (`payload: <path>`). The tool's row carries the same id as a `peer`
|
|
28
|
-
# ref (derived from the call's args, so it is
|
|
29
|
-
# runs: also on a send that then didn't happen
|
|
29
|
+
# ref (derived from the call's args and its run's tool id, so it is
|
|
30
|
+
# there before the call runs: also on a send that then didn't happen;
|
|
31
|
+
# an equal resend is a run of its own, so an id of its own). The tool is declared whether or not the peer is
|
|
30
32
|
# paired, so pairing never changes the tools (no prompt rebuild); without
|
|
31
33
|
# a paired peer it fails with how to pair.
|
|
32
34
|
#
|
|
@@ -91,21 +93,30 @@ module Samagotchi
|
|
|
91
93
|
end
|
|
92
94
|
|
|
93
95
|
# A send's id, from what the caller gave (before the title is cut):
|
|
94
|
-
# `s-` and 6 hex of SHA-256 over +kind+, +title+ and +
|
|
95
|
-
#
|
|
96
|
-
#
|
|
97
|
-
|
|
96
|
+
# `s-` and 6 hex of SHA-256 over +kind+, +title+, +text+ and +salt+,
|
|
97
|
+
# the send's own: the tool's run id (its row's ref is computed before
|
|
98
|
+
# the call runs, so from the args and the run, ctx.tool_id), a random
|
|
99
|
+
# one for a /<peer> command's. A nil +salt+ is the id over the three
|
|
100
|
+
# alone, what a send before 0.181.0 got (and a run with no id): its
|
|
101
|
+
# log and answers still name it. The peer's answer names it (`re`).
|
|
102
|
+
def self.send_id(kind, title, text, salt = nil)
|
|
103
|
+
parts = salt.nil? ? [kind, title, text] : [kind, title, text, salt.to_s]
|
|
104
|
+
"s-#{Digest::SHA256.hexdigest(parts.join("\0"))[0, 6]}"
|
|
105
|
+
end
|
|
98
106
|
|
|
99
107
|
def register(chi)
|
|
100
108
|
peer = self.class
|
|
101
|
-
|
|
102
|
-
|
|
109
|
+
# Two args: the run's tool id salts the send id, the same one the
|
|
110
|
+
# block's deliver gets (ctx.tool_id).
|
|
111
|
+
refs = lambda do |args, tool_id = nil|
|
|
112
|
+
id = Peer.send_id(args["kind"].to_s, args["title"].to_s, args["text"].to_s, tool_id)
|
|
103
113
|
[{ kind: "peer", target: { id: id }, label: "#{peer::NAME} · #{args["kind"].to_s[0, 40]}" }]
|
|
104
114
|
end
|
|
105
115
|
chi.tool peer::TOOL, peer::TOOL_DESCRIPTION, params: peer::TOOL_PARAMS, label: "sent to #{peer::NAME}",
|
|
106
116
|
preview: ->(args) { "#{args["kind"]}: #{args["title"]}" },
|
|
107
117
|
refs: refs do |args, ctx|
|
|
108
|
-
sent = deliver(ctx, kind: args["kind"].to_s, title: args["title"].to_s, text: args["text"].to_s
|
|
118
|
+
sent = deliver(ctx, kind: args["kind"].to_s, title: args["title"].to_s, text: args["text"].to_s,
|
|
119
|
+
salt: ctx.tool_id)
|
|
109
120
|
"#{sent}. #{follow_up(args["kind"].to_s)}"
|
|
110
121
|
rescue SendError => e
|
|
111
122
|
"Error: #{e.message}"
|
|
@@ -132,18 +143,19 @@ module Samagotchi
|
|
|
132
143
|
end
|
|
133
144
|
|
|
134
145
|
# Sends +text+ to the paired peer: the header, the `ref:` line
|
|
135
|
-
# (.send_id of the args as given
|
|
136
|
-
#
|
|
146
|
+
# (.send_id of the args as given and +salt+: the tool row's, so the
|
|
147
|
+
# row and the line name the same send), then the text inline or a
|
|
148
|
+
# payload file's path. Records it as the last send, with its id.
|
|
137
149
|
# @return [String] what was sent ("sent to Claude: validate · title")
|
|
138
150
|
# @raise [SendError]
|
|
139
|
-
def deliver(ctx, kind:, title:, text:, by: "model")
|
|
151
|
+
def deliver(ctx, kind:, title:, text:, by: "model", salt: nil)
|
|
140
152
|
raise SendError, "kind must be one of #{KINDS.join(", ")}" unless KINDS.include?(kind)
|
|
141
153
|
raise SendError, "nothing to send: the text is empty" if text.strip.empty?
|
|
142
154
|
if text.length > MAX_CHARS
|
|
143
155
|
raise SendError, "the text is #{text.length} chars, over #{MAX_CHARS}: send a part, not a session"
|
|
144
156
|
end
|
|
145
157
|
|
|
146
|
-
send_id = Peer.send_id(kind, title, text)
|
|
158
|
+
send_id = Peer.send_id(kind, title, text, salt)
|
|
147
159
|
id = ctx.session_id or raise SendError, "this session has no id yet: send after its first turn"
|
|
148
160
|
hint = peer_hint!(ctx)
|
|
149
161
|
title = one_line(title.strip.empty? ? text.strip.lines.first : title)
|
|
@@ -249,12 +261,16 @@ module Samagotchi
|
|
|
249
261
|
end
|
|
250
262
|
|
|
251
263
|
def send_text(ctx, kind, text)
|
|
252
|
-
"#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user")}; #{self.class::NAME}'s answer comes as the " \
|
|
264
|
+
"#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user", salt: command_salt)}; #{self.class::NAME}'s answer comes as the " \
|
|
253
265
|
"#{self.class::OUTBOX} context"
|
|
254
266
|
rescue SendError => e
|
|
255
267
|
"#{self.class::COMMAND}: #{e.message}"
|
|
256
268
|
end
|
|
257
269
|
|
|
270
|
+
# A /<peer> command send's salt (.send_id): it has no tool row to agree
|
|
271
|
+
# with, so a random one keeps an equal resend's id its own.
|
|
272
|
+
def command_salt = SecureRandom.hex(4)
|
|
273
|
+
|
|
258
274
|
# A typed text's title: its first line, past a web quote's label line
|
|
259
275
|
# (`From your thinking:`) and the `> ` of a quoted line.
|
|
260
276
|
def text_title(text)
|
|
@@ -268,7 +284,8 @@ module Samagotchi
|
|
|
268
284
|
command = self.class::COMMAND
|
|
269
285
|
return "#{command} last: no completed answer to send yet (the last turn has none); #{command} context <text> sends a text" unless answer
|
|
270
286
|
|
|
271
|
-
deliver(ctx, kind: "context", title: "chi's last answer: #{answer.strip.lines.first}", text: answer, by: "user"
|
|
287
|
+
deliver(ctx, kind: "context", title: "chi's last answer: #{answer.strip.lines.first}", text: answer, by: "user",
|
|
288
|
+
salt: command_salt)
|
|
272
289
|
rescue SendError => e
|
|
273
290
|
"#{command}: #{e.message}"
|
|
274
291
|
end
|