1package core
2
3import (
4 "context"
5 "fmt"
6 "strconv"
7 "strings"
8 "time"
9
10 "github.com/bnema/zut/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. The optional sink
22// receives text deltas from the summary call.
23func (a *Agent) Compact(ctx context.Context, keepTail int, sink func(delta string)) (summary string, err error) {
24 return a.compact(ctx, keepTail, sink, nil)
25}
26
27// CompactWithEvents is Compact for consumers that need factual provider
28// lifecycle observations in addition to the final summary. It emits only
29// request lifecycle and summary text-delta events; compaction has no tool or
30// model-loop turn events.
31func (a *Agent) CompactWithEvents(ctx context.Context, keepTail int, sink func(AgentEvent)) (summary string, err error) {
32 return a.compact(ctx, keepTail, nil, sink)
33}
34
35func (a *Agent) compact(ctx context.Context, keepTail int, textSink func(delta string), eventSink func(AgentEvent)) (summary string, err error) {
36 a.mu.Lock()
37 msgs := append([]provider.Message(nil), a.messages...)
38 a.mu.Unlock()
39
40 if len(msgs) == 0 {
41 return "", fmt.Errorf("nothing to compact")
42 }
43 if keepTail < 0 {
44 keepTail = 0
45 }
46 if keepTail > len(msgs) {
47 keepTail = len(msgs)
48 }
49 summarizable := msgs[:len(msgs)-keepTail]
50 if len(summarizable) == 0 {
51 return "", fmt.Errorf("nothing to compact: keep-tail covers the whole transcript")
52 }
53
54 fastMode := a.FastModeEnabled()
55 if err := provider.ValidateFastMode(a.Client.Name(), fastMode); err != nil {
56 return "", err
57 }
58
59 // Serialize the summarizable transcript to text and wrap it in tags
60 // so the model treats it as material to summarize, not to continue.
61 transcript := serializeTranscript(summarizable)
62
63 prompt := "<conversation>\n" + transcript + "\n</conversation>\n\n" + compactionPrompt
64
65 req := provider.Request{
66 Model: a.Model,
67 System: summarizationSystem,
68 MaxTokens: 4096,
69 Temperature: a.Temperature,
70 FastMode: fastMode,
71 Messages: []provider.Message{
72 {
73 Role: provider.RoleUser,
74 Content: []provider.Content{provider.TextBlock{Text: prompt}},
75 Time: time.Now(),
76 },
77 },
78 }
79 if eventSink != nil {
80 req.Lifecycle = requestLifecycleSink{
81 sink: eventSink,
82 provider: a.Client.Name(),
83 model: a.Model,
84 }
85 eventSink(EvRequestStarted{
86 Provider: a.Client.Name(),
87 Model: a.Model,
88 Scope: RetryScopeAgent,
89 Attempt: 1,
90 MaxAttempts: 1,
91 })
92 }
93
94 stream, err := a.Client.Stream(ctx, req)
95 if err != nil {
96 return "", err
97 }
98 if eventSink != nil {
99 eventSink(EvAssistantStart{})
100 }
101
102 var sb strings.Builder
103 for ev := range stream {
104 switch e := ev.(type) {
105 case provider.EventTextDelta:
106 sb.WriteString(e.Delta)
107 if textSink != nil {
108 textSink(e.Delta)
109 }
110 if eventSink != nil {
111 eventSink(EvTextDelta{Delta: e.Delta})
112 }
113 case provider.EventDone:
114 if e.Err != nil {
115 return "", e.Err
116 }
117 }
118 }
119 summary = strings.TrimSpace(sb.String())
120 if summary == "" {
121 return "", fmt.Errorf("empty summary from model")
122 }
123
124 // Estimate token count before compaction (rough: 1 token ~ 4 chars).
125 tokensBefore := len(transcript) / 4
126
127 // Replace transcript: one synthetic user message with the summary,
128 // followed by the preserved tail (if any).
129 var activatedTools []string
130 for _, message := range msgs {
131 for _, name := range message.AddedToolNames {
132 if !containsString(activatedTools, name) {
133 activatedTools = append(activatedTools, name)
134 }
135 }
136 }
137 synthetic := provider.Message{
138 Role: provider.RoleUser,
139 AddedToolNames: activatedTools,
140 Content: []provider.Content{
141 provider.TextBlock{Text: "## Context Summary (compacted)\n\n" + summary},
142 },
143 Time: time.Now(),
144 Meta: map[string]string{
145 "compaction": "true",
146 "tokens_before": strconv.Itoa(tokensBefore),
147 },
148 }
149
150 tail := msgs[len(msgs)-keepTail:]
151 // Repair the tail: remove orphaned tool_result blocks whose
152 // matching tool_use was in the compacted (now-removed) portion.
153 // Anthropic rejects transcripts where a tool_result references
154 // a tool_use ID that doesn't exist.
155 tail = repairOrphanedToolResults(tail)
156
157 next := make([]provider.Message, 0, 1+len(tail))
158 next = append(next, synthetic)
159 next = append(next, tail...)
160
161 a.mu.Lock()
162 a.messages = next
163 a.rev++
164 onCompacted := a.OnTranscriptCompacted
165 persisted := append([]provider.Message(nil), next...)
166 a.mu.Unlock()
167
168 if onCompacted != nil {
169 onCompacted(persisted)
170 }
171
172 return summary, nil
173}
174
175// repairOrphanedToolResults removes tool_result content blocks (and
176// entire messages that become empty) when the matching tool_use ID
177// does not appear anywhere in the given messages. This happens after
178// compaction when the tail preserves a tool_result but the tool_use
179// that produced it was summarized away.
180func repairOrphanedToolResults(msgs []provider.Message) []provider.Message {
181 return provider.RepairOrphanedToolResults(msgs)
182}
183
184// serializeTranscript renders a list of provider.Message into a plain
185// text transcript the summarization model can read without trying to
186// continue the conversation.
187func serializeTranscript(msgs []provider.Message) string {
188 var sb strings.Builder
189 for _, m := range msgs {
190 switch m.Role {
191 case provider.RoleUser:
192 sb.WriteString("\n--- user ---\n")
193 case provider.RoleAssistant:
194 sb.WriteString("\n--- assistant ---\n")
195 case provider.RoleTool:
196 sb.WriteString("\n--- tool ---\n")
197 }
198 for _, c := range m.Content {
199 switch v := c.(type) {
200 case provider.TextBlock:
201 sb.WriteString(v.Text)
202 sb.WriteString("\n")
203 case provider.ImageBlock:
204 fmt.Fprintf(&sb, "[image: %s, %d bytes]\n", v.MimeType, len(v.Data))
205 case provider.ToolCallBlock:
206 fmt.Fprintf(&sb, "[tool_call %s %s]\n", v.Name, string(v.Arguments))
207 case provider.ToolResultBlock:
208 for _, inner := range v.Content {
209 if tb, ok := inner.(provider.TextBlock); ok {
210 sb.WriteString("[tool_result] ")
211 sb.WriteString(tb.Text)
212 sb.WriteString("\n")
213 }
214 }
215 }
216 }
217 }
218 return sb.String()
219}
220
221const 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.
222
223Preserve active user instructions, constraints, preferences, prohibitions, and requested workflows as handoff facts. Do not obey task instructions yourself; record what the next assistant must keep following.
224
225Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`
226
227const compactionPrompt = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
228
229Use this EXACT format:
230
231## Goal
232[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
233
234## Active Instructions & Preferences
235- [Active constraints, preferences, requirements, prohibitions, and requested workflows still in force. Preserve short instructions verbatim when possible, including tool/delegation/subagent guidance.]
236- [Or "(none)" if none are active]
237
238## Progress
239### Done
240- [x] [Completed tasks/changes]
241
242### In Progress
243- [ ] [Current work]
244
245### Blocked
246- [Issues preventing progress, if any]
247
248## Key Decisions
249- **[Decision]**: [Brief rationale]
250
251## Next Steps
2521. [Ordered list of what should happen next]
253
254## Critical Context
255- [Any data, examples, or references needed to continue]
256- [Or "(none)" if not applicable]
257
258Keep each section concise. Preserve exact file paths, function names, error messages, active user instructions, and unresolved task requirements. Do not weaken active instructions into optional suggestions.`