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.
@@ -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,
@@ -38,6 +39,8 @@ module PineSandbox
38
39
  "/errors/no-desktop-stream" => false,
39
40
  "/errors/desktop-unavailable" => false,
40
41
  "/errors/skills-unavailable" => false,
42
+ "/errors/artifacts-unavailable" => true,
43
+ "/errors/artifacts-not-configured" => false,
41
44
  "/errors/secret-in-skill" => false,
42
45
  "/errors/skill-author-failed" => true,
43
46
  "/errors/author-in-flight" => true,
@@ -54,6 +57,8 @@ module PineSandbox
54
57
  "/errors/no-active-turn" => false,
55
58
  "/errors/no-pending-request" => false,
56
59
  "/errors/stale-turn" => false,
60
+ "/errors/turn-not-found" => false,
61
+ "/errors/stale-task" => false,
57
62
  "/errors/task-control-failed" => true,
58
63
  "/errors/task-not-found" => false,
59
64
  "/errors/task-not-ready" => true,
@@ -84,6 +89,7 @@ module PineSandbox
84
89
  "/errors/computer-stopped" => false,
85
90
  "/errors/stop-failed" => false,
86
91
  "/errors/history-expired" => false,
92
+ "/errors/events-unavailable" => true,
87
93
  "/errors/storage-exhausted" => false
88
94
  }.freeze
89
95
 
@@ -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
@@ -191,6 +240,18 @@ module PineSandbox
191
240
  class HandoffExpired < GoneError; end
192
241
  class HandoffPersistenceFailed < ServerError; end
193
242
 
243
+ # A Computer's artifacts have no file at #path (the path you passed,
244
+ # relative to the Computer's artifacts). A NotFoundError, so tier rescues
245
+ # keep catching it.
246
+ class ArtifactNotFoundError < NotFoundError
247
+ attr_reader :path
248
+
249
+ def initialize(path:, **fields)
250
+ @path = path
251
+ super(**fields)
252
+ end
253
+ end
254
+
194
255
  # Problem `type` → its typed error; anything else falls back to the status tier.
195
256
  PROBLEM_TYPE_CLASSES = {
196
257
  "/errors/control-not-held" => ControlNotHeld,
@@ -205,6 +266,22 @@ module PineSandbox
205
266
  "/errors/empty-patch" => EmptyPatch,
206
267
  "/errors/malformed-json" => MalformedJSON,
207
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,
208
285
  "/errors/desktop-bind-failed" => DesktopBindFailed,
209
286
  "/errors/handoff-not-found" => HandoffNotFound,
210
287
  "/errors/handoff-unavailable" => HandoffUnavailable,
@@ -219,24 +296,86 @@ module PineSandbox
219
296
 
220
297
  def self.problem_class_for(problem_type) = PROBLEM_TYPE_CLASSES[problem_type]
221
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
+
222
305
  # Failures with no HTTP response, or a timeout status (408/504) without a
223
306
  # problem body. #retry_after is the response's Retry-After in seconds, when
224
307
  # a timeout status set one.
225
308
  class TimeoutError < Error
226
309
  attr_accessor :retry_after
227
310
  end
228
- class ConnectionError < Error; end
229
- 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
230
315
 
231
- # The Computer reported failed, terminated or unavailable before the
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
329
+
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
232
353
  # lifecycle operation finished.
233
354
  class SandboxFailedError < Error
234
- attr_reader :sandbox_id, :state
355
+ attr_reader :sandbox_id, :state, :reason
235
356
 
236
- 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)
237
358
  @sandbox_id = sandbox_id
238
359
  @state = state
239
- 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))
364
+ end
365
+ end
366
+
367
+ # The Computer's artifacts take up more than its storage limit, so an
368
+ # upload or a copy into them is refused before anything is sent. Delete
369
+ # files to make room. #used_bytes and #limit_bytes are as Pine counted
370
+ # them when it issued the storage token.
371
+ class ArtifactStorageFullError < Error
372
+ attr_reader :used_bytes, :limit_bytes
373
+
374
+ def initialize(used_bytes:, limit_bytes:)
375
+ @used_bytes = used_bytes
376
+ @limit_bytes = limit_bytes
377
+ super("the Computer's artifacts use #{used_bytes} bytes, more than their limit of #{limit_bytes}; " \
378
+ "delete files before writing more")
240
379
  end
241
380
  end
242
381
 
@@ -277,7 +416,9 @@ module PineSandbox
277
416
  def retryable? = @retryable.nil? ? (save_error.respond_to?(:retryable?) && save_error.retryable?) : @retryable
278
417
  end
279
418
 
280
- # 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.
281
422
  # `#status` is the HTTP status when one is available; `#cause` is the
282
423
  # underlying ApiError, so callers can inspect the raw response if needed.
283
424
  class BindError < Error
@@ -290,14 +431,29 @@ module PineSandbox
290
431
  end
291
432
  end
292
433
 
293
- # 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.
294
436
  # Preserve the BindError superclass for integrations already rescuing Start conflicts.
295
437
  class SandboxRetainedError < BindError
296
- attr_reader :sandbox_id, :state
438
+ attr_reader :sandbox_id, :state, :reason
439
+
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
297
452
 
298
- def initialize(sandbox_id:, state:)
299
- @sandbox_id, @state = sandbox_id, state
300
- super("Computer hasn't stopped (Computer sandbox #{sandbox_id}, state #{state}); Stop it or Resume retained memory before Start")
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))
301
457
  end
302
458
  end
303
459
 
@@ -0,0 +1,40 @@
1
+ require "time"
2
+
3
+ module PineSandbox
4
+ module Models
5
+ # One file in a Computer's artifacts. Returned by
6
+ # {PineSandbox::Artifacts#list}, #upload and #copy. `path` is relative to
7
+ # the Computer's artifacts ("research/q3.csv"); `note` is the note the file
8
+ # was uploaded with, if any.
9
+ ArtifactFile = Struct.new(
10
+ :path,
11
+ :size,
12
+ :updated_at,
13
+ :content_type,
14
+ :note,
15
+ keyword_init: true
16
+ ) do
17
+ # From a storage object, whose name is `prefix` followed by the path.
18
+ def self.from_object(object, prefix:)
19
+ new(
20
+ path: object["name"].to_s.delete_prefix(prefix),
21
+ # Storage sends the size as a decimal string.
22
+ size: object["size"].nil? ? nil : Integer(object["size"].to_s, 10),
23
+ updated_at: object["updated"] && Time.parse(object["updated"]),
24
+ content_type: object["contentType"],
25
+ note: object.dig("metadata", "pine-note")
26
+ )
27
+ end
28
+ end
29
+
30
+ # One page of {PineSandbox::Artifacts#list}: the files, the folders
31
+ # directly below the listed prefix (each ending in "/"; none when listing
32
+ # recursively), and the token for the next page (nil on the last one).
33
+ ArtifactPage = Struct.new(
34
+ :files,
35
+ :folders,
36
+ :next_page_token,
37
+ keyword_init: true
38
+ )
39
+ end
40
+ end
@@ -12,12 +12,15 @@ module PineSandbox
12
12
  :token,
13
13
  :session_dir,
14
14
  :browser,
15
- :blind,
15
+ :artifact_access,
16
16
  :created_at,
17
17
  :last_active_at,
18
18
  keyword_init: true
19
19
  ) do
20
- def self.from_payload(payload)
20
+ # `artifact_access_known` is false for a session whose artifact access
21
+ # only the Computer knows (Computer#adopt_session): #artifact_access is
22
+ # then nil.
23
+ def self.from_payload(payload, artifact_access_known: true)
21
24
  return nil unless payload
22
25
  browser_payload = payload["browser"]
23
26
  new(
@@ -26,7 +29,8 @@ module PineSandbox
26
29
  token: payload["token"],
27
30
  session_dir: payload["session_dir"],
28
31
  browser: browser_payload && Browser.from_payload(browser_payload),
29
- blind: payload.fetch("blind", false),
32
+ # An older Computer doesn't report it; its sessions have no access.
33
+ artifact_access: artifact_access_known ? payload.fetch("artifact_access", "none") : nil,
30
34
  created_at: payload["created_at"] && Time.parse(payload["created_at"]),
31
35
  last_active_at: payload["last_active_at"] && Time.parse(payload["last_active_at"])
32
36
  )
@@ -35,7 +35,9 @@ module PineSandbox
35
35
  ["cancelAuthorRun", "POST", "/v2/sessions/{name}/skills/author/{author_id}/cancel", :computer, false, false],
36
36
  ["captureCheckpoint", "POST", "/v1/coord/capture", :computer, false, false],
37
37
  ["computerUse", "POST", "/v1/sessions/{name}/computer-use", :computer, false, false],
38
+ ["createArtifactLink", "POST", "/v1/artifacts/links", :computer, false, false],
38
39
  ["createComputer", "POST", "/computer-sandboxes", :control, true, false],
40
+ ["createComputerArtifactToken", "POST", "/v1/computers/{computer_id}/artifacts/token", :control, false, false],
39
41
  ["createDiagnostic", "POST", "/v1/diagnostics", :control, true, true],
40
42
  ["createSession", "POST", "/sessions", :computer, false, false],
41
43
  ["deactivateSkill", "POST", "/v1/skills/{name}/deactivate", :computer, false, false],
@@ -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