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,345 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require "securerandom"
6
+ require "wasmtime"
7
+ require_relative "../sandbox"
8
+
9
+ module Mistri
10
+ module Sandbox
11
+ # JavaScript in QuickJS compiled to WebAssembly, run by wasmtime inside the
12
+ # host's process. Not auto-required, because wasmtime is an optional gem.
13
+ # The pinned build is quickjs.wasm of the npm package quickjs-wasi 3.7.0.
14
+ # Every import of the module is defined below, so the code reaches nothing
15
+ # else. While the code computes it holds the interpreter lock. It passes
16
+ # the lock on at QuickJS's interrupt checks, which one built-in call never
17
+ # makes, so other threads can wait for as long as timeout.
18
+ class QuickJS
19
+ SHA256 = "c0bd8f296e18cf074969f6401b9ecb72609a1323818ec2b9bf7a8f8d740d1363"
20
+ WASI = "wasi_snapshot_preview1"
21
+ EXPORTS = %w[
22
+ _initialize qjs_init qjs_eval qjs_new_string qjs_get_string_len qjs_free_cstring
23
+ qjs_free_value qjs_is_exception qjs_get_exception qjs_execute_pending_job
24
+ qjs_is_job_pending qjs_set_memory_limit qjs_set_interrupt_handler qjs_get_global
25
+ qjs_set_prop_string qjs_new_host_function qjs_set_max_stack_size wasm_malloc wasm_free
26
+ ].freeze
27
+ PRELUDE = <<~JS
28
+ (() => {
29
+ const host = globalThis.__host;
30
+ delete globalThis.__host;
31
+ const { stringify, parse } = JSON;
32
+ const wellFormed = Function.prototype.call.bind(String.prototype.toWellFormed);
33
+ // A string cut inside an emoji holds half of a pair, which UTF-8 cannot carry.
34
+ const sendable = (_key, value) => typeof value === "string" ? wellFormed(value) : value;
35
+ const call = (op, payload) => {
36
+ const reply = parse(host(stringify({ __proto__: null, op, ...payload }, sendable)));
37
+ if (reply.error !== undefined) throw new Error(reply.error);
38
+ return reply.value;
39
+ };
40
+ globalThis.files = Object.freeze({
41
+ read: (path) => call("read", { path }),
42
+ write: (path, content) => call("write", { path, content: String(content) }),
43
+ list: (prefix) => call("list", { prefix }),
44
+ delete: (path) => call("delete", { path }),
45
+ });
46
+ const text = (part) => typeof part === "string" ? part : stringify(part);
47
+ const say = (...parts) => call("print", { text: parts.map(text).join(" ") });
48
+ globalThis.console = Object.freeze({ log: say, info: say, warn: say, error: say });
49
+ globalThis.tools = new Proxy({}, {
50
+ get: (_target, name) => async (args) => call("tool", { name, arguments: args || {} }),
51
+ });
52
+ const failed = (error) => call("throw", {
53
+ message: error && error.stack ? String(error) + "\\n" + error.stack : String(error),
54
+ });
55
+ globalThis.__run = (body) => {
56
+ const AsyncFunction = (async () => {}).constructor;
57
+ let run;
58
+ try {
59
+ run = new AsyncFunction(body);
60
+ } catch (error) {
61
+ return failed(error);
62
+ }
63
+ run().then(
64
+ (value) => {
65
+ try {
66
+ call("return", { value: value === undefined ? null : value });
67
+ } catch (error) {
68
+ call("throw", { message: "The value the code returned cannot be sent: " + error });
69
+ }
70
+ },
71
+ failed,
72
+ );
73
+ };
74
+ })();
75
+ JS
76
+ FORKED = "this process was forked after the sandbox had run code in its parent, and " \
77
+ "wasmtime does not survive a fork. Run code only in the forked processes, or " \
78
+ "build the sandbox in each of them."
79
+ MAX_PRINTED_BYTES = 100_000
80
+ # Below what wasmtime allows a call stack, so deep recursion is an error
81
+ # the code can catch and not a trap.
82
+ MAX_STACK_BYTES = 128 * 1024
83
+ private_constant :WASI, :EXPORTS, :PRELUDE, :FORKED, :MAX_PRINTED_BYTES, :MAX_STACK_BYTES
84
+
85
+ def initialize(wasm:, timeout: 10, total_timeout: 300, memory: 64 * 1024 * 1024,
86
+ sha256: SHA256)
87
+ @wasm = File.binread(wasm)
88
+ unless Digest::SHA256.hexdigest(@wasm) == sha256
89
+ raise ConfigurationError, "#{wasm} is not the QuickJS build this adapter was written for"
90
+ end
91
+
92
+ @limits = { timeout:, total_timeout:, memory: }
93
+ @building = Mutex.new
94
+ end
95
+
96
+ def run(code, host:)
97
+ engine, wasm_module = engine_here
98
+ Run.new(engine, wasm_module, host, **@limits).call(code)
99
+ rescue Wasmtime::Error => e
100
+ raise Stopped, "the code was stopped: #{e.message.lines.first.to_s.strip}"
101
+ end
102
+
103
+ private
104
+
105
+ # wasmtime's engine and its timer do not survive a fork, so a process
106
+ # builds its own at its first run, from the bytes that were checked: the
107
+ # file can be replaced by then.
108
+ def engine_here
109
+ pid, engine, wasm_module = @built || @building.synchronize { @built ||= build }
110
+ raise ConfigurationError, FORKED unless pid == Process.pid
111
+
112
+ [engine, wasm_module]
113
+ end
114
+
115
+ def build
116
+ engine = Wasmtime::Engine.new(epoch_interruption: true)
117
+ engine.start_epoch_interval(50)
118
+ [Process.pid, engine, Wasmtime::Module.new(engine, @wasm)]
119
+ end
120
+
121
+ # One run in one new instance.
122
+ class Run
123
+ def initialize(engine, wasm_module, host, timeout:, total_timeout:, memory:)
124
+ @host = host
125
+ @timeout = timeout
126
+ @total_timeout = total_timeout
127
+ @memory = memory
128
+ @deadline = now + timeout
129
+ @ends = now + total_timeout
130
+ @output = []
131
+ @printed = 0
132
+ @dropped = 0
133
+ @store = Wasmtime::Store.new(engine, nil,
134
+ limits: { memory_size: memory + (16 * 1024 * 1024) })
135
+ @store.set_epoch_deadline((timeout * 20) + 4)
136
+ instance = linker(engine).instantiate(@store, wasm_module)
137
+ @call = EXPORTS.to_h { |name| [name.to_sym, instance.export(name).to_func] }
138
+ @bytes = instance.export("memory").to_memory
139
+ end
140
+
141
+ def call(code)
142
+ start
143
+ evaluate(PRELUDE, "prelude.js")
144
+ evaluate("__run(#{JSON.generate(code)})", "code.js")
145
+ run_jobs
146
+ raise Stopped, unfinished unless @returned || @thrown
147
+
148
+ Outcome.new(value: @value, output: printed, error: @thrown)
149
+ end
150
+
151
+ private
152
+
153
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
154
+
155
+ # A job that throws outside a promise, as a callback of queueMicrotask
156
+ # does, is the code's error while the code has not returned. After
157
+ # that it is ignored, as a promise that nothing handles is.
158
+ def run_jobs
159
+ until @call[:qjs_is_job_pending].call.zero?
160
+ next unless @call[:qjs_execute_pending_job].call.negative?
161
+ raise Stopped, unfinished if now > @deadline
162
+
163
+ error = read(@call[:qjs_get_exception].call)
164
+ @thrown ||= error unless @returned
165
+ end
166
+ end
167
+
168
+ def unfinished
169
+ now > @deadline ? "it ran for #{@timeout} seconds" : "it ended without returning"
170
+ end
171
+
172
+ def start
173
+ @call[:_initialize].call
174
+ raise Error, "QuickJS did not start" unless @call[:qjs_init].call.zero?
175
+
176
+ @call[:qjs_set_memory_limit].call(@memory)
177
+ @call[:qjs_set_max_stack_size].call(MAX_STACK_BYTES)
178
+ @call[:qjs_set_interrupt_handler].call(1)
179
+ name, length = write("__host")
180
+ function = @call[:qjs_new_host_function].call(name, length, 0)
181
+ @call[:qjs_set_prop_string].call(@call[:qjs_get_global].call, name, function)
182
+ @call[:wasm_free].call(name)
183
+ end
184
+
185
+ def linker(engine)
186
+ linker = Wasmtime::Linker.new(engine)
187
+ system_imports(linker)
188
+ refused_imports(linker)
189
+ linker.func_new("env", "host_interrupt", [], [:i32]) do |_caller|
190
+ Thread.pass
191
+ now > @deadline ? 1 : 0
192
+ end
193
+ linker.func_new("env", "host_promise_rejection", %i[i32 i32 i32], []) do |_caller, *held|
194
+ held.first(2).each { |value| @call[:qjs_free_value].call(value) }
195
+ nil
196
+ end
197
+ linker.func_new("env", "host_call", %i[i32 i32 i32 i32 i32], [:i32]) do |_caller, *values|
198
+ count, pointer = values.last(2)
199
+ request = count.positive? ? read(@bytes.read(pointer, 4).unpack1("V")) : "{}"
200
+ string(JSON.generate(answer(request)))
201
+ end
202
+ linker
203
+ end
204
+
205
+ def system_imports(linker)
206
+ linker.func_new(WASI, "clock_time_get", %i[i32 i64 i32], [:i32]) do |caller, id, *values|
207
+ clock = id.zero? ? Process::CLOCK_REALTIME : Process::CLOCK_MONOTONIC
208
+ time = Process.clock_gettime(clock, :nanosecond)
209
+ memory_of(caller).write(values.last, [time].pack("Q<"))
210
+ 0
211
+ end
212
+ linker.func_new(WASI, "random_get", %i[i32 i32], [:i32]) do |caller, pointer, length|
213
+ memory_of(caller).write(pointer, SecureRandom.random_bytes(length))
214
+ 0
215
+ end
216
+ linker.func_new(WASI, "fd_write", %i[i32 i32 i32 i32], [:i32]) do |caller, *values|
217
+ _fd, vectors, count, written = values
218
+ memory = memory_of(caller)
219
+ lengths = (0...count).map { |index| memory.read(vectors + (index * 8) + 4, 4) }
220
+ total = lengths.sum { |length| length.unpack1("V") }
221
+ memory.write(written, [total].pack("V"))
222
+ 0
223
+ end
224
+ end
225
+
226
+ def refused_imports(linker)
227
+ linker.func_new(WASI, "fd_close", [:i32], [:i32]) { |_caller, _fd| 52 }
228
+ linker.func_new(WASI, "fd_fdstat_get", %i[i32 i32], [:i32]) { |_caller, *| 8 }
229
+ linker.func_new(WASI, "fd_seek", %i[i32 i64 i32 i32], [:i32]) { |_caller, *| 52 }
230
+ linker.func_new("env", "host_get_timezone_offset", %i[i32 i32], [:i32]) { |_caller, *| 0 }
231
+ linker.func_new("env", "host_module_normalize", %i[i32 i32], [:i32]) { |_caller, *| 0 }
232
+ linker.func_new("env", "host_module_load", %i[i32 i32], [:i32]) { |_caller, *| 0 }
233
+ end
234
+
235
+ def memory_of(caller) = caller.export("memory").to_memory
236
+
237
+ def answer(text)
238
+ request = JSON.parse(text)
239
+ operation = request.delete("op")
240
+ case operation
241
+ when "print" then keep(request["text"].to_s)
242
+ when "return"
243
+ @returned = true
244
+ @value = request["value"]
245
+ when "throw" then @thrown = own_frames(request["message"].to_s)
246
+ else return { "value" => asked(operation, request) }
247
+ end
248
+ { "value" => nil }
249
+ rescue JSON::ParserError => e
250
+ { "error" => "the call could not be read: #{e.message}" }
251
+ rescue Error => e
252
+ { "error" => e.message }
253
+ end
254
+
255
+ # The code is the body of a function whose source begins two lines
256
+ # above it, and the frames of the adapter name nothing the code wrote.
257
+ def own_frames(trace)
258
+ lines = trace.lines
259
+ lines.each_with_index.filter_map do |line, index|
260
+ next line unless line.match?(/\A\s+at /)
261
+ next if line.match?(/\((prelude|code)\.js:|AsyncFunction \(native\)/)
262
+
263
+ parsed = lines[index + 1].to_s.include?("Function (native)")
264
+ next line unless parsed || line.include?("(<input>:")
265
+
266
+ line.sub(/<input>:(\d+)/) { "<input>:#{Regexp.last_match(1).to_i - 2}" }
267
+ end.join.rstrip
268
+ end
269
+
270
+ def asked(operation, request)
271
+ if now > @ends
272
+ raise Error, "the run passed its limit of #{@total_timeout} seconds, so no more " \
273
+ "calls are answered"
274
+ end
275
+
276
+ unclocked { @host.call(operation, request) }
277
+ end
278
+
279
+ def keep(text)
280
+ if @dropped.zero? && @printed + text.bytesize <= MAX_PRINTED_BYTES
281
+ @output << text
282
+ @printed += text.bytesize
283
+ else
284
+ @dropped += text.bytesize
285
+ end
286
+ end
287
+
288
+ def printed
289
+ return @output if @dropped.zero?
290
+
291
+ [*@output, "[#{@dropped} more bytes were printed and not kept]"]
292
+ end
293
+
294
+ # The limit is on the code's own computing: the time the host takes
295
+ # to answer is given back.
296
+ def unclocked
297
+ started = now
298
+ yield
299
+ ensure
300
+ @deadline += now - started
301
+ @store.set_epoch_deadline(([@deadline - now, 0].max * 20).ceil + 4)
302
+ end
303
+
304
+ def evaluate(source, filename)
305
+ code, length = write(source)
306
+ file, = write(filename)
307
+ value = @call[:qjs_eval].call(code, length, file, 0)
308
+ @call[:wasm_free].call(code)
309
+ @call[:wasm_free].call(file)
310
+ return @call[:qjs_free_value].call(value) if @call[:qjs_is_exception].call(value).zero?
311
+
312
+ raise Stopped, unfinished if now > @deadline
313
+
314
+ raise Error, "#{filename}: #{read(@call[:qjs_get_exception].call)}"
315
+ end
316
+
317
+ def write(text)
318
+ bytes = text.b
319
+ pointer = @call[:wasm_malloc].call(bytes.bytesize + 1)
320
+ raise Stopped, "the code ran out of memory" if pointer.zero?
321
+
322
+ @bytes.write(pointer, "#{bytes}\0".b)
323
+ [pointer, bytes.bytesize]
324
+ end
325
+
326
+ def string(text)
327
+ pointer, length = write(text)
328
+ @call[:qjs_new_string].call(pointer, length).tap { @call[:wasm_free].call(pointer) }
329
+ end
330
+
331
+ def read(value)
332
+ slot = @call[:wasm_malloc].call(4)
333
+ pointer = @call[:qjs_get_string_len].call(value, slot)
334
+ length = @bytes.read(slot, 4).unpack1("V")
335
+ @call[:wasm_free].call(slot)
336
+ return "" if pointer.zero?
337
+
338
+ @bytes.read(pointer, length).force_encoding(Encoding::UTF_8)
339
+ .tap { @call[:qjs_free_cstring].call(pointer) }
340
+ end
341
+ end
342
+ private_constant :Run
343
+ end
344
+ end
345
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ # Where code the model wrote runs: any object that answers
5
+ # run(code, host:) with an Outcome. It must give the code no way out but
6
+ # host, and stop it at a deadline and at a memory limit. A Mistri::Error
7
+ # from host is the code's to catch. Any other error ends the run.
8
+ module Sandbox
9
+ Outcome = Data.define(:value, :output, :error) do
10
+ def initialize(value: nil, output: [], error: nil)
11
+ super
12
+ end
13
+ end
14
+
15
+ # The code was stopped at its deadline or at its memory limit.
16
+ class Stopped < Error; end
17
+ end
18
+ end
data/lib/mistri/schema.rb CHANGED
@@ -362,8 +362,14 @@ module Mistri
362
362
  not if then else contains propertyNames unevaluatedProperties
363
363
  unevaluatedItems contentSchema
364
364
  ].freeze
365
+ DRAFT7 = %w[
366
+ http://json-schema.org/draft-07/schema# http://json-schema.org/draft-07/schema
367
+ ].freeze
368
+ # The keywords local validation applies to a value.
369
+ APPLIED = %w[type enum required properties additionalProperties items prefixItems].freeze
365
370
 
366
371
  def call(schema)
372
+ @draft7 = schema.is_a?(Hash) && DRAFT7.include?(schema["$schema"])
367
373
  walk_schema(schema, "$")
368
374
  schema
369
375
  end
@@ -375,6 +381,7 @@ module Mistri
375
381
 
376
382
  configuration!(path, "must be a schema object or boolean") unless schema.is_a?(Hash)
377
383
  validate_dialect(schema, path)
384
+ validate_draft7_differences(schema, path) if @draft7
378
385
  validate_core_keywords(schema, path)
379
386
  validate_annotation_keywords(schema, path)
380
387
  validate_assertion_shapes(schema, path)
@@ -395,9 +402,26 @@ module Mistri
395
402
 
396
403
  def validate_dialect(spec, path)
397
404
  return unless spec.key?("$schema")
398
- return if spec["$schema"] == DIALECT
405
+ return if spec["$schema"] == DIALECT || (@draft7 && DRAFT7.include?(spec["$schema"]))
406
+
407
+ configuration!("#{path}.$schema", "must declare JSON Schema 2020-12 or draft-07")
408
+ end
409
+
410
+ # Draft-07 reads the same as 2020-12 for what local validation applies,
411
+ # apart from these: it ignores every keyword beside a $ref and has no
412
+ # prefixItems, and 2020-12 applies both. An array for items is refused
413
+ # in either.
414
+ def validate_draft7_differences(spec, path)
415
+ if spec.key?("prefixItems")
416
+ configuration!("#{path}.prefixItems", "is not a draft-07 keyword")
417
+ end
418
+ return unless spec.key?("$ref")
419
+
420
+ beside = APPLIED.find { |keyword| spec.key?(keyword) }
421
+ return unless beside
399
422
 
400
- configuration!("#{path}.$schema", "must declare JSON Schema 2020-12")
423
+ configuration!("#{path}.#{beside}",
424
+ "is ignored beside $ref in draft-07 and applied in 2020-12")
401
425
  end
402
426
 
403
427
  def validate_core_keywords(spec, path)
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Mistri
6
+ # The agent's own folder in a workspace the host builds and scopes, where
7
+ # the whole of a tool result that is too large to show is saved.
8
+ class Scratchpad
9
+ ROOT = "scratchpad/"
10
+ RESULTS = "scratchpad/tool-results/"
11
+ MAX_LISTING_BYTES = 4_000
12
+ NOTE = "You have a scratchpad: documents under scratchpad/ for your own work. A " \
13
+ "tool result that is too large to show is saved whole under " \
14
+ "scratchpad/tool-results/, and only its start is shown to you. Read such a " \
15
+ "document in parts with read_file, or search it with grep, instead of calling " \
16
+ "the tool again. You may keep notes of your own under scratchpad/."
17
+ SHARED = "Other agents share this scratchpad. Write what you find under %<folder>s as " \
18
+ "you go, in documents with plain names, and name them in your report: the " \
19
+ "agent that started you reads them there."
20
+ private_constant :MAX_LISTING_BYTES, :NOTE, :SHARED
21
+
22
+ attr_reader :workspace
23
+
24
+ def initialize(workspace, worker_folder: nil)
25
+ @workspace = workspace
26
+ @worker_folder = worker_folder
27
+ @atomic = Tools.atomic_workspace?(workspace)
28
+ end
29
+
30
+ def for_worker(name)
31
+ part = name.to_s.downcase.gsub(/[^a-z0-9]+/, "-").delete_prefix("-").delete_suffix("-")
32
+ self.class.new(@workspace, worker_folder: "#{ROOT}agents/#{part}/")
33
+ end
34
+
35
+ # The name ends in random characters, so agents that share a scratchpad
36
+ # with no conditional write never pick one name.
37
+ def save_result(text, tool_name)
38
+ path = "#{RESULTS}#{named(tool_name)}.#{json?(text) ? "json" : "txt"}"
39
+ create(path, text) || raise(Error, "#{path} is taken")
40
+ end
41
+
42
+ # Bytes a tool was handed that are no text, kept whole beside the results.
43
+ # extension starts with its dot. A workspace that holds only text raises.
44
+ def save_binary(bytes, tool_name, extension = ".bin")
45
+ path = "#{RESULTS}#{named(tool_name)}#{extension}"
46
+ create(path, bytes.b) || raise(Error, "#{path} is taken")
47
+ end
48
+
49
+ # After a compaction the earlier note is gone from the conversation, so the
50
+ # note also lists what the scratchpad holds.
51
+ def note
52
+ text = @worker_folder ? "#{NOTE} #{format(SHARED, folder: @worker_folder)}" : NOTE
53
+ held = listing
54
+ held.empty? ? text : "#{text}\n\nIt holds:\n#{held}"
55
+ end
56
+
57
+ private
58
+
59
+ def named(tool_name)
60
+ "#{Time.now.utc.strftime("%Y%m%dT%H%M%S")}-" \
61
+ "#{tool_name.to_s.gsub(/[^A-Za-z0-9_-]/, "_")}-#{SecureRandom.hex(4)}"
62
+ end
63
+
64
+ def create(path, text)
65
+ return create_in_two_steps(path, text) unless @atomic
66
+
67
+ @workspace.compare_and_write(path, text, expected_revision: nil)
68
+ path
69
+ rescue WorkspaceConflictError
70
+ nil
71
+ rescue ConfigurationError
72
+ create_in_two_steps(path, text)
73
+ end
74
+
75
+ def create_in_two_steps(path, text)
76
+ return if @workspace.read(path)
77
+
78
+ @workspace.write(path, text)
79
+ path
80
+ end
81
+
82
+ # Judged by its two ends, because parsing a large result to name its
83
+ # document costs more than saving it.
84
+ def json?(text)
85
+ closing = { "{" => "}", "[" => "]" }[text[0]]
86
+ return false unless closing
87
+
88
+ (text.byteslice(-64..) || text).b.rstrip.end_with?(closing)
89
+ end
90
+
91
+ def listing
92
+ lines = if @workspace.respond_to?(:sizes)
93
+ @workspace.sizes(ROOT).map { |path, bytes| "#{path} (#{bytes} bytes)" }
94
+ else
95
+ @workspace.list(ROOT)
96
+ end
97
+ shown = []
98
+ lines.each do |line|
99
+ break if shown.sum(&:bytesize) + line.bytesize > MAX_LISTING_BYTES
100
+
101
+ shown << line
102
+ end
103
+ more = lines.length - shown.length
104
+ more.positive? ? [*shown, "[#{more} more. Use list_files.]"].join("\n") : shown.join("\n")
105
+ end
106
+ end
107
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ class Session
5
+ # A session's entries as read so far. The log only grows and a committed
6
+ # entry never changes, so a read asks the store for what came after the
7
+ # entries already held. That holds only while the store says its reads are
8
+ # settled. A store that does not say so, or says no, is read fresh and
9
+ # nothing is held. The entries are frozen: every reader of one Session
10
+ # shares them, from any thread.
11
+ #
12
+ # A checkpointed log holds only its window. When the newest compaction is
13
+ # a checkpoint, that is the entries from its kept_from on; otherwise it is
14
+ # the whole log. A store that answers size is read back from the end to
15
+ # find it; any other store is read whole and cut down here.
16
+ class Log
17
+ # The held entries and the position in the log of the first of them.
18
+ Window = Data.define(:entries, :offset) do
19
+ def position(index) = offset + index
20
+ end
21
+
22
+ CHUNK = 64
23
+ private_constant :CHUNK
24
+
25
+ def self.owned(value)
26
+ case value
27
+ when Hash then value.to_h { |key, nested| [owned(key), owned(nested)] }
28
+ when Array then value.map { |nested| owned(nested) }
29
+ when String then value.dup
30
+ else value
31
+ end
32
+ end
33
+
34
+ # A compaction that carries what the loop needs from before it, and
35
+ # starts at or before its own position.
36
+ def self.checkpoint?(entry, position)
37
+ entry["type"] == "compaction" && entry["carried"].is_a?(Hash) &&
38
+ entry["kept_from"].is_a?(Integer) && entry["kept_from"].between?(0, position)
39
+ end
40
+
41
+ attr_reader :id
42
+
43
+ # A String id can be changed in place by its caller, so the log keeps its own.
44
+ def initialize(store, id, checkpointed: false)
45
+ @store = store
46
+ @id = id.is_a?(String) ? id.dup.freeze : id
47
+ @checkpointed = checkpointed
48
+ @window = nil
49
+ @mutex = Mutex.new
50
+ end
51
+
52
+ def entries = window.entries
53
+
54
+ def held? = @mutex.synchronize { !@window.nil? }
55
+
56
+ def window
57
+ return read unless settled?
58
+
59
+ @mutex.synchronize { @window = @window ? extended(@window) : read }
60
+ end
61
+
62
+ private
63
+
64
+ def settled? = @store.respond_to?(:settled?) && @store.settled?
65
+
66
+ def read
67
+ return scanned if @checkpointed && @store.respond_to?(:size)
68
+
69
+ entries = frozen(@store.load(@id)).freeze
70
+ rebased(Window.new(entries, 0), entries)
71
+ end
72
+
73
+ def extended(window)
74
+ added = frozen(@store.load(@id, from: window.position(window.entries.length)))
75
+ return window if added.empty?
76
+
77
+ rebased(Window.new((window.entries + added).freeze, window.offset), added)
78
+ end
79
+
80
+ # The newest compaction among the added entries decides where the
81
+ # window starts. One that starts before what is held is read again.
82
+ def rebased(window, added)
83
+ return window unless @checkpointed
84
+
85
+ start = start_in(added, window.position(window.entries.length - added.length))
86
+ return window if start.nil? || start == window.offset
87
+ return read if start < window.offset
88
+
89
+ Window.new(window.entries.drop(start - window.offset).freeze, start)
90
+ end
91
+
92
+ # Reads back from the end in growing chunks until one holds a
93
+ # compaction, then exactly from where that compaction says to start.
94
+ def scanned
95
+ low = @store.size(@id)
96
+ entries = []
97
+ chunk = CHUNK
98
+ until low.zero?
99
+ from = [low - chunk, 0].max
100
+ page = @store.load(@id, from:, to: low)
101
+ start = start_in(page, from)
102
+ entries = (start ? from_start(page, from, start) : page) + entries
103
+ low = start || from
104
+ break if start
105
+
106
+ chunk *= 2
107
+ end
108
+ Window.new(frozen(entries).freeze, low)
109
+ end
110
+
111
+ # Where the window starts when these entries hold a compaction: its
112
+ # kept_from when it is a checkpoint, the start of the log when not.
113
+ def start_in(entries, offset)
114
+ index = entries.rindex { |entry| entry["type"] == "compaction" }
115
+ return nil unless index
116
+
117
+ Log.checkpoint?(entries[index], offset + index) ? entries[index]["kept_from"] : 0
118
+ end
119
+
120
+ def from_start(page, from, start)
121
+ return page.drop(start - from) if start >= from
122
+
123
+ @store.load(@id, from: start, to: from) + page
124
+ end
125
+
126
+ def frozen(entries) = entries.each { |entry| deep_freeze(entry) }
127
+
128
+ def deep_freeze(value)
129
+ case value
130
+ when Hash then value.each_value { |nested| deep_freeze(nested) }
131
+ when Array then value.each { |nested| deep_freeze(nested) }
132
+ end
133
+ value.freeze
134
+ end
135
+ end
136
+ end
137
+ end