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