samagotchi 0.172.0 → 0.173.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 (120) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +2 -1
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +20 -7
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +67 -9
  10. data/docs/internals/remote-sessions.md +1 -1
  11. data/docs/internals/web-frontend.md +44 -15
  12. data/docs/plugins.md +3 -1
  13. data/docs/sessions.md +2 -2
  14. data/docs/testing.md +43 -3
  15. data/lib/samagotchi/bridge.rb +3 -2
  16. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  17. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  19. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  20. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  21. data/lib/samagotchi/engine/participants.rb +2 -2
  22. data/lib/samagotchi/engine.rb +0 -1
  23. data/lib/samagotchi/file_ref.rb +3 -5
  24. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  25. data/lib/samagotchi/memory_usage.rb +2 -1
  26. data/lib/samagotchi/message_parts.rb +5 -3
  27. data/lib/samagotchi/objectives_backing.rb +6 -10
  28. data/lib/samagotchi/parent_report.rb +1 -1
  29. data/lib/samagotchi/participant_prompts.rb +101 -0
  30. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  31. data/lib/samagotchi/project_env.rb +7 -5
  32. data/lib/samagotchi/prompt_history.rb +2 -2
  33. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  34. data/lib/samagotchi/send_command.rb +4 -4
  35. data/lib/samagotchi/session_command_catalog.rb +210 -0
  36. data/lib/samagotchi/session_commands.rb +12 -183
  37. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  38. data/lib/samagotchi/session_manager.rb +2 -1
  39. data/lib/samagotchi/session_stores.rb +2 -0
  40. data/lib/samagotchi/spawn_env.rb +75 -0
  41. data/lib/samagotchi/task_files.rb +51 -0
  42. data/lib/samagotchi/task_transcript.rb +67 -0
  43. data/lib/samagotchi/task_watch.rb +8 -6
  44. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  45. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  46. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -3
  47. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  48. data/lib/samagotchi/testing/boundary.rb +5 -0
  49. data/lib/samagotchi/tool_activity.rb +63 -79
  50. data/lib/samagotchi/tool_names.rb +179 -0
  51. data/lib/samagotchi/tool_view.rb +3 -5
  52. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  53. data/lib/samagotchi/tools/builtins.rb +1 -1
  54. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  55. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  56. data/lib/samagotchi/tools/context_read.rb +2 -1
  57. data/lib/samagotchi/tools/delegate.rb +2 -1
  58. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  59. data/lib/samagotchi/tools/edit.rb +2 -1
  60. data/lib/samagotchi/tools/execute.rb +22 -28
  61. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  62. data/lib/samagotchi/tools/leftovers.rb +8 -4
  63. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  64. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  65. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  66. data/lib/samagotchi/tools/memory.rb +3 -2
  67. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  68. data/lib/samagotchi/tools/read.rb +2 -1
  69. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  70. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  71. data/lib/samagotchi/tools/send_note.rb +2 -1
  72. data/lib/samagotchi/tools/task_create.rb +2 -1
  73. data/lib/samagotchi/tools/task_get.rb +2 -1
  74. data/lib/samagotchi/tools/task_list.rb +2 -1
  75. data/lib/samagotchi/tools/task_runtime.rb +34 -154
  76. data/lib/samagotchi/tools/task_stop.rb +2 -1
  77. data/lib/samagotchi/tools/task_wait.rb +3 -2
  78. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  79. data/lib/samagotchi/tools/write.rb +2 -1
  80. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  81. data/lib/samagotchi/version.rb +1 -1
  82. data/lib/samagotchi/web/app.rb +38 -36
  83. data/lib/samagotchi/web/message_display.rb +1 -7
  84. data/lib/samagotchi/web/participant_access.rb +12 -4
  85. data/lib/samagotchi/web/participant_history.rb +68 -0
  86. data/lib/samagotchi/web/participant_images.rb +2 -1
  87. data/lib/samagotchi/web/participant_show.rb +5 -5
  88. data/lib/samagotchi/web/participants_admin.rb +1 -1
  89. data/lib/samagotchi/web/public/app.js +13 -10
  90. data/lib/samagotchi/web/public/card_kinds.js +51 -0
  91. data/lib/samagotchi/web/public/card_registry.js +248 -0
  92. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  93. data/lib/samagotchi/web/public/cards_place.js +21 -4
  94. data/lib/samagotchi/web/public/history_shape.js +1 -2
  95. data/lib/samagotchi/web/public/participant_history.js +27 -0
  96. data/lib/samagotchi/web/public/question_cards.js +16 -15
  97. data/lib/samagotchi/web/public/reload_check.js +90 -72
  98. data/lib/samagotchi/web/public/session_sync.js +4 -2
  99. data/lib/samagotchi/web/public/session_view.js +6 -1
  100. data/lib/samagotchi/web/public/stage_asking.js +18 -13
  101. data/lib/samagotchi/web/public/stage_place.js +144 -0
  102. data/lib/samagotchi/web/public/stage_probe.js +64 -0
  103. data/lib/samagotchi/web/public/stage_view.js +52 -104
  104. data/lib/samagotchi/web/public/stage_waiting.js +28 -17
  105. data/lib/samagotchi/web/public/task_stop.js +1 -1
  106. data/lib/samagotchi/web/push_routes.rb +1 -1
  107. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  108. data/lib/samagotchi/web/request_body.rb +72 -0
  109. data/lib/samagotchi/web/server.rb +70 -0
  110. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  111. data/lib/samagotchi/web/session_control.rb +21 -15
  112. data/lib/samagotchi/web/session_create.rb +2 -1
  113. data/lib/samagotchi/web/session_show.rb +8 -8
  114. data/lib/samagotchi/web/viewer.rb +7 -2
  115. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  116. data/lib/samagotchi/worker.rb +49 -182
  117. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  118. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  119. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  120. metadata +16 -1
@@ -44,8 +44,8 @@ require_relative "context_candidates"
44
44
  require_relative "context_poller"
45
45
  require_relative "task_watch"
46
46
  require_relative "tools/task_runtime"
47
- require_relative "participants"
48
- require_relative "participant_name"
47
+ require_relative "worker_participant_gate"
48
+ require_relative "worker_exit_claim"
49
49
 
50
50
  module Samagotchi
51
51
  # The loop of a background session worker, once it owns the session (see
@@ -151,13 +151,8 @@ module Samagotchi
151
151
  @poll_interval = poll_interval || FALLBACK_TICK_SECONDS
152
152
  @waker = Waker.new
153
153
  @command_queue = Thread::Queue.new
154
- # The client_id of a client that asked the worker to exit (POST /exit).
155
- @exit_requested = nil
156
- @exit_requested_by = nil
157
154
  # Set as it leaves: nothing happened in the session (#discard?).
158
155
  @discard = false
159
- # The exit asked for is a restart (POST /exit restart: true).
160
- @exit_restart = false
161
156
  # The lines the running turn's drain merged ([prompt, TurnOrigin]), for a
162
157
  # failed prompt turn to hand back; reset as each turn begins.
163
158
  @merged_this_turn = []
@@ -176,10 +171,10 @@ module Samagotchi
176
171
  @loop_started = false
177
172
  @left_loop = false
178
173
  @signal_mutex = Mutex.new
179
- # The exit being taken or taken (:exit, :delete, :restart), claimed
180
- # under its own lock before #exit_request's slow stop-all (#claim_exit).
181
- @exit_claim = nil
182
- @exit_claim_mutex = Mutex.new
174
+ # The exit being taken or taken (POST /exit: :exit, :delete, :restart,
175
+ # who asked), claimed under its own lock before #exit_request's slow
176
+ # stop-all, and what that stop-all stopped.
177
+ @exit_claim = WorkerExitClaim.new
183
178
  @grace_expired = false
184
179
  # The running turn has ended (its end event) and its after_turn hooks
185
180
  # run: a signal's grace waits for them (#signalled).
@@ -232,9 +227,13 @@ module Samagotchi
232
227
  end
233
228
 
234
229
  # The step that stops what the user can stop (the reminders, the watched
235
- # tasks and the delegate children the exit ask lists), and what the last
236
- # stop-all exit stopped. /exit's 2 uses it; the web's Stop will too.
237
- attr_reader :hold_stop, :stopped_holds
230
+ # tasks and the delegate children the exit ask lists). /exit's 2 uses
231
+ # it; the web's Stop will too.
232
+ attr_reader :hold_stop
233
+
234
+ # @return [HoldStop::Stopped, nil] the last stop-all's list (the Bridge's
235
+ # exit_stopped)
236
+ def stopped_holds = @exit_claim.stopped
238
237
 
239
238
  private
240
239
 
@@ -291,9 +290,14 @@ module Samagotchi
291
290
  # stream gets the session's history and status in its snapshot, not
292
291
  # an empty session until the first turn.
293
292
  @engine.session = @session
293
+ # May this participant act (loop thread only): a turn as it starts,
294
+ # the drain, the mid-turn stop, the Continue.
295
+ @participant_gate = WorkerParticipantGate.new(engine: @engine, session: @session, session_id: @session_id,
296
+ state_dir: @state_dir, session_dir: @session_dir,
297
+ hook: Engine::PARTICIPANTS_HOOK)
294
298
  # Who is in the review as the worker starts: no notice for them
295
- # (#watch_participants announces the changes from here on).
296
- watch_participants
299
+ # (WorkerParticipantGate#watch announces the changes from here on).
300
+ @participant_gate.watch
297
301
  # Input already waiting in the inbox starts the next turn at once, and
298
302
  # a command queued mid-turn (/thinking, /model, /llm-context) changes
299
303
  # what it starts with: no turn-end warm-up then.
@@ -305,7 +309,7 @@ module Samagotchi
305
309
  # Bridge exists by the time anyone answers).
306
310
  @continue_offer = ContinueOffer.new(engine: @engine, turn_flow: @turn_flow, run_turn: method(:run_engine_turn),
307
311
  max_iterations: method(:max_iterations),
308
- participant_refused: method(:participant_refusal),
312
+ participant_refused: @participant_gate.method(:refusal),
309
313
  save: -> { save_or_log(:command) { save_session } },
310
314
  queue_command: lambda { |line, client_id:|
311
315
  @bridge.queue_command(line, client_id: client_id, card: true)
@@ -320,7 +324,7 @@ module Samagotchi
320
324
  # one that finishes unseen wakes the idle session (#run_task_wake).
321
325
  @task_wakes = WorkerTaskWakes.new(engine: @engine, session: @session, wakes: @wakes,
322
326
  awaiting_continue: -> { @turn_flow.awaiting_continue? },
323
- idle: -> { nothing_queued? && !@exit_requested },
327
+ idle: -> { nothing_queued? && !@exit_claim.taken? },
324
328
  save: -> { save_or_log(:task_notes) { save_session } })
325
329
  @engine.subscribe(observer: lambda { |event|
326
330
  if Events::TURN_END.include?(event[:type])
@@ -525,7 +529,7 @@ module Samagotchi
525
529
  # ahead of an exit or restart a client asked for: it is a note then.
526
530
  @inbound.absorb_notes
527
531
  absorb_fresh_verdicts
528
- return if absorb_context(wake: nothing_queued? && !@exit_requested)
532
+ return if absorb_context(wake: nothing_queued? && !@exit_claim.taken?)
529
533
 
530
534
  if (prompt = @inbound.take_initial_prompt)
531
535
  run_initial_prompt(prompt) unless @inbound.initial_command?(prompt)
@@ -555,23 +559,14 @@ module Samagotchi
555
559
  return left(:scratch_left) if scratch_unattended? && !@engine.turn_running? && leave_scratch
556
560
  return left(:idle_exit) if @idle_exit.due? && leave_idle
557
561
 
558
- leaving = @exit_requested && leave_on_request
562
+ leaving = @exit_claim.taken? && leave_on_request
559
563
  return left(leaving) if leaving
560
564
 
561
- watch_participants
565
+ @participant_gate.watch
562
566
  @waker.wait(idle_wait)
563
567
  nil
564
568
  end
565
569
 
566
- # A participant invited, revoked or expired since the last look: the
567
- # UIs hear it (Engine#announce_participants: :participants_changed).
568
- # Between turns, at most once a fallback tick; a failure only logs.
569
- def watch_participants
570
- @engine.announce_participants
571
- rescue StandardError => e
572
- Log.warn(:worker, "participants_watch_failed", error: e.class.name)
573
- end
574
-
575
570
  # A participant's input file is held (left in the inbox, still queued
576
571
  # and counted as theirs) while the owner's Continue offer stands: the
577
572
  # offer is the owner's to answer (continue, stop, or a turn of their
@@ -681,7 +676,7 @@ module Samagotchi
681
676
  # one waits, like ask_user_question.
682
677
  engine.interface = :worker
683
678
  # A pair turn stops mid-turn at its participant's cap.
684
- engine.participant_stop = ->(author) { participant_turn_stop(author) }
679
+ engine.participant_stop = ->(author) { @participant_gate.turn_stop(author) }
685
680
  engine.guardrail_state_dir = @state_dir if @state_dir
686
681
  engine.session_state_dir = @state_dir if @state_dir
687
682
  engine
@@ -813,8 +808,8 @@ module Samagotchi
813
808
  # A participant's turn queued before their link ended or their cap was
814
809
  # reached doesn't start (chi web refuses new ones; this is the
815
810
  # worker's check).
816
- if (reason = participant_refusal(origin.author))
817
- return refuse_participant_turn(origin, reason)
811
+ if (reason = @participant_gate.refusal(origin.author))
812
+ return @participant_gate.refuse(origin, reason)
818
813
  end
819
814
 
820
815
  # A candidate the prompt mentions is attached and fetched first, so
@@ -837,7 +832,7 @@ module Samagotchi
837
832
  @continue_offer.after_turn(result, no_interrupt: prompt.no_interrupt)
838
833
  end
839
834
  end
840
- participant_refusal(origin.author)
835
+ @participant_gate.refusal(origin.author)
841
836
  end
842
837
 
843
838
  # +origin+ as this session's turns run it: a participant's Verify fresh
@@ -847,106 +842,6 @@ module Samagotchi
847
842
  fresh ? fresh.origin_for(origin) : TurnOrigin.of(origin)
848
843
  end
849
844
 
850
- # Why the participant +author+ ("p:<id>") may run no more turns, nil
851
- # while they may (and for the owner): by ParticipantTurnMode, "outdated"
852
- # for an older chi's read-only invite (an entry, or a Verify fresh child
853
- # saved, without "pair": this chi runs no read-only turn), "revoked" when
854
- # participants.json has no current entry for them (revoked, expired,
855
- # never invited) or they aren't invited to this (the owner's own Verify
856
- # fresh child), "cap_reached" once they spent their cap (its own,
857
- # else the config's; their turns and the side requests they caused,
858
- # Engine#metrics). The owner hears the cap once per cap (#cap_notice).
859
- def participant_refusal(author)
860
- author = Steer.sender_author(author) or return nil
861
-
862
- entry = participant_entry(author)
863
- case ParticipantTurnMode.of(entry: entry, session: @session, now: Time.now)
864
- when :outdated then return "outdated"
865
- when :revoked, :not_invited then return "revoked"
866
- end
867
-
868
- cap = participant_cap(entry)
869
- return nil if participant_spend(author) < cap
870
-
871
- cap_notice(author, entry, cap)
872
- "cap_reached"
873
- end
874
-
875
- # Why a participant's running pair turn stops (Engine#participant_stop,
876
- # asked before each of its generations): their link ended (revoked,
877
- # expired, the session archived) or their cap reached
878
- # (#participant_refusal, which gives the owner the cap notice), else nil.
879
- def participant_turn_stop(author)
880
- reason = participant_refusal(author) or return nil
881
-
882
- entry = participant_entry(author)
883
- name = participant_label(author, entry&.name)
884
- return format(REVOKED_STOP, name: name) if %w[revoked outdated].include?(reason)
885
-
886
- format(CAP_STOP, name: name, cap: participant_cap(entry))
887
- end
888
-
889
- # +author+'s participants.json entry: this session's, a Verify fresh
890
- # child's parent's (Session#participants_source_id); nil for none.
891
- def participant_entry(author)
892
- Participants.read(participants_id, state_dir: @state_dir).find { |e| Steer.author_for(e.id) == author }
893
- end
894
-
895
- # The session whose participants.json and audit trail this session's
896
- # participants are in.
897
- def participants_id = @session&.participants_source_id || @session_id
898
-
899
- # What +author+ spent against their cap: this session's metrics (live)
900
- # and, through Verify fresh, the parent's or the children's saved ones
901
- # (VerifyFresh.related_spend).
902
- def participant_spend(author)
903
- @engine.metrics.spend(author) + VerifyFresh.related_spend(@session, author, state_dir: @state_dir)
904
- end
905
-
906
- # A participant's cap in dollars: their own, else the config's.
907
- def participant_cap(entry) = entry&.cap.is_a?(Numeric) ? entry.cap.to_f : Grants.default_cap
908
-
909
- # A participant's cleaned name, else their id.
910
- def participant_label(author, name)
911
- who = ParticipantName.clean(name)
912
- who.empty? ? Steer.participant_id(author) : who
913
- end
914
-
915
- # The owner's notice that a participant reached their cap: once per
916
- # participant and cap (a raised cap that is reached again says so again).
917
- def cap_notice(author, entry, cap)
918
- key = [author, cap]
919
- return if (@cap_noticed ||= Set.new).include?(key)
920
-
921
- @cap_noticed << key
922
- id = Steer.participant_id(author)
923
- @engine.announce(type: :hook_notice, hook: Engine::PARTICIPANTS_HOOK, level: :warn, between_turns: true,
924
- text: format(CAP_NOTICE, name: participant_label(author, entry.name), cap: cap,
925
- session: participants_id[0, 8], id: id))
926
- end
927
-
928
- CAP_NOTICE = "%<name>s reached their $%<cap>.2f cap: their turns stop and are refused until you raise it " \
929
- "(chi share cap %<session>s %<id>s AMOUNT)."
930
- # The reason a pair turn stopped at its participant's cap (the turn's
931
- # "stopped the turn: …" notice).
932
- CAP_STOP = "%<name>s reached their $%<cap>.2f cap"
933
- # The reason a pair turn stopped because its participant's link ended
934
- # (revoked, expired, or the session archived).
935
- REVOKED_STOP = "%<name>s's link was revoked or expired"
936
-
937
- # A participant's queued turn that may not start (#participant_refusal):
938
- # taken off the queue (:turn_dequeued, so every UI drops its bubble)
939
- # and audited; it never runs. Its settled record (canceled, the reason)
940
- # ends the sender's wait on it (chi send --wait, chi web's /wait).
941
- # @param origin [TurnOrigin] a participant's
942
- def refuse_participant_turn(origin, reason)
943
- TurnCheckpoint.record_refused(@session_dir, origin.enqueued_id, reason: reason, author: origin.participant_author)
944
- Participants.log(participants_id, :turn, state_dir: @state_dir, participant: origin.participant_id,
945
- enqueued_id: origin.enqueued_id, status: "refused", reason: reason)
946
- @engine.announce(type: :turn_dequeued, enqueued_id: origin.enqueued_id, client_id: origin.client_id)
947
- nil
948
- end
949
-
950
845
  # A due reminder runs as a continue turn: Engine#run_turn
951
846
  # injects the reminders as a tail system message, and no user message is
952
847
  # added. A prompt's turn may have injected them already (a stale latch):
@@ -1625,10 +1520,10 @@ module Samagotchi
1625
1520
  end
1626
1521
  begin
1627
1522
  # A participant's line gets the checks their queued turn gets at
1628
- # its start (#participant_refusal: the link, the cap): refused,
1523
+ # its start (WorkerParticipantGate#refusal: the link, the cap): refused,
1629
1524
  # it is taken off as that turn would be, and never merged.
1630
- if (author = input.origin.participant_author) && (reason = participant_refusal(author))
1631
- refuse_participant_turn(input.origin, reason)
1525
+ if (author = input.origin.participant_author) && (reason = @participant_gate.refusal(author))
1526
+ @participant_gate.refuse(input.origin, reason)
1632
1527
  next
1633
1528
  end
1634
1529
  prompt = input.prompt.to_s.strip
@@ -1822,7 +1717,7 @@ module Samagotchi
1822
1717
  return if @marked_leaving
1823
1718
 
1824
1719
  @marked_leaving = true
1825
- wait ||= @exit_restart ? 0 : @engine.recap_timeout.to_f
1720
+ wait ||= @exit_claim.restart? ? 0 : @engine.recap_timeout.to_f
1826
1721
  @owner_lock&.mark_leaving(wait: wait)
1827
1722
  rescue StandardError => e
1828
1723
  Log.warn(:worker, "mark_leaving_failed", error: e.class.name, msg: e.message)
@@ -1857,55 +1752,24 @@ module Samagotchi
1857
1752
  # stop-all, so a request of another kind meanwhile is refused (409),
1858
1753
  # not told it went through. Held at the leave, it is forgotten and the
1859
1754
  # next request counts again.
1860
- refused = claim_exit(kind)
1755
+ refused = @exit_claim.claim(kind)
1861
1756
  return refused.value if refused
1862
1757
 
1863
1758
  hold = exit_hold(client_id, kind: kind, stop: stop, ask: ask)
1864
1759
  if hold
1865
- forget_exit
1760
+ @exit_claim.forget
1866
1761
  return hold
1867
1762
  end
1868
1763
 
1869
- @stopped_holds = nil unless stop
1870
- @exit_requested_by = client_id
1871
- @exit_deletes = kind == :delete
1872
- @exit_restart = kind == :restart
1873
- @exit_requested = true
1764
+ @exit_claim.accept(by: client_id, stop: stop)
1874
1765
  @waker.wake
1875
1766
  nil
1876
1767
  rescue StandardError
1877
1768
  # A look or a stop that raised lets the claim go (the Bridge answers 500).
1878
- forget_exit unless @exit_requested
1769
+ @exit_claim.release
1879
1770
  raise
1880
1771
  end
1881
1772
 
1882
- # One answer for an exit request that doesn't get the claim, boxed so a
1883
- # nil (accepted) is told apart from "claimed".
1884
- ExitRefused = Data.define(:value)
1885
-
1886
- # @return [ExitRefused, nil] nil when this request now holds the claim;
1887
- # else its answer: nil (accepted: an exit of the same kind is already
1888
- # taken) or WorkerIdleExit.leaving (one of another kind is, or is still
1889
- # being taken)
1890
- def claim_exit(kind)
1891
- @exit_claim_mutex.synchronize do
1892
- next ExitRefused.new(value: nil) if @exit_claim == kind && @exit_requested
1893
- next ExitRefused.new(value: WorkerIdleExit.leaving(@exit_claim)) if @exit_claim
1894
-
1895
- @exit_claim = kind
1896
- nil
1897
- end
1898
- end
1899
-
1900
- # The taken exit is let go: held at the leave, or its hand-off failed.
1901
- def forget_exit
1902
- @exit_claim_mutex.synchronize do
1903
- @exit_requested = nil
1904
- @exit_restart = false
1905
- @exit_claim = nil
1906
- end
1907
- end
1908
-
1909
1773
  # What keeps the worker up for this request, nil when nothing does; a
1910
1774
  # stop request stops what the user can stop first (#exit_request).
1911
1775
  # @return [WorkerIdleExit::Hold, nil]
@@ -1928,7 +1792,7 @@ module Samagotchi
1928
1792
  # The ask's 409: the list, for the terminal to ask with.
1929
1793
  return hold unless stop
1930
1794
 
1931
- @stopped_holds = @hold_stop.stop_all
1795
+ @exit_claim.stopped!(@hold_stop.stop_all)
1932
1796
  # An unstoppable hold may have arrived while stopping (a child stopped
1933
1797
  # here is no longer counted).
1934
1798
  @idle_exit.request_hold(requester: client_id, hint: TASK_STOP_HINT)
@@ -1944,23 +1808,26 @@ module Samagotchi
1944
1808
  def leave_on_request
1945
1809
  stop_bridge_after do
1946
1810
  @engine.synchronize_events do
1947
- hold = if @exit_restart
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
1948
1815
  @idle_exit.hold_for_restart
1949
1816
  else
1950
- @idle_exit.hold_for_request(requester: @exit_requested_by, streams: false)
1817
+ @idle_exit.hold_for_request(requester: taken&.by, streams: false)
1951
1818
  end
1952
1819
  if hold
1953
- forget_exit
1820
+ @exit_claim.forget
1954
1821
  Log.info(:worker, "exit_held", reason: hold)
1955
1822
  next false
1956
1823
  end
1957
- next false if @exit_restart && !carry_reminders
1824
+ next false if restart && !carry_reminders
1958
1825
 
1959
1826
  @bridge&.close_intake
1960
1827
  # Not joined: a recap tick's emit waits for the event log held here.
1961
1828
  @engine.stop_idle(join: false)
1962
- Log.info(:worker, @exit_restart ? "restart_requested" : "exit_requested", by: @exit_requested_by || "a client")
1963
- @exit_restart ? :restart : :exit_requested
1829
+ Log.info(:worker, restart ? "restart_requested" : "exit_requested", by: taken&.by || "a client")
1830
+ restart ? :restart : :exit_requested
1964
1831
  end
1965
1832
  end
1966
1833
  end
@@ -1979,7 +1846,7 @@ module Samagotchi
1979
1846
  end
1980
1847
  true
1981
1848
  rescue StandardError => e
1982
- forget_exit
1849
+ @exit_claim.forget
1983
1850
  Log.warn(:worker, "reminders_carry_failed", error: e.class.name, msg: e.message)
1984
1851
  false
1985
1852
  end
@@ -2012,7 +1879,7 @@ module Samagotchi
2012
1879
  # A restart keeps even an empty session (a new worker takes it over at
2013
1880
  # once) and leaves the recap to the conversation's next real pause.
2014
1881
  def left(result)
2015
- deleting = (result == :exit_requested && @exit_deletes) || result == :scratch_left
1882
+ deleting = (result == :exit_requested && @exit_claim.deletes?) || result == :scratch_left
2016
1883
  # The attached context goes with this process: a change that landed after
2017
1884
  # the leaving pass looked at it has no later pass to note it, so note it
2018
1885
  # here (no wake turn: the worker is on its way out). Not into a session
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "worker_idle_exit"
4
+
5
+ module Samagotchi
6
+ # One exit at a time (Worker#exit_request, Bridge POST /exit): the kind
7
+ # being taken (claimed before the slow stop-all, so a request of another
8
+ # kind meanwhile is refused, not told it went through), the exit taken
9
+ # (who asked, whether it deletes or restarts) and what the last stop-all
10
+ # stopped. A pure state object: it calls nothing while it holds its lock.
11
+ #
12
+ # Threads: safe from any thread. Its fields change only under its own
13
+ # mutex, and the taken exit is one value replaced whole (#taken), so a
14
+ # reader never sees a kind with another request's flags. Today every
15
+ # writer also holds the event lock (Engine#synchronize_events: the Bridge's
16
+ # /exit, the loop's leave); nothing here depends on it. Lock order: the
17
+ # event lock, then this one.
18
+ class WorkerExitClaim
19
+ # The answer for a request that doesn't get the claim, boxed so a nil
20
+ # (accepted) is told apart from "claimed".
21
+ Refused = Data.define(:value)
22
+
23
+ # The exit taken: its +kind+ (:exit, :delete, :restart) and the client
24
+ # that asked (+by+).
25
+ Taken = Data.define(:kind, :by) do
26
+ def restart? = kind == :restart
27
+ def deletes? = kind == :delete
28
+ end
29
+
30
+ def initialize
31
+ @mutex = Mutex.new
32
+ # The kind being taken, or taken (:exit, :delete, :restart); nil when free.
33
+ @claim = nil
34
+ # The Taken exit once accepted; nil while free or being taken.
35
+ @taken = nil
36
+ # The last stop-all's HoldStop::Stopped (Worker#exit_hold); kept across a
37
+ # forget, cleared by a plain exit's accept.
38
+ @stopped = nil
39
+ end
40
+
41
+ # @return [Refused, nil] nil when this request now holds the claim;
42
+ # else its answer: nil (accepted: an exit of the same kind is already
43
+ # taken) or WorkerIdleExit.leaving (one of another kind is, or is still
44
+ # being taken)
45
+ def claim(kind)
46
+ @mutex.synchronize do
47
+ next Refused.new(value: nil) if @claim == kind && @taken
48
+ next Refused.new(value: WorkerIdleExit.leaving(@claim)) if @claim
49
+
50
+ @claim = kind
51
+ nil
52
+ end
53
+ end
54
+
55
+ # The claimed exit goes through: it is taken by +by+ (a client id), and
56
+ # a plain one (no +stop+) drops the last stop-all's list.
57
+ def accept(by:, stop:)
58
+ @mutex.synchronize do
59
+ @stopped = nil unless stop
60
+ @taken = Taken.new(kind: @claim, by: by)
61
+ end
62
+ nil
63
+ end
64
+
65
+ # What a stop-all exit stopped (HoldStop#stop_all), for the Bridge's 200.
66
+ def stopped!(stopped)
67
+ @mutex.synchronize { @stopped = stopped }
68
+ end
69
+
70
+ # The taken exit is let go: held at the leave, or its hand-off failed.
71
+ def forget
72
+ @mutex.synchronize do
73
+ @claim = nil
74
+ @taken = nil
75
+ end
76
+ nil
77
+ end
78
+
79
+ # A request that raised lets its claim go, unless its exit was taken.
80
+ def release
81
+ @mutex.synchronize do
82
+ next if @taken
83
+
84
+ @claim = nil
85
+ end
86
+ nil
87
+ end
88
+
89
+ # @return [Taken, nil] the exit taken, one read: its kind and asker
90
+ # always belong together
91
+ def taken = @mutex.synchronize { @taken }
92
+
93
+ def taken? = !taken.nil?
94
+
95
+ def restart? = taken&.restart? || false
96
+
97
+ def deletes? = taken&.deletes? || false
98
+
99
+ # @return [HoldStop::Stopped, nil] the last stop-all's list
100
+ def stopped = @mutex.synchronize { @stopped }
101
+ end
102
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "grants"
4
+ require_relative "log"
5
+ require_relative "participant_name"
6
+ require_relative "participant_turn_mode"
7
+ require_relative "participants"
8
+ require_relative "steer"
9
+ require_relative "turn_checkpoint"
10
+ require_relative "verify_fresh"
11
+
12
+ module Samagotchi
13
+ # The Worker's one seat for "may this participant act": a queued turn as
14
+ # it starts (Worker#run_prompt), a line the running turn's drain would
15
+ # merge (Worker#pending_input_drain), a running pair turn before each
16
+ # generation (Engine#participant_stop, #turn_stop) and the owner's
17
+ # Continue on a participant's offer (ContinueOffer's participant_refused).
18
+ # It reads participants.json and the spend on each ask, and tells the
19
+ # owner of a reached cap once per participant and cap.
20
+ #
21
+ # Threads: loop thread only. Every caller runs on the worker's loop (a
22
+ # turn runs on it too); no Bridge, anytime, signal or scratch-watch thread
23
+ # calls it, so it takes no lock (@cap_noticed is unguarded). A caller
24
+ # from another thread needs a lock here first, and Engine#metrics' spend
25
+ # would still not be safe from any thread. Worker#held_for_offer?, which
26
+ # Bridge threads reach, is not here: it is stateless.
27
+ class WorkerParticipantGate
28
+ CAP_NOTICE = "%<name>s reached their $%<cap>.2f cap: their turns stop and are refused until you raise it " \
29
+ "(chi share cap %<session>s %<id>s AMOUNT)."
30
+ # The reason a pair turn stopped at its participant's cap (the turn's
31
+ # "stopped the turn: …" notice).
32
+ CAP_STOP = "%<name>s reached their $%<cap>.2f cap"
33
+ # The reason a pair turn stopped because its participant's link ended
34
+ # (revoked, expired, or the session archived).
35
+ REVOKED_STOP = "%<name>s's link was revoked or expired"
36
+
37
+ # @param engine [Engine] announces (the cap notice, :turn_dequeued,
38
+ # #watch's :participants_changed) and its metrics' spend
39
+ # @param session [Session] the worker's (its participants source, its
40
+ # Verify fresh)
41
+ # @param hook [String] the cap notice's hook name (Engine::PARTICIPANTS_HOOK)
42
+ def initialize(engine:, session:, session_id:, state_dir:, session_dir:, hook:)
43
+ @engine = engine
44
+ @session = session
45
+ @session_id = session_id
46
+ @state_dir = state_dir
47
+ @session_dir = session_dir
48
+ @hook = hook
49
+ # [author, cap] pairs the owner was told about (#cap_notice).
50
+ @cap_noticed = Set.new
51
+ end
52
+
53
+ # Why the participant +author+ ("p:<id>") may run no more turns, nil
54
+ # while they may (and for the owner): by ParticipantTurnMode, "outdated"
55
+ # for an older chi's read-only invite (an entry, or a Verify fresh child
56
+ # saved, without "pair": this chi runs no read-only turn), "revoked" when
57
+ # participants.json has no current entry for them (revoked, expired,
58
+ # never invited) or they aren't invited to this (the owner's own Verify
59
+ # fresh child), "cap_reached" once they spent their cap (its own,
60
+ # else the config's; their turns and the side requests they caused,
61
+ # Engine#metrics). The owner hears the cap once per cap (#cap_notice).
62
+ def refusal(author)
63
+ author = Steer.sender_author(author) or return nil
64
+
65
+ entry = entry(author)
66
+ case ParticipantTurnMode.of(entry: entry, session: @session, now: Time.now)
67
+ when :outdated then return "outdated"
68
+ when :revoked, :not_invited then return "revoked"
69
+ end
70
+
71
+ cap = cap(entry)
72
+ return nil if spend(author) < cap
73
+
74
+ cap_notice(author, entry, cap)
75
+ "cap_reached"
76
+ end
77
+
78
+ # Why a participant's running pair turn stops (Engine#participant_stop,
79
+ # asked before each of its generations): their link ended (revoked,
80
+ # expired, the session archived) or their cap reached
81
+ # (#refusal, which gives the owner the cap notice), else nil.
82
+ def turn_stop(author)
83
+ reason = refusal(author) or return nil
84
+
85
+ entry = entry(author)
86
+ name = label(author, entry&.name)
87
+ return format(REVOKED_STOP, name: name) if %w[revoked outdated].include?(reason)
88
+
89
+ format(CAP_STOP, name: name, cap: cap(entry))
90
+ end
91
+
92
+ # A participant's queued turn that may not start (#refusal):
93
+ # taken off the queue (:turn_dequeued, so every UI drops its bubble)
94
+ # and audited; it never runs. Its settled record (canceled, the reason)
95
+ # ends the sender's wait on it (chi send --wait, chi web's /wait).
96
+ # @param origin [TurnOrigin] a participant's
97
+ # @return [nil]
98
+ def refuse(origin, reason)
99
+ TurnCheckpoint.record_refused(@session_dir, origin.enqueued_id, reason: reason, author: origin.participant_author)
100
+ Participants.log(source_id, :turn, state_dir: @state_dir, participant: origin.participant_id,
101
+ enqueued_id: origin.enqueued_id, status: "refused", reason: reason)
102
+ @engine.announce(type: :turn_dequeued, enqueued_id: origin.enqueued_id, client_id: origin.client_id)
103
+ nil
104
+ end
105
+
106
+ # A participant invited, revoked or expired since the last look: the
107
+ # UIs hear it (Engine#announce_participants: :participants_changed).
108
+ # Between turns, at most once a fallback tick; a failure only logs.
109
+ def watch
110
+ @engine.announce_participants
111
+ rescue StandardError => e
112
+ Log.warn(:worker, "participants_watch_failed", error: e.class.name)
113
+ end
114
+
115
+ private
116
+
117
+ # +author+'s participants.json entry: this session's, a Verify fresh
118
+ # child's parent's (Session#participants_source_id); nil for none.
119
+ def entry(author)
120
+ Participants.read(source_id, state_dir: @state_dir).find { |e| Steer.author_for(e.id) == author }
121
+ end
122
+
123
+ # The session whose participants.json and audit trail this session's
124
+ # participants are in.
125
+ def source_id = @session&.participants_source_id || @session_id
126
+
127
+ # What +author+ spent against their cap: this session's metrics (live)
128
+ # and, through Verify fresh, the parent's or the children's saved ones
129
+ # (VerifyFresh.related_spend).
130
+ def spend(author)
131
+ @engine.metrics.spend(author) + VerifyFresh.related_spend(@session, author, state_dir: @state_dir)
132
+ end
133
+
134
+ # A participant's cap in dollars: their own, else the config's.
135
+ def cap(entry) = entry&.cap.is_a?(Numeric) ? entry.cap.to_f : Grants.default_cap
136
+
137
+ # A participant's cleaned name, else their id.
138
+ def label(author, name)
139
+ who = ParticipantName.clean(name)
140
+ who.empty? ? Steer.participant_id(author) : who
141
+ end
142
+
143
+ # The owner's notice that a participant reached their cap: once per
144
+ # participant and cap (a raised cap that is reached again says so again).
145
+ def cap_notice(author, entry, cap)
146
+ key = [author, cap]
147
+ return if @cap_noticed.include?(key)
148
+
149
+ @cap_noticed << key
150
+ id = Steer.participant_id(author)
151
+ @engine.announce(type: :hook_notice, hook: @hook, level: :warn, between_turns: true,
152
+ text: format(CAP_NOTICE, name: label(author, entry.name), cap: cap,
153
+ session: source_id[0, 8], id: id))
154
+ end
155
+ end
156
+ end
@@ -7,7 +7,7 @@ require_relative "log"
7
7
  require_relative "task_finish_note"
8
8
  require_relative "task_watch"
9
9
  require_relative "tool_output_cut"
10
- require_relative "tools/task_runtime"
10
+ require_relative "task_transcript"
11
11
  require_relative "worker_inbound"
12
12
  require_relative "worker_wakes"
13
13
 
@@ -117,7 +117,7 @@ module Samagotchi
117
117
  # TaskWatch::MAX_FAILURES they no longer hold the worker up): they wait
118
118
  # for the next look.
119
119
  def take_finished
120
- @watch.take_finished(keep: Tools::TaskRuntime.created_ids_in(@engine.messages_checkpoint))
120
+ @watch.take_finished(keep: TaskTranscript.created_ids_in(@engine.messages_checkpoint))
121
121
  rescue StandardError => e
122
122
  Log.warn(:worker, "task_watch_failed", error: e.class.name, msg: e.message)
123
123
  @watch.look_failed