pinesandbox 0.3.20 → 0.3.22
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 +4 -4
- data/README.md +94 -32
- data/lib/pinesandbox/adapters/connect_aware_net_http.rb +32 -0
- data/lib/pinesandbox/adapters/coordinator_adapter.rb +127 -60
- data/lib/pinesandbox/agent_mode.rb +32 -18
- data/lib/pinesandbox/agent_turn.rb +1 -1
- data/lib/pinesandbox/artifacts.rb +18 -9
- data/lib/pinesandbox/attach_credentials_source.rb +61 -16
- data/lib/pinesandbox/author_terminal_translator.rb +12 -11
- data/lib/pinesandbox/client.rb +68 -30
- data/lib/pinesandbox/computer.rb +139 -69
- data/lib/pinesandbox/connection.rb +7 -3
- data/lib/pinesandbox/control_plane.rb +33 -15
- data/lib/pinesandbox/control_token_source.rb +3 -1
- data/lib/pinesandbox/diagnostics.rb +4 -3
- data/lib/pinesandbox/error_taxonomy.rb +4 -0
- data/lib/pinesandbox/errors.rb +163 -12
- data/lib/pinesandbox/response_handler.rb +4 -1
- data/lib/pinesandbox/runtime_admission.rb +112 -0
- data/lib/pinesandbox/sandbox_handle.rb +71 -40
- data/lib/pinesandbox/session.rb +4 -0
- data/lib/pinesandbox/terminal_reason.rb +32 -0
- data/lib/pinesandbox/timeouts.rb +22 -0
- data/lib/pinesandbox/version.rb +1 -1
- data/lib/pinesandbox/zone.rb +3 -0
- data/lib/pinesandbox.rb +2 -0
- metadata +5 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 55f1a5304b3816e9e36f1d087f979d082050f2ee19639d489272e35ca55d2a9a
|
|
4
|
+
data.tar.gz: d7e5f8f0f84a2cc876a4a54e2f47ff468c33483760a203cea636c75050891556
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 94cd92b7ff365c67c795346987cd503475bfac9bbf696d26919df8c6d671babe6c891d42e26b7678ca18f81a5a8393e4a078f9bf11e6e3bdbdd75c328670f6f4
|
|
7
|
+
data.tar.gz: 6528144c681b71f9434dfa8dee8d7a1356e0d69cc7730ff763ee79580e4470a86c4fcc814c951984aab9770db09104db17aaa57fca46a79584433c0b831ef14b
|
data/README.md
CHANGED
|
@@ -16,12 +16,12 @@ bundle add pinesandbox
|
|
|
16
16
|
|
|
17
17
|
Bundler pins it to the latest release's compatibility line (`"~> 0.3.<patch>"`), so
|
|
18
18
|
`bundle update` takes later patches but not a new minor version. Using it needs a project key (`pk_…`) from the
|
|
19
|
-
[Console](https://console.pinecomputer.io).
|
|
19
|
+
[Console](https://console.pinecomputer.io). Access is by approval:
|
|
20
20
|
[request access](https://pinecomputer.io/#access) if you don't have one yet. Each
|
|
21
21
|
release is also an archive on the [Ruby SDK page](https://console.pinecomputer.io/sdks/ruby),
|
|
22
22
|
for vendoring.
|
|
23
23
|
|
|
24
|
-
The current
|
|
24
|
+
The current SDK is on the `0.3` compatibility line.
|
|
25
25
|
|
|
26
26
|
## Create a Computer
|
|
27
27
|
|
|
@@ -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` |
|
|
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
|
|
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:`
|
|
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.
|
|
164
|
-
|
|
165
|
-
|
|
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
|
-
- `
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
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.
|
|
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
|
|
@@ -254,8 +297,8 @@ session.artifact_access # => "read_only"
|
|
|
254
297
|
A person who must type a password or an MFA code takes control of the session
|
|
255
298
|
(`session.take_control`, then `release_control`) and types it over the desktop while
|
|
256
299
|
the agent waits. A secret your application already holds goes in the task instead
|
|
257
|
-
(`session.agent.run(goal, secrets: {...})`):
|
|
258
|
-
|
|
300
|
+
(`session.agent.run(goal, secrets: {...})`): refer to its name in the goal
|
|
301
|
+
instead of including the sensitive value in task text.
|
|
259
302
|
|
|
260
303
|
## Drive — Pine's agent (hand off the loop)
|
|
261
304
|
|
|
@@ -306,7 +349,9 @@ record.update!(turn_id: turn.turn_id)
|
|
|
306
349
|
`wait` holds while the turn runs and returns it when it ends or the timeout
|
|
307
350
|
passes (still `running`). It never cancels the turn and never follows
|
|
308
351
|
`next_turn_id` for you. A read whose response was lost, or whose problem is
|
|
309
|
-
marked retryable, is read again within the timeout
|
|
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
|
|
310
355
|
turn can be answered, so starting new work leaves an open question unanswered.
|
|
311
356
|
Sending the same answer again returns the same new turn without delivering its
|
|
312
357
|
secrets again; a different answer to an answered turn raises a `409`
|
|
@@ -317,7 +362,9 @@ none). A lost response is a network fault, a `408`, or a gateway `502`, `503` or
|
|
|
317
362
|
`504`, which cannot say whether the Computer acted. If none arrives, `run`'s
|
|
318
363
|
error carries `#idempotency_key`: save it and send the run again with it. The
|
|
319
364
|
error is also a `PineSandbox::RunUnconfirmedError`, so you can rescue that name
|
|
320
|
-
or the error's own class.
|
|
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
|
|
321
368
|
key of your own, such as your message ID, so a process that restarts can do the
|
|
322
369
|
same.
|
|
323
370
|
|
|
@@ -534,7 +581,7 @@ gate: nothing learned reaches another agent until you activate it.
|
|
|
534
581
|
|
|
535
582
|
```ruby
|
|
536
583
|
computer.checkpoint # synchronous state save (content-hash dedup) — before a risky step
|
|
537
|
-
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
|
|
538
585
|
computer.kill # shut the Computer down without waiting for a save
|
|
539
586
|
client.delete_computer(computer) # PERMANENT: kill if attached, then delete id + saved state
|
|
540
587
|
```
|
|
@@ -565,23 +612,31 @@ authorization alone, then call Start separately. This lookup selects one binding
|
|
|
565
612
|
it never follows a concurrent newer binding. Private keys remain necessary for
|
|
566
613
|
Start and cannot be recovered from the ID.
|
|
567
614
|
|
|
568
|
-
A true result
|
|
569
|
-
|
|
570
|
-
|
|
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
|
|
571
619
|
state. Cookies, learned skills and compatible localStorage survive supported
|
|
572
620
|
saved-state recovery; tabs, session files, page memory and IndexedDB do not.
|
|
573
621
|
|
|
574
|
-
`start_computer` reads the current binding revision once,
|
|
575
|
-
|
|
576
|
-
|
|
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;
|
|
577
629
|
it never adopts a newer revision and displaces another worker's winner. For a
|
|
578
|
-
Computer
|
|
630
|
+
Computer that failed, explicitly call
|
|
579
631
|
`client.recover_computer(credentials)`.
|
|
580
632
|
Recovery accepts possible unsaved-state loss, shuts the failed Computer down
|
|
581
|
-
with a version precondition, waits
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
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`.
|
|
585
640
|
|
|
586
641
|
This SDK's retryable Start and server-owned Stop require the updated backend
|
|
587
642
|
and a compatible Computer; neither requires Pause opt-in. Existing
|
|
@@ -630,9 +685,11 @@ Three typed families, one per credential exchange (see `lib/pinesandbox/errors.r
|
|
|
630
685
|
A Computer that can no longer be reached raises `PineSandbox::SandboxGoneError`;
|
|
631
686
|
it preserves the wire diagnostics and original `ApiError` cause. Errors about a
|
|
632
687
|
resource on a live Computer remain distinct, including
|
|
633
|
-
`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.
|
|
634
691
|
|
|
635
|
-
- **`BindError`** —
|
|
692
|
+
- **`BindError`** — attach handshake outcomes: `BindAuthError`,
|
|
636
693
|
`ComputerAlreadyAttachedError`, `SandboxUnusableError`, `SavedStateUnavailableError`,
|
|
637
694
|
`BindTimeoutError`; plus `TokenRejectedError` on a post-bind 401 for the
|
|
638
695
|
Computer token (`ct_` not recognized — on a running Computer it is
|
|
@@ -640,11 +697,16 @@ resource on a live Computer remain distinct, including
|
|
|
640
697
|
for a session token is an ordinary `UnauthorizedError`. If `create_computer` raises
|
|
641
698
|
`AttachAuthorizationCommittedError`, retain its non-nil `#credentials` and inspect `#sandbox_id` before deciding
|
|
642
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.
|
|
643
702
|
- **`AttachCredentialsError`** — the portal attach-credentials flow:
|
|
644
703
|
`UnknownComputerError` (404 — deleted or cross-project),
|
|
645
704
|
`ProjectAccessDenied` (403), and `BindingRevisionConflictError` (412 — another start changed the binding; `#current_binding_revision` /
|
|
646
705
|
`#current_sandbox_id` identify the winner. Do not retry automatically). A bad `pk_` (401),
|
|
647
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.
|
|
648
710
|
Inspect the stable problem `#problem_type` and optional safe `#reason`; raw
|
|
649
711
|
internal exceptions are never part of the API contract.
|
|
650
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
|
|
@@ -12,6 +12,8 @@ require_relative "../exec_stream_parser"
|
|
|
12
12
|
require_relative "../response_handler"
|
|
13
13
|
require_relative "../streamed_read"
|
|
14
14
|
require_relative "../version"
|
|
15
|
+
require_relative "../timeouts"
|
|
16
|
+
require_relative "connect_aware_net_http"
|
|
15
17
|
|
|
16
18
|
module PineSandbox
|
|
17
19
|
module Adapters
|
|
@@ -30,13 +32,12 @@ module PineSandbox
|
|
|
30
32
|
#
|
|
31
33
|
# A request that is replay-safe in the public operation table is sent
|
|
32
34
|
# again after a transport fault (Operations, RetryPolicy); any other is
|
|
33
|
-
# sent once
|
|
35
|
+
# sent once, unless its connection could not be opened and so nothing was
|
|
36
|
+
# sent. A 401 for a Computer token raises TokenRejectedError; a 401
|
|
34
37
|
# for a session token is the plain UnauthorizedError.
|
|
35
38
|
class CoordinatorAdapter
|
|
36
39
|
include PineSandbox::ResponseHandler
|
|
37
40
|
|
|
38
|
-
DEFAULT_HTTP_TIMEOUT = 30
|
|
39
|
-
DEFAULT_OPEN_TIMEOUT = 5
|
|
40
41
|
# An event stream silent this long (three missed keepalives) is reopened.
|
|
41
42
|
STREAM_IDLE_TIMEOUT = 60
|
|
42
43
|
|
|
@@ -46,13 +47,15 @@ module PineSandbox
|
|
|
46
47
|
# selects the role. `zone` is a PineSandbox::Zone.
|
|
47
48
|
# `host` is the Computer sandbox's data-plane host `<sandbox_id>.computer.<zone>`
|
|
48
49
|
# (scheme-less). `scheme` is http for a .localhost zone (local-dev loop),
|
|
49
|
-
# https otherwise. `clock` paces retries and reconnects.
|
|
50
|
-
|
|
50
|
+
# https otherwise. `clock` paces retries and reconnects. `timeouts` is the
|
|
51
|
+
# client's Timeouts.
|
|
52
|
+
attr_reader :sandbox_id, :host, :scheme, :clock, :timeouts
|
|
51
53
|
|
|
52
54
|
# discovery_token is the Computer token that reads the capability
|
|
53
55
|
# manifest when a request's own token, such as a session's, cannot. An
|
|
54
56
|
# adopted binding passes it; #bind records the one it issues.
|
|
55
|
-
def initialize(zone:, sandbox_id: nil, discovery_token: nil, clock: PineSandbox::SYSTEM_CLOCK
|
|
57
|
+
def initialize(zone:, sandbox_id: nil, discovery_token: nil, clock: PineSandbox::SYSTEM_CLOCK,
|
|
58
|
+
timeouts: Timeouts::DEFAULT)
|
|
56
59
|
@sandbox_id = sandbox_id
|
|
57
60
|
raise ArgumentError, "sandbox_id required" if @sandbox_id.to_s.empty?
|
|
58
61
|
|
|
@@ -60,6 +63,7 @@ module PineSandbox
|
|
|
60
63
|
@scheme = zone.http_scheme # http for a .localhost zone (local-dev loop), https otherwise
|
|
61
64
|
@discovery_token = discovery_token
|
|
62
65
|
@clock = clock
|
|
66
|
+
@timeouts = timeouts
|
|
63
67
|
# This adapter's own connections dial as the zone says (#connection);
|
|
64
68
|
# base_url stays the public host, since a delegated connection hands
|
|
65
69
|
# it to a browser.
|
|
@@ -523,34 +527,43 @@ module PineSandbox
|
|
|
523
527
|
# no timeout at all.
|
|
524
528
|
http_timeout = timeout_ms ? ((timeout_ms / 1000.0).ceil + 5) : 60
|
|
525
529
|
error_body = +""
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
530
|
+
attempt = 0
|
|
531
|
+
begin
|
|
532
|
+
attempt += 1
|
|
533
|
+
with_transport_norm("POST", "sessions/#{escape(name)}/exec") do
|
|
534
|
+
response = connection.post(route_path("sessions/#{escape(name)}/exec")) do |req|
|
|
535
|
+
apply_token(req, token)
|
|
536
|
+
req.headers["Content-Type"] = "application/json"
|
|
537
|
+
req.headers["Accept"] = "text/event-stream"
|
|
538
|
+
req.body = body.to_json
|
|
539
|
+
req.options.on_data = proc do |chunk, _received, env|
|
|
540
|
+
if env.nil?
|
|
541
|
+
# faraday-net_http before 3.0 passes no env, so the status is
|
|
542
|
+
# known only at the end: parse the chunk and keep it in case
|
|
543
|
+
# the answer is an error.
|
|
544
|
+
parser.parse(chunk)
|
|
545
|
+
StreamedRead.keep_error_body(error_body, chunk)
|
|
546
|
+
elsif env.status.to_i.between?(200, 299)
|
|
547
|
+
parser.parse(chunk)
|
|
548
|
+
else
|
|
549
|
+
StreamedRead.keep_error_body(error_body, chunk)
|
|
550
|
+
end
|
|
543
551
|
end
|
|
552
|
+
req.options.timeout = http_timeout
|
|
553
|
+
end
|
|
554
|
+
# Non-2xx (e.g. 409 terminal_lost) is a problem+json body, not a
|
|
555
|
+
# stream; raise it so callers get ConflictError (→ recreate_terminal!)
|
|
556
|
+
# instead of a silent empty ExecResult.
|
|
557
|
+
unless response.success?
|
|
558
|
+
response.env.body = error_body if response.body.to_s.empty?
|
|
559
|
+
ensure_success!(response, token: token)
|
|
544
560
|
end
|
|
545
|
-
req.options.timeout = http_timeout
|
|
546
|
-
end
|
|
547
|
-
# Non-2xx (e.g. 409 terminal_lost) is a problem+json body, not a
|
|
548
|
-
# stream; raise it so callers get ConflictError (→ recreate_terminal!)
|
|
549
|
-
# instead of a silent empty ExecResult.
|
|
550
|
-
unless response.success?
|
|
551
|
-
response.env.body = error_body if response.body.to_s.empty?
|
|
552
|
-
ensure_success!(response, token: token)
|
|
553
561
|
end
|
|
562
|
+
rescue PineSandbox::ConnectionError => e
|
|
563
|
+
raise unless not_sent?(e) && attempt < RetryPolicy::TRANSIENT_ATTEMPTS
|
|
564
|
+
|
|
565
|
+
@clock.sleep(RetryPolicy.transient_backoff(attempt, @clock))
|
|
566
|
+
retry
|
|
554
567
|
end
|
|
555
568
|
parser.finish
|
|
556
569
|
# execd's `execution_complete` frame does NOT carry exit_code on
|
|
@@ -585,14 +598,16 @@ module PineSandbox
|
|
|
585
598
|
|
|
586
599
|
# idempotency_key names this submission: a run with the same key returns
|
|
587
600
|
# the turn that key admitted instead of starting another.
|
|
588
|
-
|
|
601
|
+
# `timeout` (seconds), when given, bounds each send in place of the request timeout.
|
|
602
|
+
def agent_run(token:, name:, goal:, context: nil, skills: nil, constraints: nil, secrets: nil, idempotency_key: nil,
|
|
603
|
+
timeout: nil, reached: nil)
|
|
589
604
|
body = { goal: goal }
|
|
590
605
|
body[:context] = context unless context.nil?
|
|
591
606
|
body[:skills] = skills unless skills.nil?
|
|
592
607
|
body[:constraints] = constraints unless constraints.nil?
|
|
593
608
|
body[:secrets] = secrets unless secrets.nil?
|
|
594
609
|
post("v2/sessions/#{escape(name)}/agent/run", token: token, json: body,
|
|
595
|
-
headers: { "Idempotency-Key" => idempotency_key }).body
|
|
610
|
+
headers: { "Idempotency-Key" => idempotency_key }, timeout: timeout, reached: reached).body
|
|
596
611
|
end
|
|
597
612
|
|
|
598
613
|
def agent_steer(token:, name:, turn_id:, text:, secrets: nil)
|
|
@@ -601,14 +616,14 @@ module PineSandbox
|
|
|
601
616
|
post("v2/sessions/#{escape(name)}/agent/steer", token: token, json: body).body
|
|
602
617
|
end
|
|
603
618
|
|
|
604
|
-
def agent_answer(token:, name:, turn_id:, answer:, secrets: nil)
|
|
619
|
+
def agent_answer(token:, name:, turn_id:, answer:, secrets: nil, timeout: nil)
|
|
605
620
|
body = { turn_id: turn_id, answer: answer }
|
|
606
621
|
body[:secrets] = secrets unless secrets.nil?
|
|
607
|
-
post("v2/sessions/#{escape(name)}/agent/answer", token: token, json: body).body
|
|
622
|
+
post("v2/sessions/#{escape(name)}/agent/answer", token: token, json: body, timeout: timeout).body
|
|
608
623
|
end
|
|
609
624
|
|
|
610
|
-
def agent_cancel(token:, name:, turn_id:)
|
|
611
|
-
post("v2/sessions/#{escape(name)}/agent/cancel", token: token, json: { turn_id: turn_id }).body
|
|
625
|
+
def agent_cancel(token:, name:, turn_id:, timeout: nil)
|
|
626
|
+
post("v2/sessions/#{escape(name)}/agent/cancel", token: token, json: { turn_id: turn_id }, timeout: timeout).body
|
|
612
627
|
end
|
|
613
628
|
|
|
614
629
|
def agent_reset(token:, name:, expected_task_id:)
|
|
@@ -625,7 +640,7 @@ module PineSandbox
|
|
|
625
640
|
# wait_seconds while the turn runs, so the read timeout allows for it.
|
|
626
641
|
def agent_turn(token:, name:, turn_id:, wait_seconds: 0)
|
|
627
642
|
path = "v2/sessions/#{escape(name)}/agent/turns/#{escape(turn_id)}?wait_seconds=#{Integer(wait_seconds)}"
|
|
628
|
-
request(:get, path, token: token, timeout:
|
|
643
|
+
request(:get, path, token: token, timeout: @timeouts.request + wait_seconds).body
|
|
629
644
|
end
|
|
630
645
|
|
|
631
646
|
# Public history: the retained turns and cursor-addressed activity pages.
|
|
@@ -885,11 +900,22 @@ module PineSandbox
|
|
|
885
900
|
|
|
886
901
|
# Opens one event-stream GET and yields each SSE frame as it arrives.
|
|
887
902
|
# A transport fault raises the raw Faraday error so the caller decides
|
|
888
|
-
# whether to normalize it or reconnect; a non-2xx raises its typed error
|
|
889
|
-
#
|
|
890
|
-
# extensions). Returns the response.
|
|
903
|
+
# whether to normalize it or reconnect; a non-2xx raises its typed error.
|
|
904
|
+
# Returns the response.
|
|
891
905
|
def open_sse(path, token:, last_event_id:)
|
|
892
906
|
parser = ::PineSandbox::SseFrameParser.new
|
|
907
|
+
response = open_event_stream(path, token: token, last_event_id: last_event_id) do |chunk|
|
|
908
|
+
parser.feed(chunk) { |frame| yield frame }
|
|
909
|
+
end
|
|
910
|
+
parser.finish
|
|
911
|
+
response
|
|
912
|
+
end
|
|
913
|
+
|
|
914
|
+
# Opens one event-stream GET and yields its bytes as they arrive. A
|
|
915
|
+
# transport fault raises the raw Faraday error; a non-2xx raises its
|
|
916
|
+
# typed error (keeping a bounded prefix of the body, so a problem keeps
|
|
917
|
+
# its type and extensions). Returns the response.
|
|
918
|
+
def open_event_stream(path, token:, last_event_id:)
|
|
893
919
|
error_body = +""
|
|
894
920
|
response = streaming_connection.get(route_path(path)) do |req|
|
|
895
921
|
apply_token(req, token)
|
|
@@ -898,18 +924,17 @@ module PineSandbox
|
|
|
898
924
|
req.options.on_data = proc do |chunk, _bytes, env|
|
|
899
925
|
if env.nil?
|
|
900
926
|
# faraday-net_http before 3.0 passes no env, so the status is
|
|
901
|
-
# known only at the end:
|
|
902
|
-
# answer is an error.
|
|
903
|
-
|
|
927
|
+
# known only at the end: pass the chunk on and keep it in case
|
|
928
|
+
# the answer is an error.
|
|
929
|
+
yield chunk
|
|
904
930
|
StreamedRead.keep_error_body(error_body, chunk)
|
|
905
931
|
elsif env.status.to_i.between?(200, 299)
|
|
906
|
-
|
|
932
|
+
yield chunk
|
|
907
933
|
else
|
|
908
934
|
StreamedRead.keep_error_body(error_body, chunk)
|
|
909
935
|
end
|
|
910
936
|
end
|
|
911
937
|
end
|
|
912
|
-
parser.finish
|
|
913
938
|
unless response.success?
|
|
914
939
|
response.env.body = error_body if response.body.to_s.empty?
|
|
915
940
|
ensure_success!(response, token: token)
|
|
@@ -917,6 +942,25 @@ module PineSandbox
|
|
|
917
942
|
response
|
|
918
943
|
end
|
|
919
944
|
|
|
945
|
+
# Passes one connection of an event stream to the block byte for byte,
|
|
946
|
+
# keepalives and ids included, for a server that relays it to its own
|
|
947
|
+
# client. An error answer raises the typed error every other read
|
|
948
|
+
# raises, and a transport fault raises its normalized error. Only a 2xx
|
|
949
|
+
# body reaches the block, except on faraday-net_http before 3.0: it
|
|
950
|
+
# learns the status after the body, and a live stream can't be held
|
|
951
|
+
# back until then, so there an error answer's body reaches the block
|
|
952
|
+
# before its error is raised.
|
|
953
|
+
def stream_event_bytes(path, token:, last_event_id: nil, &block)
|
|
954
|
+
with_transport_norm("GET", path) do
|
|
955
|
+
open_event_stream(path, token: token, last_event_id: last_event_id) do |chunk|
|
|
956
|
+
StreamedRead.pass(block, chunk)
|
|
957
|
+
end
|
|
958
|
+
end
|
|
959
|
+
nil
|
|
960
|
+
rescue BlockError => e
|
|
961
|
+
raise e.error
|
|
962
|
+
end
|
|
963
|
+
|
|
920
964
|
BlockError = StreamedRead::BlockError
|
|
921
965
|
private_constant :BlockError
|
|
922
966
|
|
|
@@ -1012,8 +1056,9 @@ module PineSandbox
|
|
|
1012
1056
|
request(:get, path, token: token, accept: accept, headers: headers)
|
|
1013
1057
|
end
|
|
1014
1058
|
|
|
1015
|
-
def post(path, token:, json: nil, body: nil, content_type: nil, headers: nil)
|
|
1016
|
-
request(:post, path, token: token, json: json, body: body, content_type: content_type, headers: headers
|
|
1059
|
+
def post(path, token:, json: nil, body: nil, content_type: nil, headers: nil, timeout: nil, reached: nil)
|
|
1060
|
+
request(:post, path, token: token, json: json, body: body, content_type: content_type, headers: headers,
|
|
1061
|
+
timeout: timeout, reached: reached)
|
|
1017
1062
|
end
|
|
1018
1063
|
|
|
1019
1064
|
def patch(path, token:, json: nil, headers: nil)
|
|
@@ -1033,9 +1078,11 @@ module PineSandbox
|
|
|
1033
1078
|
# Sends one request. A transport fault (no response) is retried with
|
|
1034
1079
|
# RetryPolicy's transient backoff only when the route is a replay-safe
|
|
1035
1080
|
# public operation (one whose safety rests on an Idempotency-Key only
|
|
1036
|
-
# when the request carries one)
|
|
1037
|
-
# resent here.
|
|
1038
|
-
|
|
1081
|
+
# when the request carries one), or when the connection could not be
|
|
1082
|
+
# opened; a response of any status is never resent here. reached, when
|
|
1083
|
+
# given, is called for each send that may have reached the Computer.
|
|
1084
|
+
def request(method, path, token:, json: nil, body: nil, content_type: nil, accept: "application/json", headers: nil, timeout: nil,
|
|
1085
|
+
reached: nil)
|
|
1039
1086
|
verb = method.to_s.upcase
|
|
1040
1087
|
operation = Operations.match(:computer, verb, route_path(path.to_s.split(/[?#]/, 2).first))
|
|
1041
1088
|
idempotency_key = headers&.find { |name, _| name.to_s.casecmp?("Idempotency-Key") }&.last
|
|
@@ -1058,11 +1105,17 @@ module PineSandbox
|
|
|
1058
1105
|
headers&.each { |k, v| req.headers[k] = v if v }
|
|
1059
1106
|
end
|
|
1060
1107
|
end
|
|
1061
|
-
|
|
1062
|
-
|
|
1108
|
+
reached&.call
|
|
1109
|
+
rescue PineSandbox::TimeoutError, PineSandbox::ConnectionError => e
|
|
1110
|
+
reached&.call unless not_sent?(e)
|
|
1111
|
+
raise unless attempt < attempts || (not_sent?(e) && attempt < RetryPolicy::TRANSIENT_ATTEMPTS)
|
|
1063
1112
|
|
|
1064
1113
|
@clock.sleep(RetryPolicy.transient_backoff(attempt, @clock))
|
|
1065
1114
|
retry
|
|
1115
|
+
rescue PineSandbox::Error
|
|
1116
|
+
# It ends the call; counted so an earlier lost response still leaves a run unconfirmed.
|
|
1117
|
+
reached&.call
|
|
1118
|
+
raise
|
|
1066
1119
|
end
|
|
1067
1120
|
ensure_success!(response, token: token)
|
|
1068
1121
|
ParsedResponse.new(response, accept)
|
|
@@ -1089,10 +1142,14 @@ module PineSandbox
|
|
|
1089
1142
|
if error.is_a?(Faraday::TimeoutError)
|
|
1090
1143
|
PineSandbox::TimeoutError.new("Computer request timed out: #{error.message}#{suffix}")
|
|
1091
1144
|
else
|
|
1092
|
-
PineSandbox::ConnectionError.new("Computer connection failed: #{error.message}#{suffix}")
|
|
1145
|
+
PineSandbox::ConnectionError.new("Computer connection failed: #{error.message}#{suffix}").tap do |fault|
|
|
1146
|
+
fault.not_sent = ConnectAwareNetHttp.not_sent?(error)
|
|
1147
|
+
end
|
|
1093
1148
|
end
|
|
1094
1149
|
end
|
|
1095
1150
|
|
|
1151
|
+
def not_sent?(error) = error.is_a?(PineSandbox::ConnectionError) && error.not_sent?
|
|
1152
|
+
|
|
1096
1153
|
# "<METHOD> /<path>" with any query string / fragment stripped — the transport-fault
|
|
1097
1154
|
# counterpart to op_for (which reads env.url.path). `path` is the SDK route, sans the
|
|
1098
1155
|
# leading slash route_path adds.
|
|
@@ -1210,8 +1267,10 @@ module PineSandbox
|
|
|
1210
1267
|
|
|
1211
1268
|
# v0 + non-problem+json error: emit the older shape, now carrying the resource spine
|
|
1212
1269
|
# in problem_extensions so ApiError#build_message renders it resource-first.
|
|
1270
|
+
# A plain answer the Computer names by a machine code keeps that name.
|
|
1213
1271
|
message = parse_legacy_error_message(response.body)
|
|
1214
|
-
klass =
|
|
1272
|
+
klass = PineSandbox.code_class_for(response.status, legacy_error_code(response.body))
|
|
1273
|
+
klass ||=
|
|
1215
1274
|
case response.status
|
|
1216
1275
|
when 401, 403 then PineSandbox::UnauthorizedError
|
|
1217
1276
|
when 404 then PineSandbox::NotFoundError
|
|
@@ -1270,6 +1329,14 @@ module PineSandbox
|
|
|
1270
1329
|
rid unless rid.to_s.empty?
|
|
1271
1330
|
end
|
|
1272
1331
|
|
|
1332
|
+
# The machine code of a plain JSON error body (`{"error": "..."}`), or nil.
|
|
1333
|
+
def legacy_error_code(body)
|
|
1334
|
+
parsed = JSON.parse(body)
|
|
1335
|
+
parsed["error"] if parsed.is_a?(Hash)
|
|
1336
|
+
rescue JSON::ParserError, TypeError
|
|
1337
|
+
nil
|
|
1338
|
+
end
|
|
1339
|
+
|
|
1273
1340
|
def parse_legacy_error_message(body)
|
|
1274
1341
|
JSON.parse(body)["error"] || body.to_s
|
|
1275
1342
|
rescue JSON::ParserError, TypeError
|
|
@@ -1284,9 +1351,9 @@ module PineSandbox
|
|
|
1284
1351
|
def connection
|
|
1285
1352
|
@connection ||= @zone.faraday(@host) do |conn|
|
|
1286
1353
|
conn.headers["User-Agent"] = PineSandbox::USER_AGENT
|
|
1287
|
-
conn.options.open_timeout =
|
|
1288
|
-
conn.options.timeout =
|
|
1289
|
-
conn.adapter
|
|
1354
|
+
conn.options.open_timeout = @timeouts.connect
|
|
1355
|
+
conn.options.timeout = @timeouts.request
|
|
1356
|
+
conn.adapter ConnectAwareNetHttp
|
|
1290
1357
|
end
|
|
1291
1358
|
end
|
|
1292
1359
|
|
|
@@ -1302,9 +1369,9 @@ module PineSandbox
|
|
|
1302
1369
|
def streaming_connection
|
|
1303
1370
|
@streaming_connection ||= @zone.faraday(@host) do |conn|
|
|
1304
1371
|
conn.headers["User-Agent"] = PineSandbox::USER_AGENT
|
|
1305
|
-
conn.options.open_timeout =
|
|
1372
|
+
conn.options.open_timeout = @timeouts.connect
|
|
1306
1373
|
# DELIBERATELY no conn.options.timeout — adapter block is authoritative.
|
|
1307
|
-
conn.adapter
|
|
1374
|
+
conn.adapter ConnectAwareNetHttp do |http|
|
|
1308
1375
|
http.read_timeout = STREAM_IDLE_TIMEOUT
|
|
1309
1376
|
end
|
|
1310
1377
|
end
|