@phi-code-admin/phi-code 0.59.8 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,567 +1,554 @@
1
1
  <p align="center">
2
- <a href="https://shittycodingagent.ai">
3
- <img src="https://shittycodingagent.ai/logo.svg" alt="pi logo" width="128">
4
- </a>
5
- </p>
6
- <p align="center">
7
- <a href="https://discord.com/invite/3cU7Bz4UPx"><img alt="Discord" src="https://img.shields.io/badge/discord-community-5865F2?style=flat-square&logo=discord&logoColor=white" /></a>
8
- <a href="https://www.npmjs.com/package/@mariozechner/pi-coding-agent"><img alt="npm" src="https://img.shields.io/npm/v/@mariozechner/pi-coding-agent?style=flat-square" /></a>
9
- <a href="https://github.com/badlogic/pi-mono/actions/workflows/ci.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/badlogic/pi-mono/ci.yml?style=flat-square&branch=main" /></a>
2
+ <h1 align="center">Φ Phi Code</h1>
3
+ <p align="center"><strong>The Ultimate Open-Source Coding Agent</strong></p>
4
+ <p align="center">Built on <a href="https://github.com/badlogic/pi-mono">Pi</a> — supercharged with memory, sub-agents, orchestration, and smart routing.</p>
10
5
  </p>
6
+
11
7
  <p align="center">
12
- <a href="https://pi.dev">pi.dev</a> domain graciously donated by
13
- <br /><br />
14
- <a href="https://exe.dev"><img src="docs/images/exy.png" alt="Exy mascot" width="48" /><br />exe.dev</a>
8
+ <a href="https://www.npmjs.com/package/@phi-code-admin/phi-code"><img alt="npm" src="https://img.shields.io/npm/v/@phi-code-admin/phi-code?style=flat-square&label=npm" /></a>
9
+ <a href="https://github.com/uglyswap/phi-code"><img alt="GitHub" src="https://img.shields.io/badge/github-phi--code-181717?style=flat-square&logo=github" /></a>
10
+ <a href="https://github.com/uglyswap/phi-code/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-green?style=flat-square" /></a>
15
11
  </p>
16
12
 
17
- Pi is a minimal terminal coding harness. Adapt pi to your workflows, not the other way around, without having to fork and modify pi internals. Extend it with TypeScript [Extensions](#extensions), [Skills](#skills), [Prompt Templates](#prompt-templates), and [Themes](#themes). Put your extensions, skills, prompt templates, and themes in [Pi Packages](#pi-packages) and share them with others via npm or git.
13
+ ---
14
+
15
+ ## What is Phi Code?
16
+
17
+ Phi Code is a **production-grade** coding agent for the terminal. It extends [Pi](https://github.com/badlogic/pi-mono) (the minimal terminal coding harness) with everything you need for serious development work:
18
18
 
19
- Pi ships with powerful defaults but skips features like sub agents and plan mode. Instead, you can ask pi to build what you want or install a third party pi package that matches your workflow.
19
+ - 🧠 **Persistent Memory** Notes, ontology, and vector search across sessions
20
+ - 🤖 **5 Sub-Agents** — Specialized agents for code, exploration, planning, review, and testing
21
+ - 🎯 **Smart Routing** — Automatically assigns the right model to the right task
22
+ - 📋 **Orchestrator** — Plan complex projects, execute with parallel sub-agents
23
+ - 🔍 **Web Search** — Brave API integration for real-time research
24
+ - ⚡ **Benchmark** — Test your models and find the best ones for each role
25
+ - 🧩 **12 Built-in Skills** — API design, security, testing, DevOps, and more
26
+ - 🔌 **Provider-Neutral** — Works with any OpenAI-compatible API
20
27
 
21
- Pi runs in four modes: interactive, print or JSON, RPC for process integration, and an SDK for embedding in your own apps. See [openclaw/openclaw](https://github.com/openclaw/openclaw) for a real-world SDK integration.
28
+ **Phi Code works with any LLM provider:** Alibaba Cloud, OpenAI, Anthropic, Google, OpenRouter, Groq, Ollama, LM Studio, and more.
29
+
30
+ ---
22
31
 
23
32
  ## Table of Contents
24
33
 
25
34
  - [Quick Start](#quick-start)
35
+ - [Setup Wizard](#setup-wizard)
36
+ - [API Key Management](#api-key-management)
26
37
  - [Providers & Models](#providers--models)
27
- - [Interactive Mode](#interactive-mode)
28
- - [Editor](#editor)
29
- - [Commands](#commands)
30
- - [Keyboard Shortcuts](#keyboard-shortcuts)
31
- - [Message Queue](#message-queue)
38
+ - [Commands](#commands)
39
+ - [Sub-Agents](#sub-agents)
40
+ - [Orchestrator](#orchestrator)
41
+ - [Memory System](#memory-system)
42
+ - [Smart Routing](#smart-routing)
43
+ - [Benchmark](#benchmark)
44
+ - [Skills](#skills)
45
+ - [Extensions](#extensions)
46
+ - [Configuration Files](#configuration-files)
47
+ - [Keyboard Shortcuts](#keyboard-shortcuts)
32
48
  - [Sessions](#sessions)
33
- - [Branching](#branching)
34
- - [Compaction](#compaction)
35
- - [Settings](#settings)
36
- - [Context Files](#context-files)
37
- - [Customization](#customization)
38
- - [Prompt Templates](#prompt-templates)
39
- - [Skills](#skills)
40
- - [Extensions](#extensions)
41
- - [Themes](#themes)
42
- - [Pi Packages](#pi-packages)
43
- - [Programmatic Usage](#programmatic-usage)
44
- - [Philosophy](#philosophy)
45
49
  - [CLI Reference](#cli-reference)
50
+ - [Philosophy](#philosophy)
51
+ - [Credits](#credits)
46
52
 
47
53
  ---
48
54
 
49
55
  ## Quick Start
50
56
 
57
+ ### Install
58
+
51
59
  ```bash
52
- npm install -g @mariozechner/pi-coding-agent
60
+ npm install -g @phi-code-admin/phi-code
53
61
  ```
54
62
 
55
- Authenticate with an API key:
63
+ The installer automatically sets up:
64
+ - 9 extensions → `~/.phi/agent/extensions/`
65
+ - 5 sub-agent definitions → `~/.phi/agent/agents/`
66
+ - 12 skills → `~/.phi/agent/skills/`
67
+
68
+ ### First Run
56
69
 
57
70
  ```bash
58
- export ANTHROPIC_API_KEY=sk-ant-...
59
- pi
71
+ phi
60
72
  ```
61
73
 
62
- Or use your existing subscription:
74
+ Then run the setup wizard:
63
75
 
64
- ```bash
65
- pi
66
- /login # Then select provider
76
+ ```
77
+ /phi-init
67
78
  ```
68
79
 
69
- Then just talk to pi. By default, pi gives the model four tools: `read`, `write`, `edit`, and `bash`. The model uses these to fulfill your requests. Add capabilities via [skills](#skills), [prompt templates](#prompt-templates), [extensions](#extensions), or [pi packages](#pi-packages).
80
+ The wizard will:
81
+ 1. Ask you to **choose a provider** (numbered list)
82
+ 2. Ask you to **paste your API key**
83
+ 3. **Save everything** to `~/.phi/agent/models.json` (persistent)
84
+ 4. Let you **choose models** for each role
70
85
 
71
- **Platform notes:** [Windows](docs/windows.md) | [Termux (Android)](docs/termux.md) | [tmux](docs/tmux.md) | [Terminal setup](docs/terminal-setup.md) | [Shell aliases](docs/shell-aliases.md)
86
+ That's it. No environment variables, no JSON editing, no command line flags.
72
87
 
73
- ---
88
+ ### Example
74
89
 
75
- ## Providers & Models
90
+ ```bash
91
+ $ phi
92
+ > /phi-init
93
+ ⚠️ No API keys detected. Let's set one up!
94
+
95
+ Available providers:
96
+ 1. Alibaba Coding Plan
97
+ 2. OpenAI
98
+ 3. Anthropic
99
+ 4. Google
100
+ ...
101
+
102
+ Choose provider (number): 1
103
+ Enter your Alibaba Coding Plan API key: sk-sp-xxxxx
104
+
105
+ ✅ API key saved to ~/.phi/agent/models.json
106
+ ⚠️ Restart phi for models to load.
107
+ ```
76
108
 
77
- For each built-in provider, pi maintains a list of tool-capable models, updated with every release. Authenticate via subscription (`/login`) or API key, then select any model from that provider via `/model` (or Ctrl+L).
78
-
79
- **Subscriptions:**
80
- - Anthropic Claude Pro/Max
81
- - OpenAI ChatGPT Plus/Pro (Codex)
82
- - GitHub Copilot
83
- - Google Gemini CLI
84
- - Google Antigravity
85
-
86
- **API keys:**
87
- - Anthropic
88
- - OpenAI
89
- - Azure OpenAI
90
- - Google Gemini
91
- - Google Vertex
92
- - Amazon Bedrock
93
- - Mistral
94
- - Groq
95
- - Cerebras
96
- - xAI
97
- - OpenRouter
98
- - Vercel AI Gateway
99
- - ZAI
100
- - OpenCode Zen
101
- - OpenCode Go
102
- - Hugging Face
103
- - Kimi For Coding
104
- - MiniMax
105
-
106
- See [docs/providers.md](docs/providers.md) for detailed setup instructions.
107
-
108
- **Custom providers & models:** Add providers via `~/.pi/agent/models.json` if they speak a supported API (OpenAI, Anthropic, Google). For custom APIs or OAuth, use extensions. See [docs/models.md](docs/models.md) and [docs/custom-provider.md](docs/custom-provider.md).
109
+ Restart `phi`, run `/phi-init` again models are detected pick a setup mode done.
109
110
 
110
111
  ---
111
112
 
112
- ## Interactive Mode
113
-
114
- <p align="center"><img src="docs/images/interactive-mode.png" alt="Interactive Mode" width="600"></p>
115
-
116
- The interface from top to bottom:
117
-
118
- - **Startup header** - Shows shortcuts (`/hotkeys` for all), loaded AGENTS.md files, prompt templates, skills, and extensions
119
- - **Messages** - Your messages, assistant responses, tool calls and results, notifications, errors, and extension UI
120
- - **Editor** - Where you type; border color indicates thinking level
121
- - **Footer** - Working directory, session name, total token/cache usage, cost, context usage, current model
122
-
123
- The editor can be temporarily replaced by other UI, like built-in `/settings` or custom UI from extensions (e.g., a Q&A tool that lets the user answer model questions in a structured format). [Extensions](#extensions) can also replace the editor, add widgets above/below it, a status line, custom footer, or overlays.
124
-
125
- ### Editor
126
-
127
- | Feature | How |
128
- |---------|-----|
129
- | File reference | Type `@` to fuzzy-search project files |
130
- | Path completion | Tab to complete paths |
131
- | Multi-line | Shift+Enter (or Ctrl+Enter on Windows Terminal) |
132
- | Images | Ctrl+V to paste (Alt+V on Windows), or drag onto terminal |
133
- | Bash commands | `!command` runs and sends output to LLM, `!!command` runs without sending |
113
+ ## Setup Wizard
134
114
 
135
- Standard editing keybindings for delete word, undo, etc. See [docs/keybindings.md](docs/keybindings.md).
115
+ The `/phi-init` wizard has **3 modes**:
136
116
 
137
- ### Commands
117
+ | Mode | What it does | Time |
118
+ |------|-------------|------|
119
+ | **auto** | Assigns optimal defaults based on available models | Instant |
120
+ | **benchmark** | Tests each model with real coding tasks, assigns by score | 10-15 min |
121
+ | **manual** | You choose the model for each role interactively | 2-5 min |
138
122
 
139
- Type `/` in the editor to trigger commands. [Extensions](#extensions) can register custom commands, [skills](#skills) are available as `/skill:name`, and [prompt templates](#prompt-templates) expand via `/templatename`.
140
-
141
- | Command | Description |
142
- |---------|-------------|
143
- | `/login`, `/logout` | OAuth authentication |
144
- | `/model` | Switch models |
145
- | `/scoped-models` | Enable/disable models for Ctrl+P cycling |
146
- | `/settings` | Thinking level, theme, message delivery, transport |
147
- | `/resume` | Pick from previous sessions |
148
- | `/new` | Start a new session |
149
- | `/name <name>` | Set session display name |
150
- | `/session` | Show session info (path, tokens, cost) |
151
- | `/tree` | Jump to any point in the session and continue from there |
152
- | `/fork` | Create a new session from the current branch |
153
- | `/compact [prompt]` | Manually compact context, optional custom instructions |
154
- | `/copy` | Copy last assistant message to clipboard |
155
- | `/export [file]` | Export session to HTML file |
156
- | `/share` | Upload as private GitHub gist with shareable HTML link |
157
- | `/reload` | Reload extensions, skills, prompts, context files (themes hot-reload automatically) |
158
- | `/hotkeys` | Show all keyboard shortcuts |
159
- | `/changelog` | Display version history |
160
- | `/quit`, `/exit` | Quit pi |
123
+ The wizard creates:
124
+ - `~/.phi/agent/routing.json` — Model assignments per task type
125
+ - `~/.phi/agent/agents/` Sub-agent definitions
126
+ - `~/.phi/memory/AGENTS.md` — Your project instructions template
161
127
 
162
- ### Keyboard Shortcuts
163
-
164
- See `/hotkeys` for the full list. Customize via `~/.pi/agent/keybindings.json`. See [docs/keybindings.md](docs/keybindings.md).
128
+ ---
165
129
 
166
- **Commonly used:**
130
+ ## API Key Management
167
131
 
168
- | Key | Action |
169
- |-----|--------|
170
- | Ctrl+C | Clear editor |
171
- | Ctrl+C twice | Quit |
172
- | Escape | Cancel/abort |
173
- | Escape twice | Open `/tree` |
174
- | Ctrl+L | Open model selector |
175
- | Ctrl+P / Shift+Ctrl+P | Cycle scoped models forward/backward |
176
- | Shift+Tab | Cycle thinking level |
177
- | Ctrl+O | Collapse/expand tool output |
178
- | Ctrl+T | Collapse/expand thinking blocks |
132
+ ### Option 1: Interactive Setup (recommended)
179
133
 
180
- ### Message Queue
134
+ Run `/phi-init` — it asks for your provider and key, saves automatically.
181
135
 
182
- Submit messages while the agent is working:
136
+ ### Option 2: In-Session Command
183
137
 
184
- - **Enter** queues a *steering* message, delivered after current tool execution (interrupts remaining tools)
185
- - **Alt+Enter** queues a *follow-up* message, delivered only after the agent finishes all work
186
- - **Escape** aborts and restores queued messages to editor
187
- - **Alt+Up** retrieves queued messages back to editor
138
+ ```
139
+ /api-key set alibaba sk-sp-your-key-here
140
+ /api-key set openai sk-your-key-here
141
+ /api-key set anthropic sk-ant-your-key-here
142
+ ```
188
143
 
189
- Configure delivery in [settings](docs/settings.md): `steeringMode` and `followUpMode` can be `"one-at-a-time"` (default, waits for response) or `"all"` (delivers all queued at once). `transport` selects provider transport preference (`"sse"`, `"websocket"`, or `"auto"`) for providers that support multiple transports.
144
+ This **saves to `~/.phi/agent/models.json`** (persistent across sessions).
145
+ Restart `phi` for new models to load.
190
146
 
191
- ---
147
+ ### Option 3: View Configured Keys
192
148
 
193
- ## Sessions
194
-
195
- Sessions are stored as JSONL files with a tree structure. Each entry has an `id` and `parentId`, enabling in-place branching without creating new files. See [docs/session.md](docs/session.md) for file format.
149
+ ```
150
+ /api-key list # Show configured keys (masked)
151
+ /api-key providers # List all supported providers
152
+ ```
196
153
 
197
- ### Management
154
+ ### Option 4: Environment Variables
198
155
 
199
- Sessions auto-save to `~/.pi/agent/sessions/` organized by working directory.
156
+ For CI/CD or scripting, you can still use environment variables:
200
157
 
201
158
  ```bash
202
- pi -c # Continue most recent session
203
- pi -r # Browse and select from past sessions
204
- pi --no-session # Ephemeral mode (don't save)
205
- pi --session <path> # Use specific session file or ID
159
+ # Linux/Mac
160
+ export ALIBABA_CODING_PLAN_KEY="sk-sp-xxx"
161
+ export OPENAI_API_KEY="sk-xxx"
162
+ export ANTHROPIC_API_KEY="sk-ant-xxx"
163
+
164
+ # Windows (persistent)
165
+ setx ALIBABA_CODING_PLAN_KEY "sk-sp-xxx"
166
+ setx OPENAI_API_KEY "sk-xxx"
206
167
  ```
207
168
 
208
- ### Branching
169
+ ### Option 5: models.json (Direct Edit)
170
+
171
+ Edit `~/.phi/agent/models.json` directly for advanced configurations:
209
172
 
210
- **`/tree`** - Navigate the session tree in-place. Select any previous point, continue from there, and switch between branches. All history preserved in a single file.
173
+ ```json
174
+ {
175
+ "providers": {
176
+ "my-provider": {
177
+ "baseUrl": "https://api.example.com/v1",
178
+ "api": "openai-completions",
179
+ "apiKey": "your-key-here",
180
+ "models": [
181
+ {
182
+ "id": "model-name",
183
+ "name": "Display Name",
184
+ "reasoning": true,
185
+ "input": ["text"],
186
+ "contextWindow": 131072,
187
+ "maxTokens": 16384
188
+ }
189
+ ]
190
+ }
191
+ }
192
+ }
193
+ ```
211
194
 
212
- <p align="center"><img src="docs/images/tree-view.png" alt="Tree View" width="600"></p>
195
+ The `apiKey` field supports:
196
+ - **Direct value**: `"sk-xxx"` — uses as-is
197
+ - **Environment variable name**: `"OPENAI_API_KEY"` — resolved at runtime
198
+ - **Shell command**: `"!cat ~/.secrets/key"` — executed and output used
213
199
 
214
- - Search by typing, page with ←/→
215
- - Filter modes (Ctrl+O): default → no-tools → user-only → labeled-only → all
216
- - Press `l` to label entries as bookmarks
200
+ ---
217
201
 
218
- **`/fork`** - Create a new session file from the current branch. Opens a selector, copies history up to the selected point, and places that message in the editor for modification.
202
+ ## Providers & Models
219
203
 
220
- ### Compaction
204
+ ### Supported Providers
221
205
 
222
- Long sessions can exhaust context windows. Compaction summarizes older messages while keeping recent ones.
206
+ | Provider | API Key Env Var | Notes |
207
+ |----------|----------------|-------|
208
+ | Alibaba Cloud | `ALIBABA_CODING_PLAN_KEY` | DashScope (Qwen, Kimi, GLM, MiniMax) |
209
+ | OpenAI | `OPENAI_API_KEY` | GPT-4o, o1, o3, etc. |
210
+ | Anthropic | `ANTHROPIC_API_KEY` | Claude Sonnet, Opus, Haiku |
211
+ | Google | `GOOGLE_API_KEY` | Gemini Pro, Flash, Ultra |
212
+ | OpenRouter | `OPENROUTER_API_KEY` | 200+ models from all providers |
213
+ | Groq | `GROQ_API_KEY` | Ultra-fast inference |
214
+ | Ollama | — | Local, `ollama serve` on port 11434 |
215
+ | LM Studio | — | Local, start server on port 1234 |
223
216
 
224
- **Manual:** `/compact` or `/compact <custom instructions>`
217
+ Plus all Pi built-in providers: Azure OpenAI, Google Vertex, Amazon Bedrock, Mistral, Cerebras, xAI, Hugging Face, and more.
225
218
 
226
- **Automatic:** Enabled by default. Triggers on context overflow (recovers and retries) or when approaching the limit (proactive). Configure via `/settings` or `settings.json`.
219
+ ### Switching Models
227
220
 
228
- Compaction is lossy. The full history remains in the JSONL file; use `/tree` to revisit. Customize compaction behavior via [extensions](#extensions). See [docs/compaction.md](docs/compaction.md) for internals.
221
+ - **Ctrl+L** Open model selector (pick from list)
222
+ - **Ctrl+P** — Cycle through scoped models
223
+ - `/model <name>` — Switch by name
229
224
 
230
225
  ---
231
226
 
232
- ## Settings
227
+ ## Commands
233
228
 
234
- Use `/settings` to modify common options, or edit JSON files directly:
229
+ Phi Code adds these commands on top of Pi's built-in commands:
235
230
 
236
- | Location | Scope |
237
- |----------|-------|
238
- | `~/.pi/agent/settings.json` | Global (all projects) |
239
- | `.pi/settings.json` | Project (overrides global) |
231
+ | Command | Description |
232
+ |---------|-------------|
233
+ | `/phi-init` | Interactive setup wizard — configure providers, keys, and models |
234
+ | `/api-key` | Manage API keys (`set`, `list`, `providers`, `help`) |
235
+ | `/plan` | Full orchestration — analyze project, create spec, execute with sub-agents |
236
+ | `/run` | Execute a todo.md plan with parallel sub-agents |
237
+ | `/agents` | List available sub-agents and their capabilities |
238
+ | `/benchmark` | Test model performance (`/benchmark all`, `/benchmark code-gen`) |
239
+ | `/search` | Web search via Brave API |
240
+ | `/crawl` | Fetch and extract content from a URL |
240
241
 
241
- See [docs/settings.md](docs/settings.md) for all options.
242
+ ### Pi Built-in Commands
243
+
244
+ | Command | Description |
245
+ |---------|-------------|
246
+ | `/login`, `/logout` | OAuth authentication |
247
+ | `/model` | Switch models |
248
+ | `/settings` | Thinking level, theme, transport |
249
+ | `/resume` | Pick from previous sessions |
250
+ | `/new` | Start a new session |
251
+ | `/tree` | Navigate session history |
252
+ | `/compact` | Manually compact context |
253
+ | `/copy` | Copy last response to clipboard |
254
+ | `/export` | Export session to HTML |
255
+ | `/reload` | Reload extensions, skills, prompts |
242
256
 
243
257
  ---
244
258
 
245
- ## Context Files
259
+ ## Sub-Agents
246
260
 
247
- Pi loads `AGENTS.md` (or `CLAUDE.md`) at startup from:
248
- - `~/.pi/agent/AGENTS.md` (global)
249
- - Parent directories (walking up from cwd)
250
- - Current directory
261
+ Phi Code ships with **5 specialized sub-agents**, each with its own system prompt and tool set:
251
262
 
252
- Use for project instructions, conventions, common commands. All matching files are concatenated.
263
+ | Agent | Role | Tools |
264
+ |-------|------|-------|
265
+ | **code** | Write and edit code, run commands | `read`, `write`, `edit`, `bash` |
266
+ | **explore** | Investigate codebases, read-only analysis | `read`, `bash` |
267
+ | **plan** | Architecture, design, technical planning | `read`, `bash` |
268
+ | **review** | Code review, security audit, best practices | `read`, `bash` |
269
+ | **test** | Write tests, fix tests, run test suites | `read`, `write`, `edit`, `bash` |
253
270
 
254
- ### System Prompt
271
+ View agents: `/agents`
272
+ View details: `/agents code`
255
273
 
256
- Replace the default system prompt with `.pi/SYSTEM.md` (project) or `~/.pi/agent/SYSTEM.md` (global). Append without replacing via `APPEND_SYSTEM.md`.
274
+ Agent definitions are Markdown files with YAML frontmatter in `~/.phi/agent/agents/`. You can customize them or add your own.
257
275
 
258
276
  ---
259
277
 
260
- ## Customization
261
-
262
- ### Prompt Templates
278
+ ## Orchestrator
263
279
 
264
- Reusable prompts as Markdown files. Type `/name` to expand.
280
+ The `/plan` command is a **full-cycle project orchestrator**:
265
281
 
266
- ```markdown
267
- <!-- ~/.pi/agent/prompts/review.md -->
268
- Review this code for bugs, security issues, and performance problems.
269
- Focus on: {{focus}}
282
+ ```
283
+ /plan Build a REST API with authentication and tests
270
284
  ```
271
285
 
272
- Place in `~/.pi/agent/prompts/`, `.pi/prompts/`, or a [pi package](#pi-packages) to share with others. See [docs/prompt-templates.md](docs/prompt-templates.md).
273
-
274
- ### Skills
286
+ This single command:
287
+ 1. **Analyzes** your project structure
288
+ 2. **Creates** a detailed spec (`spec.md`)
289
+ 3. **Generates** a task list with dependencies (`todo.md`)
290
+ 4. **Executes** all tasks with parallel sub-agents
291
+ 5. **Reports** progress in real-time (`progress.md`)
275
292
 
276
- On-demand capability packages following the [Agent Skills standard](https://agentskills.io). Invoke via `/skill:name` or let the agent load them automatically.
293
+ ### How It Works
277
294
 
278
- ```markdown
279
- <!-- ~/.pi/agent/skills/my-skill/SKILL.md -->
280
- # My Skill
281
- Use this skill when the user asks about X.
295
+ - Tasks are organized into **waves** based on dependencies
296
+ - Independent tasks run **in parallel** via `Promise.all`
297
+ - Each sub-agent receives **shared context**: project description, spec summary, and results from completed dependency tasks
298
+ - Failed tasks are skipped; dependents are also skipped with a clear report
299
+ - All files are written to `.phi/plans/<timestamp>/`
282
300
 
283
- ## Steps
284
- 1. Do this
285
- 2. Then that
286
- ```
301
+ ### Step-by-Step Mode
287
302
 
288
- Place in `~/.pi/agent/skills/`, `~/.agents/skills/`, `.pi/skills/`, or `.agents/skills/` (from `cwd` up through parent directories) or a [pi package](#pi-packages) to share with others. See [docs/skills.md](docs/skills.md).
303
+ Use `/run` to execute an existing plan:
289
304
 
290
- ### Extensions
305
+ ```
306
+ /run .phi/plans/2026-03-07T21-00-00/todo.md
307
+ ```
291
308
 
292
- <p align="center"><img src="docs/images/doom-extension.png" alt="Doom Extension" width="600"></p>
309
+ ---
293
310
 
294
- TypeScript modules that extend pi with custom tools, commands, keyboard shortcuts, event handlers, and UI components.
311
+ ## Memory System
295
312
 
296
- ```typescript
297
- export default function (pi: ExtensionAPI) {
298
- pi.registerTool({ name: "deploy", ... });
299
- pi.registerCommand("stats", { ... });
300
- pi.on("tool_call", async (event, ctx) => { ... });
301
- }
302
- ```
313
+ Phi Code remembers across sessions via **sigma-memory**:
303
314
 
304
- **What's possible:**
305
- - Custom tools (or replace built-in tools entirely)
306
- - Sub-agents and plan mode
307
- - Custom compaction and summarization
308
- - Permission gates and path protection
309
- - Custom editors and UI components
310
- - Status lines, headers, footers
311
- - Git checkpointing and auto-commit
312
- - SSH and sandbox execution
313
- - MCP server integration
314
- - Make pi look like Claude Code
315
- - Games while waiting (yes, Doom runs)
316
- - ...anything you can dream up
315
+ ### Components
317
316
 
318
- Place in `~/.pi/agent/extensions/`, `.pi/extensions/`, or a [pi package](#pi-packages) to share with others. See [docs/extensions.md](docs/extensions.md) and [examples/extensions/](examples/extensions/).
317
+ | Component | What it stores | Location |
318
+ |-----------|---------------|----------|
319
+ | **Notes** | Free-form text notes | `~/.phi/memory/notes/` |
320
+ | **Ontology** | Structured knowledge graph (entities + relations) | `~/.phi/memory/ontology/` |
321
+ | **QMD** | Vector embeddings for semantic search | `~/.phi/memory/qmd/` |
322
+ | **AGENTS.md** | Global project instructions | `~/.phi/memory/AGENTS.md` |
319
323
 
320
- ### Themes
324
+ ### Auto-Recall
321
325
 
322
- Built-in: `dark`, `light`. Themes hot-reload: modify the active theme file and pi immediately applies changes.
326
+ Memory is automatically searched before every response. When you ask "how did we implement the auth system?", Phi Code searches its memory and includes relevant context.
323
327
 
324
- Place in `~/.pi/agent/themes/`, `.pi/themes/`, or a [pi package](#pi-packages) to share with others. See [docs/themes.md](docs/themes.md).
328
+ ### Manual Commands
325
329
 
326
- ### Pi Packages
330
+ Memory tools are available to the LLM:
331
+ - `memory_search` — Semantic search across all memory
332
+ - `memory_note` — Save a note for future sessions
333
+ - `memory_entity` / `memory_relation` — Build the knowledge graph
327
334
 
328
- Bundle and share extensions, skills, prompts, and themes via npm or git. Find packages on [npmjs.com](https://www.npmjs.com/search?q=keywords%3Api-package) or [Discord](https://discord.com/channels/1456806362351669492/1457744485428629628).
335
+ ---
329
336
 
330
- > **Security:** Pi packages run with full system access. Extensions execute arbitrary code, and skills can instruct the model to perform any action including running executables. Review source code before installing third-party packages.
337
+ ## Smart Routing
331
338
 
332
- ```bash
333
- pi install npm:@foo/pi-tools
334
- pi install npm:@foo/pi-tools@1.2.3 # pinned version
335
- pi install git:github.com/user/repo
336
- pi install git:github.com/user/repo@v1 # tag or commit
337
- pi install git:git@github.com:user/repo
338
- pi install git:git@github.com:user/repo@v1 # tag or commit
339
- pi install https://github.com/user/repo
340
- pi install https://github.com/user/repo@v1 # tag or commit
341
- pi install ssh://git@github.com/user/repo
342
- pi install ssh://git@github.com/user/repo@v1 # tag or commit
343
- pi remove npm:@foo/pi-tools
344
- pi list
345
- pi update # skips pinned packages
346
- pi config # enable/disable extensions, skills, prompts, themes
347
- ```
339
+ The smart router automatically assigns the best model to each task based on your `routing.json` configuration:
348
340
 
349
- Packages install to `~/.pi/agent/git/` (git) or global npm. Use `-l` for project-local installs (`.pi/git/`, `.pi/npm/`).
341
+ | Task Type | Best For |
342
+ |-----------|----------|
343
+ | **code-generation** | Writing new code, refactoring |
344
+ | **debugging** | Finding and fixing bugs |
345
+ | **planning** | Architecture, design decisions |
346
+ | **tool-calling** | File operations, bash commands |
347
+ | **orchestration** | Managing sub-agents, complex workflows |
348
+ | **default** | Everything else |
350
349
 
351
- Create a package by adding a `pi` key to `package.json`:
350
+ Configuration: `~/.phi/agent/routing.json`
352
351
 
353
352
  ```json
354
353
  {
355
- "name": "my-pi-package",
356
- "keywords": ["pi-package"],
357
- "pi": {
358
- "extensions": ["./extensions"],
359
- "skills": ["./skills"],
360
- "prompts": ["./prompts"],
361
- "themes": ["./themes"]
362
- }
354
+ "code-generation": { "preferred": "qwen3.5-plus", "fallback": "default" },
355
+ "debugging": { "preferred": "kimi-k2.5", "fallback": "default" },
356
+ "default": { "preferred": "default", "fallback": "default" }
363
357
  }
364
358
  ```
365
359
 
366
- Without a `pi` manifest, pi auto-discovers from conventional directories (`extensions/`, `skills/`, `prompts/`, `themes/`).
367
-
368
- See [docs/packages.md](docs/packages.md).
360
+ Set models to `"default"` to use whatever model is currently active.
369
361
 
370
362
  ---
371
363
 
372
- ## Programmatic Usage
364
+ ## Benchmark
373
365
 
374
- ### SDK
366
+ Test your models with real coding tasks:
375
367
 
376
- ```typescript
377
- import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "@mariozechner/pi-coding-agent";
378
-
379
- const { session } = await createAgentSession({
380
- sessionManager: SessionManager.inMemory(),
381
- authStorage: AuthStorage.create(),
382
- modelRegistry: new ModelRegistry(authStorage),
383
- });
384
-
385
- await session.prompt("What files are in the current directory?");
386
368
  ```
387
-
388
- See [docs/sdk.md](docs/sdk.md) and [examples/sdk/](examples/sdk/).
389
-
390
- ### RPC Mode
391
-
392
- For non-Node.js integrations, use RPC mode over stdin/stdout:
393
-
394
- ```bash
395
- pi --mode rpc
369
+ /benchmark all # Test all available models
370
+ /benchmark code-gen # Test only code generation
371
+ /benchmark debug # Test only debugging
396
372
  ```
397
373
 
398
- See [docs/rpc.md](docs/rpc.md) for the protocol.
374
+ ### Categories
399
375
 
400
- ---
376
+ | Category | Weight | What it tests |
377
+ |----------|--------|---------------|
378
+ | code-gen | ×2 | Write a function from spec |
379
+ | debug | ×2 | Find and fix a bug |
380
+ | planning | ×2 | Design an architecture |
381
+ | tool-calling | ×1 | Structured tool use |
382
+ | speed | ×1 | Response latency |
383
+ | orchestration | ×2 | Multi-step task planning |
401
384
 
402
- ## Philosophy
385
+ ### Scoring
403
386
 
404
- Pi is aggressively extensible so it doesn't have to dictate your workflow. Features that other tools bake in can be built with [extensions](#extensions), [skills](#skills), or installed from third-party [pi packages](#pi-packages). This keeps the core minimal while letting you shape pi to fit how you work.
387
+ Models are scored 0-100 and ranked into tiers:
405
388
 
406
- **No MCP.** Build CLI tools with READMEs (see [Skills](#skills)), or build an extension that adds MCP support. [Why?](https://mariozechner.at/posts/2025-11-02-what-if-you-dont-need-mcp/)
389
+ | Tier | Score | Meaning |
390
+ |------|-------|---------|
391
+ | **S** | 80+ | Elite — best for critical tasks |
392
+ | **A** | 65+ | Strong — reliable for most work |
393
+ | **B** | 50+ | Decent — good for simple tasks |
394
+ | **C** | 35+ | Weak — use as fallback only |
395
+ | **D** | <35 | Avoid — not recommended |
407
396
 
408
- **No sub-agents.** There's many ways to do this. Spawn pi instances via tmux, or build your own with [extensions](#extensions), or install a package that does it your way.
397
+ ---
409
398
 
410
- **No permission popups.** Run in a container, or build your own confirmation flow with [extensions](#extensions) inline with your environment and security requirements.
399
+ ## Skills
411
400
 
412
- **No plan mode.** Write plans to files, or build it with [extensions](#extensions), or install a package.
401
+ Phi Code ships with **12 built-in skills**:
413
402
 
414
- **No built-in to-dos.** They confuse models. Use a TODO.md file, or build your own with [extensions](#extensions).
403
+ | Skill | Description |
404
+ |-------|-------------|
405
+ | api-design | REST API patterns, versioning, error handling |
406
+ | coding-standards | Code quality, naming conventions, best practices |
407
+ | database | Database design, queries, migrations, optimization |
408
+ | devops | CI/CD pipelines, deployment, monitoring |
409
+ | docker-ops | Docker containers, Compose, orchestration |
410
+ | git-workflow | Branching, commits, merges, collaboration |
411
+ | github | GitHub Actions, PRs, issues, releases |
412
+ | performance | Profiling, optimization, caching |
413
+ | prompt-architect | Crafting structured prompts for AI systems |
414
+ | security | Vulnerability scanning, hardening |
415
+ | self-improving | Learning from errors and corrections |
416
+ | testing | Test strategy, unit/integration tests |
415
417
 
416
- **No background bash.** Use tmux. Full observability, direct interaction.
418
+ Skills are loaded automatically when relevant. Invoke manually with `/skill:name`.
417
419
 
418
- Read the [blog post](https://mariozechner.at/posts/2025-11-30-pi-coding-agent/) for the full rationale.
420
+ Add your own skills in `~/.phi/agent/skills/` or `.phi/skills/`.
419
421
 
420
422
  ---
421
423
 
422
- ## CLI Reference
424
+ ## Extensions
423
425
 
424
- ```bash
425
- pi [options] [@files...] [messages...]
426
- ```
427
-
428
- ### Package Commands
426
+ Phi Code ships with **9 extensions**:
429
427
 
430
- ```bash
431
- pi install <source> [-l] # Install package, -l for project-local
432
- pi remove <source> [-l] # Remove package
433
- pi update [source] # Update packages (skips pinned)
434
- pi list # List installed packages
435
- pi config # Enable/disable package resources
436
- ```
428
+ | Extension | What it adds |
429
+ |-----------|-------------|
430
+ | **init** | `/phi-init` wizard + `/api-key` management |
431
+ | **orchestrator** | `/plan` and `/run` commands with parallel sub-agents |
432
+ | **memory** | Persistent memory (notes, ontology, QMD search) |
433
+ | **smart-router** | Automatic model routing by task type |
434
+ | **skill-loader** | Dynamic skill scanning and loading |
435
+ | **benchmark** | `/benchmark` for model testing |
436
+ | **web-search** | `/search` and `/crawl` commands via Brave API |
437
+ | **agents** | `/agents` command to list sub-agents |
437
438
 
438
- ### Modes
439
+ Extensions are TypeScript files loaded at runtime by [jiti](https://github.com/unjs/jiti). Add your own in `~/.phi/agent/extensions/`.
439
440
 
440
- | Flag | Description |
441
- |------|-------------|
442
- | (default) | Interactive mode |
443
- | `-p`, `--print` | Print response and exit |
444
- | `--mode json` | Output all events as JSON lines (see [docs/json.md](docs/json.md)) |
445
- | `--mode rpc` | RPC mode for process integration (see [docs/rpc.md](docs/rpc.md)) |
446
- | `--export <in> [out]` | Export session to HTML |
447
-
448
- ### Model Options
449
-
450
- | Option | Description |
451
- |--------|-------------|
452
- | `--provider <name>` | Provider (anthropic, openai, google, etc.) |
453
- | `--model <pattern>` | Model pattern or ID (supports `provider/id` and optional `:<thinking>`) |
454
- | `--api-key <key>` | API key (overrides env vars) |
455
- | `--thinking <level>` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh` |
456
- | `--models <patterns>` | Comma-separated patterns for Ctrl+P cycling |
457
- | `--list-models [search]` | List available models |
458
-
459
- ### Session Options
441
+ ---
460
442
 
461
- | Option | Description |
462
- |--------|-------------|
463
- | `-c`, `--continue` | Continue most recent session |
464
- | `-r`, `--resume` | Browse and select session |
465
- | `--session <path>` | Use specific session file or partial UUID |
466
- | `--session-dir <dir>` | Custom session storage directory |
467
- | `--no-session` | Ephemeral mode (don't save) |
443
+ ## Configuration Files
468
444
 
469
- ### Tool Options
445
+ All configuration lives in `~/.phi/agent/`:
470
446
 
471
- | Option | Description |
472
- |--------|-------------|
473
- | `--tools <list>` | Enable specific built-in tools (default: `read,bash,edit,write`) |
474
- | `--no-tools` | Disable all built-in tools (extension tools still work) |
447
+ | File | Purpose |
448
+ |------|---------|
449
+ | `models.json` | **API keys & custom providers** (created by `/phi-init` or `/api-key`) |
450
+ | `routing.json` | Model assignments per task type |
451
+ | `settings.json` | Pi settings (thinking level, compaction, etc.) |
452
+ | `agents/*.md` | Sub-agent definitions |
453
+ | `skills/*/SKILL.md` | Skill definitions |
454
+ | `extensions/*.ts` | Extension files |
455
+ | `AGENTS.md` | Global project instructions |
456
+ | `keybindings.json` | Custom keyboard shortcuts |
475
457
 
476
- Available built-in tools: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`
458
+ Memory lives in `~/.phi/memory/`:
477
459
 
478
- ### Resource Options
460
+ | Path | Content |
461
+ |------|---------|
462
+ | `AGENTS.md` | Global memory / instructions |
463
+ | `notes/` | Saved notes |
464
+ | `ontology/` | Knowledge graph |
465
+ | `qmd/` | Vector search index |
479
466
 
480
- | Option | Description |
481
- |--------|-------------|
482
- | `-e`, `--extension <source>` | Load extension from path, npm, or git (repeatable) |
483
- | `--no-extensions` | Disable extension discovery |
484
- | `--skill <path>` | Load skill (repeatable) |
485
- | `--no-skills` | Disable skill discovery |
486
- | `--prompt-template <path>` | Load prompt template (repeatable) |
487
- | `--no-prompt-templates` | Disable prompt template discovery |
488
- | `--theme <path>` | Load theme (repeatable) |
489
- | `--no-themes` | Disable theme discovery |
467
+ ---
490
468
 
491
- Combine `--no-*` with explicit flags to load exactly what you need, ignoring settings.json (e.g., `--no-extensions -e ./my-ext.ts`).
469
+ ## Keyboard Shortcuts
492
470
 
493
- ### Other Options
471
+ | Key | Action |
472
+ |-----|--------|
473
+ | **Ctrl+L** | Open model selector |
474
+ | **Ctrl+P** | Cycle models forward |
475
+ | **Shift+Ctrl+P** | Cycle models backward |
476
+ | **Shift+Tab** | Cycle thinking level |
477
+ | **Ctrl+O** | Collapse/expand tool output |
478
+ | **Ctrl+T** | Collapse/expand thinking |
479
+ | **Ctrl+G** | Open external editor |
480
+ | **Escape** | Cancel/abort |
481
+ | **Ctrl+C** | Clear editor |
482
+ | **Ctrl+C twice** | Quit |
483
+ | **Alt+Enter** | Queue follow-up message |
484
+
485
+ Full list: `/hotkeys`
494
486
 
495
- | Option | Description |
496
- |--------|-------------|
497
- | `--system-prompt <text>` | Replace default prompt (context files and skills still appended) |
498
- | `--append-system-prompt <text>` | Append to system prompt |
499
- | `--verbose` | Force verbose startup |
500
- | `-h`, `--help` | Show help |
501
- | `-v`, `--version` | Show version |
487
+ ---
502
488
 
503
- ### File Arguments
489
+ ## Sessions
504
490
 
505
- Prefix files with `@` to include in the message:
491
+ Sessions auto-save to `~/.phi/agent/sessions/` as JSONL files with a tree structure.
506
492
 
507
493
  ```bash
508
- pi @prompt.md "Answer this"
509
- pi -p @screenshot.png "What's in this image?"
510
- pi @code.ts @test.ts "Review these files"
494
+ phi -c # Continue last session
495
+ phi -r # Browse past sessions
496
+ phi --no-session # Ephemeral mode
511
497
  ```
512
498
 
513
- ### Examples
499
+ **Branching:** Use `/tree` to navigate history and branch from any point.
500
+ **Compaction:** Automatic context management when approaching limits.
501
+ **Export:** `/export file.html` or `--export` flag.
502
+ **Debug log:** `~/.phi/agent/phi-debug.log` (toggle with Ctrl+D).
514
503
 
515
- ```bash
516
- # Interactive with initial prompt
517
- pi "List all .ts files in src/"
504
+ ---
518
505
 
519
- # Non-interactive
520
- pi -p "Summarize this codebase"
506
+ ## CLI Reference
521
507
 
522
- # Different model
523
- pi --provider openai --model gpt-4o "Help me refactor"
508
+ ```bash
509
+ phi [options] [@files...] [messages...]
510
+ ```
524
511
 
525
- # Model with provider prefix (no --provider needed)
526
- pi --model openai/gpt-4o "Help me refactor"
512
+ | Option | Description |
513
+ |--------|-------------|
514
+ | `--provider <name>` | Provider name |
515
+ | `--model <pattern>` | Model pattern or ID |
516
+ | `--api-key <key>` | API key (session only) |
517
+ | `--thinking <level>` | off, minimal, low, medium, high, xhigh |
518
+ | `-c`, `--continue` | Continue last session |
519
+ | `-r`, `--resume` | Browse sessions |
520
+ | `-p`, `--print` | Print mode (non-interactive) |
521
+ | `--no-session` | Don't save session |
522
+ | `--verbose` | Verbose startup |
523
+ | `-v`, `--version` | Show version |
527
524
 
528
- # Model with thinking level shorthand
529
- pi --model sonnet:high "Solve this complex problem"
525
+ Platform notes: [Windows](docs/windows.md) | [Termux](docs/termux.md) | [tmux](docs/tmux.md)
530
526
 
531
- # Limit model cycling
532
- pi --models "claude-*,gpt-4o"
527
+ ---
533
528
 
534
- # Read-only mode
535
- pi --tools read,grep,find,ls -p "Review the code"
529
+ ## Philosophy
536
530
 
537
- # High thinking level
538
- pi --thinking high "Solve this complex problem"
539
- ```
531
+ Phi Code follows Pi's philosophy of **aggressive extensibility** while adding the features serious developers need out of the box:
540
532
 
541
- ### Environment Variables
533
+ - **Memory matters.** Context across sessions shouldn't require manual copy-paste.
534
+ - **Sub-agents work.** The right agent for the right task, running in parallel.
535
+ - **Routing saves money.** Don't use your most expensive model for `ls`.
536
+ - **Setup should be easy.** `/phi-init` → pick provider → paste key → done.
537
+ - **Provider-neutral.** Your choice of LLM. No vendor lock-in.
542
538
 
543
- | Variable | Description |
544
- |----------|-------------|
545
- | `PI_CODING_AGENT_DIR` | Override config directory (default: `~/.pi/agent`) |
546
- | `PI_PACKAGE_DIR` | Override package directory (useful for Nix/Guix where store paths tokenize poorly) |
547
- | `PI_SKIP_VERSION_CHECK` | Skip version check at startup |
548
- | `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache (Anthropic: 1h, OpenAI: 24h) |
549
- | `VISUAL`, `EDITOR` | External editor for Ctrl+G |
539
+ Built on [Pi](https://github.com/badlogic/pi-mono) by [Mario Zechner](https://github.com/badlogic). Everything Phi adds is through Pi's extension system — 2 lines changed in core.
550
540
 
551
541
  ---
552
542
 
553
- ## Contributing & Development
543
+ ## Credits
554
544
 
555
- See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines and [docs/development.md](docs/development.md) for setup, forking, and debugging.
545
+ - **[Pi](https://github.com/badlogic/pi-mono)** by Mario Zechner the foundation
546
+ - **[sigma-memory](https://www.npmjs.com/package/sigma-memory)** — persistent memory system
547
+ - **[sigma-agents](https://www.npmjs.com/package/sigma-agents)** — sub-agent routing
548
+ - **[sigma-skills](https://www.npmjs.com/package/sigma-skills)** — skill scanning and loading
556
549
 
557
550
  ---
558
551
 
559
552
  ## License
560
553
 
561
554
  MIT
562
-
563
- ## See Also
564
-
565
- - [@mariozechner/pi-ai](https://www.npmjs.com/package/@mariozechner/pi-ai): Core LLM toolkit
566
- - [@mariozechner/pi-agent](https://www.npmjs.com/package/@mariozechner/pi-agent): Agent framework
567
- - [@mariozechner/pi-tui](https://www.npmjs.com/package/@mariozechner/pi-tui): Terminal UI components
@@ -608,104 +608,127 @@ _Edit this file to customize Phi Code's behavior for your project._
608
608
  ctx.ui.notify("║ Φ Phi Code Setup Wizard ║", "info");
609
609
  ctx.ui.notify("╚══════════════════════════════════════╝\n", "info");
610
610
 
611
- // 1. Detect API keys and local providers
612
- ctx.ui.notify("🔍 Detecting providers...", "info");
611
+ // 1. Detect providers
612
+ ctx.ui.notify("🔍 Detecting providers...\n", "info");
613
613
  const providers = detectProviders();
614
614
 
615
+ // Also check models.json for previously configured providers
616
+ const modelsJsonPath = join(agentDir, "models.json");
617
+ try {
618
+ const mjContent = await readFile(modelsJsonPath, "utf-8");
619
+ const mjConfig = JSON.parse(mjContent);
620
+ if (mjConfig.providers) {
621
+ for (const [id, config] of Object.entries<any>(mjConfig.providers)) {
622
+ // Mark provider as available if it has an API key in models.json
623
+ if (config.apiKey) {
624
+ const match = providers.find(p =>
625
+ id.includes(p.name.toLowerCase().split(" ")[0]) ||
626
+ p.name.toLowerCase().replace(/\s+/g, "-") === id
627
+ );
628
+ if (match) {
629
+ match.available = true;
630
+ if (config.models?.length > 0) {
631
+ match.models = config.models.map((m: any) => m.id || m);
632
+ }
633
+ }
634
+ }
635
+ }
636
+ }
637
+ } catch { /* no models.json yet */ }
638
+
615
639
  // Probe local providers (Ollama, LM Studio)
616
- ctx.ui.notify("🔍 Probing local model servers...", "info");
617
640
  await detectLocalProviders(providers);
618
641
 
619
642
  let available = providers.filter(p => p.available);
643
+ const cloudConfigured = available.filter(p => !p.local);
620
644
 
621
- // If no providers found, offer interactive API key setup
622
- if (available.length === 0) {
623
- ctx.ui.notify("⚠️ No API keys detected. Let's set one up!\n", "info");
624
- ctx.ui.notify("**Available providers:**", "info");
625
- const cloudProviders = providers.filter(p => !p.local);
626
- cloudProviders.forEach((p, i) => {
627
- ctx.ui.notify(` ${i + 1}. ${p.name}`, "info");
628
- });
629
- ctx.ui.notify(` ${cloudProviders.length + 1}. Ollama (local)`, "info");
630
- ctx.ui.notify(` ${cloudProviders.length + 2}. LM Studio (local)\n`, "info");
645
+ // Always show provider status and offer to add/change
646
+ ctx.ui.notify("**Provider Status:**", "info");
647
+ for (const p of providers) {
648
+ const status = p.available ? "✅" : "";
649
+ const tag = p.local ? " (local)" : "";
650
+ const modelCount = p.available ? ` — ${p.models.length} model(s)` : "";
651
+ ctx.ui.notify(` ${status} ${p.name}${tag}${modelCount}`, "info");
652
+ }
653
+
654
+ // If no cloud providers have keys, prompt for setup
655
+ if (cloudConfigured.length === 0) {
656
+ ctx.ui.notify("\n⚠️ No cloud API keys configured.\n", "warning");
657
+ }
658
+
659
+ // Always offer to add a provider
660
+ const addProvider = await ctx.ui.input(
661
+ "Add/change a provider? (number, or Enter to skip)",
662
+ providers.map((p, i) => `${i+1}=${p.name}`).join(", ")
663
+ );
631
664
 
632
- const providerChoice = await ctx.ui.input(
633
- "Choose provider (number)",
634
- `1-${cloudProviders.length + 2}`
635
- );
636
- const choiceNum = parseInt(providerChoice ?? "0");
665
+ const choiceNum = parseInt(addProvider ?? "0");
666
+ if (choiceNum >= 1 && choiceNum <= providers.length) {
667
+ const chosen = providers[choiceNum - 1];
637
668
 
638
- if (choiceNum >= 1 && choiceNum <= cloudProviders.length) {
669
+ if (chosen.local) {
670
+ const port = chosen.name === "Ollama" ? 11434 : 1234;
671
+ if (!chosen.available) {
672
+ ctx.ui.notify(`\n💡 **${chosen.name}** — make sure it's running on port ${port}.`, "info");
673
+ ctx.ui.notify("Then restart phi and run `/phi-init` again.", "info");
674
+ return;
675
+ }
676
+ ctx.ui.notify(`\n✅ **${chosen.name}** is running with ${chosen.models.length} model(s).`, "info");
677
+ } else {
639
678
  // Cloud provider — ask for API key
640
- const chosen = cloudProviders[choiceNum - 1];
641
- ctx.ui.notify(`\n🔑 **${chosen.name}** selected.`, "info");
679
+ ctx.ui.notify(`\n🔑 **${chosen.name}**`, "info");
642
680
 
643
681
  const apiKey = await ctx.ui.input(
644
682
  `Enter your ${chosen.name} API key`,
645
- "sk-..."
683
+ "Paste your key here"
646
684
  );
647
685
 
648
686
  if (!apiKey || apiKey.trim().length < 5) {
649
- ctx.ui.notify("❌ Invalid API key. Cancelled.", "error");
650
- return;
687
+ ctx.ui.notify("❌ Invalid API key. Skipped.", "error");
688
+ } else {
689
+ // Save to models.json
690
+ let modelsConfig: any = { providers: {} };
691
+ try {
692
+ const existing = await readFile(modelsJsonPath, "utf-8");
693
+ modelsConfig = JSON.parse(existing);
694
+ } catch { /* new file */ }
695
+
696
+ const providerId = chosen.name.toLowerCase().replace(/\s+/g, "-");
697
+ modelsConfig.providers[providerId] = {
698
+ baseUrl: chosen.baseUrl,
699
+ api: "openai-completions",
700
+ apiKey: apiKey.trim(),
701
+ models: chosen.models.map((id: string) => ({
702
+ id,
703
+ name: id,
704
+ reasoning: true,
705
+ input: ["text"],
706
+ contextWindow: 131072,
707
+ maxTokens: 16384,
708
+ })),
709
+ };
710
+
711
+ await writeFile(modelsJsonPath, JSON.stringify(modelsConfig, null, 2), "utf-8");
712
+ process.env[chosen.envVar] = apiKey.trim();
713
+ chosen.available = true;
714
+
715
+ const masked = apiKey.trim().substring(0, 6) + "..." + apiKey.trim().slice(-4);
716
+ ctx.ui.notify(`✅ **${chosen.name}** saved (${masked})`, "info");
717
+ ctx.ui.notify(` ${chosen.models.length} models configured in \`models.json\``, "info");
651
718
  }
652
-
653
- // Save to models.json for persistence
654
- const modelsJsonPath = join(agentDir, "models.json");
655
- let modelsConfig: any = { providers: {} };
656
- try {
657
- const existing = await readFile(modelsJsonPath, "utf-8");
658
- modelsConfig = JSON.parse(existing);
659
- } catch { /* file doesn't exist yet */ }
660
-
661
- // Build provider config with correct provider ID
662
- const providerId = chosen.name.toLowerCase().replace(/\s+/g, "-");
663
- modelsConfig.providers[providerId] = {
664
- baseUrl: chosen.baseUrl,
665
- api: "openai-completions",
666
- apiKey: apiKey.trim(),
667
- models: chosen.models.map((id: string) => ({
668
- id,
669
- name: id,
670
- reasoning: true,
671
- input: ["text"],
672
- contextWindow: 131072,
673
- maxTokens: 16384,
674
- })),
675
- };
676
-
677
- await writeFile(modelsJsonPath, JSON.stringify(modelsConfig, null, 2), "utf-8");
678
-
679
- // Also set in current session
680
- process.env[chosen.envVar] = apiKey.trim();
681
- chosen.available = true;
682
-
683
- ctx.ui.notify(`\n✅ API key saved to \`~/.phi/agent/models.json\``, "info");
684
- ctx.ui.notify(` ${chosen.models.length} models configured.`, "info");
685
- ctx.ui.notify(` ⚠️ **Restart phi** for models to load.\n`, "warning");
686
- ctx.ui.notify("Run `phi` again, then `/phi-init` to complete setup.", "info");
687
- return;
688
-
689
- } else if (choiceNum === cloudProviders.length + 1 || choiceNum === cloudProviders.length + 2) {
690
- const localName = choiceNum === cloudProviders.length + 1 ? "Ollama" : "LM Studio";
691
- const port = choiceNum === cloudProviders.length + 1 ? 11434 : 1234;
692
- ctx.ui.notify(`\n💡 **${localName}** selected. Make sure it's running on port ${port}.`, "info");
693
- ctx.ui.notify(`Then restart phi and run /phi-init again.`, "info");
694
- return;
695
- } else {
696
- ctx.ui.notify("❌ Invalid choice. Cancelled.", "error");
697
- return;
698
719
  }
699
720
  }
700
721
 
701
- ctx.ui.notify(`✅ Found ${available.length} provider(s):`, "info");
702
- for (const p of available) {
703
- const tag = p.local ? " (local)" : "";
704
- ctx.ui.notify(` • ${p.name}${tag} — ${p.models.length} model(s)${p.local ? ": " + p.models.join(", ") : ""}`, "info");
722
+ // Re-check available after potential additions
723
+ available = providers.filter(p => p.available);
724
+
725
+ if (available.length === 0) {
726
+ ctx.ui.notify("\n❌ No providers available. Run `/phi-init` again after setting up a provider.", "error");
727
+ return;
705
728
  }
706
729
 
707
730
  const allModels = getAllAvailableModels(providers);
708
- ctx.ui.notify(` Total: ${allModels.length} models available\n`, "info");
731
+ ctx.ui.notify(`\n✅ **${allModels.length} models** available from ${available.length} provider(s).\n`, "info");
709
732
 
710
733
  // 2. Choose mode
711
734
  ctx.ui.notify("Choose setup mode:\n" +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phi-code-admin/phi-code",
3
- "version": "0.59.8",
3
+ "version": "0.60.0",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {