@mariozechner/pi-coding-agent 0.7.24 → 0.7.25
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/CHANGELOG.md +7 -1
- package/README.md +37 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +76 -10
- package/dist/main.js.map +1 -1
- package/dist/tui/custom-editor.d.ts +1 -0
- package/dist/tui/custom-editor.d.ts.map +1 -1
- package/dist/tui/custom-editor.js +6 -0
- package/dist/tui/custom-editor.js.map +1 -1
- package/dist/tui/tui-renderer.d.ts +4 -1
- package/dist/tui/tui-renderer.d.ts.map +1 -1
- package/dist/tui/tui-renderer.js +56 -2
- package/dist/tui/tui-renderer.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,11 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.7.25] - 2025-11-20
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Model Cycling**: Press `Ctrl+P` to quickly cycle through models. Use `--models` CLI argument to scope to specific models (e.g., `--models claude-sonnet,gpt-4o`). Supports pattern matching and smart version selection (prefers aliases over dated versions). ([#37](https://github.com/badlogic/pi-mono/pull/37) by [@fightbulc](https://github.com/fightbulc))
|
|
10
|
+
|
|
5
11
|
## [0.7.24] - 2025-11-20
|
|
6
12
|
|
|
7
13
|
### Added
|
|
8
14
|
|
|
9
|
-
- **Thinking Level Cycling**: Press `Shift+Tab` to cycle through thinking levels (off → minimal → low → medium → high) for reasoning-capable models. Editor border color changes to indicate current level (gray → blue → cyan → magenta).
|
|
15
|
+
- **Thinking Level Cycling**: Press `Shift+Tab` to cycle through thinking levels (off → minimal → low → medium → high) for reasoning-capable models. Editor border color changes to indicate current level (gray → blue → cyan → magenta). ([#36](https://github.com/badlogic/pi-mono/pull/36) by [@fightbulc](https://github.com/fightbulc))
|
|
10
16
|
|
|
11
17
|
## [0.7.23] - 2025-11-20
|
|
12
18
|
|
package/README.md
CHANGED
|
@@ -4,6 +4,30 @@ A radically simple and opinionated coding agent with multi-model support (includ
|
|
|
4
4
|
|
|
5
5
|
Works on Linux, macOS, and Windows (barely tested, needs Git Bash running in the "modern" Windows Terminal).
|
|
6
6
|
|
|
7
|
+
## Table of Contents
|
|
8
|
+
|
|
9
|
+
- [Installation](#installation)
|
|
10
|
+
- [Quick Start](#quick-start)
|
|
11
|
+
- [API Keys](#api-keys)
|
|
12
|
+
- [OAuth Authentication (Optional)](#oauth-authentication-optional)
|
|
13
|
+
- [Custom Models and Providers](#custom-models-and-providers)
|
|
14
|
+
- [Slash Commands](#slash-commands)
|
|
15
|
+
- [Editor Features](#editor-features)
|
|
16
|
+
- [Project Context Files](#project-context-files)
|
|
17
|
+
- [Image Support](#image-support)
|
|
18
|
+
- [Session Management](#session-management)
|
|
19
|
+
- [CLI Options](#cli-options)
|
|
20
|
+
- [Tools](#tools)
|
|
21
|
+
- [Usage](#usage)
|
|
22
|
+
- [Security (YOLO by default)](#security-yolo-by-default)
|
|
23
|
+
- [Sub-Agents](#sub-agents)
|
|
24
|
+
- [To-Dos](#to-dos)
|
|
25
|
+
- [Planning](#planning)
|
|
26
|
+
- [Background Bash](#background-bash)
|
|
27
|
+
- [Planned Features](#planned-features)
|
|
28
|
+
- [License](#license)
|
|
29
|
+
- [See Also](#see-also)
|
|
30
|
+
|
|
7
31
|
## Installation
|
|
8
32
|
|
|
9
33
|
```bash
|
|
@@ -333,6 +357,7 @@ Paste multiple lines of text (e.g., code snippets, logs) and they'll be automati
|
|
|
333
357
|
- **Ctrl+C**: Clear editor (first press) / Exit pi (second press)
|
|
334
358
|
- **Tab**: Path completion
|
|
335
359
|
- **Shift+Tab**: Cycle thinking level (for reasoning-capable models)
|
|
360
|
+
- **Ctrl+P**: Cycle models (use `--models` to scope)
|
|
336
361
|
- **Enter**: Send message
|
|
337
362
|
- **Shift+Enter**: Insert new line (multi-line input)
|
|
338
363
|
- **Backspace**: Delete character backwards
|
|
@@ -488,6 +513,14 @@ Continue the most recent session
|
|
|
488
513
|
**--resume, -r**
|
|
489
514
|
Select a session to resume (opens interactive selector)
|
|
490
515
|
|
|
516
|
+
**--models <patterns>**
|
|
517
|
+
Comma-separated model patterns for quick cycling with `Ctrl+P`. Patterns match against model IDs and names (case-insensitive). When multiple versions exist, prefers aliases over dated versions (e.g., `claude-sonnet-4-5` over `claude-sonnet-4-5-20250929`). Without this flag, `Ctrl+P` cycles through all available models.
|
|
518
|
+
|
|
519
|
+
Examples:
|
|
520
|
+
- `--models claude-sonnet,gpt-4o` - Scope to Claude Sonnet and GPT-4o
|
|
521
|
+
- `--models sonnet,haiku` - Match any model containing "sonnet" or "haiku"
|
|
522
|
+
- `--models gemini` - All Gemini models
|
|
523
|
+
|
|
491
524
|
**--help, -h**
|
|
492
525
|
Show help message
|
|
493
526
|
|
|
@@ -514,6 +547,10 @@ pi -c "What did we discuss?"
|
|
|
514
547
|
|
|
515
548
|
# Use different model
|
|
516
549
|
pi --provider openai --model gpt-4o "Help me refactor this code"
|
|
550
|
+
|
|
551
|
+
# Limit model cycling to specific models
|
|
552
|
+
pi --models claude-sonnet,claude-haiku,gpt-4o
|
|
553
|
+
# Now Ctrl+P cycles only through those models
|
|
517
554
|
```
|
|
518
555
|
|
|
519
556
|
## Tools
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAudA,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,iBAsWxC","sourcesContent":["import { Agent, ProviderTransport, type ThinkingLevel } from \"@mariozechner/pi-agent\";\nimport type { Api, KnownProvider, Model } from \"@mariozechner/pi-ai\";\nimport { ProcessTerminal, TUI } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join, resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { getChangelogPath, getNewEntries, parseChangelog } from \"./changelog.js\";\nimport { findModel, getApiKeyForModel, getAvailableModels } from \"./model-config.js\";\nimport { SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { codingTools } from \"./tools/index.js\";\nimport { SessionSelectorComponent } from \"./tui/session-selector.js\";\nimport { TuiRenderer } from \"./tui/tui-renderer.js\";\n\n// Get version from package.json\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, \"../package.json\"), \"utf-8\"));\nconst VERSION = packageJson.version;\n\nconst envApiKeyMap: Record<KnownProvider, string[]> = {\n\tgoogle: [\"GEMINI_API_KEY\"],\n\topenai: [\"OPENAI_API_KEY\"],\n\tanthropic: [\"ANTHROPIC_OAUTH_TOKEN\", \"ANTHROPIC_API_KEY\"],\n\txai: [\"XAI_API_KEY\"],\n\tgroq: [\"GROQ_API_KEY\"],\n\tcerebras: [\"CEREBRAS_API_KEY\"],\n\topenrouter: [\"OPENROUTER_API_KEY\"],\n\tzai: [\"ZAI_API_KEY\"],\n};\n\nconst defaultModelPerProvider: Record<KnownProvider, string> = {\n\tanthropic: \"claude-sonnet-4-5\",\n\topenai: \"gpt-5.1-codex\",\n\tgoogle: \"gemini-2.5-pro\",\n\topenrouter: \"openai/gpt-5.1-codex\",\n\txai: \"grok-4-fast-non-reasoning\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"zai-glm-4.6\",\n\tzai: \"glm-4.6\",\n};\n\ntype Mode = \"text\" | \"json\" | \"rpc\";\n\ninterface Args {\n\tprovider?: string;\n\tmodel?: string;\n\tapiKey?: string;\n\tsystemPrompt?: string;\n\tcontinue?: boolean;\n\tresume?: boolean;\n\thelp?: boolean;\n\tmode?: Mode;\n\tnoSession?: boolean;\n\tsession?: string;\n\tmessages: string[];\n}\n\nfunction parseArgs(args: string[]): Args {\n\tconst result: Args = {\n\t\tmessages: [],\n\t};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\tresult.help = true;\n\t\t} else if (arg === \"--mode\" && i + 1 < args.length) {\n\t\t\tconst mode = args[++i];\n\t\t\tif (mode === \"text\" || mode === \"json\" || mode === \"rpc\") {\n\t\t\t\tresult.mode = mode;\n\t\t\t}\n\t\t} else if (arg === \"--continue\" || arg === \"-c\") {\n\t\t\tresult.continue = true;\n\t\t} else if (arg === \"--resume\" || arg === \"-r\") {\n\t\t\tresult.resume = true;\n\t\t} else if (arg === \"--provider\" && i + 1 < args.length) {\n\t\t\tresult.provider = args[++i];\n\t\t} else if (arg === \"--model\" && i + 1 < args.length) {\n\t\t\tresult.model = args[++i];\n\t\t} else if (arg === \"--api-key\" && i + 1 < args.length) {\n\t\t\tresult.apiKey = args[++i];\n\t\t} else if (arg === \"--system-prompt\" && i + 1 < args.length) {\n\t\t\tresult.systemPrompt = args[++i];\n\t\t} else if (arg === \"--no-session\") {\n\t\t\tresult.noSession = true;\n\t\t} else if (arg === \"--session\" && i + 1 < args.length) {\n\t\t\tresult.session = args[++i];\n\t\t} else if (!arg.startsWith(\"-\")) {\n\t\t\tresult.messages.push(arg);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction printHelp() {\n\tconsole.log(`${chalk.bold(\"coding-agent\")} - AI coding assistant with read, bash, edit, write tools\n\n${chalk.bold(\"Usage:\")}\n coding-agent [options] [messages...]\n\n${chalk.bold(\"Options:\")}\n --provider <name> Provider name (default: google)\n --model <id> Model ID (default: gemini-2.5-flash)\n --api-key <key> API key (defaults to env vars)\n --system-prompt <text> System prompt (default: coding assistant prompt)\n --mode <mode> Output mode: text (default), json, or rpc\n --continue, -c Continue previous session\n --resume, -r Select a session to resume\n --session <path> Use specific session file\n --no-session Don't save session (ephemeral)\n --help, -h Show this help\n\n${chalk.bold(\"Examples:\")}\n # Interactive mode (no messages = interactive TUI)\n coding-agent\n\n # Single message\n coding-agent \"List all .ts files in src/\"\n\n # Multiple messages\n coding-agent \"Read package.json\" \"What dependencies do we have?\"\n\n # Continue previous session\n coding-agent --continue \"What did we discuss?\"\n\n # Use different model\n coding-agent --provider openai --model gpt-4o-mini \"Help me refactor this code\"\n\n${chalk.bold(\"Environment Variables:\")}\n GEMINI_API_KEY - Google Gemini API key\n OPENAI_API_KEY - OpenAI API key\n ANTHROPIC_API_KEY - Anthropic API key\n CODING_AGENT_DIR - Session storage directory (default: ~/.coding-agent)\n\n${chalk.bold(\"Available Tools:\")}\n read - Read file contents\n bash - Execute bash commands\n edit - Edit files with find/replace\n write - Write files (creates/overwrites)\n`);\n}\n\nfunction buildSystemPrompt(customPrompt?: string): string {\n\t// Check if customPrompt is a file path that exists\n\tif (customPrompt && existsSync(customPrompt)) {\n\t\ttry {\n\t\t\tcustomPrompt = readFileSync(customPrompt, \"utf-8\");\n\t\t} catch (error) {\n\t\t\tconsole.error(chalk.yellow(`Warning: Could not read system prompt file ${customPrompt}: ${error}`));\n\t\t\t// Fall through to use as literal string\n\t\t}\n\t}\n\n\tif (customPrompt) {\n\t\t// Use custom prompt as base, then add context/datetime\n\t\tconst now = new Date();\n\t\tconst dateTime = now.toLocaleString(\"en-US\", {\n\t\t\tweekday: \"long\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"long\",\n\t\t\tday: \"numeric\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t\ttimeZoneName: \"short\",\n\t\t});\n\n\t\tlet prompt = customPrompt;\n\n\t\t// Append project context files\n\t\tconst contextFiles = loadProjectContextFiles();\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"The following project context files have been loaded:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Add date/time and working directory last\n\t\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\t\tprompt += `\\nCurrent working directory: ${process.cwd()}`;\n\n\t\treturn prompt;\n\t}\n\n\tconst now = new Date();\n\tconst dateTime = now.toLocaleString(\"en-US\", {\n\t\tweekday: \"long\",\n\t\tyear: \"numeric\",\n\t\tmonth: \"long\",\n\t\tday: \"numeric\",\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t\tsecond: \"2-digit\",\n\t\ttimeZoneName: \"short\",\n\t});\n\n\t// Get absolute path to README.md\n\tconst readmePath = resolve(join(__dirname, \"../README.md\"));\n\n\tlet prompt = `You are actually not Claude, you are Pi. You are an expert coding assistant. You help users with coding tasks by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n- read: Read file contents\n- bash: Execute bash commands (ls, grep, find, etc.)\n- edit: Make surgical edits to files (find exact text and replace)\n- write: Create or overwrite files\n\nGuidelines:\n- Always use bash tool for file operations like ls, grep, find\n- Use read to examine files before editing\n- Use edit for precise changes (old text must match exactly)\n- Use write only for new files or complete rewrites\n- Be concise in your responses\n- Show file paths clearly when working with files\n- When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did\n\nDocumentation:\n- Your own documentation (including custom model setup) is at: ${readmePath}\n- Read it when users ask about features, configuration, or setup, and especially if the user asks you to add a custom model or provider.`;\n\n\t// Append project context files\n\tconst contextFiles = loadProjectContextFiles();\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"The following project context files have been loaded:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Add date/time and working directory last\n\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\tprompt += `\\nCurrent working directory: ${process.cwd()}`;\n\n\treturn prompt;\n}\n\n/**\n * Look for AGENTS.md or CLAUDE.md in a directory (prefers AGENTS.md)\n */\nfunction loadContextFileFromDir(dir: string): { path: string; content: string } | null {\n\tconst candidates = [\"AGENTS.md\", \"CLAUDE.md\"];\n\tfor (const filename of candidates) {\n\t\tconst filePath = join(dir, filename);\n\t\tif (existsSync(filePath)) {\n\t\t\ttry {\n\t\t\t\treturn {\n\t\t\t\t\tpath: filePath,\n\t\t\t\t\tcontent: readFileSync(filePath, \"utf-8\"),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(chalk.yellow(`Warning: Could not read ${filePath}: ${error}`));\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Load all project context files in order:\n * 1. Global: ~/.pi/agent/AGENTS.md or CLAUDE.md\n * 2. Parent directories (top-most first) down to cwd\n * Each returns {path, content} for separate messages\n */\nfunction loadProjectContextFiles(): Array<{ path: string; content: string }> {\n\tconst contextFiles: Array<{ path: string; content: string }> = [];\n\n\t// 1. Load global context from ~/.pi/agent/\n\tconst homeDir = homedir();\n\tconst globalContextDir = resolve(process.env.CODING_AGENT_DIR || join(homeDir, \".pi/agent/\"));\n\tconst globalContext = loadContextFileFromDir(globalContextDir);\n\tif (globalContext) {\n\t\tcontextFiles.push(globalContext);\n\t}\n\n\t// 2. Walk up from cwd to root, collecting all context files\n\tconst cwd = process.cwd();\n\tconst ancestorContextFiles: Array<{ path: string; content: string }> = [];\n\n\tlet currentDir = cwd;\n\tconst root = resolve(\"/\");\n\n\twhile (true) {\n\t\tconst contextFile = loadContextFileFromDir(currentDir);\n\t\tif (contextFile) {\n\t\t\t// Add to beginning so we get top-most parent first\n\t\t\tancestorContextFiles.unshift(contextFile);\n\t\t}\n\n\t\t// Stop if we've reached root\n\t\tif (currentDir === root) break;\n\n\t\t// Move up one directory\n\t\tconst parentDir = resolve(currentDir, \"..\");\n\t\tif (parentDir === currentDir) break; // Safety check\n\t\tcurrentDir = parentDir;\n\t}\n\n\t// Add ancestor files in order (top-most → cwd)\n\tcontextFiles.push(...ancestorContextFiles);\n\n\treturn contextFiles;\n}\n\nasync function checkForNewVersion(currentVersion: string): Promise<string | null> {\n\ttry {\n\t\tconst response = await fetch(\"https://registry.npmjs.org/@mariozechner/pi-coding-agent/latest\");\n\t\tif (!response.ok) return null;\n\n\t\tconst data = (await response.json()) as { version?: string };\n\t\tconst latestVersion = data.version;\n\n\t\tif (latestVersion && latestVersion !== currentVersion) {\n\t\t\treturn latestVersion;\n\t\t}\n\n\t\treturn null;\n\t} catch (error) {\n\t\t// Silently fail - don't disrupt the user experience\n\t\treturn null;\n\t}\n}\n\nasync function selectSession(sessionManager: SessionManager): Promise<string | null> {\n\treturn new Promise((resolve) => {\n\t\tconst ui = new TUI(new ProcessTerminal());\n\t\tlet resolved = false;\n\n\t\tconst selector = new SessionSelectorComponent(\n\t\t\tsessionManager,\n\t\t\t(path: string) => {\n\t\t\t\tif (!resolved) {\n\t\t\t\t\tresolved = true;\n\t\t\t\t\tui.stop();\n\t\t\t\t\tresolve(path);\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (!resolved) {\n\t\t\t\t\tresolved = true;\n\t\t\t\t\tui.stop();\n\t\t\t\t\tresolve(null);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tui.addChild(selector);\n\t\tui.setFocus(selector.getSessionList());\n\t\tui.start();\n\t});\n}\n\nasync function runInteractiveMode(\n\tagent: Agent,\n\tsessionManager: SessionManager,\n\tsettingsManager: SettingsManager,\n\tversion: string,\n\tchangelogMarkdown: string | null = null,\n\tmodelFallbackMessage: string | null = null,\n\tnewVersion: string | null = null,\n): Promise<void> {\n\tconst renderer = new TuiRenderer(agent, sessionManager, settingsManager, version, changelogMarkdown, newVersion);\n\n\t// Initialize TUI\n\tawait renderer.init();\n\n\t// Set interrupt callback\n\trenderer.setInterruptCallback(() => {\n\t\tagent.abort();\n\t});\n\n\t// Render any existing messages (from --continue mode)\n\trenderer.renderInitialMessages(agent.state);\n\n\t// Show model fallback warning at the end of the chat if applicable\n\tif (modelFallbackMessage) {\n\t\trenderer.showWarning(modelFallbackMessage);\n\t}\n\n\t// Subscribe to agent events\n\tagent.subscribe(async (event) => {\n\t\t// Pass all events to the renderer\n\t\tawait renderer.handleEvent(event, agent.state);\n\t});\n\n\t// Interactive loop\n\twhile (true) {\n\t\tconst userInput = await renderer.getUserInput();\n\n\t\t// Process the message - agent.prompt will add user message and trigger state updates\n\t\ttry {\n\t\t\tawait agent.prompt(userInput);\n\t\t} catch (error: any) {\n\t\t\t// Display error in the TUI by adding an error message to the chat\n\t\t\trenderer.showError(error.message || \"Unknown error occurred\");\n\t\t}\n\t}\n}\n\nasync function runSingleShotMode(\n\tagent: Agent,\n\t_sessionManager: SessionManager,\n\tmessages: string[],\n\tmode: \"text\" | \"json\",\n): Promise<void> {\n\tif (mode === \"json\") {\n\t\t// Subscribe to all events and output as JSON\n\t\tagent.subscribe((event) => {\n\t\t\t// Output event as JSON (same format as session manager)\n\t\t\tconsole.log(JSON.stringify(event));\n\t\t});\n\t}\n\n\tfor (const message of messages) {\n\t\tawait agent.prompt(message);\n\t}\n\n\t// In text mode, only output the final assistant message\n\tif (mode === \"text\") {\n\t\tconst lastMessage = agent.state.messages[agent.state.messages.length - 1];\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tfor (const content of lastMessage.content) {\n\t\t\t\tif (content.type === \"text\") {\n\t\t\t\t\tconsole.log(content.text);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nasync function runRpcMode(agent: Agent, _sessionManager: SessionManager): Promise<void> {\n\t// Subscribe to all events and output as JSON\n\tagent.subscribe((event) => {\n\t\tconsole.log(JSON.stringify(event));\n\t});\n\n\t// Listen for JSON input on stdin\n\tconst readline = await import(\"readline\");\n\tconst rl = readline.createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout,\n\t\tterminal: false,\n\t});\n\n\trl.on(\"line\", async (line: string) => {\n\t\ttry {\n\t\t\tconst input = JSON.parse(line);\n\n\t\t\t// Handle different RPC commands\n\t\t\tif (input.type === \"prompt\" && input.message) {\n\t\t\t\tawait agent.prompt(input.message);\n\t\t\t} else if (input.type === \"abort\") {\n\t\t\t\tagent.abort();\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\t// Output error as JSON\n\t\t\tconsole.log(JSON.stringify({ type: \"error\", error: error.message }));\n\t\t}\n\t});\n\n\t// Keep process alive\n\treturn new Promise(() => {});\n}\n\nexport async function main(args: string[]) {\n\tconst parsed = parseArgs(args);\n\n\tif (parsed.help) {\n\t\tprintHelp();\n\t\treturn;\n\t}\n\n\t// Setup session manager\n\tconst sessionManager = new SessionManager(parsed.continue && !parsed.resume, parsed.session);\n\n\t// Disable session saving if --no-session flag is set\n\tif (parsed.noSession) {\n\t\tsessionManager.disable();\n\t}\n\n\t// Handle --resume flag: show session selector\n\tif (parsed.resume) {\n\t\tconst selectedSession = await selectSession(sessionManager);\n\t\tif (!selectedSession) {\n\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\treturn;\n\t\t}\n\t\t// Set the selected session as the active session\n\t\tsessionManager.setSessionFile(selectedSession);\n\t}\n\n\t// Settings manager\n\tconst settingsManager = new SettingsManager();\n\n\t// Determine initial model using priority system:\n\t// 1. CLI args (--provider and --model)\n\t// 2. Restored from session (if --continue or --resume)\n\t// 3. Saved default from settings.json\n\t// 4. First available model with valid API key\n\t// 5. null (allowed in interactive mode)\n\tlet initialModel: Model<Api> | null = null;\n\n\tif (parsed.provider && parsed.model) {\n\t\t// 1. CLI args take priority\n\t\tconst { model, error } = findModel(parsed.provider, parsed.model);\n\t\tif (error) {\n\t\t\tconsole.error(chalk.red(error));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tif (!model) {\n\t\t\tconsole.error(chalk.red(`Model ${parsed.provider}/${parsed.model} not found`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tinitialModel = model;\n\t} else if (parsed.continue || parsed.resume) {\n\t\t// 2. Restore from session (will be handled below after loading session)\n\t\t// Leave initialModel as null for now\n\t}\n\n\tif (!initialModel) {\n\t\t// 3. Try saved default from settings\n\t\tconst defaultProvider = settingsManager.getDefaultProvider();\n\t\tconst defaultModel = settingsManager.getDefaultModel();\n\t\tif (defaultProvider && defaultModel) {\n\t\t\tconst { model, error } = findModel(defaultProvider, defaultModel);\n\t\t\tif (error) {\n\t\t\t\tconsole.error(chalk.red(error));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tinitialModel = model;\n\t\t}\n\t}\n\n\tif (!initialModel) {\n\t\t// 4. Try first available model with valid API key\n\t\t// Prefer default model for each provider if available\n\t\tconst { models: availableModels, error } = await getAvailableModels();\n\n\t\tif (error) {\n\t\t\tconsole.error(chalk.red(error));\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tif (availableModels.length > 0) {\n\t\t\t// Try to find a default model from known providers\n\t\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\t\tconst defaultModelId = defaultModelPerProvider[provider];\n\t\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultModelId);\n\t\t\t\tif (match) {\n\t\t\t\t\tinitialModel = match;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If no default found, use first available\n\t\t\tif (!initialModel) {\n\t\t\t\tinitialModel = availableModels[0];\n\t\t\t}\n\t\t}\n\t}\n\n\t// Determine mode early to know if we should print messages and fail early\n\tconst isInteractive = parsed.messages.length === 0 && parsed.mode === undefined;\n\tconst mode = parsed.mode || \"text\";\n\tconst shouldPrintMessages = isInteractive || mode === \"text\";\n\n\t// Non-interactive mode: fail early if no model available\n\tif (!isInteractive && !initialModel) {\n\t\tconsole.error(chalk.red(\"No models available.\"));\n\t\tconsole.error(chalk.yellow(\"\\nSet an API key environment variable:\"));\n\t\tconsole.error(\" ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, etc.\");\n\t\tconsole.error(chalk.yellow(\"\\nOr create ~/.pi/agent/models.json\"));\n\t\tprocess.exit(1);\n\t}\n\n\t// Non-interactive mode: validate API key exists\n\tif (!isInteractive && initialModel) {\n\t\tconst apiKey = parsed.apiKey || (await getApiKeyForModel(initialModel));\n\t\tif (!apiKey) {\n\t\t\tconsole.error(chalk.red(`No API key found for ${initialModel.provider}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tconst systemPrompt = buildSystemPrompt(parsed.systemPrompt);\n\n\t// Load previous messages if continuing or resuming\n\t// This may update initialModel if restoring from session\n\tif (parsed.continue || parsed.resume) {\n\t\tconst messages = sessionManager.loadMessages();\n\t\tif (messages.length > 0 && shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Loaded ${messages.length} messages from previous session`));\n\t\t}\n\n\t\t// Load and restore model (overrides initialModel if found and has API key)\n\t\tconst savedModel = sessionManager.loadModel();\n\t\tif (savedModel) {\n\t\t\tconst { model: restoredModel, error } = findModel(savedModel.provider, savedModel.modelId);\n\n\t\t\tif (error) {\n\t\t\t\tconsole.error(chalk.red(error));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\t// Check if restored model exists and has a valid API key\n\t\t\tconst hasApiKey = restoredModel ? !!(await getApiKeyForModel(restoredModel)) : false;\n\n\t\t\tif (restoredModel && hasApiKey) {\n\t\t\t\tinitialModel = restoredModel;\n\t\t\t\tif (shouldPrintMessages) {\n\t\t\t\t\tconsole.log(chalk.dim(`Restored model: ${savedModel.provider}/${savedModel.modelId}`));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Model not found or no API key - fall back to default selection\n\t\t\t\tconst reason = !restoredModel ? \"model no longer exists\" : \"no API key available\";\n\n\t\t\t\tif (shouldPrintMessages) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Warning: Could not restore model ${savedModel.provider}/${savedModel.modelId} (${reason}).`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Ensure we have a valid model - use the same fallback logic\n\t\t\t\tif (!initialModel) {\n\t\t\t\t\tconst { models: availableModels, error: availableError } = await getAvailableModels();\n\t\t\t\t\tif (availableError) {\n\t\t\t\t\t\tconsole.error(chalk.red(availableError));\n\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t}\n\t\t\t\t\tif (availableModels.length > 0) {\n\t\t\t\t\t\t// Try to find a default model from known providers\n\t\t\t\t\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\t\t\t\t\tconst defaultModelId = defaultModelPerProvider[provider];\n\t\t\t\t\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultModelId);\n\t\t\t\t\t\t\tif (match) {\n\t\t\t\t\t\t\t\tinitialModel = match;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// If no default found, use first available\n\t\t\t\t\t\tif (!initialModel) {\n\t\t\t\t\t\t\tinitialModel = availableModels[0];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (initialModel && shouldPrintMessages) {\n\t\t\t\t\t\t\tconsole.log(chalk.dim(`Falling back to: ${initialModel.provider}/${initialModel.id}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No models available at all\n\t\t\t\t\t\tif (shouldPrintMessages) {\n\t\t\t\t\t\t\tconsole.error(chalk.red(\"\\nNo models available.\"));\n\t\t\t\t\t\t\tconsole.error(chalk.yellow(\"Set an API key environment variable:\"));\n\t\t\t\t\t\t\tconsole.error(\" ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, etc.\");\n\t\t\t\t\t\t\tconsole.error(chalk.yellow(\"\\nOr create ~/.pi/agent/models.json\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t}\n\t\t\t\t} else if (shouldPrintMessages) {\n\t\t\t\t\tconsole.log(chalk.dim(`Falling back to: ${initialModel.provider}/${initialModel.id}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create agent (initialModel can be null in interactive mode)\n\tconst agent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt,\n\t\t\tmodel: initialModel as any, // Can be null\n\t\t\tthinkingLevel: \"off\",\n\t\t\ttools: codingTools,\n\t\t},\n\t\ttransport: new ProviderTransport({\n\t\t\t// Dynamic API key lookup based on current model's provider\n\t\t\tgetApiKey: async () => {\n\t\t\t\tconst currentModel = agent.state.model;\n\t\t\t\tif (!currentModel) {\n\t\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t\t}\n\n\t\t\t\t// Try CLI override first\n\t\t\t\tif (parsed.apiKey) {\n\t\t\t\t\treturn parsed.apiKey;\n\t\t\t\t}\n\n\t\t\t\t// Use model-specific key lookup\n\t\t\t\tconst key = await getApiKeyForModel(currentModel);\n\t\t\t\tif (!key) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`No API key found for provider \"${currentModel.provider}\". Please set the appropriate environment variable or update ~/.pi/agent/models.json`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn key;\n\t\t\t},\n\t\t}),\n\t});\n\n\t// Track if we had to fall back from saved model (to show in chat later)\n\tlet modelFallbackMessage: string | null = null;\n\n\t// Load previous messages if continuing or resuming\n\tif (parsed.continue || parsed.resume) {\n\t\tconst messages = sessionManager.loadMessages();\n\t\tif (messages.length > 0) {\n\t\t\tagent.replaceMessages(messages);\n\t\t}\n\n\t\t// Load and restore thinking level\n\t\tconst thinkingLevel = sessionManager.loadThinkingLevel() as ThinkingLevel;\n\t\tif (thinkingLevel) {\n\t\t\tagent.setThinkingLevel(thinkingLevel);\n\t\t\tif (shouldPrintMessages) {\n\t\t\t\tconsole.log(chalk.dim(`Restored thinking level: ${thinkingLevel}`));\n\t\t\t}\n\t\t}\n\n\t\t// Check if we had to fall back from saved model\n\t\tconst savedModel = sessionManager.loadModel();\n\t\tif (savedModel && initialModel) {\n\t\t\tconst savedMatches = initialModel.provider === savedModel.provider && initialModel.id === savedModel.modelId;\n\t\t\tif (!savedMatches) {\n\t\t\t\tconst { model: restoredModel, error } = findModel(savedModel.provider, savedModel.modelId);\n\t\t\t\tif (error) {\n\t\t\t\t\t// Config error - already shown above, just use generic message\n\t\t\t\t\tmodelFallbackMessage = `Could not restore model ${savedModel.provider}/${savedModel.modelId}. Using ${initialModel.provider}/${initialModel.id}.`;\n\t\t\t\t} else {\n\t\t\t\t\tconst reason = !restoredModel ? \"model no longer exists\" : \"no API key available\";\n\t\t\t\t\tmodelFallbackMessage = `Could not restore model ${savedModel.provider}/${savedModel.modelId} (${reason}). Using ${initialModel.provider}/${initialModel.id}.`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Note: Session will be started lazily after first user+assistant message exchange\n\t// (unless continuing/resuming, in which case it's already initialized)\n\n\t// Log loaded context files (they're already in the system prompt)\n\tif (shouldPrintMessages && !parsed.continue && !parsed.resume) {\n\t\tconst contextFiles = loadProjectContextFiles();\n\t\tif (contextFiles.length > 0) {\n\t\t\tconsole.log(chalk.dim(\"Loaded project context from:\"));\n\t\t\tfor (const { path: filePath } of contextFiles) {\n\t\t\t\tconsole.log(chalk.dim(` - ${filePath}`));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Subscribe to agent events to save messages\n\tagent.subscribe((event) => {\n\t\t// Save messages on completion\n\t\tif (event.type === \"message_end\") {\n\t\t\tsessionManager.saveMessage(event.message);\n\n\t\t\t// Check if we should initialize session now (after first user+assistant exchange)\n\t\t\tif (sessionManager.shouldInitializeSession(agent.state.messages)) {\n\t\t\t\tsessionManager.startSession(agent.state);\n\t\t\t}\n\t\t}\n\t});\n\n\t// Route to appropriate mode\n\tif (mode === \"rpc\") {\n\t\t// RPC mode - headless operation\n\t\tawait runRpcMode(agent, sessionManager);\n\t} else if (isInteractive) {\n\t\t// Check for new version (don't block startup if it takes too long)\n\t\tlet newVersion: string | null = null;\n\t\ttry {\n\t\t\tnewVersion = await Promise.race([\n\t\t\t\tcheckForNewVersion(VERSION),\n\t\t\t\tnew Promise<null>((resolve) => setTimeout(() => resolve(null), 1000)), // 1 second timeout\n\t\t\t]);\n\t\t} catch (e) {\n\t\t\t// Ignore errors\n\t\t}\n\n\t\t// Check if we should show changelog (only in interactive mode, only for new sessions)\n\t\tlet changelogMarkdown: string | null = null;\n\t\tif (!parsed.continue && !parsed.resume) {\n\t\t\tconst lastVersion = settingsManager.getLastChangelogVersion();\n\n\t\t\t// Check if we need to show changelog\n\t\t\tif (!lastVersion) {\n\t\t\t\t// First run - show all entries\n\t\t\t\tconst changelogPath = getChangelogPath();\n\t\t\t\tconst entries = parseChangelog(changelogPath);\n\t\t\t\tif (entries.length > 0) {\n\t\t\t\t\tchangelogMarkdown = entries.map((e) => e.content).join(\"\\n\\n\");\n\t\t\t\t\tsettingsManager.setLastChangelogVersion(VERSION);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Parse current and last versions\n\t\t\t\tconst currentParts = VERSION.split(\".\").map(Number);\n\t\t\t\tconst current = { major: currentParts[0] || 0, minor: currentParts[1] || 0, patch: currentParts[2] || 0 };\n\t\t\t\tconst changelogPath = getChangelogPath();\n\t\t\t\tconst entries = parseChangelog(changelogPath);\n\t\t\t\tconst newEntries = getNewEntries(entries, lastVersion);\n\n\t\t\t\tif (newEntries.length > 0) {\n\t\t\t\t\tchangelogMarkdown = newEntries.map((e) => e.content).join(\"\\n\\n\");\n\t\t\t\t\tsettingsManager.setLastChangelogVersion(VERSION);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// No messages and not RPC - use TUI\n\t\tawait runInteractiveMode(\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tVERSION,\n\t\t\tchangelogMarkdown,\n\t\t\tmodelFallbackMessage,\n\t\t\tnewVersion,\n\t\t);\n\t} else {\n\t\t// CLI mode with messages\n\t\tawait runSingleShotMode(agent, sessionManager, parsed.messages, mode);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAuiBA,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,iBAmXxC","sourcesContent":["import { Agent, ProviderTransport, type ThinkingLevel } from \"@mariozechner/pi-agent\";\nimport type { Api, KnownProvider, Model } from \"@mariozechner/pi-ai\";\nimport { ProcessTerminal, TUI } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join, resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { getChangelogPath, getNewEntries, parseChangelog } from \"./changelog.js\";\nimport { findModel, getApiKeyForModel, getAvailableModels } from \"./model-config.js\";\nimport { SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { codingTools } from \"./tools/index.js\";\nimport { SessionSelectorComponent } from \"./tui/session-selector.js\";\nimport { TuiRenderer } from \"./tui/tui-renderer.js\";\n\n// Get version from package.json\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, \"../package.json\"), \"utf-8\"));\nconst VERSION = packageJson.version;\n\nconst envApiKeyMap: Record<KnownProvider, string[]> = {\n\tgoogle: [\"GEMINI_API_KEY\"],\n\topenai: [\"OPENAI_API_KEY\"],\n\tanthropic: [\"ANTHROPIC_OAUTH_TOKEN\", \"ANTHROPIC_API_KEY\"],\n\txai: [\"XAI_API_KEY\"],\n\tgroq: [\"GROQ_API_KEY\"],\n\tcerebras: [\"CEREBRAS_API_KEY\"],\n\topenrouter: [\"OPENROUTER_API_KEY\"],\n\tzai: [\"ZAI_API_KEY\"],\n};\n\nconst defaultModelPerProvider: Record<KnownProvider, string> = {\n\tanthropic: \"claude-sonnet-4-5\",\n\topenai: \"gpt-5.1-codex\",\n\tgoogle: \"gemini-2.5-pro\",\n\topenrouter: \"openai/gpt-5.1-codex\",\n\txai: \"grok-4-fast-non-reasoning\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"zai-glm-4.6\",\n\tzai: \"glm-4.6\",\n};\n\ntype Mode = \"text\" | \"json\" | \"rpc\";\n\ninterface Args {\n\tprovider?: string;\n\tmodel?: string;\n\tapiKey?: string;\n\tsystemPrompt?: string;\n\tcontinue?: boolean;\n\tresume?: boolean;\n\thelp?: boolean;\n\tmode?: Mode;\n\tnoSession?: boolean;\n\tsession?: string;\n\tmodels?: string[];\n\tmessages: string[];\n}\n\nfunction parseArgs(args: string[]): Args {\n\tconst result: Args = {\n\t\tmessages: [],\n\t};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\tresult.help = true;\n\t\t} else if (arg === \"--mode\" && i + 1 < args.length) {\n\t\t\tconst mode = args[++i];\n\t\t\tif (mode === \"text\" || mode === \"json\" || mode === \"rpc\") {\n\t\t\t\tresult.mode = mode;\n\t\t\t}\n\t\t} else if (arg === \"--continue\" || arg === \"-c\") {\n\t\t\tresult.continue = true;\n\t\t} else if (arg === \"--resume\" || arg === \"-r\") {\n\t\t\tresult.resume = true;\n\t\t} else if (arg === \"--provider\" && i + 1 < args.length) {\n\t\t\tresult.provider = args[++i];\n\t\t} else if (arg === \"--model\" && i + 1 < args.length) {\n\t\t\tresult.model = args[++i];\n\t\t} else if (arg === \"--api-key\" && i + 1 < args.length) {\n\t\t\tresult.apiKey = args[++i];\n\t\t} else if (arg === \"--system-prompt\" && i + 1 < args.length) {\n\t\t\tresult.systemPrompt = args[++i];\n\t\t} else if (arg === \"--no-session\") {\n\t\t\tresult.noSession = true;\n\t\t} else if (arg === \"--session\" && i + 1 < args.length) {\n\t\t\tresult.session = args[++i];\n\t\t} else if (arg === \"--models\" && i + 1 < args.length) {\n\t\t\tresult.models = args[++i].split(\",\").map((s) => s.trim());\n\t\t} else if (!arg.startsWith(\"-\")) {\n\t\t\tresult.messages.push(arg);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction printHelp() {\n\tconsole.log(`${chalk.bold(\"pi\")} - AI coding assistant with read, bash, edit, write tools\n\n${chalk.bold(\"Usage:\")}\n pi [options] [messages...]\n\n${chalk.bold(\"Options:\")}\n --provider <name> Provider name (default: google)\n --model <id> Model ID (default: gemini-2.5-flash)\n --api-key <key> API key (defaults to env vars)\n --system-prompt <text> System prompt (default: coding assistant prompt)\n --mode <mode> Output mode: text (default), json, or rpc\n --continue, -c Continue previous session\n --resume, -r Select a session to resume\n --session <path> Use specific session file\n --no-session Don't save session (ephemeral)\n --models <patterns> Comma-separated model patterns for quick cycling with Ctrl+P\n --help, -h Show this help\n\n${chalk.bold(\"Examples:\")}\n # Interactive mode (no messages = interactive TUI)\n pi\n\n # Single message\n pi \"List all .ts files in src/\"\n\n # Multiple messages\n pi \"Read package.json\" \"What dependencies do we have?\"\n\n # Continue previous session\n pi --continue \"What did we discuss?\"\n\n # Use different model\n pi --provider openai --model gpt-4o-mini \"Help me refactor this code\"\n\n # Limit model cycling to specific models\n pi --models claude-sonnet,claude-haiku,gpt-4o\n\n${chalk.bold(\"Environment Variables:\")}\n GEMINI_API_KEY - Google Gemini API key\n OPENAI_API_KEY - OpenAI API key\n ANTHROPIC_API_KEY - Anthropic API key\n CODING_AGENT_DIR - Session storage directory (default: ~/.coding-agent)\n\n${chalk.bold(\"Available Tools:\")}\n read - Read file contents\n bash - Execute bash commands\n edit - Edit files with find/replace\n write - Write files (creates/overwrites)\n`);\n}\n\nfunction buildSystemPrompt(customPrompt?: string): string {\n\t// Check if customPrompt is a file path that exists\n\tif (customPrompt && existsSync(customPrompt)) {\n\t\ttry {\n\t\t\tcustomPrompt = readFileSync(customPrompt, \"utf-8\");\n\t\t} catch (error) {\n\t\t\tconsole.error(chalk.yellow(`Warning: Could not read system prompt file ${customPrompt}: ${error}`));\n\t\t\t// Fall through to use as literal string\n\t\t}\n\t}\n\n\tif (customPrompt) {\n\t\t// Use custom prompt as base, then add context/datetime\n\t\tconst now = new Date();\n\t\tconst dateTime = now.toLocaleString(\"en-US\", {\n\t\t\tweekday: \"long\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"long\",\n\t\t\tday: \"numeric\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t\ttimeZoneName: \"short\",\n\t\t});\n\n\t\tlet prompt = customPrompt;\n\n\t\t// Append project context files\n\t\tconst contextFiles = loadProjectContextFiles();\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"The following project context files have been loaded:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Add date/time and working directory last\n\t\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\t\tprompt += `\\nCurrent working directory: ${process.cwd()}`;\n\n\t\treturn prompt;\n\t}\n\n\tconst now = new Date();\n\tconst dateTime = now.toLocaleString(\"en-US\", {\n\t\tweekday: \"long\",\n\t\tyear: \"numeric\",\n\t\tmonth: \"long\",\n\t\tday: \"numeric\",\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t\tsecond: \"2-digit\",\n\t\ttimeZoneName: \"short\",\n\t});\n\n\t// Get absolute path to README.md\n\tconst readmePath = resolve(join(__dirname, \"../README.md\"));\n\n\tlet prompt = `You are actually not Claude, you are Pi. You are an expert coding assistant. You help users with coding tasks by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n- read: Read file contents\n- bash: Execute bash commands (ls, grep, find, etc.)\n- edit: Make surgical edits to files (find exact text and replace)\n- write: Create or overwrite files\n\nGuidelines:\n- Always use bash tool for file operations like ls, grep, find\n- Use read to examine files before editing\n- Use edit for precise changes (old text must match exactly)\n- Use write only for new files or complete rewrites\n- Be concise in your responses\n- Show file paths clearly when working with files\n- When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did\n\nDocumentation:\n- Your own documentation (including custom model setup) is at: ${readmePath}\n- Read it when users ask about features, configuration, or setup, and especially if the user asks you to add a custom model or provider.`;\n\n\t// Append project context files\n\tconst contextFiles = loadProjectContextFiles();\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"The following project context files have been loaded:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Add date/time and working directory last\n\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\tprompt += `\\nCurrent working directory: ${process.cwd()}`;\n\n\treturn prompt;\n}\n\n/**\n * Look for AGENTS.md or CLAUDE.md in a directory (prefers AGENTS.md)\n */\nfunction loadContextFileFromDir(dir: string): { path: string; content: string } | null {\n\tconst candidates = [\"AGENTS.md\", \"CLAUDE.md\"];\n\tfor (const filename of candidates) {\n\t\tconst filePath = join(dir, filename);\n\t\tif (existsSync(filePath)) {\n\t\t\ttry {\n\t\t\t\treturn {\n\t\t\t\t\tpath: filePath,\n\t\t\t\t\tcontent: readFileSync(filePath, \"utf-8\"),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(chalk.yellow(`Warning: Could not read ${filePath}: ${error}`));\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Load all project context files in order:\n * 1. Global: ~/.pi/agent/AGENTS.md or CLAUDE.md\n * 2. Parent directories (top-most first) down to cwd\n * Each returns {path, content} for separate messages\n */\nfunction loadProjectContextFiles(): Array<{ path: string; content: string }> {\n\tconst contextFiles: Array<{ path: string; content: string }> = [];\n\n\t// 1. Load global context from ~/.pi/agent/\n\tconst homeDir = homedir();\n\tconst globalContextDir = resolve(process.env.CODING_AGENT_DIR || join(homeDir, \".pi/agent/\"));\n\tconst globalContext = loadContextFileFromDir(globalContextDir);\n\tif (globalContext) {\n\t\tcontextFiles.push(globalContext);\n\t}\n\n\t// 2. Walk up from cwd to root, collecting all context files\n\tconst cwd = process.cwd();\n\tconst ancestorContextFiles: Array<{ path: string; content: string }> = [];\n\n\tlet currentDir = cwd;\n\tconst root = resolve(\"/\");\n\n\twhile (true) {\n\t\tconst contextFile = loadContextFileFromDir(currentDir);\n\t\tif (contextFile) {\n\t\t\t// Add to beginning so we get top-most parent first\n\t\t\tancestorContextFiles.unshift(contextFile);\n\t\t}\n\n\t\t// Stop if we've reached root\n\t\tif (currentDir === root) break;\n\n\t\t// Move up one directory\n\t\tconst parentDir = resolve(currentDir, \"..\");\n\t\tif (parentDir === currentDir) break; // Safety check\n\t\tcurrentDir = parentDir;\n\t}\n\n\t// Add ancestor files in order (top-most → cwd)\n\tcontextFiles.push(...ancestorContextFiles);\n\n\treturn contextFiles;\n}\n\nasync function checkForNewVersion(currentVersion: string): Promise<string | null> {\n\ttry {\n\t\tconst response = await fetch(\"https://registry.npmjs.org/@mariozechner/pi-coding-agent/latest\");\n\t\tif (!response.ok) return null;\n\n\t\tconst data = (await response.json()) as { version?: string };\n\t\tconst latestVersion = data.version;\n\n\t\tif (latestVersion && latestVersion !== currentVersion) {\n\t\t\treturn latestVersion;\n\t\t}\n\n\t\treturn null;\n\t} catch (error) {\n\t\t// Silently fail - don't disrupt the user experience\n\t\treturn null;\n\t}\n}\n\n/**\n * Resolve model patterns to actual Model objects\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n */\nasync function resolveModelScope(patterns: string[]): Promise<Model<Api>[]> {\n\tconst { models: availableModels, error } = await getAvailableModels();\n\n\tif (error) {\n\t\tconsole.warn(chalk.yellow(`Warning: Error loading models: ${error}`));\n\t\treturn [];\n\t}\n\n\tconst scopedModels: Model<Api>[] = [];\n\n\tfor (const pattern of patterns) {\n\t\t// Find all models matching this pattern (case-insensitive partial match)\n\t\tconst matches = availableModels.filter(\n\t\t\t(m) =>\n\t\t\t\tm.id.toLowerCase().includes(pattern.toLowerCase()) || m.name?.toLowerCase().includes(pattern.toLowerCase()),\n\t\t);\n\n\t\tif (matches.length === 0) {\n\t\t\tconsole.warn(chalk.yellow(`Warning: No models match pattern \"${pattern}\"`));\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Helper to check if a model ID looks like an alias (no date suffix)\n\t\t// Dates are typically in format: -20241022 or -20250929\n\t\tconst isAlias = (id: string): boolean => {\n\t\t\t// Check if ID ends with -latest\n\t\t\tif (id.endsWith(\"-latest\")) return true;\n\n\t\t\t// Check if ID ends with a date pattern (-YYYYMMDD)\n\t\t\tconst datePattern = /-\\d{8}$/;\n\t\t\treturn !datePattern.test(id);\n\t\t};\n\n\t\t// Separate into aliases and dated versions\n\t\tconst aliases = matches.filter((m) => isAlias(m.id));\n\t\tconst datedVersions = matches.filter((m) => !isAlias(m.id));\n\n\t\tlet bestMatch: Model<Api>;\n\n\t\tif (aliases.length > 0) {\n\t\t\t// Prefer alias - if multiple aliases, pick the one that sorts highest\n\t\t\taliases.sort((a, b) => b.id.localeCompare(a.id));\n\t\t\tbestMatch = aliases[0];\n\t\t} else {\n\t\t\t// No alias found, pick latest dated version\n\t\t\tdatedVersions.sort((a, b) => b.id.localeCompare(a.id));\n\t\t\tbestMatch = datedVersions[0];\n\t\t}\n\n\t\t// Avoid duplicates\n\t\tif (!scopedModels.find((m) => m.id === bestMatch.id && m.provider === bestMatch.provider)) {\n\t\t\tscopedModels.push(bestMatch);\n\t\t}\n\t}\n\n\treturn scopedModels;\n}\n\nasync function selectSession(sessionManager: SessionManager): Promise<string | null> {\n\treturn new Promise((resolve) => {\n\t\tconst ui = new TUI(new ProcessTerminal());\n\t\tlet resolved = false;\n\n\t\tconst selector = new SessionSelectorComponent(\n\t\t\tsessionManager,\n\t\t\t(path: string) => {\n\t\t\t\tif (!resolved) {\n\t\t\t\t\tresolved = true;\n\t\t\t\t\tui.stop();\n\t\t\t\t\tresolve(path);\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (!resolved) {\n\t\t\t\t\tresolved = true;\n\t\t\t\t\tui.stop();\n\t\t\t\t\tresolve(null);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tui.addChild(selector);\n\t\tui.setFocus(selector.getSessionList());\n\t\tui.start();\n\t});\n}\n\nasync function runInteractiveMode(\n\tagent: Agent,\n\tsessionManager: SessionManager,\n\tsettingsManager: SettingsManager,\n\tversion: string,\n\tchangelogMarkdown: string | null = null,\n\tmodelFallbackMessage: string | null = null,\n\tnewVersion: string | null = null,\n\tscopedModels: Model<Api>[] = [],\n): Promise<void> {\n\tconst renderer = new TuiRenderer(\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tversion,\n\t\tchangelogMarkdown,\n\t\tnewVersion,\n\t\tscopedModels,\n\t);\n\n\t// Initialize TUI\n\tawait renderer.init();\n\n\t// Set interrupt callback\n\trenderer.setInterruptCallback(() => {\n\t\tagent.abort();\n\t});\n\n\t// Render any existing messages (from --continue mode)\n\trenderer.renderInitialMessages(agent.state);\n\n\t// Show model fallback warning at the end of the chat if applicable\n\tif (modelFallbackMessage) {\n\t\trenderer.showWarning(modelFallbackMessage);\n\t}\n\n\t// Subscribe to agent events\n\tagent.subscribe(async (event) => {\n\t\t// Pass all events to the renderer\n\t\tawait renderer.handleEvent(event, agent.state);\n\t});\n\n\t// Interactive loop\n\twhile (true) {\n\t\tconst userInput = await renderer.getUserInput();\n\n\t\t// Process the message - agent.prompt will add user message and trigger state updates\n\t\ttry {\n\t\t\tawait agent.prompt(userInput);\n\t\t} catch (error: any) {\n\t\t\t// Display error in the TUI by adding an error message to the chat\n\t\t\trenderer.showError(error.message || \"Unknown error occurred\");\n\t\t}\n\t}\n}\n\nasync function runSingleShotMode(\n\tagent: Agent,\n\t_sessionManager: SessionManager,\n\tmessages: string[],\n\tmode: \"text\" | \"json\",\n): Promise<void> {\n\tif (mode === \"json\") {\n\t\t// Subscribe to all events and output as JSON\n\t\tagent.subscribe((event) => {\n\t\t\t// Output event as JSON (same format as session manager)\n\t\t\tconsole.log(JSON.stringify(event));\n\t\t});\n\t}\n\n\tfor (const message of messages) {\n\t\tawait agent.prompt(message);\n\t}\n\n\t// In text mode, only output the final assistant message\n\tif (mode === \"text\") {\n\t\tconst lastMessage = agent.state.messages[agent.state.messages.length - 1];\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tfor (const content of lastMessage.content) {\n\t\t\t\tif (content.type === \"text\") {\n\t\t\t\t\tconsole.log(content.text);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nasync function runRpcMode(agent: Agent, _sessionManager: SessionManager): Promise<void> {\n\t// Subscribe to all events and output as JSON\n\tagent.subscribe((event) => {\n\t\tconsole.log(JSON.stringify(event));\n\t});\n\n\t// Listen for JSON input on stdin\n\tconst readline = await import(\"readline\");\n\tconst rl = readline.createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout,\n\t\tterminal: false,\n\t});\n\n\trl.on(\"line\", async (line: string) => {\n\t\ttry {\n\t\t\tconst input = JSON.parse(line);\n\n\t\t\t// Handle different RPC commands\n\t\t\tif (input.type === \"prompt\" && input.message) {\n\t\t\t\tawait agent.prompt(input.message);\n\t\t\t} else if (input.type === \"abort\") {\n\t\t\t\tagent.abort();\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\t// Output error as JSON\n\t\t\tconsole.log(JSON.stringify({ type: \"error\", error: error.message }));\n\t\t}\n\t});\n\n\t// Keep process alive\n\treturn new Promise(() => {});\n}\n\nexport async function main(args: string[]) {\n\tconst parsed = parseArgs(args);\n\n\tif (parsed.help) {\n\t\tprintHelp();\n\t\treturn;\n\t}\n\n\t// Setup session manager\n\tconst sessionManager = new SessionManager(parsed.continue && !parsed.resume, parsed.session);\n\n\t// Disable session saving if --no-session flag is set\n\tif (parsed.noSession) {\n\t\tsessionManager.disable();\n\t}\n\n\t// Handle --resume flag: show session selector\n\tif (parsed.resume) {\n\t\tconst selectedSession = await selectSession(sessionManager);\n\t\tif (!selectedSession) {\n\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\treturn;\n\t\t}\n\t\t// Set the selected session as the active session\n\t\tsessionManager.setSessionFile(selectedSession);\n\t}\n\n\t// Settings manager\n\tconst settingsManager = new SettingsManager();\n\n\t// Determine initial model using priority system:\n\t// 1. CLI args (--provider and --model)\n\t// 2. Restored from session (if --continue or --resume)\n\t// 3. Saved default from settings.json\n\t// 4. First available model with valid API key\n\t// 5. null (allowed in interactive mode)\n\tlet initialModel: Model<Api> | null = null;\n\n\tif (parsed.provider && parsed.model) {\n\t\t// 1. CLI args take priority\n\t\tconst { model, error } = findModel(parsed.provider, parsed.model);\n\t\tif (error) {\n\t\t\tconsole.error(chalk.red(error));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tif (!model) {\n\t\t\tconsole.error(chalk.red(`Model ${parsed.provider}/${parsed.model} not found`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tinitialModel = model;\n\t} else if (parsed.continue || parsed.resume) {\n\t\t// 2. Restore from session (will be handled below after loading session)\n\t\t// Leave initialModel as null for now\n\t}\n\n\tif (!initialModel) {\n\t\t// 3. Try saved default from settings\n\t\tconst defaultProvider = settingsManager.getDefaultProvider();\n\t\tconst defaultModel = settingsManager.getDefaultModel();\n\t\tif (defaultProvider && defaultModel) {\n\t\t\tconst { model, error } = findModel(defaultProvider, defaultModel);\n\t\t\tif (error) {\n\t\t\t\tconsole.error(chalk.red(error));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tinitialModel = model;\n\t\t}\n\t}\n\n\tif (!initialModel) {\n\t\t// 4. Try first available model with valid API key\n\t\t// Prefer default model for each provider if available\n\t\tconst { models: availableModels, error } = await getAvailableModels();\n\n\t\tif (error) {\n\t\t\tconsole.error(chalk.red(error));\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tif (availableModels.length > 0) {\n\t\t\t// Try to find a default model from known providers\n\t\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\t\tconst defaultModelId = defaultModelPerProvider[provider];\n\t\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultModelId);\n\t\t\t\tif (match) {\n\t\t\t\t\tinitialModel = match;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If no default found, use first available\n\t\t\tif (!initialModel) {\n\t\t\t\tinitialModel = availableModels[0];\n\t\t\t}\n\t\t}\n\t}\n\n\t// Determine mode early to know if we should print messages and fail early\n\tconst isInteractive = parsed.messages.length === 0 && parsed.mode === undefined;\n\tconst mode = parsed.mode || \"text\";\n\tconst shouldPrintMessages = isInteractive || mode === \"text\";\n\n\t// Non-interactive mode: fail early if no model available\n\tif (!isInteractive && !initialModel) {\n\t\tconsole.error(chalk.red(\"No models available.\"));\n\t\tconsole.error(chalk.yellow(\"\\nSet an API key environment variable:\"));\n\t\tconsole.error(\" ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, etc.\");\n\t\tconsole.error(chalk.yellow(\"\\nOr create ~/.pi/agent/models.json\"));\n\t\tprocess.exit(1);\n\t}\n\n\t// Non-interactive mode: validate API key exists\n\tif (!isInteractive && initialModel) {\n\t\tconst apiKey = parsed.apiKey || (await getApiKeyForModel(initialModel));\n\t\tif (!apiKey) {\n\t\t\tconsole.error(chalk.red(`No API key found for ${initialModel.provider}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tconst systemPrompt = buildSystemPrompt(parsed.systemPrompt);\n\n\t// Load previous messages if continuing or resuming\n\t// This may update initialModel if restoring from session\n\tif (parsed.continue || parsed.resume) {\n\t\tconst messages = sessionManager.loadMessages();\n\t\tif (messages.length > 0 && shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Loaded ${messages.length} messages from previous session`));\n\t\t}\n\n\t\t// Load and restore model (overrides initialModel if found and has API key)\n\t\tconst savedModel = sessionManager.loadModel();\n\t\tif (savedModel) {\n\t\t\tconst { model: restoredModel, error } = findModel(savedModel.provider, savedModel.modelId);\n\n\t\t\tif (error) {\n\t\t\t\tconsole.error(chalk.red(error));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\t// Check if restored model exists and has a valid API key\n\t\t\tconst hasApiKey = restoredModel ? !!(await getApiKeyForModel(restoredModel)) : false;\n\n\t\t\tif (restoredModel && hasApiKey) {\n\t\t\t\tinitialModel = restoredModel;\n\t\t\t\tif (shouldPrintMessages) {\n\t\t\t\t\tconsole.log(chalk.dim(`Restored model: ${savedModel.provider}/${savedModel.modelId}`));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Model not found or no API key - fall back to default selection\n\t\t\t\tconst reason = !restoredModel ? \"model no longer exists\" : \"no API key available\";\n\n\t\t\t\tif (shouldPrintMessages) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Warning: Could not restore model ${savedModel.provider}/${savedModel.modelId} (${reason}).`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Ensure we have a valid model - use the same fallback logic\n\t\t\t\tif (!initialModel) {\n\t\t\t\t\tconst { models: availableModels, error: availableError } = await getAvailableModels();\n\t\t\t\t\tif (availableError) {\n\t\t\t\t\t\tconsole.error(chalk.red(availableError));\n\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t}\n\t\t\t\t\tif (availableModels.length > 0) {\n\t\t\t\t\t\t// Try to find a default model from known providers\n\t\t\t\t\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\t\t\t\t\tconst defaultModelId = defaultModelPerProvider[provider];\n\t\t\t\t\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultModelId);\n\t\t\t\t\t\t\tif (match) {\n\t\t\t\t\t\t\t\tinitialModel = match;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// If no default found, use first available\n\t\t\t\t\t\tif (!initialModel) {\n\t\t\t\t\t\t\tinitialModel = availableModels[0];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (initialModel && shouldPrintMessages) {\n\t\t\t\t\t\t\tconsole.log(chalk.dim(`Falling back to: ${initialModel.provider}/${initialModel.id}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No models available at all\n\t\t\t\t\t\tif (shouldPrintMessages) {\n\t\t\t\t\t\t\tconsole.error(chalk.red(\"\\nNo models available.\"));\n\t\t\t\t\t\t\tconsole.error(chalk.yellow(\"Set an API key environment variable:\"));\n\t\t\t\t\t\t\tconsole.error(\" ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, etc.\");\n\t\t\t\t\t\t\tconsole.error(chalk.yellow(\"\\nOr create ~/.pi/agent/models.json\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t}\n\t\t\t\t} else if (shouldPrintMessages) {\n\t\t\t\t\tconsole.log(chalk.dim(`Falling back to: ${initialModel.provider}/${initialModel.id}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create agent (initialModel can be null in interactive mode)\n\tconst agent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt,\n\t\t\tmodel: initialModel as any, // Can be null\n\t\t\tthinkingLevel: \"off\",\n\t\t\ttools: codingTools,\n\t\t},\n\t\ttransport: new ProviderTransport({\n\t\t\t// Dynamic API key lookup based on current model's provider\n\t\t\tgetApiKey: async () => {\n\t\t\t\tconst currentModel = agent.state.model;\n\t\t\t\tif (!currentModel) {\n\t\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t\t}\n\n\t\t\t\t// Try CLI override first\n\t\t\t\tif (parsed.apiKey) {\n\t\t\t\t\treturn parsed.apiKey;\n\t\t\t\t}\n\n\t\t\t\t// Use model-specific key lookup\n\t\t\t\tconst key = await getApiKeyForModel(currentModel);\n\t\t\t\tif (!key) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`No API key found for provider \"${currentModel.provider}\". Please set the appropriate environment variable or update ~/.pi/agent/models.json`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn key;\n\t\t\t},\n\t\t}),\n\t});\n\n\t// Track if we had to fall back from saved model (to show in chat later)\n\tlet modelFallbackMessage: string | null = null;\n\n\t// Load previous messages if continuing or resuming\n\tif (parsed.continue || parsed.resume) {\n\t\tconst messages = sessionManager.loadMessages();\n\t\tif (messages.length > 0) {\n\t\t\tagent.replaceMessages(messages);\n\t\t}\n\n\t\t// Load and restore thinking level\n\t\tconst thinkingLevel = sessionManager.loadThinkingLevel() as ThinkingLevel;\n\t\tif (thinkingLevel) {\n\t\t\tagent.setThinkingLevel(thinkingLevel);\n\t\t\tif (shouldPrintMessages) {\n\t\t\t\tconsole.log(chalk.dim(`Restored thinking level: ${thinkingLevel}`));\n\t\t\t}\n\t\t}\n\n\t\t// Check if we had to fall back from saved model\n\t\tconst savedModel = sessionManager.loadModel();\n\t\tif (savedModel && initialModel) {\n\t\t\tconst savedMatches = initialModel.provider === savedModel.provider && initialModel.id === savedModel.modelId;\n\t\t\tif (!savedMatches) {\n\t\t\t\tconst { model: restoredModel, error } = findModel(savedModel.provider, savedModel.modelId);\n\t\t\t\tif (error) {\n\t\t\t\t\t// Config error - already shown above, just use generic message\n\t\t\t\t\tmodelFallbackMessage = `Could not restore model ${savedModel.provider}/${savedModel.modelId}. Using ${initialModel.provider}/${initialModel.id}.`;\n\t\t\t\t} else {\n\t\t\t\t\tconst reason = !restoredModel ? \"model no longer exists\" : \"no API key available\";\n\t\t\t\t\tmodelFallbackMessage = `Could not restore model ${savedModel.provider}/${savedModel.modelId} (${reason}). Using ${initialModel.provider}/${initialModel.id}.`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Note: Session will be started lazily after first user+assistant message exchange\n\t// (unless continuing/resuming, in which case it's already initialized)\n\n\t// Log loaded context files (they're already in the system prompt)\n\tif (shouldPrintMessages && !parsed.continue && !parsed.resume) {\n\t\tconst contextFiles = loadProjectContextFiles();\n\t\tif (contextFiles.length > 0) {\n\t\t\tconsole.log(chalk.dim(\"Loaded project context from:\"));\n\t\t\tfor (const { path: filePath } of contextFiles) {\n\t\t\t\tconsole.log(chalk.dim(` - ${filePath}`));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Subscribe to agent events to save messages\n\tagent.subscribe((event) => {\n\t\t// Save messages on completion\n\t\tif (event.type === \"message_end\") {\n\t\t\tsessionManager.saveMessage(event.message);\n\n\t\t\t// Check if we should initialize session now (after first user+assistant exchange)\n\t\t\tif (sessionManager.shouldInitializeSession(agent.state.messages)) {\n\t\t\t\tsessionManager.startSession(agent.state);\n\t\t\t}\n\t\t}\n\t});\n\n\t// Route to appropriate mode\n\tif (mode === \"rpc\") {\n\t\t// RPC mode - headless operation\n\t\tawait runRpcMode(agent, sessionManager);\n\t} else if (isInteractive) {\n\t\t// Check for new version (don't block startup if it takes too long)\n\t\tlet newVersion: string | null = null;\n\t\ttry {\n\t\t\tnewVersion = await Promise.race([\n\t\t\t\tcheckForNewVersion(VERSION),\n\t\t\t\tnew Promise<null>((resolve) => setTimeout(() => resolve(null), 1000)), // 1 second timeout\n\t\t\t]);\n\t\t} catch (e) {\n\t\t\t// Ignore errors\n\t\t}\n\n\t\t// Check if we should show changelog (only in interactive mode, only for new sessions)\n\t\tlet changelogMarkdown: string | null = null;\n\t\tif (!parsed.continue && !parsed.resume) {\n\t\t\tconst lastVersion = settingsManager.getLastChangelogVersion();\n\n\t\t\t// Check if we need to show changelog\n\t\t\tif (!lastVersion) {\n\t\t\t\t// First run - show all entries\n\t\t\t\tconst changelogPath = getChangelogPath();\n\t\t\t\tconst entries = parseChangelog(changelogPath);\n\t\t\t\tif (entries.length > 0) {\n\t\t\t\t\tchangelogMarkdown = entries.map((e) => e.content).join(\"\\n\\n\");\n\t\t\t\t\tsettingsManager.setLastChangelogVersion(VERSION);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Parse current and last versions\n\t\t\t\tconst currentParts = VERSION.split(\".\").map(Number);\n\t\t\t\tconst current = { major: currentParts[0] || 0, minor: currentParts[1] || 0, patch: currentParts[2] || 0 };\n\t\t\t\tconst changelogPath = getChangelogPath();\n\t\t\t\tconst entries = parseChangelog(changelogPath);\n\t\t\t\tconst newEntries = getNewEntries(entries, lastVersion);\n\n\t\t\t\tif (newEntries.length > 0) {\n\t\t\t\t\tchangelogMarkdown = newEntries.map((e) => e.content).join(\"\\n\\n\");\n\t\t\t\t\tsettingsManager.setLastChangelogVersion(VERSION);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Resolve model scope if provided\n\t\tlet scopedModels: Model<Api>[] = [];\n\t\tif (parsed.models && parsed.models.length > 0) {\n\t\t\tscopedModels = await resolveModelScope(parsed.models);\n\n\t\t\tif (scopedModels.length > 0) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.dim(`Model scope: ${scopedModels.map((m) => m.id).join(\", \")} ${chalk.gray(\"(Ctrl+P to cycle)\")}`),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// No messages and not RPC - use TUI\n\t\tawait runInteractiveMode(\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tVERSION,\n\t\t\tchangelogMarkdown,\n\t\t\tmodelFallbackMessage,\n\t\t\tnewVersion,\n\t\t\tscopedModels,\n\t\t);\n\t} else {\n\t\t// CLI mode with messages\n\t\tawait runSingleShotMode(agent, sessionManager, parsed.messages, mode);\n\t}\n}\n"]}
|
package/dist/main.js
CHANGED
|
@@ -76,6 +76,9 @@ function parseArgs(args) {
|
|
|
76
76
|
else if (arg === "--session" && i + 1 < args.length) {
|
|
77
77
|
result.session = args[++i];
|
|
78
78
|
}
|
|
79
|
+
else if (arg === "--models" && i + 1 < args.length) {
|
|
80
|
+
result.models = args[++i].split(",").map((s) => s.trim());
|
|
81
|
+
}
|
|
79
82
|
else if (!arg.startsWith("-")) {
|
|
80
83
|
result.messages.push(arg);
|
|
81
84
|
}
|
|
@@ -83,10 +86,10 @@ function parseArgs(args) {
|
|
|
83
86
|
return result;
|
|
84
87
|
}
|
|
85
88
|
function printHelp() {
|
|
86
|
-
console.log(`${chalk.bold("
|
|
89
|
+
console.log(`${chalk.bold("pi")} - AI coding assistant with read, bash, edit, write tools
|
|
87
90
|
|
|
88
91
|
${chalk.bold("Usage:")}
|
|
89
|
-
|
|
92
|
+
pi [options] [messages...]
|
|
90
93
|
|
|
91
94
|
${chalk.bold("Options:")}
|
|
92
95
|
--provider <name> Provider name (default: google)
|
|
@@ -98,23 +101,27 @@ ${chalk.bold("Options:")}
|
|
|
98
101
|
--resume, -r Select a session to resume
|
|
99
102
|
--session <path> Use specific session file
|
|
100
103
|
--no-session Don't save session (ephemeral)
|
|
104
|
+
--models <patterns> Comma-separated model patterns for quick cycling with Ctrl+P
|
|
101
105
|
--help, -h Show this help
|
|
102
106
|
|
|
103
107
|
${chalk.bold("Examples:")}
|
|
104
108
|
# Interactive mode (no messages = interactive TUI)
|
|
105
|
-
|
|
109
|
+
pi
|
|
106
110
|
|
|
107
111
|
# Single message
|
|
108
|
-
|
|
112
|
+
pi "List all .ts files in src/"
|
|
109
113
|
|
|
110
114
|
# Multiple messages
|
|
111
|
-
|
|
115
|
+
pi "Read package.json" "What dependencies do we have?"
|
|
112
116
|
|
|
113
117
|
# Continue previous session
|
|
114
|
-
|
|
118
|
+
pi --continue "What did we discuss?"
|
|
115
119
|
|
|
116
120
|
# Use different model
|
|
117
|
-
|
|
121
|
+
pi --provider openai --model gpt-4o-mini "Help me refactor this code"
|
|
122
|
+
|
|
123
|
+
# Limit model cycling to specific models
|
|
124
|
+
pi --models claude-sonnet,claude-haiku,gpt-4o
|
|
118
125
|
|
|
119
126
|
${chalk.bold("Environment Variables:")}
|
|
120
127
|
GEMINI_API_KEY - Google Gemini API key
|
|
@@ -292,6 +299,57 @@ async function checkForNewVersion(currentVersion) {
|
|
|
292
299
|
return null;
|
|
293
300
|
}
|
|
294
301
|
}
|
|
302
|
+
/**
|
|
303
|
+
* Resolve model patterns to actual Model objects
|
|
304
|
+
* For each pattern, finds all matching models and picks the best version:
|
|
305
|
+
* 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)
|
|
306
|
+
* 2. If no alias, pick the latest dated version
|
|
307
|
+
*/
|
|
308
|
+
async function resolveModelScope(patterns) {
|
|
309
|
+
const { models: availableModels, error } = await getAvailableModels();
|
|
310
|
+
if (error) {
|
|
311
|
+
console.warn(chalk.yellow(`Warning: Error loading models: ${error}`));
|
|
312
|
+
return [];
|
|
313
|
+
}
|
|
314
|
+
const scopedModels = [];
|
|
315
|
+
for (const pattern of patterns) {
|
|
316
|
+
// Find all models matching this pattern (case-insensitive partial match)
|
|
317
|
+
const matches = availableModels.filter((m) => m.id.toLowerCase().includes(pattern.toLowerCase()) || m.name?.toLowerCase().includes(pattern.toLowerCase()));
|
|
318
|
+
if (matches.length === 0) {
|
|
319
|
+
console.warn(chalk.yellow(`Warning: No models match pattern "${pattern}"`));
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
// Helper to check if a model ID looks like an alias (no date suffix)
|
|
323
|
+
// Dates are typically in format: -20241022 or -20250929
|
|
324
|
+
const isAlias = (id) => {
|
|
325
|
+
// Check if ID ends with -latest
|
|
326
|
+
if (id.endsWith("-latest"))
|
|
327
|
+
return true;
|
|
328
|
+
// Check if ID ends with a date pattern (-YYYYMMDD)
|
|
329
|
+
const datePattern = /-\d{8}$/;
|
|
330
|
+
return !datePattern.test(id);
|
|
331
|
+
};
|
|
332
|
+
// Separate into aliases and dated versions
|
|
333
|
+
const aliases = matches.filter((m) => isAlias(m.id));
|
|
334
|
+
const datedVersions = matches.filter((m) => !isAlias(m.id));
|
|
335
|
+
let bestMatch;
|
|
336
|
+
if (aliases.length > 0) {
|
|
337
|
+
// Prefer alias - if multiple aliases, pick the one that sorts highest
|
|
338
|
+
aliases.sort((a, b) => b.id.localeCompare(a.id));
|
|
339
|
+
bestMatch = aliases[0];
|
|
340
|
+
}
|
|
341
|
+
else {
|
|
342
|
+
// No alias found, pick latest dated version
|
|
343
|
+
datedVersions.sort((a, b) => b.id.localeCompare(a.id));
|
|
344
|
+
bestMatch = datedVersions[0];
|
|
345
|
+
}
|
|
346
|
+
// Avoid duplicates
|
|
347
|
+
if (!scopedModels.find((m) => m.id === bestMatch.id && m.provider === bestMatch.provider)) {
|
|
348
|
+
scopedModels.push(bestMatch);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return scopedModels;
|
|
352
|
+
}
|
|
295
353
|
async function selectSession(sessionManager) {
|
|
296
354
|
return new Promise((resolve) => {
|
|
297
355
|
const ui = new TUI(new ProcessTerminal());
|
|
@@ -314,8 +372,8 @@ async function selectSession(sessionManager) {
|
|
|
314
372
|
ui.start();
|
|
315
373
|
});
|
|
316
374
|
}
|
|
317
|
-
async function runInteractiveMode(agent, sessionManager, settingsManager, version, changelogMarkdown = null, modelFallbackMessage = null, newVersion = null) {
|
|
318
|
-
const renderer = new TuiRenderer(agent, sessionManager, settingsManager, version, changelogMarkdown, newVersion);
|
|
375
|
+
async function runInteractiveMode(agent, sessionManager, settingsManager, version, changelogMarkdown = null, modelFallbackMessage = null, newVersion = null, scopedModels = []) {
|
|
376
|
+
const renderer = new TuiRenderer(agent, sessionManager, settingsManager, version, changelogMarkdown, newVersion, scopedModels);
|
|
319
377
|
// Initialize TUI
|
|
320
378
|
await renderer.init();
|
|
321
379
|
// Set interrupt callback
|
|
@@ -705,8 +763,16 @@ export async function main(args) {
|
|
|
705
763
|
}
|
|
706
764
|
}
|
|
707
765
|
}
|
|
766
|
+
// Resolve model scope if provided
|
|
767
|
+
let scopedModels = [];
|
|
768
|
+
if (parsed.models && parsed.models.length > 0) {
|
|
769
|
+
scopedModels = await resolveModelScope(parsed.models);
|
|
770
|
+
if (scopedModels.length > 0) {
|
|
771
|
+
console.log(chalk.dim(`Model scope: ${scopedModels.map((m) => m.id).join(", ")} ${chalk.gray("(Ctrl+P to cycle)")}`));
|
|
772
|
+
}
|
|
773
|
+
}
|
|
708
774
|
// No messages and not RPC - use TUI
|
|
709
|
-
await runInteractiveMode(agent, sessionManager, settingsManager, VERSION, changelogMarkdown, modelFallbackMessage, newVersion);
|
|
775
|
+
await runInteractiveMode(agent, sessionManager, settingsManager, VERSION, changelogMarkdown, modelFallbackMessage, newVersion, scopedModels);
|
|
710
776
|
}
|
|
711
777
|
else {
|
|
712
778
|
// CLI mode with messages
|