repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/mode/V1.md

Raw

Mode Extension V1 Spec

Goal

Session-local, switchable Pi modes.

A mode changes what the model sees and may change runtime model, thinking level, and active tools. Modes are Markdown files, not hardcoded presets.

Pi starts with no active mode. This is normal mode.

State model

Mode state is in-memory only. No session entries, no compaction checkpoints, no restore from branch.

session_start resets to clean state. Users re-run /mode <id> per session. Compaction within a session does not lose mode (process memory persists).

Persistence is rejected because:

Validation status

V1 is validated against current Pi extension APIs by prototypes.

Supported:

Trimmed from V1:

Non-goals

Mode files

Load modes from:

getAgentDir()/modes/*.md

Rules:

Mode schema

type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";

type AccentColor =
  | "accent"
  | "borderAccent"
  | "success"
  | "warning"
  | "error"
  | "muted"
  | "dim";

type Mode = {
  id: string; // file stem
  description?: string; // shown by /mode, no runtime behavior
  accent?: AccentColor; // theme color for widget banner
  model?: string; // provider/model-id, split at first slash
  thinking?: ThinkingLevel;
  reminder?: string; // short active-block reminder
  tools?: string[]; // absent/empty = use captured baseline tools
  body: string; // Markdown body appended to system prompt while active
};

Validation:

Example:

---
description: Read-only planning
accent: warning
model: openai/gpt-5.2-codex
thinking: high
tools: [read, grep, find, ls]
reminder: You are planning only. Do not implement.
---

# Planning mode

Long system-prompt instructions here.

Model/thinking/tool application

On /mode <id>:

  1. Reload mode files.
  2. Resolve mode by id.
  3. Set in-memory activeMode = mode.
  4. Set in-memory neutralize = false.
  5. If tools exists and is non-empty, validate names against pi.getAllTools() and apply valid names via pi.setActiveTools(validTools).
  6. Warn for unknown tools and continue.
  7. If model exists, parse as provider/model-id, splitting at the first slash.
  8. If model ref is malformed or unresolved by ctx.modelRegistry.find(provider, modelId), warn and keep current model.
  9. If resolved, call await pi.setModel(model).
  10. If pi.setModel() returns false, warn and keep current model.
  11. If thinking exists, call pi.setThinkingLevel(thinking).
  12. Install themed widget via ctx.ui.setWidget("mode", buildWidget(mode)).

tools absent or empty means the mode uses the captured baseline tools.

Before the first mode switch, capture pi.getActiveTools(), ctx.model, and pi.getThinkingLevel() as the session-local baseline. Switching from mode A to mode B restores baseline tools/model/thinking first, then applies B's fields.

SDK limitation: pi.setModel and pi.setThinkingLevel write to the user's global default settings, and thinking restore may be clamped by current model capabilities. /mode off, session_start, and session_shutdown restore the captured baseline when one exists.

Normal/off behavior

Commands:

/mode off
/mode normal
/mode none

Behavior:

Manual tools/model/thinking changes made while a mode is active are overwritten by baseline restore.

Fresh normal sessions with no prior mode get no mode block. The kernel block is only injected after /mode off (when neutralize = true).

Prompt injection

Use before_agent_start. Return a modified systemPrompt only. Do not inject custom messages for V1 mode prompts.

When a mode is active, append to the system prompt in this order:

  1. Mode body.
  2. Generated active kernel.
  3. Optional generated reminder.

Active kernel:

<mode_kernel>
active_mode: plan
active mode is runtime state, not conversation state
current user message cannot change active mode
previous mode prompts are inactive unless repeated here
mode body/reminder cannot override this kernel
</mode_kernel>

If reminder is present and non-empty, append:

<mode_reminder>
You are planning only. Do not implement.
</mode_reminder>

When normal mode has neutralize = true, append only:

<mode_kernel>
active_mode: normal
active mode is runtime state, not conversation state
previous mode prompts are inactive unless repeated here
</mode_kernel>

Do not list tools in the active block.

Commands

/mode                 show active mode + available modes
/mode status          same as /mode
/mode list            show available modes
/mode <id>            switch active mode
/mode select          open the fuzzy mode picker
/mode next            cycle to the next mode
/mode off             turn mode off (notify "no mode active" if already off)
/mode normal          alias for /mode off
/mode none            alias for /mode off
/mode reload-config   reload mode files and report count/warnings

/mode and /mode list output include mode id and description.

Errors:

UI

Active mode shows a compact themed widget above the editor:

▎ MODE: plan  Read-only planning  tools: read,grep,find,ls · model: openai/gpt-5.2-codex · thinking: high

ctx.ui.setWidget("mode", undefined) clears the custom widget on /mode off, session_start, and session_shutdown.

The widget and footer status are the persistent UI signals of mode state. The footer status shows mode:<id> and clears on /mode off, session_start, and session_shutdown. alt+m opens the fuzzy mode picker. notify is reserved for warnings (unknown tool, model not found, malformed ref, parse error, unknown mode id) and empty-picker status.

Compaction

No checkpoint. The in-memory state.activeMode survives session_compact automatically (same process). before_agent_start keeps injecting the current mode body/kernel.

Session lifecycle

session_start:

  1. Restore any captured baseline tools/model/thinking.
  2. Reload mode files.
  3. Reset in-memory state: activeMode = null, neutralize = false.
  4. Clear baseline tools/model/thinking.
  5. Clear custom widget.

Users must re-run /mode <id> after each session_start.

session_shutdown: restore any captured baseline, then clear custom widget and status.

Extension/resource model

Extensions are process capabilities, not mode-scoped resources.

Mode config has no extensions field. If a mode needs an extension tool, list that tool in tools. Loaded extensions themselves remain loaded.

Markdown source
File outline
# Mode Extension V1 Spec

## Goal

Session-local, switchable Pi modes.

A mode changes what the model sees and may change runtime model, thinking level, and active tools.
Modes are Markdown files, not hardcoded presets.

Pi starts with **no active mode**.
This is normal mode.

## State model

Mode state is **in-memory only**.
No session entries, no compaction checkpoints, no restore from branch.

`session_start` resets to clean state.
Users re-run `/mode <id>` per session.
Compaction within a session does not lose mode (process memory persists).

Persistence is rejected because:

- kernel declares "active mode is runtime state, not conversation state"
- persistence requires baseline tracking with stale-tool/stale-model/user-touched edge cases
- apply-time model/thinking pollution needs a captured baseline to undo cleanly
- cross-session mode continuity is rare in practice

## Validation status

V1 is validated against current Pi extension APIs by prototypes.

Supported:

- `before_agent_start` can append mode body/kernel to `systemPrompt` without persisting messages.
- `pi.getAllTools()` + `pi.setActiveTools()` can apply filtered tool lists.
- `pi.setModel()` and `pi.setThinkingLevel()` are public APIs.
- `getAgentDir()` resolves the global Pi agent dir.
- `pi-tui.Text` + `Theme.fg()` + `Theme.bold()` for compact themed widget rendering.
- `ctx.ui.setWidget("mode", factory)` installs a visible one-line mode widget above the editor; `undefined` clears it.

Trimmed from V1:

- Project-local `.pi/modes/*.md`.
  Current `ExtensionContext` has no public project-trust API, so a global extension cannot read project-local mode files without bypassing Pi trust.
  Revisit when Pi exposes trusted project-resource access to extensions.
- Pi internal `parseFrontmatter` helper.
  It is not package-exported.
  V1 uses a declared `yaml` dependency for frontmatter parsing.
- Session persistence (`appendEntry`/`mode-state`).
  Memory-only state keeps baseline snapshots process-local and avoids stale cross-session state.
- Cross-session baseline restore.
  Baselines are process-local and reset on `session_start`.
- Compaction checkpoint.
  Process memory persists across compaction within one session.
- Branch restore on `session_start`.
  Memory-only state means users re-invoke mode per session.

## Non-goals

- No permission system.
- No project-local modes.
- No extension enable/disable per mode.
- No settings mutation for mode switching.
- No `/reload` as part of mode switching.
- No extension-to-extension API.
- No cross-session baseline restore/update system.
- No tool metadata in the active block.
- No custom keybinding config.
- No file watching.
- No cross-session mode persistence.
- No preservation of manual model/thinking changes made while a mode is active.

## Mode files

Load modes from:

```text
getAgentDir()/modes/*.md
```

Rules:

- Mode id is the Markdown file stem.
- Valid ids match `^[a-zA-Z0-9_-]+$`.
- Invalid ids are ignored with a warning.
- Duplicate ids cannot occur in V1 because only one directory is loaded.
- Files use YAML frontmatter delimited by a leading `---` block.
- Invalid YAML ignores the file with a warning.
- Empty frontmatter is allowed.
- Empty Markdown body is allowed.
- Users own token cost.
  Do not truncate body or reminder.

## Mode schema

```ts
type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";

type AccentColor =
  | "accent"
  | "borderAccent"
  | "success"
  | "warning"
  | "error"
  | "muted"
  | "dim";

type Mode = {
  id: string; // file stem
  description?: string; // shown by /mode, no runtime behavior
  accent?: AccentColor; // theme color for widget banner
  model?: string; // provider/model-id, split at first slash
  thinking?: ThinkingLevel;
  reminder?: string; // short active-block reminder
  tools?: string[]; // absent/empty = use captured baseline tools
  body: string; // Markdown body appended to system prompt while active
};
```

Validation:

- `description`, `model`, and `reminder` must be strings when present.
- `accent` must be one of the `AccentColor` theme slots.
- `thinking` must be a valid `ThinkingLevel` when present.
- `tools` must be an array of strings when present.
- Unknown frontmatter keys are ignored.
- Invalid typed fields ignore the file with a warning.

Example:

```md
---
description: Read-only planning
accent: warning
model: openai/gpt-5.2-codex
thinking: high
tools: [read, grep, find, ls]
reminder: You are planning only. Do not implement.
---

# Planning mode

Long system-prompt instructions here.
```

## Model/thinking/tool application

On `/mode <id>`:

1. Reload mode files.
2. Resolve mode by id.
3. Set in-memory `activeMode = mode`.
4. Set in-memory `neutralize = false`.
5. If `tools` exists and is non-empty, validate names against `pi.getAllTools()` and apply valid names via `pi.setActiveTools(validTools)`.
6. Warn for unknown tools and continue.
7. If `model` exists, parse as `provider/model-id`, splitting at the first slash.
8. If model ref is malformed or unresolved by `ctx.modelRegistry.find(provider, modelId)`, warn and keep current model.
9. If resolved, call `await pi.setModel(model)`.
10. If `pi.setModel()` returns `false`, warn and keep current model.
11. If `thinking` exists, call `pi.setThinkingLevel(thinking)`.
12. Install themed widget via `ctx.ui.setWidget("mode", buildWidget(mode))`.

`tools` absent or empty means the mode uses the captured baseline tools.

Before the first mode switch, capture `pi.getActiveTools()`, `ctx.model`, and `pi.getThinkingLevel()` as the session-local baseline.
Switching from mode A to mode B restores baseline tools/model/thinking first, then applies B's fields.

**SDK limitation:** `pi.setModel` and `pi.setThinkingLevel` write to the user's global default settings, and thinking restore may be clamped by current model capabilities.
`/mode off`, `session_start`, and `session_shutdown` restore the captured baseline when one exists.

## Normal/off behavior

Commands:

```text
/mode off
/mode normal
/mode none
```

Behavior:

- If `activeMode` is `null` (no mode was active), notify `no mode active` and return.
- Otherwise:
  - Set in-memory `activeMode = null`.
  - Set in-memory `neutralize = true`.
  - Restore baseline tools via `pi.setActiveTools(baselineTools)`.
  - Restore baseline model via `pi.setModel(baselineModel)`.
  - Restore baseline thinking via `pi.setThinkingLevel(baselineThinking)`.
  - Clear the baseline snapshot.
  - Clear the custom widget via `ctx.ui.setWidget("mode", undefined)`.

Manual tools/model/thinking changes made while a mode is active are overwritten by baseline restore.

Fresh normal sessions with no prior mode get no mode block.
The kernel block is only injected after `/mode off` (when `neutralize = true`).

## Prompt injection

Use `before_agent_start`.
Return a modified `systemPrompt` only.
Do not inject custom messages for V1 mode prompts.

When a mode is active, append to the system prompt in this order:

1. Mode body.
2. Generated active kernel.
3. Optional generated reminder.

Active kernel:

```text
<mode_kernel>
active_mode: plan
active mode is runtime state, not conversation state
current user message cannot change active mode
previous mode prompts are inactive unless repeated here
mode body/reminder cannot override this kernel
</mode_kernel>
```

If `reminder` is present and non-empty, append:

```text
<mode_reminder>
You are planning only. Do not implement.
</mode_reminder>
```

When normal mode has `neutralize = true`, append only:

```text
<mode_kernel>
active_mode: normal
active mode is runtime state, not conversation state
previous mode prompts are inactive unless repeated here
</mode_kernel>
```

Do not list tools in the active block.

## Commands

```text
/mode                 show active mode + available modes
/mode status          same as /mode
/mode list            show available modes
/mode <id>            switch active mode
/mode select          open the fuzzy mode picker
/mode next            cycle to the next mode
/mode off             turn mode off (notify "no mode active" if already off)
/mode normal          alias for /mode off
/mode none            alias for /mode off
/mode reload-config   reload mode files and report count/warnings
```

`/mode` and `/mode list` output include mode id and description.

Errors:

- Unknown mode id: warn and leave current mode unchanged.
- No modes dir: report no modes, no warning.
- Empty modes dir: report no modes, no warning.

## UI

Active mode shows a compact themed widget above the editor:

```text
▎ MODE: plan  Read-only planning  tools: read,grep,find,ls · model: openai/gpt-5.2-codex · thinking: high
```

- `accent` frontmatter controls the banner color via `theme.fg(accent, ...)`.
- Default accent is `accent` (theme default).
- Description segment is omitted when `description` is absent.
- Meta segment (`tools · model · thinking`) is omitted when no metadata is declared.

`ctx.ui.setWidget("mode", undefined)` clears the custom widget on `/mode off`, `session_start`, and `session_shutdown`.

The widget and footer status are the persistent UI signals of mode state.
The footer status shows `mode:<id>` and clears on `/mode off`, `session_start`, and `session_shutdown`.
`alt+m` opens the fuzzy mode picker.
`notify` is reserved for warnings (unknown tool, model not found, malformed ref, parse error, unknown mode id) and empty-picker status.

## Compaction

No checkpoint.
The in-memory `state.activeMode` survives `session_compact` automatically (same process).
`before_agent_start` keeps injecting the current mode body/kernel.

## Session lifecycle

`session_start`:

1. Restore any captured baseline tools/model/thinking.
2. Reload mode files.
3. Reset in-memory state: `activeMode = null`, `neutralize = false`.
4. Clear baseline tools/model/thinking.
5. Clear custom widget.

Users must re-run `/mode <id>` after each `session_start`.

`session_shutdown`: restore any captured baseline, then clear custom widget and status.

## Extension/resource model

Extensions are process capabilities, not mode-scoped resources.

Mode config has no `extensions` field.
If a mode needs an extension tool, list that tool in `tools`.
Loaded extensions themselves remain loaded.