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
@@ -0,0 +1,263 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../version"
5
+
6
+ module Samagotchi
7
+ # chi as an MCP server (docs/mcp-server.md): the protocol core
8
+ # (Protocol), the four tools (Tools, their words in Text) and the
9
+ # transports (Stdio for `chi mcp serve`, Http for chi web's POST
10
+ # /api/mcp). Not the `mcp` bundle, which is chi as an MCP client.
11
+ module McpServer
12
+ # The modern revision (stateless, `server/discover`, the version in
13
+ # each request's _meta).
14
+ MODERN_VERSION = "2026-07-28"
15
+ # The legacy revisions an `initialize` may name; the first is the
16
+ # answer to any other. Not 2025-03-26: it allows JSON-RPC batches,
17
+ # which chi doesn't answer (one -32600), and no host sends it (spike
18
+ # Q2: Codex initializes with 2025-06-18; Claude Code is modern).
19
+ LEGACY_VERSIONS = %w[2025-11-25 2025-06-18].freeze
20
+ # Where a modern request names its revision (params._meta).
21
+ VERSION_META = "io.modelcontextprotocol/protocolVersion"
22
+ SERVER_INFO_META = "io.modelcontextprotocol/serverInfo"
23
+
24
+ # JSON-RPC in, JSON-RPC out, in both eras; it knows no transport and no
25
+ # chi: +tools+ answers #list (the tools' definitions, each with
26
+ # "name"/:name) and #call(name, arguments) (a tools/call result: content,
27
+ # structuredContent, isError). A tool's refusal is its result's
28
+ # isError; only an unknown tool is a JSON-RPC error here (-32602).
29
+ class Protocol
30
+ # The answer to one message: +status+ the HTTP status a transport
31
+ # that has one answers it with (200, 400, 404, 500), +body+ the
32
+ # JSON-RPC response (a Hash), +era+ :modern or :legacy.
33
+ Answer = Data.define(:status, :body, :era)
34
+
35
+ # Text that isn't one JSON value in UTF-8 (.parse); the message says why.
36
+ class Unparseable < StandardError; end
37
+
38
+ PARSE_ERROR = -32_700
39
+ INVALID_REQUEST = -32_600
40
+ METHOD_NOT_FOUND = -32_601
41
+ INVALID_PARAMS = -32_602
42
+ INTERNAL_ERROR = -32_603
43
+ # A request's headers don't match its body (HTTP only: Http).
44
+ HEADER_MISMATCH = -32_020
45
+ UNSUPPORTED_VERSION = -32_022
46
+
47
+ STATUS = { PARSE_ERROR => 400, INVALID_REQUEST => 400, METHOD_NOT_FOUND => 404, INVALID_PARAMS => 200,
48
+ INTERNAL_ERROR => 500, HEADER_MISMATCH => 400, UNSUPPORTED_VERSION => 400 }.freeze
49
+
50
+ # The era a message is in: an `initialize` is legacy; a modern
51
+ # request names its revision in params._meta; anything else legacy.
52
+ # @return [Symbol] :modern or :legacy
53
+ def self.era_of(message)
54
+ return :legacy unless message.is_a?(Hash)
55
+ return :legacy if message["method"] == "initialize"
56
+
57
+ meta = message.dig("params", "_meta") if message["params"].is_a?(Hash)
58
+ meta.is_a?(Hash) && meta.key?(VERSION_META) ? :modern : :legacy
59
+ end
60
+
61
+ # One message's text parsed, whatever its encoding tag (a pipe's or
62
+ # a Rack body's bytes are read as UTF-8).
63
+ # @raise [Unparseable] invalid UTF-8, or not JSON
64
+ def self.parse(text)
65
+ text = text.to_s.dup.force_encoding(Encoding::UTF_8)
66
+ raise Unparseable, "invalid UTF-8" unless text.valid_encoding?
67
+
68
+ JSON.parse(text)
69
+ rescue JSON::ParserError, EncodingError => e
70
+ raise Unparseable, e.message
71
+ end
72
+
73
+ # A request's "id" in text that didn't parse (a lone surrogate
74
+ # escape, a stray byte), so the host can match the -32700 to its
75
+ # call instead of waiting to its own timeout: only when the text names
76
+ # exactly one "id" (one in the params too: nil, never a wrong match).
77
+ ID = /"id"\s*:\s*("(?:[^"\\\x00-\x1f]|\\["\\\/bfnrt]|\\u\h{4})*"|-?(?:0|[1-9]\d*))\s*[,}]/
78
+ def self.recovered_id(text)
79
+ found = text.to_s.dup.force_encoding(Encoding::UTF_8).scrub.scan(ID)
80
+ found.size == 1 ? JSON.parse(found.first.first) : nil
81
+ rescue JSON::ParserError
82
+ nil
83
+ end
84
+
85
+ # The -32700 answer for +text+ (.parse's +error+), with the id when
86
+ # .recovered_id reads one.
87
+ def self.parse_error_body(text, error)
88
+ error_body(recovered_id(text), PARSE_ERROR, "Parse error: #{error.message}")
89
+ end
90
+
91
+ # A response as JSON text, for a transport to write: one with a
92
+ # string that isn't UTF-8 (a worker's reply, a header echoed in a
93
+ # refusal) is written scrubbed, and one that can't be written at all
94
+ # is a -32603 for its id, so no call is left unanswered.
95
+ # @return [String]
96
+ def self.dump(body)
97
+ JSON.generate(body)
98
+ rescue JSON::GeneratorError, EncodingError
99
+ begin
100
+ JSON.generate(scrubbed(body))
101
+ rescue JSON::GeneratorError, EncodingError => e
102
+ id = body.is_a?(Hash) ? body[:id] || body["id"] : nil
103
+ JSON.generate(error_body(scrubbed(id), INTERNAL_ERROR, "Internal error: the answer could not be written (#{e.class})"))
104
+ end
105
+ end
106
+
107
+ # +value+ with every string as valid UTF-8 (U+FFFD for a bad byte).
108
+ def self.scrubbed(value)
109
+ case value
110
+ when Hash then value.to_h { |key, item| [scrubbed(key), scrubbed(item)] }
111
+ when Array then value.map { |item| scrubbed(item) }
112
+ when String then utf8(value)
113
+ else value
114
+ end
115
+ end
116
+
117
+ # +text+ as UTF-8, a bad byte replaced (a binary string read as UTF-8).
118
+ def self.utf8(text)
119
+ if [Encoding::UTF_8, Encoding::BINARY, Encoding::US_ASCII].include?(text.encoding)
120
+ text.dup.force_encoding(Encoding::UTF_8).scrub
121
+ else
122
+ text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
123
+ end
124
+ end
125
+
126
+ # A JSON-RPC error response (also a transport's own, Http's -32020).
127
+ def self.error_body(id, code, message, data: nil)
128
+ error = { code: code, message: message }
129
+ error[:data] = data if data
130
+ { jsonrpc: "2.0", id: id, error: error }
131
+ end
132
+
133
+ def self.valid_id?(message)
134
+ return false unless message.is_a?(Hash)
135
+ return true unless message.key?("id")
136
+
137
+ id = message["id"]
138
+ id.is_a?(String) || id.nil? || id.is_a?(Integer) || (id.is_a?(Float) && id.finite?)
139
+ end
140
+
141
+ def self.request_id(message)
142
+ valid_id?(message) && message.key?("id") ? message["id"] : nil
143
+ end
144
+
145
+ # @param tools [#list, #call]
146
+ # @param instructions [String, nil] what the server says it is
147
+ # @param name [String] serverInfo's name
148
+ def initialize(tools:, instructions: nil, name: "chi", version: Samagotchi::VERSION)
149
+ @tools = tools
150
+ @instructions = instructions
151
+ @server_info = { name: name, version: version }
152
+ end
153
+
154
+ # One line of JSON text: #handle on what it parses to, or -32700.
155
+ # @return [Answer, nil]
156
+ def handle_text(text, era: nil)
157
+ message = self.class.parse(text)
158
+ rescue Unparseable => e
159
+ Answer.new(status: STATUS[PARSE_ERROR], body: self.class.parse_error_body(text, e), era: era || :legacy)
160
+ else
161
+ handle(message, era: era)
162
+ end
163
+
164
+ # @param message [Object] one parsed JSON-RPC message
165
+ # @param era [Symbol, nil] the era a stdio connection was locked to
166
+ # by its first request; nil: this message's own (.era_of)
167
+ # @return [Answer, nil] nil for a notification (or a response)
168
+ def handle(message, era: nil)
169
+ era ||= self.class.era_of(message)
170
+ unless message.is_a?(Hash) && message["jsonrpc"] == "2.0"
171
+ return error(self.class.request_id(message), INVALID_REQUEST, "Invalid Request", era)
172
+ end
173
+ return nil if message.key?("result") || message.key?("error")
174
+ unless message.key?("method")
175
+ return error(self.class.request_id(message), INVALID_REQUEST, "Invalid Request", era)
176
+ end
177
+ return nil unless message.key?("id")
178
+
179
+ id = self.class.request_id(message)
180
+ method = message["method"]
181
+ params = message.fetch("params", {})
182
+ return error(id, INVALID_REQUEST, "Invalid Request", era) unless method.is_a?(String) && params.is_a?(Hash)
183
+ if params.key?("_meta") && !params["_meta"].is_a?(Hash)
184
+ return error(id, INVALID_REQUEST, "Invalid Request: params._meta is an object", era)
185
+ end
186
+ unless self.class.valid_id?(message)
187
+ return error(nil, INVALID_REQUEST, "Invalid Request: id is a string, a number or null", era)
188
+ end
189
+
190
+ # A modern connection's initialize is -32601 whatever it names.
191
+ if era == :modern && method != "initialize" && (refused = version_refusal(id, params))
192
+ return refused
193
+ end
194
+
195
+ dispatch(id, method, params, era)
196
+ rescue StandardError => e
197
+ error(self.class.request_id(message), INTERNAL_ERROR, "Internal error: #{e.message}", era)
198
+ end
199
+
200
+ private
201
+
202
+ def dispatch(id, method, params, era)
203
+ case [method, era]
204
+ in ["server/discover", :modern] then result(id, discover, era)
205
+ in ["initialize", :legacy] then result(id, initialize_result(params), era)
206
+ in ["ping", :legacy] then result(id, {}, era)
207
+ in ["tools/list", _] then result(id, tools_list(era), era)
208
+ in ["tools/call", _] then call_tool(id, params, era)
209
+ else error(id, METHOD_NOT_FOUND, "Method not found: #{method}", era)
210
+ end
211
+ end
212
+
213
+ def version_refusal(id, params)
214
+ requested = params.dig("_meta", VERSION_META)
215
+ return nil if requested == MODERN_VERSION
216
+
217
+ error(id, UNSUPPORTED_VERSION, "Unsupported protocol version", :modern,
218
+ data: { supported: [MODERN_VERSION], requested: requested })
219
+ end
220
+
221
+ def discover
222
+ { supportedVersions: [MODERN_VERSION], capabilities: { tools: {} }, instructions: @instructions, ttlMs: 0,
223
+ cacheScope: "private" }.compact
224
+ end
225
+
226
+ def initialize_result(params)
227
+ asked = params["protocolVersion"]
228
+ version = LEGACY_VERSIONS.include?(asked) ? asked : LEGACY_VERSIONS.first
229
+ { protocolVersion: version, capabilities: { tools: {} }, serverInfo: @server_info,
230
+ instructions: @instructions }.compact
231
+ end
232
+
233
+ def tools_list(era)
234
+ listed = { tools: @tools.list }
235
+ era == :modern ? listed.merge(ttlMs: 0, cacheScope: "private") : listed
236
+ end
237
+
238
+ def call_tool(id, params, era)
239
+ name = params["name"]
240
+ arguments = params.fetch("arguments", nil) || {}
241
+ unless name.is_a?(String) && tool_names.include?(name)
242
+ return error(id, INVALID_PARAMS, "Unknown tool: #{name.inspect}", era)
243
+ end
244
+ return error(id, INVALID_PARAMS, "arguments is an object", era) unless arguments.is_a?(Hash)
245
+
246
+ result(id, @tools.call(name, arguments), era)
247
+ end
248
+
249
+ def tool_names = @tools.list.map { |tool| (tool[:name] || tool["name"]).to_s }
250
+
251
+ # The one place a result is stamped: a modern one carries resultType
252
+ # and the server's info in _meta.
253
+ def result(id, value, era)
254
+ value = value.merge(resultType: "complete", _meta: { SERVER_INFO_META => @server_info }) if era == :modern
255
+ Answer.new(status: 200, body: { jsonrpc: "2.0", id: id, result: value }, era: era)
256
+ end
257
+
258
+ def error(id, code, message, era, data: nil)
259
+ Answer.new(status: STATUS.fetch(code), body: self.class.error_body(id, code, message, data: data), era: era)
260
+ end
261
+ end
262
+ end
263
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "protocol"
5
+
6
+ module Samagotchi
7
+ module McpServer
8
+ # MCP over stdio: one JSON-RPC message per line on +input+, each answer
9
+ # one line on +output+. The first request locks the connection's era
10
+ # (server/discover modern, initialize legacy), as the official SDK
11
+ # does. A tools/call runs on its own thread (a 25 s slice must not
12
+ # block a tools/list); every write goes through one mutex and is
13
+ # flushed. EOF on +input+: running calls finish (each bounded by its
14
+ # slice), then #run returns. Nothing else may write to +output+.
15
+ class Stdio
16
+ # @param protocol [Protocol]
17
+ # @param before_call [#call, nil] run once, before the first
18
+ # tools/call's thread starts (a load two threads must not race)
19
+ # @param log [#call, nil] (line) a diagnostic for stderr
20
+ def initialize(protocol, input: $stdin, output: $stdout, before_call: nil, log: nil)
21
+ @protocol = protocol
22
+ @input = input
23
+ @output = output
24
+ @before_call = before_call
25
+ @log = log
26
+ @write_lock = Mutex.new
27
+ @calls = []
28
+ @era = nil
29
+ @closed = false
30
+ end
31
+
32
+ # @return [Integer] 0
33
+ def run
34
+ @input.each_line do |line|
35
+ # Bytes: a line that isn't valid UTF-8 is a -32700, never a raise.
36
+ next if line.b.strip.empty?
37
+
38
+ dispatch(line)
39
+ end
40
+ @calls.each(&:join)
41
+ 0
42
+ end
43
+
44
+ private
45
+
46
+ def dispatch(line)
47
+ message = Protocol.parse(line)
48
+ rescue Protocol::Unparseable
49
+ write(@protocol.handle_text(line, era: @era))
50
+ else
51
+ lock_era(message)
52
+ if message.is_a?(Hash) && message["method"] == "tools/call" && message.key?("id")
53
+ prepare
54
+ # Finished calls let go of, so a long-lived host's don't pile up.
55
+ @calls.select!(&:alive?)
56
+ @calls << Thread.new { write(@protocol.handle(message, era: @era)) }
57
+ else
58
+ write(@protocol.handle(message, era: @era))
59
+ end
60
+ end
61
+
62
+ def lock_era(message)
63
+ return if @era || !message.is_a?(Hash) || !message.key?("id") || !message["method"].is_a?(String)
64
+ return unless Protocol.valid_id?(message)
65
+
66
+ @era = Protocol.era_of(message)
67
+ @log&.call("mcp: #{@era} era (#{message["method"]})")
68
+ end
69
+
70
+ def prepare
71
+ return unless @before_call
72
+
73
+ @before_call.call
74
+ @before_call = nil
75
+ end
76
+
77
+ def write(answer)
78
+ return unless answer
79
+
80
+ @write_lock.synchronize do
81
+ return if @closed
82
+
83
+ @output.write("#{Protocol.dump(answer.body)}\n")
84
+ @output.flush
85
+ rescue Errno::EPIPE, IOError
86
+ # The host left: later answers go nowhere.
87
+ @closed = true
88
+ @log&.call("mcp: the host closed its end; answers dropped")
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../parent_report"
4
+ require_relative "../session_access/ask"
5
+
6
+ module Samagotchi
7
+ module McpServer
8
+ # The tools' words: each outcome as a tools/call result, text the
9
+ # host's model can act on plus the same facts as structuredContent
10
+ # (docs/mcp-server.md, "What a result says"). A refusal or a turn that
11
+ # ended without a reply is isError with chi's own words.
12
+ module Text
13
+ INSTRUCTIONS = <<~TEXT.strip
14
+ chi (Samagotchi) is an agent harness; these tools drive its sessions on this machine (or on the chi web they reach).
15
+ chi_sessions lists them. chi_ask sends a message to a session as its own turn and waits for the answer.
16
+ A result that says "Still running" carries a token: call chi_wait with it until the answer comes.
17
+ A result that says a question waits: call chi_answer with session, question_id and option (or text).
18
+ TEXT
19
+
20
+ RUNNING = "Still running. Call chi_wait with this token to keep waiting."
21
+ ANSWER_HINT = "Call chi_answer with session, question_id and option (or text)."
22
+ # chi_ask's refusal of a shell line or a session command (an MCP
23
+ # tool is approved once: narrower than chi send).
24
+ COMMAND_REFUSED = "chi_ask takes a message for the model, not a command: run the command in the session's own UI"
25
+
26
+ module_function
27
+
28
+ # A host may hand its model the structuredContent alone (Claude Code
29
+ # 2.1.330 does when there is one), so it carries the words too:
30
+ # +text+, unless +words+ is false (the sessions' rows say it all).
31
+ # @return [Hash] a tools/call result
32
+ def result(text, structured, error: false, words: true)
33
+ structured = { **structured, text: text } if words && !structured.key?(:text) && !structured.key?(:detail)
34
+ { content: [{ type: "text", text: text }], structuredContent: structured, isError: error }
35
+ end
36
+
37
+ def error(text, **structured) = result(text, { status: "error", **structured, detail: text }, error: true)
38
+
39
+ # A wait's ReplyWait::Result for +session_id+.
40
+ # @param token [String, nil] the next wait's, for :timeout
41
+ # @param strategy [Guardrails::ParentPolicy::Strategy] what a parent
42
+ # may pick there (the backend's parent_strategy)
43
+ # @param extra [Hash] more structured keys (answered_here: false)
44
+ def wait_result(result, session_id:, token:, strategy:, extra: {})
45
+ base = { session_id: session_id, **extra }
46
+ case result.status
47
+ when :done
48
+ text = result.text.to_s
49
+ text = "(the turn ended with an empty reply)" if text.strip.empty?
50
+ result(text, { status: "done", **base, turn_id: result.turn_id }.compact)
51
+ when :timeout then result("#{RUNNING}\ntoken: #{token}", { status: "running", **base, token: token })
52
+ when :waiting_for_answer then question(result.question, session_id: session_id, strategy: strategy, extra: extra)
53
+ when :no_reply then error(no_reply(result, strategy), **base, outcome: result.outcome)
54
+ when :error then error("the worker failed: #{result.text}", **base)
55
+ when :worker_gone then error("the worker is gone; ask again to start a fresh one", **base)
56
+ when :stopped then error("the session was stopped", **base)
57
+ when :canceled then error("the wait was cut short (chi is stopping); call chi_wait again", **base, token: token)
58
+ else error("still running (#{result.status}); call chi_wait again", **base, token: token)
59
+ end
60
+ end
61
+
62
+ # chi_answer's +result+ (what came next) when the answer did not go
63
+ # in: question +qid+ was answered elsewhere first, or another one
64
+ # waits (AnswerCommand's words, first in the text).
65
+ def not_answered(result, qid)
66
+ line = "Question #{qid} is no longer open (answered elsewhere, or another one waits); not answered here. " \
67
+ "What came next:"
68
+ said = "#{line}\n#{result[:content].first[:text]}"
69
+ structured = result[:structuredContent]
70
+ key = structured.key?(:detail) ? :detail : :text
71
+ { **result, content: [{ type: "text", text: said }], structuredContent: { **structured, key => said } }
72
+ end
73
+
74
+ # A pending question (a PendingQuestion) as a host's model answers it.
75
+ def question(pending, session_id:, strategy:, extra: {})
76
+ q = ParentReport.question(pending, strategy: strategy)
77
+ allowed = q[:allowed_options] || q[:options]
78
+ lines = ["A question waits in session #{session_id} (#{q[:kind]}):"]
79
+ lines << q[:header] if q[:header]
80
+ lines << q[:text].strip
81
+ q[:options].each_with_index { |option, i| lines << " #{i + 1}. #{option}" }
82
+ lines << "A parent may pick: #{allowed.join(", ")} (the rest is your user's)." if allowed != q[:options]
83
+ lines << "Several options may be picked." if q[:multi_select]
84
+ lines << "Free text is taken too." if q[:allow_freeform]
85
+ lines << "question_id: #{q[:id]}"
86
+ lines << ANSWER_HINT
87
+ structured = { status: "waiting_for_answer", session_id: session_id, **extra,
88
+ question: { id: q[:id], kind: q[:kind], text: q[:text], options: q[:options],
89
+ multi_select: q[:multi_select] },
90
+ allowed: allowed }
91
+ result(lines.join("\n"), structured)
92
+ end
93
+
94
+ # How a turn that left no reply ended (ParentReport's words; a turn
95
+ # out of iterations points at chi_ask's /continue yes).
96
+ def no_reply(result, strategy)
97
+ line = ParentReport.no_reply_line(result, strategy: strategy)
98
+ return line unless result.outcome == "exhausted"
99
+
100
+ ran_out = "the turn ran out of iterations#{" (#{result.limit} steps)" if result.limit} before it answered"
101
+ if (strategy || Guardrails::ParentPolicy.current).allow?(Guardrails::ParentPolicy::SPEND)
102
+ "#{ran_out}; chi_ask with \"/continue yes\" continues it, a message drops it"
103
+ else
104
+ "#{ran_out}; continuing it is up to your user, a message drops it"
105
+ end
106
+ end
107
+
108
+ # An Ask::Refused in its own words.
109
+ def refused(refused)
110
+ base = { session_id: refused.session_id }.compact
111
+ case refused.kind
112
+ when :busy then busy(refused)
113
+ when :unknown then error(refused.message.to_s, **base, reason: "unknown")
114
+ when :undelivered then error(refused.result.refusal_text, **base, reason: "undelivered")
115
+ when :canceled then error("chi is stopping; ask again", **base, reason: "canceled")
116
+ else error(refused.message.to_s, **base, reason: refused.kind.to_s)
117
+ end
118
+ end
119
+
120
+ def busy(refused)
121
+ busy = refused.busy
122
+ if busy.error == "waiting" && busy.question
123
+ words = "a question waits for an answer first"
124
+ text = "#{words}:\n#{question(busy.question, session_id: refused.session_id, strategy: busy.strategy)[:content].first[:text]}"
125
+ return error(text, session_id: refused.session_id, reason: "waiting", question_id: busy.question.id.to_s)
126
+ end
127
+
128
+ error("a turn is running: wait for it, then ask again", session_id: refused.session_id, reason: busy.error)
129
+ end
130
+
131
+ # A line the worker ran as a session command: no reply comes.
132
+ def ran(session_id) = result("Done: the line ran as a session command; no reply comes.",
133
+ { status: "command", session_id: session_id })
134
+
135
+ # chi_sessions' rows (SessionRow).
136
+ def sessions(rows)
137
+ listed = rows.map do |row|
138
+ { id: row.id, title: row.title || row.desc, status: row.status, waiting: row.waiting, project: row.project,
139
+ updated_at: row.updated_at }
140
+ end
141
+ text = if listed.empty?
142
+ "No sessions."
143
+ else
144
+ listed.map do |row|
145
+ bits = [row[:id], row[:title].to_s, row[:status].to_s]
146
+ bits << "a #{row[:waiting]} waits" if row[:waiting]
147
+ bits << row[:project] if row[:project]
148
+ bits.join(" · ")
149
+ end.join("\n")
150
+ end
151
+ result(text, { sessions: listed }, words: false)
152
+ end
153
+ end
154
+ end
155
+ end