samagotchi 0.182.0 → 0.184.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 (197) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +22 -11
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +4 -2
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +14 -6
  12. data/docs/internals/bundles.md +26 -5
  13. data/docs/internals/engine.md +20 -9
  14. data/docs/internals/participants.md +1 -1
  15. data/docs/internals/prompt-caching.md +8 -1
  16. data/docs/internals/remote-sessions.md +40 -5
  17. data/docs/internals/web-frontend.md +96 -31
  18. data/docs/internals/web-push.md +11 -0
  19. data/docs/internals/working-set.md +239 -7
  20. data/docs/mcp-server.md +84 -0
  21. data/docs/memory.md +2 -1
  22. data/docs/plugins.md +309 -22
  23. data/docs/scheduling.md +14 -0
  24. data/docs/sessions.md +4 -4
  25. data/docs/sub-agent.md +9 -0
  26. data/docs/testing.md +3 -1
  27. data/docs/thin-clients.md +165 -0
  28. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  29. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  30. data/lib/samagotchi/bridge.rb +59 -68
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  33. data/lib/samagotchi/bundle_command/check.rb +55 -20
  34. data/lib/samagotchi/bundle_command.rb +50 -21
  35. data/lib/samagotchi/bundle_manifest.rb +105 -4
  36. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  37. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  38. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  39. data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
  40. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  41. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  42. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  43. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  44. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  45. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  46. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  47. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  48. data/lib/samagotchi/command_intake.rb +7 -0
  49. data/lib/samagotchi/commands/registry.rb +8 -3
  50. data/lib/samagotchi/continue_offer.rb +24 -15
  51. data/lib/samagotchi/engine/block_fix.rb +4 -4
  52. data/lib/samagotchi/engine/cards.rb +14 -5
  53. data/lib/samagotchi/engine/events.rb +10 -15
  54. data/lib/samagotchi/engine/models.rb +1 -1
  55. data/lib/samagotchi/engine/plugins.rb +3 -0
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/session.rb +14 -6
  58. data/lib/samagotchi/engine/side_requests.rb +1 -1
  59. data/lib/samagotchi/engine/sign_in.rb +142 -0
  60. data/lib/samagotchi/engine/turn_end.rb +3 -3
  61. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  62. data/lib/samagotchi/engine.rb +43 -27
  63. data/lib/samagotchi/engine_snapshots.rb +1 -1
  64. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  65. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  66. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  67. data/lib/samagotchi/hold_stop.rb +4 -4
  68. data/lib/samagotchi/idle_recap.rb +19 -11
  69. data/lib/samagotchi/idle_reminders.rb +7 -5
  70. data/lib/samagotchi/idle_scheduler.rb +7 -10
  71. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  72. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  73. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  74. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  75. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  76. data/lib/samagotchi/llm/http.rb +96 -5
  77. data/lib/samagotchi/mcp_command.rb +110 -0
  78. data/lib/samagotchi/mcp_server/http.rb +112 -0
  79. data/lib/samagotchi/mcp_server/protocol.rb +263 -0
  80. data/lib/samagotchi/mcp_server/stdio.rb +93 -0
  81. data/lib/samagotchi/mcp_server/text.rb +155 -0
  82. data/lib/samagotchi/mcp_server/tools.rb +246 -0
  83. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  84. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  85. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  86. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  87. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  88. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  89. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  90. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  91. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  92. data/lib/samagotchi/model_notes.rb +34 -12
  93. data/lib/samagotchi/plugin/api.rb +6 -1
  94. data/lib/samagotchi/plugin/card.rb +36 -11
  95. data/lib/samagotchi/plugin/context.rb +63 -6
  96. data/lib/samagotchi/plugin/http.rb +40 -15
  97. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  98. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  99. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  100. data/lib/samagotchi/plugin/loader.rb +18 -11
  101. data/lib/samagotchi/plugin/secrets.rb +266 -0
  102. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  103. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  104. data/lib/samagotchi/prompt_files.rb +11 -4
  105. data/lib/samagotchi/prompt_layout.rb +88 -0
  106. data/lib/samagotchi/prompt_part.rb +82 -20
  107. data/lib/samagotchi/queued_command.rb +28 -4
  108. data/lib/samagotchi/recap_setup.rb +13 -4
  109. data/lib/samagotchi/ref.rb +3 -2
  110. data/lib/samagotchi/relay_verifier.rb +8 -7
  111. data/lib/samagotchi/relay_watcher.rb +4 -4
  112. data/lib/samagotchi/reply_wait.rb +6 -3
  113. data/lib/samagotchi/run_options.rb +2 -1
  114. data/lib/samagotchi/schedule_command.rb +18 -4
  115. data/lib/samagotchi/schedules.rb +40 -8
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +285 -0
  118. data/lib/samagotchi/session_access/contract.rb +5 -0
  119. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  120. data/lib/samagotchi/session_access/exchange.rb +176 -0
  121. data/lib/samagotchi/session_access/local.rb +34 -6
  122. data/lib/samagotchi/session_access/remote.rb +4 -1
  123. data/lib/samagotchi/session_command_catalog.rb +10 -0
  124. data/lib/samagotchi/session_commands.rb +17 -0
  125. data/lib/samagotchi/session_config.rb +4 -4
  126. data/lib/samagotchi/session_inbox.rb +15 -0
  127. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  128. data/lib/samagotchi/session_observer.rb +27 -0
  129. data/lib/samagotchi/steer_cut.rb +4 -3
  130. data/lib/samagotchi/system_prompt.rb +196 -161
  131. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  132. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  133. data/lib/samagotchi/testing/boundary.rb +4 -0
  134. data/lib/samagotchi/testing/bundle.rb +48 -2
  135. data/lib/samagotchi/testing/fake_http.rb +60 -15
  136. data/lib/samagotchi/testing/host.rb +4 -1
  137. data/lib/samagotchi/testing/recorder.rb +45 -5
  138. data/lib/samagotchi/tools/memory.rb +11 -3
  139. data/lib/samagotchi/tools/tool_index.rb +14 -3
  140. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  141. data/lib/samagotchi/version.rb +1 -1
  142. data/lib/samagotchi/web/app.rb +9 -8
  143. data/lib/samagotchi/web/ask_routes.rb +362 -0
  144. data/lib/samagotchi/web/mcp_route.rb +91 -0
  145. data/lib/samagotchi/web/public/app.js +2 -3
  146. data/lib/samagotchi/web/public/block_frame.js +72 -11
  147. data/lib/samagotchi/web/public/block_host.js +44 -8
  148. data/lib/samagotchi/web/public/block_regions.js +126 -0
  149. data/lib/samagotchi/web/public/card.js +22 -9
  150. data/lib/samagotchi/web/public/card_actions.js +21 -0
  151. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  152. data/lib/samagotchi/web/public/card_registry.js +3 -2
  153. data/lib/samagotchi/web/public/data.js +15 -12
  154. data/lib/samagotchi/web/public/delete_sheet.js +231 -169
  155. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  156. data/lib/samagotchi/web/public/format.js +3 -0
  157. data/lib/samagotchi/web/public/index.html +52 -7
  158. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  159. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  160. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  161. data/lib/samagotchi/web/public/refs.js +5 -3
  162. data/lib/samagotchi/web/public/region_hit.js +144 -0
  163. data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
  164. data/lib/samagotchi/web/public/running_tasks.js +3 -17
  165. data/lib/samagotchi/web/public/session_actions.js +96 -100
  166. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  167. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  168. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  169. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  170. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  171. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  172. data/lib/samagotchi/web/push/notifier.rb +33 -6
  173. data/lib/samagotchi/web/server.rb +1 -1
  174. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  175. data/lib/samagotchi/web/session_control.rb +31 -9
  176. data/lib/samagotchi/web/session_create.rb +2 -2
  177. data/lib/samagotchi/web/session_hub.rb +26 -4
  178. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  179. data/lib/samagotchi/worker/child_side.rb +3 -2
  180. data/lib/samagotchi/worker/command_queue.rb +13 -13
  181. data/lib/samagotchi/worker/leave.rb +3 -3
  182. data/lib/samagotchi/worker/scratch.rb +6 -6
  183. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  184. data/lib/samagotchi/worker/startup.rb +3 -3
  185. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  186. data/lib/samagotchi/worker.rb +32 -21
  187. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  188. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  189. data/lib/samagotchi/worker_inbound.rb +12 -7
  190. data/lib/samagotchi/worker_link.rb +2 -2
  191. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  192. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  193. data/lib/samagotchi/working_set.rb +162 -90
  194. data/lib/samagotchi/working_set_locator.rb +221 -0
  195. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  196. data/lib/samagotchi/working_set_part.rb +281 -0
  197. metadata +36 -1
@@ -57,6 +57,14 @@ module Samagotchi
57
57
  qid = body["id"]
58
58
  return error_response(400, "missing_fields", "id is required") if qid.to_s.strip.empty?
59
59
 
60
+ # wait: a thin client's answer that also waits for what comes next
61
+ # (AskRoutes#answered_wait), its start read before the answer goes in.
62
+ wait, error = answer_wait_option(body)
63
+ return error if error
64
+
65
+ start = answer_wait_start(id, session, qid) if wait
66
+ return session_not_found(id) if wait && !start
67
+
60
68
  # client_id: only chi answer's (a parent agent's answer, which the
61
69
  # worker holds to its guardrails.parent_answers) is passed on; any
62
70
  # other is dropped, so a forward can only tighten (an answer never
@@ -65,19 +73,27 @@ module Samagotchi
65
73
  request = once_more_on_late do |client|
66
74
  client.answer(id: qid, selected: body["selected"], freeform: body["freeform"], client_id: client_id)
67
75
  end
68
- relay(id, bridge_client(id), request, what: "the answer was not sent", cant: "answer questions") do |reply|
76
+ # With wait, the relay answers :answered / :not_pending and the wait
77
+ # runs after it: relay's rescues are the answer's, not the wait's.
78
+ relayed = relay(id, bridge_client(id), request, what: "the answer was not sent", cant: "answer questions") do |reply|
69
79
  case reply.status
70
80
  when 200
71
81
  @hub&.resolve_question(id, question_id: qid)
82
+ next :answered if wait
83
+
72
84
  json_response(200, { status: "answered", session_id: id, id: qid })
73
85
  # Another client answered first (or the question was cancelled).
74
- when 409 then error_response(409, "question_not_pending", reply_detail(reply, "question not pending"))
86
+ when 409
87
+ next :not_pending if wait
88
+
89
+ error_response(409, "question_not_pending", reply_detail(reply, "question not pending"))
75
90
  when 400 then error_response(400, "invalid_answer", reply_detail(reply, "answer rejected"))
76
91
  # The worker's guardrails.parent_answers refused a parent's option.
77
92
  when 403 then json_response(403, { error: "parent_answer_refused", reason: reply.json&.dig("reason"),
78
93
  detail: reply_detail(reply, "the worker refused that option") })
79
94
  end
80
95
  end
96
+ relayed.is_a?(Symbol) ? answered_wait(id, qid, start, wait, answered: relayed == :answered) : relayed
81
97
  end
82
98
 
83
99
  # A request to the worker sent once more when the worker dropped it as
@@ -223,18 +239,24 @@ module Samagotchi
223
239
  follow: body["follow"] == true,
224
240
  state_dir: @state_dir, manager: @manager,
225
241
  bridge: -> { live_bridge_client(id) })
242
+ return refused_delivery(result) unless result.status == :accepted
243
+
244
+ record_history(body, prompt)
245
+ # via: bridge or file (the worker was gone: its input file), which
246
+ # names the turn a remote chi send --wait follows (ReplyWait::Target).
247
+ json_response(202, result.ack.merge("via" => result.via.to_s))
248
+ rescue SessionManager::OwnedByTUI => e
249
+ owned_by_tui(e)
250
+ end
251
+
252
+ # A delivery that did not go in (POST …/turn's, POST …/ask's): the
253
+ # worker's refusal as it answered it, 504 worker_timeout, or 500.
254
+ def refused_delivery(result)
226
255
  case result.status
227
- when :accepted
228
- record_history(body, prompt)
229
- # via: bridge or file (the worker was gone: its input file), which
230
- # names the turn a remote chi send --wait follows (ReplyWait::Target).
231
- json_response(202, result.ack.merge("via" => result.via.to_s))
232
256
  when :refused then json_response(result.code, result.ack)
233
257
  when :timeout then error_response(504, "worker_timeout", result.detail)
234
258
  else error_response(500, "enqueue_failed", "could not write turn input")
235
259
  end
236
- rescue SessionManager::OwnedByTUI => e
237
- owned_by_tui(e)
238
260
  end
239
261
 
240
262
  # A turn refused before it goes in, as chi send refuses it on its own
@@ -125,7 +125,7 @@ module Samagotchi
125
125
  record_history(body, prompt) if !idle && PromptHistory.shell_line?(prompt.to_s.strip)
126
126
  json_response(201, session_to_json(session).merge(bridge_port: port, model_warning: session.model_warning,
127
127
  parent_answers_warning: Guardrails::ParentPolicy.capped_note(parent_answers),
128
- first_turn_id: session.first_turn_id))
128
+ first_turn_id: session.first_turn_id, **create_token(session)))
129
129
  end
130
130
 
131
131
  # POST /api/sessions with continues: <id, prefix or last:id>: the next
@@ -171,7 +171,7 @@ module Samagotchi
171
171
  model_warning: session.model_warning,
172
172
  opener: session.opener,
173
173
  moved_context: session.moved_context&.to_h,
174
- first_turn_id: session.first_turn_id))
174
+ first_turn_id: session.first_turn_id, **create_token(session)))
175
175
  end
176
176
 
177
177
  # The previous link's parent_answers and the model the new one runs,
@@ -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
@@ -19,7 +19,8 @@ module Samagotchi
19
19
  # Verify fresh hand-off. Writes @owes_parent, @asked_parent and
20
20
  # @reporting_turn (also written by #run_engine_turn, with @initial_turn
21
21
  # from #run_initial_prompt; #initialize sets them). Reads @session,
22
- # @state_dir, @session_dir, @engine, @child_reports and @initial_turn.
22
+ # @state_dir, @session_dir, @engine, @event_log, @child_reports and
23
+ # @initial_turn.
23
24
  module ChildSidePart
24
25
  private
25
26
 
@@ -44,7 +45,7 @@ module Samagotchi
44
45
  return unless save_or_log(:fresh_verdicts) { save_session }
45
46
 
46
47
  FileUtils.rm_f(files)
47
- added.each { |record| @engine.announce(type: :verdict_recorded, verdict: record) }
48
+ added.each { |record| @event_log.announce(type: :verdict_recorded, verdict: record) }
48
49
  rescue StandardError => e
49
50
  Log.warn(:worker, "fresh_verdicts_failed", error: e.class.name, msg: e.message)
50
51
  end
@@ -15,12 +15,12 @@ module Samagotchi
15
15
  # any queued prompt, and refuses or drops what arrives mid-turn. Includes
16
16
  # the "what waits" predicates #input_pending?, #held_for_offer? and
17
17
  # #nothing_queued?. LOCK RULE: the queue is touched with the event log held
18
- # (@engine.synchronize_events): #on_command on a Bridge thread, the pops
18
+ # (@event_log.synchronize): #on_command on a Bridge thread, the pops
19
19
  # and re-pushes in #next_ready_command, #refuse_queued_commands and
20
20
  # #drop_queued_commands. The `empty?` peeks (those, #input_pending?,
21
21
  # #nothing_queued?, #start's next_turn_waiting lambda) are benign by
22
22
  # design. Writes @command_queue's contents (created in #initialize).
23
- # Reads @engine, @session_dir, @commands (built in #start),
23
+ # Reads @engine, @event_log, @turn_state, @session_dir, @commands (built in #start),
24
24
  # @continue_offer, @turn_end_seq, @turn_end_type (#start's observer),
25
25
  # @turn_flow and @waker.
26
26
  module CommandQueuePart
@@ -72,7 +72,7 @@ module Samagotchi
72
72
  def next_ready_command
73
73
  return nil if @command_queue.empty?
74
74
 
75
- @engine.synchronize_events do
75
+ @event_log.synchronize do
76
76
  commands = drain_commands
77
77
  first = commands.first
78
78
  ready = first && ready_command?(first) ? commands.shift : nil
@@ -111,7 +111,7 @@ module Samagotchi
111
111
  def refuse_queued_commands(mid_turn: false)
112
112
  return if @command_queue.empty?
113
113
 
114
- @engine.synchronize_events do
114
+ @event_log.synchronize do
115
115
  drain_commands.each do |command|
116
116
  during = mid_turn || command.after_seq.to_i < @turn_end_seq
117
117
  case (during ? turn_answer(command, ended: !mid_turn) : :keep)
@@ -144,7 +144,7 @@ module Samagotchi
144
144
  def waiting_for_turn_end(command)
145
145
  return command unless command.mid_turn == :loop && @engine.command_registry.mid_turn(command.line) == :queue
146
146
 
147
- @engine.announce(type: :command_queued, **command.event_fields, waits: "turn_end")
147
+ @event_log.announce(type: :command_queued, **command.event_fields, waits: "turn_end")
148
148
  command.with(mid_turn: :queue)
149
149
  end
150
150
 
@@ -164,7 +164,7 @@ module Samagotchi
164
164
  def drop_queued_commands
165
165
  return if @command_queue.nil? || @command_queue.empty? || @engine.nil?
166
166
 
167
- @engine.synchronize_events do
167
+ @event_log.synchronize do
168
168
  drain_commands.each { |command| drop_command(command, "dropped: the session's worker stopped before it ran") }
169
169
  end
170
170
  rescue StandardError => e
@@ -181,11 +181,11 @@ module Samagotchi
181
181
  awaiting = @continue_offer.awaiting?
182
182
  result, shown = run_command_line(command)
183
183
  resolved = @continue_offer.resolved?(awaiting, result)
184
- @engine.synchronize_events do
184
+ @event_log.synchronize do
185
185
  @continue_offer.announce_resolved(result, command) if resolved
186
186
  announce_command(command, status: result.status.to_s, output: result.output, changed: Array(result.changed),
187
187
  confirm: result.confirm)
188
- shown.each { |event| @engine.announce(event) }
188
+ shown.each { |event| @event_log.announce(event) }
189
189
  end
190
190
  save_or_log(:command) { save_session } unless Array(result.changed).empty?
191
191
  user_input(command.client_id) if resolved
@@ -199,7 +199,7 @@ module Samagotchi
199
199
  def run_command_line(command)
200
200
  @engine.holding_announcements do
201
201
  command_result(command) do
202
- @commands.run(command.line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
202
+ @commands.run(command.run_line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
203
203
  end
204
204
  end
205
205
  end
@@ -258,7 +258,7 @@ module Samagotchi
258
258
  # :refuse while a turn runs, :loop idle
259
259
  def on_command(command, after_file: nil)
260
260
  registry = @engine.command_registry
261
- policy = if @engine.turn_running? then registry.mid_turn(command.line)
261
+ policy = if @turn_state.running? then registry.mid_turn(command.line)
262
262
  else registry.anytime?(command.line) ? :anytime : :loop
263
263
  end
264
264
  if policy == :anytime
@@ -268,7 +268,7 @@ module Samagotchi
268
268
 
269
269
  after_file ||= newest_input_file if policy == :queue
270
270
  # The count says which turn ends came before it.
271
- @command_queue << command.with(after_seq: @engine.event_count, mid_turn: policy, after_file: after_file)
271
+ @command_queue << command.with(after_seq: @event_log.event_count, mid_turn: policy, after_file: after_file)
272
272
  @waker.wake
273
273
  policy
274
274
  end
@@ -294,7 +294,7 @@ module Samagotchi
294
294
  @engine.spawn_anytime do
295
295
  result = command_result(command) do
296
296
  @engine.running_anytime do
297
- @commands.run(command.line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
297
+ @commands.run(command.run_line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
298
298
  end
299
299
  end
300
300
  # Saved before its command_ran: a client that reads the file on the reply finds it.
@@ -331,7 +331,7 @@ module Samagotchi
331
331
  SessionSetting::ALL.each { |setting| event[setting.key] = setting.summary(@engine) if setting.changed_by?(changed) }
332
332
  event[:confirm] = confirm.to_h if confirm
333
333
  event[:output_truncated] = true if text.length > COMMAND_OUTPUT_LIMIT
334
- @engine.announce(event)
334
+ @event_log.announce(event)
335
335
  end
336
336
 
337
337
  # +text+ as its :command_ran carries it: over the limit, its head to a
@@ -13,7 +13,7 @@ module Samagotchi
13
13
  # carried reminders, the recap, the discard). Writes @marked_leaving
14
14
  # (#mark_leaving) and @discard (#left), and the exit claim through its own
15
15
  # methods; reads @exit_claim, @idle_exit, @hold_stop, @session, @session_id,
16
- # @session_dir, @state_dir, @default_model, @engine, @bridge, @owner_lock,
16
+ # @session_dir, @state_dir, @default_model, @engine, @event_log, @bridge, @owner_lock,
17
17
  # @waker and @task_wakes.
18
18
  module LeavePart
19
19
  # /exit held by background tasks a finish wake waits for: how to end them.
@@ -109,7 +109,7 @@ module Samagotchi
109
109
  # decided under the lock), false when something came in since the request
110
110
  def leave_on_request
111
111
  stop_bridge_after do
112
- @engine.synchronize_events do
112
+ @event_log.synchronize do
113
113
  # One read: the kind and the asker of the same exit.
114
114
  taken = @exit_claim.taken
115
115
  restart = taken&.restart?
@@ -143,7 +143,7 @@ module Samagotchi
143
143
  # @return [Boolean] false when something came in since #due?
144
144
  def leave_idle
145
145
  stop_bridge_after do
146
- @engine.synchronize_events do
146
+ @event_log.synchronize do
147
147
  next false unless @idle_exit.due?
148
148
 
149
149
  @bridge&.close_intake
@@ -14,7 +14,7 @@ module Samagotchi
14
14
  # SCRATCH_JOIN_GRACE and SCRATCH_GONE_AFTER. Writes @unattended_since
15
15
  # (the scratch thread and the loop, no lock: a monotonic stamp, benign).
16
16
  # Reads @poll_interval, @session, @bridge, @started_at (#start), @engine,
17
- # @session_id and @waker. #scratch? and @scratch_watch (#start_background,
17
+ # @turn_state, @question_desk, @event_log, @session_id and @waker. #scratch? and @scratch_watch (#start_background,
18
18
  # #teardown) stay in Worker.
19
19
  module ScratchPart
20
20
  # How long a scratch worker waits for its terminal's first stream
@@ -46,11 +46,11 @@ module Samagotchi
46
46
  end
47
47
 
48
48
  def cancel_unattended_turn
49
- return unless @engine.turn_running? && scratch_unattended?
49
+ return unless @turn_state.running? && scratch_unattended?
50
50
 
51
51
  Log.info(:worker, "scratch_turn_cancelled", sid: @session_id)
52
- @engine.cancel_question(SessionManager::STOP_CANCEL_REASON) if @engine.pending_question
53
- @engine.cancel_current_turn!(SessionManager::STOP_CANCEL_REASON.to_sym)
52
+ @question_desk.cancel(SessionManager::STOP_CANCEL_REASON) if @question_desk.pending
53
+ @turn_state.cancel!(SessionManager::STOP_CANCEL_REASON.to_sym)
54
54
  @waker.wake
55
55
  end
56
56
 
@@ -83,9 +83,9 @@ module Samagotchi
83
83
  # @return [Boolean] false when a client came back since
84
84
  def leave_scratch
85
85
  stop_bridge_after do
86
- @engine.synchronize_events do
86
+ @event_log.synchronize do
87
87
  # A turn still running is the scratch watch's to cancel first.
88
- next false unless scratch_unattended? && !@engine.turn_running?
88
+ next false unless scratch_unattended? && !@turn_state.running?
89
89
 
90
90
  @bridge&.close_intake
91
91
  @engine.stop_idle(join: false)
@@ -11,7 +11,8 @@ module Samagotchi
11
11
  # (under @signal_mutex). Worker writes the rest it reads: @run_thread
12
12
  # (#run), @loop_started (#run_loop), @left_loop (#run's ensure),
13
13
  # @turn_ending (the turn observer) and the grace ivars and @signal_mutex
14
- # (#initialize). Reads those, @signals, @engine, @waker, @session_id and
14
+ # (#initialize). Reads those, @signals, @turn_state (nil-guarded: a
15
+ # signal may come before #start set it), @waker, @session_id and
15
16
  # @state_dir.
16
17
  module SignalGracePart
17
18
  # How long a signalled worker's turn has to end (it is canceled at once,
@@ -48,7 +49,7 @@ module Samagotchi
48
49
  # for it (the loop's first look leaves). A signal after the loop left
49
50
  # (the teardown, the caller's last steps) only brings the hard exit.
50
51
  def signalled(name, count)
51
- Log.info(:worker, "signal", signal: name, count: count, turn_running: @engine&.turn_running? || false)
52
+ Log.info(:worker, "signal", signal: name, count: count, turn_running: @turn_state&.running? || false)
52
53
  return signal_hard_exit if @left_loop
53
54
 
54
55
  @waker.wake
@@ -58,9 +59,9 @@ module Samagotchi
58
59
  hooks_deadline = deadline + @signal_hard_exit
59
60
  ended = false
60
61
  until @left_loop
61
- running = @engine&.turn_running?
62
+ running = @turn_state&.running?
62
63
  ended ||= running && @turn_ending
63
- @engine.cancel_current_turn!(:signal) if running && !ended
64
+ @turn_state.cancel!(:signal) if running && !ended
64
65
  break if @loop_started && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= (ended ? hooks_deadline : deadline)
65
66
 
66
67
  sleep(SIGNAL_RETRY)
@@ -85,7 +86,7 @@ module Samagotchi
85
86
  expired = @signal_mutex.synchronize { !@grace_expired && !@left_loop && (@grace_expired = true) }
86
87
  return unless expired
87
88
 
88
- Log.warn(:worker, "signal_grace_expired", signal: name, turn_running: @engine&.turn_running? || false)
89
+ Log.warn(:worker, "signal_grace_expired", signal: name, turn_running: @turn_state&.running? || false)
89
90
  save_or_log(:signal) { save_session }
90
91
  # Not once the loop has left (it may have, during the save).
91
92
  @signal_mutex.synchronize { @run_thread&.raise(SignalException.new(name)) unless @left_loop }
@@ -14,7 +14,7 @@ module Samagotchi
14
14
  # #drop_dead_question. Called by #start and #serve only; no state of its
15
15
  # own. Writes @session (the interrupted turn's end, the stale status, a
16
16
  # dead question) and saves it. Reads @session, @session_dir, @session_id,
17
- # @state_dir and @engine.
17
+ # @state_dir, @engine and @event_log.
18
18
  module StartupPart
19
19
  private
20
20
 
@@ -71,8 +71,8 @@ module Samagotchi
71
71
  value = @session.parent_answers
72
72
  return unless Guardrails::ParentPolicy.unknown_level?(value)
73
73
 
74
- @engine.announce({ type: :guardrail_warning, label: "parent_answers",
75
- message: "parent_answers #{value.inspect} in session #{@session_id} isn't hard/standard/soft; hard applies" })
74
+ @event_log.announce({ type: :guardrail_warning, label: "parent_answers",
75
+ message: "parent_answers #{value.inspect} in session #{@session_id} isn't hard/standard/soft; hard applies" })
76
76
  end
77
77
 
78
78
  # A question saved by a worker that died while it waited (an
@@ -17,7 +17,7 @@ module Samagotchi
17
17
  # the idle loop's sleep (#idle_wait). Glue over WorkerWakes, WorkerTaskWakes
18
18
  # and WorkerInbound: it writes no ivar of its own. Reads @child_reports,
19
19
  # @wakes, @turn_flow, @inbound, @continue_offer, @task_wakes, @engine,
20
- # @session_dir and @poll_interval.
20
+ # @event_log, @session_dir and @poll_interval.
21
21
  module WakeTurnsPart
22
22
  # A reminder turn's origin: chi's own (system:reminder). Its run gets
23
23
  # an id of its own (#wake_origin); this constant has none.
@@ -79,9 +79,9 @@ module Samagotchi
79
79
  return unless @wakes.notice_budget!
80
80
 
81
81
  count = SessionInbox.find_ring_files(@session_dir).map { |f| SessionInbox.read_ring(f)&.dig(:child_id) }.uniq.size
82
- @engine.announce(type: :hook_notice, hook: "delegate", level: :info, between_turns: true,
83
- text: "#{count} delegate report#{"s" if count != 1} waiting; #{count == 1 ? "it joins" : "they join"} " \
84
- "your next message (#{@wakes.max} turn#{"s" if @wakes.max != 1} ran for reports in a row, #{ChildRing::MAX_WAKES_KEY})")
82
+ @event_log.announce(type: :hook_notice, hook: "delegate", level: :info, between_turns: true,
83
+ text: "#{count} delegate report#{"s" if count != 1} waiting; #{count == 1 ? "it joins" : "they join"} " \
84
+ "your next message (#{@wakes.max} turn#{"s" if @wakes.max != 1} ran for reports in a row, #{ChildRing::MAX_WAKES_KEY})")
85
85
  end
86
86
 
87
87
  # A wake turn (a delegate report's, an attached context change's, a