kosa8 0.5.3 → 0.7.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 +246 -0
- data/README.md +101 -25
- data/lib/kosa8/cloud.rb +149 -32
- data/lib/kosa8/cloud_features.rb +99 -28
- data/lib/kosa8/cloud_more.rb +1012 -0
- data/lib/kosa8/cloud_rl.rb +4 -4
- data/lib/kosa8/cloud_stream.rb +329 -0
- data/lib/kosa8/errors.rb +101 -16
- data/lib/kosa8/rl.rb +16 -9
- data/lib/kosa8/toolbox.rb +2 -1
- data/lib/kosa8/version.rb +1 -1
- data/lib/kosa8.rb +2 -0
- metadata +14 -6
data/lib/kosa8/cloud_rl.rb
CHANGED
|
@@ -263,8 +263,8 @@ module Kosa8
|
|
|
263
263
|
# <prefix>-0001, ...) and partial_ok: (default true: make what fits and
|
|
264
264
|
# list the rest in +failed+; false: all or nothing). Nothing made raises
|
|
265
265
|
# the first refusal. Carries an Idempotency-Key (+idempotency_key+,
|
|
266
|
-
# default a new UUID) reused
|
|
267
|
-
# doubles the fleet.
|
|
266
|
+
# default a new UUID) reused after a timeout, so a retried batch never
|
|
267
|
+
# doubles the fleet (the default is renewed after a 5xx).
|
|
268
268
|
def create_many(count, labels: nil, run_id: nil, lease_s: nil, prefix: nil, partial_ok: nil,
|
|
269
269
|
idempotency_key: nil, **create_opts)
|
|
270
270
|
unless count.is_a?(Integer) && count.between?(1, Cloud::MAX_BATCH)
|
|
@@ -340,8 +340,8 @@ module Kosa8
|
|
|
340
340
|
# 0 and 0.0 otherwise; nil when the command did not finish. With run_id:
|
|
341
341
|
# it is recorded as a rollout of that run (rollout: step, group, index,
|
|
342
342
|
# meta), so do not record it again. files: at most 64, 8 MiB in all;
|
|
343
|
-
# timeout_s: 1 to 90. The call carries an Idempotency-Key reused
|
|
344
|
-
#
|
|
343
|
+
# timeout_s: 1 to 90. The call carries an Idempotency-Key reused after a
|
|
344
|
+
# timeout: that retry gets the first answer and records nothing twice.
|
|
345
345
|
def grade(cmd, files: nil, timeout_s: nil, env: nil, keep: false, run_id: nil, rollout: nil, idempotency_key: nil)
|
|
346
346
|
run_id = (@cloud.run_defaults || {})["run_id"] if run_id.nil?
|
|
347
347
|
body = Cloud.grade_body(cmd, files: files, timeout_s: timeout_s, env: env, keep: keep, run_id: run_id,
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "openssl"
|
|
6
|
+
require "socket"
|
|
7
|
+
require "uri"
|
|
8
|
+
|
|
9
|
+
# Streamed exec on kosa8 Cloud: POST /v1/sandboxes/{id}/exec {stream: true}
|
|
10
|
+
# answers NDJSON frames while the command prints ({stream, data: base64},
|
|
11
|
+
# an empty stdout frame with heartbeat: true every 15 s of silence, then
|
|
12
|
+
# {done: true, exit} or {done: true, error, code}). Not held to the 90 s of
|
|
13
|
+
# a buffered exec.
|
|
14
|
+
module Kosa8
|
|
15
|
+
class Cloud
|
|
16
|
+
# The longest timeout_s a streamed or background command takes (a day).
|
|
17
|
+
STREAM_MAX_TIMEOUT_S = 86_400
|
|
18
|
+
# A read that waits longer than this without a byte is a dead
|
|
19
|
+
# connection, not a quiet command (heartbeats come every 15 s).
|
|
20
|
+
STREAM_MIN_READ_TIMEOUT_S = 30
|
|
21
|
+
|
|
22
|
+
alias initialize_without_stream initialize
|
|
23
|
+
# stream_transport: an optional callable (method, url, headers, body,
|
|
24
|
+
# read_timeout) { |chunk| ... } -> [status, error_body_or_nil, headers]
|
|
25
|
+
# used for streamed answers instead of Net::HTTP (tests, proxies): it
|
|
26
|
+
# yields each chunk of a 2xx answer as it arrives and returns the
|
|
27
|
+
# body of an error answer.
|
|
28
|
+
def initialize(stream_transport: nil, **kw)
|
|
29
|
+
initialize_without_stream(**kw)
|
|
30
|
+
@stream_transport = stream_transport || method(:net_http_stream)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# One streamed request: yields the answer's bytes as they arrive. A
|
|
34
|
+
# refusal before the stream starts raises the usual typed error (a
|
|
35
|
+
# refusal made before anything ran, such as a 429, is retried as
|
|
36
|
+
# retry_policy allows); nothing is retried once bytes flow. A broken or
|
|
37
|
+
# stalled stream raises Kosa8::StreamError.
|
|
38
|
+
def stream(method, path, body)
|
|
39
|
+
headers = { "Authorization" => "Bearer #{@key}", "User-Agent" => "kosa8-ruby/#{VERSION}",
|
|
40
|
+
"Accept" => "application/x-ndjson, application/json", "Content-Type" => "application/json" }
|
|
41
|
+
payload = JSON.generate(body)
|
|
42
|
+
read_timeout = [@timeout.to_f, STREAM_MIN_READ_TIMEOUT_S].max
|
|
43
|
+
attempt = 1
|
|
44
|
+
loop do
|
|
45
|
+
started = false
|
|
46
|
+
begin
|
|
47
|
+
status, content, resp_headers = @stream_transport.call(method, @base_url + path, headers, payload,
|
|
48
|
+
read_timeout) do |chunk|
|
|
49
|
+
started = true
|
|
50
|
+
begin
|
|
51
|
+
yield chunk
|
|
52
|
+
rescue Exception => e # rubocop:disable Lint/RescueException
|
|
53
|
+
raise CallbackFailure.new(e)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
rescue CallbackFailure => e
|
|
57
|
+
raise e.cause_error
|
|
58
|
+
rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error => e
|
|
59
|
+
if started
|
|
60
|
+
raise StreamError.new("kosa8 Cloud stopped sending the exec stream (no data or heartbeat in #{read_timeout.round} s)",
|
|
61
|
+
method: method, path: path, code: "stream_stalled")
|
|
62
|
+
end
|
|
63
|
+
raise TimeoutError.new("kosa8 Cloud did not answer #{method} #{path} within #{read_timeout.round} s (#{e.message})",
|
|
64
|
+
method: method, path: path)
|
|
65
|
+
rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError => e
|
|
66
|
+
raise StreamError.new("the exec stream broke: #{e.message}", method: method, path: path, code: "stream_broken") if started
|
|
67
|
+
|
|
68
|
+
raise ConnectionError.new("could not reach kosa8 Cloud at #{@base_url}: #{e.message}; " \
|
|
69
|
+
"check the network connection and KOSA8_CLOUD_URL (or base_url:), then try again",
|
|
70
|
+
method: method, path: path)
|
|
71
|
+
end
|
|
72
|
+
return nil if status.to_i < 400
|
|
73
|
+
|
|
74
|
+
text = content.to_s.dup.force_encoding(Encoding::UTF_8).scrub
|
|
75
|
+
parsed = begin
|
|
76
|
+
text.strip.empty? ? nil : JSON.parse(text)
|
|
77
|
+
rescue JSON::ParserError
|
|
78
|
+
text
|
|
79
|
+
end
|
|
80
|
+
e = Cloud.error(status.to_i, parsed, method, path, resp_headers)
|
|
81
|
+
raise e unless !started && Cloud.pre_execution?(e) && @retry_policy.retry?(e, attempt)
|
|
82
|
+
|
|
83
|
+
@sleeper.call(@retry_policy.delay(e, attempt))
|
|
84
|
+
attempt += 1
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def self.check_stream_timeout(timeout_s)
|
|
89
|
+
return if timeout_s.nil? || (timeout_s.is_a?(Integer) && timeout_s.between?(1, STREAM_MAX_TIMEOUT_S))
|
|
90
|
+
|
|
91
|
+
raise ArgumentError, "timeout_s must be a whole number of seconds from 1 to #{STREAM_MAX_TIMEOUT_S}"
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
def net_http_stream(method, url, headers, body, timeout)
|
|
97
|
+
u = URI.parse(url)
|
|
98
|
+
http = Net::HTTP.new(u.hostname, u.port)
|
|
99
|
+
http.use_ssl = u.scheme == "https"
|
|
100
|
+
http.open_timeout = [timeout, 30].min
|
|
101
|
+
http.read_timeout = timeout
|
|
102
|
+
http.write_timeout = timeout if http.respond_to?(:write_timeout=)
|
|
103
|
+
req = Net::HTTPGenericRequest.new(method, !body.nil?, true, u.request_uri)
|
|
104
|
+
headers.each { |k, v| req[k] = v }
|
|
105
|
+
req.body = body unless body.nil?
|
|
106
|
+
http.start do |h|
|
|
107
|
+
h.request(req) do |resp|
|
|
108
|
+
code = resp.code.to_i
|
|
109
|
+
return [code, resp.read_body.to_s, resp.to_hash] if code >= 400
|
|
110
|
+
|
|
111
|
+
resp.read_body { |chunk| yield chunk }
|
|
112
|
+
return [code, nil, resp.to_hash]
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# Reads a streamed exec's NDJSON frames from chunks that split lines and
|
|
119
|
+
# UTF-8 characters anywhere.
|
|
120
|
+
class CloudExecStream # :nodoc:
|
|
121
|
+
STREAMS = %w[stdout stderr].freeze
|
|
122
|
+
attr_reader :exit_code, :done
|
|
123
|
+
|
|
124
|
+
def initialize(path, on_text)
|
|
125
|
+
@path = path
|
|
126
|
+
@on_text = on_text
|
|
127
|
+
@line = +"".b
|
|
128
|
+
@pending = { "stdout" => +"".b, "stderr" => +"".b }
|
|
129
|
+
@out = { "stdout" => +"", "stderr" => +"" }
|
|
130
|
+
@exit_code = nil
|
|
131
|
+
@done = false
|
|
132
|
+
@whole = nil
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def stdout
|
|
136
|
+
@out["stdout"]
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def stderr
|
|
140
|
+
@out["stderr"]
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# A buffered answer (an ExecResult) when the server sent one instead of frames.
|
|
144
|
+
attr_reader :whole
|
|
145
|
+
|
|
146
|
+
def feed(chunk)
|
|
147
|
+
return if @done
|
|
148
|
+
|
|
149
|
+
@line << chunk.to_s.b
|
|
150
|
+
while (i = @line.index("\n".b))
|
|
151
|
+
line = @line.slice!(0..i)
|
|
152
|
+
frame(line)
|
|
153
|
+
return if @done
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# The stream ended: the last line, then any bytes held for a split character.
|
|
158
|
+
def finish
|
|
159
|
+
frame(@line) unless @done || @line.strip.empty?
|
|
160
|
+
flush
|
|
161
|
+
return if @done || @whole
|
|
162
|
+
|
|
163
|
+
raise StreamError.new("the exec stream ended before the command finished (no final frame)",
|
|
164
|
+
stdout: stdout, stderr: stderr, method: "POST", path: @path, code: "stream_broken")
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
private
|
|
168
|
+
|
|
169
|
+
def frame(line)
|
|
170
|
+
text = line.strip
|
|
171
|
+
return if text.empty?
|
|
172
|
+
|
|
173
|
+
f = begin
|
|
174
|
+
JSON.parse(text.force_encoding(Encoding::UTF_8))
|
|
175
|
+
rescue JSON::ParserError
|
|
176
|
+
raise StreamError.new("kosa8 Cloud sent a stream line that is not JSON: #{text[0, 200].inspect}",
|
|
177
|
+
stdout: stdout, stderr: stderr, method: "POST", path: @path, code: "stream_broken")
|
|
178
|
+
end
|
|
179
|
+
return unless f.is_a?(Hash)
|
|
180
|
+
|
|
181
|
+
if f["done"]
|
|
182
|
+
flush
|
|
183
|
+
@done = true
|
|
184
|
+
fail_with(f) unless f["error"].nil?
|
|
185
|
+
@exit_code = f["exit"].is_a?(Integer) ? f["exit"] : nil
|
|
186
|
+
return
|
|
187
|
+
end
|
|
188
|
+
if f.key?("exit") && f.key?("stdout") && !f.key?("stream")
|
|
189
|
+
@whole = f # a server that ignored stream: true answered the whole result
|
|
190
|
+
@done = true
|
|
191
|
+
return
|
|
192
|
+
end
|
|
193
|
+
name = f["stream"]
|
|
194
|
+
data = f["data"]
|
|
195
|
+
return unless STREAMS.include?(name) && data.is_a?(String) && !data.empty? # a heartbeat, or unknown
|
|
196
|
+
|
|
197
|
+
bytes = begin
|
|
198
|
+
data.unpack1("m0")
|
|
199
|
+
rescue ArgumentError
|
|
200
|
+
data.b
|
|
201
|
+
end
|
|
202
|
+
emit(name, decode(name, bytes))
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def emit(name, text)
|
|
206
|
+
return if text.empty?
|
|
207
|
+
|
|
208
|
+
@out[name] << text
|
|
209
|
+
@on_text&.call(name, text)
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def flush
|
|
213
|
+
STREAMS.each do |name|
|
|
214
|
+
rest = @pending[name]
|
|
215
|
+
@pending[name] = +"".b
|
|
216
|
+
emit(name, rest.force_encoding(Encoding::UTF_8).scrub) unless rest.empty?
|
|
217
|
+
end
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
# The text of +bytes+ after what was held back, holding back a
|
|
221
|
+
# trailing incomplete UTF-8 character for the next chunk.
|
|
222
|
+
def decode(name, bytes)
|
|
223
|
+
buf = @pending[name] + bytes.b
|
|
224
|
+
cut = buf.bytesize
|
|
225
|
+
1.upto([3, buf.bytesize].min) do |k|
|
|
226
|
+
b = buf.getbyte(buf.bytesize - k)
|
|
227
|
+
break if b < 0x80 # ASCII: nothing is split
|
|
228
|
+
next unless b >= 0xC0 # a lead byte
|
|
229
|
+
|
|
230
|
+
need = if b >= 0xF0 then 4
|
|
231
|
+
elsif b >= 0xE0 then 3
|
|
232
|
+
else 2
|
|
233
|
+
end
|
|
234
|
+
cut = buf.bytesize - k if need > k
|
|
235
|
+
break
|
|
236
|
+
end
|
|
237
|
+
@pending[name] = buf.byteslice(cut..-1) || +"".b
|
|
238
|
+
buf.byteslice(0, cut).force_encoding(Encoding::UTF_8).scrub
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
def fail_with(f)
|
|
242
|
+
msg = f["error"].to_s
|
|
243
|
+
msg = "the command failed" if msg.empty?
|
|
244
|
+
code = f["code"].is_a?(String) ? f["code"] : nil
|
|
245
|
+
if code == "exec_timeout" || msg.include?("timeout_s")
|
|
246
|
+
e = ExecTimeoutError.new(msg, status: 504, daemon_message: msg, method: "POST", path: @path,
|
|
247
|
+
code: "exec_timeout")
|
|
248
|
+
e.stdout = stdout
|
|
249
|
+
e.stderr = stderr
|
|
250
|
+
raise e
|
|
251
|
+
end
|
|
252
|
+
raise StreamError.new(msg, stdout: stdout, stderr: stderr, method: "POST", path: @path, code: code)
|
|
253
|
+
end
|
|
254
|
+
end
|
|
255
|
+
|
|
256
|
+
class CloudSandbox
|
|
257
|
+
alias exec_buffered exec
|
|
258
|
+
|
|
259
|
+
# Run a command and wait for it. A String runs through sh -c, an Array is
|
|
260
|
+
# the argv. A sleeping sandbox wakes for it.
|
|
261
|
+
#
|
|
262
|
+
# With +on_stdout+ / +on_stderr+ (callables taking the text), +stream:
|
|
263
|
+
# true+ or a +timeout_s+ over 90, it runs as a streamed exec
|
|
264
|
+
# (#exec_stream): the callbacks get the output as the command prints it
|
|
265
|
+
# and the command is not held to the 90 s of a buffered exec. The result
|
|
266
|
+
# is a CloudExecResult either way. +stream: false+ always buffers.
|
|
267
|
+
def exec(cmd, image: nil, env: nil, timeout_s: nil, stream: nil, on_stdout: nil, on_stderr: nil)
|
|
268
|
+
long = timeout_s.is_a?(Numeric) && timeout_s > Cloud::EXEC_LIMIT_S
|
|
269
|
+
if stream == true || (stream.nil? && (on_stdout || on_stderr || long))
|
|
270
|
+
return exec_stream(cmd, image: image, env: env, timeout_s: timeout_s, on_stdout: on_stdout,
|
|
271
|
+
on_stderr: on_stderr)
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
r = exec_buffered(cmd, image: image, env: env, timeout_s: timeout_s)
|
|
275
|
+
on_stdout&.call(r.stdout) unless r.stdout.empty?
|
|
276
|
+
on_stderr&.call(r.stderr) unless r.stderr.empty?
|
|
277
|
+
r
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# Run a command and read its output as it prints (a streamed exec); not
|
|
281
|
+
# held to the 90 s of a buffered exec. +timeout_s+ (1 s to a day) stops
|
|
282
|
+
# it in the sandbox. Yields (stream, text) with stream "stdout" or
|
|
283
|
+
# "stderr" (UTF-8, decoded across chunk edges; heartbeats skipped), and
|
|
284
|
+
# calls +on_stdout+ / +on_stderr+ likewise; returns a CloudExecResult
|
|
285
|
+
# with everything it printed.
|
|
286
|
+
#
|
|
287
|
+
# box.exec_stream("make test") { |_stream, text| print text }
|
|
288
|
+
#
|
|
289
|
+
# A refusal (bad request, sandbox not running) raises before any output.
|
|
290
|
+
# A command stopped at +timeout_s+ raises Kosa8::ExecTimeoutError (its
|
|
291
|
+
# #stdout / #stderr hold the output so far); a stream that breaks or
|
|
292
|
+
# ends early raises Kosa8::StreamError, with the output so far.
|
|
293
|
+
def exec_stream(cmd, image: nil, env: nil, timeout_s: nil, on_stdout: nil, on_stderr: nil, &block)
|
|
294
|
+
argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
|
|
295
|
+
raise ArgumentError, "exec_stream needs a command" if argv.empty?
|
|
296
|
+
|
|
297
|
+
Cloud.check_stream_timeout(timeout_s)
|
|
298
|
+
body = { "cmd" => argv, "stream" => true }
|
|
299
|
+
body["image"] = image unless image.nil?
|
|
300
|
+
body["env"] = Cloud.env_list(env) if env && !env.empty?
|
|
301
|
+
body["timeout_s"] = timeout_s unless timeout_s.nil?
|
|
302
|
+
cbs = { "stdout" => on_stdout, "stderr" => on_stderr }
|
|
303
|
+
reader = CloudExecStream.new(path("/exec"), lambda { |name, text|
|
|
304
|
+
cbs[name]&.call(text)
|
|
305
|
+
block&.call(name, text)
|
|
306
|
+
})
|
|
307
|
+
@cloud.stream("POST", path("/exec"), body) { |chunk| reader.feed(chunk) }
|
|
308
|
+
reader.finish
|
|
309
|
+
if (w = reader.whole)
|
|
310
|
+
res = CloudExecResult.new(exit_code: w["exit"], stdout: w["stdout"].to_s, stderr: w["stderr"].to_s,
|
|
311
|
+
woke_ms: w["woke_ms"], failure_class: nil, retryable: nil)
|
|
312
|
+
fc, rt = Kosa8.exec_failure(w["exit"])
|
|
313
|
+
res.failure_class = w["failure_class"].is_a?(String) ? w["failure_class"] : fc
|
|
314
|
+
res.retryable = [true, false].include?(w["retryable"]) ? w["retryable"] : rt
|
|
315
|
+
{ "stdout" => res.stdout, "stderr" => res.stderr }.each do |n, t|
|
|
316
|
+
next if t.empty?
|
|
317
|
+
|
|
318
|
+
cbs[n]&.call(t)
|
|
319
|
+
block&.call(n, t)
|
|
320
|
+
end
|
|
321
|
+
return res
|
|
322
|
+
end
|
|
323
|
+
fc, rt = Kosa8.exec_failure(reader.exit_code)
|
|
324
|
+
CloudExecResult.new(exit_code: reader.exit_code, stdout: reader.stdout, stderr: reader.stderr, woke_ms: nil,
|
|
325
|
+
failure_class: fc, retryable: rt, stdout_truncated: false, stderr_truncated: false,
|
|
326
|
+
stdout_bytes: reader.stdout.bytesize, stderr_bytes: reader.stderr.bytesize)
|
|
327
|
+
end
|
|
328
|
+
end
|
|
329
|
+
end
|
data/lib/kosa8/errors.rb
CHANGED
|
@@ -29,6 +29,9 @@ module Kosa8
|
|
|
29
29
|
@path = path
|
|
30
30
|
@body = body
|
|
31
31
|
@code = code
|
|
32
|
+
@detail = nil
|
|
33
|
+
@retry_after = nil
|
|
34
|
+
@request_id = nil
|
|
32
35
|
end
|
|
33
36
|
|
|
34
37
|
# The message: the server's own sentence (or the SDK's), followed for a
|
|
@@ -60,30 +63,86 @@ module Kosa8
|
|
|
60
63
|
end
|
|
61
64
|
|
|
62
65
|
class ConnectionError < Error; end # daemon unreachable
|
|
63
|
-
class ApiError < Error; end # any HTTP error answer
|
|
64
|
-
class BadRequestError < ApiError; end # 400
|
|
65
|
-
class AuthError < ApiError; end # 401
|
|
66
|
-
class PolicyError < ApiError; end # 403
|
|
67
|
-
class NotFoundError < ApiError; end # 404
|
|
68
|
-
class ConflictError < ApiError; end # 409
|
|
69
|
-
class UnsupportedError < ApiError; end # 501
|
|
70
66
|
|
|
71
|
-
#
|
|
72
|
-
#
|
|
73
|
-
|
|
74
|
-
|
|
67
|
+
# Any HTTP error answer. A kosa8 Cloud answer's contract fields (see the
|
|
68
|
+
# API's Error schema) are read from +body+; each is nil when the answer
|
|
69
|
+
# did not carry it.
|
|
70
|
+
class ApiError < Error
|
|
71
|
+
# 402: where the person adds a payment method or credit, or raises the cap.
|
|
75
72
|
def upgrade_url
|
|
76
73
|
Kosa8.body_str(body, "upgrade_url")
|
|
77
74
|
end
|
|
78
75
|
|
|
79
|
-
#
|
|
76
|
+
# 402 and 429 quota_exceeded: a sentence an AI agent should relay to its
|
|
77
|
+
# person word for word.
|
|
80
78
|
def agent_message
|
|
81
79
|
Kosa8.body_str(body, "agent_message")
|
|
82
80
|
end
|
|
81
|
+
|
|
82
|
+
# 429 quota_exceeded: where to ask for a higher limit.
|
|
83
|
+
def request_url
|
|
84
|
+
Kosa8.body_str(body, "request_url")
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# 402 plan_limit: which limit (sandbox_hours, running, size, persistent or snapshots).
|
|
88
|
+
def limit_name
|
|
89
|
+
Kosa8.body_str(body, "limit_name")
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# 402 plan_limit: the plan's limit (a Number).
|
|
93
|
+
def limit
|
|
94
|
+
Kosa8.body_num(body, "limit")
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# 402 plan_limit: what the organization has used.
|
|
98
|
+
def used
|
|
99
|
+
Kosa8.body_num(body, "used")
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# 402 plan_limit and plan_feature: the organization's plan.
|
|
103
|
+
def plan
|
|
104
|
+
Kosa8.body_str(body, "plan")
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# 402 plan_limit and plan_feature: the first plan that includes more (nil: contact sales).
|
|
108
|
+
def next_plan
|
|
109
|
+
Kosa8.body_str(body, "next_plan")
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# 402 plan_feature: the feature the plan lacks.
|
|
113
|
+
def feature
|
|
114
|
+
Kosa8.body_str(body, "feature")
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# 402 plan_limit: the ways past the limit, cheaper first (Hashes: "kind"
|
|
118
|
+
# pack or upgrade, "addon", "plan", "label", "monthly_usd", "url").
|
|
119
|
+
def options
|
|
120
|
+
v = body.is_a?(Hash) ? body["options"] : nil
|
|
121
|
+
v.is_a?(Array) ? v.select { |o| o.is_a?(Hash) } : []
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# 402 plan_limit: where to add the pack for this limit, when one is sold.
|
|
125
|
+
def pack_url
|
|
126
|
+
Kosa8.body_str(body, "pack_url")
|
|
127
|
+
end
|
|
83
128
|
end
|
|
84
129
|
|
|
85
|
-
|
|
86
|
-
|
|
130
|
+
class BadRequestError < ApiError; end # 400
|
|
131
|
+
class AuthError < ApiError; end # 401
|
|
132
|
+
class PolicyError < ApiError; end # 403
|
|
133
|
+
class NotFoundError < ApiError; end # 404
|
|
134
|
+
class ConflictError < ApiError; end # 409
|
|
135
|
+
class UnsupportedError < ApiError; end # 501
|
|
136
|
+
|
|
137
|
+
# 402: kosa8 Cloud wants a payment method, credit or an accepted price first
|
|
138
|
+
# (+code+ payment_required, spending_cap_reached, price_not_accepted, ...).
|
|
139
|
+
# #upgrade_url, #agent_message and the plan_limit fields (#limit_name,
|
|
140
|
+
# #limit, #used, #plan, #next_plan, #options, #pack_url) are on ApiError.
|
|
141
|
+
class PaymentRequiredError < ApiError; end
|
|
142
|
+
|
|
143
|
+
# 429: too many requests, or a quota reached (+code+ quota_exceeded, with
|
|
144
|
+
# #agent_message and #request_url). +retry_after+ is the server's
|
|
145
|
+
# Retry-After in seconds, when it sent one.
|
|
87
146
|
class RateLimitError < ApiError; end
|
|
88
147
|
|
|
89
148
|
# 423 (+code+ org_frozen): the org is frozen in the Security Center. New
|
|
@@ -97,7 +156,24 @@ module Kosa8
|
|
|
97
156
|
# writing to /workspace, and poll it:
|
|
98
157
|
#
|
|
99
158
|
# box.exec("nohup sh -c 'make test > /workspace/test.log 2>&1' &")
|
|
100
|
-
class ExecTimeoutError < ApiError
|
|
159
|
+
class ExecTimeoutError < ApiError
|
|
160
|
+
attr_writer :stdout, :stderr
|
|
161
|
+
|
|
162
|
+
# The output so far: a streamed exec's, or what a buffered exec stopped
|
|
163
|
+
# at its own timeout_s sent back ("" when the answer had none).
|
|
164
|
+
def stdout
|
|
165
|
+
@stdout || Kosa8.body_str(body, "stdout") || ""
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def stderr
|
|
169
|
+
@stderr || Kosa8.body_str(body, "stderr") || ""
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# The limit the command ran past, in seconds, when the answer said.
|
|
173
|
+
def limit_s
|
|
174
|
+
Kosa8.body_num(body, "limit_s")
|
|
175
|
+
end
|
|
176
|
+
end
|
|
101
177
|
|
|
102
178
|
# 403 that a signed approval would lift; +approval+ is the daemon's refusal.
|
|
103
179
|
class ApprovalRequiredError < PolicyError
|
|
@@ -138,6 +214,12 @@ module Kosa8
|
|
|
138
214
|
v.is_a?(String) && !v.empty? ? v : nil
|
|
139
215
|
end
|
|
140
216
|
|
|
217
|
+
# body[key] when it is a Number, else nil.
|
|
218
|
+
def self.body_num(body, key)
|
|
219
|
+
v = body.is_a?(Hash) ? body[key] : nil
|
|
220
|
+
v.is_a?(Numeric) ? v : nil
|
|
221
|
+
end
|
|
222
|
+
|
|
141
223
|
# The typed error for an HTTP error answer: the daemon's message with its
|
|
142
224
|
# remediation in parentheses, as the CLI and MCP server print it.
|
|
143
225
|
def self.error_from_response(status, body, method:, path:, code: nil)
|
|
@@ -164,7 +246,7 @@ module Kosa8
|
|
|
164
246
|
FAILURE_CLASSES = %w[ok exit_nonzero timeout oom infra quota client].freeze
|
|
165
247
|
INFRA_CODES = %w[host_failed not_ready no_capacity host_unreachable host_unavailable host_busy host_restarting
|
|
166
248
|
wake_failed try_again internal kernel_failed egress_failed dns_unreachable host_lost host_removed
|
|
167
|
-
insufficient_storage starting].freeze
|
|
249
|
+
insufficient_storage starting database_busy].freeze
|
|
168
250
|
RATE_CODES = %w[rate_limited slow_down too_soon].freeze
|
|
169
251
|
QUOTA_CODES = %w[quota_exceeded running_limit plan_required plan_limit plan_feature payment_required payment_declined
|
|
170
252
|
spending_cap_reached snapshot_limit org_frozen org_suspended too_many_runs].freeze
|
|
@@ -177,6 +259,9 @@ module Kosa8
|
|
|
177
259
|
c = code.is_a?(String) ? code : ""
|
|
178
260
|
return ["ok", false] if status < 400
|
|
179
261
|
return ["timeout", false] if c == "exec_timeout"
|
|
262
|
+
return ["infra", true] if c == IDEMPOTENCY_IN_PROGRESS || c == "template_building"
|
|
263
|
+
# A bad parameter is the caller's to fix, whatever it names (invalid_timeout).
|
|
264
|
+
return ["client", false] if status < 500 && /\A(invalid|bad|missing|unknown)_/.match?(c)
|
|
180
265
|
return ["timeout", true] if c.include?("timeout")
|
|
181
266
|
return ["quota", true] if RATE_CODES.include?(c)
|
|
182
267
|
return ["quota", false] if QUOTA_CODES.include?(c) || status == 402 || status == 423
|
data/lib/kosa8/rl.rb
CHANGED
|
@@ -274,6 +274,10 @@ module Kosa8
|
|
|
274
274
|
@recorded = 0
|
|
275
275
|
@status = nil
|
|
276
276
|
@buf = []
|
|
277
|
+
# The chunk being sent and its Idempotency-Key, kept together until
|
|
278
|
+
# kosa8 Cloud answers: a later flush resends the same rows with the
|
|
279
|
+
# same key, so a send whose answer was lost is stored once.
|
|
280
|
+
@inflight = nil
|
|
277
281
|
@buf_lock = Mutex.new
|
|
278
282
|
@flush_lock = Mutex.new
|
|
279
283
|
@lease = nil
|
|
@@ -352,15 +356,18 @@ module Kosa8
|
|
|
352
356
|
sent = 0
|
|
353
357
|
@flush_lock.synchronize do
|
|
354
358
|
loop do
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
rescue Exception # rubocop:disable Lint/RescueException
|
|
361
|
-
@buf_lock.synchronize { @buf.unshift(*chunk) }
|
|
362
|
-
raise
|
|
359
|
+
@buf_lock.synchronize do
|
|
360
|
+
if @inflight.nil?
|
|
361
|
+
rows = @buf.shift(MAX_ROWS_PER_CALL)
|
|
362
|
+
@inflight = [rows, SecureRandom.uuid] unless rows.empty?
|
|
363
|
+
end
|
|
363
364
|
end
|
|
365
|
+
return sent if @inflight.nil?
|
|
366
|
+
|
|
367
|
+
chunk, key = @inflight
|
|
368
|
+
# On an error the chunk stays in flight with its key, for the next flush.
|
|
369
|
+
r = @cloud.request("POST", path("/rollouts"), { "rollouts" => chunk }, { idempotency_key: key })
|
|
370
|
+
@buf_lock.synchronize { @inflight = nil }
|
|
364
371
|
n = r.is_a?(Hash) && r["recorded"].is_a?(Integer) ? r["recorded"] : chunk.size
|
|
365
372
|
sent += n
|
|
366
373
|
@recorded += n
|
|
@@ -370,7 +377,7 @@ module Kosa8
|
|
|
370
377
|
|
|
371
378
|
# Rollouts buffered, not yet sent.
|
|
372
379
|
def pending
|
|
373
|
-
@buf_lock.synchronize { @buf.size }
|
|
380
|
+
@buf_lock.synchronize { @buf.size + (@inflight ? @inflight[0].size : 0) }
|
|
374
381
|
end
|
|
375
382
|
|
|
376
383
|
# The run with its summary (rewards, failure classes, live sandboxes,
|
data/lib/kosa8/toolbox.rb
CHANGED
|
@@ -290,7 +290,8 @@ module Kosa8
|
|
|
290
290
|
di = File.join(path, ".dockerignore")
|
|
291
291
|
if File.exist?(di)
|
|
292
292
|
ignore = File.readlines(di).reject { |l| l.strip.empty? || l.start_with?("#") }
|
|
293
|
-
.map { |l| Pathname.new(l.strip).cleanpath.to_s }
|
|
293
|
+
.map { |l| Pathname.new(l.strip).cleanpath.to_s.sub(%r{\A/+}, "") } # "/build" is "build"
|
|
294
|
+
.reject { |l| l.empty? || l == "." }
|
|
294
295
|
end
|
|
295
296
|
skip = ->(rel) { ignore.any? { |p| rel == p || rel.start_with?(p + "/") } }
|
|
296
297
|
io = StringIO.new(+"".b)
|
data/lib/kosa8/version.rb
CHANGED
data/lib/kosa8.rb
CHANGED
|
@@ -11,5 +11,7 @@ require_relative "kosa8/client"
|
|
|
11
11
|
require_relative "kosa8/cloud"
|
|
12
12
|
require_relative "kosa8/cloud_features"
|
|
13
13
|
require_relative "kosa8/cloud_rl"
|
|
14
|
+
require_relative "kosa8/cloud_more"
|
|
15
|
+
require_relative "kosa8/cloud_stream"
|
|
14
16
|
require_relative "kosa8/fork_map"
|
|
15
17
|
require_relative "kosa8/rl"
|
metadata
CHANGED
|
@@ -1,23 +1,25 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: kosa8
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.7.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- kosa8
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-11-
|
|
11
|
+
date: 2026-11-24 00:00:00.000000000 Z
|
|
12
12
|
dependencies: []
|
|
13
|
-
description: '
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
description: 'Zero Trust cybersecurity infrastructure for AI agents: each agent in
|
|
14
|
+
its own microVM. Typed client for the kosa8 daemon: sandboxes, run/exec streams,
|
|
15
|
+
snapshots, fork, best-of-N explore and checkpoints shared with the kosa8 CLI, plus
|
|
16
|
+
the kosa8 Cloud API. No dependencies.'
|
|
16
17
|
email:
|
|
17
18
|
executables: []
|
|
18
19
|
extensions: []
|
|
19
20
|
extra_rdoc_files: []
|
|
20
21
|
files:
|
|
22
|
+
- CHANGELOG.md
|
|
21
23
|
- LICENSE
|
|
22
24
|
- README.md
|
|
23
25
|
- lib/kosa8.rb
|
|
@@ -25,7 +27,9 @@ files:
|
|
|
25
27
|
- lib/kosa8/client.rb
|
|
26
28
|
- lib/kosa8/cloud.rb
|
|
27
29
|
- lib/kosa8/cloud_features.rb
|
|
30
|
+
- lib/kosa8/cloud_more.rb
|
|
28
31
|
- lib/kosa8/cloud_rl.rb
|
|
32
|
+
- lib/kosa8/cloud_stream.rb
|
|
29
33
|
- lib/kosa8/errors.rb
|
|
30
34
|
- lib/kosa8/fork_map.rb
|
|
31
35
|
- lib/kosa8/rl.rb
|
|
@@ -36,7 +40,11 @@ homepage: https://kosa8.com
|
|
|
36
40
|
licenses:
|
|
37
41
|
- MIT
|
|
38
42
|
metadata:
|
|
43
|
+
homepage_uri: https://kosa8.com
|
|
39
44
|
source_code_uri: https://github.com/kosa8ai/kosa8-rb
|
|
45
|
+
changelog_uri: https://github.com/kosa8ai/kosa8-rb/blob/main/CHANGELOG.md
|
|
46
|
+
bug_tracker_uri: https://github.com/kosa8ai/kosa8-rb/issues
|
|
47
|
+
documentation_uri: https://docs.kosa8.com
|
|
40
48
|
post_install_message:
|
|
41
49
|
rdoc_options: []
|
|
42
50
|
require_paths:
|
|
@@ -55,5 +63,5 @@ requirements: []
|
|
|
55
63
|
rubygems_version: 3.0.3.1
|
|
56
64
|
signing_key:
|
|
57
65
|
specification_version: 4
|
|
58
|
-
summary: '
|
|
66
|
+
summary: 'Zero Trust cybersecurity infrastructure for AI agents: the kosa8 Ruby SDK'
|
|
59
67
|
test_files: []
|