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
@@ -8,31 +8,50 @@ module Mistri
8
8
  # One JSONL file per session under a directory: durable sessions without
9
9
  # a database, and a transcript any tool can read line by line.
10
10
  class JSONL
11
+ # 249 characters and the extension fill a 255-byte filename.
12
+ SAFE_ID = /\A[A-Za-z0-9_-]{1,249}\z/
13
+ private_constant :SAFE_ID
14
+
11
15
  def initialize(dir)
12
16
  @dir = dir
13
17
  FileUtils.mkdir_p(dir)
14
18
  end
15
19
 
16
20
  # One write call per line: concurrent appenders (a steer, a child's
17
- # report) interleave whole lines, never fragments.
21
+ # report) interleave whole lines, never fragments. A crash's partial last
22
+ # line gets a newline first so it cannot swallow this entry.
18
23
  def append(id, entry)
19
- File.write(path(id), "#{JSON.generate(entry)}\n", mode: "a")
24
+ File.open(path(id), "a+", 0o600) do |file|
25
+ line = "#{JSON.generate(entry)}\n"
26
+ line = "\n#{line}" if file.size.positive? && file.pread(1, file.size - 1) != "\n"
27
+ file.write(line)
28
+ end
20
29
  nil
21
30
  end
22
31
 
23
- def load(id)
32
+ # A partial line from a crash mid-write must not block every later load.
33
+ # It is not an entry, so every line is parsed to count the ones before from.
34
+ def load(id, from: 0)
24
35
  return [] unless File.exist?(path(id))
25
36
 
26
- File.readlines(path(id)).filter_map do |line|
27
- JSON.parse(line) unless line.strip.empty?
37
+ entries = File.readlines(path(id), encoding: Encoding::UTF_8).filter_map do |line|
38
+ JSON.parse(line)
39
+ rescue JSON::ParserError
40
+ nil
28
41
  end
42
+ entries.drop(from)
29
43
  end
30
44
 
45
+ def settled? = true
46
+
31
47
  private
32
48
 
33
- # Session ids become filenames; anything path-hostile is replaced.
49
+ # Session ids become filenames; a sanitized id would alias two sessions
50
+ # onto one file.
34
51
  def path(id)
35
- File.join(@dir, "#{id.to_s.gsub(/[^a-zA-Z0-9_-]/, "-")}.jsonl")
52
+ raise ArgumentError, "unsafe session id #{id.inspect}" unless SAFE_ID.match?(id.to_s)
53
+
54
+ File.join(@dir, "#{id}.jsonl")
36
55
  end
37
56
  end
38
57
  end
@@ -14,12 +14,16 @@ module Mistri
14
14
  nil
15
15
  end
16
16
 
17
- def load(id)
17
+ def load(id, from: 0, to: nil)
18
18
  @mutex.synchronize do
19
- @entries[id].map { |entry| json_copy(entry, freeze: false) }
19
+ @entries[id][from...to].to_a.map { |entry| json_copy(entry, freeze: false) }
20
20
  end
21
21
  end
22
22
 
23
+ def size(id) = @mutex.synchronize { @entries[id].length }
24
+
25
+ def settled? = true
26
+
23
27
  private
24
28
 
25
29
  # Memory must preserve the same value ownership as stores that decode
@@ -58,15 +58,23 @@ module Mistri
58
58
 
59
59
  def run_child_agent(child:, label:, provider:, system:, tools:, task:, schema:,
60
60
  signal:, emit:, agent_options:)
61
- agent = Agent.new(provider: provider, session: child, system: system,
62
- tools: tools, **agent_options)
63
61
  origin = "#{label}##{child.id[0, 8]}"
62
+ agent = Agent.new(provider: provider, session: child, system: system,
63
+ tools: tools, log_label: origin, lease: false,
64
+ **with_own_folder(agent_options, origin))
64
65
  tagged = ->(event) { forward(event, origin, emit) }
65
66
  return agent.task(task, schema: schema, signal: signal, &tagged) if schema
66
67
 
67
68
  agent.run(task, signal: signal, &tagged)
68
69
  end
69
70
 
71
+ def with_own_folder(agent_options, origin)
72
+ shared = agent_options[:scratchpad]
73
+ return agent_options unless shared
74
+
75
+ agent_options.merge(scratchpad: Scratchpad.new(shared).for_worker(origin))
76
+ end
77
+
70
78
  def forward(event, origin, emit)
71
79
  return unless emit
72
80
 
@@ -75,7 +83,7 @@ module Mistri
75
83
  end
76
84
 
77
85
  private :abort_before_child_start!, :execute_child, :forward,
78
- :release_inline_lease, :run_child_agent
86
+ :release_inline_lease, :run_child_agent, :with_own_folder
79
87
  end
80
88
  end
81
89
  end
@@ -6,7 +6,7 @@ module Mistri
6
6
  module ChildAgentOptions
7
7
  ALLOWED = %i[
8
8
  budget max_concurrency transform_context compaction retries skills
9
- before_tool after_tool context
9
+ before_tool after_tool context result_limit files scratchpad sandbox
10
10
  ].freeze
11
11
  private_constant :ALLOWED
12
12
 
@@ -136,6 +136,7 @@ module Mistri
136
136
  validate_provider!(provider, spec["model"])
137
137
  validate_agent_options!(options)
138
138
  ordered = validate_tools!(tools, spec.fetch("tool_names"))
139
+ validate_documents!(options, spec.fetch("tool_names"))
139
140
  Resolved.new(provider: provider, system: system, tools: ordered,
140
141
  schema: schema, agent_options: options)
141
142
  end
@@ -261,6 +262,15 @@ module Mistri
261
262
  "background runtime skills would add tools outside the durable grant"
262
263
  end
263
264
 
265
+ def validate_documents!(options, names)
266
+ return unless options.key?(:files) || options.key?(:scratchpad)
267
+ return if names.include?("read_file")
268
+
269
+ raise ConfigurationError,
270
+ "background runtime files or scratchpad would add tools outside the durable " \
271
+ "grant; grant the document tools the worker may use"
272
+ end
273
+
264
274
  def validate_tools!(tools, expected)
265
275
  unless tools.all?(Tool)
266
276
  raise ConfigurationError, "background runtime tools must be Mistri::Tool instances"
@@ -13,7 +13,7 @@ module Mistri
13
13
  #
14
14
  # researcher = Mistri::SubAgent.new(
15
15
  # name: "researcher", description: "Answers factual questions.",
16
- # provider: Mistri.provider("claude-haiku-4-5-20251001"),
16
+ # provider: Mistri.provider("claude-haiku-5-5"),
17
17
  # system: "Research. Report findings only.", tools: [fetch_page],
18
18
  # )
19
19
  # agent = Mistri::Agent.new(provider:, tools: [researcher.tool])
@@ -73,7 +73,7 @@ module Mistri
73
73
  sub = self
74
74
  blurb = "#{@description} Runs as a focused sub-agent with a clean " \
75
75
  "context: give it complete instructions, it starts blank."
76
- Tool.define(@name, blurb, needs_approval: @gate,
76
+ Tool.define(@name, blurb, needs_approval: @gate, parallel: true,
77
77
  schema: lambda {
78
78
  string :task, "Complete instructions for the sub-agent",
79
79
  required: true
@@ -114,9 +114,19 @@ module Mistri
114
114
  label.empty? ? fallback : label
115
115
  end
116
116
 
117
+ # A worker with no compaction setting of its own starts compacting
118
+ # where its parent does.
119
+ def with_parent_threshold(agent_options, parent_context)
120
+ threshold = parent_context.compaction&.threshold
121
+ return agent_options if threshold.nil? || agent_options.key?(:compaction)
122
+
123
+ agent_options.merge(compaction: Compaction.new(threshold:))
124
+ end
125
+
117
126
  def run_child(label:, provider:, system:, tools:, task:, parent_context:, schema: nil,
118
127
  agent_options: {})
119
128
  ChildAgentOptions.validate!(agent_options)
129
+ agent_options = with_parent_threshold(agent_options, parent_context)
120
130
  store = parent_context.session ? parent_context.session.store : Stores::Memory.new
121
131
  child = Session.new(store: store)
122
132
  parent_context.session&.append("subagent", "name" => label, "session_id" => child.id)
@@ -158,7 +168,7 @@ module Mistri
158
168
  # a queued cancellation or finished retry and returns nil. The runner
159
169
  # retains an acquired lease through terminal persistence and reporting,
160
170
  # suppressing ordinary redelivery while that lease remains live.
161
- # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity -- ordered dispatch transitions are the safety contract
171
+ # rubocop:disable-next Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity -- ordered dispatch transitions are the safety contract
162
172
  def run_dispatched(spec, store:, emit: nil, runtime_factory: nil,
163
173
  provider: UNSET_RUNTIME_FIELD, system: UNSET_RUNTIME_FIELD,
164
174
  tools: UNSET_RUNTIME_FIELD, schema: UNSET_RUNTIME_FIELD,
@@ -248,7 +258,6 @@ module Mistri
248
258
  end
249
259
  raise cleanup_error if cleanup_error && primary_error.nil?
250
260
  end
251
- # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
252
261
 
253
262
  # A child cannot wait for a human, whichever door it entered by: any
254
263
  # calls parked for approval are denied AND settled with the denial as
data/lib/mistri/tool.rb CHANGED
@@ -15,7 +15,12 @@ module Mistri
15
15
  additionalProperties: false
16
16
  }.freeze
17
17
 
18
- attr_reader :name, :description, :input_schema, :timeout
18
+ # instructions is text from the tool's server on how to use its tools. An
19
+ # agent appends it to the conversation as a reminder. instructions_as is
20
+ # the weight it is sent with: :system as every reminder, or :user as text
21
+ # of a user turn on every provider.
22
+ attr_reader :name, :description, :input_schema, :timeout, :instructions, :instructions_as,
23
+ :result_limit
19
24
 
20
25
  # Define a tool. Give the argument shape as a JSON Schema value via
21
26
  # input_schema:, or build it in Ruby with a schema: block. The result is
@@ -33,10 +38,15 @@ module Mistri
33
38
  end
34
39
 
35
40
  def initialize(name:, description:, input_schema: EMPTY_SCHEMA, eager_input_streaming: false,
36
- needs_approval: false, ends_turn: false, timeout: nil,
37
- argument_normalizer: nil, argument_validator: nil,
38
- complete_argument_validator: nil, &handler)
41
+ needs_approval: false, ends_turn: false, timeout: nil, deferred: false,
42
+ instructions: nil, argument_normalizer: nil, argument_validator: nil,
43
+ complete_argument_validator: nil, save_result: true, result_limit: nil,
44
+ parallel: false, instructions_as: :system, &handler)
39
45
  raise ArgumentError, "tool #{name.inspect} needs a handler block" unless handler
46
+ unless %i[system user].include?(instructions_as)
47
+ raise ArgumentError, "instructions_as must be :system or :user"
48
+ end
49
+
40
50
  unless argument_normalizer.nil? || argument_normalizer.respond_to?(:call)
41
51
  raise ArgumentError, "argument_normalizer must be callable"
42
52
  end
@@ -51,8 +61,8 @@ module Mistri
51
61
  "choose argument_validator or complete_argument_validator, not both"
52
62
  end
53
63
 
54
- @name = name.to_s
55
- @description = description
64
+ @name = -name.to_s
65
+ @description = description.is_a?(String) ? -description : description
56
66
  @schema_validator = Schema.tool_validator(
57
67
  input_schema, complete: !complete_argument_validator.nil?
58
68
  )
@@ -61,6 +71,12 @@ module Mistri
61
71
  @needs_approval = needs_approval
62
72
  @ends_turn = ends_turn
63
73
  @timeout = timeout
74
+ @deferred = deferred
75
+ @instructions = instructions
76
+ @instructions_as = instructions_as
77
+ @save_result = save_result
78
+ @parallel = parallel == true
79
+ @result_limit = checked_limit(result_limit)
64
80
  @argument_normalizer = argument_normalizer
65
81
  @argument_validator = argument_validator
66
82
  @complete_argument_validator = complete_argument_validator
@@ -126,15 +142,63 @@ module Mistri
126
142
  @ends_turn
127
143
  end
128
144
 
145
+ # False for a tool that reads in parts itself, as the document tools do,
146
+ # so reading a saved result cannot save another.
147
+ def save_result?
148
+ @save_result
149
+ end
150
+
151
+ # The calls of a turn take effect in the order the model wrote them, so a
152
+ # tool runs alone, after the calls before it. A parallel tool may run at
153
+ # the same time as the parallel calls next to it: its result does not
154
+ # depend on which of them finishes first, and it changes nothing that
155
+ # another call of the turn reads. A tool that starts a worker is marked
156
+ # so that workers start together, and what a worker does is not ordered.
157
+ def parallel?
158
+ @parallel
159
+ end
160
+
161
+ # A deferred tool is not shown to the model until a tool result loads it,
162
+ # so a large set costs nothing until one is needed. An agent that holds
163
+ # any adds the tool_search tool, which finds and loads them.
164
+ def deferred?
165
+ @deferred
166
+ end
167
+
168
+ # The document tool_search indexes for this tool. The block builds it on
169
+ # the first call, so agents that share the tool share the document. It
170
+ # holds no reference to the tool, so a copy of the tool shares it too. A
171
+ # frozen tool that has none builds one for each call.
172
+ def search_document
173
+ return @search_document || yield if frozen?
174
+
175
+ @search_document ||= yield
176
+ end
177
+
129
178
  # The provider-facing definition; every serializer accepts this shape.
130
179
  def spec
131
- definition = { name: @name, description: @description, input_schema: @input_schema }
180
+ definition = { name: @name, description: reviewed_description, input_schema: @input_schema }
132
181
  definition[:eager_input_streaming] = true if @eager_input_streaming
133
182
  definition
134
183
  end
135
184
 
136
185
  private
137
186
 
187
+ # A model that cannot see the gate asks the user in text before calling,
188
+ # and the run never reaches the approval.
189
+ def reviewed_description
190
+ return @description unless @needs_approval
191
+
192
+ review = @needs_approval.respond_to?(:call) ? "may review a call" : "reviews each call"
193
+ "#{@description} A person #{review} before it runs.".lstrip
194
+ end
195
+
196
+ def checked_limit(limit)
197
+ return limit if limit.nil? || (limit.is_a?(Integer) && limit.positive?)
198
+
199
+ raise ArgumentError, "result_limit must be a positive Integer of bytes"
200
+ end
201
+
138
202
  def prepared_context?(context)
139
203
  context.respond_to?(:arguments_prepared?) && context.arguments_prepared?
140
204
  end
@@ -80,8 +80,9 @@ module Mistri
80
80
  # grammar. Counting keys as tokens leaves room for every valid document
81
81
  # under MAX_NODES while stopping wide hostile inputs before JSON.parse.
82
82
  # This byte-state machine must branch on JSON token starts without building a tree.
83
- # rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
84
- def raw_json_resource_error(raw)
83
+ # rubocop:disable-next Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
84
+ def raw_json_resource_error(raw, count_tokens: true)
85
+ limit = count_tokens ? MAX_LEXICAL_TOKENS : Float::INFINITY
85
86
  tokens = 0
86
87
  depth = 0
87
88
  index = 0
@@ -90,12 +91,12 @@ module Mistri
90
91
  case byte
91
92
  when 34
92
93
  tokens += 1
93
- return "too_many_nodes" if tokens > MAX_LEXICAL_TOKENS
94
+ return "too_many_nodes" if tokens > limit
94
95
 
95
96
  index = string_end(raw, index + 1)
96
97
  when 91, 123
97
98
  tokens += 1
98
- return "too_many_nodes" if tokens > MAX_LEXICAL_TOKENS
99
+ return "too_many_nodes" if tokens > limit
99
100
 
100
101
  depth += 1
101
102
  return "too_deep" if depth > MAX_DEPTH + 1
@@ -106,24 +107,24 @@ module Mistri
106
107
  index += 1
107
108
  when 45, 48..57
108
109
  tokens += 1
109
- return "too_many_nodes" if tokens > MAX_LEXICAL_TOKENS
110
+ return "too_many_nodes" if tokens > limit
110
111
 
111
112
  number_start = index
112
113
  index = number_end(raw, index + 1)
113
114
  return "number_too_large" if index - number_start > MAX_NUMBER_BYTES
114
115
  when 116
115
116
  tokens += 1
116
- return "too_many_nodes" if tokens > MAX_LEXICAL_TOKENS
117
+ return "too_many_nodes" if tokens > limit
117
118
 
118
119
  index += raw.byteslice(index, 4) == "true" ? 4 : 1
119
120
  when 102
120
121
  tokens += 1
121
- return "too_many_nodes" if tokens > MAX_LEXICAL_TOKENS
122
+ return "too_many_nodes" if tokens > limit
122
123
 
123
124
  index += raw.byteslice(index, 5) == "false" ? 5 : 1
124
125
  when 110
125
126
  tokens += 1
126
- return "too_many_nodes" if tokens > MAX_LEXICAL_TOKENS
127
+ return "too_many_nodes" if tokens > limit
127
128
 
128
129
  index += raw.byteslice(index, 4) == "null" ? 4 : 1
129
130
  else
@@ -132,7 +133,6 @@ module Mistri
132
133
  end
133
134
  nil
134
135
  end
135
- # rubocop:enable Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
136
136
 
137
137
  def string_end(raw, index)
138
138
  while index < raw.bytesize
@@ -250,9 +250,8 @@ module Mistri
250
250
  within(value, state) do
251
251
  copied = []
252
252
  # Array#map preallocates from an untrusted length before the node ceiling fires.
253
- # rubocop:disable Style/MapIntoArray
253
+ # rubocop:disable-next Style/MapIntoArray
254
254
  value.each { |item| copied << copy(item, state, depth + 1) }
255
- # rubocop:enable Style/MapIntoArray
256
255
  copied.freeze
257
256
  end
258
257
  end
@@ -13,15 +13,27 @@ module Mistri
13
13
  # acting user, a tenant, a request), untouched. The gem provides the
14
14
  # slot, never the vocabulary:
15
15
  #
16
- # agent = Mistri.agent("claude-opus-4-8", tools: tools,
16
+ # agent = Mistri.agent("claude-opus-5-5", tools: tools,
17
17
  # context: { traveler: current_traveler })
18
18
  # Mistri::Tool.define("book_hotel", "Books the chosen hotel.", schema: -> {
19
19
  # string :hotel_id, "Hotel ID", required: true
20
20
  # }) do |args, context|
21
21
  # Bookings.create(args.fetch("hotel_id"), traveler: context.app[:traveler])
22
22
  # end
23
- ToolContext = Data.define(:session, :signal, :emit, :app) do
24
- def initialize(session: nil, signal: nil, emit: nil, app: nil)
23
+ #
24
+ # result_limit is the bytes a result of this call keeps before it is cut,
25
+ # or nil where nothing is cut, so a tool that reads in parts can size a part.
26
+ #
27
+ # scratchpad is the agent's Scratchpad, or nil when it has none. A tool that
28
+ # is handed bytes a model cannot read keeps them there with save_binary and
29
+ # answers with the path.
30
+ #
31
+ # compaction is the agent's Compaction, or nil when it has none. A worker
32
+ # with no setting of its own takes its threshold from it.
33
+ ToolContext = Data.define(:session, :signal, :emit, :app, :result_limit, :scratchpad,
34
+ :compaction) do
35
+ def initialize(session: nil, signal: nil, emit: nil, app: nil, result_limit: nil,
36
+ scratchpad: nil, compaction: nil)
25
37
  super
26
38
  end
27
39
  end
@@ -3,10 +3,13 @@
3
3
  require "timeout"
4
4
 
5
5
  module Mistri
6
- # Runs a turn's tool calls and returns their results in the order the model
7
- # emitted them, regardless of completion order. Independent calls run
8
- # concurrently up to max_concurrency; each runs inside the Rails executor
9
- # when Rails is present, so ActiveRecord connections return to the pool.
6
+ # Runs the calls of one step of a turn together and returns their results
7
+ # in the order the model emitted them, regardless of completion order.
8
+ # CallOrder decides which calls share a step. Several calls run on up to
9
+ # max_concurrency threads, each inside the Rails executor when Rails is
10
+ # present, so their ActiveRecord connections return to the pool. One call
11
+ # runs on the calling thread, inside the caller's executor when one is
12
+ # active.
10
13
  #
11
14
  # A tool that fails becomes an in-band ToolResult with an explicit error
12
15
  # fact. An abort never starts a not-yet-started call: it gets an interrupted
@@ -32,8 +35,12 @@ module Mistri
32
35
 
33
36
  module_function
34
37
 
38
+ # Code that runs inside a tool and keeps a caller's errors from ending the
39
+ # call lets this one pass, or the call loses its limit.
40
+ def deadline?(error) = error.is_a?(InvocationTimeout)
41
+
35
42
  def call(calls, tools_by_name, signal: nil, max_concurrency: 4, session: nil, emit: nil,
36
- app: nil)
43
+ app: nil, result_limit_for: nil, scratchpad: nil, compaction: nil)
37
44
  call_with_outcomes(
38
45
  calls,
39
46
  tools_by_name,
@@ -42,6 +49,9 @@ module Mistri
42
49
  session:,
43
50
  emit:,
44
51
  app:,
52
+ result_limit_for:,
53
+ scratchpad:,
54
+ compaction:,
45
55
  prepared_arguments: false
46
56
  ).map { |call, result, seconds, _committed| [call, result, seconds] }
47
57
  end
@@ -50,19 +60,23 @@ module Mistri
50
60
  # lower-level form preserves that boundary and exposes commitment so hooks
51
61
  # cannot run for queued calls that an abort prevented from starting.
52
62
  def call_with_outcomes(calls, tools_by_name, signal: nil, max_concurrency: 4, session: nil,
53
- emit: nil, app: nil, prepared_arguments: false)
63
+ emit: nil, app: nil, result_limit_for: nil, scratchpad: nil,
64
+ compaction: nil, prepared_arguments: false)
54
65
  return [] if calls.empty?
55
66
 
56
67
  delivery = EventDelivery.wrap(emit, passthrough: [InvocationTimeout])
57
68
  context_class = prepared_arguments ? PreparedContext : ToolContext
58
69
  context = context_class.new(session: session, signal: signal,
59
- emit: thread_safe(delivery, signal), app: app)
70
+ emit: thread_safe(delivery, signal), app: app,
71
+ scratchpad: scratchpad, compaction: compaction)
60
72
  results = Array.new(calls.length)
61
73
  queue = Queue.new
62
74
  errors = Queue.new
63
- calls.each_with_index { |call, index| queue << [call, index] }
64
- workers = max_concurrency.clamp(1, calls.length)
65
- Array.new(workers) { worker(queue, results, tools_by_name, context, errors) }.each(&:join)
75
+ calls.each_with_index do |call, index|
76
+ queue << [call, index, context.with(result_limit: result_limit_for&.call(call))]
77
+ end
78
+ run_queue(queue, results, tools_by_name, context, errors,
79
+ workers: max_concurrency.clamp(1, calls.length), alone: calls.length == 1)
66
80
  unless errors.empty?
67
81
  error = errors.pop
68
82
  raise EventDelivery.unwrap(error, delivery)
@@ -76,26 +90,35 @@ module Mistri
76
90
  end
77
91
  end
78
92
 
79
- def worker(queue, results, tools_by_name, context, errors)
80
- Thread.new do
81
- loop do
82
- break unless errors.empty?
93
+ # A thread that waits on a worker holds its share of Rails' load lock
94
+ # while the worker asks for one, which hangs a reload in development. One
95
+ # call needs no worker.
96
+ def run_queue(queue, results, tools_by_name, context, errors, workers:, alone:)
97
+ return drain(queue, results, tools_by_name, context, errors) if alone
83
98
 
84
- call, index = begin
85
- queue.pop(true)
86
- rescue ThreadError
87
- break
88
- end
89
- if context.signal&.aborted?
90
- results[index] = [failure(INTERRUPTED), nil, false]
91
- next
92
- end
99
+ Array.new(workers) do
100
+ Thread.new { drain(queue, results, tools_by_name, context, errors) }
101
+ end.each(&:join)
102
+ end
93
103
 
94
- results[index] = run_one(call, index, results, tools_by_name, context)
104
+ def drain(queue, results, tools_by_name, context, errors)
105
+ loop do
106
+ break unless errors.empty?
107
+
108
+ call, index, own = begin
109
+ queue.pop(true)
110
+ rescue ThreadError
111
+ break
112
+ end
113
+ if context.signal&.aborted?
114
+ results[index] = [failure(INTERRUPTED), nil, false]
115
+ next
95
116
  end
96
- rescue StandardError => e
97
- errors << e
117
+
118
+ results[index] = run_one(call, index, results, tools_by_name, own)
98
119
  end
120
+ rescue StandardError => e
121
+ errors << e
99
122
  end
100
123
 
101
124
  def run_one(call, index, results, tools_by_name, context)
@@ -14,11 +14,17 @@ module Mistri
14
14
  #
15
15
  # ui must be JSON-serializable; it is stored and delivered in canonical
16
16
  # JSON form (string keys), the same shape a reloaded session reads.
17
- ToolResult = Data.define(:content, :ui, :error) do
18
- def initialize(content:, ui: nil, error: false)
17
+ #
18
+ # loads names deferred tools this result makes available: the model can
19
+ # call them from its next step, in this run and in later ones.
20
+ ToolResult = Data.define(:content, :ui, :error, :loads) do
21
+ def initialize(content:, ui: nil, error: false, loads: nil)
19
22
  unless [true, false].include?(error)
20
23
  raise ArgumentError, "tool result error must be true or false"
21
24
  end
25
+ unless loads.nil? || Message.names?(loads)
26
+ raise ArgumentError, "tool result loads must be an array of tool names"
27
+ end
22
28
 
23
29
  super
24
30
  end