import {
  shellEscape
} from "../chunk-H26LNIXA.js";
import "../chunk-2ESYSVXG.js";

// src/providers/e2b.ts
var SandboxClass = null;
async function loadSdk() {
  if (SandboxClass) return SandboxClass;
  try {
    const mod = await import("../dist-2NO62W6I.js");
    SandboxClass = mod.Sandbox ?? mod.default;
    if (!SandboxClass?.create) {
      throw new Error("Sandbox.create not found in e2b exports");
    }
    return SandboxClass;
  } catch (err) {
    if (err instanceof Error && (err.message.includes("Cannot find module") || err.message.includes("MODULE_NOT_FOUND") || err.message.includes("ERR_MODULE_NOT_FOUND"))) {
      throw new Error(
        "E2B provider requires the e2b package. Install it with: npm install e2b"
      );
    }
    throw err;
  }
}
var g = globalThis;
if (!g.__caE2BSandboxes) g.__caE2BSandboxes = /* @__PURE__ */ new Map();
var sandboxes = g.__caE2BSandboxes;
var DEFAULT_TEMPLATE = process.env.E2B_TEMPLATE ?? "base";
var e2bProvider = {
  name: "e2b",
  stripControlChars: false,
  async checkAvailability(secrets) {
    try {
      await loadSdk();
    } catch {
      return { available: false, message: "E2B requires the e2b package. Install with: npm install e2b" };
    }
    if (!(secrets?.E2B_API_KEY ?? process.env.E2B_API_KEY)) {
      return { available: false, message: "E2B_API_KEY required \u2014 add to vault or .env" };
    }
    return { available: true };
  },
  async create({ name, secrets }) {
    const Sandbox = await loadSdk();
    const apiKey = secrets?.E2B_API_KEY ?? process.env.E2B_API_KEY;
    if (!apiKey) throw new Error("E2B_API_KEY required \u2014 add to vault or .env");
    const sandbox = await Sandbox.create(DEFAULT_TEMPLATE, {
      apiKey,
      timeoutMs: 3e5
    });
    sandboxes.set(name, sandbox);
  },
  async delete(name) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) return;
    try {
      await sandbox.kill();
    } catch {
    }
    sandboxes.delete(name);
  },
  async list(opts) {
    const prefix = opts?.prefix ?? "ca-sess-";
    return Array.from(sandboxes.keys()).filter((n) => n.startsWith(prefix)).map((name) => ({ name }));
  },
  async exec(name, argv, opts) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) throw new Error(`E2B sandbox not found: ${name}`);
    const cmd = argv.map((a) => shellEscape(a)).join(" ");
    if (opts?.stdin) {
      const stdinPath = `/tmp/_stdin_${Date.now()}_${Math.random().toString(36).slice(2)}`;
      await sandbox.files.write(stdinPath, opts.stdin);
      const result2 = await sandbox.commands.run(
        `cat ${stdinPath} | ${cmd} ; rm -f ${stdinPath}`,
        { timeoutMs: opts?.timeoutMs }
      );
      return { stdout: result2.stdout, stderr: result2.stderr, exit_code: result2.exitCode };
    }
    const result = await sandbox.commands.run(cmd, { timeoutMs: opts?.timeoutMs });
    return { stdout: result.stdout, stderr: result.stderr, exit_code: result.exitCode };
  },
  async startExec(name, opts) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) throw new Error(`E2B sandbox not found: ${name}`);
    const cmd = opts.argv.map((a) => shellEscape(a)).join(" ");
    const fullCmd = opts.stdin ? await (async () => {
      const stdinPath = `/tmp/_stdin_${Date.now()}_${Math.random().toString(36).slice(2)}`;
      await sandbox.files.write(stdinPath, opts.stdin);
      return `cat ${stdinPath} | ${cmd} ; rm -f ${stdinPath}`;
    })() : cmd;
    const encoder = new TextEncoder();
    let streamController;
    const stdout = new ReadableStream({
      start(controller) {
        streamController = controller;
      }
    });
    const resultPromise = sandbox.commands.run(fullCmd, {
      onStdout: (data) => {
        try {
          streamController.enqueue(encoder.encode(data));
        } catch {
        }
      },
      onStderr: (_data) => {
      },
      timeoutMs: opts.timeoutMs
    });
    const exit = resultPromise.then((result) => {
      try {
        streamController.close();
      } catch {
      }
      return { code: result.exitCode };
    }).catch((err) => {
      try {
        streamController.error(err);
      } catch {
      }
      throw err;
    });
    return {
      stdout,
      exit,
      async kill() {
      }
    };
  }
};
export {
  e2bProvider
};
