|
| 1 | +export * as SessionCompaction from "./compaction" |
| 2 | + |
| 3 | +import { LLM, LLMError, LLMEvent, Message, type LLMRequest, type Model } from "@opencode-ai/llm" |
| 4 | +import { DateTime, Effect, Stream } from "effect" |
| 5 | +import type { Config } from "../config" |
| 6 | +import type { EventV2 } from "../event" |
| 7 | +import { SessionEvent } from "./event" |
| 8 | +import { SessionMessage } from "./message" |
| 9 | +import { SessionSchema } from "./schema" |
| 10 | +import { Token } from "../util/token" |
| 11 | + |
| 12 | +const DEFAULT_BUFFER = 20_000 |
| 13 | +const DEFAULT_KEEP_TOKENS = 8_000 |
| 14 | +const TOOL_OUTPUT_MAX_CHARS = 2_000 |
| 15 | +const SUMMARY_OUTPUT_TOKENS = 4_096 |
| 16 | +const SUMMARY_TEMPLATE = `Output exactly the Markdown structure shown inside <template> and keep the section order unchanged. Do not include the <template> tags in your response. |
| 17 | +<template> |
| 18 | +## Goal |
| 19 | +- [single-sentence task summary] |
| 20 | +
|
| 21 | +## Constraints & Preferences |
| 22 | +- [user constraints, preferences, specs, or "(none)"] |
| 23 | +
|
| 24 | +## Progress |
| 25 | +### Done |
| 26 | +- [completed work or "(none)"] |
| 27 | +
|
| 28 | +### In Progress |
| 29 | +- [current work or "(none)"] |
| 30 | +
|
| 31 | +### Blocked |
| 32 | +- [blockers or "(none)"] |
| 33 | +
|
| 34 | +## Key Decisions |
| 35 | +- [decision and why, or "(none)"] |
| 36 | +
|
| 37 | +## Next Steps |
| 38 | +- [ordered next actions or "(none)"] |
| 39 | +
|
| 40 | +## Critical Context |
| 41 | +- [important technical facts, errors, open questions, or "(none)"] |
| 42 | +
|
| 43 | +## Relevant Files |
| 44 | +- [file or directory path: why it matters, or "(none)"] |
| 45 | +</template> |
| 46 | +
|
| 47 | +Rules: |
| 48 | +- Keep every section, even when empty. |
| 49 | +- Use terse bullets, not prose paragraphs. |
| 50 | +- Preserve exact file paths, commands, error strings, and identifiers when known. |
| 51 | +- Do not mention the summary process or that context was compacted.` |
| 52 | + |
| 53 | +type Entry = { |
| 54 | + readonly seq: number |
| 55 | + readonly message: SessionMessage.Message |
| 56 | +} |
| 57 | + |
| 58 | +type Settings = { |
| 59 | + readonly auto: boolean |
| 60 | + readonly buffer: number |
| 61 | + readonly tokens: number |
| 62 | +} |
| 63 | + |
| 64 | +type Dependencies = { |
| 65 | + readonly events: EventV2.Interface |
| 66 | + readonly llm: { |
| 67 | + readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMError> |
| 68 | + } |
| 69 | + readonly config: readonly Config.Entry[] |
| 70 | +} |
| 71 | + |
| 72 | +const estimate = (value: unknown) => Token.estimate(JSON.stringify(value)) |
| 73 | + |
| 74 | +const truncate = (value: string) => |
| 75 | + value.length <= TOOL_OUTPUT_MAX_CHARS ? value : `${value.slice(0, TOOL_OUTPUT_MAX_CHARS)}\n[truncated]` |
| 76 | + |
| 77 | +const serialize = (message: SessionMessage.Message) => { |
| 78 | + if (message.type === "user") { |
| 79 | + const files = message.files?.map((file) => `[Attached ${file.mime}: ${file.name ?? file.uri}]`) ?? [] |
| 80 | + return [`[User]: ${message.text}`, ...files].join("\n") |
| 81 | + } |
| 82 | + if (message.type === "assistant") { |
| 83 | + return message.content |
| 84 | + .flatMap((part) => { |
| 85 | + if (part.type === "text") return [`[Assistant]: ${part.text}`] |
| 86 | + if (part.type === "reasoning") return part.text ? [`[Assistant reasoning]: ${part.text}`] : [] |
| 87 | + const input = typeof part.state.input === "string" ? part.state.input : JSON.stringify(part.state.input) |
| 88 | + if (part.state.status === "completed") |
| 89 | + return [ |
| 90 | + `[Assistant tool call]: ${part.name}(${input})`, |
| 91 | + `[Tool result]: ${truncate(JSON.stringify(part.state.content))}`, |
| 92 | + ] |
| 93 | + if (part.state.status === "error") |
| 94 | + return [`[Assistant tool call]: ${part.name}(${input})`, `[Tool error]: ${part.state.error.message}`] |
| 95 | + return [`[Assistant tool call]: ${part.name}(${input})`] |
| 96 | + }) |
| 97 | + .join("\n") |
| 98 | + } |
| 99 | + if (message.type === "system") return `[System update]: ${message.text}` |
| 100 | + if (message.type === "synthetic") return `[Synthetic context]: ${message.text}` |
| 101 | + if (message.type === "shell") return `[Shell]: ${message.command}\n${truncate(message.output)}` |
| 102 | + return "" |
| 103 | +} |
| 104 | + |
| 105 | +const settings = (documents: readonly Config.Entry[]) => { |
| 106 | + const configured = documents |
| 107 | + .filter((entry): entry is Config.Document => entry.type === "document") |
| 108 | + .flatMap((entry) => (entry.info.compaction ? [entry.info.compaction] : [])) |
| 109 | + return configured.reduce<Settings>( |
| 110 | + (result, current) => ({ |
| 111 | + auto: current.auto ?? result.auto, |
| 112 | + buffer: current.buffer ?? result.buffer, |
| 113 | + tokens: current.keep?.tokens ?? result.tokens, |
| 114 | + }), |
| 115 | + { auto: true, buffer: DEFAULT_BUFFER, tokens: DEFAULT_KEEP_TOKENS }, |
| 116 | + ) |
| 117 | +} |
| 118 | + |
| 119 | +const select = ( |
| 120 | + entries: readonly Entry[], |
| 121 | + tokens: number, |
| 122 | +): { readonly head: string; readonly recent: string } | undefined => { |
| 123 | + const conversation = entries |
| 124 | + .filter((entry) => entry.message.type !== "compaction") |
| 125 | + .map((entry) => serialize(entry.message)) |
| 126 | + .filter(Boolean) |
| 127 | + if (conversation.length === 0) return |
| 128 | + let total = 0 |
| 129 | + let split = conversation.length |
| 130 | + let splitPrefix = "" |
| 131 | + let splitSuffix = "" |
| 132 | + for (let index = conversation.length - 1; index >= 0; index--) { |
| 133 | + const next = total + Token.estimate(conversation[index]) |
| 134 | + if (next > tokens) { |
| 135 | + const remaining = Math.max(0, tokens - total) * 4 |
| 136 | + if (remaining > 0) { |
| 137 | + splitPrefix = conversation[index].slice(0, -remaining) |
| 138 | + splitSuffix = conversation[index].slice(-remaining) |
| 139 | + split = index + 1 |
| 140 | + } |
| 141 | + break |
| 142 | + } |
| 143 | + total = next |
| 144 | + split = index |
| 145 | + } |
| 146 | + return { |
| 147 | + head: [...conversation.slice(0, split), splitPrefix].filter(Boolean).join("\n\n"), |
| 148 | + recent: [splitSuffix, ...conversation.slice(split)].filter(Boolean).join("\n\n"), |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +export const buildPrompt = (input: { readonly previousSummary?: string; readonly context: readonly string[] }) => |
| 153 | + [ |
| 154 | + input.previousSummary |
| 155 | + ? `Update the anchored summary below using the conversation history above.\nPreserve still-true details, remove stale details, and merge in the new facts.\n<previous-summary>\n${input.previousSummary}\n</previous-summary>` |
| 156 | + : "Create a new anchored summary from the conversation history.", |
| 157 | + SUMMARY_TEMPLATE, |
| 158 | + ...input.context, |
| 159 | + ].join("\n\n") |
| 160 | + |
| 161 | +export const make = (dependencies: Dependencies) => { |
| 162 | + const config = settings(dependencies.config) |
| 163 | + return Effect.fn("SessionCompaction.compactIfNeeded")(function* (input: { |
| 164 | + readonly sessionID: SessionSchema.ID |
| 165 | + readonly entries: readonly Entry[] |
| 166 | + readonly model: Model |
| 167 | + readonly request: LLMRequest |
| 168 | + }) { |
| 169 | + const context = input.model.route.defaults.limits?.context |
| 170 | + if (!config.auto || context === undefined || context <= 0) return false |
| 171 | + const output = input.request.generation?.maxTokens ?? input.model.route.defaults.limits?.output ?? 0 |
| 172 | + if ( |
| 173 | + estimate({ system: input.request.system, messages: input.request.messages, tools: input.request.tools }) <= |
| 174 | + context - Math.max(output, config.buffer) |
| 175 | + ) |
| 176 | + return false |
| 177 | + |
| 178 | + const selected = select(input.entries, config.tokens) |
| 179 | + const previousSummary = input.entries.find((entry) => entry.message.type === "compaction")?.message |
| 180 | + if (!selected || (selected.head.length === 0 && previousSummary?.type !== "compaction")) return false |
| 181 | + const summaryPrompt = buildPrompt({ |
| 182 | + previousSummary: previousSummary?.type === "compaction" ? previousSummary.summary : undefined, |
| 183 | + context: [previousSummary?.type === "compaction" ? previousSummary.recent : "", selected.head].filter(Boolean), |
| 184 | + }) |
| 185 | + const summaryOutput = Math.min(output || SUMMARY_OUTPUT_TOKENS, SUMMARY_OUTPUT_TOKENS) |
| 186 | + if (Token.estimate(summaryPrompt) > context - summaryOutput) return false |
| 187 | + const messageID = SessionMessage.ID.create() |
| 188 | + yield* dependencies.events.publish(SessionEvent.Compaction.Started, { |
| 189 | + sessionID: input.sessionID, |
| 190 | + messageID, |
| 191 | + timestamp: yield* DateTime.now, |
| 192 | + reason: "auto", |
| 193 | + }) |
| 194 | + |
| 195 | + const chunks: string[] = [] |
| 196 | + yield* dependencies.llm |
| 197 | + .stream( |
| 198 | + LLM.request({ |
| 199 | + model: input.model, |
| 200 | + messages: [Message.user(summaryPrompt)], |
| 201 | + tools: [], |
| 202 | + generation: { maxTokens: summaryOutput }, |
| 203 | + }), |
| 204 | + ) |
| 205 | + .pipe( |
| 206 | + Stream.runForEach((event) => { |
| 207 | + if (!LLMEvent.is.textDelta(event)) return Effect.void |
| 208 | + chunks.push(event.text) |
| 209 | + return Effect.void |
| 210 | + }), |
| 211 | + ) |
| 212 | + const summary = chunks.join("") |
| 213 | + if (!summary.trim()) return yield* Effect.die("Compaction returned an empty summary") |
| 214 | + yield* dependencies.events.publish(SessionEvent.Compaction.Ended, { |
| 215 | + sessionID: input.sessionID, |
| 216 | + messageID, |
| 217 | + timestamp: yield* DateTime.now, |
| 218 | + reason: "auto", |
| 219 | + text: summary, |
| 220 | + recent: selected.recent, |
| 221 | + }) |
| 222 | + return true |
| 223 | + }) |
| 224 | +} |