repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(mode): memory-only state with themed header UX

e196bb14ff20f72f6cd4b016a3cd7b196fbc4c37

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Drop session persistence (mode-state entries, latestModeState,
persist, session_compact handler, branch restore on session_start).
Mode state is now in-memory only; users re-run /mode <id> per session.

Replace setStatus with setHeader using a themed Text component.
Frontmatter gains accent: AccentColor to color the banner.

Drop:
- setStatus, setTitle, setWidget (footer status becomes header)
- notify on switch/off (header appearance is the signal)
- baseline/applied/allToolsAtSwitch tracking
- compaction checkpoint
- branch restore on session_start
- tool/model/thinking restore on /mode off (SDK mutates defaults)

Added:
- buildHeader factory with theme.fg/bold on banner
- accent frontmatter (accent|borderAccent|success|warning|error|muted|dim)
- /mode off notify 'no mode active' when no mode is active

Rebase note: remove extensions/mode/__tests__/harness-full.test.ts. origin's
test-suite split (0aff0ca) had relocated the old disk-persistence harness
tests into that file, but this commit removes that behavior. Its 4 unique
tests (branch restore, compaction checkpoint, state persistence, file-restore
fallback) no longer apply; its other 9 tests duplicate harness.test.ts, which
already asserts the memory-only equivalents (session_start reset, no-persist
on off).

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

Changed files (11)

extensions/mode/PLAN.md

Modified
1 1 # Mode Extension V1 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.
3 +**Status:** Implemented.
5 -**Goal:** Build the validated V1 mode extension from `extensions/mode/V1.md`.
5 +The original V1 implementation (session persistence via `mode-state` entries) was revised mid-flight.
6 +See `V1.md` for the implemented design (memory-only state, themed `setHeader` UI, `accent` frontmatter).
7 -**Architecture:** Single Pi extension with pure helpers for mode parsing/state rendering and thin runtime glue for commands/events. Modes load from `getAgentDir()/modes/*.md`; branch state is persisted with custom `mode-state` entries; prompt injection mutates `before_agent_start.systemPrompt` only.
8 +## Implementation summary
9 -**Tech Stack:** TypeScript, Pi extension API, `yaml`, Vitest, `@marcfargas/pi-test-harness`.
10 +What was built:
11 -**Roadmap:** None
12 +- `index.ts` — pure helpers (`frontmatterSplit`, `parseModeMarkdown`, `loadModes`, `modePromptAddition`, `normalPromptAddition`, `buildHeader`) plus runtime glue (`switchMode`, `modeOff`, `applyMode`, `showStatus`).
13 +- 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).
14 +- UI: `ctx.ui.setHeader(buildHeader(mode))` replaces `setStatus`. Restoring built-in header via `setHeader(undefined)` on off/shutdown.
15 +- Frontmatter additions: `accent: AccentColor`.
16 +- Dropped: `mode-state` session entries, `latestModeState`, `persist`, `session_compact` handler, branch restore on `session_start`, baseline tracking, `setStatus`, `setTitle`, `setWidget`.
17 +- Updated: `V1.md`, `V2.md` (V2's `color` frontmatter moved to V1 as `accent`), `SPEC.md`, `README.md`.
13 -**Phase:** Single-plan implementation
15 ----
17 -## File structure
19 -- Create `extensions/mode/package.json`: workspace package metadata and `yaml` runtime dependency.
20 -- Create `extensions/mode/README.md`: user-facing behavior, commands, and V1 limits.
21 -- Create `extensions/mode/index.ts`: extension entrypoint, parser, state, commands, hooks, and test exports.
22 -- Create `extensions/mode/__tests__/unit.test.ts`: pure parser/state/kernel tests.
23 -- Create `extensions/mode/__tests__/harness.test.ts`: real Pi runtime tests for commands, tool filtering, prompt injection, restore, and compaction.
24 -- Modify `package-lock.json`: generated by `npm install` after adding the workspace package.
26 -## Task 1: Package skeleton
28 -**Files:**
30 -- Create: `extensions/mode/package.json`
31 -- Create: `extensions/mode/README.md`
33 -- [ ] **Step 1: Create package manifest**
35 -Write `extensions/mode/package.json`:
37 -```json
39 - "name": "@bugabinga/pi-ext-mode",
40 - "private": true,
41 - "type": "module",
42 - "main": "index.ts",
43 - "dependencies": {
44 - "yaml": "^2.9.0"
45 - },
46 - "peerDependencies": {
47 - "@earendil-works/pi-coding-agent": "*"
48 - },
49 - "devDependencies": {
50 - "@marcfargas/pi-test-harness": "^0.6.1",
51 - "vitest": "^4.1.8"
52 - },
53 - "license": "MIT",
54 - "description": "Session-local mode switching for Pi.",
55 - "keywords": [
56 - "pi",
57 - "pi-extension",
58 - "mode"
59 - ]
61 -```
63 -- [ ] **Step 2: Create README**
65 -Write `extensions/mode/README.md`:
67 -````markdown
68 -# mode
70 -Session-local Pi modes from Markdown files.
72 -## Install / load
74 -Loaded through the root pi-ext package.
75 -See [../../README.md](../../README.md).
77 -## Commands / tools / settings
79 -Commands:
81 -- `/mode` — show active mode and available modes.
82 -- `/mode status` — same as `/mode`.
83 -- `/mode list` — list available modes.
84 -- `/mode <id>` — switch to a mode.
85 -- `/mode off` — turn mode off.
86 -- `/mode normal` — alias for `/mode off`.
87 -- `/mode none` — alias for `/mode off`.
88 -- `/mode reload-config` — reload mode files and report count/warnings.
90 -Tools: none.
92 -Settings: none.
94 -## Mode files
96 -V1 loads only global mode files:
98 -```text
99 -~/.pi/agent/modes/*.md
100 -```
101 -````
103 -Mode id is the file stem.
104 -Valid ids match `^[a-zA-Z0-9_-]+$`.
106 -Example:
108 -```md
109 ----
110 -description: Read-only planning
111 -model: openai/gpt-5.2-codex
112 -thinking: high
113 -tools: [read, grep, find, ls]
114 -reminder: You are planning only. Do not implement.
115 ----
117 -# Planning mode
119 -Plan only.
120 -Do not implement.
121 -```
123 -## Behavior
125 -Active mode appends its Markdown body and a generated mode kernel to the system prompt for each agent turn.
126 -Mode prompts are not stored as chat messages.
128 -A mode may change active tools, model, and thinking level.
129 -Turning mode off does not restore prior tools, model, or thinking in V1.
131 -Mode state persists in session custom entries.
132 -Restore uses the current branch only.
133 -Compaction adds a mode checkpoint.
135 -## V1 limits
137 -Project-local `.pi/modes/*.md` is deferred until Pi exposes a public project-trust API to extensions.
138 -Shortcuts, extension scoping, permission policy, tool globs, and baseline restore are not in V1.
140 -````
141 -- [ ] **Step 3: Install/update lockfile**
143 -Run:
19 +## Verification
145 21 ```bash
146 -npm install
147 -````
149 -Expected:
151 -- `package-lock.json` adds workspace package `extensions/mode`.
152 -- Existing root dependencies remain intact.
154 -- [ ] **Step 4: Commit package skeleton**
156 -Run:
158 -```bash
159 -git add extensions/mode/package.json extensions/mode/README.md package-lock.json
160 -git commit -m "feat(mode): add extension package skeleton"
22 +mise run test
23 +mise run lint
163 -Expected: commit succeeds.
26 +Both pass.
165 -## Task 2: Pure mode helpers
167 -**Files:**
169 -- Create: `extensions/mode/index.ts`
170 -- Create: `extensions/mode/__tests__/unit.test.ts`
172 -- [ ] **Step 1: Write failing unit tests for parsing and rendering**
174 -Create `extensions/mode/__tests__/unit.test.ts`:
176 -```ts
177 -import { describe, expect, it } from "vitest";
178 -import { __modeTest } from "../index.ts";
180 -const nowEntry = (data: unknown) => ({
181 - type: "custom",
182 - customType: "mode-state",
183 - data,
184 -});
186 -describe("mode pure helpers", () => {
187 - it("parses valid mode markdown", () => {
188 - const mode = __modeTest.parseModeMarkdown(
189 - "plan",
190 - `---\ndescription: Read-only planning\nmodel: openai/gpt-5.2-codex\nthinking: high\ntools: [read, grep]\nreminder: Stay read-only.\n---\n\n# Plan\n\nBody.\n`,
191 - );
192 - expect(mode).toEqual({
193 - id: "plan",
194 - description: "Read-only planning",
195 - model: "openai/gpt-5.2-codex",
196 - thinking: "high",
197 - tools: ["read", "grep"],
198 - reminder: "Stay read-only.",
199 - body: "# Plan\n\nBody.\n",
200 - });
201 - });
203 - it("allows empty body and empty frontmatter", () => {
204 - expect(__modeTest.parseModeMarkdown("empty", "---\n---\n")).toEqual({
205 - id: "empty",
206 - body: "",
207 - });
208 - });
210 - it("rejects invalid field types", () => {
211 - expect(() =>
212 - __modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\nbody")
213 - ).toThrow(
214 - "mode bad: tools must be an array of strings",
215 - );
216 - expect(() =>
217 - __modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\nbody")
218 - ).toThrow(
219 - "mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
220 - );
221 - });
223 - it("validates ids", () => {
224 - expect(__modeTest.isValidModeId("plan_1-build")).toBe(true);
225 - expect(__modeTest.isValidModeId("../plan")).toBe(false);
226 - expect(__modeTest.isValidModeId("plan mode")).toBe(false);
227 - });
229 - it("splits model ref at first slash", () => {
230 - expect(__modeTest.parseModelRef("openai/gpt-5.2/codex")).toEqual({
231 - provider: "openai",
232 - modelId: "gpt-5.2/codex",
233 - });
234 - expect(__modeTest.parseModelRef("missing-slash")).toBeUndefined();
235 - expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
236 - });
238 - it("renders active prompt addition", () => {
239 - const text = __modeTest.modePromptAddition({
240 - id: "plan",
241 - body: "# Body\n",
242 - reminder: "Stay read-only.",
243 - });
244 - expect(text).toContain("# Body");
245 - expect(text).toContain("<mode_kernel>");
246 - expect(text).toContain("active_mode: plan");
247 - expect(text).toContain(
248 - "<mode_reminder>\nStay read-only.\n</mode_reminder>",
249 - );
250 - expect(text.indexOf("# Body")).toBeLessThan(text.indexOf("<mode_kernel>"));
251 - });
253 - it("renders normal neutralizer", () => {
254 - expect(__modeTest.normalPromptAddition()).toBe(
255 - `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`,
256 - );
257 - });
259 - it("restores latest mode state from current branch entries", () => {
260 - expect(
261 - __modeTest.latestModeState([
262 - nowEntry({
263 - schemaVersion: 1,
264 - activeMode: "plan",
265 - neutralize: false,
266 - reason: "switch",
267 - }),
268 - ]),
269 - ).toEqual({
270 - schemaVersion: 1,
271 - activeMode: "plan",
272 - neutralize: false,
273 - reason: "switch",
274 - });
275 - expect(__modeTest.latestModeState([nowEntry({ broken: true })]))
276 - .toBeUndefined();
277 - });
278 -});
279 -```
281 -- [ ] **Step 2: Run unit test and verify failure**
283 -Run:
285 -```bash
286 -mise run test -- extensions/mode/__tests__/unit.test.ts
287 -```
289 -Expected: FAIL because `extensions/mode/index.ts` does not exist.
291 -- [ ] **Step 3: Implement pure helpers and extension shell**
293 -Create `extensions/mode/index.ts` with these exported test helpers and default extension shell:
295 -```ts
296 -import type {
297 - ExtensionAPI,
298 - ExtensionContext,
299 -} from "@earendil-works/pi-coding-agent";
300 -import { getAgentDir } from "@earendil-works/pi-coding-agent";
301 -import { readdir, readFile } from "node:fs/promises";
302 -import path from "node:path";
303 -import { parse as parseYaml } from "yaml";
305 -type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
307 -type Mode = {
308 - id: string;
309 - description?: string;
310 - model?: string;
311 - thinking?: ThinkingLevel;
312 - reminder?: string;
313 - tools?: string[];
314 - body: string;
317 -type ModeStateEntry = {
318 - schemaVersion: 1;
319 - activeMode: string | null;
320 - neutralize: boolean;
321 - reason: "switch" | "off" | "compaction";
322 - model?: string;
323 - provider?: string;
324 - compactionEntryId?: string;
327 -type ModeRuntimeState = {
328 - activeModeId: string | null;
329 - neutralize: boolean;
330 - modes: Map<string, Mode>;
331 - warnings: string[];
334 -type ModeEntryLike = {
335 - type?: unknown;
336 - customType?: unknown;
337 - data?: unknown;
340 -type ModelRef = { provider: string; modelId: string };
342 -const MODE_STATE_VERSION = 1;
343 -const MODE_STATE_ENTRY = "mode-state";
344 -const STATUS_KEY = "mode";
345 -const THINKING_LEVELS = [
346 - "off",
347 - "minimal",
348 - "low",
349 - "medium",
350 - "high",
351 - "xhigh",
352 -] as const;
353 -const MODE_ID_RE = /^[a-zA-Z0-9_-]+$/;
355 -function isValidModeId(id: string): boolean {
356 - return MODE_ID_RE.test(id);
359 -function frontmatterSplit(
360 - markdown: string,
361 -): { frontmatter: string; body: string } {
362 - if (!markdown.startsWith("---")) return { frontmatter: "", body: markdown };
363 - const firstLineEnd = markdown.indexOf("\n");
364 - if (firstLineEnd === -1) return { frontmatter: "", body: "" };
365 - const close = markdown.indexOf("\n---", firstLineEnd + 1);
366 - if (close === -1) return { frontmatter: "", body: markdown };
367 - let bodyStart = close + "\n---".length;
368 - if (markdown.startsWith("\r\n", bodyStart)) bodyStart += 2;
369 - else if (markdown.startsWith("\n", bodyStart)) bodyStart += 1;
370 - return {
371 - frontmatter: markdown.slice(firstLineEnd + 1, close),
372 - body: markdown.slice(bodyStart),
373 - };
376 -function parseModeMarkdown(id: string, markdown: string): Mode {
377 - const { frontmatter, body } = frontmatterSplit(
378 - markdown.replaceAll("\r\n", "\n"),
379 - );
380 - const raw = frontmatter.trim() ? parseYaml(frontmatter) : {};
381 - if (
382 - raw !== undefined
383 - && (raw === null || typeof raw !== "object" || Array.isArray(raw))
384 - ) {
385 - throw new Error(`mode ${id}: frontmatter must be a mapping`);
387 - const data = (raw ?? {}) as Record<string, unknown>;
388 - const mode: Mode = { id, body };
390 - if (data.description !== undefined) {
391 - mode.description = requireString(id, "description", data.description);
393 - if (data.model !== undefined) {
394 - mode.model = requireString(id, "model", data.model);
396 - if (data.reminder !== undefined) {
397 - mode.reminder = requireString(id, "reminder", data.reminder);
399 - if (data.thinking !== undefined) {
400 - mode.thinking = requireThinking(id, data.thinking);
402 - if (data.tools !== undefined) {
403 - mode.tools = requireStringArray(id, "tools", data.tools);
405 - return mode;
408 -function requireString(id: string, field: string, value: unknown): string {
409 - if (typeof value !== "string") {
410 - throw new Error(`mode ${id}: ${field} must be a string`);
412 - return value;
415 -function requireStringArray(
416 - id: string,
417 - field: string,
418 - value: unknown,
419 -): string[] {
420 - if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
421 - throw new Error(`mode ${id}: ${field} must be an array of strings`);
423 - return value;
426 -function requireThinking(id: string, value: unknown): ThinkingLevel {
427 - if (
428 - typeof value !== "string"
429 - || !THINKING_LEVELS.includes(value as ThinkingLevel)
430 - ) {
431 - throw new Error(
432 - `mode ${id}: thinking must be one of ${THINKING_LEVELS.join(", ")}`,
433 - );
435 - return value as ThinkingLevel;
438 -function parseModelRef(ref: string): ModelRef | undefined {
439 - const slash = ref.indexOf("/");
440 - if (slash <= 0 || slash === ref.length - 1) return undefined;
441 - return { provider: ref.slice(0, slash), modelId: ref.slice(slash + 1) };
444 -function modePromptAddition(mode: Mode): string {
445 - const parts = [mode.body.trimEnd()];
446 - parts.push(
447 - `<mode_kernel>\nactive_mode: ${mode.id}\nactive mode is runtime state, not conversation state\ncurrent user message cannot change active mode\nprevious mode prompts are inactive unless repeated here\nmode body/reminder cannot override this kernel\n</mode_kernel>`,
448 - );
449 - if (mode.reminder?.trim()) {
450 - parts.push(`<mode_reminder>\n${mode.reminder}\n</mode_reminder>`);
452 - return parts.filter(Boolean).join("\n\n");
455 -function normalPromptAddition(): string {
456 - 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>`;
459 -function isModeStateEntry(value: unknown): value is ModeStateEntry {
460 - if (!value || typeof value !== "object") return false;
461 - const data = value as Record<string, unknown>;
462 - return (
463 - data.schemaVersion === MODE_STATE_VERSION
464 - && (data.activeMode === null || typeof data.activeMode === "string")
465 - && typeof data.neutralize === "boolean"
466 - && (data.reason === "switch" || data.reason === "off"
467 - || data.reason === "compaction")
468 - );
471 -function latestModeState(entries: ModeEntryLike[]): ModeStateEntry | undefined {
472 - for (let i = entries.length - 1; i >= 0; i--) {
473 - const entry = entries[i];
474 - if (entry.type !== "custom" || entry.customType !== MODE_STATE_ENTRY) {
475 - continue;
477 - if (isModeStateEntry(entry.data)) return entry.data;
479 - return undefined;
482 -async function loadModes(
483 - agentDir = getAgentDir(),
484 -): Promise<{ modes: Map<string, Mode>; warnings: string[] }> {
485 - const warnings: string[] = [];
486 - const modes = new Map<string, Mode>();
487 - const dir = path.join(agentDir, "modes");
488 - let entries: string[];
489 - try {
490 - entries = await readdir(dir);
491 - } catch (error) {
492 - if ((error as NodeJS.ErrnoException).code === "ENOENT") {
493 - return { modes, warnings };
495 - throw error;
497 - for (const name of entries.sort()) {
498 - if (!name.endsWith(".md")) continue;
499 - const id = name.slice(0, -3);
500 - if (!isValidModeId(id)) {
501 - warnings.push(`ignored invalid mode id: ${name}`);
502 - continue;
504 - try {
505 - modes.set(
506 - id,
507 - parseModeMarkdown(id, await readFile(path.join(dir, name), "utf8")),
508 - );
509 - } catch (error) {
510 - warnings.push((error as Error).message);
513 - return { modes, warnings };
516 -function modeLine(mode: Mode): string {
517 - return mode.description ? `${mode.id} — ${mode.description}` : mode.id;
520 -function statusText(modeId: string | null): string | undefined {
521 - return modeId ? `MODE ${modeId}` : undefined;
524 -function publishStatus(ctx: ExtensionContext, modeId: string | null): void {
525 - if (!ctx.hasUI) return;
526 - ctx.ui.setStatus(STATUS_KEY, statusText(modeId));
529 -function currentModelState(
530 - ctx: ExtensionContext,
531 -): Pick<ModeStateEntry, "provider" | "model"> {
532 - return ctx.model ? { provider: ctx.model.provider, model: ctx.model.id } : {};
535 -export default function modeExtension(pi: ExtensionAPI): void {
536 - const state: ModeRuntimeState = {
537 - activeModeId: null,
538 - neutralize: false,
539 - modes: new Map(),
540 - warnings: [],
541 - };
543 - async function reloadConfig(ctx?: ExtensionContext): Promise<void> {
544 - const loaded = await loadModes();
545 - state.modes = loaded.modes;
546 - state.warnings = loaded.warnings;
547 - for (const warning of state.warnings) ctx?.ui.notify(warning, "warning");
550 - function persist(
551 - ctx: ExtensionContext,
552 - reason: ModeStateEntry["reason"],
553 - compactionEntryId?: string,
554 - ): void {
555 - pi.appendEntry(
556 - MODE_STATE_ENTRY,
558 - schemaVersion: MODE_STATE_VERSION,
559 - activeMode: state.activeModeId,
560 - neutralize: state.neutralize,
561 - reason,
562 - ...currentModelState(ctx),
563 - ...(compactionEntryId ? { compactionEntryId } : {}),
564 - } satisfies ModeStateEntry,
565 - );
568 - async function applyMode(mode: Mode, ctx: ExtensionContext): Promise<void> {
569 - if (mode.tools && mode.tools.length > 0) {
570 - const all = new Set(pi.getAllTools().map((tool) => tool.name));
571 - const valid = mode.tools.filter((tool) => all.has(tool));
572 - const unknown = mode.tools.filter((tool) => !all.has(tool));
573 - for (const tool of unknown) {
574 - ctx.ui.notify(
575 - `mode ${mode.id}: unknown tool ignored: ${tool}`,
576 - "warning",
577 - );
579 - pi.setActiveTools(valid);
580 - ctx.ui.notify(`mode ${mode.id}: tools ${valid.join(", ")}`, "info");
582 - if (mode.model) {
583 - const ref = parseModelRef(mode.model);
584 - const model = ref
585 - ? ctx.modelRegistry.find(ref.provider, ref.modelId)
586 - : undefined;
587 - if (!ref || !model) {
588 - ctx.ui.notify(
589 - `mode ${mode.id}: model not found: ${mode.model}`,
590 - "warning",
591 - );
592 - } else if (!(await pi.setModel(model))) {
593 - ctx.ui.notify(
594 - `mode ${mode.id}: model unavailable: ${mode.model}`,
595 - "warning",
596 - );
599 - if (mode.thinking) pi.setThinkingLevel(mode.thinking);
602 - async function switchMode(id: string, ctx: ExtensionContext): Promise<void> {
603 - await reloadConfig(ctx);
604 - const mode = state.modes.get(id);
605 - if (!mode) {
606 - ctx.ui.notify(`unknown mode: ${id}`, "warning");
607 - return;
609 - state.activeModeId = id;
610 - state.neutralize = false;
611 - await applyMode(mode, ctx);
612 - persist(ctx, "switch");
613 - publishStatus(ctx, id);
614 - ctx.ui.notify(`mode ${id}`, "info");
617 - function modeOff(ctx: ExtensionContext): void {
618 - const hadMode = state.activeModeId !== null;
619 - state.activeModeId = null;
620 - state.neutralize = hadMode || state.neutralize;
621 - persist(ctx, "off");
622 - publishStatus(ctx, null);
623 - ctx.ui.notify("mode off", "info");
626 - function showStatus(ctx: ExtensionContext): void {
627 - const active = state.activeModeId ?? "normal";
628 - const modes = [...state.modes.values()].map(modeLine);
629 - const warnings = state.warnings.map((warning) => `warning: ${warning}`);
630 - ctx.ui.notify(
632 - `active: ${active}`,
633 - modes.length ? `modes:\n${modes.join("\n")}` : "modes: none",
634 - ...warnings,
635 - ].join("\n"),
636 - "info",
637 - );
640 - pi.registerCommand("mode", {
641 - description: "Switch session-local mode",
642 - handler: async (args, ctx) => {
643 - const arg = args.trim();
644 - if (!arg || arg === "status") {
645 - await reloadConfig(ctx);
646 - showStatus(ctx);
647 - return;
649 - if (arg === "list") {
650 - await reloadConfig(ctx);
651 - showStatus(ctx);
652 - return;
654 - if (arg === "reload-config") {
655 - await reloadConfig(ctx);
656 - ctx.ui.notify(
657 - `mode config: ${state.modes.size} mode(s), ${state.warnings.length} warning(s)`,
658 - state.warnings.length ? "warning" : "info",
659 - );
660 - return;
662 - if (arg === "off" || arg === "normal" || arg === "none") {
663 - modeOff(ctx);
664 - return;
666 - await switchMode(arg, ctx);
667 - },
668 - });
670 - pi.on("before_agent_start", (event) => {
671 - const mode = state.activeModeId
672 - ? state.modes.get(state.activeModeId)
673 - : undefined;
674 - if (mode) {
675 - return {
676 - systemPrompt: `${event.systemPrompt}\n\n${modePromptAddition(mode)}`,
677 - };
679 - if (state.neutralize) {
680 - return {
681 - systemPrompt: `${event.systemPrompt}\n\n${normalPromptAddition()}`,
682 - };
684 - });
686 - pi.on("session_start", async (_event, ctx) => {
687 - await reloadConfig(ctx);
688 - const saved = latestModeState(
689 - ctx.sessionManager.getBranch() as ModeEntryLike[],
690 - );
691 - state.activeModeId = saved?.activeMode ?? null;
692 - state.neutralize = saved?.neutralize ?? false;
693 - if (state.activeModeId) {
694 - const mode = state.modes.get(state.activeModeId);
695 - if (mode) await applyMode(mode, ctx);
696 - else {
697 - ctx.ui.notify(
698 - `mode missing: ${state.activeModeId}; falling back to normal`,
699 - "warning",
700 - );
701 - state.activeModeId = null;
702 - state.neutralize = true;
703 - persist(ctx, "off");
706 - publishStatus(ctx, state.activeModeId);
707 - });
709 - pi.on(
710 - "session_compact",
711 - (event, ctx) => persist(ctx, "compaction", event.compactionEntry.id),
712 - );
713 - pi.on("session_shutdown", (_event, ctx) => publishStatus(ctx, null));
716 -export const __modeTest = {
717 - frontmatterSplit,
718 - isValidModeId,
719 - latestModeState,
720 - loadModes,
721 - modePromptAddition,
722 - normalPromptAddition,
723 - parseModeMarkdown,
724 - parseModelRef,
725 - statusText,
727 -```
729 -- [ ] **Step 4: Run unit tests and verify pass**
731 -Run:
733 -```bash
734 -mise run test -- extensions/mode/__tests__/unit.test.ts
735 -```
737 -Expected: PASS.
739 -- [ ] **Step 5: Commit pure helpers**
741 -Run:
743 -```bash
744 -git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts
745 -git commit -m "feat(mode): parse mode files and render kernels"
746 -```
748 -Expected: commit succeeds.
750 -## Task 3: Runtime command tests
752 -**Files:**
754 -- Create: `extensions/mode/__tests__/harness.test.ts`
755 -- Modify: `extensions/mode/index.ts`
757 -- [ ] **Step 1: Write failing harness tests**
759 -Create `extensions/mode/__tests__/harness.test.ts`:
761 -```ts
762 -import { mkdirSync, writeFileSync } from "node:fs";
763 -import path from "node:path";
764 -import { afterEach, describe, expect, it } from "vitest";
765 -import { createTestSession, type TestSession } from "../../../test/harness";
767 -function extPath() {
768 - return path.resolve(import.meta.dirname, "../index.ts");
771 -function writeMode(t: TestSession, name: string, markdown: string): void {
772 - const dir = path.join(t.env.HOME!, ".pi", "agent", "modes");
773 - mkdirSync(dir, { recursive: true });
774 - writeFileSync(path.join(dir, `${name}.md`), markdown, "utf8");
777 -async function command(t: TestSession, args: string): Promise<void> {
778 - const cmd = t.session.extensionRunner.extensions[0].commands.get("mode");
779 - await cmd.handler(args, t.session.extensionRunner.createCommandContext());
782 -describe("mode harness", () => {
783 - let t: TestSession | undefined;
784 - afterEach(() => {
785 - t?.dispose();
786 - t = undefined;
787 - });
789 - it("loads in real Pi extension runtime", async () => {
790 - t = await createTestSession({ extensions: [extPath()] });
791 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
792 - expect(t.session.extensionRunner.extensions[0].commands.has("mode")).toBe(
793 - true,
794 - );
795 - });
797 - it("lists global modes", async () => {
798 - t = await createTestSession({ extensions: [extPath()] });
799 - writeMode(t, "plan", "---\ndescription: Read-only planning\n---\nbody");
800 - await command(t, "list");
801 - const note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
802 - expect(note).toContain("active: normal");
803 - expect(note).toContain("plan — Read-only planning");
804 - });
806 - it("switches mode and filters tools", async () => {
807 - t = await createTestSession({ extensions: [extPath()] });
808 - writeMode(
809 - t,
810 - "plan",
811 - "---\ntools: [read, grep, missing_tool]\nreminder: Stay read-only.\n---\n# Plan\n",
812 - );
813 - await command(t, "plan");
814 - const notes = t.events.uiCallsFor("notify").map((call) =>
815 - String(call.args[0])
816 - );
817 - expect(
818 - notes.some((note) => note.includes("unknown tool ignored: missing_tool")),
819 - ).toBe(true);
820 - expect(notes.some((note) => note.includes("mode plan: tools read, grep")))
821 - .toBe(true);
822 - });
824 - it("injects active mode prompt as system prompt", async () => {
825 - t = await createTestSession({ extensions: [extPath()] });
826 - writeMode(t, "plan", "---\nreminder: Stay read-only.\n---\n# Plan body\n");
827 - await command(t, "plan");
828 - const result = await t.session.extensionRunner.emitBeforeAgentStart(
829 - "hello",
830 - undefined,
831 - "BASE",
832 - {} as never,
833 - );
834 - expect(result?.systemPrompt).toContain("BASE\n\n# Plan body");
835 - expect(result?.systemPrompt).toContain("active_mode: plan");
836 - expect(result?.systemPrompt).toContain(
837 - "<mode_reminder>\nStay read-only.\n</mode_reminder>",
838 - );
839 - expect(result?.messages).toBeUndefined();
840 - });
842 - it("turns off and injects neutralizer", async () => {
843 - t = await createTestSession({ extensions: [extPath()] });
844 - writeMode(t, "plan", "# Plan body\n");
845 - await command(t, "plan");
846 - await command(t, "off");
847 - const result = await t.session.extensionRunner.emitBeforeAgentStart(
848 - "hello",
849 - undefined,
850 - "BASE",
851 - {} as never,
852 - );
853 - expect(result?.systemPrompt).toContain("active_mode: normal");
854 - expect(result?.systemPrompt).not.toContain("# Plan body");
855 - });
857 - it("restores mode from current branch", async () => {
858 - t = await createTestSession({ extensions: [extPath()] });
859 - writeMode(t, "plan", "# Plan body\n");
860 - await command(t, "plan");
861 - await t.session.extensionRunner.emit(
862 - { type: "session_start", reason: "reload" } as never,
863 - );
864 - const result = await t.session.extensionRunner.emitBeforeAgentStart(
865 - "hello",
866 - undefined,
867 - "BASE",
868 - {} as never,
869 - );
870 - expect(result?.systemPrompt).toContain("active_mode: plan");
871 - });
873 - it("adds compaction checkpoint", async () => {
874 - t = await createTestSession({ extensions: [extPath()] });
875 - writeMode(t, "plan", "# Plan body\n");
876 - await command(t, "plan");
877 - const msg = t.session.sessionManager.appendMessage({
878 - role: "user",
879 - content: "x",
880 - timestamp: Date.now(),
881 - });
882 - const compactionId = t.session.sessionManager.appendCompaction(
883 - "summary",
884 - msg,
885 - 123,
886 - );
887 - const compactionEntry = t.session.sessionManager.getEntry(compactionId)!;
888 - await t.session.extensionRunner.emit(
890 - type: "session_compact",
891 - compactionEntry,
892 - fromExtension: false,
893 - } as never,
894 - );
895 - const latest = t.session.sessionManager.getLeafEntry() as {
896 - type?: string;
897 - customType?: string;
898 - data?: Record<string, unknown>;
899 - };
900 - expect(latest.type).toBe("custom");
901 - expect(latest.customType).toBe("mode-state");
902 - expect(latest.data?.reason).toBe("compaction");
903 - expect(latest.data?.compactionEntryId).toBe(compactionId);
904 - });
905 -});
906 -```
908 -- [ ] **Step 2: Run harness test and verify pass**
910 -Run:
912 -```bash
913 -mise run test -- extensions/mode/__tests__/harness.test.ts
914 -```
916 -Expected: PASS.
918 -- [ ] **Step 3: Verify mode-state entries are branch custom entries**
920 -Run:
922 -```bash
923 -mise run test -- extensions/mode/__tests__/harness.test.ts -t "restores mode from current branch"
924 -```
926 -Expected: PASS.
928 -- [ ] **Step 4: Run harness test suite again**
930 -Run:
932 -```bash
933 -mise run test -- extensions/mode/__tests__/harness.test.ts
934 -```
936 -Expected: PASS.
938 -- [ ] **Step 5: Commit runtime tests**
940 -Run:
942 -```bash
943 -git add extensions/mode/index.ts extensions/mode/__tests__/harness.test.ts
944 -git commit -m "test(mode): cover runtime mode switching"
945 -```
947 -Expected: commit succeeds.
949 -## Task 4: Model/thinking restore coverage
951 -**Files:**
953 -- Modify: `extensions/mode/__tests__/unit.test.ts`
954 -- Modify: `extensions/mode/__tests__/harness.test.ts`
955 -- Modify: `extensions/mode/index.ts`
957 -- [ ] **Step 1: Add malformed model-ref unit test**
959 -Append to `extensions/mode/__tests__/unit.test.ts` inside the existing `describe`:
961 -```ts
962 -it("keeps malformed model refs unresolved", () => {
963 - expect(__modeTest.parseModelRef("/model")).toBeUndefined();
964 - expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
965 - expect(__modeTest.parseModelRef("provider/model/name")).toEqual({
966 - provider: "provider",
967 - modelId: "model/name",
968 - });
969 -});
970 -```
972 -- [ ] **Step 2: Add model/thinking warning harness test**
974 -Append to `extensions/mode/__tests__/harness.test.ts` inside the existing `describe`:
976 -```ts
977 -it("warns for unresolved model and still applies thinking", async () => {
978 - t = await createTestSession({ extensions: [extPath()] });
979 - writeMode(t, "deep", "---\nmodel: nope/missing\nthinking: high\n---\nbody");
980 - await command(t, "deep");
981 - const notes = t.events.uiCallsFor("notify").map((call) =>
982 - String(call.args[0])
983 - );
984 - expect(notes.some((note) => note.includes("model not found: nope/missing")))
985 - .toBe(true);
986 - const latestThinking = [...t.session.sessionManager.getBranch()].reverse()
987 - .find((entry: { type?: string }) =>
988 - entry.type === "thinking_level_change"
989 - ) as { thinkingLevel?: string } | undefined;
990 - expect(latestThinking?.thinkingLevel).toBe("high");
991 -});
992 -```
994 -- [ ] **Step 3: Run targeted tests**
996 -Run:
998 -```bash
999 -mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1000 -```
1002 -Expected: PASS.
1004 -- [ ] **Step 4: Commit model/thinking coverage**
1006 -Run:
1008 -```bash
1009 -git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1010 -git commit -m "test(mode): cover model and thinking application"
1011 -```
1013 -Expected: commit succeeds.
1015 -## Task 5: Static repo checks
1017 -**Files:**
1019 -- Modify: files flagged by formatter/linter only.
1021 -- [ ] **Step 1: Format**
1023 -Run:
1025 -```bash
1026 -mise run fmt
1027 -```
1029 -Expected: PASS.
1031 -- [ ] **Step 2: Run targeted tests**
1033 -Run:
1035 -```bash
1036 -mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1037 -```
1039 -Expected: PASS.
1041 -- [ ] **Step 3: Run extension static checks**
1043 -Run:
1045 -```bash
1046 -mise run check
1047 -```
1049 -Expected: PASS.
1051 -- [ ] **Step 4: Run full CI**
1053 -Run:
1055 -```bash
1056 -mise run ci
1057 -```
1059 -Expected: PASS.
1061 -If CI fails outside `extensions/mode/**` or `package-lock.json`, stop and report the unrelated dirty failure instead of editing unrelated files.
1063 -- [ ] **Step 5: Commit verification fixes**
1065 -If formatting changed files, run:
1067 -```bash
1068 -git add extensions/mode package-lock.json
1069 -git commit -m "chore(mode): satisfy repo checks"
1070 -```
1072 -Expected: commit succeeds or there are no formatting changes to commit.
1074 -## Task 6: Final implementation audit
1076 -**Files:**
1078 -- Read: `extensions/mode/V1.md`
1079 -- Read: `extensions/mode/index.ts`
1080 -- Read: `extensions/mode/__tests__/unit.test.ts`
1081 -- Read: `extensions/mode/__tests__/harness.test.ts`
1083 -- [ ] **Step 1: Map V1 requirements to code/tests**
1085 -Create this checklist in the worker notes and mark each item with file/function/test evidence:
1087 -```text
1088 -- global getAgentDir()/modes/*.md loading
1089 -- valid id filter
1090 -- YAML frontmatter validation
1091 -- mode schema fields
1092 -- active mode switch command
1093 -- off/normal/none aliases
1094 -- status/list/reload-config commands
1095 -- tool filtering and unknown warnings
1096 -- model parse/resolve/set warnings
1097 -- thinking application
1098 -- system prompt mode body/kernel/reminder injection
1099 -- normal neutralizer injection
1100 -- custom mode-state persistence
1101 -- getBranch restore
1102 -- missing restored mode fallback
1103 -- session_compact checkpoint
1104 -- status UI set/clear
1105 -- no project-local modes
1106 -- no custom prompt messages
1107 -```
1109 -- [ ] **Step 2: Fill any coverage gap with a test**
1111 -For each unchecked item, add one unit or harness test before changing implementation.
1113 -Use this command after each added test:
1115 -```bash
1116 -mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1117 -```
1119 -Expected: new test FAILS before implementation change, then PASSES after implementation change.
1121 -- [ ] **Step 3: Final CI**
1123 -Run:
1125 -```bash
1126 -mise run ci
1127 -```
1129 -Expected: PASS.
1131 -- [ ] **Step 4: Final commit**
1133 -Run:
1135 -```bash
1136 -git status --short
1137 -git add extensions/mode package-lock.json
1138 -git commit -m "feat(mode): add session-local modes"
1139 -```
1141 -Expected:
1143 -- Only mode extension files and `package-lock.json` are staged.
1144 -- Unrelated existing dirty files remain unstaged.
1145 -- Commit succeeds.
28 +See `git log -- extensions/mode` for the implementation commit history.

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 off` — turn mode off.
18 +- `/mode off` — turn mode off (notifies `no mode active` if no mode is active).
19 19 - `/mode normal` — alias for `/mode off`.
20 20 - `/mode none` — alias for `/mode off`.
21 21 - `/mode reload-config` — reload mode files and report count/warnings.
27 27 ## Mode files
29 -V1 loads only global mode files:
29 +Modes load from:
31 31 ```text
32 32 ~/.pi/agent/modes/*.md
40 40 ```md
42 42 description: Read-only planning
43 +accent: warning
43 44 model: openai/gpt-5.2-codex
44 45 thinking: high
45 46 tools: [read, grep, find, ls]
52 53 Do not implement.
56 +Frontmatter fields:
58 +| Field | Type | Effect |
59 +| ------------- | --------------------------------------------- | ------------------------------------------------------------ |
60 +| `description` | string | Shown by `/mode`, no runtime effect |
61 +| `accent` | theme color | Banner color when mode is active |
62 +| `model` | `provider/model-id` | Switched via `pi.setModel` on enter |
63 +| `thinking` | `off`/`minimal`/`low`/`medium`/`high`/`xhigh` | Switched via `pi.setThinkingLevel` |
64 +| `tools` | string array | Applied via `pi.setActiveTools` (unknown names warned) |
65 +| `reminder` | string | Wrapped in `<mode_reminder>` and injected into system prompt |
67 +`accent` must be one of: `accent`, `borderAccent`, `success`, `warning`, `error`, `muted`, `dim`.
55 69 ## Behavior
57 -Active mode appends its Markdown body and a generated mode kernel to the system prompt for each agent turn.
58 -Mode prompts are not stored as chat messages.
71 +Active mode:
60 -A mode may change active tools, model, and thinking level.
61 -Turning mode off does not restore prior tools, model, or thinking in V1.
73 +- Replaces the built-in header with a themed banner above the chat.
74 +- Appends its Markdown body and a generated `<mode_kernel>` to the system prompt for each agent turn.
75 +- May switch tools, model, and thinking level on enter.
63 -Mode state persists in session custom entries.
64 -Restore uses the current branch only.
65 -Compaction adds a mode checkpoint.
77 +`/mode off`:
79 +- Clears the custom header (built-in returns).
80 +- Removes mode body from the system prompt.
81 +- A `<mode_kernel>` with `active_mode: normal` stays injected while `neutralize = true`.
82 +- Tools, model, and thinking are **not** restored.
84 +Mode state is **in-memory only**.
85 +Each session starts clean — re-run `/mode <id>` after `session_start`.
87 +## SDK limitation
89 +`pi.setModel` and `pi.setThinkingLevel` write to the user's global default settings.
90 +Declaring `model:` or `thinking:` in a mode mutates user defaults for the duration the mode is applied.
91 +Use `/model` and `/thinking` to revert after `/mode off`.
67 93 ## V1 limits
69 -Project-local `.pi/modes/*.md` is deferred until Pi exposes a public project-trust API to extensions.
70 -Shortcuts, extension scoping, permission policy, tool globs, and baseline restore are not in V1.
95 +- Project-local `.pi/modes/*.md` deferred until Pi exposes a public project-trust API.
96 +- Cross-session mode persistence not implemented.
97 +- Tools/model/thinking not restored on `/mode off`.
98 +- Shortcuts, extension scoping, permission policy, tool globs not in V1.

extensions/mode/SPEC.md

Modified
3 3 # Mode Extension Spec
5 5 Split by version:
7 7 - `V1.md` — approved minimal implementation spec.
8 -- `V2.md` — approved provenance/status additions plus shortcut discussion.
8 +- `V2.md` — approved historical provenance markers; shortcuts discussion.
9 9 - `V3.md` — unapproved discussion bucket.
11 11 ## Current implementation target

extensions/mode/V1.md

Modified
10 10 Pi starts with **no active mode**.
11 11 This is normal mode.
13 +## State model
15 +Mode state is **in-memory only**.
16 +No session entries, no compaction checkpoints, no restore from branch.
18 +`session_start` resets to clean state.
19 +Users re-run `/mode <id>` per session.
20 +Compaction within a session does not lose mode (process memory persists).
22 +Persistence is rejected because:
24 +- kernel declares "active mode is runtime state, not conversation state"
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
27 +- cross-session mode continuity is rare in practice
13 29 ## Validation status
15 31 V1 is validated against current Pi extension APIs by prototypes.
19 35 - `before_agent_start` can append mode body/kernel to `systemPrompt` without persisting messages.
20 36 - `pi.getAllTools()` + `pi.setActiveTools()` can apply filtered tool lists.
21 37 - `pi.setModel()` and `pi.setThinkingLevel()` are public APIs.
22 -- `pi.appendEntry()` can persist mode state and compaction checkpoints.
23 -- `session_compact` exposes the compaction entry id.
24 -- `SessionManager.getBranch()` gives branch-correct state restoration.
25 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.
27 42 Trimmed from V1:
32 47 - Pi internal `parseFrontmatter` helper.
33 48 It is not package-exported.
34 49 V1 uses a declared `yaml` dependency for frontmatter parsing.
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.
54 +- Compaction checkpoint.
55 + Process memory persists across compaction within one session.
56 +- Branch restore on `session_start`.
57 + Memory-only state means users re-invoke mode per session.
36 59 ## Non-goals
45 68 - No tool metadata in the active block.
46 69 - No shortcut/keybinding support.
47 70 - No file watching.
71 +- No cross-session mode persistence.
72 +- No restore of previous tools/model/thinking on `/mode off`.
49 74 ## Mode files
72 97 ```ts
73 98 type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
100 +type AccentColor =
101 + | "accent"
102 + | "borderAccent"
103 + | "success"
104 + | "warning"
105 + | "error"
106 + | "muted"
107 + | "dim";
75 109 type Mode = {
76 110 id: string; // file stem
77 111 description?: string; // shown by /mode, no runtime behavior
112 + accent?: AccentColor; // theme color for header banner
78 113 model?: string; // provider/model-id, split at first slash
79 114 thinking?: ThinkingLevel;
80 115 reminder?: string; // short active-block reminder
86 121 Validation:
88 123 - `description`, `model`, and `reminder` must be strings when present.
124 +- `accent` must be one of the `AccentColor` theme slots.
89 125 - `thinking` must be a valid `ThinkingLevel` when present.
90 126 - `tools` must be an array of strings when present.
91 127 - Unknown frontmatter keys are ignored.
98 134 description: Read-only planning
135 +accent: warning
99 136 model: openai/gpt-5.2-codex
100 137 thinking: high
101 138 tools: [read, grep, find, ls]
107 144 Long system-prompt instructions here.
110 -## Mode state
112 -Persist mode changes as custom entries:
114 -```ts
115 -type ModeStateEntry = {
116 - schemaVersion: 1;
117 - activeMode: string | null;
118 - neutralize: boolean;
119 - reason: "switch" | "off" | "compaction";
120 - model?: string;
121 - provider?: string;
122 - compactionEntryId?: string;
123 -};
124 -```
126 -Custom type:
128 -```text
129 -mode-state
130 -```
132 -Rules:
134 -- Use `pi.appendEntry("mode-state", data)`.
135 -- Restore from `ctx.sessionManager.getBranch()`, never `getEntries()`.
136 -- Last valid `mode-state` entry on the current branch wins.
137 -- Ignore malformed future/old entries.
139 147 ## Model/thinking/tool application
141 149 On `/mode <id>`:
151 159 9. If resolved, call `await pi.setModel(model)`.
152 160 10. If `pi.setModel()` returns `false`, warn and keep current model.
153 161 11. If `thinking` exists, call `pi.setThinkingLevel(thinking)`.
154 -12. Persist a `mode-state` entry with `reason: "switch"`.
155 -13. Update status UI.
162 +12. Install themed header via `ctx.ui.setHeader(buildHeader(mode))`.
157 164 `tools` absent or empty means the mode does not alter active tools.
159 166 Switching from mode A to mode B does not restore baseline first.
160 167 B only applies fields it declares.
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.
162 173 ## Normal/off behavior
164 175 Commands:
172 183 Behavior:
174 -- Set `activeModeId = null`.
175 -- Set `neutralize = true` if an active mode was on before turning off.
176 -- Persist a `mode-state` entry with `activeMode: null`, `neutralize`, and `reason: "off"`.
177 -- Clear mode status UI.
178 -- Stop appending mode body to system prompt.
179 -- Inject the normal neutralizer block while `neutralize` is true.
180 -- Do **not** restore previous tools/model/thinking in V1.
185 +- If `activeModeId` is `null` (no mode was active), notify `no mode active` and return.
186 +- Otherwise:
187 + - Set in-memory `activeModeId = null`.
188 + - Set in-memory `neutralize = true`.
189 + - Clear the custom header via `ctx.ui.setHeader(undefined)` so the built-in header returns.
182 -Fresh normal sessions with no prior mode entry get no mode block.
191 +Tools/model/thinking are **not** restored.
192 +They keep whatever the last mode or manual change set them to.
184 -Baseline restore/update is deferred.
194 +Fresh normal sessions with no prior mode get no mode block.
195 +The kernel block is only injected after `/mode off` (when `neutralize = true`).
186 197 ## Prompt injection
234 245 /mode status same as /mode
235 246 /mode list show available modes
236 247 /mode <id> switch active mode
237 -/mode off turn mode off
248 +/mode off turn mode off (notify "no mode active" if already off)
238 249 /mode normal alias for /mode off
239 250 /mode none alias for /mode off
240 251 /mode reload-config reload mode files and report count/warnings
253 -When a mode is active, set status key `mode` to:
264 +Active mode replaces the built-in header (logo/instructions) with a themed banner above the chat:
255 266 ```text
256 -MODE plan
267 +▎ MODE: plan
268 + Read-only planning
269 + tools: read, grep, find, ls · model: openai/gpt-5.2-codex · thinking: high
259 -Normal mode clears status key `mode`.
272 +- `accent` frontmatter controls the banner color via `theme.fg(accent, ...)`.
273 +- Default accent is `accent` (theme default).
274 +- Description line omitted when `description` is absent.
275 +- Meta line (`tools · model · thinking`) omitted when no metadata is declared.
276 +- `accent` defaults; if absent, the banner uses theme accent.
261 -## Persistence and restore
278 +`ctx.ui.setHeader(undefined)` clears the custom header and restores the built-in (logo + onboarding) on `/mode off` and `session_start`.
263 -Restore on `session_start` for:
265 -- startup
266 -- reload
267 -- resume
268 -- fork/clone/new session flows where the branch contains mode entries
270 -Restoration algorithm:
272 -1. Reload mode files.
273 -2. Read `ctx.sessionManager.getBranch()`.
274 -3. Find the last valid `mode-state` custom entry.
275 -4. If none, set normal mode with `neutralize = false`.
276 -5. If `activeMode` is `null`, set normal mode and restore `neutralize` from entry.
277 -6. If `activeMode` exists and mode file exists, set in-memory state and reapply mode tools/model/thinking.
278 -7. If `activeMode` exists but mode file no longer exists, warn, fall back to normal mode, and persist `activeMode: null`, `neutralize: true`, `reason: "off"`.
279 -8. Update status UI.
280 +The header is the only persistent UI signal of mode state.
281 +`notify` is reserved for warnings (unknown tool, model not found, malformed ref, parse error, unknown mode id).
281 283 ## Compaction
283 -Compaction is not source of truth for active mode.
285 +No checkpoint.
286 +The in-memory `state.activeModeId` survives `session_compact` automatically (same process).
287 +`before_agent_start` keeps injecting the current mode body/kernel.
285 -After compaction, extension state must still inject exact current mode body/kernel.
286 -Summaries may mention historical modes, but current mode comes from extension state.
289 +## Session lifecycle
288 -On `session_compact`, append a checkpoint:
291 +`session_start`:
290 -```ts
291 -type ModeCheckpointEntry = ModeStateEntry & {
292 - reason: "compaction";
293 - compactionEntryId: string;
294 -};
295 -```
293 +1. Reload mode files.
294 +2. Reset in-memory state: `activeModeId = null`, `neutralize = false`.
295 +3. Clear custom header.
297 -Rules:
297 +Users must re-run `/mode <id>` after each `session_start`.
299 -- Checkpoint uses the current in-memory `activeModeId` and `neutralize`.
300 -- Include `provider/model` from `ctx.model` when available.
301 -- Do not customize compaction summaries in V1.
299 +`session_shutdown`: clear custom header.
303 301 ## Extension/resource model

extensions/mode/V2.md

Modified
91 91 ## Status icon/color
93 -Approved.
93 +Implemented in V1 as `accent` (theme color slot).
94 +See V1 spec for schema and rules.
95 -Additional optional frontmatter:
97 -```yaml
98 -icon: "🧭"
99 -color: "warning"
100 -```
102 -Rules:
104 -- `icon` is status eye candy only.
105 -- `color` controls status color only.
106 -- Validate both defensively.
107 -- Strip control/ANSI.
108 -- Fallback to plain status on invalid values.
109 -- Normal mode still shows no status item.
111 -Example status:
113 -```text
114 -🧭 plan
115 -```
96 +V2 may add an optional `icon` frontmatter for status eye candy if useful.
97 +Not approved.
117 99 ## Shortcuts

extensions/mode/__tests__/coverage.test.ts

Modified
4 4 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5 5 import { tmpdir } from "node:os";
6 6 import path from "node:path";
7 7 import { describe, expect, it } from "vitest";
8 8 import modeExtension, { __modeTest } from "../index.ts";
10 -const custom = (data: unknown) => ({
11 - type: "custom",
12 - customType: "mode-state",
13 - data,
14 -});
16 10 type Fake = ReturnType<typeof fakeRuntime>;
18 12 function fakeRuntime() {
18 12 { handler: (args: string, ctx: any) => Promise<void> }
20 14 const events = new Map<string, (event: any, ctx: any) => unknown>();
21 - const entries: Array<{ type: string; customType: string; data: unknown }> =
22 - [];
23 15 const notes: Array<[string, string]> = [];
24 - const statuses: Array<[string, string | undefined]> = [];
16 + const headers: unknown[] = [];
25 17 const activeTools: string[][] = [];
26 18 let setModelResult = true;
27 19 let modelFindResult: unknown;
30 22 hasUI: true,
31 23 model: { provider: "prov", id: "model" },
32 24 modelRegistry: { find: () => modelFindResult },
33 - sessionManager: { getBranch: () => entries },
25 + sessionManager: { getBranch: () => [] },
34 26 ui: {
35 27 notify: (message: string, severity: string) =>
36 28 notes.push([message, severity]),
37 - setStatus: (key: string, value: string | undefined) =>
38 - statuses.push([key, value]),
29 + setHeader: (...args: unknown[]) => headers.push(args),
41 32 modeExtension({
42 - appendEntry: (type: string, data: unknown) =>
43 - entries.push({ type: "custom", customType: type, data }),
44 33 events: { emit: () => undefined },
45 34 getAllTools: () => [{ name: "read" }, { name: "grep" }],
46 35 on: (name: string, handler: (event: any, ctx: any) => unknown) =>
59 48 activeTools,
60 49 command: (args: string) => commands.get("mode")?.handler(args, ctx),
62 - entries,
63 51 events,
52 + headers,
53 + modelFindResult: () => modelFindResult,
64 54 notes,
65 55 setModelFindResult: (model: unknown) => {
66 56 modelFindResult = model;
68 58 setModelResult: (result: boolean) => {
69 59 setModelResult = result;
71 - statuses,
72 61 thinking: () => thinking,
120 109 expect(
121 110 __modeTest.parseModeMarkdown(
122 111 "plan",
123 - "---\ndescription: d\nmodel: p/m\nreminder: r\nthinking: high\ntools: [read]\n---\nbody",
112 + "---\ndescription: d\naccent: warning\nmodel: p/m\nreminder: r\nthinking: high\ntools: [read]\n---\nbody",
125 114 ).toEqual({
126 115 id: "plan",
127 116 description: "d",
117 + accent: "warning",
128 118 model: "p/m",
129 119 reminder: "r",
130 120 thinking: "high",
147 137 expect(() =>
148 138 __modeTest.parseModeMarkdown("bad", "---\ndescription: 1\n---\n"),
149 139 ).toThrow("description must be a string");
140 + expect(() =>
141 + __modeTest.parseModeMarkdown("bad", "---\naccent: nope\n---\n"),
142 + ).toThrow("accent must be one of");
143 + expect(() =>
144 + __modeTest.parseModeMarkdown("bad", "---\naccent: 1\n---\n"),
145 + ).toThrow("accent must be one of");
150 146 expect(() =>
151 147 __modeTest.parseModeMarkdown("bad", "---\nmodel: 1\n---\n"),
152 148 ).toThrow("model must be a string");
185 181 __modeTest.modePromptAddition({ id: "plan", body: "body\n" }),
186 182 ).not.toContain("mode_reminder");
187 183 expect(__modeTest.normalPromptAddition()).toContain("active_mode: normal");
188 - expect(
189 - __modeTest.latestModeState([
190 - { type: "message", customType: "mode-state", data: {} },
191 - { type: "custom", customType: "other", data: {} },
192 - custom({ broken: true }),
193 - custom({
194 - schemaVersion: 1,
195 - activeMode: "plan",
196 - neutralize: false,
197 - reason: "switch",
198 - }),
199 - ]),
200 - ).toEqual({
201 - schemaVersion: 1,
202 - activeMode: "plan",
203 - neutralize: false,
204 - reason: "switch",
184 + expect(__modeTest.buildHeader(null)).toBeUndefined();
185 + const factory = __modeTest.buildHeader({
186 + id: "plan",
187 + body: "body",
188 + description: "d",
189 + accent: "warning",
190 + tools: ["read"],
191 + model: "openai/gpt",
192 + thinking: "high",
206 - expect(
207 - __modeTest.latestModeState([
208 - { type: "custom", customType: "other", data: {} },
209 - ]),
210 - ).toBeUndefined();
211 - expect(
212 - __modeTest.latestModeState([
213 - custom(null),
214 - custom({
215 - schemaVersion: 2,
216 - activeMode: "plan",
217 - neutralize: false,
218 - reason: "switch",
219 - }),
220 - ]),
221 - ).toBeUndefined();
222 - expect(
223 - __modeTest.latestModeState([
224 - custom({
225 - schemaVersion: 1,
226 - activeMode: null,
227 - neutralize: true,
228 - reason: "compaction",
229 - }),
230 - ]),
231 - ).toEqual({
232 - schemaVersion: 1,
233 - activeMode: null,
234 - neutralize: true,
235 - reason: "compaction",
236 - });
237 - expect(__modeTest.statusText("plan")).toBe("MODE plan");
238 - expect(__modeTest.statusText(null)).toBeUndefined();
194 + expect(factory).toBeDefined();
195 + if (!factory) throw new Error("expected factory");
196 + const identity = (text: string) => text;
197 + const passthrough = (_color: string, text: string) => text;
198 + const lines = factory(
199 + {} as never,
200 + { fg: passthrough, bold: identity } as never,
201 + ).render(120);
202 + const flat = lines.join("\n");
203 + expect(flat).toContain("MODE: plan");
204 + expect(flat).toContain("d");
205 + expect(flat).toContain("tools: read");
206 + expect(flat).toContain("model: openai/gpt");
207 + expect(flat).toContain("thinking: high");
240 209 const agentDir = mkdtempSync(path.join(tmpdir(), "mode-cov-"));
275 244 f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
276 245 ).toBeUndefined();
277 246 await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
247 + expect(f.headers.at(-1)).toEqual([undefined]);
278 248 await f.command("reload-config");
279 249 expect(f.notes.at(-1)).toEqual([
280 250 "mode config: 0 mode(s), 0 warning(s)",
283 253 await f.command("");
284 254 expect(f.notes.at(-1)?.[0]).toContain("modes: none");
285 255 await f.command("off");
286 - expect(f.entries.at(-1)?.data).toMatchObject({
287 - activeMode: null,
288 - neutralize: false,
289 - reason: "off",
290 - provider: "prov",
291 - model: "model",
292 - });
256 + expect(f.notes.at(-1)).toEqual(["no mode active", "info"]);
293 257 writeMode(home, "plain", "body");
294 258 writeMode(
296 260 "plan",
297 - "---\ndescription: d\ntools: [read, grep, missing]\nreminder: r\n---\nbody",
261 + "---\ndescription: d\naccent: warning\ntools: [read, grep, missing]\nreminder: r\n---\nbody",
299 263 writeMode(home, "bad id", "bad");
300 264 await f.command("");
311 275 expect(f.notes.at(-1)).toEqual(["unknown mode: unknown", "warning"]);
312 276 await f.command("plan");
313 277 expect(f.activeTools.at(-1)).toEqual(["read", "grep"]);
314 - expect(f.statuses.at(-1)).toEqual(["mode", "MODE plan"]);
278 + expect(typeof f.headers.at(-1)?.[0]).toBe("function");
315 279 expect(
316 280 f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
317 281 ).toEqual({ systemPrompt: expect.stringContaining("active_mode: plan") });
318 282 await f.command("normal");
319 - expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
283 + expect(f.headers.at(-1)).toEqual([undefined]);
320 284 expect(
321 285 f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
322 286 ).toEqual({
325 289 await f.command("plan");
326 290 await f.command("none");
327 - expect(f.entries.at(-1)?.data).toMatchObject({
328 - activeMode: null,
329 - neutralize: true,
330 - reason: "off",
331 - });
291 + expect(f.headers.at(-1)).toEqual([undefined]);
335 - it("covers model, restore, compaction, shutdown", async () => {
295 + it("covers model and shutdown paths", async () => {
336 296 await withHome(async (home) => {
337 297 const f = fakeRuntime();
298 + await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
299 + f.headers.length = 0;
338 300 writeMode(home, "badref", "---\nmodel: bad\n---\nbody");
339 301 await f.command("badref");
340 - expect(f.notes.at(-2)).toEqual([
302 + expect(f.notes.at(-1)).toEqual([
341 303 "mode badref: model not found: bad",
342 304 "warning",
352 314 f.setModelResult(false);
353 315 writeMode(home, "blocked", "---\nmodel: openai/gpt\n---\nbody");
354 316 await f.command("blocked");
355 - expect(f.notes.at(-2)).toEqual([
317 + expect(f.notes.at(-1)).toEqual([
356 318 "mode blocked: model unavailable: openai/gpt",
357 319 "warning",
365 327 await f.command("deep");
366 328 await f.events.get("session_start")?.({ reason: "reload" }, f.ctx);
367 - expect(f.statuses.at(-1)).toEqual(["mode", "MODE deep"]);
368 - const gone = writeMode(home, "gone", "body");
369 - await f.command("gone");
370 - rmSync(gone);
371 - await f.events.get("session_start")?.({ reason: "reload" }, f.ctx);
372 - expect(f.entries.at(-1)?.data).toMatchObject({
373 - activeMode: null,
374 - neutralize: true,
375 - reason: "off",
376 - });
377 - f.events.get("session_compact")?.(
378 - { compactionEntry: { id: "c1" } },
379 - f.ctx,
380 - );
381 - expect(f.entries.at(-1)?.data).toMatchObject({
382 - reason: "compaction",
383 - compactionEntryId: "c1",
384 - });
385 - f.events.get("session_shutdown")?.({}, f.ctx);
386 - expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
329 + expect(f.headers.at(-1)).toEqual([undefined]);
330 + await f.events.get("session_shutdown")?.({}, f.ctx);
331 + expect(f.headers.at(-1)).toEqual([undefined]);
390 - it("covers no-ui direct events", () => {
335 + it("covers no-ui session handlers", async () => {
391 336 const f: Fake = fakeRuntime();
337 + await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
392 338 f.ctx.hasUI = false;
393 339 f.ctx.model = undefined;
394 - f.events.get("session_shutdown")?.({}, f.ctx);
395 - f.events.get("session_compact")?.({ compactionEntry: { id: "c1" } }, f.ctx);
396 - expect(f.entries.at(-1)?.data).toEqual({
397 - schemaVersion: 1,
398 - activeMode: null,
399 - neutralize: false,
400 - reason: "compaction",
401 - compactionEntryId: "c1",
402 - });
340 + await f.events.get("session_shutdown")?.({}, f.ctx);
341 + expect(f.headers.at(-1)).toEqual([undefined]);

extensions/mode/__tests__/harness-full.test.ts

Deleted
deleted file mode 100644
1 -import { mkdirSync, unlinkSync, writeFileSync } from "node:fs";
2 -import path from "node:path";
3 -import { afterEach, describe, expect, it } from "vitest";
4 -import { createTestSession, type TestSession } from "../../../test/harness";
6 -function extPath() {
7 - return path.resolve(import.meta.dirname, "../index.ts");
8 -}
10 -function writeMode(t: TestSession, name: string, markdown: string): string {
11 - const home = t.env.HOME;
12 - if (!home) throw new Error("missing HOME");
13 - const dir = path.join(home, ".pi", "agent", "modes");
14 - mkdirSync(dir, { recursive: true });
15 - const file = path.join(dir, `${name}.md`);
16 - writeFileSync(file, markdown, "utf8");
17 - return file;
20 -async function command(t: TestSession, args: string): Promise<void> {
21 - const cmd = t.session.extensionRunner.extensions[0].commands.get("mode");
22 - await cmd.handler(args, t.session.extensionRunner.createCommandContext());
25 -describe("mode harness", () => {
26 - let t: TestSession | undefined;
27 - afterEach(() => {
28 - t?.dispose();
29 - t = undefined;
30 - });
32 - it("loads in real Pi extension runtime", async () => {
33 - t = await createTestSession({ extensions: [extPath()] });
34 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
35 - expect(t.session.extensionRunner.extensions[0].commands.has("mode")).toBe(
36 - true,
37 - );
38 - });
40 - it("lists global modes", async () => {
41 - t = await createTestSession({ extensions: [extPath()] });
42 - writeMode(t, "plan", "---\ndescription: Read-only planning\n---\nbody");
43 - writeMode(t, "plain", "body");
44 - await command(t, "list");
45 - let note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
46 - expect(note).toContain("active: normal");
47 - expect(note).toContain("plan — Read-only planning");
48 - expect(note).toContain("plain");
49 - await command(t, "");
50 - note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
51 - expect(note).toContain("active: normal");
52 - await command(t, "status");
53 - note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
54 - expect(note).toContain("active: normal");
55 - });
57 - it("switches mode and filters tools", async () => {
58 - t = await createTestSession({ extensions: [extPath()] });
59 - writeMode(
60 - t,
61 - "plan",
62 - "---\ntools: [read, grep, missing_tool]\nreminder: Stay read-only.\n---\n# Plan\n",
63 - );
64 - await command(t, "plan");
65 - const notes = t.events
66 - .uiCallsFor("notify")
67 - .map((call) => String(call.args[0]));
68 - expect(
69 - notes.some((note) => note.includes("unknown tool ignored: missing_tool")),
70 - ).toBe(true);
71 - expect(
72 - notes.some((note) => note.includes("mode plan: tools read, grep")),
73 - ).toBe(true);
74 - });
76 - it("injects active mode prompt as system prompt", async () => {
77 - t = await createTestSession({ extensions: [extPath()] });
78 - writeMode(t, "plan", "---\nreminder: Stay read-only.\n---\n# Plan body\n");
79 - await command(t, "plan");
80 - const result = await t.session.extensionRunner.emitBeforeAgentStart(
81 - "hello",
82 - undefined,
83 - "BASE",
84 - {} as never,
85 - );
86 - expect(result?.systemPrompt).toContain("BASE\n\n# Plan body");
87 - expect(result?.systemPrompt).toContain("active_mode: plan");
88 - expect(result?.systemPrompt).toContain(
89 - "<mode_reminder>\nStay read-only.\n</mode_reminder>",
90 - );
91 - expect(result?.messages).toBeUndefined();
92 - });
94 - it("turns off and injects neutralizer", async () => {
95 - t = await createTestSession({ extensions: [extPath()] });
96 - let result = await t.session.extensionRunner.emitBeforeAgentStart(
97 - "hello",
98 - undefined,
99 - "BASE",
100 - {} as never,
101 - );
102 - expect(result).toBeUndefined();
103 - writeMode(t, "plan", "# Plan body\n");
104 - await command(t, "plan");
105 - await command(t, "off");
106 - result = await t.session.extensionRunner.emitBeforeAgentStart(
107 - "hello",
108 - undefined,
109 - "BASE",
110 - {} as never,
111 - );
112 - expect(result?.systemPrompt).toContain("active_mode: normal");
113 - expect(result?.systemPrompt).not.toContain("# Plan body");
114 - });
116 - it("restores mode from current branch", async () => {
117 - t = await createTestSession({ extensions: [extPath()] });
118 - writeMode(t, "plan", "# Plan body\n");
119 - await command(t, "plan");
120 - await t.session.extensionRunner.emit({
121 - type: "session_start",
122 - reason: "reload",
123 - } as never);
124 - const result = await t.session.extensionRunner.emitBeforeAgentStart(
125 - "hello",
126 - undefined,
127 - "BASE",
128 - {} as never,
129 - );
130 - expect(result?.systemPrompt).toContain("active_mode: plan");
131 - });
133 - it("adds compaction checkpoint", async () => {
134 - t = await createTestSession({ extensions: [extPath()] });
135 - writeMode(t, "plan", "# Plan body\n");
136 - await command(t, "plan");
137 - const msg = t.session.sessionManager.appendMessage({
138 - role: "user",
139 - content: "x",
140 - timestamp: Date.now(),
141 - });
142 - const compactionId = t.session.sessionManager.appendCompaction(
143 - "summary",
144 - msg,
145 - 123,
146 - );
147 - const compactionEntry = t.session.sessionManager.getEntry(compactionId);
148 - expect(compactionEntry).toBeDefined();
149 - await t.session.extensionRunner.emit({
150 - type: "session_compact",
151 - compactionEntry,
152 - fromExtension: false,
153 - } as never);
154 - const latest = t.session.sessionManager.getLeafEntry() as {
155 - type?: string;
156 - customType?: string;
157 - data?: Record<string, unknown>;
158 - };
159 - expect(latest.type).toBe("custom");
160 - expect(latest.customType).toBe("mode-state");
161 - expect(latest.data?.reason).toBe("compaction");
162 - expect(latest.data?.compactionEntryId).toBe(compactionId);
163 - });
165 - it("warns for unresolved model and still applies thinking", async () => {
166 - t = await createTestSession({ extensions: [extPath()] });
167 - await t.session.setModel(
168 - t.session.modelRegistry.find("openai", "gpt-5.2-codex"),
169 - );
170 - writeMode(t, "deep", "---\nmodel: nope/missing\nthinking: high\n---\nbody");
171 - await command(t, "deep");
172 - writeMode(t, "badref", "---\nmodel: malformed\n---\nbody");
173 - await command(t, "badref");
174 - const notes = t.events
175 - .uiCallsFor("notify")
176 - .map((call) => String(call.args[0]));
177 - expect(
178 - notes.some((note) => note.includes("model not found: nope/missing")),
179 - ).toBe(true);
180 - expect(
181 - notes.some((note) => note.includes("model not found: malformed")),
182 - ).toBe(true);
183 - const latestThinking = [...t.session.sessionManager.getBranch()]
184 - .reverse()
185 - .find(
186 - (entry: { type?: string }) => entry.type === "thinking_level_change",
187 - ) as { thinkingLevel?: string } | undefined;
188 - expect(latestThinking?.thinkingLevel).toBe("high");
189 - });
191 - it("sets resolved model and thinking", async () => {
192 - t = await createTestSession({ extensions: [extPath()] });
193 - writeMode(
194 - t,
195 - "deep",
196 - "---\nmodel: openai/gpt-5.2-codex\nthinking: high\n---\nbody",
197 - );
198 - await command(t, "deep");
199 - expect(t.session.model?.id).toBe("gpt-5.2-codex");
200 - expect(t.session.thinkingLevel).toBe("high");
201 - });
203 - it("warns when resolved model cannot be applied", async () => {
204 - t = await createTestSession({ extensions: [extPath()] });
205 - t.session.extensionRunner.runtime.setModel = async () => false;
206 - writeMode(t, "deep", "---\nmodel: openai/gpt-5.2-codex\n---\nbody");
207 - await command(t, "deep");
208 - const notes = t.events
209 - .uiCallsFor("notify")
210 - .map((call) => String(call.args[0]));
211 - expect(
212 - notes.some((note) =>
213 - note.includes("model unavailable: openai/gpt-5.2-codex"),
214 - ),
215 - ).toBe(true);
216 - });
218 - it("persists switch and off states for aliases", async () => {
219 - t = await createTestSession({ extensions: [extPath()] });
220 - await command(t, "off");
221 - let latest = t.session.sessionManager.getLeafEntry() as {
222 - customType?: string;
223 - data?: Record<string, unknown>;
224 - };
225 - expect(latest.data).toMatchObject({
226 - activeMode: null,
227 - neutralize: false,
228 - reason: "off",
229 - });
230 - writeMode(t, "plan", "# Plan body\n");
231 - await command(t, "plan");
232 - latest = t.session.sessionManager.getLeafEntry() as {
233 - customType?: string;
234 - data?: Record<string, unknown>;
235 - };
236 - expect(latest.customType).toBe("mode-state");
237 - expect(latest.data).toMatchObject({
238 - activeMode: "plan",
239 - neutralize: false,
240 - reason: "switch",
241 - });
243 - await command(t, "normal");
244 - latest = t.session.sessionManager.getLeafEntry() as {
245 - customType?: string;
246 - data?: Record<string, unknown>;
247 - };
248 - expect(latest.data).toMatchObject({
249 - activeMode: null,
250 - neutralize: true,
251 - reason: "off",
252 - });
253 - expect(t.events.uiCallsFor("setStatus").at(-1)?.args).toEqual([
254 - "mode",
255 - undefined,
256 - ]);
258 - await command(t, "plan");
259 - await command(t, "none");
260 - latest = t.session.sessionManager.getLeafEntry() as {
261 - data?: Record<string, unknown>;
262 - };
263 - expect(latest.data).toMatchObject({ activeMode: null, neutralize: true });
264 - });
266 - it("reload-config reports counts and warnings", async () => {
267 - t = await createTestSession({ extensions: [extPath()] });
268 - await command(t, "reload-config");
269 - expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
270 - "mode config: 0 mode(s), 0 warning(s)",
271 - "info",
272 - ]);
273 - writeMode(t, "plan", "# Plan\n");
274 - writeMode(t, "bad id", "# Bad\n");
275 - await command(t, "reload-config");
276 - const calls = t.events.uiCallsFor("notify");
277 - expect(
278 - calls.some((call) => String(call.args[0]).includes("bad id.md")),
279 - ).toBe(true);
280 - expect(calls.at(-1)?.args).toEqual([
281 - "mode config: 1 mode(s), 1 warning(s)",
282 - "warning",
283 - ]);
284 - });
286 - it("falls back to neutral normal when restored mode file is missing", async () => {
287 - t = await createTestSession({ extensions: [extPath()] });
288 - const file = writeMode(t, "plan", "# Plan body\n");
289 - await command(t, "plan");
290 - unlinkSync(file);
291 - await t.session.extensionRunner.emit({
292 - type: "session_start",
293 - reason: "reload",
294 - } as never);
295 - const result = await t.session.extensionRunner.emitBeforeAgentStart(
296 - "hello",
297 - undefined,
298 - "BASE",
299 - {} as never,
300 - );
301 - expect(result?.systemPrompt).toContain("active_mode: normal");
302 - expect(result?.systemPrompt).not.toContain("# Plan body");
303 - const latest = t.session.sessionManager.getLeafEntry() as {
304 - customType?: string;
305 - data?: Record<string, unknown>;
306 - };
307 - expect(latest.customType).toBe("mode-state");
308 - expect(latest.data).toMatchObject({
309 - activeMode: null,
310 - neutralize: true,
311 - reason: "off",
312 - });
313 - });
314 -});

extensions/mode/__tests__/harness.test.ts

Modified
7 7 return path.resolve(import.meta.dirname, "../index.ts");
10 -function writeMode(t: TestSession, name: string, markdown: string): void {
10 +function writeMode(t: TestSession, name: string, markdown: string): string {
11 11 const home = t.env.HOME;
12 12 if (!home) throw new Error("missing HOME");
13 13 const dir = path.join(home, ".pi", "agent", "modes");
14 14 mkdirSync(dir, { recursive: true });
15 - writeFileSync(path.join(dir, `${name}.md`), markdown, "utf8");
15 + const file = path.join(dir, `${name}.md`);
16 + writeFileSync(file, markdown, "utf8");
17 + return file;
18 20 async function command(t: TestSession, args: string): Promise<void> {
20 22 await cmd.handler(args, t.session.extensionRunner.createCommandContext());
23 -// Full command matrix lives in harness-full.test.ts; this shard keeps real runtime smoke under the per-file budget.
24 -describe("mode harness smoke", () => {
25 +describe("mode harness", () => {
25 26 let t: TestSession | undefined;
26 27 afterEach(() => {
27 28 t?.dispose();
39 - it("switches mode and injects active mode prompt", async () => {
40 + it("lists global modes", async () => {
41 + t = await createTestSession({ extensions: [extPath()] });
42 + writeMode(t, "plan", "---\ndescription: Read-only planning\n---\nbody");
43 + writeMode(t, "plain", "body");
44 + await command(t, "list");
45 + let note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
46 + expect(note).toContain("active: normal");
47 + expect(note).toContain("plan — Read-only planning");
48 + expect(note).toContain("plain");
49 + await command(t, "");
50 + note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
51 + expect(note).toContain("active: normal");
52 + await command(t, "status");
53 + note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
54 + expect(note).toContain("active: normal");
55 + });
57 + it("switches mode and filters tools", async () => {
58 + t = await createTestSession({ extensions: [extPath()] });
59 + writeMode(
60 + t,
61 + "plan",
62 + "---\ntools: [read, grep, missing_tool]\nreminder: Stay read-only.\n---\n# Plan\n",
63 + );
64 + await command(t, "plan");
65 + const notes = t.events
66 + .uiCallsFor("notify")
67 + .map((call) => String(call.args[0]));
68 + expect(
69 + notes.some((note) => note.includes("unknown tool ignored: missing_tool")),
70 + ).toBe(true);
71 + expect(
72 + notes.some((note) => note.includes("mode plan: tools read, grep")),
73 + ).toBe(true);
74 + });
76 + it("injects active mode prompt as system prompt", async () => {
40 77 t = await createTestSession({ extensions: [extPath()] });
41 78 writeMode(t, "plan", "---\nreminder: Stay read-only.\n---\n# Plan body\n");
42 79 await command(t, "plan");
51 88 expect(result?.systemPrompt).toContain(
52 89 "<mode_reminder>\nStay read-only.\n</mode_reminder>",
91 + expect(result?.messages).toBeUndefined();
92 + });
94 + it("turns off and injects neutralizer", async () => {
95 + t = await createTestSession({ extensions: [extPath()] });
96 + let result = await t.session.extensionRunner.emitBeforeAgentStart(
97 + "hello",
98 + undefined,
99 + "BASE",
100 + {} as never,
101 + );
102 + expect(result).toBeUndefined();
103 + writeMode(t, "plan", "# Plan body\n");
104 + await command(t, "plan");
105 + await command(t, "off");
106 + result = await t.session.extensionRunner.emitBeforeAgentStart(
107 + "hello",
108 + undefined,
109 + "BASE",
110 + {} as never,
111 + );
112 + expect(result?.systemPrompt).toContain("active_mode: normal");
113 + expect(result?.systemPrompt).not.toContain("# Plan body");
114 + });
116 + it("clears header on off and does not persist state", async () => {
117 + t = await createTestSession({ extensions: [extPath()] });
118 + writeMode(t, "plan", "# Plan body\n");
119 + await command(t, "plan");
120 + const headers = t.events.uiCallsFor("setHeader");
121 + expect(headers.at(-1)?.args[0]).toBeTypeOf("function");
122 + await command(t, "off");
123 + expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
124 + const branches = t.session.sessionManager.getBranch() as Array<{
125 + customType?: string;
126 + }>;
127 + expect(branches.some((entry) => entry.customType === "mode-state")).toBe(
128 + false,
129 + );
130 + });
132 + it("off when no mode is active notifies", async () => {
133 + t = await createTestSession({ extensions: [extPath()] });
134 + await command(t, "off");
135 + const notes = t.events
136 + .uiCallsFor("notify")
137 + .map((call) => String(call.args[0]));
138 + expect(notes).toContain("no mode active");
139 + expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
140 + });
142 + it("session_start resets active mode and clears header", async () => {
143 + t = await createTestSession({ extensions: [extPath()] });
144 + writeMode(t, "plan", "# Plan body\n");
145 + await command(t, "plan");
146 + await t.session.extensionRunner.emit({
147 + type: "session_start",
148 + reason: "reload",
149 + } as never);
150 + expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
151 + const result = await t.session.extensionRunner.emitBeforeAgentStart(
152 + "hello",
153 + undefined,
154 + "BASE",
155 + {} as never,
156 + );
157 + expect(result).toBeUndefined();
158 + });
160 + it("session_shutdown clears header", async () => {
161 + t = await createTestSession({ extensions: [extPath()] });
162 + writeMode(t, "plan", "# Plan body\n");
163 + await command(t, "plan");
164 + t.events.uiCallsFor("setHeader").length = 0;
165 + await t.session.extensionRunner.emit({
166 + type: "session_shutdown",
167 + reason: "quit",
168 + } as never);
169 + expect(t.events.uiCallsFor("setHeader").at(-1)?.args).toEqual([undefined]);
170 + });
172 + it("warns for unresolved model and still applies thinking", async () => {
173 + t = await createTestSession({ extensions: [extPath()] });
174 + await t.session.setModel(
175 + t.session.modelRegistry.find("openai", "gpt-5.2-codex"),
176 + );
177 + writeMode(t, "deep", "---\nmodel: nope/missing\nthinking: high\n---\nbody");
178 + await command(t, "deep");
179 + writeMode(t, "badref", "---\nmodel: malformed\n---\nbody");
180 + await command(t, "badref");
181 + const notes = t.events
182 + .uiCallsFor("notify")
183 + .map((call) => String(call.args[0]));
184 + expect(
185 + notes.some((note) => note.includes("model not found: nope/missing")),
186 + ).toBe(true);
187 + expect(
188 + notes.some((note) => note.includes("model not found: malformed")),
189 + ).toBe(true);
190 + const latestThinking = [...t.session.sessionManager.getBranch()]
191 + .reverse()
192 + .find(
193 + (entry: { type?: string }) => entry.type === "thinking_level_change",
194 + ) as { thinkingLevel?: string } | undefined;
195 + expect(latestThinking?.thinkingLevel).toBe("high");
196 + });
198 + it("sets resolved model and thinking", async () => {
199 + t = await createTestSession({ extensions: [extPath()] });
200 + writeMode(
201 + t,
202 + "deep",
203 + "---\nmodel: openai/gpt-5.2-codex\nthinking: high\n---\nbody",
204 + );
205 + await command(t, "deep");
206 + expect(t.session.model?.id).toBe("gpt-5.2-codex");
207 + expect(t.session.thinkingLevel).toBe("high");
208 + });
210 + it("warns when resolved model cannot be applied", async () => {
211 + t = await createTestSession({ extensions: [extPath()] });
212 + t.session.extensionRunner.runtime.setModel = async () => false;
213 + writeMode(t, "deep", "---\nmodel: openai/gpt-5.2-codex\n---\nbody");
214 + await command(t, "deep");
215 + const notes = t.events
216 + .uiCallsFor("notify")
217 + .map((call) => String(call.args[0]));
218 + expect(
219 + notes.some((note) =>
220 + note.includes("model unavailable: openai/gpt-5.2-codex"),
221 + ),
222 + ).toBe(true);
223 + });
225 + it("reload-config reports counts and warnings", async () => {
226 + t = await createTestSession({ extensions: [extPath()] });
227 + await command(t, "reload-config");
228 + expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
229 + "mode config: 0 mode(s), 0 warning(s)",
230 + "info",
231 + ]);
232 + writeMode(t, "plan", "# Plan\n");
233 + writeMode(t, "bad id", "# Bad\n");
234 + await command(t, "reload-config");
235 + const calls = t.events.uiCallsFor("notify");
236 + expect(
237 + calls.some((call) => String(call.args[0]).includes("bad id.md")),
238 + ).toBe(true);
239 + expect(calls.at(-1)?.args).toEqual([
240 + "mode config: 1 mode(s), 1 warning(s)",
241 + "warning",
242 + ]);

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 5 import { describe, expect, it } from "vitest";
5 6 import modeExtension, { __modeTest } from "../index.ts";
7 -const nowEntry = (data: unknown) => ({
8 - type: "custom",
9 - customType: "mode-state",
10 - data,
11 -});
8 +function mockTheme(
9 + overrides: {
10 + fg?: (color: string, text: string) => string;
11 + bg?: (color: string, text: string) => string;
12 + bold?: (text: string) => string;
13 + italic?: (text: string) => string;
14 + underline?: (text: string) => string;
15 + inverse?: (text: string) => string;
16 + strikethrough?: (text: string) => string;
17 + } = {},
18 +) {
19 + const identity = (text: string) => text;
20 + const passthrough = (_color: string, text: string) => text;
21 + return {
22 + fg: overrides.fg ?? passthrough,
23 + bg: overrides.bg ?? passthrough,
24 + bold: overrides.bold ?? identity,
25 + italic: overrides.italic ?? identity,
26 + underline: overrides.underline ?? identity,
27 + inverse: overrides.inverse ?? identity,
28 + strikethrough: overrides.strikethrough ?? identity,
29 + };
32 +type HeaderFactory = (
33 + tui: TUI,
34 + theme: Theme,
35 +) => Component & {
36 + dispose?(): void;
37 +};
39 +function expectFactory(value: HeaderFactory | undefined): HeaderFactory {
40 + expect(value).toBeDefined();
41 + if (!value) throw new Error("expected header factory");
42 + return value;
13 45 describe("mode pure helpers", () => {
14 46 it("parses valid mode markdown", () => {
15 47 const mode = __modeTest.parseModeMarkdown(
16 48 "plan",
17 - `---\ndescription: Read-only planning\nmodel: openai/gpt-5.2-codex\nthinking: high\ntools: [read, grep]\nreminder: Stay read-only.\n---\n\n# Plan\n\nBody.\n`,
49 + `---\ndescription: Read-only planning\naccent: warning\nmodel: openai/gpt-5.2-codex\nthinking: high\ntools: [read, grep]\nreminder: Stay read-only.\n---\n\n# Plan\n\nBody.\n`,
19 51 expect(mode).toEqual({
20 52 id: "plan",
21 53 description: "Read-only planning",
54 + accent: "warning",
22 55 model: "openai/gpt-5.2-codex",
23 56 thinking: "high",
24 57 tools: ["read", "grep"],
80 113 ).toThrow(
81 114 "mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
116 + expect(() =>
117 + __modeTest.parseModeMarkdown("bad", "---\naccent: hotpink\n---\nbody"),
118 + ).toThrow(
119 + `mode bad: accent must be one of ${__modeTest.ACCENT_COLORS.join(", ")}`,
120 + );
121 + expect(() =>
122 + __modeTest.parseModeMarkdown("bad", "---\naccent: 1\n---\nbody"),
123 + ).toThrow(
124 + `mode bad: accent must be one of ${__modeTest.ACCENT_COLORS.join(", ")}`,
125 + );
85 128 it("validates ids", () => {
124 - it("restores latest mode state from current branch entries", () => {
125 - expect(
126 - __modeTest.latestModeState([
127 - { type: "message", customType: "mode-state", data: {} },
128 - nowEntry({
129 - schemaVersion: 1,
130 - activeMode: "plan",
131 - neutralize: false,
132 - reason: "switch",
133 - }),
134 - ]),
135 - ).toEqual({
136 - schemaVersion: 1,
137 - activeMode: "plan",
138 - neutralize: false,
139 - reason: "switch",
140 - });
141 - expect(
142 - __modeTest.latestModeState([
143 - nowEntry(null),
144 - nowEntry({ broken: true }),
145 - nowEntry({
146 - schemaVersion: 1,
147 - activeMode: null,
148 - neutralize: true,
149 - reason: "compaction",
150 - }),
151 - ]),
152 - ).toEqual({
153 - schemaVersion: 1,
154 - activeMode: null,
155 - neutralize: true,
156 - reason: "compaction",
157 - });
158 - const badReasons = ["switch", "off", "compaction"].map((reason) =>
159 - nowEntry({
160 - schemaVersion: 2,
161 - activeMode: "plan",
162 - neutralize: false,
163 - reason,
164 - }),
165 - );
166 - expect(__modeTest.latestModeState(badReasons)).toBeUndefined();
167 - });
169 167 it("keeps malformed model refs unresolved", () => {
170 168 expect(__modeTest.parseModelRef("/model")).toBeUndefined();
171 169 expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
231 229 rmSync(agentDir, { recursive: true, force: true });
232 +});
235 - it("renders status text", () => {
236 - expect(__modeTest.statusText("plan")).toBe("MODE plan");
237 - expect(__modeTest.statusText(null)).toBeUndefined();
234 +describe("mode header factory", () => {
235 + it("returns undefined for null to restore built-in", () => {
236 + expect(__modeTest.buildHeader(null)).toBeUndefined();
240 - it("handles no-UI shutdown and model-less compaction", () => {
239 + it("returns a component factory for a mode", () => {
240 + const factory = __modeTest.buildHeader({
241 + id: "plan",
242 + body: "body",
243 + accent: "warning",
244 + });
245 + expect(typeof factory).toBe("function");
246 + });
248 + it("applies theme color and bold to banner", () => {
249 + const factory = expectFactory(
250 + __modeTest.buildHeader({
251 + id: "plan",
252 + body: "body",
253 + accent: "warning",
254 + }),
255 + );
256 + const calls: Array<[string, string]> = [];
257 + const theme = mockTheme({
258 + fg: (color, text) => {
259 + calls.push(["fg", color]);
260 + return text;
261 + },
262 + bold: (text) => text,
263 + });
264 + const component = factory({} as never, theme as never);
265 + component.render(80);
266 + expect(calls).toContainEqual(["fg", "warning"]);
267 + });
269 + it("defaults accent to accent color", () => {
270 + const factory = expectFactory(
271 + __modeTest.buildHeader({ id: "plan", body: "body" }),
272 + );
273 + const calls: string[] = [];
274 + const theme = mockTheme({
275 + fg: (color) => {
276 + calls.push(color);
277 + return "";
278 + },
279 + bold: (text) => text,
280 + });
281 + factory({} as never, theme as never).render(80);
282 + expect(calls).toContain("accent");
283 + });
285 + it("includes description and meta when present", () => {
286 + const factory = expectFactory(
287 + __modeTest.buildHeader({
288 + id: "plan",
289 + body: "body",
290 + description: "Read-only planning",
291 + tools: ["read", "grep"],
292 + model: "openai/gpt-5.2-codex",
293 + thinking: "high",
294 + }),
295 + );
296 + const theme = mockTheme();
297 + const lines = factory({} as never, theme as never).render(120);
298 + const flat = lines.join("\n");
299 + expect(flat).toContain("MODE: plan");
300 + expect(flat).toContain("Read-only planning");
301 + expect(flat).toContain("tools: read, grep");
302 + expect(flat).toContain("model: openai/gpt-5.2-codex");
303 + expect(flat).toContain("thinking: high");
304 + });
306 + it("omits description and meta when absent", () => {
307 + const factory = expectFactory(
308 + __modeTest.buildHeader({ id: "plan", body: "body" }),
309 + );
310 + const theme = mockTheme();
311 + const flat = factory({} as never, theme as never)
312 + .render(120)
313 + .join("\n");
314 + expect(flat).toContain("MODE: plan");
315 + expect(flat).not.toContain("tools:");
316 + expect(flat).not.toContain("model:");
317 + expect(flat).not.toContain("thinking:");
318 + });
319 +});
321 +describe("mode runtime event handlers", () => {
322 + it("session_shutdown with no UI does not throw", () => {
241 323 const events = new Map<string, (...args: unknown[]) => unknown>();
242 - const entries: unknown[] = [];
243 324 modeExtension({
244 - appendEntry: (_type: string, data: unknown) => entries.push(data),
245 325 events: { emit: () => undefined },
246 326 getAllTools: () => [],
247 327 on: (name: string, handler: (...args: unknown[]) => unknown) =>
251 331 setModel: async () => true,
252 332 setThinkingLevel: () => undefined,
253 333 } as never);
255 334 expect(() =>
256 335 events.get("session_shutdown")?.({}, { hasUI: false } as never),
257 336 ).not.toThrow();
258 - events.get("session_compact")?.({ compactionEntry: { id: "c1" } }, {
337 + });
339 + it("session_start resets in-memory state and publishes no header", async () => {
340 + const events = new Map<string, (...args: unknown[]) => unknown>();
341 + const commands = new Map<
342 + string,
343 + { handler: (args: string, ctx: unknown) => Promise<void> }
344 + >();
345 + const headers: unknown[] = [];
346 + const ctx = {
347 + hasUI: true,
259 348 model: undefined,
260 - } as never);
261 - expect(entries).toEqual([
262 - {
263 - schemaVersion: 1,
264 - activeMode: null,
265 - neutralize: false,
266 - reason: "compaction",
267 - compactionEntryId: "c1",
349 + modelRegistry: { find: () => undefined },
350 + ui: {
351 + notify: () => undefined,
352 + setHeader: (...args: unknown[]) => headers.push(args),
269 - ]);
354 + };
355 + modeExtension({
356 + events: { emit: () => undefined },
357 + getAllTools: () => [],
358 + on: (name: string, handler: (...args: unknown[]) => unknown) =>
359 + events.set(name, handler),
360 + registerCommand: (
361 + name: string,
362 + command: { handler: (args: string, ctx: unknown) => Promise<void> },
363 + ) => commands.set(name, command),
364 + setActiveTools: () => undefined,
365 + setModel: async () => true,
366 + setThinkingLevel: () => undefined,
367 + } as never);
368 + await events.get("session_start")?.({ reason: "startup" }, ctx);
369 + expect(headers).toEqual([[undefined]]);
370 + const beforeAgent = events.get("before_agent_start")?.(
371 + { systemPrompt: "BASE" },
372 + ctx,
373 + );
374 + expect(beforeAgent).toBeUndefined();

extensions/mode/index.ts

Modified
5 5 ExtensionContext,
6 6 } from "@earendil-works/pi-coding-agent";
7 7 import { getAgentDir } from "@earendil-works/pi-coding-agent";
8 +import {
9 + type Component,
10 + Text,
11 + type Theme,
12 + type TUI,
13 +} from "@earendil-works/pi-tui";
8 14 import { parse as parseYaml } from "yaml";
10 16 type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
18 +type AccentColor =
19 + | "accent"
20 + | "borderAccent"
21 + | "success"
22 + | "warning"
23 + | "error"
24 + | "muted"
25 + | "dim";
12 27 type Mode = {
13 28 id: string;
14 29 description?: string;
30 + accent?: AccentColor;
15 31 model?: string;
16 32 thinking?: ThinkingLevel;
17 33 reminder?: string;
19 35 body: string;
22 -type ModeStateEntry = {
23 - schemaVersion: 1;
24 - activeMode: string | null;
25 - neutralize: boolean;
26 - reason: "switch" | "off" | "compaction";
27 - model?: string;
28 - provider?: string;
29 - compactionEntryId?: string;
30 -};
32 38 type ModeRuntimeState = {
33 39 activeModeId: string | null;
34 40 neutralize: boolean;
36 42 warnings: string[];
39 -type ModeEntryLike = {
40 - type?: unknown;
41 - customType?: unknown;
42 - data?: unknown;
43 -};
45 45 type ModelRef = { provider: string; modelId: string };
47 -const MODE_STATE_VERSION = 1;
48 -const MODE_STATE_ENTRY = "mode-state";
49 -const STATUS_KEY = "mode";
50 47 const THINKING_LEVELS = [
51 48 "off",
52 49 "minimal",
55 52 "high",
56 53 "xhigh",
57 54 ] as const;
56 +const ACCENT_COLORS = [
57 + "accent",
58 + "borderAccent",
59 + "success",
60 + "warning",
61 + "error",
62 + "muted",
63 + "dim",
64 +] as const;
58 66 const MODE_ID_RE = /^[a-zA-Z0-9_-]+$/;
60 68 function isValidModeId(id: string): boolean {
96 104 if (data.description !== undefined)
97 105 mode.description = requireString(id, "description", data.description);
106 + if (data.accent !== undefined) mode.accent = requireAccent(id, data.accent);
98 107 if (data.model !== undefined)
99 108 mode.model = requireString(id, "model", data.model);
100 109 if (data.reminder !== undefined)
135 144 return value as ThinkingLevel;
147 +function requireAccent(id: string, value: unknown): AccentColor {
148 + if (
149 + typeof value !== "string" ||
150 + !ACCENT_COLORS.includes(value as AccentColor)
151 + ) {
152 + throw new Error(
153 + `mode ${id}: accent must be one of ${ACCENT_COLORS.join(", ")}`,
154 + );
156 + return value as AccentColor;
138 159 function parseModelRef(ref: string): ModelRef | undefined {
139 160 const slash = ref.indexOf("/");
140 161 if (slash <= 0 || slash === ref.length - 1) return undefined;
155 176 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>`;
158 -function isModeStateEntry(value: unknown): value is ModeStateEntry {
159 - if (!value || typeof value !== "object") return false;
160 - const data = value as Record<string, unknown>;
161 - return (
162 - data.schemaVersion === MODE_STATE_VERSION &&
163 - (data.activeMode === null || typeof data.activeMode === "string") &&
164 - typeof data.neutralize === "boolean" &&
165 - (data.reason === "switch" ||
166 - data.reason === "off" ||
167 - data.reason === "compaction")
168 - );
171 -function latestModeState(entries: ModeEntryLike[]): ModeStateEntry | undefined {
172 - for (let i = entries.length - 1; i >= 0; i--) {
173 - const entry = entries[i];
174 - if (entry.type !== "custom" || entry.customType !== MODE_STATE_ENTRY)
175 - continue;
176 - if (isModeStateEntry(entry.data)) return entry.data;
177 - }
178 - return undefined;
179 +function buildHeader(
180 + mode: Mode | null,
181 +): ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined {
182 + 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 + };
181 204 async function loadModes(
215 238 return mode.description ? `${mode.id} — ${mode.description}` : mode.id;
218 -function statusText(modeId: string | null): string | undefined {
219 - return modeId ? `MODE ${modeId}` : undefined;
222 -function publishStatus(ctx: ExtensionContext, modeId: string | null): void {
241 +function publishHeader(ctx: ExtensionContext, mode: Mode | null): void {
223 242 if (!ctx.hasUI) return;
224 - ctx.ui.setStatus(STATUS_KEY, statusText(modeId));
227 -function currentModelState(
228 - ctx: ExtensionContext,
229 -): Pick<ModeStateEntry, "provider" | "model"> {
230 - return ctx.model ? { provider: ctx.model.provider, model: ctx.model.id } : {};
243 + ctx.ui.setHeader(buildHeader(mode));
233 246 export default function modeExtension(pi: ExtensionAPI): void {
245 258 for (const warning of state.warnings) ctx?.ui.notify(warning, "warning");
248 - function persist(
249 - ctx: ExtensionContext,
250 - reason: ModeStateEntry["reason"],
251 - compactionEntryId?: string,
252 - ): void {
253 - pi.appendEntry(MODE_STATE_ENTRY, {
254 - schemaVersion: MODE_STATE_VERSION,
255 - activeMode: state.activeModeId,
256 - neutralize: state.neutralize,
257 - reason,
258 - ...currentModelState(ctx),
259 - ...(compactionEntryId ? { compactionEntryId } : {}),
260 - } satisfies ModeStateEntry);
261 - }
263 261 async function applyMode(mode: Mode, ctx: ExtensionContext): Promise<void> {
264 262 if (mode.tools && mode.tools.length > 0) {
265 263 const all = new Set(pi.getAllTools().map((tool) => tool.name));
304 302 state.activeModeId = id;
305 303 state.neutralize = false;
306 304 await applyMode(mode, ctx);
307 - persist(ctx, "switch");
308 - publishStatus(ctx, id);
309 - ctx.ui.notify(`mode ${id}`, "info");
305 + publishHeader(ctx, mode);
312 308 function modeOff(ctx: ExtensionContext): void {
313 - const hadMode = state.activeModeId !== null;
309 + if (state.activeModeId === null) {
310 + ctx.ui.notify("no mode active", "info");
311 + return;
314 313 state.activeModeId = null;
315 - state.neutralize = hadMode || state.neutralize;
316 - persist(ctx, "off");
317 - publishStatus(ctx, null);
318 - ctx.ui.notify("mode off", "info");
314 + state.neutralize = true;
315 + publishHeader(ctx, null);
321 318 function showStatus(ctx: ExtensionContext): void {
380 377 pi.on("session_start", async (_event, ctx) => {
381 378 await reloadConfig(ctx);
382 - const saved = latestModeState(
383 - ctx.sessionManager.getBranch() as ModeEntryLike[],
384 - );
385 - state.activeModeId = saved?.activeMode ?? null;
386 - state.neutralize = saved?.neutralize ?? false;
387 - if (state.activeModeId) {
388 - const mode = state.modes.get(state.activeModeId);
389 - if (mode) await applyMode(mode, ctx);
390 - else {
391 - ctx.ui.notify(
392 - `mode missing: ${state.activeModeId}; falling back to normal`,
393 - "warning",
394 - );
395 - state.activeModeId = null;
396 - state.neutralize = true;
397 - persist(ctx, "off");
398 - }
399 - }
400 - publishStatus(ctx, state.activeModeId);
379 + state.activeModeId = null;
380 + state.neutralize = false;
381 + publishHeader(ctx, null);
403 - pi.on("session_compact", (event, ctx) =>
404 - persist(ctx, "compaction", event.compactionEntry.id),
405 - );
406 - pi.on("session_shutdown", (_event, ctx) => publishStatus(ctx, null));
384 + pi.on("session_shutdown", (_event, ctx) => publishHeader(ctx, null));
409 387 export const __modeTest = {
388 + ACCENT_COLORS,
389 + buildHeader,
410 390 frontmatterSplit,
411 391 isValidModeId,
412 - latestModeState,
413 392 loadModes,
414 393 modePromptAddition,
415 394 normalPromptAddition,
416 395 parseModeMarkdown,
417 396 parseModelRef,
418 - statusText,

extensions/mode/package.json

Modified
7 7 "yaml": "^2.9.0"
9 9 "peerDependencies": {
10 - "@earendil-works/pi-coding-agent": "*"
10 + "@earendil-works/pi-coding-agent": "*",
11 + "@earendil-works/pi-tui": "*"
12 13 "devDependencies": {
13 14 "@marcfargas/pi-test-harness": "^0.6.1",
14 15 "vitest": "^4.1.9"
16 17 "license": "MIT",
17 - "description": "Session-local mode switching for Pi.",
18 + "description": "Session-local mode switching with themed header visibility for Pi.",
18 19 "keywords": [
19 20 "pi",
20 21 "pi-extension",