pinesandbox 0.3.20 → 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.
@@ -14,14 +14,14 @@ require_relative "session"
14
14
  module PineSandbox
15
15
  # A persistent Computer — the one object in this SDK. It is either
16
16
  # powered-off (just an `id` + the per-Computer `key` you hold in your DB)
17
- # or powered-on (started and attached). `attach` starts it, runs the
18
- # bind/restore handshake so the Computer resumes its prior state, and
19
- # returns `self`; you then drive it through `create_session`. `stop` saves
20
- # supported state and shuts the Computer down, and you can `attach` again
21
- # later to start it with state restored.
17
+ # or powered-on (started and attached). Client#start_computer starts it,
18
+ # runs the bind/restore handshake so the Computer resumes its prior state,
19
+ # and returns it; you then drive it through `create_session`. `stop` shuts
20
+ # the Computer down after Pine tries a final save, and Client#start_computer
21
+ # starts it again later from its saved state (Client#recover_computer after
22
+ # a failure).
22
23
  #
23
- # computer = PineSandbox::Computer.new("0190…", key: secret_32_bytes)
24
- # computer.attach(connection)
24
+ # computer = client.start_computer(credentials)
25
25
  # session = computer.create_session
26
26
  # session.create_tab(url: "https://example.com")
27
27
  # computer.stop
@@ -36,6 +36,9 @@ module PineSandbox
36
36
  class Computer
37
37
  CURRENT_KEY_VERSION = 1
38
38
  DEFAULT_MAX_BIND_ATTEMPTS = 3
39
+ # How long, in seconds, a Computer keeps running without use when a start
40
+ # names no timeout:.
41
+ DEFAULT_IDLE_TIMEOUT = 1800
39
42
  # How long to wait for the Computer to start; independent of its idle timeout.
40
43
  DEFAULT_READY_TIMEOUT = 300
41
44
  # Wall-clock budget for a just-started Computer to become bindable. Spans
@@ -73,7 +76,7 @@ module PineSandbox
73
76
  # route by token class (`/exec` is ps_-only; ps_ is bound to its own
74
77
  # session), so a raw call here can only do what the caller's own token
75
78
  # already permits.
76
- attr_reader :coordinator
79
+ def coordinator = coordinator!
77
80
 
78
81
  # A fresh Computer identity: a UUIDv7 `id` + a 32-byte state `key` — the SAME
79
82
  # pair create_computer generates internally, exposed as the SDK's built-in
@@ -193,65 +196,81 @@ module PineSandbox
193
196
  # just-started Computer down and leaves it powered-off before a typed error.
194
197
  #
195
198
  # @param config [PineSandbox::Connection]
196
- # timeout is how long the Computer keeps running without use. ready_timeout
197
- # bounds how long it takes to start; bind_ready_timeout separately bounds the
198
- # bind/restore handshake.
199
+ # timeout is the idle timeout: how long, in seconds, the Computer keeps
200
+ # running after its last activity (default 1800, at least 60, at most the
201
+ # project's allowance). Activity is anything done on the Computer: a command,
202
+ # a browser action, a file write, a message to the agent, an agent turn while
203
+ # it runs, a person in control. Each one restarts the countdown. Only looking
204
+ # doesn't: reading status or results, and listening to events. After a whole
205
+ # timeout with no activity the Computer stops; call #stop yourself to wait
206
+ # for its save. #set_idle_timeout changes the timeout while the Computer runs.
207
+ # ready_timeout bounds how long it takes to start; bind_ready_timeout
208
+ # separately bounds the bind/restore handshake.
199
209
  # @param pod_env [nil, Hash] Deprecated; only nil or an empty hash is accepted.
200
- def attach(config, timeout: 300, ready_timeout: DEFAULT_READY_TIMEOUT, pod_env: nil, metadata: nil,
201
- location: nil,
202
- max_bind_attempts: DEFAULT_MAX_BIND_ATTEMPTS,
203
- bind_ready_timeout: DEFAULT_BIND_READY_TIMEOUT)
204
- unless config.respond_to?(:attach_provider) && config.respond_to?(:control_plane) && config.respond_to?(:zone)
205
- raise ArgumentError, "config must be a PineSandbox::Connection (got #{config.class})"
206
- end
207
- unless max_bind_attempts.is_a?(Integer) && max_bind_attempts.positive?
208
- raise ArgumentError, "max_bind_attempts must be a positive integer"
209
- end
210
- unless pod_env.nil? || pod_env == {}
211
- raise ArgumentError, "pod_env is unsupported for Computer attach; omit it or pass an empty hash"
212
- end
213
- unless (ready_timeout.is_a?(Integer) || ready_timeout.is_a?(Float)) && ready_timeout.finite? && ready_timeout.positive?
214
- raise ArgumentError, "ready_timeout must be a positive finite number of seconds"
215
- end
210
+ # @deprecated Use Client#start_computer or Client#recover_computer, which check the current runtime first.
211
+ def attach(config, **options)
212
+ PineSandbox.deprecated_name("Computer#attach", "Client#start_computer")
213
+ attach_runtime(config, **options)
214
+ end
215
+
216
+ # @api private — #attach without its deprecation warning, for Client.
217
+ # budget_start: when ready_timeout began (nil: now).
218
+ def attach_runtime(config, timeout: DEFAULT_IDLE_TIMEOUT, ready_timeout: DEFAULT_READY_TIMEOUT, pod_env: nil, metadata: nil,
219
+ location: nil,
220
+ max_bind_attempts: DEFAULT_MAX_BIND_ATTEMPTS,
221
+ bind_ready_timeout: DEFAULT_BIND_READY_TIMEOUT, budget_start: nil)
222
+ requested_location = check_attach_options!(config, ready_timeout: ready_timeout, pod_env: pod_env,
223
+ location: location, max_bind_attempts: max_bind_attempts)
216
224
 
217
225
  # Refuse to re-attach a live Computer: silently tearing down the prior pod
218
226
  # here would force-kill it (ungraceful) and lose state since the last
219
227
  # checkpoint. Make the teardown an explicit caller choice — #stop (graceful,
220
228
  # persist) or #kill (discard) — then attach again.
221
229
  raise BindError.new("Computer already attached — call #stop (graceful) or #kill first") if @sandbox
222
- # A persistent attach requires the capture keypair (it seals every capture
223
- # to it); an ephemeral Computer persists nothing, so it binds without one.
224
- if @capture_generation.zero? && !@ephemeral
225
- raise ArgumentError, "v3 attach requires a capture_keypair (persist both halves)"
226
- end
227
- # Preserve omission as omission. @location is only the last Portal
228
- # receipt, not authority to overwrite a newer country another client may
229
- # have committed after this instance stopped.
230
- requested_location = normalize_location(location) if location
231
230
  @last_authorized_sandbox_id = nil
232
231
  @connection = config
233
232
  @clock = config.respond_to?(:clock) ? config.clock : PineSandbox::SYSTEM_CLOCK
234
233
 
235
234
  # Provision via the project-scoped control plane (api.<zone>, project JWS).
236
235
  create_id = SecureRandom.uuid
237
- ready_deadline = monotonic_now + ready_timeout
238
- info = config.control_plane.create_computer(
239
- body: build_computer_create_body(timeout: timeout, metadata: metadata).merge(create_id: create_id),
240
- request_timeout: ready_timeout
241
- )
242
- @sandbox = SandboxHandle.new(control_plane: config.control_plane, sandbox_id: info.id, status: info.status)
236
+ budget_start ||= monotonic_now
237
+ ready_deadline = budget_start + ready_timeout
238
+ body = build_computer_create_body(timeout: timeout, metadata: metadata).merge(create_id: create_id)
239
+ sent = false
240
+ info = begin
241
+ config.control_plane.create_computer(body: body, request_timeout: ready_deadline - monotonic_now,
242
+ reached: -> { sent = true })
243
+ rescue PineSandbox::TimeoutError => e
244
+ raise unless sent && monotonic_now >= ready_deadline
245
+
246
+ # The budget cut the create off, so a runtime may exist that nothing would delete. Sent
247
+ # again with its create_id, the create names it; the spent budget below then deletes it.
248
+ begin
249
+ config.control_plane.create_computer(body: body, request_timeout: connection_timeouts(config).request)
250
+ rescue StandardError
251
+ raise e
252
+ end
253
+ end
254
+ @sandbox = SandboxHandle.new(control_plane: config.control_plane, sandbox_id: info.id,
255
+ status: info.status, reason: info.reason)
243
256
  # Wait for the pod to report Running (a CUA pod's readiness; the bind handshake
244
257
  # below is the functional coord-readiness check). A pod that fails or never
245
258
  # becomes Ready is destroyed before the typed error leaves #attach.
246
259
  begin
247
- @sandbox.wait_until_running(timeout: [ready_deadline - monotonic_now, 0].max)
260
+ # The create took the budget: a runtime that already runs isn't bound either.
261
+ if monotonic_now >= ready_deadline
262
+ raise ReadyTimeoutError.new(sandbox_id: info.id, last_state: info.status, last_reason: info.reason,
263
+ waited: monotonic_now - budget_start, target: :running, new_runtime: true)
264
+ end
265
+ @sandbox.wait_until_running(timeout: [ready_deadline - monotonic_now, 0].max, started: budget_start)
248
266
  rescue StandardError
249
267
  reset_bound_state
250
268
  raise
251
269
  end
252
270
  # Drive the Computer at its gateway host `https://<sandbox_id>.computer.<zone>`
253
271
  # — port-less, header-less, role-by-path; coord gates every route on the bearer.
254
- @coordinator = Adapters::CoordinatorAdapter.new(sandbox_id: info.id, zone: config.zone, clock: @clock)
272
+ @coordinator = Adapters::CoordinatorAdapter.new(sandbox_id: info.id, zone: config.zone, clock: @clock,
273
+ timeouts: connection_timeouts(config))
255
274
 
256
275
  # Two retry budgets converge on the bind handshake:
257
276
  # - readiness (DEADLINE-bounded): the Computer sandbox was just started, so the
@@ -310,11 +329,44 @@ module PineSandbox
310
329
  self
311
330
  end
312
331
 
313
- # attach + auto-stop. Yields self; stops the Computer (saving supported
314
- # state) when the block returns or raises.
332
+ # @api private — Start checks it before its first read, which the budget bounds.
333
+ def self.check_ready_timeout!(ready_timeout)
334
+ return if (ready_timeout.is_a?(Integer) || ready_timeout.is_a?(Float)) && ready_timeout.finite? && ready_timeout.positive?
335
+
336
+ raise ArgumentError, "ready_timeout must be a positive finite number of seconds"
337
+ end
338
+
339
+ # @api private — #attach_runtime's checks, which Start runs before its gate. Takes
340
+ # every #attach_runtime keyword, so an unknown one fails here. Returns the normalized location.
341
+ def check_attach_options!(config, ready_timeout: DEFAULT_READY_TIMEOUT, pod_env: nil, location: nil,
342
+ max_bind_attempts: DEFAULT_MAX_BIND_ATTEMPTS, timeout: nil, metadata: nil,
343
+ bind_ready_timeout: nil)
344
+ unless config.respond_to?(:attach_provider) && config.respond_to?(:control_plane) && config.respond_to?(:zone)
345
+ raise ArgumentError, "config must be a PineSandbox::Connection (got #{config.class})"
346
+ end
347
+ unless max_bind_attempts.is_a?(Integer) && max_bind_attempts.positive?
348
+ raise ArgumentError, "max_bind_attempts must be a positive integer"
349
+ end
350
+ unless pod_env.nil? || pod_env == {}
351
+ raise ArgumentError, "pod_env is unsupported for Computer attach; omit it or pass an empty hash"
352
+ end
353
+ Computer.check_ready_timeout!(ready_timeout)
354
+ # A persistent attach requires the capture keypair (it seals every capture
355
+ # to it); an ephemeral Computer persists nothing, so it binds without one.
356
+ if @capture_generation.zero? && !@ephemeral
357
+ raise ArgumentError, "v3 attach requires a capture_keypair (persist both halves)"
358
+ end
359
+ # Preserve omission as omission. @location is only the last Portal
360
+ # receipt, not authority to overwrite a newer country another client may
361
+ # have committed after this instance stopped.
362
+ normalize_location(location) if location
363
+ end
364
+
365
+ # attach + auto-stop. Yields self; stops the Computer (Pine tries a final
366
+ # save first) when the block returns or raises.
315
367
  def with_attached(config, **opts)
316
368
  PineSandbox.deprecated_name("Computer#with_attached", "Client#with_computer")
317
- attach(config, **opts)
369
+ attach_runtime(config, **opts)
318
370
  yield self
319
371
  ensure
320
372
  # Graceful by default: persist state on the way out (no-op if attach
@@ -343,7 +395,8 @@ module PineSandbox
343
395
  @connection = config
344
396
  @clock = config.respond_to?(:clock) ? config.clock : PineSandbox::SYSTEM_CLOCK
345
397
  @coordinator = Adapters::CoordinatorAdapter.new(sandbox_id: sandbox_id, zone: config.zone,
346
- discovery_token: computer_token, clock: @clock)
398
+ discovery_token: computer_token, clock: @clock,
399
+ timeouts: connection_timeouts(config))
347
400
  @sandbox = SandboxHandle.new(control_plane: config.control_plane, sandbox_id: sandbox_id, status: status)
348
401
  @computer_token = computer_token
349
402
  @binding_revision = binding_revision
@@ -353,7 +406,8 @@ module PineSandbox
353
406
  # The Computer-tier token (`ct_*`) delivered in the bind response. Raises
354
407
  # if called before #attach (or after #stop).
355
408
  def computer_token
356
- @computer_token || raise(BindError.new("Computer is not attached — call #attach first"))
409
+ require_binding!
410
+ @computer_token
357
411
  end
358
412
 
359
413
  # INFORMATIONAL ONLY: the `expires_at` returned with the ct_ in the bind
@@ -584,28 +638,33 @@ module PineSandbox
584
638
  # Preserve the current sessions, capabilities and live process memory.
585
639
  # These bounded calls wait for observed completion; neither rebinds.
586
640
  def pause(timeout: 360)
587
- raise ArgumentError, "Computer has no binding" unless @sandbox
588
-
641
+ require_binding!
589
642
  @sandbox.pause(timeout: timeout)
590
643
  self
591
644
  end
592
645
 
593
646
  def resume(timeout: 360)
594
- raise ArgumentError, "Computer has no binding" unless @sandbox
595
-
647
+ require_binding!
596
648
  @sandbox.resume(timeout: timeout)
597
649
  self
598
650
  end
599
651
 
600
- # Stop is owned by the server after acceptance. A timeout only ends this
601
- # wait; another backend using the saved handle can observe or retry it.
602
- # true confirms the Computer has shut down; if it was already gone, its
603
- # final save is unknown.
652
+ # Stops the runtime this handle is bound to (its sandbox_id); Pine tries a
653
+ # final save first. Returns true when that runtime is no longer running, or
654
+ # when the handle has no binding. true does not confirm that the final save
655
+ # succeeded: the save result cannot be read. After true the handle has no
656
+ # binding, and calls that need one raise BindError.
657
+ #
658
+ # Returns false when the runtime did not stop within wait_timeout (seconds,
659
+ # default 390); by then the Stop was submitted or the runtime was already
660
+ # shutting down. A wait_timeout of 0 skips only the wait; the Stop is still
661
+ # submitted. After false, or an error (the Stop may or may not have been
662
+ # submitted), call stop again on this handle.
604
663
  def stop(wait_timeout: 390)
605
664
  return true unless @sandbox
606
665
 
607
666
  gone = @sandbox.stop(wait_timeout: wait_timeout)
608
- clear_bound_state if gone
667
+ clear_bound_state("Stop") if gone
609
668
  gone
610
669
  end
611
670
 
@@ -615,7 +674,7 @@ module PineSandbox
615
674
  # for #kill only to recover.)
616
675
  #
617
676
  # NOTE: there is intentionally no #destroy alias. The lifecycle verbs are
618
- # distinct by intent: #stop saves supported state before shutdown;
677
+ # distinct by intent: #stop tries a final save before shutdown;
619
678
  # #kill is ungraceful force-recovery. The "done forever" verb —
620
679
  # permanent delete, which ends the identity and purges saved state — is
621
680
  # Client#delete_computer (it kills a still-attached Computer first).
@@ -623,7 +682,7 @@ module PineSandbox
623
682
  return true unless @sandbox
624
683
 
625
684
  deleted = @sandbox.kill
626
- clear_bound_state if deleted
685
+ clear_bound_state("Kill") if deleted
627
686
  deleted
628
687
  end
629
688
 
@@ -641,6 +700,7 @@ module PineSandbox
641
700
 
642
701
  kill
643
702
  provider.delete_computer(id)
703
+ clear_bound_state("Delete")
644
704
  true
645
705
  end
646
706
 
@@ -652,8 +712,7 @@ module PineSandbox
652
712
  # absence and transport/auth failures remain distinct errors. This never
653
713
  # clears a binding, resumes memory or starts the Computer again.
654
714
  def status
655
- raise BindError, "Computer has no binding" unless @sandbox
656
-
715
+ require_binding!
657
716
  @sandbox.status
658
717
  end
659
718
 
@@ -661,8 +720,7 @@ module PineSandbox
661
720
  # including while paused. If it has stopped, no Portal lookup, rebind or
662
721
  # restart follows.
663
722
  def sandbox_details
664
- raise BindError, "Computer has no binding" unless @sandbox
665
-
723
+ require_binding!
666
724
  info = @sandbox.sandbox_details
667
725
  SandboxDetails.from_info(info)
668
726
  end
@@ -670,7 +728,7 @@ module PineSandbox
670
728
  # An unchanged value is not a heartbeat. On conflict or a lost reply,
671
729
  # observe sandbox_details before deciding whether another edit is needed.
672
730
  def set_idle_timeout(seconds:)
673
- raise BindError, "Computer has no binding" unless @sandbox
731
+ require_binding!
674
732
  raise ArgumentError, "idle timeout must be an integer of at least 60 seconds" unless seconds.is_a?(Integer) && seconds >= 60
675
733
 
676
734
  SandboxDetails.from_info(@sandbox.set_idle_timeout(seconds: seconds))
@@ -679,8 +737,7 @@ module PineSandbox
679
737
  # Save after Create/Start, alongside the durable credentials. Never log JSON:
680
738
  # it contains the live Computer token. Stop clears this object's binding.
681
739
  def binding
682
- raise BindError, "Computer has no binding" unless @sandbox && @computer_token
683
-
740
+ require_binding!
684
741
  Binding.new(computer_id: id.dup, sandbox_id: @sandbox.id.dup,
685
742
  computer_token: @computer_token.dup, binding_revision: @binding_revision).validate!
686
743
  end
@@ -710,6 +767,10 @@ module PineSandbox
710
767
 
711
768
  private
712
769
 
770
+ def connection_timeouts(config)
771
+ config.respond_to?(:timeouts) ? config.timeouts : Timeouts::DEFAULT
772
+ end
773
+
713
774
  # A Computer has no default session: its session helpers need the name.
714
775
  def require_session_name!(name)
715
776
  raise ArgumentError, "session name is required" if name.to_s.empty?
@@ -728,7 +789,15 @@ module PineSandbox
728
789
  # The bound coordinator, or a clear error if powered-off. Keeps every
729
790
  # drive method from NoMethodError-ing on a nil coordinator.
730
791
  def coordinator!
731
- @coordinator || raise(BindError.new("Computer is not attached — call #attach first"))
792
+ require_binding!
793
+ @coordinator
794
+ end
795
+
796
+ def require_binding!
797
+ return if @sandbox && @computer_token
798
+
799
+ reason = @unbound_by ? "#{@unbound_by} was called on this handle" : "it was never attached"
800
+ raise BindError, "Computer #{id}: this handle has no binding (#{reason})"
732
801
  end
733
802
 
734
803
  # Ungraceful tear-down: best-effort kill (no wait) + drop the local binding.
@@ -746,7 +815,8 @@ module PineSandbox
746
815
 
747
816
  # Drop the local binding WITHOUT touching the pod — used after a graceful
748
817
  # #stop has already terminated it (so we don't double-DELETE).
749
- def clear_bound_state
818
+ def clear_bound_state(by = nil)
819
+ @unbound_by = by if by
750
820
  @sandbox = nil
751
821
  @coordinator = nil
752
822
  @computer_token = nil
@@ -1,5 +1,6 @@
1
1
  require_relative "zone"
2
2
  require_relative "clock"
3
+ require_relative "timeouts"
3
4
 
4
5
  module PineSandbox
5
6
  # Internal value object bundling everything Computer#attach needs against the
@@ -9,10 +10,12 @@ module PineSandbox
9
10
  # (project-JWS create/inspect/destroy at api.<zone>). Built by
10
11
  # PineSandbox::Client — not a public constructor.
11
12
  class Connection
12
- attr_reader :zone, :control_plane, :attach_provider, :clock
13
+ attr_reader :zone, :control_plane, :attach_provider, :clock, :timeouts
13
14
 
14
- # `clock` paces every wait the Computer and its data-plane client make.
15
- def initialize(zone:, control_plane:, attach_provider:, clock: PineSandbox::SYSTEM_CLOCK)
15
+ # `clock` paces every wait the Computer and its data-plane client make;
16
+ # `timeouts` bounds their connections and requests.
17
+ def initialize(zone:, control_plane:, attach_provider:, clock: PineSandbox::SYSTEM_CLOCK,
18
+ timeouts: Timeouts::DEFAULT)
16
19
  raise ArgumentError, "attach_provider required (mints the per-attach bind_token + broker_grant)" unless attach_provider
17
20
  raise ArgumentError, "zone required (a PineSandbox::Zone)" unless zone.is_a?(PineSandbox::Zone)
18
21
  raise ArgumentError, "control_plane required" unless control_plane
@@ -21,6 +24,7 @@ module PineSandbox
21
24
  @zone = zone
22
25
  @control_plane = control_plane
23
26
  @clock = clock
27
+ @timeouts = timeouts
24
28
  end
25
29
  end
26
30
  end
@@ -1,4 +1,6 @@
1
1
  require "faraday"
2
+ require_relative "timeouts"
3
+ require_relative "adapters/connect_aware_net_http"
2
4
  require "json"
3
5
  require "time"
4
6
  require_relative "errors"
@@ -27,10 +29,10 @@ module PineSandbox
27
29
  # public operation table) is sent on a transient transport failure
28
30
  # (connection reset / timeout). clock drives deadlines, backoff and jitter;
29
31
  # sleeper, when given, replaces only its waits (tests).
30
- attr_reader :clock
32
+ attr_reader :clock, :request_timeout
31
33
 
32
34
  def initialize(control_host:, token_source:, protocol: "https", spec_version: 1,
33
- open_timeout: 5, request_timeout: 30, connection: nil,
35
+ open_timeout: Timeouts::DEFAULT_CONNECT, request_timeout: Timeouts::DEFAULT_REQUEST, connection: nil,
34
36
  max_transient_attempts: RetryPolicy::TRANSIENT_ATTEMPTS, sleeper: nil, gateway_url: nil,
35
37
  clock: PineSandbox::SYSTEM_CLOCK)
36
38
  @control_host = control_host.to_s
@@ -48,14 +50,16 @@ module PineSandbox
48
50
 
49
51
  # Internal adapter for the public Computer contract. No generic sandbox
50
52
  # create, image selection or task dispatch is available through this client.
51
- def create_computer(body:, request_timeout: nil)
53
+ # reached, when given, is called for each send that may have reached the server.
54
+ def create_computer(body:, request_timeout: nil, reached: nil)
52
55
  # A create ID permits identical retries without extending the Computer's expiry.
53
56
  keyed = !!body[:create_id]
54
57
  deadline = monotonic_now + request_timeout if request_timeout
55
58
  busy_repeats = 0
56
59
  loop do
57
60
  resp = authed(:post, "computer-sandboxes", retry_transient: keyed && replay_safe?("createComputer"),
58
- request_timeout: deadline && remaining_timeout(deadline)) do |req|
61
+ request_timeout: deadline && remaining_timeout(deadline),
62
+ reached: reached) do |req|
59
63
  req.headers["Content-Type"] = "application/json"
60
64
  req.body = JSON.generate(body)
61
65
  end
@@ -161,20 +165,21 @@ module PineSandbox
161
165
  # is safe even for create. When retry_transient is set (idempotent reads + keyed
162
166
  # creates — see the call sites), a transient transport failure (connection reset /
163
167
  # timeout) is also re-sent with bounded backoff. Legacy unkeyed creates
164
- # remain single-shot on transport failure.
165
- def authed(method, path, retry_transient: false, request_timeout: nil, &block)
168
+ # remain single-shot on transport failure, unless the connection could not
169
+ # be opened: then nothing was sent and any request is tried again.
170
+ def authed(method, path, retry_transient: false, request_timeout: nil, reached: nil, &block)
166
171
  attempt = 0
167
172
  deadline = monotonic_now + request_timeout if request_timeout
168
173
  begin
169
174
  remaining_timeout(deadline)
170
- resp = send_request(method, path, @token_source.token, deadline: deadline, &block)
175
+ resp = send_request(method, path, @token_source.token, deadline: deadline, reached: reached, &block)
171
176
  return resp unless resp.status == 401
172
177
 
173
178
  remaining_timeout(deadline)
174
- send_request(method, path, @token_source.token(force_refresh: true), deadline: deadline, &block)
175
- rescue PineSandbox::ConnectionError, PineSandbox::TimeoutError
179
+ send_request(method, path, @token_source.token(force_refresh: true), deadline: deadline, reached: reached, &block)
180
+ rescue PineSandbox::ConnectionError, PineSandbox::TimeoutError => e
176
181
  attempt += 1
177
- raise unless retry_transient && attempt < @max_transient_attempts
182
+ raise unless (retry_transient || not_sent?(e)) && attempt < @max_transient_attempts
178
183
  delay = transient_backoff(attempt)
179
184
  delay = [delay, remaining_timeout(deadline)].min if deadline
180
185
  @sleeper.call(delay)
@@ -187,9 +192,9 @@ module PineSandbox
187
192
  RetryPolicy.transient_backoff(attempt, @clock)
188
193
  end
189
194
 
190
- def send_request(method, path, token, deadline: nil, &block)
195
+ def send_request(method, path, token, deadline: nil, reached: nil, &block)
191
196
  remaining = remaining_timeout(deadline)
192
- connection.public_send(method, path) do |req|
197
+ response = connection.public_send(method, path) do |req|
193
198
  if remaining
194
199
  req.options.timeout = remaining
195
200
  req.options.open_timeout = [@open_timeout, remaining].min
@@ -198,16 +203,25 @@ module PineSandbox
198
203
  req.headers["Accept"] = "application/json"
199
204
  block&.call(req)
200
205
  end
206
+ reached&.call
207
+ response
201
208
  rescue Faraday::TimeoutError => e
209
+ reached&.call
202
210
  raise PineSandbox::TimeoutError,
203
211
  PineSandbox.with_context("control plane request timed out: #{e.message}",
204
212
  op: "#{method.upcase} /#{path.to_s.split("?").first}")
205
213
  rescue Faraday::ConnectionFailed => e
206
- raise PineSandbox::ConnectionError,
207
- PineSandbox.with_context("control plane request failed: #{e.message}",
208
- op: "#{method.upcase} /#{path.to_s.split("?").first}")
214
+ error = PineSandbox::ConnectionError.new(
215
+ PineSandbox.with_context("control plane request failed: #{e.message}",
216
+ op: "#{method.upcase} /#{path.to_s.split("?").first}")
217
+ )
218
+ error.not_sent = Adapters::ConnectAwareNetHttp.not_sent?(e)
219
+ reached&.call unless error.not_sent?
220
+ raise error
209
221
  end
210
222
 
223
+ def not_sent?(error) = error.is_a?(PineSandbox::ConnectionError) && error.not_sent?
224
+
211
225
  def remaining_timeout(deadline)
212
226
  return unless deadline
213
227
 
@@ -1,4 +1,6 @@
1
1
  require "faraday"
2
+ require_relative "timeouts"
3
+ require_relative "adapters/connect_aware_net_http"
2
4
  require "base64"
3
5
  require "json"
4
6
  require "time"
@@ -26,7 +28,7 @@ module PineSandbox
26
28
  def initialize(api_key:, host:, protocol: "https",
27
29
  clock: -> { Time.now }, sleeper: ->(s) { Kernel.sleep(s) }, random: -> { Kernel.rand },
28
30
  skew: DEFAULT_SKEW_SECONDS, max_attempts: DEFAULT_MAX_ATTEMPTS,
29
- open_timeout: 5, request_timeout: 30, connection: nil, gateway_url: nil)
31
+ open_timeout: Timeouts::DEFAULT_CONNECT, request_timeout: Timeouts::DEFAULT_REQUEST, connection: nil, gateway_url: nil)
30
32
  raise ArgumentError, "api_key required (a pk_ client key)" if api_key.to_s.empty?
31
33
 
32
34
  @api_key = api_key.to_s
@@ -2,6 +2,7 @@ require "faraday"
2
2
  require "json"
3
3
  require "time"
4
4
  require_relative "errors"
5
+ require_relative "timeouts"
5
6
 
6
7
  module PineSandbox
7
8
  # Hash-compatible public payload with per-request scheduling metadata.
@@ -17,11 +18,11 @@ module PineSandbox
17
18
 
18
19
  # @api private — the Client exposes the project-scoped diagnostics operations.
19
20
  class Diagnostics
20
- def initialize(api_key:, zone:)
21
+ def initialize(api_key:, zone:, timeouts: Timeouts::DEFAULT)
21
22
  @api_key = api_key
22
23
  @connection = zone.faraday(zone.control_host) do |f|
23
- f.options.open_timeout = 5
24
- f.options.timeout = 30
24
+ f.options.open_timeout = timeouts.connect
25
+ f.options.timeout = timeouts.request
25
26
  end
26
27
  end
27
28
 
@@ -28,6 +28,7 @@ module PineSandbox
28
28
  "/errors/session-busy" => true,
29
29
  "/errors/agent-admission-unavailable" => true,
30
30
  "/errors/session-limit" => false,
31
+ "/errors/session-name-taken" => false,
31
32
  "/errors/session-teardown-failed" => true,
32
33
  "/errors/desktop-bind-failed" => true,
33
34
  "/errors/handoff-not-found" => false,
@@ -56,6 +57,8 @@ module PineSandbox
56
57
  "/errors/no-active-turn" => false,
57
58
  "/errors/no-pending-request" => false,
58
59
  "/errors/stale-turn" => false,
60
+ "/errors/turn-not-found" => false,
61
+ "/errors/stale-task" => false,
59
62
  "/errors/task-control-failed" => true,
60
63
  "/errors/task-not-found" => false,
61
64
  "/errors/task-not-ready" => true,
@@ -86,6 +89,7 @@ module PineSandbox
86
89
  "/errors/computer-stopped" => false,
87
90
  "/errors/stop-failed" => false,
88
91
  "/errors/history-expired" => false,
92
+ "/errors/events-unavailable" => true,
89
93
  "/errors/storage-exhausted" => false
90
94
  }.freeze
91
95