#!/usr/bin/env node
import {
  hostOpenCommand
} from "./chunk-SNTHHWKY.js";

// ../../packages/sandbox-daytona/dist/chunk-5LKRD6ED.js
import { existsSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
import { existsSync as existsSync2, readFileSync } from "fs";
import { homedir } from "os";
import { resolve as resolve2 } from "path";
import { Daytona, DaytonaNotFoundError as DaytonaNotFoundError2, Image, SandboxState } from "@daytonaio/sdk";
import {
  DaytonaAuthenticationError,
  DaytonaAuthorizationError,
  DaytonaConflictError,
  DaytonaConnectionError,
  DaytonaError,
  DaytonaNotFoundError,
  DaytonaRateLimitError,
  DaytonaTimeoutError,
  DaytonaValidationError
} from "@daytonaio/sdk";
import { spawnSync } from "child_process";
import {
  chmodSync,
  existsSync as existsSync3,
  mkdirSync,
  readFileSync as readFileSync2,
  renameSync,
  writeFileSync
} from "fs";
import { homedir as homedir2 } from "os";
import { dirname as dirname2, resolve as resolve3 } from "path";
import { confirm, isCancel, intro, log, note, outro, password, spinner, text } from "@clack/prompts";
function resolveDockerfileContext() {
  const override = process.env.AGENTBOX_DOCKER_CONTEXT;
  if (override && existsSync(resolve(override, "Dockerfile.box"))) {
    return { dockerfile: resolve(override, "Dockerfile.box"), context: override };
  }
  const here = dirname(fileURLToPath(import.meta.url));
  const staged = resolve(here, "..", "runtime", "docker");
  if (existsSync(resolve(staged, "Dockerfile.box"))) {
    return { dockerfile: resolve(staged, "Dockerfile.box"), context: staged };
  }
  const monorepoRoot = resolve(here, "..", "..", "..");
  const dockerfile = resolve(monorepoRoot, "packages", "sandbox-docker", "Dockerfile.box");
  if (existsSync(dockerfile)) {
    return { dockerfile, context: monorepoRoot };
  }
  return null;
}
function resolveDaytonaCustomClaudeMd() {
  const here = dirname(fileURLToPath(import.meta.url));
  const staged = resolve(here, "..", "runtime", "daytona", "custom-system-CLAUDE.md");
  if (existsSync(staged)) return staged;
  const monorepoRoot = resolve(here, "..", "..", "..");
  const dev = resolve(
    monorepoRoot,
    "packages",
    "sandbox-daytona",
    "scripts",
    "custom-system-CLAUDE.md"
  );
  if (existsSync(dev)) return dev;
  return null;
}
var DAYTONA_KEYS = [
  "DAYTONA_API_KEY",
  "DAYTONA_JWT_TOKEN",
  "DAYTONA_ORGANIZATION_ID",
  "DAYTONA_API_URL",
  "DAYTONA_TARGET"
];
var loaded = false;
function ensureDaytonaEnvLoaded() {
  if (loaded) return;
  loaded = true;
  importDaytonaFromFile(resolve2(homedir(), ".agentbox", "secrets.env"));
}
function importDaytonaFromFile(path) {
  if (!existsSync2(path)) return;
  let body;
  try {
    body = readFileSync(path, "utf8");
  } catch {
    return;
  }
  const parsed = parseEnvFile(body);
  for (const key of DAYTONA_KEYS) {
    if (process.env[key] !== void 0) continue;
    const value = parsed[key];
    if (typeof value === "string") {
      process.env[key] = value;
    }
  }
}
function parseEnvFile(body) {
  const out = {};
  for (const rawLine of body.split(/\r?\n/)) {
    const line = rawLine.trim();
    if (line.length === 0 || line.startsWith("#")) continue;
    const stripped = line.startsWith("export ") ? line.slice("export ".length) : line;
    const eq = stripped.indexOf("=");
    if (eq <= 0) continue;
    const key = stripped.slice(0, eq).trim();
    let value = stripped.slice(eq + 1).trim();
    if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
      value = value.slice(1, -1);
    }
    out[key] = value;
  }
  return out;
}
var DEFAULT_BACKOFF = [1e3, 2e3, 4e3];
var DEFAULT_ATTEMPT_TIMEOUT_MS = 3e4;
var AttemptTimeoutError = class extends Error {
  constructor(method, ms) {
    super(`daytona ${method}: per-attempt timeout after ${String(ms)}ms`);
    this.name = "AttemptTimeoutError";
  }
};
function isRetriable(err, allowAmbiguous) {
  if (err instanceof DaytonaRateLimitError) return true;
  if (err instanceof DaytonaNotFoundError || err instanceof DaytonaAuthenticationError || err instanceof DaytonaAuthorizationError || err instanceof DaytonaValidationError || err instanceof DaytonaConflictError) {
    return false;
  }
  if (err instanceof DaytonaConnectionError || err instanceof DaytonaTimeoutError || err instanceof AttemptTimeoutError) {
    return allowAmbiguous;
  }
  if (err instanceof DaytonaError) {
    const status = err.statusCode;
    if (typeof status === "number" && status >= 500 && status <= 599) {
      return allowAmbiguous;
    }
    return false;
  }
  if (err && typeof err === "object") {
    const code = err.code;
    if (code === "ECONNRESET" || code === "ETIMEDOUT" || code === "ECONNABORTED" || code === "EAI_AGAIN" || code === "ECONNREFUSED" || code === "ENOTFOUND") {
      return allowAmbiguous;
    }
    const status = err.response?.status ?? err.status ?? err.statusCode;
    if (typeof status === "number" && status >= 500 && status <= 599) {
      return allowAmbiguous;
    }
  }
  return false;
}
async function withDaytonaRetry(opts, fn) {
  const backoff = opts.backoffMs ?? DEFAULT_BACKOFF;
  const maxAttempts = backoff.length + 1;
  const timeoutMs = opts.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;
  const log2 = opts.onRetry ?? defaultRetryLog;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await raceTimeout(fn(), timeoutMs, opts.method);
    } catch (err) {
      const last = attempt === maxAttempts;
      if (last || !isRetriable(err, opts.retryOnAmbiguous)) throw err;
      const delay = backoff[attempt - 1] ?? backoff[backoff.length - 1] ?? 4e3;
      log2(
        `daytona ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`
      );
      await sleep(delay);
    }
  }
  throw new Error(`withDaytonaRetry: exhausted attempts for ${opts.method}`);
}
function defaultRetryLog(line) {
  process.stderr.write(`
[daytona-retry] ${line}
`);
}
function sleep(ms) {
  return new Promise((resolve4) => setTimeout(resolve4, ms));
}
async function raceTimeout(p, ms, method) {
  let timer;
  try {
    return await Promise.race([
      p,
      new Promise((_resolve, reject) => {
        timer = setTimeout(() => reject(new AttemptTimeoutError(method, ms)), ms);
      })
    ]);
  } finally {
    if (timer !== void 0) clearTimeout(timer);
  }
}
function errorSummary(err) {
  if (err instanceof DaytonaError) {
    const status = err.statusCode;
    const cls = err.constructor.name;
    return `${cls}${typeof status === "number" ? ` ${String(status)}` : ""}: ${truncate(err.message)}`;
  }
  if (err instanceof Error) {
    const code = err.code;
    return code !== void 0 ? `${err.name}(${String(code)}): ${truncate(err.message)}` : `${err.name}: ${truncate(err.message)}`;
  }
  return truncate(String(err));
}
function truncate(s, max = 160) {
  return s.length > max ? `${s.slice(0, max)}\u2026` : s;
}
function retry(method, fn, opts = {}) {
  return withDaytonaRetry(
    {
      method,
      retryOnAmbiguous: opts.retryOnAmbiguous ?? true,
      attemptTimeoutMs: opts.attemptTimeoutMs,
      backoffMs: opts.noRetry === true ? [] : void 0
    },
    fn
  );
}
var DEFAULT_BOX_IMAGE_REF = "agentbox/box:dev";
var client = null;
function getClient() {
  if (!client) {
    ensureDaytonaEnvLoaded();
    try {
      client = new Daytona();
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      throw new Error(
        `Daytona credentials not configured: ${msg}
Run \`agentbox daytona login\` interactively, or set DAYTONA_API_KEY in the environment.`
      );
    }
  }
  return client;
}
async function getSandbox(id) {
  return getClient().get(id);
}
async function maybeGetSandbox(id) {
  try {
    return await getClient().get(id);
  } catch {
    return null;
  }
}
function mapState(s) {
  switch (s) {
    case SandboxState.STARTED:
      return "running";
    case SandboxState.STARTING:
    case SandboxState.CREATING:
    case SandboxState.RESTORING:
    case SandboxState.BUILDING_SNAPSHOT:
    case SandboxState.PULLING_SNAPSHOT:
    case SandboxState.PENDING_BUILD:
    case SandboxState.STOPPING:
      return "running";
    case SandboxState.STOPPED:
      return "stopped";
    case SandboxState.ARCHIVED:
    case SandboxState.ARCHIVING:
      return "paused";
    case SandboxState.DESTROYED:
    case SandboxState.DESTROYING:
    case SandboxState.ERROR:
    case SandboxState.BUILD_FAILED:
    case SandboxState.UNKNOWN:
    default:
      return "missing";
  }
}
function toDaytonaVolumeMount(v) {
  return {
    volumeId: v.volumeId,
    mountPath: v.mountPath,
    ...v.subpath ? { subpath: v.subpath } : {}
  };
}
function resolveImage(ref) {
  if (ref !== DEFAULT_BOX_IMAGE_REF) return ref;
  const ctx = resolveDockerfileContext();
  if (!ctx) {
    throw new Error(
      "could not locate the AgentBox Dockerfile.box build context for the Daytona snapshot. Set AGENTBOX_DOCKER_CONTEXT to a directory containing Dockerfile.box, or pass --image <ref> with a Daytona-compatible image."
    );
  }
  return Image.fromDockerfile(ctx.dockerfile);
}
var daytonaBackend = {
  name: "daytona",
  async provision(req) {
    return retry(
      "provision",
      async () => {
        const baseParams = {
          ...req.resources ? { resources: req.resources } : {},
          envVars: req.env,
          ...req.volumes && req.volumes.length > 0 ? { volumes: req.volumes.map(toDaytonaVolumeMount) } : {},
          labels: { "agentbox.name": req.name }
        };
        const client2 = getClient();
        let snapshotName = req.snapshot;
        if (!snapshotName && req.image && req.image !== DEFAULT_BOX_IMAGE_REF) {
          try {
            const snap = await client2.snapshot.get(req.image);
            if (snap && snap.name) snapshotName = snap.name;
          } catch {
          }
        }
        const snapshotParams = { ...baseParams };
        delete snapshotParams.resources;
        const sandbox = snapshotName ? await client2.create({ snapshot: snapshotName, ...snapshotParams }, { timeout: 900 }) : await client2.create(
          { image: resolveImage(req.image), ...baseParams },
          {
            timeout: 900,
            ...req.onLog ? { onSnapshotCreateLogs: req.onLog } : {}
          }
        );
        return { sandboxId: sandbox.id };
      },
      { retryOnAmbiguous: false, attemptTimeoutMs: 9e5 }
    );
  },
  async ensureVolume(name) {
    const client2 = getClient();
    let vol = await retry("volume.get(create)", () => client2.volume.get(name, true));
    const deadline = Date.now() + 6e4;
    while (vol.state !== "ready") {
      if (vol.state === "error" || vol.state === "deleted" || vol.state === "deleting") {
        throw new Error(
          `Daytona volume '${name}' is in unrecoverable state '${vol.state}'. Delete it from the Daytona dashboard and retry.`
        );
      }
      if (Date.now() >= deadline) {
        throw new Error(
          `Daytona volume '${name}' did not become ready within 60s (state: ${vol.state}). Try again \u2014 the Daytona control plane may be slow.`
        );
      }
      await new Promise((r) => setTimeout(r, 1e3));
      vol = await retry("volume.get(poll)", () => client2.volume.get(name));
    }
    return { volumeId: vol.id };
  },
  async get(sandboxId) {
    return retry("get", async () => {
      const sb = await maybeGetSandbox(sandboxId);
      return sb ? { sandboxId: sb.id } : null;
    });
  },
  async list() {
    return retry("list", async () => {
      const client2 = getClient();
      const page = await client2.list();
      const items = Array.isArray(page) ? page : page.items ?? [];
      return items.map((sb) => {
        const summary = { sandboxId: sb.id };
        const raw = sb;
        const friendly = raw.labels?.["agentbox.name"] ?? raw.name;
        if (friendly) summary.name = friendly;
        if (raw.createdAt) summary.createdAt = raw.createdAt;
        if (typeof raw.state === "string") summary.state = mapState(raw.state);
        return summary;
      });
    });
  },
  async start(h) {
    return retry(
      "start",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb.start();
      },
      { attemptTimeoutMs: 6e4 }
    );
  },
  async stop(h) {
    return retry(
      "stop",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb.stop();
      },
      { attemptTimeoutMs: 6e4 }
    );
  },
  async pause(h) {
    return retry(
      "pause",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb.archive();
      },
      { attemptTimeoutMs: 6e4 }
    );
  },
  async resume(h) {
    return retry(
      "resume",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb.start();
      },
      { attemptTimeoutMs: 6e4 }
    );
  },
  async destroy(h) {
    return retry(
      "destroy",
      async () => {
        const sb = await maybeGetSandbox(h.sandboxId);
        if (!sb) return;
        try {
          await sb.stop(60);
        } catch {
        }
        try {
          await sb.delete(60);
        } catch (err) {
          const msg = err instanceof Error ? err.message : String(err);
          if (!/not found/i.test(msg)) throw err;
        }
      },
      { attemptTimeoutMs: 12e4 }
    );
  },
  async state(h) {
    return retry("state", async () => {
      const sb = await maybeGetSandbox(h.sandboxId);
      if (!sb) return "missing";
      return mapState(sb.state);
    });
  },
  async exec(h, cmd, opts) {
    return retry(
      "exec",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        const r = await sb.process.executeCommand(cmd, opts?.cwd, opts?.env);
        return { exitCode: r.exitCode, stdout: r.result, stderr: "" };
      },
      { attemptTimeoutMs: opts?.attemptTimeoutMs ?? 12e4, noRetry: opts?.noRetry }
    );
  },
  async uploadFile(h, localPath, remotePath) {
    return retry(
      "uploadFile",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb.fs.uploadFile(localPath, remotePath);
      },
      { attemptTimeoutMs: 3e5 }
    );
  },
  async downloadFile(h, remotePath, localPath) {
    return retry(
      "downloadFile",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb.fs.downloadFile(remotePath, localPath);
      },
      { attemptTimeoutMs: 3e5 }
    );
  },
  async listFiles(h, remoteDir) {
    return retry("listFiles", async () => {
      const sb = await getSandbox(h.sandboxId);
      const files = await sb.fs.listFiles(remoteDir);
      return files.map((f) => ({
        name: f.name,
        isDir: Boolean(f.isDir)
      }));
    });
  },
  async previewUrl(h, port) {
    return retry("previewUrl", async () => {
      const sb = await getSandbox(h.sandboxId);
      const p = await sb.getPreviewLink(port);
      return { url: p.url, token: p.token };
    });
  },
  async signedPreviewUrl(h, port, expiresInSeconds) {
    return retry("signedPreviewUrl", async () => {
      const sb = await getSandbox(h.sandboxId);
      const s = await sb.getSignedPreviewUrl(port, expiresInSeconds);
      return { url: s.url, token: s.token };
    });
  },
  async attachArgv(h) {
    return retry("attachArgv", async () => {
      const sb = await getSandbox(h.sandboxId);
      const ssh = await sb.createSshAccess(60);
      return [
        "ssh",
        // First-connect to a never-seen host fingerprint should be silent in a
        // PTY — the user already authenticated via Daytona's API.
        "-o",
        "StrictHostKeyChecking=accept-new",
        // Daytona's SSH gateway terminates per-token; no key file, no port.
        `${ssh.token}@ssh.app.daytona.io`
      ];
    });
  },
  async revokeAttachToken(h, argv) {
    const userhost = argv[argv.length - 1] ?? "";
    const atIdx = userhost.indexOf("@");
    if (atIdx <= 0) return;
    const token = userhost.slice(0, atIdx);
    if (token.length === 0) return;
    try {
      await retry("revokeAttachToken", async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb.revokeSshAccess(token);
      });
    } catch {
    }
  },
  async createSnapshot(h, snapshotName) {
    return retry(
      "createSnapshot",
      async () => {
        const sb = await getSandbox(h.sandboxId);
        await sb._experimental_createSnapshot(snapshotName);
      },
      { attemptTimeoutMs: 9e5, retryOnAmbiguous: false }
    );
  },
  async deleteSnapshot(snapshotName) {
    return retry("deleteSnapshot", async () => {
      try {
        const client2 = getClient();
        const snapshot = await client2.snapshot.get(snapshotName);
        await client2.snapshot.delete(snapshot);
      } catch (err) {
        if (err instanceof DaytonaNotFoundError2) return;
        const msg = err instanceof Error ? err.message : String(err);
        if (/not found/i.test(msg)) return;
        throw err;
      }
    });
  }
};
var DASHBOARD_KEYS_URL = "https://app.daytona.io/dashboard/keys";
var MANAGED_KEYS = ["DAYTONA_API_KEY", "DAYTONA_JWT_TOKEN", "DAYTONA_ORGANIZATION_ID"];
async function ensureDaytonaCredentials(opts = {}) {
  ensureDaytonaEnvLoaded();
  if (!opts.force && hasUsableCredentials()) return;
  if (!process.stdin.isTTY) return;
  intro("Daytona setup");
  note(
    `AgentBox needs a Daytona API key to provision cloud boxes.
Generate one at ${DASHBOARD_KEYS_URL}`,
    "API key required"
  );
  const open = await confirm({
    message: `Open ${DASHBOARD_KEYS_URL} in your browser?`,
    initialValue: true
  });
  if (isCancel(open)) {
    log.warn("Daytona setup cancelled \u2014 re-run `agentbox daytona login` when ready.");
    return;
  }
  if (open) openDashboard();
  for (let attempt = 0; attempt < 2; attempt++) {
    const creds = await promptForCredentials();
    if (creds === null) return;
    const result = await validateCredentials(creds);
    if (result.ok) {
      persistCredentials(creds);
      log.success(`Daytona credentials saved to ${secretsPath()}`);
      outro("Setup complete.");
      return;
    }
    if (result.kind === "auth" && attempt === 0) {
      log.error(`That key was rejected by Daytona: ${result.message}`);
      log.info("Try again, or press Ctrl-C to cancel.");
      continue;
    }
    if (result.kind === "network") {
      log.warn(`Could not reach Daytona to validate (${result.message}) \u2014 saving anyway.`);
      persistCredentials(creds);
      log.success(`Daytona credentials saved to ${secretsPath()}`);
      outro("Setup complete (unvalidated).");
      return;
    }
    throw new Error(`Daytona credentials rejected: ${result.message}`);
  }
}
function hasUsableCredentials() {
  if (process.env.DAYTONA_API_KEY) return true;
  if (process.env.DAYTONA_JWT_TOKEN && process.env.DAYTONA_ORGANIZATION_ID) return true;
  return false;
}
async function promptForCredentials() {
  const key = await password({
    message: "Paste your Daytona API key (or JWT token)",
    validate(v) {
      if (!v || v.trim().length === 0) return "Cannot be empty";
      return void 0;
    }
  });
  if (isCancel(key)) {
    log.warn("Daytona setup cancelled.");
    return null;
  }
  const trimmed = key.trim();
  if (trimmed.startsWith("eyJ")) {
    const org = await text({
      message: "Paste your Daytona organization ID",
      placeholder: "org_...",
      validate(v) {
        if (!v || v.trim().length === 0) return "Cannot be empty";
        return void 0;
      }
    });
    if (isCancel(org)) {
      log.warn("Daytona setup cancelled.");
      return null;
    }
    return { jwtToken: trimmed, organizationId: org.trim() };
  }
  return { apiKey: trimmed };
}
async function validateCredentials(creds) {
  const s = spinner();
  s.start("Validating credentials with Daytona");
  const snapshot = snapshotManagedEnv();
  applyToEnv(creds);
  try {
    const { Daytona: Daytona2 } = await import("@daytonaio/sdk");
    const client2 = new Daytona2();
    await client2.list();
    s.stop("Daytona credentials accepted");
    return { ok: true };
  } catch (err) {
    restoreManagedEnv(snapshot);
    const message = err instanceof Error ? err.message : String(err);
    s.stop("Daytona credentials check failed");
    if (/401|403|unauthor|forbidden|invalid/i.test(message)) {
      return { ok: false, kind: "auth", message };
    }
    return { ok: false, kind: "network", message };
  }
}
function snapshotManagedEnv() {
  const out = {};
  for (const k of MANAGED_KEYS) out[k] = process.env[k];
  return out;
}
function restoreManagedEnv(snap) {
  for (const k of MANAGED_KEYS) {
    if (snap[k] === void 0) delete process.env[k];
    else process.env[k] = snap[k];
  }
}
function applyToEnv(creds) {
  for (const k of MANAGED_KEYS) delete process.env[k];
  if (creds.apiKey) process.env.DAYTONA_API_KEY = creds.apiKey;
  if (creds.jwtToken) process.env.DAYTONA_JWT_TOKEN = creds.jwtToken;
  if (creds.organizationId) process.env.DAYTONA_ORGANIZATION_ID = creds.organizationId;
}
function persistCredentials(creds) {
  applyToEnv(creds);
  const path = secretsPath();
  mkdirSync(dirname2(path), { recursive: true });
  let existing = "";
  if (existsSync3(path)) {
    try {
      existing = readFileSync2(path, "utf8");
    } catch {
      existing = "";
    }
  }
  const kept = existing.split(/\r?\n/).filter((line) => {
    const stripped = line.startsWith("export ") ? line.slice("export ".length) : line;
    const eq = stripped.indexOf("=");
    if (eq <= 0) return true;
    const key = stripped.slice(0, eq).trim();
    return !MANAGED_KEYS.includes(key);
  }).join("\n").replace(/\s+$/u, "");
  const lines = [];
  if (creds.apiKey) lines.push(`DAYTONA_API_KEY=${creds.apiKey}`);
  if (creds.jwtToken) lines.push(`DAYTONA_JWT_TOKEN=${creds.jwtToken}`);
  if (creds.organizationId) lines.push(`DAYTONA_ORGANIZATION_ID=${creds.organizationId}`);
  const body = (kept ? `${kept}
` : "") + lines.join("\n") + "\n";
  const tmp = `${path}.tmp`;
  writeFileSync(tmp, body, { mode: 384 });
  try {
    chmodSync(tmp, 384);
  } catch {
  }
  renameSync(tmp, path);
  try {
    chmodSync(path, 384);
  } catch {
  }
}
function openDashboard() {
  try {
    const r = spawnSync(hostOpenCommand(), [DASHBOARD_KEYS_URL], { stdio: "ignore" });
    if (r.status !== 0) {
      log.warn(`Could not auto-open the browser \u2014 visit ${DASHBOARD_KEYS_URL} manually.`);
    }
  } catch {
    log.warn(`Could not auto-open the browser \u2014 visit ${DASHBOARD_KEYS_URL} manually.`);
  }
}
function secretsPath() {
  return resolve3(homedir2(), ".agentbox", "secrets.env");
}
function readDaytonaCredStatus() {
  const shellHadKey = !!process.env.DAYTONA_API_KEY || !!process.env.DAYTONA_JWT_TOKEN;
  ensureDaytonaEnvLoaded();
  const apiKey = process.env.DAYTONA_API_KEY;
  const jwtToken = process.env.DAYTONA_JWT_TOKEN;
  const organizationId = process.env.DAYTONA_ORGANIZATION_ID;
  if (!apiKey && !jwtToken) return { source: "none" };
  return {
    apiKey,
    jwtToken,
    organizationId,
    source: shellHadKey ? "env" : "secrets.env"
  };
}
function maskKey(value) {
  if (value.length <= 8) return "*".repeat(value.length);
  return `${value.slice(0, 4)}\u2026${"*".repeat(8)}${value.slice(-4)}`;
}

export {
  resolveDockerfileContext,
  resolveDaytonaCustomClaudeMd,
  ensureDaytonaEnvLoaded,
  DEFAULT_BOX_IMAGE_REF,
  getClient,
  daytonaBackend,
  ensureDaytonaCredentials,
  secretsPath,
  readDaytonaCredStatus,
  maskKey
};
//# sourceMappingURL=chunk-ZGVMN54V.js.map