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