1package agent
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7
8 "github.com/charmbracelet/crush/internal/config"
9 "github.com/charmbracelet/crush/internal/llm/tools"
10 "github.com/charmbracelet/crush/internal/lsp"
11 "github.com/charmbracelet/crush/internal/message"
12 "github.com/charmbracelet/crush/internal/session"
13)
14
15type agentTool struct {
16 sessions session.Service
17 messages message.Service
18 lspClients map[string]*lsp.Client
19}
20
21const (
22 AgentToolName = "agent"
23)
24
25type AgentParams struct {
26 Prompt string `json:"prompt"`
27}
28
29func (b *agentTool) Name() string {
30 return AgentToolName
31}
32
33func (b *agentTool) Info() tools.ToolInfo {
34 return tools.ToolInfo{
35 Name: AgentToolName,
36 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.",
37 Parameters: map[string]any{
38 "prompt": map[string]any{
39 "type": "string",
40 "description": "The task for the agent to perform",
41 },
42 },
43 Required: []string{"prompt"},
44 }
45}
46
47func (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {
48 var params AgentParams
49 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
50 return tools.NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
51 }
52 if params.Prompt == "" {
53 return tools.NewTextErrorResponse("prompt is required"), nil
54 }
55
56 sessionID, messageID := tools.GetContextValues(ctx)
57 if sessionID == "" || messageID == "" {
58 return tools.ToolResponse{}, fmt.Errorf("session_id and message_id are required")
59 }
60
61 agent, err := NewAgent(config.AgentTask, b.sessions, b.messages, TaskAgentTools(b.lspClients))
62 if err != nil {
63 return tools.ToolResponse{}, fmt.Errorf("error creating agent: %s", err)
64 }
65
66 session, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, "New Agent Session")
67 if err != nil {
68 return tools.ToolResponse{}, fmt.Errorf("error creating session: %s", err)
69 }
70
71 done, err := agent.Run(ctx, session.ID, params.Prompt)
72 if err != nil {
73 return tools.ToolResponse{}, fmt.Errorf("error generating agent: %s", err)
74 }
75 result := <-done
76 if result.Error != nil {
77 return tools.ToolResponse{}, fmt.Errorf("error generating agent: %s", result.Error)
78 }
79
80 response := result.Message
81 if response.Role != message.Assistant {
82 return tools.NewTextErrorResponse("no response"), nil
83 }
84
85 updatedSession, err := b.sessions.Get(ctx, session.ID)
86 if err != nil {
87 return tools.ToolResponse{}, fmt.Errorf("error getting session: %s", err)
88 }
89 parentSession, err := b.sessions.Get(ctx, sessionID)
90 if err != nil {
91 return tools.ToolResponse{}, fmt.Errorf("error getting parent session: %s", err)
92 }
93
94 parentSession.Cost += updatedSession.Cost
95
96 _, err = b.sessions.Save(ctx, parentSession)
97 if err != nil {
98 return tools.ToolResponse{}, fmt.Errorf("error saving parent session: %s", err)
99 }
100 return tools.NewTextResponse(response.Content().String()), nil
101}
102
103func NewAgentTool(
104 Sessions session.Service,
105 Messages message.Service,
106 LspClients map[string]*lsp.Client,
107) tools.BaseTool {
108 return &agentTool{
109 sessions: Sessions,
110 messages: Messages,
111 lspClients: LspClients,
112 }
113}