kosa8 0.5.2 → 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: 2e865379c864f1e968325212f3e06cb82056a58357aa06d0f443a651333d7928
4
- data.tar.gz: 340f70bfbb6ef787f0f506119462d2bf5b785a5eb546f21d645b54d7caf66621
3
+ metadata.gz: 399e180963efb7a9d1fb1d29e8e1ddb2421c85c9e7a3c866c33ed5b051573b23
4
+ data.tar.gz: fccb3c0575fd2c626c7a3e9015463af7bf49d0f136b130bb5bbb41cf96f843cf
5
5
  SHA512:
6
- metadata.gz: d8aa6298bb875c0914621763de073c5326811c7187928df33425f379a31561bc3078fee0366f91d0133dde7f787ac8e0672679f09d4c8f51f0c18388edf506a5
7
- data.tar.gz: bc7c0768719881ea2833e4ff81323a1b5bd4a7cf3fa5af1d268bb597dd377add42835445d80420354858ee5f7c38ae6bc4a5d620522d0528cd3805a4d86f7993
6
+ metadata.gz: c10b76ed210c9df1caa7282b701f6c6928e9e76670acb3e9fb76e74987f1bfc070c318c22cbdf7482d36b7a16da54a01f1f80ca6ac7a2f4d3030cc64ce5b7dd0
7
+ data.tar.gz: fb11e97557b979b5e5c92258a08dd80e41d832b3ad410d9df2a7db767b262b65586feb396642a14a5129c8598d08236ec20d1900ed7da89c644cede36cc9b7f4
data/README.md CHANGED
@@ -6,8 +6,8 @@ Method for method it matches [`@kosa8/sdk`](https://github.com/kosa8ai/kosa8-js)
6
6
  ## Quickstart: kosa8 Cloud
7
7
 
8
8
  ```sh
9
- gem install kosa8 -v 0.4.0
10
- # or in a Gemfile: gem "kosa8", "~> 0.5.0"
9
+ gem install kosa8
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") # only /workspace persists 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,17 +222,22 @@ 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
- - **Each `exec` runs in a fresh container, and only `/workspace` persists.** `cd`, `export` and anything
171
- installed outside `/workspace` (`apk add`, a system `pip install`) are gone by the next command. Install
172
- into `/workspace` (for example `pip install --target /workspace/lib ...` with `PYTHONPATH=/workspace/lib`),
173
- or chain the steps in one `sh -c`.
174
- - **A buffered `exec` runs at most 90 seconds** and raises `Kosa8::ExecTimeoutError`. Run long
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
229
+ `pip install --target /workspace/lib ...` with `PYTHONPATH=/workspace/lib`), chain the steps in one
230
+ `sh -c`, or create with `persistent: true` (one long-lived container) to keep the whole filesystem and
231
+ background processes; the code interpreter (`run_code`) needs it, and it counts against your plan's
232
+ persistent-sandbox limit.
233
+ - **A buffered `exec` runs at most 90 seconds** and raises `Kosa8::ExecTimeoutError`.
234
+ `box.exec(cmd, timeout_s: 30)` stops a command sooner, in the sandbox (1 to 90 whole seconds). Run long
175
235
  work in the background and poll it:
176
236
  `box.exec("nohup sh -c 'make test > /workspace/test.log 2>&1; echo $? > /workspace/test.exit' &")`.
177
237
  - A request body (command and env) is at most 64 KiB; a file read or write is at most 8 MiB.
178
238
  - Set `ttl_s:` (60 s to 90 days) or `delete_after:` (Unix ms) on create so a crashed script cannot leave a
179
239
  sandbox running. Bad values raise `ArgumentError` before any request.
180
- - 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.
181
241
 
182
242
  ### Cloud errors
183
243
 
@@ -187,10 +247,33 @@ Kosa8::Cloud.new(api_key: tok["secret"]) # hand this to your end user, not your
187
247
  | `Kosa8::OrgFrozenError` (423, `org_frozen`) | the org is frozen in the Security Center | an owner or admin unfreezes it; retrying does not help |
188
248
  | `Kosa8::RateLimitError` (429) | too many requests, or `quota_exceeded` (active sandbox limit) | wait `e.retry_after` seconds when set, or delete sandboxes |
189
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 |
190
- | `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 |
191
252
 
192
253
  Every Cloud error is a `Kosa8::ApiError` carrying the server's stable `e.code`, its message and `e.body`.
193
254
 
255
+ ## The same thing in each language
256
+
257
+ The five kosa8 SDKs (Python `kosa8`, JS `@kosa8/sdk`, Go `kosa8-go`, Ruby `kosa8`, Java
258
+ `com.kosa8:kosa8`) call the same kosa8 Cloud API, but some names differ by language. The ones
259
+ that catch people switching:
260
+
261
+ | | Python | JS / TS | Go | Ruby | Java |
262
+ |---|---|---|---|---|---|
263
+ | client | `Kosa8Cloud()` | `new Kosa8Cloud()` | `kosa8.NewCloud(kosa8.CloudOptions{})`, returns `(cloud, err)` | `Kosa8::Cloud.new` | `Kosa8Cloud.builder().build()` |
264
+ | lifetime on create | `ttl_s=3600` | `{ ttlS: 3600 }` | `CloudCreateOptions{TTLSeconds: 3600}` | `ttl_s: 3600` | `new CloudOptions.Create().ttlSeconds(3600)` |
265
+ | persistent sandbox | `persistent=True` | `{ persistent: true }` | `CloudCreateOptions{Persistent: true}` | `persistent: true` | `.persistent(true)` |
266
+ | sandbox id | `box.id` | `box.id` | `box.ID()`, a method (`fmt.Println(box.ID)` prints a func value; `go vet` reports it) | `box.id` | `box.id()` |
267
+ | shell command | `box.exec("ls /")` | `box.exec('ls /')` | `box.ExecShell(ctx, "ls /", nil)` | `box.exec("ls /")` | `box.exec("ls /")` |
268
+ | argv command | `box.exec(["ls", "/"])` | `box.exec(['ls', '/'])` | `box.Exec(ctx, []string{"ls", "/"}, nil)` | `box.exec(["ls", "/"])` | `box.exec(List.of("ls", "/"))` |
269
+ | per-exec timeout | `exec(cmd, timeout_s=30)` | `exec(cmd, { timeoutS: 30 })` | `&kosa8.CloudExecOptions{TimeoutS: 30}` | `exec(cmd, timeout_s: 30)` | `exec(cmd, null, null, 30)` |
270
+ | exit code | `r.exit_code` | `r.exitCode` | `r.ExitCode`, an `*int` (nil when the cloud sent none; `r.OK()` checks for 0) | `r.exit_code` | `r.exitCode()`, an `Integer` (may be null) |
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()` |
272
+ | no such sandbox | `Kosa8NotFoundError` | `Kosa8NotFoundError` | `*kosa8.Error` with `Kind` `KindNotFound` (`errors.Is(err, kosa8.ErrNotFound)`) | `Kosa8::NotFoundError` | `Kosa8Exception.NotFoundException` |
273
+
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`.
276
+
194
277
  ## Local daemon
195
278
 
196
279
  ```ruby
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
@@ -249,7 +265,9 @@ module Kosa8
249
265
  message = (msg_body.is_a?(Hash) ? msg_body["error"] : msg_body).to_s
250
266
  e = if exec_timeout?(status, code, message, path)
251
267
  said = message.empty? ? nil : message
252
- ExecTimeoutError.new("#{said || "request failed with HTTP #{status}"} (#{EXEC_HINT})",
268
+ # Its own timeout_s (exec(..., timeout_s:)) needs no hint about the 90 s limit.
269
+ hint = message.include?("timeout_s") ? "" : " (#{EXEC_HINT})"
270
+ ExecTimeoutError.new("#{said || "request failed with HTTP #{status}"}#{hint}",
253
271
  status: status, daemon_message: said, method: method, path: path,
254
272
  code: code || "exec_timeout")
255
273
  else
@@ -258,7 +276,10 @@ module Kosa8
258
276
  e.instance_variable_set(:@body, body)
259
277
  e.retry_after = retry_after(headers)
260
278
  if e.retry_after.nil? && body.is_a?(Hash)
261
- 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?
262
283
  e.retry_after = ra.to_f if ra.is_a?(Numeric) && ra.positive?
263
284
  end
264
285
  e.request_id = header(headers, "x-request-id") || header(headers, "cf-ray")
@@ -476,6 +497,11 @@ module Kosa8
476
497
  # data plane. On hosts without it the API answers 501 (not_available /
477
498
  # not_supported), raised as Kosa8::UnsupportedError; not every kosa8 Cloud
478
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.
479
505
  class CloudSandbox
480
506
  attr_reader :info
481
507
 
@@ -499,17 +525,25 @@ module Kosa8
499
525
  # Run a command and wait for it. A String runs through sh -c, an Array is
500
526
  # the argv. A sleeping sandbox wakes for it.
501
527
  #
502
- # Each exec runs in a fresh container: only /workspace persists, so cd,
503
- # export and packages installed elsewhere are gone by the next one. kosa8
504
- # Cloud stops a buffered exec after 90 s, raised as
505
- # Kosa8::ExecTimeoutError; run long work in the background
506
- # (nohup sh -c '...' > /workspace/job.log 2>&1 &) and poll it. The request
528
+ # Only /workspace is sure to persist: an exec may run in a fresh
529
+ # container (unless the sandbox is persistent), so cd, export and packages
530
+ # installed elsewhere may be gone by the next one. kosa8 Cloud stops a
531
+ # buffered exec after 90 s, raised as Kosa8::ExecTimeoutError; run long
532
+ # work in the background (nohup sh -c '...' > /workspace/job.log 2>&1 &)
533
+ # and poll it. +timeout_s+ (1 to 90 whole seconds) stops the command in
534
+ # the sandbox sooner, also as Kosa8::ExecTimeoutError. The request
507
535
  # (command and env) is at most 64 KiB (413 too_large).
508
- def exec(cmd, image: nil, env: nil)
536
+ def exec(cmd, image: nil, env: nil, timeout_s: nil)
509
537
  argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
510
538
  body = { "cmd" => argv }
511
539
  body["image"] = image unless image.nil?
512
540
  body["env"] = env.map { |k, v| "#{k}=#{v}" } if env && !env.empty?
541
+ unless timeout_s.nil?
542
+ unless timeout_s.is_a?(Integer) && timeout_s.between?(1, Cloud::EXEC_LIMIT_S)
543
+ raise ArgumentError, "timeout_s must be a whole number of seconds from 1 to #{Cloud::EXEC_LIMIT_S}"
544
+ end
545
+ body["timeout_s"] = timeout_s
546
+ end
513
547
  r = @cloud.request("POST", path("/exec"), body)
514
548
  fc, rt = Kosa8.exec_failure(r["exit"])
515
549
  fc = r["failure_class"] if r["failure_class"].is_a?(String)
@@ -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