repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

chore: land in-progress extension work

7cefcc031a7c79c7ae5bf9d975a7f5a45d565aca

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Batch-commit WIP carried in the working tree, as documented under CHANGELOG
Unreleased: header-only model auth across tldr/pulse/q/goal/session-rename/
devil/angel; angel Doubt rename + advisor-uncertainty banner; mode
off/picker/shutdown-restore and baseline capture; q extraction improvements;
leaks detection narrowing + provider-context hydration; plus the accompanying
test and doc updates.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Changed files (21)

CHANGELOG.md

Modified
2 2 # Changelog
4 4 ## Unreleased
6 +- Add ultra `subagentExtensions` setting (default `"all"`): workflow sub-agents
7 + load the host's extensions so a step can grant extension-provided tools (e.g.
8 + `web_search`), while the step `tools` allowlist stays the only gate on what is
9 + active and ultra's own `workflow` tool is stripped from every sub-agent
10 + allowlist (recursion defense); set `"none"` to keep sub-agents on core tools
11 +- Ship the ultra `feature` workflow (research → plan → adversarial critique →
12 + implement → security/quality review), and make `/ultra` positional args soak
13 + the trailing free text into the last declared param so `/ultra feature <task>`
14 + passes the whole description through
15 +- Fix an ultra crash where the `workflow` tool's live board threw
16 + `state.phases.length` on a `details` value that was not a reducer state,
17 + escaping tool-error handling and taking down the whole TUI render loop; the
18 + tool renderer now shape-checks `details` and falls back to an empty board
19 +- Fix model auth handling across tldr, pulse, q, goal, session-rename, devil,
20 + and angel so header-only providers are accepted when `auth.ok` is true and
21 + provider headers are forwarded
6 22 - Rename angel low-confidence `Devil` field to `Doubt` and widget badge from
7 23 `consider-devil` to `low confidence`
8 24 - Inject a `> ⚠ ADVISOR UNCERTAIN` banner at the top of formatted angel advice
15 31 switch and for fields whose baseline ref is stale, while keeping the
16 32 `<mode_kernel>` guard so the mode body and reminder are physically removed
17 33 from the system prompt after off
34 +- Restore the captured mode baseline before switching modes so modes without
35 + `tools`, `model`, or `thinking` do not inherit overrides from the previous
36 + mode
37 +- Add a centered fuzzy `Alt+M` mode picker that avoids editor mutation and masks
38 + the live editor border while selecting modes
18 39 - Restore mode baseline tools/model/thinking on `session_shutdown` so a mode
19 40 left active at session end does not leave the user's default model, thinking,
20 41 or tool filter polluted for the next session
28 49 baseline capture and restore-on-off / restore-on-shutdown mitigates the bleed
29 50 - Convert extension drivers, helper scripts, and skill scripts from Python to MJS,
30 51 remove the Python/ruff project setup, and rename the goal pexpect test task
52 +- Remove stale Python usage docs and the dead `requirements.txt` from the
53 + `uuid-generator` skill, fix its export examples to use `--export`, and remove
54 + short-flag support from the generator CLI
31 55 - Fix notes widget rendering so Pi displays it at column zero with width-aware
32 56 compact and expanded layouts
33 57 - Add the `gestalt` skill for visual-organization audits of UIs, diagrams,
82 106 leaks extension
83 107 - Narrow leaks structure detection to URL/query/header/cookie, JWT, private-key,
84 108 and custom-regex matches; drop generic assignment and XML scanning
109 +- Fix leaks assignment detection so code references such as `loadToken(email)`,
110 + template expressions, property chains, and CamelCase type-like values are not
111 + redacted into `__LEAK_*__` placeholders
85 112 - Fix leaks hydration for tool-result `content` and `details` so redacted
86 113 provider-context placeholders are restored before local display/session storage
114 +- Keep leaks provider redaction active when a stale UI context is encountered
115 + during provider request status/notification updates
87 116 - Add the super `mockup` tool for browser-based visual-option feedback with a
88 - minimal title/question/options/multi schema, fragment-only validation, blocking
89 - browser submit, selectable cards, annotations/global notes tabs, Accept/Iterate
90 - actions, and per-card pin notes
117 + minimal title/question/options/multi schema, fragment-only validation,
118 + blocking browser submit, selectable cards, annotations/global notes tabs,
119 + Accept/Iterate actions, and per-card pin notes
91 120 - Move super skills under `extensions/super/skills`, expose them through package
92 121 Pi resources, and validate all configured skill roots
122 +- Move non-extension-owned root skills, prompts, and themes out of `pi-ext` into
123 + global Pi config; keep public `pi-ext` focused on extensions and
124 + extension-owned skills
125 +- Remove project-local Claude settings and keep spinner/reduced-motion flags in
126 + global Claude settings
93 127 - Remove the external super `writing-skills` skill after review
94 128 - Update brainstorming to delegate visual feedback to `mockup` and retire the
95 129 brainstorming visual companion scripts

extensions/angel/index.ts

Modified
465 465 async function consult(
466 466 binding: Binding,
467 467 packet: ContextPacket,
468 - auth: { apiKey: string; headers?: Record<string, string> },
468 + auth: { apiKey?: string; headers?: Record<string, string> },
469 469 signal?: AbortSignal,
470 470 ): Promise<AngelResult> {
471 471 const res = await complete(
539 539 async function getAuth(ctx: ExtensionContext, model: AnyModel) {
540 540 const a = await ctx.modelRegistry.getApiKeyAndHeaders(model);
541 - return a.ok && a.apiKey ? { apiKey: a.apiKey, headers: a.headers } : null;
541 + return a.ok ? { apiKey: a.apiKey, headers: a.headers } : null;
544 544 async function runAngel(
561 561 const auth = await getAuth(ctx, binding.advisor);
562 - if (!auth) throw new Error(`No API key for ${binding.advisor.provider}`);
562 + if (!auth)
563 + throw new Error(`Auth unavailable for ${binding.advisor.provider}`);
564 565 callCount++;
565 566 const packet = await buildPacket(ctx, trigger, question, extraContext);

extensions/devil/index.ts

Modified
198 198 model: AnyModel;
199 199 defenderModel: AnyModel;
200 200 ctx: ExtensionContext;
201 - apiKey: string;
201 + apiKey?: string;
202 202 headers?: Record<string, string>;
203 203 devilThinkingLevel: ThinkingLevel;
204 204 defenderThinkingLevel: ThinkingLevel;
711 711 idea: string,
712 712 roundsData: string[],
713 713 model: AnyModel,
714 - apiKey: string,
714 + apiKey: string | undefined,
715 715 headers: Record<string, string> | undefined,
716 716 signal: AbortSignal | undefined,
717 717 thinkingLevel: ThinkingLevel,
981 981 const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
982 - if (!auth.ok || !auth.apiKey) {
983 - ctx.ui?.notify(`No API key for ${model.provider}`, "error");
982 + if (!auth.ok) {
983 + ctx.ui?.notify(
984 + auth.error ?? `Auth unavailable for ${model.provider}`,
985 + "error",
986 + );
984 987 return;
986 989 const apiKey = auth.apiKey;
987 990 const defenderAuth =
988 991 await ctx.modelRegistry.getApiKeyAndHeaders(defenderModel);
989 - if (!defenderAuth.ok || !defenderAuth.apiKey) {
992 + if (!defenderAuth.ok) {
990 993 ctx.ui?.notify(
991 - `No API key for defender ${defenderModel.provider}`,
994 + defenderAuth.error ??
995 + `Auth unavailable for defender ${defenderModel.provider}`,
992 996 "error",
994 998 return;

extensions/goal/index.ts

Modified
2088 2088 const model = resolveJudgeModel(ctx, settings);
2089 2089 if (!model) return { done: false, blocked: false, reason: "no judge model" };
2090 2090 const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
2091 - if (!auth.ok || !auth.apiKey)
2091 + if (!auth.ok)
2092 2092 return {
2093 2093 done: false,
2094 2094 blocked: false,
2095 - reason: auth.ok ? "no judge api key" : auth.error,
2095 + reason: auth.error,
2097 2097 const judgeContext = {
2098 2098 systemPrompt: JUDGE_SYSTEM_PROMPT,

extensions/leaks/__tests__/pi-direct.test.ts

Modified
183 183 ).toBe(true);
186 + it("keeps provider redaction when UI ctx is stale", async () => {
187 + const runtime = fakePi();
188 + leaks(runtime.pi as never);
189 + const secret = "ghp_" + "S".repeat(36);
190 + const ctx = {
191 + get hasUI() {
192 + throw new Error(
193 + "This extension ctx is stale after session replacement",
194 + );
195 + },
196 + };
198 + const provider = await runtime.handlers.get("before_provider_request")?.(
199 + { payload: { text: secret } },
200 + ctx,
201 + );
203 + expect(JSON.stringify(provider)).not.toContain(secret);
204 + expect(JSON.stringify(provider)).toMatch(LEAK_PLACEHOLDER_RE);
205 + });
186 207 it("restores every local Pi surface symmetrically", async () => {
187 208 const runtime = fakePi();
188 209 leaks(runtime.pi as never);

extensions/leaks/src/pi.ts

Modified
1 1 import { existsSync, readFileSync } from "node:fs";
2 2 import path from "node:path";
3 -import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3 +import type {
4 + ExtensionAPI,
5 + ExtensionContext,
6 +} from "@earendil-works/pi-coding-agent";
4 7 import { LeaksEngine } from "./engine.ts";
5 8 import { isPlainObject } from "./safety.ts";
6 9 import { loadLeaksSettings } from "./settings.ts";
20 23 pi.on("before_provider_request", async (event, ctx) => {
21 24 const result = engine.redactDeep(event.payload, "provider");
22 - if (ctx.hasUI) {
23 - ctx.ui.setStatus("leaks", `leaks on | last ${result.count}`);
24 - if (result.count > 0) {
25 - const newPlaceholders = result.redactions
26 - .flatMap((r) => r.placeholders)
27 - .filter((p) => !engine.notifiedPlaceholders.has(p));
28 - if (newPlaceholders.length > 0) {
29 - for (const p of newPlaceholders) engine.notifiedPlaceholders.add(p);
30 - const freshRedactions = result.redactions.filter((r) =>
31 - r.placeholders.some((p) => newPlaceholders.includes(p)),
32 - );
33 - ctx.ui.notify(
34 - formatNotice({
35 - count: newPlaceholders.length,
36 - redactions: freshRedactions,
37 - }),
38 - "info",
39 - );
40 - }
41 - }
42 - }
25 + updateProviderUi(ctx, engine, result);
43 26 return result.value;
93 +type RedactionResult = ReturnType<LeaksEngine["redactDeep"]>;
95 +function updateProviderUi(
96 + ctx: ExtensionContext,
97 + engine: LeaksEngine,
98 + result: RedactionResult,
99 +) {
100 + try {
101 + if (!ctx.hasUI) return;
102 + ctx.ui.setStatus("leaks", `leaks on | last ${result.count}`);
103 + if (result.count === 0) return;
104 + const newPlaceholders = result.redactions
105 + .flatMap((r) => r.placeholders)
106 + .filter((p) => !engine.notifiedPlaceholders.has(p));
107 + if (newPlaceholders.length === 0) return;
108 + for (const p of newPlaceholders) engine.notifiedPlaceholders.add(p);
109 + const freshRedactions = result.redactions.filter((r) =>
110 + r.placeholders.some((p) => newPlaceholders.includes(p)),
111 + );
112 + ctx.ui.notify(
113 + formatNotice({
114 + count: newPlaceholders.length,
115 + redactions: freshRedactions,
116 + }),
117 + "info",
118 + );
119 + } catch (error) {
120 + if (!isStaleContextError(error)) throw error;
124 +function isStaleContextError(error: unknown) {
125 + return (
126 + error instanceof Error && error.message.includes("extension ctx is stale")
127 + );
110 130 function restoreEventProperty(
111 131 engine: LeaksEngine,
112 132 event: Record<string, unknown>,

extensions/mode/PLAN.md

Modified
3 3 # Mode Extension V1 Implementation Plan
5 5 **Status:** Implemented.
7 7 The original V1 implementation (session persistence via `mode-state` entries) was revised mid-flight.
8 -See `V1.md` for the implemented design (memory-only state, themed `setHeader` UI, `accent` frontmatter).
8 +See `V1.md` for the implemented design (memory-only state, themed widget UI, `accent` frontmatter).
10 10 ## Implementation summary
12 12 What was built:
14 -- `index.ts` — pure helpers (`frontmatterSplit`, `parseModeMarkdown`, `loadModes`, `modePromptAddition`, `normalPromptAddition`, `buildHeader`) plus runtime glue (`switchMode`, `modeOff`, `applyMode`, `showStatus`).
15 -- Tests: `unit.test.ts` (pure helpers + header factory + no-ui shutdown), `harness.test.ts` (real pi runtime), `coverage.test.ts` (fake runtime + 100% branch coverage gate).
16 -- UI: `ctx.ui.setHeader(buildHeader(mode))` replaces `setStatus`. Restoring built-in header via `setHeader(undefined)` on off/shutdown.
14 +- `index.ts` — pure helpers (`frontmatterSplit`, `parseModeMarkdown`, `loadModes`, `modePromptAddition`, `normalPromptAddition`, `buildWidget`) plus runtime glue (`switchMode`, `modeOff`, `applyMode`, `showStatus`).
15 +- Tests: `unit.test.ts` (pure helpers + widget factory + picker + no-ui shutdown), `harness.test.ts` (real pi runtime), `coverage.test.ts` (fake runtime branch coverage).
16 +- UI: `ctx.ui.setWidget("mode", buildWidget(mode))` shows active mode. Clearing uses `setWidget("mode", undefined)` on off/shutdown.
17 17 - Frontmatter additions: `accent: AccentColor`.
18 -- Dropped: `mode-state` session entries, `latestModeState`, `persist`, `session_compact` handler, branch restore on `session_start`, baseline tracking, `setStatus`, `setTitle`, `setWidget`.
18 +- Dropped: `mode-state` session entries, `latestModeState`, `persist`, `session_compact` handler, branch restore on `session_start`, `setTitle`.
19 19 - Updated: `V1.md`, `V2.md` (V2's `color` frontmatter moved to V1 as `accent`), `SPEC.md`, `README.md`.
21 21 ## Verification

extensions/mode/README.md

Modified
15 15 - `/mode status` — same as `/mode`.
16 16 - `/mode list` — list available modes.
17 17 - `/mode <id>` — switch to a mode.
18 -- `/mode select` — open an interactive mode picker.
18 +- `/mode select` — open the fuzzy mode picker.
19 19 - `/mode next` — cycle to the next mode.
20 20 - `/mode off` — turn mode off (notifies `no mode active` if no mode is active).
21 21 - `/mode normal` — alias for `/mode off`.
25 25 Shortcuts:
27 -- `ctrl+shift+m` — open the interactive mode picker.
27 +- `alt+m` — open the fuzzy mode picker.
29 29 Tools: none.
64 64 | Field | Type | Effect |
65 65 | ------------- | --------------------------------------------- | ------------------------------------------------------------ |
66 66 | `description` | string | Shown by `/mode`, no runtime effect |
67 -| `accent` | theme color | Banner color when mode is active |
67 +| `accent` | theme color | Widget banner color when mode is active |
68 68 | `model` | `provider/model-id` | Switched via `pi.setModel` on enter |
69 69 | `thinking` | `off`/`minimal`/`low`/`medium`/`high`/`xhigh` | Switched via `pi.setThinkingLevel` |
70 70 | `tools` | string array | Applied via `pi.setActiveTools` (unknown names warned) |
77 77 Active mode:
79 -- Replaces the built-in header with a themed banner above the chat.
79 +- Shows a compact themed widget above the editor.
80 80 - Shows `mode:<id>` in the footer status.
81 81 - Appends its Markdown body and a generated `<mode_kernel>` to the system prompt for each agent turn.
82 82 - May switch tools, model, and thinking level on enter.
83 +- Restores the pre-mode baseline before each mode switch, so modes without `tools` use baseline tools.
84 85 `/mode off`:
86 -- Clears the custom header (built-in returns).
87 +- Clears the custom widget and footer status.
87 88 - Removes mode body from the system prompt.
88 89 - A `<mode_kernel>` with `active_mode: normal` stays injected while `neutralize = true`.
89 -- Tools, model, and thinking are **not** restored.
90 +- Tools, model, and thinking restore to the pre-mode baseline.
91 92 Mode state is **in-memory only**.
92 93 Each session starts clean — re-run `/mode <id>` after `session_start`.
94 95 ## SDK limitation
96 97 `pi.setModel` and `pi.setThinkingLevel` write to the user's global default settings.
97 -Declaring `model:` or `thinking:` in a mode mutates user defaults for the duration the mode is applied.
98 -Use `/model` and `/thinking` to revert after `/mode off`.
98 +`/mode off` restores the captured baseline, but model capability clamping may normalize unsupported thinking levels.
100 100 ## V1 limits
102 102 - Project-local `.pi/modes/*.md` deferred until Pi exposes a public project-trust API.
103 103 - Cross-session mode persistence not implemented.
104 -- Tools/model/thinking not restored on `/mode off`.
105 -- Shortcuts, extension scoping, permission policy, tool globs not in V1.
104 +- Manual model/thinking changes made while a mode is active are overwritten on `/mode off`.
105 +- Extension scoping, permission policy, tool globs not in V1.

extensions/mode/V1.md

Modified
24 24 - kernel declares "active mode is runtime state, not conversation state"
25 25 - persistence requires baseline tracking with stale-tool/stale-model/user-touched edge cases
26 -- apply-time model/thinking pollution already bleeds user defaults; restore makes it worse
26 +- apply-time model/thinking pollution needs a captured baseline to undo cleanly
27 27 - cross-session mode continuity is rare in practice
29 29 ## Validation status
36 36 - `pi.getAllTools()` + `pi.setActiveTools()` can apply filtered tool lists.
37 37 - `pi.setModel()` and `pi.setThinkingLevel()` are public APIs.
38 38 - `getAgentDir()` resolves the global Pi agent dir.
39 -- `pi-tui.Text` + `Theme.fg()` + `Theme.bold()` for themed header rendering.
40 -- `ctx.ui.setHeader(factory)` installs a custom header above chat; `undefined` restores the built-in.
39 +- `pi-tui.Text` + `Theme.fg()` + `Theme.bold()` for compact themed widget rendering.
40 +- `ctx.ui.setWidget("mode", factory)` installs a visible one-line mode widget above the editor; `undefined` clears it.
42 42 Trimmed from V1:
48 48 It is not package-exported.
49 49 V1 uses a declared `yaml` dependency for frontmatter parsing.
50 50 - Session persistence (`appendEntry`/`mode-state`).
51 - Memory-only state eliminates baseline tracking and stale-state edge cases.
52 -- Baseline restore on `/mode off`.
53 - Switching into a mode that overrides model/thinking already mutates user defaults via `pi.setModel`/`setThinkingLevel`; restoring adds complexity without removing the underlying SDK limitation.
51 + Memory-only state keeps baseline snapshots process-local and avoids stale cross-session state.
52 +- Cross-session baseline restore.
53 + Baselines are process-local and reset on `session_start`.
54 54 - Compaction checkpoint.
55 55 Process memory persists across compaction within one session.
56 56 - Branch restore on `session_start`.
64 64 - No settings mutation for mode switching.
65 65 - No `/reload` as part of mode switching.
66 66 - No extension-to-extension API.
67 -- No mode baseline restore/update system.
67 +- No cross-session baseline restore/update system.
68 68 - No tool metadata in the active block.
69 -- No shortcut/keybinding support.
69 +- No custom keybinding config.
70 70 - No file watching.
71 71 - No cross-session mode persistence.
72 -- No restore of previous tools/model/thinking on `/mode off`.
72 +- No preservation of manual model/thinking changes made while a mode is active.
74 74 ## Mode files
109 109 type Mode = {
110 110 id: string; // file stem
111 111 description?: string; // shown by /mode, no runtime behavior
112 - accent?: AccentColor; // theme color for header banner
112 + accent?: AccentColor; // theme color for widget banner
113 113 model?: string; // provider/model-id, split at first slash
114 114 thinking?: ThinkingLevel;
115 115 reminder?: string; // short active-block reminder
116 - tools?: string[]; // absent/empty = do not change active tools
116 + tools?: string[]; // absent/empty = use captured baseline tools
117 117 body: string; // Markdown body appended to system prompt while active
151 151 1. Reload mode files.
152 152 2. Resolve mode by id.
153 -3. Set in-memory `activeModeId = id`.
153 +3. Set in-memory `activeMode = mode`.
154 154 4. Set in-memory `neutralize = false`.
155 155 5. If `tools` exists and is non-empty, validate names against `pi.getAllTools()` and apply valid names via `pi.setActiveTools(validTools)`.
156 156 6. Warn for unknown tools and continue.
159 159 9. If resolved, call `await pi.setModel(model)`.
160 160 10. If `pi.setModel()` returns `false`, warn and keep current model.
161 161 11. If `thinking` exists, call `pi.setThinkingLevel(thinking)`.
162 -12. Install themed header via `ctx.ui.setHeader(buildHeader(mode))`.
162 +12. Install themed widget via `ctx.ui.setWidget("mode", buildWidget(mode))`.
164 -`tools` absent or empty means the mode does not alter active tools.
164 +`tools` absent or empty means the mode uses the captured baseline tools.
166 -Switching from mode A to mode B does not restore baseline first.
167 -B only applies fields it declares.
166 +Before the first mode switch, capture `pi.getActiveTools()`, `ctx.model`, and `pi.getThinkingLevel()` as the session-local baseline.
167 +Switching from mode A to mode B restores baseline tools/model/thinking first, then applies B's fields.
169 -**SDK limitation:** `pi.setModel` and `pi.setThinkingLevel` write to the user's global default settings.
170 -Declaring `model:` or `thinking:` in a mode mutates user defaults for the duration the mode is applied.
171 -Revert with `/model <id>` and `/thinking <level>` after `/mode off` if the user wants the original defaults back.
169 +**SDK limitation:** `pi.setModel` and `pi.setThinkingLevel` write to the user's global default settings, and thinking restore may be clamped by current model capabilities.
170 +`/mode off`, `session_start`, and `session_shutdown` restore the captured baseline when one exists.
173 172 ## Normal/off behavior
183 182 Behavior:
185 -- If `activeModeId` is `null` (no mode was active), notify `no mode active` and return.
184 +- If `activeMode` is `null` (no mode was active), notify `no mode active` and return.
186 185 - Otherwise:
187 - - Set in-memory `activeModeId = null`.
186 + - Set in-memory `activeMode = null`.
188 187 - Set in-memory `neutralize = true`.
189 - - Clear the custom header via `ctx.ui.setHeader(undefined)` so the built-in header returns.
188 + - Restore baseline tools via `pi.setActiveTools(baselineTools)`.
189 + - Restore baseline model via `pi.setModel(baselineModel)`.
190 + - Restore baseline thinking via `pi.setThinkingLevel(baselineThinking)`.
191 + - Clear the baseline snapshot.
192 + - Clear the custom widget via `ctx.ui.setWidget("mode", undefined)`.
191 -Tools/model/thinking are **not** restored.
192 -They keep whatever the last mode or manual change set them to.
194 +Manual tools/model/thinking changes made while a mode is active are overwritten by baseline restore.
194 196 Fresh normal sessions with no prior mode get no mode block.
195 197 The kernel block is only injected after `/mode off` (when `neutralize = true`).
245 247 /mode status same as /mode
246 248 /mode list show available modes
247 249 /mode <id> switch active mode
248 -/mode select open an interactive mode picker
250 +/mode select open the fuzzy mode picker
249 251 /mode next cycle to the next mode
250 252 /mode off turn mode off (notify "no mode active" if already off)
251 253 /mode normal alias for /mode off
266 -Active mode replaces the built-in header (logo/instructions) with a themed banner above the chat:
268 +Active mode shows a compact themed widget above the editor:
268 270 ```text
269 -▎ MODE: plan
270 - Read-only planning
271 - tools: read, grep, find, ls · model: openai/gpt-5.2-codex · thinking: high
271 +▎ MODE: plan Read-only planning tools: read,grep,find,ls · model: openai/gpt-5.2-codex · thinking: high
274 274 - `accent` frontmatter controls the banner color via `theme.fg(accent, ...)`.
275 275 - Default accent is `accent` (theme default).
276 -- Description line omitted when `description` is absent.
277 -- Meta line (`tools · model · thinking`) omitted when no metadata is declared.
278 -- `accent` defaults; if absent, the banner uses theme accent.
276 +- Description segment is omitted when `description` is absent.
277 +- Meta segment (`tools · model · thinking`) is omitted when no metadata is declared.
280 -`ctx.ui.setHeader(undefined)` clears the custom header and restores the built-in (logo + onboarding) on `/mode off` and `session_start`.
279 +`ctx.ui.setWidget("mode", undefined)` clears the custom widget on `/mode off`, `session_start`, and `session_shutdown`.
282 -The header and footer status are the persistent UI signals of mode state.
281 +The widget and footer status are the persistent UI signals of mode state.
283 282 The footer status shows `mode:<id>` and clears on `/mode off`, `session_start`, and `session_shutdown`.
284 -`ctrl+shift+m` opens the interactive mode picker.
283 +`alt+m` opens the fuzzy mode picker.
285 284 `notify` is reserved for warnings (unknown tool, model not found, malformed ref, parse error, unknown mode id) and empty-picker status.
287 286 ## Compaction
289 288 No checkpoint.
290 -The in-memory `state.activeModeId` survives `session_compact` automatically (same process).
289 +The in-memory `state.activeMode` survives `session_compact` automatically (same process).
291 290 `before_agent_start` keeps injecting the current mode body/kernel.
293 292 ## Session lifecycle
295 294 `session_start`:
297 -1. Reload mode files.
298 -2. Reset in-memory state: `activeModeId = null`, `neutralize = false`.
299 -3. Clear custom header.
296 +1. Restore any captured baseline tools/model/thinking.
297 +2. Reload mode files.
298 +3. Reset in-memory state: `activeMode = null`, `neutralize = false`.
299 +4. Clear baseline tools/model/thinking.
300 +5. Clear custom widget.
301 302 Users must re-run `/mode <id>` after each `session_start`.
303 -`session_shutdown`: clear custom header.
304 +`session_shutdown`: restore any captured baseline, then clear custom widget and status.
305 306 ## Extension/resource model

extensions/mode/V3.md

Modified
29 29 ## Baseline restore/update
31 -V1 does not restore previous tools/model/thinking on `/mode off`.
31 +V1 restores previous tools/model/thinking on `/mode off`.
33 33 V3 discussion:
65 65 ## Rich interactive switcher
67 -V1 has a minimal picker via `/mode select` and `ctrl+shift+m`.
67 +V1 has a fuzzy picker via `/mode select` and `alt+m`.
69 69 Future rich picker ideas:
71 -- fuzzy search
71 +- richer picker overlay
72 72 - render icon
73 73 - render name/id
74 74 - render description

extensions/mode/__tests__/coverage.test.ts

Modified
1 1 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 2 import { tmpdir } from "node:os";
3 3 import path from "node:path";
4 +import type { AutocompleteItem } from "@earendil-works/pi-tui";
4 5 import { describe, expect, it } from "vitest";
5 6 import modeExtension, { __modeTest } from "../index.ts";
9 10 function fakeRuntime() {
10 11 const commands = new Map<
11 12 string,
12 - { handler: (args: string, ctx: any) => Promise<void> }
13 + {
14 + handler: (args: string, ctx: any) => Promise<void>;
15 + getArgumentCompletions?: (
16 + prefix: string,
17 + ) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;
18 + }
14 20 const events = new Map<string, (event: any, ctx: any) => unknown>();
15 21 const notes: Array<[string, string]> = [];
16 - const headers: unknown[] = [];
22 + const widgets: unknown[] = [];
23 + const pickerInputs: string[][] = [];
24 + const pickerRenders: string[][][] = [];
17 25 const statuses: unknown[][] = [];
18 26 const shortcuts = new Map<string, { handler: (ctx: any) => Promise<void> }>();
19 27 const activeTools: string[][] = [];
28 + const defaultTools = ["read", "grep", "edit", "write"];
20 29 const selections: Array<string | undefined> = [];
21 30 let setModelResult = true;
22 31 let modelFindResult: unknown;
23 - let thinking: string | undefined;
32 + let thinking: string | undefined = "medium";
24 33 const ctx: any = {
25 34 hasUI: true,
26 35 model: { provider: "prov", id: "model" },
27 36 modelRegistry: { find: () => modelFindResult },
28 37 sessionManager: { getBranch: () => [] },
29 38 ui: {
39 + custom: async (factory: any) => {
40 + let done = false;
41 + let result: string | undefined;
42 + const component = await factory(
43 + { requestRender: () => undefined },
44 + ctx.ui.theme,
45 + {},
46 + (value: string | undefined) => {
47 + done = true;
48 + result = value;
49 + },
50 + );
51 + const renders = [component.render(80)];
52 + for (const input of pickerInputs.shift() ?? []) {
53 + component.handleInput?.(input);
54 + renders.push(component.render(80));
55 + if (done) break;
56 + }
57 + pickerRenders.push(renders);
58 + return result;
59 + },
30 60 notify: (message: string, severity: string) =>
31 61 notes.push([message, severity]),
32 62 select: async () => selections.shift(),
33 - setHeader: (...args: unknown[]) => headers.push(args),
34 63 setStatus: (...args: unknown[]) => statuses.push(args),
64 + setWidget: (...args: unknown[]) => widgets.push(args),
35 65 theme: {
66 + bg: (_color: string, text: string) => text,
67 + bold: (text: string) => text,
36 68 fg: (_color: string, text: string) => text,
40 72 modeExtension({
41 73 events: { emit: () => undefined },
42 - getAllTools: () => [{ name: "read" }, { name: "grep" }],
74 + getActiveTools: () => defaultTools,
75 + getThinkingLevel: () => thinking,
76 + getAllTools: () => [
77 + { name: "read" },
78 + { name: "grep" },
79 + { name: "edit" },
80 + { name: "write" },
81 + ],
43 82 on: (name: string, handler: (event: any, ctx: any) => unknown) =>
44 83 events.set(name, handler),
45 84 registerCommand: (
46 85 name: string,
47 - command: { handler: (args: string, ctx: any) => Promise<void> },
86 + command: {
87 + handler: (args: string, ctx: any) => Promise<void>;
88 + getArgumentCompletions?: (
89 + prefix: string,
90 + ) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;
91 + },
48 92 ) => commands.set(name, command),
49 93 registerShortcut: (
50 94 key: string,
59 103 return {
60 104 activeTools,
61 105 command: (args: string) => commands.get("mode")?.handler(args, ctx),
106 + complete: (prefix: string) =>
107 + commands.get("mode")?.getArgumentCompletions?.(prefix),
63 109 events,
64 - headers,
110 + pick: (...inputs: string[]) => pickerInputs.push(inputs),
111 + pickerRenders,
112 + widgets,
65 113 modelFindResult: () => modelFindResult,
66 114 notes,
67 115 select: (choice: string | undefined) => selections.push(choice),
104 152 return file;
107 -describe("mode 100% coverage gate", () => {
155 +describe("mode coverage", () => {
108 156 it("covers pure helpers", async () => {
109 157 expect(__modeTest.frontmatterSplit("body")).toEqual({
110 158 frontmatter: "",
197 245 __modeTest.modePromptAddition({ id: "plan", body: "body\n" }),
198 246 ).not.toContain("mode_reminder");
199 247 expect(__modeTest.normalPromptAddition()).toContain("active_mode: normal");
200 - expect(__modeTest.buildHeader(null)).toBeUndefined();
201 - const factory = __modeTest.buildHeader({
248 + expect(__modeTest.buildWidget(null)).toBeUndefined();
249 + const factory = __modeTest.buildWidget({
202 250 id: "plan",
203 251 body: "body",
204 252 description: "d",
260 308 f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
261 309 ).toBeUndefined();
262 310 await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
263 - expect(f.headers.at(-1)).toEqual([undefined]);
311 + expect(f.widgets.at(-1)).toEqual(["mode", undefined]);
264 312 await f.command("reload-config");
265 313 expect(f.notes.at(-1)).toEqual([
266 314 "mode config: 0 mode(s), 0 warning(s)",
290 338 await f.command("unknown");
291 339 expect(f.notes.at(-1)).toEqual(["unknown mode: unknown", "warning"]);
340 + expect((await f.complete("pln"))?.[0]).toEqual({
341 + value: "plan",
342 + label: "plan",
343 + description: "d",
344 + });
345 + expect(await f.complete("of")).toEqual([
346 + { value: "off", label: "off", description: "Turn mode off" },
347 + ]);
292 348 await f.command("plan");
293 349 expect(f.activeTools.at(-1)).toEqual(["read", "grep"]);
294 - expect(typeof f.headers.at(-1)?.[0]).toBe("function");
350 + await f.command("unknown");
351 + expect(f.statuses.at(-1)).toEqual(["mode", "mode:plan"]);
352 + expect(f.widgets.at(-1)?.[0]).toBe("mode");
353 + expect(typeof f.widgets.at(-1)?.[1]).toBe("function");
295 354 expect(f.statuses.at(-1)).toEqual(["mode", "mode:plan"]);
296 355 expect(
297 356 f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
298 357 ).toEqual({ systemPrompt: expect.stringContaining("active_mode: plan") });
299 358 await f.command("normal");
300 - expect(f.headers.at(-1)).toEqual([undefined]);
359 + expect(f.activeTools.at(-1)).toEqual(["read", "grep", "edit", "write"]);
360 + expect(f.widgets.at(-1)).toEqual(["mode", undefined]);
301 361 expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
302 362 expect(
303 363 f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
307 367 await f.command("plan");
308 368 await f.command("next");
369 + expect(f.activeTools.at(-1)).toEqual(["read", "grep", "edit", "write"]);
309 370 expect(f.statuses.at(-1)).toEqual(["mode", "mode:plain"]);
310 - f.select("plan — d");
371 + f.pick("d", "\r");
311 372 await f.command("select");
312 373 expect(f.statuses.at(-1)).toEqual(["mode", "mode:plan"]);
313 - expect(f.shortcuts.has("ctrl+shift+m")).toBe(true);
314 - f.select("plain");
315 - await f.shortcut("ctrl+shift+m");
374 + expect(f.shortcuts.has("alt+m")).toBe(true);
375 + f.pick("p", "l", "a", "i", "\r");
376 + await f.shortcut("alt+m");
316 377 expect(f.statuses.at(-1)).toEqual(["mode", "mode:plain"]);
378 + f.pick("o", "f", "\r");
379 + await f.command("select");
380 + expect(f.activeTools.at(-1)).toEqual(["read", "grep", "edit", "write"]);
381 + expect(f.thinking()).toBe("medium");
382 + expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
383 + await f.command("plan");
384 + rmSync(path.join(home, ".pi", "agent", "modes"), {
385 + recursive: true,
386 + force: true,
387 + });
388 + await f.command("reload-config");
389 + expect(
390 + f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
391 + ).toEqual({ systemPrompt: expect.stringContaining("active_mode: plan") });
392 + f.pick("o", "f", "\r");
393 + await f.command("select");
394 + expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
317 395 await f.command("plan");
318 396 await f.command("none");
319 - expect(f.headers.at(-1)).toEqual([undefined]);
397 + expect(f.widgets.at(-1)).toEqual(["mode", undefined]);
324 402 await withHome(async (home) => {
325 403 const f = fakeRuntime();
326 404 await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
327 - f.headers.length = 0;
405 + f.widgets.length = 0;
328 406 writeMode(home, "badref", "---\nmodel: bad\n---\nbody");
329 407 await f.command("badref");
330 408 expect(f.notes.at(-1)).toEqual([
353 431 "---\nmodel: openai/gpt\nthinking: high\n---\nbody",
355 433 await f.command("deep");
434 + expect(f.thinking()).toBe("high");
356 435 await f.events.get("session_start")?.({ reason: "reload" }, f.ctx);
357 - expect(f.headers.at(-1)).toEqual([undefined]);
436 + expect(f.thinking()).toBe("medium");
437 + expect(f.widgets.at(-1)).toEqual(["mode", undefined]);
358 438 expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
359 439 await f.events.get("session_shutdown")?.({}, f.ctx);
360 - expect(f.headers.at(-1)).toEqual([undefined]);
440 + expect(f.widgets.at(-1)).toEqual(["mode", undefined]);
361 441 expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
368 448 f.ctx.hasUI = false;
369 449 f.ctx.model = undefined;
370 450 await f.events.get("session_shutdown")?.({}, f.ctx);
371 - expect(f.headers.at(-1)).toEqual([undefined]);
451 + expect(f.widgets.at(-1)).toEqual(["mode", undefined]);

extensions/mode/__tests__/harness.test.ts

Modified
70 70 ).toBe(true);
71 71 expect(
72 72 notes.some((note) => note.includes("mode plan: tools read, grep")),
73 - ).toBe(true);
73 + ).toBe(false);
76 76 it("injects active mode prompt as system prompt", async () => {
113 113 expect(result?.systemPrompt).not.toContain("# Plan body");
116 - it("clears header on off and does not persist state", async () => {
116 + it("clears widget on off and does not persist state", async () => {
117 117 t = await createTestSession({ extensions: [extPath()] });
118 118 writeMode(t, "plan", "# Plan body\n");
119 119 await command(t, "plan");
120 - const headers = t.events.uiCallsFor("setHeader");
121 - expect(headers.at(-1)?.args[0]).toBeTypeOf("function");
120 + const widgets = t.events.uiCallsFor("setWidget");
121 + expect(widgets.at(-1)?.args[0]).toBe("mode");
122 + expect(widgets.at(-1)?.args[1]).toBeTypeOf("function");
122 123 await command(t, "off");
123 - expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
124 + expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
125 + "mode",
126 + undefined,
127 + ]);
124 128 const branches = t.session.sessionManager.getBranch() as Array<{
125 129 customType?: string;
136 140 .uiCallsFor("notify")
137 141 .map((call) => String(call.args[0]));
138 142 expect(notes).toContain("no mode active");
139 - expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
143 + expect(t.events.uiCallsFor("setWidget")).toHaveLength(1);
142 - it("session_start resets active mode and clears header", async () => {
146 + it("session_start resets active mode and clears widget", async () => {
143 147 t = await createTestSession({ extensions: [extPath()] });
144 148 writeMode(t, "plan", "# Plan body\n");
145 149 await command(t, "plan");
147 151 type: "session_start",
148 152 reason: "reload",
149 153 } as never);
150 - expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
154 + expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
155 + "mode",
156 + undefined,
157 + ]);
151 158 const result = await t.session.extensionRunner.emitBeforeAgentStart(
152 159 "hello",
153 160 undefined,
157 164 expect(result).toBeUndefined();
160 - it("session_shutdown clears header", async () => {
167 + it("session_shutdown restores baseline and clears widget", async () => {
161 168 t = await createTestSession({ extensions: [extPath()] });
162 - writeMode(t, "plan", "# Plan body\n");
163 - await command(t, "plan");
164 - t.events.uiCallsFor("setHeader").length = 0;
169 + const baselineModelId = t.session.model?.id;
170 + const baselineThinking = t.session.thinkingLevel;
171 + writeMode(
172 + t,
173 + "deep",
174 + "---\nmodel: openai/gpt-5.2-codex\nthinking: high\n---\nbody",
175 + );
176 + await command(t, "deep");
177 + expect(t.session.model?.id).toBe("gpt-5.2-codex");
178 + expect(t.session.thinkingLevel).toBe("high");
179 + t.events.uiCallsFor("setWidget").length = 0;
165 180 await t.session.extensionRunner.emit({
166 181 type: "session_shutdown",
167 182 reason: "quit",
168 183 } as never);
169 - expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
184 + expect(t.session.model?.id).toBe(baselineModelId);
185 + expect(t.session.thinkingLevel).toBe(baselineThinking);
186 + expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
187 + "mode",
188 + undefined,
189 + ]);
172 192 it("warns for unresolved model and still applies thinking", async () => {
177 197 writeMode(t, "deep", "---\nmodel: nope/missing\nthinking: high\n---\nbody");
178 198 await command(t, "deep");
199 + let latestThinking = [...t.session.sessionManager.getBranch()]
200 + .reverse()
201 + .find(
202 + (entry: { type?: string }) => entry.type === "thinking_level_change",
203 + ) as { thinkingLevel?: string } | undefined;
204 + expect(latestThinking?.thinkingLevel).toBe("high");
179 205 writeMode(t, "badref", "---\nmodel: malformed\n---\nbody");
180 206 await command(t, "badref");
181 207 const notes = t.events
187 213 expect(
188 214 notes.some((note) => note.includes("model not found: malformed")),
189 215 ).toBe(true);
190 - const latestThinking = [...t.session.sessionManager.getBranch()]
216 + latestThinking = [...t.session.sessionManager.getBranch()]
191 217 .reverse()
192 218 .find(
193 219 (entry: { type?: string }) => entry.type === "thinking_level_change",
194 220 ) as { thinkingLevel?: string } | undefined;
195 - expect(latestThinking?.thinkingLevel).toBe("high");
221 + expect(latestThinking?.thinkingLevel).toBe("medium");
198 224 it("sets resolved model and thinking", async () => {
199 225 t = await createTestSession({ extensions: [extPath()] });
226 + const baselineModelId = t.session.model?.id;
227 + const baselineThinking = t.session.thinkingLevel;
200 228 writeMode(
202 230 "deep",
205 233 await command(t, "deep");
206 234 expect(t.session.model?.id).toBe("gpt-5.2-codex");
207 235 expect(t.session.thinkingLevel).toBe("high");
236 + await command(t, "off");
237 + expect(t.session.model?.id).toBe(baselineModelId);
238 + expect(t.session.thinkingLevel).toBe(baselineThinking);
210 241 it("warns when resolved model cannot be applied", async () => {

extensions/mode/__tests__/unit.test.ts

Modified
1 1 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 2 import { tmpdir } from "node:os";
3 3 import path from "node:path";
4 -import type { Component, Theme, TUI } from "@earendil-works/pi-tui";
4 +import type { Theme } from "@earendil-works/pi-coding-agent";
5 +import type { Component, TUI } from "@earendil-works/pi-tui";
5 6 import { describe, expect, it } from "vitest";
6 7 import modeExtension, { __modeTest } from "../index.ts";
32 -type HeaderFactory = (
33 +type WidgetFactory = (
33 34 tui: TUI,
34 35 theme: Theme,
35 36 ) => Component & {
36 37 dispose?(): void;
39 -function expectFactory(value: HeaderFactory | undefined): HeaderFactory {
40 +function expectFactory(value: WidgetFactory | undefined): WidgetFactory {
40 41 expect(value).toBeDefined();
41 - if (!value) throw new Error("expected header factory");
42 + if (!value) throw new Error("expected widget factory");
42 43 return value;
156 157 expect(
157 158 __modeTest.modePromptAddition({ id: "plain", body: "# Body\n" }),
158 159 ).not.toContain("<mode_reminder>");
160 + const withRuntimeFields = __modeTest.modePromptAddition({
161 + id: "plan",
162 + body: "body",
163 + tools: ["read"],
164 + model: "openai/gpt",
165 + thinking: "high",
166 + });
167 + expect(withRuntimeFields).not.toContain("tools:");
168 + expect(withRuntimeFields).not.toContain("model: openai/gpt");
169 + expect(withRuntimeFields).not.toContain("thinking: high");
161 172 it("renders normal neutralizer", () => {
234 -describe("mode header factory", () => {
235 - it("returns undefined for null to restore built-in", () => {
236 - expect(__modeTest.buildHeader(null)).toBeUndefined();
245 +describe("mode widget factory", () => {
246 + it("returns undefined for null to clear widget", () => {
247 + expect(__modeTest.buildWidget(null)).toBeUndefined();
239 250 it("returns a component factory for a mode", () => {
240 - const factory = __modeTest.buildHeader({
251 + const factory = __modeTest.buildWidget({
241 252 id: "plan",
242 253 body: "body",
243 254 accent: "warning",
248 259 it("applies theme color and bold to banner", () => {
249 260 const factory = expectFactory(
250 - __modeTest.buildHeader({
261 + __modeTest.buildWidget({
251 262 id: "plan",
252 263 body: "body",
253 264 accent: "warning",
269 280 it("defaults accent to accent color", () => {
270 281 const factory = expectFactory(
271 - __modeTest.buildHeader({ id: "plan", body: "body" }),
282 + __modeTest.buildWidget({ id: "plan", body: "body" }),
273 284 const calls: string[] = [];
274 285 const theme = mockTheme({
285 296 it("includes description and meta when present", () => {
286 297 const factory = expectFactory(
287 - __modeTest.buildHeader({
298 + __modeTest.buildWidget({
288 299 id: "plan",
289 300 body: "body",
290 301 description: "Read-only planning",
296 307 const theme = mockTheme();
297 308 const lines = factory({} as never, theme as never).render(120);
298 309 const flat = lines.join("\n");
310 + expect(lines).toHaveLength(1);
299 311 expect(flat).toContain("MODE: plan");
300 312 expect(flat).toContain("Read-only planning");
301 - expect(flat).toContain("tools: read, grep");
313 + expect(flat).toContain("tools: read,grep");
302 314 expect(flat).toContain("model: openai/gpt-5.2-codex");
303 315 expect(flat).toContain("thinking: high");
316 + expect(factory({} as never, theme as never).render(40)).toHaveLength(1);
306 319 it("omits description and meta when absent", () => {
307 320 const factory = expectFactory(
308 - __modeTest.buildHeader({ id: "plan", body: "body" }),
321 + __modeTest.buildWidget({ id: "plan", body: "body" }),
310 323 const theme = mockTheme();
311 324 const flat = factory({} as never, theme as never)
334 +describe("mode picker", () => {
335 + it("fuzzy filters typed input and selects", () => {
336 + const selected: Array<string | undefined> = [];
337 + const picker = __modeTest.createModePicker(
339 + { value: "off", label: "off", description: "Turn mode off" },
340 + { value: "plan", label: "plan", description: "Read-only" },
341 + { value: "plain", label: "plain", description: "Build" },
342 + ],
343 + mockTheme() as never,
344 + (value) => selected.push(value),
345 + () => undefined,
346 + );
347 + expect(picker.render(80).join("\n")).toContain("Turn mode off");
348 + picker.handleInput?.("p");
349 + picker.handleInput?.("l");
350 + picker.handleInput?.("a");
351 + picker.handleInput?.("i");
352 + picker.handleInput?.("\r");
353 + expect(selected).toEqual(["plain"]);
354 + });
355 +});
321 357 describe("mode runtime event handlers", () => {
322 358 it("session_shutdown with no UI does not throw", () => {
323 359 const events = new Map<string, (...args: unknown[]) => unknown>();
324 360 modeExtension({
325 361 events: { emit: () => undefined },
326 362 getAllTools: () => [],
363 + getThinkingLevel: () => "medium",
327 364 on: (name: string, handler: (...args: unknown[]) => unknown) =>
328 365 events.set(name, handler),
329 366 registerCommand: () => undefined,
337 374 ).not.toThrow();
340 - it("session_start resets in-memory state and publishes no header", async () => {
377 + it("session_start resets in-memory state and clears widget", async () => {
341 378 const events = new Map<string, (...args: unknown[]) => unknown>();
342 379 const commands = new Map<
343 380 string,
344 381 { handler: (args: string, ctx: unknown) => Promise<void> }
346 - const headers: unknown[] = [];
383 + const widgets: unknown[] = [];
347 384 const ctx = {
348 385 hasUI: true,
349 386 model: undefined,
350 387 modelRegistry: { find: () => undefined },
352 389 notify: () => undefined,
353 - setHeader: (...args: unknown[]) => headers.push(args),
390 + setEditorText: () => undefined,
354 391 setStatus: () => undefined,
392 + setWidget: (...args: unknown[]) => widgets.push(args),
355 393 theme: { fg: (_color: string, text: string) => text },
358 396 modeExtension({
359 397 events: { emit: () => undefined },
360 398 getAllTools: () => [],
399 + getThinkingLevel: () => "medium",
361 400 on: (name: string, handler: (...args: unknown[]) => unknown) =>
362 401 events.set(name, handler),
363 402 registerCommand: (
370 409 setThinkingLevel: () => undefined,
371 410 } as never);
372 411 await events.get("session_start")?.({ reason: "startup" }, ctx);
373 - expect(headers).toEqual([[undefined]]);
412 + expect(widgets).toEqual([["mode", undefined]]);
374 413 const beforeAgent = events.get("before_agent_start")?.(
375 414 { systemPrompt: "BASE" },

extensions/mode/index.ts

Modified
3 3 import { readdir, readFile } from "node:fs/promises";
4 4 import path from "node:path";
5 5 import type {
6 6 ExtensionAPI,
7 7 ExtensionContext,
8 + Theme,
8 9 } from "@earendil-works/pi-coding-agent";
9 10 import { getAgentDir } from "@earendil-works/pi-coding-agent";
10 11 import {
12 + type AutocompleteItem,
11 13 type Component,
12 - Text,
13 - type Theme,
14 + decodeKittyPrintable,
15 + fuzzyFilter,
16 + matchesKey,
14 17 type TUI,
18 + truncateToWidth,
19 + visibleWidth,
15 20 } from "@earendil-works/pi-tui";
16 21 import { parse as parseYaml } from "yaml";
38 43 type ModeRuntimeState = {
39 - activeModeId: string | null;
44 + activeMode: Mode | null;
40 45 neutralize: boolean;
46 + baselineTools: string[] | null;
47 + baselineThinking: ThinkingLevel | null;
48 + baselineModel: ExtensionContext["model"] | null;
41 49 modes: Map<string, Mode>;
42 50 warnings: string[];
176 184 return `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`;
179 -function buildHeader(
187 +function buildWidget(
180 188 mode: Mode | null,
181 189 ): ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined {
182 190 if (!mode) return undefined;
183 - return (_tui, theme) => {
184 - const color: AccentColor = mode.accent ?? "accent";
185 - const banner = theme.fg(color, theme.bold(` ▎ MODE: ${mode.id} `));
186 - const descLine = mode.description
187 - ? theme.fg("muted", ` ${mode.description}`)
188 - : "";
189 - const meta: string[] = [];
190 - if (mode.tools?.length) meta.push(`tools: ${mode.tools.join(", ")}`);
191 - if (mode.model) meta.push(`model: ${mode.model}`);
192 - if (mode.thinking) meta.push(`thinking: ${mode.thinking}`);
193 - const metaLine = meta.length
194 - ? theme.fg("dim", ` ${meta.join(" · ")}`)
195 - : "";
196 - return new Text(
197 - [banner, descLine, metaLine].filter(Boolean).join("\n"),
198 - 0,
199 - 0,
200 - );
201 - };
191 + return (_tui, theme) => ({
192 + invalidate() {},
193 + render(width: number): string[] {
194 + const color: AccentColor = mode.accent ?? "accent";
195 + const banner = theme.fg(color, theme.bold(`▎ MODE: ${mode.id}`));
196 + const parts = [banner];
197 + if (mode.description) parts.push(theme.fg("muted", mode.description));
198 + const meta: string[] = [];
199 + if (mode.tools?.length) meta.push(`tools: ${mode.tools.join(",")}`);
200 + if (mode.model) meta.push(`model: ${mode.model}`);
201 + if (mode.thinking) meta.push(`thinking: ${mode.thinking}`);
202 + if (meta.length) parts.push(theme.fg("dim", meta.join(" · ")));
203 + return [truncateToWidth(parts.join(" "), width, "")];
204 + },
205 + });
204 208 async function loadModes(
238 242 return mode.description ? `${mode.id} — ${mode.description}` : mode.id;
241 -function publishHeader(ctx: ExtensionContext, mode: Mode | null): void {
245 +function modeChoices(modes: Iterable<Mode>): AutocompleteItem[] {
246 + return [
247 + { value: "off", label: "off", description: "Turn mode off" },
248 + ...[...modes].map((mode) => ({
249 + value: mode.id,
250 + label: mode.id,
251 + description: mode.description,
252 + })),
253 + ];
256 +function modeSearchText(item: AutocompleteItem): string {
257 + return `${item.value} ${item.label} ${item.description ?? ""}`;
260 +function modeCompletions(
261 + modes: Iterable<Mode>,
262 + prefix: string,
263 +): AutocompleteItem[] {
264 + return fuzzyFilter(modeChoices(modes), prefix.trim(), modeSearchText);
267 +function printableInput(data: string): string | undefined {
268 + const kitty = decodeKittyPrintable(data);
269 + if (kitty) return kitty;
270 + if (data.length === 1 && data >= " " && data !== "\x7f") return data;
273 +function createModePicker(
274 + items: AutocompleteItem[],
275 + theme: Theme,
276 + done: (result: string | undefined) => void,
277 + render: () => void,
278 +): Component {
279 + let query = "";
280 + let selected = 0;
281 + const visibleCount = 6;
283 + function filtered(): AutocompleteItem[] {
284 + const result = fuzzyFilter(items, query, modeSearchText);
285 + if (selected >= result.length) selected = Math.max(0, result.length - 1);
286 + return result;
289 + function move(delta: number): void {
290 + const total = filtered().length;
291 + if (total === 0) return;
292 + selected = (selected + delta + total) % total;
295 + function resetQuery(next: string): void {
296 + query = next;
297 + selected = 0;
300 + function pad(text: string, width: number): string {
301 + return `${text}${" ".repeat(Math.max(0, width - visibleWidth(text)))}`;
304 + function line(text: string, width: number): string {
305 + return `│ ${pad(truncateToWidth(text, width, ""), width)} │`;
308 + function fullWidth(text: string, width: number): string {
309 + return pad(text, width);
312 + return {
313 + invalidate() {},
314 + render(width: number): string[] {
315 + const viewportHeight = Math.max(18, process.stdout.rows ?? 24);
316 + const cardWidth = Math.max(42, Math.min(76, width - 4));
317 + const innerWidth = cardWidth - 4;
318 + const matches = filtered();
319 + const shown = matches
320 + .slice(
321 + Math.max(
322 + 0,
323 + Math.min(
324 + selected - Math.floor(visibleCount / 2),
325 + matches.length - visibleCount,
326 + ),
327 + ),
329 + .slice(0, visibleCount);
330 + const card: string[] = [
331 + `┌${"─".repeat(cardWidth - 2)}┐`,
332 + line(theme.fg("accent", theme.bold("MODE")), innerWidth),
333 + line(
334 + query
335 + ? `${theme.fg("dim", "filter")} ${query}`
336 + : theme.fg("dim", "type to fuzzy filter"),
337 + innerWidth,
338 + ),
339 + `├${"─".repeat(cardWidth - 2)}┤`,
340 + ];
341 + if (shown.length === 0) {
342 + card.push(line(theme.fg("warning", "no matches"), innerWidth));
343 + } else {
344 + for (const item of shown) {
345 + const index = matches.indexOf(item);
346 + const active = index === selected;
347 + const marker = active ? theme.fg("accent", "›") : " ";
348 + const label = active ? theme.fg("accent", item.label) : item.label;
349 + const left = `${marker} ${label}`;
350 + const descWidth = Math.max(0, innerWidth - visibleWidth(left) - 2);
351 + const desc = item.description
352 + ? theme.fg(
353 + "muted",
354 + truncateToWidth(item.description, descWidth, ""),
356 + : "";
357 + const content = desc ? `${left} ${desc}` : left;
358 + const row = pad(truncateToWidth(content, innerWidth, ""), innerWidth);
359 + card.push(`│ ${active ? theme.bg("selectedBg", row) : row} │`);
362 + while (card.length < 4 + visibleCount) card.push(line("", innerWidth));
363 + card.push(`├${"─".repeat(cardWidth - 2)}┤`);
364 + card.push(
365 + line(
366 + theme.fg(
367 + "dim",
368 + "type fuzzy · ↑↓ move · enter select · esc close",
369 + ),
370 + innerWidth,
371 + ),
372 + );
373 + card.push(`└${"─".repeat(cardWidth - 2)}┘`);
375 + const left = Math.max(0, Math.floor((width - cardWidth) / 2));
376 + const top = Math.max(0, Math.floor((viewportHeight - card.length) / 2));
377 + const lines = Array.from({ length: top }, () => " ".repeat(width));
378 + for (const cardLine of card) {
379 + lines.push(fullWidth(`${" ".repeat(left)}${cardLine}`, width));
381 + while (lines.length < viewportHeight) lines.push(" ".repeat(width));
382 + return lines;
383 + },
384 + handleInput(data: string): void {
385 + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
386 + done(undefined);
387 + return;
389 + if (matchesKey(data, "enter") || matchesKey(data, "return")) {
390 + done(filtered()[selected]?.value);
391 + return;
393 + if (matchesKey(data, "up")) move(-1);
394 + else if (matchesKey(data, "down")) move(1);
395 + else if (matchesKey(data, "backspace"))
396 + resetQuery([...query].slice(0, -1).join(""));
397 + else if (matchesKey(data, "ctrl+u")) resetQuery("");
398 + else {
399 + const char = printableInput(data);
400 + if (char) resetQuery(query + char);
402 + render();
403 + },
404 + };
407 +function publishWidget(ctx: ExtensionContext, mode: Mode | null): void {
242 408 if (!ctx.hasUI) return;
243 - ctx.ui.setHeader(buildHeader(mode));
409 + ctx.ui.setWidget("mode", buildWidget(mode));
246 412 function publishStatus(ctx: ExtensionContext, mode: Mode | null): void {
256 422 export default function modeExtension(pi: ExtensionAPI): void {
257 423 const state: ModeRuntimeState = {
258 - activeModeId: null,
424 + activeMode: null,
259 425 neutralize: false,
426 + baselineTools: null,
427 + baselineThinking: null,
428 + baselineModel: null,
260 429 modes: new Map(),
261 430 warnings: [],
282 451 pi.setActiveTools(valid);
283 - ctx.ui.notify(`mode ${mode.id}: tools ${valid.join(", ")}`, "info");
285 453 if (mode.model) {
286 454 const ref = parseModelRef(mode.model);
309 477 ctx.ui.notify(`unknown mode: ${id}`, "warning");
310 478 return;
312 - state.activeModeId = id;
480 + if (state.baselineTools === null) {
481 + state.baselineTools = pi.getActiveTools();
482 + state.baselineThinking = pi.getThinkingLevel();
483 + state.baselineModel = ctx.model ?? null;
484 + } else {
485 + pi.setActiveTools(state.baselineTools);
486 + if (state.baselineModel) await pi.setModel(state.baselineModel);
487 + if (state.baselineThinking) pi.setThinkingLevel(state.baselineThinking);
489 + state.activeMode = mode;
313 490 state.neutralize = false;
314 491 await applyMode(mode, ctx);
315 - publishHeader(ctx, mode);
492 + publishWidget(ctx, mode);
316 493 publishStatus(ctx, mode);
320 497 if (!ctx.hasUI) return;
321 498 await reloadConfig(ctx);
322 499 const modes = [...state.modes.values()];
323 - if (modes.length === 0) {
500 + if (modes.length === 0 && state.activeMode === null) {
324 501 ctx.ui.notify("no modes available", "info");
325 502 return;
327 - const labels = new Map(modes.map((mode) => [modeLine(mode), mode.id]));
328 - const choice = await ctx.ui.select("Select mode", [...labels.keys()]);
504 + const choice = await ctx.ui.custom<string | undefined>(
505 + (tui, theme, _keybindings, done) =>
506 + createModePicker(modeChoices(modes), theme, done, () =>
507 + tui.requestRender(),
508 + ),
510 + overlay: true,
511 + overlayOptions: {
512 + anchor: "center",
513 + width: "100%",
514 + maxHeight: "100%",
515 + },
516 + },
517 + );
329 518 if (!choice) return;
330 - const id = labels.get(choice);
331 - if (id) await switchMode(id, ctx);
519 + if (choice === "off") {
520 + await modeOff(ctx);
521 + return;
523 + await switchMode(choice, ctx);
334 526 async function cycleMode(ctx: ExtensionContext): Promise<void> {
338 530 ctx.ui.notify("no modes available", "info");
339 531 return;
341 - const currentIndex = state.activeModeId
342 - ? ids.indexOf(state.activeModeId)
533 + const currentIndex = state.activeMode
534 + ? ids.indexOf(state.activeMode.id)
344 536 const next = ids[(currentIndex + 1) % ids.length];
345 537 if (!next) return;
346 538 await switchMode(next, ctx);
349 - function modeOff(ctx: ExtensionContext): void {
350 - if (state.activeModeId === null) {
541 + async function restoreBaseline(): Promise<void> {
542 + if (state.baselineTools) pi.setActiveTools(state.baselineTools);
543 + if (state.baselineModel) await pi.setModel(state.baselineModel);
544 + if (state.baselineThinking) pi.setThinkingLevel(state.baselineThinking);
545 + state.baselineTools = null;
546 + state.baselineThinking = null;
547 + state.baselineModel = null;
550 + async function modeOff(ctx: ExtensionContext): Promise<void> {
551 + if (state.activeMode === null) {
351 552 ctx.ui.notify("no mode active", "info");
352 553 return;
354 - state.activeModeId = null;
555 + state.activeMode = null;
355 556 state.neutralize = true;
356 - publishHeader(ctx, null);
557 + await restoreBaseline();
558 + publishWidget(ctx, null);
357 559 publishStatus(ctx, null);
360 562 function showStatus(ctx: ExtensionContext): void {
361 - const active = state.activeModeId ?? "normal";
563 + const active = state.activeMode?.id ?? "normal";
362 564 const modes = [...state.modes.values()].map(modeLine);
363 565 const warnings = state.warnings.map((warning) => `warning: ${warning}`);
364 566 ctx.ui.notify(
374 576 pi.registerCommand("mode", {
375 577 description: "Switch session-local mode",
578 + getArgumentCompletions: async (prefix) => {
579 + const loaded = await loadModes();
580 + state.modes = loaded.modes;
581 + state.warnings = loaded.warnings;
582 + return modeCompletions(state.modes.values(), prefix);
583 + },
376 584 handler: async (args, ctx) => {
377 585 const arg = args.trim();
378 586 if (!arg || arg === "status") {
402 610 return;
404 612 if (arg === "off" || arg === "normal" || arg === "none") {
405 - modeOff(ctx);
613 + await modeOff(ctx);
406 614 return;
408 616 await switchMode(arg, ctx);
412 - pi.registerShortcut("ctrl+shift+m", {
620 + pi.registerShortcut("alt+m", {
413 621 description: "Select mode",
414 622 handler: async (ctx) => selectMode(ctx),
417 625 pi.on("before_agent_start", (event) => {
418 - const mode = state.activeModeId
419 - ? state.modes.get(state.activeModeId)
420 - : undefined;
626 + const mode = state.activeMode;
421 627 if (mode)
422 628 return {
423 629 systemPrompt: `${event.systemPrompt}\n\n${modePromptAddition(mode)}`,
432 638 pi.on("session_start", async (_event, ctx) => {
639 + await restoreBaseline();
433 640 await reloadConfig(ctx);
434 - state.activeModeId = null;
641 + state.activeMode = null;
435 642 state.neutralize = false;
436 - publishHeader(ctx, null);
643 + publishWidget(ctx, null);
437 644 publishStatus(ctx, null);
440 - pi.on("session_shutdown", (_event, ctx) => {
441 - publishHeader(ctx, null);
647 + pi.on("session_shutdown", async (_event, ctx) => {
648 + await restoreBaseline();
649 + state.activeMode = null;
650 + state.neutralize = false;
651 + publishWidget(ctx, null);
442 652 publishStatus(ctx, null);
446 656 export const __modeTest = {
447 657 ACCENT_COLORS,
448 - buildHeader,
658 + buildWidget,
659 + createModePicker,
660 + modeChoices,
661 + modeCompletions,
662 + printableInput,
449 663 frontmatterSplit,
450 664 isValidModeId,
451 665 loadModes,

extensions/mode/package.json

Modified
15 15 "vitest": "^4.1.9"
17 17 "license": "MIT",
18 - "description": "Session-local mode switching with themed header visibility for Pi.",
18 + "description": "Session-local mode switching with widget visibility for Pi.",
19 19 "keywords": [
20 20 "pi",
21 21 "pi-extension",

extensions/pulse/__tests__/index.test.ts

Modified
6 6 let completionText = '{"updates":[]}';
7 7 let completionTexts: string[] = [];
8 8 let completionCalls = 0;
9 +let completionOptions: Record<string, unknown> | undefined;
10 11 const {
11 12 default: pulse,
15 16 } = await import("../index.ts");
17 18 __setPulseModelClient({
18 - complete: (async () => {
19 + complete: (async (_model: unknown, _context: unknown, options: unknown) => {
19 20 completionCalls++;
21 + completionOptions = options as Record<string, unknown>;
20 22 return {
21 23 content: [
22 24 { type: "text", text: completionTexts.shift() ?? completionText },
127 129 completionText = '{"updates":[]}';
128 130 completionTexts = [];
129 131 completionCalls = 0;
132 + completionOptions = undefined;
130 133 __setPulseModelClient({
131 - complete: (async () => {
134 + complete: (async (_model: unknown, _context: unknown, options: unknown) => {
132 135 completionCalls++;
136 + completionOptions = options as Record<string, unknown>;
133 137 return {
134 138 content: [
135 139 { type: "text", text: completionTexts.shift() ?? completionText },
198 202 ).toBe(false);
205 + it("accepts header-only model auth", async () => {
206 + const root = cwd();
207 + write(root, "README.md", "doc");
208 + writeConfig(root, { documents: [{ path: "README.md" }] });
209 + const h = harness(root);
210 + h.ctx.modelRegistry.getApiKeyAndHeaders = async () => ({
211 + ok: true,
212 + headers: { authorization: "Bearer TOKEN" },
213 + });
215 + await h.commands.get("pulse").handler("force", h.ctx);
217 + expect(completionCalls).toBe(1);
218 + expect(completionOptions).toMatchObject({
219 + headers: { authorization: "Bearer TOKEN" },
220 + });
221 + expect(
222 + h.notifications.some((n) => n.message.includes("missing auth")),
223 + ).toBe(false);
224 + });
201 226 it("does not expose terminal controls in completions", () => {
202 227 const root = cwd();
203 228 if (supportsControlCharPaths) write(root, "bad\u001b[31m.md", "doc");

extensions/pulse/index.ts

Modified
282 282 docs: LoadedPulseDoc[],
283 283 recentMessages: unknown[],
284 284 model: { provider: string; id: string },
285 - apiKey: string,
285 + auth: { apiKey?: string; headers?: Record<string, string> },
286 286 ): Promise<PulseUpdate[]> {
287 287 const conversation = serializeConversation(
288 288 convertToLlm(recentMessages as any),
333 - { apiKey, cacheRetention: "none" },
334 + apiKey: auth.apiKey,
335 + headers: auth.headers,
336 + cacheRetention: "none",
337 + },
336 340 lastResponse = textFromResponse(response);
889 893 model as Parameters<typeof ctx.modelRegistry.getApiKeyAndHeaders>[0],
891 895 if (ticket !== generation) return;
892 - if (!auth.ok || !auth.apiKey) {
896 + if (!auth.ok) {
893 897 missingAuthModels.push(`${model.provider}/${model.id}`);
894 898 continue;
902 906 loadedGroup,
903 907 recentMessages,
904 908 model,
905 - auth.apiKey,
909 + auth,
907 911 if (ticket !== generation) return;
908 912 const updates = await applyModeUpdates(

extensions/q/extract.ts

Modified
397 397 // S5: inlined auth check
398 398 const auth = await ctx.modelRegistry.getApiKeyAndHeaders(resolved);
399 - if (!auth.ok || !auth.apiKey)
400 - throw new Error(
401 - auth.ok ? `No API key for ${resolved.provider}` : "auth failed",
402 - );
399 + if (!auth.ok) throw new Error(auth.error ?? "auth failed");
404 401 const userMessage: Message = {
405 402 role: "user",

extensions/session-rename/index.ts

Modified
312 312 if (!model) return undefined;
314 314 const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
315 - if (!auth?.ok || !auth.apiKey) return undefined;
315 + if (!auth?.ok) return undefined;
317 317 const prompt =
318 318 "Generate or refine a short display name for a Pi coding-agent session.\n\n" +

extensions/tldr/__tests__/tldr.test.ts

Modified
188 + it("accepts header-only auth from configured model", async () => {
189 + const ctx = fakeCtx({
190 + modelRegistry: {
191 + find(provider: string, id: string) {
192 + return provider === "fast" && id === "mini"
193 + ? { provider: "fast", id: "mini" }
194 + : undefined;
195 + },
196 + async getApiKeyAndHeaders() {
197 + return { ok: true, headers: { authorization: "Bearer TOKEN" } };
198 + },
199 + },
200 + });
202 + await expect(resolveTldrModel(ctx, "fast/mini")).resolves.toMatchObject({
203 + model: { provider: "fast", id: "mini" },
204 + headers: { authorization: "Bearer TOKEN" },
205 + });
206 + });
188 208 it("generates TLDR with cache disabled and renders sanitized result", async () => {
189 209 const calls: any[] = [];
190 210 const scheduler = fakeScheduler();

extensions/tldr/index.ts

Modified
53 53 type TldrAuth = {
54 54 model: Model<any>;
55 - apiKey: string;
55 + apiKey?: string;
56 56 headers?: Record<string, string>;
239 239 ): Promise<TldrAuth | undefined> {
240 240 if (!model) return undefined;
241 241 const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
242 - return auth.ok && auth.apiKey
242 + return auth.ok
243 243 ? { model, apiKey: auth.apiKey, headers: auth.headers }
244 244 : undefined;