@tangle-network/agent-app 0.60.227 → 0.60.228
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/dist/chat-routes/index.js +1 -1
- package/dist/{chunk-YS2RYZQG.js → chunk-JILHXHJE.js} +789 -745
- package/dist/chunk-JILHXHJE.js.map +1 -0
- package/dist/sandbox/access.d.ts +46 -0
- package/dist/sandbox/app-tools.d.ts +129 -0
- package/dist/sandbox/box-health.d.ts +8 -0
- package/dist/sandbox/configuration.d.ts +280 -0
- package/dist/sandbox/credentials.d.ts +55 -0
- package/dist/sandbox/exec-failure.d.ts +9 -0
- package/dist/sandbox/existing-box.d.ts +43 -0
- package/dist/sandbox/index.d.ts +32 -950
- package/dist/sandbox/index.js +1 -1
- package/dist/sandbox/lifecycle-errors.d.ts +51 -0
- package/dist/sandbox/payload-limits.d.ts +55 -0
- package/dist/sandbox/product-egress.d.ts +4 -0
- package/dist/sandbox/profile-corpus.d.ts +16 -0
- package/dist/sandbox/profile-files.d.ts +16 -0
- package/dist/sandbox/prompt-dispatch.d.ts +14 -0
- package/dist/sandbox/prompt-events.d.ts +71 -0
- package/dist/sandbox/prompt-options.d.ts +79 -0
- package/dist/sandbox/prompt-profile.d.ts +61 -0
- package/dist/sandbox/prompt-result.d.ts +57 -0
- package/dist/sandbox/runtime-cache.d.ts +43 -0
- package/dist/sandbox/runtime-connection.d.ts +9 -0
- package/dist/sandbox/shell-path.d.ts +2 -0
- package/dist/sandbox/workspace-boxes.d.ts +76 -0
- package/dist/sandbox/workspace-claim.d.ts +13 -0
- package/dist/sandbox/workspace-provision.d.ts +9 -0
- package/package.json +1 -1
- package/dist/chunk-YS2RYZQG.js.map +0 -1
|
@@ -29,20 +29,6 @@ import {
|
|
|
29
29
|
trimOrNull
|
|
30
30
|
} from "./chunk-D6UJEOZQ.js";
|
|
31
31
|
|
|
32
|
-
// src/sandbox/index.ts
|
|
33
|
-
import {
|
|
34
|
-
Sandbox
|
|
35
|
-
} from "@tangle-network/sandbox/core";
|
|
36
|
-
import { createHash } from "crypto";
|
|
37
|
-
import { mergeAgentProfiles } from "@tangle-network/agent-interface";
|
|
38
|
-
|
|
39
|
-
// src/sandbox/outcome.ts
|
|
40
|
-
var ok = (value) => ({ succeeded: true, value });
|
|
41
|
-
var fail = (error) => ({
|
|
42
|
-
succeeded: false,
|
|
43
|
-
error: error instanceof Error ? error : new Error(String(error))
|
|
44
|
-
});
|
|
45
|
-
|
|
46
32
|
// src/sandbox/prompt-trace.ts
|
|
47
33
|
var asRec = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
48
34
|
var asNum = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
@@ -216,6 +202,66 @@ function workersReuseStore() {
|
|
|
216
202
|
return createCacheReuseStore(() => storage.open(CACHE_NAME));
|
|
217
203
|
}
|
|
218
204
|
|
|
205
|
+
// src/sandbox/binary-read.ts
|
|
206
|
+
function shellQuote(value) {
|
|
207
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
208
|
+
}
|
|
209
|
+
function base64ToBytes(base64) {
|
|
210
|
+
const binary = atob(base64);
|
|
211
|
+
const bytes = new Uint8Array(binary.length);
|
|
212
|
+
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
|
|
213
|
+
return bytes;
|
|
214
|
+
}
|
|
215
|
+
function execInSandbox(box, command, options) {
|
|
216
|
+
return options?.sessionId ? box.exec(command, { sessionId: options.sessionId }) : box.exec(command);
|
|
217
|
+
}
|
|
218
|
+
async function statSandboxFileSize(box, absolutePath, options) {
|
|
219
|
+
const quotedPath = shellQuote(absolutePath);
|
|
220
|
+
let result;
|
|
221
|
+
try {
|
|
222
|
+
result = await execInSandbox(box, `wc -c < ${quotedPath}`, options);
|
|
223
|
+
} catch (err) {
|
|
224
|
+
return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
|
|
225
|
+
}
|
|
226
|
+
if (result.exitCode !== 0) {
|
|
227
|
+
return { succeeded: false, error: result.stderr || "unknown error" };
|
|
228
|
+
}
|
|
229
|
+
const size = Number.parseInt(result.stdout.trim(), 10);
|
|
230
|
+
if (!Number.isFinite(size)) {
|
|
231
|
+
return { succeeded: false, error: `could not parse file size from "${result.stdout.trim()}"` };
|
|
232
|
+
}
|
|
233
|
+
return { succeeded: true, value: size };
|
|
234
|
+
}
|
|
235
|
+
async function readSandboxBinaryBytes(box, absolutePath, expectedSize, options) {
|
|
236
|
+
const quotedPath = shellQuote(absolutePath);
|
|
237
|
+
let result;
|
|
238
|
+
try {
|
|
239
|
+
result = await execInSandbox(box, `base64 ${quotedPath}`, options);
|
|
240
|
+
} catch (err) {
|
|
241
|
+
return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
|
|
242
|
+
}
|
|
243
|
+
if (result.exitCode !== 0) {
|
|
244
|
+
return { succeeded: false, error: result.stderr || "unknown error" };
|
|
245
|
+
}
|
|
246
|
+
const cleaned = result.stdout.replace(/\s+/g, "");
|
|
247
|
+
let bytes;
|
|
248
|
+
try {
|
|
249
|
+
bytes = base64ToBytes(cleaned);
|
|
250
|
+
} catch (err) {
|
|
251
|
+
return {
|
|
252
|
+
succeeded: false,
|
|
253
|
+
error: `could not decode file contents: ${err instanceof Error ? err.message : String(err)}`
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
if (bytes.byteLength !== expectedSize) {
|
|
257
|
+
return {
|
|
258
|
+
succeeded: false,
|
|
259
|
+
error: `read returned ${bytes.byteLength} bytes, expected ${expectedSize} \u2014 output truncated in transit`
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
return { succeeded: true, value: { bytes, size: expectedSize } };
|
|
263
|
+
}
|
|
264
|
+
|
|
219
265
|
// src/sandbox/model.ts
|
|
220
266
|
function backendModelFields(model) {
|
|
221
267
|
return {
|
|
@@ -297,66 +343,6 @@ function requireTransportableModel(selection, context) {
|
|
|
297
343
|
return void 0;
|
|
298
344
|
}
|
|
299
345
|
|
|
300
|
-
// src/sandbox/binary-read.ts
|
|
301
|
-
function shellQuote(value) {
|
|
302
|
-
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
303
|
-
}
|
|
304
|
-
function base64ToBytes(base64) {
|
|
305
|
-
const binary = atob(base64);
|
|
306
|
-
const bytes = new Uint8Array(binary.length);
|
|
307
|
-
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
|
|
308
|
-
return bytes;
|
|
309
|
-
}
|
|
310
|
-
function execInSandbox(box, command, options) {
|
|
311
|
-
return options?.sessionId ? box.exec(command, { sessionId: options.sessionId }) : box.exec(command);
|
|
312
|
-
}
|
|
313
|
-
async function statSandboxFileSize(box, absolutePath, options) {
|
|
314
|
-
const quotedPath = shellQuote(absolutePath);
|
|
315
|
-
let result;
|
|
316
|
-
try {
|
|
317
|
-
result = await execInSandbox(box, `wc -c < ${quotedPath}`, options);
|
|
318
|
-
} catch (err) {
|
|
319
|
-
return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
|
|
320
|
-
}
|
|
321
|
-
if (result.exitCode !== 0) {
|
|
322
|
-
return { succeeded: false, error: result.stderr || "unknown error" };
|
|
323
|
-
}
|
|
324
|
-
const size = Number.parseInt(result.stdout.trim(), 10);
|
|
325
|
-
if (!Number.isFinite(size)) {
|
|
326
|
-
return { succeeded: false, error: `could not parse file size from "${result.stdout.trim()}"` };
|
|
327
|
-
}
|
|
328
|
-
return { succeeded: true, value: size };
|
|
329
|
-
}
|
|
330
|
-
async function readSandboxBinaryBytes(box, absolutePath, expectedSize, options) {
|
|
331
|
-
const quotedPath = shellQuote(absolutePath);
|
|
332
|
-
let result;
|
|
333
|
-
try {
|
|
334
|
-
result = await execInSandbox(box, `base64 ${quotedPath}`, options);
|
|
335
|
-
} catch (err) {
|
|
336
|
-
return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
|
|
337
|
-
}
|
|
338
|
-
if (result.exitCode !== 0) {
|
|
339
|
-
return { succeeded: false, error: result.stderr || "unknown error" };
|
|
340
|
-
}
|
|
341
|
-
const cleaned = result.stdout.replace(/\s+/g, "");
|
|
342
|
-
let bytes;
|
|
343
|
-
try {
|
|
344
|
-
bytes = base64ToBytes(cleaned);
|
|
345
|
-
} catch (err) {
|
|
346
|
-
return {
|
|
347
|
-
succeeded: false,
|
|
348
|
-
error: `could not decode file contents: ${err instanceof Error ? err.message : String(err)}`
|
|
349
|
-
};
|
|
350
|
-
}
|
|
351
|
-
if (bytes.byteLength !== expectedSize) {
|
|
352
|
-
return {
|
|
353
|
-
succeeded: false,
|
|
354
|
-
error: `read returned ${bytes.byteLength} bytes, expected ${expectedSize} \u2014 output truncated in transit`
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
return { succeeded: true, value: { bytes, size: expectedSize } };
|
|
358
|
-
}
|
|
359
|
-
|
|
360
346
|
// src/sandbox/workspace-sandbox-manager.ts
|
|
361
347
|
function createWorkspaceSandboxManager(opts) {
|
|
362
348
|
return {
|
|
@@ -1489,7 +1475,7 @@ function createEscalationSpeculator(options) {
|
|
|
1489
1475
|
};
|
|
1490
1476
|
}
|
|
1491
1477
|
|
|
1492
|
-
// src/sandbox/
|
|
1478
|
+
// src/sandbox/credentials.ts
|
|
1493
1479
|
var DEFAULT_SANDBOX_DIRECT_KEY_NAMES = [
|
|
1494
1480
|
"TCLOUD_SANDBOX_API_KEY",
|
|
1495
1481
|
"SANDBOX_API_KEY",
|
|
@@ -1554,6 +1540,18 @@ async function resolveSandboxClientCredentials(options = {}) {
|
|
|
1554
1540
|
`Sandbox credentials are required for ${environment} (provide a provision callback${directHint}).`
|
|
1555
1541
|
);
|
|
1556
1542
|
}
|
|
1543
|
+
|
|
1544
|
+
// src/sandbox/configuration.ts
|
|
1545
|
+
var DEFAULT_SANDBOX_RESOURCES = {
|
|
1546
|
+
image: "universal",
|
|
1547
|
+
cpuCores: 2,
|
|
1548
|
+
memoryMB: 4096,
|
|
1549
|
+
diskGB: 10,
|
|
1550
|
+
maxLifetimeSeconds: 86400,
|
|
1551
|
+
idleTimeoutSeconds: 3600
|
|
1552
|
+
};
|
|
1553
|
+
|
|
1554
|
+
// src/sandbox/product-egress.ts
|
|
1557
1555
|
function isWellFormedDomainPattern(pattern) {
|
|
1558
1556
|
if (!pattern || pattern.startsWith(".") || pattern.includes("..")) return false;
|
|
1559
1557
|
const labels = pattern.split(".");
|
|
@@ -1586,14 +1584,9 @@ function buildProductEgressPolicy(publicOrigin, extraDomains = []) {
|
|
|
1586
1584
|
includeImplicitDomains: false
|
|
1587
1585
|
};
|
|
1588
1586
|
}
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
memoryMB: 4096,
|
|
1593
|
-
diskGB: 10,
|
|
1594
|
-
maxLifetimeSeconds: 86400,
|
|
1595
|
-
idleTimeoutSeconds: 3600
|
|
1596
|
-
};
|
|
1587
|
+
|
|
1588
|
+
// src/sandbox/runtime-cache.ts
|
|
1589
|
+
import { Sandbox } from "@tangle-network/sandbox/core";
|
|
1597
1590
|
var _cached = null;
|
|
1598
1591
|
var TRUSTED_REUSE_TTL_MS = 10 * 6e4;
|
|
1599
1592
|
var REUSE_CHECKS_MAX = 1e3;
|
|
@@ -1666,6 +1659,90 @@ function resetClientCache() {
|
|
|
1666
1659
|
defaultReuseStore = void 0;
|
|
1667
1660
|
activeReuseStore = null;
|
|
1668
1661
|
}
|
|
1662
|
+
function rememberRunningBox(name, box) {
|
|
1663
|
+
runningBoxIds.delete(name);
|
|
1664
|
+
runningBoxIds.set(name, box.id);
|
|
1665
|
+
reuseNames.set(box.id, name);
|
|
1666
|
+
while (runningBoxIds.size > REUSE_CHECKS_MAX) {
|
|
1667
|
+
const oldest = runningBoxIds.keys().next().value;
|
|
1668
|
+
if (oldest === void 0) break;
|
|
1669
|
+
runningBoxIds.delete(oldest);
|
|
1670
|
+
}
|
|
1671
|
+
while (reuseNames.size > REUSE_CHECKS_MAX) {
|
|
1672
|
+
const oldest = reuseNames.keys().next().value;
|
|
1673
|
+
if (oldest === void 0) break;
|
|
1674
|
+
reuseNames.delete(oldest);
|
|
1675
|
+
}
|
|
1676
|
+
return box;
|
|
1677
|
+
}
|
|
1678
|
+
function boxNameFor(shell, options) {
|
|
1679
|
+
const scope = { workspaceId: options.workspaceId, ...options.userId ? { userId: options.userId } : {} };
|
|
1680
|
+
return shell.boxKey ? shell.boxKey(scope) : shell.name(options.workspaceId);
|
|
1681
|
+
}
|
|
1682
|
+
function hasRecentProbe(shell, options) {
|
|
1683
|
+
const probe = shell.livenessProbe;
|
|
1684
|
+
if (!probe || options.forceNew) return false;
|
|
1685
|
+
const id = runningBoxIds.get(boxNameFor(shell, options));
|
|
1686
|
+
return isRecent(id === void 0 ? void 0 : reuseChecks.get(id)?.alive, probe.cacheTtlMs ?? TRUSTED_REUSE_TTL_MS);
|
|
1687
|
+
}
|
|
1688
|
+
function reuseStoreOf(shell) {
|
|
1689
|
+
if (shell.reuseState !== void 0) return shell.reuseState;
|
|
1690
|
+
if (defaultReuseStore === void 0) defaultReuseStore = workersReuseStore();
|
|
1691
|
+
return defaultReuseStore;
|
|
1692
|
+
}
|
|
1693
|
+
async function hydrateReuseState(shell, options) {
|
|
1694
|
+
if (options.forceNew) return;
|
|
1695
|
+
const store = reuseStoreOf(shell);
|
|
1696
|
+
activeReuseStore = store;
|
|
1697
|
+
if (!store) return;
|
|
1698
|
+
const name = boxNameFor(shell, options);
|
|
1699
|
+
if (runningBoxIds.has(name)) return;
|
|
1700
|
+
try {
|
|
1701
|
+
const shared = await store.load(name);
|
|
1702
|
+
if (!shared) return;
|
|
1703
|
+
runningBoxIds.set(name, shared.boxId);
|
|
1704
|
+
reuseNames.set(shared.boxId, name);
|
|
1705
|
+
reuseChecks.set(shared.boxId, shared.checks);
|
|
1706
|
+
savedShared.set(name, JSON.stringify(shared));
|
|
1707
|
+
} catch {
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
async function persistReuseState(shell, box) {
|
|
1711
|
+
const store = reuseStoreOf(shell);
|
|
1712
|
+
const name = reuseNames.get(box.id);
|
|
1713
|
+
const checks = reuseChecks.get(box.id);
|
|
1714
|
+
if (!store || name === void 0 || !checks) return;
|
|
1715
|
+
const state = { boxId: box.id, checks };
|
|
1716
|
+
const serialized = JSON.stringify(state);
|
|
1717
|
+
if (savedShared.get(name) === serialized) return;
|
|
1718
|
+
try {
|
|
1719
|
+
await store.save(name, state);
|
|
1720
|
+
savedShared.set(name, serialized);
|
|
1721
|
+
} catch {
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
// src/sandbox/shell-path.ts
|
|
1726
|
+
function shellSingleQuote(value) {
|
|
1727
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
1728
|
+
}
|
|
1729
|
+
function shellPath(path) {
|
|
1730
|
+
if (path === "~") return '"$HOME"';
|
|
1731
|
+
if (path.startsWith("~/")) {
|
|
1732
|
+
const rest = path.slice(2);
|
|
1733
|
+
return rest ? `"$HOME"/${shellSingleQuote(rest)}` : '"$HOME"';
|
|
1734
|
+
}
|
|
1735
|
+
return shellSingleQuote(path);
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
// src/sandbox/outcome.ts
|
|
1739
|
+
var ok = (value) => ({ succeeded: true, value });
|
|
1740
|
+
var fail = (error) => ({
|
|
1741
|
+
succeeded: false,
|
|
1742
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
1743
|
+
});
|
|
1744
|
+
|
|
1745
|
+
// src/sandbox/app-tools.ts
|
|
1669
1746
|
function buildAppToolMcpServers(options) {
|
|
1670
1747
|
const entries = {};
|
|
1671
1748
|
for (const { tool, key, description } of options.tools) {
|
|
@@ -1680,16 +1757,6 @@ function buildAppToolMcpServers(options) {
|
|
|
1680
1757
|
}
|
|
1681
1758
|
return entries;
|
|
1682
1759
|
}
|
|
1683
|
-
function emitSandboxActivity(spend, box) {
|
|
1684
|
-
if (!spend?.onActivity) return;
|
|
1685
|
-
try {
|
|
1686
|
-
spend.onActivity({ sandboxId: box.id, at: Date.now() });
|
|
1687
|
-
} catch {
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
function shellSingleQuote(value) {
|
|
1691
|
-
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
1692
|
-
}
|
|
1693
1760
|
var DEFAULT_SANDBOX_TOOL_BASE_DIR = "/home/agent/tools";
|
|
1694
1761
|
var SAFE_TOOL_SEGMENT = /^[A-Za-z0-9._-]+$/;
|
|
1695
1762
|
function normalizeSandboxToolSegment(value, label) {
|
|
@@ -1775,71 +1842,17 @@ async function ensureSandboxToolBinDir(box, options) {
|
|
|
1775
1842
|
async function runSandboxToolPathSetup(box, options) {
|
|
1776
1843
|
return ensureSandboxToolBinDir(box, options);
|
|
1777
1844
|
}
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
return shellSingleQuote(path);
|
|
1785
|
-
}
|
|
1786
|
-
function splitDeferredProfileFiles(profile) {
|
|
1787
|
-
const files = profile.resources?.files ?? [];
|
|
1788
|
-
const deferredFiles = [];
|
|
1789
|
-
const keptFiles = [];
|
|
1790
|
-
for (const mount of files) {
|
|
1791
|
-
if (mount.resource.kind === "inline") deferredFiles.push(mount);
|
|
1792
|
-
else keptFiles.push(mount);
|
|
1793
|
-
}
|
|
1794
|
-
if (deferredFiles.length === 0) return { leanProfile: profile, deferredFiles };
|
|
1795
|
-
const leanProfile = {
|
|
1796
|
-
...profile,
|
|
1797
|
-
resources: { ...profile.resources ?? {}, files: keptFiles }
|
|
1798
|
-
};
|
|
1799
|
-
return { leanProfile, deferredFiles };
|
|
1800
|
-
}
|
|
1801
|
-
var PROFILE_WRITE_B64_CHUNK_CHARS = 3e3;
|
|
1802
|
-
var PROFILE_WRITE_MAX_RETRIES = 4;
|
|
1803
|
-
var PROFILE_WRITE_RETRY_BASE_MS = 250;
|
|
1804
|
-
var PROFILE_WRITE_RETRY_MAX_MS = 2e3;
|
|
1805
|
-
var PROFILE_WRITE_EXEC_TIMEOUT_MS = 3e4;
|
|
1806
|
-
var PROFILE_WRITE_PACE_MS = 150;
|
|
1807
|
-
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1808
|
-
var PROFILE_BIN_DIR_RE = /(^|\/)(s?bin)\//;
|
|
1809
|
-
var ProfileWriteExecTimeoutError = class extends Error {
|
|
1810
|
-
constructor(timeoutMs) {
|
|
1811
|
-
super(`exec exceeded ${timeoutMs}ms (proxy hang/wedge)`);
|
|
1812
|
-
this.name = "ProfileWriteExecTimeoutError";
|
|
1845
|
+
|
|
1846
|
+
// src/sandbox/exec-failure.ts
|
|
1847
|
+
var ProfileWriteExecTimeoutError = class extends Error {
|
|
1848
|
+
constructor(timeoutMs) {
|
|
1849
|
+
super(`exec exceeded ${timeoutMs}ms (proxy hang/wedge)`);
|
|
1850
|
+
this.name = "ProfileWriteExecTimeoutError";
|
|
1813
1851
|
}
|
|
1814
1852
|
};
|
|
1815
|
-
function execWithTimeout(box, cmd, timeoutMs) {
|
|
1816
|
-
return new Promise((resolve, reject) => {
|
|
1817
|
-
let settled = false;
|
|
1818
|
-
const timer = setTimeout(() => {
|
|
1819
|
-
if (settled) return;
|
|
1820
|
-
settled = true;
|
|
1821
|
-
reject(new ProfileWriteExecTimeoutError(timeoutMs));
|
|
1822
|
-
}, timeoutMs);
|
|
1823
|
-
box.exec(cmd, { timeoutMs }).then(
|
|
1824
|
-
(res) => {
|
|
1825
|
-
if (settled) return;
|
|
1826
|
-
settled = true;
|
|
1827
|
-
clearTimeout(timer);
|
|
1828
|
-
resolve(res);
|
|
1829
|
-
},
|
|
1830
|
-
(err) => {
|
|
1831
|
-
if (settled) return;
|
|
1832
|
-
settled = true;
|
|
1833
|
-
clearTimeout(timer);
|
|
1834
|
-
reject(err);
|
|
1835
|
-
}
|
|
1836
|
-
);
|
|
1837
|
-
});
|
|
1838
|
-
}
|
|
1839
1853
|
var TRANSIENT_EXEC_STATUS_CODES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504]);
|
|
1840
1854
|
var TRANSIENT_EXEC_CODE_RE = /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ECONNABORTED)$/i;
|
|
1841
1855
|
var 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;
|
|
1842
|
-
var RUNTIME_AUTH_REFRESH_SKEW_MS = 6e4;
|
|
1843
1856
|
function errorStatus(err) {
|
|
1844
1857
|
const rawStatus = err.status ?? err.statusCode ?? (err.response && typeof err.response === "object" ? err.response.status : void 0);
|
|
1845
1858
|
if (typeof rawStatus === "number") return rawStatus;
|
|
@@ -1891,62 +1904,56 @@ function transientExecError(err) {
|
|
|
1891
1904
|
if (isTransientExecError(err)) return { retryable: true, retryAfterMs: retryAfterMs(err) };
|
|
1892
1905
|
return { retryable: false };
|
|
1893
1906
|
}
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
}
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
super(
|
|
1905
|
-
`egress policy mismatch on ${stage} box ${boxName}: current ${currentPolicy.mode} policy from ${currentSource} does not explicitly match desired ${desiredPolicy.mode} policy; the existing box was preserved and egress was not updated.`
|
|
1906
|
-
);
|
|
1907
|
-
this.name = "SandboxEgressPolicyMismatchError";
|
|
1908
|
-
this.stage = stage;
|
|
1909
|
-
this.boxName = boxName;
|
|
1910
|
-
this.currentPolicy = currentPolicy;
|
|
1911
|
-
this.currentSource = currentSource;
|
|
1912
|
-
this.desiredPolicy = desiredPolicy;
|
|
1913
|
-
}
|
|
1914
|
-
};
|
|
1915
|
-
var SandboxRuntimeAuthRefreshError = class extends Error {
|
|
1916
|
-
constructor(stage, name, detail, cause) {
|
|
1917
|
-
super(`${stage} sandbox auth refresh failed for ${name}: ${detail}`, { cause });
|
|
1918
|
-
this.name = "SandboxRuntimeAuthRefreshError";
|
|
1919
|
-
}
|
|
1920
|
-
};
|
|
1921
|
-
var SandboxRecoveryFailedError = class extends Error {
|
|
1922
|
-
boxKey;
|
|
1923
|
-
stage;
|
|
1924
|
-
phase;
|
|
1925
|
-
constructor(stage, boxKey, phase, detail, cause) {
|
|
1926
|
-
super(
|
|
1927
|
-
`${stage} sandbox ${boxKey} failed liveness recovery at ${phase}: ${detail}. The workspace is preserved; pass forceNew to replace the box.`,
|
|
1928
|
-
{ cause }
|
|
1929
|
-
);
|
|
1930
|
-
this.name = "SandboxRecoveryFailedError";
|
|
1931
|
-
this.boxKey = boxKey;
|
|
1932
|
-
this.stage = stage;
|
|
1933
|
-
this.phase = phase;
|
|
1907
|
+
|
|
1908
|
+
// src/sandbox/profile-files.ts
|
|
1909
|
+
import { createHash } from "crypto";
|
|
1910
|
+
function splitDeferredProfileFiles(profile) {
|
|
1911
|
+
const files = profile.resources?.files ?? [];
|
|
1912
|
+
const deferredFiles = [];
|
|
1913
|
+
const keptFiles = [];
|
|
1914
|
+
for (const mount of files) {
|
|
1915
|
+
if (mount.resource.kind === "inline") deferredFiles.push(mount);
|
|
1916
|
+
else keptFiles.push(mount);
|
|
1934
1917
|
}
|
|
1935
|
-
};
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1918
|
+
if (deferredFiles.length === 0) return { leanProfile: profile, deferredFiles };
|
|
1919
|
+
const leanProfile = {
|
|
1920
|
+
...profile,
|
|
1921
|
+
resources: { ...profile.resources ?? {}, files: keptFiles }
|
|
1922
|
+
};
|
|
1923
|
+
return { leanProfile, deferredFiles };
|
|
1924
|
+
}
|
|
1925
|
+
var PROFILE_WRITE_B64_CHUNK_CHARS = 3e3;
|
|
1926
|
+
var PROFILE_WRITE_MAX_RETRIES = 4;
|
|
1927
|
+
var PROFILE_WRITE_RETRY_BASE_MS = 250;
|
|
1928
|
+
var PROFILE_WRITE_RETRY_MAX_MS = 2e3;
|
|
1929
|
+
var PROFILE_WRITE_EXEC_TIMEOUT_MS = 3e4;
|
|
1930
|
+
var PROFILE_WRITE_PACE_MS = 150;
|
|
1931
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1932
|
+
var PROFILE_BIN_DIR_RE = /(^|\/)(s?bin)\//;
|
|
1933
|
+
function execWithTimeout(box, cmd, timeoutMs) {
|
|
1934
|
+
return new Promise((resolve, reject) => {
|
|
1935
|
+
let settled = false;
|
|
1936
|
+
const timer = setTimeout(() => {
|
|
1937
|
+
if (settled) return;
|
|
1938
|
+
settled = true;
|
|
1939
|
+
reject(new ProfileWriteExecTimeoutError(timeoutMs));
|
|
1940
|
+
}, timeoutMs);
|
|
1941
|
+
box.exec(cmd, { timeoutMs }).then(
|
|
1942
|
+
(res) => {
|
|
1943
|
+
if (settled) return;
|
|
1944
|
+
settled = true;
|
|
1945
|
+
clearTimeout(timer);
|
|
1946
|
+
resolve(res);
|
|
1947
|
+
},
|
|
1948
|
+
(err) => {
|
|
1949
|
+
if (settled) return;
|
|
1950
|
+
settled = true;
|
|
1951
|
+
clearTimeout(timer);
|
|
1952
|
+
reject(err);
|
|
1953
|
+
}
|
|
1943
1954
|
);
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
this.stage = stage;
|
|
1947
|
-
this.runningSessions = runningSessions;
|
|
1948
|
-
}
|
|
1949
|
-
};
|
|
1955
|
+
});
|
|
1956
|
+
}
|
|
1950
1957
|
function fileApiTarget(mount) {
|
|
1951
1958
|
if (mount.resource.kind !== "inline") return null;
|
|
1952
1959
|
let rel;
|
|
@@ -2075,167 +2082,67 @@ async function writeProfileFilesToBox(box, files, options = {}) {
|
|
|
2075
2082
|
}
|
|
2076
2083
|
return ok(void 0);
|
|
2077
2084
|
}
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
const { deferredFiles } = splitDeferredProfileFiles(fullProfile);
|
|
2097
|
-
if (deferredFiles.length === 0) return ok(box);
|
|
2098
|
-
const corpusHash = deferredCorpusHash(deferredFiles);
|
|
2099
|
-
const stampedHash = box.metadata?.[DEFERRED_CORPUS_HASH_KEY];
|
|
2100
|
-
if (typeof stampedHash === "string" && stampedHash === corpusHash) return ok(box);
|
|
2101
|
-
const found = checksFor(box)?.corpus;
|
|
2102
|
-
if (isRecent(found?.at, TRUSTED_REUSE_TTL_MS) && found?.hash === corpusHash) return ok(box);
|
|
2103
|
-
if (await (corpusMarker ?? readDeferredCorpusMarker(box)) === corpusHash) {
|
|
2104
|
-
recordCheck(box, { corpus: { hash: corpusHash, at: Date.now() } });
|
|
2105
|
-
return ok(box);
|
|
2106
|
-
}
|
|
2107
|
-
const written = await writeDeferredFilesWithRuntimeAuthRefresh(client, box, deferredFiles, stage, name);
|
|
2108
|
-
if (written.succeeded) {
|
|
2109
|
-
await writeDeferredCorpusMarker(written.value, corpusHash);
|
|
2110
|
-
recordCheck(written.value, { corpus: { hash: corpusHash, at: Date.now() } });
|
|
2111
|
-
}
|
|
2112
|
-
return written;
|
|
2113
|
-
}
|
|
2114
|
-
var DEFERRED_CORPUS_MARKER_PATH = ".agent-app/deferred-corpus-hash";
|
|
2115
|
-
var DEFERRED_CORPUS_HASH_RE = /^[0-9a-f]{64}$/;
|
|
2116
|
-
async function readDeferredCorpusMarker(box) {
|
|
2117
|
-
if (typeof box.read !== "function") return null;
|
|
2118
|
-
try {
|
|
2119
|
-
const value = (await box.read(`/home/agent/${DEFERRED_CORPUS_MARKER_PATH}`)).trim();
|
|
2120
|
-
return DEFERRED_CORPUS_HASH_RE.test(value) ? value : null;
|
|
2121
|
-
} catch {
|
|
2122
|
-
return null;
|
|
2123
|
-
}
|
|
2124
|
-
}
|
|
2125
|
-
async function writeDeferredCorpusMarker(box, corpusHash) {
|
|
2126
|
-
if (typeof box.fs?.writeMany !== "function") return;
|
|
2127
|
-
try {
|
|
2128
|
-
await box.fs.writeMany([{ path: DEFERRED_CORPUS_MARKER_PATH, content: corpusHash }]);
|
|
2129
|
-
} catch {
|
|
2130
|
-
}
|
|
2131
|
-
}
|
|
2132
|
-
async function listRunning(client, name) {
|
|
2133
|
-
try {
|
|
2134
|
-
const running = await client.list({ status: "running" });
|
|
2135
|
-
return ok(running.find((s) => s.name === name) ?? null);
|
|
2136
|
-
} catch (err) {
|
|
2137
|
-
return fail(err);
|
|
2138
|
-
}
|
|
2139
|
-
}
|
|
2140
|
-
function rememberRunningBox(name, box) {
|
|
2141
|
-
runningBoxIds.delete(name);
|
|
2142
|
-
runningBoxIds.set(name, box.id);
|
|
2143
|
-
reuseNames.set(box.id, name);
|
|
2144
|
-
while (runningBoxIds.size > REUSE_CHECKS_MAX) {
|
|
2145
|
-
const oldest = runningBoxIds.keys().next().value;
|
|
2146
|
-
if (oldest === void 0) break;
|
|
2147
|
-
runningBoxIds.delete(oldest);
|
|
2148
|
-
}
|
|
2149
|
-
while (reuseNames.size > REUSE_CHECKS_MAX) {
|
|
2150
|
-
const oldest = reuseNames.keys().next().value;
|
|
2151
|
-
if (oldest === void 0) break;
|
|
2152
|
-
reuseNames.delete(oldest);
|
|
2153
|
-
}
|
|
2154
|
-
return box;
|
|
2155
|
-
}
|
|
2156
|
-
async function getRunningBox(client, id, name) {
|
|
2157
|
-
try {
|
|
2158
|
-
const box = await client.get(id);
|
|
2159
|
-
if (!box || box.name !== name || box.status !== "running") return null;
|
|
2160
|
-
if (typeof box.metadata?.harness !== "string") return null;
|
|
2161
|
-
return box;
|
|
2162
|
-
} catch {
|
|
2163
|
-
return null;
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2166
|
-
async function listStopped(client, name) {
|
|
2167
|
-
try {
|
|
2168
|
-
const stopped = await client.list({ status: "stopped" });
|
|
2169
|
-
return ok(stopped.find((s) => s.name === name) ?? null);
|
|
2170
|
-
} catch (err) {
|
|
2171
|
-
return fail(err);
|
|
2172
|
-
}
|
|
2173
|
-
}
|
|
2174
|
-
async function deleteBox(box) {
|
|
2175
|
-
try {
|
|
2176
|
-
const acknowledgement = await box.delete({ until: "removed" });
|
|
2177
|
-
forgetBox(box.id);
|
|
2178
|
-
if (acknowledgement.removal === "pending") {
|
|
2179
|
-
return fail(new Error(`sandbox ${box.id} removal is still pending; retry replacement after removal completes`));
|
|
2180
|
-
}
|
|
2181
|
-
return ok(void 0);
|
|
2182
|
-
} catch (err) {
|
|
2183
|
-
return fail(err);
|
|
2085
|
+
|
|
2086
|
+
// src/sandbox/lifecycle-errors.ts
|
|
2087
|
+
var SandboxEgressPolicyMismatchError = class extends Error {
|
|
2088
|
+
stage;
|
|
2089
|
+
boxName;
|
|
2090
|
+
currentPolicy;
|
|
2091
|
+
currentSource;
|
|
2092
|
+
desiredPolicy;
|
|
2093
|
+
constructor(stage, boxName, currentPolicy, currentSource, desiredPolicy) {
|
|
2094
|
+
super(
|
|
2095
|
+
`egress policy mismatch on ${stage} box ${boxName}: current ${currentPolicy.mode} policy from ${currentSource} does not explicitly match desired ${desiredPolicy.mode} policy; the existing box was preserved and egress was not updated.`
|
|
2096
|
+
);
|
|
2097
|
+
this.name = "SandboxEgressPolicyMismatchError";
|
|
2098
|
+
this.stage = stage;
|
|
2099
|
+
this.boxName = boxName;
|
|
2100
|
+
this.currentPolicy = currentPolicy;
|
|
2101
|
+
this.currentSource = currentSource;
|
|
2102
|
+
this.desiredPolicy = desiredPolicy;
|
|
2184
2103
|
}
|
|
2185
|
-
}
|
|
2186
|
-
var
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
var ENV_TOTAL_MAX_BYTES = 2e5;
|
|
2191
|
-
function utf8ByteLength(value) {
|
|
2192
|
-
return new TextEncoder().encode(typeof value === "string" ? value : JSON.stringify(value ?? null)).byteLength;
|
|
2193
|
-
}
|
|
2194
|
-
function assertProvisionPayloadWithinCap(payload) {
|
|
2195
|
-
const total = utf8ByteLength(payload);
|
|
2196
|
-
if (total <= PROVISION_PAYLOAD_MAX_BYTES) return;
|
|
2197
|
-
const profile = payload.backend?.profile;
|
|
2198
|
-
const files = (typeof profile === "string" ? void 0 : profile?.resources?.files) ?? [];
|
|
2199
|
-
const breakdown = `profile=${utf8ByteLength(profile ?? null)}B (files=${utf8ByteLength(files)}B), env=${utf8ByteLength(payload.env ?? {})}B, secrets=${utf8ByteLength(payload.secrets ?? [])}B`;
|
|
2200
|
-
throw new Error(
|
|
2201
|
-
`sandbox provision payload is ${total} bytes \u2014 over the ${PROVISION_PAYLOAD_MAX_BYTES}-byte gate (the platform caps the create body at 256 KiB; an over-cap payload can never create a sandbox). Breakdown: ${breakdown}. Hint: set deferProfileFiles: true or move content to resources.`
|
|
2202
|
-
);
|
|
2203
|
-
}
|
|
2204
|
-
function assertEnvWithinLimits(env) {
|
|
2205
|
-
let total = 0;
|
|
2206
|
-
let largest = null;
|
|
2207
|
-
for (const [name, value] of Object.entries(env)) {
|
|
2208
|
-
const bytes = utf8ByteLength(`${name}=${value}`);
|
|
2209
|
-
total += bytes;
|
|
2210
|
-
if (!largest || bytes > largest.bytes) largest = { name, bytes };
|
|
2211
|
-
if (bytes > ENV_VALUE_MAX_BYTES) {
|
|
2212
|
-
throw new Error(
|
|
2213
|
-
`sandbox env var ${name} is ${bytes} bytes \u2014 over the ${ENV_VALUE_MAX_BYTES}-byte gate (kernel MAX_ARG_STRLEN is 131072 bytes per env entry; anything larger E2BIGs every exec). Write large content to a file mount or resource instead of an env var.`
|
|
2214
|
-
);
|
|
2215
|
-
}
|
|
2104
|
+
};
|
|
2105
|
+
var SandboxRuntimeAuthRefreshError = class extends Error {
|
|
2106
|
+
constructor(stage, name, detail, cause) {
|
|
2107
|
+
super(`${stage} sandbox auth refresh failed for ${name}: ${detail}`, { cause });
|
|
2108
|
+
this.name = "SandboxRuntimeAuthRefreshError";
|
|
2216
2109
|
}
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2110
|
+
};
|
|
2111
|
+
var SandboxRecoveryFailedError = class extends Error {
|
|
2112
|
+
boxKey;
|
|
2113
|
+
stage;
|
|
2114
|
+
phase;
|
|
2115
|
+
constructor(stage, boxKey, phase, detail, cause) {
|
|
2116
|
+
super(
|
|
2117
|
+
`${stage} sandbox ${boxKey} failed liveness recovery at ${phase}: ${detail}. The workspace is preserved; pass forceNew to replace the box.`,
|
|
2118
|
+
{ cause }
|
|
2221
2119
|
);
|
|
2120
|
+
this.name = "SandboxRecoveryFailedError";
|
|
2121
|
+
this.boxKey = boxKey;
|
|
2122
|
+
this.stage = stage;
|
|
2123
|
+
this.phase = phase;
|
|
2222
2124
|
}
|
|
2223
|
-
}
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2125
|
+
};
|
|
2126
|
+
var SandboxBoxBusyError = class extends Error {
|
|
2127
|
+
boxKey;
|
|
2128
|
+
stage;
|
|
2129
|
+
runningSessions;
|
|
2130
|
+
constructor(stage, boxKey, runningSessions, detail) {
|
|
2131
|
+
super(
|
|
2132
|
+
`${stage} sandbox ${boxKey} is not connectable (${detail}) but is serving ${runningSessions} running session${runningSessions === 1 ? "" : "s"}, so it was not restarted. Retry when they finish.`
|
|
2133
|
+
);
|
|
2134
|
+
this.name = "SandboxBoxBusyError";
|
|
2135
|
+
this.boxKey = boxKey;
|
|
2136
|
+
this.stage = stage;
|
|
2137
|
+
this.runningSessions = runningSessions;
|
|
2234
2138
|
}
|
|
2235
|
-
}
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
}
|
|
2139
|
+
};
|
|
2140
|
+
|
|
2141
|
+
// src/sandbox/profile-corpus.ts
|
|
2142
|
+
import { createHash as createHash2 } from "crypto";
|
|
2143
|
+
|
|
2144
|
+
// src/sandbox/runtime-connection.ts
|
|
2145
|
+
var RUNTIME_AUTH_REFRESH_SKEW_MS = 6e4;
|
|
2239
2146
|
var RUNTIME_CONNECTION_WAIT_MS = 3e4;
|
|
2240
2147
|
var RUNTIME_CONNECTION_POLL_MS = 1e3;
|
|
2241
2148
|
function sandboxRuntimeUrl(box) {
|
|
@@ -2357,130 +2264,144 @@ async function writeDeferredFilesWithRuntimeAuthRefresh(client, box, files, stag
|
|
|
2357
2264
|
)
|
|
2358
2265
|
);
|
|
2359
2266
|
}
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2267
|
+
|
|
2268
|
+
// src/sandbox/profile-corpus.ts
|
|
2269
|
+
function deferredProfileWriteFailed(stage, name, cause) {
|
|
2270
|
+
return new Error(`deferred file write failed on ${stage} box ${name}: ${cause.message}`, { cause });
|
|
2271
|
+
}
|
|
2272
|
+
var DEFERRED_CORPUS_HASH_KEY = "agentAppDeferredCorpusHash";
|
|
2273
|
+
function deferredCorpusHash(files) {
|
|
2274
|
+
const norm = files.map((f) => ({
|
|
2275
|
+
p: f.path,
|
|
2276
|
+
c: f.resource.kind === "inline" ? f.resource.content ?? "" : `ref:${f.resource.kind}`
|
|
2277
|
+
})).sort((a, b) => a.p < b.p ? -1 : a.p > b.p ? 1 : 0);
|
|
2278
|
+
return createHash2("sha256").update(JSON.stringify(norm), "utf8").digest("hex");
|
|
2279
|
+
}
|
|
2280
|
+
async function materializeDeferredFilesForExistingBox(shell, client, box, stage, name, workspaceId, userId, harness, corpusMarker) {
|
|
2281
|
+
if (!shell.deferProfileFiles) return ok(box);
|
|
2282
|
+
const connectedIntegrationIds = await shell.connectedIntegrationIds(workspaceId);
|
|
2283
|
+
const buildCtx = {
|
|
2284
|
+
workspaceId,
|
|
2285
|
+
connectedIntegrationIds,
|
|
2286
|
+
...userId ? { userId } : {}
|
|
2287
|
+
};
|
|
2288
|
+
const files = await shell.files(buildCtx);
|
|
2289
|
+
const fullProfile = shell.profile({ extraFiles: files, harness });
|
|
2290
|
+
const { deferredFiles } = splitDeferredProfileFiles(fullProfile);
|
|
2291
|
+
if (deferredFiles.length === 0) return ok(box);
|
|
2292
|
+
const corpusHash = deferredCorpusHash(deferredFiles);
|
|
2293
|
+
const stampedHash = box.metadata?.[DEFERRED_CORPUS_HASH_KEY];
|
|
2294
|
+
if (typeof stampedHash === "string" && stampedHash === corpusHash) return ok(box);
|
|
2295
|
+
const found = checksFor(box)?.corpus;
|
|
2296
|
+
if (isRecent(found?.at, TRUSTED_REUSE_TTL_MS) && found?.hash === corpusHash) return ok(box);
|
|
2297
|
+
if (await (corpusMarker ?? readDeferredCorpusMarker(box)) === corpusHash) {
|
|
2298
|
+
recordCheck(box, { corpus: { hash: corpusHash, at: Date.now() } });
|
|
2299
|
+
return ok(box);
|
|
2364
2300
|
}
|
|
2365
|
-
|
|
2366
|
-
if (
|
|
2367
|
-
|
|
2368
|
-
|
|
2301
|
+
const written = await writeDeferredFilesWithRuntimeAuthRefresh(client, box, deferredFiles, stage, name);
|
|
2302
|
+
if (written.succeeded) {
|
|
2303
|
+
await writeDeferredCorpusMarker(written.value, corpusHash);
|
|
2304
|
+
recordCheck(written.value, { corpus: { hash: corpusHash, at: Date.now() } });
|
|
2369
2305
|
}
|
|
2370
|
-
|
|
2371
|
-
if (alive.succeeded) recordCheck(box, { alive: Date.now() });
|
|
2372
|
-
else forgetBox(box.id);
|
|
2373
|
-
return alive;
|
|
2306
|
+
return written;
|
|
2374
2307
|
}
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
if (
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
return Object.assign(wrapped, {
|
|
2386
|
-
status,
|
|
2387
|
-
origin: "sandbox-api",
|
|
2388
|
-
endpoint: `/v1/sandboxes/${encodeURIComponent(box.id)}/resume`,
|
|
2389
|
-
...typeof code === "number" || typeof code === "string" ? { code } : {}
|
|
2390
|
-
});
|
|
2308
|
+
var DEFERRED_CORPUS_MARKER_PATH = ".agent-app/deferred-corpus-hash";
|
|
2309
|
+
var DEFERRED_CORPUS_HASH_RE = /^[0-9a-f]{64}$/;
|
|
2310
|
+
async function readDeferredCorpusMarker(box) {
|
|
2311
|
+
if (typeof box.read !== "function") return null;
|
|
2312
|
+
try {
|
|
2313
|
+
const value = (await box.read(`/home/agent/${DEFERRED_CORPUS_MARKER_PATH}`)).trim();
|
|
2314
|
+
return DEFERRED_CORPUS_HASH_RE.test(value) ? value : null;
|
|
2315
|
+
} catch {
|
|
2316
|
+
return null;
|
|
2317
|
+
}
|
|
2391
2318
|
}
|
|
2392
|
-
async function
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2319
|
+
async function writeDeferredCorpusMarker(box, corpusHash) {
|
|
2320
|
+
if (typeof box.fs?.writeMany !== "function") return;
|
|
2321
|
+
try {
|
|
2322
|
+
await box.fs.writeMany([{ path: DEFERRED_CORPUS_MARKER_PATH, content: corpusHash }]);
|
|
2323
|
+
} catch {
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
// src/sandbox/payload-limits.ts
|
|
2328
|
+
var SHELL_PROMPT_BUDGET_HINT = "If this prompt size is a decision you already made at compose time, mirror it on the shell as `promptBudget: { maxSystemPromptBytes, overBudgetReason }` \u2014 the shell gate is the one that sees the profile actually sent.";
|
|
2329
|
+
var PROVISION_PAYLOAD_MAX_BYTES = 24e4;
|
|
2330
|
+
var ENV_VALUE_MAX_BYTES = 12e4;
|
|
2331
|
+
var DEFAULT_PROVISION_TIMEOUT_MS = 12e4;
|
|
2332
|
+
var ENV_TOTAL_MAX_BYTES = 2e5;
|
|
2333
|
+
function utf8ByteLength(value) {
|
|
2334
|
+
return new TextEncoder().encode(typeof value === "string" ? value : JSON.stringify(value ?? null)).byteLength;
|
|
2335
|
+
}
|
|
2336
|
+
function assertProvisionPayloadWithinCap(payload) {
|
|
2337
|
+
const total = utf8ByteLength(payload);
|
|
2338
|
+
if (total <= PROVISION_PAYLOAD_MAX_BYTES) return;
|
|
2339
|
+
const profile = payload.backend?.profile;
|
|
2340
|
+
const files = (typeof profile === "string" ? void 0 : profile?.resources?.files) ?? [];
|
|
2341
|
+
const breakdown = `profile=${utf8ByteLength(profile ?? null)}B (files=${utf8ByteLength(files)}B), env=${utf8ByteLength(payload.env ?? {})}B, secrets=${utf8ByteLength(payload.secrets ?? [])}B`;
|
|
2342
|
+
throw new Error(
|
|
2343
|
+
`sandbox provision payload is ${total} bytes \u2014 over the ${PROVISION_PAYLOAD_MAX_BYTES}-byte gate (the platform caps the create body at 256 KiB; an over-cap payload can never create a sandbox). Breakdown: ${breakdown}. Hint: set deferProfileFiles: true or move content to resources.`
|
|
2344
|
+
);
|
|
2345
|
+
}
|
|
2346
|
+
function assertEnvWithinLimits(env) {
|
|
2347
|
+
let total = 0;
|
|
2348
|
+
let largest = null;
|
|
2349
|
+
for (const [name, value] of Object.entries(env)) {
|
|
2350
|
+
const bytes = utf8ByteLength(`${name}=${value}`);
|
|
2351
|
+
total += bytes;
|
|
2352
|
+
if (!largest || bytes > largest.bytes) largest = { name, bytes };
|
|
2353
|
+
if (bytes > ENV_VALUE_MAX_BYTES) {
|
|
2354
|
+
throw new Error(
|
|
2355
|
+
`sandbox env var ${name} is ${bytes} bytes \u2014 over the ${ENV_VALUE_MAX_BYTES}-byte gate (kernel MAX_ARG_STRLEN is 131072 bytes per env entry; anything larger E2BIGs every exec). Write large content to a file mount or resource instead of an env var.`
|
|
2356
|
+
);
|
|
2397
2357
|
}
|
|
2398
|
-
}
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
report("completed", "The stopped sandbox is running again");
|
|
2405
|
-
return ok(box);
|
|
2406
|
-
} catch (cause) {
|
|
2407
|
-
report("error", "The stopped sandbox could not be resumed");
|
|
2408
|
-
return fail(stoppedBoxResumeError(box, cause));
|
|
2358
|
+
}
|
|
2359
|
+
if (total > ENV_TOTAL_MAX_BYTES) {
|
|
2360
|
+
const worst = largest ? ` Largest: ${largest.name} (${largest.bytes}B).` : "";
|
|
2361
|
+
throw new Error(
|
|
2362
|
+
`sandbox env block is ${total} bytes total \u2014 over the ${ENV_TOTAL_MAX_BYTES}-byte gate.${worst} Write large content to a file mount or resource instead of env vars.`
|
|
2363
|
+
);
|
|
2409
2364
|
}
|
|
2410
2365
|
}
|
|
2411
|
-
|
|
2412
|
-
|
|
2366
|
+
|
|
2367
|
+
// src/sandbox/workspace-boxes.ts
|
|
2368
|
+
async function listRunning(client, name) {
|
|
2413
2369
|
try {
|
|
2414
|
-
await
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
await box.resume({
|
|
2419
|
-
timeoutMs: Math.max(1, deadline - Date.now()),
|
|
2420
|
-
env: Object.fromEntries(missingEnvKeys.map((key) => [key, runtimeEnv[key]]))
|
|
2421
|
-
});
|
|
2370
|
+
const running = await client.list({ status: "running" });
|
|
2371
|
+
return ok(running.find((s) => s.name === name) ?? null);
|
|
2372
|
+
} catch (err) {
|
|
2373
|
+
return fail(err);
|
|
2422
2374
|
}
|
|
2423
2375
|
}
|
|
2424
|
-
function
|
|
2425
|
-
if (typeof cause !== "object" || cause === null) return void 0;
|
|
2426
|
-
const { code, missingEnvKeys } = cause;
|
|
2427
|
-
if (code !== "RESUME_ENV_REQUIRED" || !Array.isArray(missingEnvKeys)) return void 0;
|
|
2428
|
-
return missingEnvKeys.filter((key) => typeof key === "string");
|
|
2429
|
-
}
|
|
2430
|
-
async function runningSessionCount(box) {
|
|
2376
|
+
async function getRunningBox(client, id, name) {
|
|
2431
2377
|
try {
|
|
2432
|
-
const
|
|
2433
|
-
return
|
|
2434
|
-
|
|
2435
|
-
|
|
2378
|
+
const box = await client.get(id);
|
|
2379
|
+
if (!box || box.name !== name || box.status !== "running") return null;
|
|
2380
|
+
if (typeof box.metadata?.harness !== "string") return null;
|
|
2381
|
+
return box;
|
|
2436
2382
|
} catch {
|
|
2437
|
-
return
|
|
2383
|
+
return null;
|
|
2438
2384
|
}
|
|
2439
2385
|
}
|
|
2440
|
-
async function
|
|
2441
|
-
const running = await runningSessionCount(box);
|
|
2442
|
-
if (running) {
|
|
2443
|
-
if (sandboxRuntimeUrl(box) && !sandboxEdgeFailed(box)) return box;
|
|
2444
|
-
throw new SandboxBoxBusyError(
|
|
2445
|
-
stage,
|
|
2446
|
-
name,
|
|
2447
|
-
running,
|
|
2448
|
-
sandboxEdgeFailed(box) ? "runtime edge readiness failed" : "runtime URL is missing"
|
|
2449
|
-
);
|
|
2450
|
-
}
|
|
2386
|
+
async function listStopped(client, name) {
|
|
2451
2387
|
try {
|
|
2452
|
-
await
|
|
2388
|
+
const stopped = await client.list({ status: "stopped" });
|
|
2389
|
+
return ok(stopped.find((s) => s.name === name) ?? null);
|
|
2453
2390
|
} catch (err) {
|
|
2454
|
-
|
|
2455
|
-
stage,
|
|
2456
|
-
name,
|
|
2457
|
-
"stop",
|
|
2458
|
-
"the platform could not stop the box for a state-preserving restart",
|
|
2459
|
-
err
|
|
2460
|
-
);
|
|
2461
|
-
}
|
|
2462
|
-
const resumed = await resumeStoppedBox(box, resumeTimeout, runtimeEnv, onProgress);
|
|
2463
|
-
if (!resumed.succeeded) {
|
|
2464
|
-
throw new SandboxRecoveryFailedError(
|
|
2465
|
-
stage,
|
|
2466
|
-
name,
|
|
2467
|
-
"resume",
|
|
2468
|
-
"the box did not reach running after a state-preserving restart",
|
|
2469
|
-
resumed.error
|
|
2470
|
-
);
|
|
2391
|
+
return fail(err);
|
|
2471
2392
|
}
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2393
|
+
}
|
|
2394
|
+
async function deleteBox(box) {
|
|
2395
|
+
try {
|
|
2396
|
+
const acknowledgement = await box.delete({ until: "removed" });
|
|
2397
|
+
forgetBox(box.id);
|
|
2398
|
+
if (acknowledgement.removal === "pending") {
|
|
2399
|
+
return fail(new Error(`sandbox ${box.id} removal is still pending; retry replacement after removal completes`));
|
|
2400
|
+
}
|
|
2401
|
+
return ok(void 0);
|
|
2402
|
+
} catch (err) {
|
|
2403
|
+
return fail(err);
|
|
2482
2404
|
}
|
|
2483
|
-
return recovered;
|
|
2484
2405
|
}
|
|
2485
2406
|
async function resolveWorkspaceSandboxClient(shell, workspaceId, userId) {
|
|
2486
2407
|
const scope = { workspaceId, ...userId ? { userId } : {} };
|
|
@@ -2507,13 +2428,16 @@ async function peekWorkspaceSandbox(shell, options) {
|
|
|
2507
2428
|
}
|
|
2508
2429
|
return { status: "running", box: match };
|
|
2509
2430
|
}
|
|
2431
|
+
|
|
2432
|
+
// src/sandbox/existing-box.ts
|
|
2433
|
+
import { createHash as createHash3 } from "crypto";
|
|
2510
2434
|
async function resolveWorkspaceRuntimeEnv(shell, scope) {
|
|
2511
2435
|
const env = await shell.runtimeEnv?.(scope) ?? {};
|
|
2512
2436
|
assertEnvWithinLimits(env);
|
|
2513
2437
|
return env;
|
|
2514
2438
|
}
|
|
2515
2439
|
function runtimeEnvDigest(env) {
|
|
2516
|
-
return
|
|
2440
|
+
return createHash3("sha256").update(JSON.stringify(canonicalizeJson(env)), "utf8").digest("hex");
|
|
2517
2441
|
}
|
|
2518
2442
|
function hasDeliveredEnv(box, env) {
|
|
2519
2443
|
const delivered = checksFor(box)?.env;
|
|
@@ -2677,138 +2601,150 @@ async function assertExistingBoxEgress(box, desired, migrate, stage, name, prefe
|
|
|
2677
2601
|
desired
|
|
2678
2602
|
);
|
|
2679
2603
|
}
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
return
|
|
2684
|
-
}
|
|
2685
|
-
async function reuseWorkspaceSandbox(shell, options) {
|
|
2686
|
-
if (options.forceNew) return void 0;
|
|
2687
|
-
await hydrateReuseState(shell, options);
|
|
2688
|
-
if (!hasRecentProbe(shell, options)) return void 0;
|
|
2689
|
-
return claimWorkspaceSandbox(shell, options, true);
|
|
2690
|
-
}
|
|
2691
|
-
function boxNameFor(shell, options) {
|
|
2692
|
-
const scope = { workspaceId: options.workspaceId, ...options.userId ? { userId: options.userId } : {} };
|
|
2693
|
-
return shell.boxKey ? shell.boxKey(scope) : shell.name(options.workspaceId);
|
|
2694
|
-
}
|
|
2695
|
-
function hasRecentProbe(shell, options) {
|
|
2696
|
-
const probe = shell.livenessProbe;
|
|
2697
|
-
if (!probe || options.forceNew) return false;
|
|
2698
|
-
const id = runningBoxIds.get(boxNameFor(shell, options));
|
|
2699
|
-
return isRecent(id === void 0 ? void 0 : reuseChecks.get(id)?.alive, probe.cacheTtlMs ?? TRUSTED_REUSE_TTL_MS);
|
|
2700
|
-
}
|
|
2701
|
-
function reuseStoreOf(shell) {
|
|
2702
|
-
if (shell.reuseState !== void 0) return shell.reuseState;
|
|
2703
|
-
if (defaultReuseStore === void 0) defaultReuseStore = workersReuseStore();
|
|
2704
|
-
return defaultReuseStore;
|
|
2705
|
-
}
|
|
2706
|
-
async function hydrateReuseState(shell, options) {
|
|
2707
|
-
if (options.forceNew) return;
|
|
2708
|
-
const store = reuseStoreOf(shell);
|
|
2709
|
-
activeReuseStore = store;
|
|
2710
|
-
if (!store) return;
|
|
2711
|
-
const name = boxNameFor(shell, options);
|
|
2712
|
-
if (runningBoxIds.has(name)) return;
|
|
2604
|
+
|
|
2605
|
+
// src/sandbox/box-health.ts
|
|
2606
|
+
async function isBoxAlive(box, probe) {
|
|
2607
|
+
if (!probe) return ok(void 0);
|
|
2713
2608
|
try {
|
|
2714
|
-
const
|
|
2715
|
-
if (
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2609
|
+
const alive = await box.exec("echo alive", { timeoutMs: probe.execTimeoutMs ?? 5e3 });
|
|
2610
|
+
if (alive.exitCode !== 0 || alive.stdout.trim() !== "alive") {
|
|
2611
|
+
return fail(new Error("alive check did not return a successful alive marker"));
|
|
2612
|
+
}
|
|
2613
|
+
return ok(void 0);
|
|
2614
|
+
} catch (cause) {
|
|
2615
|
+
return fail(new Error("alive check failed", { cause }));
|
|
2721
2616
|
}
|
|
2722
2617
|
}
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
if (
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2618
|
+
function hasRecentLivenessVerification(box, probe, now = Date.now()) {
|
|
2619
|
+
return isRecent(checksFor(box)?.alive, probe.cacheTtlMs ?? TRUSTED_REUSE_TTL_MS, now);
|
|
2620
|
+
}
|
|
2621
|
+
async function isReusableBox(box, probe) {
|
|
2622
|
+
if (sandboxEdgeFailed(box) || !sandboxRuntimeUrl(box)) {
|
|
2623
|
+
forgetBox(box.id);
|
|
2624
|
+
return fail(new Error(sandboxEdgeFailed(box) ? "runtime edge readiness failed" : "runtime URL is missing"));
|
|
2625
|
+
}
|
|
2626
|
+
if (!probe) return ok(void 0);
|
|
2627
|
+
if (hasRecentLivenessVerification(box, probe)) {
|
|
2628
|
+
trustedBoxes.add(box);
|
|
2629
|
+
return ok(void 0);
|
|
2735
2630
|
}
|
|
2631
|
+
const alive = await isBoxAlive(box, probe);
|
|
2632
|
+
if (alive.succeeded) recordCheck(box, { alive: Date.now() });
|
|
2633
|
+
else forgetBox(box.id);
|
|
2634
|
+
return alive;
|
|
2736
2635
|
}
|
|
2737
|
-
function
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2636
|
+
function stoppedBoxResumeError(box, cause) {
|
|
2637
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
2638
|
+
const code = error.code;
|
|
2639
|
+
if (code === SANDBOX_BACKING_CONTAINER_MISSING_CODE) return cause;
|
|
2640
|
+
if (code !== void 0 && code !== "SERVER_ERROR") return cause;
|
|
2641
|
+
if (!isLegacySandboxBackingContainerMissingMessage(error.message)) return cause;
|
|
2642
|
+
const status = typeof cause === "object" && cause !== null ? cause.status : void 0;
|
|
2643
|
+
if (typeof status !== "number" && typeof status !== "string") return cause;
|
|
2644
|
+
const wrapped = new Error(error.message, { cause: error });
|
|
2645
|
+
wrapped.name = error.name;
|
|
2646
|
+
return Object.assign(wrapped, {
|
|
2647
|
+
status,
|
|
2648
|
+
origin: "sandbox-api",
|
|
2649
|
+
endpoint: `/v1/sandboxes/${encodeURIComponent(box.id)}/resume`,
|
|
2650
|
+
...typeof code === "number" || typeof code === "string" ? { code } : {}
|
|
2651
|
+
});
|
|
2748
2652
|
}
|
|
2749
|
-
async function
|
|
2750
|
-
const
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
const claim = trace?.start("sandbox.claim", "sandbox", { "workspace.harness": options.harness }, options.traceParent);
|
|
2755
|
-
const traced = trace && claim ? {
|
|
2756
|
-
...options,
|
|
2757
|
-
measure: (stage, operation) => {
|
|
2758
|
-
const run = () => trace.measure(stage, "sandbox", () => operation(), void 0, claim);
|
|
2759
|
-
return options.measure ? options.measure(stage, run) : run();
|
|
2653
|
+
async function resumeStoppedBox(box, timeoutMs, runtimeEnv, onProgress) {
|
|
2654
|
+
const report = (status, message) => {
|
|
2655
|
+
try {
|
|
2656
|
+
onProgress?.({ step: "container-start", status, message, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
2657
|
+
} catch {
|
|
2760
2658
|
}
|
|
2761
|
-
}
|
|
2659
|
+
};
|
|
2762
2660
|
try {
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
return box;
|
|
2772
|
-
} catch (error) {
|
|
2773
|
-
claim?.end(void 0, error);
|
|
2774
|
-
throw error;
|
|
2661
|
+
forgetBox(box.id);
|
|
2662
|
+
report("started", "Resuming the stopped sandbox");
|
|
2663
|
+
await resumeWithRequiredRuntimeEnv(box, timeoutMs, runtimeEnv);
|
|
2664
|
+
await box.waitFor("running", { timeoutMs, ...onProgress ? { onProgress } : {} });
|
|
2665
|
+
report("completed", "The stopped sandbox is running again");
|
|
2666
|
+
return ok(box);
|
|
2667
|
+
} catch (cause) {
|
|
2668
|
+
report("error", "The stopped sandbox could not be resumed");
|
|
2669
|
+
return fail(stoppedBoxResumeError(box, cause));
|
|
2775
2670
|
}
|
|
2776
2671
|
}
|
|
2777
|
-
async function
|
|
2778
|
-
const
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
idleTimeoutSeconds: resources.idleTimeoutSeconds,
|
|
2788
|
-
maxLifetimeSeconds: resources.maxLifetimeSeconds,
|
|
2789
|
-
at: Date.now()
|
|
2672
|
+
async function resumeWithRequiredRuntimeEnv(box, timeoutMs, runtimeEnv) {
|
|
2673
|
+
const deadline = Date.now() + timeoutMs;
|
|
2674
|
+
try {
|
|
2675
|
+
await box.resume({ timeoutMs });
|
|
2676
|
+
} catch (cause) {
|
|
2677
|
+
const missingEnvKeys = resumeEnvRequiredKeys(cause);
|
|
2678
|
+
if (!missingEnvKeys?.length || missingEnvKeys.some((key) => runtimeEnv[key] === void 0)) throw cause;
|
|
2679
|
+
await box.resume({
|
|
2680
|
+
timeoutMs: Math.max(1, deadline - Date.now()),
|
|
2681
|
+
env: Object.fromEntries(missingEnvKeys.map((key) => [key, runtimeEnv[key]]))
|
|
2790
2682
|
});
|
|
2791
|
-
}
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
function resumeEnvRequiredKeys(cause) {
|
|
2686
|
+
if (typeof cause !== "object" || cause === null) return void 0;
|
|
2687
|
+
const { code, missingEnvKeys } = cause;
|
|
2688
|
+
if (code !== "RESUME_ENV_REQUIRED" || !Array.isArray(missingEnvKeys)) return void 0;
|
|
2689
|
+
return missingEnvKeys.filter((key) => typeof key === "string");
|
|
2690
|
+
}
|
|
2691
|
+
async function runningSessionCount(box) {
|
|
2792
2692
|
try {
|
|
2793
|
-
|
|
2693
|
+
const sessions = await box.sessions();
|
|
2694
|
+
return sessions.filter(
|
|
2695
|
+
({ info }) => info.status === "running" || Boolean(info.activeExecutionId) || info.status === "queued" && Boolean(info.latestExecutionId)
|
|
2696
|
+
).length;
|
|
2794
2697
|
} catch {
|
|
2698
|
+
return void 0;
|
|
2795
2699
|
}
|
|
2796
2700
|
}
|
|
2797
|
-
async function
|
|
2701
|
+
async function recoverUnresponsiveBox(client, box, probe, stage, name, resumeTimeout, runtimeEnv, onProgress) {
|
|
2702
|
+
const running = await runningSessionCount(box);
|
|
2703
|
+
if (running) {
|
|
2704
|
+
if (sandboxRuntimeUrl(box) && !sandboxEdgeFailed(box)) return box;
|
|
2705
|
+
throw new SandboxBoxBusyError(
|
|
2706
|
+
stage,
|
|
2707
|
+
name,
|
|
2708
|
+
running,
|
|
2709
|
+
sandboxEdgeFailed(box) ? "runtime edge readiness failed" : "runtime URL is missing"
|
|
2710
|
+
);
|
|
2711
|
+
}
|
|
2798
2712
|
try {
|
|
2799
|
-
|
|
2713
|
+
await box.stop();
|
|
2800
2714
|
} catch (err) {
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2715
|
+
throw new SandboxRecoveryFailedError(
|
|
2716
|
+
stage,
|
|
2717
|
+
name,
|
|
2718
|
+
"stop",
|
|
2719
|
+
"the platform could not stop the box for a state-preserving restart",
|
|
2720
|
+
err
|
|
2721
|
+
);
|
|
2805
2722
|
}
|
|
2723
|
+
const resumed = await resumeStoppedBox(box, resumeTimeout, runtimeEnv, onProgress);
|
|
2724
|
+
if (!resumed.succeeded) {
|
|
2725
|
+
throw new SandboxRecoveryFailedError(
|
|
2726
|
+
stage,
|
|
2727
|
+
name,
|
|
2728
|
+
"resume",
|
|
2729
|
+
"the box did not reach running after a state-preserving restart",
|
|
2730
|
+
resumed.error
|
|
2731
|
+
);
|
|
2732
|
+
}
|
|
2733
|
+
const recovered = await refreshRuntimeConnection(client, resumed.value);
|
|
2734
|
+
const reusable = await isReusableBox(recovered, probe);
|
|
2735
|
+
if (!reusable.succeeded) {
|
|
2736
|
+
throw new SandboxRecoveryFailedError(
|
|
2737
|
+
stage,
|
|
2738
|
+
name,
|
|
2739
|
+
"probe",
|
|
2740
|
+
`the box is still unresponsive after a state-preserving restart: ${reusable.error.message}`,
|
|
2741
|
+
reusable.error
|
|
2742
|
+
);
|
|
2743
|
+
}
|
|
2744
|
+
return recovered;
|
|
2806
2745
|
}
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
const diagnostics = serializeSandboxProvisioningError(error);
|
|
2810
|
-
return isSandboxHostCapacityFailure(diagnostics) || isSandboxBoxConfigFailure(diagnostics);
|
|
2811
|
-
}
|
|
2746
|
+
|
|
2747
|
+
// src/sandbox/workspace-provision.ts
|
|
2812
2748
|
async function requestSandboxReplacement(recover, failure, label) {
|
|
2813
2749
|
if (!recover) throw failure.error;
|
|
2814
2750
|
const recovery = await recover(failure);
|
|
@@ -3083,6 +3019,99 @@ async function provisionWorkspaceSandbox(shell, options, gate, reuseOnly) {
|
|
|
3083
3019
|
}
|
|
3084
3020
|
return rememberRunningBox(name, box);
|
|
3085
3021
|
}
|
|
3022
|
+
|
|
3023
|
+
// src/sandbox/workspace-claim.ts
|
|
3024
|
+
async function ensureWorkspaceSandbox(shell, options) {
|
|
3025
|
+
const box = await claimWorkspaceSandbox(shell, options, false);
|
|
3026
|
+
if (!box) throw new Error("ensureWorkspaceSandbox: a claim that may provision returned no box");
|
|
3027
|
+
return box;
|
|
3028
|
+
}
|
|
3029
|
+
async function reuseWorkspaceSandbox(shell, options) {
|
|
3030
|
+
if (options.forceNew) return void 0;
|
|
3031
|
+
await hydrateReuseState(shell, options);
|
|
3032
|
+
if (!hasRecentProbe(shell, options)) return void 0;
|
|
3033
|
+
return claimWorkspaceSandbox(shell, options, true);
|
|
3034
|
+
}
|
|
3035
|
+
function spendGate(options) {
|
|
3036
|
+
let gated;
|
|
3037
|
+
return () => {
|
|
3038
|
+
const before = options.spend?.beforeProvision;
|
|
3039
|
+
if (!before) return Promise.resolve();
|
|
3040
|
+
const run = () => before({
|
|
3041
|
+
workspaceId: options.workspaceId,
|
|
3042
|
+
...options.userId ? { userId: options.userId } : {}
|
|
3043
|
+
});
|
|
3044
|
+
return gated ??= Promise.resolve(options.trace ? options.trace.measure("sandbox.spend.before_provision", "sandbox", run, void 0, options.traceParent) : run());
|
|
3045
|
+
};
|
|
3046
|
+
}
|
|
3047
|
+
async function claimWorkspaceSandbox(shell, options, reuseOnly) {
|
|
3048
|
+
const { trace } = options;
|
|
3049
|
+
const gate = spendGate(options);
|
|
3050
|
+
await hydrateReuseState(shell, options);
|
|
3051
|
+
if (!hasRecentProbe(shell, options)) await gate();
|
|
3052
|
+
const claim = trace?.start("sandbox.claim", "sandbox", { "workspace.harness": options.harness }, options.traceParent);
|
|
3053
|
+
const traced = trace && claim ? {
|
|
3054
|
+
...options,
|
|
3055
|
+
measure: (stage, operation) => {
|
|
3056
|
+
const run = () => trace.measure(stage, "sandbox", () => operation(), void 0, claim);
|
|
3057
|
+
return options.measure ? options.measure(stage, run) : run();
|
|
3058
|
+
}
|
|
3059
|
+
} : options;
|
|
3060
|
+
try {
|
|
3061
|
+
const box = await bringUpWorkspaceSandbox(shell, traced, gate, reuseOnly);
|
|
3062
|
+
if (!box) {
|
|
3063
|
+
claim?.end({ "sandbox.reuse_declined": true });
|
|
3064
|
+
return void 0;
|
|
3065
|
+
}
|
|
3066
|
+
claim?.end({ "sandbox.id": box.id, ...trustedBoxes.has(box) ? { "sandbox.probe_trusted": true } : {} });
|
|
3067
|
+
if (!trustedBoxes.has(box)) await observeProvisionedBox(shell, options, box);
|
|
3068
|
+
await persistReuseState(shell, box);
|
|
3069
|
+
return box;
|
|
3070
|
+
} catch (error) {
|
|
3071
|
+
claim?.end(void 0, error);
|
|
3072
|
+
throw error;
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
async function observeProvisionedBox(shell, options, box) {
|
|
3076
|
+
const onProvisioned = options.spend?.onProvisioned;
|
|
3077
|
+
if (!onProvisioned) return;
|
|
3078
|
+
const resources = shell.resources ?? DEFAULT_SANDBOX_RESOURCES;
|
|
3079
|
+
const observe = async () => {
|
|
3080
|
+
await onProvisioned({
|
|
3081
|
+
workspaceId: options.workspaceId,
|
|
3082
|
+
...options.userId ? { userId: options.userId } : {},
|
|
3083
|
+
sandboxId: box.id,
|
|
3084
|
+
boxKey: box.name,
|
|
3085
|
+
idleTimeoutSeconds: resources.idleTimeoutSeconds,
|
|
3086
|
+
maxLifetimeSeconds: resources.maxLifetimeSeconds,
|
|
3087
|
+
at: Date.now()
|
|
3088
|
+
});
|
|
3089
|
+
};
|
|
3090
|
+
try {
|
|
3091
|
+
await (options.trace ? options.trace.measure("sandbox.spend.observe", "sandbox", observe, void 0, options.traceParent) : observe());
|
|
3092
|
+
} catch {
|
|
3093
|
+
}
|
|
3094
|
+
}
|
|
3095
|
+
async function bringUpWorkspaceSandbox(shell, options, gate, reuseOnly) {
|
|
3096
|
+
try {
|
|
3097
|
+
return await provisionWorkspaceSandbox(shell, options, gate, reuseOnly);
|
|
3098
|
+
} catch (err) {
|
|
3099
|
+
if (!shell.replaceUnbringableBox) throw err;
|
|
3100
|
+
if (options.forceNew) throw err;
|
|
3101
|
+
if (!isUnbringableBoxError(err)) throw err;
|
|
3102
|
+
return await provisionWorkspaceSandbox(shell, { ...options, forceNew: true }, gate, reuseOnly);
|
|
3103
|
+
}
|
|
3104
|
+
}
|
|
3105
|
+
function isUnbringableBoxError(error) {
|
|
3106
|
+
if (error instanceof SandboxRecoveryFailedError) return true;
|
|
3107
|
+
const diagnostics = serializeSandboxProvisioningError(error);
|
|
3108
|
+
return isSandboxHostCapacityFailure(diagnostics) || isSandboxBoxConfigFailure(diagnostics);
|
|
3109
|
+
}
|
|
3110
|
+
|
|
3111
|
+
// src/sandbox/prompt-profile.ts
|
|
3112
|
+
import {
|
|
3113
|
+
mergeAgentProfiles
|
|
3114
|
+
} from "@tangle-network/agent-interface";
|
|
3086
3115
|
function historyTranscript(history) {
|
|
3087
3116
|
return history.map((entry) => `${entry.role === "assistant" ? "Assistant" : "User"}: ${entry.content}`).join("\n\n");
|
|
3088
3117
|
}
|
|
@@ -3157,28 +3186,101 @@ function applyPromptTokenLimits(profile, limits) {
|
|
|
3157
3186
|
profile.model?.maxVisibleOutputTokens,
|
|
3158
3187
|
requestedVisible
|
|
3159
3188
|
);
|
|
3160
|
-
let maxReasoningTokens = lowerCeiling(
|
|
3161
|
-
profile.model?.maxReasoningTokens,
|
|
3162
|
-
requestedReasoning
|
|
3189
|
+
let maxReasoningTokens = lowerCeiling(
|
|
3190
|
+
profile.model?.maxReasoningTokens,
|
|
3191
|
+
requestedReasoning
|
|
3192
|
+
);
|
|
3193
|
+
if (maxTotalOutputTokens !== void 0) {
|
|
3194
|
+
if (maxVisibleOutputTokens !== void 0) {
|
|
3195
|
+
maxVisibleOutputTokens = Math.min(maxVisibleOutputTokens, maxTotalOutputTokens);
|
|
3196
|
+
}
|
|
3197
|
+
if (maxReasoningTokens !== void 0) {
|
|
3198
|
+
maxReasoningTokens = Math.min(maxReasoningTokens, maxTotalOutputTokens);
|
|
3199
|
+
}
|
|
3200
|
+
}
|
|
3201
|
+
return {
|
|
3202
|
+
...profile,
|
|
3203
|
+
model: {
|
|
3204
|
+
...profile.model ?? {},
|
|
3205
|
+
...maxVisibleOutputTokens !== void 0 ? { maxVisibleOutputTokens } : {},
|
|
3206
|
+
...maxReasoningTokens !== void 0 ? { maxReasoningTokens } : {},
|
|
3207
|
+
...maxTotalOutputTokens !== void 0 ? { maxTotalOutputTokens } : {}
|
|
3208
|
+
}
|
|
3209
|
+
};
|
|
3210
|
+
}
|
|
3211
|
+
async function resolveSandboxPromptBackend(shell, options, operation = "sandbox prompt") {
|
|
3212
|
+
const initialHarness = options.harness ?? options.profile?.harness ?? DEFAULT_HARNESS;
|
|
3213
|
+
if (!isHarness(initialHarness)) throw new Error(`Unsupported sandbox harness: ${initialHarness}`);
|
|
3214
|
+
const extraMcp = mergeExtraMcp(
|
|
3215
|
+
options.appToolMcp ?? {},
|
|
3216
|
+
options.profile?.mcp ?? options.baseProfileMcp ?? {},
|
|
3217
|
+
options.extraMcp
|
|
3218
|
+
);
|
|
3219
|
+
const compose = (harness2) => {
|
|
3220
|
+
if (!shell.profile) throw new Error(`${operation}: supply a profile or a shell profile composer`);
|
|
3221
|
+
return shell.profile({ systemPrompt: options.systemPrompt, extraMcp, harness: harness2 });
|
|
3222
|
+
};
|
|
3223
|
+
let fullProfile = options.profile ? mergeAgentProfiles(options.profile, {
|
|
3224
|
+
...options.systemPrompt !== void 0 ? { prompt: { systemPrompt: options.systemPrompt } } : {},
|
|
3225
|
+
...Object.keys(extraMcp).length > 0 ? { mcp: extraMcp } : {}
|
|
3226
|
+
}) : compose(initialHarness);
|
|
3227
|
+
const harness = options.harness ?? fullProfile.harness ?? DEFAULT_HARNESS;
|
|
3228
|
+
if (!isHarness(harness)) throw new Error(`Unsupported sandbox harness: ${harness}`);
|
|
3229
|
+
if (!options.profile && harness !== initialHarness) fullProfile = compose(harness);
|
|
3230
|
+
const explicitModel = trimOrNull(options.model);
|
|
3231
|
+
const profileModel = trimOrNull(fullProfile.model?.default);
|
|
3232
|
+
const profileProvider = profileModel && (!explicitModel || explicitModel === profileModel) ? trimOrNull(fullProfile.model?.provider) : null;
|
|
3233
|
+
const model = requireTransportableModel(
|
|
3234
|
+
resolveModelSelection({
|
|
3235
|
+
...shell.provider,
|
|
3236
|
+
providerName: trimOrNull(shell.provider?.providerName) ?? profileProvider ?? void 0
|
|
3237
|
+
}, {
|
|
3238
|
+
model: explicitModel ?? profileModel ?? void 0,
|
|
3239
|
+
modelApiKey: options.modelApiKey
|
|
3240
|
+
}),
|
|
3241
|
+
operation
|
|
3242
|
+
);
|
|
3243
|
+
if (model) assertHarnessModelCompatible(harness, {
|
|
3244
|
+
...model,
|
|
3245
|
+
provider: profileProvider ?? model.provider
|
|
3246
|
+
});
|
|
3247
|
+
const selectedProfile = {
|
|
3248
|
+
...fullProfile,
|
|
3249
|
+
harness,
|
|
3250
|
+
// The materializer compares the profile and transport as provider-qualified
|
|
3251
|
+
// identities. Authored provider evidence has already served preflight above.
|
|
3252
|
+
...model ? { model: { ...fullProfile.model, provider: model.provider, default: model.model } } : {}
|
|
3253
|
+
};
|
|
3254
|
+
const executionProfile = shell.deferProfileFiles && !options.profile ? splitDeferredProfileFiles(selectedProfile).leanProfile : selectedProfile;
|
|
3255
|
+
const profile = applyPromptTokenLimits(
|
|
3256
|
+
attachReasoningEffort(executionProfile, harness, options.effort),
|
|
3257
|
+
{
|
|
3258
|
+
maxVisibleOutputTokens: options.maxOutputTokens,
|
|
3259
|
+
maxReasoningTokens: options.maxReasoningTokens,
|
|
3260
|
+
maxTotalOutputTokens: options.maxTotalOutputTokens
|
|
3261
|
+
}
|
|
3262
|
+
);
|
|
3263
|
+
assertProfilePromptWithinBudget(
|
|
3264
|
+
profile,
|
|
3265
|
+
shell.promptBudget ?? {},
|
|
3266
|
+
`${operation} profile systemPrompt`,
|
|
3267
|
+
SHELL_PROMPT_BUDGET_HINT
|
|
3163
3268
|
);
|
|
3164
|
-
if (
|
|
3165
|
-
|
|
3166
|
-
maxVisibleOutputTokens = Math.min(maxVisibleOutputTokens, maxTotalOutputTokens);
|
|
3167
|
-
}
|
|
3168
|
-
if (maxReasoningTokens !== void 0) {
|
|
3169
|
-
maxReasoningTokens = Math.min(maxReasoningTokens, maxTotalOutputTokens);
|
|
3170
|
-
}
|
|
3269
|
+
if (options.onProfileResolved) {
|
|
3270
|
+
options.onProfileResolved(await fingerprintAgentProfile(profile, { model: model?.model, harness }));
|
|
3171
3271
|
}
|
|
3172
3272
|
return {
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
}
|
|
3273
|
+
type: harness,
|
|
3274
|
+
profile,
|
|
3275
|
+
...model ? backendModelFields(model) : {},
|
|
3276
|
+
...options.runtimeAttachments ? { runtimeAttachments: options.runtimeAttachments } : {},
|
|
3277
|
+
...options.runtimeSecrets ? { runtimeSecrets: options.runtimeSecrets } : {},
|
|
3278
|
+
...options.secretProfileIsolation ? { metadata: { profileSecretIsolation: true } } : {},
|
|
3279
|
+
...options.interactions ? { interactions: options.interactions } : {}
|
|
3180
3280
|
};
|
|
3181
3281
|
}
|
|
3282
|
+
|
|
3283
|
+
// src/sandbox/prompt-events.ts
|
|
3182
3284
|
function cachedSandboxPromptEvents(cached, fallbackExecutionId) {
|
|
3183
3285
|
const cachedResult = cached.result;
|
|
3184
3286
|
const executionId = typeof cachedResult.executionId === "string" && cachedResult.executionId.trim() ? cachedResult.executionId : fallbackExecutionId;
|
|
@@ -3344,76 +3446,55 @@ function adaptSandboxStream(events) {
|
|
|
3344
3446
|
}
|
|
3345
3447
|
})();
|
|
3346
3448
|
}
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
);
|
|
3355
|
-
const
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
const
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
const
|
|
3368
|
-
|
|
3369
|
-
const
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
);
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
const
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
{
|
|
3394
|
-
|
|
3395
|
-
maxReasoningTokens: options.maxReasoningTokens,
|
|
3396
|
-
maxTotalOutputTokens: options.maxTotalOutputTokens
|
|
3397
|
-
}
|
|
3398
|
-
);
|
|
3399
|
-
assertProfilePromptWithinBudget(
|
|
3400
|
-
profile,
|
|
3401
|
-
shell.promptBudget ?? {},
|
|
3402
|
-
`${operation} profile systemPrompt`,
|
|
3403
|
-
SHELL_PROMPT_BUDGET_HINT
|
|
3404
|
-
);
|
|
3405
|
-
if (options.onProfileResolved) {
|
|
3406
|
-
options.onProfileResolved(await fingerprintAgentProfile(profile, { model: model?.model, harness }));
|
|
3449
|
+
var SEVERED_FINISH_REASONS = /* @__PURE__ */ new Set(["error", "other", "unknown"]);
|
|
3450
|
+
function asPlainRecord(v) {
|
|
3451
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
3452
|
+
}
|
|
3453
|
+
function classifySeveredStream(event) {
|
|
3454
|
+
const root = asPlainRecord(event);
|
|
3455
|
+
if (!root || root.type !== "message.part.updated") return null;
|
|
3456
|
+
const body = asPlainRecord(root.properties) ?? asPlainRecord(root.data) ?? root;
|
|
3457
|
+
const part = asPlainRecord(body.part);
|
|
3458
|
+
if (!part) return null;
|
|
3459
|
+
if (part.type === "step-start") return { kind: "step-start" };
|
|
3460
|
+
if (part.type !== "step-finish") return null;
|
|
3461
|
+
const reason = typeof part.reason === "string" && part.reason ? part.reason : "unknown";
|
|
3462
|
+
return { kind: "step-finish", reason, severed: SEVERED_FINISH_REASONS.has(reason) };
|
|
3463
|
+
}
|
|
3464
|
+
function isTerminalPromptEvent(event) {
|
|
3465
|
+
const t = asPlainRecord(event)?.type;
|
|
3466
|
+
return t === "result" || t === "done";
|
|
3467
|
+
}
|
|
3468
|
+
function detectInteractiveQuestion(event) {
|
|
3469
|
+
const root = asPlainRecord(event);
|
|
3470
|
+
if (!root) return null;
|
|
3471
|
+
const type = typeof root.type === "string" ? root.type : void 0;
|
|
3472
|
+
const data = asPlainRecord(root.data);
|
|
3473
|
+
const props = asPlainRecord(root.properties);
|
|
3474
|
+
const body = props ?? data ?? root;
|
|
3475
|
+
if (type === "question.asked" || type === "question") return firstQuestionText(body);
|
|
3476
|
+
if (type === "interaction" && body.kind === "question") return firstQuestionText(body);
|
|
3477
|
+
const part = asPlainRecord(data?.part) ?? asPlainRecord(body.part);
|
|
3478
|
+
const tool = typeof part?.tool === "string" && part.tool || typeof part?.name === "string" && part.name || typeof body.tool === "string" && body.tool || void 0;
|
|
3479
|
+
const isQ = type === "message.part.updated" && (tool === "question" || asPlainRecord(part)?.type === "question");
|
|
3480
|
+
if (!isQ) return null;
|
|
3481
|
+
const state = asPlainRecord(asPlainRecord(part)?.state);
|
|
3482
|
+
return firstQuestionText(asPlainRecord(state?.input) ?? state ?? part ?? body);
|
|
3483
|
+
}
|
|
3484
|
+
function firstQuestionText(value) {
|
|
3485
|
+
const arr = Array.isArray(value?.questions) ? value.questions : Array.isArray(asPlainRecord(value?.input)?.questions) ? asPlainRecord(value.input).questions : [];
|
|
3486
|
+
const first = asPlainRecord(arr[0]);
|
|
3487
|
+
const q = typeof first?.question === "string" && first.question || typeof first?.prompt === "string" && first.prompt || void 0;
|
|
3488
|
+
return q ?? "interactive question";
|
|
3489
|
+
}
|
|
3490
|
+
|
|
3491
|
+
// src/sandbox/prompt-dispatch.ts
|
|
3492
|
+
function emitSandboxActivity(spend, box) {
|
|
3493
|
+
if (!spend?.onActivity) return;
|
|
3494
|
+
try {
|
|
3495
|
+
spend.onActivity({ sandboxId: box.id, at: Date.now() });
|
|
3496
|
+
} catch {
|
|
3407
3497
|
}
|
|
3408
|
-
return {
|
|
3409
|
-
type: harness,
|
|
3410
|
-
profile,
|
|
3411
|
-
...model ? backendModelFields(model) : {},
|
|
3412
|
-
...options.runtimeAttachments ? { runtimeAttachments: options.runtimeAttachments } : {},
|
|
3413
|
-
...options.runtimeSecrets ? { runtimeSecrets: options.runtimeSecrets } : {},
|
|
3414
|
-
...options.secretProfileIsolation ? { metadata: { profileSecretIsolation: true } } : {},
|
|
3415
|
-
...options.interactions ? { interactions: options.interactions } : {}
|
|
3416
|
-
};
|
|
3417
3498
|
}
|
|
3418
3499
|
var SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS = 8 * 6e4;
|
|
3419
3500
|
async function* resendRefusedDispatch(dispatch, signal) {
|
|
@@ -3504,6 +3585,8 @@ async function* streamSandboxPrompt(shell, box, message, options) {
|
|
|
3504
3585
|
throw new Error(`sandbox model stream severed mid-turn (reason="${severedFinishReason}")`);
|
|
3505
3586
|
}
|
|
3506
3587
|
}
|
|
3588
|
+
|
|
3589
|
+
// src/sandbox/prompt-result.ts
|
|
3507
3590
|
function textPartId(part, fallback) {
|
|
3508
3591
|
for (const key of ["id", "partId", "messagePartId"]) {
|
|
3509
3592
|
const value = part?.[key];
|
|
@@ -3548,6 +3631,31 @@ async function runSandboxPrompt(shell, box, message, options) {
|
|
|
3548
3631
|
options?.history
|
|
3549
3632
|
);
|
|
3550
3633
|
}
|
|
3634
|
+
async function driveSandboxTurn(shell, box, message, options) {
|
|
3635
|
+
const backend = await resolveSandboxPromptBackend(shell, options, "driveSandboxTurn");
|
|
3636
|
+
const prompt = typeof message === "string" ? flattenHistory(message, options.history) : mergeHistoryIntoParts(message, options.history);
|
|
3637
|
+
try {
|
|
3638
|
+
const drive = await box.driveTurn(prompt, {
|
|
3639
|
+
sessionId: options.sessionId,
|
|
3640
|
+
...options.turnId ? { turnId: options.turnId } : {},
|
|
3641
|
+
...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {},
|
|
3642
|
+
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
3643
|
+
...options.signal ? { signal: options.signal } : {},
|
|
3644
|
+
...options.expectedPublicProfileRequestDigest ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest } : {},
|
|
3645
|
+
...options.expectedSecretProfileReceipt ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt } : {},
|
|
3646
|
+
// Sandbox 0.37 drives through the session message lane, so a gateway
|
|
3647
|
+
// consumer can handle these events. Callers without one should omit
|
|
3648
|
+
// interactions so the run stays unattended.
|
|
3649
|
+
backend
|
|
3650
|
+
});
|
|
3651
|
+
emitSandboxActivity(options.spend, box);
|
|
3652
|
+
return ok(drive);
|
|
3653
|
+
} catch (err) {
|
|
3654
|
+
return fail(err);
|
|
3655
|
+
}
|
|
3656
|
+
}
|
|
3657
|
+
|
|
3658
|
+
// src/sandbox/access.ts
|
|
3551
3659
|
async function syncSandboxMemberAdd(box, seam, userId, role) {
|
|
3552
3660
|
try {
|
|
3553
3661
|
await box.permissions.add({ userId, role: seam.roleToSandboxRole(role) });
|
|
@@ -3626,82 +3734,18 @@ async function mintSandboxScopedToken(box, options) {
|
|
|
3626
3734
|
return fail(err);
|
|
3627
3735
|
}
|
|
3628
3736
|
}
|
|
3629
|
-
async function driveSandboxTurn(shell, box, message, options) {
|
|
3630
|
-
const backend = await resolveSandboxPromptBackend(shell, options, "driveSandboxTurn");
|
|
3631
|
-
const prompt = typeof message === "string" ? flattenHistory(message, options.history) : mergeHistoryIntoParts(message, options.history);
|
|
3632
|
-
try {
|
|
3633
|
-
const drive = await box.driveTurn(prompt, {
|
|
3634
|
-
sessionId: options.sessionId,
|
|
3635
|
-
...options.turnId ? { turnId: options.turnId } : {},
|
|
3636
|
-
...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {},
|
|
3637
|
-
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
3638
|
-
...options.signal ? { signal: options.signal } : {},
|
|
3639
|
-
...options.expectedPublicProfileRequestDigest ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest } : {},
|
|
3640
|
-
...options.expectedSecretProfileReceipt ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt } : {},
|
|
3641
|
-
// Sandbox 0.37 drives through the session message lane, so a gateway
|
|
3642
|
-
// consumer can handle these events. Callers without one should omit
|
|
3643
|
-
// interactions so the run stays unattended.
|
|
3644
|
-
backend
|
|
3645
|
-
});
|
|
3646
|
-
emitSandboxActivity(options.spend, box);
|
|
3647
|
-
return ok(drive);
|
|
3648
|
-
} catch (err) {
|
|
3649
|
-
return fail(err);
|
|
3650
|
-
}
|
|
3651
|
-
}
|
|
3652
|
-
var SEVERED_FINISH_REASONS = /* @__PURE__ */ new Set(["error", "other", "unknown"]);
|
|
3653
|
-
function asPlainRecord(v) {
|
|
3654
|
-
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
3655
|
-
}
|
|
3656
|
-
function classifySeveredStream(event) {
|
|
3657
|
-
const root = asPlainRecord(event);
|
|
3658
|
-
if (!root || root.type !== "message.part.updated") return null;
|
|
3659
|
-
const body = asPlainRecord(root.properties) ?? asPlainRecord(root.data) ?? root;
|
|
3660
|
-
const part = asPlainRecord(body.part);
|
|
3661
|
-
if (!part) return null;
|
|
3662
|
-
if (part.type === "step-start") return { kind: "step-start" };
|
|
3663
|
-
if (part.type !== "step-finish") return null;
|
|
3664
|
-
const reason = typeof part.reason === "string" && part.reason ? part.reason : "unknown";
|
|
3665
|
-
return { kind: "step-finish", reason, severed: SEVERED_FINISH_REASONS.has(reason) };
|
|
3666
|
-
}
|
|
3667
|
-
function isTerminalPromptEvent(event) {
|
|
3668
|
-
const t = asPlainRecord(event)?.type;
|
|
3669
|
-
return t === "result" || t === "done";
|
|
3670
|
-
}
|
|
3671
|
-
function detectInteractiveQuestion(event) {
|
|
3672
|
-
const root = asPlainRecord(event);
|
|
3673
|
-
if (!root) return null;
|
|
3674
|
-
const type = typeof root.type === "string" ? root.type : void 0;
|
|
3675
|
-
const data = asPlainRecord(root.data);
|
|
3676
|
-
const props = asPlainRecord(root.properties);
|
|
3677
|
-
const body = props ?? data ?? root;
|
|
3678
|
-
if (type === "question.asked" || type === "question") return firstQuestionText(body);
|
|
3679
|
-
if (type === "interaction" && body.kind === "question") return firstQuestionText(body);
|
|
3680
|
-
const part = asPlainRecord(data?.part) ?? asPlainRecord(body.part);
|
|
3681
|
-
const tool = typeof part?.tool === "string" && part.tool || typeof part?.name === "string" && part.name || typeof body.tool === "string" && body.tool || void 0;
|
|
3682
|
-
const isQ = type === "message.part.updated" && (tool === "question" || asPlainRecord(part)?.type === "question");
|
|
3683
|
-
if (!isQ) return null;
|
|
3684
|
-
const state = asPlainRecord(asPlainRecord(part)?.state);
|
|
3685
|
-
return firstQuestionText(asPlainRecord(state?.input) ?? state ?? part ?? body);
|
|
3686
|
-
}
|
|
3687
|
-
function firstQuestionText(value) {
|
|
3688
|
-
const arr = Array.isArray(value?.questions) ? value.questions : Array.isArray(asPlainRecord(value?.input)?.questions) ? asPlainRecord(value.input).questions : [];
|
|
3689
|
-
const first = asPlainRecord(arr[0]);
|
|
3690
|
-
const q = typeof first?.question === "string" && first.question || typeof first?.prompt === "string" && first.prompt || void 0;
|
|
3691
|
-
return q ?? "interactive question";
|
|
3692
|
-
}
|
|
3693
3737
|
|
|
3694
3738
|
export {
|
|
3695
3739
|
traceSandboxPromptEvents,
|
|
3696
3740
|
createCacheReuseStore,
|
|
3741
|
+
shellQuote,
|
|
3742
|
+
statSandboxFileSize,
|
|
3743
|
+
readSandboxBinaryBytes,
|
|
3697
3744
|
backendModelFields,
|
|
3698
3745
|
resolveModelSelection,
|
|
3699
3746
|
resolveModel,
|
|
3700
3747
|
SandboxModelResolutionError,
|
|
3701
3748
|
requireTransportableModel,
|
|
3702
|
-
shellQuote,
|
|
3703
|
-
statSandboxFileSize,
|
|
3704
|
-
readSandboxBinaryBytes,
|
|
3705
3749
|
createWorkspaceSandboxManager,
|
|
3706
3750
|
createSandboxTerminalConnectionRoute,
|
|
3707
3751
|
sandboxPrewarmClaimKey,
|
|
@@ -3739,9 +3783,9 @@ export {
|
|
|
3739
3783
|
escalationHints,
|
|
3740
3784
|
createEscalationSpeculator,
|
|
3741
3785
|
resolveSandboxClientCredentials,
|
|
3786
|
+
DEFAULT_SANDBOX_RESOURCES,
|
|
3742
3787
|
PYPI_EGRESS_DOMAINS,
|
|
3743
3788
|
buildProductEgressPolicy,
|
|
3744
|
-
DEFAULT_SANDBOX_RESOURCES,
|
|
3745
3789
|
dropTrustedBox,
|
|
3746
3790
|
getClient,
|
|
3747
3791
|
resetClientCache,
|
|
@@ -3756,11 +3800,11 @@ export {
|
|
|
3756
3800
|
ensureSandboxToolBinDir,
|
|
3757
3801
|
runSandboxToolPathSetup,
|
|
3758
3802
|
splitDeferredProfileFiles,
|
|
3803
|
+
writeProfileFilesToBox,
|
|
3759
3804
|
SandboxEgressPolicyMismatchError,
|
|
3760
3805
|
SandboxRuntimeAuthRefreshError,
|
|
3761
3806
|
SandboxRecoveryFailedError,
|
|
3762
3807
|
SandboxBoxBusyError,
|
|
3763
|
-
writeProfileFilesToBox,
|
|
3764
3808
|
deferredCorpusHash,
|
|
3765
3809
|
PROVISION_PAYLOAD_MAX_BYTES,
|
|
3766
3810
|
ENV_VALUE_MAX_BYTES,
|
|
@@ -3776,22 +3820,22 @@ export {
|
|
|
3776
3820
|
mergeExtraMcp,
|
|
3777
3821
|
attachReasoningEffort,
|
|
3778
3822
|
applyPromptTokenLimits,
|
|
3779
|
-
adaptSandboxStream,
|
|
3780
3823
|
resolveSandboxPromptBackend,
|
|
3824
|
+
adaptSandboxStream,
|
|
3825
|
+
classifySeveredStream,
|
|
3826
|
+
isTerminalPromptEvent,
|
|
3827
|
+
detectInteractiveQuestion,
|
|
3781
3828
|
SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS,
|
|
3782
3829
|
streamSandboxPrompt,
|
|
3783
3830
|
collectSandboxPromptText,
|
|
3784
3831
|
runSandboxPrompt,
|
|
3832
|
+
driveSandboxTurn,
|
|
3785
3833
|
syncSandboxMemberAdd,
|
|
3786
3834
|
syncSandboxMemberRemove,
|
|
3787
3835
|
syncSandboxMemberRole,
|
|
3788
3836
|
secretStoreFromClient,
|
|
3789
3837
|
storeSecret,
|
|
3790
3838
|
deleteSecret,
|
|
3791
|
-
mintSandboxScopedToken
|
|
3792
|
-
driveSandboxTurn,
|
|
3793
|
-
classifySeveredStream,
|
|
3794
|
-
isTerminalPromptEvent,
|
|
3795
|
-
detectInteractiveQuestion
|
|
3839
|
+
mintSandboxScopedToken
|
|
3796
3840
|
};
|
|
3797
|
-
//# sourceMappingURL=chunk-
|
|
3841
|
+
//# sourceMappingURL=chunk-JILHXHJE.js.map
|