samagotchi 0.183.0 → 0.185.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 (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +84 -1
  3. data/docs/architecture.md +12 -11
  4. data/docs/bundles.md +63 -36
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +3 -2
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +7 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -3
  12. data/docs/internals/bundles.md +6 -2
  13. data/docs/internals/engine.md +2 -1
  14. data/docs/internals/llm-context-forget.md +6 -0
  15. data/docs/internals/participants.md +5 -2
  16. data/docs/internals/prompt-caching.md +8 -1
  17. data/docs/internals/remote-sessions.md +22 -4
  18. data/docs/internals/session-lifecycle.md +1 -1
  19. data/docs/internals/web-frontend.md +37 -15
  20. data/docs/internals/web-push.md +11 -0
  21. data/docs/internals/working-set.md +238 -6
  22. data/docs/mcp-server.md +11 -3
  23. data/docs/memory.md +2 -1
  24. data/docs/plugins.md +6 -6
  25. data/docs/scheduling.md +19 -0
  26. data/docs/sessions.md +13 -3
  27. data/docs/sub-agent.md +48 -3
  28. data/docs/thin-clients.md +38 -12
  29. data/lib/samagotchi/agent_caller.rb +97 -0
  30. data/lib/samagotchi/bridge.rb +7 -7
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/check.rb +20 -2
  33. data/lib/samagotchi/bundle_manifest.rb +5 -1
  34. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  35. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  37. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  39. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  40. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  41. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  42. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  43. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  44. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/http_client.rb +96 -54
  47. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  49. data/lib/samagotchi/bundles/system/self_map.md +9 -2
  50. data/lib/samagotchi/client_id.rb +61 -1
  51. data/lib/samagotchi/command_intake.rb +16 -8
  52. data/lib/samagotchi/context_absorber.rb +212 -46
  53. data/lib/samagotchi/delivery.rb +15 -0
  54. data/lib/samagotchi/driver_command.rb +68 -0
  55. data/lib/samagotchi/engine/block_fix.rb +2 -2
  56. data/lib/samagotchi/engine/session.rb +14 -6
  57. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  58. data/lib/samagotchi/engine.rb +13 -5
  59. data/lib/samagotchi/engine_peers.rb +6 -0
  60. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  61. data/lib/samagotchi/mcp_command.rb +7 -2
  62. data/lib/samagotchi/mcp_server/http.rb +3 -3
  63. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  64. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  65. data/lib/samagotchi/mcp_server/tools.rb +11 -4
  66. data/lib/samagotchi/model_notes.rb +34 -12
  67. data/lib/samagotchi/objectives_track.rb +2 -1
  68. data/lib/samagotchi/owner_prompt.rb +5 -1
  69. data/lib/samagotchi/parent_report.rb +9 -5
  70. data/lib/samagotchi/plugin/peer.rb +10 -4
  71. data/lib/samagotchi/prompt_files.rb +11 -4
  72. data/lib/samagotchi/prompt_layout.rb +88 -0
  73. data/lib/samagotchi/prompt_part.rb +82 -20
  74. data/lib/samagotchi/reply_wait.rb +16 -4
  75. data/lib/samagotchi/schedule_command.rb +18 -4
  76. data/lib/samagotchi/schedules.rb +49 -14
  77. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  78. data/lib/samagotchi/send_command.rb +45 -8
  79. data/lib/samagotchi/session.rb +9 -1
  80. data/lib/samagotchi/session_access/ask.rb +58 -14
  81. data/lib/samagotchi/session_access/contract.rb +2 -0
  82. data/lib/samagotchi/session_access/exchange.rb +5 -2
  83. data/lib/samagotchi/session_access/local.rb +13 -3
  84. data/lib/samagotchi/session_access/remote.rb +18 -2
  85. data/lib/samagotchi/session_access.rb +4 -2
  86. data/lib/samagotchi/session_command_catalog.rb +8 -0
  87. data/lib/samagotchi/session_commands.rb +9 -0
  88. data/lib/samagotchi/session_continue.rb +4 -1
  89. data/lib/samagotchi/session_inbox.rb +17 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +58 -9
  92. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  93. data/lib/samagotchi/steer.rb +95 -20
  94. data/lib/samagotchi/system_prompt.rb +196 -161
  95. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  96. data/lib/samagotchi/tool_activity.rb +4 -0
  97. data/lib/samagotchi/tool_declarations.rb +22 -1
  98. data/lib/samagotchi/tool_names.rb +4 -0
  99. data/lib/samagotchi/toolkit.rb +3 -2
  100. data/lib/samagotchi/tools/ask_session.rb +208 -0
  101. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  102. data/lib/samagotchi/tools/builtins.rb +5 -0
  103. data/lib/samagotchi/tools/memory.rb +11 -3
  104. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  105. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  106. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  107. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  108. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  109. data/lib/samagotchi/version.rb +1 -1
  110. data/lib/samagotchi/visitor.rb +37 -0
  111. data/lib/samagotchi/web/app.rb +2 -3
  112. data/lib/samagotchi/web/ask_routes.rb +95 -23
  113. data/lib/samagotchi/web/mcp_route.rb +7 -4
  114. data/lib/samagotchi/web/message_display.rb +15 -2
  115. data/lib/samagotchi/web/public/app.js +1 -1
  116. data/lib/samagotchi/web/public/block_fix.js +11 -3
  117. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  118. data/lib/samagotchi/web/public/history_shape.js +3 -1
  119. data/lib/samagotchi/web/public/index.html +8 -0
  120. data/lib/samagotchi/web/public/peer_links.js +27 -4
  121. data/lib/samagotchi/web/public/peer_note.js +19 -3
  122. data/lib/samagotchi/web/public/peer_text.js +45 -0
  123. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  124. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  125. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  126. data/lib/samagotchi/web/public/session_actions.js +0 -9
  127. data/lib/samagotchi/web/public/turn_events.js +19 -0
  128. data/lib/samagotchi/web/public/working_set_view.js +178 -23
  129. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  130. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  131. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  132. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  133. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  134. data/lib/samagotchi/web/push/notifier.rb +33 -6
  135. data/lib/samagotchi/web/server.rb +1 -1
  136. data/lib/samagotchi/web/session_control.rb +1 -1
  137. data/lib/samagotchi/web/session_create.rb +11 -7
  138. data/lib/samagotchi/web/session_hub.rb +26 -4
  139. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  140. data/lib/samagotchi/worker/command_queue.rb +5 -2
  141. data/lib/samagotchi/worker/senders.rb +79 -0
  142. data/lib/samagotchi/worker.rb +21 -18
  143. data/lib/samagotchi/worker_inbound.rb +12 -4
  144. data/lib/samagotchi/worker_link.rb +2 -2
  145. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  146. data/lib/samagotchi/worker_wakes.rb +12 -0
  147. data/lib/samagotchi/working_set.rb +162 -90
  148. data/lib/samagotchi/working_set_locator.rb +221 -0
  149. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  150. data/lib/samagotchi/working_set_part.rb +281 -0
  151. metadata +13 -1
@@ -51,7 +51,9 @@ module Samagotchi
51
51
 
52
52
  # What a subscriber gets: `session` with {session: summary} for an
53
53
  # upsert, `session_gone` with {id:} for a removal, `chi` with
54
- # the #chi_state fields when chi version state changes. seq is monotonic per
54
+ # the #chi_state fields when chi version state changes, `chi_notice`
55
+ # (#publish_notice) and `schedule_disabled` (#publish_disabled) for
56
+ # the Push::Notifier. seq is monotonic per
55
57
  # hub, for the log's sake: there is no replay.
56
58
  Event = Struct.new(:type, :seq, :data, keyword_init: true)
57
59
 
@@ -150,7 +152,7 @@ module Samagotchi
150
152
  # +full_probe_interval+ it also probes every session's owner and
151
153
  # gives the retention sweep its chance (it used to run on
152
154
  # GET /api/sessions, which the page no longer calls).
153
- def scan
155
+ def scan(tick: true)
154
156
  full = @monitor.synchronize do
155
157
  full = full_probe_due?
156
158
  SessionContinue.repair_interrupted(state_dir: @state_dir)
@@ -163,7 +165,7 @@ module Samagotchi
163
165
  end
164
166
  sweep_if_due if full
165
167
  # Outside the projection's lock: a firing can wait for a recap.
166
- schedule_tick
168
+ schedule_tick if tick
167
169
  nil
168
170
  end
169
171
 
@@ -385,7 +387,10 @@ module Samagotchi
385
387
  end
386
388
 
387
389
  def run_schedule_tick
388
- Samagotchi::Schedules.new(state_dir: @state_dir).tick
390
+ schedules = Samagotchi::Schedules.new(state_dir: @state_dir)
391
+ now = Time.now
392
+ result = schedules.tick(now: now)
393
+ publish_disabled(result, now) if result.is_a?(Samagotchi::Schedules::Tick)
389
394
  rescue StandardError => e
390
395
  Log.warn(:web, "schedule_tick_failed", error: e.class.name, msg: e.message)
391
396
  ensure
@@ -395,6 +400,23 @@ module Samagotchi
395
400
  end
396
401
  end
397
402
 
403
+ # A recurring schedule this tick turned off (Schedules::Outcome#disabled):
404
+ # one `schedule_disabled` event each, for the Push::Notifier (the page has
405
+ # no listener), emitted the way #publish_notice does. +at+ is the tick's
406
+ # time; +session_id+ is the session the schedule acts on.
407
+ def publish_disabled(result, now)
408
+ result.outcomes.select(&:disabled).each do |outcome|
409
+ entry = outcome.entry
410
+ kind = outcome.status == "skipped" ? "skipped" : "failed"
411
+ data = { id: outcome.id, title: outcome.title, kind: kind,
412
+ count: kind == "skipped" ? entry.skips : entry.failures,
413
+ reason: outcome.detail, session_id: outcome.session_id, at: now.utc.iso8601 }
414
+ @monitor.synchronize { emit("schedule_disabled", data) }
415
+ rescue StandardError => e
416
+ Log.warn(:web, "schedule_disabled_failed", id: outcome.id, error: e.class.name, msg: e.message)
417
+ end
418
+ end
419
+
398
420
  # A change (the first look too, unless it finds nothing) is a `chi`
399
421
  # event: chi web's terminal line and the open tabs hear it.
400
422
  def check_installed
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "uri"
4
4
  require_relative "../working_set"
5
+ require_relative "../working_set_part"
5
6
  require_relative "../llm_context_view"
6
7
  require_relative "../session_setting"
7
8
  require_relative "../memory_paths"
@@ -18,6 +19,14 @@ module Samagotchi
18
19
  # llm_context summary names, its folder (+cwd+) and its +pins+.
19
20
  Source = Data.define(:messages, :strategy, :cwd, :pins)
20
21
 
22
+ # The routes (App::ROUTES takes them whole): the set, an item's
23
+ # timeline, a prompt part as sent. Before /api/sessions/:id.
24
+ ROUTES = [
25
+ ["GET", %r{\A/api/sessions/([^/]+)/working_set\z}, :handle_working_set, :participant, :session],
26
+ ["GET", %r{\A/api/sessions/([^/]+)/working_set/item\z}, :handle_working_set_item, :owner, :session],
27
+ ["GET", %r{\A/api/sessions/([^/]+)/working_set/part\z}, :handle_working_set_part, :owner, :session]
28
+ ].freeze
29
+
21
30
  private
22
31
 
23
32
  # GET /api/sessions/:id/working_set: the working set as the model has
@@ -33,11 +42,25 @@ module Samagotchi
33
42
  # the session's messages, behind that turn's events, and the page
34
43
  # keeps theirs (working_set.js newerSnapshot).
35
44
  # A participant's is filtered (ParticipantView.working_set: the
36
- # project's files only).
45
+ # project's files only). The owner's also says which "From the start"
46
+ # parts are stale (parts: [{key, state}], WorkingSetPart.states: the
47
+ # source's text now differs from what was sent; no field: none is),
48
+ # whichever of the
49
+ # three answered, with the parts the part route reads (#prompt_source):
50
+ # so a live idle worker's and an older worker's sessions get them too.
51
+ # A stale part chi changed itself carries by_chi (the same source's
52
+ # messages; while a turn runs only a current one). Never a
53
+ # participant's (no prompt text, D4).
37
54
  def handle_working_set(req, id)
38
55
  session = @session_class.load(id, state_dir: default_state_dir)
39
- set = working_set_payload(id, session)
40
- return json_response(200, set) if principal(req).owner?
56
+ live = bridge_get_json(id, "snapshot")
57
+ set = working_set_payload(session, live)
58
+ if principal(req).owner?
59
+ parts, messages = prompt_source(live, session)
60
+ parts = WorkingSetPart.states(parts, root: MemoryPaths.system_dir, cwd: session.working_directory, messages: messages,
61
+ running: set[:running] == true)
62
+ return json_response(200, parts.empty? ? set : set.merge(parts: parts))
63
+ end
41
64
 
42
65
  viewer = participant_viewer(req, session)
43
66
  # Redacted as the stream's event is (ParticipantView.event): a file name may hold a secret's shape.
@@ -91,8 +114,73 @@ module Samagotchi
91
114
  json_response(200, body)
92
115
  end
93
116
 
94
- def working_set_payload(id, session)
117
+ # GET /api/sessions/:id/working_set/part?key=[&now=1]: one "From the
118
+ # start" part as chi sent it (WorkingSetPart.answer: the slice of the
119
+ # saved head, or the line that says why not and, under a changed head,
120
+ # the source now). +now+: with the slice, the source now and its diff
121
+ # (a stale row's "now" tab) and when chi gets it (rebuild: restart with
122
+ # a live worker, else next_turn). Owner only: participants see no prompt text. The parts and
123
+ # messages[0] come from one source: a live worker's complete snapshot
124
+ # frame, else the session file. The file is read only when the snapshot
125
+ # is missing or a source lookup needs the session's working directory.
126
+ def handle_working_set_part(req, id)
127
+ key = req.GET["key"].to_s
128
+ return error_response(400, "invalid_part", WorkingSetPart::INVALID) if key.strip.empty?
129
+
95
130
  live = bridge_get_json(id, "snapshot")
131
+ source = prompt_snapshot(live)
132
+ if source
133
+ parts, messages = source
134
+ cwd = live["working_directory"]
135
+ if cwd.nil? && prompt_part_needs_cwd?(parts, messages, key, req.GET["now"] == "1")
136
+ session = @session_class.load(id, state_dir: default_state_dir)
137
+ cwd = session.working_directory
138
+ end
139
+ else
140
+ session = @session_class.load(id, state_dir: default_state_dir)
141
+ parts = session.prompt_parts
142
+ messages = session.messages
143
+ cwd = session.working_directory
144
+ end
145
+ body = WorkingSetPart.answer(parts: parts, messages: messages, key: key,
146
+ older_worker: !live.nil? && WorkingSetPart.older_worker?(live.dig("snapshot", "chi_version")),
147
+ running: !live&.dig("snapshot", "current_turn").nil?, root: MemoryPaths.system_dir,
148
+ cwd: cwd, now: req.GET["now"] == "1", live: !live.nil?)
149
+ return error_response(404, "unknown_part", WorkingSetPart::UNKNOWN) unless body
150
+
151
+ json_response(200, body)
152
+ end
153
+
154
+ # A complete live snapshot source for the part route; otherwise nil.
155
+ def prompt_snapshot(live)
156
+ state = live.is_a?(Hash) ? live["session_state_snapshot"] : nil
157
+ snapshot = live.is_a?(Hash) ? live["snapshot"] : nil
158
+ return unless state.is_a?(Hash) && state["prompt_parts"].is_a?(Array) &&
159
+ snapshot.is_a?(Hash) && snapshot["messages"].is_a?(Array)
160
+
161
+ [state["prompt_parts"], snapshot["messages"]]
162
+ end
163
+
164
+ def prompt_part_needs_cwd?(parts, messages, key, now)
165
+ parts = PromptPart.list(parts)
166
+ index = PromptPart.keys(parts).index(key)
167
+ part = parts[index]
168
+ return false unless part && part.at && WorkingSet::Locator::FETCHED.include?(part.kind)
169
+
170
+ head = Array(messages).first
171
+ text = head.is_a?(Hash) && ContextNote.system_head?(head) ? (head[:content] || head["content"]) : nil
172
+ text.is_a?(String) && (now || PromptPart.digest_of(text, 16) != part.head)
173
+ end
174
+
175
+ # Prompt data for the working-set list route, which already loads the session.
176
+ def prompt_source(live, session)
177
+ state = live.is_a?(Hash) ? live["session_state_snapshot"] : nil
178
+ return [state["prompt_parts"], Array(live.dig("snapshot", "messages"))] if state.is_a?(Hash) && state["prompt_parts"].is_a?(Array)
179
+
180
+ [session.prompt_parts, session.messages]
181
+ end
182
+
183
+ def working_set_payload(session, live)
96
184
  worker_snapshot = live && live["snapshot"]
97
185
  running = !worker_snapshot&.dig("current_turn").nil?
98
186
  turn_set = running && running_working_set(live["snapshot"]["working_set"])
@@ -114,7 +202,7 @@ module Samagotchi
114
202
  def working_set_source(live, session)
115
203
  messages = live_or_saved(live && live["snapshot"], "messages") { session.messages }
116
204
  # A snapshot's entries have string keys (paired_runs reads symbols).
117
- messages = Array(messages).map { |message| message.is_a?(Hash) ? message.transform_keys(&:to_sym) : message }
205
+ messages = WorkingSetPart.symbolized(messages)
118
206
  llm_context = SessionSetting::LLM_CONTEXT.snapshot_value(live && live["session_state_snapshot"]) do
119
207
  SessionSetting::LLM_CONTEXT.saved_summary(session, registry: host_registry)
120
208
  end
@@ -218,9 +218,12 @@ module Samagotchi
218
218
  def confirm?(command) = ClientId.interactive?(command.client_id) && !command.card
219
219
 
220
220
  # Whether +command+ is a parent agent's (chi answer's marker, which chi
221
- # send and a parent's attach give a /continue yes too): held to
221
+ # send and a parent's attach give a /continue yes too, or an agent's
222
+ # id that reached the worker unmapped): held to
222
223
  # guardrails.parent_answers (SessionCommands#continue_answer).
223
- def as_parent?(command) = command.client_id.to_s == ClientId::CLI_ANSWER
224
+ def as_parent?(command)
225
+ command.client_id.to_s == ClientId::CLI_ANSWER || ClientId.agent?(command.client_id)
226
+ end
224
227
 
225
228
  # Whether +command+ is a user's at a UI (a web tab, a chi TUI, a card's
226
229
  # click), not a parent agent's: only such a line loosens
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../archive_store"
4
+ require_relative "../child_reports"
5
+ require_relative "../client_id"
6
+ require_relative "../log"
7
+ require_relative "../turn_checkpoint"
8
+ require_relative "../visitor"
9
+
10
+ module Samagotchi
11
+ class Worker
12
+ # Who a turn's input came from and what it does to the session: the
13
+ # owner's input (#user_input: un-archive, wake reset, held reports), the
14
+ # driver's (the same but the un-archive), a visitor's count toward
15
+ # session.max_wakes and its refusal (#count_visitor, #refuse_visitor),
16
+ # and the one seat for refusing a queued turn (#refuse_queued_turn).
17
+ # Reads @session, @session_id, @state_dir, @session_dir, @wakes,
18
+ # @child_reports and @event_log.
19
+ module SendersPart
20
+ private
21
+
22
+ # A visitor's turn (an agent's that doesn't drive the session: Visitor)
23
+ # counts toward session.max_wakes, the budget wake turns use, before
24
+ # anything else runs for it (no start grace, context.wake or pause
25
+ # gate: its sender asked for it).
26
+ # @return [Boolean] false when the budget is spent: refuse it
27
+ def count_visitor
28
+ return false if @wakes.spent?
29
+
30
+ @wakes.count!
31
+ true
32
+ end
33
+
34
+ # The owner's input (ClientId.owner?) un-archives the session; a
35
+ # delegate's, a plugin's, a reminder's or a participant's doesn't.
36
+ # It also resets the wakes (budget and pause); input typed in the web or
37
+ # a TUI the peer wakes too (chi send doesn't: a peer can run it).
38
+ def user_input(client_id)
39
+ # The session's driver (an agent: Visitor.driver?) resets the wake
40
+ # budget and releases held reports as chi send's input did, but never
41
+ # brings back an archived session.
42
+ if Visitor.driver?(client_id, @session)
43
+ @wakes.human_input!(interactive: false)
44
+ @child_reports&.release_holds
45
+ return
46
+ end
47
+ return unless ClientId.owner?(client_id)
48
+
49
+ ArchiveStore.user_input(@session_id, state_dir: @state_dir)
50
+ @wakes.human_input!(interactive: ClientId.interactive?(client_id))
51
+ @child_reports&.release_holds
52
+ end
53
+
54
+ # session.max_wakes spent: a visitor's queued turn is refused (its
55
+ # sender's wait reads ParentReport::REFUSED_LINES' max_wakes); the
56
+ # owner hears it once, until their next message (WorkerWakes#notice_visitor!).
57
+ def refuse_visitor(origin)
58
+ Log.info(:worker, "visitor_turn_refused", client_id: origin.client_id, reason: Visitor::CAP_REASON)
59
+ refuse_queued_turn(origin, Visitor::CAP_REASON)
60
+ return unless @wakes.notice_visitor!
61
+
62
+ # An agent's name, or another session's question by its id8.
63
+ name = ClientId.agent_name(origin.client_id) || "session #{ClientId.session_name(origin.client_id)}"
64
+ @event_log.announce(type: :hook_notice, hook: "agent", level: :info, between_turns: true,
65
+ text: "#{name}'s message was not run: #{@wakes.max} turns ran in a row with no message " \
66
+ "from you (#{ChildRing::MAX_WAKES_KEY}); agents' messages run again after your next one")
67
+ nil
68
+ end
69
+
70
+ # A queued turn that may not start (a participant's, WorkerParticipantGate#refuse):
71
+ # settled as refused for +reason+ (a code) and dropped from every UI's
72
+ # queue; it never runs (TurnCheckpoint.refuse_queued).
73
+ # @return [nil]
74
+ def refuse_queued_turn(origin, reason, author: nil)
75
+ TurnCheckpoint.refuse_queued(@session_dir, @event_log, origin, reason, author: author)
76
+ end
77
+ end
78
+ end
79
+ end
@@ -49,6 +49,7 @@ require_relative "worker/scratch"
49
49
  require_relative "worker/child_side"
50
50
  require_relative "worker/command_queue"
51
51
  require_relative "worker/block_fixes"
52
+ require_relative "worker/senders"
52
53
 
53
54
  module Samagotchi
54
55
  # The loop of a background session worker, once it owns the session (see
@@ -100,6 +101,7 @@ module Samagotchi
100
101
  include ChildSidePart
101
102
  include CommandQueuePart
102
103
  include BlockFixesPart
104
+ include SendersPart
103
105
 
104
106
  FALLBACK_TICK_SECONDS = 5
105
107
  # A worker just started runs no wake turn for delegate reports this
@@ -347,10 +349,12 @@ module Samagotchi
347
349
  # This session's own delegate children's news (rings in children/).
348
350
  @child_reports = ChildReports.new(session_id: @session_id, state_dir: @state_dir,
349
351
  predecessor: @session.continues)
350
- # Its attached context's notes (ContextSources).
352
+ # Its attached context's notes (ContextSources); a peer's text goes in
353
+ # its note up to the tool output cap, as a task's does (WorkerTaskWakes).
351
354
  @context_absorber = ContextAbsorber.new(session_id: @session_id, state_dir: @state_dir,
352
355
  project_root: @session.project_root, project_id: @session.project_id,
353
- peer_sources: @engine.peer_sources, peer_turns: -> { @wakes.peer_turns })
356
+ peer_sources: @engine.peer_sources, peer_turns: -> { @wakes.peer_turns },
357
+ cap: -> { ToolOutputCut.max_chars(nil) })
354
358
  # What comes in between turns, and how each kind is saved.
355
359
  @inbound = WorkerInbound.new(session: @session, state_dir: @state_dir, session_dir: @session_dir, engine: @engine,
356
360
  event_log: @event_log, turn_state: @turn_state, context_absorber: @context_absorber, wakes: @wakes,
@@ -690,10 +694,16 @@ module Samagotchi
690
694
  return @participant_gate.refuse(origin, reason)
691
695
  end
692
696
 
697
+ visitor = Visitor.of?(origin.client_id, @session)
698
+ return refuse_visitor(origin) if visitor && !count_visitor
699
+
693
700
  # A candidate the prompt mentions is attached and fetched first, so
694
701
  # the absorb below brings its note into this turn.
695
- ContextCandidates.before_turn(session: @session, prompt: prompt.text, author: origin.author, state_dir: @state_dir,
696
- cancelled: -> { stopped_on_disk? })
702
+ # Not for a visitor's prompt: only the owner's attaches (OwnerPrompt).
703
+ unless visitor
704
+ ContextCandidates.before_turn(session: @session, prompt: prompt.text, author: origin.author, state_dir: @state_dir,
705
+ cancelled: -> { stopped_on_disk? })
706
+ end
697
707
  # A first turn sees the context attached before it, and any turn the
698
708
  # background tasks that finished since the last look.
699
709
  absorb_context(before_turn: true)
@@ -701,8 +711,12 @@ module Samagotchi
701
711
  user_input(origin.client_id)
702
712
  @continue_offer.drop(origin)
703
713
  @turn_flow.before_prompt_turn
714
+ # A visitor's opener is saved with its sender, which gives it its
715
+ # header line (Steer::OPENER_HEADERS); the driver's and the owner's
716
+ # keep their bytes.
717
+ source = visitor ? { opener_source: origin.client_id } : {}
704
718
  run_engine_turn(prompt.text, origin: origin, max_iterations: max_iterations(prompt.no_interrupt),
705
- images: prompt.images, **prompt.anchors.kwargs) do |result, error|
719
+ images: prompt.images, **source, **prompt.anchors.kwargs) do |result, error|
706
720
  if error
707
721
  # The Engine announced :turn_failed (with the error's one line).
708
722
  restore_failed_turn([[prompt.text, origin, prompt.images, prompt.anchors], *@merged_this_turn], error: error)
@@ -748,7 +762,8 @@ module Samagotchi
748
762
  @turn_author = origin.participant_author
749
763
  restores = @turn_flow.restores
750
764
  begin
751
- @checkpoint.begin_turn(prompt: prompt, turn_id: turn_args[:id], enqueued_id: origin.enqueued_id, author: turn_author_fields(origin))
765
+ @checkpoint.begin_turn(prompt: prompt, turn_id: turn_args[:id], enqueued_id: origin.enqueued_id, author: turn_author_fields(origin),
766
+ source: turn_args[:opener_source])
752
767
  @session.status = Session::STATUS_RUNNING
753
768
  # A continue that moved this session to the chain's new link wrote
754
769
  # the new parent beside it (Session::PARENT_FILE): this turn's
@@ -957,18 +972,6 @@ module Samagotchi
957
972
 
958
973
  def monotonic_now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
959
974
 
960
- # The owner's input (ClientId.owner?) un-archives the session; a
961
- # delegate's, a plugin's, a reminder's or a participant's doesn't.
962
- # It also resets the wakes (budget and pause); input typed in the web or
963
- # a TUI the peer wakes too (chi send doesn't: a peer can run it).
964
- def user_input(client_id)
965
- return unless ClientId.owner?(client_id)
966
-
967
- ArchiveStore.user_input(@session_id, state_dir: @state_dir)
968
- @wakes.human_input!(interactive: ClientId.interactive?(client_id))
969
- @child_reports&.release_holds
970
- end
971
-
972
975
  def stopped_on_disk?
973
976
  SessionManager.stopped_on_disk?(@session_id, state_dir: @state_dir)
974
977
  end
@@ -61,8 +61,10 @@ module Samagotchi
61
61
  # that agrees closes the round and counts toward session.max_wakes only.
62
62
  def peer_turn? = peer? && !delivery.agreed
63
63
  def origin = TurnOrigin.new(client_id: "#{ClientId::CONTEXT_PREFIX}#{name}")
64
- # The plain note #unmark_wake puts back.
65
- def note = delivery.note
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
66
68
  end
67
69
 
68
70
  # A task finish wake turn to run (TaskWatch, TaskFinishNote): its wake
@@ -332,7 +334,10 @@ module Samagotchi
332
334
  what: "command", reason: "not_permitted")
333
335
  return true
334
336
  end
335
- return false unless CommandIntake.allowed?(origin.client_id) || CommandIntake.shell_line?(text)
337
+ # A ! line from a sender that may not run one (an agent's too:
338
+ # CommandIntake.refused?, asked first) is queued for its refusal
339
+ # (Worker::CommandQueue#command_result).
340
+ return false unless CommandIntake.refused?(text, origin.client_id) || CommandIntake.allowed?(origin.client_id)
336
341
 
337
342
  @queue_command.call(text, origin.client_id, after_file, origin.enqueued_id)
338
343
  true
@@ -404,7 +409,10 @@ module Samagotchi
404
409
 
405
410
  # +batch+ with +waking+'s subscription recording the wake (the 10-minute window).
406
411
  def woken(batch, waking)
407
- stamped = waking.with(subscription: waking.subscription.with(wakes_at: Time.now.iso8601))
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))
408
416
  batch.with(deliveries: batch.deliveries.map { |delivery| delivery == waking ? stamped : delivery })
409
417
  end
410
418
  end
@@ -58,8 +58,8 @@ module Samagotchi
58
58
  # The client for this worker (BridgeClient.for_sidecar: its port and its
59
59
  # secret from this one read).
60
60
  # @return [BridgeClient]
61
- def client(session_id, host: BridgeClient::HOST, read_timeout: BridgeClient::READ_TIMEOUT)
62
- BridgeClient.for_sidecar(session_id, sidecar, host: host, read_timeout: read_timeout)
61
+ def client(session_id, host: BridgeClient::HOST, read_timeout: BridgeClient::READ_TIMEOUT, deadline_margin: nil)
62
+ BridgeClient.for_sidecar(session_id, sidecar, host: host, read_timeout: read_timeout, deadline_margin: deadline_margin)
63
63
  end
64
64
 
65
65
  def port = sidecar.port
@@ -98,11 +98,9 @@ module Samagotchi
98
98
  # @param origin [TurnOrigin] a participant's
99
99
  # @return [nil]
100
100
  def refuse(origin, reason)
101
- TurnCheckpoint.record_refused(@session_dir, origin.enqueued_id, reason: reason, author: origin.participant_author)
102
101
  Participants.log(source_id, :turn, state_dir: @state_dir, participant: origin.participant_id,
103
102
  enqueued_id: origin.enqueued_id, status: "refused", reason: reason)
104
- @event_log.announce(type: :turn_dequeued, enqueued_id: origin.enqueued_id, client_id: origin.client_id)
105
- nil
103
+ TurnCheckpoint.refuse_queued(@session_dir, @event_log, origin, reason, author: origin.participant_author)
106
104
  end
107
105
 
108
106
  # A participant invited, revoked or expired since the last look: the
@@ -36,6 +36,7 @@ module Samagotchi
36
36
  @peer_in_a_row = 0
37
37
  @paused = false
38
38
  @budget_noticed = false
39
+ @visitor_noticed = false
39
40
  @peer_noticed = false
40
41
  @handed = nil
41
42
  end
@@ -145,6 +146,7 @@ module Samagotchi
145
146
  @in_a_row = 0
146
147
  @paused = false
147
148
  @budget_noticed = false
149
+ @visitor_noticed = false
148
150
  return unless interactive
149
151
 
150
152
  @peer_in_a_row = 0
@@ -159,6 +161,16 @@ module Samagotchi
159
161
  @budget_noticed = true
160
162
  end
161
163
 
164
+ # @return [Boolean] true the first time a visitor's turn (an agent's
165
+ # that doesn't drive the session) is refused since the last human
166
+ # input: the UIs hear it once. Apart from #notice_budget!, which a
167
+ # delegate's or a task's notice may have spent this stretch.
168
+ def notice_visitor!
169
+ return false if @visitor_noticed
170
+
171
+ @visitor_noticed = true
172
+ end
173
+
162
174
  # @return [Boolean] true the first time a peer's answer is held since
163
175
  # the last interactive input: the UIs hear it once
164
176
  def notice_peer_budget!