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