mistri 0.7.0 → 0.8.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 (113) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +321 -2
  3. data/CONTRIBUTING.md +17 -3
  4. data/NOTICE +11 -0
  5. data/README.md +145 -284
  6. data/UPGRADING.md +810 -0
  7. data/assets/vendors/README.md +12 -0
  8. data/assets/vendors/claude-mark.svg +3 -0
  9. data/assets/vendors/gemini-mark.svg +10 -0
  10. data/assets/vendors/openai-mark-dark.svg +1 -0
  11. data/assets/vendors/openai-mark.svg +1 -0
  12. data/docs/README.md +2 -1
  13. data/docs/context-and-workspaces.md +84 -13
  14. data/docs/logging.md +90 -0
  15. data/docs/mcp.md +762 -21
  16. data/docs/reliability.md +210 -24
  17. data/docs/sessions.md +415 -36
  18. data/docs/sub-agents.md +85 -7
  19. data/docs/tool-contracts.md +528 -13
  20. data/examples/approval.rb +7 -7
  21. data/examples/browser.rb +1 -1
  22. data/examples/page_editor.rb +2 -2
  23. data/examples/quickstart.rb +1 -1
  24. data/lib/generators/mistri/install/templates/migration.rb.tt +4 -2
  25. data/lib/generators/mistri/mcp/mcp_generator.rb +2 -2
  26. data/lib/generators/mistri/mcp/templates/model.rb.tt +21 -8
  27. data/lib/mistri/agent.rb +815 -180
  28. data/lib/mistri/call_order.rb +137 -0
  29. data/lib/mistri/child.rb +69 -13
  30. data/lib/mistri/compaction.rb +200 -35
  31. data/lib/mistri/compactor/text.rb +91 -0
  32. data/lib/mistri/compactor.rb +474 -117
  33. data/lib/mistri/console.rb +44 -11
  34. data/lib/mistri/content.rb +70 -3
  35. data/lib/mistri/definition.rb +2 -2
  36. data/lib/mistri/edit.rb +13 -7
  37. data/lib/mistri/errors.rb +37 -0
  38. data/lib/mistri/event.rb +20 -9
  39. data/lib/mistri/locks/rails_cache.rb +16 -2
  40. data/lib/mistri/locks.rb +12 -3
  41. data/lib/mistri/mcp/client.rb +247 -61
  42. data/lib/mistri/mcp/conversation.rb +161 -0
  43. data/lib/mistri/mcp/egress.rb +5 -4
  44. data/lib/mistri/mcp/mirror.rb +90 -0
  45. data/lib/mistri/mcp/negotiation.rb +222 -0
  46. data/lib/mistri/mcp/oauth/client_identity.rb +53 -0
  47. data/lib/mistri/mcp/oauth/tolerance.rb +61 -0
  48. data/lib/mistri/mcp/oauth.rb +303 -82
  49. data/lib/mistri/mcp/results.rb +97 -0
  50. data/lib/mistri/mcp/sdk_client.rb +47 -0
  51. data/lib/mistri/mcp/wires.rb +325 -52
  52. data/lib/mistri/mcp.rb +304 -55
  53. data/lib/mistri/memory.rb +1 -1
  54. data/lib/mistri/message.rb +45 -8
  55. data/lib/mistri/models.rb +146 -24
  56. data/lib/mistri/partial_json.rb +5 -5
  57. data/lib/mistri/providers/anthropic/assembler.rb +40 -3
  58. data/lib/mistri/providers/anthropic/serializer.rb +154 -22
  59. data/lib/mistri/providers/anthropic.rb +77 -12
  60. data/lib/mistri/providers/fake.rb +4 -1
  61. data/lib/mistri/providers/gemini/assembler.rb +63 -3
  62. data/lib/mistri/providers/gemini/serializer.rb +27 -16
  63. data/lib/mistri/providers/gemini.rb +56 -11
  64. data/lib/mistri/providers/openai/assembler.rb +36 -5
  65. data/lib/mistri/providers/openai/serializer.rb +76 -22
  66. data/lib/mistri/providers/openai.rb +91 -14
  67. data/lib/mistri/reminder.rb +35 -3
  68. data/lib/mistri/result.rb +6 -4
  69. data/lib/mistri/result_limit.rb +164 -0
  70. data/lib/mistri/sandbox/quickjs.rb +345 -0
  71. data/lib/mistri/sandbox.rb +18 -0
  72. data/lib/mistri/schema.rb +26 -2
  73. data/lib/mistri/scratchpad.rb +107 -0
  74. data/lib/mistri/session/log.rb +137 -0
  75. data/lib/mistri/session.rb +405 -75
  76. data/lib/mistri/sinks/logger.rb +17 -11
  77. data/lib/mistri/skills.rb +10 -4
  78. data/lib/mistri/spawner.rb +43 -12
  79. data/lib/mistri/sse.rb +3 -2
  80. data/lib/mistri/stores/active_record.rb +30 -6
  81. data/lib/mistri/stores/jsonl.rb +26 -7
  82. data/lib/mistri/stores/memory.rb +6 -2
  83. data/lib/mistri/sub_agent/execution.rb +10 -2
  84. data/lib/mistri/sub_agent/runtime.rb +11 -1
  85. data/lib/mistri/sub_agent.rb +13 -4
  86. data/lib/mistri/tool.rb +71 -7
  87. data/lib/mistri/tool_arguments.rb +10 -11
  88. data/lib/mistri/tool_context.rb +15 -3
  89. data/lib/mistri/tool_executor.rb +49 -26
  90. data/lib/mistri/tool_result.rb +8 -2
  91. data/lib/mistri/tool_search/index.rb +193 -0
  92. data/lib/mistri/tool_search.rb +200 -0
  93. data/lib/mistri/tools/delete_file.rb +22 -0
  94. data/lib/mistri/tools/edit_file.rb +24 -14
  95. data/lib/mistri/tools/find_in_file.rb +1 -0
  96. data/lib/mistri/tools/grep.rb +212 -0
  97. data/lib/mistri/tools/list_files.rb +38 -5
  98. data/lib/mistri/tools/read_file.rb +83 -21
  99. data/lib/mistri/tools/read_memory.rb +2 -1
  100. data/lib/mistri/tools/run_code.rb +167 -0
  101. data/lib/mistri/tools/write_file.rb +66 -9
  102. data/lib/mistri/tools.rb +72 -1
  103. data/lib/mistri/transport/streamable_http.rb +140 -0
  104. data/lib/mistri/transport.rb +53 -63
  105. data/lib/mistri/usage.rb +33 -4
  106. data/lib/mistri/version.rb +1 -1
  107. data/lib/mistri/workspace/active_record.rb +22 -10
  108. data/lib/mistri/workspace/directory.rb +5 -1
  109. data/lib/mistri/workspace/memory.rb +4 -0
  110. data/lib/mistri/workspace/path_space.rb +56 -0
  111. data/lib/mistri/workspace/single.rb +6 -1
  112. data/lib/mistri.rb +10 -4
  113. metadata +29 -2
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ # What the result of an MCP call becomes for a model. Part of the bridge.
5
+ module MCP
6
+ module_function
7
+
8
+ # An MCP result becomes model-readable content: text joins, images ride
9
+ # as image blocks, and isError remains structured failure data end to end.
10
+ # A link to a resource and bytes that are neither an image nor text are
11
+ # named and nothing more: a bridged tool does more with them.
12
+ def answer(result) = shown(result, nil, nil)
13
+
14
+ # reader is the name of the tool that reads this server's resources, and
15
+ # save a callable that keeps bytes and returns where. With them a link
16
+ # names that tool, and bytes a model cannot read are kept for it.
17
+ def shown(result, reader, save)
18
+ blocks = Array(result["content"]).map { |block| convert(block, reader, save) }
19
+ if result["isError"]
20
+ text_blocks = blocks.grep(String)
21
+ if result["structuredContent"]
22
+ structured = JSON.generate(result["structuredContent"])
23
+ text_blocks << structured unless text_blocks.include?(structured)
24
+ end
25
+ text = text_blocks.join("\n")
26
+ content = "MCP tool error: #{text.empty? ? "unknown error" : text}"
27
+ non_text = blocks.grep_v(String)
28
+ content = [content, *non_text] unless non_text.empty?
29
+ return ToolResult.new(content:, error: true)
30
+ end
31
+ if blocks.empty? && result["structuredContent"]
32
+ return JSON.generate(result["structuredContent"])
33
+ end
34
+ return blocks.join("\n") if blocks.all?(String)
35
+
36
+ blocks
37
+ end
38
+ private_class_method :shown
39
+
40
+ def convert(block, reader = nil, save = nil)
41
+ case block["type"]
42
+ when "text" then block["text"].to_s
43
+ when "image"
44
+ Content::Image.new(data: block["data"], mime_type: block["mimeType"] || "image/png")
45
+ when "resource" then embedded(block["resource"] || {}, save)
46
+ when "resource_link" then link(block, reader)
47
+ else "[unsupported #{block["type"]} content]"
48
+ end
49
+ end
50
+
51
+ # A resource a server put into a result: its text, or its bytes. Bytes
52
+ # that are an image are shown, bytes of a text type are read as text, and
53
+ # any other bytes are kept where the agent can find them.
54
+ def embedded(resource, save)
55
+ return resource["text"] if resource["text"]
56
+
57
+ blob = resource["blob"]
58
+ return "[resource: #{resource["uri"]}]" unless blob.is_a?(String)
59
+
60
+ type = resource["mimeType"].to_s
61
+ return Content::Image.new(data: blob, mime_type: type) if type.start_with?("image/")
62
+
63
+ bytes = Content.strict_base64(blob).unpack1("m0")
64
+ text = bytes.dup.force_encoding(Encoding::UTF_8)
65
+ return text if TEXT_TYPE.match?(type) && text.valid_encoding?
66
+
67
+ kept(resource["uri"], type, bytes, save)
68
+ end
69
+ private_class_method :embedded
70
+
71
+ def kept(uri, type, bytes, save)
72
+ return "[resource: #{uri}]" unless save
73
+
74
+ about = "#{uri} (#{type.empty? ? "unknown type" : type}, #{bytes.bytesize} bytes)"
75
+ path = save.call(bytes, uri.to_s[/\.[A-Za-z0-9]{1,8}\z/] || ".bin")
76
+ return "[Binary resource #{about} saved at #{path}]" if path
77
+
78
+ "[Binary resource #{about} is not shown: the agent has no scratchpad to keep it in]"
79
+ rescue StandardError => e
80
+ "[Binary resource #{about} could not be saved: #{e.message}]"
81
+ end
82
+ private_class_method :kept
83
+
84
+ def link(block, reader)
85
+ return "[resource: #{block["uri"]}]" unless reader
86
+
87
+ label = [block["title"], block["name"]].grep(String).first
88
+ details = [block["mimeType"], (size = block["size"]) && "#{size} bytes"].compact.join(", ")
89
+ named = "Resource #{block["uri"]}"
90
+ named += " #{label.inspect}" if label
91
+ named += " (#{details})" unless details.empty?
92
+ about = block["description"].strip.delete_suffix(".") if block["description"].is_a?(String)
93
+ "[#{[named, about, "Read it with #{reader}"].compact.join(". ")}.]"
94
+ end
95
+ private_class_method :link
96
+ end
97
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ module MCP
5
+ # A client of the official MCP Ruby SDK, the mcp gem, in the shape the
6
+ # bridge takes. The host builds and connects the SDK's client, and closes
7
+ # it:
8
+ #
9
+ # sdk = ::MCP::Client.new(transport: transport)
10
+ # sdk.connect(client_info: { name: "YourApp", version: "1.0" })
11
+ # tools = Mistri::MCP.tools(Mistri::MCP::SDKClient.new(sdk), prefix: "files")
12
+ #
13
+ # Mistri does not depend on the SDK: nothing here names one of its
14
+ # constants, so the wrapped object only has to answer as its client does.
15
+ class SDKClient
16
+ def initialize(client)
17
+ @client = client
18
+ end
19
+
20
+ def tools
21
+ @client.tools.map do |tool|
22
+ { "name" => tool.name, "title" => tool.title, "description" => tool.description,
23
+ "inputSchema" => tool.input_schema, "annotations" => tool.annotations }.compact
24
+ end
25
+ end
26
+
27
+ # The SDK returns the whole JSON-RPC response, and raises for an error
28
+ # the server answered with.
29
+ def call_tool(name, arguments = {})
30
+ response = @client.call_tool(name: name, arguments: arguments)
31
+ result = response["result"] if response.is_a?(Hash)
32
+ return result if result.is_a?(Hash)
33
+
34
+ raise Error, "tools/call returned a malformed result"
35
+ end
36
+
37
+ def instructions = @client.instructions
38
+
39
+ def resources?
40
+ declared = @client.server_capabilities
41
+ declared.is_a?(Hash) && declared.key?("resources")
42
+ end
43
+
44
+ def read_resource(uri) = @client.read_resource(uri: uri)
45
+ end
46
+ end
47
+ end
@@ -10,6 +10,12 @@ module Mistri
10
10
  # payload's own response arrives, and knows nothing about MCP semantics;
11
11
  # the Client owns those.
12
12
  module Wires
13
+ TIMED_OUT = "timed out waiting for the MCP server"
14
+ # The first revision with no handshake and no session: each request
15
+ # carries its own version.
16
+ STATELESS_SINCE = "2026-07-28"
17
+ private_constant :TIMED_OUT, :STATELESS_SINCE
18
+
13
19
  # Streamable HTTP: requests POST to one endpoint, responses arrive as
14
20
  # JSON or an SSE stream. Sessions and bearer auth live here.
15
21
  class Http
@@ -18,8 +24,39 @@ module Mistri
18
24
  RESERVED_HEADERS = %w[host content-length transfer-encoding connection keep-alive
19
25
  proxy-authenticate proxy-authorization proxy-connection te trailer
20
26
  upgrade accept content-type accept-encoding mcp-session-id
21
- mcp-protocol-version].freeze
22
- private_constant :HEADER_NAME, :INVALID_HEADER_VALUE, :RESERVED_HEADERS
27
+ mcp-protocol-version last-event-id mcp-method mcp-name].freeze
28
+ # Seconds before a stream that ended early is asked for again, when
29
+ # the server named none.
30
+ RECONNECT_WAIT = 1
31
+ # Seconds a message said aside may take.
32
+ ASIDE_TIMEOUT = 5
33
+ private_constant :HEADER_NAME, :INVALID_HEADER_VALUE, :RESERVED_HEADERS, :RECONNECT_WAIT,
34
+ :ASIDE_TIMEOUT
35
+
36
+ # The decoder of one stream, which also keeps what a client needs to
37
+ # go back to it: the id of the last whole event, and the wait the
38
+ # server asked for.
39
+ class Events < SSE
40
+ attr_reader :last_event_id, :retry_after
41
+
42
+ private
43
+
44
+ # An id counts when its event ends, at the blank line.
45
+ def decode(line, &)
46
+ if line.empty?
47
+ @last_event_id = @event_id if @event_id
48
+ elsif line.start_with?("id:")
49
+ id = line.delete_prefix("id:").delete_prefix(" ")
50
+ @event_id = id unless id.match?(/[\0\r]/)
51
+ elsif line.start_with?("retry:")
52
+ wait = line.delete_prefix("retry:").strip
53
+ @retry_after = wait.to_i / 1000.0 if wait.match?(/\A\d+\z/)
54
+ else
55
+ super
56
+ end
57
+ end
58
+ end
59
+ private_constant :Events
23
60
 
24
61
  def initialize(url:, token:, headers:, open_timeout:, read_timeout:, allow_non_public:,
25
62
  max_record_bytes: DEFAULT_MAX_RECORD_BYTES)
@@ -27,9 +64,15 @@ module Mistri
27
64
  timeout: open_timeout)
28
65
  @path = uri.path.empty? ? "/" : uri.path
29
66
  @path = "#{@path}?#{uri.query}" if uri.query
30
- @transport = Transport.new(origin: Egress.origin(uri), address_resolver: resolver,
31
- open_timeout: open_timeout, read_timeout: read_timeout,
32
- max_record_bytes: max_record_bytes)
67
+ @dial = lambda do |open, read|
68
+ Transport.new(origin: Egress.origin(uri), address_resolver: resolver,
69
+ open_timeout: open, read_timeout: read,
70
+ max_record_bytes: max_record_bytes)
71
+ end
72
+ @transport = @dial.call(open_timeout, read_timeout)
73
+ @open_timeout = open_timeout
74
+ @read_timeout = read_timeout
75
+ @max_record_bytes = max_record_bytes
33
76
  @token = token
34
77
  @headers = normalized_headers(headers)
35
78
  @session_id = nil
@@ -38,32 +81,161 @@ module Mistri
38
81
 
39
82
  attr_writer :protocol_version
40
83
 
41
- def call(payload, replayable:, &)
42
- meta = @transport.post_either(@path, body: payload, headers: request_headers,
43
- replayable: replayable, &)
84
+ # Reads until the block returns what it took for the answer. mirror is
85
+ # the schema of the tool a call is for.
86
+ def call(payload, replayable:, mirror: nil, **)
87
+ @reading = true
88
+ answered = false
89
+ took = ->(record) { answered = yield(record) || answered }
90
+ events = Events.new(max_record_bytes: @max_record_bytes)
91
+ headers = unsent_headers
92
+ headers.merge!(repeated(payload, mirror)) if stateless?
93
+ meta = post(@transport, payload, headers, replayable: replayable, events: events, &took)
94
+ return if stateless?
95
+
44
96
  capture_session(meta)
97
+ resume(events, &took) unless answered
45
98
  nil
99
+ ensure
100
+ @reading = false
46
101
  end
47
102
 
103
+ # A reply to the server's own request leaves while the response of a
104
+ # call is read, on a second connection, because the first is taken.
48
105
  def notify(payload)
49
- discard = ->(_record) {}
50
- @transport.post_either(@path, body: payload, headers: request_headers, &discard)
106
+ post(@reading ? aside : @transport, payload) { |_record| nil }
107
+ nil
108
+ end
109
+
110
+ # A call that was given up is cancelled with a notification, on the
111
+ # second connection, which waits ASIDE_TIMEOUT at most. Since
112
+ # 2026-07-28 the closed stream of the call is the cancel.
113
+ def cancel(payload)
114
+ post(aside, payload) { |_record| nil } unless stateless?
51
115
  nil
52
116
  end
53
117
 
118
+ def open? = true
119
+
120
+ # A remote server is not this client's to end.
121
+ def restartable? = false
122
+
123
+ # Since 2026-07-28 a client repeats parts of a request in its headers.
124
+ def mirrors? = stateless?
125
+
126
+ # An HTTP server that takes long to answer is slow, not old.
127
+ def probe_wait = nil
128
+
54
129
  def session? = !@session_id.nil?
55
130
 
56
131
  def refreshable? = @token.respond_to?(:call)
57
132
 
133
+ # The server refused the token last sent. A callable that takes
134
+ # refused: is given it the next time it is asked, so it can tell a
135
+ # token it should replace from one another request already replaced.
136
+ def token_refused
137
+ @refused = @authorization&.delete_prefix("Bearer ")
138
+ end
139
+
58
140
  def reset_session
59
141
  @session_id = nil
60
142
  @protocol_version = nil
61
143
  end
62
144
 
63
- def close = @transport.close
145
+ # The spec asks a client that is done with a session to say so. The
146
+ # server may refuse, and the session ends for this client either way.
147
+ # The token is the one last sent: a close does not wait for a refresh.
148
+ def end_session
149
+ aside.delete(@path, headers: request_headers(fresh: false)) if @session_id
150
+ rescue Mistri::Error
151
+ nil
152
+ ensure
153
+ reset_session
154
+ end
155
+
156
+ def close
157
+ @aside&.close
158
+ @transport.close
159
+ end
64
160
 
65
161
  private
66
162
 
163
+ # The headers of a request, resolved before anything of it is written,
164
+ # so what the host's token callable raises here is tagged NotSent.
165
+ def unsent_headers
166
+ request_headers
167
+ rescue StandardError => e
168
+ raise e.clone(freeze: false).extend(NotSent)
169
+ end
170
+
171
+ # A reply, a notice and a cancel go out with the token last sent, so no
172
+ # code of the host runs for them. A server that was too slow is kept,
173
+ # as a slow stdio server is. A refusal keeps its class, status and
174
+ # body, and its message names an MCP server, not a provider.
175
+ def post(transport, payload, headers = nil, **, &)
176
+ headers ||= request_headers(fresh: false)
177
+ begin
178
+ transport.post_either(@path, body: payload, headers: headers, **, &)
179
+ rescue ProviderError => e
180
+ raise WireTimeout, TIMED_OUT if slow?(e)
181
+ raise unless e.status
182
+
183
+ raise e.exception(refusal(e))
184
+ end
185
+ end
186
+
187
+ # A server may end the stream of a call before the answer and expect
188
+ # the client back for it: once, after the wait the server named, from
189
+ # the last event it sent. A failure here leaves the call unanswered,
190
+ # and never sends the call again.
191
+ def resume(events, &)
192
+ wait = events.retry_after || RECONNECT_WAIT
193
+ return if events.last_event_id.nil? || (@read_timeout && wait > @read_timeout)
194
+
195
+ sleep(wait)
196
+ headers = request_headers.merge("Last-Event-ID" => events.last_event_id)
197
+ @transport.get_either(@path, headers: headers,
198
+ events: Events.new(max_record_bytes: @max_record_bytes), &)
199
+ nil
200
+ rescue ProviderError => e
201
+ raise WireTimeout, TIMED_OUT if slow?(e)
202
+
203
+ nil
204
+ end
205
+
206
+ def stateless? = @protocol_version.to_s >= STATELESS_SINCE
207
+
208
+ # The method of a request, the name it is for, and each parameter the
209
+ # tool's schema marks.
210
+ def repeated(payload, mirror)
211
+ params = payload[:params] || {}
212
+ name = params[:name] || params[:uri]
213
+ headers = { "Mcp-Method" => payload[:method].to_s }
214
+ headers["Mcp-Name"] = Mirror.value(name.to_s) if name
215
+ headers.merge!(Mirror.headers(mirror, params[:arguments])) if mirror
216
+ headers
217
+ end
218
+
219
+ def aside
220
+ @aside ||= @dial.call([@open_timeout, ASIDE_TIMEOUT].compact.min, ASIDE_TIMEOUT)
221
+ end
222
+
223
+ def slow?(error)
224
+ error.cause.is_a?(Timeout::Error) && !error.cause.is_a?(Net::OpenTimeout)
225
+ end
226
+
227
+ def refusal(error)
228
+ return "the MCP server did not authorize the request" if error.is_a?(AuthenticationError)
229
+
230
+ said = begin
231
+ JSON.parse(error.body.to_s).dig("error", "message")
232
+ rescue JSON::ParserError, TypeError, NoMethodError
233
+ nil
234
+ end
235
+ detail = ": #{said[0, 200]}" if said.is_a?(String) && !said.empty?
236
+ "the MCP server answered HTTP #{error.status}#{detail}"
237
+ end
238
+
67
239
  def normalized_headers(headers)
68
240
  headers.each_with_object({}) do |(key, value), copy|
69
241
  name = key.to_s
@@ -82,17 +254,29 @@ module Mistri
82
254
  end.freeze
83
255
  end
84
256
 
85
- def request_headers
257
+ def request_headers(fresh: true)
258
+ @authorization = "Bearer #{resolve_token}" if @token && fresh
86
259
  headers = { "Accept" => "application/json, text/event-stream" }
87
260
  headers.merge!(@headers)
88
- headers["Authorization"] = "Bearer #{resolve_token}" if @token
261
+ headers["Authorization"] = @authorization if @authorization
89
262
  headers["Mcp-Session-Id"] = @session_id if @session_id
90
263
  headers["MCP-Protocol-Version"] = @protocol_version if @protocol_version
91
264
  headers
92
265
  end
93
266
 
94
267
  def resolve_token
95
- @token.respond_to?(:call) ? @token.call : @token
268
+ return @token unless @token.respond_to?(:call)
269
+
270
+ refused = @refused
271
+ @refused = nil
272
+ refused && names_refused? ? @token.call(refused: refused) : @token.call
273
+ end
274
+
275
+ def names_refused?
276
+ callable = @token.respond_to?(:parameters) ? @token : @token.method(:call)
277
+ callable.parameters.any? do |kind, name|
278
+ kind == :keyrest || (%i[key keyreq].include?(kind) && name == :refused)
279
+ end
96
280
  end
97
281
 
98
282
  def capture_session(meta)
@@ -103,11 +287,33 @@ module Mistri
103
287
 
104
288
  # Stdio: a spawned child process, one JSON-RPC message per line, with
105
289
  # credentials in its environment, as the spec prescribes for local
106
- # servers. Its stderr stays attached for honest local debugging.
290
+ # servers. It is third-party code, so it starts from INHERITED_ENV and
291
+ # the client's env, not the host's environment. Its stderr stays attached
292
+ # for honest local debugging.
107
293
  class Stdio
108
294
  READ_SIZE = 16 * 1024
295
+ WRITE_SIZE = 64 * 1024
296
+ # Seconds a server gets to say which revisions it speaks. An older
297
+ # server may not answer a request it does not know at all.
298
+ PROBE_WAIT = 5
109
299
  BLANK_RECORD = /\A[[:space:]]*\z/
110
- private_constant :READ_SIZE, :BLANK_RECORD
300
+ # Seconds a server gets to end by itself once its input is closed, and
301
+ # then to end after SIGTERM.
302
+ EXIT_WAIT = 0.5
303
+ TERM_WAIT = 1
304
+ # What a runtime needs to start and behave: identity and programs,
305
+ # RubyGems paths, locale and temp files, CA bundles. A name that can
306
+ # carry a credential stays out, proxy settings included.
307
+ INHERITED_ENV = %w[
308
+ HOME USER LOGNAME SHELL PATH TERM
309
+ GEM_HOME GEM_PATH
310
+ LANG LC_ALL LC_CTYPE TZ TMPDIR
311
+ SSL_CERT_FILE SSL_CERT_DIR NODE_EXTRA_CA_CERTS REQUESTS_CA_BUNDLE CURL_CA_BUNDLE
312
+ ].freeze
313
+ private_constant :READ_SIZE, :WRITE_SIZE, :PROBE_WAIT, :BLANK_RECORD, :EXIT_WAIT,
314
+ :TERM_WAIT, :INHERITED_ENV
315
+
316
+ attr_reader :read_timeout
111
317
 
112
318
  def initialize(command:, env: {}, read_timeout: 120,
113
319
  max_record_bytes: DEFAULT_MAX_RECORD_BYTES)
@@ -120,31 +326,53 @@ module Mistri
120
326
  @read_timeout = read_timeout
121
327
  @max_record_bytes = max_record_bytes
122
328
  @pid = nil
329
+ @cut_write = false
123
330
  end
124
331
 
125
- def call(payload, **)
126
- spawn_server unless @pid
127
- write(payload)
128
- loop do
129
- record = read_record
130
- yield record
131
- break if record.is_a?(Hash) && record["id"] == payload[:id]
132
- end
332
+ # Reads until the block returns what it took for the answer. wait
333
+ # replaces the read timeout for this one request. whole makes that
334
+ # time the wait for the answer, where it is the wait for each message.
335
+ def call(payload, wait: nil, whole: false, **)
336
+ start
337
+ wait ||= @read_timeout
338
+ deadline = clock + wait if whole && wait
339
+ write(payload, wait)
340
+ # A message that was read before the deadline is still handed on.
341
+ loop { break if yield(read_record(deadline ? [deadline - clock, 0].max : wait)) }
133
342
  nil
134
343
  end
135
344
 
136
- def notify(payload)
137
- spawn_server unless @pid
138
- write(payload)
345
+ # wait is the seconds the server may take to read the message. A
346
+ # server is never started to be sent one.
347
+ def notify(payload, wait: @read_timeout)
348
+ write(payload, wait) if open?
139
349
  nil
140
350
  end
141
351
 
352
+ # A call that was given up is cancelled with a notification, which
353
+ # does not wait for a server that has stopped reading.
354
+ def cancel(payload) = notify(payload, wait: 0)
355
+
356
+ # False once the server this wire spoke to is gone or cannot be
357
+ # written to, so the client knows to do the handshake again. A close
358
+ # that was ended early leaves a server whose input is closed.
359
+ def open? = !@pid.nil? && !@cut_write && !@stdin.closed?
360
+
361
+ # This wire started the server, so it can end it and start another.
362
+ def restartable? = true
363
+
364
+ def mirrors? = false
365
+
366
+ def probe_wait = [@read_timeout, PROBE_WAIT].compact.min
367
+
142
368
  def session? = false
143
369
 
144
370
  def refreshable? = false
145
371
 
146
372
  def reset_session = nil
147
373
 
374
+ def end_session = nil
375
+
148
376
  def protocol_version=(_version); end
149
377
 
150
378
  def close
@@ -154,46 +382,77 @@ module Mistri
154
382
  @pid = nil
155
383
  end
156
384
  @read_buffer&.clear
385
+ @cut_write = false
157
386
  nil
158
387
  end
159
388
 
160
389
  private
161
390
 
391
+ # A write that was cut short left half a message in the server's input,
392
+ # and the next message would be read as its end.
393
+ def start
394
+ close if @pid && !open?
395
+ spawn_server unless @pid
396
+ end
397
+
162
398
  def spawn_server
163
399
  child_in, @stdin = IO.pipe
164
400
  @stdout, child_out = IO.pipe
165
- @pid = Process.spawn(@env, *@command, in: child_in, out: child_out)
401
+ env = ENV.slice(*INHERITED_ENV).merge(@env)
402
+ @pid = Process.spawn(env, *@command,
403
+ in: child_in, out: child_out, unsetenv_others: true)
166
404
  @read_buffer = +"".b
167
405
  @newline_search_offset = 0
168
406
  child_in.close
169
407
  child_out.close
170
408
  end
171
409
 
172
- def write(payload)
173
- @stdin.write("#{JSON.generate(payload)}\n")
174
- @stdin.flush
410
+ # Written without blocking, so a server that has stopped reading holds
411
+ # the caller only until the deadline.
412
+ def write(payload, wait)
413
+ line = "#{JSON.generate(payload)}\n".b
414
+ deadline = wait && (clock + wait)
415
+ sent = 0
416
+ while sent < line.bytesize
417
+ @cut_write = true
418
+ count = @stdin.write_nonblock(line.byteslice(sent, WRITE_SIZE), exception: false)
419
+ if count == :wait_writable
420
+ @cut_write = sent.positive?
421
+ raise WireTimeout, TIMED_OUT unless @stdin.wait_writable(remaining(deadline))
422
+ else
423
+ sent += count
424
+ end
425
+ end
426
+ @cut_write = false
175
427
  rescue Errno::EPIPE
176
428
  raise WireError, "the MCP server closed its input"
177
429
  end
178
430
 
179
- # The spec requires stdout to carry only protocol messages, so a
180
- # line that is not one is corruption worth failing loudly on.
181
- def read_record
182
- deadline = if @read_timeout
183
- Process.clock_gettime(Process::CLOCK_MONOTONIC) + @read_timeout
184
- end
431
+ # stdout carries one message a line. A line that is not JSON is
432
+ # skipped and written to standard error, where the server's own
433
+ # standard error goes, and the wait for the message goes on.
434
+ def read_record(wait = @read_timeout)
435
+ deadline = wait && (clock + wait)
436
+ loop do
437
+ line = next_line(deadline)
438
+ return JSON.parse(line)
439
+ rescue JSON::ParserError
440
+ text = line.byteslice(0, 200).force_encoding(Encoding::UTF_8).scrub.strip
441
+ warn("mistri: the MCP server wrote a line that is not JSON: #{text.inspect}")
442
+ end
443
+ end
444
+
445
+ def next_line(deadline)
185
446
  loop do
186
447
  line = complete_record
187
- return JSON.parse(line) if line
448
+ return line if line
188
449
 
189
450
  oversized_record! if @read_buffer.bytesize > @max_record_bytes
190
451
  chunk = read_chunk(deadline)
191
- return JSON.parse(eof_record) unless chunk
452
+ return eof_record unless chunk
192
453
 
193
454
  @read_buffer << chunk
194
455
  end
195
- rescue JSON::ParserError
196
- raise WireError, "the MCP server wrote non-protocol output on stdout"
197
456
  end
198
457
 
199
458
  def complete_record
@@ -209,13 +468,7 @@ module Mistri
209
468
 
210
469
  def read_chunk(deadline)
211
470
  loop do
212
- remaining = deadline && (deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC))
213
- if remaining && !remaining.positive?
214
- raise WireError, "timed out waiting for the MCP server"
215
- end
216
-
217
- ready = @stdout.wait_readable(remaining)
218
- raise WireError, "timed out waiting for the MCP server" unless ready
471
+ raise WireTimeout, TIMED_OUT unless @stdout.wait_readable(remaining(deadline))
219
472
 
220
473
  room = @max_record_bytes - @read_buffer.bytesize + 1
221
474
  chunk = @stdout.read_nonblock([READ_SIZE, room].min, exception: false)
@@ -223,6 +476,17 @@ module Mistri
223
476
  end
224
477
  end
225
478
 
479
+ def remaining(deadline)
480
+ return unless deadline
481
+
482
+ left = deadline - clock
483
+ raise WireTimeout, TIMED_OUT unless left.positive?
484
+
485
+ left
486
+ end
487
+
488
+ def clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
489
+
226
490
  def eof_record
227
491
  raise WireError, "the MCP server exited" if @read_buffer.empty?
228
492
 
@@ -239,17 +503,26 @@ module Mistri
239
503
  end
240
504
 
241
505
  def terminate
506
+ return if exited?(EXIT_WAIT)
507
+
242
508
  Process.kill("TERM", @pid)
243
- 20.times do
244
- return if Process.waitpid(@pid, Process::WNOHANG)
509
+ return if exited?(TERM_WAIT)
245
510
 
246
- sleep(0.05)
247
- end
248
511
  Process.kill("KILL", @pid)
249
512
  Process.waitpid(@pid)
250
513
  rescue Errno::ESRCH, Errno::ECHILD
251
514
  nil
252
515
  end
516
+
517
+ def exited?(seconds)
518
+ deadline = clock + seconds
519
+ until Process.waitpid(@pid, Process::WNOHANG)
520
+ return false if clock >= deadline
521
+
522
+ sleep(0.01)
523
+ end
524
+ true
525
+ end
253
526
  end
254
527
  end
255
528
  end