samagotchi 0.187.0 → 0.189.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 (184) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +96 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +13 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +139 -120
  7. data/docs/cli.md +46 -8
  8. data/docs/configuration.md +4 -4
  9. data/docs/context.md +18 -162
  10. data/docs/guardrails.md +6 -3
  11. data/docs/hooks.md +2 -1
  12. data/docs/internals/attached-context.md +19 -37
  13. data/docs/internals/bridge.md +1 -0
  14. data/docs/internals/bundles.md +3 -3
  15. data/docs/internals/engine.md +2 -2
  16. data/docs/internals/llm-context-forget.md +5 -6
  17. data/docs/internals/objectives.md +1 -0
  18. data/docs/internals/pages.md +71 -21
  19. data/docs/internals/peers.md +149 -0
  20. data/docs/internals/remote-sessions.md +7 -4
  21. data/docs/internals/session-lifecycle.md +19 -6
  22. data/docs/internals/web-frontend.md +63 -39
  23. data/docs/internals/web-push.md +12 -6
  24. data/docs/memory.md +1 -1
  25. data/docs/pages.md +70 -16
  26. data/docs/peers.md +144 -0
  27. data/docs/plugins.md +77 -28
  28. data/docs/releasing.md +1 -1
  29. data/docs/scheduling.md +71 -8
  30. data/docs/sessions.md +12 -8
  31. data/docs/sub-agent.md +5 -5
  32. data/docs/testing.md +1 -1
  33. data/lib/samagotchi/bridge.rb +3 -3
  34. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  35. data/lib/samagotchi/bundle_command/check.rb +1 -1
  36. data/lib/samagotchi/bundle_manifest.rb +34 -5
  37. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  38. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  39. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  40. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  41. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  42. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  43. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  44. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  45. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  46. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  47. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  49. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
  50. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  51. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  52. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  53. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  54. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  55. data/lib/samagotchi/client_id.rb +15 -1
  56. data/lib/samagotchi/config.rb +8 -7
  57. data/lib/samagotchi/context_absorber.rb +23 -277
  58. data/lib/samagotchi/context_sources.rb +17 -69
  59. data/lib/samagotchi/engine/messages.rb +12 -1
  60. data/lib/samagotchi/engine/plugins.rb +1 -1
  61. data/lib/samagotchi/engine.rb +7 -6
  62. data/lib/samagotchi/engine_peers.rb +0 -3
  63. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  64. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  65. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  66. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  67. data/lib/samagotchi/inline_widgets.rb +11 -3
  68. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  69. data/lib/samagotchi/log_line.rb +1 -1
  70. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  71. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  72. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  73. data/lib/samagotchi/note_move.rb +3 -1
  74. data/lib/samagotchi/page_command.rb +25 -13
  75. data/lib/samagotchi/pages/builder.rb +7 -8
  76. data/lib/samagotchi/pages/bundled.rb +83 -0
  77. data/lib/samagotchi/pages/launch.rb +22 -4
  78. data/lib/samagotchi/pages/runner.rb +7 -2
  79. data/lib/samagotchi/pages/runtime.rb +83 -0
  80. data/lib/samagotchi/pages/store.rb +29 -7
  81. data/lib/samagotchi/pages.rb +47 -3
  82. data/lib/samagotchi/peer_command.rb +192 -0
  83. data/lib/samagotchi/peer_continue.rb +105 -0
  84. data/lib/samagotchi/peer_exchanges.rb +3 -3
  85. data/lib/samagotchi/peer_mailbox.rb +360 -0
  86. data/lib/samagotchi/peer_note.rb +208 -0
  87. data/lib/samagotchi/peer_receipts.rb +247 -0
  88. data/lib/samagotchi/peer_registry.rb +44 -0
  89. data/lib/samagotchi/peer_roster.rb +79 -0
  90. data/lib/samagotchi/peer_say.rb +168 -0
  91. data/lib/samagotchi/plugin/api.rb +29 -21
  92. data/lib/samagotchi/plugin/context.rb +7 -0
  93. data/lib/samagotchi/plugin/loader.rb +3 -3
  94. data/lib/samagotchi/plugin/peer.rb +175 -64
  95. data/lib/samagotchi/plugin/peers.rb +70 -0
  96. data/lib/samagotchi/run_options.rb +3 -2
  97. data/lib/samagotchi/schedule_command.rb +88 -39
  98. data/lib/samagotchi/schedule_display.rb +101 -0
  99. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  100. data/lib/samagotchi/schedules/edit_part.rb +120 -0
  101. data/lib/samagotchi/schedules/history_part.rb +51 -0
  102. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  103. data/lib/samagotchi/schedules/notices_part.rb +116 -0
  104. data/lib/samagotchi/schedules/protection_part.rb +103 -0
  105. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  106. data/lib/samagotchi/schedules.rb +134 -330
  107. data/lib/samagotchi/session_access/contract.rb +18 -1
  108. data/lib/samagotchi/session_access/local.rb +140 -14
  109. data/lib/samagotchi/session_access/remote.rb +6 -3
  110. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  111. data/lib/samagotchi/session_chain/delete.rb +7 -5
  112. data/lib/samagotchi/session_continue.rb +12 -0
  113. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  114. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  115. data/lib/samagotchi/session_lifecycle.rb +3 -2
  116. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  117. data/lib/samagotchi/session_manager/removal.rb +18 -9
  118. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  119. data/lib/samagotchi/session_manager.rb +1 -0
  120. data/lib/samagotchi/session_protection.rb +99 -0
  121. data/lib/samagotchi/session_retention.rb +21 -6
  122. data/lib/samagotchi/session_stores.rb +17 -0
  123. data/lib/samagotchi/sessions_command.rb +4 -0
  124. data/lib/samagotchi/steer.rb +1 -1
  125. data/lib/samagotchi/system_prompt.rb +1 -1
  126. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  127. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  128. data/lib/samagotchi/testing/boundary.rb +17 -13
  129. data/lib/samagotchi/testing/bundle.rb +40 -5
  130. data/lib/samagotchi/testing/install.rb +4 -4
  131. data/lib/samagotchi/testing/recording_api.rb +2 -1
  132. data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
  133. data/lib/samagotchi/tools/context_read.rb +0 -14
  134. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  135. data/lib/samagotchi/turn_outcome.rb +41 -0
  136. data/lib/samagotchi/version.rb +1 -1
  137. data/lib/samagotchi/web/app.rb +2 -13
  138. data/lib/samagotchi/web/message_display.rb +4 -2
  139. data/lib/samagotchi/web/page_routes.rb +13 -8
  140. data/lib/samagotchi/web/peer_routes.rb +133 -0
  141. data/lib/samagotchi/web/public/app.js +23 -29
  142. data/lib/samagotchi/web/public/bubbles.js +2 -2
  143. data/lib/samagotchi/web/public/cards_place.js +20 -1
  144. data/lib/samagotchi/web/public/context_chips.js +45 -46
  145. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  146. data/lib/samagotchi/web/public/history_shape.js +3 -2
  147. data/lib/samagotchi/web/public/index.html +24 -2
  148. data/lib/samagotchi/web/public/notify.js +1 -1
  149. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  150. data/lib/samagotchi/web/public/page_links.js +1 -1
  151. data/lib/samagotchi/web/public/page_view.js +10 -6
  152. data/lib/samagotchi/web/public/pages.css +9 -2
  153. data/lib/samagotchi/web/public/pages_group.js +21 -19
  154. data/lib/samagotchi/web/public/pages_list.js +73 -0
  155. data/lib/samagotchi/web/public/pages_model.js +54 -0
  156. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  157. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  158. data/lib/samagotchi/web/public/peer_data.js +13 -11
  159. data/lib/samagotchi/web/public/peer_links.js +12 -7
  160. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  161. data/lib/samagotchi/web/public/peer_note.js +7 -3
  162. data/lib/samagotchi/web/public/peer_text.js +4 -4
  163. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  164. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  165. data/lib/samagotchi/web/public/session_view.js +2 -2
  166. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  167. data/lib/samagotchi/web/public/turn_block.js +7 -3
  168. data/lib/samagotchi/web/public/turn_events.js +6 -0
  169. data/lib/samagotchi/web/public/views.js +77 -23
  170. data/lib/samagotchi/web/push/attention.rb +3 -2
  171. data/lib/samagotchi/web/push/notifier.rb +4 -3
  172. data/lib/samagotchi/web/server.rb +3 -1
  173. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  174. data/lib/samagotchi/web/session_hub.rb +64 -19
  175. data/lib/samagotchi/worker/leave.rb +3 -0
  176. data/lib/samagotchi/worker/mail.rb +73 -0
  177. data/lib/samagotchi/worker/startup.rb +3 -0
  178. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  179. data/lib/samagotchi/worker.rb +12 -6
  180. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  181. data/lib/samagotchi/worker_inbound.rb +43 -46
  182. data/lib/samagotchi/worker_wakes.rb +26 -21
  183. metadata +35 -2
  184. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -6,6 +6,7 @@ require_relative "../child_reports"
6
6
  require_relative "../client_id"
7
7
  require_relative "../iteration_limit"
8
8
  require_relative "../log"
9
+ require_relative "../peer_mailbox"
9
10
  require_relative "../session_inbox"
10
11
  require_relative "../turn_origin"
11
12
 
@@ -102,12 +103,12 @@ module Samagotchi
102
103
  max_iterations: IterationLimit.for) do |result, error|
103
104
  if error
104
105
  steps_kept = @turn_flow.prompt_turn_failed(error: error, wake: failed, wake_kept: kept) == :kept
105
- @inbound.unmark_wake(mark) if mark && !steps_kept
106
+ @unmarked_this_turn = @inbound.unmark_wake(mark) if mark && !steps_kept
106
107
  @wakes.pause!
107
108
  else
108
109
  @continue_offer.after_turn(result)
109
110
  if result.canceled? && @turn_flow.restores != restores
110
- @inbound.unmark_wake(mark) if mark
111
+ @unmarked_this_turn = @inbound.unmark_wake(mark) if mark
111
112
  @wakes.pause!
112
113
  end
113
114
  end
@@ -118,15 +119,27 @@ module Samagotchi
118
119
  # turn from context:<name> whose first message is the wake note already
119
120
  # in the conversation (named by +turn_id+), on the same rules as a
120
121
  # delegate report's wake turn (#run_wake): it counts toward
121
- # session.max_wakes (a peer's answer toward context.peer_turns too,
122
+ # session.max_wakes (a peer's answer toward peer.turns too,
122
123
  # unless it agrees).
123
124
  # +context_wake+: a WorkerInbound::ContextWake.
124
125
  def run_context_wake_turn(context_wake)
125
126
  name = context_wake.name
126
- Log.info(:worker, "context_wake_turn", name: name, in_a_row: @wakes.count!(peer: context_wake.peer_turn?))
127
+ Log.info(:worker, "context_wake_turn", name: name, in_a_row: @wakes.count!)
127
128
  run_wake(origin: context_wake.origin, failed: "the change in attached context #{name}", mark: context_wake)
128
129
  end
129
130
 
131
+ # A turn nobody typed for a peer's message that asked (a mail wake): a
132
+ # continue turn from peer:<name> whose first message is the batch's
133
+ # last note, already in the conversation (named by its turn id), on
134
+ # #run_wake's rules. It counts toward session.max_wakes and, unless the
135
+ # message agrees, toward peer.turns.
136
+ # +mail_wake+: a WorkerInbound::MailWake.
137
+ def run_mail_wake_turn(mail_wake)
138
+ Log.info(:worker, "mail_wake_turn", peer: mail_wake.peer, in_a_row: @wakes.count!(peer: !mail_wake.agreed))
139
+ run_wake(origin: mail_wake.origin, failed: "the message from your peer agent #{PeerMailbox.label(mail_wake.peer)}",
140
+ mark: mail_wake)
141
+ end
142
+
130
143
  # The background tasks this session started that finished unseen, as
131
144
  # notes (WorkerTaskWakes#take), and the wake turn the first one may
132
145
  # start.
@@ -184,7 +197,9 @@ module Samagotchi
184
197
 
185
198
  # The idle loop's sleep: the fallback tick, or less while reports or
186
199
  # attached-context wakes wait out the start grace.
187
- def idle_wait = @wakes.idle_wait(@poll_interval) { wake_state == :due || @inbound.context_wake_waiting? }
200
+ def idle_wait
201
+ @wakes.idle_wait(@poll_interval) { wake_state == :due || @inbound.context_wake_waiting? || @inbound.mail_wake_waiting? }
202
+ end
188
203
  end
189
204
  end
190
205
  end
@@ -51,6 +51,7 @@ require_relative "worker/child_side"
51
51
  require_relative "worker/command_queue"
52
52
  require_relative "worker/block_fixes"
53
53
  require_relative "worker/senders"
54
+ require_relative "worker/mail"
54
55
 
55
56
  module Samagotchi
56
57
  # The loop of a background session worker, once it owns the session (see
@@ -103,6 +104,7 @@ module Samagotchi
103
104
  include CommandQueuePart
104
105
  include BlockFixesPart
105
106
  include SendersPart
107
+ include MailPart
106
108
 
107
109
  FALLBACK_TICK_SECONDS = 5
108
110
  # A worker just started runs no wake turn for delegate reports this
@@ -291,6 +293,8 @@ module Samagotchi
291
293
  @event_log.announce(type: :hook_notice, hook: "config", text: message, level: :warn, between_turns: true)
292
294
  end
293
295
  prune_tombstones
296
+ # What this worker did with each peer message (PeerReceipts, read once).
297
+ @peer_receipts = PeerReceipts.new(session_id: @session_id, state_dir: @state_dir)
294
298
  settle_interrupted_turn
295
299
  settle_stale_status
296
300
  # Before the Bridge serves anything: a UI joining a resumed worker's
@@ -350,17 +354,16 @@ module Samagotchi
350
354
  # This session's own delegate children's news (rings in children/).
351
355
  @child_reports = ChildReports.new(session_id: @session_id, state_dir: @state_dir,
352
356
  predecessor: @session.continues)
353
- # Its attached context's notes (ContextSources); a peer's text goes in
354
- # its note up to the tool output cap, as a task's does (WorkerTaskWakes).
357
+ # Its attached context's notes (ContextSources).
355
358
  @context_absorber = ContextAbsorber.new(session_id: @session_id, state_dir: @state_dir,
356
- project_root: @session.project_root, project_id: @session.project_id,
357
- peer_sources: @engine.peer_sources, peer_turns: -> { @wakes.peer_turns },
358
- cap: -> { ToolOutputCut.max_chars(nil) })
359
+ project_root: @session.project_root, project_id: @session.project_id)
359
360
  # What comes in between turns, and how each kind is saved.
360
361
  @inbound = WorkerInbound.new(session: @session, state_dir: @state_dir, session_dir: @session_dir, engine: @engine,
361
362
  event_log: @event_log, turn_state: @turn_state, context_absorber: @context_absorber, wakes: @wakes,
362
363
  awaiting_continue: -> { @turn_flow.awaiting_continue? },
363
364
  stopped: -> { stopped_on_disk? },
365
+ peer_registry: @engine.peer_registry, peer_receipts: @peer_receipts,
366
+ mail_cap: -> { ToolOutputCut.max_chars(nil) },
364
367
  queue_command: lambda { |line, client_id, after_file, enqueued_id, author: nil|
365
368
  @bridge.queue_command(line, client_id: client_id, after_file: after_file,
366
369
  enqueued_id: enqueued_id, author: author)
@@ -507,6 +510,7 @@ module Samagotchi
507
510
  # ahead of an exit or restart a client asked for: it is a note then.
508
511
  @inbound.absorb_notes
509
512
  absorb_fresh_verdicts
513
+ return if absorb_mail(hold: pass_hold)
510
514
  return if absorb_context(wake: nothing_queued? && !@exit_claim.taken?)
511
515
 
512
516
  if (prompt = @inbound.take_initial_prompt)
@@ -708,6 +712,7 @@ module Samagotchi
708
712
  # A first turn sees the context attached before it, and any turn the
709
713
  # background tasks that finished since the last look.
710
714
  absorb_context(before_turn: true)
715
+ absorb_mail(hold: :before_turn)
711
716
  @task_wakes.absorb
712
717
  user_input(origin.client_id)
713
718
  @continue_offer.drop(origin)
@@ -763,6 +768,7 @@ module Samagotchi
763
768
  @turn_author = origin.participant_author
764
769
  restores = @turn_flow.restores
765
770
  begin
771
+ peer_turn_started(turn_args[:id])
766
772
  @checkpoint.begin_turn(prompt: prompt, turn_id: turn_args[:id], enqueued_id: origin.enqueued_id, author: turn_author_fields(origin),
767
773
  source: turn_args[:opener_source], reply: ReplyFor.opener_fields(@session.messages, turn_args[:reply_for]))
768
774
  @session.status = Session::STATUS_RUNNING
@@ -788,7 +794,7 @@ module Samagotchi
788
794
  @checkpoint.end_turn
789
795
  refuse_queued_commands
790
796
  end
791
- yield result, error
797
+ settle_peer_turn(turn_args[:id], result, error) { yield result, error }
792
798
  response = result&.output
793
799
  # A turn that ran out of iterations and asks whether to continue left
794
800
  # no reply: its text is what came before its last tool calls, and a
@@ -0,0 +1,214 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "time"
5
+
6
+ require_relative "../child_reports"
7
+ require_relative "../client_id"
8
+ require_relative "../context_note"
9
+ require_relative "../log"
10
+ require_relative "../peer_mailbox"
11
+ require_relative "../peer_note"
12
+ require_relative "../peer_receipts"
13
+ require_relative "../turn_origin"
14
+ require_relative "../worker_wakes"
15
+
16
+ module Samagotchi
17
+ class WorkerInbound
18
+ # A mail wake turn to run: peer +peer+'s messages are in the
19
+ # conversation, the batch's last note the start of the turn +turn_id+;
20
+ # +plain_note+ is that note without the turn start or the wake line,
21
+ # which #unmark_wake puts back; +agreed+: the newest message that asked
22
+ # agrees (it counts toward session.max_wakes only).
23
+ MailWake = Data.define(:peer, :turn_id, :plain_note, :agreed) do
24
+ def name = "peer #{PeerMailbox.label(peer)}"
25
+ def origin = TurnOrigin.new(client_id: "#{ClientId::PEER_PREFIX}#{peer}")
26
+ def note = plain_note
27
+ end
28
+
29
+ # One message of a batch: its +peer+, the PeerMessage (nil for a
30
+ # refused one), the note's id and +refused+ (nil, "undeclared",
31
+ # "invalid"); +order+ sorts the batch.
32
+ MailItem = Data.define(:peer, :message, :serial, :note_id, :refused, :order) do
33
+ def asked = message&.wake == true
34
+ def taken? = refused.nil?
35
+ end
36
+
37
+ # The fourth inbound kind: a peer's messages from the mailbox
38
+ # (PeerMailbox), one note each, between turns. Mixed into WorkerInbound;
39
+ # reads @session, @engine, @wakes, @awaiting_continue, @stopped,
40
+ # @peer_registry, @peer_receipts, @mail_cap. See docs/internals/peers.md.
41
+ module MailPart
42
+ # The holds a caller gives (a wake can't run now) and the receipt's
43
+ # reason for each, beside :off and WorkerWakes#wake_hold's.
44
+ CALLER_HOLDS = %i[queued exit leaving before_turn].freeze
45
+
46
+ # Take what peers wrote since the last look: every <peer>/in folder,
47
+ # whatever its link (the link gates the say only). A declared peer's
48
+ # messages become notes (in order: by +at+, then peer, then serial;
49
+ # within one peer serial order); an undeclared peer's are refused and
50
+ # stay untaken; a bad file is refused and taken. Notes, the session
51
+ # saved, then the receipts (at least once; the note ids dedupe).
52
+ # +hold+: why a wake can't run now (CALLER_HOLDS), nil when it may: the
53
+ # batch wakes when any message asked, +hold+ is nil and the gate is
54
+ # open (#mail_hold); within the start grace such a batch waits,
55
+ # untaken (#mail_wake_waiting?). Not before the first turn, unless
56
+ # one is about to run (+hold+ :before_turn).
57
+ # @return [MailWake, nil] the wake turn to run now
58
+ # @raise [SystemCallError, IOError] the caller logs it
59
+ def absorb_mail(hold: nil)
60
+ @mail_wake_waiting = false
61
+ return nil unless @peer_registry && @peer_receipts
62
+ return nil unless hold == :before_turn || conversation_started?
63
+ return nil if @stopped.call
64
+
65
+ signature = mail_signature
66
+ return nil if signature == @mail_signature
67
+
68
+ items = mail_items
69
+ replayed = recover_crashed_wake(items)
70
+ taken = items.select(&:taken?)
71
+ asking = taken.select(&:asked).last
72
+ @wakes.pause! if replayed && asking
73
+ reason = (replayed && asking ? :paused : hold) || (mail_hold(asking) if asking)
74
+ if asking && reason.nil? && @wakes.in_grace?
75
+ @mail_wake_waiting = true
76
+ return nil
77
+ end
78
+
79
+ waking = asking && reason.nil? ? SecureRandom.uuid : nil
80
+ plain = add_mail_notes(taken, waking, asking)
81
+ return nil if taken.any? && !save(:mail)
82
+
83
+ @peer_receipts.absorbed(items.map { |item| receipt_item(item) }, waking: waking, hold: reason)
84
+ @mail_signature = signature
85
+ mail_held(asking, reason)
86
+ waking && MailWake.new(peer: asking.peer, turn_id: waking, plain_note: plain, agreed: agreed?(asking))
87
+ end
88
+
89
+ # Whether #absorb_mail left a batch that would wake untaken for the
90
+ # start grace (the idle loop looks again when it ends).
91
+ def mail_wake_waiting? = @mail_wake_waiting == true
92
+
93
+ private
94
+
95
+ # Names and mtimes of the session's mailbox folders, each pass.
96
+ def mail_signature
97
+ PeerMailbox.peers(@session.id, state_dir: @state_dir).map do |peer|
98
+ dir = PeerMailbox.in_dir(@session.id, peer, state_dir: @state_dir)
99
+ [peer, File.exist?(dir) ? File.mtime(dir).to_r : nil]
100
+ end
101
+ end
102
+
103
+ # Every peer's messages past its taken, checked (PeerMessage.from_file),
104
+ # in the batch's order.
105
+ def mail_items
106
+ PeerMailbox.peers(@session.id, state_dir: @state_dir).flat_map do |peer|
107
+ declared = @peer_registry.declared?(peer)
108
+ last = nil
109
+ PeerMailbox.messages(@session.id, peer, since: @peer_receipts.peer(peer).taken, state_dir: @state_dir).map do |entry|
110
+ raise IOError, "unreadable peer mail #{peer} ##{entry.serial}" if entry.is_a?(PeerMailbox::BadFile) && entry.reason == "unreadable"
111
+
112
+ message = entry.is_a?(PeerMailbox::PeerMessage) ? entry : nil
113
+ at = message ? Time.iso8601(message.at) : Time.at(0)
114
+ last = at unless last && last > at
115
+ refused = if !declared then "undeclared"
116
+ elsif message.nil? then "invalid"
117
+ end
118
+ note_id = "peer-#{peer}-#{@peer_receipts.box_for(peer)}-#{entry.serial}" if refused.nil?
119
+ MailItem.new(peer: peer, message: refused ? nil : message, serial: entry.serial, note_id: note_id,
120
+ refused: refused, order: [last, peer, entry.serial])
121
+ end
122
+ end.sort_by(&:order)
123
+ end
124
+
125
+ # Why the batch's newest asking message can't wake chi now: :off
126
+ # (peer.turns is 0), else WorkerWakes#wake_hold's (an agreeing
127
+ # message is held by session.max_wakes only); nil: it may.
128
+ def mail_hold(asking)
129
+ return :off if @wakes.peer_max.zero?
130
+
131
+ @wakes.wake_hold(awaiting_continue: @awaiting_continue.call, peer: !agreed?(asking))
132
+ end
133
+
134
+ def agreed?(item) = PeerNote.agrees?(item&.message&.summary)
135
+
136
+ # The notes, in order; the last one starts the wake turn (+waking+),
137
+ # with the wake line of the newest message that asked (+asking+).
138
+ # @return [Hash, nil] the turn start's plain note
139
+ def add_mail_notes(items, waking, asking)
140
+ plain = nil
141
+ cap = @mail_cap&.call
142
+ items.each_with_index do |item, index|
143
+ full = waking && item.asked
144
+ note = mail_note(item, cap: cap, held: !full)
145
+ if waking && index == items.size - 1
146
+ plain = note
147
+ note = note.merge(text: "#{note[:text]}\n#{mail_wake_line(asking, cap)}", turn_start: true, turn_id: waking)
148
+ end
149
+ @engine.add_context_note(@session, note)
150
+ end
151
+ plain
152
+ end
153
+
154
+ # A message's plain note: its text up to +cap+ (+held+: up to
155
+ # PeerNote::HELD_CHARS), else a pointer at it.
156
+ def mail_note(item, cap:, held:)
157
+ message = item.message
158
+ label = PeerMailbox.label(item.peer)
159
+ body = PeerNote.body(message.text, cap, held: held)
160
+ box = @peer_receipts.box_for(item.peer)
161
+ text = PeerNote.message_text(label: label, serial: item.serial, summary: message.summary, body: body,
162
+ read: PeerNote.read_pointer(item.peer, item.serial, box: box))
163
+ { note_id: item.note_id, text: text, source: PeerNote.source(label), created_at: Time.now.utc.iso8601,
164
+ peer: PeerNote.payload(peer: item.peer, label: label, re: message.re, summary: message.summary,
165
+ serial: item.serial, inline: body.key?(:text)).merge("box" => box) }
166
+ end
167
+
168
+ # The wake line of +asking+ (the newest message that asked): the
169
+ # closing one when it agrees, the first-word one with no re.
170
+ def mail_wake_line(asking, cap)
171
+ body = PeerNote.body(asking.message.text, cap)
172
+ agreed = agreed?(asking)
173
+ PeerNote.message_wake_line(PeerMailbox.label(asking.peer), PeerNote.read_pointer(asking.peer, asking.serial,
174
+ box: @peer_receipts.box_for(asking.peer)),
175
+ @wakes.peer_turns, body: body, agreed: agreed, first: !agreed && asking.message.re.nil?)
176
+ end
177
+
178
+ # A note of this batch already in the conversation: written and saved
179
+ # before a crash, its receipt not. A turn start among them goes back
180
+ # plain (#unmark_wake's way). Return whether any note was present so
181
+ # the batch cannot wake again even when its saved notes were plain.
182
+ def recover_crashed_wake(items)
183
+ ids = items.filter_map(&:note_id)
184
+ present = Array(@session.messages).select { |m| ids.include?(m[:note_id]) }
185
+ return false if present.empty?
186
+
187
+ marked_notes = present.select { |m| m[:turn_start] }
188
+ return true if marked_notes.empty?
189
+
190
+ messages = @engine.messages_checkpoint
191
+ marked_notes.each do |marked|
192
+ item = items.find { |i| i.note_id == marked[:note_id] }
193
+ index = messages.index { |m| m[:note_id] == marked[:note_id] }
194
+ messages[index] = ContextNote.message(**mail_note(item, cap: @mail_cap&.call, held: !item.asked)) if index
195
+ end
196
+ @engine.rollback_to(messages)
197
+ @wakes.pause!
198
+ Log.warn(:peer, "mail_wake_recovered", notes: marked_notes.size)
199
+ true
200
+ end
201
+
202
+ def receipt_item(item) = PeerReceipts::Absorbed.new(peer: item.peer, serial: item.serial, asked: item.asked,
203
+ refused: item.refused)
204
+
205
+ # The UIs hear once that a peer's message waits for the user's next
206
+ # one when a wake budget held it (as #peer_held does for the context
207
+ # path).
208
+ def mail_held(asking, reason)
209
+ key = { max_wakes: ChildRing::MAX_WAKES_KEY, peer_turns: WorkerWakes::PEER_TURNS_KEY }[reason]
210
+ peer_held(PeerMailbox.label(asking.peer), key) if asking && key
211
+ end
212
+ end
213
+ end
214
+ end
@@ -19,6 +19,7 @@ require_relative "turn_origin"
19
19
  require_relative "participants"
20
20
  require_relative "tools/task_record"
21
21
  require_relative "worker_wakes"
22
+ require_relative "worker_inbound/mail"
22
23
 
23
24
  module Samagotchi
24
25
  # What comes into a worker's session between turns, each kind with its
@@ -29,11 +30,16 @@ module Samagotchi
29
30
  # - attached context (#absorb_context): once the conversation started,
30
31
  # saved, then the subscriptions written; a source asking to wake may
31
32
  # start a context wake turn (a ContextWake);
33
+ # - a peer's mail (#absorb_mail, MailPart): one note per message, saved,
34
+ # then the receipts written; a message asking to wake may start a mail
35
+ # wake turn (a MailWake);
32
36
  # - the first prompt (#take_initial_prompt): taken once and saved
33
37
  # cleared; as a command (#initial_command?) the session is saved idle;
34
38
  # - an input file (#take_input): a Prompt for a turn, whose own save is
35
39
  # the turn's, or a command queued.
36
40
  class WorkerInbound
41
+ include MailPart
42
+
37
43
  # One context wake per source in this long (D5): later changes inside
38
44
  # it arrive as notes.
39
45
  CONTEXT_WAKE_WINDOW = 600
@@ -55,16 +61,9 @@ module Samagotchi
55
61
  # the turn +turn_id+.
56
62
  ContextWake = Data.define(:delivery, :turn_id) do
57
63
  def name = delivery.name
58
- # For a peer agent's answer (its own budget, WorkerWakes#peer_open?).
59
- def peer? = !delivery.peer.nil?
60
- # Whether the wake counts toward context.peer_turns: a peer's answer
61
- # that agrees closes the round and counts toward session.max_wakes only.
62
- def peer_turn? = peer? && !delivery.agreed
63
64
  def origin = TurnOrigin.new(client_id: "#{ClientId::CONTEXT_PREFIX}#{name}")
64
- # The plain note #unmark_wake puts back: with the wake note's text
65
- # when only that held it (ContextAbsorber::Delivery#wake_plain), so a
66
- # failed wake turn keeps the text it marked read.
67
- def note = delivery.wake_plain || delivery.note
65
+ # The plain note #unmark_wake puts back.
66
+ def note = delivery.note
68
67
  end
69
68
 
70
69
  # A task finish wake turn to run (TaskWatch, TaskFinishNote): its wake
@@ -101,8 +100,13 @@ module Samagotchi
101
100
  # @param queue_command [#call] (line, client_id, after_file, enqueued_id)
102
101
  # queues a session command for the loop's next pass; after_file is the
103
102
  # input file it came in, or nil
103
+ # @param peer_registry [PeerRegistry, nil] the peers the loaded bundles
104
+ # declared (nil: no mail is taken)
105
+ # @param peer_receipts [PeerReceipts, nil] the worker's receipts
106
+ # @param mail_cap [#call, nil] the most characters of a peer's text a
107
+ # wake turn's note holds (the tool output cap)
104
108
  def initialize(session:, state_dir:, session_dir:, engine:, event_log:, turn_state:, context_absorber:, wakes:,
105
- awaiting_continue:, stopped:, queue_command:)
109
+ awaiting_continue:, stopped:, queue_command:, peer_registry: nil, peer_receipts: nil, mail_cap: nil)
106
110
  @session = session
107
111
  @state_dir = state_dir
108
112
  @session_dir = session_dir
@@ -114,6 +118,9 @@ module Samagotchi
114
118
  @awaiting_continue = awaiting_continue
115
119
  @stopped = stopped
116
120
  @queue_command = queue_command
121
+ @peer_registry = peer_registry
122
+ @peer_receipts = peer_receipts
123
+ @mail_cap = mail_cap
117
124
  @initial_prompt_taken = false
118
125
  @context_wake_waiting = false
119
126
  # The link this one continues, when its notes may still come here
@@ -209,14 +216,17 @@ module Samagotchi
209
216
 
210
217
  # A failed wake turn kept nothing but its note: the note goes back to
211
218
  # a plain note (no turn start, the background wording), so a reload
212
- # draws no empty turn for it. +wake+: a ContextWake or a TaskWake.
219
+ # draws no empty turn for it. +wake+: a ContextWake, a TaskWake or a
220
+ # MailWake.
221
+ # @return [Boolean] whether it put one back
213
222
  def unmark_wake(wake)
214
223
  messages = @engine.messages_checkpoint
215
224
  index = messages.index { |m| m[:turn_start] && m[:turn_id] == wake.turn_id }
216
- return unless index
225
+ return false unless index
217
226
 
218
227
  messages[index] = ContextNote.message(**wake.note)
219
228
  @engine.rollback_to(messages)
229
+ true
220
230
  end
221
231
 
222
232
  # spawn_session hands the first prompt over in last_prompt, but
@@ -348,53 +358,43 @@ module Samagotchi
348
358
  # context.wake is on, the wake budget is open (WorkerWakes#context_open?:
349
359
  # no continue offer, not paused, under session.max_wakes, past the start
350
360
  # grace) and the source hasn't woken the session in the last
351
- # CONTEXT_WAKE_WINDOW; a peer's answer (Delivery#peer) has no window but
352
- # the peer budget (WorkerWakes#peer_open?). The others stay plain notes.
353
- # Within the start grace a change is a note: it came while the session
354
- # was away. A peer's answer held by either budget is announced once.
361
+ # CONTEXT_WAKE_WINDOW. The others stay plain notes. Within the start
362
+ # grace a change is a note: it came while the session was away. The
363
+ # gate reads WorkerWakes#wake_hold, and so does
364
+ # #context_wake_waiting_for?. (A peer agent's messages have their own
365
+ # path and budget: #absorb_mail.)
355
366
  def context_wake_for(batch, now: Time.now)
356
367
  candidates = batch.deliveries.select(&:wake_note)
357
368
  return nil if candidates.empty? || !context_wakes_on?
369
+ return nil unless @wakes.context_open?(awaiting_continue: @awaiting_continue.call, names: candidates.map(&:name))
358
370
 
359
- unless @wakes.context_open?(awaiting_continue: @awaiting_continue.call, names: candidates.map(&:name))
360
- peer_held(candidates.find(&:peer), ChildRing::MAX_WAKES_KEY) if @wakes.spent?
361
- return nil
362
- end
363
-
364
- held = []
365
- waking = candidates.select do |delivery|
366
- next !woke_lately?(delivery.subscription, now) unless delivery.peer
367
-
368
- next true if @wakes.peer_open?(name: delivery.name)
369
-
370
- held << delivery
371
- false
372
- end
373
- peer_held(held.first, WorkerWakes::PEER_TURNS_KEY)
374
- waking.first
371
+ candidates.find { |delivery| !woke_lately?(delivery.subscription, now) }
375
372
  end
376
373
 
374
+ # Whether a wake in +batch+ would run but for the start grace: the
375
+ # context gate open apart from it (WorkerWakes#context_ready?), and a
376
+ # candidate the 10-minute window lets through.
377
377
  def context_wake_waiting_for?(batch)
378
378
  return false unless @wakes.in_grace?
379
379
 
380
380
  candidates = batch.deliveries.select(&:wake_note)
381
381
  return false if candidates.empty? || !context_wakes_on?
382
- return false unless @wakes.context_ready?(awaiting_continue: @awaiting_continue.call, names: candidates.map(&:name))
383
382
 
384
- candidates.any? do |delivery|
385
- delivery.peer ? @wakes.peer_in_a_row < @wakes.peer_turns : !woke_lately?(delivery.subscription, Time.now)
386
- end
383
+ awaiting = @awaiting_continue.call
384
+ return false unless @wakes.context_ready?(awaiting_continue: awaiting, names: candidates.map(&:name))
385
+
386
+ candidates.any? { |delivery| !woke_lately?(delivery.subscription, Time.now) }
387
387
  end
388
388
 
389
- # A peer's answer waits as a note: the UIs hear it once per
390
- # interactive input (WorkerWakes#notice_peer_budget!). +key+: the
391
- # budget that holds it.
392
- def peer_held(delivery, key)
393
- return unless delivery && @wakes.notice_peer_budget!
389
+ # A peer's message waits as a note (#absorb_mail): the UIs hear it once
390
+ # per interactive input (WorkerWakes#notice_peer_budget!). +label+: the
391
+ # peer's name ("Codex"), +key+: the budget that holds it.
392
+ def peer_held(label, key)
393
+ return unless label && @wakes.notice_peer_budget!
394
394
 
395
395
  turns = key == ChildRing::MAX_WAKES_KEY ? @wakes.max : @wakes.peer_turns
396
396
  @event_log.announce(type: :hook_notice, hook: "context", level: :info, between_turns: true,
397
- text: "#{delivery.peer} answered again; it waits as a note for your next message " \
397
+ text: "#{label} answered again; it waits as a note for your next message " \
398
398
  "(#{turns} wake turn#{"s" if turns != 1} in a row, #{key})")
399
399
  end
400
400
 
@@ -409,10 +409,7 @@ module Samagotchi
409
409
 
410
410
  # +batch+ with +waking+'s subscription recording the wake (the 10-minute window).
411
411
  def woken(batch, waking)
412
- # The wake note went in: its own read mark when it holds a text the
413
- # plain note doesn't (ContextAbsorber::Delivery#wake_subscription).
414
- subscription = waking.wake_subscription || waking.subscription
415
- stamped = waking.with(subscription: subscription.with(wakes_at: Time.now.iso8601))
412
+ stamped = waking.with(subscription: waking.subscription.with(wakes_at: Time.now.iso8601))
416
413
  batch.with(deliveries: batch.deliveries.map { |delivery| delivery == waking ? stamped : delivery })
417
414
  end
418
415
  end
@@ -14,18 +14,18 @@ module Samagotchi
14
14
  # started for until the turn's first boundary takes them (#hand_over,
15
15
  # #take_handed).
16
16
  #
17
- # A peer agent's answers (PeerSources) have a budget of their own on top:
18
- # context.peer_turns wake turns in a row, reset only by input typed in the
19
- # web or a TUI (ClientId.interactive?), not by chi send, which a peer can
20
- # run (docs/context.md, Waking).
17
+ # A peer agent's messages (its mailbox: WorkerInbound#absorb_mail) have a
18
+ # budget of their own on top: peer.turns wake turns in a row,
19
+ # reset only by input typed in the web or a TUI (ClientId.interactive?),
20
+ # not by chi send, which a peer can run (docs/peers.md).
21
21
  class WorkerWakes
22
- PEER_TURNS_KEY = "context.peer_turns"
22
+ PEER_TURNS_KEY = "peer.turns"
23
23
  PEER_TURNS_DEFAULT = 3
24
24
 
25
25
  # @param grace [Numeric] seconds after the start with no wake turn
26
26
  # @param clock [#call] monotonic seconds
27
27
  # @param max [#call, nil] the budget; nil reads session.max_wakes
28
- # @param peer_max [#call, nil] the peer budget; nil reads context.peer_turns
28
+ # @param peer_max [#call, nil] the peer budget; nil reads peer.turns
29
29
  def initialize(grace:, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, max: nil, peer_max: nil)
30
30
  @grace = grace
31
31
  @clock = clock
@@ -58,7 +58,7 @@ module Samagotchi
58
58
  ChildRing::MAX_WAKES_DEFAULT
59
59
  end
60
60
 
61
- # context.peer_turns: 0 (or less) is 0, the peer policy off.
61
+ # peer.turns: 0 (or less) is 0, the peer policy off.
62
62
  def peer_max
63
63
  return @peer_max.call if @peer_max
64
64
 
@@ -68,7 +68,7 @@ module Samagotchi
68
68
  PEER_TURNS_DEFAULT
69
69
  end
70
70
 
71
- # The peer wake turns that may run in a row: context.peer_turns, or
71
+ # The peer wake turns that may run in a row: peer.turns, or
72
72
  # session.max_wakes when it is lower; 0 when the peer policy is off.
73
73
  def peer_turns
74
74
  peers = peer_max
@@ -78,13 +78,22 @@ module Samagotchi
78
78
  # Whether session.max_wakes holds wake turns now.
79
79
  def spent? = @in_a_row >= max
80
80
 
81
- # Whether a peer's answer may start a wake turn by the peer budget
82
- # (#context_open? asked first). +name+: the source, for the log line.
83
- def peer_open?(name:)
84
- return true if @peer_in_a_row < peer_turns
81
+ # Why a wake (an attached context source's; +peer+: a peer agent's
82
+ # answer) is held now, apart from the start grace, which is the
83
+ # callers' (a wake may wait it out): :paused (a failed wake turn, until
84
+ # a human's input), :continue (a continue offer waits), :max_wakes
85
+ # (session.max_wakes spent), :peer_turns (a peer's, the peer budget
86
+ # spent: peer.turns, or 0 with the peer policy off); nil when
87
+ # nothing holds it. The first that applies, in that order. It logs
88
+ # nothing: the callers write the lines.
89
+ # @return [Symbol, nil]
90
+ def wake_hold(awaiting_continue:, peer:)
91
+ return :paused if @paused
92
+ return :continue if awaiting_continue
93
+ return :max_wakes if @in_a_row >= max
94
+ return :peer_turns if peer && @peer_in_a_row >= peer_turns
85
95
 
86
- Log.info(:worker, "context_wake_held", reason: "peer_turns", names: name)
87
- false
96
+ nil
88
97
  end
89
98
 
90
99
  # For delegate reports: :due when a wake turn may run now (the block
@@ -110,13 +119,9 @@ module Samagotchi
110
119
  # The context wake gates apart from start grace; used to decide whether
111
120
  # a wake must remain pending until that grace ends.
112
121
  def context_ready?(awaiting_continue:, names:)
113
- return false if @paused || awaiting_continue
114
-
115
- if @in_a_row >= max
116
- Log.info(:worker, "context_wake_held", reason: "max_wakes", names: names.join(","))
117
- return false
118
- end
119
- true
122
+ hold = wake_hold(awaiting_continue:, peer: false)
123
+ Log.info(:worker, "context_wake_held", reason: "max_wakes", names: names.join(",")) if hold == :max_wakes
124
+ hold.nil?
120
125
  end
121
126
 
122
127
  # For a background task that finished unseen (TaskWatch): no continue