# UI/UX Overhaul Plan: Subagent Management in pi-subagents

## Executive Summary

Overhaul the `/agents` interactive terminal UI to match Claude Code's rich subagent management experience — but adapted for pi's `ctx.ui.*` API (select, input, editor, notify — no Ink/React). The core gap is that current pi-subagents uses flat serial prompts, while Claude Code has a full TUI with categorized tool selection, model browsing from config, multi-step creation wizard, and rich agent detail views.

---

## 1. Current State vs Target

| Aspect | Current pi-subagents | Target (Claude Code-level) |
|--------|---------------------|---------------------------|
| Model selection | Hardcoded haiku/sonnet/opus/inherit/custom text input | Scan `~/.pi/agent/models.json` for available models, present as categorized select |
| Tool selection | Text input: "all/none/read-only/custom, type comma list" | Categorized: Read-only, Edit, Execution, MCP, Other — checkbox-style select |
| Agent creation | Two paths (generate/manual), serial prompts | Single multi-step wizard with consistent flow |
| Agent detail view | Just name + description | Full card: model, tools, source, memory, thinking, config tags |
| Agent list view | Flat list with simple indicators | Grouped by source (built-in, project, global), override-aware |
| Agent editing | Open-in-editor or delete | Edit tools, model, color — rich inline |
| Settings | Flat select → edit individual values | Keep current approach (it works) |
| Running agents | Select → view conversation | Same approach is fine |

---

## 2. Architecture: New UI Module

Create **`src/ui/agent-menu.ts`** — the new interactive agent management hub.

All menu interactions go through `ctx.ui.*` primitives:
- `ctx.ui.select(title, options)` — choice lists
- `ctx.ui.input(title, placeholder)` — text entry
- `ctx.ui.editor(title, initial)` — multi-line edit
- `ctx.ui.confirm(title, message)` — yes/no
- `ctx.ui.notify(message, type)` — feedback

No external TUI dependencies. No Ink/React.

---

## 3. File Map

```
src/
  ui/
    agent-menu.ts          — NEW: /agents command hub, top-level routing
    agent-list.ts          — NEW: Rich agent list with source grouping + override indicators
    agent-detail.ts        — NEW: Agent detail card view
    agent-editor.ts        — NEW: Inline editing (tools, model, color)  
    create-wizard.ts       — NEW: Multi-step agent creation wizard
    model-picker.ts        — NEW: Model picker that scans models.json
    tool-picker.ts         — NEW: Categorized tool selection
    schedule-menu.ts       — EXISTING: Keep as-is, minor integration
    agent-widget.ts        — EXISTING: Keep as-is
    conversation-viewer.ts — EXISTING: Keep as-is
  model-resolver.ts        — EXISTING: Keep, add scanModelsConfig utility
  settings.ts              — EXISTING: Keep
  index.ts                 — MODIFY: Replace inline menu logic with agent-menu.ts calls
```

---

## 4. New Modules — Detailed Design

### 4a. `src/ui/agent-menu.ts` — Agent Command Hub

**Top-level `/agents` menu:**

```
┌─ Agents ─────────────────────────────┐
│  Running agents (3) — 1 running, 2 done│
│  Agent types (7)                      │
│  Scheduled jobs (2)                   │
│  ──────────────────────────            │
│  Create new agent                     │
│  Settings                             │
└────────────────────────────────────────┘
```

Routing logic (already exists in `_showAgentsMenu`, refactor into module):
- Running agents → agent-list.ts (running view)
- Agent types → agent-list.ts (all agents view)
- Scheduled jobs → schedule-menu.ts (existing)
- Create new agent → create-wizard.ts
- Settings → settings.ts (existing)

### 4b. `src/ui/agent-list.ts` — Rich Agent List

**Agent types list** — grouped view with source indicators:

```
┌─ Agent types (7) ─────────────────────┐
│  Built-in:                            │
│    general-purpose · inherit           │
│    Explore · haiku                     │
│    Plan · sonnet                       │
│                                        │
│  Project (.pi/agents/):               │
│  • code-reviewer · inherit             │
│  • security-auditor · haiku           │
│                                        │
│  Global (~/.pi/agent/agents/):        │
│  ◦ test-writer · sonnet               │
│  ✕◦ legacy-bot · inherit (disabled)   │
└────────────────────────────────────────┘
```

Key features:
- **Group by source**: Built-in → Project → Global
- **Source indicator**: `•` = project, `◦` = global, `✕` = disabled
- **Model shown** next to name (resolved to human-readable label)
- **Override awareness**: project agents that shadow built-ins shown with warning
- **Select agent → detail view**

### 4c. `src/ui/agent-detail.ts` — Agent Detail Card

When user selects an agent from the list:

```
┌─ code-reviewer ───────────────────────┐
│  Description: Reviews code for issues │
│  Source: Project (.pi/agents/)        │
│  Model: Inherit from parent           │
│  Tools: read, bash, grep, find, ls    │
│  Prompt mode: replace                 │
│  Memory: none                         │
│  Thinking: inherit                    │
│  Max turns: unlimited                 │
│  Extensions: inherit all              │
│  Skills: inherit all                  │
│                                        │
│  > Edit                               │
│  > Disable                            │
│  > Delete                             │
│  > Back                               │
└────────────────────────────────────────┘
```

For built-in agents:
```
│  > Eject (export as .md)              │
│  > Disable                            │
│  > View system prompt                 │
```

### 4d. `src/ui/agent-editor.ts` — Agent Editor

Edit menu for custom/project agents:

```
┌─ Edit: code-reviewer ─────────────────┐
│  Source: Project (.pi/agents/)         │
│                                        │
│  > Open in editor                      │
│  > Edit tools                          │
│  > Edit model                          │
│  > Edit description                    │
│  > Edit system prompt                  │
│  > Edit memory scope                   │
│  > Edit config flags                   │
└────────────────────────────────────────┘
```

Each sub-action uses appropriate ctx.ui primitive:
- **Edit tools** → tool-picker.ts
- **Edit model** → model-picker.ts
- **Edit description** → `ctx.ui.input()`
- **Edit system prompt** → `ctx.ui.editor()`
- **Edit memory** → `ctx.ui.select()` (none/user/project/local)
- **Edit config flags** → serial toggles via `ctx.ui.select()`

### 4e. `src/ui/create-wizard.ts` — Multi-Step Creation Wizard

New structured wizard replacing `showGenerateWizard` + `showManualWizard`:

```
Step 1: Method
┌─ Create method ───────────────────────┐
│  > AI-generated — Describe and let AI │
│    craft the agent definition          │
│  > Manual — Walk through each setting │
│    step by step                        │
└────────────────────────────────────────┘

Step 2a (Generate path):
- Describe what agent should do (input)
- Choose name (input)  
- AI generates full agent .md

Step 2b (Manual path):
- Name (input)
- Description (input)
- Tools (→ tool-picker.ts)
- Model (→ model-picker.ts)
- Thinking level (select)
- Extensions (select: all/none/custom)
- Skills (select: all/none/custom)
- Memory (select: none/user/project/local)
- Run in background (confirm)
- Inherit context (confirm)
- System prompt (editor)

Step 3: Location
┌─ Choose location ─────────────────────┐
│  > Project (.pi/agents/)              │
│  > Personal (~/.pi/agent/agents/)     │
└────────────────────────────────────────┘

Step 4: Confirm + Create
(Shows summary, confirms, writes file)
```

### 4f. `src/ui/model-picker.ts` — Model Browser from models.json

**Core innovation**: Scan `~/.pi/agent/models.json` for available models.

```
┌─ Select model ────────────────────────┐
│  > Inherit from parent (recommended)  │
│  > Smart — Auto-choose best model     │
│  ── ccs-proxy ────                    │
│  > nvidia:glm-4.7 (CCS) — 256k ctx   │
│  > nvidia:kimi-k2-thinking (CCS)      │
│  > nvidia:minimax-m2.7 (CCS)          │
│  > copilot:gpt-4.1-2025-04-14 (CCS)  │
│  > bytedance:kimi-k2-250711 (CCS)    │
│  ── ollama ────                       │
│  > kimi-k2.6:cloud — 256k ctx        │
│  > deepseek-v4-flash:cloud — 1M ctx  │
│  > glm-5.1:cloud                      │
│  > ... (22 models)                    │
│  ── zai ────                          │
│  > glm-5.1 — 256k ctx                │
│  > glm-5                              │
│  > ...                                │
│  ── LM-studio ────                    │
│  > Gemma4-4-e4b (LM Studio)          │
│  > Qwen3.5-35bA3b (LM Studio)       │
│  ──────────────────────────            │
│  > Custom... (type provider/modelId)  │
└────────────────────────────────────────┘
```

Display for each model:
- Provider section headers
- Model name (from `models.json` → `name` field)
- Context window indicator: `— 256k ctx`, `— 1M ctx`
- Reasoning capability badge if `reasoning: true`
- Input modality tags if not text-only

Selection stores the `provider/modelId` string in the agent config.

### 4g. `src/ui/tool-picker.ts` — Categorized Tool Selection

```
┌─ Select tools ────────────────────────┐
│  [x] All tools                        │
│  ──────────────────────────            │
│  [x] Read-only tools                  │
│  [x] Edit tools                       │
│  [x] Execution tools                  │
│  [ ] MCP tools                        │
│  [ ] Other tools                      │
│  ──────────────────────────            │
│  > Show advanced (individual tools)   │
│  ──────────────────────────            │
│  [ Continue ]                         │
└────────────────────────────────────────┘
```

Categories (match Claude Code's bucketing):
- **Read-only**: read, bash, grep, find, ls
- **Edit**: edit, write
- **Execution**: bash (for write operations)
- **MCP**: All registered MCP tools
- **Other**: Catch-all

In advanced mode, show individual tool toggles.

---

## 5. models.json Integration

### New utility in `src/model-resolver.ts`:

```typescript
export interface ModelEntry {
  id: string;        // "nvidia:glm-4.7"
  name: string;      // "nvidia:glm-4.7 (CCS)"
  provider: string;  // "ccs-proxy"
  contextWindow: number;
  reasoning: boolean;
  inputTypes: string[];
}

export function scanModelsConfig(): Map<string, ModelEntry[]>;
  // Reads ~/.pi/agent/models.json
  // Returns providers → [models...]
  // Each provider is auth-ready (has apiKey + baseUrl configured)

export function getModelPickerOptions(): ModelPickerOption[];
  // Builds flat option list from scanModelsConfig()
  // Groups by provider with headers
  // Includes "inherit" + "custom..." special options
```

### Model label resolution:

```
provider/modelId → human-readable name from models.json
e.g., "ollama/deepseek-v4-flash:cloud" → "deepseek-v4-flash:cloud"
```

The agent's `model` field stores `provider/modelId` string. On display, resolve back to `models.json` name.

---

## 6. Index.ts Changes (Minimal)

In `src/index.ts`:

1. **Replace inline `_showAgentsMenu`** with delegation to `src/ui/agent-menu.ts`:
   - `_showAgentsMenu(ctx)` → `showAgentsMenu(ctx, manager, scheduler)`

2. **Replace inline `showAllAgentsList`** with `showAgentList(ctx)`

3. **Replace inline `showAgentDetail`** with `showAgentDetail(ctx, name)`

4. **Replace inline `showCreateWizard`** with `showCreateWizard(ctx)`

5. **Replace inline `showManualWizard`** + `showGenerateWizard` with wizard module

6. **Replace inline `showRunningAgents`** with `showRunningAgents(ctx, manager)`

7. **Replace inline `viewAgentConversation`** stays but delegates to conversation-viewer.ts

8. **Export helper functions** from index.ts that the UI modules need:
   - `findAgentFile`, `ejectAgent`, `disableAgent`, `enableAgent`
   - `reloadCustomAgents`
   - `getModelLabel`

---

## 7. Implementation Order

### Phase 1: Foundation (model + tool pickers)
1. Add `scanModelsConfig()` + `getModelPickerOptions()` to `model-resolver.ts`
2. Create `src/ui/model-picker.ts`
3. Create `src/ui/tool-picker.ts`

### Phase 2: Agent display
4. Create `src/ui/agent-list.ts` (rich agent list with grouping)
5. Create `src/ui/agent-detail.ts` (agent detail card)

### Phase 3: Editing + Creation
6. Create `src/ui/agent-editor.ts` (edit inline)
7. Create `src/ui/create-wizard.ts` (multi-step wizard)

### Phase 4: Integration
8. Create `src/ui/agent-menu.ts` (hub)
9. Modify `src/index.ts` — replace inline menu logic
10. Remove dead inline code (old showManualWizard, showGenerateWizard etc.)

---

## 8. Edge Cases & Considerations

### Model resolution
- Agent config stores `provider/modelId` string (e.g., `"ollama/qwen3.5:397b:cloud"`)
- On display, resolve back to models.json human name
- If model is no longer in models.json, show raw string with a `(unavailable)` warning
- `inherit` means use parent model (handled at runtime by agent-runner.ts)

### Tool selection
- "All tools" = omit tools field entirely (agent gets all available)
- Custom partial list = comma-separated in `tools` frontmatter
- Must handle MCP tools that may not be available at config-time
- Can't validate MCP tool names against current session — just store what user selected

### Agent file format compatibility
- Must preserve backward-compatible `.md` frontmatter format
- New fields (color, effort) are optional — old files still work
- Files written by Claude Code's format use `.claude/agents/` dir; pi uses `.pi/agents/`

### Migration path
- Existing `.pi/agents/*.md` files remain valid
- No schema migration needed — just richer UI for creating/editing
- Settings JSON format unchanged

### Provider grouping in model picker
- Models are grouped by provider (ccs-proxy, ollama, zai, LM-studio)
- Provider name comes from `models.json` keys
- Special provider names like "LM-studio" may have special chars — display as-is

---

## 9. Key Design Decisions

1. **No React/Ink** — Use `ctx.ui.*` primitives only. This keeps the extension lightweight and avoids pi version compatibility issues.

2. **models.json is the source of truth** — Not `ModelRegistry`. The registry is session-scoped and may not have loaded yet. Models.json is always available at config time.

3. **Provider/modelId as storage format** — The agent config stores the full ID (e.g., `"ollama/qwen3.5:397b:cloud"`). Human-readable names are for display only.

4. **Incremental build** — Each module is independently testable. Phase 1 can be shipped before Phase 3.

5. **Backward compat** — The old `showManualWizard` code path is replaced but the file format doesn't change. Existing agent files continue to work.

---

## 10. Files to Create / Modify

| Action | File | Description |
|--------|------|-------------|
| CREATE | `src/ui/agent-menu.ts` | Top-level agent command routing |
| CREATE | `src/ui/agent-list.ts` | Rich agent list grouped by source |
| CREATE | `src/ui/agent-detail.ts` | Agent detail card with actions |
| CREATE | `src/ui/agent-editor.ts` | Inline editing interface |
| CREATE | `src/ui/create-wizard.ts` | Multi-step creation wizard |
| CREATE | `src/ui/model-picker.ts` | Model browser scanning models.json |
| CREATE | `src/ui/tool-picker.ts` | Categorized tool selector |
| MODIFY | `src/model-resolver.ts` | Add `scanModelsConfig()`, `getModelPickerOptions()` |
| MODIFY | `src/index.ts` | Replace inline menu with agent-menu.ts delegates |
| KEEP | `src/ui/agent-widget.ts` | No changes needed |
| KEEP | `src/ui/conversation-viewer.ts` | No changes needed |
| KEEP | `src/ui/schedule-menu.ts` | Minor integration touch points |
| KEEP | `src/settings.ts` | No changes needed |
| KEEP | `src/types.ts` | No changes needed |
| KEEP | `src/custom-agents.ts` | No changes needed |
| KEEP | `src/agent-types.ts` | No changes needed |
| DELETE (after) | Inline `showManualWizard`, `showGenerateWizard`, `showAllAgentsList`, `showAgentDetail`, `showRunningAgents`, `viewAgentConversation`, `ejectAgent`, `disableAgent`, `enableAgent` from index.ts | Moved to ui/ modules |

---

## 11. Test Strategy

1. Unit test `scanModelsConfig()` with a fixture models.json
2. Unit test `getModelPickerOptions()` formatting
3. Unit test tool picker categorization
4. Integration test: walk through full create wizard series
5. Integration test: edit agent flow
6. Manual: verify all existing `.pi/agents/*.md` files remain valid

---

## 12. Risks

- **`ctx.ui.editor()` availability**: Not all pi modes (RPC, print) support editor. Guard with `ctx.hasUI` check.
- **`ctx.ui.select()` with many options**: ollama has 22 models, total could be 30+. Scrollable selects needed — check pi's select implementation handles this.
- **models.json parse errors**: Malformed models.json should show warning, not crash. model-picker should gracefully fall back to "inherit" + "custom..." only.
- **MCP tool names at config time**: MCP tools are session-specific. Tool picker shows them as available at config time, but they may not be available at runtime. This matches Claude Code's behavior.
