samagotchi 0.161.0 → 0.162.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.
@@ -0,0 +1,555 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require_relative "../../context_note"
6
+ require_relative "../../degrade"
7
+ require_relative "../../message_parts"
8
+ require_relative "../../message_time"
9
+ require_relative "../../output_formatter"
10
+ require_relative "../../revise_anchor"
11
+ require_relative "../../steer"
12
+ require_relative "../../tool_activity"
13
+ require_relative "../../tool_row_fields"
14
+ require_relative "../../turn_note"
15
+ require_relative "../../verify_anchor"
16
+ require_relative "../turn_accumulator"
17
+ require_relative "../turn_drawings"
18
+ require_relative "../turn_notice"
19
+ require_relative "../turn_ranges"
20
+
21
+ module Samagotchi
22
+ class Bridge
23
+ class TurnDrawings
24
+ # A drawing made from a finished turn's saved messages, for a turn no
25
+ # live-written line covers (a turn from before drawings, a fork's, a
26
+ # one-shot's, one past what was drawn): the events live would have
27
+ # emitted for it, folded by a fresh TurnAccumulator, so every drawing
28
+ # comes from the one fold (H3 step L). Pure: the messages, the turn's
29
+ # range (TurnRanges), its turn record and tool records (the session's
30
+ # timing: kind, durations, statuses) and CardStore's entries of the
31
+ # turn (`of_turn`: its cards, hook notices, retries, steer cuts, ✂
32
+ # rows and questions), each at the step it names.
33
+ #
34
+ # What the messages and records don't keep is lost (LOSSES); the drift
35
+ # spec makes each :row event say whether it is synthesized or lost.
36
+ module Synth
37
+ # The :row events (Events::CLASSIFICATION) a synthesized drawing
38
+ # makes again, from the messages, the records or CardStore.
39
+ SYNTHESIZED = %i[turn_started generation_started generation_chunk tool_call_started tool_call_completed
40
+ pending_input_merged merged_input reminder_injected card hook_notice empty_answer_retry
41
+ steer_cut llm_context_edited question_requested question_answered question_cancelled
42
+ turn_completed turn_canceled turn_failed].freeze
43
+ # What a synthesized drawing can't have (each with why), by the key
44
+ # its absence shows in: the drawing's or a part's.
45
+ # A :row event no synthesized drawing has goes here by its type
46
+ # (events_drift_spec checks every :row is one or the other).
47
+ LOSSES = {
48
+ context_added: "a context note: no turn's row, the page draws it from the messages, drawing or not",
49
+ origin: "who sent the prompt (TurnOrigin) is on the live event only",
50
+ input_origins: "a merged line's senders (input_merged) are on the live event only",
51
+ empty_step_thinking: "the thinking of a step that streamed nothing visible and was asked again " \
52
+ "(kept only on an empty answer's marker)",
53
+ reminder_details: "a reminder's description and interval: the line shows its name",
54
+ evicted_entries: "a card, hook notice or row CardStore pushed out (CAPACITY) or never saw",
55
+ untimed: "a tool's duration and status with no tool record (its status read from its output)",
56
+ tool_action: "a plugin tool's own action words (its label when saved, else 'calling tool')",
57
+ wake_start: "a wake turn's start time when no message of its own is stamped: its note's, written before it began",
58
+ failure_detail: "a failed turn's error message and class when its record keeps a summary (SessionMetrics#failure_fields)",
59
+ repeated_turn_id: "a range whose turn id an earlier one has (…~N): no record, no CardStore entries (whose they are " \
60
+ "can't be told)",
61
+ continued_steps: "a Continue's steps right after its turn read as that turn's (no message tells them apart): " \
62
+ "the turn's record and kind, the Continue's calls untimed, its own CardStore entries left out",
63
+ unopened_turn: "a turn with no opening (a reminder's, a Continue's) has no id in the messages: a made-up one, " \
64
+ "and no record to pair by"
65
+ }.freeze
66
+
67
+ # A Synth line that couldn't be made (its minimal line stands in).
68
+ class Error < StandardError; end
69
+
70
+ # Lines by key, least recently used out first past +budget+ bytes
71
+ # (each line's JSON size): a long session's turns, a few sessions.
72
+ class Memo
73
+ def initialize(budget:)
74
+ @budget = budget
75
+ @lines = {}
76
+ @bytes = 0
77
+ @mutex = Mutex.new
78
+ end
79
+
80
+ attr_reader :bytes
81
+
82
+ def size = @mutex.synchronize { @lines.size }
83
+
84
+ # The line for +key+, made by the block (outside the lock) when
85
+ # not kept.
86
+ def fetch(key)
87
+ hit = @mutex.synchronize do
88
+ entry = @lines.delete(key)
89
+ @lines[key] = entry if entry
90
+ entry
91
+ end
92
+ return hit[0] if hit
93
+
94
+ line = yield
95
+ store(key, line, JSON.generate(line.to_h).bytesize)
96
+ line
97
+ end
98
+
99
+ def clear = @mutex.synchronize { @lines.clear.tap { @bytes = 0 } }
100
+
101
+ private
102
+
103
+ def store(key, line, bytes)
104
+ @mutex.synchronize do
105
+ old = @lines.delete(key)
106
+ @bytes -= old[1] if old
107
+ @lines[key] = [line, bytes]
108
+ @bytes += bytes
109
+ while @bytes > @budget && @lines.size > 1
110
+ _, (_, gone) = @lines.shift
111
+ @bytes -= gone
112
+ end
113
+ end
114
+ end
115
+ end
116
+
117
+ # The synthesized lines chi web keeps (MEMO_BYTES of their JSON).
118
+ MEMO_BYTES = 32 * 1024 * 1024
119
+ MEMO = Memo.new(budget: MEMO_BYTES)
120
+
121
+ module_function
122
+
123
+ # @param messages [Array<Hash>] the session's messages (symbol or string keys)
124
+ # @param range [TurnRanges::Range] the turn's
125
+ # @param record [Hash, nil] its turn record (TurnRanges.records)
126
+ # @param tools [Array<Hash>] the session's tool records (its own are taken by turn id)
127
+ # @param entries [Array<Hash>] CardStore's listed entries (its own by of_turn)
128
+ # @param cwd [String, nil] the session's working directory (tool titles)
129
+ # @return [Line]
130
+ def line(messages, range, record: nil, tools: [], entries: [], cwd: nil)
131
+ list = Array(messages)
132
+ record &&= TurnAccumulator.from_wire(record)
133
+ own_tools = own_tool_records(tools, record, range)
134
+ own_entries = own_entries(entries, range)
135
+ events, untimed = Events.new(list, range, record, own_tools, own_entries, cwd).build
136
+ turn, end_event = fold(events)
137
+ untimed.each do |key|
138
+ part = turn[:parts].find { |p| p[:kind] == "tool" && [p[:iteration], p[:call_index]] == key }
139
+ part&.delete(:duration_ms)
140
+ end
141
+ line_of(list, range, turn, end_event, record)
142
+ end
143
+
144
+ # The line that stands in when #line raises: the turn's opening and
145
+ # its end's kind, no parts. Logged once (turn_synth_failed).
146
+ # @return [Line]
147
+ def safe_line(messages, range, record: nil, tools: [], entries: [], cwd: nil)
148
+ line(messages, range, record: record, tools: tools, entries: entries, cwd: cwd)
149
+ rescue StandardError => e
150
+ Degrade.note(:web, "turn_synth_failed", e, from: range.from, to: range.to)
151
+ begin
152
+ minimal(messages, range, record: record)
153
+ rescue StandardError => again
154
+ Degrade.note(:web, "turn_synth_minimal_failed", again, from: range.from, to: range.to)
155
+ constant(messages, range)
156
+ end
157
+ end
158
+
159
+ # The line that never fails: the range, its id, a completed end, no
160
+ # parts, read from nothing but the range (its ends' digests, when
161
+ # they can be made).
162
+ # @return [Line]
163
+ def constant(messages, range)
164
+ list = Array(messages)
165
+ digest = ->(message) { Degrade.call(:web, "turn_synth_digest_failed", fallback: "") { TurnDrawings.digest(message) } }
166
+ Line.new(v: VERSION, turn_id: range.id.to_s, kind: "completed", from: range.from, to: range.to,
167
+ from_digest: digest.call(list[range.from]), to_digest: digest.call(list[range.to - 1]),
168
+ drawing: { "prompt" => nil, "turn_id" => range.id.to_s, "parts" => [] }, end: { "type" => "turn_completed" })
169
+ end
170
+
171
+ # CardStore's listing fields that change with later turns (where an
172
+ # entry reads on the page), not with what the turn showed.
173
+ LISTING_KEYS = %i[turns_since current earlier opening_id during after_failed label].freeze
174
+
175
+ # #safe_line, kept per range in MEMO: a finished turn's range doesn't
176
+ # change, so a show after a turn end makes no old turn again. The key
177
+ # names everything the line is made from: the session, the range and
178
+ # every message's digest in it (an edit anywhere inside it, a plugin's
179
+ # replace_messages, misses), the turn's records and its CardStore
180
+ # entries without their listing fields (a later turn changes those).
181
+ # @return [Line]
182
+ def memoized(session_id, messages, range, record: nil, tools: [], entries: [], cwd: nil)
183
+ list = Array(messages)
184
+ own = record && Array(tools).select { |t| t.is_a?(Hash) && (t[:turn_id] || t["turn_id"]) == (record[:id] || record["id"]) }
185
+ mine = own_entries(entries, range).map { |e| e.except(*LISTING_KEYS) }
186
+ body = Digest::SHA1.hexdigest(list[range.from...range.to].to_a.map { |m| TurnDrawings.digest(m) }.join)
187
+ key = [session_id.to_s, range.from, range.to, range.id, body, Digest::SHA1.hexdigest(JSON.generate([record, own, mine, cwd]))]
188
+ MEMO.fetch(key) { safe_line(list, range, record: record, tools: tools, entries: entries, cwd: cwd) }
189
+ end
190
+
191
+ # @return [Line]
192
+ def minimal(messages, range, record: nil)
193
+ list = Array(messages)
194
+ record &&= TurnAccumulator.from_wire(record)
195
+ events = Events.new(list, range, record, [], [], nil)
196
+ line_of(list, range, events.started.merge(parts: []), events.ending, record)
197
+ end
198
+
199
+ # A turn's CardStore entries: its own turn id's (of_turn), none for a
200
+ # range whose id repeats an earlier one's (…~N: whose they are can't
201
+ # be told).
202
+ def own_entries(entries, range)
203
+ return [] unless range.own_id?
204
+
205
+ Array(entries).filter_map { |e| TurnAccumulator.from_wire(e) if e.is_a?(Hash) }.select { |e| e[:of_turn] == range.turn_id }
206
+ end
207
+ private_class_method :own_entries
208
+
209
+ # The fold raises what it can't fold (raise_errors:), so a bad event
210
+ # fails the line (safe_line logs it) instead of dropping its row.
211
+ def fold(events)
212
+ captured = nil
213
+ accumulator = TurnAccumulator.new(clock: -> { 0.0 }, raise_errors: true,
214
+ on_turn_end: ->(turn, ending) { captured = [turn, ending] })
215
+ events.each { |event| accumulator.call(event) }
216
+ raise Error, "the fold drew no turn" unless captured
217
+
218
+ captured
219
+ end
220
+ private_class_method :fold
221
+
222
+ def line_of(list, range, turn, end_event, record)
223
+ ending = TurnDrawings.end_of(end_event)
224
+ ending[:record_id] = record[:id] if record && record[:id]
225
+ Line.new(v: VERSION, turn_id: range.id, kind: KINDS[end_event[:type].to_s] || end_event[:type].to_s,
226
+ from: range.from, to: range.to,
227
+ from_digest: TurnDrawings.digest(list[range.from]), to_digest: TurnDrawings.digest(list[range.to - 1]),
228
+ drawing: JSON.parse(JSON.generate(TurnDrawings.scrub(turn.slice(*DRAWING_KEYS)))),
229
+ end: JSON.parse(JSON.generate(TurnDrawings.scrub(ending))))
230
+ end
231
+ private_class_method :line_of
232
+
233
+ # The turn's tool records: those of its record's id, else its own
234
+ # turn id's (a caller's records of the turn, no turn record saved).
235
+ def own_tool_records(tools, record, range)
236
+ id = (record && record[:id]) || (range.turn_id if range.own_id?)
237
+ return [] unless id
238
+
239
+ Array(tools).filter_map { |t| TurnAccumulator.from_wire(t) if t.is_a?(Hash) }
240
+ .select { |t| t[:turn_id] == id }
241
+ .sort_by { |t| [t[:iteration].to_i, t[:call_index].to_i] }
242
+ end
243
+ private_class_method :own_tool_records
244
+
245
+ # One turn's event stream, built once (#build).
246
+ class Events
247
+ END_TYPES = { "completed" => :turn_completed, "canceled" => :turn_canceled, "failed" => :turn_failed }.freeze
248
+ ROW_TYPES = %i[hook_notice empty_answer_retry steer_cut llm_context_edited].freeze
249
+ # A step no saved message holds: one the loop asked again.
250
+ REDONE = %i[empty_answer_retry steer_cut].freeze
251
+ REMINDER_NAME = /\A\s*(?:-\s*)?([^:\n]+?):/
252
+
253
+ def initialize(list, range, record, tools, entries, cwd)
254
+ @list = list
255
+ @range = range
256
+ @record = record
257
+ @pool = tools.dup
258
+ @entries = entries
259
+ @cwd = cwd
260
+ @opening = range.opening && list[range.opening]
261
+ @marks = MessageParts.edit_marks(list)
262
+ end
263
+
264
+ # @return [Array(Array<Hash>, Array<Array>)] the events, and the
265
+ # [iteration, call_index] of each tool with no record (no duration)
266
+ def build
267
+ @events = [started]
268
+ @untimed = []
269
+ @iteration = 0
270
+ @placed = []
271
+ @marker = nil
272
+ @last_tools = false
273
+ empties = marker_steps
274
+ own_messages.each do |message|
275
+ step(message, empties)
276
+ end
277
+ redone_steps(Float::INFINITY, empties)
278
+ # The empty answer's last steps: no message holds them.
279
+ empties.each do |thinking|
280
+ @iteration += 1
281
+ @events << { type: :generation_started, iteration: @iteration }
282
+ @events << { type: :generation_chunk, iteration: @iteration, text: "", thinking: thinking } unless thinking.empty?
283
+ place_at(@iteration, 0)
284
+ end
285
+ @events << { type: :generation_started, iteration: @iteration + 1 } if kind == "failed" && @last_tools
286
+ leftover = @entries.reject { |entry| @placed.include?(entry) }
287
+ leftover.each { |entry| place(entry) }
288
+ @events << ending
289
+ [@events, @untimed]
290
+ end
291
+
292
+ def started
293
+ prompt = prompt_message
294
+ event = { type: :turn_started, prompt: prompt && content_of(prompt), turn_id: @range.id, origin: nil,
295
+ continue: @record ? @record[:continue] == true : false }
296
+ event[:resumed] = true if @record && @record[:resumed] == true
297
+ # A wake's note was written before its turn began: the turn's
298
+ # first stamped message is nearer its start.
299
+ inside = @opening && @range.opening >= @range.from
300
+ at = MessageTime.of(inside ? @opening : (own_messages.find { |m| MessageTime.of(m) } || @opening))
301
+ event[:at] = at.to_s if at
302
+ images = prompt && fetch(prompt, :images)
303
+ event[:images] = images if images.is_a?(Array) && !images.empty?
304
+ source = prompt || (@opening if user?(@opening))
305
+ Steer::AUTHOR_KEYS.each { |key| event[key] = fetch(source, key) if source && fetch(source, key) }
306
+ event
307
+ end
308
+
309
+ def ending
310
+ type = END_TYPES.fetch(kind)
311
+ event = { type: type, kept_from: @range.from, kept_to: @range.to }
312
+ event[:turn_id] = @range.id if @range.own_id?
313
+ if @record
314
+ event[:duration_ms] = @record[:duration_ms] if @record[:duration_ms].is_a?(Integer)
315
+ event[:cancellation_reason] = @record[:cancellation_reason] if @record[:cancellation_reason]
316
+ event[:cancelled_by] = @record[:cancelled_by] if @record[:cancelled_by]
317
+ event.merge!(@record[:failure].slice(:summary, :message, :error_class, :kept_steps)) if @record[:failure].is_a?(Hash)
318
+ end
319
+ if @opening
320
+ revises = ReviseAnchor.from(fetch(@opening, :revises))
321
+ event[:revises] = revises.to_h if revises
322
+ event[:verify] = true if VerifyAnchor.from(fetch(@opening, :verify))
323
+ end
324
+ empty = marker
325
+ event[:turn_summary] = { empty_answer: empty.slice(:retries, :refusal) } if empty
326
+ event
327
+ end
328
+
329
+ private
330
+
331
+ # completed, canceled or failed: the record's, else the turn's own
332
+ # note's (a cancel's, a failure's), else completed.
333
+ def kind
334
+ status = @record && @record[:status].to_s
335
+ # A failed record saved before its failure field says nothing a
336
+ # failure's line is made of: the turn's own note decides.
337
+ return status if END_TYPES.key?(status) && !(status == "failed" && !@record[:failure].is_a?(Hash))
338
+
339
+ # Only the turn's own ending: a note that is its last message.
340
+ last = own_messages.last
341
+ note = last if TurnNote.note?(last) && !TurnNote.empty_answer(last)
342
+ text = note && fetch(note, :content).to_s
343
+ return "canceled" if text&.start_with?("#{TurnNote::OPEN}the previous turn was cancelled")
344
+ return "failed" if text&.start_with?(TurnNote::OPEN + TurnNote::FAILED, TurnNote::OPEN + TurnNote::FAILED_AFTER)
345
+
346
+ "completed"
347
+ end
348
+
349
+ # The range's messages (a damaged file's non-Hash entries left out).
350
+ def own_messages = @list[@range.from...@range.to].to_a.grep(Hash)
351
+
352
+ # The prompt the turn opened with: a user message, not a wake's
353
+ # report (an input: the turn's first merged line) or note.
354
+ def prompt_message
355
+ return nil unless @opening && user?(@opening) && !Steer.input?(@opening)
356
+
357
+ @opening
358
+ end
359
+
360
+ def step(message, empties)
361
+ return if message.equal?(prompt_message)
362
+
363
+ role = fetch(message, :role).to_s
364
+ if role == "system"
365
+ system_message(message)
366
+ elsif Steer.steer?(message)
367
+ @events << { type: :pending_input_merged, iteration: step_of(message), count: 0, content: nil,
368
+ steers: [{ source: fetch(message, :source).to_s, text: fetch(message, :content).to_s }] }
369
+ elsif Steer.input?(message)
370
+ input = { type: :pending_input_merged, iteration: step_of(message), count: 1, content: fetch(message, :content).to_s,
371
+ steers: [] }
372
+ Steer::AUTHOR_KEYS.each { |key| input[key] = fetch(message, key) if fetch(message, key) }
373
+ @events << input
374
+ elsif %w[model assistant].include?(role)
375
+ model_step(message, empties)
376
+ end
377
+ end
378
+
379
+ def system_message(message)
380
+ if TurnNote.empty_answer(message)
381
+ @marker = TurnNote.empty_answer(message)
382
+ elsif !ContextNote.note?(message) && !TurnNote.note?(message) &&
383
+ fetch(message, :content).to_s.start_with?(TurnRanges::REMINDER)
384
+ @events << { type: :reminder_injected, reminders: reminder_names(fetch(message, :content).to_s) }
385
+ end
386
+ end
387
+
388
+ def model_step(message, empties)
389
+ redone_steps(@iteration + 1, empties)
390
+ @iteration += 1
391
+ n = @iteration
392
+ index = @list.index { |m| m.equal?(message) }
393
+ parts = MessageParts.for_message(message, responses_after(index), cwd: @cwd, marks: @marks) || {}
394
+ text = OutputFormatter.strip_markup(fetch(message, :content).to_s)
395
+ thinking = parts[:thinking].to_s
396
+ thinking = empties.shift.to_s if thinking.empty? && text.empty? && parts[:tools].to_a.empty? && !empties.empty?
397
+ @events << { type: :generation_started, iteration: n }
398
+ @events << { type: :generation_chunk, iteration: n, text: "", thinking: thinking } unless thinking.empty?
399
+ @events << { type: :generation_chunk, iteration: n, text: text, thinking: "" } unless text.empty?
400
+ place_at(n, 0)
401
+ tools = parts[:tools].to_a
402
+ tools.each_with_index { |tool, j| tool_events(tool, n, j + 1) }
403
+ @last_tools = !tools.empty?
404
+ end
405
+
406
+ # The steps before +upto+ that left no message: each one a retry
407
+ # or a steer's cut asked again (CardStore's rows name them), with
408
+ # its thinking when the empty answer's marker kept it.
409
+ def redone_steps(upto, empties)
410
+ loop do
411
+ n = @iteration + 1
412
+ break if n > upto
413
+ break unless @entries.any? { |e| REDONE.include?(e[:type]&.to_sym) && e[:iteration].to_i == n && !@placed.include?(e) }
414
+
415
+ # The step a saved message holds is the one at +upto+ itself
416
+ # unless a retry names it: then it was the one asked again.
417
+ @iteration = n
418
+ @events << { type: :generation_started, iteration: n }
419
+ thinking = empties.shift.to_s
420
+ @events << { type: :generation_chunk, iteration: n, text: "", thinking: thinking } unless thinking.empty?
421
+ place_at(n, 0)
422
+ end
423
+ end
424
+
425
+ def tool_events(part, iteration, index)
426
+ rec = take_record(part[:tool])
427
+ call = { iteration: iteration, call_index: index, tool: part[:tool] }
428
+ call[:label] = part[:label] if part[:label]
429
+ call[:tool_id] = part[:tool_id] if part[:tool_id]
430
+ title = part.slice(*ToolRowFields::ACTIVITY_KEYS).compact
431
+ view = part.slice(*ToolRowFields::EVENT_KEYS).compact
432
+ @events << { type: :tool_call_started, **call, params: part[:params], **title, **view }
433
+ place_at(iteration, index)
434
+ activity = { tool: part[:tool], status: (rec && rec[:status]&.to_s) || status_of(part),
435
+ params: part[:params], **title,
436
+ action: part[:label] || ToolActivity.tool_activity_action(part[:tool]) }
437
+ activity[:no_match] = true if rec && rec[:no_match]
438
+ activity[:guardrail] = rec[:guardrail].merge(decided_by: "system one") if rec && rec[:guardrail].is_a?(Hash)
439
+ output = part[:output].to_s
440
+ completed = { type: :tool_call_completed, **call, output: output, preview: output,
441
+ output_truncated: part[:output_truncated] ? true : false, activity: activity, **view }
442
+ if rec && rec[:duration_ms].is_a?(Integer)
443
+ completed[:duration_ms] = rec[:duration_ms]
444
+ else
445
+ @untimed << [iteration, index]
446
+ end
447
+ completed[:diff] = part[:diff] if part[:diff]
448
+ completed[:images] = part[:images] if part[:images]
449
+ @events << completed
450
+ end
451
+
452
+ # A call's status with no record of it, from its saved output as a
453
+ # reload always read it: "no result" for a call the turn never
454
+ # answered, "blocked" for a guardrail's deny, else the live rule
455
+ # (a grep that found nothing is ok).
456
+ def status_of(part)
457
+ return "no result" if part[:output].nil?
458
+
459
+ text = ToolActivity.saved_result_text(part[:output])
460
+ return "blocked" if ToolActivity.guardrail_denied?(text)
461
+
462
+ command = part.dig(:view, :truncated) ? nil : part.dig(:view, :command)
463
+ ToolActivity.tool_activity_status(text, part[:tool], command: command)
464
+ end
465
+
466
+ # The turn's next tool record of +tool+, in call order, with the
467
+ # ones it skipped (the page's timing.js takeRecord).
468
+ def take_record(tool)
469
+ at = @pool.index { |r| r[:tool].to_s == tool.to_s }
470
+ return nil unless at
471
+
472
+ @pool.shift(at + 1).last
473
+ end
474
+
475
+ # The entries a step names (+iteration+, +calls+: the tool it came
476
+ # after; 0 for before any), in CardStore's order.
477
+ def place_at(iteration, calls)
478
+ @entries.each do |entry|
479
+ next if @placed.include?(entry)
480
+ next unless entry[:iteration].to_i == iteration && entry[:calls].to_i == calls
481
+
482
+ place(entry)
483
+ end
484
+ end
485
+
486
+ def place(entry)
487
+ @placed << entry
488
+ type = entry[:type]&.to_sym
489
+ if type == :card
490
+ @events << entry.slice(:id, :source, :title, :body, :level, :actions).merge(type: :card, in_turn: true)
491
+ elsif ROW_TYPES.include?(type)
492
+ @events << { type: type, **entry.slice(*TurnNotice::FIELDS.fetch(type)) }
493
+ elsif type == :question && entry[:pending_question].is_a?(Hash)
494
+ question(entry)
495
+ end
496
+ end
497
+
498
+ def question(entry)
499
+ pending = entry[:pending_question]
500
+ @events << { type: :question_requested, pending_question: pending }
501
+ if entry.key?(:answer)
502
+ @events << { type: :question_answered, id: pending[:id], answer: entry[:answer] }
503
+ elsif entry[:cancelled]
504
+ @events << { type: :question_cancelled, id: pending[:id], reason: entry[:reason] }
505
+ end
506
+ end
507
+
508
+ # The tool_response messages right after the model message at +index+.
509
+ def responses_after(index)
510
+ return [] unless index
511
+
512
+ @list[(index + 1)...@range.to].to_a.take_while { |m| fetch(m, :role).to_s == "tool_response" }
513
+ end
514
+
515
+ # The empty steps' thinking the empty answer's marker kept, in order.
516
+ def marker_steps
517
+ empty = marker
518
+ Array(empty && empty[:steps]).map { |s| (s.is_a?(Hash) ? (s[:thinking] || s["thinking"]) : nil).to_s }
519
+ end
520
+
521
+ def marker
522
+ own_messages.each { |m| (found = TurnNote.empty_answer(m)) && (return TurnAccumulator.from_wire(found)) }
523
+ nil
524
+ end
525
+
526
+ # The step that read a steer or a merged line (the server's count):
527
+ # its saved step, else one past the model messages before it.
528
+ def step_of(message)
529
+ saved = fetch(message, :step)
530
+ saved.is_a?(Integer) ? saved : @iteration + 1
531
+ end
532
+
533
+ def reminder_names(content)
534
+ lines = content.lines.drop(1).take_while { |l| !l.start_with?("[END REMINDERS]") }
535
+ lines.filter_map { |l| (name = l[REMINDER_NAME, 1]) && { name: name.strip } }
536
+ end
537
+
538
+ def content_of(message)
539
+ content = fetch(message, :content)
540
+ content.is_a?(String) ? content : content.to_s
541
+ end
542
+
543
+ def user?(message) = message.is_a?(Hash) && fetch(message, :role).to_s == "user"
544
+
545
+ def fetch(hash, key)
546
+ return nil unless hash.is_a?(Hash)
547
+
548
+ hash.key?(key) ? hash[key] : hash[key.to_s]
549
+ end
550
+ end
551
+ private_constant :Events
552
+ end
553
+ end
554
+ end
555
+ end