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 strings.ToLower(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 {
90 left, right := strings.ToLower(sorted[i].Name), strings.ToLower(sorted[j].Name)
91 if left == right {
92 return sorted[i].Name < sorted[j].Name
93 }
94 return left < right
95 })
96 s.extra = sorted
97}
98
99// SetJailed updates the current sandbox state. Called once per render
100// so state-dependent commands can appear/disappear immediately.
101func (s *slashSuggester) SetJailed(jailed bool) { s.jailed = jailed }
102
103// SetLlamaConfigured shows the management command only when a router login is
104// available.
105func (s *slashSuggester) SetLlamaConfigured(configured bool) { s.llamaConfigured = configured }
106
107// allCatalog returns slashCatalog plus the current extra commands
108// (extension-registered) with a header divider between the two
109// groups. Extra entries are only kept if they don't collide with
110// a built-in name; the built-in always wins.
111func (s *slashSuggester) allCatalog() []slashCommand {
112 base := s.baseCatalog()
113 if len(s.extra) == 0 {
114 return base
115 }
116 out := make([]slashCommand, 0, len(base)+len(s.extra)+1)
117 out = append(out, base...)
118 var kept []slashCommand
119 for _, c := range s.extra {
120 dup := false
121 for _, b := range base {
122 if strings.EqualFold(b.Name, c.Name) {
123 dup = true
124 break
125 }
126 }
127 if !dup {
128 kept = append(kept, c)
129 }
130 }
131 if len(kept) > 0 {
132 out = append(out, slashCommand{Header: true, Name: "extensions"})
133 out = append(out, kept...)
134 }
135 return out
136}
137
138// baseCatalog returns the built-in commands visible for the current
139// interactive state.
140func (s *slashSuggester) baseCatalog() []slashCommand {
141 hide := "/unjail"
142 if s.jailed {
143 hide = "/jail"
144 }
145 out := make([]slashCommand, 0, len(slashCatalog)-1)
146 for _, c := range slashCatalog {
147 if c.Name == hide || (c.Name == "/llama" && !s.llamaConfigured) {
148 continue
149 }
150 out = append(out, c)
151 }
152 return out
153}
154
155// looksLikeSlashCommand reports whether text is an attempt at a slash
156// command (valid or not). Returns true for things like "/foo" or
157// "/bar baz" but false for paths ("/Users/pat/...") and regexes
158// ("/foo.bar/") so those can be sent to the model as-is.
159//
160// The head after "/" must be a single simple word: only letters,
161// digits, hyphens, and underscores. That excludes paths (contain "/"),
162// regexes (contain "."), and URLs.
163func looksLikeSlashCommand(text string) bool {
164 text = strings.TrimSpace(text)
165 if len(text) < 2 || text[0] != '/' {
166 return false
167 }
168 head := text[1:]
169 if i := strings.IndexAny(head, " \t\n"); i >= 0 {
170 head = head[:i]
171 }
172 if head == "" {
173 return false
174 }
175 for _, r := range head {
176 if !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') &&
177 !(r >= '0' && r <= '9') && r != '-' && r != '_' {
178 return false
179 }
180 }
181 return true
182}
183
184// isKnownSlashCommand reports whether text's head matches a registered
185// slash command name in slashCatalog or hiddenSlashCommands. Built-in
186// only; extension commands are looked up separately by the dispatcher
187// (which consults the extension manager).
188func isKnownSlashCommand(text string) bool {
189 text = strings.TrimSpace(text)
190 if text == "" || text[0] != '/' {
191 return false
192 }
193 head := text
194 if i := strings.IndexAny(text, " \t\n"); i >= 0 {
195 head = text[:i]
196 }
197 for _, c := range slashCatalog {
198 if strings.EqualFold(c.Name, head) {
199 return true
200 }
201 }
202 for _, h := range hiddenSlashCommands {
203 if strings.EqualFold(h, head) {
204 return true
205 }
206 }
207 return false
208}
209
210// hiddenSlashCommands are dispatchable but intentionally absent from
211// the autocomplete popup, /help, and the README. Used for commands
212// driven by extensions or by other internal flows where surfacing
213// the verb to humans would be confusing or premature.
214var hiddenSlashCommands = []string{
215 "/cd",
216}
217
218func newSlashSuggester() *slashSuggester { return &slashSuggester{} }
219
220// matches returns the commands whose name has input as a prefix.
221// If input is just "/", everything is shown.
222func (s *slashSuggester) matches(input string) []slashCommand {
223 input = strings.TrimRight(input, " ")
224 if input == "" || !strings.HasPrefix(input, "/") {
225 return nil
226 }
227 // If there is a space, the user has moved past the command name.
228 if idx := strings.IndexByte(input, ' '); idx >= 0 {
229 return nil
230 }
231 matchPrefix := strings.ToLower(input)
232 var out []slashCommand
233 for _, c := range s.allCatalog() {
234 if c.Header {
235 // Headers ride along whenever there's at least one
236 // matching command from their group; we drop trailing
237 // orphan headers below.
238 out = append(out, c)
239 continue
240 }
241 if strings.HasPrefix(strings.ToLower(c.Name), matchPrefix) {
242 out = append(out, c)
243 }
244 }
245 return pruneOrphanHeaders(out)
246}
247
248// pruneOrphanHeaders removes header rows that have no commands
249// after them (i.e. the next non-header is missing or another
250// header). Keeps the popup clean when the input filters out a whole
251// group.
252func pruneOrphanHeaders(in []slashCommand) []slashCommand {
253 out := make([]slashCommand, 0, len(in))
254 for i, c := range in {
255 if c.Header {
256 nextReal := false
257 for j := i + 1; j < len(in); j++ {
258 if !in[j].Header {
259 nextReal = true
260 break
261 }
262 }
263 if !nextReal {
264 continue
265 }
266 }
267 out = append(out, c)
268 }
269 return out
270}
271
272// clampCursor keeps the cursor inside the current match list and
273// nudges it past any header row so navigation never lands on one.
274func (s *slashSuggester) clampCursor(n int) {
275 if n <= 0 {
276 s.cursor = 0
277 return
278 }
279 if s.cursor < 0 {
280 s.cursor = 0
281 }
282 if s.cursor >= n {
283 s.cursor = n - 1
284 }
285}
286
287// Up / Down navigate the suggestion list, skipping header rows in
288// either direction so the cursor only ever lands on selectable
289// commands.
290func (s *slashSuggester) Up() {
291 s.skipHeader(-1)
292}
293func (s *slashSuggester) Down() {
294 s.skipHeader(+1)
295}
296
297func (s *slashSuggester) PageUp() {
298 if len(s.lastMatches) == 0 {
299 return
300 }
301 s.cursor -= slashSuggestPageSize
302 if s.cursor < 0 {
303 s.cursor = 0
304 }
305 if s.lastMatches[s.cursor].Header {
306 s.skipHeader(+1)
307 }
308}
309
310func (s *slashSuggester) PageDown() {
311 if len(s.lastMatches) == 0 {
312 return
313 }
314 s.cursor += slashSuggestPageSize
315 if s.cursor >= len(s.lastMatches) {
316 s.cursor = len(s.lastMatches) - 1
317 }
318 if s.lastMatches[s.cursor].Header {
319 s.skipHeader(-1)
320 }
321}
322
323// skipHeader moves the cursor by step, then keeps moving in the same
324// direction across header rows until it lands on a real command (or
325// hits the edge, in which case it bounces back to the nearest real
326// row).
327func (s *slashSuggester) skipHeader(step int) {
328 list := s.lastMatches
329 n := len(list)
330 if n == 0 {
331 return
332 }
333 s.cursor += step
334 for s.cursor >= 0 && s.cursor < n && list[s.cursor].Header {
335 s.cursor += step
336 }
337 if s.cursor < 0 {
338 // Bounce: find the first non-header from the top.
339 for i, c := range list {
340 if !c.Header {
341 s.cursor = i
342 return
343 }
344 }
345 s.cursor = 0
346 }
347 if s.cursor >= n {
348 // Bounce: find the last non-header.
349 for i := n - 1; i >= 0; i-- {
350 if !list[i].Header {
351 s.cursor = i
352 return
353 }
354 }
355 s.cursor = n - 1
356 }
357}
358
359// Active reports whether the popup is visible for the given input.
360func (s *slashSuggester) Active(input string) bool {
361 return len(s.matches(input)) > 0
362}
363
364// Selection returns the currently highlighted command for input, or "".
365// Headers are never returned even if the cursor index would point at
366// one; the cursor is moved forward to the next real command.
367func (s *slashSuggester) Selection(input string) string {
368 m := s.matches(input)
369 if len(m) == 0 {
370 return ""
371 }
372 s.clampCursor(len(m))
373 if m[s.cursor].Header {
374 for i := s.cursor + 1; i < len(m); i++ {
375 if !m[i].Header {
376 s.cursor = i
377 break
378 }
379 }
380 }
381 if m[s.cursor].Header {
382 return ""
383 }
384 return m[s.cursor].Name
385}
386
387// Render returns the popup lines or nil.
388func (s *slashSuggester) Render(input string, th tui.Theme, width int) []string {
389 m := s.matches(input)
390 if len(m) == 0 {
391 return nil
392 }
393 s.lastMatches = m
394 s.clampCursor(len(m))
395 // Snap cursor off any header (e.g. after a filter change put it on one).
396 if s.cursor >= 0 && s.cursor < len(m) && m[s.cursor].Header {
397 for i := s.cursor + 1; i < len(m); i++ {
398 if !m[i].Header {
399 s.cursor = i
400 break
401 }
402 }
403 }
404 // Compute the widest command name across the whole match list
405 // (built-ins + extension-contributed) so every row's description
406 // starts at the same x-position. A minimum keeps short lists
407 // from collapsing the descriptions into the name column.
408 nameWidth := 10
409 for _, c := range m {
410 if c.Header {
411 continue
412 }
413 if n := len(c.Name); n > nameWidth {
414 nameWidth = n
415 }
416 }
417 var lines []string
418 for i := 0; i < len(m); i++ {
419 c := m[i]
420 if c.Header {
421 // Breathing room around group dividers — a blank row
422 // before AND after makes the boundary read at a glance.
423 lines = append(lines, "")
424 rule := strings.Repeat("─", width)
425 label := "── " + c.Name + " "
426 // runewidth, not len: the leading "── " glyphs are multi-byte,
427 // so byte-length padding leaves the rule short of the right edge.
428 if lw := runewidth.StringWidth(label); lw < width {
429 rule = label + strings.Repeat("─", width-lw)
430 }
431 lines = append(lines, th.FG256(th.Muted, rule))
432 lines = append(lines, "")
433 continue
434 }
435 name := c.Name
436 if len(name) < nameWidth {
437 name = name + strings.Repeat(" ", nameWidth-len(name))
438 }
439 plain := " " + name + " " + c.Desc
440 if i == s.cursor {
441 lines = append(lines, th.PadHighlight(plain, width))
442 } else {
443 lines = append(lines, th.FG256(th.Muted, plain))
444 }
445 }
446 // Blank row before the hint visually detaches it from the
447 // command list and groups it with its trailing blank.
448 lines = append(lines, "")
449 lines = append(lines, th.FG256(th.Muted, " ↑/↓ navigate - tab complete - enter run"))
450 // Blank row after the hint separates the popup from the status
451 // bar / editor below it.
452 lines = append(lines, "")
453 return lines
454}
455
456// Reset puts the cursor back to the first match. Call this whenever the
457// input changes in a way that reshapes the match list.
458func (s *slashSuggester) Reset() { s.cursor = 0 }