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
@@ -3,6 +3,7 @@
3
3
  require "json"
4
4
  require "securerandom"
5
5
  require "time"
6
+ require_relative "session/log"
6
7
 
7
8
  module Mistri
8
9
  # The durable record of a run: an append-only log of typed entries over a
@@ -11,15 +12,20 @@ module Mistri
11
12
  # knowing their shapes.
12
13
  #
13
14
  # A store implements two methods: append(id, entry_hash) and load(id) ->
14
- # array of entry hashes in append order. Everything else lives here.
15
+ # array of entry hashes in append order. One that also answers settled? and
16
+ # takes load(id, from: position) is read in part. Everything else lives here.
15
17
  class Session # rubocop:disable Metrics/ClassLength -- append-only ordering is the class contract
16
- attr_reader :id, :store
18
+ attr_reader :store
17
19
 
18
20
  def initialize(store:, id: nil)
19
21
  @store = store
20
- @id = id || SecureRandom.uuid
22
+ @log = Log.new(store, id || SecureRandom.uuid, checkpointed: true)
23
+ @id = @log.id
21
24
  end
22
25
 
26
+ # A string id is copied, so a caller cannot change which session this is.
27
+ def id = @id.is_a?(String) ? @id.dup : @id
28
+
23
29
  def append_message(message)
24
30
  append("message", "message" => message.to_h)
25
31
  message
@@ -35,6 +41,7 @@ module Mistri
35
41
  nil
36
42
  end
37
43
 
44
+ # The whole log, read fresh from the store: the caller owns the result.
38
45
  def entries = @store.load(@id)
39
46
 
40
47
  # Every call ID is a session-wide correlation key. Read and validate the
@@ -42,9 +49,9 @@ module Mistri
42
49
  # it accepts later turns. Approval control entries are audited in the same
43
50
  # ordered pass: they may only advance a prior assistant call.
44
51
  def tool_control_state
45
- audited = audit_history(entries)
52
+ audited = audit_history(window)
46
53
  approvals = audited.fetch(:approvals).map do |approval|
47
- decision = approval[:decision] && own_json(approval[:decision])
54
+ decision = approval[:decision] && Log.owned(approval[:decision])
48
55
  { call: rebuild_call(approval[:call]), decision: }
49
56
  end
50
57
  { tool_call_ids: audited.fetch(:tool_call_ids), approvals: }
@@ -70,26 +77,93 @@ module Mistri
70
77
  # brick every later turn with a provider rejection, so unsettled calls
71
78
  # get a synthesized interrupted result. Calls parked for human approval
72
79
  # stay open; resume owns those.
73
- def replay = replay_from(entries)
80
+ def replay = replay_from(window)
74
81
 
75
- # Context accounting ignores provider usage reported before the latest
76
- # compaction: those prompt counts describe the larger, pre-summary replay.
77
- # Until a post-compaction assistant turn reports fresh usage, the compacted
78
- # replay is estimated directly.
79
- def context_tokens
80
- log = entries
81
- replay = replay_from(log)
82
- compacted_at = log.rindex { |entry| entry["type"] == "compaction" }
83
- usage_from = if compacted_at
84
- replay.index { |(_, index)| index && index > compacted_at } || replay.length
85
- else
86
- 0
87
- end
88
- Compaction.context_tokens(replay.map(&:first), usage_from:)
82
+ def context_tokens = context_level.tokens
83
+
84
+ # The tokens in the context, and how many of them are estimated. provider
85
+ # names whose rule estimates: the one the next request goes to.
86
+ def context_level(provider: nil)
87
+ held = window
88
+ replay = replay_from(held)
89
+ Compaction.level(replay.map(&:first), provider:, **measured(held, replay))
90
+ end
91
+
92
+ # For each message of replay, the tokens it and all after it hold.
93
+ def tail_tokens(provider: nil)
94
+ held = window
95
+ replay = replay_from(held)
96
+ Compaction.tail_tokens(replay.map(&:first), provider:, **measured(held, replay))
89
97
  end
90
98
 
91
99
  def last_compaction
92
- entries.reverse_each.find { |entry| entry["type"] == "compaction" }
100
+ entry = window.entries.reverse_each.find { |candidate| candidate["type"] == "compaction" }
101
+ entry && Log.owned(entry)
102
+ end
103
+
104
+ # Write a compaction: replay starts at kept_from behind the summary. The
105
+ # entry carries what the loop needs from before it, so a later read can
106
+ # start there. The start may only move forward, to a turn boundary that
107
+ # keeps every open approval and every steer or report not folded in yet.
108
+ # A block is given the messages replay will hold and returns the
109
+ # provider's count of them, which the entry keeps as tokens_after. The
110
+ # entry also keeps the model that wrote the summary, the level before,
111
+ # what started the compaction, the seconds it took and the usage of its
112
+ # requests, when given. A
113
+ # summary that a provider wrote in its own compaction comes with the
114
+ # provider's block: the entry keeps it as it came, replay sends it back
115
+ # first, and summary is its text where it can be read. after: true puts a
116
+ # summary the gem wrote behind the turns it leaves.
117
+ def checkpoint(summary:, kept_from:, **details)
118
+ held = window
119
+ validate_cut!(held, kept_from)
120
+ carried = carried_before(held, kept_from)
121
+ entry = { "summary" => summary, "kept_from" => kept_from, "carried" => carried,
122
+ "trigger" => details[:trigger]&.to_s, "provider" => details[:provider]&.to_s }
123
+ .merge(details.slice(:model, :tokens_before, :duration, :block, :fallback_reason,
124
+ :after, :usage).transform_keys(&:to_s))
125
+ entry["tokens_after"] = yield(compacted(held, entry)) if block_given?
126
+ append("compaction", entry.compact)
127
+ note_loaded(carried.fetch("loaded", [])) if details[:block]
128
+ end
129
+
130
+ # The position of the newest compaction entry, as replay numbers
131
+ # positions. Nil when the session was never compacted.
132
+ def compacted_at
133
+ held = window
134
+ index = held.entries.rindex { |entry| entry["type"] == "compaction" }
135
+ index && held.position(index)
136
+ end
137
+
138
+ # False when nothing has been stored since the newest compaction, so
139
+ # another one would have nothing new to work on. The note of loaded tools
140
+ # that a checkpoint appends after a provider's block is not counted.
141
+ def grown_since_compaction?
142
+ log = window.entries
143
+ compacted_at = log.rindex { |entry| entry["type"] == "compaction" }
144
+ return true unless compacted_at
145
+
146
+ log.drop(compacted_at + 1).any? { |entry| entry.dig("message", "reminder") != "loaded_tools" }
147
+ end
148
+
149
+ # The earliest position replay must keep: the turn of an open approval,
150
+ # or a steer or report that is not folded in yet. Nil when nothing is open.
151
+ def open_from
152
+ held = window
153
+ open = audit_history(held).fetch(:approvals)
154
+ first = [approval_turn_start(held.entries, open), unfolded_start(held.entries)].compact.min
155
+ first && held.position(first)
156
+ end
157
+
158
+ # Failed summaries since the last checkpoint, all of them or only those
159
+ # of one trigger (:manual or :automatic). Automatic compaction counts its
160
+ # own failures to stop retrying one that has proven persistent.
161
+ def compaction_failures(trigger: nil)
162
+ log = window.entries
163
+ since = (log.rindex { |entry| entry["type"] == "compaction" } || -1) + 1
164
+ log.drop(since).count do |entry|
165
+ entry["type"] == "compaction_failed" && (trigger.nil? || entry["trigger"] == trigger.to_s)
166
+ end
93
167
  end
94
168
 
95
169
  # The inbox: entry types queued for the loop's next turn boundary, each
@@ -102,6 +176,8 @@ module Mistri
102
176
  # model sees them mid-run; one that arrives as the model finishes cleanly
103
177
  # extends the run another turn so it is answered, not left dangling.
104
178
  def steer(text)
179
+ raise ArgumentError, "steer needs text" if text.to_s.match?(/\A[[:space:]]*\z/)
180
+
105
181
  append("steer", "id" => SecureRandom.uuid, "message" => Message.user(text).to_h)
106
182
  end
107
183
 
@@ -116,10 +192,7 @@ module Mistri
116
192
  # for that. Reports normally arrive via SubAgent.run_dispatched; call this
117
193
  # directly only from a custom dispatch path.
118
194
  def deliver_report(name:, session_id:, status:, text: nil) # rubocop:disable Naming/PredicateMethod
119
- already = entries.any? do |entry|
120
- entry["type"] == "subagent_report" && entry["session_id"] == session_id
121
- end
122
- return false if already
195
+ return false if reported?(session_id)
123
196
 
124
197
  append("subagent_report", "id" => SecureRandom.uuid, "name" => name,
125
198
  "session_id" => session_id, "status" => status, "report" => text,
@@ -134,9 +207,10 @@ module Mistri
134
207
  # every process. A host that wakes an idle session when a steer arrives
135
208
  # should watch this instead: a report deserves the same pickup.
136
209
  def pending_inbox
137
- log = entries
138
- folded = log.flat_map { |entry| entry.values_at(*INBOX.values) }.compact.to_set
210
+ log = window.entries
211
+ folded = folded_ids(log)
139
212
  log.select { |entry| INBOX.key?(entry["type"]) && !folded.include?(entry["id"]) }
213
+ .map { |entry| Log.owned(entry) }
140
214
  end
141
215
 
142
216
  # The steer-only slice of the inbox, oldest first.
@@ -148,14 +222,32 @@ module Mistri
148
222
  # per link entry, each reading the child's own session. Derived from the
149
223
  # log alone, like everything else here.
150
224
  def children
151
- entries.filter_map do |entry|
152
- next unless entry["type"] == "subagent"
153
-
154
- Child.new(name: entry["name"], session_id: entry["session_id"], store: @store,
155
- parent_session_id: @id)
225
+ held = window
226
+ links = carried(held).fetch("children", []) + links_in(held.entries)
227
+ links.map do |link|
228
+ Child.new(name: Log.owned(link["name"]), session_id: Log.owned(link["session_id"]),
229
+ store: @store, parent_session_id: @id)
156
230
  end
157
231
  end
158
232
 
233
+ # Every checkpoint carries these, so the oldest give way.
234
+ MAX_CODE_DOCUMENTS = 1_000
235
+
236
+ # The documents code in this session has read or written, each with the
237
+ # version it had then, oldest first. A write from code replaces a
238
+ # document only at the version found here.
239
+ def code_documents
240
+ held = window
241
+ Log.owned(versions_in(held.entries, carried(held)["code_documents"]))
242
+ end
243
+
244
+ # What one run of code learned: pairs of a path and the version of the
245
+ # document it read or wrote there.
246
+ def remember_code_documents(versions)
247
+ versions = versions.last(MAX_CODE_DOCUMENTS)
248
+ append("code_documents", "versions" => versions) unless versions.empty?
249
+ end
250
+
159
251
  # The session as a reader renders it: entries in order with inline image
160
252
  # bytes stripped, and, with include_children, every sub-agent's own
161
253
  # transcript spliced in after its link entry. Spliced entries carry an
@@ -181,6 +273,160 @@ module Mistri
181
273
 
182
274
  private
183
275
 
276
+ # The entries from the newest checkpoint on, brought up to date. They
277
+ # are frozen and shared, so a public reader returns copies its caller owns.
278
+ def window = @log.window
279
+
280
+ # Context accounting ignores provider usage reported before the latest
281
+ # compaction: those prompt counts describe the larger, pre-summary replay.
282
+ # Until a turn after it reports fresh usage, the count the compaction
283
+ # stored stands in, and without one the replay is estimated.
284
+ def measured(held, replay)
285
+ compacted_at = held.entries.rindex { |entry| entry["type"] == "compaction" }
286
+ return { usage_from: 0 } unless compacted_at
287
+
288
+ position = held.position(compacted_at)
289
+ counted = held.entries[compacted_at]["tokens_after"]
290
+ { usage_from: replay.index { |(_, index)| index && index > position } || replay.length,
291
+ counted: (counted if counted.is_a?(Integer) && counted.positive?) }
292
+ end
293
+
294
+ def compacted(held, entry)
295
+ log = held.entries + [entry.compact.merge("type" => "compaction")]
296
+ replay_from(Log::Window.new(entries: log, offset: held.offset)).map(&:first)
297
+ end
298
+
299
+ # What the checkpoint the window starts at carries from before it.
300
+ def carried(held)
301
+ log = held.entries
302
+ index = log.rindex { |entry| entry["type"] == "compaction" }
303
+ return {} unless index && Log.checkpoint?(log[index], held.position(index))
304
+
305
+ log[index]["carried"]
306
+ end
307
+
308
+ def carried_before(held, kept_from)
309
+ before = held.entries.take(kept_from - held.offset)
310
+ kept = held.entries.drop(kept_from - held.offset)
311
+ state = carried(held)
312
+ state.merge("children" => state.fetch("children", []) + links_in(before),
313
+ "reported" => state.fetch("reported", []) | reports_in(before),
314
+ "approvals" => state.fetch("approvals", []) | legacy_approvals_in(before),
315
+ "loaded" => (state.fetch("loaded", []) | loads_in(before)) - loads_in(kept),
316
+ "code_documents" => versions_in(before, state["code_documents"]).to_a)
317
+ end
318
+
319
+ # Pairs and not an object, because a store may reorder the keys of one.
320
+ # What is not a pair of two strings is passed over: a document with no
321
+ # version here is refused, never written.
322
+ def versions_in(entries, carried)
323
+ lists = entries.select { |entry| entry["type"] == "code_documents" }
324
+ .map { |entry| entry["versions"] }
325
+ versions = {}
326
+ [carried, *lists].grep(Array).each do |pairs|
327
+ pairs.each do |path, version|
328
+ next unless path.is_a?(String) && version.is_a?(String)
329
+
330
+ versions.delete(path)
331
+ versions[path] = version
332
+ end
333
+ end
334
+ versions.drop([versions.size - MAX_CODE_DOCUMENTS, 0].max).to_h
335
+ end
336
+
337
+ # The deferred tools that results in these entries loaded. A failed
338
+ # result loads nothing, whatever it names.
339
+ def loads_in(entries)
340
+ entries.select { |entry| entry["type"] == "message" && !entry.dig("message", "tool_error") }
341
+ .flat_map { |entry| entry.dig("message", "loads").to_a }
342
+ end
343
+
344
+ # A decision written before decisions named their request is told apart
345
+ # only by its call id, and in such logs only an old call_N id repeats.
346
+ def legacy_approvals_in(entries)
347
+ entries.select { |entry| entry["type"] == "approval_request" }
348
+ .filter_map { |entry| entry.dig("call", "id") }.grep(LEGACY_CALL_ID)
349
+ end
350
+
351
+ def validate_cut!(held, kept_from)
352
+ log = held.entries
353
+ audit = audit_history(held)
354
+ latest = log.reverse_each.find { |entry| entry["type"] == "compaction" }
355
+ floor = [latest ? latest["kept_from"] : 0, held.offset].max
356
+ unless kept_from.is_a?(Integer) && kept_from.between?(floor, held.position(log.length))
357
+ raise ConfigurationError, "a compaction must start between the current start of " \
358
+ "replay and the end of the log"
359
+ end
360
+
361
+ cut = kept_from - held.offset
362
+ approval = approval_turn_start(log, audit.fetch(:approvals))
363
+ if approval && cut > approval
364
+ raise ConfigurationError, "a compaction cannot cut past an open approval"
365
+ end
366
+ if (unfolded = unfolded_start(log)) && cut > unfolded
367
+ raise ConfigurationError, "a compaction cannot cut past a steer or report that is " \
368
+ "not folded in"
369
+ end
370
+ return if turn_boundary?(log, cut)
371
+
372
+ raise ConfigurationError, "a compaction must start at a user message, at an assistant " \
373
+ "turn that calls tools, or at the end of the log"
374
+ end
375
+
376
+ # Everything a tool call leads to (its request, decision and result)
377
+ # follows it within its turn, so a start on a turn parts none of them.
378
+ def turn_boundary?(log, cut)
379
+ return true if cut == log.length
380
+
381
+ entry = log[cut]
382
+ return false unless entry["type"] == "message"
383
+
384
+ role = entry.dig("message", "role")
385
+ role == "user" || (role == "assistant" && tool_calls_from(entry).any?)
386
+ end
387
+
388
+ def splits_call?(states, cut)
389
+ states.any? do |state|
390
+ state[:result_index] && state[:source_index] < cut && state[:result_index] >= cut
391
+ end
392
+ end
393
+
394
+ def unfolded_start(log)
395
+ folded = folded_ids(log)
396
+ log.index { |entry| INBOX.key?(entry["type"]) && !folded.include?(entry["id"]) }
397
+ end
398
+
399
+ def links_in(entries)
400
+ entries.select { |entry| entry["type"] == "subagent" }
401
+ .map { |entry| entry.slice("name", "session_id") }
402
+ end
403
+
404
+ def reports_in(entries)
405
+ entries.select { |entry| entry["type"] == "subagent_report" }
406
+ .map { |entry| entry["session_id"] }
407
+ end
408
+
409
+ def reported?(session_id)
410
+ held = window
411
+ carried(held).fetch("reported", []).include?(session_id) ||
412
+ reports_in(held.entries).include?(session_id)
413
+ end
414
+
415
+ def folded_ids(log) = log.flat_map { |entry| entry.values_at(*INBOX.values) }.compact.to_set
416
+
417
+ def approval_turn_start(log, open)
418
+ return nil if open.empty?
419
+
420
+ ids = open.map { |approval| approval[:call]["id"] }
421
+ request = log.index do |entry|
422
+ entry["type"] == "approval_request" && ids.include?(entry.dig("call", "id"))
423
+ end
424
+ turn = request && log[0...request].rindex do |entry|
425
+ entry["type"] == "message" && entry.dig("message", "role") == "user"
426
+ end
427
+ turn || open.map { |approval| approval[:source_index] }.min
428
+ end
429
+
184
430
  def tool_calls_from(entry)
185
431
  Array(entry.dig("message", "content")).select do |block|
186
432
  block.is_a?(Hash) && block["type"].to_s == "tool_call"
@@ -208,7 +454,8 @@ module Mistri
208
454
  source_provider: message.provider,
209
455
  source_stop_reason: message.stop_reason,
210
456
  source_index: index, source_position: position,
211
- batch:, status: :pending, reused: !reused.nil? }
457
+ batch:, status: :pending,
458
+ reused: !reused.nil? || audit.fetch(:approval_ids).include?(id) }
212
459
  calls[owned] = state
213
460
  batch[:calls] << state
214
461
  audit.fetch(:states) << state
@@ -236,12 +483,13 @@ module Mistri
236
483
  prior
237
484
  end
238
485
 
239
- def audit_history(log)
486
+ def audit_history(held)
487
+ log = held.entries
240
488
  calls = {}
241
489
  unresolved = Set.new
242
490
  reserved = Set.new
243
491
  states = []
244
- approval_ids = Set.new
492
+ approval_ids = Set.new(carried(held).fetch("approvals", []))
245
493
  audit = { calls:, unresolved:, reserved:, states:, approval_ids: }
246
494
  latest_compaction = nil
247
495
 
@@ -258,9 +506,9 @@ module Mistri
258
506
  close_unsettled_calls(calls, unresolved)
259
507
  record_assistant_calls(entry, message, index, audit) if message.assistant?
260
508
  elsif entry["type"] == "approval_request"
261
- record_approval_call(entry, calls, audit)
509
+ record_approval_call(entry, held.position(index), calls, audit)
262
510
  elsif entry["type"] == "approval_decision"
263
- record_approval_decision(entry, calls)
511
+ record_approval_decision(entry, calls, late: held.offset.positive?)
264
512
  elsif entry["type"] == "compaction"
265
513
  latest_compaction = entry
266
514
  end
@@ -268,8 +516,8 @@ module Mistri
268
516
 
269
517
  interrupt_ambiguous_reused_approvals!(states)
270
518
  approvals = open_approval_states(states)
271
- validate_compaction!(audit, approvals, latest_compaction)
272
- { tool_call_ids: reserved, approvals:, call_states: calls }
519
+ validate_compaction!(audit, approvals, latest_compaction, held.offset)
520
+ { tool_call_ids: reserved, approvals:, call_states: calls, states: }
273
521
  end
274
522
 
275
523
  # Control entries can authorize side effects, so every message in the
@@ -351,7 +599,7 @@ module Mistri
351
599
  unresolved.clear
352
600
  end
353
601
 
354
- def record_approval_call(entry, calls, audit)
602
+ def record_approval_call(entry, position, calls, audit)
355
603
  call = entry["call"]
356
604
  unless call.is_a?(Hash)
357
605
  raise ConfigurationError, "session contains an invalid approval request"
@@ -384,7 +632,8 @@ module Mistri
384
632
  advance_call_order!(state, :approval_request_position, "approval requests")
385
633
  state[:batch][:approval_phase_started] = true
386
634
  state[:status] = :approval_requested
387
- state[:approval] = { call:, decision: nil, source_index: state[:source_index] }
635
+ state[:approval] = { call:, decision: nil, source_index: state[:source_index],
636
+ request: position }
388
637
  state[:ambiguous_approval] = state[:reused] && audit.fetch(:approval_ids).include?(id)
389
638
  audit.fetch(:approval_ids) << id
390
639
  end
@@ -420,7 +669,7 @@ module Mistri
420
669
  "same-name tool result"
421
670
  end
422
671
 
423
- def record_approval_decision(entry, calls)
672
+ def record_approval_decision(entry, calls, late:)
424
673
  id = entry["call_id"]
425
674
  problem = required_string_problem(id, "approval decision call IDs")
426
675
  raise ConfigurationError, "session contains #{problem}" if problem
@@ -431,18 +680,38 @@ module Mistri
431
680
  end
432
681
 
433
682
  state = calls[id]
434
- unless state && state[:approval]
435
- raise ConfigurationError, "session contains an approval decision without a prior " \
436
- "matching approval request"
437
- end
683
+ approval = answered_approval(entry, state, late:)
438
684
  # Store order is the write-once register. A stale loser can append after
439
685
  # execution, so it must not revoke the winner or corrupt the real result.
440
- return if state[:approval][:decision]
686
+ return if approval.nil? || approval[:decision]
441
687
 
442
- state[:approval][:decision] = entry
688
+ approval[:decision] = entry
443
689
  state[:status] = :decided
444
690
  end
445
691
 
692
+ # A decision names the request it answers and decides no other. One from
693
+ # before decisions did that goes by its call id, and past a checkpoint
694
+ # its call may be gone, so there it is skipped.
695
+ def answered_approval(entry, state, late:)
696
+ approval = state && state[:approval]
697
+ if entry.key?("request")
698
+ approval if approval&.fetch(:request) == named_request(entry)
699
+ elsif approval || (state.nil? && late)
700
+ approval
701
+ else
702
+ raise ConfigurationError, "session contains an approval decision without a prior " \
703
+ "matching approval request"
704
+ end
705
+ end
706
+
707
+ def named_request(entry)
708
+ request = entry["request"]
709
+ return request if request.is_a?(Integer) && request >= 0
710
+
711
+ raise ConfigurationError, "session contains an approval decision whose request is not " \
712
+ "a position in the log"
713
+ end
714
+
446
715
  # An old decision names only call_N. Once that ID has already participated
447
716
  # in approval, a later unsettled approval cannot prove which generation a
448
717
  # delayed decision intended, so replay it as interrupted rather than risk
@@ -461,22 +730,20 @@ module Mistri
461
730
  end
462
731
  end
463
732
 
464
- def validate_compaction!(audit, approvals, compaction)
733
+ def validate_compaction!(audit, approvals, compaction, offset)
465
734
  return unless compaction
466
735
 
467
736
  kept_from = compaction["kept_from"]
468
737
  unless kept_from.is_a?(Integer) && kept_from >= 0
469
738
  raise ConfigurationError, "session contains an invalid compaction boundary"
470
739
  end
740
+
741
+ kept_from -= offset
471
742
  if approvals.any? { |approval| approval[:source_index] < kept_from }
472
743
  raise ConfigurationError, "session contains an open approval whose assistant tool call " \
473
744
  "was removed by compaction"
474
745
  end
475
- split = audit.fetch(:states).any? do |state|
476
- state[:result_index] && state[:source_index] < kept_from &&
477
- state[:result_index] >= kept_from
478
- end
479
- return unless split
746
+ return unless splits_call?(audit.fetch(:states), kept_from)
480
747
 
481
748
  raise ConfigurationError, "session contains a compaction boundary that splits a tool call " \
482
749
  "from its result"
@@ -564,23 +831,58 @@ module Mistri
564
831
  call[field]
565
832
  end
566
833
 
567
- def replay_from(log)
568
- compaction = log.reverse_each.find { |entry| entry["type"] == "compaction" }
569
- from = compaction ? compaction["kept_from"] : 0
834
+ def replay_from(held)
835
+ log = held.entries
836
+ compacted_at = log.rindex { |entry| entry["type"] == "compaction" }
837
+ compaction = log[compacted_at] if compacted_at
838
+ from = compaction ? compaction["kept_from"] - held.offset : 0
839
+ stale = stale_before(compaction, compacted_at)
570
840
  pairs = log.each_with_index.filter_map do |entry, index|
571
841
  next unless index >= from && entry["type"] == "message"
572
842
 
573
- [Message.from_h(entry["message"]), index]
843
+ message = replay_message(entry, before_compaction: stale && index < stale)
844
+ [message, index] if message
574
845
  end
575
- pairs = heal(pairs, replay_call_states(log, from:))
576
- compaction ? [[summary_message(compaction["summary"]), nil], *pairs] : pairs
846
+ pairs = heal(pairs, replay_call_states(log, from:, held:))
847
+ pairs = pairs.map { |message, index| [message, index && held.position(index)] }
848
+ compaction ? with_summary(pairs, compaction, held.position(compacted_at)) : pairs
849
+ end
850
+
851
+ # A summary the gem wrote invalidates prefix-bound thinking in the kept
852
+ # tail. One the provider wrote in its own compaction keeps it valid.
853
+ def stale_before(compaction, compacted_at)
854
+ compacted_at unless compaction.nil? || compaction["block"]
855
+ end
856
+
857
+ # The summary stands first. One marked after stands behind the kept
858
+ # turns, before the first message stored after the compaction.
859
+ def with_summary(pairs, compaction, position)
860
+ first_after = pairs.index { |(_, index)| index && index > position } || pairs.length
861
+ pairs.insert(compaction["after"] ? first_after : 0, [summary_message(compaction), nil])
862
+ end
863
+
864
+ # Only replay drops stale thinking: the transcript and thoughts from the
865
+ # new prefix survive.
866
+ def replay_message(entry, before_compaction:)
867
+ message = Message.from_h(Log.owned(entry["message"]))
868
+ return message unless before_compaction && message.assistant? &&
869
+ message.provider == :anthropic &&
870
+ Models.prefix_bound_thinking?(message.model)
871
+
872
+ content = message.content.grep_v(Content::Thinking)
873
+ return message if content.length == message.content.length
874
+ return if content.all? { |block| block.is_a?(Content::Text) && block.text.empty? }
875
+
876
+ message.with(content:)
577
877
  end
578
878
 
579
879
  # Replay only needs occurrence pairing, not the authorization audit. Keep
580
880
  # it tolerant enough to render a rejected history while still ensuring a
581
881
  # reused call_N cannot borrow an earlier result or approval.
582
- def replay_call_states(log, from:)
583
- replay = { active: {}, seen: Set.new, approval_ids: Set.new, states: [], from: }
882
+ def replay_call_states(log, from:, held:)
883
+ approvals = carried(held).fetch("approvals", [])
884
+ replay = { active: {}, seen: Set.new(approvals), approval_ids: Set.new(approvals),
885
+ states: [], from: }
584
886
  log.each_with_index do |entry, index|
585
887
  if entry["type"] == "message"
586
888
  track_replay_message(entry, index, replay)
@@ -663,8 +965,36 @@ module Mistri
663
965
  tool_name: call.name, tool_error: true), nil]
664
966
  end
665
967
 
666
- def summary_message(summary)
667
- Message.user("#{Compaction::SUMMARY_PREFACE}\n\n#{summary}")
968
+ # The summary, and after it the tools the summarized part had loaded. It
969
+ # is built from the compaction entry alone, so it never changes. A
970
+ # provider's own block stands alone and first, as that provider asks.
971
+ def summary_message(compaction)
972
+ return provider_summary(compaction) if compaction["block"]
973
+
974
+ preface = compaction["after"] ? Compaction::SUMMARY_PREFACE_AFTER : Compaction::SUMMARY_PREFACE
975
+ text = "#{preface}\n\n#{compaction["summary"]}"
976
+ loaded = compaction.dig("carried", "loaded").to_a
977
+ loaded.empty? ? Message.user(text) : Message.user("#{text}\n\n#{loaded_note(loaded)}")
978
+ end
979
+
980
+ def provider_summary(compaction)
981
+ provider = compaction.fetch("provider").to_sym
982
+ block = Content::Compaction.new(provider:, data: Log.owned(compaction["block"]),
983
+ text: compaction["summary"])
984
+ Message.assistant(content: [block], provider:, model: compaction["model"])
985
+ end
986
+
987
+ def loaded_note(loaded)
988
+ "These tools were loaded before this summary: #{loaded.join(", ")}. Their definitions " \
989
+ "are no longer in your context. Before you call one, load it again with " \
990
+ "#{ToolSearch::NAME}: use select: followed by the names as the query. Load only the " \
991
+ "ones you need."
992
+ end
993
+
994
+ # Nothing may stand between a provider's block and the turns kept after
995
+ # it, so the note follows them as a reminder.
996
+ def note_loaded(loaded)
997
+ append_message(Message.reminder("loaded_tools", loaded_note(loaded))) if loaded.any?
668
998
  end
669
999
 
670
1000
  # Each link entry opens its child's log in place, depth first, the way
@@ -701,7 +1031,8 @@ module Mistri
701
1031
  end
702
1032
 
703
1033
  def decide(call_id, approved:, note:)
704
- open = open_approvals.find { |approval| approval[:call].id == call_id }
1034
+ open = audit_history(window).fetch(:approvals)
1035
+ .find { |approval| approval[:call]["id"] == call_id }
705
1036
  unless open
706
1037
  winner = recorded_approval_decision(call_id)
707
1038
  return nil if winner && winner["approved"] == approved
@@ -718,32 +1049,31 @@ module Mistri
718
1049
  raise ConfigurationError, "approval for #{call_id.inspect} has already been decided"
719
1050
  end
720
1051
 
721
- entry = { "call_id" => call_id, "approved" => approved }
1052
+ entry = { "call_id" => call_id, "approved" => approved, "request" => open[:request] }
722
1053
  entry["note"] = note if note
723
1054
  append("approval_decision", entry)
724
1055
 
725
1056
  # The two-method Store contract cannot combine the precheck and append.
726
1057
  # Re-read its total order so a racing conflicting caller learns it lost.
727
- winner = recorded_approval_decision(call_id)
1058
+ winner = decision_on(open[:request])
728
1059
  return nil if winner && winner["approved"] == approved
729
1060
 
730
1061
  raise ConfigurationError, "approval for #{call_id.inspect} has already been decided"
731
1062
  end
732
1063
 
733
1064
  def recorded_approval_decision(call_id)
734
- state = audit_history(entries).fetch(:call_states)[call_id]
1065
+ state = audit_history(window).fetch(:call_states)[call_id]
735
1066
  return nil if state&.fetch(:ambiguous_approval, false)
736
1067
 
737
1068
  state&.dig(:approval, :decision)
738
1069
  end
739
1070
 
740
- def own_json(value)
741
- case value
742
- when Hash then value.to_h { |key, nested| [own_json(key), own_json(nested)] }
743
- when Array then value.map { |nested| own_json(nested) }
744
- when String then value.dup
745
- else value
746
- end
1071
+ # A request the window no longer holds was settled before the newest
1072
+ # checkpoint, by a decision that cannot be seen from here.
1073
+ def decision_on(request)
1074
+ audit_history(window).fetch(:states)
1075
+ .find { |state| state.dig(:approval, :request) == request }
1076
+ &.dig(:approval, :decision)
747
1077
  end
748
1078
 
749
1079
  def rebuild_call(hash)