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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2f844e8a5a44b134b65d86679d015a5a2e631239d938df854d745b393a2b99bb
4
- data.tar.gz: a3b44827f4db786bc9c798c46f13fbfd1aa7c6e593abcda6362bb1900da8d65f
3
+ metadata.gz: 399e180963efb7a9d1fb1d29e8e1ddb2421c85c9e7a3c866c33ed5b051573b23
4
+ data.tar.gz: fccb3c0575fd2c626c7a3e9015463af7bf49d0f136b130bb5bbb41cf96f843cf
5
5
  SHA512:
6
- metadata.gz: 3e661816f8189fa290867c4a3d039a2a8250d6a07083797f5c2202838e3a4b11c843e6a86d31af06ec8871d2dfc1be6e931e3cf4d2e1eac165ebbf6885264014
7
- data.tar.gz: 550fa6e4c577c0482ec897842ea7334a34429784ebbaafc831e4f0758d75a557a28df71cb4f2f5e6ccc2950f6bf679122f75c33c0c3d33578fdfad73cd6a3c56
6
+ metadata.gz: c10b76ed210c9df1caa7282b701f6c6928e9e76670acb3e9fb76e74987f1bfc070c318c22cbdf7482d36b7a16da54a01f1f80ca6ac7a2f4d3030cc64ce5b7dd0
7
+ data.tar.gz: fb11e97557b979b5e5c92258a08dd80e41d832b3ad410d9df2a7db767b262b65586feb396642a14a5129c8598d08236ec20d1900ed7da89c644cede36cc9b7f4
data/README.md CHANGED
@@ -7,7 +7,7 @@ Method for method it matches [`@kosa8/sdk`](https://github.com/kosa8ai/kosa8-js)
7
7
 
8
8
  ```sh
9
9
  gem install kosa8
10
- # or in a Gemfile: gem "kosa8", "~> 0.5"
10
+ # or in a Gemfile: gem "kosa8", "~> 0.6"
11
11
  export KOSA8_API_KEY=k8c_live_... # made in the cloud dashboard
12
12
  ```
13
13
 
@@ -20,7 +20,7 @@ box = cloud.sandboxes.create(template: "python", ttl_s: 3600) # deleted automat
20
20
  r = box.exec(["python3", "-c", "print(6 * 7)"])
21
21
  puts r.exit_code, r.stdout # 0, 42
22
22
 
23
- box.exec("echo hello > /workspace/hello.txt") # /workspace is kept between commands
23
+ box.exec("echo hello > /workspace/hello.txt") # files in /workspace last for the sandbox's life
24
24
  puts box.exec("cat /workspace/hello.txt").stdout
25
25
 
26
26
  box.files.write("/workspace/app.py", "print('hi')\n") # needs the host's data plane (see below)
@@ -34,6 +34,19 @@ box.delete
34
34
  `cloud.templates` lists the templates your org can start. Without `template:` you get the org's
35
35
  default, `base` (see below).
36
36
 
37
+ The smallest sandbox is a quarter of a vCPU and 512 MB, for fleets of mostly idle sandboxes (RL
38
+ rollouts, evals). It reserves 0.25 vCPU and bursts while the host has idle CPU:
39
+
40
+ ```ruby
41
+ box = cloud.sandboxes.create(cpus: 0.25, mem_mb: 512, ttl_s: 600) # or size: "0.25x0.5"
42
+ puts box.exec("echo hi").stdout
43
+ box.delete
44
+ ```
45
+
46
+ The small sizes are `0.25x0.5`, `0.5x1` and `1x2` (`Kosa8::Cloud::SMALL_SIZES`); the standard ones
47
+ are `2x4`, `4x8`, `8x16` and `16x32`. A host that does not run small sizes answers 501
48
+ `not_available` (`Kosa8::UnsupportedError`).
49
+
37
50
  ### More of the Cloud API
38
51
 
39
52
  ```ruby
@@ -106,6 +119,46 @@ box.terminal(cols: 120, rows: 40)["url"] # a wss:// PTY URL
106
119
  `code_contexts`, `create_code_context`, `reset_code_context`, `delete_code_context`.
107
120
  - `schedules.create(cron: "0 * * * *", cmd: "date")`, `list`, `run`, `delete`.
108
121
  - `metrics`, `logs(limit:)`, `set_labels`, `secrets`; `cloud.capabilities`.
122
+ - `stop_background(exec_id)`; `previews.delete(port)`, `previews.domains(port)` (custom domains:
123
+ `add`, `list`, `get`, `remove`; also `cloud.preview_domains(preview_id)`).
124
+ - `embeds.create(origins: ["https://app.example.com"])` (a signed iframe URL for its terminal or
125
+ desktop), `embeds.list`, `embeds.revoke`; `recordings` (with `create(record: true)`).
126
+
127
+ ### Browsers, AI gateway, jobs and more
128
+
129
+ ```ruby
130
+ # A headless browser ($0.12 per browser-hour, billed per second), closed when the block ends.
131
+ cloud.browser(ttl_s: 120) do |b|
132
+ File.binwrite("page.png", b.screenshot("https://example.com"))
133
+ puts b.goto("https://example.com")["title"]
134
+ b.cdp_url # wss://... for any CDP client (valid 10 minutes; b.refresh for a fresh one)
135
+ end
136
+
137
+ # The AI gateway: provider keys stay on kosa8 Cloud; sandboxes made with ai_gateway: true get
138
+ # OPENAI_BASE_URL and ANTHROPIC_BASE_URL pointed at it.
139
+ cloud.ai.set_key("openai", File.read("openai.key").strip)
140
+ cloud.ai.gateway_url("openai") # https://api.kosa8.com/v1/ai/gw/openai, for an OpenAI client
141
+ cloud.ai.call("openai", "chat/completions", { "model" => "gpt-4o-mini", "messages" => [...] })
142
+ cloud.ai.usage("2026-11")
143
+
144
+ # A hosted job: every task in its own sandbox, solver then sealed grader, rollouts recorded.
145
+ job = cloud.jobs.submit(name: "eval-1", template: "python", tasks: File.read("tasks.jsonl"),
146
+ solver: "python /workspace/solve.py", solver_timeout_s: 300,
147
+ grader: { cmd: %w[python /grader/grade.py], files: { "/grader/grade.py" => File.read("grade.py") } },
148
+ budget_usd: 5)
149
+ cloud.jobs.wait(job["id"]) { |j| puts j["progress"] } # also estimate, list, get, cancel
150
+ ```
151
+
152
+ - `cloud.benchmarks`: `list`, `get`, `instances(name, state:)`, `instance`, `prepare`; create from an
153
+ instance with `template: "<benchmark>/<instance id>"`.
154
+ - `cloud.rl_compare("run_a", "run_b")`; `cloud.rl_alerts`: `list`, `create(kind:, threshold:)`,
155
+ `update`, `delete`.
156
+ - `cloud.usage`, `usage_insights`, `limits`, `request_limit`, `pricing`, `lineage`, `checkpoints`
157
+ (every sandbox's), `images`, `org_egress` / `set_org_egress`.
158
+ - `cloud.audit`: `list`, `each`, `verify`, `export`; `cloud.api_keys`: `list`, `create`, `rotate`,
159
+ `revoke`; `cloud.webhooks`: `list`, `create`, `delete`, `deliveries`, `test`.
160
+ - `cloud.recordings` (`list`, `link`, `delete`), `cloud.burst` (`get`, `activate`),
161
+ `cloud.functions.invocations(name)`, `cloud.attack_scorecards`.
109
162
 
110
163
  ### Secrets and Pipelines
111
164
 
@@ -148,11 +201,13 @@ Kosa8::RL::Run.open(cloud, "grpo-1", lease_s: 600) do |run|
148
201
  end
149
202
  ```
150
203
 
151
- Create, batch, fork and grade send an `Idempotency-Key` (a UUID, or `idempotency_key:`) that every
152
- retry reuses, so a retry after a timeout never doubles the fleet. Retries (`Kosa8::RetryPolicy`:
153
- 3 tries, backoff with full jitter, at least Retry-After) apply only where safe; every error has
154
- `failure_class` (`ok`, `exit_nonzero`, `timeout`, `infra`, `quota`, `client`, `error`) and
155
- `retryable?`.
204
+ Create, batch, fork, grade, job submits and rollout records send an `Idempotency-Key` (a UUID, or
205
+ `idempotency_key:`) that every retry reuses, so a retry after a timeout never doubles the fleet.
206
+ Retries (`Kosa8::RetryPolicy`: 3 tries, backoff with full jitter, at least the server's Retry-After or
207
+ `retry_after`) apply only where safe: reads, PUTs and deletes, keyed POSTs, and any request the server
208
+ refused before running it (429, 503 `database_busy`, 409 `template_building`). An answer marked
209
+ `retryable: false` is never retried. Every error has `failure_class` (`ok`, `exit_nonzero`, `timeout`,
210
+ `oom`, `infra`, `quota`, `client`, `error`) and `retryable?`.
156
211
 
157
212
  ```ruby
158
213
  cloud.org_templates.build("swe-task-1", image: "ghcr.io/org/task@sha256:...") # kept as a snapshot
@@ -167,9 +222,10 @@ Kosa8::Cloud.new(api_key: tok["secret"]) # hand this to your end user, not your
167
222
 
168
223
  - The `base` template is **Alpine Linux**: `sh` is busybox, and there is no `bash`, `python` or `git`.
169
224
  Use `template: "python"` (or another key from `cloud.templates`) for Python, or pass `image:` to `exec`.
170
- - **Only `/workspace` is sure to persist between commands.** A command may run in a fresh container, so
171
- `cd`, `export`, processes it leaves running and anything installed outside `/workspace` (`apk add`, a
172
- system `pip install`) may be gone by the next command. Install into `/workspace` (for example
225
+ - **Each exec is a fresh process; files in `/workspace` persist for the sandbox's life; installed
226
+ packages need `persistent: true`.** `cd` and `export` do not carry over, and a command may run in a
227
+ fresh container that shares only `/workspace`, so processes it leaves running and anything installed
228
+ outside `/workspace` (`apk add`, a system `pip install`) may be gone by the next command. Install into `/workspace` (for example
173
229
  `pip install --target /workspace/lib ...` with `PYTHONPATH=/workspace/lib`), chain the steps in one
174
230
  `sh -c`, or create with `persistent: true` (one long-lived container) to keep the whole filesystem and
175
231
  background processes; the code interpreter (`run_code`) needs it, and it counts against your plan's
@@ -181,7 +237,7 @@ Kosa8::Cloud.new(api_key: tok["secret"]) # hand this to your end user, not your
181
237
  - A request body (command and env) is at most 64 KiB; a file read or write is at most 8 MiB.
182
238
  - Set `ttl_s:` (60 s to 90 days) or `delete_after:` (Unix ms) on create so a crashed script cannot leave a
183
239
  sandbox running. Bad values raise `ArgumentError` before any request.
184
- - The Cloud API has no sandbox labels or metadata.
240
+ - Sandboxes take `name:` and `labels:` on create (`set_labels` later); `list(labels: {...})` filters by them.
185
241
 
186
242
  ### Cloud errors
187
243
 
@@ -191,7 +247,8 @@ Kosa8::Cloud.new(api_key: tok["secret"]) # hand this to your end user, not your
191
247
  | `Kosa8::OrgFrozenError` (423, `org_frozen`) | the org is frozen in the Security Center | an owner or admin unfreezes it; retrying does not help |
192
248
  | `Kosa8::RateLimitError` (429) | too many requests, or `quota_exceeded` (active sandbox limit) | wait `e.retry_after` seconds when set, or delete sandboxes |
193
249
  | `Kosa8::ExecTimeoutError` (504 `exec_timeout`, or today's 502 "timed out" on exec) | a buffered exec ran past its 90 s limit | run it in the background and poll |
194
- | `Kosa8::UnsupportedError` (501) | the host has no data plane yet (files, checkpoints, rewind, fork, ports) | use `exec`, or try later |
250
+ | `Kosa8::UnsupportedError` (501) | the host has no data plane yet (files, checkpoints, rewind, fork, ports), or the sandbox runs on overflow capacity (Cloudflare), which has no fork, checkpoint or sleep | use `exec`, or create it on a kosa8 host (a template, or a size such as `2x4`) |
251
+ | `Kosa8::ApiError` (503 `database_busy`, 409 `template_building`) | the API's database was overloaded, or a benchmark environment is still building | retried for you (Retry-After); if it still fails, try again later |
195
252
 
196
253
  Every Cloud error is a `Kosa8::ApiError` carrying the server's stable `e.code`, its message and `e.body`.
197
254
 
@@ -214,8 +271,8 @@ that catch people switching:
214
271
  | files | `box.files.write` / `read_text` / `list` | `box.files.write` / `readText` / `list` | `box.Files().WriteString` / `ReadText` / `List(ctx, "")` | `box.files.write` / `read_text` / `list` | `box.files().write` / `readText` / `list()` |
215
272
  | no such sandbox | `Kosa8NotFoundError` | `Kosa8NotFoundError` | `*kosa8.Error` with `Kind` `KindNotFound` (`errors.Is(err, kosa8.ErrNotFound)`) | `Kosa8::NotFoundError` | `Kosa8Exception.NotFoundException` |
216
273
 
217
- In every SDK a non-zero exit is returned in the result, not raised. Only `/workspace` is sure to
218
- persist between commands, unless the sandbox is persistent.
274
+ In every SDK a non-zero exit is returned in the result, not raised. Each exec is a fresh process;
275
+ files in `/workspace` persist for the sandbox's life; installed packages need `persistent: true`.
219
276
 
220
277
  ## Local daemon
221
278
 
data/lib/kosa8/cloud.rb CHANGED
@@ -45,9 +45,10 @@ module Kosa8
45
45
  # Errors are the SDK's usual typed errors; each carries the cloud's stable
46
46
  # +code+ (for example payment_required, quota_exceeded). Standard library only.
47
47
  #
48
- # Each exec runs in a fresh container and only /workspace persists; a
49
- # buffered exec runs at most 90 s (ExecTimeoutError), and a request
50
- # body is at most 64 KiB.
48
+ # Each exec is a fresh process; files in /workspace persist for the
49
+ # sandbox's life; installed packages need persistent: true. A buffered
50
+ # exec runs at most 90 s (ExecTimeoutError), and a request body is at
51
+ # most 64 KiB.
51
52
  class Cloud
52
53
  DEFAULT_URL = "https://api.kosa8.com"
53
54
  KEY_PREFIX = "k8c_live_"
@@ -86,9 +87,12 @@ module Kosa8
86
87
  # retry_policy: (default RetryPolicy.new: 3 tries, backoff with full
87
88
  # jitter) is applied where trying again is safe: reads, PUTs, deletes,
88
89
  # heartbeats and drains on infra failures; the calls that make sandboxes
89
- # (create, batch, fork, grade), which carry an Idempotency-Key reused on
90
- # every retry; and any request answered 429, waiting at least its
91
- # Retry-After. RetryPolicy::NONE turns it off. sleeper: replaces
90
+ # (create, batch, fork, grade), job submits and rollout records, which
91
+ # carry an Idempotency-Key reused on every retry; and any request the
92
+ # server refused before running it (429, 503 database_busy, 409
93
+ # template_building), waiting at least its Retry-After (or the body's
94
+ # retry_after / retry_after_s). An answer with retryable: false is never
95
+ # retried. RetryPolicy::NONE turns it off. sleeper: replaces
92
96
  # Kernel#sleep for those waits (tests).
93
97
  def initialize(api_key: nil, base_url: nil, env: ENV, timeout: 120, transport: nil, retry_policy: nil,
94
98
  sleeper: nil)
@@ -154,12 +158,18 @@ module Kosa8
154
158
  perform(method, path, nil, data, raw, nil, retry_policy)
155
159
  end
156
160
 
157
- # Methods safe to send twice. Other POSTs are retried only on 429 (refused
158
- # before anything was done), unless they carry an Idempotency-Key.
161
+ # Methods safe to send twice. Other POSTs are retried only when the
162
+ # server refused them before doing anything (PRE_EXECUTION_CODES, any
163
+ # 429), unless they carry an Idempotency-Key.
159
164
  IDEMPOTENT_METHODS = %w[GET HEAD PUT DELETE].freeze
160
165
  IDEMPOTENT_POSTS = %w[/v1/sandboxes/heartbeat /v1/sandboxes/drain].freeze
166
+ # Refusals made before the request ran, so any request may be sent again:
167
+ # 503 database_busy (the API's database was overloaded) and 409
168
+ # template_building (the environment is still being built). Both carry
169
+ # retryable: true and when to try again (retry_after / Retry-After).
170
+ PRE_EXECUTION_CODES = %w[database_busy template_building].freeze
161
171
  # The POSTs kosa8 Cloud keeps an Idempotency-Key for (24 hours).
162
- KEYED_POSTS = %r{\A/v1/sandboxes(/batch|/[A-Za-z0-9_%]{1,64}/(fork|grade))?\z}.freeze
172
+ KEYED_POSTS = %r{\A/v1/(sandboxes(/batch|/[A-Za-z0-9_%]{1,64}/(fork|grade))?|jobs|rl/runs/[A-Za-z0-9_%]{1,64}/rollouts)\z}.freeze
163
173
  IDEMPOTENCY_KEY = /\A[\x21-\x7e]{1,255}\z/.freeze
164
174
 
165
175
  # Whether kosa8 Cloud honours an Idempotency-Key on this call.
@@ -167,6 +177,12 @@ module Kosa8
167
177
  method == "POST" && KEYED_POSTS.match?(path.to_s.split("?", 2)[0])
168
178
  end
169
179
 
180
+ # Whether +e+ is a refusal made before the request ran (any 429, 503
181
+ # database_busy, 409 template_building), so even a POST may be resent.
182
+ def self.pre_execution?(e)
183
+ e.is_a?(Error) && (e.status == 429 || PRE_EXECUTION_CODES.include?(e.code))
184
+ end
185
+
170
186
  def self.check_idempotency_key(key)
171
187
  return if key.nil? || (key.is_a?(String) && IDEMPOTENCY_KEY.match?(key))
172
188
 
@@ -187,7 +203,7 @@ module Kosa8
187
203
  begin
188
204
  return perform_once(method, path, body, data, raw, extra)
189
205
  rescue Error => e
190
- raise unless policy.retry?(e, attempt) && (safe || e.status == 429)
206
+ raise unless policy.retry?(e, attempt) && (safe || Cloud.pre_execution?(e))
191
207
 
192
208
  @sleeper.call(policy.delay(e, attempt))
193
209
  attempt += 1
@@ -260,7 +276,10 @@ module Kosa8
260
276
  e.instance_variable_set(:@body, body)
261
277
  e.retry_after = retry_after(headers)
262
278
  if e.retry_after.nil? && body.is_a?(Hash)
263
- ra = body["retry_after_s"] # e.g. 409 idempotency_in_progress, 503 no_capacity
279
+ # e.g. 409 idempotency_in_progress, 503 no_capacity (retry_after_s),
280
+ # 503 database_busy (retry_after too).
281
+ ra = body["retry_after_s"]
282
+ ra = body["retry_after"] unless ra.is_a?(Numeric) && ra.positive?
264
283
  e.retry_after = ra.to_f if ra.is_a?(Numeric) && ra.positive?
265
284
  end
266
285
  e.request_id = header(headers, "x-request-id") || header(headers, "cf-ray")
@@ -478,6 +497,11 @@ module Kosa8
478
497
  # data plane. On hosts without it the API answers 501 (not_available /
479
498
  # not_supported), raised as Kosa8::UnsupportedError; not every kosa8 Cloud
480
499
  # host has it yet.
500
+ #
501
+ # A sandbox kosa8 placed on its overflow capacity (Cloudflare) has no
502
+ # fork, checkpoint, rewind or sleep: those answer 501 not_available, raised
503
+ # as Kosa8::UnsupportedError with the server's sentence. The SDK does not
504
+ # retry or imitate them.
481
505
  class CloudSandbox
482
506
  attr_reader :info
483
507
 
@@ -10,8 +10,17 @@ require "uri"
10
10
  # Kosa8::UnsupportedError; Cloud#capabilities says what the org can do.
11
11
  module Kosa8
12
12
  class Cloud
13
- # The sizes a sized create takes: vCPU x GiB.
13
+ # The standard sizes (vCPU x GiB), which every sized call takes
14
+ # (sandboxes, org templates, pipelines).
14
15
  SIZES = %w[2x4 4x8 8x16 16x32].freeze
16
+ # Small sizes, for fleets of mostly idle sandboxes (RL rollouts, evals):
17
+ # a fraction of a vCPU reserved, bursting while the host has idle CPU.
18
+ # Only a sandbox create takes them, and only hosts that run them (else
19
+ # 501 not_available, Kosa8::UnsupportedError). As cpus:/mem_mb:
20
+ # 0.25/512, 0.5/1024, 1/2048.
21
+ SMALL_SIZES = %w[0.25x0.5 0.5x1 1x2].freeze
22
+ # Every size a sandbox create takes.
23
+ SANDBOX_SIZES = (SMALL_SIZES + SIZES).freeze
15
24
  ENV_NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/.freeze
16
25
  SANDBOX_NAME = /\A[A-Za-z0-9][A-Za-z0-9._-]{0,63}\z/.freeze
17
26
  SNAPSHOT_ID = /\Asnap_[A-Za-z0-9]{8,40}\z/.freeze
@@ -91,8 +100,9 @@ module Kosa8
91
100
  # Start a sandbox. Besides template:, region:, sleep_after_s:, ttl_s:,
92
101
  # delete_after: and accept_price:
93
102
  #
94
- # - size: "2x4", "4x8", "8x16" or "16x32" (vCPU x GiB), or cpus: and
95
- # mem_mb:; image: an OCI image (such as
103
+ # - size: "2x4", "4x8", "8x16" or "16x32" (vCPU x GiB), a small size
104
+ # "0.25x0.5", "0.5x1" or "1x2" (Cloud::SMALL_SIZES), or cpus: and
105
+ # mem_mb: (cpus: 0.25, mem_mb: 512 is the smallest); image: an OCI image (such as
96
106
  # "kosa8-template/universal-24.04-20261115.2"); disk_gb: 8..200. Any of
97
107
  # these boots the sandbox cold at that size: create waits for it to
98
108
  # run unless wait: false (then call #wait_running).
@@ -102,6 +112,9 @@ module Kosa8
102
112
  # - name:, labels: (up to 16), env: (given to every command; values are
103
113
  # never logged or returned), secrets: (names from cloud.secrets),
104
114
  # egress: ({internet:, allow:, deny:, presets:}).
115
+ # - record: true saves its desktop as an MP4 to cloud.recordings when
116
+ # it is deleted; ai_gateway: true points OPENAI_BASE_URL,
117
+ # ANTHROPIC_BASE_URL and the like at the org's AI gateway (cloud.ai).
105
118
  # - snapshot: "snap_..." starts it from a durable snapshot; then give
106
119
  # only env:, name:, labels:, a lifetime or sleep_after_s:.
107
120
  #
@@ -116,12 +129,12 @@ module Kosa8
116
129
  def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil,
117
130
  size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil, persistent: nil, docker: nil, cpu: nil,
118
131
  name: nil, labels: nil, env: nil, secrets: nil, egress: nil, snapshot: nil, wait: true,
119
- poll_interval: 1, lease_s: nil, run_id: nil, idempotency_key: nil)
132
+ poll_interval: 1, lease_s: nil, run_id: nil, idempotency_key: nil, record: nil, ai_gateway: nil)
120
133
  body = create_body(template: template, region: region, sleep_after_s: sleep_after_s, ttl_s: ttl_s,
121
134
  delete_after: delete_after, accept_price: accept_price, size: size, cpus: cpus,
122
135
  mem_mb: mem_mb, image: image, disk_gb: disk_gb, persistent: persistent, docker: docker,
123
136
  cpu: cpu, name: name, labels: labels, env: env, secrets: secrets, egress: egress,
124
- snapshot: snapshot)
137
+ snapshot: snapshot, record: record, ai_gateway: ai_gateway)
125
138
  amb = @cloud.run_defaults || {}
126
139
  run_id = amb["run_id"] if run_id.nil?
127
140
  if lease_s.nil? && ttl_s.nil? && delete_after.nil?
@@ -147,7 +160,7 @@ module Kosa8
147
160
  def create_body(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil,
148
161
  accept_price: nil, size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil,
149
162
  persistent: nil, docker: nil, cpu: nil, name: nil, labels: nil, env: nil, secrets: nil,
150
- egress: nil, snapshot: nil)
163
+ egress: nil, snapshot: nil, record: nil, ai_gateway: nil)
151
164
  Cloud.check_lifetime(ttl_s, delete_after)
152
165
  Cloud.check_sleep_after(sleep_after_s)
153
166
  if !accept_price.nil? && !accept_price.is_a?(Numeric)
@@ -171,6 +184,8 @@ module Kosa8
171
184
  body["env"] = Cloud.check_env(env) unless env.nil?
172
185
  body["secrets"] = secrets.to_a.map { |n| Cloud.check_secret_name(n) } unless secrets.nil?
173
186
  body["egress"] = Cloud.egress_body(egress) unless egress.nil?
187
+ body["record"] = record == true unless record.nil?
188
+ body["ai_gateway"] = ai_gateway == true unless ai_gateway.nil?
174
189
  unless snapshot.nil?
175
190
  raise ArgumentError, "snapshot: is a snapshot id (snap_...)" unless Cloud::SNAPSHOT_ID.match?(snapshot.to_s)
176
191
 
@@ -212,7 +227,9 @@ module Kosa8
212
227
 
213
228
  def sized(body, size, cpus, mem_mb, image, disk_gb, persistent, docker, cpu)
214
229
  unless size.nil?
215
- raise ArgumentError, "size must be one of #{Cloud::SIZES.join(', ')}" unless Cloud::SIZES.include?(size.to_s)
230
+ unless Cloud::SANDBOX_SIZES.include?(size.to_s)
231
+ raise ArgumentError, "size must be one of #{Cloud::SANDBOX_SIZES.join(', ')}"
232
+ end
216
233
 
217
234
  body["size"] = size.to_s
218
235
  end
@@ -220,8 +237,12 @@ module Kosa8
220
237
 
221
238
  unless cpus.nil?
222
239
  raise ArgumentError, "give size: or cpus: and mem_mb:, not both" unless size.nil?
240
+ unless cpus.is_a?(Numeric) && cpus.positive?
241
+ raise ArgumentError, "cpus must be a positive number (0.25, 0.5, 1, 2, 4, 8 or 16)"
242
+ end
223
243
 
224
- body["cpus"] = Integer(cpus)
244
+ # 0.25 and 0.5 are sent as they are; a whole number as an Integer.
245
+ body["cpus"] = cpus == cpus.to_i ? cpus.to_i : cpus.to_f
225
246
  body["mem_mb"] = Integer(mem_mb)
226
247
  end
227
248
  body["image"] = image.to_s unless image.nil?
@@ -274,7 +295,17 @@ module Kosa8
274
295
  def background_exec(exec_id)
275
296
  raise ArgumentError, "background_exec needs an exec id (bg_...)" if exec_id.nil? || exec_id.to_s.empty?
276
297
 
277
- @cloud.request("GET", path("/exec/#{Kosa8.enc(exec_id)}"))["exec"]
298
+ @cloud.request("GET", "/v1/sandboxes/#{Kosa8.enc(id)}/exec/#{Kosa8.enc(exec_id)}")["exec"]
299
+ end
300
+
301
+ # Stop a background command and what it started (SIGTERM, then SIGKILL
302
+ # after 5 s); returns the command as it now is.
303
+ def stop_background(exec_id)
304
+ exec_id = exec_id["id"] if exec_id.is_a?(Hash)
305
+ raise ArgumentError, "stop_background needs an exec id (bg_...)" if exec_id.nil? || exec_id.to_s.empty?
306
+
307
+ r = @cloud.request("POST", "/v1/sandboxes/#{Kosa8.enc(id)}/exec/#{Kosa8.enc(exec_id)}/stop", {})
308
+ r.is_a?(Hash) ? (r["exec"] || r) : {}
278
309
  end
279
310
 
280
311
  # Poll a background command until it exits; returns it.
@@ -370,7 +401,7 @@ module Kosa8
370
401
  end
371
402
 
372
403
  def delete_code_context(name)
373
- @cloud.request("DELETE", path("/code/contexts/#{Kosa8.enc(name)}"))
404
+ @cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(id)}/code/contexts/#{Kosa8.enc(name)}")
374
405
  nil
375
406
  end
376
407
 
@@ -462,7 +493,7 @@ module Kosa8
462
493
  end
463
494
 
464
495
  def delete(port)
465
- @cloud.request("DELETE", @sandbox.path("/previews/#{check(port)}"))
496
+ @cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/previews/#{check(port)}")
466
497
  nil
467
498
  end
468
499
 
@@ -503,7 +534,7 @@ module Kosa8
503
534
  end
504
535
 
505
536
  def delete(id)
506
- @cloud.request("DELETE", @sandbox.path("/schedules/#{Kosa8.enc(id)}"))
537
+ @cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/schedules/#{Kosa8.enc(id)}")
507
538
  nil
508
539
  end
509
540
 
@@ -657,7 +688,8 @@ module Kosa8
657
688
 
658
689
  # One artifact's bytes (a .tar.gz), as a binary String.
659
690
  def download_artifact(id, job, idx)
660
- @cloud.request_bytes("GET", run_path(id, "/artifacts/#{Kosa8.enc(job)}/#{Integer(idx)}"), raw: true)
691
+ @cloud.request_bytes("GET", "/v1/pipelines/runs/#{Kosa8.enc(id)}/artifacts/#{Kosa8.enc(job)}/#{Integer(idx)}",
692
+ raw: true)
661
693
  end
662
694
 
663
695
  # A webhook URL for a repository's pushes and pull requests, and with