|
| 1 | +package agent |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/voocel/agentcore" |
| 10 | + "github.com/voocel/agentcore/memory" |
| 11 | +) |
| 12 | + |
| 13 | +type CompactionResult struct { |
| 14 | + Changed bool |
| 15 | + TokensBefore int |
| 16 | + TokensAfter int |
| 17 | + Reason string |
| 18 | +} |
| 19 | + |
| 20 | +const ( |
| 21 | + microcompactThreshold = 40000 |
| 22 | + microcompactMinSaving = 20000 |
| 23 | + largeTextThreshold = 4000 |
| 24 | + microcompactPreserveHead = 1500 |
| 25 | + microcompactPreserveTail = 1500 |
| 26 | + microcompactKeepRecent = 3 |
| 27 | +) |
| 28 | + |
| 29 | +func (s *Session) Compact() (CompactionResult, error) { |
| 30 | + return s.context.compactWithReason("manual") |
| 31 | +} |
| 32 | + |
| 33 | +func (c *sessionContextController) microcompact() bool { |
| 34 | + msgs := c.session.agent.Messages() |
| 35 | + totalTokens := memory.EstimateTotal(msgs) |
| 36 | + if totalTokens < microcompactThreshold { |
| 37 | + return false |
| 38 | + } |
| 39 | + |
| 40 | + type candidate struct { |
| 41 | + idx int |
| 42 | + savings int |
| 43 | + } |
| 44 | + var candidates []candidate |
| 45 | + for i, m := range msgs { |
| 46 | + msg, ok := m.(agentcore.Message) |
| 47 | + if !ok { |
| 48 | + continue |
| 49 | + } |
| 50 | + for _, b := range msg.Content { |
| 51 | + if b.Type == agentcore.ContentText && len([]rune(b.Text)) > largeTextThreshold { |
| 52 | + saved := len(b.Text) - microcompactPreserveHead*3 |
| 53 | + if saved > 0 { |
| 54 | + candidates = append(candidates, candidate{idx: i, savings: saved / 4}) |
| 55 | + } |
| 56 | + break |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + if len(candidates) == 0 { |
| 62 | + return false |
| 63 | + } |
| 64 | + |
| 65 | + protectCount := min(microcompactKeepRecent, len(candidates)) |
| 66 | + eligible := candidates[:len(candidates)-protectCount] |
| 67 | + if len(eligible) == 0 { |
| 68 | + return false |
| 69 | + } |
| 70 | + |
| 71 | + var totalSavings int |
| 72 | + for _, candidate := range eligible { |
| 73 | + totalSavings += candidate.savings |
| 74 | + } |
| 75 | + if totalSavings < microcompactMinSaving { |
| 76 | + return false |
| 77 | + } |
| 78 | + |
| 79 | + eligibleSet := make(map[int]struct{}, len(eligible)) |
| 80 | + for _, candidate := range eligible { |
| 81 | + eligibleSet[candidate.idx] = struct{}{} |
| 82 | + } |
| 83 | + |
| 84 | + newMsgs := make([]agentcore.AgentMessage, len(msgs)) |
| 85 | + for i, m := range msgs { |
| 86 | + if _, ok := eligibleSet[i]; ok { |
| 87 | + if msg, ok := m.(agentcore.Message); ok { |
| 88 | + newMsgs[i] = truncateMessageText(msg) |
| 89 | + continue |
| 90 | + } |
| 91 | + } |
| 92 | + newMsgs[i] = m |
| 93 | + } |
| 94 | + |
| 95 | + if err := c.session.agent.SetMessages(newMsgs); err != nil { |
| 96 | + return false |
| 97 | + } |
| 98 | + return true |
| 99 | +} |
| 100 | + |
| 101 | +func (c *sessionContextController) compactWithReason(reason string) (result CompactionResult, err error) { |
| 102 | + result = CompactionResult{Reason: reason} |
| 103 | + c.session.emit(SessionEvent{Type: SEAutoCompactionStart, CompactionReason: reason}) |
| 104 | + defer func() { |
| 105 | + if err != nil { |
| 106 | + return |
| 107 | + } |
| 108 | + c.session.emit(SessionEvent{ |
| 109 | + Type: SEAutoCompactionEnd, |
| 110 | + CompactionReason: reason, |
| 111 | + CompactionChanged: result.Changed, |
| 112 | + TokensBefore: result.TokensBefore, |
| 113 | + TokensAfter: result.TokensAfter, |
| 114 | + }) |
| 115 | + }() |
| 116 | + |
| 117 | + msgs := c.session.agent.Messages() |
| 118 | + if len(msgs) == 0 { |
| 119 | + return result, nil |
| 120 | + } |
| 121 | + |
| 122 | + tokensBefore := memory.EstimateTotal(msgs) |
| 123 | + result.TokensBefore = tokensBefore |
| 124 | + |
| 125 | + c.session.mu.Lock() |
| 126 | + prov := c.session.provider |
| 127 | + model := c.session.modelName |
| 128 | + ctxWindow := c.session.settings.ContextWindow |
| 129 | + store := c.session.store |
| 130 | + c.session.mu.Unlock() |
| 131 | + |
| 132 | + apiKey, baseURL := c.session.resolveCredentials(prov) |
| 133 | + compactModel, err := c.session.createModel(prov, model, apiKey, baseURL) |
| 134 | + if err != nil { |
| 135 | + return result, fmt.Errorf("create compaction model: %w", err) |
| 136 | + } |
| 137 | + |
| 138 | + transform := memory.NewCompaction(memory.CompactionConfig{ |
| 139 | + Model: compactModel, |
| 140 | + ContextWindow: ctxWindow, |
| 141 | + }) |
| 142 | + |
| 143 | + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) |
| 144 | + defer cancel() |
| 145 | + |
| 146 | + compacted, err := transform(ctx, msgs) |
| 147 | + if err != nil { |
| 148 | + return result, fmt.Errorf("compact context: %w", err) |
| 149 | + } |
| 150 | + |
| 151 | + tokensAfter := memory.EstimateTotal(compacted) |
| 152 | + if tokensAfter >= tokensBefore { |
| 153 | + result.TokensAfter = tokensBefore |
| 154 | + return result, nil |
| 155 | + } |
| 156 | + |
| 157 | + summary, keptRaw := extractCompactionPayload(compacted) |
| 158 | + if summary == "" { |
| 159 | + result.TokensAfter = tokensBefore |
| 160 | + return result, nil |
| 161 | + } |
| 162 | + |
| 163 | + if store != nil { |
| 164 | + if err := store.AppendCompaction(summary, keptRaw); err != nil { |
| 165 | + return result, fmt.Errorf("append compaction entry: %w", err) |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + if err := c.session.agent.SetMessages(compacted); err != nil { |
| 170 | + return result, fmt.Errorf("set compacted messages: %w", err) |
| 171 | + } |
| 172 | + result.Changed = true |
| 173 | + result.TokensAfter = tokensAfter |
| 174 | + return result, nil |
| 175 | +} |
| 176 | + |
| 177 | +func extractCompactionPayload(msgs []agentcore.AgentMessage) (string, []json.RawMessage) { |
| 178 | + var summary string |
| 179 | + start := -1 |
| 180 | + for i, m := range msgs { |
| 181 | + cs, ok := m.(memory.CompactionSummary) |
| 182 | + if !ok { |
| 183 | + continue |
| 184 | + } |
| 185 | + summary = cs.Summary |
| 186 | + start = i + 1 |
| 187 | + break |
| 188 | + } |
| 189 | + if summary == "" || start < 0 || start > len(msgs) { |
| 190 | + return "", nil |
| 191 | + } |
| 192 | + |
| 193 | + var keptRaw []json.RawMessage |
| 194 | + for _, m := range msgs[start:] { |
| 195 | + msg, ok := m.(agentcore.Message) |
| 196 | + if !ok { |
| 197 | + continue |
| 198 | + } |
| 199 | + data, err := json.Marshal(msg) |
| 200 | + if err != nil { |
| 201 | + continue |
| 202 | + } |
| 203 | + keptRaw = append(keptRaw, data) |
| 204 | + } |
| 205 | + return summary, keptRaw |
| 206 | +} |
| 207 | + |
| 208 | +func (c *sessionContextController) checkAutoCompaction() { |
| 209 | + if !c.session.settings.AutoCompaction { |
| 210 | + return |
| 211 | + } |
| 212 | + cu := c.session.agent.ContextUsage() |
| 213 | + if cu == nil || cu.Percent < 80 { |
| 214 | + return |
| 215 | + } |
| 216 | + if _, err := c.compactWithReason("threshold"); err != nil { |
| 217 | + c.session.emit(SessionEvent{ |
| 218 | + Type: SEError, |
| 219 | + Error: fmt.Errorf("auto compact failed: %w", err), |
| 220 | + }) |
| 221 | + } |
| 222 | +} |
| 223 | + |
| 224 | +func truncateMessageText(msg agentcore.Message) agentcore.Message { |
| 225 | + newContent := make([]agentcore.ContentBlock, len(msg.Content)) |
| 226 | + for i, b := range msg.Content { |
| 227 | + if b.Type == agentcore.ContentText && len([]rune(b.Text)) > largeTextThreshold { |
| 228 | + runes := []rune(b.Text) |
| 229 | + head := string(runes[:microcompactPreserveHead]) |
| 230 | + tail := string(runes[len(runes)-microcompactPreserveTail:]) |
| 231 | + trimmed := len(runes) - microcompactPreserveHead - microcompactPreserveTail |
| 232 | + newContent[i] = agentcore.ContentBlock{ |
| 233 | + Type: agentcore.ContentText, |
| 234 | + Text: fmt.Sprintf("%s\n[%d characters trimmed]\n%s", head, trimmed, tail), |
| 235 | + } |
| 236 | + } else { |
| 237 | + newContent[i] = b |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + return agentcore.Message{ |
| 242 | + Role: msg.Role, |
| 243 | + Content: newContent, |
| 244 | + StopReason: msg.StopReason, |
| 245 | + Usage: msg.Usage, |
| 246 | + Metadata: msg.Metadata, |
| 247 | + Timestamp: msg.Timestamp, |
| 248 | + } |
| 249 | +} |
0 commit comments