samagotchi 0.174.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 (63) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -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 +10 -3
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +11 -5
  10. data/docs/internals/web-frontend.md +44 -11
  11. data/docs/sessions.md +2 -2
  12. data/docs/testing.md +25 -3
  13. data/lib/samagotchi/answer_text.rb +4 -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/llm/stray_tool_call.rb +7 -4
  18. data/lib/samagotchi/llm_context_stale.rb +2 -1
  19. data/lib/samagotchi/message_parts.rb +5 -2
  20. data/lib/samagotchi/model_markup.rb +22 -0
  21. data/lib/samagotchi/model_profile.rb +8 -7
  22. data/lib/samagotchi/participant_uploads.rb +14 -1
  23. data/lib/samagotchi/prompt_literal_guard.rb +7 -6
  24. data/lib/samagotchi/task_transcript.rb +10 -5
  25. data/lib/samagotchi/tool_call_parser.rb +6 -5
  26. data/lib/samagotchi/turn_note.rb +2 -1
  27. data/lib/samagotchi/version.rb +1 -1
  28. data/lib/samagotchi/web/app.rb +15 -2
  29. data/lib/samagotchi/web/participant_images.rb +16 -12
  30. data/lib/samagotchi/web/participant_show.rb +1 -0
  31. data/lib/samagotchi/web/participant_view.rb +31 -3
  32. data/lib/samagotchi/web/public/app.js +18 -4
  33. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  34. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  35. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  36. data/lib/samagotchi/web/public/reload_check.js +0 -3
  37. data/lib/samagotchi/web/public/restore.js +3 -1
  38. data/lib/samagotchi/web/public/session_prefs.js +89 -0
  39. data/lib/samagotchi/web/public/session_sync.js +3 -0
  40. data/lib/samagotchi/web/public/session_view.js +41 -3
  41. data/lib/samagotchi/web/public/stage_asking.js +21 -18
  42. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  43. data/lib/samagotchi/web/public/stage_missing.js +148 -0
  44. data/lib/samagotchi/web/public/stage_model.js +2 -1
  45. data/lib/samagotchi/web/public/stage_view.js +14 -4
  46. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  47. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  48. data/lib/samagotchi/web/public/turn_events.js +1 -1
  49. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  50. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  51. data/lib/samagotchi/web/server.rb +6 -2
  52. data/lib/samagotchi/web/session_show.rb +42 -4
  53. data/lib/samagotchi/worker/child_side.rb +123 -0
  54. data/lib/samagotchi/worker/command_queue.rb +346 -0
  55. data/lib/samagotchi/worker/leave.rb +286 -0
  56. data/lib/samagotchi/worker/scratch.rb +99 -0
  57. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  58. data/lib/samagotchi/worker/startup.rb +92 -0
  59. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  60. data/lib/samagotchi/worker.rb +24 -1065
  61. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  62. metadata +12 -2
  63. data/lib/samagotchi/web/public/cards_offscreen.js +0 -69
@@ -4,10 +4,8 @@ require "fileutils"
4
4
  require "securerandom"
5
5
 
6
6
  require_relative "client_id"
7
- require_relative "command_intake"
8
7
  require_relative "config"
9
8
  require_relative "engine"
10
- require_relative "guardrails/parent_policy"
11
9
  require_relative "events"
12
10
  require_relative "session"
13
11
  require_relative "session_inbox"
@@ -28,15 +26,12 @@ require_relative "reminder_carry"
28
26
  require_relative "log"
29
27
  require_relative "turn_flow"
30
28
  require_relative "turn_checkpoint"
31
- require_relative "llm/errors"
32
29
  require_relative "continue_offer"
33
30
  require_relative "iteration_limit"
34
31
  require_relative "session_commands"
35
- require_relative "session_setting"
36
32
  require_relative "queued_command"
37
33
  require_relative "model_profile"
38
34
  require_relative "child_reports"
39
- require_relative "verify_fresh"
40
35
  require_relative "child_move"
41
36
  require_relative "starting_marker"
42
37
  require_relative "context_absorber"
@@ -46,6 +41,13 @@ require_relative "task_watch"
46
41
  require_relative "tools/task_runtime"
47
42
  require_relative "worker_participant_gate"
48
43
  require_relative "worker_exit_claim"
44
+ require_relative "worker/leave"
45
+ require_relative "worker/wake_turns"
46
+ require_relative "worker/startup"
47
+ require_relative "worker/signal_grace"
48
+ require_relative "worker/scratch"
49
+ require_relative "worker/child_side"
50
+ require_relative "worker/command_queue"
49
51
 
50
52
  module Samagotchi
51
53
  # The loop of a background session worker, once it owns the session (see
@@ -78,35 +80,30 @@ module Samagotchi
78
80
  # no new work. A turn that hasn't ended SIGNAL_GRACE seconds after the
79
81
  # signal is cut: the session is saved as it is and the signal raised in
80
82
  # the loop's thread, as Ruby's default would (the teardown still runs).
83
+ #
84
+ # This file keeps the loop, the wiring, the prompt turns and the steering
85
+ # drain. Seven concerns are parts, lib/samagotchi/worker/<concern>.rb
86
+ # holding Worker::<Concern>Part, included here (they share Worker's ivars):
87
+ # LeavePart (exit and leave), WakeTurnsPart (the turns nobody typed),
88
+ # StartupPart (the start-up settle), SignalGracePart (a signal's grace),
89
+ # ScratchPart (a scratch worker whose terminal left), ChildSidePart (a
90
+ # delegate child's rings, Verify fresh verdicts) and CommandQueuePart
91
+ # (session commands between turns).
81
92
  class Worker
93
+ include LeavePart
94
+ include WakeTurnsPart
95
+ include StartupPart
96
+ include SignalGracePart
97
+ include ScratchPart
98
+ include ChildSidePart
99
+ include CommandQueuePart
100
+
82
101
  FALLBACK_TICK_SECONDS = 5
83
102
  # A worker just started runs no wake turn for delegate reports this
84
103
  # long: a worker spawned for a message (chi send to a stopped parent)
85
104
  # gets it over the Bridge a moment after it starts, and that message's
86
105
  # turn goes first (the reports join it).
87
106
  WAKE_START_GRACE = 2.0
88
- # How much of a command's output goes into its :command_ran, in chars.
89
- # Room for a real listing (/guardrails with a bundle's rules, /models):
90
- # the event lives only in the Bridge's ring (256 events, in memory) and
91
- # on the streams, a session file doesn't hold it.
92
- COMMAND_OUTPUT_LIMIT = 64 * 1024
93
- BUSY_OUTPUT = "busy: wait for the turn to end"
94
- # /exit held by background tasks a finish wake waits for: how to end them.
95
- TASK_STOP_HINT = "stop one with the web's stop-task button or by asking for task_stop"
96
- # !rollback mid-turn would mean "the turn I'm in".
97
- ROLLBACK_BUSY_OUTPUT = "busy: Ctrl-C the turn first, then !rollback"
98
- # How long a signalled worker's turn has to end (it is canceled at once,
99
- # and again every SIGNAL_RETRY until it ends: a signal that lands just
100
- # before the turn begins finds none to cancel).
101
- SIGNAL_GRACE = 3.0
102
- # A second signal, or a TERM after `chi sessions stop` marked the
103
- # session stopped (that stop already canceled over the Bridge and waits
104
- # only seconds for the lock): this much.
105
- SIGNAL_SHORT_GRACE = 0.5
106
- SIGNAL_RETRY = 0.1
107
- # After the grace ran out and the signal was raised: the process ends
108
- # this much later at the latest (a teardown that hangs).
109
- SIGNAL_HARD_EXIT = 10.0
110
107
 
111
108
  # Wakes the worker loop. Whoever queues work writes it first and wakes
112
109
  # after, and #wait drains every wake before the loop looks for work: a
@@ -231,10 +228,6 @@ module Samagotchi
231
228
  # it; the web's Stop will too.
232
229
  attr_reader :hold_stop
233
230
 
234
- # @return [HoldStop::Stopped, nil] the last stop-all's list (the Bridge's
235
- # exit_stopped)
236
- def stopped_holds = @exit_claim.stopped
237
-
238
231
  private
239
232
 
240
233
  # @return [Symbol] what #run returns
@@ -453,18 +446,6 @@ module Samagotchi
453
446
  }
454
447
  end
455
448
 
456
- # The delegate children of this session that are running a turn or have
457
- # a live worker. ChildrenStatus.of scans the session files; this runs on
458
- # an exit request, not every pass.
459
- # @return [Array<ChildrenStatus::Child>]
460
- def live_delegates
461
- ChildrenStatus.of(@session_id, state_dir: @state_dir)
462
- .select { |child| child.delegate && (child.state == "running" || child.live) }
463
- rescue StandardError => e
464
- Log.warn(:worker, "delegate_look_failed", error: e.class.name, msg: e.message)
465
- []
466
- end
467
-
468
449
  # What runs beside the loop until it leaves.
469
450
  def start_background
470
451
  # Plugins' slow setup (chi.init: an MCP server's first start), in
@@ -482,30 +463,6 @@ module Samagotchi
482
463
  @scratch_watch = start_scratch_watch if @session.scratch
483
464
  end
484
465
 
485
- # A scratch session's turn never runs on with no terminal: a turn
486
- # waiting on a question or an approval would keep the worker up for
487
- # nobody. Each tick while a turn runs and its terminal is gone
488
- # (#scratch_unattended?), the question is dropped and the turn
489
- # cancelled as a stop cancels it; the idle pass then leaves
490
- # (:scratch_left) and the session is deleted.
491
- def start_scratch_watch
492
- Thread.new do
493
- loop do
494
- sleep(@poll_interval)
495
- Degrade.call(:worker, "scratch_watch_failed") { cancel_unattended_turn }
496
- end
497
- end.tap { |thread| thread.report_on_exception = false }
498
- end
499
-
500
- def cancel_unattended_turn
501
- return unless @engine.turn_running? && scratch_unattended?
502
-
503
- Log.info(:worker, "scratch_turn_cancelled", sid: @session_id)
504
- @engine.cancel_question(SessionManager::STOP_CANCEL_REASON) if @engine.pending_question
505
- @engine.cancel_current_turn!(SessionManager::STOP_CANCEL_REASON.to_sym)
506
- @waker.wake
507
- end
508
-
509
466
  # One pass of the loop: the first work found runs (queued commands, a
510
467
  # context wake turn, the first prompt, the queued input files) and the
511
468
  # next pass looks again; with none, #idle_pass.
@@ -596,18 +553,6 @@ module Samagotchi
596
553
  nil
597
554
  end
598
555
 
599
- # Whether a command or an input file waits to run (WorkerIdleExit's
600
- # :input_queued). A participant's file held for the Continue offer
601
- # (#held_for_offer?) doesn't count: what waits is the owner's answer,
602
- # the policy's :continue_offered.
603
- def input_pending?
604
- !@command_queue.empty? || SessionInbox.find_new_input_files(@session_dir).any? { |file| !held_for_offer?(file) }
605
- end
606
-
607
- # Whether +input_file+ waits for the owner's answer to the Continue
608
- # offer that stands (#run_input_files).
609
- def held_for_offer?(input_file) = @turn_flow&.awaiting_continue? && SessionInbox.participant_input?(input_file)
610
-
611
556
  # An error outside a turn: the session is marked errored.
612
557
  # @return [Symbol] :crashed
613
558
  def crashed(error)
@@ -682,76 +627,6 @@ module Samagotchi
682
627
  engine
683
628
  end
684
629
 
685
- # A turn an earlier worker died in (TurnCheckpoint's mark in the file):
686
- # ended now as canceled, with its note, and saved, before the Bridge
687
- # serves the session (TurnCheckpoint.settle). Its queued id's wait
688
- # (chi send --queue --wait) reads the end it records in the session dir.
689
- def settle_interrupted_turn
690
- mark = TurnCheckpoint.settle(@session, session_dir: @session_dir)
691
- return unless mark
692
-
693
- Log.info(:worker, "interrupted_turn_settled", turn_id: mark.id, iteration: mark.iteration, at: mark.at)
694
- save_or_log(:interrupted_turn) { save_session }
695
- end
696
-
697
- # No turn runs yet: a status a turn would be behind is from before this
698
- # worker, and goes idle under the lock (resume_session writes nothing to
699
- # the file, which this worker owns): a stopped one with no stop marker
700
- # (Session.load reads it stopped while the marker is there; a stop that
701
- # landed before an earlier worker took the lock saved it so), an error,
702
- # a running whose worker died. Not a new session's running whose first
703
- # prompt waits (WorkerInbound.initial_prompt_pending?).
704
- STALE_STATUSES = [Session::STATUS_STOPPED, Session::STATUS_ERROR, Session::STATUS_RUNNING].freeze
705
-
706
- #
707
- # Saved whatever the status: the save stamps updated_at, which a resume
708
- # used to move (an old session woken with no turn, an attach or a web
709
- # wake, stays young for the sweep and moves up the lists). Not a
710
- # stopped one: this worker leaves at once, and would write "stopped".
711
- def settle_stale_status
712
- return if Session.stopped_marker?(@session_id, state_dir: @state_dir)
713
-
714
- status = @session.status
715
- if STALE_STATUSES.include?(status) && !(status == Session::STATUS_RUNNING && WorkerInbound.initial_prompt_pending?(@session))
716
- @session.status = Session::STATUS_IDLE
717
- Log.info(:worker, "stale_status_settled", status: status)
718
- end
719
- save_or_log(:worker_start) { save_session }
720
- end
721
-
722
- # The per-input tombstones (removed, settled, merged) older than
723
- # SessionInbox::TOMBSTONE_MAX_AGE, once per worker start: they only go
724
- # with the session dir otherwise.
725
- def prune_tombstones
726
- removed = SessionInbox.prune_removed(@session_dir)
727
- settled = TurnCheckpoint.prune_settled(@session_dir)
728
- merged = SessionInbox.prune_merged(@session_dir)
729
- Log.info(:worker, "tombstones_pruned", removed: removed, settled: settled, merged: merged) if (removed + settled + merged).positive?
730
- end
731
-
732
- # A saved parent_answers that isn't a level reads as hard on every
733
- # answer without a word; said once here, as the session loads.
734
- def announce_session_warnings
735
- value = @session.parent_answers
736
- return unless Guardrails::ParentPolicy.unknown_level?(value)
737
-
738
- @engine.announce({ type: :guardrail_warning, label: "parent_answers",
739
- message: "parent_answers #{value.inspect} in session #{@session_id} isn't hard/standard/soft; hard applies" })
740
- end
741
-
742
- # A question saved by a worker that died while it waited (an
743
- # ask_user_question, an approval, a hook's question): the turn that
744
- # asked is gone, so nobody can answer it, and left in the file it
745
- # would keep the hub's "needs you" badge on for good. Dropped and saved
746
- # before the Engine and the Bridge exist (no question lock, no events).
747
- def drop_dead_question
748
- id = @session.drop_dead_question
749
- return unless id
750
-
751
- Log.info(:worker, "dead_question_dropped", id: id)
752
- save_or_log(:dead_question) { save_session }
753
- end
754
-
755
630
  # The attached context's notes (WorkerInbound#absorb_context), and the
756
631
  # context wake turn one may start. A failure to read or write them (or
757
632
  # in that turn) is logged: the next pass tries again.
@@ -767,22 +642,6 @@ module Samagotchi
767
642
  false
768
643
  end
769
644
 
770
- # No input file or queued command waits: the loop would go idle.
771
- def nothing_queued? = @command_queue.empty? && SessionInbox.find_new_input_files(@session_dir).empty?
772
-
773
- # A turn nobody typed for a changed source (a context wake): a continue
774
- # turn from context:<name> whose first message is the wake note already
775
- # in the conversation (named by +turn_id+), on the same rules as a
776
- # delegate report's wake turn (#run_wake): it counts toward
777
- # session.max_wakes (a peer's answer toward context.peer_turns too,
778
- # unless it agrees).
779
- # +context_wake+: a WorkerInbound::ContextWake.
780
- def run_context_wake_turn(context_wake)
781
- name = context_wake.name
782
- Log.info(:worker, "context_wake_turn", name: name, in_a_row: @wakes.count!(peer: context_wake.peer_turn?))
783
- run_wake(origin: context_wake.origin, failed: "the change in attached context #{name}", mark: context_wake)
784
- end
785
-
786
645
  # The first prompt (spawn_session's): a delegate child's task, which is
787
646
  # its parent's. Its turn carries the id spawn_session gave it, so a
788
647
  # wait for it (--new --wait) names it, and its sender
@@ -842,452 +701,8 @@ module Samagotchi
842
701
  fresh ? fresh.origin_for(origin) : TurnOrigin.of(origin)
843
702
  end
844
703
 
845
- # A due reminder runs as a continue turn: Engine#run_turn
846
- # injects the reminders as a tail system message, and no user message is
847
- # added. A prompt's turn may have injected them already (a stale latch):
848
- # then there is nothing to run.
849
- # @return [Boolean] whether a reminder turn ran
850
- def run_due_reminders
851
- return false if @engine.due_reminder_names.empty?
852
-
853
- @engine.clear_due_reminder_names!
854
- return false unless @engine.reminders_due?
855
-
856
- @continue_offer.drop(REMINDER_ORIGIN)
857
- # A failure has no prompt to hand back (the Engine announced
858
- # :turn_failed). The offer went before the turn
859
- # (ContinueOffer#drop); either way the rollback window closes.
860
- run_engine_turn(nil, continue: true, origin: wake_origin(REMINDER_ORIGIN),
861
- max_iterations: IterationLimit.for) { @turn_flow.after_reminder_turn }
862
- true
863
- end
864
-
865
- # A reminder turn's origin: chi's own (system:reminder). Its run gets
866
- # an id of its own (#wake_origin); this constant has none.
867
- REMINDER_ORIGIN = TurnOrigin.new(client_id: ClientId::REMINDER)
868
-
869
- # A turn nobody typed (a reminder, a wake) with an enqueued_id of its
870
- # own, minted here as it runs, so its checkpoint mark, last_turn, reply
871
- # file and settle name it (a wait with no message binds it:
872
- # ReplyWait.own_turn). Never on the origin constants nor on
873
- # ChildReports::Report#origin: a report merged into a turn keeps an
874
- # id-less origin, which the web page reads as a report (turn_events.js
875
- # promptOps), not as an unmatched steer.
876
- # @return [TurnOrigin] +origin+ with an id ("wake-<16 hex>")
877
- def wake_origin(origin)
878
- origin.enqueued_id ? origin : origin.with(enqueued_id: "#{WAKE_ID_PREFIX}#{SecureRandom.hex(8)}")
879
- end
880
-
881
- # A wake turn's minted enqueued_id starts with this
882
- # (SessionInbox::ENQUEUED_ID_NAME).
883
- WAKE_ID_PREFIX = "wake-"
884
-
885
- # :due when an idle parent should run a turn for its delegate
886
- # children's reports now (session.delegate_reports: wake): rings wait,
887
- # no continue offer does (they merge into its turn), wakes aren't paused
888
- # by a failed one, and the wake budget isn't spent; :budget when only
889
- # the budget stops it; nil otherwise.
890
- def wake_state
891
- return nil unless @child_reports && ChildRing.mode == "wake"
892
-
893
- @wakes.delegate_state(awaiting_continue: @turn_flow&.awaiting_continue?) { @child_reports.waiting? }
894
- end
895
-
896
- # Run a turn nobody typed for the reports the rings bring (a wake turn):
897
- # a continue turn (no prompt bubble) whose first boundary merges them,
898
- # with origin child:<id8>. A failure goes back to the checkpoint, keeps
899
- # the rings and pauses wakes until a human's input (a provider outage
900
- # doesn't loop).
901
- # @return [Boolean] whether a wake turn ran
902
- def run_wake_turn
903
- return false if @wakes.in_grace?
904
-
905
- state = wake_state
906
- budget_notice if state == :budget
907
- return false unless state == :due
908
-
909
- # Unresolved: a relay among them opens its card at the turn's first
910
- # boundary, on the turn thread (a Stop closes it).
911
- reports, = take_child_reports(resolve: false)
912
- # The turn must not generate with nothing to say: the drain gets this
913
- # exact list at its first boundary.
914
- return false if reports.empty?
915
-
916
- @wakes.hand_over(reports)
917
- Log.info(:worker, "delegate_wake_turn", reports: reports.size, in_a_row: @wakes.count!)
918
- # Rolled back, the rings stay (settle_child_reports): the user's next
919
- # turn takes them. A turn that got somewhere stays, and read them.
920
- run_wake(origin: reports.first.origin,
921
- failed: reports.size == 1 ? "a delegate's report" : "#{reports.size} delegate reports",
922
- kept: "chi keeps #{reports.size == 1 ? "the report and brings it" : "the reports and brings them"} " \
923
- "again with the user's next message.")
924
- true
925
- ensure
926
- @wakes.drop_handed
927
- end
928
-
929
- # A wake turn (a delegate report's, an attached context change's, a
930
- # finished task's): a continue turn nobody typed, from +origin+. A
931
- # failure goes back to before the turn and pauses wakes until a human's
932
- # input (a provider outage doesn't loop); so does a Stop before it got
933
- # anywhere (a Stop or a before_turn hook's cancel before the model
934
- # call, restored by TurnFlow), rather than waking again at once. Either
935
- # way +mark+ (a WorkerInbound::ContextWake or TaskWake: its wake note,
936
- # the turn's first message) goes back to a plain note
937
- # (WorkerInbound#unmark_wake), unless the failed turn kept its steps.
938
- # +failed+ names the wake in the failed turn's note, +kept+ says what
939
- # happens to it (TurnFlow#prompt_turn_failed).
940
- def run_wake(origin:, failed:, kept: nil, mark: nil)
941
- @turn_flow.before_prompt_turn
942
- restores = @turn_flow.restores
943
- run_engine_turn(nil, continue: true, origin: wake_origin(origin), id: mark&.turn_id,
944
- max_iterations: IterationLimit.for) do |result, error|
945
- if error
946
- steps_kept = @turn_flow.prompt_turn_failed(error: error, wake: failed, wake_kept: kept) == :kept
947
- @inbound.unmark_wake(mark) if mark && !steps_kept
948
- @wakes.pause!
949
- else
950
- @continue_offer.after_turn(result)
951
- if result.canceled? && @turn_flow.restores != restores
952
- @inbound.unmark_wake(mark) if mark
953
- @wakes.pause!
954
- end
955
- end
956
- end
957
- end
958
-
959
- # The background tasks this session started that finished unseen, as
960
- # notes (WorkerTaskWakes#take), and the wake turn the first one may
961
- # start.
962
- # @return [Boolean] whether a wake turn ran
963
- def run_task_wake
964
- task_wake = @task_wakes.take
965
- return false unless task_wake
966
-
967
- run_task_wake_turn(task_wake)
968
- true
969
- end
970
-
971
- # A turn nobody typed for a finished task: a continue turn from
972
- # task:<id> whose first message is the wake note, on the delegate wake's
973
- # rules (#run_wake; counted toward session.max_wakes): a failure that
974
- # kept nothing, or a Stop that restored the conversation, leaves the
975
- # note as a plain one (M4).
976
- def run_task_wake_turn(task_wake)
977
- Log.info(:worker, "task_wake_turn", task_id: task_wake.id, in_a_row: @wakes.count!)
978
- run_wake(origin: task_wake.origin, failed: "a finished background task (#{task_wake.name.delete_prefix("task ")})",
979
- kept: "Its note stays for the user's next message.", mark: task_wake)
980
- end
981
-
982
- # The idle loop's sleep: the fallback tick, or less while reports or
983
- # attached-context wakes wait out the start grace.
984
- def idle_wait = @wakes.idle_wait(@poll_interval) { wake_state == :due || @inbound.context_wake_waiting? }
985
-
986
- # The wake budget is spent: the parent's UIs hear once that reports
987
- # wait for the next message.
988
- def budget_notice
989
- return unless @wakes.notice_budget!
990
-
991
- count = SessionInbox.find_ring_files(@session_dir).map { |f| SessionInbox.read_ring(f)&.dig(:child_id) }.uniq.size
992
- @engine.announce(type: :hook_notice, hook: "delegate", level: :info, between_turns: true,
993
- text: "#{count} delegate report#{"s" if count != 1} waiting; #{count == 1 ? "it joins" : "they join"} " \
994
- "your next message (#{@wakes.max} turn#{"s" if @wakes.max != 1} ran for reports in a row, #{ChildRing::MAX_WAKES_KEY})")
995
- end
996
-
997
704
  def max_iterations(no_interrupt) = IterationLimit.for(no_interrupt: no_interrupt)
998
705
 
999
- # The queued commands that may run now, in order, up to one whose
1000
- # after_file (D1) still waits in the inbox: it and those behind it stay
1001
- # queued.
1002
- # @return [Boolean] whether any command ran
1003
- def run_queued_commands
1004
- ran = false
1005
- # A signalled worker runs no more (a /continue would start a turn).
1006
- while !signalled? && (command = next_ready_command)
1007
- run_command(command)
1008
- ran = true
1009
- end
1010
- ran
1011
- end
1012
-
1013
- # Pops the first queued command if it may run now (its after_file is
1014
- # taken), else none: one behind it waits too, in arrival order (an idle
1015
- # /model Y that came just after the turn ended stays behind a /model X
1016
- # still waiting for a prompt sent before it). With the event log held,
1017
- # as the Bridge queues.
1018
- def next_ready_command
1019
- return nil if @command_queue.empty?
1020
-
1021
- @engine.synchronize_events do
1022
- commands = drain_commands
1023
- first = commands.first
1024
- ready = first && ready_command?(first) ? commands.shift : nil
1025
- commands.each { |command| @command_queue << command }
1026
- ready
1027
- end
1028
- end
1029
-
1030
- # A participant's file held for the Continue offer (#run_input_files)
1031
- # doesn't hold a command back: that command may be the owner's answer.
1032
- def ready_command?(command)
1033
- return true if command.after_file.nil?
1034
-
1035
- SessionInbox.find_new_input_files(@session_dir).none? do |path|
1036
- File.basename(path) <= command.after_file && !held_for_offer?(path)
1037
- end
1038
- end
1039
-
1040
- def drain_commands
1041
- commands = []
1042
- while (command = next_command)
1043
- commands << command
1044
- end
1045
- commands
1046
- end
1047
-
1048
- # A command a turn refuses (:refuse while it ran, S1) is answered busy:
1049
- # at the turn's iteration boundaries (mid_turn: all of them), and when
1050
- # it ends (the ones queued before its end event; later ones run next).
1051
- # A queued one (:queue) stays for after the turn, but a !cmd after a
1052
- # canceled or failed turn (D4): running it would close the rollback
1053
- # window the turn left, so it is dropped. With the event log held, so
1054
- # a command the Bridge queues meanwhile stays behind the ones kept, in
1055
- # arrival order. One that comes after the empty look is the next
1056
- # boundary's (or end's), as it would be.
1057
- def refuse_queued_commands(mid_turn: false)
1058
- return if @command_queue.empty?
1059
-
1060
- @engine.synchronize_events do
1061
- drain_commands.each do |command|
1062
- during = mid_turn || command.after_seq.to_i < @turn_end_seq
1063
- case (during ? turn_answer(command, ended: !mid_turn) : :keep)
1064
- when :refuse then announce_command(command, status: "busy", output: busy_output(command), changed: [])
1065
- when :drop then drop_command(waiting_for_turn_end(command), "turn #{@turn_end_type == :turn_failed ? "failed" : "canceled"}: " \
1066
- "#{command.line} not run; send it again")
1067
- else @command_queue << (during ? waiting_for_turn_end(command) : command)
1068
- end
1069
- end
1070
- end
1071
- end
1072
-
1073
- # What a turn does with +command+, queued while it ran: :refuse, :drop
1074
- # (D4, once it +ended+) or :keep. One queued idle just as the turn
1075
- # began (:loop) goes by its line's policy (a show form waits too).
1076
- def turn_answer(command, ended:)
1077
- policy = command.mid_turn
1078
- policy = @engine.command_registry.mid_turn(command.line) if policy == :loop
1079
- return :refuse if policy == :refuse
1080
- return :drop if ended && policy == :queue && shell_command?(command) &&
1081
- %i[turn_canceled turn_failed].include?(@turn_end_type)
1082
-
1083
- :keep
1084
- end
1085
-
1086
- # +command+, kept for after the turn. One queued idle just as the turn
1087
- # began (:loop) whose line waits for a turn's end (/model X, !cmd) is
1088
- # marked as one queued mid-turn: its command_queued (waits) tells the
1089
- # UIs now, and its command_ran says queued.
1090
- def waiting_for_turn_end(command)
1091
- return command unless command.mid_turn == :loop && @engine.command_registry.mid_turn(command.line) == :queue
1092
-
1093
- @engine.announce(type: :command_queued, **command.event_fields, waits: "turn_end")
1094
- command.with(mid_turn: :queue)
1095
- end
1096
-
1097
- def shell_command?(command) = @engine.command_registry.lookup(command.line)&.id == :shell
1098
-
1099
- def busy_output(command)
1100
- @engine.command_registry.lookup(command.line)&.id == :rollback ? ROLLBACK_BUSY_OUTPUT : BUSY_OUTPUT
1101
- end
1102
-
1103
- # +command+ won't run: its sender (a UI's queued bubble) is told.
1104
- def drop_command(command, output)
1105
- announce_command(command, status: "dropped", output: output, changed: [])
1106
- end
1107
-
1108
- # The worker leaves with commands still queued (a stop, a crash): each
1109
- # one's sender is told it won't run, so no UI shows it waiting for good.
1110
- def drop_queued_commands
1111
- return if @command_queue.nil? || @command_queue.empty? || @engine.nil?
1112
-
1113
- @engine.synchronize_events do
1114
- drain_commands.each { |command| drop_command(command, "dropped: the session's worker stopped before it ran") }
1115
- end
1116
- rescue StandardError => e
1117
- Log.warn(:worker, "drop_commands_failed", error: e.class.name, msg: e.message)
1118
- end
1119
-
1120
- def next_command
1121
- @command_queue.pop(true)
1122
- rescue ThreadError
1123
- nil
1124
- end
1125
-
1126
- def run_command(command)
1127
- awaiting = @continue_offer.awaiting?
1128
- result, shown = run_command_line(command)
1129
- resolved = @continue_offer.resolved?(awaiting, result)
1130
- @engine.synchronize_events do
1131
- @continue_offer.announce_resolved(result, command) if resolved
1132
- announce_command(command, status: result.status.to_s, output: result.output, changed: Array(result.changed),
1133
- confirm: result.confirm)
1134
- shown.each { |event| @engine.announce(event) }
1135
- end
1136
- save_or_log(:command) { save_session } unless Array(result.changed).empty?
1137
- user_input(command.client_id) if resolved
1138
- @continue_offer.after_command(result, resolved: resolved)
1139
- @continue_offer.run_continue_turn(command) if result.resume
1140
- end
1141
-
1142
- # @return [Array(SessionCommands::Result, Array<Hash>)] the result, and
1143
- # the cards and notices it showed, held: they follow its command_ran,
1144
- # as its output
1145
- def run_command_line(command)
1146
- @engine.holding_announcements do
1147
- command_result(command) do
1148
- @commands.run(command.line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
1149
- end
1150
- end
1151
- end
1152
-
1153
- # A shell line from a sender that may not run one (CommandIntake: a
1154
- # delegate's task, a schedule's prompt, a plugin's message): not run,
1155
- # its command_ran an error with the one refusal text.
1156
- def shell_refused(command)
1157
- Log.warn(:worker, "shell_line_refused", client_id: command.client_id)
1158
- SessionCommands::Result.new(status: :error, output: CommandIntake::REFUSED, changed: [])
1159
- end
1160
-
1161
- # Whether +command+ asks before a costly /thinking or /reasoning-history
1162
- # change (CacheConfirm): only a person at a web tab or a TUI sees the
1163
- # question; chi send, a delegate, a plugin and a card's action apply it.
1164
- def confirm?(command) = ClientId.interactive?(command.client_id) && !command.card
1165
-
1166
- # Whether +command+ is a parent agent's (chi answer's marker, which chi
1167
- # send and a parent's attach give a /continue yes too): held to
1168
- # guardrails.parent_answers (SessionCommands#continue_answer).
1169
- def as_parent?(command) = command.client_id.to_s == ClientId::CLI_ANSWER
1170
-
1171
- # Whether +command+ is a user's at a UI (a web tab, a chi TUI, a card's
1172
- # click), not a parent agent's: only such a line loosens
1173
- # /parent-answers. chi send, a delegate's follow-up, a plugin and an
1174
- # input with no client never do (ParentAnswersCommand).
1175
- def user_ui?(command) = ClientId.interactive?(command.client_id) && !as_parent?(command)
1176
-
1177
- # The block's Result for +command+; one that raised, or found no
1178
- # command for the line, is an error Result saying so.
1179
- # @return [SessionCommands::Result]
1180
- def command_result(command)
1181
- return shell_refused(command) if CommandIntake.refused?(command.line, command.client_id)
1182
-
1183
- yield || SessionCommands::Result.new(status: :error, output: "not a session command", changed: [])
1184
- rescue StandardError => e
1185
- SessionCommands::Result.new(status: :error, output: "#{command.line.split.first}: #{e.message}", changed: [])
1186
- end
1187
-
1188
- # A session command from the Bridge, called with the event log held:
1189
- # an anytime one starts now, any other is queued for the loop (and
1190
- # refused if a turn runs: #refuse_queued_commands). While a turn runs
1191
- # the line's policy decides (a show form like /model runs now); idle,
1192
- # only an always-anytime command (/help) runs beside the loop, so an
1193
- # idle /model X then /model run in order. A turn starting or ending
1194
- # right now may see the other side: the line is only shown early or
1195
- # run in order.
1196
- #
1197
- # A queued one (:queue) keeps arrival order with the prompts (D1): it
1198
- # runs once every input file written before it is taken (after_file,
1199
- # the newest one now; names compare, not clocks), so a prompt sent
1200
- # before it runs first and one sent after it runs after. One that came
1201
- # in an input file runs once that file is taken (+after_file+).
1202
- # @return [Symbol] the policy it applied (the Bridge marks an anytime
1203
- # one's command_queued, and a queued one's): :anytime, :queue or
1204
- # :refuse while a turn runs, :loop idle
1205
- def on_command(command, after_file: nil)
1206
- registry = @engine.command_registry
1207
- policy = if @engine.turn_running? then registry.mid_turn(command.line)
1208
- else registry.anytime?(command.line) ? :anytime : :loop
1209
- end
1210
- if policy == :anytime
1211
- start_anytime_command(command)
1212
- return policy
1213
- end
1214
-
1215
- after_file ||= newest_input_file if policy == :queue
1216
- # The count says which turn ends came before it.
1217
- @command_queue << command.with(after_seq: @engine.event_count, mid_turn: policy, after_file: after_file)
1218
- @waker.wake
1219
- policy
1220
- end
1221
-
1222
- # @return [String, nil] the newest input file waiting (its basename)
1223
- def newest_input_file
1224
- SessionInbox.find_new_input_files(@session_dir).map { |path| File.basename(path) }.max
1225
- end
1226
-
1227
- # An anytime command (/help, a plugin's /btw; D8) runs now, on its own
1228
- # thread, never queued behind a turn: it is never busy. The Bridge calls
1229
- # this with the event log held, so its command_ran (announced when it
1230
- # finishes) comes after its command_queued. The cards it shows go out at
1231
- # once (btw's "thinking…" card), after its command_queued, which the
1232
- # UIs draw its line at (Engine#running_anytime). Its handler reads
1233
- # copies (ctx.messages) and shows things through ctx only. One that
1234
- # changed the session (/title, /recap off: fields no turn writes) is
1235
- # saved here, as a queued one is (#run_command), through Session#save,
1236
- # which takes the session's lock and writes a running turn's checkpoint
1237
- # (as WorkerSignals' save off the turn thread does), so the turn's own
1238
- # saves keep it.
1239
- def start_anytime_command(command)
1240
- @engine.spawn_anytime do
1241
- result = command_result(command) { @engine.running_anytime { @commands.run(command.line, confirm: confirm?(command)) } }
1242
- # Saved before its command_ran: a client that reads the file on the reply finds it.
1243
- save_or_log(:command) { save_session } unless Array(result.changed).empty?
1244
- announce_command(command, status: result.status.to_s, output: result.output, changed: Array(result.changed),
1245
- anytime: true, confirm: result.confirm)
1246
- # It may have left a note (/objectives): an idle loop takes it now, not
1247
- # at the fallback tick. Harmless otherwise: one more pass.
1248
- @waker.wake
1249
- rescue StandardError => e
1250
- Log.warn(:worker, "anytime_command_failed", line: command.line, error: e.class.name, msg: e.message)
1251
- end
1252
- end
1253
-
1254
- # @param anytime [Boolean] an anytime command's: its line was shown at
1255
- # its command_queued already
1256
- # @param confirm [CacheConfirm::Confirm, nil] the change asks first: the
1257
- # line that applies it (the TUI's prefill, the web's Apply button)
1258
- def announce_command(command, status:, output:, changed:, anytime: false, confirm: nil)
1259
- TurnCheckpoint.record_command_outcome(@session_dir, command.enqueued_id, status: status)
1260
- # Any bytes (a !cmd's): one that JSON can't take would end every stream
1261
- # that reaches this event, for as long as the ring holds it.
1262
- text = output.to_s.scrub("?")
1263
- event = { type: :command_ran, **command.event_fields, status: status, output: command_output_shown(text),
1264
- changed: changed.map(&:to_s), model_name: @engine.effective_model_name }
1265
- event[:anytime] = true if anytime
1266
- # The session's title after /title (nil: cleared), for the TUIs' row.
1267
- event[:title] = @engine.session&.title if changed.include?(:title)
1268
- # Its line was shown at its command_queued (waits: turn_end).
1269
- event[:queued] = true if command.waits_for_turn_end?
1270
- # The chips the command moved (SessionSetting#changed_by): what the next
1271
- # turn runs under now (/llm-context, /thinking, /reasoning-history,
1272
- # /toolkit, and /model for the model's).
1273
- SessionSetting::ALL.each { |setting| event[setting.key] = setting.summary(@engine) if setting.changed_by?(changed) }
1274
- event[:confirm] = confirm.to_h if confirm
1275
- event[:output_truncated] = true if text.length > COMMAND_OUTPUT_LIMIT
1276
- @engine.announce(event)
1277
- end
1278
-
1279
- # +text+ as its :command_ran carries it: over the limit, its head to a
1280
- # line's end (one long line is cut where it must be), then a line that
1281
- # says so: every UI prints this text as it is.
1282
- def command_output_shown(text)
1283
- return text if text.length <= COMMAND_OUTPUT_LIMIT
1284
-
1285
- kept = text[0, COMMAND_OUTPUT_LIMIT]
1286
- line_end = kept.rindex("\n")
1287
- kept = kept[0, line_end] if line_end && line_end > COMMAND_OUTPUT_LIMIT / 2
1288
- "#{kept}\n[cut: #{kept.length} of #{text.length} chars: a command's output stops here]"
1289
- end
1290
-
1291
706
  # One Engine turn, the same for a prompt, a reminder and a continue:
1292
707
  # the session shows as running to readers of the file (the web's
1293
708
  # session list; the Engine resets it to idle when it ends), commands
@@ -1357,102 +772,6 @@ module Samagotchi
1357
772
  forward_fresh_verdicts(verdicts_before)
1358
773
  end
1359
774
 
1360
- # A Verify fresh child's verdicts this turn recorded go to its parent
1361
- # (VerifyFresh.forward), after the save: the parent's card shows them.
1362
- # A fresh child never rings (ChildRing.ring): nothing enters the
1363
- # parent's conversation.
1364
- def forward_fresh_verdicts(before)
1365
- return unless @session.verify_fresh
1366
-
1367
- added = @session.verdicts.drop(before)
1368
- VerifyFresh.forward(@session, added, state_dir: @state_dir) unless added.empty?
1369
- end
1370
-
1371
- # The parent's side, between turns: the verdicts its Verify fresh
1372
- # children forwarded join the session's (saved, then their files go)
1373
- # and the UIs hear each (:verdict_recorded).
1374
- def absorb_fresh_verdicts
1375
- added, files = VerifyFresh.take(@session, @session_dir)
1376
- return if files.empty?
1377
-
1378
- return unless save_or_log(:fresh_verdicts) { save_session }
1379
-
1380
- FileUtils.rm_f(files)
1381
- added.each { |record| @engine.announce(type: :verdict_recorded, verdict: record) }
1382
- rescue StandardError => e
1383
- Log.warn(:worker, "fresh_verdicts_failed", error: e.class.name, msg: e.message)
1384
- end
1385
-
1386
- # The delegate reports this turn took: a kept turn moves the cursors on
1387
- # and deletes their rings; a rolled-back one leaves the rings for the
1388
- # next turn. Once either way: the model reads a report in the
1389
- # conversation, or the next turn brings it (unless a later !rollback
1390
- # erases a kept turn, which drops what it read).
1391
- def settle_child_reports(rolled_back:)
1392
- rolled_back ? @child_reports.release : @child_reports.commit
1393
- end
1394
-
1395
- # Whether +error+ ended the turn without its loop's conversation: a
1396
- # failure the loops didn't mark (LLM::FailedTurn), one past their end
1397
- # (the Engine's own end of the turn, say). The Engine kept the turn's
1398
- # start only, so the reports its loop merged are not in the
1399
- # conversation: their rings stay for the next turn, even when the turn
1400
- # itself stays (a reminder or continue turn). Not one raised after the
1401
- # turn ended (the Engine's post-turn work): the turn was kept as it
1402
- # ended, completed or canceled, the reports in it (a turn TurnFlow
1403
- # takes back is a restore, above).
1404
- def merges_lost?(error)
1405
- return false if error.nil? || error.is_a?(LLM::FailedTurn)
1406
-
1407
- !KEPT_TURN_OUTCOMES.include?(@session.last_turn&.outcome)
1408
- end
1409
-
1410
- # The Engine's turn endings that keep the turn's conversation (#merges_lost?).
1411
- KEPT_TURN_OUTCOMES = %w[completed canceled].freeze
1412
-
1413
- # A delegate child's turn that was its parent's (#reports_to_parent?)
1414
- # rings the parent, after the save: the parent reads a settled child.
1415
- # A question it rang about that still waits makes the next turn ring
1416
- # too, whoever starts it (the user answering Continue on the web).
1417
- def ring_parent_after_turn
1418
- ChildRing.ring(@session, why: "turn_end", state_dir: @state_dir) if @reporting_turn
1419
- @owes_parent = @asked_parent && !@session.pending_question.nil?
1420
- @asked_parent = false
1421
- @reporting_turn = false
1422
- end
1423
-
1424
- # Whether the turn starting now is a delegate child's parent's: its
1425
- # task (the initial prompt), a follow-up, a continue the parent
1426
- # answered, a reminder, anything but a human typing into the child
1427
- # (ClientId.human?), and any turn after a question the parent
1428
- # was rung about.
1429
- def reports_to_parent?(origin)
1430
- return false unless @session.delegate?
1431
-
1432
- @initial_turn || @owes_parent || !ClientId.human?(origin.client_id)
1433
- end
1434
-
1435
- # The Engine published a question (after the question desk saved it).
1436
- # In a turn that reports to the parent, the model's own question, the
1437
- # step-limit continue and a hook's question ring it (the parent reports
1438
- # or relays a hook's: ChildReports). Approvals don't: the relay takes
1439
- # them while the parent waits. Nor does a card relayed from this
1440
- # session's own child (relay set): the hop is the parent's wait.
1441
- def ring_question(event)
1442
- return unless @reporting_turn
1443
-
1444
- pending = event[:pending_question] || {}
1445
- kind = pending[:kind].to_s
1446
- return unless RINGING_KINDS.include?(kind)
1447
- return if pending[:relay]
1448
-
1449
- ChildRing.ring(@session, why: "question", state_dir: @state_dir)
1450
- @asked_parent = true
1451
- end
1452
-
1453
- # The kinds of question that ring a delegate child's parent (#ring_question).
1454
- RINGING_KINDS = ["", ContinueOffer::KIND, "hook"].freeze
1455
-
1456
775
  # WorkerInbound.save_or_log: a failed save between turns is logged.
1457
776
  def save_or_log(at, &) = WorkerInbound.save_or_log(at, &)
1458
777
 
@@ -1617,305 +936,8 @@ module Samagotchi
1617
936
  end
1618
937
  end
1619
938
 
1620
- # How long a scratch worker waits for its terminal's first stream
1621
- # (AttachLauncher attaches within BRIDGE_WAIT of the spawn).
1622
- SCRATCH_JOIN_GRACE = 30
1623
-
1624
- # How long a scratch worker's terminal may have no stream open, after
1625
- # it had one, before it counts as gone: twice the attached terminal's
1626
- # whole reconnect ladder (TerminalUI::LocalLink#reconnect_delays), so
1627
- # a reconnect gap (a dropped stream, a slow worker) never reads as a
1628
- # terminal that left.
1629
- SCRATCH_GONE_AFTER = 2 * BridgeClient::EventStream::REDISCOVER_DELAYS.sum
1630
-
1631
- # Whether this is a `chi scratch` session's worker whose terminal is
1632
- # gone: no terminal stream (a tui: client id's) open for
1633
- # SCRATCH_GONE_AFTER, after a stream was (a killed TUI's closes as its
1634
- # writer reads the hang-up), or none came within SCRATCH_JOIN_GRACE.
1635
- # Any other stream (a web tab's, which chi web refuses for a scratch
1636
- # session anyway) never keeps it. Its terminal deletes it on every way
1637
- # out it sees; this is for the ones it doesn't (kill -9, a closed
1638
- # terminal window).
1639
- def scratch_unattended?
1640
- return false unless @session&.scratch && @bridge
1641
-
1642
- if @bridge.open_streams_of(ClientId::TUI_PREFIX).positive?
1643
- @unattended_since = nil
1644
- return false
1645
- end
1646
- return monotonic_now - @started_at >= SCRATCH_JOIN_GRACE unless @bridge.streams_served.positive?
1647
-
1648
- # Set by the first look (the scratch watch or the idle pass) that
1649
- # finds no stream; a stream back resets it above.
1650
- @unattended_since ||= monotonic_now
1651
- monotonic_now - @unattended_since >= SCRATCH_GONE_AFTER
1652
- end
1653
-
1654
939
  def monotonic_now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1655
940
 
1656
- # #leave_idle for a scratch worker its terminal left: checked again with
1657
- # the event log held, then the intake closes. The session is deleted
1658
- # once the lock is free (WorkerBoot.run_session_loop: :scratch_left).
1659
- # @return [Boolean] false when a client came back since
1660
- def leave_scratch
1661
- stop_bridge_after do
1662
- @engine.synchronize_events do
1663
- # A turn still running is the scratch watch's to cancel first.
1664
- next false unless scratch_unattended? && !@engine.turn_running?
1665
-
1666
- @bridge&.close_intake
1667
- @engine.stop_idle(join: false)
1668
- Log.info(:worker, "scratch_left", served: @bridge.streams_served)
1669
- true
1670
- end
1671
- end
1672
- end
1673
-
1674
- # Check again with the event log held, which the Bridge holds while it
1675
- # queues a POST /turn, then close the Bridge's intake so no client can
1676
- # queue one after the check, and stop the idle jobs (reminder callback,
1677
- # recap). The Bridge stops after the log is let go (#stop_bridge_after).
1678
- # A client connecting from here on finds no worker: `chi --attach` fails
1679
- # and the web stream answers 503 (a small window, left as is).
1680
- # @return [Boolean] false when something came in since #due?
1681
- def leave_idle
1682
- stop_bridge_after do
1683
- @engine.synchronize_events do
1684
- next false unless @idle_exit.due?
1685
-
1686
- @bridge&.close_intake
1687
- # Not joined: a recap tick's emit waits for the event log held here.
1688
- @engine.stop_idle(join: false)
1689
- log_idle_exit
1690
- true
1691
- end
1692
- end
1693
- end
1694
-
1695
- # The Bridge stops once the block (which closed its intake with the
1696
- # event log held) answers true, outside the log: Bridge#stop waits for
1697
- # the requests it is answering, and one waiting on the log would hold
1698
- # it for the whole grace before being killed. The owner lock says it is
1699
- # leaving first, so a client that finds no Bridge from here on waits
1700
- # for the lock (OwnerLock.await_release) instead of giving up.
1701
- # @return [Boolean] what the block answered
1702
- def stop_bridge_after
1703
- leaving = yield
1704
- if leaving
1705
- mark_leaving
1706
- @bridge&.stop
1707
- end
1708
- leaving
1709
- end
1710
-
1711
- # How long the lock stays held after the Bridge: the recap on leave's
1712
- # timeout (#left), none for a restart (#left writes none). A delete
1713
- # writes none either, but the bound only has to be an upper one.
1714
- # Once: the teardown's (after #stop_bridge_after's) keeps the first one.
1715
- # @param wait [Numeric, nil] nil: as above
1716
- def mark_leaving(wait: nil)
1717
- return if @marked_leaving
1718
-
1719
- @marked_leaving = true
1720
- wait ||= @exit_claim.restart? ? 0 : @engine.recap_timeout.to_f
1721
- @owner_lock&.mark_leaving(wait: wait)
1722
- rescue StandardError => e
1723
- Log.warn(:worker, "mark_leaving_failed", error: e.class.name, msg: e.message)
1724
- end
1725
-
1726
- # Bridge POST /exit, on a Bridge thread with the event log held.
1727
- # +delete+: the session is deleted after (/exit --delete), so no recap.
1728
- # +restart+: a new worker takes over (on the newest chi installed), so
1729
- # WorkerIdleExit#hold_for_restart's rules, and no recap or discard.
1730
- # +stop+: the exit ask's "stop them and exit" — stop every hold the user
1731
- # can stop before leaving; a hold they can't stop refuses the request
1732
- # (WorkerIdleExit#request_hold checks again, so one that appeared
1733
- # since the ask is refused too).
1734
- # +ask+: this client asks the user what to do with what still runs, so the
1735
- # delegate children are part of the list. An exit that deletes the
1736
- # session, or one a UI can't ask about (/archive), leaves them out:
1737
- # they never hold the worker up on their own.
1738
- # @return [WorkerIdleExit::Hold, nil] what keeps the worker up (for
1739
- # :background_tasks, the watched tasks still running), nil when it
1740
- # will leave
1741
- def exit_request(client_id, delete: false, restart: false, stop: false, ask: true)
1742
- # The Bridge serves before the idle-exit policy exists.
1743
- return WorkerIdleExit::Hold.new(reason: :starting) unless @idle_exit
1744
-
1745
- kind = if restart then :restart
1746
- elsif delete then :delete
1747
- else :exit
1748
- end
1749
- # One exit at a time, and the first one taken decides how the worker
1750
- # leaves (a later stop-all can't turn a restart, whose reminders go to
1751
- # the next worker, into a plain exit): claimed before the slow
1752
- # stop-all, so a request of another kind meanwhile is refused (409),
1753
- # not told it went through. Held at the leave, it is forgotten and the
1754
- # next request counts again.
1755
- refused = @exit_claim.claim(kind)
1756
- return refused.value if refused
1757
-
1758
- hold = exit_hold(client_id, kind: kind, stop: stop, ask: ask)
1759
- if hold
1760
- @exit_claim.forget
1761
- return hold
1762
- end
1763
-
1764
- @exit_claim.accept(by: client_id, stop: stop)
1765
- @waker.wake
1766
- nil
1767
- rescue StandardError
1768
- # A look or a stop that raised lets the claim go (the Bridge answers 500).
1769
- @exit_claim.release
1770
- raise
1771
- end
1772
-
1773
- # What keeps the worker up for this request, nil when nothing does; a
1774
- # stop request stops what the user can stop first (#exit_request).
1775
- # @return [WorkerIdleExit::Hold, nil]
1776
- def exit_hold(client_id, kind:, stop:, ask:)
1777
- if kind == :restart
1778
- # A scratch session's worker ends with its terminal: never restarted.
1779
- return WorkerIdleExit::Hold.new(reason: :scratch) if @session.scratch
1780
-
1781
- hold = @idle_exit.hold_for_restart
1782
- return hold && WorkerIdleExit::Hold.new(reason: hold)
1783
- end
1784
-
1785
- # /exit names the tasks it waits for (D3), from the one look that found them.
1786
- # The ask covers the delegate children too, but only for a plain /exit: an
1787
- # exit that deletes the session, or one a UI won't ask about, ignores them.
1788
- hold = @idle_exit.request_hold(requester: client_id, hint: TASK_STOP_HINT, ask: ask && kind != :delete)
1789
- return nil unless hold
1790
- # A hold the user can't stop here: no ask, today's refusal.
1791
- return hold unless hold.ask?
1792
- # The ask's 409: the list, for the terminal to ask with.
1793
- return hold unless stop
1794
-
1795
- @exit_claim.stopped!(@hold_stop.stop_all)
1796
- # An unstoppable hold may have arrived while stopping (a child stopped
1797
- # here is no longer counted).
1798
- @idle_exit.request_hold(requester: client_id, hint: TASK_STOP_HINT)
1799
- end
1800
-
1801
- # #leave_idle for an exit a client asked for: check again with the event
1802
- # log held (a prompt may have come in since), then close the Bridge's
1803
- # intake and stop the idle jobs (the Bridge stops after the log). Other clients' streams no longer hold: the asker's
1804
- # may not have closed yet, and a UI joining now finds the worker gone
1805
- # (:stream_closed), the window #leave_idle has too.
1806
- # @return [Symbol, false] how it leaves (:restart or :exit_requested,
1807
- # decided under the lock), false when something came in since the request
1808
- def leave_on_request
1809
- stop_bridge_after do
1810
- @engine.synchronize_events do
1811
- # One read: the kind and the asker of the same exit.
1812
- taken = @exit_claim.taken
1813
- restart = taken&.restart?
1814
- hold = if restart
1815
- @idle_exit.hold_for_restart
1816
- else
1817
- @idle_exit.hold_for_request(requester: taken&.by, streams: false)
1818
- end
1819
- if hold
1820
- @exit_claim.forget
1821
- Log.info(:worker, "exit_held", reason: hold)
1822
- next false
1823
- end
1824
- next false if restart && !carry_reminders
1825
-
1826
- @bridge&.close_intake
1827
- # Not joined: a recap tick's emit waits for the event log held here.
1828
- @engine.stop_idle(join: false)
1829
- Log.info(:worker, restart ? "restart_requested" : "exit_requested", by: taken&.by || "a client")
1830
- restart ? :restart : :exit_requested
1831
- end
1832
- end
1833
- end
1834
-
1835
- # A restart hands the reminders to the next worker (ReminderCarry), while
1836
- # the event log is held: no turn can register or fire one from here. A
1837
- # write that fails keeps this worker up with them rather than losing them.
1838
- # A session stopped meanwhile drops them (WorkerBoot.run_session_loop
1839
- # then starts no successor): nothing is written.
1840
- # @return [Boolean] false when the write failed
1841
- def carry_reminders
1842
- if stopped_on_disk?
1843
- ReminderCarry.remove(@session_dir)
1844
- else
1845
- ReminderCarry.write(@session_dir, session_id: @session_id, store: @engine.reminder_store)
1846
- end
1847
- true
1848
- rescue StandardError => e
1849
- @exit_claim.forget
1850
- Log.warn(:worker, "reminders_carry_failed", error: e.class.name, msg: e.message)
1851
- false
1852
- end
1853
-
1854
- # The reminders a restart handed over (#carry_reminders), read and
1855
- # deleted; a stopped session drops them.
1856
- # @return [Array<Hash>, nil] ReminderStore#export's entries
1857
- def take_carried_reminders
1858
- ReminderCarry.take(@session_dir, session_id: @session_id, stopped: stopped_on_disk?)
1859
- rescue StandardError => e
1860
- Log.warn(:worker, "reminders_carry_take_failed", error: e.class.name, msg: e.message)
1861
- nil
1862
- end
1863
-
1864
- # Into the new Engine's store, before the idle scheduler starts polling it.
1865
- def restore_carried_reminders(entries)
1866
- return unless entries
1867
-
1868
- names = @engine.reminder_store.restore(entries)
1869
- Log.info(:worker, "reminders_carried", count: names.size)
1870
- rescue StandardError => e
1871
- Log.warn(:worker, "reminders_carry_restore_failed", error: e.class.name, msg: e.message)
1872
- end
1873
-
1874
- # @return [Symbol] +result+, with #discard? decided and, for a session
1875
- # kept, its recap written: the Bridge is closed and the idle jobs are
1876
- # stopped by now, and nothing waits on this (the TUI has detached). A
1877
- # `chi send` meanwhile is picked up after the exit (WorkerBoot.run_session_loop);
1878
- # a `chi --attach` finds no Bridge until then.
1879
- # A restart keeps even an empty session (a new worker takes it over at
1880
- # once) and leaves the recap to the conversation's next real pause.
1881
- def left(result)
1882
- deleting = (result == :exit_requested && @exit_claim.deletes?) || result == :scratch_left
1883
- # The attached context goes with this process: a change that landed after
1884
- # the leaving pass looked at it has no later pass to note it, so note it
1885
- # here (no wake turn: the worker is on its way out). Not into a session
1886
- # /exit --delete deletes next: its save could land after the delete and
1887
- # write the session back.
1888
- absorb_context unless deleting
1889
- # The watch goes with this process: a task that finished since the
1890
- # last look (nothing held the exit for it: queue, a note-only task,
1891
- # /exit) is a plain note for the next turn, not lost. Not into a
1892
- # session /exit --delete deletes next: its save could land after the
1893
- # delete and write the session back.
1894
- @task_wakes.absorb unless deleting
1895
- return result if %i[restart scratch_left].include?(result)
1896
-
1897
- @discard = empty_session?
1898
- write_recap_on_leave unless @discard || deleting
1899
- result
1900
- end
1901
-
1902
- def write_recap_on_leave
1903
- written = @engine.write_recap_now
1904
- Log.info(:worker, "recap_on_leave") if written
1905
- rescue StandardError => e
1906
- Log.warn(:worker, "recap_on_leave_failed", error: e.class.name, msg: e.message)
1907
- end
1908
-
1909
- # Memory used before any turn saved it lives only in the Engine.
1910
- def empty_session?
1911
- SessionManager.discardable?(@session_id, state_dir: @state_dir, default_model: @default_model,
1912
- used_memory_names: @engine.used_memory_names)
1913
- end
1914
-
1915
- def log_idle_exit
1916
- Log.info(:worker, "idle_exit", idle_s: @idle_exit.idle_seconds.round)
1917
- end
1918
-
1919
941
  # The owner's input (ClientId.owner?) un-archives the session; a
1920
942
  # delegate's, a plugin's, a reminder's or a participant's doesn't.
1921
943
  # It also resets the wakes (budget and pause); input typed in the web or
@@ -1940,68 +962,5 @@ module Samagotchi
1940
962
  def save_session
1941
963
  @session.save(state_dir: @state_dir)
1942
964
  end
1943
-
1944
- def signalled? = !@signals.signal.nil?
1945
-
1946
- # @return [Symbol] :stopped when the session was stopped too (chi
1947
- # sessions stop TERMs its worker), else :signal
1948
- def signal_leave
1949
- Session.stopped_marker?(@session_id, state_dir: @state_dir) ? :stopped : :signal
1950
- end
1951
-
1952
- # A signal (WorkerSignals#fire), on a thread of its own: the loop wakes
1953
- # (an idle worker leaves at once), the running turn is canceled as a
1954
- # Stop (again every SIGNAL_RETRY, until the loop has left), and when
1955
- # the grace runs out first, #signal_grace_expired. A turn that has
1956
- # ended and runs its after_turn hooks (which store the answer's display
1957
- # and refs) is no longer canceled, and gets until SIGNAL_HARD_EXIT
1958
- # past the grace, the worker's own end of the turn (its saves, after
1959
- # the turn stopped running) too: the loop leaves next. A grace that runs out before the loop started waits
1960
- # for it (the loop's first look leaves). A signal after the loop left
1961
- # (the teardown, the caller's last steps) only brings the hard exit.
1962
- def signalled(name, count)
1963
- Log.info(:worker, "signal", signal: name, count: count, turn_running: @engine&.turn_running? || false)
1964
- return signal_hard_exit if @left_loop
1965
-
1966
- @waker.wake
1967
- short = count > 1 || Session.stopped_marker?(@session_id, state_dir: @state_dir)
1968
- now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1969
- deadline = now + (short ? @signal_short_grace : @signal_grace)
1970
- hooks_deadline = deadline + @signal_hard_exit
1971
- ended = false
1972
- until @left_loop
1973
- running = @engine&.turn_running?
1974
- ended ||= running && @turn_ending
1975
- @engine.cancel_current_turn!(:signal) if running && !ended
1976
- break if @loop_started && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= (ended ? hooks_deadline : deadline)
1977
-
1978
- sleep(SIGNAL_RETRY)
1979
- end
1980
- signal_grace_expired(name) unless @left_loop
1981
- rescue StandardError => e
1982
- Log.warn(:worker, "signal_failed", signal: name, error: e.class.name, msg: e.message)
1983
- end
1984
-
1985
- # The process ends SIGNAL_HARD_EXIT from now at the latest.
1986
- def signal_hard_exit
1987
- sleep(@signal_hard_exit)
1988
- @signals.hard_exit
1989
- end
1990
-
1991
- # The turn didn't end in time (a tool that ignores the cancel, slow
1992
- # after_turn hooks): the session is saved as it is now (a turn that has
1993
- # ended: with it), and the signal raised in the loop's thread, so
1994
- # Worker#run's teardown and the lock's release still run. The process
1995
- # ends SIGNAL_HARD_EXIT later at the latest. Once, whatever the signals.
1996
- def signal_grace_expired(name)
1997
- expired = @signal_mutex.synchronize { !@grace_expired && !@left_loop && (@grace_expired = true) }
1998
- return unless expired
1999
-
2000
- Log.warn(:worker, "signal_grace_expired", signal: name, turn_running: @engine&.turn_running? || false)
2001
- save_or_log(:signal) { save_session }
2002
- # Not once the loop has left (it may have, during the save).
2003
- @signal_mutex.synchronize { @run_thread&.raise(SignalException.new(name)) unless @left_loop }
2004
- signal_hard_exit
2005
- end
2006
965
  end
2007
966
  end