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,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require_relative "guardrails/path_resolve"
5
+ require_relative "memory_paths"
6
+ require_relative "paths"
7
+
8
+ module Samagotchi
9
+ # Memories saved from a subfolder of a marked project before
10
+ # `chi project init`: a session there keyed them by its own path
11
+ # (MemoryPaths.lookup was :none, the root its cwd), and after init the
12
+ # subfolder resolves to the project, so that folder is out of reach.
13
+ #
14
+ # A path key can't be reversed, so the candidates come only from this
15
+ # machine's session rows (each stores the root it keyed by: a project-less
16
+ # session's is its cwd); memories older than the sessions kept are not
17
+ # found (docs/memory.md: move them by hand). No directory walk: one
18
+ # listing of the sessions, one stat per row. Memories only: a subfolder's
19
+ # project context sources and skills history stay where they are.
20
+ #
21
+ # The one text for the condition is #message (`chi project init`'s report
22
+ # and `chi project`'s note); #merge (`chi project init --merge-subfolders`)
23
+ # moves them, #running_message refuses while a session could write.
24
+ module ProjectSubfolders
25
+ # +path+: the subfolder a session keyed its memories by; +dir+: that
26
+ # memories folder; +count+: the memories in it.
27
+ Found = Data.define(:path, :dir, :count)
28
+
29
+ FLAG = "--merge-subfolders"
30
+ INDEX = "index.md"
31
+ # What an emptied folder may still hold, none of it moved: the index
32
+ # (removed only when #hand_written? says it holds nothing of the user's),
33
+ # IndexUpdater's lock, and .root: ProjectIdClash's claim, written only in
34
+ # an id folder, so in a path-keyed one it is a copy's stray (a copied
35
+ # id folder renamed by hand) that names no folder this key belongs to.
36
+ LEFTOVERS = [INDEX, ".index.lock", ".root"].freeze
37
+
38
+ module_function
39
+
40
+ # The subfolders of +root+ (a marked project's realpath) whose
41
+ # path-keyed memories folder exists: a row's stored root under +root+
42
+ # that resolves to +root+ now (a nested git repository or marked folder
43
+ # is its own project; a symlink out of +root+ resolves elsewhere).
44
+ # @param sessions [Array<SessionRow>] this machine's sessions (+project+, +cwd+)
45
+ # @return [Array<Found>] sorted by path
46
+ def find(root, sessions:, env: ENV, home: MemoryPaths.default_home)
47
+ projects = MemoryPaths.projects_dir(env: env)
48
+ seen = {}
49
+ Array(sessions).each do |row|
50
+ path = (row.project || row.cwd).to_s
51
+ next if path.empty? || seen.key?(path)
52
+
53
+ seen[path] = nil
54
+ real = Guardrails::PathResolve.real(path)
55
+ next if real == root || !Guardrails::PathResolve.under?(real, root)
56
+ next unless MemoryPaths.lookup(path, home: home).root == root
57
+
58
+ dir = File.join(projects, MemoryPaths.key_for_root(path))
59
+ next unless File.directory?(dir) && !File.symlink?(dir)
60
+
61
+ count = entries(dir).size
62
+ seen[path] = Found.new(path: path, dir: dir, count: count) if count.positive?
63
+ end
64
+ seen.values.compact.uniq(&:dir).sort_by(&:path)
65
+ end
66
+
67
+ # The one text for found subfolder memories, or nil for none.
68
+ def message(found)
69
+ return nil if found.empty?
70
+
71
+ list = found.map { |item| "#{Paths.tilde(item.path)} (#{item.count} #{item.count == 1 ? "memory" : "memories"})" }
72
+ "memories saved from subfolders before init: #{list.join(", ")}; move them into the project with " \
73
+ "chi project init #{FLAG}"
74
+ end
75
+
76
+ # The running sessions that refuse a merge: under +root+ by the root
77
+ # they stored or by their folder (a live pre-init session stored its cwd).
78
+ def running(root, sessions:, home: MemoryPaths.default_home)
79
+ Array(sessions).select do |row|
80
+ next false unless row.live
81
+
82
+ [row.project, row.cwd].compact.map(&:to_s).reject(&:empty?).any? do |path|
83
+ Guardrails::PathResolve.under?(Guardrails::PathResolve.real(path), root) ||
84
+ MemoryPaths.lookup(path, home: home).root == root
85
+ end
86
+ end
87
+ end
88
+
89
+ def running_message(root, rows)
90
+ "#{Paths.tilde(root)} has running sessions (#{rows.map { |row| row.id[0, 8] }.join(", ")}): stop them " \
91
+ "(chi sessions stop ID) and rerun chi project init #{FLAG}, which moves the subfolders' memories while " \
92
+ "no session can write to them"
93
+ end
94
+
95
+ # Moves each found folder's memories (the file, its model overlays,
96
+ # its index line) into +target+ (the project's memories folder). One
97
+ # the project has by that name, or a bundle owns, stays and is named;
98
+ # an emptied folder is removed, with no link: every chi that knows
99
+ # markers resolves the subfolder to the project, and a link would hide
100
+ # a folder made there again from #find.
101
+ # @return [Array<String>] the report's lines
102
+ def merge(found, target:, env: ENV)
103
+ require_relative "memory_bundle/index_updater"
104
+ require_relative "memory_bundle/provenance"
105
+ require_relative "tools/memory"
106
+ lines = []
107
+ found.each { |item| lines.concat(merge_one(item, target, env)) }
108
+ lines << "no memories saved from subfolders before init to move" if lines.empty?
109
+ lines
110
+ end
111
+
112
+ # The entries of a memories folder: each <name>.md but the index and
113
+ # the model overlays of another entry (Tools::MemoryWrite.overlay_files),
114
+ # with its managed index line (or nil).
115
+ # @return [Hash{String => String, nil}] name → line
116
+ def entries(dir)
117
+ index_text = index_text(dir)
118
+ names = Dir.children(dir).select { |name| name.end_with?(".md") && name != INDEX && File.file?(File.join(dir, name)) }
119
+ .map { |name| name.delete_suffix(".md") }.sort
120
+ require_relative "tools/memory"
121
+ overlays = names.flat_map { |name| Tools::MemoryWrite.overlay_files(dir, name, index_text) }
122
+ .map { |path| File.basename(path, ".md") }
123
+ (names - overlays).to_h { |name| [name, index_text[Tools::MemoryWrite.managed_pattern(name)]&.chomp] }
124
+ end
125
+
126
+ def index_text(dir)
127
+ path = File.join(dir, INDEX)
128
+ File.file?(path) ? File.read(path, encoding: "UTF-8") : ""
129
+ end
130
+
131
+ def merge_one(item, target, env)
132
+ from = item.dir
133
+ index_text = index_text(from)
134
+ moved = []
135
+ kept = []
136
+ entries(from).each do |name, line|
137
+ files = [File.join(from, "#{name}.md")] + Tools::MemoryWrite.overlay_files(from, name, index_text)
138
+ owner = MemoryBundle::Provenance.claimants("#{name}.md", scope: "project",
139
+ dir: MemoryPaths.bundles_dir(env: env)).first ||
140
+ (line && MemoryBundle::IndexUpdater.extract_source(line))
141
+ next kept << "#{name} (from bundle #{owner})" if owner
142
+ next kept << "#{name} (the project has one by that name)" if files.any? { |path| File.exist?(File.join(target, File.basename(path))) }
143
+
144
+ FileUtils.mkdir_p(target)
145
+ bytes = File.size(files.first)
146
+ files.each { |path| File.rename(path, File.join(target, File.basename(path))) }
147
+ description = line && MemoryBundle::IndexUpdater.extract_description(line)
148
+ MemoryBundle::IndexUpdater.update_index("project", name, bytes, description, target_dir: target)
149
+ MemoryBundle::IndexUpdater.remove_index("project", name, target_dir: from)
150
+ moved << name
151
+ end
152
+
153
+ lines = []
154
+ unless moved.empty?
155
+ lines << "moved #{moved.size} #{moved.size == 1 ? "memory" : "memories"} saved from " \
156
+ "#{Paths.tilde(item.path)} into #{Paths.tilde(target)}: #{moved.join(", ")}"
157
+ end
158
+ lines << "kept in #{Paths.tilde(from)}: #{kept.join(", ")}" unless kept.empty?
159
+ rest = Dir.children(from) - LEFTOVERS
160
+ if rest.empty? && hand_written?(index_text(from))
161
+ lines << "#{Paths.tilde(from)} keeps its index.md: it has lines written by hand"
162
+ elsif rest.empty?
163
+ FileUtils.rm_rf(from)
164
+ lines << "removed the emptied #{Paths.tilde(from)}"
165
+ else
166
+ left = index_text(from)
167
+ memory_files = entries(from).keys.flat_map do |name|
168
+ ["#{name}.md"] + Tools::MemoryWrite.overlay_files(from, name, left).map { |path| File.basename(path) }
169
+ end
170
+ others = (rest - memory_files).sort
171
+ lines << "#{Paths.tilde(from)} keeps files that aren't memories: #{others.join(", ")}" unless others.empty?
172
+ end
173
+ lines
174
+ end
175
+
176
+ # Whether an index holds a line that isn't the auto header, blank or a
177
+ # managed line (memory_write keeps every other line byte for byte; a
178
+ # dangling managed line, its file gone, may go with the folder).
179
+ def hand_written?(text)
180
+ header = MemoryBundle::IndexUpdater.auto_index_header.lines.map(&:strip)
181
+ text.each_line.any? do |line|
182
+ line = line.strip
183
+ !(line.empty? || header.include?(line) || line.match?(/\A- \*\*[^*]+\*\*[ \t]*(?:[·•].*|:.*)?\z/))
184
+ end
185
+ end
186
+ private_class_method :index_text, :merge_one, :hand_written?
187
+ end
188
+ end
@@ -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
- # A snapshot's last_turn_drawing (Bridge#snapshot: the last exchange's
37
- # turn as live drew it) draws that turn's rows; without one (an older
38
- # worker, a turn before drawings) they are rebuilt from the messages.
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
- @screen.commit(join_prompt_line(exchange[last_user]))
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?(exchange[last_user][:content])
125
- Array(exchange[last_user][:images]).each { |ref| @screen.commit(format_image_line(ref)) }
126
+ unless ImageRef.placeholder_only?(prompt[:content])
127
+ Array(prompt[:images]).each { |ref| @screen.commit(format_image_line(ref)) }
126
128
  end
127
- if (drawn = drawn_turn(drawing, exchange[last_user]))
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)
@@ -164,8 +146,8 @@ module Samagotchi
164
146
 
165
147
  # The snapshot's drawing as [turn, end event] when it is +prompt+'s
166
148
  # turn (a Continue's or a reminder's drawing isn't the prompt's: the
167
- # rows are rebuilt), else nil; nil too for one whose parts aren't a
168
- # list of rows.
149
+ # prompt's turn is made from its messages, #made_turn), else nil; nil
150
+ # too for one whose parts aren't a list of rows.
169
151
  def drawn_turn(drawing, prompt)
170
152
  return nil unless drawing.is_a?(Hash) && drawing[:drawing].is_a?(Hash) && drawing[:end].is_a?(Hash)
171
153
 
@@ -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.
@@ -14,6 +14,8 @@ require_relative "host_registry"
14
14
  require_relative "session"
15
15
  require_relative "owner_lock"
16
16
  require_relative "bridge/card_store"
17
+ require_relative "bridge/turn_accumulator"
18
+ require_relative "bridge/turn_drawings"
17
19
  require_relative "bridge/pending_card"
18
20
  require_relative "engine"
19
21
  require_relative "turn_flow"
@@ -253,11 +255,20 @@ module Samagotchi
253
255
  end
254
256
  ArchiveStore.user_input(session.id, state_dir: Session.default_state_dir)
255
257
  sink = OneShotSink.new
258
+ # The turn's drawing, as a worker's Bridge writes it: this process is
259
+ # the session's owner (OwnerLock), the file's one writer meanwhile.
260
+ drawings = Bridge::TurnDrawings.new(path: File.join(Session.session_dir(session.id), Bridge::TurnDrawings::FILE),
261
+ messages: -> { session.messages })
262
+ accumulator = Bridge::TurnAccumulator.new(on_turn_end: drawings.method(:append))
263
+ events = lambda do |event|
264
+ sink.call(event)
265
+ accumulator.call(event)
266
+ end
256
267
  save_before_first_turn(session)
257
268
  attach_mentioned_context(session, prompt)
258
269
  max_iterations = IterationLimit.for(no_interrupt: true)
259
270
  begin
260
- result = @engine.run_turn(session, prompt, on_event: sink, max_iterations: max_iterations,
271
+ result = @engine.run_turn(session, prompt, on_event: events, max_iterations: max_iterations,
261
272
  cancel_controller: nil, images: ImageInput.extract(prompt))
262
273
  rescue LLM::ProviderError, ImageStore::Error => e
263
274
  return one_shot_failed(session, e)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.161.0"
4
+ VERSION = "0.163.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -90,27 +90,31 @@ module Samagotchi
90
90
 
91
91
  # @param msgs [Array<Hash>] a session's messages; symbol keys from disk,
92
92
  # string keys from a Bridge snapshot
93
- # @param parts [Boolean] the turn block's reload (?parts=1): each
94
- # assistant message also carries what it did (MessageParts: thinking,
95
- # tool calls with params and output), and a message with nothing to
96
- # show but that (a text-less step) is kept with empty content
93
+ # @param parts [Boolean] the participant review's: each assistant
94
+ # message also carries what it did (MessageParts: thinking, tool
95
+ # calls with params and output), and a message with nothing to show
96
+ # but that (a text-less step) is kept with empty content
97
97
  # @param cwd [String, nil] the session's working directory (the parts'
98
98
  # tool titles are relative to it)
99
99
  # @param markdown [Boolean] false: no html for a delegate report or an
100
100
  # answer (the participant review drops both and renders its replies
101
101
  # from their redacted text, ParticipantReview#with_reply_html)
102
- # @param drawings [Array<Bridge::TurnDrawings::Line>] the valid lines
103
- # (TurnDrawings.valid against +msgs+): each item of a kind a drawing
104
- # draws (#drawn_kind?) from a line's range gets `drawn: <turn_id>`
105
- # @param strip_drawn [Boolean] a stamped item's parts go (the drawing
106
- # has them); it keeps its ✂ marks as `marks: {tool_id => edit}`
107
- def messages_for_display(msgs, parts: false, cwd: nil, markdown: true, drawings: [], strip_drawn: false)
102
+ # @param drawings [Array<Bridge::TurnDrawings::Line>, nil] the owner
103
+ # show's lines (TurnDrawings.cover against +msgs+): each item of a
104
+ # kind a drawing draws (#drawn_kind?) from a line's range gets
105
+ # `drawn: <turn_id>`, a step its outputs' ✂ marks as `marks:
106
+ # {tool_id => edit}` (an overlay on the drawing's rows), and a
107
+ # text-less step stays (empty content: its marks, the turn's last
108
+ # step); nil: no stamps (the participant review, a lone answer)
109
+ def messages_for_display(msgs, parts: false, cwd: nil, markdown: true, drawings: nil)
108
110
  filtered = []
109
111
  list = Array(msgs)
112
+ steps = !drawings.nil?
110
113
  # Each item's message index, for the drawings' stamps.
111
114
  origins = []
112
- # The outputs' ✂ marks (LLM context edits), by id, for the parts.
113
- marks = parts ? MessageParts.edit_marks(list) : {}
115
+ # The outputs' ✂ marks (LLM context edits), by id, for the parts
116
+ # and the drawn steps.
117
+ marks = parts || steps ? MessageParts.edit_marks(list) : {}
114
118
  # The list before each objectives note, for what its entry says changed.
115
119
  objectives = nil
116
120
  list.each_with_index do |m, index|
@@ -145,7 +149,7 @@ module Samagotchi
145
149
  # empty steps (with ?parts=1) and the item the page draws its
146
150
  # notice from; the note itself stays hidden.
147
151
  if (marker = Samagotchi::TurnNote.empty_answer(m))
148
- filtered.concat(empty_answer_items(marker, parts: parts, cwd: cwd))
152
+ filtered.concat(empty_answer_items(marker, parts: parts, steps: steps, cwd: cwd))
149
153
  next
150
154
  end
151
155
  next if role == "system"
@@ -155,8 +159,9 @@ module Samagotchi
155
159
  next if Samagotchi::Steer.recovery?(m)
156
160
 
157
161
  stripped = Samagotchi::OutputFormatter.strip_markup(content)
158
- did = parts && %w[model assistant].include?(role) ? message_parts(list, index, cwd, marks) : nil
159
- next if stripped.empty? && did.nil?
162
+ step = %w[model assistant].include?(role)
163
+ did = parts && step ? message_parts(list, index, cwd, marks) : nil
164
+ next if stripped.empty? && did.nil? && !(steps && step && did_something?(m, content))
160
165
 
161
166
  norm_role = role == "model" ? "assistant" : role
162
167
  # normalize assistant vs model, keep user as is
@@ -219,27 +224,52 @@ module Samagotchi
219
224
  message[:display_refs] = refs unless refs.empty?
220
225
  end
221
226
  message[:parts] = did if did
227
+ step_marks = steps && step ? output_marks(list, index, cwd, marks) : {}
228
+ message[:marks] = step_marks unless step_marks.empty?
222
229
  filtered << message
223
230
  end
224
231
  origins.fill(list.size - 1, origins.size...filtered.size)
225
- stamp_drawn(filtered, origins, Array(drawings), strip: strip_drawn)
232
+ stamp_drawn(filtered, origins, Array(drawings))
226
233
  rescue StandardError
227
234
  []
228
235
  end
229
236
 
237
+ # Whether a text-less model message did something a drawing draws as
238
+ # a step: a call or thinking (MessageParts' own read, without
239
+ # parsing the calls).
240
+ def did_something?(message, content)
241
+ calls = message[:tool_calls] || message["tool_calls"]
242
+ (calls.is_a?(Array) && !calls.empty?) || !content.strip.empty? || !(message[:thinking] || message["thinking"]).to_s.strip.empty?
243
+ end
244
+
245
+ # The ✂ marks of the outputs right after the model message at +index+,
246
+ # by output id, as its parts have them (a stub's size from its own
247
+ # output): its parts are read only when +marks+ (the session's, by
248
+ # output id) names one of them.
249
+ def output_marks(list, index, cwd, marks)
250
+ return {} if marks.empty?
251
+
252
+ responses = list.drop(index + 1).take_while { |r| (r[:role] || r["role"]).to_s == "tool_response" }
253
+ return {} unless responses.any? { |r| Array(r[:tool_ids] || r["tool_ids"]).any? { |id| marks.key?(id.to_s) } }
254
+
255
+ tools = Array(message_parts(list, index, cwd, marks)&.dig(:tools))
256
+ tools.filter_map { |tool| [tool[:tool_id], tool[:edit]] if tool[:tool_id] && tool[:edit] }.to_h
257
+ end
258
+
230
259
  # +items+ with a drawn turn's stamp on each item of a kind its drawing
231
260
  # draws (the opening, steps, steers, merged lines, the empty answer):
232
261
  # a context note, a `!cmd`'s record and anything else keep today's
233
262
  # place. +origins+: each item's message index.
234
- def stamp_drawn(items, origins, drawings, strip:)
263
+ # One walk: +drawings+ are sorted apart by range, +origins+ never go
264
+ # back.
265
+ def stamp_drawn(items, origins, drawings)
235
266
  return items if drawings.empty?
236
267
 
268
+ at = 0
237
269
  items.each_with_index.map do |item, i|
238
- line = drawings.find { |l| l.range.cover?(origins[i]) }
239
- next item unless line && drawn_kind?(item)
240
-
241
- stamped = item.merge(drawn: line.turn_id)
242
- strip ? without_parts(stamped) : stamped
270
+ at += 1 while at < drawings.size && drawings[at].to <= origins[i]
271
+ line = drawings[at] if at < drawings.size && drawings[at].range.cover?(origins[i])
272
+ line && drawn_kind?(item) ? item.merge(drawn: line.turn_id) : item
243
273
  end
244
274
  end
245
275
 
@@ -251,15 +281,6 @@ module Samagotchi
251
281
  end
252
282
  end
253
283
 
254
- # A drawn item without its parts: its ✂ marks by output id stay (an
255
- # overlay on the drawing's rows: later state, as a card's latest body).
256
- def without_parts(item)
257
- tools = Array(item.dig(:parts, :tools))
258
- marks = tools.filter_map { |tool| [tool[:tool_id], tool[:edit]] if tool[:tool_id] && tool[:edit] }.to_h
259
- out = item.except(:parts)
260
- marks.empty? ? out : out.merge(marks: marks)
261
- end
262
-
263
284
  # A turn opening's Revise stamp as {revises: {turn_id:}}, checked again
264
285
  # (a stored file is never trusted), or nothing.
265
286
  def revises_of(message)
@@ -276,13 +297,13 @@ module Samagotchi
276
297
 
277
298
  # A no-answer turn's marker as display items: each empty step that
278
299
  # has something to show (its thinking) as a text-less assistant step
279
- # (only with +parts+, as other text-less steps), then
280
- # { role: "empty_answer", retries: }.
281
- def empty_answer_items(marker, parts:, cwd:)
282
- steps = parts ? Array(marker[:steps] || marker["steps"]) : []
283
- items = steps.filter_map do |step|
300
+ # (only with +parts+ or +steps+, as other text-less steps; its parts
301
+ # with +parts+), then { role: "empty_answer", retries: }.
302
+ def empty_answer_items(marker, parts:, steps:, cwd:)
303
+ saved = parts || steps ? Array(marker[:steps] || marker["steps"]) : []
304
+ items = saved.filter_map do |step|
284
305
  did = step.is_a?(Hash) ? MessageParts.for_message(step, [], cwd: cwd) : nil
285
- { role: "assistant", content: "", parts: did } if did
306
+ { role: "assistant", content: "", **(parts ? { parts: did } : {}) } if did
286
307
  end
287
308
  refusal = marker[:refusal] || marker["refusal"]
288
309
  items << { role: "empty_answer", content: "", retries: (marker[:retries] || marker["retries"]).to_i, refusal: refusal }.compact
@@ -365,7 +365,7 @@ const reloadCheck = createReloadCheck({
365
365
  enabled: () => document.body.dataset.reloadCheck === "1",
366
366
  sessionId: () => store.selected,
367
367
  running: () => liveTurn.running,
368
- read: (id) => getSession(id, { parts: true }),
368
+ read: (id) => getSession(id),
369
369
  render: (data) => turnHistoryNodes(data.messages || [], normalizeTiming(data.timing), historyOpts(data)),
370
370
  post: (id, body) => api(`/api/sessions/${id}/reload_check`, { method: "POST", body: JSON.stringify(body) }),
371
371
  });
@@ -961,7 +961,7 @@ async function resync({ endText = null } = {}) {
961
961
  let data;
962
962
  try {
963
963
  try {
964
- data = await getSession(id, { parts: true });
964
+ data = await getSession(id);
965
965
  } catch (e) {
966
966
  if (e.status === 404) return leaveGoneSession(id, "not_found");
967
967
  if (id === store.selected) {
@@ -1090,13 +1090,12 @@ function renderSessionView(data, { kept = [] } = {}) {
1090
1090
  }
1091
1091
 
1092
1092
  // The working set's turns from a session's messages, as turnHistoryNodes
1093
- // numbers them; the running turn (the replay draws it in the stage) isn't
1094
- // one of them yet.
1093
+ // numbers them: the drawn ones (the running turn, which the replay draws
1094
+ // in the stage, has no drawing yet).
1095
1095
  function seedWorkingSet(data) {
1096
1096
  if (!workingSet) return;
1097
1097
  const items = data.messages || [];
1098
1098
  const groups = typeof items[0] === "object" && items[0]?.role ? turnGroups(items, store.current.timing, { drawings: data.turn_drawings }).filter((g) => g.kind === "turn") : [];
1099
- if (data.current_turn && groups.length) groups.pop();
1100
1099
  workingSet.seed(groups.map((g, i) => {
1101
1100
  const text = String(items[g.user]?.content ?? "").replace(/\s+/g, " ").trim();
1102
1101
  return { items: groupItems(g, i), prompt: text.length > 60 ? `${text.slice(0, 59)}\u2026` : text };
@@ -1104,9 +1103,11 @@ function seedWorkingSet(data) {
1104
1103
  }
1105
1104
 
1106
1105
  // turnHistoryNodes' options for a read's +data+: its turns' drawings
1107
- // (turn_drawing.js) and cards (a drawn card's body).
1106
+ // (turn_drawing.js), cards (a drawn card's body) and the running turn's id
1107
+ // (its prompt has no drawing yet: a plain row, no miss).
1108
1108
  const historyOpts = (data = {}) => ({ thumbs: (images) => thumbsTemplate(store.selected, images), workingSet: !!workingSet,
1109
- drawings: data.turn_drawings || null, cards: data.cards || null, capabilities: pageCapabilities });
1109
+ drawings: data.turn_drawings || null, cards: data.cards || null, capabilities: pageCapabilities,
1110
+ runningTurnId: data.current_turn?.turn_id || null });
1110
1111
 
1111
1112
  function renderHistory(items, data = {}) {
1112
1113
  gapClock.seed(null);