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
@@ -0,0 +1,407 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Mistri
6
+ module Sinks
7
+ # Renders the event stream as one log line per meaningful beat, so a
8
+ # log tells each run's whole story: which tools ran with which
9
+ # arguments, how long each took, what every turn cost, and how the run
10
+ # ended. Deltas never log (whole blocks do).
11
+ #
12
+ # Assigning Mistri.logger turns this on for every run in one line:
13
+ #
14
+ # Mistri.logger = Rails.logger
15
+ # Mistri.logger = Mistri::Sinks::Logger.new(logger, color: true)
16
+ #
17
+ # Payloads (inputs, text, thinking, arguments, results, reports) log in
18
+ # full by default; content: false keeps the same story with metadata
19
+ # only, for logs whose payloads must stay out. level: floors the
20
+ # ordinary lines (warnings and errors keep their own levels).
21
+ #
22
+ # Sinks the Agent builds through for_session skip origin-tagged events,
23
+ # because every agent logs its own events under its own tag: exactly
24
+ # once, however deep the nesting and whichever process runs it. A sink
25
+ # composed directly (agent.run(input, &sink)) is the only logger its
26
+ # run has, so it renders forwarded child events instead, origin first;
27
+ # framing (run, done) still comes only from the Agent.
28
+ #
29
+ # Any object responding to info/warn/error works. Logging must never
30
+ # break a run: every entry point rescues, the first failure warns, and
31
+ # the sink goes quiet for the rest of its run. Tool events arrive from
32
+ # executor threads; the only mutable state (the turn counter) moves on
33
+ # loop-thread events, and interleaved lines stay whole as long as the
34
+ # host's logger serializes writes, which stdlib Logger and Rails do.
35
+ class Logger
36
+ SKIPPED = %i[start text_start text_delta thinking_start thinking_delta
37
+ toolcall_start toolcall_delta toolcall_end].to_h { |type| [type, true] }.freeze
38
+ LINES = { text_end: :text_line, thinking_end: :thinking_line,
39
+ tool_started: :tool_line, tool_result: :tool_result_line,
40
+ done: :turn_line, error: :error_line, retry: :retry_line,
41
+ approval_needed: :approval_line, compacting: :compacting_line,
42
+ compaction: :compaction_line, compaction_failed: :compaction_failed_line,
43
+ subagent_report: :report_line, thinking_dropped: :thinking_dropped_line }.freeze
44
+ QUIET = %i[text_end thinking_end tool_started done approval_needed
45
+ compacting compaction subagent_report].to_h { |type| [type, true] }.freeze
46
+ COLORS = { bold: "1", dim: "2", red: "31", green: "32", yellow: "33" }.freeze
47
+ LEVELS = %i[debug info warn error].freeze
48
+ # C0 and C1 controls, DEL, Unicode line and paragraph separators, and
49
+ # bidi embedding controls: everything that could steer a terminal or
50
+ # forge a line while staying invisible.
51
+ HIDDEN = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/
52
+ HEAD = 4096
53
+ private_constant :SKIPPED, :LINES, :QUIET, :COLORS, :LEVELS, :HIDDEN, :HEAD
54
+
55
+ # truncate bounds every rendered value (nil for full payloads).
56
+ # session is the line tag, verbatim, so concurrent runs stay
57
+ # distinguishable. Options are validated here so a bad configuration
58
+ # fails at assignment time, not silently at run time.
59
+ def initialize(logger, session: nil, truncate: 200, color: false, level: :info,
60
+ content: true, forwarded: :render)
61
+ raise ArgumentError, "level must be one of #{LEVELS.join(", ")}" unless
62
+ LEVELS.include?(level)
63
+ unless truncate.nil? || (truncate.is_a?(Integer) && truncate.positive?)
64
+ raise ArgumentError, "truncate must be a positive Integer or nil"
65
+ end
66
+ raise ArgumentError, "forwarded must be :render or :skip" unless
67
+ %i[render skip].include?(forwarded)
68
+
69
+ @logger = logger
70
+ @truncate = truncate
71
+ @color = color
72
+ @level = level
73
+ @content = content
74
+ @forwarded = forwarded
75
+ @session = session && field(session, limit: 48)
76
+ @turns = 0
77
+ @started = now
78
+ @warned = false
79
+ @tag = paint(@session ? "[mistri #{@session}]" : "[mistri]", :dim)
80
+ end
81
+
82
+ # A fresh sink for one run: same logger and options, this run's tag
83
+ # (a sub-agent's label, or the session id), its own turn count and
84
+ # clock. Runs framed this way skip forwarded events, because each
85
+ # agent in the tree logs its own.
86
+ def for_session(id, label: nil)
87
+ self.class.new(@logger, session: label || id.to_s[0, 8], truncate: @truncate,
88
+ color: @color, level: @level, content: @content, forwarded: :skip)
89
+ end
90
+
91
+ # The global hookup: builds this run's sink from Mistri.logger, or
92
+ # nil. Contained, so a broken assignment costs the log, never the run.
93
+ def self.attach(id, label: nil)
94
+ configured = Mistri.logger
95
+ return nil unless configured
96
+
97
+ sink = configured.is_a?(self) ? configured : new(configured)
98
+ sink.for_session(id, label: label)
99
+ rescue StandardError => e
100
+ warn "mistri: logging sink construction failed (#{e.class}: #{e.message}); run not logged"
101
+ nil
102
+ end
103
+
104
+ def call(event)
105
+ return if @warned
106
+
107
+ return if event.origin && (@forwarded == :skip)
108
+ return if SKIPPED[event.type]
109
+ return if QUIET[event.type] && !floor_enabled?
110
+
111
+ handler = LINES[event.type]
112
+ prefix = event.origin ? "#{field(event.origin)} " : ""
113
+ # Future event types degrade to a greppable line, never to silence.
114
+ line = handler ? send(handler, event) : "#{event.type} #{body_of(event.content)}".rstrip
115
+ write("#{prefix}#{line.first}", level: line.last) if line.is_a?(Array)
116
+ write("#{prefix}#{line}") if line.is_a?(String)
117
+ rescue StandardError => e
118
+ quiet(e)
119
+ end
120
+
121
+ def to_proc = method(:call).to_proc
122
+
123
+ # The framing the stream cannot carry: the Agent calls these around a
124
+ # run with the input, the model, and the final Result. Each is total
125
+ # for the same reason call is: a logging failure inside a rescue
126
+ # block must never replace the host's own exception.
127
+ def run_started(verb:, model:, tool_count:, input: nil)
128
+ @turns = 0
129
+ @started = now
130
+ return unless floor_enabled?
131
+
132
+ ask = input && @content ? %( "#{trim(input)}") : ""
133
+ write("#{paint(verb, :bold)}#{ask} (#{field(model)}, #{count(tool_count, "tool")})")
134
+ rescue StandardError => e
135
+ quiet(e)
136
+ end
137
+
138
+ def run_finished(result)
139
+ status, level = status_of(result)
140
+ return if level == :info && !floor_enabled?
141
+
142
+ write("#{paint("done", :bold)} #{status} in #{clock(now - @started)}, " \
143
+ "#{count(@turns, "turn")}#{summary(result.usage)}", level: level)
144
+ rescue StandardError => e
145
+ quiet(e)
146
+ end
147
+
148
+ def run_crashed(error)
149
+ write("#{paint("crashed", :red)} #{error.class}#{note(error.message)}", level: :error)
150
+ rescue StandardError => e
151
+ quiet(e)
152
+ end
153
+
154
+ private
155
+
156
+ def text_line(event)
157
+ body = body_of(event.content)
158
+ body.empty? ? nil : "text #{body}"
159
+ end
160
+
161
+ def thinking_line(event)
162
+ body = body_of(event.content)
163
+ body.empty? ? nil : "thinking #{body}"
164
+ end
165
+
166
+ def tool_line(event)
167
+ "tool #{title(event.tool_call)} #{arguments(event.tool_call)}".rstrip
168
+ end
169
+
170
+ def tool_result_line(event)
171
+ verdict = event.tool_error? ? paint("FAILED", :red) : "ok"
172
+ parts = ["tool #{title(event.tool_call)} #{verdict}", clock(event.duration),
173
+ presence(body_of(event.content))]
174
+ [parts.compact.join(" "), event.tool_error? ? :warn : :info]
175
+ end
176
+
177
+ def turn_line(event)
178
+ @turns += 1
179
+ "turn #{@turns} done #{event.reason}#{tokens(event.message&.usage)}"
180
+ end
181
+
182
+ # :error also carries expected stops, which log calmly; only real
183
+ # failures alarm. A budget stop is synthetic (no provider call), so
184
+ # it alone does not count as a turn.
185
+ def error_line(event)
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]
192
+ end
193
+
194
+ def retry_line(event)
195
+ wait = event.delay ? " in #{event.delay.round(1)}s" : ""
196
+ ["#{paint("retry", :yellow)} #{event.attempt}/#{event.max_attempts}#{wait}" \
197
+ "#{note(event.content)}", :warn]
198
+ end
199
+
200
+ # The full call id rides the line: Session#approve takes exactly that
201
+ # id, and the short pairing suffix is not it.
202
+ def approval_line(event)
203
+ call = event.tool_call
204
+ parts = ["approval needed #{title(call)}", presence(arguments(call)),
205
+ "id #{field(call.id, limit: 128)}"]
206
+ parts.compact.join(" ")
207
+ end
208
+
209
+ def compacting_line(_event) = "compacting"
210
+
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]
220
+
221
+ def report_line(event)
222
+ "worker #{field(event.agent)} (#{field(event.session_id.to_s[0, 8], limit: 16)}) " \
223
+ "#{event.status} #{body_of(event.content)}".rstrip
224
+ end
225
+
226
+ def status_of(result)
227
+ case result.status
228
+ when :completed
229
+ [result.handed_off? ? "completed (handed off)" : "completed", :info]
230
+ when :awaiting_approval
231
+ ["suspended (#{count(result.pending.length, "approval")} pending)", :info]
232
+ when :aborted then ["aborted", :info]
233
+ when :budget then ["stopped on budget", :warn]
234
+ else [paint(result.status.to_s, :red), :error]
235
+ end
236
+ end
237
+
238
+ def summary(usage)
239
+ return "" unless usage
240
+
241
+ base = ", #{prompt(usage)} / #{usage.output} out"
242
+ cost = usage.cost
243
+ cost&.known? ? base + format(", $%.4f", cost.total) : base
244
+ end
245
+
246
+ def tokens(usage)
247
+ usage ? " (#{prompt(usage)} / #{usage.output} out)" : ""
248
+ end
249
+
250
+ # Cache traffic is real prompt volume; input alone under-reports it.
251
+ def prompt(usage)
252
+ cached = usage.cache_read + usage.cache_write
253
+ return "#{usage.input} in" unless cached.positive?
254
+
255
+ "#{usage.input + cached} in (#{cached} cached)"
256
+ end
257
+
258
+ # A short call id makes concurrent same-name calls pairable.
259
+ def title(tool_call)
260
+ return paint("?", :green) unless tool_call
261
+
262
+ name = paint(field(tool_call.name), :green)
263
+ id = field(tool_call.id, limit: 128)
264
+ ref = id.length > 4 ? id[-4, 4] : id
265
+ ref.empty? ? name : "#{name}##{ref}"
266
+ end
267
+
268
+ def arguments(tool_call)
269
+ return "[#{trim(tool_call.arguments_error)}]" if tool_call.arguments_error?
270
+ return "" unless @content
271
+
272
+ rendered = +""
273
+ preview(tool_call.arguments || {}, rendered)
274
+ trim(rendered)
275
+ end
276
+
277
+ # A bounded JSON preview: rendering stops once the budget is spent,
278
+ # so a payload near the 8 MiB argument ceiling never materializes as
279
+ # a whole serialized string on the emission path.
280
+ def preview(value, out)
281
+ return out << "..." if @truncate && out.length > @truncate
282
+
283
+ case value
284
+ when Hash
285
+ walk(value, out, "{", "}") do |(key, item)|
286
+ out << JSON.generate(snip(key.to_s)) << ":"
287
+ preview(item, out)
288
+ end
289
+ when Array
290
+ walk(value, out, "[", "]") { |item| preview(item, out) }
291
+ when String
292
+ out << JSON.generate(snip(value))
293
+ else
294
+ out << JSON.generate(value)
295
+ end
296
+ end
297
+
298
+ def snip(text) = @truncate ? text[0, @truncate] : text
299
+
300
+ def walk(items, out, open, close)
301
+ out << open
302
+ items.each_with_index do |item, index|
303
+ break if @truncate && out.length > @truncate && index.positive?
304
+
305
+ out << "," if index.positive?
306
+ yield(item)
307
+ end
308
+ out << close
309
+ end
310
+
311
+ # Diagnostics keep their class and reason in every mode; the free
312
+ # text obeys content:, because exception messages can echo payloads.
313
+ def note(text)
314
+ flat = presence(trim(text))
315
+ return "" unless flat
316
+
317
+ @content ? ": #{flat}" : " (#{bytes(text)})"
318
+ end
319
+
320
+ # content: false keeps the beat and the volume, never the words.
321
+ def body_of(text)
322
+ return "" if text.nil? || text.to_s.strip.empty?
323
+ return "(#{bytes(text)})" unless @content
324
+
325
+ quote(text)
326
+ end
327
+
328
+ def quote(text)
329
+ body, cut = clip(text)
330
+ cut ? %("#{body}" (#{bytes(text)})) : %("#{body}")
331
+ end
332
+
333
+ def trim(text) = clip(text).first
334
+
335
+ # Structural scalars (tags, names, ids, labels) are bounded and
336
+ # stripped of hidden bytes before they join a line, so untrusted
337
+ # values cannot forge lines or steer a terminal.
338
+ def field(value, limit: 64)
339
+ clip(value, limit: limit).first
340
+ end
341
+
342
+ # String work per line stays bounded: only a head of the payload is
343
+ # normalized, never all of it. scrub repairs invalid bytes (encode
344
+ # alone skips same-encoding validation), encode converts binary, and
345
+ # hidden bytes become visible escapes. The size suffix reports the
346
+ # whole payload.
347
+ def clip(text, limit: @truncate)
348
+ raw = text.to_s
349
+ head = limit ? raw[0, [(limit * 2) + 1, HEAD].max] : raw
350
+ flat = head.scrub.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
351
+ .gsub(/\s+/, " ").strip
352
+ .gsub(HIDDEN) { |hidden| format("\\u%04x", hidden.ord) }
353
+ cut = limit && (flat.length > limit || head.bytesize < raw.bytesize)
354
+ return [flat, false] unless cut
355
+
356
+ ["#{flat[0, limit].rstrip}...", true]
357
+ end
358
+
359
+ def clock(duration)
360
+ return nil unless duration
361
+
362
+ duration < 1 ? "#{(duration * 1000).round}ms" : "#{duration.round(1)}s"
363
+ end
364
+
365
+ def bytes(text)
366
+ size = text.to_s.bytesize
367
+ return "#{size}B" if size < 1024
368
+
369
+ size < 1_048_576 ? format("%.1fKB", size / 1024.0) : format("%.1fMB", size / 1_048_576.0)
370
+ end
371
+
372
+ def count(number, noun) = "#{number} #{number == 1 ? noun : "#{noun}s"}"
373
+
374
+ def presence(text) = text.nil? || text.empty? ? nil : text
375
+
376
+ def paint(text, color) = @color ? "\e[#{COLORS.fetch(color)}m#{text}\e[0m" : text
377
+
378
+ # Formatting is skipped entirely when the floor level is disabled on
379
+ # the host logger; warnings and errors always go through.
380
+ def floor_enabled?
381
+ query = :"#{@level}?"
382
+ !@logger.respond_to?(query) || @logger.public_send(query)
383
+ rescue StandardError
384
+ true
385
+ end
386
+
387
+ def write(line, level: :info)
388
+ return if @warned
389
+
390
+ level = @level if level == :info
391
+ @logger.public_send(level, "#{@tag} #{line}")
392
+ rescue StandardError => e
393
+ quiet(e)
394
+ end
395
+
396
+ def quiet(error)
397
+ return if @warned
398
+
399
+ @warned = true
400
+ warn "mistri: logging sink failed (#{error.class}: #{error.message}); " \
401
+ "logging disabled for this run"
402
+ end
403
+
404
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
405
+ end
406
+ end
407
+ end
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