import { Type } from "typebox";
import { z } from "zod";
import { createToolError, createToolResult } from "../utils/messages.js";
import { parseToolArgs } from "../utils/zod.js";
import { isMainToolDispatchContext, } from "./registry.js";
import { buildSubagentUiText } from "./subagent_ui.js";
import { TOOL_NAME_SEND_INPUT_TO_AGENT } from "./tool_names.js";
const SEND_INPUT_TO_AGENT_DESCRIPTION = [
    "Send a follow-up prompt to an existing subagent.",
    "The subagent must be idle before you can send another input.",
].join(" ");
const SEND_INPUT_TO_AGENT_ID_DESCRIPTION = "Subagent id to send input to.";
const SEND_INPUT_TO_AGENT_PROMPT_DESCRIPTION = [
    "The prompt to send to the subagent.",
    "Include all necessary context and instructions for the next run.",
].join(" ");
export const SEND_INPUT_TO_AGENT_TOOL = {
    name: TOOL_NAME_SEND_INPUT_TO_AGENT,
    description: SEND_INPUT_TO_AGENT_DESCRIPTION,
    parameters: Type.Object({
        id: Type.String({ description: SEND_INPUT_TO_AGENT_ID_DESCRIPTION }),
        prompt: Type.String({ description: SEND_INPUT_TO_AGENT_PROMPT_DESCRIPTION }),
    }, { additionalProperties: false }),
};
const sendInputArgsSchema = z.object({
    id: z.string().trim().min(1),
    prompt: z.string().trim().min(1),
});
function formatSendInputToolResult(args) {
    return [`ID: ${args.id}`, `Name: ${args.name}`, `Title: ${args.title}`, "Status: Running"].join("\n");
}
function resolveSnapshotTarget(snapshot) {
    return { name: snapshot.name, title: snapshot.title };
}
export function createSendInputToAgentToolDefinition(backend) {
    return {
        schema: SEND_INPUT_TO_AGENT_TOOL,
        async dispatch(toolCall, _riskLevel, signal, context) {
            let id = "";
            let prompt = "";
            let headerTarget = "(invalid arguments)";
            const blocked = (reason, details) => {
                const toolResult = createToolError(toolCall, reason);
                const uiEvent = {
                    type: "send_input_to_agent_blocked",
                    toolCallId: toolCall.id,
                    agentId: details?.id ?? (id || undefined),
                    name: details?.name ?? undefined,
                    title: details?.title ?? headerTarget,
                    headerTarget: details?.title ?? headerTarget,
                    reason,
                };
                return { kind: "single", toolResult, uiEvent };
            };
            const parsedArgs = parseToolArgs(sendInputArgsSchema, toolCall.arguments);
            if (!parsedArgs.ok) {
                return blocked(`Invalid arguments: ${parsedArgs.error}`);
            }
            ({ id, prompt } = parsedArgs.data);
            headerTarget = id;
            if (!isMainToolDispatchContext(context)) {
                return blocked("The send_input_to_agent tool is only available in the main session.", {
                    id,
                });
            }
            const controlPlane = context.subagentControlPlane;
            const snapshot = controlPlane.getSnapshot(id);
            if (!snapshot) {
                return blocked(`Unknown subagent ID: ${id}`, { id, title: id });
            }
            const config = context.config;
            const target = resolveSnapshotTarget(snapshot);
            return {
                kind: "phased",
                startedUiEvent: {
                    type: "send_input_to_agent_started",
                    toolCallId: toolCall.id,
                    agentId: id,
                    name: target.name,
                    title: target.title,
                    headerTarget: target.title,
                },
                run: (async () => {
                    if (signal?.aborted) {
                        const reason = "Aborted.";
                        const toolResult = createToolError(toolCall, reason);
                        const uiText = buildSubagentUiText({
                            output: reason,
                            statusText: `${target.name} · ${id}`,
                            maxOutputLines: 16,
                            fullText: reason,
                        });
                        const uiEvent = {
                            type: "send_input_to_agent_finished",
                            toolCallId: toolCall.id,
                            agentId: id,
                            name: target.name,
                            title: target.title,
                            headerTarget: target.title,
                            status: "error",
                            message: reason,
                            uiText,
                        };
                        return { kind: "single", toolResult, uiEvent };
                    }
                    const sendResult = controlPlane.sendInput({
                        id,
                        prompt,
                        config,
                        modelResolver: context.modelResolver,
                        authPath: context.authPath,
                        backend,
                        personaId: context.persona.id,
                    });
                    if (!sendResult.ok) {
                        const toolResult = createToolError(toolCall, sendResult.reason);
                        const uiEvent = {
                            type: "send_input_to_agent_blocked",
                            toolCallId: toolCall.id,
                            agentId: id,
                            name: target.name,
                            title: target.title,
                            headerTarget: target.title,
                            reason: sendResult.reason,
                        };
                        return { kind: "single", toolResult, uiEvent };
                    }
                    const resultText = formatSendInputToolResult(sendResult);
                    const toolResult = createToolResult(toolCall, resultText, false);
                    const uiText = buildSubagentUiText({
                        output: prompt,
                        statusText: `${sendResult.name} · ${sendResult.id}`,
                        maxOutputLines: 16,
                        fullText: resultText,
                    });
                    const uiEvent = {
                        type: "send_input_to_agent_finished",
                        toolCallId: toolCall.id,
                        agentId: sendResult.id,
                        name: sendResult.name,
                        title: sendResult.title,
                        headerTarget: sendResult.title,
                        status: "success",
                        uiText,
                    };
                    return { kind: "single", toolResult, uiEvent };
                })(),
            };
        },
    };
}
//# sourceMappingURL=send_input_to_agent.js.map