chore(vendor): import pi 0.85.1
Imported as a linear vendor commit so forge rebases do not replay the upstream root tree. git-subtree-dir: third_party/pi git-subtree-split: d981de1229ef899957bbe968bc8dcda02a21f477
This commit is contained in:
447
third_party/pi/packages/coding-agent/src/cli/args.ts
vendored
Normal file
447
third_party/pi/packages/coding-agent/src/cli/args.ts
vendored
Normal file
@@ -0,0 +1,447 @@
|
||||
/**
|
||||
* 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";
|
||||
import type { TuiMode } from "../core/settings-manager.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[];
|
||||
useTheme?: string;
|
||||
noThemes?: boolean;
|
||||
noContextFiles?: boolean;
|
||||
listModels?: string | true;
|
||||
offline?: boolean;
|
||||
tuiMode?: TuiMode;
|
||||
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 normalizeSessionName(value: string): string | undefined {
|
||||
const name = value.trim();
|
||||
return name.length > 0 ? name : undefined;
|
||||
}
|
||||
|
||||
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 === "--") {
|
||||
for (const positionalArg of args.slice(i + 1)) {
|
||||
if (positionalArg.startsWith("@")) {
|
||||
result.fileArgs.push(positionalArg.slice(1));
|
||||
} else {
|
||||
result.messages.push(positionalArg);
|
||||
}
|
||||
}
|
||||
break;
|
||||
} else 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 === "--use-theme") {
|
||||
const themeName = args[i + 1];
|
||||
if (themeName === undefined || themeName.startsWith("-")) {
|
||||
result.diagnostics.push({ type: "error", message: "--use-theme requires a theme name" });
|
||||
} else {
|
||||
result.useTheme = themeName;
|
||||
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 === "--tui-mode") {
|
||||
const mode = args[i + 1];
|
||||
if (mode === "regular" || mode === "fullscreen") {
|
||||
result.tuiMode = mode;
|
||||
i++;
|
||||
} else if (mode === undefined || mode.startsWith("-")) {
|
||||
result.diagnostics.push({ type: "error", message: "--tui-mode requires regular or fullscreen" });
|
||||
} else {
|
||||
i++;
|
||||
result.diagnostics.push({
|
||||
type: "error",
|
||||
message: `Invalid TUI mode "${mode}". Valid values: regular, fullscreen`,
|
||||
});
|
||||
}
|
||||
} 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 or check provider readiness
|
||||
${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)
|
||||
--use-theme <name[/name]> Set the initial interactive theme for this run
|
||||
--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)
|
||||
--tui-mode <mode> TUI mode: regular (default) or fullscreen
|
||||
--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)
|
||||
-- End option parsing; treat remaining arguments as messages/files
|
||||
--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
|
||||
|
||||
# Print an OAuth bearer token for an external client (refreshes if expired)
|
||||
${APP_NAME} auth print-bearer-token --provider openai-codex
|
||||
|
||||
# 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/"
|
||||
|
||||
# Prompt beginning with a dash
|
||||
${APP_NAME} -p -- "- Summarize these points"
|
||||
|
||||
# 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
|
||||
BASETEN_API_KEY - Baseten 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
|
||||
powershell - Execute PowerShell commands on Windows
|
||||
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)
|
||||
`);
|
||||
}
|
||||
73
third_party/pi/packages/coding-agent/src/cli/auth-check.ts
vendored
Normal file
73
third_party/pi/packages/coding-agent/src/cli/auth-check.ts
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { CredentialStore } from "@earendil-works/pi-ai";
|
||||
import { resolveCliModel } from "../core/model-resolver.ts";
|
||||
import { ModelRuntime } from "../core/model-runtime.ts";
|
||||
import { InMemoryCodingAgentModelsStore } from "../core/models-store.ts";
|
||||
import type { Args } from "./args.ts";
|
||||
import { AuthCommandError, getAuthCredential, validateAuthCommandArgs } from "./auth-command.ts";
|
||||
|
||||
export type AuthCheckStatus = "ready" | "not_ready" | "invalid";
|
||||
export type AuthCheckReason =
|
||||
| "provider_not_found"
|
||||
| "credentials_not_configured"
|
||||
| "credential_not_available"
|
||||
| "invalid_state";
|
||||
|
||||
export interface AuthCheckResult {
|
||||
status: AuthCheckStatus;
|
||||
provider: string;
|
||||
reason?: AuthCheckReason;
|
||||
authType?: "api_key" | "oauth";
|
||||
}
|
||||
|
||||
export async function checkProviderAuth(
|
||||
args: Args,
|
||||
modelRuntime: ModelRuntime,
|
||||
options: { refresh: boolean } = { refresh: false },
|
||||
): Promise<AuthCheckResult> {
|
||||
const { provider: cliProvider, model: cliModel } = validateAuthCommandArgs(args, "check");
|
||||
let provider = cliProvider;
|
||||
if (cliModel) {
|
||||
const resolved = resolveCliModel({ cliProvider, cliModel, modelRuntime });
|
||||
if (resolved.error || !resolved.model) {
|
||||
throw new AuthCommandError(resolved.error ?? `Unable to resolve model "${cliModel}"`);
|
||||
}
|
||||
provider = resolved.model.provider;
|
||||
}
|
||||
if (!provider) throw new AuthCommandError("Unable to resolve an auth provider");
|
||||
if (modelRuntime.getError()) {
|
||||
return { status: "invalid", provider, reason: "invalid_state" };
|
||||
}
|
||||
if (!modelRuntime.getProvider(provider)) {
|
||||
return { status: "not_ready", provider, reason: "provider_not_found" };
|
||||
}
|
||||
try {
|
||||
const auth = await modelRuntime.checkAuth(provider);
|
||||
if (!auth) return { status: "not_ready", provider, reason: "credentials_not_configured" };
|
||||
if (options.refresh && !(await modelRuntime.getAuth(provider))) {
|
||||
return { status: "not_ready", provider, reason: "credentials_not_configured" };
|
||||
}
|
||||
return { status: "ready", provider, authType: auth.type };
|
||||
} catch {
|
||||
return { status: "invalid", provider, reason: "invalid_state" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProviderCredential(
|
||||
providerId: string,
|
||||
modelRuntime: ModelRuntime,
|
||||
credentials: CredentialStore,
|
||||
options: { refresh: boolean },
|
||||
): Promise<string | undefined> {
|
||||
const credential = await credentials.read(providerId);
|
||||
if (!options.refresh && credential?.type === "oauth") return credential.access;
|
||||
return getAuthCredential(await modelRuntime.getAuth(providerId));
|
||||
}
|
||||
|
||||
export async function createAuthCheckModelRuntime(credentials: CredentialStore): Promise<ModelRuntime> {
|
||||
return ModelRuntime.create({
|
||||
credentials,
|
||||
modelsStore: new InMemoryCodingAgentModelsStore(),
|
||||
allowModelNetwork: false,
|
||||
refreshOnCreate: false,
|
||||
});
|
||||
}
|
||||
126
third_party/pi/packages/coding-agent/src/cli/auth-command.ts
vendored
Normal file
126
third_party/pi/packages/coding-agent/src/cli/auth-command.ts
vendored
Normal file
@@ -0,0 +1,126 @@
|
||||
import type { AuthResult } from "@earendil-works/pi-ai";
|
||||
import { APP_NAME } from "../config.ts";
|
||||
import type { Args } from "./args.ts";
|
||||
|
||||
export type AuthCommandKind = "check" | "api_key" | "bearer_token";
|
||||
|
||||
export interface AuthCommand {
|
||||
kind: AuthCommandKind;
|
||||
args: string[];
|
||||
json: boolean;
|
||||
credentials: boolean;
|
||||
noRefresh: boolean;
|
||||
minExpiryMs?: number;
|
||||
}
|
||||
|
||||
export class AuthCommandError extends Error {}
|
||||
|
||||
const AUTH_COMMAND_USAGE: Record<AuthCommandKind, string> = {
|
||||
check: `${APP_NAME} auth check --provider <provider> [--json] [--credentials] [--no-refresh]`,
|
||||
api_key: `${APP_NAME} auth print-api-key --provider <provider> [--model <model>]`,
|
||||
bearer_token: `${APP_NAME} auth print-bearer-token --provider <provider> [--model <model>] [--min-expiry <duration>]`,
|
||||
};
|
||||
|
||||
export function getAuthCommandName(kind: AuthCommandKind): string {
|
||||
return kind === "check" ? "auth check" : kind === "api_key" ? "auth print-api-key" : "auth print-bearer-token";
|
||||
}
|
||||
|
||||
export function getAuthCommandUsage(kind: AuthCommandKind): string {
|
||||
return AUTH_COMMAND_USAGE[kind];
|
||||
}
|
||||
|
||||
export function isAuthCommandHelp(args: string[]): boolean {
|
||||
return (
|
||||
args[0] === "auth" &&
|
||||
(args[1] === undefined || args[1] === "help" || args.includes("--help") || args.includes("-h"))
|
||||
);
|
||||
}
|
||||
|
||||
export function printAuthCommandHelp(): void {
|
||||
console.log(`Usage:
|
||||
pi auth print-api-key [--provider <provider>] [--model <model>]
|
||||
pi auth print-bearer-token [--provider <provider>] [--model <model>] [--min-expiry <duration>]
|
||||
pi auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]
|
||||
|
||||
Auth commands require at least one of --provider or --model. Checks refresh expired OAuth credentials by default; --no-refresh prevents this. --credentials emits the credential, or includes it in JSON output.`);
|
||||
}
|
||||
|
||||
export function parseAuthCommand(args: string[]): AuthCommand | undefined {
|
||||
if (args[0] !== "auth") return undefined;
|
||||
|
||||
const kind =
|
||||
args[1] === "check"
|
||||
? "check"
|
||||
: args[1] === "print-api-key"
|
||||
? "api_key"
|
||||
: args[1] === "print-bearer-token"
|
||||
? "bearer_token"
|
||||
: undefined;
|
||||
if (!kind) {
|
||||
throw new AuthCommandError(
|
||||
`Unknown auth command "${args[1] ?? ""}". Use "${APP_NAME} auth print-api-key", "${APP_NAME} auth print-bearer-token", or "${APP_NAME} auth check".`,
|
||||
);
|
||||
}
|
||||
|
||||
const commandArgs: string[] = [];
|
||||
let json = false;
|
||||
let credentials = false;
|
||||
let noRefresh = false;
|
||||
let minExpiryMs: number | undefined;
|
||||
for (let index = 2; index < args.length; index++) {
|
||||
const arg = args[index];
|
||||
if (arg === "--min-expiry") {
|
||||
if (kind !== "bearer_token")
|
||||
throw new AuthCommandError("--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 AuthCommandError("--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);
|
||||
continue;
|
||||
}
|
||||
if (arg === "--json" || arg === "--credentials" || arg === "--no-refresh") {
|
||||
if (kind !== "check") throw new AuthCommandError(`${arg} is only supported by auth check`);
|
||||
if (arg === "--json") json = true;
|
||||
else if (arg === "--credentials") credentials = true;
|
||||
else noRefresh = true;
|
||||
continue;
|
||||
}
|
||||
commandArgs.push(arg);
|
||||
}
|
||||
|
||||
return minExpiryMs === undefined
|
||||
? { kind, args: commandArgs, json, credentials, noRefresh }
|
||||
: { kind, args: commandArgs, json, credentials, noRefresh, minExpiryMs };
|
||||
}
|
||||
|
||||
export function validateAuthCommandArgs(args: Args, kind: AuthCommandKind): { provider?: string; model?: string } {
|
||||
const provider = args.provider?.trim() || undefined;
|
||||
const model = args.model?.trim() || undefined;
|
||||
if (args.unknownFlags.size > 0) {
|
||||
const option = args.unknownFlags.keys().next().value;
|
||||
throw new AuthCommandError(`Unknown option --${option} for "${getAuthCommandName(kind)}".`);
|
||||
}
|
||||
if (args.apiKey !== undefined || args.messages.length > 0 || args.fileArgs.length > 0) {
|
||||
throw new AuthCommandError("Auth commands only accept --provider and --model");
|
||||
}
|
||||
if (kind === "check") {
|
||||
if (!provider && !model) {
|
||||
throw new AuthCommandError("Auth checks require --provider <provider> or --model <model>");
|
||||
}
|
||||
return { provider, model };
|
||||
}
|
||||
if (!provider && !model) {
|
||||
throw new AuthCommandError("Credential printing requires --provider <provider> or --model <model>");
|
||||
}
|
||||
return { provider, model };
|
||||
}
|
||||
|
||||
export function getAuthCredential(auth: AuthResult | undefined): string | undefined {
|
||||
if (auth?.auth.apiKey) return auth.auth.apiKey;
|
||||
const authorization = Object.entries(auth?.auth.headers ?? {}).find(
|
||||
([name]) => name.toLowerCase() === "authorization",
|
||||
)?.[1];
|
||||
return typeof authorization === "string" ? /^Bearer\s+(.+)$/iu.exec(authorization)?.[1] : undefined;
|
||||
}
|
||||
61
third_party/pi/packages/coding-agent/src/cli/config-selector.ts
vendored
Normal file
61
third_party/pi/packages/coding-agent/src/cli/config-selector.ts
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* TUI config selector for `pi config` command
|
||||
*/
|
||||
|
||||
import { ProcessTerminal, type TUI, TuiMainScreen } 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: TUI = new TuiMainScreen(
|
||||
new ProcessTerminal(),
|
||||
options.settingsManager.getShowHardwareCursor(),
|
||||
options.agentDir,
|
||||
);
|
||||
ui.setClearOnShrink(options.settingsManager.getClearOnShrink());
|
||||
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();
|
||||
});
|
||||
}
|
||||
87
third_party/pi/packages/coding-agent/src/cli/credential-print.ts
vendored
Normal file
87
third_party/pi/packages/coding-agent/src/cli/credential-print.ts
vendored
Normal file
@@ -0,0 +1,87 @@
|
||||
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";
|
||||
import { AuthCommandError, type AuthCommandKind, getAuthCredential, validateAuthCommandArgs } from "./auth-command.ts";
|
||||
|
||||
const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;
|
||||
|
||||
type CredentialPrintKind = Exclude<AuthCommandKind, "check">;
|
||||
|
||||
/**
|
||||
* Resolve one configured provider credential.
|
||||
*
|
||||
* 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,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const { provider: cliProvider, model: cliModel } = validateAuthCommandArgs(args, kind);
|
||||
const credentialTypes = new Map<string, CredentialInfo["type"]>(
|
||||
(await modelRuntime.listCredentials({ signal })).map((credential) => [credential.providerId, credential.type]),
|
||||
);
|
||||
const providers: Array<{ id: string; model?: Model<Api> }> = [];
|
||||
if (cliProvider) {
|
||||
const provider = modelRuntime.getProvider(cliProvider);
|
||||
if (!provider) {
|
||||
throw new AuthCommandError(`Unknown provider "${cliProvider}". Use --list-models to see available providers.`);
|
||||
}
|
||||
if (cliModel) {
|
||||
const resolved = resolveCliModel({ cliProvider: provider.id, cliModel, modelRuntime });
|
||||
if (resolved.error || !resolved.model) {
|
||||
throw new AuthCommandError(resolved.error ?? "Unable to resolve the requested provider/model");
|
||||
}
|
||||
providers.push({ id: provider.id, model: resolved.model });
|
||||
} else {
|
||||
providers.push({ id: provider.id });
|
||||
}
|
||||
} else {
|
||||
for (const provider of modelRuntime.getProviders()) {
|
||||
if (!credentialTypes.has(provider.id)) continue;
|
||||
const resolved = resolveCliModel({ cliProvider: provider.id, cliModel: cliModel!, modelRuntime });
|
||||
if (resolved.model && !resolved.error && !resolved.warning?.includes("Using custom model id")) {
|
||||
providers.push({ id: provider.id, model: resolved.model });
|
||||
}
|
||||
}
|
||||
if (providers.length === 0) {
|
||||
throw new AuthCommandError(`Model "${cliModel}" not found. Use --list-models to see available models.`);
|
||||
}
|
||||
}
|
||||
|
||||
const credentials: Array<{ providerId: string; value: string }> = [];
|
||||
for (const provider of providers) {
|
||||
const type = credentialTypes.get(provider.id);
|
||||
if (kind === "api_key" && type === "oauth") continue;
|
||||
if (kind === "bearer_token" && type !== "oauth") continue;
|
||||
const authOptions = {
|
||||
...(kind === "bearer_token" ? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS } : {}),
|
||||
signal,
|
||||
};
|
||||
const auth = provider.model
|
||||
? await modelRuntime.getAuth(provider.model, authOptions)
|
||||
: await modelRuntime.getAuth(provider.id, authOptions);
|
||||
const value = getAuthCredential(auth);
|
||||
if (value) credentials.push({ providerId: provider.id, value });
|
||||
}
|
||||
|
||||
if (credentials.length === 1) return credentials[0].value;
|
||||
if (credentials.length === 0) {
|
||||
const providerId = providers[0]?.id;
|
||||
const type = providerId ? credentialTypes.get(providerId) : undefined;
|
||||
if (cliProvider && kind === "api_key" && type === "oauth") {
|
||||
throw new AuthCommandError(`Provider "${providerId}" is configured with OAuth, not an API key`);
|
||||
}
|
||||
if (cliProvider && kind === "bearer_token" && type !== "oauth") {
|
||||
throw new AuthCommandError(`Provider "${providerId}" is not configured with an OAuth bearer token`);
|
||||
}
|
||||
throw new AuthCommandError(`No usable ${kind === "api_key" ? "API key" : "OAuth bearer token"} is configured`);
|
||||
}
|
||||
throw new AuthCommandError(
|
||||
`Multiple configured providers matched (${credentials.map(({ providerId }) => providerId).join(", ")}). Specify --provider.`,
|
||||
);
|
||||
}
|
||||
16
third_party/pi/packages/coding-agent/src/cli/experimental/cli.ts
vendored
Normal file
16
third_party/pi/packages/coding-agent/src/cli/experimental/cli.ts
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Command } from "./command.ts";
|
||||
import { type ClientCommandContext, clientCommand } from "./commands/client.ts";
|
||||
import { type ServerCommandContext, serverCommand } from "./commands/server.ts";
|
||||
|
||||
interface ExperimentalCommandGroup {
|
||||
readonly command: "experimental";
|
||||
}
|
||||
|
||||
export type CliContext = ServerCommandContext & ClientCommandContext;
|
||||
|
||||
const experimentalCommand = new Command<ExperimentalCommandGroup, CliContext>("experimental").build(() => ({
|
||||
ok: false,
|
||||
errors: ["Expected experimental command: server or client"],
|
||||
}));
|
||||
|
||||
export const cli = experimentalCommand.command(serverCommand).command(clientCommand);
|
||||
106
third_party/pi/packages/coding-agent/src/cli/experimental/command-options.ts
vendored
Normal file
106
third_party/pi/packages/coding-agent/src/cli/experimental/command-options.ts
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
import { posix } from "node:path";
|
||||
import { isServerId, type ServerId } from "@earendil-works/pi-protocol";
|
||||
import { type ParsedCommandInput, stringOption, valueOption } from "./command.ts";
|
||||
|
||||
export type AuthInput =
|
||||
| { readonly type: "token"; readonly token: string }
|
||||
| { readonly type: "file"; readonly path: string };
|
||||
|
||||
interface UnixTransportAddress {
|
||||
readonly transport: "unix";
|
||||
readonly path: string;
|
||||
}
|
||||
|
||||
interface RadiusTransportAddress {
|
||||
readonly transport: "radius";
|
||||
readonly serverId: ServerId;
|
||||
}
|
||||
|
||||
export type TransportAddress = UnixTransportAddress | RadiusTransportAddress;
|
||||
|
||||
export const authTokenOption = stringOption("--auth-token");
|
||||
export const authTokenFileOption = stringOption("--auth-token-file");
|
||||
|
||||
function parseAuthInput(options: { readonly authToken?: string; readonly authTokenFile?: string }): {
|
||||
auth?: AuthInput;
|
||||
errors: string[];
|
||||
} {
|
||||
if (options.authToken !== undefined && options.authTokenFile !== undefined) {
|
||||
return { errors: ["--auth-token and --auth-token-file are mutually exclusive"] };
|
||||
}
|
||||
if (options.authToken !== undefined) {
|
||||
return { auth: { type: "token", token: options.authToken }, errors: [] };
|
||||
}
|
||||
if (options.authTokenFile !== undefined) {
|
||||
return { auth: { type: "file", path: options.authTokenFile }, errors: [] };
|
||||
}
|
||||
return { errors: [] };
|
||||
}
|
||||
|
||||
function parseTransportAddress(value: string): { address?: TransportAddress; error?: string } {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
if (url.protocol === "radius:") {
|
||||
if (
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.port ||
|
||||
(url.pathname !== "" && url.pathname !== "/") ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
value !== `radius://${url.hostname}${url.pathname}`
|
||||
) {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
const serverId = url.hostname;
|
||||
if (!isServerId(serverId)) {
|
||||
return { error: "Radius transport address requires a lowercase UUIDv4 server ID" };
|
||||
}
|
||||
return { address: { transport: "radius", serverId } };
|
||||
}
|
||||
if (url.protocol !== "unix:") return { error: `Unsupported --connect transport "${url.protocol}"` };
|
||||
if (url.hostname || url.port || url.username || url.password) {
|
||||
return { error: "Unix transport address must not include an authority" };
|
||||
}
|
||||
if (
|
||||
!value.startsWith("unix:///") ||
|
||||
value.startsWith("unix:////") ||
|
||||
value.includes("?") ||
|
||||
value.includes("#") ||
|
||||
url.href !== value
|
||||
) {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
let path: string;
|
||||
try {
|
||||
path = decodeURIComponent(url.pathname);
|
||||
} catch {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
if (path.includes("\0")) return { error: `Invalid --connect address "${value}"` };
|
||||
if (!posix.isAbsolute(path)) return { error: "Unix transport address requires an absolute path" };
|
||||
return { address: { transport: "unix", path } };
|
||||
}
|
||||
|
||||
export const connectOption = valueOption("--connect", (value) => {
|
||||
const result = parseTransportAddress(value);
|
||||
return result.address
|
||||
? { ok: true, value: result.address }
|
||||
: { ok: false, error: result.error ?? `Invalid --connect address "${value}"` };
|
||||
});
|
||||
|
||||
export function parseAuth(input: ParsedCommandInput): { auth?: AuthInput; errors: string[] } {
|
||||
return parseAuthInput({
|
||||
authToken: input.value(authTokenOption),
|
||||
authTokenFile: input.value(authTokenFileOption),
|
||||
});
|
||||
}
|
||||
|
||||
export function unsupportedOptions(command: string, input: ParsedCommandInput): string[] {
|
||||
if (input.remainingArgs.length === 0) return [];
|
||||
return [`The experimental ${command} command does not support existing CLI options yet`];
|
||||
}
|
||||
225
third_party/pi/packages/coding-agent/src/cli/experimental/command.ts
vendored
Normal file
225
third_party/pi/packages/coding-agent/src/cli/experimental/command.ts
vendored
Normal file
@@ -0,0 +1,225 @@
|
||||
export interface NamedCommandInvocation {
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
export type CommandParseResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =
|
||||
| { readonly ok: true; readonly command: TInvocation }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
export type CommandExecutionResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =
|
||||
| { readonly ok: true; readonly command: TInvocation }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
export type CommandOptionParseResult<TValue> =
|
||||
| { readonly ok: true; readonly value: TValue }
|
||||
| { readonly ok: false; readonly error: string };
|
||||
|
||||
export interface CommandOption<TValue> {
|
||||
readonly name: `-${string}`;
|
||||
readonly flag?: boolean;
|
||||
readonly repeatable?: boolean;
|
||||
parse(value: string): CommandOptionParseResult<TValue>;
|
||||
}
|
||||
|
||||
export function valueOption<TValue>(
|
||||
name: `-${string}`,
|
||||
parse: (value: string) => CommandOptionParseResult<TValue>,
|
||||
options: { readonly repeatable?: boolean } = {},
|
||||
): CommandOption<TValue> {
|
||||
return { name, parse, ...options };
|
||||
}
|
||||
|
||||
export function stringOption(
|
||||
name: `-${string}`,
|
||||
options: { readonly repeatable?: boolean } = {},
|
||||
): CommandOption<string> {
|
||||
return valueOption(name, (value) => ({ ok: true, value }), options);
|
||||
}
|
||||
|
||||
export function flagOption(name: `-${string}`): CommandOption<boolean> {
|
||||
return { name, flag: true, parse: () => ({ ok: true, value: true }) };
|
||||
}
|
||||
|
||||
export interface ParsedCommandInput {
|
||||
readonly remainingArgs: readonly string[];
|
||||
value<TValue>(option: CommandOption<TValue>): TValue | undefined;
|
||||
values<TValue>(option: CommandOption<TValue>): readonly TValue[];
|
||||
}
|
||||
|
||||
export type CommandBuildResult<TInvocation extends NamedCommandInvocation> =
|
||||
| { readonly ok: true; readonly command: TInvocation }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
interface MutableParsedCommandInput {
|
||||
readonly values: Map<string, unknown[]>;
|
||||
readonly remainingArgs: string[];
|
||||
readonly errors: string[];
|
||||
}
|
||||
|
||||
type CommandBuilder<TInvocation extends NamedCommandInvocation> = (
|
||||
input: ParsedCommandInput,
|
||||
) => CommandBuildResult<TInvocation>;
|
||||
|
||||
type CommandAction<TInvocation extends NamedCommandInvocation, TContext> = (
|
||||
command: TInvocation,
|
||||
context: TContext,
|
||||
) => void | Promise<void>;
|
||||
|
||||
interface RegisteredCommand {
|
||||
parse(argv: readonly string[]): CommandParseResult;
|
||||
execute(argv: readonly string[], context: unknown): Promise<CommandExecutionResult>;
|
||||
}
|
||||
|
||||
export class Command<
|
||||
TOwnInvocation extends NamedCommandInvocation,
|
||||
TContext,
|
||||
TInvocation extends NamedCommandInvocation = TOwnInvocation,
|
||||
> {
|
||||
readonly name: string;
|
||||
private readonly options = new Map<string, CommandOption<unknown>>();
|
||||
private readonly subcommands = new Map<string, RegisteredCommand>();
|
||||
private builder?: CommandBuilder<TOwnInvocation>;
|
||||
private commandAction?: CommandAction<TOwnInvocation, TContext>;
|
||||
|
||||
constructor(name: string) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
option<TValue>(option: CommandOption<TValue>): this {
|
||||
if (this.options.has(option.name)) {
|
||||
throw new Error(`Option ${option.name} is already registered for ${this.name}`);
|
||||
}
|
||||
this.options.set(option.name, option);
|
||||
return this;
|
||||
}
|
||||
|
||||
build(builder: CommandBuilder<TOwnInvocation>): this {
|
||||
this.builder = builder;
|
||||
return this;
|
||||
}
|
||||
|
||||
action(action: CommandAction<TOwnInvocation, TContext>): this {
|
||||
this.commandAction = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
command<
|
||||
TSubcommandOwnInvocation extends NamedCommandInvocation,
|
||||
TSubcommandContext,
|
||||
TSubcommandInvocation extends NamedCommandInvocation,
|
||||
>(
|
||||
command: Command<TSubcommandOwnInvocation, TSubcommandContext, TSubcommandInvocation>,
|
||||
): Command<TOwnInvocation, TContext & TSubcommandContext, TInvocation | TSubcommandInvocation> {
|
||||
if (this.subcommands.has(command.name)) throw new Error(`Command ${command.name} is already registered`);
|
||||
this.subcommands.set(command.name, {
|
||||
parse: (argv) => command.parse(argv),
|
||||
execute: (argv, context) => command.execute(argv, context as TSubcommandContext),
|
||||
});
|
||||
return this as unknown as Command<
|
||||
TOwnInvocation,
|
||||
TContext & TSubcommandContext,
|
||||
TInvocation | TSubcommandInvocation
|
||||
>;
|
||||
}
|
||||
|
||||
parse(argv: readonly string[]): CommandParseResult<TInvocation> {
|
||||
const selected = this.select(argv);
|
||||
if (selected) return selected.command.parse(selected.argv) as CommandParseResult<TInvocation>;
|
||||
return this.parseOwn(argv) as CommandParseResult<TInvocation>;
|
||||
}
|
||||
|
||||
async execute(argv: readonly string[], context: TContext): Promise<CommandExecutionResult<TInvocation>> {
|
||||
const selected = this.select(argv);
|
||||
if (selected) {
|
||||
return selected.command.execute(selected.argv, context) as Promise<CommandExecutionResult<TInvocation>>;
|
||||
}
|
||||
|
||||
const parsed = this.parseOwn(argv);
|
||||
if (!parsed.ok) return parsed;
|
||||
if (!this.commandAction) throw new Error(`Command ${this.name} does not define an action`);
|
||||
await this.commandAction(parsed.command, context);
|
||||
return { ok: true, command: parsed.command as unknown as TInvocation };
|
||||
}
|
||||
|
||||
private select(argv: readonly string[]): { command: RegisteredCommand; argv: readonly string[] } | undefined {
|
||||
const candidate = argv[0];
|
||||
if (candidate === undefined) return undefined;
|
||||
const command = this.subcommands.get(candidate);
|
||||
return command ? { command, argv: argv.slice(1) } : undefined;
|
||||
}
|
||||
|
||||
private parseOwn(argv: readonly string[]): CommandParseResult<TOwnInvocation> {
|
||||
if (!this.builder) throw new Error(`Command ${this.name} does not define a builder`);
|
||||
const parsed = this.parseOptions(argv);
|
||||
const input: ParsedCommandInput = {
|
||||
remainingArgs: parsed.remainingArgs,
|
||||
value: <TValue>(option: CommandOption<TValue>) => parsed.values.get(option.name)?.[0] as TValue | undefined,
|
||||
values: <TValue>(option: CommandOption<TValue>) => (parsed.values.get(option.name) ?? []) as readonly TValue[],
|
||||
};
|
||||
const built = this.builder(input);
|
||||
const errors = [...parsed.errors, ...(built.ok ? [] : built.errors)];
|
||||
if (errors.length > 0) return { ok: false, errors };
|
||||
if (!built.ok) throw new Error(`Command ${this.name} failed without an error`);
|
||||
return { ok: true, command: built.command };
|
||||
}
|
||||
|
||||
private parseOptions(argv: readonly string[]): MutableParsedCommandInput {
|
||||
const parsed: MutableParsedCommandInput = {
|
||||
values: new Map(),
|
||||
remainingArgs: [],
|
||||
errors: [],
|
||||
};
|
||||
for (let index = 0; index < argv.length; index++) {
|
||||
const argument = argv[index]!;
|
||||
if (argument === "--") {
|
||||
parsed.remainingArgs.push(...argv.slice(index));
|
||||
break;
|
||||
}
|
||||
|
||||
const equals = argument.indexOf("=");
|
||||
const name = equals === -1 ? argument : argument.slice(0, equals);
|
||||
const option = this.options.get(name);
|
||||
if (!option) {
|
||||
parsed.remainingArgs.push(...argv.slice(index));
|
||||
break;
|
||||
}
|
||||
|
||||
let value: string;
|
||||
if (option.flag === true) {
|
||||
if (equals !== -1) {
|
||||
parsed.errors.push(`${name} does not take a value`);
|
||||
continue;
|
||||
}
|
||||
value = "";
|
||||
} else {
|
||||
let candidate = equals === -1 ? undefined : argument.slice(equals + 1);
|
||||
if (candidate === undefined) {
|
||||
const next = argv[index + 1];
|
||||
if (next !== undefined && !next.startsWith("-")) {
|
||||
candidate = next;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
if (candidate === undefined || candidate === "") {
|
||||
parsed.errors.push(`${name} requires a value`);
|
||||
continue;
|
||||
}
|
||||
value = candidate;
|
||||
}
|
||||
|
||||
const values = parsed.values.get(name) ?? [];
|
||||
if (values.length > 0 && option.repeatable !== true) {
|
||||
parsed.errors.push(`${name} may only be specified once`);
|
||||
continue;
|
||||
}
|
||||
const result = option.parse(value);
|
||||
if (!result.ok) {
|
||||
parsed.errors.push(result.error);
|
||||
continue;
|
||||
}
|
||||
values.push(result.value);
|
||||
parsed.values.set(name, values);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
91
third_party/pi/packages/coding-agent/src/cli/experimental/commands/client.ts
vendored
Normal file
91
third_party/pi/packages/coding-agent/src/cli/experimental/commands/client.ts
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Command, flagOption, stringOption } from "../command.ts";
|
||||
import {
|
||||
type AuthInput,
|
||||
authTokenFileOption,
|
||||
authTokenOption,
|
||||
connectOption,
|
||||
parseAuth,
|
||||
type TransportAddress,
|
||||
unsupportedOptions,
|
||||
} from "../command-options.ts";
|
||||
|
||||
export interface ClientCommand {
|
||||
readonly command: "client";
|
||||
readonly auth?: AuthInput;
|
||||
readonly connect?: TransportAddress;
|
||||
readonly sessionId?: string;
|
||||
readonly continue?: boolean;
|
||||
readonly resume?: boolean;
|
||||
readonly provider?: string;
|
||||
readonly model?: string;
|
||||
readonly pluginPackages?: readonly string[];
|
||||
readonly prompt?: string;
|
||||
}
|
||||
|
||||
export interface ClientCommandContext {
|
||||
runClient(command: ClientCommand): void | Promise<void>;
|
||||
}
|
||||
|
||||
const sessionIdOption = stringOption("--session-id");
|
||||
const continueOption = flagOption("--continue");
|
||||
const continueShortOption = flagOption("-c");
|
||||
const resumeOption = flagOption("--resume");
|
||||
const resumeShortOption = flagOption("-r");
|
||||
const providerOption = stringOption("--provider");
|
||||
const modelOption = stringOption("--model");
|
||||
const pluginPackageOption = stringOption("-e", { repeatable: true });
|
||||
|
||||
export const clientCommand = new Command<ClientCommand, ClientCommandContext>("client")
|
||||
.option(connectOption)
|
||||
.option(sessionIdOption)
|
||||
.option(continueOption)
|
||||
.option(continueShortOption)
|
||||
.option(resumeOption)
|
||||
.option(resumeShortOption)
|
||||
.option(providerOption)
|
||||
.option(modelOption)
|
||||
.option(pluginPackageOption)
|
||||
.option(authTokenOption)
|
||||
.option(authTokenFileOption)
|
||||
.build((input) => {
|
||||
const { auth, errors: authErrors } = parseAuth(input);
|
||||
const connect = input.value(connectOption);
|
||||
const sessionId = input.value(sessionIdOption);
|
||||
const shouldContinue = input.value(continueOption) === true || input.value(continueShortOption) === true;
|
||||
const shouldResume = input.value(resumeOption) === true || input.value(resumeShortOption) === true;
|
||||
const provider = input.value(providerOption);
|
||||
const model = input.value(modelOption);
|
||||
const pluginPackages = input.values(pluginPackageOption);
|
||||
const promptArgs = input.remainingArgs[0] === "--" ? input.remainingArgs.slice(1) : input.remainingArgs;
|
||||
const prompt =
|
||||
promptArgs.length === 1 &&
|
||||
(input.remainingArgs[0] === "--" || !promptArgs[0]!.startsWith("-")) &&
|
||||
promptArgs[0]!.length > 0
|
||||
? promptArgs[0]
|
||||
: undefined;
|
||||
const modelErrors = provider !== undefined && model === undefined ? ["--provider requires --model"] : [];
|
||||
const sessionSelectionErrors =
|
||||
[sessionId !== undefined, shouldContinue, shouldResume].filter(Boolean).length > 1
|
||||
? ["--session-id, --continue, and --resume are mutually exclusive"]
|
||||
: [];
|
||||
const unsupportedErrors =
|
||||
input.remainingArgs.length === 0 || prompt !== undefined ? [] : unsupportedOptions("client", input);
|
||||
const errors = [...authErrors, ...modelErrors, ...sessionSelectionErrors, ...unsupportedErrors];
|
||||
if (errors.length > 0) return { ok: false, errors };
|
||||
return {
|
||||
ok: true,
|
||||
command: {
|
||||
command: "client",
|
||||
...(auth === undefined ? {} : { auth }),
|
||||
...(connect === undefined ? {} : { connect }),
|
||||
...(sessionId === undefined ? {} : { sessionId }),
|
||||
...(shouldContinue ? { continue: true } : {}),
|
||||
...(shouldResume ? { resume: true } : {}),
|
||||
...(provider === undefined ? {} : { provider }),
|
||||
...(model === undefined ? {} : { model }),
|
||||
...(pluginPackages.length === 0 ? {} : { pluginPackages }),
|
||||
...(prompt === undefined ? {} : { prompt }),
|
||||
},
|
||||
};
|
||||
})
|
||||
.action((command, context) => context.runClient(command));
|
||||
66
third_party/pi/packages/coding-agent/src/cli/experimental/commands/server.ts
vendored
Normal file
66
third_party/pi/packages/coding-agent/src/cli/experimental/commands/server.ts
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
import { isServerId, type ServerId } from "@earendil-works/pi-protocol";
|
||||
import { Command, stringOption, valueOption } from "../command.ts";
|
||||
import {
|
||||
type AuthInput,
|
||||
authTokenFileOption,
|
||||
authTokenOption,
|
||||
parseAuth,
|
||||
unsupportedOptions,
|
||||
} from "../command-options.ts";
|
||||
|
||||
export interface ServerCommand {
|
||||
readonly command: "server";
|
||||
readonly auth?: AuthInput;
|
||||
readonly provider?: string;
|
||||
readonly model?: string;
|
||||
readonly pluginPackages?: readonly string[];
|
||||
readonly serverId?: ServerId;
|
||||
readonly sessionDir?: string;
|
||||
}
|
||||
|
||||
export interface ServerCommandContext {
|
||||
runServer(command: ServerCommand): void | Promise<void>;
|
||||
}
|
||||
|
||||
const serverIdOption = valueOption("--server-id", (value) =>
|
||||
isServerId(value)
|
||||
? { ok: true, value }
|
||||
: { ok: false, error: `Invalid --server-id "${value}"; expected a lowercase UUIDv4` },
|
||||
);
|
||||
const sessionDirOption = stringOption("--session-dir");
|
||||
const providerOption = stringOption("--provider");
|
||||
const modelOption = stringOption("--model");
|
||||
const pluginPackageOption = stringOption("-e", { repeatable: true });
|
||||
|
||||
export const serverCommand = new Command<ServerCommand, ServerCommandContext>("server")
|
||||
.option(serverIdOption)
|
||||
.option(sessionDirOption)
|
||||
.option(providerOption)
|
||||
.option(modelOption)
|
||||
.option(pluginPackageOption)
|
||||
.option(authTokenOption)
|
||||
.option(authTokenFileOption)
|
||||
.build((input) => {
|
||||
const { auth, errors: authErrors } = parseAuth(input);
|
||||
const serverId = input.value(serverIdOption);
|
||||
const sessionDir = input.value(sessionDirOption);
|
||||
const provider = input.value(providerOption);
|
||||
const model = input.value(modelOption);
|
||||
const pluginPackages = input.values(pluginPackageOption);
|
||||
const modelErrors = provider !== undefined && model === undefined ? ["--provider requires --model"] : [];
|
||||
const errors = [...authErrors, ...modelErrors, ...unsupportedOptions("server", input)];
|
||||
if (errors.length > 0) return { ok: false, errors };
|
||||
return {
|
||||
ok: true,
|
||||
command: {
|
||||
command: "server",
|
||||
...(auth === undefined ? {} : { auth }),
|
||||
...(provider === undefined ? {} : { provider }),
|
||||
...(model === undefined ? {} : { model }),
|
||||
...(pluginPackages.length === 0 ? {} : { pluginPackages }),
|
||||
...(serverId === undefined ? {} : { serverId }),
|
||||
...(sessionDir === undefined ? {} : { sessionDir }),
|
||||
},
|
||||
};
|
||||
})
|
||||
.action((command, context) => context.runServer(command));
|
||||
88
third_party/pi/packages/coding-agent/src/cli/file-processor.ts
vendored
Normal file
88
third_party/pi/packages/coding-agent/src/cli/file-processor.ts
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* 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";
|
||||
import { stripBom } from "../utils/text.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 = stripBom(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 };
|
||||
}
|
||||
43
third_party/pi/packages/coding-agent/src/cli/initial-message.ts
vendored
Normal file
43
third_party/pi/packages/coding-agent/src/cli/initial-message.ts
vendored
Normal file
@@ -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,
|
||||
};
|
||||
}
|
||||
115
third_party/pi/packages/coding-agent/src/cli/list-models.ts
vendored
Normal file
115
third_party/pi/packages/coding-agent/src/cli/list-models.ts
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* 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,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const loadError = modelRuntime.getError();
|
||||
if (loadError) {
|
||||
console.error(chalk.yellow(`Warning: errors loading models.json:\n${loadError}`));
|
||||
}
|
||||
|
||||
const models = [...(await modelRuntime.getAvailable(undefined, { signal }))];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
62
third_party/pi/packages/coding-agent/src/cli/project-trust.ts
vendored
Normal file
62
third_party/pi/packages/coding-agent/src/cli/project-trust.ts
vendored
Normal file
@@ -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));
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
55
third_party/pi/packages/coding-agent/src/cli/session-picker.ts
vendored
Normal file
55
third_party/pi/packages/coding-agent/src/cli/session-picker.ts
vendored
Normal file
@@ -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);
|
||||
});
|
||||
}
|
||||
13
third_party/pi/packages/coding-agent/src/cli/setup.ts
vendored
Normal file
13
third_party/pi/packages/coding-agent/src/cli/setup.ts
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
import { APP_NAME } from "../config.ts";
|
||||
import { configureHttpDispatcher } from "../core/http-dispatcher.ts";
|
||||
|
||||
export function setupCli(): void {
|
||||
process.title = APP_NAME;
|
||||
process.env.PI_CODING_AGENT = "true";
|
||||
process.env.AI_AGENT = "pi";
|
||||
process.emitWarning = (() => {}) as typeof process.emitWarning;
|
||||
|
||||
// Configure undici before provider SDKs issue requests. Settings are applied
|
||||
// once SettingsManager has loaded global/project configuration.
|
||||
configureHttpDispatcher();
|
||||
}
|
||||
246
third_party/pi/packages/coding-agent/src/cli/startup-ui.ts
vendored
Normal file
246
third_party/pi/packages/coding-agent/src/cli/startup-ui.ts
vendored
Normal file
@@ -0,0 +1,246 @@
|
||||
import {
|
||||
ProcessTerminal,
|
||||
setCapabilityOverrides,
|
||||
setKeybindings,
|
||||
type TUI,
|
||||
TuiMainScreen,
|
||||
} 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> {
|
||||
setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides());
|
||||
setRegisteredThemes(await loadStartupThemes(settingsManager));
|
||||
const terminalTheme = detectTerminalBackgroundFromEnv().theme;
|
||||
initTheme(resolveThemeSetting(settingsManager.getThemeSetting(), terminalTheme) ?? terminalTheme);
|
||||
setKeybindings(KeybindingsManager.create());
|
||||
const ui: TUI = new TuiMainScreen(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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user