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