agent-neckbeard 1.1.2 → 1.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -10
- package/dist/index.cjs +350 -182
- package/dist/index.d.cts +96 -25
- package/dist/index.d.ts +96 -25
- package/dist/index.js +350 -182
- package/package.json +9 -9
package/dist/index.cjs
CHANGED
|
@@ -36,45 +36,30 @@ __export(index_exports, {
|
|
|
36
36
|
DeploymentError: () => DeploymentError,
|
|
37
37
|
ExecutionError: () => ExecutionError,
|
|
38
38
|
NeckbeardError: () => NeckbeardError,
|
|
39
|
-
ValidationError: () => ValidationError
|
|
39
|
+
ValidationError: () => ValidationError,
|
|
40
|
+
normalizeStackFramePath: () => normalizeStackFramePath
|
|
40
41
|
});
|
|
41
42
|
module.exports = __toCommonJS(index_exports);
|
|
42
43
|
var import_node_url = require("url");
|
|
43
44
|
var import_node_fs = require("fs");
|
|
44
45
|
var import_node_path = require("path");
|
|
45
46
|
var import_node_module = require("module");
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
function readPackageJson(path) {
|
|
48
|
+
return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
|
|
49
|
+
}
|
|
48
50
|
var getEsbuild = () => import("esbuild");
|
|
49
51
|
var getE2b = () => import("e2b");
|
|
52
|
+
var getDaytona = () => import("@daytona/sdk");
|
|
50
53
|
var DEFAULT_MAX_DURATION = 300;
|
|
51
54
|
var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
|
|
52
55
|
var QUICK_COMMAND_TIMEOUT_MS = 3e4;
|
|
56
|
+
var DAYTONA_CREATE_TIMEOUT_SEC = 120;
|
|
53
57
|
var NODE_TARGET = "node20";
|
|
54
58
|
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
55
59
|
var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
|
|
56
60
|
var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
|
|
57
61
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
58
|
-
var
|
|
59
|
-
var SANDBOX_AGENT_DIR = `${SANDBOX_HOME}/agent`;
|
|
60
|
-
var SANDBOX_PATHS = {
|
|
61
|
-
/** Agent code directory */
|
|
62
|
-
agentDir: SANDBOX_AGENT_DIR,
|
|
63
|
-
/** I/O directory for input/output files */
|
|
64
|
-
ioDir: `${SANDBOX_HOME}/io`,
|
|
65
|
-
/** Task input file */
|
|
66
|
-
inputJson: `${SANDBOX_HOME}/io/input.json`,
|
|
67
|
-
/** Result output file (contains success/error) */
|
|
68
|
-
outputJson: `${SANDBOX_HOME}/io/output.json`,
|
|
69
|
-
/** Bundled agent module */
|
|
70
|
-
agentModule: `${SANDBOX_AGENT_DIR}/agent.mjs`,
|
|
71
|
-
/** Runner module that executes the agent */
|
|
72
|
-
runnerModule: `${SANDBOX_AGENT_DIR}/runner.mjs`,
|
|
73
|
-
/** Claude skills and settings directory */
|
|
74
|
-
claudeDir: `${SANDBOX_AGENT_DIR}/.claude`,
|
|
75
|
-
/** Package.json for npm dependencies */
|
|
76
|
-
packageJson: `${SANDBOX_AGENT_DIR}/package.json`
|
|
77
|
-
};
|
|
62
|
+
var E2B_SANDBOX_HOME = "/home/user";
|
|
78
63
|
var NeckbeardError = class extends Error {
|
|
79
64
|
constructor(message) {
|
|
80
65
|
super(message);
|
|
@@ -121,9 +106,7 @@ function requireEnv(name) {
|
|
|
121
106
|
function shellEscape(str) {
|
|
122
107
|
return `'${str.replace(/'/g, "'\\''")}'`;
|
|
123
108
|
}
|
|
124
|
-
var require2 = (0, import_node_module.createRequire)(
|
|
125
|
-
typeof __filename !== "undefined" ? __filename : (0, import_node_url.fileURLToPath)(import_meta.url)
|
|
126
|
-
);
|
|
109
|
+
var require2 = (0, import_node_module.createRequire)((0, import_node_path.join)(process.cwd(), "__agent_neckbeard__.cjs"));
|
|
127
110
|
function isBareModuleImport(path) {
|
|
128
111
|
const excludes = [".", "/", "~", "file:", "data:"];
|
|
129
112
|
return !excludes.some((exclude) => path.startsWith(exclude));
|
|
@@ -134,25 +117,6 @@ function packageNameForImportPath(importPath) {
|
|
|
134
117
|
}
|
|
135
118
|
return importPath.split("/")[0];
|
|
136
119
|
}
|
|
137
|
-
function resolveModulePath(importPath, resolveDir) {
|
|
138
|
-
try {
|
|
139
|
-
return require2.resolve(importPath, { paths: [resolveDir] });
|
|
140
|
-
} catch {
|
|
141
|
-
const importMeta = import_meta ?? void 0;
|
|
142
|
-
const resolver = importMeta && typeof importMeta.resolve === "function" ? importMeta.resolve.bind(importMeta) : void 0;
|
|
143
|
-
if (!resolver) return null;
|
|
144
|
-
try {
|
|
145
|
-
const parentUrl = (0, import_node_url.pathToFileURL)((0, import_node_path.join)(resolveDir, "__neckbeard__.js"));
|
|
146
|
-
const resolved = resolver(importPath, parentUrl);
|
|
147
|
-
if (resolved.startsWith("file://")) {
|
|
148
|
-
return (0, import_node_url.fileURLToPath)(resolved);
|
|
149
|
-
}
|
|
150
|
-
} catch {
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
return null;
|
|
155
|
-
}
|
|
156
120
|
function globToRegExp(pattern) {
|
|
157
121
|
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
158
122
|
return new RegExp(`^${escaped}$`);
|
|
@@ -160,39 +124,33 @@ function globToRegExp(pattern) {
|
|
|
160
124
|
function matchesExternal(matchers, pkgName) {
|
|
161
125
|
return matchers.some((re) => re.test(pkgName));
|
|
162
126
|
}
|
|
163
|
-
async function isMainPackageJson(filePath) {
|
|
164
|
-
try {
|
|
165
|
-
const packageJson = await (0, import_pkg_types.readPackageJSON)(filePath);
|
|
166
|
-
const markerFields = /* @__PURE__ */ new Set([
|
|
167
|
-
"type",
|
|
168
|
-
"sideEffects",
|
|
169
|
-
"browser",
|
|
170
|
-
"main",
|
|
171
|
-
"module",
|
|
172
|
-
"react-native",
|
|
173
|
-
"name"
|
|
174
|
-
]);
|
|
175
|
-
if (!packageJson.type) return true;
|
|
176
|
-
const keys = Object.keys(packageJson);
|
|
177
|
-
return !keys.every((k) => markerFields.has(k));
|
|
178
|
-
} catch {
|
|
179
|
-
return false;
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
127
|
async function resolvePackageInfo(importPath, resolveDir) {
|
|
183
128
|
try {
|
|
184
|
-
const resolvedPath =
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
129
|
+
const resolvedPath = require2.resolve(importPath, { paths: [resolveDir] });
|
|
130
|
+
const packageName = packageNameForImportPath(importPath);
|
|
131
|
+
let root = (0, import_node_path.dirname)(resolvedPath);
|
|
132
|
+
let packageJsonPath = null;
|
|
133
|
+
while (true) {
|
|
134
|
+
const candidate = (0, import_node_path.join)(root, "package.json");
|
|
135
|
+
if ((0, import_node_fs.existsSync)(candidate)) {
|
|
136
|
+
const candidatePackageJson = readPackageJson(candidate);
|
|
137
|
+
if (candidatePackageJson.name === packageName) {
|
|
138
|
+
packageJsonPath = candidate;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const parent = (0, import_node_path.dirname)(root);
|
|
143
|
+
if (parent === root) break;
|
|
144
|
+
root = parent;
|
|
145
|
+
}
|
|
189
146
|
if (!packageJsonPath) return null;
|
|
190
|
-
const packageJson =
|
|
147
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
191
148
|
if (!packageJson.name || !packageJson.version) return null;
|
|
149
|
+
root = (0, import_node_path.dirname)(packageJsonPath);
|
|
192
150
|
return {
|
|
193
151
|
name: packageJson.name,
|
|
194
152
|
version: packageJson.version,
|
|
195
|
-
root
|
|
153
|
+
root,
|
|
196
154
|
resolvedPath,
|
|
197
155
|
packageJson
|
|
198
156
|
};
|
|
@@ -231,17 +189,67 @@ function isPackageCompatible(info) {
|
|
|
231
189
|
const cpuList = normalizeList(info.packageJson.cpu);
|
|
232
190
|
return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
|
|
233
191
|
}
|
|
234
|
-
|
|
192
|
+
function filterDefinedEnvs(envs) {
|
|
193
|
+
return Object.fromEntries(
|
|
194
|
+
Object.entries(envs).filter(([_, value]) => value !== void 0).map(([key, value]) => [key, value])
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
function arrayBufferToBuffer(value) {
|
|
198
|
+
return Buffer.from(value);
|
|
199
|
+
}
|
|
200
|
+
function toDaytonaUploadContent(content) {
|
|
201
|
+
if (typeof content === "string") return Buffer.from(content);
|
|
202
|
+
if (Buffer.isBuffer(content)) return content;
|
|
203
|
+
if (content instanceof Uint8Array) return Buffer.from(content);
|
|
204
|
+
return arrayBufferToBuffer(content);
|
|
205
|
+
}
|
|
206
|
+
function toE2bWriteContent(content) {
|
|
207
|
+
if (typeof content === "string") return content;
|
|
208
|
+
if (content instanceof ArrayBuffer) return content;
|
|
209
|
+
return Uint8Array.from(content).buffer;
|
|
210
|
+
}
|
|
211
|
+
function createSandboxPaths(provider, homeDir, workDir) {
|
|
212
|
+
const agentDir = `${homeDir}/agent`;
|
|
213
|
+
const ioDir = `${homeDir}/io`;
|
|
214
|
+
return {
|
|
215
|
+
provider,
|
|
216
|
+
homeDir,
|
|
217
|
+
workDir,
|
|
218
|
+
agentDir,
|
|
219
|
+
ioDir,
|
|
220
|
+
inputJson: `${ioDir}/input.json`,
|
|
221
|
+
outputJson: `${ioDir}/output.json`,
|
|
222
|
+
agentModule: `${agentDir}/agent.mjs`,
|
|
223
|
+
runnerModule: `${agentDir}/runner.mjs`,
|
|
224
|
+
claudeDir: `${agentDir}/.claude`,
|
|
225
|
+
packageJson: `${agentDir}/package.json`
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function timeoutMsToSeconds(timeoutMs) {
|
|
229
|
+
return Math.max(1, Math.ceil(timeoutMs / 1e3));
|
|
230
|
+
}
|
|
231
|
+
async function resolveDaytonaPaths(sandbox) {
|
|
232
|
+
const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
|
|
233
|
+
const homeDir = await sandbox.getUserHomeDir() ?? workDir;
|
|
234
|
+
if (!homeDir || !workDir) {
|
|
235
|
+
throw new DeploymentError("Daytona sandbox did not report a home or working directory.");
|
|
236
|
+
}
|
|
237
|
+
return createSandboxPaths("daytona", homeDir, workDir);
|
|
238
|
+
}
|
|
239
|
+
async function runE2bCommand(sandbox, cmd, options) {
|
|
235
240
|
let stdout = "";
|
|
236
241
|
let stderr = "";
|
|
237
242
|
try {
|
|
238
243
|
const result = await sandbox.commands.run(cmd, {
|
|
239
|
-
timeoutMs,
|
|
244
|
+
timeoutMs: options.timeoutMs,
|
|
245
|
+
envs: options.envs,
|
|
240
246
|
onStdout: (data) => {
|
|
241
247
|
stdout += data;
|
|
248
|
+
options.onStdout?.(data);
|
|
242
249
|
},
|
|
243
250
|
onStderr: (data) => {
|
|
244
251
|
stderr += data;
|
|
252
|
+
options.onStderr?.(data);
|
|
245
253
|
}
|
|
246
254
|
});
|
|
247
255
|
return {
|
|
@@ -259,19 +267,76 @@ async function runSandboxCommand(sandbox, cmd, timeoutMs) {
|
|
|
259
267
|
};
|
|
260
268
|
}
|
|
261
269
|
}
|
|
270
|
+
function createE2bHandle(sandbox) {
|
|
271
|
+
const paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
|
|
272
|
+
return {
|
|
273
|
+
id: sandbox.sandboxId,
|
|
274
|
+
paths,
|
|
275
|
+
writeFile: (path, content) => sandbox.files.write(path, toE2bWriteContent(content)),
|
|
276
|
+
readFile: (path) => sandbox.files.read(path),
|
|
277
|
+
runCommand: (cmd, options) => {
|
|
278
|
+
const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
|
|
279
|
+
return runE2bCommand(sandbox, command, options);
|
|
280
|
+
},
|
|
281
|
+
destroy: () => sandbox.kill()
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
async function createDaytonaHandle(sandbox) {
|
|
285
|
+
const paths = await resolveDaytonaPaths(sandbox);
|
|
286
|
+
return {
|
|
287
|
+
id: sandbox.id,
|
|
288
|
+
paths,
|
|
289
|
+
writeFile: (path, content) => sandbox.fs.uploadFile(
|
|
290
|
+
toDaytonaUploadContent(content),
|
|
291
|
+
path,
|
|
292
|
+
timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
|
|
293
|
+
),
|
|
294
|
+
readFile: async (path) => {
|
|
295
|
+
const content = await sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
|
|
296
|
+
return content.toString("utf-8");
|
|
297
|
+
},
|
|
298
|
+
runCommand: async (cmd, options) => {
|
|
299
|
+
const result = await sandbox.process.executeCommand(
|
|
300
|
+
cmd,
|
|
301
|
+
options.cwd,
|
|
302
|
+
options.envs,
|
|
303
|
+
timeoutMsToSeconds(options.timeoutMs)
|
|
304
|
+
);
|
|
305
|
+
const stdout = result.artifacts?.stdout ?? result.result ?? "";
|
|
306
|
+
if (stdout) options.onStdout?.(stdout);
|
|
307
|
+
return {
|
|
308
|
+
exitCode: result.exitCode,
|
|
309
|
+
stdout,
|
|
310
|
+
stderr: ""
|
|
311
|
+
};
|
|
312
|
+
},
|
|
313
|
+
destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
|
|
317
|
+
if (rawPath.startsWith("file://")) {
|
|
318
|
+
return (0, import_node_url.fileURLToPath)(rawPath);
|
|
319
|
+
}
|
|
320
|
+
if (rawPath.startsWith("webpack-internal:")) {
|
|
321
|
+
const afterScheme = rawPath.replace(/^webpack-internal:\/+/, "");
|
|
322
|
+
const afterLayer = afterScheme.replace(/^\([^)]+\)\//, "");
|
|
323
|
+
const resolved = (0, import_node_path.resolve)(cwd, afterLayer);
|
|
324
|
+
return (0, import_node_fs.existsSync)(resolved) ? resolved : null;
|
|
325
|
+
}
|
|
326
|
+
return rawPath;
|
|
327
|
+
}
|
|
262
328
|
function getCallerFile() {
|
|
263
|
-
const internalFiles = /* @__PURE__ */ new Set();
|
|
264
|
-
const currentFile = typeof __filename !== "undefined" ? __filename : (0, import_node_url.fileURLToPath)(import_meta.url);
|
|
265
|
-
internalFiles.add(currentFile);
|
|
266
329
|
const stack = new Error().stack?.split("\n") ?? [];
|
|
267
330
|
for (const line of stack.slice(2)) {
|
|
268
331
|
const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
|
|
269
|
-
if (match)
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
332
|
+
if (!match) continue;
|
|
333
|
+
const file = normalizeStackFramePath(match[1]);
|
|
334
|
+
if (!file) continue;
|
|
335
|
+
if (file.includes("node:")) continue;
|
|
336
|
+
if (file.includes("node_modules/agent-neckbeard")) continue;
|
|
337
|
+
if (file.includes("agent-neckbeard/dist")) continue;
|
|
338
|
+
if (file.endsWith("/src/index.ts")) continue;
|
|
339
|
+
return file;
|
|
275
340
|
}
|
|
276
341
|
throw new Error("Could not determine source file");
|
|
277
342
|
}
|
|
@@ -301,6 +366,8 @@ function readDirectoryRecursively(dirPath) {
|
|
|
301
366
|
return files;
|
|
302
367
|
}
|
|
303
368
|
var Agent = class {
|
|
369
|
+
sandbox;
|
|
370
|
+
provider;
|
|
304
371
|
template;
|
|
305
372
|
inputSchema;
|
|
306
373
|
outputSchema;
|
|
@@ -315,7 +382,9 @@ var Agent = class {
|
|
|
315
382
|
_sourceFile;
|
|
316
383
|
_sandboxId;
|
|
317
384
|
constructor(config) {
|
|
318
|
-
this.
|
|
385
|
+
this.sandbox = config.sandbox;
|
|
386
|
+
this.provider = config.sandbox.provider;
|
|
387
|
+
this.template = config.sandbox.template;
|
|
319
388
|
this.inputSchema = config.inputSchema;
|
|
320
389
|
this.outputSchema = config.outputSchema;
|
|
321
390
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
@@ -330,15 +399,155 @@ var Agent = class {
|
|
|
330
399
|
get sandboxId() {
|
|
331
400
|
return this._sandboxId;
|
|
332
401
|
}
|
|
402
|
+
get sandboxEnv() {
|
|
403
|
+
return filterDefinedEnvs(this.envs);
|
|
404
|
+
}
|
|
405
|
+
async createSandboxHandle() {
|
|
406
|
+
if (this.provider === "daytona") {
|
|
407
|
+
const apiKey2 = requireEnv("DAYTONA_API_KEY");
|
|
408
|
+
const { Daytona } = await getDaytona();
|
|
409
|
+
const daytona = new Daytona({ apiKey: apiKey2 });
|
|
410
|
+
const sandbox2 = await daytona.create(
|
|
411
|
+
{
|
|
412
|
+
snapshot: this.template,
|
|
413
|
+
envVars: this.sandboxEnv,
|
|
414
|
+
autoDeleteInterval: -1
|
|
415
|
+
},
|
|
416
|
+
{ timeout: DAYTONA_CREATE_TIMEOUT_SEC }
|
|
417
|
+
);
|
|
418
|
+
return createDaytonaHandle(sandbox2);
|
|
419
|
+
}
|
|
420
|
+
const apiKey = requireEnv("E2B_API_KEY");
|
|
421
|
+
const { Sandbox } = await getE2b();
|
|
422
|
+
const sandbox = await Sandbox.create(this.template, { apiKey });
|
|
423
|
+
return createE2bHandle(sandbox);
|
|
424
|
+
}
|
|
425
|
+
async connectSandboxHandle(sandboxId) {
|
|
426
|
+
if (this.provider === "daytona") {
|
|
427
|
+
const apiKey2 = requireEnv("DAYTONA_API_KEY");
|
|
428
|
+
const { Daytona } = await getDaytona();
|
|
429
|
+
const daytona = new Daytona({ apiKey: apiKey2 });
|
|
430
|
+
const sandbox2 = await daytona.get(sandboxId);
|
|
431
|
+
if (sandbox2.state !== "started") {
|
|
432
|
+
if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
|
|
433
|
+
await sandbox2.waitUntilStarted?.(DAYTONA_CREATE_TIMEOUT_SEC);
|
|
434
|
+
} else {
|
|
435
|
+
await sandbox2.start?.(DAYTONA_CREATE_TIMEOUT_SEC);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return createDaytonaHandle(sandbox2);
|
|
439
|
+
}
|
|
440
|
+
const apiKey = requireEnv("E2B_API_KEY");
|
|
441
|
+
const { Sandbox } = await getE2b();
|
|
442
|
+
const sandbox = await Sandbox.connect(sandboxId, { apiKey });
|
|
443
|
+
return createE2bHandle(sandbox);
|
|
444
|
+
}
|
|
445
|
+
buildRunnerCode(paths) {
|
|
446
|
+
const sandboxContext = JSON.stringify({
|
|
447
|
+
provider: paths.provider,
|
|
448
|
+
homeDir: paths.homeDir,
|
|
449
|
+
workDir: paths.workDir,
|
|
450
|
+
agentDir: paths.agentDir,
|
|
451
|
+
ioDir: paths.ioDir,
|
|
452
|
+
inputJson: paths.inputJson,
|
|
453
|
+
outputJson: paths.outputJson
|
|
454
|
+
});
|
|
455
|
+
return `
|
|
456
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
457
|
+
|
|
458
|
+
const SANDBOX_CONTEXT = ${sandboxContext};
|
|
459
|
+
const IO_DIR = SANDBOX_CONTEXT.ioDir;
|
|
460
|
+
const INPUT_FILE = SANDBOX_CONTEXT.inputJson;
|
|
461
|
+
const OUTPUT_FILE = SANDBOX_CONTEXT.outputJson;
|
|
462
|
+
|
|
463
|
+
mkdirSync(IO_DIR, { recursive: true });
|
|
464
|
+
|
|
465
|
+
let input, executionId;
|
|
466
|
+
try {
|
|
467
|
+
const taskData = JSON.parse(readFileSync(INPUT_FILE, 'utf-8'));
|
|
468
|
+
input = taskData.input;
|
|
469
|
+
executionId = taskData.executionId;
|
|
470
|
+
} catch (parseError) {
|
|
471
|
+
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Task parse failed: ' + parseError.message, stack: parseError.stack } }));
|
|
472
|
+
process.exit(0);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
let mod;
|
|
476
|
+
try {
|
|
477
|
+
mod = await import('./agent.mjs');
|
|
478
|
+
} catch (importError) {
|
|
479
|
+
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Import failed: ' + importError.message, stack: importError.stack } }));
|
|
480
|
+
process.exit(0);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const agent = mod.default || Object.values(mod).find(v => v instanceof Object && v._run);
|
|
484
|
+
if (!agent) {
|
|
485
|
+
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'No agent found in module. Exports: ' + Object.keys(mod).join(', ') } }));
|
|
486
|
+
process.exit(0);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const ctx = {
|
|
490
|
+
executionId,
|
|
491
|
+
signal: AbortSignal.timeout(${this.maxDuration * 1e3}),
|
|
492
|
+
env: process.env,
|
|
493
|
+
sandbox: SANDBOX_CONTEXT,
|
|
494
|
+
logger: {
|
|
495
|
+
debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
|
|
496
|
+
info: (msg, ...args) => console.log('[INFO]', msg, ...args),
|
|
497
|
+
warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
|
|
498
|
+
error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
|
|
499
|
+
},
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
try {
|
|
503
|
+
const validated = agent.inputSchema.parse(input);
|
|
504
|
+
const output = await agent._run(validated, ctx);
|
|
505
|
+
const validatedOutput = agent.outputSchema.parse(output);
|
|
506
|
+
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: true, output: validatedOutput }));
|
|
507
|
+
} catch (error) {
|
|
508
|
+
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: error.message, stack: error.stack } }));
|
|
509
|
+
}
|
|
510
|
+
`;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Kills the current sandbox and resets the cached sandbox ID.
|
|
514
|
+
*
|
|
515
|
+
* Use this to clean up sandbox resources after a run, especially when
|
|
516
|
+
* running multiple evaluations that each need their own sandbox.
|
|
517
|
+
*
|
|
518
|
+
* @param sandboxId - Optional sandbox ID to kill. Defaults to the cached sandbox.
|
|
519
|
+
*
|
|
520
|
+
* @example
|
|
521
|
+
* ```typescript
|
|
522
|
+
* const sandboxId = await agent.deploy();
|
|
523
|
+
* const result = await agent.run(input, { sandboxId });
|
|
524
|
+
* await agent.kill(sandboxId);
|
|
525
|
+
* ```
|
|
526
|
+
*/
|
|
527
|
+
async kill(sandboxId) {
|
|
528
|
+
const targetId = sandboxId ?? this._sandboxId;
|
|
529
|
+
if (!targetId) return;
|
|
530
|
+
try {
|
|
531
|
+
const sandbox = await this.connectSandboxHandle(targetId);
|
|
532
|
+
await sandbox.destroy();
|
|
533
|
+
} catch {
|
|
534
|
+
}
|
|
535
|
+
if (targetId === this._sandboxId) {
|
|
536
|
+
this._sandboxId = void 0;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
333
539
|
/**
|
|
334
|
-
* Deploys the agent to
|
|
540
|
+
* Deploys the agent to a sandbox provider.
|
|
335
541
|
*
|
|
336
|
-
* This method bundles the agent code using esbuild, creates a new
|
|
542
|
+
* This method bundles the agent code using esbuild, creates a new sandbox,
|
|
337
543
|
* installs any specified OS dependencies, downloads configured files, and
|
|
338
544
|
* uploads the agent code to the sandbox.
|
|
339
545
|
*
|
|
546
|
+
* @param options.fresh - When true, always creates a new sandbox without caching.
|
|
547
|
+
* Useful for concurrent evaluations where each run needs its own sandbox.
|
|
548
|
+
* The returned sandbox ID won't be stored on the instance.
|
|
340
549
|
* @returns The sandbox ID, which can be used to reconnect via `run(input, { sandboxId })`
|
|
341
|
-
* @throws {ConfigurationError} If
|
|
550
|
+
* @throws {ConfigurationError} If the selected provider credentials are not set
|
|
342
551
|
* @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
|
|
343
552
|
*
|
|
344
553
|
* @example
|
|
@@ -346,13 +555,16 @@ var Agent = class {
|
|
|
346
555
|
* const agent = new Agent({ ... });
|
|
347
556
|
* const sandboxId = await agent.deploy();
|
|
348
557
|
* console.log(`Deployed to sandbox: ${sandboxId}`);
|
|
558
|
+
*
|
|
559
|
+
* // For concurrent evals: each call gets its own sandbox
|
|
560
|
+
* const id = await agent.deploy({ fresh: true });
|
|
561
|
+
* const result = await agent.run(input, { sandboxId: id });
|
|
562
|
+
* await agent.kill(id);
|
|
349
563
|
* ```
|
|
350
564
|
*/
|
|
351
|
-
async deploy() {
|
|
352
|
-
if (this._sandboxId) return this._sandboxId;
|
|
353
|
-
const e2bApiKey = requireEnv("E2B_API_KEY");
|
|
565
|
+
async deploy(options) {
|
|
566
|
+
if (!options?.fresh && this._sandboxId) return this._sandboxId;
|
|
354
567
|
const esbuild = await getEsbuild();
|
|
355
|
-
const { Sandbox } = await getE2b();
|
|
356
568
|
const externalPatterns = Array.from(
|
|
357
569
|
/* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
|
|
358
570
|
);
|
|
@@ -420,68 +632,18 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
420
632
|
}
|
|
421
633
|
}]
|
|
422
634
|
});
|
|
423
|
-
const
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
const OUTPUT_FILE = IO_DIR + '/output.json';
|
|
429
|
-
|
|
430
|
-
mkdirSync(IO_DIR, { recursive: true });
|
|
431
|
-
|
|
432
|
-
let input, executionId;
|
|
433
|
-
try {
|
|
434
|
-
const taskData = JSON.parse(readFileSync(INPUT_FILE, 'utf-8'));
|
|
435
|
-
input = taskData.input;
|
|
436
|
-
executionId = taskData.executionId;
|
|
437
|
-
} catch (parseError) {
|
|
438
|
-
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Task parse failed: ' + parseError.message, stack: parseError.stack } }));
|
|
439
|
-
process.exit(0);
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
let mod;
|
|
443
|
-
try {
|
|
444
|
-
mod = await import('./agent.mjs');
|
|
445
|
-
} catch (importError) {
|
|
446
|
-
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Import failed: ' + importError.message, stack: importError.stack } }));
|
|
447
|
-
process.exit(0);
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
const agent = mod.default || Object.values(mod).find(v => v instanceof Object && v._run);
|
|
451
|
-
if (!agent) {
|
|
452
|
-
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'No agent found in module. Exports: ' + Object.keys(mod).join(', ') } }));
|
|
453
|
-
process.exit(0);
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
const ctx = {
|
|
457
|
-
executionId,
|
|
458
|
-
signal: AbortSignal.timeout(${this.maxDuration * 1e3}),
|
|
459
|
-
env: process.env,
|
|
460
|
-
logger: {
|
|
461
|
-
debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
|
|
462
|
-
info: (msg, ...args) => console.log('[INFO]', msg, ...args),
|
|
463
|
-
warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
|
|
464
|
-
error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
|
|
465
|
-
},
|
|
466
|
-
};
|
|
467
|
-
|
|
468
|
-
try {
|
|
469
|
-
const validated = agent.inputSchema.parse(input);
|
|
470
|
-
const output = await agent._run(validated, ctx);
|
|
471
|
-
const validatedOutput = agent.outputSchema.parse(output);
|
|
472
|
-
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: true, output: validatedOutput }));
|
|
473
|
-
} catch (error) {
|
|
474
|
-
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: error.message, stack: error.stack } }));
|
|
475
|
-
}
|
|
476
|
-
`;
|
|
477
|
-
const sandbox = await Sandbox.create(this.template, {
|
|
478
|
-
apiKey: e2bApiKey
|
|
635
|
+
const sandbox = await this.createSandboxHandle();
|
|
636
|
+
const { paths } = sandbox;
|
|
637
|
+
const runnerCode = this.buildRunnerCode(paths);
|
|
638
|
+
await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
|
|
639
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
479
640
|
});
|
|
480
|
-
await runSandboxCommand(sandbox, `mkdir -p ${SANDBOX_PATHS.agentDir}`, QUICK_COMMAND_TIMEOUT_MS);
|
|
481
641
|
const { apt, commands } = this.dependencies;
|
|
482
642
|
if (apt && apt.length > 0) {
|
|
483
643
|
const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
|
|
484
|
-
const aptResult = await
|
|
644
|
+
const aptResult = await sandbox.runCommand(aptCmd, {
|
|
645
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
646
|
+
});
|
|
485
647
|
if (aptResult.exitCode !== 0) {
|
|
486
648
|
const details = [
|
|
487
649
|
`Failed to install apt packages: ${apt.join(", ")}`,
|
|
@@ -493,7 +655,9 @@ try {
|
|
|
493
655
|
}
|
|
494
656
|
if (commands && commands.length > 0) {
|
|
495
657
|
for (const cmd of commands) {
|
|
496
|
-
const cmdResult = await
|
|
658
|
+
const cmdResult = await sandbox.runCommand(cmd, {
|
|
659
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
660
|
+
});
|
|
497
661
|
if (cmdResult.exitCode !== 0) {
|
|
498
662
|
const details = [
|
|
499
663
|
`Failed to run command: ${cmd}`,
|
|
@@ -506,13 +670,17 @@ try {
|
|
|
506
670
|
}
|
|
507
671
|
if (this.files.length > 0) {
|
|
508
672
|
for (const file of this.files) {
|
|
509
|
-
const destPath = file.path.startsWith("/") ? file.path : `${
|
|
673
|
+
const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
|
|
510
674
|
const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
|
|
511
675
|
if (parentDir) {
|
|
512
|
-
await
|
|
676
|
+
await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
|
|
677
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
678
|
+
});
|
|
513
679
|
}
|
|
514
680
|
const curlCmd = `curl -fsSL -o ${shellEscape(destPath)} ${shellEscape(file.url)}`;
|
|
515
|
-
const downloadResult = await
|
|
681
|
+
const downloadResult = await sandbox.runCommand(curlCmd, {
|
|
682
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
683
|
+
});
|
|
516
684
|
if (downloadResult.exitCode !== 0) {
|
|
517
685
|
const details = [
|
|
518
686
|
`Failed to download file from ${file.url} to ${destPath}`,
|
|
@@ -525,36 +693,39 @@ try {
|
|
|
525
693
|
}
|
|
526
694
|
if (this.claudeDir) {
|
|
527
695
|
const claudeFiles = readDirectoryRecursively(this.claudeDir);
|
|
528
|
-
await
|
|
696
|
+
await sandbox.runCommand(`mkdir -p ${shellEscape(paths.claudeDir)}`, {
|
|
697
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
698
|
+
});
|
|
529
699
|
for (const file of claudeFiles) {
|
|
530
|
-
const destPath = `${
|
|
700
|
+
const destPath = `${paths.claudeDir}/${file.relativePath}`;
|
|
531
701
|
const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
|
|
532
|
-
if (parentDir && parentDir !==
|
|
533
|
-
await
|
|
702
|
+
if (parentDir && parentDir !== paths.claudeDir) {
|
|
703
|
+
await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
|
|
704
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
705
|
+
});
|
|
534
706
|
}
|
|
535
|
-
await sandbox.
|
|
707
|
+
await sandbox.writeFile(destPath, file.content);
|
|
536
708
|
}
|
|
537
709
|
}
|
|
538
|
-
await sandbox.
|
|
539
|
-
await sandbox.
|
|
710
|
+
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
711
|
+
await sandbox.writeFile(paths.runnerModule, runnerCode);
|
|
540
712
|
if (collectedExternals.size > 0) {
|
|
541
713
|
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
542
714
|
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
543
715
|
if (Object.keys(dependencies).length === 0) {
|
|
544
|
-
this._sandboxId = sandbox.
|
|
545
|
-
return
|
|
716
|
+
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
717
|
+
return sandbox.id;
|
|
546
718
|
}
|
|
547
719
|
const pkgJson = JSON.stringify({
|
|
548
720
|
name: "agent-sandbox",
|
|
549
721
|
type: "module",
|
|
550
722
|
dependencies
|
|
551
723
|
});
|
|
552
|
-
await sandbox.
|
|
553
|
-
const installResult = await
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
);
|
|
724
|
+
await sandbox.writeFile(paths.packageJson, pkgJson);
|
|
725
|
+
const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
|
|
726
|
+
cwd: paths.agentDir,
|
|
727
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
728
|
+
});
|
|
558
729
|
if (installResult.exitCode !== 0) {
|
|
559
730
|
const details = [
|
|
560
731
|
`Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
|
|
@@ -564,8 +735,8 @@ try {
|
|
|
564
735
|
throw new DeploymentError(details);
|
|
565
736
|
}
|
|
566
737
|
}
|
|
567
|
-
this._sandboxId = sandbox.
|
|
568
|
-
return
|
|
738
|
+
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
739
|
+
return sandbox.id;
|
|
569
740
|
}
|
|
570
741
|
/**
|
|
571
742
|
* Executes the agent with the given input.
|
|
@@ -600,20 +771,16 @@ try {
|
|
|
600
771
|
};
|
|
601
772
|
}
|
|
602
773
|
try {
|
|
603
|
-
const e2bApiKey = requireEnv("E2B_API_KEY");
|
|
604
|
-
const { Sandbox } = await getE2b();
|
|
605
774
|
const validatedInput = this.inputSchema.parse(input);
|
|
606
|
-
const sandbox = await
|
|
607
|
-
|
|
608
|
-
});
|
|
609
|
-
await sandbox.files.write(SANDBOX_PATHS.inputJson, JSON.stringify({ input: validatedInput, executionId }));
|
|
775
|
+
const sandbox = await this.connectSandboxHandle(sandboxId);
|
|
776
|
+
const { paths } = sandbox;
|
|
777
|
+
await sandbox.writeFile(paths.inputJson, JSON.stringify({ input: validatedInput, executionId }));
|
|
610
778
|
let capturedStdout = "";
|
|
611
779
|
let capturedStderr = "";
|
|
612
|
-
const result = await sandbox.
|
|
780
|
+
const result = await sandbox.runCommand("node runner.mjs", {
|
|
781
|
+
cwd: paths.agentDir,
|
|
613
782
|
timeoutMs: this.maxDuration * 1e3,
|
|
614
|
-
envs:
|
|
615
|
-
Object.entries(this.envs).filter(([_, v]) => v !== void 0).map(([k, v]) => [k, v])
|
|
616
|
-
),
|
|
783
|
+
envs: this.sandboxEnv,
|
|
617
784
|
onStdout: (data) => {
|
|
618
785
|
capturedStdout += data;
|
|
619
786
|
},
|
|
@@ -624,7 +791,7 @@ try {
|
|
|
624
791
|
if (result.exitCode !== 0) {
|
|
625
792
|
let resultError = "";
|
|
626
793
|
try {
|
|
627
|
-
const resultJson = await sandbox.
|
|
794
|
+
const resultJson = await sandbox.readFile(paths.outputJson);
|
|
628
795
|
const parsed = JSON.parse(resultJson);
|
|
629
796
|
if (!parsed.success && parsed.error) {
|
|
630
797
|
resultError = `
|
|
@@ -643,7 +810,7 @@ Stack: ${parsed.error.stack}`;
|
|
|
643
810
|
].filter(Boolean).join("\n");
|
|
644
811
|
return { ok: false, executionId, error: new ExecutionError(errorDetails) };
|
|
645
812
|
}
|
|
646
|
-
const output = JSON.parse(await sandbox.
|
|
813
|
+
const output = JSON.parse(await sandbox.readFile(paths.outputJson));
|
|
647
814
|
if (!output.success) {
|
|
648
815
|
const errorDetails = [
|
|
649
816
|
output.error.message,
|
|
@@ -670,5 +837,6 @@ Stdout: ${capturedStdout}` : ""
|
|
|
670
837
|
DeploymentError,
|
|
671
838
|
ExecutionError,
|
|
672
839
|
NeckbeardError,
|
|
673
|
-
ValidationError
|
|
840
|
+
ValidationError,
|
|
841
|
+
normalizeStackFramePath
|
|
674
842
|
});
|