1package modes
2
3import (
4 "context"
5 "fmt"
6 "strings"
7
8 "github.com/patriceckhart/zot/packages/agent/swarm"
9)
10
11// runSwarm dispatches /swarm subcommands. Layout:
12//
13// /swarm -> open the dashboard
14// /swarm list -> open the dashboard
15// /swarm new [--model M] [--provider P] <task...>
16// -> spawn an agent (optionally pinned to a model)
17// /swarm kill <id> -> stop a running agent
18// /swarm remove <id> -> tear down a terminated agent
19// /swarm logs <id> -> open the scrollable transcript view
20// /swarm send <id> <text...> -> send a follow-up user turn to <id>
21// /swarm resume [id] -> resume an agent (omit id to pick from a list)
22// /swarm attach <id> -> (planned) drop into the agent's TUI
23//
24// When cfg.Swarm is nil the command tells the user the feature is
25// disabled instead of pretending to work.
26func (i *Interactive) runSwarm(ctx context.Context, args []string) {
27 if i.cfg.Swarm == nil {
28 i.mu.Lock()
29 i.statusErr = "swarm is disabled in this build"
30 i.statusOK = ""
31 i.mu.Unlock()
32 return
33 }
34
35 sub := ""
36 rest := ""
37 if len(args) > 0 {
38 sub = strings.ToLower(args[0])
39 // Guard the args[1:] reslice: when only the subcommand was
40 // typed (e.g. bare "/swarm new"), args has length 1 and the
41 // naive args[1:] is fine, but when args is empty (bare
42 // "/swarm") the reslice is [1:0] and panics. The len>0 branch
43 // here keeps both cases safe.
44 if len(args) > 1 {
45 rest = strings.TrimSpace(strings.Join(args[1:], " "))
46 }
47 }
48
49 // spawnAdapter, sendAdapter, resumeAdapter wrap the Swarm methods
50 // in the signatures the dialog expects. Defined once here so the
51 // three Open()-shaped entry points (list, logs/view-jump, resume)
52 // feed the dialog identical callbacks.
53 spawnAdapter := func(task, model, provider string) error {
54 _, err := i.cfg.Swarm.SpawnReq(ctx, swarm.SpawnRequest{
55 Task: task, Model: model, Provider: provider,
56 })
57 return err
58 }
59 sendAdapter := func(id, text string) error {
60 return i.cfg.Swarm.SendUserTurn(id, text)
61 }
62 resumeAdapter := func(id string) error {
63 _, err := i.cfg.Swarm.Resume(ctx, id)
64 return err
65 }
66
67 // Pin every fresh spawn to whatever the host's /model selection
68 // is right now. This is captured at /swarm time — if the user
69 // wants a different model for the next swarm agent, they pick it
70 // via /model first (globally), or, while inside the spawn
71 // editor, by typing /model on its own line to pop the picker.
72 i.swarmDialog.SetCurrentModel(i.cfg.Model, i.cfg.Provider)
73 if i.cfg.LoggedInProviders != nil {
74 i.swarmDialog.SetLoggedInProviders(i.cfg.LoggedInProviders())
75 }
76
77 switch sub {
78 case "", "list", "ls", "ps":
79 i.swarmDialog.Open(
80 i.cfg.Swarm.SnapshotAll,
81 i.cfg.Swarm.Stop,
82 i.cfg.Swarm.Remove,
83 spawnAdapter,
84 sendAdapter,
85 resumeAdapter,
86 i.cfg.CWD,
87 )
88 case "new", "spawn":
89 if rest == "" {
90 i.swarmStatus("", "/swarm new <task>: missing task")
91 return
92 }
93 // Permit `--model X --provider Y` flags before the task so
94 // scripts can pin a model without going through the dialog.
95 // Anything that isn't a recognised flag terminates parsing
96 // and the rest becomes the task; this keeps `/swarm new
97 // --model foo do a thing` and `/swarm new do --model thing`
98 // (where --model is part of the task) unambiguous — only
99 // leading flags are consumed.
100 model, provider, task := parseSpawnFlags(rest)
101 if task == "" {
102 i.swarmStatus("", "/swarm new: missing task (after any --model/--provider flags)")
103 return
104 }
105 a, err := i.cfg.Swarm.SpawnReq(ctx, swarm.SpawnRequest{
106 Task: task, Model: model, Provider: provider,
107 })
108 if err != nil {
109 i.swarmStatus("", "spawn: "+err.Error())
110 return
111 }
112 if model != "" {
113 i.swarmStatus("spawned "+a.ID+" (model "+model+")", "")
114 } else {
115 i.swarmStatus("spawned "+a.ID, "")
116 }
117 case "kill", "stop":
118 if rest == "" {
119 i.swarmStatus("", "/swarm kill <id>: missing id")
120 return
121 }
122 if err := i.cfg.Swarm.Stop(rest); err != nil {
123 i.swarmStatus("", "kill: "+err.Error())
124 return
125 }
126 i.swarmStatus("stopped "+rest, "")
127 case "remove", "rm":
128 if rest == "" {
129 i.swarmStatus("", "/swarm remove <id>: missing id")
130 return
131 }
132 if err := i.cfg.Swarm.Remove(rest); err != nil {
133 i.swarmStatus("", "remove: "+err.Error())
134 return
135 }
136 i.swarmStatus("removed "+rest, "")
137 case "logs", "log", "view":
138 if rest == "" {
139 i.swarmStatus("", "/swarm logs <id>: missing id")
140 return
141 }
142 ok := i.swarmDialog.OpenViewing(
143 rest,
144 i.cfg.Swarm.SnapshotAll,
145 i.cfg.Swarm.Stop,
146 i.cfg.Swarm.Remove,
147 spawnAdapter,
148 sendAdapter,
149 resumeAdapter,
150 i.cfg.CWD,
151 )
152 if !ok {
153 i.swarmStatus("", "/swarm logs: no agent matching "+rest)
154 }
155 case "resume", "reattach", "reopen":
156 if rest == "" {
157 // No id given: open the dashboard with the cursor
158 // pre-positioned on the first resumable agent, and
159 // tell the user how many there are so they know what
160 // to expect. Pressing R confirms; ↑/↓ to pick a
161 // different row first.
162 count := i.swarmDialog.OpenForResume(
163 i.cfg.Swarm.SnapshotAll,
164 i.cfg.Swarm.Stop,
165 i.cfg.Swarm.Remove,
166 spawnAdapter,
167 sendAdapter,
168 resumeAdapter,
169 i.cfg.CWD,
170 )
171 switch count {
172 case 0:
173 i.swarmStatus("", "/swarm resume: no resumable agents (none detached or terminated)")
174 case 1:
175 i.swarmStatus("1 resumable agent, press R to resume", "")
176 default:
177 i.swarmStatus(fmt.Sprintf("%d resumable agents, ↑/↓ to pick, R to resume", count), "")
178 }
179 return
180 }
181 a, err := i.cfg.Swarm.Resume(ctx, rest)
182 if err != nil {
183 i.swarmStatus("", "resume: "+err.Error())
184 return
185 }
186 i.swarmStatus("resumed "+a.ID, "")
187 case "send", "prompt", "msg":
188 // /swarm send <id> <text...> is the non-interactive
189 // counterpart of pressing 'p' in the dashboard. We split the
190 // joined `rest` ourselves rather than reusing the dispatcher's
191 // already-fielded args[] because the text may contain spaces
192 // the user expects to be preserved verbatim.
193 id, text := splitIDAndRest(rest)
194 if id == "" {
195 i.swarmStatus("", "/swarm send <id> <text>: missing id")
196 return
197 }
198 if text == "" {
199 i.swarmStatus("", "/swarm send <id> <text>: missing text")
200 return
201 }
202 if err := i.cfg.Swarm.SendUserTurn(id, text); err != nil {
203 i.swarmStatus("", friendlySendErr(id, err))
204 return
205 }
206 i.swarmStatus("sent to "+id, "")
207 case "attach":
208 // PTY-reparenting is a significant chunk of work I haven't
209 // landed yet (see the design sketch). Recognise the name so
210 // /swarm attach doesn't fall through to the generic "unknown
211 // subcommand" path — that error message is misleading because
212 // it makes attach sound like a typo instead of a planned
213 // feature. Point the user at /swarm logs in the meantime.
214 i.swarmStatus("", "/swarm attach: not implemented yet (needs PTY reparenting). Use /swarm logs "+firstWord(rest)+" to watch its transcript.")
215 default:
216 i.swarmStatus("", "/swarm: unknown subcommand "+sub+" (try list / new / kill / remove / logs / send / resume)")
217 }
218}
219
220// parseSpawnFlags consumes any leading `--model X` / `--provider Y`
221// flags from s and returns them along with the remaining task body.
222// We deliberately only honour LEADING flags so a task like "check
223// --model lookup" doesn't accidentally swallow part of its prose as
224// the model name.
225//
226// Recognised forms:
227//
228// --model X two-token form
229// --model=X single-token form
230// --provider X two-token form
231// --provider=X single-token form
232func parseSpawnFlags(s string) (model, provider, task string) {
233 fields := strings.Fields(s)
234 i := 0
235 for i < len(fields) {
236 f := fields[i]
237 switch {
238 case f == "--model":
239 // Consume the flag even when no value follows so a
240 // dangling "--model" doesn't leak into the task. The
241 // caller surfaces "missing task" instead.
242 if i+1 < len(fields) {
243 model = fields[i+1]
244 i += 2
245 } else {
246 i++
247 }
248 continue
249 case strings.HasPrefix(f, "--model="):
250 model = strings.TrimPrefix(f, "--model=")
251 i++
252 continue
253 case f == "--provider":
254 if i+1 < len(fields) {
255 provider = fields[i+1]
256 i += 2
257 } else {
258 i++
259 }
260 continue
261 case strings.HasPrefix(f, "--provider="):
262 provider = strings.TrimPrefix(f, "--provider=")
263 i++
264 continue
265 }
266 break
267 }
268 task = strings.TrimSpace(strings.Join(fields[i:], " "))
269 return
270}
271
272// splitIDAndRest splits "<id> <text...>" into (id, text). The text
273// half preserves all whitespace after the first token so the agent
274// receives the user's prompt verbatim (modulo a single trim of the
275// boundary space). Returns ("", "") when s is empty so the caller
276// can surface a missing-id error.
277func splitIDAndRest(s string) (id, text string) {
278 s = strings.TrimLeft(s, " \t")
279 if s == "" {
280 return "", ""
281 }
282 cut := strings.IndexAny(s, " \t")
283 if cut < 0 {
284 return s, ""
285 }
286 return s[:cut], strings.TrimLeft(s[cut+1:], " \t")
287}
288
289// firstWord returns the first whitespace-separated token of s, or
290// "<id>" when s is empty. Used to keep the "/swarm attach" hint
291// readable even when the user typed no argument.
292func firstWord(s string) string {
293 s = strings.TrimSpace(s)
294 if s == "" {
295 return "<id>"
296 }
297 if i := strings.IndexAny(s, " \t"); i >= 0 {
298 return s[:i]
299 }
300 return s
301}
302
303func (i *Interactive) swarmStatus(ok, errMsg string) {
304 i.mu.Lock()
305 i.statusOK = ok
306 i.statusErr = errMsg
307 i.mu.Unlock()
308 i.invalidate()
309}