samagotchi 0.175.0 → 0.176.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 (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +3 -0
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +11 -5
  10. data/docs/internals/web-frontend.md +23 -9
  11. data/docs/sessions.md +2 -2
  12. data/lib/samagotchi/bridge.rb +11 -4
  13. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  14. data/lib/samagotchi/config.rb +3 -0
  15. data/lib/samagotchi/participant_uploads.rb +14 -1
  16. data/lib/samagotchi/version.rb +1 -1
  17. data/lib/samagotchi/web/app.rb +15 -2
  18. data/lib/samagotchi/web/participant_images.rb +16 -12
  19. data/lib/samagotchi/web/participant_view.rb +27 -1
  20. data/lib/samagotchi/web/public/app.js +4 -2
  21. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  22. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  23. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  24. data/lib/samagotchi/web/public/restore.js +3 -1
  25. data/lib/samagotchi/web/public/session_prefs.js +89 -0
  26. data/lib/samagotchi/web/public/session_sync.js +3 -0
  27. data/lib/samagotchi/web/public/session_view.js +32 -2
  28. data/lib/samagotchi/web/public/stage_asking.js +20 -11
  29. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  30. data/lib/samagotchi/web/public/stage_missing.js +3 -5
  31. data/lib/samagotchi/web/public/stage_model.js +2 -1
  32. data/lib/samagotchi/web/public/stage_view.js +6 -1
  33. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  34. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  35. data/lib/samagotchi/web/public/turn_events.js +1 -1
  36. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  37. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  38. data/lib/samagotchi/web/server.rb +6 -2
  39. data/lib/samagotchi/worker/child_side.rb +123 -0
  40. data/lib/samagotchi/worker/command_queue.rb +346 -0
  41. data/lib/samagotchi/worker/leave.rb +286 -0
  42. data/lib/samagotchi/worker/scratch.rb +99 -0
  43. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  44. data/lib/samagotchi/worker/startup.rb +92 -0
  45. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  46. data/lib/samagotchi/worker.rb +24 -1065
  47. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  48. metadata +10 -1
@@ -0,0 +1,346 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../client_id"
4
+ require_relative "../command_intake"
5
+ require_relative "../log"
6
+ require_relative "../session_commands"
7
+ require_relative "../session_inbox"
8
+ require_relative "../session_setting"
9
+ require_relative "../turn_checkpoint"
10
+
11
+ module Samagotchi
12
+ class Worker
13
+ # Session commands between turns: the loop runs what #run_queued_commands
14
+ # finds in @command_queue (/model, !rollback, !cmd, /continue ...) before
15
+ # any queued prompt, and refuses or drops what arrives mid-turn. Includes
16
+ # the "what waits" predicates #input_pending?, #held_for_offer? and
17
+ # #nothing_queued?. LOCK RULE: the queue is touched with the event log held
18
+ # (@engine.synchronize_events): #on_command on a Bridge thread, the pops
19
+ # and re-pushes in #next_ready_command, #refuse_queued_commands and
20
+ # #drop_queued_commands. The `empty?` peeks (those, #input_pending?,
21
+ # #nothing_queued?, #start's next_turn_waiting lambda) are benign by
22
+ # design. Writes @command_queue's contents (created in #initialize).
23
+ # Reads @engine, @session_dir, @commands (built in #start),
24
+ # @continue_offer, @turn_end_seq, @turn_end_type (#start's observer),
25
+ # @turn_flow and @waker.
26
+ module CommandQueuePart
27
+ # How much of a command's output goes into its :command_ran, in chars.
28
+ # Room for a real listing (/guardrails with a bundle's rules, /models):
29
+ # the event lives only in the Bridge's ring (256 events, in memory) and
30
+ # on the streams, a session file doesn't hold it.
31
+ COMMAND_OUTPUT_LIMIT = 64 * 1024
32
+ BUSY_OUTPUT = "busy: wait for the turn to end"
33
+ # !rollback mid-turn would mean "the turn I'm in".
34
+ ROLLBACK_BUSY_OUTPUT = "busy: Ctrl-C the turn first, then !rollback"
35
+
36
+ private
37
+
38
+ # Whether a command or an input file waits to run (WorkerIdleExit's
39
+ # :input_queued). A participant's file held for the Continue offer
40
+ # (#held_for_offer?) doesn't count: what waits is the owner's answer,
41
+ # the policy's :continue_offered.
42
+ def input_pending?
43
+ !@command_queue.empty? || SessionInbox.find_new_input_files(@session_dir).any? { |file| !held_for_offer?(file) }
44
+ end
45
+
46
+ # Whether +input_file+ waits for the owner's answer to the Continue
47
+ # offer that stands (#run_input_files).
48
+ def held_for_offer?(input_file) = @turn_flow&.awaiting_continue? && SessionInbox.participant_input?(input_file)
49
+
50
+ # No input file or queued command waits: the loop would go idle.
51
+ def nothing_queued? = @command_queue.empty? && SessionInbox.find_new_input_files(@session_dir).empty?
52
+
53
+ # The queued commands that may run now, in order, up to one whose
54
+ # after_file (D1) still waits in the inbox: it and those behind it stay
55
+ # queued.
56
+ # @return [Boolean] whether any command ran
57
+ def run_queued_commands
58
+ ran = false
59
+ # A signalled worker runs no more (a /continue would start a turn).
60
+ while !signalled? && (command = next_ready_command)
61
+ run_command(command)
62
+ ran = true
63
+ end
64
+ ran
65
+ end
66
+
67
+ # Pops the first queued command if it may run now (its after_file is
68
+ # taken), else none: one behind it waits too, in arrival order (an idle
69
+ # /model Y that came just after the turn ended stays behind a /model X
70
+ # still waiting for a prompt sent before it). With the event log held,
71
+ # as the Bridge queues.
72
+ def next_ready_command
73
+ return nil if @command_queue.empty?
74
+
75
+ @engine.synchronize_events do
76
+ commands = drain_commands
77
+ first = commands.first
78
+ ready = first && ready_command?(first) ? commands.shift : nil
79
+ commands.each { |command| @command_queue << command }
80
+ ready
81
+ end
82
+ end
83
+
84
+ # A participant's file held for the Continue offer (#run_input_files)
85
+ # doesn't hold a command back: that command may be the owner's answer.
86
+ def ready_command?(command)
87
+ return true if command.after_file.nil?
88
+
89
+ SessionInbox.find_new_input_files(@session_dir).none? do |path|
90
+ File.basename(path) <= command.after_file && !held_for_offer?(path)
91
+ end
92
+ end
93
+
94
+ def drain_commands
95
+ commands = []
96
+ while (command = next_command)
97
+ commands << command
98
+ end
99
+ commands
100
+ end
101
+
102
+ # A command a turn refuses (:refuse while it ran, S1) is answered busy:
103
+ # at the turn's iteration boundaries (mid_turn: all of them), and when
104
+ # it ends (the ones queued before its end event; later ones run next).
105
+ # A queued one (:queue) stays for after the turn, but a !cmd after a
106
+ # canceled or failed turn (D4): running it would close the rollback
107
+ # window the turn left, so it is dropped. With the event log held, so
108
+ # a command the Bridge queues meanwhile stays behind the ones kept, in
109
+ # arrival order. One that comes after the empty look is the next
110
+ # boundary's (or end's), as it would be.
111
+ def refuse_queued_commands(mid_turn: false)
112
+ return if @command_queue.empty?
113
+
114
+ @engine.synchronize_events do
115
+ drain_commands.each do |command|
116
+ during = mid_turn || command.after_seq.to_i < @turn_end_seq
117
+ case (during ? turn_answer(command, ended: !mid_turn) : :keep)
118
+ when :refuse then announce_command(command, status: "busy", output: busy_output(command), changed: [])
119
+ when :drop then drop_command(waiting_for_turn_end(command), "turn #{@turn_end_type == :turn_failed ? "failed" : "canceled"}: " \
120
+ "#{command.line} not run; send it again")
121
+ else @command_queue << (during ? waiting_for_turn_end(command) : command)
122
+ end
123
+ end
124
+ end
125
+ end
126
+
127
+ # What a turn does with +command+, queued while it ran: :refuse, :drop
128
+ # (D4, once it +ended+) or :keep. One queued idle just as the turn
129
+ # began (:loop) goes by its line's policy (a show form waits too).
130
+ def turn_answer(command, ended:)
131
+ policy = command.mid_turn
132
+ policy = @engine.command_registry.mid_turn(command.line) if policy == :loop
133
+ return :refuse if policy == :refuse
134
+ return :drop if ended && policy == :queue && shell_command?(command) &&
135
+ %i[turn_canceled turn_failed].include?(@turn_end_type)
136
+
137
+ :keep
138
+ end
139
+
140
+ # +command+, kept for after the turn. One queued idle just as the turn
141
+ # began (:loop) whose line waits for a turn's end (/model X, !cmd) is
142
+ # marked as one queued mid-turn: its command_queued (waits) tells the
143
+ # UIs now, and its command_ran says queued.
144
+ def waiting_for_turn_end(command)
145
+ return command unless command.mid_turn == :loop && @engine.command_registry.mid_turn(command.line) == :queue
146
+
147
+ @engine.announce(type: :command_queued, **command.event_fields, waits: "turn_end")
148
+ command.with(mid_turn: :queue)
149
+ end
150
+
151
+ def shell_command?(command) = @engine.command_registry.lookup(command.line)&.id == :shell
152
+
153
+ def busy_output(command)
154
+ @engine.command_registry.lookup(command.line)&.id == :rollback ? ROLLBACK_BUSY_OUTPUT : BUSY_OUTPUT
155
+ end
156
+
157
+ # +command+ won't run: its sender (a UI's queued bubble) is told.
158
+ def drop_command(command, output)
159
+ announce_command(command, status: "dropped", output: output, changed: [])
160
+ end
161
+
162
+ # The worker leaves with commands still queued (a stop, a crash): each
163
+ # one's sender is told it won't run, so no UI shows it waiting for good.
164
+ def drop_queued_commands
165
+ return if @command_queue.nil? || @command_queue.empty? || @engine.nil?
166
+
167
+ @engine.synchronize_events do
168
+ drain_commands.each { |command| drop_command(command, "dropped: the session's worker stopped before it ran") }
169
+ end
170
+ rescue StandardError => e
171
+ Log.warn(:worker, "drop_commands_failed", error: e.class.name, msg: e.message)
172
+ end
173
+
174
+ def next_command
175
+ @command_queue.pop(true)
176
+ rescue ThreadError
177
+ nil
178
+ end
179
+
180
+ def run_command(command)
181
+ awaiting = @continue_offer.awaiting?
182
+ result, shown = run_command_line(command)
183
+ resolved = @continue_offer.resolved?(awaiting, result)
184
+ @engine.synchronize_events do
185
+ @continue_offer.announce_resolved(result, command) if resolved
186
+ announce_command(command, status: result.status.to_s, output: result.output, changed: Array(result.changed),
187
+ confirm: result.confirm)
188
+ shown.each { |event| @engine.announce(event) }
189
+ end
190
+ save_or_log(:command) { save_session } unless Array(result.changed).empty?
191
+ user_input(command.client_id) if resolved
192
+ @continue_offer.after_command(result, resolved: resolved)
193
+ @continue_offer.run_continue_turn(command) if result.resume
194
+ end
195
+
196
+ # @return [Array(SessionCommands::Result, Array<Hash>)] the result, and
197
+ # the cards and notices it showed, held: they follow its command_ran,
198
+ # as its output
199
+ def run_command_line(command)
200
+ @engine.holding_announcements do
201
+ command_result(command) do
202
+ @commands.run(command.line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
203
+ end
204
+ end
205
+ end
206
+
207
+ # A shell line from a sender that may not run one (CommandIntake: a
208
+ # delegate's task, a schedule's prompt, a plugin's message): not run,
209
+ # its command_ran an error with the one refusal text.
210
+ def shell_refused(command)
211
+ Log.warn(:worker, "shell_line_refused", client_id: command.client_id)
212
+ SessionCommands::Result.new(status: :error, output: CommandIntake::REFUSED, changed: [])
213
+ end
214
+
215
+ # Whether +command+ asks before a costly /thinking or /reasoning-history
216
+ # change (CacheConfirm): only a person at a web tab or a TUI sees the
217
+ # question; chi send, a delegate, a plugin and a card's action apply it.
218
+ def confirm?(command) = ClientId.interactive?(command.client_id) && !command.card
219
+
220
+ # Whether +command+ is a parent agent's (chi answer's marker, which chi
221
+ # send and a parent's attach give a /continue yes too): held to
222
+ # guardrails.parent_answers (SessionCommands#continue_answer).
223
+ def as_parent?(command) = command.client_id.to_s == ClientId::CLI_ANSWER
224
+
225
+ # Whether +command+ is a user's at a UI (a web tab, a chi TUI, a card's
226
+ # click), not a parent agent's: only such a line loosens
227
+ # /parent-answers. chi send, a delegate's follow-up, a plugin and an
228
+ # input with no client never do (ParentAnswersCommand).
229
+ def user_ui?(command) = ClientId.interactive?(command.client_id) && !as_parent?(command)
230
+
231
+ # The block's Result for +command+; one that raised, or found no
232
+ # command for the line, is an error Result saying so.
233
+ # @return [SessionCommands::Result]
234
+ def command_result(command)
235
+ return shell_refused(command) if CommandIntake.refused?(command.line, command.client_id)
236
+
237
+ yield || SessionCommands::Result.new(status: :error, output: "not a session command", changed: [])
238
+ rescue StandardError => e
239
+ SessionCommands::Result.new(status: :error, output: "#{command.line.split.first}: #{e.message}", changed: [])
240
+ end
241
+
242
+ # A session command from the Bridge, called with the event log held:
243
+ # an anytime one starts now, any other is queued for the loop (and
244
+ # refused if a turn runs: #refuse_queued_commands). While a turn runs
245
+ # the line's policy decides (a show form like /model runs now); idle,
246
+ # only an always-anytime command (/help) runs beside the loop, so an
247
+ # idle /model X then /model run in order. A turn starting or ending
248
+ # right now may see the other side: the line is only shown early or
249
+ # run in order.
250
+ #
251
+ # A queued one (:queue) keeps arrival order with the prompts (D1): it
252
+ # runs once every input file written before it is taken (after_file,
253
+ # the newest one now; names compare, not clocks), so a prompt sent
254
+ # before it runs first and one sent after it runs after. One that came
255
+ # in an input file runs once that file is taken (+after_file+).
256
+ # @return [Symbol] the policy it applied (the Bridge marks an anytime
257
+ # one's command_queued, and a queued one's): :anytime, :queue or
258
+ # :refuse while a turn runs, :loop idle
259
+ def on_command(command, after_file: nil)
260
+ registry = @engine.command_registry
261
+ policy = if @engine.turn_running? then registry.mid_turn(command.line)
262
+ else registry.anytime?(command.line) ? :anytime : :loop
263
+ end
264
+ if policy == :anytime
265
+ start_anytime_command(command)
266
+ return policy
267
+ end
268
+
269
+ after_file ||= newest_input_file if policy == :queue
270
+ # The count says which turn ends came before it.
271
+ @command_queue << command.with(after_seq: @engine.event_count, mid_turn: policy, after_file: after_file)
272
+ @waker.wake
273
+ policy
274
+ end
275
+
276
+ # @return [String, nil] the newest input file waiting (its basename)
277
+ def newest_input_file
278
+ SessionInbox.find_new_input_files(@session_dir).map { |path| File.basename(path) }.max
279
+ end
280
+
281
+ # An anytime command (/help, a plugin's /btw; D8) runs now, on its own
282
+ # thread, never queued behind a turn: it is never busy. The Bridge calls
283
+ # this with the event log held, so its command_ran (announced when it
284
+ # finishes) comes after its command_queued. The cards it shows go out at
285
+ # once (btw's "thinking…" card), after its command_queued, which the
286
+ # UIs draw its line at (Engine#running_anytime). Its handler reads
287
+ # copies (ctx.messages) and shows things through ctx only. One that
288
+ # changed the session (/title, /recap off: fields no turn writes) is
289
+ # saved here, as a queued one is (#run_command), through Session#save,
290
+ # which takes the session's lock and writes a running turn's checkpoint
291
+ # (as WorkerSignals' save off the turn thread does), so the turn's own
292
+ # saves keep it.
293
+ def start_anytime_command(command)
294
+ @engine.spawn_anytime do
295
+ result = command_result(command) { @engine.running_anytime { @commands.run(command.line, confirm: confirm?(command)) } }
296
+ # Saved before its command_ran: a client that reads the file on the reply finds it.
297
+ save_or_log(:command) { save_session } unless Array(result.changed).empty?
298
+ announce_command(command, status: result.status.to_s, output: result.output, changed: Array(result.changed),
299
+ anytime: true, confirm: result.confirm)
300
+ # It may have left a note (/objectives): an idle loop takes it now, not
301
+ # at the fallback tick. Harmless otherwise: one more pass.
302
+ @waker.wake
303
+ rescue StandardError => e
304
+ Log.warn(:worker, "anytime_command_failed", line: command.line, error: e.class.name, msg: e.message)
305
+ end
306
+ end
307
+
308
+ # @param anytime [Boolean] an anytime command's: its line was shown at
309
+ # its command_queued already
310
+ # @param confirm [CacheConfirm::Confirm, nil] the change asks first: the
311
+ # line that applies it (the TUI's prefill, the web's Apply button)
312
+ def announce_command(command, status:, output:, changed:, anytime: false, confirm: nil)
313
+ TurnCheckpoint.record_command_outcome(@session_dir, command.enqueued_id, status: status)
314
+ # Any bytes (a !cmd's): one that JSON can't take would end every stream
315
+ # that reaches this event, for as long as the ring holds it.
316
+ text = output.to_s.scrub("?")
317
+ event = { type: :command_ran, **command.event_fields, status: status, output: command_output_shown(text),
318
+ changed: changed.map(&:to_s), model_name: @engine.effective_model_name }
319
+ event[:anytime] = true if anytime
320
+ # The session's title after /title (nil: cleared), for the TUIs' row.
321
+ event[:title] = @engine.session&.title if changed.include?(:title)
322
+ # Its line was shown at its command_queued (waits: turn_end).
323
+ event[:queued] = true if command.waits_for_turn_end?
324
+ # The chips the command moved (SessionSetting#changed_by): what the next
325
+ # turn runs under now (/llm-context, /thinking, /reasoning-history,
326
+ # /toolkit, and /model for the model's).
327
+ SessionSetting::ALL.each { |setting| event[setting.key] = setting.summary(@engine) if setting.changed_by?(changed) }
328
+ event[:confirm] = confirm.to_h if confirm
329
+ event[:output_truncated] = true if text.length > COMMAND_OUTPUT_LIMIT
330
+ @engine.announce(event)
331
+ end
332
+
333
+ # +text+ as its :command_ran carries it: over the limit, its head to a
334
+ # line's end (one long line is cut where it must be), then a line that
335
+ # says so: every UI prints this text as it is.
336
+ def command_output_shown(text)
337
+ return text if text.length <= COMMAND_OUTPUT_LIMIT
338
+
339
+ kept = text[0, COMMAND_OUTPUT_LIMIT]
340
+ line_end = kept.rindex("\n")
341
+ kept = kept[0, line_end] if line_end && line_end > COMMAND_OUTPUT_LIMIT / 2
342
+ "#{kept}\n[cut: #{kept.length} of #{text.length} chars: a command's output stops here]"
343
+ end
344
+ end
345
+ end
346
+ end
@@ -0,0 +1,286 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../children_status"
4
+ require_relative "../log"
5
+ require_relative "../reminder_carry"
6
+ require_relative "../session_manager"
7
+ require_relative "../worker_idle_exit"
8
+
9
+ module Samagotchi
10
+ class Worker
11
+ # Exit and leave: the exit claim's requests (#exit_request, #exit_hold),
12
+ # the leaves (#leave_on_request, #leave_idle) and what they hand on (the
13
+ # carried reminders, the recap, the discard). Writes @marked_leaving
14
+ # (#mark_leaving) and @discard (#left), and the exit claim through its own
15
+ # methods; reads @exit_claim, @idle_exit, @hold_stop, @session, @session_id,
16
+ # @session_dir, @state_dir, @default_model, @engine, @bridge, @owner_lock,
17
+ # @waker and @task_wakes.
18
+ module LeavePart
19
+ # /exit held by background tasks a finish wake waits for: how to end them.
20
+ TASK_STOP_HINT = "stop one with the web's stop-task button or by asking for task_stop"
21
+
22
+ # @return [HoldStop::Stopped, nil] the last stop-all's list (the Bridge's
23
+ # exit_stopped)
24
+ def stopped_holds = @exit_claim.stopped
25
+
26
+ private
27
+
28
+ # Bridge POST /exit, on a Bridge thread with the event log held.
29
+ # +delete+: the session is deleted after (/exit --delete), so no recap.
30
+ # +restart+: a new worker takes over (on the newest chi installed), so
31
+ # WorkerIdleExit#hold_for_restart's rules, and no recap or discard.
32
+ # +stop+: the exit ask's "stop them and exit" — stop every hold the user
33
+ # can stop before leaving; a hold they can't stop refuses the request
34
+ # (WorkerIdleExit#request_hold checks again, so one that appeared
35
+ # since the ask is refused too).
36
+ # +ask+: this client asks the user what to do with what still runs, so the
37
+ # delegate children are part of the list. An exit that deletes the
38
+ # session, or one a UI can't ask about (/archive), leaves them out:
39
+ # they never hold the worker up on their own.
40
+ # @return [WorkerIdleExit::Hold, nil] what keeps the worker up (for
41
+ # :background_tasks, the watched tasks still running), nil when it
42
+ # will leave
43
+ def exit_request(client_id, delete: false, restart: false, stop: false, ask: true)
44
+ # The Bridge serves before the idle-exit policy exists.
45
+ return WorkerIdleExit::Hold.new(reason: :starting) unless @idle_exit
46
+
47
+ kind = if restart then :restart
48
+ elsif delete then :delete
49
+ else :exit
50
+ end
51
+ # One exit at a time, and the first one taken decides how the worker
52
+ # leaves (a later stop-all can't turn a restart, whose reminders go to
53
+ # the next worker, into a plain exit): claimed before the slow
54
+ # stop-all, so a request of another kind meanwhile is refused (409),
55
+ # not told it went through. Held at the leave, it is forgotten and the
56
+ # next request counts again.
57
+ refused = @exit_claim.claim(kind)
58
+ return refused.value if refused
59
+
60
+ hold = exit_hold(client_id, kind: kind, stop: stop, ask: ask)
61
+ if hold
62
+ @exit_claim.forget
63
+ return hold
64
+ end
65
+
66
+ @exit_claim.accept(by: client_id, stop: stop)
67
+ @waker.wake
68
+ nil
69
+ rescue StandardError
70
+ # A look or a stop that raised lets the claim go (the Bridge answers 500).
71
+ @exit_claim.release
72
+ raise
73
+ end
74
+
75
+ # What keeps the worker up for this request, nil when nothing does; a
76
+ # stop request stops what the user can stop first (#exit_request).
77
+ # @return [WorkerIdleExit::Hold, nil]
78
+ def exit_hold(client_id, kind:, stop:, ask:)
79
+ if kind == :restart
80
+ # A scratch session's worker ends with its terminal: never restarted.
81
+ return WorkerIdleExit::Hold.new(reason: :scratch) if @session.scratch
82
+
83
+ hold = @idle_exit.hold_for_restart
84
+ return hold && WorkerIdleExit::Hold.new(reason: hold)
85
+ end
86
+
87
+ # /exit names the tasks it waits for (D3), from the one look that found them.
88
+ # The ask covers the delegate children too, but only for a plain /exit: an
89
+ # exit that deletes the session, or one a UI won't ask about, ignores them.
90
+ hold = @idle_exit.request_hold(requester: client_id, hint: TASK_STOP_HINT, ask: ask && kind != :delete)
91
+ return nil unless hold
92
+ # A hold the user can't stop here: no ask, today's refusal.
93
+ return hold unless hold.ask?
94
+ # The ask's 409: the list, for the terminal to ask with.
95
+ return hold unless stop
96
+
97
+ @exit_claim.stopped!(@hold_stop.stop_all)
98
+ # An unstoppable hold may have arrived while stopping (a child stopped
99
+ # here is no longer counted).
100
+ @idle_exit.request_hold(requester: client_id, hint: TASK_STOP_HINT)
101
+ end
102
+
103
+ # #leave_idle for an exit a client asked for: check again with the event
104
+ # log held (a prompt may have come in since), then close the Bridge's
105
+ # intake and stop the idle jobs (the Bridge stops after the log). Other clients' streams no longer hold: the asker's
106
+ # may not have closed yet, and a UI joining now finds the worker gone
107
+ # (:stream_closed), the window #leave_idle has too.
108
+ # @return [Symbol, false] how it leaves (:restart or :exit_requested,
109
+ # decided under the lock), false when something came in since the request
110
+ def leave_on_request
111
+ stop_bridge_after do
112
+ @engine.synchronize_events do
113
+ # One read: the kind and the asker of the same exit.
114
+ taken = @exit_claim.taken
115
+ restart = taken&.restart?
116
+ hold = if restart
117
+ @idle_exit.hold_for_restart
118
+ else
119
+ @idle_exit.hold_for_request(requester: taken&.by, streams: false)
120
+ end
121
+ if hold
122
+ @exit_claim.forget
123
+ Log.info(:worker, "exit_held", reason: hold)
124
+ next false
125
+ end
126
+ next false if restart && !carry_reminders
127
+
128
+ @bridge&.close_intake
129
+ # Not joined: a recap tick's emit waits for the event log held here.
130
+ @engine.stop_idle(join: false)
131
+ Log.info(:worker, restart ? "restart_requested" : "exit_requested", by: taken&.by || "a client")
132
+ restart ? :restart : :exit_requested
133
+ end
134
+ end
135
+ end
136
+
137
+ # Check again with the event log held, which the Bridge holds while it
138
+ # queues a POST /turn, then close the Bridge's intake so no client can
139
+ # queue one after the check, and stop the idle jobs (reminder callback,
140
+ # recap). The Bridge stops after the log is let go (#stop_bridge_after).
141
+ # A client connecting from here on finds no worker: `chi --attach` fails
142
+ # and the web stream answers 503 (a small window, left as is).
143
+ # @return [Boolean] false when something came in since #due?
144
+ def leave_idle
145
+ stop_bridge_after do
146
+ @engine.synchronize_events do
147
+ next false unless @idle_exit.due?
148
+
149
+ @bridge&.close_intake
150
+ # Not joined: a recap tick's emit waits for the event log held here.
151
+ @engine.stop_idle(join: false)
152
+ log_idle_exit
153
+ true
154
+ end
155
+ end
156
+ end
157
+
158
+ def log_idle_exit
159
+ Log.info(:worker, "idle_exit", idle_s: @idle_exit.idle_seconds.round)
160
+ end
161
+
162
+ # The Bridge stops once the block (which closed its intake with the
163
+ # event log held) answers true, outside the log: Bridge#stop waits for
164
+ # the requests it is answering, and one waiting on the log would hold
165
+ # it for the whole grace before being killed. The owner lock says it is
166
+ # leaving first, so a client that finds no Bridge from here on waits
167
+ # for the lock (OwnerLock.await_release) instead of giving up.
168
+ # @return [Boolean] what the block answered
169
+ def stop_bridge_after
170
+ leaving = yield
171
+ if leaving
172
+ mark_leaving
173
+ @bridge&.stop
174
+ end
175
+ leaving
176
+ end
177
+
178
+ # How long the lock stays held after the Bridge: the recap on leave's
179
+ # timeout (#left), none for a restart (#left writes none). A delete
180
+ # writes none either, but the bound only has to be an upper one.
181
+ # Once: the teardown's (after #stop_bridge_after's) keeps the first one.
182
+ # @param wait [Numeric, nil] nil: as above
183
+ def mark_leaving(wait: nil)
184
+ return if @marked_leaving
185
+
186
+ @marked_leaving = true
187
+ wait ||= @exit_claim.restart? ? 0 : @engine.recap_timeout.to_f
188
+ @owner_lock&.mark_leaving(wait: wait)
189
+ rescue StandardError => e
190
+ Log.warn(:worker, "mark_leaving_failed", error: e.class.name, msg: e.message)
191
+ end
192
+
193
+ # A restart hands the reminders to the next worker (ReminderCarry), while
194
+ # the event log is held: no turn can register or fire one from here. A
195
+ # write that fails keeps this worker up with them rather than losing them.
196
+ # A session stopped meanwhile drops them (WorkerBoot.run_session_loop
197
+ # then starts no successor): nothing is written.
198
+ # @return [Boolean] false when the write failed
199
+ def carry_reminders
200
+ if stopped_on_disk?
201
+ ReminderCarry.remove(@session_dir)
202
+ else
203
+ ReminderCarry.write(@session_dir, session_id: @session_id, store: @engine.reminder_store)
204
+ end
205
+ true
206
+ rescue StandardError => e
207
+ @exit_claim.forget
208
+ Log.warn(:worker, "reminders_carry_failed", error: e.class.name, msg: e.message)
209
+ false
210
+ end
211
+
212
+ # The reminders a restart handed over (#carry_reminders), read and
213
+ # deleted; a stopped session drops them.
214
+ # @return [Array<Hash>, nil] ReminderStore#export's entries
215
+ def take_carried_reminders
216
+ ReminderCarry.take(@session_dir, session_id: @session_id, stopped: stopped_on_disk?)
217
+ rescue StandardError => e
218
+ Log.warn(:worker, "reminders_carry_take_failed", error: e.class.name, msg: e.message)
219
+ nil
220
+ end
221
+
222
+ # Into the new Engine's store, before the idle scheduler starts polling it.
223
+ def restore_carried_reminders(entries)
224
+ return unless entries
225
+
226
+ names = @engine.reminder_store.restore(entries)
227
+ Log.info(:worker, "reminders_carried", count: names.size)
228
+ rescue StandardError => e
229
+ Log.warn(:worker, "reminders_carry_restore_failed", error: e.class.name, msg: e.message)
230
+ end
231
+
232
+ # @return [Symbol] +result+, with #discard? decided and, for a session
233
+ # kept, its recap written: the Bridge is closed and the idle jobs are
234
+ # stopped by now, and nothing waits on this (the TUI has detached). A
235
+ # `chi send` meanwhile is picked up after the exit (WorkerBoot.run_session_loop);
236
+ # a `chi --attach` finds no Bridge until then.
237
+ # A restart keeps even an empty session (a new worker takes it over at
238
+ # once) and leaves the recap to the conversation's next real pause.
239
+ def left(result)
240
+ deleting = (result == :exit_requested && @exit_claim.deletes?) || result == :scratch_left
241
+ # The attached context goes with this process: a change that landed after
242
+ # the leaving pass looked at it has no later pass to note it, so note it
243
+ # here (no wake turn: the worker is on its way out). Not into a session
244
+ # /exit --delete deletes next: its save could land after the delete and
245
+ # write the session back.
246
+ absorb_context unless deleting
247
+ # The watch goes with this process: a task that finished since the
248
+ # last look (nothing held the exit for it: queue, a note-only task,
249
+ # /exit) is a plain note for the next turn, not lost. Not into a
250
+ # session /exit --delete deletes next: its save could land after the
251
+ # delete and write the session back.
252
+ @task_wakes.absorb unless deleting
253
+ return result if %i[restart scratch_left].include?(result)
254
+
255
+ @discard = empty_session?
256
+ write_recap_on_leave unless @discard || deleting
257
+ result
258
+ end
259
+
260
+ def write_recap_on_leave
261
+ written = @engine.write_recap_now
262
+ Log.info(:worker, "recap_on_leave") if written
263
+ rescue StandardError => e
264
+ Log.warn(:worker, "recap_on_leave_failed", error: e.class.name, msg: e.message)
265
+ end
266
+
267
+ # Memory used before any turn saved it lives only in the Engine.
268
+ def empty_session?
269
+ SessionManager.discardable?(@session_id, state_dir: @state_dir, default_model: @default_model,
270
+ used_memory_names: @engine.used_memory_names)
271
+ end
272
+
273
+ # The delegate children of this session that are running a turn or have
274
+ # a live worker. ChildrenStatus.of scans the session files; this runs on
275
+ # an exit request, not every pass.
276
+ # @return [Array<ChildrenStatus::Child>]
277
+ def live_delegates
278
+ ChildrenStatus.of(@session_id, state_dir: @state_dir)
279
+ .select { |child| child.delegate && (child.state == "running" || child.live) }
280
+ rescue StandardError => e
281
+ Log.warn(:worker, "delegate_look_failed", error: e.class.name, msg: e.message)
282
+ []
283
+ end
284
+ end
285
+ end
286
+ end