import {
  shellEscape
} from "../chunk-H26LNIXA.js";
import {
  readEnvOrSetting
} from "../chunk-2MAQ6JFL.js";
import "../chunk-HFDLUBWN.js";
import "../chunk-RII4M3J2.js";
import "../chunk-DDJOPRB7.js";
import "../chunk-TLEKKGH7.js";
import "../chunk-KBM3MISV.js";
import "../chunk-2ESYSVXG.js";

// src/providers/modal.ts
import { existsSync } from "fs";
import { join } from "path";
var clientInstance = null;
async function getClient(secrets) {
  const resolvedId = secrets?.MODAL_TOKEN_ID ?? readEnvOrSetting("MODAL_TOKEN_ID");
  const resolvedSecret = secrets?.MODAL_TOKEN_SECRET ?? readEnvOrSetting("MODAL_TOKEN_SECRET");
  const needsOverride = Boolean(
    secrets?.MODAL_TOKEN_ID || secrets?.MODAL_TOKEN_SECRET || resolvedId && resolvedId !== process.env.MODAL_TOKEN_ID || resolvedSecret && resolvedSecret !== process.env.MODAL_TOKEN_SECRET
  );
  if (needsOverride) {
    const origId = process.env.MODAL_TOKEN_ID;
    const origSecret = process.env.MODAL_TOKEN_SECRET;
    try {
      if (resolvedId) process.env.MODAL_TOKEN_ID = resolvedId;
      if (resolvedSecret) process.env.MODAL_TOKEN_SECRET = resolvedSecret;
      const mod = await import("../dist-4VD6VQBV.js");
      const ClientClass = mod.ModalClient ?? mod.default?.ModalClient;
      if (!ClientClass) throw new Error("ModalClient not found in modal exports");
      return new ClientClass();
    } 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("Modal requires the modal package. Install with: npm install modal");
      }
      throw err;
    } finally {
      if (origId !== void 0) process.env.MODAL_TOKEN_ID = origId;
      else delete process.env.MODAL_TOKEN_ID;
      if (origSecret !== void 0) process.env.MODAL_TOKEN_SECRET = origSecret;
      else delete process.env.MODAL_TOKEN_SECRET;
    }
  }
  if (clientInstance) return clientInstance;
  try {
    const mod = await import("../dist-4VD6VQBV.js");
    const ClientClass = mod.ModalClient ?? mod.default?.ModalClient;
    if (!ClientClass) throw new Error("ModalClient not found in modal exports");
    clientInstance = new ClientClass();
    return clientInstance;
  } 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("Modal requires the modal package. Install with: npm install modal");
    }
    throw err;
  }
}
var g = globalThis;
if (!g.__caModalSandboxes) g.__caModalSandboxes = /* @__PURE__ */ new Map();
var sandboxes = g.__caModalSandboxes;
var APP_NAME = "agentstep-gateway";
var modalProvider = {
  name: "modal",
  stripControlChars: false,
  async checkAvailability(secrets) {
    try {
      await getClient();
    } catch {
      return { available: false, message: "Modal requires the modal npm package. Install with: npm install modal" };
    }
    const hasTokenId = secrets?.MODAL_TOKEN_ID ?? readEnvOrSetting("MODAL_TOKEN_ID");
    const hasTokenSecret = secrets?.MODAL_TOKEN_SECRET ?? readEnvOrSetting("MODAL_TOKEN_SECRET");
    if (!hasTokenId && !hasTokenSecret) {
      const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
      const tomlPath = process.env.MODAL_CONFIG_PATH ?? join(home, ".modal.toml");
      if (!existsSync(tomlPath)) {
        return { available: false, message: "MODAL_TOKEN_ID + MODAL_TOKEN_SECRET required \u2014 add to vault or .env (or run: modal token set)" };
      }
    }
    return { available: true };
  },
  async create({ name, secrets }) {
    const client = await getClient(secrets);
    if (!g.__caModalApp) {
      g.__caModalApp = await client.apps.fromName(APP_NAME, { createIfMissing: true });
    }
    const image = client.images.fromRegistry("node:22");
    const sandbox = await client.sandboxes.create(g.__caModalApp, image, {
      command: ["sleep", "infinity"],
      cpu: 2,
      memoryMiB: 2048,
      timeoutMs: 36e5,
      // 1 hour max lifetime
      name
    });
    sandboxes.set(name, sandbox);
  },
  async delete(name) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) return;
    try {
      await sandbox.terminate();
    } 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(`Modal sandbox not found: ${name}`);
    const cmd = argv.map((a) => shellEscape(a)).join(" ");
    const proc = await sandbox.exec(["bash", "-c", cmd], {
      timeoutMs: opts?.timeoutMs
    });
    if (opts?.stdin) {
      await proc.stdin.writeText(opts.stdin);
      await proc.stdin.close();
    }
    const [stdout, stderr, exitCode] = await Promise.all([
      proc.stdout.readText(),
      proc.stderr.readText(),
      proc.wait()
    ]);
    return { stdout, stderr, exit_code: exitCode };
  },
  async startExec(name, opts) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) throw new Error(`Modal sandbox not found: ${name}`);
    const cmd = opts.argv.map((a) => shellEscape(a)).join(" ");
    const proc = await sandbox.exec(["bash", "-c", cmd], {
      timeoutMs: opts.timeoutMs
    });
    if (opts.stdin) {
      await proc.stdin.writeText(opts.stdin);
      await proc.stdin.close();
    }
    const encoder = new TextEncoder();
    let streamController;
    const stdout = new ReadableStream({
      start(controller) {
        streamController = controller;
      }
    });
    const exit = proc.stdout.readText().then(async (text) => {
      try {
        if (text) streamController.enqueue(encoder.encode(text));
        streamController.close();
      } catch {
      }
      return { code: await proc.wait() };
    }).catch(async (err) => {
      try {
        streamController.error(err);
      } catch {
      }
      throw err;
    });
    return {
      stdout,
      exit,
      async kill() {
      }
    };
  }
};
export {
  modalProvider
};
