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.
@@ -1,6 +1,10 @@
1
1
  require "faraday"
2
2
  require "json"
3
+ require "time"
4
+ require_relative "clock"
3
5
  require_relative "errors"
6
+ require_relative "timeouts"
7
+ require_relative "adapters/connect_aware_net_http"
4
8
 
5
9
  module PineSandbox
6
10
  # The pk_-backed attach-credential provider — the DEFAULT attach path
@@ -18,6 +22,8 @@ module PineSandbox
18
22
  # advances the key floor, supersedes the prior binding, and mints.
19
23
  # * DELETE /v1/computers/:computer_id — permanent delete.
20
24
  # 204 for deleted, already deleted, unknown, and cross-project ids alike.
25
+ # * POST /v1/computers/:computer_id/artifacts/token — a short-lived
26
+ # storage token for the Computer's artifacts (Artifacts).
21
27
  #
22
28
  # This source caches nothing. Computer#run_bind calls it exactly once for each
23
29
  # start, then convergence retries re-send the held envelope verbatim
@@ -29,7 +35,8 @@ module PineSandbox
29
35
  LOCATIONS_PATH = "/v1/locations"
30
36
 
31
37
  def initialize(api_key:, host:, protocol: "https",
32
- open_timeout: 5, request_timeout: 30, connection: nil, gateway_url: nil)
38
+ open_timeout: Timeouts::DEFAULT_CONNECT, request_timeout: Timeouts::DEFAULT_REQUEST, connection: nil, gateway_url: nil,
39
+ clock: PineSandbox::SYSTEM_CLOCK)
33
40
  raise ArgumentError, "api_key required (a pk_ client key)" if api_key.to_s.empty?
34
41
 
35
42
  @api_key = api_key.to_s
@@ -39,6 +46,7 @@ module PineSandbox
39
46
  @open_timeout = open_timeout
40
47
  @request_timeout = request_timeout
41
48
  @connection = connection
49
+ @clock = clock
42
50
  end
43
51
 
44
52
  # Register `computer_id` into the portal ownership registry (idempotent —
@@ -97,9 +105,34 @@ module PineSandbox
97
105
  payload
98
106
  end
99
107
 
108
+ # A short-lived storage token for the Computer's artifacts, and where they
109
+ # are: "access_token", "expires_at", "endpoint", "bucket", "prefix",
110
+ # "writable", "used_bytes" and "limit_bytes". With `copy_from` (other
111
+ # Computer ids of the project), it may also read their artifacts, and
112
+ # "copy_from" maps each id to its prefix. Works whether or not the
113
+ # Computer is running. Returns the response Hash.
114
+ def artifact_token(computer_id, copy_from: nil)
115
+ raise ArgumentError, "computer_id required" if computer_id.to_s.empty?
116
+
117
+ copy_from = Array(copy_from).map(&:to_s)
118
+ body = copy_from.empty? ? {} : { copy_from: copy_from }
119
+ resp = post("#{REGISTER_PATH}/#{computer_id}/artifacts/token", json: body, op: "artifact token")
120
+ if resp.status == 404
121
+ raise UnknownComputerError.new(error_message(resp, "Computer not found"), **error_attributes(resp))
122
+ end
123
+ raise PortalError.new(error_message(resp, "Artifact token unavailable"), **error_attributes(resp)) unless resp.status == 200
124
+
125
+ payload = parse_json(resp)
126
+ unless artifact_token?(payload, copy_from)
127
+ raise PortalError.new("Invalid artifact token response", **error_attributes(resp))
128
+ end
129
+ payload
130
+ end
131
+
100
132
  # One authorization-registry read before Start; never a Computer status poll.
101
- def current_binding(computer_id)
102
- resp = get("#{REGISTER_PATH}/#{computer_id}", op: "computer binding lookup")
133
+ # request_timeout (seconds) bounds it, retries included.
134
+ def current_binding(computer_id, request_timeout: nil)
135
+ resp = get("#{REGISTER_PATH}/#{computer_id}", op: "computer binding lookup", request_timeout: request_timeout)
103
136
  if resp.status == 404
104
137
  raise UnknownComputerError.new("Computer not found", **error_attributes(resp))
105
138
  end
@@ -114,7 +147,7 @@ module PineSandbox
114
147
 
115
148
  # Permanently delete `computer_id`. The portal tombstones it at once (no
116
149
  # further attach, renewal, or lease refresh), destroys its bound sandboxes
117
- # asynchronously, keeps saved browser state for 24 hours before purging it,
150
+ # asynchronously, keeps saved browser state for 25 hours before purging it,
118
151
  # and never accepts the id again. Idempotent and non-disclosing: an unknown,
119
152
  # already-deleted, or cross-project id is the same 204. Returns true.
120
153
  def delete_computer(computer_id)
@@ -208,12 +241,14 @@ module PineSandbox
208
241
  )
209
242
  when 412
210
243
  problem = parse_json(resp)
244
+ # A Portal that predates current_revision sends only current_binding_revision.
245
+ revision = problem.fetch("current_revision") { problem["current_binding_revision"] }
211
246
  raise BindingRevisionConflictError.new(
212
247
  binding_conflict_message(
213
248
  error_message(resp, "binding revision changed; reload and adopt the winning binding"),
214
- problem["current_binding_revision"], problem["current_sandbox_id"]
249
+ revision, problem["current_sandbox_id"]
215
250
  ),
216
- current_binding_revision: problem["current_binding_revision"],
251
+ current_binding_revision: revision,
217
252
  current_sandbox_id: problem["current_sandbox_id"],
218
253
  **error_attributes(resp)
219
254
  )
@@ -243,6 +278,19 @@ module PineSandbox
243
278
  { country: normalized.fetch("country") }
244
279
  end
245
280
 
281
+ def artifact_token?(payload, copy_from)
282
+ return false unless payload.is_a?(Hash)
283
+ return false unless %w[access_token expires_at endpoint bucket].all? { |key| payload[key].is_a?(String) && !payload[key].empty? }
284
+ return false unless payload["prefix"].is_a?(String) && [true, false].include?(payload["writable"])
285
+ return false unless payload["used_bytes"].is_a?(Integer) && payload["limit_bytes"].is_a?(Integer)
286
+
287
+ Time.iso8601(payload["expires_at"])
288
+ prefixes = payload["copy_from"] || {}
289
+ prefixes.is_a?(Hash) && copy_from.all? { |id| prefixes[id].is_a?(String) }
290
+ rescue ArgumentError
291
+ false
292
+ end
293
+
246
294
  def response_location?(value)
247
295
  value.is_a?(Hash) && value["country"].is_a?(String) &&
248
296
  value["country"].match?(/\A[A-Z]{2}\z/)
@@ -311,8 +359,8 @@ module PineSandbox
311
359
  end
312
360
  end
313
361
 
314
- def get(path, op:)
315
- request(:get, path, op: op) do |req|
362
+ def get(path, op:, request_timeout: nil)
363
+ request(:get, path, op: op, request_timeout: request_timeout) do |req|
316
364
  req.headers["Authorization"] = "Bearer #{@api_key}"
317
365
  req.headers["Accept"] = "application/json"
318
366
  end
@@ -325,8 +373,32 @@ module PineSandbox
325
373
  end
326
374
  end
327
375
 
328
- def request(method, path, op:)
329
- connection.public_send(method, path) { |req| yield req }
376
+ # A request whose connection could not be opened was not sent, so it is
377
+ # tried again on the transient backoff; any other fault raises.
378
+ def request(method, path, op:, request_timeout: nil, &block)
379
+ attempt = 0
380
+ deadline = @clock.monotonic + request_timeout if request_timeout
381
+ begin
382
+ attempt += 1
383
+ send_once(method, path, op: op, deadline: deadline, &block)
384
+ rescue PineSandbox::ConnectionError => e
385
+ raise unless e.not_sent? && attempt < RetryPolicy::TRANSIENT_ATTEMPTS
386
+
387
+ delay = RetryPolicy.transient_backoff(attempt, @clock)
388
+ @clock.sleep(deadline ? [delay, time_left(deadline, method, path, op)].min : delay)
389
+ retry
390
+ end
391
+ end
392
+
393
+ def send_once(method, path, op:, deadline: nil)
394
+ left = deadline && time_left(deadline, method, path, op)
395
+ connection.public_send(method, path) do |req|
396
+ if left
397
+ req.options.timeout = left
398
+ req.options.open_timeout = [@open_timeout, left].min
399
+ end
400
+ yield req
401
+ end
330
402
  rescue Faraday::TimeoutError => e
331
403
  raise PineSandbox::TimeoutError,
332
404
  PineSandbox.with_context(
@@ -334,11 +406,23 @@ module PineSandbox
334
406
  op: "#{method.to_s.upcase} #{path.split('?').first}"
335
407
  )
336
408
  rescue Faraday::ConnectionFailed => e
337
- raise PineSandbox::ConnectionError,
338
- PineSandbox.with_context(
339
- "portal #{op} connection failed: #{e.message}",
340
- op: "#{method.to_s.upcase} #{path.split('?').first}"
341
- )
409
+ error = PineSandbox::ConnectionError.new(
410
+ PineSandbox.with_context(
411
+ "portal #{op} connection failed: #{e.message}",
412
+ op: "#{method.to_s.upcase} #{path.split('?').first}"
413
+ )
414
+ )
415
+ error.not_sent = Adapters::ConnectAwareNetHttp.not_sent?(e)
416
+ raise error
417
+ end
418
+
419
+ def time_left(deadline, method, path, op)
420
+ left = deadline - @clock.monotonic
421
+ return left if left.positive?
422
+
423
+ raise PineSandbox::TimeoutError,
424
+ PineSandbox.with_context("portal #{op} call timed out: deadline exceeded",
425
+ op: "#{method.to_s.upcase} #{path.split('?').first}")
342
426
  end
343
427
 
344
428
  def request_id(resp)
@@ -384,6 +468,7 @@ module PineSandbox
384
468
 
385
469
  def connection
386
470
  @connection ||= Zone.faraday(scheme: @protocol, host: @host, gateway_url: @gateway_url) do |f|
471
+ f.headers["User-Agent"] = PineSandbox::USER_AGENT
387
472
  f.options.open_timeout = @open_timeout
388
473
  f.options.timeout = @request_timeout
389
474
  end
@@ -1,4 +1,5 @@
1
1
  require_relative "errors"
2
+ require_relative "terminal_reason"
2
3
 
3
4
  module PineSandbox
4
5
  # Maps a streaming authoring run's terminal Result (the last event of
@@ -9,16 +10,16 @@ module PineSandbox
9
10
  # values below; the optional `author` object carries the typed
10
11
  # authoring outcome.
11
12
  module AuthorTerminalTranslator
12
- AUTHOR_TERMINAL_DRAFT_REGISTERED = "draft_registered".freeze
13
- AUTHOR_TERMINAL_CLARIFICATION_REQUEST = "clarification_requested".freeze
14
- AUTHOR_TERMINAL_NOT_REUSABLE = "not_reusable".freeze
15
- AUTHOR_TERMINAL_REGISTRATION_FAILED = "registration_failed".freeze
16
- AUTHOR_TERMINAL_CANCELED = "canceled".freeze
17
- AUTHOR_TERMINAL_FAILED = "failed".freeze
13
+ AUTHOR_TERMINAL_DRAFT_REGISTERED = TerminalReason::DRAFT_REGISTERED
14
+ AUTHOR_TERMINAL_CLARIFICATION_REQUEST = TerminalReason::CLARIFICATION_REQUESTED
15
+ AUTHOR_TERMINAL_NOT_REUSABLE = TerminalReason::NOT_REUSABLE
16
+ AUTHOR_TERMINAL_REGISTRATION_FAILED = TerminalReason::REGISTRATION_FAILED
17
+ AUTHOR_TERMINAL_CANCELED = TerminalReason::CANCELED
18
+ AUTHOR_TERMINAL_FAILED = TerminalReason::FAILED
18
19
  # Terminal reason when the Computer's services restarted while the run
19
20
  # was in flight. Surfaced to the caller as an Error so they can retry —
20
21
  # the authoring itself didn't fail; the run got interrupted.
21
- AUTHOR_TERMINAL_COORDINATOR_RESTARTED = "coordinator_restarted".freeze
22
+ AUTHOR_TERMINAL_COORDINATOR_RESTARTED = TerminalReason::COORDINATOR_RESTARTED
22
23
 
23
24
  module_function
24
25
 
@@ -43,9 +44,9 @@ module PineSandbox
43
44
  { "learned" => false, "reason" => "the run was too ambiguous to author a reliable skill — teach it instead" }
44
45
  when AUTHOR_TERMINAL_NOT_REUSABLE
45
46
  { "learned" => false, "reason" => summary || "the navigation is not a reusable skill" }
46
- when AUTHOR_TERMINAL_REGISTRATION_FAILED, AUTHOR_TERMINAL_CANCELED, AUTHOR_TERMINAL_FAILED, "storage_exhausted"
47
+ when *TerminalReason::AUTHOR_FAILED
47
48
  raise PineSandbox::Error, "author run #{reason}: #{summary}"
48
- when AUTHOR_TERMINAL_COORDINATOR_RESTARTED
49
+ when *TerminalReason::AUTHOR_INTERRUPTED
49
50
  raise PineSandbox::Error,
50
51
  "author run interrupted because the Computer's services restarted — retry the learn call"
51
52
  else
@@ -82,9 +83,9 @@ module PineSandbox
82
83
  }
83
84
  when AUTHOR_TERMINAL_NOT_REUSABLE
84
85
  { "taught" => false, "reason" => summary || "the demonstration is not a reusable skill" }
85
- when AUTHOR_TERMINAL_REGISTRATION_FAILED, AUTHOR_TERMINAL_CANCELED, AUTHOR_TERMINAL_FAILED, "storage_exhausted"
86
+ when *TerminalReason::AUTHOR_FAILED
86
87
  raise PineSandbox::Error, "author run #{reason}: #{summary}"
87
- when AUTHOR_TERMINAL_COORDINATOR_RESTARTED
88
+ when *TerminalReason::AUTHOR_INTERRUPTED
88
89
  raise PineSandbox::Error,
89
90
  "author run interrupted because the Computer's services restarted — retry the teach call"
90
91
  else
@@ -7,6 +7,7 @@ require_relative "control_plane"
7
7
  require_relative "connection"
8
8
  require_relative "computer"
9
9
  require_relative "diagnostics"
10
+ require_relative "artifacts"
10
11
 
11
12
  module PineSandbox
12
13
  # The SDK entry point. Holds the project credential (`pk_`) + the endpoint
@@ -90,14 +91,24 @@ module PineSandbox
90
91
  alias_method :to_s, :inspect
91
92
  end
92
93
 
94
+ # `connect_timeout:` bounds opening one connection (the TCP connect, then
95
+ # the TLS handshake), default 10 seconds; a connection that could not be
96
+ # opened sent nothing, so the request is tried again. `request_timeout:`
97
+ # bounds one request that has no budget of its own, default 30 seconds; a
98
+ # turn wait adds the time the Computer holds it. Raise them for a slow or
99
+ # distant network.
100
+ #
93
101
  # `clock:` (@api private) replaces the SDK's view of time — every wait,
94
102
  # deadline and jitter — for tests that run retries on a virtual clock.
95
103
  def initialize(endpoint: nil, api_key: nil,
96
104
  control_host: nil, spec_version: DelegatedConnection::SPEC_VERSION,
97
105
  control_token_provider: nil, attach_credentials_provider: nil,
98
- gateway_url: nil, clock: PineSandbox::SYSTEM_CLOCK)
106
+ gateway_url: nil, connect_timeout: Timeouts::DEFAULT_CONNECT,
107
+ request_timeout: Timeouts::DEFAULT_REQUEST, clock: PineSandbox::SYSTEM_CLOCK)
99
108
  raise ArgumentError, "endpoint required (e.g. \"https://pinesandbox.io\")" if endpoint.nil?
100
109
 
110
+ @timeouts = Timeouts.new(connect: connect_timeout, request: request_timeout)
111
+
101
112
  @zone =
102
113
  if endpoint.is_a?(PineSandbox::Zone)
103
114
  raise ArgumentError, "pass gateway_url to the Zone, not with one" unless gateway_url.nil?
@@ -107,7 +118,8 @@ module PineSandbox
107
118
  PineSandbox::Zone.new(endpoint, control_host: control_host, gateway_url: gateway_url)
108
119
  end
109
120
  @spec_version = spec_version
110
- @diagnostics = Diagnostics.new(api_key: api_key, zone: @zone) unless api_key.to_s.empty?
121
+ @clock = clock
122
+ @diagnostics = Diagnostics.new(api_key: api_key, zone: @zone, timeouts: @timeouts) unless api_key.to_s.empty?
111
123
 
112
124
  token_source =
113
125
  if control_token_provider
@@ -116,7 +128,8 @@ module PineSandbox
116
128
  raise ArgumentError, "api_key required (a pk_ client key) unless control_token_provider is given" if api_key.to_s.empty?
117
129
 
118
130
  ControlTokenSource.new(api_key: api_key, host: @zone.control_host, protocol: @zone.http_scheme,
119
- gateway_url: @zone.gateway_url, clock: -> { clock.now },
131
+ gateway_url: @zone.gateway_url, open_timeout: @timeouts.connect,
132
+ request_timeout: @timeouts.request, clock: -> { clock.now },
120
133
  sleeper: ->(seconds) { clock.sleep(seconds) }, random: -> { clock.rand })
121
134
  end
122
135
 
@@ -131,16 +144,18 @@ module PineSandbox
131
144
  end
132
145
  elsif !api_key.to_s.empty?
133
146
  AttachCredentialsSource.new(api_key: api_key, host: @zone.control_host, protocol: @zone.http_scheme,
134
- gateway_url: @zone.gateway_url)
147
+ gateway_url: @zone.gateway_url, open_timeout: @timeouts.connect,
148
+ request_timeout: @timeouts.request, clock: clock)
135
149
  else
136
150
  raise ArgumentError, "attach credentials unavailable: pass api_key (a pk_ client key) or attach_credentials_provider:"
137
151
  end
138
152
 
139
153
  @control_plane = ControlPlane.new(control_host: @zone.control_host, token_source: token_source,
140
154
  protocol: @zone.http_scheme, spec_version: @spec_version,
141
- gateway_url: @zone.gateway_url, clock: clock)
155
+ gateway_url: @zone.gateway_url, open_timeout: @timeouts.connect,
156
+ request_timeout: @timeouts.request, clock: clock)
142
157
  @connection = Connection.new(attach_provider: attach_provider, zone: @zone, control_plane: @control_plane,
143
- clock: clock)
158
+ clock: clock, timeouts: @timeouts)
144
159
  end
145
160
 
146
161
  # @api private — retained for compatibility; applications use Computer operations.
@@ -184,12 +199,25 @@ module PineSandbox
184
199
  provider.project_policy
185
200
  end
186
201
 
202
+ # A Computer's artifacts, running or stopped: the files it keeps beyond
203
+ # its sessions, to list, upload, download, open, copy and delete (see
204
+ # Artifacts). Needs the project API key; no request is sent until the
205
+ # first operation.
206
+ def artifacts(computer_id)
207
+ raise ArgumentError, "id must be a lowercase UUIDv7" unless computer_id.to_s.match?(Computer::UUID_V7)
208
+
209
+ provider = @connection.attach_provider
210
+ raise ArgumentError, "artifacts require a project API key provider" unless provider.respond_to?(:artifact_token)
211
+
212
+ Artifacts.new(computer_id: computer_id, token_source: provider, clock: @clock, timeouts: @timeouts)
213
+ end
214
+
187
215
  # PERMANENTLY delete a Computer: its identity and saved state end (stop
188
216
  # and kill keep both). Accepts a PineSandbox::Computer or its id String. A
189
217
  # Computer that is still attached is force-terminated first (#kill — no
190
218
  # final capture, the state is being deleted). The portal tombstones the id
191
219
  # immediately, destroys any remaining sandboxes asynchronously, purges saved
192
- # state after 24 hours, and never accepts the id again. Idempotent: unknown,
220
+ # state after 25 hours, and never accepts the id again. Idempotent: unknown,
193
221
  # already-deleted, and other projects' ids all return true. No undelete.
194
222
  def delete_computer(computer)
195
223
  computer_id =
@@ -267,9 +295,14 @@ module PineSandbox
267
295
  start_existing_computer(*args, **options, recover: false)
268
296
  end
269
297
 
270
- # Gracefully stop the binding observed for this ID, even when a caller lost
271
- # its Start response before saving the Computer token. Never follow a newer
272
- # binding during this invocation; project authorization is sufficient.
298
+ # Stops the runtime that the Computer's binding points to when it's called,
299
+ # which may be a runtime another worker has just started. Use it only to
300
+ # recover after losing the Computer handle, and run the recoveries of one
301
+ # Computer one at a time. Returns true when that runtime is no longer
302
+ # running, or when there was nothing to stop. true does not confirm that the
303
+ # final save succeeded. Returns false when the runtime did not stop within
304
+ # wait_timeout (seconds, default 390; 0 skips only the wait). When
305
+ # Computer#stop returns false, call stop on that handle again instead.
273
306
  def stop_computer(computer_id, **wait_options)
274
307
  raise ArgumentError, "id must be a lowercase UUIDv7" unless computer_id.to_s.match?(Computer::UUID_V7)
275
308
  provider = @connection.attach_provider
@@ -296,49 +329,69 @@ module PineSandbox
296
329
  start_existing_computer(*args, **options, recover: true)
297
330
  end
298
331
 
332
+ # ready_timeout covers the whole Start: the release wait, the create and the start.
299
333
  def start_existing_computer(positional_id = nil, id: nil, key:, capture_keypair: nil, prior_capture_keypairs: [],
300
- binding_revision: 0, prior_keys: {}, ephemeral: false, location: nil, recover: false, **attach_opts)
334
+ binding_revision: 0, prior_keys: {}, ephemeral: false, location: nil, recover: false,
335
+ ready_timeout: Computer::DEFAULT_READY_TIMEOUT, **attach_opts)
301
336
  if positional_id && id && positional_id != id
302
337
  raise ArgumentError, "attach_computer got two different ids (positional and id:)"
303
338
  end
304
339
  id ||= positional_id
305
340
  raise ArgumentError, "attach_computer requires the Computer id" if id.nil?
306
341
 
342
+ started = @clock.monotonic
343
+ Computer.check_ready_timeout!(ready_timeout)
307
344
  provider = @connection.attach_provider
308
345
  if recover && !provider.respond_to?(:current_binding)
309
346
  raise ArgumentError, "saved-state recovery requires a provider with current_binding"
310
347
  end
311
348
  if provider.respond_to?(:current_binding)
312
- reference = provider.current_binding(id)
313
- binding_revision = reference.fetch("binding_revision")
314
- if (sandbox_id = reference["sandbox_id"])
315
- begin
316
- sandbox = @connection.control_plane.get(sandbox_id)
317
- unless sandbox.status == :terminated && sandbox.reason == "COMPUTE_RELEASED"
318
- unless recover || sandbox.status == :stopping
319
- raise SandboxRetainedError.new(sandbox_id: sandbox_id, state: sandbox.status)
320
- end
321
- handle = SandboxHandle.new(control_plane: @connection.control_plane, sandbox_id: sandbox_id)
322
- unless handle.release_failed_sandbox(sandbox)
323
- raise TimeoutError, "The failed Computer's shutdown is unconfirmed; nothing was started"
324
- end
325
- end
326
- rescue NotFoundError
327
- # Authoritative project-scoped absence allows ordinary Start.
328
- end
349
+ reference = within_ready_budget(started, ready_timeout, nil) do |left|
350
+ # A provider of the caller's own reads the binding on its own terms.
351
+ provider.is_a?(AttachCredentialsSource) ? provider.current_binding(id, request_timeout: left) : provider.current_binding(id)
329
352
  end
330
353
  end
354
+ binding_revision = reference.fetch("binding_revision") if reference
331
355
 
356
+ # Invalid caller material and options fail here, before Recover can release anything.
332
357
  computer = Computer.new(id, key: key, binding_revision: binding_revision,
333
358
  **(ephemeral ? { ephemeral: true } : {}))
334
359
  configure_capture_keypairs(computer, capture_keypair, prior_capture_keypairs)
335
360
  prior_keys.each { |version, bytes| computer.add_prior_key(version, bytes) }
336
361
  attach_opts = attach_opts.merge(location: location) if location
337
- attach_with_recovery_context(computer, initial_revision: binding_revision, **attach_opts)
362
+ computer.check_attach_options!(@connection, ready_timeout: ready_timeout, **attach_opts)
363
+
364
+ if reference && (sandbox_id = reference["sandbox_id"])
365
+ sandbox = begin
366
+ within_ready_budget(started, ready_timeout, sandbox_id) do |left|
367
+ @connection.control_plane.get(sandbox_id, request_timeout: left)
368
+ end
369
+ rescue NotFoundError
370
+ nil # Authoritative project-scoped absence.
371
+ end
372
+ SandboxHandle.new(control_plane: @connection.control_plane, sandbox_id: sandbox_id)
373
+ .admit(recover ? :recover : :start, sandbox, started: started, deadline: started + ready_timeout)
374
+ end
375
+
376
+ attach_with_recovery_context(computer, initial_revision: binding_revision, ready_timeout: ready_timeout,
377
+ budget_start: started, **attach_opts)
338
378
  end
339
379
 
340
380
  private :start_existing_computer
341
381
 
382
+ # Yields what is left of a Start's ready_timeout to a read of the Computer's binding or
383
+ # current runtime; the budget running out there is the Start's ReadyTimeoutError.
384
+ def within_ready_budget(started, ready_timeout, sandbox_id)
385
+ yield started + ready_timeout - @clock.monotonic
386
+ rescue PineSandbox::TimeoutError
387
+ raise if @clock.monotonic < started + ready_timeout
388
+
389
+ waited = @clock.monotonic - started
390
+ raise ReadyTimeoutError.new(PineSandbox.runtime_message(:current_read_timed_out, sandbox_id: sandbox_id, waited: waited),
391
+ sandbox_id: sandbox_id, waited: waited)
392
+ end
393
+ private :within_ready_budget
394
+
342
395
  # Compatibility name for saved-state Start; never a memory Resume.
343
396
  alias_method :attach_computer, :start_computer
344
397
 
@@ -421,7 +474,7 @@ module PineSandbox
421
474
  end
422
475
 
423
476
  def attach_with_recovery_context(computer, initial_revision:, recovery_credentials: nil, **attach_opts)
424
- computer.attach(@connection, **attach_opts)
477
+ computer.attach_runtime(@connection, **attach_opts)
425
478
  rescue StandardError => e
426
479
  revision = computer.binding_revision
427
480
  sandbox_id = computer.last_authorized_sandbox_id