GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(core): compact v2 session context (#30986) · koji/opencode@beae729

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • core
      • src
        • config
          • compaction.ts
        • session
          • compaction.ts
          • event.ts
          • history.ts
          • message-updater.ts
          • message.ts
          • projector.ts
          • runner
            • llm.ts
            • to-llm-message.ts
        • util
          • token.ts
        • v1/config
          • migrate.ts
      • test
        • config
          • config.test.ts
        • session-projector.test.ts
        • session-runner-message.test.ts
        • session-runner-recorded.test.ts
        • session-runner.test.ts
    • opencode
      • src
        • cli/cmd/tui
          • context
            • sync-v2.tsx
          • feature-plugins/system
            • session-v2.tsx
        • session
          • compaction.ts
        • util
          • token.ts
      • test/v2
        • session-message-updater.test.ts
    • sdk
      • js/src/v2/gen
        • types.gen.ts
      • openapi.json
  • specs/v2
    • config.md
    • schema-changelog.md
    • session.md
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/config/compaction.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/config/compaction.ts
-1Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { Schema } from "effect"
44
import { NonNegativeInt } from "../schema"
55

66
export class Keep extends Schema.Class<Keep>("ConfigV2.Compaction.Keep")({
7-
turns: NonNegativeInt.pipe(Schema.optional),
87
tokens: NonNegativeInt.pipe(Schema.optional),
98
}) {}
109

Collapse file

‎packages/core/src/session/compaction.ts‎

Copy file name to clipboard
+224Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
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+
}
Collapse file

‎packages/core/src/session/event.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/event.ts
+16-4Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -435,15 +435,16 @@ export namespace Compaction {
435435

436436
export const Delta = EventV2.define({
437437
type: "session.next.compaction.delta",
438-
...options,
439438
schema: {
440439
...Base,
440+
messageID: SessionMessageID.ID,
441441
text: Schema.String,
442442
},
443443
})
444444
export type Delta = typeof Delta.Type
445445

446-
export const Ended = EventV2.define({
446+
// Retain the unpublished v1 decoder so stored beta events remain replayable.
447+
export const EndedV1 = EventV2.define({
447448
type: "session.next.compaction.ended",
448449
...options,
449450
schema: {
@@ -452,6 +453,18 @@ export namespace Compaction {
452453
include: Schema.String.pipe(Schema.optional),
453454
},
454455
})
456+
457+
export const Ended = EventV2.define({
458+
type: "session.next.compaction.ended",
459+
sync: { aggregate: "sessionID", version: 2 },
460+
schema: {
461+
...Base,
462+
messageID: SessionMessageID.ID,
463+
reason: Started.data.fields.reason,
464+
text: Schema.String,
465+
recent: Schema.String,
466+
},
467+
})
455468
export type Ended = typeof Ended.Type
456469
}
457470

@@ -482,10 +495,9 @@ const DurableDefinitions = [
482495
Reasoning.Ended,
483496
Retried,
484497
Compaction.Started,
485-
Compaction.Delta,
486498
Compaction.Ended,
487499
] as const
488-
const EphemeralDefinitions = [Text.Delta, Tool.Input.Delta, Reasoning.Delta] as const
500+
const EphemeralDefinitions = [Text.Delta, Tool.Input.Delta, Reasoning.Delta, Compaction.Delta] as const
489501

490502
export const Durable = Schema.Union(DurableDefinitions, { mode: "oneOf" }).pipe(Schema.toTaggedUnion("type"))
491503
export type DurableEvent = typeof Durable.Type
Collapse file

‎packages/core/src/session/history.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/history.ts
+14-5Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const decode = Schema.decodeUnknownEffect(SessionMessage.Message)
1212

1313
const latestCompaction = Effect.fnUntraced(function* (db: DatabaseService, sessionID: SessionSchema.ID) {
1414
return yield* db
15-
.select({ seq: SessionMessageTable.seq })
15+
.select()
1616
.from(SessionMessageTable)
1717
.where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "compaction")))
1818
.orderBy(desc(SessionMessageTable.seq))
@@ -27,7 +27,7 @@ const messageRows = Effect.fnUntraced(function* (
2727
compaction: { readonly seq: number } | undefined,
2828
baselineSeq?: number,
2929
) {
30-
return yield* db
30+
const rows = yield* db
3131
.select()
3232
.from(SessionMessageTable)
3333
.where(
@@ -49,6 +49,7 @@ const messageRows = Effect.fnUntraced(function* (
4949
.orderBy(asc(SessionMessageTable.seq))
5050
.all()
5151
.pipe(Effect.orDie)
52+
return rows
5253
})
5354

5455
const decodeMessageRow = (row: typeof SessionMessageTable.$inferSelect) =>
@@ -83,9 +84,17 @@ export const loadForRunner = Effect.fn("SessionHistory.loadForRunner")(function*
8384
sessionID: SessionSchema.ID,
8485
baselineSeq: number,
8586
) {
86-
return yield* Effect.forEach(
87-
yield* messageRows(db, sessionID, yield* latestCompaction(db, sessionID), baselineSeq),
88-
decodeMessageRow,
87+
return (yield* entriesForRunner(db, sessionID, baselineSeq)).map((entry) => entry.message)
88+
})
89+
90+
export const entriesForRunner = Effect.fn("SessionHistory.entriesForRunner")(function* (
91+
db: DatabaseService,
92+
sessionID: SessionSchema.ID,
93+
baselineSeq: number,
94+
) {
95+
const rows = yield* messageRows(db, sessionID, yield* latestCompaction(db, sessionID), baselineSeq)
96+
return yield* Effect.forEach(rows, (row) =>
97+
decodeMessageRow(row).pipe(Effect.map((message) => ({ seq: row.seq, message }))),
8998
)
9099
})
91100

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.