repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(goldfish): add task gate experiment

eec3962578b002e92c1897bd0eaf317d4226ed41

Review <review@example.invalid> ·

unsigned

Browse filesCompare with HEAD

Changed files (9)

CHANGELOG.md

Modified
39 39 - Add a q corpus regression test that validates the extractor against the
40 40 gzip-compressed corpus and explains how to build the missing corpus
42 +- Fix goldfish startup so bare boolean `--goldfish` enables the gate after
43 + session start, uses `pi.exec` for checks, and keeps normal tools visible while
44 + hard-blocking them until `task.create` succeeds
45 +- Use `Alt+T` for the goldfish widget toggle to avoid Pi's built-in `Alt+F`
46 + shortcut conflict
47 +- Prompt goldfish agents after task creation to call `task.check` before any
48 + final answer, with regression and manual coverage for create-check-answer flow
49 +- Fix goldfish task output semantics so active tasks render as accent `◌`, done
50 + tasks as success `✓`, idle widgets as warning, and errors as error
42 52 ## 0.0.3
44 54 - Rename autoresearch to tune; add jj backend, state migration, timeout clamps

docs/super/plans/2026-06-22-goldfish.md

Added
new file mode 100644
1 +# Goldfish Implementation Plan
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
5 +**Goal:** Replace useless `forget` with `goldfish`, an automatic task-gated tool-use experiment that maps work to task segments.
7 +**Architecture:** `goldfish` is a Pi extension with one LLM-facing `task` tool, visible normal tools, hard `tool_call` enforcement while idle, and a persistent `aboveEditor` widget. State is persisted as custom session entries and replayed on `session_start` like `notes`.
9 +**Tech Stack:** TypeScript Pi extension API, Pi custom widgets, Vitest, existing `test/harness`, `mise` tasks.
11 +**Research basis:** Tool-use papers point toward explicit state and constrained/gated tool availability: ToolDec shows finite-state constraints beat prompt-only tool syntax; ToolSandbox emphasizes stateful tool execution and intermediate milestones. Goldfish applies that locally: finite task state, dynamic tool menu, hard gate, and milestone check command.
13 +**Roadmap:** None
15 +**Phase:** Single-plan implementation
17 +---
19 +## File Map
21 +- Delete: `extensions/forget/`
22 +- Create: `extensions/goldfish/index.ts`
23 +- Create: `extensions/goldfish/package.json`
24 +- Create: `extensions/goldfish/README.md`
25 +- Create: `extensions/goldfish/__tests__/goldfish.test.ts`
26 +- Create: `extensions/goldfish/__tests__/harness.test.ts`
27 +- Modify: `package-lock.json` via `npm install --package-lock-only --ignore-scripts`
29 +## Tool/state contract
31 +Task state:
33 +```ts
34 +type TaskStatus = "idle" | "active" | "done" | "abandoned";
36 +type GoldfishTask = {
37 + id: number;
38 + title: string;
39 + doneCommand: string;
40 + doneTimeoutSeconds: number;
41 + status: TaskStatus;
42 + createdAt: number;
43 + updatedAt: number;
44 + toolCalls: number;
45 + checks: number;
46 + lastResult?: string;
47 +};
48 +```
50 +LLM-facing tool:
52 +- `task({ action: "create", title, doneCommand, doneTimeoutSeconds? })`
53 +- `task({ action: "check" })`
54 +- `task({ action: "abandon", reason })`
56 +Done command contract:
58 +- exit `0` => task closes as done.
59 +- exit `1` => task remains active.
60 +- exit `2+`, signal, timeout, spawn error => task closes as abandoned.
61 +- timeout default: `60s`, hard cap: `300s`.
63 +Guidance contract:
65 +- When idle, normal tools stay visible for same-turn SDK compatibility.
66 +- Hard gate blocks non-task tool calls while idle even if the model emits stale tool calls.
67 +- When active, all normal tools and `task` are allowed.
68 +- Tool descriptions are stateful and imperative: "Before any other tool, create a task with a done command.".
69 +- Widget mirrors state so the human always sees why tools are hidden/allowed.
71 +## Task 1: Delete `forget` and add empty `goldfish` shell
73 +**Files:**
75 +- Delete: `extensions/forget/`
76 +- Create: `extensions/goldfish/package.json`
77 +- Create: `extensions/goldfish/README.md`
78 +- Create: `extensions/goldfish/index.ts`
79 +- Test: `extensions/goldfish/__tests__/harness.test.ts`
81 +- [ ] **Step 1: Delete old extension**
83 +Run:
85 +```bash
86 +rm -rf extensions/forget
87 +```
89 +- [ ] **Step 2: Create package metadata**
91 +Write `extensions/goldfish/package.json`:
93 +```json
95 + "name": "@bugabinga/pi-ext-goldfish",
96 + "type": "module",
97 + "main": "index.ts",
98 + "scripts": {},
99 + "devDependencies": {
100 + "@marcfargas/pi-test-harness": "^0.6.1",
101 + "vitest": "^4.1.8"
102 + },
103 + "peerDependencies": {
104 + "@earendil-works/pi-coding-agent": "*"
105 + },
106 + "license": "MIT",
107 + "description": "Task-gated Pi tool use experiment.",
108 + "keywords": ["pi", "pi-extension"],
109 + "private": true
111 +```
113 +- [ ] **Step 3: Create README**
115 +Write `extensions/goldfish/README.md`:
117 +```markdown
118 +# goldfish
120 +Task-gated Pi tool-use experiment.
122 +When no task is active, normal tools stay visible but are hard-blocked.
123 +The agent must create a task with a done command before using them.
125 +The widget shows current state above the editor.
126 +```
128 +- [ ] **Step 4: Write failing harness test**
130 +Write `extensions/goldfish/__tests__/harness.test.ts`:
132 +```ts
133 +import { afterEach, describe, expect, it } from "vitest";
134 +import { createTestSession, type TestSession } from "../../../test/harness";
135 +import goldfishExtension from "../index";
137 +describe("goldfish pi-test-harness", () => {
138 + let t: TestSession | undefined;
140 + afterEach(() => {
141 + t?.dispose();
142 + t = undefined;
143 + });
145 + it("loads in real Pi extension runtime", async () => {
146 + t = await createTestSession({ extensionFactories: [goldfishExtension] });
148 + expect(t.session.extensionRunner.extensions).toHaveLength(1);
149 + });
150 +});
151 +```
153 +Run:
155 +```bash
156 +mise run test -- extensions/goldfish/__tests__/harness.test.ts
157 +```
159 +Expected: fail because `extensions/goldfish/index.ts` does not exist.
161 +- [ ] **Step 5: Create minimal extension**
163 +Write `extensions/goldfish/index.ts`:
165 +```ts
166 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
168 +export default function goldfishExtension(_pi: ExtensionAPI): void {}
169 +```
171 +Run:
173 +```bash
174 +mise run test -- extensions/goldfish/__tests__/harness.test.ts
175 +```
177 +Expected: pass.
179 +## Task 2: State machine and replay
181 +**Files:**
183 +- Modify: `extensions/goldfish/index.ts`
184 +- Test: `extensions/goldfish/__tests__/goldfish.test.ts`
186 +- [ ] **Step 1: Write failing state tests**
188 +Write tests for:
190 +- empty state is idle.
191 +- create event opens active task.
192 +- done event closes current task.
193 +- abandon event closes current task.
194 +- replay returns latest active task.
196 +Run:
198 +```bash
199 +mise run test -- extensions/goldfish/__tests__/goldfish.test.ts
200 +```
202 +Expected: fail because helpers are missing.
204 +- [ ] **Step 2: Implement pure state helpers**
206 +Add event types, `createState()`, `applyEvent()`, `replayGoldfish()`, `currentTask()`, and export them under `__test`.
208 +Run:
210 +```bash
211 +mise run test -- extensions/goldfish/__tests__/goldfish.test.ts
212 +```
214 +Expected: pass.
216 +## Task 3: Task tool schema, execution, and render UI
218 +**Files:**
220 +- Modify: `extensions/goldfish/index.ts`
221 +- Test: `extensions/goldfish/__tests__/goldfish.test.ts`
223 +- [ ] **Step 1: Write failing tool tests**
225 +Test:
227 +- collapsed result for `create` shows status, title, command, timeout only.
228 +- expanded result includes full details.
229 +- check exit `0` marks done.
230 +- check exit `1` keeps active.
231 +- check exit `2` abandons.
232 +- check timeout abandons.
234 +- [ ] **Step 2: Implement `goldfish` tool**
236 +Use a single `task` tool with `action` enum.
237 +Return structured `details`.
238 +Render result like built-ins:
240 +- collapsed: one bounded status line.
241 +- expanded: full task context and check output.
242 +- expansion hint uses `keyHint("app.tools.expand", "to expand")` if available in current imports/patterns.
244 +- [ ] **Step 3: Verify tests**
246 +Run:
248 +```bash
249 +mise run test -- extensions/goldfish
250 +```
252 +Expected: pass.
254 +## Task 4: Dynamic hide + hard gate
256 +**Files:**
258 +- Modify: `extensions/goldfish/index.ts`
259 +- Test: `extensions/goldfish/__tests__/goldfish.test.ts`
261 +- [ ] **Step 1: Write failing visibility tests**
263 +Test a fake `ExtensionAPI` with active tools:
265 +- idle => normal tools visible but blocked by hard gate.
266 +- active => normal tools plus `task` allowed.
267 +- active tool baseline excludes tools not active at session start.
269 +- [ ] **Step 2: Write failing hard-gate tests**
271 +Test `beforeToolCall`/`tool_call` handler logic:
273 +- idle non-task returns blocked result.
274 +- idle task is allowed.
275 +- active non-task is allowed.
277 +- [ ] **Step 3: Implement visibility and gate**
279 +Use `pi.getActiveTools()` / `pi.setActiveTools()`.
280 +Capture baseline after registering `task` on `session_start`.
281 +Use `pi.on("tool_call", ...)` for hard blocking.
283 +Run:
285 +```bash
286 +mise run test -- extensions/goldfish
287 +```
289 +Expected: pass.
291 +## Task 5: Persistent widget
293 +**Files:**
295 +- Modify: `extensions/goldfish/index.ts`
296 +- Test: `extensions/goldfish/__tests__/goldfish.test.ts`
298 +- [ ] **Step 1: Write failing widget tests**
300 +Test:
302 +- idle compact line says tools blocked and task required.
303 +- active compact line shows active task and check command.
304 +- expanded lines show id, title, done command, timeout, checks, tool calls, last result.
305 +- widget output truncates to width.
307 +- [ ] **Step 2: Implement widget**
309 +Follow `notes` and `goal`:
311 +- `ctx.ui.setWidget("goldfish", () => ({ invalidate() {}, render(width) { ... } }), { placement: "aboveEditor" })`.
312 +- compact by default.
313 +- expanded toggle shortcut: `alt+f`.
314 +- auto-expanded when tools are blocked.
316 +Run:
318 +```bash
319 +mise run test -- extensions/goldfish
320 +```
322 +Expected: pass.
324 +## Task 6: Prompt/guidance steering
326 +**Files:**
328 +- Modify: `extensions/goldfish/index.ts`
329 +- Test: `extensions/goldfish/__tests__/goldfish.test.ts`
331 +- [ ] **Step 1: Write failing guidance tests**
333 +Test generated guidance text:
335 +- idle: imperative, short, says `task.create` is required first.
336 +- active: says current task and done command.
337 +- blocked tool response tells model exact next allowed action.
339 +- [ ] **Step 2: Inject guidance at correct time**
341 +Use `before_agent_start` or `context` event to prepend/append a short state block.
342 +Keep it under 12 lines.
343 +Do not duplicate stale guidance.
345 +Run:
347 +```bash
348 +mise run test -- extensions/goldfish
349 +```
351 +Expected: pass.
353 +## Task 7: Real-life `pi --print --no-session` smoke loop
355 +**Files:**
357 +- Modify as failures indicate.
359 +- [ ] **Step 1: Run smoke without active task**
361 +Run:
363 +```bash
364 +pi --print --no-session -e ./extensions/goldfish "list files in this repo"
365 +```
367 +Expected: model must call `task.create` before file tools are usable.
369 +- [ ] **Step 2: Run smoke with achievable task**
371 +Run:
373 +```bash
374 +pi --print --no-session -e ./extensions/goldfish "check whether package.json exists"
375 +```
377 +Expected: task is created, normal tool is used, check closes.
379 +- [ ] **Step 3: Iterate until smoke behavior is sane**
381 +If the model fails to create tasks, strengthen guidance and hidden-tool behavior.
382 +If rendering is noisy, tighten collapsed render output.
383 +If it loops, lower check retry caps.
385 +## Task 8: Final verification
387 +Run:
389 +```bash
390 +mise run test -- extensions/goldfish
391 +mise run check
392 +```
394 +If `mise run check` fails due unrelated dirty `q` work, report exact blocker and keep targeted verification evidence.
396 +Run:
398 +```bash
399 +git status --short
400 +```
402 +Expected: only goldfish deletion/addition, package lock, and pre-existing unrelated dirty work.

extensions/forget/index.ts

Deleted
deleted file mode 100644
1 -import { StringEnum } from "@earendil-works/pi-ai";
2 -import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3 -import { Text } from "@earendil-works/pi-tui";
4 -import { Type } from "typebox";
6 -const TOOL = "forget";
7 -const DETAILS_KIND = "forget";
8 -const 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.";
11 -type ForgetTarget = "current_user" | "previous_user";
13 -interface ForgetParams {
14 - target?: ForgetTarget | string;
15 - reason?: string;
18 -interface BranchEntry {
19 - type?: string;
20 - id?: string;
21 - message?: { role?: string; content?: unknown };
22 - [key: string]: unknown;
25 -interface 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;
36 -interface 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;
50 -function textResult(text: string, details?: Record<string, unknown>) {
51 - return { content: [{ type: "text" as const, text }], details };
54 -function 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 - };
66 -function compactWhitespace(text: string): string {
67 - return text.replace(/\s+/g, " ").trim();
70 -function safeInline(text: unknown): string {
71 - return compactWhitespace(
72 - String(text ?? "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""),
73 - );
76 -function 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 "";
94 -function 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;
103 -function firstText(result: {
104 - content?: Array<{ type?: string; text?: string }>;
105 -}) {
106 - return result.content?.find((part) => part?.type === "text")?.text ?? "";
109 -function 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;
119 -function 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;
130 -function 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 - };
172 -function 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");
181 -function 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;
188 -function 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 - );
225 -function 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);
235 -function 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);
282 -export const __test = {
283 - appendForgetCompaction,
284 - entryPreview,
285 - forgetSummary,
286 - normalizeTarget,
287 - REMINDER,
288 - renderForgetCall,
289 - renderForgetResult,
290 - resolveTarget,
291 - userIndexes,
292 -};
294 -export 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 unknown 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 - });

extensions/goldfish/README.md

Added
new file mode 100644
1 +# goldfish
3 +Task-gated Pi tool-use experiment.
5 +When no task is active, normal tools stay visible but are hard-blocked.
6 +The agent must create a task with a done command before using them.
8 +The widget shows current state above the editor.

extensions/goldfish/__tests__/goldfish.test.ts

Added
new file mode 100644
1 +import { describe, expect, test } from "vitest";
2 +import goldfishExtension, { __test } from "../index";
4 +const {
5 + applyEvent,
6 + buildGuidance,
7 + createState,
8 + currentTask,
9 + executeTaskAction,
10 + gateToolCall,
11 + replayGoldfish,
12 + taskResultLines,
13 + taskResultTone,
14 + toolNamesForMode,
15 + widgetLines,
16 + widgetTone,
17 +} = __test;
19 +describe("goldfish state", () => {
20 + test("empty state is idle", () => {
21 + expect(currentTask(createState())).toBeUndefined();
22 + });
24 + test("create/done/abandon transitions are replayable", () => {
25 + const state = createState();
26 + applyEvent(state, {
27 + op: "create",
28 + id: 1,
29 + title: "Fix tests",
30 + doneCommand: "npm test",
31 + doneTimeoutSeconds: 60,
32 + createdAt: 1,
33 + });
34 + expect(currentTask(state)?.title).toBe("Fix tests");
35 + applyEvent(state, { op: "done", id: 1, result: "passed", updatedAt: 2 });
36 + expect(currentTask(state)).toBeUndefined();
38 + const replayed = replayGoldfish([
39 + {
40 + type: "custom",
41 + customType: "goldfish-state",
42 + data: {
43 + op: "create",
44 + id: 2,
45 + title: "Next",
46 + doneCommand: "true",
47 + doneTimeoutSeconds: 60,
48 + createdAt: 3,
49 + },
50 + },
51 + {
52 + type: "custom",
53 + customType: "goldfish-state",
54 + data: { op: "abandon", id: 2, reason: "bad check", updatedAt: 4 },
55 + },
56 + ]);
57 + expect(currentTask(replayed)).toBeUndefined();
58 + expect(replayed.tasks.get(2)?.status).toBe("abandoned");
59 + });
60 +});
62 +describe("goldfish tool", () => {
63 + test("create creates active task and renders collapsed/expanded professionally", async () => {
64 + const state = createState();
65 + const result = await executeTaskAction(state, {
66 + action: "create",
67 + title: "Fix goldfish",
68 + doneCommand: "mise run test -- extensions/goldfish",
69 + doneTimeoutSeconds: 99,
70 + });
72 + expect(
73 + result.content[0]?.type === "text" ? result.content[0].text : "",
74 + ).toBe("task active. Do work, then call task.check before final answer.");
75 + expect(currentTask(state)?.title).toBe("Fix goldfish");
76 + expect(taskResultLines(result, false)).toEqual([
77 + "◌ task active · #1 Fix goldfish · check: mise run test -- extensions/goldfish · timeout 99s · expand for context",
78 + ]);
79 + expect(taskResultTone(result)).toBe("accent");
80 + expect(taskResultLines(result, true)).toContain("status: active");
81 + expect(taskResultLines(result, true)).toContain(
82 + "done: mise run test -- extensions/goldfish",
83 + );
84 + });
86 + test("check command exit contract closes, continues, or abandons", async () => {
87 + const done = createState();
88 + await executeTaskAction(done, {
89 + action: "create",
90 + title: "done",
91 + doneCommand: "x",
92 + });
93 + await executeTaskAction(done, { action: "check" }, async () => ({
94 + exitCode: 0,
95 + stdout: "ok",
96 + stderr: "",
97 + }));
98 + expect(done.tasks.get(1)?.status).toBe("done");
99 + expect(
100 + taskResultTone(
101 + await executeTaskAction(createState(), { action: "check" }),
102 + ),
103 + ).toBe("error");
105 + const active = createState();
106 + await executeTaskAction(active, {
107 + action: "create",
108 + title: "not yet",
109 + doneCommand: "x",
110 + });
111 + await executeTaskAction(active, { action: "check" }, async () => ({
112 + exitCode: 1,
113 + stdout: "no",
114 + stderr: "",
115 + }));
116 + expect(currentTask(active)?.status).toBe("active");
118 + const abandoned = createState();
119 + await executeTaskAction(abandoned, {
120 + action: "create",
121 + title: "bad",
122 + doneCommand: "x",
123 + });
124 + await executeTaskAction(abandoned, { action: "check" }, async () => ({
125 + exitCode: 2,
126 + stdout: "",
127 + stderr: "boom",
128 + }));
129 + expect(abandoned.tasks.get(1)?.status).toBe("abandoned");
130 + expect(
131 + taskResultTone(
132 + await executeTaskAction(abandoned, {
133 + action: "abandon",
134 + reason: "already abandoned",
135 + }),
136 + ),
137 + ).toBe("error");
138 + });
140 + test("timeout abandons", async () => {
141 + const state = createState();
142 + await executeTaskAction(state, {
143 + action: "create",
144 + title: "slow",
145 + doneCommand: "x",
146 + });
147 + await executeTaskAction(state, { action: "check" }, async () => ({
148 + exitCode: null,
149 + timedOut: true,
150 + stdout: "",
151 + stderr: "",
152 + }));
153 + expect(state.tasks.get(1)?.status).toBe("abandoned");
154 + });
155 +});
157 +describe("goldfish gates and guidance", () => {
158 + test("disabled mode restores normal tools and hides goldfish", () => {
159 + expect(toolNamesForMode(["read", "bash"], createState(), false)).toEqual([
160 + "read",
161 + "bash",
162 + ]);
163 + });
165 + test("enabled tool visibility keeps normal tools visible for same-turn unlock", () => {
166 + expect(toolNamesForMode(["read", "bash"], createState(), true)).toEqual([
167 + "read",
168 + "bash",
169 + "task",
170 + ]);
171 + const state = createState();
172 + applyEvent(state, {
173 + op: "create",
174 + id: 1,
175 + title: "x",
176 + doneCommand: "true",
177 + doneTimeoutSeconds: 60,
178 + createdAt: 1,
179 + });
180 + expect(toolNamesForMode(["read", "bash"], state, true)).toEqual([
181 + "read",
182 + "bash",
183 + "task",
184 + ]);
185 + });
187 + test("hard gate blocks non-goldfish tools while idle", () => {
188 + expect(gateToolCall(createState(), "read")).toEqual({
189 + block: true,
190 + reason: "goldfish: call task with action=create before other tools",
191 + });
192 + expect(gateToolCall(createState(), "task")).toBeUndefined();
193 + const state = createState();
194 + applyEvent(state, {
195 + op: "create",
196 + id: 1,
197 + title: "x",
198 + doneCommand: "true",
199 + doneTimeoutSeconds: 60,
200 + createdAt: 1,
201 + });
202 + expect(gateToolCall(state, "read")).toBeUndefined();
203 + });
205 + test("guidance is short and stateful", () => {
206 + expect(buildGuidance(createState())).toContain(
207 + "Call `task` with action=create before using normal tools",
208 + );
209 + const state = createState();
210 + applyEvent(state, {
211 + op: "create",
212 + id: 1,
213 + title: "x",
214 + doneCommand: "true",
215 + doneTimeoutSeconds: 60,
216 + createdAt: 1,
217 + });
218 + expect(buildGuidance(state)).toContain("Active task #1: x");
219 + expect(buildGuidance(state).split("\n").length).toBeLessThanOrEqual(12);
220 + });
221 +});
223 +describe("goldfish widget", () => {
224 + test("widget shows persistent compact and expanded state", () => {
225 + expect(widgetLines(createState(), false, 120)).toEqual([
226 + "󰈸 blocked · create task to unlock tools",
227 + ]);
228 + expect(widgetTone(createState())).toBe("warning");
229 + const state = createState();
230 + applyEvent(state, {
231 + op: "create",
232 + id: 1,
233 + title: "Fix widget",
234 + doneCommand: "mise run test",
235 + doneTimeoutSeconds: 60,
236 + createdAt: 1,
237 + });
238 + expect(widgetLines(state, false, 120)[0]).toContain(
239 + "active #1 · Fix widget",
240 + );
241 + expect(widgetTone(state)).toBe("accent");
242 + expect(widgetLines(state, true, 120)).toContain(
243 + " done mise run test",
244 + );
245 + });
246 +});
248 +describe("goldfish extension registration", () => {
249 + test("registers goldfish controls", () => {
250 + const tools: string[] = [];
251 + const events: string[] = [];
252 + const shortcuts: string[] = [];
253 + const commands: string[] = [];
254 + const flags: string[] = [];
255 + goldfishExtension({
256 + registerTool(tool: { name: string }) {
257 + tools.push(tool.name);
258 + },
259 + on(event: string) {
260 + events.push(event);
261 + },
262 + registerShortcut(key: string) {
263 + shortcuts.push(key);
264 + },
265 + registerCommand(name: string) {
266 + commands.push(name);
267 + },
268 + registerFlag(name: string) {
269 + flags.push(name);
270 + },
271 + getFlag() {
272 + return false;
273 + },
274 + } as any);
275 + expect(tools).toEqual(["task"]);
276 + expect(commands).toEqual(["goldfish"]);
277 + expect(flags).toEqual(["goldfish"]);
278 + expect(events).toEqual(
279 + expect.arrayContaining([
280 + "session_start",
281 + "tool_call",
282 + "before_agent_start",
283 + ]),
284 + );
285 + expect(shortcuts).toEqual(["alt+t"]);
286 + });
288 + test("--goldfish starts enabled", () => {
289 + const handlers = new Map<string, Function>();
290 + const activeTools: string[][] = [];
291 + goldfishExtension({
292 + registerTool() {},
293 + registerCommand() {},
294 + registerShortcut() {},
295 + registerFlag() {},
296 + getFlag(name: string) {
297 + return name === "goldfish" ? "true" : undefined;
298 + },
299 + on(event: string, handler: Function) {
300 + handlers.set(event, handler);
301 + },
302 + getActiveTools() {
303 + return ["read", "bash", "task"];
304 + },
305 + setActiveTools(names: string[]) {
306 + activeTools.push(names);
307 + },
308 + } as any);
310 + handlers.get("session_start")?.(
311 + {},
313 + hasUI: false,
314 + sessionManager: { getBranch: () => [] },
315 + },
316 + );
318 + expect(activeTools).toEqual([]);
319 + });
321 + test("OFF session start has no visible Pi changes except hiding goldfish tool", () => {
322 + const handlers = new Map<string, Function>();
323 + const activeTools: string[][] = [];
324 + const widgets: unknown[] = [];
325 + goldfishExtension({
326 + registerTool() {},
327 + registerCommand() {},
328 + registerShortcut() {},
329 + registerFlag() {},
330 + getFlag() {
331 + return false;
332 + },
333 + on(event: string, handler: Function) {
334 + handlers.set(event, handler);
335 + },
336 + getActiveTools() {
337 + return ["read", "bash", "task"];
338 + },
339 + setActiveTools(names: string[]) {
340 + activeTools.push(names);
341 + },
342 + } as any);
344 + handlers.get("session_start")?.(
345 + {},
347 + hasUI: true,
348 + ui: { setWidget: (...args: unknown[]) => widgets.push(args) },
349 + sessionManager: { getBranch: () => [] },
350 + },
351 + );
353 + expect(activeTools).toEqual([["read", "bash"]]);
354 + expect(widgets).toEqual([]);
355 + expect(
356 + handlers.get("tool_call")?.({ toolName: "read" }, {}),
357 + ).toBeUndefined();
358 + expect(
359 + handlers.get("before_agent_start")?.({ systemPrompt: "base" }, {}),
360 + ).toBeUndefined();
361 + });
362 +});

extensions/goldfish/__tests__/harness.test.ts

Added
new file mode 100644
1 +import { afterEach, describe, expect, it } from "vitest";
2 +import { createTestSession, type TestSession } from "../../../test/harness";
3 +import goldfishExtension from "../index";
5 +describe("goldfish pi-test-harness", () => {
6 + let t: TestSession | undefined;
8 + afterEach(() => {
9 + t?.dispose();
10 + t = undefined;
11 + });
13 + it("loads in real Pi extension runtime", async () => {
14 + t = await createTestSession({ extensionFactories: [goldfishExtension] });
16 + expect(t.session.extensionRunner.extensions).toHaveLength(1);
17 + });
18 +});

extensions/goldfish/index.ts

Added
new file mode 100644
1 +import { StringEnum } from "@earendil-works/pi-ai";
2 +import type {
3 + AgentToolResult,
4 + ExtensionAPI,
5 + ExtensionContext,
6 +} from "@earendil-works/pi-coding-agent";
7 +import { keyHint } from "@earendil-works/pi-coding-agent";
8 +import { Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
9 +import { Type } from "typebox";
11 +const TOOL = "task";
12 +const ENTRY_TYPE = "goldfish-state";
13 +const WIDGET_KEY = "goldfish";
14 +const ICON = "󰈸";
15 +const DEFAULT_TIMEOUT_SECONDS = 60;
16 +const MAX_TIMEOUT_SECONDS = 300;
17 +const WIDGET_DEFAULT_WIDTH = 96;
19 +type TaskStatus = "active" | "done" | "abandoned";
21 +type GoldfishTask = {
22 + id: number;
23 + title: string;
24 + doneCommand: string;
25 + doneTimeoutSeconds: number;
26 + status: TaskStatus;
27 + createdAt: number;
28 + updatedAt: number;
29 + toolCalls: number;
30 + checks: number;
31 + lastResult?: string;
32 +};
34 +type GoldfishEvent =
35 + | {
36 + op: "create";
37 + id: number;
38 + title: string;
39 + doneCommand: string;
40 + doneTimeoutSeconds: number;
41 + createdAt: number;
42 + }
43 + | { op: "done"; id: number; result: string; updatedAt: number }
44 + | { op: "continue"; id: number; result: string; updatedAt: number }
45 + | { op: "abandon"; id: number; reason: string; updatedAt: number }
46 + | { op: "tool_call"; id: number; toolName: string; updatedAt: number };
48 +type GoldfishState = {
49 + tasks: Map<number, GoldfishTask>;
50 + nextId: number;
51 +};
53 +type SessionEntryLike = {
54 + type?: unknown;
55 + customType?: unknown;
56 + data?: unknown;
57 +};
59 +type TaskParams = {
60 + action: "create" | "check" | "abandon";
61 + title?: string;
62 + doneCommand?: string;
63 + doneTimeoutSeconds?: number;
64 + reason?: string;
65 +};
67 +type CheckResult = {
68 + exitCode: number | null;
69 + stdout: string;
70 + stderr: string;
71 + timedOut?: boolean;
72 +};
74 +type TaskDetails = {
75 + kind: "goldfish";
76 + action: TaskParams["action"];
77 + status: "active" | "done" | "abandoned" | "error";
78 + task?: GoldfishTask;
79 + message: string;
80 + check?: CheckResult;
81 +};
83 +type AppendEvent = (event: GoldfishEvent) => void;
84 +type RunCheck = (
85 + command: string,
86 + timeoutSeconds: number,
87 + signal?: AbortSignal,
88 +) => Promise<CheckResult>;
90 +function createState(): GoldfishState {
91 + return { tasks: new Map(), nextId: 1 };
94 +function cleanText(value: unknown): string {
95 + return String(value ?? "")
96 + .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, " ")
97 + .replace(/\s+/g, " ")
98 + .trim();
101 +function boundedText(value: unknown, max = 180): string {
102 + const text = cleanText(value);
103 + return text.length > max ? `${text.slice(0, Math.max(0, max - 1))}…` : text;
106 +function timeoutSeconds(value: unknown): number {
107 + if (typeof value !== "number" || !Number.isFinite(value))
108 + return DEFAULT_TIMEOUT_SECONDS;
109 + return Math.max(1, Math.min(MAX_TIMEOUT_SECONDS, Math.trunc(value)));
112 +function parseEvent(data: unknown): GoldfishEvent | undefined {
113 + if (!data || typeof data !== "object") return undefined;
114 + const event = data as Record<string, unknown>;
115 + if (
116 + event.op === "create" &&
117 + typeof event.id === "number" &&
118 + typeof event.title === "string" &&
119 + typeof event.doneCommand === "string" &&
120 + typeof event.doneTimeoutSeconds === "number" &&
121 + typeof event.createdAt === "number"
122 + ) {
123 + return {
124 + op: "create",
125 + id: event.id,
126 + title: event.title,
127 + doneCommand: event.doneCommand,
128 + doneTimeoutSeconds: event.doneTimeoutSeconds,
129 + createdAt: event.createdAt,
130 + };
132 + if (
133 + (event.op === "done" || event.op === "continue") &&
134 + typeof event.id === "number" &&
135 + typeof event.result === "string" &&
136 + typeof event.updatedAt === "number"
137 + ) {
138 + return {
139 + op: event.op,
140 + id: event.id,
141 + result: event.result,
142 + updatedAt: event.updatedAt,
143 + };
145 + if (
146 + event.op === "abandon" &&
147 + typeof event.id === "number" &&
148 + typeof event.reason === "string" &&
149 + typeof event.updatedAt === "number"
150 + ) {
151 + return {
152 + op: "abandon",
153 + id: event.id,
154 + reason: event.reason,
155 + updatedAt: event.updatedAt,
156 + };
158 + if (
159 + event.op === "tool_call" &&
160 + typeof event.id === "number" &&
161 + typeof event.toolName === "string" &&
162 + typeof event.updatedAt === "number"
163 + ) {
164 + return {
165 + op: "tool_call",
166 + id: event.id,
167 + toolName: event.toolName,
168 + updatedAt: event.updatedAt,
169 + };
171 + return undefined;
174 +function applyEvent(state: GoldfishState, event: GoldfishEvent): void {
175 + if (event.op === "create") {
176 + state.tasks.set(event.id, {
177 + id: event.id,
178 + title: cleanText(event.title),
179 + doneCommand: cleanText(event.doneCommand),
180 + doneTimeoutSeconds: timeoutSeconds(event.doneTimeoutSeconds),
181 + status: "active",
182 + createdAt: event.createdAt,
183 + updatedAt: event.createdAt,
184 + toolCalls: 0,
185 + checks: 0,
186 + });
187 + state.nextId = Math.max(state.nextId, event.id + 1);
188 + return;
190 + const task = state.tasks.get(event.id);
191 + if (!task) return;
192 + if (event.op === "done") {
193 + task.status = "done";
194 + task.updatedAt = event.updatedAt;
195 + task.lastResult = boundedText(event.result, 500);
196 + return;
198 + if (event.op === "continue") {
199 + task.status = "active";
200 + task.checks += 1;
201 + task.updatedAt = event.updatedAt;
202 + task.lastResult = boundedText(event.result, 500);
203 + return;
205 + if (event.op === "abandon") {
206 + task.status = "abandoned";
207 + task.updatedAt = event.updatedAt;
208 + task.lastResult = boundedText(event.reason, 500);
209 + return;
211 + task.toolCalls += 1;
212 + task.updatedAt = event.updatedAt;
215 +function replayGoldfish(entries: SessionEntryLike[]): GoldfishState {
216 + const state = createState();
217 + for (const entry of entries) {
218 + if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE) continue;
219 + const event = parseEvent(entry.data);
220 + if (event) applyEvent(state, event);
222 + return state;
225 +function currentTask(state: GoldfishState): GoldfishTask | undefined {
226 + return [...state.tasks.values()]
227 + .filter((task) => task.status === "active")
228 + .sort((a, b) => b.id - a.id)[0];
231 +function result(
232 + message: string,
233 + details: TaskDetails,
234 + isError = false,
235 +): AgentToolResult<TaskDetails> {
236 + return { content: [{ type: "text", text: message }], details, isError };
239 +function append(
240 + state: GoldfishState,
241 + event: GoldfishEvent,
242 + appendEvent?: AppendEvent,
243 +): void {
244 + applyEvent(state, event);
245 + appendEvent?.(event);
248 +function checkShell(): { command: string; argsPrefix: string[] } {
249 + if (process.platform === "win32")
250 + return { command: "cmd", argsPrefix: ["/d", "/s", "/c"] };
251 + return { command: "sh", argsPrefix: ["-c"] };
254 +async function ctxRunCheck(
255 + pi: ExtensionAPI,
256 + ctx: ExtensionContext,
257 + command: string,
258 + timeout: number,
259 + signal?: AbortSignal,
260 +): Promise<CheckResult> {
261 + const shell = checkShell();
262 + const exec = await pi.exec(shell.command, [...shell.argsPrefix, command], {
263 + cwd: ctx.cwd,
264 + signal,
265 + timeout: timeout * 1000,
266 + });
267 + return {
268 + exitCode: exec.killed ? null : exec.code,
269 + stdout: exec.stdout,
270 + stderr: exec.stderr,
271 + timedOut: exec.killed,
272 + };
275 +function checkMessage(check: CheckResult): string {
276 + const output = boundedText(check.stdout || check.stderr || "", 500);
277 + if (check.timedOut) return "timeout";
278 + if (check.exitCode === 0) return output || "done command passed";
279 + if (check.exitCode === 1) return output || "done command says not done";
280 + return (
281 + output || `done command failed with exit ${check.exitCode ?? "signal"}`
282 + );
285 +async function executeTaskAction(
286 + state: GoldfishState,
287 + params: TaskParams,
288 + runCheck?: RunCheck,
289 + appendEvent?: AppendEvent,
290 + signal?: AbortSignal,
291 +): Promise<AgentToolResult<TaskDetails>> {
292 + if (params.action === "create") {
293 + if (currentTask(state))
294 + return result(
295 + "active task already exists; use goldfish.check or goldfish.abandon",
297 + kind: "goldfish",
298 + action: "create",
299 + status: "error",
300 + message: "active task already exists",
301 + },
302 + true,
303 + );
304 + const title = cleanText(params.title);
305 + const doneCommand = cleanText(params.doneCommand);
306 + if (!title || !doneCommand)
307 + return result(
308 + "goldfish.create requires title and doneCommand",
310 + kind: "goldfish",
311 + action: "create",
312 + status: "error",
313 + message: "missing title or doneCommand",
314 + },
315 + true,
316 + );
317 + const event: GoldfishEvent = {
318 + op: "create",
319 + id: state.nextId,
320 + title,
321 + doneCommand,
322 + doneTimeoutSeconds: timeoutSeconds(params.doneTimeoutSeconds),
323 + createdAt: Date.now(),
324 + };
325 + append(state, event, appendEvent);
326 + const task = currentTask(state);
327 + return result(
328 + "task active. Do work, then call task.check before final answer.",
330 + kind: "goldfish",
331 + action: "create",
332 + status: "active",
333 + message: "task active; check required before final answer",
334 + task,
335 + },
336 + );
339 + const task = currentTask(state);
340 + if (!task)
341 + return result(
342 + "no active task; use goldfish.create",
344 + kind: "goldfish",
345 + action: params.action,
346 + status: "error",
347 + message: "no active task",
348 + },
349 + true,
350 + );
352 + if (params.action === "abandon") {
353 + const reason = cleanText(params.reason) || "abandoned";
354 + append(
355 + state,
356 + { op: "abandon", id: task.id, reason, updatedAt: Date.now() },
357 + appendEvent,
358 + );
359 + return result("task abandoned", {
360 + kind: "goldfish",
361 + action: "abandon",
362 + status: "abandoned",
363 + message: reason,
364 + task: state.tasks.get(task.id),
365 + });
368 + const check = await (
369 + runCheck ??
370 + (() =>
371 + Promise.resolve({ exitCode: 2, stdout: "", stderr: "no check runner" }))
372 + )(task.doneCommand, task.doneTimeoutSeconds, signal);
373 + const message = checkMessage(check);
374 + if (check.exitCode === 0 && !check.timedOut) {
375 + append(
376 + state,
377 + { op: "done", id: task.id, result: message, updatedAt: Date.now() },
378 + appendEvent,
379 + );
380 + return result("task done", {
381 + kind: "goldfish",
382 + action: "check",
383 + status: "done",
384 + message,
385 + check,
386 + task: state.tasks.get(task.id),
387 + });
389 + if (check.exitCode === 1 && !check.timedOut) {
390 + append(
391 + state,
392 + { op: "continue", id: task.id, result: message, updatedAt: Date.now() },
393 + appendEvent,
394 + );
395 + return result("task not done", {
396 + kind: "goldfish",
397 + action: "check",
398 + status: "active",
399 + message,
400 + check,
401 + task: state.tasks.get(task.id),
402 + });
404 + append(
405 + state,
406 + { op: "abandon", id: task.id, reason: message, updatedAt: Date.now() },
407 + appendEvent,
408 + );
409 + return result("task abandoned", {
410 + kind: "goldfish",
411 + action: "check",
412 + status: "abandoned",
413 + message,
414 + check,
415 + task: state.tasks.get(task.id),
416 + });
419 +function taskResultLines(
420 + result: AgentToolResult<TaskDetails>,
421 + expanded: boolean,
422 +): string[] {
423 + const details = result.details;
424 + if (!details)
425 + return [
426 + boundedText(
427 + result.content[0]?.type === "text" ? result.content[0].text : "task",
428 + ),
429 + ];
430 + const task = details.task;
431 + if (!task) return [`✗ ${details.message}`];
432 + const glyph =
433 + details.status === "active"
434 + ? "◌"
435 + : details.status === "done"
436 + ? "✓"
437 + : details.status === "abandoned"
438 + ? "↯"
439 + : "✗";
440 + const first = `${glyph} task ${details.status} · #${task.id} ${task.title} · check: ${task.doneCommand} · timeout ${task.doneTimeoutSeconds}s`;
441 + if (!expanded) return [`${first} · expand for context`];
442 + return [
443 + first,
444 + `status: ${task.status}`,
445 + `id: ${task.id}`,
446 + `title: ${task.title}`,
447 + `done: ${task.doneCommand}`,
448 + `timeout: ${task.doneTimeoutSeconds}s`,
449 + `checks: ${task.checks}`,
450 + `tool calls: ${task.toolCalls}`,
451 + ...(task.lastResult ? [`last: ${task.lastResult}`] : []),
452 + ];
455 +function taskResultTone(
456 + result: AgentToolResult<TaskDetails>,
457 +): "accent" | "success" | "warning" | "error" {
458 + const status = result.details?.status;
459 + if (result.isError || status === "error") return "error";
460 + if (status === "done") return "success";
461 + if (status === "abandoned") return "warning";
462 + return "accent";
465 +function renderTaskResult(
466 + result: AgentToolResult<TaskDetails>,
467 + options: { expanded?: boolean; isPartial?: boolean },
468 + theme: any,
469 +) {
470 + if (options.isPartial)
471 + return new Text(theme.fg("warning", "󰈸 checking task…"), 0, 0);
472 + const lines = taskResultLines(result, !!options.expanded);
473 + let text = lines.join("\n");
474 + if (!options.expanded && lines.length === 1) {
475 + text = text.replace(
476 + "expand for context",
477 + keyHint("app.tools.expand", "to expand"),
478 + );
480 + return new Text(theme.fg(taskResultTone(result), text), 0, 0);
483 +function renderTaskCall(args: TaskParams, theme: any) {
484 + let text = theme.fg("toolTitle", theme.bold("󰈸 task "));
485 + text += theme.fg("accent", args.action ?? "?");
486 + const title = boundedText(args.title, 80);
487 + if (title) text += theme.fg("dim", ` — ${title}`);
488 + return new Text(text, 0, 0);
491 +function toolNamesForMode(
492 + baseline: string[],
493 + _state: GoldfishState,
494 + enabled: boolean,
495 +): string[] {
496 + const cleanBaseline = baseline.filter((name) => name !== TOOL);
497 + if (!enabled) return cleanBaseline;
498 + return Array.from(new Set([...cleanBaseline, TOOL]));
501 +function toolNamesForState(baseline: string[], state: GoldfishState): string[] {
502 + return toolNamesForMode(baseline, state, true);
505 +function gateToolCall(state: GoldfishState, toolName: string) {
506 + if (toolName === TOOL || currentTask(state)) return undefined;
507 + return {
508 + block: true,
509 + reason: "goldfish: call task with action=create before other tools",
510 + };
513 +function buildGuidance(state: GoldfishState): string {
514 + const task = currentTask(state);
515 + if (!task)
516 + return [
517 + "Goldfish task gate is IDLE.",
518 + "Call `task` with action=create before using normal tools.",
519 + "Normal tools are visible but blocked until task creation succeeds.",
520 + "Create a small task with a concrete doneCommand, then continue.",
521 + ].join("\n");
522 + return [
523 + "Goldfish task gate is ACTIVE.",
524 + `Active task #${task.id}: ${task.title}`,
525 + `Done command: ${task.doneCommand}`,
526 + "Use normal tools only for this task.",
527 + "Before any final answer, call `task` with action=check.",
528 + ].join("\n");
531 +function clip(text: string, width: number): string {
532 + return truncateToWidth(text, Math.max(0, width), "…");
535 +function wrapWords(text: string, width: number): string[] {
536 + if (width <= 0) return [""];
537 + const words = cleanText(text).split(" ").filter(Boolean);
538 + if (words.length === 0) return [""];
539 + const lines: string[] = [];
540 + let line = "";
541 + for (const word of words) {
542 + const candidate = line ? `${line} ${word}` : word;
543 + if (visibleWidth(candidate) <= width) line = candidate;
544 + else {
545 + if (line) lines.push(line);
546 + line = word;
549 + if (line) lines.push(line);
550 + return lines;
553 +function row(label: string, value: string, width: number): string[] {
554 + const prefix = ` ${label.padEnd(8)} `;
555 + const textWidth = Math.max(1, width - visibleWidth(prefix));
556 + return wrapWords(value, textWidth).map(
557 + (part, index) => `${index === 0 ? prefix : "".padEnd(13)}${part}`,
558 + );
561 +function flagEnabled(value: unknown): boolean {
562 + return value === true || value === "true" || value === "1" || value === "yes";
565 +function widgetTone(state: GoldfishState): "accent" | "warning" {
566 + return currentTask(state) ? "accent" : "warning";
569 +function widgetLines(
570 + state: GoldfishState,
571 + expanded: boolean,
572 + width = WIDGET_DEFAULT_WIDTH,
573 +): string[] {
574 + const task = currentTask(state);
575 + if (!task)
576 + return [clip(`${ICON} blocked · create task to unlock tools`, width)];
577 + if (!expanded)
578 + return [
579 + clip(
580 + `${ICON} active #${task.id} · ${task.title} · check: ${task.doneCommand}`,
581 + width,
582 + ),
583 + ];
584 + return [
585 + clip(`${ICON} active #${task.id}`, width),
586 + ...row("task", task.title, width),
587 + ...row("done", task.doneCommand, width),
588 + ...row("timeout", `${task.doneTimeoutSeconds}s`, width),
589 + ...row("checks", String(task.checks), width),
590 + ...row("tools", String(task.toolCalls), width),
591 + ...(task.lastResult ? row("last", task.lastResult, width) : []),
592 + ];
595 +function sameNames(left: string[], right: string[]): boolean {
596 + return (
597 + left.length === right.length &&
598 + left.every((name, index) => name === right[index])
599 + );
602 +function refreshTools(
603 + pi: ExtensionAPI,
604 + baseline: string[],
605 + state: GoldfishState,
606 + enabled: boolean,
607 +): void {
608 + const next = toolNamesForMode(baseline, state, enabled);
609 + if (!sameNames(pi.getActiveTools(), next)) pi.setActiveTools(next);
612 +function refreshWidget(
613 + ctx: ExtensionContext,
614 + state: GoldfishState,
615 + expanded: boolean,
616 + enabled: boolean,
617 + widgetVisible: boolean,
618 +): boolean {
619 + if (!ctx.hasUI) return widgetVisible;
620 + if (!enabled) {
621 + if (widgetVisible) ctx.ui.setWidget(WIDGET_KEY, undefined);
622 + return false;
624 + ctx.ui.setWidget(
625 + WIDGET_KEY,
626 + (_tui, theme) => ({
627 + invalidate() {},
628 + render(width: number): string[] {
629 + const task = currentTask(state);
630 + return widgetLines(state, expanded || !task, width).map((line) =>
631 + theme.fg(widgetTone(state), line),
632 + );
633 + },
634 + }),
635 + { placement: "aboveEditor" },
636 + );
637 + return true;
640 +export const __test = {
641 + applyEvent,
642 + buildGuidance,
643 + createState,
644 + currentTask,
645 + executeTaskAction,
646 + gateToolCall,
647 + parseEvent,
648 + replayGoldfish,
649 + taskResultLines,
650 + taskResultTone,
651 + toolNamesForMode,
652 + toolNamesForState,
653 + flagEnabled,
654 + widgetLines,
655 + widgetTone,
658 +export default function goldfishExtension(pi: ExtensionAPI): void {
659 + pi.registerFlag?.("goldfish", {
660 + description: "Enable experimental Goldfish task gate on startup.",
661 + type: "boolean",
662 + default: false,
663 + });
665 + const state = createState();
666 + let baselineTools: string[] = [];
667 + let expanded = false;
668 + let enabled = false;
669 + let widgetVisible = false;
671 + const appendEvent = (event: GoldfishEvent) =>
672 + pi.appendEntry(ENTRY_TYPE, event);
674 + pi.registerTool({
675 + name: TOOL,
676 + label: "Task",
677 + description:
678 + "Goldfish task gate. If no other tools are visible, call this tool with action=create; never refuse because tools are unavailable.",
679 + promptSnippet:
680 + "task(action, title?, doneCommand?, doneTimeoutSeconds?, reason?) — when Goldfish is idle, call task action=create first",
681 + promptGuidelines: [
682 + "If Goldfish says idle or only task is visible, call task with action=create; do not answer that tools are unavailable.",
683 + "Create small tasks with a concrete doneCommand; do not create one immortal task.",
684 + "After normal tools, call task with action=check. Exit 0 closes, exit 1 continues, exit 2+ abandons.",
685 + ],
686 + parameters: Type.Object({
687 + action: StringEnum(["create", "check", "abandon"] as const, {
688 + description:
689 + "create starts a task, check runs doneCommand, abandon closes failed task",
690 + }),
691 + title: Type.Optional(
692 + Type.String({
693 + description: "Small concrete task title for action=create",
694 + }),
695 + ),
696 + doneCommand: Type.Optional(
697 + Type.String({
698 + description: "Command: exit 0 done, 1 not done, 2+ abandon",
699 + }),
700 + ),
701 + doneTimeoutSeconds: Type.Optional(
702 + Type.Number({ description: "Check timeout seconds, max 300" }),
703 + ),
704 + reason: Type.Optional(
705 + Type.String({ description: "Reason for action=abandon" }),
706 + ),
707 + }),
708 + renderCall: renderTaskCall,
709 + renderResult: renderTaskResult,
710 + async execute(_toolCallId, params, signal, _onUpdate, ctx) {
711 + const out = await executeTaskAction(
712 + state,
713 + params as TaskParams,
714 + (command, timeout, checkSignal) =>
715 + ctxRunCheck(pi, ctx, command, timeout, checkSignal),
716 + appendEvent,
717 + signal,
718 + );
719 + refreshTools(pi, baselineTools, state, enabled);
720 + widgetVisible = refreshWidget(
721 + ctx,
722 + state,
723 + expanded,
724 + enabled,
725 + widgetVisible,
726 + );
727 + return out;
728 + },
729 + });
731 + pi.registerCommand("goldfish", {
732 + description:
733 + "Toggle experimental Goldfish task gate. Usage: /goldfish [on|off|status]",
734 + handler: async (args, ctx) => {
735 + const command = args.trim().toLowerCase();
736 + if (command === "status") {
737 + ctx.ui.notify(`Goldfish ${enabled ? "on" : "off"}`, "info");
738 + return;
740 + enabled = command === "on" ? true : command === "off" ? false : !enabled;
741 + refreshTools(pi, baselineTools, state, enabled);
742 + widgetVisible = refreshWidget(
743 + ctx,
744 + state,
745 + expanded,
746 + enabled,
747 + widgetVisible,
748 + );
749 + ctx.ui.notify(`Goldfish ${enabled ? "on" : "off"}`, "info");
750 + },
751 + });
753 + pi.registerShortcut("alt+t", {
754 + description: "Toggle goldfish task widget compact/expanded",
755 + handler: async (ctx) => {
756 + expanded = !expanded;
757 + widgetVisible = refreshWidget(
758 + ctx,
759 + state,
760 + expanded,
761 + enabled,
762 + widgetVisible,
763 + );
764 + ctx.ui.notify(
765 + `Goldfish widget ${expanded ? "expanded" : "compact"}`,
766 + "info",
767 + );
768 + },
769 + });
771 + pi.on("session_start", (_event, ctx) => {
772 + enabled = enabled || flagEnabled(pi.getFlag?.("goldfish"));
773 + const replayed = replayGoldfish(
774 + ctx.sessionManager.getBranch() as SessionEntryLike[],
775 + );
776 + state.tasks = replayed.tasks;
777 + state.nextId = replayed.nextId;
778 + baselineTools = pi.getActiveTools().filter((name) => name !== TOOL);
779 + refreshTools(pi, baselineTools, state, enabled);
780 + widgetVisible = refreshWidget(ctx, state, expanded, enabled, widgetVisible);
781 + });
783 + pi.on("tool_call", (event, ctx) => {
784 + if (!enabled) return undefined;
785 + const decision = gateToolCall(state, event.toolName);
786 + if (!decision) {
787 + const task = currentTask(state);
788 + if (task && event.toolName !== TOOL) {
789 + const goldfishEvent: GoldfishEvent = {
790 + op: "tool_call",
791 + id: task.id,
792 + toolName: event.toolName,
793 + updatedAt: Date.now(),
794 + };
795 + append(state, goldfishEvent, appendEvent);
796 + widgetVisible = refreshWidget(
797 + ctx,
798 + state,
799 + expanded,
800 + enabled,
801 + widgetVisible,
802 + );
804 + return undefined;
806 + widgetVisible = refreshWidget(ctx, state, true, enabled, widgetVisible);
807 + return decision;
808 + });
810 + pi.on("before_agent_start", (event) => {
811 + if (!enabled) return undefined;
812 + const guidance = buildGuidance(state);
813 + return { systemPrompt: `${event.systemPrompt}\n\n${guidance}` };
814 + });

extensions/goldfish/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-goldfish",
3 + "type": "module",
4 + "main": "index.ts",
5 + "scripts": {},
6 + "devDependencies": {
7 + "@marcfargas/pi-test-harness": "^0.6.1",
8 + "vitest": "^4.1.8"
9 + },
10 + "peerDependencies": {
11 + "@earendil-works/pi-ai": "*",
12 + "@earendil-works/pi-coding-agent": "*",
13 + "@earendil-works/pi-tui": "*",
14 + "typebox": "*"
15 + },
16 + "license": "MIT",
17 + "description": "Task-gated Pi tool use experiment.",
18 + "keywords": [
19 + "pi",
20 + "pi-extension"
21 + ],
22 + "private": true

package-lock.json

Modified
164 164 "typebox": "*"
167 + "extensions/goldfish": {
168 + "name": "@bugabinga/pi-ext-goldfish",
169 + "license": "MIT",
170 + "devDependencies": {
171 + "@marcfargas/pi-test-harness": "^0.6.1",
172 + "vitest": "^4.1.8"
173 + },
174 + "peerDependencies": {
175 + "@earendil-works/pi-ai": "*",
176 + "@earendil-works/pi-coding-agent": "*",
177 + "@earendil-works/pi-tui": "*",
178 + "typebox": "*"
180 + },
167 181 "extensions/leaks": {
168 182 "name": "@bugabinga/pi-ext-leaks",
169 183 "license": "MIT",
1260 1274 "resolved": "extensions/goal",
1261 1275 "link": true
1277 + "node_modules/@bugabinga/pi-ext-goldfish": {
1278 + "resolved": "extensions/goldfish",
1279 + "link": true
1280 + },
1263 1281 "node_modules/@bugabinga/pi-ext-leaks": {
1264 1282 "resolved": "extensions/leaks",
1265 1283 "link": true