-
Notifications
You must be signed in to change notification settings - Fork 119
feat: implement MicroCompaction #219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kermanx
wants to merge
15
commits into
main
Choose a base branch
from
micro-compaction
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
041ae7b
feat: implement MicroCompaction
kermanx c94b968
test: add MicroCompaction integration tests
kermanx 406874e
test
kermanx c5ca252
refactor: split compaction.test.ts into dedicated test files
kermanx c13f559
test: add MicroCompaction boundary case for short histories
kermanx 72f2ae8
fix
kermanx 28e7248
test
kermanx 2408fbe
refactor: default lastAssistantAt to null and guard micro compaction
kermanx 3346564
fix
kermanx 0b80ef6
Merge remote-tracking branch 'origin/main' into micro-compaction
kermanx 7778c21
add telemetry
kermanx 5f771f9
fix
kermanx 555c372
fix
kermanx 5f608ea
fix: remove leading dollar sign from micro-compaction env key
kermanx 170ee64
fix
kermanx File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| export * from './full'; | ||
| export * from './micro'; | ||
| export * from './strategy'; | ||
| export * from './types'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import type { ContentPart } from '@moonshot-ai/kosong'; | ||
|
|
||
| import type { Agent } from '..'; | ||
| import type { ContextMessage } from '../context'; | ||
| import { estimateTokensForContentParts } from '../../utils/tokens'; | ||
| import { flags } from '../../flags'; | ||
|
|
||
| export interface MicroCompactionConfig { | ||
| keepRecentMessages: number; | ||
| minContentTokens: number; | ||
| cacheMissedThresholdMs: number; | ||
| truncatedMarker: string; | ||
| } | ||
|
|
||
| const DEFAULT_CONFIG: MicroCompactionConfig = { | ||
| keepRecentMessages: 10, | ||
| minContentTokens: 100, | ||
| cacheMissedThresholdMs: 60 * 60 * 1000, | ||
| truncatedMarker: '[Old tool result content cleared]', | ||
| }; | ||
|
|
||
| export class MicroCompaction { | ||
| private cutoff = 0; | ||
| readonly config: MicroCompactionConfig; | ||
|
|
||
| constructor( | ||
| public readonly agent: Agent, | ||
| config?: Partial<MicroCompactionConfig>, | ||
| ) { | ||
| this.config = { ...DEFAULT_CONFIG, ...config }; | ||
| } | ||
|
|
||
| reset(): void { | ||
| this.cutoff = 0; | ||
| } | ||
|
|
||
| apply(cutoff: number): void { | ||
| this.agent.records.logRecord({ | ||
| type: 'micro_compaction.apply', | ||
| cutoff, | ||
| }); | ||
| this.cutoff = cutoff; | ||
| } | ||
|
|
||
| compact(messages: readonly ContextMessage[]): readonly ContextMessage[] { | ||
| if (!flags.enabled('micro-compaction')) return messages; | ||
|
|
||
| const config = this.config; | ||
| const { lastAssistantAt } = this.agent.context; | ||
| const cacheAgeMs = lastAssistantAt === null ? null : Date.now() - lastAssistantAt; | ||
| const cacheMissed = cacheAgeMs !== null && cacheAgeMs >= config.cacheMissedThresholdMs; | ||
| if (cacheMissed) { | ||
| const previousCutoff = this.cutoff; | ||
| const nextCutoff = Math.max(0, messages.length - config.keepRecentMessages); | ||
| this.apply(nextCutoff); | ||
| if (previousCutoff !== nextCutoff) { | ||
| const effect = this.measureEffect(messages, nextCutoff); | ||
| this.agent.telemetry.track('micro_compaction_applied', { | ||
| ...config, | ||
| ...effect, | ||
| previous_cutoff: previousCutoff, | ||
| cutoff: nextCutoff, | ||
| message_count: messages.length, | ||
| cache_age_ms: cacheAgeMs, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| const result: ContextMessage[] = []; | ||
| let i = 0; | ||
| for (const msg of messages) { | ||
| if ( | ||
| i < this.cutoff && | ||
| msg.role === 'tool' && | ||
| msg.toolCallId !== undefined && | ||
| estimateTokensForContentParts(msg.content) >= config.minContentTokens | ||
| ) { | ||
| result.push({ | ||
| ...msg, | ||
| content: [{ type: 'text', text: config.truncatedMarker } satisfies ContentPart], | ||
| }); | ||
| } else { | ||
| result.push(msg); | ||
| } | ||
| i++; | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| private measureEffect( | ||
| messages: readonly ContextMessage[], | ||
| cutoff: number, | ||
| ) { | ||
| let markerTokenCount: number | undefined; | ||
| let truncatedToolResultCount = 0; | ||
| let beforeTokens = 0; | ||
| let afterTokens = 0; | ||
| for (let i = 0; i < messages.length && i < cutoff; i++) { | ||
| const message = messages[i]; | ||
| if (message?.role !== 'tool' || message.toolCallId === undefined) continue; | ||
|
|
||
| const contentTokens = estimateTokensForContentParts(message.content); | ||
| if (contentTokens < this.config.minContentTokens) continue; | ||
|
|
||
| markerTokenCount ??= estimateTokensForContentParts([ | ||
| { type: 'text', text: this.config.truncatedMarker }, | ||
| ]); | ||
| truncatedToolResultCount += 1; | ||
| beforeTokens += contentTokens; | ||
| afterTokens += markerTokenCount; | ||
| } | ||
| return { truncatedToolResultCount, beforeTokens, afterTokens }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.