samagotchi 0.181.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -1
@@ -0,0 +1,260 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's first plugin part (manifest.yml plugin: parts:, loaded
4
+ # before http_client.rb and plugin.rb): the stdio JSON-RPC client and the
5
+ # error classes HttpClient's subclass. The constants it reads at run time
6
+ # (PROTOCOL_VERSION) are plugin.rb's.
7
+ require "json"
8
+ require "open3"
9
+ require "samagotchi/process_group"
10
+
11
+ class Plugin
12
+ # A JSON-RPC client for one MCP server over stdio: newline-delimited JSON
13
+ # on the process's stdin and stdout; stderr goes to the log.
14
+ class Client
15
+ # The request failed: an error answer, a timeout, or the server is gone.
16
+ class Error < StandardError; end
17
+ class Timeout < Error; end
18
+ class Cancelled < Error; end
19
+ # The server's process ended (or never started); an HTTP server that
20
+ # can't be reached.
21
+ class Dead < Error; end
22
+ # An HTTP server's answer isn't MCP's (a status, a content type).
23
+ class Unavailable < Error; end
24
+
25
+ POLL_SECONDS = 0.1
26
+ # How long close waits for the server after closing its stdin, after
27
+ # TERM, and after KILL.
28
+ STOP_GRACE_SECONDS = 1
29
+ # The server's watchdog (#start_watchdog), a shell in its process group
30
+ # whose stdin is a pipe only chi holds. A line on it (#close) lets it
31
+ # go; EOF means chi ended without closing the server (kill -9, a crash
32
+ # past Ruby), whose stdin then hit EOF too: a grace for the server to
33
+ # leave by itself, then TERM and KILL to the group, the way #close stops
34
+ # it. `kill 0` signals the shell's own group: while it runs, that group
35
+ # (and so its id) can't be anyone else's.
36
+ WATCHDOG = "trap '' TERM; read -r _ && exit 0; sleep #{STOP_GRACE_SECONDS}; " \
37
+ "kill -TERM 0; sleep #{STOP_GRACE_SECONDS}; kill -KILL 0".freeze
38
+
39
+ attr_reader :pid
40
+
41
+ # @param command [Array<String>]
42
+ # @param env [Hash] added to the environment
43
+ # @param cwd [String]
44
+ # @param log [#call] (event, fields) for stderr lines and protocol noise
45
+ # @param on_exit [#call, nil] called once, with the reason, when the
46
+ # process ends while the client is open
47
+ # @param on_notification [#call, nil] (method, params) for each
48
+ # notification from the server, on the reader thread: it must not
49
+ # wait for an answer there
50
+ def initialize(command, env: {}, cwd: Dir.pwd, log: ->(*) {}, on_exit: nil, on_notification: nil)
51
+ @log = log
52
+ @on_exit = on_exit
53
+ @on_notification = on_notification
54
+ @mutex = Mutex.new
55
+ @write_mutex = Mutex.new
56
+ @pending = {}
57
+ @next_id = 0
58
+ @dead = nil
59
+ @closing = false
60
+ @stdin, @stdout, @stderr, @wait = Open3.popen3(env.to_h { |k, v| [k.to_s, v&.to_s] }, *command,
61
+ chdir: cwd, pgroup: true)
62
+ @pid = @wait.pid
63
+ start_watchdog
64
+ @reader = Thread.new { read_loop }
65
+ @err_reader = Thread.new { stderr_loop }
66
+ rescue SystemCallError => e
67
+ raise Dead, "can't start #{command.first}: #{e.message.sub(/ - .*\z/m, "")}"
68
+ end
69
+
70
+ # @return [String, nil] why the server is gone, or nil while it runs
71
+ def dead = @mutex.synchronize { @dead }
72
+
73
+ # What /mcp's running line shows for it.
74
+ def label = "pid #{pid}"
75
+
76
+ # initialize, then notifications/initialized.
77
+ # @return [Hash] initialize's result
78
+ def handshake(timeout:, cancelled:)
79
+ result = request("initialize", { protocolVersion: PROTOCOL_VERSION, capabilities: {},
80
+ clientInfo: { name: "chi", version: Samagotchi::VERSION } },
81
+ timeout: timeout, cancelled: cancelled)
82
+ notify("notifications/initialized")
83
+ result
84
+ end
85
+
86
+ # Send a request and wait for its answer.
87
+ # @param cancelled [#call, nil] polled while waiting; true sends
88
+ # notifications/cancelled and raises Cancelled
89
+ # @return [Hash] the result
90
+ def request(method, params = nil, timeout:, cancelled: nil)
91
+ queue = Queue.new
92
+ id = @mutex.synchronize do
93
+ raise Dead, @dead if @dead
94
+
95
+ @next_id += 1
96
+ @pending[@next_id] = queue
97
+ @next_id
98
+ end
99
+ write({ jsonrpc: "2.0", id: id, method: method, params: params }.compact)
100
+ deadline = monotonic + timeout
101
+ loop do
102
+ left = deadline - monotonic
103
+ if left <= 0
104
+ cancel(id, "timed out")
105
+ raise Timeout, "#{method} timed out after #{format("%g", timeout)}s"
106
+ end
107
+ if cancelled&.call
108
+ cancel(id, "cancelled by the user")
109
+ raise Cancelled, "#{method} was cancelled"
110
+ end
111
+ message = queue.pop(timeout: [left, POLL_SECONDS].min)
112
+ next unless message
113
+ raise Dead, message[:dead] if message[:dead]
114
+ if (error = message["error"])
115
+ raise Error, "#{error["message"] || "error"} (#{error["code"]})"
116
+ end
117
+
118
+ return message["result"] || {}
119
+ end
120
+ ensure
121
+ @mutex.synchronize { @pending.delete(id) } if id
122
+ end
123
+
124
+ def notify(method, params = nil)
125
+ write({ jsonrpc: "2.0", method: method, params: params }.compact)
126
+ end
127
+
128
+ # End the process: stdin closed first (most servers leave then), then
129
+ # TERM and KILL to its process group (chi's ProcessGroup), a second's
130
+ # grace each. Then the watchdog is let go.
131
+ def close
132
+ @mutex.synchronize { @closing = true }
133
+ [@stdin].each { |io| io.close unless io.closed? }
134
+ unless @wait.join(STOP_GRACE_SECONDS)
135
+ Samagotchi::ProcessGroup.stop(@pid, grace: STOP_GRACE_SECONDS, poll: STOP_GRACE_SECONDS,
136
+ stopped: -> { !@wait.alive? }, wait: ->(seconds) { @wait.join(seconds) })
137
+ @wait.join(STOP_GRACE_SECONDS)
138
+ end
139
+ release_watchdog
140
+ [@stdout, @stderr].each { |io| io.close unless io.closed? }
141
+ [@reader, @err_reader].each { |t| t.join(1) }
142
+ nil
143
+ rescue IOError
144
+ nil
145
+ end
146
+
147
+ private
148
+
149
+ # A server outlives a chi killed without #close when it ignores its
150
+ # stdin's EOF (a Node server with another live handle does): the
151
+ # watchdog (WATCHDOG) stops its group then. One that can't start (the
152
+ # server already left its group) is logged and skipped.
153
+ def start_watchdog
154
+ reader, @watchdog_pipe = IO.pipe
155
+ watchdog = Process.spawn("/bin/sh", "-c", WATCHDOG, in: reader, out: File::NULL, err: File::NULL, pgroup: @pid)
156
+ @watchdog = Process.detach(watchdog)
157
+ rescue SystemCallError => e
158
+ @log.call("watchdog_failed", error: e.class.name)
159
+ @watchdog_pipe&.close
160
+ @watchdog_pipe = nil
161
+ ensure
162
+ reader&.close
163
+ end
164
+
165
+ # A line tells the watchdog chi stopped the server itself.
166
+ def release_watchdog
167
+ return unless @watchdog_pipe
168
+
169
+ begin
170
+ @watchdog_pipe.write("\n")
171
+ rescue IOError, SystemCallError # gone already: the group's KILL reached it
172
+ nil
173
+ end
174
+ @watchdog_pipe.close unless @watchdog_pipe.closed?
175
+ @watchdog&.join(STOP_GRACE_SECONDS)
176
+ end
177
+
178
+ def write(message)
179
+ line = JSON.generate(message)
180
+ @write_mutex.synchronize do
181
+ @stdin.write(line, "\n")
182
+ @stdin.flush
183
+ end
184
+ rescue IOError, SystemCallError => e
185
+ raise Dead, dead || "the server's stdin is closed (#{e.class})"
186
+ end
187
+
188
+ def cancel(id, reason)
189
+ notify("notifications/cancelled", { requestId: id, reason: reason })
190
+ rescue Dead
191
+ nil
192
+ end
193
+
194
+ def read_loop
195
+ @stdout.each_line do |line|
196
+ next if line.strip.empty?
197
+
198
+ message = begin
199
+ JSON.parse(line)
200
+ rescue JSON::ParserError
201
+ @log.call("bad_line", line: line[0, 200])
202
+ next
203
+ end
204
+ dispatch(message) if message.is_a?(Hash)
205
+ end
206
+ rescue IOError
207
+ nil
208
+ ensure
209
+ ended
210
+ end
211
+
212
+ def dispatch(message)
213
+ if message.key?("method")
214
+ # A request from the server (ping, roots/list, …): ping is answered,
215
+ # the rest aren't supported. A notification is logged and handed on.
216
+ unless message.key?("id")
217
+ @log.call("server_notification", method: message["method"])
218
+ return @on_notification&.call(message["method"], message["params"])
219
+ end
220
+
221
+ answer = if message["method"] == "ping"
222
+ { jsonrpc: "2.0", id: message["id"], result: {} }
223
+ else
224
+ { jsonrpc: "2.0", id: message["id"], error: { code: -32_601, message: "not supported by chi" } }
225
+ end
226
+ begin
227
+ write(answer)
228
+ rescue Dead
229
+ nil
230
+ end
231
+ else
232
+ queue = @mutex.synchronize { @pending[message["id"]] }
233
+ queue&.push(message)
234
+ end
235
+ end
236
+
237
+ def stderr_loop
238
+ @stderr.each_line { |line| @log.call("stderr", line: line.chomp[0, 500]) }
239
+ rescue IOError
240
+ nil
241
+ end
242
+
243
+ def ended
244
+ status = @wait.value
245
+ reason = if status.nil?
246
+ "the server exited"
247
+ else
248
+ "the server exited (#{status.exitstatus ? "status #{status.exitstatus}" : "signal #{status.termsig}"})"
249
+ end
250
+ waiting, closing = @mutex.synchronize do
251
+ @dead ||= reason
252
+ [@pending.values, @closing]
253
+ end
254
+ waiting.each { |queue| queue.push({ dead: reason }) }
255
+ @on_exit&.call(reason) unless closing
256
+ end
257
+
258
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
259
+ end
260
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's third plugin part (manifest.yml plugin: parts:, loaded
4
+ # before plugin.rb): a tools/call answer as the model reads it, its text and
5
+ # the images it attaches (image blocks, and an image file a stdio server
6
+ # names in its text). Plugin#call is its one caller.
7
+ require "json"
8
+ require "tmpdir"
9
+
10
+ class Plugin
11
+ IMAGE_EXT = { "image/png" => "png", "image/jpeg" => "jpg", "image/gif" => "gif", "image/webp" => "webp" }.freeze
12
+
13
+ private
14
+
15
+ # The answer's text, and the images to attach: its image blocks, and a
16
+ # text block that is only an image's path (#image_path).
17
+ # @return [Array(String, Array<Hash>)]
18
+ def content(result, server, tool)
19
+ blocks = Array(result["content"])
20
+ return [JSON.generate(result["structuredContent"]), []] if blocks.empty? && result["structuredContent"]
21
+
22
+ images = []
23
+ text = blocks.map do |block|
24
+ case block["type"]
25
+ when "text"
26
+ line = block["text"].to_s
27
+ paths = image_paths(line, server).reject { |path| images.any? { |image| image[:path] == path } }
28
+ next line if paths.empty?
29
+
30
+ notes = paths.map do |path|
31
+ images << { path: path, name: File.basename(path) }
32
+ "[image #{images.size}: #{File.basename(path)}]"
33
+ end
34
+ [line, *notes].join("\n")
35
+ when "image"
36
+ mime = block["mimeType"] || "unknown type"
37
+ bytes = block["data"].to_s.unpack1("m")
38
+ next "[image: #{mime}, empty]" if bytes.empty?
39
+
40
+ images << { bytes: bytes, name: "#{tool}-#{images.size + 1}.#{IMAGE_EXT.fetch(mime, "img")}" }
41
+ "[image #{images.size}: #{mime}]"
42
+ when "audio" then "[audio: #{block["mimeType"] || "unknown type"}]"
43
+ when "resource"
44
+ resource = block["resource"] || {}
45
+ mime = resource["mimeType"].to_s
46
+ blob = resource["blob"].to_s
47
+ if mime.start_with?("image/") && !blob.empty?
48
+ bytes = blob.unpack1("m")
49
+ next "[image: #{mime}, empty]" if bytes.empty?
50
+
51
+ images << { bytes: bytes, name: "#{tool}-#{images.size + 1}.#{IMAGE_EXT.fetch(mime, "img")}" }
52
+ "[image #{images.size}: #{mime}]"
53
+ else
54
+ resource["text"] || "[resource: #{resource["uri"]}]"
55
+ end
56
+ when "resource_link" then "[resource link: #{block["uri"]}]"
57
+ else "[#{block["type"] || "unknown"} content]"
58
+ end
59
+ end.join("\n")
60
+ [text, images]
61
+ end
62
+
63
+ # An absolute path ending in an image extension, inside a sentence
64
+ # ("Saved screenshot to /tmp/shot.png."): no spaces, quotes or brackets.
65
+ IMAGE_PATH_IN_TEXT = %r{(?<![\w/.~-])/[^\s"'`<>()\[\]{},;]+?\.(?:png|jpe?g|gif|webp)(?![\w/-])}i
66
+
67
+ # The images +text+ names, when the server's attach_image_paths isn't
68
+ # off: the whole text when it is one absolute path (any name), else each
69
+ # absolute path in it that ends in an image extension. Each must be an
70
+ # image file (by its bytes) under the system temp dir or the server's
71
+ # cwd: a server's text can't pull in any image on disk.
72
+ # @return [Array<String>] real paths, each once
73
+ def image_paths(text, server)
74
+ # A remote server can't name a local file usefully, and must not make
75
+ # chi read one.
76
+ return [] if server.config["attach_image_paths"] == false || server.url
77
+
78
+ whole = text.strip
79
+ candidates = if whole.start_with?("/") && !whole.include?("\n") && File.file?(whole)
80
+ [whole]
81
+ else
82
+ text.scan(IMAGE_PATH_IN_TEXT)
83
+ end
84
+ candidates.filter_map { |path| image_path(path, server) }.uniq
85
+ end
86
+
87
+ # +path+'s real path when it is an image file under a root, else nil.
88
+ def image_path(path, server)
89
+ return nil unless File.file?(path)
90
+
91
+ real = File.realpath(path)
92
+ # degrade-ok: a root that is gone holds no image
93
+ roots = [Dir.tmpdir, server.cwd].compact.map { |dir| File.realpath(dir) rescue nil }.compact
94
+ return nil unless roots.any? { |root| real.start_with?(root.end_with?("/") ? root : "#{root}/") }
95
+
96
+ image_magic?(real) ? real : nil
97
+ rescue SystemCallError
98
+ nil
99
+ end
100
+
101
+ # png, jpeg, gif or webp by the file's first bytes.
102
+ def image_magic?(path)
103
+ head = File.binread(path, 12).to_s.b
104
+ head.start_with?("\x89PNG\r\n\x1a\n".b, "\xFF\xD8\xFF".b, "GIF87a", "GIF89a") ||
105
+ (head.start_with?("RIFF") && head[8, 4] == "WEBP")
106
+ end
107
+ end