pinesandbox 0.3.19 → 0.3.21

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: 42cf362beb935ed10df113f8dae0e006d141ab3849f3203630fa0aad880a4616
4
- data.tar.gz: '09865bf5bd34bfb3dcd6b3832ff8dcd69e992e2fa9b485215525b154567b9528'
3
+ metadata.gz: 0d156958acb2d1acd0f962691b98b7d9427d0483b043f0f94bc9a46d35b0a69e
4
+ data.tar.gz: feee8dff7adffd1f7bd962fe94fe639bb2328045fc1cb6b17637693b7cffc200
5
5
  SHA512:
6
- metadata.gz: 5b62511ef3c2399f26d15d0372d9707534e06df49f615410b08f68493ccd290bf819d497b294aa49004b70741a4f2e607506acab686cb2cf4a429eb61c75dffe
7
- data.tar.gz: b12ea12e14b46c4ebb078d690e2df1045da8e846548a06518806c0ea8ee5ce0b7d3e9d509662095781e27adb341b9591927f2cd9cb5846684c0db0cda56aeac0
6
+ metadata.gz: 7670a560d04222fd9da967ec3ec44a5703a44c6e7395a2cd32f1f8a072408c0f934633abca1dca7b655f88ab14521d3dc5ebd0521bb86361a279c60314fe87a7
7
+ data.tar.gz: d15cb731f74c548116aa788ff3f0698bf9b6409efe3650db9ae2d7b092b2c75f66397a0a7cc67b538f6d366b84868a9ec41c8c8ca5113025eb187e67bb8d01ef
data/README.md CHANGED
@@ -47,7 +47,7 @@ store.save_credentials(credentials.id, credentials.to_json)
47
47
  computer = client.create_computer(credentials)
48
48
  store.save_binding(computer.id, computer.binding.to_json)
49
49
 
50
- session = computer.create_session(browser: true) # Pine picks the name: save session.name
50
+ session = computer.create_session # Pine picks the name: save session.name
51
51
  session.create_tab(url: "https://example.com")
52
52
  ```
53
53
 
@@ -93,7 +93,7 @@ worker can wait for existing work rather than submit it again. See
93
93
 
94
94
  | Intent | Call | Result |
95
95
  |---|---|---|
96
- | Finish using compute | `computer.stop` | Saves supported state, shuts the Computer down and ends its sessions |
96
+ | Finish using compute | `computer.stop` | Attempts a final save, shuts the Computer down and ends its sessions |
97
97
  | Start a stopped Computer | `client.start_computer(credentials)` | Runs the Computer from its saved state; create new sessions |
98
98
  | Keep live memory for later | `computer.pause` | Keeps the Computer and its sessions in memory; requires project opt-in |
99
99
  | Continue paused work | `computer.resume` | Brings back the paused Computer and its sessions |
@@ -120,11 +120,17 @@ permanent deletion.
120
120
 
121
121
  ## Idle timeout and maximum age
122
122
 
123
- `timeout:` is the inactivity window (default five minutes), not an HTTP request
123
+ `timeout:` is the inactivity window (default 30 minutes), not an HTTP request
124
124
  timeout. Work renews it; reading status, watching events and other observation do
125
125
  not. It starts when the Computer starts, so a one-minute window can expire during
126
126
  slow setup.
127
127
 
128
+ When the agent asks a question, nothing happens on the Computer until the answer
129
+ arrives, so the countdown keeps running. Choose a timeout longer than a person
130
+ may take to reply, or raise it with `set_idle_timeout` when the question arrives.
131
+ A Computer that stops this way saves its state once without confirming it; call
132
+ `stop` yourself when the state matters.
133
+
128
134
  Projects have a lifetime policy unless Pine removed it for one. The standard
129
135
  allowance is one minute to 24 hours of idle time and seven days of maximum age;
130
136
  approved project limits can be higher. A project without one has no maximum age
@@ -157,12 +163,15 @@ lifecycle terms and its opaque `runtime_revision`. Missing lifecycle means the C
157
163
  was started without a project lifetime policy. `client.project_policy` optionally reads
158
164
  allowances for future starts; ordinary operations do not require that call.
159
165
 
160
- `ready_timeout:` bounds waiting for the Computer to start and become ready, and
166
+ `ready_timeout:` (default 300 s) bounds the whole Start: waiting for the current
167
+ Computer runtime's release, creating the new one and waiting until it's ready.
161
168
  `bind_ready_timeout:` bounds the following handshake. They do not change the
162
169
  Computer's expiry. For example, `timeout: 28_800, ready_timeout: 120` requests
163
- eight hours of idle time with a two-minute readiness wait. These waits are
164
- separate from transport retries and cleanup; see the
165
- [integration guide](https://console.pinecomputer.io/docs/integration).
170
+ eight hours of idle time with a two-minute readiness wait. If it runs out,
171
+ `ReadyTimeoutError` names the runtime waited on (`sandbox_id`), its `last_state`
172
+ and `last_reason`, and the seconds `waited`; nothing was attached and the binding
173
+ is unchanged. These waits are separate from transport retries and cleanup; see the
174
+ [integration guide](https://console.pinecomputer.io/docs/integration#when-start-waits-or-refuses).
166
175
 
167
176
  ## Handle failures without replacing live work
168
177
 
@@ -170,11 +179,18 @@ separate from transport retries and cleanup; see the
170
179
  Read `status`; its `NotFoundError` confirms that it has. A
171
180
  data-plane `SandboxGoneError` alone does not: paused/restoring Computers can
172
181
  temporarily have no route.
173
- - `SandboxRetainedError` (a `BindError`) means Start found the Computer still
174
- running or paused.
175
- Match its `sandbox_id` to your saved binding, or reload the latest binding from
176
- your database. Reconnect, Resume or finish Stop as appropriate; an ID alone
177
- cannot reconstruct a missing token.
182
+ - `ComputerAlreadyStartedError` (a `BindError`, not a `SandboxRetainedError`)
183
+ means Start or Recover found the Computer already started; nothing was
184
+ released or started. Reconnect with the saved binding, or Stop it first to
185
+ start over.
186
+ - `SandboxRetainedError` (a `BindError`) means Start or Recover found a Computer
187
+ runtime it may not replace; nothing was released or started. Its `state` and
188
+ `reason` say which. For a `:failed` runtime, call `recover_computer`, or Stop
189
+ and then Start; with the reason `CaptureTimeout` (`CAPTURE_TIMEOUT` on later
190
+ servers) `recover_computer` refuses until the capture settles. Otherwise match
191
+ its `sandbox_id` to
192
+ your saved binding, or reload the latest binding from your database, and
193
+ Reconnect or Resume; an ID alone cannot reconstruct a missing token.
178
194
  - A Stop timeout means completion is unconfirmed, not canceled. Keep the binding
179
195
  and observe or retry Stop. Older servers report `StopSaveError` for a failed or
180
196
  unconfirmed save; current servers still shut the Computer down.
@@ -183,7 +199,9 @@ separate from transport retries and cleanup; see the
183
199
  retrying with a higher revision.
184
200
  - If a registered Computer's Start reply is lost before saving its binding,
185
201
  serialize recovery, call `client.stop_computer(id)`, then Start separately with
186
- the saved credentials. This stops the Computer whose token was lost.
202
+ the saved credentials. It stops whichever runtime the Computer's binding
203
+ points to when it's called, which may be one another worker has just started,
204
+ so use it only for this recovery.
187
205
  - An interrupted first Create can fail before registering the Computer. Stop-by-ID
188
206
  then returns true, but Start raises `UnknownComputerError`. For that initial
189
207
  creation, retry Create with your saved credentials after confirming the project
@@ -200,6 +218,31 @@ basis; after a process crash, that Computer sandbox runs until it expires.
200
218
  Longer requested timeouts can leave abandoned compute running longer. See
201
219
  [Errors](#errors) for the error types.
202
220
 
221
+ ## Slow or interrupted networks
222
+
223
+ ```ruby
224
+ client = PineSandbox::Client.new(endpoint: "https://pinesandbox.io", api_key: ENV.fetch("PINE_API_KEY"),
225
+ connect_timeout: 20, request_timeout: 60)
226
+ ```
227
+
228
+ `connect_timeout:` (default 10 seconds) bounds opening one connection: the TCP
229
+ connect, then the TLS handshake. `request_timeout:` (default 30 seconds) bounds a
230
+ request that has no budget of its own; a turn `wait` read gets the time the
231
+ Computer holds it on top. Raise them for a slow or distant network, for example
232
+ behind a proxy whose TLS handshake takes seconds.
233
+
234
+ A request whose connection could not be opened never reached Pine, so the SDK
235
+ sends it again, three attempts in all, whatever it is. After a fault on an open
236
+ connection, only reads, deletes and writes that are safe to repeat are sent
237
+ again; the others raise `PineSandbox::ConnectionError` or
238
+ `PineSandbox::TimeoutError`. A rejected certificate or a host that doesn't exist
239
+ is not special-cased: it goes through the same three attempts and raises
240
+ `PineSandbox::ConnectionError`.
241
+
242
+ A `ConnectionError` or `TimeoutError` from `wait`, `events` or another read means
243
+ this process lost the network, not that the turn or the Computer failed. The turn
244
+ keeps running: wait again, and don't stop the Computer because of it.
245
+
203
246
  ## Stored credentials and older integrations
204
247
 
205
248
  The project API key stays on your backend. Computer credentials contain the state
@@ -227,17 +270,36 @@ For integrations using older storage or field-based methods:
227
270
 
228
271
  ## Sessions
229
272
 
230
- A session is the unit of work — a browser context + bash terminal. Create one, then
231
- drive it (next two sections). A Computer runs up to 3 sessions at once by default;
273
+ A session is the unit of work: its own browser window and bash terminal. Create one,
274
+ then drive it (next two sections). A Computer runs up to 3 sessions at once by default;
232
275
  `computer.capabilities` reports the limit (`sessions.concurrent`).
233
276
 
234
277
  ```ruby
235
- session = computer.create_session(name: "researcher-1", browser: true)
278
+ session = computer.create_session(name: "researcher-1")
236
279
  computer.session("researcher-1") # metadata by name; token is redacted
237
280
  computer.sessions # list all on this Computer
238
281
  computer.destroy_session("researcher-1") # tear down (keeps on-disk dir; clean: true to GC)
239
282
  ```
240
283
 
284
+ A session's agent can use the Computer's [artifacts](#artifacts) only when you create
285
+ the session with `artifact_access: "read_only"` (list and read files) or
286
+ `artifact_access: "read_write"` (also save and delete files and make public links).
287
+ The default is `"none"`. `session.artifact_access` reports the access it was created
288
+ with, and is `nil` for a session from `computer.adopt_session`, whose access only the
289
+ Computer knows (`computer.session(name).artifact_access` reads it). Your own access
290
+ with the project key, through `client.artifacts`, is the same either way.
291
+
292
+ ```ruby
293
+ session = computer.create_session(name: "analyst", artifact_access: "read_only")
294
+ session.artifact_access # => "read_only"
295
+ ```
296
+
297
+ A person who must type a password or an MFA code takes control of the session
298
+ (`session.take_control`, then `release_control`) and types it over the desktop while
299
+ the agent waits. A secret your application already holds goes in the task instead
300
+ (`session.agent.run(goal, secrets: {...})`): refer to its name in the goal
301
+ instead of including the sensitive value in task text.
302
+
241
303
  ## Drive — Pine's agent (hand off the loop)
242
304
 
243
305
  For an attached Computer, `computer.require_agent_protocol!` checks public agent
@@ -287,7 +349,9 @@ record.update!(turn_id: turn.turn_id)
287
349
  `wait` holds while the turn runs and returns it when it ends or the timeout
288
350
  passes (still `running`). It never cancels the turn and never follows
289
351
  `next_turn_id` for you. A read whose response was lost, or whose problem is
290
- marked retryable, is read again within the timeout. Only the session's latest
352
+ marked retryable, is read again within the timeout; at the timeout `wait`
353
+ returns the turn as it last read it, or raises the last error when no read came
354
+ back (see [Slow or interrupted networks](#slow-or-interrupted-networks)). Only the session's latest
291
355
  turn can be answered, so starting new work leaves an open question unanswered.
292
356
  Sending the same answer again returns the same new turn without delivering its
293
357
  secrets again; a different answer to an answered turn raises a `409`
@@ -298,7 +362,9 @@ none). A lost response is a network fault, a `408`, or a gateway `502`, `503` or
298
362
  `504`, which cannot say whether the Computer acted. If none arrives, `run`'s
299
363
  error carries `#idempotency_key`: save it and send the run again with it. The
300
364
  error is also a `PineSandbox::RunUnconfirmedError`, so you can rescue that name
301
- or the error's own class. Pass a
365
+ or the error's own class. After a lost response, a resend's error, a
366
+ `SandboxGoneError` included, is marked the same way: rescue
367
+ `RunUnconfirmedError` first. Pass a
302
368
  key of your own, such as your message ID, so a process that restarts can do the
303
369
  same.
304
370
 
@@ -427,6 +493,46 @@ Without a block, `open_file` returns an Enumerator of the chunks. Session files
427
493
  until the Computer stops; save what you need first. Routes: `/files` in the
428
494
  [Computer API reference](https://console.pinecomputer.io/spec/computer).
429
495
 
496
+ ## Artifacts
497
+
498
+ A Computer's **artifacts** are the files it keeps beyond its sessions. Reach them
499
+ with the project key, whether the Computer is running or stopped. A session's agent
500
+ can use them only when the session was created with `artifact_access: "read_only"`
501
+ or `"read_write"` (see [Sessions](#sessions)); that choice doesn't change your own
502
+ access here.
503
+
504
+ ```ruby
505
+ artifacts = client.artifacts(computer_id)
506
+
507
+ page = artifacts.list(prefix: "research/") # one page: files, folders, next_page_token
508
+ page.files.each { |file| puts "#{file.path} #{file.size} #{file.note}" }
509
+
510
+ artifacts.upload("inputs/brief.pdf", Pathname("brief.pdf"), note: "the brief")
511
+ artifacts.upload("inputs/notes.txt", "plain bytes")
512
+ artifacts.download("reports/q3.pdf", "q3.pdf") # => bytes written
513
+ artifacts.open("reports/q3.csv") { |chunk| io.write(chunk) }
514
+ artifacts.copy(other_computer_id, "templates/form.pdf", "inputs/form.pdf")
515
+ artifacts.delete("inputs/notes.txt")
516
+
517
+ # A public link, served by the running Computer until it stops:
518
+ computer.artifact_link("reports/q3.pdf", expires_in_seconds: 86_400) # => { "url" => ..., "expires_at" => ... }
519
+ ```
520
+
521
+ The SDK gets one short-lived storage token from Pine and sends the files straight to
522
+ and from storage, never through Pine; it renews the token before it lapses. An upload
523
+ takes a String of bytes, a `Pathname` or an IO with a known size, and resumes after a
524
+ dropped connection; without `content_type:` it is typed by its path's extension, the
525
+ same way in every Pine SDK. A download writes beside the destination and renames into
526
+ place. `download` and `open` resume after a dropped connection, a request timeout, a
527
+ 429 or a 5xx other than 501, from where they stopped and from the same version of the
528
+ file (one replaced meanwhile raises `PineSandbox::PreconditionFailedError`). `copy` also copies within the
529
+ Computer, given its own id. A missing file raises `PineSandbox::ArtifactNotFoundError`
530
+ (`#path`); while the Computer's artifacts are over their limit, `upload` and `copy`
531
+ raise `PineSandbox::ArtifactStorageFullError` without sending anything, and check
532
+ again on the next call, so deleting files makes room. `open` passes each chunk on as it
533
+ arrives with faraday-net_http 3.0 or later; an older faraday-net_http gives the body
534
+ only once it is complete, so `open` writes it to a temporary file first.
535
+
430
536
  ## Skills — `learn` / `teach` (and when each blocks)
431
537
 
432
538
  `session.learn` and `session.teach` author a learned-skill **draft** from
@@ -475,14 +581,14 @@ gate: nothing learned reaches another agent until you activate it.
475
581
 
476
582
  ```ruby
477
583
  computer.checkpoint # synchronous state save (content-hash dedup) — before a risky step
478
- computer.stop # save cookies, learned skills and localStorage, then shut the Computer down
584
+ computer.stop # try a final save of cookies, learned skills and localStorage, then shut the Computer down
479
585
  computer.kill # shut the Computer down without waiting for a save
480
586
  client.delete_computer(computer) # PERMANENT: kill if attached, then delete id + saved state
481
587
  ```
482
588
 
483
589
  `stop` and `kill` keep the Computer's identity and saved state; `delete_computer`
484
590
  (a `Computer` or its id) ends both. The id is refused for every later attach, saved
485
- state is purged after 24 hours, and the id is never reusable. Deleting an unknown,
591
+ state is purged after 25 hours, and the id is never reusable. Deleting an unknown,
486
592
  already-deleted, or other project's id also returns `true`. There is no undelete.
487
593
 
488
594
  `stop` submits graceful Stop to Pine's controller, then waits up to 390s
@@ -506,23 +612,31 @@ authorization alone, then call Start separately. This lookup selects one binding
506
612
  it never follows a concurrent newer binding. Private keys remain necessary for
507
613
  Start and cannot be recovered from the ID.
508
614
 
509
- A true result proves the Computer has shut down or was already gone.
510
- It does not prove a final save when the Computer had already gone, and provider
511
- snapshot cleanup can still be running. Start restores only the latest committed
615
+ A true result means the runtime this handle names is no longer running, or that
616
+ the handle has no binding. It does not confirm that a final
617
+ save succeeded (the save result can't be read), and provider snapshot cleanup
618
+ can still be running. Start restores only the latest committed
512
619
  state. Cookies, learned skills and compatible localStorage survive supported
513
620
  saved-state recovery; tabs, session files, page memory and IndexedDB do not.
514
621
 
515
- `start_computer` reads the current binding revision once, checks that the
516
- Computer has stopped, waiting for an already accepted shutdown if needed,
517
- and creates a new binding. A conflict stays a conflict;
622
+ `start_computer` reads the current binding revision once, then applies the rules in
623
+ [When Start waits or refuses](https://console.pinecomputer.io/docs/integration#when-start-waits-or-refuses):
624
+ it waits within `ready_timeout:` while the current runtime is saving or stopping,
625
+ refuses the other states (an already started runtime with
626
+ `ComputerAlreadyStartedError`, the rest with `SandboxRetainedError`), and creates
627
+ a new binding.
628
+ A conflict stays a conflict;
518
629
  it never adopts a newer revision and displaces another worker's winner. For a
519
- Computer you recorded as failed, explicitly call
630
+ Computer that failed, explicitly call
520
631
  `client.recover_computer(credentials)`.
521
632
  Recovery accepts possible unsaved-state loss, shuts the failed Computer down
522
- with a version precondition, waits up to 90s for it to shut down, then Starts. It
523
- refuses healthy running or paused Computers and an unresolved capture timeout. If
524
- shutting it down times out, retry later; nothing new has been started. `kill` remains
525
- an unconditional destructive operation.
633
+ with a version precondition, waits within the same `ready_timeout:` for it to shut
634
+ down, then Starts. It refuses a running Computer with
635
+ `ComputerAlreadyStartedError`, and a paused one or an unresolved capture timeout
636
+ with `SandboxRetainedError`. If the wait runs out,
637
+ `ReadyTimeoutError` is raised and nothing new has been started. `kill` remains
638
+ an unconditional destructive operation. `Computer#attach` is deprecated: it skips
639
+ this check; use `start_computer` or `recover_computer`.
526
640
 
527
641
  This SDK's retryable Start and server-owned Stop require the updated backend
528
642
  and a compatible Computer; neither requires Pause opt-in. Existing
@@ -571,9 +685,11 @@ Three typed families, one per credential exchange (see `lib/pinesandbox/errors.r
571
685
  A Computer that can no longer be reached raises `PineSandbox::SandboxGoneError`;
572
686
  it preserves the wire diagnostics and original `ApiError` cause. Errors about a
573
687
  resource on a live Computer remain distinct, including
574
- `PineSandbox::SessionNotFound` and `PineSandbox::ControlNotHeld`.
688
+ `PineSandbox::SessionNotFound` and `PineSandbox::ControlNotHeld`. Once a Stop
689
+ has begun, whoever sent it, every call raises `PineSandbox::ComputerStopped`, a
690
+ `ConflictError`: follow the Stop in `computer.status`, then Start.
575
691
 
576
- - **`BindError`** — `Computer#attach` outcomes: `BindAuthError`,
692
+ - **`BindError`** — attach handshake outcomes: `BindAuthError`,
577
693
  `ComputerAlreadyAttachedError`, `SandboxUnusableError`, `SavedStateUnavailableError`,
578
694
  `BindTimeoutError`; plus `TokenRejectedError` on a post-bind 401 for the
579
695
  Computer token (`ct_` not recognized — on a running Computer it is
@@ -581,11 +697,16 @@ resource on a live Computer remain distinct, including
581
697
  for a session token is an ordinary `UnauthorizedError`. If `create_computer` raises
582
698
  `AttachAuthorizationCommittedError`, retain its non-nil `#credentials` and inspect `#sandbox_id` before deciding
583
699
  whether to stop or recover the failed Computer. Credential inspection redacts private material.
700
+ A `BindError` from a call that needs the binding means the handle has none: it
701
+ was never attached, or its own Stop, Kill or Delete removed the binding.
584
702
  - **`AttachCredentialsError`** — the portal attach-credentials flow:
585
703
  `UnknownComputerError` (404 — deleted or cross-project),
586
704
  `ProjectAccessDenied` (403), and `BindingRevisionConflictError` (412 — another start changed the binding; `#current_binding_revision` /
587
705
  `#current_sandbox_id` identify the winner. Do not retry automatically). A bad `pk_` (401),
588
706
  rate limit (429), and server errors are the base `AttachCredentialsError`.
707
+ A 409 whose `#problem_type` is `urn:pinesandbox:problem:idempotency-receipt-expired`
708
+ means an attach was sent again after Portal's receipt for it had expired.
709
+ Start doesn't send it again and shuts the new runtime down, so starting again is safe.
589
710
  Inspect the stable problem `#problem_type` and optional safe `#reason`; raw
590
711
  internal exceptions are never part of the API contract.
591
712
  - **`ControlTokenError`** — the `pk_` → project-token mint: `InvalidClientKey`
@@ -0,0 +1,32 @@
1
+ require "faraday"
2
+ require "faraday/net_http"
3
+
4
+ module PineSandbox
5
+ module Adapters
6
+ # @api private — Faraday's Net::HTTP adapter, except that a failure while
7
+ # connecting raises ConnectFailed: nothing was sent, so the request may be
8
+ # sent again whatever its operation.
9
+ class ConnectAwareNetHttp < Faraday::Adapter::NetHttp
10
+ # The connection could not be established (name resolution, refused or
11
+ # unreachable, connect or TLS handshake timeout or failure): the request
12
+ # was not sent.
13
+ class ConnectFailed < Faraday::ConnectionFailed; end
14
+
15
+ # Wraps Net::HTTP#connect, which opens the socket and runs the TLS handshake.
16
+ module ConnectPhase
17
+ private
18
+
19
+ def connect
20
+ super
21
+ rescue StandardError => e
22
+ raise ConnectFailed, e
23
+ end
24
+ end
25
+
26
+ # Whether a transport fault shows the request was not sent.
27
+ def self.not_sent?(error) = error.is_a?(ConnectFailed)
28
+
29
+ def build_connection(env) = super.tap { |http| http.extend(ConnectPhase) }
30
+ end
31
+ end
32
+ end