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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +25 -1
- data/docs/architecture.md +1 -1
- data/docs/internals/block-renderers.md +3 -2
- data/docs/internals/bridge.md +61 -11
- data/docs/internals/inline-widgets.md +6 -3
- data/docs/internals/web-frontend.md +1 -1
- data/docs/sessions.md +1 -1
- data/docs/testing.md +7 -1
- data/lib/samagotchi/bridge/card_store.rb +23 -13
- data/lib/samagotchi/bridge/turn_accumulator.rb +7 -1
- data/lib/samagotchi/bridge/turn_drawings/synth.rb +555 -0
- data/lib/samagotchi/bridge/turn_drawings.rb +103 -7
- data/lib/samagotchi/bridge/turn_ranges.rb +175 -0
- data/lib/samagotchi/bridge.rb +35 -12
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/plugin/sessions.rb +8 -1
- data/lib/samagotchi/project_id_clash.rb +1 -1
- data/lib/samagotchi/terminal_ui/join_replay.rb +34 -128
- data/lib/samagotchi/terminal_ui.rb +12 -1
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/message_display.rb +5 -1
- data/lib/samagotchi/web/public/block_frame.js +5 -1
- data/lib/samagotchi/web/public/timing.js +17 -6
- data/lib/samagotchi/web/public/turn_block.js +6 -2
- data/lib/samagotchi/web/public/widget_walk.js +4 -2
- data/lib/samagotchi/web/session_show.rb +22 -11
- metadata +3 -1
|
@@ -5,6 +5,8 @@ require "fileutils"
|
|
|
5
5
|
require "json"
|
|
6
6
|
require_relative "../log"
|
|
7
7
|
require_relative "../message_time"
|
|
8
|
+
require_relative "../context_note"
|
|
9
|
+
require_relative "../degrade"
|
|
8
10
|
require_relative "../steer"
|
|
9
11
|
|
|
10
12
|
module Samagotchi
|
|
@@ -31,17 +33,18 @@ module Samagotchi
|
|
|
31
33
|
# SessionObserver's delivery: the line is on disk before any stream gets
|
|
32
34
|
# the end frame. That departs from SessionObserver's "enqueue-only" note,
|
|
33
35
|
# as CardStore's save does: one append per turn end.
|
|
36
|
+
# Both read TurnDrawings at load: loaded on first use (no require cycle).
|
|
37
|
+
autoload :TurnRanges, File.expand_path("turn_ranges", __dir__)
|
|
38
|
+
|
|
34
39
|
class TurnDrawings
|
|
40
|
+
autoload :Synth, File.expand_path("turn_drawings/synth", __dir__)
|
|
41
|
+
|
|
35
42
|
FILE = "turn_drawings.jsonl"
|
|
36
43
|
# In the sidecar's features (Bridge::FEATURES): this worker's CardStore
|
|
37
44
|
# lists an in-turn entry's of_turn, which a page drawing the turn needs
|
|
38
45
|
# to leave that entry to the drawing. chi web draws no drawings for a
|
|
39
46
|
# live worker without it (an older one: its rows would show twice).
|
|
40
47
|
FEATURE = "turn_drawings"
|
|
41
|
-
# A show draws at most this many turns from their drawings, the newest
|
|
42
|
-
# (the payload and the page's offscreen render stay bounded in a long
|
|
43
|
-
# session); older turns draw as before, from their messages.
|
|
44
|
-
SHOWN_MAX = 100
|
|
45
48
|
VERSION = 1
|
|
46
49
|
# The end event's keys the page draws a finished turn's end from (not
|
|
47
50
|
# the answer: its text, html and refs stay the message's; not the range:
|
|
@@ -190,7 +193,8 @@ module Samagotchi
|
|
|
190
193
|
|
|
191
194
|
lines = parse(File.binread(path))
|
|
192
195
|
cache_mutex.synchronize do
|
|
193
|
-
cache.
|
|
196
|
+
cache.delete(path)
|
|
197
|
+
cache.shift while !cache.empty? && (cache.size >= CACHE_SIZE || cache.sum { |_, (k, _)| k[0] } + stat.size > CACHE_BYTES)
|
|
194
198
|
cache[path] = [key, lines]
|
|
195
199
|
end
|
|
196
200
|
lines
|
|
@@ -224,6 +228,90 @@ module Samagotchi
|
|
|
224
228
|
kept.sort_by(&:from)
|
|
225
229
|
end
|
|
226
230
|
|
|
231
|
+
# The lines a show draws the session's finished turns from: pure,
|
|
232
|
+
# over the file's +lines+ (.read) and the session's +messages+. The
|
|
233
|
+
# valid ones (.valid), and for each turn (TurnRanges) no valid line
|
|
234
|
+
# overlaps, a line made from its messages (Synth, memoized per
|
|
235
|
+
# range), so every finished turn has one. +timing+: the session's
|
|
236
|
+
# records (turn_records, tool_records: the show's timing payload);
|
|
237
|
+
# +entries+: CardStore's listed entries (the show's cards);
|
|
238
|
+
# +skip_turn_id+: the running turn's id (its messages may be in
|
|
239
|
+
# while its line isn't written yet: never synthesized). A file whose
|
|
240
|
+
# lines can't be checked counts as none: every turn synthesized.
|
|
241
|
+
# @return [Array<Line>] ordered by their range
|
|
242
|
+
def cover(lines, messages, timing: nil, entries: [], skip_turn_id: nil, session_id: nil, cwd: nil)
|
|
243
|
+
messages = Array(messages)
|
|
244
|
+
real = Degrade.call(:web, "turn_drawings_unreadable", fallback: []) { valid(lines, messages) }
|
|
245
|
+
ranges = TurnRanges.of(messages)
|
|
246
|
+
open = uncovered(ranges, real)
|
|
247
|
+
ranges = reserve_ids(ranges, open, real)
|
|
248
|
+
turn_records = list_of(timing, :turn_records)
|
|
249
|
+
records = TurnRanges.records(ranges, turn_records)
|
|
250
|
+
tools = list_of(timing, :tool_records).group_by { |t| field(t, :turn_id) }
|
|
251
|
+
own = Array(entries).select { |e| e.is_a?(Hash) && field(e, :of_turn) }.group_by { |e| field(e, :of_turn) }
|
|
252
|
+
made = open.filter_map do |i|
|
|
253
|
+
range = ranges[i]
|
|
254
|
+
next if skip_turn_id && range.turn_id == skip_turn_id
|
|
255
|
+
|
|
256
|
+
record = records[i]
|
|
257
|
+
# The turn's tool records by its record's id, else its own (a
|
|
258
|
+
# record lost, its tool records saved: the TUI's join does so too).
|
|
259
|
+
tool_id = record ? field(record, :id) : (range.turn_id if range.own_id?)
|
|
260
|
+
Synth.memoized(session_id, messages, range, record: record, tools: tool_id ? tools.fetch(tool_id, []) : [],
|
|
261
|
+
entries: own.fetch(range.turn_id, []), cwd: cwd)
|
|
262
|
+
end
|
|
263
|
+
(real + made).sort_by(&:from)
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# +ranges+ with each one to be made (+open+, indexes) whose id a kept
|
|
267
|
+
# line has (a failed turn's kept steps, then its re-run under the same
|
|
268
|
+
# turn id: .valid keeps the newest line for an id) renamed "<id>~<from>":
|
|
269
|
+
# never two lines with one id (the page would draw them as one turn),
|
|
270
|
+
# and not its turn's own (no end turn_id, record or entries).
|
|
271
|
+
def reserve_ids(ranges, open, lines)
|
|
272
|
+
taken = lines.to_set(&:turn_id)
|
|
273
|
+
return ranges if taken.empty?
|
|
274
|
+
|
|
275
|
+
made = open.to_set
|
|
276
|
+
ranges.each_with_index.map do |range, i|
|
|
277
|
+
made.include?(i) && taken.include?(range.id) ? range.with(id: "#{range.id}~#{range.from}") : range
|
|
278
|
+
end
|
|
279
|
+
end
|
|
280
|
+
private :reserve_ids
|
|
281
|
+
|
|
282
|
+
# The indexes of +ranges+ no line of +lines+ (sorted by from, apart)
|
|
283
|
+
# overlaps: one walk over both.
|
|
284
|
+
def uncovered(ranges, lines)
|
|
285
|
+
at = 0
|
|
286
|
+
ranges.each_index.reject do |i|
|
|
287
|
+
range = ranges[i]
|
|
288
|
+
at += 1 while at < lines.size && lines[at].to >= 0 && lines[at].to <= range.from
|
|
289
|
+
at < lines.size && lines[at].from < range.to
|
|
290
|
+
end
|
|
291
|
+
end
|
|
292
|
+
private :uncovered
|
|
293
|
+
|
|
294
|
+
# A fork's drawings (Plugin::Sessions#fork, before its child's worker
|
|
295
|
+
# spawns: no other writer): the lines of +from_dir+'s file that hold
|
|
296
|
+
# against the child's seed +messages+ (same indices, same ends; a range
|
|
297
|
+
# whose end the image copy changed doesn't), written as the child's
|
|
298
|
+
# file. A seed without the system head (a plugin's ctx.messages) is
|
|
299
|
+
# read as the child's messages will be once its first turn puts the
|
|
300
|
+
# head back at index 0 (ContextNote.with_system_head): the lines keep
|
|
301
|
+
# the parent's indices, and hold from then on. Its other turns are
|
|
302
|
+
# made from their messages at read.
|
|
303
|
+
# @return [Integer] the lines carried
|
|
304
|
+
def carry(from_dir:, to_dir:, messages:)
|
|
305
|
+
seed = Array(messages)
|
|
306
|
+
seed = [{ role: "system", content: "" }] + seed unless ContextNote.system_head?(seed.first)
|
|
307
|
+
lines = valid(read(from_dir), seed)
|
|
308
|
+
return 0 if lines.empty?
|
|
309
|
+
|
|
310
|
+
FileUtils.mkdir_p(to_dir)
|
|
311
|
+
File.write(File.join(to_dir, FILE), lines.map { |line| "#{JSON.generate(line.to_h)}\n" }.join, perm: 0o600)
|
|
312
|
+
lines.size
|
|
313
|
+
end
|
|
314
|
+
|
|
227
315
|
# The last parseable line of +path+, or nil.
|
|
228
316
|
# @return [Line, nil]
|
|
229
317
|
def tail_line(path)
|
|
@@ -256,16 +344,24 @@ module Samagotchi
|
|
|
256
344
|
message.key?(key) ? message[key] : message[key.to_s]
|
|
257
345
|
end
|
|
258
346
|
|
|
347
|
+
def field(hash, key) = hash.is_a?(Hash) ? fetch(hash, key) : nil
|
|
348
|
+
|
|
349
|
+
def list_of(timing, key) = Array(timing.is_a?(Hash) ? fetch(timing, key) : nil).grep(Hash)
|
|
350
|
+
|
|
259
351
|
def cache = (@cache ||= {})
|
|
260
352
|
def cache_mutex = (@cache_mutex ||= Mutex.new)
|
|
261
353
|
end
|
|
262
354
|
|
|
263
355
|
# Sessions whose parsed file chi web keeps (a long one's is tens of MB
|
|
264
|
-
# of objects; the mtime moves at every turn end anyway)
|
|
356
|
+
# of objects; the mtime moves at every turn end anyway), and the files'
|
|
357
|
+
# bytes they may sum to (the newest one is always kept). Both bound the
|
|
358
|
+
# files' and lines' JSON bytes, not the heap: parsed lines take several
|
|
359
|
+
# times that (as Synth::MEMO_BYTES does).
|
|
265
360
|
CACHE_SIZE = 8
|
|
361
|
+
CACHE_BYTES = 64 * 1024 * 1024
|
|
266
362
|
# Read from the end at start (#last): a drawing is a few KB, its outputs cut.
|
|
267
363
|
TAIL_BYTES = 1024 * 1024
|
|
268
|
-
private_constant :CACHE_SIZE, :TAIL_BYTES
|
|
364
|
+
private_constant :CACHE_SIZE, :CACHE_BYTES, :TAIL_BYTES
|
|
269
365
|
end
|
|
270
366
|
end
|
|
271
367
|
end
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../context_note"
|
|
4
|
+
require_relative "../steer"
|
|
5
|
+
require_relative "../turn_note"
|
|
6
|
+
require_relative "turn_drawings"
|
|
7
|
+
|
|
8
|
+
module Samagotchi
|
|
9
|
+
class Bridge
|
|
10
|
+
# A session's messages cut into turns the way the Engine cuts a turn's
|
|
11
|
+
# own messages (its end event's `kept_from`/`kept_to`, Engine#end_turn),
|
|
12
|
+
# read back from the messages alone: what a turn drawing names (its
|
|
13
|
+
# from/to) for a turn that has none (Bridge::TurnDrawings).
|
|
14
|
+
#
|
|
15
|
+
# A turn starts at the reminder lines just before its opening (they
|
|
16
|
+
# went into it: `kept_from` sits before the due reminders), else at its
|
|
17
|
+
# opening (Steer.turn_opening?: a prompt, a wake turn's report), else at
|
|
18
|
+
# the first message after a wake turn's note (the note was there before
|
|
19
|
+
# the turn began: outside, the turn's opening by its id), else at a
|
|
20
|
+
# message no opening came before (a reminder's or a Continue's turn: no
|
|
21
|
+
# prompt). It ends at its last own message: context notes after it, a
|
|
22
|
+
# `!cmd`'s record and a wake's note stay outside, between the turns.
|
|
23
|
+
# A Continue's steps right after the turn it continues read as that
|
|
24
|
+
# turn's (no message tells them apart), as the page groups them.
|
|
25
|
+
module TurnRanges
|
|
26
|
+
# One turn's messages, `messages[from...to]`.
|
|
27
|
+
# +id+: the turn's display id: its opening's turn_id, else
|
|
28
|
+
# "m<from>-<digest8>" (a turn saved before turn ids, a turn with no
|
|
29
|
+
# opening); a later range repeating an id gets "<id>~<from>", so no two
|
|
30
|
+
# ranges share one. +turn_id+: the opening's own turn_id (nil for none).
|
|
31
|
+
# +opening+: the opening's index (a wake note's sits before +from+),
|
|
32
|
+
# nil for a turn with none.
|
|
33
|
+
Range = Data.define(:from, :to, :id, :turn_id, :opening) do
|
|
34
|
+
def range = (from...to)
|
|
35
|
+
|
|
36
|
+
# Whether +id+ is a turn's own (not made up here): what an action
|
|
37
|
+
# (Revise, the answer's key) may carry.
|
|
38
|
+
def own_id? = !turn_id.nil? && id == turn_id
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
REMINDER = "[SYSTEM: REMINDERS DUE "
|
|
42
|
+
|
|
43
|
+
module_function
|
|
44
|
+
|
|
45
|
+
# @param messages [Array<Hash>] a session's messages (symbol or string keys)
|
|
46
|
+
# @return [Array<Range>] oldest first
|
|
47
|
+
def of(messages)
|
|
48
|
+
list = Array(messages)
|
|
49
|
+
cuts = cut(list)
|
|
50
|
+
seen = {}
|
|
51
|
+
cuts.map do |from, to, opening|
|
|
52
|
+
turn_id = opening && fetch(list[opening], :turn_id)
|
|
53
|
+
turn_id = nil unless turn_id.is_a?(String) && !turn_id.empty?
|
|
54
|
+
id = turn_id || "m#{from}-#{TurnDrawings.digest(list[from])[0, 8]}"
|
|
55
|
+
id = "#{id}~#{from}" if seen.key?(id)
|
|
56
|
+
seen[id] = true
|
|
57
|
+
Range.new(from: from, to: to, id: id, turn_id: turn_id, opening: opening)
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Each range's turn record (the session's timing turn records, string
|
|
62
|
+
# or symbol keys): the one with its turn's id, else, for a turn saved
|
|
63
|
+
# before turn ids, the record at its place among the turns with an
|
|
64
|
+
# opening, a failure's that kept nothing not counted (its prompt went
|
|
65
|
+
# back: no opening; the page's timing.js promptRecord rule). A range
|
|
66
|
+
# whose id repeats an earlier one's (…~N) gets none: whose it is
|
|
67
|
+
# can't be told.
|
|
68
|
+
# @return [Array<Hash, nil>] one per range
|
|
69
|
+
def records(ranges, turn_records)
|
|
70
|
+
records = Array(turn_records).grep(Hash)
|
|
71
|
+
placed = records.reject { |record| unopened_record?(record) }
|
|
72
|
+
by_id = {}
|
|
73
|
+
records.each { |record| by_id[fetch(record, :id)] ||= record }
|
|
74
|
+
place = -1
|
|
75
|
+
ranges.map do |range|
|
|
76
|
+
place += 1 if range.opening
|
|
77
|
+
if range.turn_id
|
|
78
|
+
range.own_id? ? by_id[range.turn_id] : nil
|
|
79
|
+
elsif range.opening
|
|
80
|
+
placed[place]
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# [from, to, opening] per turn.
|
|
86
|
+
def cut(list)
|
|
87
|
+
out = []
|
|
88
|
+
turn = nil
|
|
89
|
+
pending = nil
|
|
90
|
+
close = lambda do
|
|
91
|
+
out << [turn[:from], turn[:last] + 1, turn[:opening]] if turn && turn[:last]
|
|
92
|
+
turn = nil
|
|
93
|
+
end
|
|
94
|
+
list.each_with_index do |message, i|
|
|
95
|
+
next unless message.is_a?(Hash)
|
|
96
|
+
|
|
97
|
+
if Steer.shell_line?(message)
|
|
98
|
+
close.call
|
|
99
|
+
pending = nil
|
|
100
|
+
elsif fetch(message, :role).to_s == "system"
|
|
101
|
+
if Steer.turn_prompt?(message)
|
|
102
|
+
# A wake's note: the turn it opens starts after it.
|
|
103
|
+
close.call
|
|
104
|
+
pending = nil
|
|
105
|
+
turn = { from: nil, last: nil, opening: i, turn_id: fetch(message, :turn_id) }
|
|
106
|
+
elsif reminder?(message)
|
|
107
|
+
close.call if turn&.dig(:last)
|
|
108
|
+
pending ||= i
|
|
109
|
+
elsif rolled_back?(message)
|
|
110
|
+
# A failure that handed its prompt back (TurnNote.failed, no work
|
|
111
|
+
# kept): the failed turn's own range, its note alone, as the
|
|
112
|
+
# Engine kept it; never the turn before's.
|
|
113
|
+
close.call if turn&.dig(:last)
|
|
114
|
+
out << [pending || i, i + 1, nil]
|
|
115
|
+
turn = nil
|
|
116
|
+
pending = nil
|
|
117
|
+
elsif TurnNote.note?(message)
|
|
118
|
+
turn ||= { from: pending || i, last: nil, opening: nil }
|
|
119
|
+
turn[:from] ||= pending || i
|
|
120
|
+
turn[:last] = i
|
|
121
|
+
pending = nil
|
|
122
|
+
end
|
|
123
|
+
# A context note, the system head: nobody's own.
|
|
124
|
+
elsif Steer.turn_opening?(message)
|
|
125
|
+
id = fetch(message, :turn_id)
|
|
126
|
+
if turn && id && turn[:turn_id] == id && Steer.input?(message)
|
|
127
|
+
# A second opening line of the turn (a wake turn's report after its note).
|
|
128
|
+
turn[:from] ||= pending || i
|
|
129
|
+
turn[:last] = i
|
|
130
|
+
else
|
|
131
|
+
close.call
|
|
132
|
+
turn = { from: pending || i, last: i, opening: i, turn_id: id }
|
|
133
|
+
end
|
|
134
|
+
pending = nil
|
|
135
|
+
else
|
|
136
|
+
turn ||= { from: pending || i, last: nil, opening: nil }
|
|
137
|
+
turn[:from] ||= pending || i
|
|
138
|
+
turn[:last] = i
|
|
139
|
+
pending = nil
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
close.call
|
|
143
|
+
out
|
|
144
|
+
end
|
|
145
|
+
private_class_method :cut
|
|
146
|
+
|
|
147
|
+
# The note of a failure that kept nothing (TurnNote.failed, not
|
|
148
|
+
# .failed_after): its prompt went back or its turn left no step.
|
|
149
|
+
def rolled_back?(message)
|
|
150
|
+
TurnNote.note?(message) && fetch(message, :content).to_s.start_with?(TurnNote::OPEN + TurnNote::FAILED)
|
|
151
|
+
end
|
|
152
|
+
private_class_method :rolled_back?
|
|
153
|
+
|
|
154
|
+
# A turn record that left no opening (a failure that kept nothing:
|
|
155
|
+
# its prompt went back): it has no place among the openings.
|
|
156
|
+
def unopened_record?(record)
|
|
157
|
+
failure = fetch(record, :failure)
|
|
158
|
+
fetch(record, :status).to_s == "failed" && failure.is_a?(Hash) && !fetch(failure, :kept_steps)
|
|
159
|
+
end
|
|
160
|
+
private_class_method :unopened_record?
|
|
161
|
+
|
|
162
|
+
def reminder?(message)
|
|
163
|
+
!ContextNote.note?(message) && fetch(message, :content).to_s.start_with?(REMINDER)
|
|
164
|
+
end
|
|
165
|
+
private_class_method :reminder?
|
|
166
|
+
|
|
167
|
+
def fetch(hash, key)
|
|
168
|
+
return nil unless hash.is_a?(Hash)
|
|
169
|
+
|
|
170
|
+
hash.key?(key) ? hash[key] : hash[key.to_s]
|
|
171
|
+
end
|
|
172
|
+
private_class_method :fetch
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
end
|
data/lib/samagotchi/bridge.rb
CHANGED
|
@@ -23,6 +23,7 @@ require_relative "bridge/ring_buffer"
|
|
|
23
23
|
require_relative "bridge/sse_writer"
|
|
24
24
|
require_relative "bridge/turn_accumulator"
|
|
25
25
|
require_relative "bridge/turn_drawings"
|
|
26
|
+
require_relative "bridge/turn_ranges"
|
|
26
27
|
require_relative "session"
|
|
27
28
|
require_relative "engine"
|
|
28
29
|
require_relative "system_one/log"
|
|
@@ -327,11 +328,12 @@ module Samagotchi
|
|
|
327
328
|
# working_set: the running turn's last :working_set_updated ({items:,
|
|
328
329
|
# at:}, TurnAccumulator#working_set), which the messages lag; nil
|
|
329
330
|
# between turns and before the turn emitted one.
|
|
330
|
-
# last_turn_drawing: the last
|
|
331
|
-
#
|
|
332
|
-
# unfolds it, TurnAccumulator.replay_events), only while it holds
|
|
333
|
-
# these messages
|
|
334
|
-
#
|
|
331
|
+
# last_turn_drawing: the last prompt's turn as live drew it ({drawing:,
|
|
332
|
+
# end:}, the file's line for that turn id, not unfolded: an attaching
|
|
333
|
+
# TUI unfolds it, TurnAccumulator.replay_events), only while it holds
|
|
334
|
+
# against these messages; a reminder's, a Continue's or a note after it
|
|
335
|
+
# hides it no more. Absent otherwise (no prompt with a turn id, a
|
|
336
|
+
# rollback, an older worker's file).
|
|
335
337
|
# @return [Hash] {messages:, current_turn:, working_set:, queued:, queued_commands:, recap:, saved_recap:, continue_offer:, pending_question:,
|
|
336
338
|
# guardrail_warning:, plugin_warning:, init_tasks:, cards:, commands:, chi_version:, event_seq:, event_id:, last_turn_drawing:}
|
|
337
339
|
def snapshot
|
|
@@ -361,20 +363,41 @@ module Samagotchi
|
|
|
361
363
|
end
|
|
362
364
|
end
|
|
363
365
|
|
|
364
|
-
# The
|
|
365
|
-
#
|
|
366
|
-
#
|
|
367
|
-
# (TurnDrawings
|
|
366
|
+
# The last prompt's drawing as the snapshot sends it: the turn an
|
|
367
|
+
# attaching TUI draws (TerminalUI::JoinReplay: the last user message
|
|
368
|
+
# that opens a turn), its newest line that still holds against
|
|
369
|
+
# +messages+, the one this worker wrote last (TurnDrawings#last) else
|
|
370
|
+
# the file's (TurnDrawings.read, cached by its size and mtime), and no
|
|
371
|
+
# bigger than a restart reads back (TurnDrawings.sendable?). Only when
|
|
372
|
+
# it is the last turn (TurnRanges: notes after it are fine): a join
|
|
373
|
+
# draws the line's rows and then the newest answer, so a later turn's
|
|
374
|
+
# (a reminder's, a Continue's) would sit under the prompt's rows
|
|
375
|
+
# without its own. nil otherwise.
|
|
368
376
|
# @return [Hash, nil] {drawing:, end:} (string keys inside, as the file)
|
|
369
377
|
def last_turn_drawing(messages)
|
|
370
|
-
|
|
371
|
-
return nil unless
|
|
372
|
-
|
|
378
|
+
id = last_prompt_turn_id(messages)
|
|
379
|
+
return nil unless id
|
|
380
|
+
|
|
381
|
+
line = [@drawings.last].compact.find { |l| l.turn_id == id && TurnDrawings.holds?(l, messages) } ||
|
|
382
|
+
TurnDrawings.read(session_dir).reverse_each.find { |l| l.turn_id == id && TurnDrawings.holds?(l, messages) }
|
|
383
|
+
return nil unless line && TurnDrawings.sendable?(line)
|
|
384
|
+
return nil unless TurnRanges.of(messages).last&.to == line.to
|
|
373
385
|
|
|
374
386
|
{ drawing: line.drawing, end: line.end }
|
|
375
387
|
end
|
|
376
388
|
private :last_turn_drawing
|
|
377
389
|
|
|
390
|
+
# The turn id of the last user message that opens a turn
|
|
391
|
+
# (Steer.turn_prompt?, as JoinReplay finds the prompt it draws), nil
|
|
392
|
+
# for none or one with no id (a `!cmd`'s record, a line from before
|
|
393
|
+
# turn ids).
|
|
394
|
+
def last_prompt_turn_id(messages)
|
|
395
|
+
prompt = messages.reverse_each.find { |m| m.is_a?(Hash) && (m[:role] || m["role"]).to_s == "user" && Steer.turn_prompt?(m) }
|
|
396
|
+
id = prompt && (prompt[:turn_id] || prompt["turn_id"])
|
|
397
|
+
id.is_a?(String) && !id.empty? ? id : nil
|
|
398
|
+
end
|
|
399
|
+
private :last_prompt_turn_id
|
|
400
|
+
|
|
378
401
|
# The snapshot and the session state (status, pending question, ...) as
|
|
379
402
|
# one step of the event log, both as of the same event_seq: what a
|
|
380
403
|
# snapshot or reset frame (SSEWriter) and GET snapshot carry.
|
|
@@ -5,6 +5,8 @@ require_relative "../delivery"
|
|
|
5
5
|
require_relative "../session"
|
|
6
6
|
require_relative "../worker_link"
|
|
7
7
|
require_relative "../bridge/turn_accumulator"
|
|
8
|
+
require_relative "../bridge/turn_drawings"
|
|
9
|
+
require_relative "../degrade"
|
|
8
10
|
require_relative "../tools/delegate"
|
|
9
11
|
require_relative "../children_status"
|
|
10
12
|
require_relative "../context_move"
|
|
@@ -63,9 +65,14 @@ module Samagotchi
|
|
|
63
65
|
check_children(parent_id, state_dir) if prompt
|
|
64
66
|
|
|
65
67
|
# The fork takes this session's movable attached context, its
|
|
66
|
-
# subscriptions as its seed last had them
|
|
68
|
+
# subscriptions as its seed last had them, and the drawings of the
|
|
69
|
+
# turns its seed keeps as they were (Bridge::TurnDrawings.carry).
|
|
67
70
|
before_spawn = lambda do |forked|
|
|
68
71
|
ContextMove.call(from: parent_id, to: forked.id, mode: :fork, seed: forked.messages, state_dir: state_dir)
|
|
72
|
+
Degrade.call(:plugins, "fork_drawings_not_carried", fallback: 0) do
|
|
73
|
+
Bridge::TurnDrawings.carry(from_dir: Session.session_dir(parent_id, state_dir: state_dir),
|
|
74
|
+
to_dir: Session.session_dir(forked.id, state_dir: state_dir), messages: forked.messages)
|
|
75
|
+
end
|
|
69
76
|
end
|
|
70
77
|
child = SessionManager.spawn_session(
|
|
71
78
|
prompt: prompt, working_directory: @host.cwd.call || Dir.pwd, model_name: @host.model_name&.call,
|
|
@@ -18,7 +18,7 @@ module Samagotchi
|
|
|
18
18
|
# The one text for the condition.
|
|
19
19
|
def message
|
|
20
20
|
"#{Paths.tilde(root)} and #{Paths.tilde(other)} share chi project id #{id} (a copied folder?): they share " \
|
|
21
|
-
"memories
|
|
21
|
+
"memories. Run `chi project init --new-id` in the copy to give it its own."
|
|
22
22
|
end
|
|
23
23
|
end
|
|
24
24
|
|
|
@@ -2,14 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
require_relative "../bridge/turn_accumulator"
|
|
4
4
|
require_relative "../bridge/turn_drawings"
|
|
5
|
+
require_relative "../bridge/turn_drawings/synth"
|
|
6
|
+
require_relative "../bridge/turn_ranges"
|
|
5
7
|
require_relative "../context_note"
|
|
6
8
|
require_relative "../image_store"
|
|
7
9
|
require_relative "../log"
|
|
8
|
-
require_relative "../message_parts"
|
|
9
10
|
require_relative "../output_formatter"
|
|
10
11
|
require_relative "../steer"
|
|
11
|
-
require_relative "../tool_activity"
|
|
12
|
-
require_relative "../tool_view"
|
|
13
12
|
require_relative "../turn_note"
|
|
14
13
|
require_relative "event_renderer"
|
|
15
14
|
require_relative "formatting"
|
|
@@ -33,11 +32,13 @@ module Samagotchi
|
|
|
33
32
|
@renderer = renderer
|
|
34
33
|
end
|
|
35
34
|
|
|
36
|
-
#
|
|
37
|
-
#
|
|
38
|
-
#
|
|
35
|
+
# The last prompt's turn is drawn from a drawing: the snapshot's
|
|
36
|
+
# last_turn_drawing (Bridge#snapshot: as live drew it) when it is that
|
|
37
|
+
# turn's, else one made from the snapshot's messages, the link's saved
|
|
38
|
+
# records and the snapshot's cards (Bridge::TurnDrawings::Synth: an
|
|
39
|
+
# older worker, a turn before drawings, a line over 1 MB).
|
|
39
40
|
def render_join(snapshot, saved)
|
|
40
|
-
render_join_header(Array(snapshot[:messages]), drawing: snapshot[:last_turn_drawing])
|
|
41
|
+
render_join_header(Array(snapshot[:messages]), drawing: snapshot[:last_turn_drawing], cards: Array(snapshot[:cards]))
|
|
41
42
|
render_join_gap(snapshot, saved)
|
|
42
43
|
end
|
|
43
44
|
|
|
@@ -106,7 +107,7 @@ module Samagotchi
|
|
|
106
107
|
@screen.commit(gap_divider(line)) if line
|
|
107
108
|
end
|
|
108
109
|
|
|
109
|
-
def render_join_header(messages, drawing: nil)
|
|
110
|
+
def render_join_header(messages, drawing: nil, cards: [])
|
|
110
111
|
exchange = messages.select { |m| %w[user model assistant].include?(m[:role].to_s) }
|
|
111
112
|
# The id stays findable: the detach line and chi sessions list show it.
|
|
112
113
|
Log.session_id = @link.client.session_id
|
|
@@ -119,36 +120,17 @@ module Samagotchi
|
|
|
119
120
|
render_join_notes(messages, from)
|
|
120
121
|
return unless last_user
|
|
121
122
|
|
|
122
|
-
|
|
123
|
+
prompt = exchange[last_user]
|
|
124
|
+
@screen.commit(join_prompt_line(prompt))
|
|
123
125
|
# An image-only turn's text names its images already.
|
|
124
|
-
unless ImageRef.placeholder_only?(
|
|
125
|
-
Array(
|
|
126
|
+
unless ImageRef.placeholder_only?(prompt[:content])
|
|
127
|
+
Array(prompt[:images]).each { |ref| @screen.commit(format_image_line(ref)) }
|
|
126
128
|
end
|
|
127
|
-
|
|
129
|
+
drawn = drawn_turn(drawing, prompt) || made_turn(messages, from, cards)
|
|
130
|
+
if drawn
|
|
128
131
|
render_drawn_turn(*drawn, exchange[(last_user + 1)..])
|
|
129
|
-
return render_join_notes(messages, from, after_exchange: true)
|
|
130
|
-
end
|
|
131
|
-
|
|
132
|
-
render_join_steps(messages, from, durations: join_tool_records(exchange[last_user]))
|
|
133
|
-
record = @link.saved_turn_record(exchange[last_user][:turn_id] || exchange[last_user]["turn_id"])
|
|
134
|
-
failed = join_failed_record(record)
|
|
135
|
-
# A turn that ended with no answer: its notice, as live.
|
|
136
|
-
empty = messages.drop(from + 1).filter_map { |m| TurnNote.empty_answer(m) }.last
|
|
137
|
-
if empty
|
|
138
|
-
@screen.commit(format_empty_answer_line(empty[:retries] || empty["retries"], empty[:refusal] || empty["refusal"]))
|
|
139
|
-
elsif failed
|
|
140
|
-
# A failed turn whose steps stayed: the line the live view left,
|
|
141
|
-
# and no step text as if it were the answer (the web keeps a
|
|
142
|
-
# failed turn's texts as steps too).
|
|
143
|
-
failure = failed["failure"]
|
|
144
|
-
@screen.commit(@view.turn_failed_line(failure["summary"] || failure["message"], failed["duration_ms"]))
|
|
145
|
-
@screen.commit(@view.turn_end_hint(ROLLBACK_HINT)) if failure["kept_steps"]
|
|
146
|
-
elsif record && record["status"] == "canceled"
|
|
147
|
-
# A canceled turn (a Stop, Ctrl-C): its line, as live, and no
|
|
148
|
-
# text it streamed before the cancel as if it were the answer.
|
|
149
|
-
@screen.commit(@view.turn_canceled_line(record["cancellation_reason"], record["duration_ms"], by: record["cancelled_by"]))
|
|
150
|
-
@screen.commit(@view.turn_end_hint(ROLLBACK_HINT)) unless record["continue"]
|
|
151
132
|
else
|
|
133
|
+
# No turn ran for it (a `!cmd`'s record): what came after it.
|
|
152
134
|
render_join_answer(exchange[(last_user + 1)..])
|
|
153
135
|
end
|
|
154
136
|
render_join_notes(messages, from, after_exchange: true)
|
|
@@ -179,6 +161,24 @@ module Samagotchi
|
|
|
179
161
|
[turn, EventRenderer.symbolize(Bridge::TurnAccumulator.from_wire(drawing[:end]))]
|
|
180
162
|
end
|
|
181
163
|
|
|
164
|
+
# The prompt's turn (its opening at +from+ in +messages+) drawn from
|
|
165
|
+
# its messages (TurnRanges, Synth.safe_line) with the link's saved
|
|
166
|
+
# records of it (this machine's, or chi web's for --remote) and the
|
|
167
|
+
# snapshot's +cards+ (its CardStore rows), as [turn, end event]; nil
|
|
168
|
+
# when no turn opens there.
|
|
169
|
+
def made_turn(messages, from, cards)
|
|
170
|
+
# Its opening, or the range that holds it (a wake turn's report, its note the opening).
|
|
171
|
+
range = Bridge::TurnRanges.of(messages).find { |r| r.opening == from || r.range.cover?(from) }
|
|
172
|
+
return nil unless range
|
|
173
|
+
|
|
174
|
+
# Tool records first: a remote link reads both in one request then
|
|
175
|
+
# (RemoteLink#saved_tool_records keeps it for #saved_turn_record).
|
|
176
|
+
tools = range.turn_id ? Array(@link.saved_tool_records(range.turn_id)) : []
|
|
177
|
+
record = range.turn_id && @link.saved_turn_record(range.turn_id)
|
|
178
|
+
line = Bridge::TurnDrawings::Synth.safe_line(messages, range, record: record, tools: tools, entries: cards)
|
|
179
|
+
[Bridge::TurnAccumulator.from_wire(line.drawing), EventRenderer.symbolize(Bridge::TurnAccumulator.from_wire(line.end))]
|
|
180
|
+
end
|
|
181
|
+
|
|
182
182
|
# The last turn from its drawing, through the renderer as live drew it
|
|
183
183
|
# (the running turn's join path, AttachedLoop#render_current_turn): its
|
|
184
184
|
# rows with their status and duration, a retry's line, a hook's notice,
|
|
@@ -202,100 +202,6 @@ module Samagotchi
|
|
|
202
202
|
@view.finish_thinking_spinner
|
|
203
203
|
end
|
|
204
204
|
|
|
205
|
-
# What the last exchange did, as the live turn drew it: each saved
|
|
206
|
-
# call's tool row (action, params, status from its result, and its
|
|
207
|
-
# duration from +durations+, the turn's saved tool records) and a
|
|
208
|
-
# plugin's steer and the user's input merged into the turn where they
|
|
209
|
-
# came. The step texts stay out, as live (the ticker's).
|
|
210
|
-
def render_join_steps(messages, from, durations: [])
|
|
211
|
-
records = durations.dup
|
|
212
|
-
messages.each_with_index.drop(from + 1).each do |m, i|
|
|
213
|
-
if Steer.steer?(m)
|
|
214
|
-
@screen.commit(format_steer_line(source: m[:source], text: m[:content]))
|
|
215
|
-
elsif Steer.input?(m) && !Steer.turn_prompt?(m)
|
|
216
|
-
@screen.commit("input> #{m[:content]}")
|
|
217
|
-
elsif %w[model assistant].include?(m[:role].to_s)
|
|
218
|
-
responses = messages.drop(i + 1).take_while { |r| r[:role].to_s == "tool_response" }
|
|
219
|
-
Array(MessageParts.for_message(m, responses)&.dig(:tools)).each do |part|
|
|
220
|
-
record = join_record(records, part)
|
|
221
|
-
duration = record&.dig("duration_ms")
|
|
222
|
-
@screen.commit(join_tool_line(part, duration_ms: duration.is_a?(Numeric) ? duration : nil,
|
|
223
|
-
saved_status: record&.dig("status"),
|
|
224
|
-
auto_allowed: record&.dig("guardrail")))
|
|
225
|
-
end
|
|
226
|
-
end
|
|
227
|
-
end
|
|
228
|
-
end
|
|
229
|
-
|
|
230
|
-
# The prompt's turn's saved tool records (AttachLink: SessionMetrics,
|
|
231
|
-
# in this machine's state dir, as #attach_images): none for a prompt
|
|
232
|
-
# with no turn id (an older session) or a session with no analytics.
|
|
233
|
-
def join_tool_records(prompt)
|
|
234
|
-
@link.saved_tool_records(prompt[:turn_id] || prompt["turn_id"])
|
|
235
|
-
end
|
|
236
|
-
|
|
237
|
-
# The turn's saved +record+ when it failed with the fields its line is
|
|
238
|
-
# made of (SessionMetrics#failure_fields), else nil: a completed or
|
|
239
|
-
# older turn — or one saved before the failure field — draws its
|
|
240
|
-
# answer as before (a canceled one its line).
|
|
241
|
-
def join_failed_record(record)
|
|
242
|
-
return nil unless record && record["status"] == "failed" && record["failure"].is_a?(Hash)
|
|
243
|
-
|
|
244
|
-
failure = record["failure"]
|
|
245
|
-
return nil if failure["summary"].to_s.empty? && failure["message"].to_s.empty?
|
|
246
|
-
|
|
247
|
-
record
|
|
248
|
-
end
|
|
249
|
-
|
|
250
|
-
# The saved record of +part+'s call (its duration and status): the
|
|
251
|
-
# next record of its tool, in call order, consumed with the ones it
|
|
252
|
-
# skipped. By tool and order, not by iteration: an empty retry spends
|
|
253
|
-
# an iteration that left no message (as the web's timing.js
|
|
254
|
-
# takeRecord). nil for a call that left none: it never finished, or a
|
|
255
|
-
# worker before turn ids saved it.
|
|
256
|
-
def join_record(records, part)
|
|
257
|
-
return nil if part[:output].nil?
|
|
258
|
-
|
|
259
|
-
at = records.index { |r| r["tool"].to_s == part[:tool].to_s }
|
|
260
|
-
return nil unless at
|
|
261
|
-
|
|
262
|
-
records.shift(at + 1).last
|
|
263
|
-
end
|
|
264
|
-
|
|
265
|
-
# A saved call's row; "no result" for a call the turn never answered
|
|
266
|
-
# (it ended first). Its status is the saved record's, as live and the
|
|
267
|
-
# web's reload (a guardrail's "blocked" is no error), else read from
|
|
268
|
-
# its result (a guardrail's deny text reads blocked too). A record that
|
|
269
|
-
# System 1 allowed once (+auto_allowed+, its saved {rule, p}) says so,
|
|
270
|
-
# as the live row does.
|
|
271
|
-
def join_tool_line(part, duration_ms: nil, saved_status: nil, auto_allowed: nil)
|
|
272
|
-
output = part[:output]
|
|
273
|
-
command = part.dig(:view, :truncated) ? nil : part.dig(:view, :command)
|
|
274
|
-
text = ToolActivity.saved_result_text(output) unless output.nil?
|
|
275
|
-
status = if output.nil?
|
|
276
|
-
"no result"
|
|
277
|
-
elsif !saved_status.to_s.empty?
|
|
278
|
-
saved_status.to_s
|
|
279
|
-
elsif ToolActivity.guardrail_denied?(text)
|
|
280
|
-
"blocked"
|
|
281
|
-
else
|
|
282
|
-
ToolActivity.tool_activity_status(text, part[:tool], command: command)
|
|
283
|
-
end
|
|
284
|
-
activity = { action: part[:label] || ToolActivity.tool_activity_action(part[:tool]), tool: part[:tool],
|
|
285
|
-
params: part[:params], status: status,
|
|
286
|
-
description: ToolView.description_title(part[:view] || {}) }
|
|
287
|
-
"#{format_tool_activity_line(activity, duration_ms: duration_ms)}" \
|
|
288
|
-
"#{format_tool_image_suffix(part[:images])}#{format_tool_diff_suffix(part[:diff])}#{format_tool_cut_suffix(part[:output_truncated])}" \
|
|
289
|
-
"#{auto_allowed_suffix(auto_allowed)}"
|
|
290
|
-
end
|
|
291
|
-
|
|
292
|
-
# The live row's System 1 suffix for a saved record's {rule, p}.
|
|
293
|
-
def auto_allowed_suffix(saved)
|
|
294
|
-
return "" unless saved.is_a?(Hash)
|
|
295
|
-
|
|
296
|
-
format_tool_guardrail_suffix({ decided_by: "system one", p: saved["p"] || saved[:p] })
|
|
297
|
-
end
|
|
298
|
-
|
|
299
205
|
# The context notes that came since the last prompt (+from+, its index
|
|
300
206
|
# in +messages+; all of them in a session with none), after the
|
|
301
207
|
# exchange the header shows.
|