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
data/lib/mistri/agent.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require "securerandom"
4
5
 
5
6
  module Mistri
6
7
  # The agent loop: prompt the provider, run any tools it calls, feed the
@@ -23,9 +24,18 @@ module Mistri
23
24
  MAX_ARGUMENT_VIOLATIONS = 8
24
25
  MAX_ARGUMENT_ERROR_BYTES = 2048
25
26
  MAX_VIOLATION_SOURCE_BYTES = 4096
27
+ # One server's instructions in the conversation, in bytes, and all of
28
+ # them together when they are sent before any tool is loaded.
29
+ INSTRUCTIONS_BYTES = 2_000
30
+ INSTRUCTIONS_TOGETHER_BYTES = 20_000
31
+ # The reminder a server's instructions are appended as, by the weight the
32
+ # host gave them.
33
+ INSTRUCTION_KINDS = { system: "tool_instructions",
34
+ user: Reminder::AS_USER.first }.freeze
26
35
  TOOL_ARGUMENT_VALIDATOR = Tool.instance_method(:validate_arguments)
27
36
  private_constant :MAX_ARGUMENT_VIOLATIONS, :MAX_ARGUMENT_ERROR_BYTES,
28
- :MAX_VIOLATION_SOURCE_BYTES, :TOOL_ARGUMENT_VALIDATOR
37
+ :MAX_VIOLATION_SOURCE_BYTES, :INSTRUCTIONS_BYTES,
38
+ :INSTRUCTIONS_TOGETHER_BYTES, :INSTRUCTION_KINDS, :TOOL_ARGUMENT_VALIDATOR
29
39
 
30
40
  # compaction defaults on so long sessions survive their context window;
31
41
  # pass false to disable, or a tuned Compaction. It only ever triggers
@@ -33,6 +43,8 @@ module Mistri
33
43
  # skills: an array of Skill (or a directory path for Skills.load). Their
34
44
  # descriptions join the system prompt and a read_skill tool serves full
35
45
  # bodies on demand.
46
+ # A tool marked deferred is not shown to the model until a tool result
47
+ # loads it; with any present, a tool_search tool finds and loads them.
36
48
  # before_tool and after_tool are the programmatic gates around every
37
49
  # execution: before_tool(call, context) blocks a call by returning the
38
50
  # reason as a String, which answers the model in band (and it runs again
@@ -44,28 +56,30 @@ module Mistri
44
56
  def initialize(provider:, session: nil, system: nil, tools: [], budget: nil,
45
57
  max_concurrency: 4, transform_context: nil, compaction: Compaction.new,
46
58
  retries: RetryPolicy.new, skills: [], before_tool: nil, after_tool: nil,
47
- context: nil, log_label: nil)
59
+ context: nil, log_label: nil, lease: true, result_limit: ResultLimit.new,
60
+ scratchpad: nil, sandbox: nil, files: nil)
48
61
  @provider = provider
49
62
  @session = session || Session.new(store: Stores::Memory.new)
50
63
  skills = skills.is_a?(String) ? Skills.load(skills) : Array(skills)
51
64
  @system = Skills.amend(system, skills)
52
- @tools = skills.empty? ? tools : tools + [Skills.reader(skills)]
53
- @tools_by_name = @tools.to_h { |tool| [tool.name, tool] }
54
- raise ConfigurationError, "duplicate tool names" if @tools_by_name.length != @tools.length
55
-
56
- @tool_specs, @external_tool_validators = compile_tool_contracts
65
+ scratchpad = Scratchpad.new(scratchpad) if scratchpad && !scratchpad.is_a?(Scratchpad)
66
+ @scratchpad = scratchpad
67
+ @documents = documents(files, scratchpad&.workspace)
68
+ @result_limit = result_limit || nil
69
+ install_tools(with_own_tools(tools, skills, sandbox))
57
70
 
58
71
  @budget = budget || Budget.new
59
72
  @budget.validate_provider!(@provider)
60
73
  @max_concurrency = max_concurrency
61
74
  @transform_context = Array(transform_context)
62
75
  @compaction = compaction || nil
76
+ @budget.validate_provider!(@compaction.fallback) if @compaction&.fallback
63
77
  @retries = retries || nil
64
78
  @before_tool = before_tool
65
79
  @after_tool = after_tool
66
80
  @context = context
67
81
  @log_label = log_label
68
- @log_depth = 0
82
+ @lease = lease
69
83
  end
70
84
 
71
85
  attr_reader :session
@@ -79,19 +93,10 @@ module Mistri
79
93
  def run(input, images: [], signal: nil, output_schema: nil, &emit)
80
94
  # The frame covers the whole public method, so an audit rejection or
81
95
  # a store failure gets a crash line too, not just loop failures.
82
- logged(emit, verb: "run", input: input) do |subscriber|
83
- if refresh_tool_control.any?
84
- raise ConfigurationError,
85
- "session is awaiting approvals; call resume"
86
- end
87
- if input.to_s.empty? && Array(images).empty?
88
- raise ArgumentError,
89
- "run needs input text or images"
96
+ exclusive do
97
+ logged(emit, verb: "run", input: input) do |subscriber|
98
+ exchange(input, images:, signal:, output_schema:, &subscriber)
90
99
  end
91
-
92
- fold_inbox # anything queued while this session sat idle arrived first; keep that order
93
- @session.append_message(Message.user_with_images(input, images))
94
- loop_turns(signal, output_schema, &subscriber)
95
100
  end
96
101
  end
97
102
 
@@ -101,26 +106,28 @@ module Mistri
101
106
  # carries on as if it never stopped, unless a settled call's tool ends
102
107
  # the turn, in which case its execution was the run's last word.
103
108
  def resume(signal: nil, &emit)
104
- logged(emit, verb: "resume") do |subscriber|
105
- open = refresh_tool_control
106
- pending = open.select { |approval| approval[:decision].nil? }
107
- if pending.any?
108
- next Result.new(message: nil, status: :awaiting_approval,
109
- pending: pending.map { |approval| approval[:call] },
110
- usage: Usage.zero)
111
- end
109
+ exclusive do
110
+ logged(emit, verb: "resume") do |subscriber|
111
+ open = refresh_tool_control
112
+ pending = open.select { |approval| approval[:decision].nil? }
113
+ if pending.any?
114
+ next Result.new(message: nil, status: :awaiting_approval,
115
+ pending: pending.map { |approval| approval[:call] },
116
+ usage: Usage.zero)
117
+ end
112
118
 
113
- executed = settle(open, signal, &subscriber)
114
- if signal&.aborted?
115
- last = @session.messages.reverse_each.find(&:assistant?)
116
- next finished(last, Usage.zero, signal)
117
- end
118
- if executed.any? { |call| ends_turn?(call) }
119
- last = @session.messages.reverse_each.find(&:assistant?)
120
- next finished(last, Usage.zero, signal, handed_off: true)
121
- end
119
+ executed = settle(open, signal, &subscriber)
120
+ if signal&.aborted?
121
+ last = @session.messages.reverse_each.find(&:assistant?)
122
+ next finished(last, Usage.zero, signal)
123
+ end
124
+ if executed.any? { |call| ends_turn?(call) }
125
+ last = @session.messages.reverse_each.find(&:assistant?)
126
+ next finished(last, Usage.zero, signal, handed_off: true)
127
+ end
122
128
 
123
- loop_turns(signal, nil, &subscriber)
129
+ loop_turns(signal, nil, &subscriber)
130
+ end
124
131
  end
125
132
  end
126
133
 
@@ -136,38 +143,284 @@ module Mistri
136
143
  # belongs to whoever answers, and re-prompting for JSON would steal it
137
144
  # back. Ask again once the answer arrives.
138
145
  def task(input, schema:, images: [], signal: nil, fixes: 1, &emit)
139
- # One log frame for the whole task, fix passes included: the inner
140
- # runs see the frame open and only tee, so the single done line
141
- # reports the validated outcome, not a rejected intermediate answer.
142
- logged(emit, verb: "task", input: input) do |subscriber|
143
- plan = Schema.task_plan(schema)
144
- validated_task(input, plan, images, signal, fixes, &subscriber)
146
+ # One log frame, so the done line reports the validated outcome.
147
+ exclusive do
148
+ logged(emit, verb: "task", input: input) do |subscriber|
149
+ plan = Schema.task_plan(schema)
150
+ validated_task(input, plan, images, signal, fixes, &subscriber)
151
+ end
145
152
  end
146
153
  end
147
154
 
148
- # How full the context is: {tokens:, window:, fraction:}. Hosts render
149
- # meters and near-limit warnings from this; window is nil for models the
150
- # catalog does not know unless Compaction#window supplies one.
151
- def context_usage
152
- tokens = @session.context_tokens
155
+ # How full the context is: {tokens:, window:, fraction:, estimated:,
156
+ # threshold:, remaining:}. Hosts render meters and near-limit warnings
157
+ # from this; window is nil for models the catalog does not know unless
158
+ # Compaction#window supplies one. estimated is how many of the tokens are
159
+ # the gem's estimate: zero when the number is the provider's own, as it
160
+ # is after each answer. threshold is the level where a compaction starts
161
+ # and remaining the tokens left until it, both nil when nothing starts
162
+ # one. count: true asks the provider to count the next request, which
163
+ # takes one round trip; when it cannot, the estimate stands.
164
+ def context_usage(count: false)
165
+ level = @session.context_level(provider: estimator)
166
+ counted = count_context if count
167
+ tokens = counted || level.tokens
153
168
  window = context_window
154
- { tokens: tokens, window: window,
155
- fraction: window && (tokens.to_f / window).round(3) }
169
+ threshold = compaction_threshold
170
+ { tokens: tokens, window: window, fraction: window && (tokens.to_f / window).round(3),
171
+ estimated: counted ? 0 : level.estimated, threshold: threshold,
172
+ remaining: threshold && [threshold - tokens, 0].max }
156
173
  end
157
174
 
158
175
  # Compact now (a UI button, a pre-flight trim before a big task). Returns
159
176
  # the Compactor result, or nil when there is nothing worth compacting.
160
- def compact(&)
161
- Compactor.call(session: @session, provider: @provider,
162
- settings: @compaction || Compaction.new, &)
177
+ # instructions is a focus for this one summary.
178
+ def compact(instructions: nil, &)
179
+ exclusive do
180
+ Compactor.call(session: @session, provider: @provider, budget: @budget,
181
+ settings: @compaction || Compaction.new, request: method(:request_for),
182
+ instructions:, &)
183
+ end
163
184
  end
164
185
 
165
186
  private
166
187
 
188
+ def documents(files, scratchpad)
189
+ return files || scratchpad if files.nil? || scratchpad.nil? || files.equal?(scratchpad)
190
+
191
+ Workspace::PathSpace.new(files:, scratchpad:)
192
+ end
193
+
194
+ def with_own_tools(tools, skills, sandbox)
195
+ tools += [Skills.reader(skills)] unless skills.empty?
196
+ own_files = @documents && tools.none? { |tool| tool.name == "read_file" }
197
+ tools += Tools.files(@documents) if own_files
198
+ return tools unless sandbox
199
+
200
+ tools + [Tools.run_code(sandbox, limited: !@result_limit.nil?, &method(:from_code))]
201
+ end
202
+
203
+ FILES_FROM_CODE = { "read" => "read_file", "write" => "write_file", "list" => "list_files",
204
+ "delete" => "delete_file" }.freeze
205
+ SHORT_COPY = ResultLimit.new(bytes: ResultLimit::SHOWN_BYTES)
206
+ MAX_STORED_CODE_CALLS = 100
207
+ # An edit can grow a document by far more than the text it is given, so
208
+ # a run's budget for writes could not count it.
209
+ EDIT_FROM_CODE = "edit_file is not called from code. Read the document with files.read, " \
210
+ "change the text in the code and write it with files.write."
211
+ private_constant :FILES_FROM_CODE, :SHORT_COPY, :MAX_STORED_CODE_CALLS, :EDIT_FROM_CODE
212
+
213
+ def from_code(operation, payload, context, run)
214
+ raise Error, "the run was stopped" if context.signal&.aborted?
215
+ return tool_from_code(payload, context, run) if operation == "tool"
216
+
217
+ name = FILES_FROM_CODE[operation]
218
+ raise Error, "the code asked for #{operation}, which does not exist" unless name
219
+
220
+ workspace = documents_of(name, operation)
221
+ call = ToolCall.new(id: "code_#{SecureRandom.hex(8)}", name:,
222
+ arguments: payload.slice("path", "prefix", "content").compact)
223
+ call, refusal = prepare_call(call, normalize: true, signal: context.signal)
224
+ settle_from_code(call, context, run, refusal:) do
225
+ file_from_code(workspace, operation, call, context, run)
226
+ end
227
+ end
228
+
229
+ # files in code is the built-in document tool of the same kind, on the
230
+ # workspace that tool is bound to. A host's own tool of that name has a
231
+ # handler of its own, so code reaches it only as a tool.
232
+ def documents_of(name, operation)
233
+ tool = @tools_by_name[name]
234
+ raise Error, "you do not have the #{name} tool" unless tool
235
+
236
+ Tools.bound_workspace(tool) ||
237
+ raise(Error, "files.#{operation} is not available, because #{name} here is the " \
238
+ "host's own tool. Call tools.#{name} instead.")
239
+ end
240
+
241
+ # Code can pass megabytes to a call, in a loop, so the copy of a call that
242
+ # is stored and emitted keeps SHOWN_BYTES of its arguments. The largest
243
+ # give way first, so a path stays whole beside a document.
244
+ def short_copy(call)
245
+ arguments = call.arguments
246
+ limit = ResultLimit::SHOWN_BYTES
247
+ return call if ToolArguments.serialized_size_within_limit?(arguments, limit:)
248
+ return call.with(arguments: short_value(arguments, limit)) unless arguments.is_a?(Hash)
249
+
250
+ sizes = arguments.transform_values { |value| JSON.generate(value).bytesize }
251
+ short = sizes.sort_by(&:last).to_h do |key, size|
252
+ kept, used = short_argument(arguments[key], size, limit)
253
+ limit -= used
254
+ [key, kept]
255
+ end
256
+ call.with(arguments: arguments.to_h { |key, _value| [key, short[key]] })
257
+ end
258
+
259
+ def short_value(value, limit)
260
+ short_argument(value, JSON.generate(value).bytesize, limit).first
261
+ end
262
+
263
+ def short_argument(value, size, left)
264
+ return [value, size] if size <= left
265
+ return ["[#{size} bytes of JSON]", 0] unless value.is_a?(String)
266
+
267
+ start = value.byteslice(0, left).scrub("")
268
+ notice = "[cut at #{start.bytesize} of #{value.bytesize} bytes]"
269
+ [[start, notice].reject(&:empty?).join("\n"), left]
270
+ end
271
+
272
+ # A read gives after_tool the document, because that is what the code
273
+ # receives. It counts for a later write only when the code received the
274
+ # document itself, which the hook can refuse or rewrite.
275
+ def file_from_code(workspace, operation, call, context, run)
276
+ value, line = Tools.file_from_code(workspace, operation, call.arguments, run)
277
+ seen = operation == "read" ? value : line
278
+ text, result = @after_tool ? rewritten_from_code(call, seen, context) : [seen, nil]
279
+ return [nil, result] if result.is_a?(ToolResult) && result.error?
280
+
281
+ whole = text == seen
282
+ Tools.read_by_code(run, call.arguments["path"], value) if whole && operation == "read"
283
+ return [value, line] if whole
284
+
285
+ case operation
286
+ when "read" then [text, "Read #{call.arguments["path"]} (#{text.bytesize} bytes)"]
287
+ when "list" then [text.split("\n"), text]
288
+ else [value, text]
289
+ end
290
+ end
291
+
292
+ def tool_from_code(payload, context, run)
293
+ name = payload["name"].to_s
294
+ tool = @tools_by_name[name]
295
+ raise Error, "run_code cannot be called from code" if name == "run_code"
296
+ raise Error, EDIT_FROM_CODE if name == "edit_file" && Tools.bound_workspace(tool)
297
+
298
+ call = ToolCall.new(id: "code_#{SecureRandom.hex(8)}", name:, arguments: payload["arguments"])
299
+ call, refusal = prepare_call(call, normalize: true, signal: context.signal)
300
+ settle_from_code(call, context, run, refusal:) do
301
+ whole = context.with(result_limit: nil)
302
+ result = Tools.within_budget(run, tool, call.arguments) do
303
+ ToolExecutor.invoke_one(tool, call, whole).first
304
+ end
305
+ rewritten_from_code(call, result, context)
306
+ end
307
+ end
308
+
309
+ # A call from code is stored as an entry beside the messages, not as a
310
+ # message, because the model reads its result in the code.
311
+ def settle_from_code(call, context, run, refusal: nil, &)
312
+ refusal ||= refused_from_code(call, context)
313
+ call = short_copy(call)
314
+ value, result, seconds = refusal ? [nil, refusal, nil] : run_from_code(call, context, &)
315
+ content, ui, tool_error = if result.is_a?(ToolResult)
316
+ [result.content, result.ui, result.error?]
317
+ else
318
+ [result, nil, false]
319
+ end
320
+ text = ResultLimit.texts(content).join("\n")
321
+ content, cut = SHORT_COPY.bound(stored_form(content))
322
+ message = Message.tool(content:, tool_call_id: call.id, tool_name: call.name, ui:,
323
+ tool_error:, cut:)
324
+ store_from_code(run, call, message.with(ui: nil))
325
+ context.emit&.call(Event.new(type: :tool_result, tool_call: call, message:, tool_error:,
326
+ content: content.is_a?(String) ? content : "[content]",
327
+ duration: seconds))
328
+ raise Error, text if tool_error
329
+
330
+ value
331
+ end
332
+
333
+ # One run can make hundreds of thousands of calls, and a session reads
334
+ # every entry it holds, so a run stores its first hundred. Every call
335
+ # still emits its events, and only the event carries the result's ui,
336
+ # which can be a page.
337
+ def store_from_code(run, call, message)
338
+ run.calls += 1
339
+ return if run.calls > MAX_STORED_CODE_CALLS
340
+
341
+ @session.append("code_call", "call" => call.to_h, "message" => message.to_h)
342
+ end
343
+
344
+ def refused_from_code(call, context)
345
+ _cleared, blocked = screen([call], context.signal, &context.emit)
346
+ return blocked.first[1] if blocked.any?
347
+
348
+ reason = if gated?(call) then "needs a person's approval for this call"
349
+ elsif ends_turn?(call) then "ends your turn"
350
+ elsif call.name == ToolSearch::NAME then "loads tools into your own list"
351
+ end
352
+ return unless reason
353
+
354
+ ToolResult.new(content: "#{call.name} #{reason}, so code cannot make it. Call the tool " \
355
+ "yourself.", error: true)
356
+ rescue EventDelivery::Failure
357
+ raise
358
+ rescue StandardError => e
359
+ ToolResult.new(content: "Error evaluating approval policy for tool #{call.name.inspect}: " \
360
+ "#{e.class}: #{e.message}. The tool did not run.", error: true)
361
+ end
362
+
363
+ def run_from_code(call, context)
364
+ context.emit&.call(Event.new(type: :tool_started, tool_call: call))
365
+ started = monotonic_now
366
+ value, result = begin
367
+ yield
368
+ rescue EventDelivery::Failure
369
+ raise
370
+ rescue StandardError => e
371
+ [nil, ToolResult.new(content: e.message, error: true)]
372
+ end
373
+ [value, result, monotonic_now - started]
374
+ end
375
+
376
+ def rewritten_from_code(call, result, context)
377
+ result = rewrite(call, result, hook_context(context.signal, context.emit)) if @after_tool
378
+ content = stored_form(result.is_a?(ToolResult) ? result.content : result)
379
+ [ResultLimit.texts(content).join("\n"), result]
380
+ end
381
+
382
+ def install_tools(tools)
383
+ deferred = tools.select { |tool| tool.respond_to?(:deferred?) && tool.deferred? }
384
+ @loaded = []
385
+ search = ToolSearch.tool(deferred, loaded: -> { @loaded }) unless deferred.empty?
386
+ @tools = search ? tools + [search] : tools
387
+ @tools_by_name = by_name(@tools)
388
+
389
+ specs, @external_tool_validators = compile_tool_contracts
390
+ names = deferred.to_h { |tool| [tool.name, true] }
391
+ later, @eager_specs = specs.partition { |spec| names.key?(spec[:name]) }.map(&:freeze)
392
+ @deferred_specs = later.to_h { |spec| [spec[:name], spec] }.freeze
393
+ @defers_tools = @provider.respond_to?(:defers_tools?) && @provider.defers_tools?
394
+ end
395
+
396
+ def by_name(tools)
397
+ repeated = tools.map(&:name).tally.select { |_name, count| count > 1 }.keys
398
+ raise ConfigurationError, "duplicate tool names: #{repeated.join(", ")}" if repeated.any?
399
+
400
+ tools.to_h { |tool| [tool.name, tool] }
401
+ end
402
+
403
+ # run's body outside the lease; task's fix passes share task's lease.
404
+ def exchange(input, signal:, output_schema:, images: [], &emit)
405
+ if refresh_tool_control.any?
406
+ raise ConfigurationError,
407
+ "session is awaiting approvals; call resume"
408
+ end
409
+ input = nil if input.to_s.match?(/\A[[:space:]]*\z/)
410
+ if input.nil? && Array(images).empty?
411
+ raise ArgumentError,
412
+ "run needs input text or images"
413
+ end
414
+
415
+ fold_inbox # anything queued while this session sat idle arrived first; keep that order
416
+ @session.append_message(Message.user_with_images(input, images))
417
+ loop_turns(signal, output_schema, &emit)
418
+ end
419
+
167
420
  # The body of task, extracted so its early returns close the log frame
168
421
  # instead of skipping it.
169
422
  def validated_task(input, plan, images, signal, fixes, &emit)
170
- result = run(
423
+ result = exchange(
171
424
  TaskOutput.prompt(input, plan), images:, signal:, output_schema: plan, &emit
172
425
  )
173
426
  spent = result.usage
@@ -181,51 +434,64 @@ module Mistri
181
434
  return result.with(output: value) if errors.empty?
182
435
  raise SchemaError, "task output failed validation: #{errors.join("; ")}" if remaining.zero?
183
436
 
184
- result = run(TaskOutput.fix_prompt(errors), signal:, output_schema: plan, &emit)
437
+ result = exchange(TaskOutput.fix_prompt(errors), signal:, output_schema: plan, &emit)
185
438
  spent += result.usage
186
439
  end
187
440
  end
188
441
 
189
- # When a host sets Mistri.logger, every public run tees its events into
190
- # a fresh logging sink for this session alongside the caller's block,
191
- # and the framing lines carry what the stream cannot: the input, the
192
- # model, and the final Result. Nothing wraps when no logger is set, a
193
- # nested public call (task's inner runs) reuses the open frame, and a
194
- # caller's subscriber failures propagate exactly as before because the
195
- # sink never raises.
442
+ # Concurrent runners interleave appends; without an adapter the host serializes them.
443
+ def exclusive
444
+ lease = session_lease
445
+ yield
446
+ ensure
447
+ release(lease) if lease
448
+ end
449
+
450
+ # One lease per session: a child's runner holds this key for the agent it builds.
451
+ def session_lease
452
+ return unless @lease && Mistri.locks
453
+
454
+ lease = Locks.hold(Child.lease_key(@session.id))
455
+ rescue StandardError => e
456
+ warn "mistri: the lock backend failed (#{e.class}: #{e.message}); " \
457
+ "session #{@session.id} runs without its lease"
458
+ else
459
+ lease || raise(SessionBusyError.new("session #{@session.id} has an active runner",
460
+ session_id: @session.id))
461
+ end
462
+
463
+ # Never mask the run's outcome; an unreleased lease expires on its own.
464
+ def release(lease)
465
+ lease.release
466
+ rescue StandardError => e
467
+ warn "mistri: releasing the lease for session #{@session.id} failed " \
468
+ "(#{e.class}: #{e.message}); it expires on its own"
469
+ end
470
+
471
+ # With Mistri.logger set, tees events into a session log framed by the input,
472
+ # model, and Result. The sink never raises, so subscriber failures propagate unchanged.
196
473
  def logged(emit, verb:, input: nil)
197
- sink = log_sink
474
+ sink = Sinks::Logger.attach(@session.id, label: @log_label)
198
475
  return yield(emit) unless sink
199
476
 
200
- @log_depth += 1
477
+ sink.run_started(verb: verb, input: input, model: @provider.model,
478
+ tool_count: @tools.length)
479
+ subscriber = if emit
480
+ lambda { |event|
481
+ sink.call(event)
482
+ emit.call(event)
483
+ }
484
+ else
485
+ sink.to_proc
486
+ end
201
487
  begin
202
- sink.run_started(verb: verb, input: input, model: @provider.model,
203
- tool_count: @tools.length)
204
- subscriber = if emit
205
- lambda { |event|
206
- sink.call(event)
207
- emit.call(event)
208
- }
209
- else
210
- sink.to_proc
211
- end
212
- begin
213
- result = yield(subscriber)
214
- rescue StandardError => e
215
- sink.run_crashed(EventDelivery.original(e))
216
- raise
217
- end
218
- sink.run_finished(result)
219
- result
220
- ensure
221
- @log_depth -= 1
488
+ result = yield(subscriber)
489
+ rescue StandardError => e
490
+ sink.run_crashed(EventDelivery.original(e))
491
+ raise
222
492
  end
223
- end
224
-
225
- def log_sink
226
- return nil if @log_depth.positive?
227
-
228
- Sinks::Logger.attach(@session.id, label: @log_label)
493
+ sink.run_finished(result)
494
+ result
229
495
  end
230
496
 
231
497
  def loop_turns(signal, output_schema = nil, &emit)
@@ -245,7 +511,7 @@ module Mistri
245
511
  reason = @budget.exceeded(turns:, usage:, elapsed: monotonic_now - started)
246
512
  return stop_for_budget(reason, usage, &emit) if reason
247
513
  end
248
- last, turn_usage = run_turn(signal, output_schema, &emit)
514
+ last, turn_usage, said = run_turn(signal, output_schema, &emit)
249
515
  turns += 1
250
516
  usage += turn_usage
251
517
 
@@ -253,7 +519,10 @@ module Mistri
253
519
  # transcript is unpairable and replay fails.
254
520
  parked, ended = last.tool_calls? ? run_tools(last, signal, &emit) : [[], false]
255
521
  return suspended(last, parked, usage) if parked.any?
256
- return finished(last, usage, signal, handed_off: ended) if ended || done?(last, signal)
522
+ next unless ended || done?(last, signal)
523
+
524
+ said = nil unless last.stop_reason == StopReason::STOP && last.text.to_s.strip.empty?
525
+ return finished(last, usage, signal, handed_off: ended, said:)
257
526
  end
258
527
  end
259
528
 
@@ -268,22 +537,73 @@ module Mistri
268
537
  @session.pending_inbox.empty?
269
538
  end
270
539
 
271
- # Compact when the context has grown into the reserve. A failed
272
- # summarization skips quietly here: if the context genuinely no longer
273
- # fits, the next turn surfaces the real provider error.
540
+ # Compact when the level has passed the threshold. A failed
541
+ # summarization is recorded on the session and skipped here; after
542
+ # AUTOMATIC_ATTEMPTS automatic failures in a row the loop stops paying
543
+ # for a full-context request every turn, and a turn the provider then
544
+ # refuses as too long gets its one compaction in run_turn. The session
545
+ # is read again only once the level could be over the threshold, so an
546
+ # ordinary turn costs one history read, and the provider is asked for a
547
+ # count only when a compaction could start.
274
548
  def auto_compact(&)
275
549
  return nil unless @compaction
276
550
 
277
- tokens = @session.context_tokens
278
- return nil unless @compaction.needed?(tokens, context_window,
279
- max_output: Models.shared_output(@provider.model))
551
+ threshold = compaction_threshold
552
+ level = threshold && @session.context_level(provider: estimator)
553
+ return nil unless level && near_threshold?(level, threshold)
554
+ return nil unless @session.grown_since_compaction?
555
+ return nil if automatic_compaction_exhausted?
556
+ return nil unless compaction_due?(level, threshold)
280
557
 
281
558
  compact_automatically(&)
282
559
  end
283
560
 
284
- def compact_automatically(&emit)
561
+ def compaction_threshold
562
+ @compaction&.threshold_tokens(context_window,
563
+ max_output: Models.shared_output(@provider.model))
564
+ end
565
+
566
+ # True where the estimated part of the level could carry it over the
567
+ # threshold.
568
+ def near_threshold?(level, threshold)
569
+ level.reported + (Compaction::ESTIMATE_SPREAD * level.estimated) > threshold
570
+ end
571
+
572
+ # A compaction starts on the provider's numbers. Where the reported part
573
+ # of a level near the threshold is under it, the provider counts the
574
+ # request, and the count decides.
575
+ def compaction_due?(level, threshold)
576
+ level.reported > threshold || (count_context || level.tokens) > threshold
577
+ end
578
+
579
+ # Whose rule estimates what no turn has reported: the provider the next
580
+ # request goes to.
581
+ def estimator = Models.find(@provider.model)&.provider
582
+
583
+ # The arguments of the stream call a turn would make for these messages.
584
+ def request_for(messages)
585
+ history = @transform_context.reduce(messages) { |held, transform| transform.call(held) }
586
+ history = Reminder.as_user_turns(history) unless system_messages?
587
+ { messages: history, system: @system, **tool_options(history) }
588
+ end
589
+
590
+ # The provider's count of the request the next turn would send. Nil when
591
+ # it cannot be had, as from inside a subscriber of a running stream.
592
+ def count_context
593
+ Compaction.count(@provider, request_for(@session.messages))
594
+ rescue ThreadError
595
+ nil
596
+ end
597
+
598
+ def automatic_compaction_exhausted?(trigger = :automatic)
599
+ @session.compaction_failures(trigger:) >= Compaction::AUTOMATIC_ATTEMPTS
600
+ end
601
+
602
+ def compact_automatically(trigger: :automatic, &emit)
285
603
  delivery = EventDelivery.wrap(emit)
286
- Compactor.call(session: @session, provider: @provider, settings: @compaction, &delivery)
604
+ Compactor.call(session: @session, provider: @provider, settings: @compaction,
605
+ trigger:, budget: @budget, request: method(:request_for),
606
+ &delivery)
287
607
  rescue EventDelivery::Failure => e
288
608
  raise EventDelivery.unwrap(e, delivery)
289
609
  rescue CompactionError => e
@@ -317,38 +637,186 @@ module Mistri
317
637
  # (:done or :error) holds at a gate, so retries stay invisible to the
318
638
  # model and a recovered retry never shows the subscriber an error it
319
639
  # walks back. Only the accepted attempt persists and terminates.
640
+ #
641
+ # A turn the provider refuses as longer than the model's window gets one
642
+ # compaction and is sent again, once in a turn.
320
643
  def run_turn(signal, output_schema = nil, &emit)
321
- history = @transform_context.reduce(@session.messages) do |messages, transform|
322
- transform.call(messages)
323
- end
644
+ replayed = @session.messages
645
+ said = said_since_user(replayed)
646
+ history = history_of(replayed)
324
647
  attempt = 0
325
648
  usage = Usage.zero
326
649
  schema = provider_output_schema(output_schema)
650
+ shortened = nil
327
651
  loop do
328
652
  held = nil
329
653
  gate = emit && ->(event) { event.terminal? ? held = event : emit.call(event) }
330
654
  message = @provider.stream(messages: history, system: @system,
331
- tools: @tool_specs, signal: signal,
655
+ **tool_options(history), signal: signal,
332
656
  output_schema: schema, &gate)
333
657
  message, held = enforce_tool_call_envelope(message, held)
334
658
  attempt_usage = message.usage || Usage.new
335
659
  validate_usage!(attempt_usage, message:, kind: "turn", &emit)
336
660
  usage += attempt_usage
337
661
  attempt += 1
338
- error = @retries&.error_for(message)
662
+ error = attempt_error(message, said)
339
663
  if retry_turn?(error, attempt, signal)
340
664
  pause = @retries.delay(attempt, error["retry_after"])
341
665
  record_retry(message, error, attempt, pause, &emit)
342
666
  wait(pause, signal)
343
667
  next unless signal&.aborted?
344
668
  end
669
+ if (shortened = shortened ? nil : shorten_after_refusal(message, attempt, &emit))
670
+ usage += shortened[:usage]
671
+ next history = history_of(@session.messages) if shortened[:tokens_after]
672
+ end
345
673
  emit&.call(held) if held
346
674
  @session.append_message(message)
347
675
  reserve_tool_call_ids(message.tool_calls)
348
- return [message, usage]
676
+ return [message, usage, said]
677
+ end
678
+ end
679
+
680
+ def history_of(replayed)
681
+ history = noting_scratchpad(sending_instructions(listing_deferred_tools(replayed)))
682
+ history = @transform_context.reduce(history) do |messages, transform|
683
+ transform.call(messages)
684
+ end
685
+ system_messages? ? history : Reminder.as_user_turns(history)
686
+ end
687
+
688
+ # The provider refused the turn as longer than the model's window, so the
689
+ # level the gem held was too low or the window is another model's. One
690
+ # compaction, whatever the level says. The refused attempt is recorded
691
+ # as a retry, as any attempt that is thrown away. Nil when the refusal
692
+ # is another one or nothing can be compacted; a failed compaction returns
693
+ # its usage alone, and the refusal stands.
694
+ def shorten_after_refusal(message, attempt, &)
695
+ return nil unless @compaction && ErrorData.too_long?(message.error)
696
+ return nil if automatic_compaction_exhausted?(:overflow)
697
+
698
+ compacted = compact_automatically(trigger: :overflow, &)
699
+ return nil unless compacted
700
+
701
+ compacted = compacted.merge(usage: compacted[:usage] || Usage.new)
702
+ validate_usage!(compacted[:usage], kind: "compaction", &)
703
+ record_retry(message, message.error, attempt, 0.0, &) if compacted[:tokens_after]
704
+ compacted
705
+ end
706
+
707
+ # A provider that does not state that it takes a system message in a
708
+ # conversation is given each reminder as text of a user turn.
709
+ def system_messages?
710
+ @provider.respond_to?(:system_messages?) && @provider.system_messages?
711
+ end
712
+
713
+ # The list goes into the conversation, not into a definition, so the tools
714
+ # and the system prompt of a request are unchanged by what a host connects.
715
+ # An agent without deferred tools appends nothing, unless the conversation
716
+ # holds a list from an agent that had some.
717
+ def listing_deferred_tools(messages)
718
+ @listing ||= Message.reminder("deferred_tools", ToolSearch.listing(@deferred_specs.keys))
719
+ latest = messages.reverse_each.find { |message| message.reminder == @listing.reminder }
720
+ return messages if latest == @listing || (latest.nil? && @deferred_specs.empty?)
721
+
722
+ messages + [@session.append_message(@listing)]
723
+ end
724
+
725
+ # The instructions of each tool's server go into the conversation before
726
+ # the model chooses among its tools, so they can guide the choice. They
727
+ # are owed while no reminder in the conversation holds them, so a
728
+ # compaction and a load whose result failed afterwards lose nothing.
729
+ def sending_instructions(messages)
730
+ owed = owed_instructions(messages)
731
+ return messages if owed.empty?
732
+
733
+ messages + owed.group_by { |text| @instruction_kinds.fetch(text) }.map do |kind, texts|
734
+ @session.append_message(Message.reminder(kind, *texts))
735
+ end
736
+ end
737
+
738
+ # The note is owed while the conversation holds none, so a compaction that
739
+ # summarized it brings it back with what the scratchpad holds by then.
740
+ def noting_scratchpad(messages)
741
+ return messages unless @scratchpad
742
+ return messages if messages.any? { |message| message.reminder == "scratchpad" }
743
+
744
+ messages + [@session.append_message(Message.reminder("scratchpad", @scratchpad.note))]
745
+ end
746
+
747
+ # Each server's instructions that no reminder in the conversation holds
748
+ # as one of its text blocks. Every server is due at once. When that is
749
+ # more than INSTRUCTIONS_TOGETHER_BYTES, a server with only deferred
750
+ # tools is due once one of its tools is loaded.
751
+ def owed_instructions(messages)
752
+ due = tool_instructions
753
+ return [] if due.empty?
754
+
755
+ if due.keys.sum(&:bytesize) > INSTRUCTIONS_TOGETHER_BYTES
756
+ held = (@tools_by_name.keys - @deferred_specs.keys) | loaded_names(messages)
757
+ due = due.select { |_text, names| names.intersect?(held) }
758
+ end
759
+ sent = messages.select { |message| INSTRUCTION_KINDS.value?(message.reminder) }
760
+ .flat_map { |message| message.content.grep(Content::Text).map(&:text) }
761
+ due.keys - sent
762
+ end
763
+
764
+ # Each distinct instructions text, under each weight it was given, as
765
+ # the text block the model reads, with the names of the tools that carry
766
+ # it. One block that tools of both weights carry is sent once, with the
767
+ # weight of a user turn, which trusts the server less.
768
+ def tool_instructions
769
+ @tool_instructions ||= begin
770
+ @instruction_kinds = {}
771
+ carried = @tools.select { |tool| tool.respond_to?(:instructions) }
772
+ .group_by { |tool| [tool.instructions.to_s.strip, weight_of(tool)] }
773
+ .reject { |(text, _weight), _tools| text.empty? }
774
+ carried.each_with_object({}) do |((text, weight), tools), blocks|
775
+ names = tools.map(&:name)
776
+ block = "The server of #{instructed(names)} gives these instructions for using " \
777
+ "its tools:\n#{bounded_instructions(text)}"
778
+ @instruction_kinds[block] = INSTRUCTION_KINDS.fetch(blocks.key?(block) ? :user : weight)
779
+ (blocks[block] ||= []).concat(names)
780
+ end
349
781
  end
350
782
  end
351
783
 
784
+ # A tool that is not the gem's own may carry instructions and no weight.
785
+ def weight_of(tool)
786
+ tool.respond_to?(:instructions_as) ? tool.instructions_as : :system
787
+ end
788
+
789
+ # Each server's tools by their prefix, and a tool without one by its name.
790
+ def instructed(names)
791
+ names.map { |name| name.include?("__") ? "#{name.split("__", 2).first}__*" : name }
792
+ .uniq.join(", ")
793
+ end
794
+
795
+ def bounded_instructions(text)
796
+ return text if text.bytesize <= INSTRUCTIONS_BYTES
797
+
798
+ "#{text.byteslice(0, INSTRUCTIONS_BYTES).scrub("")}\n" \
799
+ "[cut at #{INSTRUCTIONS_BYTES} of #{text.bytesize} bytes]"
800
+ end
801
+
802
+ def loaded_names(history)
803
+ history.reject(&:tool_error?).flat_map { |message| message.loads.to_a }.uniq
804
+ end
805
+
806
+ # A deferred tool is loaded once a tool result in the history has loaded
807
+ # it. A provider that defers natively receives the loaded definitions
808
+ # separately, in load order, and marks the loading result in its own wire
809
+ # form. Any other provider receives them after the eager tools.
810
+ def tool_options(history)
811
+ return { tools: @eager_specs } if @deferred_specs.empty?
812
+
813
+ @loaded = loaded_names(history)
814
+ loaded = @deferred_specs.values_at(*@loaded).compact
815
+ return { tools: @eager_specs, deferred_tools: loaded } if @defers_tools
816
+
817
+ { tools: @eager_specs + loaded }
818
+ end
819
+
352
820
  def provider_output_schema(output_schema)
353
821
  return output_schema unless output_schema.respond_to?(:native_fallback?)
354
822
  return output_schema.schema unless @provider.respond_to?(:native_output_schema)
@@ -356,6 +824,21 @@ module Mistri
356
824
  @provider.native_output_schema(output_schema.schema)
357
825
  end
358
826
 
827
+ # Once the model has written to the user in this exchange, an empty
828
+ # completion is its end of turn: the same request answers the same way.
829
+ def attempt_error(message, said)
830
+ error = @retries&.error_for(message)
831
+ error unless said && error.equal?(RetryPolicy::EMPTY_COMPLETION)
832
+ end
833
+
834
+ def said_since_user(messages)
835
+ messages.reverse_each do |message|
836
+ return nil if message.user?
837
+ return message.text if message.assistant? && !message.text.to_s.strip.empty?
838
+ end
839
+ nil
840
+ end
841
+
359
842
  def retry_turn?(error, attempt, signal)
360
843
  return false unless @retries && error
361
844
  return false if signal&.aborted?
@@ -367,10 +850,11 @@ module Mistri
367
850
  entry = { "attempt" => attempt, "error" => error, "delay" => pause.round(2) }
368
851
  entry["usage"] = (message.usage || Usage.new).to_h
369
852
  @session.append("retry", entry)
370
- note = format("attempt %<attempt>d failed; retrying in %<pause>.1fs",
371
- attempt: attempt, pause: pause)
853
+ reason = [error["type"], error["status"]].compact.join(" ")
854
+ note = format("attempt %<attempt>d failed (%<reason>s); retrying in %<pause>.1fs",
855
+ attempt: attempt, reason: reason, pause: pause)
372
856
  emit&.call(Event.new(type: :retry, content: note, attempt: attempt,
373
- max_attempts: @retries.attempts, delay: pause.round(2),
857
+ max_attempts: @retries&.attempts, delay: pause.round(2),
374
858
  message: message))
375
859
  end
376
860
 
@@ -396,13 +880,13 @@ module Mistri
396
880
  sleep(0.1) while monotonic_now < deadline && !signal&.aborted?
397
881
  end
398
882
 
399
- # Answer or park the assistant's tool calls. Ungated calls execute (only
400
- # on a genuine tool_use turn with no abort; otherwise they pair with
401
- # interrupted results). Gated calls park as approval requests. Nothing
402
- # is left dangling either way. Returns the parked calls and whether an
403
- # executed tool ends the turn; a parked call outranks an executed
404
- # ends_turn, because a suspension is the stronger stop and the model
405
- # regains the floor when the run resumes.
883
+ # Answer or park the assistant's tool calls, in the order written. A call
884
+ # runs, parks as an approval request, or is answered as not run (only on
885
+ # a genuine tool_use turn with no abort; otherwise every call pairs with
886
+ # an interrupted result). Nothing is left dangling either way. Returns
887
+ # the parked calls and whether an executed tool ends the turn; a parked
888
+ # call outranks an executed ends_turn, because a suspension is the
889
+ # stronger stop and the model regains the floor when the run resumes.
406
890
  def run_tools(assistant, signal, &emit)
407
891
  calls = assistant.tool_calls
408
892
  unless assistant.stop_reason == StopReason::TOOL_USE && !signal&.aborted?
@@ -420,17 +904,23 @@ module Mistri
420
904
 
421
905
  def complete_tool_batch(source_calls, prepared, batch, signal, provider:, &emit)
422
906
  batch = protect_gemini_result_order(prepared, batch) if provider == :gemini
423
- invalid, blocked, parked, free, rejected = batch
424
- executed = execute(free, signal, &emit)
907
+ invalid, blocked, parked, _free, rejected = batch
908
+ refused = [*invalid, *blocked, *rejected]
909
+ among = prepared.length - parked.length
910
+ ran = CallOrder.new(@tools_by_name).run(prepared, refused:, parked:, signal:) do |step|
911
+ execute(step, signal, among:, &emit)
912
+ end
913
+ executed = ran.executed
914
+ unrun = [*refused, *ran.skipped]
915
+ parked = ran.parked
425
916
  if signal&.aborted?
426
- uncommitted = [*invalid, *blocked, *rejected].map(&:first) + parked
917
+ uncommitted = unrun.map(&:first) + parked
427
918
  results = [*executed, *interrupted_results(uncommitted)]
428
919
  answer_results(prepared, results, executed:, signal:, &emit)
429
920
  return [[], executed_ends_turn?(executed)]
430
921
  end
431
922
 
432
- answer_results(prepared, [*invalid, *blocked, *rejected, *executed],
433
- executed:, signal:, &emit)
923
+ answer_results(prepared, [*unrun, *executed], executed:, signal:, &emit)
434
924
  if signal&.aborted?
435
925
  answer_results(prepared, interrupted_results(parked),
436
926
  executed: [], signal:, &emit)
@@ -454,47 +944,66 @@ module Mistri
454
944
 
455
945
  # Before Gemini 3, same-name parallel calls may have no wire IDs and only
456
946
  # order pairs their responses. A later immediate result cannot pass an
457
- # earlier parked result without becoming ambiguous.
947
+ # earlier parked result without becoming ambiguous, and every call that
948
+ # does not wait is answered at once. Failing one waiting call changes
949
+ # which others wait, so the check repeats until none is passed.
458
950
  def protect_gemini_result_order(prepared, batch)
459
951
  invalid, blocked, parked, free, rejected = batch
460
- positions = prepared.each_with_index.to_h { |call, index| [call.id, index] }
461
- immediate = [*invalid, *blocked, *rejected].map(&:first) + free
462
- unsafe, safe = parked.partition do |parked_call|
463
- parked_call.provider_call_id.nil? && immediate.any? do |call|
464
- call.provider_call_id.nil? && call.name == parked_call.name &&
465
- positions.fetch(call.id) > positions.fetch(parked_call.id)
466
- end
952
+ loop do
953
+ waiting = CallOrder.new(@tools_by_name)
954
+ .waiting(prepared, refused: [*invalid, *blocked, *rejected], parked:)
955
+ unsafe = waiting.select { |call| passed_by_a_later_result?(call, prepared, waiting) }
956
+ return [invalid, blocked, parked, free, rejected] if unsafe.empty?
957
+
958
+ parked = parked.reject { |call| unsafe.any? { |other| other.equal?(call) } }
959
+ rejected += unsafe.map { |call| [call, gemini_order_failure, nil] }
467
960
  end
468
- failures = unsafe.map do |call|
469
- content = "Gemini returned parallel same-name calls without IDs across an approval " \
470
- "boundary. This tool did not run; retry those calls separately."
471
- [call, ToolResult.new(content:, error: true), nil]
961
+ end
962
+
963
+ def gemini_order_failure
964
+ content = "Gemini returned parallel same-name calls without IDs across an approval " \
965
+ "boundary. This tool did not run; retry those calls separately."
966
+ ToolResult.new(content:, error: true)
967
+ end
968
+
969
+ def passed_by_a_later_result?(waiting_call, prepared, waiting)
970
+ return false if waiting_call.provider_call_id
971
+
972
+ later = prepared.drop_while { |call| !call.equal?(waiting_call) }.drop(1)
973
+ later.any? do |call|
974
+ call.provider_call_id.nil? && call.name == waiting_call.name &&
975
+ waiting.none? { |other| other.equal?(call) }
472
976
  end
473
- [invalid, blocked, safe, free, [*rejected, *failures]]
474
977
  end
475
978
 
476
979
  # Returns the calls that actually executed (denied ones only answer).
477
980
  def settle(open, signal, &)
478
981
  approved, denied = open.partition { |approval| approval[:decision]["approved"] }
479
982
  approved_calls = approved.map { |approval| approval[:call] }
480
- _prepared, valid, invalid = prepare_calls(
983
+ prepared, valid, invalid = prepare_calls(
481
984
  approved_calls, normalize: false, signal:
482
985
  )
483
986
  return interrupt_settlement(open, approved_calls, denied, signal, &) if signal&.aborted?
484
987
 
485
- cleared, blocked = screen(valid, signal, &)
988
+ _cleared, blocked = screen(valid, signal, &)
486
989
  return interrupt_settlement(open, approved_calls, denied, signal, &) if signal&.aborted?
487
990
 
488
- executed = execute(cleared, signal, &)
991
+ spent = stored_for_turn
489
992
  denials = denial_results(denied)
993
+ ready = prepared.each
994
+ calls = open.map { |approval| approval[:decision]["approved"] ? ready.next : approval[:call] }
995
+ ran = CallOrder.new(@tools_by_name)
996
+ .run(calls, refused: [*invalid, *blocked], denied: denials, signal:) do |step|
997
+ execute(step, signal, among: open.length, spent:, &)
998
+ end
999
+ executed = ran.executed
1000
+ unrun = [*invalid, *blocked, *ran.skipped]
490
1001
  results = if signal&.aborted?
491
- uncommitted = [*invalid, *blocked].map(&:first)
492
- [*executed, *interrupted_results(uncommitted), *denials]
1002
+ [*executed, *interrupted_results(unrun.map(&:first)), *denials]
493
1003
  else
494
- [*invalid, *blocked, *executed, *denials]
1004
+ [*unrun, *executed, *denials]
495
1005
  end
496
- answer_results(open.map { |approval| approval[:call] },
497
- results, executed:, signal:, &)
1006
+ answer_results(calls, results, executed:, signal:, spent:, &)
498
1007
  executed.map(&:first)
499
1008
  end
500
1009
 
@@ -516,7 +1025,7 @@ module Mistri
516
1025
  # Provider output is untrusted until the call has resolved to a current
517
1026
  # tool, passed its one allowed normalization, and satisfied both core and
518
1027
  # host schema checks. Rejections stay paired in band, while valid siblings
519
- # continue through policy and execution.
1028
+ # continue through policy. CallOrder decides which of them then run.
520
1029
  def prepare_calls(calls, normalize:, signal: nil)
521
1030
  calls.each_with_object([[], [], []]) do |call, (ordered, valid, rejected)|
522
1031
  if signal&.aborted?
@@ -550,25 +1059,31 @@ module Mistri
550
1059
  def prepare_call(call, normalize:, signal: nil)
551
1060
  call = call.with unless call.arguments_owned?
552
1061
  tool = @tools_by_name[call.name]
553
- return [call, unavailable_tool(call.name)] unless tool
1062
+ refusal = uncallable(call.name, tool, fresh: normalize)
1063
+ return [call, refusal] if refusal
554
1064
 
1065
+ prepare_arguments(tool, call, normalize:, signal:)
1066
+ end
1067
+
1068
+ def prepare_arguments(tool, call, normalize:, signal:)
555
1069
  if call.arguments_error
556
1070
  violation = if call.arguments_error == "invalid_json"
557
1071
  "arguments were not valid JSON"
558
1072
  else
559
1073
  "arguments were not valid bounded JSON"
560
1074
  end
561
- return [call, argument_failure(call.name, violation)]
1075
+ return [call, argument_failure(call.name, violation, fresh: normalize)]
562
1076
  end
563
1077
  unless call.arguments.is_a?(Hash)
564
- return [call, argument_failure(call.name, "arguments must be a JSON object")]
1078
+ violation = "arguments must be a JSON object"
1079
+ return [call, argument_failure(call.name, violation, fresh: normalize)]
565
1080
  end
566
1081
 
567
1082
  prepared, failure = normalize ? normalize_call(tool, call) : [call, nil]
568
1083
  return [prepared, nil] if signal&.aborted?
569
1084
  return [prepared, failure] if failure
570
1085
 
571
- [prepared, validate_call(tool, prepared)]
1086
+ [prepared, validate_call(tool, prepared, fresh: normalize)]
572
1087
  end
573
1088
 
574
1089
  # Tool-result correlation is provider-owned opaque state. If any ID is
@@ -735,7 +1250,7 @@ module Mistri
735
1250
  [call, preparation_failure(call.name, "normalizer", e.class)]
736
1251
  end
737
1252
 
738
- def validate_call(tool, call)
1253
+ def validate_call(tool, call, fresh:)
739
1254
  validator = @external_tool_validators[call.name]
740
1255
  errors = if tool.is_a?(Tool)
741
1256
  TOOL_ARGUMENT_VALIDATOR.bind_call(tool, call.arguments, owned: true)
@@ -745,12 +1260,16 @@ module Mistri
745
1260
  if errors.empty? && !tool.is_a?(Tool) && tool.respond_to?(:prepared_argument_violations)
746
1261
  errors = tool.prepared_argument_violations(call.arguments)
747
1262
  end
748
- errors.empty? ? nil : argument_failure(call.name, *errors)
1263
+ errors.empty? ? nil : argument_failure(call.name, *errors, fresh:)
749
1264
  rescue StandardError => e
750
1265
  preparation_failure(call.name, "validator", e.class)
751
1266
  end
752
1267
 
753
- def argument_failure(name, *violations)
1268
+ # The model called a tool loaded before a compaction without its
1269
+ # definition, so it cannot correct the arguments. It has to load the tool.
1270
+ def argument_failure(name, *violations, fresh:)
1271
+ return unloaded_tool(name) if fresh && unloaded?(name)
1272
+
754
1273
  header = "Invalid arguments for tool #{tool_label(name)}:\n"
755
1274
  footer = "\nThe tool did not run. Correct the arguments and try again."
756
1275
  available = MAX_ARGUMENT_ERROR_BYTES - header.bytesize - footer.bytesize
@@ -768,6 +1287,28 @@ module Mistri
768
1287
  ToolResult.new(content: utf8_prefix(content, MAX_ARGUMENT_ERROR_BYTES), error: true)
769
1288
  end
770
1289
 
1290
+ # The error for a call that cannot run: no tool has the name, or the tool
1291
+ # is deferred and no result has loaded it. A call that waited for approval
1292
+ # was loaded when the model made it, and the definition of a tool loaded
1293
+ # before a compaction was sent to the model then.
1294
+ def uncallable(name, tool, fresh:)
1295
+ return unavailable_tool(name) unless tool
1296
+ return unless fresh && unloaded?(name)
1297
+
1298
+ carried = @session.last_compaction&.dig("carried", "loaded").to_a
1299
+ unloaded_tool(name) unless carried.include?(name)
1300
+ end
1301
+
1302
+ def unloaded?(name) = @deferred_specs.key?(name) && !@loaded.include?(name)
1303
+
1304
+ # The model has a name and no schema, so its arguments would be a guess.
1305
+ def unloaded_tool(name)
1306
+ content = "Tool #{tool_label(name)} is not loaded, so it did not run. Load it with " \
1307
+ "#{ToolSearch::NAME} first: write select:#{name} as the query, with the other " \
1308
+ "tools you expect to need after it, separated by commas. Then call it again."
1309
+ ToolResult.new(content: utf8_prefix(content, MAX_ARGUMENT_ERROR_BYTES), error: true)
1310
+ end
1311
+
771
1312
  def preparation_failure(name, phase, error_class)
772
1313
  klass = safe_violation(error_class.name || "Exception")
773
1314
  content = "Tool #{tool_label(name)} could not prepare arguments: its argument #{phase} " \
@@ -824,16 +1365,26 @@ module Mistri
824
1365
 
825
1366
  # Runs calls without persisting them; the caller commits and rewrites
826
1367
  # settled results in the model's original call order.
827
- def execute(calls, signal, &emit)
1368
+ def execute(calls, signal, among:, spent: 0, &emit)
828
1369
  return [] if calls.empty?
829
1370
 
830
1371
  ToolExecutor.call_with_outcomes(calls, @tools_by_name, signal: signal,
831
1372
  max_concurrency: @max_concurrency,
832
1373
  session: @session, emit: emit,
833
1374
  app: @context,
1375
+ result_limit_for: limits(among, spent),
1376
+ scratchpad: @scratchpad,
1377
+ compaction: @compaction,
834
1378
  prepared_arguments: true)
835
1379
  end
836
1380
 
1381
+ def limits(among, spent)
1382
+ return unless @result_limit
1383
+
1384
+ share = @result_limit.share(among, spent:)
1385
+ ->(call) { [own_limit(call), share].min }
1386
+ end
1387
+
837
1388
  def interrupt_tool_turn(calls, signal, &)
838
1389
  answer_results(calls, interrupted_results(calls), executed: [], signal:, &)
839
1390
  [[], false]
@@ -877,13 +1428,13 @@ module Mistri
877
1428
 
878
1429
  def rewrite(call, result, context)
879
1430
  rewritten = @after_tool.call(call, result, context) || result
880
- return rewritten unless result.is_a?(ToolResult) && result.error?
1431
+ return rewritten unless result.is_a?(ToolResult)
881
1432
 
882
- if rewritten.is_a?(ToolResult)
883
- rewritten.with(error: true)
884
- else
885
- ToolResult.new(content: rewritten, error: true)
1433
+ # A hook's text is what the model reads. The tool's loads stand.
1434
+ unless rewritten.is_a?(ToolResult)
1435
+ rewritten = ToolResult.new(content: rewritten, loads: result.loads)
886
1436
  end
1437
+ result.error? ? rewritten.with(error: true) : rewritten
887
1438
  rescue EventDelivery::Failure => e
888
1439
  raise EventDelivery.unwrap(e, context.emit)
889
1440
  rescue StandardError => e
@@ -896,42 +1447,126 @@ module Mistri
896
1447
 
897
1448
  def hook_context(signal, emit)
898
1449
  ToolContext.new(session: @session, signal: signal, emit: EventDelivery.wrap(emit),
899
- app: @context)
1450
+ app: @context, scratchpad: @scratchpad,
1451
+ compaction: @compaction)
900
1452
  end
901
1453
 
902
1454
  # The tool message carries both channels; the :tool_result event exposes
903
1455
  # it whole so hosts read event.message.ui for their side of the result.
904
- def answer(call, result, duration: nil, &emit)
905
- content, ui, tool_error = if result.is_a?(ToolResult)
906
- [result.content, result.ui, result.error?]
907
- else
908
- [result, nil, false]
909
- end
1456
+ def answer(call, result, duration: nil, turn: nil, &emit)
1457
+ content, ui, tool_error, loads = if result.is_a?(ToolResult)
1458
+ [result.content, result.ui, result.error?, result.loads]
1459
+ else
1460
+ [result, nil, false, nil]
1461
+ end
1462
+ loads = nil if tool_error
1463
+ content, cut = bound(stored_form(content), turn, call)
910
1464
  message = @session.append_message(Message.tool(content: content, tool_call_id: call.id,
911
1465
  tool_name: call.name, ui: ui,
912
- tool_error: tool_error))
1466
+ tool_error: tool_error, loads: loads,
1467
+ cut: cut))
913
1468
  text = content.is_a?(String) ? content : "[content]"
914
1469
  emit&.call(Event.new(type: :tool_result, tool_call: call, content: text,
915
1470
  message: message, duration: duration, tool_error: tool_error))
916
1471
  end
917
1472
 
918
- def answer_results(calls, results, executed:, signal:, &emit)
919
- executed_results = if @after_tool
920
- {}.compare_by_identity.tap do |index|
921
- executed.each { |result| index[result] = true if result[3] }
922
- end
923
- end
1473
+ # A hook can return rows where a tool returns text. They are bounded in
1474
+ # the blocks a message stores them as, so what is counted is what is kept.
1475
+ def stored_form(content) = content.is_a?(String) ? content : Content.wrap(content)
1476
+
1477
+ def bound(content, turn, call)
1478
+ return [content, nil] unless @result_limit
1479
+
1480
+ own = own_limit(call)
1481
+ saved = saveable?(content, call)
1482
+ limit = turn ? turn.limit(own, saved:) : own
1483
+ content, cut = (saved && saved_in_scratchpad(content, limit, call)) ||
1484
+ @result_limit.bound(content, limit, shared: limit < own)
1485
+ turn&.spend(ResultLimit.size(content))
1486
+ [content, cut]
1487
+ end
1488
+
1489
+ def own_limit(call)
1490
+ tool = @tools_by_name[call.name]
1491
+ (tool.respond_to?(:result_limit) && tool.result_limit) || @result_limit.bytes
1492
+ end
1493
+
1494
+ def saved_in_scratchpad(content, limit, call)
1495
+ text = content.is_a?(String) ? content : Array(content).map(&:text).join("\n")
1496
+ return unless text.bytesize > limit
1497
+
1498
+ @result_limit.shown(text, @scratchpad.save_result(text, call.name), limit)
1499
+ rescue StandardError => e
1500
+ warn "mistri: saving a result of #{call.name} failed (#{e.class}: #{e.message}); it is cut"
1501
+ @result_limit.bound(content, limit, unsaved: true)
1502
+ end
1503
+
1504
+ def saveable?(content, call)
1505
+ tool = @tools_by_name[call.name]
1506
+ return false unless @scratchpad && !(tool.respond_to?(:save_result?) && !tool.save_result?)
1507
+
1508
+ blocks = Array(content)
1509
+ content.is_a?(String) || (blocks.any? && blocks.all?(Content::Text))
1510
+ end
1511
+
1512
+ # after_tool runs on a result just before it is stored, so a hook sees
1513
+ # the results before it stored. When a hook changes a result, the turn is
1514
+ # planned again from there: the results after it get the room it left.
1515
+ def answer_results(calls, results, executed:, signal:, spent: 0, &emit)
1516
+ hooked = executed_entries(executed)
1517
+ context = hook_context(signal, emit) if @after_tool
1518
+ pending = in_call_order(calls, results)
1519
+ turn = result_turn(pending, spent)
1520
+ pending.each_with_index do |entry, index|
1521
+ call, returned, seconds = entry
1522
+ result = hooked&.key?(entry) ? rewrite(call, returned, context) : returned
1523
+ rest = [[call, result], *pending.drop(index + 1)]
1524
+ turn = planned_again(turn, rest) unless result.equal?(returned)
1525
+ answer(call, result, duration: seconds, turn:, &emit)
1526
+ end
1527
+ end
1528
+
1529
+ def executed_entries(executed)
1530
+ return unless @after_tool
1531
+
1532
+ {}.compare_by_identity.tap do |index|
1533
+ executed.each { |result| index[result] = true if result[3] }
1534
+ end
1535
+ end
1536
+
1537
+ def in_call_order(calls, results)
924
1538
  by_call = {}.compare_by_identity
925
1539
  results.each { |result| (by_call[result[0]] ||= []) << result }
926
- context = hook_context(signal, emit) if @after_tool
927
- calls.each do |call|
928
- queued = by_call[call]
929
- next unless queued && (entry = queued.shift)
1540
+ calls.filter_map { |call| by_call[call]&.shift }
1541
+ end
1542
+
1543
+ def planned_again(turn, rest)
1544
+ turn && result_turn(rest, @result_limit.turn_bytes - turn.left)
1545
+ end
930
1546
 
931
- _call, result, seconds = entry
932
- result = rewrite(call, result, context) if executed_results&.key?(entry)
933
- answer(call, result, duration: seconds, &emit)
1547
+ def result_turn(results, spent)
1548
+ return nil unless @result_limit
1549
+
1550
+ held = results.map do |call, result, _seconds|
1551
+ held(call, result.is_a?(ToolResult) ? result.content : result)
934
1552
  end
1553
+ @result_limit.turn(held, spent:)
1554
+ end
1555
+
1556
+ def held(call, content)
1557
+ size = ResultLimit.size(content)
1558
+ own = own_limit(call)
1559
+ saved = ResultLimit::SAVED_BYTES if saveable?(content, call)
1560
+ ResultLimit::Held.new(whole: size <= own ? size : saved || own, saved:)
1561
+ end
1562
+
1563
+ # After an approval the rest of a turn's results are answered in a later
1564
+ # run, so the turn's limit counts what is stored already.
1565
+ def stored_for_turn
1566
+ return 0 unless @result_limit
1567
+
1568
+ @session.messages.reverse_each.take_while(&:tool?)
1569
+ .sum { |message| ResultLimit.size(message.content) }
935
1570
  end
936
1571
 
937
1572
  def gated?(call)
@@ -964,12 +1599,12 @@ module Mistri
964
1599
  # the signal is what knows the user stopped it. handed_off marks a run
965
1600
  # an ends_turn tool ended, and only a genuinely completed one: a run
966
1601
  # aborted during that same tool phase handed nothing to anyone.
967
- def finished(message, usage, signal = nil, handed_off: false)
1602
+ def finished(message, usage, signal = nil, handed_off: false, said: nil)
968
1603
  status = { StopReason::ABORTED => :aborted, StopReason::BUDGET => :budget,
969
1604
  StopReason::ERROR => :error }.fetch(message.stop_reason, :completed)
970
1605
  status = :aborted if status == :completed && signal&.aborted?
971
1606
  Result.new(message: message, status: status, usage: usage,
972
- handed_off: handed_off && status == :completed)
1607
+ handed_off: handed_off && status == :completed, said:)
973
1608
  end
974
1609
 
975
1610
  def suspended(message, parked, usage)