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 SessionID: a.SessionID,
55 Messages: []provider.Message{
56 {
57 Role: provider.RoleUser,
58 Content: []provider.Content{provider.TextBlock{Text: prompt}},
59 Time: time.Now(),
60 },
61 },
62 }
63
64 stream, err := a.Client.Stream(ctx, req)
65 if err != nil {
66 return "", err
67 }
68
69 var sb strings.Builder
70 for ev := range stream {
71 switch e := ev.(type) {
72 case provider.EventTextDelta:
73 sb.WriteString(e.Delta)
74 if sink != nil {
75 sink(e.Delta)
76 }
77 case provider.EventDone:
78 if e.Err != nil {
79 return "", e.Err
80 }
81 }
82 }
83 summary = strings.TrimSpace(sb.String())
84 if summary == "" {
85 return "", fmt.Errorf("empty summary from model")
86 }
87
88 // Estimate token count before compaction (rough: 1 token ~ 4 chars).
89 tokensBefore := len(transcript) / 4
90
91 // Replace transcript: one synthetic user message with the summary,
92 // followed by the preserved tail (if any).
93 var activatedTools []string
94 for _, message := range msgs {
95 for _, name := range message.AddedToolNames {
96 if !containsString(activatedTools, name) {
97 activatedTools = append(activatedTools, name)
98 }
99 }
100 }
101 synthetic := provider.Message{
102 Role: provider.RoleUser,
103 AddedToolNames: activatedTools,
104 Content: []provider.Content{
105 provider.TextBlock{Text: "## Context Summary (compacted)\n\n" + summary},
106 },
107 Time: time.Now(),
108 Meta: map[string]string{
109 "compaction": "true",
110 "tokens_before": strconv.Itoa(tokensBefore),
111 },
112 }
113
114 tail := msgs[len(msgs)-keepTail:]
115 // Repair the tail: remove orphaned tool_result blocks whose
116 // matching tool_use was in the compacted (now-removed) portion.
117 // Anthropic rejects transcripts where a tool_result references
118 // a tool_use ID that doesn't exist.
119 tail = repairOrphanedToolResults(tail)
120
121 next := make([]provider.Message, 0, 1+len(tail))
122 next = append(next, synthetic)
123 next = append(next, tail...)
124
125 a.mu.Lock()
126 a.messages = next
127 a.rev++
128 onCompacted := a.OnTranscriptCompacted
129 persisted := append([]provider.Message(nil), next...)
130 a.mu.Unlock()
131
132 if onCompacted != nil {
133 onCompacted(persisted)
134 }
135
136 return summary, nil
137}
138
139// repairOrphanedToolResults removes tool_result content blocks (and
140// entire messages that become empty) when the matching tool_use ID
141// does not appear anywhere in the given messages. This happens after
142// compaction when the tail preserves a tool_result but the tool_use
143// that produced it was summarized away.
144func repairOrphanedToolResults(msgs []provider.Message) []provider.Message {
145 return provider.RepairOrphanedToolResults(msgs)
146}
147
148// serializeTranscript renders a list of provider.Message into a plain
149// text transcript the summarization model can read without trying to
150// continue the conversation.
151func serializeTranscript(msgs []provider.Message) string {
152 var sb strings.Builder
153 for _, m := range msgs {
154 switch m.Role {
155 case provider.RoleUser:
156 sb.WriteString("\n--- user ---\n")
157 case provider.RoleAssistant:
158 sb.WriteString("\n--- assistant ---\n")
159 case provider.RoleTool:
160 sb.WriteString("\n--- tool ---\n")
161 }
162 for _, c := range m.Content {
163 switch v := c.(type) {
164 case provider.TextBlock:
165 sb.WriteString(v.Text)
166 sb.WriteString("\n")
167 case provider.ImageBlock:
168 fmt.Fprintf(&sb, "[image: %s, %d bytes]\n", v.MimeType, len(v.Data))
169 case provider.ToolCallBlock:
170 fmt.Fprintf(&sb, "[tool_call %s %s]\n", v.Name, string(v.Arguments))
171 case provider.ToolResultBlock:
172 for _, inner := range v.Content {
173 if tb, ok := inner.(provider.TextBlock); ok {
174 sb.WriteString("[tool_result] ")
175 sb.WriteString(tb.Text)
176 sb.WriteString("\n")
177 }
178 }
179 }
180 }
181 }
182 return sb.String()
183}
184
185const 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.
186
187Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`
188
189const compactionPrompt = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
190
191Use this EXACT format:
192
193## Goal
194[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
195
196## Constraints & Preferences
197- [Any constraints, preferences, or requirements mentioned by user]
198- [Or "(none)" if none were mentioned]
199
200## Progress
201### Done
202- [x] [Completed tasks/changes]
203
204### In Progress
205- [ ] [Current work]
206
207### Blocked
208- [Issues preventing progress, if any]
209
210## Key Decisions
211- **[Decision]**: [Brief rationale]
212
213## Next Steps
2141. [Ordered list of what should happen next]
215
216## Critical Context
217- [Any data, examples, or references needed to continue]
218- [Or "(none)" if not applicable]
219
220Keep each section concise. Preserve exact file paths, function names, and error messages.`