import {
  buildCodexArgs
} from "./chunk-PJYCPDV5.js";
import {
  buildCodexAuthEnv,
  validateCodexRuntime
} from "./chunk-IXTVS4A7.js";
import {
  prepareCodexOnSandbox
} from "./chunk-NMZMRH3E.js";
import {
  createCodexTranslator
} from "./chunk-CULYZ3VA.js";
import {
  CODEX_WRAPPER_PATH
} from "./chunk-XJYR5HE3.js";
import {
  wrapPromptWithSystem
} from "./chunk-YE2RMJY7.js";
import {
  ApiError
} from "./chunk-EZYKRG4W.js";

// src/backends/codex/index.ts
function buildTurn(input) {
  const { agent, promptText, toolResults } = input;
  if (toolResults.length > 0) {
    throw new ApiError(
      400,
      "invalid_request_error",
      "codex backend does not support user.custom_tool_result re-entry in v1"
    );
  }
  const argv = buildCodexArgs({ agent });
  const env = buildCodexAuthEnv();
  const wrappedPrompt = wrapPromptWithSystem(promptText, agent.system, agent.skills);
  return { argv, env, stdin: wrappedPrompt };
}
var FIRECRACKER_PROVIDERS = /* @__PURE__ */ new Set(["sprites", "fly", "apple-firecracker"]);
var codexBackend = {
  name: "codex",
  wrapperPath: CODEX_WRAPPER_PATH,
  buildTurn,
  createTranslator: (opts) => createCodexTranslator(opts),
  prepareOnSandbox: (name, provider) => prepareCodexOnSandbox(name, provider),
  validateRuntime: validateCodexRuntime,
  // Codex's bwrap inner sandbox conflicts with firecracker VMs that
  // don't expose user namespaces — the outer VM already isolates.
  // Replace --full-auto with --dangerously-bypass-approvals-and-sandbox
  // (--yolo) which skips bwrap entirely. (openai/codex#15282)
  applyProviderQuirks(turnBuild, providerName) {
    if (!FIRECRACKER_PROVIDERS.has(providerName)) return;
    const faIdx = turnBuild.argv.indexOf("--full-auto");
    if (faIdx >= 0) turnBuild.argv.splice(faIdx, 1);
    const lastIdx = turnBuild.argv.lastIndexOf("-");
    if (lastIdx >= 0) {
      turnBuild.argv.splice(lastIdx, 0, "--dangerously-bypass-approvals-and-sandbox");
    } else {
      turnBuild.argv.push("--dangerously-bypass-approvals-and-sandbox");
    }
  }
};

export {
  codexBackend
};
