| 1 |
package transcript |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"fmt" |
| 6 |
"reflect" |
| 7 |
"strings" |
| 8 |
) |
| 9 |
|
| 10 |
type compactState struct { |
| 11 |
Source string `json:"source"` |
| 12 |
Kind string `json:"kind"` |
| 13 |
Summary string `json:"summary"` |
| 14 |
} |
| 15 |
|
| 16 |
func messageKind(msg Message) string { |
| 17 |
if msg.Role != "user" { |
| 18 |
return "" |
| 19 |
} |
| 20 |
content := strings.TrimSpace(msg.Content) |
| 21 |
switch { |
| 22 |
case compactMessage(content): |
| 23 |
return "compact" |
| 24 |
case stateMessage(content): |
| 25 |
return "state" |
| 26 |
case commandResultMessage(content): |
| 27 |
return "command" |
| 28 |
case strings.HasPrefix(content, "[protocol_error]") && |
| 29 |
strings.HasSuffix(content, "[/protocol_error]"): |
| 30 |
return "protocol" |
| 31 |
default: |
| 32 |
return "authored" |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
func commandResultMessage(content string) bool { |
| 37 |
var payload struct { |
| 38 |
Stdout *string `json:"stdout"` |
| 39 |
Stderr *string `json:"stderr"` |
| 40 |
Outcome *CommandOutcome `json:"outcome"` |
| 41 |
} |
| 42 |
if err := json.Unmarshal([]byte(content), &payload); err != nil { |
| 43 |
return false |
| 44 |
} |
| 45 |
return payload.Stdout != nil && payload.Stderr != nil && payload.Outcome != nil && |
| 46 |
payload.Outcome.Type != "" |
| 47 |
} |
| 48 |
|
| 49 |
// IsCompactMessage reports whether the message is a clnkr compact block. |
| 50 |
func IsCompactMessage(msg Message) bool { |
| 51 |
return messageKind(msg) == "compact" |
| 52 |
} |
| 53 |
|
| 54 |
func isUserAuthoredMessage(msg Message) bool { |
| 55 |
return messageKind(msg) == "authored" |
| 56 |
} |
| 57 |
|
| 58 |
// FormatCompactMessage renders the compact-summary transcript block. |
| 59 |
func FormatCompactMessage(summary string) string { |
| 60 |
body, err := json.Marshal(compactState{ |
| 61 |
Source: "clnkr", |
| 62 |
Kind: "compact", |
| 63 |
Summary: summary, |
| 64 |
}) |
| 65 |
if err != nil { |
| 66 |
panic(fmt.Sprintf("marshal compact message: %v", err)) |
| 67 |
} |
| 68 |
return fmt.Sprintf("[compact]\n%s\n[/compact]", body) |
| 69 |
} |
| 70 |
|
| 71 |
// FindCompactBoundary returns the start index of the recent tail to keep. |
| 72 |
func FindCompactBoundary(messages []Message, keepRecentTurns int) (int, bool) { |
| 73 |
if keepRecentTurns < 1 { |
| 74 |
return 0, false |
| 75 |
} |
| 76 |
|
| 77 |
authoredSeen := 0 |
| 78 |
for i := len(messages) - 1; i >= 0; i-- { |
| 79 |
if !isUserAuthoredMessage(messages[i]) { |
| 80 |
continue |
| 81 |
} |
| 82 |
authoredSeen++ |
| 83 |
if authoredSeen == keepRecentTurns { |
| 84 |
for _, earlier := range messages[:i] { |
| 85 |
if isUserAuthoredMessage(earlier) { |
| 86 |
return i, true |
| 87 |
} |
| 88 |
} |
| 89 |
return 0, false |
| 90 |
} |
| 91 |
} |
| 92 |
return 0, false |
| 93 |
} |
| 94 |
|
| 95 |
// RewriteForCompaction replaces the older transcript prefix with a compact block. |
| 96 |
func RewriteForCompaction( |
| 97 |
messages []Message, |
| 98 |
summary string, |
| 99 |
keepRecentTurns int, |
| 100 |
) ([]Message, CompactStats, error) { |
| 101 |
if keepRecentTurns < 1 { |
| 102 |
return nil, CompactStats{}, fmt.Errorf( |
| 103 |
"rewrite for compaction: keep recent turns must be at least 1", |
| 104 |
) |
| 105 |
} |
| 106 |
|
| 107 |
boundary, ok := FindCompactBoundary(messages, keepRecentTurns) |
| 108 |
if !ok { |
| 109 |
return nil, CompactStats{}, fmt.Errorf( |
| 110 |
"rewrite for compaction: not enough history to compact", |
| 111 |
) |
| 112 |
} |
| 113 |
|
| 114 |
keptTail := make([]Message, 0, len(messages)-boundary) |
| 115 |
for _, msg := range messages[boundary:] { |
| 116 |
if IsCompactMessage(msg) { |
| 117 |
continue |
| 118 |
} |
| 119 |
keptTail = append(keptTail, CloneMessage(msg)) |
| 120 |
} |
| 121 |
|
| 122 |
rewritten := make([]Message, 0, len(keptTail)+2) |
| 123 |
rewritten = append( |
| 124 |
rewritten, |
| 125 |
Message{Role: "user", Content: FormatCompactMessage(summary)}, |
| 126 |
) |
| 127 |
|
| 128 |
keptMessages := len(keptTail) |
| 129 |
for i := len(messages) - 1; i >= 0; i-- { |
| 130 |
if messageKind(messages[i]) != "state" { |
| 131 |
continue |
| 132 |
} |
| 133 |
stateMsg, present := CloneMessage(messages[i]), false |
| 134 |
for _, msg := range keptTail { |
| 135 |
if sameMessage(msg, stateMsg) { |
| 136 |
present = true |
| 137 |
break |
| 138 |
} |
| 139 |
} |
| 140 |
if !present { |
| 141 |
rewritten = append(rewritten, stateMsg) |
| 142 |
keptMessages++ |
| 143 |
} |
| 144 |
break |
| 145 |
} |
| 146 |
|
| 147 |
rewritten = append(rewritten, keptTail...) |
| 148 |
|
| 149 |
return rewritten, CompactStats{ |
| 150 |
CompactedMessages: boundary, |
| 151 |
KeptMessages: keptMessages, |
| 152 |
}, nil |
| 153 |
} |
| 154 |
|
| 155 |
func sameMessage(a, b Message) bool { |
| 156 |
return a.Role == b.Role && |
| 157 |
a.Content == b.Content && |
| 158 |
reflect.DeepEqual(a.BashToolCalls, b.BashToolCalls) && |
| 159 |
reflect.DeepEqual(a.BashToolResult, b.BashToolResult) && |
| 160 |
reflect.DeepEqual(a.ProviderReplay, b.ProviderReplay) |
| 161 |
} |
| 162 |
|
| 163 |
func compactMessage(content string) bool { |
| 164 |
var parsed compactState |
| 165 |
if !extractTaggedJSONObject(content, "[compact]", "[/compact]", &parsed) { |
| 166 |
return false |
| 167 |
} |
| 168 |
return parsed.Source == "clnkr" && parsed.Kind == "compact" |
| 169 |
} |
| 170 |
|
| 171 |
func stateMessage(content string) bool { |
| 172 |
_, ok := ExtractStateCwd(content) |
| 173 |
return ok |
| 174 |
} |
| 175 |
|
| 176 |
func extractTaggedJSONObject(content, openTag, closeTag string, dst any) bool { |
| 177 |
content = strings.TrimSpace(content) |
| 178 |
if !strings.HasPrefix(content, openTag) || !strings.HasSuffix(content, closeTag) { |
| 179 |
return false |
| 180 |
} |
| 181 |
body := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(content, openTag), closeTag)) |
| 182 |
if err := json.Unmarshal([]byte(body), dst); err != nil { |
| 183 |
return false |
| 184 |
} |
| 185 |
return true |
| 186 |
} |