agent-neckbeard 1.1.20 → 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.cjs CHANGED
@@ -159,6 +159,10 @@ function buildRequestHeaders(options) {
159
159
  if (options.provider === "e2b" && options.trafficToken) {
160
160
  headers["e2b-traffic-access-token"] = options.trafficToken;
161
161
  }
162
+ if (options.provider === "modal") {
163
+ if (!options.trafficToken) throw new Error("Modal HTTP requests require a Connect Token.");
164
+ headers.authorization = `Bearer ${options.trafficToken}`;
165
+ }
162
166
  return headers;
163
167
  }
164
168
  function validateHarnessEvent(rawEvent, invocationId) {
@@ -244,7 +248,7 @@ module.exports = __toCommonJS(src_exports);
244
248
  var import_node_url = require("url");
245
249
  var import_node_fs = require("fs");
246
250
  var import_node_path = require("path");
247
- var import_node_module = require("module");
251
+ var import_node_module2 = require("module");
248
252
  init_protocol();
249
253
 
250
254
  // src/runtime/server-source.generated.ts
@@ -574,7 +578,7 @@ var RELEASED_PATTERN = new RegExp(
574
578
  "u"
575
579
  );
576
580
  var HANDLE_PATTERN = new RegExp(
577
- `^(daytona|e2b)-process-v2:(\\d+):(\\d+):(\\d+):(${HASH_PATTERN}):(${HASH_PATTERN})$`,
581
+ `^(daytona|e2b|modal|docker)-process-v2:(\\d+):(\\d+):(\\d+):(${HASH_PATTERN}):(${HASH_PATTERN})$`,
578
582
  "u"
579
583
  );
580
584
  function boundDetachedProcessLog(value) {
@@ -781,7 +785,7 @@ function parseDetachedCommand(sessionId) {
781
785
  const match = HANDLE_PATTERN.exec(sessionId);
782
786
  if (!match) return null;
783
787
  const [, provider, pid, startTicks, processSessionId, launchKey, descriptorKey] = match;
784
- if (provider !== "daytona" && provider !== "e2b" || !pid || !startTicks || !processSessionId || !launchKey || !descriptorKey || pid !== processSessionId) {
788
+ if (provider !== "daytona" && provider !== "e2b" && provider !== "modal" && provider !== "docker" || !pid || !startTicks || !processSessionId || !launchKey || !descriptorKey || pid !== processSessionId) {
785
789
  return null;
786
790
  }
787
791
  return {
@@ -794,10 +798,16 @@ function parseDetachedCommand(sessionId) {
794
798
  };
795
799
  }
796
800
  function hasDetachedProcessV2Prefix(sessionId) {
797
- return /^(?:daytona|e2b)-process-v2/u.test(sessionId);
801
+ return /^(?:daytona|e2b|modal|docker)-process-v2/u.test(sessionId);
798
802
  }
803
+ var DETACHED_PROCESS_PROVIDER_NAMES = {
804
+ daytona: "Daytona",
805
+ e2b: "E2B",
806
+ modal: "Modal",
807
+ docker: "Docker"
808
+ };
799
809
  function detachedProcessProviderName(provider) {
800
- return provider === "daytona" ? "Daytona" : "E2B";
810
+ return DETACHED_PROCESS_PROVIDER_NAMES[provider];
801
811
  }
802
812
  function resolveDetachedCommandForProvider(sessionId, expectedProvider, failure, commandId) {
803
813
  const identity = parseDetachedCommand(sessionId);
@@ -1654,6 +1664,35 @@ function buildEnvironmentFdLaunch(paths, child, environmentMode) {
1654
1664
  "exec 7<&-"
1655
1665
  ];
1656
1666
  }
1667
+ var SANDBOX_NETWORK_ENVIRONMENT_KEYS = [
1668
+ "HTTP_PROXY",
1669
+ "HTTPS_PROXY",
1670
+ "ALL_PROXY",
1671
+ "NO_PROXY",
1672
+ "http_proxy",
1673
+ "https_proxy",
1674
+ "all_proxy",
1675
+ "no_proxy",
1676
+ "NODE_EXTRA_CA_CERTS",
1677
+ "SSL_CERT_FILE",
1678
+ "SSL_CERT_DIR",
1679
+ "REQUESTS_CA_BUNDLE",
1680
+ "CURL_CA_BUNDLE"
1681
+ ];
1682
+ function inheritSandboxNetworkEnvironment() {
1683
+ const script = [
1684
+ "import json, os",
1685
+ `payload = json.loads(os.environ[${JSON.stringify(SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV)}])`,
1686
+ `for name in ${JSON.stringify(SANDBOX_NETWORK_ENVIRONMENT_KEYS)}:`,
1687
+ " if name in os.environ:",
1688
+ ' payload["environment"].setdefault(name, os.environ[name])',
1689
+ 'encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))',
1690
+ `if len(encoded.encode("utf-8")) > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES} or len(payload["environment"]) > ${SUPERVISOR_ENVIRONMENT_MAX_ENTRIES}:`,
1691
+ " raise SystemExit(1)",
1692
+ "print(encoded)"
1693
+ ].join("\n");
1694
+ return `${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}=$(${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}="$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" python3 -I -S -c ${shellQuote(script)}) || exit 1`;
1695
+ }
1657
1696
  function cleanLifecycleShell(script, environmentMode) {
1658
1697
  let suffix = 0;
1659
1698
  let delimiter = "NECKBEARD_DETACHED_LIFECYCLE";
@@ -1668,7 +1707,8 @@ function cleanLifecycleShell(script, environmentMode) {
1668
1707
  return [
1669
1708
  `export PATH=${shellQuote(DETACHED_PROCESS_TRUSTED_PATH)}`,
1670
1709
  ...environmentMode === "exec" ? [
1671
- `if [ -z "\${${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}+present}" ]; then ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}=${shellQuote('{"version":1,"environment":{}}')}; fi`
1710
+ `if [ -z "\${${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}+present}" ]; then ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}=${shellQuote('{"version":1,"environment":{}}')}; fi`,
1711
+ inheritSandboxNetworkEnvironment()
1672
1712
  ] : [],
1673
1713
  `exec env -i ${fixedEnvironment} ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}="$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" sh -s <<'${delimiter}'`,
1674
1714
  script,
@@ -2856,6 +2896,42 @@ function createProviderSandboxPaths(provider, homeDir, workDir) {
2856
2896
  packageJson: `${agentDir}/package.json`
2857
2897
  };
2858
2898
  }
2899
+ var PROVIDER_MAX_LIFETIME_MS = 864e5;
2900
+ function validateProviderEnvs(label, value, failure) {
2901
+ 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")))) {
2902
+ throw failure(`${label} envs must contain valid environment names and string values.`);
2903
+ }
2904
+ }
2905
+ function validateProviderOptions(label, options, allowedKeys, failure) {
2906
+ const allowed = /* @__PURE__ */ new Set(["provider", ...allowedKeys]);
2907
+ for (const [key, value] of Object.entries(options)) {
2908
+ if (!allowed.has(key)) throw failure(`${label} does not support option "${key}".`);
2909
+ if (value === void 0 || key === "provider") continue;
2910
+ if (["timeoutMs", "cpu", "memoryMiB"].includes(key)) {
2911
+ 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)) {
2912
+ throw failure(`${label} ${key} must be positive${key === "timeoutMs" ? ` and a multiple of 1000 between 1000 and ${PROVIDER_MAX_LIFETIME_MS}` : ""}.`);
2913
+ }
2914
+ } else if (key === "envs") {
2915
+ validateProviderEnvs(label, value, failure);
2916
+ } else if (typeof value !== "string" || !value.trim() || value.includes("\0") || value.startsWith("-")) {
2917
+ throw failure(`${label} ${key} must be a non-empty string without null bytes or a leading "-".`);
2918
+ }
2919
+ }
2920
+ }
2921
+ function validateProviderCommand(label, command, options) {
2922
+ if (typeof command !== "string" || command.includes("\0") || !options || Array.isArray(options) || !Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
2923
+ throw new Error(`${label} commands require a string and a positive finite timeoutMs.`);
2924
+ }
2925
+ for (const key of Object.keys(options)) {
2926
+ if (!["cwd", "envs", "timeoutMs", "onStdout", "onStderr"].includes(key)) {
2927
+ throw new Error(`${label} commands do not support option "${key}".`);
2928
+ }
2929
+ }
2930
+ 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") {
2931
+ throw new Error(`${label} command cwd must be absolute and output callbacks must be functions.`);
2932
+ }
2933
+ if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message) => new Error(message));
2934
+ }
2859
2935
 
2860
2936
  // src/providers/daytona.ts
2861
2937
  var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
@@ -3256,6 +3332,547 @@ var E2bSandboxHandle = class {
3256
3332
  }
3257
3333
  };
3258
3334
 
3335
+ // src/providers/modal.ts
3336
+ var import_node_crypto2 = require("crypto");
3337
+
3338
+ // src/providers/modal-sdk.ts
3339
+ var import_node_module = require("module");
3340
+ var import_meta = {};
3341
+ function getModalSdk() {
3342
+ const require3 = (0, import_node_module.createRequire)(typeof __filename === "string" ? __filename : import_meta.url);
3343
+ return require3("modal");
3344
+ }
3345
+
3346
+ // src/providers/modal.ts
3347
+ var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
3348
+ var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
3349
+ function validateModalOptions(options, mode, failure) {
3350
+ validateProviderOptions("Modal", options, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
3351
+ "template",
3352
+ "appName",
3353
+ "timeoutMs",
3354
+ "cpu",
3355
+ "memoryMiB",
3356
+ ...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
3357
+ ]], failure);
3358
+ if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
3359
+ throw failure("Modal sandboxId is required.");
3360
+ }
3361
+ const credentials = options;
3362
+ if (credentials.tokenId === void 0 !== (credentials.tokenSecret === void 0)) {
3363
+ throw failure("Modal tokenId and tokenSecret must be supplied together.");
3364
+ }
3365
+ }
3366
+ var modalClients = /* @__PURE__ */ new Map();
3367
+ var MAX_MODAL_CLIENTS = 16;
3368
+ async function sharedClient(credentials) {
3369
+ if (Number(process.versions.node.split(".")[0]) < 22) {
3370
+ throw new Error("The Modal provider requires Node.js 22 or later.");
3371
+ }
3372
+ const configuration = {
3373
+ tokenId: credentials.tokenId,
3374
+ tokenSecret: credentials.tokenSecret,
3375
+ environment: credentials.environment,
3376
+ logLevel: "error"
3377
+ };
3378
+ const key = (0, import_node_crypto2.createHash)("sha256").update(JSON.stringify([
3379
+ configuration,
3380
+ Object.entries(process.env).filter(([name]) => name.startsWith("MODAL_")).sort(([left], [right]) => left.localeCompare(right))
3381
+ ])).digest("hex");
3382
+ const existing = modalClients.get(key);
3383
+ if (existing) return existing;
3384
+ if (modalClients.size >= MAX_MODAL_CLIENTS) {
3385
+ throw new Error("Modal client configuration limit reached (16 per module instance); use a separate worker for additional credentials or restart after credential rotation.");
3386
+ }
3387
+ let client;
3388
+ try {
3389
+ const { ModalClient } = getModalSdk();
3390
+ client = Promise.resolve(new ModalClient(configuration));
3391
+ } catch (error) {
3392
+ client = Promise.reject(error);
3393
+ }
3394
+ modalClients.set(key, client);
3395
+ return client;
3396
+ }
3397
+ var ModalSandboxHandle = class _ModalSandboxHandle {
3398
+ constructor(id, client, failure) {
3399
+ this.id = id;
3400
+ this.client = client;
3401
+ this.detachedProcesses = new DetachedProcessController({
3402
+ provider: "modal",
3403
+ genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
3404
+ execute: async (command, options) => {
3405
+ try {
3406
+ return { state: "completed", result: await this.runCommand(command, {
3407
+ ...options,
3408
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
3409
+ }) };
3410
+ } catch (error) {
3411
+ return { state: "failed", error };
3412
+ }
3413
+ },
3414
+ readLegacyLogs: async () => {
3415
+ throw failure("Modal requires a managed detached process handle.");
3416
+ },
3417
+ stopLegacy: async () => {
3418
+ throw failure("Modal requires a managed detached process handle.");
3419
+ },
3420
+ failure
3421
+ });
3422
+ }
3423
+ provider = "modal";
3424
+ paths = createProviderSandboxPaths("modal", "/root", "/root");
3425
+ detachedProcesses;
3426
+ static async create(options, failure) {
3427
+ const credentials = {
3428
+ tokenId: options.tokenId,
3429
+ tokenSecret: options.tokenSecret,
3430
+ environment: options.environment
3431
+ };
3432
+ const client = await sharedClient(credentials);
3433
+ let sandbox;
3434
+ try {
3435
+ const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
3436
+ const image = client.images.fromRegistry(options.template ?? MODAL_DEFAULT_TEMPLATE).dockerfileCommands([
3437
+ "USER root",
3438
+ "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/*",
3439
+ "WORKDIR /root"
3440
+ ]);
3441
+ sandbox = await client.sandboxes.create(app, image, {
3442
+ timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
3443
+ cpu: options.cpu,
3444
+ memoryMiB: options.memoryMiB,
3445
+ workdir: "/root",
3446
+ env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
3447
+ (entry) => entry[1] !== void 0
3448
+ ))
3449
+ // No tunnels: all HTTP access requires a port-scoped Connect Token.
3450
+ });
3451
+ return new _ModalSandboxHandle(sandbox.sandboxId, client, failure);
3452
+ } finally {
3453
+ sandbox?.detach();
3454
+ }
3455
+ }
3456
+ static async connect(options, failure) {
3457
+ const client = await sharedClient({
3458
+ tokenId: options.tokenId,
3459
+ tokenSecret: options.tokenSecret,
3460
+ environment: options.environment
3461
+ });
3462
+ const handle = new _ModalSandboxHandle(options.sandboxId, client, failure);
3463
+ await handle.use(async (sandbox) => {
3464
+ if (await sandbox.poll() !== null) throw failure("Modal sandbox is no longer running.");
3465
+ });
3466
+ return handle;
3467
+ }
3468
+ async use(operation, timeoutMs) {
3469
+ const client = this.client;
3470
+ let sandbox;
3471
+ let active = true;
3472
+ try {
3473
+ const work = (async () => {
3474
+ const connected = await client.sandboxes.fromId(this.id);
3475
+ if (!active) {
3476
+ connected.detach();
3477
+ throw new Error("Modal command request already timed out.");
3478
+ }
3479
+ sandbox = connected;
3480
+ return operation(sandbox);
3481
+ })();
3482
+ return await (timeoutMs === void 0 ? work : withTimeout(
3483
+ work,
3484
+ timeoutMs,
3485
+ "Modal command request timed out; remote completion is unknown."
3486
+ ));
3487
+ } finally {
3488
+ active = false;
3489
+ sandbox?.detach();
3490
+ }
3491
+ }
3492
+ makeDir(path) {
3493
+ return this.use((sandbox) => sandbox.filesystem.makeDirectory(path));
3494
+ }
3495
+ writeFile(path, content) {
3496
+ return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content, path) : sandbox.filesystem.writeBytes(content, path));
3497
+ }
3498
+ readFile(path) {
3499
+ return this.use((sandbox) => sandbox.filesystem.readText(path));
3500
+ }
3501
+ readFileBytes(path) {
3502
+ return this.use((sandbox) => sandbox.filesystem.readBytes(path));
3503
+ }
3504
+ runCommand(command, options) {
3505
+ try {
3506
+ validateProviderCommand("Modal", command, options);
3507
+ } catch (error) {
3508
+ return Promise.reject(error);
3509
+ }
3510
+ return this.use(async (sandbox) => {
3511
+ const process2 = await sandbox.exec(["/bin/bash", "--noprofile", "--norc", "-c", command], {
3512
+ workdir: options.cwd ?? this.paths.workDir,
3513
+ env: options.envs,
3514
+ timeoutMs: Math.ceil(options.timeoutMs / 1e3) * 1e3
3515
+ });
3516
+ const read = async (stream, callback) => {
3517
+ let output = "";
3518
+ for await (const chunk of stream) {
3519
+ output += chunk;
3520
+ callback?.(chunk);
3521
+ }
3522
+ return output;
3523
+ };
3524
+ const [stdout, stderr, exitCode] = await Promise.all([
3525
+ read(process2.stdout, options.onStdout),
3526
+ read(process2.stderr, options.onStderr),
3527
+ process2.wait()
3528
+ ]);
3529
+ return { stdout, stderr, exitCode };
3530
+ }, options.timeoutMs);
3531
+ }
3532
+ startDetachedCommand(command, options = {}) {
3533
+ return this.detachedProcesses.start(command, options);
3534
+ }
3535
+ readSessionLogs(command) {
3536
+ return this.detachedProcesses.readLogs(command);
3537
+ }
3538
+ stopSession(command) {
3539
+ return this.detachedProcesses.stop(command);
3540
+ }
3541
+ disposeSessionArtifacts(command) {
3542
+ return this.detachedProcesses.dispose(command);
3543
+ }
3544
+ getServerEndpoint(port) {
3545
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3546
+ return Promise.reject(new Error("Modal endpoint port must be between 1 and 65535."));
3547
+ }
3548
+ return this.use(async (sandbox) => {
3549
+ const credentials = await sandbox.createConnectToken({ port });
3550
+ let url;
3551
+ try {
3552
+ url = new URL(credentials.url);
3553
+ } catch {
3554
+ throw new Error("Modal returned invalid private endpoint credentials.");
3555
+ }
3556
+ if (typeof credentials.token !== "string" || !credentials.token.trim() || /[\r\n]/u.test(credentials.token) || url.protocol !== "https:" || url.username || url.password) {
3557
+ throw new Error("Modal returned invalid private endpoint credentials.");
3558
+ }
3559
+ return { url: credentials.url, trafficToken: credentials.token };
3560
+ });
3561
+ }
3562
+ async destroy() {
3563
+ const { NotFoundError } = getModalSdk();
3564
+ try {
3565
+ await this.use(async (sandbox) => {
3566
+ await sandbox.terminate({ wait: true });
3567
+ });
3568
+ } catch (error) {
3569
+ const grpcNotFound = error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
3570
+ if (!(error instanceof NotFoundError) && !grpcNotFound) throw error;
3571
+ }
3572
+ }
3573
+ };
3574
+
3575
+ // src/providers/docker.ts
3576
+ var import_node_child_process = require("child_process");
3577
+ var import_node_net = require("net");
3578
+ var import_node_string_decoder = require("string_decoder");
3579
+ var DOCKER_DEFAULT_TEMPLATE = "node:22-bookworm";
3580
+ var DOCKER_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
3581
+ var DOCKER_MANAGED_LABEL = "agent-neckbeard.managed";
3582
+ var DOCKER_HOME = "/root";
3583
+ var DOCKER_ENV_FILE = `${DOCKER_HOME}/.neckbeard-env`;
3584
+ var DOCKER_CONTROL_TIMEOUT_MS = 3e4;
3585
+ var DOCKER_FILE_TIMEOUT_MS = 3e5;
3586
+ var DOCKER_CREATE_TIMEOUT_MS = 10 * 60 * 1e3;
3587
+ var DOCKER_BOOTSTRAP_TIMEOUT_MS = 5 * 60 * 1e3;
3588
+ var DOCKER_ORPHAN_GRACE_SECONDS = 2;
3589
+ var REQUIRED_TOOLS = ["bash", "python3", "flock", "setsid", "timeout", "curl"];
3590
+ function validateDockerOptions(options, mode, failure) {
3591
+ validateProviderOptions("Docker", options, mode === "connect" ? ["sandboxId"] : [
3592
+ "template",
3593
+ "network",
3594
+ "platform",
3595
+ "timeoutMs",
3596
+ "cpu",
3597
+ "memoryMiB",
3598
+ ...mode === "create" ? ["envs"] : []
3599
+ ], failure);
3600
+ if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
3601
+ throw failure("Docker sandboxId is required.");
3602
+ }
3603
+ }
3604
+ function exportLines(envs) {
3605
+ return Object.entries(envs ?? {}).filter((entry) => entry[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
3606
+ `).join("");
3607
+ }
3608
+ var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
3609
+ const child = (0, import_node_child_process.spawn)("docker", args, { stdio: ["pipe", "pipe", "pipe"] });
3610
+ const stdout = [];
3611
+ const stdoutDecoder = new import_node_string_decoder.StringDecoder("utf8");
3612
+ const stderrDecoder = new import_node_string_decoder.StringDecoder("utf8");
3613
+ let stderr = "";
3614
+ let settled = false;
3615
+ const timer = setTimeout(() => {
3616
+ child.kill("SIGKILL");
3617
+ settle(() => reject(new Error("Docker command request timed out; remote completion is unknown.")));
3618
+ }, options.timeoutMs);
3619
+ const settle = (callback) => {
3620
+ if (settled) return;
3621
+ settled = true;
3622
+ clearTimeout(timer);
3623
+ callback();
3624
+ };
3625
+ child.stdout.on("data", (chunk) => {
3626
+ stdout.push(chunk);
3627
+ if (options.onStdout) {
3628
+ const text = stdoutDecoder.write(chunk);
3629
+ if (text) options.onStdout(text);
3630
+ }
3631
+ });
3632
+ child.stderr.on("data", (chunk) => {
3633
+ const text = stderrDecoder.write(chunk);
3634
+ stderr += text;
3635
+ if (text) options.onStderr?.(text);
3636
+ });
3637
+ child.on("error", (error) => settle(() => reject(
3638
+ Reflect.get(error, "code") === "ENOENT" ? new Error("The Docker provider requires the `docker` CLI on PATH.") : error
3639
+ )));
3640
+ child.on("close", (code) => settle(() => resolve2({
3641
+ exitCode: code ?? 1,
3642
+ stdout: Buffer.concat(stdout),
3643
+ stderr
3644
+ })));
3645
+ child.stdin.on("error", () => void 0);
3646
+ child.stdin.end(options.input);
3647
+ });
3648
+ var tunnels = /* @__PURE__ */ new Map();
3649
+ function relaySource(port) {
3650
+ return [
3651
+ "import os,socket,threading",
3652
+ `s=socket.create_connection(("127.0.0.1",${port}))`,
3653
+ "def up():",
3654
+ " while True:",
3655
+ " d=os.read(0,65536)",
3656
+ " if not d: break",
3657
+ " s.sendall(d)",
3658
+ " try: s.shutdown(socket.SHUT_WR)",
3659
+ " except OSError: pass",
3660
+ "threading.Thread(target=up,daemon=True).start()",
3661
+ "while True:",
3662
+ " d=s.recv(65536)",
3663
+ " if not d: break",
3664
+ " while d: d=d[os.write(1,d):]"
3665
+ ].join("\n");
3666
+ }
3667
+ function openTunnel(containerId, port) {
3668
+ const key = `${containerId}:${port}`;
3669
+ const existing = tunnels.get(key);
3670
+ if (existing) return existing;
3671
+ const tunnel = new Promise((resolve2, reject) => {
3672
+ const server = (0, import_node_net.createServer)((socket) => {
3673
+ const relay = (0, import_node_child_process.spawn)("docker", [
3674
+ "exec",
3675
+ "-i",
3676
+ "--user",
3677
+ "root",
3678
+ containerId,
3679
+ "python3",
3680
+ "-u",
3681
+ "-c",
3682
+ relaySource(port)
3683
+ ], { stdio: ["pipe", "pipe", "ignore"] });
3684
+ socket.pipe(relay.stdin);
3685
+ relay.stdout.pipe(socket);
3686
+ relay.stdin.on("error", () => void 0);
3687
+ relay.on("error", () => socket.destroy());
3688
+ relay.on("close", () => socket.destroy());
3689
+ socket.on("error", () => relay.kill("SIGKILL"));
3690
+ socket.on("close", () => relay.kill("SIGKILL"));
3691
+ });
3692
+ server.once("error", reject);
3693
+ server.listen(0, "127.0.0.1", () => {
3694
+ server.unref();
3695
+ resolve2(server);
3696
+ });
3697
+ });
3698
+ tunnels.set(key, tunnel);
3699
+ tunnel.catch(() => tunnels.delete(key));
3700
+ return tunnel;
3701
+ }
3702
+ async function closeTunnels(containerId) {
3703
+ for (const [key, tunnel] of tunnels) {
3704
+ if (!key.startsWith(`${containerId}:`)) continue;
3705
+ tunnels.delete(key);
3706
+ await tunnel.then((server) => server.close(), () => void 0);
3707
+ }
3708
+ }
3709
+ var DockerSandboxHandle = class _DockerSandboxHandle {
3710
+ constructor(id, managed, failure, cli = runDockerCli) {
3711
+ this.id = id;
3712
+ this.managed = managed;
3713
+ this.failure = failure;
3714
+ this.cli = cli;
3715
+ this.detachedProcesses = new DetachedProcessController({
3716
+ provider: "docker",
3717
+ genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
3718
+ execute: async (command, options) => {
3719
+ try {
3720
+ return { state: "completed", result: await this.runCommand(command, {
3721
+ ...options,
3722
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
3723
+ }) };
3724
+ } catch (error) {
3725
+ return { state: "failed", error };
3726
+ }
3727
+ },
3728
+ readLegacyLogs: async () => {
3729
+ throw failure("Docker requires a managed detached process handle.");
3730
+ },
3731
+ stopLegacy: async () => {
3732
+ throw failure("Docker requires a managed detached process handle.");
3733
+ },
3734
+ failure
3735
+ });
3736
+ }
3737
+ provider = "docker";
3738
+ paths = createProviderSandboxPaths("docker", DOCKER_HOME, DOCKER_HOME);
3739
+ detachedProcesses;
3740
+ static async create(options, failure, cli = runDockerCli) {
3741
+ const lifetimeSeconds = (options.timeoutMs ?? DOCKER_DEFAULT_TIMEOUT_MS) / 1e3;
3742
+ const created = await cli([
3743
+ "run",
3744
+ "--detach",
3745
+ "--rm",
3746
+ "--init",
3747
+ "--label",
3748
+ `${DOCKER_MANAGED_LABEL}=true`,
3749
+ "--user",
3750
+ "root",
3751
+ "--workdir",
3752
+ DOCKER_HOME,
3753
+ ...options.network ? ["--network", options.network] : [],
3754
+ ...options.platform ? ["--platform", options.platform] : [],
3755
+ ...options.cpu === void 0 ? [] : ["--cpus", String(options.cpu)],
3756
+ ...options.memoryMiB === void 0 ? [] : ["--memory", `${options.memoryMiB}m`],
3757
+ // No published ports: HTTP access goes through a loopback exec tunnel.
3758
+ "--entrypoint",
3759
+ "sleep",
3760
+ options.template ?? DOCKER_DEFAULT_TEMPLATE,
3761
+ String(lifetimeSeconds)
3762
+ ], { timeoutMs: DOCKER_CREATE_TIMEOUT_MS });
3763
+ const id = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
3764
+ if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id)) {
3765
+ throw failure(`Failed to create Docker sandbox: ${created.stderr.trim() || "no container ID returned."}`);
3766
+ }
3767
+ const handle = new _DockerSandboxHandle(id, true, failure, cli);
3768
+ try {
3769
+ await handle.writeFile(DOCKER_ENV_FILE, exportLines(options.envs));
3770
+ await handle.ensureTools();
3771
+ await handle.control(
3772
+ "Docker pip configuration",
3773
+ '[ -e /etc/pip.conf ] || printf "[global]\\nbreak-system-packages = true\\n" > /etc/pip.conf'
3774
+ );
3775
+ return handle;
3776
+ } catch (error) {
3777
+ await handle.destroy().catch(() => void 0);
3778
+ throw error;
3779
+ }
3780
+ }
3781
+ static async connect(options, failure, cli = runDockerCli) {
3782
+ const inspected = await cli([
3783
+ "inspect",
3784
+ "--type",
3785
+ "container",
3786
+ "--format",
3787
+ `{{.State.Running}} {{index .Config.Labels "${DOCKER_MANAGED_LABEL}"}}`,
3788
+ options.sandboxId
3789
+ ], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
3790
+ if (inspected.exitCode !== 0) throw failure("Docker sandbox was not found.");
3791
+ const [running, managed] = inspected.stdout.toString("utf8").trim().split(" ");
3792
+ if (running !== "true") throw failure("Docker sandbox is no longer running.");
3793
+ const handle = new _DockerSandboxHandle(options.sandboxId, managed === "true", failure, cli);
3794
+ await handle.ensureTools();
3795
+ return handle;
3796
+ }
3797
+ /** Installs the detached-process and deploy prerequisites only when the image lacks them. */
3798
+ async ensureTools() {
3799
+ await this.control(
3800
+ "Docker sandbox tool preparation",
3801
+ `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/*; }`,
3802
+ [],
3803
+ void 0,
3804
+ DOCKER_BOOTSTRAP_TIMEOUT_MS
3805
+ );
3806
+ }
3807
+ async control(label, script, args = [], input, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
3808
+ const result = await this.cli(
3809
+ ["exec", "-i", "--user", "root", this.id, "/bin/sh", "-c", script, "sh", ...args],
3810
+ { input, timeoutMs }
3811
+ );
3812
+ if (result.exitCode !== 0) {
3813
+ throw this.failure(`${label} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
3814
+ }
3815
+ return result;
3816
+ }
3817
+ async makeDir(path) {
3818
+ await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path]);
3819
+ }
3820
+ async writeFile(path, content) {
3821
+ const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
3822
+ await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path], input, DOCKER_FILE_TIMEOUT_MS);
3823
+ }
3824
+ async readFile(path) {
3825
+ return (await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
3826
+ }
3827
+ async readFileBytes(path) {
3828
+ return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
3829
+ }
3830
+ async runCommand(command, options) {
3831
+ validateProviderCommand("Docker", command, options);
3832
+ const deadlineSeconds = Math.ceil(options.timeoutMs / 1e3) + DOCKER_ORPHAN_GRACE_SECONDS;
3833
+ const script = `[ -f ${DOCKER_ENV_FILE} ] && . ${DOCKER_ENV_FILE}
3834
+ ` + exportLines(options.envs) + `cd -- ${shellQuote(options.cwd ?? this.paths.workDir)} || exit 1
3835
+ exec timeout --kill-after=1 ${deadlineSeconds} /bin/bash --noprofile --norc -c ${shellQuote(command)} </dev/null
3836
+ `;
3837
+ const result = await this.cli(["exec", "-i", "--user", "root", this.id, "/bin/bash", "--noprofile", "--norc", "-s"], {
3838
+ input: script,
3839
+ timeoutMs: options.timeoutMs,
3840
+ onStdout: options.onStdout,
3841
+ onStderr: options.onStderr
3842
+ });
3843
+ return { stdout: result.stdout.toString("utf8"), stderr: result.stderr, exitCode: result.exitCode };
3844
+ }
3845
+ startDetachedCommand(command, options = {}) {
3846
+ return this.detachedProcesses.start(command, options);
3847
+ }
3848
+ readSessionLogs(command) {
3849
+ return this.detachedProcesses.readLogs(command);
3850
+ }
3851
+ stopSession(command) {
3852
+ return this.detachedProcesses.stop(command);
3853
+ }
3854
+ disposeSessionArtifacts(command) {
3855
+ return this.detachedProcesses.dispose(command);
3856
+ }
3857
+ async getServerEndpoint(port) {
3858
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3859
+ throw new Error("Docker endpoint port must be between 1 and 65535.");
3860
+ }
3861
+ const address = (await openTunnel(this.id, port)).address();
3862
+ if (!address || typeof address === "string") throw new Error("Docker tunnel has no loopback address.");
3863
+ return { url: `http://127.0.0.1:${address.port}` };
3864
+ }
3865
+ /** Removes containers this provider created; containers it attached to are left to their owner. */
3866
+ async destroy() {
3867
+ if (!this.managed) return;
3868
+ await closeTunnels(this.id);
3869
+ const result = await this.cli(["rm", "--force", "--volumes", this.id], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
3870
+ if (result.exitCode !== 0 && !/no such container|is already in progress/iu.test(result.stderr)) {
3871
+ throw this.failure(`Failed to remove Docker sandbox: ${result.stderr.trim()}`);
3872
+ }
3873
+ }
3874
+ };
3875
+
3259
3876
  // src/index.ts
3260
3877
  function readPackageJson(path) {
3261
3878
  return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
@@ -3341,7 +3958,8 @@ function withNeckbeardNextConfig(nextConfig, options) {
3341
3958
  const result = {
3342
3959
  ...nextConfig,
3343
3960
  serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
3344
- NECKBEARD_PACKAGE_NAME
3961
+ NECKBEARD_PACKAGE_NAME,
3962
+ "modal"
3345
3963
  ]),
3346
3964
  outputFileTracingIncludes: mergeTracingIncludes(
3347
3965
  nextConfig.outputFileTracingIncludes,
@@ -3482,8 +4100,8 @@ function neckbeardExternal(contextOrRequest, requestOrCallback) {
3482
4100
  const legacyCallback = arguments[2];
3483
4101
  const request = typeof requestOrCallback === "string" ? requestOrCallback : typeof contextOrRequest === "string" ? contextOrRequest : contextOrRequest.request;
3484
4102
  const callback = typeof requestOrCallback === "function" ? requestOrCallback : legacyCallback;
3485
- if (request === NECKBEARD_PACKAGE_NAME) {
3486
- const result = `commonjs ${NECKBEARD_PACKAGE_NAME}`;
4103
+ if (request === NECKBEARD_PACKAGE_NAME || request === "modal") {
4104
+ const result = `commonjs ${request}`;
3487
4105
  if (callback) {
3488
4106
  callback(null, result);
3489
4107
  return;
@@ -3835,10 +4453,14 @@ function validateAgentConfig(config) {
3835
4453
  if (!config.sandbox || typeof config.sandbox !== "object") {
3836
4454
  throw new ConfigurationError("Agent config requires sandbox settings.");
3837
4455
  }
3838
- if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
3839
- throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
4456
+ if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona" && config.sandbox.provider !== "modal" && config.sandbox.provider !== "docker") {
4457
+ throw new ConfigurationError('sandbox.provider must be "e2b", "daytona", "modal", or "docker".');
3840
4458
  }
3841
- if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
4459
+ if (config.sandbox.provider === "modal") {
4460
+ validateModalOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
4461
+ } else if (config.sandbox.provider === "docker") {
4462
+ validateDockerOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
4463
+ } else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
3842
4464
  throw new ConfigurationError("sandbox.template must be a non-empty string.");
3843
4465
  }
3844
4466
  requireSchemaLike("inputSchema", config.inputSchema);
@@ -3881,6 +4503,10 @@ function appendTrafficTokenToUrl(url, descriptor) {
3881
4503
  }
3882
4504
  function trafficTokenHeaders(descriptor) {
3883
4505
  const token = getTrafficToken(descriptor);
4506
+ if (descriptor.provider === "modal") {
4507
+ if (!token) throw new ConfigurationError("Modal HTTP requests require a Connect Token.");
4508
+ return { authorization: `Bearer ${token}` };
4509
+ }
3884
4510
  if (descriptor.provider === "e2b" && token) {
3885
4511
  return { "e2b-traffic-access-token": token };
3886
4512
  }
@@ -3981,18 +4607,18 @@ function requireEnv(name) {
3981
4607
  }
3982
4608
  return value;
3983
4609
  }
3984
- var require2 = (0, import_node_module.createRequire)((0, import_node_path.join)(process.cwd(), "__agent_neckbeard__.cjs"));
4610
+ var require2 = (0, import_node_module2.createRequire)((0, import_node_path.join)(process.cwd(), "__agent_neckbeard__.cjs"));
3985
4611
  var packageRequire = createPackageRequire();
3986
4612
  function createPackageRequire() {
3987
4613
  const cwdPackageJsonPath = (0, import_node_path.join)(process.cwd(), "package.json");
3988
4614
  try {
3989
4615
  if ((0, import_node_fs.existsSync)(cwdPackageJsonPath) && readPackageJson(cwdPackageJsonPath).name === NECKBEARD_PACKAGE_NAME) {
3990
- return (0, import_node_module.createRequire)(cwdPackageJsonPath);
4616
+ return (0, import_node_module2.createRequire)(cwdPackageJsonPath);
3991
4617
  }
3992
4618
  } catch {
3993
4619
  }
3994
4620
  try {
3995
- return (0, import_node_module.createRequire)(require2.resolve(NECKBEARD_PACKAGE_NAME));
4621
+ return (0, import_node_module2.createRequire)(require2.resolve(NECKBEARD_PACKAGE_NAME));
3996
4622
  } catch {
3997
4623
  return require2;
3998
4624
  }
@@ -4002,7 +4628,7 @@ function isBareModuleImport(path) {
4002
4628
  return !excludes.some((exclude) => path.startsWith(exclude));
4003
4629
  }
4004
4630
  function isBuiltinModule(path) {
4005
- return import_node_module.builtinModules.includes(path.replace("node:", ""));
4631
+ return import_node_module2.builtinModules.includes(path.replace("node:", ""));
4006
4632
  }
4007
4633
  function packageNameForImportPath(importPath) {
4008
4634
  if (importPath.startsWith("@")) {
@@ -4197,6 +4823,14 @@ function providerApiKey(provider, explicitApiKey) {
4197
4823
  return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
4198
4824
  }
4199
4825
  async function createProviderSandboxHandle(options) {
4826
+ if (options.provider === "modal") {
4827
+ validateModalOptions(options, "create", (message) => new ConfigurationError(message));
4828
+ return ModalSandboxHandle.create(options, (message) => new DeploymentError(message));
4829
+ }
4830
+ if (options.provider === "docker") {
4831
+ validateDockerOptions(options, "create", (message) => new ConfigurationError(message));
4832
+ return DockerSandboxHandle.create(options, (message) => new DeploymentError(message));
4833
+ }
4200
4834
  if (options.provider === "daytona") {
4201
4835
  const apiKey2 = providerApiKey("daytona", options.apiKey);
4202
4836
  const { Daytona } = await getDaytona();
@@ -4239,6 +4873,14 @@ async function createProviderSandboxHandle(options) {
4239
4873
  return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
4240
4874
  }
4241
4875
  async function connectProviderSandboxHandle(options) {
4876
+ if (options.provider === "modal") {
4877
+ validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
4878
+ return ModalSandboxHandle.connect(options, (message) => new DeploymentError(message));
4879
+ }
4880
+ if (options.provider === "docker") {
4881
+ validateDockerOptions(options, "connect", (message) => new ConfigurationError(message));
4882
+ return DockerSandboxHandle.connect(options, (message) => new DeploymentError(message));
4883
+ }
4242
4884
  if (options.provider === "daytona") {
4243
4885
  const apiKey2 = providerApiKey("daytona", options.apiKey);
4244
4886
  const { Daytona } = await getDaytona();
@@ -4597,7 +5239,7 @@ var Agent = class {
4597
5239
  validateAgentConfig(config);
4598
5240
  this.sandbox = config.sandbox;
4599
5241
  this.provider = config.sandbox.provider;
4600
- this.template = config.sandbox.template;
5242
+ this.template = config.sandbox.template ?? (config.sandbox.provider === "docker" ? DOCKER_DEFAULT_TEMPLATE : MODAL_DEFAULT_TEMPLATE);
4601
5243
  this.inputSchema = config.inputSchema;
4602
5244
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
4603
5245
  this._sourceFile = resolveSourceFile(config.sourceFile);
@@ -4630,6 +5272,9 @@ var Agent = class {
4630
5272
  };
4631
5273
  }
4632
5274
  async createSandboxHandle() {
5275
+ if (this.sandbox.provider === "modal" || this.sandbox.provider === "docker") {
5276
+ return createProviderSandboxHandle({ ...this.sandbox, envs: this.sandboxEnv });
5277
+ }
4633
5278
  if (this.provider === "e2b") {
4634
5279
  return createProviderSandboxHandle({
4635
5280
  provider: "e2b",
@@ -4649,6 +5294,16 @@ var Agent = class {
4649
5294
  });
4650
5295
  }
4651
5296
  async connectSandboxHandle(sandboxId) {
5297
+ if (this.sandbox.provider === "modal") {
5298
+ return connectProviderSandboxHandle({
5299
+ provider: "modal",
5300
+ sandboxId,
5301
+ environment: this.sandbox.environment
5302
+ });
5303
+ }
5304
+ if (this.sandbox.provider === "docker") {
5305
+ return connectProviderSandboxHandle({ provider: "docker", sandboxId });
5306
+ }
4652
5307
  if (this.provider === "e2b") {
4653
5308
  return connectProviderSandboxHandle({
4654
5309
  provider: "e2b",
@@ -4896,7 +5551,7 @@ var require = __neckbeard_createRequire(import.meta.url);
4896
5551
  }));
4897
5552
  build.onResolve({ filter: /^[^.\/]|^\.[^.\/]|^\.\.[^\/]/ }, async (args) => {
4898
5553
  if (args.path.startsWith("node:")) return null;
4899
- if (import_node_module.builtinModules.includes(args.path.replace("node:", ""))) return null;
5554
+ if (import_node_module2.builtinModules.includes(args.path.replace("node:", ""))) return null;
4900
5555
  if (!isBareModuleImport(args.path)) return null;
4901
5556
  const pkgName = packageNameForImportPath(args.path);
4902
5557
  if (externalMatchers.length && matchesExternal(externalMatchers, pkgName)) {