"use client";
import { useCallback, useState } from "react";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
/**
 * Behavior hook that wraps `agentExecution.create()` with loading/error
 * state.
 *
 * Maps 1:1 to the AgentExecution aggregate — a single run of an agent
 * within an existing session. Requires a `sessionId`; use
 * {@link useCreateSession} to create the session first.
 *
 * Supports both secret delivery flows:
 *
 * - **Environment Flow** — Secrets are stored in Environment resources
 *   and bound via AgentInstance. No `runtimeEnv` needed; the backend
 *   resolves credentials from the session's agent instance.
 * - **Execution Flow** — Pass `runtimeEnv` to inject per-execution
 *   secrets. Values are merged with the highest priority and deleted
 *   when the execution completes.
 *
 * @example
 * ```tsx
 * // Environment Flow: secrets come from the agent instance's environments
 * const { create } = useCreateAgentExecution();
 * await create({ org: "acme", sessionId: "ses_abc", message: "Review the PR" });
 * ```
 *
 * @example
 * ```tsx
 * // Execution Flow: inject per-call secrets
 * const { create } = useCreateAgentExecution();
 * await create({
 *   org: "acme",
 *   sessionId: "ses_abc",
 *   message: "Deploy to production",
 *   runtimeEnv: {
 *     CUSTOMER_API_KEY: { value: "cust_xyz...", isSecret: true },
 *   },
 * });
 * ```
 */
export function useCreateAgentExecution() {
    const stigmer = useStigmer();
    const [isCreating, setIsCreating] = useState(false);
    const [error, setError] = useState(null);
    const clearError = useCallback(() => setError(null), []);
    const create = useCallback(async (input) => {
        setIsCreating(true);
        setError(null);
        try {
            const execution = await stigmer.agentExecution.create({
                name: `execution-${Date.now()}`,
                org: input.org,
                sessionId: input.sessionId,
                agentId: input.agentId,
                message: input.message,
                executionConfig: input.modelName
                    ? { modelName: input.modelName }
                    : undefined,
                runtimeEnv: input.runtimeEnv,
                attachments: input.attachments,
            });
            return {
                executionId: execution.metadata.id,
                sessionId: input.sessionId,
            };
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
        finally {
            setIsCreating(false);
        }
    }, [stigmer]);
    return { create, isCreating, error, clearError };
}
//# sourceMappingURL=useCreateAgentExecution.js.map