withruntime 0.27.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. checksums.yaml +4 -4
  2. data/lib/withruntime/generated/apps.rb +192 -0
  3. data/lib/withruntime/generated/audit.rb +78 -0
  4. data/lib/withruntime/generated/browsers.rb +192 -0
  5. data/lib/withruntime/generated/builds.rb +192 -0
  6. data/lib/withruntime/generated/ci.rb +192 -0
  7. data/lib/withruntime/generated/containers.rb +192 -0
  8. data/lib/withruntime/generated/desktops.rb +192 -0
  9. data/lib/withruntime/generated/domains.rb +152 -0
  10. data/lib/withruntime/generated/egress_ips.rb +81 -0
  11. data/lib/withruntime/generated/events.rb +60 -0
  12. data/lib/withruntime/generated/feedback.rb +96 -0
  13. data/lib/withruntime/generated/functions.rb +192 -0
  14. data/lib/withruntime/generated/identities.rb +68 -0
  15. data/lib/withruntime/generated/images.rb +391 -0
  16. data/lib/withruntime/generated/job_runs.rb +110 -0
  17. data/lib/withruntime/generated/jobs.rb +333 -0
  18. data/lib/withruntime/generated/keys.rb +261 -0
  19. data/lib/withruntime/generated/kit.rb +111 -0
  20. data/lib/withruntime/generated/me.rb +69 -0
  21. data/lib/withruntime/generated/networks.rb +72 -0
  22. data/lib/withruntime/generated/notebooks.rb +192 -0
  23. data/lib/withruntime/generated/otel.rb +94 -0
  24. data/lib/withruntime/generated/ports.rb +118 -0
  25. data/lib/withruntime/generated/previews.rb +124 -0
  26. data/lib/withruntime/generated/projects.rb +108 -0
  27. data/lib/withruntime/generated/roles.rb +68 -0
  28. data/lib/withruntime/generated/routes.rb +11 -0
  29. data/lib/withruntime/generated/runtime.rb +188 -0
  30. data/lib/withruntime/generated/sandboxes.rb +1835 -0
  31. data/lib/withruntime/generated/secrets.rb +294 -0
  32. data/lib/withruntime/generated/sessions.rb +143 -0
  33. data/lib/withruntime/generated/sites.rb +192 -0
  34. data/lib/withruntime/generated/snapshots.rb +32 -0
  35. data/lib/withruntime/generated/tunnels.rb +165 -0
  36. data/lib/withruntime/generated/usage.rb +287 -0
  37. data/lib/withruntime/generated/volumes.rb +61 -0
  38. data/lib/withruntime/generated/webhooks.rb +91 -0
  39. data/lib/withruntime/generated/workspaces.rb +192 -0
  40. data/lib/withruntime/signing.rb +162 -0
  41. data/lib/withruntime/version.rb +2 -2
  42. data/lib/withruntime.rb +5 -43
  43. metadata +45 -35
  44. data/lib/withruntime/agents.rb +0 -877
  45. data/lib/withruntime/api_defaults.rb +0 -17
  46. data/lib/withruntime/apps.rb +0 -377
  47. data/lib/withruntime/browsers.rb +0 -104
  48. data/lib/withruntime/builds.rb +0 -218
  49. data/lib/withruntime/ci.rb +0 -164
  50. data/lib/withruntime/client.rb +0 -140
  51. data/lib/withruntime/containers.rb +0 -39
  52. data/lib/withruntime/credentials.rb +0 -111
  53. data/lib/withruntime/fields.rb +0 -40
  54. data/lib/withruntime/file_watch.rb +0 -73
  55. data/lib/withruntime/images.rb +0 -258
  56. data/lib/withruntime/network_products.rb +0 -49
  57. data/lib/withruntime/parity_products.rb +0 -51
  58. data/lib/withruntime/products.rb +0 -560
  59. data/lib/withruntime/record.rb +0 -99
  60. data/lib/withruntime/reservations.rb +0 -76
  61. data/lib/withruntime/sandbox.rb +0 -770
  62. data/lib/withruntime/tar.rb +0 -292
  63. data/lib/withruntime/transport.rb +0 -575
  64. data/lib/withruntime/tunnel.rb +0 -275
  65. data/lib/withruntime/wallet.rb +0 -68
  66. data/lib/withruntime/websocket.rb +0 -384
@@ -1,560 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "openssl"
4
-
5
- module WithRuntime
6
- # The pieces every product shares.
7
- class Product
8
- SAFE_INTEGER = (2**53) - 1
9
-
10
- def initialize(transport)
11
- @t = transport
12
- end
13
-
14
- private
15
-
16
- def seg(value) = Transport.segment(value)
17
-
18
- # A followed log's refusal, with the cursor it resumes from in its details.
19
- def failure(code, hint, cursor) = Error.new(hint, code: code, hint: hint, details: { "cursor" => cursor })
20
-
21
- # A log cursor is opaque: a short string with no control characters.
22
- def valid_cursor?(value)
23
- value.is_a?(String) && !value.empty? && value.length <= 4096 && !value.match?(/[\x00-\x1f\x7f]/)
24
- end
25
-
26
- def safe_integer?(value) = value.is_a?(Integer) && value.abs <= SAFE_INTEGER
27
-
28
- # A change's body from keyword arguments: nil is left out, +:remove+ sends
29
- # null, which clears the field.
30
- def patch(changes)
31
- body = Fields.body(changes.reject { |_key, value| value == :remove })
32
- changes.each { |key, value| body[key.is_a?(Symbol) ? Fields.camel(key) : key.to_s] = nil if value == :remove }
33
- body
34
- end
35
-
36
- def page(path, query)
37
- body = @t.json("GET", path, query: query)
38
- Page.new(body["data"].map { |item| Record.new(item) }, body["nextCursor"]) do |cursor|
39
- page(path, query.merge("cursor" => cursor))
40
- end
41
- end
42
- end
43
-
44
- # +runtime.snapshots+. Take one with +sbx.snapshot+, start from one with
45
- # +runtime.sandboxes.create(snapshot: id)+, or do both with +sbx.fork+.
46
- class Snapshots < Product
47
- # Snapshots a sandbox by id, as it is: the API answers how the sandbox must be.
48
- def create(sandbox_id, name: nil, labels: nil, retention_days: nil, idempotency_key: nil)
49
- body = Fields.body(name: name, labels: labels, retention_days: retention_days)
50
- Record.new(@t.json("POST", "/v1/sandboxes/#{seg(sandbox_id)}:snapshot", body: body, wait: 10, key: idempotency_key))
51
- end
52
-
53
- def get(id) = Record.new(@t.json("GET", "/v1/snapshots/#{seg(id)}"))
54
-
55
- # state: capturing, ready, failed or deleting.
56
- def list(sandbox_id: nil, name: nil, state: nil, limit: nil)
57
- page("/v1/snapshots", { "sandboxId" => sandbox_id, "name" => name, "state" => state, "limit" => limit })
58
- end
59
-
60
- def delete(id)
61
- @t.json("POST", "/v1/snapshots/#{seg(id)}:delete", body: {})
62
- nil
63
- end
64
-
65
- # Keeps a snapshot for +retention_days+ from now.
66
- def extend_retention(id, retention_days)
67
- Record.new(@t.json("POST", "/v1/snapshots/#{seg(id)}:extend", body: { "retentionDays" => retention_days }))
68
- end
69
- end
70
-
71
- # +runtime.volumes+: persistent disks. Create one, then attach it when
72
- # creating a sandbox: +volumes: [{ volume_id: v.id, path: "/data" }]+. A
73
- # volume lives on one host; its backups can restore onto another host.
74
- class Volumes < Product
75
- # Creates a volume and waits (up to 10 seconds) until it is ready.
76
- def create(size_mib: nil, name: nil, labels: nil, region: nil, from_backup: nil, idempotency_key: nil)
77
- body = Fields.body(size_mib: size_mib, name: name, labels: labels, region: region, from_backup: from_backup)
78
- Record.new(@t.json("POST", "/v1/volumes", body: body, wait: 10, key: idempotency_key))
79
- end
80
-
81
- def backup(id, name: nil, labels: nil, retention_days: nil, wait: 60, idempotency_key: nil)
82
- Record.new(@t.json("POST", "/v1/volumes/#{seg(id)}:backup", body: Fields.body(name: name, labels: labels, retention_days: retention_days), wait: wait, key: idempotency_key))
83
- end
84
- # Automatic backups on or off and the days a daily one is kept; or a
85
- # schedule of the volume's own: every_minutes (15 or more) or a five-field
86
- # UTC cron, keeping the keep counts (last, hourly, daily, weekly, monthly,
87
- # yearly). no_schedule: true goes back to daily backups.
88
- def set_backup_policy(id, daily: nil, retention_days: nil, every_minutes: nil, cron: nil, keep: nil, no_schedule: false)
89
- raise ArgumentError, "Give one of every_minutes, cron and no_schedule." if [every_minutes, cron, (no_schedule || nil)].compact.size > 1
90
-
91
- body = Fields.body(daily: daily, retention_days: retention_days, keep: keep)
92
- if every_minutes then body["schedule"] = { "everyMinutes" => every_minutes }
93
- elsif cron then body["schedule"] = { "cron" => cron }
94
- elsif no_schedule then body["schedule"] = nil
95
- end
96
- Record.new(@t.json("POST", "/v1/volumes/#{seg(id)}:backup-policy", body: body))
97
- end
98
- def backups(volume_id: nil, state: nil, limit: nil) = page("/v1/volume-backups", { "volumeId" => volume_id, "state" => state, "limit" => limit })
99
- def get_backup(id) = Record.new(@t.json("GET", "/v1/volume-backups/#{seg(id)}"))
100
- def delete_backup(id) = Record.new(@t.json("POST", "/v1/volume-backups/#{seg(id)}:delete", body: {}))
101
- def restore(id, **options) = create(**options.merge(from_backup: id))
102
-
103
- def get(id) = Record.new(@t.json("GET", "/v1/volumes/#{seg(id)}"))
104
-
105
- def list(state: nil, name: nil, limit: nil) = page("/v1/volumes", { "state" => state, "name" => name, "limit" => limit })
106
-
107
- # Grows a volume no sandbox holds to +size_mib+, on its host, and waits
108
- # (up to +wait+ seconds) for it. The answer's +resize+ shows how far it got.
109
- def resize(id, size_mib:, wait: 10, idempotency_key: nil)
110
- Record.new(@t.json("POST", "/v1/volumes/#{seg(id)}:resize", body: Fields.body(size_mib: size_mib), wait: wait, key: idempotency_key))
111
- end
112
-
113
- # Deletes a volume and everything on it.
114
- def delete(id) = Record.new(@t.json("POST", "/v1/volumes/#{seg(id)}:delete", body: {}))
115
- end
116
-
117
- # +runtime.secrets+: a value your sandboxes use without seeing it. Every
118
- # sandbox of the organization has an environment variable of the secret's
119
- # name holding a placeholder; the egress proxy puts the value into HTTPS
120
- # requests to its hosts. With +exposed: true+, the sandboxes and Apps its
121
- # +only:+ names by id get the value itself instead. The value is never returned.
122
- class Secrets < Product
123
- # Stores or replaces a secret for +hosts+ ("api.openai.com", "*.github.com").
124
- # With +header:+, that header is set on every request to them, +format:+'s
125
- # {value} replaced.
126
- #
127
- # +rules:+ limits the value to the requests a rule allows, such as
128
- # [{ "methods" => ["GET"], "paths" => ["/repos/acme/*"] }]. +only:+ gives it to
129
- # those sandboxes alone ({ "labels" => [{ "role" => "hub" }], "sandboxes" => [ids],
130
- # "apps" => [App ids] }; left out when replacing, the scope it has stays; {} is every
131
- # sandbox again). +github_app:+ ({ "id" =>, "installation" =>,
132
- # "repositories" =>, "permissions" =>, "api" => }) makes +value+ a GitHub App's
133
- # private key (PEM); the servers make its installation tokens themselves, and the
134
- # secret takes no +header:+ or +format:+. +git:+ ({ "push" => [branch patterns] };
135
- # an empty list is no push at all) limits what a git push may update. +api:+
136
- # ({ "callsPerHour" =>, "writesPerHour" =>, "keep" =>, "copies" =>, "fresh" =>,
137
- # "graphql" => { "path" =>, "mutations" => [] } }) sets each sandbox's hour with the
138
- # secret, the far end's reserve, GraphQL's mutations and shared copies. The answer
139
- # and +list+ return them as +githubApp+, +git+ and +api+. +env:+ is the environment
140
- # variable sandboxes see it in, when not the secret's name. Secrets scoped to different
141
- # sandboxes may share one, such as one GITHUB_TOKEN per repository; a write that would
142
- # put two in one sandbox is refused (409). Absent when replacing: the variable it has stays.
143
- #
144
- # +exposed: true+, with no +hosts:+, gives sandboxes the value itself in the variable instead
145
- # of a placeholder: for what is not an HTTPS header, such as a database password, an SSH key
146
- # or a service account's JSON. The value may then be any text of up to 64 KiB, several lines
147
- # included, and it takes no +header:+, +format:+, +rules:+, +github_app:+, +git:+ or +api:+.
148
- # It needs +only:+ naming the sandboxes or Apps that get it by id ({ "sandboxes" => [ids] },
149
- # { "apps" => [App ids] }), never labels or every sandbox; a replacement may leave +only:+
150
- # out to keep the scope it has. Which machines get it changes only with the value: +scope+
151
- # is refused for it, so +set+ it again.
152
- # Code in the sandbox can read it and send it anywhere, and it can be in the sandbox's
153
- # snapshots and forks; for an HTTPS API, prefer +hosts:+. It is not kept: give it on every
154
- # write of such a secret. +expected_version:+ writes only if the secret is at that version
155
- # (its +version+ from +get+ or +list+; 0: it must not exist yet), or raises 409
156
- # version_conflict with the current one in +details["version"]+.
157
- def set(name, value:, hosts: nil, header: nil, format: nil, rules: nil, only: nil, github_app: nil, git: nil,
158
- api: nil, env: nil, exposed: nil, expected_version: nil)
159
- body = { "value" => value, "hosts" => hosts, "header" => header, "format" => format, "rules" => rules,
160
- "only" => only, "githubApp" => github_app, "git" => git, "api" => api, "env" => env,
161
- "exposed" => exposed, "expectedVersion" => expected_version }.compact
162
- Record.new(@t.json("PUT", "/v1/egress-secrets/#{seg(name)}", body: body))
163
- end
164
-
165
- # One secret by name: its kind (+exposed+), +version+, variable, hosts and placeholder. Never
166
- # its value. Raises 404 not_found when there is none.
167
- def get(name) = Record.new(@t.json("GET", "/v1/egress-secrets/#{seg(name)}"))
168
-
169
- # Changes which sandboxes get a secret, without its value: +{}+ is every sandbox of the
170
- # organization again. Returns the secret, with +only+ and +enforced+. Refused (400) for a
171
- # real-value secret (+exposed+), whose machines change only with its value: +set+ it again
172
- # with +value:+, +exposed: true+ and +only:+.
173
- def scope(name, only)
174
- Record.new(@t.json("PUT", "/v1/egress-secrets/#{seg(name)}/sandboxes", body: only))
175
- end
176
-
177
- # Narrows +hosts:+ and/or +rules:+ without the value; only strictly narrower
178
- # ones are accepted. Widening needs the value: call +set+ again with it.
179
- def narrow(name, hosts: nil, rules: nil)
180
- body = { "hosts" => hosts, "rules" => rules }.compact
181
- Record.new(@t.json("PUT", "/v1/egress-secrets/#{seg(name)}/rules", body: body))
182
- end
183
-
184
- # Names, kinds, versions, hosts and placeholders. Never values. With +limit:+ (1 to 100)
185
- # or +after:+, one page by name: the secrets named after +after+; the next
186
- # page's +after+ is this one's last name. Without, every secret.
187
- def list(limit: nil, after: nil)
188
- secrets = []
189
- start = after
190
- loop do
191
- page = @t.json("GET", "/v1/egress-secrets", query: { "limit" => limit, "after" => start })
192
- secrets.concat(page["secrets"].map { |secret| Record.new(secret) })
193
- return secrets if limit || after || !page["next"]
194
-
195
- start = page["next"]
196
- end
197
- end
198
-
199
- # Erases a secret; its placeholder stops working.
200
- def delete(name)
201
- @t.json("DELETE", "/v1/egress-secrets/#{seg(name)}")
202
- nil
203
- end
204
- end
205
-
206
- # +runtime.limits+: whether this key is read-only, and what its agent may still spend today, plus +account+: the account's limits (limit, label, unit, max, used), or nil.
207
- class Limits < Product
208
- def get = Record.new(@t.json("GET", "/v1/limits"))
209
- end
210
-
211
- # +runtime.jobs+: other platforms' jobs read into Runtime jobs. Create and manage
212
- # jobs with the CLI (+runtime jobs+), the TypeScript or Python SDK, or the HTTP API.
213
- class Jobs < Product
214
- # Reads a Google Cloud Run job's YAML (with the Cloud Scheduler job that runs it)
215
- # or an AWS Batch job definition (API JSON, describe-job-definitions output or a
216
- # CloudFormation template, with the EventBridge schedule or rule that submits it)
217
- # into the Runtime jobs that run the same container. +files+ is
218
- # <tt>[{ "path" => "job.yaml", "text" => ... }]</tt>; +from+ is "cloud-run" or
219
- # "aws-batch" (found from the files when nil); +parameters+ are a CloudFormation
220
- # template's values. Changes nothing: +runtime jobs import+ builds and creates it.
221
- def import_plan(files, from: nil, parameters: nil)
222
- body = { "files" => files }
223
- body["from"] = from if from
224
- body["parameters"] = parameters if parameters && !parameters.empty?
225
- Record.new(@t.json("POST", "/v1/job-imports", body: body))
226
- end
227
- end
228
-
229
- # +runtime.referrals+: the account's referral link and what it earned. Money is
230
- # integer microdollars in strings.
231
- class Referrals < Product
232
- def get = Record.new(@t.json("GET", "/v1/referrals"))
233
- end
234
-
235
- # +runtime.emails+: which of Runtime's optional emails this key's person gets
236
- # for this account: own-deletions (warnings for dates the account's own
237
- # retention set), billing, usage and tips. Sign-in, support replies, credit
238
- # expiry and deletions Runtime decides are always sent and are not listed.
239
- class Emails < Product
240
- def get = @t.json("GET", "/v1/account/emails")["settings"].map { |row| Record.new(row) }
241
-
242
- # Turns one on or off for this key's person only, and answers all of them.
243
- # Needs a key for every action.
244
- def set(category, enabled)
245
- body = { "category" => category, "enabled" => enabled }
246
- @t.json("POST", "/v1/account/emails:update", body: body)["settings"].map { |row| Record.new(row) }
247
- end
248
- end
249
-
250
- # +runtime.plans+: monthly plans whose fee is prepaid usage. The fee comes back as plan usage, spent first
251
- # each month at the same measured prices, plus a bonus for committing; plan usage left at the period's end
252
- # ends with it. Money is integer microdollars in strings.
253
- #
254
- # Every change answers +checkout_url+ (where a person starts a first plan or a trial in the browser, nil
255
- # once the change was made) and +current+ (the plan as it is now). Each takes an +idempotency_key+; one is
256
- # made per call when left out.
257
- class Plans < Product
258
- # +current+ (the plan you hold, or nil: plan_id, name, status, interval, period_start, period_end,
259
- # trial_ends_at, cancel_at_period_end, next_plan_id, started_at, add_ons, auto_upgrade, plan_usage) and
260
- # +plans+ (every plan you may choose: id, name, card, fee_micros, yearly_fee_micros, bonus_micros,
261
- # trial_days, first_period_double, support, collection, contract, position, included, limits, features,
262
- # add_ons).
263
- def list = Record.new(@t.json("GET", "/v1/plans"))
264
-
265
- # Start a plan, or move to another. With no plan, answers +checkout_url+. A dearer plan starts at once,
266
- # prorated; a cheaper one at +period_end+ (+next_plan_id+). +interval: "year"+ pays ten months for
267
- # twelve; monthly unless asked.
268
- def choose(plan, interval: nil, idempotency_key: nil)
269
- body = { "plan" => plan }
270
- body["interval"] = interval unless interval.nil?
271
- Record.new(@t.json("POST", "/v1/plans/choose", body: body, key: idempotency_key))
272
- end
273
-
274
- # End the plan at +period_end+.
275
- def cancel(idempotency_key: nil) = Record.new(@t.json("POST", "/v1/plans/cancel", body: {}, key: idempotency_key))
276
-
277
- # Keep a plan you cancelled, before +period_end+.
278
- def resume(idempotency_key: nil) = Record.new(@t.json("POST", "/v1/plans/resume", body: {}, key: idempotency_key))
279
-
280
- # Add an add-on by id: charged now for the rest of the period, prorated, then with the plan.
281
- def add_on(id, idempotency_key: nil)
282
- Record.new(@t.json("POST", "/v1/plans/add-ons", body: { "addOn" => id }, key: idempotency_key))
283
- end
284
-
285
- # Remove an add-on: its charge stops now, and it holds to +period_end+.
286
- def remove_add_on(id, idempotency_key: nil)
287
- Record.new(@t.json("DELETE", "/v1/plans/add-ons/#{seg(id)}", key: idempotency_key))
288
- end
289
-
290
- # Move up a plan by itself when a limit refuses (true), or not. Owners, and keys an owner made.
291
- def auto_upgrade(on, idempotency_key: nil)
292
- Record.new(@t.json("PUT", "/v1/plans/auto-upgrade", body: { "on" => on }, key: idempotency_key))
293
- end
294
- end
295
-
296
- # +runtime.switching+: compare usage with a rival's published rates, and record a switch.
297
- class Switching < Product
298
- # Your settled usage over the last +days+ (30 by default, at most 90) priced
299
- # on Runtime and at +provider+ (e2b, daytona, vercel, modal, cloudflare, fly, fly-machines).
300
- def compare(provider, days: nil) = Record.new(@t.json("GET", "/v1/usage/compare", query: { "provider" => provider, "days" => days }))
301
-
302
- def get = Record.new(@t.json("GET", "/v1/switching"))
303
-
304
- # Once per organization, before its first top-up.
305
- def record(provider) = Record.new(@t.json("POST", "/v1/switching", body: { "provider" => provider }))
306
- end
307
-
308
- # +runtime.events+: lifecycle events, newest first.
309
- class Events < Product
310
- def list(resource_id: nil, type: nil, limit: nil)
311
- page("/v1/events", { "resourceId" => resource_id, "type" => type, "limit" => limit })
312
- end
313
- end
314
-
315
- # +runtime.webhooks+: signed lifecycle events POSTed to your URL.
316
- class Webhooks < Product
317
- # Returns the webhook with its +secret+, shown this once. +events+ nil is every event.
318
- def create(url:, events: nil, description: nil)
319
- Record.new(@t.json("POST", "/v1/webhooks", body: { "url" => url, "events" => events, "description" => description }.compact))
320
- end
321
-
322
- def list = @t.json("GET", "/v1/webhooks")["data"].map { |hook| Record.new(hook) }
323
-
324
- def get(id) = Record.new(@t.json("GET", "/v1/webhooks/#{seg(id)}"))
325
-
326
- # Changes url, events, description or enabled; fields left out stay as they are.
327
- def update(id, **patch) = Record.new(@t.json("POST", "/v1/webhooks/#{seg(id)}:update", body: Fields.body(patch)))
328
-
329
- # A new secret, returned once. The old one keeps signing for
330
- # +keep_previous_seconds+ (a day by default, a week at most; 0 ends it now).
331
- def rotate_secret(id, keep_previous_seconds: nil)
332
- body = { "keepPreviousSeconds" => keep_previous_seconds }.compact
333
- Record.new(@t.json("POST", "/v1/webhooks/#{seg(id)}:rotate-secret", body: body))
334
- end
335
-
336
- def delete(id)
337
- @t.json("POST", "/v1/webhooks/#{seg(id)}:delete", body: {})
338
- nil
339
- end
340
-
341
- # Sends a signed webhook.test now and says how your endpoint answered.
342
- def test(id) = Record.new(@t.json("POST", "/v1/webhooks/#{seg(id)}:test", body: {}, wait: 10))
343
-
344
- # state: pending, succeeded, failed or cancelled.
345
- def deliveries(id, state: nil) = page("/v1/webhooks/#{seg(id)}/deliveries", { "state" => state })
346
-
347
- # Sends one delivery again, once, now.
348
- def retry(delivery_id) = Record.new(@t.json("POST", "/v1/webhook-deliveries/#{seg(delivery_id)}:retry", body: {}))
349
-
350
- # Checks a delivery's Runtime-Signature header against the raw body and
351
- # your secret (or secrets, during a rotation), and returns the event.
352
- # Raises WebhookVerificationError when the signature does not match or is
353
- # older than +tolerance+ seconds (300), which stops a captured delivery
354
- # being replayed. Pass the body exactly as received.
355
- def self.verify(body, header, secret, tolerance: 300, now: Time.now.to_i)
356
- raise WebhookVerificationError, "Missing Runtime-Signature header." if header.nil? || header.empty?
357
-
358
- parts = header.split(",").map { |part| part.strip.split("=", 2) }
359
- stamp = parts.find { |key, _| key == "t" }&.last
360
- given = parts.select { |key, value| key == "v1" && value && !value.empty? }.map(&:last)
361
- raise WebhookVerificationError, "Malformed Runtime-Signature header." unless stamp&.match?(/\A\d+\z/) && !given.empty?
362
- raise WebhookVerificationError, "The signature is too old; the delivery may be a replay." if (now - stamp.to_i).abs > tolerance
363
-
364
- Array(secret).each do |key|
365
- expected = OpenSSL::HMAC.hexdigest("SHA256", key, "#{stamp}.#{body}")
366
- next unless given.any? { |value| value.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(value, expected) }
367
-
368
- begin
369
- return Record.new(JSON.parse(body))
370
- rescue JSON::ParserError
371
- raise WebhookVerificationError, "The body is not JSON."
372
- end
373
- end
374
- raise WebhookVerificationError, "No signature matches the secret."
375
- end
376
- end
377
-
378
- # +runtime.otel+: events (as logs), CPU, memory, disk and network (as metrics)
379
- # and a span for every API call (as traces, with signals including "traces") pushed to
380
- # an OpenTelemetry endpoint over OTLP/HTTP.
381
- class Otel < Product
382
- # +headers+ authenticate to the endpoint and are never shown back.
383
- def create(endpoint:, headers: nil, signals: nil)
384
- Record.new(@t.json("POST", "/v1/otel-exports", body: { "endpoint" => endpoint, "headers" => headers, "signals" => signals }.compact))
385
- end
386
-
387
- def list = @t.json("GET", "/v1/otel-exports")["data"].map { |export| Record.new(export) }
388
- def get(id) = Record.new(@t.json("GET", "/v1/otel-exports/#{seg(id)}"))
389
- def update(id, **patch) = Record.new(@t.json("POST", "/v1/otel-exports/#{seg(id)}:update", body: Fields.body(patch)))
390
-
391
- # Pushes now instead of at the next interval.
392
- def flush(id) = Record.new(@t.json("POST", "/v1/otel-exports/#{seg(id)}:flush", body: {}))
393
-
394
- def delete(id)
395
- @t.json("POST", "/v1/otel-exports/#{seg(id)}:delete", body: {})
396
- nil
397
- end
398
- end
399
-
400
- # +runtime.audit+: the account's audit log, newest first.
401
- class Audit < Product
402
- # +events+ and +next+ (pass it as +before:+). +action:+ is an action
403
- # (key.created) or a group ending in a dot (member.).
404
- def list(action: nil, limit: nil, before: nil)
405
- Record.new(@t.json("GET", "/v1/audit", query: { "action" => action, "limit" => limit, "before" => before }))
406
- end
407
- end
408
-
409
- # +runtime.feedback+: tell the Runtime team something.
410
- class Feedback < Product
411
- # +kind+ is bug, missing_feature, competitor_gap, migration_blocker, docs, pricing, praise or other.
412
- def submit(kind:, summary:, detail: nil, competitor: nil, resource_id: nil, request_id: nil, context: nil)
413
- body = Fields.body(kind: kind, summary: summary, detail: detail, competitor: competitor,
414
- resource_id: resource_id, request_id: request_id, context: context)
415
- Record.new(@t.json("POST", "/v1/feedback", body: body))
416
- end
417
-
418
- # This account's reports and where each stands.
419
- def list(limit: nil) = @t.json("GET", "/v1/feedback", query: { "limit" => limit })["data"].map { |item| Record.new(item) }
420
- end
421
-
422
- # +runtime.support+: ask Runtime support.
423
- class Support < Product
424
- # When the status is "working", +read+ it again in a minute. Not retried:
425
- # support cannot deduplicate a message.
426
- def message(message = nil, conversation_id: nil, approve_action_id: nil, approve_input_hash: nil, deny_action_id: nil)
427
- body = Fields.body(message: message, conversation_id: conversation_id, approve_action_id: approve_action_id,
428
- approve_input_hash: approve_input_hash, deny_action_id: deny_action_id)
429
- Record.new(@t.json("POST", "/v1/support/messages", body: body, no_retry: true, timeout: 120))
430
- end
431
-
432
- def read(conversation_id) = Record.new(@t.json("GET", "/v1/support/conversations/#{seg(conversation_id)}"))
433
- end
434
-
435
- # +sbx.network+: turn the sandbox's internet off or on, narrow it to a list,
436
- # refuse destinations, or open host:port pairs. Changes apply at once.
437
- class Network
438
- def initialize(sandbox)
439
- @sandbox = sandbox
440
- end
441
-
442
- def get = Record.new(@sandbox.transport.json("GET", @sandbox.path("/network")))
443
-
444
- # Replaces the rules: +internet:+, +allow:+ (example.com, *.example.com, an
445
- # address or a CIDR range), +deny:+, and +connect:+ (host:port pairs beyond
446
- # 80 and 443; paid accounts only). +internet: false+ with +allow:+ is
447
- # allow-list only, stored as +internet: true+ with that list.
448
- def set(internet:, allow: nil, deny: nil, connect: nil)
449
- body = { "internet" => internet, "allow" => allow, "deny" => deny, "connect" => connect }.compact
450
- Record.new(@sandbox.transport.json("PUT", @sandbox.path("/network"), body: body))
451
- end
452
-
453
- def off = set(internet: false)
454
- def on = set(internet: true)
455
- end
456
-
457
- # +sbx.interpreter+: stateful Python and JavaScript cells, like a notebook.
458
- class Interpreter
459
- RESULT = %r{\A/workspace/\.runtime/interpreter/([a-z0-9][a-z0-9-]*)/out/([A-Za-z0-9][A-Za-z0-9_.-]*)\z}
460
-
461
- def initialize(sandbox)
462
- @sandbox = sandbox
463
- end
464
-
465
- # Runs a cell. +language:+ is "python" (the default) or "javascript";
466
- # +context:+ is a context id. With +on_stdout+, +on_stderr+ or +on_result+,
467
- # output streams as it happens. Returns the execution: status (ok, error,
468
- # interrupted, timeout, lost), stdout, stderr, results and error.
469
- def run(code, language: nil, context: nil, timeout: nil, on_stdout: nil, on_stderr: nil, on_result: nil)
470
- body = { "code" => code, "language" => language, "context" => context,
471
- "timeoutMs" => timeout && (timeout * 1000).round }.compact
472
- return Record.new(t.json("POST", path(":run"), body: body)) unless on_stdout || on_stderr || on_result
473
-
474
- t.events("POST", path(":run"), body: body.merge("stream" => true)) do |event|
475
- case event["k"]
476
- when "stdout" then on_stdout&.call(event["text"])
477
- when "stderr" then on_stderr&.call(event["text"])
478
- when "result" then on_result&.call(Record.new(event))
479
- when "execution" then return Record.new(event["execution"])
480
- when "failure" then raise Error.new(event["message"], code: event["code"], hint: event["hint"])
481
- end
482
- end
483
- raise Error.new("The interpreter stream ended without a result.", code: "stream_failed")
484
- end
485
-
486
- def contexts = t.json("GET", path("/contexts"))["data"].map { |context| Record.new(context) }
487
-
488
- def create_context(id: nil, language: nil, cwd: nil, env: nil)
489
- Record.new(t.json("POST", path("/contexts"), body: Fields.body(id: id, language: language, cwd: cwd, env: env)))
490
- end
491
-
492
- def restart_context(id) = Record.new(t.json("POST", path("/contexts/#{Transport.segment(id)}:restart"), body: {}))
493
- def interrupt_context(id) = t.json("POST", path("/contexts/#{Transport.segment(id)}:interrupt"), body: {})["interrupted"] == true
494
- def remove_context(id) = t.json("DELETE", path("/contexts/#{Transport.segment(id)}"))["deleted"] == true
495
-
496
- # The bytes of a result too large to travel inline (a refs entry's path).
497
- def result(result_path)
498
- match = RESULT.match(result_path) or raise ArgumentError, "Not an interpreter result path."
499
- t.bytes("GET", path("/contexts/#{match[1]}/results/#{match[2]}"), accept: "application/octet-stream")
500
- end
501
-
502
- private
503
-
504
- def t = @sandbox.transport
505
- def path(suffix) = @sandbox.path("/interpreter#{suffix}")
506
- end
507
-
508
- # +sbx.desktop+: a Linux desktop in the sandbox, driven like a person would.
509
- # Coordinates are pixels from the top left of the screen.
510
- class Desktop
511
- def initialize(sandbox)
512
- @sandbox = sandbox
513
- end
514
-
515
- def recordings = Recordings.new(@sandbox)
516
-
517
- # Starts the desktop; +stream_url+ opens it live in a browser.
518
- def start(width: nil, height: nil)
519
- Record.new(t.json("POST", @sandbox.path("/desktop:start"), body: { "width" => width, "height" => height }.compact))
520
- end
521
-
522
- def stop = t.json("POST", @sandbox.path("/desktop:stop"), body: {}) && nil
523
-
524
- # PNG bytes, or JPEG with +format: "jpeg"+.
525
- def screenshot(format: nil, quality: nil)
526
- t.bytes("GET", @sandbox.path("/desktop/screenshot"), query: { "format" => format, "quality" => quality })
527
- end
528
-
529
- def move(x, y) = act("action" => "move", "x" => x, "y" => y)
530
- def click(x = nil, y = nil, button: nil, double: nil) = act({ "action" => "click", "x" => x, "y" => y, "button" => button, "double" => double }.compact)
531
- def double_click(x = nil, y = nil) = click(x, y, double: true)
532
- def right_click(x = nil, y = nil) = click(x, y, button: "right")
533
- def mouse_down(button = "left") = act("action" => "mouseDown", "button" => button)
534
- def mouse_up(button = "left") = act("action" => "mouseUp", "button" => button)
535
- def drag(from, to) = act("action" => "drag", "from" => from, "to" => to)
536
-
537
- # Wheel clicks: positive +dy+ scrolls down, positive +dx+ right.
538
- def scroll(dy, dx: nil, x: nil, y: nil) = act({ "action" => "scroll", "dy" => dy, "dx" => dx, "x" => x, "y" => y }.compact)
539
-
540
- def type(text, delay_ms: nil) = act({ "action" => "type", "text" => text, "delayMs" => delay_ms }.compact)
541
-
542
- # xdotool key names, space separated: "ctrl+l", "Return", "alt+Tab".
543
- def press(keys) = act("action" => "key", "keys" => keys)
544
-
545
- def cursor = act("action" => "cursor")
546
- def windows = act("action" => "windows")["windows"]
547
- def focus(window_id) = act("action" => "focus", "windowId" => window_id)
548
-
549
- # Opens +url+ in Firefox on the desktop.
550
- def open(url) = act("action" => "open", "url" => url)
551
-
552
- # Starts a program on the desktop, detached.
553
- def launch(*argv) = act("action" => "launch", "argv" => argv)
554
-
555
- private
556
-
557
- def t = @sandbox.transport
558
- def act(body) = Record.new(t.json("POST", @sandbox.path("/desktop:act"), body: body))
559
- end
560
- end
@@ -1,99 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module WithRuntime
4
- # An answer from the API: the whole JSON object, read by snake_case name
5
- # (+info.expires_at+, +info.memory_mib+) or by the API's own key
6
- # (+info["expiresAt"]+). A field newer than this SDK is always there.
7
- class Record
8
- attr_reader :to_h
9
-
10
- def initialize(hash)
11
- @to_h = (hash || {}).freeze
12
- @index = @to_h.keys.to_h { |key| [key.to_s.delete("_").downcase, key] }
13
- end
14
-
15
- def [](key) = @to_h[key.to_s]
16
-
17
- def key?(name) = @index.key?(name.to_s.delete("_").downcase)
18
-
19
- # A field by snake_case name; nil when the answer does not carry it, as a
20
- # missing key reads in the other SDKs.
21
- def method_missing(name, *args)
22
- return super unless args.empty? && name.match?(/\A[a-z][a-z0-9_]*\??\z/) && !name.start_with?("to_")
23
-
24
- key = @index[name.to_s.delete_suffix("?").delete("_").downcase]
25
- value = key && wrap(@to_h[key])
26
- name.end_with?("?") ? !!value : value
27
- end
28
-
29
- def respond_to_missing?(name, include_private = false)
30
- @index.key?(name.to_s.delete_suffix("?").delete("_").downcase) || super
31
- end
32
-
33
- def ==(other) = other.is_a?(Record) && other.to_h == to_h
34
-
35
- def to_s = JSON.generate(to_h)
36
-
37
- def inspect = "#<#{self.class.name} #{to_s}>"
38
-
39
- private
40
-
41
- def wrap(value)
42
- case value
43
- when Hash then Record.new(value)
44
- when Array then value.map { |item| wrap(item) }
45
- else value
46
- end
47
- end
48
- end
49
-
50
- # The files a traced command (+trace_files: true+) opened: +read+ is every
51
- # file and directory it, and anything it started, opened (sorted absolute
52
- # paths with links resolved, directories ending in "/"); +written+ every file
53
- # it wrote. +truncated+ means some paths are missing, so do not treat the
54
- # lists as complete.
55
- class TracedFiles < Record
56
- def read = self["read"] || []
57
- def written = self["written"] || []
58
- def truncated = self["truncated"] == true
59
- end
60
-
61
- # A finished command. A timeout is a result (+timed_out+), not an exception.
62
- class CommandResult < Record
63
- def exit_code = self["exitCode"]
64
- def stdout = self["stdout"] || ""
65
- def stderr = self["stderr"] || ""
66
- def timed_out = self["timedOut"] == true
67
- def ok? = !timed_out && exit_code == 0
68
-
69
- # The files it read and wrote when it ran with +trace_files: true+; nil otherwise.
70
- def files = self["files"] && TracedFiles.new(self["files"])
71
- end
72
-
73
- # One page of a list. +next_page+ reads the one after it; +each+ walks every
74
- # item on this page and on every page after it.
75
- class Page
76
- include Enumerable
77
- attr_reader :data, :next_cursor
78
-
79
- def initialize(data, next_cursor, &fetch)
80
- @data = data
81
- @next_cursor = next_cursor
82
- @fetch = fetch
83
- end
84
-
85
- def more? = !(next_cursor.nil? || next_cursor.empty?)
86
-
87
- def next_page = more? ? @fetch.call(next_cursor) : nil
88
-
89
- def each(&block)
90
- return enum_for(:each) unless block
91
-
92
- page = self
93
- while page
94
- page.data.each(&block)
95
- page = page.next_page
96
- end
97
- end
98
- end
99
- end