xonecas.io
62159
Sy

symb / commit 9d856f6

feat: shell tools, good luck everyone

xonecas2026-02-14 9d856f61b362a7054d66e8784705397fe216114e parent 2c756b5

13 files changed

cmd/symb/main.go+12−0
@@ -18,6 +18,7 @@ import (
1818 "github.com/xonecas/symb/internal/mcp"
1919 "github.com/xonecas/symb/internal/mcptools"
2020 "github.com/xonecas/symb/internal/provider"
21+ "github.com/xonecas/symb/internal/shell"
2122 "github.com/xonecas/symb/internal/store"
2223 "github.com/xonecas/symb/internal/treesitter"
2324 "github.com/xonecas/symb/internal/tui"
@@ -98,6 +99,10 @@ func main() {
9899 svc.lspManager.SetCallback(func(absPath string, lines map[int]int) {
99100 p.Send(tui.LSPDiagnosticsMsg{FilePath: absPath, Lines: lines})
100101 })
102+ // Wire shell output streaming to TUI.
103+ svc.shellHandler.OnOutput = func(chunk string) {
104+ p.Send(tui.ShellOutputMsg{Content: chunk})
105+ }
101106
102107 if _, err := p.Run(); err != nil {
103108 fmt.Printf("Error running symb: %v\n", err)
@@ -143,6 +148,7 @@ type services struct {
143148 webCache *store.Cache
144149 readHandler *mcptools.ReadHandler
145150 editHandler *mcptools.EditHandler
151+ shellHandler *mcptools.ShellHandler
146152 fileTracker *mcptools.FileReadTracker
147153 deltaTracker *delta.Tracker
148154 }
@@ -181,12 +187,18 @@ func setupServices(cfg *config.Config, creds *config.Credentials) services {
181187 exaKey := creds.GetAPIKey("exa_ai")
182188 proxy.RegisterTool(mcptools.NewWebSearchTool(), mcptools.MakeWebSearchHandler(webCache, exaKey, ""))
183189
190+ // Shell tool — in-process POSIX interpreter with command blocking.
191+ sh := shell.New("", shell.DefaultBlockFuncs())
192+ shellHandler := mcptools.NewShellHandler(sh, dt)
193+ proxy.RegisterTool(mcptools.NewShellTool(), shellHandler.Handle)
194+
184195 return services{
185196 proxy: proxy,
186197 lspManager: lspManager,
187198 webCache: webCache,
188199 readHandler: readHandler,
189200 editHandler: editHandler,
201+ shellHandler: shellHandler,
190202 fileTracker: fileTracker,
191203 deltaTracker: dt,
192204 }
go.mod+3−1
@@ -13,8 +13,10 @@ require (
1313 github.com/charmbracelet/x/powernap v0.0.0-20260209132835-6b065b8ba62c
1414 github.com/rs/zerolog v1.34.0
1515 github.com/sashabaranov/go-openai v1.41.2
16+ github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82
1617 golang.org/x/net v0.50.0
1718 modernc.org/sqlite v1.45.0
19+ mvdan.cc/sh/v3 v3.12.0
1820 )
1921
2022 require (
@@ -39,12 +41,12 @@ require (
3941 github.com/ncruces/go-strftime v1.0.0 // indirect
4042 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
4143 github.com/rivo/uniseg v0.4.7 // indirect
42- github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82 // indirect
4344 github.com/sourcegraph/jsonrpc2 v0.2.1 // indirect
4445 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
4546 golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
4647 golang.org/x/sync v0.19.0 // indirect
4748 golang.org/x/sys v0.41.0 // indirect
49+ golang.org/x/term v0.40.0 // indirect
4850 golang.org/x/tools v0.41.0 // indirect
4951 modernc.org/libc v1.67.6 // indirect
5052 modernc.org/mathutil v1.7.1 // indirect
go.sum+24−0
@@ -37,11 +37,19 @@ github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEX
3737 github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
3838 github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
3939 github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
40+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
41+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
42+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
43+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4044 github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
4145 github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
4246 github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
4347 github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
48+github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
49+github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
4450 github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
51+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
52+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
4553 github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
4654 github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
4755 github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -52,6 +60,10 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs
5260 github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
5361 github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
5462 github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
63+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
64+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
65+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
66+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
5567 github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
5668 github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
5769 github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
@@ -69,10 +81,14 @@ github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIf
6981 github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
7082 github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
7183 github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
84+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
85+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
7286 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
7387 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
7488 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
7589 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
90+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
91+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
7692 github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
7793 github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
7894 github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
@@ -82,6 +98,8 @@ github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82 h1:6C8qej6f
8298 github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82/go.mod h1:xe4pgH49k4SsmkQq5OT8abwhWmnzkhpgnXeekbx2efw=
8399 github.com/sourcegraph/jsonrpc2 v0.2.1 h1:2GtljixMQYUYCmIg7W9aF2dFmniq/mOr2T9tFRh6zSQ=
84100 github.com/sourcegraph/jsonrpc2 v0.2.1/go.mod h1:ZafdZgk/axhT1cvZAPOhw+95nz2I/Ra5qMlU4gTRwIo=
101+github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
102+github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
85103 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
86104 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
87105 golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
@@ -97,8 +115,12 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
97115 golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
98116 golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
99117 golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
118+golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
119+golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
100120 golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
101121 golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
122+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
123+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
102124 modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
103125 modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
104126 modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
@@ -127,3 +149,5 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
127149 modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
128150 modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
129151 modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
152+mvdan.cc/sh/v3 v3.12.0 h1:ejKUR7ONP5bb+UGHGEG/k9V5+pRVIyD+LsZz7o8KHrI=
153+mvdan.cc/sh/v3 v3.12.0/go.mod h1:Se6Cj17eYSn+sNooLZiEUnNNmNxg0imoYlTu4CyaGyg=
internal/llm/anthropic.md+12−1
@@ -71,6 +71,17 @@ Search the web for documentation, APIs, libraries, or current information. Resul
7171
7272 **Search before assuming** — when asked about external libraries, APIs, or current information, use WebSearch to verify rather than relying on potentially outdated knowledge.
7373
74+### `Shell` — Execute shell commands
75+Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
76+Dangerous commands (network, sudo, package managers) are blocked.
77+
78+- `{"command": "go build ./...", "description": "Build the project"}`
79+- `{"command": "make test", "description": "Run tests"}`
80+- `{"command": "git diff --stat", "description": "Show changed files"}`
81+- `{"command": "ls -la src/", "description": "List source directory", "timeout": 30}`
82+
83+Use for: builds, tests, linters, git, file inspection. Default timeout: 60s.
84+
7485 ### `Edit` — Modify files using hash anchors
7586 **Prerequisite: Read the file first.** The hashes from Read output are your edit anchors.
7687
@@ -158,7 +169,7 @@ before nil check. Move the guard clause above line 31.
158169 ## Constraints
159170
160171 - **CWD-scoped**: All file operations are relative to current working directory
161-- **Security**: No shell execution, path traversal prevention
172+- **Security**: Path traversal prevention, dangerous shell commands blocked
162173 - **No guessing**: Always use tools to verify before making claims
163174
164175 ## Response Format
internal/llm/gemini.md+12−2
@@ -88,6 +88,16 @@ Search the web for documentation, APIs, libraries, or current information. Resul
8888
8989 **Search before assuming** — when asked about external libraries, APIs, or current information, use WebSearch to verify rather than relying on potentially outdated knowledge.
9090
91+### `Shell` — Execute shell commands
92+Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
93+Dangerous commands (network, sudo, package managers) are blocked.
94+
95+```json
96+{"command": "go test ./...", "description": "Run all tests", "timeout": 120}
97+```
98+
99+Use for: builds, tests, linters, git, file inspection. Default timeout: 60s.
100+
91101 ### `Edit` — Modify files using hash anchors
92102 **Prerequisite: Read the file first.** The hashes from Read output are your edit anchors.
93103
@@ -153,7 +163,7 @@ Always include file:line references:
153163
154164 - All file operations are CWD-scoped
155165 - No path traversal allowed
156-- No shell execution capabilities
166+- Shell execution restricted: dangerous commands blocked
157167 - File editing via hash-anchored Edit tool only
158168
159169 ## Response Format
@@ -179,7 +189,7 @@ Uses context for cancellation.
179189
180190 - **Edit via hashline**: Hash-anchored file editing (Read first, then Edit)
181191 - **CWD-scoped**: All paths relative to working directory
182-- **No execution**: Cannot run code or shell commands
192+- **Shell restricted**: Dangerous commands blocked, safe commands allowed
183193 - **No guessing**: Always verify with tools before claiming facts
184194 - **Security**: Defensive use only, never help with malicious intent
185195
internal/llm/gpt.md+13−2
@@ -88,6 +88,17 @@ Search the web for documentation, APIs, libraries, or current information. Resul
8888
8989 **Search before assuming** — when asked about external libraries, APIs, or current information, use WebSearch to verify rather than relying on potentially outdated knowledge.
9090
91+### `Shell` — Execute shell commands
92+Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
93+Dangerous commands (network, sudo, package managers) are blocked.
94+
95+**Parameters:**
96+```json
97+{"command": "make lint", "description": "Run linter", "timeout": 120}
98+```
99+
100+Use for: builds, tests, linters, git operations, file inspection. Default timeout: 60s.
101+
91102 ### `Edit` — Modify files using hash anchors
92103 **Prerequisite: Read the file first.** The hashes from Read output are your edit anchors.
93104
@@ -194,7 +205,7 @@ Always reference code with `file:line` notation:
194205
195206 ## Security Model
196207 - **Scoped**: CWD and subdirectories only (no path traversal)
197-- **Safe**: No shell execution, no dangerous operations
208+- **Shell restricted**: Dangerous commands blocked, safe commands allowed
198209 - **Bounded**: Search results capped, file sizes checked
199210
200211 ## Response Format Template
@@ -231,10 +242,10 @@ from 429 responses.
231242 ✓ Debug issues with tool assistance
232243
233244 ### What You CANNOT Do
234-✗ Execute code or shell commands
235245 ✗ Access files outside CWD
236246 ✗ Guess or infer without tool verification
237247 ✗ Make assumptions about file contents
248+✗ Run network, sudo, or package manager commands (blocked)
238249
239250 ## Key Principles
240251
internal/llm/qwen.md+9−1
@@ -66,6 +66,14 @@ Search for docs, APIs, libraries, current info. Cached 24h.
6666
6767 **Search before assuming** — use WebSearch to verify external APIs/libraries rather than guessing.
6868
69+### `Shell` — Execute shell commands
70+Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
71+Dangerous commands (network, sudo, package managers) are blocked.
72+```json
73+{"command": "go test -v ./...", "description": "Run tests verbosely", "timeout": 120}
74+```
75+Use for: builds, tests, linters, git, file inspection. Default timeout: 60s.
76+
6977 ### `Edit` — Modify files using hash anchors
7078 **Read the file first.** One operation per call. Returns fresh hashes after each edit.
7179
@@ -117,7 +125,7 @@ Always include file:line:
117125 **Constraints:**
118126 - File editing via hash-anchored Edit tool (Read first)
119127 - CWD-scoped (no path traversal)
120-- No shell execution
128+- Shell restricted: dangerous commands blocked
121129 - Security: defensive only
122130
123131 ## Response Pattern
internal/mcptools/shell.go+260−0
@@ -0,0 +1,260 @@
1+package mcptools
2+
3+import (
4+ "bytes"
5+ "context"
6+ "encoding/json"
7+ "fmt"
8+ "io/fs"
9+ "os"
10+ "path/filepath"
11+ "strings"
12+ "time"
13+
14+ "github.com/xonecas/symb/internal/delta"
15+ "github.com/xonecas/symb/internal/mcp"
16+ "github.com/xonecas/symb/internal/shell"
17+)
18+
19+// ShellArgs are the arguments to the Shell tool.
20+type ShellArgs struct {
21+ Command string `json:"command"`
22+ Description string `json:"description"`
23+ Timeout int `json:"timeout,omitempty"` // seconds, default 60
24+}
25+
26+// NewShellTool creates the Shell tool definition.
27+func NewShellTool() mcp.Tool {
28+ return mcp.Tool{
29+ Name: "Shell",
30+ Description: `Execute a shell command in an in-process POSIX interpreter.
31+Commands run inside the project working directory. Shell state (cwd, env vars) persists across calls within the same session.
32+Dangerous commands (network, sudo, package managers, system modification) are blocked.
33+Use this for: running builds, tests, linters, git operations, file manipulation, and inspecting project state.`,
34+ InputSchema: json.RawMessage(`{
35+ "type": "object",
36+ "properties": {
37+ "command": {"type": "string", "description": "The shell command to execute"},
38+ "description": {"type": "string", "description": "Brief description of what this command does (5-10 words)"},
39+ "timeout": {"type": "integer", "description": "Timeout in seconds (default 60)"}
40+ },
41+ "required": ["command", "description"]
42+ }`),
43+ }
44+}
45+
46+// ShellHandler handles Shell tool calls.
47+type ShellHandler struct {
48+ sh *shell.Shell
49+ deltaTracker *delta.Tracker
50+ // OnOutput is called with incremental output chunks for real-time streaming.
51+ // May be nil.
52+ OnOutput func(chunk string)
53+}
54+
55+// NewShellHandler creates a handler for the Shell tool.
56+func NewShellHandler(sh *shell.Shell, dt *delta.Tracker) *ShellHandler {
57+ return &ShellHandler{sh: sh, deltaTracker: dt}
58+}
59+
60+// Handle implements the mcp.ToolHandler interface.
61+func (h *ShellHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
62+ var args ShellArgs
63+ if err := json.Unmarshal(arguments, &args); err != nil {
64+ return toolError("Invalid arguments: %v", err), nil
65+ }
66+ if args.Command == "" {
67+ return toolError("command is required"), nil
68+ }
69+
70+ timeout := 60
71+ if args.Timeout > 0 {
72+ timeout = args.Timeout
73+ }
74+ if timeout > maxTimeoutSec {
75+ timeout = maxTimeoutSec
76+ }
77+
78+ ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
79+ defer cancel()
80+
81+ // Snapshot the shell's working directory for undo — only when the delta
82+ // tracker is active (has a turn), to avoid expensive walks on read-only commands.
83+ shellCwd := h.sh.Dir()
84+ trackDeltas := h.deltaTracker != nil && h.deltaTracker.TurnID() > 0
85+ var preSnap map[string]fileSnapshot
86+ if trackDeltas {
87+ preSnap = snapshotDir(shellCwd)
88+ }
89+
90+ // Execute command with streaming output.
91+ var stdout, stderr bytes.Buffer
92+
93+ var execErr error
94+ if h.OnOutput != nil {
95+ sw := &streamWriter{buf: &stdout, onChunk: h.OnOutput}
96+ execErr = h.sh.ExecStream(ctx, args.Command, sw, &stderr)
97+ } else {
98+ execErr = h.sh.ExecStream(ctx, args.Command, &stdout, &stderr)
99+ }
100+
101+ // Post-execution: diff the *original* cwd to record deltas for undo.
102+ // Always use shellCwd (the pre-exec directory) for both snapshots so a
103+ // `cd` inside the command doesn't cause a cross-directory mismatch.
104+ if trackDeltas {
105+ postSnap := snapshotDir(shellCwd)
106+ recordDeltas(h.deltaTracker, shellCwd, preSnap, postSnap)
107+ }
108+
109+ // Format result.
110+ exitCode := shell.ExitCode(execErr)
111+ output := formatShellOutput(stdout.String(), stderr.String(), exitCode, ctx.Err())
112+
113+ // Ensure non-empty output — some providers reject empty tool results.
114+ if output == "" {
115+ output = "(no output)\n"
116+ }
117+
118+ if len([]rune(output)) > maxOutputChars {
119+ output = truncateMiddle(output, maxOutputChars)
120+ }
121+
122+ if exitCode != 0 {
123+ return &mcp.ToolResult{
124+ Content: []mcp.ContentBlock{{Type: "text", Text: output}},
125+ IsError: true,
126+ }, nil
127+ }
128+ return toolText(output), nil
129+}
130+
131+const maxOutputChars = 30000
132+const maxTimeoutSec = 600 // 10 minutes
133+
134+// streamWriter wraps a bytes.Buffer and calls onChunk for each Write.
135+type streamWriter struct {
136+ buf *bytes.Buffer
137+ onChunk func(string)
138+}
139+
140+func (w *streamWriter) Write(p []byte) (int, error) {
141+ n, err := w.buf.Write(p)
142+ if n > 0 && w.onChunk != nil {
143+ w.onChunk(string(p[:n]))
144+ }
145+ return n, err
146+}
147+
148+func formatShellOutput(stdout, stderr string, exitCode int, ctxErr error) string {
149+ var b strings.Builder
150+ if stdout != "" {
151+ b.WriteString(stdout)
152+ if !strings.HasSuffix(stdout, "\n") {
153+ b.WriteByte('\n')
154+ }
155+ }
156+ if stderr != "" {
157+ b.WriteString(stderr)
158+ if !strings.HasSuffix(stderr, "\n") {
159+ b.WriteByte('\n')
160+ }
161+ }
162+ if ctxErr != nil {
163+ fmt.Fprintf(&b, "[timed out]\n")
164+ }
165+ if exitCode != 0 {
166+ fmt.Fprintf(&b, "[exit code: %d]\n", exitCode)
167+ }
168+ return b.String()
169+}
170+
171+func truncateMiddle(s string, maxChars int) string {
172+ runes := []rune(s)
173+ if len(runes) <= maxChars {
174+ return s
175+ }
176+ half := maxChars / 2
177+ return string(runes[:half]) + "\n\n... [truncated] ...\n\n" + string(runes[len(runes)-half:])
178+}
179+
180+// ---------------------------------------------------------------------------
181+// CWD snapshot for undo
182+// ---------------------------------------------------------------------------
183+
184+// fileSnapshot holds mtime+size+content for change detection and undo.
185+type fileSnapshot struct {
186+ modTime time.Time
187+ size int64
188+ content []byte // pre-read for undo; nil for large files
189+}
190+
191+// maxSnapshotFileSize is the max file size we pre-read for undo (1 MB).
192+const maxSnapshotFileSize = 1 << 20
193+
194+// skipDirs are directories skipped during snapshot walks.
195+var skipDirs = map[string]bool{
196+ ".git": true, "node_modules": true, "__pycache__": true,
197+ ".venv": true, "vendor": true, ".cache": true, ".next": true,
198+ "dist": true, "build": true, "target": true,
199+}
200+
201+// snapshotDir walks root and returns a map of relative path -> fileSnapshot.
202+// Files under maxSnapshotFileSize have their content pre-read for undo.
203+func snapshotDir(root string) map[string]fileSnapshot {
204+ snap := make(map[string]fileSnapshot)
205+ _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
206+ if err != nil {
207+ return nil
208+ }
209+ if d.IsDir() {
210+ if skipDirs[d.Name()] {
211+ return filepath.SkipDir
212+ }
213+ return nil
214+ }
215+ rel, err := filepath.Rel(root, path)
216+ if err != nil {
217+ return nil
218+ }
219+ info, err := d.Info()
220+ if err != nil {
221+ return nil
222+ }
223+ fs := fileSnapshot{modTime: info.ModTime(), size: info.Size()}
224+ if info.Size() <= maxSnapshotFileSize {
225+ fs.content, _ = os.ReadFile(path)
226+ }
227+ snap[rel] = fs
228+ return nil
229+ })
230+ return snap
231+}
232+
233+// recordDeltas compares pre/post snapshots and records deltas for undo.
234+func recordDeltas(dt *delta.Tracker, root string, pre, post map[string]fileSnapshot) {
235+ // New or modified files.
236+ for rel, postInfo := range post {
237+ absPath := filepath.Join(root, rel)
238+ preInfo, existed := pre[rel]
239+ if !existed {
240+ dt.RecordCreate(absPath)
241+ continue
242+ }
243+ if preInfo.modTime != postInfo.modTime || preInfo.size != postInfo.size {
244+ // File was modified — use pre-read content for undo.
245+ dt.RecordModify(absPath, preInfo.content)
246+ }
247+ }
248+ // Deleted files — existed in pre but not in post.
249+ for rel, preInfo := range pre {
250+ if _, exists := post[rel]; !exists {
251+ absPath := filepath.Join(root, rel)
252+ if preInfo.content != nil {
253+ // We have the original content; record as modify so undo restores it.
254+ dt.RecordModify(absPath, preInfo.content)
255+ }
256+ // If content is nil (file was > maxSnapshotFileSize), we can't
257+ // restore it. Skip rather than writing a 0-byte file on undo.
258+ }
259+ }
260+}
internal/shell/block.go+130−0
@@ -0,0 +1,130 @@
1+// Package shell provides an in-process POSIX shell interpreter with command
2+// blocking for safe LLM-driven execution.
3+package shell
4+
5+import "strings"
6+
7+// BlockFunc returns true if the given command args should be blocked.
8+type BlockFunc func(args []string) bool
9+
10+// CommandsBlocker returns a BlockFunc that blocks exact command name matches.
11+func CommandsBlocker(cmds []string) BlockFunc {
12+ blocked := make(map[string]struct{}, len(cmds))
13+ for _, c := range cmds {
14+ blocked[c] = struct{}{}
15+ }
16+ return func(args []string) bool {
17+ if len(args) == 0 {
18+ return false
19+ }
20+ _, ok := blocked[args[0]]
21+ return ok
22+ }
23+}
24+
25+// ArgumentsBlocker returns a BlockFunc that blocks a command when specific
26+// subcommand args and/or flags are present.
27+//
28+// For example, ArgumentsBlocker("npm", []string{"install"}, []string{"-g"})
29+// blocks "npm install -g <pkg>" but allows "npm install <pkg>".
30+func ArgumentsBlocker(cmd string, subArgs, flags []string) BlockFunc {
31+ return func(args []string) bool {
32+ if len(args) == 0 || args[0] != cmd {
33+ return false
34+ }
35+ posArgs, posFlags := splitArgsFlags(args[1:])
36+ if !prefixMatch(posArgs, subArgs) {
37+ return false
38+ }
39+ if len(flags) > 0 && !flagsPresent(posFlags, flags) {
40+ return false
41+ }
42+ return true
43+ }
44+}
45+
46+// splitArgsFlags separates positional arguments from flags (anything
47+// starting with '-').
48+func splitArgsFlags(args []string) (positional, flags []string) {
49+ for _, a := range args {
50+ if strings.HasPrefix(a, "-") {
51+ flags = append(flags, a)
52+ } else {
53+ positional = append(positional, a)
54+ }
55+ }
56+ return
57+}
58+
59+// prefixMatch returns true if haystack starts with all elements of needle.
60+func prefixMatch(haystack, needle []string) bool {
61+ if len(haystack) < len(needle) {
62+ return false
63+ }
64+ for i, n := range needle {
65+ if haystack[i] != n {
66+ return false
67+ }
68+ }
69+ return true
70+}
71+
72+// flagsPresent returns true if all required flags appear in the actual flags.
73+func flagsPresent(actual, required []string) bool {
74+ have := make(map[string]struct{}, len(actual))
75+ for _, f := range actual {
76+ have[f] = struct{}{}
77+ }
78+ for _, r := range required {
79+ if _, ok := have[r]; !ok {
80+ return false
81+ }
82+ }
83+ return true
84+}
85+
86+// BannedCommands is the default set of commands blocked for security.
87+var BannedCommands = []string{
88+ // Bypass vectors — block shells, interpreters, and indirection commands
89+ // that could re-exec blocked commands or run arbitrary network code.
90+ "bash", "sh", "zsh", "fish", "csh", "tcsh", "ksh", "dash",
91+ "env", "nohup", "xargs", "strace", "ltrace",
92+ "python", "python3", "python2", "node", "ruby", "perl",
93+ "php", "lua", "tclsh", "wish",
94+ // Network / download
95+ "aria2c", "axel", "curl", "curlie", "http-prompt", "httpie",
96+ "links", "lynx", "nc", "ncat", "scp", "sftp", "ssh",
97+ "telnet", "w3m", "wget", "xh",
98+ // Privilege escalation
99+ "doas", "su", "sudo",
100+ // Package managers
101+ "apk", "apt", "apt-cache", "apt-get", "dnf", "dpkg", "emerge",
102+ "home-manager", "makepkg", "opkg", "pacman", "paru", "pkg",
103+ "pkg_add", "pkg_delete", "portage", "rpm", "yay", "yum", "zypper",
104+ // System modification
105+ "at", "batch", "chkconfig", "crontab", "fdisk", "mkfs", "mount",
106+ "parted", "service", "systemctl", "umount",
107+ // Network configuration
108+ "firewall-cmd", "ifconfig", "ip", "iptables", "netstat", "pfctl",
109+ "route", "ufw",
110+}
111+
112+// DefaultBlockFuncs returns the standard set of block functions.
113+func DefaultBlockFuncs() []BlockFunc {
114+ return []BlockFunc{
115+ CommandsBlocker(BannedCommands),
116+ // Block global package installs
117+ ArgumentsBlocker("npm", []string{"install"}, []string{"-g"}),
118+ ArgumentsBlocker("npm", []string{"install"}, []string{"--global"}),
119+ ArgumentsBlocker("pnpm", []string{"add"}, []string{"-g"}),
120+ ArgumentsBlocker("pnpm", []string{"add"}, []string{"--global"}),
121+ ArgumentsBlocker("yarn", []string{"global"}, nil),
122+ ArgumentsBlocker("pip", []string{"install"}, nil),
123+ ArgumentsBlocker("pip3", []string{"install"}, nil),
124+ ArgumentsBlocker("gem", []string{"install"}, nil),
125+ ArgumentsBlocker("cargo", []string{"install"}, nil),
126+ ArgumentsBlocker("go", []string{"install"}, nil),
127+ // Block go test -exec (code execution escape)
128+ ArgumentsBlocker("go", []string{"test"}, []string{"-exec"}),
129+ }
130+}
internal/shell/block_test.go+109−0
@@ -0,0 +1,109 @@
1+package shell
2+
3+import "testing"
4+
5+func TestCommandsBlocker(t *testing.T) {
6+ blocker := CommandsBlocker([]string{"curl", "wget", "sudo"})
7+
8+ tests := []struct {
9+ args []string
10+ blocked bool
11+ }{
12+ {[]string{"curl", "http://example.com"}, true},
13+ {[]string{"wget", "-q", "http://example.com"}, true},
14+ {[]string{"sudo", "rm", "-rf", "/"}, true},
15+ {[]string{"ls", "-la"}, false},
16+ {[]string{"go", "build"}, false},
17+ {[]string{}, false},
18+ {nil, false},
19+ }
20+ for _, tt := range tests {
21+ if got := blocker(tt.args); got != tt.blocked {
22+ t.Errorf("CommandsBlocker(%v) = %v, want %v", tt.args, got, tt.blocked)
23+ }
24+ }
25+}
26+
27+func TestArgumentsBlocker(t *testing.T) {
28+ tests := []struct {
29+ name string
30+ cmd string
31+ sub []string
32+ flags []string
33+ args []string
34+ blocked bool
35+ }{
36+ {"npm install -g", "npm", []string{"install"}, []string{"-g"}, []string{"npm", "install", "-g", "typescript"}, true},
37+ {"npm install local", "npm", []string{"install"}, []string{"-g"}, []string{"npm", "install", "lodash"}, false},
38+ {"npm run", "npm", []string{"install"}, []string{"-g"}, []string{"npm", "run", "test"}, false},
39+ {"different cmd", "npm", []string{"install"}, []string{"-g"}, []string{"yarn", "install", "-g"}, false},
40+ {"no flags required", "pip", []string{"install"}, nil, []string{"pip", "install", "requests"}, true},
41+ {"go test -exec", "go", []string{"test"}, []string{"-exec"}, []string{"go", "test", "-exec", "echo", "./..."}, true},
42+ {"go test normal", "go", []string{"test"}, []string{"-exec"}, []string{"go", "test", "-v", "./..."}, false},
43+ {"empty args", "npm", []string{"install"}, []string{"-g"}, []string{}, false},
44+ }
45+ for _, tt := range tests {
46+ t.Run(tt.name, func(t *testing.T) {
47+ blocker := ArgumentsBlocker(tt.cmd, tt.sub, tt.flags)
48+ if got := blocker(tt.args); got != tt.blocked {
49+ t.Errorf("ArgumentsBlocker(%q, %v, %v)(%v) = %v, want %v",
50+ tt.cmd, tt.sub, tt.flags, tt.args, got, tt.blocked)
51+ }
52+ })
53+ }
54+}
55+
56+func TestDefaultBlockFuncs(t *testing.T) {
57+ blockers := DefaultBlockFuncs()
58+
59+ mustBlock := [][]string{
60+ {"curl", "http://example.com"},
61+ {"sudo", "rm", "-rf", "/"},
62+ {"ssh", "user@host"},
63+ {"npm", "install", "-g", "typescript"},
64+ {"pip", "install", "requests"},
65+ {"go", "test", "-exec", "echo"},
66+ // Bypass vectors
67+ {"bash", "-c", "curl http://evil.com"},
68+ {"sh", "-c", "wget http://evil.com"},
69+ {"env", "curl", "http://evil.com"},
70+ {"nohup", "ssh", "user@host"},
71+ {"xargs", "curl"},
72+ // Scripting interpreters
73+ {"python", "-c", "import urllib.request"},
74+ {"python3", "script.py"},
75+ {"node", "-e", "fetch('http://evil.com')"},
76+ {"ruby", "-e", "require 'net/http'"},
77+ {"perl", "-e", "use LWP::Simple"},
78+ }
79+ mustAllow := [][]string{
80+ {"ls", "-la"},
81+ {"go", "build", "./..."},
82+ {"go", "test", "-v", "./..."},
83+ {"make", "build"},
84+ {"git", "status"},
85+ {"npm", "run", "test"},
86+ {"npm", "install", "lodash"}, // local install OK
87+ }
88+
89+ for _, args := range mustBlock {
90+ blocked := false
91+ for _, bf := range blockers {
92+ if bf(args) {
93+ blocked = true
94+ break
95+ }
96+ }
97+ if !blocked {
98+ t.Errorf("expected %v to be blocked", args)
99+ }
100+ }
101+ for _, args := range mustAllow {
102+ for _, bf := range blockers {
103+ if bf(args) {
104+ t.Errorf("expected %v to be allowed", args)
105+ break
106+ }
107+ }
108+ }
109+}
internal/shell/shell.go+137−0
@@ -0,0 +1,137 @@
1+package shell
2+
3+import (
4+ "bytes"
5+ "context"
6+ "errors"
7+ "fmt"
8+ "io"
9+ "os"
10+ "strings"
11+ "sync"
12+
13+ "mvdan.cc/sh/v3/expand"
14+ "mvdan.cc/sh/v3/interp"
15+ "mvdan.cc/sh/v3/syntax"
16+)
17+
18+// Shell provides an in-process POSIX shell with persistent cwd/env across calls.
19+type Shell struct {
20+ mu sync.Mutex
21+ cwd string
22+ env []string
23+ blockFuncs []BlockFunc
24+}
25+
26+// New creates a Shell rooted at cwd with the given block functions.
27+func New(cwd string, blockers []BlockFunc) *Shell {
28+ if cwd == "" {
29+ cwd, _ = os.Getwd()
30+ }
31+ return &Shell{
32+ cwd: cwd,
33+ env: os.Environ(),
34+ blockFuncs: blockers,
35+ }
36+}
37+
38+// Exec runs a command synchronously, returning stdout, stderr, and any error.
39+func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
40+ s.mu.Lock()
41+ defer s.mu.Unlock()
42+
43+ var stdout, stderr bytes.Buffer
44+ err := s.execCommon(ctx, command, &stdout, &stderr)
45+ return stdout.String(), stderr.String(), err
46+}
47+
48+// ExecStream runs a command, streaming output to the provided writers.
49+func (s *Shell) ExecStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
50+ s.mu.Lock()
51+ defer s.mu.Unlock()
52+
53+ return s.execCommon(ctx, command, stdout, stderr)
54+}
55+
56+// Dir returns the current working directory.
57+func (s *Shell) Dir() string {
58+ s.mu.Lock()
59+ defer s.mu.Unlock()
60+ return s.cwd
61+}
62+
63+func (s *Shell) execCommon(ctx context.Context, command string, stdout, stderr io.Writer) (err error) {
64+ var runner *interp.Runner
65+ defer func() {
66+ if r := recover(); r != nil {
67+ err = fmt.Errorf("command execution panic: %v", r)
68+ }
69+ if runner != nil {
70+ s.updateFromRunner(runner)
71+ }
72+ }()
73+
74+ parsed, err := syntax.NewParser().Parse(strings.NewReader(command), "")
75+ if err != nil {
76+ return fmt.Errorf("could not parse command: %w", err)
77+ }
78+
79+ runner, err = s.newInterp(stdout, stderr)
80+ if err != nil {
81+ return fmt.Errorf("could not create interpreter: %w", err)
82+ }
83+
84+ return runner.Run(ctx, parsed)
85+}
86+
87+func (s *Shell) newInterp(stdout, stderr io.Writer) (*interp.Runner, error) {
88+ return interp.New(
89+ interp.StdIO(nil, stdout, stderr),
90+ interp.Interactive(false),
91+ interp.Env(expand.ListEnviron(s.env...)),
92+ interp.Dir(s.cwd),
93+ interp.ExecHandlers(s.blockHandler()),
94+ )
95+}
96+
97+func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
98+ return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
99+ return func(ctx context.Context, args []string) error {
100+ if len(args) == 0 {
101+ return next(ctx, args)
102+ }
103+ for _, bf := range s.blockFuncs {
104+ if bf(args) {
105+ return fmt.Errorf("command blocked: %q", args[0])
106+ }
107+ }
108+ return next(ctx, args)
109+ }
110+ }
111+}
112+
113+// updateFromRunner persists cwd and exported env vars after execution.
114+// Uses runner.Env.Each to preserve all inherited vars, not just those
115+// tracked in runner.Vars.
116+func (s *Shell) updateFromRunner(runner *interp.Runner) {
117+ s.cwd = runner.Dir
118+ s.env = s.env[:0]
119+ runner.Env.Each(func(name string, vr expand.Variable) bool {
120+ if vr.Exported {
121+ s.env = append(s.env, name+"="+vr.Str)
122+ }
123+ return true
124+ })
125+}
126+
127+// ExitCode extracts the exit code from an interpreter error.
128+func ExitCode(err error) int {
129+ if err == nil {
130+ return 0
131+ }
132+ var exitErr interp.ExitStatus
133+ if errors.As(err, &exitErr) {
134+ return int(exitErr)
135+ }
136+ return 1
137+}
internal/tui/messages.go+4−0
@@ -40,6 +40,10 @@ type llmErrorMsg struct{ err error }
4040 type llmContentDeltaMsg struct{ content string }
4141 type llmReasoningDeltaMsg struct{ content string }
4242
43+// ShellOutputMsg carries incremental shell output for real-time display.
44+// Exported so main.go can send it via program.Send from the shell handler callback.
45+type ShellOutputMsg struct{ Content string }
46+
4347 // undoMsg is sent when the user clicks the undo control.
4448 type undoMsg struct{}
4549
internal/tui/update.go+18−0
@@ -57,6 +57,12 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
5757 m.mcpTools = msg.Tools
5858 return m, nil
5959
60+ case ShellOutputMsg:
61+ m.ensureStreaming()
62+ m.streamingContent += msg.Content
63+ m.rebuildStreamEntries()
64+ return m, nil
65+
6066 case undoMsg:
6167 return m.handleUndo(), nil
6268 }
@@ -293,7 +299,19 @@ func (m *Model) applyAssistantMsg(msg llmAssistantMsg) {
293299 }
294300
295301 // applyToolResultMsg appends tool result display entries.
302+// It also clears any active streaming state (e.g. from ShellOutputMsg)
303+// so the next applyAssistantMsg doesn't truncate the tool result entries.
296304 func (m *Model) applyToolResultMsg(msg llmToolResultMsg) {
305+ if m.streaming {
306+ m.streaming = false
307+ if m.streamEntryStart >= 0 && m.streamEntryStart <= len(m.convEntries) {
308+ m.convEntries = m.convEntries[:m.streamEntryStart]
309+ }
310+ m.streamEntryStart = -1
311+ m.streamingReasoning = ""
312+ m.streamingContent = ""
313+ m.convLines = nil
314+ }
297315 var filePath string
298316 if sm := toolResultFileRe.FindStringSubmatch(msg.content); sm != nil {
299317 filePath = sm[1]