1package agent
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7
  8	"github.com/charmbracelet/crush/internal/llm/tools"
  9	"github.com/charmbracelet/crush/internal/message"
 10	"github.com/charmbracelet/crush/internal/session"
 11)
 12
 13type agentTool struct {
 14	agent    Service
 15	sessions session.Service
 16	messages message.Service
 17}
 18
 19const (
 20	AgentToolName = "agent"
 21)
 22
 23type AgentParams struct {
 24	Prompt string `json:"prompt"`
 25}
 26
 27func (b *agentTool) Name() string {
 28	return AgentToolName
 29}
 30
 31func (b *agentTool) Info() tools.ToolInfo {
 32	return tools.ToolInfo{
 33		Name:        AgentToolName,
 34		Description: "Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:\n\n- If you are searching for a keyword like \"config\" or \"logger\", or for questions like \"which file does X?\", the Agent tool is strongly recommended\n- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly\n- If you are searching for a specific class definition like \"class Foo\", use the GlobTool tool instead, to find the match more quickly\n\nUsage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. IMPORTANT: The agent can not use Bash, Replace, Edit, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.",
 35		Parameters: map[string]any{
 36			"prompt": map[string]any{
 37				"type":        "string",
 38				"description": "The task for the agent to perform",
 39			},
 40		},
 41		Required: []string{"prompt"},
 42	}
 43}
 44
 45func (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {
 46	var params AgentParams
 47	if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
 48		return tools.NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
 49	}
 50	if params.Prompt == "" {
 51		return tools.NewTextErrorResponse("prompt is required"), nil
 52	}
 53
 54	sessionID, messageID := tools.GetContextValues(ctx)
 55	if sessionID == "" || messageID == "" {
 56		return tools.ToolResponse{}, fmt.Errorf("session_id and message_id are required")
 57	}
 58
 59	session, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, "New Agent Session")
 60	if err != nil {
 61		return tools.ToolResponse{}, fmt.Errorf("error creating session: %s", err)
 62	}
 63
 64	done, err := b.agent.Run(ctx, session.ID, params.Prompt)
 65	if err != nil {
 66		return tools.ToolResponse{}, fmt.Errorf("error generating agent: %s", err)
 67	}
 68	result := <-done
 69	if result.Error != nil {
 70		return tools.ToolResponse{}, fmt.Errorf("error generating agent: %s", result.Error)
 71	}
 72
 73	response := result.Message
 74	if response.Role != message.Assistant {
 75		return tools.NewTextErrorResponse("no response"), nil
 76	}
 77
 78	updatedSession, err := b.sessions.Get(ctx, session.ID)
 79	if err != nil {
 80		return tools.ToolResponse{}, fmt.Errorf("error getting session: %s", err)
 81	}
 82	parentSession, err := b.sessions.Get(ctx, sessionID)
 83	if err != nil {
 84		return tools.ToolResponse{}, fmt.Errorf("error getting parent session: %s", err)
 85	}
 86
 87	parentSession.Cost += updatedSession.Cost
 88
 89	_, err = b.sessions.Save(ctx, parentSession)
 90	if err != nil {
 91		return tools.ToolResponse{}, fmt.Errorf("error saving parent session: %s", err)
 92	}
 93	return tools.NewTextResponse(response.Content().String()), nil
 94}
 95
 96func NewAgentTool(
 97	agent Service,
 98	sessions session.Service,
 99	messages message.Service,
100) tools.BaseTool {
101	return &agentTool{
102		sessions: sessions,
103		messages: messages,
104		agent:    agent,
105	}
106}