import { z } from "zod";
import { isCommandAvailable } from "../../utils/executable.js";
import { AgentProviderSchema } from "./provider-manifest.js";
const ProviderCommandDefaultSchema = z
    .object({
    mode: z.literal("default"),
})
    .strict();
const ProviderCommandAppendSchema = z
    .object({
    mode: z.literal("append"),
    args: z.array(z.string()).optional(),
})
    .strict();
const ProviderCommandReplaceSchema = z
    .object({
    mode: z.literal("replace"),
    argv: z.array(z.string().min(1)).min(1),
})
    .strict();
export const ProviderCommandSchema = z.discriminatedUnion("mode", [
    ProviderCommandDefaultSchema,
    ProviderCommandAppendSchema,
    ProviderCommandReplaceSchema,
]);
export const ProviderRuntimeSettingsSchema = z
    .object({
    command: ProviderCommandSchema.optional(),
    env: z.record(z.string()).optional(),
})
    .strict();
export const AgentProviderRuntimeSettingsMapSchema = z.record(AgentProviderSchema, ProviderRuntimeSettingsSchema);
export async function resolveProviderCommandPrefix(commandConfig, resolveDefaultCommand) {
    if (!commandConfig || commandConfig.mode === "default") {
        return {
            command: await resolveDefaultCommand(),
            args: [],
        };
    }
    if (commandConfig.mode === "append") {
        return {
            command: await resolveDefaultCommand(),
            args: [...(commandConfig.args ?? [])],
        };
    }
    return {
        command: commandConfig.argv[0],
        args: commandConfig.argv.slice(1),
    };
}
// Env vars that indicate a running Claude Code session. If the daemon itself is
// launched from inside Claude Code (e.g. by a Seawork agent), these leak into
// child processes and cause "cannot be launched inside another session" errors.
const PARENT_SESSION_ENV_VARS = [
    "CLAUDECODE",
    "CLAUDE_CODE_ENTRYPOINT",
    "CLAUDE_CODE_SSE_PORT",
    "CLAUDE_AGENT_SDK_VERSION",
    "CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING",
];
export function applyProviderEnv(baseEnv, runtimeSettings) {
    const merged = {
        ...baseEnv,
        ...(runtimeSettings?.env ?? {}),
    };
    for (const key of PARENT_SESSION_ENV_VARS) {
        delete merged[key];
    }
    return merged;
}
export async function isProviderCommandAvailable(commandConfig, resolveDefaultCommand) {
    try {
        const prefix = await resolveProviderCommandPrefix(commandConfig, resolveDefaultCommand);
        return isCommandAvailable(prefix.command);
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=provider-launch-config.js.map