@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 CHANGED
@@ -435,6 +435,8 @@ console.log(config);
435
435
  | Chunked upload part | 768 KiB | `FILE_UPLOAD_PART_MAX_BYTES` | One `fs.upload()` or `fs.uploadData()` part |
436
436
  | Chunked upload session | 64 MiB | `FILE_UPLOAD_SESSION_MAX_BYTES` | One complete `fs.upload()` or `fs.uploadData()` call |
437
437
 
438
+ Inline `resources.files` use the same file delivery path during creation and fresh prompt turns. A full per-turn profile (including one passed to a recovered `get()` handle) is preserved in the caller and in its retained control reference, while the SDK writes the mounts before sending a profile without inline file bodies. Successful delivery is reused for the same mount set and filesystem incarnation; a changed set or a recovered handle stages the bytes and publishes only absent files. Existing files with identical bytes and modes are accepted; different content, permissions, and symlinks are refused before dispatch. Live agent edits remain untouched when the original handle reuses its receipt; a recovered handle without that receipt fails closed on conflicting mounts. Guarded publication uses the sandbox image’s Node executable. Explicit execution-event replay performs no materialization. `primeProfile()` also delivers files separately and caches the remaining profile; its returned hash names that transport profile. Skills and other non-file resources must still fit the gateway request bound.
439
+
438
440
  Use `fs.upload()` for local files or `fs.uploadData()` for in-memory content larger than the single-request limit.
439
441
 
440
442
  The instance also exposes `git`, `tools`, `process`, `terminals`, `network`, `egress`, `previewLinks`, `images`, and `backend` capability clients.
@@ -1,7 +1,7 @@
1
- import { _ as SandboxSession, h as SandboxTaskSession, r as SandboxInstance } from "../sandbox-flgG5fbm.js";
1
+ import { _ as SandboxSession, h as SandboxTaskSession, r as SandboxInstance } from "../sandbox-BxxNbLpt.js";
2
2
  import { Ba as BackendType, D as CodeExecutionResult, E as CodeExecutionOptions, Gi as SessionInfo, Kr as SandboxFleetParent, O as CodeLanguage, d as BackendConfig, k as CodeResultPart, qi as SessionListOptions } from "../types-7TNwywMg.js";
3
- import { i as Sandbox } from "../client-BSWUEYZV.js";
4
- import { u as PreviewAuthorizer } from "../preview-6qDzj3pE.js";
3
+ import { i as Sandbox } from "../client-DwSJkoBR.js";
4
+ import { u as PreviewAuthorizer } from "../preview-DhhnuQFm.js";
5
5
  import * as _$_modelcontextprotocol_sdk_server_index_js0 from "@modelcontextprotocol/sdk/server/index.js";
6
6
  import { JSONSchema } from "zod/v4/core";
7
7
  import { ToolSet } from "ai";
@@ -1,8 +1,8 @@
1
1
  import { a as TOOL_SPECS, i as ALL_TOOL_SPECS, o as serializeToolResult, r as bindToolSpecs, t as createMcpServer } from "../mcp-local-DY1CnWBn.js";
2
2
  import { k as assertCurrentBackendType } from "../interactive-controller-f_ePJqoh.js";
3
3
  import { c as NotFoundError, g as ValidationError, m as StateError } from "../errors-D1JIX7Jm.js";
4
- import { n as Sandbox } from "../client-DAndLVD6.js";
5
- import { t as SandboxInstance } from "../sandbox-Do-2V95e.js";
4
+ import { n as Sandbox } from "../client-D7a7RnRi.js";
5
+ import { t as SandboxInstance } from "../sandbox-o39VWaxn.js";
6
6
  import { z } from "zod";
7
7
  //#region src/agent/instances.ts
8
8
  const managers = /* @__PURE__ */ new WeakMap();
@@ -1,2 +1,2 @@
1
- import { _ as publishAgentPreview, a as previewOperationTool, c as AgentPreviewOptions, d as PreviewExecutionContext, f as PublishAgentPreviewOptions, g as listAgentPreviews, h as getAgentPreview, i as PreviewTool, l as PreviewAuthorizationRequest, m as ensureAgentPreview, n as PREVIEW_MCP_ALIAS, o as previewToolsForProfile, p as assertPreviewId, r as PREVIEW_TOOLS, s as AgentPreviewError, t as servePreviewMcp, u as PreviewAuthorizer, v as removeAgentPreview, y as resolveSelfSandbox } from "../preview-6qDzj3pE.js";
1
+ import { _ as publishAgentPreview, a as previewOperationTool, c as AgentPreviewOptions, d as PreviewExecutionContext, f as PublishAgentPreviewOptions, g as listAgentPreviews, h as getAgentPreview, i as PreviewTool, l as PreviewAuthorizationRequest, m as ensureAgentPreview, n as PREVIEW_MCP_ALIAS, o as previewToolsForProfile, p as assertPreviewId, r as PREVIEW_TOOLS, s as AgentPreviewError, t as servePreviewMcp, u as PreviewAuthorizer, v as removeAgentPreview, y as resolveSelfSandbox } from "../preview-DhhnuQFm.js";
2
2
  export { AgentPreviewError, AgentPreviewOptions, PREVIEW_MCP_ALIAS, PREVIEW_TOOLS, PreviewAuthorizationRequest, PreviewAuthorizer, PreviewExecutionContext, PreviewTool, PublishAgentPreviewOptions, assertPreviewId, ensureAgentPreview, getAgentPreview, listAgentPreviews, previewOperationTool, previewToolsForProfile, publishAgentPreview, removeAgentPreview, resolveSelfSandbox, servePreviewMcp };
@@ -1,8 +1,8 @@
1
1
  import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
2
- import { C as SANDBOX_PROXY_REQUEST_MAX_BYTES, D as parseSSEStream, E as encodeTextForWire, O as applyRequestedModel, T as encodePromptForWire, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, s as requestInteractiveSessionToken } from "./interactive-controller-f_ePJqoh.js";
2
+ import { D as parseSSEStream, O as applyRequestedModel, T as encodePromptForWire, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, s as requestInteractiveSessionToken } from "./interactive-controller-f_ePJqoh.js";
3
3
  import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, l as PartialFailureError, p as ServerError, s as NetworkError, t as AuthError, v as parseResponseError, y as readResponseJson } from "./errors-D1JIX7Jm.js";
4
4
  import { f as combineAbortSignals } from "./browser-interactive-control-controller-BJf0P_J4.js";
5
- import { C as normalizeSandboxShape, E as exportTraceBundle, S as normalizeConnection, a as normalizeStartupDiagnostics, i as normalizeSandboxCreateReceipt, n as createSandboxInstanceFromResponse, r as normalizeCaptureProof, w as rewrapResponse } from "./sandbox-Do-2V95e.js";
5
+ import { A as exportTraceBundle, C as splitInlineProfileFileMounts, D as normalizeSandboxShape, E as normalizeConnection, O as rewrapResponse, T as validateDeferredProfileFileMounts, a as normalizeStartupDiagnostics, i as normalizeSandboxCreateReceipt, n as createSandboxInstanceFromResponse, r as normalizeCaptureProof, w as splitInlineProfileSkills } from "./sandbox-o39VWaxn.js";
6
6
  import { LinesClient } from "./lines.js";
7
7
  import { agentProfileSchema } from "@tangle-network/agent-interface";
8
8
  import { z } from "zod";
@@ -1045,7 +1045,7 @@ const batchEventSchema = z.discriminatedUnion("type", [
1045
1045
  //#endregion
1046
1046
  //#region ../../../packages/runtime-contracts/dist/workspace-cwd.js
1047
1047
  const MAX_RUNTIME_WORKSPACE_CWD_LENGTH = 4096;
1048
- function hasControlCharacter$1(value) {
1048
+ function hasControlCharacter(value) {
1049
1049
  return Array.from(value).some((character) => {
1050
1050
  const codePoint = character.codePointAt(0);
1051
1051
  return codePoint !== void 0 && (codePoint <= 31 || codePoint === 127);
@@ -1066,7 +1066,7 @@ const runtimeWorkspaceCwdSchema = z.string().min(1).max(MAX_RUNTIME_WORKSPACE_CW
1066
1066
  code: "custom",
1067
1067
  message: "Workspace cwd must use POSIX separators"
1068
1068
  });
1069
- if (hasControlCharacter$1(value)) refinement.addIssue({
1069
+ if (hasControlCharacter(value)) refinement.addIssue({
1070
1070
  code: "custom",
1071
1071
  message: "Workspace cwd cannot contain control characters"
1072
1072
  });
@@ -3096,443 +3096,6 @@ async function read(response) {
3096
3096
  return { instance: parsed.instance };
3097
3097
  }
3098
3098
  //#endregion
3099
- //#region src/profile-file-mounts.ts
3100
- const PROFILE_FILE_MOUNT_B64_CHUNK_CHARS = 3e3;
3101
- const PROFILE_FILE_MOUNT_MAX_RETRIES = 4;
3102
- const PROFILE_FILE_MOUNT_RETRY_BASE_MS = 250;
3103
- const PROFILE_FILE_MOUNT_RETRY_MAX_MS = 2e3;
3104
- const PROFILE_FILE_MOUNT_EXEC_TIMEOUT_MS = 3e4;
3105
- /**
3106
- * Wall-clock ceiling for retrying one file API batch write that got no decided
3107
- * answer, waits included. A gateway can answer 502 after waiting out its own
3108
- * 3 s key-verification budget, so this admits about three such attempts: it
3109
- * rides out a stall of a few seconds without holding create() through a
3110
- * platform restart, which the caller is better told about.
3111
- */
3112
- const PROFILE_FILE_MOUNT_WRITE_RETRY_BUDGET_MS = 1e4;
3113
- /**
3114
- * Answers that decided nothing about the write: the gateway or proxy in front
3115
- * of the sandbox runtime answered for it, so the write may never have run.
3116
- */
3117
- const UNDECIDED_WRITE_STATUSES = new Set([
3118
- 502,
3119
- 503,
3120
- 504
3121
- ]);
3122
- const PROFILE_FILE_MOUNT_PACE_MS = 0;
3123
- const PROFILE_BIN_DIR_RE = /(^|\/)(s?bin)\//;
3124
- const PROFILE_AGENT_HOME = ["/home", "agent"].join("/");
3125
- /**
3126
- * Wire budget for a single-shot `POST /files/write` of a mount.
3127
- * Materialization runs over whatever connection the box has — on the
3128
- * default create() path that is the GATEWAY, whose wire cap
3129
- * ({@link SANDBOX_PROXY_REQUEST_MAX_BYTES}, 1 MiB) binds long before the
3130
- * sidecar's 5 MiB decoded cap. The routing decision measures the ACTUAL
3131
- * serialized content (JSON escaping inflates unevenly — a NUL byte
3132
- * becomes the six characters `\u0000`, a backslash doubles — so no fixed
3133
- * inflation factor is safe), leaving headroom for the request envelope
3134
- * (path up to 4 KiB, mode, encoding, braces). Anything that doesn't fit
3135
- * rides chunked upload, whose parts are sized for the gateway.
3136
- */
3137
- const PROFILE_FILE_WRITE_WIRE_BUDGET_BYTES = SANDBOX_PROXY_REQUEST_MAX_BYTES - 8 * 1024;
3138
- function fitsSingleShotWrite(content, contentBytes) {
3139
- if (contentBytes > 5242880) return false;
3140
- if (contentBytes * 6 <= PROFILE_FILE_WRITE_WIRE_BUDGET_BYTES) return true;
3141
- return new TextEncoder().encode(JSON.stringify(content)).byteLength <= PROFILE_FILE_WRITE_WIRE_BUDGET_BYTES;
3142
- }
3143
- const DEFAULT_PROFILE_FILE_API_ABSOLUTE_PREFIXES = [
3144
- PROFILE_AGENT_HOME,
3145
- ["/home", "user"].join("/"),
3146
- "/tmp",
3147
- "/output"
3148
- ];
3149
- function inlineContent(mount) {
3150
- const resource = mount.resource;
3151
- if (resource.kind !== "inline") throw new Error(`materializeProfileFileMounts: ${mount.path} requires an inline resource`);
3152
- if (typeof resource.content !== "string") throw new Error(`materializeProfileFileMounts: ${mount.path} inline resource requires string content`);
3153
- return resource.content;
3154
- }
3155
- /**
3156
- * Synchronous pre-flight validation of deferred inline mounts: the same
3157
- * content/path rules {@link materializeProfileFileMounts} enforces, runnable
3158
- * BEFORE a sandbox is provisioned. create() calls this ahead of its POST so
3159
- * client-detectable bad input (traversal paths, control characters,
3160
- * non-string content) fails without paying for a sandbox that would only be
3161
- * orphaned by the post-provision throw.
3162
- */
3163
- function validateDeferredProfileFileMounts(files) {
3164
- for (const mount of files) {
3165
- inlineContent(mount);
3166
- validateProfileFilePath(mount.path);
3167
- }
3168
- }
3169
- /**
3170
- * Split inline `resources.skills` out of a profile the way
3171
- * {@link splitInlineProfileFileMounts} splits inline files: the returned
3172
- * `leanProfile` drops them so the create POST fits its wire cap. Unlike file
3173
- * mounts, skills are NOT materialized to disk here — they are harness-specific
3174
- * (each turn's harness needs them in its own dir), so they must ride the
3175
- * per-turn profile. The full profile is delivered once (create-time priming)
3176
- * and referenced by hash thereafter.
3177
- */
3178
- function splitInlineProfileSkills(profile) {
3179
- const skills = profile.resources?.skills ?? [];
3180
- const kept = skills.filter((ref) => ref.kind !== "inline");
3181
- const deferredSkillCount = skills.length - kept.length;
3182
- if (deferredSkillCount === 0) return {
3183
- leanProfile: profile,
3184
- deferredSkillCount: 0
3185
- };
3186
- return {
3187
- leanProfile: {
3188
- ...profile,
3189
- resources: {
3190
- ...profile.resources ?? {},
3191
- skills: kept
3192
- }
3193
- },
3194
- deferredSkillCount
3195
- };
3196
- }
3197
- function splitInlineProfileFileMounts(profile) {
3198
- const files = profile.resources?.files ?? [];
3199
- const deferredFiles = [];
3200
- const keptFiles = [];
3201
- for (const mount of files) if (mount.resource.kind === "inline") deferredFiles.push(mount);
3202
- else keptFiles.push(mount);
3203
- if (deferredFiles.length === 0) return {
3204
- leanProfile: profile,
3205
- deferredFiles
3206
- };
3207
- return {
3208
- leanProfile: {
3209
- ...profile,
3210
- resources: {
3211
- ...profile.resources ?? {},
3212
- files: keptFiles
3213
- }
3214
- },
3215
- deferredFiles
3216
- };
3217
- }
3218
- function shellSingleQuote(value) {
3219
- return `'${value.replace(/'/g, `'\\''`)}'`;
3220
- }
3221
- function shellPath(path) {
3222
- if (path === "~") return "\"$HOME\"";
3223
- if (path.startsWith("~/")) {
3224
- const rest = path.slice(2);
3225
- return rest ? `"$HOME"/${shellSingleQuote(rest)}` : "\"$HOME\"";
3226
- }
3227
- return shellSingleQuote(path);
3228
- }
3229
- function validateProfileFilePath(path) {
3230
- if (!path) throw new Error("materializeProfileFileMounts: file path is required");
3231
- if (path.endsWith("/")) throw new Error(`materializeProfileFileMounts: refusing directory-shaped file path ${path}`);
3232
- if (hasControlCharacter(path)) throw new Error(`materializeProfileFileMounts: refusing unsafe file path ${JSON.stringify(path)}`);
3233
- if (path === "~" || /^~[^/]/.test(path)) throw new Error(`materializeProfileFileMounts: refusing unsupported home path ${path}`);
3234
- if (hasUnsafeFileApiSegment(path)) throw new Error(`materializeProfileFileMounts: refusing unsafe file path ${path}`);
3235
- }
3236
- function hasUnsafeFileApiSegment(path) {
3237
- return path.split("/").some((segment) => segment === "." || segment === ".." || segment === ".sidecar");
3238
- }
3239
- function hasControlCharacter(value) {
3240
- for (let i = 0; i < value.length; i++) {
3241
- const code = value.charCodeAt(i);
3242
- if (code < 32 || code === 127) return true;
3243
- }
3244
- return false;
3245
- }
3246
- function normalizeAbsolutePrefixes(prefixes) {
3247
- return prefixes.map((prefix) => {
3248
- const normalized = prefix.trim().replace(/\/+$/, "");
3249
- if (!normalized.startsWith("/") || hasControlCharacter(normalized)) throw new Error(`materializeProfileFileMounts: fileApiAbsolutePrefixes must contain absolute paths; received ${JSON.stringify(prefix)}`);
3250
- if (hasUnsafeFileApiSegment(normalized)) throw new Error(`materializeProfileFileMounts: fileApiAbsolutePrefixes contains unsafe path ${JSON.stringify(prefix)}`);
3251
- return normalized;
3252
- });
3253
- }
3254
- function isAllowedAbsoluteFileApiPath(path, prefixes) {
3255
- for (const prefix of prefixes) if (path === prefix || path.startsWith(`${prefix}/`)) return true;
3256
- return false;
3257
- }
3258
- function fileApiTarget(mount, absolutePrefixes) {
3259
- if (mount.path.startsWith("~/")) {
3260
- const homePath = `${PROFILE_AGENT_HOME}/${mount.path.slice(2)}`;
3261
- return isAllowedAbsoluteFileApiPath(homePath, absolutePrefixes) ? homePath : null;
3262
- }
3263
- if (mount.path.startsWith("/")) return isAllowedAbsoluteFileApiPath(mount.path, absolutePrefixes) ? mount.path : null;
3264
- if (mount.path.startsWith("~")) return null;
3265
- if (mount.path.length === 0) return null;
3266
- return mount.path;
3267
- }
3268
- function isExecutableProfileFile(mount) {
3269
- return mount.executable ?? PROFILE_BIN_DIR_RE.test(mount.path);
3270
- }
3271
- function profileFileMode(mount) {
3272
- return isExecutableProfileFile(mount) ? 493 : void 0;
3273
- }
3274
- function fileApiSupportsMode(box) {
3275
- return box.fs?.supportsWriteMode === true;
3276
- }
3277
- function isFileApiRootOnlyError(error) {
3278
- return error instanceof SandboxError && error.status === 403 && error.message.includes("Absolute path is outside allowed roots");
3279
- }
3280
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3281
- var ProfileFileMountExecTimeoutError = class extends Error {
3282
- constructor(timeoutMs) {
3283
- super(`exec exceeded ${timeoutMs}ms`);
3284
- this.name = "ProfileFileMountExecTimeoutError";
3285
- }
3286
- };
3287
- function execWithTimeout(box, cmd, timeoutMs) {
3288
- return new Promise((resolve, reject) => {
3289
- let settled = false;
3290
- const timer = setTimeout(() => {
3291
- if (settled) return;
3292
- settled = true;
3293
- reject(new ProfileFileMountExecTimeoutError(timeoutMs));
3294
- }, timeoutMs);
3295
- box.exec(cmd, { timeoutMs }).then((res) => {
3296
- if (settled) return;
3297
- settled = true;
3298
- clearTimeout(timer);
3299
- resolve(res);
3300
- }, (err) => {
3301
- if (settled) return;
3302
- settled = true;
3303
- clearTimeout(timer);
3304
- reject(err);
3305
- });
3306
- });
3307
- }
3308
- const TRANSIENT_EXEC_STATUS_CODES = new Set([
3309
- 408,
3310
- 409,
3311
- 425,
3312
- 429,
3313
- 500,
3314
- 502,
3315
- 503,
3316
- 504
3317
- ]);
3318
- const TRANSIENT_EXEC_CODE_RE = /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ECONNABORTED)$/i;
3319
- 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;
3320
- function errorStatus(err) {
3321
- const rawStatus = err.status ?? err.statusCode ?? (err.response && typeof err.response === "object" ? err.response.status : void 0);
3322
- if (typeof rawStatus === "number") return rawStatus;
3323
- if (typeof rawStatus === "string" && /^\d+$/.test(rawStatus)) return Number(rawStatus);
3324
- }
3325
- function retryAfterMs(err, seen = /* @__PURE__ */ new Set()) {
3326
- if (!err || typeof err !== "object") return void 0;
3327
- if (seen.has(err)) return void 0;
3328
- seen.add(err);
3329
- const e = err;
3330
- if (typeof e.retryAfterMs === "number") return e.retryAfterMs;
3331
- return retryAfterMs(e.cause, seen);
3332
- }
3333
- function isTransientExecError(err, seen = /* @__PURE__ */ new Set()) {
3334
- if (!err || typeof err !== "object") return false;
3335
- if (seen.has(err)) return false;
3336
- seen.add(err);
3337
- const e = err;
3338
- const status = errorStatus(e);
3339
- if (status !== void 0 && TRANSIENT_EXEC_STATUS_CODES.has(status)) return true;
3340
- if (typeof e.code === "string") {
3341
- if (TRANSIENT_EXEC_CODE_RE.test(e.code)) return true;
3342
- if (/rate.?limit|too.?many.?requests|429|server.?error|service.?unavailable/i.test(e.code)) return true;
3343
- }
3344
- if (typeof e.message === "string" && TRANSIENT_EXEC_MESSAGE_RE.test(e.message)) return true;
3345
- return isTransientExecError(e.cause, seen);
3346
- }
3347
- function transientExecError(err) {
3348
- if (err instanceof ProfileFileMountExecTimeoutError) return { retryable: false };
3349
- if (isTransientExecError(err)) return {
3350
- retryable: true,
3351
- retryAfterMs: retryAfterMs(err)
3352
- };
3353
- return { retryable: false };
3354
- }
3355
- function isUndecidedWriteFailure(err) {
3356
- if (err instanceof NetworkError) return true;
3357
- if (!err || typeof err !== "object") return false;
3358
- const status = errorStatus(err);
3359
- return status !== void 0 && UNDECIDED_WRITE_STATUSES.has(status);
3360
- }
3361
- /**
3362
- * Run one file API batch write, sending it again after an undecided answer.
3363
- *
3364
- * Only a batch without write preconditions comes here, so a repeat after a
3365
- * write that did land leaves the same files with the same content and mode.
3366
- * A decided refusal is thrown at once. Retries stop at `maxRetries`, or when
3367
- * the next attempt would start past {@link PROFILE_FILE_MOUNT_WRITE_RETRY_BUDGET_MS}.
3368
- */
3369
- async function writeBatchRidingOutUndecided(write, maxRetries) {
3370
- const startedAt = Date.now();
3371
- for (let attempt = 0;; attempt += 1) try {
3372
- await write();
3373
- return;
3374
- } catch (err) {
3375
- if (!isUndecidedWriteFailure(err) || attempt >= maxRetries) throw err;
3376
- const waitMs = retryAfterMs(err) ?? Math.min(PROFILE_FILE_MOUNT_RETRY_BASE_MS * 2 ** attempt, PROFILE_FILE_MOUNT_RETRY_MAX_MS);
3377
- if (Date.now() - startedAt + waitMs >= PROFILE_FILE_MOUNT_WRITE_RETRY_BUDGET_MS) throw err;
3378
- await sleep(waitMs);
3379
- }
3380
- }
3381
- async function sha256Hex(content) {
3382
- const bytes = new TextEncoder().encode(content);
3383
- const webSubtle = globalThis.crypto?.subtle;
3384
- if (webSubtle) {
3385
- const digest = await webSubtle.digest("SHA-256", bytes);
3386
- return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
3387
- }
3388
- const { createHash } = await import("node:crypto");
3389
- return createHash("sha256").update(content, "utf8").digest("hex");
3390
- }
3391
- async function execProfileFileMount(box, mount, content, options, execState) {
3392
- const maxRetries = options.maxRetries ?? PROFILE_FILE_MOUNT_MAX_RETRIES;
3393
- const path = mount.path;
3394
- const b64 = encodeTextForWire(content);
3395
- const b64Chunks = [];
3396
- 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));
3397
- const expectedSha256 = await sha256Hex(content);
3398
- const dir = path.replace(/\/[^/]*$/, "");
3399
- const executable = isExecutableProfileFile(mount);
3400
- const q = shellPath(path);
3401
- const qb64 = shellPath(`${path}.b64`);
3402
- const qtmp = shellPath(`${path}.tmp`);
3403
- const qpartPrefix = shellPath(`${path}.b64.part.`);
3404
- const homeGuard = path.startsWith("~/") ? `[ -n "$HOME" ] || { echo ${shellSingleQuote(`materializeProfileFileMounts: HOME is unset for ${path}`)} >&2; exit 1; }; ` : "";
3405
- const run = async (cmd) => {
3406
- for (let attempt = 0;; attempt++) {
3407
- if (execState.started && options.paceMs > 0) await sleep(options.paceMs);
3408
- execState.started = true;
3409
- try {
3410
- return await execWithTimeout(box, cmd, options.execTimeoutMs);
3411
- } catch (err) {
3412
- const { retryable, retryAfterMs: retryAfter } = transientExecError(err);
3413
- if (retryable && attempt < maxRetries) {
3414
- const backoff = Math.min(PROFILE_FILE_MOUNT_RETRY_BASE_MS * 2 ** attempt, PROFILE_FILE_MOUNT_RETRY_MAX_MS);
3415
- await sleep(Math.min(retryAfter ?? backoff, PROFILE_FILE_MOUNT_RETRY_MAX_MS));
3416
- continue;
3417
- }
3418
- throw new Error(`materializeProfileFileMounts: exec failed for ${path}`, { cause: err });
3419
- }
3420
- }
3421
- };
3422
- const step = async (cmd) => {
3423
- const result = await run(`${homeGuard}${cmd}`);
3424
- if (result.exitCode !== 0) throw new Error(`materializeProfileFileMounts: failed to write ${path} (exit ${result.exitCode}): ${result.stderr.slice(0, 500)}`);
3425
- };
3426
- await step(dir ? `mkdir -p ${shellPath(dir)}` : ":");
3427
- for (let i = 0; i < b64Chunks.length; i++) {
3428
- const slice = b64Chunks[i];
3429
- if (slice === void 0) continue;
3430
- await step(`printf '%s' '${slice}' > ${shellPath(`${path}.b64.part.${i}`)}`);
3431
- }
3432
- const chmod = executable ? `chmod +x ${q} || exit 1; ` : "";
3433
- const checksumMismatch = shellSingleQuote(`materializeProfileFileMounts: checksum mismatch for ${path}`);
3434
- 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; }`);
3435
- }
3436
- async function materializeProfileFileMounts(box, files, options = {}) {
3437
- const execTimeoutMs = options.execTimeoutMs ?? PROFILE_FILE_MOUNT_EXEC_TIMEOUT_MS;
3438
- const paceMs = options.paceMs ?? PROFILE_FILE_MOUNT_PACE_MS;
3439
- const maxRetries = options.maxRetries ?? PROFILE_FILE_MOUNT_MAX_RETRIES;
3440
- const absolutePrefixes = normalizeAbsolutePrefixes(options.fileApiAbsolutePrefixes ?? DEFAULT_PROFILE_FILE_API_ABSOLUTE_PREFIXES);
3441
- const fs = box.fs;
3442
- const fileApiAvailable = typeof fs?.writeMany === "function";
3443
- const modeAwareFileApi = fileApiSupportsMode(box);
3444
- const uploadDataFn = fs?.uploadData;
3445
- const viaFileApi = [];
3446
- const viaHomeFileApi = [];
3447
- const viaExec = [];
3448
- const viaUpload = [];
3449
- for (const mount of files) {
3450
- const content = inlineContent(mount);
3451
- validateProfileFilePath(mount.path);
3452
- const target = fileApiAvailable ? fileApiTarget(mount, absolutePrefixes) : null;
3453
- const executable = isExecutableProfileFile(mount);
3454
- if (target !== null && (!executable || modeAwareFileApi)) {
3455
- const mode = profileFileMode(mount);
3456
- const contentBytes = new TextEncoder().encode(content).byteLength;
3457
- if (!fitsSingleShotWrite(content, contentBytes)) {
3458
- 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`);
3459
- viaUpload.push({
3460
- path: target,
3461
- content,
3462
- ...mode !== void 0 ? { mode } : {}
3463
- });
3464
- continue;
3465
- }
3466
- const write = {
3467
- path: target,
3468
- content,
3469
- ...mode !== void 0 ? { mode } : {}
3470
- };
3471
- if (mount.path.startsWith("~/")) viaHomeFileApi.push({
3472
- mount,
3473
- ...write
3474
- });
3475
- else viaFileApi.push(write);
3476
- } else viaExec.push({
3477
- mount,
3478
- content
3479
- });
3480
- }
3481
- if (viaFileApi.length > 0) try {
3482
- await writeBatchRidingOutUndecided(async () => fs?.writeMany(viaFileApi, {
3483
- paceMs,
3484
- maxRetries
3485
- }), maxRetries);
3486
- } catch (err) {
3487
- throw new Error("materializeProfileFileMounts: file API batch write failed", { cause: err });
3488
- }
3489
- let homeFilesWrittenByApi = 0;
3490
- if (viaHomeFileApi.length > 0) {
3491
- const homeWrites = viaHomeFileApi.map(({ path, content, mode }) => ({
3492
- path,
3493
- content,
3494
- ...mode !== void 0 ? { mode } : {}
3495
- }));
3496
- try {
3497
- await writeBatchRidingOutUndecided(async () => fs?.writeMany(homeWrites, {
3498
- paceMs,
3499
- maxRetries
3500
- }), maxRetries);
3501
- homeFilesWrittenByApi = viaHomeFileApi.length;
3502
- } catch (err) {
3503
- if (!isFileApiRootOnlyError(err)) throw new Error("materializeProfileFileMounts: home file API batch write failed", { cause: err });
3504
- viaExec.push(...viaHomeFileApi.map(({ mount, content }) => ({
3505
- mount,
3506
- content
3507
- })));
3508
- }
3509
- }
3510
- if (viaUpload.length > 0) {
3511
- if (typeof uploadDataFn !== "function") throw new Error("materializeProfileFileMounts: viaUpload entries exist but fs.uploadData is unavailable");
3512
- for (const item of viaUpload) try {
3513
- await uploadDataFn(item.path, item.content, {
3514
- ...item.mode !== void 0 ? { mode: item.mode } : {},
3515
- paceMs,
3516
- maxRetries
3517
- });
3518
- } catch (err) {
3519
- throw new Error(`materializeProfileFileMounts: uploadData failed for ${item.path}`, { cause: err });
3520
- }
3521
- }
3522
- const execState = { started: false };
3523
- for (const item of viaExec) await execProfileFileMount(box, item.mount, item.content, {
3524
- execTimeoutMs,
3525
- paceMs,
3526
- maxRetries
3527
- }, execState);
3528
- return {
3529
- written: viaFileApi.length + homeFilesWrittenByApi + viaExec.length + viaUpload.length,
3530
- viaFileApi: viaFileApi.length + homeFilesWrittenByApi,
3531
- viaExec: viaExec.length,
3532
- viaUpload: viaUpload.length
3533
- };
3534
- }
3535
- //#endregion
3536
3099
  //#region src/session-events.ts
3537
3100
  async function broadcastSessionEvent(client, sessionId, event) {
3538
3101
  if (!sessionId.trim()) throw new ValidationError("Session ID is required");
@@ -3924,6 +3487,7 @@ var Sandbox = class Sandbox {
3924
3487
  }
3925
3488
  async create(inputOptions, requestOptions) {
3926
3489
  let options = inputOptions;
3490
+ normalizeRuntimeBackendConfig(options?.backend);
3927
3491
  if (options?.backend?.runtimeAttachments !== void 0) {
3928
3492
  normalizeRuntimeBackendConfig(options.backend);
3929
3493
  options = {
@@ -3969,7 +3533,7 @@ var Sandbox = class Sandbox {
3969
3533
  handleProfile = split.leanProfile;
3970
3534
  if (deferredProfileFiles.length > 0) {
3971
3535
  profileFilesFailOnError = profile.resources?.failOnError !== false;
3972
- if (profileFilesFailOnError) validateDeferredProfileFileMounts(deferredProfileFiles);
3536
+ validateDeferredProfileFileMounts(deferredProfileFiles);
3973
3537
  }
3974
3538
  }
3975
3539
  handleBackend = {
@@ -4123,7 +3687,7 @@ var Sandbox = class Sandbox {
4123
3687
  signal: requestOptions?.signal
4124
3688
  });
4125
3689
  }
4126
- if (deferredProfileFiles.length > 0) {
3690
+ if (deferredProfileFiles.length > 0 && resolvedBackend?.profile !== void 0) {
4127
3691
  if (instance.status !== "running") {
4128
3692
  const paths = deferredProfileFiles.map((file) => file.path);
4129
3693
  const message = `Sandbox ${instance.id} reached status "${instance.status}" before its ${deferredProfileFiles.length} deferred inline profile file mount(s) [${paths.join(", ")}] could be materialized. The sandbox was NOT deleted — inspect it, or recreate with autoMaterializeProfileFiles: false.`;
@@ -4134,7 +3698,7 @@ var Sandbox = class Sandbox {
4134
3698
  throw new PartialFailureError(message, "PROFILE_FILES_MATERIALIZE_FAILED", 502, void 0, paths.map((path) => ({ path })));
4135
3699
  }
4136
3700
  try {
4137
- await materializeProfileFileMounts(instance, deferredProfileFiles);
3701
+ await instance.materializeProfileFiles(resolvedBackend.profile, void 0, "replace");
4138
3702
  } catch (err) {
4139
3703
  const paths = deferredProfileFiles.map((file) => file.path);
4140
3704
  const message = `Sandbox ${instance.id} is RUNNING but INCOMPLETELY PROVISIONED: materialization of its ${deferredProfileFiles.length} deferred inline profile file mount(s) failed partway; some or all of [${paths.join(", ")}] may be missing in the sandbox. The sandbox was NOT deleted — inspect it, retry writing the files yourself, or delete it once you've recovered what you need. Cause: ${err instanceof Error ? err.message : String(err)}`;
@@ -4938,4 +4502,4 @@ var TeamsClient = class {
4938
4502
  }
4939
4503
  };
4940
4504
  //#endregion
4941
- export { backendRegistryInteractionKindSchema as _, splitInlineProfileSkills as a, parseBackendRegistryResponse as b, InstanceRestartingError as c, SandboxFleetClient as d, runtimeWorkspaceCwdSchema as f, backendRegistryEntrySchema as g, backendRegistryCapabilitiesSchema as h, splitInlineProfileFileMounts as i, InstancesClient as l, validateBatchRunRequest as m, Sandbox as n, validateDeferredProfileFileMounts as o, createBatchResultAccumulator as p, materializeProfileFileMounts as r, HostedInstance as s, IntelligenceClient as t, SandboxFleet as u, backendRegistryResponseSchema as v, parseBackendRegistryResponseBody as x, isBackendRegistryInteractionKind as y };
4505
+ export { parseBackendRegistryResponseBody as _, InstancesClient as a, runtimeWorkspaceCwdSchema as c, backendRegistryCapabilitiesSchema as d, backendRegistryEntrySchema as f, parseBackendRegistryResponse as g, isBackendRegistryInteractionKind as h, InstanceRestartingError as i, createBatchResultAccumulator as l, backendRegistryResponseSchema as m, Sandbox as n, SandboxFleet as o, backendRegistryInteractionKindSchema as p, HostedInstance as r, SandboxFleetClient as s, IntelligenceClient as t, validateBatchRunRequest as u };
@@ -1,4 +1,4 @@
1
- import { l as TraceExportResult, n as HttpClient, r as SandboxInstance, u as TraceExportSink } from "./sandbox-flgG5fbm.js";
1
+ import { l as TraceExportResult, n as HttpClient, r as SandboxInstance, u as TraceExportSink } from "./sandbox-BxxNbLpt.js";
2
2
  import { l as ScopedToken, s as MintInteractiveSessionTokenOptions } from "./terminal-stream-BUMu8Oae.js";
3
3
  import { P as LinesClient } from "./lines-CBlVXTb_.js";
4
4
  import { $n as PublicTemplateInfo, Ar as SandboxFleetArtifact, B as CreateSandboxOptions, Bt as FleetDispatchStreamOptions, Ea as UsageInfo, En as ListSandboxOptions, Er as SandboxEnvironment, F as CreateIntelligenceReportOptions, Fi as SecretsManager, Fr as SandboxFleetDriverCapability, Ft as FleetAgentResult, G as DeleteMatchingSandboxesFilter, Gr as SandboxFleetOperationsSummary, Gt as FleetMachineId, Hr as SandboxFleetMachineSpec, Ht as FleetDriveTurnRequest, I as CreateRequestOptions, Jn as PromptResult, Jr as SandboxFleetPolicy, Jt as FleetRunEvent, K as DeleteMatchingSandboxesOptions, Kn as PromptInputPart, Kr as SandboxFleetParent, Kt as FleetPromptDispatchOptions, L as CreateSandboxFleetOptions, Lr as SandboxFleetInfo, Lt as FleetDispatchCancelResult, M as ConversationTurnOptions, Mr as SandboxFleetCostEstimate, N as ConversationTurnResult, Nt as FleetAgentId, Or as SandboxFleetAgent, Pa as BatchEvent, Pr as SandboxFleetDispatchResponse, Qr as SandboxFleetTraceBundle, R as CreateSandboxFleetTokenOptions, Rt as FleetDispatchResultBuffer, Tn as ListSandboxFleetOptions, Ur as SandboxFleetManifest, Ut as FleetExecDispatchOptions, Vr as SandboxFleetMachineRecord, Vt as FleetDriveTurnOutcome, Wt as FleetExecDispatchResult, Xr as SandboxFleetSpend, Yt as FleetRunOptions, Zr as SandboxFleetToken, _n as IntelligenceReport, aa as SshKeysManager, ai as SandboxFleetWorkspaceRestoreResult, ar as ReconcileSandboxFleetsOptions, b as BatchRunRequest, ba as TokenRefreshHandler, ci as SandboxInfo, d as BackendConfig, er as PublicTemplateVersionInfo, ii as SandboxFleetWorkspaceReconcileResult, ir as ReapExpiredSandboxFleetsResult, jr as SandboxFleetArtifactSpec, l as AttachSandboxFleetMachineOptions, la as SubscriptionInfo, ni as SandboxFleetUsage, nr as PublishPublicTemplateVersionOptions, oi as SandboxFleetWorkspaceSnapshotResult, or as ReconcileSandboxFleetsResult, q as DeleteMatchingSandboxesResult, qn as PromptOptions, qt as FleetPromptDispatchResult, rr as ReapExpiredSandboxFleetsOptions, si as SandboxIdentity, ti as SandboxFleetTraceOptions, tr as PublishPublicTemplateOptions, v as BatchResult, vn as IntelligenceReportBudget, vt as ExecOptions, xn as IntelligenceReportWindow, y as BatchRunOptions, yi as SandboxShapesInfo, yn as IntelligenceReportCompareTo, yr as SandboxConfig, yt as ExecResult, z as CreateSandboxFleetWithCoordinatorOptions, zt as FleetDispatchResultBufferOptions } from "./types-7TNwywMg.js";
package/dist/core.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { a as WorkspaceImagePublishRequestOptions, i as WorkspaceImagePublishInput, o as WorkspaceImagePublishResult, r as SandboxInstance, s as WorkspaceImages } from "./sandbox-flgG5fbm.js";
1
+ import { a as WorkspaceImagePublishRequestOptions, i as WorkspaceImagePublishInput, o as WorkspaceImagePublishResult, r as SandboxInstance, s as WorkspaceImages } from "./sandbox-BxxNbLpt.js";
2
2
  import { B as LINE_APPLICATION_REQUEST_MAX_BYTES, D as LineSendReceipt, E as LineSendInput, G as LineApplicationView, H as LineApplicationRequest, K as parseLineApplicationRequest, L as lineInstanceKey, O as LineSenderVerification, P as LinesClient, R as profileChannelReference, U as LineApplicationResult, V as LineApplication, W as LineApplicationState, a as LineApplicationAttachOptions, b as LineProvider, c as LineAttachmentReauthorization, d as LineInstanceAttachOptions, f as LineInstanceCreate, h as LineMemberInstance, k as LineSenderVerificationStart, l as LineExecutionKey, m as LineMember, n as LineAgentRolePolicy, q as parseLineApplicationResult, s as LineAttachment, t as Line, x as LineReminderPreferences, y as LineNumberInventory, z as LINE_APPLICATION_REPLY_MAX_CHARS } from "./lines-CBlVXTb_.js";
3
3
  import { An as NetworkConfig, B as CreateSandboxOptions, Fn as PreviewLinkInfo, Ga as ManagedProcessRecord, Ha as ManagedProcessClient, In as PreviewLinkManager, Ka as ManagedProcessSpec, Kn as PromptInputPart, Ln as PreviewLinkWaitOptions, M as ConversationTurnOptions, N as ConversationTurnResult, Ua as ManagedProcessJobs, Wa as ManagedProcessOptions, Yi as SessionMessageAdmission, bi as SandboxStatus, ci as SandboxInfo, qa as ManagedProcessState, vt as ExecOptions, yr as SandboxConfig, yt as ExecResult } from "./types-7TNwywMg.js";
4
- import { A as isBackendRegistryInteractionKind, C as BackendRegistryEntry, D as backendRegistryEntrySchema, E as backendRegistryCapabilitiesSchema, M as parseBackendRegistryResponseBody, O as backendRegistryInteractionKindSchema, S as BackendRegistryCapabilities, T as BackendRegistryResponse, d as HostedInstance, f as InstanceProfile, g as InstancesClient, i as Sandbox, j as parseBackendRegistryResponse, k as backendRegistryResponseSchema, m as InstanceRestartingError, p as InstanceRecord, u as EnsureInstanceOptions, w as BackendRegistryInteractionKind } from "./client-BSWUEYZV.js";
4
+ import { A as isBackendRegistryInteractionKind, C as BackendRegistryEntry, D as backendRegistryEntrySchema, E as backendRegistryCapabilitiesSchema, M as parseBackendRegistryResponseBody, O as backendRegistryInteractionKindSchema, S as BackendRegistryCapabilities, T as BackendRegistryResponse, d as HostedInstance, f as InstanceProfile, g as InstancesClient, i as Sandbox, j as parseBackendRegistryResponse, k as backendRegistryResponseSchema, m as InstanceRestartingError, p as InstanceRecord, u as EnsureInstanceOptions, w as BackendRegistryInteractionKind } from "./client-DwSJkoBR.js";
5
5
  import { _ as TimeoutError, a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as StateError, h as ServerError, l as PartialFailureError, m as SandboxFailureDetail, n as CapabilityError, p as SandboxErrorJson, s as NetworkError, t as AuthError, u as QuotaError, v as ValidationError } from "./errors-CybOpzWU.js";
6
6
 
7
7
  //#region src/core.d.ts
package/dist/core.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, l as PartialFailureError, m as StateError, n as CapabilityError, p as ServerError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-D1JIX7Jm.js";
2
- import { _ as backendRegistryInteractionKindSchema, b as parseBackendRegistryResponse, c as InstanceRestartingError, g as backendRegistryEntrySchema, h as backendRegistryCapabilitiesSchema, l as InstancesClient, n as Sandbox, s as HostedInstance, v as backendRegistryResponseSchema, x as parseBackendRegistryResponseBody, y as isBackendRegistryInteractionKind } from "./client-DAndLVD6.js";
3
- import { o as WorkspaceImages, t as SandboxInstance, x as ManagedProcessClient } from "./sandbox-Do-2V95e.js";
2
+ import { _ as parseBackendRegistryResponseBody, a as InstancesClient, d as backendRegistryCapabilitiesSchema, f as backendRegistryEntrySchema, g as parseBackendRegistryResponse, h as isBackendRegistryInteractionKind, i as InstanceRestartingError, m as backendRegistryResponseSchema, n as Sandbox, p as backendRegistryInteractionKindSchema, r as HostedInstance } from "./client-D7a7RnRi.js";
3
+ import { o as WorkspaceImages, t as SandboxInstance, x as ManagedProcessClient } from "./sandbox-o39VWaxn.js";
4
4
  import { LinesClient, lineInstanceKey, profileChannelReference } from "./lines.js";
5
5
  import { i as parseLineApplicationResult, n as LINE_APPLICATION_REQUEST_MAX_BYTES, r as parseLineApplicationRequest, t as LINE_APPLICATION_REPLY_MAX_CHARS } from "./line-application-C2SuT1zK.js";
6
6
  //#region src/core.ts
@@ -1,4 +1,4 @@
1
- import { n as HttpClient, r as SandboxInstance } from "./sandbox-flgG5fbm.js";
1
+ import { n as HttpClient, r as SandboxInstance } from "./sandbox-BxxNbLpt.js";
2
2
  import { B as CreateSandboxOptions } from "./types-7TNwywMg.js";
3
3
 
4
4
  //#region src/tangle/abi.d.ts