import { StringEnum } from "@earendil-works/pi-ai"; import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; const TOOL = "forget"; const DETAILS_KIND = "forget"; const REMINDER = "Context hygiene: use forget for safe prefix cuts in long mixed-task sessions. current_user=new task; previous_user=keep immediate setup. Skip if prior context may be needed."; type ForgetTarget = "current_user" | "previous_user"; interface ForgetParams { target?: ForgetTarget | string; reason?: string; } interface BranchEntry { type?: string; id?: string; message?: { role?: string; content?: unknown }; [key: string]: unknown; } interface TargetResolution { ok: boolean; target: ForgetTarget; offset: 0 | 1; index: number; userCount: number; entry?: BranchEntry; code?: string; hint?: string; } interface ForgetResultDetails { kind?: typeof DETAILS_KIND; version?: number; code?: string; skipped?: boolean; compactionId?: string; target?: ForgetTarget | string; offset?: 0 | 1; keptFromEntryId?: string; keptPreview?: string; forgottenBefore?: number; reason?: string; } function textResult(text: string, details?: Record) { return { content: [{ type: "text" as const, text }], details }; } function errorResult( code: string, hint: string, details?: Record, ) { return { content: [{ type: "text" as const, text: `${code}. ${hint}` }], isError: true, details: { kind: DETAILS_KIND, code, ...details }, }; } function compactWhitespace(text: string): string { return text.replace(/\s+/g, " ").trim(); } function safeInline(text: unknown): string { return compactWhitespace( String(text ?? "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""), ); } function contentText(content: unknown): string { if (typeof content === "string") return content; if (Array.isArray(content)) { return content .map((part) => { if (typeof part === "string") return part; if (part && typeof part === "object" && "text" in part) { const text = (part as { text?: unknown }).text; return typeof text === "string" ? text : ""; } return ""; }) .filter(Boolean) .join(" "); } return ""; } function entryPreview( entry: BranchEntry | undefined, max = 180, ): string | undefined { const text = safeInline(contentText(entry?.message?.content)); if (!text) return undefined; return text.length > max ? `${text.slice(0, max - 1)}…` : text; } function firstText(result: { content?: Array<{ type?: string; text?: string }>; }) { return result.content?.find((part) => part?.type === "text")?.text ?? ""; } function userIndexes(branch: BranchEntry[]): number[] { const indexes: number[] = []; for (let i = 0; i < branch.length; i++) { const entry = branch[i]; if (entry?.type === "message" && entry.message?.role === "user") indexes.push(i); } return indexes; } function normalizeTarget(target: unknown): ForgetTarget | undefined { if (target === undefined || target === null || target === "") return "current_user"; if (target === "current_user" || target === "previous_user") return target; if (target === "current" || target === "latest" || target === "user:0") return "current_user"; if (target === "previous" || target === "prev" || target === "user:1") return "previous_user"; return undefined; } function resolveTarget( branch: BranchEntry[], rawTarget?: unknown, ): TargetResolution { const target = normalizeTarget(rawTarget); if (!target) return { ok: false, target: "current_user", offset: 0, index: -1, userCount: 0, code: "bad_target", hint: "use current_user or previous_user", }; const offset = target === "current_user" ? 0 : 1; const users = userIndexes(branch); const position = users.length - 1 - offset; if (position < 0) return { ok: false, target, offset, index: -1, userCount: users.length, code: "no_boundary", hint: offset === 1 ? "no previous user; use current_user or skip" : "no current user", }; const index = users[position]; return { ok: true, target, offset, index, userCount: users.length, entry: branch[index], }; } function forgetSummary(resolution: TargetResolution, reason?: string): string { return [ "[Forget] Earlier conversation context intentionally removed from active LLM context.", `Kept from ${resolution.target} entry ${resolution.entry?.id ?? "?"}.`, `Reason: ${reason?.trim() || "context budget"}.`, "History remains append-only/recoverable; active prompt context changed only.", ].join("\n"); } function countTokensBefore(ctx: { getContextUsage?: () => { tokens?: number | null } | undefined; }): number { const tokens = ctx.getContextUsage?.()?.tokens; return typeof tokens === "number" && Number.isFinite(tokens) ? tokens : 0; } function appendForgetCompaction( ctx: unknown, resolution: TargetResolution, reason?: string, ): string { const sessionManager = (ctx as { sessionManager?: unknown }) .sessionManager as { appendCompaction?: ( summary: string, firstKeptEntryId: string, tokensBefore: number, details?: unknown, fromHook?: boolean, ) => string; }; if (typeof sessionManager?.appendCompaction !== "function") throw new Error( "SessionManager appendCompaction unavailable in this Pi runtime", ); return sessionManager.appendCompaction( forgetSummary(resolution, reason), resolution.entry?.id ?? "", countTokensBefore( ctx as { getContextUsage?: () => { tokens?: number | null } | undefined }, ), { kind: DETAILS_KIND, version: 2, target: resolution.target, keptFromEntryId: resolution.entry?.id, forgottenBefore: resolution.index, reason, }, true, ); } function renderForgetCall(args: ForgetParams, theme: any) { const target = normalizeTarget(args.target) ?? safeInline(args.target ?? "current_user"); let text = theme.fg("toolTitle", theme.bold("◌ forget ")); text += theme.fg("accent", target); const reason = safeInline(args.reason); if (reason) text += theme.fg("dim", ` — ${reason}`); return new Text(text, 0, 0); } function renderForgetResult( result: { content?: Array<{ type?: string; text?: string }>; details?: unknown; isError?: boolean; }, options: { expanded?: boolean; isPartial?: boolean }, theme: any, ) { if (options.isPartial) return new Text(theme.fg("warning", "◌ forgetting context…"), 0, 0); const details = result.details as ForgetResultDetails | undefined; if (result.isError || details?.code) { const msg = safeInline( firstText(result) || details?.code || "forget failed", ); return new Text(theme.fg("error", `✗ ${msg}`), 0, 0); } if (details?.skipped) { let text = theme.fg("muted", "↷ nothing to forget"); if (details.target) text += theme.fg("dim", ` · ${details.target}`); return new Text(text, 0, 0); } let text = theme.fg("success", "✓ "); text += theme.fg("accent", `kept ${details?.target ?? "boundary"}`); if (typeof details?.forgottenBefore === "number") text += theme.fg("dim", ` · dropped ${details.forgottenBefore} entries`); if (details?.keptPreview) text += `\n ${theme.fg("muted", "↳ kept context:")} ${theme.fg("dim", details.keptPreview)}`; if (options.expanded) { if (details?.reason) text += `\n ${theme.fg("muted", "reason:")} ${theme.fg("dim", safeInline(details.reason))}`; if (details?.keptFromEntryId) text += `\n ${theme.fg("muted", "entry:")} ${theme.fg("dim", details.keptFromEntryId)}`; if (details?.compactionId) text += `\n ${theme.fg("muted", "compaction:")} ${theme.fg("dim", details.compactionId)}`; text += `\n ${theme.fg("muted", "history append-only; active context prefix-cut only")}`; } return new Text(text, 0, 0); } export const __test = { appendForgetCompaction, entryPreview, forgetSummary, normalizeTarget, REMINDER, renderForgetCall, renderForgetResult, resolveTarget, userIndexes, }; export default function (pi: ExtensionAPI) { pi.on("before_agent_start", (event) => { if (event.systemPrompt.includes(REMINDER)) return undefined; return { systemPrompt: `${event.systemPrompt}\n\n${REMINDER}` }; }); pi.registerTool({ name: TOOL, label: "Forget", description: "Context-budget tool. Drops older active context before current_user or previous_user. Not privacy deletion.", promptSnippet: "forget(target?, reason?) — prefix-cut active context before current_user or previous_user", promptGuidelines: [ "target=current_user: latest user starts an independent new task; drop older context.", "target=previous_user: latest request depends on immediate prior setup; keep that setup and drop older context.", "Skip forget if prior discussion may be needed or no safe prefix cut exists.", ], parameters: Type.Object({ target: Type.Optional( StringEnum(["current_user", "previous_user"] as const, { description: "Prefix-cut boundary. Defaults to current_user.", }), ), reason: Type.Optional( Type.String({ description: "Short reason for context compaction" }), ), }), renderCall: renderForgetCall, renderResult: renderForgetResult, async execute(_toolCallId, params: ForgetParams, _signal, _onUpdate, ctx) { const branch = ctx.sessionManager.getBranch() as unknown as BranchEntry[]; const resolution = resolveTarget(branch, params.target); if (!resolution.ok) return errorResult( resolution.code ?? "invalid", resolution.hint ?? "skip forget", { target: params.target }, ); if (resolution.target === "current_user" && resolution.userCount <= 1) return textResult("already_first. nothing to forget", { kind: DETAILS_KIND, version: 3, skipped: true, target: resolution.target, keptFromEntryId: resolution.entry?.id, keptPreview: entryPreview(resolution.entry), forgottenBefore: 0, }); const compactionId = appendForgetCompaction( ctx, resolution, params.reason, ); return textResult( `done. kept=${resolution.target} dropped_entries=${resolution.index}`, { kind: DETAILS_KIND, version: 3, compactionId, target: resolution.target, offset: resolution.offset, keptFromEntryId: resolution.entry?.id, keptPreview: entryPreview(resolution.entry), forgottenBefore: resolution.index, reason: params.reason, }, ); }, }); }