@tangle-network/sandbox 0.45.0 → 0.46.0

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,4 @@
1
- import { a as uploadChunked, c as encodePromptForWire, d as applyRequestedModel, f as assertCurrentBackendType, g as deriveAgentResultOutcome, h as createAgentRunOutcomeTracker, i as sessionHeaders, m as normalizeRuntimeBackendConfig, n as normalizeSessionInfo, o as SANDBOX_PROXY_REQUEST_MAX_BYTES, p as mergeRuntimeBackendConfig, r as appendSessionIdQuery, t as SandboxRuntimeApi, u as parseSSEStream } from "./runtime-api-C10Hg1OF.js";
1
+ import { _ as normalizeRuntimeBackendConfig, a as sessionHeaders, c as validateAcceptedDispatchRunRef, d as encodePromptForWire, g as mergeRuntimeBackendConfig, h as assertCurrentBackendType, i as appendSessionIdQuery, l as SANDBOX_PROXY_REQUEST_MAX_BYTES, m as applyRequestedModel, n as normalizeSessionInfo, o as uploadChunked, p as parseSSEStream, r as sessionMessageRequestBody, s as resolveDispatchRunIdentity, t as SandboxRuntimeApi, v as createAgentRunOutcomeTracker, y as deriveAgentResultOutcome } from "./runtime-api-D7CdKcbu.js";
2
2
  import { c as NotFoundError, d as SandboxError, f as ServerError, g as parseErrorResponse, h as ValidationError, m as TimeoutError, n as CapabilityError, p as StateError, r as EdgeNotReadyError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-CdDyExth.js";
3
3
  import { c as createInteractiveControlHolderId, d as interactiveSessionControlReleaseResponseSchema, f as interactiveSessionControlValidationResponseSchema, i as createBrowserInteractiveSessionControlTransport, o as InteractiveSessionControlController, p as interactiveSessionStatusResponseSchema, r as browserInteractiveTerminalEndpoint, s as assertInteractiveSessionRef, u as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-Dv0gbFMu.js";
4
4
  import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-si1WMfJb.js";
@@ -254,6 +254,24 @@ function normalizeSshCredentials(raw) {
254
254
  proxyCommand: s.proxyCommand
255
255
  };
256
256
  }
257
+ /**
258
+ * Narrow a raw `resources` grant into a `SandboxShape`. Returns `undefined`
259
+ * when any of the three sizing terms is missing, so a payload that carries no
260
+ * grant (a list row, an older sandbox) leaves the caller's known grant alone
261
+ * rather than overwriting it with a partial object.
262
+ */
263
+ function normalizeSandboxShape(raw) {
264
+ if (!raw || typeof raw !== "object") return void 0;
265
+ const r = raw;
266
+ if (typeof r.cpuCores !== "number" || typeof r.memoryMB !== "number" || typeof r.diskGB !== "number") return;
267
+ return {
268
+ cpuCores: r.cpuCores,
269
+ memoryMB: r.memoryMB,
270
+ diskGB: r.diskGB,
271
+ ...typeof r.pool === "string" ? { pool: r.pool } : {},
272
+ ...typeof r.ttlMs === "number" ? { ttlMs: r.ttlMs } : {}
273
+ };
274
+ }
257
275
  //#endregion
258
276
  //#region src/capabilities.ts
259
277
  function invalidCapabilities(message) {
@@ -378,56 +396,240 @@ function parseCompletedTurnResult(value, expected) {
378
396
  };
379
397
  }
380
398
  //#endregion
381
- //#region src/dispatch-run-control.ts
382
- const DISPATCH_RUN_PROVIDER = "tangle-sandbox";
383
- function generateRuntimeId(prefix) {
384
- const crypto = globalThis.crypto;
385
- if (crypto?.randomUUID) return `${prefix}-${crypto.randomUUID()}`;
386
- if (crypto?.getRandomValues) {
387
- const bytes = crypto.getRandomValues(new Uint8Array(16));
388
- return `${prefix}-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
389
- }
390
- throw new ValidationError("Run identity generation requires global crypto");
399
+ //#region src/direct-read-route.ts
400
+ /**
401
+ * Direct regional status reads.
402
+ *
403
+ * A status read through the sandbox API pays the whole control hop — the
404
+ * Cloudflare edge, the Worker's middleware and D1 reads, and the
405
+ * Worker-to-origin leg — for about 1 ms of work at the origin. Measured on
406
+ * production release 919fda997f from a vantage 7 ms from the origin, that
407
+ * read cost 293-337 ms; from Los Angeles the same hop is the 78 ms edge plus
408
+ * a 265 ms transport leg on top of the Worker's own time. Every lifecycle
409
+ * verb polls that read while it settles, so the hop is paid per poll.
410
+ *
411
+ * WHAT THE DIRECT ROUTE ANSWERS, AND WHAT IT DELIBERATELY DOES NOT.
412
+ *
413
+ * It answers one question: has this sandbox's state moved since the API last
414
+ * described it? It never produces a status of its own. The API remains the
415
+ * only thing that ever tells the SDK what a sandbox IS — it owns the
416
+ * projection from the orchestrator's vocabulary into the SDK's, the runtime
417
+ * token mint, the egress annotation and the team fields, and none of that is
418
+ * reproduced here. So a poll loop becomes: N cheap "still the same" reads at
419
+ * the regional endpoint, then ONE full API read at the moment something
420
+ * changed. A direct read can never report a state the API path would not have
421
+ * reported, because it reports no state at all.
422
+ *
423
+ * THE FALLBACK IS THE CONTRACT. A refusal, an expiry, a timeout, an
424
+ * unreachable origin or a body that does not parse costs the caller nothing:
425
+ * the read is answered by the API exactly as it always was. A failure also
426
+ * COOLS THE ROUTE DOWN — the grant is dropped and no direct attempt is made
427
+ * for {@link DIRECT_READ_COOLDOWN_MS} — so a regional endpoint that is down
428
+ * costs one failed connect per cooldown window, not one per poll. That window
429
+ * matches the Worker's own direct-origin cooldown, so both sides retreat from
430
+ * a sick origin on the same clock.
431
+ *
432
+ * AND A FALLBACK IS DECLARED. The API request a failure forces carries
433
+ * {@link DIRECT_READ_FALLBACK_HEADER} naming the reason, so a direct plane
434
+ * that has quietly stopped working shows up at the API as a fallback rate
435
+ * instead of as unattributed latency. A read that goes to the API because the
436
+ * state CHANGED is not a fallback and is not counted as one — that is the
437
+ * route working as designed.
438
+ */
439
+ /**
440
+ * The statuses a direct read may serve.
441
+ *
442
+ * A settling sandbox is polled; a settled one is not, and its next refresh is
443
+ * usually a caller asking for the WHOLE description (connection, runtime
444
+ * token, egress annotation) rather than for a status. Restricting the route
445
+ * to the two settling statuses means every other refresh in the SDK keeps the
446
+ * exact behaviour it has today, and the route can only ever remove calls from
447
+ * the loop it was built for.
448
+ */
449
+ const DIRECT_READ_POLLABLE_STATUSES = new Set(["pending", "provisioning"]);
450
+ /** See the module note: same clock as the Worker's direct-origin cooldown. */
451
+ const DIRECT_READ_COOLDOWN_MS = 3e4;
452
+ /** Bound on one direct attempt. A slow origin must not outlast the fast path. */
453
+ const DIRECT_READ_TIMEOUT_MS = 5e3;
454
+ /**
455
+ * Stop using a grant this long before it expires, so a read that starts just
456
+ * inside the window cannot arrive just outside it.
457
+ */
458
+ const DIRECT_READ_EXPIRY_MARGIN_MS = 2e3;
459
+ /** Must match products/sandbox/api/src/routes/sandbox-direct-read-relay.ts. */
460
+ const DIRECT_READ_FALLBACK_HEADER = "x-tangle-direct-read-fallback";
461
+ /**
462
+ * The state fingerprint. Both fields are raw orchestrator fields, so an equal
463
+ * fingerprint means the API's own answer would also be unchanged — which is
464
+ * the only property this route needs to be correct.
465
+ *
466
+ * Shared with the Worker relay by shape, and pinned by
467
+ * `direct-read-route.test.ts` against the relay's own fixture.
468
+ */
469
+ function directReadFingerprint(project) {
470
+ return `${typeof project?.status === "string" ? project.status : ""}|${typeof project?.filesystemIncarnationReadiness === "string" ? project.filesystemIncarnationReadiness : ""}`;
391
471
  }
392
- function resolveDispatchRunIdentity(sandboxId, message, options) {
393
- const sessionId = options?.sessionId ?? options?.runControlRef?.sessionId ?? generateRuntimeId("session");
394
- const executionId = options?.executionId ?? options?.runControlRef?.executionId ?? generateRuntimeId("execution");
472
+ /**
473
+ * Narrow the relayed field without trusting its shape. The input is an
474
+ * arbitrary field off an HTTP response body, and deciding whether it is a
475
+ * grant is exactly this function's job, so a named input type would assert
476
+ * what it is here to check.
477
+ */
478
+ function parseDirectReadGrant(value) {
479
+ if (!value || typeof value !== "object") return null;
480
+ const { url, token, expiresAt, observed } = value;
481
+ if (typeof url !== "string" || !url.startsWith("https://")) return null;
482
+ if (typeof token !== "string" || token.length === 0) return null;
483
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) return null;
484
+ if (typeof observed !== "string") return null;
395
485
  return {
396
- sessionId,
397
- executionId,
398
- runControlRef: options?.runControlRef ?? {
399
- runId: generateRuntimeId("run"),
400
- provider: DISPATCH_RUN_PROVIDER,
401
- environmentId: sandboxId,
402
- sessionId,
403
- executionId,
404
- requestDigest: canonicalCandidateDigest({
405
- message,
406
- sessionId,
407
- turnId: options?.turnId ?? null,
408
- backend: options?.backend ?? null,
409
- model: options?.model ?? null,
410
- context: options?.context ?? null
411
- })
412
- }
486
+ url,
487
+ token,
488
+ expiresAt,
489
+ observed
413
490
  };
414
491
  }
415
- function sameExactRunControlRef(left, right) {
416
- return left.runId === right.runId && left.provider === right.provider && left.environmentId === right.environmentId && left.sessionId === right.sessionId && left.executionId === right.executionId && left.requestDigest === right.requestDigest;
417
- }
418
- function validateAcceptedDispatchRunRef(raw, expected, sandboxId, sessionId, executionId) {
419
- const parsed = AgentExactRunControlRefSchema.safeParse(raw);
420
- if (!parsed.success) throw new ServerError("Sandbox returned an invalid exact run reference on admission", 502, {
421
- origin: "runtime",
422
- endpoint: "/agents/run/stream"
423
- });
424
- const accepted = parsed.data;
425
- if (accepted.environmentId !== sandboxId || accepted.sessionId !== sessionId || accepted.executionId !== executionId || !sameExactRunControlRef(accepted, expected)) throw new ServerError("Sandbox returned an exact run reference for another execution", 502, {
426
- origin: "runtime",
427
- endpoint: "/agents/run/stream"
428
- });
429
- return accepted;
430
- }
492
+ /**
493
+ * One sandbox's direct-read route. Owns the grant, the cooldown and the
494
+ * counters, and performs the direct read — nothing else. The caller owns the
495
+ * API request, because the API request is what has to happen anyway whenever
496
+ * this route declines.
497
+ */
498
+ var DirectReadRoute = class {
499
+ grant = null;
500
+ cooldownUntil = 0;
501
+ /**
502
+ * Whether this cell ever armed the route. A latch, not the live grant:
503
+ * once the API has handed over one grant, an expiry or a cooldown IS a
504
+ * degradation worth declaring, but a cell that never armed the plane must
505
+ * not report a 100% fallback rate for never having tried.
506
+ */
507
+ engagedOnce = false;
508
+ fetchImpl;
509
+ now;
510
+ stats = {
511
+ attempts: 0,
512
+ unchanged: 0,
513
+ changed: 0,
514
+ fallbacks: 0,
515
+ lastReason: null
516
+ };
517
+ constructor(options = {}) {
518
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
519
+ this.now = options.now ?? Date.now;
520
+ }
521
+ /** Adopt the grant carried on an API response, if it carried one. */
522
+ adopt(payload) {
523
+ const grant = parseDirectReadGrant(payload?.directRead);
524
+ if (!grant) return;
525
+ this.grant = grant;
526
+ this.engagedOnce = true;
527
+ }
528
+ /**
529
+ * True once the API has armed this route. Callers ask before reading, so a
530
+ * deployment without the direct plane keeps the exact request it sends
531
+ * today and contributes nothing to the fallback rate.
532
+ */
533
+ engaged() {
534
+ return this.engagedOnce;
535
+ }
536
+ snapshotStats() {
537
+ return { ...this.stats };
538
+ }
539
+ /** True when a direct attempt would be made right now. Test and probe aid. */
540
+ armed() {
541
+ const now = this.now();
542
+ if (now < this.cooldownUntil) return false;
543
+ const grant = this.grant;
544
+ if (!grant) return false;
545
+ return grant.expiresAt - DIRECT_READ_EXPIRY_MARGIN_MS > now;
546
+ }
547
+ fallback(reason) {
548
+ this.stats.fallbacks += 1;
549
+ this.stats.lastReason = reason;
550
+ if (reason !== "expired" && reason !== "cooldown") {
551
+ this.cooldownUntil = this.now() + DIRECT_READ_COOLDOWN_MS;
552
+ this.grant = null;
553
+ }
554
+ return {
555
+ kind: "fallback",
556
+ reason
557
+ };
558
+ }
559
+ /**
560
+ * Ask the regional endpoint whether the state has moved.
561
+ *
562
+ * `unchanged` means the caller needs no API call at all. `changed` and
563
+ * `fallback` both mean "read through the API"; only `fallback` is a
564
+ * degradation, and only `fallback` is declared on that request.
565
+ */
566
+ async read(signal) {
567
+ this.stats.attempts += 1;
568
+ const now = this.now();
569
+ if (now < this.cooldownUntil) {
570
+ this.stats.fallbacks += 1;
571
+ this.stats.lastReason = "cooldown";
572
+ return {
573
+ kind: "fallback",
574
+ reason: "cooldown"
575
+ };
576
+ }
577
+ const grant = this.grant;
578
+ if (!grant || grant.expiresAt - 2e3 <= now) {
579
+ this.grant = null;
580
+ this.stats.fallbacks += 1;
581
+ this.stats.lastReason = "expired";
582
+ return {
583
+ kind: "fallback",
584
+ reason: "expired"
585
+ };
586
+ }
587
+ const controller = new AbortController();
588
+ const timer = setTimeout(() => controller.abort(), DIRECT_READ_TIMEOUT_MS);
589
+ const onAbort = () => controller.abort();
590
+ signal?.addEventListener("abort", onAbort, { once: true });
591
+ let response;
592
+ try {
593
+ response = await this.fetchImpl(grant.url, {
594
+ method: "GET",
595
+ headers: { Authorization: `Bearer ${grant.token}` },
596
+ signal: controller.signal
597
+ });
598
+ } catch {
599
+ if (signal?.aborted) {
600
+ this.stats.fallbacks += 1;
601
+ this.stats.lastReason = "unreachable";
602
+ return {
603
+ kind: "fallback",
604
+ reason: "unreachable"
605
+ };
606
+ }
607
+ return this.fallback(controller.signal.aborted ? "timeout" : "unreachable");
608
+ } finally {
609
+ clearTimeout(timer);
610
+ signal?.removeEventListener("abort", onAbort);
611
+ }
612
+ if (!response.ok) return this.fallback("refused");
613
+ let body;
614
+ try {
615
+ body = await response.json();
616
+ } catch {
617
+ return this.fallback("malformed");
618
+ }
619
+ const project = body?.project;
620
+ if (!project || typeof project !== "object" || Array.isArray(project)) return this.fallback("malformed");
621
+ if (directReadFingerprint(project) === grant.observed) {
622
+ this.stats.unchanged += 1;
623
+ return { kind: "unchanged" };
624
+ }
625
+ this.stats.changed += 1;
626
+ return { kind: "changed" };
627
+ }
628
+ /** Headers to stamp on the API request that a FAILURE forced. */
629
+ fallbackHeaders(reason) {
630
+ return { [DIRECT_READ_FALLBACK_HEADER]: reason };
631
+ }
632
+ };
431
633
  //#endregion
432
634
  //#region ../../../packages/runtime-contracts/dist/interaction-response.js
433
635
  /** Durable states reported for a recorded interaction response. */
@@ -698,15 +900,30 @@ function isRecord$1(v) {
698
900
  function firstString(...candidates) {
699
901
  for (const candidate of candidates) if (typeof candidate === "string") return candidate;
700
902
  }
903
+ /** Snapshot text wins when a runtime sends both its snapshot and delta. */
904
+ function messageTextUpdate(event) {
905
+ if (event.type !== "message.part.updated") return void 0;
906
+ const data = isRecord$1(event.data) ? event.data : {};
907
+ const properties = isRecord$1(data.properties) ? data.properties : void 0;
908
+ const part = isRecord$1(data.part) ? data.part : isRecord$1(properties?.part) ? properties.part : void 0;
909
+ if (part?.type !== "text") return void 0;
910
+ const snapshot = firstString(part.text, part.content);
911
+ if (snapshot !== void 0) return {
912
+ text: snapshot,
913
+ incremental: false
914
+ };
915
+ const delta = firstString(data.delta, properties?.delta);
916
+ return delta === void 0 ? void 0 : {
917
+ text: delta,
918
+ incremental: true
919
+ };
920
+ }
701
921
  function getSandboxEventText(event) {
702
922
  const data = isRecord$1(event.data) ? event.data : {};
703
923
  if (event.type === "result") return firstString(data.finalText, data.response, data.output, data.content, data.text);
704
924
  if (event.type === "token") return firstString(data.value, data.delta, data.text, data.content);
705
925
  if (event.type !== "message.part.updated") return;
706
- const properties = isRecord$1(data.properties) ? data.properties : void 0;
707
- const part = isRecord$1(data.part) ? data.part : isRecord$1(properties?.part) ? properties.part : void 0;
708
- if (part?.type !== "text") return;
709
- return firstString(part.text, part.content);
926
+ return messageTextUpdate(event)?.text;
710
927
  }
711
928
  /** As {@link getSandboxEventText}, but treats a whitespace-only payload as no
712
929
  * text — so blank parts never overwrite real accumulated text. */
@@ -716,11 +933,9 @@ function getMeaningfulSandboxEventText(event) {
716
933
  return text;
717
934
  }
718
935
  /**
719
- * Fold one event into the running response text. `token` events APPEND their
720
- * incremental delta/value; every other text-bearing event (`result`,
721
- * `message.part.updated`) carries the cumulative text, so it REPLACES — unless
722
- * it is a strict continuation of what we already have, in which case it is
723
- * appended once. An event with no meaningful text leaves `current` untouched.
936
+ * Fold one event into the running response text. Explicit deltas append,
937
+ * including whitespace and repeated chunks. Cumulative message parts and
938
+ * final results replace the text. Blank snapshots leave `current` untouched.
724
939
  *
725
940
  * Whitespace handling differs by kind: an incremental `token` keeps its RAW text
726
941
  * (a lone space delta is a word separator — dropping it concatenates words), but
@@ -728,6 +943,8 @@ function getMeaningfulSandboxEventText(event) {
728
943
  * real accumulated text.
729
944
  */
730
945
  function applySandboxEventText(current, event) {
946
+ const update = messageTextUpdate(event);
947
+ if (update?.incremental) return `${current ?? ""}${update.text}`;
731
948
  const text = event.type === "token" ? getSandboxEventText(event) : getMeaningfulSandboxEventText(event);
732
949
  if (text === void 0) return current;
733
950
  if (event.type !== "token") return text;
@@ -853,8 +1070,9 @@ function collectAgentFinalMessageText(events) {
853
1070
  const properties = isRecord$1(data.properties) ? data.properties : void 0;
854
1071
  const part = isRecord$1(data.part) ? data.part : isRecord$1(properties?.part) ? properties.part : void 0;
855
1072
  if (part?.type !== "text") continue;
856
- const text = firstString(part.text, part.content);
857
- if (text === void 0 || text.trim().length === 0) continue;
1073
+ const update = messageTextUpdate(event);
1074
+ const text = update?.text;
1075
+ if (text === void 0 || !update?.incremental && text.trim().length === 0) continue;
858
1076
  const rawId = part.id;
859
1077
  if (typeof rawId !== "string") {
860
1078
  slots.push(text);
@@ -866,7 +1084,8 @@ function collectAgentFinalMessageText(events) {
866
1084
  slots.push(text);
867
1085
  continue;
868
1086
  }
869
- if (text.startsWith(slots[at])) slots[at] = text;
1087
+ if (update?.incremental) slots[at] += text;
1088
+ else if (text.startsWith(slots[at])) slots[at] = text;
870
1089
  else {
871
1090
  slotOfPartId.set(rawId, slots.length);
872
1091
  slots.push(text);
@@ -2764,6 +2983,12 @@ var SandboxSession = class SandboxSession {
2764
2983
  async runs() {
2765
2984
  return this.box._sessionRuns(this.id);
2766
2985
  }
2986
+ /** Read the exact execution admitted for a turn, including server-owned plan follow-ups.
2987
+ * This never admits work or verifies the input of a proposed retry.
2988
+ */
2989
+ async admission(turnId, options) {
2990
+ return this.box._sessionAdmission(this.id, turnId, options);
2991
+ }
2767
2992
  /**
2768
2993
  * Await a terminal result. With `executionId`, drains only that execution;
2769
2994
  * without it, reads status and selects the latest execution. Event replay
@@ -3270,6 +3495,7 @@ function normalizeSandboxCreateReceipt(raw) {
3270
3495
  return {
3271
3496
  outcome,
3272
3497
  idempotencyKeyApplied,
3498
+ ...record.ownerContext === "inherit" || record.ownerContext === "isolated" ? { ownerContext: record.ownerContext } : {},
3273
3499
  ...injectedSecrets ? { injectedSecrets } : {}
3274
3500
  };
3275
3501
  }
@@ -3565,8 +3791,9 @@ function readFilesystemIncarnationTuple(value) {
3565
3791
  readiness
3566
3792
  };
3567
3793
  }
3568
- function createSandboxInstanceFromResponse(client, info, defaultRuntimeBackend) {
3794
+ function createSandboxInstanceFromResponse(client, info, defaultRuntimeBackend, raw) {
3569
3795
  const instance = new SandboxInstance(client, info, defaultRuntimeBackend);
3796
+ if (raw) instance.adoptDirectRead(raw);
3570
3797
  sandboxStatusObservedAt.set(instance, Date.now());
3571
3798
  return instance;
3572
3799
  }
@@ -3644,6 +3871,12 @@ var SandboxInstance = class SandboxInstance {
3644
3871
  * never by object identity, and a changed profile is sent inline.
3645
3872
  */
3646
3873
  deferredProfileReference;
3874
+ /**
3875
+ * Direct regional status reads for THIS sandbox. Inert until the API
3876
+ * relays a grant, and it retreats to the API path on any failure — see
3877
+ * direct-read-route.ts.
3878
+ */
3879
+ directRead = new DirectReadRoute();
3647
3880
  constructor(client, info, defaultRuntimeBackend) {
3648
3881
  this.client = client;
3649
3882
  const incarnation = readFilesystemIncarnationTuple(info);
@@ -3728,6 +3961,15 @@ var SandboxInstance = class SandboxInstance {
3728
3961
  get gpuLease() {
3729
3962
  return this.info.gpuLease;
3730
3963
  }
3964
+ /**
3965
+ * The shape this sandbox was granted: the cgroup and volume limits it runs
3966
+ * at and the numbers it is billed at. Present on a freshly created box and
3967
+ * on one resolved by `get`; `undefined` for a box from a list row until it
3968
+ * is refreshed, and for a sandbox created before the platform recorded it.
3969
+ */
3970
+ get resources() {
3971
+ return this.info.resources;
3972
+ }
3731
3973
  /** Web terminal URL for browser-based access */
3732
3974
  get url() {
3733
3975
  return this.info.connection?.webTerminalUrl;
@@ -3795,7 +4037,8 @@ var SandboxInstance = class SandboxInstance {
3795
4037
  lastActivityAt: this.lastActivityAt,
3796
4038
  expiresAt: this.expiresAt,
3797
4039
  error: this.error,
3798
- gpuLease: this.gpuLease
4040
+ gpuLease: this.gpuLease,
4041
+ resources: this.resources
3799
4042
  };
3800
4043
  }
3801
4044
  /**
@@ -3886,16 +4129,37 @@ var SandboxInstance = class SandboxInstance {
3886
4129
  }
3887
4130
  }
3888
4131
  async refreshInfo() {
3889
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}`);
4132
+ const direct = this.directRead.engaged() && DIRECT_READ_POLLABLE_STATUSES.has(this.info.status) ? await this.directRead.read() : null;
4133
+ if (direct?.kind === "unchanged") {
4134
+ sandboxStatusObservedAt.set(this, Date.now());
4135
+ return;
4136
+ }
4137
+ const response = await this.client.fetch(`/v1/sandboxes/${this.id}`, ...direct?.kind === "fallback" ? [{ headers: this.directRead.fallbackHeaders(direct.reason) }] : []);
3890
4138
  if (!response.ok) {
3891
4139
  const body = await response.text();
3892
4140
  throw parseErrorResponse(response.status, body, void 0, response.headers);
3893
4141
  }
3894
4142
  const data = await response.json();
4143
+ this.directRead.adopt(data);
3895
4144
  this.info = this.parseInfo(data, this.info);
3896
4145
  sandboxStatusObservedAt.set(this, Date.now());
3897
4146
  }
3898
4147
  /**
4148
+ * What the direct regional read route has done for this sandbox: attempts,
4149
+ * reads it served, reads that fell back to the API, and the last reason.
4150
+ * Read by the lifecycle probe; safe for a caller to read too.
4151
+ */
4152
+ directReadStats() {
4153
+ return this.directRead.snapshotStats();
4154
+ }
4155
+ /**
4156
+ * Arm the direct regional read from an API payload this instance did not
4157
+ * fetch itself. @internal — called by `createSandboxInstanceFromResponse`.
4158
+ */
4159
+ adoptDirectRead(payload) {
4160
+ this.directRead.adopt(payload);
4161
+ }
4162
+ /**
3899
4163
  * Fetch fresh TEE attestation evidence for this sandbox.
3900
4164
  *
3901
4165
  * When `attestationNonce` is supplied, the runtime must return evidence bound
@@ -4405,7 +4669,7 @@ var SandboxInstance = class SandboxInstance {
4405
4669
  * content references by hash, changed content sends inline.
4406
4670
  */
4407
4671
  buildRunBackendBody(overrideBackend, forceFullProfile, requestedModel) {
4408
- const normalized = normalizeRuntimeBackendConfig(applyRequestedModel(mergeRuntimeBackendConfig(this.defaultRuntimeBackend, overrideBackend), requestedModel));
4672
+ const normalized = normalizeRuntimeBackendConfig(mergeRuntimeBackendConfig(this.defaultRuntimeBackend, applyRequestedModel(overrideBackend, requestedModel)));
4409
4673
  if (!normalized) return normalized;
4410
4674
  const deferred = this.deferredProfileReference;
4411
4675
  if (!forceFullProfile && deferred !== void 0 && normalized.profile !== void 0 && serializeProfileSnapshot(normalized.profile) === deferred.snapshot) {
@@ -7475,6 +7739,7 @@ var SandboxInstance = class SandboxInstance {
7475
7739
  expiresAt: data.expiresAt ? new Date(data.expiresAt) : void 0,
7476
7740
  error: data.error,
7477
7741
  gpuLease: data.gpuLease ?? carryCreateFacts?.gpuLease,
7742
+ resources: normalizeSandboxShape(data.resources) ?? (id === this.id ? this.info.resources : void 0),
7478
7743
  startupDiagnostics: normalizeStartupDiagnostics(data.startupDiagnostics) ?? carryCreateFacts?.startupDiagnostics,
7479
7744
  createReceipt: normalizeSandboxCreateReceipt(data.createReceipt) ?? carryCreateFacts?.createReceipt
7480
7745
  };
@@ -7675,6 +7940,7 @@ var SandboxInstance = class SandboxInstance {
7675
7940
  }
7676
7941
  /** @internal — invoked by SandboxSession.sendMessage(). */
7677
7942
  async _sessionSendMessage(id, request, options = {}) {
7943
+ if (request.runControlRef && (request.runControlRef.environmentId !== this.id || request.runControlRef.sessionId !== id)) throw new ValidationError("runControlRef does not belong to this sandbox conversation");
7678
7944
  return this.runtime.sendSessionMessage(id, request, options);
7679
7945
  }
7680
7946
  /** @internal — invoked by SandboxSession.delete(). */
@@ -7774,7 +8040,7 @@ var SandboxInstance = class SandboxInstance {
7774
8040
  if (turn) return settleTurnDrive(turn.result);
7775
8041
  const info = await this._sessionStatus(opts.sessionId);
7776
8042
  const hasExplicitBackend = opts.backend !== void 0 || opts.model !== void 0;
7777
- const backend = applyRequestedModel(mergeRuntimeBackendConfig(this.defaultRuntimeBackend, opts.backend), opts.model);
8043
+ const backend = mergeRuntimeBackendConfig(this.defaultRuntimeBackend, applyRequestedModel(opts.backend, opts.model));
7778
8044
  if (info?.status === "queued" && hasExplicitBackend) await this.createSession({
7779
8045
  sessionId: opts.sessionId,
7780
8046
  ...backend !== void 0 ? { backend } : {}
@@ -7803,7 +8069,7 @@ var SandboxInstance = class SandboxInstance {
7803
8069
  };
7804
8070
  const result = await this._sessionResult(opts.sessionId, { executionId: info.latestExecutionId }, info);
7805
8071
  const settled = settleTurnDrive({ ...result });
7806
- if (settled.state === "awaiting_plan_decision") return settled;
8072
+ if (settled.state !== "failed" && settled.state !== "completed") return settled;
7807
8073
  if (!result.success) {
7808
8074
  const cause = result.error ?? info.failureReason?.message;
7809
8075
  return {
@@ -7836,6 +8102,18 @@ var SandboxInstance = class SandboxInstance {
7836
8102
  async driveConversationTurn(message, opts) {
7837
8103
  if (!opts.sessionId || !opts.turnId) throw new Error("Conversation sessionId and turnId are required");
7838
8104
  if (opts.wallCapMs !== void 0 && (!Number.isFinite(opts.wallCapMs) || opts.wallCapMs <= 0)) throw new Error("wallCapMs must be a positive finite duration");
8105
+ const backend = mergeRuntimeBackendConfig(this.defaultRuntimeBackend, applyRequestedModel(opts.backend, opts.model));
8106
+ const request = {
8107
+ parts: typeof message === "string" ? [{
8108
+ type: "text",
8109
+ text: message
8110
+ }] : [...message],
8111
+ turnId: opts.turnId,
8112
+ ...backend !== void 0 ? { backend } : {},
8113
+ ...opts.runControlRef !== void 0 ? { runControlRef: opts.runControlRef } : {}
8114
+ };
8115
+ const wireRequest = sessionMessageRequestBody(request);
8116
+ if (opts.runControlRef && (opts.runControlRef.sessionId !== opts.sessionId || opts.runControlRef.environmentId !== this.id)) throw new ValidationError("runControlRef does not belong to this sandbox conversation");
7839
8117
  const cached = await this.findCompletedTurn(opts.turnId, { sessionId: opts.sessionId });
7840
8118
  let info = await this._sessionStatus(opts.sessionId);
7841
8119
  if (!info) {
@@ -7843,7 +8121,8 @@ var SandboxInstance = class SandboxInstance {
7843
8121
  if (opts.allowDispatch === false) return { state: "not_admitted" };
7844
8122
  await this.createSession({
7845
8123
  sessionId: opts.sessionId,
7846
- retention: "workspace"
8124
+ retention: "workspace",
8125
+ ...backend !== void 0 ? { backend } : {}
7847
8126
  });
7848
8127
  info = await this._sessionStatus(opts.sessionId);
7849
8128
  if (!info) throw new Error("Conversation session creation was not confirmed");
@@ -7851,10 +8130,7 @@ var SandboxInstance = class SandboxInstance {
7851
8130
  const response = await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(opts.sessionId)}/admissions/${encodeURIComponent(opts.turnId)}/check`, {
7852
8131
  method: "POST",
7853
8132
  headers: { "Content-Type": "application/json" },
7854
- body: JSON.stringify({
7855
- parts: encodePromptForWire(message),
7856
- turnId: opts.turnId
7857
- }),
8133
+ body: JSON.stringify(wireRequest),
7858
8134
  signal: opts.signal
7859
8135
  });
7860
8136
  if (!response.ok) throw parseErrorResponse(response.status, await response.text(), void 0, response.headers);
@@ -7865,14 +8141,7 @@ var SandboxInstance = class SandboxInstance {
7865
8141
  if (cached) throw new StateError("Retained result has no matching request evidence", "unverified", "verified admission", void 0, "MESSAGE_ADMISSION_UNVERIFIED");
7866
8142
  if (opts.allowDispatch === false) return { state: "not_admitted" };
7867
8143
  if (isSessionInFlight(info)) return { state: "running" };
7868
- const parts = typeof message === "string" ? [{
7869
- type: "text",
7870
- text: message
7871
- }] : message;
7872
- const receipt = await this.session(opts.sessionId).sendMessage({
7873
- parts: [...parts],
7874
- turnId: opts.turnId
7875
- }, {
8144
+ const receipt = await this.session(opts.sessionId).sendMessage(request, {
7876
8145
  ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {},
7877
8146
  ...opts.signal ? { signal: opts.signal } : {}
7878
8147
  });
@@ -7884,6 +8153,7 @@ var SandboxInstance = class SandboxInstance {
7884
8153
  }
7885
8154
  if (typeof body.receipt?.info?.id !== "string" || !body.receipt.info.id || body.receipt.processing !== true) throw new Error("Runtime returned an invalid message admission receipt");
7886
8155
  executionId = body.receipt.info.id;
8156
+ if (opts.runControlRef) validateAcceptedDispatchRunRef(body.receipt.runControlRef, opts.runControlRef, this.id, opts.sessionId, executionId, `/agents/sessions/${encodeURIComponent(opts.sessionId)}/admissions/${encodeURIComponent(opts.turnId)}/check`);
7887
8157
  if (cached) return {
7888
8158
  ...settleTurnDrive(cached.result),
7889
8159
  executionId
@@ -7952,6 +8222,10 @@ var SandboxInstance = class SandboxInstance {
7952
8222
  async _sessionRuns(id) {
7953
8223
  return this.runtime.runs(id);
7954
8224
  }
8225
+ /** @internal — invoked by SandboxSession.admission(). */
8226
+ async _sessionAdmission(id, turnId, options) {
8227
+ return this.runtime.admission(id, turnId, options);
8228
+ }
7955
8229
  /** @internal — invoked by SandboxSession.events(). */
7956
8230
  async *_sessionEvents(id, opts, stopOnTurnTerminal = false) {
7957
8231
  await this.ensureRunning();
@@ -8248,6 +8522,22 @@ function settleTurnDrive(result) {
8248
8522
  plan: outcome.plan,
8249
8523
  result
8250
8524
  };
8525
+ if (outcome.status === "blocked_on_approval" && outcome.approval) return {
8526
+ state: "blocked_on_approval",
8527
+ approval: outcome.approval,
8528
+ result
8529
+ };
8530
+ if (outcome.status === "awaiting_question" && outcome.question) return {
8531
+ state: "awaiting_question",
8532
+ question: outcome.question,
8533
+ ...outcome.interaction ? { interaction: outcome.interaction } : {},
8534
+ result
8535
+ };
8536
+ if (outcome.status === "awaiting_interaction" && outcome.interaction) return {
8537
+ state: "awaiting_interaction",
8538
+ interaction: outcome.interaction,
8539
+ result
8540
+ };
8251
8541
  const text = typeof result.text === "string" ? result.text : typeof result.response === "string" ? result.response : void 0;
8252
8542
  if (outcome.status !== "success") return {
8253
8543
  state: "failed",
@@ -8327,4 +8617,4 @@ function quoteForShell(value) {
8327
8617
  return `'${value.replace(/'/g, "'\\''")}'`;
8328
8618
  }
8329
8619
  //#endregion
8330
- export { toOtelJson as A, collectAgentResponseText as C, buildTraceExportPayload as D, normalizeConnection as E, exportTraceBundle as O, collectAgentFinalMessageText as S, isToolBearingEvent as T, TerminalStream as _, WorkspaceImages as a, requestInteractiveSessionToken as b, SandboxTaskSession as c, agentInteractiveSessionPromptRequestDigest as d, InteractiveTerminalFrameLog as f, InteractiveSessionController as g, BrowserInteractiveSessionController as h, normalizeStartupDiagnostics as i, otelTraceIdForTangleTrace as k, SandboxSession as l, createInteractiveTerminalSession as m, createSandboxInstanceFromResponse as n, GPU_LEASE_PROVIDER_NAMES as o, createInteractiveTerminalCapture as p, normalizeSandboxCreateReceipt as r, MAX_EGRESS_DENIALS_LIMIT as s, SandboxInstance as t, InteractiveSessionHandle as u, TerminalStreamError as v, getSandboxEventText as w, applySandboxEventText as x, TERMINAL_WS_ECHO_SUBPROTOCOL as y };
8620
+ export { otelTraceIdForTangleTrace as A, collectAgentResponseText as C, normalizeSandboxShape as D, normalizeConnection as E, buildTraceExportPayload as O, collectAgentFinalMessageText as S, isToolBearingEvent as T, TerminalStream as _, WorkspaceImages as a, requestInteractiveSessionToken as b, SandboxTaskSession as c, agentInteractiveSessionPromptRequestDigest as d, InteractiveTerminalFrameLog as f, InteractiveSessionController as g, BrowserInteractiveSessionController as h, normalizeStartupDiagnostics as i, toOtelJson as j, exportTraceBundle as k, SandboxSession as l, createInteractiveTerminalSession as m, createSandboxInstanceFromResponse as n, GPU_LEASE_PROVIDER_NAMES as o, createInteractiveTerminalCapture as p, normalizeSandboxCreateReceipt as r, MAX_EGRESS_DENIALS_LIMIT as s, SandboxInstance as t, InteractiveSessionHandle as u, TerminalStreamError as v, getSandboxEventText as w, applySandboxEventText as x, TERMINAL_WS_ECHO_SUBPROTOCOL as y };