v0.2.62 5f6a3d0

compact.go RawHistoryFolder

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close