feat: integrate Pi backend and Pi Web

This commit is contained in:
luckyyzh
2026-07-30 19:37:53 +08:00
commit 7392ab9dd7
1390 changed files with 337197 additions and 0 deletions
+400
View File
@@ -0,0 +1,400 @@
/**
* CLI argument parsing and help display
*/
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import chalk from "chalk";
import { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR, ENV_SESSION_DIR } from "../config.ts";
import type { ExtensionFlag } from "../core/extensions/types.ts";
export type Mode = "text" | "json" | "rpc";
export interface Args {
provider?: string;
model?: string;
apiKey?: string;
systemPrompt?: string;
appendSystemPrompt?: string[];
thinking?: ThinkingLevel;
continue?: boolean;
resume?: boolean;
help?: boolean;
version?: boolean;
mode?: Mode;
name?: string;
noSession?: boolean;
session?: string;
sessionId?: string;
fork?: string;
sessionDir?: string;
models?: string[];
tools?: string[];
excludeTools?: string[];
noTools?: boolean;
noBuiltinTools?: boolean;
extensions?: string[];
noExtensions?: boolean;
print?: boolean;
export?: string;
noSkills?: boolean;
skills?: string[];
promptTemplates?: string[];
noPromptTemplates?: boolean;
themes?: string[];
noThemes?: boolean;
noContextFiles?: boolean;
listModels?: string | true;
offline?: boolean;
verbose?: boolean;
projectTrustOverride?: boolean;
messages: string[];
fileArgs: string[];
/** Unknown flags (potentially extension flags) - map of flag name to value */
unknownFlags: Map<string, boolean | string>;
diagnostics: Array<{ type: "warning" | "error"; message: string }>;
}
const VALID_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
export function isValidThinkingLevel(level: string): level is ThinkingLevel {
return VALID_THINKING_LEVELS.includes(level as ThinkingLevel);
}
export function parseArgs(args: string[]): Args {
const result: Args = {
messages: [],
fileArgs: [],
unknownFlags: new Map(),
diagnostics: [],
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === "--help" || arg === "-h") {
result.help = true;
} else if (arg === "--version" || arg === "-v") {
result.version = true;
} else if (arg === "--mode" && i + 1 < args.length) {
const mode = args[++i];
if (mode === "text" || mode === "json" || mode === "rpc") {
result.mode = mode;
}
} else if (arg === "--continue" || arg === "-c") {
result.continue = true;
} else if (arg === "--resume" || arg === "-r") {
result.resume = true;
} else if (arg === "--provider" && i + 1 < args.length) {
result.provider = args[++i];
} else if (arg === "--model" && i + 1 < args.length) {
result.model = args[++i];
} else if (arg === "--api-key" && i + 1 < args.length) {
result.apiKey = args[++i];
} else if (arg === "--system-prompt" && i + 1 < args.length) {
result.systemPrompt = args[++i];
} else if (arg === "--append-system-prompt" && i + 1 < args.length) {
result.appendSystemPrompt = result.appendSystemPrompt ?? [];
result.appendSystemPrompt.push(args[++i]);
} else if (arg === "--name" || arg === "-n") {
if (i + 1 < args.length) {
result.name = args[++i];
} else {
result.diagnostics.push({ type: "error", message: "--name requires a value" });
}
} else if (arg === "--no-session") {
result.noSession = true;
} else if (arg === "--session" && i + 1 < args.length) {
result.session = args[++i];
} else if (arg === "--session-id" && i + 1 < args.length) {
result.sessionId = args[++i];
} else if (arg === "--fork" && i + 1 < args.length) {
result.fork = args[++i];
} else if (arg === "--session-dir" && i + 1 < args.length) {
result.sessionDir = args[++i];
} else if (arg === "--models" && i + 1 < args.length) {
result.models = args[++i].split(",").map((s) => s.trim());
} else if (arg === "--no-tools" || arg === "-nt") {
result.noTools = true;
} else if (arg === "--no-builtin-tools" || arg === "-nbt") {
result.noBuiltinTools = true;
} else if ((arg === "--tools" || arg === "-t") && i + 1 < args.length) {
result.tools = args[++i]
.split(",")
.map((s) => s.trim())
.filter((name) => name.length > 0);
} else if ((arg === "--exclude-tools" || arg === "-xt") && i + 1 < args.length) {
result.excludeTools = args[++i]
.split(",")
.map((s) => s.trim())
.filter((name) => name.length > 0);
} else if (arg === "--thinking" && i + 1 < args.length) {
const level = args[++i];
if (isValidThinkingLevel(level)) {
result.thinking = level;
} else {
result.diagnostics.push({
type: "warning",
message: `Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`,
});
}
} else if (arg === "--print" || arg === "-p") {
result.print = true;
const next = args[i + 1];
if (next !== undefined && !next.startsWith("@") && (!next.startsWith("-") || next.startsWith("---"))) {
result.messages.push(next);
i++;
}
} else if (arg === "--export" && i + 1 < args.length) {
result.export = args[++i];
} else if ((arg === "--extension" || arg === "-e") && i + 1 < args.length) {
result.extensions = result.extensions ?? [];
result.extensions.push(args[++i]);
} else if (arg === "--no-extensions" || arg === "-ne") {
result.noExtensions = true;
} else if (arg === "--skill" && i + 1 < args.length) {
result.skills = result.skills ?? [];
result.skills.push(args[++i]);
} else if (arg === "--prompt-template" && i + 1 < args.length) {
result.promptTemplates = result.promptTemplates ?? [];
result.promptTemplates.push(args[++i]);
} else if (arg === "--theme" && i + 1 < args.length) {
result.themes = result.themes ?? [];
result.themes.push(args[++i]);
} else if (arg === "--no-skills" || arg === "-ns") {
result.noSkills = true;
} else if (arg === "--no-prompt-templates" || arg === "-np") {
result.noPromptTemplates = true;
} else if (arg === "--no-themes") {
result.noThemes = true;
} else if (arg === "--no-context-files" || arg === "-nc") {
result.noContextFiles = true;
} else if (arg === "--list-models") {
// Check if next arg is a search pattern (not a flag or file arg)
if (i + 1 < args.length && !args[i + 1].startsWith("-") && !args[i + 1].startsWith("@")) {
result.listModels = args[++i];
} else {
result.listModels = true;
}
} else if (arg === "--verbose") {
result.verbose = true;
} else if (arg === "--approve" || arg === "-a") {
result.projectTrustOverride = true;
} else if (arg === "--no-approve" || arg === "-na") {
result.projectTrustOverride = false;
} else if (arg === "--offline") {
result.offline = true;
} else if (arg.startsWith("@")) {
result.fileArgs.push(arg.slice(1)); // Remove @ prefix
} else if (arg.startsWith("--")) {
const eqIndex = arg.indexOf("=");
if (eqIndex !== -1) {
result.unknownFlags.set(arg.slice(2, eqIndex), arg.slice(eqIndex + 1));
} else {
const flagName = arg.slice(2);
const next = args[i + 1];
if (next !== undefined && !next.startsWith("-") && !next.startsWith("@")) {
result.unknownFlags.set(flagName, next);
i++;
} else {
result.unknownFlags.set(flagName, true);
}
}
} else if (arg.startsWith("-") && !arg.startsWith("--")) {
result.diagnostics.push({ type: "error", message: `Unknown option: ${arg}` });
} else if (!arg.startsWith("-")) {
result.messages.push(arg);
}
}
return result;
}
export function printHelp(extensionFlags?: ExtensionFlag[]): void {
const extensionFlagsText =
extensionFlags && extensionFlags.length > 0
? `\n${chalk.bold("Extension CLI Flags:")}\n${extensionFlags
.map((flag) => {
const value = flag.type === "string" ? " <value>" : "";
const description = flag.description ?? `Registered by ${flag.extensionPath}`;
return ` --${flag.name}${value}`.padEnd(30) + description;
})
.join("\n")}\n`
: "";
console.log(`${chalk.bold(APP_NAME)} - AI coding assistant with read, bash, edit, write tools
${chalk.bold("Usage:")}
${APP_NAME} [options] [@files...] [messages...]
${chalk.bold("Commands:")}
${APP_NAME} install <source> [-l] Install extension source and add to settings
${APP_NAME} remove <source> [-l] Remove extension source from settings
${APP_NAME} uninstall <source> [-l] Alias for remove
${APP_NAME} update [source|self|pi] Update pi, extensions, or model catalogs
${APP_NAME} list List installed extensions from settings
${APP_NAME} config [-l] Open TUI to enable/disable package resources (Tab switches scope)
${APP_NAME} auth <command> Print credentials for external clients
${APP_NAME} <command> --help Show help for install/remove/uninstall/update/list/config/auth
${chalk.bold("Options:")}
--provider <name> Provider name (default: google)
--model <pattern> Model pattern or ID (supports "provider/id" and optional ":<thinking>")
--api-key <key> API key (defaults to env vars)
--system-prompt <text> System prompt (default: coding assistant prompt)
--append-system-prompt <text> Append text or file contents to the system prompt (can be used multiple times)
--mode <mode> Output mode: text (default), json, or rpc
--print, -p Non-interactive mode: process prompt and exit
--continue, -c Continue previous session
--resume, -r Select a session to resume
--session <path|id> Use specific session file or partial UUID
--session-id <id> Use exact project session ID, creating it if missing
--fork <path|id> Fork specific session file or partial UUID into a new session
--session-dir <dir> Directory for session storage and lookup
--no-session Don't save session (ephemeral)
--name, -n <name> Set session display name
--models <patterns> Comma-separated model patterns for Ctrl+P cycling
Supports globs (anthropic/*, *sonnet*) and fuzzy matching
--no-tools, -nt Disable all tools by default (built-in and extension)
--no-builtin-tools, -nbt Disable built-in tools by default but keep extension/custom tools enabled
--tools, -t <tools> Comma-separated allowlist of tool names to enable
Applies to built-in, extension, and custom tools
--exclude-tools, -xt <tools> Comma-separated denylist of tool names to disable
Applies to built-in, extension, and custom tools
--thinking <level> Set thinking level: off, minimal, low, medium, high, xhigh, max
--extension, -e <path> Load an extension file (can be used multiple times)
--no-extensions, -ne Disable extension discovery (explicit -e paths still work)
--skill <path> Load a skill file or directory (can be used multiple times)
--no-skills, -ns Disable skills discovery and loading
--prompt-template <path> Load a prompt template file or directory (can be used multiple times)
--no-prompt-templates, -np Disable prompt template discovery and loading
--theme <path> Load a theme file or directory (can be used multiple times)
--no-themes Disable theme discovery and loading
--no-context-files, -nc Disable AGENTS.md and CLAUDE.md discovery and loading
--export <file> Export session file to HTML and exit
--list-models [search] List available models (with optional fuzzy search)
--verbose Force verbose startup (overrides quietStartup setting)
--approve, -a Trust project-local files for this run
--no-approve, -na Ignore project-local files for this run
--offline Disable startup network operations (same as PI_OFFLINE=1)
--help, -h Show this help
--version, -v Show version number
Extensions can register additional flags (e.g., --plan from plan-mode extension).${extensionFlagsText}
${chalk.bold("Examples:")}
# Print a provider API key for an external client
${APP_NAME} auth print-api-key --provider openai --model gpt-5.5
# Print an OAuth bearer token for an external client (refreshes if expired)
${APP_NAME} auth print-bearer-token --provider openai-codex --model gpt-5.5
# Interactive mode
${APP_NAME}
# Interactive mode with initial prompt
${APP_NAME} "List all .ts files in src/"
# Include files in initial message
${APP_NAME} @prompt.md @image.png "What color is the sky?"
# Non-interactive mode (process and exit)
${APP_NAME} -p "List all .ts files in src/"
# Multiple messages (interactive)
${APP_NAME} "Read package.json" "What dependencies do we have?"
# Continue previous session
${APP_NAME} --continue "What did we discuss?"
# Start a named session
${APP_NAME} --name "Refactor auth module"
# Use different model
${APP_NAME} --provider openai --model gpt-4o-mini "Help me refactor this code"
# Use model with provider prefix (no --provider needed)
${APP_NAME} --model openai/gpt-4o "Help me refactor this code"
# Use model with thinking level shorthand
${APP_NAME} --model sonnet:high "Solve this complex problem"
# Limit model cycling to specific models
${APP_NAME} --models claude-sonnet,claude-haiku,gpt-4o
# Limit to a specific provider with glob pattern
${APP_NAME} --models "github-copilot/*"
# Cycle models with fixed thinking levels
${APP_NAME} --models sonnet:high,haiku:low
# Start with a specific thinking level
${APP_NAME} --thinking high "Solve this complex problem"
# Read-only mode (no file modifications possible)
${APP_NAME} --tools read,grep,find,ls -p "Review the code in src/"
# Disable one tool while keeping the rest available
${APP_NAME} --exclude-tools ask_question
# Export a session file to HTML
${APP_NAME} --export ~/${CONFIG_DIR_NAME}/agent/sessions/--path--/session.jsonl
${APP_NAME} --export session.jsonl output.html
${chalk.bold("Environment Variables:")}
ANTHROPIC_AUTH_TOKEN - Anthropic bearer auth token
ANTHROPIC_API_KEY - Anthropic Claude API key
ANTHROPIC_OAUTH_TOKEN - Anthropic OAuth token (alternative to API key)
ANT_LING_API_KEY - Ant Ling API key
OPENAI_API_KEY - OpenAI GPT API key
AZURE_OPENAI_API_KEY - Azure OpenAI API key
AZURE_OPENAI_BASE_URL - Azure OpenAI/Cognitive Services base URL (e.g. https://{resource}.openai.azure.com)
AZURE_OPENAI_RESOURCE_NAME - Azure OpenAI resource name (alternative to base URL)
AZURE_OPENAI_API_VERSION - Azure OpenAI API version (default: v1)
AZURE_OPENAI_DEPLOYMENT_NAME_MAP - Azure OpenAI model=deployment map (comma-separated)
DEEPSEEK_API_KEY - DeepSeek API key
NVIDIA_API_KEY - NVIDIA NIM API key
GEMINI_API_KEY - Google Gemini API key
GROQ_API_KEY - Groq API key
CEREBRAS_API_KEY - Cerebras API key
XAI_API_KEY - xAI Grok API key
FIREWORKS_API_KEY - Fireworks API key
TOGETHER_API_KEY - Together AI API key
OPENROUTER_API_KEY - OpenRouter API key
AI_GATEWAY_API_KEY - Vercel AI Gateway API key
ZAI_API_KEY - ZAI Coding Plan API key (Global)
ZAI_CODING_CN_API_KEY - ZAI Coding Plan API key (China)
MISTRAL_API_KEY - Mistral API key
MINIMAX_API_KEY - MiniMax API key
MOONSHOT_API_KEY - Moonshot AI API key
OPENCODE_API_KEY - OpenCode Zen/OpenCode Go API key
KIMI_API_KEY - Kimi For Coding API key
CLOUDFLARE_API_KEY - Cloudflare API token (Workers AI and AI Gateway)
CLOUDFLARE_ACCOUNT_ID - Cloudflare account id (required for both)
CLOUDFLARE_GATEWAY_ID - Cloudflare AI Gateway slug (required for AI Gateway)
QWEN_TOKEN_PLAN_API_KEY - Qwen Token Plan API key (international region)
QWEN_TOKEN_PLAN_CN_API_KEY - Qwen Token Plan API key (China region)
XIAOMI_API_KEY - Xiaomi MiMo API key (api.xiaomimimo.com billing)
XIAOMI_TOKEN_PLAN_CN_API_KEY - Xiaomi MiMo Token Plan API key (China region)
XIAOMI_TOKEN_PLAN_AMS_API_KEY - Xiaomi MiMo Token Plan API key (Amsterdam region)
XIAOMI_TOKEN_PLAN_SGP_API_KEY - Xiaomi MiMo Token Plan API key (Singapore region)
AWS_PROFILE - AWS profile for Amazon Bedrock
AWS_ACCESS_KEY_ID - AWS access key for Amazon Bedrock
AWS_SECRET_ACCESS_KEY - AWS secret key for Amazon Bedrock
AWS_BEARER_TOKEN_BEDROCK - Bedrock API key (bearer token)
AWS_REGION - AWS region for Amazon Bedrock (e.g., us-east-1)
${ENV_AGENT_DIR.padEnd(32)} - Config directory (default: ~/${CONFIG_DIR_NAME}/agent)
${ENV_SESSION_DIR.padEnd(32)} - Session storage directory (overridden by --session-dir)
PI_PACKAGE_DIR - Override package directory (for Nix/Guix store paths)
PI_OFFLINE - Disable startup network operations when set to 1/true/yes
PI_TELEMETRY - Override install telemetry when set to 1/true/yes or 0/false/no
PI_SHARE_VIEWER_URL - Base URL for /share command (default: https://pi.dev/session/)
${chalk.bold("Built-in Tool Names:")}
read - Read file contents
bash - Execute bash commands
edit - Edit files with find/replace
write - Write files (creates/overwrites)
grep - Search file contents (read-only, off by default)
find - Find files by glob pattern (read-only, off by default)
ls - List directory contents (read-only, off by default)
`);
}
@@ -0,0 +1,56 @@
/**
* TUI config selector for `pi config` command
*/
import { ProcessTerminal, TUI } from "@earendil-works/pi-tui";
import type { SettingsManager } from "../core/settings-manager.ts";
import { ConfigSelectorComponent, type ScopedResolvedPaths } from "../modes/interactive/components/config-selector.ts";
import { initTheme, stopThemeWatcher } from "../modes/interactive/theme/theme.ts";
export interface ConfigSelectorOptions {
resolvedPaths: ScopedResolvedPaths;
settingsManager: SettingsManager;
cwd: string;
agentDir: string;
writeScope: "global" | "project";
projectModeAvailable: boolean;
}
/** Show TUI config selector and return when closed */
export async function selectConfig(options: ConfigSelectorOptions): Promise<void> {
// Initialize theme before showing TUI
initTheme(options.settingsManager.getTheme(), true);
return new Promise((resolve) => {
const ui = new TUI(new ProcessTerminal(), undefined, options.agentDir);
let resolved = false;
const selector = new ConfigSelectorComponent(
options.resolvedPaths,
options.settingsManager,
options.cwd,
options.agentDir,
() => {
if (!resolved) {
resolved = true;
ui.stop();
stopThemeWatcher();
resolve();
}
},
() => {
ui.stop();
stopThemeWatcher();
process.exit(0);
},
() => ui.requestRender(),
ui.terminal.rows,
options.writeScope,
options.projectModeAvailable,
);
ui.addChild(selector);
ui.setFocus(selector.getResourceList());
ui.start();
});
}
@@ -0,0 +1,152 @@
import type { Api, CredentialInfo, Model } from "@earendil-works/pi-ai";
import { resolveCliModel } from "../core/model-resolver.ts";
import type { ModelRuntime } from "../core/model-runtime.ts";
import type { Args } from "./args.ts";
export type CredentialPrintKind = "api_key" | "bearer_token";
const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;
export interface CredentialPrintCommand {
kind: CredentialPrintKind;
args: string[];
minExpiryMs?: number;
}
export class CredentialPrintError extends Error {}
export function isCredentialPrintHelp(args: string[]): boolean {
return (
args[0] === "auth" && (args[1] === undefined || args[1] === "help" || args[1] === "--help" || args[1] === "-h")
);
}
export function printCredentialPrintHelp(): void {
console.log(`Usage:
pi auth print-api-key --model <model> [--provider <provider>]
pi auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]
Prints the configured credential alone on stdout. Provider inference uses configured credentials; specify --provider to select explicitly. Bearer tokens have a 30-minute minimum expiry by default. --min-expiry accepts ms, s, m, or h (for example, 30m).`);
}
/** Parse the small, extensible `pi auth` command surface before normal startup. */
export function parseCredentialPrintCommand(args: string[]): CredentialPrintCommand | undefined {
if (args[0] !== "auth") return undefined;
const kind = args[1] === "print-api-key" ? "api_key" : args[1] === "print-bearer-token" ? "bearer_token" : undefined;
if (!kind) {
throw new CredentialPrintError(
`Unknown auth command "${args[1] ?? ""}". Use "pi auth print-api-key" or "pi auth print-bearer-token".`,
);
}
const commandArgs: string[] = [];
let minExpiryMs: number | undefined;
for (let index = 2; index < args.length; index++) {
if (args[index] !== "--min-expiry") {
commandArgs.push(args[index]);
continue;
}
if (kind !== "bearer_token") {
throw new CredentialPrintError("--min-expiry is only supported by print-bearer-token");
}
const value = args[++index];
const match = value ? /^(\d+)(ms|s|m|h)$/iu.exec(value) : undefined;
if (!match) {
throw new CredentialPrintError("--min-expiry must use a duration such as 30m or 1h");
}
const amount = Number(match[1]);
const unit = match[2];
minExpiryMs = amount * (unit === "ms" ? 1 : unit === "s" ? 1_000 : unit === "m" ? 60_000 : 3_600_000);
}
return minExpiryMs === undefined ? { kind, args: commandArgs } : { kind, args: commandArgs, minExpiryMs };
}
export function validateCredentialPrintArgs(args: Args): void {
if (!args.model?.trim()) {
throw new CredentialPrintError("Credential printing requires --model <model>");
}
if (args.apiKey !== undefined) {
throw new CredentialPrintError("Credential printing reads configured credentials; --api-key is not supported");
}
if (args.messages.length > 0 || args.fileArgs.length > 0 || args.unknownFlags.size > 0) {
throw new CredentialPrintError("Credential printing only accepts --provider and --model");
}
}
/**
* Resolve one request credential for a specific provider/model pair.
*
* This intentionally calls ModelRuntime.getAuth(), which refreshes and persists
* OAuth credentials with less than five minutes remaining through the normal request-auth path.
*/
export async function resolveCredentialForPrint(
args: Args,
modelRuntime: ModelRuntime,
kind: CredentialPrintKind,
minExpiryMs?: number,
): Promise<string> {
validateCredentialPrintArgs(args);
const credentialTypes = new Map<string, CredentialInfo["type"]>(
(await modelRuntime.listCredentials()).map((credential) => [credential.providerId, credential.type]),
);
const models: Model<Api>[] = [];
if (args.provider) {
const resolved = resolveCliModel({ cliProvider: args.provider, cliModel: args.model, modelRuntime });
if (resolved.error || !resolved.model) {
throw new CredentialPrintError(resolved.error ?? "Unable to resolve the requested provider/model");
}
models.push(resolved.model);
} else {
for (const provider of modelRuntime.getProviders()) {
if (!credentialTypes.has(provider.id)) continue;
const resolved = resolveCliModel({ cliProvider: provider.id, cliModel: args.model, modelRuntime });
if (resolved.model && !resolved.error && !resolved.warning?.includes("Using custom model id")) {
models.push(resolved.model);
}
}
if (models.length === 0) {
throw new CredentialPrintError(`Model "${args.model}" not found. Use --list-models to see available models.`);
}
}
const credentials: Array<{ providerId: string; value: string }> = [];
for (const model of models) {
const type = credentialTypes.get(model.provider);
if (kind === "api_key" && type === "oauth") continue;
if (kind === "bearer_token" && type !== "oauth") continue;
const auth = await modelRuntime.getAuth(
model,
kind === "bearer_token"
? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS }
: undefined,
);
const authorization = Object.entries(auth?.auth.headers ?? {}).find(
([name]) => name.toLowerCase() === "authorization",
)?.[1];
const bearerToken = typeof authorization === "string" ? /^Bearer\s+(.+)$/iu.exec(authorization)?.[1] : undefined;
const value = kind === "bearer_token" ? (auth?.auth.apiKey ?? bearerToken) : auth?.auth.apiKey;
if (value) credentials.push({ providerId: model.provider, value });
}
if (credentials.length === 1) return credentials[0].value;
if (credentials.length === 0) {
const providerId = models[0]?.provider;
const type = providerId ? credentialTypes.get(providerId) : undefined;
if (args.provider && kind === "api_key" && type === "oauth") {
throw new CredentialPrintError(`Provider "${providerId}" is configured with OAuth, not an API key`);
}
if (args.provider && kind === "bearer_token" && type !== "oauth") {
throw new CredentialPrintError(`Provider "${providerId}" is not configured with an OAuth bearer token`);
}
throw new CredentialPrintError(
`No usable ${kind === "api_key" ? "API key" : "OAuth bearer token"} is configured`,
);
}
throw new CredentialPrintError(
`Model "${args.model}" has multiple configured providers (${credentials.map(({ providerId }) => providerId).join(", ")}). Specify --provider.`,
);
}
@@ -0,0 +1,87 @@
/**
* Process @file CLI arguments into text content and image attachments
*/
import { access, readFile, stat } from "node:fs/promises";
import type { ImageContent } from "@earendil-works/pi-ai";
import chalk from "chalk";
import { resolve } from "path";
import { resolveReadPath } from "../core/tools/path-utils.ts";
import { processImage } from "../utils/image-process.ts";
import { detectSupportedImageMimeTypeFromFile } from "../utils/mime.ts";
export interface ProcessedFiles {
text: string;
images: ImageContent[];
}
export interface ProcessFileOptions {
/** Whether to auto-resize images to 2000x2000 max. Default: true */
autoResizeImages?: boolean;
}
/** Process @file arguments into text content and image attachments */
export async function processFileArguments(fileArgs: string[], options?: ProcessFileOptions): Promise<ProcessedFiles> {
const autoResizeImages = options?.autoResizeImages ?? true;
let text = "";
const images: ImageContent[] = [];
for (const fileArg of fileArgs) {
// Expand and resolve path (handles ~ expansion and macOS screenshot Unicode spaces)
const absolutePath = resolve(resolveReadPath(fileArg, process.cwd()));
// Check if file exists
try {
await access(absolutePath);
} catch {
console.error(chalk.red(`Error: File not found: ${absolutePath}`));
process.exit(1);
}
// Check if file is empty
const stats = await stat(absolutePath);
if (stats.size === 0) {
// Skip empty files
continue;
}
const mimeType = await detectSupportedImageMimeTypeFromFile(absolutePath);
if (mimeType) {
// Handle image file
const content = await readFile(absolutePath);
const processed = await processImage(content, mimeType, { autoResizeImages });
if (!processed.ok) {
text += `<file name="${absolutePath}">${processed.message}</file>\n`;
continue;
}
const attachment: ImageContent = {
type: "image",
mimeType: processed.mimeType,
data: processed.data,
};
images.push(attachment);
// Add text reference to image with optional processing hints
if (processed.hints.length > 0) {
text += `<file name="${absolutePath}">${processed.hints.join("\n")}</file>\n`;
} else {
text += `<file name="${absolutePath}"></file>\n`;
}
} else {
// Handle text file
try {
const content = await readFile(absolutePath, "utf-8");
text += `<file name="${absolutePath}">\n${content}\n</file>\n`;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
console.error(chalk.red(`Error: Could not read file ${absolutePath}: ${message}`));
process.exit(1);
}
}
}
return { text, images };
}
@@ -0,0 +1,43 @@
import type { ImageContent } from "@earendil-works/pi-ai";
import type { Args } from "./args.ts";
export interface InitialMessageInput {
parsed: Args;
fileText?: string;
fileImages?: ImageContent[];
stdinContent?: string;
}
export interface InitialMessageResult {
initialMessage?: string;
initialImages?: ImageContent[];
}
/**
* Combine stdin content, @file text, and the first CLI message into a single
* initial prompt for non-interactive mode.
*/
export function buildInitialMessage({
parsed,
fileText,
fileImages,
stdinContent,
}: InitialMessageInput): InitialMessageResult {
const parts: string[] = [];
if (stdinContent !== undefined) {
parts.push(stdinContent);
}
if (fileText) {
parts.push(fileText);
}
if (parsed.messages.length > 0) {
parts.push(parsed.messages[0]);
parsed.messages.shift();
}
return {
initialMessage: parts.length > 0 ? parts.join("") : undefined,
initialImages: fileImages && fileImages.length > 0 ? fileImages : undefined,
};
}
@@ -0,0 +1,111 @@
/**
* List available models with optional fuzzy search
*/
import type { Api, Model } from "@earendil-works/pi-ai";
import { fuzzyFilter } from "@earendil-works/pi-tui";
import chalk from "chalk";
import { formatNoModelsAvailableMessage } from "../core/auth-guidance.ts";
import type { ModelRuntime } from "../core/model-runtime.ts";
/**
* Format a number as human-readable (e.g., 200000 -> "200K", 1000000 -> "1M")
*/
function formatTokenCount(count: number): string {
if (count >= 1_000_000) {
const millions = count / 1_000_000;
return millions % 1 === 0 ? `${millions}M` : `${millions.toFixed(1)}M`;
}
if (count >= 1_000) {
const thousands = count / 1_000;
return thousands % 1 === 0 ? `${thousands}K` : `${thousands.toFixed(1)}K`;
}
return count.toString();
}
/**
* List available models, optionally filtered by search pattern
*/
export async function listModels(modelRuntime: ModelRuntime, searchPattern?: string): Promise<void> {
const loadError = modelRuntime.getError();
if (loadError) {
console.error(chalk.yellow(`Warning: errors loading models.json:\n${loadError}`));
}
const models = [...(await modelRuntime.getAvailable())];
if (models.length === 0) {
console.log(formatNoModelsAvailableMessage());
return;
}
// Apply fuzzy filter if search pattern provided
let filteredModels: Model<Api>[] = models;
if (searchPattern) {
filteredModels = fuzzyFilter(models, searchPattern, (m) => `${m.provider} ${m.id}`);
}
if (filteredModels.length === 0) {
console.log(`No models matching "${searchPattern}"`);
return;
}
// Sort by provider, then by model id
filteredModels.sort((a, b) => {
const providerCmp = a.provider.localeCompare(b.provider);
if (providerCmp !== 0) return providerCmp;
return a.id.localeCompare(b.id);
});
// Calculate column widths
const rows = filteredModels.map((m) => ({
provider: m.provider,
model: m.id,
context: formatTokenCount(m.contextWindow),
maxOut: formatTokenCount(m.maxTokens),
thinking: m.reasoning ? "yes" : "no",
images: m.input.includes("image") ? "yes" : "no",
}));
const headers = {
provider: "provider",
model: "model",
context: "context",
maxOut: "max-out",
thinking: "thinking",
images: "images",
};
const widths = {
provider: Math.max(headers.provider.length, ...rows.map((r) => r.provider.length)),
model: Math.max(headers.model.length, ...rows.map((r) => r.model.length)),
context: Math.max(headers.context.length, ...rows.map((r) => r.context.length)),
maxOut: Math.max(headers.maxOut.length, ...rows.map((r) => r.maxOut.length)),
thinking: Math.max(headers.thinking.length, ...rows.map((r) => r.thinking.length)),
images: Math.max(headers.images.length, ...rows.map((r) => r.images.length)),
};
// Print header
const headerLine = [
headers.provider.padEnd(widths.provider),
headers.model.padEnd(widths.model),
headers.context.padEnd(widths.context),
headers.maxOut.padEnd(widths.maxOut),
headers.thinking.padEnd(widths.thinking),
headers.images.padEnd(widths.images),
].join(" ");
console.log(headerLine);
// Print rows
for (const row of rows) {
const line = [
row.provider.padEnd(widths.provider),
row.model.padEnd(widths.model),
row.context.padEnd(widths.context),
row.maxOut.padEnd(widths.maxOut),
row.thinking.padEnd(widths.thinking),
row.images.padEnd(widths.images),
].join(" ");
console.log(line);
}
}
@@ -0,0 +1,62 @@
import chalk from "chalk";
import type { ProjectTrustContext } from "../core/extensions/types.ts";
import type { AppMode } from "../core/project-trust.ts";
import type { SettingsManager } from "../core/settings-manager.ts";
import { showStartupInput, showStartupSelector } from "./startup-ui.ts";
export function createProjectTrustContext(options: {
cwd: string;
mode: AppMode;
settingsManager: SettingsManager;
hasUI: boolean;
}): ProjectTrustContext {
return {
cwd: options.cwd,
mode: options.mode === "interactive" ? "tui" : options.mode,
hasUI: options.hasUI,
ui: {
select: async (title, selectOptions) => {
if (!options.hasUI) {
return undefined;
}
if (options.mode !== "interactive") {
return undefined;
}
return showStartupSelector(
options.settingsManager,
title,
selectOptions.map((option) => ({ label: option, value: option })),
);
},
confirm: async (title, message) => {
if (!options.hasUI) {
return false;
}
if (options.mode !== "interactive") {
return false;
}
return (
(await showStartupSelector(options.settingsManager, `${title}\n${message}`, [
{ label: "Yes", value: true },
{ label: "No", value: false },
])) ?? false
);
},
input: async (title, placeholder) => {
if (!options.hasUI) {
return undefined;
}
if (options.mode !== "interactive") {
return undefined;
}
return showStartupInput(options.settingsManager, title, placeholder);
},
notify: (message, type = "info") => {
if (options.mode !== "interactive") {
const color = type === "error" ? chalk.red : type === "warning" ? chalk.yellow : chalk.cyan;
console.error(color(message));
}
},
},
};
}
@@ -0,0 +1,55 @@
/**
* TUI session selector for --resume flag
*/
import { setKeybindings } from "@earendil-works/pi-tui";
import { KeybindingsManager } from "../core/keybindings.ts";
import type { SessionInfo, SessionListProgress } from "../core/session-manager.ts";
import type { SettingsManager } from "../core/settings-manager.ts";
import { SessionSelectorComponent } from "../modes/interactive/components/session-selector.ts";
import { createStartupTui, startStartupTui } from "./startup-ui.ts";
type SessionsLoader = (onProgress?: SessionListProgress) => Promise<SessionInfo[]>;
/** Show TUI session selector and return selected session path or null if cancelled */
export async function selectSession(
currentSessionsLoader: SessionsLoader,
allSessionsLoader: SessionsLoader,
settingsManager: SettingsManager,
): Promise<string | null> {
const ui = await createStartupTui(settingsManager);
return new Promise((resolve) => {
const keybindings = KeybindingsManager.create();
setKeybindings(keybindings);
let resolved = false;
const selector = new SessionSelectorComponent(
currentSessionsLoader,
allSessionsLoader,
(path: string) => {
if (!resolved) {
resolved = true;
ui.stop();
resolve(path);
}
},
() => {
if (!resolved) {
resolved = true;
ui.stop();
resolve(null);
}
},
() => {
ui.stop();
process.exit(0);
},
() => ui.requestRender(),
{ showRenameHint: false, keybindings },
);
ui.addChild(selector);
ui.setFocus(selector.getSessionList());
startStartupTui(ui, settingsManager);
});
}
@@ -0,0 +1,239 @@
import { ProcessTerminal, setKeybindings, TUI } from "@earendil-works/pi-tui";
import { existsSync } from "fs";
import { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR, getAgentDir, getSettingsPath, PACKAGE_NAME } from "../config.ts";
import { areExperimentalFeaturesEnabled } from "../core/experimental.ts";
import { KeybindingsManager } from "../core/keybindings.ts";
import { DefaultPackageManager, type ResolvedResource } from "../core/package-manager.ts";
import { SettingsManager } from "../core/settings-manager.ts";
import { ExtensionInputComponent } from "../modes/interactive/components/extension-input.ts";
import { ExtensionSelectorComponent } from "../modes/interactive/components/extension-selector.ts";
import {
FirstTimeSetupComponent,
type FirstTimeSetupResult,
} from "../modes/interactive/components/first-time-setup.ts";
import {
detectTerminalBackgroundFromEnv,
detectTerminalThemeForAuto,
initTheme,
loadThemeFromPath,
parseAutoThemeSetting,
resolveThemeSetting,
setRegisteredThemes,
setTheme,
type Theme,
} from "../modes/interactive/theme/theme.ts";
const OFFICIAL_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
const OFFICIAL_APP_NAME = "pi";
const OFFICIAL_CONFIG_DIR_NAME = ".pi";
interface DistributionMetadata {
packageName: string;
appName: string;
configDirName: string;
}
function isOfficialDistribution({ packageName, appName, configDirName }: DistributionMetadata): boolean {
return (
packageName === OFFICIAL_PACKAGE_NAME &&
appName === OFFICIAL_APP_NAME &&
configDirName === OFFICIAL_CONFIG_DIR_NAME
);
}
function loadThemes(resources: ResolvedResource[]): Theme[] {
const themes: Theme[] = [];
const seen = new Set<string>();
for (const resource of resources) {
if (!resource.enabled) continue;
try {
const loadedTheme = loadThemeFromPath(resource.path);
if (loadedTheme.name) {
if (seen.has(loadedTheme.name)) continue;
seen.add(loadedTheme.name);
}
themes.push(loadedTheme);
} catch {
// Startup prompts should not fail because a theme is broken. The normal
// resource loader reports theme diagnostics later in startup.
}
}
return themes;
}
async function loadStartupThemes(settingsManager: SettingsManager): Promise<Theme[]> {
const globalSettingsManager = SettingsManager.inMemory(settingsManager.getGlobalSettings(), {
projectTrusted: false,
});
const packageManager = new DefaultPackageManager({
cwd: process.cwd(),
agentDir: getAgentDir(),
settingsManager: globalSettingsManager,
});
const resolvedPaths = await packageManager.resolve(async () => "skip");
return loadThemes(resolvedPaths.themes);
}
export async function createStartupTui(settingsManager: SettingsManager): Promise<TUI> {
setRegisteredThemes(await loadStartupThemes(settingsManager));
const terminalTheme = detectTerminalBackgroundFromEnv().theme;
initTheme(resolveThemeSetting(settingsManager.getThemeSetting(), terminalTheme) ?? terminalTheme);
setKeybindings(KeybindingsManager.create());
const ui = new TUI(new ProcessTerminal(), settingsManager.getShowHardwareCursor(), getAgentDir());
ui.setClearOnShrink(settingsManager.getClearOnShrink());
return ui;
}
export function startStartupTui(ui: TUI, settingsManager: SettingsManager): void {
ui.start();
void applyDetectedStartupTheme(ui, settingsManager);
}
async function applyDetectedStartupTheme(ui: TUI, settingsManager: SettingsManager): Promise<void> {
const themeSetting = settingsManager.getThemeSetting();
if (themeSetting && !parseAutoThemeSetting(themeSetting)) return;
const terminalTheme = await detectTerminalThemeForAuto({ ui, timeoutMs: 100 });
setTheme(resolveThemeSetting(themeSetting, terminalTheme) ?? terminalTheme);
ui.invalidate();
ui.requestRender();
}
async function clearStartupTui(ui: TUI): Promise<void> {
ui.clear();
ui.requestRender();
await new Promise((resolve) => setTimeout(resolve, 25));
}
/**
* First-time setup runs when all of these hold:
* - this is the official Pi distribution (not a fork/rebrand)
* - experimental features are enabled (PI_EXPERIMENTAL=1)
* - the default agent directory is used (no custom agent dir override)
* - setup was not completed before (settings.json does not exist)
*/
export function shouldRunFirstTimeSetup(settingsPath: string = getSettingsPath()): boolean {
if (
!isOfficialDistribution({
packageName: PACKAGE_NAME,
appName: APP_NAME,
configDirName: CONFIG_DIR_NAME,
})
) {
return false;
}
if (!areExperimentalFeaturesEnabled()) {
return false;
}
if (process.env[ENV_AGENT_DIR]) {
return false;
}
return !existsSync(settingsPath);
}
export async function showStartupSelector<T>(
settingsManager: SettingsManager,
title: string,
options: Array<{ label: string; value: T }>,
): Promise<T | undefined> {
const ui = await createStartupTui(settingsManager);
return new Promise((resolve) => {
let settled = false;
const finish = async (result: T | undefined) => {
if (settled) {
return;
}
settled = true;
await clearStartupTui(ui);
ui.stop();
resolve(result);
};
const selector = new ExtensionSelectorComponent(
title,
options.map((option) => option.label),
(option) => void finish(options.find((entry) => entry.label === option)?.value),
() => void finish(undefined),
{ tui: ui },
);
ui.addChild(selector);
ui.setFocus(selector);
startStartupTui(ui, settingsManager);
});
}
/** Show the first-time setup dialog and persist the result */
export async function showFirstTimeSetup(settingsManager: SettingsManager): Promise<void> {
const ui = await createStartupTui(settingsManager);
return new Promise((resolve) => {
let settled = false;
const finish = async (result: FirstTimeSetupResult | undefined) => {
if (settled) {
return;
}
settled = true;
if (result) {
settingsManager.setTheme(result.theme);
settingsManager.setEnableAnalytics(result.shareAnalytics);
await settingsManager.flush();
}
await clearStartupTui(ui);
ui.stop();
resolve();
};
const showSetup = async () => {
ui.start();
const detectedTheme = await detectTerminalThemeForAuto({ ui, timeoutMs: 100 });
setTheme(detectedTheme);
const component = new FirstTimeSetupComponent({
detectedTheme,
onThemePreview: (themeName) => {
setTheme(themeName);
ui.requestRender();
},
onSubmit: (result) => void finish(result),
onCancel: () => void finish(undefined),
});
ui.addChild(component);
ui.setFocus(component);
ui.requestRender();
};
void showSetup();
});
}
export async function showStartupInput(
settingsManager: SettingsManager,
title: string,
placeholder?: string,
): Promise<string | undefined> {
const ui = await createStartupTui(settingsManager);
return new Promise((resolve) => {
let settled = false;
const finish = async (result: string | undefined) => {
if (settled) {
return;
}
settled = true;
input.dispose();
await clearStartupTui(ui);
ui.stop();
resolve(result);
};
const input = new ExtensionInputComponent(
title,
placeholder,
(value) => void finish(value),
() => void finish(undefined),
{
tui: ui,
},
);
ui.addChild(input);
ui.setFocus(input);
startStartupTui(ui, settingsManager);
});
}