@tangle-network/sandbox 0.60.9 → 0.60.11
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 +9 -0
- package/dist/agent/index.d.ts +4 -4
- package/dist/agent/index.js +2 -2
- package/dist/agent/preview.d.ts +1 -1
- package/dist/{agent-run-outcome-xuBxUyRc.d.ts → agent-run-outcome-BLsOZXss.d.ts} +1 -1
- package/dist/{client-DAndLVD6.js → client-CFB_MZ0q.js} +9 -445
- package/dist/{client-BSWUEYZV.d.ts → client-g9SpDqN4.d.ts} +3 -3
- package/dist/core.d.ts +5 -5
- package/dist/core.js +2 -2
- package/dist/{index-CK2dUHe0.d.ts → index-FPutSe7b.d.ts} +2 -2
- package/dist/index.d.ts +9 -7
- package/dist/index.js +3 -3
- package/dist/{lines-CBlVXTb_.d.ts → lines-5Y7R5l_M.d.ts} +1 -1
- package/dist/lines.d.ts +1 -1
- package/dist/{preview-6qDzj3pE.d.ts → preview-PqH4_9hA.d.ts} +3 -3
- package/dist/runtime.d.ts +2 -2
- package/dist/{sandbox-flgG5fbm.d.ts → sandbox-BDqN9Xbx.d.ts} +14 -9
- package/dist/{sandbox-Do-2V95e.js → sandbox-BtzDSIt0.js} +655 -28
- package/dist/tangle/index.d.ts +1 -1
- package/dist/tangle/index.js +1 -1
- package/dist/{tangle-BuamBAzx.js → tangle-h87rED9E.js} +1 -1
- package/dist/{types-7TNwywMg.d.ts → types-B-RSmSBY.d.ts} +21 -3
- package/package.json +5 -5
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
|
|
2
|
-
import { A as mergeRuntimeBackendConfig, C as SANDBOX_PROXY_REQUEST_MAX_BYTES, D as parseSSEStream, M as createAgentRunOutcomeTracker, N as deriveAgentResultOutcome, O as applyRequestedModel, S as validateAcceptedDispatchRunRef, T as encodePromptForWire, _ as resolveTraceId, b as uploadChunked, c as requestScopedToken, d as normalizeSessionInfo, f as sessionMessageRequestBody, g as mintTraceId, h as isTraceId, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, 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, x as resolveDispatchRunIdentity, y as sessionHeaders } from "./interactive-controller-f_ePJqoh.js";
|
|
2
|
+
import { A as mergeRuntimeBackendConfig, C as SANDBOX_PROXY_REQUEST_MAX_BYTES, D as parseSSEStream, E as encodeTextForWire, M as createAgentRunOutcomeTracker, N as deriveAgentResultOutcome, O as applyRequestedModel, S as validateAcceptedDispatchRunRef, T as encodePromptForWire, _ as resolveTraceId, b as uploadChunked, c as requestScopedToken, d as normalizeSessionInfo, f as sessionMessageRequestBody, g as mintTraceId, h as isTraceId, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, 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, x as resolveDispatchRunIdentity, y as sessionHeaders } from "./interactive-controller-f_ePJqoh.js";
|
|
3
3
|
import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, m as StateError, n as CapabilityError, p as ServerError, r as EdgeNotReadyError, s as NetworkError, t as AuthError, u as QuotaError, v as parseResponseError, y as readResponseJson } from "./errors-D1JIX7Jm.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
6
|
import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-CJSdRlx0.js";
|
|
7
|
-
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, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
|
|
7
|
+
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";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
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";
|
|
10
10
|
import { readTokenCostUsd, readTokenUsage } from "@tangle-network/agent-core";
|
|
@@ -302,6 +302,548 @@ function normalizeSandboxShape(raw) {
|
|
|
302
302
|
};
|
|
303
303
|
}
|
|
304
304
|
//#endregion
|
|
305
|
+
//#region src/profile-file-mounts.ts
|
|
306
|
+
const PROFILE_FILE_MOUNT_B64_CHUNK_CHARS = 3e3;
|
|
307
|
+
const PROFILE_FILE_MOUNT_MAX_RETRIES = 4;
|
|
308
|
+
const PROFILE_FILE_MOUNT_RETRY_BASE_MS = 250;
|
|
309
|
+
const PROFILE_FILE_MOUNT_RETRY_MAX_MS = 2e3;
|
|
310
|
+
const PROFILE_FILE_MOUNT_EXEC_TIMEOUT_MS = 3e4;
|
|
311
|
+
/**
|
|
312
|
+
* Wall-clock ceiling for retrying one file API batch write that got no decided
|
|
313
|
+
* answer, waits included. A gateway can answer 502 after waiting out its own
|
|
314
|
+
* 3 s key-verification budget, so this admits about three such attempts: it
|
|
315
|
+
* rides out a stall of a few seconds without holding create() through a
|
|
316
|
+
* platform restart, which the caller is better told about.
|
|
317
|
+
*/
|
|
318
|
+
const PROFILE_FILE_MOUNT_WRITE_RETRY_BUDGET_MS = 1e4;
|
|
319
|
+
/**
|
|
320
|
+
* Answers that decided nothing about the write: the gateway or proxy in front
|
|
321
|
+
* of the sandbox runtime answered for it, so the write may never have run.
|
|
322
|
+
*/
|
|
323
|
+
const UNDECIDED_WRITE_STATUSES = new Set([
|
|
324
|
+
502,
|
|
325
|
+
503,
|
|
326
|
+
504
|
|
327
|
+
]);
|
|
328
|
+
const PROFILE_FILE_MOUNT_PACE_MS = 0;
|
|
329
|
+
const PROFILE_BIN_DIR_RE = /(^|\/)(s?bin)\//;
|
|
330
|
+
const PROFILE_AGENT_HOME = ["/home", "agent"].join("/");
|
|
331
|
+
/**
|
|
332
|
+
* Wire budget for a single-shot `POST /files/write` of a mount.
|
|
333
|
+
* Materialization runs over whatever connection the box has — on the
|
|
334
|
+
* default create() path that is the GATEWAY, whose wire cap
|
|
335
|
+
* ({@link SANDBOX_PROXY_REQUEST_MAX_BYTES}, 1 MiB) binds long before the
|
|
336
|
+
* sidecar's 5 MiB decoded cap. The routing decision measures the ACTUAL
|
|
337
|
+
* serialized content (JSON escaping inflates unevenly — a NUL byte
|
|
338
|
+
* becomes the six characters `\u0000`, a backslash doubles — so no fixed
|
|
339
|
+
* inflation factor is safe), leaving headroom for the request envelope
|
|
340
|
+
* (path up to 4 KiB, mode, encoding, braces). Anything that doesn't fit
|
|
341
|
+
* rides chunked upload, whose parts are sized for the gateway.
|
|
342
|
+
*/
|
|
343
|
+
const PROFILE_FILE_WRITE_WIRE_BUDGET_BYTES = SANDBOX_PROXY_REQUEST_MAX_BYTES - 8 * 1024;
|
|
344
|
+
function fitsSingleShotWrite(content, contentBytes) {
|
|
345
|
+
if (contentBytes > 5242880) return false;
|
|
346
|
+
if (contentBytes * 6 <= PROFILE_FILE_WRITE_WIRE_BUDGET_BYTES) return true;
|
|
347
|
+
return new TextEncoder().encode(JSON.stringify(content)).byteLength <= PROFILE_FILE_WRITE_WIRE_BUDGET_BYTES;
|
|
348
|
+
}
|
|
349
|
+
const DEFAULT_PROFILE_FILE_API_ABSOLUTE_PREFIXES = [
|
|
350
|
+
PROFILE_AGENT_HOME,
|
|
351
|
+
["/home", "user"].join("/"),
|
|
352
|
+
"/tmp",
|
|
353
|
+
"/output"
|
|
354
|
+
];
|
|
355
|
+
function inlineContent(mount) {
|
|
356
|
+
const resource = mount.resource;
|
|
357
|
+
if (resource.kind !== "inline") throw new Error(`materializeProfileFileMounts: ${mount.path} requires an inline resource`);
|
|
358
|
+
if (typeof resource.content !== "string") throw new Error(`materializeProfileFileMounts: ${mount.path} inline resource requires string content`);
|
|
359
|
+
return resource.content;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Synchronous pre-flight validation of deferred inline mounts: the same
|
|
363
|
+
* content/path rules {@link materializeProfileFileMounts} enforces, runnable
|
|
364
|
+
* BEFORE a sandbox is provisioned. create() calls this ahead of its POST so
|
|
365
|
+
* client-detectable bad input (traversal paths, control characters,
|
|
366
|
+
* non-string content) fails without paying for a sandbox that would only be
|
|
367
|
+
* orphaned by the post-provision throw.
|
|
368
|
+
*/
|
|
369
|
+
function validateDeferredProfileFileMounts(files) {
|
|
370
|
+
const paths = /* @__PURE__ */ new Set();
|
|
371
|
+
for (const mount of files) {
|
|
372
|
+
inlineContent(mount);
|
|
373
|
+
validateProfileFilePath(mount.path);
|
|
374
|
+
const path = (mount.path.startsWith("~/") ? `${PROFILE_AGENT_HOME}/${mount.path.slice(2)}` : mount.path).replace(/\/+/g, "/");
|
|
375
|
+
if (paths.has(path)) throw new Error(`materializeProfileFileMounts: duplicate file path ${mount.path}`);
|
|
376
|
+
paths.add(path);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Split inline `resources.skills` out of a profile the way
|
|
381
|
+
* {@link splitInlineProfileFileMounts} splits inline files: the returned
|
|
382
|
+
* `leanProfile` drops them so the create POST fits its wire cap. Unlike file
|
|
383
|
+
* mounts, skills are NOT materialized to disk here — they are harness-specific
|
|
384
|
+
* (each turn's harness needs them in its own dir), so they must ride the
|
|
385
|
+
* per-turn profile. The full profile is delivered once (create-time priming)
|
|
386
|
+
* and referenced by hash thereafter.
|
|
387
|
+
*/
|
|
388
|
+
function splitInlineProfileSkills(profile) {
|
|
389
|
+
const skills = profile.resources?.skills ?? [];
|
|
390
|
+
const kept = skills.filter((ref) => ref.kind !== "inline");
|
|
391
|
+
const deferredSkillCount = skills.length - kept.length;
|
|
392
|
+
if (deferredSkillCount === 0) return {
|
|
393
|
+
leanProfile: profile,
|
|
394
|
+
deferredSkillCount: 0
|
|
395
|
+
};
|
|
396
|
+
return {
|
|
397
|
+
leanProfile: {
|
|
398
|
+
...profile,
|
|
399
|
+
resources: {
|
|
400
|
+
...profile.resources ?? {},
|
|
401
|
+
skills: kept
|
|
402
|
+
}
|
|
403
|
+
},
|
|
404
|
+
deferredSkillCount
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
function splitInlineProfileFileMounts(profile) {
|
|
408
|
+
const files = profile.resources?.files ?? [];
|
|
409
|
+
const deferredFiles = [];
|
|
410
|
+
const keptFiles = [];
|
|
411
|
+
for (const mount of files) if (mount.resource.kind === "inline") deferredFiles.push(mount);
|
|
412
|
+
else keptFiles.push(mount);
|
|
413
|
+
if (deferredFiles.length === 0) return {
|
|
414
|
+
leanProfile: profile,
|
|
415
|
+
deferredFiles
|
|
416
|
+
};
|
|
417
|
+
return {
|
|
418
|
+
leanProfile: {
|
|
419
|
+
...profile,
|
|
420
|
+
resources: {
|
|
421
|
+
...profile.resources ?? {},
|
|
422
|
+
files: keptFiles
|
|
423
|
+
}
|
|
424
|
+
},
|
|
425
|
+
deferredFiles
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
function shellSingleQuote(value) {
|
|
429
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
430
|
+
}
|
|
431
|
+
function shellPath(path) {
|
|
432
|
+
if (path === "~") return "\"$HOME\"";
|
|
433
|
+
if (path.startsWith("~/")) {
|
|
434
|
+
const rest = path.slice(2);
|
|
435
|
+
return rest ? `"$HOME"/${shellSingleQuote(rest)}` : "\"$HOME\"";
|
|
436
|
+
}
|
|
437
|
+
return shellSingleQuote(path);
|
|
438
|
+
}
|
|
439
|
+
function validateProfileFilePath(path) {
|
|
440
|
+
if (!path) throw new Error("materializeProfileFileMounts: file path is required");
|
|
441
|
+
if (path.endsWith("/")) throw new Error(`materializeProfileFileMounts: refusing directory-shaped file path ${path}`);
|
|
442
|
+
if (hasControlCharacter(path)) throw new Error(`materializeProfileFileMounts: refusing unsafe file path ${JSON.stringify(path)}`);
|
|
443
|
+
if (path === "~" || /^~[^/]/.test(path)) throw new Error(`materializeProfileFileMounts: refusing unsupported home path ${path}`);
|
|
444
|
+
if (hasUnsafeFileApiSegment(path)) throw new Error(`materializeProfileFileMounts: refusing unsafe file path ${path}`);
|
|
445
|
+
}
|
|
446
|
+
function hasUnsafeFileApiSegment(path) {
|
|
447
|
+
return path.split("/").some((segment) => segment === "." || segment === ".." || segment === ".sidecar");
|
|
448
|
+
}
|
|
449
|
+
function hasControlCharacter(value) {
|
|
450
|
+
for (let i = 0; i < value.length; i++) {
|
|
451
|
+
const code = value.charCodeAt(i);
|
|
452
|
+
if (code < 32 || code === 127) return true;
|
|
453
|
+
}
|
|
454
|
+
return false;
|
|
455
|
+
}
|
|
456
|
+
function normalizeAbsolutePrefixes(prefixes) {
|
|
457
|
+
return prefixes.map((prefix) => {
|
|
458
|
+
const normalized = prefix.trim().replace(/\/+$/, "");
|
|
459
|
+
if (!normalized.startsWith("/") || hasControlCharacter(normalized)) throw new Error(`materializeProfileFileMounts: fileApiAbsolutePrefixes must contain absolute paths; received ${JSON.stringify(prefix)}`);
|
|
460
|
+
if (hasUnsafeFileApiSegment(normalized)) throw new Error(`materializeProfileFileMounts: fileApiAbsolutePrefixes contains unsafe path ${JSON.stringify(prefix)}`);
|
|
461
|
+
return normalized;
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
function isAllowedAbsoluteFileApiPath(path, prefixes) {
|
|
465
|
+
for (const prefix of prefixes) if (path === prefix || path.startsWith(`${prefix}/`)) return true;
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
function fileApiTarget(mount, absolutePrefixes) {
|
|
469
|
+
if (mount.path.startsWith("~/")) {
|
|
470
|
+
const homePath = `${PROFILE_AGENT_HOME}/${mount.path.slice(2)}`;
|
|
471
|
+
return isAllowedAbsoluteFileApiPath(homePath, absolutePrefixes) ? homePath : null;
|
|
472
|
+
}
|
|
473
|
+
if (mount.path.startsWith("/")) return isAllowedAbsoluteFileApiPath(mount.path, absolutePrefixes) ? mount.path : null;
|
|
474
|
+
if (mount.path.startsWith("~")) return null;
|
|
475
|
+
if (mount.path.length === 0) return null;
|
|
476
|
+
return mount.path;
|
|
477
|
+
}
|
|
478
|
+
function isExecutableProfileFile(mount) {
|
|
479
|
+
return mount.executable ?? PROFILE_BIN_DIR_RE.test(mount.path);
|
|
480
|
+
}
|
|
481
|
+
function profileFileMode(mount) {
|
|
482
|
+
return isExecutableProfileFile(mount) ? 493 : void 0;
|
|
483
|
+
}
|
|
484
|
+
function fileApiSupportsMode(box) {
|
|
485
|
+
return box.fs?.supportsWriteMode === true;
|
|
486
|
+
}
|
|
487
|
+
function isFileApiRootOnlyError(error) {
|
|
488
|
+
return error instanceof SandboxError && error.status === 403 && error.message.includes("Absolute path is outside allowed roots");
|
|
489
|
+
}
|
|
490
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
491
|
+
var ProfileFileMountExecTimeoutError = class extends Error {
|
|
492
|
+
constructor(timeoutMs) {
|
|
493
|
+
super(`exec exceeded ${timeoutMs}ms`);
|
|
494
|
+
this.name = "ProfileFileMountExecTimeoutError";
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
function execWithTimeout(box, cmd, timeoutMs) {
|
|
498
|
+
return new Promise((resolve, reject) => {
|
|
499
|
+
let settled = false;
|
|
500
|
+
const timer = setTimeout(() => {
|
|
501
|
+
if (settled) return;
|
|
502
|
+
settled = true;
|
|
503
|
+
reject(new ProfileFileMountExecTimeoutError(timeoutMs));
|
|
504
|
+
}, timeoutMs);
|
|
505
|
+
box.exec(cmd, { timeoutMs }).then((res) => {
|
|
506
|
+
if (settled) return;
|
|
507
|
+
settled = true;
|
|
508
|
+
clearTimeout(timer);
|
|
509
|
+
resolve(res);
|
|
510
|
+
}, (err) => {
|
|
511
|
+
if (settled) return;
|
|
512
|
+
settled = true;
|
|
513
|
+
clearTimeout(timer);
|
|
514
|
+
reject(err);
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
const TRANSIENT_EXEC_STATUS_CODES = new Set([
|
|
519
|
+
408,
|
|
520
|
+
409,
|
|
521
|
+
425,
|
|
522
|
+
429,
|
|
523
|
+
500,
|
|
524
|
+
502,
|
|
525
|
+
503,
|
|
526
|
+
504
|
|
527
|
+
]);
|
|
528
|
+
const TRANSIENT_EXEC_CODE_RE = /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ECONNABORTED)$/i;
|
|
529
|
+
const TRANSIENT_EXEC_MESSAGE_RE = /\b(408|409|425|429|500|502|503|504)\b|rate.?limit|too many requests|\bfetch failed\b|network error|connection reset|socket hang up|timed? out|service unavailable|bad gateway|gateway timeout|internal server error|\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\b.{0,80}\bnot ready\b|\bnot ready\b.{0,80}\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\b/i;
|
|
530
|
+
function errorStatus(err) {
|
|
531
|
+
const rawStatus = err.status ?? err.statusCode ?? (err.response && typeof err.response === "object" ? err.response.status : void 0);
|
|
532
|
+
if (typeof rawStatus === "number") return rawStatus;
|
|
533
|
+
if (typeof rawStatus === "string" && /^\d+$/.test(rawStatus)) return Number(rawStatus);
|
|
534
|
+
}
|
|
535
|
+
function retryAfterMs(err, seen = /* @__PURE__ */ new Set()) {
|
|
536
|
+
if (!err || typeof err !== "object") return void 0;
|
|
537
|
+
if (seen.has(err)) return void 0;
|
|
538
|
+
seen.add(err);
|
|
539
|
+
const e = err;
|
|
540
|
+
if (typeof e.retryAfterMs === "number") return e.retryAfterMs;
|
|
541
|
+
return retryAfterMs(e.cause, seen);
|
|
542
|
+
}
|
|
543
|
+
function isTransientExecError(err, seen = /* @__PURE__ */ new Set()) {
|
|
544
|
+
if (!err || typeof err !== "object") return false;
|
|
545
|
+
if (seen.has(err)) return false;
|
|
546
|
+
seen.add(err);
|
|
547
|
+
const e = err;
|
|
548
|
+
const status = errorStatus(e);
|
|
549
|
+
if (status !== void 0 && TRANSIENT_EXEC_STATUS_CODES.has(status)) return true;
|
|
550
|
+
if (typeof e.code === "string") {
|
|
551
|
+
if (TRANSIENT_EXEC_CODE_RE.test(e.code)) return true;
|
|
552
|
+
if (/rate.?limit|too.?many.?requests|429|server.?error|service.?unavailable/i.test(e.code)) return true;
|
|
553
|
+
}
|
|
554
|
+
if (typeof e.message === "string" && TRANSIENT_EXEC_MESSAGE_RE.test(e.message)) return true;
|
|
555
|
+
return isTransientExecError(e.cause, seen);
|
|
556
|
+
}
|
|
557
|
+
function transientExecError(err) {
|
|
558
|
+
if (err instanceof ProfileFileMountExecTimeoutError) return { retryable: false };
|
|
559
|
+
if (isTransientExecError(err)) return {
|
|
560
|
+
retryable: true,
|
|
561
|
+
retryAfterMs: retryAfterMs(err)
|
|
562
|
+
};
|
|
563
|
+
return { retryable: false };
|
|
564
|
+
}
|
|
565
|
+
function isUndecidedWriteFailure(err) {
|
|
566
|
+
if (err instanceof NetworkError) return true;
|
|
567
|
+
if (!err || typeof err !== "object") return false;
|
|
568
|
+
const status = errorStatus(err);
|
|
569
|
+
return status !== void 0 && UNDECIDED_WRITE_STATUSES.has(status);
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Run one file API batch write, sending it again after an undecided answer.
|
|
573
|
+
*
|
|
574
|
+
* Only a batch without write preconditions comes here, so a repeat after a
|
|
575
|
+
* write that did land leaves the same files with the same content and mode.
|
|
576
|
+
* A decided refusal is thrown at once. Retries stop at `maxRetries`, or when
|
|
577
|
+
* the next attempt would start past {@link PROFILE_FILE_MOUNT_WRITE_RETRY_BUDGET_MS}.
|
|
578
|
+
*/
|
|
579
|
+
async function writeBatchRidingOutUndecided(write, maxRetries) {
|
|
580
|
+
const startedAt = Date.now();
|
|
581
|
+
for (let attempt = 0;; attempt += 1) try {
|
|
582
|
+
await write();
|
|
583
|
+
return;
|
|
584
|
+
} catch (err) {
|
|
585
|
+
if (!isUndecidedWriteFailure(err) || attempt >= maxRetries) throw err;
|
|
586
|
+
const waitMs = retryAfterMs(err) ?? Math.min(PROFILE_FILE_MOUNT_RETRY_BASE_MS * 2 ** attempt, PROFILE_FILE_MOUNT_RETRY_MAX_MS);
|
|
587
|
+
if (Date.now() - startedAt + waitMs >= PROFILE_FILE_MOUNT_WRITE_RETRY_BUDGET_MS) throw err;
|
|
588
|
+
await sleep(waitMs);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
async function sha256Hex(content) {
|
|
592
|
+
const bytes = new TextEncoder().encode(content);
|
|
593
|
+
const webSubtle = globalThis.crypto?.subtle;
|
|
594
|
+
if (webSubtle) {
|
|
595
|
+
const digest = await webSubtle.digest("SHA-256", bytes);
|
|
596
|
+
return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
597
|
+
}
|
|
598
|
+
const { createHash } = await import("node:crypto");
|
|
599
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
600
|
+
}
|
|
601
|
+
async function execProfileFileMount(box, mount, content, options, execState) {
|
|
602
|
+
const maxRetries = options.maxRetries ?? PROFILE_FILE_MOUNT_MAX_RETRIES;
|
|
603
|
+
const path = mount.path;
|
|
604
|
+
const b64 = encodeTextForWire(content);
|
|
605
|
+
const b64Chunks = [];
|
|
606
|
+
for (let i = 0; i < b64.length; i += PROFILE_FILE_MOUNT_B64_CHUNK_CHARS) b64Chunks.push(b64.slice(i, i + PROFILE_FILE_MOUNT_B64_CHUNK_CHARS));
|
|
607
|
+
const expectedSha256 = await sha256Hex(content);
|
|
608
|
+
const dir = path.replace(/\/[^/]*$/, "");
|
|
609
|
+
const executable = isExecutableProfileFile(mount);
|
|
610
|
+
const q = shellPath(path);
|
|
611
|
+
const qb64 = shellPath(`${path}.b64`);
|
|
612
|
+
const qtmp = shellPath(`${path}.tmp`);
|
|
613
|
+
const qpartPrefix = shellPath(`${path}.b64.part.`);
|
|
614
|
+
const homeGuard = path.startsWith("~/") ? `[ -n "$HOME" ] || { echo ${shellSingleQuote(`materializeProfileFileMounts: HOME is unset for ${path}`)} >&2; exit 1; }; ` : "";
|
|
615
|
+
const run = async (cmd) => {
|
|
616
|
+
for (let attempt = 0;; attempt++) {
|
|
617
|
+
if (execState.started && options.paceMs > 0) await sleep(options.paceMs);
|
|
618
|
+
execState.started = true;
|
|
619
|
+
try {
|
|
620
|
+
return await execWithTimeout(box, cmd, options.execTimeoutMs);
|
|
621
|
+
} catch (err) {
|
|
622
|
+
const { retryable, retryAfterMs: retryAfter } = transientExecError(err);
|
|
623
|
+
if (retryable && attempt < maxRetries) {
|
|
624
|
+
const backoff = Math.min(PROFILE_FILE_MOUNT_RETRY_BASE_MS * 2 ** attempt, PROFILE_FILE_MOUNT_RETRY_MAX_MS);
|
|
625
|
+
await sleep(Math.min(retryAfter ?? backoff, PROFILE_FILE_MOUNT_RETRY_MAX_MS));
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
throw new Error(`materializeProfileFileMounts: exec failed for ${path}`, { cause: err });
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
const step = async (cmd) => {
|
|
633
|
+
const result = await run(`${homeGuard}${cmd}`);
|
|
634
|
+
if (result.exitCode !== 0) throw new Error(`materializeProfileFileMounts: failed to write ${path} (exit ${result.exitCode}): ${result.stderr.slice(0, 500)}`);
|
|
635
|
+
};
|
|
636
|
+
await step(dir ? `mkdir -p ${shellPath(dir)}` : ":");
|
|
637
|
+
for (let i = 0; i < b64Chunks.length; i++) {
|
|
638
|
+
const slice = b64Chunks[i];
|
|
639
|
+
if (slice === void 0) continue;
|
|
640
|
+
await step(`printf '%s' '${slice}' > ${shellPath(`${path}.b64.part.${i}`)}`);
|
|
641
|
+
}
|
|
642
|
+
const chmod = executable ? `chmod +x ${q} || exit 1; ` : "";
|
|
643
|
+
const checksumMismatch = shellSingleQuote(`materializeProfileFileMounts: checksum mismatch for ${path}`);
|
|
644
|
+
await step(`cleanup() { ${`rm -f ${qb64} ${qtmp}; i=0; while [ "$i" -lt ${b64Chunks.length} ]; do rm -f ${qpartPrefix}$i; i=$((i+1)); done`}; }; trap cleanup EXIT; expected='${expectedSha256}'; if [ -f ${q} ] && [ "$(sha256sum ${q} | awk '{print $1}')" = "$expected" ]; then ${chmod}exit 0; fi; : > ${qb64} && i=0; while [ "$i" -lt ${b64Chunks.length} ]; do cat ${qpartPrefix}$i >> ${qb64} || exit 1; i=$((i+1)); done && base64 -d ${qb64} > ${qtmp} && [ "$(sha256sum ${qtmp} | awk '{print $1}')" = "$expected" ] || { echo ${checksumMismatch} >&2; exit 1; }; mv ${qtmp} ${q} && ${executable ? `chmod +x ${q} && ` : ""}[ "$(sha256sum ${q} | awk '{print $1}')" = "$expected" ] || { echo ${checksumMismatch} >&2; exit 1; }`);
|
|
645
|
+
}
|
|
646
|
+
async function materializeProfileFileMounts(box, files, options = {}) {
|
|
647
|
+
if (options.existingFiles === "allow-identical" && files.length > 0) return materializeAbsentProfileFiles(box, files, options);
|
|
648
|
+
const execTimeoutMs = options.execTimeoutMs ?? PROFILE_FILE_MOUNT_EXEC_TIMEOUT_MS;
|
|
649
|
+
const paceMs = options.paceMs ?? PROFILE_FILE_MOUNT_PACE_MS;
|
|
650
|
+
const maxRetries = options.maxRetries ?? PROFILE_FILE_MOUNT_MAX_RETRIES;
|
|
651
|
+
const absolutePrefixes = normalizeAbsolutePrefixes(options.fileApiAbsolutePrefixes ?? DEFAULT_PROFILE_FILE_API_ABSOLUTE_PREFIXES);
|
|
652
|
+
const fs = box.fs;
|
|
653
|
+
const fileApiAvailable = typeof fs?.writeMany === "function";
|
|
654
|
+
const modeAwareFileApi = fileApiSupportsMode(box);
|
|
655
|
+
const uploadDataFn = fs?.uploadData;
|
|
656
|
+
const viaFileApi = [];
|
|
657
|
+
const viaHomeFileApi = [];
|
|
658
|
+
const viaExec = [];
|
|
659
|
+
const viaUpload = [];
|
|
660
|
+
for (const mount of files) {
|
|
661
|
+
const content = inlineContent(mount);
|
|
662
|
+
validateProfileFilePath(mount.path);
|
|
663
|
+
const target = fileApiAvailable ? fileApiTarget(mount, absolutePrefixes) : null;
|
|
664
|
+
const executable = isExecutableProfileFile(mount);
|
|
665
|
+
if (target !== null && (!executable || modeAwareFileApi)) {
|
|
666
|
+
const mode = profileFileMode(mount);
|
|
667
|
+
const contentBytes = new TextEncoder().encode(content).byteLength;
|
|
668
|
+
if (!fitsSingleShotWrite(content, contentBytes)) {
|
|
669
|
+
if (typeof uploadDataFn !== "function") throw new Error(`materializeProfileFileMounts: ${mount.path} (${contentBytes} bytes decoded) does not fit a gateway-safe single-shot write once JSON-serialized, and the box does not expose fs.uploadData for chunked delivery`);
|
|
670
|
+
viaUpload.push({
|
|
671
|
+
path: target,
|
|
672
|
+
content,
|
|
673
|
+
...mode !== void 0 ? { mode } : {}
|
|
674
|
+
});
|
|
675
|
+
continue;
|
|
676
|
+
}
|
|
677
|
+
const write = {
|
|
678
|
+
path: target,
|
|
679
|
+
content,
|
|
680
|
+
...mode !== void 0 ? { mode } : {}
|
|
681
|
+
};
|
|
682
|
+
if (mount.path.startsWith("~/")) viaHomeFileApi.push({
|
|
683
|
+
mount,
|
|
684
|
+
...write
|
|
685
|
+
});
|
|
686
|
+
else viaFileApi.push(write);
|
|
687
|
+
} else viaExec.push({
|
|
688
|
+
mount,
|
|
689
|
+
content
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
if (viaFileApi.length > 0) try {
|
|
693
|
+
await writeBatchRidingOutUndecided(async () => fs?.writeMany(viaFileApi, {
|
|
694
|
+
paceMs,
|
|
695
|
+
maxRetries
|
|
696
|
+
}), maxRetries);
|
|
697
|
+
} catch (err) {
|
|
698
|
+
throw new Error("materializeProfileFileMounts: file API batch write failed", { cause: err });
|
|
699
|
+
}
|
|
700
|
+
let homeFilesWrittenByApi = 0;
|
|
701
|
+
if (viaHomeFileApi.length > 0) {
|
|
702
|
+
const homeWrites = viaHomeFileApi.map(({ path, content, mode }) => ({
|
|
703
|
+
path,
|
|
704
|
+
content,
|
|
705
|
+
...mode !== void 0 ? { mode } : {}
|
|
706
|
+
}));
|
|
707
|
+
try {
|
|
708
|
+
await writeBatchRidingOutUndecided(async () => fs?.writeMany(homeWrites, {
|
|
709
|
+
paceMs,
|
|
710
|
+
maxRetries
|
|
711
|
+
}), maxRetries);
|
|
712
|
+
homeFilesWrittenByApi = viaHomeFileApi.length;
|
|
713
|
+
} catch (err) {
|
|
714
|
+
if (!isFileApiRootOnlyError(err)) throw new Error("materializeProfileFileMounts: home file API batch write failed", { cause: err });
|
|
715
|
+
viaExec.push(...viaHomeFileApi.map(({ mount, content }) => ({
|
|
716
|
+
mount,
|
|
717
|
+
content
|
|
718
|
+
})));
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if (viaUpload.length > 0) {
|
|
722
|
+
if (typeof uploadDataFn !== "function") throw new Error("materializeProfileFileMounts: viaUpload entries exist but fs.uploadData is unavailable");
|
|
723
|
+
for (const item of viaUpload) try {
|
|
724
|
+
await uploadDataFn(item.path, item.content, {
|
|
725
|
+
...item.mode !== void 0 ? { mode: item.mode } : {},
|
|
726
|
+
paceMs,
|
|
727
|
+
maxRetries
|
|
728
|
+
});
|
|
729
|
+
} catch (err) {
|
|
730
|
+
throw new Error(`materializeProfileFileMounts: uploadData failed for ${item.path}`, { cause: err });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const execState = { started: false };
|
|
734
|
+
for (const item of viaExec) await execProfileFileMount(box, item.mount, item.content, {
|
|
735
|
+
execTimeoutMs,
|
|
736
|
+
paceMs,
|
|
737
|
+
maxRetries
|
|
738
|
+
}, execState);
|
|
739
|
+
return {
|
|
740
|
+
written: viaFileApi.length + homeFilesWrittenByApi + viaExec.length + viaUpload.length,
|
|
741
|
+
viaFileApi: viaFileApi.length + homeFilesWrittenByApi,
|
|
742
|
+
viaExec: viaExec.length,
|
|
743
|
+
viaUpload: viaUpload.length
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
const APPLY_STAGED_PROFILE_FILES = `
|
|
747
|
+
const fs = require('node:fs');
|
|
748
|
+
const path = require('node:path');
|
|
749
|
+
const os = require('node:os');
|
|
750
|
+
const { createHash, randomUUID } = require('node:crypto');
|
|
751
|
+
const stage = path.resolve(process.argv[1]);
|
|
752
|
+
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
753
|
+
const stat = (file) => {
|
|
754
|
+
try { return fs.lstatSync(file); }
|
|
755
|
+
catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
|
|
756
|
+
};
|
|
757
|
+
const safeParents = (file) => {
|
|
758
|
+
let current = path.parse(file).root;
|
|
759
|
+
for (const part of file.slice(current.length).split(path.sep).slice(0, -1)) {
|
|
760
|
+
current = path.join(current, part);
|
|
761
|
+
const info = stat(current);
|
|
762
|
+
if (info && (!info.isDirectory() || info.isSymbolicLink()))
|
|
763
|
+
throw new Error('Refusing profile file through non-directory or symlink: ' + current);
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
const matches = (file) => {
|
|
767
|
+
const info = stat(file.target);
|
|
768
|
+
if (!info) return false;
|
|
769
|
+
if (!info.isFile() || info.isSymbolicLink() ||
|
|
770
|
+
(info.mode & 511) !== file.mode || hash(fs.readFileSync(file.target)) !== file.sha256)
|
|
771
|
+
throw new Error('Refusing to replace existing profile file: ' + file.path);
|
|
772
|
+
return true;
|
|
773
|
+
};
|
|
774
|
+
try {
|
|
775
|
+
const plan = JSON.parse(fs.readFileSync(path.join(stage, 'manifest.json'), 'utf8'));
|
|
776
|
+
const targets = new Set();
|
|
777
|
+
const files = plan.map((file, index) => {
|
|
778
|
+
const target = path.resolve(file.path.startsWith('~/')
|
|
779
|
+
? path.join(os.homedir(), file.path.slice(2)) : file.path);
|
|
780
|
+
if (targets.has(target)) throw new Error('Duplicate profile file target: ' + file.path);
|
|
781
|
+
targets.add(target);
|
|
782
|
+
const source = path.join(stage, String(index));
|
|
783
|
+
if (!fs.lstatSync(source).isFile() || hash(fs.readFileSync(source)) !== file.sha256)
|
|
784
|
+
throw new Error('Staged profile file checksum mismatch: ' + file.path);
|
|
785
|
+
return { ...file, target, source };
|
|
786
|
+
});
|
|
787
|
+
// Validate the complete plan before publishing any path.
|
|
788
|
+
for (const file of files) { safeParents(file.target); matches(file); }
|
|
789
|
+
for (const file of files) {
|
|
790
|
+
safeParents(file.target);
|
|
791
|
+
if (matches(file)) continue;
|
|
792
|
+
fs.mkdirSync(path.dirname(file.target), { recursive: true });
|
|
793
|
+
safeParents(file.target);
|
|
794
|
+
const temporary = path.join(path.dirname(file.target), '.sandbox-profile-' + randomUUID());
|
|
795
|
+
try {
|
|
796
|
+
fs.writeFileSync(temporary, fs.readFileSync(file.source), { flag: 'wx', mode: file.mode });
|
|
797
|
+
fs.chmodSync(temporary, file.mode);
|
|
798
|
+
safeParents(file.target);
|
|
799
|
+
try { fs.linkSync(temporary, file.target); }
|
|
800
|
+
catch (error) { if (error.code !== 'EEXIST' || !matches(file)) throw error; }
|
|
801
|
+
} finally { fs.rmSync(temporary, { force: true }); }
|
|
802
|
+
}
|
|
803
|
+
} finally { fs.rmSync(stage, { recursive: true, force: true }); }
|
|
804
|
+
`;
|
|
805
|
+
async function materializeAbsentProfileFiles(box, files, options) {
|
|
806
|
+
validateDeferredProfileFileMounts(files);
|
|
807
|
+
const stage = `.sandbox-profile-${globalThis.crypto.randomUUID()}`;
|
|
808
|
+
const absolutePrefixes = normalizeAbsolutePrefixes(options.fileApiAbsolutePrefixes ?? DEFAULT_PROFILE_FILE_API_ABSOLUTE_PREFIXES);
|
|
809
|
+
const manifest = await Promise.all(files.map(async (mount) => ({
|
|
810
|
+
path: typeof box.fs?.writeMany === "function" ? fileApiTarget(mount, absolutePrefixes) ?? mount.path : mount.path,
|
|
811
|
+
sha256: await sha256Hex(inlineContent(mount)),
|
|
812
|
+
mode: profileFileMode(mount) ?? 420
|
|
813
|
+
})));
|
|
814
|
+
const staged = files.map((mount, index) => ({
|
|
815
|
+
path: `${stage}/${index}`,
|
|
816
|
+
resource: mount.resource,
|
|
817
|
+
executable: false
|
|
818
|
+
}));
|
|
819
|
+
staged.push({
|
|
820
|
+
path: `${stage}/manifest.json`,
|
|
821
|
+
resource: {
|
|
822
|
+
kind: "inline",
|
|
823
|
+
name: "profile-file-manifest",
|
|
824
|
+
content: JSON.stringify(manifest)
|
|
825
|
+
},
|
|
826
|
+
executable: false
|
|
827
|
+
});
|
|
828
|
+
let result;
|
|
829
|
+
try {
|
|
830
|
+
result = await materializeProfileFileMounts(box, staged, {
|
|
831
|
+
...options,
|
|
832
|
+
existingFiles: "replace"
|
|
833
|
+
});
|
|
834
|
+
} catch (error) {
|
|
835
|
+
await execWithTimeout(box, `rm -rf -- ${shellSingleQuote(stage)}`, options.execTimeoutMs ?? PROFILE_FILE_MOUNT_EXEC_TIMEOUT_MS).catch(() => void 0);
|
|
836
|
+
throw error;
|
|
837
|
+
}
|
|
838
|
+
const applied = await execWithTimeout(box, `node -e ${shellSingleQuote(APPLY_STAGED_PROFILE_FILES)} ${shellSingleQuote(stage)}`, options.execTimeoutMs ?? PROFILE_FILE_MOUNT_EXEC_TIMEOUT_MS);
|
|
839
|
+
if (applied.exitCode !== 0) throw new Error(`materializeProfileFileMounts: ${applied.stderr.slice(0, 1500)}`);
|
|
840
|
+
return {
|
|
841
|
+
...result,
|
|
842
|
+
written: files.length,
|
|
843
|
+
viaFileApi: result.viaFileApi - 1
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
//#endregion
|
|
305
847
|
//#region src/lib/file-download.ts
|
|
306
848
|
/** Retain only complete downloads; failed streams leave the destination intact. */
|
|
307
849
|
async function downloadFile(request, localPath, options = {}) {
|
|
@@ -394,14 +936,14 @@ var ManagedProcessClient = class {
|
|
|
394
936
|
this.request = request;
|
|
395
937
|
this.environmentId = environmentId;
|
|
396
938
|
}
|
|
397
|
-
async call(method, id,
|
|
939
|
+
async call(method, id, body, options, action) {
|
|
398
940
|
if (typeof id !== "string" || !id.length || id.length > 256) throw new ValidationError("Invalid managed process id");
|
|
399
941
|
const headers = new Headers({ "Content-Type": "application/json" });
|
|
400
942
|
if (options?.sessionId) headers.set("X-Session-Id", options.sessionId);
|
|
401
|
-
const response = await this.request(method === "POST" ? "/process/jobs" : `/process/jobs/${encodeURIComponent(id)}`, {
|
|
943
|
+
const response = await this.request(action === "resume" ? `/process/jobs/${encodeURIComponent(id)}/resume` : method === "POST" ? "/process/jobs" : `/process/jobs/${encodeURIComponent(id)}`, {
|
|
402
944
|
method,
|
|
403
945
|
headers,
|
|
404
|
-
...
|
|
946
|
+
...body ? { body: JSON.stringify(body) } : {}
|
|
405
947
|
});
|
|
406
948
|
const text = await response.text();
|
|
407
949
|
let value;
|
|
@@ -412,7 +954,7 @@ var ManagedProcessClient = class {
|
|
|
412
954
|
throw new ValidationError("Managed process response is not JSON");
|
|
413
955
|
}
|
|
414
956
|
const envelope = value;
|
|
415
|
-
if (method !== "POST" && response.status === 404 && envelope?.error?.code === "MANAGED_PROCESS_NOT_FOUND") return null;
|
|
957
|
+
if ((method !== "POST" || action === "resume") && response.status === 404 && envelope?.error?.code === "MANAGED_PROCESS_NOT_FOUND") return null;
|
|
416
958
|
if (!response.ok) throw parseErrorResponse(response.status, text, void 0, response.headers);
|
|
417
959
|
const record = envelope?.data;
|
|
418
960
|
if (envelope?.success !== true || record?.schema !== 1 || record.spec?.id !== id || record.environmentId !== this.environmentId || ![
|
|
@@ -435,6 +977,14 @@ var ManagedProcessClient = class {
|
|
|
435
977
|
get(id, options) {
|
|
436
978
|
return this.call("GET", id, void 0, options);
|
|
437
979
|
}
|
|
980
|
+
resume(id, options) {
|
|
981
|
+
const { expectedAttempt, expectedDigest } = options;
|
|
982
|
+
if (!Number.isSafeInteger(expectedAttempt) || expectedAttempt < 0 || typeof expectedDigest !== "string" || !/^[a-f0-9]{64}$/.test(expectedDigest)) throw new ValidationError("Invalid managed process resume precondition");
|
|
983
|
+
return this.call("POST", id, {
|
|
984
|
+
expectedAttempt,
|
|
985
|
+
expectedDigest
|
|
986
|
+
}, options, "resume");
|
|
987
|
+
}
|
|
438
988
|
cancel(id, options) {
|
|
439
989
|
return this.call("DELETE", id, void 0, options);
|
|
440
990
|
}
|
|
@@ -1284,6 +1834,36 @@ function collectAgentFinalMessageText(events) {
|
|
|
1284
1834
|
return composed.trim().length > 0 ? composed : void 0;
|
|
1285
1835
|
}
|
|
1286
1836
|
//#endregion
|
|
1837
|
+
//#region src/profile-file-delivery.ts
|
|
1838
|
+
/** Successful immutable mount delivery is scoped to one filesystem incarnation. */
|
|
1839
|
+
var ProfileFileDelivery = class {
|
|
1840
|
+
delivered;
|
|
1841
|
+
pending = Promise.resolve();
|
|
1842
|
+
prepare(box, profile, signal, existingFiles = "allow-identical") {
|
|
1843
|
+
const { leanProfile, deferredFiles } = splitInlineProfileFileMounts(structuredClone(profile));
|
|
1844
|
+
validateDeferredProfileFileMounts(deferredFiles);
|
|
1845
|
+
if (deferredFiles.length === 0) return Promise.resolve(leanProfile);
|
|
1846
|
+
const prepared = this.pending.then(async () => {
|
|
1847
|
+
signal?.throwIfAborted();
|
|
1848
|
+
const incarnation = box.filesystemIncarnationId;
|
|
1849
|
+
const fingerprint = canonicalCandidateDigest(deferredFiles);
|
|
1850
|
+
if (incarnation === void 0 || this.delivered?.incarnation !== incarnation || this.delivered.fingerprint !== fingerprint) {
|
|
1851
|
+
this.delivered = void 0;
|
|
1852
|
+
await materializeProfileFileMounts(box, deferredFiles, { existingFiles });
|
|
1853
|
+
if (box.filesystemIncarnationId !== incarnation) throw new StateError("Filesystem incarnation changed during profile file delivery", box.filesystemIncarnationId ?? "unknown", incarnation ?? "unknown");
|
|
1854
|
+
if (incarnation !== void 0) this.delivered = {
|
|
1855
|
+
incarnation,
|
|
1856
|
+
fingerprint
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1859
|
+
signal?.throwIfAborted();
|
|
1860
|
+
return leanProfile;
|
|
1861
|
+
});
|
|
1862
|
+
this.pending = prepared.then(() => {}, () => {});
|
|
1863
|
+
return prepared;
|
|
1864
|
+
}
|
|
1865
|
+
};
|
|
1866
|
+
//#endregion
|
|
1287
1867
|
//#region ../../../packages/runtime-contracts/dist/interactive-session-http.js
|
|
1288
1868
|
const runningStatusSchema = AgentInteractiveSessionStatusSchema.options[0];
|
|
1289
1869
|
const exitedStatusSchema = AgentInteractiveSessionStatusSchema.options[1];
|
|
@@ -2950,7 +3530,7 @@ function isProfileNotCachedError(err) {
|
|
|
2950
3530
|
* inline), never breaks correctness. Used purely for the local content check.
|
|
2951
3531
|
*/
|
|
2952
3532
|
function serializeProfileSnapshot(profile) {
|
|
2953
|
-
return
|
|
3533
|
+
return canonicalCandidateJson(profile);
|
|
2954
3534
|
}
|
|
2955
3535
|
/** Preserve the server's refusal without inferring an HTTP status from its message. */
|
|
2956
3536
|
function fromStreamErrorEvent(data) {
|
|
@@ -3223,13 +3803,14 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3223
3803
|
* A profile the runtime has cached (create-time priming), letting turns
|
|
3224
3804
|
* send `backend.profileSha256` instead of re-shipping the profile's static
|
|
3225
3805
|
* corpus. Set only when priming succeeded; when unset every turn sends the
|
|
3226
|
-
*
|
|
3806
|
+
* transport profile. `snapshot` is the canonicalized
|
|
3227
3807
|
* content at prime time — a turn substitutes the reference only when the
|
|
3228
|
-
* outgoing profile
|
|
3808
|
+
* outgoing profile has identical canonical content, so a caller that mutates the
|
|
3229
3809
|
* profile in place (or passes an equivalent object) is compared by CONTENT,
|
|
3230
3810
|
* never by object identity, and a changed profile is sent inline.
|
|
3231
3811
|
*/
|
|
3232
3812
|
deferredProfileReference;
|
|
3813
|
+
profileFiles = new ProfileFileDelivery();
|
|
3233
3814
|
/**
|
|
3234
3815
|
* Direct regional status reads for THIS sandbox. Inert until the API
|
|
3235
3816
|
* relays a grant, and it retreats to the API path on any failure — see
|
|
@@ -3943,7 +4524,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3943
4524
|
*/
|
|
3944
4525
|
/**
|
|
3945
4526
|
* Record that the runtime already holds `profile` under `sha256`, so
|
|
3946
|
-
* subsequent turns whose profile
|
|
4527
|
+
* subsequent turns whose profile has the same canonical content send
|
|
3947
4528
|
* `backend.profileSha256` instead of the inline corpus. Use this to hydrate
|
|
3948
4529
|
* a freshly-fetched instance (`get()`/`list()`) from caller-persisted state
|
|
3949
4530
|
* — the reference otherwise lives only on the instance that primed it.
|
|
@@ -3957,8 +4538,9 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3957
4538
|
};
|
|
3958
4539
|
}
|
|
3959
4540
|
/**
|
|
3960
|
-
*
|
|
3961
|
-
* the
|
|
4541
|
+
* Deliver inline file mounts separately, then upload the remaining profile
|
|
4542
|
+
* to the runtime (`POST /agents/profiles`) and record
|
|
4543
|
+
* the returned transport-profile hash via {@link attachProfileReference}, so subsequent turns
|
|
3962
4544
|
* reference it by `profileSha256` instead of re-sending the corpus.
|
|
3963
4545
|
* `create()` calls this automatically for its inline profile when
|
|
3964
4546
|
* `autoDeferProfile` is on; call it directly when the profile only exists
|
|
@@ -3966,13 +4548,20 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3966
4548
|
* the returned sha256 alongside a content hash of the profile to
|
|
3967
4549
|
* re-attach on later instances without re-priming. Throws on transport/HTTP
|
|
3968
4550
|
* failure — the caller decides whether that is fatal (it is not: turns fall
|
|
3969
|
-
* back to sending the
|
|
4551
|
+
* back to sending the file-free profile inline).
|
|
3970
4552
|
*/
|
|
3971
4553
|
async primeProfile(profile) {
|
|
4554
|
+
const parsed = agentProfileSchema.safeParse(profile);
|
|
4555
|
+
if (!parsed.success) throw new ValidationError("Profile priming requires an AgentProfile object");
|
|
4556
|
+
const lean = splitInlineProfileFileMounts(parsed.data).leanProfile;
|
|
4557
|
+
const body = JSON.stringify({ profile: lean });
|
|
4558
|
+
if (new TextEncoder().encode(body).byteLength > 1048576) throw new ValidationError("Profile priming exceeds the gateway request bound; place large content in resources.files");
|
|
4559
|
+
await this.ensureRunning();
|
|
4560
|
+
const delivered = await this.materializeProfileFiles(parsed.data);
|
|
3972
4561
|
const response = await this.runtimeFetch("/agents/profiles", {
|
|
3973
4562
|
method: "POST",
|
|
3974
4563
|
headers: { "content-type": "application/json" },
|
|
3975
|
-
body
|
|
4564
|
+
body
|
|
3976
4565
|
});
|
|
3977
4566
|
if (!response.ok) {
|
|
3978
4567
|
const body = await response.text();
|
|
@@ -3983,7 +4572,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3983
4572
|
}
|
|
3984
4573
|
const data = await response.json();
|
|
3985
4574
|
if (typeof data.sha256 !== "string" || data.sha256.length === 0) throw new Error("Profile priming returned no sha256; runtime response malformed");
|
|
3986
|
-
this.attachProfileReference(
|
|
4575
|
+
this.attachProfileReference(delivered, data.sha256);
|
|
3987
4576
|
return data.sha256;
|
|
3988
4577
|
}
|
|
3989
4578
|
/**
|
|
@@ -3995,9 +4584,27 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3995
4584
|
* object passed as a per-turn override — is compared correctly: unchanged
|
|
3996
4585
|
* content references by hash, changed content sends inline.
|
|
3997
4586
|
*/
|
|
3998
|
-
|
|
3999
|
-
|
|
4587
|
+
/** @internal Shared create/turn delivery; caller policy decides how to expose failures. */
|
|
4588
|
+
materializeProfileFiles(profile, signal, existingFiles = "allow-identical") {
|
|
4589
|
+
return this.profileFiles.prepare(this, profile, signal, existingFiles);
|
|
4590
|
+
}
|
|
4591
|
+
async buildRunBackendBody(overrideBackend, forceFullProfile, requestedModel, signal) {
|
|
4592
|
+
const backend = mergeRuntimeBackendConfig(this.defaultRuntimeBackend, applyRequestedModel(overrideBackend, requestedModel));
|
|
4593
|
+
let normalized = normalizeRuntimeBackendConfig(backend);
|
|
4000
4594
|
if (!normalized) return normalized;
|
|
4595
|
+
if (backend?.profile !== void 0) try {
|
|
4596
|
+
normalized = {
|
|
4597
|
+
...normalized,
|
|
4598
|
+
profile: await this.materializeProfileFiles(backend.profile, signal)
|
|
4599
|
+
};
|
|
4600
|
+
} catch (error) {
|
|
4601
|
+
if (signal?.aborted || backend.profile.resources?.failOnError !== false) throw error;
|
|
4602
|
+
console.warn("[sandbox.prompt] Best-effort profile file delivery failed", error);
|
|
4603
|
+
normalized = {
|
|
4604
|
+
...normalized,
|
|
4605
|
+
profile: splitInlineProfileFileMounts(backend.profile).leanProfile
|
|
4606
|
+
};
|
|
4607
|
+
}
|
|
4001
4608
|
const deferred = this.deferredProfileReference;
|
|
4002
4609
|
if (!forceFullProfile && deferred !== void 0 && normalized.profile !== void 0 && serializeProfileSnapshot(normalized.profile) === deferred.snapshot) {
|
|
4003
4610
|
const { profile: _omitted, ...rest } = normalized;
|
|
@@ -4166,9 +4773,10 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4166
4773
|
...timeoutMs ? { timeoutMs } : {},
|
|
4167
4774
|
...ttlMs !== void 0 ? { ttlMs } : {},
|
|
4168
4775
|
...options?.detach ? { detach: true } : {},
|
|
4169
|
-
backend: this.buildRunBackendBody(options?.backend, internal?.forceFullProfile ?? false, options?.model)
|
|
4776
|
+
backend: await this.buildRunBackendBody(options?.backend, internal?.forceFullProfile ?? false, options?.model, streamSignal)
|
|
4170
4777
|
})
|
|
4171
4778
|
};
|
|
4779
|
+
if (typeof request.body === "string" && new TextEncoder().encode(request.body).byteLength > 1048576) throw new ValidationError("Agent run request exceeds the gateway request bound; place large content in resources.files");
|
|
4172
4780
|
response = await this.runtimeFetch(requestEndpoint, request);
|
|
4173
4781
|
for (let attempt = 1; !explicitReplay && response.status === 503 && attempt <= MAX_CREDENTIAL_REFUSAL_RETRIES; attempt += 1) {
|
|
4174
4782
|
const body = await response.clone().text();
|
|
@@ -4837,7 +5445,8 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4837
5445
|
uploadData: (remotePath, data, options) => this.fsUploadData(remotePath, data, options),
|
|
4838
5446
|
download: (remotePath, localPath, options) => this.fsDownload(remotePath, localPath, options),
|
|
4839
5447
|
uploadDir: (localDir, remoteDir) => this.fsUploadDir(localDir, remoteDir),
|
|
4840
|
-
|
|
5448
|
+
downloadArchive: (remoteDir, localPath, options) => this.fsDownloadArchive(remoteDir, localPath, options),
|
|
5449
|
+
downloadDir: (remoteDir, localDir, options) => this.fsDownloadDir(remoteDir, localDir, options),
|
|
4841
5450
|
list: (path, options) => this.fsList(path, options),
|
|
4842
5451
|
stat: (path) => this.fsStat(path),
|
|
4843
5452
|
delete: (path, options) => this.fsDelete(path, options),
|
|
@@ -4916,22 +5525,40 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4916
5525
|
await fs.unlink(tempTarPath).catch(() => {});
|
|
4917
5526
|
}
|
|
4918
5527
|
}
|
|
4919
|
-
async
|
|
4920
|
-
|
|
5528
|
+
async fsDownloadArchive(remoteDir, localPath, options) {
|
|
5529
|
+
return downloadFile(async (signal) => {
|
|
5530
|
+
await this.ensureRunning();
|
|
5531
|
+
const response = await this.runtimeFetch(runtimeFilesystemPath("/fs/download-dir", remoteDir), {
|
|
5532
|
+
method: "GET",
|
|
5533
|
+
signal
|
|
5534
|
+
});
|
|
5535
|
+
if (!response.ok) throw await parseResponseError(response);
|
|
5536
|
+
return response;
|
|
5537
|
+
}, localPath, options);
|
|
5538
|
+
}
|
|
5539
|
+
async fsDownloadDir(remoteDir, localDir, options) {
|
|
4921
5540
|
const fs = await import("node:fs/promises");
|
|
4922
5541
|
const path = await import("node:path");
|
|
4923
|
-
const {
|
|
4924
|
-
const
|
|
4925
|
-
if (!response.ok) throw await parseResponseError(response);
|
|
5542
|
+
const { execFile } = await import("node:child_process");
|
|
5543
|
+
const { promisify } = await import("node:util");
|
|
4926
5544
|
const tempDir = await fs.mkdtemp(path.join((await import("node:os")).tmpdir(), "download-"));
|
|
4927
5545
|
const tempTarPath = path.join(tempDir, "archive.tar.gz");
|
|
4928
5546
|
try {
|
|
4929
|
-
|
|
4930
|
-
|
|
5547
|
+
await this.fsDownloadArchive(remoteDir, tempTarPath, options);
|
|
5548
|
+
options?.signal?.throwIfAborted();
|
|
4931
5549
|
await fs.mkdir(localDir, { recursive: true });
|
|
4932
5550
|
try {
|
|
4933
|
-
|
|
5551
|
+
await promisify(execFile)("tar", [
|
|
5552
|
+
"-xzf",
|
|
5553
|
+
tempTarPath,
|
|
5554
|
+
"-C",
|
|
5555
|
+
localDir
|
|
5556
|
+
], {
|
|
5557
|
+
encoding: "buffer",
|
|
5558
|
+
signal: options?.signal
|
|
5559
|
+
});
|
|
4934
5560
|
} catch (error) {
|
|
5561
|
+
options?.signal?.throwIfAborted();
|
|
4935
5562
|
const stderr = error.stderr?.toString().trim();
|
|
4936
5563
|
throw new Error(`downloadDir: host tar failed to extract the archive${stderr ? ` — ${stderr}` : ""}`);
|
|
4937
5564
|
}
|
|
@@ -7741,4 +8368,4 @@ function quoteForShell(value) {
|
|
|
7741
8368
|
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
7742
8369
|
}
|
|
7743
8370
|
//#endregion
|
|
7744
|
-
export {
|
|
8371
|
+
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 };
|