refactor(coding-agent): replace AgentSessionRuntimeHost with closure-based AgentSessionRuntime
- Replace AgentSessionRuntimeHost and bootstrap abstractions with AgentSessionRuntime - Runtime creation is now closure-based via CreateAgentSessionRuntimeFactory - Factory closes over process-global fixed inputs, recreates cwd-bound services per effective cwd - Session config (model, thinking, tools, scoped models) re-resolved per target cwd - CLI resource paths resolved once at startup as absolute paths - Swap lifecycle: teardown old, create next, apply next (hard fail on creation error) - Unified diagnostics model (info/warning/error) for args, services, session resolution, resources - No logging or process exits inside creation/parsing logic - Removed session_directory support - Removed session_switch and session_fork extension events (use session_start with reason) - Moved package/config CLI to package-manager-cli.ts - Fixed theme init for --resume session picker - Fixed flaky reftable footer test (content-based polling) - Fixed silent drop of unknown single-dash CLI flags - Added error diagnostics for missing explicit CLI resource paths - Updated SDK docs, examples, plans, exports, tests, changelog fixes #2753
This commit is contained in:
@@ -9,27 +9,23 @@ import { resolve } from "node:path";
|
||||
import { type ImageContent, modelsAreEqual, supportsXhigh } from "@mariozechner/pi-ai";
|
||||
import chalk from "chalk";
|
||||
import { createInterface } from "readline";
|
||||
import { type Args, parseArgs, printHelp } from "./cli/args.js";
|
||||
import { selectConfig } from "./cli/config-selector.js";
|
||||
import { type Args, type Mode, parseArgs, printHelp } from "./cli/args.js";
|
||||
import { processFileArguments } from "./cli/file-processor.js";
|
||||
import { buildInitialMessage } from "./cli/initial-message.js";
|
||||
import { listModels } from "./cli/list-models.js";
|
||||
import { selectSession } from "./cli/session-picker.js";
|
||||
import { APP_NAME, getAgentDir, getModelsPath, VERSION } from "./config.js";
|
||||
import { getAgentDir, getModelsPath, VERSION } from "./config.js";
|
||||
import { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from "./core/agent-session-runtime.js";
|
||||
import {
|
||||
type AgentSessionRuntimeBootstrap,
|
||||
AgentSessionRuntimeHost,
|
||||
createAgentSessionRuntime,
|
||||
} from "./core/agent-session-runtime.js";
|
||||
type AgentSessionRuntimeDiagnostic,
|
||||
createAgentSessionFromServices,
|
||||
createAgentSessionServices,
|
||||
} from "./core/agent-session-services.js";
|
||||
import { AuthStorage } from "./core/auth-storage.js";
|
||||
import { exportFromFile } from "./core/export-html/index.js";
|
||||
import type { LoadExtensionsResult } from "./core/extensions/index.js";
|
||||
import { migrateKeybindingsConfigFile } from "./core/keybindings.js";
|
||||
import { ModelRegistry } from "./core/model-registry.js";
|
||||
import type { ModelRegistry } from "./core/model-registry.js";
|
||||
import { resolveCliModel, resolveModelScope, type ScopedModel } from "./core/model-resolver.js";
|
||||
import { restoreStdout, takeOverStdout } from "./core/output-guard.js";
|
||||
import { DefaultPackageManager } from "./core/package-manager.js";
|
||||
import { DefaultResourceLoader } from "./core/resource-loader.js";
|
||||
import type { CreateAgentSessionOptions } from "./core/sdk.js";
|
||||
import { SessionManager } from "./core/session-manager.js";
|
||||
import { SettingsManager } from "./core/settings-manager.js";
|
||||
@@ -38,6 +34,7 @@ import { allTools } from "./core/tools/index.js";
|
||||
import { runMigrations, showDeprecationWarnings } from "./migrations.js";
|
||||
import { InteractiveMode, runPrintMode, runRpcMode } from "./modes/index.js";
|
||||
import { initTheme, stopThemeWatcher } from "./modes/interactive/theme/theme.js";
|
||||
import { handleConfigCommand, handlePackageCommand } from "./package-manager-cli.js";
|
||||
|
||||
/**
|
||||
* Read all content from piped stdin.
|
||||
@@ -62,13 +59,21 @@ async function readPipedStdin(): Promise<string | undefined> {
|
||||
});
|
||||
}
|
||||
|
||||
function reportSettingsErrors(settingsManager: SettingsManager, context: string): void {
|
||||
const errors = settingsManager.drainErrors();
|
||||
for (const { scope, error } of errors) {
|
||||
console.error(chalk.yellow(`Warning (${context}, ${scope} settings): ${error.message}`));
|
||||
if (error.stack) {
|
||||
console.error(chalk.dim(error.stack));
|
||||
}
|
||||
function collectSettingsDiagnostics(
|
||||
settingsManager: SettingsManager,
|
||||
context: string,
|
||||
): AgentSessionRuntimeDiagnostic[] {
|
||||
return settingsManager.drainErrors().map(({ scope, error }) => ({
|
||||
type: "warning",
|
||||
message: `(${context}, ${scope} settings) ${error.message}`,
|
||||
}));
|
||||
}
|
||||
|
||||
function reportDiagnostics(diagnostics: readonly AgentSessionRuntimeDiagnostic[]): void {
|
||||
for (const diagnostic of diagnostics) {
|
||||
const color = diagnostic.type === "error" ? chalk.red : diagnostic.type === "warning" ? chalk.yellow : chalk.dim;
|
||||
const prefix = diagnostic.type === "error" ? "Error: " : diagnostic.type === "warning" ? "Warning: " : "";
|
||||
console.error(color(`${prefix}${diagnostic.message}`));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,243 +82,23 @@ function isTruthyEnvFlag(value: string | undefined): boolean {
|
||||
return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes";
|
||||
}
|
||||
|
||||
type PackageCommand = "install" | "remove" | "update" | "list";
|
||||
type AppMode = "interactive" | "print" | "json" | "rpc";
|
||||
|
||||
interface PackageCommandOptions {
|
||||
command: PackageCommand;
|
||||
source?: string;
|
||||
local: boolean;
|
||||
help: boolean;
|
||||
invalidOption?: string;
|
||||
function resolveAppMode(parsed: Args, stdinIsTTY: boolean): AppMode {
|
||||
if (parsed.mode === "rpc") {
|
||||
return "rpc";
|
||||
}
|
||||
if (parsed.mode === "json") {
|
||||
return "json";
|
||||
}
|
||||
if (parsed.print || !stdinIsTTY) {
|
||||
return "print";
|
||||
}
|
||||
return "interactive";
|
||||
}
|
||||
|
||||
function getPackageCommandUsage(command: PackageCommand): string {
|
||||
switch (command) {
|
||||
case "install":
|
||||
return `${APP_NAME} install <source> [-l]`;
|
||||
case "remove":
|
||||
return `${APP_NAME} remove <source> [-l]`;
|
||||
case "update":
|
||||
return `${APP_NAME} update [source]`;
|
||||
case "list":
|
||||
return `${APP_NAME} list`;
|
||||
}
|
||||
}
|
||||
|
||||
function printPackageCommandHelp(command: PackageCommand): void {
|
||||
switch (command) {
|
||||
case "install":
|
||||
console.log(`${chalk.bold("Usage:")}
|
||||
${getPackageCommandUsage("install")}
|
||||
|
||||
Install a package and add it to settings.
|
||||
|
||||
Options:
|
||||
-l, --local Install project-locally (.pi/settings.json)
|
||||
|
||||
Examples:
|
||||
${APP_NAME} install npm:@foo/bar
|
||||
${APP_NAME} install git:github.com/user/repo
|
||||
${APP_NAME} install git:git@github.com:user/repo
|
||||
${APP_NAME} install https://github.com/user/repo
|
||||
${APP_NAME} install ssh://git@github.com/user/repo
|
||||
${APP_NAME} install ./local/path
|
||||
`);
|
||||
return;
|
||||
|
||||
case "remove":
|
||||
console.log(`${chalk.bold("Usage:")}
|
||||
${getPackageCommandUsage("remove")}
|
||||
|
||||
Remove a package and its source from settings.
|
||||
Alias: ${APP_NAME} uninstall <source> [-l]
|
||||
|
||||
Options:
|
||||
-l, --local Remove from project settings (.pi/settings.json)
|
||||
|
||||
Examples:
|
||||
${APP_NAME} remove npm:@foo/bar
|
||||
${APP_NAME} uninstall npm:@foo/bar
|
||||
`);
|
||||
return;
|
||||
|
||||
case "update":
|
||||
console.log(`${chalk.bold("Usage:")}
|
||||
${getPackageCommandUsage("update")}
|
||||
|
||||
Update installed packages.
|
||||
If <source> is provided, only that package is updated.
|
||||
`);
|
||||
return;
|
||||
|
||||
case "list":
|
||||
console.log(`${chalk.bold("Usage:")}
|
||||
${getPackageCommandUsage("list")}
|
||||
|
||||
List installed packages from user and project settings.
|
||||
`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function parsePackageCommand(args: string[]): PackageCommandOptions | undefined {
|
||||
const [rawCommand, ...rest] = args;
|
||||
let command: PackageCommand | undefined;
|
||||
if (rawCommand === "uninstall") {
|
||||
command = "remove";
|
||||
} else if (rawCommand === "install" || rawCommand === "remove" || rawCommand === "update" || rawCommand === "list") {
|
||||
command = rawCommand;
|
||||
}
|
||||
if (!command) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let local = false;
|
||||
let help = false;
|
||||
let invalidOption: string | undefined;
|
||||
let source: string | undefined;
|
||||
|
||||
for (const arg of rest) {
|
||||
if (arg === "-h" || arg === "--help") {
|
||||
help = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "-l" || arg === "--local") {
|
||||
if (command === "install" || command === "remove") {
|
||||
local = true;
|
||||
} else {
|
||||
invalidOption = invalidOption ?? arg;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg.startsWith("-")) {
|
||||
invalidOption = invalidOption ?? arg;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!source) {
|
||||
source = arg;
|
||||
}
|
||||
}
|
||||
|
||||
return { command, source, local, help, invalidOption };
|
||||
}
|
||||
|
||||
async function handlePackageCommand(args: string[]): Promise<boolean> {
|
||||
const options = parsePackageCommand(args);
|
||||
if (!options) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.help) {
|
||||
printPackageCommandHelp(options.command);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (options.invalidOption) {
|
||||
console.error(chalk.red(`Unknown option ${options.invalidOption} for "${options.command}".`));
|
||||
console.error(chalk.dim(`Use "${APP_NAME} --help" or "${getPackageCommandUsage(options.command)}".`));
|
||||
process.exitCode = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
const source = options.source;
|
||||
if ((options.command === "install" || options.command === "remove") && !source) {
|
||||
console.error(chalk.red(`Missing ${options.command} source.`));
|
||||
console.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));
|
||||
process.exitCode = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
const cwd = process.cwd();
|
||||
const agentDir = getAgentDir();
|
||||
const settingsManager = SettingsManager.create(cwd, agentDir);
|
||||
reportSettingsErrors(settingsManager, "package command");
|
||||
const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
|
||||
|
||||
packageManager.setProgressCallback((event) => {
|
||||
if (event.type === "start") {
|
||||
process.stdout.write(chalk.dim(`${event.message}\n`));
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
switch (options.command) {
|
||||
case "install":
|
||||
await packageManager.install(source!, { local: options.local });
|
||||
packageManager.addSourceToSettings(source!, { local: options.local });
|
||||
console.log(chalk.green(`Installed ${source}`));
|
||||
return true;
|
||||
|
||||
case "remove": {
|
||||
await packageManager.remove(source!, { local: options.local });
|
||||
const removed = packageManager.removeSourceFromSettings(source!, { local: options.local });
|
||||
if (!removed) {
|
||||
console.error(chalk.red(`No matching package found for ${source}`));
|
||||
process.exitCode = 1;
|
||||
return true;
|
||||
}
|
||||
console.log(chalk.green(`Removed ${source}`));
|
||||
return true;
|
||||
}
|
||||
|
||||
case "list": {
|
||||
const globalSettings = settingsManager.getGlobalSettings();
|
||||
const projectSettings = settingsManager.getProjectSettings();
|
||||
const globalPackages = globalSettings.packages ?? [];
|
||||
const projectPackages = projectSettings.packages ?? [];
|
||||
|
||||
if (globalPackages.length === 0 && projectPackages.length === 0) {
|
||||
console.log(chalk.dim("No packages installed."));
|
||||
return true;
|
||||
}
|
||||
|
||||
const formatPackage = (pkg: (typeof globalPackages)[number], scope: "user" | "project") => {
|
||||
const source = typeof pkg === "string" ? pkg : pkg.source;
|
||||
const filtered = typeof pkg === "object";
|
||||
const display = filtered ? `${source} (filtered)` : source;
|
||||
console.log(` ${display}`);
|
||||
const path = packageManager.getInstalledPath(source, scope);
|
||||
if (path) {
|
||||
console.log(chalk.dim(` ${path}`));
|
||||
}
|
||||
};
|
||||
|
||||
if (globalPackages.length > 0) {
|
||||
console.log(chalk.bold("User packages:"));
|
||||
for (const pkg of globalPackages) {
|
||||
formatPackage(pkg, "user");
|
||||
}
|
||||
}
|
||||
|
||||
if (projectPackages.length > 0) {
|
||||
if (globalPackages.length > 0) console.log();
|
||||
console.log(chalk.bold("Project packages:"));
|
||||
for (const pkg of projectPackages) {
|
||||
formatPackage(pkg, "project");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
case "update":
|
||||
await packageManager.update(source);
|
||||
if (source) {
|
||||
console.log(chalk.green(`Updated ${source}`));
|
||||
} else {
|
||||
console.log(chalk.green("Updated packages"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown package command error";
|
||||
console.error(chalk.red(`Error: ${message}`));
|
||||
process.exitCode = 1;
|
||||
return true;
|
||||
}
|
||||
function toPrintOutputMode(appMode: AppMode): Exclude<Mode, "rpc"> {
|
||||
return appMode === "json" ? "json" : "text";
|
||||
}
|
||||
|
||||
async function prepareInitialMessage(
|
||||
@@ -389,32 +174,6 @@ async function promptConfirm(message: string): Promise<boolean> {
|
||||
});
|
||||
}
|
||||
|
||||
/** Helper to call CLI-only session_directory handlers before the initial session manager is created */
|
||||
async function callSessionDirectoryHook(extensions: LoadExtensionsResult, cwd: string): Promise<string | undefined> {
|
||||
let customSessionDir: string | undefined;
|
||||
|
||||
for (const ext of extensions.extensions) {
|
||||
const handlers = ext.handlers.get("session_directory");
|
||||
if (!handlers || handlers.length === 0) continue;
|
||||
|
||||
for (const handler of handlers) {
|
||||
try {
|
||||
const event = { type: "session_directory" as const, cwd };
|
||||
const result = (await handler(event)) as { sessionDir?: string } | undefined;
|
||||
|
||||
if (result?.sessionDir) {
|
||||
customSessionDir = result.sessionDir;
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(chalk.red(`Extension "${ext.path}" session_directory handler failed: ${message}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return customSessionDir;
|
||||
}
|
||||
|
||||
function validateForkFlags(parsed: Args): void {
|
||||
if (!parsed.fork) return;
|
||||
|
||||
@@ -444,25 +203,21 @@ function forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string)
|
||||
async function createSessionManager(
|
||||
parsed: Args,
|
||||
cwd: string,
|
||||
extensions: LoadExtensionsResult,
|
||||
sessionDir: string | undefined,
|
||||
settingsManager: SettingsManager,
|
||||
): Promise<SessionManager | undefined> {
|
||||
): Promise<SessionManager> {
|
||||
if (parsed.noSession) {
|
||||
return SessionManager.inMemory();
|
||||
}
|
||||
|
||||
// Priority: CLI flag > settings.json > extension hook
|
||||
const effectiveSessionDir =
|
||||
parsed.sessionDir ?? settingsManager.getSessionDir() ?? (await callSessionDirectoryHook(extensions, cwd));
|
||||
|
||||
if (parsed.fork) {
|
||||
const resolved = await resolveSessionPath(parsed.fork, cwd, effectiveSessionDir);
|
||||
const resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir);
|
||||
|
||||
switch (resolved.type) {
|
||||
case "path":
|
||||
case "local":
|
||||
case "global":
|
||||
return forkSessionOrExit(resolved.path, cwd, effectiveSessionDir);
|
||||
return forkSessionOrExit(resolved.path, cwd, sessionDir);
|
||||
|
||||
case "not_found":
|
||||
console.error(chalk.red(`No session found matching '${resolved.arg}'`));
|
||||
@@ -471,22 +226,21 @@ async function createSessionManager(
|
||||
}
|
||||
|
||||
if (parsed.session) {
|
||||
const resolved = await resolveSessionPath(parsed.session, cwd, effectiveSessionDir);
|
||||
const resolved = await resolveSessionPath(parsed.session, cwd, sessionDir);
|
||||
|
||||
switch (resolved.type) {
|
||||
case "path":
|
||||
case "local":
|
||||
return SessionManager.open(resolved.path, effectiveSessionDir);
|
||||
return SessionManager.open(resolved.path, sessionDir);
|
||||
|
||||
case "global": {
|
||||
// Session found in different project - ask user if they want to fork
|
||||
console.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));
|
||||
const shouldFork = await promptConfirm("Fork this session into current directory?");
|
||||
if (!shouldFork) {
|
||||
console.log(chalk.dim("Aborted."));
|
||||
process.exit(0);
|
||||
}
|
||||
return forkSessionOrExit(resolved.path, cwd, effectiveSessionDir);
|
||||
return forkSessionOrExit(resolved.path, cwd, sessionDir);
|
||||
}
|
||||
|
||||
case "not_found":
|
||||
@@ -494,32 +248,46 @@ async function createSessionManager(
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (parsed.resume) {
|
||||
initTheme(settingsManager.getTheme(), true);
|
||||
try {
|
||||
const selectedPath = await selectSession(
|
||||
(onProgress) => SessionManager.list(cwd, sessionDir, onProgress),
|
||||
SessionManager.listAll,
|
||||
);
|
||||
if (!selectedPath) {
|
||||
console.log(chalk.dim("No session selected"));
|
||||
process.exit(0);
|
||||
}
|
||||
return SessionManager.open(selectedPath, sessionDir);
|
||||
} finally {
|
||||
stopThemeWatcher();
|
||||
}
|
||||
}
|
||||
|
||||
if (parsed.continue) {
|
||||
return SessionManager.continueRecent(cwd, effectiveSessionDir);
|
||||
return SessionManager.continueRecent(cwd, sessionDir);
|
||||
}
|
||||
// --resume is handled separately (needs picker UI)
|
||||
// If effective session dir is set, create new session there
|
||||
if (effectiveSessionDir) {
|
||||
return SessionManager.create(cwd, effectiveSessionDir);
|
||||
}
|
||||
// Default case (new session) returns undefined, SDK will create one
|
||||
return undefined;
|
||||
|
||||
return SessionManager.create(cwd, sessionDir);
|
||||
}
|
||||
|
||||
function buildSessionOptions(
|
||||
parsed: Args,
|
||||
scopedModels: ScopedModel[],
|
||||
sessionManager: SessionManager | undefined,
|
||||
hasExistingSession: boolean,
|
||||
modelRegistry: ModelRegistry,
|
||||
settingsManager: SettingsManager,
|
||||
): { options: CreateAgentSessionOptions; cliThinkingFromModel: boolean } {
|
||||
): {
|
||||
options: CreateAgentSessionOptions;
|
||||
cliThinkingFromModel: boolean;
|
||||
diagnostics: AgentSessionRuntimeDiagnostic[];
|
||||
} {
|
||||
const options: CreateAgentSessionOptions = {};
|
||||
const diagnostics: AgentSessionRuntimeDiagnostic[] = [];
|
||||
let cliThinkingFromModel = false;
|
||||
|
||||
if (sessionManager) {
|
||||
options.sessionManager = sessionManager;
|
||||
}
|
||||
|
||||
// Model from CLI
|
||||
// - supports --provider <name> --model <pattern>
|
||||
// - supports --model <provider>/<pattern>
|
||||
@@ -530,11 +298,10 @@ function buildSessionOptions(
|
||||
modelRegistry,
|
||||
});
|
||||
if (resolved.warning) {
|
||||
console.warn(chalk.yellow(`Warning: ${resolved.warning}`));
|
||||
diagnostics.push({ type: "warning", message: resolved.warning });
|
||||
}
|
||||
if (resolved.error) {
|
||||
console.error(chalk.red(resolved.error));
|
||||
process.exit(1);
|
||||
diagnostics.push({ type: "error", message: resolved.error });
|
||||
}
|
||||
if (resolved.model) {
|
||||
options.model = resolved.model;
|
||||
@@ -547,7 +314,7 @@ function buildSessionOptions(
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.model && scopedModels.length > 0 && !parsed.continue && !parsed.resume) {
|
||||
if (!options.model && scopedModels.length > 0 && !hasExistingSession) {
|
||||
// Check if saved default is in scoped models - use it if so, otherwise first scoped model
|
||||
const savedProvider = settingsManager.getDefaultProvider();
|
||||
const savedModelId = settingsManager.getDefaultModel();
|
||||
@@ -600,66 +367,13 @@ function buildSessionOptions(
|
||||
options.tools = parsed.tools.map((name) => allTools[name]);
|
||||
}
|
||||
|
||||
return { options, cliThinkingFromModel };
|
||||
return { options, cliThinkingFromModel, diagnostics };
|
||||
}
|
||||
|
||||
function resolveCliPaths(cwd: string, paths: string[] | undefined): string[] | undefined {
|
||||
return paths?.map((value) => resolve(cwd, value));
|
||||
}
|
||||
|
||||
function buildRuntimeBootstrap(
|
||||
parsed: Args,
|
||||
cwd: string,
|
||||
agentDir: string,
|
||||
authStorage: AuthStorage,
|
||||
sessionOptions: CreateAgentSessionOptions,
|
||||
): AgentSessionRuntimeBootstrap {
|
||||
return {
|
||||
agentDir,
|
||||
authStorage,
|
||||
model: sessionOptions.model,
|
||||
thinkingLevel: sessionOptions.thinkingLevel,
|
||||
scopedModels: sessionOptions.scopedModels,
|
||||
tools: sessionOptions.tools,
|
||||
customTools: sessionOptions.customTools,
|
||||
resourceLoader: {
|
||||
additionalExtensionPaths: resolveCliPaths(cwd, parsed.extensions),
|
||||
additionalSkillPaths: resolveCliPaths(cwd, parsed.skills),
|
||||
additionalPromptTemplatePaths: resolveCliPaths(cwd, parsed.promptTemplates),
|
||||
additionalThemePaths: resolveCliPaths(cwd, parsed.themes),
|
||||
noExtensions: parsed.noExtensions,
|
||||
noSkills: parsed.noSkills,
|
||||
noPromptTemplates: parsed.noPromptTemplates,
|
||||
noThemes: parsed.noThemes,
|
||||
systemPrompt: parsed.systemPrompt,
|
||||
appendSystemPrompt: parsed.appendSystemPrompt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function handleConfigCommand(args: string[]): Promise<boolean> {
|
||||
if (args[0] !== "config") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cwd = process.cwd();
|
||||
const agentDir = getAgentDir();
|
||||
const settingsManager = SettingsManager.create(cwd, agentDir);
|
||||
reportSettingsErrors(settingsManager, "config command");
|
||||
const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
|
||||
|
||||
const resolvedPaths = await packageManager.resolve();
|
||||
|
||||
await selectConfig({
|
||||
resolvedPaths,
|
||||
settingsManager,
|
||||
cwd,
|
||||
agentDir,
|
||||
});
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
export async function main(args: string[]) {
|
||||
resetTimings();
|
||||
const offlineMode = args.includes("--offline") || isTruthyEnvFlag(process.env.PI_OFFLINE);
|
||||
@@ -676,105 +390,28 @@ export async function main(args: string[]) {
|
||||
return;
|
||||
}
|
||||
|
||||
// First pass: parse args to get --extension paths
|
||||
const firstPass = parseArgs(args);
|
||||
time("parseArgs.firstPass");
|
||||
const shouldTakeOverStdout = firstPass.mode !== undefined || firstPass.print || !process.stdin.isTTY;
|
||||
const parsed = parseArgs(args);
|
||||
if (parsed.diagnostics.length > 0) {
|
||||
for (const d of parsed.diagnostics) {
|
||||
const color = d.type === "error" ? chalk.red : chalk.yellow;
|
||||
console.error(color(`${d.type === "error" ? "Error" : "Warning"}: ${d.message}`));
|
||||
}
|
||||
if (parsed.diagnostics.some((d) => d.type === "error")) {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
time("parseArgs");
|
||||
let appMode = resolveAppMode(parsed, process.stdin.isTTY);
|
||||
const shouldTakeOverStdout = appMode !== "interactive";
|
||||
if (shouldTakeOverStdout) {
|
||||
takeOverStdout();
|
||||
}
|
||||
|
||||
// Run migrations (pass cwd for project-local migrations)
|
||||
const { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(process.cwd());
|
||||
time("runMigrations");
|
||||
|
||||
// Early load extensions to discover their CLI flags
|
||||
const cwd = process.cwd();
|
||||
const agentDir = getAgentDir();
|
||||
const settingsManager = SettingsManager.create(cwd, agentDir);
|
||||
reportSettingsErrors(settingsManager, "startup");
|
||||
const authStorage = AuthStorage.create();
|
||||
const modelRegistry = ModelRegistry.create(authStorage, getModelsPath());
|
||||
|
||||
const resourceLoader = new DefaultResourceLoader({
|
||||
cwd,
|
||||
agentDir,
|
||||
settingsManager,
|
||||
additionalExtensionPaths: firstPass.extensions,
|
||||
additionalSkillPaths: firstPass.skills,
|
||||
additionalPromptTemplatePaths: firstPass.promptTemplates,
|
||||
additionalThemePaths: firstPass.themes,
|
||||
noExtensions: firstPass.noExtensions,
|
||||
noSkills: firstPass.noSkills,
|
||||
noPromptTemplates: firstPass.noPromptTemplates,
|
||||
noThemes: firstPass.noThemes,
|
||||
systemPrompt: firstPass.systemPrompt,
|
||||
appendSystemPrompt: firstPass.appendSystemPrompt,
|
||||
});
|
||||
time("createResourceLoader");
|
||||
await resourceLoader.reload();
|
||||
time("resourceLoader.reload");
|
||||
|
||||
const extensionsResult: LoadExtensionsResult = resourceLoader.getExtensions();
|
||||
for (const { path, error } of extensionsResult.errors) {
|
||||
console.error(chalk.red(`Failed to load extension "${path}": ${error}`));
|
||||
}
|
||||
|
||||
// Apply pending provider registrations from extensions immediately
|
||||
// so they're available for model resolution before AgentSession is created
|
||||
for (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {
|
||||
try {
|
||||
modelRegistry.registerProvider(name, config);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(chalk.red(`Extension "${extensionPath}" error: ${message}`));
|
||||
}
|
||||
}
|
||||
extensionsResult.runtime.pendingProviderRegistrations = [];
|
||||
|
||||
const extensionFlags = new Map<string, { type: "boolean" | "string" }>();
|
||||
for (const ext of extensionsResult.extensions) {
|
||||
for (const [name, flag] of ext.flags) {
|
||||
extensionFlags.set(name, { type: flag.type });
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: parse args with extension flags
|
||||
const parsed = parseArgs(args, extensionFlags);
|
||||
time("parseArgs.secondPass");
|
||||
|
||||
// Pass flag values to extensions via runtime
|
||||
for (const [name, value] of parsed.unknownFlags) {
|
||||
extensionsResult.runtime.flagValues.set(name, value);
|
||||
}
|
||||
|
||||
if (parsed.version) {
|
||||
console.log(VERSION);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (parsed.help) {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (parsed.listModels !== undefined) {
|
||||
const searchPattern = typeof parsed.listModels === "string" ? parsed.listModels : undefined;
|
||||
await listModels(modelRegistry, searchPattern);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Read piped stdin content (if any) - skip for RPC mode which uses stdin for JSON-RPC
|
||||
let stdinContent: string | undefined;
|
||||
if (parsed.mode !== "rpc") {
|
||||
stdinContent = await readPipedStdin();
|
||||
if (stdinContent !== undefined) {
|
||||
// Force print mode since interactive mode requires a TTY for keyboard input
|
||||
parsed.print = true;
|
||||
}
|
||||
}
|
||||
time("readPipedStdin");
|
||||
|
||||
if (parsed.export) {
|
||||
let result: string;
|
||||
try {
|
||||
@@ -789,9 +426,6 @@ export async function main(args: string[]) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
migrateKeybindingsConfigFile(agentDir);
|
||||
time("migrateKeybindingsConfigFile");
|
||||
|
||||
if (parsed.mode === "rpc" && parsed.fileArgs.length > 0) {
|
||||
console.error(chalk.red("Error: @file arguments are not supported in RPC mode"));
|
||||
process.exit(1);
|
||||
@@ -799,90 +433,179 @@ export async function main(args: string[]) {
|
||||
|
||||
validateForkFlags(parsed);
|
||||
|
||||
// Run migrations (pass cwd for project-local migrations)
|
||||
const { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(process.cwd());
|
||||
time("runMigrations");
|
||||
|
||||
const cwd = process.cwd();
|
||||
const agentDir = getAgentDir();
|
||||
const startupSettingsManager = SettingsManager.create(cwd, agentDir);
|
||||
reportDiagnostics(collectSettingsDiagnostics(startupSettingsManager, "startup session lookup"));
|
||||
|
||||
// Decide the final runtime cwd before creating cwd-bound runtime services.
|
||||
// --session and --resume may select a session from another project, so project-local
|
||||
// settings, resources, provider registrations, and models must be resolved only after
|
||||
// the target session cwd is known. The startup-cwd settings manager is used only for
|
||||
// sessionDir lookup during session selection.
|
||||
const sessionManager = await createSessionManager(
|
||||
parsed,
|
||||
cwd,
|
||||
parsed.sessionDir ?? startupSettingsManager.getSessionDir(),
|
||||
startupSettingsManager,
|
||||
);
|
||||
time("createSessionManager");
|
||||
|
||||
const resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions);
|
||||
const resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);
|
||||
const resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);
|
||||
const resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);
|
||||
const authStorage = AuthStorage.create();
|
||||
const createRuntime: CreateAgentSessionRuntimeFactory = async ({
|
||||
cwd,
|
||||
agentDir,
|
||||
sessionManager,
|
||||
sessionStartEvent,
|
||||
}) => {
|
||||
const services = await createAgentSessionServices({
|
||||
cwd,
|
||||
agentDir,
|
||||
authStorage,
|
||||
extensionFlagValues: parsed.unknownFlags,
|
||||
resourceLoaderOptions: {
|
||||
additionalExtensionPaths: resolvedExtensionPaths,
|
||||
additionalSkillPaths: resolvedSkillPaths,
|
||||
additionalPromptTemplatePaths: resolvedPromptTemplatePaths,
|
||||
additionalThemePaths: resolvedThemePaths,
|
||||
noExtensions: parsed.noExtensions,
|
||||
noSkills: parsed.noSkills,
|
||||
noPromptTemplates: parsed.noPromptTemplates,
|
||||
noThemes: parsed.noThemes,
|
||||
systemPrompt: parsed.systemPrompt,
|
||||
appendSystemPrompt: parsed.appendSystemPrompt,
|
||||
},
|
||||
});
|
||||
const { settingsManager, modelRegistry, resourceLoader } = services;
|
||||
const diagnostics: AgentSessionRuntimeDiagnostic[] = [
|
||||
...services.diagnostics,
|
||||
...collectSettingsDiagnostics(settingsManager, "runtime creation"),
|
||||
...resourceLoader.getExtensions().errors.map(({ path, error }) => ({
|
||||
type: "error" as const,
|
||||
message: `Failed to load extension "${path}": ${error}`,
|
||||
})),
|
||||
];
|
||||
|
||||
const modelPatterns = parsed.models ?? settingsManager.getEnabledModels();
|
||||
const scopedModels =
|
||||
modelPatterns && modelPatterns.length > 0 ? await resolveModelScope(modelPatterns, modelRegistry) : [];
|
||||
const {
|
||||
options: sessionOptions,
|
||||
cliThinkingFromModel,
|
||||
diagnostics: sessionOptionDiagnostics,
|
||||
} = buildSessionOptions(
|
||||
parsed,
|
||||
scopedModels,
|
||||
sessionManager.buildSessionContext().messages.length > 0,
|
||||
modelRegistry,
|
||||
settingsManager,
|
||||
);
|
||||
diagnostics.push(...sessionOptionDiagnostics);
|
||||
|
||||
if (parsed.apiKey) {
|
||||
if (!sessionOptions.model) {
|
||||
diagnostics.push({
|
||||
type: "error",
|
||||
message: "--api-key requires a model to be specified via --model, --provider/--model, or --models",
|
||||
});
|
||||
} else {
|
||||
authStorage.setRuntimeApiKey(sessionOptions.model.provider, parsed.apiKey);
|
||||
}
|
||||
}
|
||||
|
||||
const created = await createAgentSessionFromServices({
|
||||
services,
|
||||
sessionManager,
|
||||
sessionStartEvent,
|
||||
model: sessionOptions.model,
|
||||
thinkingLevel: sessionOptions.thinkingLevel,
|
||||
scopedModels: sessionOptions.scopedModels,
|
||||
tools: sessionOptions.tools,
|
||||
customTools: sessionOptions.customTools,
|
||||
});
|
||||
const cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel;
|
||||
if (created.session.model && cliThinkingOverride) {
|
||||
let effectiveThinking = created.session.thinkingLevel;
|
||||
if (!created.session.model.reasoning) {
|
||||
effectiveThinking = "off";
|
||||
} else if (effectiveThinking === "xhigh" && !supportsXhigh(created.session.model)) {
|
||||
effectiveThinking = "high";
|
||||
}
|
||||
if (effectiveThinking !== created.session.thinkingLevel) {
|
||||
created.session.setThinkingLevel(effectiveThinking);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...created,
|
||||
services,
|
||||
diagnostics,
|
||||
};
|
||||
};
|
||||
time("createRuntime");
|
||||
const runtime = await createAgentSessionRuntime(createRuntime, {
|
||||
cwd: sessionManager.getCwd(),
|
||||
agentDir,
|
||||
sessionManager,
|
||||
});
|
||||
const { services, session, modelFallbackMessage } = runtime;
|
||||
const { settingsManager, modelRegistry, resourceLoader } = services;
|
||||
|
||||
if (parsed.help) {
|
||||
const extensionFlags = resourceLoader
|
||||
.getExtensions()
|
||||
.extensions.flatMap((extension) => Array.from(extension.flags.values()));
|
||||
printHelp(extensionFlags);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (parsed.listModels !== undefined) {
|
||||
const searchPattern = typeof parsed.listModels === "string" ? parsed.listModels : undefined;
|
||||
await listModels(modelRegistry, searchPattern);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Read piped stdin content (if any) - skip for RPC mode which uses stdin for JSON-RPC
|
||||
let stdinContent: string | undefined;
|
||||
if (appMode !== "rpc") {
|
||||
stdinContent = await readPipedStdin();
|
||||
if (stdinContent !== undefined) {
|
||||
appMode = "print";
|
||||
}
|
||||
}
|
||||
time("readPipedStdin");
|
||||
|
||||
const { initialMessage, initialImages } = await prepareInitialMessage(
|
||||
parsed,
|
||||
settingsManager.getImageAutoResize(),
|
||||
stdinContent,
|
||||
);
|
||||
time("prepareInitialMessage");
|
||||
const isInteractive = !parsed.print && parsed.mode === undefined;
|
||||
const startupBenchmark = isTruthyEnvFlag(process.env.PI_STARTUP_BENCHMARK);
|
||||
if (startupBenchmark && !isInteractive) {
|
||||
console.error(chalk.red("Error: PI_STARTUP_BENCHMARK only supports interactive mode"));
|
||||
process.exit(1);
|
||||
}
|
||||
const mode = parsed.mode || "text";
|
||||
initTheme(settingsManager.getTheme(), isInteractive);
|
||||
initTheme(settingsManager.getTheme(), appMode === "interactive");
|
||||
time("initTheme");
|
||||
|
||||
// Show deprecation warnings in interactive mode
|
||||
if (isInteractive && deprecationWarnings.length > 0) {
|
||||
if (appMode === "interactive" && deprecationWarnings.length > 0) {
|
||||
await showDeprecationWarnings(deprecationWarnings);
|
||||
}
|
||||
|
||||
let scopedModels: ScopedModel[] = [];
|
||||
const modelPatterns = parsed.models ?? settingsManager.getEnabledModels();
|
||||
if (modelPatterns && modelPatterns.length > 0) {
|
||||
scopedModels = await resolveModelScope(modelPatterns, modelRegistry);
|
||||
}
|
||||
const scopedModels = [...session.scopedModels];
|
||||
time("resolveModelScope");
|
||||
|
||||
// Create session manager based on CLI flags
|
||||
let sessionManager = await createSessionManager(parsed, cwd, extensionsResult, settingsManager);
|
||||
time("createSessionManager");
|
||||
|
||||
// Handle --resume: show session picker
|
||||
if (parsed.resume) {
|
||||
// Compute effective session dir for resume (same logic as createSessionManager)
|
||||
const effectiveSessionDir =
|
||||
parsed.sessionDir ??
|
||||
settingsManager.getSessionDir() ??
|
||||
(await callSessionDirectoryHook(extensionsResult, cwd));
|
||||
|
||||
const selectedPath = await selectSession(
|
||||
(onProgress) => SessionManager.list(cwd, effectiveSessionDir, onProgress),
|
||||
SessionManager.listAll,
|
||||
);
|
||||
if (!selectedPath) {
|
||||
console.log(chalk.dim("No session selected"));
|
||||
stopThemeWatcher();
|
||||
process.exit(0);
|
||||
}
|
||||
sessionManager = SessionManager.open(selectedPath, effectiveSessionDir);
|
||||
reportDiagnostics(runtime.diagnostics);
|
||||
if (runtime.diagnostics.some((diagnostic) => diagnostic.type === "error")) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { options: sessionOptions, cliThinkingFromModel } = buildSessionOptions(
|
||||
parsed,
|
||||
scopedModels,
|
||||
sessionManager,
|
||||
modelRegistry,
|
||||
settingsManager,
|
||||
);
|
||||
|
||||
if (parsed.apiKey) {
|
||||
if (!sessionOptions.model) {
|
||||
console.error(
|
||||
chalk.red("--api-key requires a model to be specified via --model, --provider/--model, or --models"),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
authStorage.setRuntimeApiKey(sessionOptions.model.provider, parsed.apiKey);
|
||||
}
|
||||
|
||||
const runtimeBootstrap = buildRuntimeBootstrap(parsed, cwd, agentDir, authStorage, sessionOptions);
|
||||
const runtime = await createAgentSessionRuntime(runtimeBootstrap, {
|
||||
cwd: sessionManager?.getCwd() ?? cwd,
|
||||
sessionManager,
|
||||
resourceLoader,
|
||||
});
|
||||
if (process.cwd() !== runtime.cwd) {
|
||||
process.chdir(runtime.cwd);
|
||||
}
|
||||
const runtimeHost = new AgentSessionRuntimeHost(runtimeBootstrap, runtime);
|
||||
const { session, modelFallbackMessage } = runtime;
|
||||
time("createAgentSession");
|
||||
|
||||
if (!isInteractive && !session.model) {
|
||||
if (appMode !== "interactive" && !session.model) {
|
||||
console.error(chalk.red("No models available."));
|
||||
console.error(chalk.yellow("\nSet an API key environment variable:"));
|
||||
console.error(" ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, etc.");
|
||||
@@ -890,25 +613,16 @@ export async function main(args: string[]) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Clamp thinking level to model capabilities for CLI-provided thinking levels.
|
||||
// This covers both --thinking <level> and --model <pattern>:<thinking>.
|
||||
const cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel;
|
||||
if (session.model && cliThinkingOverride) {
|
||||
let effectiveThinking = session.thinkingLevel;
|
||||
if (!session.model.reasoning) {
|
||||
effectiveThinking = "off";
|
||||
} else if (effectiveThinking === "xhigh" && !supportsXhigh(session.model)) {
|
||||
effectiveThinking = "high";
|
||||
}
|
||||
if (effectiveThinking !== session.thinkingLevel) {
|
||||
session.setThinkingLevel(effectiveThinking);
|
||||
}
|
||||
const startupBenchmark = isTruthyEnvFlag(process.env.PI_STARTUP_BENCHMARK);
|
||||
if (startupBenchmark && appMode !== "interactive") {
|
||||
console.error(chalk.red("Error: PI_STARTUP_BENCHMARK only supports interactive mode"));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (mode === "rpc") {
|
||||
if (appMode === "rpc") {
|
||||
printTimings();
|
||||
await runRpcMode(runtimeHost);
|
||||
} else if (isInteractive) {
|
||||
await runRpcMode(runtime);
|
||||
} else if (appMode === "interactive") {
|
||||
if (scopedModels.length > 0 && (parsed.verbose || !settingsManager.getQuietStartup())) {
|
||||
const modelList = scopedModels
|
||||
.map((sm) => {
|
||||
@@ -919,7 +633,7 @@ export async function main(args: string[]) {
|
||||
console.log(chalk.dim(`Model scope: ${modelList} ${chalk.gray("(Ctrl+P to cycle)")}`));
|
||||
}
|
||||
|
||||
const interactiveMode = new InteractiveMode(runtimeHost, {
|
||||
const interactiveMode = new InteractiveMode(runtime, {
|
||||
migratedProviders,
|
||||
modelFallbackMessage,
|
||||
initialMessage,
|
||||
@@ -946,8 +660,8 @@ export async function main(args: string[]) {
|
||||
await interactiveMode.run();
|
||||
} else {
|
||||
printTimings();
|
||||
const exitCode = await runPrintMode(runtimeHost, {
|
||||
mode,
|
||||
const exitCode = await runPrintMode(runtime, {
|
||||
mode: toPrintOutputMode(appMode),
|
||||
messages: parsed.messages,
|
||||
initialMessage,
|
||||
initialImages,
|
||||
|
||||
Reference in New Issue
Block a user