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/dist/index.js CHANGED
@@ -1,39 +1,24 @@
1
1
  // src/index.ts
2
- import { fileURLToPath, pathToFileURL } from "url";
2
+ import { fileURLToPath } from "url";
3
3
  import { existsSync, readdirSync, readFileSync, statSync } from "fs";
4
- import { dirname, join, relative } from "path";
4
+ import { dirname, join, relative, resolve } from "path";
5
5
  import { builtinModules, createRequire } from "module";
6
- import { readPackageJSON, resolvePackageJSON } from "pkg-types";
6
+ function readPackageJson(path) {
7
+ return JSON.parse(readFileSync(path, "utf8"));
8
+ }
7
9
  var getEsbuild = () => import("esbuild");
8
10
  var getE2b = () => import("e2b");
11
+ var getDaytona = () => import("@daytona/sdk");
9
12
  var DEFAULT_MAX_DURATION = 300;
10
13
  var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
11
14
  var QUICK_COMMAND_TIMEOUT_MS = 3e4;
15
+ var DAYTONA_CREATE_TIMEOUT_SEC = 120;
12
16
  var NODE_TARGET = "node20";
13
17
  var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
14
18
  var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
15
19
  var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
16
20
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
17
- var SANDBOX_HOME = "/home/user";
18
- var SANDBOX_AGENT_DIR = `${SANDBOX_HOME}/agent`;
19
- var SANDBOX_PATHS = {
20
- /** Agent code directory */
21
- agentDir: SANDBOX_AGENT_DIR,
22
- /** I/O directory for input/output files */
23
- ioDir: `${SANDBOX_HOME}/io`,
24
- /** Task input file */
25
- inputJson: `${SANDBOX_HOME}/io/input.json`,
26
- /** Result output file (contains success/error) */
27
- outputJson: `${SANDBOX_HOME}/io/output.json`,
28
- /** Bundled agent module */
29
- agentModule: `${SANDBOX_AGENT_DIR}/agent.mjs`,
30
- /** Runner module that executes the agent */
31
- runnerModule: `${SANDBOX_AGENT_DIR}/runner.mjs`,
32
- /** Claude skills and settings directory */
33
- claudeDir: `${SANDBOX_AGENT_DIR}/.claude`,
34
- /** Package.json for npm dependencies */
35
- packageJson: `${SANDBOX_AGENT_DIR}/package.json`
36
- };
21
+ var E2B_SANDBOX_HOME = "/home/user";
37
22
  var NeckbeardError = class extends Error {
38
23
  constructor(message) {
39
24
  super(message);
@@ -80,9 +65,7 @@ function requireEnv(name) {
80
65
  function shellEscape(str) {
81
66
  return `'${str.replace(/'/g, "'\\''")}'`;
82
67
  }
83
- var require2 = createRequire(
84
- typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url)
85
- );
68
+ var require2 = createRequire(join(process.cwd(), "__agent_neckbeard__.cjs"));
86
69
  function isBareModuleImport(path) {
87
70
  const excludes = [".", "/", "~", "file:", "data:"];
88
71
  return !excludes.some((exclude) => path.startsWith(exclude));
@@ -93,25 +76,6 @@ function packageNameForImportPath(importPath) {
93
76
  }
94
77
  return importPath.split("/")[0];
95
78
  }
96
- function resolveModulePath(importPath, resolveDir) {
97
- try {
98
- return require2.resolve(importPath, { paths: [resolveDir] });
99
- } catch {
100
- const importMeta = import.meta ?? void 0;
101
- const resolver = importMeta && typeof importMeta.resolve === "function" ? importMeta.resolve.bind(importMeta) : void 0;
102
- if (!resolver) return null;
103
- try {
104
- const parentUrl = pathToFileURL(join(resolveDir, "__neckbeard__.js"));
105
- const resolved = resolver(importPath, parentUrl);
106
- if (resolved.startsWith("file://")) {
107
- return fileURLToPath(resolved);
108
- }
109
- } catch {
110
- return null;
111
- }
112
- }
113
- return null;
114
- }
115
79
  function globToRegExp(pattern) {
116
80
  const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
117
81
  return new RegExp(`^${escaped}$`);
@@ -119,39 +83,33 @@ function globToRegExp(pattern) {
119
83
  function matchesExternal(matchers, pkgName) {
120
84
  return matchers.some((re) => re.test(pkgName));
121
85
  }
122
- async function isMainPackageJson(filePath) {
123
- try {
124
- const packageJson = await readPackageJSON(filePath);
125
- const markerFields = /* @__PURE__ */ new Set([
126
- "type",
127
- "sideEffects",
128
- "browser",
129
- "main",
130
- "module",
131
- "react-native",
132
- "name"
133
- ]);
134
- if (!packageJson.type) return true;
135
- const keys = Object.keys(packageJson);
136
- return !keys.every((k) => markerFields.has(k));
137
- } catch {
138
- return false;
139
- }
140
- }
141
86
  async function resolvePackageInfo(importPath, resolveDir) {
142
87
  try {
143
- const resolvedPath = resolveModulePath(importPath, resolveDir);
144
- if (!resolvedPath) return null;
145
- const packageJsonPath = await resolvePackageJSON(dirname(resolvedPath), {
146
- test: isMainPackageJson
147
- });
88
+ const resolvedPath = require2.resolve(importPath, { paths: [resolveDir] });
89
+ const packageName = packageNameForImportPath(importPath);
90
+ let root = dirname(resolvedPath);
91
+ let packageJsonPath = null;
92
+ while (true) {
93
+ const candidate = join(root, "package.json");
94
+ if (existsSync(candidate)) {
95
+ const candidatePackageJson = readPackageJson(candidate);
96
+ if (candidatePackageJson.name === packageName) {
97
+ packageJsonPath = candidate;
98
+ break;
99
+ }
100
+ }
101
+ const parent = dirname(root);
102
+ if (parent === root) break;
103
+ root = parent;
104
+ }
148
105
  if (!packageJsonPath) return null;
149
- const packageJson = await readPackageJSON(packageJsonPath);
106
+ const packageJson = readPackageJson(packageJsonPath);
150
107
  if (!packageJson.name || !packageJson.version) return null;
108
+ root = dirname(packageJsonPath);
151
109
  return {
152
110
  name: packageJson.name,
153
111
  version: packageJson.version,
154
- root: dirname(packageJsonPath),
112
+ root,
155
113
  resolvedPath,
156
114
  packageJson
157
115
  };
@@ -190,17 +148,67 @@ function isPackageCompatible(info) {
190
148
  const cpuList = normalizeList(info.packageJson.cpu);
191
149
  return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
192
150
  }
193
- async function runSandboxCommand(sandbox, cmd, timeoutMs) {
151
+ function filterDefinedEnvs(envs) {
152
+ return Object.fromEntries(
153
+ Object.entries(envs).filter(([_, value]) => value !== void 0).map(([key, value]) => [key, value])
154
+ );
155
+ }
156
+ function arrayBufferToBuffer(value) {
157
+ return Buffer.from(value);
158
+ }
159
+ function toDaytonaUploadContent(content) {
160
+ if (typeof content === "string") return Buffer.from(content);
161
+ if (Buffer.isBuffer(content)) return content;
162
+ if (content instanceof Uint8Array) return Buffer.from(content);
163
+ return arrayBufferToBuffer(content);
164
+ }
165
+ function toE2bWriteContent(content) {
166
+ if (typeof content === "string") return content;
167
+ if (content instanceof ArrayBuffer) return content;
168
+ return Uint8Array.from(content).buffer;
169
+ }
170
+ function createSandboxPaths(provider, homeDir, workDir) {
171
+ const agentDir = `${homeDir}/agent`;
172
+ const ioDir = `${homeDir}/io`;
173
+ return {
174
+ provider,
175
+ homeDir,
176
+ workDir,
177
+ agentDir,
178
+ ioDir,
179
+ inputJson: `${ioDir}/input.json`,
180
+ outputJson: `${ioDir}/output.json`,
181
+ agentModule: `${agentDir}/agent.mjs`,
182
+ runnerModule: `${agentDir}/runner.mjs`,
183
+ claudeDir: `${agentDir}/.claude`,
184
+ packageJson: `${agentDir}/package.json`
185
+ };
186
+ }
187
+ function timeoutMsToSeconds(timeoutMs) {
188
+ return Math.max(1, Math.ceil(timeoutMs / 1e3));
189
+ }
190
+ async function resolveDaytonaPaths(sandbox) {
191
+ const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
192
+ const homeDir = await sandbox.getUserHomeDir() ?? workDir;
193
+ if (!homeDir || !workDir) {
194
+ throw new DeploymentError("Daytona sandbox did not report a home or working directory.");
195
+ }
196
+ return createSandboxPaths("daytona", homeDir, workDir);
197
+ }
198
+ async function runE2bCommand(sandbox, cmd, options) {
194
199
  let stdout = "";
195
200
  let stderr = "";
196
201
  try {
197
202
  const result = await sandbox.commands.run(cmd, {
198
- timeoutMs,
203
+ timeoutMs: options.timeoutMs,
204
+ envs: options.envs,
199
205
  onStdout: (data) => {
200
206
  stdout += data;
207
+ options.onStdout?.(data);
201
208
  },
202
209
  onStderr: (data) => {
203
210
  stderr += data;
211
+ options.onStderr?.(data);
204
212
  }
205
213
  });
206
214
  return {
@@ -218,19 +226,76 @@ async function runSandboxCommand(sandbox, cmd, timeoutMs) {
218
226
  };
219
227
  }
220
228
  }
229
+ function createE2bHandle(sandbox) {
230
+ const paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
231
+ return {
232
+ id: sandbox.sandboxId,
233
+ paths,
234
+ writeFile: (path, content) => sandbox.files.write(path, toE2bWriteContent(content)),
235
+ readFile: (path) => sandbox.files.read(path),
236
+ runCommand: (cmd, options) => {
237
+ const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
238
+ return runE2bCommand(sandbox, command, options);
239
+ },
240
+ destroy: () => sandbox.kill()
241
+ };
242
+ }
243
+ async function createDaytonaHandle(sandbox) {
244
+ const paths = await resolveDaytonaPaths(sandbox);
245
+ return {
246
+ id: sandbox.id,
247
+ paths,
248
+ writeFile: (path, content) => sandbox.fs.uploadFile(
249
+ toDaytonaUploadContent(content),
250
+ path,
251
+ timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
252
+ ),
253
+ readFile: async (path) => {
254
+ const content = await sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
255
+ return content.toString("utf-8");
256
+ },
257
+ runCommand: async (cmd, options) => {
258
+ const result = await sandbox.process.executeCommand(
259
+ cmd,
260
+ options.cwd,
261
+ options.envs,
262
+ timeoutMsToSeconds(options.timeoutMs)
263
+ );
264
+ const stdout = result.artifacts?.stdout ?? result.result ?? "";
265
+ if (stdout) options.onStdout?.(stdout);
266
+ return {
267
+ exitCode: result.exitCode,
268
+ stdout,
269
+ stderr: ""
270
+ };
271
+ },
272
+ destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
273
+ };
274
+ }
275
+ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
276
+ if (rawPath.startsWith("file://")) {
277
+ return fileURLToPath(rawPath);
278
+ }
279
+ if (rawPath.startsWith("webpack-internal:")) {
280
+ const afterScheme = rawPath.replace(/^webpack-internal:\/+/, "");
281
+ const afterLayer = afterScheme.replace(/^\([^)]+\)\//, "");
282
+ const resolved = resolve(cwd, afterLayer);
283
+ return existsSync(resolved) ? resolved : null;
284
+ }
285
+ return rawPath;
286
+ }
221
287
  function getCallerFile() {
222
- const internalFiles = /* @__PURE__ */ new Set();
223
- const currentFile = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
224
- internalFiles.add(currentFile);
225
288
  const stack = new Error().stack?.split("\n") ?? [];
226
289
  for (const line of stack.slice(2)) {
227
290
  const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
228
- if (match) {
229
- let file = match[1];
230
- if (file.startsWith("file://")) file = fileURLToPath(file);
231
- if (internalFiles.has(file)) continue;
232
- if (!file.includes("node:") && !file.includes("node_modules/agent-neckbeard") && !file.includes("agent-neckbeard/dist")) return file;
233
- }
291
+ if (!match) continue;
292
+ const file = normalizeStackFramePath(match[1]);
293
+ if (!file) continue;
294
+ if (file.includes("node:")) continue;
295
+ if (file.includes("node_modules/agent-neckbeard")) continue;
296
+ if (file.includes("agent-neckbeard/dist")) continue;
297
+ if (file.endsWith("/src/index.ts")) continue;
298
+ return file;
234
299
  }
235
300
  throw new Error("Could not determine source file");
236
301
  }
@@ -260,6 +325,8 @@ function readDirectoryRecursively(dirPath) {
260
325
  return files;
261
326
  }
262
327
  var Agent = class {
328
+ sandbox;
329
+ provider;
263
330
  template;
264
331
  inputSchema;
265
332
  outputSchema;
@@ -274,7 +341,9 @@ var Agent = class {
274
341
  _sourceFile;
275
342
  _sandboxId;
276
343
  constructor(config) {
277
- this.template = config.template;
344
+ this.sandbox = config.sandbox;
345
+ this.provider = config.sandbox.provider;
346
+ this.template = config.sandbox.template;
278
347
  this.inputSchema = config.inputSchema;
279
348
  this.outputSchema = config.outputSchema;
280
349
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
@@ -289,15 +358,155 @@ var Agent = class {
289
358
  get sandboxId() {
290
359
  return this._sandboxId;
291
360
  }
361
+ get sandboxEnv() {
362
+ return filterDefinedEnvs(this.envs);
363
+ }
364
+ async createSandboxHandle() {
365
+ if (this.provider === "daytona") {
366
+ const apiKey2 = requireEnv("DAYTONA_API_KEY");
367
+ const { Daytona } = await getDaytona();
368
+ const daytona = new Daytona({ apiKey: apiKey2 });
369
+ const sandbox2 = await daytona.create(
370
+ {
371
+ snapshot: this.template,
372
+ envVars: this.sandboxEnv,
373
+ autoDeleteInterval: -1
374
+ },
375
+ { timeout: DAYTONA_CREATE_TIMEOUT_SEC }
376
+ );
377
+ return createDaytonaHandle(sandbox2);
378
+ }
379
+ const apiKey = requireEnv("E2B_API_KEY");
380
+ const { Sandbox } = await getE2b();
381
+ const sandbox = await Sandbox.create(this.template, { apiKey });
382
+ return createE2bHandle(sandbox);
383
+ }
384
+ async connectSandboxHandle(sandboxId) {
385
+ if (this.provider === "daytona") {
386
+ const apiKey2 = requireEnv("DAYTONA_API_KEY");
387
+ const { Daytona } = await getDaytona();
388
+ const daytona = new Daytona({ apiKey: apiKey2 });
389
+ const sandbox2 = await daytona.get(sandboxId);
390
+ if (sandbox2.state !== "started") {
391
+ if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
392
+ await sandbox2.waitUntilStarted?.(DAYTONA_CREATE_TIMEOUT_SEC);
393
+ } else {
394
+ await sandbox2.start?.(DAYTONA_CREATE_TIMEOUT_SEC);
395
+ }
396
+ }
397
+ return createDaytonaHandle(sandbox2);
398
+ }
399
+ const apiKey = requireEnv("E2B_API_KEY");
400
+ const { Sandbox } = await getE2b();
401
+ const sandbox = await Sandbox.connect(sandboxId, { apiKey });
402
+ return createE2bHandle(sandbox);
403
+ }
404
+ buildRunnerCode(paths) {
405
+ const sandboxContext = JSON.stringify({
406
+ provider: paths.provider,
407
+ homeDir: paths.homeDir,
408
+ workDir: paths.workDir,
409
+ agentDir: paths.agentDir,
410
+ ioDir: paths.ioDir,
411
+ inputJson: paths.inputJson,
412
+ outputJson: paths.outputJson
413
+ });
414
+ return `
415
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
416
+
417
+ const SANDBOX_CONTEXT = ${sandboxContext};
418
+ const IO_DIR = SANDBOX_CONTEXT.ioDir;
419
+ const INPUT_FILE = SANDBOX_CONTEXT.inputJson;
420
+ const OUTPUT_FILE = SANDBOX_CONTEXT.outputJson;
421
+
422
+ mkdirSync(IO_DIR, { recursive: true });
423
+
424
+ let input, executionId;
425
+ try {
426
+ const taskData = JSON.parse(readFileSync(INPUT_FILE, 'utf-8'));
427
+ input = taskData.input;
428
+ executionId = taskData.executionId;
429
+ } catch (parseError) {
430
+ writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Task parse failed: ' + parseError.message, stack: parseError.stack } }));
431
+ process.exit(0);
432
+ }
433
+
434
+ let mod;
435
+ try {
436
+ mod = await import('./agent.mjs');
437
+ } catch (importError) {
438
+ writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Import failed: ' + importError.message, stack: importError.stack } }));
439
+ process.exit(0);
440
+ }
441
+
442
+ const agent = mod.default || Object.values(mod).find(v => v instanceof Object && v._run);
443
+ if (!agent) {
444
+ writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'No agent found in module. Exports: ' + Object.keys(mod).join(', ') } }));
445
+ process.exit(0);
446
+ }
447
+
448
+ const ctx = {
449
+ executionId,
450
+ signal: AbortSignal.timeout(${this.maxDuration * 1e3}),
451
+ env: process.env,
452
+ sandbox: SANDBOX_CONTEXT,
453
+ logger: {
454
+ debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
455
+ info: (msg, ...args) => console.log('[INFO]', msg, ...args),
456
+ warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
457
+ error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
458
+ },
459
+ };
460
+
461
+ try {
462
+ const validated = agent.inputSchema.parse(input);
463
+ const output = await agent._run(validated, ctx);
464
+ const validatedOutput = agent.outputSchema.parse(output);
465
+ writeFileSync(OUTPUT_FILE, JSON.stringify({ success: true, output: validatedOutput }));
466
+ } catch (error) {
467
+ writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: error.message, stack: error.stack } }));
468
+ }
469
+ `;
470
+ }
471
+ /**
472
+ * Kills the current sandbox and resets the cached sandbox ID.
473
+ *
474
+ * Use this to clean up sandbox resources after a run, especially when
475
+ * running multiple evaluations that each need their own sandbox.
476
+ *
477
+ * @param sandboxId - Optional sandbox ID to kill. Defaults to the cached sandbox.
478
+ *
479
+ * @example
480
+ * ```typescript
481
+ * const sandboxId = await agent.deploy();
482
+ * const result = await agent.run(input, { sandboxId });
483
+ * await agent.kill(sandboxId);
484
+ * ```
485
+ */
486
+ async kill(sandboxId) {
487
+ const targetId = sandboxId ?? this._sandboxId;
488
+ if (!targetId) return;
489
+ try {
490
+ const sandbox = await this.connectSandboxHandle(targetId);
491
+ await sandbox.destroy();
492
+ } catch {
493
+ }
494
+ if (targetId === this._sandboxId) {
495
+ this._sandboxId = void 0;
496
+ }
497
+ }
292
498
  /**
293
- * Deploys the agent to an E2B sandbox.
499
+ * Deploys the agent to a sandbox provider.
294
500
  *
295
- * This method bundles the agent code using esbuild, creates a new E2B sandbox,
501
+ * This method bundles the agent code using esbuild, creates a new sandbox,
296
502
  * installs any specified OS dependencies, downloads configured files, and
297
503
  * uploads the agent code to the sandbox.
298
504
  *
505
+ * @param options.fresh - When true, always creates a new sandbox without caching.
506
+ * Useful for concurrent evaluations where each run needs its own sandbox.
507
+ * The returned sandbox ID won't be stored on the instance.
299
508
  * @returns The sandbox ID, which can be used to reconnect via `run(input, { sandboxId })`
300
- * @throws {ConfigurationError} If E2B_API_KEY environment variable is not set
509
+ * @throws {ConfigurationError} If the selected provider credentials are not set
301
510
  * @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
302
511
  *
303
512
  * @example
@@ -305,13 +514,16 @@ var Agent = class {
305
514
  * const agent = new Agent({ ... });
306
515
  * const sandboxId = await agent.deploy();
307
516
  * console.log(`Deployed to sandbox: ${sandboxId}`);
517
+ *
518
+ * // For concurrent evals: each call gets its own sandbox
519
+ * const id = await agent.deploy({ fresh: true });
520
+ * const result = await agent.run(input, { sandboxId: id });
521
+ * await agent.kill(id);
308
522
  * ```
309
523
  */
310
- async deploy() {
311
- if (this._sandboxId) return this._sandboxId;
312
- const e2bApiKey = requireEnv("E2B_API_KEY");
524
+ async deploy(options) {
525
+ if (!options?.fresh && this._sandboxId) return this._sandboxId;
313
526
  const esbuild = await getEsbuild();
314
- const { Sandbox } = await getE2b();
315
527
  const externalPatterns = Array.from(
316
528
  /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
317
529
  );
@@ -379,68 +591,18 @@ var require = __neckbeard_createRequire(import.meta.url);
379
591
  }
380
592
  }]
381
593
  });
382
- const runnerCode = `
383
- import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
384
-
385
- const IO_DIR = '/home/user/io';
386
- const INPUT_FILE = IO_DIR + '/input.json';
387
- const OUTPUT_FILE = IO_DIR + '/output.json';
388
-
389
- mkdirSync(IO_DIR, { recursive: true });
390
-
391
- let input, executionId;
392
- try {
393
- const taskData = JSON.parse(readFileSync(INPUT_FILE, 'utf-8'));
394
- input = taskData.input;
395
- executionId = taskData.executionId;
396
- } catch (parseError) {
397
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Task parse failed: ' + parseError.message, stack: parseError.stack } }));
398
- process.exit(0);
399
- }
400
-
401
- let mod;
402
- try {
403
- mod = await import('./agent.mjs');
404
- } catch (importError) {
405
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Import failed: ' + importError.message, stack: importError.stack } }));
406
- process.exit(0);
407
- }
408
-
409
- const agent = mod.default || Object.values(mod).find(v => v instanceof Object && v._run);
410
- if (!agent) {
411
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'No agent found in module. Exports: ' + Object.keys(mod).join(', ') } }));
412
- process.exit(0);
413
- }
414
-
415
- const ctx = {
416
- executionId,
417
- signal: AbortSignal.timeout(${this.maxDuration * 1e3}),
418
- env: process.env,
419
- logger: {
420
- debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
421
- info: (msg, ...args) => console.log('[INFO]', msg, ...args),
422
- warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
423
- error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
424
- },
425
- };
426
-
427
- try {
428
- const validated = agent.inputSchema.parse(input);
429
- const output = await agent._run(validated, ctx);
430
- const validatedOutput = agent.outputSchema.parse(output);
431
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: true, output: validatedOutput }));
432
- } catch (error) {
433
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: error.message, stack: error.stack } }));
434
- }
435
- `;
436
- const sandbox = await Sandbox.create(this.template, {
437
- apiKey: e2bApiKey
594
+ const sandbox = await this.createSandboxHandle();
595
+ const { paths } = sandbox;
596
+ const runnerCode = this.buildRunnerCode(paths);
597
+ await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
598
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
438
599
  });
439
- await runSandboxCommand(sandbox, `mkdir -p ${SANDBOX_PATHS.agentDir}`, QUICK_COMMAND_TIMEOUT_MS);
440
600
  const { apt, commands } = this.dependencies;
441
601
  if (apt && apt.length > 0) {
442
602
  const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
443
- const aptResult = await runSandboxCommand(sandbox, aptCmd, SANDBOX_COMMAND_TIMEOUT_MS);
603
+ const aptResult = await sandbox.runCommand(aptCmd, {
604
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
605
+ });
444
606
  if (aptResult.exitCode !== 0) {
445
607
  const details = [
446
608
  `Failed to install apt packages: ${apt.join(", ")}`,
@@ -452,7 +614,9 @@ try {
452
614
  }
453
615
  if (commands && commands.length > 0) {
454
616
  for (const cmd of commands) {
455
- const cmdResult = await runSandboxCommand(sandbox, cmd, SANDBOX_COMMAND_TIMEOUT_MS);
617
+ const cmdResult = await sandbox.runCommand(cmd, {
618
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
619
+ });
456
620
  if (cmdResult.exitCode !== 0) {
457
621
  const details = [
458
622
  `Failed to run command: ${cmd}`,
@@ -465,13 +629,17 @@ try {
465
629
  }
466
630
  if (this.files.length > 0) {
467
631
  for (const file of this.files) {
468
- const destPath = file.path.startsWith("/") ? file.path : `${SANDBOX_HOME}/${file.path}`;
632
+ const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
469
633
  const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
470
634
  if (parentDir) {
471
- await runSandboxCommand(sandbox, `mkdir -p ${shellEscape(parentDir)}`, QUICK_COMMAND_TIMEOUT_MS);
635
+ await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
636
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
637
+ });
472
638
  }
473
639
  const curlCmd = `curl -fsSL -o ${shellEscape(destPath)} ${shellEscape(file.url)}`;
474
- const downloadResult = await runSandboxCommand(sandbox, curlCmd, SANDBOX_COMMAND_TIMEOUT_MS);
640
+ const downloadResult = await sandbox.runCommand(curlCmd, {
641
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
642
+ });
475
643
  if (downloadResult.exitCode !== 0) {
476
644
  const details = [
477
645
  `Failed to download file from ${file.url} to ${destPath}`,
@@ -484,36 +652,39 @@ try {
484
652
  }
485
653
  if (this.claudeDir) {
486
654
  const claudeFiles = readDirectoryRecursively(this.claudeDir);
487
- await runSandboxCommand(sandbox, `mkdir -p ${SANDBOX_PATHS.claudeDir}`, QUICK_COMMAND_TIMEOUT_MS);
655
+ await sandbox.runCommand(`mkdir -p ${shellEscape(paths.claudeDir)}`, {
656
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
657
+ });
488
658
  for (const file of claudeFiles) {
489
- const destPath = `${SANDBOX_PATHS.claudeDir}/${file.relativePath}`;
659
+ const destPath = `${paths.claudeDir}/${file.relativePath}`;
490
660
  const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
491
- if (parentDir && parentDir !== SANDBOX_PATHS.claudeDir) {
492
- await runSandboxCommand(sandbox, `mkdir -p ${shellEscape(parentDir)}`, QUICK_COMMAND_TIMEOUT_MS);
661
+ if (parentDir && parentDir !== paths.claudeDir) {
662
+ await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
663
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
664
+ });
493
665
  }
494
- await sandbox.files.write(destPath, file.content);
666
+ await sandbox.writeFile(destPath, file.content);
495
667
  }
496
668
  }
497
- await sandbox.files.write(SANDBOX_PATHS.agentModule, result.outputFiles[0].text);
498
- await sandbox.files.write(SANDBOX_PATHS.runnerModule, runnerCode);
669
+ await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
670
+ await sandbox.writeFile(paths.runnerModule, runnerCode);
499
671
  if (collectedExternals.size > 0) {
500
672
  const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
501
673
  const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
502
674
  if (Object.keys(dependencies).length === 0) {
503
- this._sandboxId = sandbox.sandboxId;
504
- return this._sandboxId;
675
+ if (!options?.fresh) this._sandboxId = sandbox.id;
676
+ return sandbox.id;
505
677
  }
506
678
  const pkgJson = JSON.stringify({
507
679
  name: "agent-sandbox",
508
680
  type: "module",
509
681
  dependencies
510
682
  });
511
- await sandbox.files.write(SANDBOX_PATHS.packageJson, pkgJson);
512
- const installResult = await runSandboxCommand(
513
- sandbox,
514
- `cd ${SANDBOX_PATHS.agentDir} && npm install --legacy-peer-deps`,
515
- SANDBOX_COMMAND_TIMEOUT_MS
516
- );
683
+ await sandbox.writeFile(paths.packageJson, pkgJson);
684
+ const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
685
+ cwd: paths.agentDir,
686
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
687
+ });
517
688
  if (installResult.exitCode !== 0) {
518
689
  const details = [
519
690
  `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
@@ -523,8 +694,8 @@ try {
523
694
  throw new DeploymentError(details);
524
695
  }
525
696
  }
526
- this._sandboxId = sandbox.sandboxId;
527
- return this._sandboxId;
697
+ if (!options?.fresh) this._sandboxId = sandbox.id;
698
+ return sandbox.id;
528
699
  }
529
700
  /**
530
701
  * Executes the agent with the given input.
@@ -559,20 +730,16 @@ try {
559
730
  };
560
731
  }
561
732
  try {
562
- const e2bApiKey = requireEnv("E2B_API_KEY");
563
- const { Sandbox } = await getE2b();
564
733
  const validatedInput = this.inputSchema.parse(input);
565
- const sandbox = await Sandbox.connect(sandboxId, {
566
- apiKey: e2bApiKey
567
- });
568
- await sandbox.files.write(SANDBOX_PATHS.inputJson, JSON.stringify({ input: validatedInput, executionId }));
734
+ const sandbox = await this.connectSandboxHandle(sandboxId);
735
+ const { paths } = sandbox;
736
+ await sandbox.writeFile(paths.inputJson, JSON.stringify({ input: validatedInput, executionId }));
569
737
  let capturedStdout = "";
570
738
  let capturedStderr = "";
571
- const result = await sandbox.commands.run(`cd ${SANDBOX_PATHS.agentDir} && node runner.mjs`, {
739
+ const result = await sandbox.runCommand("node runner.mjs", {
740
+ cwd: paths.agentDir,
572
741
  timeoutMs: this.maxDuration * 1e3,
573
- envs: Object.fromEntries(
574
- Object.entries(this.envs).filter(([_, v]) => v !== void 0).map(([k, v]) => [k, v])
575
- ),
742
+ envs: this.sandboxEnv,
576
743
  onStdout: (data) => {
577
744
  capturedStdout += data;
578
745
  },
@@ -583,7 +750,7 @@ try {
583
750
  if (result.exitCode !== 0) {
584
751
  let resultError = "";
585
752
  try {
586
- const resultJson = await sandbox.files.read(SANDBOX_PATHS.outputJson);
753
+ const resultJson = await sandbox.readFile(paths.outputJson);
587
754
  const parsed = JSON.parse(resultJson);
588
755
  if (!parsed.success && parsed.error) {
589
756
  resultError = `
@@ -602,7 +769,7 @@ Stack: ${parsed.error.stack}`;
602
769
  ].filter(Boolean).join("\n");
603
770
  return { ok: false, executionId, error: new ExecutionError(errorDetails) };
604
771
  }
605
- const output = JSON.parse(await sandbox.files.read(SANDBOX_PATHS.outputJson));
772
+ const output = JSON.parse(await sandbox.readFile(paths.outputJson));
606
773
  if (!output.success) {
607
774
  const errorDetails = [
608
775
  output.error.message,
@@ -628,5 +795,6 @@ export {
628
795
  DeploymentError,
629
796
  ExecutionError,
630
797
  NeckbeardError,
631
- ValidationError
798
+ ValidationError,
799
+ normalizeStackFramePath
632
800
  };