-
Notifications
You must be signed in to change notification settings - Fork 0
Add /clear context command #27
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
ianwalter
wants to merge
8
commits into
main
Choose a base branch
from
clear-command
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
8 commits
Select commit
Hold shift + click to select a range
4bba9d0
Add clear context command
ianwalter 06d4d6b
Merge remote-tracking branch 'origin/main' into clear-command
ianwalter 3f343e4
Address clear command review feedback
ianwalter 1fa5421
Merge main and address clear review follow-ups
ianwalter 35e419d
Address latest clear review comments
ianwalter b4caad3
Harden queued clear and raw history bounds
ianwalter 5deb0c9
Treat explicit Stop as a successful cancellation
ianwalter a24de7c
Address clear command review feedback
ianwalter 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 |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| import { | ||
| type ContextEvent, | ||
| type ExtensionAPI, | ||
| estimateTokens, | ||
| findCutPoint, | ||
| generateSummaryWithUsage, | ||
| type SessionEntry, | ||
| sessionEntryToContextMessages, | ||
| } from "@earendil-works/pi-coding-agent"; | ||
| import { WEB_CLEAR_CONTEXT_ENTRY } from "../web/clear-command.js"; | ||
|
|
||
| export const CLEAR_CONTEXT_ENTRY = WEB_CLEAR_CONTEXT_ENTRY; | ||
| export const CLEAR_CONTEXT_MATERIALIZED_ENTRY = | ||
| "vessup:clear-context-materialized"; | ||
| export const CLEAR_CONTEXT_COMPLETE_MESSAGE = "Context cleared."; | ||
| const CLEAR_COMPACTION_DETAIL = "clearContextBoundary"; | ||
|
|
||
| function latestActiveClear( | ||
| entries: readonly SessionEntry[], | ||
| ): SessionEntry | undefined { | ||
| for (let index = entries.length - 1; index >= 0; index -= 1) { | ||
| const entry = entries[index]; | ||
| if (entry?.type !== "custom") continue; | ||
| if (entry.customType === CLEAR_CONTEXT_MATERIALIZED_ENTRY) return undefined; | ||
| if (entry.customType === CLEAR_CONTEXT_ENTRY) return entry; | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| /** Add a durable boundary after which earlier conversation is excluded from LLM context. */ | ||
| export function clearSessionContext( | ||
| pi: Pick<ExtensionAPI, "appendEntry">, | ||
| ): void { | ||
| pi.appendEntry(CLEAR_CONTEXT_ENTRY); | ||
| } | ||
|
|
||
| /** Preserve the transcript while returning only context messages after the latest clear boundary. */ | ||
| export function contextAfterLatestClear( | ||
| entries: readonly SessionEntry[], | ||
| ): ContextEvent["messages"] | undefined { | ||
| const clear = latestActiveClear(entries); | ||
| if (!clear) return undefined; | ||
| const clearIndex = entries.indexOf(clear); | ||
| return entries | ||
| .slice(clearIndex + 1) | ||
| .flatMap((entry) => sessionEntryToContextMessages(entry)); | ||
| } | ||
|
|
||
| function preparePostClearCompaction( | ||
| entries: SessionEntry[], | ||
| settings: { keepRecentTokens: number; reserveTokens: number }, | ||
| ): | ||
| | { | ||
| firstKeptEntryId: string; | ||
| messagesToSummarize: ContextEvent["messages"]; | ||
| turnPrefixMessages: ContextEvent["messages"]; | ||
| tokensBefore: number; | ||
| settings: typeof settings; | ||
| } | ||
| | undefined { | ||
| const cutPoint = findCutPoint( | ||
| entries, | ||
| 0, | ||
| entries.length, | ||
| settings.keepRecentTokens, | ||
| ); | ||
| const firstKeptEntry = entries[cutPoint.firstKeptEntryIndex]; | ||
| if (!firstKeptEntry?.id) return undefined; | ||
| const historyEnd = cutPoint.isSplitTurn | ||
| ? cutPoint.turnStartIndex | ||
| : cutPoint.firstKeptEntryIndex; | ||
| const messagesToSummarize = entries | ||
| .slice(0, historyEnd) | ||
| .flatMap((entry) => sessionEntryToContextMessages(entry)); | ||
| const turnPrefixMessages = cutPoint.isSplitTurn | ||
| ? entries | ||
| .slice(cutPoint.turnStartIndex, cutPoint.firstKeptEntryIndex) | ||
| .flatMap((entry) => sessionEntryToContextMessages(entry)) | ||
| : []; | ||
| if (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0) | ||
| return undefined; | ||
| return { | ||
| firstKeptEntryId: firstKeptEntry.id, | ||
| messagesToSummarize, | ||
| turnPrefixMessages, | ||
| tokensBefore: entries | ||
| .flatMap((entry) => sessionEntryToContextMessages(entry)) | ||
| .reduce((total, message) => total + estimateTokens(message), 0), | ||
| settings, | ||
| }; | ||
| } | ||
|
|
||
| export default function clearContextExtension(pi: ExtensionAPI): void { | ||
| pi.registerCommand("clear", { | ||
| description: "Clear conversation context while keeping the transcript", | ||
| handler: async (args, ctx) => { | ||
| if (args.trim()) { | ||
| ctx.ui.notify("/clear does not accept arguments", "error"); | ||
| return; | ||
| } | ||
| await ctx.waitForIdle(); | ||
| clearSessionContext(pi); | ||
| ctx.ui.notify(CLEAR_CONTEXT_COMPLETE_MESSAGE, "info"); | ||
| }, | ||
| }); | ||
|
|
||
| pi.on("context", (_event, ctx) => { | ||
| const messages = contextAfterLatestClear( | ||
| ctx.sessionManager.buildContextEntries(), | ||
| ); | ||
| return messages === undefined ? undefined : { messages }; | ||
| }); | ||
|
|
||
| // Pi prepares compaction from the raw branch rather than the context hook's | ||
| // filtered messages. Rebuild preparation from the post-clear branch so neither | ||
| // automatic nor explicit compaction can summarize pre-clear text. | ||
| pi.on("session_before_compact", async (event, ctx) => { | ||
| const clear = latestActiveClear(event.branchEntries); | ||
| if (!clear) return undefined; | ||
|
|
||
| const clearIndex = event.branchEntries.indexOf(clear); | ||
| const postClearEntries = event.branchEntries | ||
| .slice(clearIndex) | ||
| .map((entry, index) => | ||
| index === 0 ? { ...entry, parentId: null } : entry, | ||
| ); | ||
| const preparation = preparePostClearCompaction( | ||
| postClearEntries, | ||
| event.preparation.settings, | ||
| ); | ||
| if (!preparation) { | ||
| return { | ||
| compaction: { | ||
| summary: "", | ||
| firstKeptEntryId: clear.id, | ||
| tokensBefore: event.preparation.tokensBefore, | ||
| details: { [CLEAR_COMPACTION_DETAIL]: true }, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| const model = ctx.model; | ||
| if (!model) return { cancel: true }; | ||
| const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); | ||
| if (!auth.ok) throw new Error(auth.error); | ||
| const response = await generateSummaryWithUsage( | ||
| [...preparation.messagesToSummarize, ...preparation.turnPrefixMessages], | ||
| model, | ||
| preparation.settings.reserveTokens, | ||
| auth.apiKey, | ||
| auth.headers | ||
| ? Object.fromEntries( | ||
| Object.entries(auth.headers).flatMap(([key, value]) => | ||
| typeof value === "string" ? [[key, value]] : [], | ||
| ), | ||
| ) | ||
| : undefined, | ||
| event.signal, | ||
| event.customInstructions, | ||
| undefined, | ||
| ctx.thinkingLevel, | ||
| ); | ||
| return { | ||
| compaction: { | ||
| summary: response.text, | ||
| firstKeptEntryId: preparation.firstKeptEntryId, | ||
| tokensBefore: preparation.tokensBefore, | ||
| usage: response.usage, | ||
| details: { [CLEAR_COMPACTION_DETAIL]: true }, | ||
|
ianwalter marked this conversation as resolved.
|
||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| pi.on("session_compact", (event) => { | ||
| const details = event.compactionEntry.details; | ||
| if ( | ||
| !details || | ||
| typeof details !== "object" || | ||
| !(CLEAR_COMPACTION_DETAIL in details) | ||
| ) | ||
| return; | ||
| pi.appendEntry(CLEAR_CONTEXT_MATERIALIZED_ENTRY); | ||
| }); | ||
| } | ||
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.
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.