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