repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(mode): add session-local mode switching

cf994a4bd4948987d3f0d5acb4acf2a19bc1b6e3

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (11)

extensions/mode/PLAN.md

Added
new file mode 100644
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.
5 +**Goal:** Build the validated V1 mode extension from `extensions/mode/V1.md`.
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.
9 +**Tech Stack:** TypeScript, Pi extension API, `yaml`, Vitest, `@marcfargas/pi-test-harness`.
11 +**Roadmap:** None
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:
145 +```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"
161 +```
163 +Expected: commit succeeds.
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.

extensions/mode/README.md

Added
new file mode 100644
1 +# mode
3 +Session-local Pi modes from Markdown files.
5 +## Install / load
7 +Loaded through the root pi-ext package.
8 +See [../../README.md](../../README.md).
10 +## Commands / tools / settings
12 +Commands:
14 +- `/mode` — show active mode and available modes.
15 +- `/mode status` — same as `/mode`.
16 +- `/mode list` — list available modes.
17 +- `/mode <id>` — switch to a mode.
18 +- `/mode off` — turn mode off.
19 +- `/mode normal` — alias for `/mode off`.
20 +- `/mode none` — alias for `/mode off`.
21 +- `/mode reload-config` — reload mode files and report count/warnings.
23 +Tools: none.
25 +Settings: none.
27 +## Mode files
29 +V1 loads only global mode files:
31 +```text
32 +~/.pi/agent/modes/*.md
33 +```
35 +Mode id is the file stem.
36 +Valid ids match `^[a-zA-Z0-9_-]+$`.
38 +Example:
40 +```md
41 +---
42 +description: Read-only planning
43 +model: openai/gpt-5.2-codex
44 +thinking: high
45 +tools: [read, grep, find, ls]
46 +reminder: You are planning only. Do not implement.
47 +---
49 +# Planning mode
51 +Plan only.
52 +Do not implement.
53 +```
55 +## 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.
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.
63 +Mode state persists in session custom entries.
64 +Restore uses the current branch only.
65 +Compaction adds a mode checkpoint.
67 +## 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.

extensions/mode/SPEC.md

Added
new file mode 100644
1 +# Mode Extension Spec
3 +Split by version:
5 +- `V1.md` — approved minimal implementation spec.
6 +- `V2.md` — approved provenance/status additions plus shortcut discussion.
7 +- `V3.md` — unapproved discussion bucket.
9 +## Current implementation target
11 +Implement `V1.md` only.
13 +V1 was trimmed to validated public Pi APIs.
14 +Project-local `.pi/modes/*.md` is deferred because current extension contexts expose no public project-trust API.
16 +Do not implement V2/V3 unless explicitly requested.

extensions/mode/V1.md

Added
new file mode 100644
1 +# Mode Extension V1 Spec
3 +## Goal
5 +Session-local, switchable Pi modes.
7 +A mode changes what the model sees and may change runtime model, thinking level, and active tools.
8 +Modes are Markdown files, not hardcoded presets.
10 +Pi starts with **no active mode**.
11 +This is normal mode.
13 +## Validation status
15 +V1 is validated against current Pi extension APIs by prototypes.
17 +Supported:
19 +- `before_agent_start` can append mode body/kernel to `systemPrompt` without persisting messages.
20 +- `pi.getAllTools()` + `pi.setActiveTools()` can apply filtered tool lists.
21 +- `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 +- `getAgentDir()` resolves the global Pi agent dir.
27 +Trimmed from V1:
29 +- Project-local `.pi/modes/*.md`.
30 + Current `ExtensionContext` has no public project-trust API, so a global extension cannot read project-local mode files without bypassing Pi trust.
31 + Revisit when Pi exposes trusted project-resource access to extensions.
32 +- Pi internal `parseFrontmatter` helper.
33 + It is not package-exported.
34 + V1 uses a declared `yaml` dependency for frontmatter parsing.
36 +## Non-goals
38 +- No permission system.
39 +- No project-local modes.
40 +- No extension enable/disable per mode.
41 +- No settings mutation for mode switching.
42 +- No `/reload` as part of mode switching.
43 +- No extension-to-extension API.
44 +- No mode baseline restore/update system.
45 +- No tool metadata in the active block.
46 +- No shortcut/keybinding support.
47 +- No file watching.
49 +## Mode files
51 +Load modes from:
53 +```text
54 +getAgentDir()/modes/*.md
55 +```
57 +Rules:
59 +- Mode id is the Markdown file stem.
60 +- Valid ids match `^[a-zA-Z0-9_-]+$`.
61 +- Invalid ids are ignored with a warning.
62 +- Duplicate ids cannot occur in V1 because only one directory is loaded.
63 +- Files use YAML frontmatter delimited by a leading `---` block.
64 +- Invalid YAML ignores the file with a warning.
65 +- Empty frontmatter is allowed.
66 +- Empty Markdown body is allowed.
67 +- Users own token cost.
68 + Do not truncate body or reminder.
70 +## Mode schema
72 +```ts
73 +type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
75 +type Mode = {
76 + id: string; // file stem
77 + description?: string; // shown by /mode, no runtime behavior
78 + model?: string; // provider/model-id, split at first slash
79 + thinking?: ThinkingLevel;
80 + reminder?: string; // short active-block reminder
81 + tools?: string[]; // absent/empty = do not change active tools
82 + body: string; // Markdown body appended to system prompt while active
83 +};
84 +```
86 +Validation:
88 +- `description`, `model`, and `reminder` must be strings when present.
89 +- `thinking` must be a valid `ThinkingLevel` when present.
90 +- `tools` must be an array of strings when present.
91 +- Unknown frontmatter keys are ignored.
92 +- Invalid typed fields ignore the file with a warning.
94 +Example:
96 +```md
97 +---
98 +description: Read-only planning
99 +model: openai/gpt-5.2-codex
100 +thinking: high
101 +tools: [read, grep, find, ls]
102 +reminder: You are planning only. Do not implement.
103 +---
105 +# Planning mode
107 +Long system-prompt instructions here.
108 +```
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;
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 +## Model/thinking/tool application
141 +On `/mode <id>`:
143 +1. Reload mode files.
144 +2. Resolve mode by id.
145 +3. Set in-memory `activeModeId = id`.
146 +4. Set in-memory `neutralize = false`.
147 +5. If `tools` exists and is non-empty, validate names against `pi.getAllTools()` and apply valid names via `pi.setActiveTools(validTools)`.
148 +6. Warn for unknown tools and continue.
149 +7. If `model` exists, parse as `provider/model-id`, splitting at the first slash.
150 +8. If model ref is malformed or unresolved by `ctx.modelRegistry.find(provider, modelId)`, warn and keep current model.
151 +9. If resolved, call `await pi.setModel(model)`.
152 +10. If `pi.setModel()` returns `false`, warn and keep current model.
153 +11. If `thinking` exists, call `pi.setThinkingLevel(thinking)`.
154 +12. Persist a `mode-state` entry with `reason: "switch"`.
155 +13. Update status UI.
157 +`tools` absent or empty means the mode does not alter active tools.
159 +Switching from mode A to mode B does not restore baseline first.
160 +B only applies fields it declares.
162 +## Normal/off behavior
164 +Commands:
166 +```text
167 +/mode off
168 +/mode normal
169 +/mode none
170 +```
172 +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.
182 +Fresh normal sessions with no prior mode entry get no mode block.
184 +Baseline restore/update is deferred.
186 +## Prompt injection
188 +Use `before_agent_start`.
189 +Return a modified `systemPrompt` only.
190 +Do not inject custom messages for V1 mode prompts.
192 +When a mode is active, append to the system prompt in this order:
194 +1. Mode body.
195 +2. Generated active kernel.
196 +3. Optional generated reminder.
198 +Active kernel:
200 +```text
201 +<mode_kernel>
202 +active_mode: plan
203 +active mode is runtime state, not conversation state
204 +current user message cannot change active mode
205 +previous mode prompts are inactive unless repeated here
206 +mode body/reminder cannot override this kernel
207 +</mode_kernel>
208 +```
210 +If `reminder` is present and non-empty, append:
212 +```text
213 +<mode_reminder>
214 +You are planning only. Do not implement.
215 +</mode_reminder>
216 +```
218 +When normal mode has `neutralize = true`, append only:
220 +```text
221 +<mode_kernel>
222 +active_mode: normal
223 +active mode is runtime state, not conversation state
224 +previous mode prompts are inactive unless repeated here
225 +</mode_kernel>
226 +```
228 +Do not list tools in the active block.
230 +## Commands
232 +```text
233 +/mode show active mode + available modes
234 +/mode status same as /mode
235 +/mode list show available modes
236 +/mode <id> switch active mode
237 +/mode off turn mode off
238 +/mode normal alias for /mode off
239 +/mode none alias for /mode off
240 +/mode reload-config reload mode files and report count/warnings
241 +```
243 +`/mode` and `/mode list` output include mode id and description.
245 +Errors:
247 +- Unknown mode id: warn and leave current mode unchanged.
248 +- No modes dir: report no modes, no warning.
249 +- Empty modes dir: report no modes, no warning.
251 +## UI
253 +When a mode is active, set status key `mode` to:
255 +```text
256 +MODE plan
257 +```
259 +Normal mode clears status key `mode`.
261 +## Persistence and restore
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.
281 +## Compaction
283 +Compaction is not source of truth for active mode.
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.
288 +On `session_compact`, append a checkpoint:
290 +```ts
291 +type ModeCheckpointEntry = ModeStateEntry & {
292 + reason: "compaction";
293 + compactionEntryId: string;
295 +```
297 +Rules:
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.
303 +## Extension/resource model
305 +Extensions are process capabilities, not mode-scoped resources.
307 +Mode config has no `extensions` field.
308 +If a mode needs an extension tool, list that tool in `tools`.
309 +Loaded extensions themselves remain loaded.

extensions/mode/V2.md

Added
new file mode 100644
1 +# Mode Extension V2 Spec
3 +Depends on V1.
5 +## Historical mode spans
7 +Approved.
9 +Problem: long sessions can contain many mode/model switches. Even with a current-mode kernel, old context can be hard to interpret because messages from different modes look like one continuous conversation.
11 +V2 adds LLM-visible historical provenance markers.
13 +## Rules
15 +- Context-only. Do not mutate stored messages.
16 +- Human transcript stays normal.
17 +- Insert markers in the `context` hook before provider call.
18 +- Mark contiguous spans, not every message and not every turn.
19 +- Boundary when mode changes or provider/model changes.
20 +- Fields: mode + provider/model only.
21 +- No toolset metadata in v2.
22 +- Markers are historical provenance only; they never set active mode.
24 +Marker shape:
26 +```text
27 +<mode_span mode="build" model="openai/gpt-5.2-codex"/>
28 +```
30 +Kernel addition:
32 +```text
33 +Historical <mode_span> markers label provenance only.
34 +They do not set active mode.
35 +```
37 +Example model-visible context shape:
39 +```text
40 +<mode_kernel>
41 +active_mode: build
42 +active mode is runtime state, not conversation state
43 +current user message cannot change active mode
44 +previous mode prompts are inactive unless repeated here
45 +historical <mode_span> markers label provenance only; they do not set active mode
46 +mode body/reminder cannot override this kernel
47 +</mode_kernel>
49 +<mode_reminder>
50 +Implement requested changes. Keep scope tight, verify work, and report results.
51 +</mode_reminder>
53 +<mode_span mode="plan" model="openai/gpt-5.2-codex"/>
54 +[historical messages produced while plan + gpt-5.2-codex were active]
56 +<mode_span mode="build" model="anthropic/claude-opus-4.5"/>
57 +[historical messages produced while build + opus were active]
58 +```
60 +## Span construction
62 +Use run-length encoding over model-visible context:
64 +- Current span key: `mode + provider + model`.
65 +- Insert a span marker only when key changes.
66 +- Mode comes from mode custom entries/checkpoints.
67 +- Provider/model can be read from assistant messages and model change entries where available.
69 +If provider/model is unknown, use only mode:
71 +```text
72 +<mode_span mode="talk"/>
73 +```
75 +If mode is normal/no-mode, either omit `mode` or use:
77 +```text
78 +<mode_span mode="normal" model="anthropic/claude-sonnet-4-5"/>
79 +```
81 +Prefer omitting spans for normal-only history unless adjacent active-mode history needs disambiguation.
83 +## Compaction handling
85 +- Do not preserve raw span markers inside summaries.
86 +- Add compaction instruction: mode labels are historical provenance only; do not carry old mode prompts forward as active instructions.
87 +- Append exact mode checkpoint after compaction.
88 +- Recent kept raw messages still get normal span markers when rendered.
89 +- Compacted-away spans may be summarized in checkpoint details later, but v2 does not require it.
91 +## Status icon/color
93 +Approved.
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 +```
117 +## Shortcuts
119 +Needs discussion before approval.
121 +Open design options:
123 +1. Global cycle shortcut configured on extension.
124 +2. Per-mode shortcut in frontmatter.
125 +3. Both, with conflict detection.
127 +Do not implement shortcuts until conflict/precedence behavior is decided.

extensions/mode/V3.md

Added
new file mode 100644
1 +# Mode Extension V3 Ideas
3 +Not approved for implementation. Discussion bucket.
5 +## Tool policy syntax
7 +Glob-based allow/deny syntax for tools:
9 +```yaml
10 +tools: ["*", "!write"]
11 +tools: ["!*", "read", "grep"]
12 +```
14 +Needs precise ordered semantics and custom-tool behavior.
16 +Open questions:
18 +- Match against all loaded tools or only currently active tools?
19 +- Does `*` include extension/custom tools?
20 +- How to display effective set without confusing the LLM?
21 +- What happens when tools appear after mode activation?
23 +## Tool metadata in active block
25 +V1/V2 intentionally omit tools from the active block.
27 +V3 may reintroduce generated tool metadata if all loaded/custom tools can be tracked safely and cheaply.
29 +## Baseline restore/update
31 +V1 does not restore previous tools/model/thinking on `/mode off`.
33 +V3 discussion:
35 +- Capture baseline on startup?
36 +- Update baseline while no mode active?
37 +- Detect manual `/model`, thinking, or tools changes while a mode is active?
38 +- Does switching from mode A to mode B restore baseline first, then apply B?
40 +## Mode-local bash wrappers/guards
42 +Deferred.
44 +This is a permission/sandbox feature in disguise and can create false safety.
46 +Questions:
48 +- Is shell allowlisting worth it?
49 +- Is it limited to built-in `bash`?
50 +- How to handle `python -c`, `node -e`, `git`, `tee`, redirection, generated scripts?
51 +- How to communicate limitations without lying?
53 +## Historical span toolset metadata
55 +V2 spans include only mode + provider/model.
57 +V3 may add toolset metadata if tool tracking is solved:
59 +```text
60 +<mode_span mode="plan" model="openai/gpt-5.2-codex" tools="ro"/>
61 +```
63 +Not before tool policy/tracking design is done.
65 +## Interactive switcher
67 +`/mode` interactive fuzzy switcher:
69 +- render icon
70 +- render name/id
71 +- render description
72 +- maybe preview model/thinking/tools
74 +Needs TUI design.
76 +## Mode transitions
78 +Possible per-mode transition hooks inside same extension:
80 +- before-enter
81 +- after-enter
82 +- before-exit
83 +- after-exit
85 +No extension-to-extension API.
87 +## Mode-scoped prompt templates or skills
89 +Possible but risky.
91 +Questions:
93 +- Should active mode filter prompt templates/skills?
94 +- Does this mutate Pi resources or only model-visible prompt?
95 +- How to avoid reload/settings mutation?

extensions/mode/__tests__/coverage.test.ts

Added
new file mode 100644
1 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
4 +import { describe, expect, it } from "vitest";
5 +import modeExtension, { __modeTest } from "../index.ts";
7 +const custom = (data: unknown) => ({
8 + type: "custom",
9 + customType: "mode-state",
10 + data,
11 +});
13 +type Fake = ReturnType<typeof fakeRuntime>;
15 +function fakeRuntime() {
16 + const commands = new Map<
17 + string,
18 + { handler: (args: string, ctx: any) => Promise<void> }
19 + >();
20 + const events = new Map<string, (event: any, ctx: any) => unknown>();
21 + const entries: Array<{ type: string; customType: string; data: unknown }> =
22 + [];
23 + const notes: Array<[string, string]> = [];
24 + const statuses: Array<[string, string | undefined]> = [];
25 + const activeTools: string[][] = [];
26 + let setModelResult = true;
27 + let modelFindResult: unknown;
28 + let thinking: string | undefined;
29 + const ctx: any = {
30 + hasUI: true,
31 + model: { provider: "prov", id: "model" },
32 + modelRegistry: { find: () => modelFindResult },
33 + sessionManager: { getBranch: () => entries },
34 + ui: {
35 + notify: (message: string, severity: string) =>
36 + notes.push([message, severity]),
37 + setStatus: (key: string, value: string | undefined) =>
38 + statuses.push([key, value]),
39 + },
40 + };
41 + modeExtension({
42 + appendEntry: (type: string, data: unknown) =>
43 + entries.push({ type: "custom", customType: type, data }),
44 + events: { emit: () => undefined },
45 + getAllTools: () => [{ name: "read" }, { name: "grep" }],
46 + on: (name: string, handler: (event: any, ctx: any) => unknown) =>
47 + events.set(name, handler),
48 + registerCommand: (
49 + name: string,
50 + command: { handler: (args: string, ctx: any) => Promise<void> },
51 + ) => commands.set(name, command),
52 + setActiveTools: (tools: string[]) => activeTools.push(tools),
53 + setModel: async () => setModelResult,
54 + setThinkingLevel: (level: string) => {
55 + thinking = level;
56 + },
57 + } as never);
58 + return {
59 + activeTools,
60 + command: (args: string) => commands.get("mode")?.handler(args, ctx),
61 + ctx,
62 + entries,
63 + events,
64 + notes,
65 + setModelFindResult: (model: unknown) => {
66 + modelFindResult = model;
67 + },
68 + setModelResult: (result: boolean) => {
69 + setModelResult = result;
70 + },
71 + statuses,
72 + thinking: () => thinking,
73 + };
76 +async function withHome<T>(fn: (home: string) => T | Promise<T>): Promise<T> {
77 + const oldHome = process.env.HOME;
78 + const oldUserProfile = process.env.USERPROFILE;
79 + const root = mkdtempSync(path.join(tmpdir(), "mode-cov-home-"));
80 + const home = path.join(root, "home");
81 + process.env.HOME = home;
82 + process.env.USERPROFILE = home;
83 + try {
84 + return await fn(home);
85 + } finally {
86 + if (oldHome === undefined) delete process.env.HOME;
87 + else process.env.HOME = oldHome;
88 + if (oldUserProfile === undefined) delete process.env.USERPROFILE;
89 + else process.env.USERPROFILE = oldUserProfile;
90 + rmSync(root, { recursive: true, force: true });
91 + }
94 +function writeMode(home: string, name: string, markdown: string): string {
95 + const dir = path.join(home, ".pi", "agent", "modes");
96 + mkdirSync(dir, { recursive: true });
97 + const file = path.join(dir, `${name}.md`);
98 + writeFileSync(file, markdown, "utf8");
99 + return file;
102 +describe("mode 100% coverage gate", () => {
103 + it("covers pure helpers", async () => {
104 + expect(__modeTest.frontmatterSplit("body")).toEqual({
105 + frontmatter: "",
106 + body: "body",
107 + });
108 + expect(__modeTest.frontmatterSplit("---\nopen")).toEqual({
109 + frontmatter: "",
110 + body: "---\nopen",
111 + });
112 + expect(__modeTest.frontmatterSplit("---\na: 1\n---\nbody")).toEqual({
113 + frontmatter: "a: 1",
114 + body: "body",
115 + });
116 + expect(__modeTest.frontmatterSplit("---\na: 1\n---\n\nbody")).toEqual({
117 + frontmatter: "a: 1",
118 + body: "body",
119 + });
120 + expect(
121 + __modeTest.parseModeMarkdown(
122 + "plan",
123 + "---\ndescription: d\nmodel: p/m\nreminder: r\nthinking: high\ntools: [read]\n---\nbody",
124 + ),
125 + ).toEqual({
126 + id: "plan",
127 + description: "d",
128 + model: "p/m",
129 + reminder: "r",
130 + thinking: "high",
131 + tools: ["read"],
132 + body: "body",
133 + });
134 + expect(__modeTest.parseModeMarkdown("empty", "---\n---\n")).toEqual({
135 + id: "empty",
136 + body: "",
137 + });
138 + expect(
139 + __modeTest.parseModeMarkdown("comment", "---\n# comment\n---\nbody"),
140 + ).toEqual({ id: "comment", body: "body" });
141 + expect(() => __modeTest.parseModeMarkdown("bad", "---\n[\n---\n")).toThrow(
142 + "invalid YAML",
143 + );
144 + expect(() =>
145 + __modeTest.parseModeMarkdown("bad", "---\n[1]\n---\n"),
146 + ).toThrow("frontmatter must be a mapping");
147 + expect(() =>
148 + __modeTest.parseModeMarkdown("bad", "---\ndescription: 1\n---\n"),
149 + ).toThrow("description must be a string");
150 + expect(() =>
151 + __modeTest.parseModeMarkdown("bad", "---\nmodel: 1\n---\n"),
152 + ).toThrow("model must be a string");
153 + expect(() =>
154 + __modeTest.parseModeMarkdown("bad", "---\nreminder: 1\n---\n"),
155 + ).toThrow("reminder must be a string");
156 + expect(() =>
157 + __modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\n"),
158 + ).toThrow("tools must be an array of strings");
159 + expect(() =>
160 + __modeTest.parseModeMarkdown("bad", "---\ntools: [read, 1]\n---\n"),
161 + ).toThrow("tools must be an array of strings");
162 + expect(() =>
163 + __modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\n"),
164 + ).toThrow("thinking must be one of");
165 + expect(() =>
166 + __modeTest.parseModeMarkdown("bad", "---\nthinking: 1\n---\n"),
167 + ).toThrow("thinking must be one of");
168 + expect(__modeTest.isValidModeId("a_1-b")).toBe(true);
169 + expect(__modeTest.isValidModeId("bad id")).toBe(false);
170 + expect(__modeTest.parseModelRef("p/m/x")).toEqual({
171 + provider: "p",
172 + modelId: "m/x",
173 + });
174 + expect(__modeTest.parseModelRef("bad")).toBeUndefined();
175 + expect(__modeTest.parseModelRef("/m")).toBeUndefined();
176 + expect(__modeTest.parseModelRef("p/")).toBeUndefined();
177 + expect(
178 + __modeTest.modePromptAddition({
179 + id: "plan",
180 + body: "body\n",
181 + reminder: "r",
182 + }),
183 + ).toContain("<mode_reminder>\nr\n</mode_reminder>");
184 + expect(
185 + __modeTest.modePromptAddition({ id: "plan", body: "body\n" }),
186 + ).not.toContain("mode_reminder");
187 + 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",
205 + });
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();
240 + const agentDir = mkdtempSync(path.join(tmpdir(), "mode-cov-"));
241 + try {
242 + const modes = path.join(agentDir, "modes");
243 + mkdirSync(modes);
244 + writeFileSync(path.join(modes, "plan.md"), "# Plan\n", "utf8");
245 + writeFileSync(path.join(modes, "skip.txt"), "skip", "utf8");
246 + writeFileSync(path.join(modes, "bad id.md"), "bad", "utf8");
247 + writeFileSync(
248 + path.join(modes, "bad.md"),
249 + "---\ntools: read\n---\n",
250 + "utf8",
251 + );
252 + const loaded = await __modeTest.loadModes(agentDir);
253 + expect([...loaded.modes.keys()]).toEqual(["plan"]);
254 + expect(loaded.warnings).toHaveLength(2);
255 + } finally {
256 + rmSync(agentDir, { recursive: true, force: true });
258 + const missing = mkdtempSync(path.join(tmpdir(), "mode-cov-"));
259 + try {
260 + expect(await __modeTest.loadModes(missing)).toEqual({
261 + modes: new Map(),
262 + warnings: [],
263 + });
264 + writeFileSync(path.join(missing, "modes"), "file", "utf8");
265 + await expect(__modeTest.loadModes(missing)).rejects.toThrow();
266 + } finally {
267 + rmSync(missing, { recursive: true, force: true });
269 + });
271 + it("covers extension runtime directly", async () => {
272 + await withHome(async (home) => {
273 + const f = fakeRuntime();
274 + expect(
275 + f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
276 + ).toBeUndefined();
277 + await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
278 + await f.command("reload-config");
279 + expect(f.notes.at(-1)).toEqual([
280 + "mode config: 0 mode(s), 0 warning(s)",
281 + "info",
282 + ]);
283 + await f.command("");
284 + expect(f.notes.at(-1)?.[0]).toContain("modes: none");
285 + 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 + });
293 + writeMode(home, "plain", "body");
294 + writeMode(
295 + home,
296 + "plan",
297 + "---\ndescription: d\ntools: [read, grep, missing]\nreminder: r\n---\nbody",
298 + );
299 + writeMode(home, "bad id", "bad");
300 + await f.command("");
301 + await f.command("status");
302 + await f.command("list");
303 + expect(f.notes.at(-1)?.[0]).toContain("plain");
304 + expect(f.notes.at(-1)?.[0]).toContain("plan — d");
305 + await f.command("reload-config");
306 + expect(f.notes.at(-1)).toEqual([
307 + "mode config: 2 mode(s), 1 warning(s)",
308 + "warning",
309 + ]);
310 + await f.command("unknown");
311 + expect(f.notes.at(-1)).toEqual(["unknown mode: unknown", "warning"]);
312 + await f.command("plan");
313 + expect(f.activeTools.at(-1)).toEqual(["read", "grep"]);
314 + expect(f.statuses.at(-1)).toEqual(["mode", "MODE plan"]);
315 + expect(
316 + f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
317 + ).toEqual({ systemPrompt: expect.stringContaining("active_mode: plan") });
318 + await f.command("normal");
319 + expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
320 + expect(
321 + f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
322 + ).toEqual({
323 + systemPrompt: expect.stringContaining("active_mode: normal"),
324 + });
325 + await f.command("plan");
326 + await f.command("none");
327 + expect(f.entries.at(-1)?.data).toMatchObject({
328 + activeMode: null,
329 + neutralize: true,
330 + reason: "off",
331 + });
332 + });
333 + });
335 + it("covers model, restore, compaction, shutdown", async () => {
336 + await withHome(async (home) => {
337 + const f = fakeRuntime();
338 + writeMode(home, "badref", "---\nmodel: bad\n---\nbody");
339 + await f.command("badref");
340 + expect(f.notes.at(-2)).toEqual([
341 + "mode badref: model not found: bad",
342 + "warning",
343 + ]);
344 + writeMode(
345 + home,
346 + "missing",
347 + "---\nmodel: nope/missing\nthinking: high\n---\nbody",
348 + );
349 + await f.command("missing");
350 + expect(f.thinking()).toBe("high");
351 + f.setModelFindResult({ id: "gpt", provider: "openai" });
352 + f.setModelResult(false);
353 + writeMode(home, "blocked", "---\nmodel: openai/gpt\n---\nbody");
354 + await f.command("blocked");
355 + expect(f.notes.at(-2)).toEqual([
356 + "mode blocked: model unavailable: openai/gpt",
357 + "warning",
358 + ]);
359 + f.setModelResult(true);
360 + writeMode(
361 + home,
362 + "deep",
363 + "---\nmodel: openai/gpt\nthinking: high\n---\nbody",
364 + );
365 + await f.command("deep");
366 + 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]);
387 + });
388 + });
390 + it("covers no-ui direct events", () => {
391 + const f: Fake = fakeRuntime();
392 + f.ctx.hasUI = false;
393 + 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 + });
403 + });
404 +});

extensions/mode/__tests__/harness.test.ts

Added
new 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__/unit.test.ts

Added
new file mode 100644
1 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
4 +import { describe, expect, it } from "vitest";
5 +import modeExtension, { __modeTest } from "../index.ts";
7 +const nowEntry = (data: unknown) => ({
8 + type: "custom",
9 + customType: "mode-state",
10 + data,
11 +});
13 +describe("mode pure helpers", () => {
14 + it("parses valid mode markdown", () => {
15 + const mode = __modeTest.parseModeMarkdown(
16 + "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`,
18 + );
19 + expect(mode).toEqual({
20 + id: "plan",
21 + description: "Read-only planning",
22 + model: "openai/gpt-5.2-codex",
23 + thinking: "high",
24 + tools: ["read", "grep"],
25 + reminder: "Stay read-only.",
26 + body: "# Plan\n\nBody.\n",
27 + });
28 + });
30 + it("splits frontmatter variants", () => {
31 + expect(__modeTest.frontmatterSplit("body")).toEqual({
32 + frontmatter: "",
33 + body: "body",
34 + });
35 + expect(__modeTest.frontmatterSplit("---\nmissing close")).toEqual({
36 + frontmatter: "",
37 + body: "---\nmissing close",
38 + });
39 + expect(__modeTest.frontmatterSplit("---\na: 1\n---\nbody")).toEqual({
40 + frontmatter: "a: 1",
41 + body: "body",
42 + });
43 + });
45 + it("allows empty body, empty frontmatter, and unknown keys", () => {
46 + expect(
47 + __modeTest.parseModeMarkdown("empty", "---\nunknown: ok\n---\n"),
48 + ).toEqual({
49 + id: "empty",
50 + body: "",
51 + });
52 + });
54 + it("rejects invalid frontmatter and field types", () => {
55 + expect(() =>
56 + __modeTest.parseModeMarkdown("bad", "---\n[1]\n---\nbody"),
57 + ).toThrow("mode bad: frontmatter must be a mapping");
58 + expect(() =>
59 + __modeTest.parseModeMarkdown("bad", "---\ndescription: 1\n---\nbody"),
60 + ).toThrow("mode bad: description must be a string");
61 + expect(() =>
62 + __modeTest.parseModeMarkdown("bad", "---\nmodel: 1\n---\nbody"),
63 + ).toThrow("mode bad: model must be a string");
64 + expect(() =>
65 + __modeTest.parseModeMarkdown("bad", "---\nreminder: 1\n---\nbody"),
66 + ).toThrow("mode bad: reminder must be a string");
67 + expect(() =>
68 + __modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\nbody"),
69 + ).toThrow("mode bad: tools must be an array of strings");
70 + expect(() =>
71 + __modeTest.parseModeMarkdown("bad", "---\ntools: [read, 1]\n---\nbody"),
72 + ).toThrow("mode bad: tools must be an array of strings");
73 + expect(() =>
74 + __modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\nbody"),
75 + ).toThrow(
76 + "mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
77 + );
78 + expect(() =>
79 + __modeTest.parseModeMarkdown("bad", "---\nthinking: 1\n---\nbody"),
80 + ).toThrow(
81 + "mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
82 + );
83 + });
85 + it("validates ids", () => {
86 + expect(__modeTest.isValidModeId("plan_1-build")).toBe(true);
87 + expect(__modeTest.isValidModeId("../plan")).toBe(false);
88 + expect(__modeTest.isValidModeId("plan mode")).toBe(false);
89 + });
91 + it("splits model ref at first slash", () => {
92 + expect(__modeTest.parseModelRef("openai/gpt-5.2/codex")).toEqual({
93 + provider: "openai",
94 + modelId: "gpt-5.2/codex",
95 + });
96 + expect(__modeTest.parseModelRef("missing-slash")).toBeUndefined();
97 + expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
98 + });
100 + it("renders active prompt addition", () => {
101 + const text = __modeTest.modePromptAddition({
102 + id: "plan",
103 + body: "# Body\n",
104 + reminder: "Stay read-only.",
105 + });
106 + expect(text).toContain("# Body");
107 + expect(text).toContain("<mode_kernel>");
108 + expect(text).toContain("active_mode: plan");
109 + expect(text).toContain(
110 + "<mode_reminder>\nStay read-only.\n</mode_reminder>",
111 + );
112 + expect(text.indexOf("# Body")).toBeLessThan(text.indexOf("<mode_kernel>"));
113 + expect(
114 + __modeTest.modePromptAddition({ id: "plain", body: "# Body\n" }),
115 + ).not.toContain("<mode_reminder>");
116 + });
118 + it("renders normal neutralizer", () => {
119 + expect(__modeTest.normalPromptAddition()).toBe(
120 + `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`,
121 + );
122 + });
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 + it("keeps malformed model refs unresolved", () => {
170 + expect(__modeTest.parseModelRef("/model")).toBeUndefined();
171 + expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
172 + expect(__modeTest.parseModelRef("provider/model/name")).toEqual({
173 + provider: "provider",
174 + modelId: "model/name",
175 + });
176 + });
178 + it("loads mode files and reports invalid files", async () => {
179 + const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
180 + try {
181 + const modesDir = path.join(agentDir, "modes");
182 + mkdirSync(modesDir);
183 + writeFileSync(path.join(modesDir, "plan.md"), "# Plan\n", "utf8");
184 + writeFileSync(path.join(modesDir, "notes.txt"), "skip", "utf8");
185 + writeFileSync(path.join(modesDir, "bad id.md"), "# Bad\n", "utf8");
186 + writeFileSync(
187 + path.join(modesDir, "bad-yaml.md"),
188 + "---\n[\n---\n",
189 + "utf8",
190 + );
191 + writeFileSync(
192 + path.join(modesDir, "bad-field.md"),
193 + "---\ndescription: 1\n---\n",
194 + "utf8",
195 + );
197 + const loaded = await __modeTest.loadModes(agentDir);
199 + expect([...loaded.modes.keys()]).toEqual(["plan"]);
200 + expect(loaded.warnings).toEqual(
201 + expect.arrayContaining([
202 + "ignored invalid mode id: bad id.md",
203 + "mode bad-field: description must be a string",
204 + ]),
205 + );
206 + expect(
207 + loaded.warnings.some((warning) => warning.includes("bad-yaml")),
208 + ).toBe(true);
209 + } finally {
210 + rmSync(agentDir, { recursive: true, force: true });
212 + });
214 + it("returns no modes when the mode directory is absent", async () => {
215 + const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
216 + try {
217 + const loaded = await __modeTest.loadModes(agentDir);
218 + expect(loaded.modes.size).toBe(0);
219 + expect(loaded.warnings).toEqual([]);
220 + } finally {
221 + rmSync(agentDir, { recursive: true, force: true });
223 + });
225 + it("throws non-missing mode directory read errors", async () => {
226 + const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
227 + try {
228 + writeFileSync(path.join(agentDir, "modes"), "not a dir", "utf8");
229 + await expect(__modeTest.loadModes(agentDir)).rejects.toThrow();
230 + } finally {
231 + rmSync(agentDir, { recursive: true, force: true });
233 + });
235 + it("renders status text", () => {
236 + expect(__modeTest.statusText("plan")).toBe("MODE plan");
237 + expect(__modeTest.statusText(null)).toBeUndefined();
238 + });
240 + it("handles no-UI shutdown and model-less compaction", () => {
241 + const events = new Map<string, (...args: unknown[]) => unknown>();
242 + const entries: unknown[] = [];
243 + modeExtension({
244 + appendEntry: (_type: string, data: unknown) => entries.push(data),
245 + events: { emit: () => undefined },
246 + getAllTools: () => [],
247 + on: (name: string, handler: (...args: unknown[]) => unknown) =>
248 + events.set(name, handler),
249 + registerCommand: () => undefined,
250 + setActiveTools: () => undefined,
251 + setModel: async () => true,
252 + setThinkingLevel: () => undefined,
253 + } as never);
255 + expect(() =>
256 + events.get("session_shutdown")?.({}, { hasUI: false } as never),
257 + ).not.toThrow();
258 + events.get("session_compact")?.({ compactionEntry: { id: "c1" } }, {
259 + model: undefined,
260 + } as never);
261 + expect(entries).toEqual([
263 + schemaVersion: 1,
264 + activeMode: null,
265 + neutralize: false,
266 + reason: "compaction",
267 + compactionEntryId: "c1",
268 + },
269 + ]);
270 + });
271 +});

extensions/mode/index.ts

Added
new file mode 100644
1 +import { readdir, readFile } from "node:fs/promises";
2 +import path from "node:path";
3 +import type {
4 + ExtensionAPI,
5 + ExtensionContext,
6 +} from "@earendil-works/pi-coding-agent";
7 +import { getAgentDir } from "@earendil-works/pi-coding-agent";
8 +import { parse as parseYaml } from "yaml";
10 +type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
12 +type Mode = {
13 + id: string;
14 + description?: string;
15 + model?: string;
16 + thinking?: ThinkingLevel;
17 + reminder?: string;
18 + tools?: string[];
19 + body: string;
20 +};
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 +type ModeRuntimeState = {
33 + activeModeId: string | null;
34 + neutralize: boolean;
35 + modes: Map<string, Mode>;
36 + warnings: string[];
37 +};
39 +type ModeEntryLike = {
40 + type?: unknown;
41 + customType?: unknown;
42 + data?: unknown;
43 +};
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 +const THINKING_LEVELS = [
51 + "off",
52 + "minimal",
53 + "low",
54 + "medium",
55 + "high",
56 + "xhigh",
57 +] as const;
58 +const MODE_ID_RE = /^[a-zA-Z0-9_-]+$/;
60 +function isValidModeId(id: string): boolean {
61 + return MODE_ID_RE.test(id);
64 +function frontmatterSplit(markdown: string): {
65 + frontmatter: string;
66 + body: string;
67 +} {
68 + const lines = markdown.split("\n");
69 + if (lines[0] !== "---") return { frontmatter: "", body: markdown };
70 + const close = lines.indexOf("---", 1);
71 + if (close === -1) return { frontmatter: "", body: markdown };
72 + let bodyLines = lines.slice(close + 1);
73 + if (bodyLines[0] === "") bodyLines = bodyLines.slice(1);
74 + return {
75 + frontmatter: lines.slice(1, close).join("\n"),
76 + body: bodyLines.join("\n"),
77 + };
80 +function parseModeMarkdown(id: string, markdown: string): Mode {
81 + const { frontmatter, body } = frontmatterSplit(
82 + markdown.replaceAll("\r\n", "\n"),
83 + );
84 + let raw: unknown = {};
85 + try {
86 + raw = frontmatter.trim() ? (parseYaml(frontmatter) ?? {}) : {};
87 + } catch (error) {
88 + throw new Error(`mode ${id}: invalid YAML: ${(error as Error).message}`);
89 + }
90 + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
91 + throw new Error(`mode ${id}: frontmatter must be a mapping`);
92 + }
93 + const data = raw as Record<string, unknown>;
94 + const mode: Mode = { id, body };
96 + if (data.description !== undefined)
97 + mode.description = requireString(id, "description", data.description);
98 + if (data.model !== undefined)
99 + mode.model = requireString(id, "model", data.model);
100 + if (data.reminder !== undefined)
101 + mode.reminder = requireString(id, "reminder", data.reminder);
102 + if (data.thinking !== undefined)
103 + mode.thinking = requireThinking(id, data.thinking);
104 + if (data.tools !== undefined)
105 + mode.tools = requireStringArray(id, "tools", data.tools);
106 + return mode;
109 +function requireString(id: string, field: string, value: unknown): string {
110 + if (typeof value !== "string")
111 + throw new Error(`mode ${id}: ${field} must be a string`);
112 + return value;
115 +function requireStringArray(
116 + id: string,
117 + field: string,
118 + value: unknown,
119 +): string[] {
120 + if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
121 + throw new Error(`mode ${id}: ${field} must be an array of strings`);
123 + return value;
126 +function requireThinking(id: string, value: unknown): ThinkingLevel {
127 + if (
128 + typeof value !== "string" ||
129 + !THINKING_LEVELS.includes(value as ThinkingLevel)
130 + ) {
131 + throw new Error(
132 + `mode ${id}: thinking must be one of ${THINKING_LEVELS.join(", ")}`,
133 + );
135 + return value as ThinkingLevel;
138 +function parseModelRef(ref: string): ModelRef | undefined {
139 + const slash = ref.indexOf("/");
140 + if (slash <= 0 || slash === ref.length - 1) return undefined;
141 + return { provider: ref.slice(0, slash), modelId: ref.slice(slash + 1) };
144 +function modePromptAddition(mode: Mode): string {
145 + const parts = [mode.body.trimEnd()];
146 + parts.push(
147 + `<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>`,
148 + );
149 + if (mode.reminder?.trim())
150 + parts.push(`<mode_reminder>\n${mode.reminder}\n</mode_reminder>`);
151 + return parts.filter(Boolean).join("\n\n");
154 +function normalPromptAddition(): string {
155 + 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;
178 + return undefined;
181 +async function loadModes(
182 + agentDir = getAgentDir(),
183 +): Promise<{ modes: Map<string, Mode>; warnings: string[] }> {
184 + const warnings: string[] = [];
185 + const modes = new Map<string, Mode>();
186 + const dir = path.join(agentDir, "modes");
187 + let entries: string[];
188 + try {
189 + entries = await readdir(dir);
190 + } catch (error) {
191 + if ((error as NodeJS.ErrnoException).code === "ENOENT")
192 + return { modes, warnings };
193 + throw error;
195 + for (const name of entries.sort()) {
196 + if (!name.endsWith(".md")) continue;
197 + const id = name.slice(0, -3);
198 + if (!isValidModeId(id)) {
199 + warnings.push(`ignored invalid mode id: ${name}`);
200 + continue;
202 + try {
203 + modes.set(
204 + id,
205 + parseModeMarkdown(id, await readFile(path.join(dir, name), "utf8")),
206 + );
207 + } catch (error) {
208 + warnings.push((error as Error).message);
211 + return { modes, warnings };
214 +function modeLine(mode: Mode): string {
215 + 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 {
223 + 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 } : {};
233 +export default function modeExtension(pi: ExtensionAPI): void {
234 + const state: ModeRuntimeState = {
235 + activeModeId: null,
236 + neutralize: false,
237 + modes: new Map(),
238 + warnings: [],
239 + };
241 + async function reloadConfig(ctx?: ExtensionContext): Promise<void> {
242 + const loaded = await loadModes();
243 + state.modes = loaded.modes;
244 + state.warnings = loaded.warnings;
245 + 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);
263 + async function applyMode(mode: Mode, ctx: ExtensionContext): Promise<void> {
264 + if (mode.tools && mode.tools.length > 0) {
265 + const all = new Set(pi.getAllTools().map((tool) => tool.name));
266 + const valid = mode.tools.filter((tool) => all.has(tool));
267 + const unknown = mode.tools.filter((tool) => !all.has(tool));
268 + for (const tool of unknown) {
269 + ctx.ui.notify(
270 + `mode ${mode.id}: unknown tool ignored: ${tool}`,
271 + "warning",
272 + );
274 + pi.setActiveTools(valid);
275 + ctx.ui.notify(`mode ${mode.id}: tools ${valid.join(", ")}`, "info");
277 + if (mode.model) {
278 + const ref = parseModelRef(mode.model);
279 + const model = ref
280 + ? ctx.modelRegistry.find(ref.provider, ref.modelId)
281 + : undefined;
282 + if (!ref || !model)
283 + ctx.ui.notify(
284 + `mode ${mode.id}: model not found: ${mode.model}`,
285 + "warning",
286 + );
287 + else if (!(await pi.setModel(model))) {
288 + ctx.ui.notify(
289 + `mode ${mode.id}: model unavailable: ${mode.model}`,
290 + "warning",
291 + );
294 + if (mode.thinking) pi.setThinkingLevel(mode.thinking);
297 + async function switchMode(id: string, ctx: ExtensionContext): Promise<void> {
298 + await reloadConfig(ctx);
299 + const mode = state.modes.get(id);
300 + if (!mode) {
301 + ctx.ui.notify(`unknown mode: ${id}`, "warning");
302 + return;
304 + state.activeModeId = id;
305 + state.neutralize = false;
306 + await applyMode(mode, ctx);
307 + persist(ctx, "switch");
308 + publishStatus(ctx, id);
309 + ctx.ui.notify(`mode ${id}`, "info");
312 + function modeOff(ctx: ExtensionContext): void {
313 + const hadMode = state.activeModeId !== null;
314 + state.activeModeId = null;
315 + state.neutralize = hadMode || state.neutralize;
316 + persist(ctx, "off");
317 + publishStatus(ctx, null);
318 + ctx.ui.notify("mode off", "info");
321 + function showStatus(ctx: ExtensionContext): void {
322 + const active = state.activeModeId ?? "normal";
323 + const modes = [...state.modes.values()].map(modeLine);
324 + const warnings = state.warnings.map((warning) => `warning: ${warning}`);
325 + ctx.ui.notify(
327 + `active: ${active}`,
328 + modes.length ? `modes:\n${modes.join("\n")}` : "modes: none",
329 + ...warnings,
330 + ].join("\n"),
331 + "info",
332 + );
335 + pi.registerCommand("mode", {
336 + description: "Switch session-local mode",
337 + handler: async (args, ctx) => {
338 + const arg = args.trim();
339 + if (!arg || arg === "status") {
340 + await reloadConfig(ctx);
341 + showStatus(ctx);
342 + return;
344 + if (arg === "list") {
345 + await reloadConfig(ctx);
346 + showStatus(ctx);
347 + return;
349 + if (arg === "reload-config") {
350 + await reloadConfig(ctx);
351 + ctx.ui.notify(
352 + `mode config: ${state.modes.size} mode(s), ${state.warnings.length} warning(s)`,
353 + state.warnings.length ? "warning" : "info",
354 + );
355 + return;
357 + if (arg === "off" || arg === "normal" || arg === "none") {
358 + modeOff(ctx);
359 + return;
361 + await switchMode(arg, ctx);
362 + },
363 + });
365 + pi.on("before_agent_start", (event) => {
366 + const mode = state.activeModeId
367 + ? state.modes.get(state.activeModeId)
368 + : undefined;
369 + if (mode)
370 + return {
371 + systemPrompt: `${event.systemPrompt}\n\n${modePromptAddition(mode)}`,
372 + };
373 + if (state.neutralize) {
374 + return {
375 + systemPrompt: `${event.systemPrompt}\n\n${normalPromptAddition()}`,
376 + };
378 + });
380 + pi.on("session_start", async (_event, ctx) => {
381 + 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");
400 + publishStatus(ctx, state.activeModeId);
401 + });
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));
409 +export const __modeTest = {
410 + frontmatterSplit,
411 + isValidModeId,
412 + latestModeState,
413 + loadModes,
414 + modePromptAddition,
415 + normalPromptAddition,
416 + parseModeMarkdown,
417 + parseModelRef,
418 + statusText,

extensions/mode/package.json

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