agent-neckbeard 1.1.27 → 1.1.28
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/CHANGELOG.md +11 -0
- package/README.md +53 -461
- package/dist/build.cjs +5560 -0
- package/dist/build.d.cts +80 -0
- package/dist/build.d.ts +80 -0
- package/dist/build.js +17 -0
- package/dist/chunk-JF5YPOBY.js +4339 -0
- package/dist/chunk-KG6SJM74.js +97 -0
- package/dist/chunk-M3FISP7J.js +377 -0
- package/dist/chunk-M7XNBKG4.js +346 -0
- package/dist/cli.cjs +5606 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +75 -0
- package/dist/index.cjs +1444 -146
- package/dist/index.d.cts +312 -6
- package/dist/index.d.ts +312 -6
- package/dist/index.js +36 -3397
- package/dist/{invoke-client-YKWOTQWG.js → invoke-client-P2CPBYTF.js} +2 -41
- package/dist/serve-Dan1HQKN.d.cts +89 -0
- package/dist/serve-Dan1HQKN.d.ts +89 -0
- package/dist/serve.cjs +337 -0
- package/dist/serve.d.cts +1 -0
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +8 -0
- package/docs/AGENT.md +173 -0
- package/docs/DAYTONA.md +56 -0
- package/docs/DOCKER.md +7 -7
- package/docs/E2B.md +11 -0
- package/docs/LEGACY.md +335 -0
- package/docs/MODAL.md +14 -12
- package/docs/SUPERVISOR.md +2 -2
- package/package.json +43 -3
- package/dist/chunk-6GCQOKYI.js +0 -48
package/dist/index.cjs
CHANGED
|
@@ -106,7 +106,12 @@ async function* decodeSseStream(chunks) {
|
|
|
106
106
|
}
|
|
107
107
|
const tail = buffer.trim();
|
|
108
108
|
if (tail.length > 0) {
|
|
109
|
-
|
|
109
|
+
let parsed;
|
|
110
|
+
try {
|
|
111
|
+
parsed = parseFrame(tail);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
throw new IncompleteSseFrameError(`Incomplete SSE data frame: ${error instanceof Error ? error.message : String(error)}`);
|
|
114
|
+
}
|
|
110
115
|
if (parsed !== void 0) {
|
|
111
116
|
yield parsed;
|
|
112
117
|
}
|
|
@@ -127,9 +132,12 @@ function parseFrame(raw) {
|
|
|
127
132
|
throw new Error(`Malformed SSE data frame: ${message}`);
|
|
128
133
|
}
|
|
129
134
|
}
|
|
135
|
+
var IncompleteSseFrameError;
|
|
130
136
|
var init_sse_framing = __esm({
|
|
131
137
|
"src/sse-framing.ts"() {
|
|
132
138
|
"use strict";
|
|
139
|
+
IncompleteSseFrameError = class extends Error {
|
|
140
|
+
};
|
|
133
141
|
}
|
|
134
142
|
});
|
|
135
143
|
|
|
@@ -246,21 +254,31 @@ __export(src_exports, {
|
|
|
246
254
|
Agent: () => Agent,
|
|
247
255
|
ConfigurationError: () => ConfigurationError,
|
|
248
256
|
DEFAULT_DEPENDENCIES: () => DEFAULT_DEPENDENCIES,
|
|
257
|
+
DefinedAgent: () => DefinedAgent,
|
|
249
258
|
DeploymentError: () => DeploymentError,
|
|
250
259
|
ExecutionError: () => ExecutionError,
|
|
260
|
+
LegacyBundledAgent: () => LegacyBundledAgent,
|
|
251
261
|
NeckbeardError: () => NeckbeardError,
|
|
252
262
|
RuntimeBusyError: () => RuntimeBusyError,
|
|
263
|
+
SKILLS_DIR: () => SKILLS_DIR,
|
|
253
264
|
SandboxClient: () => SandboxClient,
|
|
265
|
+
TURN_PROTOCOL_VERSION: () => TURN_PROTOCOL_VERSION,
|
|
266
|
+
TurnLostError: () => TurnLostError,
|
|
254
267
|
ValidationError: () => ValidationError,
|
|
268
|
+
defineAgent: () => defineAgent,
|
|
269
|
+
destroyProviderSandbox: () => destroyProviderSandbox,
|
|
270
|
+
getPiTurnResult: () => getPiTurnResult,
|
|
271
|
+
isDefinedAgent: () => isDefinedAgent,
|
|
255
272
|
normalizeStackFramePath: () => normalizeStackFramePath,
|
|
256
273
|
resolveAgentSourceFile: () => resolveAgentSourceFile,
|
|
274
|
+
resolveImageTag: () => resolveImageTag,
|
|
257
275
|
withNeckbeardNextConfig: () => withNeckbeardNextConfig
|
|
258
276
|
});
|
|
259
277
|
module.exports = __toCommonJS(src_exports);
|
|
260
278
|
var import_node_url = require("url");
|
|
261
279
|
var import_node_fs = require("fs");
|
|
262
|
-
var
|
|
263
|
-
var
|
|
280
|
+
var import_node_path2 = require("path");
|
|
281
|
+
var import_node_crypto4 = require("crypto");
|
|
264
282
|
var import_node_module2 = require("module");
|
|
265
283
|
init_protocol();
|
|
266
284
|
|
|
@@ -555,11 +573,11 @@ function writeString(header2, value, offset, length) {
|
|
|
555
573
|
function writeOctal(header2, value, offset, length) {
|
|
556
574
|
header2.write(`${value.toString(8).padStart(length - 1, "0")}\0`, offset, length, "ascii");
|
|
557
575
|
}
|
|
558
|
-
function splitUstarPath(
|
|
559
|
-
if (import_node_buffer.Buffer.byteLength(
|
|
560
|
-
for (let index =
|
|
561
|
-
const prefix =
|
|
562
|
-
const name =
|
|
576
|
+
function splitUstarPath(path2) {
|
|
577
|
+
if (import_node_buffer.Buffer.byteLength(path2) <= 100) return { name: path2, prefix: "" };
|
|
578
|
+
for (let index = path2.indexOf("/"); index !== -1; index = path2.indexOf("/", index + 1)) {
|
|
579
|
+
const prefix = path2.slice(0, index);
|
|
580
|
+
const name = path2.slice(index + 1);
|
|
563
581
|
if (import_node_buffer.Buffer.byteLength(prefix) <= 155 && import_node_buffer.Buffer.byteLength(name) <= 100 && name) {
|
|
564
582
|
return { name, prefix };
|
|
565
583
|
}
|
|
@@ -590,8 +608,8 @@ function header(options) {
|
|
|
590
608
|
function padding(size) {
|
|
591
609
|
return import_node_buffer.Buffer.alloc((BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE);
|
|
592
610
|
}
|
|
593
|
-
function paxPathRecord(
|
|
594
|
-
const body = ` path=${
|
|
611
|
+
function paxPathRecord(path2) {
|
|
612
|
+
const body = ` path=${path2}
|
|
595
613
|
`;
|
|
596
614
|
let length = import_node_buffer.Buffer.byteLength(body);
|
|
597
615
|
while (String(length).length + import_node_buffer.Buffer.byteLength(body) !== length) {
|
|
@@ -603,18 +621,18 @@ async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
|
|
|
603
621
|
const chunks = [];
|
|
604
622
|
for (const entry of entries) {
|
|
605
623
|
const isDirectory = entry.content === void 0;
|
|
606
|
-
const
|
|
624
|
+
const path2 = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
|
|
607
625
|
const size = entry.content?.byteLength ?? 0;
|
|
608
626
|
const type = isDirectory ? "5" : "0";
|
|
609
627
|
const mode = isDirectory ? 493 : 420;
|
|
610
|
-
const split = splitUstarPath(
|
|
628
|
+
const split = splitUstarPath(path2);
|
|
611
629
|
if (split) {
|
|
612
630
|
chunks.push(header({ ...split, mode, size, mtime, type }));
|
|
613
631
|
} else {
|
|
614
|
-
const record = paxPathRecord(
|
|
632
|
+
const record = paxPathRecord(path2);
|
|
615
633
|
chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
|
|
616
634
|
chunks.push(record, padding(record.byteLength));
|
|
617
|
-
chunks.push(header({ name:
|
|
635
|
+
chunks.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
|
|
618
636
|
}
|
|
619
637
|
if (entry.content) {
|
|
620
638
|
chunks.push(import_node_buffer.Buffer.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
|
|
@@ -1339,8 +1357,8 @@ function decisionFunctions(paths) {
|
|
|
1339
1357
|
"}"
|
|
1340
1358
|
];
|
|
1341
1359
|
}
|
|
1342
|
-
function exactLifecycleMarkerFunction(functionName, variablePrefix,
|
|
1343
|
-
const quotedPath = shellQuote(
|
|
1360
|
+
function exactLifecycleMarkerFunction(functionName, variablePrefix, path2, expectation) {
|
|
1361
|
+
const quotedPath = shellQuote(path2);
|
|
1344
1362
|
const missingMarker = expectation.kind === "populated" ? [
|
|
1345
1363
|
` if [ ! -e ${quotedPath} ] && [ ! -L ${quotedPath} ]; then return 1; fi`
|
|
1346
1364
|
] : [];
|
|
@@ -1577,25 +1595,25 @@ function buildLegacyDetachedStopCommand(pid, startTicks, providerName) {
|
|
|
1577
1595
|
})
|
|
1578
1596
|
].join("\n");
|
|
1579
1597
|
}
|
|
1580
|
-
function atomicFile(partialPath,
|
|
1598
|
+
function atomicFile(partialPath, path2, parentDirectory, write) {
|
|
1581
1599
|
return [
|
|
1582
1600
|
`${write} || exit 1`,
|
|
1583
1601
|
`sync -f ${shellQuote(partialPath)} || exit 1`,
|
|
1584
|
-
`mv -f ${shellQuote(partialPath)} ${shellQuote(
|
|
1602
|
+
`mv -f ${shellQuote(partialPath)} ${shellQuote(path2)} || exit 1`,
|
|
1585
1603
|
`sync -f ${shellQuote(parentDirectory)} || exit 1`
|
|
1586
1604
|
];
|
|
1587
1605
|
}
|
|
1588
|
-
function secureDirectory(
|
|
1606
|
+
function secureDirectory(path2, create) {
|
|
1589
1607
|
return [
|
|
1590
1608
|
...create ? [
|
|
1591
|
-
`if [ ! -e ${shellQuote(
|
|
1592
|
-
` mkdir ${shellQuote(
|
|
1609
|
+
`if [ ! -e ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ]; then`,
|
|
1610
|
+
` mkdir ${shellQuote(path2)} 2>/dev/null || true`,
|
|
1593
1611
|
"fi"
|
|
1594
1612
|
] : [],
|
|
1595
|
-
`[ -d ${shellQuote(
|
|
1596
|
-
`directory_owner=$(stat -c %u ${shellQuote(
|
|
1613
|
+
`[ -d ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ] || exit 1`,
|
|
1614
|
+
`directory_owner=$(stat -c %u ${shellQuote(path2)} 2>/dev/null) || exit 1`,
|
|
1597
1615
|
'[ "$directory_owner" = "$(id -u)" ] || exit 1',
|
|
1598
|
-
`directory_mode=$(stat -c %a ${shellQuote(
|
|
1616
|
+
`directory_mode=$(stat -c %a ${shellQuote(path2)} 2>/dev/null) || exit 1`,
|
|
1599
1617
|
'[ "$directory_mode" = 700 ] || exit 1'
|
|
1600
1618
|
];
|
|
1601
1619
|
}
|
|
@@ -1605,10 +1623,10 @@ function secureDetachedRoot() {
|
|
|
1605
1623
|
function secureLaunchDirectory(paths, create) {
|
|
1606
1624
|
return secureDirectory(paths.directory, create);
|
|
1607
1625
|
}
|
|
1608
|
-
function assertSafeRegularFile(
|
|
1626
|
+
function assertSafeRegularFile(path2) {
|
|
1609
1627
|
return [
|
|
1610
|
-
`[ -e ${shellQuote(
|
|
1611
|
-
`[ -f ${shellQuote(
|
|
1628
|
+
`[ -e ${shellQuote(path2)} ] || return 1`,
|
|
1629
|
+
`[ -f ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ] || exit 1`
|
|
1612
1630
|
];
|
|
1613
1631
|
}
|
|
1614
1632
|
function publishDecision(paths, action, partialPath) {
|
|
@@ -1665,8 +1683,8 @@ function releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChange
|
|
|
1665
1683
|
];
|
|
1666
1684
|
}
|
|
1667
1685
|
function renderShellLockAssertion(options) {
|
|
1668
|
-
const { functionName, variablePrefix, path, descriptorFd } = options;
|
|
1669
|
-
const pathExpression = shellQuote(
|
|
1686
|
+
const { functionName, variablePrefix, path: path2, descriptorFd } = options;
|
|
1687
|
+
const pathExpression = shellQuote(path2);
|
|
1670
1688
|
const descriptorPathExpression = `/proc/self/fd/${descriptorFd}`;
|
|
1671
1689
|
const descriptorChecks = [
|
|
1672
1690
|
`[ -f ${descriptorPathExpression} ] || return 1`,
|
|
@@ -1816,23 +1834,23 @@ function cleanLifecycleShell(script, environmentMode) {
|
|
|
1816
1834
|
delimiter
|
|
1817
1835
|
].join("\n");
|
|
1818
1836
|
}
|
|
1819
|
-
function previousLogPath(
|
|
1820
|
-
return `${
|
|
1837
|
+
function previousLogPath(path2) {
|
|
1838
|
+
return `${path2}.previous`;
|
|
1821
1839
|
}
|
|
1822
|
-
function logPipePath(
|
|
1823
|
-
return `${
|
|
1840
|
+
function logPipePath(path2) {
|
|
1841
|
+
return `${path2}.pipe`;
|
|
1824
1842
|
}
|
|
1825
|
-
function logSnapshotPath(
|
|
1826
|
-
return `${
|
|
1843
|
+
function logSnapshotPath(path2) {
|
|
1844
|
+
return `${path2}.snapshot`;
|
|
1827
1845
|
}
|
|
1828
|
-
function logSnapshotStagingPath(
|
|
1829
|
-
return `${logSnapshotPath(
|
|
1846
|
+
function logSnapshotStagingPath(path2) {
|
|
1847
|
+
return `${logSnapshotPath(path2)}.partial`;
|
|
1830
1848
|
}
|
|
1831
|
-
function legacyLogSnapshotLockPath(
|
|
1832
|
-
return `${logSnapshotPath(
|
|
1849
|
+
function legacyLogSnapshotLockPath(path2) {
|
|
1850
|
+
return `${logSnapshotPath(path2)}.lock`;
|
|
1833
1851
|
}
|
|
1834
|
-
function logChunkPath(
|
|
1835
|
-
return `${
|
|
1852
|
+
function logChunkPath(path2) {
|
|
1853
|
+
return `${path2}.chunk`;
|
|
1836
1854
|
}
|
|
1837
1855
|
function boundedLogProgram() {
|
|
1838
1856
|
return [
|
|
@@ -2678,9 +2696,9 @@ function buildReadLegacyDetachedLogsCommand(nonce) {
|
|
|
2678
2696
|
].join("\n");
|
|
2679
2697
|
}
|
|
2680
2698
|
function readLogFiles(stdout, stderr, previous, beforePrint = []) {
|
|
2681
|
-
const optionalPrevious = (
|
|
2682
|
-
`if [ -e ${shellQuote(
|
|
2683
|
-
...assertSafeRegularFile(
|
|
2699
|
+
const optionalPrevious = (path2) => [
|
|
2700
|
+
`if [ -e ${shellQuote(path2)} ] || [ -L ${shellQuote(path2)} ]; then`,
|
|
2701
|
+
...assertSafeRegularFile(path2).map((line) => line.replace("return 1", "exit 1")).map((line) => ` ${line}`),
|
|
2684
2702
|
"fi"
|
|
2685
2703
|
];
|
|
2686
2704
|
const boundedPayload = (current, prior) => prior === void 0 ? `read_bounded_log_file ${shellQuote(current)}` : `read_bounded_log_snapshot ${shellQuote(current)} ${shellQuote(prior)} ${shellQuote(logSnapshotPath(current))}`;
|
|
@@ -2922,10 +2940,10 @@ async function executeRawDaytonaCommand(sandbox, command, options) {
|
|
|
2922
2940
|
daytonaTimeoutSeconds(options.timeoutMs)
|
|
2923
2941
|
);
|
|
2924
2942
|
}
|
|
2925
|
-
async function makeDaytonaDirectory(sandbox,
|
|
2943
|
+
async function makeDaytonaDirectory(sandbox, path2, options) {
|
|
2926
2944
|
return executeRawDaytonaCommand(
|
|
2927
2945
|
sandbox,
|
|
2928
|
-
`mkdir -p -- ${shellQuote(
|
|
2946
|
+
`mkdir -p -- ${shellQuote(path2)}`,
|
|
2929
2947
|
options
|
|
2930
2948
|
);
|
|
2931
2949
|
}
|
|
@@ -2935,11 +2953,11 @@ function daytonaUploadContent(content) {
|
|
|
2935
2953
|
if (content instanceof Uint8Array) return import_node_buffer3.Buffer.from(content);
|
|
2936
2954
|
return import_node_buffer3.Buffer.from(content);
|
|
2937
2955
|
}
|
|
2938
|
-
async function uploadDaytonaFile(sandbox,
|
|
2956
|
+
async function uploadDaytonaFile(sandbox, path2, content, options) {
|
|
2939
2957
|
await options.beforeIo?.();
|
|
2940
2958
|
await sandbox.fs.uploadFile(
|
|
2941
2959
|
daytonaUploadContent(content),
|
|
2942
|
-
|
|
2960
|
+
path2,
|
|
2943
2961
|
daytonaTimeoutSeconds(options.timeoutMs)
|
|
2944
2962
|
);
|
|
2945
2963
|
}
|
|
@@ -3072,29 +3090,29 @@ var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
|
|
|
3072
3090
|
get id() {
|
|
3073
3091
|
return this.sandbox.id;
|
|
3074
3092
|
}
|
|
3075
|
-
async makeDir(
|
|
3076
|
-
const result = await makeDaytonaDirectory(this.sandbox,
|
|
3093
|
+
async makeDir(path2) {
|
|
3094
|
+
const result = await makeDaytonaDirectory(this.sandbox, path2, {
|
|
3077
3095
|
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
3078
3096
|
});
|
|
3079
3097
|
if (result.exitCode !== 0) {
|
|
3080
|
-
throw this.failure(result.result || `Failed to create directory ${
|
|
3098
|
+
throw this.failure(result.result || `Failed to create directory ${path2}`);
|
|
3081
3099
|
}
|
|
3082
3100
|
}
|
|
3083
|
-
writeFile(
|
|
3084
|
-
return uploadDaytonaFile(this.sandbox,
|
|
3101
|
+
writeFile(path2, content) {
|
|
3102
|
+
return uploadDaytonaFile(this.sandbox, path2, content, {
|
|
3085
3103
|
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
3086
3104
|
});
|
|
3087
3105
|
}
|
|
3088
|
-
async readFile(
|
|
3106
|
+
async readFile(path2) {
|
|
3089
3107
|
const content = await this.sandbox.fs.downloadFile(
|
|
3090
|
-
|
|
3108
|
+
path2,
|
|
3091
3109
|
daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
|
|
3092
3110
|
);
|
|
3093
3111
|
return content.toString("utf8");
|
|
3094
3112
|
}
|
|
3095
|
-
async readFileBytes(
|
|
3113
|
+
async readFileBytes(path2) {
|
|
3096
3114
|
const content = await this.sandbox.fs.downloadFile(
|
|
3097
|
-
|
|
3115
|
+
path2,
|
|
3098
3116
|
daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
|
|
3099
3117
|
);
|
|
3100
3118
|
return new Uint8Array(content);
|
|
@@ -3335,17 +3353,17 @@ var E2bSandboxHandle = class {
|
|
|
3335
3353
|
get id() {
|
|
3336
3354
|
return this.sandbox.sandboxId;
|
|
3337
3355
|
}
|
|
3338
|
-
async makeDir(
|
|
3339
|
-
await this.sandbox.files.makeDir(
|
|
3356
|
+
async makeDir(path2) {
|
|
3357
|
+
await this.sandbox.files.makeDir(path2);
|
|
3340
3358
|
}
|
|
3341
|
-
writeFile(
|
|
3342
|
-
return this.sandbox.files.write(
|
|
3359
|
+
writeFile(path2, content) {
|
|
3360
|
+
return this.sandbox.files.write(path2, writeContent(content)).then(() => void 0);
|
|
3343
3361
|
}
|
|
3344
|
-
readFile(
|
|
3345
|
-
return this.sandbox.files.read(
|
|
3362
|
+
readFile(path2) {
|
|
3363
|
+
return this.sandbox.files.read(path2, { format: "text" });
|
|
3346
3364
|
}
|
|
3347
|
-
readFileBytes(
|
|
3348
|
-
return this.sandbox.files.read(
|
|
3365
|
+
readFileBytes(path2) {
|
|
3366
|
+
return this.sandbox.files.read(path2, { format: "bytes" });
|
|
3349
3367
|
}
|
|
3350
3368
|
runCommand(cmd, options) {
|
|
3351
3369
|
return runE2bCommand(this.sandbox, cmd, options);
|
|
@@ -3460,15 +3478,18 @@ function modalNetworkOptions(options) {
|
|
|
3460
3478
|
};
|
|
3461
3479
|
}
|
|
3462
3480
|
function validateModalOptions(options, mode, failure) {
|
|
3463
|
-
const { networkBlockAll, networkAllowList, domainAllowList, regions, ...rest } = options;
|
|
3481
|
+
const { networkBlockAll, networkAllowList, domainAllowList, regions, command, ...rest } = options;
|
|
3464
3482
|
validateProviderOptions("Modal", mode === "connect" ? options : rest, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
|
|
3465
3483
|
"template",
|
|
3466
3484
|
"appName",
|
|
3467
3485
|
"timeoutMs",
|
|
3468
3486
|
"cpu",
|
|
3469
3487
|
"memoryMiB",
|
|
3470
|
-
...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
|
|
3488
|
+
...mode === "create" ? ["tokenId", "tokenSecret", "envs", "registrySecret"] : []
|
|
3471
3489
|
]], failure);
|
|
3490
|
+
if (command !== void 0 && (mode !== "create" || !Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || part.includes("\0")))) {
|
|
3491
|
+
throw failure(mode === "create" ? "Modal command must be a non-empty array of strings without null bytes." : 'Modal does not support option "command".');
|
|
3492
|
+
}
|
|
3472
3493
|
if (regions !== void 0 && (!Array.isArray(regions) || regions.length === 0 || regions.some((region) => typeof region !== "string" || !/^[a-z0-9-]+$/u.test(region)))) {
|
|
3473
3494
|
throw failure('Modal regions must be a non-empty array of region names such as "us" or "us-east".');
|
|
3474
3495
|
}
|
|
@@ -3562,7 +3583,9 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3562
3583
|
try {
|
|
3563
3584
|
const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
|
|
3564
3585
|
const network = modalNetworkOptions(options);
|
|
3565
|
-
const
|
|
3586
|
+
const template = options.template ?? MODAL_DEFAULT_TEMPLATE;
|
|
3587
|
+
const registryImage = options.registrySecret === void 0 ? client.images.fromRegistry(template) : client.images.fromRegistry(template, await client.secrets.fromName(options.registrySecret));
|
|
3588
|
+
const image = options.command ? registryImage : registryImage.dockerfileCommands([
|
|
3566
3589
|
"USER root",
|
|
3567
3590
|
"RUN apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils sudo curl ca-certificates && rm -rf /var/lib/apt/lists/*",
|
|
3568
3591
|
// The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
|
|
@@ -3577,7 +3600,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3577
3600
|
timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
|
|
3578
3601
|
cpu: options.cpu,
|
|
3579
3602
|
memoryMiB: options.memoryMiB,
|
|
3580
|
-
workdir: "/root",
|
|
3603
|
+
...options.command ? { command: options.command } : { workdir: "/root" },
|
|
3581
3604
|
env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
|
|
3582
3605
|
(entry) => entry[1] !== void 0
|
|
3583
3606
|
))
|
|
@@ -3588,6 +3611,15 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3588
3611
|
sandbox?.detach();
|
|
3589
3612
|
}
|
|
3590
3613
|
}
|
|
3614
|
+
/** Terminates a sandbox by ID; one that is gone counts as terminated. */
|
|
3615
|
+
static async destroyById(options, failure) {
|
|
3616
|
+
const client = await sharedClient({
|
|
3617
|
+
tokenId: options.tokenId,
|
|
3618
|
+
tokenSecret: options.tokenSecret,
|
|
3619
|
+
environment: options.environment
|
|
3620
|
+
});
|
|
3621
|
+
await new _ModalSandboxHandle(options.sandboxId, client, failure).destroy();
|
|
3622
|
+
}
|
|
3591
3623
|
static async connect(options, failure) {
|
|
3592
3624
|
const client = await sharedClient({
|
|
3593
3625
|
tokenId: options.tokenId,
|
|
@@ -3624,17 +3656,17 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3624
3656
|
sandbox?.detach();
|
|
3625
3657
|
}
|
|
3626
3658
|
}
|
|
3627
|
-
makeDir(
|
|
3628
|
-
return this.use((sandbox) => sandbox.filesystem.makeDirectory(
|
|
3659
|
+
makeDir(path2) {
|
|
3660
|
+
return this.use((sandbox) => sandbox.filesystem.makeDirectory(path2));
|
|
3629
3661
|
}
|
|
3630
|
-
writeFile(
|
|
3631
|
-
return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content,
|
|
3662
|
+
writeFile(path2, content) {
|
|
3663
|
+
return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content, path2) : sandbox.filesystem.writeBytes(content, path2));
|
|
3632
3664
|
}
|
|
3633
|
-
readFile(
|
|
3634
|
-
return this.use((sandbox) => sandbox.filesystem.readText(
|
|
3665
|
+
readFile(path2) {
|
|
3666
|
+
return this.use((sandbox) => sandbox.filesystem.readText(path2));
|
|
3635
3667
|
}
|
|
3636
|
-
readFileBytes(
|
|
3637
|
-
return this.use((sandbox) => sandbox.filesystem.readBytes(
|
|
3668
|
+
readFileBytes(path2) {
|
|
3669
|
+
return this.use((sandbox) => sandbox.filesystem.readBytes(path2));
|
|
3638
3670
|
}
|
|
3639
3671
|
runCommand(command, options) {
|
|
3640
3672
|
try {
|
|
@@ -3707,6 +3739,1220 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3707
3739
|
}
|
|
3708
3740
|
};
|
|
3709
3741
|
|
|
3742
|
+
// src/define.ts
|
|
3743
|
+
var import_promises = require("fs/promises");
|
|
3744
|
+
var import_node_os = __toESM(require("os"), 1);
|
|
3745
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
3746
|
+
|
|
3747
|
+
// src/agent.ts
|
|
3748
|
+
var import_node_crypto3 = require("crypto");
|
|
3749
|
+
init_sse_framing();
|
|
3750
|
+
|
|
3751
|
+
// src/turn-protocol.ts
|
|
3752
|
+
var TURN_PROTOCOL_VERSION = 2;
|
|
3753
|
+
var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
|
|
3754
|
+
var MAX_TURN_ID_LENGTH = 200;
|
|
3755
|
+
function isRecord2(value) {
|
|
3756
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3757
|
+
}
|
|
3758
|
+
function parseTurnRecord(record) {
|
|
3759
|
+
if (!isRecord2(record)) throw new Error("Turn record must be an object.");
|
|
3760
|
+
const { seq } = record;
|
|
3761
|
+
if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) {
|
|
3762
|
+
throw new Error("Turn record seq must be a non-negative integer.");
|
|
3763
|
+
}
|
|
3764
|
+
if (record.type === "event" && "event" in record) {
|
|
3765
|
+
return { seq, type: "event", event: record.event };
|
|
3766
|
+
}
|
|
3767
|
+
if (record.type === "end" && (record.outcome === "completed" || record.outcome === "aborted" || record.outcome === "failed") && (record.error === void 0 || typeof record.error === "string")) {
|
|
3768
|
+
return {
|
|
3769
|
+
seq,
|
|
3770
|
+
type: "end",
|
|
3771
|
+
outcome: record.outcome,
|
|
3772
|
+
...record.error === void 0 ? {} : { error: record.error }
|
|
3773
|
+
};
|
|
3774
|
+
}
|
|
3775
|
+
throw new Error("Turn record has an unknown shape.");
|
|
3776
|
+
}
|
|
3777
|
+
function parseTurnHealth(value) {
|
|
3778
|
+
if (!isRecord2(value)) throw new Error("Health response must be an object.");
|
|
3779
|
+
const { ok, protocolVersion, busy, turnId } = value;
|
|
3780
|
+
if (ok !== true || typeof protocolVersion !== "number" || typeof busy !== "boolean" || turnId !== null && typeof turnId !== "string") {
|
|
3781
|
+
throw new Error("Health response is not { ok: true, protocolVersion, busy, turnId }.");
|
|
3782
|
+
}
|
|
3783
|
+
return { ok, protocolVersion, busy, turnId };
|
|
3784
|
+
}
|
|
3785
|
+
function readAssistantMessageEnd(event) {
|
|
3786
|
+
if (!isRecord2(event) || event.type !== "message_end" || !isRecord2(event.message)) return void 0;
|
|
3787
|
+
const { role, content, stopReason, errorMessage: errorMessage2 } = event.message;
|
|
3788
|
+
if (role !== "assistant") return void 0;
|
|
3789
|
+
const text = (Array.isArray(content) ? content : []).flatMap((block) => isRecord2(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
|
|
3790
|
+
return {
|
|
3791
|
+
text,
|
|
3792
|
+
stopReason: typeof stopReason === "string" ? stopReason : void 0,
|
|
3793
|
+
errorMessage: typeof errorMessage2 === "string" ? errorMessage2 : void 0
|
|
3794
|
+
};
|
|
3795
|
+
}
|
|
3796
|
+
function getPiTurnResult(records) {
|
|
3797
|
+
let end;
|
|
3798
|
+
let message;
|
|
3799
|
+
for (const record of records) {
|
|
3800
|
+
if (record.type === "end") {
|
|
3801
|
+
end = record;
|
|
3802
|
+
continue;
|
|
3803
|
+
}
|
|
3804
|
+
message = readAssistantMessageEnd(record.event) ?? message;
|
|
3805
|
+
}
|
|
3806
|
+
if (!end) return { completed: false, error: "The agent turn has not ended." };
|
|
3807
|
+
if (end.outcome !== "completed") {
|
|
3808
|
+
return { completed: false, error: end.error ?? `The agent turn was ${end.outcome}.` };
|
|
3809
|
+
}
|
|
3810
|
+
if (!message) return { completed: false, error: "The agent did not reply." };
|
|
3811
|
+
if (message.stopReason !== "stop") {
|
|
3812
|
+
return {
|
|
3813
|
+
completed: false,
|
|
3814
|
+
error: message.errorMessage?.trim() || `The agent stopped with ${message.stopReason ?? "no reason"}.`
|
|
3815
|
+
};
|
|
3816
|
+
}
|
|
3817
|
+
return { completed: true, text: message.text || null };
|
|
3818
|
+
}
|
|
3819
|
+
|
|
3820
|
+
// src/agent.ts
|
|
3821
|
+
var DEFAULT_COMMAND = ["node", "/app/agent.mjs"];
|
|
3822
|
+
var DEFAULT_PORT = 8080;
|
|
3823
|
+
var DEFAULT_START_TIMEOUT_MS = 12e4;
|
|
3824
|
+
var DEFAULT_PREPARE_TIMEOUT_MS = 30 * 6e4;
|
|
3825
|
+
var DEFAULT_RECONNECT_TIMEOUT_MS = 12e4;
|
|
3826
|
+
var HEALTH_POLL_INTERVAL_MS = 500;
|
|
3827
|
+
var RECONNECT_MIN_DELAY_MS = 250;
|
|
3828
|
+
var RECONNECT_MAX_DELAY_MS = 5e3;
|
|
3829
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
3830
|
+
var ARTIFACT_PREFIX = "nb-";
|
|
3831
|
+
function filterDefined(envs) {
|
|
3832
|
+
return Object.fromEntries(Object.entries(envs ?? {}).filter(
|
|
3833
|
+
(entry) => entry[1] !== void 0
|
|
3834
|
+
));
|
|
3835
|
+
}
|
|
3836
|
+
function delay2(ms, signal) {
|
|
3837
|
+
return new Promise((resolve2, reject) => {
|
|
3838
|
+
if (signal?.aborted) return reject(abortError(signal));
|
|
3839
|
+
const onAbort = () => {
|
|
3840
|
+
clearTimeout(timer);
|
|
3841
|
+
reject(abortError(signal));
|
|
3842
|
+
};
|
|
3843
|
+
const timer = setTimeout(() => {
|
|
3844
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3845
|
+
resolve2();
|
|
3846
|
+
}, ms);
|
|
3847
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3848
|
+
});
|
|
3849
|
+
}
|
|
3850
|
+
function untilDeadline(deadline, signal) {
|
|
3851
|
+
const timeout = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
|
|
3852
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
3853
|
+
}
|
|
3854
|
+
function untilAborted(operation, signal) {
|
|
3855
|
+
if (signal?.aborted) return Promise.reject(abortError(signal));
|
|
3856
|
+
return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
|
|
3857
|
+
}
|
|
3858
|
+
function abortError(signal) {
|
|
3859
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
3860
|
+
const error = new Error("Operation aborted.");
|
|
3861
|
+
error.name = "AbortError";
|
|
3862
|
+
return error;
|
|
3863
|
+
}
|
|
3864
|
+
async function* textChunks(body, onChunk) {
|
|
3865
|
+
const decoder = new TextDecoder();
|
|
3866
|
+
const reader = body.getReader();
|
|
3867
|
+
try {
|
|
3868
|
+
while (true) {
|
|
3869
|
+
const { done, value } = await reader.read();
|
|
3870
|
+
if (done) break;
|
|
3871
|
+
onChunk();
|
|
3872
|
+
yield decoder.decode(value, { stream: true });
|
|
3873
|
+
}
|
|
3874
|
+
} finally {
|
|
3875
|
+
await reader.cancel().catch(() => void 0);
|
|
3876
|
+
reader.releaseLock();
|
|
3877
|
+
}
|
|
3878
|
+
}
|
|
3879
|
+
var EndpointRejectedError = class extends Error {
|
|
3880
|
+
};
|
|
3881
|
+
var Agent = class {
|
|
3882
|
+
constructor(options) {
|
|
3883
|
+
this.options = options;
|
|
3884
|
+
if (!options || typeof options !== "object") throw new ConfigurationError("Agent options must be an object.");
|
|
3885
|
+
if (typeof options.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(options.name)) {
|
|
3886
|
+
throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
|
|
3887
|
+
}
|
|
3888
|
+
if (typeof options.image !== "string" || !options.image.trim() || /\s/u.test(options.image)) {
|
|
3889
|
+
throw new ConfigurationError("Agent image must be a registry image reference.");
|
|
3890
|
+
}
|
|
3891
|
+
const provider = options.sandbox?.provider;
|
|
3892
|
+
if (provider !== "modal" && provider !== "daytona" && provider !== "e2b") {
|
|
3893
|
+
throw new ConfigurationError('Agent sandbox.provider must be "modal", "daytona", or "e2b".');
|
|
3894
|
+
}
|
|
3895
|
+
const command = options.command ?? DEFAULT_COMMAND;
|
|
3896
|
+
if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || !part)) {
|
|
3897
|
+
throw new ConfigurationError("Agent command must be a non-empty array of non-empty strings.");
|
|
3898
|
+
}
|
|
3899
|
+
const port = options.port ?? DEFAULT_PORT;
|
|
3900
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
3901
|
+
throw new ConfigurationError("Agent port must be between 1 and 65535.");
|
|
3902
|
+
}
|
|
3903
|
+
this.name = options.name;
|
|
3904
|
+
this.image = options.image;
|
|
3905
|
+
this.command = [...command];
|
|
3906
|
+
this.port = port;
|
|
3907
|
+
}
|
|
3908
|
+
name;
|
|
3909
|
+
image;
|
|
3910
|
+
command;
|
|
3911
|
+
port;
|
|
3912
|
+
endpoints = /* @__PURE__ */ new Map();
|
|
3913
|
+
preparing;
|
|
3914
|
+
get provider() {
|
|
3915
|
+
return this.options.sandbox.provider;
|
|
3916
|
+
}
|
|
3917
|
+
/**
|
|
3918
|
+
* Name of the Daytona snapshot or E2B template for this image, command, and resources. Equal
|
|
3919
|
+
* inputs share one, so preparing again is a lookup.
|
|
3920
|
+
*/
|
|
3921
|
+
get artifactName() {
|
|
3922
|
+
const { sandbox } = this.options;
|
|
3923
|
+
const resources = sandbox.provider === "daytona" ? sandbox.resources : sandbox.provider === "e2b" ? { cpuCount: sandbox.cpuCount, memoryMB: sandbox.memoryMB } : void 0;
|
|
3924
|
+
const hash2 = (0, import_node_crypto3.createHash)("sha256").update(JSON.stringify([this.image, sandbox.provider === "daytona" ? this.command : [], resources ?? null])).digest("hex").slice(0, 16);
|
|
3925
|
+
return `${ARTIFACT_PREFIX}${this.name}-${hash2}`;
|
|
3926
|
+
}
|
|
3927
|
+
/**
|
|
3928
|
+
* Creates the Daytona snapshot or E2B template for the image if it is missing and waits until
|
|
3929
|
+
* it can start sandboxes. Run it from CI after pushing the image so no sandbox waits on a
|
|
3930
|
+
* build. Modal pulls the image directly, so this does nothing there. `refresh` builds it again
|
|
3931
|
+
* even when it exists, as after pushing new contents under a tag it was built from, since its
|
|
3932
|
+
* name comes from the image's reference, not its contents.
|
|
3933
|
+
*/
|
|
3934
|
+
prepare(options = {}) {
|
|
3935
|
+
const { sandbox } = this.options;
|
|
3936
|
+
if (sandbox.provider === "modal") return Promise.resolve();
|
|
3937
|
+
if (options.signal?.aborted) return Promise.reject(abortError(options.signal));
|
|
3938
|
+
if (!this.preparing || options.refresh) {
|
|
3939
|
+
const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
|
|
3940
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
3941
|
+
const steps = { signal: deadline, refresh: options.refresh ?? false, ...options.onLog ? { onLog: options.onLog } : {} };
|
|
3942
|
+
this.preparing = untilAborted(
|
|
3943
|
+
() => sandbox.provider === "daytona" ? this.prepareDaytonaSnapshot(sandbox, steps) : this.prepareE2bTemplate(sandbox, steps),
|
|
3944
|
+
deadline
|
|
3945
|
+
).catch((error) => {
|
|
3946
|
+
this.preparing = void 0;
|
|
3947
|
+
if (deadline.aborted) throw new DeploymentError(`Preparing ${this.artifactName} took longer than ${timeoutMs}ms.`);
|
|
3948
|
+
throw error;
|
|
3949
|
+
});
|
|
3950
|
+
this.preparing.catch(() => void 0);
|
|
3951
|
+
}
|
|
3952
|
+
const preparing = this.preparing;
|
|
3953
|
+
return untilAborted(() => preparing, options.signal);
|
|
3954
|
+
}
|
|
3955
|
+
/** Starts a sandbox from the image and waits for its runtime. Returns the sandbox ID. */
|
|
3956
|
+
async start(options = {}) {
|
|
3957
|
+
await this.prepare({ ...options.signal ? { signal: options.signal } : {} });
|
|
3958
|
+
const envs = {
|
|
3959
|
+
...filterDefined(this.options.envs),
|
|
3960
|
+
...filterDefined(options.envs),
|
|
3961
|
+
...options.sessionId === void 0 ? {} : { NECKBEARD_SESSION_ID: options.sessionId },
|
|
3962
|
+
NECKBEARD_PORT: String(this.port)
|
|
3963
|
+
};
|
|
3964
|
+
if (options.signal?.aborted) throw abortError(options.signal);
|
|
3965
|
+
let sandbox;
|
|
3966
|
+
try {
|
|
3967
|
+
sandbox = await this.createSandbox(envs);
|
|
3968
|
+
} catch (error) {
|
|
3969
|
+
this.preparing = void 0;
|
|
3970
|
+
throw error;
|
|
3971
|
+
}
|
|
3972
|
+
try {
|
|
3973
|
+
if (this.options.sandbox.provider === "e2b") await this.startE2bRuntime(this.options.sandbox, sandbox.id, envs);
|
|
3974
|
+
await this.waitForRuntime(sandbox.id, options.signal);
|
|
3975
|
+
return sandbox.id;
|
|
3976
|
+
} catch (error) {
|
|
3977
|
+
this.endpoints.delete(sandbox.id);
|
|
3978
|
+
try {
|
|
3979
|
+
await sandbox.destroy();
|
|
3980
|
+
} catch (cleanupError) {
|
|
3981
|
+
const startMessage = error instanceof Error ? error.message : String(error);
|
|
3982
|
+
const cleanupMessage = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
3983
|
+
throw new DeploymentError(
|
|
3984
|
+
`Sandbox ${sandbox.id} failed to start (${startMessage}), and deleting it failed (${cleanupMessage}); kill() it to retry.`,
|
|
3985
|
+
error instanceof Error ? error : void 0,
|
|
3986
|
+
sandbox.id
|
|
3987
|
+
);
|
|
3988
|
+
}
|
|
3989
|
+
throw error;
|
|
3990
|
+
}
|
|
3991
|
+
}
|
|
3992
|
+
/**
|
|
3993
|
+
* Starts a turn and streams its records until its `end` record. Starting a turn whose
|
|
3994
|
+
* `turnId` the runtime already has resumes it instead of running it again.
|
|
3995
|
+
*/
|
|
3996
|
+
async *prompt(sandboxId, turn, options = {}) {
|
|
3997
|
+
const response = await this.request(sandboxId, "POST", "/turns", turn, options.signal);
|
|
3998
|
+
if (response.status === 409) {
|
|
3999
|
+
const body = await response.json().catch(() => ({}));
|
|
4000
|
+
throw new RuntimeBusyError(`Sandbox ${sandboxId} is running another turn (${body.turnId ?? "unknown"}).`);
|
|
4001
|
+
}
|
|
4002
|
+
if (response.status !== 200 && response.status !== 202) {
|
|
4003
|
+
throw new ExecutionError(`Starting turn ${turn.turnId} failed with ${response.status}: ${await response.text()}`);
|
|
4004
|
+
}
|
|
4005
|
+
await response.body?.cancel();
|
|
4006
|
+
yield* this.events(sandboxId, turn.turnId, options);
|
|
4007
|
+
}
|
|
4008
|
+
/**
|
|
4009
|
+
* Runs a Pi turn to its end and returns its final assistant text, or null when it had none.
|
|
4010
|
+
* Throws `ExecutionError` when the turn did not complete or its model did not stop on its own.
|
|
4011
|
+
* Running a turn again with the same `turnId` replays its records from the start.
|
|
4012
|
+
*/
|
|
4013
|
+
async run(sandboxId, turn, options = {}) {
|
|
4014
|
+
const { onRecord, ...streamOptions } = options;
|
|
4015
|
+
const records = [];
|
|
4016
|
+
for await (const record of this.prompt(sandboxId, turn, streamOptions)) {
|
|
4017
|
+
records.push(record);
|
|
4018
|
+
await onRecord?.(record);
|
|
4019
|
+
}
|
|
4020
|
+
options.signal?.throwIfAborted();
|
|
4021
|
+
const result = getPiTurnResult(records);
|
|
4022
|
+
if (!result.completed) throw new ExecutionError(`Turn ${turn.turnId} did not finish: ${result.error}`);
|
|
4023
|
+
return result.text;
|
|
4024
|
+
}
|
|
4025
|
+
/**
|
|
4026
|
+
* Streams a turn's records after `options.after` until its `end` record, reconnecting when
|
|
4027
|
+
* the connection drops. Throws `TurnLostError` when the runtime no longer has the turn.
|
|
4028
|
+
*/
|
|
4029
|
+
async *events(sandboxId, turnId, options = {}) {
|
|
4030
|
+
let last = options.after ?? -1;
|
|
4031
|
+
const reconnectTimeoutMs = options.reconnectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS;
|
|
4032
|
+
let failingSince;
|
|
4033
|
+
let attempt = 0;
|
|
4034
|
+
while (true) {
|
|
4035
|
+
let lastError;
|
|
4036
|
+
const stalled = new AbortController();
|
|
4037
|
+
let watchdog;
|
|
4038
|
+
const armWatchdog = () => {
|
|
4039
|
+
clearTimeout(watchdog);
|
|
4040
|
+
const budget = failingSince === void 0 ? reconnectTimeoutMs : Math.max(0, failingSince + reconnectTimeoutMs - Date.now());
|
|
4041
|
+
watchdog = setTimeout(() => stalled.abort(new Error(`Turn stream sent nothing for ${budget}ms.`)), budget);
|
|
4042
|
+
};
|
|
4043
|
+
armWatchdog();
|
|
4044
|
+
try {
|
|
4045
|
+
const response = await this.request(
|
|
4046
|
+
sandboxId,
|
|
4047
|
+
"GET",
|
|
4048
|
+
`/turns/${encodeURIComponent(turnId)}/events?after=${last}`,
|
|
4049
|
+
void 0,
|
|
4050
|
+
options.signal ? AbortSignal.any([options.signal, stalled.signal]) : stalled.signal,
|
|
4051
|
+
{ stream: true }
|
|
4052
|
+
);
|
|
4053
|
+
if (response.status === 404) {
|
|
4054
|
+
await response.body?.cancel();
|
|
4055
|
+
throw new TurnLostError(`Sandbox ${sandboxId} has no turn ${turnId}.`);
|
|
4056
|
+
}
|
|
4057
|
+
if (!response.ok || !response.body) {
|
|
4058
|
+
await response.body?.cancel();
|
|
4059
|
+
throw new Error(`Turn stream returned ${response.status}.`);
|
|
4060
|
+
}
|
|
4061
|
+
try {
|
|
4062
|
+
const onChunk = () => {
|
|
4063
|
+
failingSince = void 0;
|
|
4064
|
+
armWatchdog();
|
|
4065
|
+
};
|
|
4066
|
+
for await (const frame of decodeSseStream(textChunks(response.body, onChunk))) {
|
|
4067
|
+
let record;
|
|
4068
|
+
try {
|
|
4069
|
+
record = parseTurnRecord(frame);
|
|
4070
|
+
} catch (error) {
|
|
4071
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4072
|
+
throw new ExecutionError(`Sandbox ${sandboxId} sent an invalid record for turn ${turnId}: ${message}`);
|
|
4073
|
+
}
|
|
4074
|
+
if (record.seq <= last) {
|
|
4075
|
+
if (record.type === "end") return;
|
|
4076
|
+
continue;
|
|
4077
|
+
}
|
|
4078
|
+
last = record.seq;
|
|
4079
|
+
failingSince = void 0;
|
|
4080
|
+
attempt = 0;
|
|
4081
|
+
clearTimeout(watchdog);
|
|
4082
|
+
yield record;
|
|
4083
|
+
armWatchdog();
|
|
4084
|
+
if (record.type === "end") return;
|
|
4085
|
+
}
|
|
4086
|
+
} catch (error) {
|
|
4087
|
+
if (error instanceof Error && error.message.startsWith("Malformed SSE data frame")) {
|
|
4088
|
+
throw new ExecutionError(`Sandbox ${sandboxId} sent a malformed frame for turn ${turnId}: ${error.message}`);
|
|
4089
|
+
}
|
|
4090
|
+
if (!(error instanceof IncompleteSseFrameError)) throw error;
|
|
4091
|
+
}
|
|
4092
|
+
lastError = new Error("Turn stream ended before the turn did.");
|
|
4093
|
+
} catch (error) {
|
|
4094
|
+
if (error instanceof TurnLostError || error instanceof ExecutionError) throw error;
|
|
4095
|
+
if (options.signal?.aborted) throw abortError(options.signal);
|
|
4096
|
+
if (error instanceof EndpointRejectedError) this.endpoints.delete(sandboxId);
|
|
4097
|
+
lastError = stalled.signal.aborted ? stalled.signal.reason : error;
|
|
4098
|
+
} finally {
|
|
4099
|
+
clearTimeout(watchdog);
|
|
4100
|
+
}
|
|
4101
|
+
failingSince ??= Date.now();
|
|
4102
|
+
if (Date.now() - failingSince > reconnectTimeoutMs) {
|
|
4103
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
4104
|
+
throw new ExecutionError(`Lost the stream of turn ${turnId} for over ${reconnectTimeoutMs}ms: ${message}`);
|
|
4105
|
+
}
|
|
4106
|
+
attempt += 1;
|
|
4107
|
+
await delay2(Math.min(RECONNECT_MAX_DELAY_MS, RECONNECT_MIN_DELAY_MS * 2 ** (attempt - 1)), options.signal);
|
|
4108
|
+
}
|
|
4109
|
+
}
|
|
4110
|
+
/** Asks the runtime to stop the turn; its stream then ends with an `aborted` record. */
|
|
4111
|
+
async abort(sandboxId, turnId, signal) {
|
|
4112
|
+
const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/abort`, void 0, signal);
|
|
4113
|
+
await response.body?.cancel();
|
|
4114
|
+
if (response.status !== 202 && response.status !== 404) {
|
|
4115
|
+
throw new ExecutionError(`Aborting turn ${turnId} failed with ${response.status}.`);
|
|
4116
|
+
}
|
|
4117
|
+
}
|
|
4118
|
+
async health(sandboxId, signal) {
|
|
4119
|
+
const response = await this.request(sandboxId, "GET", "/health", void 0, signal);
|
|
4120
|
+
if (!response.ok) throw new ExecutionError(`Health check of sandbox ${sandboxId} returned ${response.status}.`);
|
|
4121
|
+
return parseTurnHealth(await response.json());
|
|
4122
|
+
}
|
|
4123
|
+
/** Waits until no turn runs, for example before reading files a turn writes. */
|
|
4124
|
+
async waitForIdle(sandboxId, options = {}) {
|
|
4125
|
+
const deadline = Date.now() + (options.timeoutMs ?? 6e4);
|
|
4126
|
+
while (true) {
|
|
4127
|
+
try {
|
|
4128
|
+
if (!(await this.health(sandboxId, untilDeadline(deadline, options.signal))).busy) return;
|
|
4129
|
+
} catch (error) {
|
|
4130
|
+
if (options.signal?.aborted) throw error;
|
|
4131
|
+
}
|
|
4132
|
+
if (Date.now() > deadline) throw new RuntimeBusyError(`Sandbox ${sandboxId} did not become idle.`);
|
|
4133
|
+
await delay2(HEALTH_POLL_INTERVAL_MS, options.signal);
|
|
4134
|
+
}
|
|
4135
|
+
}
|
|
4136
|
+
/**
|
|
4137
|
+
* Deletes the sandbox without starting it. One that is already gone counts as deleted; any other
|
|
4138
|
+
* failure throws, so cleanup can be retried, since a Daytona sandbox need not expire on its own.
|
|
4139
|
+
*/
|
|
4140
|
+
async kill(sandboxId) {
|
|
4141
|
+
this.endpoints.delete(sandboxId);
|
|
4142
|
+
const { sandbox } = this.options;
|
|
4143
|
+
if (sandbox.provider === "modal") {
|
|
4144
|
+
await destroyProviderSandbox({
|
|
4145
|
+
provider: "modal",
|
|
4146
|
+
sandboxId,
|
|
4147
|
+
...sandbox.environment ? { environment: sandbox.environment } : {}
|
|
4148
|
+
});
|
|
4149
|
+
return;
|
|
4150
|
+
}
|
|
4151
|
+
await destroyProviderSandbox({ provider: sandbox.provider, sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
|
|
4152
|
+
}
|
|
4153
|
+
/** File and command access to a sandbox, for staging inputs and reading results. */
|
|
4154
|
+
sandbox(sandboxId) {
|
|
4155
|
+
const { sandbox } = this.options;
|
|
4156
|
+
if (sandbox.provider === "modal") {
|
|
4157
|
+
return SandboxClient.connect({
|
|
4158
|
+
provider: "modal",
|
|
4159
|
+
sandboxId,
|
|
4160
|
+
...sandbox.environment ? { environment: sandbox.environment } : {}
|
|
4161
|
+
});
|
|
4162
|
+
}
|
|
4163
|
+
if (sandbox.provider === "e2b") {
|
|
4164
|
+
return SandboxClient.connect({
|
|
4165
|
+
provider: "e2b",
|
|
4166
|
+
sandboxId,
|
|
4167
|
+
...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {},
|
|
4168
|
+
...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
|
|
4169
|
+
});
|
|
4170
|
+
}
|
|
4171
|
+
return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
|
|
4172
|
+
}
|
|
4173
|
+
/**
|
|
4174
|
+
* Deletes this agent's Daytona snapshots or E2B templates except the newest `keep` and the
|
|
4175
|
+
* current one. Returns the names it deleted.
|
|
4176
|
+
*/
|
|
4177
|
+
async gc(options = {}) {
|
|
4178
|
+
const keep = options.keep ?? 3;
|
|
4179
|
+
if (!Number.isInteger(keep) || keep < 0) throw new ConfigurationError("gc keep must be a non-negative integer.");
|
|
4180
|
+
const { sandbox } = this.options;
|
|
4181
|
+
if (sandbox.provider === "modal") return [];
|
|
4182
|
+
const ownName = new RegExp(`^${ARTIFACT_PREFIX}${this.name}-[0-9a-f]{16}$`, "u");
|
|
4183
|
+
const protectedNames = /* @__PURE__ */ new Set([this.artifactName, ...options.alsoKeep ?? []]);
|
|
4184
|
+
const artifacts = sandbox.provider === "daytona" ? await this.listDaytonaSnapshots(sandbox, ownName) : await this.listE2bTemplates(sandbox, ownName);
|
|
4185
|
+
const stale = artifacts.sort((left, right) => right.createdAt - left.createdAt).filter((artifact) => !protectedNames.has(artifact.name)).slice(Math.max(0, keep - artifacts.filter((artifact) => protectedNames.has(artifact.name)).length));
|
|
4186
|
+
for (const artifact of stale) await artifact.delete();
|
|
4187
|
+
return stale.map((artifact) => artifact.name);
|
|
4188
|
+
}
|
|
4189
|
+
createSandbox(envs) {
|
|
4190
|
+
const { sandbox } = this.options;
|
|
4191
|
+
if (sandbox.provider === "modal") {
|
|
4192
|
+
const { provider: _provider, ...modal } = sandbox;
|
|
4193
|
+
return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs });
|
|
4194
|
+
}
|
|
4195
|
+
if (sandbox.provider === "daytona") {
|
|
4196
|
+
const { resources: _resources, ...daytona } = sandbox;
|
|
4197
|
+
return SandboxClient.create({ ...daytona, template: this.artifactName, envs });
|
|
4198
|
+
}
|
|
4199
|
+
const { cpuCount: _cpuCount, memoryMB: _memoryMB, registry: _registry, ...e2b } = sandbox;
|
|
4200
|
+
return SandboxClient.create({ ...e2b, template: this.artifactName, envs, allowPublicTraffic: false });
|
|
4201
|
+
}
|
|
4202
|
+
// An E2B template's start command runs once at build time, without each sandbox's environment.
|
|
4203
|
+
async startE2bRuntime(sandbox, sandboxId, envs) {
|
|
4204
|
+
const { Sandbox } = await import("e2b");
|
|
4205
|
+
const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
|
|
4206
|
+
const e2bSandbox = await Sandbox.connect(sandboxId, {
|
|
4207
|
+
...apiKey ? { apiKey } : {},
|
|
4208
|
+
...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
|
|
4209
|
+
});
|
|
4210
|
+
const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs, timeoutMs: 0 });
|
|
4211
|
+
await command.disconnect();
|
|
4212
|
+
}
|
|
4213
|
+
async waitForRuntime(sandboxId, signal) {
|
|
4214
|
+
const timeoutMs = this.options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS;
|
|
4215
|
+
const deadline = Date.now() + timeoutMs;
|
|
4216
|
+
let lastError;
|
|
4217
|
+
while (Date.now() < deadline) {
|
|
4218
|
+
try {
|
|
4219
|
+
const health = await this.health(sandboxId, untilDeadline(deadline, signal));
|
|
4220
|
+
if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
|
|
4221
|
+
throw new DeploymentError(
|
|
4222
|
+
`Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`
|
|
4223
|
+
);
|
|
4224
|
+
}
|
|
4225
|
+
return;
|
|
4226
|
+
} catch (error) {
|
|
4227
|
+
if (error instanceof DeploymentError || signal?.aborted) throw error;
|
|
4228
|
+
lastError = error;
|
|
4229
|
+
}
|
|
4230
|
+
await delay2(HEALTH_POLL_INTERVAL_MS, signal);
|
|
4231
|
+
}
|
|
4232
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
4233
|
+
throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message}`);
|
|
4234
|
+
}
|
|
4235
|
+
endpoint(sandboxId) {
|
|
4236
|
+
let endpoint = this.endpoints.get(sandboxId);
|
|
4237
|
+
if (!endpoint) {
|
|
4238
|
+
endpoint = this.sandbox(sandboxId).then((sandbox) => sandbox.getServerEndpoint(this.port));
|
|
4239
|
+
endpoint.catch(() => this.endpoints.delete(sandboxId));
|
|
4240
|
+
this.endpoints.set(sandboxId, endpoint);
|
|
4241
|
+
}
|
|
4242
|
+
return endpoint;
|
|
4243
|
+
}
|
|
4244
|
+
async request(sandboxId, method, path2, body, signal, options = {}) {
|
|
4245
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
4246
|
+
const endpoint = await untilAborted(() => this.endpoint(sandboxId), signal);
|
|
4247
|
+
const url = new URL(`${endpoint.url}${path2}`);
|
|
4248
|
+
for (const [name, value] of Object.entries(endpoint.query)) url.searchParams.set(name, value);
|
|
4249
|
+
const timeout = options.stream ? void 0 : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
4250
|
+
const signals = [signal, timeout].filter((value) => value !== void 0);
|
|
4251
|
+
const response = await fetch(url, {
|
|
4252
|
+
method,
|
|
4253
|
+
headers: {
|
|
4254
|
+
...endpoint.headers,
|
|
4255
|
+
...body === void 0 ? {} : { "content-type": "application/json" },
|
|
4256
|
+
...options.stream ? { accept: "text/event-stream" } : {}
|
|
4257
|
+
},
|
|
4258
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
4259
|
+
...signals.length ? { signal: AbortSignal.any(signals) } : {}
|
|
4260
|
+
});
|
|
4261
|
+
if (response.status === 401 || response.status === 403) {
|
|
4262
|
+
await response.body?.cancel();
|
|
4263
|
+
this.endpoints.delete(sandboxId);
|
|
4264
|
+
if (attempt === 0) continue;
|
|
4265
|
+
throw new EndpointRejectedError(`Sandbox ${sandboxId} rejected its endpoint credentials (${response.status}).`);
|
|
4266
|
+
}
|
|
4267
|
+
return response;
|
|
4268
|
+
}
|
|
4269
|
+
}
|
|
4270
|
+
async prepareDaytonaSnapshot(sandbox, options) {
|
|
4271
|
+
const { Daytona, DaytonaNotFoundError } = await import("@daytona/sdk");
|
|
4272
|
+
const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
|
|
4273
|
+
const name = this.artifactName;
|
|
4274
|
+
const deadline = Date.now() + (this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS);
|
|
4275
|
+
const find = () => untilAborted(() => daytona.snapshot.get(name), options.signal).catch((error) => {
|
|
4276
|
+
if (error instanceof DaytonaNotFoundError) return void 0;
|
|
4277
|
+
throw error;
|
|
4278
|
+
});
|
|
4279
|
+
const isFailed = (found) => found.state === "error" || found.state === "build_failed";
|
|
4280
|
+
const isGoing = (found) => isFailed(found) || found.state === "removing";
|
|
4281
|
+
let snapshot = await find();
|
|
4282
|
+
let replaced;
|
|
4283
|
+
if (snapshot && snapshot.state !== "removing" && (isFailed(snapshot) || options.refresh)) {
|
|
4284
|
+
const old = snapshot;
|
|
4285
|
+
replaced = old;
|
|
4286
|
+
await untilAborted(() => daytona.snapshot.delete(old), options.signal).catch((error) => {
|
|
4287
|
+
if (!(error instanceof DaytonaNotFoundError)) throw error;
|
|
4288
|
+
});
|
|
4289
|
+
}
|
|
4290
|
+
while (snapshot && (isGoing(snapshot) || replaced !== void 0 && snapshot.id === replaced.id)) {
|
|
4291
|
+
await delay2(1e3, options.signal);
|
|
4292
|
+
snapshot = await find();
|
|
4293
|
+
}
|
|
4294
|
+
if (!snapshot) {
|
|
4295
|
+
try {
|
|
4296
|
+
snapshot = await untilAborted(() => daytona.snapshot.create(
|
|
4297
|
+
{
|
|
4298
|
+
name,
|
|
4299
|
+
image: this.image,
|
|
4300
|
+
entrypoint: this.command,
|
|
4301
|
+
...sandbox.resources ? { resources: sandbox.resources } : {}
|
|
4302
|
+
},
|
|
4303
|
+
{
|
|
4304
|
+
timeout: Math.ceil((deadline - Date.now()) / 1e3),
|
|
4305
|
+
...options.onLog ? { onLogs: options.onLog } : {}
|
|
4306
|
+
}
|
|
4307
|
+
), options.signal);
|
|
4308
|
+
} catch (error) {
|
|
4309
|
+
if (options.signal.aborted) throw error;
|
|
4310
|
+
snapshot = await find();
|
|
4311
|
+
if (!snapshot) throw error;
|
|
4312
|
+
}
|
|
4313
|
+
}
|
|
4314
|
+
while (true) {
|
|
4315
|
+
if (snapshot.state === "active") return;
|
|
4316
|
+
if (snapshot.state === "inactive") {
|
|
4317
|
+
const inactive = snapshot;
|
|
4318
|
+
snapshot = await untilAborted(() => daytona.snapshot.activate(inactive), options.signal);
|
|
4319
|
+
continue;
|
|
4320
|
+
}
|
|
4321
|
+
if (isFailed(snapshot)) {
|
|
4322
|
+
throw new DeploymentError(`Daytona snapshot ${name} is ${snapshot.state}: ${snapshot.errorReason ?? "no reason given"}`);
|
|
4323
|
+
}
|
|
4324
|
+
await delay2(2e3, options.signal);
|
|
4325
|
+
snapshot = await find() ?? snapshot;
|
|
4326
|
+
}
|
|
4327
|
+
}
|
|
4328
|
+
async prepareE2bTemplate(sandbox, { signal, refresh, onLog }) {
|
|
4329
|
+
const { Template } = await import("e2b");
|
|
4330
|
+
const name = this.artifactName;
|
|
4331
|
+
const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
|
|
4332
|
+
const connection = { ...apiKey ? { apiKey } : {}, signal };
|
|
4333
|
+
const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
|
|
4334
|
+
const waitingGraceMs = Math.min(6e4, timeoutMs / 4);
|
|
4335
|
+
const pollMs = Math.min(2e3, waitingGraceMs / 4);
|
|
4336
|
+
let waitingSince;
|
|
4337
|
+
while (!refresh) {
|
|
4338
|
+
const { templates } = await this.e2bTemplates(sandbox, signal);
|
|
4339
|
+
const status = templates.find((template2) => [...template2.names ?? [], ...template2.aliases ?? []].includes(name))?.buildStatus;
|
|
4340
|
+
if (status === "ready") return;
|
|
4341
|
+
if (status === "waiting") {
|
|
4342
|
+
waitingSince ??= Date.now();
|
|
4343
|
+
if (Date.now() - waitingSince > waitingGraceMs) break;
|
|
4344
|
+
} else if (status !== "building") {
|
|
4345
|
+
break;
|
|
4346
|
+
}
|
|
4347
|
+
await delay2(pollMs, signal);
|
|
4348
|
+
}
|
|
4349
|
+
const template = Template().fromImage(
|
|
4350
|
+
this.image,
|
|
4351
|
+
...sandbox.registry ? [sandbox.registry] : []
|
|
4352
|
+
);
|
|
4353
|
+
await Template.build(template, name, {
|
|
4354
|
+
...connection,
|
|
4355
|
+
...sandbox.cpuCount === void 0 ? {} : { cpuCount: sandbox.cpuCount },
|
|
4356
|
+
...sandbox.memoryMB === void 0 ? {} : { memoryMB: sandbox.memoryMB },
|
|
4357
|
+
...onLog ? { onBuildLogs: (entry) => onLog(entry.toString()) } : {}
|
|
4358
|
+
});
|
|
4359
|
+
}
|
|
4360
|
+
async listDaytonaSnapshots(sandbox, ownName) {
|
|
4361
|
+
const { Daytona } = await import("@daytona/sdk");
|
|
4362
|
+
const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
|
|
4363
|
+
const artifacts = [];
|
|
4364
|
+
for (let page = 1; ; page += 1) {
|
|
4365
|
+
const result = await daytona.snapshot.list({ page, limit: 100 });
|
|
4366
|
+
for (const snapshot of result.items) {
|
|
4367
|
+
if (!ownName.test(snapshot.name)) continue;
|
|
4368
|
+
artifacts.push({
|
|
4369
|
+
name: snapshot.name,
|
|
4370
|
+
createdAt: new Date(snapshot.createdAt).getTime(),
|
|
4371
|
+
delete: () => daytona.snapshot.delete(snapshot)
|
|
4372
|
+
});
|
|
4373
|
+
}
|
|
4374
|
+
if (page >= result.totalPages) return artifacts;
|
|
4375
|
+
}
|
|
4376
|
+
}
|
|
4377
|
+
async e2bTemplates(sandbox, signal) {
|
|
4378
|
+
const { ApiClient, ConnectionConfig } = await import("e2b");
|
|
4379
|
+
const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
|
|
4380
|
+
const client = new ApiClient(new ConnectionConfig(apiKey ? { apiKey } : {}));
|
|
4381
|
+
const { data, error } = await client.api.GET("/templates", signal ? { signal } : {});
|
|
4382
|
+
if (error || !data) throw new ExecutionError(`Listing E2B templates failed: ${JSON.stringify(error)}`);
|
|
4383
|
+
return { client, templates: data };
|
|
4384
|
+
}
|
|
4385
|
+
async listE2bTemplates(sandbox, ownName) {
|
|
4386
|
+
const { client, templates } = await this.e2bTemplates(sandbox);
|
|
4387
|
+
return templates.flatMap((template) => {
|
|
4388
|
+
const name = [...template.names ?? [], ...template.aliases ?? []].find((value) => ownName.test(value));
|
|
4389
|
+
if (!name) return [];
|
|
4390
|
+
return [{
|
|
4391
|
+
name,
|
|
4392
|
+
createdAt: new Date(template.createdAt).getTime(),
|
|
4393
|
+
delete: async () => {
|
|
4394
|
+
const result = await client.api.DELETE("/templates/{templateID}", {
|
|
4395
|
+
params: { path: { templateID: template.templateID } }
|
|
4396
|
+
});
|
|
4397
|
+
if (result.error) throw new ExecutionError(`Deleting E2B template ${name} failed: ${JSON.stringify(result.error)}`);
|
|
4398
|
+
}
|
|
4399
|
+
}];
|
|
4400
|
+
});
|
|
4401
|
+
}
|
|
4402
|
+
};
|
|
4403
|
+
|
|
4404
|
+
// src/braintrust.ts
|
|
4405
|
+
var API_KEY = "BRAINTRUST_API_KEY";
|
|
4406
|
+
var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
|
|
4407
|
+
var FLUSH_TIMEOUT_MS = 1e4;
|
|
4408
|
+
var BRAINTRUST_PACKAGE = "braintrust";
|
|
4409
|
+
var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
|
|
4410
|
+
var warn = (message) => console.warn(`neckbeard: ${message}`);
|
|
4411
|
+
var errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
4412
|
+
function readBraintrustSettings(env, where) {
|
|
4413
|
+
const apiKey = env[API_KEY]?.trim();
|
|
4414
|
+
const projectName = env[PROJECT_NAME]?.trim();
|
|
4415
|
+
if (apiKey && projectName) return { apiKey, projectName };
|
|
4416
|
+
if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
|
|
4417
|
+
return void 0;
|
|
4418
|
+
}
|
|
4419
|
+
async function startBraintrust({ apiKey, projectName }) {
|
|
4420
|
+
const notTracing = "Braintrust tracing is off in the sandbox";
|
|
4421
|
+
let sdk;
|
|
4422
|
+
try {
|
|
4423
|
+
sdk = await import(
|
|
4424
|
+
/* webpackIgnore: true */
|
|
4425
|
+
BRAINTRUST_PACKAGE
|
|
4426
|
+
);
|
|
4427
|
+
} catch (error) {
|
|
4428
|
+
if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
|
|
4429
|
+
warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
|
|
4430
|
+
} else {
|
|
4431
|
+
warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
|
|
4432
|
+
}
|
|
4433
|
+
return void 0;
|
|
4434
|
+
}
|
|
4435
|
+
if (typeof sdk.wrapPiCodingAgentSDK !== "function") {
|
|
4436
|
+
warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
|
|
4437
|
+
return void 0;
|
|
4438
|
+
}
|
|
4439
|
+
try {
|
|
4440
|
+
sdk.initLogger({ projectName, apiKey });
|
|
4441
|
+
} catch (error) {
|
|
4442
|
+
warn(`${notTracing}: ${errorText(error)}`);
|
|
4443
|
+
return void 0;
|
|
4444
|
+
}
|
|
4445
|
+
return {
|
|
4446
|
+
wrapPi: (pi) => sdk.wrapPiCodingAgentSDK(pi),
|
|
4447
|
+
async flush() {
|
|
4448
|
+
try {
|
|
4449
|
+
await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
|
|
4450
|
+
} catch (error) {
|
|
4451
|
+
warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
};
|
|
4455
|
+
}
|
|
4456
|
+
|
|
4457
|
+
// src/serve.ts
|
|
4458
|
+
var import_node_http = require("http");
|
|
4459
|
+
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
4460
|
+
var DEFAULT_ABORT_GRACE_MS = 1e4;
|
|
4461
|
+
var DEFAULT_PORT2 = 8080;
|
|
4462
|
+
function toPiJsonEvent(event) {
|
|
4463
|
+
if (!isRecord2(event) || event.type !== "message_update") return event;
|
|
4464
|
+
const { message, assistantMessageEvent } = event;
|
|
4465
|
+
if (!isRecord2(message) || message.role !== "assistant") {
|
|
4466
|
+
throw new Error("message_update message is not an assistant message");
|
|
4467
|
+
}
|
|
4468
|
+
if (!isRecord2(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
|
|
4469
|
+
throw new Error("message_update has no assistantMessageEvent");
|
|
4470
|
+
}
|
|
4471
|
+
const { partial, ...delta } = assistantMessageEvent;
|
|
4472
|
+
if (assistantMessageEvent.type === "toolcall_start") {
|
|
4473
|
+
const { contentIndex } = assistantMessageEvent;
|
|
4474
|
+
const content = isRecord2(partial) && Array.isArray(partial.content) ? partial.content : [];
|
|
4475
|
+
const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
|
|
4476
|
+
if (!isRecord2(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
|
|
4477
|
+
throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
|
|
4478
|
+
}
|
|
4479
|
+
return {
|
|
4480
|
+
type: "message_update",
|
|
4481
|
+
usage: message.usage,
|
|
4482
|
+
assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
|
|
4483
|
+
};
|
|
4484
|
+
}
|
|
4485
|
+
return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
|
|
4486
|
+
}
|
|
4487
|
+
var RequestError = class extends Error {
|
|
4488
|
+
constructor(status, message) {
|
|
4489
|
+
super(message);
|
|
4490
|
+
this.status = status;
|
|
4491
|
+
}
|
|
4492
|
+
};
|
|
4493
|
+
function sendJson(response, status, body) {
|
|
4494
|
+
response.writeHead(status, { "content-type": "application/json" });
|
|
4495
|
+
response.end(JSON.stringify(body));
|
|
4496
|
+
}
|
|
4497
|
+
async function readJsonBody(request) {
|
|
4498
|
+
const chunks = [];
|
|
4499
|
+
let size = 0;
|
|
4500
|
+
for await (const chunk of request) {
|
|
4501
|
+
size += chunk.byteLength;
|
|
4502
|
+
if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
|
|
4503
|
+
chunks.push(chunk);
|
|
4504
|
+
}
|
|
4505
|
+
try {
|
|
4506
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
4507
|
+
} catch {
|
|
4508
|
+
throw new RequestError(400, "Request body must be JSON.");
|
|
4509
|
+
}
|
|
4510
|
+
}
|
|
4511
|
+
function parseStartTurn(body) {
|
|
4512
|
+
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
4513
|
+
const { turnId, message, env } = body;
|
|
4514
|
+
if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
|
|
4515
|
+
throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
4516
|
+
}
|
|
4517
|
+
if (typeof message !== "string" || !message.trim()) {
|
|
4518
|
+
throw new RequestError(400, "message must be a non-empty string.");
|
|
4519
|
+
}
|
|
4520
|
+
if (env !== void 0 && (!env || typeof env !== "object" || Array.isArray(env) || Object.entries(env).some(([name, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || typeof value !== "string"))) {
|
|
4521
|
+
throw new RequestError(400, "env must map environment variable names to strings.");
|
|
4522
|
+
}
|
|
4523
|
+
return { turnId, message, ...env === void 0 ? {} : { env } };
|
|
4524
|
+
}
|
|
4525
|
+
async function serve(options) {
|
|
4526
|
+
const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
|
|
4527
|
+
let sessionPromise;
|
|
4528
|
+
let current;
|
|
4529
|
+
let previous;
|
|
4530
|
+
let currentSessionAbort;
|
|
4531
|
+
const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
|
|
4532
|
+
const append = (turn, record) => {
|
|
4533
|
+
const json = JSON.stringify({ seq: turn.records.length, ...record });
|
|
4534
|
+
turn.records.push(json);
|
|
4535
|
+
for (const wake of turn.waiters) wake();
|
|
4536
|
+
};
|
|
4537
|
+
const end = (turn, outcome, error) => {
|
|
4538
|
+
if (turn.ended) return;
|
|
4539
|
+
append(turn, { type: "end", outcome, ...error === void 0 ? {} : { error } });
|
|
4540
|
+
turn.ended = true;
|
|
4541
|
+
};
|
|
4542
|
+
const endAfterGrace = (turn, outcome, error) => {
|
|
4543
|
+
if (turn.ended || turn.finishing || turn.forceEnd) return;
|
|
4544
|
+
turn.forceEnd = setTimeout(() => end(turn, outcome, error), options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS);
|
|
4545
|
+
};
|
|
4546
|
+
const runTurn = async (turn, request) => {
|
|
4547
|
+
const previousEnv = /* @__PURE__ */ new Map();
|
|
4548
|
+
let unsubscribe;
|
|
4549
|
+
let timedOut = false;
|
|
4550
|
+
let session;
|
|
4551
|
+
const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
|
|
4552
|
+
const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
|
|
4553
|
+
timedOut = true;
|
|
4554
|
+
if (session) void session.abort().catch(() => void 0);
|
|
4555
|
+
endAfterGrace(turn, "failed", timeoutMessage);
|
|
4556
|
+
}, options.maxTurnDurationMs);
|
|
4557
|
+
const finish = async (outcome, error) => {
|
|
4558
|
+
turn.finishing = true;
|
|
4559
|
+
if (timer) clearTimeout(timer);
|
|
4560
|
+
clearTimeout(turn.forceEnd);
|
|
4561
|
+
try {
|
|
4562
|
+
await session?.afterTurn?.();
|
|
4563
|
+
} catch {
|
|
4564
|
+
}
|
|
4565
|
+
end(turn, outcome, error);
|
|
4566
|
+
};
|
|
4567
|
+
try {
|
|
4568
|
+
sessionPromise ??= options.createSession();
|
|
4569
|
+
try {
|
|
4570
|
+
session = await sessionPromise;
|
|
4571
|
+
} catch (error) {
|
|
4572
|
+
sessionPromise = void 0;
|
|
4573
|
+
throw error;
|
|
4574
|
+
}
|
|
4575
|
+
if (timedOut) {
|
|
4576
|
+
end(turn, "failed", timeoutMessage);
|
|
4577
|
+
return;
|
|
4578
|
+
}
|
|
4579
|
+
const started = session;
|
|
4580
|
+
for (const [name, value] of Object.entries(request.env ?? {})) {
|
|
4581
|
+
previousEnv.set(name, process.env[name]);
|
|
4582
|
+
process.env[name] = value;
|
|
4583
|
+
}
|
|
4584
|
+
unsubscribe = session.subscribe((event) => {
|
|
4585
|
+
if (turn.ended) return;
|
|
4586
|
+
try {
|
|
4587
|
+
append(turn, { type: "event", event: toWireEvent(event) });
|
|
4588
|
+
} catch (error) {
|
|
4589
|
+
end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
|
|
4590
|
+
void started.abort().catch(() => void 0);
|
|
4591
|
+
}
|
|
4592
|
+
});
|
|
4593
|
+
currentSessionAbort = () => started.abort();
|
|
4594
|
+
if (turn.abortRequested) {
|
|
4595
|
+
end(turn, "aborted");
|
|
4596
|
+
return;
|
|
4597
|
+
}
|
|
4598
|
+
await started.prompt(request.message);
|
|
4599
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
4600
|
+
else await finish(turn.abortRequested ? "aborted" : "completed");
|
|
4601
|
+
} catch (error) {
|
|
4602
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4603
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
4604
|
+
else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
|
|
4605
|
+
} finally {
|
|
4606
|
+
if (timer) clearTimeout(timer);
|
|
4607
|
+
clearTimeout(turn.forceEnd);
|
|
4608
|
+
unsubscribe?.();
|
|
4609
|
+
currentSessionAbort = void 0;
|
|
4610
|
+
for (const [name, value] of previousEnv) {
|
|
4611
|
+
if (value === void 0) delete process.env[name];
|
|
4612
|
+
else process.env[name] = value;
|
|
4613
|
+
}
|
|
4614
|
+
turn.settled = true;
|
|
4615
|
+
}
|
|
4616
|
+
};
|
|
4617
|
+
const busy = () => Boolean(current && !current.settled);
|
|
4618
|
+
const startTurn = async (request) => {
|
|
4619
|
+
const existing = findTurn(request.turnId);
|
|
4620
|
+
if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
|
|
4621
|
+
if (current && !current.settled) {
|
|
4622
|
+
return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
|
|
4623
|
+
}
|
|
4624
|
+
const turn = {
|
|
4625
|
+
id: request.turnId,
|
|
4626
|
+
records: [],
|
|
4627
|
+
ended: false,
|
|
4628
|
+
settled: false,
|
|
4629
|
+
abortRequested: false,
|
|
4630
|
+
finishing: false,
|
|
4631
|
+
waiters: /* @__PURE__ */ new Set()
|
|
4632
|
+
};
|
|
4633
|
+
previous = current;
|
|
4634
|
+
current = turn;
|
|
4635
|
+
void runTurn(turn, request);
|
|
4636
|
+
return { status: 202, body: { turnId: turn.id, ended: false } };
|
|
4637
|
+
};
|
|
4638
|
+
const streamTurn = async (turn, after, request, response) => {
|
|
4639
|
+
response.writeHead(200, {
|
|
4640
|
+
"content-type": "text/event-stream",
|
|
4641
|
+
"cache-control": "no-cache, no-transform",
|
|
4642
|
+
connection: "keep-alive",
|
|
4643
|
+
"x-accel-buffering": "no"
|
|
4644
|
+
});
|
|
4645
|
+
response.write(": connected\n\n");
|
|
4646
|
+
let closed = false;
|
|
4647
|
+
let wake;
|
|
4648
|
+
const onClose = () => {
|
|
4649
|
+
closed = true;
|
|
4650
|
+
wake?.();
|
|
4651
|
+
};
|
|
4652
|
+
request.on("close", onClose);
|
|
4653
|
+
response.on("close", onClose);
|
|
4654
|
+
const heartbeat = setInterval(() => {
|
|
4655
|
+
if (!closed) response.write(": ping\n\n");
|
|
4656
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
4657
|
+
let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
|
|
4658
|
+
try {
|
|
4659
|
+
while (!closed) {
|
|
4660
|
+
while (!closed && next < turn.records.length) {
|
|
4661
|
+
const ok = response.write(`id: ${next}
|
|
4662
|
+
data: ${turn.records[next]}
|
|
4663
|
+
|
|
4664
|
+
`);
|
|
4665
|
+
next += 1;
|
|
4666
|
+
if (!ok && !closed) {
|
|
4667
|
+
let onDrain;
|
|
4668
|
+
await new Promise((resolve2) => {
|
|
4669
|
+
wake = onDrain = resolve2;
|
|
4670
|
+
response.once("drain", resolve2);
|
|
4671
|
+
});
|
|
4672
|
+
if (onDrain) response.off("drain", onDrain);
|
|
4673
|
+
wake = void 0;
|
|
4674
|
+
}
|
|
4675
|
+
}
|
|
4676
|
+
if (closed || turn.ended && next >= turn.records.length) break;
|
|
4677
|
+
await new Promise((resolve2) => {
|
|
4678
|
+
wake = resolve2;
|
|
4679
|
+
turn.waiters.add(resolve2);
|
|
4680
|
+
});
|
|
4681
|
+
if (wake) turn.waiters.delete(wake);
|
|
4682
|
+
wake = void 0;
|
|
4683
|
+
}
|
|
4684
|
+
} finally {
|
|
4685
|
+
clearInterval(heartbeat);
|
|
4686
|
+
request.off("close", onClose);
|
|
4687
|
+
response.off("close", onClose);
|
|
4688
|
+
if (!closed) response.end();
|
|
4689
|
+
}
|
|
4690
|
+
};
|
|
4691
|
+
const server = (0, import_node_http.createServer)((request, response) => {
|
|
4692
|
+
void (async () => {
|
|
4693
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
4694
|
+
const turnPath = /^\/turns\/([^/]+)\/(events|abort)$/u.exec(url.pathname);
|
|
4695
|
+
if (request.method === "GET" && url.pathname === "/health") {
|
|
4696
|
+
const health = {
|
|
4697
|
+
ok: true,
|
|
4698
|
+
protocolVersion: TURN_PROTOCOL_VERSION,
|
|
4699
|
+
busy: busy(),
|
|
4700
|
+
turnId: current?.id ?? null
|
|
4701
|
+
};
|
|
4702
|
+
return sendJson(response, 200, health);
|
|
4703
|
+
}
|
|
4704
|
+
if (request.method === "POST" && url.pathname === "/turns") {
|
|
4705
|
+
const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
|
|
4706
|
+
return sendJson(response, status, body);
|
|
4707
|
+
}
|
|
4708
|
+
if (turnPath) {
|
|
4709
|
+
const turn = findTurn(decodeURIComponent(turnPath[1]));
|
|
4710
|
+
if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
|
|
4711
|
+
if (request.method === "GET" && turnPath[2] === "events") {
|
|
4712
|
+
const afterParam = url.searchParams.get("after");
|
|
4713
|
+
const after = afterParam === null ? -1 : Number(afterParam);
|
|
4714
|
+
if (!Number.isSafeInteger(after) || after < -1) {
|
|
4715
|
+
return sendJson(response, 400, { error: "after must be an integer of at least -1." });
|
|
4716
|
+
}
|
|
4717
|
+
return streamTurn(turn, after, request, response);
|
|
4718
|
+
}
|
|
4719
|
+
if (request.method === "POST" && turnPath[2] === "abort") {
|
|
4720
|
+
if (!turn.ended && !turn.finishing && !turn.abortRequested) {
|
|
4721
|
+
turn.abortRequested = true;
|
|
4722
|
+
if (turn === current) void currentSessionAbort?.().catch(() => void 0);
|
|
4723
|
+
endAfterGrace(turn, "aborted");
|
|
4724
|
+
}
|
|
4725
|
+
return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
|
|
4726
|
+
}
|
|
4727
|
+
}
|
|
4728
|
+
sendJson(response, 404, { error: "Not found." });
|
|
4729
|
+
})().catch((error) => {
|
|
4730
|
+
if (response.headersSent) {
|
|
4731
|
+
response.destroy();
|
|
4732
|
+
return;
|
|
4733
|
+
}
|
|
4734
|
+
const status = error instanceof RequestError ? error.status : 500;
|
|
4735
|
+
sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
|
|
4736
|
+
});
|
|
4737
|
+
});
|
|
4738
|
+
const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT2);
|
|
4739
|
+
await new Promise((resolve2, reject) => {
|
|
4740
|
+
server.once("error", reject);
|
|
4741
|
+
server.listen(port, options.host ?? "0.0.0.0", () => {
|
|
4742
|
+
server.off("error", reject);
|
|
4743
|
+
resolve2();
|
|
4744
|
+
});
|
|
4745
|
+
});
|
|
4746
|
+
return {
|
|
4747
|
+
port: server.address().port,
|
|
4748
|
+
close: () => new Promise((resolve2, reject) => {
|
|
4749
|
+
server.closeAllConnections();
|
|
4750
|
+
server.close((error) => error ? reject(error) : resolve2());
|
|
4751
|
+
})
|
|
4752
|
+
};
|
|
4753
|
+
}
|
|
4754
|
+
|
|
4755
|
+
// src/define.ts
|
|
4756
|
+
var SKILLS_DIR = "/app/.agents/skills";
|
|
4757
|
+
var IMAGE_TAG_ENV_VARS = [
|
|
4758
|
+
"NECKBEARD_IMAGE_TAG",
|
|
4759
|
+
"GITHUB_SHA",
|
|
4760
|
+
"CI_COMMIT_SHA",
|
|
4761
|
+
"BITBUCKET_COMMIT",
|
|
4762
|
+
"CODEBUILD_RESOLVED_SOURCE_VERSION",
|
|
4763
|
+
"BUILDKITE_COMMIT",
|
|
4764
|
+
"CIRCLE_SHA1",
|
|
4765
|
+
"CF_PAGES_COMMIT_SHA",
|
|
4766
|
+
"HEROKU_BUILD_COMMIT",
|
|
4767
|
+
"HEROKU_SLUG_COMMIT",
|
|
4768
|
+
"RAILWAY_GIT_COMMIT_SHA",
|
|
4769
|
+
"RENDER_GIT_COMMIT",
|
|
4770
|
+
"VERCEL_GIT_COMMIT_SHA",
|
|
4771
|
+
"SOURCE_VERSION",
|
|
4772
|
+
"GIT_COMMIT"
|
|
4773
|
+
];
|
|
4774
|
+
function resolveImageTag(env = process.env) {
|
|
4775
|
+
for (const name of IMAGE_TAG_ENV_VARS) {
|
|
4776
|
+
const value = env[name]?.trim();
|
|
4777
|
+
if (value && value !== name) return value;
|
|
4778
|
+
}
|
|
4779
|
+
return void 0;
|
|
4780
|
+
}
|
|
4781
|
+
var PI_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
4782
|
+
var definedAgentMarker = /* @__PURE__ */ Symbol.for("agent-neckbeard.DefinedAgent");
|
|
4783
|
+
var DefinedAgent = class {
|
|
4784
|
+
constructor(definition) {
|
|
4785
|
+
this.definition = definition;
|
|
4786
|
+
if (!definition || typeof definition !== "object") throw new ConfigurationError("Agent definition must be an object.");
|
|
4787
|
+
if (typeof definition.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(definition.name)) {
|
|
4788
|
+
throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
|
|
4789
|
+
}
|
|
4790
|
+
if (Boolean(definition.pi) === Boolean(definition.createSession)) {
|
|
4791
|
+
throw new ConfigurationError(`Agent ${definition.name} needs exactly one of pi and createSession.`);
|
|
4792
|
+
}
|
|
4793
|
+
if (!definition.image && !definition.registry) {
|
|
4794
|
+
throw new ConfigurationError(`Agent ${definition.name} needs a registry or an image.`);
|
|
4795
|
+
}
|
|
4796
|
+
}
|
|
4797
|
+
[definedAgentMarker] = true;
|
|
4798
|
+
client;
|
|
4799
|
+
braintrustChecked = false;
|
|
4800
|
+
get name() {
|
|
4801
|
+
return this.definition.name;
|
|
4802
|
+
}
|
|
4803
|
+
/** The image this host runs: `image`, else `<registry>/<name>:<tag>` with the tag `resolveImageTag()` finds. */
|
|
4804
|
+
imageRef(tag = resolveImageTag()) {
|
|
4805
|
+
const { image, registry, name } = this.definition;
|
|
4806
|
+
if (image) return image;
|
|
4807
|
+
if (!tag) {
|
|
4808
|
+
throw new ConfigurationError(
|
|
4809
|
+
`Set NECKBEARD_IMAGE_TAG to choose agent ${name}'s image, or deploy from a platform that names the commit, such as RENDER_GIT_COMMIT.`
|
|
4810
|
+
);
|
|
4811
|
+
}
|
|
4812
|
+
return `${registry.replace(/\/+$/u, "")}/${name}:${tag}`;
|
|
4813
|
+
}
|
|
4814
|
+
/** The `Agent` for an image, by default the one this host runs. */
|
|
4815
|
+
forImage(image = this.imageRef()) {
|
|
4816
|
+
const { definition } = this;
|
|
4817
|
+
const sandbox = typeof definition.sandbox === "function" ? definition.sandbox() : definition.sandbox;
|
|
4818
|
+
const envs = typeof definition.envs === "function" ? definition.envs() : definition.envs;
|
|
4819
|
+
return new Agent({
|
|
4820
|
+
name: definition.name,
|
|
4821
|
+
image,
|
|
4822
|
+
sandbox,
|
|
4823
|
+
...envs ? { envs } : {},
|
|
4824
|
+
...definition.command ? { command: definition.command } : {},
|
|
4825
|
+
...definition.port === void 0 ? {} : { port: definition.port },
|
|
4826
|
+
...definition.startTimeoutMs === void 0 ? {} : { startTimeoutMs: definition.startTimeoutMs },
|
|
4827
|
+
...definition.prepareTimeoutMs === void 0 ? {} : { prepareTimeoutMs: definition.prepareTimeoutMs }
|
|
4828
|
+
});
|
|
4829
|
+
}
|
|
4830
|
+
get agent() {
|
|
4831
|
+
this.client ??= this.forImage();
|
|
4832
|
+
return this.client;
|
|
4833
|
+
}
|
|
4834
|
+
get artifactName() {
|
|
4835
|
+
return this.agent.artifactName;
|
|
4836
|
+
}
|
|
4837
|
+
prepare(options) {
|
|
4838
|
+
return this.agent.prepare(options);
|
|
4839
|
+
}
|
|
4840
|
+
start(options) {
|
|
4841
|
+
if (this.definition.pi && !this.braintrustChecked) {
|
|
4842
|
+
this.braintrustChecked = true;
|
|
4843
|
+
const envs = typeof this.definition.envs === "function" ? this.definition.envs() : this.definition.envs;
|
|
4844
|
+
readBraintrustSettings({ ...filterDefined(envs), ...filterDefined(options?.envs) }, `for agent ${this.name}'s sandboxes`);
|
|
4845
|
+
}
|
|
4846
|
+
return this.agent.start(options);
|
|
4847
|
+
}
|
|
4848
|
+
prompt(sandboxId, turn, options) {
|
|
4849
|
+
return this.agent.prompt(sandboxId, turn, options);
|
|
4850
|
+
}
|
|
4851
|
+
run(sandboxId, turn, options) {
|
|
4852
|
+
return this.agent.run(sandboxId, turn, options);
|
|
4853
|
+
}
|
|
4854
|
+
events(sandboxId, turnId, options) {
|
|
4855
|
+
return this.agent.events(sandboxId, turnId, options);
|
|
4856
|
+
}
|
|
4857
|
+
abort(sandboxId, turnId, signal) {
|
|
4858
|
+
return this.agent.abort(sandboxId, turnId, signal);
|
|
4859
|
+
}
|
|
4860
|
+
health(sandboxId, signal) {
|
|
4861
|
+
return this.agent.health(sandboxId, signal);
|
|
4862
|
+
}
|
|
4863
|
+
waitForIdle(sandboxId, options) {
|
|
4864
|
+
return this.agent.waitForIdle(sandboxId, options);
|
|
4865
|
+
}
|
|
4866
|
+
kill(sandboxId) {
|
|
4867
|
+
return this.agent.kill(sandboxId);
|
|
4868
|
+
}
|
|
4869
|
+
sandbox(sandboxId) {
|
|
4870
|
+
return this.agent.sandbox(sandboxId);
|
|
4871
|
+
}
|
|
4872
|
+
gc(options) {
|
|
4873
|
+
return this.agent.gc(options);
|
|
4874
|
+
}
|
|
4875
|
+
/** Where a persisted session's file is in a sandbox whose home is `homeDir`, as for copying it out and back. */
|
|
4876
|
+
sessionFilePath(homeDir, sessionId) {
|
|
4877
|
+
return import_node_path.default.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.jsonl`);
|
|
4878
|
+
}
|
|
4879
|
+
/** Serves the agent's session; the image's entry point, which `neckbeard build` generates, calls it. */
|
|
4880
|
+
serve(options = {}) {
|
|
4881
|
+
const { definition } = this;
|
|
4882
|
+
const { pi } = definition;
|
|
4883
|
+
return serve({
|
|
4884
|
+
createSession: pi ? () => createPiSession(pi) : definition.createSession,
|
|
4885
|
+
...definition.maxTurnDurationMs === void 0 ? {} : { maxTurnDurationMs: definition.maxTurnDurationMs },
|
|
4886
|
+
...definition.abortGraceMs === void 0 ? {} : { abortGraceMs: definition.abortGraceMs },
|
|
4887
|
+
...options
|
|
4888
|
+
});
|
|
4889
|
+
}
|
|
4890
|
+
};
|
|
4891
|
+
function defineAgent(definition) {
|
|
4892
|
+
return new DefinedAgent(definition);
|
|
4893
|
+
}
|
|
4894
|
+
function isDefinedAgent(value) {
|
|
4895
|
+
return typeof value === "object" && value !== null && definedAgentMarker in value;
|
|
4896
|
+
}
|
|
4897
|
+
async function createPiSession(config) {
|
|
4898
|
+
const home = import_node_os.default.homedir();
|
|
4899
|
+
const cwd = import_node_path.default.resolve(home, config.cwd ?? "workspace");
|
|
4900
|
+
await (0, import_promises.mkdir)(cwd, { recursive: true });
|
|
4901
|
+
process.env.NECKBEARD_CWD = cwd;
|
|
4902
|
+
const agentDir = import_node_path.default.join(home, "agent", ".pi");
|
|
4903
|
+
const loaded = await import(
|
|
4904
|
+
/* webpackIgnore: true */
|
|
4905
|
+
PI_PACKAGE
|
|
4906
|
+
);
|
|
4907
|
+
const braintrustSettings = readBraintrustSettings(process.env, "in the sandbox");
|
|
4908
|
+
const braintrust = braintrustSettings && await startBraintrust(braintrustSettings);
|
|
4909
|
+
const pi = braintrust ? braintrust.wrapPi(loaded) : loaded;
|
|
4910
|
+
const modelRuntime = await pi.ModelRuntime.create({ modelsPath: null });
|
|
4911
|
+
const separator = config.model.indexOf("/");
|
|
4912
|
+
const model = separator > 0 ? modelRuntime.getModel(config.model.slice(0, separator), config.model.slice(separator + 1)) : void 0;
|
|
4913
|
+
if (!model) throw new ConfigurationError(`Pi has no model ${config.model}; name it as provider/model.`);
|
|
4914
|
+
const settingsManager = pi.SettingsManager.inMemory();
|
|
4915
|
+
const resourceLoader = new pi.DefaultResourceLoader({
|
|
4916
|
+
cwd,
|
|
4917
|
+
agentDir,
|
|
4918
|
+
settingsManager,
|
|
4919
|
+
additionalSkillPaths: [SKILLS_DIR],
|
|
4920
|
+
noSkills: true,
|
|
4921
|
+
noExtensions: true,
|
|
4922
|
+
noPromptTemplates: true,
|
|
4923
|
+
noContextFiles: true,
|
|
4924
|
+
systemPrompt: config.systemPrompt
|
|
4925
|
+
});
|
|
4926
|
+
await resourceLoader.reload();
|
|
4927
|
+
let sessionManager;
|
|
4928
|
+
if (config.persist) {
|
|
4929
|
+
const sessionId = process.env.NECKBEARD_SESSION_ID;
|
|
4930
|
+
if (!sessionId) throw new ConfigurationError("A persisted Pi session needs the sessionId passed to start().");
|
|
4931
|
+
const sessionFile = import_node_path.default.join(agentDir, "sessions", `${sessionId}.jsonl`);
|
|
4932
|
+
sessionManager = pi.SessionManager.open(sessionFile, import_node_path.default.dirname(sessionFile), cwd);
|
|
4933
|
+
} else {
|
|
4934
|
+
sessionManager = pi.SessionManager.inMemory(cwd);
|
|
4935
|
+
}
|
|
4936
|
+
const { session } = await pi.createAgentSession({
|
|
4937
|
+
cwd,
|
|
4938
|
+
agentDir,
|
|
4939
|
+
model,
|
|
4940
|
+
modelRuntime,
|
|
4941
|
+
resourceLoader,
|
|
4942
|
+
settingsManager,
|
|
4943
|
+
sessionManager,
|
|
4944
|
+
...config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {},
|
|
4945
|
+
...config.tools ? { tools: config.tools } : {}
|
|
4946
|
+
});
|
|
4947
|
+
if (!braintrust) return session;
|
|
4948
|
+
return {
|
|
4949
|
+
subscribe: (listener) => session.subscribe(listener),
|
|
4950
|
+
prompt: (text) => session.prompt(text),
|
|
4951
|
+
abort: () => session.abort(),
|
|
4952
|
+
afterTurn: () => braintrust.flush()
|
|
4953
|
+
};
|
|
4954
|
+
}
|
|
4955
|
+
|
|
3710
4956
|
// src/providers/docker.ts
|
|
3711
4957
|
var import_node_child_process = require("child_process");
|
|
3712
4958
|
var import_node_net = require("net");
|
|
@@ -3949,18 +5195,18 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
|
|
|
3949
5195
|
}
|
|
3950
5196
|
return result;
|
|
3951
5197
|
}
|
|
3952
|
-
async makeDir(
|
|
3953
|
-
await this.control("Docker directory creation", 'mkdir -p -- "$1"', [
|
|
5198
|
+
async makeDir(path2) {
|
|
5199
|
+
await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path2]);
|
|
3954
5200
|
}
|
|
3955
|
-
async writeFile(
|
|
5201
|
+
async writeFile(path2, content) {
|
|
3956
5202
|
const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
|
|
3957
|
-
await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [
|
|
5203
|
+
await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input, DOCKER_FILE_TIMEOUT_MS);
|
|
3958
5204
|
}
|
|
3959
|
-
async readFile(
|
|
3960
|
-
return (await this.control("Docker file read", 'cat -- "$1"', [
|
|
5205
|
+
async readFile(path2) {
|
|
5206
|
+
return (await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
|
|
3961
5207
|
}
|
|
3962
|
-
async readFileBytes(
|
|
3963
|
-
return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [
|
|
5208
|
+
async readFileBytes(path2) {
|
|
5209
|
+
return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
|
|
3964
5210
|
}
|
|
3965
5211
|
async runCommand(command, options) {
|
|
3966
5212
|
validateProviderCommand("Docker", command, options);
|
|
@@ -4009,8 +5255,8 @@ exec timeout --kill-after=1 ${deadlineSeconds} /bin/bash --noprofile --norc -c $
|
|
|
4009
5255
|
};
|
|
4010
5256
|
|
|
4011
5257
|
// src/index.ts
|
|
4012
|
-
function readPackageJson(
|
|
4013
|
-
return JSON.parse((0, import_node_fs.readFileSync)(
|
|
5258
|
+
function readPackageJson(path2) {
|
|
5259
|
+
return JSON.parse((0, import_node_fs.readFileSync)(path2, "utf8"));
|
|
4014
5260
|
}
|
|
4015
5261
|
var getEsbuild = () => import("esbuild");
|
|
4016
5262
|
var getE2b = () => import("e2b");
|
|
@@ -4040,9 +5286,11 @@ var NeckbeardError = class extends Error {
|
|
|
4040
5286
|
}
|
|
4041
5287
|
};
|
|
4042
5288
|
var DeploymentError = class extends NeckbeardError {
|
|
4043
|
-
|
|
5289
|
+
/** A sandbox the failure left behind, for `kill()`. */
|
|
5290
|
+
constructor(message, cause, sandboxId) {
|
|
4044
5291
|
super(message);
|
|
4045
5292
|
this.cause = cause;
|
|
5293
|
+
this.sandboxId = sandboxId;
|
|
4046
5294
|
this.name = "DeploymentError";
|
|
4047
5295
|
}
|
|
4048
5296
|
};
|
|
@@ -4066,6 +5314,12 @@ var RuntimeBusyError = class extends ExecutionError {
|
|
|
4066
5314
|
this.name = "RuntimeBusyError";
|
|
4067
5315
|
}
|
|
4068
5316
|
};
|
|
5317
|
+
var TurnLostError = class extends ExecutionError {
|
|
5318
|
+
constructor(message) {
|
|
5319
|
+
super(message);
|
|
5320
|
+
this.name = "TurnLostError";
|
|
5321
|
+
}
|
|
5322
|
+
};
|
|
4069
5323
|
var ConfigurationError = class extends NeckbeardError {
|
|
4070
5324
|
constructor(message) {
|
|
4071
5325
|
super(message);
|
|
@@ -4079,7 +5333,7 @@ function resolveAgentSourceFile(candidates, options = {}) {
|
|
|
4079
5333
|
return sourceFile;
|
|
4080
5334
|
}
|
|
4081
5335
|
if (process.env[NECKBEARD_SANDBOX_RUNTIME_ENV] === "1") {
|
|
4082
|
-
const sandboxSourceFile = options.sandboxSourceFile ?? (0,
|
|
5336
|
+
const sandboxSourceFile = options.sandboxSourceFile ?? (0, import_node_path2.resolve)(process.cwd(), "agent.mjs");
|
|
4083
5337
|
if ((0, import_node_fs.existsSync)(sandboxSourceFile)) {
|
|
4084
5338
|
return sandboxSourceFile;
|
|
4085
5339
|
}
|
|
@@ -4201,7 +5455,7 @@ function appendIncludesToTraceAssets({
|
|
|
4201
5455
|
if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
|
|
4202
5456
|
continue;
|
|
4203
5457
|
}
|
|
4204
|
-
const traceDir = (0,
|
|
5458
|
+
const traceDir = (0, import_node_path2.dirname)((0, import_node_path2.join)(outputPath, assetName));
|
|
4205
5459
|
const nextSource = traceWithIncludedFiles(String(asset.source()), traceDir, includedFiles);
|
|
4206
5460
|
if (rawSource && updateAsset) {
|
|
4207
5461
|
updateAsset(assetName, new rawSource(nextSource));
|
|
@@ -4273,7 +5527,7 @@ function appendIncludesToTraceFiles(outputPath, appDir, sourceFiles, routeGlobs,
|
|
|
4273
5527
|
function appendFilesToTrace(traceFile, includedFiles) {
|
|
4274
5528
|
const nextSource = traceWithIncludedFiles(
|
|
4275
5529
|
(0, import_node_fs.readFileSync)(traceFile, "utf8"),
|
|
4276
|
-
(0,
|
|
5530
|
+
(0, import_node_path2.dirname)(traceFile),
|
|
4277
5531
|
includedFiles
|
|
4278
5532
|
);
|
|
4279
5533
|
(0, import_node_fs.writeFileSync)(traceFile, nextSource);
|
|
@@ -4283,7 +5537,7 @@ function traceWithIncludedFiles(traceSource, traceDir, includedFiles) {
|
|
|
4283
5537
|
const files = Array.isArray(trace.files) ? trace.files.filter((file) => typeof file === "string") : [];
|
|
4284
5538
|
const nextFiles = new Set(files);
|
|
4285
5539
|
for (const includedFile of includedFiles) {
|
|
4286
|
-
nextFiles.add((0,
|
|
5540
|
+
nextFiles.add((0, import_node_path2.relative)(traceDir, includedFile).replace(/\\/g, "/"));
|
|
4287
5541
|
}
|
|
4288
5542
|
return JSON.stringify({
|
|
4289
5543
|
version: trace.version ?? 1,
|
|
@@ -4309,7 +5563,7 @@ function traceIncludeFilesForConfig(appDir, sourceFiles, traceSourceDependencies
|
|
|
4309
5563
|
return mergeStringArray(sourceFiles, tracedFiles);
|
|
4310
5564
|
}
|
|
4311
5565
|
function toNextTraceIncludePath(appDir, file) {
|
|
4312
|
-
const relativePath = (0,
|
|
5566
|
+
const relativePath = (0, import_node_path2.relative)(appDir, file).replace(/\\/g, "/");
|
|
4313
5567
|
if (relativePath.startsWith("..")) {
|
|
4314
5568
|
return relativePath;
|
|
4315
5569
|
}
|
|
@@ -4318,14 +5572,14 @@ function toNextTraceIncludePath(appDir, file) {
|
|
|
4318
5572
|
function expandTraceIncludePattern(appDir, sourceFile) {
|
|
4319
5573
|
const normalized = sourceFile.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
4320
5574
|
if (normalized.endsWith("/**/*")) {
|
|
4321
|
-
const dir = (0,
|
|
5575
|
+
const dir = (0, import_node_path2.resolve)(appDir, normalized.slice(0, -5));
|
|
4322
5576
|
return findFiles(dir);
|
|
4323
5577
|
}
|
|
4324
5578
|
if (normalized.endsWith("/*")) {
|
|
4325
|
-
const dir = (0,
|
|
5579
|
+
const dir = (0, import_node_path2.resolve)(appDir, normalized.slice(0, -2));
|
|
4326
5580
|
return directFiles(dir);
|
|
4327
5581
|
}
|
|
4328
|
-
const file = (0,
|
|
5582
|
+
const file = (0, import_node_path2.resolve)(appDir, normalized);
|
|
4329
5583
|
return (0, import_node_fs.existsSync)(file) && (0, import_node_fs.statSync)(file).isFile() ? [file] : [];
|
|
4330
5584
|
}
|
|
4331
5585
|
function traceSourceDependencyFiles(appDir, sourceFiles) {
|
|
@@ -4371,12 +5625,12 @@ function traceSourceDependencyFiles(appDir, sourceFiles) {
|
|
|
4371
5625
|
continue;
|
|
4372
5626
|
}
|
|
4373
5627
|
const resolvedImportPath = importRecord.external ? void 0 : resolveMetafileInput(appDir, importRecord.path);
|
|
4374
|
-
const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, (0,
|
|
5628
|
+
const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, (0, import_node_path2.dirname)(absoluteInput));
|
|
4375
5629
|
if (!packageInfo) {
|
|
4376
5630
|
continue;
|
|
4377
5631
|
}
|
|
4378
5632
|
addFile(packageInfo.resolvedPath);
|
|
4379
|
-
addFile((0,
|
|
5633
|
+
addFile((0, import_node_path2.join)(packageInfo.root, "package.json"));
|
|
4380
5634
|
}
|
|
4381
5635
|
}
|
|
4382
5636
|
return [...files];
|
|
@@ -4390,7 +5644,7 @@ function getEsbuildSync() {
|
|
|
4390
5644
|
return packageRequire("esbuild");
|
|
4391
5645
|
}
|
|
4392
5646
|
function resolveMetafileInput(absWorkingDir, inputPath) {
|
|
4393
|
-
return (0,
|
|
5647
|
+
return (0, import_node_path2.resolve)(absWorkingDir, inputPath);
|
|
4394
5648
|
}
|
|
4395
5649
|
function findTraceFiles(root) {
|
|
4396
5650
|
return findFiles(root).filter((file) => file.endsWith(".nft.json"));
|
|
@@ -4408,7 +5662,7 @@ function findFiles(root) {
|
|
|
4408
5662
|
}
|
|
4409
5663
|
const files = [];
|
|
4410
5664
|
for (const entry of (0, import_node_fs.readdirSync)(root)) {
|
|
4411
|
-
files.push(...findFiles((0,
|
|
5665
|
+
files.push(...findFiles((0, import_node_path2.join)(root, entry)));
|
|
4412
5666
|
}
|
|
4413
5667
|
return files;
|
|
4414
5668
|
}
|
|
@@ -4416,10 +5670,10 @@ function directFiles(root) {
|
|
|
4416
5670
|
if (!(0, import_node_fs.existsSync)(root) || !(0, import_node_fs.statSync)(root).isDirectory()) {
|
|
4417
5671
|
return [];
|
|
4418
5672
|
}
|
|
4419
|
-
return (0, import_node_fs.readdirSync)(root).map((entry) => (0,
|
|
5673
|
+
return (0, import_node_fs.readdirSync)(root).map((entry) => (0, import_node_path2.join)(root, entry)).filter((file) => (0, import_node_fs.statSync)(file).isFile());
|
|
4420
5674
|
}
|
|
4421
5675
|
function routePathFromTraceFile(outputPath, traceFile) {
|
|
4422
|
-
const relativeTrace = (0,
|
|
5676
|
+
const relativeTrace = (0, import_node_path2.relative)(outputPath, traceFile).replace(/\\/g, "/");
|
|
4423
5677
|
return routePathFromRelativeTrace(outputPath, relativeTrace);
|
|
4424
5678
|
}
|
|
4425
5679
|
function routePathFromTraceAsset(outputPath, assetName) {
|
|
@@ -4439,7 +5693,7 @@ function routePathFromRelativeTrace(outputPath, relativeTrace) {
|
|
|
4439
5693
|
if (normalizedTrace.startsWith("pages/")) {
|
|
4440
5694
|
return normalizeTraceRoute(normalizedTrace.slice("pages/".length));
|
|
4441
5695
|
}
|
|
4442
|
-
if ((0,
|
|
5696
|
+
if ((0, import_node_path2.basename)(outputPath) === "app" || (0, import_node_path2.basename)(outputPath) === "pages") {
|
|
4443
5697
|
return normalizeTraceRoute(relativeTrace);
|
|
4444
5698
|
}
|
|
4445
5699
|
return void 0;
|
|
@@ -4549,7 +5803,7 @@ function normalizeLocalDirectoryDestination(destination, name) {
|
|
|
4549
5803
|
throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
|
|
4550
5804
|
}
|
|
4551
5805
|
const sandboxPath = destination.replace(/\\/g, "/");
|
|
4552
|
-
if ((0,
|
|
5806
|
+
if ((0, import_node_path2.isAbsolute)(destination) || import_node_path2.posix.isAbsolute(sandboxPath) || import_node_path2.win32.isAbsolute(destination)) {
|
|
4553
5807
|
throw new ConfigurationError(
|
|
4554
5808
|
`${name}.destination must be relative to the sandbox agent directory.`
|
|
4555
5809
|
);
|
|
@@ -4559,7 +5813,7 @@ function normalizeLocalDirectoryDestination(destination, name) {
|
|
|
4559
5813
|
`${name}.destination must not traverse outside the sandbox agent directory.`
|
|
4560
5814
|
);
|
|
4561
5815
|
}
|
|
4562
|
-
const normalized =
|
|
5816
|
+
const normalized = import_node_path2.posix.normalize(sandboxPath);
|
|
4563
5817
|
if (normalized === ".") {
|
|
4564
5818
|
throw new ConfigurationError(`${name}.destination must not be ".".`);
|
|
4565
5819
|
}
|
|
@@ -4758,10 +6012,10 @@ function requireEnv(name) {
|
|
|
4758
6012
|
}
|
|
4759
6013
|
return value;
|
|
4760
6014
|
}
|
|
4761
|
-
var require2 = (0, import_node_module2.createRequire)((0,
|
|
6015
|
+
var require2 = (0, import_node_module2.createRequire)((0, import_node_path2.join)(process.cwd(), "__agent_neckbeard__.cjs"));
|
|
4762
6016
|
var packageRequire = createPackageRequire();
|
|
4763
6017
|
function createPackageRequire() {
|
|
4764
|
-
const cwdPackageJsonPath = (0,
|
|
6018
|
+
const cwdPackageJsonPath = (0, import_node_path2.join)(process.cwd(), "package.json");
|
|
4765
6019
|
try {
|
|
4766
6020
|
if ((0, import_node_fs.existsSync)(cwdPackageJsonPath) && readPackageJson(cwdPackageJsonPath).name === NECKBEARD_PACKAGE_NAME) {
|
|
4767
6021
|
return (0, import_node_module2.createRequire)(cwdPackageJsonPath);
|
|
@@ -4774,12 +6028,12 @@ function createPackageRequire() {
|
|
|
4774
6028
|
return require2;
|
|
4775
6029
|
}
|
|
4776
6030
|
}
|
|
4777
|
-
function isBareModuleImport(
|
|
6031
|
+
function isBareModuleImport(path2) {
|
|
4778
6032
|
const excludes = [".", "/", "~", "file:", "data:"];
|
|
4779
|
-
return !excludes.some((exclude) =>
|
|
6033
|
+
return !excludes.some((exclude) => path2.startsWith(exclude));
|
|
4780
6034
|
}
|
|
4781
|
-
function isBuiltinModule(
|
|
4782
|
-
return import_node_module2.builtinModules.includes(
|
|
6035
|
+
function isBuiltinModule(path2) {
|
|
6036
|
+
return import_node_module2.builtinModules.includes(path2.replace("node:", ""));
|
|
4783
6037
|
}
|
|
4784
6038
|
function packageNameForImportPath(importPath) {
|
|
4785
6039
|
if (importPath.startsWith("@")) {
|
|
@@ -4801,10 +6055,10 @@ function resolvePackageInfoSync(importPath, resolveDir) {
|
|
|
4801
6055
|
try {
|
|
4802
6056
|
const resolvedPath = require2.resolve(importPath, { paths: [resolveDir] });
|
|
4803
6057
|
const packageName = packageNameForImportPath(importPath);
|
|
4804
|
-
let root = (0,
|
|
6058
|
+
let root = (0, import_node_path2.dirname)(resolvedPath);
|
|
4805
6059
|
let packageJsonPath = null;
|
|
4806
6060
|
while (true) {
|
|
4807
|
-
const candidate = (0,
|
|
6061
|
+
const candidate = (0, import_node_path2.join)(root, "package.json");
|
|
4808
6062
|
if ((0, import_node_fs.existsSync)(candidate)) {
|
|
4809
6063
|
const candidatePackageJson = readPackageJson(candidate);
|
|
4810
6064
|
if (candidatePackageJson.name === packageName) {
|
|
@@ -4812,14 +6066,14 @@ function resolvePackageInfoSync(importPath, resolveDir) {
|
|
|
4812
6066
|
break;
|
|
4813
6067
|
}
|
|
4814
6068
|
}
|
|
4815
|
-
const parent = (0,
|
|
6069
|
+
const parent = (0, import_node_path2.dirname)(root);
|
|
4816
6070
|
if (parent === root) break;
|
|
4817
6071
|
root = parent;
|
|
4818
6072
|
}
|
|
4819
6073
|
if (!packageJsonPath) return null;
|
|
4820
6074
|
const packageJson = readPackageJson(packageJsonPath);
|
|
4821
6075
|
if (!packageJson.name || !packageJson.version) return null;
|
|
4822
|
-
root = (0,
|
|
6076
|
+
root = (0, import_node_path2.dirname)(packageJsonPath);
|
|
4823
6077
|
return {
|
|
4824
6078
|
name: packageJson.name,
|
|
4825
6079
|
version: packageJson.version,
|
|
@@ -4833,9 +6087,9 @@ function resolvePackageInfoSync(importPath, resolveDir) {
|
|
|
4833
6087
|
}
|
|
4834
6088
|
function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
|
|
4835
6089
|
const packageName = packageNameForImportPath(importPath);
|
|
4836
|
-
let root = (0,
|
|
6090
|
+
let root = (0, import_node_path2.dirname)(resolvedPath);
|
|
4837
6091
|
while (true) {
|
|
4838
|
-
const packageJsonPath = (0,
|
|
6092
|
+
const packageJsonPath = (0, import_node_path2.join)(root, "package.json");
|
|
4839
6093
|
if ((0, import_node_fs.existsSync)(packageJsonPath)) {
|
|
4840
6094
|
const packageJson = readPackageJson(packageJsonPath);
|
|
4841
6095
|
if (packageJson.name === packageName) {
|
|
@@ -4849,7 +6103,7 @@ function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
|
|
|
4849
6103
|
};
|
|
4850
6104
|
}
|
|
4851
6105
|
}
|
|
4852
|
-
const parent = (0,
|
|
6106
|
+
const parent = (0, import_node_path2.dirname)(root);
|
|
4853
6107
|
if (parent === root) return null;
|
|
4854
6108
|
root = parent;
|
|
4855
6109
|
}
|
|
@@ -4864,7 +6118,7 @@ function hasNativeHints(info) {
|
|
|
4864
6118
|
function shouldAutoExternalize(info) {
|
|
4865
6119
|
if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
|
|
4866
6120
|
if (hasNativeHints(info)) return true;
|
|
4867
|
-
if ((0, import_node_fs.existsSync)((0,
|
|
6121
|
+
if ((0, import_node_fs.existsSync)((0, import_node_path2.join)(info.root, "binding.gyp"))) return true;
|
|
4868
6122
|
return false;
|
|
4869
6123
|
}
|
|
4870
6124
|
function normalizeList(value) {
|
|
@@ -5055,6 +6309,24 @@ async function connectProviderSandboxHandle(options) {
|
|
|
5055
6309
|
});
|
|
5056
6310
|
return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
|
|
5057
6311
|
}
|
|
6312
|
+
async function destroyProviderSandbox(options) {
|
|
6313
|
+
if (options.provider === "modal") {
|
|
6314
|
+
validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
|
|
6315
|
+
return ModalSandboxHandle.destroyById(options, (message) => new DeploymentError(message));
|
|
6316
|
+
}
|
|
6317
|
+
if (options.provider === "daytona") {
|
|
6318
|
+
const { Daytona, DaytonaNotFoundError } = await getDaytona();
|
|
6319
|
+
const daytona = new Daytona({ apiKey: providerApiKey("daytona", options.apiKey) });
|
|
6320
|
+
try {
|
|
6321
|
+
await (await daytona.get(options.sandboxId)).delete(Math.ceil(SANDBOX_COMMAND_TIMEOUT_MS2 / 1e3), true);
|
|
6322
|
+
} catch (error) {
|
|
6323
|
+
if (!(error instanceof DaytonaNotFoundError)) throw error;
|
|
6324
|
+
}
|
|
6325
|
+
return;
|
|
6326
|
+
}
|
|
6327
|
+
const { Sandbox } = await getE2b();
|
|
6328
|
+
await Sandbox.kill(options.sandboxId, { apiKey: providerApiKey("e2b", options.apiKey) });
|
|
6329
|
+
}
|
|
5058
6330
|
var SandboxClient = class _SandboxClient {
|
|
5059
6331
|
constructor(handle) {
|
|
5060
6332
|
this.handle = handle;
|
|
@@ -5082,17 +6354,17 @@ var SandboxClient = class _SandboxClient {
|
|
|
5082
6354
|
outputJson: this.handle.paths.outputJson
|
|
5083
6355
|
};
|
|
5084
6356
|
}
|
|
5085
|
-
async makeDir(
|
|
5086
|
-
await this.handle.makeDir(
|
|
6357
|
+
async makeDir(path2) {
|
|
6358
|
+
await this.handle.makeDir(path2);
|
|
5087
6359
|
}
|
|
5088
|
-
async writeFile(
|
|
5089
|
-
await this.handle.writeFile(
|
|
6360
|
+
async writeFile(path2, content) {
|
|
6361
|
+
await this.handle.writeFile(path2, content);
|
|
5090
6362
|
}
|
|
5091
|
-
async readFile(
|
|
5092
|
-
return this.handle.readFile(
|
|
6363
|
+
async readFile(path2) {
|
|
6364
|
+
return this.handle.readFile(path2);
|
|
5093
6365
|
}
|
|
5094
|
-
async readFileBytes(
|
|
5095
|
-
return this.handle.readFileBytes(
|
|
6366
|
+
async readFileBytes(path2) {
|
|
6367
|
+
return this.handle.readFileBytes(path2);
|
|
5096
6368
|
}
|
|
5097
6369
|
async runCommand(command, options) {
|
|
5098
6370
|
return this.handle.runCommand(command, options);
|
|
@@ -5158,6 +6430,22 @@ var SandboxClient = class _SandboxClient {
|
|
|
5158
6430
|
}
|
|
5159
6431
|
await this.handle.setTimeout(timeoutMs);
|
|
5160
6432
|
}
|
|
6433
|
+
/**
|
|
6434
|
+
* Where to reach an HTTP server the sandbox runs on `port`, with the provider's auth: send
|
|
6435
|
+
* `headers` with every request and add `query` to every URL.
|
|
6436
|
+
*/
|
|
6437
|
+
async getServerEndpoint(port) {
|
|
6438
|
+
if (!this.handle.getServerEndpoint) {
|
|
6439
|
+
throw new ConfigurationError(`Sandbox provider "${this.provider}" does not expose server ports.`);
|
|
6440
|
+
}
|
|
6441
|
+
const { url, trafficToken } = await this.handle.getServerEndpoint(port);
|
|
6442
|
+
const descriptor = { provider: this.provider, trafficToken };
|
|
6443
|
+
return {
|
|
6444
|
+
url: url.replace(/\/+$/u, ""),
|
|
6445
|
+
headers: trafficTokenHeaders(descriptor),
|
|
6446
|
+
query: this.provider === "daytona" && trafficToken ? { DAYTONA_SANDBOX_AUTH_KEY: trafficToken } : {}
|
|
6447
|
+
};
|
|
6448
|
+
}
|
|
5161
6449
|
async kill() {
|
|
5162
6450
|
await this.handle.destroy();
|
|
5163
6451
|
}
|
|
@@ -5172,7 +6460,7 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
|
|
|
5172
6460
|
if (rawPath.startsWith("webpack-internal:")) {
|
|
5173
6461
|
const afterScheme = rawPath.replace(/^webpack-internal:\/+/, "");
|
|
5174
6462
|
const afterLayer = afterScheme.replace(/^\([^)]+\)\//, "");
|
|
5175
|
-
const resolved = (0,
|
|
6463
|
+
const resolved = (0, import_node_path2.resolve)(cwd, afterLayer);
|
|
5176
6464
|
return (0, import_node_fs.existsSync)(resolved) ? resolved : null;
|
|
5177
6465
|
}
|
|
5178
6466
|
return rawPath;
|
|
@@ -5222,7 +6510,7 @@ function resolveSourceFile(sourceFile) {
|
|
|
5222
6510
|
if (!normalized) {
|
|
5223
6511
|
throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
|
|
5224
6512
|
}
|
|
5225
|
-
const resolved = (0,
|
|
6513
|
+
const resolved = (0, import_node_path2.resolve)(normalized);
|
|
5226
6514
|
if (isFrameworkBuildOutputPath(resolved)) {
|
|
5227
6515
|
throw frameworkBuildOutputError(resolved);
|
|
5228
6516
|
}
|
|
@@ -5257,7 +6545,7 @@ function localPathStats(localPath, upload, isSourceRoot = false) {
|
|
|
5257
6545
|
}
|
|
5258
6546
|
}
|
|
5259
6547
|
function readConfiguredLocalDirectory(upload) {
|
|
5260
|
-
const rootPath = (0,
|
|
6548
|
+
const rootPath = (0, import_node_path2.resolve)(process.cwd(), upload.source);
|
|
5261
6549
|
const rootStats = localPathStats(rootPath, upload, true);
|
|
5262
6550
|
if (!rootStats.isDirectory()) {
|
|
5263
6551
|
throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
|
|
@@ -5274,7 +6562,7 @@ function readConfiguredLocalDirectory(upload) {
|
|
|
5274
6562
|
);
|
|
5275
6563
|
}
|
|
5276
6564
|
for (const entry of entries) {
|
|
5277
|
-
const localPath = (0,
|
|
6565
|
+
const localPath = (0, import_node_path2.join)(currentPath, entry);
|
|
5278
6566
|
const stats = localPathStats(localPath, upload);
|
|
5279
6567
|
if (stats.isDirectory()) {
|
|
5280
6568
|
walk(localPath);
|
|
@@ -5285,8 +6573,8 @@ function readConfiguredLocalDirectory(upload) {
|
|
|
5285
6573
|
`${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
|
|
5286
6574
|
);
|
|
5287
6575
|
}
|
|
5288
|
-
const relativePath = (0,
|
|
5289
|
-
const targetPath =
|
|
6576
|
+
const relativePath = (0, import_node_path2.relative)(rootPath, localPath).split(import_node_path2.sep).join("/");
|
|
6577
|
+
const targetPath = import_node_path2.posix.join(destination, relativePath);
|
|
5290
6578
|
let content;
|
|
5291
6579
|
try {
|
|
5292
6580
|
content = (0, import_node_fs.readFileSync)(localPath);
|
|
@@ -5336,7 +6624,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
|
|
|
5336
6624
|
}
|
|
5337
6625
|
}
|
|
5338
6626
|
for (const file of filesByTarget.values()) {
|
|
5339
|
-
let parent =
|
|
6627
|
+
let parent = import_node_path2.posix.dirname(file.targetPath);
|
|
5340
6628
|
while (parent !== ".") {
|
|
5341
6629
|
const parentFile = filesByTarget.get(parent);
|
|
5342
6630
|
if (parentFile) {
|
|
@@ -5345,7 +6633,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
|
|
|
5345
6633
|
);
|
|
5346
6634
|
}
|
|
5347
6635
|
requiredDirectories.add(parent);
|
|
5348
|
-
parent =
|
|
6636
|
+
parent = import_node_path2.posix.dirname(parent);
|
|
5349
6637
|
}
|
|
5350
6638
|
}
|
|
5351
6639
|
const directories = [...requiredDirectories].sort((left, right) => {
|
|
@@ -5357,7 +6645,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
|
|
|
5357
6645
|
);
|
|
5358
6646
|
return { directories, files };
|
|
5359
6647
|
}
|
|
5360
|
-
var
|
|
6648
|
+
var LegacyBundledAgent = class {
|
|
5361
6649
|
sandbox;
|
|
5362
6650
|
provider;
|
|
5363
6651
|
template;
|
|
@@ -5623,7 +6911,7 @@ var Agent = class {
|
|
|
5623
6911
|
*
|
|
5624
6912
|
* @example
|
|
5625
6913
|
* ```typescript
|
|
5626
|
-
* const agent = new
|
|
6914
|
+
* const agent = new LegacyBundledAgent({ ... });
|
|
5627
6915
|
* const sandboxId = await agent.deploy();
|
|
5628
6916
|
* console.log(`Deployed to sandbox: ${sandboxId}`);
|
|
5629
6917
|
*
|
|
@@ -5678,7 +6966,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5678
6966
|
}));
|
|
5679
6967
|
build.onLoad({ filter: /.*/, namespace: "agent-shim" }, () => ({
|
|
5680
6968
|
contents: `
|
|
5681
|
-
export class
|
|
6969
|
+
export class LegacyBundledAgent {
|
|
5682
6970
|
constructor(config) {
|
|
5683
6971
|
this.inputSchema = config.inputSchema;
|
|
5684
6972
|
this.outputSchema = config.outputSchema;
|
|
@@ -5785,7 +7073,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5785
7073
|
}
|
|
5786
7074
|
}
|
|
5787
7075
|
if (localDirectoryUploads.directories.length > 0 || localDirectoryUploads.files.length > 0) {
|
|
5788
|
-
const archivePath =
|
|
7076
|
+
const archivePath = import_node_path2.posix.join(paths.agentDir, `.neckbeard-local-directories-${(0, import_node_crypto4.randomUUID)()}.tar.gz`);
|
|
5789
7077
|
await sandbox.writeFile(archivePath, await createTarGz([
|
|
5790
7078
|
...localDirectoryUploads.directories.map((directory) => ({ path: directory })),
|
|
5791
7079
|
...localDirectoryUploads.files.map((file) => ({ path: file.targetPath, content: file.content }))
|
|
@@ -5966,18 +7254,18 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5966
7254
|
);
|
|
5967
7255
|
}
|
|
5968
7256
|
if (!options || typeof options !== "object") {
|
|
5969
|
-
throw new ConfigurationError("
|
|
7257
|
+
throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
|
|
5970
7258
|
}
|
|
5971
7259
|
let optionsAreArray;
|
|
5972
7260
|
try {
|
|
5973
7261
|
optionsAreArray = Array.isArray(options);
|
|
5974
7262
|
} catch {
|
|
5975
7263
|
throw new ConfigurationError(
|
|
5976
|
-
"
|
|
7264
|
+
"LegacyBundledAgent.createSession() options must have readable values."
|
|
5977
7265
|
);
|
|
5978
7266
|
}
|
|
5979
7267
|
if (optionsAreArray) {
|
|
5980
|
-
throw new ConfigurationError("
|
|
7268
|
+
throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
|
|
5981
7269
|
}
|
|
5982
7270
|
let durability;
|
|
5983
7271
|
let requestedSandboxId;
|
|
@@ -5988,22 +7276,22 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5988
7276
|
signal = options.signal;
|
|
5989
7277
|
} catch {
|
|
5990
7278
|
throw new ConfigurationError(
|
|
5991
|
-
"
|
|
7279
|
+
"LegacyBundledAgent.createSession() options must have readable values."
|
|
5992
7280
|
);
|
|
5993
7281
|
}
|
|
5994
7282
|
if (durability !== void 0 && durability !== "attached") {
|
|
5995
7283
|
throw new ConfigurationError(
|
|
5996
|
-
"
|
|
7284
|
+
"LegacyBundledAgent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
|
|
5997
7285
|
);
|
|
5998
7286
|
}
|
|
5999
7287
|
if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
|
|
6000
7288
|
throw new ConfigurationError(
|
|
6001
|
-
"
|
|
7289
|
+
"LegacyBundledAgent.createSession() sandboxId must be a non-empty string when provided."
|
|
6002
7290
|
);
|
|
6003
7291
|
}
|
|
6004
7292
|
if (signal !== void 0 && !isAbortSignal(signal)) {
|
|
6005
7293
|
throw new ConfigurationError(
|
|
6006
|
-
"
|
|
7294
|
+
"LegacyBundledAgent.createSession() signal must be an AbortSignal when provided."
|
|
6007
7295
|
);
|
|
6008
7296
|
}
|
|
6009
7297
|
const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
@@ -6123,13 +7411,23 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
6123
7411
|
Agent,
|
|
6124
7412
|
ConfigurationError,
|
|
6125
7413
|
DEFAULT_DEPENDENCIES,
|
|
7414
|
+
DefinedAgent,
|
|
6126
7415
|
DeploymentError,
|
|
6127
7416
|
ExecutionError,
|
|
7417
|
+
LegacyBundledAgent,
|
|
6128
7418
|
NeckbeardError,
|
|
6129
7419
|
RuntimeBusyError,
|
|
7420
|
+
SKILLS_DIR,
|
|
6130
7421
|
SandboxClient,
|
|
7422
|
+
TURN_PROTOCOL_VERSION,
|
|
7423
|
+
TurnLostError,
|
|
6131
7424
|
ValidationError,
|
|
7425
|
+
defineAgent,
|
|
7426
|
+
destroyProviderSandbox,
|
|
7427
|
+
getPiTurnResult,
|
|
7428
|
+
isDefinedAgent,
|
|
6132
7429
|
normalizeStackFramePath,
|
|
6133
7430
|
resolveAgentSourceFile,
|
|
7431
|
+
resolveImageTag,
|
|
6134
7432
|
withNeckbeardNextConfig
|
|
6135
7433
|
});
|