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}
133
134// startQueuedTurn keeps host provenance in the agent queue until injection,
135// including when the next turn first needs pre-turn compaction.
136func (i *Interactive) startQueuedTurn(parent context.Context, message core.QueuedMessage) {
137 if message.HostEvent && i.agent != nil {
138 i.agent.QueuePrompt(message)
139 i.startTurnRequest(parent, "", nil, true, false)
140 return
141 }
142 i.startTurnWithImages(parent, message.Text, message.Images)
143}
144func (i *Interactive) startTurnRequest(parent context.Context, prompt string, images []provider.ImageBlock, continueExisting, overflowRecoveryAttempted bool) {
145 if i.agent == nil {
146 // Text startup pre cannot run without credentials; continue so
147 // deferred InitialInput (pre-fill or auto-submit) still applies.
148 i.mu.Lock()
149 awaitingPre := i.awaitingStartupPre
150 i.mu.Unlock()
151 if awaitingPre {
152 i.completeStartupPre()
153 }
154 return
155 }
156 // Pre-turn safety: if the most recent context measurement is
157 // already past the auto-compact threshold, condense before
158 // sending so the next outbound request stays under the limit.
159 // The condense flow re-fires the user's queued prompt for us, so
160 // we just hand it off and exit.
161 i.mu.Lock()
162 var resetHandoff json.RawMessage
163 var persistResetHandoff bool
164 if !continueExisting {
165 resetHandoff, persistResetHandoff = i.resetCompactContinuationLocked()
166 }
167 needsPreCompact := !overflowRecoveryAttempted && !i.autoCompacting && i.shouldAutoCompactLocked()
168 if needsPreCompact {
169 // Reserve the compaction hand-off before releasing i.mu. A completion
170 // update arriving in the small gap before runCompact acquires the
171 // mutex must join the host queue rather than starting a competing turn.
172 i.busy = true
173 i.compacting = true
174 i.autoCompacting = true
175 if continueExisting {
176 i.continueAfterCompact = true
177 } else {
178 i.pendingCompactPrompt = prompt
179 i.pendingCompactImages = append([]provider.ImageBlock(nil), images...)
180 i.hasPendingCompactPrompt = true
181 }
182 i.statusErr = ""
183 i.extNotes = append(i.extNotes, autoCompactNoteLine(i.cfg.Theme, "context near limit — condensing history before sending..."))
184 i.pendingPostCompactNote = "context auto-compacted; sending your last message"
185 i.mu.Unlock()
186 if persistResetHandoff {
187 i.persistCompactHandoff(resetHandoff)
188 }
189 i.invalidate()
190 i.runCompact(parent, compactContinuationRequest{origin: compactOriginPreTurnThreshold})
191 return
192 }
193 i.mu.Unlock()
194 if persistResetHandoff {
195 i.persistCompactHandoff(resetHandoff)
196 }
197 // Bind a pending Esc interruption to the ordinary user turn that is
198 // actually starting. Queued-while-busy prompts do not consume it; only
199 // this start path does, so the hidden instruction precedes the prompt
200 // that owns the single automatic goal return.
201 if !continueExisting {
202 i.consumeInterruptedGoalPrompt()
203 }
204
205 ctx, cancel := context.WithCancel(parent)
206 i.mu.Lock()
207 i.busy = true
208 i.spin.Start()
209 i.activity = newAgentActivity(i.cfg.Provider, i.cfg.Model)
210 i.cancelTurn = cancel
211 i.statusErr = ""
212 i.statusOK = ""
213 i.streaming.Reset()
214 i.streamOn = true
215 i.pendingAlert = nil
216 i.toolCalls = map[string]*tui.ToolCallView{}
217 i.toolOrder = nil
218 i.toolGate = map[string]int{}
219 i.extNotes = nil // ext notes are one-shot; a new prompt clears them
220 i.scrollOffset = 0 // jump back to the bottom on new turn
221 // Lift the resume tail cap once the user starts interacting. The
222 // cap is purely a first-paint optimization (don't markdown the
223 // whole history before showing anything). Keeping it active during
224 // a turn makes the rendered chat a sliding window: appended
225 // messages push older ones off the TOP of the buffer, which the
226 // renderer must treat as a change above the viewport and repaint
227 // fully, snapping the terminal's native scrollback to the bottom on
228 // every streamed chunk. A fresh session has no cap (append-only),
229 // which is why the jump only shows up in resumed sessions. Dropping
230 // the cap here makes resumed turns append-only too.
231 i.view.TailLimit = 0
232 // Reset the auto-follow baseline so the very next render at
233 // interactive.go:1053 doesn't see a synthetic shrink between
234 // "last frame had the previous turn's tool overlay" and
235 // "this frame had it cleared above". Without this, the guard
236 // reads delta = -(rows in cleared overlay) and decrements
237 // scrollOffset, which on terminals that mirror zut's pane
238 // scroll into the host scrollbar visibly yanks the viewport.
239 // See autofollow_shrink_test.go for the exact arithmetic.
240 i.prevChatLen = 0
241 i.prevChatCols = 0
242 i.parkedTurn = 0 // starting a turn clears the /jump parked state
243 i.parkedTotal = 0
244 i.helpBlock = nil // hide the help block once the user asks something
245 i.mu.Unlock()
246 i.invalidate()
247
248 var (
249 lastStop provider.StopReason
250 lastTurnErr error
251 )
252 sink := func(ev core.AgentEvent) {
253 if e, ok := ev.(core.EvTurnEnd); ok {
254 lastStop = e.Stop
255 lastTurnErr = e.Err
256 }
257 i.observeGoalRun(ev)
258 i.handleEventForPresentation(ev)
259 }
260
261 releaseCompletionHold := i.beginCompletionDeliveryHold()
262 go func() {
263 defer releaseCompletionHold()
264 var err error
265 if continueExisting {
266 err = i.agent.Continue(ctx, sink)
267 } else {
268 err = i.agent.Prompt(ctx, prompt, images, sink)
269 }
270 i.mu.Lock()
271 // Keep busy asserted through final cleanup and queue selection. A
272 // watcher may enqueue a completion summary concurrently with the
273 // provider's final event; publishing idle before inspecting queues can
274 // strand that summary in the core agent queue or start an overlapping
275 // turn.
276 // Don't touch streamPending / streamFlushPending here — the
277 // pacer may still be draining the final deltas and needs to
278 // paint them even though Prompt has returned. It will reset
279 // streamOn on its own once the buffer empties.
280 if len(i.streamPending) == 0 {
281 i.streamOn = false
282 }
283 i.cancelTurn = nil
284 pendingIdleWork := i.takePendingIdleWorkLocked()
285 if err != nil && ctx.Err() == nil {
286 i.statusErr = err.Error()
287 }
288 // Decide whether to offer a model rescue picker for recoverable
289 // provider failures (auth/rate/temporary). The picker opens after
290 // the mutex is released so it can take its own locks freely.
291 var (
292 offer bool
293 rescueWhy string
294 rescueImgs []provider.ImageBlock
295 rescueModel string
296 rescueProv string
297 rescueFprov string
298 )
299 if err != nil && ctx.Err() == nil {
300 if ok, reason := classifyRescueError(err); ok {
301 offer = true
302 rescueWhy = reason
303 rescueImgs = images
304 rescueModel = i.cfg.Model
305 rescueProv = i.cfg.Provider
306 rescueFprov = extractFailedProvider(err)
307 if rescueFprov == "" {
308 rescueFprov = i.cfg.Provider
309 }
310 // Suppress the red banner — the rescue dialog already
311 // surfaces the failure.
312 i.statusErr = ""
313 }
314 }
315 // Detect responses that reject the current context, either as an
316 // HTTP 413 payload limit or a model context-window error. Token-
317 // based auto-compact can miss both when metadata is stale or the
318 // limit is measured in raw bytes. Compact once, then continue the
319 // user message already present in the transcript.
320 contextOverflow := err != nil && ctx.Err() == nil && provider.IsContextOverflowError(err)
321 recoverContextOverflow := contextOverflow && !overflowRecoveryAttempted
322 if recoverContextOverflow {
323 i.statusErr = ""
324 i.continueAfterCompact = true
325 i.extNotes = append(i.extNotes, autoCompactNoteLine(i.cfg.Theme, "request was too large. condensing history before retrying ..."))
326 i.pendingPostCompactNote = "context auto-compacted; retrying your last message"
327 }
328 // Persist the assistant's reply (and every tool row before
329 // it) to the session file while the turn memory is hot.
330 // Without this, WriteNewTranscript only fires at zut exit,
331 // meaning a crash or ungraceful kill drops the whole
332 // conversation. FlushSession is idempotent (it advances the
333 // baseline so subsequent flushes only write new rows).
334 flush := i.cfg.FlushSession
335 i.mu.Unlock()
336 runPendingIdleWork(pendingIdleWork)
337 if flush != nil {
338 flush()
339 }
340 terminalGoalError := ctx.Err() == nil && !offer && !recoverContextOverflow && (err != nil || lastTurnErr != nil || lastStop == provider.StopError)
341 if terminalGoalError {
342 i.updateActiveGoal(core.GoalBlocked, "turn ended with an error")
343 }
344 // A cancelled or failed turn unwinds without scheduling autonomous
345 // work below. Preserve a freshly armed Esc return for the next
346 // ordinary prompt; drop only a return already bound to this turn.
347 if ctx.Err() != nil || err != nil {
348 i.mu.Lock()
349 if state := i.interruptedGoalReturn; state != nil && state.returnAfterTurn {
350 i.interruptedGoalReturn = nil
351 }
352 i.mu.Unlock()
353 }
354 goalContextLimited := lastStop == provider.StopLength
355 // Cancellation is user action, not model inaction: unwind the lease
356 // without consuming the no-progress allowance or stalling the goal.
357 continueGoal := i.finishGoalRunCancelled(goalContextLimited, ctx.Err() != nil)
358 i.mu.Lock()
359 awaitingPre := i.awaitingStartupPre
360 // A newer explicit prompt may have cleared the handoff while the
361 // completed turn was being flushed. Re-read it under the mutex before
362 // deciding whether this continuation may spend another rescue attempt.
363 statusRescueActive := i.compactContinuation.reason == compactContinuationStatusRescue
364 // Pop the next queued message, if any, and relaunch.
365 var next core.QueuedMessage
366 var hasNext bool
367 if !awaitingPre && len(i.queued) > 0 && ctx.Err() == nil && err == nil {
368 next, i.queued = i.queued[0], i.queued[1:]
369 hasNext = true
370 }
371 // If the turn was cancelled or errored, drop ordinary input so the
372 // user isn't bombarded with stale messages after an interrupt.
373 // Scheduler follow-ups deliberately remain: they are distinct turns
374 // whose due time must not let them steer this failed turn.
375 if ctx.Err() != nil || (err != nil && !recoverContextOverflow) {
376 i.discardQueuedMessagesLocked(ctx.Err() == nil)
377 }
378 var scheduled scheduledFollowUp
379 var hasScheduled bool
380 if !awaitingPre && !hasNext && len(i.scheduled) > 0 {
381 scheduled, i.scheduled = i.scheduled[0], i.scheduled[1:]
382 hasScheduled = true
383 }
384 // Decide whether the next thing to do is an auto-compaction.
385 // Only fires when the turn completed cleanly AND no host-side
386 // or agent-side queued messages are waiting (otherwise a queued
387 // message would race the condense).
388 agentQueued := 0
389 if i.agent != nil {
390 agentQueued = i.agent.QueuedMessageCount()
391 }
392 continueQueued := !awaitingPre && !hasNext && agentQueued > 0 && err == nil && ctx.Err() == nil
393 // A truncated autonomous goal needs fresh execution capacity even when
394 // context-usage metadata is absent or below the configured threshold.
395 // Route it through compaction rather than immediately reusing the same
396 // exhausted transcript.
397 goalNeedsFreshContext := continueGoal && goalContextLimited
398 shouldAutoCompact := !awaitingPre && !hasNext && agentQueued == 0 && err == nil && ctx.Err() == nil && (goalNeedsFreshContext || i.shouldAutoCompactLocked())
399 continueStatusRescue := false
400 var handoff json.RawMessage
401 var persistHandoff bool
402 if goalNeedsFreshContext {
403 // Persist ownership before compaction starts. If the process exits
404 // while condensing, session resume repeats compaction before it
405 // provisions a fresh leased goal turn.
406 handoff, persistHandoff = i.setCompactContinuationLocked(compactContinuationState{reason: compactContinuationGoalCompactionPending})
407 }
408 if statusRescueActive && i.agent != nil && !awaitingPre && !hasNext && !continueQueued && !shouldAutoCompact && err == nil && ctx.Err() == nil && lastStop == provider.StopEnd && lastTurnErr == nil {
409 followUpMessages := i.agent.Messages()
410 reason := classifyCompactionContinuation(compactOriginManual, true, lastStop, lastTurnErr, followUpMessages)
411 if reason == compactContinuationStatusRescue && i.compactContinuation.rescueAttempts < maxStatusRescueContinuations {
412 handoff, persistHandoff = i.setCompactContinuationLocked(compactContinuationState{
413 reason: compactContinuationStatusRescue,
414 rescueAttempts: i.compactContinuation.rescueAttempts + 1,
415 })
416 continueStatusRescue = true
417 } else {
418 handoff, persistHandoff = i.resetCompactContinuationLocked()
419 }
420 }
421 if !continueStatusRescue && (i.agent == nil || ctx.Err() != nil || err != nil || awaitingPre || hasNext || hasScheduled || continueQueued || offer || recoverContextOverflow || (!shouldAutoCompact && !statusRescueActive)) {
422 handoff, persistHandoff = i.resetCompactContinuationLocked()
423 }
424 // The agent run can finish before the paced final text reaches the
425 // transcript. A compaction replaces that transcript, so it must never
426 // race the still-live stream frame; otherwise stale deltas can repaint
427 // after the replacement and corrupt the scrollback renderer's model.
428 if recoverContextOverflow || shouldAutoCompact {
429 i.resetStreamingStateLocked()
430 }
431 // A clean ordinary turn that owns a pending Esc return resumes the
432 // same still-active goal exactly once through the existing scheduler.
433 // It yields to every existing priority above; terminal, paused, or
434 // replaced goals never resume because the match check fails.
435 interruptedReturn := false
436 if err == nil && ctx.Err() == nil && !awaitingPre && !hasNext && !hasScheduled && !continueQueued && !offer && !recoverContextOverflow && !shouldAutoCompact && !continueStatusRescue && !continueGoal {
437 state := i.interruptedGoalReturn
438 if state != nil && state.returnAfterTurn && i.interruptedGoalMatchesLocked() {
439 // Consume only after matching: the match helper reads the
440 // state being consumed.
441 i.interruptedGoalReturn = nil
442 interruptedReturn = true
443 }
444 } else if ctx.Err() == nil && err == nil {
445 // Another follow-up won this turn: keep an armed-but-unbound
446 // interruption pending without consuming the one-shot return.
447 // A bound return that lost priority is inert until replaced.
448 if state := i.interruptedGoalReturn; state != nil && state.returnAfterTurn {
449 i.interruptedGoalReturn = nil
450 }
451 }
452 alertReason := mainAlertReason(ctx, err, lastTurnErr, lastStop, awaitingPre, hasNext || hasScheduled || agentQueued > 0 || continueGoal || interruptedReturn, offer, recoverContextOverflow, shouldAutoCompact)
453 // interruptedReturn already reserves the turn slot (like the
454 // compact handoff path below): the reserved continuation owns
455 // busy and must not re-enter the idle gate.
456 i.busy = hasNext || hasScheduled || continueQueued || continueStatusRescue || recoverContextOverflow || shouldAutoCompact || interruptedReturn
457 i.mu.Unlock()
458 if persistHandoff {
459 i.persistCompactHandoff(handoff)
460 }
461 if alertReason != "" {
462 i.scheduleMainAlert(alertReason)
463 }
464 i.invalidate()
465 parent := i.runCtx
466 if parent == nil {
467 parent = context.Background()
468 }
469 if awaitingPre {
470 i.completeStartupPre()
471 return
472 }
473 switch {
474 case hasNext:
475 i.startQueuedTurn(parent, next)
476 case hasScheduled:
477 // The scheduler holds the session transition read lock until this
478 // acknowledgement, so accepting here binds the prompt to the agent
479 // that just completed rather than a subsequently loaded session.
480 scheduled.accepted <- nil
481 i.startTurn(parent, scheduled.text)
482 case continueQueued:
483 i.startTurnRequest(parent, "", nil, true, false)
484 case continueStatusRescue:
485 i.startAutoCompactContinuation(parent)
486 case offer:
487 i.openRescueDialog(rescueProv, rescueFprov, rescueModel, rescueWhy, prompt, rescueImgs)
488 case recoverContextOverflow:
489 i.runCompact(parent, compactContinuationRequest{origin: compactOriginRecovery})
490 case shouldAutoCompact:
491 i.runCompact(parent, compactContinuationRequest{
492 origin: compactOriginAfterTurnThreshold,
493 force: lastStop == provider.StopLength,
494 lastStop: lastStop,
495 turnError: lastTurnErr,
496 })
497 case continueGoal:
498 i.requestGoalContinuationIfIdle(parent)
499 case interruptedReturn:
500 // busy is already reserved above; use the reserved entry point
501 // so the one-shot return cannot fail the idle gate and leak
502 // the reservation.
503 i.startReservedGoalContinuation(parent)
504 }
505 }()
506}
507func mainAlertReason(ctx context.Context, err, turnErr error, stop provider.StopReason, awaitingPre, hasNext, rescue, recovering, autoCompacting bool) string {
508 if awaitingPre || ctx.Err() != nil || hasNext || recovering || autoCompacting {
509 return ""
510 }
511 if rescue {
512 return "rescue_required"
513 }
514 if stop == provider.StopAborted {
515 return ""
516 }
517 if err != nil || turnErr != nil || stop == provider.StopError {
518 return "agent_error"
519 }
520 if stop == provider.StopLength {
521 return "response_truncated"
522 }
523 return "agent_done"
524}
525func (i *Interactive) openRescueDialog(activeProvider, failedProvider, failedModel, reason, prompt string, images []provider.ImageBlock) {
526 if i.rescueDialog == nil {
527 return
528 }
529 loggedIn := []string{}
530 if i.cfg.LoggedInProviders != nil {
531 loggedIn = i.cfg.LoggedInProviders()
532 }
533 fprov := failedProvider
534 if fprov == "" {
535 fprov = activeProvider
536 }
537 i.mu.Lock()
538 i.pendingRescuePrompt = prompt
539 i.pendingRescueImages = images
540 i.mu.Unlock()
541 i.rescueDialog.Open(failedModel, loggedIn, fprov, failedModel, reason, prompt)
542 i.invalidate()
543}
544func (i *Interactive) applyRescueSelection(prov, model, prompt string) {
545 if model == "" {
546 return
547 }
548 i.applyRescueModelSelection(prov, model)
549 i.mu.Lock()
550 images := i.pendingRescueImages
551 if prompt == "" {
552 prompt = i.pendingRescuePrompt
553 }
554 i.pendingRescuePrompt = ""
555 i.pendingRescueImages = nil
556 i.mu.Unlock()
557 parent := i.runCtx
558 if parent == nil {
559 parent = context.Background()
560 }
561 i.startTurnWithImages(parent, prompt, images)
562}
563func stripAutoCompactNotes(notes []string) []string {
564 if len(notes) == 0 {
565 return notes
566 }
567 out := notes[:0]
568 for _, n := range notes {
569 if strings.Contains(n, "condensing history") {
570 continue
571 }
572 out = append(out, n)
573 }
574 return out
575}
576func autoCompactNoteLine(th tui.Theme, msg string) string {
577 return " " + th.FGColor(th.Warning, "⚠ "+msg)
578}
579func NormalizeAutoCompactThreshold(threshold *int) int {
580 const defaultAutoCompactThreshold = 85
581 if threshold == nil {
582 return defaultAutoCompactThreshold
583 }
584 switch *threshold {
585 case 0, 70, 80, 85, 90, 95:
586 return *threshold
587 default:
588 return defaultAutoCompactThreshold
589 }
590}
591func ShouldAutoCompact(inputTokens, contextWindow, thresholdPercent int) bool {
592 if inputTokens <= 0 || contextWindow <= 0 || thresholdPercent <= 0 {
593 return false
594 }
595 return float64(inputTokens)/float64(contextWindow) >= float64(thresholdPercent)/100
596}
597func classifyCompactionContinuation(origin compactContinuationOrigin, statusRescueActive bool, stop provider.StopReason, turnErr error, msgs []provider.Message) compactContinuationReason {
598 if origin != compactOriginManual && structuralCompactionContinuation(msgs) {
599 return compactContinuationStructuralTail
600 }
601 if (origin != compactOriginAfterTurnThreshold && !statusRescueActive) || stop != provider.StopEnd || turnErr != nil {
602 return compactContinuationNone
603 }
604 if likelyForwardWorkStatus(msgs) {
605 return compactContinuationStatusRescue
606 }
607 return compactContinuationNone
608}
609func structuralCompactionContinuation(msgs []provider.Message) bool {
610 if len(msgs) == 0 {
611 return false
612 }
613 last := msgs[len(msgs)-1]
614 if last.Role != provider.RoleAssistant {
615 return true
616 }
617 hasText := false
618 for _, content := range last.Content {
619 switch block := content.(type) {
620 case provider.ToolCallBlock:
621 return true
622 case provider.TextBlock:
623 if strings.TrimSpace(block.Text) != "" {
624 hasText = true
625 }
626 case provider.ReasoningBlock:
627 // Reasoning without a visible answer is not terminal.
628 default:
629 return true
630 }
631 }
632 return !hasText
633}
634func likelyForwardWorkStatus(msgs []provider.Message) bool {
635 if len(msgs) == 0 {
636 return false
637 }
638 last := msgs[len(msgs)-1]
639 if last.Role != provider.RoleAssistant {
640 return false
641 }
642 var text strings.Builder
643 for _, content := range last.Content {
644 block, ok := content.(provider.TextBlock)
645 if !ok {
646 if _, hasTool := content.(provider.ToolCallBlock); hasTool {
647 return false
648 }
649 continue
650 }
651 if strings.TrimSpace(block.Text) == "" {
652 continue
653 }
654 if text.Len() > 0 {
655 text.WriteByte(' ')
656 }
657 text.WriteString(block.Text)
658 }
659 if text.Len() == 0 {
660 return false
661 }
662 normalized := strings.ToLower(strings.Join(strings.Fields(text.String()), " "))
663 normalized = strings.NewReplacer("’", "'", "‘", "'", "`", "'").Replace(normalized)
664 for _, phrase := range []string{
665 "next i will",
666 "next, i will",
667 "i'll now",
668 "i will now",
669 "i am going to",
670 "i need to continue",
671 "then i will",
672 "then, i will",
673 "i will proceed",
674 } {
675 if containsFutureWorkPhrase(normalized, phrase) {
676 return true
677 }
678 }
679 return false
680}
681func containsFutureWorkPhrase(text, phrase string) bool {
682 for offset := 0; offset < len(text); {
683 index := strings.Index(text[offset:], phrase)
684 if index < 0 {
685 return false
686 }
687 index += offset
688 end := index + len(phrase)
689 if !wordRuneBefore(text, index) && !wordRuneAfter(text, end) {
690 return true
691 }
692 offset = end
693 }
694 return false
695}
696func wordRuneBefore(text string, index int) bool {
697 if index == 0 {
698 return false
699 }
700 rune_, _ := utf8.DecodeLastRuneInString(text[:index])
701 return unicode.IsLetter(rune_) || unicode.IsDigit(rune_) || rune_ == '_'
702}
703func wordRuneAfter(text string, index int) bool {
704 if index == len(text) {
705 return false
706 }
707 rune_, _ := utf8.DecodeRuneInString(text[index:])
708 return unicode.IsLetter(rune_) || unicode.IsDigit(rune_) || rune_ == '_'
709}
710func (i *Interactive) shouldAutoCompactLocked() bool {
711 if i.agent == nil {
712 return false
713 }
714 if i.autoCompacting {
715 return false
716 }
717 m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
718 if err != nil || m.ContextWindow <= 0 {
719 return false
720 }
721 threshold := NormalizeAutoCompactThreshold(i.cfg.AutoCompactThreshold)
722 return ShouldAutoCompact(i.lastCtxInput, m.ContextWindow, threshold)
723}