Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

sync prime auth with prime cli (#322)

ktcad81d9b682c
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index c940a17243..9d61d1d2f1 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,8 @@
## [Unreleased]
+- Fixed Prime Inference auth syncing with Prime CLI login and team selection.
+- Fixed provider auth failures showing provider-specific `/login` commands instead of the `/login` selector.
- Removed the legacy pi-mono `bash` and `edit` built-in tools; use IPython `%%bash` cells and the Python `edit` skill instead.
## [0.2.5] - 2026-07-06
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index ce9ae7bd74..2196f98029 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -64,7 +64,13 @@ import {
ORCHESTRATION_HEARTBEAT_SKILL_NAME,
} from "./agent-observe.js";
import { flushAgentTraceUpload } from "./agent-traces.js";
-import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
+import {
+ addLoginGuidanceToAuthError,
+ formatAuthenticationFailedMessage,
+ formatNoApiKeyFoundMessage,
+ formatNoModelSelectedMessage,
+ isLikelyAuthenticationError,
+} from "./auth-guidance.js";
import { type BashResult, executeBashWithOperations } from "./bash-executor.js";
import {
type CompactionResult,
@@ -743,11 +749,7 @@ export class AgentSession {
const isOAuth = this._modelRegistry.isUsingOAuth(model);
if (isOAuth) {
- throw new Error(
- `Authentication failed for "${model.provider}". ` +
- `Credentials may have expired or network is unavailable. ` +
- `Run '/login ${model.provider}' to re-authenticate.`,
- );
+ throw new Error(formatAuthenticationFailedMessage(model.provider));
}
throw new Error(formatNoApiKeyFoundMessage(model.provider));
}
@@ -1081,11 +1083,7 @@ export class AgentSession {
if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
if (isOAuth) {
- throw new Error(
- `Authentication failed for "${this.model.provider}". ` +
- `Credentials may have expired or network is unavailable. ` +
- `Run '/login ${this.model.provider}' to re-authenticate.`,
- );
+ throw new Error(formatAuthenticationFailedMessage(this.model.provider));
}
throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
}
@@ -1615,6 +1613,22 @@ export class AgentSession {
return undefined;
}
+ private _addLoginGuidanceToAuthError(event: AgentEvent): void {
+ const message =
+ event.type === "message_end" && event.message.role === "assistant"
+ ? (event.message as AssistantMessage)
+ : event.type === "agent_end"
+ ? this._findLastAssistantInMessages(event.messages)
+ : undefined;
+ if (!message || message.stopReason !== "error" || !message.errorMessage) {
+ return;
+ }
+ if (!isLikelyAuthenticationError(message.errorMessage)) {
+ return;
+ }
+ message.errorMessage = addLoginGuidanceToAuthError(message.errorMessage);
+ }
+
private async _processAgentEvent(event: AgentEvent): Promise<void> {
const acceptedPrompt = this._acceptedAgentMessagePrompt;
if (acceptedPrompt && (event.type === "message_start" || event.type === "message_end")) {
@@ -1684,6 +1698,8 @@ export class AgentSession {
return;
}
+ this._addLoginGuidanceToAuthError(event);
+
// Notify all listeners
this._emit(event);
@@ -2349,11 +2365,7 @@ export class AgentSession {
if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
if (isOAuth) {
- throw new Error(
- `Authentication failed for "${this.model.provider}". ` +
- `Credentials may have expired or network is unavailable. ` +
- `Run '/login ${this.model.provider}' to re-authenticate.`,
- );
+ throw new Error(formatAuthenticationFailedMessage(this.model.provider));
}
throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
}
diff --git a/packages/coding-agent/src/core/auth-guidance.ts b/packages/coding-agent/src/core/auth-guidance.ts
index 9919bc3cd0..47fa6fd388 100644
--- a/packages/coding-agent/src/core/auth-guidance.ts
+++ b/packages/coding-agent/src/core/auth-guidance.ts
@@ -2,6 +2,7 @@ import { join } from "node:path";
import { getDocsPath } from "../config.js";
const UNKNOWN_PROVIDER = "unknown";
+const LOGIN_RECOVERY_MESSAGE = "Run /login to update credentials.";
export function getProviderLoginHelp(): string {
return [
@@ -35,3 +36,26 @@ export function formatNoApiKeyFoundMessage(provider: string): string {
const providerDisplay = provider === UNKNOWN_PROVIDER ? "the selected model" : provider;
return `No API key found for ${providerDisplay}.\n\n${getProviderLoginHelp()}`;
}
+
+export function formatAuthenticationFailedMessage(provider: string): string {
+ return (
+ `Authentication failed for "${provider}". Credentials may have expired or network is unavailable.\n\n` +
+ LOGIN_RECOVERY_MESSAGE
+ );
+}
+
+export function isLikelyAuthenticationError(message: string): boolean {
+ return (
+ /\b(401|403)\b/i.test(message) ||
+ /unauthorized|forbidden|invalid[_ -]?api[_ -]?key|api key.*invalid/i.test(message) ||
+ /authentication failed|invalid authentication|missing authentication/i.test(message) ||
+ /(expired|invalid) token|token expired|access denied|permission denied/i.test(message)
+ );
+}
+
+export function addLoginGuidanceToAuthError(message: string): string {
+ if (/\/login\b/.test(message)) {
+ return message;
+ }
+ return `${message}\n\n${LOGIN_RECOVERY_MESSAGE}`;
+}
diff --git a/packages/coding-agent/src/core/auth-storage.ts b/packages/coding-agent/src/core/auth-storage.ts
index ccceb3ad83..618170ec15 100644
--- a/packages/coding-agent/src/core/auth-storage.ts
+++ b/packages/coding-agent/src/core/auth-storage.ts
@@ -19,10 +19,14 @@ import { dirname, join } from "path";
import lockfile from "proper-lockfile";
import { getAgentDir } from "../config.js";
import {
+ clearPrimeCliCredentials,
+ getPrimeCliConfigPath,
loadPrimeCliConfig,
PRIME_INFERENCE_PROVIDER_ID,
type PrimeCliConfig,
type PrimeTeam,
+ savePrimeCliApiKey,
+ savePrimeCliTeamSelection,
} from "./prime-inference-auth.js";
import { resolveConfigValue } from "./resolve-config-value.js";
@@ -214,8 +218,6 @@ export class AuthStorage {
private fallbackResolver?: (provider: string) => string | undefined;
private loadError: Error | null = null;
private errors: Error[] = [];
- private primeCliConfigCache: PrimeCliConfig | undefined;
- private primeCliConfigCacheLoaded = false;
private constructor(
private storage: AuthStorageBackend,
@@ -278,8 +280,6 @@ export class AuthStorage {
* Reload credentials from storage.
*/
reload(): void {
- this.primeCliConfigCache = undefined;
- this.primeCliConfigCacheLoaded = false;
let content: string | undefined;
try {
this.storage.withLock((current) => {
@@ -358,9 +358,15 @@ export class AuthStorage {
*/
hasAuth(provider: string): boolean {
if (this.runtimeOverrides.has(provider)) return true;
+ if (provider === PRIME_INFERENCE_PROVIDER_ID) {
+ if (this.getPrimeCliApiKey(provider)) return true;
+ if (this.data[provider]) return true;
+ if (getEnvApiKey(provider)) return true;
+ if (this.fallbackResolver?.(provider)) return true;
+ return false;
+ }
if (this.data[provider]) return true;
if (getEnvApiKey(provider)) return true;
- if (this.getPrimeCliApiKey(provider)) return true;
if (this.fallbackResolver?.(provider)) return true;
return false;
}
@@ -369,6 +375,10 @@ export class AuthStorage {
* Return auth status without exposing credential values or refreshing tokens.
*/
getAuthStatus(provider: string): AuthStatus {
+ if (provider === PRIME_INFERENCE_PROVIDER_ID) {
+ return this.getPrimeInferenceAuthStatus();
+ }
+
if (this.data[provider]) {
return { configured: true, source: "stored" };
}
@@ -382,10 +392,6 @@ export class AuthStorage {
return { configured: false, source: "environment", label: envKeys[0] };
}
- if (this.getPrimeCliApiKey(provider)) {
- return { configured: false, source: "prime_cli", label: "Prime CLI" };
- }
-
if (this.fallbackResolver?.(provider)) {
return { configured: false, source: "fallback", label: "custom provider config" };
}
@@ -423,6 +429,14 @@ export class AuthStorage {
* Logout from a provider.
*/
logout(provider: string): void {
+ if (provider === PRIME_INFERENCE_PROVIDER_ID && this.isPrimeCliConfigEnabled()) {
+ try {
+ clearPrimeCliCredentials(this.getEnabledPrimeCliConfigPath());
+ } catch (error) {
+ this.recordError(error);
+ throw error;
+ }
+ }
this.remove(provider);
}
@@ -492,6 +506,11 @@ export class AuthStorage {
return runtimeKey;
}
+ if (providerId === PRIME_INFERENCE_PROVIDER_ID) {
+ const primeCliKey = this.getPrimeCliApiKey(providerId);
+ if (primeCliKey) return primeCliKey;
+ }
+
const cred = this.data[providerId];
if (cred?.type === "api_key") {
@@ -559,6 +578,16 @@ export class AuthStorage {
}
setPrimeInferenceTeamSelection(team: PrimeTeam | null): void {
+ if (this.isPrimeCliConfigEnabled()) {
+ try {
+ savePrimeCliTeamSelection(team, this.getEnabledPrimeCliConfigPath());
+ } catch (error) {
+ this.recordError(error);
+ throw error;
+ }
+ return;
+ }
+
const credential = this.data[PRIME_INFERENCE_PROVIDER_ID];
if (credential?.type !== "api_key") {
return;
@@ -569,9 +598,75 @@ export class AuthStorage {
});
}
+ setPrimeInferenceApiKey(apiKey: string): void {
+ if (this.isPrimeCliConfigEnabled()) {
+ try {
+ const configPath = this.getEnabledPrimeCliConfigPath();
+ const config = loadPrimeCliConfig(configPath);
+ const existingCredential = this.data[PRIME_INFERENCE_PROVIDER_ID];
+ const legacyPrimeTeam = existingCredential?.type === "api_key" ? existingCredential.primeTeam : undefined;
+ if (config.apiKey !== apiKey) {
+ savePrimeCliApiKey(apiKey, configPath);
+ } else if (!config.teamIdFromEnv && (legacyPrimeTeam === null || (!config.teamId && legacyPrimeTeam))) {
+ savePrimeCliTeamSelection(legacyPrimeTeam, configPath);
+ }
+ } catch (error) {
+ this.recordError(error);
+ throw error;
+ }
+ if (this.data[PRIME_INFERENCE_PROVIDER_ID]) {
+ this.remove(PRIME_INFERENCE_PROVIDER_ID);
+ }
+ return;
+ }
+
+ const existingCredential = this.data[PRIME_INFERENCE_PROVIDER_ID];
+ const existingPrimeTeam = existingCredential?.type === "api_key" ? existingCredential.primeTeam : undefined;
+ this.set(PRIME_INFERENCE_PROVIDER_ID, {
+ type: "api_key",
+ key: apiKey,
+ ...(existingPrimeTeam !== undefined ? { primeTeam: existingPrimeTeam } : {}),
+ });
+ }
+
getPrimeInferenceTeamSelection(): PrimeTeamCredential | null | undefined {
+ let config: PrimeCliConfig | undefined;
+ if (this.isPrimeCliConfigEnabled()) {
+ config = this.getPrimeCliConfig(PRIME_INFERENCE_PROVIDER_ID);
+ if (config?.teamIdFromEnv) {
+ return undefined;
+ }
+ const credential = this.data[PRIME_INFERENCE_PROVIDER_ID];
+ if (config?.apiKey) {
+ if (credential?.type === "api_key" && credential.primeTeam === null) {
+ return null;
+ }
+ if (config.teamId) {
+ return this.toPrimeTeamCredential({
+ teamId: config.teamId,
+ name: config.teamName ?? "Prime CLI team",
+ ...(config.teamRole ? { role: config.teamRole } : {}),
+ });
+ }
+ if (credential?.type === "api_key" && credential.primeTeam) {
+ return credential.primeTeam;
+ }
+ return null;
+ }
+ }
+
const credential = this.data[PRIME_INFERENCE_PROVIDER_ID];
- return credential?.type === "api_key" ? credential.primeTeam : undefined;
+ if (credential?.type === "api_key" && credential.primeTeam !== undefined) {
+ return credential.primeTeam;
+ }
+ if (config?.teamId) {
+ return this.toPrimeTeamCredential({
+ teamId: config.teamId,
+ name: config.teamName ?? "Prime CLI team",
+ ...(config.teamRole ? { role: config.teamRole } : {}),
+ });
+ }
+ return undefined;
}
getProviderHeaders(providerId: string): Record<string, string> | undefined {
@@ -585,6 +680,18 @@ export class AuthStorage {
}
const credential = this.data[providerId];
+ if (primeCliConfig?.apiKey) {
+ if (credential?.type === "api_key" && credential.primeTeam === null) {
+ return undefined;
+ }
+ if (primeCliConfig.teamId) {
+ return { "X-Prime-Team-ID": primeCliConfig.teamId };
+ }
+ return credential?.type === "api_key" && credential.primeTeam?.teamId
+ ? { "X-Prime-Team-ID": credential.primeTeam.teamId }
+ : undefined;
+ }
+
if (credential?.type === "api_key") {
if (credential.primeTeam === null) {
return undefined;
@@ -599,6 +706,13 @@ export class AuthStorage {
return teamId ? { "X-Prime-Team-ID": teamId } : undefined;
}
+ getPrimeCliConfigPath(): string | undefined {
+ if (!this.isPrimeCliConfigEnabled()) {
+ return undefined;
+ }
+ return getPrimeCliConfigPath(this.options.primeCliConfigPath);
+ }
+
private toPrimeTeamCredential(team: PrimeTeam): PrimeTeamCredential {
const credential: PrimeTeamCredential = {
teamId: team.teamId,
@@ -620,17 +734,50 @@ export class AuthStorage {
if (providerId !== PRIME_INFERENCE_PROVIDER_ID) {
return undefined;
}
- if (!this.options.usePrimeCliConfig && !this.options.primeCliConfigPath) {
+ if (!this.isPrimeCliConfigEnabled()) {
return undefined;
}
- if (!this.primeCliConfigCacheLoaded) {
- this.primeCliConfigCache = loadPrimeCliConfig(this.options.primeCliConfigPath);
- this.primeCliConfigCacheLoaded = true;
- }
- return this.primeCliConfigCache;
+ return loadPrimeCliConfig(this.options.primeCliConfigPath);
}
private getPrimeCliApiKey(providerId: string): string | undefined {
return this.getPrimeCliConfig(providerId)?.apiKey;
}
+
+ private getEnabledPrimeCliConfigPath(): string {
+ const configPath = this.getPrimeCliConfigPath();
+ if (!configPath) {
+ throw new Error("Prime CLI config is not enabled");
+ }
+ return configPath;
+ }
+
+ private getPrimeInferenceAuthStatus(): AuthStatus {
+ if (this.runtimeOverrides.has(PRIME_INFERENCE_PROVIDER_ID)) {
+ return { configured: false, source: "runtime", label: "--api-key" };
+ }
+
+ if (this.getPrimeCliApiKey(PRIME_INFERENCE_PROVIDER_ID)) {
+ return { configured: false, source: "prime_cli", label: "Prime CLI" };
+ }
+
+ if (this.data[PRIME_INFERENCE_PROVIDER_ID]) {
+ return { configured: true, source: "stored" };
+ }
+
+ const envKeys = findEnvKeys(PRIME_INFERENCE_PROVIDER_ID);
+ if (envKeys?.[0]) {
+ return { configured: false, source: "environment", label: envKeys[0] };
+ }
+
+ if (this.fallbackResolver?.(PRIME_INFERENCE_PROVIDER_ID)) {
+ return { configured: false, source: "fallback", label: "custom provider config" };
+ }
+
+ return { configured: false };
+ }
+
+ private isPrimeCliConfigEnabled(): boolean {
+ return Boolean(this.options.usePrimeCliConfig || this.options.primeCliConfigPath);
+ }
}
diff --git a/packages/coding-agent/src/core/prime-inference-auth.ts b/packages/coding-agent/src/core/prime-inference-auth.ts
index 9082d053fa..3331ae3605 100644
--- a/packages/coding-agent/src/core/prime-inference-auth.ts
+++ b/packages/coding-agent/src/core/prime-inference-auth.ts
@@ -1,8 +1,18 @@
import { Buffer } from "node:buffer";
import { constants, generateKeyPairSync, privateDecrypt } from "node:crypto";
-import { existsSync, readFileSync } from "node:fs";
+import {
+ chmodSync,
+ closeSync,
+ existsSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { basename, dirname, join } from "node:path";
import type { OAuthAuthInfo } from "@earendil-works/pi-ai";
export const PRIME_INFERENCE_PROVIDER_ID = "prime-inference";
@@ -80,6 +90,10 @@ function defaultPrimeCliConfigPath(): string {
return join(homedir(), ".prime", "config.json");
}
+export function getPrimeCliConfigPath(configPath?: string): string {
+ return configPath ?? defaultPrimeCliConfigPath();
+}
+
function normalizeBaseUrl(value: string | undefined): string {
return (value?.trim() || DEFAULT_PRIME_API_BASE_URL).replace(/\/+$/, "").replace(/\/api\/v1$/, "");
}
@@ -122,6 +136,39 @@ function readPrimeCliConfigData(configPath: string): Record<string, unknown> {
return data;
}
+function writePrimeCliConfigData(configPath: string, data: Record<string, unknown>): void {
+ const dir = dirname(configPath);
+ if (!existsSync(dir)) {
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ }
+ const tempPath = join(
+ dir,
+ `.${basename(configPath)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`,
+ );
+ let fd: number | undefined = openSync(tempPath, "wx", 0o600);
+ try {
+ writeFileSync(fd, `${JSON.stringify(data, null, 2)}\n`, "utf-8");
+ closeSync(fd);
+ fd = undefined;
+ chmodSync(tempPath, 0o600);
+ renameSync(tempPath, configPath);
+ chmodSync(configPath, 0o600);
+ } finally {
+ if (fd !== undefined) {
+ closeSync(fd);
+ }
+ if (existsSync(tempPath)) {
+ rmSync(tempPath, { force: true });
+ }
+ }
+}
+
+function clearPrimeTeamFields(data: Record<string, unknown>): void {
+ delete data.team_id;
+ delete data.team_name;
+ delete data.team_role;
+}
+
export function loadPrimeCliConfig(configPath: string = defaultPrimeCliConfigPath()): PrimeCliConfig {
const data = readPrimeCliConfigData(configPath);
const teamIdFromEnv = stringEnv("PRIME_TEAM_ID");
@@ -154,6 +201,42 @@ export function loadPrimeCliConfig(configPath: string = defaultPrimeCliConfigPat
return config;
}
+export function savePrimeCliApiKey(apiKey: string, configPath: string = defaultPrimeCliConfigPath()): PrimeCliConfig {
+ const data = readPrimeCliConfigData(configPath);
+ data.api_key = apiKey;
+ clearPrimeTeamFields(data);
+ writePrimeCliConfigData(configPath, data);
+ return loadPrimeCliConfig(configPath);
+}
+
+export function clearPrimeCliCredentials(configPath: string = defaultPrimeCliConfigPath()): PrimeCliConfig {
+ const data = readPrimeCliConfigData(configPath);
+ delete data.api_key;
+ clearPrimeTeamFields(data);
+ writePrimeCliConfigData(configPath, data);
+ return loadPrimeCliConfig(configPath);
+}
+
+export function savePrimeCliTeamSelection(
+ team: PrimeTeam | null,
+ configPath: string = defaultPrimeCliConfigPath(),
+): PrimeCliConfig {
+ const data = readPrimeCliConfigData(configPath);
+ if (team) {
+ data.team_id = team.teamId;
+ data.team_name = team.name;
+ if (team.role) {
+ data.team_role = team.role;
+ } else {
+ delete data.team_role;
+ }
+ } else {
+ clearPrimeTeamFields(data);
+ }
+ writePrimeCliConfigData(configPath, data);
+ return loadPrimeCliConfig(configPath);
+}
+
export function resolvePrimeAgentTracesBaseUrl(baseUrl?: string): string {
return normalizeBaseUrl(baseUrl ?? stringEnv("PRIME_AGENT_TRACES_BASE_URL"));
}
diff --git a/packages/coding-agent/src/modes/interactive/auth-flows.ts b/packages/coding-agent/src/modes/interactive/auth-flows.ts
index 8a5c464d59..cda0c15edc 100644
--- a/packages/coding-agent/src/modes/interactive/auth-flows.ts
+++ b/packages/coding-agent/src/modes/interactive/auth-flows.ts
@@ -294,6 +294,17 @@ export class ProviderAuthFlows {
});
}
+ if (!options.some((option) => option.id === PRIME_INFERENCE_PROVIDER_ID)) {
+ const primeInferenceStatus = authStorage.getAuthStatus(PRIME_INFERENCE_PROVIDER_ID);
+ if (primeInferenceStatus.source === "prime_cli") {
+ options.push({
+ id: PRIME_INFERENCE_PROVIDER_ID,
+ name: PRIME_INFERENCE_PROVIDER_NAME,
+ authType: "api_key",
+ });
+ }
+ }
+
return options.sort((a, b) => a.name.localeCompare(b.name));
}
@@ -303,13 +314,14 @@ export class ProviderAuthFlows {
authType: "oauth" | "api_key",
statusSuffix?: string,
kind: "provider" | "service" = "provider",
+ credentialPath: string = getAuthPath(),
): Promise<AuthenticationResult> {
this.host.modelRegistry.refresh();
const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;
await this.host.onAuthChanged?.();
this.host.showStatus(
- `${actionLabel}. Credentials saved to ${getAuthPath()}${statusSuffix ? `. ${statusSuffix}` : ""}`,
+ `${actionLabel}. Credentials saved to ${credentialPath}${statusSuffix ? `. ${statusSuffix}` : ""}`,
);
this.host.onLoginCompleted?.();
return {
@@ -409,6 +421,24 @@ export class ProviderAuthFlows {
}
private getPrimeInferenceDefaultTeamStatus(): string {
+ const configPath = this.host.modelRegistry.authStorage.getPrimeCliConfigPath();
+ if (configPath) {
+ let config: ReturnType<typeof loadPrimeCliConfig>;
+ try {
+ config = loadPrimeCliConfig(configPath);
+ } catch {
+ return "Using personal account.";
+ }
+ if (config.teamIdFromEnv) {
+ return "Using team from PRIME_TEAM_ID.";
+ }
+ if (config.teamName) {
+ return `Using team "${config.teamName}".`;
+ }
+ if (config.teamId) {
+ return "Using Prime CLI team.";
+ }
+ }
const storedTeam = this.host.modelRegistry.authStorage.getPrimeInferenceTeamSelection();
if (storedTeam) {
return `Using team "${storedTeam.name}".`;
@@ -416,27 +446,12 @@ export class ProviderAuthFlows {
if (storedTeam === null) {
return "Using personal account.";
}
- let config: ReturnType<typeof loadPrimeCliConfig>;
- try {
- config = loadPrimeCliConfig();
- } catch {
- return "Using personal account.";
- }
- if (config.teamIdFromEnv) {
- return "Using team from PRIME_TEAM_ID.";
- }
- if (config.teamName) {
- return `Using team "${config.teamName}".`;
- }
- if (config.teamId) {
- return "Using Prime CLI team.";
- }
return "Using personal account.";
}
private async selectPrimeInferenceTeam(apiKey: string, dialog: LoginDialogComponent): Promise<string | undefined> {
try {
- const config = loadPrimeCliConfig();
+ const config = loadPrimeCliConfig(this.host.modelRegistry.authStorage.getPrimeCliConfigPath());
if (config.teamIdFromEnv) {
this.host.modelRegistry.authStorage.reload();
return "Using team from PRIME_TEAM_ID.";
@@ -474,14 +489,7 @@ export class ProviderAuthFlows {
dialog: LoginDialogComponent,
closeDialog: () => void,
): Promise<AuthenticationResult> {
- const previousPrimeCredential = this.host.modelRegistry.authStorage.get(PRIME_INFERENCE_PROVIDER_ID);
- const previousPrimeTeam =
- previousPrimeCredential?.type === "api_key" ? previousPrimeCredential.primeTeam : undefined;
- this.host.modelRegistry.authStorage.set(PRIME_INFERENCE_PROVIDER_ID, {
- type: "api_key",
- key: apiKey,
- ...(previousPrimeTeam !== undefined ? { primeTeam: previousPrimeTeam } : {}),
- });
+ this.host.modelRegistry.authStorage.setPrimeInferenceApiKey(apiKey);
const teamStatus = await this.selectPrimeInferenceTeam(apiKey, dialog);
closeDialog();
@@ -490,6 +498,8 @@ export class ProviderAuthFlows {
PRIME_INFERENCE_PROVIDER_NAME,
"api_key",
teamStatus,
+ "provider",
+ this.host.modelRegistry.authStorage.getPrimeCliConfigPath() ?? getAuthPath(),
);
}
@@ -549,16 +559,21 @@ export class ProviderAuthFlows {
};
try {
- const browserLogin = loginPrimeInference({
- onAuth: (info) => {
- dialog.showAuth(info.url, info.instructions);
- armManualInput("Complete the sign-in in your browser, or paste an API key below:");
+ const browserLogin = loginPrimeInference(
+ {
+ onAuth: (info) => {
+ dialog.showAuth(info.url, info.instructions);
+ armManualInput("Complete the sign-in in your browser, or paste an API key below:");
+ },
+ onProgress: (message) => {
+ dialog.showProgress(message);
+ },
+ signal: browserAbort.signal,
},
- onProgress: (message) => {
- dialog.showProgress(message);
+ {
+ configPath: this.host.modelRegistry.authStorage.getPrimeCliConfigPath(),
},
- signal: browserAbort.signal,
- });
+ );
// When the browser challenge cannot start or breaks down, keep the dialog
// open and fall back to plain API key entry instead of failing outright.
const browserLoginOrFallback = browserLogin.catch((error: unknown) => {
@@ -592,7 +607,7 @@ export class ProviderAuthFlows {
if (result.source === "manual") {
browserAbort.abort();
dialog.showProgress("Checking Prime Inference access...");
- const config = loadPrimeCliConfig();
+ const config = loadPrimeCliConfig(this.host.modelRegistry.authStorage.getPrimeCliConfigPath());
const access = await checkPrimeInferenceAccess(result.apiKey, config.baseUrl, { signal: dialog.signal });
if (dialog.signal.aborted) {
closeDialog();
diff --git a/packages/coding-agent/test/agent-session-auto-compaction-queue.test.ts b/packages/coding-agent/test/agent-session-auto-compaction-queue.test.ts
index 8f37e3a36b..d8d491d45c 100644
--- a/packages/coding-agent/test/agent-session-auto-compaction-queue.test.ts
+++ b/packages/coding-agent/test/agent-session-auto-compaction-queue.test.ts
@@ -237,7 +237,7 @@ describe("AgentSession auto-compaction queue resume", () => {
it("should trigger threshold compaction for error messages using last successful usage", async () => {
const model = session.model!;
- const highUsageTokens = model.contextWindow;
+ const totalTokens = model.contextWindow - 16_384 + 1;
// A successful assistant message with high token usage (near context limit)
const successfulAssistant: AssistantMessage = {
@@ -247,11 +247,11 @@ describe("AgentSession auto-compaction queue resume", () => {
provider: model.provider,
model: model.id,
usage: {
- input: highUsageTokens,
- output: 0,
+ input: totalTokens - 10_000,
+ output: 10_000,
cacheRead: 0,
cacheWrite: 0,
- totalTokens: highUsageTokens,
+ totalTokens,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
stopReason: "stop",
diff --git a/packages/coding-agent/test/auth-flows.test.ts b/packages/coding-agent/test/auth-flows.test.ts
new file mode 100644
index 0000000000..8460f671dc
--- /dev/null
+++ b/packages/coding-agent/test/auth-flows.test.ts
@@ -0,0 +1,208 @@
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { Component, OverlayHandle, TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { AuthStorage } from "../src/core/auth-storage.js";
+import type { ModelRegistry } from "../src/core/model-registry.js";
+import { PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.js";
+import { ProviderAuthFlows, type ProviderAuthFlowsHost } from "../src/modes/interactive/auth-flows.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+function jsonResponse(body: unknown, status: number = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+}
+
+function createOverlayHandle(): OverlayHandle {
+ return {
+ hide: vi.fn(),
+ setHidden: vi.fn(),
+ isHidden: () => false,
+ focus: vi.fn(),
+ unfocus: vi.fn(),
+ isFocused: () => true,
+ };
+}
+
+function createFakeTui(overlays: Component[] = []): TUI {
+ return {
+ terminal: { columns: 80, rows: 24 },
+ requestRender: vi.fn(),
+ showOverlay: vi.fn((component: Component) => {
+ overlays.push(component);
+ return createOverlayHandle();
+ }),
+ } as unknown as TUI;
+}
+
+function createHost(authStorage: AuthStorage): {
+ host: ProviderAuthFlowsHost;
+ statusMessages: string[];
+ errorMessages: string[];
+ overlays: Component[];
+} {
+ const statusMessages: string[] = [];
+ const errorMessages: string[] = [];
+ const overlays: Component[] = [];
+ const modelRegistry = {
+ authStorage,
+ refresh: vi.fn(),
+ getAll: () => [],
+ getProviderDisplayName: (providerId: string) => providerId,
+ } as unknown as ModelRegistry;
+
+ return {
+ host: {
+ ui: createFakeTui(overlays),
+ modelRegistry,
+ showStatus: (message) => statusMessages.push(message),
+ showError: (message) => errorMessages.push(message),
+ getAvailableModels: async () => [],
+ },
+ statusMessages,
+ errorMessages,
+ overlays,
+ };
+}
+
+describe("ProviderAuthFlows", () => {
+ let tempDir: string;
+ let authJsonPath: string;
+ let primeConfigPath: string;
+ let originalHome: string | undefined;
+ let originalPrimeTeamId: string | undefined;
+
+ beforeAll(() => {
+ initTheme("dark");
+ });
+
+ beforeEach(() => {
+ tempDir = join(tmpdir(), `pi-auth-flows-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(tempDir, { recursive: true });
+ authJsonPath = join(tempDir, "auth.json");
+ primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(authJsonPath, "{}");
+ originalHome = process.env.HOME;
+ originalPrimeTeamId = process.env.PRIME_TEAM_ID;
+ });
+
+ afterEach(() => {
+ if (originalHome === undefined) {
+ delete process.env.HOME;
+ } else {
+ process.env.HOME = originalHome;
+ }
+ if (originalPrimeTeamId === undefined) {
+ delete process.env.PRIME_TEAM_ID;
+ } else {
+ process.env.PRIME_TEAM_ID = originalPrimeTeamId;
+ }
+ if (existsSync(tempDir)) {
+ rmSync(tempDir, { recursive: true });
+ }
+ vi.restoreAllMocks();
+ });
+
+ it("preserves the Prime CLI team when login reuses the existing Prime CLI key", async () => {
+ process.env.PRIME_TEAM_ID = "env-team";
+ writeFileSync(
+ primeConfigPath,
+ JSON.stringify({
+ api_key: "prime-cli-key",
+ team_id: "cli-team",
+ team_name: "CLI Research",
+ team_role: "admin",
+ }),
+ );
+ writeFileSync(
+ authJsonPath,
+ JSON.stringify({
+ [PRIME_INFERENCE_PROVIDER_ID]: {
+ type: "api_key",
+ key: "legacy-agent-key",
+ },
+ }),
+ );
+ const authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ jsonResponse({
+ data: { scope: { inference: { write: true } } },
+ }),
+ );
+ const { host, statusMessages, errorMessages } = createHost(authStorage);
+
+ const result = await new ProviderAuthFlows(host).runPrimeInferenceLogin();
+
+ expect(errorMessages).toEqual([]);
+ expect(result.status).toBe("success");
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(statusMessages.join("\n")).toContain("Using team from PRIME_TEAM_ID.");
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.api_key).toBe("prime-cli-key");
+ expect(config.team_id).toBe("cli-team");
+ expect(config.team_name).toBe("CLI Research");
+ expect(config.team_role).toBe("admin");
+ expect(authStorage.has(PRIME_INFERENCE_PROVIDER_ID)).toBe(false);
+ });
+
+ it("stores a reused Prime CLI key when Prime CLI config sync is disabled", async () => {
+ process.env.HOME = tempDir;
+ process.env.PRIME_TEAM_ID = "env-team";
+ const defaultPrimeDir = join(tempDir, ".prime");
+ mkdirSync(defaultPrimeDir, { recursive: true });
+ writeFileSync(join(defaultPrimeDir, "config.json"), JSON.stringify({ api_key: "prime-cli-key" }));
+ const authStorage = AuthStorage.create(authJsonPath, { usePrimeCliConfig: false });
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ jsonResponse({
+ data: { scope: { inference: { write: true } } },
+ }),
+ );
+ const { host, errorMessages } = createHost(authStorage);
+
+ const result = await new ProviderAuthFlows(host).runPrimeInferenceLogin();
+
+ expect(errorMessages).toEqual([]);
+ expect(result.status).toBe("success");
+ expect(fetchMock).toHaveBeenCalledOnce();
+ await expect(authStorage.getApiKey(PRIME_INFERENCE_PROVIDER_ID)).resolves.toBe("prime-cli-key");
+ expect(authStorage.getAuthStatus(PRIME_INFERENCE_PROVIDER_ID)).toEqual({
+ configured: true,
+ source: "stored",
+ });
+
+ const authData = JSON.parse(readFileSync(authJsonPath, "utf-8")) as Record<
+ string,
+ { type?: string; key?: string }
+ >;
+ expect(authData[PRIME_INFERENCE_PROVIDER_ID]).toEqual({
+ type: "api_key",
+ key: "prime-cli-key",
+ });
+ });
+
+ it("offers Prime Inference logout when auth comes from the Prime CLI config", async () => {
+ writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key" }));
+ const authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+ const { host, overlays } = createHost(authStorage);
+
+ const logoutResult = new ProviderAuthFlows(host).runLogout();
+
+ expect(overlays).toHaveLength(1);
+ expect(stripAnsi(overlays[0]?.render(80).join("\n") ?? "")).toContain("Prime Inference");
+ overlays[0]?.handleInput?.("\x1b");
+ await expect(logoutResult).resolves.toBeNull();
+ });
+});
diff --git a/packages/coding-agent/test/auth-storage.test.ts b/packages/coding-agent/test/auth-storage.test.ts
index 2af65ebad6..4aa3058123 100644
--- a/packages/coding-agent/test/auth-storage.test.ts
+++ b/packages/coding-agent/test/auth-storage.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { registerOAuthProvider } from "@earendil-works/pi-ai/oauth";
@@ -167,7 +167,7 @@ describe("AuthStorage", () => {
});
});
- test("prime cli config fallback is cached until reload", async () => {
+ test("prime cli config changes are picked up without reload", async () => {
const primeConfigPath = join(tempDir, "prime-config.json");
writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key" }));
writeAuthJson({});
@@ -179,15 +179,71 @@ describe("AuthStorage", () => {
await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("prime-cli-key");
writeFileSync(primeConfigPath, JSON.stringify({ api_key: "changed-prime-key" }));
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("changed-prime-key");
+ });
+
+ test("prime inference uses Prime CLI auth over legacy Prime Agent auth", async () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key" }));
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("prime-cli-key");
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({
+ configured: false,
+ source: "prime_cli",
+ label: "Prime CLI",
+ });
+ });
- authStorage.reload();
- await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("changed-prime-key");
+ test("prime inference uses Prime CLI auth over environment auth", async () => {
+ const originalPrimeApiKey = process.env.PRIME_API_KEY;
+ process.env.PRIME_API_KEY = "env-prime-key";
+ try {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key" }));
+ writeAuthJson({});
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("prime-cli-key");
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({
+ configured: false,
+ source: "prime_cli",
+ label: "Prime CLI",
+ });
+ } finally {
+ if (originalPrimeApiKey === undefined) {
+ delete process.env.PRIME_API_KEY;
+ } else {
+ process.env.PRIME_API_KEY = originalPrimeApiKey;
+ }
+ }
});
- test("prime inference provider headers include selected Prime Agent team", () => {
+ test("prime inference provider headers use selected Prime CLI team", () => {
const primeConfigPath = join(tempDir, "prime-config.json");
- writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key", team_id: "cli-team" }));
+ writeFileSync(
+ primeConfigPath,
+ JSON.stringify({
+ api_key: "prime-cli-key",
+ team_id: "cli-team",
+ team_name: "CLI Research",
+ team_role: "admin",
+ }),
+ );
writeAuthJson({
"prime-inference": {
type: "api_key",
@@ -201,16 +257,35 @@ describe("AuthStorage", () => {
usePrimeCliConfig: true,
});
- expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-1" });
+ expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "cli-team" });
expect(authStorage.getPrimeInferenceTeamSelection()).toEqual({
- teamId: "team-1",
- name: "Research",
- slug: "research",
+ teamId: "cli-team",
+ name: "CLI Research",
role: "admin",
});
});
- test("prime inference personal selection suppresses Prime CLI team fallback for stored Agent key", () => {
+ test("prime inference legacy personal selection suppresses Prime CLI team fallback without Prime CLI key", () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(primeConfigPath, JSON.stringify({ team_id: "cli-team" }));
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ primeTeam: null,
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ expect(authStorage.getProviderHeaders("prime-inference")).toBeUndefined();
+ expect(authStorage.getPrimeInferenceTeamSelection()).toBeNull();
+ });
+
+ test("prime inference legacy personal selection suppresses Prime CLI team with Prime CLI key", () => {
const primeConfigPath = join(tempDir, "prime-config.json");
writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key", team_id: "cli-team" }));
writeAuthJson({
@@ -227,6 +302,37 @@ describe("AuthStorage", () => {
});
expect(authStorage.getProviderHeaders("prime-inference")).toBeUndefined();
+ expect(authStorage.getPrimeInferenceTeamSelection()).toBeNull();
+ });
+
+ test("prime inference environment team overrides legacy personal selection", () => {
+ const originalPrimeTeamId = process.env.PRIME_TEAM_ID;
+ process.env.PRIME_TEAM_ID = "env-team";
+ try {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(primeConfigPath, JSON.stringify({ team_id: "cli-team" }));
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ primeTeam: null,
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "env-team" });
+ expect(authStorage.getPrimeInferenceTeamSelection()).toBeUndefined();
+ } finally {
+ if (originalPrimeTeamId === undefined) {
+ delete process.env.PRIME_TEAM_ID;
+ } else {
+ process.env.PRIME_TEAM_ID = originalPrimeTeamId;
+ }
+ }
});
test("prime inference missing Agent team selection falls back to Prime CLI team", () => {
@@ -247,7 +353,7 @@ describe("AuthStorage", () => {
expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "cli-team" });
});
- test("prime inference provider headers fall back to Prime CLI team until reload", () => {
+ test("prime inference provider header changes are picked up without reload", () => {
const primeConfigPath = join(tempDir, "prime-config.json");
writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key", team_id: "team-1" }));
writeAuthJson({});
@@ -259,10 +365,253 @@ describe("AuthStorage", () => {
expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-1" });
writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key", team_id: "team-2" }));
+ expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-2" });
+ });
+
+ test("setPrimeInferenceApiKey creates Prime CLI config", async () => {
+ const primeConfigPath = join(tempDir, "prime", "config.json");
+ writeAuthJson({});
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.setPrimeInferenceApiKey("new-prime-key");
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.api_key).toBe("new-prime-key");
+ expect(statSync(primeConfigPath).mode & 0o777).toBe(0o600);
+ expect(authStorage.has("prime-inference")).toBe(false);
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("new-prime-key");
+ });
+
+ test("setPrimeInferenceApiKey clears stale Prime CLI team selection", () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(
+ primeConfigPath,
+ JSON.stringify({
+ api_key: "old-prime-key",
+ team_id: "old-team",
+ team_name: "Old Team",
+ team_role: "admin",
+ }),
+ );
+ writeAuthJson({});
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.setPrimeInferenceApiKey("new-prime-key");
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.api_key).toBe("new-prime-key");
+ expect(config.team_id).toBeUndefined();
+ expect(config.team_name).toBeUndefined();
+ expect(config.team_role).toBeUndefined();
+ });
+
+ test("setPrimeInferenceApiKey preserves Prime CLI team selection for the same key", () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(
+ primeConfigPath,
+ JSON.stringify({
+ api_key: "prime-cli-key",
+ team_id: "team-1",
+ team_name: "Research",
+ team_role: "admin",
+ }),
+ );
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.setPrimeInferenceApiKey("prime-cli-key");
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.api_key).toBe("prime-cli-key");
+ expect(config.team_id).toBe("team-1");
+ expect(config.team_name).toBe("Research");
+ expect(config.team_role).toBe("admin");
+ expect(authStorage.has("prime-inference")).toBe(false);
+ });
+
+ test("setPrimeInferenceApiKey migrates legacy team selection for the same Prime CLI key", () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key" }));
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ primeTeam: { teamId: "team-1", name: "Research", slug: "research", role: "admin" },
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.setPrimeInferenceApiKey("prime-cli-key");
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.api_key).toBe("prime-cli-key");
+ expect(config.team_id).toBe("team-1");
+ expect(config.team_name).toBe("Research");
+ expect(config.team_role).toBe("admin");
+ expect(authStorage.has("prime-inference")).toBe(false);
expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-1" });
+ });
- authStorage.reload();
- expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-2" });
+ test("setPrimeInferenceApiKey migrates legacy personal selection for the same Prime CLI key", () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(
+ primeConfigPath,
+ JSON.stringify({
+ api_key: "prime-cli-key",
+ team_id: "team-1",
+ team_name: "Research",
+ }),
+ );
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ primeTeam: null,
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.setPrimeInferenceApiKey("prime-cli-key");
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.api_key).toBe("prime-cli-key");
+ expect(config.team_id).toBeUndefined();
+ expect(config.team_name).toBeUndefined();
+ expect(authStorage.has("prime-inference")).toBe(false);
+ expect(authStorage.getProviderHeaders("prime-inference")).toBeUndefined();
+ });
+
+ test("setPrimeInferenceApiKey removes legacy Prime Agent credential after Prime CLI save", () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ primeTeam: { teamId: "team-1", name: "Research" },
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.setPrimeInferenceApiKey("new-prime-key");
+
+ const agentAuth = JSON.parse(readFileSync(authJsonPath, "utf-8")) as Record<string, unknown>;
+ expect(agentAuth["prime-inference"]).toBeUndefined();
+ expect(authStorage.has("prime-inference")).toBe(false);
+ });
+
+ test("setPrimeInferenceApiKey throws when Prime CLI config cannot be written", () => {
+ const primeConfigPath = join(tempDir, "prime-config-dir");
+ mkdirSync(primeConfigPath);
+ writeAuthJson({});
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ expect(() => authStorage.setPrimeInferenceApiKey("new-prime-key")).toThrow();
+ expect(authStorage.drainErrors()).toHaveLength(1);
+ });
+
+ test("setPrimeInferenceApiKey preserves team selection when Prime CLI config is disabled", () => {
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ primeTeam: { teamId: "team-1", name: "Research" },
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, { usePrimeCliConfig: false });
+
+ authStorage.setPrimeInferenceApiKey("new-prime-key");
+
+ expect(authStorage.get("prime-inference")).toEqual({
+ type: "api_key",
+ key: "new-prime-key",
+ primeTeam: { teamId: "team-1", name: "Research" },
+ });
+ });
+
+ test("logout clears Prime CLI credentials when enabled", async () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(
+ primeConfigPath,
+ JSON.stringify({
+ api_key: "prime-cli-key",
+ team_id: "team-1",
+ team_name: "Research",
+ }),
+ );
+ writeAuthJson({
+ "prime-inference": {
+ type: "api_key",
+ key: "agent-key",
+ primeTeam: { teamId: "team-1", name: "Research" },
+ },
+ });
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.logout("prime-inference");
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.api_key).toBeUndefined();
+ expect(config.team_id).toBeUndefined();
+ expect(config.team_name).toBeUndefined();
+ expect(authStorage.has("prime-inference")).toBe(false);
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
+ });
+
+ test("setPrimeInferenceTeamSelection writes Prime CLI config", () => {
+ const primeConfigPath = join(tempDir, "prime-config.json");
+ writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key" }));
+ writeAuthJson({});
+
+ authStorage = AuthStorage.create(authJsonPath, {
+ primeCliConfigPath: primeConfigPath,
+ usePrimeCliConfig: true,
+ });
+
+ authStorage.setPrimeInferenceTeamSelection({ teamId: "team-1", name: "Research", role: "admin" });
+
+ const config = JSON.parse(readFileSync(primeConfigPath, "utf-8")) as Record<string, unknown>;
+ expect(config.team_id).toBe("team-1");
+ expect(config.team_name).toBe("Research");
+ expect(config.team_role).toBe("admin");
+ expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-1" });
});
test("apiKey command can use shell features like pipes", async () => {
diff --git a/packages/coding-agent/test/suite/agent-session-goal.test.ts b/packages/coding-agent/test/suite/agent-session-goal.test.ts
index cbf9c075fb..adb6973aaf 100644
--- a/packages/coding-agent/test/suite/agent-session-goal.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-goal.test.ts
@@ -750,7 +750,7 @@ describe("AgentSession goals", () => {
expect(harness.session.goalState).toMatchObject({
active: false,
status: "error",
- lastError: "invalid_api_key",
+ lastError: "invalid_api_key\n\nRun /login to update credentials.",
});
expect(harness.getPendingResponseCount()).toBe(0);
});
diff --git a/packages/coding-agent/test/suite/regressions/4435-auth-error-login-guidance.test.ts b/packages/coding-agent/test/suite/regressions/4435-auth-error-login-guidance.test.ts
new file mode 100644
index 0000000000..bd9c42b7e0
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4435-auth-error-login-guidance.test.ts
@@ -0,0 +1,50 @@
+import type { AgentEvent } from "@earendil-works/pi-agent-core";
+import { type AssistantMessage, fauxAssistantMessage } from "@earendil-works/pi-ai";
+import { afterEach, describe, expect, it } from "vitest";
+import { createHarness, type Harness } from "../harness.js";
+
+describe("issue #4435 auth error login guidance", () => {
+ const harnesses: Harness[] = [];
+
+ afterEach(() => {
+ while (harnesses.length > 0) {
+ harnesses.pop()?.cleanup();
+ }
+ });
+
+ it("adds /login guidance to provider authentication errors", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([
+ fauxAssistantMessage("", {
+ stopReason: "error",
+ errorMessage: "401 Unauthorized: invalid API key",
+ }),
+ ]);
+
+ await harness.session.prompt("hello");
+
+ const assistantMessages = harness.session.messages.filter(
+ (message): message is AssistantMessage => message.role === "assistant",
+ );
+ expect(assistantMessages[0]?.errorMessage).toContain("Run /login to update credentials.");
+ expect(assistantMessages[0]?.errorMessage).not.toContain("/login faux");
+ });
+
+ it("adds /login guidance to authentication errors surfaced only on agent_end", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const message = fauxAssistantMessage("", {
+ stopReason: "error",
+ errorMessage: "401 Unauthorized: invalid API key",
+ });
+ const event = { type: "agent_end", messages: [message] } as AgentEvent;
+ const session = harness.session as unknown as {
+ _addLoginGuidanceToAuthError(event: AgentEvent): void;
+ };
+
+ session._addLoginGuidanceToAuthError(event);
+
+ expect(message.errorMessage).toContain("Run /login to update credentials.");
+ });
+});