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