1package core
2
3import (
4 "context"
5 "fmt"
6 "strconv"
7 "strings"
8 "time"
9
10 "github.com/patriceckhart/zot/packages/provider"
11)
12
13// Compact summarizes the agent's transcript via the LLM and replaces
14// it with a single synthetic user message carrying the summary. A
15// small tail of recent messages is optionally preserved for continuity.
16//
17// keepTail is the number of most-recent messages to keep verbatim after
18// the summary. 0 means summarize everything; a typical useful value is
19// 4-8 (last couple of exchanges).
20//
21// The method blocks until the summary request completes. Emitted
22// events via sink are limited to text deltas from the summary call so
23// the UI can show progress.
24func (a *Agent) Compact(ctx context.Context, keepTail int, sink func(delta string)) (summary string, err error) {
25 a.mu.Lock()
26 msgs := append([]provider.Message(nil), a.messages...)
27 a.mu.Unlock()
28
29 if len(msgs) == 0 {
30 return "", fmt.Errorf("nothing to compact")
31 }
32 if keepTail < 0 {
33 keepTail = 0
34 }
35 if keepTail > len(msgs) {
36 keepTail = len(msgs)
37 }
38 summarizable := msgs[:len(msgs)-keepTail]
39 if len(summarizable) == 0 {
40 return "", fmt.Errorf("nothing to compact: keep-tail covers the whole transcript")
41 }
42
43 // Serialize the summarizable transcript to text and wrap it in tags
44 // so the model treats it as material to summarize, not to continue.
45 transcript := serializeTranscript(summarizable)
46
47 prompt := "<conversation>\n" + transcript + "\n</conversation>\n\n" + compactionPrompt
48
49 req := provider.Request{
50 Model: a.Model,
51 System: summarizationSystem,
52 MaxTokens: 4096,
53 Temperature: a.Temperature,
54 Messages: []provider.Message{
55 {
56 Role: provider.RoleUser,
57 Content: []provider.Content{provider.TextBlock{Text: prompt}},
58 Time: time.Now(),
59 },
60 },
61 }
62
63 stream, err := a.Client.Stream(ctx, req)
64 if err != nil {
65 return "", err
66 }
67
68 var sb strings.Builder
69 for ev := range stream {
70 switch e := ev.(type) {
71 case provider.EventTextDelta:
72 sb.WriteString(e.Delta)
73 if sink != nil {
74 sink(e.Delta)
75 }
76 case provider.EventDone:
77 if e.Err != nil {
78 return "", e.Err
79 }
80 }
81 }
82 summary = strings.TrimSpace(sb.String())
83 if summary == "" {
84 return "", fmt.Errorf("empty summary from model")
85 }
86
87 // Estimate token count before compaction (rough: 1 token ~ 4 chars).
88 tokensBefore := len(transcript) / 4
89
90 // Replace transcript: one synthetic user message with the summary,
91 // followed by the preserved tail (if any).
92 var activatedTools []string
93 for _, message := range msgs {
94 for _, name := range message.AddedToolNames {
95 if !containsString(activatedTools, name) {
96 activatedTools = append(activatedTools, name)
97 }
98 }
99 }
100 synthetic := provider.Message{
101 Role: provider.RoleUser,
102 AddedToolNames: activatedTools,
103 Content: []provider.Content{
104 provider.TextBlock{Text: "## Context Summary (compacted)\n\n" + summary},
105 },
106 Time: time.Now(),
107 Meta: map[string]string{
108 "compaction": "true",
109 "tokens_before": strconv.Itoa(tokensBefore),
110 },
111 }
112
113 tail := msgs[len(msgs)-keepTail:]
114 // Repair the tail: remove orphaned tool_result blocks whose
115 // matching tool_use was in the compacted (now-removed) portion.
116 // Anthropic rejects transcripts where a tool_result references
117 // a tool_use ID that doesn't exist.
118 tail = repairOrphanedToolResults(tail)
119
120 next := make([]provider.Message, 0, 1+len(tail))
121 next = append(next, synthetic)
122 next = append(next, tail...)
123
124 a.mu.Lock()
125 a.messages = next
126 a.rev++
127 onCompacted := a.OnTranscriptCompacted
128 persisted := append([]provider.Message(nil), next...)
129 a.mu.Unlock()
130
131 if onCompacted != nil {
132 onCompacted(persisted)
133 }
134
135 return summary, nil
136}
137
138// repairOrphanedToolResults removes tool_result content blocks (and
139// entire messages that become empty) when the matching tool_use ID
140// does not appear anywhere in the given messages. This happens after
141// compaction when the tail preserves a tool_result but the tool_use
142// that produced it was summarized away.
143func repairOrphanedToolResults(msgs []provider.Message) []provider.Message {
144 return provider.RepairOrphanedToolResults(msgs)
145}
146
147// serializeTranscript renders a list of provider.Message into a plain
148// text transcript the summarization model can read without trying to
149// continue the conversation.
150func serializeTranscript(msgs []provider.Message) string {
151 var sb strings.Builder
152 for _, m := range msgs {
153 switch m.Role {
154 case provider.RoleUser:
155 sb.WriteString("\n--- user ---\n")
156 case provider.RoleAssistant:
157 sb.WriteString("\n--- assistant ---\n")
158 case provider.RoleTool:
159 sb.WriteString("\n--- tool ---\n")
160 }
161 for _, c := range m.Content {
162 switch v := c.(type) {
163 case provider.TextBlock:
164 sb.WriteString(v.Text)
165 sb.WriteString("\n")
166 case provider.ImageBlock:
167 fmt.Fprintf(&sb, "[image: %s, %d bytes]\n", v.MimeType, len(v.Data))
168 case provider.ToolCallBlock:
169 fmt.Fprintf(&sb, "[tool_call %s %s]\n", v.Name, string(v.Arguments))
170 case provider.ToolResultBlock:
171 for _, inner := range v.Content {
172 if tb, ok := inner.(provider.TextBlock); ok {
173 sb.WriteString("[tool_result] ")
174 sb.WriteString(tb.Text)
175 sb.WriteString("\n")
176 }
177 }
178 }
179 }
180 }
181 return sb.String()
182}
183
184const summarizationSystem = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.
185
186Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`
187
188const compactionPrompt = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
189
190Use this EXACT format:
191
192## Goal
193[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
194
195## Constraints & Preferences
196- [Any constraints, preferences, or requirements mentioned by user]
197- [Or "(none)" if none were mentioned]
198
199## Progress
200### Done
201- [x] [Completed tasks/changes]
202
203### In Progress
204- [ ] [Current work]
205
206### Blocked
207- [Issues preventing progress, if any]
208
209## Key Decisions
210- **[Decision]**: [Brief rationale]
211
212## Next Steps
2131. [Ordered list of what should happen next]
214
215## Critical Context
216- [Any data, examples, or references needed to continue]
217- [Or "(none)" if not applicable]
218
219Keep each section concise. Preserve exact file paths, function names, and error messages.`