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,7 +1,6 @@
1
1
  require "faraday"
2
2
  require "json"
3
3
  require "securerandom"
4
- require "tempfile"
5
4
  require "uri"
6
5
  require_relative "../clock"
7
6
  require_relative "../errors"
@@ -11,6 +10,10 @@ require_relative "../control_events"
11
10
  require_relative "../sse_frame_parser"
12
11
  require_relative "../exec_stream_parser"
13
12
  require_relative "../response_handler"
13
+ require_relative "../streamed_read"
14
+ require_relative "../version"
15
+ require_relative "../timeouts"
16
+ require_relative "connect_aware_net_http"
14
17
 
15
18
  module PineSandbox
16
19
  module Adapters
@@ -29,17 +32,12 @@ module PineSandbox
29
32
  #
30
33
  # A request that is replay-safe in the public operation table is sent
31
34
  # again after a transport fault (Operations, RetryPolicy); any other is
32
- # sent once. A 401 for a Computer token raises TokenRejectedError; a 401
35
+ # sent once, unless its connection could not be opened and so nothing was
36
+ # sent. A 401 for a Computer token raises TokenRejectedError; a 401
33
37
  # for a session token is the plain UnauthorizedError.
34
38
  class CoordinatorAdapter
35
39
  include PineSandbox::ResponseHandler
36
40
 
37
- DEFAULT_HTTP_TIMEOUT = 30
38
- DEFAULT_OPEN_TIMEOUT = 5
39
- # A non-2xx stream answer keeps this much of its body for the error.
40
- STREAM_ERROR_BODY_CAP = 64 * 1024
41
- # Chunk size for passing on a body that was spooled to a temp file.
42
- SPOOL_READ_SIZE = 64 * 1024
43
41
  # An event stream silent this long (three missed keepalives) is reopened.
44
42
  STREAM_IDLE_TIMEOUT = 60
45
43
 
@@ -49,13 +47,15 @@ module PineSandbox
49
47
  # selects the role. `zone` is a PineSandbox::Zone.
50
48
  # `host` is the Computer sandbox's data-plane host `<sandbox_id>.computer.<zone>`
51
49
  # (scheme-less). `scheme` is http for a .localhost zone (local-dev loop),
52
- # https otherwise. `clock` paces retries and reconnects.
53
- attr_reader :sandbox_id, :host, :scheme, :clock
50
+ # https otherwise. `clock` paces retries and reconnects. `timeouts` is the
51
+ # client's Timeouts.
52
+ attr_reader :sandbox_id, :host, :scheme, :clock, :timeouts
54
53
 
55
54
  # discovery_token is the Computer token that reads the capability
56
55
  # manifest when a request's own token, such as a session's, cannot. An
57
56
  # adopted binding passes it; #bind records the one it issues.
58
- def initialize(zone:, sandbox_id: nil, discovery_token: nil, clock: PineSandbox::SYSTEM_CLOCK)
57
+ def initialize(zone:, sandbox_id: nil, discovery_token: nil, clock: PineSandbox::SYSTEM_CLOCK,
58
+ timeouts: Timeouts::DEFAULT)
59
59
  @sandbox_id = sandbox_id
60
60
  raise ArgumentError, "sandbox_id required" if @sandbox_id.to_s.empty?
61
61
 
@@ -63,6 +63,7 @@ module PineSandbox
63
63
  @scheme = zone.http_scheme # http for a .localhost zone (local-dev loop), https otherwise
64
64
  @discovery_token = discovery_token
65
65
  @clock = clock
66
+ @timeouts = timeouts
66
67
  # This adapter's own connections dial as the zone says (#connection);
67
68
  # base_url stays the public host, since a delegated connection hands
68
69
  # it to a browser.
@@ -192,15 +193,23 @@ module PineSandbox
192
193
  true
193
194
  end
194
195
 
195
- def create_session(token:, name: nil, label: nil, browser: false, blind: false)
196
+ # POST /v1/artifacts/links — a public link this running Computer serves
197
+ # to one of its artifacts (ct_ only). Returns { "url", "expires_at"? }.
198
+ def create_artifact_link(token:, path:, expires_in_seconds: nil)
199
+ body = { path: path }
200
+ body[:expires_in_seconds] = expires_in_seconds if expires_in_seconds
201
+ post("v1/artifacts/links", token: token, json: body).body
202
+ end
203
+
204
+ def create_session(token:, name: nil, label: nil, artifact_access: nil)
196
205
  # Omit :name when blank so the coordinator mints a friendly name; only
197
- # send :label when the caller set one. Name stays first so the on-wire
198
- # body order is stable.
206
+ # send :label and :artifact_access when the caller set them. Name stays
207
+ # first so the on-wire body order is stable. Every session has a
208
+ # browser window, so the request names none.
199
209
  body = {}
200
210
  body[:name] = name unless name.nil? || name.to_s.empty?
201
- body[:browser] = browser
202
211
  body[:label] = label unless label.nil? || label.to_s.empty?
203
- body[:blind] = true if blind
212
+ body[:artifact_access] = artifact_access if artifact_access
204
213
  post("sessions", token: token, json: body)
205
214
  .body
206
215
  .fetch("session")
@@ -509,7 +518,7 @@ module PineSandbox
509
518
  event.data["exitCode"] || event.data[:exitCode]
510
519
  exit_code = raw unless raw.nil?
511
520
  end
512
- pass_to_block(block, event) if block
521
+ StreamedRead.pass(block, event) if block
513
522
  end
514
523
  # Clamp the HTTP timeout above timeout_ms so the client waits for
515
524
  # the server's own timeout to fire an execution_complete event
@@ -518,34 +527,43 @@ module PineSandbox
518
527
  # no timeout at all.
519
528
  http_timeout = timeout_ms ? ((timeout_ms / 1000.0).ceil + 5) : 60
520
529
  error_body = +""
521
- with_transport_norm("POST", "sessions/#{escape(name)}/exec") do
522
- response = connection.post(route_path("sessions/#{escape(name)}/exec")) do |req|
523
- apply_token(req, token)
524
- req.headers["Content-Type"] = "application/json"
525
- req.headers["Accept"] = "text/event-stream"
526
- req.body = body.to_json
527
- req.options.on_data = proc do |chunk, _received, env|
528
- if env.nil?
529
- # faraday-net_http before 3.0 passes no env, so the status is
530
- # known only at the end: parse the chunk and keep it in case
531
- # the answer is an error.
532
- parser.parse(chunk)
533
- keep_error_body(error_body, chunk)
534
- elsif env.status.to_i.between?(200, 299)
535
- parser.parse(chunk)
536
- else
537
- keep_error_body(error_body, chunk)
530
+ attempt = 0
531
+ begin
532
+ attempt += 1
533
+ with_transport_norm("POST", "sessions/#{escape(name)}/exec") do
534
+ response = connection.post(route_path("sessions/#{escape(name)}/exec")) do |req|
535
+ apply_token(req, token)
536
+ req.headers["Content-Type"] = "application/json"
537
+ req.headers["Accept"] = "text/event-stream"
538
+ req.body = body.to_json
539
+ req.options.on_data = proc do |chunk, _received, env|
540
+ if env.nil?
541
+ # faraday-net_http before 3.0 passes no env, so the status is
542
+ # known only at the end: parse the chunk and keep it in case
543
+ # the answer is an error.
544
+ parser.parse(chunk)
545
+ StreamedRead.keep_error_body(error_body, chunk)
546
+ elsif env.status.to_i.between?(200, 299)
547
+ parser.parse(chunk)
548
+ else
549
+ StreamedRead.keep_error_body(error_body, chunk)
550
+ end
538
551
  end
552
+ req.options.timeout = http_timeout
553
+ end
554
+ # Non-2xx (e.g. 409 terminal_lost) is a problem+json body, not a
555
+ # stream; raise it so callers get ConflictError (→ recreate_terminal!)
556
+ # instead of a silent empty ExecResult.
557
+ unless response.success?
558
+ response.env.body = error_body if response.body.to_s.empty?
559
+ ensure_success!(response, token: token)
539
560
  end
540
- req.options.timeout = http_timeout
541
- end
542
- # Non-2xx (e.g. 409 terminal_lost) is a problem+json body, not a
543
- # stream; raise it so callers get ConflictError (→ recreate_terminal!)
544
- # instead of a silent empty ExecResult.
545
- unless response.success?
546
- response.env.body = error_body if response.body.to_s.empty?
547
- ensure_success!(response, token: token)
548
561
  end
562
+ rescue PineSandbox::ConnectionError => e
563
+ raise unless not_sent?(e) && attempt < RetryPolicy::TRANSIENT_ATTEMPTS
564
+
565
+ @clock.sleep(RetryPolicy.transient_backoff(attempt, @clock))
566
+ retry
549
567
  end
550
568
  parser.finish
551
569
  # execd's `execution_complete` frame does NOT carry exit_code on
@@ -580,14 +598,16 @@ module PineSandbox
580
598
 
581
599
  # idempotency_key names this submission: a run with the same key returns
582
600
  # the turn that key admitted instead of starting another.
583
- def agent_run(token:, name:, goal:, context: nil, skills: nil, constraints: nil, secrets: nil, idempotency_key: nil)
601
+ # `timeout` (seconds), when given, bounds each send in place of the request timeout.
602
+ def agent_run(token:, name:, goal:, context: nil, skills: nil, constraints: nil, secrets: nil, idempotency_key: nil,
603
+ timeout: nil, reached: nil)
584
604
  body = { goal: goal }
585
605
  body[:context] = context unless context.nil?
586
606
  body[:skills] = skills unless skills.nil?
587
607
  body[:constraints] = constraints unless constraints.nil?
588
608
  body[:secrets] = secrets unless secrets.nil?
589
609
  post("v2/sessions/#{escape(name)}/agent/run", token: token, json: body,
590
- headers: { "Idempotency-Key" => idempotency_key }).body
610
+ headers: { "Idempotency-Key" => idempotency_key }, timeout: timeout, reached: reached).body
591
611
  end
592
612
 
593
613
  def agent_steer(token:, name:, turn_id:, text:, secrets: nil)
@@ -596,14 +616,14 @@ module PineSandbox
596
616
  post("v2/sessions/#{escape(name)}/agent/steer", token: token, json: body).body
597
617
  end
598
618
 
599
- def agent_answer(token:, name:, turn_id:, answer:, secrets: nil)
619
+ def agent_answer(token:, name:, turn_id:, answer:, secrets: nil, timeout: nil)
600
620
  body = { turn_id: turn_id, answer: answer }
601
621
  body[:secrets] = secrets unless secrets.nil?
602
- post("v2/sessions/#{escape(name)}/agent/answer", token: token, json: body).body
622
+ post("v2/sessions/#{escape(name)}/agent/answer", token: token, json: body, timeout: timeout).body
603
623
  end
604
624
 
605
- def agent_cancel(token:, name:, turn_id:)
606
- post("v2/sessions/#{escape(name)}/agent/cancel", token: token, json: { turn_id: turn_id }).body
625
+ def agent_cancel(token:, name:, turn_id:, timeout: nil)
626
+ post("v2/sessions/#{escape(name)}/agent/cancel", token: token, json: { turn_id: turn_id }, timeout: timeout).body
607
627
  end
608
628
 
609
629
  def agent_reset(token:, name:, expected_task_id:)
@@ -620,7 +640,7 @@ module PineSandbox
620
640
  # wait_seconds while the turn runs, so the read timeout allows for it.
621
641
  def agent_turn(token:, name:, turn_id:, wait_seconds: 0)
622
642
  path = "v2/sessions/#{escape(name)}/agent/turns/#{escape(turn_id)}?wait_seconds=#{Integer(wait_seconds)}"
623
- request(:get, path, token: token, timeout: DEFAULT_HTTP_TIMEOUT + wait_seconds).body
643
+ request(:get, path, token: token, timeout: @timeouts.request + wait_seconds).body
624
644
  end
625
645
 
626
646
  # Public history: the retained turns and cursor-addressed activity pages.
@@ -880,11 +900,22 @@ module PineSandbox
880
900
 
881
901
  # Opens one event-stream GET and yields each SSE frame as it arrives.
882
902
  # A transport fault raises the raw Faraday error so the caller decides
883
- # whether to normalize it or reconnect; a non-2xx raises its typed error
884
- # (keeping a bounded prefix of the body, so a problem keeps its type and
885
- # extensions). Returns the response.
903
+ # whether to normalize it or reconnect; a non-2xx raises its typed error.
904
+ # Returns the response.
886
905
  def open_sse(path, token:, last_event_id:)
887
906
  parser = ::PineSandbox::SseFrameParser.new
907
+ response = open_event_stream(path, token: token, last_event_id: last_event_id) do |chunk|
908
+ parser.feed(chunk) { |frame| yield frame }
909
+ end
910
+ parser.finish
911
+ response
912
+ end
913
+
914
+ # Opens one event-stream GET and yields its bytes as they arrive. A
915
+ # transport fault raises the raw Faraday error; a non-2xx raises its
916
+ # typed error (keeping a bounded prefix of the body, so a problem keeps
917
+ # its type and extensions). Returns the response.
918
+ def open_event_stream(path, token:, last_event_id:)
888
919
  error_body = +""
889
920
  response = streaming_connection.get(route_path(path)) do |req|
890
921
  apply_token(req, token)
@@ -893,18 +924,17 @@ module PineSandbox
893
924
  req.options.on_data = proc do |chunk, _bytes, env|
894
925
  if env.nil?
895
926
  # faraday-net_http before 3.0 passes no env, so the status is
896
- # known only at the end: parse the chunk and keep it in case the
897
- # answer is an error.
898
- parser.feed(chunk) { |frame| yield frame }
899
- keep_error_body(error_body, chunk)
927
+ # known only at the end: pass the chunk on and keep it in case
928
+ # the answer is an error.
929
+ yield chunk
930
+ StreamedRead.keep_error_body(error_body, chunk)
900
931
  elsif env.status.to_i.between?(200, 299)
901
- parser.feed(chunk) { |frame| yield frame }
932
+ yield chunk
902
933
  else
903
- keep_error_body(error_body, chunk)
934
+ StreamedRead.keep_error_body(error_body, chunk)
904
935
  end
905
936
  end
906
937
  end
907
- parser.finish
908
938
  unless response.success?
909
939
  response.env.body = error_body if response.body.to_s.empty?
910
940
  ensure_success!(response, token: token)
@@ -912,28 +942,27 @@ module PineSandbox
912
942
  response
913
943
  end
914
944
 
915
- # Raised through Faraday's read loop in place of an exception from the
916
- # caller's block, so the block's own error is never mistaken for a
917
- # dropped connection.
918
- class BlockError < StandardError
919
- attr_reader :error
920
-
921
- def initialize(error)
922
- @error = error
923
- super(error.message)
945
+ # Passes one connection of an event stream to the block byte for byte,
946
+ # keepalives and ids included, for a server that relays it to its own
947
+ # client. An error answer raises the typed error every other read
948
+ # raises, and a transport fault raises its normalized error. Only a 2xx
949
+ # body reaches the block, except on faraday-net_http before 3.0: it
950
+ # learns the status after the body, and a live stream can't be held
951
+ # back until then, so there an error answer's body reaches the block
952
+ # before its error is raised.
953
+ def stream_event_bytes(path, token:, last_event_id: nil, &block)
954
+ with_transport_norm("GET", path) do
955
+ open_event_stream(path, token: token, last_event_id: last_event_id) do |chunk|
956
+ StreamedRead.pass(block, chunk)
957
+ end
924
958
  end
959
+ nil
960
+ rescue BlockError => e
961
+ raise e.error
925
962
  end
926
- private_constant :BlockError
927
963
 
928
- # Runs the caller's block on one piece of a streamed answer from inside
929
- # Faraday's read loop, which would turn an IOError or EPIPE from the
930
- # block into a dropped connection. The streaming method raises the
931
- # block's error again as it was.
932
- def pass_to_block(block, value)
933
- block.call(value)
934
- rescue StandardError => e
935
- raise BlockError.new(e)
936
- end
964
+ BlockError = StreamedRead::BlockError
965
+ private_constant :BlockError
937
966
 
938
967
  # The resuming event-stream engine. Each connection opens from the last
939
968
  # event id seen; frames advance the cursor before any decode, so a
@@ -944,7 +973,7 @@ module PineSandbox
944
973
  # dead one ends with StreamLostError. An error answer raises at once.
945
974
  # Returns the cursor when `terminal` or `stop_when` matches an event, or
946
975
  # when `max_reconnects` (a caller cap on total reconnects) is used up.
947
- def follow_events(op:, cursor:, open:, decode:, terminal: nil, stop_when: nil, max_reconnects: nil)
976
+ def follow_events(op:, cursor:, open:, decode:, terminal: nil, stop_when: nil, max_reconnects: nil, &block)
948
977
  cursor = cursor.to_s
949
978
  failures = 0
950
979
  reconnects = 0
@@ -962,11 +991,7 @@ module PineSandbox
962
991
  next if event.nil?
963
992
 
964
993
  delivered = true
965
- begin
966
- yield event
967
- rescue StandardError => e
968
- raise BlockError.new(e)
969
- end
994
+ StreamedRead.pass(block, event)
970
995
  throw :pine_stream_stop if terminal&.call(event) || stop_when&.call(event)
971
996
  end
972
997
  request_id = request_id_header(response) || request_id
@@ -1005,11 +1030,6 @@ module PineSandbox
1005
1030
  ::PineSandbox::ControlEvents.decode_event(frame.event, id, frame.data)
1006
1031
  end
1007
1032
 
1008
- def keep_error_body(buffer, chunk)
1009
- remaining = STREAM_ERROR_BODY_CAP - buffer.bytesize
1010
- buffer << chunk.byteslice(0, remaining) if remaining.positive?
1011
- end
1012
-
1013
1033
  # Passes a binary GET's body to the block in chunks as it arrives instead
1014
1034
  # of buffering it. Only a 2xx body reaches the block: an error answer is
1015
1035
  # kept (bounded) and raised as the same typed error the buffered read
@@ -1017,52 +1037,28 @@ module PineSandbox
1017
1037
  # raises too, so the caller knows the body is incomplete. The default
1018
1038
  # connection's read timeout bounds each wait for the next chunk.
1019
1039
  def stream_bytes(path, token:, accept:, &block)
1020
- error_body = +""
1021
- # faraday-net_http before 3.0 passes no env and learns the status only
1022
- # after the body, so a chunk can't be told from an error body until the
1023
- # response ends. Those chunks go to a temp file, not memory, and are
1024
- # passed on once the status is known.
1025
- spool = nil
1026
1040
  with_transport_norm("GET", path) do
1027
- response = connection.get(route_path(path)) do |req|
1028
- apply_token(req, token)
1029
- req.headers["Accept"] = accept
1030
- req.options.on_data = proc do |chunk, _received, env|
1031
- if env.nil?
1032
- (spool ||= Tempfile.new("pinesandbox-read", binmode: true)).write(chunk)
1033
- elsif env.status.to_i.between?(200, 299)
1034
- pass_to_block(block, chunk.b) unless chunk.empty?
1035
- else
1036
- keep_error_body(error_body, chunk)
1037
- end
1038
- end
1039
- end
1040
- if spool
1041
- spool.rewind
1042
- if response.success?
1043
- while (chunk = spool.read(SPOOL_READ_SIZE))
1044
- yield chunk
1045
- end
1046
- else
1047
- keep_error_body(error_body, spool.read(STREAM_ERROR_BODY_CAP).to_s)
1041
+ response = StreamedRead.read(->(chunk, _answer) { StreamedRead.pass(block, chunk) }) do |on_data|
1042
+ connection.get(route_path(path)) do |req|
1043
+ apply_token(req, token)
1044
+ req.headers["Accept"] = accept
1045
+ req.options.on_data = on_data
1048
1046
  end
1049
1047
  end
1050
- response.env.body = error_body if !response.success? && response.body.to_s.empty?
1051
1048
  ensure_success!(response, token: token) unless response.success?
1052
1049
  end
1053
1050
  nil
1054
1051
  rescue BlockError => e
1055
1052
  raise e.error
1056
- ensure
1057
- spool&.close!
1058
1053
  end
1059
1054
 
1060
1055
  def get(path, token:, accept: "application/json", headers: nil)
1061
1056
  request(:get, path, token: token, accept: accept, headers: headers)
1062
1057
  end
1063
1058
 
1064
- def post(path, token:, json: nil, body: nil, content_type: nil, headers: nil)
1065
- request(:post, path, token: token, json: json, body: body, content_type: content_type, headers: headers)
1059
+ def post(path, token:, json: nil, body: nil, content_type: nil, headers: nil, timeout: nil, reached: nil)
1060
+ request(:post, path, token: token, json: json, body: body, content_type: content_type, headers: headers,
1061
+ timeout: timeout, reached: reached)
1066
1062
  end
1067
1063
 
1068
1064
  def patch(path, token:, json: nil, headers: nil)
@@ -1082,9 +1078,11 @@ module PineSandbox
1082
1078
  # Sends one request. A transport fault (no response) is retried with
1083
1079
  # RetryPolicy's transient backoff only when the route is a replay-safe
1084
1080
  # public operation (one whose safety rests on an Idempotency-Key only
1085
- # when the request carries one); a response of any status is never
1086
- # resent here.
1087
- def request(method, path, token:, json: nil, body: nil, content_type: nil, accept: "application/json", headers: nil, timeout: nil)
1081
+ # when the request carries one), or when the connection could not be
1082
+ # opened; a response of any status is never resent here. reached, when
1083
+ # given, is called for each send that may have reached the Computer.
1084
+ def request(method, path, token:, json: nil, body: nil, content_type: nil, accept: "application/json", headers: nil, timeout: nil,
1085
+ reached: nil)
1088
1086
  verb = method.to_s.upcase
1089
1087
  operation = Operations.match(:computer, verb, route_path(path.to_s.split(/[?#]/, 2).first))
1090
1088
  idempotency_key = headers&.find { |name, _| name.to_s.casecmp?("Idempotency-Key") }&.last
@@ -1107,11 +1105,17 @@ module PineSandbox
1107
1105
  headers&.each { |k, v| req.headers[k] = v if v }
1108
1106
  end
1109
1107
  end
1110
- rescue PineSandbox::TimeoutError, PineSandbox::ConnectionError
1111
- raise if attempt >= attempts
1108
+ reached&.call
1109
+ rescue PineSandbox::TimeoutError, PineSandbox::ConnectionError => e
1110
+ reached&.call unless not_sent?(e)
1111
+ raise unless attempt < attempts || (not_sent?(e) && attempt < RetryPolicy::TRANSIENT_ATTEMPTS)
1112
1112
 
1113
1113
  @clock.sleep(RetryPolicy.transient_backoff(attempt, @clock))
1114
1114
  retry
1115
+ rescue PineSandbox::Error
1116
+ # It ends the call; counted so an earlier lost response still leaves a run unconfirmed.
1117
+ reached&.call
1118
+ raise
1115
1119
  end
1116
1120
  ensure_success!(response, token: token)
1117
1121
  ParsedResponse.new(response, accept)
@@ -1138,10 +1142,14 @@ module PineSandbox
1138
1142
  if error.is_a?(Faraday::TimeoutError)
1139
1143
  PineSandbox::TimeoutError.new("Computer request timed out: #{error.message}#{suffix}")
1140
1144
  else
1141
- PineSandbox::ConnectionError.new("Computer connection failed: #{error.message}#{suffix}")
1145
+ PineSandbox::ConnectionError.new("Computer connection failed: #{error.message}#{suffix}").tap do |fault|
1146
+ fault.not_sent = ConnectAwareNetHttp.not_sent?(error)
1147
+ end
1142
1148
  end
1143
1149
  end
1144
1150
 
1151
+ def not_sent?(error) = error.is_a?(PineSandbox::ConnectionError) && error.not_sent?
1152
+
1145
1153
  # "<METHOD> /<path>" with any query string / fragment stripped — the transport-fault
1146
1154
  # counterpart to op_for (which reads env.url.path). `path` is the SDK route, sans the
1147
1155
  # leading slash route_path adds.
@@ -1259,8 +1267,10 @@ module PineSandbox
1259
1267
 
1260
1268
  # v0 + non-problem+json error: emit the older shape, now carrying the resource spine
1261
1269
  # in problem_extensions so ApiError#build_message renders it resource-first.
1270
+ # A plain answer the Computer names by a machine code keeps that name.
1262
1271
  message = parse_legacy_error_message(response.body)
1263
- klass =
1272
+ klass = PineSandbox.code_class_for(response.status, legacy_error_code(response.body))
1273
+ klass ||=
1264
1274
  case response.status
1265
1275
  when 401, 403 then PineSandbox::UnauthorizedError
1266
1276
  when 404 then PineSandbox::NotFoundError
@@ -1319,6 +1329,14 @@ module PineSandbox
1319
1329
  rid unless rid.to_s.empty?
1320
1330
  end
1321
1331
 
1332
+ # The machine code of a plain JSON error body (`{"error": "..."}`), or nil.
1333
+ def legacy_error_code(body)
1334
+ parsed = JSON.parse(body)
1335
+ parsed["error"] if parsed.is_a?(Hash)
1336
+ rescue JSON::ParserError, TypeError
1337
+ nil
1338
+ end
1339
+
1322
1340
  def parse_legacy_error_message(body)
1323
1341
  JSON.parse(body)["error"] || body.to_s
1324
1342
  rescue JSON::ParserError, TypeError
@@ -1332,10 +1350,10 @@ module PineSandbox
1332
1350
  # API key (coord gates every route on the bearer).
1333
1351
  def connection
1334
1352
  @connection ||= @zone.faraday(@host) do |conn|
1335
- conn.headers["User-Agent"] = "pinesandbox-ruby/#{PineSandbox::VERSION}"
1336
- conn.options.open_timeout = DEFAULT_OPEN_TIMEOUT
1337
- conn.options.timeout = DEFAULT_HTTP_TIMEOUT
1338
- conn.adapter Faraday.default_adapter
1353
+ conn.headers["User-Agent"] = PineSandbox::USER_AGENT
1354
+ conn.options.open_timeout = @timeouts.connect
1355
+ conn.options.timeout = @timeouts.request
1356
+ conn.adapter ConnectAwareNetHttp
1339
1357
  end
1340
1358
  end
1341
1359
 
@@ -1350,10 +1368,10 @@ module PineSandbox
1350
1368
  # block, which the adapter calls AFTER applying request_timeout.
1351
1369
  def streaming_connection
1352
1370
  @streaming_connection ||= @zone.faraday(@host) do |conn|
1353
- conn.headers["User-Agent"] = "pinesandbox-ruby/#{PineSandbox::VERSION}"
1354
- conn.options.open_timeout = DEFAULT_OPEN_TIMEOUT
1371
+ conn.headers["User-Agent"] = PineSandbox::USER_AGENT
1372
+ conn.options.open_timeout = @timeouts.connect
1355
1373
  # DELIBERATELY no conn.options.timeout — adapter block is authoritative.
1356
- conn.adapter Faraday.default_adapter do |http|
1374
+ conn.adapter ConnectAwareNetHttp do |http|
1357
1375
  http.read_timeout = STREAM_IDLE_TIMEOUT
1358
1376
  end
1359
1377
  end
@@ -45,22 +45,25 @@ module PineSandbox
45
45
  # it saved to get the same turn back. When no response arrives within the
46
46
  # resend budget, #run raises the last failure — a ConnectionError,
47
47
  # TimeoutError or ApiError — extended with RunUnconfirmedError, with
48
- # #idempotency_key naming the key to send it again with.
48
+ # #idempotency_key naming the key to send it again with. After a lost
49
+ # response, any error a later send raises is extended the same way, a
50
+ # SandboxGoneError included, so rescue RunUnconfirmedError first.
49
51
  #
50
- # secrets: optional name→value secrets, delivered to the session secrets
51
- # file ($SESSION_SECRETS) once the run is admitted and before the agent
52
- # starts — never model-visible text; the agent references values as $NAME.
53
- # See the spec's SessionSecrets schema for the naming rules and lifecycle
54
- # (ephemeral; re-send after re-attach).
52
+ # secrets: optional name→value secrets. The agent can discover the supplied names.
53
+ # See the spec's SessionSecrets schema for limits, lifetime and privacy
54
+ # boundaries; later tool output can still expose values to the model.
55
55
  def run(goal, context: nil, skills: nil, constraints: nil, secrets: nil, idempotency_key: nil)
56
56
  idempotency_key ||= SecureRandom.uuid_v7
57
- send_turn do
57
+ sends = 0
58
+ send_turn do |timeout|
58
59
  coordinator.agent_run(token: ct, name: name, goal: goal,
59
60
  context: context, skills: skills, constraints: constraints,
60
- secrets: secrets, idempotency_key: idempotency_key)
61
+ secrets: secrets, idempotency_key: idempotency_key, timeout: timeout,
62
+ reached: -> { sends += 1 })
61
63
  end
62
- rescue TimeoutError, ConnectionError, ApiError => e
63
- if lost_response?(e)
64
+ rescue Error => e
65
+ # A later send's answer can't show what an earlier one whose response was lost did.
66
+ if lost_response?(e) || sends > 1
64
67
  e.idempotency_key = idempotency_key
65
68
  e.extend(RunUnconfirmedError)
66
69
  end
@@ -74,13 +77,17 @@ module PineSandbox
74
77
  # "running" or "canceling"; timeout 0 reads it once. Waiting never cancels
75
78
  # the turn or follows its next turn. A read whose response was lost (a
76
79
  # network fault, a 408, or a gateway 502, 503 or 504), or whose problem is
77
- # marked retryable, is read again until the timeout; any other error
78
- # raises, including a missing or expired turn. A read that comes back
79
- # sooner than it asked the Computer to hold is followed by a pause of up
80
- # to a second, so waiting never spins.
80
+ # marked retryable, is read again until the timeout; then wait returns the
81
+ # turn as it last read it, or raises the last error when no read came
82
+ # back. Such an error means this process lost the Computer, not that the
83
+ # turn failed: the turn keeps running, so wait again rather than stopping
84
+ # the Computer. Any other error raises, including a missing or expired
85
+ # turn. A read that comes back sooner than it asked the Computer to hold
86
+ # is followed by a pause of up to a second, so waiting never spins.
81
87
  def wait(turn_id:, timeout:)
82
88
  deadline = monotonic + timeout
83
89
  failures = 0
90
+ last = nil
84
91
  loop do
85
92
  hold = (deadline - monotonic).clamp(0, WAIT_HOLD_SECONDS).floor
86
93
  started = monotonic
@@ -88,13 +95,16 @@ module PineSandbox
88
95
  turn = coordinator.agent_turn(token: read_token, name: name, turn_id: turn_id, wait_seconds: hold)
89
96
  rescue TimeoutError, ConnectionError, ApiError => e
90
97
  retryable = lost_response?(e) || (e.is_a?(ApiError) && e.retryable? == true)
91
- raise unless retryable && monotonic < deadline
98
+ raise unless retryable
99
+ return AgentTurn.wrap(last) if last && monotonic >= deadline
100
+ raise unless monotonic < deadline
92
101
 
93
102
  failures += 1
94
103
  sleep([retry_delay(failures, e), deadline - monotonic].min)
95
104
  next
96
105
  end
97
106
  failures = 0
107
+ last = turn
98
108
  return AgentTurn.wrap(turn) unless WAITING_STATES.include?(turn["state"]) && monotonic < deadline
99
109
 
100
110
  # The Computer holds whole seconds, and may answer before the hold
@@ -113,7 +123,9 @@ module PineSandbox
113
123
  # leaves the question open), so the answer can reference a password or
114
124
  # code as $NAME.
115
125
  def answer(turn_id:, answer:, secrets: nil)
116
- send_turn { coordinator.agent_answer(token: ct, name: name, turn_id: turn_id, answer: answer, secrets: secrets) }
126
+ send_turn do |timeout|
127
+ coordinator.agent_answer(token: ct, name: name, turn_id: turn_id, answer: answer, secrets: secrets, timeout: timeout)
128
+ end
117
129
  end
118
130
 
119
131
  # steer(turn_id:, text:) — add guidance to turn_id while it runs. Returns
@@ -132,7 +144,7 @@ module PineSandbox
132
144
  # answered turn raises a 409 (/errors/stale-turn): cancel the turn its
133
145
  # answer opened instead.
134
146
  def cancel(turn_id:)
135
- send_turn { coordinator.agent_cancel(token: ct, name: name, turn_id: turn_id) }
147
+ send_turn { |timeout| coordinator.agent_cancel(token: ct, name: name, turn_id: turn_id, timeout: timeout) }
136
148
  end
137
149
 
138
150
  # reset — forget the agent's thread so the next run starts on a fresh memory
@@ -185,11 +197,13 @@ module PineSandbox
185
197
 
186
198
  # Send a mutation whose repeat names the same turn, resending it after a
187
199
  # lost response, and wrap the turn it returns.
200
+ # Yields the timeout for this send: what is left of the budget, at most the
201
+ # client's request timeout, so no send outlasts the budget.
188
202
  def send_turn
189
203
  attempt = 0
190
204
  started = monotonic
191
205
  begin
192
- AgentTurn.wrap(yield)
206
+ AgentTurn.wrap(yield([RESEND_BUDGET_SECONDS - (monotonic - started), coordinator.timeouts.request].min))
193
207
  rescue TimeoutError, ConnectionError, ApiError => e
194
208
  raise unless lost_response?(e)
195
209
 
@@ -19,6 +19,7 @@ module PineSandbox
19
19
  # The agent's closing message; the question for "needs_input".
20
20
  def summary = self["summary"]
21
21
  def artifacts = self["artifacts"]
22
+ # Saved paths: client.artifacts(ref["computer_id"]).download(ref["path"], destination).
22
23
  def author = self["author"]
23
24
  def usage = self["usage"]
24
25
  end
@@ -56,7 +57,7 @@ module PineSandbox
56
57
  # turn did not end with one.
57
58
  def question
58
59
  ended = result
59
- ended.is_a?(Hash) && ended["terminal_reason"] == "needs_input" ? ended["summary"] : nil
60
+ ended.is_a?(Hash) && ended["terminal_reason"] == TerminalReason::NEEDS_INPUT ? ended["summary"] : nil
60
61
  end
61
62
 
62
63
  def started_at = parse_time(self["started_at"])