mistri 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +321 -2
  3. data/CONTRIBUTING.md +17 -3
  4. data/NOTICE +11 -0
  5. data/README.md +145 -284
  6. data/UPGRADING.md +810 -0
  7. data/assets/vendors/README.md +12 -0
  8. data/assets/vendors/claude-mark.svg +3 -0
  9. data/assets/vendors/gemini-mark.svg +10 -0
  10. data/assets/vendors/openai-mark-dark.svg +1 -0
  11. data/assets/vendors/openai-mark.svg +1 -0
  12. data/docs/README.md +2 -1
  13. data/docs/context-and-workspaces.md +84 -13
  14. data/docs/logging.md +90 -0
  15. data/docs/mcp.md +762 -21
  16. data/docs/reliability.md +210 -24
  17. data/docs/sessions.md +415 -36
  18. data/docs/sub-agents.md +85 -7
  19. data/docs/tool-contracts.md +528 -13
  20. data/examples/approval.rb +7 -7
  21. data/examples/browser.rb +1 -1
  22. data/examples/page_editor.rb +2 -2
  23. data/examples/quickstart.rb +1 -1
  24. data/lib/generators/mistri/install/templates/migration.rb.tt +4 -2
  25. data/lib/generators/mistri/mcp/mcp_generator.rb +2 -2
  26. data/lib/generators/mistri/mcp/templates/model.rb.tt +21 -8
  27. data/lib/mistri/agent.rb +815 -180
  28. data/lib/mistri/call_order.rb +137 -0
  29. data/lib/mistri/child.rb +69 -13
  30. data/lib/mistri/compaction.rb +200 -35
  31. data/lib/mistri/compactor/text.rb +91 -0
  32. data/lib/mistri/compactor.rb +474 -117
  33. data/lib/mistri/console.rb +44 -11
  34. data/lib/mistri/content.rb +70 -3
  35. data/lib/mistri/definition.rb +2 -2
  36. data/lib/mistri/edit.rb +13 -7
  37. data/lib/mistri/errors.rb +37 -0
  38. data/lib/mistri/event.rb +20 -9
  39. data/lib/mistri/locks/rails_cache.rb +16 -2
  40. data/lib/mistri/locks.rb +12 -3
  41. data/lib/mistri/mcp/client.rb +247 -61
  42. data/lib/mistri/mcp/conversation.rb +161 -0
  43. data/lib/mistri/mcp/egress.rb +5 -4
  44. data/lib/mistri/mcp/mirror.rb +90 -0
  45. data/lib/mistri/mcp/negotiation.rb +222 -0
  46. data/lib/mistri/mcp/oauth/client_identity.rb +53 -0
  47. data/lib/mistri/mcp/oauth/tolerance.rb +61 -0
  48. data/lib/mistri/mcp/oauth.rb +303 -82
  49. data/lib/mistri/mcp/results.rb +97 -0
  50. data/lib/mistri/mcp/sdk_client.rb +47 -0
  51. data/lib/mistri/mcp/wires.rb +325 -52
  52. data/lib/mistri/mcp.rb +304 -55
  53. data/lib/mistri/memory.rb +1 -1
  54. data/lib/mistri/message.rb +45 -8
  55. data/lib/mistri/models.rb +146 -24
  56. data/lib/mistri/partial_json.rb +5 -5
  57. data/lib/mistri/providers/anthropic/assembler.rb +40 -3
  58. data/lib/mistri/providers/anthropic/serializer.rb +154 -22
  59. data/lib/mistri/providers/anthropic.rb +77 -12
  60. data/lib/mistri/providers/fake.rb +4 -1
  61. data/lib/mistri/providers/gemini/assembler.rb +63 -3
  62. data/lib/mistri/providers/gemini/serializer.rb +27 -16
  63. data/lib/mistri/providers/gemini.rb +56 -11
  64. data/lib/mistri/providers/openai/assembler.rb +36 -5
  65. data/lib/mistri/providers/openai/serializer.rb +76 -22
  66. data/lib/mistri/providers/openai.rb +91 -14
  67. data/lib/mistri/reminder.rb +35 -3
  68. data/lib/mistri/result.rb +6 -4
  69. data/lib/mistri/result_limit.rb +164 -0
  70. data/lib/mistri/sandbox/quickjs.rb +345 -0
  71. data/lib/mistri/sandbox.rb +18 -0
  72. data/lib/mistri/schema.rb +26 -2
  73. data/lib/mistri/scratchpad.rb +107 -0
  74. data/lib/mistri/session/log.rb +137 -0
  75. data/lib/mistri/session.rb +405 -75
  76. data/lib/mistri/sinks/logger.rb +17 -11
  77. data/lib/mistri/skills.rb +10 -4
  78. data/lib/mistri/spawner.rb +43 -12
  79. data/lib/mistri/sse.rb +3 -2
  80. data/lib/mistri/stores/active_record.rb +30 -6
  81. data/lib/mistri/stores/jsonl.rb +26 -7
  82. data/lib/mistri/stores/memory.rb +6 -2
  83. data/lib/mistri/sub_agent/execution.rb +10 -2
  84. data/lib/mistri/sub_agent/runtime.rb +11 -1
  85. data/lib/mistri/sub_agent.rb +13 -4
  86. data/lib/mistri/tool.rb +71 -7
  87. data/lib/mistri/tool_arguments.rb +10 -11
  88. data/lib/mistri/tool_context.rb +15 -3
  89. data/lib/mistri/tool_executor.rb +49 -26
  90. data/lib/mistri/tool_result.rb +8 -2
  91. data/lib/mistri/tool_search/index.rb +193 -0
  92. data/lib/mistri/tool_search.rb +200 -0
  93. data/lib/mistri/tools/delete_file.rb +22 -0
  94. data/lib/mistri/tools/edit_file.rb +24 -14
  95. data/lib/mistri/tools/find_in_file.rb +1 -0
  96. data/lib/mistri/tools/grep.rb +212 -0
  97. data/lib/mistri/tools/list_files.rb +38 -5
  98. data/lib/mistri/tools/read_file.rb +83 -21
  99. data/lib/mistri/tools/read_memory.rb +2 -1
  100. data/lib/mistri/tools/run_code.rb +167 -0
  101. data/lib/mistri/tools/write_file.rb +66 -9
  102. data/lib/mistri/tools.rb +72 -1
  103. data/lib/mistri/transport/streamable_http.rb +140 -0
  104. data/lib/mistri/transport.rb +53 -63
  105. data/lib/mistri/usage.rb +33 -4
  106. data/lib/mistri/version.rb +1 -1
  107. data/lib/mistri/workspace/active_record.rb +22 -10
  108. data/lib/mistri/workspace/directory.rb +5 -1
  109. data/lib/mistri/workspace/memory.rb +4 -0
  110. data/lib/mistri/workspace/path_space.rb +56 -0
  111. data/lib/mistri/workspace/single.rb +6 -1
  112. data/lib/mistri.rb +10 -4
  113. metadata +29 -2
@@ -39,7 +39,8 @@ module Mistri
39
39
  tool_started: :tool_line, tool_result: :tool_result_line,
40
40
  done: :turn_line, error: :error_line, retry: :retry_line,
41
41
  approval_needed: :approval_line, compacting: :compacting_line,
42
- compaction: :compaction_line, subagent_report: :report_line }.freeze
42
+ compaction: :compaction_line, compaction_failed: :compaction_failed_line,
43
+ subagent_report: :report_line, thinking_dropped: :thinking_dropped_line }.freeze
43
44
  QUIET = %i[text_end thinking_end tool_started done approval_needed
44
45
  compacting compaction subagent_report].to_h { |type| [type, true] }.freeze
45
46
  COLORS = { bold: "1", dim: "2", red: "31", green: "32", yellow: "33" }.freeze
@@ -182,15 +183,12 @@ module Mistri
182
183
  # failures alarm. A budget stop is synthetic (no provider call), so
183
184
  # it alone does not count as a turn.
184
185
  def error_line(event)
185
- case event.reason
186
- when StopReason::BUDGET then ["stopped on budget", :warn]
187
- when StopReason::ABORTED
188
- @turns += 1
189
- "aborted"
190
- else
191
- @turns += 1
192
- ["#{paint("error", :red)} #{event.reason}#{note(event.error_message)}", :error]
193
- end
186
+ return ["stopped on budget", :warn] if event.reason == StopReason::BUDGET
187
+
188
+ @turns += 1
189
+ return "aborted" if event.reason == StopReason::ABORTED
190
+
191
+ ["#{paint("error", :red)} #{event.reason}#{note(event.error_message)}", :error]
194
192
  end
195
193
 
196
194
  def retry_line(event)
@@ -210,7 +208,15 @@ module Mistri
210
208
 
211
209
  def compacting_line(_event) = "compacting"
212
210
 
213
- def compaction_line(event) = "compacted #{body_of(event.content)}"
211
+ def compaction_line(event) = "compacted#{summarizer(event.message)} #{body_of(event.content)}"
212
+
213
+ def summarizer(message) = message&.model ? " (#{field(message.model)})" : ""
214
+
215
+ def compaction_failed_line(event)
216
+ ["#{paint("compaction failed", :yellow)}#{note(event.error_message)}", :warn]
217
+ end
218
+
219
+ def thinking_dropped_line(event) = ["thinking dropped: #{field(event.content)}", :warn]
214
220
 
215
221
  def report_line(event)
216
222
  "worker #{field(event.agent)} (#{field(event.session_id.to_s[0, 8], limit: 16)}) " \
data/lib/mistri/skills.rb CHANGED
@@ -6,6 +6,8 @@ module Mistri
6
6
  # the read_skill tool, so a large library costs almost nothing until a
7
7
  # skill is actually used.
8
8
  module Skills
9
+ READER = "read_skill"
10
+
9
11
  module_function
10
12
 
11
13
  # Reads a directory of skills in either layout: <dir>/<name>/SKILL.md
@@ -14,7 +16,7 @@ module Mistri
14
16
  def load(path)
15
17
  raise ConfigurationError, "no skills directory at #{path}" unless File.directory?(path)
16
18
 
17
- skills = Dir.children(path).sort.filter_map do |child|
19
+ skills = Dir.children(path, encoding: Encoding::UTF_8).sort.filter_map do |child|
18
20
  full = File.join(path, child)
19
21
  if File.directory?(full) && File.file?(File.join(full, "SKILL.md"))
20
22
  read(File.join(full, "SKILL.md"), default_name: child)
@@ -26,7 +28,7 @@ module Mistri
26
28
  end
27
29
 
28
30
  def read(file, default_name:)
29
- meta, body = parse(File.read(file))
31
+ meta, body = parse(File.read(file, encoding: Encoding::UTF_8))
30
32
  Skill.new(name: meta.fetch("name", default_name),
31
33
  description: meta.fetch("description", ""), body: body)
32
34
  end
@@ -53,12 +55,16 @@ module Mistri
53
55
 
54
56
  def reader(skills)
55
57
  by_name = skills.to_h { |skill| [skill.name, skill] }
56
- Tool.define("read_skill", "Reads the full playbook for a named skill.",
58
+ Tool.define(READER, "Reads the full playbook for a named skill.",
59
+ result_limit: ResultLimit::DEFAULT_BYTES, parallel: true,
57
60
  schema: -> { string :name, "Skill name", required: true }) do |args|
58
61
  skill = by_name[args["name"]]
59
62
  next skill.body if skill
60
63
 
61
- "Unknown skill #{args["name"].inspect}. Available: #{by_name.keys.join(", ")}"
64
+ ToolResult.new(
65
+ content: "Unknown skill #{args["name"].inspect}. Available: #{by_name.keys.join(", ")}",
66
+ error: true
67
+ )
62
68
  end
63
69
  end
64
70
 
@@ -37,7 +37,7 @@ module Mistri
37
37
 
38
38
  def tool
39
39
  spawner = self
40
- Tool.define("spawn_agent", description, needs_approval: @needs_approval,
40
+ Tool.define("spawn_agent", description, needs_approval: @needs_approval, parallel: true,
41
41
  schema: schema) do |args, context|
42
42
  spawner.spawn(args, context)
43
43
  end
@@ -55,11 +55,19 @@ module Mistri
55
55
  SubAgent.run_child(label: label_for(args), provider: provider_for(worker),
56
56
  system: worker[:system], tools: worker[:tools],
57
57
  task: args.fetch("task"), parent_context: context,
58
- agent_options: @agent_options)
58
+ agent_options: options_within(worker[:tools]))
59
59
  end
60
60
 
61
61
  private
62
62
 
63
+ # An agent with documents and no read_file adds the document tools itself,
64
+ # which a spawn that did not grant read_file never gave.
65
+ def options_within(granted)
66
+ return @agent_options if granted.any? { |tool| tool.name == "read_file" }
67
+
68
+ @agent_options.except(:files, :scratchpad)
69
+ end
70
+
63
71
  def validate_configuration!(tools, models, dispatcher, runtime_factory)
64
72
  validate_tool_pool!(tools)
65
73
  validate_models!(models)
@@ -255,15 +263,21 @@ module Mistri
255
263
 
256
264
  by_name = @pool.to_h { |tool| [tool.name, tool] }
257
265
  names.map do |name|
258
- by_name.fetch(name) do
259
- raise ArgumentError,
260
- "unknown tool #{name.inspect}; available: #{by_name.keys.join(", ")}"
261
- end
266
+ by_name.fetch(name) { raise ArgumentError, "unknown tool #{name.inspect}; #{available}" }
262
267
  end
263
268
  end
264
269
 
270
+ # The pool as an error result lists it. Deferred tools are counted, not
271
+ # named.
272
+ def available
273
+ later, ready = @pool.partition(&:deferred?)
274
+ listed = ready.map(&:name)
275
+ listed << "tools that load on demand: #{later.length}" if later.any?
276
+ "available: #{listed.join(", ")}"
277
+ end
278
+
265
279
  def schema
266
- pool_names = @pool.map(&:name)
280
+ granting = tools_argument
267
281
  type_names = ["general-purpose", *@types.keys]
268
282
  types = @types
269
283
  models = @models
@@ -280,11 +294,7 @@ module Mistri
280
294
  else
281
295
  string :instructions, "The child's system prompt", required: true
282
296
  end
283
- if pool_names.any?
284
- array :tools, "Exact tools to grant (omit for all, or the type's own list; " \
285
- "an empty list grants none)",
286
- items: { type: "string", enum: pool_names }, uniqueItems: true
287
- end
297
+ array :tools, granting.first, items: granting.last, uniqueItems: true if granting
288
298
  string :model, "Model for the child#{fallback}", enum: models if models.any?
289
299
  if dispatcher
290
300
  string :mode, "inline blocks until the report; background returns a receipt " \
@@ -294,6 +304,27 @@ module Mistri
294
304
  end
295
305
  end
296
306
 
307
+ # The description and item schema of the tools argument. For a pool that
308
+ # holds deferred tools, the description names only the tools that are not
309
+ # deferred.
310
+ def tools_argument
311
+ names = @pool.map(&:name)
312
+ return if names.empty?
313
+
314
+ ready = @pool.reject(&:deferred?).map(&:name)
315
+ text = "Exact tools to grant (omit for all, or the type's own list; an empty list " \
316
+ "grants none)"
317
+ return [text, { type: "string", enum: names }] if ready.length == names.length
318
+
319
+ pool = if ready.empty?
320
+ "Every tool of the pool loads on demand"
321
+ else
322
+ "Available without loading: #{ready.join(", ")}. The others load on demand"
323
+ end
324
+ ["#{text}. #{pool}: grant one by its exact name, or omit tools and the child loads " \
325
+ "what it needs.", { type: "string" }]
326
+ end
327
+
297
328
  def description
298
329
  text = SubAgent::SPAWNER_DESCRIPTION
299
330
  unless @types.empty?
data/lib/mistri/sse.rb CHANGED
@@ -17,12 +17,13 @@ module Mistri
17
17
  # fails to parse is skipped rather than killing a live stream. Only the
18
18
  # partial line is bounded; the complete stream is not.
19
19
  class SSE
20
- def initialize(max_record_bytes: DEFAULT_MAX_RECORD_BYTES)
20
+ def initialize(max_record_bytes: DEFAULT_MAX_RECORD_BYTES, count_tokens: false)
21
21
  unless max_record_bytes.is_a?(Integer) && max_record_bytes.positive?
22
22
  raise ConfigurationError, "max_record_bytes: must be a positive integer"
23
23
  end
24
24
 
25
25
  @max_record_bytes = max_record_bytes
26
+ @count_tokens = count_tokens
26
27
  @buffer = +""
27
28
  end
28
29
 
@@ -70,7 +71,7 @@ module Mistri
70
71
  line.strip!
71
72
  return if line.empty? || line == "[DONE]"
72
73
 
73
- case ToolArguments.raw_json_resource_error(line)
74
+ case ToolArguments.raw_json_resource_error(line, count_tokens: @count_tokens)
74
75
  when "too_many_nodes"
75
76
  raise ResponseTooComplexError.new(kind: :sse_record_tokens,
76
77
  limit: ToolArguments::MAX_LEXICAL_TOKENS)
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require_relative "../errors"
4
5
 
5
6
  module Mistri
6
7
  module Stores
@@ -9,11 +10,11 @@ module Mistri
9
10
  # Postgres, whatever the app runs. Not auto-required; load it with
10
11
  # require "mistri/stores/active_record".
11
12
  #
12
- # The model needs three columns: session_id (string, indexed), position
13
+ # The model needs three columns: session_id (string), position
13
14
  # (integer), payload (text). A migration to copy:
14
15
  #
15
16
  # create_table :mistri_entries do |t|
16
- # t.string :session_id, null: false, index: true
17
+ # t.string :session_id, null: false
17
18
  # t.integer :position, null: false
18
19
  # t.text :payload, size: :long, null: false
19
20
  # t.timestamps
@@ -57,13 +58,36 @@ module Mistri
57
58
  # a cached read would never see a child's report land. Read past it.
58
59
  # Only past Rails' cache: an open REPEATABLE READ transaction still
59
60
  # pins its snapshot, so never poll from inside one.
60
- def load(id)
61
+ def load(id, from: 0, to: nil)
61
62
  @model.uncached do
62
- @model.where(session_id: id).pluck(:position, :payload)
63
- .sort_by(&:first)
64
- .map { |_position, payload| JSON.parse(payload) }
63
+ rows = @model.where(session_id: id, position: (from + 1)..to)
64
+ .pluck(:position, :payload).sort_by(&:first)
65
+ verify_positions(id, rows, from)
66
+ rows.map { |_position, payload| JSON.parse(payload) }
65
67
  end
66
68
  end
69
+
70
+ def size(id)
71
+ @model.uncached { @model.where(session_id: id).maximum(:position).to_i }
72
+ end
73
+
74
+ # Inside a transaction a read can be rolled back or pinned to an older
75
+ # snapshot, so a session reads fresh there and holds nothing.
76
+ # The pool lends a connection for the question; asking the model for its
77
+ # connection would keep one checked out for the rest of the run.
78
+ def settled? = !@model.connection_pool.with_connection(&:transaction_open?)
79
+
80
+ private
81
+
82
+ # An entry's place in the log is its position minus one, so the rows of
83
+ # one read must sit at consecutive positions from the one asked for.
84
+ def verify_positions(id, rows, from)
85
+ return if rows.empty?
86
+ return if rows.first.first == from + 1 && rows.last.first == from + rows.length
87
+
88
+ raise ConfigurationError, "session #{id.inspect} has entries that are not at " \
89
+ "consecutive positions in the store"
90
+ end
67
91
  end
68
92
  end
69
93
  end
@@ -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
@@ -60,13 +60,21 @@ module Mistri
60
60
  signal:, emit:, agent_options:)
61
61
  origin = "#{label}##{child.id[0, 8]}"
62
62
  agent = Agent.new(provider: provider, session: child, system: system,
63
- tools: tools, log_label: origin, **agent_options)
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