withruntime 0.1.0 → 0.2.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.
metadata CHANGED
@@ -1,24 +1,26 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: withruntime
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Runtime
8
+ autorequire:
8
9
  bindir: bin
9
10
  cert_chain: []
10
- date: 1980-01-02 00:00:00.000000000 Z
11
+ date: 2026-10-16 00:00:00.000000000 Z
11
12
  dependencies: []
12
13
  description: 'Linux sandboxes for agents, and every other Runtime Cloud product: streaming
13
14
  commands and terminals, files and watches, images, durable volumes and backups,
14
15
  domains, TCP ports, private networking and secrets. Standard library only.'
16
+ email:
15
17
  executables: []
16
18
  extensions: []
17
19
  extra_rdoc_files: []
18
20
  files:
19
- - GUIDE.md
20
21
  - LICENSE
21
22
  - lib/withruntime.rb
23
+ - lib/withruntime/api_defaults.rb
22
24
  - lib/withruntime/client.rb
23
25
  - lib/withruntime/credentials.rb
24
26
  - lib/withruntime/errors.rb
@@ -34,6 +36,7 @@ files:
34
36
  - lib/withruntime/transport.rb
35
37
  - lib/withruntime/tunnel.rb
36
38
  - lib/withruntime/version.rb
39
+ - lib/withruntime/wallet.rb
37
40
  - lib/withruntime/websocket.rb
38
41
  homepage: https://withruntime.com
39
42
  licenses:
@@ -44,6 +47,7 @@ metadata:
44
47
  source_code_uri: https://github.com/withruntime/runtime/tree/main/sdks/ruby
45
48
  bug_tracker_uri: https://github.com/withruntime/runtime/issues
46
49
  rubygems_mfa_required: 'true'
50
+ post_install_message:
47
51
  rdoc_options: []
48
52
  require_paths:
49
53
  - lib
@@ -58,7 +62,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
58
62
  - !ruby/object:Gem::Version
59
63
  version: '0'
60
64
  requirements: []
61
- rubygems_version: 4.0.16
65
+ rubygems_version: 3.4.20
66
+ signing_key:
62
67
  specification_version: 4
63
68
  summary: 'Runtime Cloud: one client for every Runtime product. Sandboxes first.'
64
69
  test_files: []
data/GUIDE.md DELETED
@@ -1,406 +0,0 @@
1
- # Ruby SDK
2
-
3
- One Ruby client for every Runtime Cloud product.
4
-
5
- The `withruntime` gem needs Ruby 3.2 or later and uses only the standard
6
- library. It is safe to share between threads and keeps its connections open.
7
-
8
- ```bash no-run
9
- gem install withruntime
10
- ```
11
-
12
- **The client finds its key by itself.** It uses `RUNTIME_API_KEY` when that is
13
- set, and otherwise the connection this machine saved (any `npx withruntime`
14
- command connects it, with one browser approval).
15
-
16
- On a server, put a key from https://withruntime.com/account/keys in
17
- `RUNTIME_API_KEY` from your secret manager. Never put it in source code, a URL
18
- or a command-line argument. With no key anywhere, `WithRuntime::Client.new`
19
- raises `WithRuntime::AuthenticationError` whose `code` is `missing_api_key`
20
- and whose `hint` says how to get one.
21
-
22
- ## Hello, sandbox
23
-
24
- ```ruby
25
- require "withruntime"
26
-
27
- runtime = WithRuntime::Client.new
28
- sbx = runtime.sandboxes.create(funding: "trial")
29
- begin
30
- puts sbx.exec("python3 -c 'print(6 * 7)'", check: true).stdout
31
- ensure
32
- sbx.stop
33
- end
34
- ```
35
-
36
- `create` returns once the sandbox is running. With no arguments you get the
37
- free trial while it lasts, the default region, and 2 vCPU, 4 GiB of memory and
38
- a 4 GiB disk for up to 30 minutes. `funding: "trial"` never falls back to paid
39
- credit. Every field is optional, in snake_case:
40
-
41
- ```ruby
42
- require "withruntime"
43
-
44
- runtime = WithRuntime::Client.new
45
- sbx = runtime.sandboxes.create(
46
- name: "tests-42",
47
- labels: { team: "search", job: "42" },
48
- vcpu: 2,
49
- memory_mib: 4096,
50
- disk_mib: 8192,
51
- timeout_seconds: 900,
52
- on_lease_end: "stop",
53
- network: { internet: true, allow: ["rubygems.org", "*.githubusercontent.com"] }
54
- )
55
- puts sbx.id, sbx.info.funding, sbx.info.expires_at
56
- sbx.stop
57
- ```
58
-
59
- An answer reads by snake_case name (`sbx.info.memory_mib`) or by the API's own
60
- key (`sbx.info["memoryMiB"]`), so a field newer than the SDK is always there. A
61
- string key in a request (`"newField" => 1`) is sent as it is.
62
-
63
- ## Run commands
64
-
65
- A string runs under `bash -c`; an array runs the program directly, with no
66
- shell, which is what you want for untrusted arguments.
67
-
68
- ```ruby
69
- require "withruntime"
70
-
71
- runtime = WithRuntime::Client.new
72
- sbx = runtime.sandboxes.create
73
- sbx.exec("mkdir -p app && echo 'print(1 + 1)' > app/main.py")
74
- run = sbx.exec(["python3", "main.py"], cwd: "/workspace/app", env: { API_TOKEN: ENV.fetch("API_TOKEN", "") }, timeout: 120)
75
- warn run.stderr unless run.exit_code.zero?
76
- print run.stdout
77
-
78
- sbx.exec("for i in 1 2 3; do echo line $i; sleep 1; done", on_stdout: ->(text) { print text })
79
- sbx.exec_stream("node --version") do |event|
80
- print event["data"] if event["type"] == "stdout"
81
- end
82
- sbx.stop
83
- ```
84
-
85
- - `env:` is how secrets reach a command. It is never echoed back. Never put a
86
- secret in the command line itself.
87
- - `stdin:` gives the command input, then closes it.
88
- - The default timeout is 60 seconds; the maximum is a day. A timeout is a
89
- result (`timed_out` is true, with the output so far), not an exception.
90
- - `check: true` raises `WithRuntime::CommandError`, with the exit code and
91
- output, on a non-zero exit or a timeout.
92
- - With `on_stdout:`, `on_stderr:` or a timeout over a minute, the command
93
- streams and the result keeps everything it printed. A long stream resumes by
94
- itself when the server ends it, so no output is dropped.
95
-
96
- ## Background processes
97
-
98
- ```ruby
99
- require "withruntime"
100
-
101
- runtime = WithRuntime::Client.new
102
- sbx = runtime.sandboxes.create
103
- server = sbx.spawn("python3 -m http.server 8000", cwd: "/workspace")
104
- repl = sbx.spawn(["python3", "-i", "-q"], pipe_stdin: true)
105
- repl.write("print(21 * 2)\n", eof: true)
106
- print repl.wait.stdout
107
- sbx.processes.each { |process| puts "#{process.id} #{process.state} #{process.command}" }
108
- server.kill("SIGTERM")
109
- sbx.stop
110
- ```
111
-
112
- A process outlives your connection; get it back with `sbx.process(id)`.
113
- `write` tracks input offsets, so a retried write is never typed twice.
114
-
115
- ## Files
116
-
117
- ```ruby
118
- require "withruntime"
119
-
120
- runtime = WithRuntime::Client.new
121
- sbx = runtime.sandboxes.create
122
- sbx.files.write("/workspace/data/input.csv", "a,b\n1,2\n")
123
- print sbx.files.read_text("/workspace/data/input.csv")
124
- sbx.files.list("/workspace", depth: 2).each { |entry| puts "#{entry.type} #{entry.size} #{entry.path}" }
125
- sbx.files.mkdir("/workspace/out")
126
- sbx.files.rename("/workspace/data/input.csv", "/workspace/out/input.csv")
127
- sbx.files.upload("./lib", "/workspace/project/lib")
128
- sbx.files.download("/workspace/out", "./out")
129
- sbx.stop
130
- ```
131
-
132
- `write` makes parent directories and replaces the file atomically; a file over
133
- 1 MiB goes in parallel chunks checked by SHA-256. `stat` returns `nil` for a
134
- path that does not exist. `upload` and `download` move a whole directory as
135
- one gzipped archive. Pass `mode: 0o755` to write an executable, or
136
- `mode: 0` for no permission bits. `chmod(path, mode)` changes an existing
137
- file. A caller-supplied `idempotency_key:` also makes a complete large-file
138
- write safe to repeat; each upload phase keeps its own stable key. On an
139
- older guest, setting a mode also needs the exec grant for its chmod fallback.
140
-
141
- ## Pause, wake, fork and snapshot
142
-
143
- ```ruby
144
- require "withruntime"
145
-
146
- runtime = WithRuntime::Client.new
147
- sbx = runtime.sandboxes.create(funding: "trial")
148
- sbx.pause # memory and files are kept; compute billing stops
149
- again = runtime.sandboxes.get(sbx.id)
150
- again.wake(timeout_seconds: 1200)
151
- again.extend_lease(600)
152
-
153
- copies = again.fork(count: 2, funding: "trial")
154
- copies.each(&:stop)
155
- snapshot = again.snapshot(name: "ready", retention_days: 7)
156
- runtime.sandboxes.create(snapshot: snapshot.id, funding: "trial").stop
157
- runtime.snapshots.delete(snapshot.id)
158
- again.stop
159
- ```
160
-
161
- A fork copies a sandbox as it is now, with its files, memory and running
162
- processes, on the same server; see [JavaScript](./javascript) for what forks
163
- and snapshots keep and how they are billed. If a copy fails, the error's
164
- `details["startedSandboxIds"]` names the copies that did start. Because
165
- `extend` is Ruby's own, the lease is extended with `extend_lease(seconds)`.
166
- `sbx.keep_alive` extends it from your process until `stop`, and
167
- `runtime.sandboxes.get_or_create(name, **fields)` answers the sandbox with
168
- that name, woken or restarted, or creates it.
169
-
170
- ## Share a port
171
-
172
- ```ruby
173
- require "withruntime"
174
-
175
- runtime = WithRuntime::Client.new
176
- sbx = runtime.sandboxes.create
177
- sbx.spawn("python3 -m http.server 3000")
178
- preview = sbx.previews.create(3000)
179
- puts preview.url, preview.token # send the token as x-runtime-preview-token
180
- sbx.stop
181
- ```
182
-
183
- A preview is private by default; `visibility: "public"` shares it with anyone
184
- who has the address. Addresses are under `runtimehost.com`.
185
-
186
- ## Images, volumes, network rules and secrets
187
-
188
- ```ruby
189
- require "withruntime"
190
-
191
- runtime = WithRuntime::Client.new
192
- image = runtime.images.build(name: "data", recipe: { pip: ["pandas"], apt: ["jq"] }) { |line| puts line.text }
193
- volume = runtime.volumes.create(size_mib: 10_240, name: "cache")
194
- sbx = runtime.sandboxes.create(image: image.id, volumes: [{ volume_id: volume.id, path: "/data" }])
195
- print sbx.exec("python3 -c 'import pandas; print(pandas.__version__)'").stdout
196
- cell = sbx.interpreter.run("import math\nround(math.pi * 2, 3)")
197
- puts cell.results.first.data["text/plain"]
198
- sbx.network.set(internet: true, allow: ["pypi.org", "*.pythonhosted.org"])
199
- sbx.stop
200
-
201
- secret = runtime.secrets.set("OPENAI_API_KEY", value: "sk-...", hosts: ["api.openai.com"])
202
- puts secret.placeholder # what sandboxes see in $OPENAI_API_KEY
203
- ```
204
-
205
- `images.build` waits until the image is ready and raises with code
206
- `image_failed` when the build fails; `images.create` queues it and returns. A
207
- Dockerfile build takes `dockerfile:` and `context_dir:`, the folder
208
- `docker build` would read, with its `.dockerignore`; only the parts the server
209
- does not have yet are uploaded. See [custom images](./images). A volume lives
210
- on one server; volume backups can restore its data onto another host.
211
- `sbx.desktop` drives a Linux desktop in the sandbox.
212
-
213
- ## Domains, TCP ports and private networking
214
-
215
- ```ruby
216
- require "withruntime"
217
-
218
- runtime = WithRuntime::Client.new
219
- sbx = runtime.sandboxes.create
220
- runtime.domains.add(hostname: "app.example.org", sandbox_id: sbx.id, port: 8080)
221
- p runtime.domains.get("app.example.org") # DNS records to install, then verify
222
- runtime.domains.verify("app.example.org")
223
- port = runtime.ports.open(sandbox_id: sbx.id, port: 5432)
224
- p port
225
- runtime.ports.close(port.id)
226
- runtime.domains.remove("app.example.org")
227
- sbx.stop
228
- ```
229
-
230
- `runtime.addresses.reserve(family: 4)` reserves a dedicated address;
231
- `list` and `release(id)` manage it. Returned funding fields and integer money
232
- are preserved. `runtime.tunnel` manages the account's WireGuard network with
233
- `create`, `get`, `delete`, `add_peer`, `rotate_peer` and `remove_peer`.
234
- Save a generated peer's `config` securely even when `config_ready` is false:
235
- its private key is returned once. Calls generating a private key are not
236
- retried automatically. `runtime.sso.get` reads the organization's SSO state.
237
-
238
- ## Backups, mounts, MCP and recordings
239
-
240
- ```ruby
241
- require "withruntime"
242
-
243
- runtime = WithRuntime::Client.new
244
- volume = runtime.volumes.create(size_mib: 1024)
245
- backup = runtime.volumes.backup(volume.id, name: "before-import", retention_days: 7)
246
- runtime.volumes.set_backup_policy(volume.id, daily: true, retention_days: 7)
247
- restored = runtime.volumes.restore(backup.id, name: "restored")
248
- p runtime.volumes.backups(volume_id: volume.id).data
249
- runtime.volumes.delete_backup(backup.id)
250
- runtime.volumes.delete(restored.id)
251
- runtime.volumes.delete(volume.id)
252
- ```
253
-
254
- `sbx.mounts.add(provider: "s3", bucket: "data", path: "/data", secret: "S3_KEY")`
255
- mounts an object store; `list` and `remove(path)` manage mounts. The named
256
- secret stays on Runtime. `runtime.mcp.catalog` lists supported servers;
257
- `sbx.mcp.start(servers: [{ id: "fetch" }])`, `ready`, `get` and `stop` manage
258
- servers in a sandbox. Server `secrets`, `env` and `options` keep their
259
- original dictionary keys.
260
-
261
- `sbx.desktop.recordings.start(fps: 10)` returns a recording. Use `get(id)`,
262
- `list`, `stop(id)`, `download(id)` for MP4 bytes, and `delete(id)` to manage it.
263
-
264
- ## Watch files
265
-
266
- ```ruby
267
- require "withruntime"
268
-
269
- runtime = WithRuntime::Client.new
270
- sbx = runtime.sandboxes.create
271
- watch = sbx.files.watch("/workspace", recursive: true)
272
- begin
273
- watch.events.each { |event| puts "#{event.k}: #{event.path}" }
274
- ensure
275
- watch.stop
276
- sbx.stop
277
- end
278
- ```
279
-
280
- The reader follows continuation messages and keeps `watch.cursor`. Overflow
281
- and lost-event notices reach your block. `watch.close` cancels only the active
282
- reader; another thread can call it while HTTP headers, a body or a retry delay
283
- is pending. `watch.stop` also removes the watch in the guest and prevents new
284
- readers. A paused sandbox ends the current stream.
285
-
286
- ## Terminal and local port forwarding
287
-
288
- ```ruby
289
- require "withruntime"
290
-
291
- runtime = WithRuntime::Client.new
292
- sbx = runtime.sandboxes.get("your-sandbox-id")
293
- terminal = sbx.terminal(cols: 100, rows: 30)
294
- begin
295
- terminal.write("printf 'hello\n'\n")
296
- print terminal.read
297
- terminal.resize(cols: 120, rows: 40)
298
- ensure
299
- terminal.close
300
- end
301
- forward = sbx.port_forward(8080)
302
- begin
303
- puts "Local server: http://#{forward.host}:#{forward.port}"
304
- ensure
305
- forward.close
306
- end
307
- ```
308
-
309
- A terminal exposes `read`, `write`, `resize`, `process_id`, `exit_code` and
310
- `close`. `sbx.open_tunnel` shares one authenticated connection across
311
- `connect(port)` and `ssh(public_key)` streams. Each stream supports `read`,
312
- `write`, `close_write` and `close`; half-closing input still permits a response.
313
- `port_forward` binds to `127.0.0.1` and a free port by default; pass `host:`
314
- and `local_port:` to choose them. Closing it releases its listener and active
315
- connections.
316
-
317
- Read responses while writing large requests. An individual unread stream has
318
- at most 1 MiB buffered; overflow closes that stream with
319
- `tunnel_receive_overflow` and leaves other streams usable. Closing a terminal
320
- or tunnel wakes blocked readers and writers. WebSockets use the same API key
321
- and origin, support an HTTP CONNECT proxy, and verify TLS certificates.
322
-
323
- ## Metrics, events and webhooks
324
-
325
- ```ruby
326
- require "withruntime"
327
-
328
- runtime = WithRuntime::Client.new
329
- hook = runtime.webhooks.create(url: "https://example.com/hooks/runtime")
330
- secret = hook.secret # shown once; keep it
331
-
332
- # In your endpoint, with the raw body and the Runtime-Signature header:
333
- begin
334
- event = WithRuntime::Webhooks.verify("{}", "t=0,v1=0", secret)
335
- puts event.type
336
- rescue WithRuntime::WebhookVerificationError => e
337
- puts "refused: #{e.message}"
338
- end
339
- runtime.events.list(type: "sandbox.stopped").each { |event| puts "#{event.created_at} #{event.type}" }
340
- ```
341
-
342
- `sbx.metrics(range: "15m")` returns the sandbox's measured CPU and memory, and
343
- `runtime.otel.create(endpoint: ...)` pushes events and metrics to an
344
- OpenTelemetry endpoint. See [metrics and webhooks](./observability).
345
-
346
- ## Errors and retries
347
-
348
- ```ruby
349
- require "withruntime"
350
-
351
- runtime = WithRuntime::Client.new
352
- begin
353
- runtime.sandboxes.get("00000000-0000-4000-8000-000000000000")
354
- rescue WithRuntime::NotFoundError
355
- puts "no such sandbox"
356
- rescue WithRuntime::Error => e
357
- puts e.code, e.hint, e.request_id
358
- end
359
- ```
360
-
361
- Every error is a `WithRuntime::Error` with `code`, `message`, `hint`,
362
- `request_id`, `status` and `details`. Its subclasses are
363
- `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`,
364
- `ConflictError`, `InvalidRequestError`, `RateLimitError`,
365
- `ServiceUnavailableError`, `ConnectionError` and `CommandError`, the same
366
- classes as the JavaScript, Python, Go and Java SDKs.
367
-
368
- Every write carries an idempotency key, made for you and kept across the
369
- client's own retries. Transport failures, 429, 502, 503 and 504 are retried
370
- with the same key, so a retry never makes two sandboxes or runs a command
371
- twice. `retryable?` says whether trying the same call again may work.
372
-
373
- **A create waits for room.** When every trial slot is taken (`trial_busy`), the
374
- account is at its limit (`quota_exceeded`) or the region is full
375
- (`no_capacity`), `sandboxes.create` waits and sends the same request again, for
376
- up to two minutes. Pass `wait_for_capacity:` (seconds) to the client or to one
377
- create; zero fails at once.
378
-
379
- An owner, admin or developer can make a read-only key and set a daily spending
380
- limit on a key at [API keys](https://withruntime.com/account/keys).
381
- `runtime.limits.get` reads both; past the limit, a create, wake or extension
382
- raises with code `spending_limit_reached`, and it is not retried.
383
-
384
- ## Configuration
385
-
386
- ```ruby
387
- require "withruntime"
388
-
389
- runtime = WithRuntime::Client.new(
390
- api_key: ENV.fetch("MY_RUNTIME_KEY"),
391
- timeout: 120,
392
- max_retries: 4,
393
- wait_for_capacity: 600
394
- )
395
- puts runtime.me.org_id
396
- p runtime.request("GET", "/v1/volumes") # any endpoint, same rules
397
- ```
398
-
399
- - `RUNTIME_API_URL` points the client at another API origin, as `base_url:`
400
- does.
401
- - The client is safe to share between threads. It keeps its connections open
402
- and holds at most 32 calls in flight (`max_connections:`).
403
- - It honours `HTTPS_PROXY` and `NO_PROXY`.
404
- - Money is integer microdollars: 1,000,000 is one US dollar.
405
- `runtime.usage.available` is the account's balance as an exact decimal
406
- string.