1package modes
2
3import (
4 "context"
5 "encoding/json"
6 "strings"
7 "unicode"
8 "unicode/utf8"
9
10 "github.com/bnema/zut/packages/agent/tools"
11 "github.com/bnema/zut/packages/core"
12 "github.com/bnema/zut/packages/provider"
13 "github.com/bnema/zut/packages/tui"
14)
15
16func shellEscapeCommand(text string) (string, bool) {
17 return ShellEscapeCommand(text)
18}
19func ShellEscapeCommand(text string) (string, bool) {
20 trimmed := strings.TrimLeft(text, " \t")
21 if !strings.HasPrefix(trimmed, "!") {
22 return "", false
23 }
24 cmd := strings.TrimSpace(strings.TrimPrefix(trimmed, "!"))
25 if cmd == "" {
26 return "", false
27 }
28 return cmd, true
29}
30func (i *Interactive) startShellEscape(parent context.Context, cmd string) {
31 i.mu.Lock()
32 if i.busy || i.shellRunning {
33 i.statusErr = "busy — wait for the current turn to finish before running a shell command"
34 i.statusOK = ""
35 i.mu.Unlock()
36 i.invalidate()
37 return
38 }
39 if parent == nil {
40 parent = i.runCtx
41 }
42 if parent == nil {
43 parent = context.Background()
44 }
45 ctx, cancel := context.WithCancel(parent)
46 i.busy = true
47 i.shellRunning = true
48 i.shellLive = "$ " + cmd + "\n\n"
49 i.cancelTurn = cancel
50 i.statusErr = ""
51 i.statusOK = ""
52 i.spin.Start()
53 i.activity = agentActivity{activity: activity{kind: activityRunningShellCommand}}
54 // Clear stale extension notes the same way a new turn would so the
55 // screen doesn't accumulate transient state.
56 i.extNotes = nil
57 i.scrollOffset = 0
58 i.parkedTurn = 0
59 i.parkedTotal = 0
60 i.helpBlock = nil
61 sandbox := i.cfg.Sandbox
62 cwd := i.cfg.CWD
63 i.mu.Unlock()
64 i.invalidate()
65
66 go func() {
67 defer cancel()
68 raw, _ := json.Marshal(map[string]any{
69 "command": cmd,
70 "timeout": ShellEscapeTimeoutSeconds,
71 })
72 bash := &tools.BashTool{CWD: cwd, Sandbox: sandbox}
73 progress := func(chunk string) {
74 i.mu.Lock()
75 i.shellLive += chunk
76 i.mu.Unlock()
77 i.invalidate()
78 }
79 res, err := bash.Execute(ctx, raw, progress)
80
81 var out string
82 if err != nil {
83 out = "$ " + cmd + "\n\n" + err.Error() + "\n\n[error]"
84 } else {
85 for _, c := range res.Content {
86 if tb, ok := c.(provider.TextBlock); ok {
87 out += tb.Text
88 }
89 }
90 }
91 cancelled := ctx.Err() != nil
92 failed := err != nil || res.IsError || cancelled
93 if cancelled {
94 out += "\n\n[cancelled]"
95 }
96
97 if i.agent != nil {
98 i.agent.AppendUserContext(out, map[string]string{shellEscapeMetaKey: "true"})
99 }
100
101 i.mu.Lock()
102 i.shellRunning = false
103 i.shellLive = ""
104 i.busy = false
105 i.cancelTurn = nil
106 pendingIdleWork := i.takePendingIdleWorkLocked()
107 awaitingPre := i.awaitingStartupPre
108 if failed {
109 if cancelled {
110 i.statusErr = "shell command cancelled"
111 } else {
112 i.statusErr = "shell command failed"
113 }
114 i.statusOK = ""
115 } else {
116 i.statusOK = "shell command finished"
117 i.statusErr = ""
118 }
119 i.mu.Unlock()
120 runPendingIdleWork(pendingIdleWork)
121 i.invalidate()
122 if awaitingPre {
123 i.completeStartupPre()
124 }
125 }()
126}
127func (i *Interactive) startTurn(parent context.Context, prompt string) {
128 i.startTurnWithImages(parent, prompt, nil)
129}
130func (i *Interactive) startTurnWithImages(parent context.Context, prompt string, images []provider.ImageBlock) {
131 i.startTurnRequest(parent, prompt, images, false, false)
132}
133func (i *Interactive) startTurnRequest(parent context.Context, prompt string, images []provider.ImageBlock, continueExisting, overflowRecoveryAttempted bool) {
134 if i.agent == nil {
135 // Text startup pre cannot run without credentials; continue so
136 // deferred InitialInput (pre-fill or auto-submit) still applies.
137 i.mu.Lock()
138 awaitingPre := i.awaitingStartupPre
139 i.mu.Unlock()
140 if awaitingPre {
141 i.completeStartupPre()
142 }
143 return
144 }
145 // Pre-turn safety: if the most recent context measurement is
146 // already past the auto-compact threshold, condense before
147 // sending so the next outbound request stays under the limit.
148 // The condense flow re-fires the user's queued prompt for us, so
149 // we just hand it off and exit.
150 i.mu.Lock()
151 var resetHandoff json.RawMessage
152 var persistResetHandoff bool
153 if !continueExisting {
154 resetHandoff, persistResetHandoff = i.resetCompactContinuationLocked()
155 }
156 needsPreCompact := !overflowRecoveryAttempted && !i.autoCompacting && i.shouldAutoCompactLocked()
157 if needsPreCompact {
158 // Reserve the compaction hand-off before releasing i.mu. A completion
159 // update arriving in the small gap before runCompact acquires the
160 // mutex must join the host queue rather than starting a competing turn.
161 i.busy = true
162 i.compacting = true
163 i.autoCompacting = true
164 if continueExisting {
165 i.continueAfterCompact = true
166 } else {
167 i.pendingCompactPrompt = prompt
168 i.pendingCompactImages = append([]provider.ImageBlock(nil), images...)
169 i.hasPendingCompactPrompt = true
170 }
171 i.statusErr = ""
172 i.extNotes = append(i.extNotes, autoCompactNoteLine(i.cfg.Theme, "context near limit — condensing history before sending..."))
173 i.pendingPostCompactNote = "context auto-compacted; sending your last message"
174 i.mu.Unlock()
175 if persistResetHandoff {
176 i.persistCompactHandoff(resetHandoff)
177 }
178 i.invalidate()
179 i.runCompact(parent, compactContinuationRequest{origin: compactOriginPreTurnThreshold})
180 return
181 }
182 i.mu.Unlock()
183 if persistResetHandoff {
184 i.persistCompactHandoff(resetHandoff)
185 }
186
187 ctx, cancel := context.WithCancel(parent)
188 i.mu.Lock()
189 i.busy = true
190 i.spin.Start()
191 i.activity = newAgentActivity(i.cfg.Provider, i.cfg.Model)
192 i.cancelTurn = cancel
193 i.statusErr = ""
194 i.statusOK = ""
195 i.streaming.Reset()
196 i.streamOn = true
197 i.pendingAlert = nil
198 i.toolCalls = map[string]*tui.ToolCallView{}
199 i.toolOrder = nil
200 i.toolGate = map[string]int{}
201 i.extNotes = nil // ext notes are one-shot; a new prompt clears them
202 i.scrollOffset = 0 // jump back to the bottom on new turn
203 // Lift the resume tail cap once the user starts interacting. The
204 // cap is purely a first-paint optimization (don't markdown the
205 // whole history before showing anything). Keeping it active during
206 // a turn makes the rendered chat a sliding window: appended
207 // messages push older ones off the TOP of the buffer, which the
208 // renderer must treat as a change above the viewport and repaint
209 // fully, snapping the terminal's native scrollback to the bottom on
210 // every streamed chunk. A fresh session has no cap (append-only),
211 // which is why the jump only shows up in resumed sessions. Dropping
212 // the cap here makes resumed turns append-only too.
213 i.view.TailLimit = 0
214 // Reset the auto-follow baseline so the very next render at
215 // interactive.go:1053 doesn't see a synthetic shrink between
216 // "last frame had the previous turn's tool overlay" and
217 // "this frame had it cleared above". Without this, the guard
218 // reads delta = -(rows in cleared overlay) and decrements
219 // scrollOffset, which on terminals that mirror zut's pane
220 // scroll into the host scrollbar visibly yanks the viewport.
221 // See autofollow_shrink_test.go for the exact arithmetic.
222 i.prevChatLen = 0
223 i.prevChatCols = 0
224 i.parkedTurn = 0 // starting a turn clears the /jump parked state
225 i.parkedTotal = 0
226 i.helpBlock = nil // hide the help block once the user asks something
227 i.mu.Unlock()
228 i.invalidate()
229
230 var (
231 lastStop provider.StopReason
232 lastTurnErr error
233 )
234 sink := func(ev core.AgentEvent) {
235 if e, ok := ev.(core.EvTurnEnd); ok {
236 lastStop = e.Stop
237 lastTurnErr = e.Err
238 }
239 i.observeGoalRun(ev)
240 i.handleEventForPresentation(ev)
241 }
242
243 releaseCompletionHold := i.beginCompletionDeliveryHold()
244 go func() {
245 defer releaseCompletionHold()
246 var err error
247 if continueExisting {
248 err = i.agent.Continue(ctx, sink)
249 } else {
250 err = i.agent.Prompt(ctx, prompt, images, sink)
251 }
252 i.mu.Lock()
253 // Keep busy asserted through final cleanup and queue selection. A
254 // watcher may enqueue a completion summary concurrently with the
255 // provider's final event; publishing idle before inspecting queues can
256 // strand that summary in the core agent queue or start an overlapping
257 // turn.
258 // Don't touch streamPending / streamFlushPending here — the
259 // pacer may still be draining the final deltas and needs to
260 // paint them even though Prompt has returned. It will reset
261 // streamOn on its own once the buffer empties.
262 if len(i.streamPending) == 0 {
263 i.streamOn = false
264 }
265 i.cancelTurn = nil
266 pendingIdleWork := i.takePendingIdleWorkLocked()
267 if err != nil && ctx.Err() == nil {
268 i.statusErr = err.Error()
269 }
270 // Decide whether to offer a model rescue picker for recoverable
271 // provider failures (auth/rate/temporary). The picker opens after
272 // the mutex is released so it can take its own locks freely.
273 var (
274 offer bool
275 rescueWhy string
276 rescueImgs []provider.ImageBlock
277 rescueModel string
278 rescueProv string
279 rescueFprov string
280 )
281 if err != nil && ctx.Err() == nil {
282 if ok, reason := classifyRescueError(err); ok {
283 offer = true
284 rescueWhy = reason
285 rescueImgs = images
286 rescueModel = i.cfg.Model
287 rescueProv = i.cfg.Provider
288 rescueFprov = extractFailedProvider(err)
289 if rescueFprov == "" {
290 rescueFprov = i.cfg.Provider
291 }
292 // Suppress the red banner — the rescue dialog already
293 // surfaces the failure.
294 i.statusErr = ""
295 }
296 }
297 // Detect responses that reject the current context, either as an
298 // HTTP 413 payload limit or a model context-window error. Token-
299 // based auto-compact can miss both when metadata is stale or the
300 // limit is measured in raw bytes. Compact once, then continue the
301 // user message already present in the transcript.
302 contextOverflow := err != nil && ctx.Err() == nil && provider.IsContextOverflowError(err)
303 recoverContextOverflow := contextOverflow && !overflowRecoveryAttempted
304 if recoverContextOverflow {
305 i.statusErr = ""
306 i.continueAfterCompact = true
307 i.extNotes = append(i.extNotes, autoCompactNoteLine(i.cfg.Theme, "request was too large. condensing history before retrying ..."))
308 i.pendingPostCompactNote = "context auto-compacted; retrying your last message"
309 }
310 // Persist the assistant's reply (and every tool row before
311 // it) to the session file while the turn memory is hot.
312 // Without this, WriteNewTranscript only fires at zut exit,
313 // meaning a crash or ungraceful kill drops the whole
314 // conversation. FlushSession is idempotent (it advances the
315 // baseline so subsequent flushes only write new rows).
316 flush := i.cfg.FlushSession
317 i.mu.Unlock()
318 runPendingIdleWork(pendingIdleWork)
319 if flush != nil {
320 flush()
321 }
322 terminalGoalError := ctx.Err() == nil && !offer && !recoverContextOverflow && (err != nil || lastTurnErr != nil || lastStop == provider.StopError)
323 if terminalGoalError {
324 i.updateActiveGoal(core.GoalBlocked, "turn ended with an error")
325 }
326 continueGoal := i.finishGoalRun()
327 i.mu.Lock()
328 awaitingPre := i.awaitingStartupPre
329 // A newer explicit prompt may have cleared the handoff while the
330 // completed turn was being flushed. Re-read it under the mutex before
331 // deciding whether this continuation may spend another rescue attempt.
332 statusRescueActive := i.compactContinuation.reason == compactContinuationStatusRescue
333 // Pop the next queued message, if any, and relaunch.
334 var next string
335 var hasNext bool
336 if !awaitingPre && len(i.queued) > 0 && ctx.Err() == nil && err == nil {
337 next, i.queued = i.queued[0], i.queued[1:]
338 hasNext = true
339 }
340 // If the turn was cancelled or errored, drop the queue so the
341 // user isn't bombarded with stale messages after an interrupt.
342 if ctx.Err() != nil || (err != nil && !recoverContextOverflow) {
343 i.queued = nil
344 if i.agent != nil {
345 i.agent.DrainQueuedMessages()
346 }
347 }
348 // Decide whether the next thing to do is an auto-compaction.
349 // Only fires when the turn completed cleanly AND no host-side
350 // or agent-side queued messages are waiting (otherwise a queued
351 // message would race the condense).
352 agentQueued := 0
353 if i.agent != nil {
354 agentQueued = i.agent.QueuedMessageCount()
355 }
356 continueQueued := !awaitingPre && !hasNext && agentQueued > 0 && err == nil && ctx.Err() == nil
357 shouldAutoCompact := !awaitingPre && !hasNext && agentQueued == 0 && err == nil && ctx.Err() == nil && i.shouldAutoCompactLocked()
358 continueStatusRescue := false
359 var handoff json.RawMessage
360 var persistHandoff bool
361 if statusRescueActive && i.agent != nil && !awaitingPre && !hasNext && !continueQueued && !shouldAutoCompact && err == nil && ctx.Err() == nil && lastStop == provider.StopEnd && lastTurnErr == nil {
362 followUpMessages := i.agent.Messages()
363 reason := classifyCompactionContinuation(compactOriginManual, true, lastStop, lastTurnErr, followUpMessages)
364 if reason == compactContinuationStatusRescue && i.compactContinuation.rescueAttempts < maxStatusRescueContinuations {
365 handoff, persistHandoff = i.setCompactContinuationLocked(compactContinuationState{
366 reason: compactContinuationStatusRescue,
367 rescueAttempts: i.compactContinuation.rescueAttempts + 1,
368 })
369 continueStatusRescue = true
370 } else {
371 handoff, persistHandoff = i.resetCompactContinuationLocked()
372 }
373 }
374 if !continueStatusRescue && (i.agent == nil || ctx.Err() != nil || err != nil || awaitingPre || hasNext || continueQueued || offer || recoverContextOverflow || (!shouldAutoCompact && !statusRescueActive)) {
375 handoff, persistHandoff = i.resetCompactContinuationLocked()
376 }
377 // The agent run can finish before the paced final text reaches the
378 // transcript. A compaction replaces that transcript, so it must never
379 // race the still-live stream frame; otherwise stale deltas can repaint
380 // after the replacement and corrupt the scrollback renderer's model.
381 if recoverContextOverflow || shouldAutoCompact {
382 i.resetStreamingStateLocked()
383 }
384 alertReason := mainAlertReason(ctx, err, lastTurnErr, lastStop, awaitingPre, hasNext || agentQueued > 0 || continueGoal, offer, recoverContextOverflow, shouldAutoCompact)
385 i.busy = hasNext || continueQueued || continueStatusRescue || recoverContextOverflow || shouldAutoCompact
386 i.mu.Unlock()
387 if persistHandoff {
388 i.persistCompactHandoff(handoff)
389 }
390 if alertReason != "" {
391 i.scheduleMainAlert(alertReason)
392 }
393 i.invalidate()
394 parent := i.runCtx
395 if parent == nil {
396 parent = context.Background()
397 }
398 if awaitingPre {
399 i.completeStartupPre()
400 return
401 }
402 switch {
403 case hasNext:
404 i.startTurn(parent, next)
405 case continueQueued:
406 i.startTurnRequest(parent, "", nil, true, false)
407 case continueStatusRescue:
408 i.startAutoCompactContinuation(parent)
409 case offer:
410 i.openRescueDialog(rescueProv, rescueFprov, rescueModel, rescueWhy, prompt, rescueImgs)
411 case recoverContextOverflow:
412 i.runCompact(parent, compactContinuationRequest{origin: compactOriginRecovery})
413 case shouldAutoCompact:
414 i.runCompact(parent, compactContinuationRequest{
415 origin: compactOriginAfterTurnThreshold,
416 force: lastStop == provider.StopLength,
417 lastStop: lastStop,
418 turnError: lastTurnErr,
419 })
420 case continueGoal:
421 i.requestGoalContinuationIfIdle(parent)
422 }
423 }()
424}
425func mainAlertReason(ctx context.Context, err, turnErr error, stop provider.StopReason, awaitingPre, hasNext, rescue, recovering, autoCompacting bool) string {
426 if awaitingPre || ctx.Err() != nil || hasNext || recovering || autoCompacting {
427 return ""
428 }
429 if rescue {
430 return "rescue_required"
431 }
432 if stop == provider.StopAborted {
433 return ""
434 }
435 if err != nil || turnErr != nil || stop == provider.StopError {
436 return "agent_error"
437 }
438 if stop == provider.StopLength {
439 return "response_truncated"
440 }
441 return "agent_done"
442}
443func (i *Interactive) openRescueDialog(activeProvider, failedProvider, failedModel, reason, prompt string, images []provider.ImageBlock) {
444 if i.rescueDialog == nil {
445 return
446 }
447 loggedIn := []string{}
448 if i.cfg.LoggedInProviders != nil {
449 loggedIn = i.cfg.LoggedInProviders()
450 }
451 fprov := failedProvider
452 if fprov == "" {
453 fprov = activeProvider
454 }
455 i.mu.Lock()
456 i.pendingRescuePrompt = prompt
457 i.pendingRescueImages = images
458 i.mu.Unlock()
459 i.rescueDialog.Open(failedModel, loggedIn, fprov, failedModel, reason, prompt)
460 i.invalidate()
461}
462func (i *Interactive) applyRescueSelection(prov, model, prompt string) {
463 if model == "" {
464 return
465 }
466 i.applyRescueModelSelection(prov, model)
467 i.mu.Lock()
468 images := i.pendingRescueImages
469 if prompt == "" {
470 prompt = i.pendingRescuePrompt
471 }
472 i.pendingRescuePrompt = ""
473 i.pendingRescueImages = nil
474 i.mu.Unlock()
475 parent := i.runCtx
476 if parent == nil {
477 parent = context.Background()
478 }
479 i.startTurnWithImages(parent, prompt, images)
480}
481func stripAutoCompactNotes(notes []string) []string {
482 if len(notes) == 0 {
483 return notes
484 }
485 out := notes[:0]
486 for _, n := range notes {
487 if strings.Contains(n, "condensing history") {
488 continue
489 }
490 out = append(out, n)
491 }
492 return out
493}
494func autoCompactNoteLine(th tui.Theme, msg string) string {
495 return " " + th.FGColor(th.Warning, "⚠ "+msg)
496}
497func NormalizeAutoCompactThreshold(threshold *int) int {
498 const defaultAutoCompactThreshold = 85
499 if threshold == nil {
500 return defaultAutoCompactThreshold
501 }
502 switch *threshold {
503 case 0, 70, 80, 85, 90, 95:
504 return *threshold
505 default:
506 return defaultAutoCompactThreshold
507 }
508}
509func ShouldAutoCompact(inputTokens, contextWindow, thresholdPercent int) bool {
510 if inputTokens <= 0 || contextWindow <= 0 || thresholdPercent <= 0 {
511 return false
512 }
513 return float64(inputTokens)/float64(contextWindow) >= float64(thresholdPercent)/100
514}
515func classifyCompactionContinuation(origin compactContinuationOrigin, statusRescueActive bool, stop provider.StopReason, turnErr error, msgs []provider.Message) compactContinuationReason {
516 if origin != compactOriginManual && structuralCompactionContinuation(msgs) {
517 return compactContinuationStructuralTail
518 }
519 if (origin != compactOriginAfterTurnThreshold && !statusRescueActive) || stop != provider.StopEnd || turnErr != nil {
520 return compactContinuationNone
521 }
522 if likelyForwardWorkStatus(msgs) {
523 return compactContinuationStatusRescue
524 }
525 return compactContinuationNone
526}
527func structuralCompactionContinuation(msgs []provider.Message) bool {
528 if len(msgs) == 0 {
529 return false
530 }
531 last := msgs[len(msgs)-1]
532 if last.Role != provider.RoleAssistant {
533 return true
534 }
535 hasText := false
536 for _, content := range last.Content {
537 switch block := content.(type) {
538 case provider.ToolCallBlock:
539 return true
540 case provider.TextBlock:
541 if strings.TrimSpace(block.Text) != "" {
542 hasText = true
543 }
544 case provider.ReasoningBlock:
545 // Reasoning without a visible answer is not terminal.
546 default:
547 return true
548 }
549 }
550 return !hasText
551}
552func likelyForwardWorkStatus(msgs []provider.Message) bool {
553 if len(msgs) == 0 {
554 return false
555 }
556 last := msgs[len(msgs)-1]
557 if last.Role != provider.RoleAssistant {
558 return false
559 }
560 var text strings.Builder
561 for _, content := range last.Content {
562 block, ok := content.(provider.TextBlock)
563 if !ok {
564 if _, hasTool := content.(provider.ToolCallBlock); hasTool {
565 return false
566 }
567 continue
568 }
569 if strings.TrimSpace(block.Text) == "" {
570 continue
571 }
572 if text.Len() > 0 {
573 text.WriteByte(' ')
574 }
575 text.WriteString(block.Text)
576 }
577 if text.Len() == 0 {
578 return false
579 }
580 normalized := strings.ToLower(strings.Join(strings.Fields(text.String()), " "))
581 normalized = strings.NewReplacer("’", "'", "‘", "'", "`", "'").Replace(normalized)
582 for _, phrase := range []string{
583 "next i will",
584 "next, i will",
585 "i'll now",
586 "i will now",
587 "i am going to",
588 "i need to continue",
589 "then i will",
590 "then, i will",
591 "i will proceed",
592 } {
593 if containsFutureWorkPhrase(normalized, phrase) {
594 return true
595 }
596 }
597 return false
598}
599func containsFutureWorkPhrase(text, phrase string) bool {
600 for offset := 0; offset < len(text); {
601 index := strings.Index(text[offset:], phrase)
602 if index < 0 {
603 return false
604 }
605 index += offset
606 end := index + len(phrase)
607 if !wordRuneBefore(text, index) && !wordRuneAfter(text, end) {
608 return true
609 }
610 offset = end
611 }
612 return false
613}
614func wordRuneBefore(text string, index int) bool {
615 if index == 0 {
616 return false
617 }
618 rune_, _ := utf8.DecodeLastRuneInString(text[:index])
619 return unicode.IsLetter(rune_) || unicode.IsDigit(rune_) || rune_ == '_'
620}
621func wordRuneAfter(text string, index int) bool {
622 if index == len(text) {
623 return false
624 }
625 rune_, _ := utf8.DecodeRuneInString(text[index:])
626 return unicode.IsLetter(rune_) || unicode.IsDigit(rune_) || rune_ == '_'
627}
628func (i *Interactive) shouldAutoCompactLocked() bool {
629 if i.agent == nil {
630 return false
631 }
632 if i.autoCompacting {
633 return false
634 }
635 m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
636 if err != nil || m.ContextWindow <= 0 {
637 return false
638 }
639 threshold := NormalizeAutoCompactThreshold(i.cfg.AutoCompactThreshold)
640 return ShouldAutoCompact(i.lastCtxInput, m.ContextWindow, threshold)
641}