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
@@ -29,6 +29,15 @@ end
29
29
  The handler may accept only `args`, or `args` and `context`. `context.app` is
30
30
  the object passed as `Mistri.agent(context:)`; it is the usual place for the
31
31
  acting user, tenant, or request-scoped authorization context.
32
+ `context.result_limit` is the bytes the result of this call keeps before it
33
+ is cut, or nil where nothing is cut, so a tool that reads in parts can size a
34
+ part. It is the tool's own limit or the agent's, or the call's share of the
35
+ turn's bytes where that is less: the more calls the model makes at once, the
36
+ smaller the part.
37
+
38
+ `context.scratchpad` is the agent's scratchpad, or nil when it has none. A tool
39
+ that is handed bytes a model cannot read keeps them there and answers with
40
+ the path: `context.scratchpad.save_binary(bytes, "tool_name", ".pdf")`.
32
41
 
33
42
  Handlers may return:
34
43
 
@@ -50,18 +59,83 @@ A completed model call moves through these phases in order:
50
59
  5. `before_tool` evaluates current application policy.
51
60
  6. `needs_approval` decides whether the prepared call must park.
52
61
  7. A free call emits `:tool_started` and invokes the handler.
53
- 8. `after_tool` may rewrite the result, which then persists and emits
54
- `:tool_result`.
62
+ 8. `after_tool` may rewrite the result.
63
+ 9. The result is [bounded](#large-results), persists and emits `:tool_result`.
55
64
 
56
65
  Malformed or invalid calls do not reach policy or execution. The model receives
57
- a bounded error result it can correct, while valid sibling calls in the same
58
- turn continue. Results settle in the model's call order even when handlers run
59
- concurrently.
66
+ a bounded error result it can correct. Results settle in the model's call
67
+ order. What a refused call means for the calls after it is under
68
+ [The order of a turn's calls](#the-order-of-a-turns-calls).
60
69
 
61
70
  An approved call is revalidated against the current tool definition and passes
62
71
  through `before_tool` again on `resume`. Its normalizer and approval predicate
63
72
  do not run again: the human approved the already prepared arguments.
64
73
 
74
+ ## The order of a turn's calls
75
+
76
+ A model can send several calls in one turn. They take effect in the order it
77
+ wrote them, so a read written after a write sees the write.
78
+
79
+ A tool runs alone, in its place, unless it is marked `parallel: true`:
80
+
81
+ ```ruby
82
+ Mistri::Tool.define("search_orders", "Searches orders.", parallel: true,
83
+ schema: -> { string :query, "Search text", required: true }) do |args|
84
+ Orders.search(args.fetch("query"))
85
+ end
86
+ ```
87
+
88
+ - Marked calls that sit next to each other run together, on up to
89
+ `max_concurrency` threads. Any other call waits for the calls before it, and
90
+ the calls after it wait for it. A call that is not run does not separate the
91
+ marked calls around it.
92
+ - Mark a tool that only reads, or that starts work of its own. Its result must
93
+ not depend on which of its marked neighbours finishes first, and it must
94
+ change nothing that another call of the turn reads.
95
+ - A call that runs by itself, marked or not, runs on the thread that called
96
+ the agent, as part of that thread's work. What its handler sets on the
97
+ thread stays set after the run, and a `throw` to a `catch` around the run
98
+ ends the run. Inside a Rails job or request it sees the `Current` attributes
99
+ set there, it uses that thread's database connection and any transaction
100
+ open on it, and the executor does not report an error it raises. Calls that
101
+ run together run on worker threads, each in an executor of its own, so a
102
+ marked tool cannot rely on any of this.
103
+
104
+ When a call that runs alone does not take effect, the calls after it are not
105
+ run. That covers a handler that raised or timed out, a result with
106
+ `error: true`, refused arguments, an unknown tool, a `before_tool` block and
107
+ an approval rule that raised. Each call after it gets the error result
108
+ `Not run: the edit_page call before this one failed.`, and the model sends it
109
+ again if it still wants it. A call refused for its own arguments keeps its own
110
+ error. A marked call that fails holds back nothing. A call that is not run has
111
+ already passed its checks and `before_tool`, and it never reaches `after_tool`.
112
+ Whether a call took effect is judged on what its handler returned, before
113
+ `after_tool`, so a hook that turns a result into an error holds back nothing.
114
+
115
+ When the first call of a turn waits for approval, the calls before it have
116
+ run, and no call after it runs before the decision. A later call that needs
117
+ approval waits with it, so a person sees them together. Any other call gets
118
+ `Not run: the send_invite call before this one waits for a person's approval.
119
+ Send this call again once it is decided.` That holds for a marked call too: a
120
+ read written after a write that waits would return what was there before the
121
+ write. Once a call that is not marked has been held back, a later call that
122
+ needs approval is held back as well, because it may rely on that call. A call
123
+ after a refused or blocked call that is not marked gets the failure text
124
+ instead. On `resume` the approved calls run in the order written, and one
125
+ that is not marked and fails holds back the ones after it. A denied call holds
126
+ back nothing.
127
+
128
+ The gem's own tools are marked where they only read or start a worker:
129
+ `read_file`, `grep`, `list_files`, `find_in_file`, `read_memory`, the skill
130
+ reader, tool search, `spawn_agent` and a named sub-agent. `write_file`,
131
+ `edit_file`, `delete_file`, `update_memory`, `run_code` and the four worker
132
+ console tools run alone. A call that `run_code` makes from code runs when the
133
+ code makes it. `spawn_agent` and a named sub-agent are marked so that workers
134
+ started in one turn work at the same time. What a worker does is not ordered
135
+ against the calls beside it. `list_agents` and `read_agent` only read, and
136
+ still run alone: they read what `spawn_agent` starts, and `read_agent` can
137
+ wait for a worker.
138
+
65
139
  ## Schema forms
66
140
 
67
141
  The DSL builds a JSON Schema 2020-12 object:
@@ -228,7 +302,7 @@ before_tool = lambda do |call, context|
228
302
  next "currency is not enabled" unless call.arguments.fetch("currency") == "USD"
229
303
  end
230
304
 
231
- agent = Mistri.agent("claude-opus-4-8", tools: tools, before_tool: before_tool)
305
+ agent = Mistri.agent("claude-opus-5-5", tools: tools, before_tool: before_tool)
232
306
  ```
233
307
 
234
308
  The hook also runs when an approved call resumes, so long-lived approval does
@@ -236,7 +310,11 @@ not bypass current authorization. A raised hook error blocks conservatively.
236
310
 
237
311
  `after_tool` receives `(call, result, context)` and may return a replacement
238
312
  result. Returning nil keeps the original. If the original result is an error,
239
- rewriting its text cannot relabel it as success.
313
+ rewriting its text cannot relabel it as success. Text returned for a result
314
+ that [loads tools](#tools-on-demand) replaces what the model reads and the
315
+ tools still load. A `Mistri::ToolResult` returned for it decides the loads:
316
+ `result.with(content: text)` keeps them, and one built without `loads:`
317
+ cancels the load.
240
318
 
241
319
  ## Results and UI
242
320
 
@@ -257,10 +335,129 @@ end
257
335
  `ui` persists on the tool message and appears on the `:tool_result` event, but
258
336
  is never sent to a provider.
259
337
 
260
- Non-text tool-result content remains provider-neutral in the Session. Anthropic
261
- can receive image blocks in a tool result. The current OpenAI and Gemini
262
- function-result serializers have no such encoding and send an explicit
263
- non-text-omission marker alongside the text instead.
338
+ ## Large results
339
+
340
+ A stored result is sent to the model with every later request, so Mistri bounds
341
+ it where it is stored. `after_tool` still receives the whole result.
342
+
343
+ - One result keeps its start, 50,000 bytes at most, on whole lines where it has
344
+ them. Its last line states the true size, that the rest was not kept, and
345
+ that the tool can be called again for a narrower part.
346
+ - The results that answer one assistant message share 200,000 bytes. Over
347
+ that, the largest give way first, down to one size for all of them, which is
348
+ never under 2,000 bytes. A compaction never makes one turn smaller, so this
349
+ is what keeps a turn inside the model's window. `after_tool` runs on
350
+ each result just before it is stored, in the model's order. When a hook
351
+ changes a result, the bytes are shared again among that result and the ones
352
+ after it, so a result that a hook makes smaller leaves its room to the later
353
+ ones. The results stored before it keep what they were given.
354
+ - An image is not counted and is never cut.
355
+ - `cut` on the tool message holds the true size, as in
356
+ `{ "bytes" => 2062500, "lines" => 62500 }`. It is nil on a result stored
357
+ whole and is never sent to a provider. The `:tool_result` event carries the
358
+ stored text.
359
+
360
+ Give a tool that can return a lot a way to ask for less: a page, a filter or a
361
+ count. The model reads the last line and calls the tool again.
362
+
363
+ ```ruby
364
+ agent = Mistri.agent(
365
+ "claude-opus-5-5",
366
+ tools: tools,
367
+ result_limit: Mistri::ResultLimit.new(bytes: 20_000, turn_bytes: 100_000),
368
+ )
369
+ ```
370
+
371
+ `result_limit: false` stores every result whole. One result larger than the
372
+ model's window then leaves the session with no way back, because a compaction
373
+ cannot shrink the turn that holds it.
374
+
375
+ A tool takes `result_limit:` too, the bytes one of its own results keeps in
376
+ place of the agent's number. A host can then lower the agent's limit for
377
+ chatty tools and leave a tool whose result the model needs whole as it is. The
378
+ skill reader keeps 50,000 bytes whatever the agent's limit. A tool's limit is
379
+ a positive number of bytes: no tool is exempt, and its results still share the
380
+ turn's bytes with the others.
381
+
382
+ ### Saving the whole result
383
+
384
+ Pass `scratchpad:`, a [workspace](context-and-workspaces.md#workspaces-and-document-tools)
385
+ the host builds and scopes to the session, and nothing is lost:
386
+
387
+ ```ruby
388
+ agent = Mistri.agent("claude-opus-5-5", tools: tools, scratchpad: workspace)
389
+ ```
390
+
391
+ - The whole of a text result over its limit is saved under
392
+ `scratchpad/tool-results/`, exactly as the tool returned it. Its name ends
393
+ in `.json` when the text begins and ends as a JSON object or array, and in
394
+ `.txt` otherwise.
395
+ - The stored result is its first 2,000 bytes and one line with the true size
396
+ and the path. `cut` holds the path too.
397
+ - Where the results of one turn are over its 200,000 bytes together, the
398
+ largest are saved first, and the ones that then fit stay whole.
399
+ - The agent adds the six document tools when the host passed none, so the
400
+ model reads a saved result in parts or searches it. The scratchpad is a
401
+ folder of the workspace you pass, and the tools reach every path of that
402
+ workspace, not only `scratchpad/`. Pass one that holds only what the model
403
+ may read and change. A host that passes its own document tools binds them
404
+ to the same workspace, and leaves out any the model must not have, such as
405
+ `delete_file`.
406
+ - A note tells the model what the scratchpad is for. After a compaction that
407
+ summarized it, the note is appended again with what the scratchpad holds.
408
+ - `scratchpad/tool-results/` is read-only to the model, so that it does not
409
+ write over a saved result by mistake. It may keep notes of its own elsewhere
410
+ under `scratchpad/`. The folder's own path is refused as well, and so is a
411
+ path that differs from it by capitals or accents. The check guards against a
412
+ mistake and is not a boundary: a store may match further letters to the
413
+ folder, as MySQL's default collation matches `ł` to `l`, and such a path
414
+ then reaches a saved result as any path reaches the host's own documents.
415
+ - A result with an image is cut and not saved. So is a result the scratchpad
416
+ cannot take: its line says it could not be saved, and Mistri prints a warning.
417
+ - A tool defined with `save_result: false` is cut and never saved. The document
418
+ tools are, so reading a saved result cannot save another.
419
+
420
+ With a scratchpad a lower limit costs little, because the model can still reach
421
+ the whole. `Mistri::ResultLimit.new(bytes: 8_000)` keeps results of middle
422
+ size out of every later request.
423
+
424
+ A result can hold images beside its text, and every provider sends them to the
425
+ model:
426
+
427
+ ```ruby
428
+ Mistri::Tool.define("screenshot", "Takes a picture of the page.") do
429
+ ["The page at 1280 pixels wide.",
430
+ Mistri::Content::Image.from_bytes(Browser.screenshot, mime_type: "image/png")]
431
+ end
432
+ ```
433
+
434
+ The session stores an image once, in a form no provider owns. Anthropic
435
+ receives it as an image block of the tool result, OpenAI as a part of the
436
+ function call output, and Gemini as inline data nested in the function
437
+ response, which Gemini takes from its 3 series on. Anthropic takes text alone
438
+ in a failed result, so the image of one follows the results of the turn,
439
+ behind a line that names the tool. Every request that carries the result costs
440
+ the image's tokens.
441
+
442
+ Return PNG, JPEG or WebP, which all three providers take. Anthropic and OpenAI
443
+ also take GIF and refuse every other format, so for those two Mistri reads the
444
+ first bytes of an image. A PNG, JPEG, GIF or WebP is sent with the type its
445
+ bytes show, whatever its label says. Any other image, such as a BMP or an SVG
446
+ from an MCP server, is sent as a line of text that says an image was not sent
447
+ and why, so the model knows a picture was left out. The session keeps the
448
+ image. Gemini is sent every image.
449
+
450
+ An image holds strict base64, the form `Base64.strict_encode64` writes and
451
+ the only form every provider takes. `Content::Image.new` takes base64 in any
452
+ form, with line breaks as `Base64.encode64` writes it, without padding or in
453
+ the URL-safe alphabet, and holds it in strict form. `from_bytes`,
454
+ `from_data_uri` and an image from an MCP server go through the same place.
455
+
456
+ An image over a provider's size limits is still refused, and so is one whose
457
+ data is broken. The provider then refuses the whole request, and the result
458
+ stays in the session, so the requests after it are refused too. Make a large
459
+ image smaller in `after_tool`. `transform_context:` does the same for a
460
+ result that is already stored.
264
461
 
265
462
  Return `error: true` for an expected failure the model should handle:
266
463
 
@@ -285,6 +482,320 @@ before raising or timing out. Mistri never mechanically replays the same call
285
482
  because it is marked failed, but the model may issue another call. The host
286
483
  still owns idempotency and reconciliation.
287
484
 
485
+ ## Code the model writes
486
+
487
+ Some work is arithmetic over more data than a model should read: a sum over a
488
+ saved result, a join of two documents, a count of every link on a page. With a
489
+ sandbox the agent gains `run_code`, and the model writes JavaScript that does
490
+ the work and returns only the answer.
491
+
492
+ ```ruby
493
+ # Gemfile: gem "wasmtime"
494
+ require "mistri/sandbox/quickjs"
495
+
496
+ SANDBOX = Mistri::Sandbox::QuickJS.new(wasm: "vendor/quickjs.wasm")
497
+
498
+ agent = Mistri.agent("claude-opus-5-5", tools: tools, scratchpad: workspace,
499
+ sandbox: SANDBOX)
500
+ ```
501
+
502
+ `Mistri::Sandbox::QuickJS` runs the code in QuickJS compiled to WebAssembly,
503
+ inside the host's process, on the `wasmtime` gem. Nothing else is installed
504
+ and no other process or machine is involved. The wasm file is `quickjs.wasm`
505
+ from the npm package `quickjs-wasi`, version 3.7.0. The adapter checks its
506
+ SHA-256 and refuses another build unless you pass `sha256:`. Build one adapter
507
+ for the process. It compiles the module at its first run, which takes about
508
+ 100 ms, and each run gets a new instance with its own memory. On a server that
509
+ forks its workers, build the adapter before the fork and run code only in the
510
+ workers: wasmtime does not survive a fork, so a process forked from one that
511
+ has already run code is refused. On macOS such a process also aborts when it
512
+ exits, inside the wasmtime gem.
513
+
514
+ What the code has:
515
+
516
+ - `files.read(path)`, `files.write(path, text)`, `files.list(prefix)` and
517
+ `files.delete(path)`. Each is the document tool of the same kind, on the
518
+ workspace that tool is bound to, so the agent needs that tool. A read returns
519
+ the whole document, and of a document that is not text it is an error the
520
+ code can catch. A write replaces a document only when the code has read or
521
+ written it through `files`, in this run or an earlier one of the session, and
522
+ it has not changed since. `scratchpad/tool-results/` stays read-only. Where a
523
+ document tool is the host's own, code calls it as a tool, as in
524
+ `await tools.write_file({ path, content })`.
525
+ - `await tools.NAME(arguments)` for every other tool of the agent. It returns
526
+ the result's text, and a failed result is thrown as an error. The built-in
527
+ `edit_file` is the one exception: code changes a document by reading it and
528
+ writing it with `files.write`.
529
+ - `console.log`, of which the first 100,000 bytes are kept, and the standard
530
+ JavaScript objects. There is no network, no file system, no timers and no
531
+ `URL` class. Dates are in UTC.
532
+ - Text leaves the code as UTF-8. Half of a character that a cut left behind,
533
+ as `slice` can leave of an emoji, arrives as U+FFFD.
534
+
535
+ A call from code is a tool call. It passes the tool's argument contract, its
536
+ timeout, `before_tool` and `after_tool`, and emits `:tool_started` and
537
+ `:tool_result` with a call id that begins with `code_`. `before_tool` is given
538
+ what the code passed, the content of a write included, and the code receives
539
+ what `after_tool` returned. For `files.read`
540
+ that is the document. A tool that needs approval for the call, or that ends
541
+ the turn, is refused in the code with a message to call it directly. So is
542
+ `tool_search`, which loads tools for the model. The call is stored as a
543
+ `code_call` entry beside the messages, not as a message: the model reads the
544
+ result in its code, so it is not sent again with later requests. One run
545
+ stores its first 100 calls, and every call emits its events. The result's `ui`
546
+ travels on the event and is not stored. The entry and the two events hold a
547
+ short copy: 2,000 bytes of the call's arguments and 2,000 bytes of its result.
548
+ Among the arguments the largest give way first, so a path stays whole beside
549
+ the content of a write, which keeps its start and its true size.
550
+
551
+ What code read or wrote is kept in the session, so the rule for a write holds
552
+ from one run to the next, after a restart and after a compaction. A run whose
553
+ code read or wrote a document at a version the session does not hold yet
554
+ appends one `code_documents` entry when it ends, with the path and the version
555
+ of each. A read counts once the code has received the document: one that
556
+ `after_tool` refused or rewrote does not. A session keeps 1,000 documents, the
557
+ ones whose version it learned last, and a checkpoint carries them.
558
+ `Session#code_documents` returns them. A read at the version the session
559
+ already holds does not make a document newer. A document that fell out of the
560
+ 1,000 is refused until the code reads it again. So is one that another hand
561
+ changed since: another agent, a person, or the model's own `write_file` or
562
+ `edit_file`. So is a document written by a run that the process did not finish,
563
+ because that run left no entry. A read under `scratchpad/tool-results/` is not
564
+ kept, because nothing is written there.
565
+
566
+ Limits: ten seconds of the code's own computing, five minutes for the whole
567
+ run with the calls it makes, and 64 MB, set with `timeout:`, `total_timeout:`
568
+ and `memory:`. One run writes 5 MB to documents at most, through `files` or
569
+ the built-in `write_file`, and a write past that is an error the code can
570
+ catch. A run that passes the first or the third is stopped and the model is
571
+ told. The time a tool or a document takes to answer the code does not count
572
+ against the first, so a slow tool does not end the run that called it. It
573
+ counts against the second: after the total limit, and once the agent's run is
574
+ stopped, every further call from the code is refused. The result of `run_code`
575
+ keeps 10,000 bytes, and with a scratchpad the whole is saved. The tool's
576
+ description states the limit and tells the model to write a longer output to a
577
+ document.
578
+
579
+ While code computes it holds Ruby's interpreter lock. The adapter passes the
580
+ lock on each time QuickJS checks for an interrupt, which it does in the code's
581
+ own loops and not inside one built-in call. A search in a long string or a
582
+ sort of a large array runs to its end with the lock held, and a loop of such
583
+ calls is checked rarely: code that searched a string of 20 MB in a loop kept
584
+ every other thread waiting for the whole ten seconds. On a process that serves
585
+ requests, set `timeout:` to the longest wait its other threads can take, or
586
+ run the agent in a job. The code also shares the CPU with those threads, so a
587
+ busy process gives it less computing within the same timeout.
588
+
589
+ A sandbox of your own is any object that answers `run(code, host:)` and
590
+ returns a `Mistri::Sandbox::Outcome`. `host` is a callable given an operation
591
+ name and a Hash, and is the only way out of the sandbox. A `Mistri::Error` that
592
+ `host` raises is the code's to catch. Any other error ends the run, so an
593
+ event subscriber's failure reaches the caller as it does for any tool call.
594
+
595
+ ## Tools on demand
596
+
597
+ A tool definition costs input tokens on every model round, and a host that
598
+ bridges a few MCP servers can hold hundreds of them. Mark a tool
599
+ `deferred: true` and the model is not shown it until it is needed:
600
+
601
+ ```ruby
602
+ refund = Mistri::Tool.define(
603
+ "refund_charge", "Gives a customer their money back.",
604
+ deferred: true,
605
+ schema: -> { string :charge, "Charge id", required: true },
606
+ ) { |args| Billing.refund(args.fetch("charge")) }
607
+ tracker = Mistri::MCP.tools(client, prefix: "tracker", deferred: true)
608
+
609
+ agent = Mistri.agent("claude-haiku-5-5", tools: [lookup_order, refund, *tracker])
610
+ ```
611
+
612
+ An agent that holds a deferred tool adds one of its own, `tool_search`. The
613
+ model asks it in words for what it needs to do. The search ranks the deferred
614
+ tools by their name, their description and the names and descriptions of their
615
+ parameters, loads the best matches (five by default, twenty at most) and
616
+ answers with their names. From its next step the model calls them like any
617
+ other tool. One load also holds no more than 20 KB of definitions; of 303
618
+ definitions measured on 22 public servers, nine in ten were under 2.2 KB. A
619
+ first match larger than that still loads, alone. When the size bound stops a
620
+ load before its count, the result states that more tools match, and the next
621
+ search loads them.
622
+
623
+ The deferred tools are listed in the conversation. With its first request an
624
+ agent appends a reminder to the session, after the user's message, that names
625
+ every deferred tool, the loaded ones too. It states that a tool is loaded with
626
+ `tool_search` before it is called, and that a tool is called directly once a
627
+ search result has stated that it is loaded. The agent appends one again when
628
+ the list has changed, and after a compaction that summarized the previous one.
629
+ An agent that holds no deferred tool, on a session that has a list, appends
630
+ one that states so. Past 20 KB of names the reminder gives the number of tools
631
+ under each name prefix instead, up to 20 KB of prefixes, and one count for the
632
+ rest. So give a server a prefix that describes it. The definition of
633
+ `tool_search` is the same whatever the list holds. Connecting a server
634
+ therefore changes neither the tools nor the system prompt of a request, and
635
+ the prompt cache holds.
636
+
637
+ The reminder is a system message of the conversation whose `reminder` is
638
+ `"deferred_tools"`. It is not the user's message, so a host that shows the
639
+ user and assistant messages to a person does not show it. A compaction does
640
+ not summarize it.
641
+
642
+ How a reminder reaches the model depends on the provider. A user cannot write
643
+ a system or developer message, so where a provider has one in the middle of a
644
+ conversation, the model can tell a reminder from text a user typed.
645
+
646
+ - Anthropic takes a system message in the middle of a conversation on Opus
647
+ 4.8 and later, Sonnet 5.5, Haiku 5.5 and the Fable models, and a reminder
648
+ is sent to those as one, on the official origin. It is sent after a user
649
+ turn and before the assistant turn that follows, which is where the API
650
+ takes it.
651
+ - OpenAI takes a developer message anywhere in a conversation, and a
652
+ reminder is sent as one, on the official origin.
653
+ - Every other model, origin and provider receives a reminder as text of a
654
+ user turn in a system-reminder block.
655
+
656
+ `provider.system_messages?` states which form a provider sends. On both
657
+ providers a request whose last message is such a reminder is not read from
658
+ the prompt cache by the next request, so the reminder's tokens are sent
659
+ uncached once more than they are as text of a user turn. After that the
660
+ cache holds.
661
+
662
+ A conversation that starts on one form and continues on the other, such as a
663
+ session moved to an older model, changes what was sent before. The prompt
664
+ cache is rebuilt once, and signed thinking from before the move is dropped.
665
+
666
+ A query that is a tool's name loads that tool and no other. The same applies
667
+ to the name without its prefix and to the words of the name, so `create issue`
668
+ loads `tracker__create_issue`. The model can name several tools in one query:
669
+ `select:` followed by their names, separated by commas, or their full names
670
+ separated by spaces. The result lists the names that match no tool. A name
671
+ that many tools share, such as `list` under thirty prefixes, loads no more
672
+ than the limit, and the result gives the number that remain. When the query
673
+ gives no limit, a search loads five tools, or as many as the query names
674
+ when that is more, up to twenty.
675
+
676
+ A tool that is already loaded is not loaded again. The result states that it
677
+ is loaded and names it in its own `loads`, so the tool stays loaded while
678
+ either result is in the history. Its definition is still sent once. The
679
+ search continues with the next matches, so a repeated search loads tools
680
+ further down the ranking. A search also treats a tool as loaded once another
681
+ search of the same turn has selected it, so two searches in one turn do not
682
+ load the same tool. If an `after_tool` hook cancels a load and no other
683
+ result names the tool, a search loads it again from the next request.
684
+
685
+ Any other query is a word search. It matches the words of a name, a
686
+ description or a parameter, not their meaning. A run of Han, kana or Hangul
687
+ characters, which often has no spaces between its words, is matched by pairs
688
+ of characters, and by one character when the query is one. In words,
689
+ half-width and full-width forms match each other; a name is matched as it is
690
+ written. Other scripts written without spaces match poorly. A query is read
691
+ up to 500 characters.
692
+
693
+ A load is stored with the tool result that names it. A later run on the same
694
+ session offers the same tools with no new search. A tool is loaded while a
695
+ successful result that names it is in the history. After a compaction that
696
+ summarizes every such result of a tool, the summary is followed by the names
697
+ of the tools loaded before it. The message states that their definitions are
698
+ no longer in the model's context and instructs it to load the ones it needs
699
+ again by name. A call to one of them without a new load still runs, after the
700
+ usual argument check: the model received that definition when it loaded the
701
+ tool. When that check fails, the result states that the tool is not loaded and
702
+ instructs the model to load it, because the model cannot correct arguments for
703
+ a definition it no longer has.
704
+
705
+ Any tool can load deferred tools with its result:
706
+
707
+ ```ruby
708
+ Mistri::ToolResult.new(
709
+ content: "The tracker is open.",
710
+ loads: %w[tracker__create_issue tracker__list_issues],
711
+ )
712
+ ```
713
+
714
+ A name that is not a deferred tool of this agent is ignored, and a result
715
+ marked `error: true` loads nothing.
716
+
717
+ A deferred tool is still one of the agent's tools. Its approval gate, the
718
+ argument check, `before_tool` and `after_tool` apply when it runs. A call to
719
+ one that no result has loaded does not run: the model has the name and not the
720
+ schema, so its arguments would be a guess. The error result instructs the
721
+ model to load the tool with `tool_search` and call it again. A call that
722
+ waited for approval was loaded when the model made it, and it is not checked
723
+ again when the run resumes. Keep the few tools every conversation needs out of
724
+ deferral, so the model does not search for them, and do not name a deferred
725
+ tool in a system prompt as if it were already loaded. A host tool named
726
+ `tool_search` beside a deferred tool is a duplicate name and fails Agent
727
+ construction.
728
+
729
+ How a loaded tool reaches the model depends on the provider, and a host does
730
+ not choose:
731
+
732
+ - Anthropic receives a deferred definition from the request whose result loads
733
+ it, marked `defer_loading` so that it stays out of the prompt, and that
734
+ result carries a reference to it. A later result that names the same tool
735
+ carries none, because every reference adds the definition to the prompt
736
+ again. The prompt cache holds across a load. One reserved definition,
737
+ `mistri_deferred_tools`, is sent the same way from the first request,
738
+ because the first deferred definition in a conversation would otherwise
739
+ rebuild the cache once. No result references it, so it never enters the
740
+ prompt. No result can load it, and a tool of that name beside deferred tools
741
+ fails the request before it is sent. The result's own text follows the tool
742
+ results of that turn. This form is used on the official origin. Another
743
+ origin is treated like the last provider below unless the host sets
744
+ `defers_tools: true`.
745
+ - OpenAI keeps the request's own tools as they are, and a result that loads
746
+ tools is followed by an item in the input that makes them callable from
747
+ that point on. The prompt cache holds across a load here too. This is used
748
+ on the official origin, for the models OpenAI documents it for: gpt-5.4 and
749
+ later, the nano models aside. An older model, a nano model and another
750
+ origin are treated like the provider below unless the host sets
751
+ `defers_tools:`.
752
+ - Gemini, and any other provider, is sent the tools that are not deferred,
753
+ then the loaded ones in the order they were loaded.
754
+
755
+ The growing list costs more for each load than the two forms above. A load
756
+ changes the request's tools, so the prompt cache is built again from the
757
+ start. On Anthropic's API a changed tool list also makes the thinking of
758
+ earlier turns invalid: the request after a load is refused on the models that
759
+ check it, unless the host set
760
+ `block_binding: { prefix_mismatch_behavior: "drop_block" }`, and then that
761
+ thinking is dropped. So a host that reaches Anthropic or OpenAI through a
762
+ gateway that forwards requests unchanged sets `defers_tools: true`, which
763
+ selects the form that keeps the cached prefix across a load:
764
+
765
+ ```ruby
766
+ Mistri.agent(
767
+ "claude-opus-5-5",
768
+ tools: tools,
769
+ provider_options: { origin: "https://gateway.example", defers_tools: true },
770
+ )
771
+ ```
772
+
773
+ `defers_tools: false` selects the growing list on the official origin.
774
+
775
+ What it costs in the process is small. Building an agent with deferred tools
776
+ costs what a flat list costs. The search document of a deferred tool is built
777
+ from its description and schema on the first search that covers it, and is
778
+ kept on the tool. Agents that are given the same tool objects therefore share
779
+ the index, so bridge a server once for the process. A tool's name, description
780
+ and schema are fixed once it is built; a different definition is a new tool.
781
+ Building a request reads the history a few more times, each a single pass: one
782
+ collects the loaded names, one finds the newest reminder with the list of
783
+ deferred tools, and one finds the reminders that hold server instructions when
784
+ a tool carries any. Where the provider takes no system message in a
785
+ conversation, the agent makes each reminder a user message in one more pass,
786
+ and a built-in provider checks the history for one once more. On OpenAI one
787
+ pass over the loaded definitions indexes them by name.
788
+
789
+ On the wire no request carries the definition of a deferred tool until a
790
+ result loads it, on any provider.
791
+
792
+ A provider of your own is sent the growing tool list. To hold definitions
793
+ back itself it answers `defers_tools?` with true, and `stream` is then given
794
+ the loaded deferred definitions as `deferred_tools:` beside `tools:`. It is
795
+ given each reminder as a user message whose text is in a system-reminder
796
+ block. To send a reminder its own way it answers `system_messages?` with
797
+ true, and `messages:` then holds the system message the session stores.
798
+
288
799
  ## Hand off the turn
289
800
 
290
801
  `ends_turn: true` ends the run after the tool executes instead of asking the
@@ -303,7 +814,10 @@ end
303
814
 
304
815
  `result.handed_off?` reports that the model's floor moved away. It does not
305
816
  claim the tool succeeded; inspect the tool result separately. The human answer
306
- arrives as the next `run` input.
817
+ arrives as the next `run` input. Calls written after it in the same turn still
818
+ take their turn, as [The order of a turn's calls](#the-order-of-a-turns-calls)
819
+ says. One that waits for approval suspends the run instead, and `handed_off?`
820
+ is then false.
307
821
 
308
822
  ## Resource limits
309
823
 
@@ -314,7 +828,8 @@ same structural preflight before its argument object is canonicalized.
314
828
 
315
829
  These are safety boundaries, not business validation. Keep tool schemas narrow,
316
830
  validate domain rules explicitly, and return references rather than embedding
317
- unbounded data in a tool call.
831
+ unbounded data in a tool call. A tool result is bounded as
832
+ [Large results](#large-results) describes.
318
833
 
319
834
  ## Related guides
320
835
 
data/examples/approval.rb CHANGED
@@ -15,22 +15,22 @@ Dir.mktmpdir do |dir|
15
15
  store = Mistri::Stores::JSONL.new(dir)
16
16
  session = Mistri::Session.new(store:)
17
17
 
18
- send_gift = Mistri::Tool.define(
19
- "send_gift", "Sends a real gift.", needs_approval: true,
20
- schema: -> { string :to, "Recipient", required: true }
18
+ send_email = Mistri::Tool.define(
19
+ "send_email", "Sends a real email.", needs_approval: true,
20
+ schema: -> { string :to, "Recipient", required: true }
21
21
  ) do |args|
22
- "gift queued for #{args["to"]}"
22
+ "email queued for #{args["to"]}"
23
23
  end
24
24
 
25
- agent = Mistri.agent("claude-opus-4-8", tools: [send_gift], session:)
26
- result = agent.run("Send a welcome gift to Ana.")
25
+ agent = Mistri.agent("claude-opus-5-5", tools: [send_email], session:)
26
+ result = agent.run("Send a welcome email to Ana.")
27
27
  puts "suspended: #{result.awaiting_approval?} (nothing executed)"
28
28
 
29
29
  # Any process can decide: a bare session is enough.
30
30
  Mistri::Session.new(store:, id: session.id).approve(result.pending.first.id)
31
31
 
32
32
  reloaded = Mistri::Session.new(store:, id: session.id)
33
- resumed = Mistri.agent("claude-opus-4-8", tools: [send_gift], session: reloaded).resume
33
+ resumed = Mistri.agent("claude-opus-5-5", tools: [send_email], session: reloaded).resume
34
34
  puts "resumed: #{resumed.status}"
35
35
  puts resumed.text
36
36
  end
data/examples/browser.rb CHANGED
@@ -18,7 +18,7 @@ begin
18
18
  tools = Mistri::MCP.tools(browser, prefix: "web",
19
19
  allow: %w[browser_navigate browser_snapshot])
20
20
 
21
- agent = Mistri.agent("claude-opus-4-8", tools: tools,
21
+ agent = Mistri.agent("claude-opus-5-5", tools: tools,
22
22
  system: "Use the browser tools to answer. Be brief.")
23
23
 
24
24
  puts agent.run("Open https://example.com and report the main heading.").text
@@ -22,10 +22,10 @@ workspace = Mistri::Workspace::Single.new(
22
22
  path: "hero.html"
23
23
  )
24
24
 
25
- agent = Mistri.agent("claude-opus-4-8",
25
+ agent = Mistri.agent("claude-opus-5-5",
26
26
  tools: Mistri::Tools.files(workspace),
27
27
  system: "Edit the page with the document tools. Read before editing.")
28
28
 
29
- agent.run("Change the h1 headline to: Gifts that land.")
29
+ agent.run("Change the h1 headline to: Deploy on every merge.")
30
30
 
31
31
  puts page
@@ -13,7 +13,7 @@ weather = Mistri::Tool.define(
13
13
  "34C and clear in #{args["city"]}"
14
14
  end
15
15
 
16
- agent = Mistri.agent("claude-opus-4-8", tools: [weather])
16
+ agent = Mistri.agent("claude-opus-5-5", tools: [weather])
17
17
 
18
18
  agent.run("What should I wear in Lahore today? One sentence.") do |event|
19
19
  print event.delta if event.type == :text_delta