@tangle-network/sandbox 0.43.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-BpOFn4cB.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
  }
@@ -3591,10 +3818,35 @@ const MAX_TIMER_MS = 2147483647;
3591
3818
  */
3592
3819
  function usableTimeoutMs(timeoutMs) {
3593
3820
  if (timeoutMs === void 0) return void 0;
3594
- if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) throw new RangeError(`timeoutMs must be an integer between 1 and ${MAX_TIMER_MS}ms; got ${typeof timeoutMs === "number" ? String(timeoutMs) : typeof timeoutMs}`);
3821
+ const got = timerMsViolation(timeoutMs);
3822
+ if (got !== void 0) throw new RangeError(`timeoutMs must be an integer between 1 and ${MAX_TIMER_MS}ms; got ${got}`);
3595
3823
  return { timeoutMs };
3596
3824
  }
3597
3825
  /**
3826
+ * The execution time limit to send, or `undefined` when the caller supplied
3827
+ * none and the runtime default applies. A supplied value the runtime would
3828
+ * refuse (non-integer, non-positive, or wider than a timer can hold) is a
3829
+ * caller bug and fails here, before the request is dispatched.
3830
+ */
3831
+ function usableExecutionTtlMs(ttlMs) {
3832
+ if (ttlMs === void 0) return void 0;
3833
+ const got = timerMsViolation(ttlMs);
3834
+ if (got !== void 0) throw new ValidationError(`ttlMs must be an integer between 1 and ${MAX_TIMER_MS}ms; got ${got}`, { ttlMs: "Must be a positive integer of milliseconds" });
3835
+ return ttlMs;
3836
+ }
3837
+ /**
3838
+ * `undefined` when `value` is a duration a timer can hold (a positive integer
3839
+ * of milliseconds within the 32-bit field), else a description of what was
3840
+ * passed. The runtime `typeof` guard stays although the type says number: a
3841
+ * `Symbol` from an untyped JavaScript caller reaches here, and `${value}` on
3842
+ * one throws TypeError before the intended error could be built — the wrong
3843
+ * error for the wrong reason.
3844
+ */
3845
+ function timerMsViolation(value) {
3846
+ if (typeof value === "number" && Number.isInteger(value) && value > 0 && value <= MAX_TIMER_MS) return;
3847
+ return typeof value === "number" ? String(value) : typeof value;
3848
+ }
3849
+ /**
3598
3850
  * A sandbox instance with methods for interaction.
3599
3851
  */
3600
3852
  var SandboxInstance = class SandboxInstance {
@@ -3619,6 +3871,12 @@ var SandboxInstance = class SandboxInstance {
3619
3871
  * never by object identity, and a changed profile is sent inline.
3620
3872
  */
3621
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();
3622
3880
  constructor(client, info, defaultRuntimeBackend) {
3623
3881
  this.client = client;
3624
3882
  const incarnation = readFilesystemIncarnationTuple(info);
@@ -3703,6 +3961,15 @@ var SandboxInstance = class SandboxInstance {
3703
3961
  get gpuLease() {
3704
3962
  return this.info.gpuLease;
3705
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
+ }
3706
3973
  /** Web terminal URL for browser-based access */
3707
3974
  get url() {
3708
3975
  return this.info.connection?.webTerminalUrl;
@@ -3770,7 +4037,8 @@ var SandboxInstance = class SandboxInstance {
3770
4037
  lastActivityAt: this.lastActivityAt,
3771
4038
  expiresAt: this.expiresAt,
3772
4039
  error: this.error,
3773
- gpuLease: this.gpuLease
4040
+ gpuLease: this.gpuLease,
4041
+ resources: this.resources
3774
4042
  };
3775
4043
  }
3776
4044
  /**
@@ -3861,16 +4129,37 @@ var SandboxInstance = class SandboxInstance {
3861
4129
  }
3862
4130
  }
3863
4131
  async refreshInfo() {
3864
- 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) }] : []);
3865
4138
  if (!response.ok) {
3866
4139
  const body = await response.text();
3867
4140
  throw parseErrorResponse(response.status, body, void 0, response.headers);
3868
4141
  }
3869
4142
  const data = await response.json();
4143
+ this.directRead.adopt(data);
3870
4144
  this.info = this.parseInfo(data, this.info);
3871
4145
  sandboxStatusObservedAt.set(this, Date.now());
3872
4146
  }
3873
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
+ /**
3874
4163
  * Fetch fresh TEE attestation evidence for this sandbox.
3875
4164
  *
3876
4165
  * When `attestationNonce` is supplied, the runtime must return evidence bound
@@ -4249,7 +4538,7 @@ var SandboxInstance = class SandboxInstance {
4249
4538
  * Returns the complete response after the agent finishes.
4250
4539
  */
4251
4540
  async prompt(message, options) {
4252
- await this.ensureRunning();
4541
+ if (options?.ttlMs === void 0 || timerMsViolation(options.ttlMs) === void 0) await this.ensureRunning();
4253
4542
  const startTime = Date.now();
4254
4543
  let responseText;
4255
4544
  const outcomeTracker = createAgentRunOutcomeTracker();
@@ -4380,7 +4669,7 @@ var SandboxInstance = class SandboxInstance {
4380
4669
  * content references by hash, changed content sends inline.
4381
4670
  */
4382
4671
  buildRunBackendBody(overrideBackend, forceFullProfile, requestedModel) {
4383
- const normalized = normalizeRuntimeBackendConfig(applyRequestedModel(mergeRuntimeBackendConfig(this.defaultRuntimeBackend, overrideBackend), requestedModel));
4672
+ const normalized = normalizeRuntimeBackendConfig(mergeRuntimeBackendConfig(this.defaultRuntimeBackend, applyRequestedModel(overrideBackend, requestedModel)));
4384
4673
  if (!normalized) return normalized;
4385
4674
  const deferred = this.deferredProfileReference;
4386
4675
  if (!forceFullProfile && deferred !== void 0 && normalized.profile !== void 0 && serializeProfileSnapshot(normalized.profile) === deferred.snapshot) {
@@ -4459,6 +4748,7 @@ var SandboxInstance = class SandboxInstance {
4459
4748
  const runControlRef = options?.runControlRef ? AgentExactRunControlRefSchema.safeParse(options.runControlRef) : void 0;
4460
4749
  if (runControlRef && !runControlRef.success) throw new ValidationError("Invalid runControlRef", { runControlRef: runControlRef.error.message });
4461
4750
  if (runControlRef?.success && (runControlRef.data.environmentId !== this.id || runControlRef.data.sessionId !== options?.sessionId || runControlRef.data.executionId !== options?.executionId)) throw new ValidationError("runControlRef does not belong to this sandbox dispatch", { runControlRef: "environmentId, sessionId, and executionId must match the dispatch" });
4751
+ const ttlMs = usableExecutionTtlMs(options?.ttlMs);
4462
4752
  await this.ensureRunning();
4463
4753
  const timeoutMs = typeof options?.timeoutMs === "number" && options.timeoutMs > 0 ? options.timeoutMs : void 0;
4464
4754
  const timeoutSignal = timeoutMs ? AbortSignal.timeout(timeoutMs) : void 0;
@@ -4524,6 +4814,7 @@ var SandboxInstance = class SandboxInstance {
4524
4814
  metadata: options?.context,
4525
4815
  requireVisibleAssistantOutput: options?.requireVisibleAssistantOutput,
4526
4816
  ...timeoutMs ? { timeoutMs } : {},
4817
+ ...ttlMs !== void 0 ? { ttlMs } : {},
4527
4818
  ...options?.detach ? { detach: true } : {},
4528
4819
  backend: this.buildRunBackendBody(options?.backend, internal?.forceFullProfile ?? false, options?.model)
4529
4820
  })
@@ -7448,6 +7739,7 @@ var SandboxInstance = class SandboxInstance {
7448
7739
  expiresAt: data.expiresAt ? new Date(data.expiresAt) : void 0,
7449
7740
  error: data.error,
7450
7741
  gpuLease: data.gpuLease ?? carryCreateFacts?.gpuLease,
7742
+ resources: normalizeSandboxShape(data.resources) ?? (id === this.id ? this.info.resources : void 0),
7451
7743
  startupDiagnostics: normalizeStartupDiagnostics(data.startupDiagnostics) ?? carryCreateFacts?.startupDiagnostics,
7452
7744
  createReceipt: normalizeSandboxCreateReceipt(data.createReceipt) ?? carryCreateFacts?.createReceipt
7453
7745
  };
@@ -7648,6 +7940,7 @@ var SandboxInstance = class SandboxInstance {
7648
7940
  }
7649
7941
  /** @internal — invoked by SandboxSession.sendMessage(). */
7650
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");
7651
7944
  return this.runtime.sendSessionMessage(id, request, options);
7652
7945
  }
7653
7946
  /** @internal — invoked by SandboxSession.delete(). */
@@ -7747,7 +8040,7 @@ var SandboxInstance = class SandboxInstance {
7747
8040
  if (turn) return settleTurnDrive(turn.result);
7748
8041
  const info = await this._sessionStatus(opts.sessionId);
7749
8042
  const hasExplicitBackend = opts.backend !== void 0 || opts.model !== void 0;
7750
- const backend = applyRequestedModel(mergeRuntimeBackendConfig(this.defaultRuntimeBackend, opts.backend), opts.model);
8043
+ const backend = mergeRuntimeBackendConfig(this.defaultRuntimeBackend, applyRequestedModel(opts.backend, opts.model));
7751
8044
  if (info?.status === "queued" && hasExplicitBackend) await this.createSession({
7752
8045
  sessionId: opts.sessionId,
7753
8046
  ...backend !== void 0 ? { backend } : {}
@@ -7776,7 +8069,7 @@ var SandboxInstance = class SandboxInstance {
7776
8069
  };
7777
8070
  const result = await this._sessionResult(opts.sessionId, { executionId: info.latestExecutionId }, info);
7778
8071
  const settled = settleTurnDrive({ ...result });
7779
- if (settled.state === "awaiting_plan_decision") return settled;
8072
+ if (settled.state !== "failed" && settled.state !== "completed") return settled;
7780
8073
  if (!result.success) {
7781
8074
  const cause = result.error ?? info.failureReason?.message;
7782
8075
  return {
@@ -7803,6 +8096,108 @@ var SandboxInstance = class SandboxInstance {
7803
8096
  });
7804
8097
  return { state: "running" };
7805
8098
  }
8099
+ /** Advance exactly the named turn while retaining the native conversation.
8100
+ * Admission receipts are independent of expiring event logs. A previous
8101
+ * turn's terminal session status cannot settle a newly submitted message. */
8102
+ async driveConversationTurn(message, opts) {
8103
+ if (!opts.sessionId || !opts.turnId) throw new Error("Conversation sessionId and turnId are required");
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");
8117
+ const cached = await this.findCompletedTurn(opts.turnId, { sessionId: opts.sessionId });
8118
+ let info = await this._sessionStatus(opts.sessionId);
8119
+ if (!info) {
8120
+ if (cached) throw new StateError("Retained result has no verifiable conversation admission", "unverified", "verified admission", void 0, "MESSAGE_ADMISSION_UNVERIFIED");
8121
+ if (opts.allowDispatch === false) return { state: "not_admitted" };
8122
+ await this.createSession({
8123
+ sessionId: opts.sessionId,
8124
+ retention: "workspace",
8125
+ ...backend !== void 0 ? { backend } : {}
8126
+ });
8127
+ info = await this._sessionStatus(opts.sessionId);
8128
+ if (!info) throw new Error("Conversation session creation was not confirmed");
8129
+ }
8130
+ const response = await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(opts.sessionId)}/admissions/${encodeURIComponent(opts.turnId)}/check`, {
8131
+ method: "POST",
8132
+ headers: { "Content-Type": "application/json" },
8133
+ body: JSON.stringify(wireRequest),
8134
+ signal: opts.signal
8135
+ });
8136
+ if (!response.ok) throw parseErrorResponse(response.status, await response.text(), void 0, response.headers);
8137
+ const body = await response.json();
8138
+ if (body.requestVerified !== true || !Object.hasOwn(body, "receipt")) throw new Error("Runtime did not verify the durable message admission request");
8139
+ let executionId;
8140
+ if (body.receipt === null) {
8141
+ if (cached) throw new StateError("Retained result has no matching request evidence", "unverified", "verified admission", void 0, "MESSAGE_ADMISSION_UNVERIFIED");
8142
+ if (opts.allowDispatch === false) return { state: "not_admitted" };
8143
+ if (isSessionInFlight(info)) return { state: "running" };
8144
+ const receipt = await this.session(opts.sessionId).sendMessage(request, {
8145
+ ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {},
8146
+ ...opts.signal ? { signal: opts.signal } : {}
8147
+ });
8148
+ if (!receipt.info?.id) throw new Error("Message admission returned no execution identity");
8149
+ return {
8150
+ state: "running",
8151
+ executionId: receipt.info.id
8152
+ };
8153
+ }
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");
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`);
8157
+ if (cached) return {
8158
+ ...settleTurnDrive(cached.result),
8159
+ executionId
8160
+ };
8161
+ const run = (await this._sessionRuns(opts.sessionId)).find((candidate) => candidate.executionId === executionId);
8162
+ if (run?.status === "active") {
8163
+ const elapsedMs = Date.now() - run.startedAt;
8164
+ if (opts.wallCapMs !== void 0 && elapsedMs > opts.wallCapMs) {
8165
+ await this._interrupt(opts.sessionId, { executionId });
8166
+ return {
8167
+ state: "failed",
8168
+ executionId,
8169
+ error: "Conversation turn exceeded its authorized wall-clock duration"
8170
+ };
8171
+ }
8172
+ const requests = (await this.session(opts.sessionId).interactions()).filter((request) => request.binding.executionId === executionId);
8173
+ if (requests.length) return {
8174
+ state: "awaiting_input",
8175
+ executionId,
8176
+ requests
8177
+ };
8178
+ return {
8179
+ state: "running",
8180
+ executionId,
8181
+ startedAt: new Date(run.startedAt),
8182
+ elapsedMs
8183
+ };
8184
+ }
8185
+ if (!run) {
8186
+ const completed = await this.findCompletedTurn(opts.turnId, { sessionId: opts.sessionId });
8187
+ return completed ? {
8188
+ ...settleTurnDrive(completed.result),
8189
+ executionId
8190
+ } : {
8191
+ state: "failed",
8192
+ executionId,
8193
+ error: "The admitted turn's result is unavailable; execution was not repeated"
8194
+ };
8195
+ }
8196
+ return {
8197
+ ...settleTurnDrive({ ...await this._sessionResult(opts.sessionId, { executionId }, info) }),
8198
+ executionId
8199
+ };
8200
+ }
7806
8201
  /**
7807
8202
  * Mint a scoped, time-bounded JWT for browser access (Issue #913 Gap 1).
7808
8203
  * Authority is the caller's `TANGLE_API_KEY` (sk-tan-*); signing secrets
@@ -7827,6 +8222,10 @@ var SandboxInstance = class SandboxInstance {
7827
8222
  async _sessionRuns(id) {
7828
8223
  return this.runtime.runs(id);
7829
8224
  }
8225
+ /** @internal — invoked by SandboxSession.admission(). */
8226
+ async _sessionAdmission(id, turnId, options) {
8227
+ return this.runtime.admission(id, turnId, options);
8228
+ }
7830
8229
  /** @internal — invoked by SandboxSession.events(). */
7831
8230
  async *_sessionEvents(id, opts, stopOnTurnTerminal = false) {
7832
8231
  await this.ensureRunning();
@@ -8123,6 +8522,22 @@ function settleTurnDrive(result) {
8123
8522
  plan: outcome.plan,
8124
8523
  result
8125
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
+ };
8126
8541
  const text = typeof result.text === "string" ? result.text : typeof result.response === "string" ? result.response : void 0;
8127
8542
  if (outcome.status !== "success") return {
8128
8543
  state: "failed",
@@ -8202,4 +8617,4 @@ function quoteForShell(value) {
8202
8617
  return `'${value.replace(/'/g, "'\\''")}'`;
8203
8618
  }
8204
8619
  //#endregion
8205
- 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 };