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