import { Logger, OpenExternal } from '@pwrdrvr/agent-core'; /** * Budget for a single ` --version` probe, in ms. * * Sized for the SLOWEST realistic launch path, not the fastest. Measured * against a real Codex 0.146.0 install on Windows: a native `codex.exe` * answers in ~0.3s, but npm's `codex.cmd` is a `cmd.exe -> node -> shim` * chain that needs ~1.5s WARM — and several times that cold, or on a loaded * machine. The previous hardcoded 2s sat right on top of that number. * * Overrunning is not a "slow" result, it is a WRONG one: the candidate comes * back without a version, and every version-gating consumer reads that as * "this tool is not installed". So the default buys headroom for the shim * chain rather than matching what a native binary needs; a host that wants a * snappier first paint can lower it and re-probe on its own budget. */ declare const DEFAULT_COMMAND_VERSION_TIMEOUT_MS = 10000; /** `CommandDiscoverySnapshot.error` when a caller's `AbortSignal` fired. */ declare const COMMAND_DISCOVERY_ABORTED = "discovery_aborted"; /** * Why a `--version` probe ended. The point of the enum is that `timed_out` is * NOT `not_found`: a probe that overran its budget says nothing about whether * the command exists, so a consumer can re-probe on a larger budget (or say * "could not verify") instead of reporting the tool as missing. */ type CommandVersionProbeOutcome = /** Ran and reported a parseable version. */ "ok" /** Ran, but nothing in stdout/stderr parsed as a version. */ | "version_not_reported" /** The command does not exist (ENOENT / ENOTDIR). */ | "not_found" /** The command exists but could not be executed (EACCES / EPERM). */ | "not_executable" /** The probe exceeded its budget. Says NOTHING about installedness. */ | "timed_out" /** The caller's `AbortSignal` fired. Says NOTHING about installedness. */ | "aborted" /** Ran and failed some other way (non-zero exit, spawn error, …). */ | "failed"; /** * True for the outcomes that carry NO evidence about the command: the probe * did not get to run to completion, so "no version" means "unknown", not * "absent". Callers should re-probe (or say "could not verify") rather than * treat these as a failed or missing tool. */ declare function isUnprovenVersionProbe(outcome: CommandVersionProbeOutcome | undefined): boolean; type CommandVersionProbeResult = { outcome: CommandVersionProbeOutcome; /** True only when the command actually executed to completion. */ ran: boolean; version?: string | undefined; /** Machine-readable reason string mirrored onto the discovery candidate. */ failureReason?: string | undefined; /** Budget this probe was given — echoed so a retrying caller knows what * already proved too small. Absent when no probe was spawned. */ timeoutMs?: number | undefined; }; type CommandDiscoveryCandidate = { command: string; source: Source; executable: boolean; selected: boolean; version?: string | undefined; versionFailureReason?: string | undefined; failureReason?: string | undefined; /** Outcome of this candidate's `--version` probe, when one was attempted. * `timed_out` / `aborted` mean the version is UNKNOWN, not absent — a * version-gating consumer should re-probe rather than demote the * candidate to "not installed". */ versionProbeOutcome?: CommandVersionProbeOutcome | undefined; }; type CommandDiscoverySnapshot = { selectedCommand?: string | undefined; selectedSource?: Source | undefined; candidates: Array>; /** `COMMAND_DISCOVERY_ABORTED` when the caller's signal fired; any * candidates already probed are still returned. */ error?: string | undefined; }; type CommandDiscoveryInput = { command: string | undefined; source: Source; }; type DiscoverCommandOptions = { fixedCandidates: Array>; autoCandidates: Array>; env: NodeJS.ProcessEnv; platform?: NodeJS.Platform | undefined; versionArgs?: string[] | undefined; parseVersion: (output: string) => string | undefined; compareVersions?: ((left?: string, right?: string) => number) | undefined; validateVersion?: ((version: string) => string | undefined) | undefined; preflightCandidate?: ((params: { command: string; source: Source; env: NodeJS.ProcessEnv; platform: NodeJS.Platform; signal?: AbortSignal | undefined; }) => Promise) | undefined; includeFailedAutoCandidates?: boolean | "if-none-executable" | undefined; /** Per-candidate `--version` budget. Defaults to * `DEFAULT_COMMAND_VERSION_TIMEOUT_MS`. */ versionTimeoutMs?: number | undefined; /** Abandon in-flight probes — discovery re-triggered while the previous run * is still going, or the app quitting mid-probe. Aborting yields a snapshot * with `error: COMMAND_DISCOVERY_ABORTED` rather than a rejection. */ signal?: AbortSignal | undefined; }; type CommandDiscoveryPreflightResult = { version?: string | undefined; failureReason?: string | undefined; versionFailureReason?: string | undefined; skipVersionProbe?: boolean | undefined; }; type ResolvedCommandCandidate = { command: string; source: Source; version?: string | undefined; /** Why the selected candidate's `--version` probe ended. A resolved command * with NO version and `versionProbeOutcome: "timed_out"` is a machine that * answered too slowly, not one missing the tool. */ versionProbeOutcome?: CommandVersionProbeOutcome | undefined; }; type PathIsExecutableOptions = { env?: NodeJS.ProcessEnv | undefined; platform?: NodeJS.Platform | undefined; }; /** * Is this path something the OS could actually launch? * * POSIX asks the filesystem (`X_OK`). Windows cannot: it has no execute bit, * so `access(X_OK)` degrades to `F_OK` and answers "true" for every file that * exists — a README included. There, startability is carried by the EXTENSION * instead, which is the same rule `CreateProcess` and `cmd.exe` apply, so we * check the name against PATHEXT and confirm existence separately. * * `options` is optional purely for back-compat with the original * `pathIsExecutable(path)` signature; without it the win32 branch falls back * to `process.env` and the default PATHEXT. */ declare function pathIsExecutable(candidate: string, options?: PathIsExecutableOptions): Promise; type ReadCommandVersionOptions = { command: string; env: NodeJS.ProcessEnv; platform?: NodeJS.Platform | undefined; parseVersion: (output: string) => string | undefined; /** Defaults to `["--version"]`. */ versionArgs?: string[] | undefined; /** Defaults to `DEFAULT_COMMAND_VERSION_TIMEOUT_MS`. Values below 1ms are * clamped up; the probe always settles within the budget. */ timeoutMs?: number | undefined; signal?: AbortSignal | undefined; }; /** * Run ` --version` and report BOTH the parsed version and why the * probe ended. Exported so a host can re-probe a candidate on its own budget * after discovery reported `timed_out`, without re-implementing the Windows * shim quoting in `createCommandInvocation`. * * The budget is authoritative: the probe resolves within `timeoutMs` even when * the child cannot be killed. That matters on Windows, where a `.cmd` shim runs * under `cmd.exe` and killing `cmd.exe` leaves the `node` grandchild holding * the stdio pipes open — `execFile`'s own `timeout` would then never surface a * result and discovery would hang forever instead of merely reporting slowly. */ declare function readCommandVersion(params: ReadCommandVersionOptions): Promise; declare function buildCommandDiscoveryCandidate(candidate: CommandDiscoveryInput, options: { env: NodeJS.ProcessEnv; platform?: NodeJS.Platform | undefined; versionArgs?: string[] | undefined; parseVersion: (output: string) => string | undefined; validateVersion?: ((version: string) => string | undefined) | undefined; preflightCandidate?: ((params: { command: string; source: Source; env: NodeJS.ProcessEnv; platform: NodeJS.Platform; signal?: AbortSignal | undefined; }) => Promise) | undefined; versionTimeoutMs?: number | undefined; signal?: AbortSignal | undefined; }): Promise | undefined>; declare function discoverCommands(options: DiscoverCommandOptions): Promise>; declare function resolveDiscoveredCommand(params: { command: string; fallbackSource: Source; discover: (configuredCommand?: string) => Promise>; }): Promise>; /** * Where a discovered Codex candidate came from. `env` = the * `PWRDRVR_CODEX_COMMAND` override; `config` = a host-persisted command path; * `path` = a bare PATH lookup; `application` = a well-known install location. */ type CodexCandidateSource = "env" | "config" | "path" | "application"; type CodexDiscoveryCandidate = CommandDiscoveryCandidate; type CodexDiscoverySnapshot = CommandDiscoverySnapshot; /** Where an auth-profile candidate came from on disk. */ type CodexAuthProfileSource = "default" | "directory" | "config"; type CodexAuthProfileCandidate = { name: string; displayName: string; codexHome: string; accountEmail?: string; source: CodexAuthProfileSource; exists: boolean; selected: boolean; hasAuthFile: boolean; hasConfigFile: boolean; }; type CodexAuthProfileDiscoverySnapshot = { profileRoot: string; effectiveCodexHome: string; profiles: CodexAuthProfileCandidate[]; error?: string; }; /** JWT-derived identity surfaced after a profile logs in. */ type CodexAuthInfo = { email?: string; planType?: string; }; type CodexAuthStatusRequest = { profile: string; }; /** How a `codex login status` probe ended. `timed_out` / `aborted` say the CLI * never answered — NOT that the profile is unauthenticated. */ type CodexStatusOutcome = "answered" | "timed_out" | "aborted" | "spawn_failed"; type CodexStatusResult = { /** Process exit code; `null` when the CLI never got to report one. */ code: number | null; detail: string; outcome: CodexStatusOutcome; }; type CodexAuthStatusResponse = { profile: string; codexHome: string; authenticated: boolean; status: "authenticated" | "unauthenticated" | "failed"; /** How the underlying `codex login status` probe ended. Only `answered` * makes `status` a verdict: `timed_out` and `aborted` both mean the * profile's real state is UNKNOWN, not that it is broken or signed out. */ outcome?: CodexStatusOutcome; detail?: string; /** ChatGPT account email extracted from the JWT in `auth.json`, when present. */ email?: string; /** ChatGPT plan type ("free", "plus", "pro", "team", "enterprise", …), * best-effort from the JWT's OpenAI-namespaced auth claim. */ planType?: string; }; type CodexProfileLoginResponse = { profile: string; codexHome: string; started: boolean; authenticated?: boolean; pid?: number; loginUrl?: string; detail?: string; }; /** Env var the host can set to force a specific Codex binary. */ declare const CODEX_COMMAND_ENV = "PWRDRVR_CODEX_COMMAND"; declare const MINIMUM_CODEX_CLI_VERSION = "0.125.0"; type ResolvedCodexCommandCandidate = { command: string; source: CodexCandidateSource; version?: string | undefined; }; declare function compareCodexCliVersions(left?: string, right?: string): number; /** * Well-known install locations for the Codex CLI, used as auto-candidates * alongside the PATH lookup. Platform-aware: macOS gets `ChatGPT.app` and * `Codex.app` resource bundles plus common Homebrew prefixes, Linux gets the * standard FHS dirs plus the common user-local Node/Rust/Bun toolchain * locations that aren't typically on an Electron-spawned process's PATH. * Note that this order does NOT decide which install wins: `discoverCommands` * ranks auto-candidates by version (newest first), so list order only breaks * ties between equal versions. Callers that must pin a specific binary should * use the `config` command or the `PWRDRVR_CODEX_COMMAND` env override, both * of which outrank every auto-candidate. */ declare function getCodexInstallCandidatePaths(platform: NodeJS.Platform, homeDir?: string): string[]; /** * Narrows or redirects the well-known install locations probed as * auto-candidates alongside the PATH lookup. Both fields are optional and * default to today's behavior, so existing callers are unaffected. */ type CodexInstallCandidateOptions = { /** * Install locations to probe, *replacing* (not extending) the platform * defaults. Defaults to `getCodexInstallCandidatePaths(platform, homeDir)`; * to extend instead, spread that helper's result into your own list. Pass * `[]` to probe nothing but PATH and the caller-supplied env/config * commands. * * Entries must be absolute paths. A bare name is resolved through `PATH` * like any other command, which reports it as an `application` candidate at * whatever path the lookup happened to find. */ installCandidatePaths?: readonly string[] | undefined; /** * Home directory used to expand the user-local entries of the default * candidate list. Defaults to `os.homedir()`. Ignored when * `installCandidatePaths` is supplied. */ homeDir?: string | undefined; }; type DiscoverCodexCommandsParams = { configuredCommand?: string | undefined; env?: NodeJS.ProcessEnv | undefined; platform?: NodeJS.Platform | undefined; /** Budget for each `codex --version` probe. Defaults to * `DEFAULT_COMMAND_VERSION_TIMEOUT_MS`. */ versionTimeoutMs?: number | undefined; /** Abandon in-flight probes (discovery re-triggered, app quitting). The * snapshot then carries `error: COMMAND_DISCOVERY_ABORTED`. */ signal?: AbortSignal | undefined; } & CodexInstallCandidateOptions; declare function discoverCodexCommands(params?: DiscoverCodexCommandsParams): Promise; /** * Thrown by `resolveCodexCommand` when discovery finds no executable * Codex CLI on this machine. Callers catch this to surface a clean * "Codex CLI not installed" state instead of attempting a spawn that * would `ENOENT`. Discovery already searched PATH plus whichever install * locations were in scope, so a `spawn("codex")` fallback would just repeat * the same lookup that already failed. Note that a caller which narrowed * `installCandidatePaths` narrowed that search too: this error then means * "not found where you told us to look", not "not installed". */ declare class CodexCliNotInstalledError extends Error { /** * Commands whose `--version` probe overran its budget instead of failing * outright. NON-EMPTY means "we could not tell", not "not installed": retry * on a larger `versionTimeoutMs` before telling anyone to install Codex. */ readonly timedOutCommands: string[]; constructor(message?: string, options?: { timedOutCommands?: string[] | undefined; }); /** True when a probe timeout — not a missing binary — is why nothing resolved. */ get probeTimedOut(): boolean; } /** * Thrown by `resolveCodexCommand` when the caller's `AbortSignal` fired mid- * discovery. Deliberately NOT a `CodexCliNotInstalledError`: an abandoned run * found nothing because it stopped looking, which is not evidence about what * is installed. */ declare class CodexDiscoveryAbortedError extends Error { constructor(message?: string); } declare function resolveCodexCommand(params: { command: string; env: NodeJS.ProcessEnv; platform?: NodeJS.Platform | undefined; /** Budget for each `codex --version` probe. Defaults to * `DEFAULT_COMMAND_VERSION_TIMEOUT_MS`. */ versionTimeoutMs?: number | undefined; signal?: AbortSignal | undefined; } & CodexInstallCandidateOptions): Promise>; declare const CODEX_HOME_ENV = "CODEX_HOME"; declare function resolveDefaultCodexHome(options?: { env?: NodeJS.ProcessEnv; homeDir?: string; }): string; declare function resolveCodexProfileRoot(options?: { env?: NodeJS.ProcessEnv; homeDir?: string; }): string; declare function resolveCodexHomeForProfile(profileName: string | undefined, options?: { env?: NodeJS.ProcessEnv; homeDir?: string; }): string | undefined; declare function createCodexAuthProfile(profileName: string, options?: { env?: NodeJS.ProcessEnv; homeDir?: string; }): { profile: string; codexHome: string; created: boolean; }; declare function discoverCodexAuthProfiles(options?: { configuredProfile?: string; env?: NodeJS.ProcessEnv; homeDir?: string; }): CodexAuthProfileDiscoverySnapshot; /** * Read the cached JWT from `auth.json` and pull out the operator-facing * identity fields. Returns `{}` if anything fails — we never want a * partially-parsed JWT to surface as a wrong email or plan label. */ declare function readCodexAuthInfo(codexHome: string): CodexAuthInfo; declare function normalizeProfileName(value: string): string; declare function isValidProfileName(value: string): boolean; declare function isCanonicalProfileName(value: string): boolean; /** * Budget for `codex login status`, in ms. Same reasoning as the discovery * version probe: the CLI may be an npm `.cmd` shim (`cmd.exe -> node -> shim`) * and this one also reads `auth.json` and can touch the network, so it is * sized for the slow path. Before this existed the spawn had NO budget — a * wedged child hung the caller forever. */ declare const DEFAULT_CODEX_STATUS_TIMEOUT_MS = 10000; type CollectCodexStatusOptions = { /** Defaults to `DEFAULT_CODEX_STATUS_TIMEOUT_MS`. */ timeoutMs?: number | undefined; /** Abandon the probe (app quitting, profile switched away). */ signal?: AbortSignal | undefined; }; /** * Spawn `codex login status` for a CODEX_HOME and report the raw exit code + * combined stdout/stderr. Exit 0 means authenticated. * * Never hangs: it settles within `timeoutMs`, and `outcome` says whether the * CLI actually answered so a caller does not read a slow machine as a signed- * out one. */ declare function collectCodexStatus(command: string, codexHome: string, options?: CollectCodexStatusOptions): Promise; /** * Resolve a profile's auth status, surfacing JWT-derived identity (email + * plan) when authenticated. `codexHome` is the resolved CODEX_HOME for the * profile (use `resolveCodexHomeForProfile` / `resolveDefaultCodexHome`). */ declare function checkCodexAuthStatus(params: { command: string; codexHome: string; profile: string; /** Budget for the `codex login status` spawn. Defaults to * `DEFAULT_CODEX_STATUS_TIMEOUT_MS`. */ timeoutMs?: number | undefined; signal?: AbortSignal | undefined; }): Promise; declare function parseCodexLoginPrompt(output: string): { loginUrl?: string; }; type CodexLoginManagerOptions = { logger?: Logger; /** Opens the scraped OAuth URL in the user's browser (host injects * Electron `shell.openExternal`). Defaults to a no-op so the flow never * imports Electron and stays testable. */ openExternal?: OpenExternal; /** How long to wait for the login prompt's OAuth URL before resolving with * `started: true` anyway. Defaults to 8s; tests set it small. */ loginUrlTimeoutMs?: number; /** Budget for the `codex login status` re-check run when a login child * exits. Defaults to `DEFAULT_CODEX_STATUS_TIMEOUT_MS`. */ statusTimeoutMs?: number; }; type StartCodexLoginParams = { codexHome: string; command: string; profile: string; }; /** * Tracks active `codex login` children keyed by profile so a re-login for a * profile kills the prior child first. The host constructs one of these (it * decides the lifetime + cleanup); `dispose()` kills every tracked child. */ declare class CodexLoginManager { private readonly logger; private readonly openExternal; private readonly loginUrlTimeoutMs; private readonly statusTimeoutMs; private readonly activeLoginProcesses; constructor(options?: CodexLoginManagerOptions); /** * Spawn `codex login` for a profile's CODEX_HOME, scrape the OAuth URL, * hand it to the injected `OpenExternal`, and resolve. If no URL surfaces * within ~8s the promise resolves anyway with `started: true` and whatever * detail was captured. On child close, re-checks status and resolves * authenticated if `codex login status` exits 0. */ startProfileLogin(params: StartCodexLoginParams): Promise; /** Kill every tracked login child. Call on host shutdown. */ dispose(): void; } /** * Convenience that mirrors PwrAgnt's module-level * `startCodexProfileLoginProcess`: a default manager keyed by profile across * calls. Pass `manager` to scope tracking to a host-owned instance instead. */ declare function startCodexProfileLoginProcess(params: StartCodexLoginParams, options?: CodexLoginManagerOptions & { manager?: CodexLoginManager; }): Promise; export { CODEX_COMMAND_ENV, CODEX_HOME_ENV, COMMAND_DISCOVERY_ABORTED, type CodexAuthInfo, type CodexAuthProfileCandidate, type CodexAuthProfileDiscoverySnapshot, type CodexAuthProfileSource, type CodexAuthStatusRequest, type CodexAuthStatusResponse, type CodexCandidateSource, CodexCliNotInstalledError, CodexDiscoveryAbortedError, type CodexDiscoveryCandidate, type CodexDiscoverySnapshot, type CodexInstallCandidateOptions, CodexLoginManager, type CodexLoginManagerOptions, type CodexProfileLoginResponse, type CodexStatusOutcome, type CodexStatusResult, type CollectCodexStatusOptions, type CommandDiscoveryCandidate, type CommandDiscoveryInput, type CommandDiscoveryPreflightResult, type CommandDiscoverySnapshot, type CommandVersionProbeOutcome, type CommandVersionProbeResult, DEFAULT_CODEX_STATUS_TIMEOUT_MS, DEFAULT_COMMAND_VERSION_TIMEOUT_MS, type DiscoverCodexCommandsParams, type DiscoverCommandOptions, MINIMUM_CODEX_CLI_VERSION, type PathIsExecutableOptions, type ReadCommandVersionOptions, type ResolvedCodexCommandCandidate, type ResolvedCommandCandidate, type StartCodexLoginParams, buildCommandDiscoveryCandidate, checkCodexAuthStatus, collectCodexStatus, compareCodexCliVersions, createCodexAuthProfile, discoverCodexAuthProfiles, discoverCodexCommands, discoverCommands, getCodexInstallCandidatePaths, isCanonicalProfileName, isUnprovenVersionProbe, isValidProfileName, normalizeProfileName, parseCodexLoginPrompt, pathIsExecutable, readCodexAuthInfo, readCommandVersion, resolveCodexCommand, resolveCodexHomeForProfile, resolveCodexProfileRoot, resolveDefaultCodexHome, resolveDiscoveredCommand, startCodexProfileLoginProcess };