agent-neckbeard 1.1.13 → 1.1.15

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 CHANGED
@@ -174,6 +174,35 @@ const result = await agent.run({ topic: 'hello' }, { sandboxId: savedSandboxId }
174
174
 
175
175
  Neckbeard rehydrates the sandbox endpoint and provider traffic token from the sandbox ID using the configured provider SDK. E2B traffic tokens are sent as the `e2b-traffic-access-token` header. Daytona preview tokens are sent as the `DAYTONA_SANDBOX_AUTH_KEY` query parameter. Consumers only need to store the sandbox ID and configure the same provider/API key in the process that reconnects.
176
176
 
177
+ ### Environment Changes with Reused Sandboxes
178
+
179
+ `envs` are applied when Neckbeard creates the sandbox and starts the sandbox server. If the host app was missing a required value such as `ANTHROPIC_API_KEY` when the sandbox was created, the sandbox can remain healthy but unauthenticated even after you fix the host environment and redeploy the app.
180
+
181
+ Updating Vercel, Render, or 1Password environment variables does not mutate already-running sandboxes. Kill the old sandbox or deploy a fresh one and replace the persisted sandbox ID. Consumers that keep long-lived sandbox IDs should treat authentication failures such as `Not logged in` or `Please run /login` as a signal to discard the sandbox after verifying the host environment is now correct.
182
+
183
+ ## Direct Sandbox Access
184
+
185
+ Use `SandboxClient` when host code needs provider-neutral filesystem or command access without running an agent invocation:
186
+
187
+ ```typescript
188
+ import { SandboxClient } from 'agent-neckbeard';
189
+
190
+ const sandbox = await SandboxClient.connect({
191
+ provider: 'e2b',
192
+ sandboxId,
193
+ timeoutMs: 30 * 60 * 1000,
194
+ });
195
+
196
+ await sandbox.makeDir('/home/user/documents');
197
+ await sandbox.writeFile('/home/user/documents/input.txt', 'hello');
198
+ const result = await sandbox.runCommand('ls documents', {
199
+ cwd: '/home/user',
200
+ timeoutMs: 60_000,
201
+ });
202
+ ```
203
+
204
+ `SandboxClient.create()` and `SandboxClient.connect()` support E2B and Daytona. E2B supports `setTimeout()` for sandbox lifetime extension; providers without that lifecycle primitive throw a `ConfigurationError`.
205
+
177
206
  ## Configuration
178
207
 
179
208
  ```typescript
package/dist/index.cjs CHANGED
@@ -229,6 +229,7 @@ __export(index_exports, {
229
229
  DeploymentError: () => DeploymentError,
230
230
  ExecutionError: () => ExecutionError,
231
231
  NeckbeardError: () => NeckbeardError,
232
+ SandboxClient: () => SandboxClient,
232
233
  ValidationError: () => ValidationError,
233
234
  normalizeStackFramePath: () => normalizeStackFramePath,
234
235
  resolveAgentSourceFile: () => resolveAgentSourceFile,
@@ -242,7 +243,7 @@ var import_node_module = require("module");
242
243
  init_protocol();
243
244
 
244
245
  // src/runtime/server-source.generated.ts
245
- var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
246
+ var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
246
247
 
247
248
  // src/index.ts
248
249
  function readPackageJson(path) {
@@ -995,9 +996,13 @@ function isPackageCompatible(info) {
995
996
  return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
996
997
  }
997
998
  function filterDefinedEnvs(envs) {
998
- return Object.fromEntries(
999
- Object.entries(envs).filter(([_, value]) => value !== void 0).map(([key, value]) => [key, value])
1000
- );
999
+ const filtered = {};
1000
+ for (const [key, value] of Object.entries(envs)) {
1001
+ if (value !== void 0) {
1002
+ filtered[key] = value;
1003
+ }
1004
+ }
1005
+ return filtered;
1001
1006
  }
1002
1007
  function arrayBufferToBuffer(value) {
1003
1008
  return Buffer.from(value);
@@ -1048,6 +1053,16 @@ async function resolveDaytonaPaths(sandbox) {
1048
1053
  }
1049
1054
  return createSandboxPaths("daytona", homeDir, workDir);
1050
1055
  }
1056
+ function numberProperty(value, property) {
1057
+ if (typeof value !== "object" || value === null) return void 0;
1058
+ const propertyValue = Reflect.get(value, property);
1059
+ return typeof propertyValue === "number" ? propertyValue : void 0;
1060
+ }
1061
+ function stringProperty(value, property) {
1062
+ if (typeof value !== "object" || value === null) return void 0;
1063
+ const propertyValue = Reflect.get(value, property);
1064
+ return typeof propertyValue === "string" ? propertyValue : void 0;
1065
+ }
1051
1066
  async function runE2bCommand(sandbox, cmd, options) {
1052
1067
  let stdout = "";
1053
1068
  let stderr = "";
@@ -1055,6 +1070,7 @@ async function runE2bCommand(sandbox, cmd, options) {
1055
1070
  const result = await sandbox.commands.run(cmd, {
1056
1071
  timeoutMs: options.timeoutMs,
1057
1072
  envs: options.envs,
1073
+ background: false,
1058
1074
  onStdout: (data) => {
1059
1075
  stdout += data;
1060
1076
  options.onStdout?.(data);
@@ -1070,118 +1086,271 @@ async function runE2bCommand(sandbox, cmd, options) {
1070
1086
  stderr: stderr || result.stderr
1071
1087
  };
1072
1088
  } catch (error) {
1073
- const exitCode = error.exitCode ?? 1;
1074
- const errorMessage2 = error instanceof Error ? error.message : String(error);
1089
+ const exitCode = numberProperty(error, "exitCode") ?? 1;
1075
1090
  return {
1076
1091
  exitCode,
1077
- stdout,
1078
- stderr: stderr || errorMessage2
1092
+ stdout: stdout || stringProperty(error, "stdout") || "",
1093
+ stderr: stderr || stringProperty(error, "stderr") || errorMessage(error)
1079
1094
  };
1080
1095
  }
1081
1096
  }
1082
- function createE2bHandle(sandbox) {
1083
- const paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
1084
- return {
1085
- id: sandbox.sandboxId,
1086
- paths,
1087
- writeFile: (path, content) => sandbox.files.write(path, toE2bWriteContent(content)),
1088
- readFile: (path) => sandbox.files.read(path),
1089
- runCommand: (cmd, options) => {
1090
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
1091
- return runE2bCommand(sandbox, command, options);
1092
- },
1093
- startDetachedCommand: async (cmd, options) => {
1094
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
1095
- const handle = await sandbox.commands.run(command, {
1096
- timeoutMs: 0,
1097
- envs: options.envs,
1098
- background: true
1099
- });
1100
- return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
1101
- },
1102
- readSessionLogs: async (_sessionId, commandId) => {
1103
- if (!sandbox.commands.connect) return { stdout: "", stderr: "" };
1104
- try {
1105
- const handle = await sandbox.commands.connect(Number(commandId));
1106
- return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
1107
- } catch {
1108
- return { stdout: "", stderr: "" };
1109
- }
1110
- },
1111
- stopSession: async (sessionId) => {
1112
- const pid = Number(sessionId.replace(/^e2b:/, ""));
1113
- if (Number.isFinite(pid)) {
1114
- await sandbox.commands.kill?.(pid);
1115
- }
1116
- },
1117
- getServerEndpoint: async (port) => ({
1118
- url: `https://${sandbox.getHost(port)}`,
1119
- trafficToken: sandbox.trafficAccessToken
1120
- }),
1121
- destroy: () => sandbox.kill()
1122
- };
1123
- }
1124
- async function createDaytonaHandle(sandbox) {
1125
- const paths = await resolveDaytonaPaths(sandbox);
1126
- return {
1127
- id: sandbox.id,
1128
- paths,
1129
- writeFile: (path, content) => sandbox.fs.uploadFile(
1097
+ var E2bSandboxHandle = class {
1098
+ constructor(sandbox) {
1099
+ this.sandbox = sandbox;
1100
+ }
1101
+ provider = "e2b";
1102
+ paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
1103
+ get id() {
1104
+ return this.sandbox.sandboxId;
1105
+ }
1106
+ async makeDir(path) {
1107
+ await this.sandbox.files.makeDir(path);
1108
+ }
1109
+ writeFile(path, content) {
1110
+ return this.sandbox.files.write(path, toE2bWriteContent(content)).then(() => void 0);
1111
+ }
1112
+ readFile(path) {
1113
+ return this.sandbox.files.read(path, { format: "text" });
1114
+ }
1115
+ readFileBytes(path) {
1116
+ return this.sandbox.files.read(path, { format: "bytes" });
1117
+ }
1118
+ runCommand(cmd, options) {
1119
+ const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
1120
+ return runE2bCommand(this.sandbox, command, options);
1121
+ }
1122
+ setTimeout(timeoutMs) {
1123
+ return this.sandbox.setTimeout(timeoutMs);
1124
+ }
1125
+ async startDetachedCommand(cmd, options) {
1126
+ const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
1127
+ const handle = await this.sandbox.commands.run(command, {
1128
+ timeoutMs: 0,
1129
+ envs: options.envs,
1130
+ background: true
1131
+ });
1132
+ return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
1133
+ }
1134
+ async readSessionLogs(_sessionId, commandId) {
1135
+ try {
1136
+ const handle = await this.sandbox.commands.connect(Number(commandId));
1137
+ return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
1138
+ } catch {
1139
+ return { stdout: "", stderr: "" };
1140
+ }
1141
+ }
1142
+ async stopSession(sessionId) {
1143
+ const pid = Number(sessionId.replace(/^e2b:/, ""));
1144
+ if (Number.isFinite(pid)) {
1145
+ await this.sandbox.commands.kill(pid);
1146
+ }
1147
+ }
1148
+ async getServerEndpoint(port) {
1149
+ return {
1150
+ url: `https://${this.sandbox.getHost(port)}`,
1151
+ trafficToken: this.sandbox.trafficAccessToken
1152
+ };
1153
+ }
1154
+ destroy() {
1155
+ return this.sandbox.kill();
1156
+ }
1157
+ };
1158
+ var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
1159
+ constructor(sandbox, paths) {
1160
+ this.sandbox = sandbox;
1161
+ this.paths = paths;
1162
+ }
1163
+ provider = "daytona";
1164
+ static async create(sandbox) {
1165
+ return new _DaytonaSandboxHandle(sandbox, await resolveDaytonaPaths(sandbox));
1166
+ }
1167
+ get id() {
1168
+ return this.sandbox.id;
1169
+ }
1170
+ async makeDir(path) {
1171
+ const result = await this.sandbox.process.executeCommand(
1172
+ `mkdir -p ${shellEscape(path)}`,
1173
+ void 0,
1174
+ void 0,
1175
+ timeoutMsToSeconds(QUICK_COMMAND_TIMEOUT_MS)
1176
+ );
1177
+ if (result.exitCode !== 0) {
1178
+ throw new DeploymentError(result.result || `Failed to create directory ${path}`);
1179
+ }
1180
+ }
1181
+ writeFile(path, content) {
1182
+ return this.sandbox.fs.uploadFile(
1130
1183
  toDaytonaUploadContent(content),
1131
1184
  path,
1132
1185
  timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
1133
- ),
1134
- readFile: async (path) => {
1135
- const content = await sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1136
- return content.toString("utf-8");
1137
- },
1138
- runCommand: async (cmd, options) => {
1139
- const result = await sandbox.process.executeCommand(
1140
- cmd,
1141
- options.cwd,
1142
- options.envs,
1143
- timeoutMsToSeconds(options.timeoutMs)
1144
- );
1145
- const stdout = result.artifacts?.stdout ?? result.result ?? "";
1146
- if (stdout) options.onStdout?.(stdout);
1186
+ );
1187
+ }
1188
+ async readFile(path) {
1189
+ const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1190
+ return content.toString("utf-8");
1191
+ }
1192
+ async readFileBytes(path) {
1193
+ const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1194
+ return new Uint8Array(content);
1195
+ }
1196
+ async runCommand(cmd, options) {
1197
+ const result = await this.sandbox.process.executeCommand(
1198
+ cmd,
1199
+ options.cwd,
1200
+ options.envs,
1201
+ timeoutMsToSeconds(options.timeoutMs)
1202
+ );
1203
+ const stdout = result.artifacts?.stdout ?? result.result ?? "";
1204
+ if (stdout) options.onStdout?.(stdout);
1205
+ return {
1206
+ exitCode: result.exitCode,
1207
+ stdout,
1208
+ stderr: ""
1209
+ };
1210
+ }
1211
+ async startDetachedCommand(cmd, options) {
1212
+ const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1213
+ await this.sandbox.process.createSession(sessionId);
1214
+ const envPrefix = options.envs ? Object.entries(options.envs).map(([key, value]) => `${key}=${shellEscape(value)}`).join(" ") + " " : "";
1215
+ const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
1216
+ const result = await this.sandbox.process.executeSessionCommand(sessionId, {
1217
+ command: `${cwdPrefix}${envPrefix}${cmd}`,
1218
+ runAsync: true
1219
+ });
1220
+ return { sessionId, commandId: result.cmdId };
1221
+ }
1222
+ async readSessionLogs(sessionId, commandId) {
1223
+ try {
1224
+ const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
1147
1225
  return {
1148
- exitCode: result.exitCode,
1149
- stdout,
1150
- stderr: ""
1226
+ stdout: logs.stdout ?? logs.output ?? "",
1227
+ stderr: logs.stderr ?? ""
1151
1228
  };
1152
- },
1153
- startDetachedCommand: async (cmd, options) => {
1154
- const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1155
- await sandbox.process.createSession(sessionId);
1156
- const envPrefix = options.envs ? Object.entries(options.envs).map(([k, v]) => `${k}=${shellEscape(v)}`).join(" ") + " " : "";
1157
- const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
1158
- const result = await sandbox.process.executeSessionCommand(sessionId, {
1159
- command: `${cwdPrefix}${envPrefix}${cmd}`,
1160
- runAsync: true
1161
- });
1162
- return { sessionId, commandId: result.cmdId };
1163
- },
1164
- readSessionLogs: async (sessionId, commandId) => {
1165
- try {
1166
- const logs = await sandbox.process.getSessionCommandLogs(sessionId, commandId);
1167
- return {
1168
- stdout: logs.stdout ?? logs.output ?? "",
1169
- stderr: logs.stderr ?? ""
1170
- };
1171
- } catch {
1172
- return { stdout: "", stderr: "" };
1173
- }
1174
- },
1175
- stopSession: async (sessionId) => {
1176
- await sandbox.process.deleteSession(sessionId);
1177
- },
1178
- getServerEndpoint: async (port) => {
1179
- const preview = await sandbox.getPreviewLink(port);
1180
- return { url: preview.url, trafficToken: preview.token };
1181
- },
1182
- destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
1229
+ } catch {
1230
+ return { stdout: "", stderr: "" };
1231
+ }
1232
+ }
1233
+ stopSession(sessionId) {
1234
+ return this.sandbox.process.deleteSession(sessionId);
1235
+ }
1236
+ async getServerEndpoint(port) {
1237
+ const preview = await this.sandbox.getPreviewLink(port);
1238
+ return { url: preview.url, trafficToken: preview.token };
1239
+ }
1240
+ destroy() {
1241
+ return this.sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1242
+ }
1243
+ };
1244
+ function providerApiKey(provider, explicitApiKey) {
1245
+ if (explicitApiKey) return explicitApiKey;
1246
+ return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
1247
+ }
1248
+ async function createProviderSandboxHandle(options) {
1249
+ if (options.provider === "daytona") {
1250
+ const apiKey2 = providerApiKey("daytona", options.apiKey);
1251
+ const { Daytona } = await getDaytona();
1252
+ const daytona = new Daytona({ apiKey: apiKey2 });
1253
+ const sandbox2 = await daytona.create(
1254
+ {
1255
+ ...options.template ? { snapshot: options.template } : {},
1256
+ envVars: filterDefinedEnvs(options.envs ?? {}),
1257
+ autoDeleteInterval: options.autoDeleteInterval ?? -1
1258
+ },
1259
+ { timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
1260
+ );
1261
+ return DaytonaSandboxHandle.create(sandbox2);
1262
+ }
1263
+ const apiKey = providerApiKey("e2b", options.apiKey);
1264
+ const { Sandbox } = await getE2b();
1265
+ const sandboxOptions = {
1266
+ apiKey,
1267
+ envs: filterDefinedEnvs(options.envs ?? {}),
1268
+ timeoutMs: options.timeoutMs,
1269
+ requestTimeoutMs: options.requestTimeoutMs,
1270
+ network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
1183
1271
  };
1272
+ const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
1273
+ return new E2bSandboxHandle(sandbox);
1184
1274
  }
1275
+ async function connectProviderSandboxHandle(options) {
1276
+ if (options.provider === "daytona") {
1277
+ const apiKey2 = providerApiKey("daytona", options.apiKey);
1278
+ const { Daytona } = await getDaytona();
1279
+ const daytona = new Daytona({ apiKey: apiKey2 });
1280
+ const sandbox2 = await daytona.get(options.sandboxId);
1281
+ if (sandbox2.state !== "started") {
1282
+ if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
1283
+ await sandbox2.waitUntilStarted(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
1284
+ } else {
1285
+ await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
1286
+ }
1287
+ }
1288
+ return DaytonaSandboxHandle.create(sandbox2);
1289
+ }
1290
+ const apiKey = providerApiKey("e2b", options.apiKey);
1291
+ const { Sandbox } = await getE2b();
1292
+ const sandbox = await Sandbox.connect(options.sandboxId, {
1293
+ apiKey,
1294
+ timeoutMs: options.timeoutMs,
1295
+ requestTimeoutMs: options.requestTimeoutMs
1296
+ });
1297
+ return new E2bSandboxHandle(sandbox);
1298
+ }
1299
+ var SandboxClient = class _SandboxClient {
1300
+ constructor(handle) {
1301
+ this.handle = handle;
1302
+ }
1303
+ static async create(options) {
1304
+ return new _SandboxClient(await createProviderSandboxHandle(options));
1305
+ }
1306
+ static async connect(options) {
1307
+ return new _SandboxClient(await connectProviderSandboxHandle(options));
1308
+ }
1309
+ get id() {
1310
+ return this.handle.id;
1311
+ }
1312
+ get provider() {
1313
+ return this.handle.provider;
1314
+ }
1315
+ get paths() {
1316
+ return {
1317
+ provider: this.handle.paths.provider,
1318
+ homeDir: this.handle.paths.homeDir,
1319
+ workDir: this.handle.paths.workDir,
1320
+ agentDir: this.handle.paths.agentDir,
1321
+ ioDir: this.handle.paths.ioDir,
1322
+ inputJson: this.handle.paths.inputJson,
1323
+ outputJson: this.handle.paths.outputJson
1324
+ };
1325
+ }
1326
+ async makeDir(path) {
1327
+ await this.handle.makeDir(path);
1328
+ }
1329
+ async writeFile(path, content) {
1330
+ await this.handle.writeFile(path, content);
1331
+ }
1332
+ async readFile(path) {
1333
+ return this.handle.readFile(path);
1334
+ }
1335
+ async readFileBytes(path) {
1336
+ return this.handle.readFileBytes(path);
1337
+ }
1338
+ async runCommand(command, options) {
1339
+ return this.handle.runCommand(command, options);
1340
+ }
1341
+ async setTimeout(timeoutMs) {
1342
+ if (!this.handle.setTimeout) {
1343
+ throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
1344
+ }
1345
+ await this.handle.setTimeout(timeoutMs);
1346
+ }
1347
+ async kill() {
1348
+ await this.handle.destroy();
1349
+ }
1350
+ async destroy() {
1351
+ await this.kill();
1352
+ }
1353
+ };
1185
1354
  function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
1186
1355
  if (rawPath.startsWith("file://")) {
1187
1356
  return (0, import_node_url.fileURLToPath)(rawPath);
@@ -1321,48 +1490,31 @@ var Agent = class {
1321
1490
  };
1322
1491
  }
1323
1492
  async createSandboxHandle() {
1324
- if (this.provider === "daytona") {
1325
- const apiKey2 = requireEnv("DAYTONA_API_KEY");
1326
- const { Daytona } = await getDaytona();
1327
- const daytona = new Daytona({ apiKey: apiKey2 });
1328
- const sandbox2 = await daytona.create(
1329
- {
1330
- snapshot: this.template,
1331
- envVars: this.sandboxEnv,
1332
- autoDeleteInterval: -1
1333
- },
1334
- { timeout: DAYTONA_CREATE_TIMEOUT_SEC }
1335
- );
1336
- return createDaytonaHandle(sandbox2);
1337
- }
1338
- const apiKey = requireEnv("E2B_API_KEY");
1339
- const { Sandbox } = await getE2b();
1340
- const sandbox = await Sandbox.create(this.template, {
1341
- apiKey,
1342
- envs: this.sandboxEnv,
1343
- network: { allowPublicTraffic: false }
1493
+ if (this.provider === "e2b") {
1494
+ return createProviderSandboxHandle({
1495
+ provider: "e2b",
1496
+ template: this.template,
1497
+ envs: this.sandboxEnv,
1498
+ allowPublicTraffic: false
1499
+ });
1500
+ }
1501
+ return createProviderSandboxHandle({
1502
+ provider: "daytona",
1503
+ template: this.template,
1504
+ envs: this.sandboxEnv
1344
1505
  });
1345
- return createE2bHandle(sandbox);
1346
1506
  }
1347
1507
  async connectSandboxHandle(sandboxId) {
1348
- if (this.provider === "daytona") {
1349
- const apiKey2 = requireEnv("DAYTONA_API_KEY");
1350
- const { Daytona } = await getDaytona();
1351
- const daytona = new Daytona({ apiKey: apiKey2 });
1352
- const sandbox2 = await daytona.get(sandboxId);
1353
- if (sandbox2.state !== "started") {
1354
- if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
1355
- await sandbox2.waitUntilStarted?.(DAYTONA_CREATE_TIMEOUT_SEC);
1356
- } else {
1357
- await sandbox2.start?.(DAYTONA_CREATE_TIMEOUT_SEC);
1358
- }
1359
- }
1360
- return createDaytonaHandle(sandbox2);
1508
+ if (this.provider === "e2b") {
1509
+ return connectProviderSandboxHandle({
1510
+ provider: "e2b",
1511
+ sandboxId
1512
+ });
1361
1513
  }
1362
- const apiKey = requireEnv("E2B_API_KEY");
1363
- const { Sandbox } = await getE2b();
1364
- const sandbox = await Sandbox.connect(sandboxId, { apiKey });
1365
- return createE2bHandle(sandbox);
1514
+ return connectProviderSandboxHandle({
1515
+ provider: "daytona",
1516
+ sandboxId
1517
+ });
1366
1518
  }
1367
1519
  async readRuntimeServerConfig(sandbox) {
1368
1520
  try {
@@ -1860,6 +2012,7 @@ ${parts.join("\n\n")}`;
1860
2012
  DeploymentError,
1861
2013
  ExecutionError,
1862
2014
  NeckbeardError,
2015
+ SandboxClient,
1863
2016
  ValidationError,
1864
2017
  normalizeStackFramePath,
1865
2018
  resolveAgentSourceFile,
package/dist/index.d.cts CHANGED
@@ -289,6 +289,67 @@ type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig;
289
289
  * Mode is discriminated at runtime by the presence of `server` vs `run`.
290
290
  */
291
291
  type AgentConfig<TInput, TOutput, TFrame = unknown> = RunAgentConfig<TInput, TOutput> | ServerAgentConfig<TInput, TFrame>;
292
+ type SandboxFileContent = string | ArrayBuffer | Uint8Array | Buffer;
293
+ interface SandboxCommandOptions {
294
+ cwd?: string;
295
+ envs?: Record<string, string>;
296
+ timeoutMs: number;
297
+ onStdout?: (data: string) => void;
298
+ onStderr?: (data: string) => void;
299
+ }
300
+ /**
301
+ * Result from running a sandbox command with captured output.
302
+ */
303
+ interface SandboxCommandResult {
304
+ exitCode: number;
305
+ stdout: string;
306
+ stderr: string;
307
+ }
308
+ type SandboxClientCreateOptions = {
309
+ provider: 'e2b';
310
+ template?: string;
311
+ apiKey?: string;
312
+ envs?: Record<string, string | undefined>;
313
+ timeoutMs?: number;
314
+ requestTimeoutMs?: number;
315
+ allowPublicTraffic?: boolean;
316
+ } | {
317
+ provider: 'daytona';
318
+ template?: string;
319
+ apiKey?: string;
320
+ envs?: Record<string, string | undefined>;
321
+ createTimeoutSec?: number;
322
+ autoDeleteInterval?: number;
323
+ };
324
+ type SandboxClientConnectOptions = {
325
+ provider: 'e2b';
326
+ sandboxId: string;
327
+ apiKey?: string;
328
+ timeoutMs?: number;
329
+ requestTimeoutMs?: number;
330
+ } | {
331
+ provider: 'daytona';
332
+ sandboxId: string;
333
+ apiKey?: string;
334
+ createTimeoutSec?: number;
335
+ };
336
+ declare class SandboxClient {
337
+ private readonly handle;
338
+ private constructor();
339
+ static create(options: SandboxClientCreateOptions): Promise<SandboxClient>;
340
+ static connect(options: SandboxClientConnectOptions): Promise<SandboxClient>;
341
+ get id(): string;
342
+ get provider(): SandboxProvider;
343
+ get paths(): AgentSandboxContext;
344
+ makeDir(path: string): Promise<void>;
345
+ writeFile(path: string, content: SandboxFileContent): Promise<void>;
346
+ readFile(path: string): Promise<string>;
347
+ readFileBytes(path: string): Promise<Uint8Array>;
348
+ runCommand(command: string, options: SandboxCommandOptions): Promise<SandboxCommandResult>;
349
+ setTimeout(timeoutMs: number): Promise<void>;
350
+ kill(): Promise<void>;
351
+ destroy(): Promise<void>;
352
+ }
292
353
  type AgentMode = 'run' | 'stream';
293
354
  declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
294
355
  readonly sandbox: SandboxConfig;
@@ -402,4 +463,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
402
463
  }): AsyncGenerator<TFrame>;
403
464
  }
404
465
 
405
- export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
466
+ export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, type SandboxCommandOptions, type SandboxCommandResult, type SandboxConfig, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
package/dist/index.d.ts CHANGED
@@ -289,6 +289,67 @@ type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig;
289
289
  * Mode is discriminated at runtime by the presence of `server` vs `run`.
290
290
  */
291
291
  type AgentConfig<TInput, TOutput, TFrame = unknown> = RunAgentConfig<TInput, TOutput> | ServerAgentConfig<TInput, TFrame>;
292
+ type SandboxFileContent = string | ArrayBuffer | Uint8Array | Buffer;
293
+ interface SandboxCommandOptions {
294
+ cwd?: string;
295
+ envs?: Record<string, string>;
296
+ timeoutMs: number;
297
+ onStdout?: (data: string) => void;
298
+ onStderr?: (data: string) => void;
299
+ }
300
+ /**
301
+ * Result from running a sandbox command with captured output.
302
+ */
303
+ interface SandboxCommandResult {
304
+ exitCode: number;
305
+ stdout: string;
306
+ stderr: string;
307
+ }
308
+ type SandboxClientCreateOptions = {
309
+ provider: 'e2b';
310
+ template?: string;
311
+ apiKey?: string;
312
+ envs?: Record<string, string | undefined>;
313
+ timeoutMs?: number;
314
+ requestTimeoutMs?: number;
315
+ allowPublicTraffic?: boolean;
316
+ } | {
317
+ provider: 'daytona';
318
+ template?: string;
319
+ apiKey?: string;
320
+ envs?: Record<string, string | undefined>;
321
+ createTimeoutSec?: number;
322
+ autoDeleteInterval?: number;
323
+ };
324
+ type SandboxClientConnectOptions = {
325
+ provider: 'e2b';
326
+ sandboxId: string;
327
+ apiKey?: string;
328
+ timeoutMs?: number;
329
+ requestTimeoutMs?: number;
330
+ } | {
331
+ provider: 'daytona';
332
+ sandboxId: string;
333
+ apiKey?: string;
334
+ createTimeoutSec?: number;
335
+ };
336
+ declare class SandboxClient {
337
+ private readonly handle;
338
+ private constructor();
339
+ static create(options: SandboxClientCreateOptions): Promise<SandboxClient>;
340
+ static connect(options: SandboxClientConnectOptions): Promise<SandboxClient>;
341
+ get id(): string;
342
+ get provider(): SandboxProvider;
343
+ get paths(): AgentSandboxContext;
344
+ makeDir(path: string): Promise<void>;
345
+ writeFile(path: string, content: SandboxFileContent): Promise<void>;
346
+ readFile(path: string): Promise<string>;
347
+ readFileBytes(path: string): Promise<Uint8Array>;
348
+ runCommand(command: string, options: SandboxCommandOptions): Promise<SandboxCommandResult>;
349
+ setTimeout(timeoutMs: number): Promise<void>;
350
+ kill(): Promise<void>;
351
+ destroy(): Promise<void>;
352
+ }
292
353
  type AgentMode = 'run' | 'stream';
293
354
  declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
294
355
  readonly sandbox: SandboxConfig;
@@ -402,4 +463,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
402
463
  }): AsyncGenerator<TFrame>;
403
464
  }
404
465
 
405
- export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
466
+ export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, type SandboxCommandOptions, type SandboxCommandResult, type SandboxConfig, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { basename, dirname, join, relative, resolve } from "path";
9
9
  import { builtinModules, createRequire } from "module";
10
10
 
11
11
  // src/runtime/server-source.generated.ts
12
- var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
12
+ var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
13
13
 
14
14
  // src/index.ts
15
15
  function readPackageJson(path) {
@@ -762,9 +762,13 @@ function isPackageCompatible(info) {
762
762
  return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
763
763
  }
764
764
  function filterDefinedEnvs(envs) {
765
- return Object.fromEntries(
766
- Object.entries(envs).filter(([_, value]) => value !== void 0).map(([key, value]) => [key, value])
767
- );
765
+ const filtered = {};
766
+ for (const [key, value] of Object.entries(envs)) {
767
+ if (value !== void 0) {
768
+ filtered[key] = value;
769
+ }
770
+ }
771
+ return filtered;
768
772
  }
769
773
  function arrayBufferToBuffer(value) {
770
774
  return Buffer.from(value);
@@ -815,6 +819,16 @@ async function resolveDaytonaPaths(sandbox) {
815
819
  }
816
820
  return createSandboxPaths("daytona", homeDir, workDir);
817
821
  }
822
+ function numberProperty(value, property) {
823
+ if (typeof value !== "object" || value === null) return void 0;
824
+ const propertyValue = Reflect.get(value, property);
825
+ return typeof propertyValue === "number" ? propertyValue : void 0;
826
+ }
827
+ function stringProperty(value, property) {
828
+ if (typeof value !== "object" || value === null) return void 0;
829
+ const propertyValue = Reflect.get(value, property);
830
+ return typeof propertyValue === "string" ? propertyValue : void 0;
831
+ }
818
832
  async function runE2bCommand(sandbox, cmd, options) {
819
833
  let stdout = "";
820
834
  let stderr = "";
@@ -822,6 +836,7 @@ async function runE2bCommand(sandbox, cmd, options) {
822
836
  const result = await sandbox.commands.run(cmd, {
823
837
  timeoutMs: options.timeoutMs,
824
838
  envs: options.envs,
839
+ background: false,
825
840
  onStdout: (data) => {
826
841
  stdout += data;
827
842
  options.onStdout?.(data);
@@ -837,118 +852,271 @@ async function runE2bCommand(sandbox, cmd, options) {
837
852
  stderr: stderr || result.stderr
838
853
  };
839
854
  } catch (error) {
840
- const exitCode = error.exitCode ?? 1;
841
- const errorMessage2 = error instanceof Error ? error.message : String(error);
855
+ const exitCode = numberProperty(error, "exitCode") ?? 1;
842
856
  return {
843
857
  exitCode,
844
- stdout,
845
- stderr: stderr || errorMessage2
858
+ stdout: stdout || stringProperty(error, "stdout") || "",
859
+ stderr: stderr || stringProperty(error, "stderr") || errorMessage(error)
846
860
  };
847
861
  }
848
862
  }
849
- function createE2bHandle(sandbox) {
850
- const paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
851
- return {
852
- id: sandbox.sandboxId,
853
- paths,
854
- writeFile: (path, content) => sandbox.files.write(path, toE2bWriteContent(content)),
855
- readFile: (path) => sandbox.files.read(path),
856
- runCommand: (cmd, options) => {
857
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
858
- return runE2bCommand(sandbox, command, options);
859
- },
860
- startDetachedCommand: async (cmd, options) => {
861
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
862
- const handle = await sandbox.commands.run(command, {
863
- timeoutMs: 0,
864
- envs: options.envs,
865
- background: true
866
- });
867
- return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
868
- },
869
- readSessionLogs: async (_sessionId, commandId) => {
870
- if (!sandbox.commands.connect) return { stdout: "", stderr: "" };
871
- try {
872
- const handle = await sandbox.commands.connect(Number(commandId));
873
- return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
874
- } catch {
875
- return { stdout: "", stderr: "" };
876
- }
877
- },
878
- stopSession: async (sessionId) => {
879
- const pid = Number(sessionId.replace(/^e2b:/, ""));
880
- if (Number.isFinite(pid)) {
881
- await sandbox.commands.kill?.(pid);
882
- }
883
- },
884
- getServerEndpoint: async (port) => ({
885
- url: `https://${sandbox.getHost(port)}`,
886
- trafficToken: sandbox.trafficAccessToken
887
- }),
888
- destroy: () => sandbox.kill()
889
- };
890
- }
891
- async function createDaytonaHandle(sandbox) {
892
- const paths = await resolveDaytonaPaths(sandbox);
893
- return {
894
- id: sandbox.id,
895
- paths,
896
- writeFile: (path, content) => sandbox.fs.uploadFile(
863
+ var E2bSandboxHandle = class {
864
+ constructor(sandbox) {
865
+ this.sandbox = sandbox;
866
+ }
867
+ provider = "e2b";
868
+ paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
869
+ get id() {
870
+ return this.sandbox.sandboxId;
871
+ }
872
+ async makeDir(path) {
873
+ await this.sandbox.files.makeDir(path);
874
+ }
875
+ writeFile(path, content) {
876
+ return this.sandbox.files.write(path, toE2bWriteContent(content)).then(() => void 0);
877
+ }
878
+ readFile(path) {
879
+ return this.sandbox.files.read(path, { format: "text" });
880
+ }
881
+ readFileBytes(path) {
882
+ return this.sandbox.files.read(path, { format: "bytes" });
883
+ }
884
+ runCommand(cmd, options) {
885
+ const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
886
+ return runE2bCommand(this.sandbox, command, options);
887
+ }
888
+ setTimeout(timeoutMs) {
889
+ return this.sandbox.setTimeout(timeoutMs);
890
+ }
891
+ async startDetachedCommand(cmd, options) {
892
+ const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
893
+ const handle = await this.sandbox.commands.run(command, {
894
+ timeoutMs: 0,
895
+ envs: options.envs,
896
+ background: true
897
+ });
898
+ return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
899
+ }
900
+ async readSessionLogs(_sessionId, commandId) {
901
+ try {
902
+ const handle = await this.sandbox.commands.connect(Number(commandId));
903
+ return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
904
+ } catch {
905
+ return { stdout: "", stderr: "" };
906
+ }
907
+ }
908
+ async stopSession(sessionId) {
909
+ const pid = Number(sessionId.replace(/^e2b:/, ""));
910
+ if (Number.isFinite(pid)) {
911
+ await this.sandbox.commands.kill(pid);
912
+ }
913
+ }
914
+ async getServerEndpoint(port) {
915
+ return {
916
+ url: `https://${this.sandbox.getHost(port)}`,
917
+ trafficToken: this.sandbox.trafficAccessToken
918
+ };
919
+ }
920
+ destroy() {
921
+ return this.sandbox.kill();
922
+ }
923
+ };
924
+ var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
925
+ constructor(sandbox, paths) {
926
+ this.sandbox = sandbox;
927
+ this.paths = paths;
928
+ }
929
+ provider = "daytona";
930
+ static async create(sandbox) {
931
+ return new _DaytonaSandboxHandle(sandbox, await resolveDaytonaPaths(sandbox));
932
+ }
933
+ get id() {
934
+ return this.sandbox.id;
935
+ }
936
+ async makeDir(path) {
937
+ const result = await this.sandbox.process.executeCommand(
938
+ `mkdir -p ${shellEscape(path)}`,
939
+ void 0,
940
+ void 0,
941
+ timeoutMsToSeconds(QUICK_COMMAND_TIMEOUT_MS)
942
+ );
943
+ if (result.exitCode !== 0) {
944
+ throw new DeploymentError(result.result || `Failed to create directory ${path}`);
945
+ }
946
+ }
947
+ writeFile(path, content) {
948
+ return this.sandbox.fs.uploadFile(
897
949
  toDaytonaUploadContent(content),
898
950
  path,
899
951
  timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
900
- ),
901
- readFile: async (path) => {
902
- const content = await sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
903
- return content.toString("utf-8");
904
- },
905
- runCommand: async (cmd, options) => {
906
- const result = await sandbox.process.executeCommand(
907
- cmd,
908
- options.cwd,
909
- options.envs,
910
- timeoutMsToSeconds(options.timeoutMs)
911
- );
912
- const stdout = result.artifacts?.stdout ?? result.result ?? "";
913
- if (stdout) options.onStdout?.(stdout);
952
+ );
953
+ }
954
+ async readFile(path) {
955
+ const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
956
+ return content.toString("utf-8");
957
+ }
958
+ async readFileBytes(path) {
959
+ const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
960
+ return new Uint8Array(content);
961
+ }
962
+ async runCommand(cmd, options) {
963
+ const result = await this.sandbox.process.executeCommand(
964
+ cmd,
965
+ options.cwd,
966
+ options.envs,
967
+ timeoutMsToSeconds(options.timeoutMs)
968
+ );
969
+ const stdout = result.artifacts?.stdout ?? result.result ?? "";
970
+ if (stdout) options.onStdout?.(stdout);
971
+ return {
972
+ exitCode: result.exitCode,
973
+ stdout,
974
+ stderr: ""
975
+ };
976
+ }
977
+ async startDetachedCommand(cmd, options) {
978
+ const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
979
+ await this.sandbox.process.createSession(sessionId);
980
+ const envPrefix = options.envs ? Object.entries(options.envs).map(([key, value]) => `${key}=${shellEscape(value)}`).join(" ") + " " : "";
981
+ const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
982
+ const result = await this.sandbox.process.executeSessionCommand(sessionId, {
983
+ command: `${cwdPrefix}${envPrefix}${cmd}`,
984
+ runAsync: true
985
+ });
986
+ return { sessionId, commandId: result.cmdId };
987
+ }
988
+ async readSessionLogs(sessionId, commandId) {
989
+ try {
990
+ const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
914
991
  return {
915
- exitCode: result.exitCode,
916
- stdout,
917
- stderr: ""
992
+ stdout: logs.stdout ?? logs.output ?? "",
993
+ stderr: logs.stderr ?? ""
918
994
  };
919
- },
920
- startDetachedCommand: async (cmd, options) => {
921
- const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
922
- await sandbox.process.createSession(sessionId);
923
- const envPrefix = options.envs ? Object.entries(options.envs).map(([k, v]) => `${k}=${shellEscape(v)}`).join(" ") + " " : "";
924
- const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
925
- const result = await sandbox.process.executeSessionCommand(sessionId, {
926
- command: `${cwdPrefix}${envPrefix}${cmd}`,
927
- runAsync: true
928
- });
929
- return { sessionId, commandId: result.cmdId };
930
- },
931
- readSessionLogs: async (sessionId, commandId) => {
932
- try {
933
- const logs = await sandbox.process.getSessionCommandLogs(sessionId, commandId);
934
- return {
935
- stdout: logs.stdout ?? logs.output ?? "",
936
- stderr: logs.stderr ?? ""
937
- };
938
- } catch {
939
- return { stdout: "", stderr: "" };
940
- }
941
- },
942
- stopSession: async (sessionId) => {
943
- await sandbox.process.deleteSession(sessionId);
944
- },
945
- getServerEndpoint: async (port) => {
946
- const preview = await sandbox.getPreviewLink(port);
947
- return { url: preview.url, trafficToken: preview.token };
948
- },
949
- destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
995
+ } catch {
996
+ return { stdout: "", stderr: "" };
997
+ }
998
+ }
999
+ stopSession(sessionId) {
1000
+ return this.sandbox.process.deleteSession(sessionId);
1001
+ }
1002
+ async getServerEndpoint(port) {
1003
+ const preview = await this.sandbox.getPreviewLink(port);
1004
+ return { url: preview.url, trafficToken: preview.token };
1005
+ }
1006
+ destroy() {
1007
+ return this.sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1008
+ }
1009
+ };
1010
+ function providerApiKey(provider, explicitApiKey) {
1011
+ if (explicitApiKey) return explicitApiKey;
1012
+ return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
1013
+ }
1014
+ async function createProviderSandboxHandle(options) {
1015
+ if (options.provider === "daytona") {
1016
+ const apiKey2 = providerApiKey("daytona", options.apiKey);
1017
+ const { Daytona } = await getDaytona();
1018
+ const daytona = new Daytona({ apiKey: apiKey2 });
1019
+ const sandbox2 = await daytona.create(
1020
+ {
1021
+ ...options.template ? { snapshot: options.template } : {},
1022
+ envVars: filterDefinedEnvs(options.envs ?? {}),
1023
+ autoDeleteInterval: options.autoDeleteInterval ?? -1
1024
+ },
1025
+ { timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
1026
+ );
1027
+ return DaytonaSandboxHandle.create(sandbox2);
1028
+ }
1029
+ const apiKey = providerApiKey("e2b", options.apiKey);
1030
+ const { Sandbox } = await getE2b();
1031
+ const sandboxOptions = {
1032
+ apiKey,
1033
+ envs: filterDefinedEnvs(options.envs ?? {}),
1034
+ timeoutMs: options.timeoutMs,
1035
+ requestTimeoutMs: options.requestTimeoutMs,
1036
+ network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
950
1037
  };
1038
+ const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
1039
+ return new E2bSandboxHandle(sandbox);
1040
+ }
1041
+ async function connectProviderSandboxHandle(options) {
1042
+ if (options.provider === "daytona") {
1043
+ const apiKey2 = providerApiKey("daytona", options.apiKey);
1044
+ const { Daytona } = await getDaytona();
1045
+ const daytona = new Daytona({ apiKey: apiKey2 });
1046
+ const sandbox2 = await daytona.get(options.sandboxId);
1047
+ if (sandbox2.state !== "started") {
1048
+ if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
1049
+ await sandbox2.waitUntilStarted(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
1050
+ } else {
1051
+ await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
1052
+ }
1053
+ }
1054
+ return DaytonaSandboxHandle.create(sandbox2);
1055
+ }
1056
+ const apiKey = providerApiKey("e2b", options.apiKey);
1057
+ const { Sandbox } = await getE2b();
1058
+ const sandbox = await Sandbox.connect(options.sandboxId, {
1059
+ apiKey,
1060
+ timeoutMs: options.timeoutMs,
1061
+ requestTimeoutMs: options.requestTimeoutMs
1062
+ });
1063
+ return new E2bSandboxHandle(sandbox);
951
1064
  }
1065
+ var SandboxClient = class _SandboxClient {
1066
+ constructor(handle) {
1067
+ this.handle = handle;
1068
+ }
1069
+ static async create(options) {
1070
+ return new _SandboxClient(await createProviderSandboxHandle(options));
1071
+ }
1072
+ static async connect(options) {
1073
+ return new _SandboxClient(await connectProviderSandboxHandle(options));
1074
+ }
1075
+ get id() {
1076
+ return this.handle.id;
1077
+ }
1078
+ get provider() {
1079
+ return this.handle.provider;
1080
+ }
1081
+ get paths() {
1082
+ return {
1083
+ provider: this.handle.paths.provider,
1084
+ homeDir: this.handle.paths.homeDir,
1085
+ workDir: this.handle.paths.workDir,
1086
+ agentDir: this.handle.paths.agentDir,
1087
+ ioDir: this.handle.paths.ioDir,
1088
+ inputJson: this.handle.paths.inputJson,
1089
+ outputJson: this.handle.paths.outputJson
1090
+ };
1091
+ }
1092
+ async makeDir(path) {
1093
+ await this.handle.makeDir(path);
1094
+ }
1095
+ async writeFile(path, content) {
1096
+ await this.handle.writeFile(path, content);
1097
+ }
1098
+ async readFile(path) {
1099
+ return this.handle.readFile(path);
1100
+ }
1101
+ async readFileBytes(path) {
1102
+ return this.handle.readFileBytes(path);
1103
+ }
1104
+ async runCommand(command, options) {
1105
+ return this.handle.runCommand(command, options);
1106
+ }
1107
+ async setTimeout(timeoutMs) {
1108
+ if (!this.handle.setTimeout) {
1109
+ throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
1110
+ }
1111
+ await this.handle.setTimeout(timeoutMs);
1112
+ }
1113
+ async kill() {
1114
+ await this.handle.destroy();
1115
+ }
1116
+ async destroy() {
1117
+ await this.kill();
1118
+ }
1119
+ };
952
1120
  function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
953
1121
  if (rawPath.startsWith("file://")) {
954
1122
  return fileURLToPath(rawPath);
@@ -1088,48 +1256,31 @@ var Agent = class {
1088
1256
  };
1089
1257
  }
1090
1258
  async createSandboxHandle() {
1091
- if (this.provider === "daytona") {
1092
- const apiKey2 = requireEnv("DAYTONA_API_KEY");
1093
- const { Daytona } = await getDaytona();
1094
- const daytona = new Daytona({ apiKey: apiKey2 });
1095
- const sandbox2 = await daytona.create(
1096
- {
1097
- snapshot: this.template,
1098
- envVars: this.sandboxEnv,
1099
- autoDeleteInterval: -1
1100
- },
1101
- { timeout: DAYTONA_CREATE_TIMEOUT_SEC }
1102
- );
1103
- return createDaytonaHandle(sandbox2);
1259
+ if (this.provider === "e2b") {
1260
+ return createProviderSandboxHandle({
1261
+ provider: "e2b",
1262
+ template: this.template,
1263
+ envs: this.sandboxEnv,
1264
+ allowPublicTraffic: false
1265
+ });
1104
1266
  }
1105
- const apiKey = requireEnv("E2B_API_KEY");
1106
- const { Sandbox } = await getE2b();
1107
- const sandbox = await Sandbox.create(this.template, {
1108
- apiKey,
1109
- envs: this.sandboxEnv,
1110
- network: { allowPublicTraffic: false }
1267
+ return createProviderSandboxHandle({
1268
+ provider: "daytona",
1269
+ template: this.template,
1270
+ envs: this.sandboxEnv
1111
1271
  });
1112
- return createE2bHandle(sandbox);
1113
1272
  }
1114
1273
  async connectSandboxHandle(sandboxId) {
1115
- if (this.provider === "daytona") {
1116
- const apiKey2 = requireEnv("DAYTONA_API_KEY");
1117
- const { Daytona } = await getDaytona();
1118
- const daytona = new Daytona({ apiKey: apiKey2 });
1119
- const sandbox2 = await daytona.get(sandboxId);
1120
- if (sandbox2.state !== "started") {
1121
- if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
1122
- await sandbox2.waitUntilStarted?.(DAYTONA_CREATE_TIMEOUT_SEC);
1123
- } else {
1124
- await sandbox2.start?.(DAYTONA_CREATE_TIMEOUT_SEC);
1125
- }
1126
- }
1127
- return createDaytonaHandle(sandbox2);
1274
+ if (this.provider === "e2b") {
1275
+ return connectProviderSandboxHandle({
1276
+ provider: "e2b",
1277
+ sandboxId
1278
+ });
1128
1279
  }
1129
- const apiKey = requireEnv("E2B_API_KEY");
1130
- const { Sandbox } = await getE2b();
1131
- const sandbox = await Sandbox.connect(sandboxId, { apiKey });
1132
- return createE2bHandle(sandbox);
1280
+ return connectProviderSandboxHandle({
1281
+ provider: "daytona",
1282
+ sandboxId
1283
+ });
1133
1284
  }
1134
1285
  async readRuntimeServerConfig(sandbox) {
1135
1286
  try {
@@ -1626,6 +1777,7 @@ export {
1626
1777
  DeploymentError,
1627
1778
  ExecutionError,
1628
1779
  NeckbeardError,
1780
+ SandboxClient,
1629
1781
  ValidationError,
1630
1782
  normalizeStackFramePath,
1631
1783
  resolveAgentSourceFile,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.13",
3
+ "version": "1.1.15",
4
4
  "description": "Deploy AI agents to E2B and Daytona sandboxes",
5
5
  "type": "module",
6
6
  "exports": {