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