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
@@ -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
@@ -4,16 +4,16 @@ require "monitor"
4
4
  require_relative "log"
5
5
 
6
6
  module Samagotchi
7
- # Shared background poller for all Engine-owned idle subsystems
8
- # (currently: IdleReminders and the optional IdleRecap).
7
+ # Shared background poller for idle subsystems (currently: IdleReminders
8
+ # and the optional IdleRecap).
9
9
  #
10
10
  # Previously each subsystem ran its own 0.5s polling thread against the
11
- # Engine's `last_activity_at` / `activity_seq` / `turn_running?` seam.
11
+ # Engine's TurnState (`last_activity_at` / `activity_seq` / `running?`).
12
12
  # Now a single thread steps every registered job in turn, so the whole
13
- # idle layer polls the Engine seam from one loop.
13
+ # idle layer polls from one loop.
14
14
  #
15
15
  # Jobs must implement `tick`. Each job keeps its own eligibility guard
16
- # (e.g. `should_fire?` / `should_check?`, including the `turn_running?`
16
+ # (e.g. `should_fire?` / `should_check?`, including the `running?`
17
17
  # check) and its own internal state (generation ids, latches). A job that
18
18
  # raises is logged and isolated — the remaining jobs keep polling.
19
19
  class IdleScheduler
@@ -23,14 +23,11 @@ module Samagotchi
23
23
  STOP_JOIN_SECONDS = 1.0
24
24
  THREAD_NAME = "idle_scheduler"
25
25
 
26
- attr_reader :engine, :jobs, :interval
26
+ attr_reader :jobs, :interval
27
27
 
28
28
  # +interval+: the pause between ticks (a spec passes a long one, so its
29
29
  # own #tick is the only one after the first).
30
- def initialize(engine:, jobs: [], interval: POLL_INTERVAL_SECONDS)
31
- raise ArgumentError, "IdleScheduler requires an engine" unless engine
32
-
33
- @engine = engine
30
+ def initialize(jobs: [], interval: POLL_INTERVAL_SECONDS)
34
31
  @jobs = jobs.compact.freeze
35
32
  @interval = interval
36
33
  # The loop's pause: a pop with the interval as its timeout, which
@@ -51,6 +51,35 @@ module Samagotchi
51
51
  file ? File.join(plugin_dir, file) : nil
52
52
  end
53
53
 
54
+ # The plugin's parts as installed (plugin/<part>), in load order; []
55
+ # without a plugin or parts.
56
+ # @param bundle [Record, nil] its record (read when not given)
57
+ def plugin_part_paths(bundle = record)
58
+ (bundle&.plugin&.parts || {}).keys.map { |part| File.join(plugin_dir, part) }
59
+ end
60
+
61
+ # Why chi won't load this installed bundle's plugin, nil when every file
62
+ # of it is as installed: the plugin file's #file_refusal, then each
63
+ # part's in load order, the first one found. A record without parts
64
+ # whose kept manifest names some (an older chi installed the plugin file
65
+ # alone: it doesn't read parts:) is refused as :parts_missing, read from
66
+ # the record's Manifest (no kept manifest, or one that doesn't read: no
67
+ # refusal of this kind). The loader, `chi bundle status` and the session
68
+ # settings all ask this.
69
+ # @param bundle [Record] its record, with a plugin
70
+ # @return [Refusal, nil]
71
+ def plugin_refusal(bundle)
72
+ plugin = bundle.plugin
73
+ refusal = file_refusal(:plugin, plugin&.file, plugin&.sha256)
74
+ return refusal if refusal || plugin.nil?
75
+
76
+ plugin.parts.each do |part, sha|
77
+ refusal = file_refusal(:plugin, part, sha)
78
+ return refusal if refusal
79
+ end
80
+ parts_missing(bundle)
81
+ end
82
+
54
83
  # Why chi won't load or run this installed file, nil when it is as
55
84
  # installed: the one "is this file as installed" check of what chi loads
56
85
  # (the plugin), runs (a provider's scripts), serves (a renderer's
@@ -80,6 +109,14 @@ module Samagotchi
80
109
  text: "#{what} differs from the installed one (reinstall the bundle)")
81
110
  end
82
111
 
112
+ # #plugin_refusal's :parts_missing: the kept manifest names parts the record has none of.
113
+ def parts_missing(bundle)
114
+ return nil unless bundle.plugin.parts.empty? && bundle.manifest.plugin_parts.any?
115
+
116
+ Refusal.new(kind: :parts_missing, text: "bundle #{@name}'s plugin parts aren't installed (reinstall the bundle)")
117
+ end
118
+ private :parts_missing
119
+
83
120
  # The installed bundle's record, nil when it isn't installed.
84
121
  # @return [Record, nil]
85
122
  # @raise [JSON::ParserError] manifest.json doesn't parse
@@ -52,6 +52,9 @@ module Samagotchi
52
52
  # call): the record's (PluginRef#required,
53
53
  # recorded at install) or the kept manifest's,
54
54
  # so a lost or edited kept file keeps it
55
+ # plugin_parts the names of the plugin's parts (plugin:
56
+ # parts:) in load order: the kept manifest's,
57
+ # the record's from the mirror (PluginRef#parts)
55
58
  # includes a profile's recorded members (the record's
56
59
  # identity, never the kept file's), nil for a plain bundle
57
60
  # unknown_keys the kept manifest's keys this chi doesn't know
@@ -61,7 +64,8 @@ module Samagotchi
61
64
  class Manifest < Data.define(:name, :version, :requires_chi, :trust_level, :description, :needs,
62
65
  :script_names, :context_providers, :block_renderers, :session_settings,
63
66
  :session_setting_types, :settings, :setting_types, :file_descriptions,
64
- :plugin_required, :includes, :unknown_keys, :floor_keys, :problems, :origin)
67
+ :plugin_required, :plugin_parts, :includes, :unknown_keys, :floor_keys, :problems,
68
+ :origin)
65
69
  # The key problems names the kept file's standing under.
66
70
  KEPT_FILE = "manifest.yml"
67
71
  # How many manifests the cache holds before it starts again.
@@ -135,6 +139,7 @@ module Samagotchi
135
139
  settings: settings.settings, setting_types: settings.setting_types,
136
140
  file_descriptions: pick.call("files", kept.file_descriptions, mirrored.file_descriptions),
137
141
  plugin_required: kept.plugin&.dig(:required) == true || mirrored.plugin_required,
142
+ plugin_parts: pick.call("plugin", kept.plugin_parts.keys, mirrored.plugin_parts),
138
143
  includes: bundle.includes,
139
144
  unknown_keys: kept.unknown_keys.map(&:to_s), floor_keys: floors(kept), problems: problems.freeze, origin: :kept)
140
145
  end
@@ -161,6 +166,7 @@ module Samagotchi
161
166
  setting_types: types(raw["setting_types"]),
162
167
  file_descriptions: file_descriptions(bundle.files),
163
168
  plugin_required: bundle.plugin&.required == true,
169
+ plugin_parts: bundle.plugin ? bundle.plugin.parts.keys : [],
164
170
  includes: bundle.includes, unknown_keys: [], floor_keys: {}, problems: problems.freeze, origin: :record)
165
171
  end
166
172
 
@@ -6,10 +6,12 @@ module Samagotchi
6
6
  # file under plugin/, the sha256 recorded at install ("" when none
7
7
  # is; either "sha256:<hex>" or a bare hex, Sha.recorded
8
8
  # reads both), and whether its manifest called it required (a guardrail
9
- # plugin: plugin: required: true; an older chi ignores the key).
10
- PluginRef = Data.define(:file, :sha256, :required) do
11
- def initialize(file:, sha256: "", required: false)
12
- super
9
+ # plugin: plugin: required: true; an older chi ignores the key), and its
10
+ # parts (plugin: parts:, beside the file in plugin/): name => sha256 as
11
+ # recorded, in load order, {} without any (an older chi ignores the key).
12
+ PluginRef = Data.define(:file, :sha256, :required, :parts) do
13
+ def initialize(file:, sha256: "", required: false, parts: {})
14
+ super(file: file, sha256: sha256, required: required, parts: parts.to_h { |name, sha| [name.to_s, sha.to_s] }.freeze)
13
15
  end
14
16
 
15
17
  # @param raw [Hash, PluginRef, nil] the record's plugin: mapping
@@ -21,7 +23,9 @@ module Samagotchi
21
23
 
22
24
  h = raw.transform_keys(&:to_s)
23
25
  file = h["file"].to_s
24
- file.empty? ? nil : new(file: file, sha256: h["sha256"].to_s, required: h["required"] == true)
26
+ return nil if file.empty?
27
+
28
+ new(file: file, sha256: h["sha256"].to_s, required: h["required"] == true, parts: h["parts"].is_a?(Hash) ? h["parts"] : {})
25
29
  end
26
30
  end
27
31
  end
@@ -133,8 +133,9 @@ module Samagotchi
133
133
 
134
134
  def owns?(file_key) = files.key?(file_key.to_s)
135
135
 
136
- # The plugin's file => its recorded sha256, as guardrails and scripts read.
137
- def plugin_shas = plugin ? { plugin.file => plugin.sha256 } : {}
136
+ # The plugin's files (its parts, then the plugin file) => their recorded
137
+ # sha256, as guardrails and scripts read.
138
+ def plugin_shas = plugin ? plugin.parts.merge(plugin.file => plugin.sha256) : {}
138
139
 
139
140
  # The marked files that stay behind: one that isn't there is a missing file,
140
141
  # and one with the bundle's bytes has nothing left to miss.
@@ -10,7 +10,9 @@ module Samagotchi
10
10
  # kind :unreadable (the record: manifest.json doesn't read),
11
11
  # :too_new (its requires_chi isn't met), or for one file
12
12
  # (Dir#file_refusal) :file_missing, :file_unrecorded (no
13
- # sha256 recorded for it), :file_changed
13
+ # sha256 recorded for it), :file_changed; for a plugin
14
+ # (Dir#plugin_refusal) also :parts_missing (its kept manifest
15
+ # names parts the record has none of)
14
16
  # text what the reader says of it today (one wording per kind of
15
17
  # file: the plugin's, a script's, a rule's)
16
18
  # actual, expected the file's sha256 and the recorded one, hex, for
@@ -236,8 +236,70 @@ module Samagotchi
236
236
  end
237
237
  end
238
238
 
239
+ # The marks a streamed attempt's reader (Plugin::Http::Stream) leaves
240
+ # for the log line when the body's read fails mid-stream: the error
241
+ # then surfaces from the caller's block, mapped, and #logged tells it
242
+ # from the block's own raise by these.
243
+ class StreamMarks
244
+ def initialize(current)
245
+ @current = current
246
+ end
247
+
248
+ # The body's read failed on the wire (+error+, the raw one).
249
+ def failed(error) = @current[:wire_error] = error
250
+
251
+ # The body's read ended because the request was cancelled.
252
+ def cancelled(reason) = @current[:cancelled] = [reason]
253
+ end
254
+
255
+ # One unretried streamed attempt (ctx.http.stream): yields the
256
+ # response before its body is read, its status unchecked, and the
257
+ # StreamMarks its reader marks a mid-body failure on. Returns the
258
+ # block's value. Leaving the block closes the connection however it
259
+ # is left: Net::HTTP reads the rest of the body after a normal block
260
+ # end (on an open stream, until the read timeout), so a normal end
261
+ # throws past that drain; Net::HTTP.start's ensure closes the socket.
262
+ # No first_token_timeout or stream_idle_timeout (the model stream's).
263
+ # @raise [RequestCancelled] cancelled before the block
264
+ def open_stream(uri, request, write_timeout: nil, cancel_controller: nil, log_fields: {})
265
+ identify(request)
266
+ current = new_attempt_state(uri, request, log_fields, stream: true).merge!(attempts: 1)
267
+ marks = StreamMarks.new(current)
268
+ done = Object.new
269
+ logged(current) do
270
+ cancellable(cancel_controller, current) do
271
+ catch(done) do
272
+ start(uri, write_timeout: write_timeout, max_retries: 0) do |http|
273
+ current[:http] = http
274
+ http.request(request) do |response|
275
+ current[:status] = response.code.to_i
276
+ throw done, in_block(current) { yield(response, marks) }
277
+ end
278
+ end
279
+ end
280
+ rescue StandardError => e
281
+ if !e.is_a?(RequestCancelled) && !current[:left_by_block] && cancel_controller&.cancelled?
282
+ raise RequestCancelled, cancel_controller.reason
283
+ end
284
+
285
+ raise
286
+ end
287
+ end
288
+ end
289
+
239
290
  private
240
291
 
292
+ # The caller's block: a raise out of it marks the attempt (#logged
293
+ # logs its end then, not a failure, unless its reader marked one).
294
+ def in_block(current)
295
+ left = true
296
+ value = yield
297
+ left = false
298
+ value
299
+ ensure
300
+ current[:left_by_block] = true if left
301
+ end
302
+
241
303
  # User-Agent, and the host's key when it has one (AuthError, before
242
304
  # any request, when its variable is not set).
243
305
  def identify(request)
@@ -433,16 +495,46 @@ module Samagotchi
433
495
  # One line per request, whatever its end: done (status, time to the
434
496
  # first token of a stream, total), failed, timed out or cancelled.
435
497
  # Retries have their own WARN lines (#retry_after).
498
+ # An `ensure` logs the way out a rescue can't see (break, return, a
499
+ # throw): as done, with the status it got. A streamed attempt's block
500
+ # that raised logs done too, unless its reader marked a wire failure
501
+ # or a cancel (StreamMarks).
436
502
  def logged(current)
437
503
  result = yield
438
- Log.public_send(current[:level], :http, current[:stream] ? "stream" : "fetch", **log_base(current),
439
- status: current[:status], ttft_ms: ttft_ms(current),
440
- ms: elapsed_ms(current), attempts: retried(current))
504
+ log_end(current)
441
505
  result
442
506
  rescue RequestCancelled => e
443
- Log.public_send(current[:level], :http, "cancelled", **log_base(current), ms: elapsed_ms(current), reason: e.reason&.to_s)
507
+ log_cancelled(current, e.reason)
444
508
  raise
445
509
  rescue StandardError => e
510
+ current[:left_by_block] ? log_end(current) : log_failed(current, e)
511
+ raise
512
+ ensure
513
+ log_end(current) unless current[:logged]
514
+ end
515
+
516
+ # Done, or what a stream's reader marked (StreamMarks).
517
+ def log_end(current)
518
+ if current[:cancelled] then log_cancelled(current, current[:cancelled].first)
519
+ elsif current[:wire_error] then log_failed(current, current[:wire_error])
520
+ else log_done(current)
521
+ end
522
+ end
523
+
524
+ def log_done(current)
525
+ current[:logged] = true
526
+ Log.public_send(current[:level], :http, current[:stream] ? "stream" : "fetch", **log_base(current),
527
+ status: current[:status], ttft_ms: ttft_ms(current),
528
+ ms: elapsed_ms(current), attempts: retried(current))
529
+ end
530
+
531
+ def log_cancelled(current, reason)
532
+ current[:logged] = true
533
+ Log.public_send(current[:level], :http, "cancelled", **log_base(current), ms: elapsed_ms(current), reason: reason&.to_s)
534
+ end
535
+
536
+ def log_failed(current, e)
537
+ current[:logged] = true
446
538
  failure_level = current[:level] == :info ? :error : :debug
447
539
  event = case e
448
540
  when FirstTokenTimeout then "first_token_timeout"
@@ -454,7 +546,6 @@ module Samagotchi
454
546
  ms: elapsed_ms(current), attempts: current[:attempts], error: e.class.name,
455
547
  idle_s: e.is_a?(StreamStalled) ? e.limit : nil,
456
548
  msg: log_message(e.respond_to?(:summary) ? e.summary : e.message))
457
- raise
458
549
  end
459
550
 
460
551
  def elapsed_ms(current, at = monotonic_now)
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "cli/command"
4
+ require_relative "cli/exit"
5
+ require_relative "mcp_server/protocol"
6
+ require_relative "mcp_server/stdio"
7
+
8
+ module Samagotchi
9
+ # `chi mcp serve`: chi as an MCP server on stdio, for an MCP host (Claude
10
+ # Code, Codex) to drive this machine's sessions as tools, or another
11
+ # machine's under `chi --remote NAME`. See docs/mcp-server.md. Nothing
12
+ # but the protocol goes to stdout; diagnostics go to stderr.
13
+ class McpCommand
14
+ include CLI::Command
15
+
16
+ SUBCOMMANDS = %w[serve].freeze
17
+
18
+ USAGE = <<~TEXT
19
+ Usage: chi mcp serve
20
+ chi as an MCP server on stdio (JSON-RPC lines): an MCP host drives
21
+ this machine's chi sessions with four tools (chi_sessions, chi_ask,
22
+ chi_wait, chi_answer); under chi --remote NAME, that machine's.
23
+ claude mcp add chi -- chi mcp serve
24
+ codex: [mcp_servers.chi] command = "chi", args = ["mcp", "serve"]
25
+ chi web serves the same at POST /api/mcp. See docs/mcp-server.md.
26
+ TEXT
27
+
28
+ # One load of what the tools' calls autoload (SessionManager, and what
29
+ # a probe of their paths loaded on a first call: SessionContinue,
30
+ # SessionInbox's delivery; about 6 ms) before the first call's thread:
31
+ # two threads must not trigger them at once.
32
+ LOAD_LOCK = Mutex.new
33
+
34
+ # @param access [SessionAccess::Local, SessionAccess::Remote, nil]
35
+ # where the sessions are; default this machine's, in +state_dir+
36
+ def initialize(argv, access: nil, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil)
37
+ @argv = argv.dup
38
+ @access = access
39
+ @stdin = stdin
40
+ @stdout = stdout
41
+ @stderr = stderr
42
+ @state_dir = state_dir
43
+ end
44
+
45
+ # @return [Integer] the exit status
46
+ def run
47
+ first = @argv.first
48
+ if HELP_WORDS.include?(first) || (first == "serve" && @argv.drop(1).any? { |arg| HELP_WORDS.include?(arg) })
49
+ @stdout.puts(USAGE)
50
+ return 0
51
+ end
52
+ return usage_error(first ? "unknown subcommand #{first}" : "give a subcommand: serve") unless first == "serve"
53
+ return usage_error("serve takes no arguments") unless @argv.size == 1
54
+
55
+ serve
56
+ end
57
+
58
+ private
59
+
60
+ def command_name = "chi mcp"
61
+
62
+ def serve
63
+ log = ->(line) { @stderr.puts(line) }
64
+ tools = LazyTools.new { build_tools }
65
+ protocol = McpServer::Protocol.new(tools: tools, instructions: instructions)
66
+ McpServer::Stdio.new(protocol, input: @stdin, output: @stdout, before_call: -> { tools.load }, log: log).run
67
+ end
68
+
69
+ def instructions
70
+ require_relative "mcp_server/text"
71
+ McpServer::Text::INSTRUCTIONS
72
+ end
73
+
74
+ def build_tools
75
+ require_relative "mcp_server/tools"
76
+ access = @access || begin
77
+ require_relative "session_access/local"
78
+ SessionAccess::Local.new(state_dir: @state_dir)
79
+ end
80
+ load_for_calls unless access.remote?
81
+ McpServer::Tools.new(access)
82
+ end
83
+
84
+ def load_for_calls
85
+ LOAD_LOCK.synchronize do
86
+ Samagotchi.const_get(:SessionManager)
87
+ Samagotchi.const_get(:SessionContinue)
88
+ SessionInbox.const_get(:Dispatch)
89
+ end
90
+ end
91
+
92
+ # The tools, built on the first tools/list or tools/call, so answering
93
+ # server/discover or initialize loads no session code.
94
+ class LazyTools
95
+ def initialize(&build)
96
+ @build = build
97
+ @lock = Mutex.new
98
+ end
99
+
100
+ def load = @lock.synchronize { @tools ||= @build.call }
101
+
102
+ def list
103
+ require_relative "mcp_server/tools"
104
+ McpServer::Tools::DEFINITIONS
105
+ end
106
+
107
+ def call(name, arguments) = load.call(name, arguments)
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+ require_relative "protocol"
6
+
7
+ module Samagotchi
8
+ module McpServer
9
+ # MCP over HTTP, one POST at a time (chi web's POST /api/mcp): one
10
+ # JSON-RPC message in, a JSON answer out (no SSE: spike D2). The era is
11
+ # decided per POST (Protocol.era_of). A modern request's headers must
12
+ # match its body before anything runs (MCP-Protocol-Version = _meta's
13
+ # version, Mcp-Method = method, Mcp-Name = params.name on tools/call):
14
+ # 400 -32020 otherwise. A legacy initialize is handed a fresh
15
+ # Mcp-Session-Id, which every later legacy POST must carry (400
16
+ # "Missing session ID" without one, as the reference server answers);
17
+ # any well-formed one is served. A later legacy POST's
18
+ # MCP-Protocol-Version, when it has one, is a legacy version chi
19
+ # serves (2025-06-18 on: 400 -32600 otherwise; none is served, as the
20
+ # spec says for a client before the header). Nothing is stored for it: the tools
21
+ # hold no per-connection state, so an id only marks a legacy client
22
+ # that did initialize. The transport's gates (Host, Origin, the token)
23
+ # are the caller's.
24
+ class Http
25
+ JSON_HEADERS = { "Content-Type" => "application/json", "Cache-Control" => "no-store" }.freeze
26
+ SESSION_HEADER = "Mcp-Session-Id"
27
+ SESSION_ID = /\A[\x21-\x7e]{1,128}\z/
28
+ ENCODED = /\A=\?base64\?(.*)\?=\z/m
29
+
30
+ # @param protocol [Protocol]
31
+ def initialize(protocol)
32
+ @protocol = protocol
33
+ end
34
+
35
+ # @param env [Hash] the Rack env (its HTTP_MCP_* headers)
36
+ # @param body [String] the request's body as read
37
+ # @return [Array(Integer, Hash, Array<String>)]
38
+ def call(env, body)
39
+ message = Protocol.parse(body)
40
+ rescue Protocol::Unparseable => e
41
+ respond(400, Protocol.parse_error_body(body, e))
42
+ else
43
+ era = Protocol.era_of(message)
44
+ refused = era == :modern ? header_refusal(env, message) : session_refusal(env, message)
45
+ return respond(400, refused) if refused
46
+
47
+ answer = @protocol.handle(message, era: era)
48
+ return [202, {}, []] unless answer
49
+
50
+ headers = {}
51
+ # A body that isn't an object (a batch, null) is -32600 already.
52
+ if era == :legacy && message.is_a?(Hash) && message["method"] == "initialize" && answer.body.key?(:result)
53
+ headers[SESSION_HEADER] = SecureRandom.uuid
54
+ end
55
+ respond(answer.status, answer.body, headers)
56
+ end
57
+
58
+ private
59
+
60
+ def header_refusal(env, message)
61
+ params = message["params"].is_a?(Hash) ? message["params"] : {}
62
+ id = Protocol.request_id(message)
63
+ version = env["HTTP_MCP_PROTOCOL_VERSION"]
64
+ meta_version = params.dig("_meta", VERSION_META)
65
+ unless version == meta_version
66
+ return mismatch(id, version.nil? ? "MCP-Protocol-Version header is missing" : "MCP-Protocol-Version header " \
67
+ "#{version} does not match _meta's #{meta_version}")
68
+ end
69
+ method = env["HTTP_MCP_METHOD"]
70
+ return mismatch(id, "Mcp-Method header is required on the modern path") if method.nil?
71
+ return mismatch(id, "Mcp-Method header value '#{method}' does not match body value '#{message["method"]}'") unless method == message["method"]
72
+ return nil unless message["method"] == "tools/call"
73
+
74
+ name = decoded(env["HTTP_MCP_NAME"])
75
+ return mismatch(id, "Mcp-Name header is required on tools/call") if name.nil?
76
+
77
+ name == params["name"] ? nil : mismatch(id, "Mcp-Name header value '#{name}' does not match body value '#{params["name"]}'")
78
+ end
79
+
80
+ def mismatch(id, words) = Protocol.error_body(id, Protocol::HEADER_MISMATCH, "Header mismatch: #{words}")
81
+
82
+ # A legacy request past initialize carries its session id, and a
83
+ # version chi serves if it names one.
84
+ def session_refusal(env, message)
85
+ return nil if !message.is_a?(Hash) || message["method"] == "initialize"
86
+
87
+ session = env["HTTP_MCP_SESSION_ID"]
88
+ unless session.is_a?(String) && SESSION_ID.match?(session)
89
+ return Protocol.error_body(Protocol.request_id(message), Protocol::INVALID_REQUEST, "Bad Request: Missing session ID")
90
+ end
91
+
92
+ version = env["HTTP_MCP_PROTOCOL_VERSION"]
93
+ return nil if version.nil? || LEGACY_VERSIONS.include?(version)
94
+
95
+ Protocol.error_body(Protocol.request_id(message), Protocol::INVALID_REQUEST,
96
+ "Bad Request: Unsupported protocol version #{version} (supported: #{LEGACY_VERSIONS.join(", ")})")
97
+ end
98
+
99
+ # A header in the =?base64?…?= form decoded (a name that isn't ASCII).
100
+ def decoded(value)
101
+ return value unless value&.match?(ENCODED)
102
+
103
+ Protocol.utf8(value[ENCODED, 1].unpack1("m"))
104
+ end
105
+
106
+ def respond(status, body, headers = {})
107
+ text = Protocol.dump(body)
108
+ [status, JSON_HEADERS.merge("Content-Length" => text.bytesize.to_s, **headers), [text]]
109
+ end
110
+ end
111
+ end
112
+ end