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.
@@ -0,0 +1,1012 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+ require "uri"
6
+
7
+ # More of kosa8 Cloud (0.6.0), to match @kosa8/sdk and the Python SDK:
8
+ # browsers, the AI gateway, hosted jobs, benchmarks, RL compare and alerts,
9
+ # usage insights, limits and pricing, the audit log, API keys, webhooks,
10
+ # function invocations, org egress, Burst Passes, embeds, custom preview
11
+ # domains and desktop recordings. Answers are the API's own Hashes
12
+ # (snake_case keys, times in Unix ms unless the API says otherwise).
13
+ module Kosa8
14
+ class Cloud
15
+ # Headless Chromium on demand (a CloudBrowsers).
16
+ attr_reader :browsers
17
+ # The org's AI gateway: provider keys kept server-side, usage (a CloudAi).
18
+ attr_reader :ai
19
+ # Hosted eval/RL jobs: tasks, a solver and a grader (a CloudJobs).
20
+ attr_reader :jobs
21
+ # Ready-made benchmarks and their environments (a CloudBenchmarks).
22
+ attr_reader :benchmarks
23
+ # Alert rules on RL runs (a CloudRlAlerts).
24
+ attr_reader :rl_alerts
25
+ # The audit log (a CloudAudit).
26
+ attr_reader :audit
27
+ # The org's API keys (a CloudApiKeys; needs a key with keys:manage).
28
+ attr_reader :api_keys
29
+ # Webhook endpoints (a CloudWebhooks).
30
+ attr_reader :webhooks
31
+ # Desktop recordings (a CloudRecordings).
32
+ attr_reader :recordings
33
+ # Burst Passes (a CloudBurst).
34
+ attr_reader :burst
35
+
36
+ alias initialize_without_more initialize
37
+ def initialize(**kw)
38
+ initialize_without_more(**kw)
39
+ @browsers = CloudBrowsers.new(self)
40
+ @ai = CloudAi.new(self)
41
+ @jobs = CloudJobs.new(self)
42
+ @benchmarks = CloudBenchmarks.new(self)
43
+ @rl_alerts = CloudRlAlerts.new(self)
44
+ @audit = CloudAudit.new(self)
45
+ @api_keys = CloudApiKeys.new(self)
46
+ @webhooks = CloudWebhooks.new(self)
47
+ @recordings = CloudRecordings.new(self)
48
+ @burst = CloudBurst.new(self)
49
+ end
50
+
51
+ # Open a browser (cloud.browsers.create); with a block, it is closed
52
+ # when the block ends, error or not, and the block's value is returned.
53
+ def browser(ttl_s: nil, sandbox_id: nil, name: nil)
54
+ b = @browsers.create(ttl_s: ttl_s, sandbox_id: sandbox_id, name: name)
55
+ return b unless block_given?
56
+
57
+ begin
58
+ yield b
59
+ ensure
60
+ begin
61
+ b.close
62
+ rescue Error
63
+ nil # closing on the way out must not hide the real error
64
+ end
65
+ end
66
+ end
67
+
68
+ # Spend day by day this month, top sandboxes, credit left and the
69
+ # projected month-end spend.
70
+ def usage_insights
71
+ request("GET", "/v1/usage/insights")
72
+ end
73
+
74
+ # The rate card: prices per vCPU, GiB, storage, browsers and so on.
75
+ def pricing
76
+ request("GET", "/v1/pricing")
77
+ end
78
+
79
+ # The running-sandbox limit: "active", "max_running", "reached" and the
80
+ # last request for more.
81
+ def limits
82
+ request("GET", "/v1/limits")
83
+ end
84
+
85
+ # Ask kosa8 for a higher running-sandbox limit (once a day); kosa8
86
+ # answers the owner by email.
87
+ def request_limit(max_running, reason: nil)
88
+ body = { "max_running" => Integer(max_running) }
89
+ body["reason"] = reason.to_s unless reason.nil?
90
+ request("POST", "/v1/limits/request", body)
91
+ end
92
+
93
+ # Sandboxes with their fork parents ("nodes", "roots", "forked"), for
94
+ # drawing the fork tree.
95
+ def lineage
96
+ request("GET", "/v1/lineage")
97
+ end
98
+
99
+ # Checkpoints of every running or sleeping sandbox (up to 25), asked of
100
+ # each host; wakes nothing. One sandbox's own: box.checkpoints.
101
+ def checkpoints
102
+ request("GET", "/v1/checkpoints")
103
+ end
104
+
105
+ # The images behind the templates the org's hosts offer, with tag and
106
+ # digest ("images", "default_template").
107
+ def images
108
+ request("GET", "/v1/images")
109
+ end
110
+
111
+ # The org's default egress policy ("default", "enforce"), or nil when
112
+ # there is none (open internet).
113
+ def org_egress
114
+ r = request("GET", "/v1/org/egress")
115
+ r.is_a?(Hash) ? r["egress"] : nil
116
+ end
117
+
118
+ # Set the org's default egress policy (an admin key); nil clears it. With
119
+ # +enforce+ it is a ceiling sandboxes cannot widen. Pushed at once to the
120
+ # running and sleeping sandboxes it changes.
121
+ def set_org_egress(policy, enforce: nil)
122
+ body = { "default" => policy.nil? ? nil : Cloud.egress_body(policy) }
123
+ body["enforce"] = enforce == true if !policy.nil? && !enforce.nil?
124
+ request("PUT", "/v1/org/egress", body)
125
+ end
126
+
127
+ # The custom domains of a preview by its id ("{sandbox_id}:{port}", a
128
+ # preview's "id"); box.previews.domains(port) is the same.
129
+ def preview_domains(preview_id)
130
+ raise ArgumentError, "preview_domains needs a preview id" if preview_id.nil? || preview_id.to_s.empty?
131
+
132
+ CloudPreviewDomains.new(self, preview_id: preview_id.to_s)
133
+ end
134
+
135
+ # Two to four RL runs side by side: reward by step, failure classes, cost.
136
+ def rl_compare(*ids)
137
+ ids = ids.flatten.map(&:to_s)
138
+ raise ArgumentError, "rl_compare takes 2 to 4 run ids" unless ids.size.between?(2, 4)
139
+
140
+ request("GET", "/v1/rl/compare?#{URI.encode_www_form([['ids', ids.join(',')]])}")
141
+ end
142
+
143
+ # Agent attack scorecards the org uploaded (from `kosa8 attack run`),
144
+ # newest first.
145
+ def attack_scorecards(limit: nil)
146
+ r = request("GET", "/v1/attack/scorecards#{Cloud.query_string([['limit', limit]])}")
147
+ r.is_a?(Hash) ? (r["scorecards"] || []) : []
148
+ end
149
+
150
+ # One scorecard, with the signed file as uploaded.
151
+ def attack_scorecard(id)
152
+ request("GET", "/v1/attack/scorecards/#{Kosa8.enc(id)}")["scorecard"]
153
+ end
154
+
155
+ # Upload a signed scorecard (the file `kosa8 attack run` wrote, as a
156
+ # String or parsed); its signature is checked before it is stored.
157
+ def upload_attack_scorecard(signed)
158
+ if signed.is_a?(String)
159
+ begin
160
+ signed = JSON.parse(signed)
161
+ rescue JSON::ParserError
162
+ raise ArgumentError, "the signed scorecard is not JSON"
163
+ end
164
+ end
165
+ request("POST", "/v1/attack/scorecards", { "signed" => signed })["scorecard"]
166
+ end
167
+
168
+ def self.check_range(name, v, min, max)
169
+ return v if v.is_a?(Integer) && v.between?(min, max)
170
+
171
+ raise ArgumentError, "#{name} must be a whole number from #{min} to #{max}"
172
+ end
173
+
174
+ # "?k=v&..." for the pairs whose value is not nil, or "".
175
+ def self.query_string(pairs)
176
+ q = pairs.reject { |_, v| v.nil? }.map { |k, v| [k.to_s, v.to_s] }
177
+ q.empty? ? "" : "?#{URI.encode_www_form(q)}"
178
+ end
179
+ end
180
+
181
+ class CloudSandbox
182
+ # Signed, expiring iframe URLs for its terminal or desktop (a CloudEmbeds).
183
+ def embeds
184
+ CloudEmbeds.new(@cloud, self)
185
+ end
186
+
187
+ # Its desktop recordings (made when it is deleted, for a sandbox created
188
+ # with record: true).
189
+ def recordings
190
+ r = @cloud.request("GET", path("/recordings"))
191
+ r.is_a?(Hash) ? (r["recordings"] || []) : []
192
+ end
193
+ end
194
+
195
+ class CloudPreviews
196
+ # The custom domains of the preview on +port+ (a CloudPreviewDomains).
197
+ def domains(port)
198
+ CloudPreviewDomains.new(@cloud, sandbox_id: @sandbox.id, port: check(port))
199
+ end
200
+ end
201
+
202
+ class CloudFunctions
203
+ # Its recent calls, newest first (with logs for keys that may read its code).
204
+ def invocations(name, limit: nil)
205
+ q = limit.nil? ? "" : "?limit=#{Cloud.check_range('limit', limit, 1, 1000)}"
206
+ r = @cloud.request("GET", "/v1/functions/#{Kosa8.enc(name)}/invocations#{q}")
207
+ r.is_a?(Hash) ? (r["invocations"] || []) : []
208
+ end
209
+ end
210
+
211
+ # ---------------------------------------------------------------------------
212
+ # Browsers
213
+
214
+ # One cloud browser. +info+ is its state as of the last call; #cdp_url
215
+ # (valid 10 minutes) connects a CDP client (Playwright's
216
+ # connect_over_cdp, Ferrum, Puppeteer); #refresh gets a fresh one.
217
+ # $0.12 per browser-hour, billed per second.
218
+ class CloudBrowser
219
+ attr_reader :info
220
+
221
+ def initialize(cloud, info)
222
+ @cloud = cloud
223
+ @info = info.is_a?(Hash) ? info : {}
224
+ end
225
+
226
+ def id
227
+ @info["id"]
228
+ end
229
+
230
+ def state
231
+ @info["state"].to_s
232
+ end
233
+
234
+ # wss://.../v1/browsers/{id}/cdp?token=... while open; nil when closed or
235
+ # from a list (refresh it).
236
+ def cdp_url
237
+ @info["cdp_url"]
238
+ end
239
+
240
+ def cdp_url_expires_at
241
+ @info["cdp_url_expires_at"]
242
+ end
243
+
244
+ # Never the cdp_url (it carries a token).
245
+ def inspect
246
+ "#<Kosa8::CloudBrowser id=#{id.inspect} state=#{state.inspect}>"
247
+ end
248
+
249
+ # The path of its CDP WebSocket (GET /v1/browsers/{id}/cdp?token=...);
250
+ # #cdp_url is this with a token, ready to open.
251
+ def cdp_path
252
+ "/v1/browsers/#{Kosa8.enc(id)}/cdp"
253
+ end
254
+
255
+ # Read it again: its state and, while open, a fresh #cdp_url.
256
+ def refresh
257
+ @info = @cloud.request("GET", "/v1/browsers/#{Kosa8.enc(id)}")["browser"]
258
+ self
259
+ end
260
+
261
+ # Load +url+: "url", "title" and, if asked, "text" and
262
+ # "screenshot_png_base64".
263
+ def page(url, screenshot: nil, text: nil, full_page: nil)
264
+ raise ArgumentError, "page needs a url" if url.nil? || url.to_s.empty?
265
+
266
+ body = { "url" => url.to_s }
267
+ body["screenshot"] = screenshot == true unless screenshot.nil?
268
+ body["text"] = text == true unless text.nil?
269
+ body["full_page"] = full_page == true unless full_page.nil?
270
+ @cloud.request("POST", "/v1/browsers/#{Kosa8.enc(id)}/page", body)["page"]
271
+ end
272
+
273
+ # Load +url+; "url", "title" and (unless text: false) the page's "text".
274
+ def goto(url, text: true)
275
+ page(url, text: text)
276
+ end
277
+
278
+ # Load +url+ and return a PNG of it (a binary String): the viewport, or
279
+ # the whole page with full_page: true.
280
+ def screenshot(url, full_page: false)
281
+ p = page(url, screenshot: true, full_page: full_page ? true : nil)
282
+ b64 = p.is_a?(Hash) ? p["screenshot_png_base64"] : nil
283
+ if b64.nil? || b64.empty?
284
+ note = p.is_a?(Hash) && p["screenshot_note"].is_a?(String) ? ": #{p['screenshot_note']}" : ""
285
+ raise Error, "the API sent no screenshot#{note}"
286
+ end
287
+
288
+ b64.unpack1("m").b
289
+ end
290
+
291
+ # Close it; billing stops.
292
+ def close
293
+ r = @cloud.request("DELETE", "/v1/browsers/#{Kosa8.enc(id)}")
294
+ @info = @info.merge("state" => "closed", "cdp_url" => nil)
295
+ r
296
+ end
297
+ end
298
+
299
+ # cloud.browsers: headless Chromium on demand.
300
+ class CloudBrowsers
301
+ # USD per browser-hour, billed per second (the API's price_per_hour_usd is the live figure).
302
+ PRICE_PER_HOUR_USD = 0.12
303
+
304
+ def initialize(cloud)
305
+ @cloud = cloud
306
+ end
307
+
308
+ def inspect
309
+ "#<Kosa8::CloudBrowsers>"
310
+ end
311
+
312
+ # Open a browser. +ttl_s+ 30..3600 (default 300): it closes on its own
313
+ # after this. +sandbox_id+ ties it to a sandbox.
314
+ def create(ttl_s: nil, sandbox_id: nil, name: nil)
315
+ body = {}
316
+ body["ttl_s"] = Cloud.check_range("ttl_s", ttl_s, 30, 3600) unless ttl_s.nil?
317
+ body["sandbox_id"] = sandbox_id.to_s unless sandbox_id.nil?
318
+ body["name"] = name.to_s unless name.nil?
319
+ CloudBrowser.new(@cloud, @cloud.request("POST", "/v1/browsers", body)["browser"])
320
+ end
321
+
322
+ # The list answer as sent: "browsers" (no cdp_url), "enabled", "limit",
323
+ # "price_per_hour_usd". state: "open" (default) or "all".
324
+ def info(state: nil)
325
+ raise ArgumentError, 'state must be "open" or "all"' unless state.nil? || %w[open all].include?(state.to_s)
326
+
327
+ r = @cloud.request("GET", "/v1/browsers#{Cloud.query_string([['state', state]])}")
328
+ r.is_a?(Hash) ? r : {}
329
+ end
330
+
331
+ # Open browsers (state: "all" for closed ones too), as CloudBrowsers.
332
+ def list(state: nil)
333
+ (info(state: state)["browsers"] || []).map { |b| CloudBrowser.new(@cloud, b) }
334
+ end
335
+
336
+ # One browser, with a fresh cdp_url while open.
337
+ def get(id)
338
+ CloudBrowser.new(@cloud, @cloud.request("GET", "/v1/browsers/#{Kosa8.enc(id)}")["browser"])
339
+ end
340
+
341
+ # Close a browser by id.
342
+ def delete(id)
343
+ @cloud.request("DELETE", "/v1/browsers/#{Kosa8.enc(id)}")
344
+ end
345
+ end
346
+
347
+ # ---------------------------------------------------------------------------
348
+ # AI gateway
349
+
350
+ # cloud.ai: the org's AI gateway. Provider keys stay on kosa8 Cloud; a
351
+ # sandbox created with ai_gateway: true gets OPENAI_BASE_URL,
352
+ # ANTHROPIC_BASE_URL, KOSA8_AI_GATEWAY_URL and KOSA8_AI_TOKEN. Outside a
353
+ # sandbox, point a client at #gateway_url with the kosa8 API key as its key.
354
+ class CloudAi
355
+ PROVIDER = /\A[a-z0-9][a-z0-9-]{0,39}\z/.freeze
356
+
357
+ def initialize(cloud)
358
+ @cloud = cloud
359
+ end
360
+
361
+ def inspect
362
+ "#<Kosa8::CloudAi>"
363
+ end
364
+
365
+ # "settings" ("enabled", "all_sandboxes", "cache_ttl_s", "rate_per_min"),
366
+ # "available", "base_url", "providers", ...
367
+ def settings
368
+ @cloud.request("GET", "/v1/ai/settings")
369
+ end
370
+
371
+ # Change the given settings only.
372
+ def update_settings(enabled: nil, all_sandboxes: nil, cache_ttl_s: nil, rate_per_min: nil)
373
+ body = {}
374
+ body["enabled"] = enabled == true unless enabled.nil?
375
+ body["all_sandboxes"] = all_sandboxes == true unless all_sandboxes.nil?
376
+ body["cache_ttl_s"] = Integer(cache_ttl_s) unless cache_ttl_s.nil?
377
+ body["rate_per_min"] = Integer(rate_per_min) unless rate_per_min.nil?
378
+ raise ArgumentError, "give at least one setting to change" if body.empty?
379
+
380
+ @cloud.request("PATCH", "/v1/ai/settings", body)
381
+ end
382
+
383
+ # Store a provider's API key ("openai", "anthropic", ...). It is never sent back.
384
+ def set_key(provider, key)
385
+ raise ArgumentError, "provider and key are required" if key.nil? || key.to_s.empty?
386
+
387
+ @cloud.request("PUT", "/v1/ai/keys/#{check(provider)}", { "key" => key.to_s })
388
+ end
389
+
390
+ # Stored keys ("provider", "hint", ...: never the key).
391
+ def keys
392
+ r = @cloud.request("GET", "/v1/ai/keys")
393
+ r.is_a?(Hash) ? (r["keys"] || []) : []
394
+ end
395
+
396
+ def delete_key(provider)
397
+ @cloud.request("DELETE", "/v1/ai/keys/#{check(provider)}")
398
+ end
399
+
400
+ # A month's ("YYYY-MM", default this one) calls and cost: "total",
401
+ # "by_model", "by_sandbox", "recent".
402
+ def usage(month = nil)
403
+ unless month.nil? || /\A\d{4}-(0[1-9]|1[0-2])\z/.match?(month.to_s)
404
+ raise ArgumentError, "month must be YYYY-MM"
405
+ end
406
+
407
+ @cloud.request("GET", "/v1/ai/usage#{Cloud.query_string([['month', month]])}")
408
+ end
409
+
410
+ # The base URL for a provider's own SDK, through the gateway:
411
+ # "https://api.kosa8.com/v1/ai/gw/openai" (OpenAI's client appends
412
+ # /chat/completions, Anthropic's /v1/messages). Use the kosa8 API key
413
+ # as the client's API key.
414
+ def gateway_url(provider)
415
+ "#{@cloud.base_url}/v1/ai/gw/#{check(provider)}"
416
+ end
417
+
418
+ # One model call through the gateway, in the provider's own request
419
+ # shape: call("openai", "chat/completions", {"model" => ..., "messages" => [...]}).
420
+ # Not retried unless the gateway refused it first (429 ai_rate_limit).
421
+ def call(provider, api_path, body)
422
+ p = api_path.to_s.sub(%r{\A/+}, "")
423
+ raise ArgumentError, "api_path is the provider's API path, e.g. chat/completions" if p.empty? || p.include?("..")
424
+
425
+ @cloud.request("POST", "/v1/ai/gw/#{check(provider)}/#{p}", body.to_h)
426
+ end
427
+
428
+ private
429
+
430
+ def check(provider)
431
+ return provider.to_s if PROVIDER.match?(provider.to_s)
432
+
433
+ raise ArgumentError, "provider is a name such as openai or anthropic"
434
+ end
435
+ end
436
+
437
+ # ---------------------------------------------------------------------------
438
+ # Jobs
439
+
440
+ # cloud.jobs: hosted eval and RL jobs. kosa8 runs each task in its own
441
+ # sandbox (template:, image: or snapshot:), runs the solver then the sealed
442
+ # grader, records every rollout under the job's RL run and stops at
443
+ # +budget_usd+. A submit carries an Idempotency-Key (see Cloud#request).
444
+ class CloudJobs
445
+ DONE_STATES = %w[done failed cancelled budget_reached].freeze
446
+ MAX_TASKS = 10_000
447
+
448
+ def initialize(cloud)
449
+ @cloud = cloud
450
+ end
451
+
452
+ def inspect
453
+ "#<Kosa8::CloudJobs>"
454
+ end
455
+
456
+ # Whether a job (a Hash) has finished.
457
+ def self.done?(job)
458
+ DONE_STATES.include?(job.is_a?(Hash) ? job["status"].to_s : "")
459
+ end
460
+
461
+ # Submit a job; returns it (a Hash: "id", "run_id", "status", ...).
462
+ #
463
+ # name:, tasks: (an Array of {"id" =>, "input" =>, "files" => {path =>
464
+ # bytes}} or a JSONL String), solver: and grader: (a command, String or
465
+ # Array, or a Hash with "cmd", "timeout_s", "env" and for the grader
466
+ # "files"), exactly one of template:/image:/snapshot:, and
467
+ # solver_timeout_s: unless the solver Hash has one. Optional: project:,
468
+ # size:, grader_timeout_s:, grader_files:, concurrency:,
469
+ # retries_on_infra:, lease_s:, budget_usd:.
470
+ def submit(idempotency_key: nil, **opts)
471
+ Cloud.check_idempotency_key(idempotency_key)
472
+ job_of(@cloud.request("POST", "/v1/jobs", CloudJobs.body(**opts), idempotency_key: idempotency_key))
473
+ end
474
+
475
+ # What a job would cost (sandbox hours, USD low/high), without running it;
476
+ # sample: n runs n tasks first to measure, or sample_job_id: uses a job's.
477
+ def estimate(sample: nil, sample_job_id: nil, **opts)
478
+ raise ArgumentError, "give sample or sample_job_id, not both" if !sample.nil? && !sample_job_id.nil?
479
+
480
+ body = CloudJobs.body(**opts)
481
+ body["sample"] = Integer(sample) unless sample.nil?
482
+ body["sample_job_id"] = sample_job_id.to_s unless sample_job_id.nil?
483
+ @cloud.request("POST", "/v1/jobs/estimate", body) || {}
484
+ end
485
+
486
+ def get(id)
487
+ job_of(@cloud.request("GET", "/v1/jobs/#{Kosa8.enc(id)}"))
488
+ end
489
+
490
+ def list(status: nil, project: nil, limit: nil, cursor: nil)
491
+ q = Cloud.query_string([["status", status], ["project", project], ["limit", limit], ["cursor", cursor]])
492
+ r = @cloud.request("GET", "/v1/jobs#{q}")
493
+ r.is_a?(Hash) ? (r["jobs"] || []) : []
494
+ end
495
+
496
+ # Stop it: no new tasks start, running ones are stopped.
497
+ def cancel(id)
498
+ job_of(@cloud.request("POST", "/v1/jobs/#{Kosa8.enc(id)}/cancel", {}))
499
+ end
500
+
501
+ # Poll until it is done; the block (if given) gets each poll's job.
502
+ def wait(id, timeout: nil, poll_interval: 5)
503
+ deadline = timeout.nil? ? nil : Time.now + timeout
504
+ loop do
505
+ job = get(id)
506
+ yield job if block_given?
507
+ return job if CloudJobs.done?(job)
508
+ if deadline && Time.now + poll_interval > deadline
509
+ raise TimeoutError, "job #{id} not finished after #{timeout} s (status #{job['status']})"
510
+ end
511
+
512
+ @cloud.sleeper.call(poll_interval)
513
+ end
514
+ end
515
+
516
+ # The body of POST /v1/jobs (ArgumentError on a bad option).
517
+ def self.body(name:, tasks:, solver:, grader:, template: nil, image: nil, snapshot: nil, size: nil, project: nil,
518
+ solver_timeout_s: nil, grader_timeout_s: nil, grader_files: nil, concurrency: nil,
519
+ retries_on_infra: nil, lease_s: nil, budget_usd: nil)
520
+ raise ArgumentError, "a job needs a name" if name.to_s.empty?
521
+ if [template, image, snapshot].compact.size != 1
522
+ raise ArgumentError, "give exactly one of template:, image: or snapshot:"
523
+ end
524
+
525
+ s = cmd_spec(solver, "solver", false)
526
+ s["timeout_s"] = solver_timeout_s unless solver_timeout_s.nil?
527
+ if s["timeout_s"].nil?
528
+ raise ArgumentError, "solver needs timeout_s (seconds; a solver past it is recorded as timeout)"
529
+ end
530
+
531
+ g = cmd_spec(grader, "grader", true)
532
+ g["timeout_s"] = grader_timeout_s unless grader_timeout_s.nil?
533
+ g["files"] = (g["files"] || {}).merge(encode_files(grader_files)) if grader_files && !grader_files.empty?
534
+ body = { "name" => name.to_s, "tasks" => load_tasks(tasks), "solver" => s, "grader" => g }
535
+ { "project" => project, "template" => template, "image" => image, "snapshot" => snapshot, "size" => size,
536
+ "concurrency" => concurrency, "retries_on_infra" => retries_on_infra, "lease_s" => lease_s,
537
+ "budget_usd" => budget_usd }.each { |k, v| body[k] = v unless v.nil? }
538
+ body
539
+ end
540
+
541
+ # {path => base64} for {absolute path => bytes}.
542
+ def self.encode_files(files)
543
+ files.to_h.map do |p, v|
544
+ raise ArgumentError, "file paths are absolute (in the sandbox), got #{p.to_s.inspect}" unless p.to_s.start_with?("/")
545
+
546
+ [p.to_s, [v.to_s].pack("m0")]
547
+ end.to_h
548
+ end
549
+
550
+ def self.load_tasks(tasks)
551
+ text = tasks.is_a?(String)
552
+ rows = if text
553
+ tasks.each_line.with_index.map do |line, i|
554
+ t = line.strip
555
+ next nil if t.empty?
556
+
557
+ begin
558
+ JSON.parse(t)
559
+ rescue JSON::ParserError => e
560
+ raise ArgumentError, "tasks line #{i + 1}: not JSON: #{e.message}"
561
+ end
562
+ end.compact
563
+ else
564
+ tasks.to_a
565
+ end
566
+ raise ArgumentError, "a job has 1 to #{MAX_TASKS} tasks, got #{rows.size}" unless rows.size.between?(1, MAX_TASKS)
567
+
568
+ seen = {}
569
+ rows.each_with_index.map do |t, i|
570
+ raise ArgumentError, "tasks[#{i}] must be a Hash with an id" unless t.is_a?(Hash)
571
+
572
+ t = t.map { |k, v| [k.to_s, v] }.to_h
573
+ id = t["id"].is_a?(Integer) ? t["id"].to_s : t["id"]
574
+ raise ArgumentError, "tasks[#{i}] needs an id (a String)" unless id.is_a?(String) && !id.empty?
575
+ raise ArgumentError, "task id #{id.inspect} appears twice" if seen[id]
576
+
577
+ seen[id] = true
578
+ row = { "id" => id }
579
+ row["input"] = t["input"] unless t["input"].nil?
580
+ if t["files"].is_a?(Hash) && !t["files"].empty?
581
+ # Already base64 in JSONL: kept as is.
582
+ row["files"] = text ? t["files"] : encode_files(t["files"])
583
+ end
584
+ row
585
+ end
586
+ end
587
+
588
+ def self.cmd_spec(spec, what, files)
589
+ s = spec.is_a?(String) || spec.is_a?(Array) ? { "cmd" => spec } : spec.to_h.map { |k, v| [k.to_s, v] }.to_h
590
+ cmd = s["cmd"]
591
+ if cmd.nil? || (cmd.respond_to?(:empty?) && cmd.empty?)
592
+ raise ArgumentError, "#{what} needs cmd (a String run with sh -c, or an Array of arguments)"
593
+ end
594
+
595
+ extra = s.keys - ["cmd", "timeout_s", "env"] - (files ? ["files"] : [])
596
+ raise ArgumentError, "#{what}: unknown fields #{extra.sort.join(', ')}" unless extra.empty?
597
+
598
+ out = { "cmd" => cmd.is_a?(String) ? cmd : cmd.to_a.map(&:to_s) }
599
+ out["timeout_s"] = s["timeout_s"] unless s["timeout_s"].nil?
600
+ out["env"] = s["env"].to_h.map { |k, v| [k.to_s, v.to_s] }.to_h if s["env"] && !s["env"].empty?
601
+ out["files"] = encode_files(s["files"]) if files && s["files"] && !s["files"].empty?
602
+ out
603
+ end
604
+
605
+ private
606
+
607
+ def job_of(answer)
608
+ return {} unless answer.is_a?(Hash)
609
+
610
+ job = answer["job"].is_a?(Hash) ? answer["job"].dup : {}
611
+ job["id"] ||= answer["job_id"] if answer["job_id"]
612
+ job["run_id"] ||= answer["run_id"] if answer["run_id"]
613
+ job
614
+ end
615
+ end
616
+
617
+ # ---------------------------------------------------------------------------
618
+ # Benchmarks
619
+
620
+ # cloud.benchmarks: ready-made benchmarks (SWE-bench and the like). Create a
621
+ # sandbox from an instance with template: "<benchmark>/<instance id>"; one
622
+ # whose environment is still being built answers 409 template_building,
623
+ # which the SDK waits out (Retry-After) within its retry policy.
624
+ class CloudBenchmarks
625
+ def initialize(cloud)
626
+ @cloud = cloud
627
+ end
628
+
629
+ def inspect
630
+ "#<Kosa8::CloudBenchmarks>"
631
+ end
632
+
633
+ def list
634
+ r = @cloud.request("GET", "/v1/benchmarks")
635
+ r.is_a?(Hash) ? (r["benchmarks"] || []) : []
636
+ end
637
+
638
+ def get(name)
639
+ @cloud.request("GET", "/v1/benchmarks/#{Kosa8.enc(name)}")["benchmark"]
640
+ end
641
+
642
+ # One page of its instances: {"instances" => [...], "next_cursor" => ...}.
643
+ # state: ready, building, queued, failed or not_built; limit: 1..1000.
644
+ def instances(name, state: nil, limit: nil, cursor: nil)
645
+ Cloud.check_range("limit", limit, 1, 1000) unless limit.nil?
646
+ q = Cloud.query_string([["state", state], ["limit", limit], ["cursor", cursor]])
647
+ @cloud.request("GET", "/v1/benchmarks/#{Kosa8.enc(name)}/instances#{q}")
648
+ end
649
+
650
+ # One instance: the solver's input and its environment's state and ETA.
651
+ def instance(name, id)
652
+ @cloud.request("GET", "/v1/benchmarks/#{Kosa8.enc(name)}/instances/#{Kosa8.enc(id)}")["instance"]
653
+ end
654
+
655
+ # Build environments ahead of use (at most 100 a call): +instances+ is
656
+ # an Array of instance ids (or what the API takes for a sample, with seed:).
657
+ def prepare(name, instances, seed: nil)
658
+ body = { "instances" => instances }
659
+ body["seed"] = Integer(seed) unless seed.nil?
660
+ @cloud.request("POST", "/v1/benchmarks/#{Kosa8.enc(name)}/prepare", body)
661
+ end
662
+ end
663
+
664
+ # ---------------------------------------------------------------------------
665
+ # RL alerts
666
+
667
+ # cloud.rl_alerts: alert rules on RL runs (reward drop, infra failure
668
+ # rate, ...); list answers the kinds too.
669
+ class CloudRlAlerts
670
+ def initialize(cloud)
671
+ @cloud = cloud
672
+ end
673
+
674
+ def inspect
675
+ "#<Kosa8::CloudRlAlerts>"
676
+ end
677
+
678
+ # {"alerts" => [...], "kinds" => {...}}; run_id: one run's rules.
679
+ def list(run_id: nil)
680
+ @cloud.request("GET", "/v1/rl/alerts#{Cloud.query_string([['run_id', run_id]])}")
681
+ end
682
+
683
+ def create(kind:, threshold:, run_id: nil, window: nil)
684
+ body = { "kind" => kind.to_s, "threshold" => threshold }
685
+ body["run_id"] = run_id.to_s unless run_id.nil?
686
+ body["window"] = window unless window.nil?
687
+ @cloud.request("POST", "/v1/rl/alerts", body)["alert"]
688
+ end
689
+
690
+ # Change, pause (enabled: false) or resume a rule.
691
+ def update(id, threshold: nil, window: nil, enabled: nil)
692
+ body = {}
693
+ body["threshold"] = threshold unless threshold.nil?
694
+ body["window"] = window unless window.nil?
695
+ body["enabled"] = enabled == true unless enabled.nil?
696
+ raise ArgumentError, "give threshold:, window: or enabled:" if body.empty?
697
+
698
+ @cloud.request("PATCH", "/v1/rl/alerts/#{Kosa8.enc(id)}", body)["alert"]
699
+ end
700
+
701
+ def delete(id)
702
+ @cloud.request("DELETE", "/v1/rl/alerts/#{Kosa8.enc(id)}")
703
+ end
704
+ end
705
+
706
+ # ---------------------------------------------------------------------------
707
+ # Audit
708
+
709
+ # cloud.audit: the org's tamper-evident audit log.
710
+ class CloudAudit
711
+ def initialize(cloud)
712
+ @cloud = cloud
713
+ end
714
+
715
+ def inspect
716
+ "#<Kosa8::CloudAudit>"
717
+ end
718
+
719
+ # One page, newest first: {"events" => [...], "next_before_seq" => n}.
720
+ def list(sandbox_id: nil, actor: nil, action: nil, since: nil, until_ms: nil, before_seq: nil, limit: nil)
721
+ q = Cloud.query_string([["sandbox_id", sandbox_id], ["actor", actor], ["action", action], ["since", since],
722
+ ["until", until_ms], ["before_seq", before_seq], ["limit", limit]])
723
+ @cloud.request("GET", "/v1/audit#{q}")
724
+ end
725
+
726
+ # Every event matching, walking next_before_seq. Without a block, an Enumerator.
727
+ def each(**filters)
728
+ return enum_for(:each, **filters) unless block_given?
729
+
730
+ before = nil
731
+ loop do
732
+ page = list(**filters, before_seq: before)
733
+ (page["events"] || []).each { |e| yield e }
734
+ nxt = page["next_before_seq"]
735
+ break if nxt.nil? || nxt == before
736
+
737
+ before = nxt
738
+ end
739
+ self
740
+ end
741
+
742
+ # Recompute the org's hash chain: "ok", "checked", "verified_at", ...
743
+ def verify
744
+ @cloud.request("GET", "/v1/audit/verify")
745
+ end
746
+
747
+ # Every event, oldest first, with its hashes (parsed from NDJSON).
748
+ def export
749
+ text = @cloud.request_bytes("GET", "/v1/audit/export", raw: true).force_encoding(Encoding::UTF_8)
750
+ text.each_line.map(&:strip).reject(&:empty?).map { |l| JSON.parse(l) }
751
+ end
752
+ end
753
+
754
+ # ---------------------------------------------------------------------------
755
+ # API keys
756
+
757
+ # cloud.api_keys: the org's API keys (a key with keys:manage). Secrets are
758
+ # shown once, in the answer that made them.
759
+ class CloudApiKeys
760
+ def initialize(cloud)
761
+ @cloud = cloud
762
+ end
763
+
764
+ def inspect
765
+ "#<Kosa8::CloudApiKeys>"
766
+ end
767
+
768
+ def list
769
+ r = @cloud.request("GET", "/v1/api-keys")
770
+ r.is_a?(Hash) ? (r["api_keys"] || []) : []
771
+ end
772
+
773
+ # A new key ("secret" only here). scopes: nil for a full key.
774
+ def create(name:, scopes: nil, expires_in_s: nil)
775
+ body = { "name" => name.to_s }
776
+ body["scopes"] = scopes.to_a.map(&:to_s) unless scopes.nil?
777
+ body["expires_in_s"] = Integer(expires_in_s) unless expires_in_s.nil?
778
+ @cloud.request("POST", "/v1/api-keys", body)["api_key"]
779
+ end
780
+
781
+ # Revoke a key; it stops at once.
782
+ def revoke(id)
783
+ @cloud.request("DELETE", "/v1/api-keys/#{Kosa8.enc(id)}")
784
+ end
785
+ alias delete revoke
786
+
787
+ # A new key with the same name and scopes; the old one works grace_s more.
788
+ def rotate(id, grace_s: nil)
789
+ body = {}
790
+ body["grace_s"] = Integer(grace_s) unless grace_s.nil?
791
+ @cloud.request("POST", "/v1/api-keys/#{Kosa8.enc(id)}/rotate", body)["api_key"]
792
+ end
793
+ end
794
+
795
+ # ---------------------------------------------------------------------------
796
+ # Webhooks
797
+
798
+ # cloud.webhooks: endpoints kosa8 Cloud POSTs events to, signed with the
799
+ # endpoint's whsec_ secret (shown once, on create).
800
+ class CloudWebhooks
801
+ def initialize(cloud)
802
+ @cloud = cloud
803
+ end
804
+
805
+ def inspect
806
+ "#<Kosa8::CloudWebhooks>"
807
+ end
808
+
809
+ # {"webhooks" => [...], "events" => [the event names]}.
810
+ def info
811
+ r = @cloud.request("GET", "/v1/webhooks")
812
+ r.is_a?(Hash) ? r : {}
813
+ end
814
+
815
+ def list
816
+ info["webhooks"] || []
817
+ end
818
+
819
+ def create(url:, events: nil, description: nil)
820
+ body = { "url" => url.to_s }
821
+ body["events"] = events.to_a.map(&:to_s) unless events.nil?
822
+ body["description"] = description.to_s unless description.nil?
823
+ @cloud.request("POST", "/v1/webhooks", body)["webhook"]
824
+ end
825
+
826
+ # Stop sending, including retries.
827
+ def delete(id)
828
+ @cloud.request("DELETE", "/v1/webhooks/#{Kosa8.enc(id)}")
829
+ end
830
+
831
+ def deliveries(id, limit: nil)
832
+ r = @cloud.request("GET", "/v1/webhooks/#{Kosa8.enc(id)}/deliveries#{Cloud.query_string([['limit', limit]])}")
833
+ r.is_a?(Hash) ? (r["deliveries"] || []) : []
834
+ end
835
+
836
+ # Send a webhook.test event now; returns the delivery.
837
+ def test(id)
838
+ @cloud.request("POST", "/v1/webhooks/#{Kosa8.enc(id)}/test", {})["delivery"]
839
+ end
840
+ end
841
+
842
+ # ---------------------------------------------------------------------------
843
+ # Recordings, embeds, preview domains, Burst Passes
844
+
845
+ # cloud.recordings: desktop recordings (MP4), made when a sandbox created
846
+ # with record: true is deleted.
847
+ class CloudRecordings
848
+ def initialize(cloud)
849
+ @cloud = cloud
850
+ end
851
+
852
+ def inspect
853
+ "#<Kosa8::CloudRecordings>"
854
+ end
855
+
856
+ # Newest first: {"recordings" => [...], "configured" => bool,
857
+ # "retention_days" => n}. sandbox_id: one sandbox's; limit: 1..200.
858
+ def info(sandbox_id: nil, limit: nil)
859
+ Cloud.check_range("limit", limit, 1, 200) unless limit.nil?
860
+ r = @cloud.request("GET", "/v1/recordings#{Cloud.query_string([['sandbox_id', sandbox_id], ['limit', limit]])}")
861
+ r.is_a?(Hash) ? r : {}
862
+ end
863
+
864
+ def list(sandbox_id: nil, limit: nil)
865
+ info(sandbox_id: sandbox_id, limit: limit)["recordings"] || []
866
+ end
867
+
868
+ # A signed download URL for its MP4 ("url", "expires_at", "bytes");
869
+ # ttl_s 60..86400 (default 900).
870
+ def link(id, ttl_s: nil)
871
+ body = {}
872
+ body["ttl_s"] = Cloud.check_range("ttl_s", ttl_s, 60, 86_400) unless ttl_s.nil?
873
+ @cloud.request("POST", "/v1/recordings/#{Kosa8.enc(id)}/link", body)["link"]
874
+ end
875
+
876
+ def delete(id)
877
+ @cloud.request("DELETE", "/v1/recordings/#{Kosa8.enc(id)}")
878
+ nil
879
+ end
880
+ end
881
+
882
+ # sandbox.embeds: signed, expiring iframe URLs for its terminal or desktop.
883
+ # The framed page posts {source: "kosa8", type} messages to the listed
884
+ # origins: ready, exited, approval_requested, expired.
885
+ class CloudEmbeds
886
+ def initialize(cloud, sandbox)
887
+ @cloud = cloud
888
+ @sandbox = sandbox
889
+ end
890
+
891
+ def inspect
892
+ "#<Kosa8::CloudEmbeds sandbox=#{@sandbox.id.inspect}>"
893
+ end
894
+
895
+ # origins: 1..10 (e.g. https://app.example.com); mode: "view" (default)
896
+ # or "interact"; ui: "terminal" (default) or "desktop"; ttl_s 60..604800.
897
+ # The answer's "url" is the credential: give it only to pages you trust.
898
+ def create(origins:, mode: nil, ui: nil, ttl_s: nil, command: nil)
899
+ list = origins.to_a.map(&:to_s)
900
+ raise ArgumentError, "an embed takes 1 to 10 origins" unless list.size.between?(1, 10)
901
+
902
+ body = { "origins" => list }
903
+ body["mode"] = mode.to_s unless mode.nil?
904
+ body["ui"] = ui.to_s unless ui.nil?
905
+ body["ttl_s"] = Cloud.check_range("ttl_s", ttl_s, 60, 604_800) unless ttl_s.nil?
906
+ body["command"] = command.to_a.map(&:to_s) unless command.nil?
907
+ @cloud.request("POST", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/embed", body)["embed"]
908
+ end
909
+
910
+ # Its live embeds (no URLs).
911
+ def list
912
+ r = @cloud.request("GET", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/embeds")
913
+ r.is_a?(Hash) ? (r["embeds"] || []) : []
914
+ end
915
+
916
+ # End an embed's URL before it expires.
917
+ def revoke(embed_id)
918
+ raise ArgumentError, "revoke needs an embed id (emb_...)" if embed_id.nil? || embed_id.to_s.empty?
919
+
920
+ @cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/embeds/#{Kosa8.enc(embed_id)}")
921
+ nil
922
+ end
923
+ end
924
+
925
+ # A preview's custom domains (at most 5 a preview). The domain serves the
926
+ # preview as it is and follows it across a rotate. 501 not_available
927
+ # where custom hostnames are not configured.
928
+ class CloudPreviewDomains
929
+ # Give preview_id: (cloud.preview_domains), or sandbox_id: and port:
930
+ # (box.previews.domains(port)).
931
+ def initialize(cloud, preview_id: nil, sandbox_id: nil, port: nil)
932
+ @cloud = cloud
933
+ @preview_id = preview_id
934
+ @sandbox_id = sandbox_id
935
+ @port = port
936
+ end
937
+
938
+ def inspect
939
+ "#<Kosa8::CloudPreviewDomains #{collection}>"
940
+ end
941
+
942
+ # {"domains" => [...], "configured" => bool, "cname_target" => host}.
943
+ def info
944
+ r = @cloud.request("GET", collection)
945
+ r.is_a?(Hash) ? r : {}
946
+ end
947
+
948
+ def list
949
+ info["domains"] || []
950
+ end
951
+
952
+ # Serve the preview at +hostname+; make the "records" it answers at your
953
+ # DNS provider. ssl_method: "http" or "txt".
954
+ def add(hostname, ssl_method: nil)
955
+ body = { "hostname" => hostname.to_s }
956
+ body["ssl_method"] = ssl_method.to_s unless ssl_method.nil?
957
+ @cloud.request("POST", collection, body)["domain"]
958
+ end
959
+
960
+ # Its status, asked of the certificate provider again.
961
+ def get(hostname)
962
+ @cloud.request("GET", item(hostname))["domain"]
963
+ end
964
+
965
+ def remove(hostname)
966
+ @cloud.request("DELETE", item(hostname))
967
+ nil
968
+ end
969
+
970
+ private
971
+
972
+ # "/v1/sandboxes/{id}/previews/{port}/domains" or "/v1/previews/{preview_id}/domains".
973
+ def collection
974
+ return "/v1/previews/#{Kosa8.enc(@preview_id)}/domains" if @preview_id
975
+
976
+ "/v1/sandboxes/#{Kosa8.enc(@sandbox_id)}/previews/#{@port}/domains"
977
+ end
978
+
979
+ def item(hostname)
980
+ raise ArgumentError, "a hostname is required" if hostname.nil? || hostname.to_s.empty?
981
+
982
+ h = Kosa8.enc(hostname)
983
+ return "/v1/previews/#{Kosa8.enc(@preview_id)}/domains/#{h}" if @preview_id
984
+
985
+ "/v1/sandboxes/#{Kosa8.enc(@sandbox_id)}/previews/#{@port}/domains/#{h}"
986
+ end
987
+ end
988
+
989
+ # cloud.burst: Burst Passes, each raising the running limit for its hours.
990
+ class CloudBurst
991
+ def initialize(cloud)
992
+ @cloud = cloud
993
+ end
994
+
995
+ def inspect
996
+ "#<Kosa8::CloudBurst>"
997
+ end
998
+
999
+ # "available", "pass", "held", "active", "adds_now".
1000
+ def get
1001
+ @cloud.request("GET", "/v1/billing/burst")
1002
+ end
1003
+
1004
+ # Activate +quantity+ passes (an owner's admin key). Holding fewer, the
1005
+ # answer is a checkout "url" for the rest.
1006
+ def activate(quantity = 1)
1007
+ raise ArgumentError, "quantity must be a whole number of at least 1" unless quantity.is_a?(Integer) && quantity >= 1
1008
+
1009
+ @cloud.request("POST", "/v1/billing/burst", { "quantity" => quantity })
1010
+ end
1011
+ end
1012
+ end