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
@@ -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
- shown = lambda do
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] ||= monotonic_now
183
+ current[:first_shown_at] ||= now
164
184
  end
165
- watch_first_token(current) do
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 limit: a watchdog
316
- # thread closes the attempt's socket when the limit passes before
317
- # anything was shown, so the read fails and #with_retries raises
318
- # FirstTokenTimeout; while still connecting, it raises that in the
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 watch_first_token(current)
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
- sleep(@first_token_timeout)
327
- current[:mutex].synchronize do
328
- next if current[:streamed] || current[:attempt_over] || current[:done]
329
-
330
- current[:first_token_expired] = true
331
- # No Net::HTTP yet: still connecting. One whose socket is closed
332
- # has finished, and the attempt returns on its own.
333
- if current[:http]
334
- socket_io(current[:http])&.close
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, :default_max_tokens
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, open_timeout: 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
- shown.call if !content.empty? || !reasoning.empty? || Assembly.tool_call_delta?(payload)
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 = +""
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # The optional commonmarker gem (the Gemfile's :markdown group), loaded on
5
+ # first need by whoever parses an answer's markdown: the web's render
6
+ # (Web::MarkdownRenderer) and the worker's block fixes (BlockFix.locate), so
7
+ # both read a block the same way. Loading it once is enough for the process.
8
+ module MarkdownParser
9
+ @mutex = Mutex.new
10
+ @available = nil
11
+
12
+ class << self
13
+ # Whether ::Commonmarker is loaded (it is required on the first call).
14
+ def available?
15
+ @mutex.synchronize do
16
+ return @available unless @available.nil?
17
+
18
+ @available = begin
19
+ require "commonmarker"
20
+ true
21
+ rescue LoadError
22
+ false
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -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]
@@ -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. It runs inside the
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 if list.empty?
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 there before the call
29
- # runs: also on a send that then didn't happen). The tool is declared whether or not the peer is
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 +text+. Equal
95
- # args give the same id (the tool row's ref is computed from them
96
- # before the call runs); the peer's answer names it (`re`).
97
- def self.send_id(kind, title, text) = "s-#{Digest::SHA256.hexdigest([kind, title, text].join("\0"))[0, 6]}"
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
- refs = lambda do |args|
102
- id = Peer.send_id(args["kind"].to_s, args["title"].to_s, args["text"].to_s)
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), then the text inline or a payload
136
- # file's path. Records it as the last send, with its id.
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
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "json"
4
4
  require_relative "../tools/args"
5
+ require_relative "../row_refs"
5
6
 
6
7
  module Samagotchi
7
8
  module Plugin
@@ -137,7 +138,8 @@ module Samagotchi
137
138
 
138
139
  # Registry#register's keywords for it: its block wrapped as a handler
139
140
  # (typed args, the Context), preview, targets (in the entry's form,
140
- # (call, surface): a plugin's reads the call only), refs (call only).
141
+ # (call, surface): a plugin's reads the call only), refs ((call,
142
+ # tool_id): a plugin's two-arg refs: lambda gets the run's id too).
141
143
  def entry_fields(context)
142
144
  block = self.block
143
145
  parameters = schema[:parameters]
@@ -151,7 +153,7 @@ module Samagotchi
151
153
  },
152
154
  preview: preview && ->(call, _surface = nil) { preview.call(call)&.to_s },
153
155
  targets: targets && ->(call, _surface = nil) { targets.call(call) },
154
- refs: per_call(refs, parameters)
156
+ refs: refs_per_call(parameters)
155
157
  }
156
158
  end
157
159
 
@@ -163,6 +165,15 @@ module Samagotchi
163
165
  def per_call(fn, parameters)
164
166
  fn && ->(call) { fn.call(ToolSpec.args_of(call, parameters)) }
165
167
  end
168
+
169
+ # The refs: lambda as (call, tool_id) → refs: one that takes two args
170
+ # (args, tool_id) gets the run's id (ToolIds, nil when the run has
171
+ # none), the one its handler reads as ctx.tool_id; a one-arg one the
172
+ # args only (RowRefs.call_with_id).
173
+ def refs_per_call(parameters)
174
+ fn = refs
175
+ fn && ->(call, tool_id = nil) { RowRefs.call_with_id(fn, ToolSpec.args_of(call, parameters), tool_id) }
176
+ end
166
177
  end
167
178
  end
168
179
  end
@@ -27,17 +27,20 @@ module Samagotchi
27
27
  module_function
28
28
 
29
29
  # Runs +fn+ (the tool's refs: lambda, as ToolSpec#per_call wraps it: call →
30
- # a list of {kind:, target:, label:, actions:}) on +call+. Never
30
+ # a list of {kind:, target:, label:, actions:}) on +call+, and on
31
+ # +tool_id+ too when it takes two args (#call_with_id). Never
31
32
  # raises: a lambda that raises or returns something other than a list
32
33
  # gives none, and a bad ref is dropped; both are logged (warn, not
33
34
  # echoed: the turn's live region is on screen).
34
35
  # @param cwd [String, nil] the session's folder
36
+ # @param tool_id [String, nil] the run's id (ToolIds), the one its
37
+ # handler reads (ToolIds.current, a plugin's ctx.tool_id)
35
38
  # @return [Array<Hash>] Ref#to_h each, deduped, at most MAX_REFS
36
- def for(fn, call, cwd:)
39
+ def for(fn, call, cwd:, tool_id: nil)
37
40
  return [] unless fn
38
41
 
39
42
  tool = call[:name].to_s
40
- raw = fn.call(call)
43
+ raw = call_with_id(fn, call, tool_id)
41
44
  return [] if raw.nil?
42
45
  raise ArgumentError, "refs: returned #{raw.class}, not a list" unless raw.is_a?(Array)
43
46
 
@@ -47,6 +50,14 @@ module Samagotchi
47
50
  []
48
51
  end
49
52
 
53
+ # +fn+ on +first+, and on +tool_id+ too when it takes two args (arity
54
+ # 2, or one required and more optional): a one-arg lambda is called as
55
+ # before. ToolSpec's refs: wrapper and #for share it.
56
+ def call_with_id(fn, first, tool_id)
57
+ arity = fn.respond_to?(:arity) ? fn.arity : fn.method(:call).arity
58
+ arity >= 2 || arity <= -2 ? fn.call(first, tool_id) : fn.call(first)
59
+ end
60
+
50
61
  # Stored refs (+raw+, a saved tool_refs entry), each rebuilt and
51
62
  # checked again as #for checks a lambda's: a stored file is never
52
63
  # trusted. What isn't valid any more is dropped, a relative path too
@@ -121,6 +121,9 @@ module Samagotchi
121
121
  "sessions delete --force" => SUPPORTED,
122
122
  "sessions delete --chain" => SUPPORTED,
123
123
  "sessions delete --stop-tasks" => SUPPORTED,
124
+ # A chi web without delete_plan_all (Remote#delete_plan checks its
125
+ # feature) refuses with RemoteTooOld, nothing deleted.
126
+ "sessions delete --dry-run" => SUPPORTED,
124
127
  "sessions prune" => LOCAL_ONLY,
125
128
  "sessions clean" => LOCAL_ONLY,
126
129
  "sessions stats" => LOCAL_ONLY,
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Samagotchi
6
+ # Loaded on first use: RunningTasks::Listing.from_wire reads the tasks.
7
+ autoload :SessionManager, File.expand_path("../session_manager", __dir__)
8
+
9
+ module SessionAccess
10
+ # A session's delete plan (SessionChain::Delete::Preview, GET
11
+ # /api/sessions/:id/delete_plan) as chi sessions delete --dry-run reads
12
+ # it, on either backend: Local's hash has symbol keys, the route's JSON
13
+ # string keys, and both are read here only (#read). Each choice says
14
+ # what goes, what is stopped first and what stays (docs/sessions.md,
15
+ # Deleting a link).
16
+ module DeletePlan
17
+ # +chained+ false: no +position+, +size+ or +chain+.
18
+ Plan = Data.define(:session_id, :chained, :position, :size, :link, :chain)
19
+
20
+ # One choice (the link, or the whole chain): +delete+ the delegates'
21
+ # ids that go with it, +leave+ the ones left (Left), +tasks+ the
22
+ # running tasks its delete would meet (RunningTasks::Listing),
23
+ # +workers+ how many of its sessions have a worker and +turns+ how
24
+ # many of those run a turn, +links+ the links it deletes (1 for a
25
+ # link), +previous_id+ the link its undo brings back (nil: none),
26
+ # +moved+ the sessions that go back with it, +refusal+ (Refusal, nil
27
+ # when it can go now).
28
+ Choice = Data.define(:delete, :leave, :tasks, :workers, :turns, :links, :previous_id, :moved, :refusal)
29
+
30
+ # A session the choice leaves: +running+ false for a stopped one left
31
+ # under a running delegate (it stays with it).
32
+ Left = Data.define(:id, :running)
33
+
34
+ # Why the delete can't happen now: +reason+ the refusal's code
35
+ # ("scheduled", "owned_by_tui", …), +message+ its words.
36
+ Refusal = Data.define(:reason, :message)
37
+
38
+ module_function
39
+
40
+ # @param plan [Hash] Preview.call's (symbol keys) or the route's
41
+ # parsed JSON (string keys)
42
+ # @return [Plan]
43
+ def read(plan)
44
+ json = JSON.parse(JSON.generate(plan))
45
+ Plan.new(session_id: json["session_id"].to_s, chained: json["chained"] == true, position: json["position"],
46
+ size: json["size"], link: choice(json["link"], links: 1),
47
+ chain: (choice(json["chain"], links: json.dig("chain", "links").to_i) if json["chain"].is_a?(Hash)))
48
+ end
49
+
50
+ def choice(json, links:)
51
+ json = {} unless json.is_a?(Hash)
52
+ delegates = json["delegates"].is_a?(Hash) ? json["delegates"] : {}
53
+ workers, turns = worker_counts(json["worker"])
54
+ Choice.new(delete: Array(delegates["delete"]).map(&:to_s),
55
+ leave: Array(delegates["leave"]).map { |left| Left.new(id: left["id"].to_s, running: left["running"] == true) },
56
+ tasks: SessionManager::RunningTasks::Listing.from_wire(json["tasks"]),
57
+ workers: workers, turns: turns, links: links, previous_id: json["previous_id"],
58
+ moved: json["moved"].to_i, refusal: refusal(json["refusal"]))
59
+ end
60
+
61
+ # A link's "turn" / "idle" / nil, a chain's {idle: n, turn: n}.
62
+ # @return [Array(Integer, Integer)] workers, turns
63
+ def worker_counts(worker)
64
+ case worker
65
+ when "turn" then [1, 1]
66
+ when "idle" then [1, 0]
67
+ when Hash then [worker["idle"].to_i + worker["turn"].to_i, worker["turn"].to_i]
68
+ else [0, 0]
69
+ end
70
+ end
71
+
72
+ def refusal(json)
73
+ Refusal.new(reason: json["reason"].to_s, message: json["message"].to_s) if json.is_a?(Hash)
74
+ end
75
+ end
76
+ end
77
+ end