agent-neckbeard 1.1.9 → 1.1.11

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zacwellmer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -6,6 +6,8 @@ Neckbeard deploys your agent code into an E2B or Daytona sandbox and runs it beh
6
6
 
7
7
  The intent is simple: your production process should not run the agent. The sandbox runs the agent, keeps its filesystem/process state, and exposes a private `/invoke` endpoint that neckbeard calls for each turn.
8
8
 
9
+ This is designed to work from short-lived request handlers and long-running workers, including Vercel Functions, Hatchet workers, and Trigger.dev tasks. See `docs/CONSUMER_ENVIRONMENTS.md` before changing lifecycle, timeout, streaming, or cleanup behavior for those environments.
10
+
9
11
  ## What This Does
10
12
 
11
13
  You write an agent:
@@ -46,10 +48,19 @@ const sandboxId = await agent.deploy();
46
48
  const result = await agent.run({ topic: 'TypeScript generics' }, { sandboxId });
47
49
  ```
48
50
 
49
- `deploy()` bundles your agent, uploads `agent.mjs` and a TypeScript runtime server to the sandbox, starts `node server.mjs`, waits for `/health`, and returns the sandbox ID.
51
+ `deploy()` bundles your agent, uploads `agent.mjs` and the embedded runtime server to the sandbox, starts `node server.mjs`, waits for `/health`, and returns the sandbox ID.
50
52
 
51
53
  `run()` validates input locally, POSTs it to the sandbox server, reads SSE harness events, validates the final output, and returns the existing `{ ok, executionId, output | error }` result shape.
52
54
 
55
+ By default, the package infers the file to bundle from the `new Agent(...)` call stack. In frameworks that bundle server code before runtime, set `sourceFile` to the real agent module so `deploy()` does not rebundle a framework output chunk:
56
+
57
+ ```typescript
58
+ new Agent({
59
+ sourceFile: path.resolve(process.cwd(), 'packages/my-agent/src/agent.ts'),
60
+ // ...
61
+ });
62
+ ```
63
+
53
64
  ## Setup
54
65
 
55
66
  ```bash
@@ -152,13 +163,6 @@ new Agent({
152
163
  template: string,
153
164
  },
154
165
  inputSchema: ZodSchema,
155
- outputSchema?: ZodSchema,
156
- run?: (input, ctx) => Promise<output>,
157
- server?: {
158
- port?: number,
159
- frameSchema: ZodSchema,
160
- handler: ({ input, ctx, signal, emit }) => Promise<void>,
161
- },
162
166
  maxDuration?: number,
163
167
  dependencies?: {
164
168
  apt?: string[],
@@ -167,6 +171,15 @@ new Agent({
167
171
  files?: [{ url, path }],
168
172
  claudeDir?: string,
169
173
  envs?: Record<string, string | undefined>,
174
+ // Run-output agents require:
175
+ outputSchema: ZodSchema,
176
+ run: (input, ctx) => Promise<output>,
177
+ // Streaming agents require this instead of outputSchema/run:
178
+ server: {
179
+ port?: number,
180
+ frameSchema: ZodSchema,
181
+ handler: ({ input, ctx, signal, emit }) => Promise<void>,
182
+ },
170
183
  });
171
184
  ```
172
185
 
@@ -209,9 +222,11 @@ try {
209
222
  ## Testing
210
223
 
211
224
  ```bash
212
- npm test
225
+ npm run check
213
226
  ```
214
227
 
228
+ The local check runs typecheck, repository lint checks, formatting hygiene checks, unit tests, generated runtime verification, CJS build verification, and package dry-run validation.
229
+
215
230
  Jest drives both the fast local suite and the live smoke suites. Each live suite automatically skips when its provider key is not set:
216
231
 
217
232
  ```bash
@@ -0,0 +1,50 @@
1
+ // src/runtime/protocol.ts
2
+ var RUNTIME_PROTOCOL_VERSION = 1;
3
+ function isHarnessEvent(value) {
4
+ if (!value || typeof value !== "object") return false;
5
+ const candidate = value;
6
+ if (typeof candidate.kind !== "string") return false;
7
+ if (typeof candidate.invocationId !== "string") return false;
8
+ if (!hasValidMetadata(candidate)) return false;
9
+ switch (candidate.kind) {
10
+ case "started":
11
+ case "done":
12
+ return true;
13
+ case "frame":
14
+ return Object.hasOwn(candidate, "data");
15
+ case "output":
16
+ return Object.hasOwn(candidate, "output");
17
+ case "error":
18
+ return isSerializedError(candidate.error);
19
+ default:
20
+ return false;
21
+ }
22
+ }
23
+ function hasValidMetadata(candidate) {
24
+ if (candidate.protocolVersion !== void 0 && candidate.protocolVersion !== RUNTIME_PROTOCOL_VERSION) {
25
+ return false;
26
+ }
27
+ if (candidate.sequence !== void 0 && typeof candidate.sequence !== "number") {
28
+ return false;
29
+ }
30
+ if (candidate.timestamp !== void 0 && typeof candidate.timestamp !== "string") {
31
+ return false;
32
+ }
33
+ if (candidate.elapsedMs !== void 0 && typeof candidate.elapsedMs !== "number") {
34
+ return false;
35
+ }
36
+ return true;
37
+ }
38
+ function isSerializedError(value) {
39
+ if (!value || typeof value !== "object") return false;
40
+ const candidate = value;
41
+ if (typeof candidate.message !== "string") return false;
42
+ if (candidate.name !== void 0 && typeof candidate.name !== "string") return false;
43
+ if (candidate.stack !== void 0 && typeof candidate.stack !== "string") return false;
44
+ return true;
45
+ }
46
+
47
+ export {
48
+ RUNTIME_PROTOCOL_VERSION,
49
+ isHarnessEvent
50
+ };
package/dist/index.cjs CHANGED
@@ -30,6 +30,58 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
+ // src/runtime/protocol.ts
34
+ function isHarnessEvent(value) {
35
+ if (!value || typeof value !== "object") return false;
36
+ const candidate = value;
37
+ if (typeof candidate.kind !== "string") return false;
38
+ if (typeof candidate.invocationId !== "string") return false;
39
+ if (!hasValidMetadata(candidate)) return false;
40
+ switch (candidate.kind) {
41
+ case "started":
42
+ case "done":
43
+ return true;
44
+ case "frame":
45
+ return Object.hasOwn(candidate, "data");
46
+ case "output":
47
+ return Object.hasOwn(candidate, "output");
48
+ case "error":
49
+ return isSerializedError(candidate.error);
50
+ default:
51
+ return false;
52
+ }
53
+ }
54
+ function hasValidMetadata(candidate) {
55
+ if (candidate.protocolVersion !== void 0 && candidate.protocolVersion !== RUNTIME_PROTOCOL_VERSION) {
56
+ return false;
57
+ }
58
+ if (candidate.sequence !== void 0 && typeof candidate.sequence !== "number") {
59
+ return false;
60
+ }
61
+ if (candidate.timestamp !== void 0 && typeof candidate.timestamp !== "string") {
62
+ return false;
63
+ }
64
+ if (candidate.elapsedMs !== void 0 && typeof candidate.elapsedMs !== "number") {
65
+ return false;
66
+ }
67
+ return true;
68
+ }
69
+ function isSerializedError(value) {
70
+ if (!value || typeof value !== "object") return false;
71
+ const candidate = value;
72
+ if (typeof candidate.message !== "string") return false;
73
+ if (candidate.name !== void 0 && typeof candidate.name !== "string") return false;
74
+ if (candidate.stack !== void 0 && typeof candidate.stack !== "string") return false;
75
+ return true;
76
+ }
77
+ var RUNTIME_PROTOCOL_VERSION;
78
+ var init_protocol = __esm({
79
+ "src/runtime/protocol.ts"() {
80
+ "use strict";
81
+ RUNTIME_PROTOCOL_VERSION = 1;
82
+ }
83
+ });
84
+
33
85
  // src/sse-framing.ts
34
86
  async function* decodeSseStream(chunks) {
35
87
  let buffer = "";
@@ -64,8 +116,9 @@ function parseFrame(raw) {
64
116
  if (dataLines.length === 0) return void 0;
65
117
  try {
66
118
  return JSON.parse(dataLines.join("\n"));
67
- } catch {
68
- return void 0;
119
+ } catch (error) {
120
+ const message = error instanceof Error ? error.message : String(error);
121
+ throw new Error(`Malformed SSE data frame: ${message}`);
69
122
  }
70
123
  }
71
124
  var init_sse_framing = __esm({
@@ -74,18 +127,6 @@ var init_sse_framing = __esm({
74
127
  }
75
128
  });
76
129
 
77
- // src/runtime/protocol.ts
78
- function isHarnessEvent(value) {
79
- if (!value || typeof value !== "object") return false;
80
- const candidate = value;
81
- return typeof candidate.kind === "string" && typeof candidate.invocationId === "string" && ["started", "frame", "output", "done", "error"].includes(candidate.kind);
82
- }
83
- var init_protocol = __esm({
84
- "src/runtime/protocol.ts"() {
85
- "use strict";
86
- }
87
- });
88
-
89
130
  // src/invoke-client.ts
90
131
  var invoke_client_exports = {};
91
132
  __export(invoke_client_exports, {
@@ -115,6 +156,16 @@ function buildRequestHeaders(options) {
115
156
  }
116
157
  return headers;
117
158
  }
159
+ function validateHarnessEvent(rawEvent, invocationId) {
160
+ if (!isHarnessEvent(rawEvent)) {
161
+ throw new Error("Server returned an invalid harness event");
162
+ }
163
+ if (rawEvent.invocationId !== invocationId) {
164
+ throw new Error(
165
+ `Server returned event for invocation ${rawEvent.invocationId}; expected ${invocationId}`
166
+ );
167
+ }
168
+ }
118
169
  async function* invokeServer(input, options) {
119
170
  const fetchImpl = options.fetch ?? fetch;
120
171
  const invocationId = options.invocationId ?? createInvocationId();
@@ -150,9 +201,7 @@ async function* invokeServer(input, options) {
150
201
  }
151
202
  }
152
203
  for await (const rawEvent of decodeSseStream(chunks())) {
153
- if (!isHarnessEvent(rawEvent)) {
154
- throw new Error("Server returned an invalid harness event");
155
- }
204
+ validateHarnessEvent(rawEvent, invocationId);
156
205
  if (rawEvent.kind === "frame" && options.frameSchema) {
157
206
  yield {
158
207
  ...rawEvent,
@@ -188,6 +237,12 @@ var import_node_url = require("url");
188
237
  var import_node_fs = require("fs");
189
238
  var import_node_path = require("path");
190
239
  var import_node_module = require("module");
240
+ init_protocol();
241
+
242
+ // src/runtime/server-source.generated.ts
243
+ 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';
244
+
245
+ // src/index.ts
191
246
  function readPackageJson(path) {
192
247
  return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
193
248
  }
@@ -245,6 +300,60 @@ var DEFAULT_DEPENDENCIES = {};
245
300
  function isServerAgentConfig(config) {
246
301
  return "server" in config && config.server !== void 0;
247
302
  }
303
+ function isSchemaLike(value) {
304
+ return Boolean(
305
+ value && typeof value === "object" && typeof value.parse === "function"
306
+ );
307
+ }
308
+ function requireSchemaLike(name, value) {
309
+ if (!isSchemaLike(value)) {
310
+ throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
311
+ }
312
+ return value;
313
+ }
314
+ function validateAgentConfig(config) {
315
+ if (!config || typeof config !== "object") {
316
+ throw new ConfigurationError("Agent config must be an object.");
317
+ }
318
+ if (!config.sandbox || typeof config.sandbox !== "object") {
319
+ throw new ConfigurationError("Agent config requires sandbox settings.");
320
+ }
321
+ if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
322
+ throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
323
+ }
324
+ if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
325
+ throw new ConfigurationError("sandbox.template must be a non-empty string.");
326
+ }
327
+ requireSchemaLike("inputSchema", config.inputSchema);
328
+ if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
329
+ throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
330
+ }
331
+ if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
332
+ throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
333
+ }
334
+ if (isServerAgentConfig(config)) {
335
+ if ("run" in config && typeof config.run === "function") {
336
+ throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
337
+ }
338
+ if (!config.server || typeof config.server !== "object") {
339
+ throw new ConfigurationError("server must be an object.");
340
+ }
341
+ if (config.server.port !== void 0) {
342
+ if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
343
+ throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
344
+ }
345
+ }
346
+ requireSchemaLike("server.frameSchema", config.server.frameSchema);
347
+ if (typeof config.server.handler !== "function") {
348
+ throw new ConfigurationError("server.handler must be a function.");
349
+ }
350
+ return;
351
+ }
352
+ if (typeof config.run !== "function") {
353
+ throw new ConfigurationError("run must be a function for run-output agents.");
354
+ }
355
+ requireSchemaLike("outputSchema", config.outputSchema);
356
+ }
248
357
  function getTrafficToken(descriptor) {
249
358
  return descriptor.trafficToken;
250
359
  }
@@ -420,6 +529,9 @@ function createSandboxPaths(provider, homeDir, workDir) {
420
529
  function timeoutMsToSeconds(timeoutMs) {
421
530
  return Math.max(1, Math.ceil(timeoutMs / 1e3));
422
531
  }
532
+ function asError(error) {
533
+ return error instanceof Error ? error : new Error(String(error));
534
+ }
423
535
  async function resolveDaytonaPaths(sandbox) {
424
536
  const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
425
537
  const homeDir = await sandbox.getUserHomeDir() ?? workDir;
@@ -589,6 +701,18 @@ function getCallerFile() {
589
701
  }
590
702
  throw new Error("Could not determine source file");
591
703
  }
704
+ function resolveSourceFile(sourceFile) {
705
+ if (!sourceFile) return getCallerFile();
706
+ const normalized = normalizeStackFramePath(sourceFile);
707
+ if (!normalized) {
708
+ throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
709
+ }
710
+ const resolved = (0, import_node_path.resolve)(normalized);
711
+ if (!(0, import_node_fs.existsSync)(resolved)) {
712
+ throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
713
+ }
714
+ return resolved;
715
+ }
592
716
  function readDirectoryRecursively(dirPath) {
593
717
  const files = [];
594
718
  function walkDir(currentPath) {
@@ -614,32 +738,6 @@ function readDirectoryRecursively(dirPath) {
614
738
  walkDir(dirPath);
615
739
  return files;
616
740
  }
617
- function getRuntimeServerEntryPoint() {
618
- const currentFile = getCurrentModuleFile();
619
- const currentDir = currentFile ? (0, import_node_path.dirname)(currentFile) : process.cwd();
620
- const candidates = [
621
- (0, import_node_path.join)(currentDir, "runtime/server.ts"),
622
- (0, import_node_path.join)(currentDir, "runtime/server.js"),
623
- (0, import_node_path.join)(currentDir, "runtime/server.mjs")
624
- ];
625
- const entry = candidates.find((candidate) => (0, import_node_fs.existsSync)(candidate));
626
- if (!entry) {
627
- throw new DeploymentError(
628
- `Could not find neckbeard runtime server entry. Tried: ${candidates.join(", ")}`
629
- );
630
- }
631
- return entry;
632
- }
633
- function getCurrentModuleFile() {
634
- const stack = new Error().stack?.split("\n") ?? [];
635
- for (const line of stack.slice(1)) {
636
- const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
637
- if (!match) continue;
638
- const normalized = normalizeStackFramePath(match[1]);
639
- if (normalized && (0, import_node_fs.existsSync)(normalized)) return normalized;
640
- }
641
- return null;
642
- }
643
741
  var Agent = class {
644
742
  sandbox;
645
743
  provider;
@@ -665,12 +763,13 @@ var Agent = class {
665
763
  _sandboxId;
666
764
  _sourceFile;
667
765
  constructor(config) {
766
+ validateAgentConfig(config);
668
767
  this.sandbox = config.sandbox;
669
768
  this.provider = config.sandbox.provider;
670
769
  this.template = config.sandbox.template;
671
770
  this.inputSchema = config.inputSchema;
672
771
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
673
- this._sourceFile = getCallerFile();
772
+ this._sourceFile = resolveSourceFile(config.sourceFile);
674
773
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
675
774
  this.files = config.files ?? [];
676
775
  this.claudeDir = config.claudeDir;
@@ -957,16 +1056,6 @@ var require = __neckbeard_createRequire(import.meta.url);
957
1056
  }
958
1057
  }]
959
1058
  });
960
- const serverResult = await esbuild.build({
961
- entryPoints: [getRuntimeServerEntryPoint()],
962
- bundle: true,
963
- platform: "node",
964
- target: NODE_TARGET,
965
- format: "esm",
966
- write: false,
967
- minify: false,
968
- external: ["./agent.mjs"]
969
- });
970
1059
  const sandbox = await this.createSandboxHandle();
971
1060
  const { paths } = sandbox;
972
1061
  await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
@@ -1042,8 +1131,9 @@ var require = __neckbeard_createRequire(import.meta.url);
1042
1131
  }
1043
1132
  }
1044
1133
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1045
- await sandbox.writeFile(paths.serverModule, serverResult.outputFiles[0].text);
1134
+ await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
1046
1135
  const serverConfig = {
1136
+ protocolVersion: RUNTIME_PROTOCOL_VERSION,
1047
1137
  port: this._server?.port ?? DEFAULT_SERVER_PORT,
1048
1138
  maxDurationMs: this.maxDuration * 1e3,
1049
1139
  sandboxContext: {
@@ -1146,7 +1236,12 @@ ${parts.join("\n\n")}`;
1146
1236
  }
1147
1237
  try {
1148
1238
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1149
- const validatedInput = this.inputSchema.parse(input);
1239
+ let validatedInput;
1240
+ try {
1241
+ validatedInput = this.inputSchema.parse(input);
1242
+ } catch (error) {
1243
+ throw new ValidationError("Input validation failed.", asError(error));
1244
+ }
1150
1245
  const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
1151
1246
  let output;
1152
1247
  let sawOutput = false;
@@ -1174,7 +1269,12 @@ ${parts.join("\n\n")}`;
1174
1269
  error: new ExecutionError("Agent server completed without returning output.")
1175
1270
  };
1176
1271
  }
1177
- const validated = this.outputSchema ? this.outputSchema.parse(output) : output;
1272
+ let validated;
1273
+ try {
1274
+ validated = this.outputSchema ? this.outputSchema.parse(output) : output;
1275
+ } catch (error) {
1276
+ throw new ValidationError("Output validation failed.", asError(error));
1277
+ }
1178
1278
  return { ok: true, executionId, output: validated };
1179
1279
  } catch (err) {
1180
1280
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
@@ -1192,21 +1292,31 @@ ${parts.join("\n\n")}`;
1192
1292
  }
1193
1293
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1194
1294
  const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
1195
- const validated = this.inputSchema.parse(input);
1196
- for await (const frame of invokeServer2(validated, {
1197
- serverUrl: connection.serverUrl,
1198
- provider: connection.provider,
1199
- trafficToken: getTrafficToken(connection),
1200
- frameSchema: this.frameSchema,
1201
- signal: options?.signal
1202
- })) {
1203
- if (frame.kind === "frame") {
1204
- yield frame.data;
1205
- } else if (frame.kind === "error") {
1206
- const err = new ExecutionError(frame.error.message);
1207
- err.stack = frame.error.stack;
1208
- throw err;
1295
+ let validated;
1296
+ try {
1297
+ validated = this.inputSchema.parse(input);
1298
+ } catch (error) {
1299
+ throw new ValidationError("Input validation failed.", asError(error));
1300
+ }
1301
+ try {
1302
+ for await (const frame of invokeServer2(validated, {
1303
+ serverUrl: connection.serverUrl,
1304
+ provider: connection.provider,
1305
+ trafficToken: getTrafficToken(connection),
1306
+ frameSchema: this.frameSchema,
1307
+ signal: options?.signal
1308
+ })) {
1309
+ if (frame.kind === "frame") {
1310
+ yield frame.data;
1311
+ } else if (frame.kind === "error") {
1312
+ const err = new ExecutionError(frame.error.message);
1313
+ err.stack = frame.error.stack;
1314
+ throw err;
1315
+ }
1209
1316
  }
1317
+ } catch (error) {
1318
+ if (error instanceof ExecutionError) throw error;
1319
+ throw error instanceof Error ? error : new Error(String(error));
1210
1320
  }
1211
1321
  }
1212
1322
  };
package/dist/index.d.cts CHANGED
@@ -107,6 +107,14 @@ interface AgentSharedConfig<TInput> {
107
107
  sandbox: SandboxConfig;
108
108
  inputSchema: SchemaLike<TInput>;
109
109
  maxDuration?: number;
110
+ /**
111
+ * Local source file to bundle for deploy().
112
+ *
113
+ * By default this is inferred from the Agent constructor stack. Set this
114
+ * explicitly when a framework bundles server code before runtime, such as a
115
+ * Next.js route handler running from `.next/server/chunks/*.js`.
116
+ */
117
+ sourceFile?: string;
110
118
  /** OS-level dependencies to install in the sandbox. Defaults to Claude Code. Set to {} to skip. */
111
119
  dependencies?: OsDependencies;
112
120
  /**
@@ -214,25 +222,6 @@ type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig;
214
222
  * Mode is discriminated at runtime by the presence of `server` vs `run`.
215
223
  */
216
224
  type AgentConfig<TInput, TOutput, TFrame = unknown> = RunAgentConfig<TInput, TOutput> | ServerAgentConfig<TInput, TFrame>;
217
- interface RuntimeConnection {
218
- sandboxId: string;
219
- serverUrl: string;
220
- provider: SandboxProvider;
221
- trafficToken?: string;
222
- }
223
- /**
224
- * Normalizes a path captured from a stack trace into a real on-disk file
225
- * path. Handles plain paths, `file://` URLs, and `webpack-internal://` URLs
226
- * emitted when user code runs inside a Next.js route handler or other
227
- * webpack-bundled context.
228
- *
229
- * Returns null when the input is a `webpack-internal://` URL but the
230
- * resolved disk path does not exist — callers should skip and keep walking
231
- * the stack in that case.
232
- *
233
- * @internal Exported for testing.
234
- */
235
- declare function normalizeStackFramePath(rawPath: string, cwd?: string): string | null;
236
225
  type AgentMode = 'run' | 'stream';
237
226
  declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
238
227
  readonly sandbox: SandboxConfig;
@@ -250,16 +239,6 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
250
239
  readonly claudeDir?: string;
251
240
  readonly envs: Record<string, string | undefined>;
252
241
  readonly build: BuildOptions;
253
- /** @internal Used by the in-sandbox server for run-output agents. */
254
- _run?: (input: TInput, ctx: AgentRunContext) => Promise<TOutput>;
255
- /** @internal Used by the in-sandbox server for streaming agents. */
256
- _server?: ServerAgentConfig<TInput, TFrame>['server'];
257
- /** @internal Runtime state populated by deploy(). */
258
- _serverRuntime?: {
259
- sessionId?: string;
260
- commandId?: string;
261
- connection: RuntimeConnection;
262
- };
263
242
  private _sandboxId?;
264
243
  private _sourceFile;
265
244
  constructor(config: RunAgentConfig<TInput, TOutput>);
@@ -356,4 +335,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
356
335
  }): AsyncGenerator<TFrame>;
357
336
  }
358
337
 
359
- 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 OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError, normalizeStackFramePath };
338
+ 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 OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError };
package/dist/index.d.ts CHANGED
@@ -107,6 +107,14 @@ interface AgentSharedConfig<TInput> {
107
107
  sandbox: SandboxConfig;
108
108
  inputSchema: SchemaLike<TInput>;
109
109
  maxDuration?: number;
110
+ /**
111
+ * Local source file to bundle for deploy().
112
+ *
113
+ * By default this is inferred from the Agent constructor stack. Set this
114
+ * explicitly when a framework bundles server code before runtime, such as a
115
+ * Next.js route handler running from `.next/server/chunks/*.js`.
116
+ */
117
+ sourceFile?: string;
110
118
  /** OS-level dependencies to install in the sandbox. Defaults to Claude Code. Set to {} to skip. */
111
119
  dependencies?: OsDependencies;
112
120
  /**
@@ -214,25 +222,6 @@ type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig;
214
222
  * Mode is discriminated at runtime by the presence of `server` vs `run`.
215
223
  */
216
224
  type AgentConfig<TInput, TOutput, TFrame = unknown> = RunAgentConfig<TInput, TOutput> | ServerAgentConfig<TInput, TFrame>;
217
- interface RuntimeConnection {
218
- sandboxId: string;
219
- serverUrl: string;
220
- provider: SandboxProvider;
221
- trafficToken?: string;
222
- }
223
- /**
224
- * Normalizes a path captured from a stack trace into a real on-disk file
225
- * path. Handles plain paths, `file://` URLs, and `webpack-internal://` URLs
226
- * emitted when user code runs inside a Next.js route handler or other
227
- * webpack-bundled context.
228
- *
229
- * Returns null when the input is a `webpack-internal://` URL but the
230
- * resolved disk path does not exist — callers should skip and keep walking
231
- * the stack in that case.
232
- *
233
- * @internal Exported for testing.
234
- */
235
- declare function normalizeStackFramePath(rawPath: string, cwd?: string): string | null;
236
225
  type AgentMode = 'run' | 'stream';
237
226
  declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
238
227
  readonly sandbox: SandboxConfig;
@@ -250,16 +239,6 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
250
239
  readonly claudeDir?: string;
251
240
  readonly envs: Record<string, string | undefined>;
252
241
  readonly build: BuildOptions;
253
- /** @internal Used by the in-sandbox server for run-output agents. */
254
- _run?: (input: TInput, ctx: AgentRunContext) => Promise<TOutput>;
255
- /** @internal Used by the in-sandbox server for streaming agents. */
256
- _server?: ServerAgentConfig<TInput, TFrame>['server'];
257
- /** @internal Runtime state populated by deploy(). */
258
- _serverRuntime?: {
259
- sessionId?: string;
260
- commandId?: string;
261
- connection: RuntimeConnection;
262
- };
263
242
  private _sandboxId?;
264
243
  private _sourceFile;
265
244
  constructor(config: RunAgentConfig<TInput, TOutput>);
@@ -356,4 +335,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
356
335
  }): AsyncGenerator<TFrame>;
357
336
  }
358
337
 
359
- 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 OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError, normalizeStackFramePath };
338
+ 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 OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError };
package/dist/index.js CHANGED
@@ -1,8 +1,17 @@
1
+ import {
2
+ RUNTIME_PROTOCOL_VERSION
3
+ } from "./chunk-AM2J5KBI.js";
4
+
1
5
  // src/index.ts
2
6
  import { fileURLToPath } from "url";
3
7
  import { existsSync, readdirSync, readFileSync, statSync } from "fs";
4
8
  import { dirname, join, relative, resolve } from "path";
5
9
  import { builtinModules, createRequire } from "module";
10
+
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';
13
+
14
+ // src/index.ts
6
15
  function readPackageJson(path) {
7
16
  return JSON.parse(readFileSync(path, "utf8"));
8
17
  }
@@ -60,6 +69,60 @@ var DEFAULT_DEPENDENCIES = {};
60
69
  function isServerAgentConfig(config) {
61
70
  return "server" in config && config.server !== void 0;
62
71
  }
72
+ function isSchemaLike(value) {
73
+ return Boolean(
74
+ value && typeof value === "object" && typeof value.parse === "function"
75
+ );
76
+ }
77
+ function requireSchemaLike(name, value) {
78
+ if (!isSchemaLike(value)) {
79
+ throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
80
+ }
81
+ return value;
82
+ }
83
+ function validateAgentConfig(config) {
84
+ if (!config || typeof config !== "object") {
85
+ throw new ConfigurationError("Agent config must be an object.");
86
+ }
87
+ if (!config.sandbox || typeof config.sandbox !== "object") {
88
+ throw new ConfigurationError("Agent config requires sandbox settings.");
89
+ }
90
+ if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
91
+ throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
92
+ }
93
+ if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
94
+ throw new ConfigurationError("sandbox.template must be a non-empty string.");
95
+ }
96
+ requireSchemaLike("inputSchema", config.inputSchema);
97
+ if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
98
+ throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
99
+ }
100
+ if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
101
+ throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
102
+ }
103
+ if (isServerAgentConfig(config)) {
104
+ if ("run" in config && typeof config.run === "function") {
105
+ throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
106
+ }
107
+ if (!config.server || typeof config.server !== "object") {
108
+ throw new ConfigurationError("server must be an object.");
109
+ }
110
+ if (config.server.port !== void 0) {
111
+ if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
112
+ throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
113
+ }
114
+ }
115
+ requireSchemaLike("server.frameSchema", config.server.frameSchema);
116
+ if (typeof config.server.handler !== "function") {
117
+ throw new ConfigurationError("server.handler must be a function.");
118
+ }
119
+ return;
120
+ }
121
+ if (typeof config.run !== "function") {
122
+ throw new ConfigurationError("run must be a function for run-output agents.");
123
+ }
124
+ requireSchemaLike("outputSchema", config.outputSchema);
125
+ }
63
126
  function getTrafficToken(descriptor) {
64
127
  return descriptor.trafficToken;
65
128
  }
@@ -235,6 +298,9 @@ function createSandboxPaths(provider, homeDir, workDir) {
235
298
  function timeoutMsToSeconds(timeoutMs) {
236
299
  return Math.max(1, Math.ceil(timeoutMs / 1e3));
237
300
  }
301
+ function asError(error) {
302
+ return error instanceof Error ? error : new Error(String(error));
303
+ }
238
304
  async function resolveDaytonaPaths(sandbox) {
239
305
  const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
240
306
  const homeDir = await sandbox.getUserHomeDir() ?? workDir;
@@ -404,6 +470,18 @@ function getCallerFile() {
404
470
  }
405
471
  throw new Error("Could not determine source file");
406
472
  }
473
+ function resolveSourceFile(sourceFile) {
474
+ if (!sourceFile) return getCallerFile();
475
+ const normalized = normalizeStackFramePath(sourceFile);
476
+ if (!normalized) {
477
+ throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
478
+ }
479
+ const resolved = resolve(normalized);
480
+ if (!existsSync(resolved)) {
481
+ throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
482
+ }
483
+ return resolved;
484
+ }
407
485
  function readDirectoryRecursively(dirPath) {
408
486
  const files = [];
409
487
  function walkDir(currentPath) {
@@ -429,32 +507,6 @@ function readDirectoryRecursively(dirPath) {
429
507
  walkDir(dirPath);
430
508
  return files;
431
509
  }
432
- function getRuntimeServerEntryPoint() {
433
- const currentFile = getCurrentModuleFile();
434
- const currentDir = currentFile ? dirname(currentFile) : process.cwd();
435
- const candidates = [
436
- join(currentDir, "runtime/server.ts"),
437
- join(currentDir, "runtime/server.js"),
438
- join(currentDir, "runtime/server.mjs")
439
- ];
440
- const entry = candidates.find((candidate) => existsSync(candidate));
441
- if (!entry) {
442
- throw new DeploymentError(
443
- `Could not find neckbeard runtime server entry. Tried: ${candidates.join(", ")}`
444
- );
445
- }
446
- return entry;
447
- }
448
- function getCurrentModuleFile() {
449
- const stack = new Error().stack?.split("\n") ?? [];
450
- for (const line of stack.slice(1)) {
451
- const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
452
- if (!match) continue;
453
- const normalized = normalizeStackFramePath(match[1]);
454
- if (normalized && existsSync(normalized)) return normalized;
455
- }
456
- return null;
457
- }
458
510
  var Agent = class {
459
511
  sandbox;
460
512
  provider;
@@ -480,12 +532,13 @@ var Agent = class {
480
532
  _sandboxId;
481
533
  _sourceFile;
482
534
  constructor(config) {
535
+ validateAgentConfig(config);
483
536
  this.sandbox = config.sandbox;
484
537
  this.provider = config.sandbox.provider;
485
538
  this.template = config.sandbox.template;
486
539
  this.inputSchema = config.inputSchema;
487
540
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
488
- this._sourceFile = getCallerFile();
541
+ this._sourceFile = resolveSourceFile(config.sourceFile);
489
542
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
490
543
  this.files = config.files ?? [];
491
544
  this.claudeDir = config.claudeDir;
@@ -772,16 +825,6 @@ var require = __neckbeard_createRequire(import.meta.url);
772
825
  }
773
826
  }]
774
827
  });
775
- const serverResult = await esbuild.build({
776
- entryPoints: [getRuntimeServerEntryPoint()],
777
- bundle: true,
778
- platform: "node",
779
- target: NODE_TARGET,
780
- format: "esm",
781
- write: false,
782
- minify: false,
783
- external: ["./agent.mjs"]
784
- });
785
828
  const sandbox = await this.createSandboxHandle();
786
829
  const { paths } = sandbox;
787
830
  await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
@@ -857,8 +900,9 @@ var require = __neckbeard_createRequire(import.meta.url);
857
900
  }
858
901
  }
859
902
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
860
- await sandbox.writeFile(paths.serverModule, serverResult.outputFiles[0].text);
903
+ await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
861
904
  const serverConfig = {
905
+ protocolVersion: RUNTIME_PROTOCOL_VERSION,
862
906
  port: this._server?.port ?? DEFAULT_SERVER_PORT,
863
907
  maxDurationMs: this.maxDuration * 1e3,
864
908
  sandboxContext: {
@@ -961,8 +1005,13 @@ ${parts.join("\n\n")}`;
961
1005
  }
962
1006
  try {
963
1007
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
964
- const validatedInput = this.inputSchema.parse(input);
965
- const { invokeServer } = await import("./invoke-client-WYMFPR3F.js");
1008
+ let validatedInput;
1009
+ try {
1010
+ validatedInput = this.inputSchema.parse(input);
1011
+ } catch (error) {
1012
+ throw new ValidationError("Input validation failed.", asError(error));
1013
+ }
1014
+ const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
966
1015
  let output;
967
1016
  let sawOutput = false;
968
1017
  for await (const event of invokeServer(validatedInput, {
@@ -989,7 +1038,12 @@ ${parts.join("\n\n")}`;
989
1038
  error: new ExecutionError("Agent server completed without returning output.")
990
1039
  };
991
1040
  }
992
- const validated = this.outputSchema ? this.outputSchema.parse(output) : output;
1041
+ let validated;
1042
+ try {
1043
+ validated = this.outputSchema ? this.outputSchema.parse(output) : output;
1044
+ } catch (error) {
1045
+ throw new ValidationError("Output validation failed.", asError(error));
1046
+ }
993
1047
  return { ok: true, executionId, output: validated };
994
1048
  } catch (err) {
995
1049
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
@@ -1006,22 +1060,32 @@ ${parts.join("\n\n")}`;
1006
1060
  );
1007
1061
  }
1008
1062
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1009
- const { invokeServer } = await import("./invoke-client-WYMFPR3F.js");
1010
- const validated = this.inputSchema.parse(input);
1011
- for await (const frame of invokeServer(validated, {
1012
- serverUrl: connection.serverUrl,
1013
- provider: connection.provider,
1014
- trafficToken: getTrafficToken(connection),
1015
- frameSchema: this.frameSchema,
1016
- signal: options?.signal
1017
- })) {
1018
- if (frame.kind === "frame") {
1019
- yield frame.data;
1020
- } else if (frame.kind === "error") {
1021
- const err = new ExecutionError(frame.error.message);
1022
- err.stack = frame.error.stack;
1023
- throw err;
1063
+ const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
1064
+ let validated;
1065
+ try {
1066
+ validated = this.inputSchema.parse(input);
1067
+ } catch (error) {
1068
+ throw new ValidationError("Input validation failed.", asError(error));
1069
+ }
1070
+ try {
1071
+ for await (const frame of invokeServer(validated, {
1072
+ serverUrl: connection.serverUrl,
1073
+ provider: connection.provider,
1074
+ trafficToken: getTrafficToken(connection),
1075
+ frameSchema: this.frameSchema,
1076
+ signal: options?.signal
1077
+ })) {
1078
+ if (frame.kind === "frame") {
1079
+ yield frame.data;
1080
+ } else if (frame.kind === "error") {
1081
+ const err = new ExecutionError(frame.error.message);
1082
+ err.stack = frame.error.stack;
1083
+ throw err;
1084
+ }
1024
1085
  }
1086
+ } catch (error) {
1087
+ if (error instanceof ExecutionError) throw error;
1088
+ throw error instanceof Error ? error : new Error(String(error));
1025
1089
  }
1026
1090
  }
1027
1091
  };
@@ -1,3 +1,7 @@
1
+ import {
2
+ isHarnessEvent
3
+ } from "./chunk-AM2J5KBI.js";
4
+
1
5
  // src/sse-framing.ts
2
6
  async function* decodeSseStream(chunks) {
3
7
  let buffer = "";
@@ -32,18 +36,12 @@ function parseFrame(raw) {
32
36
  if (dataLines.length === 0) return void 0;
33
37
  try {
34
38
  return JSON.parse(dataLines.join("\n"));
35
- } catch {
36
- return void 0;
39
+ } catch (error) {
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ throw new Error(`Malformed SSE data frame: ${message}`);
37
42
  }
38
43
  }
39
44
 
40
- // src/runtime/protocol.ts
41
- function isHarnessEvent(value) {
42
- if (!value || typeof value !== "object") return false;
43
- const candidate = value;
44
- return typeof candidate.kind === "string" && typeof candidate.invocationId === "string" && ["started", "frame", "output", "done", "error"].includes(candidate.kind);
45
- }
46
-
47
45
  // src/invoke-client.ts
48
46
  function createInvocationId() {
49
47
  return `invoke_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
@@ -69,6 +67,16 @@ function buildRequestHeaders(options) {
69
67
  }
70
68
  return headers;
71
69
  }
70
+ function validateHarnessEvent(rawEvent, invocationId) {
71
+ if (!isHarnessEvent(rawEvent)) {
72
+ throw new Error("Server returned an invalid harness event");
73
+ }
74
+ if (rawEvent.invocationId !== invocationId) {
75
+ throw new Error(
76
+ `Server returned event for invocation ${rawEvent.invocationId}; expected ${invocationId}`
77
+ );
78
+ }
79
+ }
72
80
  async function* invokeServer(input, options) {
73
81
  const fetchImpl = options.fetch ?? fetch;
74
82
  const invocationId = options.invocationId ?? createInvocationId();
@@ -104,9 +112,7 @@ async function* invokeServer(input, options) {
104
112
  }
105
113
  }
106
114
  for await (const rawEvent of decodeSseStream(chunks())) {
107
- if (!isHarnessEvent(rawEvent)) {
108
- throw new Error("Server returned an invalid harness event");
109
- }
115
+ validateHarnessEvent(rawEvent, invocationId);
110
116
  if (rawEvent.kind === "frame" && options.frameSchema) {
111
117
  yield {
112
118
  ...rawEvent,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.9",
3
+ "version": "1.1.11",
4
4
  "description": "Deploy AI agents to E2B and Daytona sandboxes",
5
5
  "type": "module",
6
6
  "exports": {
@@ -25,15 +25,21 @@
25
25
  "engines": {
26
26
  "node": ">=20.0.0"
27
27
  },
28
+ "packageManager": "npm@10.9.4",
28
29
  "scripts": {
29
- "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
30
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && node scripts/generate-runtime-server-source.mjs && tsup",
31
+ "check": "npm run typecheck && npm run lint && npm run format:check && npm test && npm run check:generated && npm run test:cjs && npm run pack:dry-run",
32
+ "check:generated": "node scripts/verify-runtime-server-source.mjs",
30
33
  "dev": "tsup --watch",
34
+ "format:check": "node scripts/check-format.mjs",
35
+ "lint": "node scripts/repo-lint.mjs",
36
+ "pack:dry-run": "npm pack --dry-run",
31
37
  "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs",
32
38
  "test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs --watch",
33
39
  "test:e2e": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand",
34
40
  "test:e2e:e2b": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand --testNamePattern=\"live E2B smoke tests\"",
35
41
  "test:e2e:daytona": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand --testNamePattern=\"live Daytona smoke tests\"",
36
- "test:cjs": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs --testPathPatterns=cjs-build",
42
+ "test:cjs": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.build.config.mjs",
37
43
  "typecheck": "tsc --noEmit -p tsconfig.test.json",
38
44
  "prepare": "npm run build"
39
45
  },
@@ -1,163 +0,0 @@
1
- // src/runtime/server.ts
2
- import { createServer } from "http";
3
- import { readFileSync } from "fs";
4
- import { fileURLToPath } from "url";
5
- import { dirname, join } from "path";
6
- var CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");
7
- var CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
8
- function createLogger() {
9
- return {
10
- debug: (message, ...args) => console.log("[DEBUG]", message, ...args),
11
- info: (message, ...args) => console.log("[INFO]", message, ...args),
12
- warn: (message, ...args) => console.warn("[WARN]", message, ...args),
13
- error: (message, ...args) => console.error("[ERROR]", message, ...args)
14
- };
15
- }
16
- function serializeError(error) {
17
- if (error instanceof Error) {
18
- return {
19
- name: error.name,
20
- message: error.message,
21
- stack: error.stack
22
- };
23
- }
24
- return { message: String(error) };
25
- }
26
- function sendJson(res, status, body) {
27
- res.writeHead(status, { "content-type": "application/json" });
28
- res.end(JSON.stringify(body));
29
- }
30
- function sendSseFrame(res, event) {
31
- res.write(`data: ${JSON.stringify(event)}
32
-
33
- `);
34
- }
35
- async function readRequestBody(req) {
36
- const chunks = [];
37
- for await (const chunk of req) {
38
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
39
- }
40
- return Buffer.concat(chunks).toString("utf-8");
41
- }
42
- async function loadAgent() {
43
- const mod = await import(new URL("./agent.mjs", import.meta.url).href);
44
- const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(
45
- (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)
46
- );
47
- if (!agent || typeof agent !== "object") {
48
- throw new Error(
49
- `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`
50
- );
51
- }
52
- return agent;
53
- }
54
- async function main() {
55
- const agent = await loadAgent();
56
- const server = createServer(async (req, res) => {
57
- try {
58
- const url = new URL(req.url ?? "/", "http://localhost");
59
- if (url.pathname === "/health" && req.method === "GET") {
60
- return sendJson(res, 200, { ok: true });
61
- }
62
- if (url.pathname === "/shutdown" && req.method === "POST") {
63
- sendJson(res, 200, { ok: true });
64
- setTimeout(() => shutdown(), 10).unref();
65
- return;
66
- }
67
- if (url.pathname === "/invoke" && req.method === "POST") {
68
- const rawBody = await readRequestBody(req);
69
- let requestBody;
70
- try {
71
- requestBody = JSON.parse(rawBody);
72
- } catch {
73
- return sendJson(res, 400, { error: "invalid JSON body" });
74
- }
75
- if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {
76
- return sendJson(res, 400, { error: "invalid invoke request" });
77
- }
78
- let validatedInput;
79
- try {
80
- validatedInput = agent.inputSchema.parse(requestBody.input);
81
- } catch (error) {
82
- return sendJson(res, 400, {
83
- error: `input validation failed: ${serializeError(error).message}`
84
- });
85
- }
86
- res.writeHead(200, {
87
- "content-type": "text/event-stream",
88
- "cache-control": "no-cache, no-transform",
89
- connection: "keep-alive",
90
- "x-accel-buffering": "no"
91
- });
92
- const controller = new AbortController();
93
- req.on("aborted", () => controller.abort());
94
- res.on("close", () => {
95
- if (!res.writableEnded) {
96
- controller.abort();
97
- }
98
- });
99
- const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);
100
- const invocationId = requestBody.invocationId;
101
- const emitHarnessEvent = (event) => {
102
- if (!res.writableEnded) {
103
- sendSseFrame(res, event);
104
- }
105
- };
106
- const ctx = {
107
- executionId: invocationId,
108
- signal: controller.signal,
109
- env: process.env,
110
- sandbox: CONFIG.sandboxContext,
111
- logger: createLogger()
112
- };
113
- try {
114
- emitHarnessEvent({ kind: "started", invocationId });
115
- if (agent._server) {
116
- await agent._server.handler({
117
- input: validatedInput,
118
- ctx,
119
- signal: controller.signal,
120
- emit: async (data) => emitHarnessEvent({ kind: "frame", invocationId, data })
121
- });
122
- } else if (agent._run) {
123
- const output = await agent._run(validatedInput, ctx);
124
- emitHarnessEvent({ kind: "output", invocationId, output });
125
- } else {
126
- throw new Error("Agent has neither a run handler nor a server handler.");
127
- }
128
- emitHarnessEvent({ kind: "done", invocationId });
129
- } catch (error) {
130
- emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });
131
- } finally {
132
- clearTimeout(timeout);
133
- if (!res.writableEnded) {
134
- res.end();
135
- }
136
- }
137
- return;
138
- }
139
- return sendJson(res, 404, { error: "not found" });
140
- } catch (error) {
141
- console.error("[neckbeard-server] unexpected error", error);
142
- if (!res.headersSent) {
143
- sendJson(res, 500, { error: "internal error" });
144
- } else if (!res.writableEnded) {
145
- res.end();
146
- }
147
- }
148
- });
149
- function shutdown() {
150
- console.log("[neckbeard-server] shutting down");
151
- server.close(() => process.exit(0));
152
- setTimeout(() => process.exit(0), 5e3).unref();
153
- }
154
- server.listen(CONFIG.port, "0.0.0.0", () => {
155
- console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);
156
- });
157
- process.on("SIGTERM", shutdown);
158
- process.on("SIGINT", shutdown);
159
- }
160
- main().catch((error) => {
161
- console.error("[neckbeard-server] failed to start", error);
162
- process.exit(1);
163
- });