samagotchi 0.181.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 (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +26 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +30 -4
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/block-renderers.md +114 -0
  8. data/docs/internals/bridge.md +10 -0
  9. data/docs/internals/engine.md +11 -0
  10. data/docs/internals/inline-widgets.md +3 -1
  11. data/docs/internals/prompt-caching.md +9 -1
  12. data/docs/internals/remote-sessions.md +14 -2
  13. data/docs/internals/web-frontend.md +33 -3
  14. data/docs/sessions.md +7 -4
  15. data/lib/samagotchi/answer_display.rb +3 -2
  16. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  17. data/lib/samagotchi/block_fix.rb +220 -0
  18. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  19. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  20. data/lib/samagotchi/bridge.rb +11 -2
  21. data/lib/samagotchi/bridge_client.rb +9 -0
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/config.rb +3 -0
  24. data/lib/samagotchi/continue_intent.rb +8 -0
  25. data/lib/samagotchi/engine/block_fix.rb +332 -0
  26. data/lib/samagotchi/engine/side_requests.rb +7 -5
  27. data/lib/samagotchi/engine.rb +4 -0
  28. data/lib/samagotchi/events.rb +1 -0
  29. data/lib/samagotchi/idle_client.rb +10 -6
  30. data/lib/samagotchi/inline_widgets.rb +12 -0
  31. data/lib/samagotchi/kernel_loop.rb +7 -5
  32. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  33. data/lib/samagotchi/markdown_parser.rb +28 -0
  34. data/lib/samagotchi/session_access/contract.rb +3 -0
  35. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  36. data/lib/samagotchi/session_access/local.rb +13 -0
  37. data/lib/samagotchi/session_access/remote.rb +19 -1
  38. data/lib/samagotchi/session_access.rb +1 -0
  39. data/lib/samagotchi/session_chain/delete.rb +39 -81
  40. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  41. data/lib/samagotchi/session_delete_command.rb +129 -3
  42. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  43. data/lib/samagotchi/session_manager/listing.rb +4 -4
  44. data/lib/samagotchi/session_manager/removal.rb +38 -12
  45. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  46. data/lib/samagotchi/session_manager.rb +1 -0
  47. data/lib/samagotchi/version.rb +1 -1
  48. data/lib/samagotchi/web/app.rb +13 -1
  49. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  50. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  51. data/lib/samagotchi/web/message_display.rb +6 -1
  52. data/lib/samagotchi/web/participant_view.rb +1 -1
  53. data/lib/samagotchi/web/public/app.js +5 -5
  54. data/lib/samagotchi/web/public/block_fix.js +270 -0
  55. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  56. data/lib/samagotchi/web/public/block_frame.js +6 -3
  57. data/lib/samagotchi/web/public/block_host.js +1 -1
  58. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  59. data/lib/samagotchi/web/public/block_watch.js +16 -2
  60. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  61. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  62. data/lib/samagotchi/web/public/turn_block.js +5 -2
  63. data/lib/samagotchi/web/server.rb +6 -4
  64. data/lib/samagotchi/web/session_control.rb +53 -21
  65. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  66. data/lib/samagotchi/worker.rb +10 -3
  67. metadata +12 -1
@@ -0,0 +1,332 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../answer_display"
4
+ require_relative "../answer_tail"
5
+ require_relative "../block_fix"
6
+ require_relative "../bridge/turn_drawings"
7
+ require_relative "../log"
8
+
9
+ module Samagotchi
10
+ class Engine
11
+ # A failed block asked for again (docs/internals/block-renderers.md, A
12
+ # failed block is asked for again). #fix_block answers the Bridge's
13
+ # route and starts the side request; its result waits in
14
+ # @block_fix_ready until the worker's loop, between turns, calls
15
+ # #apply_block_fixes, which writes the conversation: the answer's text
16
+ # when no turn started since the ask and it is still the newest answer,
17
+ # else its display only, or nothing when the answer is gone.
18
+ # Writes @block_fix_running, @block_fix_ready, @block_fix_turns (under
19
+ # @block_fix_mutex; the counter on the turn thread), reads @session,
20
+ # @side_judgments, @session_observer.
21
+ module BlockFixPart
22
+ # What a pending result knows of its answer: its place in the
23
+ # conversation, its digest then (Bridge::TurnDrawings.digest), and the
24
+ # turn counter then (nil: a turn was running as it was asked).
25
+ Anchor = Data.define(:index, :digest, :turns)
26
+ MOVED_DIGEST_LIMIT = 64
27
+ # A finished ask: +fixed+ (the new source) or +reason+ (why not).
28
+ Result = Data.define(:turn_id, :lang, :key, :source, :fixed, :reason, :anchor, :started) do
29
+ def fixed? = !fixed.nil?
30
+ end
31
+
32
+ # The worker's wake (Waker#wake), called once a result waits: an idle
33
+ # worker applies it at once. nil (the default): nothing is woken.
34
+ def block_fix_ready=(callback)
35
+ @block_fix_wake = callback
36
+ end
37
+
38
+ # The Bridge's POST blocks/fix: whether +source+, a +lang+ block of
39
+ # +turn_id+'s answer, is asked for again.
40
+ # @return [Array(Integer, Hash)] the status and the body: 200
41
+ # {state: "fixed" | "failed", reason:} (asked before), 202
42
+ # {state: "running"}, or an error ({error:, detail:}: 409
43
+ # fix_unavailable / block_not_found, 413 block_too_large, 429
44
+ # fix_limit (BlockFix::PER_ANSWER) / fix_busy)
45
+ def fix_block(turn_id:, lang:, source:, reason:)
46
+ session = @session
47
+ return block_fix_refused(409, :fix_unavailable) if session.nil? || session.scratch || !BlockFix.available?
48
+ return block_fix_refused(413, :block_too_large) if source.to_s.bytesize > BlockFix::MAX_SOURCE_BYTES
49
+
50
+ # The counter before the running flag: a turn sets the flag, then
51
+ # counts (#note_block_fix_turn), so one starting between the reads
52
+ # still shows as a change. The running turn ending with this answer
53
+ # (the page asks on its end event, before its hooks are done) is no
54
+ # turn since; any other running turn is.
55
+ turns = @block_fix_turns
56
+ turns = nil if turn_running? && turn_context&.id.to_s != turn_id.to_s
57
+ messages = session.messages
58
+ answer = AnswerTail.find(messages, turn_id: turn_id)
59
+ index = answer && messages.index { |message| message.equal?(answer) }
60
+ return block_fix_refused(409, :block_not_found) unless index
61
+
62
+ key = BlockFix.key(lang, source)
63
+ shown = !BlockFix.locate(block_fix_shown(answer), lang: lang, source: source).nil?
64
+ # The stamp before the text: a page that drew the answer before its
65
+ # fix (a second tab) asks for a block no longer in it, and is told
66
+ # fixed (it reads the answer again).
67
+ known = BlockFix.stamp_for(answer, key)
68
+ return [200, block_fix_known(known, key, shown: shown)] if known
69
+ return block_fix_refused(409, :block_not_found) unless shown
70
+
71
+ # In flight per answer and block: the same block in a newer answer
72
+ # is that answer's own ask (its result lands in it, its event names it).
73
+ asking = [index, key]
74
+ @block_fix_mutex.synchronize do
75
+ return [202, { state: "running" }] if block_fix_pending?(asking)
76
+ return block_fix_refused(429, :fix_limit) if block_fix_asked(answer, index) >= BlockFix::PER_ANSWER
77
+ return block_fix_refused(429, :fix_busy) if @block_fix_running.size >= BlockFix::MAX_RUNNING
78
+
79
+ @block_fix_running << asking
80
+ end
81
+ anchor = Anchor.new(index: index, digest: Bridge::TurnDrawings.digest(answer), turns: turns)
82
+ conversation = AnswerDisplay.strip_all(messages[0..index])
83
+ Log.info(:model, "block_fix_asked", lang: lang, key: key, bytes: source.to_s.bytesize)
84
+ start_block_fix(conversation, turn_id: turn_id.to_s, lang: lang.to_s, key: key, source: source.to_s,
85
+ reason: reason.to_s, anchor: anchor)
86
+ [202, { state: "running" }]
87
+ end
88
+
89
+ # The results waiting, applied: on the worker's loop, between turns
90
+ # (a running turn holds its own copy of the conversation and writes it
91
+ # back at its end). The caller saves the session when this is > 0.
92
+ # @return [Integer] how many changed the conversation
93
+ def apply_block_fixes
94
+ return 0 if turn_running? || @session.nil?
95
+
96
+ ready = @block_fix_mutex.synchronize { @block_fix_ready.slice!(0..) }
97
+ return 0 if ready.empty?
98
+
99
+ synchronize_events { ready.count { |result| apply_block_fix(@session, result) } }
100
+ end
101
+
102
+ # The block fix's [answer index, key] pairs still asked for (specs).
103
+ def block_fixes_running = @block_fix_mutex.synchronize { @block_fix_running.dup }
104
+
105
+ private
106
+
107
+ def init_block_fix
108
+ @block_fix_mutex = Mutex.new
109
+ @block_fix_running = []
110
+ @block_fix_ready = []
111
+ @block_fix_turns = 0
112
+ @block_fix_wake = nil
113
+ # An answer's digest before a fix in its text => after (on the loop
114
+ # thread): the other block of the same answer, asked before that fix
115
+ # landed, still knows its answer.
116
+ @block_fix_moved = {}
117
+ end
118
+
119
+ # A turn takes its messages (#turn_messages): a fix asked before it
120
+ # lands in the answer's display only.
121
+ def note_block_fix_turn
122
+ @block_fix_turns += 1
123
+ end
124
+
125
+ # Whether [answer index, key] is asked for or its result waits (under
126
+ # @block_fix_mutex).
127
+ def block_fix_pending?(asking)
128
+ @block_fix_running.include?(asking) || @block_fix_ready.any? { |r| [r.anchor.index, r.key] == asking }
129
+ end
130
+
131
+ # How many blocks of the answer at +index+ were asked for: its stamp's
132
+ # and those in flight or waiting (under @block_fix_mutex). The stamp
133
+ # is on the message, so the count holds across a page's reload.
134
+ def block_fix_asked(answer, index)
135
+ keys = BlockFix.stamps(answer).map { |entry| entry[:key] }
136
+ keys += @block_fix_running.filter_map { |at, key| key if at == index }
137
+ keys += @block_fix_ready.filter_map { |r| r.key if r.anchor.index == index }
138
+ keys.uniq.size
139
+ end
140
+
141
+ def block_fix_refused(status, code)
142
+ [status, { error: code.to_s, detail: BlockFix::REFUSALS.fetch(code) }]
143
+ end
144
+
145
+ # A block the answer's stamp knows: asked before. A block that is the
146
+ # fix of an earlier one fails again: failed, whatever that fix was. A
147
+ # fixed block still +shown+ (a copy the fix couldn't reach) is failed
148
+ # too: "fixed" would have the page read the answer again, draw the
149
+ # copy, fail it and ask again, with no end.
150
+ def block_fix_known(entry, key, shown:)
151
+ return { state: "failed", reason: "it failed again after a fix" } if entry[:fixed_key] == key && entry[:key] != key
152
+ return { state: "failed", reason: "a copy of it is still in the answer" } if entry[:state].to_s == "fixed" && shown
153
+
154
+ { state: entry[:state].to_s, reason: entry[:reason] }.compact
155
+ end
156
+
157
+ # The text the page draws an answer from.
158
+ def block_fix_shown(message)
159
+ (message[AnswerDisplay::KEY] || message[AnswerDisplay::KEY.to_s] || message[:content] || message["content"]).to_s
160
+ end
161
+
162
+ def start_block_fix(conversation, **job)
163
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
164
+ warn = ->(error) { Log.warn(:model, "block_fix_thread_failed", error: error.class.name, msg: error.message.to_s[0, 200]) }
165
+ @side_judgments.aside(warn: warn) do
166
+ result = begin
167
+ ask_block_fix(conversation, **job, started: started)
168
+ rescue StandardError => e
169
+ Result.new(**job.except(:reason), started: started, fixed: nil,
170
+ reason: e.message.to_s.lines.first.to_s.strip[0, 200])
171
+ end
172
+ @block_fix_mutex.synchronize do
173
+ @block_fix_running.delete([job[:anchor].index, job[:key]])
174
+ @block_fix_ready << result
175
+ end
176
+ @block_fix_wake&.call
177
+ end
178
+ end
179
+
180
+ def ask_block_fix(conversation, turn_id:, lang:, key:, source:, reason:, anchor:, started:)
181
+ request = BlockFix.request(messages: conversation, lang: lang, source: source, reason: reason)
182
+ answer = ask_side_model(request, timeout: BlockFix::TIMEOUT_SECONDS, max_tokens: BlockFix::MAX_TOKENS,
183
+ cancel_controller: nil, source: BlockFix::SOURCE, whole: true)
184
+ extracted = BlockFix.extract(answer.text, cut_off: answer.cut_off, failed: source)
185
+ refusal = extracted.refusal || BlockFix.check(lang: lang, source: extracted.source)
186
+ Result.new(turn_id: turn_id, lang: lang, key: key, source: source, anchor: anchor, started: started,
187
+ fixed: refusal ? nil : extracted.source, reason: refusal)
188
+ end
189
+
190
+ # One result, under the event lock.
191
+ # @return [Boolean] whether the conversation changed
192
+ # A fix that can't land in an answer still there (its shown text lost
193
+ # the block, or the fix would pass the display's size) stamps it
194
+ # failed with the reason, so a reload doesn't ask again; only a gone
195
+ # or changed answer is dropped, with no stamp.
196
+ def apply_block_fix(session, result)
197
+ messages = session.messages
198
+ answer = messages[result.anchor.index]
199
+ return block_fix_dropped(result, "the answer changed") unless answer && block_fix_anchored?(messages, answer, result)
200
+
201
+ unless BlockFix.locate(block_fix_shown(answer), lang: result.lang, source: result.source)
202
+ result = result.with(fixed: nil, reason: "the answer changed")
203
+ end
204
+ copy, landed = block_fix_patched(messages, answer, result)
205
+ unless copy
206
+ result = result.with(fixed: nil, reason: "the fix is too long")
207
+ copy, landed = block_fix_patched(messages, answer, result)
208
+ end
209
+
210
+ list = messages.dup
211
+ list[result.anchor.index] = copy
212
+ replace_session_messages(session, list)
213
+ was = Bridge::TurnDrawings.digest(answer)
214
+ now = Bridge::TurnDrawings.digest(copy)
215
+ if was != now
216
+ @block_fix_moved.delete(was)
217
+ @block_fix_moved[was] = now
218
+ @block_fix_moved.shift while @block_fix_moved.size > MOVED_DIGEST_LIMIT
219
+ end
220
+ block_fix_announce(result, state: result.fixed? ? "fixed" : "failed", landed: landed, was_digest: was, digest: now)
221
+ true
222
+ end
223
+
224
+ # Still the message asked about: the same digest, and still the one
225
+ # the turn id names (a reminder turn's id names no prompt, so it falls
226
+ # back to the newest answer, which a later turn's answer becomes).
227
+ def block_fix_anchored?(messages, answer, result)
228
+ Bridge::TurnDrawings.digest(answer) == block_fix_digest_now(result.anchor.digest) &&
229
+ AnswerTail.find(messages, turn_id: result.turn_id).equal?(answer)
230
+ end
231
+
232
+ # +digest+ after the fixes that landed in its answer's text since.
233
+ def block_fix_digest_now(digest)
234
+ seen = []
235
+ while (moved = @block_fix_moved[digest]) && !seen.include?(digest)
236
+ seen << digest
237
+ digest = moved
238
+ end
239
+ digest
240
+ end
241
+
242
+ # The answer's copy with the fix (or, for a failed ask, only the stamp)
243
+ # and where it landed ("answer", "display", nil); nil copy: refused.
244
+ def block_fix_patched(messages, answer, result)
245
+ unless result.fixed?
246
+ entry = BlockFix.entry(key: result.key, state: "failed", reason: result.reason)
247
+ return [BlockFix.with_stamp(answer, entry), nil]
248
+ end
249
+
250
+ copy, landed = if result.anchor.turns == @block_fix_turns && AnswerTail.find(messages).equal?(answer)
251
+ block_fix_in_answer(answer, result)
252
+ else
253
+ block_fix_in_display(answer, result)
254
+ end
255
+ return [nil, nil] unless copy
256
+
257
+ entry = BlockFix.entry(key: result.key, fixed_key: BlockFix.key(result.lang, result.fixed), state: "fixed")
258
+ [BlockFix.with_stamp(copy, entry), landed]
259
+ end
260
+
261
+ # No turn since, the newest answer: its text (and its display, and
262
+ # on api: anthropic its saved blocks) holds the fix, in every copy of
263
+ # the block; nil copy: the display would pass its size.
264
+ def block_fix_in_answer(answer, result)
265
+ content = answer[:content].to_s
266
+ places = BlockFix.locate_all(content, lang: result.lang, source: result.source)
267
+ return block_fix_in_display(answer, result) if places.empty?
268
+
269
+ copy = answer.merge(content: BlockFix.replace_all(content, places, result.fixed))
270
+ if (display = answer[AnswerDisplay::KEY])
271
+ shown = BlockFix.locate_all(display, lang: result.lang, source: result.source)
272
+ text = shown.empty? ? display : BlockFix.replace_all(display, shown, result.fixed)
273
+ # The display's own cap (AnswerDisplay::MAX_CHARS), as #block_fix_in_display keeps it.
274
+ return [nil, nil] if text.length > AnswerDisplay::MAX_CHARS
275
+
276
+ copy[AnswerDisplay::KEY] = text
277
+ end
278
+ [block_fix_blocks(copy, result, places.size), "answer"]
279
+ end
280
+
281
+ # A turn since: only what the page renders (`display`), never what a
282
+ # model was sent.
283
+ def block_fix_in_display(answer, result)
284
+ shown = block_fix_shown(answer)
285
+ places = BlockFix.locate_all(shown, lang: result.lang, source: result.source)
286
+ return [nil, nil] if places.empty?
287
+
288
+ text = BlockFix.replace_all(shown, places, result.fixed)
289
+ return [nil, nil] if text.length > AnswerDisplay::MAX_CHARS
290
+
291
+ [answer.merge(AnswerDisplay::KEY => text), "display"]
292
+ end
293
+
294
+ # The saved Messages-API blocks (anthropic_content), which
295
+ # AnthropicWire sends as they are: the text blocks holding the
296
+ # +copies+ the text had patched, or the blocks dropped (the answer goes
297
+ # as its text) when they don't hold every copy whole. A thinking block
298
+ # is never touched.
299
+ def block_fix_blocks(copy, result, copies)
300
+ blocks = copy[:anthropic_content]
301
+ return copy unless blocks.is_a?(Array) && !blocks.empty?
302
+
303
+ found = 0
304
+ patched = blocks.map do |block|
305
+ next block if !block.is_a?(Hash) || (block["type"] || block[:type]).to_s != "text"
306
+
307
+ text_key = block.key?("text") ? "text" : :text
308
+ places = BlockFix.locate_all(block[text_key].to_s, lang: result.lang, source: result.source)
309
+ next block if places.empty?
310
+
311
+ found += places.size
312
+ block.merge(text_key => BlockFix.replace_all(block[text_key].to_s, places, result.fixed))
313
+ end
314
+ found == copies ? copy.merge(anthropic_content: patched) : copy.except(:anthropic_content)
315
+ end
316
+
317
+ def block_fix_dropped(result, why)
318
+ block_fix_announce(result, state: "dropped", landed: nil, reason: why)
319
+ false
320
+ end
321
+
322
+ def block_fix_announce(result, state:, landed:, reason: result.reason, was_digest: nil, digest: nil)
323
+ ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - result.started) * 1000).round
324
+ Log.info(:model, "block_fix_#{state}", lang: result.lang, key: result.key, bytes: result.fixed.to_s.bytesize,
325
+ ms: ms, landed: landed, reason: reason)
326
+ @session_observer.notify({ type: :block_fix, turn_id: result.turn_id, key: result.key, lang: result.lang,
327
+ state: state, landed: landed, reason: reason, was_digest: was_digest,
328
+ digest: digest }.compact)
329
+ end
330
+ end
331
+ end
332
+ end
@@ -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,
@@ -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"
@@ -1090,17 +1091,18 @@ module Samagotchi
1090
1091
  # +keep_thought_from+: model messages from this index on keep their
1091
1092
  # thought blocks (a resumed run's); nil strips every one.
1092
1093
  # A model message is rebuilt from an allow-list: `display`,
1093
- # `display_refs` and its wall time (MessageTime::KEY) ride along so the
1094
- # stored conversation keeps them; the prompt formatter never reads them
1095
- # (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).
1096
1097
  def sanitize_history(messages, keep_thought_from: nil)
1097
1098
  messages.each_with_index.map do |m, index|
1098
1099
  if m[:role] == "model" && keep_thought_from && index >= keep_thought_from
1099
1100
  { role: m[:role], content: m[:content].to_s, display: m[:display], display_refs: m[:display_refs],
1100
- MessageTime::KEY => m[MessageTime::KEY] }.compact
1101
+ BlockFix::STAMP => m[BlockFix::STAMP], MessageTime::KEY => m[MessageTime::KEY] }.compact
1101
1102
  elsif m[:role] == "model"
1102
1103
  { role: m[:role], content: strip_thought_blocks(m[:content].to_s), display: m[:display],
1103
- 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
1104
1106
  else
1105
1107
  m.dup
1106
1108
  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)
@@ -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
@@ -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
@@ -310,6 +310,19 @@ module Samagotchi
310
310
  SessionManager.delete_chain(id, stop: force, running_tasks: tasks_policy(stop_tasks), **dir)
311
311
  end
312
312
 
313
+ # What #delete (+chain+: #delete_chain) would do now, deleting
314
+ # nothing (chi sessions delete --dry-run): the web sheet's plan.
315
+ # A folder whose session file is gone has a plan too (chi web's
316
+ # route answers for it); neither on disk is no session.
317
+ # @return [DeletePlan::Plan]
318
+ # @raise [Session::NotFound]
319
+ def delete_plan(id)
320
+ raise Session::NotFound, id unless File.exist?(Session.session_file(id, state_dir: state_dir!)) || Dir.exist?(session_dir(id))
321
+
322
+ require_relative "../session_chain/delete_preview"
323
+ DeletePlan.read(SessionChain::Delete::Preview.call(id, state_dir: state_dir!))
324
+ end
325
+
313
326
  # A user's delete or archive: REFUSE, or a stop by "user".
314
327
  private def tasks_policy(stop_tasks)
315
328
  policies = SessionManager::RunningTasks::Policy