mistri 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +355 -2
  3. data/CONTRIBUTING.md +17 -3
  4. data/NOTICE +11 -0
  5. data/README.md +145 -226
  6. data/UPGRADING.md +810 -0
  7. data/assets/vendors/README.md +12 -0
  8. data/assets/vendors/claude-mark.svg +3 -0
  9. data/assets/vendors/gemini-mark.svg +10 -0
  10. data/assets/vendors/openai-mark-dark.svg +1 -0
  11. data/assets/vendors/openai-mark.svg +1 -0
  12. data/docs/README.md +2 -1
  13. data/docs/context-and-workspaces.md +84 -13
  14. data/docs/logging.md +90 -0
  15. data/docs/mcp.md +762 -21
  16. data/docs/reliability.md +210 -24
  17. data/docs/sessions.md +415 -36
  18. data/docs/sub-agents.md +85 -7
  19. data/docs/tool-contracts.md +528 -13
  20. data/examples/approval.rb +7 -7
  21. data/examples/browser.rb +1 -1
  22. data/examples/page_editor.rb +2 -2
  23. data/examples/quickstart.rb +1 -1
  24. data/lib/generators/mistri/install/templates/migration.rb.tt +4 -2
  25. data/lib/generators/mistri/mcp/mcp_generator.rb +2 -2
  26. data/lib/generators/mistri/mcp/templates/model.rb.tt +21 -8
  27. data/lib/mistri/agent.rb +839 -141
  28. data/lib/mistri/call_order.rb +137 -0
  29. data/lib/mistri/child.rb +69 -13
  30. data/lib/mistri/compaction.rb +200 -35
  31. data/lib/mistri/compactor/text.rb +91 -0
  32. data/lib/mistri/compactor.rb +474 -117
  33. data/lib/mistri/console.rb +44 -11
  34. data/lib/mistri/content.rb +70 -3
  35. data/lib/mistri/definition.rb +2 -2
  36. data/lib/mistri/edit.rb +13 -7
  37. data/lib/mistri/errors.rb +37 -0
  38. data/lib/mistri/event.rb +20 -9
  39. data/lib/mistri/locks/rails_cache.rb +16 -2
  40. data/lib/mistri/locks.rb +12 -3
  41. data/lib/mistri/mcp/client.rb +247 -61
  42. data/lib/mistri/mcp/conversation.rb +161 -0
  43. data/lib/mistri/mcp/egress.rb +5 -4
  44. data/lib/mistri/mcp/mirror.rb +90 -0
  45. data/lib/mistri/mcp/negotiation.rb +222 -0
  46. data/lib/mistri/mcp/oauth/client_identity.rb +53 -0
  47. data/lib/mistri/mcp/oauth/tolerance.rb +61 -0
  48. data/lib/mistri/mcp/oauth.rb +303 -82
  49. data/lib/mistri/mcp/results.rb +97 -0
  50. data/lib/mistri/mcp/sdk_client.rb +47 -0
  51. data/lib/mistri/mcp/wires.rb +325 -52
  52. data/lib/mistri/mcp.rb +304 -55
  53. data/lib/mistri/memory.rb +1 -1
  54. data/lib/mistri/message.rb +45 -8
  55. data/lib/mistri/models.rb +146 -24
  56. data/lib/mistri/partial_json.rb +5 -5
  57. data/lib/mistri/providers/anthropic/assembler.rb +40 -3
  58. data/lib/mistri/providers/anthropic/serializer.rb +154 -22
  59. data/lib/mistri/providers/anthropic.rb +77 -12
  60. data/lib/mistri/providers/fake.rb +4 -1
  61. data/lib/mistri/providers/gemini/assembler.rb +63 -3
  62. data/lib/mistri/providers/gemini/serializer.rb +27 -16
  63. data/lib/mistri/providers/gemini.rb +56 -11
  64. data/lib/mistri/providers/openai/assembler.rb +36 -5
  65. data/lib/mistri/providers/openai/serializer.rb +76 -22
  66. data/lib/mistri/providers/openai.rb +91 -14
  67. data/lib/mistri/reminder.rb +35 -3
  68. data/lib/mistri/result.rb +6 -4
  69. data/lib/mistri/result_limit.rb +164 -0
  70. data/lib/mistri/sandbox/quickjs.rb +345 -0
  71. data/lib/mistri/sandbox.rb +18 -0
  72. data/lib/mistri/schema.rb +26 -2
  73. data/lib/mistri/scratchpad.rb +107 -0
  74. data/lib/mistri/session/log.rb +137 -0
  75. data/lib/mistri/session.rb +405 -75
  76. data/lib/mistri/sinks/logger.rb +407 -0
  77. data/lib/mistri/skills.rb +10 -4
  78. data/lib/mistri/spawner.rb +43 -12
  79. data/lib/mistri/sse.rb +3 -2
  80. data/lib/mistri/stores/active_record.rb +30 -6
  81. data/lib/mistri/stores/jsonl.rb +26 -7
  82. data/lib/mistri/stores/memory.rb +6 -2
  83. data/lib/mistri/sub_agent/execution.rb +11 -3
  84. data/lib/mistri/sub_agent/runtime.rb +11 -1
  85. data/lib/mistri/sub_agent.rb +13 -4
  86. data/lib/mistri/tool.rb +71 -7
  87. data/lib/mistri/tool_arguments.rb +10 -11
  88. data/lib/mistri/tool_context.rb +15 -3
  89. data/lib/mistri/tool_executor.rb +49 -26
  90. data/lib/mistri/tool_result.rb +8 -2
  91. data/lib/mistri/tool_search/index.rb +193 -0
  92. data/lib/mistri/tool_search.rb +200 -0
  93. data/lib/mistri/tools/delete_file.rb +22 -0
  94. data/lib/mistri/tools/edit_file.rb +24 -14
  95. data/lib/mistri/tools/find_in_file.rb +1 -0
  96. data/lib/mistri/tools/grep.rb +212 -0
  97. data/lib/mistri/tools/list_files.rb +38 -5
  98. data/lib/mistri/tools/read_file.rb +83 -21
  99. data/lib/mistri/tools/read_memory.rb +2 -1
  100. data/lib/mistri/tools/run_code.rb +167 -0
  101. data/lib/mistri/tools/write_file.rb +66 -9
  102. data/lib/mistri/tools.rb +72 -1
  103. data/lib/mistri/transport/streamable_http.rb +140 -0
  104. data/lib/mistri/transport.rb +53 -63
  105. data/lib/mistri/usage.rb +33 -4
  106. data/lib/mistri/version.rb +1 -1
  107. data/lib/mistri/workspace/active_record.rb +22 -10
  108. data/lib/mistri/workspace/directory.rb +5 -1
  109. data/lib/mistri/workspace/memory.rb +4 -0
  110. data/lib/mistri/workspace/path_space.rb +56 -0
  111. data/lib/mistri/workspace/single.rb +6 -1
  112. data/lib/mistri.rb +28 -4
  113. metadata +30 -2
data/lib/mistri/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,35 +43,43 @@ 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
39
51
  # when an approved call finally executes, so a decision that aged days
40
52
  # still passes current policy); after_tool(call, result, context) may
41
53
  # return a replacement result, or nil to keep the original.
54
+ # log_label tags this agent's log lines (sub-agents
55
+ # get their worker label); nil falls back to the session id.
42
56
  def initialize(provider:, session: nil, system: nil, tools: [], budget: nil,
43
57
  max_concurrency: 4, transform_context: nil, compaction: Compaction.new,
44
58
  retries: RetryPolicy.new, skills: [], before_tool: nil, after_tool: nil,
45
- context: nil)
59
+ context: nil, log_label: nil, lease: true, result_limit: ResultLimit.new,
60
+ scratchpad: nil, sandbox: nil, files: nil)
46
61
  @provider = provider
47
62
  @session = session || Session.new(store: Stores::Memory.new)
48
63
  skills = skills.is_a?(String) ? Skills.load(skills) : Array(skills)
49
64
  @system = Skills.amend(system, skills)
50
- @tools = skills.empty? ? tools : tools + [Skills.reader(skills)]
51
- @tools_by_name = @tools.to_h { |tool| [tool.name, tool] }
52
- raise ConfigurationError, "duplicate tool names" if @tools_by_name.length != @tools.length
53
-
54
- @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))
55
70
 
56
71
  @budget = budget || Budget.new
57
72
  @budget.validate_provider!(@provider)
58
73
  @max_concurrency = max_concurrency
59
74
  @transform_context = Array(transform_context)
60
75
  @compaction = compaction || nil
76
+ @budget.validate_provider!(@compaction.fallback) if @compaction&.fallback
61
77
  @retries = retries || nil
62
78
  @before_tool = before_tool
63
79
  @after_tool = after_tool
64
80
  @context = context
81
+ @log_label = log_label
82
+ @lease = lease
65
83
  end
66
84
 
67
85
  attr_reader :session
@@ -73,18 +91,13 @@ module Mistri
73
91
  # schema, natively where the provider supports it. task adds validation
74
92
  # on top; run alone does not validate.
75
93
  def run(input, images: [], signal: nil, output_schema: nil, &emit)
76
- if refresh_tool_control.any?
77
- raise ConfigurationError,
78
- "session is awaiting approvals; call resume"
79
- end
80
- if input.to_s.empty? && Array(images).empty?
81
- raise ArgumentError,
82
- "run needs input text or images"
94
+ # The frame covers the whole public method, so an audit rejection or
95
+ # a store failure gets a crash line too, not just loop failures.
96
+ exclusive do
97
+ logged(emit, verb: "run", input: input) do |subscriber|
98
+ exchange(input, images:, signal:, output_schema:, &subscriber)
99
+ end
83
100
  end
84
-
85
- fold_inbox # anything queued while this session sat idle arrived first; keep that order
86
- @session.append_message(Message.user_with_images(input, images))
87
- loop_turns(signal, output_schema, &emit)
88
101
  end
89
102
 
90
103
  # Continue a suspended run. Undecided approvals return immediately, still
@@ -93,25 +106,29 @@ module Mistri
93
106
  # carries on as if it never stopped, unless a settled call's tool ends
94
107
  # the turn, in which case its execution was the run's last word.
95
108
  def resume(signal: nil, &emit)
96
- open = refresh_tool_control
97
- pending = open.select { |approval| approval[:decision].nil? }
98
- if pending.any?
99
- return Result.new(message: nil, status: :awaiting_approval,
100
- pending: pending.map { |approval| approval[:call] },
101
- usage: Usage.zero)
102
- 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
103
118
 
104
- executed = settle(open, signal, &emit)
105
- if signal&.aborted?
106
- last = @session.messages.reverse_each.find(&:assistant?)
107
- return finished(last, Usage.zero, signal)
108
- end
109
- if executed.any? { |call| ends_turn?(call) }
110
- last = @session.messages.reverse_each.find(&:assistant?)
111
- return finished(last, Usage.zero, signal, handed_off: true)
112
- 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
113
128
 
114
- loop_turns(signal, nil, &emit)
129
+ loop_turns(signal, nil, &subscriber)
130
+ end
131
+ end
115
132
  end
116
133
 
117
134
  # Run an exchange that must end in a JSON value matching schema. Tools
@@ -126,8 +143,284 @@ module Mistri
126
143
  # belongs to whoever answers, and re-prompting for JSON would steal it
127
144
  # back. Ask again once the answer arrives.
128
145
  def task(input, schema:, images: [], signal: nil, fixes: 1, &emit)
129
- plan = Schema.task_plan(schema)
130
- result = run(
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
152
+ end
153
+ end
154
+
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
168
+ window = context_window
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 }
173
+ end
174
+
175
+ # Compact now (a UI button, a pre-flight trim before a big task). Returns
176
+ # the Compactor result, or nil when there is nothing worth compacting.
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
184
+ end
185
+
186
+ private
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
+
420
+ # The body of task, extracted so its early returns close the log frame
421
+ # instead of skipping it.
422
+ def validated_task(input, plan, images, signal, fixes, &emit)
423
+ result = exchange(
131
424
  TaskOutput.prompt(input, plan), images:, signal:, output_schema: plan, &emit
132
425
  )
133
426
  spent = result.usage
@@ -141,29 +434,65 @@ module Mistri
141
434
  return result.with(output: value) if errors.empty?
142
435
  raise SchemaError, "task output failed validation: #{errors.join("; ")}" if remaining.zero?
143
436
 
144
- result = run(TaskOutput.fix_prompt(errors), signal:, output_schema: plan, &emit)
437
+ result = exchange(TaskOutput.fix_prompt(errors), signal:, output_schema: plan, &emit)
145
438
  spent += result.usage
146
439
  end
147
440
  end
148
441
 
149
- # How full the context is: {tokens:, window:, fraction:}. Hosts render
150
- # meters and near-limit warnings from this; window is nil for models the
151
- # catalog does not know unless Compaction#window supplies one.
152
- def context_usage
153
- tokens = @session.context_tokens
154
- window = context_window
155
- { tokens: tokens, window: window,
156
- fraction: window && (tokens.to_f / window).round(3) }
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
157
448
  end
158
449
 
159
- # Compact now (a UI button, a pre-flight trim before a big task). Returns
160
- # the Compactor result, or nil when there is nothing worth compacting.
161
- def compact(&)
162
- Compactor.call(session: @session, provider: @provider,
163
- settings: @compaction || Compaction.new, &)
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))
164
461
  end
165
462
 
166
- private
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.
473
+ def logged(emit, verb:, input: nil)
474
+ sink = Sinks::Logger.attach(@session.id, label: @log_label)
475
+ return yield(emit) unless sink
476
+
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
487
+ begin
488
+ result = yield(subscriber)
489
+ rescue StandardError => e
490
+ sink.run_crashed(EventDelivery.original(e))
491
+ raise
492
+ end
493
+ sink.run_finished(result)
494
+ result
495
+ end
167
496
 
168
497
  def loop_turns(signal, output_schema = nil, &emit)
169
498
  turns = 0
@@ -182,7 +511,7 @@ module Mistri
182
511
  reason = @budget.exceeded(turns:, usage:, elapsed: monotonic_now - started)
183
512
  return stop_for_budget(reason, usage, &emit) if reason
184
513
  end
185
- last, turn_usage = run_turn(signal, output_schema, &emit)
514
+ last, turn_usage, said = run_turn(signal, output_schema, &emit)
186
515
  turns += 1
187
516
  usage += turn_usage
188
517
 
@@ -190,7 +519,10 @@ module Mistri
190
519
  # transcript is unpairable and replay fails.
191
520
  parked, ended = last.tool_calls? ? run_tools(last, signal, &emit) : [[], false]
192
521
  return suspended(last, parked, usage) if parked.any?
193
- 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:)
194
526
  end
195
527
  end
196
528
 
@@ -205,22 +537,73 @@ module Mistri
205
537
  @session.pending_inbox.empty?
206
538
  end
207
539
 
208
- # Compact when the context has grown into the reserve. A failed
209
- # summarization skips quietly here: if the context genuinely no longer
210
- # 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.
211
548
  def auto_compact(&)
212
549
  return nil unless @compaction
213
550
 
214
- tokens = @session.context_tokens
215
- return nil unless @compaction.needed?(tokens, context_window,
216
- 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)
217
557
 
218
558
  compact_automatically(&)
219
559
  end
220
560
 
221
- 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)
222
603
  delivery = EventDelivery.wrap(emit)
223
- 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)
224
607
  rescue EventDelivery::Failure => e
225
608
  raise EventDelivery.unwrap(e, delivery)
226
609
  rescue CompactionError => e
@@ -254,38 +637,186 @@ module Mistri
254
637
  # (:done or :error) holds at a gate, so retries stay invisible to the
255
638
  # model and a recovered retry never shows the subscriber an error it
256
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.
257
643
  def run_turn(signal, output_schema = nil, &emit)
258
- history = @transform_context.reduce(@session.messages) do |messages, transform|
259
- transform.call(messages)
260
- end
644
+ replayed = @session.messages
645
+ said = said_since_user(replayed)
646
+ history = history_of(replayed)
261
647
  attempt = 0
262
648
  usage = Usage.zero
263
649
  schema = provider_output_schema(output_schema)
650
+ shortened = nil
264
651
  loop do
265
652
  held = nil
266
653
  gate = emit && ->(event) { event.terminal? ? held = event : emit.call(event) }
267
654
  message = @provider.stream(messages: history, system: @system,
268
- tools: @tool_specs, signal: signal,
655
+ **tool_options(history), signal: signal,
269
656
  output_schema: schema, &gate)
270
657
  message, held = enforce_tool_call_envelope(message, held)
271
658
  attempt_usage = message.usage || Usage.new
272
659
  validate_usage!(attempt_usage, message:, kind: "turn", &emit)
273
660
  usage += attempt_usage
274
661
  attempt += 1
275
- error = @retries&.error_for(message)
662
+ error = attempt_error(message, said)
276
663
  if retry_turn?(error, attempt, signal)
277
664
  pause = @retries.delay(attempt, error["retry_after"])
278
665
  record_retry(message, error, attempt, pause, &emit)
279
666
  wait(pause, signal)
280
667
  next unless signal&.aborted?
281
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
282
673
  emit&.call(held) if held
283
674
  @session.append_message(message)
284
675
  reserve_tool_call_ids(message.tool_calls)
285
- 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
286
781
  end
287
782
  end
288
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
+
289
820
  def provider_output_schema(output_schema)
290
821
  return output_schema unless output_schema.respond_to?(:native_fallback?)
291
822
  return output_schema.schema unless @provider.respond_to?(:native_output_schema)
@@ -293,6 +824,21 @@ module Mistri
293
824
  @provider.native_output_schema(output_schema.schema)
294
825
  end
295
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
+
296
842
  def retry_turn?(error, attempt, signal)
297
843
  return false unless @retries && error
298
844
  return false if signal&.aborted?
@@ -304,10 +850,11 @@ module Mistri
304
850
  entry = { "attempt" => attempt, "error" => error, "delay" => pause.round(2) }
305
851
  entry["usage"] = (message.usage || Usage.new).to_h
306
852
  @session.append("retry", entry)
307
- note = format("attempt %<attempt>d failed; retrying in %<pause>.1fs",
308
- 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)
309
856
  emit&.call(Event.new(type: :retry, content: note, attempt: attempt,
310
- max_attempts: @retries.attempts, delay: pause.round(2),
857
+ max_attempts: @retries&.attempts, delay: pause.round(2),
311
858
  message: message))
312
859
  end
313
860
 
@@ -333,13 +880,13 @@ module Mistri
333
880
  sleep(0.1) while monotonic_now < deadline && !signal&.aborted?
334
881
  end
335
882
 
336
- # Answer or park the assistant's tool calls. Ungated calls execute (only
337
- # on a genuine tool_use turn with no abort; otherwise they pair with
338
- # interrupted results). Gated calls park as approval requests. Nothing
339
- # is left dangling either way. Returns the parked calls and whether an
340
- # executed tool ends the turn; a parked call outranks an executed
341
- # ends_turn, because a suspension is the stronger stop and the model
342
- # 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.
343
890
  def run_tools(assistant, signal, &emit)
344
891
  calls = assistant.tool_calls
345
892
  unless assistant.stop_reason == StopReason::TOOL_USE && !signal&.aborted?
@@ -357,17 +904,23 @@ module Mistri
357
904
 
358
905
  def complete_tool_batch(source_calls, prepared, batch, signal, provider:, &emit)
359
906
  batch = protect_gemini_result_order(prepared, batch) if provider == :gemini
360
- invalid, blocked, parked, free, rejected = batch
361
- 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
362
916
  if signal&.aborted?
363
- uncommitted = [*invalid, *blocked, *rejected].map(&:first) + parked
917
+ uncommitted = unrun.map(&:first) + parked
364
918
  results = [*executed, *interrupted_results(uncommitted)]
365
919
  answer_results(prepared, results, executed:, signal:, &emit)
366
920
  return [[], executed_ends_turn?(executed)]
367
921
  end
368
922
 
369
- answer_results(prepared, [*invalid, *blocked, *rejected, *executed],
370
- executed:, signal:, &emit)
923
+ answer_results(prepared, [*unrun, *executed], executed:, signal:, &emit)
371
924
  if signal&.aborted?
372
925
  answer_results(prepared, interrupted_results(parked),
373
926
  executed: [], signal:, &emit)
@@ -391,47 +944,66 @@ module Mistri
391
944
 
392
945
  # Before Gemini 3, same-name parallel calls may have no wire IDs and only
393
946
  # order pairs their responses. A later immediate result cannot pass an
394
- # 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.
395
950
  def protect_gemini_result_order(prepared, batch)
396
951
  invalid, blocked, parked, free, rejected = batch
397
- positions = prepared.each_with_index.to_h { |call, index| [call.id, index] }
398
- immediate = [*invalid, *blocked, *rejected].map(&:first) + free
399
- unsafe, safe = parked.partition do |parked_call|
400
- parked_call.provider_call_id.nil? && immediate.any? do |call|
401
- call.provider_call_id.nil? && call.name == parked_call.name &&
402
- positions.fetch(call.id) > positions.fetch(parked_call.id)
403
- 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] }
404
960
  end
405
- failures = unsafe.map do |call|
406
- content = "Gemini returned parallel same-name calls without IDs across an approval " \
407
- "boundary. This tool did not run; retry those calls separately."
408
- [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) }
409
976
  end
410
- [invalid, blocked, safe, free, [*rejected, *failures]]
411
977
  end
412
978
 
413
979
  # Returns the calls that actually executed (denied ones only answer).
414
980
  def settle(open, signal, &)
415
981
  approved, denied = open.partition { |approval| approval[:decision]["approved"] }
416
982
  approved_calls = approved.map { |approval| approval[:call] }
417
- _prepared, valid, invalid = prepare_calls(
983
+ prepared, valid, invalid = prepare_calls(
418
984
  approved_calls, normalize: false, signal:
419
985
  )
420
986
  return interrupt_settlement(open, approved_calls, denied, signal, &) if signal&.aborted?
421
987
 
422
- cleared, blocked = screen(valid, signal, &)
988
+ _cleared, blocked = screen(valid, signal, &)
423
989
  return interrupt_settlement(open, approved_calls, denied, signal, &) if signal&.aborted?
424
990
 
425
- executed = execute(cleared, signal, &)
991
+ spent = stored_for_turn
426
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]
427
1001
  results = if signal&.aborted?
428
- uncommitted = [*invalid, *blocked].map(&:first)
429
- [*executed, *interrupted_results(uncommitted), *denials]
1002
+ [*executed, *interrupted_results(unrun.map(&:first)), *denials]
430
1003
  else
431
- [*invalid, *blocked, *executed, *denials]
1004
+ [*unrun, *executed, *denials]
432
1005
  end
433
- answer_results(open.map { |approval| approval[:call] },
434
- results, executed:, signal:, &)
1006
+ answer_results(calls, results, executed:, signal:, spent:, &)
435
1007
  executed.map(&:first)
436
1008
  end
437
1009
 
@@ -453,7 +1025,7 @@ module Mistri
453
1025
  # Provider output is untrusted until the call has resolved to a current
454
1026
  # tool, passed its one allowed normalization, and satisfied both core and
455
1027
  # host schema checks. Rejections stay paired in band, while valid siblings
456
- # continue through policy and execution.
1028
+ # continue through policy. CallOrder decides which of them then run.
457
1029
  def prepare_calls(calls, normalize:, signal: nil)
458
1030
  calls.each_with_object([[], [], []]) do |call, (ordered, valid, rejected)|
459
1031
  if signal&.aborted?
@@ -487,25 +1059,31 @@ module Mistri
487
1059
  def prepare_call(call, normalize:, signal: nil)
488
1060
  call = call.with unless call.arguments_owned?
489
1061
  tool = @tools_by_name[call.name]
490
- return [call, unavailable_tool(call.name)] unless tool
1062
+ refusal = uncallable(call.name, tool, fresh: normalize)
1063
+ return [call, refusal] if refusal
491
1064
 
1065
+ prepare_arguments(tool, call, normalize:, signal:)
1066
+ end
1067
+
1068
+ def prepare_arguments(tool, call, normalize:, signal:)
492
1069
  if call.arguments_error
493
1070
  violation = if call.arguments_error == "invalid_json"
494
1071
  "arguments were not valid JSON"
495
1072
  else
496
1073
  "arguments were not valid bounded JSON"
497
1074
  end
498
- return [call, argument_failure(call.name, violation)]
1075
+ return [call, argument_failure(call.name, violation, fresh: normalize)]
499
1076
  end
500
1077
  unless call.arguments.is_a?(Hash)
501
- 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)]
502
1080
  end
503
1081
 
504
1082
  prepared, failure = normalize ? normalize_call(tool, call) : [call, nil]
505
1083
  return [prepared, nil] if signal&.aborted?
506
1084
  return [prepared, failure] if failure
507
1085
 
508
- [prepared, validate_call(tool, prepared)]
1086
+ [prepared, validate_call(tool, prepared, fresh: normalize)]
509
1087
  end
510
1088
 
511
1089
  # Tool-result correlation is provider-owned opaque state. If any ID is
@@ -672,7 +1250,7 @@ module Mistri
672
1250
  [call, preparation_failure(call.name, "normalizer", e.class)]
673
1251
  end
674
1252
 
675
- def validate_call(tool, call)
1253
+ def validate_call(tool, call, fresh:)
676
1254
  validator = @external_tool_validators[call.name]
677
1255
  errors = if tool.is_a?(Tool)
678
1256
  TOOL_ARGUMENT_VALIDATOR.bind_call(tool, call.arguments, owned: true)
@@ -682,12 +1260,16 @@ module Mistri
682
1260
  if errors.empty? && !tool.is_a?(Tool) && tool.respond_to?(:prepared_argument_violations)
683
1261
  errors = tool.prepared_argument_violations(call.arguments)
684
1262
  end
685
- errors.empty? ? nil : argument_failure(call.name, *errors)
1263
+ errors.empty? ? nil : argument_failure(call.name, *errors, fresh:)
686
1264
  rescue StandardError => e
687
1265
  preparation_failure(call.name, "validator", e.class)
688
1266
  end
689
1267
 
690
- 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
+
691
1273
  header = "Invalid arguments for tool #{tool_label(name)}:\n"
692
1274
  footer = "\nThe tool did not run. Correct the arguments and try again."
693
1275
  available = MAX_ARGUMENT_ERROR_BYTES - header.bytesize - footer.bytesize
@@ -705,6 +1287,28 @@ module Mistri
705
1287
  ToolResult.new(content: utf8_prefix(content, MAX_ARGUMENT_ERROR_BYTES), error: true)
706
1288
  end
707
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
+
708
1312
  def preparation_failure(name, phase, error_class)
709
1313
  klass = safe_violation(error_class.name || "Exception")
710
1314
  content = "Tool #{tool_label(name)} could not prepare arguments: its argument #{phase} " \
@@ -761,16 +1365,26 @@ module Mistri
761
1365
 
762
1366
  # Runs calls without persisting them; the caller commits and rewrites
763
1367
  # settled results in the model's original call order.
764
- def execute(calls, signal, &emit)
1368
+ def execute(calls, signal, among:, spent: 0, &emit)
765
1369
  return [] if calls.empty?
766
1370
 
767
1371
  ToolExecutor.call_with_outcomes(calls, @tools_by_name, signal: signal,
768
1372
  max_concurrency: @max_concurrency,
769
1373
  session: @session, emit: emit,
770
1374
  app: @context,
1375
+ result_limit_for: limits(among, spent),
1376
+ scratchpad: @scratchpad,
1377
+ compaction: @compaction,
771
1378
  prepared_arguments: true)
772
1379
  end
773
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
+
774
1388
  def interrupt_tool_turn(calls, signal, &)
775
1389
  answer_results(calls, interrupted_results(calls), executed: [], signal:, &)
776
1390
  [[], false]
@@ -814,13 +1428,13 @@ module Mistri
814
1428
 
815
1429
  def rewrite(call, result, context)
816
1430
  rewritten = @after_tool.call(call, result, context) || result
817
- return rewritten unless result.is_a?(ToolResult) && result.error?
1431
+ return rewritten unless result.is_a?(ToolResult)
818
1432
 
819
- if rewritten.is_a?(ToolResult)
820
- rewritten.with(error: true)
821
- else
822
- 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)
823
1436
  end
1437
+ result.error? ? rewritten.with(error: true) : rewritten
824
1438
  rescue EventDelivery::Failure => e
825
1439
  raise EventDelivery.unwrap(e, context.emit)
826
1440
  rescue StandardError => e
@@ -833,42 +1447,126 @@ module Mistri
833
1447
 
834
1448
  def hook_context(signal, emit)
835
1449
  ToolContext.new(session: @session, signal: signal, emit: EventDelivery.wrap(emit),
836
- app: @context)
1450
+ app: @context, scratchpad: @scratchpad,
1451
+ compaction: @compaction)
837
1452
  end
838
1453
 
839
1454
  # The tool message carries both channels; the :tool_result event exposes
840
1455
  # it whole so hosts read event.message.ui for their side of the result.
841
- def answer(call, result, duration: nil, &emit)
842
- content, ui, tool_error = if result.is_a?(ToolResult)
843
- [result.content, result.ui, result.error?]
844
- else
845
- [result, nil, false]
846
- 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)
847
1464
  message = @session.append_message(Message.tool(content: content, tool_call_id: call.id,
848
1465
  tool_name: call.name, ui: ui,
849
- tool_error: tool_error))
1466
+ tool_error: tool_error, loads: loads,
1467
+ cut: cut))
850
1468
  text = content.is_a?(String) ? content : "[content]"
851
1469
  emit&.call(Event.new(type: :tool_result, tool_call: call, content: text,
852
1470
  message: message, duration: duration, tool_error: tool_error))
853
1471
  end
854
1472
 
855
- def answer_results(calls, results, executed:, signal:, &emit)
856
- executed_results = if @after_tool
857
- {}.compare_by_identity.tap do |index|
858
- executed.each { |result| index[result] = true if result[3] }
859
- end
860
- 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)
861
1538
  by_call = {}.compare_by_identity
862
1539
  results.each { |result| (by_call[result[0]] ||= []) << result }
863
- context = hook_context(signal, emit) if @after_tool
864
- calls.each do |call|
865
- queued = by_call[call]
866
- next unless queued && (entry = queued.shift)
1540
+ calls.filter_map { |call| by_call[call]&.shift }
1541
+ end
867
1542
 
868
- _call, result, seconds = entry
869
- result = rewrite(call, result, context) if executed_results&.key?(entry)
870
- answer(call, result, duration: seconds, &emit)
1543
+ def planned_again(turn, rest)
1544
+ turn && result_turn(rest, @result_limit.turn_bytes - turn.left)
1545
+ end
1546
+
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)
871
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) }
872
1570
  end
873
1571
 
874
1572
  def gated?(call)
@@ -901,12 +1599,12 @@ module Mistri
901
1599
  # the signal is what knows the user stopped it. handed_off marks a run
902
1600
  # an ends_turn tool ended, and only a genuinely completed one: a run
903
1601
  # aborted during that same tool phase handed nothing to anyone.
904
- def finished(message, usage, signal = nil, handed_off: false)
1602
+ def finished(message, usage, signal = nil, handed_off: false, said: nil)
905
1603
  status = { StopReason::ABORTED => :aborted, StopReason::BUDGET => :budget,
906
1604
  StopReason::ERROR => :error }.fetch(message.stop_reason, :completed)
907
1605
  status = :aborted if status == :completed && signal&.aborted?
908
1606
  Result.new(message: message, status: status, usage: usage,
909
- handed_off: handed_off && status == :completed)
1607
+ handed_off: handed_off && status == :completed, said:)
910
1608
  end
911
1609
 
912
1610
  def suspended(message, parked, usage)