@tangle-network/sandbox 0.60.69 → 0.60.74

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.
Files changed (46) hide show
  1. package/dist/agent/index.d.ts +4 -4
  2. package/dist/agent/index.js +4 -4
  3. package/dist/agent/preview.d.ts +1 -1
  4. package/dist/{agent-run-outcome-BBk2-5vp.d.ts → agent-run-outcome-eZF8RuUN.d.ts} +1 -1
  5. package/dist/auth/index.d.ts +1 -1
  6. package/dist/auth/index.js +1 -1
  7. package/dist/backend-types-D6bYbvMB.js +42 -0
  8. package/dist/{browser-interactive-control-controller-JUW3gOGH.d.ts → browser-interactive-control-controller-rpTbyvAS.d.ts} +1 -1
  9. package/dist/{chunked-upload-BklCn3Li.js → chunked-upload-CDrLMO8N.js} +1 -1
  10. package/dist/{chunked-upload-file-Cp-iWsWN.js → chunked-upload-file-BwbqHWUX.js} +1 -1
  11. package/dist/{cli-auth-bundle-D61iX68d.js → cli-auth-bundle-cSJjPeFF.js} +2 -2
  12. package/dist/{client-DVouBFPR.d.ts → client-BujziOIc.d.ts} +10 -6
  13. package/dist/{client-DUDqUYDG.js → client-C7Y6waVg.js} +20 -9
  14. package/dist/collaboration/index.d.ts +1 -1
  15. package/dist/collaboration/index.js +1 -1
  16. package/dist/{collaboration-B2g1j2ey.js → collaboration-CTbq2OYh.js} +1 -1
  17. package/dist/core.d.ts +6 -6
  18. package/dist/core.js +3 -3
  19. package/dist/{errors-5j_Hlkm-.d.ts → errors-Bj5DL2ge.d.ts} +61 -2
  20. package/dist/{errors-iWIsey1D.js → errors-C8YcR1BL.js} +31 -1
  21. package/dist/{index-DaJrtipt.d.ts → index-CP9a77KP.d.ts} +2 -2
  22. package/dist/index.d.ts +14 -15
  23. package/dist/index.js +9 -9
  24. package/dist/intelligence/index.js +1 -1
  25. package/dist/interactive-control.d.ts +1 -1
  26. package/dist/{interactive-controller-DaYmUCO_.js → interactive-controller-BFbCkMq4.js} +213 -21
  27. package/dist/{lines-D07bn-mu.d.ts → lines-_rRdwxof.d.ts} +1 -1
  28. package/dist/lines.d.ts +1 -1
  29. package/dist/lines.js +1 -1
  30. package/dist/{local-cli-auth-t8KUbrfI.js → local-cli-auth-CBV7Vjk5.js} +1 -1
  31. package/dist/{managed-process-RMyVq_du.d.ts → managed-process-CPHeQONO.d.ts} +1 -1
  32. package/dist/{preview-dIOd13_U.d.ts → preview-n41aOXde.d.ts} +3 -3
  33. package/dist/runtime.d.ts +5 -6
  34. package/dist/runtime.js +3 -3
  35. package/dist/{sandbox-Dg0WI1ZF.js → sandbox-DGoQMthD.js} +678 -69
  36. package/dist/{sandbox-C7wOeFZB.d.ts → sandbox-DfSqEr3f.d.ts} +70 -17
  37. package/dist/tangle/index.d.ts +1 -1
  38. package/dist/tangle/index.js +1 -1
  39. package/dist/{tangle-CaY9_VGA.js → tangle-vyeLQFFg.js} +2 -2
  40. package/dist/{terminal-stream-CV1pMSKC.d.ts → terminal-stream-jdYomM1m.d.ts} +123 -4
  41. package/dist/{types-BLCY5T4s.d.ts → types-Mi83KD0D.d.ts} +155 -21
  42. package/package.json +5 -5
  43. package/dist/backend-types-C7b_Gpa0.js +0 -59
  44. package/dist/interactive-controller-DNbLzamS.d.ts +0 -40
  45. /package/dist/{index-BgmgfYZZ.d.ts → index-DO7GVpk_.d.ts} +0 -0
  46. /package/dist/{index-DHuHjNie.d.ts → index-DZ27pdB8.d.ts} +0 -0
@@ -1,12 +1,12 @@
1
- import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
2
- import { A as requestedPublicProfileDigest, C as encodeTextForWire, E as assertCurrentBackendType, F as deriveAgentResultOutcome, N as withoutRuntimeSecrets, O as mergeRuntimeBackendConfig, P as createAgentRunOutcomeTracker, S as encodePromptForWire, T as applyRequestedModel, _ as resolveTraceId, b as resolveDispatchRunIdentity, c as requestScopedToken, d as normalizeSessionInfo, f as sessionMessageRequestBody, g as mintTraceId, h as isTraceId, j as requestedSecretProfilePublicDigest, k as normalizeRuntimeBackendConfig, l as SandboxRuntimeApi, m as TRACE_ID_HEADER, n as InteractiveSessionController, o as assertScopedTokenActive, p as waitForRetryAfter, r as TerminalStream, u as isRetryableCredentialRefusal, v as appendSessionIdQuery, w as parseSSEStream, x as validateAcceptedDispatchRunRef, y as sessionHeaders } from "./interactive-controller-DaYmUCO_.js";
3
- import { _ as TimeoutError, b as parseResponseError, c as NetworkError, d as QuotaError, g as StreamInterruptedError, h as StateError, l as NotFoundError, m as ServerError, n as CapabilityError, p as SandboxError, r as EdgeNotReadyError, t as AuthError, v as ValidationError, x as readResponseJson, y as parseErrorResponse } from "./errors-iWIsey1D.js";
1
+ import { r as backendTypeSchema } from "./backend-types-D6bYbvMB.js";
2
+ import { A as normalizeRuntimeBackendConfig, C as encodePromptForWire, D as assertCurrentBackendType, E as applyRequestedModel, F as createAgentRunOutcomeTracker, I as deriveAgentResultOutcome, M as requestedSecretProfilePublicDigest, P as withoutRuntimeSecrets, S as validateAcceptedDispatchRunRef, T as parseSSEStream, _ as mintTraceId, a as terminalUpgradeHeadersSupported, b as sessionHeaders, d as isRetryableCredentialRefusal, f as normalizeSessionInfo, g as isTraceId, h as TRACE_ID_HEADER, i as TerminalStreamError, j as requestedPublicProfileDigest, k as mergeRuntimeBackendConfig, l as requestScopedToken, m as waitForRetryAfter, n as InteractiveSessionController, p as sessionMessageRequestBody, r as TerminalStream, s as assertScopedTokenActive, u as SandboxRuntimeApi, v as resolveTraceId, w as encodeTextForWire, x as resolveDispatchRunIdentity, y as appendSessionIdQuery } from "./interactive-controller-BFbCkMq4.js";
3
+ import { S as readResponseJson, _ as StreamInterruptedError, b as parseErrorResponse, f as QuotaError, g as StateError, h as ServerError, i as EdgeNotReadyError, l as NetworkError, m as SandboxError, r as CapabilityError, t as AuthError, u as NotFoundError, v as TimeoutError, x as parseResponseError, y as ValidationError } from "./errors-C8YcR1BL.js";
4
4
  import { d as awaitWithAbort, f as combineAbortSignals, g as interactiveSessionStatusResponseSchema, h as interactiveSessionControlValidationResponseSchema, l as createInteractiveControlHolderId, m as interactiveSessionControlReleaseResponseSchema, p as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-BJf0P_J4.js";
5
5
  import { SandboxLines } from "./lines.js";
6
- import { l as SANDBOX_PROXY_REQUEST_MAX_BYTES, s as uploadChunked } from "./chunked-upload-BklCn3Li.js";
7
- import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-D61iX68d.js";
8
- import { AgentExactRunControlRefSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimRequestSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionPromptCommandSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStartSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentInteractiveSessionStopCommandSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, InteractionAcknowledgementSchema, InteractionBindingSchema, InteractionRequestSchema, InteractionResponseCommandSchema, InteractionResponseSchema, TerminalInputSchema, TerminalOutputEventSchema, TerminalReplayWindowSchema, TerminalResizeSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimIsNewer, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, canonicalCandidateJson, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
6
+ import { l as SANDBOX_PROXY_REQUEST_MAX_BYTES, s as uploadChunked } from "./chunked-upload-CDrLMO8N.js";
7
+ import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-cSJjPeFF.js";
9
8
  import { z } from "zod";
9
+ import { AgentExactRunControlRefSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimRequestSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionPromptCommandSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStartSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentInteractiveSessionStopCommandSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, InteractionAcknowledgementSchema, InteractionBindingSchema, InteractionRequestSchema, InteractionResponseCommandSchema, InteractionResponseSchema, TerminalInputSchema, TerminalOutputEventSchema, TerminalReplayWindowSchema, TerminalResizeSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimIsNewer, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, canonicalCandidateJson, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
10
10
  import { AgentInteractiveSessionControlClaimSchema as AgentInteractiveSessionControlClaimSchema$1, AgentInteractiveSessionPromptAcknowledgementSchema as AgentInteractiveSessionPromptAcknowledgementSchema$1, AgentInteractiveSessionRefSchema as AgentInteractiveSessionRefSchema$1, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema as AgentInteractiveSessionStopAcknowledgementSchema$1 } from "@tangle-network/agent-interface/environment-interactive-control";
11
11
  import { readTokenCostUsd, readTokenUsage } from "@tangle-network/agent-core";
12
12
  import { createHash } from "node:crypto";
@@ -210,6 +210,244 @@ function snakeCase(value) {
210
210
  return value.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
211
211
  }
212
212
  //#endregion
213
+ //#region src/lib/keep-alive-fetch.ts
214
+ /** How long an idle SDK socket stays open. The servers keep theirs open for 35 s and more. */
215
+ const KEEP_ALIVE_TIMEOUT_MS = 6e4;
216
+ const GLOBAL_DISPATCHER = Symbol.for("undici.globalDispatcher.1");
217
+ /** Report a span. A hook that throws must never fail an SDK call. */
218
+ function emitTiming(hook, entry) {
219
+ if (!hook) return;
220
+ try {
221
+ hook(entry);
222
+ } catch {}
223
+ }
224
+ /** Milliseconds, at 0.1 ms: the resolution these spans can honestly claim. */
225
+ function ms(value) {
226
+ return Math.round(value * 10) / 10;
227
+ }
228
+ let cachedHost;
229
+ let cachedAgent = null;
230
+ function readGlobalDispatcher() {
231
+ const read = () => globalThis[GLOBAL_DISPATCHER];
232
+ const host = read();
233
+ if (host) return host;
234
+ globalThis.Headers;
235
+ return read();
236
+ }
237
+ /** The options undici stored on an Agent, if this version keeps them where we look. */
238
+ function agentOptions(agent) {
239
+ for (const symbol of Object.getOwnPropertySymbols(agent)) {
240
+ if (symbol.description !== "options") continue;
241
+ const value = agent[symbol];
242
+ if (value && typeof value === "object") return value;
243
+ }
244
+ }
245
+ function buildKeepAliveAgent(host) {
246
+ const AgentClass = Object.getPrototypeOf(host)?.constructor;
247
+ if (typeof AgentClass !== "function" || AgentClass.name !== "Agent") return null;
248
+ const options = agentOptions(host);
249
+ if (!options || options.keepAliveTimeout !== void 0) return null;
250
+ try {
251
+ return new AgentClass({
252
+ ...options,
253
+ keepAliveTimeout: KEEP_ALIVE_TIMEOUT_MS
254
+ });
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+ /**
260
+ * The dispatcher SDK calls pass to `fetch`, or `undefined` to keep the host's.
261
+ * Rebuilt when the host replaces its global dispatcher, so a test that installs
262
+ * a mock agent, or an app that reconfigures its own, is never bypassed.
263
+ */
264
+ function keepAliveDispatcher() {
265
+ const host = readGlobalDispatcher();
266
+ if (!host) return void 0;
267
+ if (host !== cachedHost) {
268
+ const previous = cachedAgent;
269
+ cachedHost = host;
270
+ cachedAgent = buildKeepAliveAgent(host);
271
+ Promise.resolve(previous?.close?.()).catch(() => void 0);
272
+ }
273
+ return cachedAgent ?? void 0;
274
+ }
275
+ /**
276
+ * In-flight requests by undici request. A response whose body is never read
277
+ * never completes, so the map is bounded rather than trusted to drain.
278
+ */
279
+ const MAX_LIVE_CAPTURES = 256;
280
+ const captures = /* @__PURE__ */ new Map();
281
+ const socketMarks = /* @__PURE__ */ new WeakMap();
282
+ let dispatching;
283
+ let observing;
284
+ function subscribeChannels(channels) {
285
+ const now = () => performance.now();
286
+ channels.subscribe("net.client.socket", (message) => {
287
+ const socket = message.socket;
288
+ if (!socket || captures.size === 0) return;
289
+ const marks = {
290
+ createdAt: now(),
291
+ claimed: false
292
+ };
293
+ socketMarks.set(socket, marks);
294
+ const once = socket.once;
295
+ if (typeof once !== "function") return;
296
+ once.call(socket, "lookup", () => {
297
+ marks.lookupAt = now();
298
+ });
299
+ once.call(socket, "connect", () => {
300
+ marks.connectAt = now();
301
+ });
302
+ once.call(socket, "secureConnect", () => {
303
+ marks.secureAt = now();
304
+ });
305
+ });
306
+ channels.subscribe("undici:request:create", (message) => {
307
+ const request = message.request;
308
+ if (!dispatching || !request) return;
309
+ dispatching.request = request;
310
+ captures.set(request, dispatching);
311
+ if (captures.size > MAX_LIVE_CAPTURES) {
312
+ const oldest = captures.keys().next().value;
313
+ if (oldest !== void 0) captures.delete(oldest);
314
+ }
315
+ });
316
+ channels.subscribe("undici:client:sendHeaders", (message) => {
317
+ const { request, socket } = message;
318
+ const capture = request ? captures.get(request) : void 0;
319
+ if (!capture) return;
320
+ capture.sentAt = now();
321
+ const marks = socket ? socketMarks.get(socket) : void 0;
322
+ if (marks && !marks.claimed) {
323
+ marks.claimed = true;
324
+ capture.marks = marks;
325
+ }
326
+ });
327
+ channels.subscribe("undici:request:headers", (message) => {
328
+ const request = message.request;
329
+ const capture = request ? captures.get(request) : void 0;
330
+ if (capture) capture.headersAt = now();
331
+ });
332
+ channels.subscribe("undici:request:trailers", (message) => {
333
+ const request = message.request;
334
+ const capture = request ? captures.get(request) : void 0;
335
+ if (!capture) return;
336
+ capture.doneAt = now();
337
+ captures.delete(request);
338
+ capture.finish();
339
+ });
340
+ channels.subscribe("undici:request:error", (message) => {
341
+ const request = message.request;
342
+ const capture = request ? captures.get(request) : void 0;
343
+ if (!capture) return;
344
+ capture.failed = true;
345
+ capture.doneAt = now();
346
+ captures.delete(request);
347
+ capture.finish();
348
+ });
349
+ }
350
+ /** Subscribe once. False where the runtime has no Node diagnostics channels. */
351
+ function observeRequests() {
352
+ observing ??= import("node:diagnostics_channel").then((channels) => {
353
+ if (typeof channels.subscribe !== "function") return false;
354
+ subscribeChannels(channels);
355
+ return true;
356
+ }, () => false);
357
+ return observing;
358
+ }
359
+ /** A dispatcher that tells `capture` which undici request its dispatch created. */
360
+ function tagged(base, capture) {
361
+ return new Proxy(base, { get(target, property) {
362
+ if (property === "dispatch") return (options, handler) => {
363
+ dispatching = capture;
364
+ try {
365
+ return target.dispatch(options, handler);
366
+ } finally {
367
+ dispatching = void 0;
368
+ }
369
+ };
370
+ const value = Reflect.get(target, property, target);
371
+ return typeof value === "function" ? value.bind(target) : value;
372
+ } });
373
+ }
374
+ function phasesOf(capture) {
375
+ if (capture.sentAt === void 0 || capture.headersAt === void 0) return;
376
+ const phases = { ttfbMs: ms(capture.headersAt - capture.sentAt) };
377
+ const marks = capture.marks;
378
+ if (marks?.connectAt !== void 0) {
379
+ if (marks.lookupAt !== void 0) phases.dnsMs = ms(marks.lookupAt - marks.createdAt);
380
+ phases.connectMs = ms(marks.connectAt - (marks.lookupAt ?? marks.createdAt));
381
+ if (marks.secureAt !== void 0) phases.tlsMs = ms(marks.secureAt - marks.connectAt);
382
+ }
383
+ if (capture.doneAt !== void 0 && !capture.failed) phases.bodyMs = ms(capture.doneAt - capture.headersAt);
384
+ return phases;
385
+ }
386
+ /**
387
+ * `fetch` for an SDK call: the keep-alive dispatcher on Node, and a timing
388
+ * entry per request when the client has a hook. Calls `globalThis.fetch` at
389
+ * call time, so a caller's fetch override still receives the request.
390
+ */
391
+ async function fetchWithKeepAlive(url, init, options) {
392
+ let dispatcher = keepAliveDispatcher();
393
+ const hook = options.onTiming;
394
+ if (!hook) return dispatcher ? globalThis.fetch(url, {
395
+ ...init,
396
+ dispatcher
397
+ }) : globalThis.fetch(url, init);
398
+ const startedAt = performance.now();
399
+ const method = init.method ?? "GET";
400
+ const observed = await observeRequests();
401
+ const host = dispatcher ?? (observed ? readGlobalDispatcher() : void 0);
402
+ let capture;
403
+ let finished;
404
+ if (observed && host) {
405
+ let finish = () => {};
406
+ finished = new Promise((resolve) => {
407
+ finish = resolve;
408
+ });
409
+ capture = {
410
+ startedAt,
411
+ finish
412
+ };
413
+ dispatcher = tagged(host, capture);
414
+ }
415
+ let response;
416
+ try {
417
+ response = await globalThis.fetch(url, dispatcher ? {
418
+ ...init,
419
+ dispatcher
420
+ } : init);
421
+ } catch (error) {
422
+ if (capture?.request) captures.delete(capture.request);
423
+ emitTiming(hook, {
424
+ name: "sdk.request",
425
+ durMs: ms(performance.now() - startedAt),
426
+ desc: "failed",
427
+ method,
428
+ path: options.path
429
+ });
430
+ throw error;
431
+ }
432
+ const report = () => {
433
+ const phases = capture ? phasesOf(capture) : void 0;
434
+ const socket = phases ? capture?.marks ? "new" : "reused" : void 0;
435
+ emitTiming(hook, {
436
+ name: "sdk.request",
437
+ durMs: ms((capture?.doneAt ?? capture?.headersAt ?? performance.now()) - startedAt),
438
+ desc: socket ? `socket=${socket}` : "",
439
+ method,
440
+ path: options.path,
441
+ status: response.status,
442
+ ...socket ? { socket } : {},
443
+ ...phases ? { phases } : {}
444
+ });
445
+ };
446
+ if (capture?.request && finished) finished.then(report);
447
+ else report();
448
+ return response;
449
+ }
450
+ //#endregion
213
451
  //#region src/lib/response-rewrap.ts
214
452
  /**
215
453
  * Response wrappers that must outlive the fetch Response they wrap.
@@ -1756,7 +1994,7 @@ async function submitSandboxInteractionCommand(transport, sessionId, command, op
1756
1994
  * `data.properties.part.text` when replayed by the session
1757
1995
  * endpoint.
1758
1996
  */
1759
- function isRecord$1(v) {
1997
+ function isRecord$2(v) {
1760
1998
  return typeof v === "object" && v !== null;
1761
1999
  }
1762
2000
  /** The first candidate that is actually a string. Using `typeof` rather than a
@@ -1769,9 +2007,9 @@ function firstString(...candidates) {
1769
2007
  /** Snapshot text wins when a runtime sends both its snapshot and delta. */
1770
2008
  function messageTextUpdate(event) {
1771
2009
  if (event.type !== "message.part.updated") return void 0;
1772
- const data = isRecord$1(event.data) ? event.data : {};
1773
- const properties = isRecord$1(data.properties) ? data.properties : void 0;
1774
- const part = isRecord$1(data.part) ? data.part : isRecord$1(properties?.part) ? properties.part : void 0;
2010
+ const data = isRecord$2(event.data) ? event.data : {};
2011
+ const properties = isRecord$2(data.properties) ? data.properties : void 0;
2012
+ const part = isRecord$2(data.part) ? data.part : isRecord$2(properties?.part) ? properties.part : void 0;
1775
2013
  if (part?.type !== "text") return void 0;
1776
2014
  const snapshot = firstString(part.text, part.content);
1777
2015
  if (snapshot !== void 0) return {
@@ -1785,7 +2023,7 @@ function messageTextUpdate(event) {
1785
2023
  };
1786
2024
  }
1787
2025
  function getSandboxEventText(event) {
1788
- const data = isRecord$1(event.data) ? event.data : {};
2026
+ const data = isRecord$2(event.data) ? event.data : {};
1789
2027
  if (event.type === "result") return firstString(data.finalText, data.response, data.output, data.content, data.text);
1790
2028
  if (event.type === "token") return firstString(data.value, data.delta, data.text, data.content);
1791
2029
  if (event.type !== "message.part.updated") return;
@@ -1872,11 +2110,11 @@ function namesATool(type) {
1872
2110
  }
1873
2111
  function isToolBearingEvent(event) {
1874
2112
  if (namesATool(event.type)) return true;
1875
- const data = isRecord$1(event.data) ? event.data : void 0;
2113
+ const data = isRecord$2(event.data) ? event.data : void 0;
1876
2114
  if (!data) return false;
1877
2115
  if (event.type === "raw" && typeof data.type === "string") return namesATool(data.type);
1878
- const properties = isRecord$1(data.properties) ? data.properties : void 0;
1879
- const part = isRecord$1(data.part) ? data.part : isRecord$1(properties?.part) ? properties.part : void 0;
2116
+ const properties = isRecord$2(data.properties) ? data.properties : void 0;
2117
+ const part = isRecord$2(data.part) ? data.part : isRecord$2(properties?.part) ? properties.part : void 0;
1880
2118
  return typeof part?.type === "string" && namesATool(part.type);
1881
2119
  }
1882
2120
  /**
@@ -1932,9 +2170,9 @@ function collectAgentFinalMessageText(events) {
1932
2170
  for (let i = lastToolAt + 1; i < end; i++) {
1933
2171
  const event = events[i];
1934
2172
  if (event.type !== "message.part.updated") continue;
1935
- const data = isRecord$1(event.data) ? event.data : {};
1936
- const properties = isRecord$1(data.properties) ? data.properties : void 0;
1937
- const part = isRecord$1(data.part) ? data.part : isRecord$1(properties?.part) ? properties.part : void 0;
2173
+ const data = isRecord$2(event.data) ? event.data : {};
2174
+ const properties = isRecord$2(data.properties) ? data.properties : void 0;
2175
+ const part = isRecord$2(data.part) ? data.part : isRecord$2(properties?.part) ? properties.part : void 0;
1938
2176
  if (part?.type !== "text") continue;
1939
2177
  const update = messageTextUpdate(event);
1940
2178
  const text = update?.text;
@@ -2075,6 +2313,172 @@ function waitForReconnect(ms, signal) {
2075
2313
  signal?.addEventListener("abort", onAbort, { once: true });
2076
2314
  });
2077
2315
  }
2316
+ //#endregion
2317
+ //#region src/operation.ts
2318
+ /**
2319
+ * A stop or snapshot the API accepted with `wait: false`.
2320
+ *
2321
+ * The verb answered as soon as the platform durably recorded it; the work
2322
+ * finishes in the background. `wait()` polls the operation until it is
2323
+ * terminal and resolves with it, or throws {@link SandboxOperationFailedError}
2324
+ * carrying the failure code. A verb the API finished synchronously comes back
2325
+ * as an operation that is already `succeeded`.
2326
+ */
2327
+ const FIRST_POLL_MS = 250;
2328
+ const MAX_POLL_MS = 2e3;
2329
+ const DEFAULT_WAIT_TIMEOUT_MS = 10 * 6e4;
2330
+ /** An accepted operation ended in failure. `code` names why. */
2331
+ var SandboxOperationFailedError = class extends SandboxError {
2332
+ operation;
2333
+ constructor(operation) {
2334
+ super(operation.error?.message ?? `Sandbox ${operation.kind} operation ${operation.id} failed`, operation.error?.code ?? "OPERATION_FAILED");
2335
+ this.name = "SandboxOperationFailedError";
2336
+ this.operation = operation;
2337
+ }
2338
+ };
2339
+ function isRecord$1(value) {
2340
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2341
+ }
2342
+ const KINDS = [
2343
+ "stop",
2344
+ "snapshot",
2345
+ "delete"
2346
+ ];
2347
+ const STATES = [
2348
+ "accepted",
2349
+ "running",
2350
+ "succeeded",
2351
+ "failed"
2352
+ ];
2353
+ function parseSnapshot(value) {
2354
+ if (!isRecord$1(value) || typeof value.snapshotId !== "string") return;
2355
+ return {
2356
+ snapshotId: value.snapshotId,
2357
+ createdAt: new Date(typeof value.createdAt === "string" ? value.createdAt : Date.now()),
2358
+ ...typeof value.sizeBytes === "number" ? { sizeBytes: value.sizeBytes } : {},
2359
+ tags: Array.isArray(value.tags) ? value.tags.filter((tag) => typeof tag === "string") : []
2360
+ };
2361
+ }
2362
+ /** Parse the API's operation body; throws on a body that is not one. */
2363
+ function parseSandboxOperation(value) {
2364
+ if (!isRecord$1(value) || typeof value.id !== "string" || typeof value.sandboxId !== "string" || typeof value.statusUrl !== "string" || typeof value.acceptedAt !== "string" || !KINDS.includes(value.kind) || !STATES.includes(value.state)) throw new SandboxError(`The API answered an operation that does not match the contract: ${JSON.stringify(value).slice(0, 200)}`, "UPSTREAM_CONTRACT_VIOLATION", 502);
2365
+ const result = isRecord$1(value.result) ? value.result : void 0;
2366
+ const snapshot = parseSnapshot(result?.snapshot);
2367
+ const durability = result?.durability === "local" || result?.durability === "remote" ? result.durability : void 0;
2368
+ const error = isRecord$1(value.error) ? value.error : void 0;
2369
+ return {
2370
+ id: value.id,
2371
+ kind: value.kind,
2372
+ sandboxId: value.sandboxId,
2373
+ state: value.state,
2374
+ ...typeof value.phase === "string" ? { phase: value.phase } : {},
2375
+ acceptedAt: new Date(value.acceptedAt),
2376
+ ...typeof value.completedAt === "string" ? { completedAt: new Date(value.completedAt) } : {},
2377
+ statusUrl: value.statusUrl,
2378
+ ...result ? { result: {
2379
+ ...durability ? { durability } : {},
2380
+ ...snapshot ? { snapshot } : {},
2381
+ ...isRecord$1(result.sandbox) ? { sandbox: result.sandbox } : {}
2382
+ } } : {},
2383
+ ...error && typeof error.code === "string" && typeof error.message === "string" ? { error: {
2384
+ code: error.code,
2385
+ message: error.message
2386
+ } } : {}
2387
+ };
2388
+ }
2389
+ function isTerminalOperation(info) {
2390
+ return info.state === "succeeded" || info.state === "failed";
2391
+ }
2392
+ var SandboxOperation = class SandboxOperation {
2393
+ #info;
2394
+ #client;
2395
+ #onSettled;
2396
+ #settled = false;
2397
+ /**
2398
+ * @param client - null for a verb that already finished synchronously.
2399
+ * @param onSettled - runs once when the operation is first seen succeeded.
2400
+ */
2401
+ constructor(info, client, onSettled) {
2402
+ this.#info = info;
2403
+ this.#client = client;
2404
+ this.#onSettled = onSettled;
2405
+ }
2406
+ /** A verb the API finished synchronously, as a succeeded operation. */
2407
+ static completed(kind, sandboxId, result) {
2408
+ const now = /* @__PURE__ */ new Date();
2409
+ return new SandboxOperation({
2410
+ id: "",
2411
+ kind,
2412
+ sandboxId,
2413
+ state: "succeeded",
2414
+ acceptedAt: now,
2415
+ completedAt: now,
2416
+ statusUrl: "",
2417
+ ...result ? { result } : {}
2418
+ }, null);
2419
+ }
2420
+ get id() {
2421
+ return this.#info.id;
2422
+ }
2423
+ get state() {
2424
+ return this.#info.state;
2425
+ }
2426
+ /** The last state read. */
2427
+ get info() {
2428
+ return this.#info;
2429
+ }
2430
+ /** Read the operation's current state. */
2431
+ async refresh() {
2432
+ if (!this.#client || isTerminalOperation(this.#info)) {
2433
+ await this.#settle();
2434
+ return this.#info;
2435
+ }
2436
+ const response = await this.#client.fetch(`/v1/sandboxes/${encodeURIComponent(this.#info.sandboxId)}/operations/${encodeURIComponent(this.#info.id)}`);
2437
+ if (!response.ok) {
2438
+ const body = await response.text();
2439
+ throw new SandboxError(`Reading operation ${this.#info.id} failed (${response.status}): ${body.slice(0, 200)}`, response.status === 404 ? "OPERATION_NOT_FOUND" : "OPERATION_READ_FAILED", response.status);
2440
+ }
2441
+ this.#info = parseSandboxOperation(await response.json());
2442
+ await this.#settle();
2443
+ return this.#info;
2444
+ }
2445
+ async #settle() {
2446
+ if (this.#settled || this.#info.state !== "succeeded") return;
2447
+ this.#settled = true;
2448
+ await this.#onSettled?.(this.#info);
2449
+ }
2450
+ /**
2451
+ * Poll until the operation is terminal (250 ms, doubling to 2 s). Resolves
2452
+ * with a succeeded operation; throws {@link SandboxOperationFailedError} on
2453
+ * a failed one and {@link TimeoutError} past `timeoutMs` (default 10 min).
2454
+ */
2455
+ async wait(options = {}) {
2456
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
2457
+ const startedAt = Date.now();
2458
+ const { signal } = options;
2459
+ let delayMs = FIRST_POLL_MS;
2460
+ let info = await this.refresh();
2461
+ while (!isTerminalOperation(info)) {
2462
+ if (Date.now() - startedAt + delayMs > timeoutMs) throw new TimeoutError(timeoutMs, `Timed out waiting for ${info.kind} operation ${info.id} (last state ${info.state})`);
2463
+ signal?.throwIfAborted();
2464
+ await new Promise((resolve, reject) => {
2465
+ const onAbort = () => {
2466
+ clearTimeout(timer);
2467
+ reject(signal?.reason);
2468
+ };
2469
+ const timer = setTimeout(() => {
2470
+ signal?.removeEventListener("abort", onAbort);
2471
+ resolve();
2472
+ }, delayMs);
2473
+ signal?.addEventListener("abort", onAbort, { once: true });
2474
+ });
2475
+ delayMs = Math.min(delayMs * 2, MAX_POLL_MS);
2476
+ info = await this.refresh();
2477
+ }
2478
+ if (info.state === "failed") throw new SandboxOperationFailedError(info);
2479
+ return info;
2480
+ }
2481
+ };
2078
2482
  const CODEX_SYSTEM_PROMPT_FILE = ".codex/system-prompt.md";
2079
2483
  const OPENCODE_APPEND_SYSTEM_PROMPT_FILE = ".opencode/agent-system-prompt.md";
2080
2484
  const OPENCODE_CONFIG_FILE = "opencode.json";
@@ -2682,10 +3086,107 @@ var SandboxInteractiveOperations = class {
2682
3086
  };
2683
3087
  //#endregion
2684
3088
  //#region src/sandbox-interactive-terminal.ts
3089
+ /**
3090
+ * How long a refused API-key upgrade keeps this sandbox handle on scoped
3091
+ * tokens. One refusal is evidence about the gateway (a deployment that does
3092
+ * not yet take the key on an upgrade), so the next attaches skip the failed
3093
+ * dial instead of paying it each time.
3094
+ */
3095
+ const API_KEY_UPGRADE_REFUSAL_TTL_MS = 5 * 6e4;
3096
+ /**
3097
+ * A refused upgrade: the socket never opened. A WebSocket client cannot read
3098
+ * the HTTP status, so this stands for 401 and 403 and also for a network drop;
3099
+ * the scoped-token dial that follows tells them apart.
3100
+ */
3101
+ function isUpgradeRefusal(error) {
3102
+ return error instanceof TerminalStreamError && error.beforeOpen;
3103
+ }
3104
+ /**
3105
+ * Hold the caller's `onClose` until the stream is ready. A dial that is
3106
+ * abandoned for a scoped-token dial must not report a close the caller never
3107
+ * saw open; once ready, every callback passes straight through.
3108
+ */
3109
+ function holdCloseUntilReady(handlers) {
3110
+ let ready = false;
3111
+ let held;
3112
+ return {
3113
+ handlers: {
3114
+ ...handlers,
3115
+ onReady: (info) => {
3116
+ ready = true;
3117
+ handlers?.onReady?.(info);
3118
+ },
3119
+ onClose: (code, reason) => {
3120
+ if (ready) handlers?.onClose?.(code, reason);
3121
+ else held = {
3122
+ code,
3123
+ reason
3124
+ };
3125
+ }
3126
+ },
3127
+ releaseHeldClose: () => {
3128
+ if (held !== void 0) handlers?.onClose?.(held.code, held.reason);
3129
+ held = void 0;
3130
+ }
3131
+ };
3132
+ }
2685
3133
  var SandboxInteractiveTerminalOperations = class {
3134
+ apiKeyRefusedUntil = 0;
2686
3135
  constructor(host) {
2687
3136
  this.host = host;
2688
3137
  }
3138
+ apiKeyDial() {
3139
+ if (Date.now() < this.apiKeyRefusedUntil) return void 0;
3140
+ if (!terminalUpgradeHeadersSupported()) return void 0;
3141
+ return this.host.terminalApiKeyDial?.();
3142
+ }
3143
+ /**
3144
+ * Open the stream for `streamPath`. A Node caller sends the API key as the
3145
+ * upgrade's `Authorization` header: the gateway takes its owner path for
3146
+ * it, so the scoped-token mint (a serial round trip before the upgrade) is
3147
+ * skipped. A browser, or a gateway that refuses the key on an upgrade,
3148
+ * mints a scoped token for `sessionId` and dials with that — the refusal
3149
+ * costs one failed upgrade, and the mint then reports its own typed error
3150
+ * if the credential is the problem.
3151
+ */
3152
+ async connectStream(sessionId, streamPath, stream) {
3153
+ const signal = stream.signal;
3154
+ const dial = this.apiKeyDial();
3155
+ let refused = false;
3156
+ if (dial !== void 0) {
3157
+ const held = holdCloseUntilReady(stream.handlers);
3158
+ const url = `${new URL(dial.baseUrl).origin}/v1/sidecar-proxy/${encodeURIComponent(this.host.id)}${streamPath}`;
3159
+ try {
3160
+ return await this.host.terminalStreamConnect({
3161
+ ...stream,
3162
+ handlers: held.handlers,
3163
+ url,
3164
+ token: { apiKey: dial.apiKey }
3165
+ });
3166
+ } catch (error) {
3167
+ if (!isUpgradeRefusal(error) || signal?.aborted) {
3168
+ held.releaseHeldClose();
3169
+ throw error;
3170
+ }
3171
+ refused = true;
3172
+ }
3173
+ }
3174
+ const mintStartedAt = performance.now();
3175
+ const scoped = await this.host.mintScopedToken({
3176
+ scope: "session-runtime",
3177
+ sessionId,
3178
+ ...signal === void 0 ? {} : { signal }
3179
+ });
3180
+ const mintMs = performance.now() - mintStartedAt;
3181
+ const connected = await this.host.terminalStreamConnect({
3182
+ ...stream,
3183
+ url: this.resolveTerminalStreamUrl(scoped.sidecarProxyUrl, streamPath),
3184
+ token: this.terminalTokenProvider(scoped, sessionId),
3185
+ mintMs
3186
+ });
3187
+ if (refused) this.apiKeyRefusedUntil = Date.now() + API_KEY_UPGRADE_REFUSAL_TTL_MS;
3188
+ return connected;
3189
+ }
2689
3190
  /**
2690
3191
  * Resolve a sandbox-relative terminal stream path against the browser-safe
2691
3192
  * sidecar proxy base returned by the scoped-token mint. Concatenation, not
@@ -2715,14 +3216,7 @@ var SandboxInteractiveTerminalOperations = class {
2715
3216
  endpoint: `/agents/sessions/${encodeURIComponent(id)}/interactive`
2716
3217
  }, "INTERACTIVE_SESSION_EXITED");
2717
3218
  if (canonicalCandidateDigest(status.ref) !== canonicalCandidateDigest(exactRef)) throw new ValidationError("Interactive attach ref does not match the current session");
2718
- const scoped = await this.host.mintScopedToken({
2719
- scope: "session-runtime",
2720
- sessionId: id,
2721
- ...options?.signal === void 0 ? {} : { signal: options.signal }
2722
- });
2723
- const stream = await this.host.terminalStreamConnect({
2724
- url: this.resolveTerminalStreamUrl(scoped.sidecarProxyUrl, `/terminals/${encodeURIComponent(id)}/ws`),
2725
- token: this.terminalTokenProvider(scoped, id),
3219
+ const stream = await this.connectStream(id, `/terminals/${encodeURIComponent(id)}/ws`, {
2726
3220
  connectionId: id,
2727
3221
  cols: exactRequest.cols,
2728
3222
  rows: exactRequest.rows,
@@ -2767,13 +3261,7 @@ var SandboxInteractiveTerminalOperations = class {
2767
3261
  /** @internal — invoked by `box.terminals.attach()`. */
2768
3262
  async _attachTerminal(connectionId, options = {}) {
2769
3263
  if (!connectionId.trim()) throw new ValidationError("Terminal connectionId is required");
2770
- const scoped = await this.host.mintScopedToken({
2771
- scope: "session-runtime",
2772
- sessionId: connectionId
2773
- });
2774
- return this.host.terminalStreamConnect({
2775
- url: this.resolveTerminalStreamUrl(scoped.sidecarProxyUrl, `/terminals/${encodeURIComponent(connectionId)}/ws`),
2776
- token: this.terminalTokenProvider(scoped, connectionId),
3264
+ return this.connectStream(connectionId, `/terminals/${encodeURIComponent(connectionId)}/ws`, {
2777
3265
  connectionId,
2778
3266
  cols: options.cols,
2779
3267
  rows: options.rows,
@@ -4313,7 +4801,29 @@ async function withLifecycleConflictRetry(run, options) {
4313
4801
  }
4314
4802
  const SANDBOX_STATUS_FRESHNESS_MS = 1e3;
4315
4803
  const sandboxStatusObservedAt = /* @__PURE__ */ new WeakMap();
4316
- const directRuntimeInstances = /* @__PURE__ */ new WeakSet();
4804
+ const REFRESH_REASON_HEADER = "x-tangle-refresh-reason";
4805
+ /**
4806
+ * A browser preflights any header the API does not list in its CORS allow
4807
+ * list, and the reason header is the SDK's, so only runtimes that have no
4808
+ * CORS (Node, Workers) send it.
4809
+ */
4810
+ function sendsRefreshReason() {
4811
+ return !("document" in globalThis);
4812
+ }
4813
+ /**
4814
+ * A runtime refusal that says the sandbox is not there to answer: the edge
4815
+ * has no route for the box (`unknown_host`), or the proxy could not reach its
4816
+ * sidecar (502, 503). These are the answers a stale cached `running` earns.
4817
+ */
4818
+ async function isRuntimeUnreachable(response) {
4819
+ if (response.status === 502 || response.status === 503) return true;
4820
+ if (response.status !== 404) return false;
4821
+ try {
4822
+ return (await response.clone().json()).reason === "unknown_host";
4823
+ } catch {
4824
+ return false;
4825
+ }
4826
+ }
4317
4827
  function readFilesystemIncarnationTuple(value) {
4318
4828
  const rawId = value.filesystemIncarnationId;
4319
4829
  const rawProvenance = value.filesystemIncarnationProvenance;
@@ -4446,6 +4956,14 @@ var SandboxInstance = class SandboxInstance {
4446
4956
  });
4447
4957
  this.interactiveTerminalOperations = new SandboxInteractiveTerminalOperations({
4448
4958
  id: this.info.id,
4959
+ terminalApiKeyDial: () => {
4960
+ const apiKey = this.client.getApiKey?.();
4961
+ const baseUrl = this.client.getBaseUrl?.();
4962
+ return apiKey && baseUrl ? {
4963
+ apiKey,
4964
+ baseUrl
4965
+ } : void 0;
4966
+ },
4449
4967
  mintScopedToken: (options) => this.mintScopedToken(options),
4450
4968
  terminalStreamConnect: (options) => this._terminalStreamConnect(options),
4451
4969
  interactiveStatus: (id, incarnationId, options) => this._interactiveStatus(id, incarnationId, options)
@@ -4619,13 +5137,22 @@ var SandboxInstance = class SandboxInstance {
4619
5137
  if (!this.connection?.runtimeUrl) throw new StateError("Sandbox has no direct runtime URL", this.status, "running");
4620
5138
  let directInstance;
4621
5139
  directInstance = new SandboxInstance(new DirectRuntimeHttpClient(this.client, this.id, () => directInstance.connection, async () => {
4622
- await directInstance.refresh();
5140
+ await directInstance.refreshFor("bearer-refused");
4623
5141
  const next = directInstance.connection?.authToken;
4624
5142
  const client = this.client;
4625
5143
  if (next && typeof client._emitTokenRefresh === "function") client._emitTokenRefresh(this.id, next);
5144
+ }, async () => {
5145
+ try {
5146
+ await directInstance.refreshFor("runtime-refused");
5147
+ } catch (error) {
5148
+ if (error instanceof NotFoundError) throw new StateError("Sandbox is not running (status: deleted)", "deleted", "running");
5149
+ return;
5150
+ }
5151
+ directInstance.assertRunnable();
4626
5152
  }), { ...this.info }, this.defaultRuntimeBackend);
4627
5153
  if (this.deferredProfileReference !== void 0) directInstance.deferredProfileReference = this.deferredProfileReference;
4628
- directRuntimeInstances.add(directInstance);
5154
+ const observedAt = sandboxStatusObservedAt.get(this);
5155
+ if (observedAt !== void 0) sandboxStatusObservedAt.set(directInstance, observedAt);
4629
5156
  return directInstance;
4630
5157
  }
4631
5158
  /**
@@ -4660,12 +5187,15 @@ var SandboxInstance = class SandboxInstance {
4660
5187
  * Refresh sandbox information from the server.
4661
5188
  */
4662
5189
  async refresh(signal) {
5190
+ return this.refreshFor("caller", signal);
5191
+ }
5192
+ async refreshFor(reason, signal) {
4663
5193
  signal?.throwIfAborted();
4664
5194
  if (this.refreshInFlight) {
4665
5195
  await awaitWithAbort(this.refreshInFlight, signal);
4666
5196
  return;
4667
5197
  }
4668
- const refresh = this.refreshInfo();
5198
+ const refresh = this.refreshInfo(reason);
4669
5199
  this.refreshInFlight = refresh;
4670
5200
  try {
4671
5201
  await awaitWithAbort(refresh, signal);
@@ -4673,13 +5203,27 @@ var SandboxInstance = class SandboxInstance {
4673
5203
  if (this.refreshInFlight === refresh) this.refreshInFlight = void 0;
4674
5204
  }
4675
5205
  }
4676
- async refreshInfo() {
5206
+ async refreshInfo(reason) {
5207
+ const startedAt = performance.now();
5208
+ try {
5209
+ await this.readStatus(reason);
5210
+ } finally {
5211
+ emitTiming(this.client.onTiming, {
5212
+ name: "sdk.refresh",
5213
+ durMs: Math.round((performance.now() - startedAt) * 10) / 10,
5214
+ desc: reason
5215
+ });
5216
+ }
5217
+ }
5218
+ async readStatus(reason) {
4677
5219
  const direct = this.directRead.engaged() && DIRECT_READ_POLLABLE_STATUSES.has(this.info.status) ? await this.directRead.read() : null;
4678
5220
  if (direct?.kind === "unchanged") {
4679
5221
  sandboxStatusObservedAt.set(this, Date.now());
4680
5222
  return;
4681
5223
  }
4682
- const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}`, ...direct?.kind === "fallback" ? [{ headers: this.directRead.fallbackHeaders(direct.reason) }] : []));
5224
+ const headers = direct?.kind === "fallback" ? { ...this.directRead.fallbackHeaders(direct.reason) } : {};
5225
+ if (sendsRefreshReason()) headers[REFRESH_REASON_HEADER] = reason;
5226
+ const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}`, ...Object.keys(headers).length > 0 ? [{ headers }] : []));
4683
5227
  this.directRead.adopt(data);
4684
5228
  this.info = this.parseInfo(data, this.info);
4685
5229
  sandboxStatusObservedAt.set(this, Date.now());
@@ -5342,7 +5886,7 @@ var SandboxInstance = class SandboxInstance {
5342
5886
  if (runControlRef && !runControlRef.success) throw new ValidationError("Invalid runControlRef", { runControlRef: runControlRef.error.message });
5343
5887
  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" });
5344
5888
  const ttlMs = usableExecutionTtlMs(options?.ttlMs);
5345
- await this.ensureRunningForPrompt();
5889
+ await this.ensureRunning();
5346
5890
  const timeoutMs = typeof options?.timeoutMs === "number" && options.timeoutMs > 0 ? options.timeoutMs : void 0;
5347
5891
  const timeoutSignal = timeoutMs ? AbortSignal.timeout(timeoutMs) : void 0;
5348
5892
  const streamSignal = timeoutSignal ? options?.signal ? combineAbortSignals([options.signal, timeoutSignal]) : timeoutSignal : options?.signal;
@@ -5357,15 +5901,14 @@ var SandboxInstance = class SandboxInstance {
5357
5901
  if (status !== 404 && status !== 409 && status !== 503) return;
5358
5902
  sandboxStatusObservedAt.delete(this);
5359
5903
  try {
5360
- await this.refresh(streamSignal);
5904
+ await this.refreshFor("runtime-refused", streamSignal);
5361
5905
  } catch (refreshError) {
5362
5906
  if (streamSignal?.aborted) {
5363
5907
  throwIfTimedOut();
5364
5908
  throw refreshError;
5365
5909
  }
5366
5910
  }
5367
- if (this.status !== "running") throw new StateError(`Sandbox is not running (status: ${this.status})`, this.status, "running");
5368
- this.assertFilesystemIncarnationReady();
5911
+ this.assertRunnable();
5369
5912
  };
5370
5913
  const streamStartedAt = Date.now();
5371
5914
  const logStreamCheckpoint = (checkpoint, data = {}) => {
@@ -6209,7 +6752,7 @@ var SandboxInstance = class SandboxInstance {
6209
6752
  totalBytes: size,
6210
6753
  percentage: 0
6211
6754
  });
6212
- const { uploadChunkedFromFile } = await import("./chunked-upload-file-Cp-iWsWN.js");
6755
+ const { uploadChunkedFromFile } = await import("./chunked-upload-file-BwbqHWUX.js");
6213
6756
  await uploadChunkedFromFile({ fetch: (path, init) => this.runtimeFetch(path, init) }, remotePath, localPath, {
6214
6757
  mode: options?.permissions,
6215
6758
  onProgress: options?.onProgress ? (progress) => {
@@ -7390,6 +7933,7 @@ var SandboxInstance = class SandboxInstance {
7390
7933
  return result;
7391
7934
  }
7392
7935
  async snapshot(options) {
7936
+ if (options?.wait === false) return this.#snapshotNoWait(options);
7393
7937
  if (options && "paths" in options) throw new Error("Path-scoped snapshot capture is not supported; create a whole-workspace snapshot and use restorePaths()");
7394
7938
  if (options?.idempotencyKey && options.storage) throw new Error("idempotencyKey is not supported with customer-provided storage; the BYOS3 snapshot path keeps no operation ledger");
7395
7939
  await this.ensureRunning();
@@ -7434,6 +7978,31 @@ var SandboxInstance = class SandboxInstance {
7434
7978
  };
7435
7979
  }
7436
7980
  /**
7981
+ * `snapshot({ wait: false })`: the API may accept the capture and answer
7982
+ * 202 with the operation; a capture it finished synchronously comes back as
7983
+ * an operation that is already `succeeded`, its result naming the snapshot.
7984
+ */
7985
+ async #snapshotNoWait(options) {
7986
+ if ("paths" in options) throw new Error("Path-scoped snapshot capture is not supported; create a whole-workspace snapshot and use restorePaths()");
7987
+ if (options.storage) throw new Error("wait: false is not supported with customer-provided storage; the BYOS3 snapshot path keeps no operation record");
7988
+ await this.ensureRunning();
7989
+ const response = await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots?wait=false`, {
7990
+ method: "POST",
7991
+ ...options.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {},
7992
+ body: JSON.stringify({ tags: options.tags })
7993
+ }, { timeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS });
7994
+ const body = await readResponseJson(response);
7995
+ if (response.status === 202) return new SandboxOperation(parseSandboxOperation(body.operation), this.client);
7996
+ const snapshotId = body.snapshotId ?? body.id;
7997
+ if (typeof snapshotId !== "string" || snapshotId.length === 0) throw new ServerError(`Snapshot create returned ${response.status} but body had no snapshot ID: ${JSON.stringify(body).slice(0, 200)}`, response.status);
7998
+ return SandboxOperation.completed("snapshot", this.id, { snapshot: {
7999
+ snapshotId,
8000
+ createdAt: new Date(typeof body.createdAt === "string" ? body.createdAt : Date.now()),
8001
+ ...typeof body.sizeBytes === "number" ? { sizeBytes: body.sizeBytes } : {},
8002
+ tags: Array.isArray(body.tags) ? body.tags.filter((tag) => typeof tag === "string") : []
8003
+ } });
8004
+ }
8005
+ /**
7437
8006
  * List all snapshots for this sandbox.
7438
8007
  *
7439
8008
  * If `storage` is provided (BYOS3), lists snapshots from customer-provided
@@ -7809,27 +8378,34 @@ var SandboxInstance = class SandboxInstance {
7809
8378
  await this.sleep(pollIntervalMs);
7810
8379
  }
7811
8380
  }
7812
- /**
7813
- * Stop the sandbox (keeps state for resume).
7814
- *
7815
- * The stop response carries the orchestrator's per-phase stop breakdown
7816
- * (`stop_metering` / `container_kill` / `stop_complete` /
7817
- * `stop_unaccounted`); after this resolves, {@link startupDiagnostics}
7818
- * returns it (replacing the create breakdown).
7819
- */
7820
- async stop() {
8381
+ async stop(options) {
8382
+ return this.#stop(options);
8383
+ }
8384
+ async #stop(options) {
8385
+ const noWait = options?.wait === false;
7821
8386
  const response = await withLifecycleConflictRetry(async () => {
7822
- const attempt = await this.client.fetch(`/v1/sandboxes/${this.id}/stop`, { method: "POST" });
8387
+ const attempt = await this.client.fetch(`/v1/sandboxes/${this.id}/stop${noWait ? "?wait=false" : ""}`, {
8388
+ method: "POST",
8389
+ ...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {}
8390
+ });
7823
8391
  if (!attempt.ok) {
7824
8392
  const body = await attempt.text();
7825
8393
  throw parseErrorResponse(attempt.status, body, void 0, attempt.headers);
7826
8394
  }
7827
8395
  return attempt;
7828
8396
  });
8397
+ if (noWait && response.status === 202) return new SandboxOperation(parseSandboxOperation((await readResponseJson(response)).operation), this.client, async (done) => {
8398
+ if (!this.applyLifecycleResponse(done.result?.sandbox ?? null)) await this.refresh();
8399
+ });
7829
8400
  const data = await this.readLifecycleResponse(response);
7830
- if (!this.applyLifecycleResponse(data)) await this.refresh();
8401
+ if (!this.applyLifecycleResponse(data)) await this.refreshFor("lifecycle");
7831
8402
  const diagnostics = data ? normalizeStartupDiagnostics(data.startupDiagnostics) : null;
7832
8403
  if (diagnostics) this.info.startupDiagnostics = diagnostics;
8404
+ return noWait ? SandboxOperation.completed("stop", this.id) : void 0;
8405
+ }
8406
+ /** Read an operation a `wait: false` stop or snapshot of this sandbox returned. */
8407
+ async getOperation(operationId) {
8408
+ return new SandboxOperation(parseSandboxOperation(await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/operations/${encodeURIComponent(operationId)}`))), this.client);
7833
8409
  }
7834
8410
  /** Read credential recovery metadata without changing sandbox lifecycle. */
7835
8411
  async getEnvRecovery() {
@@ -7871,7 +8447,7 @@ var SandboxInstance = class SandboxInstance {
7871
8447
  return attempt;
7872
8448
  }, signal ? { signal } : {});
7873
8449
  const data = await this.readLifecycleResponse(response);
7874
- if (!this.applyLifecycleResponse(data)) await this.refresh(signal);
8450
+ if (!this.applyLifecycleResponse(data)) await this.refreshFor("lifecycle", signal);
7875
8451
  const diagnostics = data ? normalizeStartupDiagnostics(data.startupDiagnostics) : null;
7876
8452
  if (diagnostics) this.info.startupDiagnostics = diagnostics;
7877
8453
  }
@@ -8089,7 +8665,7 @@ var SandboxInstance = class SandboxInstance {
8089
8665
  if (this.hasFreshStatus() && this.hasReachedWaitTarget(statuses)) return;
8090
8666
  while (true) {
8091
8667
  if (signal.aborted) rethrowWaitError(signal.reason);
8092
- await this.refresh(signal).catch(rethrowWaitError);
8668
+ await this.refreshFor("poll", signal).catch(rethrowWaitError);
8093
8669
  if (this.hasReachedWaitTarget(statuses)) return;
8094
8670
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
8095
8671
  if (Date.now() - startTime > timeoutMs) throw new TimeoutError(timeoutMs, `Timed out waiting for sandbox to reach ${statuses.join(" or ")}`);
@@ -8133,11 +8709,11 @@ var SandboxInstance = class SandboxInstance {
8133
8709
  await this.refresh(abortController.signal);
8134
8710
  throw new StateError(event.data.error ?? "Provisioning failed", this.status);
8135
8711
  } else if (event.type === "provision_complete" || event.type === "status_change") {
8136
- await this.refresh(abortController.signal);
8712
+ await this.refreshFor("poll", abortController.signal);
8137
8713
  if (this.hasReachedWaitTarget(statuses)) return true;
8138
8714
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
8139
8715
  }
8140
- await this.refresh(abortController.signal);
8716
+ await this.refreshFor("poll", abortController.signal);
8141
8717
  if (this.hasReachedWaitTarget(statuses)) return true;
8142
8718
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
8143
8719
  if (statuses.includes("running") && this.status === "running") return false;
@@ -8172,19 +8748,41 @@ var SandboxInstance = class SandboxInstance {
8172
8748
  const statusAgeMs = Date.now() - statusObservedAt;
8173
8749
  return statusObservedAt > 0 && statusAgeMs >= 0 && statusAgeMs < SANDBOX_STATUS_FRESHNESS_MS;
8174
8750
  }
8751
+ /**
8752
+ * The check before a runtime call. A handle that has seen the sandbox
8753
+ * running and ready dispatches at once: the authenticated runtime route
8754
+ * checks current sandbox state itself, so a status GET before every call was
8755
+ * a whole round trip through the Worker that only moved the same refusal
8756
+ * earlier. A stale cache surfaces as the call's own answer, which the
8757
+ * direct client and the prompt stream turn into a typed `StateError`. A
8758
+ * handle that has not seen the status, or saw one that is not runnable,
8759
+ * reads it first.
8760
+ */
8175
8761
  async ensureRunning(signal) {
8176
8762
  signal?.throwIfAborted();
8177
- const statusObservedAt = sandboxStatusObservedAt.get(this) ?? 0;
8178
- const statusAgeMs = Date.now() - statusObservedAt;
8179
- if (directRuntimeInstances.has(this) || statusObservedAt <= 0 || statusAgeMs < 0 || statusAgeMs >= SANDBOX_STATUS_FRESHNESS_MS) await this.refresh(signal);
8763
+ const startedAt = performance.now();
8764
+ const reason = this.statusReadReason();
8765
+ try {
8766
+ if (reason) await this.refreshFor(reason, signal);
8767
+ } finally {
8768
+ emitTiming(this.client.onTiming, {
8769
+ name: "sdk.ensureRunning",
8770
+ durMs: Math.round((performance.now() - startedAt) * 10) / 10,
8771
+ desc: reason ?? "cached"
8772
+ });
8773
+ }
8180
8774
  signal?.throwIfAborted();
8775
+ this.assertRunnable();
8776
+ }
8777
+ /** Why the status must be read before a runtime call, or undefined to trust the cache. */
8778
+ statusReadReason() {
8779
+ if (!sandboxStatusObservedAt.has(this)) return "unobserved";
8780
+ if (this.status !== "running" || this.filesystemIncarnationReadiness !== "ready") return "not-running";
8781
+ }
8782
+ assertRunnable() {
8181
8783
  if (this.status !== "running") throw new StateError(`Sandbox is not running (status: ${this.status})`, this.status, "running");
8182
8784
  this.assertFilesystemIncarnationReady();
8183
8785
  }
8184
- async ensureRunningForPrompt() {
8185
- if (!directRuntimeInstances.has(this) && sandboxStatusObservedAt.has(this) && this.status === "running" && this.filesystemIncarnationReadiness === "ready") return;
8186
- await this.ensureRunning();
8187
- }
8188
8786
  assertFilesystemIncarnationReady() {
8189
8787
  if (this.filesystemIncarnationReadiness !== "ready") throw new StateError("Sandbox filesystem incarnation is not ready", this.status, "running with a ready filesystem incarnation");
8190
8788
  }
@@ -8204,6 +8802,7 @@ var SandboxInstance = class SandboxInstance {
8204
8802
  if (response.ok) sandboxStatusObservedAt.set(this, Date.now());
8205
8803
  return response;
8206
8804
  } catch (err) {
8805
+ if (err instanceof StateError) throw err;
8207
8806
  throw new NetworkError(`Failed to connect to sandbox: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0, {
8208
8807
  endpoint: path,
8209
8808
  origin: "runtime"
@@ -9315,11 +9914,16 @@ var DirectRuntimeHttpClient = class {
9315
9914
  sandboxId;
9316
9915
  getConnection;
9317
9916
  onUnauthorized;
9318
- constructor(baseClient, sandboxId, getConnection, onUnauthorized) {
9917
+ onUnreachable;
9918
+ constructor(baseClient, sandboxId, getConnection, onUnauthorized, onUnreachable) {
9319
9919
  this.baseClient = baseClient;
9320
9920
  this.sandboxId = sandboxId;
9321
9921
  this.getConnection = getConnection;
9322
9922
  this.onUnauthorized = onUnauthorized;
9923
+ this.onUnreachable = onUnreachable;
9924
+ }
9925
+ get onTiming() {
9926
+ return this.baseClient.onTiming;
9323
9927
  }
9324
9928
  async fetch(path, options, fetchOptions) {
9325
9929
  const runtimePrefix = `/v1/sandboxes/${encodeURIComponent(this.sandboxId)}/runtime`;
@@ -9341,7 +9945,11 @@ var DirectRuntimeHttpClient = class {
9341
9945
  if (options?.body && typeof options.body === "object" && !isFormDataBody) init.duplex = "half";
9342
9946
  const directTimeoutMs = fetchOptions?.timeoutMs;
9343
9947
  if (!init.signal && typeof directTimeoutMs === "number" && directTimeoutMs > 0) init.signal = AbortSignal.timeout(directTimeoutMs);
9344
- let response = await fetch(targetUrl, init);
9948
+ const send = (request) => fetchWithKeepAlive(targetUrl, request, {
9949
+ onTiming: this.onTiming,
9950
+ path
9951
+ });
9952
+ let response = await send(init);
9345
9953
  if ((response.status === 401 || response.status === 403 && await isRefusedBearer(response)) && this.onUnauthorized && !headers.has("x-no-retry")) {
9346
9954
  const refusedStatus = response.status;
9347
9955
  await response.arrayBuffer().catch(() => void 0);
@@ -9356,12 +9964,13 @@ var DirectRuntimeHttpClient = class {
9356
9964
  const refreshedConnection = this.getConnection();
9357
9965
  if (refreshedConnection?.authToken) {
9358
9966
  headers.set("Authorization", `Bearer ${refreshedConnection.authToken}`);
9359
- response = await fetch(targetUrl, {
9967
+ response = await send({
9360
9968
  ...init,
9361
9969
  headers
9362
9970
  });
9363
9971
  }
9364
9972
  }
9973
+ if (this.onUnreachable && await isRuntimeUnreachable(response)) await this.onUnreachable();
9365
9974
  const responseHeaders = new Headers(response.headers);
9366
9975
  responseHeaders.set("x-tangle-request-path", path);
9367
9976
  if (options?.method) responseHeaders.set("x-tangle-request-method", options.method);
@@ -9385,4 +9994,4 @@ function quoteForShell(value) {
9385
9994
  return `'${value.replace(/'/g, "'\\''")}'`;
9386
9995
  }
9387
9996
  //#endregion
9388
- export { exportTraceBundle as A, splitInlineProfileFileMounts as C, normalizeSandboxShape as D, normalizeConnection as E, toOtelJson as M, rewrapResponse as O, materializeProfileFileMounts as S, validateDeferredProfileFileMounts as T, collectAgentFinalMessageText as _, normalizeStartupDiagnostics as a, isToolBearingEvent as b, MAX_EGRESS_DENIALS_LIMIT as c, InteractiveSessionHandle as d, agentInteractiveSessionPromptRequestDigest as f, applySandboxEventText as g, createInteractiveTerminalSession as h, normalizeSandboxCreateReceipt as i, otelTraceIdForTangleTrace as j, buildTraceExportPayload as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, WorkspaceImages as o, InteractiveTerminalFrameLog as p, normalizeCaptureProof as r, GPU_LEASE_PROVIDER_NAMES as s, SandboxInstance as t, SandboxSession as u, collectAgentResponseText as v, splitInlineProfileSkills as w, ManagedProcessClient as x, getSandboxEventText as y };
9997
+ export { rewrapResponse as A, ManagedProcessClient as C, validateDeferredProfileFileMounts as D, splitInlineProfileSkills as E, toOtelJson as F, buildTraceExportPayload as M, exportTraceBundle as N, normalizeConnection as O, otelTraceIdForTangleTrace as P, isToolBearingEvent as S, splitInlineProfileFileMounts as T, SandboxOperationFailedError as _, normalizeStartupDiagnostics as a, collectAgentResponseText as b, MAX_EGRESS_DENIALS_LIMIT as c, InteractiveSessionHandle as d, agentInteractiveSessionPromptRequestDigest as f, SandboxOperation as g, createInteractiveTerminalSession as h, normalizeSandboxCreateReceipt as i, fetchWithKeepAlive as j, normalizeSandboxShape as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, WorkspaceImages as o, InteractiveTerminalFrameLog as p, normalizeCaptureProof as r, GPU_LEASE_PROVIDER_NAMES as s, SandboxInstance as t, SandboxSession as u, applySandboxEventText as v, materializeProfileFileMounts as w, getSandboxEventText as x, collectAgentFinalMessageText as y };