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
@@ -14,63 +14,113 @@ module Mistri
14
14
  # pairing needs: Thinking.signature holds the whole reasoning item,
15
15
  # Text.signature the message item id, ToolCall.signature the
16
16
  # function_call item id.
17
+ #
18
+ # A result that loads deferred tools is followed by an additional_tools
19
+ # item, which makes them callable from that point on and leaves the
20
+ # request's own tools, and so the cached prefix, as they were.
17
21
  module Serializer
18
22
  module_function
19
23
 
20
- def input_items(history)
21
- history.reject(&:system?).flat_map { |msg| items_for(msg) }
24
+ # The deferred tools are indexed by the name they are sent with. One
25
+ # is converted when a result loads it, not on every request.
26
+ def input_items(history, deferred: [], system_messages: false)
27
+ specs = deferred.to_h { |tool| [tool.transform_keys(&:to_sym)[:name], tool] }
28
+ declared = {}
29
+ history = if system_messages
30
+ Reminder.user_weighted(history)
31
+ else
32
+ Reminder.as_user_turns(history)
33
+ end
34
+ history.flat_map do |msg|
35
+ items = items_for(msg, declared)
36
+ msg.tool? ? items + additions(msg, specs, declared) : items
37
+ end
22
38
  end
23
39
 
40
+ def additions(msg, specs, declared)
41
+ return [] if msg.tool_error?
42
+
43
+ fresh = msg.loads.to_a.uniq.select { |name| specs.key?(name) && !declared.key?(name) }
44
+ return [] if fresh.empty?
45
+
46
+ fresh.each { |name| declared[name] = true }
47
+ [{ type: "additional_tools", role: "developer", tools: tools(specs.values_at(*fresh)) }]
48
+ end
49
+
50
+ # Left unset, the API makes each schema strict, which makes every
51
+ # optional field required, and the model then invents their values.
24
52
  def tools(definitions)
25
53
  definitions.map do |tool|
26
54
  spec = tool.transform_keys(&:to_sym)
27
55
  { type: "function", name: spec[:name], description: spec[:description],
28
- parameters: spec[:input_schema] }
56
+ parameters: spec[:input_schema], strict: false }
29
57
  end
30
58
  end
31
59
 
32
- def items_for(msg)
60
+ def items_for(msg, declared = {})
33
61
  case msg.role
34
62
  when :user then [user_item(msg)]
35
63
  when :tool then [tool_result_item(msg)]
36
- when :assistant then assistant_items(msg)
37
- else []
64
+ when :assistant then assistant_items(msg, declared)
65
+ else msg.reminder ? [developer_item(msg)] : []
38
66
  end
39
67
  end
40
68
 
69
+ # A reminder as a developer message. The API takes one anywhere in the
70
+ # input, so it is sent where the conversation holds it.
71
+ def developer_item(msg)
72
+ developer_message(msg.content.grep(Content::Text).map(&:text))
73
+ end
74
+
75
+ def developer_message(texts)
76
+ { role: "developer", content: texts.map { |text| { type: "input_text", text: } } }
77
+ end
78
+
41
79
  def user_item(msg)
42
- { role: "user", content: msg.content.map { |block| user_block(block) } }
80
+ { role: "user", content: msg.content.map { |block| input_part(block) } }
43
81
  end
44
82
 
45
- def user_block(block)
83
+ def input_part(block)
46
84
  case block
47
85
  when Content::Text then { type: "input_text", text: block.text }
48
- when Content::Image
49
- { type: "input_image", image_url: "data:#{block.mime_type};base64,#{block.data}" }
86
+ when Content::Image then image_part(block)
50
87
  else
51
- raise SchemaError, "cannot serialize #{block.class} for OpenAI user input"
88
+ raise SchemaError, "cannot serialize #{block.class} for OpenAI input"
52
89
  end
53
90
  end
54
91
 
55
- # Non-text blocks in a tool result have no function_call_output
56
- # encoding; note the omission rather than dropping it silently.
92
+ # The API refuses a format it does not take and a label that is not a
93
+ # MIME type, so the type sent is the one the bytes show.
94
+ def image_part(image)
95
+ type = image.detected_mime_type
96
+ return { type: "input_text", text: image.placeholder } unless type
97
+
98
+ { type: "input_image", image_url: "data:#{type};base64,#{image.data}" }
99
+ end
100
+
101
+ # The output is a string, or an array of parts when the result holds
102
+ # an image. Text alone stays a string, so a stored session replays as
103
+ # the request it sent before.
57
104
  def tool_result_item(msg)
58
- omitted = msg.content.count { |block| !block.is_a?(Content::Text) }
59
- text = msg.text.to_s
60
- text = "#{text}\n[#{omitted} non-text block(s) omitted]".strip if omitted.positive?
61
- { type: "function_call_output", call_id: msg.tool_call_id, output: text }
105
+ output = if msg.content.any?(Content::Image)
106
+ msg.content.map { |block| input_part(block) }
107
+ else
108
+ msg.text.to_s
109
+ end
110
+ { type: "function_call_output", call_id: msg.tool_call_id, output: }
62
111
  end
63
112
 
64
- def assistant_items(msg)
113
+ def assistant_items(msg, declared = {})
65
114
  own = msg.provider == :openai
66
- msg.content.filter_map { |block| assistant_item(block, own:) }
115
+ msg.content.filter_map { |block| assistant_item(block, own:, declared:) }
67
116
  end
68
117
 
69
- def assistant_item(block, own: true)
118
+ def assistant_item(block, own: true, declared: {})
70
119
  case block
71
120
  when Content::Thinking then reasoning_item(block, own:)
121
+ when Content::Compaction then block.data
72
122
  when Content::Text then message_item(block, own:)
73
- when ToolCall then function_call_item(block, own:)
123
+ when ToolCall then function_call_item(block, own:, declared:)
74
124
  end
75
125
  end
76
126
 
@@ -93,9 +143,13 @@ module Mistri
93
143
  item
94
144
  end
95
145
 
96
- def function_call_item(block, own: true)
146
+ # A tool that came through additional_tools sits in a namespace of its
147
+ # own name. gpt-5.4 and gpt-5.5 refuse a call to it without one, and
148
+ # every model takes one, whoever made the call.
149
+ def function_call_item(block, own: true, declared: {})
97
150
  item = { type: "function_call", call_id: block.id, name: block.name,
98
151
  arguments: JSON.generate(ToolArguments.replay_value(block)) }
152
+ item[:namespace] = block.name if declared.key?(block.name)
99
153
  item[:id] = block.signature if own && block.signature && !block.arguments_error
100
154
  item
101
155
  end
@@ -7,23 +7,28 @@ module Mistri
7
7
  # The OpenAI Responses API, streamed and stateless: store is always false,
8
8
  # the full history replays every turn, and encrypted reasoning items round
9
9
  # trip through the signature slots so nothing depends on server-side
10
- # state. Reasoning summaries stream as thinking. max_output_tokens is
11
- # deliberately omitted: the API defaults to the model's own ceiling.
10
+ # state. Reasoning summaries stream as thinking. max_output_tokens is sent
11
+ # only when a stream call passes max_tokens; otherwise the API defaults to
12
+ # the model's own ceiling.
12
13
  #
13
14
  # Provider failures fold into the stream as an error turn rather than
14
15
  # raising, matching the Anthropic provider's contract.
15
16
  class OpenAI
16
17
  DEFAULT_ORIGIN = "https://api.openai.com"
17
18
  DEFAULT_REASONING = { summary: "auto" }.freeze
19
+ # What the count endpoint takes of a request's body.
20
+ COUNTED = %i[model input instructions tools reasoning text].freeze
18
21
 
19
- def initialize(api_key:, model: "gpt-5.5", origin: DEFAULT_ORIGIN,
22
+ def initialize(api_key:, model: "gpt-6.1-sol", origin: DEFAULT_ORIGIN,
20
23
  reasoning: DEFAULT_REASONING, service_tier: nil,
21
- catalog_pricing: nil, **transport_options)
24
+ catalog_pricing: nil, defers_tools: nil, **transport_options)
22
25
  @api_key = api_key
23
26
  @model = model
24
27
  @reasoning = reasoning
25
28
  @service_tier = service_tier
26
- @catalog_pricing = catalog_pricing.nil? ? official_origin?(origin) : catalog_pricing
29
+ @official = official_origin?(origin)
30
+ @catalog_pricing = catalog_pricing.nil? ? @official : catalog_pricing
31
+ @defers_tools = defers_tools
27
32
  @transport = Transport.new(origin: origin, **transport_options)
28
33
  end
29
34
 
@@ -39,6 +44,31 @@ module Mistri
39
44
  SchemaCapabilities.derive(schema, :openai)
40
45
  end
41
46
 
47
+ # The API makes a tool callable from an item in the input, so an agent
48
+ # passes the loaded deferred tools as deferred_tools and the request's
49
+ # own tools never change. Another origin may not support the item, and a
50
+ # model that does not use such tools reliably receives the loaded tools
51
+ # as tools. A host overrides either default with defers_tools:.
52
+ def defers_tools?
53
+ @defers_tools.nil? ? @official && Models.tool_loading?(@model) : @defers_tools
54
+ end
55
+
56
+ # The API takes a developer message anywhere in a conversation. A
57
+ # reminder is sent as one, and so is the system prompt. Another origin
58
+ # may refuse the role, and receives a reminder as text of a user turn
59
+ # and the system prompt as instructions.
60
+ def system_messages? = @official
61
+
62
+ # The API writes a compaction itself when a request ends with a
63
+ # trigger, for every model it serves. The compactor calls stream with
64
+ # compaction:, and the reply holds one Content::Compaction that only
65
+ # the API can read.
66
+ def compacts? = @official
67
+
68
+ # The API removes the reasoning of a turn that follows a summary the
69
+ # caller wrote, so such a summary is placed after the turns it leaves.
70
+ def summary_after_kept? = true
71
+
42
72
  def stream(messages:, system: nil, tools: [], signal: nil, **overrides, &emit)
43
73
  delivery = EventDelivery.wrap(emit)
44
74
  model = overrides.fetch(:model, @model)
@@ -55,29 +85,50 @@ module Mistri
55
85
  rescue EventDelivery::Failure => e
56
86
  raise EventDelivery.unwrap(e, delivery)
57
87
  rescue Error => e
58
- assembler.fail_stream(e, &emit)
88
+ assembler.fail_stream(too_long(e), &emit)
89
+ end
90
+
91
+ # The API's own count of the input tokens of the request that stream
92
+ # would send for the same arguments. It takes about 13 ms for each
93
+ # 1,000 tokens. Nil on another origin, which may not have the endpoint.
94
+ def count_tokens(messages:, system: nil, tools: [], **overrides)
95
+ return nil unless @official
96
+
97
+ model = overrides.fetch(:model, @model)
98
+ body = build_body(model, messages, system, tools, overrides).slice(*COUNTED)
99
+ @transport.post("/v1/responses/input_tokens", body:, headers:).fetch("input_tokens")
59
100
  end
60
101
 
61
102
  def close = @transport.close
62
103
 
63
104
  private
64
105
 
106
+ # The API refused each streamed request that was longer than the window
107
+ # inside the stream. A request that is not streamed is refused with
108
+ # status 400 and the same code, and that form has the same type.
109
+ def too_long(error)
110
+ ContextTooLongError.from(error) do |status, body|
111
+ status == 400 && body.include?("context_length_exceeded")
112
+ end
113
+ end
114
+
65
115
  def official_origin?(origin) = origin.to_s.delete_suffix("/") == DEFAULT_ORIGIN
66
116
 
67
117
  def build_body(model, messages, system, tools, overrides)
68
- body = {
69
- model: model,
70
- input: Serializer.input_items(messages),
71
- stream: true,
72
- store: false,
73
- include: ["reasoning.encrypted_content"]
74
- }
75
- body[:instructions] = system if system && !system.empty?
118
+ Content.refuse_foreign_compaction!(messages, :openai)
119
+ input = Serializer.input_items(messages,
120
+ deferred: overrides.fetch(:deferred_tools, []),
121
+ system_messages: system_messages?)
122
+ body = { model: model, input: input, stream: true, store: false,
123
+ include: ["reasoning.encrypted_content"] }
124
+ place_system(body, system) if system && !system.empty?
76
125
  body[:tools] = Serializer.tools(tools) if tools.any?
77
126
  service_tier = overrides.fetch(:service_tier, @service_tier)
78
127
  body[:service_tier] = service_tier if service_tier
79
128
  reasoning = overrides.fetch(:reasoning, @reasoning)
80
129
  body[:reasoning] = reasoning if reasoning
130
+ compact(body, overrides)
131
+ body[:prompt_cache_options] = { mode: "explicit" } if writes_no_cache?(model, overrides)
81
132
  if (schema = overrides[:output_schema])
82
133
  body[:text] = { format: { type: "json_schema", name: "output", strict: true,
83
134
  schema: Schema.strict(schema, all_required: true) } }
@@ -85,6 +136,32 @@ module Mistri
85
136
  body
86
137
  end
87
138
 
139
+ # GPT-6.2 and later append top-level instructions after the input,
140
+ # where no cache breakpoint reaches them, so the system prompt leads
141
+ # the input. Earlier models cache both forms as one prefix.
142
+ def place_system(body, system)
143
+ if system_messages?
144
+ body[:input].unshift(Serializer.developer_message([system]))
145
+ else
146
+ body[:instructions] = system
147
+ end
148
+ end
149
+
150
+ # A trigger as the last input item asks for a compaction in place of an
151
+ # answer. The API takes no instructions for it, and refuses an output
152
+ # limit under 20,000 tokens, so none is sent.
153
+ def compact(body, overrides)
154
+ return body[:input] << { type: "compaction_trigger" } if overrides[:compaction]
155
+
156
+ body[:max_output_tokens] = overrides[:max_tokens] if overrides[:max_tokens]
157
+ end
158
+
159
+ # A request of one kind, such as a summary, would pay to write a cache
160
+ # that nothing reads. The explicit mode with no breakpoint writes none.
161
+ def writes_no_cache?(model, overrides)
162
+ overrides[:cache] == false && @official && Models.cache_options?(model)
163
+ end
164
+
88
165
  def headers
89
166
  { "Authorization" => "Bearer #{@api_key}" }
90
167
  end
@@ -7,9 +7,9 @@ module Mistri
7
7
  # transform_context, so it appears fresh on the wire each time it is due
8
8
  # and never persists to the session.
9
9
  #
10
- # agent = Mistri.agent("claude-opus-4-8", tools: tools,
10
+ # agent = Mistri.agent("claude-opus-5-5", tools: tools,
11
11
  # transform_context: Mistri::Reminder.every(
12
- # 3, "Stay on gifting. Verify with tools before claiming.",
12
+ # 3, "Stay on the request. Verify with tools before claiming.",
13
13
  # ))
14
14
  #
15
15
  # Due is counted in completed assistant turns: the first reminder lands
@@ -20,10 +20,42 @@ module Mistri
20
20
  new(interval: interval, text: text, after: after)
21
21
  end
22
22
 
23
+ # The wire form of a harness note inside a user turn.
24
+ def self.wrap(text) = "<system-reminder>\n#{text}\n</system-reminder>"
25
+
26
+ # The history with each system message that is stored among the results
27
+ # of one turn moved after them, so the results of parallel calls stay
28
+ # together in whichever form a reminder is sent.
29
+ def self.after_results(history)
30
+ history.chunk_while { |a, b| (a.tool? || a.system?) && (b.tool? || b.system?) }
31
+ .flat_map { |run| run.partition(&:tool?).flatten(1) }
32
+ end
33
+
34
+ # The kinds of reminder that a host gave the weight of a user turn. They
35
+ # are sent as text of one on every provider.
36
+ AS_USER = %w[tool_instructions_as_user].freeze
37
+
38
+ # The history for a provider that sends a note as text of a user turn:
39
+ # each reminder message as a user message of wrapped text blocks.
40
+ def self.as_user_turns(history)
41
+ after_results(history).map { |message| message.reminder ? as_user(message) : message }
42
+ end
43
+
44
+ # The history for a provider that sends a note as a system message: only
45
+ # a reminder of a kind in AS_USER becomes a user message.
46
+ def self.user_weighted(history)
47
+ history.map { |message| AS_USER.include?(message.reminder) ? as_user(message) : message }
48
+ end
49
+
50
+ def self.as_user(message)
51
+ Message.user(message.content.grep(Content::Text).map { |block| wrap(block.text) })
52
+ end
53
+ private_class_method :as_user
54
+
23
55
  def initialize(interval:, text:, after: nil)
24
56
  @interval = [interval.to_i, 1].max
25
57
  @after = (after || @interval).to_i
26
- @body = "<system-reminder>\n#{text}\n</system-reminder>"
58
+ @body = Reminder.wrap(text)
27
59
  end
28
60
 
29
61
  def call(messages)
data/lib/mistri/result.rb CHANGED
@@ -8,16 +8,18 @@ module Mistri
8
8
  # for a decision that may come days later.
9
9
  #
10
10
  # Reads delegate to the final message, so result.text works whether the run
11
- # completed or suspended.
11
+ # completed or suspended. said is the text the model last wrote where its
12
+ # final message is empty, as after a tool call it had nothing to add to, and
13
+ # result.text reads it then.
12
14
  # output is a task's validated value, nil on plain runs. usage is the
13
15
  # run's own accounting: every provider attempt plus compaction calls, summed
14
16
  # (a resumed run counts from the resume; task sums across its fix passes).
15
17
  # handed_off marks a run that ended because an ends_turn tool executed:
16
18
  # complete, but the final word was the tool's, and whatever comes next (a
17
19
  # human's answer) arrives as the next run's input.
18
- Result = Data.define(:message, :status, :pending, :output, :usage, :handed_off) do
20
+ Result = Data.define(:message, :status, :pending, :output, :usage, :handed_off, :said) do
19
21
  def initialize(message:, status:, pending: [], output: nil, usage: Usage.zero,
20
- handed_off: false)
22
+ handed_off: false, said: nil)
21
23
  super
22
24
  end
23
25
 
@@ -28,7 +30,7 @@ module Mistri
28
30
  def errored? = status == :error
29
31
  def handed_off? = handed_off
30
32
 
31
- def text = message&.text
33
+ def text = said || message&.text
32
34
  def stop_reason = message&.stop_reason
33
35
  def error_message = message&.error_message
34
36
  def tool_calls = message ? message.tool_calls : []
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ # How much of a tool result is stored, and so sent to the model with every
5
+ # later request. The results that answer one assistant message share
6
+ # turn_bytes, because a compaction never makes one turn smaller.
7
+ class ResultLimit
8
+ DEFAULT_BYTES = 50_000
9
+ DEFAULT_TURN_BYTES = 200_000
10
+ SHARED_FLOOR_BYTES = 2_000
11
+ SHOWN_BYTES = 2_000
12
+ # 300 bytes are room for the line that names where the whole is saved.
13
+ SAVED_BYTES = SHOWN_BYTES + 300
14
+
15
+ OWN = "[This result was %<bytes>d bytes in %<lines>d lines. Only its start is above. The " \
16
+ "rest was not kept. If the tool can page or filter its results, call it again for " \
17
+ "the part you need.]"
18
+ SHARED = "[This result was %<bytes>d bytes in %<lines>d lines. Only its start is above, " \
19
+ "because the results of tool calls made together share one limit. The rest was " \
20
+ "not kept. If the tool can page or filter its results, call it again for the " \
21
+ "part you need, with fewer calls at a time.]"
22
+ UNSAVED = "[This result was %<bytes>d bytes in %<lines>d lines. Only its start is above. " \
23
+ "It could not be saved, so the rest was not kept. If the tool can page or " \
24
+ "filter its results, call it again for the part you need.]"
25
+ SAVED = "[This result is %<bytes>d bytes in %<lines>d lines. Only its start is above. The " \
26
+ "whole is saved at %<path>s. Read it in parts with read_file, or search it with " \
27
+ "grep.]"
28
+ private_constant :OWN, :SHARED, :UNSAVED, :SAVED
29
+
30
+ # The limit of each result of one assistant message, asked for as the
31
+ # results are stored. left is tracked as well, because a hook can make a
32
+ # result larger than the tool returned it.
33
+ class Turn
34
+ attr_reader :left
35
+
36
+ def initialize(levels, left)
37
+ @cut, @saved = levels
38
+ @left = left
39
+ end
40
+
41
+ def limit(own_limit, saved: false)
42
+ left = [@left, SHARED_FLOOR_BYTES].max
43
+ [own_limit, (saved ? @saved : @cut) || own_limit, left].min
44
+ end
45
+
46
+ def spend(bytes)
47
+ @left -= bytes
48
+ end
49
+ end
50
+ private_constant :Turn
51
+
52
+ # What one result holds: whole, with the turn to itself, and saved, once
53
+ # the scratchpad has taken it, which is nil where it can only be cut.
54
+ Held = Data.define(:whole, :saved)
55
+
56
+ attr_reader :bytes, :turn_bytes
57
+
58
+ def self.texts(content)
59
+ Array(content).filter_map do |block|
60
+ case block
61
+ when String then block
62
+ when Content::Text then block.text
63
+ end
64
+ end
65
+ end
66
+
67
+ def self.size(content) = texts(content).sum(&:bytesize)
68
+
69
+ def initialize(bytes: DEFAULT_BYTES, turn_bytes: DEFAULT_TURN_BYTES)
70
+ unless [bytes, turn_bytes].all? { |value| value.is_a?(Integer) && value.positive? }
71
+ raise ArgumentError, "bytes and turn_bytes must be positive Integers"
72
+ end
73
+
74
+ @bytes = bytes
75
+ @turn_bytes = turn_bytes
76
+ end
77
+
78
+ # The level of a turn is never under this, so a result that is sized to
79
+ # it is never cut.
80
+ def share(count, spent: 0)
81
+ [[turn_bytes - spent, 0].max / count, SHARED_FLOOR_BYTES].max
82
+ end
83
+
84
+ def turn(held, spent: 0)
85
+ left = turn_bytes - spent
86
+ Turn.new(held.sum(&:whole) <= left ? nil : levels(held, [left, 0].max), left)
87
+ end
88
+
89
+ def bound(content, limit = bytes, shared: false, unsaved: false)
90
+ texts = self.class.texts(content)
91
+ size = texts.sum(&:bytesize)
92
+ return [content, nil] if size <= limit
93
+
94
+ cut = { "bytes" => size, "lines" => texts.sum { |text| lines(text) } }
95
+ wording = if unsaved
96
+ UNSAVED
97
+ else
98
+ shared ? SHARED : OWN
99
+ end
100
+ notice = format(wording, bytes: size, lines: cut["lines"])
101
+ [cut_to(content, [limit - notice.bytesize - 1, 0].max, notice), cut]
102
+ end
103
+
104
+ def shown(text, path, limit = bytes)
105
+ cut = { "bytes" => text.bytesize, "lines" => lines(text), "path" => path }
106
+ notice = format(SAVED, **cut.transform_keys(&:to_sym))
107
+ start = start_of(text, (limit - notice.bytesize - 1).clamp(0, SHOWN_BYTES))
108
+ [[start, notice].reject(&:empty?).join("\n"), cut]
109
+ end
110
+
111
+ private
112
+
113
+ # The largest results give way first, so a small result stays whole beside
114
+ # a large one. The results that can only be cut give way to one level. A
115
+ # result that can be saved gives way to its start, and so does every one
116
+ # of its size or more: hence a level of their own, under the smallest.
117
+ def levels(held, left)
118
+ rest, left = giving_way(held.sort_by(&:whole), left)
119
+ saved, cut = rest.partition(&:saved)
120
+ left -= saved.sum { |result| [result.whole, result.saved].min }
121
+ [(left / cut.length if cut.any?), (saved.first.whole - 1 if saved.any?)]
122
+ .map { |bytes| bytes && [bytes, SHARED_FLOOR_BYTES].max }
123
+ end
124
+
125
+ def giving_way(rest, left)
126
+ while (whole = rest.first&.whole)
127
+ larger = rest.drop(1).sum { |result| [result.saved || whole, whole].min }
128
+ break if whole + larger > left
129
+
130
+ left -= whole
131
+ rest = rest.drop(1)
132
+ end
133
+ [rest, left]
134
+ end
135
+
136
+ def cut_to(content, limit, notice)
137
+ return "#{start_of(content, limit)}\n#{notice}" if content.is_a?(String)
138
+
139
+ blocks = Array(content).filter_map do |block|
140
+ text = self.class.texts(block).first
141
+ next block unless text
142
+ next if limit <= 0
143
+
144
+ start = start_of(text, limit)
145
+ limit -= text.bytesize
146
+ Content::Text.new(text: start)
147
+ end
148
+ blocks << Content::Text.new(text: notice)
149
+ end
150
+
151
+ # A cut at a line end, unless that loses more than half of what fits.
152
+ def start_of(text, limit)
153
+ return text if text.bytesize <= limit
154
+
155
+ start = text.byteslice(0, limit).scrub("")
156
+ line_end = start.rindex("\n")
157
+ line_end && line_end >= start.length / 2 ? start[0...line_end] : start
158
+ end
159
+
160
+ def lines(text)
161
+ text.count("\n") + (text.end_with?("\n") ? 0 : 1)
162
+ end
163
+ end
164
+ end