repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

chore: remove forget extension

51b2c89b6a8337845484b12a68b1fc57714f3a3a

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (10)

+0 / −962 text lines

Diff layout

README.md

Modified

+0 / −1 text lines

6969| `devil` | Structured `/devil` stress test against a devil's advocate and defender. | [README](extensions/devil/README.md) |
7070| `diff-review` | Browser UI for reviewing git diffs and sending findings back to Pi. | [README](extensions/diff-review/README.md) |
7171| `fast` | OpenAI Codex priority service tier for Pi. | [README](extensions/fast/README.md) |
72| `forget` | Experimental active-context forgetting tool for Pi. | [README](extensions/forget/README.md) |
7372| `footer` | Shared stable footer renderer for Pi. | [README](extensions/footer/README.md) |
7473| `ghost` | Background Pi agent overlay for quick side-channel prompts. | [README](extensions/ghost/README.md) |
7574| `git-safe` | Hardened git clone tool for Pi. | [README](extensions/git-safe/README.md) |

extensions/forget/CHANGELOG.md

Deleted
deleted file mode 100644

+0 / −8 text lines

1# changelog
2
3## unreleased
4
5- Add experimental `forget` tool.
6- Replace inspect/id flow with `current_user` and `previous_user` prefix cuts.
7- Add short per-prompt context-hygiene reminder.
8- Add unit, harness, and optional real MiniMax tests.

extensions/forget/PLAN.md

Deleted
deleted file mode 100644

+0 / −74 text lines

1# forget plan
2
3Experimental goal:
4let the model manage stale active context in long mixed-task sessions with one
5small prefix-cut API.
6
7## SDK constraints
8
9- Pi session files are append-only.
10 Entries cannot be modified or physically deleted through `SessionManager`.
11- Active context can still be changed safely by adding a compaction entry.
12 `appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook)`
13 makes `buildSessionContext()` emit the summary, then branch messages from
14 `firstKeptEntryId` onward.
15- Recent tail deletion is already covered by Pi tree navigation/forking.
16 It is out of scope for Forget.
17- Middle deletion is not supported without replaying or filtering the
18 transcript.
19 Replay breaks IDs/tool-call adjacency; per-turn filtering is fragile and not a
20 persistent session edit.
22## Design
24- Tool:
25 `forget(target?, reason?)`
26 - `target="current_user"`:
27 keep the latest user request onward; drop older active context.
28 - `target="previous_user"`:
29 keep the immediately previous user request onward; drop older active
30 context.
31 - omitted `target` defaults to `current_user`.
32- Per-prompt system reminder:
33 short turn-local line tells the agent to consider Forget in long mixed-task
34 sessions and skip when prior context may still be needed.
35- Guardrails:
36 - no entry IDs exposed to the model.
37 - no inspect/debug/status tool.
38 - no ranges or holes.
39 - target must resolve to a user message on the active branch.
40 - no physical deletion claim; JSONL keeps recoverable history.
41 - not a secret-redaction guarantee; newer/current messages and model thinking
42 can still contain sensitive strings.
44## Real-provider learnings
46- Long-session probes showed `previous_user` is useful for preserving immediate
47 setup while dropping older task context.
48- Kimi and OpenAI used the API best in long mixed-task sessions.
49- Z.ai used it aggressively but still gained context cleanup.
50- MiniMax often ignored the tool; that is acceptable for weak-tool models.
51- `inspect`, raw entry IDs, `status`, and `user:<offset>` added complexity
52 without reliable model gains.
54## Tests
56- Unit:
57 target normalization, user-boundary resolution, terse errors, tombstone
58 summary.
59- Harness:
60 extension loads, tool registers, reminder injects, `current_user` and
61 `previous_user` create compactions with expected `firstKeptEntryId`, context
62 drops old text, invalid targets fail tersely.
63- Real MiniMax:
64 optional `FORGET_REAL=1`; runs isolated SDK session with only Forget loaded,
65 calls the tool directly, verifies compaction is active.
67## Manual test
69```bash
70cd extensions/forget
71bun test
72FORGET_REAL=1 bun run test:real
73pi -e ./index.ts --model kimi-coding/kimi-for-coding
74```

extensions/forget/README.md

Deleted
deleted file mode 100644

+0 / −62 text lines

1# forget
2
3Experimental active-context forgetting for Pi.
4
5## Install / load
6
7Loaded through the root `pi-ext` package.
8See [root README](../../README.md).
9
10## Commands / tools / settings
12Commands:
13none.
15Tools:
17- `forget`:
18 drops older active context before `current_user` or `previous_user`.
20Settings:
21none.
23Hooks/events:
25- `before_agent_start`:
26 injects one short reminder so the agent considers Forget in long mixed-task
27 sessions.
29## Behavior
31`forget` appends a Pi compaction entry. Active LLM context becomes:
331. a short tombstone summary saying prior context was intentionally forgotten;
342. branch messages from the chosen user boundary onward;
353. future messages.
37Targets:
39- `current_user`:
40 keep the latest user request onward. Use for independent new tasks.
41- `previous_user`:
42 keep the immediately previous user request onward. Use when the latest request
43 depends on immediate setup but older context is stale.
45If `target` is omitted, `current_user` is used.
47History is not physically deleted from the JSONL session file.
48It is removed from the active context path by Pi compaction semantics and can be
49recovered through tree/session history.
51Forget is a context-budget tool, not a secrecy/redaction tool.
52If sensitive text appears in the current request, assistant reasoning, tool
53results, or later messages, Forget cannot remove that newer span without also
54dropping the newer branch.
56Middle deletion is intentionally unsupported.
57Pi sessions are append-only, so Forget only performs prefix cuts.
59The injected reminder is turn-local system prompt text, not a stored reminder
60message.
61It costs a short line each turn but does not accumulate inside the session
62transcript.

extensions/forget/__tests__/harness.test.ts

Deleted
deleted file mode 100644

+0 / −147 text lines

1import { afterEach, describe, expect, it } from "vitest";
2import path from "node:path";
3import {
4 createTestSession,
5 type TestSession,
6} from "@marcfargas/pi-test-harness";
7
8let t: TestSession | undefined;
9
10afterEach(() => {
11 t?.dispose();
12 t = undefined;
13});
15function forgetPath(): string {
16 return path.resolve(import.meta.dir, "../index.ts");
17}
19function textOf(result: any): string {
20 return result.content
21 .map((part: { text?: string }) => part.text ?? "")
22 .join("\n");
23}
25async function callForget(params: Record<string, unknown>) {
26 const tool = t!.session.extensionRunner.getToolDefinition("forget");
27 return tool.execute(
28 "call-1",
29 params,
30 undefined,
31 undefined,
32 t!.session.extensionRunner.createContext(),
33 );
34}
36describe("forget harness integration", () => {
37 it("loads and registers only the forget tool", async () => {
38 t = await createTestSession({ extensions: [forgetPath()] });
39 const [extension] = t.session.extensionRunner.extensions;
40 expect([...extension.tools.keys()]).toContain("forget");
41 expect([...extension.commands.keys()]).toEqual([]);
42 });
44 it("current_user appends compaction and drops older active context", async () => {
45 t = await createTestSession({ extensions: [forgetPath()] });
46 t.session.sessionManager.appendMessage({
47 role: "user",
48 content: [{ type: "text", text: "OLD_SECRET_DO_NOT_KEEP" }],
49 });
50 const keep = t.session.sessionManager.appendMessage({
51 role: "user",
52 content: [{ type: "text", text: "new safe request" }],
53 });
54 t.session.sessionManager.appendMessage({
55 role: "assistant",
56 content: [{ type: "text", text: "safe answer" }],
57 });
59 const result = await callForget({
60 target: "current_user",
61 reason: "new task",
62 });
63 expect(textOf(result)).toContain("done. kept=current_user");
65 const compaction = t.session.sessionManager
66 .getEntries()
67 .find((entry: any) => entry.type === "compaction") as any;
68 expect(compaction).toBeTruthy();
69 expect(compaction.firstKeptEntryId).toBe(keep);
70 expect(compaction.fromHook).toBe(true);
71 expect(compaction.details).toMatchObject({
72 kind: "forget",
73 version: 2,
74 target: "current_user",
75 keptFromEntryId: keep,
76 reason: "new task",
77 });
78 expect(compaction.details.forgottenBefore).toBeGreaterThan(0);
80 const context = (t.session.sessionManager as any).buildSessionContext();
81 const serialized = JSON.stringify(context.messages);
82 expect(serialized).toContain("[Forget]");
83 expect(serialized).toContain("new safe request");
84 expect(serialized).toContain("safe answer");
85 expect(serialized).not.toContain("OLD_SECRET_DO_NOT_KEEP");
86 });
88 it("previous_user keeps immediate setup and drops older context", async () => {
89 t = await createTestSession({ extensions: [forgetPath()] });
90 t.session.sessionManager.appendMessage({
91 role: "user",
92 content: [{ type: "text", text: "OLD_ARCHIVE" }],
93 });
94 t.session.sessionManager.appendMessage({
95 role: "assistant",
96 content: [{ type: "text", text: "ok" }],
97 });
98 const setup = t.session.sessionManager.appendMessage({
99 role: "user",
100 content: [{ type: "text", text: "SETUP_KEEP_ME" }],
101 });
102 t.session.sessionManager.appendMessage({
103 role: "user",
104 content: [{ type: "text", text: "continue setup" }],
105 });
107 const result = await callForget({ target: "previous_user" });
108 expect(textOf(result)).toContain("done. kept=previous_user");
110 const compaction = t.session.sessionManager
111 .getEntries()
112 .find((entry: any) => entry.type === "compaction") as any;
113 expect(compaction.firstKeptEntryId).toBe(setup);
114 expect(compaction.details.target).toBe("previous_user");
116 const context = (t.session.sessionManager as any).buildSessionContext();
117 const serialized = JSON.stringify(context.messages);
118 expect(serialized).toContain("SETUP_KEEP_ME");
119 expect(serialized).toContain("continue setup");
120 expect(serialized).not.toContain("OLD_ARCHIVE");
121 });
123 it("returns terse errors and no-op when no safe cut exists", async () => {
124 t = await createTestSession({ extensions: [forgetPath()] });
125 const bad = await callForget({ target: "user:2" });
126 expect(bad.isError).toBe(true);
127 expect(textOf(bad)).toBe("bad_target. use current_user or previous_user");
129 t.session.sessionManager.appendMessage({
130 role: "user",
131 content: [{ type: "text", text: "first" }],
132 });
133 const previous = await callForget({ target: "previous_user" });
134 expect(previous.isError).toBe(true);
135 expect(textOf(previous)).toBe(
136 "no_boundary. no previous user; use current_user or skip",
137 );
139 const current = await callForget({ target: "current_user" });
140 expect(textOf(current)).toBe("already_first. nothing to forget");
141 expect(
142 t.session.sessionManager
143 .getEntries()
144 .some((entry: any) => entry.type === "compaction"),
145 ).toBe(false);
146 });
147});

extensions/forget/__tests__/real/minimax.test.ts

Deleted
deleted file mode 100644

+0 / −105 text lines

1import { describe, expect, it } from "vitest";
2import fs from "node:fs";
3import os from "node:os";
4import path from "node:path";
5import { getModel } from "@earendil-works/pi-ai";
6import {
7 AuthStorage,
8 createAgentSession,
9 DefaultResourceLoader,
10 ModelRegistry,
11 SessionManager,
12 SettingsManager,
13} from "@earendil-works/pi-coding-agent";
15const real = process.env.FORGET_REAL === "1";
16const d = real ? describe : describe.skip;
18function textOf(result: any): string {
19 return result.content
20 .map((part: { text?: string }) => part.text ?? "")
21 .join("\n");
22}
24d("real MiniMax integration", () => {
25 it("runs isolated SDK session then forgets older active context", async () => {
26 const temp = fs.mkdtempSync(path.join(os.tmpdir(), "forget-real-"));
27 const cwd = path.join(temp, "cwd");
28 const agentDir = path.join(temp, "agent");
29 fs.mkdirSync(cwd, { recursive: true });
30 fs.mkdirSync(agentDir, { recursive: true });
32 const forgetPath = path.resolve(import.meta.dir, "../../index.ts");
33 const settingsManager = SettingsManager.inMemory({
34 defaultProvider: "minimax",
35 defaultModel: "MiniMax-M2.7-highspeed",
36 defaultThinkingLevel: "off",
37 });
39 const loader = new DefaultResourceLoader({
40 cwd,
41 agentDir,
42 settingsManager,
43 noExtensions: true,
44 noSkills: true,
45 noPromptTemplates: true,
46 noThemes: true,
47 noContextFiles: true,
48 additionalExtensionPaths: [forgetPath],
49 });
50 await loader.reload();
52 const authStorage = AuthStorage.create();
53 const modelRegistry = ModelRegistry.create(authStorage);
54 const model = getModel("minimax", "MiniMax-M2.7-highspeed");
55 const { session, extensionsResult } = await createAgentSession({
56 cwd,
57 agentDir,
58 authStorage,
59 modelRegistry,
60 model,
61 thinkingLevel: "off",
62 sessionManager: SessionManager.inMemory(),
63 settingsManager,
64 resourceLoader: loader,
65 noTools: "all",
66 });
68 try {
69 expect(extensionsResult.extensions.map((e) => e.path)).toEqual([
70 forgetPath,
71 ]);
73 await session.prompt("Reply exactly OK. Remember OLD_REAL_SECRET_TOKEN.");
74 await session.agent.waitForIdle();
75 const keep = session.sessionManager.appendMessage({
76 role: "user",
77 content: [{ type: "text", text: "New safe context starts here." }],
78 });
80 const tool = session.extensionRunner.getToolDefinition("forget");
81 const result = await tool.execute(
82 "real-call-1",
83 { target: "current_user", reason: "new task" },
84 undefined,
85 undefined,
86 session.extensionRunner.createContext(),
87 );
88 expect(textOf(result)).toContain("done. kept=current_user");
90 const compaction = session.sessionManager
91 .getEntries()
92 .find((entry: any) => entry.type === "compaction") as any;
93 expect(compaction.firstKeptEntryId).toBe(keep);
94 expect(compaction.details.target).toBe("current_user");
96 const context = (session.sessionManager as any).buildSessionContext();
97 const serialized = JSON.stringify(context.messages);
98 expect(serialized).toContain("New safe context starts here");
99 expect(serialized).not.toContain("OLD_REAL_SECRET_TOKEN");
100 } finally {
101 session.dispose();
102 fs.rmSync(temp, { recursive: true, force: true });
103 }
104 }, 120000);
105});

extensions/forget/__tests__/unit.test.ts

Deleted
deleted file mode 100644

+0 / −157 text lines

1import { describe, expect, test } from "vitest";
2import forgetExtension, { __test } from "../index.ts";
3
4const {
5 entryPreview,
6 forgetSummary,
7 normalizeTarget,
8 REMINDER,
9 renderForgetCall,
10 renderForgetResult,
11 resolveTarget,
12 userIndexes,
13} = __test;
15const theme = {
16 bold: (text: string) => text,
17 fg: (_tone: string, text: string) => text,
18};
20function rendered(component: { render(width: number): string[] }) {
21 return component.render(120).join("\n");
22}
24function msg(id: string, role: string, text: string) {
25 return {
26 type: "message",
27 id,
28 parentId: null,
29 timestamp: "",
30 message: { role, content: text },
31 };
32}
34describe("forget pure helpers", () => {
35 test("registers short before-agent reminder", () => {
36 const handlers = new Map<string, any>();
37 forgetExtension({
38 on: (name: string, handler: unknown) => handlers.set(name, handler),
39 registerTool: () => undefined,
40 } as never);
42 const handler = handlers.get("before_agent_start");
43 const result = handler({ systemPrompt: "base" });
44 expect(result.systemPrompt).toContain(REMINDER);
45 expect(REMINDER).toContain("current_user");
46 expect(REMINDER).toContain("previous_user");
47 });
49 test("normalizes model-friendly target aliases", () => {
50 expect(normalizeTarget(undefined)).toBe("current_user");
51 expect(normalizeTarget("")).toBe("current_user");
52 expect(normalizeTarget("current")).toBe("current_user");
53 expect(normalizeTarget("user:0")).toBe("current_user");
54 expect(normalizeTarget("prev")).toBe("previous_user");
55 expect(normalizeTarget("user:1")).toBe("previous_user");
56 expect(normalizeTarget("user:2")).toBeUndefined();
57 });
59 test("finds user boundaries", () => {
60 const branch = [
61 msg("u1", "user", "one"),
62 msg("a1", "assistant", "two"),
63 msg("u2", "user", "three"),
64 ];
65 expect(userIndexes(branch)).toEqual([0, 2]);
66 });
68 test("resolves current and previous user prefix cuts", () => {
69 const branch = [
70 msg("u1", "user", "old"),
71 msg("a1", "assistant", "answer"),
72 msg("u2", "user", "new"),
73 msg("a2", "assistant", "answer"),
74 ];
75 const current = resolveTarget(branch);
76 expect(current).toMatchObject({
77 ok: true,
78 target: "current_user",
79 offset: 0,
80 index: 2,
81 });
82 expect(current.entry?.id).toBe("u2");
84 const previous = resolveTarget(branch, "previous_user");
85 expect(previous).toMatchObject({
86 ok: true,
87 target: "previous_user",
88 offset: 1,
89 index: 0,
90 });
91 expect(previous.entry?.id).toBe("u1");
92 });
94 test("returns terse errors for bad or missing boundaries", () => {
95 expect(resolveTarget([], "wat")).toMatchObject({
96 ok: false,
97 code: "bad_target",
98 hint: "use current_user or previous_user",
99 });
100 expect(
101 resolveTarget([msg("u1", "user", "one")], "previous_user"),
102 ).toMatchObject({
103 ok: false,
104 code: "no_boundary",
105 hint: "no previous user; use current_user or skip",
106 });
107 });
109 test("forget summary is explicit tombstone not hidden data", () => {
110 const branch = [msg("u1", "user", "secret")];
111 const resolution = resolveTarget(branch);
112 const summary = forgetSummary(resolution, "new task");
113 expect(summary).toContain("intentionally removed");
114 expect(summary).toContain("current_user");
115 expect(summary).toContain("u1");
116 expect(summary).toContain("new task");
117 expect(summary).not.toContain("secret");
118 });
120 test("renders call and result with kept context preview", () => {
121 const branch = [msg("u1", "user", "keep this setup text")];
122 const resolution = resolveTarget(branch);
123 const preview = entryPreview(resolution.entry);
124 expect(preview).toBe("keep this setup text");
126 const call = rendered(
127 renderForgetCall(
128 { target: "previous_user", reason: "new direction" },
129 theme,
130 ),
131 );
132 expect(call).toContain("forget previous_user");
133 expect(call).toContain("new direction");
135 const result = rendered(
136 renderForgetResult(
137 {
138 content: [{ type: "text", text: "done" }],
139 details: {
140 target: "current_user",
141 keptPreview: preview,
142 keptFromEntryId: "u1",
143 forgottenBefore: 4,
144 reason: "new direction",
145 compactionId: "c1",
146 },
147 },
148 { expanded: true },
149 theme,
150 ),
151 );
152 expect(result).toContain("kept current_user");
153 expect(result).toContain("dropped 4 entries");
154 expect(result).toContain("keep this setup text");
155 expect(result).toContain("compaction: c1");
156 });
157});

extensions/forget/index.ts

Deleted
deleted file mode 100644

+0 / −364 text lines

1import { StringEnum } from "@earendil-works/pi-ai";
2import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3import { Text } from "@earendil-works/pi-tui";
4import { Type } from "typebox";
5
6const TOOL = "forget";
7const DETAILS_KIND = "forget";
8const REMINDER =
9 "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.";
11type ForgetTarget = "current_user" | "previous_user";
13interface ForgetParams {
14 target?: ForgetTarget | string;
15 reason?: string;
16}
18interface BranchEntry {
19 type?: string;
20 id?: string;
21 message?: { role?: string; content?: unknown };
22 [key: string]: unknown;
23}
25interface TargetResolution {
26 ok: boolean;
27 target: ForgetTarget;
28 offset: 0 | 1;
29 index: number;
30 userCount: number;
31 entry?: BranchEntry;
32 code?: string;
33 hint?: string;
34}
36interface ForgetResultDetails {
37 kind?: typeof DETAILS_KIND;
38 version?: number;
39 code?: string;
40 skipped?: boolean;
41 compactionId?: string;
42 target?: ForgetTarget | string;
43 offset?: 0 | 1;
44 keptFromEntryId?: string;
45 keptPreview?: string;
46 forgottenBefore?: number;
47 reason?: string;
48}
50function textResult(text: string, details?: Record<string, unknown>) {
51 return { content: [{ type: "text" as const, text }], details };
52}
54function errorResult(
55 code: string,
56 hint: string,
57 details?: Record<string, unknown>,
58) {
59 return {
60 content: [{ type: "text" as const, text: `${code}. ${hint}` }],
61 isError: true,
62 details: { kind: DETAILS_KIND, code, ...details },
63 };
64}
66function compactWhitespace(text: string): string {
67 return text.replace(/\s+/g, " ").trim();
68}
70function safeInline(text: unknown): string {
71 return compactWhitespace(
72 String(text ?? "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""),
73 );
74}
76function contentText(content: unknown): string {
77 if (typeof content === "string") return content;
78 if (Array.isArray(content)) {
79 return content
80 .map((part) => {
81 if (typeof part === "string") return part;
82 if (part && typeof part === "object" && "text" in part) {
83 const text = (part as { text?: unknown }).text;
84 return typeof text === "string" ? text : "";
85 }
86 return "";
87 })
88 .filter(Boolean)
89 .join(" ");
90 }
91 return "";
92}
94function entryPreview(
95 entry: BranchEntry | undefined,
96 max = 180,
97): string | undefined {
98 const text = safeInline(contentText(entry?.message?.content));
99 if (!text) return undefined;
100 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
101}
103function firstText(result: {
104 content?: Array<{ type?: string; text?: string }>;
105}) {
106 return result.content?.find((part) => part?.type === "text")?.text ?? "";
107}
109function userIndexes(branch: BranchEntry[]): number[] {
110 const indexes: number[] = [];
111 for (let i = 0; i < branch.length; i++) {
112 const entry = branch[i];
113 if (entry?.type === "message" && entry.message?.role === "user")
114 indexes.push(i);
115 }
116 return indexes;
117}
119function normalizeTarget(target: unknown): ForgetTarget | undefined {
120 if (target === undefined || target === null || target === "")
121 return "current_user";
122 if (target === "current_user" || target === "previous_user") return target;
123 if (target === "current" || target === "latest" || target === "user:0")
124 return "current_user";
125 if (target === "previous" || target === "prev" || target === "user:1")
126 return "previous_user";
127 return undefined;
128}
130function resolveTarget(
131 branch: BranchEntry[],
132 rawTarget?: unknown,
133): TargetResolution {
134 const target = normalizeTarget(rawTarget);
135 if (!target)
136 return {
137 ok: false,
138 target: "current_user",
139 offset: 0,
140 index: -1,
141 userCount: 0,
142 code: "bad_target",
143 hint: "use current_user or previous_user",
144 };
145 const offset = target === "current_user" ? 0 : 1;
146 const users = userIndexes(branch);
147 const position = users.length - 1 - offset;
148 if (position < 0)
149 return {
150 ok: false,
151 target,
152 offset,
153 index: -1,
154 userCount: users.length,
155 code: "no_boundary",
156 hint:
157 offset === 1
158 ? "no previous user; use current_user or skip"
159 : "no current user",
160 };
161 const index = users[position];
162 return {
163 ok: true,
164 target,
165 offset,
166 index,
167 userCount: users.length,
168 entry: branch[index],
169 };
170}
172function forgetSummary(resolution: TargetResolution, reason?: string): string {
173 return [
174 "[Forget] Earlier conversation context intentionally removed from active LLM context.",
175 `Kept from ${resolution.target} entry ${resolution.entry?.id ?? "?"}.`,
176 `Reason: ${reason?.trim() || "context budget"}.`,
177 "History remains append-only/recoverable; active prompt context changed only.",
178 ].join("\n");
179}
181function countTokensBefore(ctx: {
182 getContextUsage?: () => { tokens?: number | null } | undefined;
183}): number {
184 const tokens = ctx.getContextUsage?.()?.tokens;
185 return typeof tokens === "number" && Number.isFinite(tokens) ? tokens : 0;
186}
188function appendForgetCompaction(
189 ctx: unknown,
190 resolution: TargetResolution,
191 reason?: string,
192): string {
193 const sessionManager = (ctx as { sessionManager?: unknown })
194 .sessionManager as {
195 appendCompaction?: (
196 summary: string,
197 firstKeptEntryId: string,
198 tokensBefore: number,
199 details?: unknown,
200 fromHook?: boolean,
201 ) => string;
202 };
203 if (typeof sessionManager?.appendCompaction !== "function")
204 throw new Error(
205 "SessionManager appendCompaction unavailable in this Pi runtime",
206 );
207 return sessionManager.appendCompaction(
208 forgetSummary(resolution, reason),
209 resolution.entry?.id ?? "",
210 countTokensBefore(
211 ctx as { getContextUsage?: () => { tokens?: number | null } | undefined },
212 ),
213 {
214 kind: DETAILS_KIND,
215 version: 2,
216 target: resolution.target,
217 keptFromEntryId: resolution.entry?.id,
218 forgottenBefore: resolution.index,
219 reason,
220 },
221 true,
222 );
223}
225function renderForgetCall(args: ForgetParams, theme: any) {
226 const target =
227 normalizeTarget(args.target) ?? safeInline(args.target ?? "current_user");
228 let text = theme.fg("toolTitle", theme.bold("◌ forget "));
229 text += theme.fg("accent", target);
230 const reason = safeInline(args.reason);
231 if (reason) text += theme.fg("dim", ` — ${reason}`);
232 return new Text(text, 0, 0);
233}
235function renderForgetResult(
236 result: {
237 content?: Array<{ type?: string; text?: string }>;
238 details?: unknown;
239 isError?: boolean;
240 },
241 options: { expanded?: boolean; isPartial?: boolean },
242 theme: any,
243) {
244 if (options.isPartial)
245 return new Text(theme.fg("warning", "◌ forgetting context…"), 0, 0);
247 const details = result.details as ForgetResultDetails | undefined;
248 if (result.isError || details?.code) {
249 const msg = safeInline(
250 firstText(result) || details?.code || "forget failed",
251 );
252 return new Text(theme.fg("error", `✗ ${msg}`), 0, 0);
253 }
255 if (details?.skipped) {
256 let text = theme.fg("muted", "↷ nothing to forget");
257 if (details.target) text += theme.fg("dim", ` · ${details.target}`);
258 return new Text(text, 0, 0);
259 }
261 let text = theme.fg("success", "✓ ");
262 text += theme.fg("accent", `kept ${details?.target ?? "boundary"}`);
263 if (typeof details?.forgottenBefore === "number")
264 text += theme.fg("dim", ` · dropped ${details.forgottenBefore} entries`);
266 if (details?.keptPreview)
267 text += `\n ${theme.fg("muted", "↳ kept context:")} ${theme.fg("dim", details.keptPreview)}`;
269 if (options.expanded) {
270 if (details?.reason)
271 text += `\n ${theme.fg("muted", "reason:")} ${theme.fg("dim", safeInline(details.reason))}`;
272 if (details?.keptFromEntryId)
273 text += `\n ${theme.fg("muted", "entry:")} ${theme.fg("dim", details.keptFromEntryId)}`;
274 if (details?.compactionId)
275 text += `\n ${theme.fg("muted", "compaction:")} ${theme.fg("dim", details.compactionId)}`;
276 text += `\n ${theme.fg("muted", "history append-only; active context prefix-cut only")}`;
277 }
279 return new Text(text, 0, 0);
280}
282export const __test = {
283 appendForgetCompaction,
284 entryPreview,
285 forgetSummary,
286 normalizeTarget,
287 REMINDER,
288 renderForgetCall,
289 renderForgetResult,
290 resolveTarget,
291 userIndexes,
292};
294export default function (pi: ExtensionAPI) {
295 pi.on("before_agent_start", (event) => {
296 if (event.systemPrompt.includes(REMINDER)) return undefined;
297 return { systemPrompt: `${event.systemPrompt}\n\n${REMINDER}` };
298 });
300 pi.registerTool({
301 name: TOOL,
302 label: "Forget",
303 description:
304 "Context-budget tool. Drops older active context before current_user or previous_user. Not privacy deletion.",
305 promptSnippet:
306 "forget(target?, reason?) — prefix-cut active context before current_user or previous_user",
307 promptGuidelines: [
308 "target=current_user: latest user starts an independent new task; drop older context.",
309 "target=previous_user: latest request depends on immediate prior setup; keep that setup and drop older context.",
310 "Skip forget if prior discussion may be needed or no safe prefix cut exists.",
311 ],
312 parameters: Type.Object({
313 target: Type.Optional(
314 StringEnum(["current_user", "previous_user"] as const, {
315 description: "Prefix-cut boundary. Defaults to current_user.",
316 }),
317 ),
318 reason: Type.Optional(
319 Type.String({ description: "Short reason for context compaction" }),
320 ),
321 }),
322 renderCall: renderForgetCall,
323 renderResult: renderForgetResult,
324 async execute(_toolCallId, params: ForgetParams, _signal, _onUpdate, ctx) {
325 const branch = ctx.sessionManager.getBranch() as BranchEntry[];
326 const resolution = resolveTarget(branch, params.target);
327 if (!resolution.ok)
328 return errorResult(
329 resolution.code ?? "invalid",
330 resolution.hint ?? "skip forget",
331 { target: params.target },
332 );
333 if (resolution.target === "current_user" && resolution.userCount <= 1)
334 return textResult("already_first. nothing to forget", {
335 kind: DETAILS_KIND,
336 version: 3,
337 skipped: true,
338 target: resolution.target,
339 keptFromEntryId: resolution.entry?.id,
340 keptPreview: entryPreview(resolution.entry),
341 forgottenBefore: 0,
342 });
343 const compactionId = appendForgetCompaction(
344 ctx,
345 resolution,
346 params.reason,
347 );
348 return textResult(
349 `done. kept=${resolution.target} dropped_entries=${resolution.index}`,
350 {
351 kind: DETAILS_KIND,
352 version: 3,
353 compactionId,
354 target: resolution.target,
355 offset: resolution.offset,
356 keptFromEntryId: resolution.entry?.id,
357 keptPreview: entryPreview(resolution.entry),
358 forgottenBefore: resolution.index,
359 reason: params.reason,
360 },
361 );
362 },
363 });
364}

extensions/forget/package.json

Deleted
deleted file mode 100644

+0 / −27 text lines

1{
2 "name": "@bugabinga/pi-ext-forget",
3 "description": "Experimental active-context forgetting tool for pi",
4 "type": "module",
5 "main": "index.ts",
6 "scripts": {
7 "test:real": "FORGET_REAL=1 vitest run ./__tests__/real/*.test.ts --timeout 120000"
8 },
9 "keywords": [
10 "pi",
11 "extension",
12 "context",
13 "forget",
14 "pi-extension"
15 ],
16 "license": "MIT",
17 "peerDependencies": {
18 "@earendil-works/pi-ai": "*",
19 "@earendil-works/pi-coding-agent": "*",
20 "@earendil-works/pi-tui": "*",
21 "typebox": "*"
22 },
23 "devDependencies": {
24 "@marcfargas/pi-test-harness": "^0.6.1"
25 },
26 "private": true
27}

package-lock.json

Modified

+0 / −17 text lines

124124 "@earendil-works/pi-tui": "*"
125125 }
126126 },
127 "extensions/forget": {
128 "name": "@bugabinga/pi-ext-forget",
129 "license": "MIT",
130 "devDependencies": {
131 "@marcfargas/pi-test-harness": "^0.6.1"
132 },
133 "peerDependencies": {
134 "@earendil-works/pi-ai": "*",
135 "@earendil-works/pi-coding-agent": "*",
136 "@earendil-works/pi-tui": "*",
137 "typebox": "*"
138 }
139 },
140127 "extensions/ghost": {
141128 "name": "@bugabinga/pi-ext-ghost",
142129 "license": "MIT",
948935 "resolved": "extensions/footer",
949936 "link": true
950937 },
951 "node_modules/@bugabinga/pi-ext-forget": {
952 "resolved": "extensions/forget",
953 "link": true
954 },
955938 "node_modules/@bugabinga/pi-ext-ghost": {
956939 "resolved": "extensions/ghost",
957940 "link": true