1package modes
2
3import (
4 "sort"
5 "strings"
6
7 "github.com/mattn/go-runewidth"
8
9 "github.com/patriceckhart/zot/packages/tui"
10)
11
12// slashCommand is one entry in the autocomplete popup. Header rows
13// (group dividers like "── extensions ───") are real entries
14// flagged with header=true; they render but aren't navigable.
15type slashCommand struct {
16 Name string // with leading "/"
17 Desc string
18 Header bool // true = visual divider, not selectable
19}
20
21// slashCancelsTurn reports whether the named slash command, when run
22// while a turn is in flight, requires the active turn to be cancelled
23// first. The destructive commands (those that mutate the transcript
24// or rebuild the agent) need a quiet state; the rest run alongside
25// the streaming response without trouble.
26func slashCancelsTurn(head string) bool {
27 switch head {
28 case "/clear", "/compact", "/logout", "/login", "/model", "/llama", "/reload-ext", "/cd":
29 return true
30 }
31 return false
32}
33
34// slashCatalog lists every slash command the interactive mode handles.
35// Keep in sync with runSlash().
36var slashCatalog = []slashCommand{
37 {Name: "/help", Desc: "show key bindings and commands"},
38 {Name: "/login", Desc: "log in via api key or subscription"},
39 {Name: "/logout", Desc: "clear a provider's credentials"},
40 {Name: "/model", Desc: "pick a model (or /model <id>)"},
41 {Name: "/llama", Desc: "manage llama.cpp router models"},
42 {Name: "/sessions", Desc: "resume a previous session for this directory"},
43 {Name: "/session", Desc: "export the current session to a .zotsession file, or import one"},
44 {Name: "/jump", Desc: "scroll the chat to a previous turn (or /jump <text>)"},
45 {Name: "/compact", Desc: "summarize and replace the transcript to free up context"},
46 {Name: "/study", Desc: "read every file in the cwd (or a passed file/dir) so the agent has full context"},
47 {Name: "/btw", Desc: "side-chat that doesn't add to the main thread (saves tokens)"},
48 {Name: "/jail", Desc: "confine tools to the current directory"},
49 {Name: "/unjail", Desc: "allow tools to touch paths outside this directory"},
50 {Name: "/skills", Desc: "list discovered skills (SKILL.md files)"},
51 {Name: "/swarm", Desc: "supervise background agents that share this working directory"},
52 {Name: "/reload-ext", Desc: "hot-reload all extensions (re-read manifests and respawn)"},
53 {Name: "/telegram", Desc: "connect, disconnect, or show status of the telegram bridge"},
54 {Name: "/settings", Desc: "open settings"},
55 {Name: "/clear", Desc: "clear the chat transcript"},
56 {Name: "/exit", Desc: "exit zot"},
57}
58
59// slashSuggester renders the popup that appears when the editor starts
60// with "/". It does not own any input state — the editor drives.
61const slashSuggestPageSize = 8
62
63type slashSuggester struct {
64 cursor int
65
66 // jailed and llamaConfigured drive state-dependent command visibility.
67 jailed bool
68 llamaConfigured bool
69
70 // extra are commands contributed by extensions, refreshed each
71 // frame from the extension manager. Empty when no extensions
72 // have registered any. Sorted by name in SetExtra so map
73 // iteration order doesn't reshuffle the popup between frames.
74 extra []slashCommand
75
76 // lastMatches is the list shown in the most recent Render call.
77 // Up/Down read it so they know which indexes to skip across
78 // header rows.
79 lastMatches []slashCommand
80}
81
82// SetExtra updates the extension-contributed command list. Called
83// once per render with the live snapshot from the extension manager.
84// The list is sorted by name so the popup ordering stays stable
85// across redraws (Manager.Commands() iterates a map, which Go
86// randomises).
87func (s *slashSuggester) SetExtra(cmds []slashCommand) {
88 sorted := append([]slashCommand(nil), cmds...)
89 sort.Slice(sorted, func(i, j int) bool { return sorted[i].Name < sorted[j].Name })
90 s.extra = sorted
91}
92
93// SetJailed updates the current sandbox state. Called once per render
94// so state-dependent commands can appear/disappear immediately.
95func (s *slashSuggester) SetJailed(jailed bool) { s.jailed = jailed }
96
97// SetLlamaConfigured shows the management command only when a router login is
98// available.
99func (s *slashSuggester) SetLlamaConfigured(configured bool) { s.llamaConfigured = configured }
100
101// allCatalog returns slashCatalog plus the current extra commands
102// (extension-registered) with a header divider between the two
103// groups. Extra entries are only kept if they don't collide with
104// a built-in name; the built-in always wins.
105func (s *slashSuggester) allCatalog() []slashCommand {
106 base := s.baseCatalog()
107 if len(s.extra) == 0 {
108 return base
109 }
110 out := make([]slashCommand, 0, len(base)+len(s.extra)+1)
111 out = append(out, base...)
112 var kept []slashCommand
113 for _, c := range s.extra {
114 dup := false
115 for _, b := range base {
116 if b.Name == c.Name {
117 dup = true
118 break
119 }
120 }
121 if !dup {
122 kept = append(kept, c)
123 }
124 }
125 if len(kept) > 0 {
126 out = append(out, slashCommand{Header: true, Name: "extensions"})
127 out = append(out, kept...)
128 }
129 return out
130}
131
132// baseCatalog returns the built-in commands visible for the current
133// interactive state.
134func (s *slashSuggester) baseCatalog() []slashCommand {
135 hide := "/unjail"
136 if s.jailed {
137 hide = "/jail"
138 }
139 out := make([]slashCommand, 0, len(slashCatalog)-1)
140 for _, c := range slashCatalog {
141 if c.Name == hide || (c.Name == "/llama" && !s.llamaConfigured) {
142 continue
143 }
144 out = append(out, c)
145 }
146 return out
147}
148
149// looksLikeSlashCommand reports whether text is an attempt at a slash
150// command (valid or not). Returns true for things like "/foo" or
151// "/bar baz" but false for paths ("/Users/pat/...") and regexes
152// ("/foo.bar/") so those can be sent to the model as-is.
153//
154// The head after "/" must be a single simple word: only letters,
155// digits, hyphens, and underscores. That excludes paths (contain "/"),
156// regexes (contain "."), and URLs.
157func looksLikeSlashCommand(text string) bool {
158 text = strings.TrimSpace(text)
159 if len(text) < 2 || text[0] != '/' {
160 return false
161 }
162 head := text[1:]
163 if i := strings.IndexAny(head, " \t\n"); i >= 0 {
164 head = head[:i]
165 }
166 if head == "" {
167 return false
168 }
169 for _, r := range head {
170 if !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') &&
171 !(r >= '0' && r <= '9') && r != '-' && r != '_' {
172 return false
173 }
174 }
175 return true
176}
177
178// isKnownSlashCommand reports whether text's head matches a registered
179// slash command name in slashCatalog or hiddenSlashCommands. Built-in
180// only; extension commands are looked up separately by the dispatcher
181// (which consults the extension manager).
182func isKnownSlashCommand(text string) bool {
183 text = strings.TrimSpace(text)
184 if text == "" || text[0] != '/' {
185 return false
186 }
187 head := text
188 if i := strings.IndexAny(text, " \t\n"); i >= 0 {
189 head = text[:i]
190 }
191 for _, c := range slashCatalog {
192 if c.Name == head {
193 return true
194 }
195 }
196 for _, h := range hiddenSlashCommands {
197 if h == head {
198 return true
199 }
200 }
201 return false
202}
203
204// hiddenSlashCommands are dispatchable but intentionally absent from
205// the autocomplete popup, /help, and the README. Used for commands
206// driven by extensions or by other internal flows where surfacing
207// the verb to humans would be confusing or premature.
208var hiddenSlashCommands = []string{
209 "/cd",
210}
211
212func newSlashSuggester() *slashSuggester { return &slashSuggester{} }
213
214// matches returns the commands whose name has input as a prefix.
215// If input is just "/", everything is shown.
216func (s *slashSuggester) matches(input string) []slashCommand {
217 input = strings.TrimRight(input, " ")
218 if input == "" || !strings.HasPrefix(input, "/") {
219 return nil
220 }
221 // If there is a space, the user has moved past the command name.
222 if idx := strings.IndexByte(input, ' '); idx >= 0 {
223 return nil
224 }
225 var out []slashCommand
226 for _, c := range s.allCatalog() {
227 if c.Header {
228 // Headers ride along whenever there's at least one
229 // matching command from their group; we drop trailing
230 // orphan headers below.
231 out = append(out, c)
232 continue
233 }
234 if strings.HasPrefix(c.Name, input) {
235 out = append(out, c)
236 }
237 }
238 return pruneOrphanHeaders(out)
239}
240
241// pruneOrphanHeaders removes header rows that have no commands
242// after them (i.e. the next non-header is missing or another
243// header). Keeps the popup clean when the input filters out a whole
244// group.
245func pruneOrphanHeaders(in []slashCommand) []slashCommand {
246 out := make([]slashCommand, 0, len(in))
247 for i, c := range in {
248 if c.Header {
249 nextReal := false
250 for j := i + 1; j < len(in); j++ {
251 if !in[j].Header {
252 nextReal = true
253 break
254 }
255 }
256 if !nextReal {
257 continue
258 }
259 }
260 out = append(out, c)
261 }
262 return out
263}
264
265// clampCursor keeps the cursor inside the current match list and
266// nudges it past any header row so navigation never lands on one.
267func (s *slashSuggester) clampCursor(n int) {
268 if n <= 0 {
269 s.cursor = 0
270 return
271 }
272 if s.cursor < 0 {
273 s.cursor = 0
274 }
275 if s.cursor >= n {
276 s.cursor = n - 1
277 }
278}
279
280// Up / Down navigate the suggestion list, skipping header rows in
281// either direction so the cursor only ever lands on selectable
282// commands.
283func (s *slashSuggester) Up() {
284 s.skipHeader(-1)
285}
286func (s *slashSuggester) Down() {
287 s.skipHeader(+1)
288}
289
290func (s *slashSuggester) PageUp() {
291 if len(s.lastMatches) == 0 {
292 return
293 }
294 s.cursor -= slashSuggestPageSize
295 if s.cursor < 0 {
296 s.cursor = 0
297 }
298 if s.lastMatches[s.cursor].Header {
299 s.skipHeader(+1)
300 }
301}
302
303func (s *slashSuggester) PageDown() {
304 if len(s.lastMatches) == 0 {
305 return
306 }
307 s.cursor += slashSuggestPageSize
308 if s.cursor >= len(s.lastMatches) {
309 s.cursor = len(s.lastMatches) - 1
310 }
311 if s.lastMatches[s.cursor].Header {
312 s.skipHeader(-1)
313 }
314}
315
316// skipHeader moves the cursor by step, then keeps moving in the same
317// direction across header rows until it lands on a real command (or
318// hits the edge, in which case it bounces back to the nearest real
319// row).
320func (s *slashSuggester) skipHeader(step int) {
321 list := s.lastMatches
322 n := len(list)
323 if n == 0 {
324 return
325 }
326 s.cursor += step
327 for s.cursor >= 0 && s.cursor < n && list[s.cursor].Header {
328 s.cursor += step
329 }
330 if s.cursor < 0 {
331 // Bounce: find the first non-header from the top.
332 for i, c := range list {
333 if !c.Header {
334 s.cursor = i
335 return
336 }
337 }
338 s.cursor = 0
339 }
340 if s.cursor >= n {
341 // Bounce: find the last non-header.
342 for i := n - 1; i >= 0; i-- {
343 if !list[i].Header {
344 s.cursor = i
345 return
346 }
347 }
348 s.cursor = n - 1
349 }
350}
351
352// Active reports whether the popup is visible for the given input.
353func (s *slashSuggester) Active(input string) bool {
354 return len(s.matches(input)) > 0
355}
356
357// Selection returns the currently highlighted command for input, or "".
358// Headers are never returned even if the cursor index would point at
359// one; the cursor is moved forward to the next real command.
360func (s *slashSuggester) Selection(input string) string {
361 m := s.matches(input)
362 if len(m) == 0 {
363 return ""
364 }
365 s.clampCursor(len(m))
366 if m[s.cursor].Header {
367 for i := s.cursor + 1; i < len(m); i++ {
368 if !m[i].Header {
369 s.cursor = i
370 break
371 }
372 }
373 }
374 if m[s.cursor].Header {
375 return ""
376 }
377 return m[s.cursor].Name
378}
379
380// Render returns the popup lines or nil.
381func (s *slashSuggester) Render(input string, th tui.Theme, width int) []string {
382 m := s.matches(input)
383 if len(m) == 0 {
384 return nil
385 }
386 s.lastMatches = m
387 s.clampCursor(len(m))
388 // Snap cursor off any header (e.g. after a filter change put it on one).
389 if s.cursor >= 0 && s.cursor < len(m) && m[s.cursor].Header {
390 for i := s.cursor + 1; i < len(m); i++ {
391 if !m[i].Header {
392 s.cursor = i
393 break
394 }
395 }
396 }
397 // Compute the widest command name across the whole match list
398 // (built-ins + extension-contributed) so every row's description
399 // starts at the same x-position. A minimum keeps short lists
400 // from collapsing the descriptions into the name column.
401 nameWidth := 10
402 for _, c := range m {
403 if c.Header {
404 continue
405 }
406 if n := len(c.Name); n > nameWidth {
407 nameWidth = n
408 }
409 }
410 var lines []string
411 for i := 0; i < len(m); i++ {
412 c := m[i]
413 if c.Header {
414 // Breathing room around group dividers — a blank row
415 // before AND after makes the boundary read at a glance.
416 lines = append(lines, "")
417 rule := strings.Repeat("─", width)
418 label := "── " + c.Name + " "
419 // runewidth, not len: the leading "── " glyphs are multi-byte,
420 // so byte-length padding leaves the rule short of the right edge.
421 if lw := runewidth.StringWidth(label); lw < width {
422 rule = label + strings.Repeat("─", width-lw)
423 }
424 lines = append(lines, th.FG256(th.Muted, rule))
425 lines = append(lines, "")
426 continue
427 }
428 name := c.Name
429 if len(name) < nameWidth {
430 name = name + strings.Repeat(" ", nameWidth-len(name))
431 }
432 plain := " " + name + " " + c.Desc
433 if i == s.cursor {
434 lines = append(lines, th.PadHighlight(plain, width))
435 } else {
436 lines = append(lines, th.FG256(th.Muted, plain))
437 }
438 }
439 // Blank row before the hint visually detaches it from the
440 // command list and groups it with its trailing blank.
441 lines = append(lines, "")
442 lines = append(lines, th.FG256(th.Muted, " ↑/↓ navigate - tab complete - enter run"))
443 // Blank row after the hint separates the popup from the status
444 // bar / editor below it.
445 lines = append(lines, "")
446 return lines
447}
448
449// Reset puts the cursor back to the first match. Call this whenever the
450// input changes in a way that reshapes the match list.
451func (s *slashSuggester) Reset() { s.cursor = 0 }