import { z } from 'zod';
const schema = z.object({
    description: z.string().min(1),
    prompt: z.string().min(1),
});
/**
 * Subagent tool: runs a nested agent with a fresh, isolated context and
 * returns only its final answer. Keeps big exploration out of the parent's
 * context window. Subagents cannot spawn further subagents.
 */
export function createTaskTool(deps) {
    return {
        name: 'task',
        description: 'Launch a subagent with a fresh context to handle a self-contained task ' +
            '(e.g. broad codebase exploration, a multi-step side quest). The subagent has the same tools ' +
            'except task itself, and only its final report comes back, so give it complete instructions ' +
            'and tell it exactly what to return.',
        schema,
        jsonSchema: {
            type: 'object',
            properties: {
                description: { type: 'string', description: 'Short 3-6 word title for the subtask' },
                prompt: {
                    type: 'string',
                    description: 'Full self-contained instructions, including what to return in the final response',
                },
            },
            required: ['description', 'prompt'],
        },
        readOnly: false,
        summarize: (i) => i.description,
        run: async (input, ctx) => {
            // Imported lazily to avoid a circular import at module load time
            // (loop.ts -> tools/index.ts -> task.ts -> loop.ts).
            const { runAgent } = await import('../agent/loop.js');
            const messages = [
                {
                    role: 'system',
                    content: deps.buildSystemPrompt(ctx.cwd) +
                        '\n\n# Subagent\n\nYou are running as a subagent. Complete the task and end with a clear final report; your last message is the only thing returned to the caller.',
                },
                { role: 'user', content: input.prompt },
            ];
            const subTools = deps.getTools().filter((t) => t.name !== 'task');
            const controller = new AbortController();
            let finalText = '';
            let toolCalls = 0;
            let errorMsg = null;
            const events = runAgent({
                apiKey: deps.apiKey,
                model: deps.getModel(),
                provider: deps.provider,
                messages,
                tools: subTools,
                gate: deps.gate,
                ctx,
                signal: controller.signal,
                maxTurns: 25,
            });
            for await (const ev of events) {
                if (ev.type === 'assistant-message' && ev.text)
                    finalText = ev.text;
                if (ev.type === 'tool-start')
                    toolCalls++;
                if (ev.type === 'error')
                    errorMsg = ev.message;
            }
            if (!finalText && errorMsg)
                return `error: subagent failed: ${errorMsg}`;
            return `[subagent "${input.description}" finished after ${toolCalls} tool call(s)]\n\n${finalText || '(no final report)'}`;
        },
    };
}
