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/models.rb CHANGED
@@ -33,8 +33,8 @@ module Mistri
33
33
  # a provider from sending an unsupported thinking shape that 400s.
34
34
  #
35
35
  # context_window is the provider's published context or input limit.
36
- # Anthropic and OpenAI share it with the next output; Gemini publishes a
37
- # separate inputTokenLimit and outputTokenLimit.
36
+ # Anthropic, OpenAI and Gemini 4 share it with the next output. Gemini
37
+ # before 4 publishes a separate inputTokenLimit and outputTokenLimit.
38
38
  #
39
39
  # Pricing is selected per request from its prompt size. Rates are paid
40
40
  # standard direct-API list prices. cache_write is the provider's baseline
@@ -98,8 +98,22 @@ module Mistri
98
98
  private_class_method :price
99
99
 
100
100
  CATALOG = [
101
+ ["claude-fable-5-2", :anthropic, 128_000, 1_000_000, :adaptive,
102
+ [price(input: 8.0, output: 40.0, cache_read: 0.2, cache_write: 10.0)]],
103
+ ["claude-opus-5-5", :anthropic, 128_000, 1_000_000, :adaptive,
104
+ [price(input: 4.0, output: 20.0, cache_read: 0.2, cache_write: 5.0)]],
105
+ ["claude-sonnet-5-5", :anthropic, 128_000, 1_000_000, :adaptive,
106
+ [price(input: 2.0, output: 10.0, cache_read: 0.1, cache_write: 2.5)]],
107
+ ["claude-haiku-5-5", :anthropic, 128_000, 1_000_000, :adaptive,
108
+ [price({ input: 0.1, output: 0.5, cache_read: 0.01, cache_write: 0.125 },
109
+ above: 100_000,
110
+ higher: { input: 0.5, output: 2.5, cache_read: 0.05, cache_write: 0.625 })]],
111
+ ["claude-fable-5-1", :anthropic, 128_000, 1_000_000, :adaptive,
112
+ [price(input: 10.0, output: 50.0, cache_read: 0.25, cache_write: 12.5)]],
101
113
  ["claude-fable-5", :anthropic, 128_000, 1_000_000, :adaptive,
102
114
  [price(input: 10.0, output: 50.0, cache_read: 1.0, cache_write: 12.5)]],
115
+ ["claude-opus-5", :anthropic, 128_000, 1_000_000, :adaptive,
116
+ [price(input: 5.0, output: 25.0, cache_read: 0.5, cache_write: 6.25)]],
103
117
  ["claude-opus-4-8", :anthropic, 128_000, 1_000_000, :adaptive,
104
118
  [price(input: 5.0, output: 25.0, cache_read: 0.5, cache_write: 6.25)]],
105
119
  ["claude-opus-4-7", :anthropic, 128_000, 1_000_000, :adaptive,
@@ -107,28 +121,58 @@ module Mistri
107
121
  ["claude-opus-4-6", :anthropic, 128_000, 1_000_000, :adaptive,
108
122
  [price(input: 5.0, output: 25.0, cache_read: 0.5, cache_write: 6.25)]],
109
123
  ["claude-sonnet-5", :anthropic, 128_000, 1_000_000, :adaptive,
110
- [price(input: 2.0, output: 10.0, cache_read: 0.2, cache_write: 2.5),
111
- price({ input: 3.0, output: 15.0, cache_read: 0.3, cache_write: 3.75 },
112
- from: Time.utc(2026, 9, 1))]],
124
+ [price(input: 2.0, output: 10.0, cache_read: 0.2, cache_write: 2.5)]],
113
125
  ["claude-sonnet-4-6", :anthropic, 128_000, 1_000_000, :adaptive,
114
126
  [price(input: 3.0, output: 15.0, cache_read: 0.3, cache_write: 3.75)]],
115
127
  ["claude-haiku-4-5", :anthropic, 64_000, 200_000, :budget,
116
128
  [price(input: 1.0, output: 5.0, cache_read: 0.1, cache_write: 1.25)]],
129
+ ["gpt-6.2-astra", :openai, 128_000, 1_050_000, :effort,
130
+ [price({ input: 8.0, output: 40.0, cache_read: 0.4, cache_write: 10.0 },
131
+ above: 272_000,
132
+ higher: { input: 16.0, output: 60.0, cache_read: 0.8,
133
+ cache_write: 20.0 })]],
134
+ ["gpt-6.2-sol", :openai, 128_000, 1_050_000, :effort,
135
+ [price({ input: 2.0, output: 10.0, cache_read: 0.1, cache_write: 2.5 },
136
+ above: 272_000,
137
+ higher: { input: 4.0, output: 15.0, cache_read: 0.2, cache_write: 5.0 })]],
138
+ ["gpt-6-astra", :openai, 128_000, 1_050_000, :effort,
139
+ [price({ input: 10.0, output: 50.0, cache_read: 1.0, cache_write: 12.5 },
140
+ above: 272_000,
141
+ higher: { input: 20.0, output: 75.0, cache_read: 2.0,
142
+ cache_write: 25.0 })]],
143
+ ["gpt-6.1-sol", :openai, 128_000, 1_050_000, :effort,
144
+ [price({ input: 2.0, output: 10.0, cache_read: 0.1, cache_write: 2.5 },
145
+ above: 272_000,
146
+ higher: { input: 4.0, output: 15.0, cache_read: 0.2, cache_write: 5.0 })]],
147
+ ["gpt-6.1-terra", :openai, 128_000, 1_050_000, :effort,
148
+ [price({ input: 1.0, output: 5.0, cache_read: 0.05, cache_write: 1.25 },
149
+ above: 272_000,
150
+ higher: { input: 2.0, output: 7.5, cache_read: 0.1, cache_write: 2.5 })]],
151
+ ["gpt-6-luna", :openai, 128_000, 1_050_000, :effort,
152
+ [price({ input: 0.1, output: 0.5, cache_read: 0.01, cache_write: 0.125 },
153
+ above: 272_000,
154
+ higher: { input: 0.2, output: 0.75, cache_read: 0.02, cache_write: 0.25 })]],
155
+ ["gpt-6-sol", :openai, 128_000, 1_050_000, :effort,
156
+ [price({ input: 2.0, output: 10.0, cache_read: 0.2, cache_write: 2.5 },
157
+ above: 272_000,
158
+ higher: { input: 4.0, output: 15.0, cache_read: 0.4, cache_write: 5.0 })]],
159
+ # OpenAI's promotional price ends with November 30, 2026, Pacific time.
117
160
  ["gpt-5.6-sol", :openai, 128_000, 1_050_000, :effort,
118
- [price({ input: 5.0, output: 30.0, cache_read: 0.5, cache_write: 6.25 },
161
+ [price({ input: 4.0, output: 20.0, cache_read: 0.4, cache_write: 5.0 },
119
162
  above: 272_000,
163
+ higher: { input: 8.0, output: 30.0, cache_read: 0.8, cache_write: 10.0 }),
164
+ price({ input: 5.0, output: 30.0, cache_read: 0.5, cache_write: 6.25 },
165
+ from: Time.utc(2026, 12, 1, 8), above: 272_000,
120
166
  higher: { input: 10.0, output: 45.0, cache_read: 1.0,
121
167
  cache_write: 12.5 })]],
122
168
  ["gpt-5.6-terra", :openai, 128_000, 1_050_000, :effort,
123
- [price({ input: 2.5, output: 15.0, cache_read: 0.25, cache_write: 3.125 },
169
+ [price({ input: 2.0, output: 12.0, cache_read: 0.2, cache_write: 2.5 },
124
170
  above: 272_000,
125
- higher: { input: 5.0, output: 22.5, cache_read: 0.5,
126
- cache_write: 6.25 })]],
171
+ higher: { input: 4.0, output: 18.0, cache_read: 0.4, cache_write: 5.0 })]],
127
172
  ["gpt-5.6-luna", :openai, 128_000, 1_050_000, :effort,
128
- [price({ input: 1.0, output: 6.0, cache_read: 0.1, cache_write: 1.25 },
173
+ [price({ input: 0.2, output: 1.2, cache_read: 0.02, cache_write: 0.25 },
129
174
  above: 272_000,
130
- higher: { input: 2.0, output: 9.0, cache_read: 0.2,
131
- cache_write: 2.5 })]],
175
+ higher: { input: 0.4, output: 1.8, cache_read: 0.04, cache_write: 0.5 })]],
132
176
  ["gpt-5.5", :openai, 128_000, 1_050_000, :effort,
133
177
  [price({ input: 5.0, output: 30.0, cache_read: 0.5 },
134
178
  above: 272_000, higher: { input: 10.0, output: 45.0, cache_read: 1.0 })]],
@@ -137,22 +181,50 @@ module Mistri
137
181
  above: 272_000, higher: { input: 5.0, output: 22.5, cache_read: 0.5 })]],
138
182
  ["gpt-5-nano", :openai, 128_000, 400_000, :effort,
139
183
  [price(input: 0.05, output: 0.4, cache_read: 0.005)]],
140
- ["gemini-3.5-flash", :gemini, 65_536, 1_048_576, :level,
141
- [price(input: 1.5, output: 9.0, cache_read: 0.15)]],
184
+ # max_output is what one streamed request of a Gemini 4 model returns.
185
+ ["gemini-4-carbon", :gemini, 65_536, 1_048_576, :level,
186
+ [price(input: 2.0, output: 10.0, cache_read: 0.1),
187
+ price({ input: 4.0, output: 20.0, cache_read: 0.2 },
188
+ from: Time.utc(2026, 12, 1))]],
189
+ ["gemini-4-argon", :gemini, 65_536, 1_048_576, :level,
190
+ [price(input: 2.0, output: 10.0, cache_read: 0.1),
191
+ price({ input: 4.0, output: 20.0, cache_read: 0.2 },
192
+ from: Time.utc(2026, 12, 1))]],
193
+ ["gemini-4-neon", :gemini, 65_536, 1_048_576, :level,
194
+ [price(input: 3.0, output: 15.0, cache_read: 0.15)]],
195
+ ["gemini-4-hydrogen", :gemini, 65_536, 1_048_576, :level,
196
+ [price(input: 1.5, output: 7.5, cache_read: 0.075)]],
197
+ ["gemini-3.8-flash", :gemini, 65_536, 1_048_576, :level,
198
+ [price(input: 0.75, output: 3.75, cache_read: 0.075),
199
+ price({ input: 1.5, output: 7.5, cache_read: 0.15 },
200
+ from: Time.utc(2027, 1, 1))]],
201
+ ["gemini-3.6-flash", :gemini, 65_536, 1_048_576, :level,
202
+ [price(input: 0.75, output: 3.75, cache_read: 0.075),
203
+ price({ input: 1.5, output: 7.5, cache_read: 0.15 },
204
+ from: Time.utc(2027, 1, 1))]],
205
+ ["gemini-3.5-flash-lite", :gemini, 65_536, 1_048_576, :level,
206
+ [price(input: 0.3, output: 2.5, cache_read: 0.03)]],
142
207
  ["gemini-3.1-pro-preview", :gemini, 65_536, 1_048_576, :level,
143
208
  [price({ input: 2.0, output: 12.0, cache_read: 0.2 },
144
- above: 200_000, higher: { input: 4.0, output: 18.0, cache_read: 0.4 })]],
145
- ["gemini-2.5-pro", :gemini, 65_536, 1_048_576, :budget,
146
- [price({ input: 1.25, output: 10.0, cache_read: 0.125 },
147
- above: 200_000, higher: { input: 2.5, output: 15.0, cache_read: 0.25 })]],
148
- ["gemini-2.5-flash", :gemini, 65_536, 1_048_576, :budget,
149
- [price(input: 0.3, output: 2.5, cache_read: 0.03)]]
209
+ above: 200_000, higher: { input: 4.0, output: 18.0, cache_read: 0.4 })]]
150
210
  ].to_h do |row|
151
211
  id, provider, max_output, context_window, thinking, pricing = row
152
212
  [id, Model.new(id:, provider:, max_output:, context_window:, thinking:, pricing:)]
153
213
  end.freeze
154
214
 
155
- ALIASES = { "gpt-5.6" => "gpt-5.6-sol" }.freeze
215
+ # The API answers a request for gemini-3.5-flash with gemini-3.6-flash.
216
+ ALIASES = { "gpt-5.6" => "gpt-5.6-sol", "gemini-3.5-flash" => "gemini-3.6-flash" }.freeze
217
+ SEPARATE_OUTPUT = %w[gemini-3.8-flash gemini-3.6-flash gemini-3.5-flash-lite
218
+ gemini-3.1-pro-preview].freeze
219
+ TURN_BOUND_THINKING = %w[claude-fable-5 claude-opus-5 claude-opus-4-8 claude-opus-4-7
220
+ claude-opus-4-6 claude-sonnet-5 claude-sonnet-4-6
221
+ claude-haiku-4-5].freeze
222
+ TOOL_LOADING_FROM = [5, 4].freeze
223
+ CACHE_OPTIONS_FROM = [5, 6].freeze
224
+ COMPACTION_FROM = { "opus" => [4, 6], "sonnet" => [4, 6], "haiku" => [5, 5],
225
+ "fable" => [5], "mythos" => [5] }.freeze
226
+ SYSTEM_MESSAGES_FROM = { "opus" => [4, 8], "sonnet" => [5, 5], "haiku" => [5, 5],
227
+ "fable" => [5], "mythos" => [5] }.freeze
156
228
 
157
229
  # Published family aliases and dated ids resolve to their canonical entry.
158
230
  def self.find(id)
@@ -165,15 +237,65 @@ module Mistri
165
237
 
166
238
  def self.max_output(id) = find(id)&.max_output
167
239
 
168
- # Output capacity that occupies the published context limit. Gemini's
169
- # output limit is independent, so its compaction headroom is input-only.
240
+ # Output capacity that occupies the published context limit. A Gemini
241
+ # model before 4 has an independent output limit, so its compaction
242
+ # headroom is input-only.
170
243
  def self.shared_output(id)
171
244
  model = find(id)
172
- model&.max_output unless model&.provider == :gemini
245
+ model&.max_output unless SEPARATE_OUTPUT.include?(model&.id)
173
246
  end
174
247
 
175
248
  def self.thinking(id) = find(id)&.thinking
176
249
 
250
+ # Anthropic signatures bind to the preceding conversation, not just their
251
+ # turn, on every model released after the turn-bound ones. An id the
252
+ # catalog does not know is newer, so it counts as bound.
253
+ def self.prefix_bound_thinking?(id)
254
+ model = find(id)
255
+ model.nil? || (model.provider == :anthropic && !TURN_BOUND_THINKING.include?(model.id))
256
+ end
257
+
258
+ # OpenAI documents loading tools into a running conversation for gpt-5.4
259
+ # and later, and not for its nano models, which take the request and
260
+ # then search again where they should call the loaded tool. The version
261
+ # is read from the id, so a later model qualifies before the catalog
262
+ # knows it, and any id that does not say is taken for an older model.
263
+ def self.tool_loading?(id)
264
+ version = id.to_s[/\Agpt-(\d+(?:\.\d+)?)/, 1]
265
+ return false if version.nil? || id.to_s.include?("-nano")
266
+
267
+ (version.split(".").map(&:to_i) <=> TOOL_LOADING_FROM) >= 0
268
+ end
269
+
270
+ # OpenAI bills a cache write from gpt-5.6 on, and takes
271
+ # prompt_cache_options to say where one ends. An earlier model writes for
272
+ # nothing and refuses the option. The version is read from the id, as for
273
+ # tool_loading?.
274
+ def self.cache_options?(id)
275
+ version = id.to_s[/\Agpt-(\d+(?:\.\d+)?)/, 1]
276
+ !version.nil? && (version.split(".").map(&:to_i) <=> CACHE_OPTIONS_FROM) >= 0
277
+ end
278
+
279
+ # Anthropic takes a system message in the middle of a conversation from
280
+ # these versions of each family on. Sonnet 5 is left out because its
281
+ # reference names it as a model that does not. The version is read from
282
+ # the id, so a later model qualifies before the catalog knows it, and an
283
+ # id of any other form is taken for an older model.
284
+ def self.system_messages?(id)
285
+ family, version = id.to_s.match(/\Aclaude-([a-z]+)-(\d+(?:-\d{1,2})?)(?:-\d{8})?\z/)&.captures
286
+ from = SYSTEM_MESSAGES_FROM[family]
287
+ !from.nil? && (version.split("-").map(&:to_i) <=> from) >= 0
288
+ end
289
+
290
+ # Anthropic writes a compaction's summary on demand from these versions
291
+ # of each family on. The version is read from the id, as for
292
+ # system_messages?.
293
+ def self.compaction?(id)
294
+ family, version = id.to_s.match(/\Aclaude-([a-z]+)-(\d+(?:-\d{1,2})?)(?:-\d{8})?\z/)&.captures
295
+ from = COMPACTION_FROM[family]
296
+ !from.nil? && (version.split("-").map(&:to_i) <=> from) >= 0
297
+ end
298
+
177
299
  def self.rates(id, usage: nil, at: Time.now) = find(id)&.rates(usage:, at:)
178
300
 
179
301
  def self.priced?(id) = find(id)&.priced? || false
@@ -166,8 +166,8 @@ module Mistri
166
166
  Integer(token)
167
167
  rescue ArgumentError
168
168
  begin
169
- finite(Float(token))
170
- rescue ArgumentError
169
+ finite(JSON.parse(token))
170
+ rescue JSON::ParserError
171
171
  trimmed_number(token)
172
172
  end
173
173
  end
@@ -178,15 +178,15 @@ module Mistri
178
178
  trimmed = token.sub(/[eE][+-]?\z/, "").sub(/\.\z/, "")
179
179
  return NOTHING if trimmed.empty? || trimmed == "-"
180
180
 
181
- finite(Float(trimmed))
182
- rescue ArgumentError
181
+ finite(JSON.parse(trimmed))
182
+ rescue JSON::ParserError
183
183
  NOTHING
184
184
  end
185
185
 
186
186
  # A model that emits 1e999 yields Float::INFINITY, which JSON cannot
187
187
  # generate, so it would crash replay and persistence. Drop it.
188
188
  def finite(number)
189
- number.finite? ? number : NOTHING
189
+ number.is_a?(Numeric) && number.finite? ? number : NOTHING
190
190
  end
191
191
 
192
192
  def decode(json_string)
@@ -38,7 +38,7 @@ module Mistri
38
38
  end
39
39
 
40
40
  case type
41
- when "message_start" then message_start(record)
41
+ when "message_start" then message_start(record, &)
42
42
  when "content_block_start" then start_block(record, &)
43
43
  when "content_block_delta" then delta_block(record, &)
44
44
  when "content_block_stop" then stop_block(record, &)
@@ -133,10 +133,20 @@ module Mistri
133
133
 
134
134
  private
135
135
 
136
- def message_start(record)
136
+ def message_start(record, &)
137
137
  raw = record.dig("message", "usage")
138
138
  @service_tier = raw&.fetch("service_tier", nil)
139
139
  @usage = priced(parse_usage(raw))
140
+ report_dropped_thinking(record.dig("message", "input_transformations"), &)
141
+ end
142
+
143
+ def report_dropped_thinking(transformations, &)
144
+ reasons = Array(transformations).filter_map do |entry|
145
+ entry["reason"] if entry.is_a?(Hash) && entry["type"] == "thinking_dropped"
146
+ end
147
+ return if reasons.empty?
148
+
149
+ emit_event(:thinking_dropped, content: reasons.uniq.join(", "), &)
140
150
  end
141
151
 
142
152
  def start_block(record, &)
@@ -154,8 +164,11 @@ module Mistri
154
164
 
155
165
  @open_wire_index = index
156
166
  @next_wire_index += 1
167
+ open_block(record["content_block"] || {}, &)
168
+ end
157
169
 
158
- block = record["content_block"] || {}
170
+ def open_block(block, &)
171
+ return @blocks << compaction(block) if block["type"] == "compaction"
159
172
  if block["type"] == "tool_use" && block.key?("input") &&
160
173
  (!block["input"].is_a?(Hash) || !block["input"].empty?)
161
174
  return protocol_error("tool_use started with nonempty input before its deltas", &)
@@ -286,6 +299,9 @@ module Mistri
286
299
  @refused = true
287
300
  @refusal = record.dig("delta", "stop_details")
288
301
  end
302
+ usage = record["usage"]
303
+ return count_compaction(usage) if reason == "compaction" || compaction_billed?(usage)
304
+
289
305
  # message_delta usage is cumulative; merge output counts over the
290
306
  # opening snapshot rather than summing.
291
307
  output = record.dig("usage", "output_tokens")
@@ -295,6 +311,26 @@ module Mistri
295
311
  @usage_authoritative = true
296
312
  end
297
313
 
314
+ # The block arrives whole, and is kept as it came: the API takes it
315
+ # back only unchanged.
316
+ def compaction(block)
317
+ Content::Compaction.new(provider: :anthropic, data: block, text: block["content"])
318
+ end
319
+
320
+ # A compaction is billed in usage.iterations, and the top-level
321
+ # counts of its response are zero.
322
+ def count_compaction(usage)
323
+ spent = Array(usage&.fetch("iterations", nil)).map { |entry| parse_usage(entry) }
324
+ @usage = priced(spent.reduce(Usage.new, :+)) if spent.any?
325
+ @usage_authoritative = spent.any?
326
+ end
327
+
328
+ # A compaction request that ends with no block, as at the output
329
+ # limit, is billed the same way.
330
+ def compaction_billed?(usage)
331
+ Array(usage&.fetch("iterations", nil)).any? { |entry| entry["type"] == "compaction" }
332
+ end
333
+
298
334
  def stop_message(&)
299
335
  protocol_error("message stopped before the content block stopped", &) if @open_wire_index
300
336
  @done = true
@@ -380,6 +416,7 @@ module Mistri
380
416
  # window is a truncation, per the API's own guidance.
381
417
  def map_stop_reason(reason)
382
418
  { "end_turn" => StopReason::STOP, "stop_sequence" => StopReason::STOP,
419
+ "compaction" => StopReason::STOP,
383
420
  "max_tokens" => StopReason::LENGTH, "tool_use" => StopReason::TOOL_USE,
384
421
  "model_context_window_exceeded" => StopReason::LENGTH,
385
422
  "pause_turn" => StopReason::TOOL_USE }.fetch(reason, StopReason::STOP)
@@ -10,8 +10,19 @@ module Mistri
10
10
  # blocks replay with their signature and must never be altered, redacted
11
11
  # thinking replays as its opaque payload, and cache_control marks the
12
12
  # last system block and the last user message so the stable prefix and
13
- # the growing history both cache.
13
+ # the growing history both cache. A deferred tool travels with
14
+ # defer_loading, which keeps it out of the prompt, and a result that
15
+ # loads one carries a tool_reference to it.
14
16
  module Serializer
17
+ # The first deferred definition in a conversation rebuilds its cached
18
+ # prefix. This one is sent from the first request, so a load never
19
+ # does. No result references it, so it never enters the prompt.
20
+ RESERVED = { name: "mistri_deferred_tools",
21
+ description: "Reserved. Keeps tool loading in place. Never call it.",
22
+ input_schema: { type: "object", properties: {}.freeze }.freeze,
23
+ defer_loading: true }.freeze
24
+ private_constant :RESERVED
25
+
15
26
  module_function
16
27
 
17
28
  def system_blocks(system, cache:)
@@ -22,41 +33,142 @@ module Mistri
22
33
  blocks
23
34
  end
24
35
 
25
- def messages(history, cache: false)
26
- turns = history.reject(&:system?).chunk_while { |a, b| a.tool? && b.tool? }
27
- wire = turns.map do |group|
28
- group.first.tool? ? tool_results(group) : message(group.first)
36
+ # deferred names the deferred tools of this request: only those can
37
+ # be referenced, and the API refuses a reference to any other.
38
+ # system_messages sends each reminder as a system message. Without it
39
+ # a reminder is text of a user turn.
40
+ def messages(history, cache: false, deferred: [], system_messages: false)
41
+ unreferenced = deferred.dup
42
+ history = if system_messages
43
+ Reminder.user_weighted(Reminder.after_results(history))
44
+ else
45
+ Reminder.as_user_turns(history)
46
+ end
47
+ wire = []
48
+ held = []
49
+ history.chunk_while { |a, b| a.tool? && b.tool? }.each do |group|
50
+ first = group.first
51
+ next (held << first if first.reminder) if first.system?
52
+
53
+ turn = first.tool? ? tool_results(group, unreferenced) : message(first)
54
+ next unless turn
55
+
56
+ wire.concat(system_turns(held, wire.last)) if first.assistant?
57
+ wire << turn
29
58
  end
59
+ wire.concat(system_turns(held, wire.last))
30
60
  mark_last_user_turn(wire) if cache
31
61
  wire
32
62
  end
33
63
 
34
- def tools(definitions)
35
- definitions.map do |tool|
36
- spec = tool.transform_keys(&:to_sym)
37
- wire = { name: spec[:name], description: spec[:description],
38
- input_schema: spec[:input_schema] }
39
- wire[:eager_input_streaming] = true if spec[:eager_input_streaming]
40
- wire
64
+ # The API takes a system message after a user turn, and before an
65
+ # assistant turn or at the end. A reminder stored anywhere else is
66
+ # sent there. When no user turn precedes that place, it is sent as
67
+ # text of a user turn.
68
+ def system_turns(held, before)
69
+ reminders = held.slice!(0..)
70
+ unless before && before[:role] == "user"
71
+ return Reminder.as_user_turns(reminders).filter_map { |msg| message(msg) }
72
+ end
73
+
74
+ reminders.filter_map do |reminder|
75
+ blocks = reminder.content.grep(Content::Text).filter_map { |text| text_block(text) }
76
+ { role: "system", content: blocks } if blocks.any?
77
+ end
78
+ end
79
+
80
+ # A model the API writes no compaction for refuses a block. It is sent
81
+ # the text of the block, in the form of a summary the gem wrote.
82
+ def without_blocks(history)
83
+ history.map do |msg|
84
+ block = msg.content.grep(Content::Compaction).first
85
+ block ? Message.user("#{Compaction::SUMMARY_PREFACE}\n\n#{block.text}") : msg
86
+ end
87
+ end
88
+
89
+ # deferred is nil for an agent that defers nothing, and the loaded
90
+ # deferred tools for one that does.
91
+ def tools(definitions, deferred = nil)
92
+ eager = definitions.map { |tool| definition(tool) }
93
+ return eager unless deferred
94
+
95
+ loaded = deferred.map { |tool| definition(tool).merge(defer_loading: true) }
96
+ if (eager + loaded).any? { |tool| tool[:name] == RESERVED[:name] }
97
+ raise ConfigurationError, "the tool name #{RESERVED[:name]} is reserved while " \
98
+ "tools are deferred on Anthropic"
99
+ end
100
+
101
+ eager + [RESERVED] + loaded
102
+ end
103
+
104
+ # The names a result may reference: the deferred tools of the request,
105
+ # never the reserved definition.
106
+ def referable(definitions)
107
+ definitions.filter_map do |tool|
108
+ tool[:name] if tool[:defer_loading] && !tool.equal?(RESERVED)
41
109
  end
42
110
  end
43
111
 
112
+ def definition(tool)
113
+ spec = tool.transform_keys(&:to_sym)
114
+ wire = { name: spec[:name], description: spec[:description],
115
+ input_schema: spec[:input_schema] }
116
+ wire[:eager_input_streaming] = true if spec[:eager_input_streaming]
117
+ wire
118
+ end
119
+
120
+ # The API rejects a user turn with no content.
44
121
  def message(msg)
45
122
  own = msg.provider == :anthropic
46
- { role: msg.role.to_s,
47
- content: msg.content.filter_map { |content| block(content, own:) } }
123
+ blocks = msg.content.filter_map { |content| block(content, own:) }
124
+ { role: msg.role.to_s, content: blocks } unless msg.user? && blocks.empty?
48
125
  end
49
126
 
50
- def tool_results(group)
51
- { role: "user", content: group.map do |msg|
127
+ # The API takes references alone in a tool_result, and text alone in a
128
+ # failed one, so the content it refuses there follows the results of
129
+ # the turn.
130
+ def tool_results(group, unreferenced = [])
131
+ after = []
132
+ results = group.map do |msg|
52
133
  blocks = msg.content.filter_map { |content| block(content, own: false) }
134
+ references = references(msg, unreferenced)
135
+ if references.any?
136
+ after.concat(blocks)
137
+ blocks = references
138
+ elsif msg.tool_error?
139
+ blocks, others = blocks.partition { |block| block[:type] == "text" }
140
+ after.concat(outside(msg, others))
141
+ end
53
142
  # The API rejects an empty tool_result; a space stands in for a
54
143
  # tool that returned nothing.
55
144
  blocks = [{ type: "text", text: " " }] if blocks.empty?
56
145
  result = { type: "tool_result", tool_use_id: msg.tool_call_id, content: blocks }
57
146
  result[:is_error] = true if msg.tool_error?
58
147
  result
59
- end }
148
+ end
149
+ { role: "user", content: results + after }
150
+ end
151
+
152
+ # Outside its tool_result nothing ties a block to its call, and with
153
+ # two failed calls in a turn a model mixed their pictures up, so a line
154
+ # of text names the tool first.
155
+ def outside(msg, blocks)
156
+ return blocks if blocks.empty?
157
+
158
+ call = msg.tool_name ? "#{msg.tool_name} call" : "tool call"
159
+ [{ type: "text", text: "The failed #{call} also returned:" }, *blocks]
160
+ end
161
+
162
+ # A failed result must be text alone. The API adds a tool's definition
163
+ # to the prompt at every reference, so only the first result that
164
+ # loads a tool references it: its name is then removed from
165
+ # unreferenced.
166
+ def references(msg, unreferenced)
167
+ return [] if msg.tool_error?
168
+
169
+ names = msg.loads.to_a & unreferenced
170
+ unreferenced.reject! { |name| names.include?(name) }
171
+ names.map { |name| { type: "tool_reference", tool_name: name } }
60
172
  end
61
173
 
62
174
  # Returns nil for a block the API would reject (empty text, unusable
@@ -65,9 +177,8 @@ module Mistri
65
177
  case block
66
178
  when Content::Text then text_block(block)
67
179
  when Content::Thinking then thinking_block(block, own:)
68
- when Content::Image
69
- { type: "image",
70
- source: { type: "base64", media_type: block.mime_type, data: block.data } }
180
+ when Content::Image then image_block(block)
181
+ when Content::Compaction then block.data
71
182
  when ToolCall
72
183
  { type: "tool_use", id: block.id, name: block.name,
73
184
  input: ToolArguments.replay_object(block) }
@@ -76,9 +187,30 @@ module Mistri
76
187
  end
77
188
  end
78
189
 
79
- # The API rejects empty text content blocks.
190
+ # True when a message of a request holds a compaction block, which the
191
+ # API returned with string keys and takes back as it came. Replay
192
+ # sends it first. A block that a context transform moved is still sent
193
+ # with the header, so the API's refusal names the block.
194
+ def compacted?(wire)
195
+ wire.any? do |turn|
196
+ Array(turn[:content]).any? do |block|
197
+ block.is_a?(Hash) && block["type"] == "compaction"
198
+ end
199
+ end
200
+ end
201
+
202
+ # The API refuses a format it does not take and a label that differs
203
+ # from the bytes, so the type sent is the one the bytes show.
204
+ def image_block(image)
205
+ type = image.detected_mime_type
206
+ return { type: "text", text: image.placeholder } unless type
207
+
208
+ { type: "image", source: { type: "base64", media_type: type, data: image.data } }
209
+ end
210
+
211
+ # The API rejects a turn whose text is only whitespace.
80
212
  def text_block(block)
81
- block.text.empty? ? nil : { type: "text", text: block.text }
213
+ block.text.match?(/\A[[:space:]]*\z/) ? nil : { type: "text", text: block.text }
82
214
  end
83
215
 
84
216
  # Thinking replays only with its signature. Redacted thinking carries