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