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
@@ -42,10 +42,12 @@ module Mistri
42
42
  Tool.define(
43
43
  "read_agent",
44
44
  "Read what a worker has done so far without interrupting it, or pass " \
45
- "wait to block until it finishes and get its report.",
45
+ "wait to block until it finishes and get its report. Each line starts " \
46
+ "with the entry's number, and offset reads from another entry.",
46
47
  schema: lambda {
47
48
  string :agent, "The worker's name or session id", required: true
48
- integer :tail, "How many recent entries to read (default 20)"
49
+ integer :offset, "The number of the first entry to read (default: the most recent)"
50
+ integer :limit, "How many entries to read (default 20, at most 200)"
49
51
  boolean :wait, "Block until the worker finishes, then return its report"
50
52
  }
51
53
  ) do |args, context|
@@ -55,7 +57,9 @@ module Mistri
55
57
  if args["wait"]
56
58
  Console.await(child, timeout, poll, context.signal)
57
59
  else
58
- Console.render(child, args.fetch("tail", 20).to_i.clamp(1, 200))
60
+ # tail is what limit was called; a session from before still says it.
61
+ limit = args.fetch("limit") { args.fetch("tail", 20) }
62
+ Console.render(child, limit.to_i.clamp(1, 200), offset: args["offset"])
59
63
  end
60
64
  end
61
65
  end
@@ -156,15 +160,42 @@ module Mistri
156
160
  "#{child.name} #{child.status}." + (report ? "\n#{report}" : "")
157
161
  end
158
162
 
159
- # A compact, readable transcript for a model: one line per entry, text
160
- # extracted, long values truncated. The gem never summarizes; the
161
- # caller can.
162
- def render(child, tail)
163
- entries = child.transcript(tail: tail)
164
- return "#{child.name} (#{child.status}): no entries yet." if entries.empty?
163
+ # A compact, readable page of a transcript for a model: one line per
164
+ # entry under its number, text extracted, long values truncated. The
165
+ # most recent entries by default, or the ones from offset. The gem never
166
+ # summarizes; the caller can.
167
+ def render(child, limit, offset: nil)
168
+ who = "#{child.name} (#{child.status})"
169
+ total = child.size
170
+ return "#{who}: no entries yet." if total.zero?
171
+
172
+ first = offset ? [offset.to_i, 0].max : [total - limit, 0].max
173
+ # A worker may write on between the count and the read; the page stays
174
+ # inside the count it states.
175
+ entries = child.transcript(from: first, to: [first + limit, total].min)
176
+ if entries.empty?
177
+ return "#{who} has #{total} entries, numbered 0 to #{total - 1}. " \
178
+ "Nothing is at offset #{first}."
179
+ end
180
+
181
+ lines = entries.each_with_index.filter_map do |entry, index|
182
+ line = Console.line(entry)
183
+ "#{first + index}: #{line.gsub(/\R/, '\n')}" if line
184
+ end
185
+ ["#{who}, entries #{first} to #{first + entries.length - 1} of #{total}:", *lines,
186
+ *Console.further(first, entries.length, limit, total)].join("\n")
187
+ end
165
188
 
166
- lines = entries.map { |entry| Console.line(entry) }.compact
167
- "#{child.name} (#{child.status}), last #{lines.length} entries:\n#{lines.join("\n")}"
189
+ # The offset and limit that read on from a page, in either direction,
190
+ # without reading an entry twice.
191
+ def further(first, shown, limit, total)
192
+ lines = []
193
+ if first.positive?
194
+ back = [first - limit, 0].max
195
+ lines << "Earlier entries: offset #{back}, limit #{first - back}."
196
+ end
197
+ lines << "Later entries: offset #{first + shown}, limit #{limit}." if first + shown < total
198
+ lines
168
199
  end
169
200
 
170
201
  def line(entry)
@@ -178,6 +209,8 @@ module Mistri
178
209
  # Tool calls ride the message's content as typed blocks, never as a
179
210
  # separate key; render both channels from the blocks.
180
211
  def message_line(message)
212
+ return "reminder: #{message["reminder"]}" if message["reminder"]
213
+
181
214
  blocks = message["content"].is_a?(Array) ? message["content"] : []
182
215
  calls = blocks.filter_map do |block|
183
216
  next unless block.is_a?(Hash) && block["type"] == "tool_call"
@@ -14,6 +14,18 @@ module Mistri
14
14
  s.frozen? ? s : s.dup.freeze
15
15
  end
16
16
 
17
+ # Strict base64 of what the text decodes to. Providers refuse line breaks,
18
+ # missing padding, the URL-safe alphabet and pad bits that are not zero,
19
+ # so Ruby's strict decoder decides whether the text is kept as it is.
20
+ # Anything else is read the way MIME reads base64 and written again.
21
+ def self.strict_base64(text)
22
+ text = text.to_s
23
+ text.unpack1("m0")
24
+ freeze_string(text)
25
+ rescue ArgumentError
26
+ [text.b.tr("-_", "+/").unpack1("m")].pack("m0").freeze
27
+ end
28
+
17
29
  # `signature` carries opaque provider metadata that must round-trip, such as
18
30
  # the OpenAI Responses message id and output phase.
19
31
  Text = Data.define(:text, :signature) do
@@ -48,7 +60,12 @@ module Mistri
48
60
  end
49
61
  end
50
62
 
51
- # A base64-encoded image with its MIME type.
63
+ PNG_START = "\x89PNG\r\n\x1A\n".b.freeze
64
+ JPEG_START = "\xFF\xD8\xFF".b.freeze
65
+ private_constant :PNG_START, :JPEG_START
66
+
67
+ # An image as strict base64, whatever form of base64 it was given in, with
68
+ # its MIME type.
52
69
  Image = Data.define(:data, :mime_type) do
53
70
  # Frozen at the pack site so the initializer's ownership check skips a
54
71
  # second copy of what can be a multi-megabyte payload.
@@ -60,20 +77,68 @@ module Mistri
60
77
  match = /\Adata:(?<mime>[^;,]+);base64,(?<data>.+)\z/m.match(uri.to_s)
61
78
  raise ArgumentError, "not a base64 data: URI" unless match
62
79
 
63
- new(data: match[:data].delete("\n").freeze, mime_type: match[:mime])
80
+ new(data: match[:data], mime_type: match[:mime])
64
81
  end
65
82
 
66
83
  def initialize(data:, mime_type:)
67
- super(data: Content.freeze_string(data), mime_type: Content.freeze_string(mime_type))
84
+ super(data: Content.strict_base64(data), mime_type: Content.freeze_string(mime_type))
68
85
  end
69
86
 
87
+ # On Ruby 3.2 Data#with skips initialize, and the data must stay strict.
88
+ def with(data: self.data, mime_type: self.mime_type) = self.class.new(data:, mime_type:)
89
+
70
90
  def type = :image
71
91
 
72
92
  def bytes = data.unpack1("m0")
73
93
 
94
+ # The type the first bytes show, of the four that Anthropic and OpenAI
95
+ # take, or nil. A label can be wrong, and Anthropic refuses an image
96
+ # whose label and bytes differ, so those two are sent this type.
97
+ def detected_mime_type
98
+ head = data[0, 24].unpack1("m")
99
+ if head.start_with?(PNG_START) then "image/png"
100
+ elsif head.start_with?(JPEG_START) then "image/jpeg"
101
+ elsif head.start_with?("GIF87a", "GIF89a") then "image/gif"
102
+ elsif head.start_with?("RIFF") && head[8, 4] == "WEBP" then "image/webp"
103
+ end
104
+ end
105
+
106
+ # What those two are sent in place of an image of any other format. It
107
+ # is built for each request, so it speaks of the model that reads it.
108
+ def placeholder
109
+ "[This image is not sent to this model: its data is not a PNG, JPEG, GIF or WebP, the " \
110
+ "formats this model takes. It is labelled #{mime_type.inspect}.]"
111
+ end
112
+
74
113
  def to_h = { type: :image, data:, mime_type: }
75
114
  end
76
115
 
116
+ # A summary of earlier messages that a provider wrote in its own
117
+ # compaction. `data` is the block as it came, which that provider takes
118
+ # back unchanged and no other provider can read. `text` is the summary
119
+ # where a person can read it, and nil where the provider keeps it sealed.
120
+ Compaction = Data.define(:provider, :data, :text) do
121
+ def initialize(provider:, data:, text: nil)
122
+ text = Content.freeze_string(text) if text
123
+ super(provider: provider.to_sym, data:, text:)
124
+ end
125
+
126
+ def type = :compaction
127
+
128
+ def to_h = { type: :compaction, provider:, data:, text: }.compact
129
+ end
130
+
131
+ # A session stays on one provider: a compaction that one wrote is refused
132
+ # before it reaches another.
133
+ def self.refuse_foreign_compaction!(messages, provider)
134
+ first = messages.first
135
+ block = first && first.content.grep(Compaction).first
136
+ return if block.nil? || block.provider == provider
137
+
138
+ raise ConfigurationError, "this session holds a compaction that #{block.provider} wrote, " \
139
+ "and only #{block.provider} can read it"
140
+ end
141
+
77
142
  # Coerce a value into a list of blocks: nil becomes none, a String becomes
78
143
  # one Text block, blocks pass through, arrays may mix all of these.
79
144
  def self.wrap(content)
@@ -92,6 +157,8 @@ module Mistri
92
157
  Thinking.new(thinking: h["thinking"], signature: h["signature"],
93
158
  redacted: h.fetch("redacted", false))
94
159
  when "image" then Image.new(data: h["data"], mime_type: h["mime_type"])
160
+ when "compaction"
161
+ Compaction.new(provider: h["provider"], data: h["data"], text: h["text"])
95
162
  when "tool_call"
96
163
  arguments = h.key?("arguments") ? h["arguments"] : {}
97
164
  ToolCall.new(id: h["id"], name: h["name"], arguments:,
@@ -9,7 +9,7 @@ module Mistri
9
9
  #
10
10
  # ---
11
11
  # role: Trip Planner
12
- # model: claude-opus-4-8
12
+ # model: claude-opus-5-5
13
13
  # tools:
14
14
  # - search_flights
15
15
  # - book_hotel
@@ -29,7 +29,7 @@ module Mistri
29
29
  attr_reader :name, :body, :config
30
30
 
31
31
  def self.load(path)
32
- match = FRONTMATTER.match(File.read(path))
32
+ match = FRONTMATTER.match(File.read(path, encoding: Encoding::UTF_8))
33
33
  raise ConfigurationError, "#{path} has no frontmatter" unless match
34
34
 
35
35
  config = YAML.safe_load(match[:yaml]) || {}
data/lib/mistri/edit.rb CHANGED
@@ -121,13 +121,13 @@ module Mistri
121
121
  end
122
122
 
123
123
  # Match the old text's lines against a window of content lines, comparing
124
- # each line stripped of leading and trailing whitespace. The matched region
125
- # is the exact original bytes those content lines span.
124
+ # each line stripped of leading and trailing whitespace. A final line
125
+ # separator belongs to the match only when the old text includes it.
126
126
  def fuzzy_match(content, edit)
127
127
  lines = line_spans(content)
128
128
  wanted = edit[:old].lines.map(&:strip)
129
- wanted.pop if wanted.last == "" # a trailing newline in old text is not a line to match
130
- return nil if wanted.empty?
129
+ # Whitespace alone must not turn an empty line into a zero-length match.
130
+ return nil if wanted.empty? || wanted == [""]
131
131
 
132
132
  windows = matching_windows(lines, wanted)
133
133
  return nil if windows.empty?
@@ -135,8 +135,15 @@ module Mistri
135
135
  raise EditError, ambiguous_message(edit, windows.map { |w| w + 1 }) if windows.length > 1
136
136
 
137
137
  first = windows.first
138
- Match.new(lines[first][:start], lines[first + wanted.length - 1][:finish],
139
- edit[:new], edit[:index])
138
+ finish = fuzzy_finish(content, lines[first + wanted.length - 1][:finish], edit[:old])
139
+ Match.new(lines[first][:start], finish, edit[:new], edit[:index])
140
+ end
141
+
142
+ def fuzzy_finish(content, finish, old)
143
+ return finish if old.end_with?("\n")
144
+ return finish - 2 if content[finish - 2, 2] == "\r\n"
145
+
146
+ content[finish - 1] == "\n" ? finish - 1 : finish
140
147
  end
141
148
 
142
149
  # When nothing matched, show the model the closest region and exactly how
@@ -161,7 +168,6 @@ module Mistri
161
168
  lines = line_spans(content)
162
169
  wanted_raw = old_text.lines.map(&:chomp)
163
170
  wanted = wanted_raw.map(&:strip)
164
- wanted.pop && wanted_raw.pop if wanted.last == ""
165
171
  return nil if wanted.empty? || lines.length < wanted.length
166
172
 
167
173
  best = best_window(lines, wanted)
data/lib/mistri/errors.rb CHANGED
@@ -39,6 +39,14 @@ module Mistri
39
39
  end
40
40
 
41
41
  class AuthenticationError < ProviderError
42
+ # The WWW-Authenticate header of the refusal, when the response had one.
43
+ attr_reader :challenge
44
+
45
+ def initialize(message = nil, challenge: nil, **)
46
+ @challenge = challenge
47
+ super(message, **)
48
+ end
49
+
42
50
  def self.default_message = "invalid or missing API key"
43
51
  end
44
52
 
@@ -99,12 +107,37 @@ module Mistri
99
107
  def self.default_message = "provider rejected the request"
100
108
  end
101
109
 
110
+ # The provider refused the request because its input is longer than the
111
+ # model's context window. A compaction can make the next request fit.
112
+ class ContextTooLongError < InvalidRequestError
113
+ def self.default_message = "the request is longer than the model's context window"
114
+
115
+ # error as this type when the block says that its status and body are
116
+ # the provider's refusal of an input that is too long.
117
+ def self.from(error)
118
+ return error unless error.is_a?(ProviderError) && error.status
119
+ return error unless yield(error.status, error.body.to_s)
120
+
121
+ new(status: error.status, body: error.body)
122
+ end
123
+ end
124
+
102
125
  # Tool arguments or structured output that violate their declared schema.
103
126
  class SchemaError < Error; end
104
127
 
105
128
  # A run cancelled by the host, raised only when the caller opts into raising.
106
129
  class AbortError < Error; end
107
130
 
131
+ # Another runner holds the session's lease. Nothing was appended.
132
+ class SessionBusyError < Error
133
+ attr_reader :session_id
134
+
135
+ def initialize(message, session_id:)
136
+ @session_id = session_id
137
+ super(message)
138
+ end
139
+ end
140
+
108
141
  # A cost-budgeted request returned without trustworthy accounting. Usage and
109
142
  # provider_message preserve the uncertain attempt for host reconciliation.
110
143
  class BudgetError < Error
@@ -152,6 +185,10 @@ module Mistri
152
185
  module ErrorData
153
186
  module_function
154
187
 
188
+ # Whether the data of an errored message says that the request was
189
+ # longer than the model's context window.
190
+ def too_long?(error) = !error.nil? && error["type"] == "ContextTooLongError"
191
+
155
192
  def for(reason)
156
193
  case reason
157
194
  when RateLimitError
data/lib/mistri/event.rb CHANGED
@@ -15,29 +15,38 @@ module Mistri
15
15
  # means no duration is available, not necessarily that no side effect ran.
16
16
  # tool_error is explicit on :tool_result and does not change Event#error?,
17
17
  # which means a terminal provider-turn failure.
18
+ # A compaction's events say what started it in reason, :manual or
19
+ # :automatic, the level before and after in tokens_before and tokens_after,
20
+ # and the seconds it took in duration.
18
21
  class Event < Data.define(:type, :content_index, :delta, :content, :tool_call,
19
22
  :reason, :message, :error_message, :partial, :origin,
20
23
  :duration, :attempt, :max_attempts, :delay,
21
- :agent, :session_id, :status, :tool_error)
24
+ :agent, :session_id, :status, :tool_error,
25
+ :tokens_before, :tokens_after)
22
26
  # The stream types come from a provider mid-turn; the loop adds
23
27
  # :tool_started when a resolved tool commits to execution, :tool_result
24
28
  # after it finishes, :approval_needed when a gated call parks for a human,
25
- # :compacting/:compaction around a context
26
- # compaction, and :retry (with attempt, max_attempts, delay) before it
27
- # waits out a transient failure, so one subscription sees the whole
28
- # exchange. :done and :error are loop-owned and terminal: only the
29
- # accepted attempt's terminal event reaches the subscriber.
29
+ # :compacting before a context compaction and then :compaction or
30
+ # :compaction_failed (the reason in error_message), and :retry (with
31
+ # attempt, max_attempts, delay) before it waits out a transient failure,
32
+ # so one subscription sees the whole exchange. :done and :error are
33
+ # loop-owned and terminal: only the accepted attempt's terminal event
34
+ # reaches the subscriber.
30
35
  # :subagent_report announces a background child's terminal outcome
31
36
  # (agent, session_id, status; content carries the report), so a UI that
32
37
  # watched the spawn can settle the child's lane the moment it ends.
38
+ # :thinking_dropped says the provider discarded replayed thinking it could
39
+ # no longer verify; content carries its reasons. Anthropic sends it after
40
+ # :start, and OpenAI only with the finished response.
33
41
  TYPES = %i[
34
42
  start
43
+ thinking_dropped
35
44
  text_start text_delta text_end
36
45
  thinking_start thinking_delta thinking_end
37
46
  toolcall_start toolcall_delta toolcall_end
38
47
  done error
39
48
  tool_started tool_result approval_needed
40
- compacting compaction
49
+ compacting compaction compaction_failed
41
50
  retry
42
51
  subagent_report
43
52
  ].freeze
@@ -45,7 +54,8 @@ module Mistri
45
54
  def initialize(type:, content_index: nil, delta: nil, content: nil, tool_call: nil,
46
55
  reason: nil, message: nil, error_message: nil, partial: nil, origin: nil,
47
56
  duration: nil, attempt: nil, max_attempts: nil, delay: nil,
48
- agent: nil, session_id: nil, status: nil, tool_error: nil)
57
+ agent: nil, session_id: nil, status: nil, tool_error: nil,
58
+ tokens_before: nil, tokens_after: nil)
49
59
  raise ArgumentError, "unknown event type #{type.inspect}" unless TYPES.include?(type)
50
60
 
51
61
  if type == :tool_result
@@ -74,7 +84,8 @@ module Mistri
74
84
  def to_h
75
85
  { type:, content_index:, delta:, content:, tool_call: tool_call&.to_h,
76
86
  reason:, message: message&.to_h, error_message:, origin:, duration:,
77
- attempt:, max_attempts:, delay:, agent:, session_id:, status:, tool_error: }.compact
87
+ attempt:, max_attempts:, delay:, agent:, session_id:, status:, tool_error:,
88
+ tokens_before:, tokens_after: }.compact
78
89
  end
79
90
  end
80
91
  end
@@ -12,14 +12,20 @@ module Mistri
12
12
  @cache = cache || (defined?(Rails) && Rails.cache) ||
13
13
  raise(ConfigurationError, "no cache store; pass cache: or configure Rails.cache")
14
14
  @namespace = namespace
15
+ return unless defined?(ActiveSupport::Cache::NullStore)
16
+ return unless @cache.is_a?(ActiveSupport::Cache::NullStore)
17
+
18
+ warn "mistri: Mistri::Locks::RailsCache was given a null cache store, which grants " \
19
+ "every lock, so two runs can write one session at once. Pass a cache that every " \
20
+ "process shares."
15
21
  end
16
22
 
17
23
  def acquire(key, ttl:)
18
- @cache.write(scoped(key), true, unless_exist: true, expires_in: ttl)
24
+ write(key, unless_exist: true, expires_in: ttl)
19
25
  end
20
26
 
21
27
  def renew(key, ttl:)
22
- @cache.write(scoped(key), true, expires_in: ttl)
28
+ write(key, expires_in: ttl)
23
29
  nil
24
30
  end
25
31
 
@@ -42,6 +48,14 @@ module Mistri
42
48
 
43
49
  private
44
50
 
51
+ # Redis and Memcache stores answer nil, not false, when the backend is down.
52
+ def write(key, **)
53
+ written = @cache.write(scoped(key), true, **)
54
+ raise Error, "lock cache write failed for #{scoped(key)}" if written.nil?
55
+
56
+ written
57
+ end
58
+
45
59
  def scoped(key) = "#{@namespace}:#{key}"
46
60
  end
47
61
  end
data/lib/mistri/locks.rb CHANGED
@@ -61,10 +61,19 @@ module Mistri
61
61
  sleep (deadline - now).clamp(0.01, 1.0)
62
62
  break if @stopping
63
63
 
64
- signal.abort!("stopped by user") if stop_key && signal && adapter.flag?(stop_key)
65
- if now >= deadline
64
+ begin
65
+ signal.abort!("stopped by user") if stop_key && signal && adapter.flag?(stop_key)
66
+ rescue StandardError
67
+ nil # retried next tick; renewal failures warn
68
+ end
69
+ next if now < deadline
70
+
71
+ deadline = now + heartbeat
72
+ begin
66
73
  adapter.renew(key, ttl: ttl)
67
- deadline = now + heartbeat
74
+ rescue StandardError => e
75
+ warn "mistri: renewing lease #{key} failed (#{e.class}: #{e.message}); " \
76
+ "retrying in #{heartbeat}s"
68
77
  end
69
78
  end
70
79
  end