agent-neckbeard 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,
@@ -181,16 +230,19 @@ __export(index_exports, {
181
230
  ExecutionError: () => ExecutionError,
182
231
  NeckbeardError: () => NeckbeardError,
183
232
  ValidationError: () => ValidationError,
184
- normalizeStackFramePath: () => normalizeStackFramePath
233
+ normalizeStackFramePath: () => normalizeStackFramePath,
234
+ resolveAgentSourceFile: () => resolveAgentSourceFile,
235
+ withNeckbeardNextConfig: () => withNeckbeardNextConfig
185
236
  });
186
237
  module.exports = __toCommonJS(index_exports);
187
238
  var import_node_url = require("url");
188
239
  var import_node_fs = require("fs");
189
240
  var import_node_path = require("path");
190
241
  var import_node_module = require("module");
242
+ init_protocol();
191
243
 
192
244
  // src/runtime/server-source.generated.ts
193
- 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";\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\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 sendSseFrame(res, event) {\n res.write(`data: ${JSON.stringify(event)}\n\n`);\n}\nasync function readRequestBody(req) {\n const chunks = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString("utf-8");\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, { ok: true });\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 const rawBody = await readRequestBody(req);\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 timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const emitHarnessEvent = (event) => {\n if (!res.writableEnded) {\n sendSseFrame(res, event);\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 emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => emitHarnessEvent({ kind: "frame", invocationId, data })\n });\n } else if (agent._run) {\n const output = await agent._run(validatedInput, ctx);\n emitHarnessEvent({ kind: "output", invocationId, output });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n 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';
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';
194
246
 
195
247
  // src/index.ts
196
248
  function readPackageJson(path) {
@@ -205,6 +257,8 @@ var QUICK_COMMAND_TIMEOUT_MS = 3e4;
205
257
  var DAYTONA_CREATE_TIMEOUT_SEC = 120;
206
258
  var NODE_TARGET = "node20";
207
259
  var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
260
+ var NECKBEARD_PACKAGE_NAME = "agent-neckbeard";
261
+ var NECKBEARD_SANDBOX_RUNTIME_ENV = "AGENT_NECKBEARD_SANDBOX_RUNTIME";
208
262
  var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
209
263
  var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
210
264
  var DEFAULT_SERVER_PORT = 3e3;
@@ -246,10 +300,412 @@ var ConfigurationError = class extends NeckbeardError {
246
300
  this.name = "ConfigurationError";
247
301
  }
248
302
  };
303
+ function resolveAgentSourceFile(candidates, options = {}) {
304
+ const normalizedCandidates = normalizeNonEmptyStrings("candidates", candidates);
305
+ const sourceFile = normalizedCandidates.find((candidate) => (0, import_node_fs.existsSync)(candidate));
306
+ if (sourceFile) {
307
+ return sourceFile;
308
+ }
309
+ if (process.env[NECKBEARD_SANDBOX_RUNTIME_ENV] === "1") {
310
+ const sandboxSourceFile = options.sandboxSourceFile ?? (0, import_node_path.resolve)(process.cwd(), "agent.mjs");
311
+ if ((0, import_node_fs.existsSync)(sandboxSourceFile)) {
312
+ return sandboxSourceFile;
313
+ }
314
+ }
315
+ throw new ConfigurationError(
316
+ options.errorMessage ?? `Could not resolve agent source file. Checked: ${candidates.join(", ")}`
317
+ );
318
+ }
319
+ function withNeckbeardNextConfig(nextConfig, options) {
320
+ const sourceFiles = normalizeNonEmptyStrings("sourceFiles", options.sourceFiles);
321
+ const routeGlobs = normalizeNonEmptyStrings("routeGlob", options.routeGlob ?? "/*");
322
+ const experimental = asRecord(nextConfig.experimental);
323
+ const useLegacyExperimental = options.legacyExperimental ?? ("serverComponentsExternalPackages" in experimental || "outputFileTracingIncludes" in experimental || "outputFileTracingRoot" in experimental);
324
+ if (useLegacyExperimental) {
325
+ const nextExperimental = {
326
+ ...experimental,
327
+ serverComponentsExternalPackages: mergeStringArray(
328
+ experimental.serverComponentsExternalPackages,
329
+ [NECKBEARD_PACKAGE_NAME]
330
+ ),
331
+ outputFileTracingIncludes: mergeTracingIncludes(
332
+ experimental.outputFileTracingIncludes,
333
+ routeGlobs,
334
+ sourceFiles
335
+ )
336
+ };
337
+ if (options.outputFileTracingRoot !== void 0) {
338
+ nextExperimental.outputFileTracingRoot = options.outputFileTracingRoot;
339
+ }
340
+ return {
341
+ ...nextConfig,
342
+ experimental: nextExperimental,
343
+ webpack: withNextTraceIncludeWebpack(nextConfig.webpack, sourceFiles, routeGlobs)
344
+ };
345
+ }
346
+ const result = {
347
+ ...nextConfig,
348
+ serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
349
+ NECKBEARD_PACKAGE_NAME
350
+ ]),
351
+ outputFileTracingIncludes: mergeTracingIncludes(
352
+ nextConfig.outputFileTracingIncludes,
353
+ routeGlobs,
354
+ sourceFiles
355
+ )
356
+ };
357
+ if (options.outputFileTracingRoot !== void 0) {
358
+ result.outputFileTracingRoot = options.outputFileTracingRoot;
359
+ }
360
+ return result;
361
+ }
362
+ var NextTraceIncludePlugin = class {
363
+ constructor(appDir, sourceFiles, routeGlobs) {
364
+ this.appDir = appDir;
365
+ this.sourceFiles = sourceFiles;
366
+ this.routeGlobs = routeGlobs;
367
+ }
368
+ apply(compiler) {
369
+ const compilationHook = compiler.hooks?.compilation;
370
+ if (typeof compilationHook?.tap === "function") {
371
+ compilationHook.tap("NeckbeardNextTraceIncludePlugin", (compilation) => {
372
+ const processAssets = compilation.hooks?.processAssets;
373
+ if (typeof processAssets?.tap !== "function") {
374
+ return;
375
+ }
376
+ processAssets.tap({
377
+ name: "NeckbeardNextTraceIncludePlugin",
378
+ stage: compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_REPORT ?? 5e3
379
+ }, (assets) => {
380
+ appendIncludesToTraceAssets({
381
+ appDir: this.appDir,
382
+ assets,
383
+ outputPath: compilation.outputOptions?.path ?? compiler.outputPath ?? "",
384
+ rawSource: compiler.webpack?.sources?.RawSource,
385
+ routeGlobs: this.routeGlobs,
386
+ sourceFiles: this.sourceFiles,
387
+ updateAsset: compilation.updateAsset?.bind(compilation)
388
+ });
389
+ });
390
+ });
391
+ }
392
+ const afterEmit = compiler.hooks?.afterEmit;
393
+ const done = compiler.hooks?.done;
394
+ if (typeof afterEmit?.tap !== "function" && typeof done?.tap !== "function") {
395
+ return;
396
+ }
397
+ if (!compiler.outputPath) {
398
+ return;
399
+ }
400
+ const appendIncludes = () => {
401
+ appendIncludesToTraceFiles(
402
+ compiler.outputPath ?? "",
403
+ this.appDir,
404
+ this.sourceFiles,
405
+ this.routeGlobs
406
+ );
407
+ };
408
+ if (typeof afterEmit?.tap === "function") {
409
+ afterEmit.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
410
+ }
411
+ if (typeof done?.tap === "function") {
412
+ done.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
413
+ }
414
+ }
415
+ };
416
+ function appendIncludesToTraceAssets({
417
+ appDir,
418
+ assets,
419
+ outputPath,
420
+ rawSource,
421
+ routeGlobs,
422
+ sourceFiles,
423
+ updateAsset
424
+ }) {
425
+ const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles);
426
+ if (includedFiles.length === 0) {
427
+ return;
428
+ }
429
+ for (const [assetName, asset] of Object.entries(assets)) {
430
+ if (!assetName.endsWith(".nft.json")) {
431
+ continue;
432
+ }
433
+ const routePath = routePathFromTraceAsset(outputPath, assetName);
434
+ if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
435
+ continue;
436
+ }
437
+ const traceDir = (0, import_node_path.dirname)((0, import_node_path.join)(outputPath, assetName));
438
+ const nextSource = traceWithIncludedFiles(String(asset.source()), traceDir, includedFiles);
439
+ if (rawSource && updateAsset) {
440
+ updateAsset(assetName, new rawSource(nextSource));
441
+ } else {
442
+ assets[assetName] = {
443
+ source: () => nextSource,
444
+ size: () => Buffer.byteLength(nextSource)
445
+ };
446
+ }
447
+ }
448
+ }
449
+ function withNextTraceIncludeWebpack(originalWebpack, sourceFiles, routeGlobs) {
450
+ return (config, context) => {
451
+ const nextConfig = originalWebpack ? originalWebpack(config, context) : config;
452
+ if (!context.isServer || context.dev) {
453
+ return nextConfig;
454
+ }
455
+ nextConfig.externals = withNeckbeardExternal(nextConfig.externals);
456
+ nextConfig.plugins = [
457
+ ...Array.isArray(nextConfig.plugins) ? nextConfig.plugins : [],
458
+ new NextTraceIncludePlugin(context.dir ?? process.cwd(), sourceFiles, routeGlobs)
459
+ ];
460
+ return nextConfig;
461
+ };
462
+ }
463
+ function withNeckbeardExternal(externals) {
464
+ return [
465
+ neckbeardExternal,
466
+ ...Array.isArray(externals) ? externals : externals ? [externals] : []
467
+ ];
468
+ }
469
+ function neckbeardExternal(contextOrRequest, requestOrCallback) {
470
+ const legacyCallback = arguments[2];
471
+ const request = typeof requestOrCallback === "string" ? requestOrCallback : typeof contextOrRequest === "string" ? contextOrRequest : contextOrRequest.request;
472
+ const callback = typeof requestOrCallback === "function" ? requestOrCallback : legacyCallback;
473
+ if (request === NECKBEARD_PACKAGE_NAME) {
474
+ const result = `commonjs ${NECKBEARD_PACKAGE_NAME}`;
475
+ if (callback) {
476
+ callback(null, result);
477
+ return;
478
+ }
479
+ return result;
480
+ }
481
+ if (callback) {
482
+ callback();
483
+ }
484
+ }
485
+ function appendIncludesToTraceFiles(outputPath, appDir, sourceFiles, routeGlobs) {
486
+ if (!outputPath || !(0, import_node_fs.existsSync)(outputPath)) {
487
+ return;
488
+ }
489
+ const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles);
490
+ if (includedFiles.length === 0) {
491
+ return;
492
+ }
493
+ for (const traceFile of findTraceFiles(outputPath)) {
494
+ const routePath = routePathFromTraceFile(outputPath, traceFile);
495
+ if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
496
+ continue;
497
+ }
498
+ appendFilesToTrace(traceFile, includedFiles);
499
+ }
500
+ }
501
+ function appendFilesToTrace(traceFile, includedFiles) {
502
+ const nextSource = traceWithIncludedFiles(
503
+ (0, import_node_fs.readFileSync)(traceFile, "utf8"),
504
+ (0, import_node_path.dirname)(traceFile),
505
+ includedFiles
506
+ );
507
+ (0, import_node_fs.writeFileSync)(traceFile, nextSource);
508
+ }
509
+ function traceWithIncludedFiles(traceSource, traceDir, includedFiles) {
510
+ const trace = JSON.parse(traceSource);
511
+ const files = Array.isArray(trace.files) ? trace.files.filter((file) => typeof file === "string") : [];
512
+ const nextFiles = new Set(files);
513
+ for (const includedFile of includedFiles) {
514
+ nextFiles.add((0, import_node_path.relative)(traceDir, includedFile).replace(/\\/g, "/"));
515
+ }
516
+ return JSON.stringify({
517
+ version: trace.version ?? 1,
518
+ files: [...nextFiles]
519
+ });
520
+ }
521
+ function expandTraceIncludeFiles(appDir, sourceFiles) {
522
+ const files = /* @__PURE__ */ new Set();
523
+ for (const sourceFile of sourceFiles) {
524
+ for (const file of expandTraceIncludePattern(appDir, sourceFile)) {
525
+ files.add(file);
526
+ }
527
+ }
528
+ return [...files];
529
+ }
530
+ function expandTraceIncludePattern(appDir, sourceFile) {
531
+ const normalized = sourceFile.replace(/\\/g, "/").replace(/^\.\//, "");
532
+ if (normalized.endsWith("/**/*")) {
533
+ const dir = (0, import_node_path.resolve)(appDir, normalized.slice(0, -5));
534
+ return findFiles(dir);
535
+ }
536
+ if (normalized.endsWith("/*")) {
537
+ const dir = (0, import_node_path.resolve)(appDir, normalized.slice(0, -2));
538
+ return directFiles(dir);
539
+ }
540
+ const file = (0, import_node_path.resolve)(appDir, normalized);
541
+ return (0, import_node_fs.existsSync)(file) && (0, import_node_fs.statSync)(file).isFile() ? [file] : [];
542
+ }
543
+ function findTraceFiles(root) {
544
+ return findFiles(root).filter((file) => file.endsWith(".nft.json"));
545
+ }
546
+ function findFiles(root) {
547
+ if (!(0, import_node_fs.existsSync)(root)) {
548
+ return [];
549
+ }
550
+ const stat = (0, import_node_fs.statSync)(root);
551
+ if (stat.isFile()) {
552
+ return [root];
553
+ }
554
+ if (!stat.isDirectory()) {
555
+ return [];
556
+ }
557
+ const files = [];
558
+ for (const entry of (0, import_node_fs.readdirSync)(root)) {
559
+ files.push(...findFiles((0, import_node_path.join)(root, entry)));
560
+ }
561
+ return files;
562
+ }
563
+ function directFiles(root) {
564
+ if (!(0, import_node_fs.existsSync)(root) || !(0, import_node_fs.statSync)(root).isDirectory()) {
565
+ return [];
566
+ }
567
+ return (0, import_node_fs.readdirSync)(root).map((entry) => (0, import_node_path.join)(root, entry)).filter((file) => (0, import_node_fs.statSync)(file).isFile());
568
+ }
569
+ function routePathFromTraceFile(outputPath, traceFile) {
570
+ const relativeTrace = (0, import_node_path.relative)(outputPath, traceFile).replace(/\\/g, "/");
571
+ return routePathFromRelativeTrace(outputPath, relativeTrace);
572
+ }
573
+ function routePathFromTraceAsset(outputPath, assetName) {
574
+ return routePathFromRelativeTrace(outputPath, assetName.replace(/\\/g, "/"));
575
+ }
576
+ function routePathFromRelativeTrace(outputPath, relativeTrace) {
577
+ const normalizedTrace = relativeTrace.replace(/^(\.\.\/)+/, "");
578
+ if (relativeTrace.startsWith("app/")) {
579
+ return normalizeTraceRoute(relativeTrace.slice("app/".length));
580
+ }
581
+ if (relativeTrace.startsWith("pages/")) {
582
+ return normalizeTraceRoute(relativeTrace.slice("pages/".length));
583
+ }
584
+ if (normalizedTrace.startsWith("app/")) {
585
+ return normalizeTraceRoute(normalizedTrace.slice("app/".length));
586
+ }
587
+ if (normalizedTrace.startsWith("pages/")) {
588
+ return normalizeTraceRoute(normalizedTrace.slice("pages/".length));
589
+ }
590
+ if ((0, import_node_path.basename)(outputPath) === "app" || (0, import_node_path.basename)(outputPath) === "pages") {
591
+ return normalizeTraceRoute(relativeTrace);
592
+ }
593
+ return void 0;
594
+ }
595
+ function normalizeTraceRoute(relativeTrace) {
596
+ const withoutTraceSuffix = relativeTrace.replace(/\.js\.nft\.json$/, "");
597
+ const route = withoutTraceSuffix.replace(/\/route$/, "").replace(/\/page$/, "").replace(/\/index$/, "");
598
+ return `/${route}`;
599
+ }
600
+ function routeGlobMatches(routeGlob, routePath) {
601
+ if (routeGlob === "/*") {
602
+ return true;
603
+ }
604
+ return routeGlobToRegExp(routeGlob).test(routePath);
605
+ }
606
+ function routeGlobToRegExp(glob) {
607
+ let pattern = "";
608
+ for (let index = 0; index < glob.length; index += 1) {
609
+ const char = glob[index];
610
+ const nextChar = glob[index + 1];
611
+ if (char === "*" && nextChar === "*") {
612
+ pattern += ".*";
613
+ index += 1;
614
+ } else if (char === "*") {
615
+ pattern += "[^/]*";
616
+ } else {
617
+ pattern += escapeRegExp(char);
618
+ }
619
+ }
620
+ return new RegExp(`^${pattern}$`);
621
+ }
622
+ function escapeRegExp(value) {
623
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
624
+ }
625
+ function asRecord(value) {
626
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
627
+ }
628
+ function normalizeNonEmptyStrings(name, value) {
629
+ const values = Array.isArray(value) ? value : [value];
630
+ if (values.length === 0) {
631
+ throw new ConfigurationError(`${name} must contain at least one entry.`);
632
+ }
633
+ for (const entry of values) {
634
+ if (typeof entry !== "string" || entry.trim() === "") {
635
+ throw new ConfigurationError(`${name} entries must be non-empty strings.`);
636
+ }
637
+ }
638
+ return values;
639
+ }
640
+ function mergeStringArray(existing, values) {
641
+ const current = Array.isArray(existing) ? existing.filter((value) => typeof value === "string") : [];
642
+ return [.../* @__PURE__ */ new Set([...current, ...values])];
643
+ }
644
+ function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
645
+ const includes = { ...asRecord(existing) };
646
+ for (const routeGlob of routeGlobs) {
647
+ includes[routeGlob] = mergeStringArray(includes[routeGlob], sourceFiles);
648
+ }
649
+ return includes;
650
+ }
249
651
  var DEFAULT_DEPENDENCIES = {};
250
652
  function isServerAgentConfig(config) {
251
653
  return "server" in config && config.server !== void 0;
252
654
  }
655
+ function isSchemaLike(value) {
656
+ return Boolean(
657
+ value && typeof value === "object" && typeof value.parse === "function"
658
+ );
659
+ }
660
+ function requireSchemaLike(name, value) {
661
+ if (!isSchemaLike(value)) {
662
+ throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
663
+ }
664
+ return value;
665
+ }
666
+ function validateAgentConfig(config) {
667
+ if (!config || typeof config !== "object") {
668
+ throw new ConfigurationError("Agent config must be an object.");
669
+ }
670
+ if (!config.sandbox || typeof config.sandbox !== "object") {
671
+ throw new ConfigurationError("Agent config requires sandbox settings.");
672
+ }
673
+ if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
674
+ throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
675
+ }
676
+ if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
677
+ throw new ConfigurationError("sandbox.template must be a non-empty string.");
678
+ }
679
+ requireSchemaLike("inputSchema", config.inputSchema);
680
+ if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
681
+ throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
682
+ }
683
+ if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
684
+ throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
685
+ }
686
+ if (isServerAgentConfig(config)) {
687
+ if ("run" in config && typeof config.run === "function") {
688
+ throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
689
+ }
690
+ if (!config.server || typeof config.server !== "object") {
691
+ throw new ConfigurationError("server must be an object.");
692
+ }
693
+ if (config.server.port !== void 0) {
694
+ if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
695
+ throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
696
+ }
697
+ }
698
+ requireSchemaLike("server.frameSchema", config.server.frameSchema);
699
+ if (typeof config.server.handler !== "function") {
700
+ throw new ConfigurationError("server.handler must be a function.");
701
+ }
702
+ return;
703
+ }
704
+ if (typeof config.run !== "function") {
705
+ throw new ConfigurationError("run must be a function for run-output agents.");
706
+ }
707
+ requireSchemaLike("outputSchema", config.outputSchema);
708
+ }
253
709
  function getTrafficToken(descriptor) {
254
710
  return descriptor.trafficToken;
255
711
  }
@@ -425,6 +881,9 @@ function createSandboxPaths(provider, homeDir, workDir) {
425
881
  function timeoutMsToSeconds(timeoutMs) {
426
882
  return Math.max(1, Math.ceil(timeoutMs / 1e3));
427
883
  }
884
+ function asError(error) {
885
+ return error instanceof Error ? error : new Error(String(error));
886
+ }
428
887
  async function resolveDaytonaPaths(sandbox) {
429
888
  const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
430
889
  const homeDir = await sandbox.getUserHomeDir() ?? workDir;
@@ -594,6 +1053,36 @@ function getCallerFile() {
594
1053
  }
595
1054
  throw new Error("Could not determine source file");
596
1055
  }
1056
+ function isFrameworkBuildOutputPath(file) {
1057
+ const normalized = file.replace(/\\/g, "/");
1058
+ return normalized.includes("/.next/server/chunks/") || normalized.includes("/.next/server/app/") || normalized.includes("/.next/server/pages/");
1059
+ }
1060
+ function frameworkBuildOutputError(file) {
1061
+ return new ConfigurationError(
1062
+ `Agent source resolved to framework build output (${file}). Set sourceFile to the original agent module so deploy() bundles your agent source instead of a framework chunk.`
1063
+ );
1064
+ }
1065
+ function resolveSourceFile(sourceFile) {
1066
+ if (!sourceFile) {
1067
+ const inferred = getCallerFile();
1068
+ if (isFrameworkBuildOutputPath(inferred)) {
1069
+ throw frameworkBuildOutputError(inferred);
1070
+ }
1071
+ return inferred;
1072
+ }
1073
+ const normalized = normalizeStackFramePath(sourceFile);
1074
+ if (!normalized) {
1075
+ throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
1076
+ }
1077
+ const resolved = (0, import_node_path.resolve)(normalized);
1078
+ if (isFrameworkBuildOutputPath(resolved)) {
1079
+ throw frameworkBuildOutputError(resolved);
1080
+ }
1081
+ if (!(0, import_node_fs.existsSync)(resolved)) {
1082
+ throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
1083
+ }
1084
+ return resolved;
1085
+ }
597
1086
  function readDirectoryRecursively(dirPath) {
598
1087
  const files = [];
599
1088
  function walkDir(currentPath) {
@@ -644,12 +1133,13 @@ var Agent = class {
644
1133
  _sandboxId;
645
1134
  _sourceFile;
646
1135
  constructor(config) {
1136
+ validateAgentConfig(config);
647
1137
  this.sandbox = config.sandbox;
648
1138
  this.provider = config.sandbox.provider;
649
1139
  this.template = config.sandbox.template;
650
1140
  this.inputSchema = config.inputSchema;
651
1141
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
652
- this._sourceFile = getCallerFile();
1142
+ this._sourceFile = resolveSourceFile(config.sourceFile);
653
1143
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
654
1144
  this.files = config.files ?? [];
655
1145
  this.claudeDir = config.claudeDir;
@@ -669,7 +1159,10 @@ var Agent = class {
669
1159
  return this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
670
1160
  }
671
1161
  get sandboxEnv() {
672
- return filterDefinedEnvs(this.envs);
1162
+ return {
1163
+ ...filterDefinedEnvs(this.envs),
1164
+ [NECKBEARD_SANDBOX_RUNTIME_ENV]: "1"
1165
+ };
673
1166
  }
674
1167
  async createSandboxHandle() {
675
1168
  if (this.provider === "daytona") {
@@ -912,6 +1405,9 @@ var require = __neckbeard_createRequire(import.meta.url);
912
1405
  }
913
1406
  }
914
1407
  }
1408
+ export function resolveAgentSourceFile(_candidates, options = {}) {
1409
+ return options.sandboxSourceFile ?? process.cwd() + '/agent.mjs';
1410
+ }
915
1411
  `,
916
1412
  loader: "js"
917
1413
  }));
@@ -1013,6 +1509,7 @@ var require = __neckbeard_createRequire(import.meta.url);
1013
1509
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1014
1510
  await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
1015
1511
  const serverConfig = {
1512
+ protocolVersion: RUNTIME_PROTOCOL_VERSION,
1016
1513
  port: this._server?.port ?? DEFAULT_SERVER_PORT,
1017
1514
  maxDurationMs: this.maxDuration * 1e3,
1018
1515
  sandboxContext: {
@@ -1115,7 +1612,12 @@ ${parts.join("\n\n")}`;
1115
1612
  }
1116
1613
  try {
1117
1614
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1118
- const validatedInput = this.inputSchema.parse(input);
1615
+ let validatedInput;
1616
+ try {
1617
+ validatedInput = this.inputSchema.parse(input);
1618
+ } catch (error) {
1619
+ throw new ValidationError("Input validation failed.", asError(error));
1620
+ }
1119
1621
  const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
1120
1622
  let output;
1121
1623
  let sawOutput = false;
@@ -1143,7 +1645,12 @@ ${parts.join("\n\n")}`;
1143
1645
  error: new ExecutionError("Agent server completed without returning output.")
1144
1646
  };
1145
1647
  }
1146
- const validated = this.outputSchema ? this.outputSchema.parse(output) : output;
1648
+ let validated;
1649
+ try {
1650
+ validated = this.outputSchema ? this.outputSchema.parse(output) : output;
1651
+ } catch (error) {
1652
+ throw new ValidationError("Output validation failed.", asError(error));
1653
+ }
1147
1654
  return { ok: true, executionId, output: validated };
1148
1655
  } catch (err) {
1149
1656
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
@@ -1161,21 +1668,31 @@ ${parts.join("\n\n")}`;
1161
1668
  }
1162
1669
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1163
1670
  const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
1164
- const validated = this.inputSchema.parse(input);
1165
- for await (const frame of invokeServer2(validated, {
1166
- serverUrl: connection.serverUrl,
1167
- provider: connection.provider,
1168
- trafficToken: getTrafficToken(connection),
1169
- frameSchema: this.frameSchema,
1170
- signal: options?.signal
1171
- })) {
1172
- if (frame.kind === "frame") {
1173
- yield frame.data;
1174
- } else if (frame.kind === "error") {
1175
- const err = new ExecutionError(frame.error.message);
1176
- err.stack = frame.error.stack;
1177
- throw err;
1671
+ let validated;
1672
+ try {
1673
+ validated = this.inputSchema.parse(input);
1674
+ } catch (error) {
1675
+ throw new ValidationError("Input validation failed.", asError(error));
1676
+ }
1677
+ try {
1678
+ for await (const frame of invokeServer2(validated, {
1679
+ serverUrl: connection.serverUrl,
1680
+ provider: connection.provider,
1681
+ trafficToken: getTrafficToken(connection),
1682
+ frameSchema: this.frameSchema,
1683
+ signal: options?.signal
1684
+ })) {
1685
+ if (frame.kind === "frame") {
1686
+ yield frame.data;
1687
+ } else if (frame.kind === "error") {
1688
+ const err = new ExecutionError(frame.error.message);
1689
+ err.stack = frame.error.stack;
1690
+ throw err;
1691
+ }
1178
1692
  }
1693
+ } catch (error) {
1694
+ if (error instanceof ExecutionError) throw error;
1695
+ throw error instanceof Error ? error : new Error(String(error));
1179
1696
  }
1180
1697
  }
1181
1698
  };
@@ -1188,5 +1705,7 @@ ${parts.join("\n\n")}`;
1188
1705
  ExecutionError,
1189
1706
  NeckbeardError,
1190
1707
  ValidationError,
1191
- normalizeStackFramePath
1708
+ normalizeStackFramePath,
1709
+ resolveAgentSourceFile,
1710
+ withNeckbeardNextConfig
1192
1711
  });