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