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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +321 -2
- data/CONTRIBUTING.md +17 -3
- data/NOTICE +11 -0
- data/README.md +145 -284
- data/UPGRADING.md +810 -0
- data/assets/vendors/README.md +12 -0
- data/assets/vendors/claude-mark.svg +3 -0
- data/assets/vendors/gemini-mark.svg +10 -0
- data/assets/vendors/openai-mark-dark.svg +1 -0
- data/assets/vendors/openai-mark.svg +1 -0
- data/docs/README.md +2 -1
- data/docs/context-and-workspaces.md +84 -13
- data/docs/logging.md +90 -0
- data/docs/mcp.md +762 -21
- data/docs/reliability.md +210 -24
- data/docs/sessions.md +415 -36
- data/docs/sub-agents.md +85 -7
- data/docs/tool-contracts.md +528 -13
- data/examples/approval.rb +7 -7
- data/examples/browser.rb +1 -1
- data/examples/page_editor.rb +2 -2
- data/examples/quickstart.rb +1 -1
- data/lib/generators/mistri/install/templates/migration.rb.tt +4 -2
- data/lib/generators/mistri/mcp/mcp_generator.rb +2 -2
- data/lib/generators/mistri/mcp/templates/model.rb.tt +21 -8
- data/lib/mistri/agent.rb +815 -180
- data/lib/mistri/call_order.rb +137 -0
- data/lib/mistri/child.rb +69 -13
- data/lib/mistri/compaction.rb +200 -35
- data/lib/mistri/compactor/text.rb +91 -0
- data/lib/mistri/compactor.rb +474 -117
- data/lib/mistri/console.rb +44 -11
- data/lib/mistri/content.rb +70 -3
- data/lib/mistri/definition.rb +2 -2
- data/lib/mistri/edit.rb +13 -7
- data/lib/mistri/errors.rb +37 -0
- data/lib/mistri/event.rb +20 -9
- data/lib/mistri/locks/rails_cache.rb +16 -2
- data/lib/mistri/locks.rb +12 -3
- data/lib/mistri/mcp/client.rb +247 -61
- data/lib/mistri/mcp/conversation.rb +161 -0
- data/lib/mistri/mcp/egress.rb +5 -4
- data/lib/mistri/mcp/mirror.rb +90 -0
- data/lib/mistri/mcp/negotiation.rb +222 -0
- data/lib/mistri/mcp/oauth/client_identity.rb +53 -0
- data/lib/mistri/mcp/oauth/tolerance.rb +61 -0
- data/lib/mistri/mcp/oauth.rb +303 -82
- data/lib/mistri/mcp/results.rb +97 -0
- data/lib/mistri/mcp/sdk_client.rb +47 -0
- data/lib/mistri/mcp/wires.rb +325 -52
- data/lib/mistri/mcp.rb +304 -55
- data/lib/mistri/memory.rb +1 -1
- data/lib/mistri/message.rb +45 -8
- data/lib/mistri/models.rb +146 -24
- data/lib/mistri/partial_json.rb +5 -5
- data/lib/mistri/providers/anthropic/assembler.rb +40 -3
- data/lib/mistri/providers/anthropic/serializer.rb +154 -22
- data/lib/mistri/providers/anthropic.rb +77 -12
- data/lib/mistri/providers/fake.rb +4 -1
- data/lib/mistri/providers/gemini/assembler.rb +63 -3
- data/lib/mistri/providers/gemini/serializer.rb +27 -16
- data/lib/mistri/providers/gemini.rb +56 -11
- data/lib/mistri/providers/openai/assembler.rb +36 -5
- data/lib/mistri/providers/openai/serializer.rb +76 -22
- data/lib/mistri/providers/openai.rb +91 -14
- data/lib/mistri/reminder.rb +35 -3
- data/lib/mistri/result.rb +6 -4
- data/lib/mistri/result_limit.rb +164 -0
- data/lib/mistri/sandbox/quickjs.rb +345 -0
- data/lib/mistri/sandbox.rb +18 -0
- data/lib/mistri/schema.rb +26 -2
- data/lib/mistri/scratchpad.rb +107 -0
- data/lib/mistri/session/log.rb +137 -0
- data/lib/mistri/session.rb +405 -75
- data/lib/mistri/sinks/logger.rb +17 -11
- data/lib/mistri/skills.rb +10 -4
- data/lib/mistri/spawner.rb +43 -12
- data/lib/mistri/sse.rb +3 -2
- data/lib/mistri/stores/active_record.rb +30 -6
- data/lib/mistri/stores/jsonl.rb +26 -7
- data/lib/mistri/stores/memory.rb +6 -2
- data/lib/mistri/sub_agent/execution.rb +10 -2
- data/lib/mistri/sub_agent/runtime.rb +11 -1
- data/lib/mistri/sub_agent.rb +13 -4
- data/lib/mistri/tool.rb +71 -7
- data/lib/mistri/tool_arguments.rb +10 -11
- data/lib/mistri/tool_context.rb +15 -3
- data/lib/mistri/tool_executor.rb +49 -26
- data/lib/mistri/tool_result.rb +8 -2
- data/lib/mistri/tool_search/index.rb +193 -0
- data/lib/mistri/tool_search.rb +200 -0
- data/lib/mistri/tools/delete_file.rb +22 -0
- data/lib/mistri/tools/edit_file.rb +24 -14
- data/lib/mistri/tools/find_in_file.rb +1 -0
- data/lib/mistri/tools/grep.rb +212 -0
- data/lib/mistri/tools/list_files.rb +38 -5
- data/lib/mistri/tools/read_file.rb +83 -21
- data/lib/mistri/tools/read_memory.rb +2 -1
- data/lib/mistri/tools/run_code.rb +167 -0
- data/lib/mistri/tools/write_file.rb +66 -9
- data/lib/mistri/tools.rb +72 -1
- data/lib/mistri/transport/streamable_http.rb +140 -0
- data/lib/mistri/transport.rb +53 -63
- data/lib/mistri/usage.rb +33 -4
- data/lib/mistri/version.rb +1 -1
- data/lib/mistri/workspace/active_record.rb +22 -10
- data/lib/mistri/workspace/directory.rb +5 -1
- data/lib/mistri/workspace/memory.rb +4 -0
- data/lib/mistri/workspace/path_space.rb +56 -0
- data/lib/mistri/workspace/single.rb +6 -1
- data/lib/mistri.rb +10 -4
- metadata +29 -2
data/lib/mistri/tools.rb
CHANGED
|
@@ -8,15 +8,29 @@ module Mistri
|
|
|
8
8
|
module Tools
|
|
9
9
|
ATOMIC_WORKSPACE_METHODS = %i[snapshot compare_and_write].freeze
|
|
10
10
|
private_constant :ATOMIC_WORKSPACE_METHODS
|
|
11
|
+
MAX_PATH_BYTES = 512
|
|
11
12
|
ALIASES = { "oldText" => "old_string", "old" => "old_string", "search" => "old_string",
|
|
12
13
|
"newText" => "new_string", "new" => "new_string", "replace" => "new_string",
|
|
13
14
|
"replaceAll" => "replace_all", "file" => "path", "filename" => "path" }.freeze
|
|
14
15
|
|
|
16
|
+
BOUND_WORKSPACES = ObjectSpace::WeakMap.new
|
|
17
|
+
private_constant :BOUND_WORKSPACES
|
|
18
|
+
|
|
15
19
|
module_function
|
|
16
20
|
|
|
21
|
+
# files in code works only through a built-in document tool, on the
|
|
22
|
+
# workspace that tool is bound to.
|
|
23
|
+
def bound_workspace(tool) = BOUND_WORKSPACES[tool]
|
|
24
|
+
|
|
25
|
+
def bind(workspace, tool)
|
|
26
|
+
BOUND_WORKSPACES[tool] = workspace
|
|
27
|
+
tool
|
|
28
|
+
end
|
|
29
|
+
private_class_method :bind
|
|
30
|
+
|
|
17
31
|
def files(workspace)
|
|
18
32
|
[read_file(workspace), write_file(workspace), edit_file(workspace),
|
|
19
|
-
|
|
33
|
+
grep(workspace), list_files(workspace), delete_file(workspace)]
|
|
20
34
|
end
|
|
21
35
|
|
|
22
36
|
def memory(store)
|
|
@@ -24,12 +38,66 @@ module Mistri
|
|
|
24
38
|
end
|
|
25
39
|
|
|
26
40
|
def with_document(workspace, args)
|
|
41
|
+
unusable = unusable_path(args["path"])
|
|
42
|
+
return unusable if unusable
|
|
43
|
+
|
|
27
44
|
content = workspace.read(args["path"])
|
|
28
45
|
return missing_document(args["path"]) if content.nil?
|
|
29
46
|
|
|
30
47
|
yield content
|
|
31
48
|
end
|
|
32
49
|
|
|
50
|
+
# A hash of the content, so a version is the same in any process.
|
|
51
|
+
def version(content)
|
|
52
|
+
Digest::SHA256.hexdigest(content.b)[0, 12]
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Checked before any workspace is asked, so the same rules hold on every
|
|
56
|
+
# backend.
|
|
57
|
+
def unusable_path(path, prefix: false)
|
|
58
|
+
path = path.to_s
|
|
59
|
+
path = path.delete_suffix("/") if prefix
|
|
60
|
+
problem = path_problem(path)
|
|
61
|
+
return unless problem
|
|
62
|
+
|
|
63
|
+
ToolResult.new(
|
|
64
|
+
content: "#{path.inspect} is not a path here: #{problem}. Use a relative path such " \
|
|
65
|
+
"as notes/plan.md.",
|
|
66
|
+
error: true
|
|
67
|
+
)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def path_problem(path)
|
|
71
|
+
return "it is empty" if path.empty?
|
|
72
|
+
return "it is longer than #{MAX_PATH_BYTES} bytes" if path.bytesize > MAX_PATH_BYTES
|
|
73
|
+
return "it is not valid UTF-8" unless path.valid_encoding?
|
|
74
|
+
return "it holds a control character or a backslash" if path.match?(/[\x00-\x1f\x7f\\]/)
|
|
75
|
+
return "it starts with /" if path.start_with?("/")
|
|
76
|
+
|
|
77
|
+
parts = path.split("/", -1)
|
|
78
|
+
"it holds an empty part, . or .." if parts.intersect?(["", ".", ".."])
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# A store may match a path to the folder without case or accents, or by
|
|
82
|
+
# Unicode's folding, so the first two parts are compared as plain letters.
|
|
83
|
+
def read_only(path)
|
|
84
|
+
first, second, = plain_letters(path.to_s).split("/", 3)
|
|
85
|
+
return unless "#{first}/" == Scratchpad::ROOT
|
|
86
|
+
|
|
87
|
+
reason = if second.nil?
|
|
88
|
+
"scratchpad is a folder, so no document can have that path."
|
|
89
|
+
elsif "#{first}/#{second}/" == Scratchpad::RESULTS
|
|
90
|
+
"#{Scratchpad::RESULTS} holds saved tool results and is read-only."
|
|
91
|
+
end
|
|
92
|
+
ToolResult.new(content: "#{reason} Write under scratchpad/ instead.", error: true) if reason
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def plain_letters(path)
|
|
96
|
+
return path.downcase if path.ascii_only?
|
|
97
|
+
|
|
98
|
+
path.unicode_normalize(:nfkd).downcase(:fold).gsub(/[^[:ascii:]]/, "")
|
|
99
|
+
end
|
|
100
|
+
|
|
33
101
|
def missing_document(path)
|
|
34
102
|
ToolResult.new(
|
|
35
103
|
content: "No document at #{path.inspect}. Use list_files to see paths.",
|
|
@@ -82,6 +150,9 @@ require_relative "tools/read_file"
|
|
|
82
150
|
require_relative "tools/write_file"
|
|
83
151
|
require_relative "tools/edit_file"
|
|
84
152
|
require_relative "tools/find_in_file"
|
|
153
|
+
require_relative "tools/grep"
|
|
85
154
|
require_relative "tools/list_files"
|
|
155
|
+
require_relative "tools/delete_file"
|
|
156
|
+
require_relative "tools/run_code"
|
|
86
157
|
require_relative "tools/read_memory"
|
|
87
158
|
require_relative "tools/update_memory"
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Mistri
|
|
4
|
+
class Transport
|
|
5
|
+
# Requests to a Streamable HTTP endpoint, the MCP shape: it answers a POST
|
|
6
|
+
# with a JSON body or with an SSE stream, a GET with a stream, and a
|
|
7
|
+
# DELETE with a status.
|
|
8
|
+
module StreamableHTTP
|
|
9
|
+
# Seconds a stream gets to end once it has given its answer. A stream
|
|
10
|
+
# read to its end keeps its connection. Most end within a few
|
|
11
|
+
# milliseconds, and one that stays open would hold the caller.
|
|
12
|
+
LINGER = 0.1
|
|
13
|
+
private_constant :LINGER
|
|
14
|
+
|
|
15
|
+
# POST for Streamable-HTTP endpoints (the MCP shape) that answer either
|
|
16
|
+
# a JSON body or an SSE stream: yields each JSON record either way and
|
|
17
|
+
# returns the response headers, downcased. The block returns true once
|
|
18
|
+
# it has the answer the request was sent for. A stream is read a moment
|
|
19
|
+
# more then, so that its connection can be kept, and left if it stays
|
|
20
|
+
# open. events: is the decoder a stream is read with. A replayable
|
|
21
|
+
# request retries once when a dead idle socket fails before any response
|
|
22
|
+
# starts.
|
|
23
|
+
def post_either(path, body:, headers: {}, replayable: true, events: nil, &block)
|
|
24
|
+
@mutex.synchronize do
|
|
25
|
+
either(replayable, events, block) { build_request(path, body, headers, streaming: true) }
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# GET for the same endpoints, which answer it with an SSE stream. An MCP
|
|
30
|
+
# client goes back this way to a response whose stream ended early.
|
|
31
|
+
def get_either(path, headers: {}, events: nil, &block)
|
|
32
|
+
@mutex.synchronize do
|
|
33
|
+
either(true, events, block) { bodiless(Net::HTTP::Get, path, headers) }
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# DELETE with no body. Only the status of the response matters.
|
|
38
|
+
def delete(path, headers: {})
|
|
39
|
+
@mutex.synchronize do
|
|
40
|
+
with_retry do
|
|
41
|
+
read_whole do
|
|
42
|
+
connection.request(bodiless(Net::HTTP::Delete, path, headers)) do |response|
|
|
43
|
+
raise_for_status(response)
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
rescue ProviderError
|
|
48
|
+
teardown
|
|
49
|
+
raise
|
|
50
|
+
end
|
|
51
|
+
nil
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
private
|
|
55
|
+
|
|
56
|
+
# The block builds the request, again for a retry. A failure of the
|
|
57
|
+
# connection after the answer does not fail the request.
|
|
58
|
+
def either(replayable, events, block)
|
|
59
|
+
retried = false
|
|
60
|
+
begin
|
|
61
|
+
started = false
|
|
62
|
+
answered = false
|
|
63
|
+
response_headers = nil
|
|
64
|
+
catch(:left) do
|
|
65
|
+
read_whole do
|
|
66
|
+
connection.request(yield) do |response|
|
|
67
|
+
started = true
|
|
68
|
+
raise_for_status(response)
|
|
69
|
+
response_headers = response.to_hash.transform_values(&:first)
|
|
70
|
+
read_either(response, events) { |record| answered = block.call(record) || answered }
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
response_headers
|
|
75
|
+
rescue ResponseTooLargeError, ResponseTooComplexError, ProviderError
|
|
76
|
+
teardown
|
|
77
|
+
raise
|
|
78
|
+
rescue IOError, SocketError, SystemCallError, Timeout::Error, JSON::ParserError,
|
|
79
|
+
Net::HTTPBadResponse, OpenSSL::SSL::SSLError => e
|
|
80
|
+
teardown
|
|
81
|
+
return response_headers if answered
|
|
82
|
+
|
|
83
|
+
unless replayable || Transport.unopened?(e)
|
|
84
|
+
raise AmbiguousDeliveryError, "#{AmbiguousDeliveryError.default_message}: #{e.message}"
|
|
85
|
+
end
|
|
86
|
+
if started || retried || e.is_a?(Timeout::Error)
|
|
87
|
+
raise ProviderError, "connection failed: #{e.message}"
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
retried = true
|
|
91
|
+
retry
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def read_either(response, events, &)
|
|
96
|
+
if response["content-type"].to_s.include?("text/event-stream")
|
|
97
|
+
read_events(response, events || SSE.new(max_record_bytes: @max_record_bytes), &)
|
|
98
|
+
else
|
|
99
|
+
raw = read_json_body(response)
|
|
100
|
+
yield JSON.parse(raw) unless BLANK_BODY.match?(raw)
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Net::HTTP's read timeout starts again with every byte, so a comment a
|
|
105
|
+
# second would hold a request for ever. The wait is for a message, and
|
|
106
|
+
# after the answer for the end of the stream. Whenever bytes arrive, the
|
|
107
|
+
# socket's timeout is set to what is left of that wait.
|
|
108
|
+
def read_events(response, sse, &block)
|
|
109
|
+
heard = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
110
|
+
answered = nil
|
|
111
|
+
response.read_body do |chunk|
|
|
112
|
+
sse.feed(chunk) do |record|
|
|
113
|
+
heard = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
114
|
+
answered ||= heard if block.call(record)
|
|
115
|
+
end
|
|
116
|
+
limit = answered ? LINGER : @read_timeout
|
|
117
|
+
next unless limit
|
|
118
|
+
|
|
119
|
+
left = limit - (Process.clock_gettime(Process::CLOCK_MONOTONIC) - (answered || heard))
|
|
120
|
+
throw :left if answered && !left.positive?
|
|
121
|
+
unless left.positive?
|
|
122
|
+
raise Timeout::Error, "no message from the server in #{@read_timeout} seconds"
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
@connection.read_timeout = left
|
|
126
|
+
end
|
|
127
|
+
sse.finish(&block)
|
|
128
|
+
ensure
|
|
129
|
+
@connection.read_timeout = @read_timeout
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def bodiless(verb, path, headers)
|
|
133
|
+
request = verb.new(URI("#{@origin}#{path}"))
|
|
134
|
+
headers.each { |key, value| request[key] = value }
|
|
135
|
+
request["Accept-Encoding"] = "identity"
|
|
136
|
+
request
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|
data/lib/mistri/transport.rb
CHANGED
|
@@ -4,6 +4,7 @@ require "net/http"
|
|
|
4
4
|
require "openssl"
|
|
5
5
|
require "json"
|
|
6
6
|
require "uri"
|
|
7
|
+
require_relative "transport/streamable_http"
|
|
7
8
|
|
|
8
9
|
module Mistri
|
|
9
10
|
# HTTP for one provider origin, held open across the turns of a run: a
|
|
@@ -27,6 +28,12 @@ module Mistri
|
|
|
27
28
|
CONNECT_ERRORS = [IOError, SocketError, SystemCallError, Timeout::Error,
|
|
28
29
|
Net::HTTPBadResponse, OpenSSL::SSL::SSLError].freeze
|
|
29
30
|
|
|
31
|
+
# Marks an error raised while a connection was being opened, so before
|
|
32
|
+
# any request was written on it. The class of an error does not say
|
|
33
|
+
# that: a socket that was connected can still raise ECONNREFUSED or
|
|
34
|
+
# EHOSTUNREACH.
|
|
35
|
+
module Unopened; end
|
|
36
|
+
|
|
30
37
|
# Net::HTTP reconnects expired keep-alives internally. Resolving inside
|
|
31
38
|
# connect makes every MCP connection cycle cross the egress boundary.
|
|
32
39
|
class ResolvedHTTP < Net::HTTP
|
|
@@ -56,11 +63,19 @@ module Mistri
|
|
|
56
63
|
end
|
|
57
64
|
end
|
|
58
65
|
raise failure || Net::OpenTimeout.new("all approved addresses timed out")
|
|
66
|
+
rescue *CONNECT_ERRORS => e
|
|
67
|
+
raise e.extend(Unopened)
|
|
59
68
|
ensure
|
|
60
69
|
@open_timeout = original_timeout if original_timeout
|
|
61
70
|
end
|
|
62
71
|
end
|
|
63
|
-
private_constant :ResolvedHTTP, :CONNECT_ERRORS, :BLANK_BODY
|
|
72
|
+
private_constant :ResolvedHTTP, :CONNECT_ERRORS, :BLANK_BODY, :Unopened
|
|
73
|
+
|
|
74
|
+
include StreamableHTTP
|
|
75
|
+
|
|
76
|
+
# True for an error that was raised while a connection was being opened,
|
|
77
|
+
# so no request was sent on it.
|
|
78
|
+
def self.unopened?(error) = error.is_a?(Unopened)
|
|
64
79
|
|
|
65
80
|
def initialize(origin:, open_timeout: 15, read_timeout: 300, write_timeout: 60,
|
|
66
81
|
address_resolver: nil, max_record_bytes: DEFAULT_MAX_RECORD_BYTES)
|
|
@@ -85,9 +100,11 @@ module Mistri
|
|
|
85
100
|
@mutex.synchronize do
|
|
86
101
|
with_retry do
|
|
87
102
|
parsed = nil
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
103
|
+
read_whole do
|
|
104
|
+
connection.request(build_request(path, body, headers)) do |response|
|
|
105
|
+
raise_for_status(response)
|
|
106
|
+
parsed = JSON.parse(read_json_body(response))
|
|
107
|
+
end
|
|
91
108
|
end
|
|
92
109
|
parsed
|
|
93
110
|
end
|
|
@@ -98,19 +115,12 @@ module Mistri
|
|
|
98
115
|
end
|
|
99
116
|
|
|
100
117
|
# POST and stream the SSE response, yielding each decoded data record.
|
|
101
|
-
# Returns :aborted when the signal cancelled the stream, else nil.
|
|
102
|
-
|
|
118
|
+
# Returns :aborted when the signal cancelled the stream, else nil. The
|
|
119
|
+
# JSON tokens in a record are counted only for a caller that asks.
|
|
120
|
+
def stream_post(path, body:, headers: {}, signal: nil, count_tokens: false, &block)
|
|
103
121
|
return :aborted if signal&.aborted?
|
|
104
122
|
|
|
105
|
-
@mutex.synchronize { stream_locked(path, body, headers, signal, &block) }
|
|
106
|
-
end
|
|
107
|
-
|
|
108
|
-
# POST for Streamable-HTTP endpoints (the MCP shape) that answer either
|
|
109
|
-
# a JSON body or an SSE stream: yields each JSON record either way and
|
|
110
|
-
# returns the response headers, downcased. A replayable request retries
|
|
111
|
-
# once when a dead idle socket fails before any response starts.
|
|
112
|
-
def post_either(path, body:, headers: {}, replayable: true, &block)
|
|
113
|
-
@mutex.synchronize { post_either_locked(path, body, headers, replayable, &block) }
|
|
123
|
+
@mutex.synchronize { stream_locked(path, body, headers, signal, count_tokens, &block) }
|
|
114
124
|
end
|
|
115
125
|
|
|
116
126
|
def close
|
|
@@ -119,48 +129,7 @@ module Mistri
|
|
|
119
129
|
|
|
120
130
|
private
|
|
121
131
|
|
|
122
|
-
def
|
|
123
|
-
retried = false
|
|
124
|
-
begin
|
|
125
|
-
started = false
|
|
126
|
-
response_headers = nil
|
|
127
|
-
connection.request(build_request(path, body, headers, streaming: true)) do |response|
|
|
128
|
-
started = true
|
|
129
|
-
raise_for_status(response)
|
|
130
|
-
response_headers = response.to_hash.transform_values(&:first)
|
|
131
|
-
read_either(response, &block)
|
|
132
|
-
end
|
|
133
|
-
response_headers
|
|
134
|
-
rescue ResponseTooLargeError, ResponseTooComplexError, ProviderError
|
|
135
|
-
teardown
|
|
136
|
-
raise
|
|
137
|
-
rescue IOError, SocketError, SystemCallError, Timeout::Error, JSON::ParserError,
|
|
138
|
-
Net::HTTPBadResponse, OpenSSL::SSL::SSLError => e
|
|
139
|
-
teardown
|
|
140
|
-
unless replayable
|
|
141
|
-
raise AmbiguousDeliveryError, "#{AmbiguousDeliveryError.default_message}: #{e.message}"
|
|
142
|
-
end
|
|
143
|
-
if started || retried || e.is_a?(Timeout::Error)
|
|
144
|
-
raise ProviderError, "connection failed: #{e.message}"
|
|
145
|
-
end
|
|
146
|
-
|
|
147
|
-
retried = true
|
|
148
|
-
retry
|
|
149
|
-
end
|
|
150
|
-
end
|
|
151
|
-
|
|
152
|
-
def read_either(response, &block)
|
|
153
|
-
if response["content-type"].to_s.include?("text/event-stream")
|
|
154
|
-
sse = SSE.new(max_record_bytes: @max_record_bytes)
|
|
155
|
-
response.read_body { |chunk| sse.feed(chunk, &block) }
|
|
156
|
-
sse.finish(&block)
|
|
157
|
-
else
|
|
158
|
-
raw = read_json_body(response)
|
|
159
|
-
block.call(JSON.parse(raw)) unless BLANK_BODY.match?(raw)
|
|
160
|
-
end
|
|
161
|
-
end
|
|
162
|
-
|
|
163
|
-
def stream_locked(path, body, headers, signal, &block)
|
|
132
|
+
def stream_locked(path, body, headers, signal, count_tokens, &block)
|
|
164
133
|
retried = false
|
|
165
134
|
begin
|
|
166
135
|
started = false
|
|
@@ -171,10 +140,12 @@ module Mistri
|
|
|
171
140
|
# socket.
|
|
172
141
|
closer = signal&.on_abort { quietly_finish(conn) }
|
|
173
142
|
begin
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
143
|
+
read_whole do
|
|
144
|
+
conn.request(build_request(path, body, headers, streaming: true)) do |response|
|
|
145
|
+
started = true
|
|
146
|
+
raise_for_status(response)
|
|
147
|
+
aborted = read_stream(response, signal, count_tokens, &block)
|
|
148
|
+
end
|
|
178
149
|
end
|
|
179
150
|
ensure
|
|
180
151
|
signal&.remove_callback(closer) if closer
|
|
@@ -200,8 +171,20 @@ module Mistri
|
|
|
200
171
|
end
|
|
201
172
|
end
|
|
202
173
|
|
|
203
|
-
|
|
204
|
-
|
|
174
|
+
# A request can be left by an error that is no StandardError, such as the
|
|
175
|
+
# one a Timeout raises. It passes every rescue here and the one Net::HTTP
|
|
176
|
+
# closes its socket in, so the response would stay half read on the kept
|
|
177
|
+
# connection and the next request would take it for its own.
|
|
178
|
+
def read_whole
|
|
179
|
+
whole = false
|
|
180
|
+
yield
|
|
181
|
+
whole = true
|
|
182
|
+
ensure
|
|
183
|
+
teardown unless whole
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def read_stream(response, signal, count_tokens, &block)
|
|
187
|
+
sse = SSE.new(max_record_bytes: @max_record_bytes, count_tokens:)
|
|
205
188
|
aborted = false
|
|
206
189
|
response.read_body do |fragment|
|
|
207
190
|
if signal&.aborted?
|
|
@@ -275,6 +258,8 @@ module Mistri
|
|
|
275
258
|
http.read_timeout = @read_timeout
|
|
276
259
|
http.write_timeout = @write_timeout
|
|
277
260
|
http.keep_alive_timeout = KEEP_ALIVE_SECONDS
|
|
261
|
+
# Net::HTTP sends a GET or a DELETE again by itself after a failure.
|
|
262
|
+
http.max_retries = 0
|
|
278
263
|
http.start
|
|
279
264
|
http
|
|
280
265
|
end
|
|
@@ -312,6 +297,7 @@ module Mistri
|
|
|
312
297
|
body = preview.dup.force_encoding(Encoding::UTF_8).scrub("?")
|
|
313
298
|
options = { status: status, body: body }
|
|
314
299
|
options[:retry_after] = retry_after(response) if klass == RateLimitError
|
|
300
|
+
options[:challenge] = challenge(response) if klass == AuthenticationError
|
|
315
301
|
klass.new(**options)
|
|
316
302
|
end
|
|
317
303
|
|
|
@@ -325,6 +311,10 @@ module Mistri
|
|
|
325
311
|
end
|
|
326
312
|
end
|
|
327
313
|
|
|
314
|
+
def challenge(response)
|
|
315
|
+
response["www-authenticate"]&.scrub("?")&.slice(0, ERROR_PREVIEW_BYTES)
|
|
316
|
+
end
|
|
317
|
+
|
|
328
318
|
def retry_after(response)
|
|
329
319
|
value = response["retry-after"]
|
|
330
320
|
value&.match?(/\A\d+(\.\d+)?\z/) ? value.to_f : nil
|
data/lib/mistri/usage.rb
CHANGED
|
@@ -9,6 +9,11 @@ module Mistri
|
|
|
9
9
|
# writes are separate fields, so a cached token is never double-billed.
|
|
10
10
|
# `reasoning` is the thinking slice of `output`. `cache_write_1h` is the slice
|
|
11
11
|
# of `cache_write` held for an hour, which bills at twice the input rate.
|
|
12
|
+
#
|
|
13
|
+
# A turn that took several requests counts every request, because each one
|
|
14
|
+
# is billed, and every request after the first reads the earlier ones again.
|
|
15
|
+
# `context` is then what sits in the model's context once the turn ends. It
|
|
16
|
+
# stays outside the released Data shape, as Cost#known does.
|
|
12
17
|
class Usage < Data.define(:input, :output, :cache_read, :cache_write,
|
|
13
18
|
:cache_write_1h, :reasoning, :cost)
|
|
14
19
|
# Dollar amounts plus whether every contributing token had known pricing.
|
|
@@ -57,8 +62,9 @@ module Mistri
|
|
|
57
62
|
end
|
|
58
63
|
|
|
59
64
|
def initialize(input: 0, output: 0, cache_read: 0, cache_write: 0,
|
|
60
|
-
cache_write_1h: 0, reasoning: 0, cost: Cost.unknown)
|
|
61
|
-
|
|
65
|
+
cache_write_1h: 0, reasoning: 0, cost: Cost.unknown, context: nil)
|
|
66
|
+
@context = context if context
|
|
67
|
+
super(input:, output:, cache_read:, cache_write:, cache_write_1h:, reasoning:, cost:)
|
|
62
68
|
end
|
|
63
69
|
|
|
64
70
|
def self.zero = new(cost: Cost.zero)
|
|
@@ -77,9 +83,29 @@ module Mistri
|
|
|
77
83
|
total: c.fetch("total", 0).to_f }
|
|
78
84
|
known = c.fetch("known", false) == true
|
|
79
85
|
known ||= !c.key?("known") && counts.values.all?(&:zero?) && amounts.values.all?(&:zero?)
|
|
80
|
-
new(**counts, cost: Cost.new(**amounts, known:))
|
|
86
|
+
new(**counts, cost: Cost.new(**amounts, known:), context: h["context"]&.to_i)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def self._load(payload) = from_h(JSON.parse(payload))
|
|
90
|
+
|
|
91
|
+
def context = defined?(@context) ? @context : nil
|
|
92
|
+
|
|
93
|
+
# The tokens in the model's context once this turn ended.
|
|
94
|
+
def context_tokens = context || (prompt_tokens + output)
|
|
95
|
+
|
|
96
|
+
def with(**changes)
|
|
97
|
+
self.class.new(**self.class.members.to_h { |member| [member, public_send(member)] },
|
|
98
|
+
context:, **changes)
|
|
81
99
|
end
|
|
82
100
|
|
|
101
|
+
def ==(other) = super && context == other.context
|
|
102
|
+
|
|
103
|
+
alias eql? ==
|
|
104
|
+
|
|
105
|
+
def hash = [super, context].hash
|
|
106
|
+
|
|
107
|
+
def _dump(_level) = JSON.generate(to_h)
|
|
108
|
+
|
|
83
109
|
def prompt_tokens = input + cache_read + cache_write
|
|
84
110
|
|
|
85
111
|
def total_tokens = input + output + cache_read + cache_write
|
|
@@ -110,7 +136,10 @@ module Mistri
|
|
|
110
136
|
cost: cost + other.cost)
|
|
111
137
|
end
|
|
112
138
|
|
|
113
|
-
def to_h
|
|
139
|
+
def to_h
|
|
140
|
+
serialized = super.merge(cost: cost.to_h)
|
|
141
|
+
context ? serialized.merge(context:) : serialized
|
|
142
|
+
end
|
|
114
143
|
|
|
115
144
|
private
|
|
116
145
|
|
data/lib/mistri/version.rb
CHANGED
|
@@ -99,23 +99,35 @@ module Mistri
|
|
|
99
99
|
prefix ? paths.select { |p| p.start_with?(prefix.to_s) } : paths
|
|
100
100
|
end
|
|
101
101
|
|
|
102
|
+
# One query, and no document's content leaves the database.
|
|
103
|
+
def sizes(prefix = nil)
|
|
104
|
+
bytes = Arel::Nodes::NamedFunction.new("OCTET_LENGTH", [@model.arel_table[:content]])
|
|
105
|
+
rows = @model.uncached { @model.where(**@scope).pluck(:path, bytes) }.sort
|
|
106
|
+
rows = rows.select { |path, _bytes| path.start_with?(prefix.to_s) } if prefix
|
|
107
|
+
rows.to_h
|
|
108
|
+
end
|
|
109
|
+
|
|
102
110
|
private
|
|
103
111
|
|
|
104
112
|
def verify_atomic_context!
|
|
105
113
|
unless atomic_writes?
|
|
106
|
-
adapter =
|
|
114
|
+
adapter = with_connection(&:adapter_name)
|
|
107
115
|
raise ConfigurationError,
|
|
108
116
|
"atomic Active Record workspace writes require PostgreSQL or InnoDB, " \
|
|
109
117
|
"a matching non-null primary key, non-null scope/path/content columns, " \
|
|
110
118
|
"and an exact unique scope/path key; #{@model.table_name.inspect} on " \
|
|
111
119
|
"#{adapter} does not qualify"
|
|
112
120
|
end
|
|
113
|
-
return unless
|
|
121
|
+
return unless with_connection(&:transaction_open?)
|
|
114
122
|
|
|
115
123
|
raise ConfigurationError,
|
|
116
124
|
"atomic Active Record workspace operations cannot join an open transaction"
|
|
117
125
|
end
|
|
118
126
|
|
|
127
|
+
# Borrows a connection for the block and returns it. Asking the model
|
|
128
|
+
# for its connection would keep one checked out for the rest of the run.
|
|
129
|
+
def with_connection(&) = @model.connection_pool.with_connection(&)
|
|
130
|
+
|
|
119
131
|
def relation(path) = @model.where(**@scope, path: path.to_s)
|
|
120
132
|
|
|
121
133
|
def create_if_absent(path, content)
|
|
@@ -131,14 +143,15 @@ module Mistri
|
|
|
131
143
|
end
|
|
132
144
|
|
|
133
145
|
def atomic_storage?
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
146
|
+
with_connection do |connection|
|
|
147
|
+
adapter = connection.adapter_name
|
|
148
|
+
supported = adapter == "PostgreSQL" ||
|
|
149
|
+
(MYSQL_ADAPTERS.include?(adapter) && innodb_table?(connection))
|
|
150
|
+
supported && atomic_schema?(connection)
|
|
151
|
+
end
|
|
138
152
|
end
|
|
139
153
|
|
|
140
|
-
def innodb_table?
|
|
141
|
-
connection = @model.connection
|
|
154
|
+
def innodb_table?(connection)
|
|
142
155
|
database, table = mysql_table_coordinates(connection)
|
|
143
156
|
sql = "SELECT ENGINE FROM information_schema.TABLES " \
|
|
144
157
|
"WHERE TABLE_SCHEMA = #{connection.quote(database)} " \
|
|
@@ -153,8 +166,7 @@ module Mistri
|
|
|
153
166
|
[connection.current_database, names.first]
|
|
154
167
|
end
|
|
155
168
|
|
|
156
|
-
def atomic_schema?
|
|
157
|
-
connection = @model.connection
|
|
169
|
+
def atomic_schema?(connection)
|
|
158
170
|
columns = connection.columns(@model.table_name).to_h { |column| [column.name, column] }
|
|
159
171
|
primary_columns = Array(@model.primary_key).compact.map(&:to_s)
|
|
160
172
|
catalog_primary = Array(connection.primary_keys(@model.table_name)).map(&:to_s)
|
|
@@ -19,7 +19,7 @@ module Mistri
|
|
|
19
19
|
|
|
20
20
|
def read(path)
|
|
21
21
|
full = resolve(path)
|
|
22
|
-
File.exist?(full) ? File.read(full) : nil
|
|
22
|
+
File.exist?(full) ? File.read(full, encoding: Encoding::UTF_8) : nil
|
|
23
23
|
end
|
|
24
24
|
|
|
25
25
|
def write(path, content)
|
|
@@ -47,6 +47,10 @@ module Mistri
|
|
|
47
47
|
prefix ? paths.select { |p| p.start_with?(prefix.to_s) } : paths
|
|
48
48
|
end
|
|
49
49
|
|
|
50
|
+
def sizes(prefix = nil)
|
|
51
|
+
list(prefix).to_h { |path| [path, File.size(File.join(@root, path))] }
|
|
52
|
+
end
|
|
53
|
+
|
|
50
54
|
private
|
|
51
55
|
|
|
52
56
|
def resolve(path)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../workspace"
|
|
4
|
+
|
|
5
|
+
module Mistri
|
|
6
|
+
module Workspace
|
|
7
|
+
# A host's documents and an agent's scratchpad as one workspace: a path
|
|
8
|
+
# under scratchpad/ belongs to the scratchpad's workspace and every other
|
|
9
|
+
# path to the host's. Paths are passed on as they are, so the two may be
|
|
10
|
+
# the same workspace.
|
|
11
|
+
class PathSpace
|
|
12
|
+
# Sizes in one listing, where both workspaces answer them.
|
|
13
|
+
module Sizes
|
|
14
|
+
def sizes(prefix = nil)
|
|
15
|
+
@files.sizes(prefix).reject { |path, _bytes| scratch?(path) }
|
|
16
|
+
.merge(@scratchpad.sizes(prefix).select { |path, _bytes| scratch?(path) })
|
|
17
|
+
.sort.to_h
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
private_constant :Sizes
|
|
21
|
+
|
|
22
|
+
def initialize(files:, scratchpad:)
|
|
23
|
+
@files = files
|
|
24
|
+
@scratchpad = scratchpad
|
|
25
|
+
extend(Sizes) if [files, scratchpad].all? { |workspace| workspace.respond_to?(:sizes) }
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def read(path) = home(path).read(path)
|
|
29
|
+
|
|
30
|
+
def write(path, content) = home(path).write(path, content)
|
|
31
|
+
|
|
32
|
+
def delete(path) = home(path).delete(path)
|
|
33
|
+
|
|
34
|
+
def list(prefix = nil)
|
|
35
|
+
(@files.list(prefix).reject { |path| scratch?(path) } +
|
|
36
|
+
@scratchpad.list(prefix).select { |path| scratch?(path) }).sort
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def atomic_writes?
|
|
40
|
+
[@files, @scratchpad].all? { |workspace| Tools.atomic_workspace?(workspace) }
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def snapshot(path) = home(path).snapshot(path)
|
|
44
|
+
|
|
45
|
+
def compare_and_write(path, content, expected_revision:)
|
|
46
|
+
home(path).compare_and_write(path, content, expected_revision:)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
private
|
|
50
|
+
|
|
51
|
+
def home(path) = scratch?(path) ? @scratchpad : @files
|
|
52
|
+
|
|
53
|
+
def scratch?(path) = path.to_s.start_with?(Scratchpad::ROOT)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|