on main help sign in
Merge pull request #301 from charmbracelet/tool_improvements

Tool improvements

commitb702fbf5fcc491a5fcc3d1e13a3fc7eae8706253 authorKujtim Hoxha <kujtimii.h@gmail.com> dateTue 29 Jul 2025, 12:37 (1 year ago) parent7e8804bbcd944c
38 files changed+2011−491
go.mod+5−5 go.sum+8−8 internal/app/app.go+1 internal/config/config.go+7 internal/config/load.go+10−1 internal/llm/agent/mcp-tools.go+1 internal/llm/prompt/coder.go+5−354 internal/llm/prompt/coder.md+267 internal/llm/prompt/init.md+10 internal/llm/prompt/initialize.go+5−9 internal/llm/prompt/summarize.md+11 internal/llm/prompt/summarizer.go+5−9 internal/llm/prompt/title.go+6−7 internal/llm/prompt/title.md+8 internal/llm/provider/openai.go+42−3 internal/llm/provider/provider.go−6 internal/llm/tools/bash.go+2−1 internal/llm/tools/edit.go+68−34 internal/llm/tools/fetch.go+1 internal/llm/tools/multiedit.go+467 internal/llm/tools/write.go+1 internal/permission/permission.go+75−11 internal/permission/permission_test.go+159 internal/tui/components/chat/chat.go+30−5 internal/tui/components/chat/editor/editor.go+43−3 internal/tui/components/chat/messages/messages.go+12 internal/tui/components/chat/messages/renderer.go+59−1 internal/tui/components/chat/messages/tool.go+496−5 internal/tui/components/chat/splash/splash.go+20 internal/tui/components/core/status/status.go+10−3 internal/tui/components/dialogs/commands/commands.go+61−15 internal/tui/components/dialogs/filepicker/filepicker.go+6−4 internal/tui/components/dialogs/permissions/permissions.go+42−1 internal/tui/exp/list/filterable.go+1−1 internal/tui/exp/list/list.go+12 internal/tui/keys.go+5 internal/tui/page/chat/chat.go+24−3 internal/tui/tui.go+26−2
go.mod+5−5
@@ -8,12 +8,13 @@ require (
88 github.com/PuerkitoBio/goquery v1.9.2
99 github.com/alecthomas/chroma/v2 v2.15.0
1010 github.com/anthropics/anthropic-sdk-go v1.6.2
11+ github.com/atotto/clipboard v0.1.4
1112 github.com/aymanbagabas/go-udiff v0.3.1
1213 github.com/bmatcuk/doublestar/v4 v4.9.0
1314 github.com/charlievieth/fastwalk v1.0.11
1415 github.com/charmbracelet/bubbles/v2 v2.0.0-beta.1.0.20250716191546-1e2ffbbcf5c5
1516 github.com/charmbracelet/bubbletea/v2 v2.0.0-beta.4.0.20250724172607-5ba56e2bec69
16− github.com/charmbracelet/catwalk v0.3.1
17+ github.com/charmbracelet/catwalk v0.3.5
1718 github.com/charmbracelet/fang v0.3.1-0.20250711140230-d5ebb8c1d674
1819 github.com/charmbracelet/glamour/v2 v2.0.0-20250516160903-6f1e2c8f9ebe
1920 github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.3.0.20250721205738-ea66aa652ee0
@@ -55,7 +56,6 @@ require (
5556 github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0 // indirect
5657 github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect
5758 github.com/andybalholm/cascadia v1.3.2 // indirect
58− github.com/atotto/clipboard v0.1.4 // indirect
5959 github.com/aws/aws-sdk-go-v2 v1.30.3 // indirect
6060 github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 // indirect
6161 github.com/aws/aws-sdk-go-v2/config v1.27.27 // indirect
@@ -126,13 +126,13 @@ require (
126126 go.opentelemetry.io/otel/metric v1.35.0 // indirect
127127 go.opentelemetry.io/otel/trace v1.35.0 // indirect
128128 go.uber.org/multierr v1.11.0 // indirect
129− golang.org/x/crypto v0.37.0 // indirect
129+ golang.org/x/crypto v0.38.0 // indirect
130130 golang.org/x/image v0.26.0 // indirect
131− golang.org/x/net v0.39.0 // indirect
131+ golang.org/x/net v0.40.0 // indirect
132132 golang.org/x/sync v0.16.0 // indirect
133133 golang.org/x/sys v0.34.0
134134 golang.org/x/term v0.32.0 // indirect
135− golang.org/x/text v0.24.0
135+ golang.org/x/text v0.25.0
136136 google.golang.org/genai v1.3.0
137137 google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 // indirect
138138 google.golang.org/grpc v1.71.0 // indirect
go.sum+8−8
@@ -72,8 +72,8 @@ github.com/charmbracelet/bubbles/v2 v2.0.0-beta.1.0.20250716191546-1e2ffbbcf5c5
7272github.com/charmbracelet/bubbles/v2 v2.0.0-beta.1.0.20250716191546-1e2ffbbcf5c5/go.mod h1:6HamsBKWqEC/FVHuQMHgQL+knPyvHH55HwJDHl/adMw=
7373github.com/charmbracelet/bubbletea/v2 v2.0.0-beta.4.0.20250724172607-5ba56e2bec69 h1:nXLMl4ows2qogDXhuEtDNgFNXQiU+PJer+UEBsQZuns=
7474github.com/charmbracelet/bubbletea/v2 v2.0.0-beta.4.0.20250724172607-5ba56e2bec69/go.mod h1:XIQ1qQfRph6Z5o2EikCydjumo0oDInQySRHuPATzbZc=
75−github.com/charmbracelet/catwalk v0.3.1 h1:MkGWspcMyE659zDkqS+9wsaCMTKRFEDBFY2A2sap6+U=
76−github.com/charmbracelet/catwalk v0.3.1/go.mod h1:gUUCqqZ8bk4D7ZzGTu3I77k7cC2x4exRuJBN1H2u2pc=
75+github.com/charmbracelet/catwalk v0.3.5 h1:ChMvA5ooTNZhDKFagmGNQgIZvZp8XjpdaJ+cDmhgCgA=
76+github.com/charmbracelet/catwalk v0.3.5/go.mod h1:gUUCqqZ8bk4D7ZzGTu3I77k7cC2x4exRuJBN1H2u2pc=
7777github.com/charmbracelet/colorprofile v0.3.1 h1:k8dTHMd7fgw4bnFd7jXTLZrSU/CQrKnL3m+AxCzDz40=
7878github.com/charmbracelet/colorprofile v0.3.1/go.mod h1:/GkGusxNs8VB/RSOh3fu0TJmQ4ICMMPApIIVn0KszZ0=
7979github.com/charmbracelet/fang v0.3.1-0.20250711140230-d5ebb8c1d674 h1:+Cz+VfxD5DO+JT1LlswXWhre0HYLj6l2HW8HVGfMuC0=
@@ -298,8 +298,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y
298298golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
299299golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
300300golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
301−golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
302−golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
301+golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
302+golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
303303golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
304304golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
305305golang.org/x/image v0.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY=
@@ -315,8 +315,8 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
315315golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
316316golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
317317golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
318−golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
319−golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
318+golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
319+golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
320320golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
321321golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
322322golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -354,8 +354,8 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
354354golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
355355golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
356356golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
357−golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
358−golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
357+golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
358+golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
359359golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
360360golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
361361golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
internal/app/app.go+1
@@ -205,6 +205,7 @@ func (app *App) setupEvents() {
205205 setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
206206 setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
207207 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
208+ setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
208209 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
209210 cleanupFunc := func() {
210211 cancel()
internal/config/config.go+7
@@ -5,6 +5,7 @@ import (
55 "fmt"
66 "log/slog"
77 "net/http"
8+ "net/url"
89 "os"
910 "slices"
1011 "strings"
@@ -471,6 +472,12 @@ func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
471472 testURL = baseURL + "/models"
472473 headers["x-api-key"] = apiKey
473474 headers["anthropic-version"] = "2023-06-01"
475+ case catwalk.TypeGemini:
476+ baseURL, _ := resolver.ResolveValue(c.BaseURL)
477+ if baseURL == "" {
478+ baseURL = "https://generativelanguage.googleapis.com"
479+ }
480+ testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
474481 }
475482 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
476483 defer cancel()
internal/config/load.go+10−1
@@ -5,6 +5,7 @@ import (
55 "fmt"
66 "io"
77 "log/slog"
8+ "maps"
89 "os"
910 "path/filepath"
1011 "runtime"
@@ -135,6 +136,14 @@ func (c *Config) configureProviders(env env.Env, resolver VariableResolver, know
135136 p.Models = models
136137 }
137138 }
139+
140+ headers := map[string]string{}
141+ if len(p.DefaultHeaders) > 0 {
142+ maps.Copy(headers, p.DefaultHeaders)
143+ }
144+ if len(config.ExtraHeaders) > 0 {
145+ maps.Copy(headers, config.ExtraHeaders)
146+ }
138147 prepared := ProviderConfig{
139148 ID: string(p.ID),
140149 Name: p.Name,
@@ -142,7 +151,7 @@ func (c *Config) configureProviders(env env.Env, resolver VariableResolver, know
142151 APIKey: p.APIKey,
143152 Type: p.Type,
144153 Disable: config.Disable,
145− ExtraHeaders: config.ExtraHeaders,
154+ ExtraHeaders: headers,
146155 ExtraBody: config.ExtraBody,
147156 ExtraParams: make(map[string]string),
148157 Models: p.Models,
internal/llm/agent/mcp-tools.go+1
@@ -102,6 +102,7 @@ func (b *mcpTool) Run(ctx context.Context, params tools.ToolCall) (tools.ToolRes
102102 p := b.permissions.Request(
103103 permission.CreatePermissionRequest{
104104 SessionID: sessionID,
105+ ToolCallID: params.ID,
105106 Path: b.workingDir,
106107 ToolName: b.Info().Name,
107108 Action: "execute",
internal/llm/prompt/coder.go+5−354
@@ -2,6 +2,7 @@ package prompt
22
33import (
44 "context"
5+ _ "embed"
56 "fmt"
67 "log/slog"
78 "os"
@@ -9,21 +10,14 @@ import (
910 "runtime"
1011 "time"
1112
12− "github.com/charmbracelet/catwalk/pkg/catwalk"
1313 "github.com/charmbracelet/crush/internal/config"
1414 "github.com/charmbracelet/crush/internal/llm/tools"
1515)
1616
1717func CoderPrompt(p string, contextFiles ...string) string {
1818 var basePrompt string
19− switch p {
20− case string(catwalk.InferenceProviderOpenAI):
21− basePrompt = baseOpenAICoderPrompt
22− case string(catwalk.InferenceProviderGemini), string(catwalk.InferenceProviderVertexAI):
23− basePrompt = baseGeminiCoderPrompt
24− default:
25− basePrompt = baseAnthropicCoderPrompt
26− }
19+
20+ basePrompt = string(baseCoderPrompt)
2721 envInfo := getEnvironmentInfo()
2822
2923 basePrompt = fmt.Sprintf("%s\n\n%s\n%s", basePrompt, envInfo, lspInformation())
@@ -36,351 +30,8 @@ func CoderPrompt(p string, contextFiles ...string) string {
3630 return basePrompt
3731}
3832
39−const baseOpenAICoderPrompt = `
40−Please resolve the user's task by editing and testing the code files in your current code execution session.
41−You are a deployed coding agent.
42−Your session allows you to easily modify and run code in the user's local environment.
43−The repo(s) are already available in your working directory, and you must fully solve the problem for your answer to be considered correct.
44−
45−IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
46−
47−# Memory
48−If the current working directory contains a file called CRUSH.md, it will be automatically added to your context. This file serves multiple purposes:
49−1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time
50−2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)
51−3. Maintaining useful information about the codebase structure and organization
52−
53−When you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to CRUSH.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to CRUSH.md so you can remember it for next time.
54−
55−You MUST adhere to the following criteria when executing the task:
56−
57−- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
58−- Analyzing code for vulnerabilities is allowed.
59−- Showing user code and tool call details is allowed.
60−- User instructions may overwrite the _CODING GUIDELINES_ section in this developer message.
61−- Do not use ` + "`ls -R`" + `, ` + "`find`" + `, or ` + "`grep`" + ` - these are slow in large repos. Use the Agent tool for searching instead.
62−- Use the ` + "`edit`" + ` tool to modify files: provide file_path, old_string (with sufficient context), and new_string. The edit tool requires:
63− - Absolute file paths (starting with /)
64− - Unique old_string matches with 3-5 lines of context before and after
65− - Exact whitespace and indentation matching
66− - For new files: provide file_path and new_string, leave old_string empty
67− - For deleting content: provide file_path and old_string, leave new_string empty
68−
69−# Following conventions
70−When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
71−- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
72−- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
73−- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
74−- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
75−
76−# Code style
77−- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
78−
79−- If completing the user's task requires writing or modifying files:
80− - Your code and final answer should follow these _CODING GUIDELINES_:
81− - Fix the problem at the root cause rather than applying surface-level patches, when possible.
82− - Avoid unneeded complexity in your solution.
83− - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.
84− - Update documentation as necessary.
85− - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
86− - Use ` + "`git log`" + ` and ` + "`git blame`" + ` to search the history of the codebase if additional context is required.
87− - NEVER add copyright or license headers unless specifically requested.
88− - You do not need to ` + "`git commit`" + ` your changes; this will be done automatically for you.
89− - If there is a .pre-commit-config.yaml, use ` + "`pre-commit run --files ...`" + ` to check that your changes pass the pre-commit checks. However, do not fix pre-existing errors on lines you didn't touch.
90− - If pre-commit doesn't work after a few retries, politely inform the user that the pre-commit setup is broken.
91− - Once you finish coding, you must
92− - Check ` + "`git status`" + ` to sanity check your changes; revert any scratch files or changes.
93− - Remove all inline comments you added as much as possible, even if they look normal. Check using ` + "`git diff`" + `. Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.
94− - Check if you accidentally add copyright or license headers. If so, remove them.
95− - Try to run pre-commit if it is available.
96− - For smaller tasks, describe in brief bullet points
97− - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.
98−
99−# Doing tasks
100−The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
101−1. Use the available search tools to understand the codebase and the user's query.
102−2. Implement the solution using all tools available to you
103−3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
104−4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to CRUSH.md so that you will know to run it next time.
105−
106−NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
107−
108−# Tool usage policy
109−- When doing file search, prefer to use the Agent tool in order to reduce context usage.
110−- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in parallel.
111−- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user.
112−
113−# Proactiveness
114−You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
115−1. Doing the right thing when asked, including taking actions and follow-up actions
116−2. Not surprising the user with actions you take without asking
117−For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
118−3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
119−
120−- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):
121− - Respond in a friendly tone as a remote teammate, who is knowledgeable, capable and eager to help with coding.
122−- When your task involves writing or modifying files:
123− - Do NOT tell the user to "save the file" or "copy the code into a file" if you already created or modified the file using ` + "`edit`" + `. Instead, reference the file as already saved.
124− - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.
125−- NEVER use emojis in your responses
126−`
127−
128−const baseAnthropicCoderPrompt = `You are Crush, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
129−
130−IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
131−
132−
133−# Memory
134−If the current working directory contains a file called CRUSH.md, it will be automatically added to your context. This file serves multiple purposes:
135−1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time
136−2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)
137−3. Maintaining useful information about the codebase structure and organization
138−
139−When you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to CRUSH.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to CRUSH.md so you can remember it for next time.
140−
141−# Tone and style
142−You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
143−Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
144−Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
145−If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
146−IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
147−IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
148−IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
149−<example>
150−user: 2 + 2
151−assistant: 4
152−</example>
153−
154−<example>
155−user: what is 2+2?
156−assistant: 4
157−</example>
158−
159−<example>
160−user: is 11 a prime number?
161−assistant: true
162−</example>
163−
164−<example>
165−user: what command should I run to list files in the current directory?
166−assistant: ls
167−</example>
168−
169−<example>
170−user: what command should I run to watch files in the current directory?
171−assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
172−npm run dev
173−</example>
174−
175−<example>
176−user: How many golf balls fit inside a jetta?
177−assistant: 150000
178−</example>
179−
180−<example>
181−user: what files are in the directory src/?
182−assistant: [runs ls and sees foo.c, bar.c, baz.c]
183−user: which file contains the implementation of foo?
184−assistant: src/foo.c
185−</example>
186−
187−<example>
188−user: write tests for new feature
189−assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
190−</example>
191−
192−# Proactiveness
193−You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
194−1. Doing the right thing when asked, including taking actions and follow-up actions
195−2. Not surprising the user with actions you take without asking
196−For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
197−3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
198−
199−# Following conventions
200−When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
201−- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
202−- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
203−- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
204−- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
205−
206−# Code style
207−- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
208−
209−# Doing tasks
210−The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
211−1. Use the available search tools to understand the codebase and the user's query.
212−2. Implement the solution using all tools available to you
213−3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
214−4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to CRUSH.md so that you will know to run it next time.
215−
216−NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
217−
218−# Tool usage policy
219−- When doing file search, prefer to use the Agent tool in order to reduce context usage.
220−- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in parallel.
221−- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user.
222−
223−VERY IMPORTANT NEVER use emojis in your responses.
224−
225−You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.`
226−
227−const baseGeminiCoderPrompt = `
228−You are an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.
229−
230−IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
231−
232−# Memory
233−If the current working directory contains a file called CRUSH.md, it will be automatically added to your context. This file serves multiple purposes:
234−1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time
235−2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)
236−3. Maintaining useful information about the codebase structure and organization
237−
238−When you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to CRUSH.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to CRUSH.md so you can remember it for next time.
239−
240−# Core Mandates
241−
242−- **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
243−- **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
244−- **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
245−- **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
246−- **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
247−- **Proactiveness:** Fulfill the user's request thoroughly, including reasonable, directly implied follow-up actions.
248−- **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
249−- **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
250−- **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.
251−
252−# Code style
253−- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
254−
255−# Primary Workflows
256−
257−## Software Engineering Tasks
258−When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence:
259−1. **Understand:** Think about the user's request and the relevant codebase context. Use ` + "`grep`" + ` and ` + "`glob`" + ` search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. Use ` + "`view`" + ` to understand context and validate any assumptions you may have.
260−2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should try to use a self-verification loop by writing unit tests if relevant to the task. Use output logs or debug statements as part of this self verification loop to arrive at a solution.
261−3. **Implement:** Use the available tools (e.g., ` + "`edit`" + `, ` + "`write`" + ` ` + "`bash`" + ` ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
262−4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
263−5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
264−
265−NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
266−
267−# Operational Guidelines
268−
269−## Tone and Style (CLI Interaction)
270−- **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment.
271−- **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query.
272−- **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.
273−- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.
274−- **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
275−- **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
276−- **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.
277−
278−## Security and Safety Rules
279−- **Explain Critical Commands:** Before executing commands with ` + "`bash`" + ` that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety.
280−- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
281−
282−## Tool Usage
283−- **File Paths:** Always use absolute paths when referring to files with tools like ` + "`view`" + ` or ` + "`write`" + `. Relative paths are not supported. You must provide an absolute path.
284−- **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase).
285−- **Command Execution:** Use the ` + "`bash`" + ` tool for running shell commands, remembering the safety rule to explain modifying commands first.
286−- **Background Processes:** Use background processes (via ` + "`&`" + `) for commands that are unlikely to stop on their own, e.g. ` + "`node server.js &`" + `. If unsure, ask the user.
287−- **Interactive Commands:** Try to avoid shell commands that are likely to require user interaction (e.g. ` + "`git rebase -i`" + `). Use non-interactive versions of commands (e.g. ` + "`npm init -y`" + ` instead of ` + "`npm init`" + `) when available, and otherwise remind the user that interactive shell commands are not supported and may cause hangs until canceled by the user.
288−
289−# Examples (Illustrating Tone and Workflow)
290−
291−<example>
292−user: 1 + 2
293−model: 3
294−</example>
295−
296−<example>
297−user: is 13 a prime number?
298−model: true
299−</example>
300−
301−<example>
302−user: list files here.
303−model: [tool_call: ls for path '.']
304−</example>
305−
306−<example>
307−user: start the server implemented in server.js
308−model: [tool_call: bash for 'node server.js &' because it must run in the background]
309−</example>
310−
311−<example>
312−user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
313−model: Okay, I can refactor 'src/auth.py'.
314−First, I'll analyze the code and check for a test safety net before planning any changes.
315−[tool_call: glob for pattern 'tests/test_auth.py']
316−[tool_call: view for absolute_path '/path/to/tests/test_auth.py']
317−(After analysis)
318−Great, 'tests/test_auth.py' exists and covers the core authentication logic. With this safety net in place, I can safely plan the refactoring.
319−I'll also confirm 'requests' is a dependency.
320−[tool_call: view for absolute_path '/path/to/requirements.txt']
321−(After analysis)
322−Looks good, 'requests' is available.
323−
324−Here's the plan:
325−1. Replace the 'urllib' calls with 'requests'.
326−2. Add proper 'try...except' error handling for the new network calls.
327−3. Remove the old 'urllib' import.
328−4. Run the project's linter and tests to verify the changes.
329−
330−Should I proceed?
331−user: Yes
332−model:
333−[tool_call: edit to apply the refactoring to 'src/auth.py']
334−Refactoring complete. Running verification...
335−[tool_call: bash for 'ruff check src/auth.py && pytest']
336−(After verification passes)
337−All checks passed. This is a stable checkpoint.
338−</example>
339−
340−<example>
341−user: Delete the temp directory.
342−model: I can run ` + "`rm -rf ./temp`" + `. This will permanently delete the directory and all its contents.
343−</example>
344−
345−<example>
346−user: Write tests for someFile.ts
347−model:
348−Okay, I can write those tests. First, I'll read ` + "`someFile.ts`" + ` to understand its functionality.
349−[tool_call: view for absolute_path '/path/to/someFile.ts' or use glob to find ` + "`someFile.ts`" + ` if its location is unknown]
350−Now I'll look for existing or related test files to understand current testing conventions and dependencies.
351−[tool_call: glob for pattern '**/*.test.ts' and '**/*.spec.ts']
352−(After reviewing existing tests and the file content)
353−[tool_call: write to create /path/to/someFile.test.ts with the test code]
354−I've written the tests. Now I'll run the project's test command to verify them.
355−[tool_call: bash for 'npm run test']
356−</example>
357−
358−<example>
359−user: How do I update the user's profile information in this system?
360−model:
361−I'm not immediately sure how user profile information is updated. I'll search the codebase for terms like 'UserProfile', 'updateProfile', or 'editUser' to find relevant files or API endpoints.
362−[tool_call: grep for pattern 'UserProfile|updateProfile|editUser']
363−(After reviewing search results, assuming a relevant file like '/path/to/UserProfileService.java' was found)
364−Okay, ` + "`/path/to/UserProfileService.java`" + ` seems like the most relevant file. I'll read its content to understand how updates are handled.
365−[tool_call: view for absolute_path '/path/to/UserProfileService.java']
366−(After reading the file)
367−It appears the ` + "`updateUserProfile`" + ` method in ` + "`UserProfileService.java`" + ` is responsible for this. It expects a user ID and a ` + "`UserProfileDTO`" + ` object...
368−</example>
369−
370−<example>
371−user: Where are all the 'app.config' files in this project? I need to check their settings.
372−model:
373−[tool_call: glob for pattern '**/app.config']
374−(Assuming glob returns a list of paths like ['/path/to/moduleA/app.config', '/path/to/moduleB/app.config'])
375−I found the following 'app.config' files:
376−- /path/to/moduleA/app.config
377−- /path/to/moduleB/app.config
378−To help you check their settings, I can read their contents. Which one would you like to start with, or should I read all of them?
379−</example>
380−
381−# Final Reminder
382−Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use ` + "`view`" + ` to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved.
383−`
33+//go:embed coder.md
34+var baseCoderPrompt []byte
38435
38536func getEnvironmentInfo() string {
38637 cwd := config.Get().WorkingDir()
internal/llm/prompt/coder.mdnew file+267
@@ -0,0 +1,267 @@
1+You are Crush, an autonomous software engineering agent that helps users with coding tasks. Use the instructions below and the tools available to you to assist the user.
2+
3+# Core Principles
4+
5+You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user.
6+
7+Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
8+
9+You MUST iterate and keep going until the problem is solved.
10+
11+You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.
12+
13+Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
14+
15+**IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames, directory structure, and existing codebase patterns.**
16+
17+When the user provides URLs or when you need to research external information, use the fetch tool to gather that information. If you find relevant links in the fetched content, follow them to gather comprehensive information.
18+
19+When working with third-party packages, libraries, or frameworks that you're unfamiliar with or need to verify usage patterns for, you can use the Sourcegraph tool to search for code examples across public repositories. This can help you understand best practices and common implementation patterns.
20+
21+Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.
22+
23+If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.
24+
25+Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking approach if needed. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
26+
27+You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
28+
29+You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead just saying that you will do it.
30+
31+You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.
32+
33+# Proactiveness and Balance
34+
35+You should strive to strike a balance between:
36+
37+1. Doing the right thing when asked, including taking actions and follow-up actions
38+2. Not surprising the user with actions you take without asking
39+3. Being thorough and autonomous while staying focused on the user's actual request
40+
41+For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions. However, when they ask you to solve a problem or implement something, be proactive in completing the entire task.
42+
43+# Workflow
44+
45+1. **Understand the Context**: Think about what the code you're editing is supposed to do based on filenames, directory structure, and existing patterns.
46+2. **Fetch URLs**: Fetch any URLs provided by the user using the `fetch` tool.
47+3. **Deep Problem Understanding**: Carefully read the issue and think critically about what is required.
48+4. **Codebase Investigation**: Explore relevant files, search for key functions, and gather context.
49+5. **Research**: If needed, research the problem using available tools.
50+6. **Plan Development**: Develop a clear, step-by-step plan with a todo list.
51+7. **Incremental Implementation**: Make small, testable code changes.
52+8. **Debug and Test**: Debug as needed and test frequently.
53+9. **Iterate**: Continue until the root cause is fixed and all tests pass.
54+10. **Comprehensive Validation**: Reflect and validate thoroughly after tests pass.
55+
56+Refer to the detailed sections below for more information on each step.
57+
58+## 1. Understanding Context and Fetching URLs
59+
60+- **Context First**: Before diving into code, understand what the existing code is supposed to do based on file names, directory structure, imports, and existing patterns.
61+- **URL Fetching**: If the user provides a URL, use the `fetch` tool to retrieve the content.
62+- **Recursive Information Gathering**: If you find additional relevant URLs or links, fetch those as well until you have all necessary information.
63+
64+## 2. Deep Problem Understanding
65+
66+Carefully read the issue and think hard about a plan to solve it before coding. Consider:
67+
68+- What is the expected behavior?
69+- What are the edge cases?
70+- What are the potential pitfalls?
71+- How does this fit into the larger context of the codebase?
72+- What are the dependencies and interactions with other parts of the code?
73+
74+## 3. Codebase Investigation
75+
76+- Explore relevant files and directories using `ls`, `view`, `glob`, and `grep` tools.
77+- Search for key functions, classes, or variables related to the issue.
78+- Read and understand relevant code snippets.
79+- Identify the root cause of the problem.
80+- Validate and update your understanding continuously as you gather more context.
81+
82+## 4. Research When Needed
83+
84+- Use the `sourcegraph` tool when you need to find code examples or verify usage patterns for libraries/frameworks.
85+- Use the `fetch` tool to retrieve documentation or other web resources.
86+- Look for patterns, best practices, and implementation examples.
87+- Focus your research on what's necessary to solve the specific problem at hand.
88+
89+## 5. Develop a Detailed Plan
90+
91+- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
92+- Create a todo list in markdown format to track your progress.
93+- Each time you complete a step, check it off using `[x]` syntax.
94+- Each time you check off a step, display the updated todo list to the user.
95+- Make sure that you ACTUALLY continue on to the next step after checking off a step instead of ending your turn.
96+
97+## 6. Making Code Changes
98+
99+- Before editing, always read the relevant file contents or section to ensure complete context using the `view` tool.
100+- Always read at least 2000 lines of code at a time to ensure you have enough context.
101+- If a patch is not applied correctly, attempt to reapply it.
102+- Make small, testable, incremental changes that logically follow from your investigation and plan.
103+- Whenever you detect that a project requires an environment variable (such as an API key or secret), always check if a .env file exists in the project root. If it does not exist, automatically create a .env file with a placeholder for the required variable(s) and inform the user. Do this proactively, without waiting for the user to request it.
104+- Prefer using the `multiedit` tool when making multiple edits to the same file.
105+
106+## 7. Debugging and Testing
107+
108+- Use the `bash` tool to run commands and check for errors.
109+- Make code changes only if you have high confidence they can solve the problem.
110+- When debugging, try to determine the root cause rather than addressing symptoms.
111+- Debug for as long as needed to identify the root cause and identify a fix.
112+- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening.
113+- To test hypotheses, you can also add test statements or functions.
114+- Revisit your assumptions if unexpected behavior occurs.
115+- **Test rigorously and frequently** - this is critical for success.
116+
117+# Memory
118+
119+If the current working directory contains a file called CRUSH.md, it will be automatically added to your context. This file serves multiple purposes:
120+
121+1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time
122+2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)
123+3. Maintaining useful information about the codebase structure and organization
124+
125+When you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to CRUSH.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to CRUSH.md so you can remember it for next time.
126+
127+# How to Create a Todo List
128+
129+Use the following format to create a todo list:
130+
131+```markdown
132+- [ ] Step 1: Description of the first step
133+- [ ] Step 2: Description of the second step
134+- [ ] Step 3: Description of the third step
135+```
136+
137+Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above. Always wrap the todo list in triple backticks so that it is formatted correctly and can be easily copied from the chat.
138+
139+Always show the completed todo list to the user as the last item in your message, so that they can see that you have addressed all of the steps.
140+
141+# Communication Guidelines
142+
143+Always communicate clearly and concisely in a casual, friendly yet professional tone.
144+
145+<examples>
146+"Let me fetch the URL you provided to gather more information."
147+"Ok, I've got all of the information I need on the API and I know how to use it."
148+"Now, I will search the codebase for the function that handles the API requests."
149+"I need to update several files here - stand by"
150+"OK! Now let's run the tests to make sure everything is working correctly."
151+"Whelp - I see we have some problems. Let's fix those up."
152+</examples>
153+
154+- Respond with clear, direct answers. Use bullet points and code blocks for structure.
155+- Avoid unnecessary explanations, repetition, and filler.
156+- Always write code directly to the correct files.
157+- Do not display code to the user unless they specifically ask for it.
158+- Only elaborate when clarification is essential for accuracy or user understanding.
159+
160+# Tone and Style
161+
162+You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
163+
164+Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
165+
166+Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
167+
168+If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
169+
170+IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request.
171+
172+IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
173+
174+VERY IMPORTANT: NEVER use emojis in your responses.
175+
176+# Following Conventions
177+
178+When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
179+
180+- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
181+- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
182+- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
183+- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
184+
185+# Code Style
186+
187+- IMPORTANT: DO NOT ADD **_ANY_** COMMENTS unless asked
188+
189+# Task Execution
190+
191+The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
192+
193+1. Use the available search tools to understand the codebase and the user's query.
194+2. Implement the solution using all tools available to you
195+3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
196+4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to CRUSH.md so that you will know to run it next time.
197+
198+NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
199+
200+# Tool Usage Policy
201+
202+- When doing file search, prefer to use the Agent tool in order to reduce context usage.
203+- **IMPORTANT**: If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in parallel for efficiency.
204+- **IMPORTANT**: The user does not see the full output of the tool responses, so if you need the output of the tool for your response, make sure to summarize it for the user.
205+- All tools are executed in parallel when multiple tool calls are sent in a single message. Only send multiple tool calls when they are safe to run in parallel (no dependencies between them).
206+
207+# Reading Files and Folders
208+
209+**Always check if you have already read a file, folder, or workspace structure before reading it again.**
210+
211+- If you have already read the content and it has not changed, do NOT re-read it.
212+- Only re-read files or folders if:
213+ - You suspect the content has changed since your last read.
214+ - You have made edits to the file or folder.
215+ - You encounter an error that suggests the context may be stale or incomplete.
216+- Use your internal memory and previous context to avoid redundant reads.
217+- This will save time, reduce unnecessary operations, and make your workflow more efficient.
218+
219+# Directory Context and Navigation
220+
221+**Always maintain awareness of your current working directory by tracking it mentally from the command history.**
222+
223+- **Remember directory changes**: When you use `cd` to change directories, mentally note and remember the new location for all subsequent operations.
224+- **Track your location from context**: Use the command history and previous `cd` commands to know where you currently are without constantly checking.
225+- **Check location only when commands fail**: If a command fails unexpectedly with file/path errors, then use `pwd` to verify your current directory as the failure might be due to being in the wrong location.
226+- **Use relative paths confidently**: Once you know your location, use relative paths appropriately based on your mental model of the current directory.
227+- **Maintain directory awareness across operations**: Keep track of where you are throughout a multi-step task, especially when working with files in different directories.
228+
229+**When to verify with `pwd`:**
230+
231+- After a command fails with "file not found" or similar path-related or `exit status 1` errors
232+- When resuming work or continuing from a previous step if uncertain
233+- When you realize you may have lost track of your current location
234+
235+**Mental tracking example:**
236+
237+```bash
238+# You start in /project/root
239+cd src/components # Now mentally note: I'm in /project/root/src/components
240+# Work with files here using relative paths
241+ls ./Button.tsx # This should work because I know I'm in components/
242+# If this fails, THEN run pwd to double-check location
243+```
244+
245+# Git and Version Control
246+
247+If the user tells you to stage and commit, you may do so.
248+
249+You are NEVER allowed to stage and commit files automatically. Only do this when explicitly requested.
250+
251+# Error Handling and Recovery
252+
253+- When you encounter errors, don't give up - analyze the error carefully and try alternative approaches.
254+- If a tool fails, try a different tool or approach to accomplish the same goal.
255+- When debugging, be systematic: isolate the problem, test hypotheses, and iterate until resolved.
256+- Always validate your solutions work correctly before considering the task complete.
257+
258+# Final Validation
259+
260+Before completing any task:
261+
262+1. Ensure all todo items are checked off
263+2. Run all relevant tests
264+3. Run linting and type checking if available
265+4. Verify the original problem is solved
266+5. Test edge cases and boundary conditions
267+6. Confirm no regressions were introduced
internal/llm/prompt/init.mdnew file+10
@@ -0,0 +1,10 @@
1+`Please analyze this codebase and create a **CRUSH.md** file containing:
2+
3+- Build/lint/test commands - especially for running a single test
4+- Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.
5+
6+The file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20-30 lines long.
7+If there's already a **CRUSH.md**, improve it.
8+
9+If there are Cursor rules (in `.cursor/rules/` or `.cursorrules`) or Copilot rules (in `.github/copilot-instructions.md`), make sure to include them.
10+Add the `.crush` directory to the `.gitignore` file if it's not already there.
internal/llm/prompt/initialize.go+5−9
@@ -1,14 +1,10 @@
11package prompt
22
3−func Initialize() string {
4− return `Please analyze this codebase and create a **CRUSH.md** file containing:
5−
6−- Build/lint/test commands - especially for running a single test
7−- Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.
3+import _ "embed"
84
9−The file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20-30 lines long.
10−If there's already a **CRUSH.md**, improve it.
5+//go:embed init.md
6+var initPrompt []byte
117
12−If there are Cursor rules` + " (in `.cursor/rules/` or `.cursorrules`) or Copilot rules (in `.github/copilot-instructions.md`), make sure to include them.\n" +
13− "Add the `.crush` directory to the `.gitignore` file if it's not already there."
8+func Initialize() string {
9+ return string(initPrompt)
1410}
internal/llm/prompt/summarize.mdnew file+11
@@ -0,0 +1,11 @@
1+You are a helpful AI assistant tasked with summarizing conversations.
2+
3+When asked to summarize, provide a detailed but concise summary of the conversation.
4+Focus on information that would be helpful for continuing the conversation, including:
5+
6+- What was done
7+- What is currently being worked on
8+- Which files are being modified
9+- What needs to be done next
10+
11+Your summary should be comprehensive enough to provide context but concise enough to be quickly understood.
internal/llm/prompt/summarizer.go+5−9
@@ -1,14 +1,10 @@
11package prompt
22
3−func SummarizerPrompt() string {
4− return `You are a helpful AI assistant tasked with summarizing conversations.
3+import _ "embed"
54
6−When asked to summarize, provide a detailed but concise summary of the conversation.
7−Focus on information that would be helpful for continuing the conversation, including:
8−- What was done
9−- What is currently being worked on
10−- Which files are being modified
11−- What needs to be done next
5+//go:embed summarize.md
6+var summarizePrompt []byte
127
13−Your summary should be comprehensive enough to provide context but concise enough to be quickly understood.`
8+func SummarizerPrompt() string {
9+ return string(summarizePrompt)
1410}
internal/llm/prompt/title.go+6−7
@@ -1,11 +1,10 @@
11package prompt
22
3+import _ "embed"
4+
5+//go:embed title.md
6+var titlePrompt []byte
7+
38func TitlePrompt() string {
4− return `you will generate a short title based on the first message a user begins a conversation with
5−- ensure it is not more than 50 characters long
6−- the title should be a summary of the user's message
7−- it should be one line long
8−- do not use quotes or colons
9−- the entire text you return will be used as the title
10−- never return anything that is more than one sentence (one line) long`
9+ return string(titlePrompt)
1110}
internal/llm/prompt/title.mdnew file+8
@@ -0,0 +1,8 @@
1+you will generate a short title based on the first message a user begins a conversation with
2+
3+- ensure it is not more than 50 characters long
4+- the title should be a summary of the user's message
5+- it should be one line long
6+- do not use quotes or colons
7+- the entire text you return will be used as the title
8+- never return anything that is more than one sentence (one line) long
internal/llm/provider/openai.go+42−3
@@ -7,6 +7,7 @@ import (
77 "fmt"
88 "io"
99 "log/slog"
10+ "strings"
1011 "time"
1112
1213 "github.com/charmbracelet/catwalk/pkg/catwalk"
@@ -56,14 +57,33 @@ func createOpenAIClient(opts providerClientOptions) openai.Client {
5657}
5758
5859func (o *openaiClient) convertMessages(messages []message.Message) (openaiMessages []openai.ChatCompletionMessageParamUnion) {
60+ isAnthropicModel := o.providerOptions.config.ID == string(catwalk.InferenceProviderOpenRouter) && strings.HasPrefix(o.Model().ID, "anthropic/")
5961 // Add system message first
6062 systemMessage := o.providerOptions.systemMessage
6163 if o.providerOptions.systemPromptPrefix != "" {
6264 systemMessage = o.providerOptions.systemPromptPrefix + "\n" + systemMessage
6365 }
64− openaiMessages = append(openaiMessages, openai.SystemMessage(systemMessage))
6566
66− for _, msg := range messages {
67+ systemTextBlock := openai.ChatCompletionContentPartTextParam{Text: systemMessage}
68+ if isAnthropicModel && !o.providerOptions.disableCache {
69+ systemTextBlock.SetExtraFields(
70+ map[string]any{
71+ "cache_control": map[string]string{
72+ "type": "ephemeral",
73+ },
74+ },
75+ )
76+ }
77+ var content []openai.ChatCompletionContentPartTextParam
78+ content = append(content, systemTextBlock)
79+ system := openai.SystemMessage(content)
80+ openaiMessages = append(openaiMessages, system)
81+
82+ for i, msg := range messages {
83+ cache := false
84+ if i > len(messages)-3 {
85+ cache = true
86+ }
6787 switch msg.Role {
6888 case message.User:
6989 var content []openai.ChatCompletionContentPartUnionParam
@@ -75,6 +95,13 @@ func (o *openaiClient) convertMessages(messages []message.Message) (openaiMessag
7595
7696 content = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})
7797 }
98+ if cache && !o.providerOptions.disableCache && isAnthropicModel {
99+ textBlock.SetExtraFields(map[string]any{
100+ "cache_control": map[string]string{
101+ "type": "ephemeral",
102+ },
103+ })
104+ }
78105
79106 openaiMessages = append(openaiMessages, openai.UserMessage(content))
80107
@@ -86,8 +113,20 @@ func (o *openaiClient) convertMessages(messages []message.Message) (openaiMessag
86113 hasContent := false
87114 if msg.Content().String() != "" {
88115 hasContent = true
116+ textBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}
117+ if cache && !o.providerOptions.disableCache && isAnthropicModel {
118+ textBlock.SetExtraFields(map[string]any{
119+ "cache_control": map[string]string{
120+ "type": "ephemeral",
121+ },
122+ })
123+ }
89124 assistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{
90− OfString: openai.String(msg.Content().String()),
125+ OfArrayOfContentParts: []openai.ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion{
126+ {
127+ OfText: &textBlock,
128+ },
129+ },
91130 }
92131 }
93132
internal/llm/provider/provider.go−6
@@ -199,12 +199,6 @@ func NewProvider(cfg config.ProviderConfig, opts ...ProviderClientOption) (Provi
199199 options: clientOptions,
200200 client: newVertexAIClient(clientOptions),
201201 }, nil
202− case catwalk.TypeXAI:
203− clientOptions.baseURL = "https://api.x.ai/v1"
204− return &baseProvider[OpenAIClient]{
205− options: clientOptions,
206− client: newOpenAIClient(clientOptions),
207− }, nil
208202 }
209203 return nil, fmt.Errorf("provider not supported: %s", cfg.Type)
210204}
internal/llm/tools/bash.go+2−1
@@ -373,6 +373,7 @@ func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error)
373373 permission.CreatePermissionRequest{
374374 SessionID: sessionID,
375375 Path: b.workingDir,
376+ ToolCallID: call.ID,
376377 ToolName: BashToolName,
377378 Action: "execute",
378379 Description: fmt.Sprintf("Execute command: %s", params.Command),
@@ -439,10 +440,10 @@ func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error)
439440 Output: stdout,
440441 WorkingDirectory: currentWorkingDir,
441442 }
442− stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", currentWorkingDir)
443443 if stdout == "" {
444444 return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
445445 }
446+ stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", currentWorkingDir)
446447 return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
447448}
448449
internal/llm/tools/edit.go+68−34
@@ -18,9 +18,10 @@ import (
1818)
1919
2020type EditParams struct {
21− FilePath string `json:"file_path"`
22− OldString string `json:"old_string"`
23− NewString string `json:"new_string"`
21+ FilePath string `json:"file_path"`
22+ OldString string `json:"old_string"`
23+ NewString string `json:"new_string"`
24+ ReplaceAll bool `json:"replace_all,omitempty"`
2425}
2526
2627type EditPermissionsParams struct {
@@ -58,31 +59,33 @@ To make a file edit, provide the following:
58591. file_path: The absolute path to the file to modify (must be absolute, not relative)
59602. old_string: The text to replace (must be unique within the file, and must match the file contents exactly, including all whitespace and indentation)
60613. new_string: The edited text to replace the old_string
62+4. replace_all: Replace all occurrences of old_string (default false)
6163
6264Special cases:
6365- To create a new file: provide file_path and new_string, leave old_string empty
6466- To delete content: provide file_path and old_string, leave new_string empty
6567
66−The tool will replace ONE occurrence of old_string with new_string in the specified file.
68+The tool will replace ONE occurrence of old_string with new_string in the specified file by default. Set replace_all to true to replace all occurrences.
6769
6870CRITICAL REQUIREMENTS FOR USING THIS TOOL:
6971
70−1. UNIQUENESS: The old_string MUST uniquely identify the specific instance you want to change. This means:
72+1. UNIQUENESS: When replace_all is false (default), the old_string MUST uniquely identify the specific instance you want to change. This means:
7173 - Include AT LEAST 3-5 lines of context BEFORE the change point
7274 - Include AT LEAST 3-5 lines of context AFTER the change point
7375 - Include all whitespace, indentation, and surrounding code exactly as it appears in the file
7476
75−2. SINGLE INSTANCE: This tool can only change ONE instance at a time. If you need to change multiple instances:
76− - Make separate calls to this tool for each instance
77+2. SINGLE INSTANCE: When replace_all is false, this tool can only change ONE instance at a time. If you need to change multiple instances:
78+ - Set replace_all to true to replace all occurrences at once
79+ - Or make separate calls to this tool for each instance
7780 - Each call must uniquely identify its specific instance using extensive context
7881
79823. VERIFICATION: Before using this tool:
8083 - Check how many instances of the target text exist in the file
81− - If multiple instances exist, gather enough context to uniquely identify each one
82− - Plan separate tool calls for each instance
84+ - If multiple instances exist and replace_all is false, gather enough context to uniquely identify each one
85+ - Plan separate tool calls for each instance or use replace_all
8386
8487WARNING: If you do not follow these requirements:
85− - The tool will fail if old_string matches multiple locations
88+ - The tool will fail if old_string matches multiple locations and replace_all is false
8689 - The tool will fail if old_string doesn't match exactly (including whitespace)
8790 - You may change the wrong instance if you don't include enough context
8891
@@ -129,6 +132,10 @@ func (e *editTool) Info() ToolInfo {
129132 "type": "string",
130133 "description": "The text to replace it with",
131134 },
135+ "replace_all": map[string]any{
136+ "type": "boolean",
137+ "description": "Replace all occurrences of old_string (default false)",
138+ },
132139 },
133140 Required: []string{"file_path", "old_string", "new_string"},
134141 }
@@ -152,20 +159,20 @@ func (e *editTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error)
152159 var err error
153160
154161 if params.OldString == "" {
155− response, err = e.createNewFile(ctx, params.FilePath, params.NewString)
162+ response, err = e.createNewFile(ctx, params.FilePath, params.NewString, call)
156163 if err != nil {
157164 return response, err
158165 }
159166 }
160167
161168 if params.NewString == "" {
162− response, err = e.deleteContent(ctx, params.FilePath, params.OldString)
169+ response, err = e.deleteContent(ctx, params.FilePath, params.OldString, params.ReplaceAll, call)
163170 if err != nil {
164171 return response, err
165172 }
166173 }
167174
168− response, err = e.replaceContent(ctx, params.FilePath, params.OldString, params.NewString)
175+ response, err = e.replaceContent(ctx, params.FilePath, params.OldString, params.NewString, params.ReplaceAll, call)
169176 if err != nil {
170177 return response, err
171178 }
@@ -182,7 +189,7 @@ func (e *editTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error)
182189 return response, nil
183190}
184191
185−func (e *editTool) createNewFile(ctx context.Context, filePath, content string) (ToolResponse, error) {
192+func (e *editTool) createNewFile(ctx context.Context, filePath, content string, call ToolCall) (ToolResponse, error) {
186193 fileInfo, err := os.Stat(filePath)
187194 if err == nil {
188195 if fileInfo.IsDir() {
@@ -217,6 +224,7 @@ func (e *editTool) createNewFile(ctx context.Context, filePath, content string)
217224 permission.CreatePermissionRequest{
218225 SessionID: sessionID,
219226 Path: permissionPath,
227+ ToolCallID: call.ID,
220228 ToolName: EditToolName,
221229 Action: "write",
222230 Description: fmt.Sprintf("Create file %s", filePath),
@@ -264,7 +272,7 @@ func (e *editTool) createNewFile(ctx context.Context, filePath, content string)
264272 ), nil
265273}
266274
267−func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string) (ToolResponse, error) {
275+func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string, replaceAll bool, call ToolCall) (ToolResponse, error) {
268276 fileInfo, err := os.Stat(filePath)
269277 if err != nil {
270278 if os.IsNotExist(err) {
@@ -297,17 +305,29 @@ func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string
297305
298306 oldContent := string(content)
299307
300− index := strings.Index(oldContent, oldString)
301− if index == -1 {
302− return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
303− }
308+ var newContent string
309+ var deletionCount int
304310
305− lastIndex := strings.LastIndex(oldContent, oldString)
306− if index != lastIndex {
307− return NewTextErrorResponse("old_string appears multiple times in the file. Please provide more context to ensure a unique match"), nil
308− }
311+ if replaceAll {
312+ newContent = strings.ReplaceAll(oldContent, oldString, "")
313+ deletionCount = strings.Count(oldContent, oldString)
314+ if deletionCount == 0 {
315+ return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
316+ }
317+ } else {
318+ index := strings.Index(oldContent, oldString)
319+ if index == -1 {
320+ return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
321+ }
322+
323+ lastIndex := strings.LastIndex(oldContent, oldString)
324+ if index != lastIndex {
325+ return NewTextErrorResponse("old_string appears multiple times in the file. Please provide more context to ensure a unique match, or set replace_all to true"), nil
326+ }
309327
310− newContent := oldContent[:index] + oldContent[index+len(oldString):]
328+ newContent = oldContent[:index] + oldContent[index+len(oldString):]
329+ deletionCount = 1
330+ }
311331
312332 sessionID, messageID := GetContextValues(ctx)
313333
@@ -330,6 +350,7 @@ func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string
330350 permission.CreatePermissionRequest{
331351 SessionID: sessionID,
332352 Path: permissionPath,
353+ ToolCallID: call.ID,
333354 ToolName: EditToolName,
334355 Action: "write",
335356 Description: fmt.Sprintf("Delete content from file %s", filePath),
@@ -385,7 +406,7 @@ func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string
385406 ), nil
386407}
387408
388−func (e *editTool) replaceContent(ctx context.Context, filePath, oldString, newString string) (ToolResponse, error) {
409+func (e *editTool) replaceContent(ctx context.Context, filePath, oldString, newString string, replaceAll bool, call ToolCall) (ToolResponse, error) {
389410 fileInfo, err := os.Stat(filePath)
390411 if err != nil {
391412 if os.IsNotExist(err) {
@@ -418,17 +439,29 @@ func (e *editTool) replaceContent(ctx context.Context, filePath, oldString, newS
418439
419440 oldContent := string(content)
420441
421− index := strings.Index(oldContent, oldString)
422− if index == -1 {
423− return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
424− }
442+ var newContent string
443+ var replacementCount int
425444
426− lastIndex := strings.LastIndex(oldContent, oldString)
427− if index != lastIndex {
428− return NewTextErrorResponse("old_string appears multiple times in the file. Please provide more context to ensure a unique match"), nil
429− }
445+ if replaceAll {
446+ newContent = strings.ReplaceAll(oldContent, oldString, newString)
447+ replacementCount = strings.Count(oldContent, oldString)
448+ if replacementCount == 0 {
449+ return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
450+ }
451+ } else {
452+ index := strings.Index(oldContent, oldString)
453+ if index == -1 {
454+ return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
455+ }
456+
457+ lastIndex := strings.LastIndex(oldContent, oldString)
458+ if index != lastIndex {
459+ return NewTextErrorResponse("old_string appears multiple times in the file. Please provide more context to ensure a unique match, or set replace_all to true"), nil
460+ }
430461
431− newContent := oldContent[:index] + newString + oldContent[index+len(oldString):]
462+ newContent = oldContent[:index] + newString + oldContent[index+len(oldString):]
463+ replacementCount = 1
464+ }
432465
433466 if oldContent == newContent {
434467 return NewTextErrorResponse("new content is the same as old content. No changes made."), nil
@@ -452,6 +485,7 @@ func (e *editTool) replaceContent(ctx context.Context, filePath, oldString, newS
452485 permission.CreatePermissionRequest{
453486 SessionID: sessionID,
454487 Path: permissionPath,
488+ ToolCallID: call.ID,
455489 ToolName: EditToolName,
456490 Action: "write",
457491 Description: fmt.Sprintf("Replace content in file %s", filePath),
internal/llm/tools/fetch.go+1
@@ -136,6 +136,7 @@ func (t *fetchTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error
136136 permission.CreatePermissionRequest{
137137 SessionID: sessionID,
138138 Path: t.workingDir,
139+ ToolCallID: call.ID,
139140 ToolName: FetchToolName,
140141 Action: "fetch",
141142 Description: fmt.Sprintf("Fetch content from URL: %s", params.URL),
internal/llm/tools/multiedit.gonew file+467
@@ -0,0 +1,467 @@
1+package tools
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "fmt"
7+ "log/slog"
8+ "os"
9+ "path/filepath"
10+ "strings"
11+ "time"
12+
13+ "github.com/charmbracelet/crush/internal/diff"
14+ "github.com/charmbracelet/crush/internal/history"
15+ "github.com/charmbracelet/crush/internal/lsp"
16+ "github.com/charmbracelet/crush/internal/permission"
17+)
18+
19+type MultiEditOperation struct {
20+ OldString string `json:"old_string"`
21+ NewString string `json:"new_string"`
22+ ReplaceAll bool `json:"replace_all,omitempty"`
23+}
24+
25+type MultiEditParams struct {
26+ FilePath string `json:"file_path"`
27+ Edits []MultiEditOperation `json:"edits"`
28+}
29+
30+type MultiEditPermissionsParams struct {
31+ FilePath string `json:"file_path"`
32+ OldContent string `json:"old_content,omitempty"`
33+ NewContent string `json:"new_content,omitempty"`
34+}
35+
36+type MultiEditResponseMetadata struct {
37+ Additions int `json:"additions"`
38+ Removals int `json:"removals"`
39+ OldContent string `json:"old_content,omitempty"`
40+ NewContent string `json:"new_content,omitempty"`
41+ EditsApplied int `json:"edits_applied"`
42+}
43+
44+type multiEditTool struct {
45+ lspClients map[string]*lsp.Client
46+ permissions permission.Service
47+ files history.Service
48+ workingDir string
49+}
50+
51+const (
52+ MultiEditToolName = "multiedit"
53+ multiEditDescription = `This is a tool for making multiple edits to a single file in one operation. It is built on top of the Edit tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the Edit tool when you need to make multiple edits to the same file.
54+
55+Before using this tool:
56+
57+1. Use the Read tool to understand the file's contents and context
58+
59+2. Verify the directory path is correct
60+
61+To make multiple file edits, provide the following:
62+1. file_path: The absolute path to the file to modify (must be absolute, not relative)
63+2. edits: An array of edit operations to perform, where each edit contains:
64+ - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
65+ - new_string: The edited text to replace the old_string
66+ - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
67+
68+IMPORTANT:
69+- All edits are applied in sequence, in the order they are provided
70+- Each edit operates on the result of the previous edit
71+- All edits must be valid for the operation to succeed - if any edit fails, none will be applied
72+- This tool is ideal when you need to make several changes to different parts of the same file
73+
74+CRITICAL REQUIREMENTS:
75+1. All edits follow the same requirements as the single Edit tool
76+2. The edits are atomic - either all succeed or none are applied
77+3. Plan your edits carefully to avoid conflicts between sequential operations
78+
79+WARNING:
80+- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
81+- The tool will fail if edits.old_string and edits.new_string are the same
82+- Since edits are applied in sequence, ensure that earlier edits don't affect the text that later edits are trying to find
83+
84+When making edits:
85+- Ensure all edits result in idiomatic, correct code
86+- Do not leave the code in a broken state
87+- Always use absolute file paths (starting with /)
88+- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
89+- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
90+
91+If you want to create a new file, use:
92+- A new file path, including dir name if needed
93+- First edit: empty old_string and the new file's contents as new_string
94+- Subsequent edits: normal edit operations on the created content`
95+)
96+
97+func NewMultiEditTool(lspClients map[string]*lsp.Client, permissions permission.Service, files history.Service, workingDir string) BaseTool {
98+ return &multiEditTool{
99+ lspClients: lspClients,
100+ permissions: permissions,
101+ files: files,
102+ workingDir: workingDir,
103+ }
104+}
105+
106+func (m *multiEditTool) Name() string {
107+ return MultiEditToolName
108+}
109+
110+func (m *multiEditTool) Info() ToolInfo {
111+ return ToolInfo{
112+ Name: MultiEditToolName,
113+ Description: multiEditDescription,
114+ Parameters: map[string]any{
115+ "file_path": map[string]any{
116+ "type": "string",
117+ "description": "The absolute path to the file to modify",
118+ },
119+ "edits": map[string]any{
120+ "type": "array",
121+ "items": map[string]any{
122+ "type": "object",
123+ "properties": map[string]any{
124+ "old_string": map[string]any{
125+ "type": "string",
126+ "description": "The text to replace",
127+ },
128+ "new_string": map[string]any{
129+ "type": "string",
130+ "description": "The text to replace it with",
131+ },
132+ "replace_all": map[string]any{
133+ "type": "boolean",
134+ "default": false,
135+ "description": "Replace all occurrences of old_string (default false).",
136+ },
137+ },
138+ "required": []string{"old_string", "new_string"},
139+ "additionalProperties": false,
140+ },
141+ "minItems": 1,
142+ "description": "Array of edit operations to perform sequentially on the file",
143+ },
144+ },
145+ Required: []string{"file_path", "edits"},
146+ }
147+}
148+
149+func (m *multiEditTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
150+ var params MultiEditParams
151+ if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
152+ return NewTextErrorResponse("invalid parameters"), nil
153+ }
154+
155+ if params.FilePath == "" {
156+ return NewTextErrorResponse("file_path is required"), nil
157+ }
158+
159+ if len(params.Edits) == 0 {
160+ return NewTextErrorResponse("at least one edit operation is required"), nil
161+ }
162+
163+ if !filepath.IsAbs(params.FilePath) {
164+ params.FilePath = filepath.Join(m.workingDir, params.FilePath)
165+ }
166+
167+ // Validate all edits before applying any
168+ if err := m.validateEdits(params.Edits); err != nil {
169+ return NewTextErrorResponse(err.Error()), nil
170+ }
171+
172+ var response ToolResponse
173+ var err error
174+
175+ // Handle file creation case (first edit has empty old_string)
176+ if len(params.Edits) > 0 && params.Edits[0].OldString == "" {
177+ response, err = m.processMultiEditWithCreation(ctx, params, call)
178+ } else {
179+ response, err = m.processMultiEditExistingFile(ctx, params, call)
180+ }
181+
182+ if err != nil {
183+ return response, err
184+ }
185+
186+ if response.IsError {
187+ return response, nil
188+ }
189+
190+ // Wait for LSP diagnostics and add them to the response
191+ waitForLspDiagnostics(ctx, params.FilePath, m.lspClients)
192+ text := fmt.Sprintf("<result>\n%s\n</result>\n", response.Content)
193+ text += getDiagnostics(params.FilePath, m.lspClients)
194+ response.Content = text
195+ return response, nil
196+}
197+
198+func (m *multiEditTool) validateEdits(edits []MultiEditOperation) error {
199+ for i, edit := range edits {
200+ if edit.OldString == edit.NewString {
201+ return fmt.Errorf("edit %d: old_string and new_string are identical", i+1)
202+ }
203+ // Only the first edit can have empty old_string (for file creation)
204+ if i > 0 && edit.OldString == "" {
205+ return fmt.Errorf("edit %d: only the first edit can have empty old_string (for file creation)", i+1)
206+ }
207+ }
208+ return nil
209+}
210+
211+func (m *multiEditTool) processMultiEditWithCreation(ctx context.Context, params MultiEditParams, call ToolCall) (ToolResponse, error) {
212+ // First edit creates the file
213+ firstEdit := params.Edits[0]
214+ if firstEdit.OldString != "" {
215+ return NewTextErrorResponse("first edit must have empty old_string for file creation"), nil
216+ }
217+
218+ // Check if file already exists
219+ if _, err := os.Stat(params.FilePath); err == nil {
220+ return NewTextErrorResponse(fmt.Sprintf("file already exists: %s", params.FilePath)), nil
221+ } else if !os.IsNotExist(err) {
222+ return ToolResponse{}, fmt.Errorf("failed to access file: %w", err)
223+ }
224+
225+ // Create parent directories
226+ dir := filepath.Dir(params.FilePath)
227+ if err := os.MkdirAll(dir, 0o755); err != nil {
228+ return ToolResponse{}, fmt.Errorf("failed to create parent directories: %w", err)
229+ }
230+
231+ // Start with the content from the first edit
232+ currentContent := firstEdit.NewString
233+
234+ // Apply remaining edits to the content
235+ for i := 1; i < len(params.Edits); i++ {
236+ edit := params.Edits[i]
237+ newContent, err := m.applyEditToContent(currentContent, edit)
238+ if err != nil {
239+ return NewTextErrorResponse(fmt.Sprintf("edit %d failed: %s", i+1, err.Error())), nil
240+ }
241+ currentContent = newContent
242+ }
243+
244+ // Get session and message IDs
245+ sessionID, messageID := GetContextValues(ctx)
246+ if sessionID == "" || messageID == "" {
247+ return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
248+ }
249+
250+ // Check permissions
251+ _, additions, removals := diff.GenerateDiff("", currentContent, strings.TrimPrefix(params.FilePath, m.workingDir))
252+ rootDir := m.workingDir
253+ permissionPath := filepath.Dir(params.FilePath)
254+ if strings.HasPrefix(params.FilePath, rootDir) {
255+ permissionPath = rootDir
256+ }
257+
258+ p := m.permissions.Request(permission.CreatePermissionRequest{
259+ SessionID: sessionID,
260+ Path: permissionPath,
261+ ToolCallID: call.ID,
262+ ToolName: MultiEditToolName,
263+ Action: "write",
264+ Description: fmt.Sprintf("Create file %s with %d edits", params.FilePath, len(params.Edits)),
265+ Params: MultiEditPermissionsParams{
266+ FilePath: params.FilePath,
267+ OldContent: "",
268+ NewContent: currentContent,
269+ },
270+ })
271+ if !p {
272+ return ToolResponse{}, permission.ErrorPermissionDenied
273+ }
274+
275+ // Write the file
276+ err := os.WriteFile(params.FilePath, []byte(currentContent), 0o644)
277+ if err != nil {
278+ return ToolResponse{}, fmt.Errorf("failed to write file: %w", err)
279+ }
280+
281+ // Update file history
282+ _, err = m.files.Create(ctx, sessionID, params.FilePath, "")
283+ if err != nil {
284+ return ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
285+ }
286+
287+ _, err = m.files.CreateVersion(ctx, sessionID, params.FilePath, currentContent)
288+ if err != nil {
289+ slog.Debug("Error creating file history version", "error", err)
290+ }
291+
292+ recordFileWrite(params.FilePath)
293+ recordFileRead(params.FilePath)
294+
295+ return WithResponseMetadata(
296+ NewTextResponse(fmt.Sprintf("File created with %d edits: %s", len(params.Edits), params.FilePath)),
297+ MultiEditResponseMetadata{
298+ OldContent: "",
299+ NewContent: currentContent,
300+ Additions: additions,
301+ Removals: removals,
302+ EditsApplied: len(params.Edits),
303+ },
304+ ), nil
305+}
306+
307+func (m *multiEditTool) processMultiEditExistingFile(ctx context.Context, params MultiEditParams, call ToolCall) (ToolResponse, error) {
308+ // Validate file exists and is readable
309+ fileInfo, err := os.Stat(params.FilePath)
310+ if err != nil {
311+ if os.IsNotExist(err) {
312+ return NewTextErrorResponse(fmt.Sprintf("file not found: %s", params.FilePath)), nil
313+ }
314+ return ToolResponse{}, fmt.Errorf("failed to access file: %w", err)
315+ }
316+
317+ if fileInfo.IsDir() {
318+ return NewTextErrorResponse(fmt.Sprintf("path is a directory, not a file: %s", params.FilePath)), nil
319+ }
320+
321+ // Check if file was read before editing
322+ if getLastReadTime(params.FilePath).IsZero() {
323+ return NewTextErrorResponse("you must read the file before editing it. Use the View tool first"), nil
324+ }
325+
326+ // Check if file was modified since last read
327+ modTime := fileInfo.ModTime()
328+ lastRead := getLastReadTime(params.FilePath)
329+ if modTime.After(lastRead) {
330+ return NewTextErrorResponse(
331+ fmt.Sprintf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
332+ params.FilePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339),
333+ )), nil
334+ }
335+
336+ // Read current file content
337+ content, err := os.ReadFile(params.FilePath)
338+ if err != nil {
339+ return ToolResponse{}, fmt.Errorf("failed to read file: %w", err)
340+ }
341+
342+ oldContent := string(content)
343+ currentContent := oldContent
344+
345+ // Apply all edits sequentially
346+ for i, edit := range params.Edits {
347+ newContent, err := m.applyEditToContent(currentContent, edit)
348+ if err != nil {
349+ return NewTextErrorResponse(fmt.Sprintf("edit %d failed: %s", i+1, err.Error())), nil
350+ }
351+ currentContent = newContent
352+ }
353+
354+ // Check if content actually changed
355+ if oldContent == currentContent {
356+ return NewTextErrorResponse("no changes made - all edits resulted in identical content"), nil
357+ }
358+
359+ // Get session and message IDs
360+ sessionID, messageID := GetContextValues(ctx)
361+ if sessionID == "" || messageID == "" {
362+ return ToolResponse{}, fmt.Errorf("session ID and message ID are required for editing file")
363+ }
364+
365+ // Generate diff and check permissions
366+ _, additions, removals := diff.GenerateDiff(oldContent, currentContent, strings.TrimPrefix(params.FilePath, m.workingDir))
367+ rootDir := m.workingDir
368+ permissionPath := filepath.Dir(params.FilePath)
369+ if strings.HasPrefix(params.FilePath, rootDir) {
370+ permissionPath = rootDir
371+ }
372+
373+ p := m.permissions.Request(permission.CreatePermissionRequest{
374+ SessionID: sessionID,
375+ Path: permissionPath,
376+ ToolCallID: call.ID,
377+ ToolName: MultiEditToolName,
378+ Action: "write",
379+ Description: fmt.Sprintf("Apply %d edits to file %s", len(params.Edits), params.FilePath),
380+ Params: MultiEditPermissionsParams{
381+ FilePath: params.FilePath,
382+ OldContent: oldContent,
383+ NewContent: currentContent,
384+ },
385+ })
386+ if !p {
387+ return ToolResponse{}, permission.ErrorPermissionDenied
388+ }
389+
390+ // Write the updated content
391+ err = os.WriteFile(params.FilePath, []byte(currentContent), 0o644)
392+ if err != nil {
393+ return ToolResponse{}, fmt.Errorf("failed to write file: %w", err)
394+ }
395+
396+ // Update file history
397+ file, err := m.files.GetByPathAndSession(ctx, params.FilePath, sessionID)
398+ if err != nil {
399+ _, err = m.files.Create(ctx, sessionID, params.FilePath, oldContent)
400+ if err != nil {
401+ return ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
402+ }
403+ }
404+ if file.Content != oldContent {
405+ // User manually changed the content, store an intermediate version
406+ _, err = m.files.CreateVersion(ctx, sessionID, params.FilePath, oldContent)
407+ if err != nil {
408+ slog.Debug("Error creating file history version", "error", err)
409+ }
410+ }
411+
412+ // Store the new version
413+ _, err = m.files.CreateVersion(ctx, sessionID, params.FilePath, currentContent)
414+ if err != nil {
415+ slog.Debug("Error creating file history version", "error", err)
416+ }
417+
418+ recordFileWrite(params.FilePath)
419+ recordFileRead(params.FilePath)
420+
421+ return WithResponseMetadata(
422+ NewTextResponse(fmt.Sprintf("Applied %d edits to file: %s", len(params.Edits), params.FilePath)),
423+ MultiEditResponseMetadata{
424+ OldContent: oldContent,
425+ NewContent: currentContent,
426+ Additions: additions,
427+ Removals: removals,
428+ EditsApplied: len(params.Edits),
429+ },
430+ ), nil
431+}
432+
433+func (m *multiEditTool) applyEditToContent(content string, edit MultiEditOperation) (string, error) {
434+ if edit.OldString == "" && edit.NewString == "" {
435+ return content, nil
436+ }
437+
438+ if edit.OldString == "" {
439+ return "", fmt.Errorf("old_string cannot be empty for content replacement")
440+ }
441+
442+ var newContent string
443+ var replacementCount int
444+
445+ if edit.ReplaceAll {
446+ newContent = strings.ReplaceAll(content, edit.OldString, edit.NewString)
447+ replacementCount = strings.Count(content, edit.OldString)
448+ if replacementCount == 0 {
449+ return "", fmt.Errorf("old_string not found in content. Make sure it matches exactly, including whitespace and line breaks")
450+ }
451+ } else {
452+ index := strings.Index(content, edit.OldString)
453+ if index == -1 {
454+ return "", fmt.Errorf("old_string not found in content. Make sure it matches exactly, including whitespace and line breaks")
455+ }
456+
457+ lastIndex := strings.LastIndex(content, edit.OldString)
458+ if index != lastIndex {
459+ return "", fmt.Errorf("old_string appears multiple times in the content. Please provide more context to ensure a unique match, or set replace_all to true")
460+ }
461+
462+ newContent = content[:index] + edit.NewString + content[index+len(edit.OldString):]
463+ replacementCount = 1
464+ }
465+
466+ return newContent, nil
467+}
internal/llm/tools/write.go+1
@@ -181,6 +181,7 @@ func (w *writeTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error
181181 permission.CreatePermissionRequest{
182182 SessionID: sessionID,
183183 Path: permissionPath,
184+ ToolCallID: call.ID,
184185 ToolName: WriteToolName,
185186 Action: "write",
186187 Description: fmt.Sprintf("Create file %s", filePath),
internal/permission/permission.go+75−11
@@ -1,6 +1,7 @@
11package permission
22
33import (
4+ "context"
45 "errors"
56 "path/filepath"
67 "slices"
@@ -15,6 +16,7 @@ var ErrorPermissionDenied = errors.New("permission denied")
1516
1617type CreatePermissionRequest struct {
1718 SessionID string `json:"session_id"`
19+ ToolCallID string `json:"tool_call_id"`
1820 ToolName string `json:"tool_name"`
1921 Description string `json:"description"`
2022 Action string `json:"action"`
@@ -22,9 +24,16 @@ type CreatePermissionRequest struct {
2224 Path string `json:"path"`
2325}
2426
27+type PermissionNotification struct {
28+ ToolCallID string `json:"tool_call_id"`
29+ Granted bool `json:"granted"`
30+ Denied bool `json:"denied"`
31+}
32+
2533type PermissionRequest struct {
2634 ID string `json:"id"`
2735 SessionID string `json:"session_id"`
36+ ToolCallID string `json:"tool_call_id"`
2837 ToolName string `json:"tool_name"`
2938 Description string `json:"description"`
3039 Action string `json:"action"`
@@ -39,22 +48,32 @@ type Service interface {
3948 Deny(permission PermissionRequest)
4049 Request(opts CreatePermissionRequest) bool
4150 AutoApproveSession(sessionID string)
51+ SubscribeNotifications(ctx context.Context) <-chan pubsub.Event[PermissionNotification]
4252}
4353
4454type permissionService struct {
4555 *pubsub.Broker[PermissionRequest]
4656
57+ notificationBroker *pubsub.Broker[PermissionNotification]
4758 workingDir string
4859 sessionPermissions []PermissionRequest
4960 sessionPermissionsMu sync.RWMutex
5061 pendingRequests *csync.Map[string, chan bool]
51− autoApproveSessions []string
62+ autoApproveSessions map[string]bool
5263 autoApproveSessionsMu sync.RWMutex
5364 skip bool
5465 allowedTools []string
66+
67+ // used to make sure we only process one request at a time
68+ requestMu sync.Mutex
69+ activeRequest *PermissionRequest
5570}
5671
5772func (s *permissionService) GrantPersistent(permission PermissionRequest) {
73+ s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
74+ ToolCallID: permission.ToolCallID,
75+ Granted: true,
76+ })
5877 respCh, ok := s.pendingRequests.Get(permission.ID)
5978 if ok {
6079 respCh <- true
@@ -63,20 +82,41 @@ func (s *permissionService) GrantPersistent(permission PermissionRequest) {
6382 s.sessionPermissionsMu.Lock()
6483 s.sessionPermissions = append(s.sessionPermissions, permission)
6584 s.sessionPermissionsMu.Unlock()
85+
86+ if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
87+ s.activeRequest = nil
88+ }
6689}
6790
6891func (s *permissionService) Grant(permission PermissionRequest) {
92+ s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
93+ ToolCallID: permission.ToolCallID,
94+ Granted: true,
95+ })
6996 respCh, ok := s.pendingRequests.Get(permission.ID)
7097 if ok {
7198 respCh <- true
7299 }
100+
101+ if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
102+ s.activeRequest = nil
103+ }
73104}
74105
75106func (s *permissionService) Deny(permission PermissionRequest) {
107+ s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
108+ ToolCallID: permission.ToolCallID,
109+ Granted: false,
110+ Denied: true,
111+ })
76112 respCh, ok := s.pendingRequests.Get(permission.ID)
77113 if ok {
78114 respCh <- false
79115 }
116+
117+ if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
118+ s.activeRequest = nil
119+ }
80120}
81121
82122func (s *permissionService) Request(opts CreatePermissionRequest) bool {
@@ -84,6 +124,13 @@ func (s *permissionService) Request(opts CreatePermissionRequest) bool {
84124 return true
85125 }
86126
127+ // tell the UI that a permission was requested
128+ s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
129+ ToolCallID: opts.ToolCallID,
130+ })
131+ s.requestMu.Lock()
132+ defer s.requestMu.Unlock()
133+
87134 // Check if the tool/action combination is in the allowlist
88135 commandKey := opts.ToolName + ":" + opts.Action
89136 if slices.Contains(s.allowedTools, commandKey) || slices.Contains(s.allowedTools, opts.ToolName) {
@@ -91,7 +138,7 @@ func (s *permissionService) Request(opts CreatePermissionRequest) bool {
91138 }
92139
93140 s.autoApproveSessionsMu.RLock()
94− autoApprove := slices.Contains(s.autoApproveSessions, opts.SessionID)
141+ autoApprove := s.autoApproveSessions[opts.SessionID]
95142 s.autoApproveSessionsMu.RUnlock()
96143
97144 if autoApprove {
@@ -106,6 +153,7 @@ func (s *permissionService) Request(opts CreatePermissionRequest) bool {
106153 ID: uuid.New().String(),
107154 Path: dir,
108155 SessionID: opts.SessionID,
156+ ToolCallID: opts.ToolCallID,
109157 ToolName: opts.ToolName,
110158 Description: opts.Description,
111159 Action: opts.Action,
@@ -121,30 +169,46 @@ func (s *permissionService) Request(opts CreatePermissionRequest) bool {
121169 }
122170 s.sessionPermissionsMu.RUnlock()
123171
124− respCh := make(chan bool, 1)
172+ s.sessionPermissionsMu.RLock()
173+ for _, p := range s.sessionPermissions {
174+ if p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {
175+ s.sessionPermissionsMu.RUnlock()
176+ return true
177+ }
178+ }
179+ s.sessionPermissionsMu.RUnlock()
180+
181+ s.activeRequest = &permission
125182
183+ respCh := make(chan bool, 1)
126184 s.pendingRequests.Set(permission.ID, respCh)
127185 defer s.pendingRequests.Del(permission.ID)
128186
187+ // Publish the request
129188 s.Publish(pubsub.CreatedEvent, permission)
130189
131− // Wait for the response indefinitely
132190 return <-respCh
133191}
134192
135193func (s *permissionService) AutoApproveSession(sessionID string) {
136194 s.autoApproveSessionsMu.Lock()
137− s.autoApproveSessions = append(s.autoApproveSessions, sessionID)
195+ s.autoApproveSessions[sessionID] = true
138196 s.autoApproveSessionsMu.Unlock()
139197}
140198
199+func (s *permissionService) SubscribeNotifications(ctx context.Context) <-chan pubsub.Event[PermissionNotification] {
200+ return s.notificationBroker.Subscribe(ctx)
201+}
202+
141203func NewPermissionService(workingDir string, skip bool, allowedTools []string) Service {
142204 return &permissionService{
143− Broker: pubsub.NewBroker[PermissionRequest](),
144− workingDir: workingDir,
145− sessionPermissions: make([]PermissionRequest, 0),
146− skip: skip,
147− allowedTools: allowedTools,
148− pendingRequests: csync.NewMap[string, chan bool](),
205+ Broker: pubsub.NewBroker[PermissionRequest](),
206+ notificationBroker: pubsub.NewBroker[PermissionNotification](),
207+ workingDir: workingDir,
208+ sessionPermissions: make([]PermissionRequest, 0),
209+ autoApproveSessions: make(map[string]bool),
210+ skip: skip,
211+ allowedTools: allowedTools,
212+ pendingRequests: csync.NewMap[string, chan bool](),
149213 }
150214}
internal/permission/permission_test.go+159
@@ -1,7 +1,10 @@
11package permission
22
33import (
4+ "sync"
45 "testing"
6+
7+ "github.com/stretchr/testify/assert"
58)
69
710func TestPermissionService_AllowedCommands(t *testing.T) {
@@ -90,3 +93,159 @@ func TestPermissionService_SkipMode(t *testing.T) {
9093 t.Error("expected permission to be granted in skip mode")
9194 }
9295}
96+
97+func TestPermissionService_SequentialProperties(t *testing.T) {
98+ t.Run("Sequential permission requests with persistent grants", func(t *testing.T) {
99+ service := NewPermissionService("/tmp", false, []string{})
100+
101+ req1 := CreatePermissionRequest{
102+ SessionID: "session1",
103+ ToolName: "file_tool",
104+ Description: "Read file",
105+ Action: "read",
106+ Params: map[string]string{"file": "test.txt"},
107+ Path: "/tmp/test.txt",
108+ }
109+
110+ var result1 bool
111+ var wg sync.WaitGroup
112+ wg.Add(1)
113+
114+ events := service.Subscribe(t.Context())
115+
116+ go func() {
117+ defer wg.Done()
118+ result1 = service.Request(req1)
119+ }()
120+
121+ var permissionReq PermissionRequest
122+ event := <-events
123+
124+ permissionReq = event.Payload
125+ service.GrantPersistent(permissionReq)
126+
127+ wg.Wait()
128+ assert.True(t, result1, "First request should be granted")
129+
130+ // Second identical request should be automatically approved due to persistent permission
131+ req2 := CreatePermissionRequest{
132+ SessionID: "session1",
133+ ToolName: "file_tool",
134+ Description: "Read file again",
135+ Action: "read",
136+ Params: map[string]string{"file": "test.txt"},
137+ Path: "/tmp/test.txt",
138+ }
139+ result2 := service.Request(req2)
140+ assert.True(t, result2, "Second request should be auto-approved")
141+ })
142+ t.Run("Sequential requests with temporary grants", func(t *testing.T) {
143+ service := NewPermissionService("/tmp", false, []string{})
144+
145+ req := CreatePermissionRequest{
146+ SessionID: "session2",
147+ ToolName: "file_tool",
148+ Description: "Write file",
149+ Action: "write",
150+ Params: map[string]string{"file": "test.txt"},
151+ Path: "/tmp/test.txt",
152+ }
153+
154+ events := service.Subscribe(t.Context())
155+ var result1 bool
156+ var wg sync.WaitGroup
157+ wg.Add(1)
158+
159+ go func() {
160+ defer wg.Done()
161+ result1 = service.Request(req)
162+ }()
163+
164+ var permissionReq PermissionRequest
165+ event := <-events
166+ permissionReq = event.Payload
167+
168+ service.Grant(permissionReq)
169+ wg.Wait()
170+ assert.True(t, result1, "First request should be granted")
171+
172+ var result2 bool
173+ wg.Add(1)
174+
175+ go func() {
176+ defer wg.Done()
177+ result2 = service.Request(req)
178+ }()
179+
180+ event = <-events
181+ permissionReq = event.Payload
182+ service.Deny(permissionReq)
183+ wg.Wait()
184+ assert.False(t, result2, "Second request should be denied")
185+ })
186+ t.Run("Concurrent requests with different outcomes", func(t *testing.T) {
187+ service := NewPermissionService("/tmp", false, []string{})
188+
189+ events := service.Subscribe(t.Context())
190+
191+ var wg sync.WaitGroup
192+ results := make([]bool, 0)
193+
194+ requests := []CreatePermissionRequest{
195+ {
196+ SessionID: "concurrent1",
197+ ToolName: "tool1",
198+ Action: "action1",
199+ Path: "/tmp/file1.txt",
200+ Description: "First concurrent request",
201+ },
202+ {
203+ SessionID: "concurrent2",
204+ ToolName: "tool2",
205+ Action: "action2",
206+ Path: "/tmp/file2.txt",
207+ Description: "Second concurrent request",
208+ },
209+ {
210+ SessionID: "concurrent3",
211+ ToolName: "tool3",
212+ Action: "action3",
213+ Path: "/tmp/file3.txt",
214+ Description: "Third concurrent request",
215+ },
216+ }
217+
218+ for i, req := range requests {
219+ wg.Add(1)
220+ go func(index int, request CreatePermissionRequest) {
221+ defer wg.Done()
222+ results = append(results, service.Request(request))
223+ }(i, req)
224+ }
225+
226+ for range 3 {
227+ event := <-events
228+ switch event.Payload.ToolName {
229+ case "tool1":
230+ service.Grant(event.Payload)
231+ case "tool2":
232+ service.GrantPersistent(event.Payload)
233+ case "tool3":
234+ service.Deny(event.Payload)
235+ }
236+ }
237+ wg.Wait()
238+ grantedCount := 0
239+ for _, result := range results {
240+ if result {
241+ grantedCount++
242+ }
243+ }
244+
245+ assert.Equal(t, 2, grantedCount, "Should have 2 granted and 1 denied")
246+ secondReq := requests[1]
247+ secondReq.Description = "Repeat of second request"
248+ result := service.Request(secondReq)
249+ assert.True(t, result, "Repeated request should be auto-approved due to persistent permission")
250+ })
251+}
internal/tui/components/chat/chat.go+30−5
@@ -2,6 +2,7 @@ package chat
22
33import (
44 "context"
5+ "log/slog"
56 "time"
67
78 "github.com/charmbracelet/bubbles/v2/key"
@@ -9,6 +10,7 @@ import (
910 "github.com/charmbracelet/crush/internal/app"
1011 "github.com/charmbracelet/crush/internal/llm/agent"
1112 "github.com/charmbracelet/crush/internal/message"
13+ "github.com/charmbracelet/crush/internal/permission"
1214 "github.com/charmbracelet/crush/internal/pubsub"
1315 "github.com/charmbracelet/crush/internal/session"
1416 "github.com/charmbracelet/crush/internal/tui/components/chat/messages"
@@ -85,6 +87,8 @@ func (m *messageListCmp) Init() tea.Cmd {
8587// Update handles incoming messages and updates the component state.
8688func (m *messageListCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
8789 switch msg := msg.(type) {
90+ case pubsub.Event[permission.PermissionNotification]:
91+ return m, m.handlePermissionRequest(msg.Payload)
8892 case SessionSelectedMsg:
8993 if msg.ID != m.session.ID {
9094 cmd := m.SetSession(msg)
@@ -124,6 +128,20 @@ func (m *messageListCmp) View() string {
124128 )
125129}
126130
131+func (m *messageListCmp) handlePermissionRequest(permission permission.PermissionNotification) tea.Cmd {
132+ items := m.listCmp.Items()
133+ slog.Info("Handling permission request", "tool_call_id", permission.ToolCallID, "granted", permission.Granted)
134+ if toolCallIndex := m.findToolCallByID(items, permission.ToolCallID); toolCallIndex != NotFound {
135+ toolCall := items[toolCallIndex].(messages.ToolCallCmp)
136+ toolCall.SetPermissionRequested()
137+ if permission.Granted {
138+ toolCall.SetPermissionGranted()
139+ }
140+ m.listCmp.UpdateItem(toolCall.ID(), toolCall)
141+ }
142+ return nil
143+}
144+
127145// handleChildSession handles messages from child sessions (agent tools).
128146func (m *messageListCmp) handleChildSession(event pubsub.Event[message.Message]) tea.Cmd {
129147 var cmds []tea.Cmd
@@ -158,6 +176,7 @@ func (m *messageListCmp) handleChildSession(event pubsub.Event[message.Message])
158176 nestedCall := messages.NewToolCallCmp(
159177 event.Payload.ID,
160178 tc,
179+ m.app.Permissions,
161180 messages.WithToolCallNested(true),
162181 )
163182 cmds = append(cmds, nestedCall.Init())
@@ -199,7 +218,12 @@ func (m *messageListCmp) handleMessageEvent(event pubsub.Event[message.Message])
199218 if event.Payload.SessionID != m.session.ID {
200219 return m.handleChildSession(event)
201220 }
202− return m.handleUpdateAssistantMessage(event.Payload)
221+ switch event.Payload.Role {
222+ case message.Assistant:
223+ return m.handleUpdateAssistantMessage(event.Payload)
224+ case message.Tool:
225+ return m.handleToolMessage(event.Payload)
226+ }
203227 }
204228 return nil
205229}
@@ -371,7 +395,7 @@ func (m *messageListCmp) updateOrAddToolCall(msg message.Message, tc message.Too
371395 }
372396
373397 // Add new tool call if not found
374− return m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc))
398+ return m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions))
375399}
376400
377401// handleNewAssistantMessage processes new assistant messages and their tool calls.
@@ -390,7 +414,7 @@ func (m *messageListCmp) handleNewAssistantMessage(msg message.Message) tea.Cmd
390414
391415 // Add tool calls
392416 for _, tc := range msg.ToolCalls() {
393− cmd := m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc))
417+ cmd := m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions))
394418 cmds = append(cmds, cmd)
395419 }
396420
@@ -473,11 +497,12 @@ func (m *messageListCmp) convertAssistantMessage(msg message.Message, toolResult
473497 // Add tool calls with their results and status
474498 for _, tc := range msg.ToolCalls() {
475499 options := m.buildToolCallOptions(tc, msg, toolResultMap)
476− uiMessages = append(uiMessages, messages.NewToolCallCmp(msg.ID, tc, options...))
500+ uiMessages = append(uiMessages, messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions, options...))
477501 // If this tool call is the agent tool, fetch nested tool calls
478502 if tc.Name == agent.AgentToolName {
479503 nestedMessages, _ := m.app.Messages.List(context.Background(), tc.ID)
480− nestedUIMessages := m.convertMessagesToUI(nestedMessages, make(map[string]message.ToolResult))
504+ nestedToolResultMap := m.buildToolResultMap(nestedMessages)
505+ nestedUIMessages := m.convertMessagesToUI(nestedMessages, nestedToolResultMap)
481506 nestedToolCalls := make([]messages.ToolCallCmp, 0, len(nestedUIMessages))
482507 for _, nestedMsg := range nestedUIMessages {
483508 if toolCall, ok := nestedMsg.(messages.ToolCallCmp); ok {
internal/tui/components/chat/editor/editor.go+43−3
@@ -2,8 +2,10 @@ package editor
22
33import (
44 "fmt"
5+ "net/http"
56 "os"
67 "os/exec"
8+ "path/filepath"
79 "runtime"
810 "slices"
911 "strings"
@@ -80,7 +82,7 @@ const (
8082 maxAttachments = 5
8183)
8284
83−type openEditorMsg struct {
85+type OpenEditorMsg struct {
8486 Text string
8587}
8688
@@ -119,7 +121,7 @@ func (m *editorCmp) openEditor(value string) tea.Cmd {
119121 return util.ReportWarn("Message is empty")
120122 }
121123 os.Remove(tmpfile.Name())
122− return openEditorMsg{
124+ return OpenEditorMsg{
123125 Text: strings.TrimSpace(string(content)),
124126 }
125127 })
@@ -204,9 +206,47 @@ func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
204206 m.completionsStartIndex = 0
205207 }
206208 }
207− case openEditorMsg:
209+ case OpenEditorMsg:
208210 m.textarea.SetValue(msg.Text)
209211 m.textarea.MoveToEnd()
212+ case tea.PasteMsg:
213+ path := strings.ReplaceAll(string(msg), "\\ ", " ")
214+ // try to get an image
215+ path, err := filepath.Abs(path)
216+ if err != nil {
217+ m.textarea, cmd = m.textarea.Update(msg)
218+ return m, cmd
219+ }
220+ isAllowedType := false
221+ for _, ext := range filepicker.AllowedTypes {
222+ if strings.HasSuffix(path, ext) {
223+ isAllowedType = true
224+ break
225+ }
226+ }
227+ if !isAllowedType {
228+ m.textarea, cmd = m.textarea.Update(msg)
229+ return m, cmd
230+ }
231+ tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
232+ if tooBig {
233+ m.textarea, cmd = m.textarea.Update(msg)
234+ return m, cmd
235+ }
236+
237+ content, err := os.ReadFile(path)
238+ if err != nil {
239+ m.textarea, cmd = m.textarea.Update(msg)
240+ return m, cmd
241+ }
242+ mimeBufferSize := min(512, len(content))
243+ mimeType := http.DetectContentType(content[:mimeBufferSize])
244+ fileName := filepath.Base(path)
245+ attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
246+ return m, util.CmdHandler(filepicker.FilePickedMsg{
247+ Attachment: attachment,
248+ })
249+
210250 case tea.KeyPressMsg:
211251 cur := m.textarea.Cursor()
212252 curIdx := m.textarea.Width()*cur.Y + cur.X
internal/tui/components/chat/messages/messages.go+12
@@ -6,6 +6,7 @@ import (
66 "strings"
77 "time"
88
9+ "github.com/charmbracelet/bubbles/v2/key"
910 "github.com/charmbracelet/bubbles/v2/viewport"
1011 tea "github.com/charmbracelet/bubbletea/v2"
1112 "github.com/charmbracelet/catwalk/pkg/catwalk"
@@ -13,6 +14,7 @@ import (
1314 "github.com/charmbracelet/x/ansi"
1415 "github.com/google/uuid"
1516
17+ "github.com/atotto/clipboard"
1618 "github.com/charmbracelet/crush/internal/config"
1719 "github.com/charmbracelet/crush/internal/message"
1820 "github.com/charmbracelet/crush/internal/tui/components/anim"
@@ -23,6 +25,8 @@ import (
2325 "github.com/charmbracelet/crush/internal/tui/util"
2426)
2527
28+var copyKey = key.NewBinding(key.WithKeys("c", "y", "C", "Y"), key.WithHelp("c/y", "copy"))
29+
2630// MessageCmp defines the interface for message components in the chat interface.
2731// It combines standard UI model interfaces with message-specific functionality.
2832type MessageCmp interface {
@@ -94,6 +98,14 @@ func (m *messageCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
9498 m.anim = u.(*anim.Anim)
9599 return m, cmd
96100 }
101+ case tea.KeyPressMsg:
102+ if key.Matches(msg, copyKey) {
103+ err := clipboard.WriteAll(m.message.Content().Text)
104+ if err != nil {
105+ return m, util.ReportError(fmt.Errorf("failed to copy message content to clipboard: %w", err))
106+ }
107+ return m, util.ReportInfo("Message copied to clipboard")
108+ }
97109 }
98110 return m, nil
99111}
internal/tui/components/chat/messages/renderer.go+59−1
@@ -166,6 +166,7 @@ func init() {
166166 registry.register(tools.DownloadToolName, func() renderer { return downloadRenderer{} })
167167 registry.register(tools.ViewToolName, func() renderer { return viewRenderer{} })
168168 registry.register(tools.EditToolName, func() renderer { return editRenderer{} })
169+ registry.register(tools.MultiEditToolName, func() renderer { return multiEditRenderer{} })
169170 registry.register(tools.WriteToolName, func() renderer { return writeRenderer{} })
170171 registry.register(tools.FetchToolName, func() renderer { return fetchRenderer{} })
171172 registry.register(tools.GlobToolName, func() renderer { return globRenderer{} })
@@ -294,6 +295,57 @@ func (er editRenderer) Render(v *toolCallCmp) string {
294295 return renderPlainContent(v, v.result.Content)
295296 }
296297
298+ formatter := core.DiffFormatter().
299+ Before(fsext.PrettyPath(params.FilePath), meta.OldContent).
300+ After(fsext.PrettyPath(params.FilePath), meta.NewContent).
301+ Width(v.textWidth() - 2) // -2 for padding
302+ if v.textWidth() > 120 {
303+ formatter = formatter.Split()
304+ }
305+ // add a message to the bottom if the content was truncated
306+ formatted := formatter.String()
307+ if lipgloss.Height(formatted) > responseContextHeight {
308+ contentLines := strings.Split(formatted, "\n")
309+ truncateMessage := t.S().Muted.
310+ Background(t.BgBaseLighter).
311+ PaddingLeft(2).
312+ Width(v.textWidth() - 2).
313+ Render(fmt.Sprintf("… (%d lines)", len(contentLines)-responseContextHeight))
314+ formatted = strings.Join(contentLines[:responseContextHeight], "\n") + "\n" + truncateMessage
315+ }
316+ return formatted
317+ })
318+}
319+
320+// -----------------------------------------------------------------------------
321+// Multi-Edit renderer
322+// -----------------------------------------------------------------------------
323+
324+// multiEditRenderer handles multiple file edits with diff visualization
325+type multiEditRenderer struct {
326+ baseRenderer
327+}
328+
329+// Render displays the multi-edited file with a formatted diff of changes
330+func (mer multiEditRenderer) Render(v *toolCallCmp) string {
331+ t := styles.CurrentTheme()
332+ var params tools.MultiEditParams
333+ var args []string
334+ if err := mer.unmarshalParams(v.call.Input, &params); err == nil {
335+ file := fsext.PrettyPath(params.FilePath)
336+ editsCount := len(params.Edits)
337+ args = newParamBuilder().
338+ addMain(file).
339+ addKeyValue("edits", fmt.Sprintf("%d", editsCount)).
340+ build()
341+ }
342+
343+ return mer.renderWithParams(v, "Multi-Edit", args, func() string {
344+ var meta tools.MultiEditResponseMetadata
345+ if err := mer.unmarshalParams(v.result.Metadata, &meta); err != nil {
346+ return renderPlainContent(v, v.result.Content)
347+ }
348+
297349 formatter := core.DiffFormatter().
298350 Before(fsext.PrettyPath(params.FilePath), meta.OldContent).
299351 After(fsext.PrettyPath(params.FilePath), meta.NewContent).
@@ -672,7 +724,11 @@ func earlyState(header string, v *toolCallCmp) (string, bool) {
672724 case v.cancelled:
673725 message = t.S().Base.Foreground(t.FgSubtle).Render("Canceled.")
674726 case v.result.ToolCallID == "":
675− message = t.S().Base.Foreground(t.FgSubtle).Render("Waiting for tool to start...")
727+ if v.permissionRequested && !v.permissionGranted {
728+ message = t.S().Base.Foreground(t.FgSubtle).Render("Requesting for permission...")
729+ } else {
730+ message = t.S().Base.Foreground(t.FgSubtle).Render("Waiting for tool response...")
731+ }
676732 default:
677733 return "", false
678734 }
@@ -799,6 +855,8 @@ func prettifyToolName(name string) string {
799855 return "Download"
800856 case tools.EditToolName:
801857 return "Edit"
858+ case tools.MultiEditToolName:
859+ return "Multi-Edit"
802860 case tools.FetchToolName:
803861 return "Fetch"
804862 case tools.GlobToolName:
internal/tui/components/chat/messages/tool.go+496−5
@@ -1,10 +1,21 @@
11package messages
22
33import (
4+ "encoding/json"
45 "fmt"
6+ "path/filepath"
7+ "strings"
8+ "time"
59
10+ "github.com/atotto/clipboard"
11+ "github.com/charmbracelet/bubbles/v2/key"
612 tea "github.com/charmbracelet/bubbletea/v2"
13+ "github.com/charmbracelet/crush/internal/diff"
14+ "github.com/charmbracelet/crush/internal/fsext"
15+ "github.com/charmbracelet/crush/internal/llm/agent"
16+ "github.com/charmbracelet/crush/internal/llm/tools"
717 "github.com/charmbracelet/crush/internal/message"
18+ "github.com/charmbracelet/crush/internal/permission"
819 "github.com/charmbracelet/crush/internal/tui/components/anim"
920 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
1021 "github.com/charmbracelet/crush/internal/tui/styles"
@@ -30,6 +41,8 @@ type ToolCallCmp interface {
3041 SetNestedToolCalls([]ToolCallCmp) // Set nested tool calls
3142 SetIsNested(bool) // Set whether this tool call is nested
3243 ID() string
44+ SetPermissionRequested() // Mark permission request
45+ SetPermissionGranted() // Mark permission granted
3346}
3447
3548// toolCallCmp implements the ToolCallCmp interface for displaying tool calls.
@@ -40,10 +53,12 @@ type toolCallCmp struct {
4053 isNested bool // Whether this tool call is nested within another
4154
4255 // Tool call data and state
43− parentMessageID string // ID of the message that initiated this tool call
44− call message.ToolCall // The tool call being executed
45− result message.ToolResult // The result of the tool execution
46− cancelled bool // Whether the tool call was cancelled
56+ parentMessageID string // ID of the message that initiated this tool call
57+ call message.ToolCall // The tool call being executed
58+ result message.ToolResult // The result of the tool execution
59+ cancelled bool // Whether the tool call was cancelled
60+ permissionRequested bool
61+ permissionGranted bool
4762
4863 // Animation state for pending tool calls
4964 spinning bool // Whether to show loading animation
@@ -81,9 +96,21 @@ func WithToolCallNestedCalls(calls []ToolCallCmp) ToolCallOption {
8196 }
8297}
8398
99+func WithToolPermissionRequested() ToolCallOption {
100+ return func(m *toolCallCmp) {
101+ m.permissionRequested = true
102+ }
103+}
104+
105+func WithToolPermissionGranted() ToolCallOption {
106+ return func(m *toolCallCmp) {
107+ m.permissionGranted = true
108+ }
109+}
110+
84111// NewToolCallCmp creates a new tool call component with the given parent message ID,
85112// tool call, and optional configuration
86−func NewToolCallCmp(parentMessageID string, tc message.ToolCall, opts ...ToolCallOption) ToolCallCmp {
113+func NewToolCallCmp(parentMessageID string, tc message.ToolCall, permissions permission.Service, opts ...ToolCallOption) ToolCallCmp {
87114 m := &toolCallCmp{
88115 call: tc,
89116 parentMessageID: parentMessageID,
@@ -137,6 +164,10 @@ func (m *toolCallCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
137164 cmds = append(cmds, cmd)
138165 }
139166 return m, tea.Batch(cmds...)
167+ case tea.KeyPressMsg:
168+ if key.Matches(msg, copyKey) {
169+ return m, m.copyTool()
170+ }
140171 }
141172 return m, nil
142173}
@@ -165,6 +196,456 @@ func (m *toolCallCmp) SetCancelled() {
165196 m.cancelled = true
166197}
167198
199+func (m *toolCallCmp) copyTool() tea.Cmd {
200+ content := m.formatToolForCopy()
201+ err := clipboard.WriteAll(content)
202+ if err != nil {
203+ return util.ReportError(fmt.Errorf("failed to copy tool content to clipboard: %w", err))
204+ }
205+ return util.ReportInfo("Tool content copied to clipboard")
206+}
207+
208+func (m *toolCallCmp) formatToolForCopy() string {
209+ var parts []string
210+
211+ toolName := prettifyToolName(m.call.Name)
212+ parts = append(parts, fmt.Sprintf("## %s Tool Call", toolName))
213+
214+ if m.call.Input != "" {
215+ params := m.formatParametersForCopy()
216+ if params != "" {
217+ parts = append(parts, "### Parameters:")
218+ parts = append(parts, params)
219+ }
220+ }
221+
222+ if m.result.ToolCallID != "" {
223+ if m.result.IsError {
224+ parts = append(parts, "### Error:")
225+ parts = append(parts, m.result.Content)
226+ } else {
227+ parts = append(parts, "### Result:")
228+ content := m.formatResultForCopy()
229+ if content != "" {
230+ parts = append(parts, content)
231+ }
232+ }
233+ } else if m.cancelled {
234+ parts = append(parts, "### Status:")
235+ parts = append(parts, "Cancelled")
236+ } else {
237+ parts = append(parts, "### Status:")
238+ parts = append(parts, "Pending...")
239+ }
240+
241+ return strings.Join(parts, "\n\n")
242+}
243+
244+func (m *toolCallCmp) formatParametersForCopy() string {
245+ switch m.call.Name {
246+ case tools.BashToolName:
247+ var params tools.BashParams
248+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
249+ cmd := strings.ReplaceAll(params.Command, "\n", " ")
250+ cmd = strings.ReplaceAll(cmd, "\t", " ")
251+ return fmt.Sprintf("**Command:** %s", cmd)
252+ }
253+ case tools.ViewToolName:
254+ var params tools.ViewParams
255+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
256+ var parts []string
257+ parts = append(parts, fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath)))
258+ if params.Limit > 0 {
259+ parts = append(parts, fmt.Sprintf("**Limit:** %d", params.Limit))
260+ }
261+ if params.Offset > 0 {
262+ parts = append(parts, fmt.Sprintf("**Offset:** %d", params.Offset))
263+ }
264+ return strings.Join(parts, "\n")
265+ }
266+ case tools.EditToolName:
267+ var params tools.EditParams
268+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
269+ return fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath))
270+ }
271+ case tools.MultiEditToolName:
272+ var params tools.MultiEditParams
273+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
274+ var parts []string
275+ parts = append(parts, fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath)))
276+ parts = append(parts, fmt.Sprintf("**Edits:** %d", len(params.Edits)))
277+ return strings.Join(parts, "\n")
278+ }
279+ case tools.WriteToolName:
280+ var params tools.WriteParams
281+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
282+ return fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath))
283+ }
284+ case tools.FetchToolName:
285+ var params tools.FetchParams
286+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
287+ var parts []string
288+ parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
289+ if params.Format != "" {
290+ parts = append(parts, fmt.Sprintf("**Format:** %s", params.Format))
291+ }
292+ if params.Timeout > 0 {
293+ parts = append(parts, fmt.Sprintf("**Timeout:** %s", (time.Duration(params.Timeout)*time.Second).String()))
294+ }
295+ return strings.Join(parts, "\n")
296+ }
297+ case tools.GrepToolName:
298+ var params tools.GrepParams
299+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
300+ var parts []string
301+ parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
302+ if params.Path != "" {
303+ parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
304+ }
305+ if params.Include != "" {
306+ parts = append(parts, fmt.Sprintf("**Include:** %s", params.Include))
307+ }
308+ if params.LiteralText {
309+ parts = append(parts, "**Literal:** true")
310+ }
311+ return strings.Join(parts, "\n")
312+ }
313+ case tools.GlobToolName:
314+ var params tools.GlobParams
315+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
316+ var parts []string
317+ parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
318+ if params.Path != "" {
319+ parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
320+ }
321+ return strings.Join(parts, "\n")
322+ }
323+ case tools.LSToolName:
324+ var params tools.LSParams
325+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
326+ path := params.Path
327+ if path == "" {
328+ path = "."
329+ }
330+ return fmt.Sprintf("**Path:** %s", fsext.PrettyPath(path))
331+ }
332+ case tools.DownloadToolName:
333+ var params tools.DownloadParams
334+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
335+ var parts []string
336+ parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
337+ parts = append(parts, fmt.Sprintf("**File Path:** %s", fsext.PrettyPath(params.FilePath)))
338+ if params.Timeout > 0 {
339+ parts = append(parts, fmt.Sprintf("**Timeout:** %s", (time.Duration(params.Timeout)*time.Second).String()))
340+ }
341+ return strings.Join(parts, "\n")
342+ }
343+ case tools.SourcegraphToolName:
344+ var params tools.SourcegraphParams
345+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
346+ var parts []string
347+ parts = append(parts, fmt.Sprintf("**Query:** %s", params.Query))
348+ if params.Count > 0 {
349+ parts = append(parts, fmt.Sprintf("**Count:** %d", params.Count))
350+ }
351+ if params.ContextWindow > 0 {
352+ parts = append(parts, fmt.Sprintf("**Context:** %d", params.ContextWindow))
353+ }
354+ return strings.Join(parts, "\n")
355+ }
356+ case tools.DiagnosticsToolName:
357+ return "**Project:** diagnostics"
358+ case agent.AgentToolName:
359+ var params agent.AgentParams
360+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
361+ return fmt.Sprintf("**Task:**\n%s", params.Prompt)
362+ }
363+ }
364+
365+ var params map[string]any
366+ if json.Unmarshal([]byte(m.call.Input), &params) == nil {
367+ var parts []string
368+ for key, value := range params {
369+ displayKey := strings.ReplaceAll(key, "_", " ")
370+ if len(displayKey) > 0 {
371+ displayKey = strings.ToUpper(displayKey[:1]) + displayKey[1:]
372+ }
373+ parts = append(parts, fmt.Sprintf("**%s:** %v", displayKey, value))
374+ }
375+ return strings.Join(parts, "\n")
376+ }
377+
378+ return ""
379+}
380+
381+func (m *toolCallCmp) formatResultForCopy() string {
382+ switch m.call.Name {
383+ case tools.BashToolName:
384+ return m.formatBashResultForCopy()
385+ case tools.ViewToolName:
386+ return m.formatViewResultForCopy()
387+ case tools.EditToolName:
388+ return m.formatEditResultForCopy()
389+ case tools.MultiEditToolName:
390+ return m.formatMultiEditResultForCopy()
391+ case tools.WriteToolName:
392+ return m.formatWriteResultForCopy()
393+ case tools.FetchToolName:
394+ return m.formatFetchResultForCopy()
395+ case agent.AgentToolName:
396+ return m.formatAgentResultForCopy()
397+ case tools.DownloadToolName, tools.GrepToolName, tools.GlobToolName, tools.LSToolName, tools.SourcegraphToolName, tools.DiagnosticsToolName:
398+ return fmt.Sprintf("```\n%s\n```", m.result.Content)
399+ default:
400+ return m.result.Content
401+ }
402+}
403+
404+func (m *toolCallCmp) formatBashResultForCopy() string {
405+ var meta tools.BashResponseMetadata
406+ if m.result.Metadata != "" {
407+ json.Unmarshal([]byte(m.result.Metadata), &meta)
408+ }
409+
410+ output := meta.Output
411+ if output == "" && m.result.Content != tools.BashNoOutput {
412+ output = m.result.Content
413+ }
414+
415+ if output == "" {
416+ return ""
417+ }
418+
419+ return fmt.Sprintf("```bash\n%s\n```", output)
420+}
421+
422+func (m *toolCallCmp) formatViewResultForCopy() string {
423+ var meta tools.ViewResponseMetadata
424+ if m.result.Metadata != "" {
425+ json.Unmarshal([]byte(m.result.Metadata), &meta)
426+ }
427+
428+ if meta.Content == "" {
429+ return m.result.Content
430+ }
431+
432+ lang := ""
433+ if meta.FilePath != "" {
434+ ext := strings.ToLower(filepath.Ext(meta.FilePath))
435+ switch ext {
436+ case ".go":
437+ lang = "go"
438+ case ".js", ".mjs":
439+ lang = "javascript"
440+ case ".ts":
441+ lang = "typescript"
442+ case ".py":
443+ lang = "python"
444+ case ".rs":
445+ lang = "rust"
446+ case ".java":
447+ lang = "java"
448+ case ".c":
449+ lang = "c"
450+ case ".cpp", ".cc", ".cxx":
451+ lang = "cpp"
452+ case ".sh", ".bash":
453+ lang = "bash"
454+ case ".json":
455+ lang = "json"
456+ case ".yaml", ".yml":
457+ lang = "yaml"
458+ case ".xml":
459+ lang = "xml"
460+ case ".html":
461+ lang = "html"
462+ case ".css":
463+ lang = "css"
464+ case ".md":
465+ lang = "markdown"
466+ }
467+ }
468+
469+ var result strings.Builder
470+ if lang != "" {
471+ result.WriteString(fmt.Sprintf("```%s\n", lang))
472+ } else {
473+ result.WriteString("```\n")
474+ }
475+ result.WriteString(meta.Content)
476+ result.WriteString("\n```")
477+
478+ return result.String()
479+}
480+
481+func (m *toolCallCmp) formatEditResultForCopy() string {
482+ var meta tools.EditResponseMetadata
483+ if m.result.Metadata == "" {
484+ return m.result.Content
485+ }
486+
487+ if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
488+ return m.result.Content
489+ }
490+
491+ var params tools.EditParams
492+ json.Unmarshal([]byte(m.call.Input), &params)
493+
494+ var result strings.Builder
495+
496+ if meta.OldContent != "" || meta.NewContent != "" {
497+ fileName := params.FilePath
498+ if fileName != "" {
499+ fileName = fsext.PrettyPath(fileName)
500+ }
501+ diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
502+
503+ result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
504+ result.WriteString("```diff\n")
505+ result.WriteString(diffContent)
506+ result.WriteString("\n```")
507+ }
508+
509+ return result.String()
510+}
511+
512+func (m *toolCallCmp) formatMultiEditResultForCopy() string {
513+ var meta tools.MultiEditResponseMetadata
514+ if m.result.Metadata == "" {
515+ return m.result.Content
516+ }
517+
518+ if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
519+ return m.result.Content
520+ }
521+
522+ var params tools.MultiEditParams
523+ json.Unmarshal([]byte(m.call.Input), &params)
524+
525+ var result strings.Builder
526+ if meta.OldContent != "" || meta.NewContent != "" {
527+ fileName := params.FilePath
528+ if fileName != "" {
529+ fileName = fsext.PrettyPath(fileName)
530+ }
531+ diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
532+
533+ result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
534+ result.WriteString("```diff\n")
535+ result.WriteString(diffContent)
536+ result.WriteString("\n```")
537+ }
538+
539+ return result.String()
540+}
541+
542+func (m *toolCallCmp) formatWriteResultForCopy() string {
543+ var params tools.WriteParams
544+ if json.Unmarshal([]byte(m.call.Input), &params) != nil {
545+ return m.result.Content
546+ }
547+
548+ lang := ""
549+ if params.FilePath != "" {
550+ ext := strings.ToLower(filepath.Ext(params.FilePath))
551+ switch ext {
552+ case ".go":
553+ lang = "go"
554+ case ".js", ".mjs":
555+ lang = "javascript"
556+ case ".ts":
557+ lang = "typescript"
558+ case ".py":
559+ lang = "python"
560+ case ".rs":
561+ lang = "rust"
562+ case ".java":
563+ lang = "java"
564+ case ".c":
565+ lang = "c"
566+ case ".cpp", ".cc", ".cxx":
567+ lang = "cpp"
568+ case ".sh", ".bash":
569+ lang = "bash"
570+ case ".json":
571+ lang = "json"
572+ case ".yaml", ".yml":
573+ lang = "yaml"
574+ case ".xml":
575+ lang = "xml"
576+ case ".html":
577+ lang = "html"
578+ case ".css":
579+ lang = "css"
580+ case ".md":
581+ lang = "markdown"
582+ }
583+ }
584+
585+ var result strings.Builder
586+ result.WriteString(fmt.Sprintf("File: %s\n", fsext.PrettyPath(params.FilePath)))
587+ if lang != "" {
588+ result.WriteString(fmt.Sprintf("```%s\n", lang))
589+ } else {
590+ result.WriteString("```\n")
591+ }
592+ result.WriteString(params.Content)
593+ result.WriteString("\n```")
594+
595+ return result.String()
596+}
597+
598+func (m *toolCallCmp) formatFetchResultForCopy() string {
599+ var params tools.FetchParams
600+ if json.Unmarshal([]byte(m.call.Input), &params) != nil {
601+ return m.result.Content
602+ }
603+
604+ var result strings.Builder
605+ if params.URL != "" {
606+ result.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
607+ }
608+
609+ switch params.Format {
610+ case "html":
611+ result.WriteString("```html\n")
612+ case "text":
613+ result.WriteString("```\n")
614+ default: // markdown
615+ result.WriteString("```markdown\n")
616+ }
617+ result.WriteString(m.result.Content)
618+ result.WriteString("\n```")
619+
620+ return result.String()
621+}
622+
623+func (m *toolCallCmp) formatAgentResultForCopy() string {
624+ var result strings.Builder
625+
626+ if len(m.nestedToolCalls) > 0 {
627+ result.WriteString("### Nested Tool Calls:\n")
628+ for i, nestedCall := range m.nestedToolCalls {
629+ nestedContent := nestedCall.(*toolCallCmp).formatToolForCopy()
630+ indentedContent := strings.ReplaceAll(nestedContent, "\n", "\n ")
631+ result.WriteString(fmt.Sprintf("%d. %s\n", i+1, indentedContent))
632+ if i < len(m.nestedToolCalls)-1 {
633+ result.WriteString("\n")
634+ }
635+ }
636+
637+ if m.result.Content != "" {
638+ result.WriteString("\n### Final Result:\n")
639+ }
640+ }
641+
642+ if m.result.Content != "" {
643+ result.WriteString(fmt.Sprintf("```markdown\n%s\n```", m.result.Content))
644+ }
645+
646+ return result.String()
647+}
648+
168649// SetToolCall updates the tool call data and stops spinning if finished
169650func (m *toolCallCmp) SetToolCall(call message.ToolCall) {
170651 m.call = call
@@ -316,3 +797,13 @@ func (m *toolCallCmp) Spinning() bool {
316797func (m *toolCallCmp) ID() string {
317798 return m.call.ID
318799}
800+
801+// SetPermissionRequested marks that a permission request was made for this tool call
802+func (m *toolCallCmp) SetPermissionRequested() {
803+ m.permissionRequested = true
804+}
805+
806+// SetPermissionGranted marks that permission was granted for this tool call
807+func (m *toolCallCmp) SetPermissionGranted() {
808+ m.permissionGranted = true
809+}
internal/tui/components/chat/splash/splash.go+20
@@ -562,6 +562,8 @@ func (s *splashCmp) infoSection() string {
562562 lipgloss.Left,
563563 s.cwd(),
564564 "",
565+ s.currentModelBlock(),
566+ "",
565567 lipgloss.JoinHorizontal(lipgloss.Left, s.lspBlock(), s.mcpBlock()),
566568 "",
567569 ),
@@ -740,6 +742,24 @@ func (s *splashCmp) mcpBlock() string {
740742 )
741743}
742744
745+func (s *splashCmp) currentModelBlock() string {
746+ cfg := config.Get()
747+ agentCfg := cfg.Agents["coder"]
748+ model := config.Get().GetModelByType(agentCfg.Model)
749+ t := styles.CurrentTheme()
750+ modelIcon := t.S().Base.Foreground(t.FgSubtle).Render(styles.ModelIcon)
751+ modelName := t.S().Text.Render(model.Name)
752+ modelInfo := fmt.Sprintf("%s %s", modelIcon, modelName)
753+ parts := []string{
754+ modelInfo,
755+ }
756+
757+ return lipgloss.JoinVertical(
758+ lipgloss.Left,
759+ parts...,
760+ )
761+}
762+
743763func (s *splashCmp) IsShowingAPIKey() bool {
744764 return s.needsAPIKey
745765}
internal/tui/components/core/status/status.go+10−3
@@ -7,6 +7,7 @@ import (
77 tea "github.com/charmbracelet/bubbletea/v2"
88 "github.com/charmbracelet/crush/internal/tui/styles"
99 "github.com/charmbracelet/crush/internal/tui/util"
10+ "github.com/charmbracelet/lipgloss/v2"
1011 "github.com/charmbracelet/x/ansi"
1112)
1213
@@ -72,13 +73,19 @@ func (m *statusCmp) infoMsg() string {
7273 switch m.info.Type {
7374 case util.InfoTypeError:
7475 infoType = t.S().Base.Background(t.Red).Padding(0, 1).Render("ERROR")
75− message = t.S().Base.Background(t.Error).Width(m.width).Foreground(t.White).Padding(0, 1).Render(m.info.Msg)
76+ widthLeft := m.width - (lipgloss.Width(infoType) + 2)
77+ info := ansi.Truncate(m.info.Msg, widthLeft, "…")
78+ message = t.S().Base.Background(t.Error).Width(widthLeft+2).Foreground(t.White).Padding(0, 1).Render(info)
7679 case util.InfoTypeWarn:
7780 infoType = t.S().Base.Foreground(t.BgOverlay).Background(t.Yellow).Padding(0, 1).Render("WARNING")
78− message = t.S().Base.Foreground(t.BgOverlay).Width(m.width).Background(t.Warning).Padding(0, 1).Render(m.info.Msg)
81+ widthLeft := m.width - (lipgloss.Width(infoType) + 2)
82+ info := ansi.Truncate(m.info.Msg, widthLeft, "…")
83+ message = t.S().Base.Foreground(t.BgOverlay).Width(widthLeft+2).Background(t.Warning).Padding(0, 1).Render(info)
7984 default:
8085 infoType = t.S().Base.Foreground(t.BgOverlay).Background(t.Green).Padding(0, 1).Render("OKAY!")
81− message = t.S().Base.Background(t.Success).Width(m.width).Foreground(t.White).Padding(0, 1).Render(m.info.Msg)
86+ widthLeft := m.width - (lipgloss.Width(infoType) + 2)
87+ info := ansi.Truncate(m.info.Msg, widthLeft, "…")
88+ message = t.S().Base.Background(t.Success).Width(widthLeft+2).Foreground(t.White).Padding(0, 1).Render(info)
8289 }
8390 return ansi.Truncate(infoType+message, m.width, "…")
8491}
internal/tui/components/dialogs/commands/commands.go+61−15
@@ -59,7 +59,11 @@ type commandDialogCmp struct {
5959
6060type (
6161 SwitchSessionsMsg struct{}
62+ NewSessionsMsg struct{}
6263 SwitchModelMsg struct{}
64+ QuitMsg struct{}
65+ OpenFilePickerMsg struct{}
66+ ToggleHelpMsg struct{}
6367 ToggleCompactModeMsg struct{}
6468 ToggleThinkingMsg struct{}
6569 CompactMsg struct {
@@ -248,13 +252,29 @@ func (c *commandDialogCmp) Position() (int, int) {
248252func (c *commandDialogCmp) defaultCommands() []Command {
249253 commands := []Command{
250254 {
251− ID: "init",
252− Title: "Initialize Project",
253− Description: "Create/Update the CRUSH.md memory file",
255+ ID: "new_session",
256+ Title: "New Session",
257+ Description: "start a new session",
258+ Shortcut: "ctrl+n",
254259 Handler: func(cmd Command) tea.Cmd {
255− return util.CmdHandler(chat.SendMsg{
256− Text: prompt.Initialize(),
257− })
260+ return util.CmdHandler(NewSessionsMsg{})
261+ },
262+ },
263+ {
264+ ID: "switch_session",
265+ Title: "Switch Session",
266+ Description: "Switch to a different session",
267+ Shortcut: "ctrl+s",
268+ Handler: func(cmd Command) tea.Cmd {
269+ return util.CmdHandler(SwitchSessionsMsg{})
270+ },
271+ },
272+ {
273+ ID: "switch_model",
274+ Title: "Switch Model",
275+ Description: "Switch to a different model",
276+ Handler: func(cmd Command) tea.Cmd {
277+ return util.CmdHandler(SwitchModelMsg{})
258278 },
259279 },
260280 }
@@ -307,23 +327,49 @@ func (c *commandDialogCmp) defaultCommands() []Command {
307327 },
308328 })
309329 }
330+ if c.sessionID != "" {
331+ agentCfg := config.Get().Agents["coder"]
332+ model := config.Get().GetModelByType(agentCfg.Model)
333+ if model.SupportsImages {
334+ commands = append(commands, Command{
335+ ID: "file_picker",
336+ Title: "Open File Picker",
337+ Shortcut: "ctrl+f",
338+ Description: "Open file picker",
339+ Handler: func(cmd Command) tea.Cmd {
340+ return util.CmdHandler(OpenFilePickerMsg{})
341+ },
342+ })
343+ }
344+ }
310345
311346 return append(commands, []Command{
312347 {
313− ID: "switch_session",
314− Title: "Switch Session",
315− Description: "Switch to a different session",
316− Shortcut: "ctrl+s",
348+ ID: "toggle_help",
349+ Title: "Toggle Help",
350+ Shortcut: "ctrl+g",
351+ Description: "Toggle help",
317352 Handler: func(cmd Command) tea.Cmd {
318− return util.CmdHandler(SwitchSessionsMsg{})
353+ return util.CmdHandler(ToggleHelpMsg{})
319354 },
320355 },
321356 {
322− ID: "switch_model",
323− Title: "Switch Model",
324− Description: "Switch to a different model",
357+ ID: "init",
358+ Title: "Initialize Project",
359+ Description: "Create/Update the CRUSH.md memory file",
325360 Handler: func(cmd Command) tea.Cmd {
326− return util.CmdHandler(SwitchModelMsg{})
361+ return util.CmdHandler(chat.SendMsg{
362+ Text: prompt.Initialize(),
363+ })
364+ },
365+ },
366+ {
367+ ID: "quit",
368+ Title: "Quit",
369+ Description: "Quit",
370+ Shortcut: "ctrl+c",
371+ Handler: func(cmd Command) tea.Cmd {
372+ return util.CmdHandler(QuitMsg{})
327373 },
328374 },
329375 }...)
internal/tui/components/dialogs/filepicker/filepicker.go+6−4
@@ -21,7 +21,7 @@ import (
2121)
2222
2323const (
24− maxAttachmentSize = int64(5 * 1024 * 1024) // 5MB
24+ MaxAttachmentSize = int64(5 * 1024 * 1024) // 5MB
2525 FilePickerID = "filepicker"
2626 fileSelectionHight = 10
2727)
@@ -45,10 +45,12 @@ type model struct {
4545 help help.Model
4646}
4747
48+var AllowedTypes = []string{".jpg", ".jpeg", ".png"}
49+
4850func NewFilePickerCmp(workingDir string) FilePicker {
4951 t := styles.CurrentTheme()
5052 fp := filepicker.New()
51− fp.AllowedTypes = []string{".jpg", ".jpeg", ".png"}
53+ fp.AllowedTypes = AllowedTypes
5254
5355 if workingDir != "" {
5456 fp.CurrentDirectory = workingDir
@@ -127,7 +129,7 @@ func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
127129 return m, tea.Sequence(
128130 util.CmdHandler(dialogs.CloseDialogMsg{}),
129131 func() tea.Msg {
130− isFileLarge, err := ValidateFileSize(path, maxAttachmentSize)
132+ isFileLarge, err := IsFileTooBig(path, MaxAttachmentSize)
131133 if err != nil {
132134 return util.ReportError(fmt.Errorf("unable to read the image: %w", err))
133135 }
@@ -222,7 +224,7 @@ func (m *model) Position() (int, int) {
222224 return row, col
223225}
224226
225−func ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {
227+func IsFileTooBig(filePath string, sizeLimit int64) (bool, error) {
226228 fileInfo, err := os.Stat(filePath)
227229 if err != nil {
228230 return false, fmt.Errorf("error getting file info: %w", err)
internal/tui/components/dialogs/permissions/permissions.go+42−1
@@ -84,7 +84,7 @@ func (p *permissionDialogCmp) Init() tea.Cmd {
8484}
8585
8686func (p *permissionDialogCmp) supportsDiffView() bool {
87− return p.permission.ToolName == tools.EditToolName || p.permission.ToolName == tools.WriteToolName
87+ return p.permission.ToolName == tools.EditToolName || p.permission.ToolName == tools.WriteToolName || p.permission.ToolName == tools.MultiEditToolName
8888}
8989
9090func (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
@@ -305,6 +305,20 @@ func (p *permissionDialogCmp) renderHeader() string {
305305 ),
306306 baseStyle.Render(strings.Repeat(" ", p.width)),
307307 )
308+ case tools.MultiEditToolName:
309+ params := p.permission.Params.(tools.MultiEditPermissionsParams)
310+ fileKey := t.S().Muted.Render("File")
311+ filePath := t.S().Text.
312+ Width(p.width - lipgloss.Width(fileKey)).
313+ Render(fmt.Sprintf(" %s", fsext.PrettyPath(params.FilePath)))
314+ headerParts = append(headerParts,
315+ lipgloss.JoinHorizontal(
316+ lipgloss.Left,
317+ fileKey,
318+ filePath,
319+ ),
320+ baseStyle.Render(strings.Repeat(" ", p.width)),
321+ )
308322 case tools.FetchToolName:
309323 headerParts = append(headerParts, t.S().Muted.Width(p.width).Bold(true).Render("URL"))
310324 }
@@ -329,6 +343,8 @@ func (p *permissionDialogCmp) getOrGenerateContent() string {
329343 content = p.generateEditContent()
330344 case tools.WriteToolName:
331345 content = p.generateWriteContent()
346+ case tools.MultiEditToolName:
347+ content = p.generateMultiEditContent()
332348 case tools.FetchToolName:
333349 content = p.generateFetchContent()
334350 default:
@@ -435,6 +451,28 @@ func (p *permissionDialogCmp) generateDownloadContent() string {
435451 return ""
436452}
437453
454+func (p *permissionDialogCmp) generateMultiEditContent() string {
455+ if pr, ok := p.permission.Params.(tools.MultiEditPermissionsParams); ok {
456+ // Use the cache for diff rendering
457+ formatter := core.DiffFormatter().
458+ Before(fsext.PrettyPath(pr.FilePath), pr.OldContent).
459+ After(fsext.PrettyPath(pr.FilePath), pr.NewContent).
460+ Height(p.contentViewPort.Height()).
461+ Width(p.contentViewPort.Width()).
462+ XOffset(p.diffXOffset).
463+ YOffset(p.diffYOffset)
464+ if p.useDiffSplitMode() {
465+ formatter = formatter.Split()
466+ } else {
467+ formatter = formatter.Unified()
468+ }
469+
470+ diff := formatter.String()
471+ return diff
472+ }
473+ return ""
474+}
475+
438476func (p *permissionDialogCmp) generateFetchContent() string {
439477 t := styles.CurrentTheme()
440478 baseStyle := t.S().Base.Background(t.BgSubtle)
@@ -579,6 +617,9 @@ func (p *permissionDialogCmp) SetSize() tea.Cmd {
579617 case tools.WriteToolName:
580618 p.width = int(float64(p.wWidth) * 0.8)
581619 p.height = int(float64(p.wHeight) * 0.8)
620+ case tools.MultiEditToolName:
621+ p.width = int(float64(p.wWidth) * 0.8)
622+ p.height = int(float64(p.wHeight) * 0.8)
582623 case tools.FetchToolName:
583624 p.width = int(float64(p.wWidth) * 0.8)
584625 p.height = int(float64(p.wHeight) * 0.3)
internal/tui/exp/list/filterable.go+1−1
@@ -94,7 +94,7 @@ func NewFilterableList[T FilterableItem](items []T, opts ...filterableListOption
9494 for _, opt := range opts {
9595 opt(f.filterableOptions)
9696 }
97− f.list = New[T](items, f.listOptions...).(*list[T])
97+ f.list = New(items, f.listOptions...).(*list[T])
9898
9999 f.updateKeyMaps()
100100 f.items = slices.Collect(f.list.items.Seq())
internal/tui/exp/list/list.go+12
@@ -236,6 +236,18 @@ func (l *list[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
236236 case key.Matches(msg, l.keyMap.Home):
237237 return l, l.GoToTop()
238238 }
239+ s := l.SelectedItem()
240+ if s == nil {
241+ return l, nil
242+ }
243+ item := *s
244+ var cmds []tea.Cmd
245+ updated, cmd := item.Update(msg)
246+ cmds = append(cmds, cmd)
247+ if u, ok := updated.(T); ok {
248+ cmds = append(cmds, l.UpdateItem(u.ID(), u))
249+ }
250+ return l, tea.Batch(cmds...)
239251 }
240252 }
241253 return l, nil
internal/tui/keys.go+5
@@ -8,6 +8,7 @@ type KeyMap struct {
88 Quit key.Binding
99 Help key.Binding
1010 Commands key.Binding
11+ Suspend key.Binding
1112 Sessions key.Binding
1213
1314 pageBindings []key.Binding
@@ -27,6 +28,10 @@ func DefaultKeyMap() KeyMap {
2728 key.WithKeys("ctrl+p"),
2829 key.WithHelp("ctrl+p", "commands"),
2930 ),
31+ Suspend: key.NewBinding(
32+ key.WithKeys("ctrl+z"),
33+ key.WithHelp("ctrl+z", "suspend"),
34+ ),
3035 Sessions: key.NewBinding(
3136 key.WithKeys("ctrl+s"),
3237 key.WithHelp("ctrl+s", "sessions"),
internal/tui/page/chat/chat.go+24−3
@@ -12,6 +12,7 @@ import (
1212 "github.com/charmbracelet/crush/internal/config"
1313 "github.com/charmbracelet/crush/internal/history"
1414 "github.com/charmbracelet/crush/internal/message"
15+ "github.com/charmbracelet/crush/internal/permission"
1516 "github.com/charmbracelet/crush/internal/pubsub"
1617 "github.com/charmbracelet/crush/internal/session"
1718 "github.com/charmbracelet/crush/internal/tui/components/anim"
@@ -36,8 +37,7 @@ import (
3637var ChatPageID page.PageID = "chat"
3738
3839type (
39− OpenFilePickerMsg struct{}
40− ChatFocusedMsg struct {
40+ ChatFocusedMsg struct {
4141 Focused bool
4242 }
4343 CancelTimerExpiredMsg struct{}
@@ -178,6 +178,10 @@ func (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
178178 case CancelTimerExpiredMsg:
179179 p.isCanceling = false
180180 return p, nil
181+ case editor.OpenEditorMsg:
182+ u, cmd := p.editor.Update(msg)
183+ p.editor = u.(editor.Editor)
184+ return p, cmd
181185 case chat.SendMsg:
182186 return p, p.sendMessage(msg.Text, msg.Attachments)
183187 case chat.SessionSelectedMsg:
@@ -253,6 +257,11 @@ func (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
253257 p.sidebar = u.(sidebar.Sidebar)
254258 cmds = append(cmds, cmd)
255259 return p, tea.Batch(cmds...)
260+ case pubsub.Event[permission.PermissionNotification]:
261+ u, cmd := p.chat.Update(msg)
262+ p.chat = u.(chat.MessageListCmp)
263+ cmds = append(cmds, cmd)
264+ return p, tea.Batch(cmds...)
256265
257266 case commands.CommandRunCustomMsg:
258267 if p.app.CoderAgent.IsBusy() {
@@ -278,15 +287,23 @@ func (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
278287 p.isProjectInit = false
279288 p.focusedPane = PanelTypeEditor
280289 return p, p.SetSize(p.width, p.height)
290+ case commands.NewSessionsMsg:
291+ if p.app.CoderAgent.IsBusy() {
292+ return p, util.ReportWarn("Agent is busy, please wait before starting a new session...")
293+ }
294+ return p, p.newSession()
281295 case tea.KeyPressMsg:
282296 switch {
283297 case key.Matches(msg, p.keyMap.NewSession):
298+ if p.app.CoderAgent.IsBusy() {
299+ return p, util.ReportWarn("Agent is busy, please wait before starting a new session...")
300+ }
284301 return p, p.newSession()
285302 case key.Matches(msg, p.keyMap.AddAttachment):
286303 agentCfg := config.Get().Agents["coder"]
287304 model := config.Get().GetModelByType(agentCfg.Model)
288305 if model.SupportsImages {
289− return p, util.CmdHandler(OpenFilePickerMsg{})
306+ return p, util.CmdHandler(commands.OpenFilePickerMsg{})
290307 } else {
291308 return p, util.ReportWarn("File attachments are not supported by the current model: " + model.Name)
292309 }
@@ -812,6 +829,10 @@ func (p *chatPage) Help() help.KeyMap {
812829 key.WithKeys("up", "down"),
813830 key.WithHelp("↑↓", "scroll"),
814831 ),
832+ key.NewBinding(
833+ key.WithKeys("c", "y"),
834+ key.WithHelp("c/y", "copy"),
835+ ),
815836 )
816837 fullList = append(fullList,
817838 []key.Binding{
internal/tui/tui.go+26−2
@@ -170,7 +170,14 @@ func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
170170 return a, util.CmdHandler(dialogs.OpenDialogMsg{
171171 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
172172 })
173−
173+ case commands.QuitMsg:
174+ return a, util.CmdHandler(dialogs.OpenDialogMsg{
175+ Model: quit.NewQuitDialog(),
176+ })
177+ case commands.ToggleHelpMsg:
178+ a.status.ToggleFullHelp()
179+ a.showingFullHelp = !a.showingFullHelp
180+ return a, a.handleWindowResize(a.wWidth, a.wHeight)
174181 // Model Switch
175182 case models.ModelSelectedMsg:
176183 config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
@@ -187,7 +194,7 @@ func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
187194 return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
188195
189196 // File Picker
190− case chat.OpenFilePickerMsg:
197+ case commands.OpenFilePickerMsg:
191198 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
192199 // If the commands dialog is already open, close it
193200 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
@@ -196,6 +203,11 @@ func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
196203 Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
197204 })
198205 // Permissions
206+ case pubsub.Event[permission.PermissionNotification]:
207+ // forward to page
208+ updated, cmd := a.pages[a.currentPage].Update(msg)
209+ a.pages[a.currentPage] = updated.(util.Model)
210+ return a, cmd
199211 case pubsub.Event[permission.PermissionRequest]:
200212 return a, util.CmdHandler(dialogs.OpenDialogMsg{
201213 Model: permissions.NewPermissionDialogCmp(msg.Payload),
@@ -248,6 +260,13 @@ func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
248260 case tea.KeyPressMsg:
249261 return a, a.handleKeyPressMsg(msg)
250262
263+ case tea.MouseWheelMsg:
264+ if !a.dialog.HasDialogs() {
265+ updated, pageCmd := a.pages[a.currentPage].Update(msg)
266+ a.pages[a.currentPage] = updated.(util.Model)
267+ cmds = append(cmds, pageCmd)
268+ }
269+ return a, tea.Batch(cmds...)
251270 case tea.PasteMsg:
252271 if a.dialog.HasDialogs() {
253272 u, dialogCmd := a.dialog.Update(msg)
@@ -370,6 +389,11 @@ func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
370389 },
371390 )
372391 return tea.Sequence(cmds...)
392+ case key.Matches(msg, a.keyMap.Suspend):
393+ if a.app.CoderAgent.IsBusy() {
394+ return util.ReportWarn("Agent is busy, please wait...")
395+ }
396+ return tea.Suspend
373397 default:
374398 if a.dialog.HasDialogs() {
375399 u, dialogCmd := a.dialog.Update(msg)