@tangle-network/sandbox 0.60.9 → 0.60.10
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 +2 -0
- package/dist/agent/index.d.ts +3 -3
- package/dist/agent/index.js +2 -2
- package/dist/agent/preview.d.ts +1 -1
- package/dist/{client-DAndLVD6.js → client-D7a7RnRi.js} +9 -445
- package/dist/{client-BSWUEYZV.d.ts → client-DwSJkoBR.d.ts} +1 -1
- package/dist/core.d.ts +2 -2
- package/dist/core.js +2 -2
- package/dist/{index-CK2dUHe0.d.ts → index-B77WhChz.d.ts} +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.js +3 -3
- package/dist/{preview-6qDzj3pE.d.ts → preview-DhhnuQFm.d.ts} +2 -2
- package/dist/{sandbox-flgG5fbm.d.ts → sandbox-BxxNbLpt.d.ts} +11 -7
- package/dist/{sandbox-Do-2V95e.js → sandbox-o39VWaxn.js} +615 -15
- package/dist/tangle/index.d.ts +1 -1
- package/dist/tangle/index.js +1 -1
- package/dist/{tangle-BuamBAzx.js → tangle-As8hIs0S.js} +1 -1
- 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 = {}) {
|
|
@@ -1284,6 +1826,36 @@ function collectAgentFinalMessageText(events) {
|
|
|
1284
1826
|
return composed.trim().length > 0 ? composed : void 0;
|
|
1285
1827
|
}
|
|
1286
1828
|
//#endregion
|
|
1829
|
+
//#region src/profile-file-delivery.ts
|
|
1830
|
+
/** Successful immutable mount delivery is scoped to one filesystem incarnation. */
|
|
1831
|
+
var ProfileFileDelivery = class {
|
|
1832
|
+
delivered;
|
|
1833
|
+
pending = Promise.resolve();
|
|
1834
|
+
prepare(box, profile, signal, existingFiles = "allow-identical") {
|
|
1835
|
+
const { leanProfile, deferredFiles } = splitInlineProfileFileMounts(structuredClone(profile));
|
|
1836
|
+
validateDeferredProfileFileMounts(deferredFiles);
|
|
1837
|
+
if (deferredFiles.length === 0) return Promise.resolve(leanProfile);
|
|
1838
|
+
const prepared = this.pending.then(async () => {
|
|
1839
|
+
signal?.throwIfAborted();
|
|
1840
|
+
const incarnation = box.filesystemIncarnationId;
|
|
1841
|
+
const fingerprint = canonicalCandidateDigest(deferredFiles);
|
|
1842
|
+
if (incarnation === void 0 || this.delivered?.incarnation !== incarnation || this.delivered.fingerprint !== fingerprint) {
|
|
1843
|
+
this.delivered = void 0;
|
|
1844
|
+
await materializeProfileFileMounts(box, deferredFiles, { existingFiles });
|
|
1845
|
+
if (box.filesystemIncarnationId !== incarnation) throw new StateError("Filesystem incarnation changed during profile file delivery", box.filesystemIncarnationId ?? "unknown", incarnation ?? "unknown");
|
|
1846
|
+
if (incarnation !== void 0) this.delivered = {
|
|
1847
|
+
incarnation,
|
|
1848
|
+
fingerprint
|
|
1849
|
+
};
|
|
1850
|
+
}
|
|
1851
|
+
signal?.throwIfAborted();
|
|
1852
|
+
return leanProfile;
|
|
1853
|
+
});
|
|
1854
|
+
this.pending = prepared.then(() => {}, () => {});
|
|
1855
|
+
return prepared;
|
|
1856
|
+
}
|
|
1857
|
+
};
|
|
1858
|
+
//#endregion
|
|
1287
1859
|
//#region ../../../packages/runtime-contracts/dist/interactive-session-http.js
|
|
1288
1860
|
const runningStatusSchema = AgentInteractiveSessionStatusSchema.options[0];
|
|
1289
1861
|
const exitedStatusSchema = AgentInteractiveSessionStatusSchema.options[1];
|
|
@@ -2950,7 +3522,7 @@ function isProfileNotCachedError(err) {
|
|
|
2950
3522
|
* inline), never breaks correctness. Used purely for the local content check.
|
|
2951
3523
|
*/
|
|
2952
3524
|
function serializeProfileSnapshot(profile) {
|
|
2953
|
-
return
|
|
3525
|
+
return canonicalCandidateJson(profile);
|
|
2954
3526
|
}
|
|
2955
3527
|
/** Preserve the server's refusal without inferring an HTTP status from its message. */
|
|
2956
3528
|
function fromStreamErrorEvent(data) {
|
|
@@ -3223,13 +3795,14 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3223
3795
|
* A profile the runtime has cached (create-time priming), letting turns
|
|
3224
3796
|
* send `backend.profileSha256` instead of re-shipping the profile's static
|
|
3225
3797
|
* corpus. Set only when priming succeeded; when unset every turn sends the
|
|
3226
|
-
*
|
|
3798
|
+
* transport profile. `snapshot` is the canonicalized
|
|
3227
3799
|
* content at prime time — a turn substitutes the reference only when the
|
|
3228
|
-
* outgoing profile
|
|
3800
|
+
* outgoing profile has identical canonical content, so a caller that mutates the
|
|
3229
3801
|
* profile in place (or passes an equivalent object) is compared by CONTENT,
|
|
3230
3802
|
* never by object identity, and a changed profile is sent inline.
|
|
3231
3803
|
*/
|
|
3232
3804
|
deferredProfileReference;
|
|
3805
|
+
profileFiles = new ProfileFileDelivery();
|
|
3233
3806
|
/**
|
|
3234
3807
|
* Direct regional status reads for THIS sandbox. Inert until the API
|
|
3235
3808
|
* relays a grant, and it retreats to the API path on any failure — see
|
|
@@ -3943,7 +4516,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3943
4516
|
*/
|
|
3944
4517
|
/**
|
|
3945
4518
|
* Record that the runtime already holds `profile` under `sha256`, so
|
|
3946
|
-
* subsequent turns whose profile
|
|
4519
|
+
* subsequent turns whose profile has the same canonical content send
|
|
3947
4520
|
* `backend.profileSha256` instead of the inline corpus. Use this to hydrate
|
|
3948
4521
|
* a freshly-fetched instance (`get()`/`list()`) from caller-persisted state
|
|
3949
4522
|
* — the reference otherwise lives only on the instance that primed it.
|
|
@@ -3957,8 +4530,9 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3957
4530
|
};
|
|
3958
4531
|
}
|
|
3959
4532
|
/**
|
|
3960
|
-
*
|
|
3961
|
-
* the
|
|
4533
|
+
* Deliver inline file mounts separately, then upload the remaining profile
|
|
4534
|
+
* to the runtime (`POST /agents/profiles`) and record
|
|
4535
|
+
* the returned transport-profile hash via {@link attachProfileReference}, so subsequent turns
|
|
3962
4536
|
* reference it by `profileSha256` instead of re-sending the corpus.
|
|
3963
4537
|
* `create()` calls this automatically for its inline profile when
|
|
3964
4538
|
* `autoDeferProfile` is on; call it directly when the profile only exists
|
|
@@ -3966,13 +4540,20 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3966
4540
|
* the returned sha256 alongside a content hash of the profile to
|
|
3967
4541
|
* re-attach on later instances without re-priming. Throws on transport/HTTP
|
|
3968
4542
|
* failure — the caller decides whether that is fatal (it is not: turns fall
|
|
3969
|
-
* back to sending the
|
|
4543
|
+
* back to sending the file-free profile inline).
|
|
3970
4544
|
*/
|
|
3971
4545
|
async primeProfile(profile) {
|
|
4546
|
+
const parsed = agentProfileSchema.safeParse(profile);
|
|
4547
|
+
if (!parsed.success) throw new ValidationError("Profile priming requires an AgentProfile object");
|
|
4548
|
+
const lean = splitInlineProfileFileMounts(parsed.data).leanProfile;
|
|
4549
|
+
const body = JSON.stringify({ profile: lean });
|
|
4550
|
+
if (new TextEncoder().encode(body).byteLength > 1048576) throw new ValidationError("Profile priming exceeds the gateway request bound; place large content in resources.files");
|
|
4551
|
+
await this.ensureRunning();
|
|
4552
|
+
const delivered = await this.materializeProfileFiles(parsed.data);
|
|
3972
4553
|
const response = await this.runtimeFetch("/agents/profiles", {
|
|
3973
4554
|
method: "POST",
|
|
3974
4555
|
headers: { "content-type": "application/json" },
|
|
3975
|
-
body
|
|
4556
|
+
body
|
|
3976
4557
|
});
|
|
3977
4558
|
if (!response.ok) {
|
|
3978
4559
|
const body = await response.text();
|
|
@@ -3983,7 +4564,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3983
4564
|
}
|
|
3984
4565
|
const data = await response.json();
|
|
3985
4566
|
if (typeof data.sha256 !== "string" || data.sha256.length === 0) throw new Error("Profile priming returned no sha256; runtime response malformed");
|
|
3986
|
-
this.attachProfileReference(
|
|
4567
|
+
this.attachProfileReference(delivered, data.sha256);
|
|
3987
4568
|
return data.sha256;
|
|
3988
4569
|
}
|
|
3989
4570
|
/**
|
|
@@ -3995,9 +4576,27 @@ var SandboxInstance = class SandboxInstance {
|
|
|
3995
4576
|
* object passed as a per-turn override — is compared correctly: unchanged
|
|
3996
4577
|
* content references by hash, changed content sends inline.
|
|
3997
4578
|
*/
|
|
3998
|
-
|
|
3999
|
-
|
|
4579
|
+
/** @internal Shared create/turn delivery; caller policy decides how to expose failures. */
|
|
4580
|
+
materializeProfileFiles(profile, signal, existingFiles = "allow-identical") {
|
|
4581
|
+
return this.profileFiles.prepare(this, profile, signal, existingFiles);
|
|
4582
|
+
}
|
|
4583
|
+
async buildRunBackendBody(overrideBackend, forceFullProfile, requestedModel, signal) {
|
|
4584
|
+
const backend = mergeRuntimeBackendConfig(this.defaultRuntimeBackend, applyRequestedModel(overrideBackend, requestedModel));
|
|
4585
|
+
let normalized = normalizeRuntimeBackendConfig(backend);
|
|
4000
4586
|
if (!normalized) return normalized;
|
|
4587
|
+
if (backend?.profile !== void 0) try {
|
|
4588
|
+
normalized = {
|
|
4589
|
+
...normalized,
|
|
4590
|
+
profile: await this.materializeProfileFiles(backend.profile, signal)
|
|
4591
|
+
};
|
|
4592
|
+
} catch (error) {
|
|
4593
|
+
if (signal?.aborted || backend.profile.resources?.failOnError !== false) throw error;
|
|
4594
|
+
console.warn("[sandbox.prompt] Best-effort profile file delivery failed", error);
|
|
4595
|
+
normalized = {
|
|
4596
|
+
...normalized,
|
|
4597
|
+
profile: splitInlineProfileFileMounts(backend.profile).leanProfile
|
|
4598
|
+
};
|
|
4599
|
+
}
|
|
4001
4600
|
const deferred = this.deferredProfileReference;
|
|
4002
4601
|
if (!forceFullProfile && deferred !== void 0 && normalized.profile !== void 0 && serializeProfileSnapshot(normalized.profile) === deferred.snapshot) {
|
|
4003
4602
|
const { profile: _omitted, ...rest } = normalized;
|
|
@@ -4166,9 +4765,10 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4166
4765
|
...timeoutMs ? { timeoutMs } : {},
|
|
4167
4766
|
...ttlMs !== void 0 ? { ttlMs } : {},
|
|
4168
4767
|
...options?.detach ? { detach: true } : {},
|
|
4169
|
-
backend: this.buildRunBackendBody(options?.backend, internal?.forceFullProfile ?? false, options?.model)
|
|
4768
|
+
backend: await this.buildRunBackendBody(options?.backend, internal?.forceFullProfile ?? false, options?.model, streamSignal)
|
|
4170
4769
|
})
|
|
4171
4770
|
};
|
|
4771
|
+
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
4772
|
response = await this.runtimeFetch(requestEndpoint, request);
|
|
4173
4773
|
for (let attempt = 1; !explicitReplay && response.status === 503 && attempt <= MAX_CREDENTIAL_REFUSAL_RETRIES; attempt += 1) {
|
|
4174
4774
|
const body = await response.clone().text();
|
|
@@ -7741,4 +8341,4 @@ function quoteForShell(value) {
|
|
|
7741
8341
|
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
7742
8342
|
}
|
|
7743
8343
|
//#endregion
|
|
7744
|
-
export {
|
|
8344
|
+
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 };
|