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.
@@ -1,4 +1,5 @@
1
1
  require_relative "error_taxonomy"
2
+ require_relative "runtime_admission"
2
3
 
3
4
  module PineSandbox
4
5
  # Marks a renamed public method: the old name keeps working and, when Ruby's
@@ -184,6 +185,54 @@ module PineSandbox
184
185
  class EmptyPatch < BadRequestError; end
185
186
  class MalformedJSON < BadRequestError; end
186
187
  class SessionNotFound < NotFoundError; end
188
+ # Create found a session with this name already. Choose another name.
189
+ class SessionNameTaken < ConflictError; end
190
+ # The Computer has as many sessions as it allows. Close an idle or finished
191
+ # one, then create again.
192
+ class SessionLimit < ConflictError; end
193
+ # The session's agent is still working, or a deleted session with this name
194
+ # is still shutting down. Retry once it is idle.
195
+ class SessionBusy < ConflictError; end
196
+ # The session lost its shell (the Computer answers exec with the code
197
+ # "terminal_lost"). Session#recreate_terminal rebuilds it; then run the
198
+ # command again.
199
+ class TerminalLost < ConflictError; end
200
+ # A Stop has begun, whoever sent it, and the Computer refuses every call
201
+ # until it starts again. Not a conflict to retry: follow the Stop in the
202
+ # Computer's status, then Start.
203
+ class ComputerStopped < ConflictError; end
204
+ # An agent read found no task: the session hasn't run a turn yet. The
205
+ # session is fine; start a turn on it.
206
+ class TaskNotFound < NotFoundError; end
207
+ # A read pinned to a task (expected_task_id) found the session on another
208
+ # one. Its saved cursors belong to the old task; read the current task.
209
+ class StaleTask < ConflictError; end
210
+ # An agent action found nothing to act on: the session is idle
211
+ # (NoActiveTask), or its turn ended while the request was on its way
212
+ # (NoActiveTurn). The session is fine; start a turn on it.
213
+ class NoActiveTask < ConflictError; end
214
+ class NoActiveTurn < ConflictError; end
215
+ # The action named a turn that is no longer the current one: newer work
216
+ # started, or the turn was already answered. Read the current turn.
217
+ class StaleTurn < ConflictError; end
218
+ # An answer found the turn isn't waiting for one.
219
+ class NoPendingRequest < ConflictError; end
220
+ # The session has no turn with this id.
221
+ class TurnNotFound < NotFoundError; end
222
+ # A skill is already being written for this session; one authoring run at a
223
+ # time.
224
+ class AuthorInFlight < ConflictError; end
225
+ # The skill wasn't saved because it contains something that looks like a
226
+ # secret.
227
+ class SecretInSkill < UnprocessableEntityError; end
228
+ # Skills aren't available on this Computer.
229
+ class SkillsUnavailable < ServiceUnavailableError; end
230
+ # The cursor is older than the history the Computer keeps; the problem's
231
+ # pruned_through says where the kept history begins.
232
+ class HistoryExpired < GoneError; end
233
+ # The Computer couldn't read its event history just now. Retry with the
234
+ # same cursor.
235
+ class EventsUnavailable < ServiceUnavailableError; end
187
236
  class DesktopBindFailed < ServiceUnavailableError; end
188
237
  class HandoffNotFound < NotFoundError; end
189
238
  class HandoffUnavailable < ConflictError; end
@@ -217,6 +266,22 @@ module PineSandbox
217
266
  "/errors/empty-patch" => EmptyPatch,
218
267
  "/errors/malformed-json" => MalformedJSON,
219
268
  "/errors/session-not-found" => SessionNotFound,
269
+ "/errors/session-name-taken" => SessionNameTaken,
270
+ "/errors/session-limit" => SessionLimit,
271
+ "/errors/session-busy" => SessionBusy,
272
+ "/errors/computer-stopped" => ComputerStopped,
273
+ "/errors/task-not-found" => TaskNotFound,
274
+ "/errors/stale-task" => StaleTask,
275
+ "/errors/no-active-task" => NoActiveTask,
276
+ "/errors/no-active-turn" => NoActiveTurn,
277
+ "/errors/stale-turn" => StaleTurn,
278
+ "/errors/no-pending-request" => NoPendingRequest,
279
+ "/errors/turn-not-found" => TurnNotFound,
280
+ "/errors/author-in-flight" => AuthorInFlight,
281
+ "/errors/secret-in-skill" => SecretInSkill,
282
+ "/errors/skills-unavailable" => SkillsUnavailable,
283
+ "/errors/history-expired" => HistoryExpired,
284
+ "/errors/events-unavailable" => EventsUnavailable,
220
285
  "/errors/desktop-bind-failed" => DesktopBindFailed,
221
286
  "/errors/handoff-not-found" => HandoffNotFound,
222
287
  "/errors/handoff-unavailable" => HandoffUnavailable,
@@ -231,24 +296,71 @@ module PineSandbox
231
296
 
232
297
  def self.problem_class_for(problem_type) = PROBLEM_TYPE_CLASSES[problem_type]
233
298
 
299
+ # Answers the Computer names by its status and the machine code in a plain
300
+ # JSON body (`{"error": "terminal_lost"}`), not by a problem type.
301
+ CODE_CLASSES = { [409, "terminal_lost"] => TerminalLost }.freeze
302
+
303
+ def self.code_class_for(status, code) = CODE_CLASSES[[status, code]]
304
+
234
305
  # Failures with no HTTP response, or a timeout status (408/504) without a
235
306
  # problem body. #retry_after is the response's Retry-After in seconds, when
236
307
  # a timeout status set one.
237
308
  class TimeoutError < Error
238
309
  attr_accessor :retry_after
239
310
  end
240
- class ConnectionError < Error; end
241
- class ReadyTimeoutError < Error; end
311
+ # #not_sent? is true when the connection could not be opened, so the
312
+ # request never reached Pine.
313
+ class ConnectionError < Error
314
+ attr_writer :not_sent
315
+
316
+ def not_sent? = @not_sent == true
317
+ end
318
+
319
+ # Fills an admission-table template: a RuntimeAdmission::MESSAGES id (with or without
320
+ # the reason) or a text RuntimeAdmission.decide chose. waited rounds half up.
321
+ # @api private
322
+ def self.runtime_message(template, sandbox_id:, state: nil, reason: nil, target: nil, new_runtime: false, waited: nil)
323
+ reason = nil if reason.to_s.empty?
324
+ template = RuntimeAdmission::MESSAGES.fetch(template)[reason ? 0 : 1] if template.is_a?(Symbol)
325
+ values = { "sandbox_id" => sandbox_id, "state" => state, "reason" => reason, "target" => target,
326
+ "new" => new_runtime ? "New " : "", "waited" => waited&.round }
327
+ template.gsub(/\{(\w+)\}/) { values.fetch(Regexp.last_match(1)).to_s }
328
+ end
242
329
 
243
- # The Computer reported failed, terminated or unavailable before the
330
+ # The ready_timeout budget ran out before the current runtime was released
331
+ # (nothing was started) or the new one ran; also Pause's and Resume's deadline.
332
+ # Nothing was attached and the binding is unchanged. #waited is in seconds.
333
+ class ReadyTimeoutError < Error
334
+ attr_reader :sandbox_id, :last_state, :last_reason, :waited
335
+
336
+ # target: the state not reached (:running, :paused); the release wait passes its own message.
337
+ def initialize(message = nil, sandbox_id: nil, last_state: nil, last_reason: nil, waited: nil,
338
+ target: nil, new_runtime: false)
339
+ @sandbox_id, @last_state, @last_reason, @waited = sandbox_id, last_state, last_reason, waited
340
+ if message.nil? && target
341
+ message = PineSandbox.runtime_message(:ready_timed_out, sandbox_id: sandbox_id, state: last_state,
342
+ reason: last_reason, target: target,
343
+ new_runtime: new_runtime, waited: waited.to_f)
344
+ end
345
+ super(message)
346
+ end
347
+
348
+ # Not retryable: each Start makes a new runtime.
349
+ def retryable? = false
350
+ end
351
+
352
+ # The runtime reported failed, terminated or unavailable before the
244
353
  # lifecycle operation finished.
245
354
  class SandboxFailedError < Error
246
- attr_reader :sandbox_id, :state
355
+ attr_reader :sandbox_id, :state, :reason
247
356
 
248
- def initialize(message = nil, sandbox_id: nil, state: nil)
357
+ def initialize(message = nil, sandbox_id: nil, state: nil, reason: nil, target: :running, new_runtime: false)
249
358
  @sandbox_id = sandbox_id
250
359
  @state = state
251
- super(message || "Computer sandbox #{sandbox_id} reported #{state.inspect} before completing the lifecycle operation")
360
+ @reason = reason
361
+ super(message || PineSandbox.runtime_message(:runtime_failed, sandbox_id: sandbox_id, state: state,
362
+ reason: reason, target: target,
363
+ new_runtime: new_runtime))
252
364
  end
253
365
  end
254
366
 
@@ -304,7 +416,9 @@ module PineSandbox
304
416
  def retryable? = @retryable.nil? ? (save_error.respond_to?(:retryable?) && save_error.retryable?) : @retryable
305
417
  end
306
418
 
307
- # BindError and its subclasses are the typed outcomes of Computer#attach.
419
+ # BindError and its subclasses are the typed outcomes of Computer#attach. A
420
+ # plain BindError is also raised by a call that needs a
421
+ # binding on a handle that has none.
308
422
  # `#status` is the HTTP status when one is available; `#cause` is the
309
423
  # underlying ApiError, so callers can inspect the raw response if needed.
310
424
  class BindError < Error
@@ -317,14 +431,29 @@ module PineSandbox
317
431
  end
318
432
  end
319
433
 
320
- # Start found the Computer still running or paused, and started nothing.
434
+ # Start or Recover refused the Computer's unreleased current runtime and
435
+ # started nothing.
321
436
  # Preserve the BindError superclass for integrations already rescuing Start conflicts.
322
437
  class SandboxRetainedError < BindError
323
- attr_reader :sandbox_id, :state
438
+ attr_reader :sandbox_id, :state, :reason
324
439
 
325
- def initialize(sandbox_id:, state:)
326
- @sandbox_id, @state = sandbox_id, state
327
- super("Computer hasn't stopped (Computer sandbox #{sandbox_id}, state #{state}); Stop it or Resume retained memory before Start")
440
+ # message: the admission table's text (RuntimeAdmission); by default Start's.
441
+ def initialize(sandbox_id:, state:, reason: nil, message: nil)
442
+ @sandbox_id, @state, @reason = sandbox_id, state, reason
443
+ super(message || PineSandbox.runtime_message(RuntimeAdmission.decide(:start, state, reason).message.to_s,
444
+ sandbox_id: sandbox_id))
445
+ end
446
+ end
447
+
448
+ # Start or Recover found the Computer's current runtime already started, and
449
+ # started nothing. Not a SandboxRetainedError.
450
+ class ComputerAlreadyStartedError < BindError
451
+ attr_reader :sandbox_id, :state, :reason
452
+
453
+ def initialize(sandbox_id:, state:, reason: nil, message: nil)
454
+ @sandbox_id, @state, @reason = sandbox_id, state, reason
455
+ super(message || PineSandbox.runtime_message(RuntimeAdmission.decide(:start, state, reason).message.to_s,
456
+ sandbox_id: sandbox_id))
328
457
  end
329
458
  end
330
459
 
@@ -513,6 +642,28 @@ module PineSandbox
513
642
  end
514
643
  end
515
644
 
645
+ # 403 SPEND_LIMIT_REACHED: the project has reached its monthly spend limit, or
646
+ # its organization is out of credits, so a Computer wasn't started or resumed
647
+ # or its idle timeout wasn't changed. The same error whichever call was
648
+ # refused. Reads, stop, pause and delete still work. Not retried by the SDK:
649
+ # credits are added or the limit raised first; #message says which.
650
+ class SpendLimitReachedError < Error
651
+ CODE = "SPEND_LIMIT_REACHED".freeze
652
+ # The refusal's problem type, the same from every call.
653
+ PROBLEM_TYPE = "urn:pinesandbox:problem:spend-limit-reached".freeze
654
+
655
+ attr_reader :status, :request_id, :op
656
+
657
+ def initialize(message, status: 403, request_id: nil, op: nil)
658
+ @status = status
659
+ @request_id = request_id
660
+ @op = op
661
+ super(PineSandbox.with_context(message, op: op, request_id: request_id))
662
+ end
663
+
664
+ def code = CODE
665
+ end
666
+
516
667
  # 429 COMPUTER_CAPACITY_EXCEEDED on create/attach: the project is at its
517
668
  # concurrent Computer limit, so nothing was provisioned. Not retried by the
518
669
  # SDK — capacity frees only when another of the project's Computers stops.
@@ -76,11 +76,14 @@ module PineSandbox
76
76
  end
77
77
  end
78
78
 
79
+ # The body as a Hash. A body that isn't a JSON object carries no problem
80
+ # detail: it becomes the message.
79
81
  def parse_error_body(body)
80
82
  return body if body.is_a?(Hash)
81
83
  return {} if body.nil? || body == ""
82
84
 
83
- JSON.parse(body)
85
+ parsed = JSON.parse(body)
86
+ parsed.is_a?(Hash) ? parsed : { "message" => body.to_s }
84
87
  rescue JSON::ParserError
85
88
  { "message" => body.to_s }
86
89
  end
@@ -0,0 +1,112 @@
1
+ # Generated by specs/gen-runtime-admission.py from sdks/pine-computer/contract/runtime-admission.json. Do not edit; run `python3 specs/gen-runtime-admission.py`.
2
+ # runtime-admission source-sha256=45d8ef514610a60a8a04542e02a85e416a253a6863ab901e23ebcd830824bab2 body-sha256=90d7a582135e9031597be0de84399277363b844156617c448196bfa917783f7d
3
+
4
+ module PineSandbox
5
+ # @api private — when a new Computer runtime may replace the current one.
6
+ module RuntimeAdmission
7
+ # The caller fills {sandbox_id} and, for a wait, {waited} in message.
8
+ # refusal: the error a refuse raises (:retained SandboxRetainedError, :already_started ComputerAlreadyStartedError).
9
+ Decision = Data.define(:action, :message, :refusal)
10
+ # One row of the table; reason nil matches any reason. A message is the
11
+ # template with the runtime's reason and without it.
12
+ Row = Data.define(:state, :reason, :start, :recover, :start_message, :recover_message, :refusal)
13
+
14
+ REASON_ALIASES = { "CAPTURE_TIMEOUT" => "CaptureTimeout" }.freeze
15
+ START_REFUSED = [ "Start refused: Computer runtime {sandbox_id} hasn't been released (state {state}, reason {reason}); nothing was started",
16
+ "Start refused: Computer runtime {sandbox_id} hasn't been released (state {state}); nothing was started" ].freeze
17
+ START_REFUSED_RECOVER = [ "Start refused: Computer runtime {sandbox_id} hasn't been released (state {state}, reason {reason}); nothing was started; recover it with recover_computer, or Stop it and then Start",
18
+ "Start refused: Computer runtime {sandbox_id} hasn't been released (state {state}); nothing was started; recover it with recover_computer, or Stop it and then Start" ].freeze
19
+ START_REFUSED_RESUMABLE = [ "Start refused: Computer runtime {sandbox_id} hasn't been released (state {state}, reason {reason}); nothing was started; Resume it, or recover it with recover_computer, which discards its memory",
20
+ "Start refused: Computer runtime {sandbox_id} hasn't been released (state {state}); nothing was started; Resume it, or recover it with recover_computer, which discards its memory" ].freeze
21
+ START_ALREADY_STARTED = [ "Start refused: Computer runtime {sandbox_id} is already started (state {state}, reason {reason}); nothing was started",
22
+ "Start refused: Computer runtime {sandbox_id} is already started (state {state}); nothing was started" ].freeze
23
+ RECOVER_REFUSED = [ "Recover refused: Computer runtime {sandbox_id} has no recorded failure (state {state}, reason {reason}); nothing was released or started",
24
+ "Recover refused: Computer runtime {sandbox_id} has no recorded failure (state {state}); nothing was released or started" ].freeze
25
+ RECOVER_REFUSED_CAPTURE_UNRESOLVED = [ "Recover refused: the capture of Computer runtime {sandbox_id} hasn't resolved (state {state}, reason {reason}); nothing was released or started",
26
+ "Recover refused: the capture of Computer runtime {sandbox_id} hasn't resolved (state {state}); nothing was released or started" ].freeze
27
+ CURRENT_READ_TIMED_OUT = [ "The Computer's current runtime wasn't read within {waited} s; nothing was released or started",
28
+ "The Computer's current runtime wasn't read within {waited} s; nothing was released or started" ].freeze
29
+ RELEASE_WAIT_TIMED_OUT = [ "Computer runtime {sandbox_id} wasn't released after {waited} s (last state {state}, reason {reason}); nothing was started",
30
+ "Computer runtime {sandbox_id} wasn't released after {waited} s (last state {state}); nothing was started" ].freeze
31
+ READY_TIMED_OUT = [ "{new}Computer runtime {sandbox_id} wasn't {target} after {waited} s (last state {state}, reason {reason})",
32
+ "{new}Computer runtime {sandbox_id} wasn't {target} after {waited} s (last state {state})" ].freeze
33
+ RUNTIME_FAILED = [ "{new}Computer runtime {sandbox_id} reported state {state}, reason {reason} before it was {target}",
34
+ "{new}Computer runtime {sandbox_id} reported state {state} before it was {target}" ].freeze
35
+ NO_VERSION = [ "Recover refused: the server sent no version for Computer runtime {sandbox_id}; nothing was released or started",
36
+ "Recover refused: the server sent no version for Computer runtime {sandbox_id}; nothing was released or started" ].freeze
37
+ MESSAGES = {
38
+ start_refused: START_REFUSED,
39
+ start_refused_recover: START_REFUSED_RECOVER,
40
+ start_refused_resumable: START_REFUSED_RESUMABLE,
41
+ start_already_started: START_ALREADY_STARTED,
42
+ recover_refused: RECOVER_REFUSED,
43
+ recover_refused_capture_unresolved: RECOVER_REFUSED_CAPTURE_UNRESOLVED,
44
+ current_read_timed_out: CURRENT_READ_TIMED_OUT,
45
+ release_wait_timed_out: RELEASE_WAIT_TIMED_OUT,
46
+ ready_timed_out: READY_TIMED_OUT,
47
+ runtime_failed: RUNTIME_FAILED,
48
+ no_version: NO_VERSION
49
+ }.freeze
50
+ ABSENT = Row.new(nil, nil, :proceed, :proceed, nil, nil, :retained)
51
+ UNKNOWN = Row.new(nil, nil, :refuse, :refuse, START_REFUSED, RECOVER_REFUSED, :retained)
52
+ ROWS = [
53
+ Row.new(:terminated, "COMPUTE_RELEASED", :proceed, :proceed, nil, nil, :retained),
54
+ Row.new(:saving, nil, :wait, :wait, RELEASE_WAIT_TIMED_OUT, RELEASE_WAIT_TIMED_OUT, :retained),
55
+ Row.new(:stopping, nil, :wait, :wait, RELEASE_WAIT_TIMED_OUT, RELEASE_WAIT_TIMED_OUT, :retained),
56
+ Row.new(:failed, "CaptureTimeout", :refuse, :refuse, START_REFUSED, RECOVER_REFUSED_CAPTURE_UNRESOLVED, :retained),
57
+ Row.new(:failed, nil, :refuse, :release, START_REFUSED_RECOVER, RELEASE_WAIT_TIMED_OUT, :retained),
58
+ Row.new(:unavailable, "CaptureTimeout", :refuse, :refuse, START_REFUSED, RECOVER_REFUSED_CAPTURE_UNRESOLVED, :retained),
59
+ Row.new(:unavailable, nil, :refuse, :release, START_REFUSED_RESUMABLE, RELEASE_WAIT_TIMED_OUT, :retained),
60
+ Row.new(:save_failed, nil, :refuse, :release, START_REFUSED_RECOVER, RELEASE_WAIT_TIMED_OUT, :retained),
61
+ Row.new(:terminated, nil, :refuse, :release, START_REFUSED_RECOVER, RELEASE_WAIT_TIMED_OUT, :retained),
62
+ Row.new(:running, nil, :refuse, :refuse, START_ALREADY_STARTED, RECOVER_REFUSED, :already_started),
63
+ Row.new(:paused, nil, :refuse, :refuse, START_REFUSED, RECOVER_REFUSED, :retained),
64
+ Row.new(:pausing, nil, :refuse, :refuse, START_REFUSED, RECOVER_REFUSED, :retained),
65
+ Row.new(:resuming, nil, :refuse, :refuse, START_ALREADY_STARTED, RECOVER_REFUSED, :already_started),
66
+ Row.new(:pending, nil, :refuse, :refuse, START_ALREADY_STARTED, RECOVER_REFUSED, :already_started),
67
+ Row.new(:allocated, nil, :refuse, :refuse, START_ALREADY_STARTED, RECOVER_REFUSED, :already_started)
68
+ ].freeze
69
+ NEW_RUNTIME = {
70
+ running: :done,
71
+ pending: :wait,
72
+ allocated: :wait,
73
+ resuming: :wait,
74
+ failed: :fail,
75
+ terminated: :fail,
76
+ unavailable: :fail,
77
+ stopping: :wait,
78
+ saving: :wait,
79
+ save_failed: :wait,
80
+ pausing: :wait,
81
+ paused: :wait
82
+ }.freeze
83
+ private_constant :Row, :REASON_ALIASES, :START_REFUSED, :START_REFUSED_RECOVER, :START_REFUSED_RESUMABLE, :START_ALREADY_STARTED, :RECOVER_REFUSED, :RECOVER_REFUSED_CAPTURE_UNRESOLVED, :CURRENT_READ_TIMED_OUT, :RELEASE_WAIT_TIMED_OUT, :READY_TIMED_OUT, :RUNTIME_FAILED, :NO_VERSION, :ABSENT, :UNKNOWN, :ROWS,
84
+ :NEW_RUNTIME
85
+
86
+ # state: as the SDK reports it (:failed); nil when there is none (none bound, or a 404).
87
+ def self.decide(column, state, reason)
88
+ unless %i[start recover].include?(column)
89
+ raise ArgumentError, "column must be :start or :recover, not #{column.inspect}"
90
+ end
91
+
92
+ reason = nil if reason.to_s.empty?
93
+ row = state.nil? ? ABSENT : row_for(state.to_sym, REASON_ALIASES.fetch(reason, reason))
94
+ template = row.public_send(:"#{column}_message")
95
+ text = template && (reason ? template[0].gsub("{reason}") { reason } : template[1])
96
+ Decision.new(row.public_send(column), text&.gsub("{state}", state.to_s), row.refusal)
97
+ end
98
+
99
+ # The most specific row: this state and reason, else this state with any reason.
100
+ def self.row_for(state, reason)
101
+ ROWS.find { |r| r.state == state && !reason.nil? && r.reason == reason } ||
102
+ ROWS.find { |r| r.state == state && r.reason.nil? } || UNKNOWN
103
+ end
104
+ private_class_method :row_for
105
+
106
+ # What the SDK's wait does with the runtime it just created: :done, :wait or
107
+ # :fail (SandboxFailedError). Pause and Resume fail on the same states.
108
+ def self.decide_new_runtime(state)
109
+ NEW_RUNTIME.fetch(state&.to_sym, :wait)
110
+ end
111
+ end
112
+ end
@@ -1,6 +1,7 @@
1
1
  require "securerandom"
2
2
  require_relative "errors"
3
3
  require_relative "clock"
4
+ require_relative "runtime_admission"
4
5
 
5
6
  module PineSandbox
6
7
  # Lifecycle handle for a Computer sandbox, backed by the project-scoped
@@ -9,8 +10,6 @@ module PineSandbox
9
10
  # the coordinator host is derived separately from the Zone.
10
11
  # @api private
11
12
  class SandboxHandle
12
- READY = :running
13
- WAIT_FAILURE_STATES = %i[failed terminated unavailable].freeze
14
13
  LIVE = %i[running pending stopping].freeze
15
14
  DEFAULT_POLL_INTERVAL = 2
16
15
 
@@ -19,7 +18,8 @@ module PineSandbox
19
18
 
20
19
  # `clock` returns monotonic seconds and `sleeper` waits; both default to
21
20
  # the control plane's clock.
22
- def initialize(control_plane:, sandbox_id: nil, status: nil, clock: nil, sleeper: nil)
21
+ # status and reason: the create response's observation, when there is one.
22
+ def initialize(control_plane:, sandbox_id: nil, status: nil, reason: nil, clock: nil, sleeper: nil)
23
23
  id = sandbox_id
24
24
  raise ArgumentError, "sandbox_id required" if id.to_s.empty?
25
25
 
@@ -27,16 +27,18 @@ module PineSandbox
27
27
  @control_plane = control_plane
28
28
  @id = id.to_s
29
29
  @status = status
30
+ @reason = reason
30
31
  @clock = clock || -> { source.monotonic }
31
32
  @sleeper = sleeper || ->(seconds) { source.sleep(seconds) }
32
33
  end
33
34
 
34
35
  # Allocation may reuse Running from its create response. Memory resume must
35
36
  # discard that observation and wait for the controller's new completion.
36
- def wait_until_running(timeout:, interval: DEFAULT_POLL_INTERVAL)
37
- return self if @status == READY
37
+ # started: when the caller's ready_timeout began (errors report time waited since).
38
+ def wait_until_running(timeout:, interval: DEFAULT_POLL_INTERVAL, started: nil)
39
+ return self if RuntimeAdmission.decide_new_runtime(@status) == :done
38
40
 
39
- wait_until_state(:running, timeout: timeout, interval: interval)
41
+ wait_until_state(:running, timeout: timeout, interval: interval, started: started, new_runtime: true)
40
42
  end
41
43
 
42
44
  def pause(timeout: 360, interval: DEFAULT_POLL_INTERVAL)
@@ -64,25 +66,26 @@ module PineSandbox
64
66
 
65
67
  # Observe existing intent before admitting a new operation. No SDK memory
66
68
  # or saved operation cursor is needed to continue Stop from another backend.
69
+ # The wait bounds only the polling: false means the Stop was submitted (or
70
+ # the runtime was already shutting down), and a submit failure raises.
67
71
  def stop(wait_timeout: 390, interval: DEFAULT_POLL_INTERVAL)
68
- return false if wait_timeout <= 0
69
-
70
72
  deadline = @clock.call + wait_timeout
71
- info = @control_plane.get(@id, request_timeout: wait_timeout)
73
+ info = @control_plane.get(@id, request_timeout: submit_timeout(deadline))
72
74
  return true if released?(info)
73
75
  if info.status == :save_failed && !info.retryable
74
76
  raise StopSaveError.new(Error.new(info.message), retryable: false)
75
77
  end
76
78
  unless %i[saving stopping].include?(info.status)
77
79
  begin
78
- @control_plane.stop(@id, operation_id: SecureRandom.uuid, request_timeout: remaining(deadline))
80
+ @control_plane.stop(@id, operation_id: SecureRandom.uuid, request_timeout: submit_timeout(deadline))
79
81
  rescue PineSandbox::ConflictError
80
82
  # A concurrent caller may have admitted Stop first. Join only that
81
83
  # actual operation; a memory-transition conflict is still an error.
82
- info = @control_plane.get(@id, request_timeout: remaining(deadline))
84
+ info = @control_plane.get(@id, request_timeout: submit_timeout(deadline))
83
85
  raise unless %i[saving stopping].include?(info.status)
84
86
  end
85
87
  end
88
+ submitted = true
86
89
  loop do
87
90
  info = next_observation(info, deadline, interval)
88
91
  return true if released?(info)
@@ -93,27 +96,47 @@ module PineSandbox
93
96
  rescue PineSandbox::NotFoundError
94
97
  true
95
98
  rescue PineSandbox::TimeoutError
96
- raise if @clock.call < deadline
99
+ raise unless submitted && @clock.call >= deadline
97
100
 
98
101
  false
99
102
  end
100
103
 
101
- # Explicit saved-state recovery discards retained memory. It is allowed
102
- # only after a recorded failure and is fenced by the observed HTTP ETag.
103
- def release_failed_sandbox(info, wait_timeout: 90, interval: DEFAULT_POLL_INTERVAL)
104
- deadline = @clock.call + wait_timeout
105
- unless info.status == :stopping
106
- # Accepts CAPTURE_TIMEOUT as well as CaptureTimeout to unify on SNAKE_CASE while staying backward compatible.
107
- unless %i[save_failed unavailable failed terminated].include?(info.status) && !%w[CAPTURE_TIMEOUT CaptureTimeout].include?(info.reason)
108
- raise PineSandbox::ConflictError.new(status: 409, error_message: "The Computer has no recorded failure; use Stop or Resume")
104
+ # Applies the admission table's column (:start or :recover) to the current
105
+ # runtime `info` (nil: none) and to each new observation while it says wait,
106
+ # until `deadline` (monotonic seconds). A release is a DELETE fenced by the
107
+ # observed ETag, which discards retained memory.
108
+ def admit(column, info, started:, deadline:, interval: DEFAULT_POLL_INTERVAL)
109
+ released = nil
110
+ loop do
111
+ decision = RuntimeAdmission.decide(column, info&.status, info&.reason)
112
+ case decision.action
113
+ when :proceed then return self
114
+ when :refuse
115
+ refusal = decision.refusal == :already_started ? ComputerAlreadyStartedError : SandboxRetainedError
116
+ raise refusal.new(sandbox_id: @id, state: info.status, reason: info.reason,
117
+ message: PineSandbox.runtime_message(decision.message, sandbox_id: @id))
118
+ when :release
119
+ # Release each observed version once; the wait below sees it go.
120
+ unless released && info.etag == released
121
+ raise Error, PineSandbox.runtime_message(:no_version, sandbox_id: @id) if info.etag.to_s.empty?
122
+ @control_plane.destroy(@id, if_match: info.etag, request_timeout: remaining(deadline))
123
+ released = info.etag
124
+ end
125
+ end
126
+ info = begin
127
+ next_observation(info, deadline, interval)
128
+ rescue PineSandbox::NotFoundError
129
+ nil
109
130
  end
110
- raise PineSandbox::Error, "Server did not supply a conditional release version" if info.etag.to_s.empty?
111
- @control_plane.destroy(@id, if_match: info.etag, request_timeout: remaining(deadline))
112
131
  end
113
- wait_until_released(info, deadline, interval)
114
132
  rescue PineSandbox::TimeoutError
115
133
  raise if @clock.call < deadline
116
- false
134
+
135
+ waited = @clock.call - started
136
+ text = PineSandbox.runtime_message(RuntimeAdmission.decide(column, info.status, info.reason).message,
137
+ sandbox_id: @id, waited: waited)
138
+ raise ReadyTimeoutError.new(text, sandbox_id: @id, last_state: info.status, last_reason: info.reason,
139
+ waited: waited)
117
140
  end
118
141
 
119
142
  # Delete, then wait for the sandbox record to disappear. This confirms
@@ -190,52 +213,60 @@ module PineSandbox
190
213
  timeout
191
214
  end
192
215
 
216
+ def submit_timeout(deadline)
217
+ [deadline - @clock.call, @control_plane.request_timeout].max
218
+ end
219
+
193
220
  def released?(info)
194
- info.status == :terminated && info.reason == "COMPUTE_RELEASED"
221
+ !info.status.nil? && RuntimeAdmission.decide(:start, info.status, info.reason).action == :proceed
195
222
  end
196
223
 
197
224
  def transition_memory(operation, target, timeout:, interval:)
198
225
  raise ArgumentError, "timeout must be positive" unless timeout.positive?
199
226
 
200
- deadline = @clock.call + timeout
227
+ started = @clock.call
228
+ deadline = started + timeout
201
229
  accepted = @control_plane.public_send(operation, @id, request_timeout: timeout)
202
- @status = nil
230
+ @status = @reason = nil
203
231
  unless accepted
204
232
  # Older Docker servers answer 409 for an already completed transition.
205
233
  remaining = deadline - @clock.call
206
- raise PineSandbox::ReadyTimeoutError, "Computer #{@id} #{operation} exceeded its deadline" if remaining <= 0
234
+ raise ready_timeout(target, started, new_runtime: false) if remaining <= 0
207
235
  return self if refresh_status(request_timeout: remaining) == target
208
236
 
209
237
  raise PineSandbox::ConflictError.new(status: 409, error_message: "Computer #{@id} cannot #{operation} in its current state")
210
238
  end
211
- wait_until_state(target, timeout: deadline - @clock.call, interval: interval)
239
+ wait_until_state(target, timeout: deadline - @clock.call, interval: interval, started: started, new_runtime: false)
212
240
  end
213
241
 
214
- def wait_until_state(target, timeout:, interval:)
242
+ def wait_until_state(target, timeout:, interval:, started:, new_runtime:)
243
+ started ||= @clock.call
215
244
  deadline = @clock.call + timeout
216
245
  info = nil
217
246
  loop do
218
- remaining = deadline - @clock.call
219
- if remaining <= 0
220
- raise PineSandbox::ReadyTimeoutError, "Computer #{@id} did not reach #{target} before the deadline (last state #{@status.inspect})"
221
- end
247
+ raise ready_timeout(target, started, new_runtime: new_runtime) if deadline - @clock.call <= 0
222
248
  begin
223
249
  info = next_observation(info, deadline, interval)
224
250
  state = @status = info.status
251
+ @reason = info.reason
225
252
  rescue PineSandbox::TimeoutError => error
226
253
  raise error if @clock.call < deadline
227
254
 
228
- raise PineSandbox::ReadyTimeoutError, "Computer #{@id} did not reach #{target} before the deadline"
255
+ raise ready_timeout(target, started, new_runtime: new_runtime)
229
256
  end
230
- return self if state == target
231
- if WAIT_FAILURE_STATES.include?(state)
232
- raise PineSandbox::SandboxFailedError.new(
233
- "Computer sandbox #{@id} reported #{state.inspect} before reaching #{target}", sandbox_id: @id, state: state
234
- )
257
+ return self if new_runtime ? RuntimeAdmission.decide_new_runtime(state) == :done : state == target
258
+ if RuntimeAdmission.decide_new_runtime(state) == :fail
259
+ raise PineSandbox::SandboxFailedError.new(sandbox_id: @id, state: state, reason: @reason,
260
+ target: target, new_runtime: new_runtime)
235
261
  end
236
262
  end
237
263
  end
238
264
 
265
+ def ready_timeout(target, started, new_runtime:)
266
+ ReadyTimeoutError.new(sandbox_id: @id, last_state: @status, last_reason: @reason,
267
+ waited: @clock.call - started, target: target, new_runtime: new_runtime)
268
+ end
269
+
239
270
  def refresh_status(request_timeout: nil)
240
271
  @status = if request_timeout
241
272
  @control_plane.get(@id, request_timeout: request_timeout).status
@@ -454,8 +454,12 @@ module PineSandbox
454
454
  #
455
455
  # `actor_type:` is REQUIRED; the Computer returns 400
456
456
  # /errors/actor-type-required when missing.
457
+ #
458
+ # `idle_paused:` is deprecated: to give the person more time, pass a later
459
+ # `idle_deadline:`. A paused hold doesn't keep the Computer running.
457
460
  def update_control(controller: nil, idle_paused: nil, idle_deadline: nil,
458
461
  actor_type:, if_match:, force: false, idempotency_key: nil)
462
+ PineSandbox.deprecated_name("Session#update_control(idle_paused:)", "idle_deadline:") unless idle_paused.nil?
459
463
  body = { actor_type: actor_type }
460
464
  body[:controller] = controller unless controller.nil?
461
465
  body[:idle_paused] = idle_paused unless idle_paused.nil?
@@ -0,0 +1,32 @@
1
+ # Generated by specs/gen-signal-actions.py from sdks/pine-computer/contract/signal-actions.json. Do not edit; run `python3 specs/gen-signal-actions.py`.
2
+ # signal-actions source-sha256=6b1fd0c880882510913e27b38e9169567f64c4d7193e7acc158a4da906ff8c20 body-sha256=8b26db77552ce1578c3677792aab7c0519ef534aee4668e65e183e5951857fa2
3
+
4
+ module PineSandbox
5
+ # @api private — the terminal_reason values of a turn's result: how a turn or a
6
+ # skill-author run ended.
7
+ module TerminalReason
8
+ COMPLETED = "completed".freeze
9
+ NEEDS_INPUT = "needs_input".freeze
10
+ BUDGET = "budget".freeze
11
+ CANCELED = "canceled".freeze
12
+ TIMEOUT = "timeout".freeze
13
+ INCOMPLETE = "incomplete".freeze
14
+ ERROR = "error".freeze
15
+ EXECUTOR_PANIC = "executor_panic".freeze
16
+ COORDINATOR_RESTARTED = "coordinator_restarted".freeze
17
+ STORAGE_EXHAUSTED = "storage_exhausted".freeze
18
+ SPEND_LIMIT_REACHED = "spend_limit_reached".freeze
19
+ OUTPUT_INVALID = "output_invalid".freeze
20
+ DRAFT_REGISTERED = "draft_registered".freeze
21
+ CLARIFICATION_REQUESTED = "clarification_requested".freeze
22
+ NOT_REUSABLE = "not_reusable".freeze
23
+ REGISTRATION_FAILED = "registration_failed".freeze
24
+ FAILED = "failed".freeze
25
+ TERMINAL_MISSING = "terminal_missing".freeze
26
+
27
+ # The skill-author run values the blocking learn and teach calls report as a failed run.
28
+ AUTHOR_FAILED = [ CANCELED, STORAGE_EXHAUSTED, REGISTRATION_FAILED, FAILED ].freeze
29
+ # The skill-author run values that mean the Computer's services restarted during the run.
30
+ AUTHOR_INTERRUPTED = [ COORDINATOR_RESTARTED ].freeze
31
+ end
32
+ end
@@ -0,0 +1,22 @@
1
+ module PineSandbox
2
+ # The client's network timeouts, in seconds. `connect` bounds opening one
3
+ # connection: the TCP connect, then the TLS handshake. `request` bounds one request that
4
+ # has no budget of its own; a read the Computer holds open, such as a turn
5
+ # wait, gets its hold on top. A connection that could not be opened sent
6
+ # nothing, so the request is tried again within the retry policy.
7
+ Timeouts = Struct.new(:connect, :request) do
8
+ def initialize(connect: Timeouts::DEFAULT_CONNECT, request: Timeouts::DEFAULT_REQUEST)
9
+ { connect: connect, request: request }.each do |name, value|
10
+ next if value.is_a?(Numeric) && value.positive? && value.finite?
11
+
12
+ raise ArgumentError, "#{name}_timeout must be a positive number of seconds, got #{value.inspect}"
13
+ end
14
+ super(connect, request)
15
+ freeze
16
+ end
17
+ end
18
+
19
+ Timeouts::DEFAULT_CONNECT = 10
20
+ Timeouts::DEFAULT_REQUEST = 30
21
+ Timeouts::DEFAULT = Timeouts.new
22
+ end