1package modes
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "strings"
9 "time"
10
11 "github.com/bnema/zut/packages/agent/extproto"
12 "github.com/bnema/zut/packages/agent/internal/orchestration"
13 "github.com/bnema/zut/packages/agent/subagents"
14 "github.com/bnema/zut/packages/core"
15 "github.com/bnema/zut/packages/provider"
16 "github.com/bnema/zut/packages/tui"
17)
18
19func (i *Interactive) invokeExtensionCommand(ctx context.Context, name, args string) {
20 resp, err := i.cfg.Extensions.Invoke(ctx, name, args, 30*time.Second)
21 if err != nil {
22 i.mu.Lock()
23 i.statusErr = "extension /" + name + ": " + err.Error()
24 i.statusOK = ""
25 i.mu.Unlock()
26 i.invalidate()
27 return
28 }
29 if resp.Error != "" {
30 i.mu.Lock()
31 i.statusErr = "extension /" + name + ": " + resp.Error
32 i.statusOK = ""
33 i.mu.Unlock()
34 i.invalidate()
35 return
36 }
37 switch resp.Action {
38 case "open_panel":
39 if resp.OpenPanel != nil {
40 extName := name
41 if i.cfg.Extensions != nil {
42 if owner := i.cfg.Extensions.CommandOwner(name); owner != "" {
43 extName = owner
44 }
45 }
46 i.OpenPanel(extName, *resp.OpenPanel)
47 }
48 case "prompt":
49 if strings.TrimSpace(resp.Prompt) == "" {
50 return
51 }
52 i.startTurn(i.runCtx, resp.Prompt)
53 case "insert":
54 i.ed.Insert(resp.Insert)
55 i.invalidate()
56 case "display":
57 i.appendExtensionNote(name, resp.Display, "info")
58 case "noop", "":
59 // nothing
60 default:
61 i.mu.Lock()
62 i.statusErr = "extension /" + name + ": unknown action " + resp.Action
63 i.mu.Unlock()
64 i.invalidate()
65 }
66}
67func (i *Interactive) appendExtensionNote(extName, msg, level string) {
68 if msg == "" {
69 return
70 }
71 i.mu.Lock()
72 defer i.mu.Unlock()
73 color := i.cfg.Theme.Muted
74 switch level {
75 case "warn":
76 color = i.cfg.Theme.Warning
77 case "error":
78 color = i.cfg.Theme.Error
79 case "success":
80 color = i.cfg.Theme.Tool
81 }
82 prefix := i.cfg.Theme.FGColor(i.cfg.Theme.Accent, "["+extName+"] ")
83 for _, line := range strings.Split(msg, "\n") {
84 i.statusOK = "" // clear any stale ok
85 i.statusErr = ""
86 i.extNotes = append(i.extNotes, prefix+i.cfg.Theme.FGColor(color, line))
87 }
88 // Extension slash commands complete asynchronously. If their result is
89 // displayed while confirmation is waiting, keep Esc assigned to the note
90 // until it is dismissed rather than letting it answer the tool call.
91 i.confirmDialog.Blur()
92}
93func (i *Interactive) ApplySessionAgent(ag *core.Agent, providerName, model string) {
94 i.ApplySessionAgentWithCompactHandoff(ag, providerName, model, nil)
95}
96func (i *Interactive) ApplySessionAgentWithCompactHandoff(ag *core.Agent, providerName, model string, compactHandoff json.RawMessage) {
97 if ag == nil {
98 return
99 }
100 i.agentMu.Lock()
101 defer i.agentMu.Unlock()
102 i.mu.Lock()
103 i.prepareReplacementAgentLocked(ag)
104 i.compactContinuation = decodeCompactHandoff(compactHandoff)
105 i.agent = ag
106 i.cfg.Provider = providerName
107 i.cfg.Model = model
108 i.view.Messages = filterHiddenTranscriptMessages(ag.Messages())
109 i.cumUsage = ag.Cost()
110 last := ag.LastTurnUsage()
111 i.lastCtxInput = last.InputTokens + last.CacheReadTokens + last.CacheWriteTokens
112 if len(i.view.Messages) > initialResumeTailLimit {
113 i.view.TailLimit = initialResumeTailLimit
114 } else {
115 i.view.TailLimit = 0
116 }
117 i.view.InvalidateRenderCache()
118 i.toolCalls = map[string]*tui.ToolCallView{}
119 i.toolOrder = nil
120 i.toolGate = map[string]int{}
121 i.helpBlock = nil
122 i.extNotes = nil
123 i.parkedTurn = 0
124 i.parkedTotal = 0
125 i.mu.Unlock()
126 i.invalidate()
127}
128func (i *Interactive) SetSubagentSessionScope(_ string) {
129 i.invalidate()
130}
131func (i *Interactive) ApplyChangedCWD(ag *core.Agent, provider, model, cwd string) {
132 i.applyChangedCWD(ag, provider, model, cwd, nil)
133}
134func (i *Interactive) ApplyChangedCWDWithStartupContext(ag *core.Agent, provider, model, cwd string, startupContextPaths []string) {
135 i.applyChangedCWD(ag, provider, model, cwd, startupContextPaths)
136}
137func (i *Interactive) applyChangedCWD(ag *core.Agent, provider, model, cwd string, startupContextPaths []string) {
138 home, _ := os.UserHomeDir()
139 profiles, _ := subagents.Discover(cwd, home)
140 subagentsAddendum := subagents.SystemPromptAddendum(profiles)
141
142 i.agentMu.Lock()
143 defer i.agentMu.Unlock()
144 i.mu.Lock()
145 i.prepareReplacementAgentLocked(ag)
146 i.resetCompactContinuationLocked()
147 i.agent = ag
148 i.cfg.CWD = cwd
149 i.cfg.SubagentsSystemAddendum = subagentsAddendum
150 i.managedAutoSubagentsAddenda = autoSubagentsAddenda(i.cfg, i.autoSubagentsEnabledLocked())
151 i.cfg.StartupContextPaths = append([]string(nil), startupContextPaths...)
152 i.view.StartupContextPaths = nil
153 i.view.InvalidateRenderCache()
154 if i.cfg.ShowInstructionsAtStartup != nil && *i.cfg.ShowInstructionsAtStartup {
155 i.view.StartupContextPaths = append(i.view.StartupContextPaths, startupContextPaths...)
156 }
157 // Re-report the working directory to the terminal so "new tab here"
158 // tracks the /cd change (OSC 7, see issue #38).
159 if i.cfg.Terminal != nil {
160 if seq := tui.ReportCWD(cwd); seq != "" {
161 _, _ = i.cfg.Terminal.Write([]byte(seq))
162 }
163 }
164 i.cfg.Provider = provider
165 i.cfg.Model = model
166 titleCancel := i.titleCancel
167 i.titleCancel = nil
168 i.titleVersion++
169 i.sessionTitle = ""
170 i.titleRealPromptSeen = false
171 i.titleGenerationStarted = false
172 i.writeTerminalTitleLocked("")
173 i.toolCalls = map[string]*tui.ToolCallView{}
174 i.toolOrder = nil
175 i.toolGate = map[string]int{}
176 i.helpBlock = nil
177 i.parkedTurn = 0
178 i.statusErr = ""
179 i.mu.Unlock()
180 if titleCancel != nil {
181 titleCancel()
182 }
183 i.fileSuggest.Reset()
184 i.fileSuggest.SetCWD(cwd)
185 i.invalidate()
186}
187func (i *Interactive) SubmitSlash(text string) {
188 i.mu.Lock()
189 i.doubleEscape.Reset()
190 i.mu.Unlock()
191 text = strings.TrimSpace(text)
192 if !strings.HasPrefix(text, "/") {
193 return
194 }
195 if slashCommandCancelsTurn(text) {
196 i.cancelAndWaitForIdle()
197 }
198 i.runSlash(i.runCtx, text)
199 i.invalidate()
200}
201func (i *Interactive) SubmitOrQueue(text string, images []provider.ImageBlock) {
202 i.submitOrQueue(text, images, true)
203}
204func (i *Interactive) submitOrQueue(text string, images []provider.ImageBlock, userInput bool) {
205 if cmd, ok := shellEscapeCommand(text); ok {
206 i.startShellEscape(i.runCtx, cmd)
207 return
208 }
209 i.mu.Lock()
210 if i.agent == nil {
211 i.statusErr = "not logged in. type /login first."
212 i.mu.Unlock()
213 i.invalidate()
214 return
215 }
216 i.mu.Unlock()
217 if userInput && i.cfg.EnsureMission != nil {
218 if err := i.cfg.EnsureMission(text); err != nil {
219 i.ReportError(fmt.Errorf("persist mission: %w", err))
220 return
221 }
222 }
223 // User input is an orchestration event, not merely a queue append. When
224 // the manager is dormant behind a sealed worker wave, the coordinator makes
225 // this the next manager turn and carries any completed worker summary with it.
226 if userInput && i.coordinatorAcceptsUserInput() {
227 actions := i.applyCoordinator(orchestration.Event{Kind: orchestration.EventUserInput, Text: text})
228 i.executeCoordinatorActions(actions)
229 // The coordinator has accepted the input for its sealed worker wave.
230 // It may intentionally defer an action until pending workers finish;
231 // falling through would start a normal turn and discard that wave.
232 return
233 }
234 i.maybeStartSessionTitle(i.runCtx, text)
235 i.mu.Lock()
236 if i.busy {
237 // Queue text only; images are dropped for queued prompts. Keep the
238 // interactive mutex held through Agent.QueueMessage so turn teardown
239 // cannot inspect the agent queue between the busy check and enqueue.
240 // Compaction uses the host queue because it has no active agent loop
241 // to drain Agent.QueueMessage entries.
242 var handoff json.RawMessage
243 var persistHandoff bool
244 if i.agent != nil && !i.compacting {
245 handoff, persistHandoff = i.resetCompactContinuationLocked()
246 i.agent.QueueMessage(text)
247 } else {
248 handoff, persistHandoff = i.resetCompactContinuationLocked()
249 i.queued = append(i.queued, text)
250 }
251 i.mu.Unlock()
252 if persistHandoff {
253 i.persistCompactHandoff(handoff)
254 }
255 i.invalidate()
256 return
257 }
258 i.mu.Unlock()
259 i.startTurnWithImages(i.runCtx, text, images)
260}
261func (i *Interactive) ChangelogVersion() string {
262 if i.changelogDialog != nil {
263 return i.changelogDialog.version
264 }
265 return ""
266}
267func (i *Interactive) CancelTurn() {
268 i.mu.Lock()
269 cancel := i.cancelTurn
270 i.mu.Unlock()
271 if cancel != nil {
272 i.cancelCoordinator()
273
274 i.mu.Lock()
275 handoff, persistHandoff := i.resetCompactContinuationLocked()
276 i.mu.Unlock()
277 cancel()
278 i.confirmDialog.CancelAll("turn cancelled")
279 if persistHandoff {
280 i.persistCompactHandoff(handoff)
281 }
282 }
283}
284func (i *Interactive) Insert(text string) {
285 i.ed.Insert(text)
286 i.invalidate()
287}
288func (i *Interactive) Display(extName, text string) {
289 i.appendExtensionNote(extName, text, "info")
290 i.invalidate()
291}
292func (i *Interactive) ReportError(err error) {
293 if err == nil {
294 return
295 }
296 i.mu.Lock()
297 i.statusOK = ""
298 i.statusErr = err.Error()
299 i.mu.Unlock()
300 i.invalidate()
301}
302func (i *Interactive) SetStatus(extName, key, level, text string) {
303 if strings.TrimSpace(extName) == "" || strings.TrimSpace(key) == "" {
304 return
305 }
306 i.mu.Lock()
307 if i.extStatuses == nil {
308 i.extStatuses = map[string]map[string]extensionStatus{}
309 }
310 if strings.TrimSpace(text) == "" {
311 if items := i.extStatuses[extName]; items != nil {
312 delete(items, key)
313 if len(items) == 0 {
314 delete(i.extStatuses, extName)
315 }
316 }
317 } else {
318 if i.extStatuses[extName] == nil {
319 i.extStatuses[extName] = map[string]extensionStatus{}
320 }
321 i.extStatuses[extName][key] = extensionStatus{Level: level, Text: text}
322 }
323 i.mu.Unlock()
324 i.invalidate()
325}
326func (i *Interactive) SetWidget(extName, id, position, title string, lines []string) {
327 if strings.TrimSpace(extName) == "" || strings.TrimSpace(id) == "" {
328 return
329 }
330 position = extproto.NormalizeWidgetPosition(position)
331 i.mu.Lock()
332 if i.extWidgets == nil {
333 i.extWidgets = map[string]map[string]extensionWidget{}
334 }
335 if i.extWidgets[extName] == nil {
336 i.extWidgets[extName] = map[string]extensionWidget{}
337 }
338 i.extWidgets[extName][id] = extensionWidget{
339 Position: position,
340 Title: title,
341 Lines: append([]string(nil), lines...),
342 }
343 i.mu.Unlock()
344 i.invalidate()
345}
346func (i *Interactive) ClearWidget(extName, id string) {
347 i.mu.Lock()
348 if items := i.extWidgets[extName]; items != nil {
349 delete(items, id)
350 if len(items) == 0 {
351 delete(i.extWidgets, extName)
352 }
353 }
354 i.mu.Unlock()
355 i.invalidate()
356}
357func (i *Interactive) ClearExtensionChrome(extName string) {
358 if strings.TrimSpace(extName) == "" {
359 return
360 }
361 marker := "[" + extName + "] "
362 i.mu.Lock()
363 changed := false
364 if _, ok := i.extStatuses[extName]; ok {
365 delete(i.extStatuses, extName)
366 changed = true
367 }
368 if _, ok := i.extWidgets[extName]; ok {
369 delete(i.extWidgets, extName)
370 changed = true
371 }
372 if len(i.extNotes) > 0 {
373 kept := i.extNotes[:0:0]
374 for _, line := range i.extNotes {
375 if strings.Contains(line, marker) {
376 changed = true
377 continue
378 }
379 kept = append(kept, line)
380 }
381 i.extNotes = kept
382 }
383 if i.extPanel != nil && i.extPanel.Active() && i.extPanel.ext == extName {
384 i.extPanel.Close()
385 changed = true
386 }
387 i.mu.Unlock()
388 if changed {
389 i.invalidate()
390 }
391}
392func (i *Interactive) OpenPanel(extName string, spec extproto.PanelSpec) {
393 i.mu.Lock()
394 defer i.mu.Unlock()
395 i.extPanel.Open(extName, spec.ID, spec.Title, spec.Lines, spec.Footer)
396 i.confirmDialog.Blur()
397 if i.cfg.Extensions != nil {
398 cols, rows := i.cfg.Terminal.Size()
399 _ = cols
400 _ = rows
401 }
402 i.invalidate()
403}
404func (i *Interactive) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
405 i.mu.Lock()
406 defer i.mu.Unlock()
407 if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
408 i.extPanel.Update(title, lines, footer)
409 i.invalidate()
410 }
411}
412func (i *Interactive) ClosePanel(extName, panelID string) {
413 i.mu.Lock()
414 defer i.mu.Unlock()
415 if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
416 i.extPanel.Close()
417 i.invalidate()
418 }
419}