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