Add before_compact hook event (closes #281) (#285)

* Add before_compact hook event (closes #281)

* Add compact hook event and documentation

- Add compact event that fires after compaction completes
- Update hooks.md with lifecycle diagram, field docs, and example
- Add CHANGELOG entry
- Add comprehensive test coverage (10 tests) for before_compact and compact events
- Tests cover: event emission, cancellation, custom entry, error handling, multiple hooks
This commit is contained in:
Nico Bailon 2025-12-24 02:26:29 -08:00 committed by GitHub
parent 20b24cf5a4
commit 1e1a92ea47
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 700 additions and 36 deletions

View file

@ -6,8 +6,9 @@
*/
import type { AppMessage, Attachment } from "@mariozechner/pi-agent-core";
import type { ImageContent, TextContent, ToolResultMessage } from "@mariozechner/pi-ai";
import type { SessionEntry } from "../session-manager.js";
import type { ImageContent, Model, TextContent, ToolResultMessage } from "@mariozechner/pi-ai";
import type { CutPointResult } from "../compaction.js";
import type { CompactionEntry, SessionEntry } from "../session-manager.js";
import type {
BashToolDetails,
FindToolDetails,
@ -111,6 +112,7 @@ interface SessionEventBase {
* - before_switch / switch: Session switch (e.g., /resume command)
* - before_clear / clear: Session clear (e.g., /clear command)
* - before_branch / branch: Session branch (e.g., /branch command)
* - before_compact / compact: Before/after context compaction
* - shutdown: Process exit (SIGINT/SIGTERM)
*
* "before_*" events fire before the action and can be cancelled via SessionEventResult.
@ -124,6 +126,22 @@ export type SessionEvent =
reason: "branch" | "before_branch";
/** Index of the turn to branch from */
targetTurnIndex: number;
})
| (SessionEventBase & {
reason: "before_compact";
cutPoint: CutPointResult;
messagesToSummarize: AppMessage[];
tokensBefore: number;
customInstructions?: string;
model: Model<any>;
apiKey: string;
})
| (SessionEventBase & {
reason: "compact";
compactionEntry: CompactionEntry;
tokensBefore: number;
/** Whether the compaction entry was provided by a hook */
fromHook: boolean;
});
/**
@ -325,6 +343,8 @@ export interface SessionEventResult {
cancel?: boolean;
/** If true (for before_branch only), skip restoring conversation to branch point while still creating the branched session file */
skipConversationRestore?: boolean;
/** Custom compaction entry (for before_compact event) */
compactionEntry?: CompactionEntry;
}
// ============================================================================