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
@@ -0,0 +1,212 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ module Tools
5
+ MAX_PATTERN_CHARS = 500
6
+ MAX_SEARCHED_BYTES = 5_000_000
7
+ MAX_SEARCH_SECONDS = 5
8
+ MAX_HEAD_LIMIT = 200
9
+ MATCH_SIDE_CHARS = 150
10
+
11
+ module_function
12
+
13
+ def grep(workspace, seconds: MAX_SEARCH_SECONDS)
14
+ Tool.define("grep",
15
+ "Search documents with a regular expression. Returns each match with its " \
16
+ "line number, and with its path when a folder is searched, or a count. On " \
17
+ "a very long line, each match comes with the characters around it and its " \
18
+ "character offset in the document, which read_file takes with unit " \
19
+ "\"characters\".",
20
+ save_result: false, parallel: true,
21
+ schema: lambda {
22
+ string :pattern, "Regular expression", required: true
23
+ string :path, "A document, or a folder to search every document under. " \
24
+ "Without it, every document"
25
+ string :output_mode, "content for the matches (the default), count for " \
26
+ "how many there are", enum: %w[content count]
27
+ integer :context, "Lines to show around each match (default 0)"
28
+ integer :head_limit, "Matches to show at most (default 50, " \
29
+ "#{MAX_HEAD_LIMIT} at most)"
30
+ }) do |args, context|
31
+ Search.new(workspace, args, seconds:, bytes: window_bytes(context)).call
32
+ end
33
+ end
34
+
35
+ # One grep call: the documents under a path, searched line by line.
36
+ class Search
37
+ Line = Data.define(:path, :index, :text, :offset)
38
+ private_constant :Line
39
+
40
+ def initialize(workspace, args, seconds:, bytes:)
41
+ @workspace = workspace
42
+ @seconds = seconds
43
+ @bytes = bytes
44
+ @path = args["path"]
45
+ @pattern = args["pattern"].to_s
46
+ @count_only = args["output_mode"] == "count"
47
+ @context = args["context"].to_i.clamp(0, 10)
48
+ @limit = (args["head_limit"] || 50).to_i.clamp(1, MAX_HEAD_LIMIT)
49
+ @blocks = []
50
+ @size = 0
51
+ @shown = 0
52
+ @matches = 0
53
+ @lines = 0
54
+ @searched = 0
55
+ @unsearched = 0
56
+ @unread = 0
57
+ end
58
+
59
+ def call
60
+ if @pattern.length > MAX_PATTERN_CHARS
61
+ return failure("The pattern is longer than #{MAX_PATTERN_CHARS} characters.")
62
+ end
63
+
64
+ unusable = @path && Tools.unusable_path(@path, prefix: true)
65
+ return unusable if unusable
66
+
67
+ regexp = Regexp.new(@pattern, timeout: 1.0)
68
+ paths = documents
69
+ if paths.empty?
70
+ return failure("No document at or under #{@path.inspect}. Use list_files to see paths.")
71
+ end
72
+
73
+ @named = paths == [@path]
74
+ @deadline = clock + @seconds
75
+ paths.each_with_index do |path, index|
76
+ search(path, regexp)
77
+ @unsearched = paths.length - index - 1
78
+ break if @searched > MAX_SEARCHED_BYTES || @late
79
+ end
80
+ report
81
+ rescue RegexpError => e
82
+ failure("The pattern could not be used: #{e.message}")
83
+ end
84
+
85
+ private
86
+
87
+ def failure(text) = ToolResult.new(content: text, error: true)
88
+
89
+ def documents
90
+ paths = @workspace.list(@path)
91
+ return paths unless @path
92
+
93
+ folder = "#{@path.delete_suffix("/")}/"
94
+ paths.select { |path| path == @path || path.start_with?(folder) }
95
+ end
96
+
97
+ def search(path, regexp)
98
+ content = @workspace.read(path).to_s
99
+ return @unread += 1 unless content.valid_encoding?
100
+
101
+ lines = content.lines
102
+ offset = 0
103
+ lines.each_with_index do |text, index|
104
+ break @late = true if clock > @deadline
105
+
106
+ count, found = matches_on(text, regexp)
107
+ if count.positive?
108
+ @lines += 1
109
+ @matches += count
110
+ show(lines, Line.new(path:, index:, text:, offset:), count, found) unless @count_only
111
+ end
112
+ offset += text.length
113
+ end
114
+ @searched += content.bytesize
115
+ end
116
+
117
+ # Only the matches that can still be shown are kept, so a pattern that
118
+ # matches at every character of a large line holds no more than those.
119
+ def matches_on(line, regexp)
120
+ count = 0
121
+ found = []
122
+ keep = @count_only || line.length <= LONG_LINE_CHARS ? 0 : @limit - @shown
123
+ line.scan(regexp) do
124
+ count += 1
125
+ found << Regexp.last_match if found.length < keep
126
+ break @late = true if clock > @deadline
127
+ end
128
+ [count, found]
129
+ end
130
+
131
+ def show(lines, line, count, found)
132
+ if line.text.length > LONG_LINE_CHARS
133
+ found.each { |match| add(around(line, match), 1) }
134
+ elsif @shown < @limit
135
+ add(with_context(line.path, lines, line.index), count)
136
+ end
137
+ end
138
+
139
+ def add(block, matches)
140
+ @full ||= @blocks.any? && @size + block.bytesize > @bytes
141
+ return if @full
142
+
143
+ @blocks << block
144
+ @size += block.bytesize + 4
145
+ @shown += matches
146
+ end
147
+
148
+ def with_context(path, lines, index)
149
+ from = [index - @context, 0].max
150
+ to = [index + @context, lines.length - 1].min
151
+ (from..to).map do |n|
152
+ "#{place(path, n + 1)}: #{lines[n].chomp[0, LONG_LINE_CHARS]}"
153
+ end.join("\n")
154
+ end
155
+
156
+ def around(line, match)
157
+ text = line.text
158
+ from = [match.begin(0) - MATCH_SIDE_CHARS, 0].max
159
+ to = [match.end(0) + MATCH_SIDE_CHARS, text.length].min
160
+ "#{place(line.path, line.index + 1)}: [character #{line.offset + match.begin(0)}] " \
161
+ "#{"..." if from.positive?}#{text[from...to].chomp}#{"..." if to < text.length}"
162
+ end
163
+
164
+ # The path of the one document searched is the argument, so no line repeats it.
165
+ def place(path, number) = @named ? number.to_s : "#{path}:#{number}"
166
+
167
+ def report
168
+ return "#{@matches} matches in #{@lines} lines#{left_out}" if @count_only
169
+ return "No matches.#{left_out}" if @matches.zero?
170
+
171
+ found = @blocks.join("\n--\n")
172
+ text = Tools.fitting(found, @bytes)
173
+ text = "#{text}\n[cut at #{@bytes} bytes]" if text.bytesize < found.bytesize
174
+ "#{text}#{more}#{left_out}"
175
+ end
176
+
177
+ def more
178
+ return unless @matches > @shown
179
+
180
+ advice = ["Narrow the pattern", wider].compact.join(" or ")
181
+ "\n[#{@matches} matches in all, #{@shown} shown. #{advice}.]"
182
+ end
183
+
184
+ def wider
185
+ return "raise head_limit" if !@full && @limit < MAX_HEAD_LIMIT
186
+
187
+ "pass a path" unless @named
188
+ end
189
+
190
+ def left_out
191
+ return stopped unless @unread.positive?
192
+
193
+ "\n[Documents that are not text were not searched: #{@unread}.]#{stopped}"
194
+ end
195
+
196
+ # The timeout of the pattern is for one match, so the whole search has
197
+ # a deadline of its own.
198
+ def stopped
199
+ if @late
200
+ "\n[The search stopped after #{@seconds} seconds. Pass a path or a simpler pattern " \
201
+ "to search the rest.]"
202
+ elsif @unsearched.positive?
203
+ "\n[The search stopped after #{MAX_SEARCHED_BYTES} bytes. Pass a path to search the " \
204
+ "rest.]"
205
+ end
206
+ end
207
+
208
+ def clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
209
+ end
210
+ private_constant :Search
211
+ end
212
+ end
@@ -2,14 +2,47 @@
2
2
 
3
3
  module Mistri
4
4
  module Tools
5
+ MAX_LISTED = 200
6
+
5
7
  module_function
6
8
 
7
9
  def list_files(workspace)
8
- Tool.define("list_files",
9
- "List document paths in the workspace, optionally under a prefix.",
10
- schema: -> { string :prefix, "Only paths starting with this" }) do |args|
11
- paths = workspace.list(args["prefix"])
12
- paths.empty? ? "No documents found." : paths.join("\n")
10
+ tool = Tool.define("list_files",
11
+ "List documents with their sizes, optionally under a prefix.",
12
+ save_result: false, parallel: true,
13
+ schema: lambda {
14
+ string :prefix, "Only paths starting with this"
15
+ }) do |args, context|
16
+ prefix = args["prefix"].to_s
17
+ bytes = window_bytes(context)
18
+ next listing(workspace, nil, bytes) if prefix.empty?
19
+
20
+ unusable_path(prefix, prefix: true) || listing(workspace, prefix, bytes)
21
+ end
22
+ bind(workspace, tool)
23
+ end
24
+
25
+ # Sizes come from a workspace that answers sizes, so a listing never
26
+ # reads a document to measure it.
27
+ def listing(workspace, prefix, bytes = MAX_READ_BYTES)
28
+ lines = if workspace.respond_to?(:sizes)
29
+ workspace.sizes(prefix).map { |path, size| "#{path} (#{size} bytes)" }
30
+ else
31
+ workspace.list(prefix)
32
+ end
33
+ return "No documents found." if lines.empty?
34
+
35
+ shown = listed(lines, bytes)
36
+ more = lines.length - shown.length
37
+ rest = more.positive? ? "\n[#{more} more not shown. Pass a prefix to narrow.]" : ""
38
+ "#{shown.join("\n")}#{rest}"
39
+ end
40
+
41
+ def listed(lines, bytes)
42
+ size = 0
43
+ lines.first(MAX_LISTED).take_while.with_index do |line, index|
44
+ size += line.bytesize + 1
45
+ index.zero? || size <= bytes
13
46
  end
14
47
  end
15
48
  end
@@ -2,37 +2,99 @@
2
2
 
3
3
  module Mistri
4
4
  module Tools
5
- MAX_READ_CHARS = 20_000
5
+ MAX_READ_BYTES = 20_000
6
+ LONG_LINE_CHARS = 2_000
7
+ WINDOW_MARGIN_BYTES = 400
8
+ private_constant :WINDOW_MARGIN_BYTES
6
9
 
7
10
  module_function
8
11
 
9
12
  def read_file(workspace)
10
- Tool.define("read_file",
11
- "Read a document with line numbers. Use offset and limit for a window " \
12
- "into a long document.",
13
- schema: lambda {
14
- string :path, "Document path", required: true
15
- integer :offset, "First line to read (1-based)"
16
- integer :limit, "How many lines to read"
17
- }) do |args|
13
+ tool = Tool.define("read_file",
14
+ "Read a document. Lines come back with their numbers, at most " \
15
+ "#{MAX_READ_BYTES} bytes a call: pass offset and limit to read " \
16
+ "further. A very long line is shown cut, with the offset to read on " \
17
+ "from with unit \"characters\". The first line states the document's " \
18
+ "version, which write_file takes as if_version.",
19
+ save_result: false, parallel: true,
20
+ schema: lambda {
21
+ string :path, "Document path", required: true
22
+ integer :offset, "The line to start at, from 1. With unit characters, " \
23
+ "the character, from 0"
24
+ integer :limit, "How many lines, or characters, to read"
25
+ string :unit, "lines (the default) or characters",
26
+ enum: %w[lines characters]
27
+ }) do |args, context|
18
28
  with_document(workspace, args) do |content|
19
- Tools.numbered_window(content, args["offset"], args["limit"])
29
+ Tools.window(args["path"], content, args["offset"], args["limit"], args["unit"],
30
+ bytes: window_bytes(context))
20
31
  end
21
32
  end
33
+ bind(workspace, tool)
22
34
  end
23
35
 
24
- def numbered_window(content, offset, limit)
25
- lines = content.lines
26
- from = [(offset || 1).to_i, 1].max
27
- to = limit ? [from + limit.to_i - 1, lines.length].min : lines.length
28
- numbered = (from..to).map { |n| "#{n}: #{lines[n - 1]}" }.join
29
- windowed = to < lines.length || from > 1
30
- suffix = windowed ? "\n[showing lines #{from}-#{to} of #{lines.length}]" : ""
31
- return "#{numbered}#{suffix}" if numbered.length <= MAX_READ_CHARS
36
+ # A tool that reads in parts keeps its part under the limit in force, so
37
+ # a cut never takes the line that says how to read on.
38
+ def window_bytes(context)
39
+ limit = context&.result_limit
40
+ return MAX_READ_BYTES unless limit
32
41
 
33
- cut = numbered[0, MAX_READ_CHARS]
34
- cut = cut[0..(cut.rindex("\n") || -1)]
35
- "#{cut}\n[truncated at #{MAX_READ_CHARS} chars; use offset/limit to read more]"
42
+ (limit - WINDOW_MARGIN_BYTES).clamp(WINDOW_MARGIN_BYTES, MAX_READ_BYTES)
43
+ end
44
+
45
+ def window(path, content, offset = nil, limit = nil, unit = nil, bytes: MAX_READ_BYTES)
46
+ title = "#{path}, version #{version(content)}"
47
+ return "#{title}, empty." if content.empty?
48
+ return "#{title}, #{content.bytesize} bytes that are not text." unless content.valid_encoding?
49
+ if unit == "characters"
50
+ return character_window(title, content, offset.to_i, limit.to_i, bytes)
51
+ end
52
+
53
+ line_window(title, content.lines, [offset.to_i, 1].max, limit.to_i, bytes)
54
+ end
55
+
56
+ def line_window(title, lines, from, limit, bytes)
57
+ return "#{title}, #{lines.length} lines. Line #{from} is past the end." if from > lines.length
58
+
59
+ shown = shown_lines(lines, from, limit.positive? ? limit : lines.length, bytes)
60
+ last = from + shown.length - 1
61
+ more = lines.length - last
62
+ rest = more.positive? ? "\n[#{more} more lines. Continue with offset #{last + 1}.]" : ""
63
+ "#{title}, lines #{from}-#{last} of #{lines.length}:\n#{shown.join("\n")}#{rest}"
64
+ end
65
+
66
+ def shown_lines(lines, from, limit, bytes)
67
+ size = 0
68
+ offset = lines.first(from - 1).sum(&:length)
69
+ lines[from - 1, limit].each_with_index.with_object([]) do |(line, index), shown|
70
+ entry = "#{from + index}: #{shown_line(line.chomp, offset, bytes)}"
71
+ break shown if size + entry.bytesize > bytes && shown.any?
72
+
73
+ shown << entry
74
+ size += entry.bytesize + 1
75
+ offset += line.length
76
+ end
77
+ end
78
+
79
+ def shown_line(line, offset, bytes)
80
+ kept = fitting(line[0, LONG_LINE_CHARS], bytes)
81
+ return line if kept.length == line.length
82
+
83
+ "#{kept} [line cut: #{line.length - kept.length} more characters. Read on with unit " \
84
+ "characters and offset #{offset + kept.length}.]"
85
+ end
86
+
87
+ def fitting(text, bytes)
88
+ text.bytesize > bytes ? text.byteslice(0, bytes).scrub("") : text
89
+ end
90
+
91
+ def character_window(title, content, from, limit, bytes)
92
+ from = from.clamp(0, content.length)
93
+ part = fitting(content[from, limit.positive? ? [limit, bytes].min : bytes], bytes)
94
+ last = from + part.length
95
+ more = content.length - last
96
+ rest = more.positive? ? "\n[#{more} more characters. Continue with offset #{last}.]" : ""
97
+ "#{title}, characters #{from}-#{last} of #{content.length}:\n#{part}#{rest}"
36
98
  end
37
99
  end
38
100
  end
@@ -7,7 +7,8 @@ module Mistri
7
7
  def read_memory(memory)
8
8
  Tool.define("read_memory",
9
9
  "Read the durable memory: knowledge kept across sessions. Check it " \
10
- "before starting work that earlier sessions may have learned about.") do |_args|
10
+ "before starting work that earlier sessions may have learned about.",
11
+ parallel: true) do |_args|
11
12
  content = memory.read
12
13
  content.empty? ? "Memory is empty." : content
13
14
  end
@@ -0,0 +1,167 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ module Tools
5
+ MAX_CODE_RESULT_BYTES = 10_000
6
+ MAX_WRITTEN_BYTES = 5_000_000
7
+ RUN_CODE = "Run JavaScript on your documents and tools. The code is the body of an async " \
8
+ "function, so await and return work. Only what the code returns, and what it " \
9
+ "prints with console.log, comes back to you. Use it to search, count, sort, add " \
10
+ "up or join data without reading the data into the conversation. In the code: " \
11
+ "files.read(path) returns the whole text of a document as a string; " \
12
+ "files.write(path, text) writes one; files.list(prefix) returns the paths under " \
13
+ "a folder; files.delete(path) deletes one. files.write replaces a document " \
14
+ "only if your code read it with files.read or wrote it with files.write, in " \
15
+ "this call or an earlier one, and it has not changed since. " \
16
+ "await tools.NAME(arguments) calls " \
17
+ "one of your other tools with the arguments it takes and returns its result as " \
18
+ "a string, or throws an error when the tool fails. Standard JavaScript is there " \
19
+ "(JSON, RegExp, Math, Date, Map, Set). There is no network, no Node.js, no " \
20
+ "require, no timers and no URL class. Return only what you need to " \
21
+ "read%<limit>s. Write a longer output to a document with files.write and return " \
22
+ "its path."
23
+ private_constant :RUN_CODE
24
+
25
+ # What one run of code has done so far: the versions of the documents it
26
+ # and the runs before it read or wrote, the bytes it wrote and the calls
27
+ # it made.
28
+ CodeRun = Struct.new(:seen, :written, :calls)
29
+ private_constant :CodeRun
30
+
31
+ module_function
32
+
33
+ def run_code(sandbox, limited: true, &host)
34
+ limit = ": a result over #{MAX_CODE_RESULT_BYTES} bytes is cut" if limited
35
+ Tool.define("run_code", format(RUN_CODE, limit:),
36
+ result_limit: MAX_CODE_RESULT_BYTES,
37
+ schema: lambda {
38
+ string :code, "JavaScript, the body of an async function", required: true
39
+ }) do |args, context|
40
+ remembering(context.session) do |run|
41
+ asked = ->(operation, payload) { host.call(operation, payload, context, run) }
42
+ code_result(sandbox.run(args["code"].to_s, host: asked))
43
+ end
44
+ rescue Error => e
45
+ ToolResult.new(content: "The code did not finish: #{e.message}", error: true)
46
+ end
47
+ end
48
+
49
+ # A run starts from the versions the session holds and leaves the ones it
50
+ # learned there, also when the code fails or is stopped.
51
+ def remembering(session)
52
+ known = session ? session.code_documents : {}
53
+ run = CodeRun.new(known.dup, 0, 0)
54
+ begin
55
+ yield run
56
+ ensure
57
+ learned = run.seen.reject { |path, version| known[path] == version }
58
+ session&.remember_code_documents(learned.to_a)
59
+ end
60
+ end
61
+
62
+ def code_result(outcome)
63
+ parts = outcome.output.dup
64
+ if outcome.error
65
+ parts << "The code failed:\n#{outcome.error}"
66
+ elsif !outcome.value.nil?
67
+ parts << (outcome.value.is_a?(String) ? outcome.value : JSON.generate(outcome.value))
68
+ end
69
+ text = parts.empty? ? "(the code returned nothing and printed nothing)" : parts.join("\n")
70
+ outcome.error ? ToolResult.new(content: text, error: true) : text
71
+ end
72
+
73
+ def file_from_code(workspace, operation, payload, run)
74
+ path = (operation == "list" ? payload["prefix"] : payload["path"]).to_s
75
+ everything = operation == "list" && path.empty?
76
+ unusable = unusable_path(path, prefix: operation == "list") unless everything
77
+ raise Error, unusable.content if unusable
78
+
79
+ case operation
80
+ when "read" then read_from_code(workspace, path)
81
+ when "list"
82
+ paths = workspace.list(payload["prefix"])
83
+ [paths, paths.join("\n")]
84
+ when "write" then write_from_code(workspace, path, payload["content"].to_s, run)
85
+ when "delete" then delete_from_code(workspace, path)
86
+ end
87
+ end
88
+
89
+ def read_from_code(workspace, path)
90
+ content = workspace.read(path)
91
+ raise Error, "No document at #{path.inspect}" if content.nil?
92
+ raise Error, "#{path} is not text, so code cannot read it" unless content.valid_encoding?
93
+
94
+ [content, "Read #{path} (#{content.bytesize} bytes)"]
95
+ end
96
+
97
+ # A read counts once the code has received the document. A host's hook
98
+ # can refuse a read or rewrite it, so the agent says when that is.
99
+ def read_by_code(run, path, content)
100
+ remember(run.seen, path, content) unless read_only(path)
101
+ end
102
+
103
+ # The newest last, so a table that is full gives up its oldest.
104
+ def remember(seen, path, content)
105
+ seen.delete(path)
106
+ seen[path] = version(content)
107
+ end
108
+
109
+ # The version code last read or wrote stands in for if_version, so a write
110
+ # from code is conditional wherever write_file's is.
111
+ def write_from_code(workspace, path, content, run)
112
+ refuse_read_only(path)
113
+ refuse_over_budget(run, content.bytesize)
114
+ seen = run.seen
115
+ written = if atomic_workspace?(workspace)
116
+ write_atomically(workspace, path, content, seen[path])
117
+ else
118
+ write_legacy(workspace, path, content, seen[path])
119
+ end
120
+ if written.is_a?(StaleWrite)
121
+ raise Error, "#{path} holds a document your code has not read or written, or one " \
122
+ "that changed since. Nothing was written. Read it with files.read and " \
123
+ "build the new text from what it holds now."
124
+ end
125
+
126
+ run.written += written.bytesize
127
+ remember(seen, path, written)
128
+ [nil, "Wrote #{path} (#{written.length} chars), version #{seen[path]}"]
129
+ end
130
+
131
+ # A model's own write is bounded by what it can write in a turn. Code is
132
+ # bounded only by the clock, so one run has a budget.
133
+ def refuse_over_budget(run, bytes)
134
+ return if run.written + bytes <= MAX_WRITTEN_BYTES
135
+
136
+ raise Error, "One run of code writes #{MAX_WRITTEN_BYTES} bytes at most, and this " \
137
+ "write would pass that. Write the rest in another run_code call."
138
+ end
139
+
140
+ # tools.write_file in code writes where files.write does, so it counts
141
+ # against the same budget.
142
+ def within_budget(run, tool, arguments)
143
+ built_in = tool.name == "write_file" && bound_workspace(tool)
144
+ bytes = built_in ? arguments["content"].to_s.bytesize : 0
145
+ refuse_over_budget(run, bytes)
146
+ result = yield
147
+ run.written += bytes unless result.is_a?(ToolResult) && result.error?
148
+ result
149
+ end
150
+
151
+ def delete_from_code(workspace, path)
152
+ refuse_read_only(path)
153
+ raise Error, "No document at #{path.inspect}" if workspace.read(path).nil?
154
+
155
+ workspace.delete(path)
156
+ [nil, "Deleted #{path}"]
157
+ end
158
+
159
+ def refuse_read_only(path)
160
+ refusal = read_only(path)
161
+ raise Error, refusal.content if refusal
162
+ end
163
+
164
+ private_class_method :code_result, :read_from_code, :write_from_code, :delete_from_code,
165
+ :refuse_read_only, :refuse_over_budget, :remember, :remembering
166
+ end
167
+ end
@@ -2,19 +2,76 @@
2
2
 
3
3
  module Mistri
4
4
  module Tools
5
+ StaleWrite = Data.define(:current)
6
+ private_constant :StaleWrite
7
+
5
8
  module_function
6
9
 
7
10
  def write_file(workspace)
8
- Tool.define("write_file",
9
- "Create or fully overwrite a document with the given content.",
10
- eager_input_streaming: true,
11
- schema: lambda {
12
- string :path, "Document path", required: true
13
- string :content, "The full document content", required: true
14
- }) do |args|
15
- workspace.write(args["path"], args["content"])
16
- "Wrote #{args["path"]} (#{args["content"].to_s.length} chars)"
11
+ atomic = atomic_workspace?(workspace)
12
+ tool = Tool.define("write_file",
13
+ "Create a document, or replace one. To replace a document that exists, " \
14
+ "pass if_version, the version read_file showed for it. A write without " \
15
+ "the current version is refused and returns the document as it is now.",
16
+ eager_input_streaming: true, save_result: false,
17
+ schema: lambda {
18
+ string :path, "Document path", required: true
19
+ string :content, "The full document content", required: true
20
+ string :if_version, "The version of the document this replaces"
21
+ }) do |args, context|
22
+ path = args["path"]
23
+ refusal = unusable_path(path) || read_only(path)
24
+ next refusal if refusal
25
+
26
+ content = args["content"].to_s
27
+ written = if atomic
28
+ write_atomically(workspace, path, content, args["if_version"])
29
+ else
30
+ write_legacy(workspace, path, content, args["if_version"])
31
+ end
32
+ if written.is_a?(StaleWrite)
33
+ next stale_write(path, written.current, args["if_version"], window_bytes(context))
34
+ end
35
+
36
+ "Wrote #{path} (#{written.length} chars), version #{version(written)}"
17
37
  end
38
+ bind(workspace, tool)
39
+ end
40
+
41
+ def write_legacy(workspace, path, content, if_version)
42
+ current = workspace.read(path)
43
+ return StaleWrite.new(current) if current && version(current) != if_version
44
+
45
+ workspace.write(path, content)
46
+ content
47
+ end
48
+
49
+ # A workspace that cannot make the check and the write one step where it
50
+ # is called, as the Active Record one inside a transaction the host
51
+ # opened, gets them as two.
52
+ def write_atomically(workspace, path, content, if_version)
53
+ snapshot = workspace.snapshot(path)
54
+ return StaleWrite.new(snapshot.content) if snapshot && version(snapshot.content) != if_version
55
+
56
+ workspace.compare_and_write(path, content, expected_revision: snapshot&.revision).content
57
+ rescue WorkspaceConflictError
58
+ StaleWrite.new(workspace.read(path).to_s)
59
+ rescue ConfigurationError
60
+ write_legacy(workspace, path, content, if_version)
61
+ end
62
+
63
+ def stale_write(path, current, if_version, bytes)
64
+ reason = if if_version
65
+ "#{path} is not at version #{if_version} any more"
66
+ else
67
+ "#{path} holds a document already"
68
+ end
69
+ ToolResult.new(
70
+ content: "write_file refused: #{reason}. Nothing was written. To replace it, pass " \
71
+ "its version as if_version. To change part of it, use edit_file. The " \
72
+ "document now:\n#{window(path, current, bytes: bytes - WINDOW_MARGIN_BYTES)}",
73
+ error: true
74
+ )
18
75
  end
19
76
  end
20
77
  end