chore(vendor): import pi 1.3.0

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: 71023aec1546d6d677a65669c5665c0927ce0dd0
This commit is contained in:
2026-10-15 17:58:48 -04:00
parent 719370c8f7
commit 6081e3e325
1743 changed files with 205460 additions and 131705 deletions

View File

@@ -6,7 +6,7 @@ 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";
import { getToolListError, type TuiMode } from "../core/settings-manager.ts";
export type Mode = "text" | "json" | "rpc";
@@ -35,6 +35,7 @@ export interface Args {
noBuiltinTools?: boolean;
extensions?: string[];
noExtensions?: boolean;
noMcp?: boolean;
print?: boolean;
export?: string;
noSkills?: boolean;
@@ -92,11 +93,21 @@ export function parseArgs(args: string[]): Args {
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 === "--mode") {
const mode = args[i + 1];
if (mode === undefined || mode.startsWith("-")) {
result.diagnostics.push({ type: "error", message: "--mode requires text, json, or rpc" });
continue;
}
i++;
if (mode !== "text" && mode !== "json" && mode !== "rpc") {
result.diagnostics.push({
type: "error",
message: `Invalid mode "${mode}". Valid values: text, json, rpc`,
});
continue;
}
result.mode = mode;
} else if (arg === "--continue" || arg === "-c") {
result.continue = true;
} else if (arg === "--resume" || arg === "-r") {
@@ -129,16 +140,25 @@ export function parseArgs(args: string[]): Args {
} 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());
result.models = args[++i]
.split(",")
.map((s) => s.trim())
.filter((pattern) => pattern.length > 0);
} 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]
const tools = args[++i]
.split(",")
.map((s) => s.trim())
.filter((name) => name.length > 0);
const error = getToolListError(tools);
if (error) {
result.diagnostics.push({ type: "error", message: `${arg}: ${error}` });
} else {
result.tools = tools;
}
} else if ((arg === "--exclude-tools" || arg === "-xt") && i + 1 < args.length) {
result.excludeTools = args[++i]
.split(",")
@@ -168,6 +188,8 @@ export function parseArgs(args: string[]): Args {
result.extensions.push(args[++i]);
} else if (arg === "--no-extensions" || arg === "-ne") {
result.noExtensions = true;
} else if (arg === "--no-mcp") {
result.noMcp = true;
} else if (arg === "--skill" && i + 1 < args.length) {
result.skills = result.skills ?? [];
result.skills.push(args[++i]);
@@ -272,10 +294,11 @@ ${chalk.bold("Commands:")}
${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
${APP_NAME} mcp <command> Check MCP servers, sign in to or out of OAuth servers
${APP_NAME} <command> --help Show help for install/remove/uninstall/update/list/config/auth/mcp
${chalk.bold("Options:")}
--provider <name> Provider name (default: google)
--provider <name> Provider to search for --model (requires --model)
--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)
@@ -294,13 +317,15 @@ ${chalk.bold("Options:")}
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
--tools, -t <tools> Comma-separated allowlist of tool names or patterns (*) to enable
Keeps MCP tools unless an entry starts with mcp__
Only +name/-name entries add to or remove from the defaults
--exclude-tools, -xt <tools> Comma-separated denylist of tool names or patterns (*) to disable
Applies to all tools, MCP tools included
--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)
--extension, -e <path> Load an extension file or builtin:<name> (can be used multiple times)
--no-extensions, -ne Disable extension discovery and built-in extensions (explicit -e paths still work)
--no-mcp Disable built-in MCP support: no servers connect and no MCP tools
--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)
@@ -312,7 +337,7 @@ ${chalk.bold("Options:")}
--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
--tui-mode <mode> TUI mode: fullscreen (default) or regular
--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)
@@ -377,6 +402,12 @@ ${chalk.bold("Examples:")}
# Read-only mode (no file modifications possible)
${APP_NAME} --tools read,grep,find,ls -p "Review the code in src/"
# Add codemode to the default tools
${APP_NAME} --tools +codemode
# Codemode with only the tools of one MCP server
${APP_NAME} --tools read,bash,codemode,'mcp__radius__*'
# Disable one tool while keeping the rest available
${APP_NAME} --exclude-tools ask_question
@@ -413,6 +444,7 @@ ${chalk.bold("Environment Variables:")}
MOONSHOT_API_KEY - Moonshot AI API key
OPENCODE_API_KEY - OpenCode Zen/OpenCode Go API key
KIMI_API_KEY - Kimi For Coding API key
META_API_KEY - Meta Model 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)

View File

@@ -1,5 +1,5 @@
import type { Api, CredentialInfo, Model } from "@earendil-works/pi-ai";
import { resolveCliModel } from "../core/model-resolver.ts";
import { resolveCliModel, resolveModelReference } 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";
@@ -41,12 +41,15 @@ export async function resolveCredentialForPrint(
providers.push({ id: provider.id });
}
} else {
const models = modelRuntime.getModels();
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 });
}
const resolved = resolveModelReference(
{ text: cliModel!, provider: provider.id, thinkingSuffix: "strict", fuzzy: true },
models,
() => true,
);
if (resolved.status === "resolved") 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.`);

View File

@@ -1,16 +0,0 @@
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);

View File

@@ -1,106 +0,0 @@
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`];
}

View File

@@ -1,225 +0,0 @@
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;
}
}

View File

@@ -1,91 +0,0 @@
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));

View File

@@ -1,66 +0,0 @@
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));

View File

@@ -17,7 +17,7 @@ export interface ProcessedFiles {
}
export interface ProcessFileOptions {
/** Whether to auto-resize images to 2000x2000 max. Default: true */
/** Whether to auto-resize images. Default: true */
autoResizeImages?: boolean;
}

View File

@@ -9,7 +9,7 @@ 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[]>;
type SessionsLoader = (onProgress?: SessionListProgress, signal?: AbortSignal) => Promise<SessionInfo[]>;
/** Show TUI session selector and return selected session path or null if cancelled */
export async function selectSession(

View File

@@ -17,17 +17,19 @@ import {
FirstTimeSetupComponent,
type FirstTimeSetupResult,
} from "../modes/interactive/components/first-time-setup.ts";
import { SYSTEM_THEME_NAME } from "../modes/interactive/theme/system-theme.ts";
import {
detectTerminalBackgroundFromEnv,
detectTerminalThemeForAuto,
getTerminalTheme,
initTheme,
loadThemeFromPath,
parseAutoThemeSetting,
markTerminalColorsPending,
resolveThemeSetting,
setRegisteredThemes,
setTerminalColors,
setTheme,
type Theme,
} from "../modes/interactive/theme/theme.ts";
import { requestTerminalColors } from "../modes/interactive/theme/theme-controller.ts";
const OFFICIAL_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
const OFFICIAL_APP_NAME = "pi";
@@ -83,8 +85,9 @@ async function loadStartupThemes(settingsManager: SettingsManager): Promise<Them
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);
// The system theme starts in grayscale until the terminal reports its colors.
markTerminalColorsPending();
initTheme(resolveThemeSetting(settingsManager.getThemeSetting(), getTerminalTheme()) ?? SYSTEM_THEME_NAME);
setKeybindings(KeybindingsManager.create());
const ui: TUI = new TuiMainScreen(new ProcessTerminal(), settingsManager.getShowHardwareCursor(), getAgentDir());
ui.setClearOnShrink(settingsManager.getClearOnShrink());
@@ -93,17 +96,23 @@ export async function createStartupTui(settingsManager: SettingsManager): Promis
export function startStartupTui(ui: TUI, settingsManager: SettingsManager): void {
ui.start();
void applyDetectedStartupTheme(ui, settingsManager);
const themeSetting = settingsManager.getThemeSetting();
queryStartupTerminalColors(ui, () => {
setTheme(resolveThemeSetting(themeSetting, getTerminalTheme()) ?? SYSTEM_THEME_NAME);
});
}
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();
/**
* Query the terminal's colors without waiting for them. When they arrive, including after the timeout,
* record them for the system theme and "" (terminal default) tokens, run `onColors`, and re-render.
*/
function queryStartupTerminalColors(ui: TUI, onColors: () => void): void {
void requestTerminalColors(ui, (colors) => {
setTerminalColors(colors);
onColors();
ui.invalidate();
ui.requestRender();
});
}
async function clearStartupTui(ui: TUI): Promise<void> {
@@ -189,25 +198,23 @@ export async function showFirstTimeSetup(settingsManager: SettingsManager): Prom
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();
ui.start();
let previewTheme = SYSTEM_THEME_NAME;
setTheme(previewTheme);
const component = new FirstTimeSetupComponent({
onThemePreview: (themeName) => {
previewTheme = themeName;
setTheme(themeName);
ui.requestRender();
},
onSubmit: (result) => void finish(result),
onCancel: () => void finish(undefined),
});
ui.addChild(component);
ui.setFocus(component);
ui.requestRender();
// The terminal's colors regenerate the system theme; re-rendering rebuilds the dialog with it.
queryStartupTerminalColors(ui, () => setTheme(previewTheme));
});
}