// ../packages/adaptor/dist/chunk-DMO7RTY3.js
import { execFile } from "child_process";
import { spawn } from "child_process";
import { createInterface } from "readline";
var NESTED_AGENT_ENV_PREFIXES = [
  "CLAUDECODE",
  "CODEX_HOME",
  // All CODEX_* prefix keys
  "CODEX_",
  "CLAUDE_CODE_ENTRYPOINT"
];
function shouldStripNestedAgentEnv(key) {
  return NESTED_AGENT_ENV_PREFIXES.some(
    (prefix) => key === prefix || key.startsWith(prefix + "_") || key.startsWith(prefix)
  );
}
var CLAUDE_AGENT_SDK_CLIENT_APP = "weft/agent-bridge";
function createSanitizedClaudeEnvironment(source = process.env) {
  const env = {};
  for (const [key, value] of Object.entries(source)) {
    if (value !== void 0 && !shouldStripNestedAgentEnv(key)) {
      env[key] = value;
    }
  }
  env.CLAUDE_AGENT_SDK_CLIENT_APP = CLAUDE_AGENT_SDK_CLIENT_APP;
  return env;
}
function resolveClaudeExecutable(env) {
  return env.WEFT_CLAUDE_EXECUTABLE || void 0;
}
async function readClaudeAuth(executable, env) {
  const resolvedEnv = env ?? createSanitizedClaudeEnvironment();
  const claudeBin = executable ?? resolveClaudeExecutable(resolvedEnv) ?? "claude";
  try {
    const { stdout, exitCode } = await new Promise((resolve) => {
      execFile(claudeBin, ["auth", "status", "--json"], { env: resolvedEnv }, (error, stdout2, stderr) => {
        resolve({
          stdout: stdout2?.toString() ?? "",
          stderr: stderr?.toString() ?? "",
          exitCode: error ? error.code ?? 1 : 0
        });
      });
    });
    if (exitCode !== 0) {
      return {
        mode: "provider-owned",
        configured: false,
        source: `${claudeBin} auth status --json`,
        error: `Claude Code CLI returned exit code ${exitCode}. Ensure \`claude\` is on PATH or set WEFT_CLAUDE_EXECUTABLE.`
      };
    }
    const status = JSON.parse(stdout);
    return {
      mode: "provider-owned",
      configured: status.loggedIn === true,
      source: `${claudeBin} auth status --json`,
      method: status.authMethod,
      provider: status.apiProvider,
      accountPresent: Boolean(status.account)
    };
  } catch (err) {
    return {
      mode: "provider-owned",
      configured: false,
      source: `${claudeBin} auth status --json`,
      error: `Claude Code auth detection failed: ${err.message}. Run \`claude\` and complete login, or set CLAUDE_CONFIG_DIR.`
    };
  }
}
function claudeAuthMissingMessage() {
  return "Claude Code authentication is not configured. Run `claude` and complete login, or set CLAUDE_CONFIG_DIR.";
}
var DEFAULT_REQUEST_TIMEOUT_MS = 1e4;
var nextRpcId = 1;
function makeRequest(method, params) {
  return { jsonrpc: "2.0", id: nextRpcId++, method, params };
}
function resolveCodexExecutable(env) {
  return env.WEFT_CODEX_EXECUTABLE || void 0;
}
function codexAuthFromResult(result, source) {
  const requiresOpenaiAuth = result.requiresOpenaiAuth === true;
  const accountPresent = Boolean(result.account);
  const configured = !requiresOpenaiAuth || accountPresent;
  return {
    mode: "provider-owned",
    configured,
    source,
    accountPresent,
    requiresOpenaiAuth,
    error: configured ? void 0 : codexAuthMissingMessage()
  };
}
async function readCodexAuth(executable, env, requestTimeoutMs) {
  const resolvedEnv = env ?? Object.fromEntries(
    Object.entries(process.env).filter(([, v]) => v !== void 0)
  );
  const codexBin = executable ?? resolveCodexExecutable(resolvedEnv) ?? "codex";
  const timeout = requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
  const source = `${codexBin} app-server account/read`;
  let proc = null;
  try {
    proc = spawn(codexBin, ["app-server"], {
      env: resolvedEnv,
      stdio: ["pipe", "pipe", "pipe"]
    });
  } catch (err) {
    return {
      mode: "provider-owned",
      configured: false,
      source,
      error: `Codex auth detection failed: ${err.message}. Ensure \`codex\` is on PATH or set WEFT_CODEX_EXECUTABLE.`
    };
  }
  const spawnError = new Promise((_, reject) => {
    proc.on("error", (err) => {
      reject(new Error(`Codex auth detection failed: ${err.message}. Ensure \`codex\` is on PATH or set WEFT_CODEX_EXECUTABLE.`));
    });
  });
  try {
    const rl = createInterface({ input: proc.stdout, crlfDelay: Infinity });
    const writeMsg = (msg) => {
      proc.stdin.write(JSON.stringify(msg) + "\n");
    };
    const readResponse = () => {
      const linePromise = new Promise((resolve, reject) => {
        const deadline = Date.now() + timeout;
        const timer = setTimeout(() => {
          reject(new Error(`Timeout waiting for Codex app-server response (${timeout}ms)`));
        }, Math.max(0, deadline - Date.now()));
        rl.once("line", (line) => {
          clearTimeout(timer);
          const trimmed = line.trim();
          if (trimmed) {
            try {
              resolve(JSON.parse(trimmed));
            } catch {
              reject(new Error(`Invalid JSON-RPC response: ${trimmed}`));
            }
          }
        });
      });
      return Promise.race([linePromise, spawnError]);
    };
    writeMsg(makeRequest("initialize", {
      protocolVersion: "2025-03-26",
      capabilities: {},
      clientInfo: { name: "weft", title: "Weft", version: "0.1.0" }
    }));
    const initResp = await readResponse();
    if (initResp.error) {
      rl.close();
      proc.kill();
      return {
        mode: "provider-owned",
        configured: false,
        source,
        error: `Codex initialize failed: ${initResp.error.message}`
      };
    }
    writeMsg({ jsonrpc: "2.0", method: "initialized", params: {} });
    await new Promise((resolve) => setTimeout(resolve, 50));
    writeMsg(makeRequest("account/read", { refreshToken: false }));
    const accountResp = await readResponse();
    rl.close();
    proc.kill();
    if (accountResp.error) {
      return {
        mode: "provider-owned",
        configured: false,
        source,
        error: `Codex account/read failed: ${accountResp.error.message}`
      };
    }
    return codexAuthFromResult(
      accountResp.result,
      source
    );
  } catch (err) {
    try {
      proc.kill();
    } catch {
    }
    return {
      mode: "provider-owned",
      configured: false,
      source,
      error: `Codex auth detection failed: ${err.message}. Ensure \`codex\` is on PATH or set WEFT_CODEX_EXECUTABLE.`
    };
  }
}
function codexAuthMissingMessage() {
  return "Codex authentication is not configured. Run `codex login` or set CODEX_HOME to a directory with valid auth.";
}
function assertCodexAuthConfigured(auth) {
  if (!auth.configured) {
    throw new Error(auth.error ?? codexAuthMissingMessage());
  }
}

export {
  createSanitizedClaudeEnvironment,
  readClaudeAuth,
  claudeAuthMissingMessage,
  codexAuthFromResult,
  readCodexAuth,
  codexAuthMissingMessage,
  assertCodexAuthConfigured
};
