samagotchi 0.182.0 → 0.183.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  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 +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+ require_relative "../log"
5
+ require_relative "../plugin/card"
6
+ require_relative "../plugin/sign_in"
7
+
8
+ module Samagotchi
9
+ class Engine
10
+ # Browser sign-ins (ctx.sign_in, docs/plugins.md, Sign-in): the flows
11
+ # waiting now, their cards, the /callback paste, and their end when the
12
+ # worker leaves (#shutdown closes every one first, so a card a later
13
+ # worker loads never offers a dead sign-in). A flow never outlives its
14
+ # worker and is tied to no turn (unless the bundle passes cancel:, a
15
+ # turn's controller). Reads and writes @sign_in_flows under
16
+ # @lifecycle_mutex.
17
+ module SignInPart
18
+ # Start a flow for +bundle+: a loopback listener, the address +build+
19
+ # makes for its redirect_uri, the card with its button. Returns at
20
+ # once; the bundle waits on Plugin::SignIn#wait. Once #shutdown has
21
+ # begun it starts nothing: an already-stopped flow, no card, no port
22
+ # (a command or a thread of the plugin's may still call it then). The
23
+ # flow is listed before its card shows, so a shutdown in between
24
+ # stops it and its card says cancelled.
25
+ # @param build [#call] (redirect_uri) → the address to send the user to
26
+ # @param cancel [CancellationController, nil] ends it :cancelled (a
27
+ # tool's turn's Stop, when the bundle passes ctx.cancel_controller)
28
+ # @return [Plugin::SignIn]
29
+ # @raise [ArgumentError] a bad option, a taken port, an address the
30
+ # card refuses (Plugin::Card's url check); nothing stays open then
31
+ def start_sign_in(bundle:, title:, button:, timeout:, build:, port: nil, path: Plugin::SignIn::DEFAULT_PATH,
32
+ cancel: nil, listener_options: {})
33
+ Plugin::SignIn.check_options!(timeout: timeout, path: path, cancel: cancel)
34
+ return Plugin::SignIn.stopped(bundle: bundle, title: title) if sign_ins_closed?
35
+
36
+ listener = Plugin::SignIn::Listener.new(port: port, path: path, **listener_options)
37
+ flow = Plugin::SignIn.new(bundle: bundle, title: title, button: button, timeout: timeout, listener: listener,
38
+ cancel: cancel, on_settle: ->(settled, outcome) { sign_in_settled(settled, outcome) })
39
+ begin
40
+ address = build.call(flow.redirect_uri).to_s.strip
41
+ card = { title: title, body: Plugin::SignIn::PASTE_LINE, actions: [{ label: button, url: address }] }
42
+ # The card's checks (the address), before anything is listed.
43
+ card_id = Plugin::Card.build(source: bundle, level: :info, id: nil, **card)[:id]
44
+ flow.started(address, card_id)
45
+ rescue StandardError
46
+ listener.close
47
+ raise
48
+ end
49
+ unless list_sign_in(flow)
50
+ listener.close
51
+ return Plugin::SignIn.stopped(bundle: bundle, title: title)
52
+ end
53
+
54
+ show_sign_in_card(flow, card)
55
+ Log.info(:plugins, "sign_in_started", bundle: bundle, card: card_id, port: listener.port, to: address_shown(address))
56
+ flow.listen
57
+ flow
58
+ end
59
+
60
+ # Whether a flow waits for its callback (WorkerIdleExit holds then).
61
+ def sign_in_waiting? = waiting_sign_ins.any?
62
+
63
+ # /callback <address>: the waiting flow whose redirect_uri +address+
64
+ # starts with takes its query, without a #fragment (a provider's
65
+ # "#_=_" isn't the query's).
66
+ # @return [Array(Boolean, String)] settled, and the line to answer
67
+ def sign_in_callback(address)
68
+ address = address.to_s.strip.split("#", 2).first.to_s
69
+ flows = waiting_sign_ins
70
+ return [false, "no sign-in is waiting"] if flows.empty?
71
+
72
+ flow = flows.find { |waiting| waiting.redirect_of?(address) }
73
+ return [false, "that isn't this sign-in's address (it starts #{flows.first.redirect_uri})"] unless flow
74
+ return [false, "that isn't this sign-in's address"] unless flow.offer(address.split("?", 2)[1])
75
+
76
+ [true, "Got it."]
77
+ end
78
+
79
+ private
80
+
81
+ def sign_ins_closed? = @lifecycle_mutex.synchronize { @shut_down }
82
+
83
+ # @return [Boolean] false once #shutdown has begun (nothing listed)
84
+ def list_sign_in(flow)
85
+ @lifecycle_mutex.synchronize do
86
+ next false if @shut_down
87
+
88
+ (@sign_in_flows ||= []) << flow
89
+ true
90
+ end
91
+ end
92
+
93
+ # Its card, unless a shutdown stopped it already; one that stopped it
94
+ # while the card showed gets its ended card again, after this one.
95
+ def show_sign_in_card(flow, card)
96
+ return unless flow.waiting?
97
+
98
+ sign_in_card(flow.bundle, id: flow.card_id, **card)
99
+ ended = Plugin::SignIn.ended_card(flow, flow.outcome) unless flow.waiting?
100
+ sign_in_card(flow.bundle, **ended) if ended
101
+ end
102
+
103
+ # Read off the lock: a flow past its deadline ends in #waiting?, and
104
+ # its #sign_in_settled takes the lock.
105
+ def waiting_sign_ins
106
+ @lifecycle_mutex.synchronize { (@sign_in_flows || []).dup }.select(&:waiting?)
107
+ end
108
+
109
+ # The worker leaves (#shutdown): each waiting flow stops, its card
110
+ # replaced by the cancelled one, before the services go.
111
+ def stop_sign_ins
112
+ waiting_sign_ins.each(&:stop)
113
+ end
114
+
115
+ # A flow ended: it leaves the list; one that ended without a callback
116
+ # gets its ended card in place of its button. :done leaves the card
117
+ # for the bundle's result.
118
+ def sign_in_settled(flow, outcome)
119
+ @lifecycle_mutex.synchronize { @sign_in_flows&.delete(flow) }
120
+ Log.info(:plugins, "sign_in_ended", bundle: flow.bundle, card: flow.card_id, outcome: outcome)
121
+ card = Plugin::SignIn.ended_card(flow, outcome)
122
+ sign_in_card(flow.bundle, **card) if card
123
+ rescue StandardError => e
124
+ Log.warn(:plugins, "sign_in_card_failed", bundle: flow.bundle, error: e.class.name)
125
+ end
126
+
127
+ # A flow's card is never a running turn's (a timeout fires whenever):
128
+ # Engine#show_card's between_turns.
129
+ def sign_in_card(bundle, **card)
130
+ show_card(source: bundle, **card, between_turns: true)
131
+ end
132
+
133
+ # Its host and path: an authorize address can carry a login hint.
134
+ def address_shown(address)
135
+ uri = URI.parse(address)
136
+ "#{uri.host}#{uri.path}"
137
+ rescue URI::InvalidURIError
138
+ "?"
139
+ end
140
+ end
141
+ end
142
+ end
@@ -13,7 +13,7 @@ module Samagotchi
13
13
  # after-turn hooks, a stop before the model, the release, what an ending
14
14
  # keeps (TurnEndings, forwarded), last_turn, the answer's display.
15
15
  # Writes @last_context_status; reads @turn_endings, @turn_state,
16
- # @steer_cut, @hooks, @session_observer, @client.
16
+ # @steer_cut, @hooks, @event_log, @client.
17
17
  module TurnEndPart
18
18
  # How the turn ended, on the session (Session#last_turn): the caller's
19
19
  # save puts it in the file the session hub watches. Public for the
@@ -69,9 +69,9 @@ module Samagotchi
69
69
  replace_session_messages(session, messages[0...-1] + [merged])
70
70
  event = { type: :answer_display, display: changed ? display.text : nil }
71
71
  event[:refs] = refs.count if added
72
- @session_observer.notify(event)
72
+ @event_log.notify(event)
73
73
  elsif pending
74
- @session_observer.notify({ type: :answer_display, display: nil })
74
+ @event_log.notify({ type: :answer_display, display: nil })
75
75
  end
76
76
  end
77
77
  end
@@ -125,6 +125,7 @@ require_relative "engine/models"
125
125
  require_relative "engine/model_settings"
126
126
  require_relative "engine/events"
127
127
  require_relative "engine/cards"
128
+ require_relative "engine/sign_in"
128
129
  require_relative "engine/objectives"
129
130
  require_relative "engine/messages"
130
131
  require_relative "engine/plugins"
@@ -162,6 +163,7 @@ module Samagotchi
162
163
  include ModelSettingsPart
163
164
  include EventsPart
164
165
  include CardsPart
166
+ include SignInPart
165
167
  include ObjectivesPart
166
168
  include MessagesPart
167
169
  include PluginsPart
@@ -327,7 +329,7 @@ module Samagotchi
327
329
  # Who is in the review now, and who came or went (#announce_participants).
328
330
  @participants_watch = ParticipantsWatch.new(session_id: -> { @session&.id }, state_dir: -> { session_state_dir })
329
331
  @session = nil
330
- @session_observer = SessionObserver.new
332
+ @event_log = SessionObserver.new
331
333
  @metrics = SessionMetrics.new
332
334
  @used_memories = UsedMemories.new
333
335
  # Hydrate from resumed session if present
@@ -348,7 +350,7 @@ module Samagotchi
348
350
  # recap). Both jobs read the activity seam above; the scheduler owns
349
351
  # the single background thread and isolates per-job failures.
350
352
  @idle_scheduler = build_idle_scheduler
351
- subscribe_session_observers
353
+ subscribe_log_observers
352
354
  # The UIs' read model (/state, /stats). Built last: nothing calls a
353
355
  # snapshot while the Engine is built.
354
356
  @engine_snapshots = build_engine_snapshots
@@ -381,6 +383,9 @@ module Samagotchi
381
383
  # commands running now (#spawn_anytime), which it waits for.
382
384
  @services = Plugin::Services.new
383
385
  @anytime_threads = []
386
+ # ctx.sign_in's flows waiting for their callback (SignInPart), which
387
+ # #shutdown stops first.
388
+ @sign_in_flows = []
384
389
  # chi.init tasks (#add_init_task), started by #start_init_tasks!, and
385
390
  # plugins' tool sets from chi.replace_tools until the turn thread
386
391
  # applies them (#apply_staged_tools!). Built before the plugins load.
@@ -426,19 +431,19 @@ module Samagotchi
426
431
  private :restrict_scratch_tools!
427
432
 
428
433
  # The persistent observers of every turn's events.
429
- def subscribe_session_observers
434
+ def subscribe_log_observers
430
435
  # The metrics collector is a persistent observer so every run_turn event
431
436
  # (a -p --non-interactive one-shot and SessionManager workers)
432
437
  # feeds it automatically.
433
- @session_observer.subscribe(observer: @metrics)
438
+ @event_log.subscribe(observer: @metrics)
434
439
  # And the event trail in the debug log (`turn` records).
435
- @session_observer.subscribe(observer: LogSubscriber.new(session_id: -> { @session&.id }))
440
+ @event_log.subscribe(observer: LogSubscriber.new(session_id: -> { @session&.id }))
436
441
  # The thinking of cut and capped generations, kept in the session dir.
437
- @session_observer.subscribe(observer: ThinkingTails.new(session_dir: lambda {
442
+ @event_log.subscribe(observer: ThinkingTails.new(session_dir: lambda {
438
443
  @session&.id && Session.session_dir(@session.id, state_dir: session_state_dir)
439
444
  }))
440
445
  end
441
- private :subscribe_session_observers
446
+ private :subscribe_log_observers
442
447
 
443
448
  # The kernel and what it holds of the Engine for its life, one
444
449
  # KernelLoop::Services (stores, hooks, tools, the mutes, the question
@@ -517,7 +522,7 @@ module Samagotchi
517
522
  # The event fan-out and the stream handler (see #initialize for when).
518
523
  def build_event_fanout
519
524
  EventFanout.new(
520
- observer: -> { @session_observer },
525
+ observer: -> { @event_log },
521
526
  used_memories: -> { @used_memories },
522
527
  muted: -> { @muted_memory_names },
523
528
  steer_cut: -> { @steer_cut },
@@ -547,7 +552,7 @@ module Samagotchi
547
552
  EngineSnapshots.new(
548
553
  session: -> { @session },
549
554
  metrics: -> { @metrics },
550
- observer: -> { @session_observer },
555
+ observer: -> { @event_log },
551
556
  question_desk: -> { @question_desk },
552
557
  used_memories: -> { @used_memories },
553
558
  muted: -> { @muted_memory_names },
@@ -628,7 +633,7 @@ module Samagotchi
628
633
 
629
634
  # The idle layer's shared scheduler (see #initialize for when).
630
635
  def build_idle_scheduler
631
- IdleScheduler.new(engine: self, jobs: [@reminders, @recap].compact)
636
+ IdleScheduler.new(jobs: [@reminders, @recap].compact)
632
637
  end
633
638
  private :build_idle_scheduler
634
639
 
@@ -643,6 +648,22 @@ module Samagotchi
643
648
  # @return [SessionMetrics] the per-session analytics collector
644
649
  attr_reader :metrics
645
650
 
651
+ # @return [SessionObserver] the session's event log: the Worker hands it
652
+ # to the Bridge and its collaborators, which call it directly
653
+ attr_reader :event_log
654
+
655
+ # @return [TurnState] the turn as other threads see it: the Worker hands
656
+ # it to the Bridge and its collaborators, which call it directly
657
+ attr_reader :turn_state
658
+
659
+ # @return [QuestionDesk] the one open question: the Worker hands it to
660
+ # the Bridge and its collaborators, which call it directly
661
+ attr_reader :question_desk
662
+
663
+ # @return [SteerCut] the mid-turn steer cut: the Worker hands it to the
664
+ # Bridge, which calls it directly
665
+ attr_reader :steer_cut
666
+
646
667
  attr_reader :default_model_name, :host_registry, :client
647
668
 
648
669
  # @return [Commands::Registry] the commands this session runs: the
@@ -652,15 +673,6 @@ module Samagotchi
652
673
  # @return [PeerSources] the sources the peer bundles declared
653
674
  attr_reader :peer_sources
654
675
 
655
- # Event types #announce accepts: facts about the session's input queue,
656
- # a failed turn's prompt handed back and the continue offer, which live
657
- # UIs need in the event log, emitted outside any turn's stream; a
658
- # Verify fresh child's verdict landing on its card (:verdict_recorded).
659
- ANNOUNCEABLE_EVENTS = %i[turn_enqueued turn_dequeued input_merged prompt_restored continue_offered continue_resolved
660
- command_queued command_ran context_added card hook_notice guardrail_warning
661
- plugin_init_started plugin_init_finished working_set_updated participants_changed
662
- verdict_recorded objectives_updated].freeze
663
-
664
676
  # ── Plugin init tasks (chi.init) ──────────────────────────────────────
665
677
 
666
678
  # A plugin's slow setup (docs/plugins.md, Init tasks): PluginTasks.
@@ -676,7 +688,8 @@ module Samagotchi
676
688
  SIDE_JUDGMENTS_JOIN_SECONDS = 1.0
677
689
 
678
690
  # The session's worker (or a one-shot run) is leaving (/exit, an idle
679
- # exit, a crash, TERM): stop the idle jobs, give the running anytime commands
691
+ # exit, a crash, TERM): stop the waiting sign-ins (their cards say
692
+ # cancelled) and the idle jobs, give the running anytime commands
680
693
  # up to +join_timeout+ seconds to finish (their command_ran is
681
694
  # announced), and settle already-reaped tasks under a shared deadline
682
695
  # of at least TaskRuntime::SETTLE_ON_EXIT_SECONDS. Then stop the plugins'
@@ -690,6 +703,9 @@ module Samagotchi
690
703
  # An init task's requests end (a server's boot), so it finishes.
691
704
  @anytime_threads.dup + @plugin_tasks.shut_down!
692
705
  end
706
+ # A waiting sign-in's card says cancelled while the Bridge still
707
+ # listens (its cards.json), and its port closes.
708
+ stop_sign_ins
693
709
  # #stop_idle's work (the scheduler's stop is idempotent), where the
694
710
  # callers haven't stopped it already.
695
711
  @idle_scheduler&.stop
@@ -810,7 +826,9 @@ module Samagotchi
810
826
  # @return [IdleRecap, nil]
811
827
  def build_recap
812
828
  @recap_built_for = session_recap_values
813
- recap = RecapSetup.build(@recap_kwarg, engine: self, host_registry: @host_registry,
829
+ recap = RecapSetup.build(@recap_kwarg, turn_state: @turn_state, messages_json: -> { messages_json_for_recap },
830
+ emit_recap: ->(**fields) { emit_recap(**fields) },
831
+ on_usage: ->(usage) { note_side_usage(usage) }, host_registry: @host_registry,
814
832
  session_target: -> { session_model_recap_target },
815
833
  session_id: -> { @session&.id }, state_dir: -> { session_state_dir },
816
834
  session_config: -> { @session&.settings&.core })
@@ -1252,14 +1270,12 @@ module Samagotchi
1252
1270
 
1253
1271
  def running_command_key = :"samagotchi_command_#{object_id}"
1254
1272
 
1255
- # The one named seam for replacing a session's conversation (the
1256
- # array is replaced, never mutated in place). No lock: a reader gets
1257
- # the old array or the new one, and both are whole.
1258
- # The turn as other threads see it (TurnState).
1259
- attr_reader :turn_state
1260
1273
  # The due reminders on their way into a turn (ReminderQueue).
1261
1274
  attr_reader :reminder_queue
1262
1275
 
1276
+ # The one named seam for replacing a session's conversation (the
1277
+ # array is replaced, never mutated in place). No lock: a reader gets
1278
+ # the old array or the new one, and both are whole.
1263
1279
  def replace_session_messages(session, messages)
1264
1280
  session.messages = messages
1265
1281
  end
@@ -1307,7 +1323,7 @@ module Samagotchi
1307
1323
  def build_reminders(auto_turn_callback: nil)
1308
1324
  @auto_turn_callback = auto_turn_callback
1309
1325
  IdleReminders.new(
1310
- engine: self,
1326
+ turn_state: @turn_state,
1311
1327
  queue: @reminder_queue,
1312
1328
  callback: @auto_turn_callback
1313
1329
  )
@@ -118,7 +118,7 @@ module Samagotchi
118
118
  # :status [String, nil] current session status
119
119
  # :message_count [Integer] number of messages in the session
120
120
  # :last_prompt [String, nil] the last user prompt (empty string if none)
121
- # :event_seq [Integer] @session_observer.event_count
121
+ # :event_seq [Integer] @event_log.event_count
122
122
  # :metrics [Hash] @metrics.snapshot (per-session analytics)
123
123
  # :pending_question [Hash, nil] the pending question (PendingQuestion#to_h)
124
124
  # :used_memory_names [Array<String>] deduped memory names active this session
@@ -271,6 +271,7 @@ module Samagotchi
271
271
  require_relative "context_sources"
272
272
  require_relative "chi_home"
273
273
  require_relative "chi_shim"
274
+ require_relative "paths"
274
275
  Guardrails::ProtectedPaths.new(
275
276
  store_dir: File.dirname(@approvals.path),
276
277
  bundles_dir: InstalledBundles.dir,
@@ -279,7 +280,8 @@ module Samagotchi
279
280
  context_dir: ContextSources.root,
280
281
  runs_dir: File.join(File.dirname(@approvals.path, 2), "system_one"),
281
282
  home_path: ChiHome.path,
282
- shim_path: ChiShim.path
283
+ shim_path: ChiShim.path,
284
+ plugins_dir: File.join(Paths.state_dir, "plugins")
283
285
  )
284
286
  end
285
287
  end
@@ -25,8 +25,22 @@ module Samagotchi
25
25
  # breaking it.
26
26
  # execute can still write all of them (the guardrails bundle adds a
27
27
  # text match for that).
28
+ #
29
+ # A bundle's secrets (<state dir>/plugins/<bundle>/secrets, ctx.secrets)
30
+ # are kept from chi's model whatever the call does: every file tool's
31
+ # path there is denied, read included, and a shell command that names
32
+ # the folder asks once (the user only). An accident guard, not a
33
+ # sandbox: a command that doesn't name it (cd there first, a variable,
34
+ # a script) still reads it.
28
35
  class ProtectedPaths
29
36
  SOURCE = "core"
37
+ SECRETS_RULE = "bundle-secrets"
38
+ SECRETS_SHELL_RULE = "bundle-secrets-shell"
39
+ SECRETS_REASON = "a bundle's secrets (tokens) are its own: chi's model doesn't read or change them"
40
+ SECRETS_SHELL_REASON = "the command names a bundle's secrets folder (its tokens)"
41
+ # A command naming a secrets folder under chi's state dir, as typed:
42
+ # the dir's name (samagotchi), then plugins/<bundle or a glob>/secrets.
43
+ SECRETS_TEXT = %r{samagotchi/plugins/[^/\s'"]+/secrets(?![\w.-])}
30
44
 
31
45
  # @param store_dir [String] <state dir>/guardrails
32
46
  # @param bundles_dir [String] <memories>/.bundles
@@ -36,7 +50,14 @@ module Samagotchi
36
50
  # @param runs_dir [String, nil] <state dir>/system_one (SystemOne::Runs)
37
51
  # @param home_path [String, nil] home.json (ChiHome.path)
38
52
  # @param shim_path [String, nil] the chi shim (ChiShim.path)
39
- def initialize(store_dir:, bundles_dir:, config_path:, hooks_dir:, context_dir: nil, runs_dir: nil, home_path: nil, shim_path: nil)
53
+ # @param plugins_dir [String, nil] <state dir>/plugins (the bundles' data, their secrets/ in it)
54
+ def initialize(store_dir:, bundles_dir:, config_path:, hooks_dir:, context_dir: nil, runs_dir: nil, home_path: nil, shim_path: nil,
55
+ plugins_dir: nil)
56
+ @plugins_dir = plugins_dir
57
+ # The same, spelled out: this state dir's own plugins/<x>/secrets.
58
+ @secrets_text = plugins_dir && Regexp.union(SECRETS_TEXT, *([plugins_dir.to_s.chomp("/")] | PathResolve.reals(plugins_dir.to_s.chomp("/"))).map do |dir|
59
+ %r{#{Regexp.escape(dir)}/[^/\s'"]+/secrets(?![\w.-])}
60
+ end)
40
61
  @deny = [
41
62
  ["guardrail-store", store_dir, "the approval store belongs to the user"],
42
63
  ["installed-bundles", bundles_dir, "installed bundles (hooks, rules, manifests) are changed by chi bundle install"],
@@ -56,7 +77,10 @@ module Samagotchi
56
77
  # targets: writes: true) is judged on its paths.
57
78
  def check(verdict)
58
79
  targets = verdict.targets
59
- return verdict unless targets&.writes?
80
+ return verdict unless targets
81
+
82
+ check_secrets(verdict, targets)
83
+ return verdict unless targets.writes?
60
84
 
61
85
  paths = targets.paths.flat_map { |p| PathResolve.reals(p) }
62
86
  @deny.each do |rule, root, reason|
@@ -72,6 +96,16 @@ module Samagotchi
72
96
  verdict
73
97
  end
74
98
 
99
+ # Whether +path+ (absolute, resolved) is a bundle's secrets folder or
100
+ # in it: <plugins dir>/<bundle>/secrets[/…].
101
+ def secrets_path?(path)
102
+ return false unless @plugins_dir
103
+
104
+ PathResolve.reals(@plugins_dir.to_s.chomp("/")).any? do |dir|
105
+ PathResolve.under?(path, dir) && path[(dir.length + 1)..].to_s.split("/")[1]&.casecmp?("secrets")
106
+ end
107
+ end
108
+
75
109
  # The path primitives (PathResolve) as this class has long named
76
110
  # them; specs and older callers reach them here.
77
111
  def self.expand(path, base = nil) = PathResolve.expand(path, base)
@@ -81,6 +115,21 @@ module Samagotchi
81
115
  def self.within?(path, root) = PathResolve.within?(path, root)
82
116
  def self.under?(path, dir) = PathResolve.under?(path, dir)
83
117
  def self.folds_case?(path) = PathResolve.folds_case?(path)
118
+
119
+ private
120
+
121
+ def check_secrets(verdict, targets)
122
+ return unless @plugins_dir
123
+
124
+ paths = targets.paths.flat_map { |p| PathResolve.reals(p) }
125
+ if targets.shell?
126
+ return unless paths.any? { |p| secrets_path?(p) } || targets.command.to_s.match?(@secrets_text)
127
+
128
+ verdict.ask!(SECRETS_SHELL_REASON, scopes: %w[once], rule: SECRETS_SHELL_RULE, source: SOURCE, decided_by: "core")
129
+ elsif paths.any? { |p| secrets_path?(p) }
130
+ verdict.deny!(SECRETS_REASON, rule: SECRETS_RULE, source: SOURCE, decided_by: "core")
131
+ end
132
+ end
84
133
  end
85
134
  end
86
135
  end
@@ -19,13 +19,14 @@ module Samagotchi
19
19
  # that reaches the system prompt, or a model overlay, is written (a
20
20
  # parent model would be writing a model's prompt); and the bundle's
21
21
  # asks before answering chi's questions around chi answer (a parent
22
- # allowing one would answer a grandchild's question as the user).
22
+ # allowing one would answer a grandchild's question as the user); and
23
+ # a shell command that names a bundle's secrets (ProtectedPaths).
23
24
  # A parent agent may never allow them (ParentApprovals.protected?,
24
25
  # ParentPolicy's user_only); System 1 may, only if the user lists the
25
26
  # rule by name in guardrails.system_one.rules, and never for the
26
27
  # chi-answer/chi-broadcast ones (SystemOne::SelfProtect::NEVER_AUTO).
27
28
  PROTECTED_RULES = %w[chi-config chi-home chi-shim chi-hooks shell-touches-chi chi-context-cmd chi-broadcast prompt-memory-write
28
- model-overlay-write chi-answer-piped chi-answer-http].freeze
29
+ model-overlay-write chi-answer-piped chi-answer-http bundle-secrets-shell].freeze
29
30
  SCOPES = %w[once session repo rule].freeze
30
31
  # Who answered an ask when it was a parent agent, not the user.
31
32
  PARENT_AGENT = "parent agent"
@@ -24,13 +24,13 @@ module Samagotchi
24
24
  def any? = reminders.any? || tasks.any? || delegates.any?
25
25
  end
26
26
 
27
- # @param engine [Engine] #reminder_store
27
+ # @param reminder_store [ReminderStore, nil] the session's reminders
28
28
  # @param task_watch [TaskWatch, nil] this session's finish-wake watch
29
29
  # (nil with session.task_wakes: off)
30
30
  # @param delegates [#call] the children to stop (ChildrenStatus::Child)
31
31
  # @param state_dir [String] where the child sessions live
32
- def initialize(engine:, task_watch:, delegates:, state_dir:)
33
- @engine = engine
32
+ def initialize(reminder_store:, task_watch:, delegates:, state_dir:)
33
+ @reminder_store = reminder_store
34
34
  @task_watch = task_watch
35
35
  @delegates = delegates
36
36
  @state_dir = state_dir
@@ -49,7 +49,7 @@ module Samagotchi
49
49
  # Reminders live only in this process, so clearing the store ends them;
50
50
  # the names go to the report before it is emptied.
51
51
  def stop_reminders
52
- store = @engine.reminder_store
52
+ store = @reminder_store
53
53
  return [] unless store
54
54
 
55
55
  names = store.reminders.values.map { |reminder| reminder[:name] }
@@ -19,7 +19,7 @@ module Samagotchi
19
19
  # IdleScheduler (one background thread for the whole idle layer).
20
20
  #
21
21
  # Owns the inactivity clock bookkeeping shared across UIs: it reads the
22
- # Engine's `last_activity_at` / `activity_seq` / `turn_running?` seam (the
22
+ # Engine's TurnState (`last_activity_at` / `activity_seq` / `running?`, the
23
23
  # single source of truth) rather than tracking its own timeline, so the
24
24
  # clock behaves identically for any Engine-backed worker.
25
25
  #
@@ -308,7 +308,13 @@ module Samagotchi
308
308
  # @param base_url [String] the OpenAI API base the recap asks
309
309
  # @param api_key_env [String, nil] the variable holding its key
310
310
  # @param target [#call, nil] -> IdleTarget
311
- def initialize(engine:, model: nil, base_url: nil, api_key_env: nil, target: nil,
311
+ # @param turn_state [TurnState] the Engine's (Engine#turn_state): whether a
312
+ # turn runs, the activity seq and the latest activity's time
313
+ # @param messages_json [#call] → the conversation to recap, as a JSON
314
+ # string (Engine#messages_json_for_recap)
315
+ # @param emit_recap [#call] (recap:, generation:, covered:, created_at:)
316
+ # announces a written recap (Engine#emit_recap)
317
+ def initialize(turn_state:, messages_json:, emit_recap:, model: nil, base_url: nil, api_key_env: nil, target: nil,
312
318
  inactivity: DEFAULT_INACTIVITY_SECONDS,
313
319
  min_user_turns: DEFAULT_MIN_USER_TURNS,
314
320
  timeout: DEFAULT_TIMEOUT_SECONDS,
@@ -318,9 +324,11 @@ module Samagotchi
318
324
  session_id: -> {},
319
325
  on_usage: nil,
320
326
  clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
321
- raise ArgumentError, "IdleRecap requires an engine" unless engine
327
+ raise ArgumentError, "IdleRecap requires a turn state" unless turn_state
322
328
 
323
- @engine = engine
329
+ @turn_state = turn_state
330
+ @messages_json = messages_json
331
+ @emit_recap = emit_recap
324
332
  # The recapped session's id, sent with the request (IdleClient#summarize).
325
333
  @session_id = session_id
326
334
  # Called with each recap request's SideUsage (IdleClient#summarize),
@@ -381,7 +389,7 @@ module Samagotchi
381
389
  def request_now
382
390
  @run_mutex.synchronize do
383
391
  next :in_flight if in_flight?
384
- next :busy if @engine.turn_running?
392
+ next :busy if @turn_state.running?
385
393
 
386
394
  start
387
395
  end
@@ -427,14 +435,14 @@ module Samagotchi
427
435
 
428
436
  # @return [Boolean] true when a recap is eligible to fire right now.
429
437
  def should_fire?
430
- return false if @engine.turn_running?
438
+ return false if @turn_state.running?
431
439
  return false unless last_idle_seconds >= @inactivity
432
440
  # Fire at most once per idle window: require that activity advanced the
433
441
  # shared seq since the last fire. Pure monotonic time passing does NOT
434
442
  # bump the seq, so a long idle window only summarizes once.
435
443
  return true if @last_fire_activity_seq.nil?
436
444
 
437
- @engine.activity_seq > @last_fire_activity_seq
445
+ @turn_state.activity_seq > @last_fire_activity_seq
438
446
  end
439
447
 
440
448
  # SHA1 of one message's role and text: detects a rewrite a count alone
@@ -458,7 +466,7 @@ module Samagotchi
458
466
  end
459
467
 
460
468
  def last_idle_seconds
461
- @clock.call - @engine.last_activity_at
469
+ @clock.call - @turn_state.last_activity_at
462
470
  end
463
471
 
464
472
  # Start an attempt: snapshot, build the prompt, and spawn the summarize
@@ -469,8 +477,8 @@ module Samagotchi
469
477
  # Latch the attempt, not the success: a short history, a failed or
470
478
  # empty summary, or an invalidated run must not re-fire on every
471
479
  # scheduler tick. The next recorded activity re-arms the window.
472
- @last_fire_activity_seq = @engine.activity_seq
473
- parsed = safe_parse(@engine.messages_json_for_recap)
480
+ @last_fire_activity_seq = @turn_state.activity_seq
481
+ parsed = safe_parse(@messages_json.call)
474
482
  return :too_short if parsed.nil?
475
483
 
476
484
  # The turns as the page counts them (Steer.turn_opening?): not Qwen's
@@ -533,7 +541,7 @@ module Samagotchi
533
541
  model: served || job[:model], created_at: Time.now.utc.iso8601 }.compact
534
542
  @mutex.synchronize { @state = saved }
535
543
  save(saved)
536
- @engine.emit_recap(recap: text, generation: job[:generation], covered: job[:covered], created_at: saved[:created_at])
544
+ @emit_recap.call(recap: text, generation: job[:generation], covered: job[:covered], created_at: saved[:created_at])
537
545
  rescue StandardError
538
546
  @in_flight = nil
539
547
  end
@@ -19,13 +19,15 @@ module Samagotchi
19
19
 
20
20
  attr_reader :inactivity
21
21
 
22
- def initialize(engine:, inactivity: DEFAULT_MIN_INACTIVITY_SECONDS,
22
+ # @param turn_state [TurnState] the Engine's (Engine#turn_state): whether
23
+ # a turn runs, and when the latest activity was
24
+ def initialize(turn_state:, inactivity: DEFAULT_MIN_INACTIVITY_SECONDS,
23
25
  queue: nil,
24
26
  clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) },
25
27
  callback: nil)
26
- raise ArgumentError, "IdleReminders requires an engine" unless engine
28
+ raise ArgumentError, "IdleReminders requires a turn state" unless turn_state
27
29
 
28
- @engine = engine
30
+ @turn_state = turn_state
29
31
  @inactivity = inactivity
30
32
  @queue = queue
31
33
  @clock = clock
@@ -43,7 +45,7 @@ module Samagotchi
43
45
 
44
46
  # @return [Boolean] true when it's time to check for reminders.
45
47
  def should_check?
46
- return false if @engine.turn_running?
48
+ return false if @turn_state.running?
47
49
  return false unless last_idle_seconds >= @inactivity
48
50
 
49
51
  true
@@ -52,7 +54,7 @@ module Samagotchi
52
54
  private
53
55
 
54
56
  def last_idle_seconds
55
- @clock.call - @engine.last_activity_at
57
+ @clock.call - @turn_state.last_activity_at
56
58
  end
57
59
 
58
60
  def check_due_reminders