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/README.md +32 -10
- package/dist/index.cjs +346 -180
- package/dist/index.d.cts +96 -25
- package/dist/index.d.ts +96 -25
- package/dist/index.js +347 -181
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -1,39 +1,22 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { fileURLToPath
|
|
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
|
|
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
|
|
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 =
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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
|
|
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
|
-
|
|
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,19 +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
|
-
const internalFiles = /* @__PURE__ */ new Set();
|
|
223
|
-
const currentFile = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
|
|
224
|
-
internalFiles.add(currentFile);
|
|
225
286
|
const stack = new Error().stack?.split("\n") ?? [];
|
|
226
287
|
for (const line of stack.slice(2)) {
|
|
227
288
|
const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
|
|
228
|
-
if (match)
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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;
|
|
234
297
|
}
|
|
235
298
|
throw new Error("Could not determine source file");
|
|
236
299
|
}
|
|
@@ -260,6 +323,8 @@ function readDirectoryRecursively(dirPath) {
|
|
|
260
323
|
return files;
|
|
261
324
|
}
|
|
262
325
|
var Agent = class {
|
|
326
|
+
sandbox;
|
|
327
|
+
provider;
|
|
263
328
|
template;
|
|
264
329
|
inputSchema;
|
|
265
330
|
outputSchema;
|
|
@@ -274,7 +339,9 @@ var Agent = class {
|
|
|
274
339
|
_sourceFile;
|
|
275
340
|
_sandboxId;
|
|
276
341
|
constructor(config) {
|
|
277
|
-
this.
|
|
342
|
+
this.sandbox = config.sandbox;
|
|
343
|
+
this.provider = config.sandbox.provider;
|
|
344
|
+
this.template = config.sandbox.template;
|
|
278
345
|
this.inputSchema = config.inputSchema;
|
|
279
346
|
this.outputSchema = config.outputSchema;
|
|
280
347
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
@@ -289,15 +356,155 @@ var Agent = class {
|
|
|
289
356
|
get sandboxId() {
|
|
290
357
|
return this._sandboxId;
|
|
291
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
|
+
}
|
|
292
496
|
/**
|
|
293
|
-
* Deploys the agent to
|
|
497
|
+
* Deploys the agent to a sandbox provider.
|
|
294
498
|
*
|
|
295
|
-
* This method bundles the agent code using esbuild, creates a new
|
|
499
|
+
* This method bundles the agent code using esbuild, creates a new sandbox,
|
|
296
500
|
* installs any specified OS dependencies, downloads configured files, and
|
|
297
501
|
* uploads the agent code to the sandbox.
|
|
298
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.
|
|
299
506
|
* @returns The sandbox ID, which can be used to reconnect via `run(input, { sandboxId })`
|
|
300
|
-
* @throws {ConfigurationError} If
|
|
507
|
+
* @throws {ConfigurationError} If the selected provider credentials are not set
|
|
301
508
|
* @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
|
|
302
509
|
*
|
|
303
510
|
* @example
|
|
@@ -305,13 +512,16 @@ var Agent = class {
|
|
|
305
512
|
* const agent = new Agent({ ... });
|
|
306
513
|
* const sandboxId = await agent.deploy();
|
|
307
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);
|
|
308
520
|
* ```
|
|
309
521
|
*/
|
|
310
|
-
async deploy() {
|
|
311
|
-
if (this._sandboxId) return this._sandboxId;
|
|
312
|
-
const e2bApiKey = requireEnv("E2B_API_KEY");
|
|
522
|
+
async deploy(options) {
|
|
523
|
+
if (!options?.fresh && this._sandboxId) return this._sandboxId;
|
|
313
524
|
const esbuild = await getEsbuild();
|
|
314
|
-
const { Sandbox } = await getE2b();
|
|
315
525
|
const externalPatterns = Array.from(
|
|
316
526
|
/* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
|
|
317
527
|
);
|
|
@@ -379,68 +589,18 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
379
589
|
}
|
|
380
590
|
}]
|
|
381
591
|
});
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
|
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
|
|
438
597
|
});
|
|
439
|
-
await runSandboxCommand(sandbox, `mkdir -p ${SANDBOX_PATHS.agentDir}`, QUICK_COMMAND_TIMEOUT_MS);
|
|
440
598
|
const { apt, commands } = this.dependencies;
|
|
441
599
|
if (apt && apt.length > 0) {
|
|
442
600
|
const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
|
|
443
|
-
const aptResult = await
|
|
601
|
+
const aptResult = await sandbox.runCommand(aptCmd, {
|
|
602
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
603
|
+
});
|
|
444
604
|
if (aptResult.exitCode !== 0) {
|
|
445
605
|
const details = [
|
|
446
606
|
`Failed to install apt packages: ${apt.join(", ")}`,
|
|
@@ -452,7 +612,9 @@ try {
|
|
|
452
612
|
}
|
|
453
613
|
if (commands && commands.length > 0) {
|
|
454
614
|
for (const cmd of commands) {
|
|
455
|
-
const cmdResult = await
|
|
615
|
+
const cmdResult = await sandbox.runCommand(cmd, {
|
|
616
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
617
|
+
});
|
|
456
618
|
if (cmdResult.exitCode !== 0) {
|
|
457
619
|
const details = [
|
|
458
620
|
`Failed to run command: ${cmd}`,
|
|
@@ -465,13 +627,17 @@ try {
|
|
|
465
627
|
}
|
|
466
628
|
if (this.files.length > 0) {
|
|
467
629
|
for (const file of this.files) {
|
|
468
|
-
const destPath = file.path.startsWith("/") ? file.path : `${
|
|
630
|
+
const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
|
|
469
631
|
const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
|
|
470
632
|
if (parentDir) {
|
|
471
|
-
await
|
|
633
|
+
await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
|
|
634
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
635
|
+
});
|
|
472
636
|
}
|
|
473
637
|
const curlCmd = `curl -fsSL -o ${shellEscape(destPath)} ${shellEscape(file.url)}`;
|
|
474
|
-
const downloadResult = await
|
|
638
|
+
const downloadResult = await sandbox.runCommand(curlCmd, {
|
|
639
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
640
|
+
});
|
|
475
641
|
if (downloadResult.exitCode !== 0) {
|
|
476
642
|
const details = [
|
|
477
643
|
`Failed to download file from ${file.url} to ${destPath}`,
|
|
@@ -484,36 +650,39 @@ try {
|
|
|
484
650
|
}
|
|
485
651
|
if (this.claudeDir) {
|
|
486
652
|
const claudeFiles = readDirectoryRecursively(this.claudeDir);
|
|
487
|
-
await
|
|
653
|
+
await sandbox.runCommand(`mkdir -p ${shellEscape(paths.claudeDir)}`, {
|
|
654
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
655
|
+
});
|
|
488
656
|
for (const file of claudeFiles) {
|
|
489
|
-
const destPath = `${
|
|
657
|
+
const destPath = `${paths.claudeDir}/${file.relativePath}`;
|
|
490
658
|
const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
|
|
491
|
-
if (parentDir && parentDir !==
|
|
492
|
-
await
|
|
659
|
+
if (parentDir && parentDir !== paths.claudeDir) {
|
|
660
|
+
await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
|
|
661
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
662
|
+
});
|
|
493
663
|
}
|
|
494
|
-
await sandbox.
|
|
664
|
+
await sandbox.writeFile(destPath, file.content);
|
|
495
665
|
}
|
|
496
666
|
}
|
|
497
|
-
await sandbox.
|
|
498
|
-
await sandbox.
|
|
667
|
+
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
668
|
+
await sandbox.writeFile(paths.runnerModule, runnerCode);
|
|
499
669
|
if (collectedExternals.size > 0) {
|
|
500
670
|
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
501
671
|
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
502
672
|
if (Object.keys(dependencies).length === 0) {
|
|
503
|
-
this._sandboxId = sandbox.
|
|
504
|
-
return
|
|
673
|
+
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
674
|
+
return sandbox.id;
|
|
505
675
|
}
|
|
506
676
|
const pkgJson = JSON.stringify({
|
|
507
677
|
name: "agent-sandbox",
|
|
508
678
|
type: "module",
|
|
509
679
|
dependencies
|
|
510
680
|
});
|
|
511
|
-
await sandbox.
|
|
512
|
-
const installResult = await
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
);
|
|
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
|
+
});
|
|
517
686
|
if (installResult.exitCode !== 0) {
|
|
518
687
|
const details = [
|
|
519
688
|
`Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
|
|
@@ -523,8 +692,8 @@ try {
|
|
|
523
692
|
throw new DeploymentError(details);
|
|
524
693
|
}
|
|
525
694
|
}
|
|
526
|
-
this._sandboxId = sandbox.
|
|
527
|
-
return
|
|
695
|
+
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
696
|
+
return sandbox.id;
|
|
528
697
|
}
|
|
529
698
|
/**
|
|
530
699
|
* Executes the agent with the given input.
|
|
@@ -559,20 +728,16 @@ try {
|
|
|
559
728
|
};
|
|
560
729
|
}
|
|
561
730
|
try {
|
|
562
|
-
const e2bApiKey = requireEnv("E2B_API_KEY");
|
|
563
|
-
const { Sandbox } = await getE2b();
|
|
564
731
|
const validatedInput = this.inputSchema.parse(input);
|
|
565
|
-
const sandbox = await
|
|
566
|
-
|
|
567
|
-
});
|
|
568
|
-
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 }));
|
|
569
735
|
let capturedStdout = "";
|
|
570
736
|
let capturedStderr = "";
|
|
571
|
-
const result = await sandbox.
|
|
737
|
+
const result = await sandbox.runCommand("node runner.mjs", {
|
|
738
|
+
cwd: paths.agentDir,
|
|
572
739
|
timeoutMs: this.maxDuration * 1e3,
|
|
573
|
-
envs:
|
|
574
|
-
Object.entries(this.envs).filter(([_, v]) => v !== void 0).map(([k, v]) => [k, v])
|
|
575
|
-
),
|
|
740
|
+
envs: this.sandboxEnv,
|
|
576
741
|
onStdout: (data) => {
|
|
577
742
|
capturedStdout += data;
|
|
578
743
|
},
|
|
@@ -583,7 +748,7 @@ try {
|
|
|
583
748
|
if (result.exitCode !== 0) {
|
|
584
749
|
let resultError = "";
|
|
585
750
|
try {
|
|
586
|
-
const resultJson = await sandbox.
|
|
751
|
+
const resultJson = await sandbox.readFile(paths.outputJson);
|
|
587
752
|
const parsed = JSON.parse(resultJson);
|
|
588
753
|
if (!parsed.success && parsed.error) {
|
|
589
754
|
resultError = `
|
|
@@ -602,7 +767,7 @@ Stack: ${parsed.error.stack}`;
|
|
|
602
767
|
].filter(Boolean).join("\n");
|
|
603
768
|
return { ok: false, executionId, error: new ExecutionError(errorDetails) };
|
|
604
769
|
}
|
|
605
|
-
const output = JSON.parse(await sandbox.
|
|
770
|
+
const output = JSON.parse(await sandbox.readFile(paths.outputJson));
|
|
606
771
|
if (!output.success) {
|
|
607
772
|
const errorDetails = [
|
|
608
773
|
output.error.message,
|
|
@@ -628,5 +793,6 @@ export {
|
|
|
628
793
|
DeploymentError,
|
|
629
794
|
ExecutionError,
|
|
630
795
|
NeckbeardError,
|
|
631
|
-
ValidationError
|
|
796
|
+
ValidationError,
|
|
797
|
+
normalizeStackFramePath
|
|
632
798
|
};
|