agent-neckbeard 1.1.2 → 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/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 SANDBOX_HOME = "/home/user";
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 = resolveModulePath(importPath, resolveDir);
185
- if (!resolvedPath) return null;
186
- const packageJsonPath = await (0, import_pkg_types.resolvePackageJSON)((0, import_node_path.dirname)(resolvedPath), {
187
- test: isMainPackageJson
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: (0, import_node_path.dirname)(packageJsonPath),
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
- async function runSandboxCommand(sandbox, cmd, timeoutMs) {
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,19 +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
- 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
327
  const stack = new Error().stack?.split("\n") ?? [];
267
328
  for (const line of stack.slice(2)) {
268
329
  const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
269
- if (match) {
270
- let file = match[1];
271
- if (file.startsWith("file://")) file = (0, import_node_url.fileURLToPath)(file);
272
- if (internalFiles.has(file)) continue;
273
- if (!file.includes("node:") && !file.includes("node_modules/agent-neckbeard") && !file.includes("agent-neckbeard/dist")) return file;
274
- }
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;
275
338
  }
276
339
  throw new Error("Could not determine source file");
277
340
  }
@@ -301,6 +364,8 @@ function readDirectoryRecursively(dirPath) {
301
364
  return files;
302
365
  }
303
366
  var Agent = class {
367
+ sandbox;
368
+ provider;
304
369
  template;
305
370
  inputSchema;
306
371
  outputSchema;
@@ -315,7 +380,9 @@ var Agent = class {
315
380
  _sourceFile;
316
381
  _sandboxId;
317
382
  constructor(config) {
318
- this.template = config.template;
383
+ this.sandbox = config.sandbox;
384
+ this.provider = config.sandbox.provider;
385
+ this.template = config.sandbox.template;
319
386
  this.inputSchema = config.inputSchema;
320
387
  this.outputSchema = config.outputSchema;
321
388
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
@@ -330,15 +397,155 @@ var Agent = class {
330
397
  get sandboxId() {
331
398
  return this._sandboxId;
332
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
+ }
333
537
  /**
334
- * Deploys the agent to an E2B sandbox.
538
+ * Deploys the agent to a sandbox provider.
335
539
  *
336
- * This method bundles the agent code using esbuild, creates a new E2B sandbox,
540
+ * This method bundles the agent code using esbuild, creates a new sandbox,
337
541
  * installs any specified OS dependencies, downloads configured files, and
338
542
  * uploads the agent code to the sandbox.
339
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.
340
547
  * @returns The sandbox ID, which can be used to reconnect via `run(input, { sandboxId })`
341
- * @throws {ConfigurationError} If E2B_API_KEY environment variable is not set
548
+ * @throws {ConfigurationError} If the selected provider credentials are not set
342
549
  * @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
343
550
  *
344
551
  * @example
@@ -346,13 +553,16 @@ var Agent = class {
346
553
  * const agent = new Agent({ ... });
347
554
  * const sandboxId = await agent.deploy();
348
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);
349
561
  * ```
350
562
  */
351
- async deploy() {
352
- if (this._sandboxId) return this._sandboxId;
353
- const e2bApiKey = requireEnv("E2B_API_KEY");
563
+ async deploy(options) {
564
+ if (!options?.fresh && this._sandboxId) return this._sandboxId;
354
565
  const esbuild = await getEsbuild();
355
- const { Sandbox } = await getE2b();
356
566
  const externalPatterns = Array.from(
357
567
  /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
358
568
  );
@@ -420,68 +630,18 @@ var require = __neckbeard_createRequire(import.meta.url);
420
630
  }
421
631
  }]
422
632
  });
423
- const runnerCode = `
424
- import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
425
-
426
- const IO_DIR = '/home/user/io';
427
- const INPUT_FILE = IO_DIR + '/input.json';
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
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
479
638
  });
480
- await runSandboxCommand(sandbox, `mkdir -p ${SANDBOX_PATHS.agentDir}`, QUICK_COMMAND_TIMEOUT_MS);
481
639
  const { apt, commands } = this.dependencies;
482
640
  if (apt && apt.length > 0) {
483
641
  const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
484
- const aptResult = await runSandboxCommand(sandbox, aptCmd, SANDBOX_COMMAND_TIMEOUT_MS);
642
+ const aptResult = await sandbox.runCommand(aptCmd, {
643
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
644
+ });
485
645
  if (aptResult.exitCode !== 0) {
486
646
  const details = [
487
647
  `Failed to install apt packages: ${apt.join(", ")}`,
@@ -493,7 +653,9 @@ try {
493
653
  }
494
654
  if (commands && commands.length > 0) {
495
655
  for (const cmd of commands) {
496
- const cmdResult = await runSandboxCommand(sandbox, cmd, SANDBOX_COMMAND_TIMEOUT_MS);
656
+ const cmdResult = await sandbox.runCommand(cmd, {
657
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
658
+ });
497
659
  if (cmdResult.exitCode !== 0) {
498
660
  const details = [
499
661
  `Failed to run command: ${cmd}`,
@@ -506,13 +668,17 @@ try {
506
668
  }
507
669
  if (this.files.length > 0) {
508
670
  for (const file of this.files) {
509
- const destPath = file.path.startsWith("/") ? file.path : `${SANDBOX_HOME}/${file.path}`;
671
+ const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
510
672
  const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
511
673
  if (parentDir) {
512
- await runSandboxCommand(sandbox, `mkdir -p ${shellEscape(parentDir)}`, QUICK_COMMAND_TIMEOUT_MS);
674
+ await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
675
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
676
+ });
513
677
  }
514
678
  const curlCmd = `curl -fsSL -o ${shellEscape(destPath)} ${shellEscape(file.url)}`;
515
- const downloadResult = await runSandboxCommand(sandbox, curlCmd, SANDBOX_COMMAND_TIMEOUT_MS);
679
+ const downloadResult = await sandbox.runCommand(curlCmd, {
680
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
681
+ });
516
682
  if (downloadResult.exitCode !== 0) {
517
683
  const details = [
518
684
  `Failed to download file from ${file.url} to ${destPath}`,
@@ -525,36 +691,39 @@ try {
525
691
  }
526
692
  if (this.claudeDir) {
527
693
  const claudeFiles = readDirectoryRecursively(this.claudeDir);
528
- await runSandboxCommand(sandbox, `mkdir -p ${SANDBOX_PATHS.claudeDir}`, QUICK_COMMAND_TIMEOUT_MS);
694
+ await sandbox.runCommand(`mkdir -p ${shellEscape(paths.claudeDir)}`, {
695
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
696
+ });
529
697
  for (const file of claudeFiles) {
530
- const destPath = `${SANDBOX_PATHS.claudeDir}/${file.relativePath}`;
698
+ const destPath = `${paths.claudeDir}/${file.relativePath}`;
531
699
  const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
532
- if (parentDir && parentDir !== SANDBOX_PATHS.claudeDir) {
533
- await runSandboxCommand(sandbox, `mkdir -p ${shellEscape(parentDir)}`, QUICK_COMMAND_TIMEOUT_MS);
700
+ if (parentDir && parentDir !== paths.claudeDir) {
701
+ await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
702
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
703
+ });
534
704
  }
535
- await sandbox.files.write(destPath, file.content);
705
+ await sandbox.writeFile(destPath, file.content);
536
706
  }
537
707
  }
538
- await sandbox.files.write(SANDBOX_PATHS.agentModule, result.outputFiles[0].text);
539
- await sandbox.files.write(SANDBOX_PATHS.runnerModule, runnerCode);
708
+ await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
709
+ await sandbox.writeFile(paths.runnerModule, runnerCode);
540
710
  if (collectedExternals.size > 0) {
541
711
  const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
542
712
  const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
543
713
  if (Object.keys(dependencies).length === 0) {
544
- this._sandboxId = sandbox.sandboxId;
545
- return this._sandboxId;
714
+ if (!options?.fresh) this._sandboxId = sandbox.id;
715
+ return sandbox.id;
546
716
  }
547
717
  const pkgJson = JSON.stringify({
548
718
  name: "agent-sandbox",
549
719
  type: "module",
550
720
  dependencies
551
721
  });
552
- await sandbox.files.write(SANDBOX_PATHS.packageJson, pkgJson);
553
- const installResult = await runSandboxCommand(
554
- sandbox,
555
- `cd ${SANDBOX_PATHS.agentDir} && npm install --legacy-peer-deps`,
556
- SANDBOX_COMMAND_TIMEOUT_MS
557
- );
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
+ });
558
727
  if (installResult.exitCode !== 0) {
559
728
  const details = [
560
729
  `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
@@ -564,8 +733,8 @@ try {
564
733
  throw new DeploymentError(details);
565
734
  }
566
735
  }
567
- this._sandboxId = sandbox.sandboxId;
568
- return this._sandboxId;
736
+ if (!options?.fresh) this._sandboxId = sandbox.id;
737
+ return sandbox.id;
569
738
  }
570
739
  /**
571
740
  * Executes the agent with the given input.
@@ -600,20 +769,16 @@ try {
600
769
  };
601
770
  }
602
771
  try {
603
- const e2bApiKey = requireEnv("E2B_API_KEY");
604
- const { Sandbox } = await getE2b();
605
772
  const validatedInput = this.inputSchema.parse(input);
606
- const sandbox = await Sandbox.connect(sandboxId, {
607
- apiKey: e2bApiKey
608
- });
609
- 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 }));
610
776
  let capturedStdout = "";
611
777
  let capturedStderr = "";
612
- const result = await sandbox.commands.run(`cd ${SANDBOX_PATHS.agentDir} && node runner.mjs`, {
778
+ const result = await sandbox.runCommand("node runner.mjs", {
779
+ cwd: paths.agentDir,
613
780
  timeoutMs: this.maxDuration * 1e3,
614
- envs: Object.fromEntries(
615
- Object.entries(this.envs).filter(([_, v]) => v !== void 0).map(([k, v]) => [k, v])
616
- ),
781
+ envs: this.sandboxEnv,
617
782
  onStdout: (data) => {
618
783
  capturedStdout += data;
619
784
  },
@@ -624,7 +789,7 @@ try {
624
789
  if (result.exitCode !== 0) {
625
790
  let resultError = "";
626
791
  try {
627
- const resultJson = await sandbox.files.read(SANDBOX_PATHS.outputJson);
792
+ const resultJson = await sandbox.readFile(paths.outputJson);
628
793
  const parsed = JSON.parse(resultJson);
629
794
  if (!parsed.success && parsed.error) {
630
795
  resultError = `
@@ -643,7 +808,7 @@ Stack: ${parsed.error.stack}`;
643
808
  ].filter(Boolean).join("\n");
644
809
  return { ok: false, executionId, error: new ExecutionError(errorDetails) };
645
810
  }
646
- const output = JSON.parse(await sandbox.files.read(SANDBOX_PATHS.outputJson));
811
+ const output = JSON.parse(await sandbox.readFile(paths.outputJson));
647
812
  if (!output.success) {
648
813
  const errorDetails = [
649
814
  output.error.message,
@@ -670,5 +835,6 @@ Stdout: ${capturedStdout}` : ""
670
835
  DeploymentError,
671
836
  ExecutionError,
672
837
  NeckbeardError,
673
- ValidationError
838
+ ValidationError,
839
+ normalizeStackFramePath
674
840
  });