kosa8 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 399e180963efb7a9d1fb1d29e8e1ddb2421c85c9e7a3c866c33ed5b051573b23
4
- data.tar.gz: fccb3c0575fd2c626c7a3e9015463af7bf49d0f136b130bb5bbb41cf96f843cf
3
+ metadata.gz: 9a50144be68b53047784290bcf9844f848024f95eb60c0774dc4b3161460facd
4
+ data.tar.gz: d58ec88f79ad342a504248d6f9075de75be797839e518fb8d45d9be57279583f
5
5
  SHA512:
6
- metadata.gz: c10b76ed210c9df1caa7282b701f6c6928e9e76670acb3e9fb76e74987f1bfc070c318c22cbdf7482d36b7a16da54a01f1f80ca6ac7a2f4d3030cc64ce5b7dd0
7
- data.tar.gz: fb11e97557b979b5e5c92258a08dd80e41d832b3ad410d9df2a7db767b262b65586feb396642a14a5129c8598d08236ec20d1900ed7da89c644cede36cc9b7f4
6
+ metadata.gz: e3d17ad9b172436e8fa3b639709317a6dc10be5cebfb31f90c4afaf35e13314267b8ecab8e3b6fcee60288bf691e802b4c24f9d5cc47e3a29ee6496936f385e5
7
+ data.tar.gz: 5492189821d7ba825656304f9e2f0d74e0989d4331d96dea35adeeeda607c4e4fff1a56574918e6ad8d3f535db78d08bbe59262a51c896707a63ecd891a223b0
data/CHANGELOG.md ADDED
@@ -0,0 +1,246 @@
1
+ # Changelog
2
+
3
+ ## 0.7.0 - 2026-11-23
4
+
5
+ - RL rollouts: each flushed chunk carries an Idempotency-Key that stays with those rows until
6
+ kosa8 Cloud answers, so a flush whose answer was lost and is resent later is stored once.
7
+ - `build_template` / `tar_dir`: a `.dockerignore` entry with a leading `/` (`/build`) now excludes that path
8
+ (it was sent in the build context); a bare `/` or `.` entry is ignored rather than matching nothing.
9
+ - `CloudBrowser#screenshot` says why when the API sent none (`screenshot_note`, e.g. too large).
10
+ - Gem metadata: summary and description start "Zero Trust cybersecurity infrastructure for AI agents";
11
+ homepage, changelog, bug tracker and documentation URIs; CHANGELOG.md ships in the gem.
12
+ - `sandboxes.create(disk_gb:)` takes up to 500 (was refused past 200, though Team and Scale plans allow 256
13
+ and 500); `kvm: true` (preview). A create from a snapshot also refuses `mem_mb:` and `kvm:`.
14
+ `exec_background(timeout_s:)` (up to a day). `CloudExecResult` has `stdout_truncated`, `stderr_truncated`,
15
+ `stdout_bytes` and `stderr_bytes`. README: the live region is `us-ash1` (`eu` is not offered).
16
+ - Files: `read` / `download` take `range:` (`0..1023`, `1024..`, `-500` or `"bytes=a-b"`; one Range header);
17
+ `write` takes `offset:`, `append: true` and `mode:`; `upload` takes an IO (a File is read a part at a time)
18
+ and sends anything past `part_size:` (64 MiB) in parts with `offset=`, so files over the API's 100 MB request
19
+ limit upload. An `append` write is never retried after a 5xx or no answer, so it cannot land twice. The docs no
20
+ longer say a file is at most 8 MiB (that is only hosts without streamed files).
21
+ - Streamed exec: `CloudSandbox#exec_stream(cmd, timeout_s:, on_stdout:, on_stderr:) { |stream, text| ... }`
22
+ reads the output as the command prints it (NDJSON frames, heartbeats skipped, UTF-8 decoded across chunks)
23
+ and is not held to the 90 s of a buffered exec; `timeout_s` up to a day. `exec` streams when given
24
+ `stream: true`, `on_stdout:` / `on_stderr:` or a `timeout_s` over 90 (as the Python SDK). A command
25
+ stopped at its `timeout_s` raises `ExecTimeoutError` with the output so far; a broken stream raises
26
+ `StreamError`. `Cloud.new(stream_transport:)` replaces Net::HTTP for streamed answers (tests).
27
+ - Every Cloud error (`Kosa8::ApiError`) now reads the API's contract fields: `agent_message` and
28
+ `request_url` on a 429 `quota_exceeded` (before, only a 402 had `agent_message`), and for a 402
29
+ `plan_limit` / `plan_feature` `limit_name`, `limit`, `used`, `plan`, `next_plan`, `feature`, `options` and
30
+ `pack_url`. `ExecTimeoutError#stdout` / `#stderr` / `#limit_s` give the output a command stopped at its
31
+ `timeout_s` had printed.
32
+ - Retries of creates, batches, forks, grades, job submits and rollout records use a new SDK-made
33
+ `Idempotency-Key` after a 5xx (502 `host_failed`, 503 `no_capacity` / `host_restarting` /
34
+ `host_unavailable`, 504), so each retry of a server-side failure is a new attempt. The key is still
35
+ kept after no answer (the first try may have created the sandbox), a 429 and a 409
36
+ `idempotency_in_progress` / `template_building`. A key you pass as `idempotency_key:` is never
37
+ changed. Retry-After is honoured as before. `Kosa8::Cloud.renews_idempotency_key?(e)` says which
38
+ failures renew it.
39
+
40
+ ## 0.6.0 - 2026-11-22
41
+
42
+ The Ruby SDK now covers what the Python and JS SDKs do (no longer "core tier" only):
43
+
44
+ - **Browsers:** `cloud.browsers` (`create`, `list`, `info`, `get`, `delete`), `cloud.browser { |b| ... }`
45
+ (closed when the block ends), `CloudBrowser#page`, `goto`, `screenshot`, `close`, `refresh`, `cdp_url`
46
+ (never shown by `inspect`) and `cdp_path` (GET /v1/browsers/{id}/cdp).
47
+ - **AI gateway:** `cloud.ai` (`keys`, `set_key`, `delete_key`, `settings`, `update_settings`, `usage`),
48
+ `gateway_url(provider)` (`.../v1/ai/gw/{provider}` for a provider's own client) and `call(provider,
49
+ path, body)`. `sandboxes.create(ai_gateway: true)` and `record: true`.
50
+ - **Hosted jobs:** `cloud.jobs` (`submit` with an Idempotency-Key, `estimate`, `get`, `list`, `cancel`,
51
+ `wait`); tasks as an Array or JSONL, files base64-encoded for you.
52
+ - **Benchmarks:** `cloud.benchmarks` (`list`, `get`, `instances`, `instance`, `prepare`).
53
+ - **RL:** `cloud.rl_compare(*ids)` and `cloud.rl_alerts` (`list`, `create`, `update`, `delete`).
54
+ - **Org:** `usage_insights`, `pricing`, `limits`, `request_limit`, `lineage`, `checkpoints`, `images`,
55
+ `org_egress`, `set_org_egress`, `preview_domains`, `attack_scorecards`; `cloud.audit` (`list`, `each`,
56
+ `verify`, `export`), `cloud.api_keys` (`list`, `create`, `rotate`, `revoke`), `cloud.webhooks` (`list`,
57
+ `create`, `delete`, `deliveries`, `test`), `cloud.recordings` (`list`, `link`, `delete`), `cloud.burst`
58
+ (`get`, `activate`), `cloud.functions.invocations(name)`.
59
+ - **Per sandbox:** `stop_background(exec_id)`, `embeds` (`create`, `list`, `revoke`), `recordings`,
60
+ `previews.domains(port)` (`add`, `list`, `get`, `remove`).
61
+ - **Small sizes:** `create(size: "0.25x0.5" | "0.5x1" | "1x2")` or `cpus: 0.25, mem_mb: 512`
62
+ (`Kosa8::Cloud::SMALL_SIZES`); `cpus:` takes fractions (it was `Integer(cpus)`).
63
+ - **Retries:** every request is retried (backoff with full jitter, bounded by the policy's attempts,
64
+ at least the Retry-After header or the body's `retry_after` / `retry_after_s`) on 503
65
+ `database_busy`, 409 `template_building` and 429, POSTs included, since the server refused them before
66
+ running anything. POST /v1/jobs and rollout records now carry an Idempotency-Key, so they are retried
67
+ on infra failures too. `retryable: false` is never retried. `Kosa8.failure_of` follows the server's
68
+ rules for `database_busy`, `template_building`, `idempotency_in_progress` and `invalid_*` codes.
69
+ - Overflow capacity (Cloudflare) sandboxes answer fork, checkpoint, rewind and sleep with 501
70
+ `not_available`; documented, raised as `Kosa8::UnsupportedError`, never retried.
71
+ - README: `gem "kosa8", "~> 0.6"`; one persistence sentence for all SDKs (each exec is a fresh process;
72
+ files in /workspace persist for the sandbox's life; installed packages need `persistent: true`); the
73
+ stale "no sandbox labels" line removed.
74
+
75
+ ## 0.5.3
76
+
77
+ - `CloudSandbox#exec(cmd, timeout_s:)`: the API's exec `timeout_s` (1 to 90 whole seconds) stops the command in the sandbox when it runs that long and raises `Kosa8::ExecTimeoutError` (without the hint about the 90 s buffered limit). Python, JS, Go and Java have the same option. Any other value is an `ArgumentError` before the call.
78
+ - README: `gem install kosa8` (it said `-v 0.4.0`) and `gem "kosa8", "~> 0.5"`; what persists between commands (only `/workspace`, unless the sandbox is persistent) matches the server; a "same thing in each language" table for the five SDKs.
79
+
80
+ ## 0.5.2
81
+
82
+ - **Actionable API errors:** an error from kosa8 Cloud now reads as the server's sentence followed by its
83
+ context, e.g. `no capacity: fork fewer or retry in 2 s [HTTP 503 no_capacity; retry in 10 s; request a5e7…-BOS]`.
84
+ A 402 adds its `upgrade_url` (when the sentence does not already have it) and a 401 says to check
85
+ `KOSA8_API_KEY` and where to make a key. The bare sentence stays in `daemon_message`.
86
+ - `Kosa8::Error#request_id`: the failed request's `X-Request-Id`, else Cloudflare's `cf-ray` (quote it to
87
+ support). `#retry_after_s` is `#retry_after` under the API's name.
88
+ - Client-side errors say what to do next: a missing or malformed key points at `KOSA8_API_KEY` and
89
+ https://app.kosa8.com/app#keys; a timeout names the call and suggests a longer `timeout:`; a connection
90
+ failure says to check the network and `KOSA8_CLOUD_URL`.
91
+
92
+ ## 0.5.1
93
+
94
+ - Failure class `oom`: exit 137 with the guest kernel's OOM count raised (kosa8 Cloud reports it on exec and grade; a grade killed for memory has no reward). It can be added to a rollout mask.
95
+
96
+ ## 0.5.0 — unreleased
97
+
98
+ RL training and fan-out on kosa8 Cloud (the API of kosa8 Cloud's RL release):
99
+
100
+ - **Fan-out:** `cloud.sandboxes.create_many(count, ...)` (POST /v1/sandboxes/batch, up to 1000, a
101
+ `Kosa8::SandboxBatch` with `failed`, `requested`, `created`, `run_id`). `box.fork(n)` now takes
102
+ up to 1000 and `labels:`, `run_id:`, `lease_s:`, `prefix:`, `partial_ok:`, `idempotency_key:`,
103
+ and returns a `SandboxBatch` (still an Array). `create` takes `lease_s:`, `run_id:` and
104
+ `idempotency_key:`.
105
+ - **Leases:** `cloud.sandboxes.heartbeat(run_id:/labels:/ids:, extend_s:)`, `box.heartbeat`,
106
+ `cloud.sandboxes.drain(...)` (calls again while the server says there are more), and
107
+ `Kosa8::RL::Lease`.
108
+ - **Sealed grader:** `box.grade(cmd, files:, timeout_s:, env:, keep:, run_id:, rollout:)` and
109
+ `cloud.sandboxes.grade(id, ...)`, a `Kosa8::GradeResult`.
110
+ - **Idempotency-Key** on create, batch, fork and grade (a UUID by default), the same on every retry.
111
+ - **Retries:** `Kosa8::RetryPolicy` (3 tries, exponential backoff with full jitter, at least the
112
+ server's Retry-After), on by default where safe (reads, PUTs, deletes, heartbeats, drains, keyed
113
+ POSTs, and any 429); `Cloud.new(retry_policy: Kosa8::RetryPolicy::NONE)` turns it off,
114
+ `sleeper:` replaces the waits. `Kosa8.with_retry`.
115
+ - **Failure classes:** every `Kosa8::Error` has `failure_class` and `retryable?`
116
+ (`Kosa8.classify_failure`, `Kosa8.failure_of`) and `retry_after` (Retry-After seconds or HTTP
117
+ date, or the body's `retry_after_s`); `CloudExecResult` has `failure_class` and `retryable`.
118
+ - **fork_map:** `box.fork_map(items, concurrency:, retries:, timeout_s:, ...) { |child, item| }`
119
+ and `cloud.fork_map(base, items, ...)`, `Kosa8::ForkResult`s in order; every fork deleted, Ctrl-C
120
+ included.
121
+ - **RL runs:** `Kosa8::RL::Run` (`open`, `start`, `record`, `flush` in batches of at most 500,
122
+ `finish`, `summary`, `update`, `rollouts`, `export`, `drain`, `Run.list`, `Run.attach`) and
123
+ `Run#map` (one training step: fork, solve, sealed grade, record, with masking of infra, quota
124
+ and harness failures), `Kosa8::RL::Rollouts`, `RolloutResult`.
125
+ - **Org templates:** `cloud.org_templates` (`build`, `import`, `list`, `get`, `delete`, `wait_ready`).
126
+ - **Capability tokens:** `cloud.tokens` (`create`, `list`, `revoke`); `Cloud.new` takes a
127
+ `k8c_tok_` token as its key.
128
+ - `Cloud::MAX_FORK` is now 1000. Requests that used to fail at once on a 5xx (reads, deletes) are
129
+ now retried; pass `retry_policy: Kosa8::RetryPolicy::NONE` for the old behaviour.
130
+
131
+ ## 0.4.0 — 2026-11-15
132
+
133
+ The rest of the kosa8 Cloud API:
134
+
135
+ - **Sized and Docker creates**: `create` takes `size:`, `cpus:`/`mem_mb:`, `image:`, `disk_gb:`,
136
+ `persistent:`, `docker:`, `cpu:`, `name:`, `labels:`, `env:`, `secrets:`, `egress:`,
137
+ `snapshot:` and `wait:`; a cold boot is waited for with the new `wait_running`. `list` takes
138
+ `name:` and `labels:`.
139
+ - **Background commands** (`exec_background`, `background_exec`, `wait_background`), **durable
140
+ snapshots** (`snapshot`, `cloud.snapshots`), **previews**, **terminal**, raw `files.download` /
141
+ `files.upload` and `files.link`, **egress**, **secrets** (`cloud.secrets`), **schedules**,
142
+ **code interpreter**, `metrics`, `logs`, `set_labels`, `cloud.capabilities`.
143
+ - **Pipelines** (`cloud.pipelines`): `run`, `runs`, `get`, `wait`, `logs`, `cancel`,
144
+ `artifacts`, `download_artifact`, `create_hook`, `hooks`, `delete_hook`.
145
+ - Every Cloud request sends `User-Agent: kosa8-ruby/<version>` (api.kosa8.com's edge refuses some
146
+ default library user agents).
147
+
148
+ kosa8 Cloud parity with the Python SDK. The default address stays `https://api.kosa8.com` (0.3.0 defaulted to `api.kosa8.cloud`; do not use 0.3.0).
149
+
150
+ - **Lifetime:** `cloud.sandboxes.create` takes `ttl_s:` (60 s to 90 days), `delete_after:` (Unix ms) and `accept_price:` (paid Store items); bad values raise `ArgumentError` before any request. New `CloudSandbox#update(ttl_s:, delete_after:, sleep_after_s:, clear_lifetime:)` (PATCH; `clear_lifetime: true` sends `ttl_s: null`) and `#notes`.
151
+ - **Paging:** `cloud.sandboxes.list` still returns an Array and now takes `limit:` and `cursor:`. New `list_page` (a `Kosa8::CloudSandboxPage` with `sandboxes` and `next_cursor`) and `each(all:, page_size:)`, which follows `next_cursor` (an Enumerator without a block) and stops on a repeated cursor.
152
+ - **Data plane** (needs the host's data plane; 501 `Kosa8::UnsupportedError` on hosts without it): `box.files` (`read` binary, `read_text`, `write`, `list`, `mkdir`, `delete(recursive:)`, raw `application/octet-stream` bodies), `box.checkpoint(label)`, `box.checkpoints`, `box.rewind(id)` (a `Kosa8::CloudRewindResult`), `box.fork(n)` and `box.ports`.
153
+ - `cloud.templates`. New `cloud.request_bytes` for raw bodies.
154
+ - **Errors:** `PaymentRequiredError#upgrade_url` and `#agent_message`. New `Kosa8::OrgFrozenError` (423 `org_frozen`) and `Kosa8::ExecTimeoutError` (504 `exec_timeout`, or today's 502 "timed out" on exec after about 30 s; also a client-side timeout on exec). `RateLimitError#retry_after` from Retry-After. A `transport:` may now return `[status, body, headers]`.
155
+ - README: Cloud quickstart first; the base template (Alpine, busybox sh, fresh container per exec, only `/workspace` persists, 30 s exec limit, 64 KiB bodies, 8 MiB files); Cloud errors.
156
+
157
+ ## 0.3.1 — 2026-11-03
158
+
159
+ - The default kosa8 Cloud address is now `https://api.kosa8.com` (0.3.0 defaulted to `api.kosa8.cloud`, which kosa8 Cloud does not use). `KOSA8_CLOUD_URL` still overrides it.
160
+
161
+ ## 0.3.0 — 2026-11-03
162
+
163
+ kosa8 Cloud's API (api.kosa8.cloud) is not open yet; the `Kosa8Cloud` client is ready for when it is.
164
+
165
+ kosa8 Cloud, the same as the Python SDK's `Kosa8Cloud` and `@kosa8/sdk`'s.
166
+
167
+ - `Kosa8::Cloud`: a client for the kosa8 Cloud control plane, authenticated with a `k8c_live_` API key
168
+ (`KOSA8_API_KEY`; address `KOSA8_CLOUD_URL`, default `https://api.kosa8.cloud`, https only except
169
+ localhost). Standard library only; `inspect` never shows the key; `transport:` swaps Net::HTTP out.
170
+ - `cloud.sandboxes.create`, `list` and `get` return a `Kosa8::CloudSandbox` with `exec` (returns
171
+ `Kosa8::CloudExecResult`: `exit_code`, `stdout`, `stderr`, `woke_ms`), `sleep`, `wake`, `refresh` and `delete`.
172
+ - `cloud.functions`: `deploy`, `list`, `get`, `delete`, `invoke` and `map`.
173
+ - `cloud.me` and `cloud.usage`.
174
+ - Errors: every error has `code`, the cloud's stable error code. New `Kosa8::PaymentRequiredError` (402)
175
+ and `Kosa8::RateLimitError` (429).
176
+
177
+ The saved worker connection, as the CLI uses it (Windows especially).
178
+
179
+ - With no `host:` and no `KOSA8_HOST`, and no `socket_path:`, the client uses the connection
180
+ `kosa8 wsl setup` or `kosa8 worker join` saved in `~/.kosa8/worker.json`: its host, its token
181
+ (unless `token:` is given) and its `"insecure": true`. A saved token is never sent to a host from
182
+ `KOSA8_HOST` or `host:`. New `worker_file:` option (`false` reads none).
183
+ - On Windows, a failed connection to the default socket says to run `kosa8 wsl setup` or set `KOSA8_HOST`.
184
+ - CI on ubuntu, macOS and Windows; mock-daemon tests skip where unix sockets are unavailable.
185
+
186
+ ## 0.2.0 — 2026-11-03
187
+
188
+ The sandbox toolbox, matching the Python SDK and the v0.13.0 daemon.
189
+
190
+ - **Run code**: `run_code` (Python, JavaScript, TypeScript) returns `Kosa8::CodeResult`; matplotlib
191
+ charts come back in `artifacts` as `Kosa8::Artifact` with binary `data`.
192
+ - **Files**: `list_files`, `stat_file`, `read_file` (binary String; a short body raises),
193
+ `read_text`, `write_file` (with `mode:`), `delete_file` (with `recursive:`), `make_dir`, `move_file`.
194
+ - **Git**: `git(op, **fields)` returns `Kosa8::GitResult`, plus `git_clone`, `git_status` and
195
+ `git_commit`, which stages everything first (`add_all: false` to skip).
196
+ - **Sessions**: `create_session`, `list_sessions`, `session_exec` (`Kosa8::ShellResult` with `cwd`),
197
+ `delete_session`, and `shell`, which makes the session the first time it is used.
198
+ - **Terminals and previews**: `start_pty`, `resize_pty`, `create_preview`, `revoke_previews`.
199
+ - **Lifecycle**: `set_lifecycle`, and `create_sandbox` takes `auto_stop_min:`, `ttl_min:`,
200
+ `auto_delete_min:`, `ephemeral:` and `template:`.
201
+ - **Templates**: `list_templates`, `delete_template`, and `build_template`, which tars the context
202
+ folder (honouring `.dockerignore`) with the standard library, streams build output to a block or
203
+ `on_output:`, and raises `Kosa8::StreamError` when the build fails.
204
+ - `Kosa8::Sandbox` gains every toolbox method that takes a sandbox.
205
+ - `run_code` and `session_exec` wait for the daemon's own limit (5 min, or `timeout_s` when given)
206
+ plus 2 min, and git for 12 min, rather than Net::HTTP's 60 s default.
207
+
208
+ ## 0.1.2 — 2026-11-03
209
+
210
+ - **Concurrent checkpoints really no longer collide.** 0.1.1 retried by re-reading the
211
+ store, which still returned the taken id (the winner records it only after its snapshot
212
+ completes). The loser now steps to the next id; a 409 for any other reason is raised.
213
+ Verified live with two threads checkpointing one sandbox.
214
+
215
+ ## 0.1.1 — 2026-11-03
216
+
217
+ Fixes found while writing and testing the docs at https://docs.kosa8.com/guides/rb-guide/.
218
+
219
+ - **`run`, `exec`, `exec_frames` and `attach` no longer time out after 60 s of silence.**
220
+ With no `timeout:`, streaming calls now wait as long as the command runs. Net::HTTP's
221
+ 60 s read timeout used to raise `Kosa8::TimeoutError` on any command quiet for a minute.
222
+ JSON calls keep Net::HTTP's defaults.
223
+ - **A second `write_stdin` to the same container now raises `Kosa8::Error`** instead of
224
+ answering `{"ok"=>true}` for input the process never sees. The daemon treats one request
225
+ body as the whole of stdin and closes it at the end; stream with an IO or Enumerable.
226
+ - **`Kosa8::Error#method` is renamed `#http_method`**, so `Object#method` works on errors
227
+ again (`e.method(:message)` used to raise ArgumentError).
228
+ - **An exception raised in your own `on_stdout` / `on_stderr` / `on_status` callback comes
229
+ out unchanged.** An `IOError` there used to be relabelled `Kosa8::ConnectionError`.
230
+ - **A frame that is not valid NDJSON raises `Kosa8::ProtocolError`** (a `Kosa8::Error`),
231
+ not `JSON::ParserError`.
232
+ - **Concurrent checkpoints of one sandbox no longer collide.** When two pick the same id,
233
+ the one refused with 409 picks the next id and retries.
234
+ - **The checkpoint file lock waits at most 10 s** (`FileCheckpointStore.new(lock_timeout:)`),
235
+ as `@kosa8/sdk` does, then raises `Kosa8::CheckpointError` instead of hanging.
236
+ - **A failed `rewind` says what happened**: the sandbox was deleted (not stopped) and the
237
+ checkpoint is intact, with the `restore_snapshot` call that recovers it.
238
+ - **`explore` no longer sleeps after its last retry.**
239
+ - **`Kosa8::Sandbox` gains `exec_frames`, `start_interactive`, `write_stdin` and `attach`.**
240
+
241
+ Not changed: a client-side `timeout:` stops waiting but does not stop the command in the
242
+ sandbox; the daemon has no cancel for a run in progress.
243
+
244
+ ## 0.1.0 — 2026-11-03
245
+
246
+ First release.
data/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # kosa8 (Ruby)
2
2
 
3
- The Ruby SDK for [kosa8](https://kosa8.com): microVM sandboxes for AI agents. No dependencies; Ruby 2.6+.
3
+ **[kosa8](https://kosa8.com): Zero Trust cybersecurity infrastructure for AI agents.**
4
+
5
+ The Ruby SDK for [kosa8](https://kosa8.com): each agent in its own microVM. No dependencies; Ruby 2.6+.
4
6
  Method for method it matches [`@kosa8/sdk`](https://github.com/kosa8ai/kosa8-js), the Python `kosa8` package and `kosa8-go`.
5
7
 
6
8
  ## Quickstart: kosa8 Cloud
@@ -61,8 +63,11 @@ page = cloud.sandboxes.list_page(limit: 50) # one page: page.sandboxes, page.ne
61
63
  # These need the host's data plane. On a host without it they raise
62
64
  # Kosa8::UnsupportedError (501 not_available / not_supported): not every
63
65
  # kosa8 Cloud host has it yet.
64
- box.files.write("/workspace/data.bin", File.binread("data.bin")) # bytes or text, at most 8 MiB
66
+ box.files.write("/workspace/data.bin", File.binread("data.bin")) # bytes or text, streamed to the host
65
67
  bytes = box.files.read("/workspace/data.bin") # a binary String
68
+ head = box.files.read("/workspace/data.bin", range: 0..1023) # part of it (also range: -500, 1024..)
69
+ box.files.write("/workspace/log.txt", "line\n", append: true) # also offset: and mode: "755"
70
+ File.open("big.tar", "rb") { |f| box.files.upload("/workspace/big.tar", f) } # any size, in 64 MiB parts
66
71
  puts box.files.list("/workspace").map { |f| f["name"] }
67
72
  box.files.mkdir("/workspace/out")
68
73
  box.files.delete("/workspace/out", recursive: true)
@@ -98,8 +103,10 @@ copy = cloud.sandboxes.create(snapshot: snap["id"])
98
103
  cloud.snapshots.delete(snap["id"]) # also list, get
99
104
  ```
100
105
 
101
- Also `cpus:`/`mem_mb:`, `disk_gb:`, `persistent:`, `cpu: "dedicated"`, `region:` (`us`, `eu` or
102
- an id), `secrets:` and `egress:`. `list` takes `name:` and `labels:`.
106
+ Also `cpus:`/`mem_mb:`, `disk_gb:` (8 to 500; past 200 on plans with a bigger sandbox disk), `persistent:`,
107
+ `cpu: "dedicated"`, `kvm: true` (preview: `/dev/kvm` for an emulator), `region:` (`us-ash1`, the one live
108
+ region, or `us`), `secrets:` and `egress:`. `list` takes `name:` and `labels:`. `exec` results carry
109
+ `stdout_truncated` / `stdout_bytes` (and stderr's) when a buffered exec dropped the middle of its output.
103
110
 
104
111
  ### Background commands, previews, terminal and more
105
112
 
@@ -112,8 +119,8 @@ puts box.previews.create(3000)["url"] # private signed URL; public
112
119
  box.terminal(cols: 120, rows: 40)["url"] # a wss:// PTY URL
113
120
  ```
114
121
 
115
- - Files: `files.download(path)` / `files.upload(path, data)` (no 8 MiB cap), `files.link(path,
116
- method: "PUT")` (presigned URL).
122
+ - Files: `files.download(path, range:)` / `files.upload(path, data_or_io, part_size:, mode:)` (any size; past
123
+ 100 MB in parts with `offset=`), `files.link(path, method: "PUT")` (presigned URL, straight to the host).
117
124
  - `egress`, `set_egress(presets: ["pypi"])`, `reset_egress`; `cloud.egress_presets`.
118
125
  - `run_code("print(6*7)", context: "a")` (stateful Python; persistent sandbox with python3),
119
126
  `code_contexts`, `create_code_context`, `reset_code_context`, `delete_code_context`.
@@ -202,7 +209,10 @@ end
202
209
  ```
203
210
 
204
211
  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.
212
+ `idempotency_key:`). The SDK's own key is reused after no answer (a timeout or a dropped connection:
213
+ the first try may still be running), a 429 and a 409 `idempotency_in_progress` / `template_building`,
214
+ so such a retry never doubles the fleet; after a 5xx (502 `host_failed`, 503 `no_capacity`, ...) the
215
+ retry gets a new key, so it is a new attempt. A key you pass is never changed.
206
216
  Retries (`Kosa8::RetryPolicy`: 3 tries, backoff with full jitter, at least the server's Retry-After or
207
217
  `retry_after`) apply only where safe: reads, PUTs and deletes, keyed POSTs, and any request the server
208
218
  refused before running it (429, 503 `database_busy`, 409 `template_building`). An answer marked
@@ -230,11 +240,16 @@ Kosa8::Cloud.new(api_key: tok["secret"]) # hand this to your end user, not your
230
240
  `sh -c`, or create with `persistent: true` (one long-lived container) to keep the whole filesystem and
231
241
  background processes; the code interpreter (`run_code`) needs it, and it counts against your plan's
232
242
  persistent-sandbox limit.
233
- - **A buffered `exec` runs at most 90 seconds** and raises `Kosa8::ExecTimeoutError`.
243
+ - **A buffered `exec` runs at most 90 seconds** and raises `Kosa8::ExecTimeoutError`. For longer
244
+ commands stream them: `box.exec_stream("make test") { |stream, text| print text }` (or `exec(cmd,
245
+ stream: true)`, `on_stdout:` / `on_stderr:`, or a `timeout_s:` over 90, up to a day) prints as the command
246
+ does and is not held to 90 s.
234
247
  `box.exec(cmd, timeout_s: 30)` stops a command sooner, in the sandbox (1 to 90 whole seconds). Run long
235
248
  work in the background and poll it:
236
249
  `box.exec("nohup sh -c 'make test > /workspace/test.log 2>&1; echo $? > /workspace/test.exit' &")`.
237
- - A request body (command and env) is at most 64 KiB; a file read or write is at most 8 MiB.
250
+ - A request body (command and env) is at most 64 KiB. A file read or write streams to the host (one request
251
+ at most 100 MB through the API; `files.upload` sends a bigger file in parts); hosts without streamed files
252
+ take at most 8 MiB a file.
238
253
  - Set `ttl_s:` (60 s to 90 days) or `delete_after:` (Unix ms) on create so a crashed script cannot leave a
239
254
  sandbox running. Bad values raise `ArgumentError` before any request.
240
255
  - Sandboxes take `name:` and `labels:` on create (`set_labels` later); `list(labels: {...})` filters by them.
@@ -245,12 +260,16 @@ Kosa8::Cloud.new(api_key: tok["secret"]) # hand this to your end user, not your
245
260
  |---|---|---|
246
261
  | `Kosa8::PaymentRequiredError` (402) | no payment method (`payment_required`), spending cap reached (`spending_cap_reached`), Store price not accepted (`price_not_accepted`) | show `e.upgrade_url`; an agent should relay `e.agent_message` to its person and stop |
247
262
  | `Kosa8::OrgFrozenError` (423, `org_frozen`) | the org is frozen in the Security Center | an owner or admin unfreezes it; retrying does not help |
248
- | `Kosa8::RateLimitError` (429) | too many requests, or `quota_exceeded` (active sandbox limit) | wait `e.retry_after` seconds when set, or delete sandboxes |
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 |
263
+ | `Kosa8::RateLimitError` (429) | too many requests, or `quota_exceeded` (active sandbox limit) | wait `e.retry_after` seconds when set, or delete sandboxes; for `quota_exceeded` relay `e.agent_message` and point at `e.request_url` |
264
+ | `Kosa8::ExecTimeoutError` (504 `exec_timeout`, or today's 502 "timed out" on exec) | a buffered exec ran past its 90 s limit, or a command ran past its own `timeout_s` (`e.stdout` / `e.stderr` hold the output so far) | stream it (`exec_stream`), or run it in the background and poll |
250
265
  | `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
266
  | `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 |
252
267
 
253
- Every Cloud error is a `Kosa8::ApiError` carrying the server's stable `e.code`, its message and `e.body`.
268
+ Every Cloud error is a `Kosa8::ApiError` carrying the server's stable `e.code`, its message and `e.body`,
269
+ and the contract fields as methods (nil when absent): `upgrade_url`, `agent_message`, `request_url`, and for a
270
+ 402 `plan_limit` / `plan_feature` `limit_name`, `limit`, `used`, `plan`, `next_plan`, `feature`, `options`
271
+ (the ways past the limit, cheaper first) and `pack_url`. `Kosa8::ExecTimeoutError#stdout` / `#stderr` hold the
272
+ output so far.
254
273
 
255
274
  ## The same thing in each language
256
275
 
data/lib/kosa8/cloud.rb CHANGED
@@ -13,7 +13,12 @@ module Kosa8
13
13
  # and woke for this command.
14
14
  # +failure_class+ is "ok" (exit 0), "exit_nonzero" (the command failed) or
15
15
  # "infra" (the host gave no exit code; +retryable+ true).
16
+ # A buffered exec keeps the first and last 1 MiB of each stream:
17
+ # +stdout_truncated+ / +stderr_truncated+ are true when the middle was
18
+ # dropped, and +stdout_bytes+ / +stderr_bytes+ count what the command
19
+ # wrote, kept or not (nil when the server did not say).
16
20
  CloudExecResult = Struct.new(:exit_code, :stdout, :stderr, :woke_ms, :failure_class, :retryable,
21
+ :stdout_truncated, :stderr_truncated, :stdout_bytes, :stderr_bytes,
17
22
  keyword_init: true) do
18
23
  def ok?
19
24
  exit_code == 0 # exit_code is nil when the command never ran
@@ -88,7 +93,9 @@ module Kosa8
88
93
  # jitter) is applied where trying again is safe: reads, PUTs, deletes,
89
94
  # heartbeats and drains on infra failures; the calls that make sandboxes
90
95
  # (create, batch, fork, grade), job submits and rollout records, which
91
- # carry an Idempotency-Key reused on every retry; and any request the
96
+ # carry an Idempotency-Key (the SDK's own is reused after no answer, a
97
+ # 429 or a 409, and renewed after a 5xx; yours is never changed); and
98
+ # any request the
92
99
  # server refused before running it (429, 503 database_busy, 409
93
100
  # template_building), waiting at least its Retry-After (or the body's
94
101
  # retry_after / retry_after_s). An answer with retryable: false is never
@@ -141,8 +148,10 @@ module Kosa8
141
148
 
142
149
  # One JSON request, retried as retry_policy allows; raises the typed
143
150
  # error for an error answer. A call that makes sandboxes (Cloud.keyed?)
144
- # sends +idempotency_key+ (a new UUID when not given), the same on every
145
- # retry, so it may be retried after a timeout or a 5xx too.
151
+ # sends +idempotency_key+ (a new UUID when not given), so it may be
152
+ # retried after a timeout or a 5xx too. A given key goes unchanged with
153
+ # every retry; the SDK's own is kept after no answer, a 429 or a 409 and
154
+ # replaced after a 5xx (Cloud.renews_idempotency_key?).
146
155
  #
147
156
  # +opts+ (a Hash, not keywords, so an empty body Hash stays the body):
148
157
  # :idempotency_key and :retry_policy.
@@ -153,9 +162,10 @@ module Kosa8
153
162
 
154
163
  # One request whose body is +data+ (raw bytes, application/octet-stream)
155
164
  # when given; with +raw+ a successful answer's bytes come back as a binary
156
- # String instead of parsed JSON. Raises the typed error for an error answer.
157
- def request_bytes(method, path, data: nil, raw: false, retry_policy: nil)
158
- perform(method, path, nil, data, raw, nil, retry_policy)
165
+ # String instead of parsed JSON. +headers+ are sent too (such as Range).
166
+ # Raises the typed error for an error answer.
167
+ def request_bytes(method, path, data: nil, raw: false, retry_policy: nil, headers: nil)
168
+ perform(method, path, nil, data, raw, nil, retry_policy, headers)
159
169
  end
160
170
 
161
171
  # Methods safe to send twice. Other POSTs are retried only when the
@@ -183,21 +193,42 @@ module Kosa8
183
193
  e.is_a?(Error) && (e.status == 429 || PRE_EXECUTION_CODES.include?(e.code))
184
194
  end
185
195
 
196
+ # Whether a retry after +e+ gets a new SDK-made Idempotency-Key: only
197
+ # when kosa8 Cloud answered with a 5xx (502 host_failed, 503
198
+ # no_capacity, ...), so each retry of a server-side failure is a new
199
+ # attempt. No answer (a timeout or a dropped connection: the first try
200
+ # may still be running and may have made the sandbox), a 429 and a 409
201
+ # (idempotency_in_progress, template_building) keep the key.
202
+ def self.renews_idempotency_key?(e)
203
+ e.is_a?(Error) && e.status.is_a?(Integer) && e.status >= 500
204
+ end
205
+
206
+ # Whether +path+ is a file write with append= (not safe to send twice).
207
+ def self.append_write?(path)
208
+ q = path.to_s.split("?", 2)[1].to_s
209
+ URI.decode_www_form(q).any? { |k, v| k == "append" && %w[1 true].include?(v) }
210
+ rescue ArgumentError
211
+ false
212
+ end
213
+
186
214
  def self.check_idempotency_key(key)
187
215
  return if key.nil? || (key.is_a?(String) && IDEMPOTENCY_KEY.match?(key))
188
216
 
189
217
  raise ArgumentError, "idempotency_key must be 1-255 printable ASCII characters, e.g. a UUID"
190
218
  end
191
219
 
192
- private def perform(method, path, body, data, raw, idempotency_key, policy)
220
+ private def perform(method, path, body, data, raw, idempotency_key, policy, headers = nil)
193
221
  Cloud.check_idempotency_key(idempotency_key)
194
- extra = {}
195
- if !idempotency_key.nil? || Cloud.keyed?(method, path)
222
+ extra = (headers || {}).map { |k, v| [k.to_s, v.to_s] }.to_h
223
+ own_key = idempotency_key.nil? && Cloud.keyed?(method, path)
224
+ if !idempotency_key.nil? || own_key
196
225
  extra["Idempotency-Key"] = idempotency_key || SecureRandom.uuid
197
226
  end
198
227
  policy ||= @retry_policy
199
228
  bare = path.to_s.split("?", 2)[0]
200
- safe = !extra.empty? || IDEMPOTENT_METHODS.include?(method) || IDEMPOTENT_POSTS.include?(bare)
229
+ safe = extra.key?("Idempotency-Key") || IDEMPOTENT_METHODS.include?(method) || IDEMPOTENT_POSTS.include?(bare)
230
+ # An append adds the body again if sent twice: retried only when refused before it ran.
231
+ safe = false if method == "PUT" && Cloud.append_write?(path)
201
232
  attempt = 1
202
233
  loop do
203
234
  begin
@@ -206,6 +237,7 @@ module Kosa8
206
237
  raise unless policy.retry?(e, attempt) && (safe || Cloud.pre_execution?(e))
207
238
 
208
239
  @sleeper.call(policy.delay(e, attempt))
240
+ extra["Idempotency-Key"] = SecureRandom.uuid if own_key && Cloud.renews_idempotency_key?(e)
209
241
  attempt += 1
210
242
  end
211
243
  end
@@ -549,7 +581,9 @@ module Kosa8
549
581
  fc = r["failure_class"] if r["failure_class"].is_a?(String)
550
582
  rt = r["retryable"] if r["retryable"] == true || r["retryable"] == false
551
583
  CloudExecResult.new(exit_code: r["exit"], stdout: r["stdout"] || "", stderr: r["stderr"] || "",
552
- woke_ms: r["woke_ms"], failure_class: fc, retryable: rt)
584
+ woke_ms: r["woke_ms"], failure_class: fc, retryable: rt,
585
+ stdout_truncated: r["stdout_truncated"] == true, stderr_truncated: r["stderr_truncated"] == true,
586
+ stdout_bytes: r["stdout_bytes"], stderr_bytes: r["stderr_bytes"])
553
587
  end
554
588
 
555
589
  # Snapshot it and free its VM; it then costs only snapshot storage.
@@ -666,7 +700,7 @@ module Kosa8
666
700
  # of failing the call; false is all or nothing. The API's default is true
667
701
  # when a fan-out option is given or n is over 100. A fork that made none
668
702
  # raises the first refusal. The call carries an Idempotency-Key
669
- # (+idempotency_key+, default a new UUID) reused on every retry.
703
+ # (+idempotency_key+, default a new UUID; see Cloud#request for retries).
670
704
  #
671
705
  # Needs the host's data plane; on hosts without it the API answers 501
672
706
  # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
@@ -700,10 +734,15 @@ module Kosa8
700
734
  end
701
735
  end
702
736
 
703
- # sandbox.files: files in a cloud sandbox, at most 8 MiB each. Paths are
704
- # absolute, such as /workspace/app.py; only /workspace outlives an exec. A
705
- # sleeping sandbox wakes first. File info Hashes have "name", "path",
706
- # "type" ("file" or "dir"), "size", "mode" and "mod_time".
737
+ # sandbox.files: files in a cloud sandbox. Paths are absolute, such as
738
+ # /workspace/app.py; only /workspace outlives an exec. A sleeping sandbox
739
+ # wakes first. File info Hashes have "name", "path", "type" ("file" or
740
+ # "dir"), "size", "mode" and "mod_time".
741
+ #
742
+ # The bytes stream to and from the sandbox's host, so a file has no size
743
+ # cap but its disk; one request body is at most 100 MB through the API
744
+ # (#upload sends a bigger one in parts). Hosts without streamed files
745
+ # take at most 8 MiB a file (413 too_large).
707
746
  #
708
747
  # Needs the host's data plane; on hosts without it the API answers 501
709
748
  # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not every
@@ -718,9 +757,11 @@ module Kosa8
718
757
  "#<Kosa8::CloudFiles sandbox=#{@sandbox.id.inspect}>"
719
758
  end
720
759
 
721
- # The file's bytes, as a binary (ASCII-8BIT) String.
722
- def read(path)
723
- @cloud.request_bytes("GET", query("/files", path), raw: true)
760
+ # The file's bytes, as a binary (ASCII-8BIT) String. +range+ reads part
761
+ # of it: a Range of byte offsets (100..199, 100..), a negative Integer
762
+ # for the last bytes (-500), or "bytes=a-b" as sent.
763
+ def read(path, range: nil)
764
+ @cloud.request_bytes("GET", query("/files", path), raw: true, headers: CloudFiles.range_header(range))
724
765
  end
725
766
 
726
767
  # The file as text (UTF-8 by default).
@@ -729,12 +770,64 @@ module Kosa8
729
770
  end
730
771
 
731
772
  # Create or replace a file with +content+ (a String; sent as raw bytes).
732
- # Returns its info Hash.
733
- def write(path, content)
734
- r = @cloud.request_bytes("PUT", query("/files", path), data: content.to_s)
773
+ # Returns its info Hash. +offset:+ writes it at that byte, keeping the
774
+ # rest of the file (parts of a big file, in any order); +append: true+
775
+ # adds it at the end (never retried after no answer, so it is not added
776
+ # twice); +mode:+ sets permission bits ("755" or 0o755).
777
+ def write(path, content, offset: nil, append: false, mode: nil)
778
+ r = @cloud.request_bytes("PUT", query("/files", path, CloudFiles.put_params(offset, append, mode)),
779
+ data: content.to_s)
735
780
  r.is_a?(Hash) ? (r["file"] || {}) : {}
736
781
  end
737
782
 
783
+ # The Range header for +range+ (see #read), or nil.
784
+ def self.range_header(range)
785
+ return nil if range.nil?
786
+
787
+ v = case range
788
+ when String then range
789
+ when Integer
790
+ raise ArgumentError, "range: a negative Integer reads the last bytes, e.g. -500" unless range.negative?
791
+
792
+ "bytes=#{range}"
793
+ when Range
794
+ first = range.begin
795
+ last = range.end
796
+ unless first.is_a?(Integer) && first >= 0 && (last.nil? || (last.is_a?(Integer) && last >= first))
797
+ raise ArgumentError, "range: byte offsets from 0, e.g. 0..1023 or 1024.."
798
+ end
799
+
800
+ last -= 1 if !last.nil? && range.exclude_end?
801
+ raise ArgumentError, "range: an empty Range" if !last.nil? && last < first
802
+
803
+ "bytes=#{first}-#{last}"
804
+ else raise ArgumentError, "range: a Range of byte offsets, a negative Integer or \"bytes=a-b\""
805
+ end
806
+ raise ArgumentError, "range: one byte range, bytes=a-b, a- or -n" unless /\Abytes=(\d+-\d*|-\d+)\z/.match?(v)
807
+
808
+ { "Range" => v }
809
+ end
810
+
811
+ # The query parameters of a write (offset=, append=, mode=).
812
+ def self.put_params(offset, append, mode)
813
+ out = []
814
+ raise ArgumentError, "give offset: or append: true, not both" if !offset.nil? && append
815
+
816
+ unless offset.nil?
817
+ raise ArgumentError, "offset: a whole number of bytes, 0 or more" unless offset.is_a?(Integer) && offset >= 0
818
+
819
+ out << ["offset", offset.to_s]
820
+ end
821
+ out << %w[append 1] if append
822
+ unless mode.nil?
823
+ m = mode.is_a?(Integer) ? format("%o", mode) : mode.to_s
824
+ raise ArgumentError, 'mode: permission bits in octal, e.g. "755" or 0o755' unless /\A[0-7]{3,4}\z/.match?(m)
825
+
826
+ out << ["mode", m]
827
+ end
828
+ out
829
+ end
830
+
738
831
  # A folder's entries (default /workspace), as info Hashes.
739
832
  def list(path = "/workspace")
740
833
  r = @cloud.request("GET", query("/files/list", path))