kosa8 0.5.3 → 0.6.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/README.md +71 -14
- data/lib/kosa8/cloud.rb +35 -11
- data/lib/kosa8/cloud_features.rb +45 -13
- data/lib/kosa8/cloud_more.rb +1009 -0
- data/lib/kosa8/errors.rb +7 -1
- data/lib/kosa8/version.rb +1 -1
- data/lib/kosa8.rb +1 -0
- metadata +2 -1
|
@@ -0,0 +1,1009 @@
|
|
|
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
|
+
raise Error, "the API sent no screenshot" if b64.nil? || b64.empty?
|
|
284
|
+
|
|
285
|
+
b64.unpack1("m").b
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
# Close it; billing stops.
|
|
289
|
+
def close
|
|
290
|
+
r = @cloud.request("DELETE", "/v1/browsers/#{Kosa8.enc(id)}")
|
|
291
|
+
@info = @info.merge("state" => "closed", "cdp_url" => nil)
|
|
292
|
+
r
|
|
293
|
+
end
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
# cloud.browsers: headless Chromium on demand.
|
|
297
|
+
class CloudBrowsers
|
|
298
|
+
# USD per browser-hour, billed per second (the API's price_per_hour_usd is the live figure).
|
|
299
|
+
PRICE_PER_HOUR_USD = 0.12
|
|
300
|
+
|
|
301
|
+
def initialize(cloud)
|
|
302
|
+
@cloud = cloud
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def inspect
|
|
306
|
+
"#<Kosa8::CloudBrowsers>"
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
# Open a browser. +ttl_s+ 30..3600 (default 300): it closes on its own
|
|
310
|
+
# after this. +sandbox_id+ ties it to a sandbox.
|
|
311
|
+
def create(ttl_s: nil, sandbox_id: nil, name: nil)
|
|
312
|
+
body = {}
|
|
313
|
+
body["ttl_s"] = Cloud.check_range("ttl_s", ttl_s, 30, 3600) unless ttl_s.nil?
|
|
314
|
+
body["sandbox_id"] = sandbox_id.to_s unless sandbox_id.nil?
|
|
315
|
+
body["name"] = name.to_s unless name.nil?
|
|
316
|
+
CloudBrowser.new(@cloud, @cloud.request("POST", "/v1/browsers", body)["browser"])
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
# The list answer as sent: "browsers" (no cdp_url), "enabled", "limit",
|
|
320
|
+
# "price_per_hour_usd". state: "open" (default) or "all".
|
|
321
|
+
def info(state: nil)
|
|
322
|
+
raise ArgumentError, 'state must be "open" or "all"' unless state.nil? || %w[open all].include?(state.to_s)
|
|
323
|
+
|
|
324
|
+
r = @cloud.request("GET", "/v1/browsers#{Cloud.query_string([['state', state]])}")
|
|
325
|
+
r.is_a?(Hash) ? r : {}
|
|
326
|
+
end
|
|
327
|
+
|
|
328
|
+
# Open browsers (state: "all" for closed ones too), as CloudBrowsers.
|
|
329
|
+
def list(state: nil)
|
|
330
|
+
(info(state: state)["browsers"] || []).map { |b| CloudBrowser.new(@cloud, b) }
|
|
331
|
+
end
|
|
332
|
+
|
|
333
|
+
# One browser, with a fresh cdp_url while open.
|
|
334
|
+
def get(id)
|
|
335
|
+
CloudBrowser.new(@cloud, @cloud.request("GET", "/v1/browsers/#{Kosa8.enc(id)}")["browser"])
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
# Close a browser by id.
|
|
339
|
+
def delete(id)
|
|
340
|
+
@cloud.request("DELETE", "/v1/browsers/#{Kosa8.enc(id)}")
|
|
341
|
+
end
|
|
342
|
+
end
|
|
343
|
+
|
|
344
|
+
# ---------------------------------------------------------------------------
|
|
345
|
+
# AI gateway
|
|
346
|
+
|
|
347
|
+
# cloud.ai: the org's AI gateway. Provider keys stay on kosa8 Cloud; a
|
|
348
|
+
# sandbox created with ai_gateway: true gets OPENAI_BASE_URL,
|
|
349
|
+
# ANTHROPIC_BASE_URL, KOSA8_AI_GATEWAY_URL and KOSA8_AI_TOKEN. Outside a
|
|
350
|
+
# sandbox, point a client at #gateway_url with the kosa8 API key as its key.
|
|
351
|
+
class CloudAi
|
|
352
|
+
PROVIDER = /\A[a-z0-9][a-z0-9-]{0,39}\z/.freeze
|
|
353
|
+
|
|
354
|
+
def initialize(cloud)
|
|
355
|
+
@cloud = cloud
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
def inspect
|
|
359
|
+
"#<Kosa8::CloudAi>"
|
|
360
|
+
end
|
|
361
|
+
|
|
362
|
+
# "settings" ("enabled", "all_sandboxes", "cache_ttl_s", "rate_per_min"),
|
|
363
|
+
# "available", "base_url", "providers", ...
|
|
364
|
+
def settings
|
|
365
|
+
@cloud.request("GET", "/v1/ai/settings")
|
|
366
|
+
end
|
|
367
|
+
|
|
368
|
+
# Change the given settings only.
|
|
369
|
+
def update_settings(enabled: nil, all_sandboxes: nil, cache_ttl_s: nil, rate_per_min: nil)
|
|
370
|
+
body = {}
|
|
371
|
+
body["enabled"] = enabled == true unless enabled.nil?
|
|
372
|
+
body["all_sandboxes"] = all_sandboxes == true unless all_sandboxes.nil?
|
|
373
|
+
body["cache_ttl_s"] = Integer(cache_ttl_s) unless cache_ttl_s.nil?
|
|
374
|
+
body["rate_per_min"] = Integer(rate_per_min) unless rate_per_min.nil?
|
|
375
|
+
raise ArgumentError, "give at least one setting to change" if body.empty?
|
|
376
|
+
|
|
377
|
+
@cloud.request("PATCH", "/v1/ai/settings", body)
|
|
378
|
+
end
|
|
379
|
+
|
|
380
|
+
# Store a provider's API key ("openai", "anthropic", ...). It is never sent back.
|
|
381
|
+
def set_key(provider, key)
|
|
382
|
+
raise ArgumentError, "provider and key are required" if key.nil? || key.to_s.empty?
|
|
383
|
+
|
|
384
|
+
@cloud.request("PUT", "/v1/ai/keys/#{check(provider)}", { "key" => key.to_s })
|
|
385
|
+
end
|
|
386
|
+
|
|
387
|
+
# Stored keys ("provider", "hint", ...: never the key).
|
|
388
|
+
def keys
|
|
389
|
+
r = @cloud.request("GET", "/v1/ai/keys")
|
|
390
|
+
r.is_a?(Hash) ? (r["keys"] || []) : []
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
def delete_key(provider)
|
|
394
|
+
@cloud.request("DELETE", "/v1/ai/keys/#{check(provider)}")
|
|
395
|
+
end
|
|
396
|
+
|
|
397
|
+
# A month's ("YYYY-MM", default this one) calls and cost: "total",
|
|
398
|
+
# "by_model", "by_sandbox", "recent".
|
|
399
|
+
def usage(month = nil)
|
|
400
|
+
unless month.nil? || /\A\d{4}-(0[1-9]|1[0-2])\z/.match?(month.to_s)
|
|
401
|
+
raise ArgumentError, "month must be YYYY-MM"
|
|
402
|
+
end
|
|
403
|
+
|
|
404
|
+
@cloud.request("GET", "/v1/ai/usage#{Cloud.query_string([['month', month]])}")
|
|
405
|
+
end
|
|
406
|
+
|
|
407
|
+
# The base URL for a provider's own SDK, through the gateway:
|
|
408
|
+
# "https://api.kosa8.com/v1/ai/gw/openai" (OpenAI's client appends
|
|
409
|
+
# /chat/completions, Anthropic's /v1/messages). Use the kosa8 API key
|
|
410
|
+
# as the client's API key.
|
|
411
|
+
def gateway_url(provider)
|
|
412
|
+
"#{@cloud.base_url}/v1/ai/gw/#{check(provider)}"
|
|
413
|
+
end
|
|
414
|
+
|
|
415
|
+
# One model call through the gateway, in the provider's own request
|
|
416
|
+
# shape: call("openai", "chat/completions", {"model" => ..., "messages" => [...]}).
|
|
417
|
+
# Not retried unless the gateway refused it first (429 ai_rate_limit).
|
|
418
|
+
def call(provider, api_path, body)
|
|
419
|
+
p = api_path.to_s.sub(%r{\A/+}, "")
|
|
420
|
+
raise ArgumentError, "api_path is the provider's API path, e.g. chat/completions" if p.empty? || p.include?("..")
|
|
421
|
+
|
|
422
|
+
@cloud.request("POST", "/v1/ai/gw/#{check(provider)}/#{p}", body.to_h)
|
|
423
|
+
end
|
|
424
|
+
|
|
425
|
+
private
|
|
426
|
+
|
|
427
|
+
def check(provider)
|
|
428
|
+
return provider.to_s if PROVIDER.match?(provider.to_s)
|
|
429
|
+
|
|
430
|
+
raise ArgumentError, "provider is a name such as openai or anthropic"
|
|
431
|
+
end
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
# ---------------------------------------------------------------------------
|
|
435
|
+
# Jobs
|
|
436
|
+
|
|
437
|
+
# cloud.jobs: hosted eval and RL jobs. kosa8 runs each task in its own
|
|
438
|
+
# sandbox (template:, image: or snapshot:), runs the solver then the sealed
|
|
439
|
+
# grader, records every rollout under the job's RL run and stops at
|
|
440
|
+
# +budget_usd+. A submit carries an Idempotency-Key reused on every retry.
|
|
441
|
+
class CloudJobs
|
|
442
|
+
DONE_STATES = %w[done failed cancelled budget_reached].freeze
|
|
443
|
+
MAX_TASKS = 10_000
|
|
444
|
+
|
|
445
|
+
def initialize(cloud)
|
|
446
|
+
@cloud = cloud
|
|
447
|
+
end
|
|
448
|
+
|
|
449
|
+
def inspect
|
|
450
|
+
"#<Kosa8::CloudJobs>"
|
|
451
|
+
end
|
|
452
|
+
|
|
453
|
+
# Whether a job (a Hash) has finished.
|
|
454
|
+
def self.done?(job)
|
|
455
|
+
DONE_STATES.include?(job.is_a?(Hash) ? job["status"].to_s : "")
|
|
456
|
+
end
|
|
457
|
+
|
|
458
|
+
# Submit a job; returns it (a Hash: "id", "run_id", "status", ...).
|
|
459
|
+
#
|
|
460
|
+
# name:, tasks: (an Array of {"id" =>, "input" =>, "files" => {path =>
|
|
461
|
+
# bytes}} or a JSONL String), solver: and grader: (a command, String or
|
|
462
|
+
# Array, or a Hash with "cmd", "timeout_s", "env" and for the grader
|
|
463
|
+
# "files"), exactly one of template:/image:/snapshot:, and
|
|
464
|
+
# solver_timeout_s: unless the solver Hash has one. Optional: project:,
|
|
465
|
+
# size:, grader_timeout_s:, grader_files:, concurrency:,
|
|
466
|
+
# retries_on_infra:, lease_s:, budget_usd:.
|
|
467
|
+
def submit(idempotency_key: nil, **opts)
|
|
468
|
+
Cloud.check_idempotency_key(idempotency_key)
|
|
469
|
+
job_of(@cloud.request("POST", "/v1/jobs", CloudJobs.body(**opts), idempotency_key: idempotency_key))
|
|
470
|
+
end
|
|
471
|
+
|
|
472
|
+
# What a job would cost (sandbox hours, USD low/high), without running it;
|
|
473
|
+
# sample: n runs n tasks first to measure, or sample_job_id: uses a job's.
|
|
474
|
+
def estimate(sample: nil, sample_job_id: nil, **opts)
|
|
475
|
+
raise ArgumentError, "give sample or sample_job_id, not both" if !sample.nil? && !sample_job_id.nil?
|
|
476
|
+
|
|
477
|
+
body = CloudJobs.body(**opts)
|
|
478
|
+
body["sample"] = Integer(sample) unless sample.nil?
|
|
479
|
+
body["sample_job_id"] = sample_job_id.to_s unless sample_job_id.nil?
|
|
480
|
+
@cloud.request("POST", "/v1/jobs/estimate", body) || {}
|
|
481
|
+
end
|
|
482
|
+
|
|
483
|
+
def get(id)
|
|
484
|
+
job_of(@cloud.request("GET", "/v1/jobs/#{Kosa8.enc(id)}"))
|
|
485
|
+
end
|
|
486
|
+
|
|
487
|
+
def list(status: nil, project: nil, limit: nil, cursor: nil)
|
|
488
|
+
q = Cloud.query_string([["status", status], ["project", project], ["limit", limit], ["cursor", cursor]])
|
|
489
|
+
r = @cloud.request("GET", "/v1/jobs#{q}")
|
|
490
|
+
r.is_a?(Hash) ? (r["jobs"] || []) : []
|
|
491
|
+
end
|
|
492
|
+
|
|
493
|
+
# Stop it: no new tasks start, running ones are stopped.
|
|
494
|
+
def cancel(id)
|
|
495
|
+
job_of(@cloud.request("POST", "/v1/jobs/#{Kosa8.enc(id)}/cancel", {}))
|
|
496
|
+
end
|
|
497
|
+
|
|
498
|
+
# Poll until it is done; the block (if given) gets each poll's job.
|
|
499
|
+
def wait(id, timeout: nil, poll_interval: 5)
|
|
500
|
+
deadline = timeout.nil? ? nil : Time.now + timeout
|
|
501
|
+
loop do
|
|
502
|
+
job = get(id)
|
|
503
|
+
yield job if block_given?
|
|
504
|
+
return job if CloudJobs.done?(job)
|
|
505
|
+
if deadline && Time.now + poll_interval > deadline
|
|
506
|
+
raise TimeoutError, "job #{id} not finished after #{timeout} s (status #{job['status']})"
|
|
507
|
+
end
|
|
508
|
+
|
|
509
|
+
@cloud.sleeper.call(poll_interval)
|
|
510
|
+
end
|
|
511
|
+
end
|
|
512
|
+
|
|
513
|
+
# The body of POST /v1/jobs (ArgumentError on a bad option).
|
|
514
|
+
def self.body(name:, tasks:, solver:, grader:, template: nil, image: nil, snapshot: nil, size: nil, project: nil,
|
|
515
|
+
solver_timeout_s: nil, grader_timeout_s: nil, grader_files: nil, concurrency: nil,
|
|
516
|
+
retries_on_infra: nil, lease_s: nil, budget_usd: nil)
|
|
517
|
+
raise ArgumentError, "a job needs a name" if name.to_s.empty?
|
|
518
|
+
if [template, image, snapshot].compact.size != 1
|
|
519
|
+
raise ArgumentError, "give exactly one of template:, image: or snapshot:"
|
|
520
|
+
end
|
|
521
|
+
|
|
522
|
+
s = cmd_spec(solver, "solver", false)
|
|
523
|
+
s["timeout_s"] = solver_timeout_s unless solver_timeout_s.nil?
|
|
524
|
+
if s["timeout_s"].nil?
|
|
525
|
+
raise ArgumentError, "solver needs timeout_s (seconds; a solver past it is recorded as timeout)"
|
|
526
|
+
end
|
|
527
|
+
|
|
528
|
+
g = cmd_spec(grader, "grader", true)
|
|
529
|
+
g["timeout_s"] = grader_timeout_s unless grader_timeout_s.nil?
|
|
530
|
+
g["files"] = (g["files"] || {}).merge(encode_files(grader_files)) if grader_files && !grader_files.empty?
|
|
531
|
+
body = { "name" => name.to_s, "tasks" => load_tasks(tasks), "solver" => s, "grader" => g }
|
|
532
|
+
{ "project" => project, "template" => template, "image" => image, "snapshot" => snapshot, "size" => size,
|
|
533
|
+
"concurrency" => concurrency, "retries_on_infra" => retries_on_infra, "lease_s" => lease_s,
|
|
534
|
+
"budget_usd" => budget_usd }.each { |k, v| body[k] = v unless v.nil? }
|
|
535
|
+
body
|
|
536
|
+
end
|
|
537
|
+
|
|
538
|
+
# {path => base64} for {absolute path => bytes}.
|
|
539
|
+
def self.encode_files(files)
|
|
540
|
+
files.to_h.map do |p, v|
|
|
541
|
+
raise ArgumentError, "file paths are absolute (in the sandbox), got #{p.to_s.inspect}" unless p.to_s.start_with?("/")
|
|
542
|
+
|
|
543
|
+
[p.to_s, [v.to_s].pack("m0")]
|
|
544
|
+
end.to_h
|
|
545
|
+
end
|
|
546
|
+
|
|
547
|
+
def self.load_tasks(tasks)
|
|
548
|
+
text = tasks.is_a?(String)
|
|
549
|
+
rows = if text
|
|
550
|
+
tasks.each_line.with_index.map do |line, i|
|
|
551
|
+
t = line.strip
|
|
552
|
+
next nil if t.empty?
|
|
553
|
+
|
|
554
|
+
begin
|
|
555
|
+
JSON.parse(t)
|
|
556
|
+
rescue JSON::ParserError => e
|
|
557
|
+
raise ArgumentError, "tasks line #{i + 1}: not JSON: #{e.message}"
|
|
558
|
+
end
|
|
559
|
+
end.compact
|
|
560
|
+
else
|
|
561
|
+
tasks.to_a
|
|
562
|
+
end
|
|
563
|
+
raise ArgumentError, "a job has 1 to #{MAX_TASKS} tasks, got #{rows.size}" unless rows.size.between?(1, MAX_TASKS)
|
|
564
|
+
|
|
565
|
+
seen = {}
|
|
566
|
+
rows.each_with_index.map do |t, i|
|
|
567
|
+
raise ArgumentError, "tasks[#{i}] must be a Hash with an id" unless t.is_a?(Hash)
|
|
568
|
+
|
|
569
|
+
t = t.map { |k, v| [k.to_s, v] }.to_h
|
|
570
|
+
id = t["id"].is_a?(Integer) ? t["id"].to_s : t["id"]
|
|
571
|
+
raise ArgumentError, "tasks[#{i}] needs an id (a String)" unless id.is_a?(String) && !id.empty?
|
|
572
|
+
raise ArgumentError, "task id #{id.inspect} appears twice" if seen[id]
|
|
573
|
+
|
|
574
|
+
seen[id] = true
|
|
575
|
+
row = { "id" => id }
|
|
576
|
+
row["input"] = t["input"] unless t["input"].nil?
|
|
577
|
+
if t["files"].is_a?(Hash) && !t["files"].empty?
|
|
578
|
+
# Already base64 in JSONL: kept as is.
|
|
579
|
+
row["files"] = text ? t["files"] : encode_files(t["files"])
|
|
580
|
+
end
|
|
581
|
+
row
|
|
582
|
+
end
|
|
583
|
+
end
|
|
584
|
+
|
|
585
|
+
def self.cmd_spec(spec, what, files)
|
|
586
|
+
s = spec.is_a?(String) || spec.is_a?(Array) ? { "cmd" => spec } : spec.to_h.map { |k, v| [k.to_s, v] }.to_h
|
|
587
|
+
cmd = s["cmd"]
|
|
588
|
+
if cmd.nil? || (cmd.respond_to?(:empty?) && cmd.empty?)
|
|
589
|
+
raise ArgumentError, "#{what} needs cmd (a String run with sh -c, or an Array of arguments)"
|
|
590
|
+
end
|
|
591
|
+
|
|
592
|
+
extra = s.keys - ["cmd", "timeout_s", "env"] - (files ? ["files"] : [])
|
|
593
|
+
raise ArgumentError, "#{what}: unknown fields #{extra.sort.join(', ')}" unless extra.empty?
|
|
594
|
+
|
|
595
|
+
out = { "cmd" => cmd.is_a?(String) ? cmd : cmd.to_a.map(&:to_s) }
|
|
596
|
+
out["timeout_s"] = s["timeout_s"] unless s["timeout_s"].nil?
|
|
597
|
+
out["env"] = s["env"].to_h.map { |k, v| [k.to_s, v.to_s] }.to_h if s["env"] && !s["env"].empty?
|
|
598
|
+
out["files"] = encode_files(s["files"]) if files && s["files"] && !s["files"].empty?
|
|
599
|
+
out
|
|
600
|
+
end
|
|
601
|
+
|
|
602
|
+
private
|
|
603
|
+
|
|
604
|
+
def job_of(answer)
|
|
605
|
+
return {} unless answer.is_a?(Hash)
|
|
606
|
+
|
|
607
|
+
job = answer["job"].is_a?(Hash) ? answer["job"].dup : {}
|
|
608
|
+
job["id"] ||= answer["job_id"] if answer["job_id"]
|
|
609
|
+
job["run_id"] ||= answer["run_id"] if answer["run_id"]
|
|
610
|
+
job
|
|
611
|
+
end
|
|
612
|
+
end
|
|
613
|
+
|
|
614
|
+
# ---------------------------------------------------------------------------
|
|
615
|
+
# Benchmarks
|
|
616
|
+
|
|
617
|
+
# cloud.benchmarks: ready-made benchmarks (SWE-bench and the like). Create a
|
|
618
|
+
# sandbox from an instance with template: "<benchmark>/<instance id>"; one
|
|
619
|
+
# whose environment is still being built answers 409 template_building,
|
|
620
|
+
# which the SDK waits out (Retry-After) within its retry policy.
|
|
621
|
+
class CloudBenchmarks
|
|
622
|
+
def initialize(cloud)
|
|
623
|
+
@cloud = cloud
|
|
624
|
+
end
|
|
625
|
+
|
|
626
|
+
def inspect
|
|
627
|
+
"#<Kosa8::CloudBenchmarks>"
|
|
628
|
+
end
|
|
629
|
+
|
|
630
|
+
def list
|
|
631
|
+
r = @cloud.request("GET", "/v1/benchmarks")
|
|
632
|
+
r.is_a?(Hash) ? (r["benchmarks"] || []) : []
|
|
633
|
+
end
|
|
634
|
+
|
|
635
|
+
def get(name)
|
|
636
|
+
@cloud.request("GET", "/v1/benchmarks/#{Kosa8.enc(name)}")["benchmark"]
|
|
637
|
+
end
|
|
638
|
+
|
|
639
|
+
# One page of its instances: {"instances" => [...], "next_cursor" => ...}.
|
|
640
|
+
# state: ready, building, queued, failed or not_built; limit: 1..1000.
|
|
641
|
+
def instances(name, state: nil, limit: nil, cursor: nil)
|
|
642
|
+
Cloud.check_range("limit", limit, 1, 1000) unless limit.nil?
|
|
643
|
+
q = Cloud.query_string([["state", state], ["limit", limit], ["cursor", cursor]])
|
|
644
|
+
@cloud.request("GET", "/v1/benchmarks/#{Kosa8.enc(name)}/instances#{q}")
|
|
645
|
+
end
|
|
646
|
+
|
|
647
|
+
# One instance: the solver's input and its environment's state and ETA.
|
|
648
|
+
def instance(name, id)
|
|
649
|
+
@cloud.request("GET", "/v1/benchmarks/#{Kosa8.enc(name)}/instances/#{Kosa8.enc(id)}")["instance"]
|
|
650
|
+
end
|
|
651
|
+
|
|
652
|
+
# Build environments ahead of use (at most 100 a call): +instances+ is
|
|
653
|
+
# an Array of instance ids (or what the API takes for a sample, with seed:).
|
|
654
|
+
def prepare(name, instances, seed: nil)
|
|
655
|
+
body = { "instances" => instances }
|
|
656
|
+
body["seed"] = Integer(seed) unless seed.nil?
|
|
657
|
+
@cloud.request("POST", "/v1/benchmarks/#{Kosa8.enc(name)}/prepare", body)
|
|
658
|
+
end
|
|
659
|
+
end
|
|
660
|
+
|
|
661
|
+
# ---------------------------------------------------------------------------
|
|
662
|
+
# RL alerts
|
|
663
|
+
|
|
664
|
+
# cloud.rl_alerts: alert rules on RL runs (reward drop, infra failure
|
|
665
|
+
# rate, ...); list answers the kinds too.
|
|
666
|
+
class CloudRlAlerts
|
|
667
|
+
def initialize(cloud)
|
|
668
|
+
@cloud = cloud
|
|
669
|
+
end
|
|
670
|
+
|
|
671
|
+
def inspect
|
|
672
|
+
"#<Kosa8::CloudRlAlerts>"
|
|
673
|
+
end
|
|
674
|
+
|
|
675
|
+
# {"alerts" => [...], "kinds" => {...}}; run_id: one run's rules.
|
|
676
|
+
def list(run_id: nil)
|
|
677
|
+
@cloud.request("GET", "/v1/rl/alerts#{Cloud.query_string([['run_id', run_id]])}")
|
|
678
|
+
end
|
|
679
|
+
|
|
680
|
+
def create(kind:, threshold:, run_id: nil, window: nil)
|
|
681
|
+
body = { "kind" => kind.to_s, "threshold" => threshold }
|
|
682
|
+
body["run_id"] = run_id.to_s unless run_id.nil?
|
|
683
|
+
body["window"] = window unless window.nil?
|
|
684
|
+
@cloud.request("POST", "/v1/rl/alerts", body)["alert"]
|
|
685
|
+
end
|
|
686
|
+
|
|
687
|
+
# Change, pause (enabled: false) or resume a rule.
|
|
688
|
+
def update(id, threshold: nil, window: nil, enabled: nil)
|
|
689
|
+
body = {}
|
|
690
|
+
body["threshold"] = threshold unless threshold.nil?
|
|
691
|
+
body["window"] = window unless window.nil?
|
|
692
|
+
body["enabled"] = enabled == true unless enabled.nil?
|
|
693
|
+
raise ArgumentError, "give threshold:, window: or enabled:" if body.empty?
|
|
694
|
+
|
|
695
|
+
@cloud.request("PATCH", "/v1/rl/alerts/#{Kosa8.enc(id)}", body)["alert"]
|
|
696
|
+
end
|
|
697
|
+
|
|
698
|
+
def delete(id)
|
|
699
|
+
@cloud.request("DELETE", "/v1/rl/alerts/#{Kosa8.enc(id)}")
|
|
700
|
+
end
|
|
701
|
+
end
|
|
702
|
+
|
|
703
|
+
# ---------------------------------------------------------------------------
|
|
704
|
+
# Audit
|
|
705
|
+
|
|
706
|
+
# cloud.audit: the org's tamper-evident audit log.
|
|
707
|
+
class CloudAudit
|
|
708
|
+
def initialize(cloud)
|
|
709
|
+
@cloud = cloud
|
|
710
|
+
end
|
|
711
|
+
|
|
712
|
+
def inspect
|
|
713
|
+
"#<Kosa8::CloudAudit>"
|
|
714
|
+
end
|
|
715
|
+
|
|
716
|
+
# One page, newest first: {"events" => [...], "next_before_seq" => n}.
|
|
717
|
+
def list(sandbox_id: nil, actor: nil, action: nil, since: nil, until_ms: nil, before_seq: nil, limit: nil)
|
|
718
|
+
q = Cloud.query_string([["sandbox_id", sandbox_id], ["actor", actor], ["action", action], ["since", since],
|
|
719
|
+
["until", until_ms], ["before_seq", before_seq], ["limit", limit]])
|
|
720
|
+
@cloud.request("GET", "/v1/audit#{q}")
|
|
721
|
+
end
|
|
722
|
+
|
|
723
|
+
# Every event matching, walking next_before_seq. Without a block, an Enumerator.
|
|
724
|
+
def each(**filters)
|
|
725
|
+
return enum_for(:each, **filters) unless block_given?
|
|
726
|
+
|
|
727
|
+
before = nil
|
|
728
|
+
loop do
|
|
729
|
+
page = list(**filters, before_seq: before)
|
|
730
|
+
(page["events"] || []).each { |e| yield e }
|
|
731
|
+
nxt = page["next_before_seq"]
|
|
732
|
+
break if nxt.nil? || nxt == before
|
|
733
|
+
|
|
734
|
+
before = nxt
|
|
735
|
+
end
|
|
736
|
+
self
|
|
737
|
+
end
|
|
738
|
+
|
|
739
|
+
# Recompute the org's hash chain: "ok", "checked", "verified_at", ...
|
|
740
|
+
def verify
|
|
741
|
+
@cloud.request("GET", "/v1/audit/verify")
|
|
742
|
+
end
|
|
743
|
+
|
|
744
|
+
# Every event, oldest first, with its hashes (parsed from NDJSON).
|
|
745
|
+
def export
|
|
746
|
+
text = @cloud.request_bytes("GET", "/v1/audit/export", raw: true).force_encoding(Encoding::UTF_8)
|
|
747
|
+
text.each_line.map(&:strip).reject(&:empty?).map { |l| JSON.parse(l) }
|
|
748
|
+
end
|
|
749
|
+
end
|
|
750
|
+
|
|
751
|
+
# ---------------------------------------------------------------------------
|
|
752
|
+
# API keys
|
|
753
|
+
|
|
754
|
+
# cloud.api_keys: the org's API keys (a key with keys:manage). Secrets are
|
|
755
|
+
# shown once, in the answer that made them.
|
|
756
|
+
class CloudApiKeys
|
|
757
|
+
def initialize(cloud)
|
|
758
|
+
@cloud = cloud
|
|
759
|
+
end
|
|
760
|
+
|
|
761
|
+
def inspect
|
|
762
|
+
"#<Kosa8::CloudApiKeys>"
|
|
763
|
+
end
|
|
764
|
+
|
|
765
|
+
def list
|
|
766
|
+
r = @cloud.request("GET", "/v1/api-keys")
|
|
767
|
+
r.is_a?(Hash) ? (r["api_keys"] || []) : []
|
|
768
|
+
end
|
|
769
|
+
|
|
770
|
+
# A new key ("secret" only here). scopes: nil for a full key.
|
|
771
|
+
def create(name:, scopes: nil, expires_in_s: nil)
|
|
772
|
+
body = { "name" => name.to_s }
|
|
773
|
+
body["scopes"] = scopes.to_a.map(&:to_s) unless scopes.nil?
|
|
774
|
+
body["expires_in_s"] = Integer(expires_in_s) unless expires_in_s.nil?
|
|
775
|
+
@cloud.request("POST", "/v1/api-keys", body)["api_key"]
|
|
776
|
+
end
|
|
777
|
+
|
|
778
|
+
# Revoke a key; it stops at once.
|
|
779
|
+
def revoke(id)
|
|
780
|
+
@cloud.request("DELETE", "/v1/api-keys/#{Kosa8.enc(id)}")
|
|
781
|
+
end
|
|
782
|
+
alias delete revoke
|
|
783
|
+
|
|
784
|
+
# A new key with the same name and scopes; the old one works grace_s more.
|
|
785
|
+
def rotate(id, grace_s: nil)
|
|
786
|
+
body = {}
|
|
787
|
+
body["grace_s"] = Integer(grace_s) unless grace_s.nil?
|
|
788
|
+
@cloud.request("POST", "/v1/api-keys/#{Kosa8.enc(id)}/rotate", body)["api_key"]
|
|
789
|
+
end
|
|
790
|
+
end
|
|
791
|
+
|
|
792
|
+
# ---------------------------------------------------------------------------
|
|
793
|
+
# Webhooks
|
|
794
|
+
|
|
795
|
+
# cloud.webhooks: endpoints kosa8 Cloud POSTs events to, signed with the
|
|
796
|
+
# endpoint's whsec_ secret (shown once, on create).
|
|
797
|
+
class CloudWebhooks
|
|
798
|
+
def initialize(cloud)
|
|
799
|
+
@cloud = cloud
|
|
800
|
+
end
|
|
801
|
+
|
|
802
|
+
def inspect
|
|
803
|
+
"#<Kosa8::CloudWebhooks>"
|
|
804
|
+
end
|
|
805
|
+
|
|
806
|
+
# {"webhooks" => [...], "events" => [the event names]}.
|
|
807
|
+
def info
|
|
808
|
+
r = @cloud.request("GET", "/v1/webhooks")
|
|
809
|
+
r.is_a?(Hash) ? r : {}
|
|
810
|
+
end
|
|
811
|
+
|
|
812
|
+
def list
|
|
813
|
+
info["webhooks"] || []
|
|
814
|
+
end
|
|
815
|
+
|
|
816
|
+
def create(url:, events: nil, description: nil)
|
|
817
|
+
body = { "url" => url.to_s }
|
|
818
|
+
body["events"] = events.to_a.map(&:to_s) unless events.nil?
|
|
819
|
+
body["description"] = description.to_s unless description.nil?
|
|
820
|
+
@cloud.request("POST", "/v1/webhooks", body)["webhook"]
|
|
821
|
+
end
|
|
822
|
+
|
|
823
|
+
# Stop sending, including retries.
|
|
824
|
+
def delete(id)
|
|
825
|
+
@cloud.request("DELETE", "/v1/webhooks/#{Kosa8.enc(id)}")
|
|
826
|
+
end
|
|
827
|
+
|
|
828
|
+
def deliveries(id, limit: nil)
|
|
829
|
+
r = @cloud.request("GET", "/v1/webhooks/#{Kosa8.enc(id)}/deliveries#{Cloud.query_string([['limit', limit]])}")
|
|
830
|
+
r.is_a?(Hash) ? (r["deliveries"] || []) : []
|
|
831
|
+
end
|
|
832
|
+
|
|
833
|
+
# Send a webhook.test event now; returns the delivery.
|
|
834
|
+
def test(id)
|
|
835
|
+
@cloud.request("POST", "/v1/webhooks/#{Kosa8.enc(id)}/test", {})["delivery"]
|
|
836
|
+
end
|
|
837
|
+
end
|
|
838
|
+
|
|
839
|
+
# ---------------------------------------------------------------------------
|
|
840
|
+
# Recordings, embeds, preview domains, Burst Passes
|
|
841
|
+
|
|
842
|
+
# cloud.recordings: desktop recordings (MP4), made when a sandbox created
|
|
843
|
+
# with record: true is deleted.
|
|
844
|
+
class CloudRecordings
|
|
845
|
+
def initialize(cloud)
|
|
846
|
+
@cloud = cloud
|
|
847
|
+
end
|
|
848
|
+
|
|
849
|
+
def inspect
|
|
850
|
+
"#<Kosa8::CloudRecordings>"
|
|
851
|
+
end
|
|
852
|
+
|
|
853
|
+
# Newest first: {"recordings" => [...], "configured" => bool,
|
|
854
|
+
# "retention_days" => n}. sandbox_id: one sandbox's; limit: 1..200.
|
|
855
|
+
def info(sandbox_id: nil, limit: nil)
|
|
856
|
+
Cloud.check_range("limit", limit, 1, 200) unless limit.nil?
|
|
857
|
+
r = @cloud.request("GET", "/v1/recordings#{Cloud.query_string([['sandbox_id', sandbox_id], ['limit', limit]])}")
|
|
858
|
+
r.is_a?(Hash) ? r : {}
|
|
859
|
+
end
|
|
860
|
+
|
|
861
|
+
def list(sandbox_id: nil, limit: nil)
|
|
862
|
+
info(sandbox_id: sandbox_id, limit: limit)["recordings"] || []
|
|
863
|
+
end
|
|
864
|
+
|
|
865
|
+
# A signed download URL for its MP4 ("url", "expires_at", "bytes");
|
|
866
|
+
# ttl_s 60..86400 (default 900).
|
|
867
|
+
def link(id, ttl_s: nil)
|
|
868
|
+
body = {}
|
|
869
|
+
body["ttl_s"] = Cloud.check_range("ttl_s", ttl_s, 60, 86_400) unless ttl_s.nil?
|
|
870
|
+
@cloud.request("POST", "/v1/recordings/#{Kosa8.enc(id)}/link", body)["link"]
|
|
871
|
+
end
|
|
872
|
+
|
|
873
|
+
def delete(id)
|
|
874
|
+
@cloud.request("DELETE", "/v1/recordings/#{Kosa8.enc(id)}")
|
|
875
|
+
nil
|
|
876
|
+
end
|
|
877
|
+
end
|
|
878
|
+
|
|
879
|
+
# sandbox.embeds: signed, expiring iframe URLs for its terminal or desktop.
|
|
880
|
+
# The framed page posts {source: "kosa8", type} messages to the listed
|
|
881
|
+
# origins: ready, exited, approval_requested, expired.
|
|
882
|
+
class CloudEmbeds
|
|
883
|
+
def initialize(cloud, sandbox)
|
|
884
|
+
@cloud = cloud
|
|
885
|
+
@sandbox = sandbox
|
|
886
|
+
end
|
|
887
|
+
|
|
888
|
+
def inspect
|
|
889
|
+
"#<Kosa8::CloudEmbeds sandbox=#{@sandbox.id.inspect}>"
|
|
890
|
+
end
|
|
891
|
+
|
|
892
|
+
# origins: 1..10 (e.g. https://app.example.com); mode: "view" (default)
|
|
893
|
+
# or "interact"; ui: "terminal" (default) or "desktop"; ttl_s 60..604800.
|
|
894
|
+
# The answer's "url" is the credential: give it only to pages you trust.
|
|
895
|
+
def create(origins:, mode: nil, ui: nil, ttl_s: nil, command: nil)
|
|
896
|
+
list = origins.to_a.map(&:to_s)
|
|
897
|
+
raise ArgumentError, "an embed takes 1 to 10 origins" unless list.size.between?(1, 10)
|
|
898
|
+
|
|
899
|
+
body = { "origins" => list }
|
|
900
|
+
body["mode"] = mode.to_s unless mode.nil?
|
|
901
|
+
body["ui"] = ui.to_s unless ui.nil?
|
|
902
|
+
body["ttl_s"] = Cloud.check_range("ttl_s", ttl_s, 60, 604_800) unless ttl_s.nil?
|
|
903
|
+
body["command"] = command.to_a.map(&:to_s) unless command.nil?
|
|
904
|
+
@cloud.request("POST", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/embed", body)["embed"]
|
|
905
|
+
end
|
|
906
|
+
|
|
907
|
+
# Its live embeds (no URLs).
|
|
908
|
+
def list
|
|
909
|
+
r = @cloud.request("GET", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/embeds")
|
|
910
|
+
r.is_a?(Hash) ? (r["embeds"] || []) : []
|
|
911
|
+
end
|
|
912
|
+
|
|
913
|
+
# End an embed's URL before it expires.
|
|
914
|
+
def revoke(embed_id)
|
|
915
|
+
raise ArgumentError, "revoke needs an embed id (emb_...)" if embed_id.nil? || embed_id.to_s.empty?
|
|
916
|
+
|
|
917
|
+
@cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/embeds/#{Kosa8.enc(embed_id)}")
|
|
918
|
+
nil
|
|
919
|
+
end
|
|
920
|
+
end
|
|
921
|
+
|
|
922
|
+
# A preview's custom domains (at most 5 a preview). The domain serves the
|
|
923
|
+
# preview as it is and follows it across a rotate. 501 not_available
|
|
924
|
+
# where custom hostnames are not configured.
|
|
925
|
+
class CloudPreviewDomains
|
|
926
|
+
# Give preview_id: (cloud.preview_domains), or sandbox_id: and port:
|
|
927
|
+
# (box.previews.domains(port)).
|
|
928
|
+
def initialize(cloud, preview_id: nil, sandbox_id: nil, port: nil)
|
|
929
|
+
@cloud = cloud
|
|
930
|
+
@preview_id = preview_id
|
|
931
|
+
@sandbox_id = sandbox_id
|
|
932
|
+
@port = port
|
|
933
|
+
end
|
|
934
|
+
|
|
935
|
+
def inspect
|
|
936
|
+
"#<Kosa8::CloudPreviewDomains #{collection}>"
|
|
937
|
+
end
|
|
938
|
+
|
|
939
|
+
# {"domains" => [...], "configured" => bool, "cname_target" => host}.
|
|
940
|
+
def info
|
|
941
|
+
r = @cloud.request("GET", collection)
|
|
942
|
+
r.is_a?(Hash) ? r : {}
|
|
943
|
+
end
|
|
944
|
+
|
|
945
|
+
def list
|
|
946
|
+
info["domains"] || []
|
|
947
|
+
end
|
|
948
|
+
|
|
949
|
+
# Serve the preview at +hostname+; make the "records" it answers at your
|
|
950
|
+
# DNS provider. ssl_method: "http" or "txt".
|
|
951
|
+
def add(hostname, ssl_method: nil)
|
|
952
|
+
body = { "hostname" => hostname.to_s }
|
|
953
|
+
body["ssl_method"] = ssl_method.to_s unless ssl_method.nil?
|
|
954
|
+
@cloud.request("POST", collection, body)["domain"]
|
|
955
|
+
end
|
|
956
|
+
|
|
957
|
+
# Its status, asked of the certificate provider again.
|
|
958
|
+
def get(hostname)
|
|
959
|
+
@cloud.request("GET", item(hostname))["domain"]
|
|
960
|
+
end
|
|
961
|
+
|
|
962
|
+
def remove(hostname)
|
|
963
|
+
@cloud.request("DELETE", item(hostname))
|
|
964
|
+
nil
|
|
965
|
+
end
|
|
966
|
+
|
|
967
|
+
private
|
|
968
|
+
|
|
969
|
+
# "/v1/sandboxes/{id}/previews/{port}/domains" or "/v1/previews/{preview_id}/domains".
|
|
970
|
+
def collection
|
|
971
|
+
return "/v1/previews/#{Kosa8.enc(@preview_id)}/domains" if @preview_id
|
|
972
|
+
|
|
973
|
+
"/v1/sandboxes/#{Kosa8.enc(@sandbox_id)}/previews/#{@port}/domains"
|
|
974
|
+
end
|
|
975
|
+
|
|
976
|
+
def item(hostname)
|
|
977
|
+
raise ArgumentError, "a hostname is required" if hostname.nil? || hostname.to_s.empty?
|
|
978
|
+
|
|
979
|
+
h = Kosa8.enc(hostname)
|
|
980
|
+
return "/v1/previews/#{Kosa8.enc(@preview_id)}/domains/#{h}" if @preview_id
|
|
981
|
+
|
|
982
|
+
"/v1/sandboxes/#{Kosa8.enc(@sandbox_id)}/previews/#{@port}/domains/#{h}"
|
|
983
|
+
end
|
|
984
|
+
end
|
|
985
|
+
|
|
986
|
+
# cloud.burst: Burst Passes, each raising the running limit for its hours.
|
|
987
|
+
class CloudBurst
|
|
988
|
+
def initialize(cloud)
|
|
989
|
+
@cloud = cloud
|
|
990
|
+
end
|
|
991
|
+
|
|
992
|
+
def inspect
|
|
993
|
+
"#<Kosa8::CloudBurst>"
|
|
994
|
+
end
|
|
995
|
+
|
|
996
|
+
# "available", "pass", "held", "active", "adds_now".
|
|
997
|
+
def get
|
|
998
|
+
@cloud.request("GET", "/v1/billing/burst")
|
|
999
|
+
end
|
|
1000
|
+
|
|
1001
|
+
# Activate +quantity+ passes (an owner's admin key). Holding fewer, the
|
|
1002
|
+
# answer is a checkout "url" for the rest.
|
|
1003
|
+
def activate(quantity = 1)
|
|
1004
|
+
raise ArgumentError, "quantity must be a whole number of at least 1" unless quantity.is_a?(Integer) && quantity >= 1
|
|
1005
|
+
|
|
1006
|
+
@cloud.request("POST", "/v1/billing/burst", { "quantity" => quantity })
|
|
1007
|
+
end
|
|
1008
|
+
end
|
|
1009
|
+
end
|