mistri 0.6.1 → 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 +355 -2
  3. data/CONTRIBUTING.md +17 -3
  4. data/NOTICE +11 -0
  5. data/README.md +145 -226
  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 +839 -141
  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 +407 -0
  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 +11 -3
  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 +28 -4
  113. metadata +30 -2
data/lib/mistri/mcp.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  require "json"
4
5
 
5
6
  module Mistri
@@ -10,24 +11,46 @@ module Mistri
10
11
  #
11
12
  # client = Mistri::MCP::Client.new(url: "https://mcp.linear.app/mcp",
12
13
  # token: -> { connection.fresh_token })
13
- # agent = Mistri.agent("claude-opus-4-8",
14
+ # agent = Mistri.agent("claude-opus-5-5",
14
15
  # tools: Mistri::MCP.tools(client, prefix: "linear"))
15
16
  #
16
- # The bridge is duck-typed: any client responding to tools (an array of
17
- # {"name", "description", "inputSchema"} hashes) and call_tool(name, args)
18
- # bridges the same way, so the official mcp gem's client plugs in too.
17
+ # The bridge takes any client that answers two methods: tools, an array of
18
+ # {"name", "description", "inputSchema"} hashes, and call_tool(name, args),
19
+ # the result of the call as a hash. instructions, and resources? with
20
+ # read_resource(uri), are used when a client has them. A host's own client
21
+ # bridges the same way, and the official mcp gem's client goes through
22
+ # Mistri::MCP::SDKClient.
19
23
  module MCP
20
24
  EMPTY_INPUT_SCHEMA = {
21
25
  "type" => "object", "properties" => {}.freeze, "additionalProperties" => false
22
26
  }.freeze
27
+ # What every catalogued provider takes for a tool name: letters, digits,
28
+ # underscores and hyphens, 64 at most, not starting with a digit or hyphen.
29
+ NAME_LIMIT = 64
30
+ SAFE_NAME = /\A[A-Za-z_][A-Za-z0-9_-]{0,63}\z/
31
+ # A server that keeps sending and never answers restarts the read timeout
32
+ # with every message, so one call is bounded in all.
33
+ CALL_TIMEOUT = 300
34
+ READ_RESOURCE = "read_resource"
35
+ READ_RESOURCE_SCHEMA = {
36
+ "type" => "object", "additionalProperties" => false, "required" => ["uri"],
37
+ "properties" => { "uri" => { "type" => "string",
38
+ "description" => "The resource's URI, as a result gave it." } }
39
+ }.freeze
40
+ # A type whose bytes are text a model can read.
41
+ TEXT_TYPE = %r{\A(?:text/|application/(?:json|xml|yaml)\b|[^;]*\+(?:json|xml)\b)}i
42
+ # Characters of a tool's description that reach the model. A description
43
+ # is text from the server that the model reads as guidance.
44
+ DESCRIPTION_LIMIT = 4_096
23
45
 
24
46
  # A protocol-level failure: a JSON-RPC error, a missing response, an
25
47
  # unsupported negotiation.
26
48
  class Error < Mistri::Error
27
- attr_reader :code
49
+ attr_reader :code, :data
28
50
 
29
- def initialize(message = nil, code: nil)
51
+ def initialize(message = nil, code: nil, data: nil)
30
52
  @code = code
53
+ @data = data
31
54
  super(message)
32
55
  end
33
56
  end
@@ -35,6 +58,10 @@ module Mistri
35
58
  # The stdio peer failed while a protocol message was in flight.
36
59
  class WireError < Error; end
37
60
 
61
+ # The server took longer than the read timeout to send a message or to
62
+ # take one. The server, or its session, is kept.
63
+ class WireTimeout < WireError; end
64
+
38
65
  # The server expired this client's session (a 404 with a session
39
66
  # attached); the spec says start a fresh one, and Client does.
40
67
  class SessionExpired < Error; end
@@ -42,26 +69,194 @@ module Mistri
42
69
  # A remote URL cannot be used without weakening the MCP network boundary.
43
70
  class UnsafeURLError < ConfigurationError; end
44
71
 
72
+ # Tags the copy of an error that Client#call_tool raises before it sends
73
+ # the call: no connection could be established, so the tool did not run.
74
+ module NotSent; end
75
+
45
76
  module_function
46
77
 
47
78
  # The server's tools as Mistri tools. allow/deny filter by remote name,
48
79
  # prefix namespaces local names ("linear__create_issue") against
49
80
  # collisions, and gates marks tools needing human approval
50
- # (gates: { "create_issue" => true }, or needs_approval: for all).
81
+ # (gates: { "create_issue" => true }, or needs_approval: for all). A key
82
+ # of gates that names no tool of the server raises, and so does one of a
83
+ # parallel hash. A tool that cannot be bridged is left out: the block is
84
+ # given its definition and the error, and without a block it is named in
85
+ # a warning. deferred keeps the server's tools out of the model's sight
86
+ # until a search loads them. instructions: false keeps the server's
87
+ # instructions out of the conversation, and a string is sent in their
88
+ # place. parallel says which tools may run beside others in a turn: nil
89
+ # follows each tool's readOnlyHint, true or false sets every tool, and a
90
+ # hash sets tools by remote name and leaves the rest to their hint.
91
+ # trust_hints: false means no tool is marked by its hint, only by
92
+ # parallel. timeout is the seconds one call may take in all before the
93
+ # agent stops waiting for it, and nil sets no limit. description_limit is
94
+ # the characters of a description that reach the model, and nil sets
95
+ # none. instructions_as: :user sends the instructions as text of a user
96
+ # turn where they would be a system message.
97
+ #
98
+ # A server that has resources gets one more tool, read_resource, which
99
+ # reads one by its URI: a result of the server's tools names them.
100
+ # resources: true offers it for a server that declares none, and false
101
+ # leaves it out. It is gated by gates: { "read_resource" => true }, and
102
+ # allow and deny take it or leave it out under that name.
51
103
  def tools(client, allow: nil, deny: [], prefix: nil, needs_approval: false, gates: {},
52
- complete_argument_validator: nil)
104
+ complete_argument_validator: nil, deferred: false, instructions: true,
105
+ parallel: nil, timeout: CALL_TIMEOUT, description_limit: DESCRIPTION_LIMIT,
106
+ instructions_as: :system, trust_hints: true, resources: nil)
107
+ description_limit!(description_limit)
108
+ taken = {}
53
109
  listed = client.tools
54
- listed = listed.select { |tool| allow.include?(tool["name"]) } if allow
55
- listed = listed.reject { |tool| deny.include?(tool["name"]) }
56
- listed.map do |tool|
57
- bridge(client, tool, prefix: prefix, gate: gates.fetch(tool["name"], needs_approval),
58
- complete_argument_validator: complete_argument_validator)
110
+ reader = reader_name(client, listed, resources, prefix)
111
+ names = names_of(client, listed, reader)
112
+ { parallel:, gates: }.each { |option, keyed| known_keys!(option, keyed, names) }
113
+ reader = nil unless allowed?(READ_RESOURCE, allow, deny)
114
+ instructions = instructions_for(client, instructions)
115
+ bridged = listed.filter_map do |tool|
116
+ remote = tool["name"] if tool.is_a?(Hash)
117
+ next unless allowed?(remote, allow, deny)
118
+
119
+ bridged = bridge(client, tool, prefix: prefix, gate: gates.fetch(remote, needs_approval),
120
+ complete_argument_validator: complete_argument_validator,
121
+ deferred: deferred, instructions: instructions,
122
+ parallel: parallel.is_a?(Hash) ? parallel[remote] : parallel,
123
+ timeout: timeout, description_limit: description_limit,
124
+ instructions_as: instructions_as, trust_hints: trust_hints,
125
+ reader: reader)
126
+ claim(taken, bridged.name, remote)
127
+ bridged
128
+ rescue ConfigurationError => e
129
+ block_given? ? yield(tool, e) : warn("mistri: #{e.message}; the tool was left out")
130
+ nil
131
+ end
132
+ return bridged unless reader
133
+
134
+ bridged << resource_reader(client, reader, prefix: prefix, deferred: deferred,
135
+ gate: gates.fetch(READ_RESOURCE, needs_approval),
136
+ instructions: instructions, timeout: timeout,
137
+ instructions_as: instructions_as,
138
+ parallel: parallel)
139
+ end
140
+
141
+ # The local name of the tool that reads this server's resources, or nil
142
+ # when none is offered. A server's own tool of that name keeps it.
143
+ def reader_name(client, listed, choice, prefix)
144
+ return unless client.respond_to?(:read_resource)
145
+ return if choice == false
146
+ return unless choice || (client.respond_to?(:resources?) && client.resources?)
147
+
148
+ name = local_name(READ_RESOURCE, prefix)
149
+ own = listed.grep(Hash).any? { |tool| local_name(tool["name"], prefix) == name }
150
+ name unless own
151
+ end
152
+ private_class_method :reader_name
153
+
154
+ def resource_reader(client, local, prefix:, gate:, deferred:, instructions:, timeout:,
155
+ instructions_as:, parallel:)
156
+ server = prefix ? "the MCP server #{prefix.to_s.inspect}" : "the MCP server"
157
+ # A read changes nothing, so it runs beside others unless the host says no.
158
+ alone = (parallel.is_a?(Hash) ? parallel[READ_RESOURCE] : parallel) == false
159
+ Tool.define(local, "Reads one resource of #{server} by its URI. A result of this " \
160
+ "server's tools names a resource it can be read from.",
161
+ input_schema: READ_RESOURCE_SCHEMA, parallel: !alone, needs_approval: gate,
162
+ deferred: deferred, instructions: instructions, timeout: timeout,
163
+ instructions_as: instructions_as) do |args, context|
164
+ contents = client.read_resource(args.fetch("uri"))
165
+ several = contents.length > 1
166
+ blocks = contents.grep(Hash).flat_map do |content|
167
+ [({ "type" => "text", "text" => "#{content["uri"]}:" } if several),
168
+ { "type" => "resource", "resource" => content }].compact
169
+ end
170
+ shown({ "content" => blocks }, nil, saver(context, local))
171
+ rescue Mistri::Error => e
172
+ ToolResult.new(content: "#{local} could not read the resource from #{server}: " \
173
+ "#{e.message}", error: true)
174
+ end
175
+ end
176
+ private_class_method :resource_reader
177
+
178
+ # Keeps bytes in the scratchpad of the agent that made the call, and
179
+ # returns where. nil when that agent has none.
180
+ def saver(context, local)
181
+ ->(bytes, extension) { context.scratchpad&.save_binary(bytes, local, extension) }
182
+ end
183
+ private_class_method :saver
184
+
185
+ def allowed?(name, allow, deny) = !deny.include?(name) && (allow.nil? || allow.include?(name))
186
+
187
+ # The names a host's key may use: the tools the client lists, the ones it
188
+ # left out itself, and the tool that reads resources.
189
+ def names_of(client, listed, reader)
190
+ names = listed.grep(Hash).map { |tool| tool["name"] }
191
+ names.concat(Array(client.left_out)) if client.respond_to?(:left_out)
192
+ reader ? names << READ_RESOURCE : names
193
+ end
194
+
195
+ # A key that names no tool leaves the tool it was meant for without what
196
+ # the host set: without its approval, or to a hint that can mark a tool
197
+ # the host set to run alone. A key may name a tool that allow or deny
198
+ # leaves out.
199
+ def known_keys!(option, keyed, names)
200
+ return unless keyed.is_a?(Hash)
201
+
202
+ unknown = keyed.keys - names
203
+ return if unknown.empty?
204
+
205
+ raise ConfigurationError, "#{option}: names no tool of this server: " \
206
+ "#{unknown.map { |name| label(name) }.join(", ")}"
207
+ end
208
+ private_class_method :allowed?, :names_of, :known_keys!
209
+
210
+ def claim(taken, local, remote)
211
+ holder = taken[local]
212
+ if holder
213
+ raise ConfigurationError,
214
+ "MCP tool #{label(remote)}: the name #{local.inspect} is taken by #{label(holder)}"
59
215
  end
216
+
217
+ taken[local] = remote
60
218
  end
219
+ private_class_method :claim
220
+
221
+ # Text every later step can take: a name is matched and compared, and
222
+ # both travel to a provider as JSON.
223
+ def utf8?(text)
224
+ text.ascii_only? || (text.encoding == Encoding::UTF_8 && text.valid_encoding?)
225
+ end
226
+ private_class_method :utf8?
227
+
228
+ # A remote name is the server's to choose, so a message carries its start.
229
+ def label(remote) = remote.inspect[0, 120]
230
+ private_class_method :label
61
231
 
62
- def bridge(client, spec, prefix: nil, gate: false, complete_argument_validator: nil)
63
- remote = spec.fetch("name")
64
- local = prefix ? "#{prefix}__#{remote}" : remote
232
+ # The text a server's tools carry into the conversation: the host's own
233
+ # string, the server's instructions, or none.
234
+ def instructions_for(client, choice)
235
+ return choice if choice.is_a?(String)
236
+
237
+ client.instructions if choice && client.respond_to?(:instructions)
238
+ end
239
+ private_class_method :instructions_for
240
+
241
+ # The model calls the tool by name, or by a safe name made from prefix and
242
+ # the remote name. The server is always called with the remote name.
243
+ def bridge(client, spec, prefix: nil, name: nil, gate: false,
244
+ complete_argument_validator: nil, deferred: false, instructions: nil,
245
+ parallel: nil, timeout: CALL_TIMEOUT, description_limit: DESCRIPTION_LIMIT,
246
+ instructions_as: :system, trust_hints: true, reader: nil)
247
+ raise ConfigurationError, "the definition is not an object" unless spec.is_a?(Hash)
248
+
249
+ remote = spec["name"]
250
+ unless remote.is_a?(String) && !remote.empty?
251
+ raise ConfigurationError, "the definition has no name"
252
+ end
253
+ raise ConfigurationError, "the name is not valid UTF-8" unless utf8?(remote)
254
+
255
+ description_limit!(description_limit)
256
+ description = spec["description"].to_s
257
+ raise ConfigurationError, "the description is not valid UTF-8" unless utf8?(description)
258
+
259
+ local = name || local_name(remote, prefix)
65
260
  if spec.key?("inputSchema") && spec["inputSchema"].nil?
66
261
  raise ConfigurationError, "inputSchema must be an object, not null"
67
262
  end
@@ -70,61 +265,115 @@ module Mistri
70
265
  input_schema = Schema.validate_mcp!(
71
266
  raw_schema, complete: !complete_argument_validator.nil?
72
267
  )
73
- Tool.define(local, spec["description"].to_s,
74
- input_schema: input_schema,
75
- needs_approval: gate,
76
- complete_argument_validator: complete_argument_validator) do |args|
77
- answer(client.call_tool(remote, args || {}))
268
+ Tool.define(local, bounded(description, description_limit),
269
+ input_schema: input_schema, parallel: marked?(spec, parallel, trust_hints),
270
+ needs_approval: gate, deferred: deferred, instructions: instructions,
271
+ instructions_as: instructions_as, timeout: timeout,
272
+ complete_argument_validator: complete_argument_validator) do |args, context|
273
+ shown(client.call_tool(remote, args || {}), reader, saver(context, local))
274
+ rescue NotSent, AuthenticationError => e
275
+ ToolResult.new(content: unreachable(local, prefix, e), error: true)
78
276
  end
79
277
  rescue ConfigurationError => e
80
- raise ConfigurationError, "MCP tool #{remote.inspect}: #{e.message}"
81
- end
82
-
83
- # An MCP result becomes model-readable content: text joins, images ride
84
- # as image blocks, and isError remains structured failure data end to end.
85
- def answer(result)
86
- blocks = Array(result["content"]).map { |block| convert(block) }
87
- if result["isError"]
88
- text_blocks = blocks.grep(String)
89
- if result["structuredContent"]
90
- structured = JSON.generate(result["structuredContent"])
91
- text_blocks << structured unless text_blocks.include?(structured)
92
- end
93
- text = text_blocks.join("\n")
94
- content = "MCP tool error: #{text.empty? ? "unknown error" : text}"
95
- non_text = blocks.grep_v(String)
96
- content = [content, *non_text] unless non_text.empty?
97
- return ToolResult.new(content:, error: true)
278
+ raise ConfigurationError, "MCP tool #{label(remote)}: #{e.message}"
279
+ end
280
+
281
+ # Without the host's choice a tool is marked by its readOnlyHint, which is
282
+ # the server's own word about its tool. Nothing checks it, so a host that
283
+ # does not trust the server turns the hint off.
284
+ def marked?(spec, choice, trusted)
285
+ return choice unless choice.nil?
286
+
287
+ annotations = spec["annotations"]
288
+ trusted && annotations.is_a?(Hash) && annotations["readOnlyHint"] == true
289
+ end
290
+ private_class_method :marked?
291
+
292
+ # What the model reads when a tool could not run because its server could
293
+ # not be used: which server, by the name the host gave it, and why.
294
+ def unreachable(local, prefix, error)
295
+ server = prefix ? "the MCP server #{prefix.to_s.inspect}" : "the MCP server"
296
+ if SIGN_IN_ERRORS.any? { |kind| error.is_a?(kind) }
297
+ return "#{local} did not run: #{server} needs a sign-in before its tools can be used " \
298
+ "(#{error.message})."
98
299
  end
99
- if blocks.empty? && result["structuredContent"]
100
- return JSON.generate(result["structuredContent"])
300
+
301
+ if ToolExecutor.deadline?(error)
302
+ return "#{local} did not run: its time limit passed before the call was sent to #{server}."
101
303
  end
102
- return blocks.join("\n") if blocks.all?(String)
103
304
 
104
- blocks
305
+ "No connection to #{server} could be established, so #{local} did not run: #{error.message}"
105
306
  end
307
+ private_class_method :unreachable
106
308
 
107
- def convert(block)
108
- case block["type"]
109
- when "text" then block["text"].to_s
110
- when "image"
111
- Content::Image.from_bytes(block["data"].to_s.unpack1("m"),
112
- mime_type: block["mimeType"] || "image/png")
113
- when "resource" then resource_text(block["resource"] || {})
114
- when "resource_link" then "[resource: #{block["uri"]}]"
115
- else "[unsupported #{block["type"]} content]"
309
+ def description_limit!(limit)
310
+ return if limit.nil? || (limit.is_a?(Integer) && !limit.negative?)
311
+
312
+ raise ConfigurationError, "description_limit: must be nil or an integer that is not negative"
313
+ end
314
+ private_class_method :description_limit!
315
+
316
+ def bounded(description, limit)
317
+ return description if limit.nil? || description.length <= limit
318
+
319
+ "#{description[0, limit]}\n[cut at #{limit} of #{description.length} characters]"
320
+ end
321
+ private_class_method :bounded
322
+
323
+ # The SHA-256 of a tool's definition, as JSON with the keys of every
324
+ # object in order. A host keeps it with the definition a person approved.
325
+ def digest(definition)
326
+ Digest::SHA256.hexdigest(JSON.generate(ordered(JSON.parse(JSON.generate(definition)))))
327
+ end
328
+
329
+ # The names of the tools that a fresh listing adds, removes and changes,
330
+ # against a kept one. Each is what Client#listing returned, or an array
331
+ # of definitions.
332
+ def changes(kept, fresh)
333
+ before, after = [kept, fresh].map do |listing|
334
+ tools = listing.is_a?(Hash) ? listing["tools"] : listing
335
+ # Of two definitions with one name the first counts, as for the bridge.
336
+ Array(tools).grep(Hash).each_with_object({}) do |tool, seen|
337
+ seen[tool["name"]] ||= digest(tool)
338
+ end
339
+ end
340
+ { "added" => after.keys - before.keys, "removed" => before.keys - after.keys,
341
+ "changed" => before.keys.select { |name| after.key?(name) && after[name] != before[name] } }
342
+ end
343
+
344
+ def ordered(value)
345
+ case value
346
+ when Hash then value.sort.to_h.transform_values { |member| ordered(member) }
347
+ when Array then value.map { |member| ordered(member) }
348
+ else value
116
349
  end
117
350
  end
351
+ private_class_method :ordered
352
+
353
+ # The local name of a remote tool. One that every provider takes stays
354
+ # as it is. Any other has its unsafe characters replaced and ends in a
355
+ # hash of the whole name, so it depends on nothing but prefix and remote.
356
+ def local_name(remote, prefix = nil)
357
+ whole = prefix ? "#{prefix}__#{remote}" : remote.to_s
358
+ return whole if whole.match?(SAFE_NAME)
118
359
 
119
- def resource_text(resource)
120
- resource["text"] || "[resource: #{resource["uri"]}]"
360
+ safe = whole.gsub(/[^A-Za-z0-9_-]/, "_")
361
+ safe = "_#{safe}" unless safe.match?(/\A[A-Za-z_]/)
362
+ "#{safe[0, NAME_LIMIT - 9]}_#{Digest::SHA256.hexdigest(whole)[0, 8]}"
121
363
  end
122
364
  end
123
365
  end
124
366
 
367
+ require_relative "mcp/results"
125
368
  require_relative "mcp/egress"
369
+ require_relative "mcp/mirror"
370
+ require_relative "mcp/negotiation"
371
+ require_relative "mcp/conversation"
126
372
  require_relative "mcp/wires"
127
373
  require_relative "mcp/client"
374
+ require_relative "mcp/sdk_client"
128
375
  require_relative "mcp/oauth"
129
376
 
130
- Mistri::MCP.private_constant :Egress, :WireError, :EMPTY_INPUT_SCHEMA
377
+ Mistri::MCP.private_constant :Egress, :Mirror, :WireError, :WireTimeout, :EMPTY_INPUT_SCHEMA,
378
+ :READ_RESOURCE, :READ_RESOURCE_SCHEMA, :TEXT_TYPE,
379
+ :NAME_LIMIT, :SAFE_NAME
data/lib/mistri/memory.rb CHANGED
@@ -9,7 +9,7 @@ module Mistri
9
9
  # read: -> { org.agent_memory.to_s },
10
10
  # write: ->(text) { org.update!(agent_memory: text) }
11
11
  # )
12
- # agent = Mistri.agent("claude-opus-4-8", tools: [*Mistri::Tools.memory(memory)])
12
+ # agent = Mistri.agent("claude-opus-5-5", tools: [*Mistri::Tools.memory(memory)])
13
13
  class Memory
14
14
  def initialize(read:, write:)
15
15
  @read = read
@@ -13,15 +13,20 @@ module Mistri
13
13
  # ui is a tool result's host-only channel. tool_error is true or false on
14
14
  # newly produced tool results and nil on legacy records that predate the
15
15
  # field. error is the machine-readable failure on an errored provider turn
16
- # (ErrorData shape); error_message stays the human story.
16
+ # (ErrorData shape); error_message stays the human story. loads names the
17
+ # deferred tools a tool result made available. reminder marks a system
18
+ # message that the harness wrote into the conversation for the model, and
19
+ # holds the kind of note. Its content is the note's text alone: each
20
+ # provider gives it the wire form the model reads. cut holds the true bytes
21
+ # and lines of a tool result that was stored cut, for the host alone.
17
22
  class Message < Data.define(:role, :content, :tool_call_id, :tool_name,
18
23
  :model, :provider, :usage, :stop_reason, :error_message, :ui,
19
- :error, :tool_error)
24
+ :error, :tool_error, :loads, :reminder, :cut)
20
25
  ROLES = %i[system user assistant tool].freeze
21
26
 
22
27
  def initialize(role:, content: nil, tool_call_id: nil, tool_name: nil, model: nil,
23
28
  provider: nil, usage: nil, stop_reason: nil, error_message: nil, ui: nil,
24
- error: nil, tool_error: nil)
29
+ error: nil, tool_error: nil, loads: nil, reminder: nil, cut: nil)
25
30
  role = role.to_sym
26
31
  raise ArgumentError, "unknown role #{role.inspect}" unless ROLES.include?(role)
27
32
  if stop_reason && !StopReason.valid?(stop_reason)
@@ -34,9 +39,23 @@ module Mistri
34
39
  end
35
40
  raise ArgumentError, "tool_error is only valid on tool messages" if role != :tool
36
41
  end
42
+ loads = owned_loads(loads, role)
43
+ if reminder && role != :system
44
+ raise ArgumentError, "reminder is only valid on system messages"
45
+ end
46
+ raise ArgumentError, "cut is only valid on tool messages" if cut && role != :tool
37
47
 
38
48
  super(role:, content: Content.wrap(content).freeze, tool_call_id:, tool_name:,
39
- model:, provider:, usage:, stop_reason:, error_message:, ui:, error:, tool_error:)
49
+ model:, provider:, usage:, stop_reason:, error_message:, ui:, error:, tool_error:,
50
+ loads:, reminder:, cut:)
51
+ end
52
+
53
+ # Tool names a session can store: strings of plain ASCII or valid UTF-8.
54
+ def self.names?(value)
55
+ value.is_a?(Array) && value.all? do |name|
56
+ name.is_a?(String) &&
57
+ (name.ascii_only? || (name.encoding == Encoding::UTF_8 && name.valid_encoding?))
58
+ end
40
59
  end
41
60
 
42
61
  def self.system(content) = new(role: :system, content:)
@@ -53,12 +72,18 @@ module Mistri
53
72
  new(role: :user, content: blocks)
54
73
  end
55
74
 
75
+ # One text block for each text.
76
+ def self.reminder(kind, *texts)
77
+ new(role: :system, content: texts, reminder: kind.to_s)
78
+ end
79
+
56
80
  def self.assistant(content: nil, tool_calls: [], **meta)
57
81
  new(role: :assistant, content: [*Content.wrap(content), *tool_calls], **meta)
58
82
  end
59
83
 
60
- def self.tool(content:, tool_call_id:, tool_name: nil, ui: nil, tool_error: false)
61
- new(role: :tool, content:, tool_call_id:, tool_name:, ui:, tool_error:)
84
+ def self.tool(content:, tool_call_id:, tool_name: nil, ui: nil, tool_error: false, loads: nil,
85
+ cut: nil)
86
+ new(role: :tool, content:, tool_call_id:, tool_name:, ui:, tool_error:, loads:, cut:)
62
87
  end
63
88
 
64
89
  def self.from_h(hash)
@@ -69,7 +94,8 @@ module Mistri
69
94
  model: h["model"], provider: h["provider"]&.to_sym,
70
95
  usage: h["usage"] && Usage.from_h(h["usage"]),
71
96
  stop_reason: h["stop_reason"]&.to_sym, error_message: h["error_message"],
72
- ui: h["ui"], error: h["error"], tool_error: h["tool_error"])
97
+ ui: h["ui"], error: h["error"], tool_error: h["tool_error"], loads: h["loads"],
98
+ reminder: h["reminder"], cut: h["cut"])
73
99
  end
74
100
 
75
101
  def system? = role == :system
@@ -94,7 +120,18 @@ module Mistri
94
120
  def to_h
95
121
  { role:, content: content.map(&:to_h), tool_call_id:, tool_name:, model:,
96
122
  provider:, usage: usage&.to_h, stop_reason:, error_message:, ui:, error:,
97
- tool_error: }.compact
123
+ tool_error:, loads:, reminder:, cut: }.compact
124
+ end
125
+
126
+ private
127
+
128
+ def owned_loads(loads, role)
129
+ return nil if loads.nil?
130
+ raise ArgumentError, "loads must be an array of tool names" unless Message.names?(loads)
131
+ return nil if loads.empty?
132
+ raise ArgumentError, "loads is only valid on tool messages" if role != :tool
133
+
134
+ loads.map { |name| Content.freeze_string(name) }.freeze
98
135
  end
99
136
  end
100
137
  end