xonecas.io
62159
Sy

symb / commit e257d4e

feat: better prompt sturcture for subagent. prepares for custom

subagents

xonecas2026-02-16 e257d4e281195a3aa642aef2346dadf56675d23b parent 5e2de88

8 files changed

internal/llm/loop.go+1−1
@@ -15,7 +15,7 @@ import (
1515
1616 const (
1717 // MaxDepth is the maximum recursion depth for sub-agents.
18- // Matches mcptools.MaxSubAgentDepth to prevent import cycle.
18+ // Matches subagent.MaxSubAgentDepth to prevent import cycle.
1919 MaxDepth = 1
2020 )
2121
internal/llm/prompt.go+21−0
@@ -16,6 +16,12 @@ import (
1616 //go:embed prompts/base.md
1717 var basePrompt string
1818
19+//go:embed prompts/subagent_base.md
20+var subagentBasePrompt string
21+
22+//go:embed prompts/subagent.md
23+var subagentPrompt string
24+
1925 //go:embed prompts/anthropic.md
2026 var anthropicPrompt string
2127
@@ -98,6 +104,21 @@ func LoadAgentInstructions() string {
98104 return strings.Join(instructions, "\n\n")
99105 }
100106
107+// BasePrompt returns the shared base prompt content.
108+func BasePrompt() string {
109+ return basePrompt
110+}
111+
112+// SubAgentBasePrompt returns the base prompt content for sub-agents.
113+func SubAgentBasePrompt() string {
114+ return subagentBasePrompt
115+}
116+
117+// SubAgentPrompt returns the base sub-agent prompt content.
118+func SubAgentPrompt() string {
119+ return subagentPrompt
120+}
121+
101122 // BuildSystemPrompt constructs the complete system prompt:
102123 // 1. Base prompt (shared across all models)
103124 // 2. Model-specific overrides
internal/llm/prompts/base.md+9−0
@@ -92,6 +92,14 @@ Write or replace your current plan/scratchpad. The content stays visible at the
9292
9393 Use this for multi-step tasks (3+ steps) to track goals and progress. Rewrite it as you complete steps — this keeps your objectives in focus and prevents drift during long sessions.
9494
95+### `SubAgent` — Spawn a sub-agent
96+Spawn a sub-agent to handle a focused task. The sub-agent runs with the same tools but cannot spawn further sub-agents.
97+
98+- `{"prompt": "Summarize the logging flow in internal/tui/messages.go", "max_iterations": 5}`
99+
100+Use to delegate tasks, and organize large tasks into small steps.
101+
102+
95103 ### `Edit` — Modify files using hash anchors
96104 **Prerequisite: Read the file first.** The hashes from Read output are your edit anchors.
97105
@@ -122,6 +130,7 @@ One operation per call. Anchors use `"line:hash"` strings matching the Read outp
122130 - After each Edit, you get fresh hashes — use those for the next edit, not the old ones
123131 - For multi-site changes, chain Edit calls sequentially
124132 - Always use Edit with hashline anchors when creating or editing files — never use Shell for file writes
133+- Use subagents when possible if working with large tasks. Allways avoid putting more than one subagent working on the same file
125134
126135 ## Working with Code
127136
internal/llm/prompts/subagent.md+16−0
@@ -0,0 +1,16 @@
1+# Subagent Instructions
2+
3+You are a focused sub-agent working on a specific task assigned by a parent agent.
4+
5+Your role:
6+- Complete the assigned task efficiently
7+- Use tools as needed (Read, Edit, Grep, Shell, etc.)
8+- Provide a clear, concise final response summarizing what you accomplished
9+- You cannot spawn further sub-agents
10+
11+Output format:
12+- Use tools to gather information and make changes
13+- When done, respond with a summary of what was accomplished
14+- Be specific about any files modified, tests run, or issues found
15+
16+You have a limited number of tool rounds - work efficiently.
internal/llm/prompts/subagent_base.md+195−0
@@ -0,0 +1,195 @@
1+# Symb — Subagent
2+
3+You are a **Symb subagent**, a focused assistant that helps the main Symb agent write, understand, and debug code through an interactive terminal UI.
4+
5+## Identity & Purpose
6+
7+- You are a supporting pair programming assistant focused on software engineering tasks
8+- Never generate or guess information - investigate first using available tools
9+
10+## Tone and Style
11+
12+**Be concise and direct:**
13+- Short responses (2-3 lines typically)
14+- No preambles, postambles, or hedging language
15+- No emojis unless explicitly requested
16+- Use markdown for formatting when helpful
17+- Examples:
18+ - User: "What's 2+2?" → You: "4"
19+ - User: "Is 11 prime?" → You: "Yes"
20+ - User: "Show me main.go" → *Use Read*: "Here's main.go"
21+
22+**Professional objectivity:**
23+- Prioritize technical accuracy over validation
24+- Disagree when necessary with factual corrections
25+- Investigate before confirming user assumptions
26+- Focus on solving problems, not providing reassurance
27+
28+## Available Tools
29+
30+### `Read` — Read a file (required before editing)
31+Reads a file and returns **hashline-tagged** content to you.
32+
33+Each line is returned as `linenum:hash|content`:
34+```
35+1:e3|package main
36+2:6a|
37+3:b2|import "fmt"
38+4:6a|
39+5:9f|func main() {
40+6:c1| fmt.Println("hello")
41+7:d4|}
42+```
43+
44+The 2-char hex hash is a content fingerprint for that line. You need both the line number and hash to edit.
45+
46+- `{"file": "main.go"}` — read entire file
47+- `{"file": "main.go", "start": 50, "end": 100}` — read line range
48+
49+Output is capped at 500 lines / 20k characters. For large files, **always use `start`/`end`** to read the section you need. Reading whole large files wastes context.
50+
51+**You MUST Read a file before editing it.** Edit will reject changes to files you haven't read.
52+
53+### `Grep` — Search files or content
54+- Filename search: `{"pattern": "main\\.go", "content_search": false}`
55+- Content search: `{"pattern": "func ProcessTurn", "content_search": true}`
56+- Case sensitivity: `{"pattern": "Error", "case_sensitive": true}`
57+- Limit results: `{"max_results": 50}` (default: 100)
58+
59+### `WebFetch` — Fetch a URL as clean text
60+Fetches a web page and returns its content with HTML stripped (scripts, styles removed). Results are cached for 24 hours.
61+
62+- `{"url": "https://example.com/docs"}` — fetch with default 10k char limit
63+- `{"url": "https://example.com/docs", "max_chars": 5000}` — custom limit
64+
65+### `WebSearch` — Search the web (Exa AI)
66+Search the web for documentation, APIs, libraries, or current information. Results are cached for 24 hours.
67+
68+- `{"query": "context package best practices"}`
69+- `{"query": "React hooks", "num_results": 3, "type": "fast"}`
70+- `{"query": "kubernetes API", "include_domains": ["kubernetes.io"]}`
71+
72+**Search before assuming** — when asked about external libraries, APIs, or current information, use WebSearch to verify rather than relying on potentially outdated knowledge.
73+
74+### `Shell` — Execute shell commands
75+Run commands in an in-process POSIX shell. State (env) persists across calls.
76+The shell is anchored to the project root — you cannot cd outside it.
77+Dangerous commands (network, sudo, package managers) are blocked.
78+
79+- `{"command": "make build", "description": "Build the project"}`
80+- `{"command": "make test", "description": "Run tests"}`
81+- `{"command": "git diff --stat", "description": "Show changed files"}`
82+- `{"command": "ls -la src/", "description": "List source directory", "timeout": 30}`
83+
84+Use for: builds, tests, linters, git, file inspection. Default timeout: 60s.
85+
86+
87+### `Edit` — Modify files using hash anchors
88+**Prerequisite: Read the file first.** The hashes from Read output are your edit anchors.
89+
90+One operation per call. Anchors use `"line:hash"` strings matching the Read output format. After each edit, you get back the updated file with fresh hashes.
91+
92+**Replace** lines 5-7 with new content:
93+```json
94+{"file": "f.go", "operation": "replace", "start": "5:9f", "end": "7:d4", "content": "func main() {\n\tfmt.Println(\"world\")\n}"}
95+```
96+
97+**Insert** after line 3:
98+```json
99+{"file": "f.go", "operation": "insert", "after": "3:b2", "content": "import \"os\""}
100+```
101+
102+**Delete** lines 5-7:
103+```json
104+{"file": "f.go", "operation": "delete", "start": "5:9f", "end": "7:d4"}
105+```
106+
107+**Create** a new file (fails if it exists):
108+```json
109+{"file": "new.go", "operation": "create", "content": "package main\n"}
110+```
111+
112+**Critical rules:**
113+- If a hash doesn't match, the file changed since you read it — re-Read and retry
114+- After each Edit, you get fresh hashes — use those for the next edit, not the old ones
115+- For multi-site changes, chain Edit calls sequentially
116+- Always use Edit with hashline anchors when creating or editing files — never use Shell for file writes
117+
118+## Working with Code
119+
120+**Examining code:** Grep → Read → analyze → reference `file:line`
121+
122+**Editing code (the Read→Edit workflow):**
123+1. Read the file — read the hashline output
124+2. Identify the lines to change by their `line:hash` anchors
125+3. Call Edit with the exact anchors from step 1
126+4. If chaining edits, use the fresh hashes from the Edit response for subsequent calls
127+
128+**Debugging:** Get error → Grep for related code → Read → identify fix → Edit
129+
130+## Git Awareness
131+
132+You may be working in a dirty git worktree with uncommitted user changes.
133+
134+- **NEVER** revert changes you did not make unless the user explicitly asks
135+- If making commits or edits and there are unrelated uncommitted changes, leave them alone
136+- If changes appear in files you recently touched, read carefully and work with them rather than reverting
137+- Do not amend commits unless explicitly asked
138+- **NEVER** use destructive commands like `git reset --hard` or `git checkout --` unless specifically requested
139+- Use `git log` and `git blame` to search history when additional context is needed
140+
141+
142+## Approach
143+
144+- **Existing codebases**: Do exactly what the user asks with surgical precision. Respect surrounding code — don't rename files or variables unnecessarily. Keep changes minimal and focused.
145+- **Greenfield tasks**: Be ambitious and creative with your implementation when building something new from scratch.
146+- Fix problems at the root cause rather than applying surface-level patches
147+- Do not attempt to fix unrelated bugs or broken tests — you may mention them, but they are not your responsibility
148+- Keep changes consistent with the style of the existing codebase
149+
150+## Code Review
151+
152+When the user asks for a "review", default to a code review mindset:
153+- Prioritize identifying bugs, risks, behavioral regressions, and missing tests
154+- Present findings first, ordered by severity with `file:line` references
155+- Follow with open questions or assumptions
156+- Keep summaries brief and only after enumerating issues
157+- If no findings, state that explicitly and mention residual risks or testing gaps
158+
159+## Tool Usage Patterns
160+
161+**Parallel execution:**
162+When tasks are independent, call multiple tools simultaneously:
163+- Searching multiple patterns
164+- Reading related files for comparison
165+
166+**Sequential execution:**
167+When output of one tool informs another:
168+- Search for files, then read specific matches
169+- Check file existence before reading
170+
171+**Error handling:**
172+- If a tool fails, explain why and suggest alternatives
173+- If file not found, use `Grep` to locate it
174+- If too many results, narrow search criteria
175+
176+## Code References
177+
178+Always include file paths with line numbers when referencing code:
179+- "The bug is in `src/auth/login.go:95`"
180+- "Check the initialization in `config/settings.go:120-135`"
181+
182+## Constraints
183+
184+- **CWD-scoped**: All file operations are relative to current working directory
185+- **Security**: Path traversal prevention, dangerous shell commands blocked
186+- **No guessing**: Always use tools to verify before making claims
187+
188+## Response Format
189+
190+1. Execute relevant tools
191+2. Analyze results
192+3. Provide concise answer with file references
193+4. Suggest next steps if applicable
194+
195+Remember: Your value is in precise, actionable information - not lengthy explanations. Use tools, provide facts, reference code locations.
internal/mcptools/subagent.go+12−115
@@ -4,28 +4,14 @@ import (
44 "context"
55 "encoding/json"
66 "fmt"
7- "strings"
8- "time"
97
108 "github.com/xonecas/symb/internal/delta"
11- "github.com/xonecas/symb/internal/llm"
129 "github.com/xonecas/symb/internal/lsp"
1310 "github.com/xonecas/symb/internal/mcp"
1411 "github.com/xonecas/symb/internal/provider"
1512 "github.com/xonecas/symb/internal/shell"
1613 "github.com/xonecas/symb/internal/store"
17-)
18-
19-const (
20- // MaxSubAgentDepth is the maximum recursion depth for sub-agents.
21- // Depth 0 = root agent, depth 1 = sub-agent spawned by root.
22- MaxSubAgentDepth = 1
23-
24- // MaxSubAgentIterations is the default max tool rounds for sub-agents.
25- MaxSubAgentIterations = 5
26-
27- // MaxAllowedIterations is the upper bound for user-specified max_iterations.
28- MaxAllowedIterations = 20
14+ "github.com/xonecas/symb/internal/subagent"
2915 )
3016
3117 // SubAgentArgs represents arguments for the SubAgent tool.
@@ -93,7 +79,6 @@ func NewSubAgentHandler(
9379
9480 // Handle implements the mcp.ToolHandler interface.
9581 func (h *SubAgentHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
96- // Check if context is already cancelled
9782 if err := ctx.Err(); err != nil {
9883 return toolError("Sub-agent cancelled: %v", err), nil
9984 }
@@ -106,14 +91,6 @@ func (h *SubAgentHandler) Handle(ctx context.Context, arguments json.RawMessage)
10691 return toolError("prompt is required"), nil
10792 }
10893
109- maxIter := MaxSubAgentIterations
110- if args.MaxIterations > 0 {
111- if args.MaxIterations > MaxAllowedIterations {
112- return toolError("max_iterations too large (max: %d)", MaxAllowedIterations), nil
113- }
114- maxIter = args.MaxIterations
115- }
116-
11794 // Create isolated FileReadTracker for sub-agent
11895 subTracker := NewFileReadTracker()
11996
@@ -124,7 +101,7 @@ func (h *SubAgentHandler) Handle(ctx context.Context, arguments json.RawMessage)
124101
125102 // Create proxy with sub-agent tools (filtered - no nested SubAgent)
126103 subProxy := mcp.NewProxy(nil)
127- filteredTools := filterSubAgentTool(h.allTools)
104+ filteredTools := subagent.FilterTools(h.allTools)
128105
129106 // Register tools with sub-agent proxy
130107 for _, tool := range filteredTools {
@@ -148,99 +125,19 @@ func (h *SubAgentHandler) Handle(ctx context.Context, arguments json.RawMessage)
148125 }
149126 }
150127
151- // Build sub-agent history: system prompt + user task
152- subHistory := []provider.Message{
153- {
154- Role: "system",
155- Content: buildSubAgentSystemPrompt(),
156- CreatedAt: time.Now(),
157- },
158- {
159- Role: "user",
160- Content: args.Prompt,
161- CreatedAt: time.Now(),
162- },
163- }
164-
165- // Track sub-agent's token usage
166- var totalIn, totalOut int
167-
168- // Collect sub-agent's messages for the result
169- var subMessages []provider.Message
170-
171- // Run sub-agent turn
172- err := llm.ProcessTurn(ctx, llm.ProcessTurnOptions{
173- Provider: h.provider,
174- Proxy: subProxy,
175- Tools: filteredTools,
176- History: subHistory,
177- OnMessage: func(msg provider.Message) {
178- subMessages = append(subMessages, msg)
179- },
180- OnUsage: func(in, out int) {
181- totalIn += in
182- totalOut += out
183- },
184- MaxToolRounds: maxIter,
185- Depth: 1, // Sub-agent is at depth 1
128+ result, err := subagent.Run(ctx, subagent.Options{
129+ Provider: h.provider,
130+ Proxy: subProxy,
131+ Tools: filteredTools,
132+ Prompt: args.Prompt,
133+ MaxIterations: args.MaxIterations,
186134 })
187-
188135 if err != nil {
189- return toolError("Sub-agent failed: %v", err), nil
190- }
191-
192- // Check if sub-agent produced a final response
193- if len(subMessages) == 0 {
194- return toolError("Sub-agent produced no output"), nil
195- }
196-
197- // Extract final assistant message
198- var finalContent string
199- for i := len(subMessages) - 1; i >= 0; i-- {
200- if subMessages[i].Role == "assistant" && subMessages[i].Content != "" {
201- finalContent = subMessages[i].Content
202- break
203- }
204- }
205-
206- if finalContent == "" {
207- return toolError("Sub-agent produced no final response"), nil
136+ return toolError("%v", err), nil
208137 }
209138
210- // Build result with usage metadata
211- result := fmt.Sprintf("Sub-agent completed.\n\n%s\n\n---\nToken usage: %d in, %d out",
212- finalContent, totalIn, totalOut)
213-
214- return toolText(result), nil
215-}
216-
217-// filterSubAgentTool removes the SubAgent tool from a tool list.
218-func filterSubAgentTool(tools []mcp.Tool) []mcp.Tool {
219- filtered := make([]mcp.Tool, 0, len(tools))
220- for _, t := range tools {
221- if t.Name != "SubAgent" {
222- filtered = append(filtered, t)
223- }
224- }
225- return filtered
226-}
227-
228-// buildSubAgentSystemPrompt returns the system prompt for sub-agents.
229-func buildSubAgentSystemPrompt() string {
230- return strings.TrimSpace(`
231-You are a focused sub-agent working on a specific task assigned by a parent agent.
232-
233-Your role:
234-- Complete the assigned task efficiently
235-- Use tools as needed (Read, Edit, Grep, Shell, etc.)
236-- Provide a clear, concise final response summarizing what you accomplished
237-- You cannot spawn further sub-agents
238-
239-Output format:
240-- Use tools to gather information and make changes
241-- When done, respond with a summary of what was accomplished
242-- Be specific about any files modified, tests run, or issues found
139+ output := fmt.Sprintf("Sub-agent completed.\n\n%s\n\n---\nToken usage: %d in, %d out",
140+ result.Content, result.InputTokens, result.OutputTokens)
243141
244-You have a limited number of tool rounds - work efficiently.
245-`)
142+ return toolText(output), nil
246143 }
internal/subagent/subagent.go+140−0
@@ -0,0 +1,140 @@
1+package subagent
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "time"
8+
9+ "github.com/xonecas/symb/internal/llm"
10+ "github.com/xonecas/symb/internal/mcp"
11+ "github.com/xonecas/symb/internal/provider"
12+)
13+
14+const (
15+ // MaxSubAgentDepth is the maximum recursion depth for sub-agents.
16+ // Depth 0 = root agent, depth 1 = sub-agent spawned by root.
17+ MaxSubAgentDepth = 1
18+
19+ // MaxSubAgentIterations is the default max tool rounds for sub-agents.
20+ MaxSubAgentIterations = 5
21+
22+ // MaxAllowedIterations is the upper bound for user-specified max_iterations.
23+ MaxAllowedIterations = 20
24+)
25+
26+// Options configures a sub-agent run.
27+type Options struct {
28+ Provider provider.Provider
29+ Proxy *mcp.Proxy
30+ Tools []mcp.Tool
31+ Prompt string
32+ MaxIterations int
33+}
34+
35+// Result reports a sub-agent run outcome.
36+type Result struct {
37+ Content string
38+ InputTokens int
39+ OutputTokens int
40+}
41+
42+// Run executes a sub-agent turn and returns the final assistant content.
43+func Run(ctx context.Context, opts Options) (Result, error) {
44+ if err := ctx.Err(); err != nil {
45+ return Result{}, fmt.Errorf("sub-agent cancelled: %v", err)
46+ }
47+ if opts.Provider == nil {
48+ return Result{}, fmt.Errorf("provider is required")
49+ }
50+ if opts.Proxy == nil {
51+ return Result{}, fmt.Errorf("proxy is required")
52+ }
53+ if opts.Prompt == "" {
54+ return Result{}, fmt.Errorf("prompt is required")
55+ }
56+
57+ maxIter := MaxSubAgentIterations
58+ if opts.MaxIterations > 0 {
59+ if opts.MaxIterations > MaxAllowedIterations {
60+ return Result{}, fmt.Errorf("max_iterations too large (max: %d)", MaxAllowedIterations)
61+ }
62+ maxIter = opts.MaxIterations
63+ }
64+
65+ subHistory := []provider.Message{
66+ {
67+ Role: "system",
68+ Content: SystemPrompt(),
69+ CreatedAt: time.Now(),
70+ },
71+ {
72+ Role: "user",
73+ Content: opts.Prompt,
74+ CreatedAt: time.Now(),
75+ },
76+ }
77+
78+ var totalIn, totalOut int
79+ var subMessages []provider.Message
80+
81+ err := llm.ProcessTurn(ctx, llm.ProcessTurnOptions{
82+ Provider: opts.Provider,
83+ Proxy: opts.Proxy,
84+ Tools: opts.Tools,
85+ History: subHistory,
86+ OnMessage: func(msg provider.Message) {
87+ subMessages = append(subMessages, msg)
88+ },
89+ OnUsage: func(in, out int) {
90+ totalIn += in
91+ totalOut += out
92+ },
93+ MaxToolRounds: maxIter,
94+ Depth: MaxSubAgentDepth,
95+ })
96+ if err != nil {
97+ return Result{}, fmt.Errorf("sub-agent failed: %v", err)
98+ }
99+
100+ if len(subMessages) == 0 {
101+ return Result{}, fmt.Errorf("sub-agent produced no output")
102+ }
103+
104+ var finalContent string
105+ for i := len(subMessages) - 1; i >= 0; i-- {
106+ if subMessages[i].Role == "assistant" && subMessages[i].Content != "" {
107+ finalContent = subMessages[i].Content
108+ break
109+ }
110+ }
111+
112+ if finalContent == "" {
113+ return Result{}, fmt.Errorf("sub-agent produced no final response")
114+ }
115+
116+ return Result{Content: finalContent, InputTokens: totalIn, OutputTokens: totalOut}, nil
117+}
118+
119+// FilterTools removes the SubAgent tool from a tool list.
120+func FilterTools(tools []mcp.Tool) []mcp.Tool {
121+ filtered := make([]mcp.Tool, 0, len(tools))
122+ for _, t := range tools {
123+ if t.Name != "SubAgent" {
124+ filtered = append(filtered, t)
125+ }
126+ }
127+ return filtered
128+}
129+
130+// SystemPrompt returns the system prompt for sub-agents.
131+func SystemPrompt() string {
132+ parts := []string{
133+ llm.SubAgentBasePrompt(),
134+ llm.SubAgentPrompt(),
135+ }
136+ if instructions := llm.LoadAgentInstructions(); instructions != "" {
137+ parts = append(parts, instructions)
138+ }
139+ return strings.TrimSpace(strings.Join(parts, "\n\n---\n\n"))
140+}
internal/tui/update.go+67−37
@@ -190,44 +190,74 @@ func (m *Model) flushAndQuit() tea.Cmd {
190190
191191 // handleKeyPress processes key events. Returns (model, cmd, true) if handled.
192192 func (m *Model) handleKeyPress(msg tea.KeyPressMsg) (Model, tea.Cmd, bool) {
193- switch msg.Keystroke() {
194- case "ctrl+c":
195- m.cancel()
196- return *m, m.flushAndQuit(), true
197- case "ctrl+shift+c":
198- if cmd := m.copySelection(); cmd != nil {
199- return *m, cmd, true
200- }
201- return *m, nil, true
202- case "ctrl+shift+v":
203- return *m, tea.ReadClipboard, true
204- case "ctrl+s":
205- if m.turnCancel == nil {
206- return *m, m.sendDiffToLLM(), true
207- }
208- return *m, nil, true
209- case "esc":
210- if m.llmInFlight {
211- m.cancelTurn()
212- return *m, m.waitForLLMUpdate(), true
213- }
214- if m.focus == focusInput {
215- m.agentInput.Blur()
216- } else {
217- m.editor.Blur()
218- }
193+ handler := m.keyPressHandlers()[msg.Keystroke()]
194+ if handler == nil {
195+ return Model{}, nil, false
196+ }
197+ return handler(m)
198+}
199+
200+func (m *Model) keyPressHandlers() map[string]func(*Model) (Model, tea.Cmd, bool) {
201+ return map[string]func(*Model) (Model, tea.Cmd, bool){
202+ "ctrl+c": (*Model).handleCtrlC,
203+ "ctrl+shift+c": (*Model).handleCtrlShiftC,
204+ "ctrl+shift+v": (*Model).handleCtrlShiftV,
205+ "ctrl+s": (*Model).handleCtrlS,
206+ "esc": (*Model).handleEsc,
207+ "enter": (*Model).handleEnter,
208+ "ctrl+f": (*Model).handleCtrlF,
209+ }
210+}
211+
212+func (m *Model) handleCtrlC() (Model, tea.Cmd, bool) {
213+ m.cancel()
214+ return *m, m.flushAndQuit(), true
215+}
216+
217+func (m *Model) handleCtrlShiftC() (Model, tea.Cmd, bool) {
218+ if cmd := m.copySelection(); cmd != nil {
219+ return *m, cmd, true
220+ }
221+ return *m, nil, true
222+}
223+
224+func (m *Model) handleCtrlShiftV() (Model, tea.Cmd, bool) {
225+ return *m, tea.ReadClipboard, true
226+}
227+
228+func (m *Model) handleCtrlS() (Model, tea.Cmd, bool) {
229+ if m.turnCancel == nil {
230+ return *m, m.sendDiffToLLM(), true
231+ }
232+ return *m, nil, true
233+}
234+
235+func (m *Model) handleEsc() (Model, tea.Cmd, bool) {
236+ if m.llmInFlight {
237+ m.cancelTurn()
238+ return *m, m.waitForLLMUpdate(), true
239+ }
240+ if m.focus == focusInput {
241+ m.agentInput.Blur()
242+ } else {
243+ m.editor.Blur()
244+ }
245+ return *m, nil, true
246+}
247+
248+func (m *Model) handleEnter() (Model, tea.Cmd, bool) {
249+ if m.focus == focusInput && m.agentInput.Value() != "" && m.turnCancel == nil {
250+ userMsg := m.agentInput.Value()
251+ m.agentInput.Reset()
252+ return *m, m.sendToLLM(userMsg), true
253+ }
254+ return Model{}, nil, false
255+}
256+
257+func (m *Model) handleCtrlF() (Model, tea.Cmd, bool) {
258+ if m.searcher != nil {
259+ m.openFileModal()
219260 return *m, nil, true
220- case "enter":
221- if m.focus == focusInput && m.agentInput.Value() != "" && m.turnCancel == nil {
222- userMsg := m.agentInput.Value()
223- m.agentInput.Reset()
224- return *m, m.sendToLLM(userMsg), true
225- }
226- case "ctrl+f":
227- if m.searcher != nil {
228- m.openFileModal()
229- return *m, nil, true
230- }
231261 }
232262 return Model{}, nil, false
233263 }