agent-neckbeard 1.1.21 → 1.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  parseDetachedProcessLogs,
16
16
  shellQuote,
17
17
  uploadDaytonaFile
18
- } from "./chunk-FL7Y55YM.js";
18
+ } from "./chunk-6P5I7ZCH.js";
19
19
  import {
20
20
  RUNTIME_PROTOCOL_VERSION
21
21
  } from "./chunk-DHFC3O44.js";
@@ -42,7 +42,7 @@ import {
42
42
  sep,
43
43
  win32
44
44
  } from "path";
45
- import { builtinModules, createRequire } from "module";
45
+ import { builtinModules, createRequire as createRequire2 } from "module";
46
46
 
47
47
  // src/runtime/server-source.generated.ts
48
48
  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/serialized-error.ts\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/timeout.ts\nfunction settleOperation(operation, options = {}) {\n const { abort, timeout } = options;\n if (abort?.signal.aborted) throw abort.createError();\n if (!abort && !timeout) {\n try {\n return Promise.resolve(operation());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer;\n const cleanup = () => {\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n abort?.signal.removeEventListener("abort", onAbort);\n };\n const settle = (callback) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const onAbort = () => settle(() => reject(abort.createError()));\n abort?.signal.addEventListener("abort", onAbort, { once: true });\n if (timeout) {\n timer = setTimeout(\n () => settle(() => reject(timeout.createError())),\n timeout.timeoutMs\n );\n }\n let task;\n try {\n task = operation();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(task).then(\n (value) => settle(() => resolve(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(operation, signal, maxDurationMs) {\n return settleOperation(operation, {\n abort: {\n signal,\n createError: () => createTimeoutError(maxDurationMs)\n }\n });\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n () => agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n () => agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
@@ -188,6 +188,42 @@ function createProviderSandboxPaths(provider, homeDir, workDir) {
188
188
  packageJson: `${agentDir}/package.json`
189
189
  };
190
190
  }
191
+ var PROVIDER_MAX_LIFETIME_MS = 864e5;
192
+ function validateProviderEnvs(label, value, failure) {
193
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.entries(value).some(([name, item]) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || item !== void 0 && (typeof item !== "string" || item.includes("\0")))) {
194
+ throw failure(`${label} envs must contain valid environment names and string values.`);
195
+ }
196
+ }
197
+ function validateProviderOptions(label, options, allowedKeys, failure) {
198
+ const allowed = /* @__PURE__ */ new Set(["provider", ...allowedKeys]);
199
+ for (const [key, value] of Object.entries(options)) {
200
+ if (!allowed.has(key)) throw failure(`${label} does not support option "${key}".`);
201
+ if (value === void 0 || key === "provider") continue;
202
+ if (["timeoutMs", "cpu", "memoryMiB"].includes(key)) {
203
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || key === "timeoutMs" && (value % 1e3 !== 0 || value < 1e3 || value > PROVIDER_MAX_LIFETIME_MS) || key === "memoryMiB" && !Number.isInteger(value)) {
204
+ throw failure(`${label} ${key} must be positive${key === "timeoutMs" ? ` and a multiple of 1000 between 1000 and ${PROVIDER_MAX_LIFETIME_MS}` : ""}.`);
205
+ }
206
+ } else if (key === "envs") {
207
+ validateProviderEnvs(label, value, failure);
208
+ } else if (typeof value !== "string" || !value.trim() || value.includes("\0") || value.startsWith("-")) {
209
+ throw failure(`${label} ${key} must be a non-empty string without null bytes or a leading "-".`);
210
+ }
211
+ }
212
+ }
213
+ function validateProviderCommand(label, command, options) {
214
+ if (typeof command !== "string" || command.includes("\0") || !options || Array.isArray(options) || !Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
215
+ throw new Error(`${label} commands require a string and a positive finite timeoutMs.`);
216
+ }
217
+ for (const key of Object.keys(options)) {
218
+ if (!["cwd", "envs", "timeoutMs", "onStdout", "onStderr"].includes(key)) {
219
+ throw new Error(`${label} commands do not support option "${key}".`);
220
+ }
221
+ }
222
+ if (options.cwd !== void 0 && (typeof options.cwd !== "string" || !options.cwd.startsWith("/") || options.cwd.includes("\0")) || options.onStdout !== void 0 && typeof options.onStdout !== "function" || options.onStderr !== void 0 && typeof options.onStderr !== "function") {
223
+ throw new Error(`${label} command cwd must be absolute and output callbacks must be functions.`);
224
+ }
225
+ if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message) => new Error(message));
226
+ }
191
227
 
192
228
  // src/providers/daytona.ts
193
229
  var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
@@ -588,6 +624,546 @@ var E2bSandboxHandle = class {
588
624
  }
589
625
  };
590
626
 
627
+ // src/providers/modal.ts
628
+ import { createHash } from "crypto";
629
+
630
+ // src/providers/modal-sdk.ts
631
+ import { createRequire } from "module";
632
+ function getModalSdk() {
633
+ const require3 = createRequire(typeof __filename === "string" ? __filename : import.meta.url);
634
+ return require3("modal");
635
+ }
636
+
637
+ // src/providers/modal.ts
638
+ var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
639
+ var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
640
+ function validateModalOptions(options, mode, failure) {
641
+ validateProviderOptions("Modal", options, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
642
+ "template",
643
+ "appName",
644
+ "timeoutMs",
645
+ "cpu",
646
+ "memoryMiB",
647
+ ...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
648
+ ]], failure);
649
+ if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
650
+ throw failure("Modal sandboxId is required.");
651
+ }
652
+ const credentials = options;
653
+ if (credentials.tokenId === void 0 !== (credentials.tokenSecret === void 0)) {
654
+ throw failure("Modal tokenId and tokenSecret must be supplied together.");
655
+ }
656
+ }
657
+ var modalClients = /* @__PURE__ */ new Map();
658
+ var MAX_MODAL_CLIENTS = 16;
659
+ async function sharedClient(credentials) {
660
+ if (Number(process.versions.node.split(".")[0]) < 22) {
661
+ throw new Error("The Modal provider requires Node.js 22 or later.");
662
+ }
663
+ const configuration = {
664
+ tokenId: credentials.tokenId,
665
+ tokenSecret: credentials.tokenSecret,
666
+ environment: credentials.environment,
667
+ logLevel: "error"
668
+ };
669
+ const key = createHash("sha256").update(JSON.stringify([
670
+ configuration,
671
+ Object.entries(process.env).filter(([name]) => name.startsWith("MODAL_")).sort(([left], [right]) => left.localeCompare(right))
672
+ ])).digest("hex");
673
+ const existing = modalClients.get(key);
674
+ if (existing) return existing;
675
+ if (modalClients.size >= MAX_MODAL_CLIENTS) {
676
+ throw new Error("Modal client configuration limit reached (16 per module instance); use a separate worker for additional credentials or restart after credential rotation.");
677
+ }
678
+ let client;
679
+ try {
680
+ const { ModalClient } = getModalSdk();
681
+ client = Promise.resolve(new ModalClient(configuration));
682
+ } catch (error) {
683
+ client = Promise.reject(error);
684
+ }
685
+ modalClients.set(key, client);
686
+ return client;
687
+ }
688
+ var ModalSandboxHandle = class _ModalSandboxHandle {
689
+ constructor(id, client, failure) {
690
+ this.id = id;
691
+ this.client = client;
692
+ this.detachedProcesses = new DetachedProcessController({
693
+ provider: "modal",
694
+ genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
695
+ execute: async (command, options) => {
696
+ try {
697
+ return { state: "completed", result: await this.runCommand(command, {
698
+ ...options,
699
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
700
+ }) };
701
+ } catch (error) {
702
+ return { state: "failed", error };
703
+ }
704
+ },
705
+ readLegacyLogs: async () => {
706
+ throw failure("Modal requires a managed detached process handle.");
707
+ },
708
+ stopLegacy: async () => {
709
+ throw failure("Modal requires a managed detached process handle.");
710
+ },
711
+ failure
712
+ });
713
+ }
714
+ provider = "modal";
715
+ paths = createProviderSandboxPaths("modal", "/root", "/root");
716
+ detachedProcesses;
717
+ static async create(options, failure) {
718
+ const credentials = {
719
+ tokenId: options.tokenId,
720
+ tokenSecret: options.tokenSecret,
721
+ environment: options.environment
722
+ };
723
+ const client = await sharedClient(credentials);
724
+ let sandbox;
725
+ try {
726
+ const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
727
+ const image = client.images.fromRegistry(options.template ?? MODAL_DEFAULT_TEMPLATE).dockerfileCommands([
728
+ "USER root",
729
+ "RUN apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils sudo curl ca-certificates && rm -rf /var/lib/apt/lists/*",
730
+ "WORKDIR /root"
731
+ ]);
732
+ sandbox = await client.sandboxes.create(app, image, {
733
+ timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
734
+ cpu: options.cpu,
735
+ memoryMiB: options.memoryMiB,
736
+ workdir: "/root",
737
+ env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
738
+ (entry) => entry[1] !== void 0
739
+ ))
740
+ // No tunnels: all HTTP access requires a port-scoped Connect Token.
741
+ });
742
+ return new _ModalSandboxHandle(sandbox.sandboxId, client, failure);
743
+ } finally {
744
+ sandbox?.detach();
745
+ }
746
+ }
747
+ static async connect(options, failure) {
748
+ const client = await sharedClient({
749
+ tokenId: options.tokenId,
750
+ tokenSecret: options.tokenSecret,
751
+ environment: options.environment
752
+ });
753
+ const handle = new _ModalSandboxHandle(options.sandboxId, client, failure);
754
+ await handle.use(async (sandbox) => {
755
+ if (await sandbox.poll() !== null) throw failure("Modal sandbox is no longer running.");
756
+ });
757
+ return handle;
758
+ }
759
+ async use(operation, timeoutMs) {
760
+ const client = this.client;
761
+ let sandbox;
762
+ let active = true;
763
+ try {
764
+ const work = (async () => {
765
+ const connected = await client.sandboxes.fromId(this.id);
766
+ if (!active) {
767
+ connected.detach();
768
+ throw new Error("Modal command request already timed out.");
769
+ }
770
+ sandbox = connected;
771
+ return operation(sandbox);
772
+ })();
773
+ return await (timeoutMs === void 0 ? work : withTimeout(
774
+ work,
775
+ timeoutMs,
776
+ "Modal command request timed out; remote completion is unknown."
777
+ ));
778
+ } finally {
779
+ active = false;
780
+ sandbox?.detach();
781
+ }
782
+ }
783
+ makeDir(path) {
784
+ return this.use((sandbox) => sandbox.filesystem.makeDirectory(path));
785
+ }
786
+ writeFile(path, content) {
787
+ return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content, path) : sandbox.filesystem.writeBytes(content, path));
788
+ }
789
+ readFile(path) {
790
+ return this.use((sandbox) => sandbox.filesystem.readText(path));
791
+ }
792
+ readFileBytes(path) {
793
+ return this.use((sandbox) => sandbox.filesystem.readBytes(path));
794
+ }
795
+ runCommand(command, options) {
796
+ try {
797
+ validateProviderCommand("Modal", command, options);
798
+ } catch (error) {
799
+ return Promise.reject(error);
800
+ }
801
+ return this.use(async (sandbox) => {
802
+ const process2 = await sandbox.exec(["/bin/bash", "--noprofile", "--norc", "-c", command], {
803
+ workdir: options.cwd ?? this.paths.workDir,
804
+ env: options.envs,
805
+ timeoutMs: Math.ceil(options.timeoutMs / 1e3) * 1e3
806
+ });
807
+ const read = async (stream, callback) => {
808
+ let output = "";
809
+ for await (const chunk of stream) {
810
+ output += chunk;
811
+ callback?.(chunk);
812
+ }
813
+ return output;
814
+ };
815
+ const [stdout, stderr, exitCode] = await Promise.all([
816
+ read(process2.stdout, options.onStdout),
817
+ read(process2.stderr, options.onStderr),
818
+ process2.wait()
819
+ ]);
820
+ return { stdout, stderr, exitCode };
821
+ }, options.timeoutMs);
822
+ }
823
+ startDetachedCommand(command, options = {}) {
824
+ return this.detachedProcesses.start(command, options);
825
+ }
826
+ readSessionLogs(command) {
827
+ return this.detachedProcesses.readLogs(command);
828
+ }
829
+ stopSession(command) {
830
+ return this.detachedProcesses.stop(command);
831
+ }
832
+ disposeSessionArtifacts(command) {
833
+ return this.detachedProcesses.dispose(command);
834
+ }
835
+ getServerEndpoint(port) {
836
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
837
+ return Promise.reject(new Error("Modal endpoint port must be between 1 and 65535."));
838
+ }
839
+ return this.use(async (sandbox) => {
840
+ const credentials = await sandbox.createConnectToken({ port });
841
+ let url;
842
+ try {
843
+ url = new URL(credentials.url);
844
+ } catch {
845
+ throw new Error("Modal returned invalid private endpoint credentials.");
846
+ }
847
+ if (typeof credentials.token !== "string" || !credentials.token.trim() || /[\r\n]/u.test(credentials.token) || url.protocol !== "https:" || url.username || url.password) {
848
+ throw new Error("Modal returned invalid private endpoint credentials.");
849
+ }
850
+ return { url: credentials.url, trafficToken: credentials.token };
851
+ });
852
+ }
853
+ async destroy() {
854
+ const { NotFoundError } = getModalSdk();
855
+ try {
856
+ await this.use(async (sandbox) => {
857
+ await sandbox.terminate({ wait: true });
858
+ });
859
+ } catch (error) {
860
+ const grpcNotFound = error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
861
+ if (!(error instanceof NotFoundError) && !grpcNotFound) throw error;
862
+ }
863
+ }
864
+ };
865
+
866
+ // src/providers/docker.ts
867
+ import { spawn } from "child_process";
868
+ import { createServer } from "net";
869
+ import { StringDecoder } from "string_decoder";
870
+ var DOCKER_DEFAULT_TEMPLATE = "node:22-bookworm";
871
+ var DOCKER_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
872
+ var DOCKER_MANAGED_LABEL = "agent-neckbeard.managed";
873
+ var DOCKER_HOME = "/root";
874
+ var DOCKER_ENV_FILE = `${DOCKER_HOME}/.neckbeard-env`;
875
+ var DOCKER_CONTROL_TIMEOUT_MS = 3e4;
876
+ var DOCKER_FILE_TIMEOUT_MS = 3e5;
877
+ var DOCKER_CREATE_TIMEOUT_MS = 10 * 60 * 1e3;
878
+ var DOCKER_BOOTSTRAP_TIMEOUT_MS = 5 * 60 * 1e3;
879
+ var DOCKER_ORPHAN_GRACE_SECONDS = 2;
880
+ var REQUIRED_TOOLS = ["bash", "python3", "flock", "setsid", "timeout", "curl"];
881
+ function validateDockerOptions(options, mode, failure) {
882
+ validateProviderOptions("Docker", options, mode === "connect" ? ["sandboxId"] : [
883
+ "template",
884
+ "network",
885
+ "platform",
886
+ "timeoutMs",
887
+ "cpu",
888
+ "memoryMiB",
889
+ ...mode === "create" ? ["envs"] : []
890
+ ], failure);
891
+ if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
892
+ throw failure("Docker sandboxId is required.");
893
+ }
894
+ }
895
+ function exportLines(envs) {
896
+ return Object.entries(envs ?? {}).filter((entry) => entry[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
897
+ `).join("");
898
+ }
899
+ var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
900
+ const child = spawn("docker", args, { stdio: ["pipe", "pipe", "pipe"] });
901
+ const stdout = [];
902
+ const stdoutDecoder = new StringDecoder("utf8");
903
+ const stderrDecoder = new StringDecoder("utf8");
904
+ let stderr = "";
905
+ let settled = false;
906
+ const timer = setTimeout(() => {
907
+ child.kill("SIGKILL");
908
+ settle(() => reject(new Error("Docker command request timed out; remote completion is unknown.")));
909
+ }, options.timeoutMs);
910
+ const settle = (callback) => {
911
+ if (settled) return;
912
+ settled = true;
913
+ clearTimeout(timer);
914
+ callback();
915
+ };
916
+ child.stdout.on("data", (chunk) => {
917
+ stdout.push(chunk);
918
+ if (options.onStdout) {
919
+ const text = stdoutDecoder.write(chunk);
920
+ if (text) options.onStdout(text);
921
+ }
922
+ });
923
+ child.stderr.on("data", (chunk) => {
924
+ const text = stderrDecoder.write(chunk);
925
+ stderr += text;
926
+ if (text) options.onStderr?.(text);
927
+ });
928
+ child.on("error", (error) => settle(() => reject(
929
+ Reflect.get(error, "code") === "ENOENT" ? new Error("The Docker provider requires the `docker` CLI on PATH.") : error
930
+ )));
931
+ child.on("close", (code) => settle(() => resolve2({
932
+ exitCode: code ?? 1,
933
+ stdout: Buffer.concat(stdout),
934
+ stderr
935
+ })));
936
+ child.stdin.on("error", () => void 0);
937
+ child.stdin.end(options.input);
938
+ });
939
+ var tunnels = /* @__PURE__ */ new Map();
940
+ function relaySource(port) {
941
+ return [
942
+ "import os,socket,threading",
943
+ `s=socket.create_connection(("127.0.0.1",${port}))`,
944
+ "def up():",
945
+ " while True:",
946
+ " d=os.read(0,65536)",
947
+ " if not d: break",
948
+ " s.sendall(d)",
949
+ " try: s.shutdown(socket.SHUT_WR)",
950
+ " except OSError: pass",
951
+ "threading.Thread(target=up,daemon=True).start()",
952
+ "while True:",
953
+ " d=s.recv(65536)",
954
+ " if not d: break",
955
+ " while d: d=d[os.write(1,d):]"
956
+ ].join("\n");
957
+ }
958
+ function openTunnel(containerId, port) {
959
+ const key = `${containerId}:${port}`;
960
+ const existing = tunnels.get(key);
961
+ if (existing) return existing;
962
+ const tunnel = new Promise((resolve2, reject) => {
963
+ const server = createServer((socket) => {
964
+ const relay = spawn("docker", [
965
+ "exec",
966
+ "-i",
967
+ "--user",
968
+ "root",
969
+ containerId,
970
+ "python3",
971
+ "-u",
972
+ "-c",
973
+ relaySource(port)
974
+ ], { stdio: ["pipe", "pipe", "ignore"] });
975
+ socket.pipe(relay.stdin);
976
+ relay.stdout.pipe(socket);
977
+ relay.stdin.on("error", () => void 0);
978
+ relay.on("error", () => socket.destroy());
979
+ relay.on("close", () => socket.destroy());
980
+ socket.on("error", () => relay.kill("SIGKILL"));
981
+ socket.on("close", () => relay.kill("SIGKILL"));
982
+ });
983
+ server.once("error", reject);
984
+ server.listen(0, "127.0.0.1", () => {
985
+ server.unref();
986
+ resolve2(server);
987
+ });
988
+ });
989
+ tunnels.set(key, tunnel);
990
+ tunnel.catch(() => tunnels.delete(key));
991
+ return tunnel;
992
+ }
993
+ async function closeTunnels(containerId) {
994
+ for (const [key, tunnel] of tunnels) {
995
+ if (!key.startsWith(`${containerId}:`)) continue;
996
+ tunnels.delete(key);
997
+ await tunnel.then((server) => server.close(), () => void 0);
998
+ }
999
+ }
1000
+ var DockerSandboxHandle = class _DockerSandboxHandle {
1001
+ constructor(id, managed, failure, cli = runDockerCli) {
1002
+ this.id = id;
1003
+ this.managed = managed;
1004
+ this.failure = failure;
1005
+ this.cli = cli;
1006
+ this.detachedProcesses = new DetachedProcessController({
1007
+ provider: "docker",
1008
+ genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
1009
+ execute: async (command, options) => {
1010
+ try {
1011
+ return { state: "completed", result: await this.runCommand(command, {
1012
+ ...options,
1013
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
1014
+ }) };
1015
+ } catch (error) {
1016
+ return { state: "failed", error };
1017
+ }
1018
+ },
1019
+ readLegacyLogs: async () => {
1020
+ throw failure("Docker requires a managed detached process handle.");
1021
+ },
1022
+ stopLegacy: async () => {
1023
+ throw failure("Docker requires a managed detached process handle.");
1024
+ },
1025
+ failure
1026
+ });
1027
+ }
1028
+ provider = "docker";
1029
+ paths = createProviderSandboxPaths("docker", DOCKER_HOME, DOCKER_HOME);
1030
+ detachedProcesses;
1031
+ static async create(options, failure, cli = runDockerCli) {
1032
+ const lifetimeSeconds = (options.timeoutMs ?? DOCKER_DEFAULT_TIMEOUT_MS) / 1e3;
1033
+ const created = await cli([
1034
+ "run",
1035
+ "--detach",
1036
+ "--rm",
1037
+ "--init",
1038
+ "--label",
1039
+ `${DOCKER_MANAGED_LABEL}=true`,
1040
+ "--user",
1041
+ "root",
1042
+ "--workdir",
1043
+ DOCKER_HOME,
1044
+ ...options.network ? ["--network", options.network] : [],
1045
+ ...options.platform ? ["--platform", options.platform] : [],
1046
+ ...options.cpu === void 0 ? [] : ["--cpus", String(options.cpu)],
1047
+ ...options.memoryMiB === void 0 ? [] : ["--memory", `${options.memoryMiB}m`],
1048
+ // No published ports: HTTP access goes through a loopback exec tunnel.
1049
+ "--entrypoint",
1050
+ "sleep",
1051
+ options.template ?? DOCKER_DEFAULT_TEMPLATE,
1052
+ String(lifetimeSeconds)
1053
+ ], { timeoutMs: DOCKER_CREATE_TIMEOUT_MS });
1054
+ const id = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
1055
+ if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id)) {
1056
+ throw failure(`Failed to create Docker sandbox: ${created.stderr.trim() || "no container ID returned."}`);
1057
+ }
1058
+ const handle = new _DockerSandboxHandle(id, true, failure, cli);
1059
+ try {
1060
+ await handle.writeFile(DOCKER_ENV_FILE, exportLines(options.envs));
1061
+ await handle.ensureTools();
1062
+ await handle.control(
1063
+ "Docker pip configuration",
1064
+ '[ -e /etc/pip.conf ] || printf "[global]\\nbreak-system-packages = true\\n" > /etc/pip.conf'
1065
+ );
1066
+ return handle;
1067
+ } catch (error) {
1068
+ await handle.destroy().catch(() => void 0);
1069
+ throw error;
1070
+ }
1071
+ }
1072
+ static async connect(options, failure, cli = runDockerCli) {
1073
+ const inspected = await cli([
1074
+ "inspect",
1075
+ "--type",
1076
+ "container",
1077
+ "--format",
1078
+ `{{.State.Running}} {{index .Config.Labels "${DOCKER_MANAGED_LABEL}"}}`,
1079
+ options.sandboxId
1080
+ ], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
1081
+ if (inspected.exitCode !== 0) throw failure("Docker sandbox was not found.");
1082
+ const [running, managed] = inspected.stdout.toString("utf8").trim().split(" ");
1083
+ if (running !== "true") throw failure("Docker sandbox is no longer running.");
1084
+ const handle = new _DockerSandboxHandle(options.sandboxId, managed === "true", failure, cli);
1085
+ await handle.ensureTools();
1086
+ return handle;
1087
+ }
1088
+ /** Installs the detached-process and deploy prerequisites only when the image lacks them. */
1089
+ async ensureTools() {
1090
+ await this.control(
1091
+ "Docker sandbox tool preparation",
1092
+ `command -v sudo >/dev/null || { printf '#!/bin/sh\\nwhile [ "\${1#-}" != "$1" ]; do shift; done\\nexec "$@"\\n' > /usr/local/bin/sudo && chmod +x /usr/local/bin/sudo; }; for tool in ${REQUIRED_TOOLS.join(" ")}; do command -v "$tool" >/dev/null || missing=1; done; [ -z "$missing" ] || { apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils curl ca-certificates && rm -rf /var/lib/apt/lists/*; }`,
1093
+ [],
1094
+ void 0,
1095
+ DOCKER_BOOTSTRAP_TIMEOUT_MS
1096
+ );
1097
+ }
1098
+ async control(label, script, args = [], input, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
1099
+ const result = await this.cli(
1100
+ ["exec", "-i", "--user", "root", this.id, "/bin/sh", "-c", script, "sh", ...args],
1101
+ { input, timeoutMs }
1102
+ );
1103
+ if (result.exitCode !== 0) {
1104
+ throw this.failure(`${label} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
1105
+ }
1106
+ return result;
1107
+ }
1108
+ async makeDir(path) {
1109
+ await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path]);
1110
+ }
1111
+ async writeFile(path, content) {
1112
+ const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
1113
+ await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path], input, DOCKER_FILE_TIMEOUT_MS);
1114
+ }
1115
+ async readFile(path) {
1116
+ return (await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
1117
+ }
1118
+ async readFileBytes(path) {
1119
+ return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
1120
+ }
1121
+ async runCommand(command, options) {
1122
+ validateProviderCommand("Docker", command, options);
1123
+ const deadlineSeconds = Math.ceil(options.timeoutMs / 1e3) + DOCKER_ORPHAN_GRACE_SECONDS;
1124
+ const script = `[ -f ${DOCKER_ENV_FILE} ] && . ${DOCKER_ENV_FILE}
1125
+ ` + exportLines(options.envs) + `cd -- ${shellQuote(options.cwd ?? this.paths.workDir)} || exit 1
1126
+ exec timeout --kill-after=1 ${deadlineSeconds} /bin/bash --noprofile --norc -c ${shellQuote(command)} </dev/null
1127
+ `;
1128
+ const result = await this.cli(["exec", "-i", "--user", "root", this.id, "/bin/bash", "--noprofile", "--norc", "-s"], {
1129
+ input: script,
1130
+ timeoutMs: options.timeoutMs,
1131
+ onStdout: options.onStdout,
1132
+ onStderr: options.onStderr
1133
+ });
1134
+ return { stdout: result.stdout.toString("utf8"), stderr: result.stderr, exitCode: result.exitCode };
1135
+ }
1136
+ startDetachedCommand(command, options = {}) {
1137
+ return this.detachedProcesses.start(command, options);
1138
+ }
1139
+ readSessionLogs(command) {
1140
+ return this.detachedProcesses.readLogs(command);
1141
+ }
1142
+ stopSession(command) {
1143
+ return this.detachedProcesses.stop(command);
1144
+ }
1145
+ disposeSessionArtifacts(command) {
1146
+ return this.detachedProcesses.dispose(command);
1147
+ }
1148
+ async getServerEndpoint(port) {
1149
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1150
+ throw new Error("Docker endpoint port must be between 1 and 65535.");
1151
+ }
1152
+ const address = (await openTunnel(this.id, port)).address();
1153
+ if (!address || typeof address === "string") throw new Error("Docker tunnel has no loopback address.");
1154
+ return { url: `http://127.0.0.1:${address.port}` };
1155
+ }
1156
+ /** Removes containers this provider created; containers it attached to are left to their owner. */
1157
+ async destroy() {
1158
+ if (!this.managed) return;
1159
+ await closeTunnels(this.id);
1160
+ const result = await this.cli(["rm", "--force", "--volumes", this.id], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
1161
+ if (result.exitCode !== 0 && !/no such container|is already in progress/iu.test(result.stderr)) {
1162
+ throw this.failure(`Failed to remove Docker sandbox: ${result.stderr.trim()}`);
1163
+ }
1164
+ }
1165
+ };
1166
+
591
1167
  // src/index.ts
592
1168
  function readPackageJson(path) {
593
1169
  return JSON.parse(readFileSync(path, "utf8"));
@@ -673,7 +1249,8 @@ function withNeckbeardNextConfig(nextConfig, options) {
673
1249
  const result = {
674
1250
  ...nextConfig,
675
1251
  serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
676
- NECKBEARD_PACKAGE_NAME
1252
+ NECKBEARD_PACKAGE_NAME,
1253
+ "modal"
677
1254
  ]),
678
1255
  outputFileTracingIncludes: mergeTracingIncludes(
679
1256
  nextConfig.outputFileTracingIncludes,
@@ -814,8 +1391,8 @@ function neckbeardExternal(contextOrRequest, requestOrCallback) {
814
1391
  const legacyCallback = arguments[2];
815
1392
  const request = typeof requestOrCallback === "string" ? requestOrCallback : typeof contextOrRequest === "string" ? contextOrRequest : contextOrRequest.request;
816
1393
  const callback = typeof requestOrCallback === "function" ? requestOrCallback : legacyCallback;
817
- if (request === NECKBEARD_PACKAGE_NAME) {
818
- const result = `commonjs ${NECKBEARD_PACKAGE_NAME}`;
1394
+ if (request === NECKBEARD_PACKAGE_NAME || request === "modal") {
1395
+ const result = `commonjs ${request}`;
819
1396
  if (callback) {
820
1397
  callback(null, result);
821
1398
  return;
@@ -1167,10 +1744,14 @@ function validateAgentConfig(config) {
1167
1744
  if (!config.sandbox || typeof config.sandbox !== "object") {
1168
1745
  throw new ConfigurationError("Agent config requires sandbox settings.");
1169
1746
  }
1170
- if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
1171
- throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
1747
+ if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona" && config.sandbox.provider !== "modal" && config.sandbox.provider !== "docker") {
1748
+ throw new ConfigurationError('sandbox.provider must be "e2b", "daytona", "modal", or "docker".');
1172
1749
  }
1173
- if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
1750
+ if (config.sandbox.provider === "modal") {
1751
+ validateModalOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
1752
+ } else if (config.sandbox.provider === "docker") {
1753
+ validateDockerOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
1754
+ } else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
1174
1755
  throw new ConfigurationError("sandbox.template must be a non-empty string.");
1175
1756
  }
1176
1757
  requireSchemaLike("inputSchema", config.inputSchema);
@@ -1213,6 +1794,10 @@ function appendTrafficTokenToUrl(url, descriptor) {
1213
1794
  }
1214
1795
  function trafficTokenHeaders(descriptor) {
1215
1796
  const token = getTrafficToken(descriptor);
1797
+ if (descriptor.provider === "modal") {
1798
+ if (!token) throw new ConfigurationError("Modal HTTP requests require a Connect Token.");
1799
+ return { authorization: `Bearer ${token}` };
1800
+ }
1216
1801
  if (descriptor.provider === "e2b" && token) {
1217
1802
  return { "e2b-traffic-access-token": token };
1218
1803
  }
@@ -1313,18 +1898,18 @@ function requireEnv(name) {
1313
1898
  }
1314
1899
  return value;
1315
1900
  }
1316
- var require2 = createRequire(join(process.cwd(), "__agent_neckbeard__.cjs"));
1901
+ var require2 = createRequire2(join(process.cwd(), "__agent_neckbeard__.cjs"));
1317
1902
  var packageRequire = createPackageRequire();
1318
1903
  function createPackageRequire() {
1319
1904
  const cwdPackageJsonPath = join(process.cwd(), "package.json");
1320
1905
  try {
1321
1906
  if (existsSync(cwdPackageJsonPath) && readPackageJson(cwdPackageJsonPath).name === NECKBEARD_PACKAGE_NAME) {
1322
- return createRequire(cwdPackageJsonPath);
1907
+ return createRequire2(cwdPackageJsonPath);
1323
1908
  }
1324
1909
  } catch {
1325
1910
  }
1326
1911
  try {
1327
- return createRequire(require2.resolve(NECKBEARD_PACKAGE_NAME));
1912
+ return createRequire2(require2.resolve(NECKBEARD_PACKAGE_NAME));
1328
1913
  } catch {
1329
1914
  return require2;
1330
1915
  }
@@ -1529,6 +2114,14 @@ function providerApiKey(provider, explicitApiKey) {
1529
2114
  return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
1530
2115
  }
1531
2116
  async function createProviderSandboxHandle(options) {
2117
+ if (options.provider === "modal") {
2118
+ validateModalOptions(options, "create", (message) => new ConfigurationError(message));
2119
+ return ModalSandboxHandle.create(options, (message) => new DeploymentError(message));
2120
+ }
2121
+ if (options.provider === "docker") {
2122
+ validateDockerOptions(options, "create", (message) => new ConfigurationError(message));
2123
+ return DockerSandboxHandle.create(options, (message) => new DeploymentError(message));
2124
+ }
1532
2125
  if (options.provider === "daytona") {
1533
2126
  const apiKey2 = providerApiKey("daytona", options.apiKey);
1534
2127
  const { Daytona } = await getDaytona();
@@ -1571,6 +2164,14 @@ async function createProviderSandboxHandle(options) {
1571
2164
  return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
1572
2165
  }
1573
2166
  async function connectProviderSandboxHandle(options) {
2167
+ if (options.provider === "modal") {
2168
+ validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
2169
+ return ModalSandboxHandle.connect(options, (message) => new DeploymentError(message));
2170
+ }
2171
+ if (options.provider === "docker") {
2172
+ validateDockerOptions(options, "connect", (message) => new ConfigurationError(message));
2173
+ return DockerSandboxHandle.connect(options, (message) => new DeploymentError(message));
2174
+ }
1574
2175
  if (options.provider === "daytona") {
1575
2176
  const apiKey2 = providerApiKey("daytona", options.apiKey);
1576
2177
  const { Daytona } = await getDaytona();
@@ -1929,7 +2530,7 @@ var Agent = class {
1929
2530
  validateAgentConfig(config);
1930
2531
  this.sandbox = config.sandbox;
1931
2532
  this.provider = config.sandbox.provider;
1932
- this.template = config.sandbox.template;
2533
+ this.template = config.sandbox.template ?? (config.sandbox.provider === "docker" ? DOCKER_DEFAULT_TEMPLATE : MODAL_DEFAULT_TEMPLATE);
1933
2534
  this.inputSchema = config.inputSchema;
1934
2535
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
1935
2536
  this._sourceFile = resolveSourceFile(config.sourceFile);
@@ -1962,6 +2563,9 @@ var Agent = class {
1962
2563
  };
1963
2564
  }
1964
2565
  async createSandboxHandle() {
2566
+ if (this.sandbox.provider === "modal" || this.sandbox.provider === "docker") {
2567
+ return createProviderSandboxHandle({ ...this.sandbox, envs: this.sandboxEnv });
2568
+ }
1965
2569
  if (this.provider === "e2b") {
1966
2570
  return createProviderSandboxHandle({
1967
2571
  provider: "e2b",
@@ -1981,6 +2585,16 @@ var Agent = class {
1981
2585
  });
1982
2586
  }
1983
2587
  async connectSandboxHandle(sandboxId) {
2588
+ if (this.sandbox.provider === "modal") {
2589
+ return connectProviderSandboxHandle({
2590
+ provider: "modal",
2591
+ sandboxId,
2592
+ environment: this.sandbox.environment
2593
+ });
2594
+ }
2595
+ if (this.sandbox.provider === "docker") {
2596
+ return connectProviderSandboxHandle({ provider: "docker", sandboxId });
2597
+ }
1984
2598
  if (this.provider === "e2b") {
1985
2599
  return connectProviderSandboxHandle({
1986
2600
  provider: "e2b",
@@ -2429,7 +3043,7 @@ var require = __neckbeard_createRequire(import.meta.url);
2429
3043
  } catch (error) {
2430
3044
  throw new ValidationError("Input validation failed.", asError(error));
2431
3045
  }
2432
- const { invokeServer } = await import("./invoke-client-D5TMTOYM.js");
3046
+ const { invokeServer } = await import("./invoke-client-HIXYE2WN.js");
2433
3047
  let output;
2434
3048
  let sawOutput = false;
2435
3049
  for await (const event of invokeServer(validatedInput, {
@@ -2535,7 +3149,7 @@ var require = __neckbeard_createRequire(import.meta.url);
2535
3149
  signal,
2536
3150
  reuseMatchingCachedConnection: true
2537
3151
  });
2538
- const { invokeServer } = await import("./invoke-client-D5TMTOYM.js");
3152
+ const { invokeServer } = await import("./invoke-client-HIXYE2WN.js");
2539
3153
  let validated;
2540
3154
  try {
2541
3155
  validated = this.inputSchema.parse(input);