"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var spawn_exports = {};
__export(spawn_exports, {
  backoffFor: () => backoffFor,
  buildArgs: () => buildArgs,
  isOverloaded: () => isOverloaded,
  pickAgent: () => pickAgent,
  spawnAiAgent: () => spawnAiAgent
});
module.exports = __toCommonJS(spawn_exports);
var import_message = require("../errors/message");
var import_object = require("../primordials/object");
var import_spawn = require("../spawn/spawn");
var import_errors = require("../spawn/errors");
var import_discover = require("./discover");
const MAX_ATTEMPTS = 3;
const BACKOFF_BASE_MS = 5e3;
function backoffFor(attempt) {
  return BACKOFF_BASE_MS * 3 ** (attempt - 1);
}
function buildArgs(agent, opts) {
  const allAllowed = [...opts.tools, ...opts.allow ?? []];
  switch (agent) {
    case "claude": {
      const args = [
        "--print",
        "--no-session-persistence",
        "--permission-mode",
        opts.permissionMode,
        "--add-dir",
        opts.cwd
      ];
      for (const dir of opts.addDirs ?? []) {
        args.push("--add-dir", dir);
      }
      if (opts.model) {
        args.push("--model", opts.model);
      }
      if (allAllowed.length > 0) {
        args.push("--allowedTools", ...allAllowed);
      }
      if (opts.disallow.length > 0) {
        args.push("--disallowedTools", ...opts.disallow);
      }
      if (opts.extraArgs) {
        args.push(...opts.extraArgs);
      }
      return args;
    }
    case "codex": {
      const args = ["--print"];
      if (opts.permissionMode === "plan") {
        args.push("--read-only");
      }
      if (opts.model) {
        args.push("--model", opts.model);
      }
      if (allAllowed.length > 0) {
        args.push("--tools", allAllowed.join(","));
      }
      if (opts.disallow.length > 0) {
        args.push("--disallow-tools", opts.disallow.join(","));
      }
      args.push("--cwd", opts.cwd);
      if (opts.extraArgs) {
        args.push(...opts.extraArgs);
      }
      return args;
    }
    case "gemini": {
      const args = ["--no-interactive", "--workspace", opts.cwd];
      if (opts.model) {
        args.push("--model", opts.model);
      }
      if (allAllowed.length > 0) {
        args.push("--allowed-tools", allAllowed.join(","));
      }
      if (opts.disallow.length > 0) {
        args.push("--denied-tools", opts.disallow.join(","));
      }
      if (opts.permissionMode === "plan") {
        args.push("--read-only");
      }
      if (opts.extraArgs) {
        args.push(...opts.extraArgs);
      }
      return args;
    }
    case "opencode": {
      const args = ["--print", "--cwd", opts.cwd];
      if (opts.model) {
        args.push("--model", opts.model);
      }
      if (allAllowed.length > 0) {
        args.push("--tools", allAllowed.join(","));
      }
      if (opts.disallow.length > 0) {
        args.push("--no-tools", opts.disallow.join(","));
      }
      if (opts.extraArgs) {
        args.push(...opts.extraArgs);
      }
      return args;
    }
  }
}
function isOverloaded(stdout, stderr) {
  const re = /API Error: 529|Overloaded/i;
  return re.test(stdout) || re.test(stderr);
}
async function pickAgent(requested, cwd) {
  const discovered = await (0, import_discover.discoverAiAgents)({ repoRoot: cwd });
  if (requested) {
    if (!(requested in discovered)) {
      throw new Error(
        `spawnAiAgent: requested agent "${requested}" is not on PATH. Install the CLI or pass a different agent. Discovered: ${(0, import_object.ObjectKeys)(discovered).join(", ") || "(none)"}`
      );
    }
    return requested;
  }
  if ("claude" in discovered) {
    return "claude";
  }
  for (const candidate of ["codex", "opencode", "gemini"]) {
    if (candidate in discovered) {
      return candidate;
    }
  }
  throw new Error(
    "spawnAiAgent: no AI agent CLI on PATH. Install one of: claude, codex, opencode, gemini."
  );
}
async function spawnAiAgent(opts) {
  const agent = await pickAgent(opts.agent, opts.cwd);
  const args = buildArgs(agent, opts);
  let stdout = "";
  let stderr = "";
  let exitCode = 0;
  let attempts = 0;
  const start = Date.now();
  while (attempts < MAX_ATTEMPTS) {
    attempts += 1;
    stdout = "";
    stderr = "";
    exitCode = 0;
    try {
      const child = (0, import_spawn.spawn)(agent, args, {
        cwd: opts.cwd,
        stdio: "pipe",
        stdioString: true,
        timeout: opts.timeoutMs
      });
      child.stdin?.end(opts.prompt);
      const result = await child;
      stdout = String(result.stdout ?? "");
      stderr = String(result.stderr ?? "");
      exitCode = result.code ?? 0;
    } catch (e) {
      if ((0, import_errors.isSpawnError)(e)) {
        stdout = String(e.stdout ?? "");
        stderr = String(e.stderr ?? "");
        exitCode = e.code ?? 1;
      } else {
        stderr = (0, import_message.errorMessage)(e);
        exitCode = 1;
      }
    }
    if (!isOverloaded(stdout, stderr) || attempts >= MAX_ATTEMPTS) {
      break;
    }
    await new Promise((resolve) => setTimeout(resolve, backoffFor(attempts)));
  }
  return {
    attempts,
    durationMs: Date.now() - start,
    exitCode,
    stderr,
    stdout
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  backoffFor,
  buildArgs,
  isOverloaded,
  pickAgent,
  spawnAiAgent
});
