samagotchi 0.175.0 → 0.177.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 (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +11 -4
  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 +13 -6
  10. data/docs/internals/prompt-caching.md +3 -0
  11. data/docs/internals/web-frontend.md +38 -11
  12. data/docs/internals/working-set.md +77 -6
  13. data/docs/sessions.md +3 -2
  14. data/lib/samagotchi/bridge.rb +11 -4
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/config.rb +3 -0
  17. data/lib/samagotchi/engine/models.rb +11 -0
  18. data/lib/samagotchi/engine/session.rb +9 -0
  19. data/lib/samagotchi/engine.rb +1 -0
  20. data/lib/samagotchi/engine_snapshots.rb +3 -0
  21. data/lib/samagotchi/participant_uploads.rb +14 -1
  22. data/lib/samagotchi/prompt_part.rb +66 -0
  23. data/lib/samagotchi/session.rb +10 -1
  24. data/lib/samagotchi/system_prompt.rb +191 -12
  25. data/lib/samagotchi/version.rb +1 -1
  26. data/lib/samagotchi/web/app.rb +15 -2
  27. data/lib/samagotchi/web/participant_images.rb +16 -12
  28. data/lib/samagotchi/web/participant_show.rb +1 -1
  29. data/lib/samagotchi/web/participant_view.rb +27 -1
  30. data/lib/samagotchi/web/public/app.js +7 -2
  31. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  32. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  33. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  34. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  35. data/lib/samagotchi/web/public/index.html +43 -9
  36. data/lib/samagotchi/web/public/restore.js +3 -1
  37. data/lib/samagotchi/web/public/session_fields.js +10 -4
  38. data/lib/samagotchi/web/public/session_prefs.js +92 -0
  39. data/lib/samagotchi/web/public/session_state.js +14 -1
  40. data/lib/samagotchi/web/public/session_store.js +1 -1
  41. data/lib/samagotchi/web/public/session_sync.js +3 -0
  42. data/lib/samagotchi/web/public/session_view.js +33 -3
  43. data/lib/samagotchi/web/public/stage_asking.js +20 -11
  44. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  45. data/lib/samagotchi/web/public/stage_missing.js +3 -5
  46. data/lib/samagotchi/web/public/stage_model.js +2 -1
  47. data/lib/samagotchi/web/public/stage_view.js +6 -1
  48. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  49. data/lib/samagotchi/web/public/stream_handlers.js +10 -5
  50. data/lib/samagotchi/web/public/tokens.css +2 -2
  51. data/lib/samagotchi/web/public/turn_events.js +1 -1
  52. data/lib/samagotchi/web/public/working_set.js +51 -7
  53. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  54. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  55. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  56. data/lib/samagotchi/web/public/ws_sections.js +251 -0
  57. data/lib/samagotchi/web/server.rb +6 -2
  58. data/lib/samagotchi/web/session_show.rb +13 -2
  59. data/lib/samagotchi/worker/child_side.rb +123 -0
  60. data/lib/samagotchi/worker/command_queue.rb +350 -0
  61. data/lib/samagotchi/worker/leave.rb +286 -0
  62. data/lib/samagotchi/worker/scratch.rb +99 -0
  63. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  64. data/lib/samagotchi/worker/startup.rb +92 -0
  65. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  66. data/lib/samagotchi/worker.rb +25 -1065
  67. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  68. data/lib/samagotchi/working_set.rb +32 -4
  69. data/lib/samagotchi/working_set_command.rb +3 -2
  70. data/lib/samagotchi/working_set_steer.rb +21 -3
  71. metadata +13 -1
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../bridge_client"
4
+ require_relative "../client_id"
5
+ require_relative "../degrade"
6
+ require_relative "../log"
7
+ require_relative "../session_manager"
8
+
9
+ module Samagotchi
10
+ class Worker
11
+ # A `chi scratch` worker whose terminal is gone: #start_scratch_watch (a
12
+ # thread that cancels an unattended turn each tick), #cancel_unattended_turn,
13
+ # #scratch_unattended? and #leave_scratch (the idle pass's leave), with
14
+ # SCRATCH_JOIN_GRACE and SCRATCH_GONE_AFTER. Writes @unattended_since
15
+ # (the scratch thread and the loop, no lock: a monotonic stamp, benign).
16
+ # Reads @poll_interval, @session, @bridge, @started_at (#start), @engine,
17
+ # @session_id and @waker. #scratch? and @scratch_watch (#start_background,
18
+ # #teardown) stay in Worker.
19
+ module ScratchPart
20
+ # How long a scratch worker waits for its terminal's first stream
21
+ # (AttachLauncher attaches within BRIDGE_WAIT of the spawn).
22
+ SCRATCH_JOIN_GRACE = 30
23
+
24
+ # How long a scratch worker's terminal may have no stream open, after
25
+ # it had one, before it counts as gone: twice the attached terminal's
26
+ # whole reconnect ladder (TerminalUI::LocalLink#reconnect_delays), so
27
+ # a reconnect gap (a dropped stream, a slow worker) never reads as a
28
+ # terminal that left.
29
+ SCRATCH_GONE_AFTER = 2 * BridgeClient::EventStream::REDISCOVER_DELAYS.sum
30
+
31
+ private
32
+
33
+ # A scratch session's turn never runs on with no terminal: a turn
34
+ # waiting on a question or an approval would keep the worker up for
35
+ # nobody. Each tick while a turn runs and its terminal is gone
36
+ # (#scratch_unattended?), the question is dropped and the turn
37
+ # cancelled as a stop cancels it; the idle pass then leaves
38
+ # (:scratch_left) and the session is deleted.
39
+ def start_scratch_watch
40
+ Thread.new do
41
+ loop do
42
+ sleep(@poll_interval)
43
+ Degrade.call(:worker, "scratch_watch_failed") { cancel_unattended_turn }
44
+ end
45
+ end.tap { |thread| thread.report_on_exception = false }
46
+ end
47
+
48
+ def cancel_unattended_turn
49
+ return unless @engine.turn_running? && scratch_unattended?
50
+
51
+ Log.info(:worker, "scratch_turn_cancelled", sid: @session_id)
52
+ @engine.cancel_question(SessionManager::STOP_CANCEL_REASON) if @engine.pending_question
53
+ @engine.cancel_current_turn!(SessionManager::STOP_CANCEL_REASON.to_sym)
54
+ @waker.wake
55
+ end
56
+
57
+ # Whether this is a `chi scratch` session's worker whose terminal is
58
+ # gone: no terminal stream (a tui: client id's) open for
59
+ # SCRATCH_GONE_AFTER, after a stream was (a killed TUI's closes as its
60
+ # writer reads the hang-up), or none came within SCRATCH_JOIN_GRACE.
61
+ # Any other stream (a web tab's, which chi web refuses for a scratch
62
+ # session anyway) never keeps it. Its terminal deletes it on every way
63
+ # out it sees; this is for the ones it doesn't (kill -9, a closed
64
+ # terminal window).
65
+ def scratch_unattended?
66
+ return false unless @session&.scratch && @bridge
67
+
68
+ if @bridge.open_streams_of(ClientId::TUI_PREFIX).positive?
69
+ @unattended_since = nil
70
+ return false
71
+ end
72
+ return monotonic_now - @started_at >= SCRATCH_JOIN_GRACE unless @bridge.streams_served.positive?
73
+
74
+ # Set by the first look (the scratch watch or the idle pass) that
75
+ # finds no stream; a stream back resets it above.
76
+ @unattended_since ||= monotonic_now
77
+ monotonic_now - @unattended_since >= SCRATCH_GONE_AFTER
78
+ end
79
+
80
+ # #leave_idle for a scratch worker its terminal left: checked again with
81
+ # the event log held, then the intake closes. The session is deleted
82
+ # once the lock is free (WorkerBoot.run_session_loop: :scratch_left).
83
+ # @return [Boolean] false when a client came back since
84
+ def leave_scratch
85
+ stop_bridge_after do
86
+ @engine.synchronize_events do
87
+ # A turn still running is the scratch watch's to cancel first.
88
+ next false unless scratch_unattended? && !@engine.turn_running?
89
+
90
+ @bridge&.close_intake
91
+ @engine.stop_idle(join: false)
92
+ Log.info(:worker, "scratch_left", served: @bridge.streams_served)
93
+ true
94
+ end
95
+ end
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../log"
4
+ require_relative "../session"
5
+
6
+ module Samagotchi
7
+ class Worker
8
+ # A signal's grace, on a thread of its own (WorkerSignals#fire):
9
+ # #signalled?, #signal_leave, #signalled, #signal_hard_exit and
10
+ # #signal_grace_expired, with the SIGNAL_* times. Writes @grace_expired
11
+ # (under @signal_mutex). Worker writes the rest it reads: @run_thread
12
+ # (#run), @loop_started (#run_loop), @left_loop (#run's ensure),
13
+ # @turn_ending (the turn observer) and the grace ivars and @signal_mutex
14
+ # (#initialize). Reads those, @signals, @engine, @waker, @session_id and
15
+ # @state_dir.
16
+ module SignalGracePart
17
+ # How long a signalled worker's turn has to end (it is canceled at once,
18
+ # and again every SIGNAL_RETRY until it ends: a signal that lands just
19
+ # before the turn begins finds none to cancel).
20
+ SIGNAL_GRACE = 3.0
21
+ # A second signal, or a TERM after `chi sessions stop` marked the
22
+ # session stopped (that stop already canceled over the Bridge and waits
23
+ # only seconds for the lock): this much.
24
+ SIGNAL_SHORT_GRACE = 0.5
25
+ SIGNAL_RETRY = 0.1
26
+ # After the grace ran out and the signal was raised: the process ends
27
+ # this much later at the latest (a teardown that hangs).
28
+ SIGNAL_HARD_EXIT = 10.0
29
+
30
+ private
31
+
32
+ def signalled? = !@signals.signal.nil?
33
+
34
+ # @return [Symbol] :stopped when the session was stopped too (chi
35
+ # sessions stop TERMs its worker), else :signal
36
+ def signal_leave
37
+ Session.stopped_marker?(@session_id, state_dir: @state_dir) ? :stopped : :signal
38
+ end
39
+
40
+ # A signal (WorkerSignals#fire), on a thread of its own: the loop wakes
41
+ # (an idle worker leaves at once), the running turn is canceled as a
42
+ # Stop (again every SIGNAL_RETRY, until the loop has left), and when
43
+ # the grace runs out first, #signal_grace_expired. A turn that has
44
+ # ended and runs its after_turn hooks (which store the answer's display
45
+ # and refs) is no longer canceled, and gets until SIGNAL_HARD_EXIT
46
+ # past the grace, the worker's own end of the turn (its saves, after
47
+ # the turn stopped running) too: the loop leaves next. A grace that runs out before the loop started waits
48
+ # for it (the loop's first look leaves). A signal after the loop left
49
+ # (the teardown, the caller's last steps) only brings the hard exit.
50
+ def signalled(name, count)
51
+ Log.info(:worker, "signal", signal: name, count: count, turn_running: @engine&.turn_running? || false)
52
+ return signal_hard_exit if @left_loop
53
+
54
+ @waker.wake
55
+ short = count > 1 || Session.stopped_marker?(@session_id, state_dir: @state_dir)
56
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
57
+ deadline = now + (short ? @signal_short_grace : @signal_grace)
58
+ hooks_deadline = deadline + @signal_hard_exit
59
+ ended = false
60
+ until @left_loop
61
+ running = @engine&.turn_running?
62
+ ended ||= running && @turn_ending
63
+ @engine.cancel_current_turn!(:signal) if running && !ended
64
+ break if @loop_started && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= (ended ? hooks_deadline : deadline)
65
+
66
+ sleep(SIGNAL_RETRY)
67
+ end
68
+ signal_grace_expired(name) unless @left_loop
69
+ rescue StandardError => e
70
+ Log.warn(:worker, "signal_failed", signal: name, error: e.class.name, msg: e.message)
71
+ end
72
+
73
+ # The process ends SIGNAL_HARD_EXIT from now at the latest.
74
+ def signal_hard_exit
75
+ sleep(@signal_hard_exit)
76
+ @signals.hard_exit
77
+ end
78
+
79
+ # The turn didn't end in time (a tool that ignores the cancel, slow
80
+ # after_turn hooks): the session is saved as it is now (a turn that has
81
+ # ended: with it), and the signal raised in the loop's thread, so
82
+ # Worker#run's teardown and the lock's release still run. The process
83
+ # ends SIGNAL_HARD_EXIT later at the latest. Once, whatever the signals.
84
+ def signal_grace_expired(name)
85
+ expired = @signal_mutex.synchronize { !@grace_expired && !@left_loop && (@grace_expired = true) }
86
+ return unless expired
87
+
88
+ Log.warn(:worker, "signal_grace_expired", signal: name, turn_running: @engine&.turn_running? || false)
89
+ save_or_log(:signal) { save_session }
90
+ # Not once the loop has left (it may have, during the save).
91
+ @signal_mutex.synchronize { @run_thread&.raise(SignalException.new(name)) unless @left_loop }
92
+ signal_hard_exit
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../guardrails/parent_policy"
4
+ require_relative "../log"
5
+ require_relative "../session"
6
+ require_relative "../session_inbox"
7
+ require_relative "../turn_checkpoint"
8
+ require_relative "../worker_inbound"
9
+
10
+ module Samagotchi
11
+ class Worker
12
+ # The start-up settle, before the Bridge serves: #settle_interrupted_turn,
13
+ # #settle_stale_status, #prune_tombstones, #announce_session_warnings and
14
+ # #drop_dead_question. Called by #start and #serve only; no state of its
15
+ # own. Writes @session (the interrupted turn's end, the stale status, a
16
+ # dead question) and saves it. Reads @session, @session_dir, @session_id,
17
+ # @state_dir and @engine.
18
+ module StartupPart
19
+ private
20
+
21
+ # A turn an earlier worker died in (TurnCheckpoint's mark in the file):
22
+ # ended now as canceled, with its note, and saved, before the Bridge
23
+ # serves the session (TurnCheckpoint.settle). Its queued id's wait
24
+ # (chi send --queue --wait) reads the end it records in the session dir.
25
+ def settle_interrupted_turn
26
+ mark = TurnCheckpoint.settle(@session, session_dir: @session_dir)
27
+ return unless mark
28
+
29
+ Log.info(:worker, "interrupted_turn_settled", turn_id: mark.id, iteration: mark.iteration, at: mark.at)
30
+ save_or_log(:interrupted_turn) { save_session }
31
+ end
32
+
33
+ # Statuses that can be stale before this worker handles its first turn.
34
+ # No turn runs yet: a status a turn would be behind is from before this
35
+ # worker, and goes idle under the lock (resume_session writes nothing to
36
+ # the file, which this worker owns): a stopped one with no stop marker
37
+ # (Session.load reads it stopped while the marker is there; a stop that
38
+ # landed before an earlier worker took the lock saved it so), an error,
39
+ # a running whose worker died. Not a new session's running whose first
40
+ # prompt waits (WorkerInbound.initial_prompt_pending?).
41
+ STALE_STATUSES = [Session::STATUS_STOPPED, Session::STATUS_ERROR, Session::STATUS_RUNNING].freeze
42
+
43
+ # Saved whatever the status: the save stamps updated_at, which a resume
44
+ # used to move (an old session woken with no turn, an attach or a web
45
+ # wake, stays young for the sweep and moves up the lists). Not a
46
+ # stopped one: this worker leaves at once, and would write "stopped".
47
+ def settle_stale_status
48
+ return if Session.stopped_marker?(@session_id, state_dir: @state_dir)
49
+
50
+ status = @session.status
51
+ if STALE_STATUSES.include?(status) && !(status == Session::STATUS_RUNNING && WorkerInbound.initial_prompt_pending?(@session))
52
+ @session.status = Session::STATUS_IDLE
53
+ Log.info(:worker, "stale_status_settled", status: status)
54
+ end
55
+ save_or_log(:worker_start) { save_session }
56
+ end
57
+
58
+ # The per-input tombstones (removed, settled, merged) older than
59
+ # SessionInbox::TOMBSTONE_MAX_AGE, once per worker start: they only go
60
+ # with the session dir otherwise.
61
+ def prune_tombstones
62
+ removed = SessionInbox.prune_removed(@session_dir)
63
+ settled = TurnCheckpoint.prune_settled(@session_dir)
64
+ merged = SessionInbox.prune_merged(@session_dir)
65
+ Log.info(:worker, "tombstones_pruned", removed: removed, settled: settled, merged: merged) if (removed + settled + merged).positive?
66
+ end
67
+
68
+ # A saved parent_answers that isn't a level reads as hard on every
69
+ # answer without a word; said once here, as the session loads.
70
+ def announce_session_warnings
71
+ value = @session.parent_answers
72
+ return unless Guardrails::ParentPolicy.unknown_level?(value)
73
+
74
+ @engine.announce({ type: :guardrail_warning, label: "parent_answers",
75
+ message: "parent_answers #{value.inspect} in session #{@session_id} isn't hard/standard/soft; hard applies" })
76
+ end
77
+
78
+ # A question saved by a worker that died while it waited (an
79
+ # ask_user_question, an approval, a hook's question): the turn that
80
+ # asked is gone, so nobody can answer it, and left in the file it
81
+ # would keep the hub's "needs you" badge on for good. Dropped and saved
82
+ # before the Engine and the Bridge exist (no question lock, no events).
83
+ def drop_dead_question
84
+ id = @session.drop_dead_question
85
+ return unless id
86
+
87
+ Log.info(:worker, "dead_question_dropped", id: id)
88
+ save_or_log(:dead_question) { save_session }
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ require_relative "../child_reports"
6
+ require_relative "../client_id"
7
+ require_relative "../iteration_limit"
8
+ require_relative "../log"
9
+ require_relative "../session_inbox"
10
+ require_relative "../turn_origin"
11
+
12
+ module Samagotchi
13
+ class Worker
14
+ # The turns nobody typed: a delegate report's wake (#run_wake_turn), a
15
+ # finished task's (#run_task_wake), an attached context change's
16
+ # (#run_context_wake_turn) and the due reminders (#run_due_reminders), and
17
+ # the idle loop's sleep (#idle_wait). Glue over WorkerWakes, WorkerTaskWakes
18
+ # and WorkerInbound: it writes no ivar of its own. Reads @child_reports,
19
+ # @wakes, @turn_flow, @inbound, @continue_offer, @task_wakes, @engine,
20
+ # @session_dir and @poll_interval.
21
+ module WakeTurnsPart
22
+ # A reminder turn's origin: chi's own (system:reminder). Its run gets
23
+ # an id of its own (#wake_origin); this constant has none.
24
+ REMINDER_ORIGIN = TurnOrigin.new(client_id: ClientId::REMINDER)
25
+
26
+ # A wake turn's minted enqueued_id starts with this
27
+ # (SessionInbox::ENQUEUED_ID_NAME).
28
+ WAKE_ID_PREFIX = "wake-"
29
+
30
+ private
31
+
32
+ # :due when an idle parent should run a turn for its delegate
33
+ # children's reports now (session.delegate_reports: wake): rings wait,
34
+ # no continue offer does (they merge into its turn), wakes aren't paused
35
+ # by a failed one, and the wake budget isn't spent; :budget when only
36
+ # the budget stops it; nil otherwise.
37
+ def wake_state
38
+ return nil unless @child_reports && ChildRing.mode == "wake"
39
+
40
+ @wakes.delegate_state(awaiting_continue: @turn_flow&.awaiting_continue?) { @child_reports.waiting? }
41
+ end
42
+
43
+ # Run a turn nobody typed for the reports the rings bring (a wake turn):
44
+ # a continue turn (no prompt bubble) whose first boundary merges them,
45
+ # with origin child:<id8>. A failure goes back to the checkpoint, keeps
46
+ # the rings and pauses wakes until a human's input (a provider outage
47
+ # doesn't loop).
48
+ # @return [Boolean] whether a wake turn ran
49
+ def run_wake_turn
50
+ return false if @wakes.in_grace?
51
+
52
+ state = wake_state
53
+ budget_notice if state == :budget
54
+ return false unless state == :due
55
+
56
+ # Unresolved: a relay among them opens its card at the turn's first
57
+ # boundary, on the turn thread (a Stop closes it).
58
+ reports, = take_child_reports(resolve: false)
59
+ # The turn must not generate with nothing to say: the drain gets this
60
+ # exact list at its first boundary.
61
+ return false if reports.empty?
62
+
63
+ @wakes.hand_over(reports)
64
+ Log.info(:worker, "delegate_wake_turn", reports: reports.size, in_a_row: @wakes.count!)
65
+ # Rolled back, the rings stay (settle_child_reports): the user's next
66
+ # turn takes them. A turn that got somewhere stays, and read them.
67
+ run_wake(origin: reports.first.origin,
68
+ failed: reports.size == 1 ? "a delegate's report" : "#{reports.size} delegate reports",
69
+ kept: "chi keeps #{reports.size == 1 ? "the report and brings it" : "the reports and brings them"} " \
70
+ "again with the user's next message.")
71
+ true
72
+ ensure
73
+ @wakes.drop_handed
74
+ end
75
+
76
+ # The wake budget is spent: the parent's UIs hear once that reports
77
+ # wait for the next message.
78
+ def budget_notice
79
+ return unless @wakes.notice_budget!
80
+
81
+ count = SessionInbox.find_ring_files(@session_dir).map { |f| SessionInbox.read_ring(f)&.dig(:child_id) }.uniq.size
82
+ @engine.announce(type: :hook_notice, hook: "delegate", level: :info, between_turns: true,
83
+ text: "#{count} delegate report#{"s" if count != 1} waiting; #{count == 1 ? "it joins" : "they join"} " \
84
+ "your next message (#{@wakes.max} turn#{"s" if @wakes.max != 1} ran for reports in a row, #{ChildRing::MAX_WAKES_KEY})")
85
+ end
86
+
87
+ # A wake turn (a delegate report's, an attached context change's, a
88
+ # finished task's): a continue turn nobody typed, from +origin+. A
89
+ # failure goes back to before the turn and pauses wakes until a human's
90
+ # input (a provider outage doesn't loop); so does a Stop before it got
91
+ # anywhere (a Stop or a before_turn hook's cancel before the model
92
+ # call, restored by TurnFlow), rather than waking again at once. Either
93
+ # way +mark+ (a WorkerInbound::ContextWake or TaskWake: its wake note,
94
+ # the turn's first message) goes back to a plain note
95
+ # (WorkerInbound#unmark_wake), unless the failed turn kept its steps.
96
+ # +failed+ names the wake in the failed turn's note, +kept+ says what
97
+ # happens to it (TurnFlow#prompt_turn_failed).
98
+ def run_wake(origin:, failed:, kept: nil, mark: nil)
99
+ @turn_flow.before_prompt_turn
100
+ restores = @turn_flow.restores
101
+ run_engine_turn(nil, continue: true, origin: wake_origin(origin), id: mark&.turn_id,
102
+ max_iterations: IterationLimit.for) do |result, error|
103
+ if error
104
+ steps_kept = @turn_flow.prompt_turn_failed(error: error, wake: failed, wake_kept: kept) == :kept
105
+ @inbound.unmark_wake(mark) if mark && !steps_kept
106
+ @wakes.pause!
107
+ else
108
+ @continue_offer.after_turn(result)
109
+ if result.canceled? && @turn_flow.restores != restores
110
+ @inbound.unmark_wake(mark) if mark
111
+ @wakes.pause!
112
+ end
113
+ end
114
+ end
115
+ end
116
+
117
+ # A turn nobody typed for a changed source (a context wake): a continue
118
+ # turn from context:<name> whose first message is the wake note already
119
+ # in the conversation (named by +turn_id+), on the same rules as a
120
+ # delegate report's wake turn (#run_wake): it counts toward
121
+ # session.max_wakes (a peer's answer toward context.peer_turns too,
122
+ # unless it agrees).
123
+ # +context_wake+: a WorkerInbound::ContextWake.
124
+ def run_context_wake_turn(context_wake)
125
+ name = context_wake.name
126
+ Log.info(:worker, "context_wake_turn", name: name, in_a_row: @wakes.count!(peer: context_wake.peer_turn?))
127
+ run_wake(origin: context_wake.origin, failed: "the change in attached context #{name}", mark: context_wake)
128
+ end
129
+
130
+ # The background tasks this session started that finished unseen, as
131
+ # notes (WorkerTaskWakes#take), and the wake turn the first one may
132
+ # start.
133
+ # @return [Boolean] whether a wake turn ran
134
+ def run_task_wake
135
+ task_wake = @task_wakes.take
136
+ return false unless task_wake
137
+
138
+ run_task_wake_turn(task_wake)
139
+ true
140
+ end
141
+
142
+ # A turn nobody typed for a finished task: a continue turn from
143
+ # task:<id> whose first message is the wake note, on the delegate wake's
144
+ # rules (#run_wake; counted toward session.max_wakes): a failure that
145
+ # kept nothing, or a Stop that restored the conversation, leaves the
146
+ # note as a plain one (M4).
147
+ def run_task_wake_turn(task_wake)
148
+ Log.info(:worker, "task_wake_turn", task_id: task_wake.id, in_a_row: @wakes.count!)
149
+ run_wake(origin: task_wake.origin, failed: "a finished background task (#{task_wake.name.delete_prefix("task ")})",
150
+ kept: "Its note stays for the user's next message.", mark: task_wake)
151
+ end
152
+
153
+ # A due reminder runs as a continue turn: Engine#run_turn
154
+ # injects the reminders as a tail system message, and no user message is
155
+ # added. A prompt's turn may have injected them already (a stale latch):
156
+ # then there is nothing to run.
157
+ # @return [Boolean] whether a reminder turn ran
158
+ def run_due_reminders
159
+ return false if @engine.due_reminder_names.empty?
160
+
161
+ @engine.clear_due_reminder_names!
162
+ return false unless @engine.reminders_due?
163
+
164
+ @continue_offer.drop(REMINDER_ORIGIN)
165
+ # A failure has no prompt to hand back (the Engine announced
166
+ # :turn_failed). The offer went before the turn
167
+ # (ContinueOffer#drop); either way the rollback window closes.
168
+ run_engine_turn(nil, continue: true, origin: wake_origin(REMINDER_ORIGIN),
169
+ max_iterations: IterationLimit.for) { @turn_flow.after_reminder_turn }
170
+ true
171
+ end
172
+
173
+ # A turn nobody typed (a reminder, a wake) with an enqueued_id of its
174
+ # own, minted here as it runs, so its checkpoint mark, last_turn, reply
175
+ # file and settle name it (a wait with no message binds it:
176
+ # ReplyWait.own_turn). Never on the origin constants nor on
177
+ # ChildReports::Report#origin: a report merged into a turn keeps an
178
+ # id-less origin, which the web page reads as a report (turn_events.js
179
+ # promptOps), not as an unmatched steer.
180
+ # @return [TurnOrigin] +origin+ with an id ("wake-<16 hex>")
181
+ def wake_origin(origin)
182
+ origin.enqueued_id ? origin : origin.with(enqueued_id: "#{WAKE_ID_PREFIX}#{SecureRandom.hex(8)}")
183
+ end
184
+
185
+ # The idle loop's sleep: the fallback tick, or less while reports or
186
+ # attached-context wakes wait out the start grace.
187
+ def idle_wait = @wakes.idle_wait(@poll_interval) { wake_state == :due || @inbound.context_wake_waiting? }
188
+ end
189
+ end
190
+ end