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
@@ -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 = message["id"]
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(message["id"], 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(message["id"], 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