samagotchi 0.182.0 → 0.183.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
@@ -0,0 +1,244 @@
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
+ # @param tools [#list, #call]
134
+ # @param instructions [String, nil] what the server says it is
135
+ # @param name [String] serverInfo's name
136
+ def initialize(tools:, instructions: nil, name: "chi", version: Samagotchi::VERSION)
137
+ @tools = tools
138
+ @instructions = instructions
139
+ @server_info = { name: name, version: version }
140
+ end
141
+
142
+ # One line of JSON text: #handle on what it parses to, or -32700.
143
+ # @return [Answer, nil]
144
+ def handle_text(text, era: nil)
145
+ message = self.class.parse(text)
146
+ rescue Unparseable => e
147
+ Answer.new(status: STATUS[PARSE_ERROR], body: self.class.parse_error_body(text, e), era: era || :legacy)
148
+ else
149
+ handle(message, era: era)
150
+ end
151
+
152
+ # @param message [Object] one parsed JSON-RPC message
153
+ # @param era [Symbol, nil] the era a stdio connection was locked to
154
+ # by its first request; nil: this message's own (.era_of)
155
+ # @return [Answer, nil] nil for a notification (or a response)
156
+ def handle(message, era: nil)
157
+ era ||= self.class.era_of(message)
158
+ unless message.is_a?(Hash) && message["jsonrpc"] == "2.0"
159
+ return error(message.is_a?(Hash) ? message["id"] : nil, INVALID_REQUEST, "Invalid Request", era)
160
+ end
161
+ return nil unless message.key?("id") && message.key?("method")
162
+
163
+ id = message["id"]
164
+ method = message["method"]
165
+ params = message.fetch("params", {})
166
+ return error(id, INVALID_REQUEST, "Invalid Request", era) unless method.is_a?(String) && params.is_a?(Hash)
167
+ if params.key?("_meta") && !params["_meta"].is_a?(Hash)
168
+ return error(id, INVALID_REQUEST, "Invalid Request: params._meta is an object", era)
169
+ end
170
+
171
+ # A modern connection's initialize is -32601 whatever it names.
172
+ if era == :modern && method != "initialize" && (refused = version_refusal(id, params))
173
+ return refused
174
+ end
175
+
176
+ dispatch(id, method, params, era)
177
+ rescue StandardError => e
178
+ error(message.is_a?(Hash) ? message["id"] : nil, INTERNAL_ERROR, "Internal error: #{e.message}", era)
179
+ end
180
+
181
+ private
182
+
183
+ def dispatch(id, method, params, era)
184
+ case [method, era]
185
+ in ["server/discover", :modern] then result(id, discover, era)
186
+ in ["initialize", :legacy] then result(id, initialize_result(params), era)
187
+ in ["ping", :legacy] then result(id, {}, era)
188
+ in ["tools/list", _] then result(id, tools_list(era), era)
189
+ in ["tools/call", _] then call_tool(id, params, era)
190
+ else error(id, METHOD_NOT_FOUND, "Method not found: #{method}", era)
191
+ end
192
+ end
193
+
194
+ def version_refusal(id, params)
195
+ requested = params.dig("_meta", VERSION_META)
196
+ return nil if requested == MODERN_VERSION
197
+
198
+ error(id, UNSUPPORTED_VERSION, "Unsupported protocol version", :modern,
199
+ data: { supported: [MODERN_VERSION], requested: requested })
200
+ end
201
+
202
+ def discover
203
+ { supportedVersions: [MODERN_VERSION], capabilities: { tools: {} }, instructions: @instructions, ttlMs: 0,
204
+ cacheScope: "private" }.compact
205
+ end
206
+
207
+ def initialize_result(params)
208
+ asked = params["protocolVersion"]
209
+ version = LEGACY_VERSIONS.include?(asked) ? asked : LEGACY_VERSIONS.first
210
+ { protocolVersion: version, capabilities: { tools: {} }, serverInfo: @server_info,
211
+ instructions: @instructions }.compact
212
+ end
213
+
214
+ def tools_list(era)
215
+ listed = { tools: @tools.list }
216
+ era == :modern ? listed.merge(ttlMs: 0, cacheScope: "private") : listed
217
+ end
218
+
219
+ def call_tool(id, params, era)
220
+ name = params["name"]
221
+ arguments = params.fetch("arguments", nil) || {}
222
+ unless name.is_a?(String) && tool_names.include?(name)
223
+ return error(id, INVALID_PARAMS, "Unknown tool: #{name.inspect}", era)
224
+ end
225
+ return error(id, INVALID_PARAMS, "arguments is an object", era) unless arguments.is_a?(Hash)
226
+
227
+ result(id, @tools.call(name, arguments), era)
228
+ end
229
+
230
+ def tool_names = @tools.list.map { |tool| (tool[:name] || tool["name"]).to_s }
231
+
232
+ # The one place a result is stamped: a modern one carries resultType
233
+ # and the server's info in _meta.
234
+ def result(id, value, era)
235
+ value = value.merge(resultType: "complete", _meta: { SERVER_INFO_META => @server_info }) if era == :modern
236
+ Answer.new(status: 200, body: { jsonrpc: "2.0", id: id, result: value }, era: era)
237
+ end
238
+
239
+ def error(id, code, message, era, data: nil)
240
+ Answer.new(status: STATUS.fetch(code), body: self.class.error_body(id, code, message, data: data), era: era)
241
+ end
242
+ end
243
+ end
244
+ end
@@ -0,0 +1,92 @@
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
+
65
+ @era = Protocol.era_of(message)
66
+ @log&.call("mcp: #{@era} era (#{message["method"]})")
67
+ end
68
+
69
+ def prepare
70
+ return unless @before_call
71
+
72
+ @before_call.call
73
+ @before_call = nil
74
+ end
75
+
76
+ def write(answer)
77
+ return unless answer
78
+
79
+ @write_lock.synchronize do
80
+ return if @closed
81
+
82
+ @output.write("#{Protocol.dump(answer.body)}\n")
83
+ @output.flush
84
+ rescue Errno::EPIPE, IOError
85
+ # The host left: later answers go nowhere.
86
+ @closed = true
87
+ @log&.call("mcp: the host closed its end; answers dropped")
88
+ end
89
+ end
90
+ end
91
+ end
92
+ 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