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.handleEventForPresentation(ev)
240 }
241
242 releaseCompletionHold := i.beginCompletionDeliveryHold()
243 go func() {
244 defer releaseCompletionHold()
245 var err error
246 if continueExisting {
247 err = i.agent.Continue(ctx, sink)
248 } else {
249 err = i.agent.Prompt(ctx, prompt, images, sink)
250 }
251 i.mu.Lock()
252 // Keep busy asserted through final cleanup and queue selection. A
253 // watcher may enqueue a completion summary concurrently with the
254 // provider's final event; publishing idle before inspecting queues can
255 // strand that summary in the core agent queue or start an overlapping
256 // turn.
257 // Don't touch streamPending / streamFlushPending here — the
258 // pacer may still be draining the final deltas and needs to
259 // paint them even though Prompt has returned. It will reset
260 // streamOn on its own once the buffer empties.
261 if len(i.streamPending) == 0 {
262 i.streamOn = false
263 }
264 i.cancelTurn = nil
265 pendingIdleWork := i.takePendingIdleWorkLocked()
266 if err != nil && ctx.Err() == nil {
267 i.statusErr = err.Error()
268 }
269 // Decide whether to offer a model rescue picker for recoverable
270 // provider failures (auth/rate/temporary). The picker opens after
271 // the mutex is released so it can take its own locks freely.
272 var (
273 offer bool
274 rescueWhy string
275 rescueImgs []provider.ImageBlock
276 rescueModel string
277 rescueProv string
278 rescueFprov string
279 )
280 if err != nil && ctx.Err() == nil {
281 if ok, reason := classifyRescueError(err); ok {
282 offer = true
283 rescueWhy = reason
284 rescueImgs = images
285 rescueModel = i.cfg.Model
286 rescueProv = i.cfg.Provider
287 rescueFprov = extractFailedProvider(err)
288 if rescueFprov == "" {
289 rescueFprov = i.cfg.Provider
290 }
291 // Suppress the red banner — the rescue dialog already
292 // surfaces the failure.
293 i.statusErr = ""
294 }
295 }
296 // Detect responses that reject the current context, either as an
297 // HTTP 413 payload limit or a model context-window error. Token-
298 // based auto-compact can miss both when metadata is stale or the
299 // limit is measured in raw bytes. Compact once, then continue the
300 // user message already present in the transcript.
301 contextOverflow := err != nil && ctx.Err() == nil && provider.IsContextOverflowError(err)
302 recoverContextOverflow := contextOverflow && !overflowRecoveryAttempted
303 if recoverContextOverflow {
304 i.statusErr = ""
305 i.continueAfterCompact = true
306 i.extNotes = append(i.extNotes, autoCompactNoteLine(i.cfg.Theme, "request was too large. condensing history before retrying ..."))
307 i.pendingPostCompactNote = "context auto-compacted; retrying your last message"
308 }
309 // Persist the assistant's reply (and every tool row before
310 // it) to the session file while the turn memory is hot.
311 // Without this, WriteNewTranscript only fires at zut exit,
312 // meaning a crash or ungraceful kill drops the whole
313 // conversation. FlushSession is idempotent (it advances the
314 // baseline so subsequent flushes only write new rows).
315 flush := i.cfg.FlushSession
316 i.mu.Unlock()
317 runPendingIdleWork(pendingIdleWork)
318 if flush != nil {
319 flush()
320 }
321 terminalGoalError := ctx.Err() == nil && !offer && !recoverContextOverflow && (err != nil || lastTurnErr != nil || lastStop == provider.StopError)
322 if terminalGoalError {
323 i.updateActiveGoal(core.GoalBlocked, "turn ended with an error")
324 }
325 i.mu.Lock()
326 awaitingPre := i.awaitingStartupPre
327 // A newer explicit prompt may have cleared the handoff while the
328 // completed turn was being flushed. Re-read it under the mutex before
329 // deciding whether this continuation may spend another rescue attempt.
330 statusRescueActive := i.compactContinuation.reason == compactContinuationStatusRescue
331 // Pop the next queued message, if any, and relaunch.
332 var next string
333 var hasNext bool
334 if !awaitingPre && len(i.queued) > 0 && ctx.Err() == nil && err == nil {
335 next, i.queued = i.queued[0], i.queued[1:]
336 hasNext = true
337 }
338 // If the turn was cancelled or errored, drop the queue so the
339 // user isn't bombarded with stale messages after an interrupt.
340 if ctx.Err() != nil || (err != nil && !recoverContextOverflow) {
341 i.queued = nil
342 if i.agent != nil {
343 i.agent.DrainQueuedMessages()
344 }
345 }
346 // Decide whether the next thing to do is an auto-compaction.
347 // Only fires when the turn completed cleanly AND no host-side
348 // or agent-side queued messages are waiting (otherwise a queued
349 // message would race the condense).
350 agentQueued := 0
351 if i.agent != nil {
352 agentQueued = i.agent.QueuedMessageCount()
353 }
354 continueQueued := !awaitingPre && !hasNext && agentQueued > 0 && err == nil && ctx.Err() == nil
355 shouldAutoCompact := !awaitingPre && !hasNext && agentQueued == 0 && err == nil && ctx.Err() == nil && i.shouldAutoCompactLocked()
356 continueStatusRescue := false
357 var handoff json.RawMessage
358 var persistHandoff bool
359 if statusRescueActive && i.agent != nil && !awaitingPre && !hasNext && !continueQueued && !shouldAutoCompact && err == nil && ctx.Err() == nil && lastStop == provider.StopEnd && lastTurnErr == nil {
360 followUpMessages := i.agent.Messages()
361 reason := classifyCompactionContinuation(compactOriginManual, true, lastStop, lastTurnErr, followUpMessages)
362 if reason == compactContinuationStatusRescue && i.compactContinuation.rescueAttempts < maxStatusRescueContinuations {
363 handoff, persistHandoff = i.setCompactContinuationLocked(compactContinuationState{
364 reason: compactContinuationStatusRescue,
365 rescueAttempts: i.compactContinuation.rescueAttempts + 1,
366 })
367 continueStatusRescue = true
368 } else {
369 handoff, persistHandoff = i.resetCompactContinuationLocked()
370 }
371 }
372 if !continueStatusRescue && (i.agent == nil || ctx.Err() != nil || err != nil || awaitingPre || hasNext || continueQueued || offer || recoverContextOverflow || (!shouldAutoCompact && !statusRescueActive)) {
373 handoff, persistHandoff = i.resetCompactContinuationLocked()
374 }
375 // The agent run can finish before the paced final text reaches the
376 // transcript. A compaction replaces that transcript, so it must never
377 // race the still-live stream frame; otherwise stale deltas can repaint
378 // after the replacement and corrupt the scrollback renderer's model.
379 if recoverContextOverflow || shouldAutoCompact {
380 i.resetStreamingStateLocked()
381 }
382 alertReason := mainAlertReason(ctx, err, lastTurnErr, lastStop, awaitingPre, hasNext || agentQueued > 0, offer, recoverContextOverflow, shouldAutoCompact)
383 i.busy = hasNext || continueQueued || continueStatusRescue || recoverContextOverflow || shouldAutoCompact
384 i.mu.Unlock()
385 if persistHandoff {
386 i.persistCompactHandoff(handoff)
387 }
388 if alertReason != "" {
389 i.scheduleMainAlert(alertReason)
390 }
391 i.invalidate()
392 parent := i.runCtx
393 if parent == nil {
394 parent = context.Background()
395 }
396 if awaitingPre {
397 i.completeStartupPre()
398 return
399 }
400 switch {
401 case hasNext:
402 i.startTurn(parent, next)
403 case continueQueued:
404 i.startTurnRequest(parent, "", nil, true, false)
405 case continueStatusRescue:
406 i.startAutoCompactContinuation(parent)
407 case offer:
408 i.openRescueDialog(rescueProv, rescueFprov, rescueModel, rescueWhy, prompt, rescueImgs)
409 case recoverContextOverflow:
410 i.runCompact(parent, compactContinuationRequest{origin: compactOriginRecovery})
411 case shouldAutoCompact:
412 i.runCompact(parent, compactContinuationRequest{
413 origin: compactOriginAfterTurnThreshold,
414 force: lastStop == provider.StopLength,
415 lastStop: lastStop,
416 turnError: lastTurnErr,
417 })
418 }
419 }()
420}
421func mainAlertReason(ctx context.Context, err, turnErr error, stop provider.StopReason, awaitingPre, hasNext, rescue, recovering, autoCompacting bool) string {
422 if awaitingPre || ctx.Err() != nil || hasNext || recovering || autoCompacting {
423 return ""
424 }
425 if rescue {
426 return "rescue_required"
427 }
428 if stop == provider.StopAborted {
429 return ""
430 }
431 if err != nil || turnErr != nil || stop == provider.StopError {
432 return "agent_error"
433 }
434 if stop == provider.StopLength {
435 return "response_truncated"
436 }
437 return "agent_done"
438}
439func (i *Interactive) openRescueDialog(activeProvider, failedProvider, failedModel, reason, prompt string, images []provider.ImageBlock) {
440 if i.rescueDialog == nil {
441 return
442 }
443 loggedIn := []string{}
444 if i.cfg.LoggedInProviders != nil {
445 loggedIn = i.cfg.LoggedInProviders()
446 }
447 fprov := failedProvider
448 if fprov == "" {
449 fprov = activeProvider
450 }
451 i.mu.Lock()
452 i.pendingRescuePrompt = prompt
453 i.pendingRescueImages = images
454 i.mu.Unlock()
455 i.rescueDialog.Open(failedModel, loggedIn, fprov, failedModel, reason, prompt)
456 i.invalidate()
457}
458func (i *Interactive) applyRescueSelection(prov, model, prompt string) {
459 if model == "" {
460 return
461 }
462 i.applyRescueModelSelection(prov, model)
463 i.mu.Lock()
464 images := i.pendingRescueImages
465 if prompt == "" {
466 prompt = i.pendingRescuePrompt
467 }
468 i.pendingRescuePrompt = ""
469 i.pendingRescueImages = nil
470 i.mu.Unlock()
471 parent := i.runCtx
472 if parent == nil {
473 parent = context.Background()
474 }
475 i.startTurnWithImages(parent, prompt, images)
476}
477func stripAutoCompactNotes(notes []string) []string {
478 if len(notes) == 0 {
479 return notes
480 }
481 out := notes[:0]
482 for _, n := range notes {
483 if strings.Contains(n, "condensing history") {
484 continue
485 }
486 out = append(out, n)
487 }
488 return out
489}
490func autoCompactNoteLine(th tui.Theme, msg string) string {
491 return " " + th.FGColor(th.Warning, "⚠ "+msg)
492}
493func NormalizeAutoCompactThreshold(threshold *int) int {
494 const defaultAutoCompactThreshold = 85
495 if threshold == nil {
496 return defaultAutoCompactThreshold
497 }
498 switch *threshold {
499 case 0, 70, 80, 85, 90, 95:
500 return *threshold
501 default:
502 return defaultAutoCompactThreshold
503 }
504}
505func ShouldAutoCompact(inputTokens, contextWindow, thresholdPercent int) bool {
506 if inputTokens <= 0 || contextWindow <= 0 || thresholdPercent <= 0 {
507 return false
508 }
509 return float64(inputTokens)/float64(contextWindow) >= float64(thresholdPercent)/100
510}
511func classifyCompactionContinuation(origin compactContinuationOrigin, statusRescueActive bool, stop provider.StopReason, turnErr error, msgs []provider.Message) compactContinuationReason {
512 if origin != compactOriginManual && structuralCompactionContinuation(msgs) {
513 return compactContinuationStructuralTail
514 }
515 if (origin != compactOriginAfterTurnThreshold && !statusRescueActive) || stop != provider.StopEnd || turnErr != nil {
516 return compactContinuationNone
517 }
518 if likelyForwardWorkStatus(msgs) {
519 return compactContinuationStatusRescue
520 }
521 return compactContinuationNone
522}
523func structuralCompactionContinuation(msgs []provider.Message) bool {
524 if len(msgs) == 0 {
525 return false
526 }
527 last := msgs[len(msgs)-1]
528 if last.Role != provider.RoleAssistant {
529 return true
530 }
531 hasText := false
532 for _, content := range last.Content {
533 switch block := content.(type) {
534 case provider.ToolCallBlock:
535 return true
536 case provider.TextBlock:
537 if strings.TrimSpace(block.Text) != "" {
538 hasText = true
539 }
540 case provider.ReasoningBlock:
541 // Reasoning without a visible answer is not terminal.
542 default:
543 return true
544 }
545 }
546 return !hasText
547}
548func likelyForwardWorkStatus(msgs []provider.Message) bool {
549 if len(msgs) == 0 {
550 return false
551 }
552 last := msgs[len(msgs)-1]
553 if last.Role != provider.RoleAssistant {
554 return false
555 }
556 var text strings.Builder
557 for _, content := range last.Content {
558 block, ok := content.(provider.TextBlock)
559 if !ok {
560 if _, hasTool := content.(provider.ToolCallBlock); hasTool {
561 return false
562 }
563 continue
564 }
565 if strings.TrimSpace(block.Text) == "" {
566 continue
567 }
568 if text.Len() > 0 {
569 text.WriteByte(' ')
570 }
571 text.WriteString(block.Text)
572 }
573 if text.Len() == 0 {
574 return false
575 }
576 normalized := strings.ToLower(strings.Join(strings.Fields(text.String()), " "))
577 normalized = strings.NewReplacer("’", "'", "‘", "'", "`", "'").Replace(normalized)
578 for _, phrase := range []string{
579 "next i will",
580 "next, i will",
581 "i'll now",
582 "i will now",
583 "i am going to",
584 "i need to continue",
585 "then i will",
586 "then, i will",
587 "i will proceed",
588 } {
589 if containsFutureWorkPhrase(normalized, phrase) {
590 return true
591 }
592 }
593 return false
594}
595func containsFutureWorkPhrase(text, phrase string) bool {
596 for offset := 0; offset < len(text); {
597 index := strings.Index(text[offset:], phrase)
598 if index < 0 {
599 return false
600 }
601 index += offset
602 end := index + len(phrase)
603 if !wordRuneBefore(text, index) && !wordRuneAfter(text, end) {
604 return true
605 }
606 offset = end
607 }
608 return false
609}
610func wordRuneBefore(text string, index int) bool {
611 if index == 0 {
612 return false
613 }
614 rune_, _ := utf8.DecodeLastRuneInString(text[:index])
615 return unicode.IsLetter(rune_) || unicode.IsDigit(rune_) || rune_ == '_'
616}
617func wordRuneAfter(text string, index int) bool {
618 if index == len(text) {
619 return false
620 }
621 rune_, _ := utf8.DecodeRuneInString(text[index:])
622 return unicode.IsLetter(rune_) || unicode.IsDigit(rune_) || rune_ == '_'
623}
624func (i *Interactive) shouldAutoCompactLocked() bool {
625 if i.agent == nil {
626 return false
627 }
628 if i.autoCompacting {
629 return false
630 }
631 m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
632 if err != nil || m.ContextWindow <= 0 {
633 return false
634 }
635 threshold := NormalizeAutoCompactThreshold(i.cfg.AutoCompactThreshold)
636 return ShouldAutoCompact(i.lastCtxInput, m.ContextWindow, threshold)
637}