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
@@ -15,17 +15,24 @@ module Mistri
15
15
  DEFAULT_ORIGIN = "https://api.anthropic.com"
16
16
  VERSION_HEADER = "2023-06-01"
17
17
  DEFAULT_THINKING = { type: "adaptive", display: "summarized" }.freeze
18
+ # Thinking signed under a prefix that later changed is dropped by the
19
+ # API instead of failing the request and every request after it.
20
+ DROP_STALE_THINKING = { block_binding: { prefix_mismatch_behavior: "drop_block" } }.freeze
21
+ BINDING_BETA = "thinking-binding-controls-2026-08-01"
22
+ COMPACTION_BETA = "compact-2026-09-04"
18
23
 
19
24
  # Messages API parameters passed through verbatim from a stream override.
20
25
  PASSTHROUGH = %i[temperature top_p top_k stop_sequences metadata tool_choice].freeze
26
+ # What the count endpoint takes of a request's body.
27
+ COUNTED = %i[model messages system tools thinking tool_choice output_config].freeze
21
28
  # The ceiling for an uncatalogued model: high enough for headroom, low
22
29
  # enough that every current model accepts it. Catalog a model to unlock
23
30
  # its real output limit.
24
31
  UNKNOWN_MODEL_MAX_TOKENS = 64_000
25
32
 
26
- def initialize(api_key:, model: "claude-opus-4-8", origin: DEFAULT_ORIGIN,
33
+ def initialize(api_key:, model: "claude-opus-5-5", origin: DEFAULT_ORIGIN,
27
34
  max_tokens: nil, thinking: DEFAULT_THINKING, cache: true,
28
- service_tier: nil, catalog_pricing: nil,
35
+ service_tier: nil, catalog_pricing: nil, defers_tools: nil,
29
36
  **transport_options)
30
37
  @api_key = api_key
31
38
  @model = model
@@ -33,7 +40,9 @@ module Mistri
33
40
  @thinking = thinking
34
41
  @cache = cache
35
42
  @service_tier = service_tier
36
- @catalog_pricing = catalog_pricing.nil? ? official_origin?(origin) : catalog_pricing
43
+ @official = official_origin?(origin)
44
+ @catalog_pricing = catalog_pricing.nil? ? @official : catalog_pricing
45
+ @defers_tools = defers_tools.nil? ? @official : defers_tools
37
46
  @transport = Transport.new(origin: origin, **transport_options)
38
47
  end
39
48
 
@@ -49,13 +58,31 @@ module Mistri
49
58
  SchemaCapabilities.derive(schema, :anthropic)
50
59
  end
51
60
 
61
+ # The API keeps a deferred definition out of the prompt until a result
62
+ # references it, so an agent passes the loaded deferred tools as
63
+ # deferred_tools and the eager tools of a request never change. Another
64
+ # origin may not support this, and receives the loaded tools as tools
65
+ # unless the host sets defers_tools: true.
66
+ def defers_tools? = @defers_tools
67
+
68
+ # The API takes a system message in the middle of a conversation on its
69
+ # newer models, and a reminder is sent to them as one. An older model,
70
+ # and another origin, which may refuse the role, receive a reminder as
71
+ # text of a user turn.
72
+ def system_messages?(model = @model) = @official && Models.system_messages?(model)
73
+
74
+ # The API writes a compaction's summary itself for these models. The
75
+ # compactor then calls stream with compaction: { instructions: }, and
76
+ # the reply holds one Content::Compaction and no answer.
77
+ def compacts?(model = @model) = @official && Models.compaction?(model)
78
+
52
79
  def stream(messages:, system: nil, tools: [], signal: nil, **overrides, &emit)
53
80
  delivery = EventDelivery.wrap(emit)
54
81
  model = overrides.fetch(:model, @model)
55
82
  assembler = Anthropic::Assembler.new(model: model, catalog_pricing: @catalog_pricing)
56
83
  assembler.start(&delivery)
57
84
  body = build_body(model, messages, system, tools, overrides)
58
- outcome = @transport.stream_post("/v1/messages", body: body, headers: headers,
85
+ outcome = @transport.stream_post("/v1/messages", body: body, headers: headers(body),
59
86
  signal: signal) do |record|
60
87
  assembler.feed(
61
88
  record, &delivery
@@ -65,25 +92,51 @@ module Mistri
65
92
  rescue EventDelivery::Failure => e
66
93
  raise EventDelivery.unwrap(e, delivery)
67
94
  rescue Error => e
68
- assembler.fail_stream(e, &emit)
95
+ assembler.fail_stream(too_long(e), &emit)
96
+ end
97
+
98
+ # The API's own count of the input tokens of the request that stream
99
+ # would send for the same arguments. It is free and has its own rate
100
+ # limit. Nil on another origin, which may not have the endpoint.
101
+ def count_tokens(messages:, system: nil, tools: [], **overrides)
102
+ return nil unless @official
103
+
104
+ model = overrides.fetch(:model, @model)
105
+ body = build_body(model, messages, system, tools, overrides).slice(*COUNTED)
106
+ @transport.post("/v1/messages/count_tokens", body:, headers: headers(body))
107
+ .fetch("input_tokens")
69
108
  end
70
109
 
71
110
  def close = @transport.close
72
111
 
73
112
  private
74
113
 
114
+ # The API refuses an input longer than the window with status 400 and
115
+ # "prompt is too long", and a request of too many bytes with 413.
116
+ def too_long(error)
117
+ ContextTooLongError.from(error) do |status, body|
118
+ status == 413 || (status == 400 && body.include?("prompt is too long"))
119
+ end
120
+ end
121
+
75
122
  def official_origin?(origin) = origin.to_s.delete_suffix("/") == DEFAULT_ORIGIN
76
123
 
77
124
  def build_body(model, messages, system, tools, overrides)
125
+ Content.refuse_foreign_compaction!(messages, :anthropic)
126
+ messages = Serializer.without_blocks(messages) unless compacts?(model)
127
+ definitions = Serializer.tools(tools, overrides[:deferred_tools])
128
+ deferred = Serializer.referable(definitions)
129
+ cache = overrides.fetch(:cache, @cache)
78
130
  body = {
79
131
  model: model,
80
132
  max_tokens: max_tokens_for(model, overrides),
81
133
  stream: true,
82
- messages: Serializer.messages(messages, cache: @cache)
134
+ messages: Serializer.messages(messages, cache:, deferred:,
135
+ system_messages: system_messages?(model))
83
136
  }
84
- system_blocks = Serializer.system_blocks(system, cache: @cache)
137
+ system_blocks = Serializer.system_blocks(system, cache:)
85
138
  body[:system] = system_blocks if system_blocks
86
- body[:tools] = Serializer.tools(tools) if tools.any?
139
+ body[:tools] = definitions if definitions.any?
87
140
  service_tier = overrides.fetch(:service_tier, @service_tier)
88
141
  body[:service_tier] = service_tier if service_tier
89
142
  thinking = thinking_for(model, overrides)
@@ -92,6 +145,9 @@ module Mistri
92
145
  body[:output_config] = { format: { type: "json_schema",
93
146
  schema: Schema.strict(schema) } }
94
147
  end
148
+ if (compaction = overrides[:compaction])
149
+ body[:compaction] = { type: "summarize", **compaction.compact }
150
+ end
95
151
  body.merge(PASSTHROUGH.each_with_object({}) do |key, params|
96
152
  params[key] = overrides[key] if overrides.key?(key)
97
153
  end)
@@ -100,13 +156,15 @@ module Mistri
100
156
  # Adaptive thinking 400s on budget-only models like Haiku 4.5, so the
101
157
  # adaptive default is dropped for a model the catalog marks :budget; a
102
158
  # host that wants thinking there passes an explicit budget config. An
103
- # unknown model keeps the default, since new models are adaptive.
159
+ # unknown model keeps the default, since new models are adaptive. Another
160
+ # origin may not accept the binding control, so a host sets it there.
104
161
  def thinking_for(model, overrides)
105
162
  thinking = overrides.fetch(:thinking, @thinking)
106
163
  return thinking unless thinking && thinking[:type] == "adaptive"
107
164
  return nil if Models.thinking(model) == :budget
165
+ return thinking if thinking.key?(:block_binding) || !@official
108
166
 
109
- thinking
167
+ thinking.merge(DROP_STALE_THINKING)
110
168
  end
111
169
 
112
170
  # The API requires max_tokens and bills only actual output, so the
@@ -118,8 +176,15 @@ module Mistri
118
176
  end
119
177
  end
120
178
 
121
- def headers
122
- { "x-api-key" => @api_key, "anthropic-version" => VERSION_HEADER }
179
+ # The API asks for the compaction header on the request that writes a
180
+ # block and on every later one that carries it.
181
+ def headers(body)
182
+ betas = []
183
+ betas << BINDING_BETA if body.dig(:thinking, :block_binding)
184
+ betas << COMPACTION_BETA if body[:compaction] || Serializer.compacted?(body[:messages])
185
+ headers = { "x-api-key" => @api_key, "anthropic-version" => VERSION_HEADER }
186
+ headers["anthropic-beta"] = betas.join(",") if betas.any?
187
+ headers
123
188
  end
124
189
  end
125
190
  end
@@ -38,6 +38,9 @@ module Mistri
38
38
 
39
39
  def prices_usage? = @prices_usage
40
40
 
41
+ # A request is recorded with each reminder as the session holds it.
42
+ def system_messages? = true
43
+
41
44
  def stream(messages: [], **options, &emit)
42
45
  # Snapshot the array: the loop appends replies to it in place.
43
46
  @requests << { messages: messages.dup, options: }
@@ -128,7 +131,7 @@ module Mistri
128
131
  end
129
132
 
130
133
  def assemble(blocks, **meta)
131
- Message.assistant(content: blocks, model: MODEL, provider: :fake, **meta)
134
+ Message.assistant(content: blocks, model: model, provider: :fake, **meta)
132
135
  end
133
136
 
134
137
  def emit_event(emit, type, blocks, **fields)
@@ -13,6 +13,12 @@ module Mistri
13
13
  #
14
14
  # Thought signatures ride on individual parts and are captured onto the
15
15
  # block they arrived with, verbatim, for replay.
16
+ #
17
+ # One answer can take several requests. A request that ends with
18
+ # CONTINUATION leaves its text open, because the next one goes on in the
19
+ # middle of a sentence. Each request is billed, so their usage is added
20
+ # up, and every request after the first reads the earlier output again
21
+ # as its prompt, so the context is kept as a figure of its own.
16
22
  class Assembler
17
23
  def initialize(model:, catalog_pricing: true, service_tier: nil)
18
24
  @model = model
@@ -24,8 +30,14 @@ module Mistri
24
30
  @usage = Usage.new
25
31
  @finish_reason = nil
26
32
  @terminal = false
33
+ @requests = 1
27
34
  end
28
35
 
36
+ # Twice the streamed requests of 65,536 tokens that fill the shared
37
+ # window, so only an answer that never ends reaches it.
38
+ MAX_REQUESTS = 32
39
+ CONTINUATION = "CONTINUATION"
40
+
29
41
  # Finish reasons that are the provider's verdict on the content
30
42
  # itself: a retry of the same input meets the same filter, and a
31
43
  # harness that re-rolls against a policy verdict is machinery for
@@ -73,13 +85,30 @@ module Mistri
73
85
  Array(candidate.dig("content", "parts")).each_with_index do |part, index|
74
86
  fold_part(part, part_boundary: index.positive?, &)
75
87
  end
88
+ @token = candidate["continuationToken"] if candidate["continuationToken"]
76
89
  @finish_reason = candidate["finishReason"] if candidate["finishReason"]
77
90
  @terminal = true if @finish_reason || @block_reason
78
- close_current(&) if @terminal
91
+ close_current(&) if @terminal && @finish_reason != CONTINUATION
79
92
  ingest_usage(record)
80
93
  end
81
94
  private :after_terminal, :record_error, :fold_record
82
95
 
96
+ # Called when a request has ended. Returns the token to send the same
97
+ # request again with when the answer goes on, and nil when it is over.
98
+ def continue
99
+ return nil unless @finish_reason == CONTINUATION && @error.nil?
100
+ return cannot_continue("carried no token to go on with") unless @token
101
+ return never_ends if @requests >= MAX_REQUESTS
102
+
103
+ @requests += 1
104
+ bank_usage
105
+ @finish_reason = nil
106
+ @terminal = false
107
+ token = @token
108
+ @token = nil
109
+ token
110
+ end
111
+
83
112
  # A stream that ended without a finishReason was truncated, not
84
113
  # cancelled: fail it so the loop can treat it as retryable.
85
114
  def finish(&emit)
@@ -129,11 +158,15 @@ module Mistri
129
158
  def fold_part(part, part_boundary: false, &)
130
159
  if part.key?("functionCall")
131
160
  fold_function_call(part, &)
132
- elsif part.key?("text")
161
+ elsif part.key?("text") && !hollow?(part)
133
162
  fold_text(part, part["thought"] ? :thinking : :text, part_boundary:, &)
134
163
  end
135
164
  end
136
165
 
166
+ # The API ends a turn that calls a tool with a text part of no text.
167
+ # Without a signature it holds nothing to show and nothing to replay.
168
+ def hollow?(part) = part["text"].to_s.empty? && part["thoughtSignature"].nil?
169
+
137
170
  def terminal_content?(record)
138
171
  return true if record["error"]
139
172
  return true unless record.dig("promptFeedback", "blockReason").to_s.empty?
@@ -237,6 +270,33 @@ module Mistri
237
270
  ProviderError.new("generation stopped: #{@finish_reason}")
238
271
  end
239
272
 
273
+ def cannot_continue(reason)
274
+ @error = ProviderError.new("the answer #{reason}")
275
+ nil
276
+ end
277
+
278
+ # A retry would send and bill every request again and end the same way.
279
+ def never_ends
280
+ @error = InvalidRequestError.new("the answer went on past #{MAX_REQUESTS} requests")
281
+ nil
282
+ end
283
+
284
+ def bank_usage
285
+ invalidate_cost unless @usage_authoritative
286
+ @earlier = @earlier ? @earlier + @usage : @usage
287
+ @usage = Usage.new
288
+ @usage_authoritative = false
289
+ end
290
+
291
+ # The last request read every request before it as its prompt, so
292
+ # its own count is what sits in the context.
293
+ def answer_usage
294
+ return @usage unless @earlier
295
+
296
+ last = @usage.prompt_tokens + @usage.output
297
+ (@earlier + @usage).with(context: (last if last.positive?))
298
+ end
299
+
240
300
  def stop_reason
241
301
  return StopReason::LENGTH if @finish_reason == "MAX_TOKENS"
242
302
  return StopReason::TOOL_USE if @blocks.any?(ToolCall)
@@ -259,7 +319,7 @@ module Mistri
259
319
  blocks = @blocks.dup
260
320
  blocks << build_current if @current
261
321
  Message.assistant(content: blocks, model: @model, provider: :gemini,
262
- usage: @usage, **meta)
322
+ usage: answer_usage, **meta)
263
323
  end
264
324
 
265
325
  def parse_usage(raw)
@@ -20,7 +20,7 @@ module Mistri
20
20
 
21
21
  def contents(history)
22
22
  result_metadata = tool_result_metadata(history)
23
- groups = history.reject(&:system?).chunk_while do |a, b|
23
+ groups = Reminder.as_user_turns(history).reject(&:system?).chunk_while do |a, b|
24
24
  a.tool? && b.tool? && native_tool_result?(a, result_metadata) ==
25
25
  native_tool_result?(b, result_metadata)
26
26
  end
@@ -37,10 +37,17 @@ module Mistri
37
37
  end
38
38
  end
39
39
 
40
- def system_instruction(system)
41
- return nil if system.nil? || system.empty?
40
+ def system_instruction(system, history = [])
41
+ text = [system, *loaded_skills(history)].compact.reject(&:empty?).join("\n\n")
42
+ text.empty? ? nil : { parts: [{ text: }] }
43
+ end
42
44
 
43
- { parts: [{ text: system }] }
45
+ # Gemini takes instructions from its system instruction and treats a
46
+ # tool result as data, so a skill the model loaded is repeated here.
47
+ def loaded_skills(history)
48
+ history.select { |message| message.tool? && message.tool_name == Skills::READER }
49
+ .reject(&:tool_error?).filter_map(&:text).uniq
50
+ .map { |body| "## Loaded skill\n\n#{body}" }
44
51
  end
45
52
 
46
53
  def tools(definitions)
@@ -68,38 +75,42 @@ module Mistri
68
75
  end
69
76
 
70
77
  key = msg.tool_error? ? "error" : "result"
71
- response = { name: msg.tool_name, response: { key => result_text(msg) } }
78
+ response = { name: msg.tool_name, response: { key => msg.text.to_s } }
72
79
  wire_id = result_metadata.dig(msg, :provider_call_id)
73
80
  response[:id] = wire_id if wire_id
81
+ images = image_parts(msg)
82
+ response[:parts] = images if images.any?
74
83
  { functionResponse: response }
75
84
  end }
76
85
  end
77
86
 
78
87
  def foreign_tool_turn(group)
79
- { role: "user", parts: group.map do |msg|
88
+ { role: "user", parts: group.flat_map do |msg|
80
89
  raise SchemaError, "Gemini tool results need tool_name" unless msg.tool_name
81
90
 
82
91
  label = msg.tool_error? ? "error" : "result"
83
92
  text = "Tool #{JSON.generate(msg.tool_name)} #{label} " \
84
- "(call #{JSON.generate(msg.tool_call_id)}): #{result_text(msg)}"
85
- { text: text }
93
+ "(call #{JSON.generate(msg.tool_call_id)}): #{msg.text}"
94
+ [{ text: text }, *image_parts(msg)]
86
95
  end }
87
96
  end
88
97
 
89
- # Non-text blocks in a tool result have no functionResponse encoding;
90
- # note the omission rather than dropping it silently.
91
- def result_text(msg)
92
- omitted = msg.content.count { |block| !block.is_a?(Content::Text) }
93
- text = msg.text.to_s
94
- omitted.positive? ? "#{text}\n[#{omitted} non-text block(s) omitted]".strip : text
98
+ # A functionResponse takes an image as a part of its own, beside the
99
+ # response object, on Gemini 3 and later. A turn of text takes one as
100
+ # any user turn does.
101
+ def image_parts(msg)
102
+ msg.content.grep(Content::Image).map { |image| inline_data(image) }
103
+ end
104
+
105
+ def inline_data(image)
106
+ { inlineData: { mimeType: image.mime_type, data: image.data } }
95
107
  end
96
108
 
97
109
  def user_parts(msg)
98
110
  msg.content.map do |block|
99
111
  case block
100
112
  when Content::Text then { text: block.text }
101
- when Content::Image
102
- { inlineData: { mimeType: block.mime_type, data: block.data } }
113
+ when Content::Image then inline_data(block)
103
114
  else
104
115
  raise SchemaError, "cannot serialize #{block.class} for Gemini user input"
105
116
  end
@@ -10,20 +10,27 @@ module Mistri
10
10
  # Thinking is deliberately unconstrained: no budget, no level, only
11
11
  # includeThoughts so summaries stream for the UI. The model's own defaults
12
12
  # decide how much to think, and a host override passes through verbatim.
13
- # maxOutputTokens is omitted for the same reason: the API defaults to the
14
- # model's ceiling.
13
+ # maxOutputTokens is sent only when the provider or a stream call is given
14
+ # max_tokens. Otherwise the API's default applies, which on Gemini 4 is
15
+ # the 65,536 tokens of one request.
16
+ #
17
+ # A Gemini 4 model returns at most that many tokens for one request. An
18
+ # answer that needs more ends its request with CONTINUATION and a token,
19
+ # and the same request sent again with the token goes on from there.
15
20
  class Gemini
16
21
  DEFAULT_ORIGIN = "https://generativelanguage.googleapis.com"
17
22
  DEFAULT_THINKING = { includeThoughts: true }.freeze
18
23
 
19
- def initialize(api_key:, model: "gemini-2.5-flash",
20
- origin: DEFAULT_ORIGIN, thinking: DEFAULT_THINKING,
24
+ def initialize(api_key:, model: "gemini-3.8-flash",
25
+ origin: DEFAULT_ORIGIN, thinking: DEFAULT_THINKING, max_tokens: nil,
21
26
  service_tier: nil, catalog_pricing: nil, **transport_options)
22
27
  @api_key = api_key
23
28
  @model = model
24
29
  @thinking = thinking
30
+ @max_tokens = max_tokens
25
31
  @service_tier = service_tier
26
- @catalog_pricing = catalog_pricing.nil? ? official_origin?(origin) : catalog_pricing
32
+ @official = official_origin?(origin)
33
+ @catalog_pricing = catalog_pricing.nil? ? @official : catalog_pricing
27
34
  @transport = Transport.new(origin: origin, **transport_options)
28
35
  end
29
36
 
@@ -34,6 +41,10 @@ module Mistri
34
41
  @catalog_pricing && Models.priced?(model) && tier_known
35
42
  end
36
43
 
44
+ # The API has no system message in the middle of a conversation, so a
45
+ # reminder is sent as text of a user turn.
46
+ def system_messages? = false
47
+
37
48
  def native_output_schema(schema)
38
49
  return unless Models.find(model)&.provider == :gemini
39
50
 
@@ -49,27 +60,59 @@ module Mistri
49
60
  assembler.start(&delivery)
50
61
  body = build_body(messages, system, tools, overrides)
51
62
  path = "/v1beta/models/#{model}:streamGenerateContent?alt=sse"
52
- outcome = @transport.stream_post(path, body: body, headers: headers,
53
- signal: signal) do |record|
54
- assembler.feed(record,
55
- &delivery)
63
+ outcome = nil
64
+ loop do
65
+ # A tool call's arguments arrive as an object inside the record, so
66
+ # the record's tokens are counted before it is parsed.
67
+ outcome = @transport.stream_post(path, body:, headers:, signal:,
68
+ count_tokens: true) do |record|
69
+ assembler.feed(record, &delivery)
70
+ end
71
+ token = assembler.continue unless outcome == :aborted
72
+ break unless token
73
+
74
+ body = body.merge(continuationToken: token)
56
75
  end
57
76
  outcome == :aborted ? assembler.abort(&delivery) : assembler.finish(&delivery)
58
77
  rescue EventDelivery::Failure => e
59
78
  raise EventDelivery.unwrap(e, delivery)
60
79
  rescue Error => e
61
- assembler.fail_stream(e, &emit)
80
+ assembler.fail_stream(too_long(e), &emit)
81
+ end
82
+
83
+ # The API's own count of the input tokens of the request that stream
84
+ # would send for the same arguments. It counts a thought signature
85
+ # lower than a request does, by about 8 tokens for each tool call. Nil
86
+ # on another origin, which may not have the endpoint.
87
+ def count_tokens(messages:, system: nil, tools: [], **overrides)
88
+ return nil unless @official
89
+
90
+ model = overrides.fetch(:model, @model)
91
+ request = build_body(messages, system, tools, overrides)
92
+ .slice(:contents, :systemInstruction, :tools).merge(model: "models/#{model}")
93
+ @transport.post("/v1beta/models/#{model}:countTokens",
94
+ body: { generateContentRequest: request }, headers:).fetch("totalTokens")
62
95
  end
63
96
 
64
97
  def close = @transport.close
65
98
 
66
99
  private
67
100
 
101
+ # The API refuses an input longer than the window with status 400 and
102
+ # a message that the input token count exceeds the maximum number of
103
+ # tokens allowed.
104
+ def too_long(error)
105
+ ContextTooLongError.from(error) do |status, body|
106
+ status == 400 && body.include?("exceeds the maximum number of tokens")
107
+ end
108
+ end
109
+
68
110
  def official_origin?(origin) = origin.to_s.delete_suffix("/") == DEFAULT_ORIGIN
69
111
 
70
112
  def build_body(messages, system, tools, overrides)
113
+ Content.refuse_foreign_compaction!(messages, :gemini)
71
114
  body = { contents: Serializer.contents(messages) }
72
- instruction = Serializer.system_instruction(system)
115
+ instruction = Serializer.system_instruction(system, messages)
73
116
  body[:systemInstruction] = instruction if instruction
74
117
  body[:tools] = Serializer.tools(tools) if tools.any?
75
118
  service_tier = overrides.fetch(:service_tier, @service_tier)
@@ -77,6 +120,8 @@ module Mistri
77
120
  config = {}
78
121
  thinking = overrides.fetch(:thinking, @thinking)
79
122
  config[:thinkingConfig] = thinking if thinking
123
+ max_tokens = overrides.fetch(:max_tokens, @max_tokens)
124
+ config[:maxOutputTokens] = max_tokens if max_tokens
80
125
  # Constrained decoding combines with tools only on 3-series models
81
126
  # (preview); with tools present the task loop's validate-and-fix
82
127
  # pass carries the guarantee instead.
@@ -74,10 +74,12 @@ module Mistri
74
74
  end
75
75
 
76
76
  # In-stream failures carry a code; rate limits and server errors must
77
- # classify as retryable, not fold into prose.
77
+ # classify as retryable, not fold into prose. The code and the message
78
+ # sit on the record itself or under "error", as the API sends both.
78
79
  def wire_error(record)
79
- message = record["message"] || "provider error"
80
- code = record["code"].to_s
80
+ detail = record["error"].is_a?(Hash) ? record["error"] : record
81
+ code = detail["code"].to_s
82
+ message = [code, detail["message"] || "provider error"].reject(&:empty?).join(": ")
81
83
  classify_error(code, message, unknown: ProviderError)
82
84
  end
83
85
 
@@ -217,7 +219,10 @@ module Mistri
217
219
  return if @error
218
220
 
219
221
  item = record["item"]
220
- kind = KINDS[item&.fetch("type", nil)]
222
+ type = item&.fetch("type", nil)
223
+ return keep_compaction(item) if type == "compaction"
224
+
225
+ kind = KINDS[type]
221
226
  return unless kind || @current
222
227
 
223
228
  problem = completed_item_problem(record, item, kind)
@@ -227,6 +232,12 @@ module Mistri
227
232
  commit_item(item, kind, &)
228
233
  end
229
234
 
235
+ # A compaction arrives whole and sealed, and is kept as it came: the
236
+ # API takes it back only unchanged.
237
+ def keep_compaction(item)
238
+ @blocks << Content::Compaction.new(provider: :openai, data: item)
239
+ end
240
+
230
241
  def completed_item_problem(record, item, kind)
231
242
  return "response closed an output item that was never opened" unless @current
232
243
  unless kind == @current.kind
@@ -335,12 +346,29 @@ module Mistri
335
346
  @service_tier = response["service_tier"]
336
347
  usage = response["usage"]
337
348
  @usage = priced(parse_usage(usage)) if usage
349
+ report_dropped_thinking(response["input_transformations"], &)
350
+ end
351
+
352
+ # The API removes a replayed reasoning item it will not take again and
353
+ # still answers 200. Only the finished response says so. A model
354
+ # before GPT-5.6 leaves out the reasoning of earlier turns by design,
355
+ # which is not a removal to report.
356
+ def report_dropped_thinking(transformations, &)
357
+ reasons = Array(transformations).filter_map do |entry|
358
+ next unless entry.is_a?(Hash) && entry["type"] == "reasoning"
359
+
360
+ entry["reason"] if entry["action"] == "removed" && entry["reason"] != "turn_boundary"
361
+ end
362
+ return if reasons.empty?
363
+
364
+ emit_event(:thinking_dropped, content: reasons.uniq.join(", "), &)
338
365
  end
339
366
 
340
367
  # A failed response is the provider's verdict on this input, not a
341
368
  # transport accident: only its documented transient codes retry
342
369
  # (rate limits, server errors, timeouts). Everything else, like
343
- # invalid_prompt and the image family, cannot succeed on a retry.
370
+ # invalid_prompt, a policy refusal and the image family, is not
371
+ # retried.
344
372
  def failure_error(error)
345
373
  return ProviderError.new("the response failed without an error") unless error
346
374
 
@@ -350,10 +378,13 @@ module Mistri
350
378
  classify_error(code, message, unknown: InvalidRequestError)
351
379
  end
352
380
 
381
+ # A streamed request longer than the window is answered with status
382
+ # 200 and then fails with the code context_length_exceeded.
353
383
  def classify_error(code, message, unknown:)
354
384
  klass = if code.include?("rate_limit") then RateLimitError
355
385
  elsif code.include?("server") then ServerError
356
386
  elsif code.include?("timeout") then ProviderError
387
+ elsif code == "context_length_exceeded" then ContextTooLongError
357
388
  elsif code.empty? then unknown
358
389
  else InvalidRequestError
359
390
  end