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