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,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ # Walks the calls of one turn in the order the model wrote them. Calls of
5
+ # tools marked parallel that sit next to each other are one step and run
6
+ # together; any other call is a step alone, after everything before it.
7
+ #
8
+ # A call that runs alone and does not take effect holds back the rest of
9
+ # the turn, because a later call may rely on it. A call that waits for a
10
+ # person holds back the rest as well: a read written after it would return
11
+ # what was there before it. A call that needs approval waits with it, so a
12
+ # person sees both, until a held or refused call that is not marked comes
13
+ # between them: the later one may rely on that call.
14
+ class CallOrder
15
+ FAILED = "Not run: the %<name>s call before this one failed."
16
+ WAITING = "Not run: the %<name>s call before this one waits for a person's approval. " \
17
+ "Send this call again once it is decided."
18
+
19
+ # executed holds the entries the steps returned. skipped holds
20
+ # [call, result, nil] for a call that never started. parked holds the
21
+ # calls that still wait.
22
+ Outcome = Data.define(:executed, :skipped, :parked)
23
+
24
+ def initialize(tools_by_name)
25
+ @tools = tools_by_name
26
+ end
27
+
28
+ # refused entries were answered before execution, and one that is not
29
+ # marked holds back the rest. denied ones were answered by a person's no
30
+ # and hold back nothing. The block runs one step and returns its entries.
31
+ def run(calls, refused: [], denied: [], parked: [], signal: nil, &run_step)
32
+ @run_step = run_step
33
+ @signal = signal
34
+ @held = nil
35
+ @closed = false
36
+ @step = []
37
+ @outcome = Outcome.new(executed: [], skipped: [], parked: [])
38
+ kinds = kinds_of(refused, denied, parked)
39
+ calls.each { |call| place(call, kinds[call]) }
40
+ flush
41
+ @outcome
42
+ end
43
+
44
+ # The calls that would wait for a person if every call that runs took
45
+ # effect. A call that fails can only take calls out of them.
46
+ def waiting(calls, refused: [], parked: [])
47
+ run(calls, refused:, parked:) { |step| step.map { |call| [call] } }.parked
48
+ end
49
+
50
+ private
51
+
52
+ def kinds_of(refused, denied, parked)
53
+ kinds = {}.compare_by_identity
54
+ refused.each { |entry| kinds[entry.first] = :refused }
55
+ denied.each { |entry| kinds[entry.first] = :denied }
56
+ parked.each { |call| kinds[call] = :parked }
57
+ kinds
58
+ end
59
+
60
+ def place(call, kind)
61
+ case kind
62
+ when :denied then nil
63
+ when :refused then fail_at(call) unless parallel?(call)
64
+ when :parked then park(call)
65
+ else free(call)
66
+ end
67
+ end
68
+
69
+ def park(call)
70
+ return skip(call) if failed? || @closed
71
+
72
+ flush
73
+ @held ||= [WAITING, call]
74
+ @outcome.parked << call
75
+ end
76
+
77
+ def free(call)
78
+ return hold_back(call) if @held
79
+ return @step << call if parallel?(call)
80
+
81
+ alone(call)
82
+ end
83
+
84
+ # A later call that needs approval may rely on a call that is not marked,
85
+ # so none waits once one was held back.
86
+ def hold_back(call)
87
+ @closed ||= !parallel?(call)
88
+ skip(call)
89
+ end
90
+
91
+ def alone(call)
92
+ flush
93
+ entry = execute([call]).first
94
+ fail_at(call) if entry && failure?(entry[1])
95
+ end
96
+
97
+ def flush
98
+ step = @step
99
+ @step = []
100
+ execute(step) unless step.empty?
101
+ end
102
+
103
+ # An abort leaves the calls that have not started to the caller, which
104
+ # answers each as interrupted.
105
+ def execute(step)
106
+ if @signal&.aborted?
107
+ step.each { |call| @outcome.skipped << [call, interrupted, nil] }
108
+ return []
109
+ end
110
+
111
+ @run_step.call(step).tap { |entries| @outcome.executed.concat(entries) }
112
+ end
113
+
114
+ # The name is the model's own text when no tool has it, so it is bounded
115
+ # as the agent bounds a name in its other messages.
116
+ def skip(call)
117
+ text, holder = @held
118
+ name = holder.name.gsub(/[[:space:]]+/, " ")[0, 120]
119
+ @outcome.skipped << [call, ToolResult.new(content: format(text, name:), error: true), nil]
120
+ end
121
+
122
+ def fail_at(call)
123
+ @held = [FAILED, call] unless failed?
124
+ end
125
+
126
+ def failed? = @held&.first.equal?(FAILED)
127
+
128
+ def failure?(result) = result.is_a?(ToolResult) && result.error?
129
+
130
+ def interrupted = ToolResult.new(content: ToolExecutor::INTERRUPTED, error: true)
131
+
132
+ def parallel?(call)
133
+ tool = @tools[call.name]
134
+ tool.respond_to?(:parallel?) && tool.parallel?
135
+ end
136
+ end
137
+ end
data/lib/mistri/child.rb CHANGED
@@ -9,6 +9,7 @@ module Mistri
9
9
  # child.status # queued, running, interrupted, or terminal
10
10
  # child.report # the terminal entry's report, once finished
11
11
  # child.transcript(tail: 20) # recent entries, image bytes stripped
12
+ # child.transcript(from: 40, to: 60) # entries 40 to 59
12
13
  # child.say("Also check their pricing page")
13
14
  #
14
15
  # Status is a walk over the child's own entries: a terminal entry wins; a
@@ -24,7 +25,7 @@ module Mistri
24
25
  # Interrupted work is nonterminal but not actively live.
25
26
  LIVE = %i[running queued].freeze
26
27
 
27
- attr_reader :name, :session_id
28
+ attr_reader :name
28
29
 
29
30
  def self.lease_key(session_id) = "child:#{session_id}"
30
31
 
@@ -32,13 +33,20 @@ module Mistri
32
33
 
33
34
  def initialize(name:, session_id:, store:, parent_session_id: nil)
34
35
  @name = name
35
- @session_id = session_id
36
36
  @store = store
37
+ @log = Session::Log.new(store, session_id)
38
+ @session_id = @log.id
37
39
  @parent_session_id = parent_session_id
38
40
  end
39
41
 
42
+ # A string id is copied, so a caller cannot change which child this window reads.
43
+ def session_id = @session_id.is_a?(String) ? @session_id.dup : @session_id
44
+
40
45
  def status
41
- log = session.entries
46
+ terminal = terminal_at_end
47
+ return terminal["status"].to_sym if terminal
48
+
49
+ log = read_log
42
50
  terminal = log.reverse_each.find { |entry| entry["type"] == TERMINAL }
43
51
  return terminal["status"].to_sym if terminal
44
52
  if log.any? { |entry| entry["type"] == DISPATCHED } &&
@@ -58,21 +66,30 @@ module Mistri
58
66
  end
59
67
 
60
68
  def report
61
- terminal_entry&.fetch("report", nil)
69
+ Session::Log.owned(terminal_entry&.fetch("report", nil))
62
70
  end
63
71
 
64
72
  # The terminal entry's error string, once failed.
65
73
  def error
66
- terminal_entry&.fetch("error", nil)
74
+ Session::Log.owned(terminal_entry&.fetch("error", nil))
67
75
  end
68
76
 
69
77
  # Recent entries, oldest first, with inline image bytes replaced by a
70
78
  # marker: transcripts are for reading and re-sending, not for hauling
71
- # screenshots back into a context window.
72
- def transcript(tail: 20)
73
- entries = session.entries
74
- entries = entries.last(tail) if tail
75
- entries.map { |entry| self.class.strip_images(entry) }
79
+ # screenshots back into a context window. from: reads another part of
80
+ # the log instead: the entries from that position up to, and not
81
+ # including, to:, counted the way the store counts them.
82
+ def transcript(tail: 20, from: nil, to: nil)
83
+ entries = if !from.nil? || !to.nil? then entries_between(from, to)
84
+ elsif tail then last_entries(tail)
85
+ else read_log
86
+ end
87
+ entries.map { |entry| Session::Log.owned(self.class.strip_images(entry)) }
88
+ end
89
+
90
+ # How many entries the child's log holds.
91
+ def size
92
+ from_the_end? ? @store.size(@session_id) : read_log.length
76
93
  end
77
94
 
78
95
  # Queue a message the child folds at its next turn boundary. Delivery is
@@ -130,7 +147,7 @@ module Mistri
130
147
  return :contended unless lease
131
148
 
132
149
  begin
133
- log = session.entries
150
+ log = read_log
134
151
  terminal = log.reverse_each.find { |entry| entry["type"] == TERMINAL }
135
152
  dispatched = log.any? { |entry| entry["type"] == DISPATCHED }
136
153
  if terminal
@@ -154,7 +171,7 @@ module Mistri
154
171
  # grant; legacy children fall back to the parent link because their
155
172
  # dispatched entry did not retain a spec.
156
173
  def deliver_cancellation
157
- dispatched = session.entries.find { |entry| entry["type"] == DISPATCHED }
174
+ dispatched = read_log.find { |entry| entry["type"] == DISPATCHED }
158
175
  return unless dispatched
159
176
 
160
177
  spec = dispatched["spec"]
@@ -179,8 +196,47 @@ module Mistri
179
196
  @session ||= Session.new(store: @store, id: @session_id)
180
197
  end
181
198
 
199
+ def read_log = @log.entries
200
+
182
201
  def terminal_entry
183
- session.entries.reverse_each.find { |entry| entry["type"] == TERMINAL }
202
+ terminal_at_end || read_log.reverse_each.find { |entry| entry["type"] == TERMINAL }
203
+ end
204
+
205
+ # A finished child's log nearly always ends on its terminal entry, so
206
+ # that one entry answers for it without the rest.
207
+ def terminal_at_end
208
+ return nil unless from_the_end?
209
+
210
+ last = last_entries(1).first
211
+ last if last && last["type"] == TERMINAL
184
212
  end
213
+
214
+ def last_entries(count)
215
+ return read_log.last(count) unless from_the_end?
216
+
217
+ size = @store.size(@session_id)
218
+ # The count is taken the way Array#last takes it.
219
+ first = (0...size).last(count).first || size
220
+ @store.load(@session_id, from: first, to: size)
221
+ end
222
+
223
+ # Positions mean the same on every store and every path, so they are
224
+ # checked before either is chosen. An end at or before the start is an
225
+ # empty range.
226
+ def entries_between(from, to)
227
+ unless position?(from) && (to.nil? || position?(to))
228
+ raise ArgumentError, "from: and to: are positions in the log, whole numbers from 0"
229
+ end
230
+ return [] if to && to <= from
231
+ return read_log[from...to].to_a unless from_the_end?
232
+
233
+ @store.load(@session_id, from:, to:)
234
+ end
235
+
236
+ def position?(value) = value.is_a?(Integer) && !value.negative?
237
+
238
+ # A log that is already held is read on from where it stopped, which
239
+ # is cheaper than asking the store for its end again.
240
+ def from_the_end? = @store.respond_to?(:size) && !@log.held?
185
241
  end
186
242
  end
@@ -3,48 +3,142 @@
3
3
  require "json"
4
4
 
5
5
  module Mistri
6
- # When a session compacts, and how much of it survives. Compaction is
7
- # client-side and provider-agnostic: the session's own provider writes a
8
- # visible summary, so a host can always show the user exactly what the
9
- # model still remembers.
6
+ # When a session compacts, and how much of it survives. Mistri decides
7
+ # when, and where the cut is. The provider's own compaction writes the
8
+ # summary where there is one, and elsewhere the session's provider is
9
+ # asked for it. A host can show the summary wherever it can be read:
10
+ # OpenAI's own is sealed.
10
11
  #
11
12
  # The trigger measures real token accounting, not guesses: the last healthy
12
- # turn's reported usage plus a character heuristic for whatever came after
13
- # it.
13
+ # turn's reported usage, plus an estimate by a rule measured on each
14
+ # provider's own counts for whatever came after it.
14
15
  class Compaction
15
16
  DEFAULT_RESERVE = 16_384
16
17
  DEFAULT_KEEP_RECENT = 20_000
18
+ DEFAULT_MAX_TOKENS = 16_384
19
+ # Automatic compaction stops retrying after this many automatic failures
20
+ # in a row: a failure the configuration makes predictable must not bill a
21
+ # full-context request every turn.
22
+ AUTOMATIC_ATTEMPTS = 3
17
23
  OUTPUT_SAFETY = 4_096
18
- IMAGE_CHARS = 4_800
24
+ IMAGE_TOKENS = 1_200
25
+ # For a provider the rule below was not measured on.
26
+ CHARS_PER_TOKEN = 4.0
27
+ # The characters a token holds, measured on each provider's own counts,
28
+ # for letters and spaces, for digits, and for everything else. The kind of
29
+ # content moves the figure more than the provider does.
30
+ CLASS_CHARS_PER_TOKEN = { anthropic: [3.2, 1.6, 1.0], openai: [5.0, 1.2, 1.75],
31
+ gemini: [5.3, 0.9, 1.05] }.freeze
32
+ # The lowest estimate measured was half of the provider's count.
33
+ ESTIMATE_SPREAD = 2
19
34
 
20
- SUMMARY_PREFACE = "The earlier conversation was compacted. This summary replaces it:"
35
+ # How full the context is, and how many of those tokens are an estimate
36
+ # and not the provider's own count.
37
+ Level = Data.define(:tokens, :estimated) do
38
+ def reported = tokens - estimated
39
+ end
40
+
41
+ SUMMARY_PREFACE = "The earlier part of this conversation was compacted. Another model " \
42
+ "wrote the handoff summary below from those earlier messages; the " \
43
+ "messages after it are the most recent turns, kept intact. Build on the " \
44
+ "work already done, do not repeat it, and treat the user's most recent " \
45
+ "request as the current instruction."
46
+
47
+ # For a summary that stands after the turns it leaves, as OpenAI asks of
48
+ # one the caller wrote.
49
+ SUMMARY_PREFACE_AFTER = "The part of this conversation before the messages above was " \
50
+ "compacted. Another model wrote the handoff summary below from " \
51
+ "those earlier messages; the messages above are the most recent " \
52
+ "turns, kept intact. Build on the work already done, do not repeat " \
53
+ "it, and treat the user's most recent request as the current " \
54
+ "instruction."
21
55
 
22
- attr_reader :reserve, :keep_recent, :window, :instructions
56
+ attr_reader :reserve, :keep_recent, :window, :instructions, :max_tokens, :fallback, :threshold,
57
+ :native
23
58
 
24
59
  # window overrides the model catalog's context window (required for
25
60
  # models the catalog does not know). A nil reserve selects automatic
26
61
  # headroom; a number is explicit host policy. instructions add a
27
- # host-specific focus to the summary prompt.
28
- def initialize(reserve: nil, keep_recent: DEFAULT_KEEP_RECENT,
29
- window: nil, instructions: nil)
62
+ # host-specific focus to the summary prompt. max_tokens bounds the
63
+ # summary request's output: the summary is the compactor's own request
64
+ # and never inherits the limit a host set for its chat replies. fallback
65
+ # names a second summarizer, a provider or a model id, that gets one try
66
+ # when the session's provider cannot write a usable summary; the host
67
+ # chooses it, so a refusal never changes models silently. threshold is
68
+ # the level where a compaction starts: an Integer of tokens, or a Float
69
+ # for that share of the window. The reserve stays under it as the net.
70
+ # native lets the provider write the summary where it can, which keeps
71
+ # the thinking of the kept turns; false asks for the gem's own summary.
72
+ def initialize(reserve: nil, keep_recent: DEFAULT_KEEP_RECENT, window: nil, instructions: nil,
73
+ max_tokens: DEFAULT_MAX_TOKENS, fallback: nil, threshold: nil, native: true)
74
+ unless max_tokens.is_a?(Integer) && max_tokens.positive?
75
+ raise ArgumentError, "max_tokens must be a positive Integer"
76
+ end
77
+ unless threshold.nil? || tokens?(threshold) || share?(threshold)
78
+ raise ArgumentError, "threshold must be a positive Integer of tokens or a Float " \
79
+ "share of the window, above 0 and at most 1"
80
+ end
81
+
30
82
  @automatic_reserve = reserve.nil?
31
83
  @reserve = reserve || DEFAULT_RESERVE
32
84
  @keep_recent = keep_recent
33
85
  @window = window
34
86
  @instructions = instructions
87
+ @max_tokens = max_tokens
88
+ @fallback = summarizer(fallback)
89
+ @threshold = threshold
90
+ @native = native
35
91
  end
36
92
 
37
93
  def automatic_reserve? = @automatic_reserve
38
94
 
39
- # Automatic headroom fits output that shares the context window, plus
40
- # estimation and framing slack. An explicit reserve remains host policy.
41
- # An unknown window never triggers.
95
+ # The level in tokens above which a compaction is due: the threshold a
96
+ # host set, and never more than the window less the reserve. Automatic
97
+ # headroom fits output that shares the context window, plus estimation
98
+ # and framing slack. An explicit reserve remains host policy. With no
99
+ # window and no threshold in tokens there is none, and nothing triggers.
100
+ def threshold_tokens(window, max_output: nil)
101
+ own = share?(threshold) ? window && (window * threshold).floor : threshold
102
+ [own, ceiling(window, max_output:)].compact.min
103
+ end
104
+
105
+ # The most tokens a request may hold in a window: the window less the
106
+ # reserve. Nil with no window.
107
+ def ceiling(window, max_output: nil)
108
+ window && (window - effective_reserve(max_output))
109
+ end
110
+
42
111
  def needed?(tokens, window, max_output: nil)
43
- window ? tokens > window - effective_reserve(max_output) : false
112
+ limit = threshold_tokens(window, max_output:)
113
+ limit ? tokens > limit : false
114
+ end
115
+
116
+ # The tokens of recent turns a compaction keeps: keep_recent, and never
117
+ # more than half of what the threshold leaves above the fixed part of a
118
+ # request, its system prompt and tools. So about half of that room is
119
+ # free for the turns that follow.
120
+ def keep_within(threshold, fixed)
121
+ return keep_recent unless threshold
122
+
123
+ ((threshold - fixed) / 2).clamp(0, keep_recent)
44
124
  end
45
125
 
46
126
  private
47
127
 
128
+ def tokens?(value) = value.is_a?(Integer) && value.positive?
129
+
130
+ def share?(value) = value.is_a?(Float) && value.positive? && value <= 1
131
+
132
+ # A model id resolves at construction, so a missing key fails where the
133
+ # setting is written rather than in the middle of a run.
134
+ def summarizer(fallback)
135
+ return fallback if fallback.nil?
136
+ return fallback if fallback.respond_to?(:stream) && fallback.respond_to?(:model)
137
+ return Mistri.provider(fallback) if fallback.is_a?(String)
138
+
139
+ raise ArgumentError, "fallback must be a provider or a model id"
140
+ end
141
+
48
142
  def effective_reserve(max_output)
49
143
  return reserve unless automatic_reserve?
50
144
 
@@ -52,43 +146,114 @@ module Mistri
52
146
  end
53
147
 
54
148
  class << self
55
- # Context size for a replay: the last healthy turn's reported tokens
149
+ def context_tokens(messages, **)
150
+ level(messages, **).tokens
151
+ end
152
+
153
+ # The level of a replay: the last healthy turn's reported tokens
56
154
  # (prompt, cache, and output all sit in context next turn) plus an
57
- # estimate of every message after it.
58
- def context_tokens(messages, usage_from: 0)
155
+ # estimate of every message after it. counted is the provider's count of
156
+ # what a compaction left, which stands in until a turn reports. provider
157
+ # names whose rule estimates, when it is not the one that wrote the
158
+ # latest turn.
159
+ def level(messages, usage_from: 0, counted: nil, provider: nil)
59
160
  index = (usage_from...messages.length).reverse_each.find do |position|
60
161
  reported(messages[position])
61
162
  end
62
- base = index ? reported(messages[index]) : 0
63
- messages.drop(index ? index + 1 : 0).sum(base) { |message| estimate(message) }
163
+ base, from = if index then [reported(messages[index]).context_tokens, index + 1]
164
+ elsif counted then [counted, usage_from]
165
+ else [0, 0]
166
+ end
167
+ provider ||= latest_provider(messages)
168
+ estimated = messages.drop(from).sum { |message| estimate(message, provider) }
169
+ Level.new(tokens: base + estimated, estimated:)
170
+ end
171
+
172
+ # The tokens that each message and all after it hold in the context.
173
+ # The prompt a turn reported is the size of everything before that
174
+ # turn, so a tail is the level less that prompt. Only a message with no
175
+ # reported turn at or after it is estimated to the end.
176
+ def tail_tokens(messages, usage_from: 0, counted: nil, provider: nil)
177
+ provider ||= latest_provider(messages)
178
+ total = context_tokens(messages, usage_from:, counted:, provider:)
179
+ before = nil
180
+ estimated = 0
181
+ tails = Array.new(messages.length)
182
+ (messages.length - 1).downto(0) do |position|
183
+ message = messages[position]
184
+ usage = reported(message) if position >= usage_from
185
+ if usage then before = usage.context_tokens - usage.output
186
+ elsif before then before = [before - estimate(message, provider), 0].max
187
+ else estimated += estimate(message, provider)
188
+ end
189
+ tails[position] = before ? total - before : estimated
190
+ end
191
+ tails
192
+ end
193
+
194
+ # The provider's own count of the input tokens of a request. A call that
195
+ # still waits for its result is counted with an empty one, because
196
+ # Anthropic and OpenAI refuse to count a history that leaves a call
197
+ # unanswered. Nil when the provider has none or the count fails: an
198
+ # estimate stands then.
199
+ def count(provider, request)
200
+ return nil unless provider.respond_to?(:count_tokens)
201
+
202
+ provider.count_tokens(**request, messages: answered(request.fetch(:messages)))
203
+ rescue Error
204
+ nil
205
+ end
206
+
207
+ def latest_provider(messages)
208
+ messages.reverse_each.find { |message| message.assistant? && message.provider }&.provider
64
209
  end
65
210
 
66
- def estimate(message)
67
- (chars(message) / 4.0).ceil
211
+ def estimate(message, provider = nil)
212
+ rule = CLASS_CHARS_PER_TOKEN[provider]
213
+ message.content.sum { |block| tokens_of(block, rule) }.ceil
68
214
  end
69
215
 
70
216
  private
71
217
 
218
+ def answered(messages)
219
+ turn = messages.rindex(&:assistant?)
220
+ return messages unless turn
221
+
222
+ results = messages.drop(turn + 1).take_while(&:tool?).map(&:tool_call_id)
223
+ waiting = messages[turn].tool_calls.reject { |call| results.include?(call.id) }
224
+ return messages if waiting.empty?
225
+
226
+ empty = waiting.map do |call|
227
+ Message.tool(content: "", tool_call_id: call.id, tool_name: call.name)
228
+ end
229
+ messages.dup.insert(turn + 1 + results.length, *empty)
230
+ end
231
+
72
232
  def reported(message)
73
233
  return nil unless message.assistant? && message.usage
74
234
  return nil if %i[aborted error].include?(message.stop_reason)
75
235
 
76
- usage = message.usage
77
- total = usage.input + usage.cache_read + usage.cache_write + usage.output
78
- total.positive? ? total : nil
236
+ message.usage if message.usage.context_tokens.positive?
79
237
  end
80
238
 
81
- def chars(message)
82
- message.content.sum do |block|
83
- case block
84
- when Content::Text then block.text.length
85
- when Content::Thinking then block.thinking.length
86
- when Content::Image then IMAGE_CHARS
87
- when ToolCall then block.name.length + JSON.generate(block.arguments).length
88
- else 0
89
- end
239
+ def tokens_of(block, rule)
240
+ case block
241
+ when Content::Image then IMAGE_TOKENS
242
+ when Content::Text then tokens_in(block.text, rule)
243
+ when Content::Thinking then tokens_in(block.thinking, rule)
244
+ when Content::Compaction then tokens_in(block.text.to_s, rule)
245
+ else tokens_in("#{block.name}#{JSON.generate(block.arguments)}", rule)
90
246
  end
91
247
  end
248
+
249
+ def tokens_in(text, rule)
250
+ return text.length / CHARS_PER_TOKEN unless rule
251
+
252
+ words, digits, other = rule
253
+ spelled = text.count("a-zA-Z \n\t\r")
254
+ figures = text.count("0-9")
255
+ (spelled / words) + (figures / digits) + ((text.length - spelled - figures) / other)
256
+ end
92
257
  end
93
258
  end
94
259
  end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ class Compactor
5
+ # The plain text a summarizer reads when it cannot be given the
6
+ # conversation itself: tool calls by name and arguments, results as text,
7
+ # thinking never (it stays in its turn).
8
+ module Text
9
+ class << self
10
+ # A tool result is whole when the text fits the room, in tokens.
11
+ # When it does not, one length makes it fit, so the longest results
12
+ # are cut first, and never to less than the cut made when no window
13
+ # is known.
14
+ def of(messages, room = nil, estimator = nil)
15
+ texts = messages.map { |message| text_of(message) }
16
+ return render(messages, texts, TOOL_RESULT_MAX_CHARS) unless room
17
+
18
+ whole = render(messages, texts)
19
+ tokens = Compaction.estimate(Message.user(whole), estimator)
20
+ return whole if tokens <= room
21
+
22
+ results = messages.zip(texts).filter_map { |message, text| text.length if message.tool? }
23
+ fitting = (room * whole.length / tokens) - (whole.length - results.sum)
24
+ render(messages, texts, [shared_limit(results.sort, fitting), TOOL_RESULT_MAX_CHARS].max)
25
+ end
26
+
27
+ # The messages in as few runs as fit the room, each measured with
28
+ # its long results cut. One run when no room is known.
29
+ def parts(messages, room, estimator)
30
+ return [messages] unless room&.positive?
31
+
32
+ held = 0
33
+ messages.each_with_object([[]]) do |message, runs|
34
+ text = text_of(message)
35
+ text = truncate_tool_result(text, TOOL_RESULT_MAX_CHARS) if message.tool?
36
+ tokens = Compaction.estimate(Message.user(text), estimator)
37
+ if held + tokens > room && runs.last.any?
38
+ runs << []
39
+ held = 0
40
+ end
41
+ runs.last << message
42
+ held += tokens
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ def render(messages, texts, limit = nil)
49
+ messages.zip(texts).map do |message, text|
50
+ text = truncate_tool_result(text, limit) if limit && message.tool?
51
+ "#{message.role.to_s.upcase}:\n#{text}"
52
+ end.join("\n\n")
53
+ end
54
+
55
+ # The largest length such that the results, each cut to it, hold no
56
+ # more than the characters given.
57
+ def shared_limit(lengths, chars)
58
+ lengths.each_with_index do |length, index|
59
+ share = chars / (lengths.length - index)
60
+ return share if length > share
61
+
62
+ chars -= length
63
+ end
64
+ chars
65
+ end
66
+
67
+ def text_of(message)
68
+ message.content.filter_map do |block|
69
+ case block
70
+ when Content::Text then block.text
71
+ when Content::Image then "[image]"
72
+ when ToolCall then "[called #{block.name} with #{JSON.generate(block.arguments)}]"
73
+ end
74
+ end.join("\n")
75
+ end
76
+
77
+ # Large tool output remains durable and unchanged on ordinary model
78
+ # requests; only the lossy summary wire is bounded, with both ends
79
+ # kept.
80
+ def truncate_tool_result(text, limit)
81
+ return text if text.length <= limit
82
+
83
+ marker = "\n[tool result truncated; original length: #{text.length} characters]\n"
84
+ visible = limit - marker.length
85
+ head = (visible * 0.75).floor
86
+ "#{text[0, head]}#{marker}#{text[-(visible - head), visible - head]}"
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end