v0.9.0 84a0b9d

subagents_slash.go RawHistoryFolder

1package modes
2
3import (
4	"context"
5	"fmt"
6	"strings"
7
8	"github.com/bnema/zut/packages/agent/subagents"
9	"github.com/bnema/zut/packages/provider"
10	"github.com/bnema/zut/packages/tui"
11)
12
13// runSubagents dispatches /subagents subcommands. Layout:
14//
15//	/subagents                       -> open the dashboard
16//	/subagents list                  -> open the dashboard
17//	/subagents new [--agent A] [--model M] [--provider P] [--reasoning L] <task...>
18//	                             -> spawn an agent with optional profile/model overrides
19//	/subagents kill <id>             -> stop a running agent
20//	/subagents cancel <id>           -> cancel the active turn
21//	/subagents remove <id>           -> tear down a terminated agent
22//	/subagents logs <id>             -> open the scrollable transcript view
23//	/subagents result|inspect <id>   -> show the completed result
24//	/subagents wait <id>             -> wait for the agent to finish
25//	/subagents send <id> <text...>   -> send a follow-up user turn to <id>
26//	/subagents resume [id]           -> resume an agent (omit id to pick from a list)
27//	/subagents restart-task|restart <id> -> restart the original task
28//	/subagents attach <id>           -> (planned) drop into the agent's TUI
29//
30// When cfg.Supervisor is nil the command tells the user the feature is
31// disabled instead of pretending to work.
32func (i *Interactive) runSubagents(ctx context.Context, args []string) {
33	if i.cfg.Supervisor == nil {
34		i.mu.Lock()
35		i.statusErr = "subagent is disabled in this build"
36		i.statusOK = ""
37		i.mu.Unlock()
38		return
39	}
40
41	sub := ""
42	rest := ""
43	if len(args) > 0 {
44		sub = strings.ToLower(args[0])
45		// Guard the args[1:] reslice: when only the subcommand was
46		// typed (e.g. bare "/subagents new"), args has length 1 and the
47		// naive args[1:] is fine, but when args is empty (bare
48		// "/subagents") the reslice is [1:0] and panics. The len>0 branch
49		// here keeps both cases safe.
50		if len(args) > 1 {
51			rest = strings.TrimSpace(strings.Join(args[1:], " "))
52		}
53	}
54
55	// spawnAdapter, sendAdapter, resumeAdapter wrap the Supervisor methods
56	// in the signatures the dialog expects. Defined once here so the
57	// three Open()-shaped entry points (list, logs/view-jump, resume)
58	// feed the dialog identical callbacks.
59	spawnAdapter := func(task, model, provider string) error {
60		_, err := i.cfg.Supervisor.SpawnReq(ctx, subagents.SpawnRequest{
61			Task: task, Model: model, Provider: provider, Reasoning: i.cfg.Reasoning,
62		})
63		return err
64	}
65	sendAdapter := func(id, text string) error {
66		return i.cfg.Supervisor.SendUserTurn(id, text)
67	}
68	resumeAdapter := func(id string) error {
69		_, err := i.cfg.Supervisor.ResumeSession(ctx, id)
70		return err
71	}
72
73	// Pin every fresh spawn to whatever the host's /model selection
74	// is right now. This is captured at /subagents time — if the user
75	// wants a different model for the next subagent agent, they pick it
76	// via /model first (globally), or, while inside the spawn
77	// editor, by typing /model on its own line to pop the picker.
78	i.subagentsDialog.SetCompactMode(i.compactModeEnabled())
79	i.subagentsDialog.SetLineInput(tui.NormalizeInputStyle(i.cfg.TUIInputStyle) == tui.InputStyleLines)
80	i.subagentsDialog.SetLoadTranscript(i.cfg.Supervisor.LoadTranscript)
81	i.subagentsDialog.SetCurrentModel(i.cfg.Model, i.cfg.Provider)
82	if i.cfg.LoggedInProviders != nil {
83		i.subagentsDialog.SetLoggedInProviders(i.cfg.LoggedInProviders())
84	}
85
86	switch sub {
87	case "", "list", "ls", "ps":
88		i.subagentsDialog.Open(
89			i.cfg.Supervisor.SnapshotAll,
90			i.cfg.Supervisor.Stop,
91			i.cfg.Supervisor.Remove,
92			spawnAdapter,
93			sendAdapter,
94			resumeAdapter,
95			i.cfg.CWD,
96		)
97	case "new", "spawn":
98		if rest == "" {
99			i.subagentsStatus("", "/subagents new <task>: missing task")
100			return
101		}
102		// Permit profile/model/provider/reasoning flags before the task
103		// so scripts can pin a child without going through the dialog.
104		// Anything that isn't a recognised flag terminates parsing and
105		// the rest becomes the task; only leading flags are consumed.
106		model, provider, reasoning, subagent, task := parseSpawnFlags(rest)
107		var profileTools []string
108		var fastModeOverride *bool
109		if task == "" {
110			i.subagentsStatus("", "/subagents new: missing task (after any spawn flags)")
111			return
112		}
113		if subagent != "" {
114			if i.cfg.ResolveSubagent == nil {
115				i.subagentsStatus("", "spawn: named subagent profiles are unavailable")
116				return
117			}
118			profile, err := i.cfg.ResolveSubagent(subagent)
119			if err != nil {
120				i.subagentsStatus("", "spawn: "+err.Error())
121				return
122			}
123			if profile == nil {
124				i.subagentsStatus("", "spawn: unknown subagent profile "+subagent)
125				return
126			}
127			subagent = profile.Name
128			profileTools = append([]string(nil), profile.Tools...)
129			fastModeOverride = profile.FastMode
130			profileProvider, profileModel := profile.ModelSelection()
131			if model == "" {
132				model = profileModel
133			}
134			if provider == "" {
135				provider = profileProvider
136			}
137			if reasoning == "" {
138				reasoning = profile.Thinking
139			}
140		}
141		if model == "" {
142			model = i.cfg.Model
143		}
144		if provider == "" {
145			provider = i.cfg.Provider
146		}
147		if reasoning == "" {
148			reasoning = i.cfg.Reasoning
149		}
150		if reasoning != "" {
151			normalizedReasoning, err := normalizeSpawnReasoning(reasoning)
152			if err != nil {
153				i.subagentsStatus("", "spawn: "+err.Error())
154				return
155			}
156			reasoning = normalizedReasoning
157		}
158		a, err := i.cfg.Supervisor.SpawnReq(ctx, subagents.SpawnRequest{
159			Task: task, Model: model, Provider: provider, Reasoning: reasoning,
160			FastMode: fastModeOverride, Subagent: subagent,
161			Tools: profileTools,
162		})
163		if err != nil {
164			i.subagentsStatus("", "spawn: "+err.Error())
165			return
166		}
167		status := "spawned " + a.ID
168		if subagent != "" {
169			status += " (agent " + subagent + ")"
170		} else if model != "" {
171			status += " (model " + model + ")"
172		}
173		i.subagentsStatus(status, "")
174	case "kill", "stop":
175		if rest == "" {
176			i.subagentsStatus("", "/subagents kill <id>: missing id")
177			return
178		}
179		if err := i.cfg.Supervisor.Stop(rest); err != nil {
180			i.subagentsStatus("", "kill: "+err.Error())
181			return
182		}
183		i.subagentsStatus("stopped "+rest, "")
184	case "cancel":
185		if rest == "" {
186			i.subagentsStatus("", "/subagents cancel <id>: missing id")
187			return
188		}
189		if err := i.cfg.Supervisor.CancelTurn(rest); err != nil {
190			i.subagentsStatus("", "cancel: "+err.Error())
191			return
192		}
193		i.subagentsStatus("canceling turn "+rest, "")
194	case "remove", "rm":
195		if rest == "" {
196			i.subagentsStatus("", "/subagents remove <id>: missing id")
197			return
198		}
199		if err := i.cfg.Supervisor.Remove(rest); err != nil {
200			i.subagentsStatus("", "remove: "+err.Error())
201			return
202		}
203		i.subagentsStatus("removed "+rest, "")
204	case "logs", "log", "view":
205		if rest == "" {
206			i.subagentsStatus("", "/subagents logs <id>: missing id")
207			return
208		}
209		if err := i.cfg.Supervisor.LoadTranscript(rest); err != nil {
210			i.subagentsStatus("", "logs: "+err.Error())
211			return
212		}
213		ok := i.subagentsDialog.OpenViewing(
214			rest,
215			i.cfg.Supervisor.SnapshotAll,
216			i.cfg.Supervisor.Stop,
217			i.cfg.Supervisor.Remove,
218			spawnAdapter,
219			sendAdapter,
220			resumeAdapter,
221			i.cfg.CWD,
222		)
223		if !ok {
224			i.subagentsStatus("", "/subagents logs: no agent matching "+rest)
225		}
226	case "result", "inspect":
227		if rest == "" {
228			i.subagentsStatus("", "/subagents result <id>: missing id")
229			return
230		}
231		result, err := i.cfg.Supervisor.ReadResult(rest)
232		if err != nil {
233			i.subagentsStatus("", "result: "+err.Error())
234			return
235		}
236		status := fmt.Sprintf("%s result %s", result.Status, i.cfg.Supervisor.ResultReference(rest))
237		if result.Summary != "" {
238			status += ": " + truncateStatus(result.Summary, 160)
239		}
240		i.subagentsStatus(status, "")
241	case "wait":
242		if rest == "" {
243			i.subagentsStatus("", "/subagents wait <id>: missing id")
244			return
245		}
246		a := i.cfg.Supervisor.Get(rest)
247		if a == nil {
248			i.subagentsStatus("", "wait: no such agent "+rest)
249			return
250		}
251		waitWatcherDone := i.subagentsWaitWatcherDone
252		go func() {
253			defer func() {
254				if waitWatcherDone != nil {
255					waitWatcherDone()
256				}
257			}()
258			if err := a.WaitContext(ctx); err != nil {
259				return
260			}
261			// If cancellation became observable at the same time as
262			// completion, do not report a completion that the caller
263			// no longer owns.
264			if ctx.Err() == nil {
265				i.subagentsStatus("completed "+a.ID, "")
266			}
267		}()
268		i.subagentsStatus("waiting for "+a.ID, "")
269	case "resume-session", "resume", "reattach", "reopen":
270		if rest == "" {
271			count := i.subagentsDialog.OpenForResume(
272				i.cfg.Supervisor.SnapshotAll,
273				i.cfg.Supervisor.Stop,
274				i.cfg.Supervisor.Remove,
275				spawnAdapter,
276				sendAdapter,
277				resumeAdapter,
278				i.cfg.CWD,
279			)
280			switch count {
281			case 0:
282				i.subagentsStatus("", "/subagents resume-session: no resumable agents")
283			case 1:
284				i.subagentsStatus("1 resumable agent, press R to resume", "")
285			default:
286				i.subagentsStatus(fmt.Sprintf("%d resumable agents, ↑/↓ to pick, R to resume", count), "")
287			}
288			return
289		}
290		a, err := i.cfg.Supervisor.ResumeSession(ctx, rest)
291		if err != nil {
292			i.subagentsStatus("", "resume-session: "+err.Error())
293			return
294		}
295		i.subagentsStatus("resumed "+a.ID, "")
296	case "restart-task", "restart":
297		if rest == "" {
298			i.subagentsStatus("", "/subagents restart-task <id>: missing id")
299			return
300		}
301		a, err := i.cfg.Supervisor.RestartTask(ctx, rest)
302		if err != nil {
303			i.subagentsStatus("", "restart-task: "+err.Error())
304			return
305		}
306		i.subagentsStatus("restarted task "+a.ID, "")
307	case "send", "prompt", "msg":
308		// /subagents send <id> <text...> is the non-interactive
309		// counterpart of pressing 'p' in the dashboard. We split the
310		// joined `rest` ourselves rather than reusing the dispatcher's
311		// already-fielded args[] because the text may contain spaces
312		// the user expects to be preserved verbatim.
313		id, text := splitIDAndRest(rest)
314		if id == "" {
315			i.subagentsStatus("", "/subagents send <id> <text>: missing id")
316			return
317		}
318		if text == "" {
319			i.subagentsStatus("", "/subagents send <id> <text>: missing text")
320			return
321		}
322		if err := i.cfg.Supervisor.SendUserTurn(id, text); err != nil {
323			i.subagentsStatus("", friendlySendErr(id, err))
324			return
325		}
326		i.subagentsStatus("sent to "+id, "")
327	case "attach":
328		// PTY-reparenting is a significant chunk of work I haven't
329		// landed yet (see the design sketch). Recognise the name so
330		// /subagents attach doesn't fall through to the generic "unknown
331		// subcommand" path — that error message is misleading because
332		// it makes attach sound like a typo instead of a planned
333		// feature. Point the user at /subagents logs in the meantime.
334		i.subagentsStatus("", "/subagents attach: not implemented yet (needs PTY reparenting). Use /subagents logs "+firstWord(rest)+" to watch its transcript.")
335	default:
336		i.subagentsStatus("", "/subagents: unknown subcommand "+sub+" (try list / new / kill / cancel / remove / logs / send / result / wait / resume-session / restart-task)")
337	}
338}
339
340// normalizeSpawnReasoning validates and canonicalizes the reasoning levels
341// accepted by ParseArgs before a child process is launched.
342func normalizeSpawnReasoning(value string) (string, error) {
343	raw := strings.ToLower(strings.TrimSpace(value))
344	switch raw {
345	case "", "off":
346		return raw, nil
347	case "minimal", "minimum", "low", "medium", "high", "xhigh", "maximum", "max":
348		return provider.NormalizeReasoning(raw), nil
349	default:
350		return "", fmt.Errorf("reasoning must be off|minimum|low|medium|high|xhigh|max")
351	}
352}
353
354// parseSpawnFlags consumes leading profile/model/provider/reasoning flags
355// using both separate-value and equals forms. Flags after the task remain
356// part of the task text.
357func parseSpawnFlags(s string) (model, provider, reasoning, subagent, task string) {
358	fields := strings.Fields(s)
359	i := 0
360	for i < len(fields) {
361		f := fields[i]
362		switch {
363		case f == "--agent":
364			if i+1 < len(fields) && !strings.HasPrefix(fields[i+1], "--") {
365				subagent = fields[i+1]
366				i += 2
367			} else {
368				i++
369			}
370			continue
371		case strings.HasPrefix(f, "--agent="):
372			subagent = strings.TrimPrefix(f, "--agent=")
373			i++
374			continue
375		case f == "--model":
376			// Consume the flag even when no value follows so a
377			// dangling "--model" doesn't leak into the task. The
378			// caller surfaces "missing task" instead.
379			if i+1 < len(fields) && !strings.HasPrefix(fields[i+1], "--") {
380				model = fields[i+1]
381				i += 2
382			} else {
383				i++
384			}
385			continue
386		case strings.HasPrefix(f, "--model="):
387			model = strings.TrimPrefix(f, "--model=")
388			i++
389			continue
390		case f == "--provider":
391			if i+1 < len(fields) && !strings.HasPrefix(fields[i+1], "--") {
392				provider = fields[i+1]
393				i += 2
394			} else {
395				i++
396			}
397			continue
398		case strings.HasPrefix(f, "--provider="):
399			provider = strings.TrimPrefix(f, "--provider=")
400			i++
401			continue
402		case f == "--reasoning" || f == "--thinking":
403			if i+1 < len(fields) && !strings.HasPrefix(fields[i+1], "--") {
404				reasoning = fields[i+1]
405				i += 2
406			} else {
407				i++
408			}
409			continue
410		case strings.HasPrefix(f, "--reasoning="):
411			reasoning = strings.TrimPrefix(f, "--reasoning=")
412			i++
413			continue
414		case strings.HasPrefix(f, "--thinking="):
415			reasoning = strings.TrimPrefix(f, "--thinking=")
416			i++
417			continue
418		}
419		break
420	}
421	task = strings.TrimSpace(strings.Join(fields[i:], " "))
422	return
423}
424
425// splitIDAndRest splits "<id> <text...>" into (id, text). The text
426// half preserves all whitespace after the first token so the agent
427// receives the user's prompt verbatim (modulo a single trim of the
428// boundary space). Returns ("", "") when s is empty so the caller
429// can surface a missing-id error.
430func splitIDAndRest(s string) (id, text string) {
431	s = strings.TrimLeft(s, " \t")
432	if s == "" {
433		return "", ""
434	}
435	cut := strings.IndexAny(s, " \t")
436	if cut < 0 {
437		return s, ""
438	}
439	return s[:cut], strings.TrimLeft(s[cut+1:], " \t")
440}
441
442// firstWord returns the first whitespace-separated token of s, or
443// "<id>" when s is empty. Used to keep the "/subagents attach" hint
444// readable even when the user typed no argument.
445func firstWord(s string) string {
446	s = strings.TrimSpace(s)
447	if s == "" {
448		return "<id>"
449	}
450	if i := strings.IndexAny(s, " \t"); i >= 0 {
451		return s[:i]
452	}
453	return s
454}
455
456func truncateStatus(value string, max int) string {
457	value = strings.ReplaceAll(strings.TrimSpace(value), "\n", " ")
458	if len([]rune(value)) <= max {
459		return value
460	}
461	if max <= 3 {
462		return string([]rune(value)[:max])
463	}
464	return string([]rune(value)[:max-3]) + "..."
465}
466
467func (i *Interactive) subagentsStatus(ok, errMsg string) {
468	i.mu.Lock()
469	i.statusOK = ok
470	i.statusErr = errMsg
471	i.mu.Unlock()
472	i.invalidate()
473}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close