Skip to content

Commit db3f860

Browse files
fix: now works reliably
1 parent ff8c4f8 commit db3f860

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

packages/opencode/src/session/compaction.ts

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,32 +51,55 @@ export namespace SessionCompaction {
5151
if (Flag.OPENCODE_DISABLE_PRUNE) return
5252
log.info("pruning", { force: input.force })
5353
const msgs = await Session.messages({ sessionID: input.sessionID })
54+
55+
if (input.force) {
56+
const toPrune = [] as Array<MessageV2.ToolPart & { state: MessageV2.ToolStateCompleted }>
57+
let pruned = 0
58+
for (const msg of msgs) {
59+
for (const part of msg.parts) {
60+
if (part.type !== "tool") continue
61+
if (part.state.status !== "completed") continue
62+
if (part.state.time.compacted) continue
63+
const estimate = Token.estimate(part.state.output)
64+
pruned += estimate
65+
toPrune.push(part as MessageV2.ToolPart & { state: MessageV2.ToolStateCompleted })
66+
}
67+
}
68+
log.info("found", { pruned, total: pruned })
69+
for (const part of toPrune) {
70+
part.state.time.compacted = Date.now()
71+
await Session.updatePart(part)
72+
}
73+
log.info("pruned", { count: toPrune.length })
74+
return
75+
}
76+
5477
let total = 0
5578
let pruned = 0
5679
const toPrune = []
5780
let turns = 0
5881

5982
loop: for (let msgIndex = msgs.length - 1; msgIndex >= 0; msgIndex--) {
6083
const msg = msgs[msgIndex]
84+
if (msg.info.role === "assistant" && msg.info.summary) break loop
6185
if (msg.info.role === "user") turns++
6286
if (turns < 2) continue
63-
if (msg.info.role === "assistant" && msg.info.summary) break loop
6487
for (let partIndex = msg.parts.length - 1; partIndex >= 0; partIndex--) {
6588
const part = msg.parts[partIndex]
6689
if (part.type === "tool")
6790
if (part.state.status === "completed") {
6891
if (part.state.time.compacted) break loop
6992
const estimate = Token.estimate(part.state.output)
7093
total += estimate
71-
if (input.force || total > PRUNE_PROTECT) {
94+
if (total > PRUNE_PROTECT) {
7295
pruned += estimate
7396
toPrune.push(part)
7497
}
7598
}
7699
}
77100
}
78101
log.info("found", { pruned, total })
79-
if (input.force || pruned > PRUNE_MINIMUM) {
102+
if (pruned > PRUNE_MINIMUM) {
80103
for (const part of toPrune) {
81104
if (part.state.status === "completed") {
82105
part.state.time.compacted = Date.now()

0 commit comments

Comments
 (0)