|
| 1 | +package engine |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "sort" |
| 6 | + |
| 7 | + "github.com/GrayCodeAI/hawk/internal/types" |
| 8 | +) |
| 9 | + |
| 10 | +// Two-tier context management (adopted from herm): before compacting, "clear" |
| 11 | +// the content of old tool results into a short placeholder to reclaim context |
| 12 | +// gently. The tool_use blocks are left intact, so the model still knows what was |
| 13 | +// called, and can re-read files if needed. Only when clearing is insufficient |
| 14 | +// does the compaction strategy chain run. |
| 15 | + |
| 16 | +const ( |
| 17 | + // clearThresholdFraction is the fraction of the context window at which old |
| 18 | + // tool results start getting cleared. 0.8 = clear when input tokens > 80%. |
| 19 | + clearThresholdFraction = 0.8 |
| 20 | + // clearKeepRecent is the number of most-recent tool-result messages kept intact. |
| 21 | + clearKeepRecent = 4 |
| 22 | + // outputClearedPlaceholder replaces cleared tool-result content. |
| 23 | + outputClearedPlaceholder = "[output cleared]" |
| 24 | +) |
| 25 | + |
| 26 | +// clearOldToolResults returns a copy of msgs with the content of old tool |
| 27 | +// results replaced by a short placeholder, biggest-first, keeping the most |
| 28 | +// recent clearKeepRecent tool-result messages intact, until estimatedTokens |
| 29 | +// drops below threshold. It returns the new messages and the estimated tokens |
| 30 | +// freed. Adopted from herm's clearOldToolResults. |
| 31 | +func clearOldToolResults(msgs []types.EyrieMessage, estimatedTokens, threshold int) ([]types.EyrieMessage, int) { |
| 32 | + if threshold <= 0 || estimatedTokens <= 0 || len(msgs) == 0 { |
| 33 | + return msgs, 0 |
| 34 | + } |
| 35 | + type candidate struct { |
| 36 | + idx int |
| 37 | + size int |
| 38 | + } |
| 39 | + var candidates []candidate |
| 40 | + for i := range msgs { |
| 41 | + if size := toolResultBytes(msgs[i]); size > 0 { |
| 42 | + candidates = append(candidates, candidate{idx: i, size: size}) |
| 43 | + } |
| 44 | + } |
| 45 | + if len(candidates) <= clearKeepRecent { |
| 46 | + return msgs, 0 |
| 47 | + } |
| 48 | + clearable := candidates[:len(candidates)-clearKeepRecent] |
| 49 | + sort.Slice(clearable, func(i, j int) bool { return clearable[i].size > clearable[j].size }) |
| 50 | + |
| 51 | + out := cloneToolResults(msgs) |
| 52 | + tokens := estimatedTokens |
| 53 | + freed := 0 |
| 54 | + for _, c := range clearable { |
| 55 | + if tokens < threshold { |
| 56 | + break |
| 57 | + } |
| 58 | + f := clearMessageToolResults(&out[c.idx]) |
| 59 | + if f == 0 { |
| 60 | + continue |
| 61 | + } |
| 62 | + tokens -= f |
| 63 | + freed += f |
| 64 | + } |
| 65 | + return out, freed |
| 66 | +} |
| 67 | + |
| 68 | +// ClearOldToolResults is the session-level entry point: it clears old tool |
| 69 | +// results when token usage crosses 80% of the context window. Returns true when |
| 70 | +// anything was cleared. It is a gentler tier below compaction. |
| 71 | +func (s *Session) ClearOldToolResults(ctx context.Context) bool { |
| 72 | + if s == nil { |
| 73 | + return false |
| 74 | + } |
| 75 | + raw := s.Persistence().RawMessages() |
| 76 | + if len(raw) == 0 { |
| 77 | + return false |
| 78 | + } |
| 79 | + window := s.ContextWindowSize() |
| 80 | + if window <= 0 { |
| 81 | + return false |
| 82 | + } |
| 83 | + tokens := EstimateTokens(raw) |
| 84 | + threshold := int(float64(window) * clearThresholdFraction) |
| 85 | + if tokens < threshold { |
| 86 | + return false |
| 87 | + } |
| 88 | + cleared, freed := clearOldToolResults(raw, tokens, threshold) |
| 89 | + if freed > 0 { |
| 90 | + s.Persistence().SetRawMessages(cleared) |
| 91 | + return true |
| 92 | + } |
| 93 | + return false |
| 94 | +} |
| 95 | + |
| 96 | +// toolResultBytes returns the total byte size of a message's tool results. |
| 97 | +func toolResultBytes(m types.EyrieMessage) int { |
| 98 | + total := 0 |
| 99 | + for _, tr := range m.ToolResults { |
| 100 | + total += len(tr.Content) |
| 101 | + } |
| 102 | + return total |
| 103 | +} |
| 104 | + |
| 105 | +// clearMessageToolResults replaces each non-empty tool-result content with the |
| 106 | +// placeholder and returns the estimated tokens freed (~4 bytes per token). |
| 107 | +func clearMessageToolResults(m *types.EyrieMessage) int { |
| 108 | + freedBytes := 0 |
| 109 | + for i := range m.ToolResults { |
| 110 | + c := m.ToolResults[i].Content |
| 111 | + if c == "" || c == outputClearedPlaceholder { |
| 112 | + continue |
| 113 | + } |
| 114 | + freedBytes += len(c) - len(outputClearedPlaceholder) |
| 115 | + m.ToolResults[i].Content = outputClearedPlaceholder |
| 116 | + } |
| 117 | + return freedBytes / 4 |
| 118 | +} |
| 119 | + |
| 120 | +// cloneToolResults copies msgs, deep-copying the ToolResults slices so callers |
| 121 | +// can mutate the copy without touching the persisted originals. |
| 122 | +func cloneToolResults(msgs []types.EyrieMessage) []types.EyrieMessage { |
| 123 | + out := make([]types.EyrieMessage, len(msgs)) |
| 124 | + for i, m := range msgs { |
| 125 | + out[i] = m |
| 126 | + if m.ToolResults != nil { |
| 127 | + out[i].ToolResults = append([]types.ToolResult(nil), m.ToolResults...) |
| 128 | + } |
| 129 | + } |
| 130 | + return out |
| 131 | +} |
0 commit comments