@tangle-network/sandbox 0.60.69 → 0.60.77-develop.20261016230332.7f22d61
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.
- package/README.md +46 -0
- package/dist/agent/index.d.ts +4 -4
- package/dist/agent/index.js +4 -4
- package/dist/agent/preview.d.ts +1 -1
- package/dist/{agent-run-outcome-BBk2-5vp.d.ts → agent-run-outcome-CTEpjCEZ.d.ts} +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/backend-types-D6bYbvMB.js +42 -0
- package/dist/{browser-interactive-control-controller-JUW3gOGH.d.ts → browser-interactive-control-controller-rpTbyvAS.d.ts} +1 -1
- package/dist/{chunked-upload-BklCn3Li.js → chunked-upload-DtIvkKNo.js} +1 -1
- package/dist/{chunked-upload-file-Cp-iWsWN.js → chunked-upload-file-DnsHEjg0.js} +1 -1
- package/dist/{cli-auth-bundle-D61iX68d.js → cli-auth-bundle-cSJjPeFF.js} +2 -2
- package/dist/{client-DUDqUYDG.js → client-CRkHfByN.js} +21 -9
- package/dist/{client-DVouBFPR.d.ts → client-Lhxo82x1.d.ts} +10 -6
- package/dist/collaboration/index.d.ts +1 -1
- package/dist/collaboration/index.js +1 -1
- package/dist/{collaboration-B2g1j2ey.js → collaboration-DaJU5O0E.js} +1 -1
- package/dist/core.d.ts +6 -6
- package/dist/core.js +3 -3
- package/dist/{errors-iWIsey1D.js → errors-DSJBKmGZ.js} +60 -1
- package/dist/{errors-5j_Hlkm-.d.ts → errors-mPL-qvgF.d.ts} +79 -2
- package/dist/{index-DaJrtipt.d.ts → index-DRto9Ijb.d.ts} +2 -2
- package/dist/index.d.ts +19 -17
- package/dist/index.js +9 -9
- package/dist/intelligence/index.js +1 -1
- package/dist/interactive-control.d.ts +1 -1
- package/dist/{interactive-controller-DaYmUCO_.js → interactive-controller-CJ24g8Va.js} +237 -25
- package/dist/{lines-D07bn-mu.d.ts → lines-DodQslsf.d.ts} +1 -1
- package/dist/lines.d.ts +1 -1
- package/dist/lines.js +1 -1
- package/dist/{local-cli-auth-t8KUbrfI.js → local-cli-auth-CBV7Vjk5.js} +1 -1
- package/dist/{managed-process-RMyVq_du.d.ts → managed-process-B7WfqKmi.d.ts} +1 -1
- package/dist/{preview-dIOd13_U.d.ts → preview-wpGGk0bu.d.ts} +3 -3
- package/dist/runtime.d.ts +5 -6
- package/dist/runtime.js +3 -3
- package/dist/{sandbox-C7wOeFZB.d.ts → sandbox-CoIGxzm_.d.ts} +78 -24
- package/dist/{sandbox-Dg0WI1ZF.js → sandbox-DzSEprto.js} +732 -79
- package/dist/tangle/index.d.ts +1 -1
- package/dist/tangle/index.js +1 -1
- package/dist/{tangle-CaY9_VGA.js → tangle-DHFKq9sn.js} +2 -2
- package/dist/{terminal-stream-CV1pMSKC.d.ts → terminal-stream-jdYomM1m.d.ts} +123 -4
- package/dist/{types-BLCY5T4s.d.ts → types-B_QF-iHm.d.ts} +242 -28
- package/package.json +5 -5
- package/dist/backend-types-C7b_Gpa0.js +0 -59
- package/dist/interactive-controller-DNbLzamS.d.ts +0 -40
- /package/dist/{index-BgmgfYZZ.d.ts → index-DO7GVpk_.d.ts} +0 -0
- /package/dist/{index-DHuHjNie.d.ts → index-DZ27pdB8.d.ts} +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { r as backendTypeSchema } from "./backend-types-
|
|
2
|
-
import { A as
|
|
3
|
-
import {
|
|
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-CJ24g8Va.js";
|
|
3
|
+
import { C as readResponseJson, S as parseResponseError, _ as StateError, b as ValidationError, d as NotFoundError, g as ServerError, h as SandboxError, i as EdgeNotReadyError, p as QuotaError, r as CapabilityError, t as AuthError, u as NetworkError, v as StreamInterruptedError, x as parseErrorResponse, y as TimeoutError } from "./errors-DSJBKmGZ.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-
|
|
7
|
-
import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-
|
|
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-DtIvkKNo.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, PlanContinuationSchema, 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$
|
|
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$
|
|
1773
|
-
const properties = isRecord$
|
|
1774
|
-
const part = isRecord$
|
|
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$
|
|
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$
|
|
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$
|
|
1879
|
-
const part = isRecord$
|
|
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$
|
|
1936
|
-
const properties = isRecord$
|
|
1937
|
-
const part = isRecord$
|
|
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
|
|
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
|
-
|
|
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,
|
|
@@ -3584,19 +4072,19 @@ var SandboxSession = class SandboxSession {
|
|
|
3584
4072
|
async plan() {
|
|
3585
4073
|
return this.box._currentPlan(this.id);
|
|
3586
4074
|
}
|
|
3587
|
-
/** Approve a durable plan
|
|
3588
|
-
async approvePlan(planId) {
|
|
4075
|
+
/** Approve a durable plan; caller mode returns admission for fresh preparation. */
|
|
4076
|
+
async approvePlan(planId, options) {
|
|
3589
4077
|
const id = planId ?? (await this.requireCurrentPlan()).id;
|
|
3590
|
-
return this.box._decidePlan(this.id, id, { outcome: "approved" });
|
|
4078
|
+
return this.box._decidePlan(this.id, id, { outcome: "approved" }, options);
|
|
3591
4079
|
}
|
|
3592
|
-
/** Reject a durable plan with
|
|
3593
|
-
async rejectPlan(feedback, planId) {
|
|
4080
|
+
/** Reject a durable plan with feedback; caller mode prepares the revision turn. */
|
|
4081
|
+
async rejectPlan(feedback, planId, options) {
|
|
3594
4082
|
if (!feedback.trim()) throw new Error("Plan rejection feedback is required");
|
|
3595
4083
|
const id = planId ?? (await this.requireCurrentPlan()).id;
|
|
3596
4084
|
return this.box._decidePlan(this.id, id, {
|
|
3597
4085
|
outcome: "rejected",
|
|
3598
4086
|
feedback: feedback.trim()
|
|
3599
|
-
});
|
|
4087
|
+
}, options);
|
|
3600
4088
|
}
|
|
3601
4089
|
async requireCurrentPlan() {
|
|
3602
4090
|
const plan = await this.plan();
|
|
@@ -3665,7 +4153,8 @@ const GPU_LEASE_PROVIDER_NAMES = [
|
|
|
3665
4153
|
"gcp",
|
|
3666
4154
|
"azure",
|
|
3667
4155
|
"crusoe",
|
|
3668
|
-
"fluidstack"
|
|
4156
|
+
"fluidstack",
|
|
4157
|
+
"modal"
|
|
3669
4158
|
];
|
|
3670
4159
|
/** Largest `limit` the denials route accepts; it rejects anything above. */
|
|
3671
4160
|
const MAX_EGRESS_DENIALS_LIMIT = 50;
|
|
@@ -4313,7 +4802,29 @@ async function withLifecycleConflictRetry(run, options) {
|
|
|
4313
4802
|
}
|
|
4314
4803
|
const SANDBOX_STATUS_FRESHNESS_MS = 1e3;
|
|
4315
4804
|
const sandboxStatusObservedAt = /* @__PURE__ */ new WeakMap();
|
|
4316
|
-
const
|
|
4805
|
+
const REFRESH_REASON_HEADER = "x-tangle-refresh-reason";
|
|
4806
|
+
/**
|
|
4807
|
+
* A browser preflights any header the API does not list in its CORS allow
|
|
4808
|
+
* list, and the reason header is the SDK's, so only runtimes that have no
|
|
4809
|
+
* CORS (Node, Workers) send it.
|
|
4810
|
+
*/
|
|
4811
|
+
function sendsRefreshReason() {
|
|
4812
|
+
return !("document" in globalThis);
|
|
4813
|
+
}
|
|
4814
|
+
/**
|
|
4815
|
+
* A runtime refusal that says the sandbox is not there to answer: the edge
|
|
4816
|
+
* has no route for the box (`unknown_host`), or the proxy could not reach its
|
|
4817
|
+
* sidecar (502, 503). These are the answers a stale cached `running` earns.
|
|
4818
|
+
*/
|
|
4819
|
+
async function isRuntimeUnreachable(response) {
|
|
4820
|
+
if (response.status === 502 || response.status === 503) return true;
|
|
4821
|
+
if (response.status !== 404) return false;
|
|
4822
|
+
try {
|
|
4823
|
+
return (await response.clone().json()).reason === "unknown_host";
|
|
4824
|
+
} catch {
|
|
4825
|
+
return false;
|
|
4826
|
+
}
|
|
4827
|
+
}
|
|
4317
4828
|
function readFilesystemIncarnationTuple(value) {
|
|
4318
4829
|
const rawId = value.filesystemIncarnationId;
|
|
4319
4830
|
const rawProvenance = value.filesystemIncarnationProvenance;
|
|
@@ -4446,6 +4957,14 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4446
4957
|
});
|
|
4447
4958
|
this.interactiveTerminalOperations = new SandboxInteractiveTerminalOperations({
|
|
4448
4959
|
id: this.info.id,
|
|
4960
|
+
terminalApiKeyDial: () => {
|
|
4961
|
+
const apiKey = this.client.getApiKey?.();
|
|
4962
|
+
const baseUrl = this.client.getBaseUrl?.();
|
|
4963
|
+
return apiKey && baseUrl ? {
|
|
4964
|
+
apiKey,
|
|
4965
|
+
baseUrl
|
|
4966
|
+
} : void 0;
|
|
4967
|
+
},
|
|
4449
4968
|
mintScopedToken: (options) => this.mintScopedToken(options),
|
|
4450
4969
|
terminalStreamConnect: (options) => this._terminalStreamConnect(options),
|
|
4451
4970
|
interactiveStatus: (id, incarnationId, options) => this._interactiveStatus(id, incarnationId, options)
|
|
@@ -4619,13 +5138,22 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4619
5138
|
if (!this.connection?.runtimeUrl) throw new StateError("Sandbox has no direct runtime URL", this.status, "running");
|
|
4620
5139
|
let directInstance;
|
|
4621
5140
|
directInstance = new SandboxInstance(new DirectRuntimeHttpClient(this.client, this.id, () => directInstance.connection, async () => {
|
|
4622
|
-
await directInstance.
|
|
5141
|
+
await directInstance.refreshFor("bearer-refused");
|
|
4623
5142
|
const next = directInstance.connection?.authToken;
|
|
4624
5143
|
const client = this.client;
|
|
4625
5144
|
if (next && typeof client._emitTokenRefresh === "function") client._emitTokenRefresh(this.id, next);
|
|
5145
|
+
}, async () => {
|
|
5146
|
+
try {
|
|
5147
|
+
await directInstance.refreshFor("runtime-refused");
|
|
5148
|
+
} catch (error) {
|
|
5149
|
+
if (error instanceof NotFoundError) throw new StateError("Sandbox is not running (status: deleted)", "deleted", "running");
|
|
5150
|
+
return;
|
|
5151
|
+
}
|
|
5152
|
+
directInstance.assertRunnable();
|
|
4626
5153
|
}), { ...this.info }, this.defaultRuntimeBackend);
|
|
4627
5154
|
if (this.deferredProfileReference !== void 0) directInstance.deferredProfileReference = this.deferredProfileReference;
|
|
4628
|
-
|
|
5155
|
+
const observedAt = sandboxStatusObservedAt.get(this);
|
|
5156
|
+
if (observedAt !== void 0) sandboxStatusObservedAt.set(directInstance, observedAt);
|
|
4629
5157
|
return directInstance;
|
|
4630
5158
|
}
|
|
4631
5159
|
/**
|
|
@@ -4660,12 +5188,15 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4660
5188
|
* Refresh sandbox information from the server.
|
|
4661
5189
|
*/
|
|
4662
5190
|
async refresh(signal) {
|
|
5191
|
+
return this.refreshFor("caller", signal);
|
|
5192
|
+
}
|
|
5193
|
+
async refreshFor(reason, signal) {
|
|
4663
5194
|
signal?.throwIfAborted();
|
|
4664
5195
|
if (this.refreshInFlight) {
|
|
4665
5196
|
await awaitWithAbort(this.refreshInFlight, signal);
|
|
4666
5197
|
return;
|
|
4667
5198
|
}
|
|
4668
|
-
const refresh = this.refreshInfo();
|
|
5199
|
+
const refresh = this.refreshInfo(reason);
|
|
4669
5200
|
this.refreshInFlight = refresh;
|
|
4670
5201
|
try {
|
|
4671
5202
|
await awaitWithAbort(refresh, signal);
|
|
@@ -4673,13 +5204,27 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4673
5204
|
if (this.refreshInFlight === refresh) this.refreshInFlight = void 0;
|
|
4674
5205
|
}
|
|
4675
5206
|
}
|
|
4676
|
-
async refreshInfo() {
|
|
5207
|
+
async refreshInfo(reason) {
|
|
5208
|
+
const startedAt = performance.now();
|
|
5209
|
+
try {
|
|
5210
|
+
await this.readStatus(reason);
|
|
5211
|
+
} finally {
|
|
5212
|
+
emitTiming(this.client.onTiming, {
|
|
5213
|
+
name: "sdk.refresh",
|
|
5214
|
+
durMs: Math.round((performance.now() - startedAt) * 10) / 10,
|
|
5215
|
+
desc: reason
|
|
5216
|
+
});
|
|
5217
|
+
}
|
|
5218
|
+
}
|
|
5219
|
+
async readStatus(reason) {
|
|
4677
5220
|
const direct = this.directRead.engaged() && DIRECT_READ_POLLABLE_STATUSES.has(this.info.status) ? await this.directRead.read() : null;
|
|
4678
5221
|
if (direct?.kind === "unchanged") {
|
|
4679
5222
|
sandboxStatusObservedAt.set(this, Date.now());
|
|
4680
5223
|
return;
|
|
4681
5224
|
}
|
|
4682
|
-
const
|
|
5225
|
+
const headers = direct?.kind === "fallback" ? { ...this.directRead.fallbackHeaders(direct.reason) } : {};
|
|
5226
|
+
if (sendsRefreshReason()) headers[REFRESH_REASON_HEADER] = reason;
|
|
5227
|
+
const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}`, ...Object.keys(headers).length > 0 ? [{ headers }] : []));
|
|
4683
5228
|
this.directRead.adopt(data);
|
|
4684
5229
|
this.info = this.parseInfo(data, this.info);
|
|
4685
5230
|
sandboxStatusObservedAt.set(this, Date.now());
|
|
@@ -5342,7 +5887,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
5342
5887
|
if (runControlRef && !runControlRef.success) throw new ValidationError("Invalid runControlRef", { runControlRef: runControlRef.error.message });
|
|
5343
5888
|
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
5889
|
const ttlMs = usableExecutionTtlMs(options?.ttlMs);
|
|
5345
|
-
await this.
|
|
5890
|
+
await this.ensureRunning();
|
|
5346
5891
|
const timeoutMs = typeof options?.timeoutMs === "number" && options.timeoutMs > 0 ? options.timeoutMs : void 0;
|
|
5347
5892
|
const timeoutSignal = timeoutMs ? AbortSignal.timeout(timeoutMs) : void 0;
|
|
5348
5893
|
const streamSignal = timeoutSignal ? options?.signal ? combineAbortSignals([options.signal, timeoutSignal]) : timeoutSignal : options?.signal;
|
|
@@ -5357,15 +5902,14 @@ var SandboxInstance = class SandboxInstance {
|
|
|
5357
5902
|
if (status !== 404 && status !== 409 && status !== 503) return;
|
|
5358
5903
|
sandboxStatusObservedAt.delete(this);
|
|
5359
5904
|
try {
|
|
5360
|
-
await this.
|
|
5905
|
+
await this.refreshFor("runtime-refused", streamSignal);
|
|
5361
5906
|
} catch (refreshError) {
|
|
5362
5907
|
if (streamSignal?.aborted) {
|
|
5363
5908
|
throwIfTimedOut();
|
|
5364
5909
|
throw refreshError;
|
|
5365
5910
|
}
|
|
5366
5911
|
}
|
|
5367
|
-
|
|
5368
|
-
this.assertFilesystemIncarnationReady();
|
|
5912
|
+
this.assertRunnable();
|
|
5369
5913
|
};
|
|
5370
5914
|
const streamStartedAt = Date.now();
|
|
5371
5915
|
const logStreamCheckpoint = (checkpoint, data = {}) => {
|
|
@@ -6209,7 +6753,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
6209
6753
|
totalBytes: size,
|
|
6210
6754
|
percentage: 0
|
|
6211
6755
|
});
|
|
6212
|
-
const { uploadChunkedFromFile } = await import("./chunked-upload-file-
|
|
6756
|
+
const { uploadChunkedFromFile } = await import("./chunked-upload-file-DnsHEjg0.js");
|
|
6213
6757
|
await uploadChunkedFromFile({ fetch: (path, init) => this.runtimeFetch(path, init) }, remotePath, localPath, {
|
|
6214
6758
|
mode: options?.permissions,
|
|
6215
6759
|
onProgress: options?.onProgress ? (progress) => {
|
|
@@ -6889,6 +7433,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
6889
7433
|
*/
|
|
6890
7434
|
get gpu() {
|
|
6891
7435
|
return {
|
|
7436
|
+
providers: (options) => this.gpuProviders(options),
|
|
6892
7437
|
attach: (options) => this.gpuAttach(options),
|
|
6893
7438
|
list: () => this.gpuList(),
|
|
6894
7439
|
exec: (leaseId, options) => this.gpuExec(leaseId, options),
|
|
@@ -7077,6 +7622,21 @@ var SandboxInstance = class SandboxInstance {
|
|
|
7077
7622
|
incompleteReasons: record.incompleteReasons
|
|
7078
7623
|
};
|
|
7079
7624
|
}
|
|
7625
|
+
async gpuProviders(options = {}) {
|
|
7626
|
+
const query = new URLSearchParams();
|
|
7627
|
+
const accelerator = options.accelerator;
|
|
7628
|
+
if (accelerator) {
|
|
7629
|
+
query.set("acceleratorKind", accelerator.kind);
|
|
7630
|
+
if (accelerator.count !== void 0) query.set("acceleratorCount", String(accelerator.count));
|
|
7631
|
+
if (accelerator.memoryMB !== void 0) query.set("acceleratorMemoryMB", String(accelerator.memoryMB));
|
|
7632
|
+
}
|
|
7633
|
+
const suffix = query.size > 0 ? `?${query.toString()}` : "";
|
|
7634
|
+
const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/providers${suffix}`));
|
|
7635
|
+
return {
|
|
7636
|
+
usable: data.providers ?? [],
|
|
7637
|
+
statuses: data.statuses ?? []
|
|
7638
|
+
};
|
|
7639
|
+
}
|
|
7080
7640
|
async gpuAttach(options) {
|
|
7081
7641
|
return (await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases`, {
|
|
7082
7642
|
method: "POST",
|
|
@@ -7390,6 +7950,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
7390
7950
|
return result;
|
|
7391
7951
|
}
|
|
7392
7952
|
async snapshot(options) {
|
|
7953
|
+
if (options?.wait === false) return this.#snapshotNoWait(options);
|
|
7393
7954
|
if (options && "paths" in options) throw new Error("Path-scoped snapshot capture is not supported; create a whole-workspace snapshot and use restorePaths()");
|
|
7394
7955
|
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
7956
|
await this.ensureRunning();
|
|
@@ -7434,6 +7995,31 @@ var SandboxInstance = class SandboxInstance {
|
|
|
7434
7995
|
};
|
|
7435
7996
|
}
|
|
7436
7997
|
/**
|
|
7998
|
+
* `snapshot({ wait: false })`: the API may accept the capture and answer
|
|
7999
|
+
* 202 with the operation; a capture it finished synchronously comes back as
|
|
8000
|
+
* an operation that is already `succeeded`, its result naming the snapshot.
|
|
8001
|
+
*/
|
|
8002
|
+
async #snapshotNoWait(options) {
|
|
8003
|
+
if ("paths" in options) throw new Error("Path-scoped snapshot capture is not supported; create a whole-workspace snapshot and use restorePaths()");
|
|
8004
|
+
if (options.storage) throw new Error("wait: false is not supported with customer-provided storage; the BYOS3 snapshot path keeps no operation record");
|
|
8005
|
+
await this.ensureRunning();
|
|
8006
|
+
const response = await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots?wait=false`, {
|
|
8007
|
+
method: "POST",
|
|
8008
|
+
...options.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {},
|
|
8009
|
+
body: JSON.stringify({ tags: options.tags })
|
|
8010
|
+
}, { timeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS });
|
|
8011
|
+
const body = await readResponseJson(response);
|
|
8012
|
+
if (response.status === 202) return new SandboxOperation(parseSandboxOperation(body.operation), this.client);
|
|
8013
|
+
const snapshotId = body.snapshotId ?? body.id;
|
|
8014
|
+
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);
|
|
8015
|
+
return SandboxOperation.completed("snapshot", this.id, { snapshot: {
|
|
8016
|
+
snapshotId,
|
|
8017
|
+
createdAt: new Date(typeof body.createdAt === "string" ? body.createdAt : Date.now()),
|
|
8018
|
+
...typeof body.sizeBytes === "number" ? { sizeBytes: body.sizeBytes } : {},
|
|
8019
|
+
tags: Array.isArray(body.tags) ? body.tags.filter((tag) => typeof tag === "string") : []
|
|
8020
|
+
} });
|
|
8021
|
+
}
|
|
8022
|
+
/**
|
|
7437
8023
|
* List all snapshots for this sandbox.
|
|
7438
8024
|
*
|
|
7439
8025
|
* If `storage` is provided (BYOS3), lists snapshots from customer-provided
|
|
@@ -7809,27 +8395,34 @@ var SandboxInstance = class SandboxInstance {
|
|
|
7809
8395
|
await this.sleep(pollIntervalMs);
|
|
7810
8396
|
}
|
|
7811
8397
|
}
|
|
7812
|
-
|
|
7813
|
-
|
|
7814
|
-
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
* `stop_unaccounted`); after this resolves, {@link startupDiagnostics}
|
|
7818
|
-
* returns it (replacing the create breakdown).
|
|
7819
|
-
*/
|
|
7820
|
-
async stop() {
|
|
8398
|
+
async stop(options) {
|
|
8399
|
+
return this.#stop(options);
|
|
8400
|
+
}
|
|
8401
|
+
async #stop(options) {
|
|
8402
|
+
const noWait = options?.wait === false;
|
|
7821
8403
|
const response = await withLifecycleConflictRetry(async () => {
|
|
7822
|
-
const attempt = await this.client.fetch(`/v1/sandboxes/${this.id}/stop
|
|
8404
|
+
const attempt = await this.client.fetch(`/v1/sandboxes/${this.id}/stop${noWait ? "?wait=false" : ""}`, {
|
|
8405
|
+
method: "POST",
|
|
8406
|
+
...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {}
|
|
8407
|
+
});
|
|
7823
8408
|
if (!attempt.ok) {
|
|
7824
8409
|
const body = await attempt.text();
|
|
7825
8410
|
throw parseErrorResponse(attempt.status, body, void 0, attempt.headers);
|
|
7826
8411
|
}
|
|
7827
8412
|
return attempt;
|
|
7828
8413
|
});
|
|
8414
|
+
if (noWait && response.status === 202) return new SandboxOperation(parseSandboxOperation((await readResponseJson(response)).operation), this.client, async (done) => {
|
|
8415
|
+
if (!this.applyLifecycleResponse(done.result?.sandbox ?? null)) await this.refresh();
|
|
8416
|
+
});
|
|
7829
8417
|
const data = await this.readLifecycleResponse(response);
|
|
7830
|
-
if (!this.applyLifecycleResponse(data)) await this.
|
|
8418
|
+
if (!this.applyLifecycleResponse(data)) await this.refreshFor("lifecycle");
|
|
7831
8419
|
const diagnostics = data ? normalizeStartupDiagnostics(data.startupDiagnostics) : null;
|
|
7832
8420
|
if (diagnostics) this.info.startupDiagnostics = diagnostics;
|
|
8421
|
+
return noWait ? SandboxOperation.completed("stop", this.id) : void 0;
|
|
8422
|
+
}
|
|
8423
|
+
/** Read an operation a `wait: false` stop or snapshot of this sandbox returned. */
|
|
8424
|
+
async getOperation(operationId) {
|
|
8425
|
+
return new SandboxOperation(parseSandboxOperation(await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/operations/${encodeURIComponent(operationId)}`))), this.client);
|
|
7833
8426
|
}
|
|
7834
8427
|
/** Read credential recovery metadata without changing sandbox lifecycle. */
|
|
7835
8428
|
async getEnvRecovery() {
|
|
@@ -7871,7 +8464,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
7871
8464
|
return attempt;
|
|
7872
8465
|
}, signal ? { signal } : {});
|
|
7873
8466
|
const data = await this.readLifecycleResponse(response);
|
|
7874
|
-
if (!this.applyLifecycleResponse(data)) await this.
|
|
8467
|
+
if (!this.applyLifecycleResponse(data)) await this.refreshFor("lifecycle", signal);
|
|
7875
8468
|
const diagnostics = data ? normalizeStartupDiagnostics(data.startupDiagnostics) : null;
|
|
7876
8469
|
if (diagnostics) this.info.startupDiagnostics = diagnostics;
|
|
7877
8470
|
}
|
|
@@ -8089,7 +8682,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8089
8682
|
if (this.hasFreshStatus() && this.hasReachedWaitTarget(statuses)) return;
|
|
8090
8683
|
while (true) {
|
|
8091
8684
|
if (signal.aborted) rethrowWaitError(signal.reason);
|
|
8092
|
-
await this.
|
|
8685
|
+
await this.refreshFor("poll", signal).catch(rethrowWaitError);
|
|
8093
8686
|
if (this.hasReachedWaitTarget(statuses)) return;
|
|
8094
8687
|
if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
|
|
8095
8688
|
if (Date.now() - startTime > timeoutMs) throw new TimeoutError(timeoutMs, `Timed out waiting for sandbox to reach ${statuses.join(" or ")}`);
|
|
@@ -8133,11 +8726,11 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8133
8726
|
await this.refresh(abortController.signal);
|
|
8134
8727
|
throw new StateError(event.data.error ?? "Provisioning failed", this.status);
|
|
8135
8728
|
} else if (event.type === "provision_complete" || event.type === "status_change") {
|
|
8136
|
-
await this.
|
|
8729
|
+
await this.refreshFor("poll", abortController.signal);
|
|
8137
8730
|
if (this.hasReachedWaitTarget(statuses)) return true;
|
|
8138
8731
|
if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
|
|
8139
8732
|
}
|
|
8140
|
-
await this.
|
|
8733
|
+
await this.refreshFor("poll", abortController.signal);
|
|
8141
8734
|
if (this.hasReachedWaitTarget(statuses)) return true;
|
|
8142
8735
|
if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
|
|
8143
8736
|
if (statuses.includes("running") && this.status === "running") return false;
|
|
@@ -8172,19 +8765,41 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8172
8765
|
const statusAgeMs = Date.now() - statusObservedAt;
|
|
8173
8766
|
return statusObservedAt > 0 && statusAgeMs >= 0 && statusAgeMs < SANDBOX_STATUS_FRESHNESS_MS;
|
|
8174
8767
|
}
|
|
8768
|
+
/**
|
|
8769
|
+
* The check before a runtime call. A handle that has seen the sandbox
|
|
8770
|
+
* running and ready dispatches at once: the authenticated runtime route
|
|
8771
|
+
* checks current sandbox state itself, so a status GET before every call was
|
|
8772
|
+
* a whole round trip through the Worker that only moved the same refusal
|
|
8773
|
+
* earlier. A stale cache surfaces as the call's own answer, which the
|
|
8774
|
+
* direct client and the prompt stream turn into a typed `StateError`. A
|
|
8775
|
+
* handle that has not seen the status, or saw one that is not runnable,
|
|
8776
|
+
* reads it first.
|
|
8777
|
+
*/
|
|
8175
8778
|
async ensureRunning(signal) {
|
|
8176
8779
|
signal?.throwIfAborted();
|
|
8177
|
-
const
|
|
8178
|
-
const
|
|
8179
|
-
|
|
8780
|
+
const startedAt = performance.now();
|
|
8781
|
+
const reason = this.statusReadReason();
|
|
8782
|
+
try {
|
|
8783
|
+
if (reason) await this.refreshFor(reason, signal);
|
|
8784
|
+
} finally {
|
|
8785
|
+
emitTiming(this.client.onTiming, {
|
|
8786
|
+
name: "sdk.ensureRunning",
|
|
8787
|
+
durMs: Math.round((performance.now() - startedAt) * 10) / 10,
|
|
8788
|
+
desc: reason ?? "cached"
|
|
8789
|
+
});
|
|
8790
|
+
}
|
|
8180
8791
|
signal?.throwIfAborted();
|
|
8792
|
+
this.assertRunnable();
|
|
8793
|
+
}
|
|
8794
|
+
/** Why the status must be read before a runtime call, or undefined to trust the cache. */
|
|
8795
|
+
statusReadReason() {
|
|
8796
|
+
if (!sandboxStatusObservedAt.has(this)) return "unobserved";
|
|
8797
|
+
if (this.status !== "running" || this.filesystemIncarnationReadiness !== "ready") return "not-running";
|
|
8798
|
+
}
|
|
8799
|
+
assertRunnable() {
|
|
8181
8800
|
if (this.status !== "running") throw new StateError(`Sandbox is not running (status: ${this.status})`, this.status, "running");
|
|
8182
8801
|
this.assertFilesystemIncarnationReady();
|
|
8183
8802
|
}
|
|
8184
|
-
async ensureRunningForPrompt() {
|
|
8185
|
-
if (!directRuntimeInstances.has(this) && sandboxStatusObservedAt.has(this) && this.status === "running" && this.filesystemIncarnationReadiness === "ready") return;
|
|
8186
|
-
await this.ensureRunning();
|
|
8187
|
-
}
|
|
8188
8803
|
assertFilesystemIncarnationReady() {
|
|
8189
8804
|
if (this.filesystemIncarnationReadiness !== "ready") throw new StateError("Sandbox filesystem incarnation is not ready", this.status, "running with a ready filesystem incarnation");
|
|
8190
8805
|
}
|
|
@@ -8204,6 +8819,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8204
8819
|
if (response.ok) sandboxStatusObservedAt.set(this, Date.now());
|
|
8205
8820
|
return response;
|
|
8206
8821
|
} catch (err) {
|
|
8822
|
+
if (err instanceof StateError) throw err;
|
|
8207
8823
|
throw new NetworkError(`Failed to connect to sandbox: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0, {
|
|
8208
8824
|
endpoint: path,
|
|
8209
8825
|
origin: "runtime"
|
|
@@ -9209,21 +9825,25 @@ var SandboxInstance = class SandboxInstance {
|
|
|
9209
9825
|
const response = await this.client.fetch(path);
|
|
9210
9826
|
if (response.status === 404) return null;
|
|
9211
9827
|
const decoded = await readResponseJson(response);
|
|
9212
|
-
if (!decoded.plan) throw new ServerError("Durable plan response is missing plan", 502, {
|
|
9828
|
+
if (!decoded.plan || typeof decoded.plan.sourceTurnId !== "string" || !decoded.plan.sourceTurnId.trim()) throw new ServerError("Durable plan response is missing plan or original sourceTurnId", 502, {
|
|
9213
9829
|
endpoint: path,
|
|
9214
9830
|
origin: "control-plane"
|
|
9215
9831
|
});
|
|
9216
9832
|
return decoded.plan;
|
|
9217
9833
|
}
|
|
9218
9834
|
/** @internal — invoked by SandboxSession.approvePlan()/rejectPlan(). */
|
|
9219
|
-
async _decidePlan(sessionId, planId, decision) {
|
|
9835
|
+
async _decidePlan(sessionId, planId, decision, options = {}) {
|
|
9220
9836
|
const path = `/v1/sandboxes/${encodeURIComponent(this.id)}/agent-sessions/${encodeURIComponent(sessionId)}/plans/${encodeURIComponent(planId)}/decision`;
|
|
9221
9837
|
const decoded = await readResponseJson(await this.client.fetch(path, {
|
|
9222
9838
|
method: "POST",
|
|
9223
|
-
body: JSON.stringify(
|
|
9839
|
+
body: JSON.stringify({
|
|
9840
|
+
...decision,
|
|
9841
|
+
...options
|
|
9842
|
+
})
|
|
9224
9843
|
}));
|
|
9225
9844
|
const followUpState = decoded.followUp?.state;
|
|
9226
9845
|
if (!decoded.plan || typeof decoded.followUp?.turnId !== "string" || ![
|
|
9846
|
+
"awaiting_caller",
|
|
9227
9847
|
"queued",
|
|
9228
9848
|
"leased",
|
|
9229
9849
|
"started",
|
|
@@ -9233,10 +9853,33 @@ var SandboxInstance = class SandboxInstance {
|
|
|
9233
9853
|
endpoint: path,
|
|
9234
9854
|
origin: "control-plane"
|
|
9235
9855
|
});
|
|
9856
|
+
if (options.followUp && decoded.followUp.mode !== "caller") throw new ServerError("Server did not acknowledge caller-owned plan follow-up", 502, {
|
|
9857
|
+
endpoint: path,
|
|
9858
|
+
origin: "control-plane"
|
|
9859
|
+
});
|
|
9860
|
+
let resume;
|
|
9861
|
+
if (decoded.followUp.resume !== void 0) {
|
|
9862
|
+
const candidate = decoded.followUp.resume;
|
|
9863
|
+
const continuation = PlanContinuationSchema.safeParse(candidate?.continuation);
|
|
9864
|
+
if (!continuation.success || typeof candidate.sourceTurnId !== "string" || !candidate.sourceTurnId || typeof candidate.credential !== "string" || !candidate.credential || typeof candidate.callbackUrl !== "string" || !/^https?:\/\//.test(candidate.callbackUrl) || typeof candidate.expiresAt !== "string" || !Number.isFinite(Date.parse(candidate.expiresAt))) throw new ServerError("Caller plan admission response is invalid", 502, {
|
|
9865
|
+
endpoint: path,
|
|
9866
|
+
origin: "control-plane"
|
|
9867
|
+
});
|
|
9868
|
+
resume = {
|
|
9869
|
+
sourceTurnId: candidate.sourceTurnId,
|
|
9870
|
+
continuation: continuation.data,
|
|
9871
|
+
credential: candidate.credential,
|
|
9872
|
+
callbackUrl: candidate.callbackUrl,
|
|
9873
|
+
expiresAt: candidate.expiresAt
|
|
9874
|
+
};
|
|
9875
|
+
}
|
|
9236
9876
|
return {
|
|
9237
9877
|
plan: decoded.plan,
|
|
9238
9878
|
followUp: {
|
|
9239
9879
|
turnId: decoded.followUp.turnId,
|
|
9880
|
+
...decoded.followUp.mode === "caller" ? { mode: "caller" } : {},
|
|
9881
|
+
...typeof decoded.followUp.executionId === "string" ? { executionId: decoded.followUp.executionId } : {},
|
|
9882
|
+
...resume ? { resume } : {},
|
|
9240
9883
|
state: followUpState
|
|
9241
9884
|
},
|
|
9242
9885
|
idempotent: decoded.idempotent
|
|
@@ -9315,11 +9958,16 @@ var DirectRuntimeHttpClient = class {
|
|
|
9315
9958
|
sandboxId;
|
|
9316
9959
|
getConnection;
|
|
9317
9960
|
onUnauthorized;
|
|
9318
|
-
|
|
9961
|
+
onUnreachable;
|
|
9962
|
+
constructor(baseClient, sandboxId, getConnection, onUnauthorized, onUnreachable) {
|
|
9319
9963
|
this.baseClient = baseClient;
|
|
9320
9964
|
this.sandboxId = sandboxId;
|
|
9321
9965
|
this.getConnection = getConnection;
|
|
9322
9966
|
this.onUnauthorized = onUnauthorized;
|
|
9967
|
+
this.onUnreachable = onUnreachable;
|
|
9968
|
+
}
|
|
9969
|
+
get onTiming() {
|
|
9970
|
+
return this.baseClient.onTiming;
|
|
9323
9971
|
}
|
|
9324
9972
|
async fetch(path, options, fetchOptions) {
|
|
9325
9973
|
const runtimePrefix = `/v1/sandboxes/${encodeURIComponent(this.sandboxId)}/runtime`;
|
|
@@ -9341,7 +9989,11 @@ var DirectRuntimeHttpClient = class {
|
|
|
9341
9989
|
if (options?.body && typeof options.body === "object" && !isFormDataBody) init.duplex = "half";
|
|
9342
9990
|
const directTimeoutMs = fetchOptions?.timeoutMs;
|
|
9343
9991
|
if (!init.signal && typeof directTimeoutMs === "number" && directTimeoutMs > 0) init.signal = AbortSignal.timeout(directTimeoutMs);
|
|
9344
|
-
|
|
9992
|
+
const send = (request) => fetchWithKeepAlive(targetUrl, request, {
|
|
9993
|
+
onTiming: this.onTiming,
|
|
9994
|
+
path
|
|
9995
|
+
});
|
|
9996
|
+
let response = await send(init);
|
|
9345
9997
|
if ((response.status === 401 || response.status === 403 && await isRefusedBearer(response)) && this.onUnauthorized && !headers.has("x-no-retry")) {
|
|
9346
9998
|
const refusedStatus = response.status;
|
|
9347
9999
|
await response.arrayBuffer().catch(() => void 0);
|
|
@@ -9356,12 +10008,13 @@ var DirectRuntimeHttpClient = class {
|
|
|
9356
10008
|
const refreshedConnection = this.getConnection();
|
|
9357
10009
|
if (refreshedConnection?.authToken) {
|
|
9358
10010
|
headers.set("Authorization", `Bearer ${refreshedConnection.authToken}`);
|
|
9359
|
-
response = await
|
|
10011
|
+
response = await send({
|
|
9360
10012
|
...init,
|
|
9361
10013
|
headers
|
|
9362
10014
|
});
|
|
9363
10015
|
}
|
|
9364
10016
|
}
|
|
10017
|
+
if (this.onUnreachable && await isRuntimeUnreachable(response)) await this.onUnreachable();
|
|
9365
10018
|
const responseHeaders = new Headers(response.headers);
|
|
9366
10019
|
responseHeaders.set("x-tangle-request-path", path);
|
|
9367
10020
|
if (options?.method) responseHeaders.set("x-tangle-request-method", options.method);
|
|
@@ -9385,4 +10038,4 @@ function quoteForShell(value) {
|
|
|
9385
10038
|
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
9386
10039
|
}
|
|
9387
10040
|
//#endregion
|
|
9388
|
-
export {
|
|
10041
|
+
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 };
|