samagotchi 0.160.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.
Files changed (127) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +110 -1
  3. data/docs/architecture.md +8 -4
  4. data/docs/cli.md +6 -4
  5. data/docs/context.md +10 -1
  6. data/docs/guardrails.md +12 -3
  7. data/docs/internals/block-renderers.md +3 -2
  8. data/docs/internals/bridge.md +82 -17
  9. data/docs/internals/bundles.md +24 -5
  10. data/docs/internals/inline-widgets.md +6 -3
  11. data/docs/internals/objectives.md +8 -2
  12. data/docs/internals/remote-sessions.md +2 -1
  13. data/docs/internals/web-frontend.md +1 -1
  14. data/docs/memory.md +4 -2
  15. data/docs/plugins.md +13 -4
  16. data/docs/releasing.md +7 -4
  17. data/docs/scheduling.md +37 -5
  18. data/docs/sessions.md +15 -12
  19. data/docs/testing.md +16 -2
  20. data/lib/samagotchi/bridge/card_store.rb +54 -16
  21. data/lib/samagotchi/bridge/ring_buffer.rb +11 -1
  22. data/lib/samagotchi/bridge/sse_writer.rb +8 -5
  23. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -1
  24. data/lib/samagotchi/bridge/turn_drawings/synth.rb +555 -0
  25. data/lib/samagotchi/bridge/turn_drawings.rb +103 -7
  26. data/lib/samagotchi/bridge/turn_ranges.rb +175 -0
  27. data/lib/samagotchi/bridge.rb +127 -54
  28. data/lib/samagotchi/bridge_client.rb +9 -6
  29. data/lib/samagotchi/broadcast_command.rb +24 -8
  30. data/lib/samagotchi/bundle_command.rb +56 -6
  31. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  32. data/lib/samagotchi/child_reports.rb +29 -23
  33. data/lib/samagotchi/client_id.rb +2 -0
  34. data/lib/samagotchi/compat.rb +32 -0
  35. data/lib/samagotchi/context_candidates_log.rb +10 -1
  36. data/lib/samagotchi/context_command.rb +1 -1
  37. data/lib/samagotchi/context_move.rb +6 -1
  38. data/lib/samagotchi/engine/events.rb +12 -0
  39. data/lib/samagotchi/engine/plugins.rb +1 -1
  40. data/lib/samagotchi/engine/steering.rb +2 -2
  41. data/lib/samagotchi/guardrails/child_boundary.rb +37 -4
  42. data/lib/samagotchi/guardrails/protected_paths.rb +8 -5
  43. data/lib/samagotchi/guardrails/targets.rb +25 -6
  44. data/lib/samagotchi/live_versions.rb +7 -2
  45. data/lib/samagotchi/memory_bundle/asset_installer.rb +59 -12
  46. data/lib/samagotchi/memory_bundle/file_state.rb +11 -0
  47. data/lib/samagotchi/memory_bundle/index_updater.rb +7 -4
  48. data/lib/samagotchi/memory_bundle/installer.rb +79 -12
  49. data/lib/samagotchi/memory_bundle/provenance.rb +158 -6
  50. data/lib/samagotchi/memory_bundle/shipped_update.rb +2 -1
  51. data/lib/samagotchi/memory_bundle/status.rb +1 -1
  52. data/lib/samagotchi/memory_bundle/system_bundle.rb +2 -0
  53. data/lib/samagotchi/memory_bundle/uninstaller.rb +27 -13
  54. data/lib/samagotchi/memory_orphans.rb +40 -9
  55. data/lib/samagotchi/note_command.rb +9 -1
  56. data/lib/samagotchi/note_delivery.rb +34 -24
  57. data/lib/samagotchi/note_move.rb +205 -0
  58. data/lib/samagotchi/objectives_command.rb +3 -1
  59. data/lib/samagotchi/owner_lock.rb +7 -1
  60. data/lib/samagotchi/plugin/sessions.rb +8 -1
  61. data/lib/samagotchi/project_id_clash.rb +1 -1
  62. data/lib/samagotchi/project_init.rb +3 -3
  63. data/lib/samagotchi/review_start.rb +5 -3
  64. data/lib/samagotchi/schedule_command.rb +12 -0
  65. data/lib/samagotchi/schedules.rb +286 -48
  66. data/lib/samagotchi/send_command.rb +2 -15
  67. data/lib/samagotchi/session.rb +42 -5
  68. data/lib/samagotchi/session_access/local.rb +45 -17
  69. data/lib/samagotchi/session_access/remote.rb +11 -4
  70. data/lib/samagotchi/session_access/web_bridge_client.rb +2 -2
  71. data/lib/samagotchi/session_access.rb +16 -3
  72. data/lib/samagotchi/session_continue.rb +155 -21
  73. data/lib/samagotchi/session_delete_command.rb +3 -1
  74. data/lib/samagotchi/session_inbox.rb +41 -1
  75. data/lib/samagotchi/session_inbox_delivery.rb +254 -0
  76. data/lib/samagotchi/session_manager/delivery.rb +66 -12
  77. data/lib/samagotchi/session_manager/emptiness.rb +7 -2
  78. data/lib/samagotchi/session_manager/lifecycle.rb +2 -1
  79. data/lib/samagotchi/session_manager/listing.rb +4 -1
  80. data/lib/samagotchi/session_manager/removal.rb +130 -26
  81. data/lib/samagotchi/session_manager/spawn.rb +164 -104
  82. data/lib/samagotchi/session_manager.rb +1 -0
  83. data/lib/samagotchi/session_retention.rb +53 -23
  84. data/lib/samagotchi/session_setup.rb +27 -7
  85. data/lib/samagotchi/starting_marker.rb +93 -24
  86. data/lib/samagotchi/state_format.rb +18 -7
  87. data/lib/samagotchi/system_one/runs.rb +6 -1
  88. data/lib/samagotchi/system_one/runs_store.rb +18 -14
  89. data/lib/samagotchi/terminal_ui/attach_launcher.rb +7 -4
  90. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +5 -2
  91. data/lib/samagotchi/terminal_ui/attached_loop.rb +5 -0
  92. data/lib/samagotchi/terminal_ui/join_replay.rb +34 -128
  93. data/lib/samagotchi/terminal_ui/version_lines.rb +4 -2
  94. data/lib/samagotchi/terminal_ui.rb +14 -4
  95. data/lib/samagotchi/tools/delegate.rb +9 -4
  96. data/lib/samagotchi/tools/schedule_task.rb +5 -3
  97. data/lib/samagotchi/tools/send_note.rb +10 -4
  98. data/lib/samagotchi/turn_state.rb +108 -4
  99. data/lib/samagotchi/update_command.rb +7 -2
  100. data/lib/samagotchi/verify_fresh.rb +27 -9
  101. data/lib/samagotchi/version.rb +1 -1
  102. data/lib/samagotchi/web/app.rb +1 -1
  103. data/lib/samagotchi/web/message_display.rb +5 -1
  104. data/lib/samagotchi/web/public/app.js +2 -7
  105. data/lib/samagotchi/web/public/block_frame.js +5 -1
  106. data/lib/samagotchi/web/public/chains.js +4 -4
  107. data/lib/samagotchi/web/public/data.js +18 -2
  108. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  109. data/lib/samagotchi/web/public/session_fields.js +3 -2
  110. data/lib/samagotchi/web/public/session_state.js +2 -0
  111. data/lib/samagotchi/web/public/timing.js +17 -6
  112. data/lib/samagotchi/web/public/turn_block.js +6 -2
  113. data/lib/samagotchi/web/public/update_notice.js +2 -2
  114. data/lib/samagotchi/web/public/widget_walk.js +4 -2
  115. data/lib/samagotchi/web/session_access_routes.rb +12 -8
  116. data/lib/samagotchi/web/session_control.rb +9 -3
  117. data/lib/samagotchi/web/session_create.rb +8 -4
  118. data/lib/samagotchi/web/session_hub.rb +50 -5
  119. data/lib/samagotchi/web/session_show.rb +22 -11
  120. data/lib/samagotchi/web/session_summary.rb +5 -2
  121. data/lib/samagotchi/worker.rb +45 -7
  122. data/lib/samagotchi/worker_boot.rb +22 -11
  123. data/lib/samagotchi/worker_inbound.rb +41 -8
  124. data/lib/samagotchi/worker_link.rb +4 -1
  125. data/lib/samagotchi/worker_presence.rb +106 -0
  126. data/lib/samagotchi/worker_sidecar.rb +3 -4
  127. metadata +7 -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.shift while cache.size >= CACHE_SIZE
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
@@ -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"
@@ -160,6 +161,9 @@ module Samagotchi
160
161
  @connection_threads = []
161
162
  @stopped = false
162
163
  @mutex = Monitor.new
164
+ @post_turn_mutex = Mutex.new
165
+ @enqueued_requests = {}
166
+ @enqueued_request_order = []
163
167
  @refused_log_mutex = Mutex.new
164
168
  @refused_logged_at = {}
165
169
  @open_streams = 0
@@ -324,11 +328,12 @@ module Samagotchi
324
328
  # working_set: the running turn's last :working_set_updated ({items:,
325
329
  # at:}, TurnAccumulator#working_set), which the messages lag; nil
326
330
  # between turns and before the turn emitted one.
327
- # last_turn_drawing: the last exchange's turn as live drew it
328
- # ({drawing:, end:}, TurnDrawings#last, not unfolded: an attaching TUI
329
- # unfolds it, TurnAccumulator.replay_events), only while it holds against
330
- # these messages and ends at their end; absent otherwise (a rollback, a
331
- # later Continue or note, an older worker's file).
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).
332
337
  # @return [Hash] {messages:, current_turn:, working_set:, queued:, queued_commands:, recap:, saved_recap:, continue_offer:, pending_question:,
333
338
  # guardrail_warning:, plugin_warning:, init_tasks:, cards:, commands:, chi_version:, event_seq:, event_id:, last_turn_drawing:}
334
339
  def snapshot
@@ -358,20 +363,41 @@ module Samagotchi
358
363
  end
359
364
  end
360
365
 
361
- # The newest drawing (TurnDrawings#last) as the snapshot sends it, when
362
- # it is the last exchange's: its range still holds against +messages+
363
- # and ends at their end, and is no bigger than a restart reads back
364
- # (TurnDrawings.sendable?). nil otherwise.
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.
365
376
  # @return [Hash, nil] {drawing:, end:} (string keys inside, as the file)
366
377
  def last_turn_drawing(messages)
367
- line = @drawings.last
368
- return nil unless line && line.to == messages.size && TurnDrawings.holds?(line, messages)
369
- return nil unless TurnDrawings.sendable?(line)
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
370
385
 
371
386
  { drawing: line.drawing, end: line.end }
372
387
  end
373
388
  private :last_turn_drawing
374
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
+
375
401
  # The snapshot and the session state (status, pending question, ...) as
376
402
  # one step of the event log, both as of the same event_seq: what a
377
403
  # snapshot or reset frame (SSEWriter) and GET snapshot carry.
@@ -767,14 +793,23 @@ module Samagotchi
767
793
  def handle_cancel(_session_id, body)
768
794
  # Optional reason from JSON body
769
795
  reason = :manual
796
+ turn_id = nil
770
797
  if body && !body.strip.empty?
771
798
  parsed = parse_json(body)
772
799
  r = parsed.is_a?(Hash) ? (fetched(parsed, "reason") || fetched(parsed, "cancellation_reason")) : nil
773
800
  reason = CANCEL_REASONS.include?(r.to_s.strip) ? r.to_s.strip.to_sym : :manual
801
+ turn_id = fetched(parsed, "turn_id").to_s.strip if parsed.is_a?(Hash)
802
+ turn_id = nil if turn_id && turn_id.empty?
774
803
  end
775
804
 
776
805
  if @engine.turn_running? && @engine.active_cancel_controller
777
- ok = @engine.cancel_current_turn!(reason)
806
+ # With a turn_id the engine compares it to the running turn's under
807
+ # its lock; clients that send none (older ones) cancel whichever runs.
808
+ ok = turn_id ? @engine.cancel_current_turn!(reason, turn_id: turn_id) : @engine.cancel_current_turn!(reason)
809
+ if ok == :turn_mismatch
810
+ return [{}, 409, { error: "turn_mismatch", detail: "the running turn is not the one named", session_id: @session_id }]
811
+ end
812
+
778
813
  return [{}, 202, { status: "cancel_requested", session_id: @session_id, reason: reason.to_s }] if ok
779
814
 
780
815
  [{}, 409, { error: "cancel_failed", detail: "could not cancel", session_id: @session_id }]
@@ -1209,29 +1244,47 @@ module Samagotchi
1209
1244
  end
1210
1245
  end
1211
1246
 
1212
- enqueued_id = SecureRandom.uuid
1247
+ enqueued_id = fetched(parsed, "enqueued_id")
1248
+ enqueued_id = SessionInbox.new_enqueued_id unless SessionInbox.valid_enqueued_id?(enqueued_id)
1249
+ enqueue_post_turn(sid: sid, prompt: prompt, client_id: client_id, no_interrupt: no_interrupt, author: author,
1250
+ anchors: anchors, images: images, delivery: delivery, deadline: deadline, pending_limit: pending_limit,
1251
+ enqueued_id: enqueued_id)
1252
+ end
1253
+
1254
+ def enqueue_post_turn(sid:, prompt:, client_id:, no_interrupt:, author:, anchors:, images:, delivery:, deadline:,
1255
+ pending_limit:, enqueued_id:)
1213
1256
  # Before it is queued: a drain after this may have taken it (#cut_for_steer).
1214
- epoch = @engine.input_epoch
1215
- # Whether a queue waits for a running turn: read with the write under
1216
- # the event log, so no :turn_started or :turn_completed falls between.
1217
- # To an idle worker the queued file simply runs as the next turn.
1218
- queued_behind_turn = false
1219
- # Write and announce with the event log held: the worker can't emit
1220
- # this turn's :turn_started (or merge it mid-turn) before
1221
- # :turn_enqueued, and a failed write announces nothing.
1222
- enqueued = @engine.synchronize_events do
1223
- raise IntakeClosed if stopped?
1224
- next :expired if expired?("turn_expired", deadline, sid: sid, client_id: client_id)
1225
- next :too_many if pending_limit && pending_turns(author) >= pending_limit
1226
-
1227
- # The owner's input never goes into a participant's read-only
1228
- # review turn (a steer, a cut): it queues behind it as the owner's
1229
- # own turn, and the ack and :turn_enqueued say so.
1230
- delivery = Delivery::QUEUE if @accumulator.participant_turn?
1231
- queued_behind_turn = Delivery.queue?(delivery) && !@accumulator.current_turn.nil?
1232
- enqueue_turn(prompt: prompt, client_id: client_id, enqueued_id: enqueued_id,
1233
- no_interrupt: no_interrupt, images: images, delivery: delivery, author: author, anchors: anchors).tap do |ok|
1234
- next unless ok
1257
+ @post_turn_mutex.synchronize do
1258
+ epoch = @engine.input_epoch
1259
+ # Whether a queue waits for a running turn: read with the write under
1260
+ # the event log, so no :turn_started or :turn_completed falls between.
1261
+ # To an idle worker the queued file simply runs as the next turn.
1262
+ queued_behind_turn = false
1263
+ # Write and announce with the event log held: the worker can't emit
1264
+ # this turn's :turn_started (or merge it mid-turn) before
1265
+ # :turn_enqueued, and a failed write announces nothing.
1266
+ enqueued = @engine.synchronize_events do
1267
+ raise IntakeClosed if stopped?
1268
+
1269
+ existing = @enqueued_requests[enqueued_id]
1270
+ if existing
1271
+ next(existing[:prompt] == prompt.to_s ? :duplicate : :conflict)
1272
+ end
1273
+ next :duplicate if @engine.enqueued_id?(enqueued_id)
1274
+ next :expired if expired?("turn_expired", deadline, sid: sid, client_id: client_id)
1275
+ next :too_many if pending_limit && pending_turns(author) >= pending_limit
1276
+ next :duplicate unless @engine.reserve_enqueued_id(enqueued_id)
1277
+
1278
+ # The owner's input never goes into a participant's read-only
1279
+ # review turn (a steer, a cut): it queues behind it as the owner's
1280
+ # own turn, and the ack and :turn_enqueued say so.
1281
+ delivery = Delivery::QUEUE if @accumulator.participant_turn?
1282
+ queued_behind_turn = Delivery.queue?(delivery) && !@accumulator.current_turn.nil?
1283
+ unless enqueue_turn(prompt: prompt, client_id: client_id, enqueued_id: enqueued_id,
1284
+ no_interrupt: no_interrupt, images: images, delivery: delivery, author: author, anchors: anchors)
1285
+ @engine.forget_enqueued_id(enqueued_id)
1286
+ next false
1287
+ end
1235
1288
 
1236
1289
  enqueued_event = { type: :turn_enqueued, enqueued_id: enqueued_id, client_id: client_id, prompt: prompt.to_s }
1237
1290
  enqueued_event[:images] = images unless images.empty?
@@ -1239,26 +1292,43 @@ module Samagotchi
1239
1292
  enqueued_event[:author] = author if author
1240
1293
  @engine.announce(enqueued_event)
1241
1294
  @on_input&.call
1295
+ true
1296
+ end
1297
+ if enqueued == :duplicate
1298
+ ack = @enqueued_requests.dig(enqueued_id, :ack) ||
1299
+ { status: "accepted", enqueued_id: enqueued_id, session_id: @session_id }
1300
+ return [{}, 202, ack]
1301
+ end
1302
+ if enqueued == :conflict
1303
+ return [{}, 409, { error: "enqueued_id_conflict",
1304
+ detail: "enqueued_id was already accepted for a different prompt" }]
1242
1305
  end
1306
+ return deadline_passed("turn") if enqueued == :expired
1307
+ return [{}, 429, { error: "too_many_turns", detail: ParticipantMessages::TOO_MANY_TURNS }] if enqueued == :too_many
1308
+ return [{}, 500, { error: "enqueue_failed", detail: "could not write turn input" }] unless enqueued
1309
+
1310
+ # Queued (outside the event lock): a message sent as +cut+ cuts a
1311
+ # running generation that has only been thinking for long, unless a
1312
+ # plugin or a client chi doesn't know sent it. An image input never
1313
+ # merges mid-turn, so it never cuts. Nothing else cuts: a message
1314
+ # that says nothing (an older client, the web composer) goes in at
1315
+ # the running turn's next step.
1316
+ cut = nil
1317
+ cut = @engine.cut_for_steer(Steer.source_for_client(client_id), epoch: epoch) if images.empty? && Delivery.cut?(delivery)
1318
+ # A queue to an idle worker is a turn now: the ack says next_step.
1319
+ ack_delivery = Delivery.queue?(delivery) && !queued_behind_turn ? Delivery::NEXT_STEP : delivery
1320
+ ack = { status: "accepted", enqueued_id: enqueued_id, session_id: @session_id, delivery: ack_delivery }
1321
+ ack[:cut] = cut.to_s if cut
1322
+ ack[:cut_after] = @engine.steer_cut_after if cut == :waits
1323
+ remember_enqueued_request(enqueued_id, prompt, ack)
1324
+ [{}, 202, ack]
1243
1325
  end
1244
- return deadline_passed("turn") if enqueued == :expired
1245
- return [{}, 429, { error: "too_many_turns", detail: ParticipantMessages::TOO_MANY_TURNS }] if enqueued == :too_many
1246
- return [{}, 500, { error: "enqueue_failed", detail: "could not write turn input" }] unless enqueued
1247
-
1248
- # Queued (outside the event lock): a message sent as +cut+ cuts a
1249
- # running generation that has only been thinking for long, unless a
1250
- # plugin or a client chi doesn't know sent it. An image input never
1251
- # merges mid-turn, so it never cuts. Nothing else cuts: a message
1252
- # that says nothing (an older client, the web composer) goes in at
1253
- # the running turn's next step.
1254
- cut = nil
1255
- cut = @engine.cut_for_steer(Steer.source_for_client(client_id), epoch: epoch) if images.empty? && Delivery.cut?(delivery)
1256
- # A queue to an idle worker is a turn now: the ack says next_step.
1257
- ack_delivery = Delivery.queue?(delivery) && !queued_behind_turn ? Delivery::NEXT_STEP : delivery
1258
- ack = { status: "accepted", enqueued_id: enqueued_id, session_id: @session_id, delivery: ack_delivery }
1259
- ack[:cut] = cut.to_s if cut
1260
- ack[:cut_after] = @engine.steer_cut_after if cut == :waits
1261
- [{}, 202, ack]
1326
+ end
1327
+
1328
+ def remember_enqueued_request(id, prompt, ack)
1329
+ @enqueued_requests[id] = { prompt: prompt.to_s, ack: ack }
1330
+ @enqueued_request_order << id
1331
+ @enqueued_requests.delete(@enqueued_request_order.shift) while @enqueued_requests.size > TurnState::ENQUEUED_ID_HISTORY
1262
1332
  end
1263
1333
 
1264
1334
  # POST /session/:id/turn/dequeue {enqueued_id, client_id?, deadline?}:
@@ -1290,7 +1360,10 @@ module Samagotchi
1290
1360
  next [:expired, nil] if expired?("dequeue_expired", deadline, sid: session_id, enqueued_id: id)
1291
1361
 
1292
1362
  SessionInbox.take_queued_input(session_dir, id).tap do |status, _|
1293
- @engine.announce(type: :turn_dequeued, enqueued_id: id, client_id: client_id) if status == :removed
1363
+ if status == :removed
1364
+ @engine.drop_enqueued_id(id)
1365
+ @engine.announce(type: :turn_dequeued, enqueued_id: id, client_id: client_id)
1366
+ end
1294
1367
  end
1295
1368
  end
1296
1369
  dequeue_reply(taken, id, input)
@@ -8,6 +8,7 @@ require_relative "degrade"
8
8
  require_relative "worker_sidecar"
9
9
  require_relative "bridge_secret"
10
10
  require_relative "delivery"
11
+ require_relative "session_inbox"
11
12
  require_relative "chi_invocation"
12
13
  require_relative "bridge_client/stream_open"
13
14
  require_relative "bridge_client/sse_parser"
@@ -197,9 +198,10 @@ module Samagotchi
197
198
  # many of their turns may be running or waiting (429 too_many_turns past it)
198
199
  # @param anchors [TurnAnchors, Hash, nil] a Verify turn's claim, a Revise
199
200
  # turn's draft: their own body keys ("verify", "revises")
200
- def post_turn(prompt:, client_id: nil, no_interrupt: false, images: nil, delivery: nil, author: nil, pending_limit: nil,
201
- anchors: nil)
202
- body = { session_id: @session_id, prompt: prompt, client_id: client_id }
201
+ def post_turn(prompt:, client_id: nil, enqueued_id: nil, no_interrupt: false, images: nil, delivery: nil, author: nil,
202
+ pending_limit: nil, anchors: nil)
203
+ body = { session_id: @session_id, prompt: prompt, client_id: client_id,
204
+ enqueued_id: enqueued_id || SessionInbox.new_enqueued_id }
203
205
  body[:no_interrupt] = true if no_interrupt
204
206
  body[:author] = author if author
205
207
  body[:pending_limit] = pending_limit if author && pending_limit
@@ -246,10 +248,11 @@ module Samagotchi
246
248
  end
247
249
 
248
250
  # POST /session/:id/cancel. 202 = requested (body names the reason the
249
- # Bridge took), 409 = no active turn.
251
+ # Bridge took), 409 = no active turn, or (error "turn_mismatch") not the
252
+ # +turn_id+ named: nothing was cancelled.
250
253
  # @return [Response]
251
- def cancel(reason:)
252
- post("cancel", { reason: reason }, read_body: true)
254
+ def cancel(reason:, turn_id: nil)
255
+ post("cancel", { reason: reason, turn_id: turn_id }.compact, read_body: true)
253
256
  end
254
257
 
255
258
  # POST /session/:id/tasks/stop: stop a background task this session's